language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#todo pragmas
// Power the left side of the drive train
int left(int power)
{
return power;
}
// Power the right side of the drive train
int right(int power)
{
return motor[Right] = power;
}
// The encoder distance width of the ramp
// This is used in functions such as straightRamp().
#define RAMP_DIST 1600
// The minimum motor power value of the ramp
// The motors start at this power when the robot has not yet moved and
// when the robot is finishing its movement.
// This must be powerful enough to overcome inertia and move the robot.
// This is used in functions such as straightRamp().
#define RAMP_MIN 25
// Moves the robot straight for the given encoder distance, ramping up and down to reduce skipping
// Ramp up based on encoder distance, going from 25% to 100% over the first 1600 degrees.
// Ramp down based on encoder distance, going from 25% to 0% over the last 1600 degrees.
// Ramps are cut off at the given power, without changing the ramp slope; in other words,
// the lower the power, the shorter the ramp time.
// dist: The encoder distance which the robot will move. Must be positive.
// power: The maximum motor power at which the robot will move. May be negative to go backwards.
void straightRamp(int dist, int power)
{
int encVal = nMotorEncoder[Right] = 0; // reset the encoder
while (encVal < dist) { // loop while the robot has not yet traversed the given distance
float mStart = (float)(100 - RAMP_MIN) / RAMP_DIST; // calculate the slope of the starting ramp
int rampStart = mStart * encVal + RAMP_MIN; // calculate the power value of the starting ramp
float mEnd = (float)(100 - RAMP_MIN) / (- RAMP_DIST); // calculate the slope of the ending ramp
int rampEnd = m * (encVal - dist) + RAMP_MIN; // calculate the power value of the ending ramp
if (rampStart < power) power = rampStart; // find the minimum power value between the given power and the starting ramp
if (rampEnd < power) power = rampEnd; // find the minimum power value between the given power and the ending ramp
left(right(power));
wait10Msec(1); // wait 10 msecs to allow the robot to move a bit before repeating
encVal = abs(nMotorEncoder[Right]); // get the current traversed distance on the encoder
}
left(right(0));
}
// Moves the robot straight for the given encoder distance, ramping up and down to reduce skipping
// Ramp up based on encoder distance, going from 25% to 100% over the first 1600 degrees.
// Ramp down based on encoder distance, going from 25% to 0% over the last 1600 degrees.
// Ramps are cut off at the given power, without changing the ramp slope; in other words,
// the lower the power, the shorter the ramp time.
// dist: The encoder distance which the robot will move. Must be positive.
// power: The maximum motor power at which the robot will move. Must be positive.
// dir: The direction, left or right.
void turnRamp(int dist, int power, int dir)
{
power *= dir; // incorporate the turning direction into the power
int encVal = nMotorEncoder[Right] = 0; // reset the encoder
while (encVal < dist) { // loop while the robot has not yet traversed the given distance
float mStart = (float)(100 - RAMP_MIN) / RAMP_DIST; // calculate the slope of the starting ramp
int rampStart = mStart * encVal + RAMP_MIN; // calculate the power value of the starting ramp
float mEnd = (float)(100 - RAMP_MIN) / (- RAMP_DIST); // calculate the slope of the ending ramp
int rampEnd = m * (encVal - dist) + RAMP_MIN; // calculate the power value of the ending ramp
if (rampStart < power) power = rampStart; // find the minimum power value between the given power and the starting ramp
if (rampEnd < power) power = rampEnd; // find the minimum power value between the given power and the ending ramp
left(- right(power));
wait10Msec(1); // wait 10 msecs to allow the robot to move a bit before repeating
encVal = abs(nMotorEncoder[Right]); // get the current traversed distance on the encoder
}
left(right(0));
}
task main()
{
straightRamp(2000, 100);
}
|
C
|
#define N_MAX 100000
unsigned long int P[N_MAX];
inline unsigned long int pent(unsigned long int i) {
return i*(3*i-1)/2;
}
inline int is_pent(unsigned long int val, unsigned long int cur_i) {
int i;
for(i=1;i<cur_i;i++) {
if (P[i] == val) return 1;
}
return 0;
}
int main() {
unsigned long int i,j,k;
unsigned long int D=pent(N_MAX);
unsigned long int test;
for (i=1;i<N_MAX;i++) {
P[i] = pent(i);
// printf("%llu : %llu --\n",i,P[i]);
for (j=1;j<i;j++) {
for(k=1;k<j;k++) {
if (P[j]+P[k] == P[i]) {
// printf("P[%llu] = %llu is sum of pents P[%llu] + P[%llu]\n",
// i, P[i], j, k);
test = P[j]-P[k];
if (is_pent(test,i)) {
// printf("!!---difference is pent!!!!---\n");
if (test < D) {
D = test;
printf("%llu\n",D);
}
}
}
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//declaracion de una varibale goblal.
char textPublic[] = {"Texto en una variable global. \n\n"};
// Funcion
void comprobar()
{
printf("\n\n--Imprimir una fucion: comparar --\n\n");
printf("%s", textPublic);
//Proboca error, no pude compilar por que no encuentra la variable: textPrivado.
//hay que comentar la linea para que el programa compile.
printf("Variable loca: ");
// puts(textPribado)
}
int main()
{
printf("Varibles publciar y privadas \n");
printf("-- Imprimir desde la funcion: main --\n\n");
char textPrivado[] = {"Texto de una variable local.\n"};
printf("Variable global: ");
printf("%s", textPublic);
printf("Variable local: ");
printf("%s", textPrivado);
comprobar();
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int i, n = 10;
int vetA[n];
int vetB[n];
int temp;
for (i = 0; i < n; i++) {
printf("Vetor A, posicao %i\n", i + 1);
scanf("%i", &vetA[i]);
printf("Vetor B, posicao %i\n", i + 1);
scanf("%i", &vetB[i]);
}
for (i = 0; i < n; i++) {
printf("Antes\n");
printf("Vetor A, posicao %i = %i\n", i + 1, vetA[i]);
printf("Vetor B, posicao %i = %i\n", i + 1, vetB[i]);
temp = vetB[i];
vetB[i] = vetA[i];
vetA[i] = temp;
printf("Depois\n");
printf("Vetor A, posicao %i = %i\n", i + 1, vetA[i]);
printf("Vetor B, posicao %i = %i\n", i + 1, vetB[i]);
}
return 0;
}
|
C
|
#ifndef SingleList_h
#define SingleList_h
#include <stdio.h>
typedef struct __CharNode CharNode;
typedef struct __CharList
{
CharNode *head;
CharNode *tail;
int count;
}CharList;
extern const int ListError;
void theBubbleSorting(CharNode *theList, int Count);//funcion for sorting list(the bubble sorting)
CharList *ListCreate();
void FreeList(CharList *aList);
CharNode *NodeAdd(CharList *aList, char *aValue);
CharList *MinMax(CharList *aList);
int CountList(const CharList *aList);
CharNode *NodeAtIndex(const CharList *aList, int aIndex);
CharNode *InsertNodeAtIndex(CharList *aList, CharNode *aNewNode, int anIndex);
CharNode *RemovedNodeAtIndex(CharList *aList, int anIndex);
#endif /* SingleList_h */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#include "gmp.h"
/*
Algorithem 1: Valid number range
Data:
f(3):
[0] [1093]
[2187] [3280]
[6561] [9841]
[19683] [29524]
[59049] [88573]
...
f(4):
[0] [5461]
[16384] [21845]
[65536] [87381]
[262144] [349525]
[1048576] [1398101]
...
f(5):
[0] [19531]
[78125] [97656]
[390625] [488281]
[1953125] [2441406]
[9765625] [12207031]
...
Explain:
f(base):
[a] [b]
[c] [d]
init:
n = base - 1
a = 0
b = Algo3(base)
Next:
c = (b * n) + 1
d = b + c
a = c
b = d
Algorithem 2: Number position
Data:
f(3):
[0] [126]
[127] [254]
[255] [510]
[511] [1022]
[1023] [2046]
...
f(4):
[0] [126]
[127] [254]
[255] [510]
[511] [1022]
[1023] [2046]
...
Explain:
f(base):
[a] [b]
[c] [d]
init:
a = 0
b = 126
Loop:
a and b is known we can generate c and d
c = b + 1
d = c * 2
a = c
b = d
Algorithem 3:
Data:
f(3): 1093
f(4): 5461
f(5): 19531
f(6): 55987
Explain:
f(base):
return (x^8 - x) / (x^2 - x)
*/
//Temp
static mpz_t c;
static mpz_t d;
struct Range {
int n;
mpz_t a;
mpz_t b;
};
void algo3(int base, mpz_t solution) {
mpz_t a, b;
//Init
mpz_init_set_ui(a, base);
mpz_init_set_ui(b, base);
//(x^8 - x)
mpz_pow_ui(a, a, 8);
mpz_sub_ui(a, a, base);
//(x^2 - x)
mpz_pow_ui(b, b, 2);
mpz_sub_ui(b, b, base);
mpz_div(solution, a, b);
}
void algo2(int base) {
int i, n;
char c_a[1000], c_b[1000];
mpz_t a, b, c, d;
//Init
mpz_init_set_ui(a, 0);
mpz_init_set_ui(b, 126);
mpz_init(c);
mpz_init(d);
//Generate
n = base - 1;
//Draw
mpz_get_str(c_a, 10, a);
mpz_get_str(c_b, 10, b);
printf("[%s] [%s]\n", c_a, c_b);
for(i = 0; i < 5; i++) {
//c = b + 1
mpz_add_ui(c, b, 1);
//d = c * 2
mpz_mul_ui(d, c, 2);
//a = c
mpz_set(a, c);
//b = d
mpz_set(b, d);
//Draw
mpz_get_str(c_a, 10, a);
mpz_get_str(c_b, 10, b);
printf("[%s] [%s]\n", c_a, c_b);
}
}
void algo1_init(struct Range* r, int base) {
//Init
mpz_init_set_ui(r->a, 0);
mpz_init(r->b);
//Generate
r->n = base - 1;
algo3(base, r->b);
}
void algo1_next(struct Range* r) {
//c = (b * n) + 1
mpz_mul_ui(c, r->b, r->n);
mpz_add_ui(c, c, 1);
//d = b + c
mpz_add(d, r->b, c);
//a = c
mpz_set(r->a, c);
//b = d
mpz_set(r->b, d);
}
void algo1_draw(struct Range* r) {
char c_a[1000], c_b[1000];
mpz_get_str(c_a, 10, r->a);
mpz_get_str(c_b, 10, r->b);
printf("[%s] [%s]\n", c_a, c_b);
}
void algo1(int base) {
int i, n, count;
char c_a[1000], c_b[1000];
mpz_t a, b, c, d;
//Init
mpz_init_set_ui(a, 0);
mpz_init(b);
mpz_init(c);
mpz_init(d);
count = 0;
//Generate
n = base - 1;
algo3(base, b);
//Draw
mpz_get_str(c_a, 10, a);
mpz_get_str(c_b, 10, b);
printf("[%s] [%s]\n", c_a, c_b);
for(i = 0; i < 10; i++) {
//c = (b * n) + 1
mpz_mul_ui(c, b, n);
mpz_add_ui(c, c, 1);
//d = b + c
mpz_add(d, b, c);
//a = c
mpz_set(a, c);
//b = d
mpz_set(b, d);
//Draw
mpz_get_str(c_a, 10, a);
mpz_get_str(c_b, 10, b);
printf("[%s] [%s]\n", c_a, c_b);
/*
if(count % 10000 == 0)
printf("digits: %ld\n", mpz_sizeinbase(d, 10));
count++;
*/
}
}
void collapsedRanges(int base) {
int i, j, r_length, count, collision;
struct Range *r;
bool check, check_collision;
mpz_t smallest, biggest, total;
char buffer[1000];
//Init
count = 0;
collision = 0;
mpz_init(smallest);
mpz_init(biggest);
mpz_init(total);
//Generate Range
r_length = base - 3;
r = malloc(4 * sizeof(struct Range));
for(i = 0; i < r_length; i++)
algo1_init(&r[i], 3 + i);
algo1_init(&r[r_length], base);
//Loop
for(i = 0; i < 1000000; i++) {
check = true;
check_collision = true;
for(j = 0; j < r_length; j++) {
if(mpz_cmp(r[j].b, r[j + 1].a) < 0) {
algo1_next(&r[j]);
check = false;
j = r_length;
}
if(mpz_cmp(r[j].a, r[j + 1].b) > 0)
check_collision = false;
}
if(check) {
if(check_collision) {
mpz_set(biggest, r[r_length].a);
mpz_set(smallest, r[r_length].b);
for(j = 0; j < r_length; j++) {
if(mpz_cmp(biggest, r[j].a) < 0)
mpz_set(biggest, r[j].a);
if(mpz_cmp(smallest, r[j].b) > 0)
mpz_set(smallest, r[j].b);
}
mpz_sub(total, smallest, biggest);
if(mpz_cmp_ui(total, 0) > 0) {
/*
mpz_get_str(buffer, 10, biggest);
printf("a biggest: %s\n", buffer);
mpz_get_str(buffer, 10, smallest);
printf("b smallest: %s\n", buffer);
mpz_get_str(buffer, 10, total);
printf("total: %s\n", buffer);
printf("biggest digits: %ld\n", mpz_sizeinbase(biggest, 10));
printf("smallest digits: %ld\n", mpz_sizeinbase(smallest, 10));
printf("total digits: %ld\n", mpz_sizeinbase(total, 10));
*/
collision++;
}
}
algo1_next(&r[r_length]);
}
//Draw
if(count % 100000 == 0)
printf("digits: %ld\n", mpz_sizeinbase(r[r_length].b, 10));
count++;
}
printf("collsions: %d\n", collision);
}
int main() {
//Init
mpz_init(c);
mpz_init(d);
collapsedRanges(6);
//Clean
mpz_clear(c);
mpz_clear(d);
}
|
C
|
#include<stdio.h>
#include<math.h>
int inverso1(int inverso);
int inverso2(int* inverso);
int inverso2(int* inverso){
int cont = 0;
int control = *inverso;
float controle = control;
while(controle >= 10){
controle /= 10;
cont++;
}
int i = 0, soma= 0, potencia = 0;
float v[cont];
while(i <= cont){
i++;
potencia = pow(10,i);
v[i] = (control%potencia)-soma;
soma += v[i];
}
i = 0; potencia = 0;
while(i <= cont){
potencia = pow(10,i);
i++;
v[i]= v[i] / potencia;
}
int devolva=0;
i = 1; potencia = 0;
while(cont >= 0){
v[i] *= pow(10, cont);
cont--;
devolva += v[i];
i++;
}
inverso = devolva;
}
int inverso1(int inverso){
int cont = 0;
float controle = inverso;
while(controle >= 10){
controle /= 10;
cont++;
}
int i = 0, soma= 0, potencia = 0;
float v[cont];
while(i <= cont){
i++;
potencia = pow(10,i);
v[i] = (inverso%potencia)-soma;
soma += v[i];
}
i = 0; potencia = 0;
while(i <= cont){
potencia = pow(10,i);
i++;
v[i]= v[i] / potencia;
}
inverso = 0; i = 1; potencia = 0;
while(cont >= 0){
v[i] *= pow(10, cont);
cont--;
inverso += v[i];
i++;
}
return inverso;
}
void main(){
//return
printf("MÉTODO CONVENCIONAL\n");
printf("345 - seu inverso é: %d\n", inverso1(345));
printf("1 - seu inverso é: %d\n", inverso1(1));
printf("1234627 - seu inverso é: %d\n", inverso1(1234627));
printf("24 - seu inverso é: %d\n\n", inverso1(24));
//scanf
int inverso = 1234345;
printf("MÉTODO SCANF\n");
printf("O inverso de 1234345 é %d\n",inverso2(&inverso));
}
|
C
|
/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
int main()
{
int a;
scanf("%d",&a);
for (int i=2;i<a/2;i++)
{
if (a%i==0)
{
int flag =1;
for (int j=2;j<i;j++)
{
if (i%j==0)
{
flag=0;
break;
}
else flag=1;
}
if (flag ==1)
{
printf("%d ",i);
}
}
}
return 0;
}
|
C
|
#include "v3p_netlib.h"
#include <stdio.h>
double f(double *x)
{
return (*x)/(1+(*x)*(*x));
}
void test_simpson_integral()
{
double a = 0;
double b = 1;
double res;
long n = 100;
v3p_netlib_simpru_(&f, &a, &b, &n, &res);
printf("simpson integral of x/(1+x^2) from 0 to 1 (%ld grids) is %2.10f\n", n, res);
}
void test_trapezod_integral()
{
double a = 0;
double b = 1;
double res;
long n = 500;
v3p_netlib_trapru_(&f, &a, &b, &n, &res);
printf("trapezod integral of x/(1+x^2) from 0 to 1 (%ld grids) is %f\n", n, res);
}
int main()
{
test_simpson_integral();
test_trapezod_integral();
return 0;
}
|
C
|
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <mysql/mysql.h>
#include "json_finder.h"
my_bool
jfget_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
if (args->arg_count != 2) {
strcpy(message, "jfget() requires two arguments");
return 1;
}
if (args->arg_type[0] != STRING_RESULT) {
strcpy(message, "jfget() requires a string for first argument");
return 1;
}
if (args->arg_type[1] != STRING_RESULT) {
strcpy(message, "jfget() requires a string for second argument");
return 1;
}
args->maybe_null[0] = 0;
args->maybe_null[1] = 0;
initid->ptr = NULL;
return 0;
}
void
jfget_deinit(UDF_INIT *initid)
{
free(initid->ptr);
return;
}
char *
jfget(UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long *length, char *is_null, char *error)
{
json_elem_t elem;
char *uestr;
size_t uestr_size;
switch (json_finder_find(
&elem,
(const char *)args->args[0],
(ssize_t)args->lengths[0],
(char *)args->args[1],
(ssize_t)args->lengths[1],
NULL,
NULL,
NULL)) {
case 1:
*error = 1;
return NULL;
case -1:
*is_null = 1;
return NULL;
default:
break;
}
switch (elem.type) {
case JSON_BOOL:
if (elem.value.b) {
strcpy(result, "true");
*length = sizeof("true") - 1;
return result;
} else {
strcpy(result, "false");
*length = sizeof("false") - 1;
return result;
}
case JSON_INTEGER:
memcpy(result, elem.value.ll.s.ptr, elem.value.ll.s.len);
result[elem.value.ll.s.len] = '\0';
*length = elem.value.ll.s.len;
return result;
case JSON_DOUBLE:
memcpy(result, elem.value.d.s.ptr, elem.value.d.s.len);
result[elem.value.d.s.len] = '\0';
*length = elem.value.d.s.len;
return result;
case JSON_STRING:
if (json_finder_unescape_strdup(&uestr, &uestr_size, &elem.value.s)) {
*error = 1;
return NULL;
}
*length = uestr_size - 1;
initid->ptr = uestr;
return uestr;
case JSON_NULL:
*is_null = 1;
return NULL;
default:
*error = 1;
return NULL;
}
}
my_bool
jfgetint_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
if (args->arg_count != 2) {
strcpy(message, "jfget() requires two arguments");
return 1;
}
if (args->arg_type[0] != STRING_RESULT) {
strcpy(message, "jfget() requires a string for first argument");
return 1;
}
if (args->arg_type[1] != STRING_RESULT) {
strcpy(message, "jfget() requires a string for second argument");
return 1;
}
args->maybe_null[0] = 0;
args->maybe_null[1] = 0;
return 0;
}
void
jfgetint_deinit(UDF_INIT *initid)
{
return;
}
long long
jfgetint(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
json_elem_t elem;
switch (json_finder_find(
&elem,
(const char *)args->args[0],
(ssize_t)args->lengths[0],
(char *)args->args[1],
(ssize_t)args->lengths[1],
NULL,
NULL,
NULL)) {
case 1:
*error = 1;
return 0;
case -1:
*is_null = 1;
return 0;
default:
break;
}
switch (elem.type) {
case JSON_BOOL:
return (long long)elem.value.b;
case JSON_INTEGER:
return elem.value.ll.v;
case JSON_DOUBLE:
*error = 1;
return 0;
case JSON_STRING:
*error = 1;
return 0;
case JSON_NULL:
*is_null = 1;
return 0;
default:
*error = 1;
return 0;
}
}
my_bool
jfgetreal_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
if (args->arg_count != 2) {
strcpy(message, "jfget() requires two arguments");
return 1;
}
if (args->arg_type[0] != STRING_RESULT) {
strcpy(message, "jfget() requires a string for first argument");
return 1;
}
if (args->arg_type[1] != STRING_RESULT) {
strcpy(message, "jfget() requires a string for second argument");
return 1;
}
args->maybe_null[0] = 0;
args->maybe_null[1] = 0;
return 0;
}
void
jfgetreal_deinit(UDF_INIT *initid)
{
return;
}
double
jfgetreal(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
json_elem_t elem;
switch (json_finder_find(
&elem,
(const char *)args->args[0],
(ssize_t)args->lengths[0],
(char *)args->args[1],
(ssize_t)args->lengths[1],
NULL,
NULL,
NULL)) {
case 1:
*error = 1;
return 0;
case -1:
*is_null = 1;
return 0;
default:
break;
}
switch (elem.type) {
case JSON_BOOL:
*error = 1;
return 0;
case JSON_INTEGER:
*error = 1;
return 0;
case JSON_DOUBLE:
return elem.value.d.v;
case JSON_STRING:
*error = 1;
return 0;
case JSON_NULL:
*is_null = 1;
return 0;
default:
*error = 1;
return 0;
}
}
my_bool
jfmin_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
if (args->arg_count != 1) {
strcpy(message, "jfget() requires one arguments");
return 1;
}
if (args->arg_type[0] != STRING_RESULT) {
strcpy(message, "jfget() requires a string");
return 1;
}
args->maybe_null[0] = 0;
initid->ptr = NULL;
return 0;
}
void
jfmin_deinit(UDF_INIT *initid)
{
free(initid->ptr);
return;
}
char *
jfmin(UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long *length, char *is_null, char *error)
{
char *json_min;
ssize_t json_min_size;
if (json_finder_minimize(
&json_min,
&json_min_size,
(const char *)args->args[0],
(ssize_t)args->lengths[0])) {
*error = 1;
return NULL;
}
initid->ptr = json_min;
*length = json_min_size - 1;
return json_min;
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("[1] apple\n[2] pear\n[3] orange\n[4] grape\n[0] exit\n");
double price[4]={3.00,2.50,4.10,10.20};
for (int i = 0; i < 5; ++i)
{
int n;
scanf("%d",&n);
if (n<=5 && n>=1)
{
printf("price = %.2f\n",price[n-1]);
}
else if (n==0)
{
break;
}
else
{
printf("price = 0.00\n");
}
}
// printf("%.2f\n", price[1]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define SUCESSO 0
#define PILHA_VAZIA 1
#define FALTOU_MEMORIA 2
// Structs
typedef struct nodo Nodo;
struct nodo {
int info; /* Informação armazenada */
Nodo *prox; /* Endereço do próximo */
};
typedef struct {
Nodo *topo;
} Pilha;
// Funções
void criaPilha(Pilha *p){
p->topo = NULL;
}
int empilha( Pilha *p, int dado){
Nodo *pNodo;
pNodo = (Nodo *) malloc (sizeof (Nodo));
if (pNodo == NULL){
return FALTOU_MEMORIA;
} else {
pNodo->info=dado;
pNodo->prox=p->topo;
p->topo=pNodo;
return SUCESSO;
}
}
int desempilha (Pilha *p, int *dado){
if(p->topo == NULL){
return PILHA_VAZIA;
}else {
Nodo *pTemp;
*dado=p->topo->info;
pTemp=p->topo;
p->topo=p->topo->prox;
free(pTemp);
return SUCESSO;
}
}
int estaVazia(Pilha p){
if(p.topo == NULL){
return 1;
}else {
return 0;
}
}
int consulta(Pilha p,int *dado){
if(p.topo == NULL){
return PILHA_VAZIA;
}else {
Nodo *pNodo;
pNodo=p.topo;
*dado=pNodo->info;
return SUCESSO;
}
}
void exibe(Pilha p){
if(p.topo != NULL){
Nodo *pAux;
pAux=p.topo;
while(pAux!=NULL){
printf("Dado: %d\n",pAux->info);
pAux=pAux->prox;
}
}
}
int main(){
Pilha p;
criaPilha(&p);
int op,ret,dado;
do{
printf("0 -Fim\n");
printf("1 -Empilha\n");
printf("2 -Exibe na lista\n");
printf("3 -Desempilha\n");
printf("4 -Esta Vazia\n");
printf("5 -Consulta\n");
scanf("%d",&op);
if(op>=0 && op<=5){
switch(op){
case 0:
op=15; // Para Sair do Prog, seta op para 15
break;
case 1:
printf("Informe o Cod: ");
scanf("%d",&dado);
ret=empilha(&p,dado);
if(ret==SUCESSO){
printf("\nSucesso\n");
}else if(ret==FALTOU_MEMORIA){
printf("\nErro MEMORIA CHEIA\n");
}
break;
case 2:
exibe(p);
printf("Sucesso\n");
break;
case 3:
ret=desempilha(&p,&dado);
if(ret==SUCESSO){
printf("Dado Excluido\n");
printf("Cod: %d\n",dado);
}else if(ret==PILHA_VAZIA) {
printf("Lista Vazia Sucesso\n ");
}
break;
case 4:
ret=estaVazia(p);
if(ret==0){
printf("Lista Nao Esta Vazia\n");
}else if(ret==1){
printf("Lista Esta Vazia\n");
}
break;
case 5:
ret=consulta(p,&dado);
if(ret==SUCESSO){
printf("SUCESSO\n");
printf("Cod: %d\n",dado);
}else if(ret==PILHA_VAZIA){
printf("PILHA VAZIA\n");
}
break;
}
exibe(p);
}
}while (op>=0 && op<=5);
return 0;
}
|
C
|
#ifndef data_structures_list_h
#define data_structures_list_h
typedef struct ListNode {
void *value;
struct ListNode *prev;
struct ListNode *next;
} ListNode;
typedef struct List {
int count;
struct ListNode *first;
struct ListNode *last;
} List;
typedef void *(*ListNodeIterator)(ListNode *node);
#define list_count(L) ((L)->count)
#define list_first(L) ((L)->first ? (L)->first->value : NULL)
#define list_last(L) ((L)->last == NULL ? NULL : (L)->last->value)
List *List_create();
void list_push( List *list, void *value);
void *list_pop( List *list);
void list_unshift(List *list, void *value);
void *list_shift( List *list);
List *list_map( List *list, void *(*f)(ListNode *node));
void list_each( List *list, void *(*f)(ListNode *node));
void list_print( List *list);
void list_destroy(List *list);
void list_clear( List *list);
void list_clear_and_destroy(List *list);
#endif
|
C
|
/* consDiskTest -- Test Virtual P's and V's. consdiskTest (consumer) and
* prodDiskTest (producer) exchange a message using disk1, and the shared
* segment for synchronization.
*/
#include "uconst.h"
#include "ulib.e"
#include "ulibuarm.e"
int main() {
int *hold = (int *)(SEG3 + 40);
int *empty = (int *)(SEG3 + 44);
int *full = (int *)(SEG3 + 48);
#define MES_SIZE 40
char buf1[4096];
char buf2[4096];
char buf3[4096];
char msg[MES_SIZE], *p, c, *tmp;
int count = 0;
print_term("consDiskTest starts\n");
/* initialize shared memory */
*hold = 0;
*full = 0;
*empty = 0;
/* block until prodDiskTest has started up */
P(hold, 1);
print_term("consDiskTest starts consuming...\n");
/* receive characters from prodDiskTest */
p = msg; /* p points at the beginning of msg, so writes into msg */
do {
P(full, 1); /* Blocks on full, waits for produces */
switch (count % 3) {
case 0: tmp = buf1; break;
case 1: tmp = buf2; break;
case 2: tmp = buf3; break;
}
read_disk(tmp, 1, 0);
*p = c = *tmp;
p++;
print_term("Consumer, consumed a char\n");
V(empty, 1); /* Signal on empty, unblock producer */
} while (c != '\0');
/* print message received from producer */
print_term("\nI received the following message from prodDiskTest:\n");
print_term(msg);
print_term("\nconsDiskTest completed\n");
/* terminate normally */
return 0;
print_term("pvTestA error: did not terminate\n");
uexit();
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int n1,n2,i,j,lcs[10][10];
char a[10],b[10];
printf("Enter 2 strings\n");
gets(a);
gets(b);
n1=strlen(a);
n2=strlen(b);
for(i=0;i<=n2;i++)
{
for(j=0;j<=n1;j++)
{
if(i==0||j==0)
lcs[i][j]=0;
}
}
for(i=0;i<=n2;i++)
{
for(j=0;j<=n1;j++)
{
if(b[i]==a[j])
lcs[i+1][j+1]=lcs[i][j]+1;
else
{
if(lcs[i+1][j]>lcs[i][j+1])
lcs[i+1][j+1]=lcs[i+1][j];
else
lcs[i+1][j+1]=lcs[i][j+1];
}
}
}
printf("\t");
for(i=0;i<=n1;i++)
printf("\t%c",a[i]);
printf("\n");
for(i=0;i<=n2;i++)
{
if(i!=0)
printf("%c\t",b[i-1]);
else
printf("\t");
for(j=0;j<=n1;j++)
printf("%d\t",lcs[i][j]);
printf("\n");
}
printf("\nLength of lcs is %d",lcs[i-1][j-1]);
return 0;
}
|
C
|
#include "func_list.h"
func_decl_t* create_func_decl(hash_node_t *id)
{
func_decl_t *new_func = calloc(1, sizeof(func_decl_t));
new_func->id = id;
return new_func;
}
func_list_t* create_func_list()
{
func_list_t *list = calloc(1, sizeof(func_list_t));
list->head = 0;
list->tail = 0;
return list;
}
func_list_t* insert_decl(func_list_t *func_list, func_decl_t *func_decl)
{
if(!func_list->tail)
{
func_list->head = func_decl;
func_list->tail = func_decl;
}
else
{
func_list->tail->next = func_decl;
func_list->tail = func_decl;
}
}
hash_node_t* insert_param(func_decl_t *func_decl, hash_node_t *param)
{
hash_node_t *p = calloc(1, sizeof(hash_node_t));
p->text = param->text;
p->type = param->type;
hash_node_t *curr = func_decl->params;
hash_node_t *prev;
if(!curr)
{
func_decl->params = p;
return p;
}
while(curr)
{
prev = curr;
curr = curr->next;
}
prev->next = p;
return p;
}
hash_node_t* find_param(func_decl_t *func_decl, char* text)
{
hash_node_t *curr = func_decl->params;
while(curr)
{
if(hashString(curr->text) == hashString(text))
return curr;
curr = curr->next;
}
return 0;
}
func_decl_t* find_decl(func_list_t *func_list, hash_node_t *id)
{
func_decl_t *curr = func_list->head;
while(curr)
{
if(curr->id == id)
return curr;
curr = curr->next;
}
return 0;
}
int get_param_pos(func_list_t *funcs,
hash_node_t *currentFunction,
hash_node_t *param)
{
func_decl_t *function = find_decl(funcs, currentFunction);
hash_node_t *curr = function->params;
int pos = 0;
int total = 0;
while(curr)
{
if(hashString(curr->text) == hashString(param->text))
pos = total;
curr = curr->next;
total++;
}
return total - pos - 1;
}
int count_args(func_list_t *funcs, hash_node_t *func)
{
func_decl_t *function = find_decl(funcs, func);
hash_node_t *curr = function->params;
int total = 0;
while(curr)
{
curr = curr->next;
total++;
}
return total;
}
|
C
|
/*
** EPITECH PROJECT, 2022
** NWP_mychap_2018
** File description:
** Created by Florian Louvet,
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>
#include <time.h>
#include "parser.h"
#include "my_chap.h"
void resolver(parser_t *args)
{
struct hostent *host;
if ((host = gethostbyname(optarg)) == NULL) {
fprintf(stderr, "No such hostname: %s\n", optarg);
exit(84);
}
args->target = strdup(
inet_ntoa(*((struct in_addr **)host->h_addr_list)[0]));
}
void parser(int option, parser_t *args)
{
switch (option) {
case 't':
resolver(args);
break;
case 'p':
args->port = atoi(optarg);
break;
case 'P':
args->password = optarg;
break;
case '?':
break;
default:
abort();
}
}
int main(int argc, char **argv)
{
int option;
int index;
parser_t args = {NULL, 0, NULL, 0};
srand(time(NULL));
args.source_port = (rand() + 1024) % 5000;
while (42) {
index = 0;
option = getopt_long(argc, argv, "t:p:P:", long_options, &index);
if (option == -1)
break;
parser(option, &args);
}
create_socket(&args);
if (args.target == NULL || args.password == NULL || args.port == 0)
return (84);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int mmm(unsigned int x, unsigned int y, unsigned int p) {
unsigned int result = 0;
x = x%p;
while(y > 0) {
printf("y = %d, x = %d, result = %d\n", y, x, result);
if(y%2 == 1)
result = (result + x) % p;
x = (x*2) % p;
y /= 2;
}
return result%p;
}
int mme(unsigned int x, unsigned int y, unsigned int p) {
unsigned int result = 1;
x = x % p;
while(y > 0) {
if(y & 1)
result = (result*x) % p;//result = mmm(result, x, p);
y = y >> 1;
x = (x*x) % p;//mmm(x, x, p);
}
return result;
}
int main() {
unsigned int E = 17;
unsigned int D = 2753;
unsigned int T = 123;
unsigned int M = 3233;
printf("Initial: %d\n", T);
int C = mme(T, E, M);
printf("Encrypted: %d\n", C);
int P = mme(C, D, M);
printf("Decrypted: %d\n", P);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int b,p;
printf("enter the base and power value");
scanf("%d%d",&b,&p);
c=b^p;
printf("the value ofc is %d",&c);
getch();
}
|
C
|
/*
* echoserveri.c - An iterative echo server
*/
/* $begin echoserverimain */
#include "csapp.h"
#define MAXCONNECTIONS (20)
void echo(int connfd);
void init_connect_list();
int add_to_connect_list(char *client_hostname, char *client_port);
void print_connected_list();
typedef struct{
char client_hostname[MAXLINE];
char client_port[MAXLINE];
int active;
} connected_t;
connected_t connected_list[MAXCONNECTIONS];
int main(int argc, char **argv)
{
init_connect_list();
int listenfd, connfd;
socklen_t clientlen;
struct sockaddr_storage clientaddr; /* Enough space for any address */ //line:netp:echoserveri:sockaddrstorage
char client_hostname[MAXLINE], client_port[MAXLINE];
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(0);
}
listenfd = Open_listenfd(argv[1]);
Fork();
while (1) {
clientlen = sizeof(struct sockaddr_storage);
connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
Getnameinfo((SA *) &clientaddr, clientlen, client_hostname, MAXLINE,
client_port, MAXLINE, 0);
add_to_connect_list(client_hostname, client_port);
printf("Connected to (%s, %s)\n", client_hostname, client_port);
print_connected_list();
echo(connfd);
Close(connfd);
}
exit(0);
}
/* $end echoserverimain */
void init_connect_list(){
for(int i = 0; i < MAXCONNECTIONS; i++){
connected_list[i].active = -1;
}
}
int add_to_connect_list(char *client_hostname, char *client_port){
for(int i = 0; i < MAXCONNECTIONS; i++){
if(connected_list[i].active == -1){
connected_list[i].active = 1;
*connected_list[i].client_hostname = *client_hostname;
*connected_list[i].client_port = *client_port;
return 1;
}
}
// not enough space
printf("NO MOAR SPACE MAN \n");
return -1;
}
void print_connected_list(){
for(int i = 0; i < MAXCONNECTIONS; i++){
if(connected_list[i].active == 1){
printf("Connected to (%s, %s)\n", connected_list[i].client_hostname, connected_list[i].client_port);
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
int fileManagement(char*);
int createFiles(FILE*);
void closeFile(FILE*, bool*);
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2){
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
// remember filename
char* cardfile = argv[1];
// control of file opening and closing
int ret = fileManagement(cardfile);
if (ret != 0){
return ret;
}
// success
return 0;
}
/*
* Control of file opening and closing
*/
int fileManagement(char* cardfile)
{
// open card file
FILE* cardptr = fopen(cardfile, "rb");
if (cardptr == NULL){
fprintf(stderr, "Could not open %s.\n", cardfile);
return 2;
}
// create JPEG-files from cardfile
int ret = createFiles(cardptr);
// close cardfile
fclose(cardptr);
// not ok
if (ret != 0){
return ret;
}
// success
return 0;
}
/*
* Create JPEG-files from cardfile
*/
//int createFiles(BYTE* buffer[], FILE* cardptr)
int createFiles(FILE* cardptr)
{
/*
NMEMB - number elements of data
BUFFER_SIZE - size of buffer for cardfile's block
*/
enum constants {
NMEMB = 1, BUFFER_SIZE = 512
};
enum bytes {
FIRST_B = 0, SECOND_B, THIRD_B, FOURTH_B
};
// create counter of JPEG files
int count = 0;
// create an array of chars for the name of JPEG-file
char filename[8];
// file exists or not ?
bool file_exists = false;
FILE* img;
// create temporary buffer for cardfile's block
typedef uint8_t BYTE;
BYTE buffer[BUFFER_SIZE];
// iterate over cardfile's blocks
while(fread(&buffer, BUFFER_SIZE, NMEMB, cardptr) > 0){
//printf("%02x%02x%02x\n", buffer[FIRST_B], buffer[SECOND_B], buffer[THIRD_B]);
// start of a new JPEG ?
if (buffer[FIRST_B] == 0xff && buffer[SECOND_B] == 0xd8 &&
buffer[THIRD_B] == 0xff && (buffer[FOURTH_B] & 0xf0) == 0xe0){
// close existing JPEG-file
closeFile(img, &file_exists);
// open a new JPEG-file
sprintf(filename, "%03i.jpg", count);
img = fopen(filename, "wb");
if (img == NULL){
fprintf(stderr, "Could not open %s.\n", filename);
return 2;
}
file_exists = true;
// next be later
count++;
}
if (false == file_exists){
continue;
}
else if(true == file_exists){
// write block to JPEG-file
fwrite(&buffer, BUFFER_SIZE, NMEMB, img);
}
}
// close existing JPEG-file
closeFile(img, &file_exists);
// success
return 0;
}
/*
* Close existing JPEG-file
*/
void closeFile(FILE* img, bool* file_exists)
{
if (true == *file_exists){
fclose(img);
}
}
|
C
|
/// Module de gestion mémoire
/// En mettant partout #include "memoire.h" on bénéficie automatiquement
/// d'une "encapsulation" des allocations et libérations mémoires (malloc, free ...)
///
/// -> Avoir une "protection" sur les échecs d'allocation :
/// concrètement une terminaison immédiate du programme, ce n'est
/// pas la solution ultime mais évite un plantage ultérieur...
///
/// -> Comptabiliser précisément le nombre d'allocations et de libérations
/// pour avoir un bilan complet avec alloc_bilan() et vérifier l'absence de fuite mémoire.
///
/// -> Fonctions concernées : malloc, calloc, realloc, strdup, free
/* Usage :
Inclure memoire.h en tête de TOUS les .c du projet
L'inclusion peut être directe (dans les .c)
ou indirecte (dans un .h lui même inclus dans le(s) .c)
Le reste du code est inchangé.
Appeler memoire_alloc_bilan(); pour avoir un bilan complet
Ce bilan peut être fait à n'importe quel moment,
ou à la fin du programme (juste avant le return 0 du main)
Mettre la variable globale memoire_tracer à 1 pour avoir le détail en console
Exemple pour étudier précisément ce qui se passe dans "faire des choses" :
memoire_tracer = 1;
faire des choses
memoire_tracer = 0;
*/
#ifndef SERVICES_H_INCLUDED
#define SERVICES_H_INCLUDED
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>
//===========================================================
/// Booléen pour trace détaillée en console à chaque appel ( non par défaut )
extern int memoire_tracer;
//===========================================================
/// Affichage bilan allocations/libérations.
void memoire_alloc_bilan();
/// Wrappers : NE PAS APPELER DIRECTEMENT
/// VOS APPELS A MALLOC etc... VONT AUTOMATIQUEMENT APPELER CES FONCTIONS
void *malloc_check(size_t size);
void free_check(void *ptr);
void *calloc_check(size_t nmemb, size_t size);
void *realloc_check(void *ptr, size_t size);
char *strdup_check(const char *s);
//===========================================================
/// Déroutage des fonctions mémoire standards vers les fonctions wrappers du module.
#define malloc malloc_check
#define free free_check
#define calloc calloc_check
#define realloc realloc_check
#define strdup strdup_check
#endif // MEMOIRE_H_INCLUDED
|
C
|
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
static const size_t VGA_COLS = 80;
static const size_t VGA_ROWS = 25;
enum vga_color {
VGA_COLOR_BLACK = 0,
VGA_COLOR_BLUE = 1,
VGA_COLOR_GREEN = 2,
VGA_COLOR_CYAN = 3,
VGA_COLOR_RED = 4,
VGA_COLOR_MAGENTA = 5,
VGA_COLOR_BROWN = 6,
VGA_COLOR_LIGHT_GREY = 7,
VGA_COLOR_DARK_GREY = 8,
VGA_COLOR_LIGHT_BLUE = 9,
VGA_COLOR_LIGHT_GREEN = 10,
VGA_COLOR_LIGHT_CYAN = 11,
VGA_COLOR_LIGHT_RED = 12,
VGA_COLOR_LIGHT_MAGENTA = 13,
VGA_COLOR_LIGHT_BROWN = 14,
VGA_COLOR_WHITE = 15,
};
/* Static: static storage duration and internal linkage
- Duration: storage duration is entire execution of the program
- Linkage: identifier can be referred to from all scopes in current translation unit
Inline: replaces a call of the function with its body, eliminating the need for a
function call */
static inline uint8_t vga_entry_color(enum vga_color fg, enum vga_color bg) {
return fg | bg << 4;
}
static inline uint16_t vga_entry(unsigned char uc, uint8_t color) {
return (uint16_t)uc | (uint16_t)color << 8;
}
size_t strlen(const char* str) {
size_t len = 0;
while(str[len])
len++;
return len;
}
size_t term_row;
size_t term_col;
uint8_t term_color;
uint16_t* term_buffer;
void term_init(uint8_t color){
term_row = 0;
term_col = 0;
term_color = color;
term_buffer = (uint16_t*) 0xB8000;
}
void cls() {
for(size_t y = 0; y < VGA_ROWS; y++) {
for(size_t x = 0; x < VGA_COLS; x++) {
const size_t index = y * VGA_COLS + x;
term_buffer[index] = vga_entry(' ', term_color);
}
}
}
void term_set_color(uint8_t color) {
term_color = color;
}
void term_putch_at(char c, uint8_t color, size_t x, size_t y) {
const size_t index = y * VGA_COLS + x;
term_buffer[index] = vga_entry(c, color);
}
void term_putch(char c) {
// Handle newlines
if(c == '\n') {
term_row++;
term_col = -1;
} else {
term_putch_at(c, term_color, term_col, term_row);
}
// If reached edge of screen
if(++term_col == VGA_COLS) {
term_col = 0;
if(++term_row == VGA_ROWS) {
term_row = 0;
}
}
}
void term_put(const char* data, size_t size) {
for(size_t i = 0; i < size; i++) {
term_putch(data[i]);
}
}
void term_puts(const char* data) {
term_put(data, strlen(data));
}
void kernel_main(void) {
term_init(vga_entry_color(VGA_COLOR_GREEN, VGA_COLOR_BLACK));
term_puts("hello\nhello");
//cls();
}
|
C
|
/* BEGIN: just some struct to test, fell free to move them on external header file */
struct A
{
int a1;
long a2;
};
struct B
{
float b1;
char b2[6];
};
struct C
{
unsigned int c1;
double c2[5];
};
/* END: just some struct to test, fell free to move them on external header file */
|
C
|
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int a,b,c,d,x1,x2;
printf("Enter the value of a,b,c=\n");
scanf("%d%d%d",&a,&b,&c);
d= sqrt(b*b-4*a*c);
if(d>0)
{
x1=(-b+d)/(2*a);
x2=(-b-d)/(2*a);
printf("The value x1 and x2 are %d and %d",x1,x2);
}
else if(d<0)
{
printf("roots are imaginary");
}
else
{
x1=-b/(2*a);
printf("Value of x1 is %d",x1);
}
getch();
}
|
C
|
#include "classifica.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//inserisce ordinatamente un nuovo giocatore. restituisce il puntatore al nuovo giocatore
giocatore inserisci_giocatore(classifica my_classifica,char* nickname,char* password,int punteggio){
//due puntatori di appoggio che faccio puntare inizialmente alla testa
giocatore r = my_classifica->head;
giocatore q = my_classifica->head;
//creo un nuovo giocatore
giocatore new_giocatore=(giocatore)malloc(sizeof(struct giocatore));
//in caso di errore
if(new_giocatore==NULL)
return NULL;
//inizializzo il giocatore con i parametri inseriti
strcpy(new_giocatore->nickname, nickname);
strcpy(new_giocatore->password, password);
new_giocatore->punteggio=punteggio;
if (my_classifica->head==NULL){ /*la lista è vuota*/
new_giocatore->next=NULL;
my_classifica->head=new_giocatore;
//restituisce il puntatore al nuovo giocatore inserito
return new_giocatore;
}
/* trova il punto di inserimento */
while ((q != NULL) && (q->punteggio > new_giocatore->punteggio)){
//r raggiunge q
r = q;
//q va avanti di uno
q = q->next;
}
if(q == my_classifica->head){ /*inserimento in testa*/
new_giocatore->next=my_classifica->head;
my_classifica->head=new_giocatore;
}
else{ /*caso generico*/
r->next=new_giocatore;
new_giocatore->next=q;
}
//se tutto è andato a buon fine restituisce il puntatore al giocatore appena inserito
return new_giocatore;
}
//carica la classifica da file
classifica carica_classifica(){
//crea una classifica
classifica new_classifica=(classifica)malloc(sizeof(struct classifica));
//verifica se ci sono errori
if(new_classifica==NULL)
return NULL;
//inizializza la testa della classifica a NULL
new_classifica->head=NULL;
//apre il file in lettura
FILE* f = fopen("classifica.txt", "r");
//verifica se ci sono errori
if (f==NULL) {
perror("Errore nell'apertura del file classifica");
exit(1);
}
//variabili per salvare l'input letto
char nickname[10];
char password[10];
int punteggio;
//ciclo di lettura file
while(fscanf(f,"%s%s%d\n",nickname,password,&punteggio ) != EOF)
//se non ci sono errori inserisce ordinatamente i vari giocatori letti nella classifica creata
if(inserisci_giocatore(new_classifica,nickname,password,punteggio)==NULL){
perror("Errore nella lettura della classifica");
exit(1);
}
//chiude la lettura
fclose(f);
//restituisce la classifica
return new_classifica;
}
/*verifica i dati immessi dall'utente ed in caso positivo resitusice
il puntatore al giocatore che esegue il login*/
giocatore login(classifica my_classifica, char* nickname,char* password){
//puntatore d'appoggio
giocatore p;
//parte dalla testa della classifica
p=my_classifica->head;
//esegue una ricerca esaustiva
while(p!=NULL){
//se trovo l'utente ne restituisco il puntatore
if(strcmp(p->nickname,nickname)==0 && strcmp(p->password,password)==0)
return p;
//vado avanti con la ricerca
p=p->next;
}
//se alla fine non trovo nulla restituisco NULL
return NULL;
}
//verifica se il nickname inserito è già in uso. Restituisce 1 se lo è.
int esiste_nickname(classifica my_classifica,char* nickname){
//puntatore d'appoggio
struct giocatore* p;
//se la classifica è vuota ritorna 0
if(my_classifica->head==NULL)
return 0;
//parte dalla testa della classifica
p=my_classifica->head;
//esegue una ricerca esaustiva
while(p!=NULL){
//se trova il nickname restituisce 1
if(strcmp(p->nickname,nickname)==0){
return 1;
}
//vado avanti con la ricerca
p=p->next;
}
//se alla fine non lo trova restituisce 0
return 0;
}
//elimina un giocatore. Ritorna 0 in caso positivo
int elimina_giocatore(classifica my_classifica,char* nickname){
//puntatori che servono a ricollegare i nodi dopo l'eliminazione
giocatore r =my_classifica->head;
giocatore q =my_classifica->head;
while ((q != NULL) && strcmp(q->nickname, nickname)!=0){
r = q;
q = q->next;
}
//se la lista è vuota
if (q == NULL)
return 1;
//se devo cancellare in testa
if (q==my_classifica->head)
my_classifica->head = my_classifica->head->next;
//caso generale
else
r->next = q->next;
free(q);
return 0;
}
//aggiorna il punteggio di un giocatore. Restituisce 1 in caso positivo
//Questa funzione prima cancella il giocatore e poi lo reinserisce ordinatamente
//La funzione aggiornerà il punteggio solo se quello nuovo è migliore del precedente
int aggiorna_punteggio(classifica my_classifica, giocatore player,int punteggio){
//verifica se il precedente punteggio è migliore
if(player->punteggio>=punteggio){
return 1;
}
//aggiorna il punteggio
else{
//salva i dati del giocatore da dover reinserire
char nickname[10];
strcpy(nickname, player->nickname);
char password[10];
strcpy(password, player->password);
//cancella il giocatore
int result =elimina_giocatore(my_classifica,player->nickname);
//se non è stato cancellato
if(result == 1) return 0;
//reinserisce il giocatore
giocatore result2 = inserisci_giocatore(my_classifica, nickname, password,punteggio);
//se non è stato inserito
if(result2 == NULL) return 0;
return 1;
}
}
//libera lo spazio della classifica
void cancella_classifica(classifica my_classifica){
//puntatori di appoggio
giocatore p=my_classifica->head;
giocatore q=my_classifica->head;
//scorro fino alla fine
while (q != NULL){
//p raggiunge q
p=q;
//q va avanti
q = q->next;
//cancello p
free(p);
}
//cancello q
free(q);
free(my_classifica);
}
//salva la classifica su file
void salva_classifica(classifica my_classifica){
//apre il file in scrittura
FILE* f = fopen("classifica.txt", "w");
//verifica se ci sono errori
if (f==NULL) {
perror("Errore nella scrittura su file classifica");
exit(1);
}
//puntatore di appoggio
giocatore p=my_classifica->head;
//ciclo che stampa ogni utente nel file
while(p!=NULL){
fprintf(f,"%s ",p->nickname);
fprintf(f,"%s ",p->password);
fprintf(f,"%d ",p->punteggio);
fprintf(f,"\n");
//vado al giocatore successivo
p=p->next;
}
//chiude la scrittura
fclose(f);
}
//stampa la classifica
void stampa_classifica(classifica my_classifica){
//se la classifica è vuota
if(my_classifica->head==NULL){
printf("Classifica vuota\n");
return;
}
//puntatore di appoggio
giocatore p=my_classifica->head;
//variabile per stampare la posizione in classifica
int i=1;
//scorro fino alla fine e stampo
while (p != NULL){
printf(" (%d) %s %d\n",i,p->nickname,p->punteggio);
p = p->next;
i++;
}
printf("\n");
}
|
C
|
/*
ID: fanzeyi1
LANG: C
TASK: subset
*/
/*
* =====================================================================================
*
* Filename: subset.c
* Version: 1.0
* Created: 09/22/2011 06:03:33 AM
* Revision: none
* Compiler: gcc
* Author: Zeray Fan, fanzeyi1994[at]gmail.com
* Company: http://www.fanhe.org/
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long long f[40][781];
int main(void) {
FILE *fin = fopen("subset.in","r");
FILE *fout = fopen("subset.out", "w");
int i, j;
int n;
int sum;
fscanf(fin, "%d", &n);
sum = (n * (n + 1))/2;
if(sum % 2 != 0) {
fprintf(fout, "0\n");
return 0;
}
sum = sum / 2;
f[1][1] = 1;
f[1][0] = 1;
for( i = 2 ; i <= n ; i++ ) {
for( j = 0 ; j <= sum ; j++ ) {
if( j - i >= 0 ) {
f[i][j] = f[i-1][j] + f[i-1][j-i];
}else{
f[i][j] = f[i-1][j];
}
}
}
fprintf(fout, "%lld\n", f[n][sum]/2);
return 0;
}
|
C
|
#include <Peripherals/twiCommController.h>
uint8_t statusCode;
bool TWIError;
volatile bool timeoutIsSet = false;
void decodeStatus(uint8_t code){
statusCode = code;
if(code == 0x30 ||
code == 0x38 ||
code == 0x48 ||
code == 0x58){
TWIError = true;
}
}
/*
Set compare register
Enable output compare interrupt
TCCR1B
Enable Clear Timer on Compare Match (CTC) mode
Set CPU clock prescaler to 1/8 (For 8MHz it gaves 1000000 tick per sec)
*/
void setTimeoutTimer(uint8_t ms){
OCR1A = ms * 1000;
TIMSK1 = (1 << OCIE1A);
TCCR1B = (1 << WGM12) | (1 << CS11);
}
/*
Timeout timer compare match interrupt
*/
ISR(TIMER1_COMPA_vect){
TCNT0 = 0;
TCCR1B = 0; // stop the timer
timeoutIsSet = true;
}
/*
Set SCL frequency to 100kHz for 8MHz CPU internal clock
TWCR
Enable TWI
*/
void initTWI(){
TWBR = 32;
TWCR |= (1 << TWEN);
statusCode = 0;
TWIError = false;
}
/*
Start Timeout timer
Wait until TWINT bit is set or Timeout timer goes off
If Timeout timer breaks the while loop,
raise an error and set TWINT bit manually
Otherwise, stop and reset the timer
*/
void waitForComplete(void){
setTimeoutTimer(TIME_OUT_MS);
while(!(TWCR & (1<<TWINT))){
if(timeoutIsSet){
break;
}
}
if(timeoutIsSet){
timeoutIsSet = false;
TWIError = true;
statusCode = 0x99; // Temp status code for timeout
TWCR |= (1 << TWINT);
} else {
TCNT0 = 0;
TCCR1B = 0; // stop the timer
}
}
void TWIStart(void){
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
waitForComplete();
statusCode = TWSR & 0xF8;
}
/*
Combine agent address and direction bit
Load SLA_X into Data Register
*/
void TWISendAddress(uint8_t address, uint8_t direction){
uint8_t SLA_X = address * 2 + direction;
TWDR = SLA_X;
TWCR = (1<<TWINT) | (1<<TWEN);
waitForComplete();
statusCode = TWSR & 0xF8;
}
void TWISendData(uint8_t data){
TWDR = data;
TWCR = (1<<TWINT) | (1<<TWEN);
waitForComplete();
statusCode = TWSR & 0xF8;
}
uint8_t TWIGetData(bool ack){
if(ack){
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
}
else{
TWCR = (1<<TWINT) | (1<<TWEN);
}
waitForComplete();
statusCode = TWSR & 0xF8;
return (TWDR);
}
void TWIStop(void){
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
}
uint8_t TWIStatusCode(void){
return statusCode;
}
bool isError(void){
return TWIError;
}
void clearTWIError(void){
TWIError = false;
}
|
C
|
#include <stdio.h>
#define NUM_QUESTIONS 7
#define MAX_STR_SIZE 1024
void showAnswers() {
int x, y;
x = y = 4;
printf("%d\n", 13>>4+2*3/1&4|2||3);
x = y = 4;
printf("%d\n", --x>>3*++y/4&5);
x = y = 4;
printf("%d\n", y++-4<<4|2);
x = y = 4;
printf("%d\n", 0x22+y++- --x*3<<2);
x = y = 4;
printf("%d\n", 0312&0x49|3<<4*3/4/y++&++x);
x = y = 4;
printf("%d\n", x-->=4^++y%10<<3>>1);
x = y = 4;
printf("%d\n", x--+--y<<3*1/4*12<<1%2);
}
// Gets an int from standard input.
int getInt() {
char c;
int n = 0;
while ((c = getchar()) != '\n') {
n = 10 * n + c - '0';
}
return n;
}
/* An expression using a combination of increment, decrement, or assignment
* operators which modifies the same object more than once is undefined:
*
* http://c-faq.com/expr/evalorder2.html
*
* An expression like this might have different results on differnt compilers:
*
* x++ * --y - --x + x++ + y++ - --y
*/
int main() {
int i, x, y;
int answer, numCorrect;
char questions[NUM_QUESTIONS][MAX_STR_SIZE] = {
"13>>4+2*3/1&4|2||3",
"--x>>3*++y/4&5",
"y++-4<<4|2",
"0x22+y++- --x*3<<2",
"0312&0x49|3<<4*3/4/y++&++x",
"x-->=4^++y%10<<3>>1",
"x--+--y<<3*1/4*12<<1%2"
};
int answers[] = {1, 0, 2, 116, 73, 21, 14};
numCorrect = 0;
//showAnswers();
printf("Welcome to 7 Expressions!\n\n");
printf("Assume x = y = 4\n");
for (i = 0; i < NUM_QUESTIONS; ++i) {
printf("%s\n", questions[i]);
answer = getInt();
if (answer == answers[i]) {
printf("Correct!!\n");
++numCorrect;
} else {
printf("Incorrect.\n");
}
}
printf("Score: %d/%d\n", numCorrect, NUM_QUESTIONS);
return 0;
}
|
C
|
#include<stdio.h>
/*
배열 ( array )
- 같은 타입의 데이터 공간을 한번의 선언으로 메모리에 연속적으로 생성하는 것을 말합함
배열 선언(생성)
- 자료형 배열명[ 크기(공간갯수) ]
배열의 요소 사용
- 배열명[ index ]
> 배열의 index 번호는 무조건 '0'부터 시작
*/
int main() {
int ar1[3]; //ar1 12byte
// | ? | ? | ? |
// [0] [1] [2]
ar1[0] = 11;
ar1[1] = 22;
ar1[2] = 33;
printf("ar[0] : %d\n", ar1[0]);
printf("ar[1] : %d\n", ar1[1]);
printf("ar[2] : %d\n", ar1[2]);
int ar2[3] = { 1, 2, 3 }; // ar2
// | 1 | 2 | 3 |
// [0] [1] [2]
// ar = { 10, 20, 30 }; Error
// 배열 전체 요소 or 여러개의 요소에 한번에 접근 할 수 있는건
// 배열 생성과 동시에 최초 한번만 가능
int ar3[] = { 5, 6, 7, 8 }; // ar3
// | 5 | 6 | 7 | 8 |
// [0] [1] [2] [3]
// 배열 선언과 동시에 저장하려는 데이터의 수와 값이 정해져 있으면
// 배열 크기를 지정하지 않아도 저장하려는 데이터 수만큼 자동으로 생성한다
int ar4[3] = { 1 }; // ar4
// | 1 | 0 | 0 |
// [0] [1] [2]
// 배열 선언과 동시에 한개의 요소라도 초기화하면
// 나머지 뒤에 요소는 자동 '0'으로 초기화
//int size = 3;
//int ar5[size];
//배열의 크기값으로 상수만 가능함
int ar5[3];
ar5[0] = 11;
ar5[1] = 22;
int idx = 2;
ar5[idx] = 33;
printf("ar5[0] : %d\n", ar5[0]);
printf("ar5[1] : %d\n", ar5[1]);
printf("ar5[%d] : %d\n", idx, ar5[idx]);
puts("");
for (int i = 0; i < 3; i++) {
printf("ar5[%d] : %d\n", i, ar5[i]);
}
puts("");
}
|
C
|
#ifndef _BSD_SOURCE
#define _BSD_SOURCE
#endif
#include <endian.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include "pathops.h"
#include "public.h"
#include "mt_log.h"
extern char *default_md5sum_filename;
unsigned int crc32(const char *s, unsigned int len)
{
/* 生成 CRC32 的查询表 */
static unsigned int table[256];
static bool needinit = true;
if (needinit) {
int i, j;
unsigned int crc;
for (i = 0; i < 256; i++) {
crc = i;
for (j = 0; j < 8; j++) {
if (crc & 1) {
crc = (crc >> 1) ^ 0xEDB88320;
} else {
crc = crc >> 1;
}
}
table[i] = crc;
}
needinit = false;
} else {
/* 查询表已经初始化,无需再次初始化 */
}
/* 开始计算 CRC32 校验值 */
unsigned int crc = 0xFFFFFFFF;
unsigned int k;
for (k = 0; k < len; k++) {
int x = (crc & 0xff) ^ s[k];
crc = (crc >> 8) ^ table[x];
}
crc = crc ^ 0xFFFFFFFF;
return crc;
}
void map1(const char *s, int size, int *x1, int *x2)
{
unsigned int crc = crc32(s, size);
unsigned int key = crc % 4096;
*x1 = key / 64; /* 第一级的 0~63 */
*x2 = key % 64; /* 第二级的 0~63 */
}
void map2(const char *buf, unsigned int len, int *x3, int *x4)
{
/* 第三级的 0~99 */
unsigned int i;
int v;
v = 0;
for (i = 0; i < len; i++) {
v = v * 31 + buf[i];
}
v = v % 101;
if (v < 0) {
/* 发生了溢出 */
v = v + 101;
} else {
/* 没有溢出 */
}
*x3 = v;
/* 第四级的 0~99(可能回到103) */
unsigned int j;
int z;
z = 0;
for (j = 0; j < len; j++) {
z = z * 37 + buf[j];
}
z = z % 103;
if (z < 0) {
/* 发生了溢出 */
z = z + 103;
} else {
/* 没有溢出 */
}
*x4 = z;
}
void maplevel(const char *buf, unsigned int len,
int *x1, int *x2, int *x3, int *x4)
{
map1(buf, len, x1, x2);
map2(buf, len, x3, x4);
}
/*
* 根据给定的挂载点(mountpoiint),检查号(studyid),检查的系列号
* (serial)计算出路径名。计算出来的结果放在用户传入的缓冲区中。
*
* 注意:挂载点要求是一个绝对路径。
*
* 如果计算成功,返回 0;如果出现错误,返回 -1。
*/
int calcpath(
const char *mountpoint, const char *studyid, const char *serial,
char *resultpath, int *resultlen)
{
int studylen = strlen(studyid);
int leftsize = *resultlen;
char *unused = resultpath;
int x1, x2, x3, x4;
maplevel(studyid, studylen, &x1, &x2, &x3, &x4);
char buf[1024]; /* XXX: 路径名不能超过 1024,暂时这样实现 */
int pathlen;
/* 挂载点 盘符 四级目录 检查号 系列号 */
if (serial) {
/* pathlen 不包括空字符 '\0' */
pathlen = snprintf(
buf, sizeof(buf), "%s/%d/%d/%d/%d/%s/%s",
mountpoint, x1, x2, x3, x4, studyid, serial);
} else {
/* 没有系列号,直接查找检查号 */
pathlen = snprintf(
buf, sizeof(buf), "%s/%d/%d/%d/%d/%s",
mountpoint, x1, x2, x3, x4, studyid);
}
if (leftsize >= pathlen + 1/*空字符'\0'*/) {
if (!access(buf, F_OK)) {
memmove(unused, buf, pathlen+1/*包括字符串结束符'\0'*/);
unused = unused + pathlen + 1;
leftsize = leftsize - pathlen - 1;
} else {
/* 路径不存在,忽略之,不填入缓冲区,继续下一次处理 */
// log_info("skip %s: no such path", buf);
}
} else {
/* 用户给出的缓冲区已经没有空间,不填充结果,返回错误 */
return -1;
}
*resultlen = *resultlen - leftsize;
return 0;
}
void test1(void)
{
const char *mountpoint = "/sgw.1";
const char *studyid = "1.2.826.0.1.3680043.2.461.9701983.3645589902";
const char *serial = "serial111";
char buffer[16384];
int buflen = 16384;
calcpath(mountpoint, studyid, serial, buffer, &buflen);
int leftsize = buflen;
char *next = buffer;
while (leftsize > 0) {
int n = printf("%s", next);
printf("\n");
leftsize = leftsize - n - 1;
next = next + n + 1;
}
}
/*
* 输入参数形如 "studyid/serial" 这样的字符串,返回指向 studyid 和
* serial 的起始地址。
*/
void split_serial(char *s, char **studyid, char **serial)
{
char *s1 = s;
while (*s1 != '\0' && *s1 != '/') {
s1 = s1 + 1;
}
if (*s1 == '\0') {
/* 没有 serial */
*studyid = s;
*serial = NULL;
} else {
/* studyid/serial */
*s1 = '\0';
*studyid = s;
char *s2 = s1 + 1;
while (*s2 == '/') {
s2 = s2 + 1;
}
if (*s2 == '\0') {
*serial = NULL;
} else {
*serial = s2;
/* 处理 studyid/serial////xxxx 这种情况,只保留 serial */
while (*s2 != '/' && *s2 != '\0') {
s2 = s2 + 1;
}
if (*s2 == '/') {
*s2 = '\0';
} else {
/* 到了字符串末尾,不做处理 */
}
}
}
}
/* 从绝对路径 abspath 中剪除挂载点路径 mountpoint */
void cut_mount_path(char *abspath, const char *mountpoint)
{
int mountlen = strlen(mountpoint);
char *mountpath = malloc(mountlen + 1);
assert(mountpath);
memmove(mountpath, mountpoint, mountlen + 1);
char *c = mountpath + mountlen - 1;
int n = 0;
while (c >= mountpath && *c == '/') {
*c = '\0';
n = n + 1;
c = c - 1;
}
mountlen = mountlen - n;
if (!memcmp(abspath, mountpath, mountlen)) {
int abslen = strlen(abspath);
int reallen = abslen - mountlen;
memmove(abspath, &abspath[mountlen], reallen);
abspath[reallen] = '\0';
} else {
/* 挂载点不匹配,不做处理 */
}
free(mountpath);
}
/*
* 2 个字节的文件名长度,因为一个字节最多表示 31 个字节的文件名长度。
* 文件名长度如果是负数,则表示出错了。
*/
static int fill_file_list(char *out, char *end,
char *filename, int64_t filesize)
{
int namelen = strlen(filename);
if (out + 2/*文件名长度*/ + namelen + 8/*文件内容长度*/ <= end) {
*((int16_t *)out) = htobe16(namelen);
out = out + 2;
(void) memmove(out, filename, namelen);
out = out + namelen;
*((int64_t *)out) = htobe64(filesize);
return namelen + 10;
} else {
/* 缓冲区的长度不够,返回错误 */
log_error("buffer is too small!");
return -1;
}
}
/*
* 根据给出的目录路径名,找出目录下的所有文件名。每个文件获取大小,按
* 照特定的格式输出。文件列表格式如下:
*
* (5 hello 14) (4 abcd 102) (3 123 4096)
*
* 注意:文件列表的路径是绝对路径,并且是剪除了挂载点目录后的绝对路径。
* 如果挂载点在路径名不存在,则不做剪除操作。
*
* 返回值:
*
* 0 - 成功
* -1 - 打开目录失败
* -2 - 读取目录项失败
* -3 - 获取子目录失败(已废弃)
* -4 - 缓冲区太小
*/
int get_dir_list(
const char *dirpath, const char *mountpath,
char *list, int listlen,
struct file_list_result *res)
{
int rc;
int retcode = 0;
int32_t nr_files = 0;
DIR *dp = opendir(dirpath);
if (dp) {
struct dirent entry;
struct dirent *result;
char *out = list;
char *end = list + listlen;
for (;;) {
int rc = readdir_r(dp, &entry, &result);
if (rc == 0) {
if (!result) {
/* 读取目录项完毕,可以关闭目录 */
assert(nr_files >= 0);
res->nr_files = nr_files;
res->used_buflen = out - list;
retcode = 0;
goto out;
} else {
/*
* 现在目录项中的一项内容已经读取到 entry 中,可以
* 在 entry.d_name 读取文件名
*/
struct stat s;
char filepath[2048];
snprintf(filepath, sizeof(filepath), "%s/%s", dirpath, entry.d_name);
int rc = stat(filepath, &s);
if (rc == 0) {
if (S_ISREG(s.st_mode)) {
if (!strcmp(entry.d_name, default_md5sum_filename)) {
/* 不返回生成的,用来记录 md5 校验和的文件 */
} else {
nr_files = nr_files + 1;
// log_info("get_dir_list: %d: %s %lld", nr_files, filepath, (long long int)s.st_size);
cut_mount_path(filepath, mountpath);
int filllen = fill_file_list(
out, end, filepath, s.st_size);
if (filllen > 0) {
/* 缓冲区内容有填充,更新缓冲区指针 */
out = out + filllen;
} else {
/* 出错了,缓冲区太小了? */
log_error("fill %s failed", filepath);
retcode = -4;
goto out;
}
}
} else if (S_ISDIR(s.st_mode)) {
if (!strcmp(entry.d_name, ".") || !strcmp(entry.d_name, "..")) {
/* 跳过当前目录和上一级目录 */
} else {
struct file_list_result res;
int rc = get_dir_list(
filepath, mountpath, out, end - out, &res);
if (rc != 0) {
/* 嗯,递归调用出错了!提前终止 */
log_error("get_dir_list: get %s file list failed", entry.d_name);
retcode = rc;
goto out;
} else {
/*
* 递归获取目录成功,文件列表已经放在
* 缓冲区中,更新文件数量和缓冲区长度
*/
nr_files = nr_files + res.nr_files;
out = out + res.used_buflen;
}
}
} else {
/* 忽略其他文件 */
log_error("skip %s: is not a regular file or directory",
entry.d_name);
}
} else {
/* 获取文件的元信息失败,继续处理下一个文件 */
int ec = errno;
log_error("skip %s: %s", filepath, strerror(ec));
}
}
} else {
int ec = errno;
log_error("readdir_r %s failed on %s: %s",
dirpath, entry.d_name, strerror(ec));
retcode = -2;
goto out;
}
}
return 0;
} else {
int ec = errno;
log_error("opendir %s failed: %s", dirpath, strerror(ec));
return -1;
}
/* 程序不会运行到这里 */
assert(0);
out:
rc = closedir(dp);
if (rc == -1) {
int ec = errno;
log_error("closedir %s failed: %s", dirpath, strerror(ec));
} else {
/* 关闭目录成功,不需要特别处理 */
}
return retcode;
}
/*
* 依次每次获取目录下的文件列表,所有目录都处理完毕之后,再填充缓冲区
* 头部的消息包长度和文件列表个数
*
* (256) (3) (5 hello 12) (3 abc 123) (4 1234 4096)
*/
char *fill_many_dir_list(
const char *mountpath, const char *dirs[], int nr_dir,
struct file_list_result *out)
{
/* 一个系列最多 3000 个文件,假设一个检查最多 10 个系列,每个文件
* 的路径名最多 256 字节,最多有 23 个盘符。
*
* 文件列表的最大大小=3000*10*256*23=176640000字节=172500KB=169MB
*
* 文件列表的最小大小=3000*1*256*1=768000字节=750KB
*/
int nr_files = 0; /* 记录获取的文件列表数量 */
int used_buflen = 0; /* 已使用的消息包缓冲区长度 */
char *buffer = NULL; /* 消息包缓冲区 */
int maxbufsize = 170 * 1024 * 1024; /* 消息包的最大缓冲区大小:170MB */
int bufsize = 2 * 1024 * 1024; /* 首次尝试使用的消息包缓冲区是 2MB */
int nr_scan = 0; /* 成功扫描的目录个数 */
buffer = malloc(bufsize);
if (!buffer) {
log_error("malloc %d bytes failed", bufsize);
return NULL;
} else {
/* 缓冲区分配成功,继续执行,获取目录下的文件列表 */
}
/*
* 如果获取单个目录下的文件列表失败,就加大缓冲区重试,已获取的文
* 件列表拷贝到新的缓冲区中。当获取某个目录下的文件列表超过了最大
* 重试次数,则放弃这个目录,进行处理下一个目录。
*/
int i;
for (i = 0; i < nr_dir; i++) {
const char *dirpath = dirs[i];
struct file_list_result res;
char *start;
int buflen;
again:
/* 8字节的消息包长度,4字节的文件列表长度 */
start = buffer + 8 + 4 + used_buflen;
buflen = bufsize - 8 - 4 - used_buflen;
int rc = get_dir_list(dirpath, mountpath, start, buflen, &res);
if (rc != 0) {
if (rc == -4) {
if (bufsize < maxbufsize) {
/* 缓冲区太小,加大缓冲区重试 */
if (bufsize * 2 > maxbufsize) {
bufsize = maxbufsize;
} else {
bufsize = bufsize * 2;
}
buffer = realloc(buffer, bufsize);
if (!buffer) {
log_error("realloc %d bytes failed", bufsize);
free(buffer);
return NULL;
} else {
/* 重新分配缓冲区成功,重试 */
log_info("increase buffer to %d bytes", bufsize);
goto again;
}
} else {
log_error("skip %s: max bufsize (%d bytes) reach",
dirpath, bufsize);
goto out;
}
} else {
log_error("skip %s: get_dir_list failed", dirpath);
}
} else {
/* 当前目录处理完毕,累计文件数量和缓冲区使用量 */
nr_scan = nr_scan + 1;
nr_files = nr_files + res.nr_files;
used_buflen = used_buflen + res.used_buflen;
}
}
out: {
/* 获取多个目录下的文件列表完成,最后填充消息包长度和文件列表个数 */
int64_t *msglen = (int64_t *)(&buffer[0]);
*msglen = htobe64(used_buflen + 12);
int32_t *listlen = (int32_t *)(&buffer[8]);
*listlen = htobe32(nr_files);
out->nr_files = nr_files;
out->used_buflen = 8/*消息包总长度*/ + 4/*文件列表长度*/ + used_buflen;
log_info("%d directory, %d scan, %d files, %d bytes",
nr_dir, nr_scan, nr_files, used_buflen+12);
return buffer;
}
}
void print_file_list(const char *buffer)
{
int64_t msglen = *((int64_t *)&buffer[0]);
msglen = be64toh(msglen);
printf("print_file_list: message length %lld\n", (long long int)msglen);
int listlen = *((int *)(&buffer[8]));
listlen = be32toh(listlen);
printf("print_file_list: found %d files\n", listlen);
const char *p = &buffer[12]; /* 8个字节表示消息长度,4个字节表示文件列表个数 */
char filename[4096];
int i;
for (i = 0; i < listlen; i++) {
int16_t namelen = *((int16_t *)p);
namelen = be16toh(namelen);
p = p + 2;
(void) memmove(filename, p, namelen);
filename[namelen] = '\0';
p = p + namelen;
int64_t contentlen = *((int64_t *)p);
contentlen = be64toh(contentlen);
p = p + 8;
printf("%s: %lld\n", filename, (long long int)contentlen);
}
}
off_t get_file_size(const char *filepath)
{
struct stat s;
int rc = stat(filepath, &s);
if (rc == 0) {
return s.st_size;
} else {
printf("get %s status failed: %s\n", filepath, strerror(errno));
return -1;
}
}
|
C
|
/*
*
* Factorial Zeros: Write an algorithm which computes the number of trailing zeros in n factorial.
*
*/
#include <stdio.h>
void factorization_in_2_and_5(unsigned int a, int * power_of_2, int * power_of_5);
void factorial_zero(unsigned int a, int * power_of_2, int * power_of_5);
int min(int a, int b);
int main()
{
for (unsigned int i = 1; i < 40; i ++)
{
int power_of_2, power_of_5;
factorial_zero(i,&power_of_2, &power_of_5);
printf("number of trailing zeros for %d! is %d.\n", i, min(power_of_2,power_of_5));
}
return 0;
}
void factorial_zero(unsigned int a, int * power_of_2, int * power_of_5)
{
/* some base cases */
if (a == 1 || a == 0)
{
*power_of_2 = 0;
*power_of_5 = 0;
return;
}
/* recurse */
factorial_zero(a - 1, power_of_2, power_of_5);
int res_2, res_5;
factorization_in_2_and_5(a, &res_2, &res_5);
*power_of_2 += res_2;
*power_of_5 += res_5;
}
void factorization_in_2_and_5(unsigned int a, int * power_of_2, int * power_of_5)
{
/* first, the power of 2 in a */
int res_2 = 0;
unsigned int tmp = a;
while ( (tmp & 1) == 0)
{
res_2 ++;
tmp = tmp >> 1;
}
*power_of_2 = res_2;
/* now the power of 5 */
int res_5 = 0;
tmp = a;
while ( (tmp %5) == 0)
{
res_5 ++;
tmp = tmp / 5;
}
*power_of_5 = res_5;
}
int min(int a, int b)
{
return a<b?a:b;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
struct memstream
{
char *buf;
size_t rsize;//缓冲实际大小
size_t vsize;//缓冲虚拟大小
size_t curpos;//缓冲中目前的位置
int flags;
};
/*flags*/
#define MS_READ 0x01 //打开读取
#define MS_WRITE 0x02 //写入
#define MS_APPEND 0x04 //插入到流中
#define MS_TRUNC 0x08//截断打开
#define MS_FREB 0x10//关闭流,清空buff
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
static int mstream_read(void *, char *, int);
static int mstream_write(void *, const char *, int);
static fpos_t mstream_seek(void *, fpos_t, int);
static int mstream_close(void *);
static int type_to_flags(const char *__restrict type);
static off_t find_end(char *buf, size_t len);
FILE * fmemopen(void *__restrict buf, size_t size, const char *__restrict type);
|
C
|
#include <stdio.h>
#include <stdlib.h>
// definicja naszego typu
typedef struct Node {
int data;
struct Node *next;
} Node;
void insert(Node **ptr_head, int x);
void print(Node *head);
int main(int argc, char const *argv[]) {
int n, i, x;
// stworzenie pierwszego elementu listy i wypełnienie zerami
Node *head = NULL;
printf("How long the list should be?\n");
scanf("%d", &n);
for (i=0; i<n; i++){
printf("Enter the number: ");
scanf("%d", &x);
// Przekazanie wskaznika do wskaznika ktory wskazuje na pierwszy element listy
insert(&head, x);
print(head);
}
return 0;
}
void insert(Node **ptr_head, int x){
// stworzenie dynamicznie miejsca w pamięci dla nowego elementu listy
Node *temp = (Node*) malloc(sizeof(struct Node));
// wypelnienie struktury danymi
temp->data = x;
// ustawienie wskaznika na NULL - ustawiamy element jako ostatni
temp->next = NULL;
// Jesli head nie jest NULL, czyli jesli jest juz jakis element w liscie
if (*ptr_head != NULL) temp->next = *ptr_head;
*ptr_head = temp;
}
void print(Node *head){
printf("List is: ");
while (head != NULL){
printf("%d , ", head->data);
head = head->next;
}
printf("\n");
}
|
C
|
#include <stdio.h>
#define ST_NUM 100 //学生数
typedef struct
{
int nu; //序号
int SNo[11]; //学号
char Name[9]; //姓名
int GSHu; //数学
int Dying;//大学英语
int CCHeng;//c语言
int DTi;//体育
int JDaiSHi;//现代历史
int RDao;//软件
int FDaoYuan;//辅导员评分
int BZHuRen;//班主任评分
int Bjin;//班级同学评分
int GKeFlag;//挂科标记
double sum;
double ZHeFen;//综合成绩
}student;
student ST[ST_NUM]={0};
//输入函数
int input(int num)
{
int i;
printf ("请输入%d个学生的信息:\n",num);
for (i=0;i<num;i++)
{
printf("序号:");
if(scanf("%d",&ST[i].nu)!=1)
{
printf("输入错误");
return 1;
}
printf ("学号:");
scanf ("%d",&ST[i].SNo);
printf("姓名:");
scanf ("%s",ST[i].Name);
printf("请输入业务考试成绩:\n");
printf("高等数学的成绩:");
if(scanf("%d",&ST[i].GSHu)!=1)
{
printf("输入错误");
return 1;
}
printf("C语言程序设计的成绩:");
if(scanf("%d",&ST[i].CCHeng)!=1)
{
printf("输入错误");
return 1;
}
printf("大学英语视听一的成绩:");
if(scanf("%d",&ST[i].Dying)!=1)
{
printf("输入错误");
return 1;
}
printf("软件技术导论成绩:");
if(scanf("%d",&ST[i].RDao)!=1)
{
printf("输入错误");
return 1;
}
printf("近代史的成绩:");
if(scanf("%d",&ST[i].JDaiSHi)!=1)
{
printf("输入错误");
return 1;
}
printf("大学体育的成绩:");
if(scanf("%d",&ST[i].DTi)!=1)
{
printf("输入错误");
return 1;
}
printf("请输入平时表现成绩:\n");
printf("辅导员评分:");
if(scanf("%d",&ST[i].FDaoYuan)!=1)
{
printf("输入错误");
return 1;
}
printf("班主任评分:");
if(scanf("%d",&ST[i].BZHuRen)!=1)
{
printf("输入错误");
return 1;
}
printf("同学评分:");
if(scanf("%d",&ST[i].Bjin)!=1)
{
printf("输入错误");
return 1;
}
}
return 0;
}
//数据处理
void process(int num)
{
int i;
//挂科判断
for(i=0;i<num;i++)
{
if(ST[i].Dying<60)
{
ST[i].GKeFlag=1;
break;
}
if(ST[i].CCHeng<60)
{
ST[i].GKeFlag=1;
break;
}
if(ST[i].DTi<60)
{
ST[i].GKeFlag=1;
break;
}
if(ST[i].JDaiSHi<60)
{
ST[i].GKeFlag=1;
break;
}
if(ST[i].RDao<60)
{
ST[i].GKeFlag=1;
break;
}
if(ST[i].GSHu<60)
{
ST[i].GKeFlag=1;
break;
}
}
//综合成绩计算;
for(i=0;i<num;i++)
{
ST[i].sum+=(ST[i].Dying+ST[i].CCHeng+ST[i].DTi+ST[i].JDaiSHi+ST[i].RDao)*0.7+(ST[i].FDaoYuan+ST[i].BZHuRen+ST[i].Bjin)*0.3;
}
}
//排名
void sort(int num)
{
student temp;
int i,j,t,flag=0;
//依据是否挂科排名
for(i=0;i<num;i++)
{
for(j=0;j<num-1-i;j++)
{
if(ST[j].GKeFlag<ST[j+1].GKeFlag)
{
temp=ST[j];
ST[j]=ST[j+1];
ST[j+1]=temp;
flag++;
}
}
}
//未挂科同学排名
for (t=0;t<flag-1;t++)
{
for(i=t;i<flag-1-t;i++)
{
if(ST[i].ZHeFen<ST[i+1].ZHeFen)
{
temp=ST[i];
ST[i]=ST[i+1];
ST[i+1]=temp;
}
}
}
}
void output(int num)
{
int i;
double j1,j2,j3;
printf("获得奖学金的同学:\n");
printf("\t\t\t\t奖学金\t序号\t姓名\n");
j1=num*0.03;
j2=num*0.07;
j3=num*0.2;
//四舍五入
j1=(int)(j1+0.5);
j2=(int)(j2+0.5);
j3=(int)(j3+0.5);
for (i=0;i<=j1;i++)
{
printf("\t\t\t\t一等奖\t%d\t%s\t\n",ST[i].nu,ST[i].Name);
}
for (i=j1;i<j2;i++)
{
printf("\t\t\t二等奖\t");
printf("%d\t%s\t\n",ST[i].nu,ST[i].Name);
}
for (i=j2;i<j3;i++)
{
printf("\t\t\t三等奖\t");
printf("%d\t%s\t\n",ST[i].nu,ST[i].Name);
}
}
int main()
{
int num;
printf("请输入学生人数:");
scanf("%d",&num);
if(input(num)==1)
return 0;
process(num);
sort(num);
output(num);
return 0;
}
|
C
|
/*
** my_nbr.c for my_nbr in /home/mar_b/rendu/Piscine-C-Jour_11/do-op
**
** Made by Fabien Martinez
** Login <mar_b@epitech.net>
**
** Started on Mon Mar 24 15:04:01 2014 Fabien Martinez
** Last update Mon Mar 24 16:36:33 2014 Fabien Martinez
*/
#include "my_fun.h"
int my_bool_int(unsigned int nbr, char bool)
{
unsigned int max;
unsigned int min;
max = 2147483647;
min = 2147483648;
if ((nbr > max && bool != 1) || (nbr > min && bool == 1))
{
return (1);
}
return (0);
}
int my_getnbr(char *str)
{
int i;
unsigned int nbr;
int less;
less = 0;
nbr = 0;
i = 0;
if (my_strlen(str) > 11)
return (0);
while (str[i] != 0 && (str[i] == '-' || str[i] == '+'))
{
if (str[i] == '-')
less += 1;
i += 1;
}
while (str[i] != 0 && str[i] >= '0' && str[i] <= '9')
{
nbr = nbr * 10 + (*(str + i) - '0');
if (my_bool_int(nbr, less % 2) == 1)
return (0);
i += 1;
}
if (less % 2 == 1 && nbr <= 2147483648)
return (-nbr);
return (nbr);
}
void rec_my_put_nbr(unsigned int nbr)
{
if (nbr <= 9)
{
my_putchar('0' + nbr);
}
else
{
rec_my_put_nbr(nbr / 10);
my_putchar ('0' + (nbr % 10));
}
}
void my_put_nbr(int nbr)
{
if (nbr < 0)
{
my_putchar('-');
rec_my_put_nbr(-nbr);
}
else
rec_my_put_nbr(nbr);
}
|
C
|
#include "dk_tool.h"
pnode new_bt_node(int x){
pnode ret = malloc(sizeof(node));
if(ret==NULL){printf("INVALID MALLOC\n");return NULL;}
ret->a = x;
ret->ch[0] = NULL;
ret->ch[1] = NULL;
return ret;
}
bintree* new_bintree(){
bintree* ret = malloc(sizeof(bintree));
if(ret==NULL){printf("INVALID MALLOC\n");return NULL;}
ret->length=0;
ret->head = NULL;
return ret;
}
pnode bin_search(bintree* bt, int d){
pnode tmp = bt->head;
while(1){
if(tmp == NULL) return NULL;
else if(d == tmp->a) return tmp;
else tmp = tmp->ch[(d > tmp->a)?1:0];
}
}
void add_node(bintree* bt, int d)
{
pnode tmp, *new;
new = &bt->head;
tmp = bt->head;
while(1){
if(tmp == NULL)
{
tmp = *new = new_bt_node(d);return;
}
else if(d == tmp->a) return;
else{
new = &tmp->ch[(d > tmp->a)];
tmp = tmp->ch[(d > tmp->a)];
}
}
}
pnode pop_node(bintree* bt, int d){
pnode* q, z;
q=&bt->head;
z=bt->head;
while(1){
if(z == NULL) return NULL;
else if(d == z->a) break;
else{
q = &z->ch[(d > z->a)];
z = z->ch[(d > z->a)];
}
}
if(z->ch[1] == NULL){
*q = z->ch[0];
}else{
pnode y = z->ch[1];
if(y->ch[0] == NULL){
y->ch[0] = z->ch[0];
*q=y;
}else{
pnode x=y->ch[0];
while(x->ch[0] != NULL){
y = x;
x = y->ch[0];
}
y->ch[0] = x->ch[1];
x->ch[0] = z->ch[0];
x->ch[1] = z->ch[1];
*q=x;
}
}
bt->length--;
return z;
}
void node_print(pnode in){
if(in == NULL)return;
node_print(in->ch[0]);
printf("%d\n", in->a);
node_print(in->ch[1]);
}
void bt_print(bintree* in){
node_print(in->head);
}
void node_free(pnode in){
if(in == NULL)return;
node_free(in->ch[0]);
node_free(in->ch[1]);
free(in);
}
void bt_free(bintree* in){
node_free(in->head);
free(in);
}
int get_int(void){ //from MIT's cs50 library i dont understand how it works
regex_t pattern;
char* str = malloc(64);
scanf("%s", str);
regcomp(&pattern, "[+-]?[0-9]+", REG_EXTENDED | REG_NOSUB);
while(regexec(&pattern, str, 0, NULL, 0)){
printf("Retry: ");
scanf("%s", str);
}
int d = atoi(str);
free(str);
regfree(&pattern);
return d;
}
|
C
|
#include<conio.h>
#include<stdio.h>
void main()
{
float weight;
printf("ENTER THE WEIGHT OF THE BOXER(IN POUNDS) TO KNOW THEIR WEIGHT CLASS\n");
scanf("%f",&weight);
if(weight<115)
printf("CLASS:'FLY WEIGHT'");
else if(weight>=115 && weight<=121)
printf("CLASS:'BANTAM WEIGHT'");
else if(weight>=122 && weight<=153)
printf("CLASS:'FEATHER WEIGHT'");
else if(weight>=154 && weight<=189)
printf("CLASS:'MIDDLE WEIGHT'");
else
printf("CLASS:'HEAVY WEIGHT'");
getch();
clrscr();
}
|
C
|
/* GRUPO: COVidoneos */
/* FICHERO CON LAS FUNCIONES DE LAS 13 ESCENAS */
/* Las funciones dibujarEscena imprimen el texto correspondiente */
/* de la historia en la ventana lateral, la imagen de la escena */
/* que esta guardada en el txt correspondiente y en la ventana */
/* title se imprime el lugar en el que os encontramos. */
/* Tanto el texto de la historia como la imagen de la escena se */
/* encuentran en archivos txt. Para imprimir el texto, usamos la */
/* función setLateralPath que se encuentra en personaje.c; y la */
/* escena la imprimimos con la función setMapa que se encuentra en */
/* personaje.c. */
/* Mientras que el título lo imprimimos directamente con la función */
/* printCentered definida en el fichero print_helper.c. */
/* Las funciones updateEscena sirven para llamar a la siguiente */
/* escena tecleando la tecla 'n'. Pero para poder pasar de escena */
/* pulsando esta tecla, es necsario que el usuario realice ciertas */
/* "pruebas". Además, algunas de estas funciones cambiarán el texto */
/* que aparece en la ventana lateral para guiar al usuario y que */
/* pueda seguir la historia. */
/* AÑADIR COMETARIOS EN CADA FUNCIÓN */
#include <stdio.h>
#include <stdlib.h>
#include "escenas.h"
static int flag;
static int elegida;
static int correcta;
/* Para acabar el juego */
/* *iescena = -1 */
void dibujarEscena0(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
flag = FALSE;
setWindowFile(lateral, "./res/text/inicio.txt");
clearWin(title);
printFile(title, "./res/text/title_escena0.txt");
setMapa(game, "./res/maps/hospital.txt");
return;
}
void updateEscena0(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
if (*input=='o' || *input=='O') {
setWindowFile(lateral, "./res/text/email.txt");
flag = TRUE;
clearInput(input);
}
/* Para pasar a la siguiente escena */
if (flag==TRUE && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena1(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena1(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
/* flag indica si se ha conseguido el reto */
flag = FALSE;
setWindowFile(lateral, "./res/text/madrid.txt");
clearWin(title);
printFile(title,"./res/text/title_escena1.txt");
setMapa(game, "./res/maps/aeropuerto.txt");
return;
}
void updateEscena1(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
/* Comprobamos que se ha usado la mascarilla y que el valor introducido tiene sentido */
if (*input>='1' && *input<='4') {
if (ObjectIsUsed(getObject(prota, MASCARILLA))) {
/* Indicamos que se ha conseguido el reto */
flag = TRUE;
setWindowFile(lateral, "./res/text/next.txt");
}
/* Si se usa otro objeto del maletín bajamos la salud */
else if (*input!='1'){
bajarSalud(prota);
}
}
/* Para pasar a la siguiente escena */
if (flag && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena2(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena2(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
clearWin(title);
printFile(title, "./res/text/title_escena2.txt");
setMapa(game, "./res/maps/aeropuerto_it.txt");
return;
}
void updateEscena2(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
setWindowFile(lateral, "./res/text/italia1.txt");
/* Comprobamos que se ha usado la PCR y que el valor introducido tiene sentido */
if (*input>='1' && *input<='4') {
if (ObjectIsUsed(getObject(prota, PCR))) {
/* Indicamos que se ha conseguido el reto */
flag = TRUE;
setWindowFile(lateral, "./res/text/next.txt");
}
/* Si se usa otro objeto del maletín bajamos la salud */
else if (*input!='2'){
bajarSalud(prota);
}
}
/* Para pasar a la siguiente escena */
if (flag && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena3(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena3(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
clearWin(title);
printFile(title, "./res/text/title_escena3.txt");
setMapa(game, "./res/maps/beirut.txt");
return;
}
void updateEscena3(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
setWindowFile(lateral, "./res/text/libano1.txt");
/* Para pasar a la siguiente escena */
if (*input=='n' || *input=='N') {
(*iescena)++;
dibujarEscena4(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena4(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
/* flag indica si el reto está conseguido */
flag = FALSE;
clearWin(title);
printFile(title, "./res/text/title_escena3.txt");
setMapa(game, "./res/maps/fabrica.txt");
setWindowFile(lateral, "./res/text/libano2.txt");
return;
}
void updateEscena4(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
int lastLine, contador=0, i;
char output[STR_LEN];
char serie[4] = {'_', '_', '_', '_'};
int blink[4] = { 5, 25, 25, 25 };
char inp;
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
if (flag==FALSE && (*input=='p' || *input=='P')) {
clearWin(game);
setMapa(game, "./res/maps/papel.txt");
lastLine = setWindowFile(lateral, "./res/text/libano_num.txt");
clearInput(input);
/* Mientras la serie introducida no sea correcta */
while (flag==FALSE) {
/* Mientras el usuario introduce los valores */
while (contador<4) {
sprintf(output, "%c[%dm%c%c[%dm-%c[%dm%c%c[%dm-%c[%dm%c%c[%dm-%c[%dm%c%c[%dm", ESC_SEQ, blink[0], serie[0], ESC_SEQ, 25,
ESC_SEQ, blink[1], serie[1], ESC_SEQ, 25,
ESC_SEQ, blink[2], serie[2], ESC_SEQ, 25,
ESC_SEQ, blink[3], serie[3], ESC_SEQ, 25);
printPos(lateral, 1, lastLine + 1, FALSE, output);
inp = getc(stdin);
/* Si no se introducen números */
while (inp<'1' && inp>'9') {
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
inp = getc(stdin);
}
clearLine(lateral, lastLine);
serie[contador] = inp;
blink[contador] = 25;
if (contador<3) blink[contador+1] = 5;
contador++;
}
/* Comprobar que la serie introducida por el usuario es la correcta */
/* Cambio de flag a TRUE, se ha conseguido el reto */
if (serie[0]=='6' && serie[1]=='7' && serie[2]=='3' && serie[3]=='1') {
flag = TRUE;
clearWin(game);
setMapa(game, "./res/maps/fabrica2.txt");
setWindowFile(lateral, "./res/text/libano3.txt");
}
/* Si los números no coinciden, reasignamos valores y quitamos vida */
else {
if (bajarSalud(prota)) break;
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
for(i=0; i<4; i++) {
serie[i]='_';
}
blink[0]=5;
for(i=1; i<4; i++) {
blink[i]=25;
}
contador=0;
}
}
}
/* Para pasar a la siguiente escena */
if (flag==TRUE && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena5(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena5(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
clearWin(title);
printFile(title, "./res/text/title_escena5.txt");
setMapa(game, "./res/maps/cartel_santini.txt");
return;
}
void updateEscena5(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
setWindowFile(lateral, "./res/text/rusia1.txt");
/* Para obtener más información y se pasa a la siguiente escena */
if (*input=='i' || *input=='I') {
(*iescena)++;
dibujarEscena6(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena6(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
/* flag indica si el reto está conseguido */
flag = FALSE;
clearWin(title);
printFile(title, "./res/text/title_escena5.txt");
setMapa(game, "./res/maps/rusia.txt");
setWindowFile(lateral, "./res/text/rusia2.txt");
return;
}
void updateEscena6(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
int lastLine, contador=0, i;
char output[STR_LEN];
char serie[5] = {'_', '_', '_', '_', '_'};
int blink[5] = { 5, 25, 25, 25, 25};
char inp;
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
if (flag==FALSE && (*input=='p' || *input=='P')) {
lastLine = setWindowFile(lateral, "./res/text/rusia3.txt");
clearInput(input);
/* Mientras la serie introducida no sea correcta */
while (flag==FALSE) {
/* Mientras el usuario introduce los valores */
while (contador<5) {
sprintf(output, "%c[%dm%c%c[%dm%c[%dm%c%c[%dm%c[%dm%c%c[%dm%c[%dm%c%c[%dm%c[%dm%c%c[%dm", ESC_SEQ, blink[0], serie[0], ESC_SEQ, 25,
ESC_SEQ, blink[1], serie[1], ESC_SEQ, 25,
ESC_SEQ, blink[2], serie[2], ESC_SEQ, 25,
ESC_SEQ, blink[3], serie[3], ESC_SEQ, 25,
ESC_SEQ, blink[4], serie[4], ESC_SEQ, 25);
printPos(lateral, 1, lastLine + 1, FALSE, output);
inp = getc(stdin);
/* Comprobamos que se han introducido letras */
while ((inp<'a' && inp>'z') && (inp<'A' && inp>'Z') ) {
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
inp = getc(stdin);
}
clearLine(lateral, lastLine);
serie[contador] = inp;
blink[contador] = 25;
if (contador<3) blink[contador+1] = 5;
contador++;
}
/* Comprobar que la serie introducida por el usuario es la correcta */
if ((serie[0]=='c' || serie[0]=='C') && (serie[1]=='h' || serie[1]=='H') && (serie[2]=='i' || serie[2]=='I') && (serie[3]=='n' || serie[3]=='N') && (serie[4]=='a' || serie[4]=='A')) {
flag = TRUE;
setWindowFile(lateral, "./res/text/next.txt");
}
/* Si los números no coinciden, reasignamos valores y quitamos vida*/
else {
if (bajarSalud(prota)) break;
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
for(i=0; i<5; i++) {
serie[i]='_';
}
blink[0]=5;
for(i=1; i<5; i++) {
blink[i]=25;
}
contador=0;
}
}
}
/* Para pasar a la siguiente escena */
if (flag==TRUE && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena7(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena7(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
clearWin(title);
printFile(title, "./res/text/title_escena7.txt");
setMapa(game, "./res/maps/laboratorio.txt");
clearWin(lateral);
return;
}
void updateEscena7(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
setWindowFile(lateral, "./res/text/wuhan1.txt");
/* Comprobamos que se han usado los guantes y que el valor introducido tiene sentido */
if (*input>='1' && *input<='4') {
if (ObjectIsUsed(getObject(prota, GUANTES))) {
/* Indicamos que se ha conseguido el reto */
flag = TRUE;
setWindowFile(lateral, "./res/text/next.txt");
}
/* Si se usa otro objeto del maletín bajamos la salud */
else if (*input!='3'){
bajarSalud(prota);
}
}
/* Para pasar a la siguiente escena */
if (flag && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena8(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena8(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
clearWin(title);
printFile(title, "./res/text/title_escena7.txt");
setMapa(game, "./res/maps/lab_guantes.txt");
/* flag indica si el reto está conseguido */
flag = FALSE;
clearWin(lateral);
return;
}
void updateEscena8(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
int lastLine, contador=0, i;
char output[STR_LEN];
char serie[3] = {'_', '_', '_'};
int blink[3] = { 5, 25, 25};
char inp;
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
if (flag==FALSE) {
lastLine = setWindowFile(lateral, "./res/text/wuhan2.txt");
clearInput(input);
/* Mientras la serie introducida no sea correcta */
while (flag==FALSE) {
/* Mientras el usuario introduce los valores */
while (contador<3) {
sprintf(output, "%c[%dm%c%c[%dm%c[%dm%c%c[%dm%c[%dm%c%c[%dm", ESC_SEQ, blink[0], serie[0], ESC_SEQ, 25,
ESC_SEQ, blink[1], serie[1], ESC_SEQ, 25,
ESC_SEQ, blink[2], serie[2], ESC_SEQ, 25);
printPos(lateral, 1, lastLine + 1, FALSE, output);
inp = getc(stdin);
/* Comprobamos si se ha introducido letras */
while ((inp<'a' && inp>'z') && (inp<'A' && inp>'Z')) {
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
inp = getc(stdin);
}
clearLine(lateral, lastLine);
serie[contador] = inp;
blink[contador] = 25;
if (contador<2) blink[contador+1] = 5;
contador++;
}
/* Comprobar que la serie introducida por el usuario es la correcta */
if ((serie[0]=='e' || serie[0]=='E') && (serie[1]=='l' || serie[1]=='L') && (serie[2]=='s' || serie[2]=='S')){
flag = TRUE;
clearWin(game);
setMapa(game, "./res/maps/cofre.txt");
setWindowFile(lateral, "./res/text/wuhan3.txt");
}
/* Si las letras no coinciden, reasignamos valores y quitamos vida*/
else {
if (bajarSalud(prota)) break;
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
for(i=0; i<3; i++) {
serie[i]='_';
}
blink[0]=5;
for(i=1; i<3; i++) {
blink[i]=25;
}
contador=0;
}
}
}
/* Para pasar a la siguiente escena */
if (flag==TRUE && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena9(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena9(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
clearWin(title);
printFile(title, "./res/text/title_escena7.txt");
setMapa(game, "./res/maps/contagio.txt");
return;
}
void updateEscena9(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
setWindowFile(lateral, "./res/text/wuhan4.txt");
/* Comprobamos que se ha usado el gel y que el valor introducido tiene sentido */
if (*input>='1' && *input<='4') {
if (ObjectIsUsed(getObject(prota, GEL_HIDROALCOHOLICO))) {
/* Indicamos que se ha conseguido el reto */
flag = TRUE;
setWindowFile(lateral, "./res/text/next.txt");
}
/* Si se usa otro objeto del maletín bajamos la salud */
else if (*input!='4'){
bajarSalud(prota);
}
}
/* Para pasar a la siguiente escena */
if (flag && (*input=='n' || *input=='N')) {
(*iescena)++;
dibujarEscena10(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena10(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
/* flag indica si el reto está conseguido */
flag = FALSE;
clearWin(title);
printFile(title, "./res/text/title_escena7.txt");
setMapa(game, "./res/maps/leer.txt");
return;
}
void updateEscena10(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
int lastLine=0;
char inp;
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
lastLine = setWindowFile(lateral, "./res/text/wuhan6.txt");
/* Mientras no se haya conseguido el reto */
while (flag==FALSE) {
inp = getc(stdin);
switch (inp) {
/* Opción correcta, cambia bandera a TRUE */
case 'a':
case 'A':
clearLine(lateral, lastLine);
flag = TRUE;
setWindowFile(lateral, "./res/text/next.txt");
break;
/* Opción incorrecta, baja salud e imprime mensaje de incorrecto */
case 'b':
case 'B':
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
if (bajarSalud(prota)) return;
break;
/* Opción incorrecta, baja salud e imprime mensaje de incorrecto */
case 'c':
case 'C':
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
if (bajarSalud(prota)) return;
break;
default:
printColorPos(lateral, COLOR_RED, COLOR_BLACK, 1, lastLine, TRUE, getIncorrectoStr());
break;
}
}
/* Para pasar a la siguiente escena */
if (flag==TRUE && (*input=='n' || *input=='N')){
(*iescena)++;
dibujarEscena11(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena11(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
setMapa(game, "./res/maps/torre.txt");
clearWin(title);
printFile(title, "./res/text/title_escena7.txt");
setWindowFile(lateral, "./res/text/wuhan7.txt");
return;
}
void updateEscena11(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
/* Para pasar a la siguiente escena */
if (*input=='n' || *input=='N'){
(*iescena)++;
dibujarEscena12(iescena, game, lateral, title);
clearInput(input);
}
return;
}
void dibujarEscena12(int *iescena, Window *game, Window *lateral, Window *title) {
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
setMapa(game, "./res/maps/puertas_nada.txt");
setWindowFile(lateral, "./res/text/wuhan8.txt");
clearWin(title);
printFile(title, "./res/text/title_escena7.txt");
/* Para diferenciar entre la primera elección o la segunda en la siguiente función */
flag = FALSE;
srand (time(NULL));
/* Entre 0 y 2, se escoge aleatoriamente cuál será la puerta correcta */
correcta = rand()*3/RAND_MAX;
return;
}
void updateEscena12(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
/* Según la puerta que haya salido correcta aleatoriamente y la elección del usuario los casos posibles son: */
/* Primera elección */
if (flag == FALSE) {
switch (*input) {
case 'a':
case 'A':
elegida = 0;
if (correcta==1) setMapa(game, "./res/maps/puertas_der.txt");
else setMapa(game, "./res/maps/puertas_centro.txt");
break;
case 'v':
case 'V':
elegida = 1;
if (correcta==0) setMapa(game, "./res/maps/puertas_der.txt");
else setMapa(game, "./res/maps/puertas_izq.txt");
break;
case 'r':
case 'R':
elegida = 2;
if (correcta==0) setMapa(game, "./res/maps/puertas_centro.txt");
else setMapa(game, "./res/maps/puertas_izq.txt");
break;
default:
clearInput(input);
return;
}
setWindowFile(lateral, "./res/text/wuhan9.txt");
flag = TRUE;
clearInput(input);
return;
}
/* Segunda elección */
else {
/* Si se queire cambiar */
if (*input=='c' || *input=='C') {
if (elegida==0) {
if (correcta==1) elegida = 1;
else elegida = 2;
}
else if (elegida==1) {
if (correcta==0) elegida = 0;
else elegida = 2;
}
else {
if (correcta==0) elegida = 0;
else elegida = 1;
}
clearInput(input);
}
/* Si se mantiene la elección */
else if (*input=='s' || *input=='S') {
clearInput(input);
}
/* Si pulsa una tecla que no es correcta */
else {
clearInput(input);
return;
}
/* Si se ha acertado, se pasa a la siguiente escena */
if (correcta==elegida) {
(*iescena)++;
dibujarEscena13(iescena, game, lateral, title);
return;
}
bajarSalud(prota);
bajarSalud(prota);
bajarSalud(prota);
dibujarEscena12(iescena, game, lateral, title);
return;
}
return;
}
void dibujarEscena13(int *iescena, Window *game, Window *lateral, Window *title){
if(game==NULL||title==NULL||lateral==NULL){
*iescena=-1;
return;
}
setMapa(game, "./res/maps/hermano.txt");
setWindowFile(lateral, "./res/text/final.txt");
clearWin(title);
printFile(title, "./res/text/title_escena0.txt");
return;
}
void updateEscena13(int *iescena, char *input, Window *game, Window *title, Window *lateral, Personaje *prota) {
if(iescena==NULL||game==NULL||title==NULL||lateral==NULL||prota==NULL || input==NULL){
*iescena=-1;
return;
}
/* Para finalizar el juego */
if (*input=='f' || *input=='F'){
(*iescena)=-1;
}
return;
}
|
C
|
#include <stdio.h>
#include<math.h>
#include <mpi.h>
#define NodeNum 4
#define ROOT 0
#define L 1.0
#define LAMBDA 0.0003
#define PI 3.141592
int main(int argc, char* argv[]){
int nRank, nProcs;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &nRank);
MPI_Comm_size(MPI_COMM_WORLD, &nProcs);
MPI_Request req;
MPI_Status status;
int JOB = L/LAMBDA;
int lastR,start,end,remain, jobs;
lastR = NodeNum - 1;
jobs = JOB / NodeNum;
remain = JOB % NodeNum;
start = nRank * jobs;
if (nRank == lastR) {
end = start + jobs + remain;
}
else {
end = start + jobs;
}
long int count = 0, num_modes;
double x, y, z, r, delta, sol;
delta = LAMBDA;
int i;
if(nRank==lastR){
for (i= start; i<=end; i++){
x = i*delta;
for (y = 0.0; y <= L; y = y + delta){
for (z = 0.0; z <= L; z = z + delta){
r = sqrt(x*x + y*y + z*z);
if (r <= L)
count++;
}
}
}
}
else{
for (i = start; i< end; i++){
x = i*delta;
for (y = 0.0; y <= L; y = y + delta){
for (z = 0.0; z <= L; z = z + delta){
r = sqrt(x*x + y*y + z*z);
if (r <= L)
count++;
}
}
}
}
printf("rank : %d,count : %ld\n",nRank,count);
long int sum = 0.0;
MPI_Reduce(&count, &sum, 1, MPI_LONG, MPI_SUM, ROOT, MPI_COMM_WORLD);
if(nRank==ROOT){
num_modes = 16 * sum;
sol = 8.0*PI*L *L*L / 3.0 / LAMBDA / LAMBDA / LAMBDA;
printf("Number of modes = %ld (from mode counting)\n", num_modes);
printf("Number of modes = %f (from solution)\n", sol);
}
MPI_Finalize(); // MPI End
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
long long int x,y,z,max,c,i,t,j,k,p,q;
scanf("%lld",&t);
for(i=0;i<t;i++)
{
max=0;
scanf("%lld%lld",&x,&y);
for(j=x;j<=y;j++)
{
q=sqrt(j);
c=0;
for(k=1;k<=q;k++){
if(j%k==0){
c++;
if(j/k!=k)
c++;
}
}
if(max<c){
max=c;
z=j;
}
}
printf("Between %lld and %lld, %lld has a maximum of %lld divisors.\n",x,y,z,max);
}
}
|
C
|
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <stdbool.h>
typedef struct node {
void* value;
struct node* next;
} node;
typedef struct {
node* head;
node* tail;
//do not modify the size value manually
int _size;
} linkedList;
linkedList* createList();
bool appendToList(linkedList* l, void* pVal);
bool prependToList(linkedList* l, void* pVal);
bool insertValueAt(linkedList* l, int index, void* pVal);
void* removeValueAt(linkedList* l, int index);
void* removeValue(linkedList* l, void* pVal, bool (*comparator)(void*, void*));
void* removeFirst(linkedList* l);
void* removeLast(linkedList* l);
void* getValueAt(linkedList* l, int index);
void* getFirst(linkedList* l);
void* getLast(linkedList* l);
int getLastIndex(linkedList* l);
int findIndexOfValue(linkedList* l, void* value, bool (*comparator)(void*, void*));
int getListSize(linkedList* l);
bool listIsEmpty(linkedList* l);
void iterateListValues(linkedList* l, void (*iterator)(void*));
void reverseList(linkedList* l);
void clearList(linkedList* l, bool freeValues);
void freeList(linkedList* l, bool freeValues);
bool intComp(void* searchVal, void* currentVal);
bool floatComp(void* searchVal, void* currentVal);
bool doubleComp(void* searchVal, void* currentVal);
bool longComp(void* searchVal, void* currentVal);
bool charComp(void* searchVal, void* currentVal);
bool strComp(void* searchVal, void* currentVal);
void** listToArrayShallowCpy(linkedList* l);
void** listToArrayDeepCpy(linkedList* l, void* (*memAllocFunc)(void*));
void* intMemAlloc(void* intToCpy);
void* floatMemAlloc(void* floatToCpy);
void* doubleMemAlloc(void* doubleToCpy);
void* longMemAlloc(void* longToCpy);
void* charMemAlloc(void* charToCpy);
void* stringMemAlloc(void* strToCpy);
#endif
#ifndef KVP_H
#define KVP_H
typedef struct {
void* key;
void* val;
} keyValPair;
#endif
|
C
|
/***************************************************************************
* FILENAME: level_sprite.c
* DESCRIPTION: Handles the Sprites for level buttons
*
* ENVIRONMENT:
* macOS Catalina 10.15.7
* Visual Studio Code 1.56.2
* AUTHORS:
* Kevin Colour
* DATES:
* Created: 22Jun2021
***************************************************************************/
#include "main.h"
SDLX_Sprite_Data *carve_hp_sprite(void)
{
size_t i;
SDL_Texture *texture;
SDLX_Sprite_Data *result;
result = SDL_calloc(20, sizeof(*result));
texture = SDLX_LoadTexture(ASSETS"hp.png");
i = 0;
/* The HP */
result[i].texture = texture;
result[i]._src = (SDL_Rect){0, 0, 16, 16};
result[i].src = &(result[i]._src);
result[i].cycle = 1;
i++;
result[i].texture = texture;
result[i]._src = (SDL_Rect){16, 0, 16, 16};
result[i].src = &(result[i]._src);
result[i].cycle = 1;
i++;
/* The Loss HP */
result[i].texture = texture;
result[i]._src = (SDL_Rect){0, 16, 16, 16};
result[i].src = &(result[i]._src);
result[i].cycle = 1;
i++;
result[i].texture = texture;
result[i]._src = (SDL_Rect){16, 16, 16, 16};
result[i].src = &(result[i]._src);
result[i].cycle = 1;
i++;
while (i < 20)
{
result[i].texture = texture;
result[i]._src = (SDL_Rect){(i - 4) * 16, 32, 16, 16};
result[i].src = &(result[i]._src);
result[i].cycle = 16;
i++;
}
return (result);
}
int fetch_hp_sprite(SDLX_Sprite_Data **dst, int no)
{
static SDLX_Sprite_Data *sprite_arr;
if (sprite_arr == NULL)
sprite_arr = carve_hp_sprite();
if (no == 1) { (*dst) = &(sprite_arr[0]); return (EXIT_SUCCESS); }
else if (no == 1) { (*dst) = &(sprite_arr[1]); return (EXIT_SUCCESS); }
else if (no == -1) { (*dst) = &(sprite_arr[2]); return (EXIT_SUCCESS); }
else if (no == -2) { (*dst) = &(sprite_arr[3]); return (EXIT_SUCCESS); }
else if (no == 3) { (*dst) = &(sprite_arr[4]); return (EXIT_SUCCESS); }
else { return (EXIT_FAILURE); }
}
|
C
|
#include <mpi.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the number of processes and rank of the process
int size, my_rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
int my_sum = 0;
int send_rank = my_rank; // Send buffer
int recv_rank = 0; // Receive buffer
// Compute the ranks of left/right neighbours
int left_rank, right_rank;
left_rank=(my_rank+size-1)%size;
right_rank=(my_rank+1)%size;
// Loop over the number of processes
// send to right, receive from left
// update the send buffer
// update the local sum
for(int i=0; i<size; i++){
MPI_Ssend(&send_rank, 1, MPI_INT, right_rank,0, MPI_COMM_WORLD);
MPI_Recv(&recv_rank, 1, MPI_INT, left_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
send_rank=recv_rank;
my_sum += recv_rank;
}
printf("I am processor %d out of %d, and the sum is %d\n", my_rank, size, my_sum);
// Finalize the MPI environment.
MPI_Finalize();
}
|
C
|
#include "holberton.h"
/**
* _strcmp - compare two strings
*@s1: compared with s2
*@s2: compared with s1
*Return: integer value
*/
int _strcmp(char *s1, char *s2)
{
int n;
for (n = 0; s1[n] == s2[n]; n++)
{
if (s1[n] == 0)
return (0);
}
return (s1[n] - s2[n]);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
int split_line(char *args[], char line[]) {
int i=0;
args[i] = strtok(line," ");
while(1) {
char *temp = strtok(NULL," ");
if (temp == NULL){
break;
}
i++;
args[i]=temp;
}
return i;
}
void read_line(char line[]) {
int i=0;
fgets(line, 200, stdin);
while(1) {
if(line[i] == '\n'){
line[i] = '\0';
break;
}
i++;
}
}
void writeChildId(int id){
FILE* fp ;
fp = fopen("ID.log" , "a");
fprintf(fp, " Child is terminate . Child id is %d \n" ,id);
fclose(fp);
}
void handler() {
//printf("handler\n");
int id =getpid();
writeChildId(id);
}
int main() {
while (1){
char *args[20];
char line[200];
printf("AKL>");
read_line(line);
int len = split_line(args,line);
char *comm = args[0];
if(comm == NULL) continue;
if( strcmp(comm,"exit")==0)
exit(0);
char *attrs[20];
for(int i=1; i<=len; i++){
attrs[i] = args[i];
}
attrs[len+1]=NULL;
signal(SIGCHLD,handler);
pid_t child_pid=fork();
if (child_pid==0) {
int w = execvp(comm, attrs);
if (w==-1){
printf("Error:%s not found!\n",comm);
exit(0);
}
}
else
if(strcmp(args[len], "&") != 0){
waitpid(child_pid,0, 0);
//printf("Parent ID is %d \n",getpid());
}
}
return 0;
}
|
C
|
/**
* \file debut.c
* \author Nathan OUALET
* \brief Permet via un menu, de choisir entre un enouvelle partie, voir les rêgles ou quitter le jeu.
* \date 05 décembre 2016
* \verson 1.0
*/
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void Page_Regles(WINDOW *localwin, int y, int x){
mvwprintw(localwin, y, x, " Rêgles du Yahtzee ");
mvwprintw(localwin, y+1, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+2, x, "| As à Six | Vous multipliez le nombre d occurrences d une |");
mvwprintw(localwin, y+3, x, "| | valeur par cette valeur et l écrivez dans la |");
mvwprintw(localwin, y+4, x, "| | case correspondante. i.e. Vous obtenez 5 Deux, |");
mvwprintw(localwin, y+5, x, "| | vous inscrivez 10 dans la case. |");
mvwprintw(localwin, y+6, x, "| | |");
mvwprintw(localwin, y+7, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+8, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+9, x, "| Brelan | Vous obtenez trois fois le même chiffre et deux|");
mvwprintw(localwin, y+10, x, "| | autres chiffres. Vous additionnez le total des |");
mvwprintw(localwin, y+11, x, "| | dés et l'écrivez dans la case « Brelan » |");
mvwprintw(localwin, y+12, x, "| | |");
mvwprintw(localwin, y+13, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+14, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+15, x, "| Pt Suite | Vous obtenez une suite de quatre chiffre. |");
mvwprintw(localwin, y+16, x, "| | Vous gagnez 30 points. |");
mvwprintw(localwin, y+17, x, "| | |");
mvwprintw(localwin, y+18, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+19, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+20, x, "| Gd Suite | Vous obtenez une suite de cinq chiffres. |");
mvwprintw(localwin, y+21, x, "| | Vous gagnez 40 points. |");
mvwprintw(localwin, y+22, x, "| | |");
mvwprintw(localwin, y+23, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+24, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+25, x, "| Carré | Vous obtenez quatre fois le même chiffre et un |");
mvwprintw(localwin, y+26, x, "| | autre. Vous additionnez le total des dés et |");
mvwprintw(localwin, y+27, x, "| | l'écrivez dans la case « Carré ». |");
mvwprintw(localwin, y+28, x, "| | |");
mvwprintw(localwin, y+29, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+30, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+31, x, "| Full | Vous obtenez trois dés identiques et 2 dés |");
mvwprintw(localwin, y+32, x, "| | identiques entre eux. Vous additionnez le total|");
mvwprintw(localwin, y+33, x, "| | des dés et l'écrivez dans la case « Full », |");
mvwprintw(localwin, y+34, x, "| | vous gagnez 25 points bonus. |");
mvwprintw(localwin, y+35, x, "| | |");
mvwprintw(localwin, y+36, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+37, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+38, x, "| Yahtzee | Vous obtenez 5 dés identiques. |");
mvwprintw(localwin, y+39, x, "| | Vous marquez 50 points. |");
mvwprintw(localwin, y+40, x, "| | |");
mvwprintw(localwin, y+41, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+42, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+43, x, "| Chance | Vous additionnez la valeur de chaque dé et |");
mvwprintw(localwin, y+44, x, "| | l'écrivez dans la case. |");
mvwprintw(localwin, y+45, x, "| | |");
mvwprintw(localwin, y+46, x, "+------------+------------------------------------------------+");
mvwprintw(localwin, y+47, x, "+-------------------------------------------------------------+");
mvwprintw(localwin, y+48, x, "| Attention ! Plusieurs résultats peuvent correspondre à |");
mvwprintw(localwin, y+49, x, "| plusieurs catégories mais vous ne pouvez remplir une case |");
mvwprintw(localwin, y+50, x, "| qu'une seule fois, soyez stratégiques ! |");
mvwprintw(localwin, y+51, x, "+-------------------------------------------------------------+");
}
void Regles(){
/* A faire dans une fenetre ayant moins de lignes que le texte que l'on veut afficher */
int x, y, ch;
WINDOW * ZoneRegles;
ZoneRegles = newwin(30, 67, 1, 1);
wrefresh(ZoneRegles);
keypad(ZoneRegles, TRUE);
y = 1;
x = 1;
do
{
wclear(ZoneRegles);
/* Copier Les règles ici */
Page_Regles(ZoneRegles, y, x);
wrefresh(ZoneRegles);
ch = wgetch(ZoneRegles);
switch (ch)
{
case KEY_DOWN:
if ( y > -24 )
{
y = y-1;
}
break;
case KEY_UP:
if ( y < 1)
{
y = y + 1;
}
break;
//case 'q' : Debut(); break;
}
} while (ch != 10); /* Entrée fait sortir de l'affichage des règles */
/* Retour au menu ici */
}
int debut(WINDOW *localwin, int y, int x){
/* Affichage du menu et saisie du choix */
mvwprintw(localwin, y, x, "Bonjour Joueurs de Yahtzee !");
mvwprintw(localwin, y+1, x, " |Nouvelle Partie ?");
mvwprintw(localwin, y+2, x, " |Voir les Regles.");
mvwprintw(localwin, y+3, x, " |Quitter le jeu.");
}
void SelectDebut()
{
int y, x, ch;
y = 1; //indice d'ordonnée
x = 1; // indice d'abscisse
WINDOW * ZoneDebut;
ZoneDebut = newwin(30, 67, 1, 1);
keypad(ZoneDebut, TRUE); //Permet l'utilisation des touches directionnelles
debut(ZoneDebut, y, x);
wmove(ZoneDebut, 2, 1);
wrefresh(ZoneDebut);
do
{
ch = wgetch(ZoneDebut);
switch (ch)
{
case KEY_DOWN:
if ( y < 4 )
{
y += 1;
wmove(ZoneDebut, y, x);
wrefresh(ZoneDebut);
}
else{
y -= 2;
wmove(ZoneDebut, y, x);
wrefresh(ZoneDebut);
}
break;
case KEY_UP:
if ( y > 2)
{
y -= 1;
wmove(ZoneDebut, y, x);
wrefresh(ZoneDebut);
}
else{
y += 2;
wmove(ZoneDebut, y, x);
wrefresh(ZoneDebut);
}
break;
}
wrefresh(ZoneDebut);
} while ( ch != 10 );
/* On valide la selection avec la touche entree */
/*if ( y == 3 ) {
Partie();
}*/
if ( y == 3){
Regles();
}
else{
}
}
int Debut(){
initscr();
cbreak();
noecho(); /* Les trois lignes au dessus sont dans MiseEnPlace() */
SelectDebut();
endwin();
}
int main(){
Debut();
}
|
C
|
#include <stdio.h>
#define NIL -1
#define MAX 100
int lookup[MAX];
void initialzeLookup()
{
for (int i = 0; i < MAX; i++)
{
lookup[i] = NIL;
}
}
int fib(int n)
{
if (lookup[n] == NIL)
{
if (n <= 1) {
lookup[n] = n;
} else
{
lookup[n] = fib(n - 1) + fib(n-2);
}
}
return lookup[n];
}
int main()
{
int n = 41;
initialzeLookup();
printf("%d\n",fib(n));
return 0;
}
|
C
|
/// @file
/// Test CeedVectorSetArray to remove array access
/// \test Test CeedVectorSetArray to remove array access
#include <ceed.h>
#include <math.h>
int main(int argc, char **argv) {
Ceed ceed;
CeedVector x;
const CeedInt n = 10;
CeedScalar a[n];
CeedScalar *b, *c;
CeedInit(argv[1], &ceed);
CeedVectorCreate(ceed, n, &x);
for (CeedInt i=0; i<n; i++)
a[i] = 0;
a[3] = -3.14;
CeedVectorSetArray(x, CEED_MEM_HOST, CEED_USE_POINTER, a);
// Taking array should return a
CeedVectorTakeArray(x, CEED_MEM_HOST, &c);
if (fabs(c[3] + 3.14) > 1E-15)
// LCOV_EXCL_START
printf("Error taking array c[3] = %f", (double)c[3]);
// LCOV_EXCL_STOP
// Getting array should not modify a
CeedVectorGetArray(x, CEED_MEM_HOST, &b);
b[5] = -3.14;
CeedVectorRestoreArray(x, &b);
if (fabs(a[5] + 3.14) < 1E-15)
// LCOV_EXCL_START
printf("Error protecting array a[3] = %f", (double)a[3]);
// LCOV_EXCL_STOP
// Note: We do not need to free c because c == a was stack allocated.
// If libCEED allocated c, then free() would be required.
CeedVectorDestroy(&x);
CeedDestroy(&ceed);
return 0;
}
|
C
|
#include<stdio.h>
#define fun2(y,new_y,flag) \
y=new_y;\
printf("%s=%f\n",#y,y);\
flag=1
#define fun(key_char,y,new_y,flag) \
if(key==key_char){\
printf("key=%c,",key_char);\
fun2(y,new_y,flag);\
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* Link list struct Node */
struct Node
{
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data)
{
struct Node *temp;
temp=(struct Node*) malloc(sizeof(struct Node));
temp->data=new_data;
temp->next=NULL;
if(*head_ref == NULL)
{
*head_ref=temp;
}
else
{
temp->next=*head_ref;
*head_ref=temp;
}
}
void pairWiseSwap(struct Node *head)
{
struct Node *temp = head;
/* Traverse further only if there are at-least two nodes left */
while (temp != NULL && temp->next != NULL)
{
/* Swap data of node with its next node's data */
swap(&temp->data, &temp->next->data);
/* Move temp by 2 for the next pair */
temp = temp->next->next;
}
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void printList( struct Node *head)
{
struct Node *temp=head;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
}
int main()
{
struct Node *start = NULL;
int a, x, i;
scanf("%d", &a);
for (i = 0; i < a; i++)
{
scanf("%d",&x);
push(&start, x);
}
pairWiseSwap(start);
printList(start);
return 0;
}
|
C
|
#include "cs136.h"
/////////////////////////////////////////////////////////////////////////////
// INTEGRITY INSTRUCTIONS
// Explicitly state the level of collaboration on this question
// Examples:
// * I discussed ideas with classmate(s) [include name(s)]
// * I worked together with classmate(s) in the lab [include name(s)]
// * Classmate [include name] helped me debug my code
// * I consulted website [include url]
// * None
// A "None" indicates you completed this question entirely by yourself
// (or with assistance from course staff)
/////////////////////////////////////////////////////////////////////////////
// INTEGRITY STATEMENT:
// I received help from the following sources:
// None
// Name: Jiadong Mai
// login ID: J4mai
/////////////////////////////////////////////////////////////////////////////
bool pay_duty1(int duration, int goods, bool alcohol, bool diplomat) {
if (diplomat == true) {
return false;
} else if (duration < 24) {
return (goods > 0);
} else if (duration >= 48) {
return (goods > 800);
} else if (goods <= 200) {
return alcohol;
} else {
return true;
}
}
bool pay_duty2(int duration, int goods, bool alcohol, bool diplomat) {
return (diplomat == false) &&
(((duration < 24) && (goods > 0)) ||
((duration < 48) &&
((goods > 200) || alcohol)) ||
(goods > 800));
}
int my_pow(int n, int k) {
if (k == 0) {
return 1;
} else {
return (n * my_pow(n, (k-1)));
}
}
int count_digits(int n) {
if (n < 10) {
return 1;
} else {
return 1 + count_digits(n / 10);
}
}
bool is_prime_core(int k, int n) {
if (k == 1) {
return true;
} else if ((n % k) == 0) {
return false;
} else {
return is_prime_core((k-1), n);
}
}
bool is_prime(int n) {
return is_prime_core ((n-1), n);
}
int fibonacci_countup(int f2, int f1, int k, int n) {
if (k == n) {
return (f2 + f1);
} else {
return fibonacci_countup(f1, (f2 + f1), (k +1), n);
}
}
int fibonacci(int n) {
if (n < 2) {
return n;
} else {
return fibonacci_countup(0, 1, 2, n);
}
}
int reverse_digits(int n) {
if (n == 0) {
return 0;
} else {
return (n % 10) * my_pow(10, (count_digits(n)-1)) +
reverse_digits(n / 10);
}
}
int median3(int a, int b, int c) {
if (((a <= b) && (a >= c)) || ((a >= b) && (a <= c))) {
return a;
} else if (((b <= a) && (b >= c)) || ((b >= a) && (b <= c))) {
return b;
} else {
return c;
}
}
int main(void) {
assert(pay_duty1(1, 1, false, false));
assert(pay_duty2(1, 1, false, false) ==
pay_duty1(1, 1, false, false));
assert(my_pow(1, 1) == 1);
assert(count_digits(0) == 1);
assert(is_prime(2));
assert(fibonacci(1) == 1);
assert(reverse_digits(1) == 1);
assert(median3(1, 1, 1) == 1);
// add more asserts below to test your code
// pay_duty1
assert(pay_duty1(1,2,false, true) == false);
assert(pay_duty1(23,-1,false, false) == false );
assert(pay_duty1(23,5,false, false));
assert(pay_duty1(55,100,false, false) == false );
assert(pay_duty1(55,805,false, false) == true);
assert(pay_duty1(35,205,true, false));
assert(pay_duty1(35,150,false, false) == false);
// pay_duty2
assert(pay_duty2(1,2,false, true) == false);
assert(pay_duty2(23,-1,false, false) == false );
assert(pay_duty2(23,5,false, false));
assert(pay_duty2(55,100,false, false) == false );
assert(pay_duty2(55,805,false, false) == true);
assert(pay_duty2(35,205,true, false));
assert(pay_duty2(35,150,false, false) == false);
// my_pow
assert(my_pow(1, 0) == 1);
assert(my_pow(6, 2) == 36);
//count_digits
assert(count_digits(1234) == 4);
assert(count_digits(15) == 2);
assert(count_digits(5) == 1);
//is-prime
assert(is_prime(3));
assert(is_prime(13));
assert(is_prime(12) == false);
assert(is_prime(39)== false);
assert(is_prime(37));
//fibonacci
assert(fibonacci(2) == 1);
assert(fibonacci(3) == 2);
assert(fibonacci(4) == 3);
assert(fibonacci(5) == 5);
assert(fibonacci(6) == 8);
//reverse-digits
assert(reverse_digits(7) == 7);
assert(reverse_digits(10) == 1);
assert(reverse_digits(0) == 0);
assert(reverse_digits(1100) == 11);
assert(reverse_digits(11530) == 3511);
//median3
assert(median3(1, 5, 7) == 5);
assert(median3(5, 1, 7) == 5);
assert(median3(5, 5, 7) == 5);
assert(median3(5, 5, 5) == 5);
assert(median3(-5, 5, 0) == 0);
assert(median3(-1, 8, 7) == 7);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool used[20] = {0};
int num[20] , path[20] , n;
int dfs(int index){
if(index == n - 1){
int left = 0 , right = 0;
for(int i = 0; i < n / 2; i++){
left += path[i] * (n / 2 - i);
right += path[i + n / 2] * (i + 1);
}
if(right == left){
for(int i = 0; i < n / 2; i++)
printf("%d " , path[i]);
printf("_^_");
for(int i = n / 2; i < n - 1; i++)
printf(" %d" , path[i]);
printf("\n");
return 1;
}
return 0;
}
for(int i = 0; i < n; i++){
if(!used[i]){
path[index] = num[i] , used[i] = 1;
if(dfs(index + 1))
return 1;
used[i] = 0;
}
}
return 0;
}
int main(){
while(scanf("%d" , &n) == 1){
for(int i = 0; i < n; i++)
scanf("%d" , &num[i]);
memset(used , 0 , sizeof(used));
if(!dfs(0))
printf("N\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
int kiem_tra(char n[600], int len){
int i, sum = 0;
if(n[0] != '8' || n[len - 1] != '8') return 0;
for(i = 0; i <= (len - 1)/2; i++){
if(n[i] != n[len - i - 1]) return 0;
}
for(i = 0; i < len; i++){
int temp = (int) n[i] - 48;
sum += temp;
}
if(sum % 10 != 0) return 0;
return 1;
}
void bai_lam(){
char n[600];
gets(n);
int len = strlen(n);
if(kiem_tra(n, len)) printf("YES\n");
else printf("NO\n");
}
int main(){
int a; scanf("%d", &a); getchar();
while(a--){
bai_lam();
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ncurses.h>
#include "fileParsing.h"
#include "roomHandling.h"
FILE* openThisFile(char *fileToOpen, char *action)
{
FILE* filePtr = NULL;
filePtr = fopen(fileToOpen, action); // Opens the file name passed in for t$
if (filePtr == NULL) // Error case if the file failed to open
{
printf("File failed to open properly!\n");
exit(1); // Exit the program
}
else // If the file opened
{
printf("File successfully opened!\n");
}
return filePtr;
}
RoomInfo** parseRoomFile(FILE* roomFile)
{
char fileText[150];
RoomInfo** room;
int roomNumber = 0;
int spaceCounterArray[6];
// char* ptr;
room = malloc(sizeof(RoomInfo*)*6); //malloc for 6 RoomInfo pointers
for (int i=0; i<6; i++) {
room[i] = malloc(sizeof(RoomInfo)); //malloc for 6 RoomInfo variables in an array
}
while(fgets(fileText, 150, roomFile) != NULL)
{
int spaceCounter = 0;
int length = strlen(fileText);
char* ptr;
//counts number of spaces
for(int i=0; i<=length; i++){
if (fileText[i] == ' ') {
spaceCounter++;
}
}
//parses the room dimensions and stores them in the struct variable
ptr = strtok(fileText,"X");
room[roomNumber]->height = atoi(ptr);
ptr = strtok(NULL, " ");
room[roomNumber]->width = atoi(ptr);
spaceCounterArray[roomNumber] = spaceCounter;
//dynamically mallocs for the array of strings in the struct
int j = 0;
ptr = strtok (NULL, " \n");
while(ptr != NULL) {
room[roomNumber]->other[j] = malloc(strlen(ptr) + 1);
strcpy(room[roomNumber]->other[j], ptr);
j++;
ptr = strtok (NULL, " \n");
}
roomNumber++;
}
//parses for the room's items and doors
char* dummyPtr;
char* dummyPtr2;
char* dummyPtr3;
for (int k=0; k<roomNumber; k++) {
int doorCounter = 0;
int itemCounter = 0;
for (int l=0; l<spaceCounterArray[k]; l++) { //loops for the number of things after the dimensions
//handles parsing for the doors
if (room[k]->other[l][0] == 'd'){
room[k]->doorWall[doorCounter] = room[k]->other[l][1];
dummyPtr = strtok(room[k]->other[l], "nsew");
if(dummyPtr) {
}
dummyPtr = strtok(NULL, "\0");
room[k]->doorPosition[doorCounter] = atoi(dummyPtr);
doorCounter++;
}
//handles parsing for the hero
else if (room[k]->other[l][0] == 'h') {
room[k]->itemVal[itemCounter] = '@';
room[0]->heroRoom = k+1;
dummyPtr = strtok(room[k]->other[l], "hzagGwWmeMp");
room[k]->itemY[itemCounter] = strtol(dummyPtr, &dummyPtr2, 10);
room[0]->heroYPos = room[k]->itemY[itemCounter];
dummyPtr3 = strtok(dummyPtr2, ",");
room[k]->itemX[itemCounter] = strtol(dummyPtr3, NULL, 10);
room[0]->heroXPos = room[k]->itemX[itemCounter];
itemCounter++;
}
//handles parsing for all items
else {
room[k]->itemVal[itemCounter] = room[k]->other[l][0];
dummyPtr = strtok(room[k]->other[l], "hzagGwWmeMp");
room[k]->itemY[itemCounter] = strtol(dummyPtr, &dummyPtr2, 10);
dummyPtr3 = strtok(dummyPtr2, ",");
room[k]->itemX[itemCounter] = strtol(dummyPtr3, NULL, 10);
itemCounter++;
}
}
}
return room;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
# include<windows.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int gotoxy(int x,int y)
{
COORD coord = {x,y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
void box(int,int);
int main(void){
/*int hight,width;
printf("enter the hight of your square: ");
scanf("%d",&hight);
printf("enter the width of your square: ");
scanf("%d",&width);*/
box(20,60);//box(hight,width)
getch();
}
void box(int x,int y)
{
int hight=x,width=y,startpointleft=1,top=1,i;
system("cls");
gotoxy(startpointleft,top);
printf("%c",218);
for(i=0;i<width-startpointleft-1;i++){
printf("%c",196);
}
printf("%c",191);
for(i=1;i<hight-top;i++)
{
gotoxy(startpointleft,top+i);printf("%c",179);
gotoxy(width,top+i);printf("%c",179);
}
gotoxy(startpointleft,hight);
printf("%c",192);
for(i=0;i<width-startpointleft-1;i++){
printf("%c",196);
}
printf("%c",217);
}
|
C
|
/*
* chiller_pump.c
*
* Created on: Aug 5, 2013
* Author: brad
*/
//-------------------------------------------------------------------------
// Included Libraries
//-------------------------------------------------------------------------
#include <stdint.h>
#include <stdio.h>
#include "stm32f10x.h"
#include "FreeRTOS.h"
#include "lcd.h"
#include "task.h"
#include "adc.h"
#include "leds.h"
#include "semphr.h"
#include "I2C-IO.h"
#include "chiller_pump.h"
#include "console.h"
#include "main.h"
ChillerPumpState_t ChillerPumpState = CHILLER_PUMP_STOPPED;
ChillerPumpState_t GetChillerPumpState(){
return ChillerPumpState;
}
void vChillerPumpInit(void){
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = CHILLER_PUMP_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;// Output - Push Pull
GPIO_Init( CHILLER_PUMP_PORT, &GPIO_InitStructure );
GPIO_ResetBits(CHILLER_PUMP_PORT, CHILLER_PUMP_PIN); //pull low
}
void vChillerPump(ChillerPumpCommand command )
{
if (command == START_CHILLER_PUMP && ChillerPumpState != CHILLER_PUMP_PUMPING)
{
vConsolePrint("Starting Chiller Pump\r\n\0");
GPIO_SetBits(CHILLER_PUMP_PORT, CHILLER_PUMP_PIN);
ChillerPumpState = CHILLER_PUMP_PUMPING;
}
else if (command == STOP_CHILLER_PUMP && ChillerPumpState != CHILLER_PUMP_STOPPED)
{
vConsolePrint("Stopping Chiller Pump\r\n\0");
GPIO_ResetBits(CHILLER_PUMP_PORT, CHILLER_PUMP_PIN); //pull low
ChillerPumpState = CHILLER_PUMP_STOPPED;
}
}
void vToggleChillerPump()
{
if(ChillerPumpState != CHILLER_PUMP_PUMPING)
{
//printf("MPStart\r\n");
vChillerPump(START_CHILLER_PUMP);
}
else
// printf("MPStop\r\n");
vChillerPump(STOP_CHILLER_PUMP);
}
|
C
|
#include <stdio.h>
int main()
{
int i,b,c;
b=0;
scanf("%d",&i);
c=i-1;
int arr[i];
while(b<i){
scanf("%d",&arr[b]);
b++;
}
while(c>=0){
printf("%d\n",arr[c]);
c=c-1;
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void){
int b,h;
printf("Insira o valor da base do triangulo: ");
scanf("%d",&b);
printf("Insira a altura do triangulo: ");
scanf("%d",&h);
system ("cls");
printf("\nPara o triangulo de base %d e altura %d\n",b,h);
printf("A area equivale a %d.\n\n\n\n\n\n\n",b*h/2);
return 0;
}
|
C
|
#include "types.h"
#include "x86.h"
#define SECTSIZE 512
int
main(void)
{
void *dst = (void *)0x7C00;
uint32_t offset = 0;
// wait for disk to be ready
while ((inb(0x1F7) & 0xC0) != 0x40) { }
// ref. "7.35 READ SECTOR(S)" in [ATA8-ACS]
outb(0x1F2, 1); // sector count = 1
outb(0x1F3, offset); // LBA low : LBA28 [ 0: 7]
outb(0x1F4, offset >> 8); // LBA mid : LBA28 [ 8:15]
outb(0x1F5, offset >> 16); // LBA high: LBA28 [16:23]
// NOTE. 0x1F6:
// Bit 7: obsolete in LBA, 1 in CHS
// Bit 6: mode, 1=LBA, 0=CHS
// Bit 5: obsolete in LBA, 1 in CHS
// Bit 4: dev, 0=master, 1=slave
// Bit 3-0: [24:27] in LSB, #head in CHS
outb(0x1F6, (offset >> 24) | 0xE0); // Dev: LBA28 [24:27], LBA=1, master
outb(0x1F7, 0x20); // cmd 0x20 - read sectors
// wait for disk to be ready
while ((inb(0x1F7) & 0xC0) != 0x40) { }
// read a sector from a data port
insl(0x1F0, dst, SECTSIZE/4);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct graphNode* graphPointer;
typedef struct graphNode {
int data1;
int data2;
graphPointer link1;
graphPointer link2;
}graphNode;
graphPointer* adjList; // Ҵ
graphPointer createEdge(int ver1, int ver2); // create the edge node
void addEdge(graphPointer temp, int ver1, int ver2);
void printMultilist(int numVertex, int choice); // choice: 0 or 1
int main()
{
int vertex, edge;
int a, b;
int i;
FILE* fp = fopen("input.txt", "r");
fscanf(fp, "%d", &vertex);
fscanf(fp, "%d", &edge);
adjList = malloc(sizeof(graphPointer)*vertex);
for (i = 0; i < vertex; i++)
{
adjList[i] = NULL;
}//
graphPointer temp;
//while(!feof(fp))
for (i = 0; i < edge; i++)
{
fscanf(fp, "%d %d", &a, &b);
temp = createEdge(a, b);
addEdge(temp, a, b);
}
for(int j = 0; j < vertex; j++)
printMultilist(j, 0);
printf("\n");
//
for(int j = 0; j < vertex; j++)
printMultilist(j, 1);
printf("\n");
fclose(fp);
return 0;
}
graphPointer createEdge(int a, int b)
{
graphPointer node1;
node1 = malloc(sizeof(graphNode));
node1->data1 = a;
node1->data2 = b;
node1->link1 = NULL; //ָ returnҶ - addEgde Լ ȿ óָ
node1->link2 = NULL;
return node1;
}
void addEdge(graphPointer temp, int a, int b)
{
graphPointer cur;
if (adjList[a] == NULL) adjList[a] = temp; //ù
else
{
cur = adjList[a]; //߿!! ǵ ȵ
while (1)
{
if (cur->data1 == a)
{
if (cur->link1 == NULL) {cur->link1 = temp; break;}
else cur = cur->link1;
}
else if(cur->data2 == a)
{
if (cur->link2 == NULL) {cur->link2 = temp; break;}
else cur = cur->link2;
}
else break;
}
}
// bʿ
if (adjList[b] == NULL) adjList[b] = temp;
else
{
cur = adjList[b];
while (1)
{
if (cur->data1 == b)
{
if (cur->link1 == NULL) {cur->link1 = temp; break;}
else cur = cur->link1;
}
else if (cur->data2 == b)
{
if (cur->link2 == NULL) {cur->link2 = temp; break;}
else cur = cur->link2;
}
else break;
}
}
}
void printMultilist(int numVertex, int choice)
{
graphPointer cur = adjList[numVertex];
printf("adjList[%d]:", numVertex);
if (choice == 0)
{
while (cur != NULL)
{
printf(" (%d, %d)", cur->data1, cur->data2);
if (cur->data1 == numVertex)
cur = cur->link1;
else if (cur->data2 == numVertex)
cur = cur->link2;
}
printf("\n");
}
else if (choice == 1) //
{
while (cur != NULL)
{
if (cur->data1 == numVertex)
{
printf(" (%d, %d)", cur->data1, cur->data2);
cur = cur->link1;
}
else if (cur->data2 == numVertex)
{
printf(" (%d, %d)", cur->data2, cur->data1);
cur = cur->link2;
}
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
#include <tinyara/gpio.h>
#include <tinyara/config.h>
#include <time.h>
#include <string.h>
#define GPIO_FUNC_SHIFT 13
#define GPIO_INPUT (0x0 << GPIO_FUNC_SHIFT)
#define GPIO_OUTPUT (0x1 << GPIO_FUNC_SHIFT)
#define GPIO_PORT_SHIFT 3
#define GPIO_PORTG2 (0x6 << GPIO_PORT_SHIFT)
#define GPIO_PIN_SHIFT 0
#define GPIO_PIN6 (0x6 << GPIO_PIN_SHIFT)
#define GPIO_PIN7 (0x7 << GPIO_PIN_SHIFT)
#define GPIO_PUPD_SHIFT 11
#define GPIO_PULLDOWN (0x1 << GPIO_PUPD_SHIFT)
#define GPIO_PULLUP (0x3 << GPIO_PUPD_SHIFT)
void blink_led(int repeat, int duration);
uint32_t pir_signal;
uint32_t led;
int main(int argc, FAR char *argv[]) {
struct timespec currentTime;
struct tm tm_now;
char buf[32];
size_t sz_buf = sizeof(buf);
int pirState = 0;
pir_signal = GPIO_INPUT | GPIO_PORTG2 | GPIO_PIN6 | GPIO_PULLDOWN;
led = GPIO_OUTPUT | GPIO_PORTG2 | GPIO_PIN7 | GPIO_PULLDOWN;
s5j_configgpio(pir_signal);
s5j_configgpio(led);
printf("Waiting for Motion Sensor Initialized.\n");
up_mdelay(2000);
printf("Detecting Motion...\n");
blink_led(2, 200);
while (1) {
if (s5j_gpioread(pir_signal) == 1) {
s5j_gpiowrite(led, 1);
if (pirState == 0) {
clock_gettime(CLOCK_REALTIME, ¤tTime);
localtime_r((time_t*)¤tTime.tv_sec, &tm_now);
strftime(buf, sz_buf, "%Y/%m/%d %H:%M:%S", &tm_now);
printf("Motion Started: %s\n", buf);
pirState = 1;
}
} else {
s5j_gpiowrite(led, 0);
if (pirState == 1) {
printf("Motion Ended!!\n");
pirState = 0;
}
}
}
return 0;
}
void blink_led(int repeat, int duration) {
int i;
for (i = 0; i < repeat; i++) {
s5j_gpiowrite(led, 1);
up_mdelay(duration);
s5j_gpiowrite(led, 0);
up_mdelay(duration);
}
}
|
C
|
#include <stdio.h>
#include <math.h>
int main(void){
float a, b, c, p, s, t;
scanf("%f%f%f", &a, &b, &c);
if(a > b && a > c){
p = a;
if(b > c){
s = b; t = c;
} else {
s = c; t = b;
}
}
if(b > a && b > c){
p = b;
if(a > c){
s = a; t = c;
} else {
s = c; t = b;
}
}
if(c > a && c > b){
p = c;
if(a > b){
s = a; t = b;
} else {
s = b; t = b;
}
}
printf("%.2f, %.2f, %.2f\n", truncf(t*100)/100, truncf(s*100)/100, truncf(p*100)/100);
return 0;
}
|
C
|
/* Sahaana Iyer
SE Computer
Batch B
8609*/
#include<stdio.h>
void sel(int[],int);
int main()
{
int a[10],n,i,j;
printf("Enter the number of elements - \n");
scanf("%d",&n);
printf("Enter the elements : \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sel(a,n);
printf("The elements in sorted order is : \n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
return 0;
}
void sel(int a[],int n)
{
int i,j,temp,min;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
}
/* OUTPUT :
Enter the number of elements -
5
Enter the elements :
24 33 19 45 13
The elements in sorted order is :
13 19 24 33 45 */
|
C
|
#include"header.h"
// in this file we handle echho command.
// not yet taken quotes and environment variables into consideration
ll ECHO(char **args)
{
// if no input is given after echo
if(args[1]==NULL)
{
printf("\n");
return 1;
}
char a[1000];
ll x= strlen(args[1]);
ll i=1, isenv=0;
// printf("%c\n",args[1][1] );
if(args[1][0]=='$')
{
isenv = 1;
}
if(isenv==0)
{
i=1;
// printing all arguments given back to the terminal
while(args[i]!=NULL)
{
printf("%s ",args[i] );
i++;
}
printf("\n");
return 1;
}
else
{
for(i=0; i<x-1; i++)
{
a[i]=args[1][i+1];
}
a[x]='\0';
if(getenv(a)==NULL)
{
perror("Not a env:");
done[0]=':';
done[1]='(';
return 0;
}
else
{
done[0]=':';
done[1]=')';
}
printf("%s\n",getenv(a));
return 1;
}
}
|
C
|
/*
The most basic AO application ordering routines. These store the
entire orderings on each processor.
*/
#include <../src/vec/is/ao/aoimpl.h> /*I "petscao.h" I*/
typedef struct {
PetscInt *app; /* app[i] is the partner for the ith PETSc slot */
PetscInt *petsc; /* petsc[j] is the partner for the jth app slot */
} AO_Basic;
/*
All processors have the same data so processor 1 prints it
*/
PetscErrorCode AOView_Basic(AO ao,PetscViewer viewer)
{
PetscErrorCode ierr;
PetscMPIInt rank;
PetscInt i;
AO_Basic *aobasic = (AO_Basic*)ao->data;
PetscBool iascii;
PetscFunctionBegin;
ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)ao),&rank);CHKERRQ(ierr);
if (!rank) {
ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
if (iascii) {
ierr = PetscViewerASCIIPrintf(viewer,"Number of elements in ordering %D\n",ao->N);CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, "PETSc->App App->PETSc\n");CHKERRQ(ierr);
for (i=0; i<ao->N; i++) {
ierr = PetscViewerASCIIPrintf(viewer,"%3D %3D %3D %3D\n",i,aobasic->app[i],i,aobasic->petsc[i]);CHKERRQ(ierr);
}
}
}
ierr = PetscViewerFlush(viewer);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode AODestroy_Basic(AO ao)
{
AO_Basic *aobasic = (AO_Basic*)ao->data;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscFree2(aobasic->app,aobasic->petsc);CHKERRQ(ierr);
ierr = PetscFree(aobasic);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode AOBasicGetIndices_Private(AO ao,PetscInt **app,PetscInt **petsc)
{
AO_Basic *basic = (AO_Basic*)ao->data;
PetscFunctionBegin;
if (app) *app = basic->app;
if (petsc) *petsc = basic->petsc;
PetscFunctionReturn(0);
}
PetscErrorCode AOPetscToApplication_Basic(AO ao,PetscInt n,PetscInt *ia)
{
PetscInt i,N=ao->N;
AO_Basic *aobasic = (AO_Basic*)ao->data;
PetscFunctionBegin;
for (i=0; i<n; i++) {
if (ia[i] >= 0 && ia[i] < N) {
ia[i] = aobasic->app[ia[i]];
} else {
ia[i] = -1;
}
}
PetscFunctionReturn(0);
}
PetscErrorCode AOApplicationToPetsc_Basic(AO ao,PetscInt n,PetscInt *ia)
{
PetscInt i,N=ao->N;
AO_Basic *aobasic = (AO_Basic*)ao->data;
PetscFunctionBegin;
for (i=0; i<n; i++) {
if (ia[i] >= 0 && ia[i] < N) {
ia[i] = aobasic->petsc[ia[i]];
} else {
ia[i] = -1;
}
}
PetscFunctionReturn(0);
}
PetscErrorCode AOPetscToApplicationPermuteInt_Basic(AO ao, PetscInt block, PetscInt *array)
{
AO_Basic *aobasic = (AO_Basic*) ao->data;
PetscInt *temp;
PetscInt i, j;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscMalloc1(ao->N*block, &temp);CHKERRQ(ierr);
for (i = 0; i < ao->N; i++) {
for (j = 0; j < block; j++) temp[i*block+j] = array[aobasic->petsc[i]*block+j];
}
ierr = PetscArraycpy(array, temp, ao->N*block);CHKERRQ(ierr);
ierr = PetscFree(temp);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode AOApplicationToPetscPermuteInt_Basic(AO ao, PetscInt block, PetscInt *array)
{
AO_Basic *aobasic = (AO_Basic*) ao->data;
PetscInt *temp;
PetscInt i, j;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscMalloc1(ao->N*block, &temp);CHKERRQ(ierr);
for (i = 0; i < ao->N; i++) {
for (j = 0; j < block; j++) temp[i*block+j] = array[aobasic->app[i]*block+j];
}
ierr = PetscArraycpy(array, temp, ao->N*block);CHKERRQ(ierr);
ierr = PetscFree(temp);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode AOPetscToApplicationPermuteReal_Basic(AO ao, PetscInt block, PetscReal *array)
{
AO_Basic *aobasic = (AO_Basic*) ao->data;
PetscReal *temp;
PetscInt i, j;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscMalloc1(ao->N*block, &temp);CHKERRQ(ierr);
for (i = 0; i < ao->N; i++) {
for (j = 0; j < block; j++) temp[i*block+j] = array[aobasic->petsc[i]*block+j];
}
ierr = PetscArraycpy(array, temp, ao->N*block);CHKERRQ(ierr);
ierr = PetscFree(temp);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode AOApplicationToPetscPermuteReal_Basic(AO ao, PetscInt block, PetscReal *array)
{
AO_Basic *aobasic = (AO_Basic*) ao->data;
PetscReal *temp;
PetscInt i, j;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscMalloc1(ao->N*block, &temp);CHKERRQ(ierr);
for (i = 0; i < ao->N; i++) {
for (j = 0; j < block; j++) temp[i*block+j] = array[aobasic->app[i]*block+j];
}
ierr = PetscArraycpy(array, temp, ao->N*block);CHKERRQ(ierr);
ierr = PetscFree(temp);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static struct _AOOps AOOps_Basic = {
AOView_Basic,
AODestroy_Basic,
AOPetscToApplication_Basic,
AOApplicationToPetsc_Basic,
AOPetscToApplicationPermuteInt_Basic,
AOApplicationToPetscPermuteInt_Basic,
AOPetscToApplicationPermuteReal_Basic,
AOApplicationToPetscPermuteReal_Basic
};
PETSC_EXTERN PetscErrorCode AOCreate_Basic(AO ao)
{
AO_Basic *aobasic;
PetscMPIInt size,rank,count,*lens,*disp;
PetscInt napp,*allpetsc,*allapp,ip,ia,N,i,*petsc=NULL,start;
PetscErrorCode ierr;
IS isapp=ao->isapp,ispetsc=ao->ispetsc;
MPI_Comm comm;
const PetscInt *myapp,*mypetsc=NULL;
PetscFunctionBegin;
/* create special struct aobasic */
ierr = PetscNewLog(ao,&aobasic);CHKERRQ(ierr);
ao->data = (void*) aobasic;
ierr = PetscMemcpy(ao->ops,&AOOps_Basic,sizeof(struct _AOOps));CHKERRQ(ierr);
ierr = PetscObjectChangeTypeName((PetscObject)ao,AOBASIC);CHKERRQ(ierr);
ierr = ISGetLocalSize(isapp,&napp);CHKERRQ(ierr);
ierr = ISGetIndices(isapp,&myapp);CHKERRQ(ierr);
ierr = PetscMPIIntCast(napp,&count);CHKERRQ(ierr);
/* transmit all lengths to all processors */
ierr = PetscObjectGetComm((PetscObject)isapp,&comm);CHKERRQ(ierr);
ierr = MPI_Comm_size(comm, &size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm, &rank);CHKERRQ(ierr);
ierr = PetscMalloc2(size, &lens,size,&disp);CHKERRQ(ierr);
ierr = MPI_Allgather(&count, 1, MPI_INT, lens, 1, MPI_INT, comm);CHKERRQ(ierr);
N = 0;
for (i = 0; i < size; i++) {
ierr = PetscMPIIntCast(N,disp+i);CHKERRQ(ierr); /* = sum(lens[j]), j< i */
N += lens[i];
}
ao->N = N;
ao->n = N;
/* If mypetsc is 0 then use "natural" numbering */
if (napp) {
if (!ispetsc) {
start = disp[rank];
ierr = PetscMalloc1(napp+1, &petsc);CHKERRQ(ierr);
for (i=0; i<napp; i++) petsc[i] = start + i;
} else {
ierr = ISGetIndices(ispetsc,&mypetsc);CHKERRQ(ierr);
petsc = (PetscInt*)mypetsc;
}
}
/* get all indices on all processors */
ierr = PetscMalloc2(N,&allpetsc,N,&allapp);CHKERRQ(ierr);
ierr = MPI_Allgatherv(petsc, count, MPIU_INT, allpetsc, lens, disp, MPIU_INT, comm);CHKERRQ(ierr);
ierr = MPI_Allgatherv((void*)myapp, count, MPIU_INT, allapp, lens, disp, MPIU_INT, comm);CHKERRQ(ierr);
ierr = PetscFree2(lens,disp);CHKERRQ(ierr);
#if defined(PETSC_USE_DEBUG)
{
PetscInt *sorted;
ierr = PetscMalloc1(N,&sorted);CHKERRQ(ierr);
ierr = PetscArraycpy(sorted,allpetsc,N);CHKERRQ(ierr);
ierr = PetscSortInt(N,sorted);CHKERRQ(ierr);
for (i=0; i<N; i++) {
if (sorted[i] != i) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"PETSc ordering requires a permutation of numbers 0 to N-1\n it is missing %D has %D",i,sorted[i]);
}
ierr = PetscArraycpy(sorted,allapp,N);CHKERRQ(ierr);
ierr = PetscSortInt(N,sorted);CHKERRQ(ierr);
for (i=0; i<N; i++) {
if (sorted[i] != i) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Application ordering requires a permutation of numbers 0 to N-1\n it is missing %D has %D",i,sorted[i]);
}
ierr = PetscFree(sorted);CHKERRQ(ierr);
}
#endif
/* generate a list of application and PETSc node numbers */
ierr = PetscCalloc2(N, &aobasic->app,N,&aobasic->petsc);CHKERRQ(ierr);
ierr = PetscLogObjectMemory((PetscObject)ao,2*N*sizeof(PetscInt));CHKERRQ(ierr);
for (i = 0; i < N; i++) {
ip = allpetsc[i];
ia = allapp[i];
/* check there are no duplicates */
if (aobasic->app[ip]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Duplicate in PETSc ordering at position %d. Already mapped to %d, not %d.", i, aobasic->app[ip]-1, ia);
aobasic->app[ip] = ia + 1;
if (aobasic->petsc[ia]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Duplicate in Application ordering at position %d. Already mapped to %d, not %d.", i, aobasic->petsc[ia]-1, ip);
aobasic->petsc[ia] = ip + 1;
}
if (napp && !mypetsc) {
ierr = PetscFree(petsc);CHKERRQ(ierr);
}
ierr = PetscFree2(allpetsc,allapp);CHKERRQ(ierr);
/* shift indices down by one */
for (i = 0; i < N; i++) {
aobasic->app[i]--;
aobasic->petsc[i]--;
}
ierr = ISRestoreIndices(isapp,&myapp);CHKERRQ(ierr);
if (napp) {
if (ispetsc) {
ierr = ISRestoreIndices(ispetsc,&mypetsc);CHKERRQ(ierr);
} else {
ierr = PetscFree(petsc);CHKERRQ(ierr);
}
}
PetscFunctionReturn(0);
}
/*@C
AOCreateBasic - Creates a basic application ordering using two integer arrays.
Collective
Input Parameters:
+ comm - MPI communicator that is to share AO
. napp - size of integer arrays
. myapp - integer array that defines an ordering
- mypetsc - integer array that defines another ordering (may be NULL to
indicate the natural ordering, that is 0,1,2,3,...)
Output Parameter:
. aoout - the new application ordering
Level: beginner
Notes:
the arrays myapp and mypetsc must contain the all the integers 0 to napp-1 with no duplicates; that is there cannot be any "holes"
in the indices. Use AOCreateMapping() or AOCreateMappingIS() if you wish to have "holes" in the indices.
.seealso: AOCreateBasicIS(), AODestroy(), AOPetscToApplication(), AOApplicationToPetsc()
@*/
PetscErrorCode AOCreateBasic(MPI_Comm comm,PetscInt napp,const PetscInt myapp[],const PetscInt mypetsc[],AO *aoout)
{
PetscErrorCode ierr;
IS isapp,ispetsc;
const PetscInt *app=myapp,*petsc=mypetsc;
PetscFunctionBegin;
ierr = ISCreateGeneral(comm,napp,app,PETSC_USE_POINTER,&isapp);CHKERRQ(ierr);
if (mypetsc) {
ierr = ISCreateGeneral(comm,napp,petsc,PETSC_USE_POINTER,&ispetsc);CHKERRQ(ierr);
} else {
ispetsc = NULL;
}
ierr = AOCreateBasicIS(isapp,ispetsc,aoout);CHKERRQ(ierr);
ierr = ISDestroy(&isapp);CHKERRQ(ierr);
if (mypetsc) {
ierr = ISDestroy(&ispetsc);CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
/*@C
AOCreateBasicIS - Creates a basic application ordering using two index sets.
Collective on IS
Input Parameters:
+ isapp - index set that defines an ordering
- ispetsc - index set that defines another ordering (may be NULL to use the
natural ordering)
Output Parameter:
. aoout - the new application ordering
Level: beginner
Notes:
the index sets isapp and ispetsc must contain the all the integers 0 to napp-1 (where napp is the length of the index sets) with no duplicates;
that is there cannot be any "holes"
.seealso: AOCreateBasic(), AODestroy()
@*/
PetscErrorCode AOCreateBasicIS(IS isapp,IS ispetsc,AO *aoout)
{
PetscErrorCode ierr;
MPI_Comm comm;
AO ao;
PetscFunctionBegin;
ierr = PetscObjectGetComm((PetscObject)isapp,&comm);CHKERRQ(ierr);
ierr = AOCreate(comm,&ao);CHKERRQ(ierr);
ierr = AOSetIS(ao,isapp,ispetsc);CHKERRQ(ierr);
ierr = AOSetType(ao,AOBASIC);CHKERRQ(ierr);
ierr = AOViewFromOptions(ao,NULL,"-ao_view");CHKERRQ(ierr);
*aoout = ao;
PetscFunctionReturn(0);
}
|
C
|
/*
* escritorFic.c
*
* Created on: 13/4/2019
* Author: ALUMNO
*/
#include <stdio.h>
#include <stdlib.h>
#include "meterBarco.h"
#include "interaccion.h"
#include "escritorFic.h"
#include <string.h>
void escribirAFichero(char * nom1, char * nom2, char * nomPartida, Barco * barcos1, Barco * barcos2, int opcion)
{
char letraCom=' ';
char letraFin=' ';
int tamanyo=0;
int numCom=0;
int numFin=0;
int num=opcion*2+3;
char * nomFichero = malloc(8*sizeof(char));
nomFichero= "HLF.txt";
FILE * fic;
fic=fopen(nomFichero, "w");
fprintf(fic, "%i\n", opcion);
fprintf(fic, "%s\n", nomPartida);
fprintf(fic, "%s\n", nom1);
fprintf(fic, "%s\n", nom2);
for(int i=0; i<num; i++)
{
letraCom = (barcos1+i)->letraCom;
letraFin = (barcos1+i)->letraFin;
tamanyo = (barcos1+i)->tamanyo;
numCom = (barcos1+i)->numCom;
numFin = (barcos1+i)->numFin;
fprintf(fic, "%c\n", letraCom);
fprintf(fic, "%c\n", letraFin);
fprintf(fic, "%i\n", tamanyo);
fprintf(fic, "%i\n", numCom);
fprintf(fic, "%i\n", numFin);
}
for(int i=0; i<num; i++)
{
letraCom = (barcos2+i)->letraCom;
letraFin = (barcos2+i)->letraFin;
tamanyo = (barcos2+i)->tamanyo;
numCom = (barcos2+i)->numCom;
numFin = (barcos2+i)->numFin;
fprintf(fic, "%c\n", letraCom);
fprintf(fic, "%c\n", letraFin);
fprintf(fic, "%i\n", tamanyo);
fprintf(fic, "%i\n", numCom);
fprintf(fic, "%i\n", numFin);
}
fclose(fic);
}
|
C
|
//
// main.c
// Pointers-2
//
// Created by Kris Evans on 13/08/2012.
// Copyright (c) 2012 Kris Evans. All rights reserved.
// Shamelessly copied from code at http://theocacao.com/document.page/234 and then modified
// with extra commenting for my own re-education
//
// Output (on OS X Mountain Lion) should be:
//
// value of number: 5
// value of &number: 0x7fff5fbff84c
// value of pointer: 0x7fff5fbff84c
// value of pointer's _target_: 5
#include <stdio.h>
int main(int argc, const char * argv[])
{
// declare an int variable and an int pointer variable
int number;
int* pointer;
// set a value for 'number'
number = 5;
// now link 'pointer' to 'number' by putting the 'addressof'
// operator (&) in front of the number variable
pointer = &number;
// print values of number and pointer
// note the %p marker is used for pointer and &number
// Print the value of number
printf( "value of number: %i\n", number );
// Print the address that number is stored at
printf( "value of &number: %p\n", &number );
// Print the address that number is stored at by way of the pointer
printf( "value of pointer: %p\n", pointer );
// print value of pointer's target (number) using
// the asterisk (*) operator
printf( "value of pointer's _target_: %i\n", *pointer );
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include "dlopen_lib.h"
int main(int argc, char **argv)
{
const char *lib = argc > 1 ? argv[1] : "./libfoo.so";
void *handle;
void (*function)();
const char *error;
handle = dlopen(lib, RTLD_NOW);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
function = dlsym(handle, "foo");
error = dlerror();
if (error) {
fputs(error, stderr);
exit(1);
}
(*function)();
dlclose(handle);
return 0;
}
|
C
|
#include "GLUE.h"
//========================================================================//
// I N T E R F A C E L O G I C //
//========================================================================//
// //
// This file contains all of the interface functionalities. You can //
// implement your custom interface application by writing code with //
// the DSPController API inside the two functions defined below. //
// //
//========================================================================//
//========================================================================//
// STEP 1 - Define the variables and symbols //
//========================================================================//
// //
// Define local and GLUE variables and give them initial values //
// //
//========================================================================//
// Defined symbols
#define DEFAULT_GLUE_VOLUME 0.5f
#define MAX_VOLUME 60
// Local variables
int volume = 30;
// GLUE variables
float GLUE_volume = DEFAULT_GLUE_VOLUME;
//========================================================================//
// STEP 2 - Initialize the interface and the data structures //
//========================================================================//
// //
// Initialize the DSPController with API functions and set up your //
// data structures. This function will be called once before the signal //
// processing starts. //
// //
//========================================================================//
void initInterface(void) {
DSPController_init( FS_48KHZ | ENCODER_VELOCITY_ON );
}
//========================================================================//
// STEP 3 - Write your interface logic //
//========================================================================//
// //
// With the DSPConroller API create an event based state machine that //
// interacts the user by processing the input events, and by displaying //
// data on the outputs (LCD/LED bars). //
// //
// You can update or read the GLUE variables here, to control the DSP //
// code or update the displays according to the audio input. //
// //
// This function will be called periodically from the main loop as a //
// low priority function, therefore you are free to put some processing //
// heavy code here (i.e. sprintf(), LCD handling API functions). //
// //
//========================================================================//
void updateInterface(void) {
int temp_volume = DSPController_get_encoder(3);
if(temp_volume != 0) {
volume += temp_volume;
if (volume < 0) volume = 0;
if (volume > MAX_VOLUME) volume = MAX_VOLUME;
GLUE_volume = (float)(volume)/(float)MAX_VOLUME;
}
DSPController_lcd_top("Bare minimum app");
DSPController_lcd_bottom("Volume [%02d]",volume);
}
|
C
|
#include <stdio.h>
#include <memory.h>
#include "sim4.h"
#include "sim4_test_commonCode.h"
int main()
{
int i;
#define COUNT 4
WORD badInstructions[COUNT];
WORD regs[34];
for (i=0; i<34; i++)
regs[i] = 0x01010101 * i;
badInstructions[0] = J_FORMAT(24, 0x3ffffff);
badInstructions[1] = I_FORMAT(60, 31,21, 0xabcd);
badInstructions[2] = R_FORMAT(14, 1,2,3, 19);
badInstructions[3] = R_FORMAT(47, 31,31,31, 31);
for (i=0; i<COUNT; i++)
{
InstructionFields fields;
CPUControl control;
memset(&fields, 0, sizeof(fields));
memset(&control, 0, sizeof(control));
extract_instructionFields(badInstructions[i], &fields);
WORD rsVal = regs[fields.rs];
WORD rtVal = regs[fields.rt];
int ok = fill_CPUControl(&fields, &control);
printf("Bad Instruction: 0x%04x_%04x\n",
(badInstructions[i] >> 16) & 0xffff,
badInstructions[i] & 0xffff);
dumpFields(&fields);
printf(" --\n");
if (ok == 0)
printf(" fill_CPUControl() returned 0, as expected.\n");
else
printf("*** fill_CPUControl() returned nonzero, even thoug the instruction was invalid! ***\n");
dumpControl(rsVal,rtVal, &control);
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
int main(){
double eps=0.000000000001;
double s1=0;
double s2;
int i=1;
do{
s2=s1;
s1=s1+1.0/(i*i);
i++;
}while (s1-s2>eps);
printf("Sn = %f \n",s1);
}
|
C
|
#include<stdio.h>
#include<cs50.h>
#include<math.h>
//int remainder(int , int)
/*int remainder(int num, int divident)
{
int rem;
rem = num - (num/divident)*divident;
return rem;
}*/
int main(void)
{
float change;
int numberOfCoins=0;
printf("O hai, ");
do
{
printf("how much change is owed?\n");
change = GetFloat();
}while(change<0);
change = change*100;
//printf("%f\n", change);
change = round(change);
//printf("%f\n", change);
int changeUseForCalc;
changeUseForCalc = (int) change;
numberOfCoins = numberOfCoins + changeUseForCalc/25;
changeUseForCalc = changeUseForCalc%25;
numberOfCoins = numberOfCoins + changeUseForCalc/10;
changeUseForCalc = changeUseForCalc%10;
numberOfCoins = numberOfCoins + changeUseForCalc/5;
changeUseForCalc = changeUseForCalc%5;
numberOfCoins = numberOfCoins + changeUseForCalc;
printf("%d\n", numberOfCoins);
}
|
C
|
/*
* Paul Rafferty 2019
*
* The drawing surface
*/
#include <stdio.h>
#include <graphics/canvas.h>
#include <graphics/color.h>
#include <util/mem.h>
#include <util/log.h>
/*
* Create a new canvas, every color will be initialized to (0, 0, 0)
*/
struct canvas canvas_new(const int w, const int h)
{
struct canvas c = {w, h, NULL};
c.pixels = (struct color *)mem_alloc(w * h * sizeof(struct color));
int i;
for (i = 0; i < w * h; i++) {
c.pixels[i] = color_new(0.0f, 0.0f, 0.0f);
}
return c;
}
/*
* Print the contents of a canvas, for testing purposes
*/
void canvas_print(struct canvas c)
{
int i;
for (i = 0; i < c.w * c.h; i++) {
color_print(c.pixels[i]);
if (i % c.w == c.w - 1) {
fprintf(stdout, "\n");
} else {
fprintf(stdout, " ");
}
}
}
/*
* Check if a pixel is on the surface of the canvas, checks both x and y
* coords separately rather than just checking buffer index
*/
int _within_bounds(struct canvas c, int x, int y)
{
if (x < 0 || x >= c.w || y < 0 || y >= c.h) {
log_err("canvas - out of bounds pixel access: (%d, %d)", x, y);
return 0;
}
return 1;
}
/*
* Get the value of a pixel at a given position on the canvas
* Returns (0.0f, 0.0f, 0.0f) on failure
*/
struct color canvas_read_pixel(struct canvas c, int x, int y)
{
if(!_within_bounds(c, x, y)) {
return color_new(0.0f, 0.0f, 0.0f);
}
return c.pixels[y * c.w + x];
}
/*
* Write the given color to the given coordinates, returns 1 if successful,
* 0 otherwise
*/
const int canvas_write_pixel(struct canvas canvas, int x, int y, struct color col)
{
if(!_within_bounds(canvas, x, y)) {
return 0;
}
canvas.pixels[y * canvas.w + x] = col;
return 1;
}
/*
* blit an area of one canvas onto another, adding the colours together
*/
void canvas_blit_add(struct canvas dest, struct canvas source,
int dx, int dy, int sx, int sy, int sw, int sh)
{
int x, y;
struct color newcol;
for (x = 0; x < sw; x++) {
for (y = 0; y < sh; y++) {
newcol = color_add(canvas_read_pixel(dest, dx+x, dy+y),
canvas_read_pixel(source, sx+x, sy+y));
canvas_write_pixel(dest, dx+x, dy+y, newcol);
}
}
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
int main(void)
{
int a, b,c;
printf("JTӾƨåΪŮj}:");
scanf("%d %d %d",&a,&b,&c);
if (a>b)
{
if(a>c)
printf("̤jȬ:%d\n",a);
else
printf("̤jȬ:%d\n",c);
}
else
{
if(b>c)
printf("̤jȬ:%d\n",b);
else
printf("̤jȬ:%d\n",c);
}
if(a<b)
{
if(a<c)
printf("̤pȬ:%d\n",a);
else
printf("̤pȬ:%d\n",c);
}
else
{
if(b<c)
printf("̤pȬ:%d\n",b);
else
printf("̤pȬ:%d\n",c);
}
//system("pause");
return 0;
}
|
C
|
// The input consists of five valid character sets in the Base64 alphabet,
// which we need to map back to the 6-bit values they represent.
// There are three ranges, two singles, and then there's the rest.
//
// # From To LUT Characters
// 1 [0..42] [255] #1 invalid input
// 2 [43] [62] #1 +
// 3 [44..46] [255] #1 invalid input
// 4 [47] [63] #1 /
// 5 [48..57] [52..61] #1 0..9
// 6 [58..63] [255] #1 invalid input
// 7 [64] [255] #2 invalid input
// 8 [65..90] [0..25] #2 A..Z
// 9 [91..96] [255] #2 invalid input
// 10 [97..122] [26..51] #2 a..z
// 11 [123..126] [255] #2 invalid input
// (12) Everything else => invalid input
// The first LUT will use the VTBL instruction (out of range indices are set to
// 0 in destination).
static const uint8_t dec_lut1[] = {
255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U,
255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U,
255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 62U, 255U, 255U, 255U, 63U,
52U, 53U, 54U, 55U, 56U, 57U, 58U, 59U, 60U, 61U, 255U, 255U, 255U, 255U, 255U, 255U,
};
// The second LUT will use the VTBX instruction (out of range indices will be
// unchanged in destination). Input [64..126] will be mapped to index [1..63]
// in this LUT. Index 0 means that value comes from LUT #1.
static const uint8_t dec_lut2[] = {
0U, 255U, 0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 9U, 10U, 11U, 12U, 13U,
14U, 15U, 16U, 17U, 18U, 19U, 20U, 21U, 22U, 23U, 24U, 25U, 255U, 255U, 255U, 255U,
255U, 255U, 26U, 27U, 28U, 29U, 30U, 31U, 32U, 33U, 34U, 35U, 36U, 37U, 38U, 39U,
40U, 41U, 42U, 43U, 44U, 45U, 46U, 47U, 48U, 49U, 50U, 51U, 255U, 255U, 255U, 255U,
};
// All input values in range for the first look-up will be 0U in the second
// look-up result. All input values out of range for the first look-up will be
// 0U in the first look-up result. Thus, the two results can be ORed without
// conflicts.
//
// Invalid characters that are in the valid range for either look-up will be
// set to 255U in the combined result. Other invalid characters will just be
// passed through with the second look-up result (using the VTBX instruction).
// Since the second LUT is 64 bytes, those passed-through values are guaranteed
// to have a value greater than 63U. Therefore, valid characters will be mapped
// to the valid [0..63] range and all invalid characters will be mapped to
// values greater than 63.
static inline void
dec_loop_neon64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)
{
if (*slen < 64) {
return;
}
// Process blocks of 64 bytes per round. Unlike the SSE codecs, no
// extra trailing zero bytes are written, so it is not necessary to
// reserve extra input bytes:
size_t rounds = *slen / 64;
*slen -= rounds * 64; // 64 bytes consumed per round
*olen += rounds * 48; // 48 bytes produced per round
const uint8x16x4_t tbl_dec1 = load_64byte_table(dec_lut1);
const uint8x16x4_t tbl_dec2 = load_64byte_table(dec_lut2);
do {
const uint8x16_t offset = vdupq_n_u8(63U);
uint8x16x4_t dec1, dec2;
uint8x16x3_t dec;
// Load 64 bytes and deinterleave:
uint8x16x4_t str = vld4q_u8((uint8_t *) *s);
// Get indices for second LUT:
dec2.val[0] = vqsubq_u8(str.val[0], offset);
dec2.val[1] = vqsubq_u8(str.val[1], offset);
dec2.val[2] = vqsubq_u8(str.val[2], offset);
dec2.val[3] = vqsubq_u8(str.val[3], offset);
// Get values from first LUT:
dec1.val[0] = vqtbl4q_u8(tbl_dec1, str.val[0]);
dec1.val[1] = vqtbl4q_u8(tbl_dec1, str.val[1]);
dec1.val[2] = vqtbl4q_u8(tbl_dec1, str.val[2]);
dec1.val[3] = vqtbl4q_u8(tbl_dec1, str.val[3]);
// Get values from second LUT:
dec2.val[0] = vqtbx4q_u8(dec2.val[0], tbl_dec2, dec2.val[0]);
dec2.val[1] = vqtbx4q_u8(dec2.val[1], tbl_dec2, dec2.val[1]);
dec2.val[2] = vqtbx4q_u8(dec2.val[2], tbl_dec2, dec2.val[2]);
dec2.val[3] = vqtbx4q_u8(dec2.val[3], tbl_dec2, dec2.val[3]);
// Get final values:
str.val[0] = vorrq_u8(dec1.val[0], dec2.val[0]);
str.val[1] = vorrq_u8(dec1.val[1], dec2.val[1]);
str.val[2] = vorrq_u8(dec1.val[2], dec2.val[2]);
str.val[3] = vorrq_u8(dec1.val[3], dec2.val[3]);
// Check for invalid input, any value larger than 63:
const uint8x16_t classified
= vcgtq_u8(str.val[0], vdupq_n_u8(63))
| vcgtq_u8(str.val[1], vdupq_n_u8(63))
| vcgtq_u8(str.val[2], vdupq_n_u8(63))
| vcgtq_u8(str.val[3], vdupq_n_u8(63));
// Check that all bits are zero:
if (vmaxvq_u8(classified) != 0U) {
break;
}
// Compress four bytes into three:
dec.val[0] = vshlq_n_u8(str.val[0], 2) | vshrq_n_u8(str.val[1], 4);
dec.val[1] = vshlq_n_u8(str.val[1], 4) | vshrq_n_u8(str.val[2], 2);
dec.val[2] = vshlq_n_u8(str.val[2], 6) | str.val[3];
// Interleave and store decoded result:
vst3q_u8((uint8_t *) *o, dec);
*s += 64;
*o += 48;
} while (--rounds > 0);
// Adjust for any rounds that were skipped:
*slen += rounds * 64;
*olen -= rounds * 48;
}
|
C
|
# include <stdio.h>
# include <time.h>
int fib(int n){
switch(n){
case 0: return 0;
case 1: return 1;
default: return fib(n-2)+fib(n-1);
}
}
int main(void){
clock_t c_start, c_end;
int n = 10;
c_start = clock();
printf("F(%d)=%d\n", n, fib(n));
c_end = clock();
printf("time:%f\n", (double)(c_end-c_start));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
size_t maxSeq(int * array, size_t n);
int main (void){
int arr[4] = {1,3,3,4};
size_t n = maxSeq(arr,4);
if(n!=2) return EXIT_FAILURE;
int arr1[6] = {1,2,-3,4,5,9};
size_t n1 = maxSeq(arr1,6);
if(n1!=4) return EXIT_FAILURE;
int arr2[4] = {5,4,2,0};
size_t n2 = maxSeq(arr2,4);
if(n2!=1) return EXIT_FAILURE;
int arr3[0];
size_t n3=maxSeq(arr3,0);
if(n3!=0) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
|
C
|
/* ImageToString.c
* Copyright (C) 2020 nstavr04 mvasil17
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License.
*/
/**
* @file ImageToString.c
* @brief The class that decodes an encrypted message thats in an image back to its .txt format
*
* @author nstavr04
* @bug No known bugs.
*/
#include "bmp.h"
#include "bmplib.h"
void ImageToString(unsigned char *bitmapData, BITMAPFILEHEADER *bitmapFileHeader, BITMAPINFOHEADER *bitmapInfoHeader) {
// File "outputText.txt" Where we will write the text back
FILE *fp = NULL;
fp = fopen("outputText", "w");
if (fp == NULL) {
printf("unable to open");
exit(-1);
}
char curChar;
int number1 = 0;
int number2 = 0;
int number3 = 0;
int number4 = 0;
int number5 = 0;
int number6 = 0;
int number7 = 0;
int number8 = 0;
//Proceed pixel by pixel. Every 8 pixels we got a char
for (int i = 0; i < bitmapInfoHeader->biSizeImage; i += 24) {
number1 = ((bitmapData[i]));
number2 = ((bitmapData[i + 3]) >> 1);
number3 = ((bitmapData[i + 6]) >> 2);
number4 = ((bitmapData[i + 9]) >> 3);
number5 = ((bitmapData[i + 12]) >> 4);
number6 = ((bitmapData[i + 15]) >> 5);
number7 = ((bitmapData[i + 18]) >> 6);
number8 = ((bitmapData[i + 21]) >> 7);
//Create each char by adding the 8 pixels of the image
curChar = number1 + number2 + number3 + number4 + number5 + number6 + number7 + number8;
//Put the character into the file
fprintf(fp, "%c", curChar);
}
fclose(fp);
}
#ifdef ImageToStringDEBUG
int main(int argc, char *argv[]) {
unsigned char *bitmapData;
BITMAPINFOHEADER bitmapInfoHeader;
BITMAPFILEHEADER bitmapFileHeader;
//Save the data of the image in bitmapData
bitmapData = LoadBitmapFile(argv[2], &bitmapFileHeader, &bitmapInfoHeader);
ImageToString(bitmapData,&bitmapFileHeader,&bitmapInfoHeader);
}
#endif
|
C
|
struct foo
{
int a;
int b;
};
struct foo s1 = { 5, 7 };
struct foo s2;
void
bar()
{
struct foo s3;
s2.b = (s3 = s1).a;
s1.a = s2.b;
}
|
C
|
/*
* meta_pointer.c
* Copyright (C) 2014 jaidevd <deshpande.jaidev@gmail.com>
*
* Distributed under terms of the MIT license.
*/
#include <stdio.h>
int main()
{
float x, y;
long int i,j;
char *letter, *course[3], **marker;
course[0] = "Numerical Methods";
course[1] = "and programming";
marker = &course[1];
printf("%s %s\n", course[0], *marker);
marker--;
printf("%s %s\n", course[0], *marker);
marker++;
for (i=0;i<13;i++){
printf("%ld %c\n",i,*(*marker)++);
}
}
|
C
|
#ifndef SERVICE_H_INCLUDED
#define SERVICE_H_INCLUDED
#include "types.h"
#include <math.h>
inline double pi() { return 3.1415926535F; }
// Функция максимума (целочисленная)
inline int max(int a, int b) { return ((a < b) ? b : a); }
// Функция максимума (дробная)
inline double max(double a, double b) { return ((a < b) ? b : a); }
//Функция минимума (дробная)
inline double min(double a, double b) { return ((a > b) ? b : a); }
// Функция минимума (целочисленная)
inline int min(int a, int b) { return ((a > b) ? b : a); }
//Функция модуля (целочисленная)
inline int abs(int a) { return ((a < 0) ? -a : a); }
//Функция модуля (дробная)
//inline double abs(double a) { return ((a < 0) ? -a : a);}
// Логистическая функция (усеченная, всегда положительная)
inline double tansig(double x) { return ( 1/ (1 + exp(-2*x)) ); }
// Стандартная логистическая функция
inline double tansig_standart(double x) { return (2/(1+exp(-2*x)) - 1); }
// Процедура перевода десятичного числа в двоичное
void DecToBin(int DecNumber, int* BinNumber, int BinResolution);
// Процедура перевода двоичного числа в десятичное
int BinToDec(int* BinNumber, int BinResolution);
// Процедура инвертирования двоичного числа
void InvertBin(int* BinNumber, int BinResolution);
// Процедура конвертирования десятичного числа в шестнадцатеричное (символьное, так что в старших разрядах - в начале массива - могут быть нули)
void DecToHex(int DecNumber, char* HexNumber, int HexResolution);
// Сортировка методом пузырька
void BubbleSort(int* NumbersArray, int NumbersQuantity);
// Сортировка методом пузырька (дробная)
void BubbleSortdouble(double* NumbersArray, int NumbersQuantity);
// Функция генерации псеводослучайного равномерно распределенного числа (куски интервалов не включаются, только если указано)
double UniformDistribution(double A, double B, bool include_start = true, bool include_end = true);
// Функция генерации псевдослучайного равномерно распределенного дискретной величины (куски интервалов включаются)
int UniformDiscreteDistribution(int A, int B);
// Функция генерация псевдослучайного нормально распределенного числа
double NormalDistribution(double Mean, double Variance);
// Функция генерации неповторяющейся последовательности случайных чисел в заданном дипазоне
void GenerateRandomNumbers(int FirstNumber, int LastNumber, int Quantity, int* NumbersSequence);
// Получение полного пути к файлу среды
void GetEnvironmentFilename(char* EnvironmentFilename, char* EnvironmentDirectory, int EnvironmentNumber);
// Получение полного пути к файлу результатов
void GetResultsFilename(char* ResultsFilename, TRunSettings* RunSettings, TModeSettings* ModeSettings, char* ResultsDirectory, bool EnvironmentStability);
// Получение полного пути к файлу с гистограммами
void GetHistogramFilename(char* HistogramFilename, TRunSettings* RunSettings, TModeSettings* ModeSettings, char* ResultsDirectory, bool EnvironmentStability);
// Получение полного пути к файлу лучшей популяции
void GetBestPopulationFilename(char* BestPopulationFilename, TRunSettings* RunSettings, TModeSettings* ModeSettings, char* ResultsDirectory, bool EnvironmentStability);
// Получение полного пути к файлу с лучшими агентами в популяциях
void GetBestAgentFilename(char* BestAgentFilename, TRunSettings* RunSettings, TModeSettings* ModeSettings, char* ResultsDirectory, bool EnvironmentStability);
// Получение полного пути к файлу общего отчета по средам
void GetFullResultFilename(char* ResultFullFilename, TRunSettings* RunSettings, int FirstTry, int LastTry, TModeSettings* ModeSettings, char* ResultsDirectory, bool EnvironmentStability);
#endif // SERVICE_H_INCLUDED
|
C
|
#include <stdio.h>
#include <math.h>
/* Esempio di funzione ricorsiva: il fattoriale */
int fattoriale (int n){
int fatt;
if(n<0){
printf("Errore di Input: inserisci un numero non negativo\n");
}else{
if(n==0){
fatt=1;
}else{
fatt=n*fattoriale(n-1);
}
}
return fatt;
}
int main(){
int n;
puts("Inserisci un numero intero non negativo: ");
scanf("%i",&n);
printf("Il fattoriale del numero inserito è %i\n",fattoriale(n));
return 0;
}
|
C
|
/**********************************************************
* Programmer: Garett Pascual-Folster *
* Class: CptS 122, Spring, 2020; Lab Section 4 *
* Programming Assignment: PA1 *
* Date: January 20, 2020 *
* Description: This program works with fitbit data *
**********************************************************/
#include "fitbit.h"
int main(void)
{
FitbitData userData[_MINUTES_PER_DAY] = {"", "", 0.0, 0.0, 0, 0, 0, NONE};
FILE *fitbit_data = fopen("FitbitData.csv", "r");
double calories_t, distance_t;
unsigned int floors_t, heartR_t, steps_t, max_steps;
char startTime[9], endTime[9];
if (fitbit_data == NULL)
{ // check if file exists
printf("File failed to open\n");
exit(-1);
}
// Reading each record into fitbit_data
read_data(userData, fitbit_data);
fclose(fitbit_data);
// calculate total
calc_total(userData, &calories_t, &distance_t,
&floors_t, &heartR_t, &steps_t);
// average heart rate over the day
double avg_heartR = (double)heartR_t / _MINUTES_PER_DAY;
// get maximum steps in a minute
max_steps = get_max_steps(userData);
// get poorest sleep range
poorest_sleepRange(userData, startTime, endTime);
// write results
FILE *results = fopen("Results.csv", "w");
fprintf(results, "Total Calories, Total Distance, Total Floors, Total Steps, Avg Heartrate, Max Steps, Sleep\n");
fprintf(results, "%lf, %lf, %d, %d, %lf, %d, %s:%s\n",
calories_t, distance_t, floors_t, steps_t, avg_heartR, max_steps, startTime, endTime);
fclose(results);
printf("Finished Execution\n");
return 0;
}
|
C
|
#pragma once
/*
https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
https://github.com/sol-prog/ansi-escape-codes-windows-posix-terminals-c-programming-examples/blob/master/ansi_escapes.h
https://bluesock.org/~willkg/dev/ansi.html
http://ascii-table.com/ansi-escape-sequences.php
https://en.wikipedia.org/wiki/ANSI_escape_code
https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences
https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html
*/
#include "stdio.h"
#include "stdarg.h"
#include "usart.h"
#include "string.h"
#define UART_HANDLE &huart2
#define DYN_BUFFER_SIZE 256
enum ColorCodes
{
T_Black,
T_Red,
T_Green,
T_Yellow,
T_Blue,
T_Magenta,
T_Cyan,
T_White,
T_Default
};
static inline void println(const char *format, ...)
{
char buffer[DYN_BUFFER_SIZE];
va_list args;
va_start(args, format);
int length = vsprintf(buffer, format, args);
if (length >= 0)
{
strcat(buffer, "\r\n");
HAL_UART_Transmit(UART_HANDLE, (uint8_t *)buffer, strlen(buffer), HAL_MAX_DELAY);
}
va_end(args);
}
static inline void print(const char *format, ...)
{
char buffer[DYN_BUFFER_SIZE];
va_list args;
va_start(args, format);
int length = vsprintf(buffer, format, args);
if (length >= 0)
{
HAL_UART_Transmit(UART_HANDLE, (uint8_t *)buffer, length, HAL_MAX_DELAY);
}
va_end(args);
}
static inline void t_clear(void)
{
print("\e[1J\e[3J\e[H");
}
static inline void t_report(int bg, int fg, const char *format, ...)
{
int fg_code = fg == T_Default ? 0 : fg + 30;
int bg_code = bg == T_Default ? 0 : bg + 40;
print("\e[%d;%dm", fg_code, bg_code);
char buffer[DYN_BUFFER_SIZE];
va_list args;
va_start(args, format);
int length = vsprintf(buffer, format, args);
if (length >= 0)
{
strcat(buffer, "\e[m\r\n");
HAL_UART_Transmit(UART_HANDLE, (uint8_t *)buffer, strlen(buffer), HAL_MAX_DELAY);
}
va_end(args);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define VMIN 5
#define VMAX 30
struct T_Case
{
int x;
int y;
};
typedef struct T_Case T_Case; //on lui dit de remplacer "struct T_Case" par "T_Case"
typedef T_Case *T_Tab_Case;
int Existe(T_Tab_Case tab, int taille, T_Case valeur)
{
int i;
for (i = 0; i < taille; i++)
if (tab[i].x == valeur.x && tab[i].y == valeur.y)
return 1;
return 0;
}
void Voisines(T_Case pion, T_Tab_Case ban, int nban, int ncol, int nlig, T_Tab_Case casesVoisines, int *nVoisines)
{
T_Case aTester;
aTester.x = pion.x + 1;
aTester.y = pion.y;
*nVoisines = 0;
if (!Existe(ban, nban, aTester) && aTester.x < ncol)
{
casesVoisines[*nVoisines] = aTester;
(*nVoisines)++;
aTester.x++;
if (!Existe(ban, nban, aTester) && aTester.x < ncol)
{
casesVoisines[*nVoisines] = aTester;
(*nVoisines)++;
}
}
aTester.x = pion.x;
aTester.y = pion.y + 1;
if (!Existe(ban, nban, aTester) && aTester.y < nlig)
{
casesVoisines[*nVoisines] = aTester;
(*nVoisines)++;
aTester.y++;
if (!Existe(ban, nban, aTester) && aTester.y < nlig)
{
casesVoisines[*nVoisines] = aTester;
(*nVoisines)++;
}
}
}
void Calcul_Nimbers(int nim[][VMAX], int nlig, int ncol) //Remplir la table nim avant la partie
{
int x, y;
int nimberDuBas = 0; //la dernière case a pour nimber 0
for (x = ncol - 1; x >= 0; x--) //double boucle décroissante pour parcourir le tableau
{
int nimberColonne = nimberDuBas; //nimberColonne est le nimber de chaque case d'une colonne, qu'on initialise au nimber de la case en bas de cette colonne comme on compte en décroissant
for (y = nlig - 1; y >= 0; y--)
{
if (nimberColonne == 0)
nim[x][y] = 0;
else
nim[x][y] = 1;
nimberColonne = (nimberColonne + 1) % 3;
}
nimberDuBas = (nimberDuBas + 2) % 3;
}
}
//Cases bannies
void Hasard_Ban(int *nban, T_Tab_Case ban, int nlig, int ncol)
{
int max;
if (nlig > ncol)
max = nlig;
else
max = ncol;
*nban = rand() % max;
int i;
for (i = 0; i < *nban; i++)
{
T_Case caseBannie;
int positionPossible = 0; // booléen qui dit si oui ou non, notre case est valide
while (!positionPossible) // tant qu'on a pas de case valide, on génère une position aléatoire
{
caseBannie.x = rand() % ncol;
caseBannie.y = rand() % nlig;
if (Existe(ban, i, caseBannie)) //pourquoi i ? car pour l'instant, on a généré i nombre de cases bannies
continue;
if (caseBannie.y == 0 && caseBannie.x < ncol - 1) //si notre case est sur la première ligne (jusqu'à l'avant dernière case)
continue;
if (caseBannie.y == nlig - 1 && caseBannie.x > 0) //si notre case est sur la dernière ligne (à partir de la deuxième case)
continue;
if (caseBannie.x == 0 && caseBannie.y < nlig - 1) //si notre case est sur la première colonne (jusqu'à l'avant dernière case)
continue;
if (caseBannie.x == ncol - 1 && caseBannie.y > 0) //si notre case est sur la dernière colonne (à partir de la deuxième case)
continue;
T_Case voisine1, voisine2; //Test case banni en diagonale
voisine1.x = caseBannie.x - 1;
voisine1.y = caseBannie.y + 1;
voisine2.x = caseBannie.x + 1;
voisine2.y = caseBannie.y - 1;
if (Existe(ban, i, voisine1) || Existe(ban, i, voisine2))
continue;
positionPossible = 1;
}
ban[i] = caseBannie;
}
}
//Dessiner plateau du jeu dans la console
void DessinPlateau(T_Case pion, T_Tab_Case ban, int nban, int nlig, int ncol)
{
printf("\n");
int x, y;
printf(" ");
for (x = 0; x < ncol; x++)
{
printf("%d", x);
if (x < 10)
printf(" ");
}
printf("\n");
for (y = 0; y < nlig; y++)
{
printf("%d", y);
if (y < 10)
printf(" ");
for (x = 0; x < ncol; x++)
{
T_Case caseActuelle; //variable case pour notre point actuel dans le programme (dans la boucle)
caseActuelle.x = x;
caseActuelle.y = y;
if (pion.x == x && pion.y == y) //premier test : si notre case est le pion
printf("|O");
else if (Existe(ban, nban, caseActuelle)) //sinon on vérifie que notre case est un mur (bannie)
printf("|X");
else
printf("|-");
}
printf("|\n");
}
printf("\n");
}
void LireEntier(int *x, int min, int max) //on modifie x, donc on prend un pointeur vers lui
{
while ((*x > max) || (min > *x))
{
printf("La valeur est incorrect. Nouvelle valeur : ");
scanf("%d", x);
getchar();
}
}
void Parametres(int *nlig, int *ncol, int *niveau, int *next) //on prend uniquement les paramètre qu'on a besoin
{
printf(" _ _ _ \n | | | | (_) \n | | ___ _ _ __| | ___ _ __ _ _ __ ___ \n _ | |/ _ \\ | | | / _` |/ _ \\ | '_ \\| | '_ ` _ \\ \n | |__| | __/ |_| | | (_| | __/ | | | | | | | | | |\n \\____/ \\___|\\__,_| \\__,_|\\___| |_| |_|_|_| |_| |_|\n\n");
printf("Entrez le nombres de lignes du plateau : ");
scanf("%d", nlig);
getchar();
LireEntier(nlig, VMIN, VMAX);
printf("Entrez le nombre de colonnes du plateau : ");
scanf("%d", ncol);
getchar();
LireEntier(ncol, VMIN, VMAX);
printf("Entrez le niveau de difficultes de l'ordinateur (compris entre 1 et 4) : ");
scanf("%d", niveau);
getchar();
LireEntier(niveau, 1, 4);
printf("Qui commence la partie ? 1 : l'ordinateur, 2 : vous. Alors : ");
scanf("%d", next);
getchar();
LireEntier(next, 1, 2);
}
void Coup_Joueur(T_Case *pion, T_Tab_Case ban, int nban, int nlig, int ncol)
{
T_Case vois[4];
int nVoisines;
Voisines(*pion, ban, nban, ncol, nlig, vois, &nVoisines);
DessinPlateau(*pion, ban, nban, nlig, ncol);
printf("Choisissez la future position du pion : ");
int i;
for (i = 0; i < nVoisines; i++)
printf("%d : (%d, %d)", i, vois[i].x, vois[i].y);
printf("\n----> ");
int choix;
scanf("%d", &choix);
LireEntier(&choix, 0, nVoisines - 1);
*pion = vois[choix];
DessinPlateau(*pion, ban, nban, nlig, ncol);
}
void Coup_Ordi_Hasard(T_Case *pion, T_Tab_Case ban, int nban, int nlig, int ncol)
{
DessinPlateau(*pion, ban, nban, nlig, ncol);
T_Case vois[4];
int nVoisines;
Voisines(*pion, ban, nban, ncol, nlig, vois, &nVoisines);
*pion = vois[rand() % nVoisines];
printf("L'ordi deplace le pion en (%d, %d)\n", pion->x, pion->y);
}
void Coup_Ordi_Gagnant(T_Case *pion, int nim[][VMAX], T_Tab_Case ban, int nban, int nlig, int ncol)
{
DessinPlateau(*pion, ban, nban, nlig, ncol);
T_Case vois[4];
int nVoisines;
Voisines(*pion, ban, nban, ncol, nlig, vois, &nVoisines);
int i;
for (i = 0; i < nVoisines; i++)
if (nim[vois[i].x][vois[i].y] == 0)
{
*pion = vois[i];
DessinPlateau(*pion, ban, nban, nlig, ncol);
printf("L'ordi deplace le pion en (%d, %d)\n", pion->x, pion->y);
return;
}
*pion = vois[rand() % nVoisines];
printf("L'ordi deplace le pion en (%d, %d)\n", pion->x, pion->y);
}
int main()
{
srand(time(NULL)); // le temps srand initialise la séquence
int nlig = 0, ncol = 0, niveau = 0, next = 0, nban, i, j;
Parametres(&nlig, &ncol, &niveau, &next);
printf("Les parametres du jeu ont bien ete enregistrees !\n");
T_Case ban[VMAX];
T_Case pion;
pion.x = 0;
pion.y = 0;
Hasard_Ban(&nban, ban, nlig, ncol);
int nim[VMAX][VMAX];
Calcul_Nimbers(nim, nlig, ncol);
while (!(pion.x == ncol - 1 && pion.y == nlig - 1)) //tant que le pion n'est pas dans la dernière case
{
if (next == 2)
{
Coup_Joueur(&pion, ban, nban, nlig, ncol);
next = 1;
}
else
{
switch (niveau)
{
case 1:
Coup_Ordi_Hasard(&pion, ban, nban, nlig, ncol);
break;
case 2:
if (rand() % 3 == 1)
Coup_Ordi_Gagnant(&pion, nim, ban, nban, nlig, ncol);
else
Coup_Ordi_Hasard(&pion, ban, nban, nlig, ncol);
break;
case 3:
if (rand() % 3 >= 1)
Coup_Ordi_Gagnant(&pion, nim, ban, nban, nlig, ncol);
else
Coup_Ordi_Hasard(&pion, ban, nban, nlig, ncol);
break;
case 4:
Coup_Ordi_Gagnant(&pion, nim, ban, nban, nlig, ncol);
break;
}
next = 2;
}
}
if (next == 1)
printf("Vous avez gagne !\n");
else
printf("Vous avez perdu !\n");
}
|
C
|
#include <stdio.h>
void main()
{
char a[10];
int i, k=3;
printf("enter the string");
{
scanf("%s",&a[i]);
}
for(i=0;i<3;i++)
{
printf("%c",a[i]);
}
}
|
C
|
#define _GNU_SOURCE
#include <sys/utsname.h>
#include "light.h"
/*
* usage:
* $ ./t_uname
* Node name: tekapo
* System name: Linux
* Release: 2.6.30-default
* Version: #3 SMP Fri Jul 17 10:25:00 CEST 2009
* Machine: i686
*/
int main(int argc, char *argv[])
{
struct utsname uts;
if (uname(&uts) == -1)
err_exit("uname");
printf("Node name: %s\n", uts.nodename);
printf("System name: %s\n", uts.sysname);
printf("Release: %s\n", uts.release);
printf("Version: %s\n", uts.version);
printf("Machine: %s\n", uts.machine);
exit(EXIT_SUCCESS);
}
|
C
|
/*
* pointer04.h
* Created on: 2012/4/6
* Author: boris
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
void run04(void) {
char a[6];
int addr = (int) &a;
char *s = a;
printf( "\ns initial address: %X", s );
char c;
for (c = 'a'; c <= 'e'; c++){
*s = c;
printf( "\ns address: %X, s: %c, c: %c", s, *s, c );
s++;
}
*s = '\0';
s = (int*)addr;
printf( "\naddr : %X, %s", addr, s );
for (c = 'a'; c <= 'e'; c++){
printf( "\ns address: %X, s: %c", s, *s );
s++;
}
printf( "\naddr : %X, %s", addr, (int*)addr );
putchar('\n');
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int usage) {
int answer = 0;
if(usage > 30)
answer = 20 * 430 + 10 * 570 + (usage - 20) * 840;
else if(usage > 20)
answer = 20 * 430 + (usage - 20) * 570;
else
answer = usage * 430;
return answer;
}
// 아래는 테스트케이스 출력을 해보기 위한 main 함수입니다. 아래에는 잘못된 부분이 없으니 위의 코드만 수정하세요.
int main() {
int usage = 35;
int ret = solution(usage);
// [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
printf("solution 함수의 반환 값은 %d 입니다.\n", ret);
}
|
C
|
/*
* robot.c
*
* Created: 11/22/2016 1:10:48 PM
* Author: MAE_Labs
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include "serial.h"
#include <util/delay.h>
#include "QTI.h"
#include "sonar.h"
volatile int itime;
int i;
ISR(PCINT0_vect){
//Interrupt for Sonar
unsigned char sreg;
if(PINB & 0b00000001) { //pin PB0
sreg = SREG;
cli();
TCNT1 = 0;
SREG = sreg;
} else {
PCMSK0 &= 0b11111110; //sets PCINT0 to 0
itime = TCNT1;
}
}
ISR(PCINT2_vect){
//Interrupt for QTI's
//FIX ME: does it sense the other robot when front 1 QTI's go off???
if (~PIND & 1<<PD4){
killQTI();
}
if (seeOpponent() == 0){
//PB0 = sonar, PB1 = forward right, PB4 = backwards right, PB2 = forward left, PB3 = backwards left
if ((~PIND & (1<<PD2)) && (~PIND & 1<<PD3)) { //both pins go off PD2 and PD3
PORTB &= 0b11111001; //stops
PORTB |= (1<<PB4) | (1<<PB3); //backwards
_delay_ms(500); //delay
PORTB &= 0b11100111; //stops
PORTB |= (1<<PB2) | (1<<PB4); //spin left
_delay_ms(500); //delay
i = 0; //continue to spin left in main
} else if (~PIND & 1<<PD2){ // PD2 goes off turn left
PORTB &= 0b11110101; //stops wheels
PORTB |= (1<<PB4) | (1<<PB2); //spin left
_delay_ms(500); //delay
PORTB &= 0b11100111;
PORTB |= (1<<PB1) | (1<<PB2); //drive forward
_delay_ms(50); //delay
i = 0; //continue to spin left in main
} else if (~PIND & 1<<PD3){ // PD3 goes off turn right
PORTB &= 0b11101011; //stops wheels
PORTB |= (1<<PB3) | (1<<PB1); //spin right
_delay_ms(500); //delay
PORTB &= 0b11100111;
PORTB |= (1<<PB1) | (1<<PB2); //drive forward
_delay_ms(50); //delay
i = 1; //spin right in main
} else { //no white under any sensors
PORTB &= 0b11100111;
PORTB |= (1<<PB1) | (1<<PB2); //drive forward
}
}
}
int main(void){
init_uart();
//setup interrupt for QTI pins and set the LED to an output
setupQTI(PD2, PD3, PD4, PCIE2, PD5); //pins for QTIs, interrupt, and LED
//setup interrupt for sonar
initSonar();
//set wheels to outputs
wheelSetup(PB4, PB1, PB2, PB3);
//enable interrupt
sei();
i = 0; //initialize i to spin left first
while(1){
while (seeOpponent() == 0){
//do not see opponent- spin either left or right until you do
if (i == 0){
PORTB &= 0b11110101;
PORTB |= (1<<PB4) | (1<<PB2); //spin left
} else {
PORTB &= 0b11101011;
PORTB |= (1<<PB3) | (1<<PB1); //spin right
}
}
while(seeOpponent() == 1){
//drive if you see the opponent in front of you
PORTB &= 0b11100111;
PORTB |= (1<<PB1) | (1<<PB2); //drive
}
}
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
int** make2dArray(int rows, int cols);
int main(void)
{
int n, m, i, j, k;
int moves = 0, flags = 1;
int ibug, jbug;
int imove[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
int jmove[8] = { 1, 1, 1, 0, -1, -1, -1, 0};
int **countArray, **checkArray;
srand((unsigned) time(NULL));
/*Get information from user*/
printf("Input n: ");
scanf("%d", &n);
printf("Input m: ");
scanf("%d", &m);
printf("Input initial X: ");
scanf("%d", &ibug);
printf("Input initial Y: ");
scanf("%d", &jbug);
/*Set two-dimensional array of count and check*/
countArray = make2dArray(n, m);
checkArray = make2dArray(n, m);
countArray[ibug][jbug] = 1; //The bug is already standing
checkArray[ibug][jbug] = 1; //on the starting point
/*Loop of the bug walk through certain tiles randomly */
while(moves <= 50000)
{
k = rand() % 8;
ibug = ibug + imove[k];
jbug = jbug + jmove[k];
if( ibug < 0 || ibug >= n || jbug < 0 || jbug >= m ){
ibug = ibug - imove[k]; //When ehe coordinates lead up a wall,
jbug = jbug - jmove[k]; //ignore this move
continue; }
countArray[ibug][jbug]++;
moves++;
if(checkArray[ibug][jbug] == 0){ //Record the tile which is toched first time
checkArray[ibug][jbug] = 1;
flags++; }
if(flags == (n * m)) //Every tile is touched by the bug
break;
}
/*Output the result*/
printf("~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n");
if(moves == 50001){
printf("Mission failed!\n");
printf("Total number of legal moves is 50000.\n");
}
else
printf("Total number of legal moves is %d.\n", moves);
printf("\nFinal Count Array:\n");
for(i = 0; i < n; i++){
for(j = 0; j < m; j++)
printf("%3d ", countArray[i][j]);
printf("\n");
}
/*Release the blocks of memory*/
free(countArray);
free(checkArray);
getch();
return 0;
}
int** make2dArray(int rows, int cols)
{
int **x, i, j;
x = calloc(rows , sizeof (*x));
for(i = 0; i < rows; i++)
x[i] = calloc(cols , sizeof(**x));
return x;
}
|
C
|
#ifndef LIST_H
#define LIST_H
#include<stdio.h>
//节点
typedef struct _NODE
{
int m_data;
struct _NODE *next;
} node_t;
//单项链表
typedef struct _LIST
{
node_t *head;
} list_t;
//操作
void init_list(list_t *list);
void add_node(list_t *list, int data);
void delete_node(list_t *list, int data);
node_t *find_node(list_t *list, int data);
list_t *reverse(list_t *list);
list_t *sort(list_t *list);
void print_list(list_t *list);
void swap(int *a, int *b);
#endif // LIST_H
|
C
|
//Arif Burak Demiray
//This code is compiled with C99
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "linked_list.h"
/**
* This function tries to find an empty location for add operation
* If not found returns null
*/
Node *find_empty_location(Node *node)
{
Node *next = NULL;
next = node->next;
if (next == NULL)
{
return node;
}
else
{
return find_empty_location(node->next);
}
}
int length(Node *first)
{
int size = 0;
Node *node = NULL;
node = first;
while (node != NULL)
{
size++;
node = node->next;
}
return size;
}
void add_product(Node *first, product *new_data)
{
if (first == NULL) //if list empty
{ //malloc space for first element and make it first
first = (Node *)malloc(sizeof(Node));
first->data = new_data;
first->before = NULL;
first->next = NULL;
}
else
{ //otherwise create a new node and find an empty space for it
Node *new_node = malloc(sizeof(Node));
new_node->data = new_data;
new_node->before = NULL;
new_node->next = NULL;
Node *node = find_empty_location(first);
if (node != NULL) //if found, set up links
{
node->next = new_node;
new_node->before = node;
}
else
{
free(new_node);
return;
}
}
}
/**
* This function tries to find a node that contains specified product
* If not found returns null
*/
Node *find_product(Node *node, product *data)
{
if (node == NULL || node->data == NULL || data == NULL)
{
return NULL;
}
product *node_data = NULL;
node_data = node->data;
if (node_data == NULL)
return NULL;
if (equals(&node_data, &data) != 1)
{
return find_product(node->next, data);
}
else
{
return node;
}
}
void remove_product(Node **first, product *data)
{
Node *node = find_product(*first, data);
if (node == NULL){ //if we come to end return
return;
}else{
Node *next = NULL; //set up temporary variables
next = node->next;
Node *before = NULL;
before = node->before;
int isHead = 0; //check for is head
if (next != NULL && before != NULL){ //if node is between not null nodes
before->next = next;
next->before = before;
}else if (before != NULL){ //if node at the end
before->next = NULL;
}else if (next != NULL){ //if node is the head
Node *head = *first; //take real address
*first = (*first)->next; //make first next node of the head
(*first)->before = NULL; //make before null
free(head); //and free head
isHead = 1; //make flag true
}else{
return;
}
if (!isHead) //free removed and links' broke node
{
free(node);
node = NULL;
}
}
}
void free_list(Node *first)
{
Node *node = first;
if (first == NULL)
{
return; //if empty return
}
Node *next = NULL;
do
{
next = node->next;
free(node);
node = next;
} while (next != NULL); //while hasNext
}
void print_list(Node *first)
{
Node *node = NULL;
node = first;
if (node == NULL)
{
return;
}
while (node != NULL) //while hasNext
{
product *data = NULL;
data = node->data;
to_string(data);
node = node->next;
}
}
product *find_product_by_type(Node *node, char *type)
{
if (node == NULL || type == NULL || node->data == NULL)
{ //if one of the datas is null, return
return NULL;
}
if (type_equals(node->data, type) != 1) //if types are not matched
{
return find_product_by_type(node->next, type);
}
else
{
return node->data;
}
}
product *get(Node *first, int index)
{
int len = length(first);
if (first == NULL || first->data == NULL || index >= len)
{
return NULL;
}
Node *temp = NULL;
temp = first;
int i = 0;
while (temp != NULL) //while has next
{
if (index == i) //if given index matches
return temp->data;
temp = temp->next;
i++;
}
}
void print_list_bound(Node *first, int budget)
{
Node *node = NULL;
node = first;
if (node == NULL)
{
return;
}
while (node != NULL)
{
product *data = NULL;
data = node->data;
if (data->price <= budget) //if given bound greater than or equal to product's price
{
to_string(data);
}
node = node->next;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 6
#define COLS 10
void make_string(char *a, char *b, int size_a);
int is_in_col(char **a, char *string_to_find, int col);
int string_is_in_char_matrix(char **a, char *string_to_find);
int is_in_char_array(char *char_array, char *string_to_find, int size_of_char_array);
int main()
{
char string_to_find[] = "eee";
char **a;
int i,j;
a = (char **) malloc (ROWS*sizeof(char *));
for (i=0; i<ROWS; i++)
a[i] = (char *) malloc (COLS*sizeof(char));
for (i=0; i<ROWS; i++)
for (j=0; j<COLS; j++)
a[i][j] = 'a' + i;
if (string_is_in_char_matrix(a,string_to_find))
printf("string %s is in char matrix\n",string_to_find);
return 0;
}
void make_string(char *a, char *b, int size_a)
{
int i;
i=0;
while( i<size_a)
{
b[i] = a[i];
i++;
}
b[i] = '\0';
}
int is_in_char_array(char *char_array, char *string_to_find, int size_of_char_array)
{
char *char_array_as_string;
char_array_as_string = (char *) malloc ((size_of_char_array+1) * sizeof(char));
make_string(char_array,char_array_as_string,size_of_char_array);
if (strstr(char_array_as_string,string_to_find) != NULL)
return 1;
return 0;
}
int string_is_in_char_matrix(char **a, char *string_to_find)
{
int i;
for (i=0; i<ROWS; i++)
if (is_in_char_array(a[i],string_to_find,COLS))
return 1;
for (i=0; i<COLS; i++)
{
if (is_in_col(a,string_to_find,i))
return 1;
}
return 0;
}
int is_in_col(char **a, char *string_to_find, int col)
{
int i;
char col_as_row[ROWS+1];
for (i=0; i<ROWS; i++)
col_as_row[i] = a[i][col];
if (is_in_char_array(col_as_row,string_to_find,ROWS))
return 1;
return 0;
}
|
C
|
#include <stdio.h>
#include<string.h>
int main(void) {
char a[1000]="hello world.123";
int i,c=0;
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='0'||a[i]=='1'||a[i]=='2'||a[i]=='3'||a[i]=='4'||a[i]=='5'||a[i]=='6'||a[i]=='7'||a[i]=='8'||a[i]=='9'||a[i]=='*'||a[i]=='@'||a[i]=='&')
{
c++;
}
}
printf("%d",c);
return 0;
}
|
C
|
/**
* Projekt: Implementace překladače imperativního jazyka IFJ20.
*
* @brief Implementácia analyzy vyrazov.
*
* @author Matej Kocman <xkocma07@vutbr.cz>
*/
#ifndef _EXPR_H
#define _EXPR_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include "symtable.h"
typedef enum {
L_PLUS, // +
L_MINUS, // -
L_MUL, // *
L_DIV, // /
L_LEFT_BR, // (
L_RIGHT_BR, // )
L_ID, // i
L_LESS, // <
L_MORE, // >
L_LESS_EQ, // <=
L_MORE_EQ, // >=
L_EQUAL, // ==
L_NOT_EQUAL, // !=
L_DOLLAR, // $
L_INT, // int
L_STRING, // str
L_FLOAT, // float
L_NON_TERMINAL, // E
L_ERR, // pre T_ERR alebo T_UNKNOWN
L_BOOL // pre bool
} expr_lexem;
/*
* @brief Konvertuje token zo scanneru na token pre analyzu
*
* @return Novy typ tokenu
*/
expr_lexem token_convert();
/*
* @brief Spočíta itemy nad handle
*
* @return Vráti počet itemov nad handle
*/
int items_above_handle();
/*
* @brief Redukuje stack
*
* @return Vráti ERR_RIGHT či nejakú z syntaktických alebo semantických chýb
*/
int reduce_stack(bool *rel_flag,tType *change);
/*
* @brief Hlavná funkcia precedenčnej analýzy
*
* @return Vráti ERR_RIGHT či nejakú z syntaktických alebo semantických chýb
*/
int expression(tType *change,bool *cond,BTreeStackPtr Local_trees);
/*
* @brief Kontroluje, či premenné sú správneho typu, semantická kontrola
*
* @return Vráti ERR_RIGHT či nejakú zo semantických chýb
*/
int sem_check_var(tType *change,BTreeStackPtr Local_trees);
#endif
|
C
|
#include <stdio.h>
#include <malloc.h>
#define ElementType int
#define Error(str) printf("error: %s", str)
struct TreeNode;
typedef struct TreeNode* TreeNode;
typedef struct TreeNode* LeftistHeap;
struct TreeNode
{
ElementType value;
TreeNode left;
TreeNode right;
int nullPathLen;
};
TreeNode createTreeNode(ElementType value);
LeftistHeap insert(LeftistHeap heap, ElementType value);
LeftistHeap merge(LeftistHeap h1, LeftistHeap h2);
LeftistHeap secondMerge(LeftistHeap h1, LeftistHeap h2);
void printPreorder(int depth, TreeNode root);
LeftistHeap deleteMin(LeftistHeap heap);
// create tree node with value.
TreeNode createTreeNode(ElementType value)
{
TreeNode temp = (TreeNode)malloc(sizeof(struct TreeNode));
if(temp==NULL)
{
Error("failed createTreeNode() for out of space.");
return NULL;
}
temp->value = value;
temp->left = NULL;
temp->right = NULL;
temp->nullPathLen = 0;
return temp;
}
// insert value into the leftist heap.
LeftistHeap insert(LeftistHeap heap, ElementType value)
{
TreeNode temp = createTreeNode(value);
if(temp==NULL)
{
Error("failed insert().");
return NULL;
}
else
{
return merge(heap, temp);
}
}
// by default, h1->root->value > h2->root->value.
// merge h1 and h2.
LeftistHeap merge(LeftistHeap h1, LeftistHeap h2)
{
if(h1==NULL)
{
return h2;
}
else if(h2==NULL)
{
return h1;
}
if(h1->value < h2->value)
{
return secondMerge(h1, h2);
}
else if(h1->value > h2->value)
{
return secondMerge(h2, h1);
}
else
{
Error("failed merge() for the value has been inserted.");
return h1;
}
}
void swapChild(LeftistHeap h1)
{
TreeNode temp;
temp = h1->left;
h1->left = h1->right;
h1->right = temp;
}
// by default, h1->root->value > h2->root->value.
// second merge h1 and h2.
LeftistHeap secondMerge(LeftistHeap h1, LeftistHeap h2)
{
if(h1->left==NULL) // if h1 has no left child.
{
h1->left = h2;
}
else // if h1 has a left child, then merge its right child with h2.
{
h1->right = merge(h1->right, h2);
// after merging, dont forget to update the nullPathLen.
if(h1->left->nullPathLen < h1->right->nullPathLen)
{
swapChild(h1);
}
h1->nullPathLen = h1->right->nullPathLen + 1;
// update over.
}
return h1;
}
// delete minimal tree node from heap.
LeftistHeap deleteMin(LeftistHeap heap)
{
LeftistHeap left;
LeftistHeap right;
if(heap==NULL)
{
Error("failed deleteMin() for the heap is NULL.");
return heap;
}
left = heap->left;
right = heap->right;
free(heap);
return merge(left, right);
}
// analog print directories and files name in the BinaryTree, which involves postorder traversal.
void printPreorder(int depth, LeftistHeap root)
{
int i;
if(root)
{
for(i = 0; i < depth; i++)
printf(" ");
printf("%d\n", root->value);
printPreorder(depth + 1, root->left);
// Attention: there's difference between traversing binary tree and common tree.
printPreorder(depth + 1, root->right);
}
else
{
for(i = 0; i < depth; i++)
printf(" ");
printf("NULL\n");
}
}
|
C
|
for (i=0; i<lim-1; ++i) {
c = getchar();
if (c == '\n')
break
if (c == EOF)
break
s[i] = c;
}
|
C
|
#pragma once
#include <cmath>
#include <Eigen/Core>
void normalize(double axis[3]){
double sum = sqrt(axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2]);
axis[0] /= (sum + 1e-20);
axis[1] /= (sum + 1e-20);
axis[2] /= (sum + 1e-20);
}
void cross_product(double axis_a[3], double axis_b[3], double axis_c[3]){
axis_c[0] = axis_a[1]*axis_b[2] - axis_a[2]*axis_b[1];
axis_c[1] = axis_a[2]*axis_b[0] - axis_a[0]*axis_b[2];
axis_c[2] = axis_a[0]*axis_b[1] - axis_a[1]*axis_b[0];
}
void set_axis(double axis_a[3], double axis_b[3], double axis_c[3], double position[3], Eigen::MatrixXd& rot){
rot = Eigen::MatrixXd::Zero(4,4);
rot(0,0) = axis_a[0]; rot(1,0) = axis_a[1]; rot(2,0) = axis_a[2];
rot(0,1) = axis_b[0]; rot(1,1) = axis_b[1]; rot(2,1) = axis_b[2];
rot(0,2) = axis_c[0]; rot(1,2) = axis_c[1]; rot(2,2) = axis_c[2];
rot(0,3) = position[0]; rot(1,3) = position[1]; rot(2,3) = position[2];
rot(3,3) = 1.0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.