language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#ifndef QUEUE_H
#define QUEUE_H
typedef struct _queue_object{
void* object;
struct _queue_object* next;
}queue_object;
/**
* @param new_object pointer to some object you want to add into the FIFO queue
* @param queue the pointer to a queue you want to add the obejct to
* @return 0 if everything was fine
*/
int queue_add(void* new_obejct, queue_object* queue);
/**
* gets and deletes the oldest item from the queue
* @param queue The pointer to a queue handler you want to poll from
* @result pointer to an object that was previously added using function int queue_add or NULL if the queue is empty
*/
void* queue_poll(queue_object* queue);
/**
* Creates and returns a new queue. Should be called before working with the queue.
* @result a pointer to a new queue handler.
*/
queue_object* new_queue();
/**
* deletes and frees all queue items
* @param queue The pointer to the queue you want to delete
*/
void free_queue(queue_object* queue);
/**
* gets the oldest item in the queue, but doesn't delete it
* @param queue Pointer to the queue you want to peek from
* @result pointer to an object that was previously added using queue add or NULL if the queue is empty
*/
void* queue_peek(queue_object* queue);
#endif //QUEUE_H
|
C
|
/**************************************************************************
**
** bezier3.h
** Author : ericjang
** Created: 6/14/2014
**
** General-purpose cubic bezier curve. Smooth enough for most purposes.
** This forms the mathematical primitive of a path.
**
**************************************************************************/
#ifndef BEZIER3_H
#define BEZIER3_H
#include "vec2.h"
struct bezier3
{
vec2 p0,p1,p2,p3;
// union {
// vec2 data[4];
// struct {vec2 a,b,c,d;};
// struct {};
// };
// constructor
inline bezier3() { p0=vec2();p1=vec2();p2=vec2();p3=vec2(); }
inline bezier3(vec2 a, vec2 b, vec2 c, vec2 d) { p0=a;p1=b;p2=c;p3=d;}
inline bezier3& operator = (const bezier3 &rhs) {
p0=rhs.p0;
p1=rhs.p1;
p2=rhs.p2;
p3=rhs.p3;
return *this;
};
// Adaptive Subdivision of Bezier Curves
//http://antigrain.com/research/adaptive_bezier/
static inline float arclength(vec2 a,vec2 b,vec2 c,vec2 d) {
float TOLERANCE = .01;
float L0,L1;
L1 = vec2::dist(a,b)+vec2::dist(b,c)+vec2::dist(c,d);
L0 = vec2::dist(a,d);
if (L1-L0 > TOLERANCE) {
// perform recursive subdivision
vec2 p01 = (a+b)/2;
vec2 p12 = (b+c)/2;
vec2 p23 = (c+d)/2;
vec2 p012 = (p01+p12)/2;
vec2 p123 = (p12+p23)/2;
vec2 p0123 = (p012+p123)/2;
return arclength(a,p01,p012,p0123) + arclength(p0123,p123,p23,d);
} else {
return (L0+L1)/2;
}
}
inline float arclength() {
return arclength(p0,p1,p2,p3);
}
// returns point on curve parameterized from t between 0,1
inline vec2 bezierP(float t) {
return bezierP(p0,p1,p2,p3,t);
}
// class static method for convenience
static inline vec2 bezierP(vec2 a, vec2 b, vec2 c, vec2 d, float t) {
float x = (1-t);
return a*(x*x*x)+b*(3*x*x*t)+c*(3*x*t*t)+d*(t*t*t);
};
static inline void print(const bezier3 &b) {
printf("p0 : [%10f %10f]\n", b.p0.x, b.p0.y );
printf("p1 : [%10f %10f]\n", b.p1.x, b.p1.y );
printf("p2 : [%10f %10f]\n", b.p2.x, b.p2.y );
printf("p3 : [%10f %10f]\n", b.p3.x, b.p3.y );
}
};
#endif // BEZIER3_H
|
C
|
/***************************************************************************
(c) 1998, Joseph L. Thorley
All rights reserved
History: 31/7/98
****************************************************************************/
#ifndef _TLEAFSET_H
#define _TLEAFSET_H
#include "TClassTypes.h"
#include "TSortable.h"
#include "TBitSet.h"
// seriously add flag that handles if contiguous elements....
// could always also store last leaf.......could be interesting...
class TLeafSet : public TSortable
{
public:
TLeafSet (void) : fBitSet () { };
TLeafSet (const unsigned int n) : fBitSet (n) { };
TLeafSet (const TLeafSet& leafSet) : fBitSet (leafSet.fBitSet) { };
virtual ~TLeafSet (void) { };
virtual void AddToThis (const TLeafSet& leafSet) { fBitSet.AddToThis (leafSet.fBitSet); };
virtual void AddToThis (const unsigned int leaf) { fBitSet.AddToThis (leaf); };
virtual ClassType Class (void) const { return (kTLeafSetClass); };
virtual TObject* Clone (void) const { return (new TLeafSet (*this)); };
virtual int Compare (const TSortable& sortable) const;
virtual void Complement (TLeafSet& leafSet, const unsigned int n = kMaxLeaves) const { fBitSet.Complement (leafSet.fBitSet, n); };
virtual void Copy (const TObject& obj);
virtual unsigned int CurLeaf (void) const { return ((unsigned int)(fBitSet.CurElement ())); };
virtual void SubtractFromThis (const TLeafSet& leafSet) { fBitSet.SubtractFromThis (leafSet.fBitSet); };
virtual void SubtractFromThis (const unsigned int n) { fBitSet.SubtractFromThis (n); };
virtual void SetEmpty (void) { fBitSet.SetEmpty (); };
virtual unsigned int FirstLeaf (void) const { return ((unsigned int)(fBitSet.FirstElement ())); };
virtual void SetFull (const unsigned int n = kMaxLeaves) { fBitSet.SetFull (n); };
virtual HashValue Hash (void) const { return (fBitSet.Hash ()); };
virtual void Intersection (const TLeafSet& leafSet, TLeafSet& intersection) const { fBitSet.Intersection (leafSet.fBitSet, intersection.fBitSet); };
virtual void IntersectWithThis (const TLeafSet& leafSet) { fBitSet.IntersectWithThis (leafSet.fBitSet); };
virtual void IntersectWithThis (const unsigned int leaf) { fBitSet.IntersectWithThis (leaf); };
virtual bool IsSequential (void) const { return (fBitSet.IsSequential ()); };
virtual bool IsDisjoint (const TLeafSet& leafSet) const { return (fBitSet.IsDisjoint (leafSet.fBitSet)); };
virtual bool IsEmpty (void) const { return (fBitSet.IsEmpty ()); };
virtual bool IsEqual (const TObject&) const;
virtual bool IsLeaf (const unsigned int n) const { return (fBitSet.IsElement ((unsigned int) n)); };
virtual bool IsSubset (const TLeafSet& leafSet) const { return (fBitSet.IsSubset (leafSet.fBitSet)); };
virtual bool IsSuperset (const TLeafSet& leafSet) const { return (fBitSet.IsSuperset (leafSet.fBitSet)); };
virtual unsigned int IthLeaf (const unsigned int n) const { return (fBitSet.IthElement ((unsigned int) n)); };
virtual unsigned int LastLeaf (void) const { return ((unsigned int)(fBitSet.LastElement ())); };
virtual unsigned int GetLeaves (void) const { return ((unsigned int)(fBitSet.GetSize ())); }
virtual unsigned int NumberOfLeaf (const unsigned int n) const { return ((unsigned int)(fBitSet.NumberOfElement ((unsigned int) n))); };
virtual unsigned int NextLeaf (void) const { return ((unsigned int)(fBitSet.NextElement ())); };
virtual unsigned int NextLeaf (const unsigned int n) const { return ((unsigned int)(fBitSet.NextElement ((unsigned int) n))); }
TLeafSet& operator = (const TLeafSet& leafSet);
virtual TLeafSet& operator += (const TLeafSet& leafSet);
virtual TLeafSet& operator += (const unsigned int leaf);
virtual TLeafSet& operator *= (const TLeafSet& leafSet);
virtual TLeafSet& operator *= (const unsigned int leaf);
virtual TLeafSet& operator -= (const TLeafSet& leafSet);
virtual TLeafSet& operator -= (const unsigned int leaf);
virtual TLeafSet operator + (const TLeafSet& leafSet) const;
virtual TLeafSet operator * (const TLeafSet& leafSet) const;
virtual TLeafSet operator - (const TLeafSet& leafSet) const;
virtual SetRelations Relationship (const TLeafSet& leafSet) const { return (fBitSet.Relationship (leafSet.fBitSet)); };
virtual void SetDifference (const TLeafSet& leafSet, TLeafSet& setDifference) const { fBitSet.SetDifference (leafSet.fBitSet, setDifference.fBitSet); };
virtual void ShiftLeaves (const unsigned int positions = 1);
virtual void Union (const TLeafSet& leafSet, TLeafSet& uniun) const { fBitSet.Union (leafSet.fBitSet, uniun.fBitSet); };
virtual ostream& Write (ostream& o) const { return (fBitSet.Write (o)); };
protected:
TBitSet<kMaxLeaves> fBitSet;
};
#endif // _TLEAFSET_H
|
C
|
/*
Ejercicio 1.19
Escriba una funcin reverse(s) que invierta la cadena de caracteres s.
sela para escribir un programa que invierta su entrada, lnea a lnea
*/
#include <stdio.h>
#define MAXLINE ((unsigned int)1000) /* tamao mximo de la lnea de entrada */
int intGetline(char line[], int maxline);
void reverse(char [], int);
/* imprime la lnea de entrada ms larga */
main()
{
/*VARIABLE DECLARATIONS*/
int intLength; /* longitud actual de la lnea */
int intCharTestValueIndex;
int charTestValue;
int intLineIndex;
char arrayCharLine[MAXLINE]; /* lnea de entrada actual */
/*INITIALIZATIONS*/
intLineIndex = 0;
/*MAIN LOGIC*/
intLength = intGetline(arrayCharLine, MAXLINE);
while (intLength > 0)
{
reverse(arrayCharLine, intLength);
printf("%s\n", arrayCharLine);
intLength = intGetline(arrayCharLine, MAXLINE);
}
return 0;
}
/* getline: lee una lnea en s, regresa su longitud */
int intGetline(char acInputString[], int iInputStringLimit)
{
/*VARIABLE DECLARATIONS*/
int intInputChar;
int intIndex = 0;
/*MAIN LOGIC*/
intInputChar = getchar();
for( ;(intIndex < iInputStringLimit-1) && (intInputChar != EOF) && (intInputChar != '\n'); intIndex++) {
acInputString[intIndex] = intInputChar;
intInputChar = getchar();
}
acInputString[intIndex] = '\0';
return intIndex;
}
void reverse(char arrayInputCharLine[], int intInputArrayLength)
{
int intStartIndex;
int intEndIndex;
char charTempValueForSwap;
intStartIndex = 0;
intEndIndex = intInputArrayLength - 1;
while ((intStartIndex < intEndIndex))
{
charTempValueForSwap = arrayInputCharLine[intStartIndex];
arrayInputCharLine[intStartIndex] = arrayInputCharLine[intEndIndex];
arrayInputCharLine[intEndIndex] = charTempValueForSwap;
intStartIndex++;
intEndIndex--;
}
}
|
C
|
#include "nuphasedaq.h"
#include <stdio.h>
#include <stdlib.h>
// read_reg spidev byte0 byte1 byte2 byte3
int main(int nargs, char ** args)
{
uint8_t bytes[4];
int i,status;
nuphase_dev_t * dev;
if (nargs < 6)
{
printf("Usage: read_reg spidev");
return 1;
}
//no interrupt, no locking, default config,
dev = nuphase_open(args[1],0,0,0);
bytes[i] = strtol(args[i+2], 0, 16);
}
for (i = 0; i < 4; i++)
{
printf("Sending:(%x,%x,%x,%x)\n", bytes[0], bytes[1], bytes[2], bytes[3]);
}
status = nuphase_write(dev, bytes);
printf(status ? "Success!\n" : "Something went wrong\n");
nuphase_close(dev);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
float tb,gb,mb,kb,byte;
printf("\n Ingrese un valor expresado en Terabyte:\n\n\t");
scanf("%f",&tb);
gb=tb*1024;
mb=gb*1024;
kb=mb*1024;
byte=kb*1024;
printf("\n %f terabyte equivale a:\n\n %f gigabyte \n\n %f megabyte \n\n %f kilobyte \n\n %f byte\n\n",tb,gb,mb,kb,byte);
getch();
}
|
C
|
#ifndef NJSON_H_
#define NJSON_H_
typedef enum { false, true } bool;
typedef struct _Njson {
char* key;
void* value;
void (*print_nj)(void* this, FILE* out);
unsigned size_type;
unsigned count_elem;
bool is_array; // Se utiliza para imprimir
} Njson;
Njson* njson_init(Njson* this, char* key, void* value, unsigned size_type, unsigned count_elem, void (*print_nj)(void* this, FILE* out), unsigned is_array);
void njson_release(Njson* this);
void njson_print(Njson* this, FILE* out);
void njson_print_string(void* value, FILE* out);
void njson_print_int(void* value, FILE* out);
void njson_print_double(void* value, FILE* out);
void njson_print_boolean(void* value, FILE* out);
void njson_print_json(void* value, FILE* out);
Njson* njson_set_value(Njson* this, void* value, unsigned size_type, unsigned count_elem, void (*print_nj)(void* this, FILE* out), unsigned is_array);
#endif /* NJSON_H_ */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fo_input_mouse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rmc-coma <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/19 02:13:14 by rmc-coma #+# #+# */
/* Updated: 2016/03/22 02:39:03 by rmc-coma ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
static void fo_zoom_in(int x, int y, t_fo *obj)
{
double xd;
double yd;
static t_size i = 0;
obj->fractal->zoom_coeff *= 1.05;
xd = (double)x / obj->fractal->zoom_x;
yd = (double)y / obj->fractal->zoom_y;
obj->fractal->x1 += xd;
obj->fractal->x2 += xd;
obj->fractal->y1 += yd;
obj->fractal->y2 += yd;
i++;
if (i == 5)
{
obj->fractal->max_i += 1;
i = 0;
}
}
static void fo_zoom_out(int x, int y, t_fo *obj)
{
double xd;
double yd;
static t_size i = 0;
obj->fractal->zoom_coeff *= 1.0 / 1.05;
xd = ((double)x - 67.5) / obj->fractal->zoom_x;
yd = ((double)y - 61.0) / obj->fractal->zoom_y;
obj->fractal->x1 += xd;
obj->fractal->x2 += xd;
obj->fractal->y1 += yd;
obj->fractal->y2 += yd;
i++;
if (i == 5)
{
if (obj->fractal->max_i > 1)
obj->fractal->max_i += 1;
i = 0;
}
}
int fo_input_mouse(int buttoncode, int x, int y, t_fo *obj)
{
if (x > 0 && x < (int)obj->win_width &&
y > 0 && y < (int)obj->win_height)
{
if (buttoncode == 1 || buttoncode == 4)
fo_zoom_in(x - obj->win_width / 2, y - obj->win_height / 2, obj);
else if (buttoncode == 2 || buttoncode == 5)
fo_zoom_out(x - obj->win_width / 2, y - obj->win_height / 2, obj);
else
return (0);
if (obj->fractal->type == MANDELBROT)
fo_draw_mandelbrot(obj);
else if (obj->fractal->type == JULIA)
fo_draw_julia(obj);
else if (obj->fractal->type == SHIP)
fo_draw_ship(obj);
}
return (0);
}
|
C
|
#ifndef HASHMAP_H_INCLUDED
#define HASHMAP_H_INCLUDED
#include <stdlib.h>
typedef struct NC_vararray NC_vararray;
typedef struct NC_dimarray NC_dimarray;
/** Hashmap structure (forward declaration) */
struct s_hashmap;
typedef struct s_hashmap NC_hashmap;
/** Creates a new hashmap near the given size. */
extern NC_hashmap* NC_hashmapCreate(unsigned long startsize);
/** Inserts a new element into the hashmap. */
extern void NC_hashmapAddDim(const NC_dimarray*, long data, const char *name);
/** Removes the storage for the element of the key and returns the element. */
extern long NC_hashmapRemoveDim(const NC_dimarray*, const char *name);
/** Returns the element for the key. */
extern long NC_hashmapGetDim(const NC_dimarray*, const char *name);
/** Inserts a new element into the hashmap. */
extern void NC_hashmapAddVar(const NC_vararray*, long data, const char *name);
/** Removes the storage for the element of the key and returns the element. */
extern long NC_hashmapRemoveVar(const NC_vararray*, const char *name);
/** Returns the element for the key. */
extern long NC_hashmapGetVar(const NC_vararray*, const char *name);
/** Returns the number of saved elements. */
extern unsigned long NC_hashmapCount(NC_hashmap*);
/** Removes the hashmap structure. */
extern void NC_hashmapDelete(NC_hashmap*);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
int p=1;
int f=1;
int main()
{
float e(int x,int n);
int x;
int n;
printf("enter the power of exponential: \n");
scanf("%d",&x);
printf("enter number of terms to be used in series: \n");
scanf("%d",&n);
printf("value of exponential = %f \n",e(x,n));
}
float e(int x,int n)
{
float r;
if(n==0)
{
return 1;
}
else
{
r=e(x,n-1);
p=p*x;
f=f*n;
return r+(p/f);
}
}
|
C
|
#include <stdlib.h>
#include "game/game_state.h"
#include "game/scenes/credits.h"
#include "utils/allocator.h"
#include "video/video.h"
typedef struct credits_local_t {
int ticks;
} credits_local;
void credits_input_tick(scene *scene) {
game_player *player1 = game_state_get_player(scene->gs, 0);
ctrl_event *p1 = NULL, *i;
controller_poll(player1->ctrl, &p1);
i = p1;
if(i) {
do {
if(i->type == EVENT_TYPE_ACTION) {
if(i->event_data.action == ACT_ESC || i->event_data.action == ACT_KICK ||
i->event_data.action == ACT_PUNCH) {
game_state_set_next(scene->gs, SCENE_NONE);
}
}
} while((i = i->next));
}
controller_free_chain(p1);
}
void credits_tick(scene *scene, int paused) {
credits_local *local = scene_get_userdata(scene);
local->ticks++;
if(local->ticks > 4500) {
game_state_set_next(scene->gs, SCENE_NONE);
}
}
void credits_free(scene *scene) {
credits_local *local = scene_get_userdata(scene);
omf_free(local);
scene_set_userdata(scene, local);
}
void credits_startup(scene *scene, int id, int *m_load, int *m_repeat) {
switch(id) {
case 20:
*m_load = 1;
return;
}
}
int credits_create(scene *scene) {
credits_local *local = omf_calloc(1, sizeof(credits_local));
local->ticks = 0;
// Callbacks
scene_set_userdata(scene, local);
scene_set_dynamic_tick_cb(scene, credits_tick);
scene_set_free_cb(scene, credits_free);
scene_set_startup_cb(scene, credits_startup);
scene_set_input_poll_cb(scene, credits_input_tick);
// Don't render background on its own layer
// Fix for some additive blending tricks.
video_render_bg_separately(false);
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int a,b,c;
a = 1;
b = 2;
c = b + a;
printf("%d",c);
}
|
C
|
#include "ͷ.h"
void queueInit(Queue* q)
{
//ʼն
q->_front = q->_rear = NULL;
q->_size = 0;
}
QNode* creatNode(QDataType data)
{
QNode* node = (QNode*)malloc(sizeof(QNode));
node->_data = data;
node->_next = NULL;
return node;
}
//β
void queuePush(Queue* q, QDataType data)
{
QNode* node = creatNode(data);
//ն
if (q->_front == NULL)
q->_front = q->_rear = node;
else
{
q->_rear->_next = node;
q->_rear = node;
}
++q->_size;
}
//ͷ
void queuePop(Queue* q)
{
if (q->_front)
{
QNode* next = q->_front->_next;
free(q->_front);
q->_front = next;
//ɾ֮ǷΪձ
if (q->_front == NULL)
q->_rear = NULL;
--q->_size;
}
}
//ȡͷԪ
QDataType queueFront(Queue* q)
{
return q->_front->_data;
}
//ȡβԪ
QDataType queueBack(Queue* q)
{
return q->_rear->_data;
}
int queueSize(Queue* q)
{
/*
int num = 0;
QNode* cur = q->_front;
while (cur)
{
++num;
cur = cur->_next;
}
return num;
*/
return q->_size;
}
int queueEmpty(Queue* q)
{
if (q->_front == NULL)
return 1;
return 0;
}
void queueDestory(Queue* q)
{
QNode* cur = q->_front;
while (cur)
{
QNode* next = cur->_next;
free(cur);
cur = next;
}
q->_front = q->_rear = NULL;
q->_size = 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
float liczba1, liczba2;
int wyb;
printf("Podaj pierwsza liczbe: ");
scanf("%f", &liczba1);
printf("Wybierz rodzaj dzialania:\n");
printf("1 - dodawanie\n");
printf("2 - odejmowanie\n");
printf("3 - mnozenie\n");
printf("4 - dzielenie\n");
printf("Wybierz operacje wpisujac odpowiednia cyfre: ");
scanf("%d", &wyb);
printf("\nPodaj druga liczbe: ");
scanf("%f", &liczba2);
if(wyb == 1){
float wynik = liczba1 + liczba2;
printf("%.f + %.f = %.f", liczba1, liczba2, wynik);
}
else if(wyb == 2){
float wynik = liczba1 - liczba2;
printf("%.f - %.f = %.f", liczba1, liczba2, wynik);
}
else if(wyb == 3){
float wynik = liczba1 * liczba2;
printf("%.f * %.f = %.f", liczba1, liczba2, wynik);
}
else if(wyb == 4){
float wynik = liczba1 / liczba2;
printf("%f / %f = %g", liczba1, liczba2, wynik);
}
else{
printf("wpisana liczba nie odnosi sie do zadnej operacji");
}
return 0;
}
|
C
|
#include<stdio.h>
main()
{
int n,i,k,z;
printf("Enter size of array. : ");
scanf("%d%d",&n,&k);
z=n+k;
int a[n], a1[k], a2[z];
printf("Enter value in first array.:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter value in second array.:\n");
for(i=0;i<k;i++)
scanf("%d",&a1[i]);
for(i=0;i<z;i++){
if(i<n)
a2[i]=a[i];
else
a2[i]=a1[i-n];
}
printf("After merge two array is .:\n");
for(i=0;i<z;i++)
printf("%d\n",a2[i]);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* style_handler.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gozsertt <gozsertt@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/01 18:49:09 by gozsertt #+# #+# */
/* Updated: 2019/12/06 11:50:32 by gozsertt ### ########.fr */
/* */
/* ************************************************************************** */
#include "../ft_printf.h"
t_style g_style_table[] =
{
{ "default", "0" },
\
{ "bold", "1" },
{ "faint", "2" },
{ "italic", "3" },
{ "underlined", "4" },
{ "inverted", "7"},
{ "hidden", "8"},
\
{ "black", "30" },
{ "red", "31" },
{ "green", "32" },
{ "yellow", "33" },
{ "blue", "34" },
{ "magenta", "35" },
{ "cyan", "36" },
{ "gray", "37" },
\
{ "lgray", "90" },
{ "lred", "91" },
{ "lgreen", "92" },
{ "lyellow", "93" },
{ "lblue", "94" },
{ "lmagenta", "95" },
{ "lcyan", "96" },
{ "lwhite", "97" },
\
{ "bgblack", "40" },
{ "bgred", "41" },
{ "bggreen", "42" },
{ "bgyellow", "43" },
{ "bgblue", "44" },
{ "bgmagenta", "45" },
{ "bgcyan", "46" },
{ "bggray", "47" },
\
{ "bglgray", "100" },
{ "bglred", "101" },
{ "bglgreen", "102" },
{ "bglyellow", "103" },
{ "bglblue", "104" },
{ "bglmagenta", "105" },
{ "bglcyan", "106" },
{ "bglwhite", "107" },
\
{ NULL, NULL}
};
char *style_handler(t_format format, char *string)
{
char *style;
int8_t i;
int8_t j;
if (format.style == NULL)
return (string);
style = ft_strdup("\033[");
i = -1;
while (format.style[++i])
{
j = -1;
while (g_style_table[++j].style)
if (ft_strcmp(format.style[i], g_style_table[j].style) == 0)
{
style = ft_strappend(style, g_style_table[j].ansi_code, 1, 0);
if (format.style[i + 1] != NULL)
style = ft_strappend(style, ";", 1, 0);
free(format.style[i]);
break ;
}
}
free(format.style);
style = ft_strappend(style, "m", 1, 0);
string = ft_strprepend(string, style, 1, 1);
return (ft_strappend(string, "\033[0m", 1, 0));
}
|
C
|
#ifndef ANTISOUND_FIFO_H
#define ANTISOUND_FIFO_H
#include <stdlib.h>
#include <stdbool.h>
typedef struct FIFO
{
int id;
void* data;
struct FIFO* next;
struct FIFO* tale;
}fifo_t;
/*
* initializes struct FIFO and returns pointer to fifo_t
*/
fifo_t* antiSound_fifo_initializeFifo();
/*
* removes first item(head) and returns pointer to new head
*/
bool antiSound_fifo_pop(fifo_t* fifo);
/*
* add data to last item(tail)
* returns true in case success, otherwise fasle
*/
bool antiSound_fifo_push(fifo_t* fifo, void* data);
/*
* checking the queue for the presence of elements in it,
* returns true in case success, otherwise fasle
*/
bool antiSound_fifo_isEmpty(fifo_t* fifo);
/*
* returns size of fifo;
*/
int antiSound_fifo_size(fifo_t* fifo);
fifo_t* antiSound_fifo_getHead(fifo_t* head);
#endif // ANTISOUND_FIFO_H
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_formatd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ael-kass <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/19 10:45:24 by ael-kass #+# #+# */
/* Updated: 2020/01/09 11:13:41 by ael-kass ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_formatd(const char **format, int nbatoi, va_list args)
{
int nbargs;
int nbpoint;
char *stritoa;
nbpoint = 1;
if (**format != '%')
nbargs = va_arg(args, int);
if (**format == 'x' || **format == 'X')
stritoa = casdex(nbargs, format);
else if (**format != '%')
stritoa = ft_itoa(format, nbargs);
else
{
if ((stritoa = (char *)malloc(2)) == NULL)
return (-1);
stritoa[0] = '%';
stritoa[1] = '\0';
}
if (nbatoi > 0)
ft_positive(&stritoa, nbatoi, nbpoint);
if (nbatoi < 0)
ft_negative(&stritoa, nbatoi, nbpoint);
nbargs = ft_putstr(stritoa);
ft_free(&stritoa);
return (nbargs);
}
int ft_formatd1(const char **format, int nbatoi, va_list args)
{
int nbargs;
char *stritoa;
if (**format != '%')
nbargs = va_arg(args, int);
if (**format == 'x' || **format == 'X')
stritoa = casdex(nbargs, format);
else if (**format != '%')
stritoa = ft_itoa(format, nbargs);
else
{
if ((stritoa = (char *)malloc(2)) == NULL)
return (-1);
stritoa[0] = '%';
stritoa[1] = '\0';
}
if (nbargs >= 0 || **format == 'u' || **format == 'x' || **format == 'X'
|| **format == '%')
ft_positivecas0(&stritoa, nbatoi);
else
ft_negativecas0(&stritoa, nbatoi);
nbargs = ft_putstr(stritoa);
ft_free(&stritoa);
return (nbargs);
}
int ft_formatd2(const char **format, int nbatoi, int nbpoint, va_list args)
{
int nbargs;
char *stritoa;
if (**format != '%')
nbargs = va_arg(args, int);
if (**format == '%')
{
nbpoint = 0;
nbargs = 1;
}
if (nbargs == 0 && nbatoi == 0 && nbpoint == 0)
return (nbargs);
stritoa = helpformatd2(nbargs, format);
if (nbpoint > 0)
{
if (nbargs >= 0 || **format == 'u' || **format == 'x'
|| **format == 'X')
ft_positivecas0(&stritoa, nbpoint);
else
{
nbpoint = nbpoint + 1;
ft_negativecas0(&stritoa, nbpoint);
}
}
return (helpformad02(nbatoi, stritoa, nbpoint, nbargs));
}
int helpformad02(int nbatoi, char *stritoa, int nbpoint, int nbargs)
{
if (nbatoi > 0)
ft_positive(&stritoa, nbatoi, nbpoint);
if (nbatoi < 0)
ft_negative(&stritoa, nbatoi, nbpoint);
nbargs = ft_putstr(stritoa);
ft_free(&stritoa);
return (nbargs);
}
char *helpformatd2(int nbargs, const char **format)
{
char *stritoa;
if (**format == 'x' || **format == 'X')
stritoa = casdex(nbargs, format);
else if (**format != '%')
stritoa = ft_itoa(format, nbargs);
else
{
if ((stritoa = (char *)malloc(2)) == NULL)
return (NULL);
stritoa[0] = '%';
stritoa[1] = '\0';
}
return (stritoa);
}
|
C
|
#include<stdio.h>
int main() {
/* code */
int year = 2020;
if((year % 4 == 0 && year % 100 != 0)|| year % 400 == 0)
printf("its leap year\n");
else
printf("NOT LEAP year\n");
}
|
C
|
#include <stdio.h>
#include <conio.h>
int main(){
int n;
int aSay=0,bSay=0,cSay=0,dSay=0,fSay=0;
printf("Harf notlarini giriniz:\n");
printf("Cikis icin EOF karakterini giriniz:\n");
while((n=getchar())!=EOF){
if(n=='A'||n=='a'){
aSay++;
}
else if(n=='B'||n=='b'){
bSay++;
}
else if(n=='C'||n=='c'){
cSay++;
}
else if(n=='D'||n=='d'){
dSay++;
}
else if(n=='F'||n=='f'){
fSay++;
}
}
printf( "\n Her harf notu icin toplam:\n" );
printf( "A: %d\n", aSay );
printf( "B: %d\n", bSay );
printf( "C: %d\n", cSay );
printf( "D: %d\n", dSay );
printf( "F: %d\n", fSay );
getch();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int is_abundant(int n) {
int sum = 0;
for (int i = 2; i <= n/2; i++) {
if (n % i == 0) {
sum += i;
if (sum > n) {
return 1;
}
}
}
return 0;
}
int main() {
int n = 1;
int count = 0;
while (count < 20) {
if (is_abundant(n)) {
printf("%d ", n);
count ++;
}
n += 2;
}
}
|
C
|
/*
author: James Ross
note: if you found it, ask before using it for something other than bowling.
thx :D
handles the flow of the game in a single player instance as described in
singleplayer.h
filename: singleplayer.c
*/
/* headers */
#include "singleplayer.h"
#include "game.h"
#include <stdio.h>
#include <stdlib.h>
#define NDEBUG /* prevents assert.h */
#include <assert.h>
/* function source */
/* Keep score of an entire game from start to finish */
void playfull_single(player *currentp)/*#{{{*/
{
frame *currFrame = NULL; /* current frame in play */
uint64_t *scoreTotal = NULL; /* total score for current player */
register uint64_t i = 0;
char previousR2 = '\0';
char previousR1 = '\0';
assert(currentp != NULL);
/* single player specific opening */
printf("\nYou are playing single player, get some!\n");
scoreTotal = ¤tp -> scoreTotal;
/* go through each frame for the player, and play it! */
currFrame = currentp -> allFrames;
for(i = 1; i < MAXFRAMES; ++i, ++currFrame) /* all but frame 11 */
{
/* get 2 rolls */
printf("\nEnter in current frame results.");
play_frame(currFrame);
/* fill in fv and score */
*scoreTotal = calc_score(currFrame);
display_game(¤tp, NULL, 1);
} /* end for */
/* current frame is currently on frame 11/11, pointers are fun! */
--currFrame;
previousR2 = currFrame -> roll[R2];
previousR1 = currFrame -> roll[R1];
++currFrame;
if(previousR2 == '/' || previousR1 == 'X')
{
yes_bonus_r(currFrame);
*scoreTotal += calc_bonus_r(currFrame);
} /* end if */
/* clear the screen before printing final results */
system("clear");
printf("\n\n\nYou finished a single player game! alone!\n");
display_game(¤tp, NULL, 1);
} /* end playfull_single #}}} */
|
C
|
#ifndef __LCD_BMP_H
#define __LCD_BMP_H
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#define RGB(r,g,b) (((r>>3)<<11)|((g>>2)<<5)|(b>>3))
typedef unsigned char BYTE;//1 byte
typedef unsigned short WORD;//2 byte
typedef unsigned long DWORD;//4 byte
/****************************** Bitmap standard information*************************************/
/*Bitmap file header 14bit*/
typedef struct BMP_FILE_HEADER {
WORD bType; //File identifier
DWORD bSize; //The size of the file
WORD bReserved1; //Reserved value, must be set to 0
WORD bReserved2; //Reserved value, must be set to 0
DWORD bOffset; //The offset from the beginning of the file header to the beginning of the image data bit
} __attribute__ ((packed)) BMPFILEHEADER; // 14bit
/*Bitmap information header 40bit*/
typedef struct BMP_INFO {
DWORD bInfoSize; //The size of the header
DWORD bWidth; //The width of the image
DWORD bHeight; //The height of the image
WORD bPlanes; //The number of planes in the image
WORD bBitCount; //The number of bits per pixel
DWORD bCompression; //Compression type
DWORD bmpImageSize; //The size of the image, in bytes
DWORD bXPelsPerMeter; //Horizontal resolution
DWORD bYPelsPerMeter; //Vertical resolution
DWORD bClrUsed; //The number of colors used
DWORD bClrImportant; //The number of important colors
} __attribute__ ((packed)) BMPINF;
/*Color table: palette */
typedef struct RGB_QUAD {
BYTE rgbBlue; //Blue intensity
BYTE rgbGreen; //Green strength
BYTE rgbRed; //Red intensity
BYTE rgbReversed; //Reserved value
} __attribute__ ((packed)) RGBQUAD;
/**************************************** end ***********************************************/
uint8_t LCD_ShowBmp(const char *path);
#endif
|
C
|
void initialize(agent_struct *agent, int action_index){
int row; /*Starting positions for the scan area*/
int column;
row = (int)(40 * ((double)rand()/(double)RAND_MAX));
column = (int)(40 * ((double)rand()/(double)RAND_MAX));
agent->field[1] = row;
agent->field[2] = column;
agent->field[3] = 4; /*Row offset*/
agent->field[4] = 4; /*Colum offset*/
}
void bounce(agent_struct *agent, int action_index){
int wall; /* Holds value indicating which wall the agent hit. */
/* acquire the FSA state of the current agent */
wall = agent->fsa->current_state; /*This determines which wall was hit */
if(wall == 1 || wall == 3){
switch (agent->dir) {
case 1: agent->dir = 3;
break;
case 3: agent->dir = 1;
break;
}
switch (agent->switch_dir) {
case 1: agent->switch_dir = 3;
break;
case 3: agent->switch_dir = 1;
break;
}
}
if(wall == 2 || wall == 3){
switch (agent->dir) {
case 0: agent->dir = 2;
break;
case 2: agent->dir = 0;
break;
}
switch (agent->switch_dir) {
case 0: agent->switch_dir = 2;
break;
case 2: agent->switch_dir = 0;
break;
}
}
}
void scan(agent_struct *agent, int action_index){
int i, j; /*Row and column counters*/
int row; /*Starting positions for the scan area*/
int column;
int row_max;
int col_max; /*Upper bounds for row and col, set by GGETR and GGETC*/
int there = 0; /*0 if the target is not found, 1 if found */
int state;
function_struct temp_func;
update_grid_struct temp_grid;
row_max = GGETR(0);
col_max = GGETC(0);
row = (int)agent->field[1];
column = (int)agent->field[2];
/* acquire the FSA state of the current agent */
state = agent->fsa->current_state;
/* access the support grid to be updated by this function */
temp_func = agent->state_functions[state].function_list[action_index];
/* determines which support grid contains pertinent information */
temp_grid = temp_func.update_grids[0];
for(i = row; i < (row + 5); i++){
for(j = column; j < (column + 5); j++){
if(i >= row_max || j >= col_max){
break;
}
if(GGET(temp_grid.grid, i, j) == 1){
there = 1;
break;
}
GSET(temp_grid.grid, i, j, 2);
}
if (there != 0){
break;
}
}
if (there == 1){
// printf("The target was located in the grid starting at (%d,%d)\n", row, column);
GSET(temp_grid.grid, agent->y_pos, agent->x_pos, 3);
} else {
agent->field[2] = agent->field[2] + agent->field[4]; /* Moves the search area over by the offset amount */
if(agent->field[2] >= col_max || agent->field[2] < 0 ){ /*This handles the case where the search area is off the grid*/
agent->field[4] = -agent->field[4];
if(agent->field[2] < 0){
agent->field[2] = 0;
} else {
agent->field[2] = agent->field[2] + agent->field[4];
}
agent->field[1] = agent->field[1] + agent->field[3];
}
if(agent->field[1] >= row_max || agent->field[1] < 0 ){
agent->field[3] = -agent->field[3];
if(agent->field[1] < 0){
agent->field[1] = 0;
} else {
agent->field[1] = agent->field[1] + agent->field[3];
}
agent->field[2] = agent->field[2] + agent->field[4];
}
}
}
void location(agent_struct *agent, int action_index){
int row;
int col;
int count;
row = (int)agent->field[1];
col = (int)agent->field[2];
count = (int)agent->field[5];
printf("%d %d %d\n", count, row, col);
}
|
C
|
#include<stdio.h>
#include<string.h>
#define LINES 100 /* max lines to be sorted */
main() /* sort input lines */
{
char *lineptr[LINES]; /* pointers to text lines */
int nlines; /* number of input lines read */
if ((nlines = readlines(lineptr, LINES)) >= 0) {
sort(lineptr, nlines);
writelines(lineptr, nlines);
}
else
printf("input too big to sort\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <pthread.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/sendfile.h>
#include <fcntl.h>
#include <sys/wait.h>
#define HOME_PAGE "index.html"
#define MAX 1024
static void usage(const char *proc)
{
printf("Usage:\n\t%s prot\n", proc);
}
int get_line(int sock, char line[], int num)
{
assert(line);
assert(num > 0);
int i = 0;
char c = 'x';
while(c != '\n' && i < num-1)
{
ssize_t s = recv(sock, &c, 1, 0);
if(s > 0)
{
if(c == '\r')
{//\r or \r\n ----> \n
recv(sock, &c, 1, MSG_PEEK);
if(c == '\n')
recv(sock, &c, 1, 0);
else
c = '\n';
}
line[i++] = c;
}else{
break;
}
}
line[i] = 0;
return i;
}
void clear_header(int sock)
{
char line[MAX];
do{
get_line(sock, line, sizeof(line));
}while(strcmp(line, "\n"));
}
void echo_error(int sock, int code)
{
switch(code){
case 404:
//show_404();
break;
default:
break;
}
}
//
int echo_wwww(int sock, char *path, int size)
{
int fd = open(path, O_RDONLY);//打开对应文件
if(fd < 0)
{
return 404;
}
//清除header
clear_header(sock);
//给客户回复
char line[MAX];
sprintf(line, "HTTP/1.0 200 OK\r\n");//首行
send(sock, line, strlen(line), 0);
sprintf(line, "Content-Type: text/html;charset=ISO-8859-1\r\n");//请求头
send(sock, line, strlen(line), 0);
sprintf(line, "\r\n");//空行
send(sock, line, strlen(line), 0);
//发送正文
sendfile(sock, fd, NULL, size);//拷贝数据,从一个描述符拷到另一个描述符,内核中拷贝。将fd文件描述符中的内容写到sock中。
close(fd);
}
void *header_request(void *arg)
{
int sock = (int)arg;
char line[MAX] = {0};
char method[MAX/10];//方法
char url[MAX] = {0};//url请求
char path[MAX] = {0};//用来保存路径, 也就是url前的资源路径字符串
int i=0, j=0;
int status_code = 200; //状态码
int cgi = 0; //CGI的存在是为了处理后续的数据。url中的数据
char *query_string; //指向参数字符串。
get_line(sock, line, sizeof(line)); // line->\r,\r\n,\n -->\n
//假如请求为 GET /a/a/a?name=zhangsan HTTP/1.1 下面将这个字符串解析
while(i < sizeof(method)-1 && j < sizeof(line) && !isspace(line[j]) )
{
method[i] = line[j];
i++, j++;
}
method[i] = 0;//获取到方法
if(strcasecmp(method, "GET") == 0){
}else if(strcasecmp(method, "POST") == 0)
{
cgi = 1; //在HTTP当中如果请求方法是POST,那么必须要以CGI方式运行,因为我们认定POST方法是传参的。
//当然GET方法也可能以CGI方式运行
}else{//如果不是GET也不是POST那么 将其头部清空,然后设置错误码,最后返回
clear_header(sock);//清空头部
status_code = 404;//设置错误码
goto end;
}
//走到这里,要么是GET方法,要么是POST方法
//获取url
i = 0;
//清除空格,让j指向url开始部分
while(j < sizeof(line) && isspace(line[j]) )
{
j++;
}
while(i < sizeof(url)-1 && j < sizeof(line) && !isspace(line[j]) )
{
url[i] = line[j];
j++, i++;
}
url[i] = 0;
#ifdef DEBUG
printf("line: %s\n", line);
printf("method: %s, url=: %s\n", method, url);
#endif
//处理默认首页,
//mehod GET/POST, url, GET(query_string)/POST, cgi
sprintf(path, "wwwroot%s", url);//两种情况 wwwroot/, wwwroot/a/b/c.html
//如果字符串最后一个是斜杠,
if(path[strlen(path)-1] == '/'){
strcat(path, HOME_PAGE);
}
struct stat st;
if(stat(path, &st) < 0){
clear_header(sock);//清空头部
status_code = 404;//文件不存在,设置错误码
goto end;
}else
{
if(S_ISDIR(st.st_mode)){//是是不是目录
strcat(path, HOME_PAGE);
//可执行文件
}else if((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH)){
cgi = 1;
}else{
//是普通文件
}
}
status_code = echo_wwww(sock, path, st.st_size);
end:
if(status_code != 200)
{
echo_error(sock, status_code);
}
close(sock);
}
int startup(int port)
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("socket");
exit(2);
}
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_port = htons(port);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
{
perror("bind");
exit(3);
}
if(listen(sock, 5) < 0)
{
perror("listen");
exit(4);
}
return sock;
}
// ./httpd 80
int main(int argc, char *argv[])
{
int listen_sock = startup(atoi(argv[1]));
printf("%d\n", listen_sock);
if(argc != 2)
{
usage(argv[0]);
return 1;
}
//将服务器端口蛇尾可复用,防止关闭服务器后TIME_WAIT对服务器造成的影响
int opt = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
for(;;){
struct sockaddr_in client;
socklen_t len = sizeof(client);
int sock = accept(listen_sock, (struct sockaddr*)&client, &len);
printf("%d\n", sock);
if(sock < 0){
perror("accept");
continue;
}
printf("get a new client!\n");
pthread_t tid;
pthread_create(&tid, NULL, header_request, (void *)sock);
pthread_detach(tid);
}
}
|
C
|
#include <stdio.h>
# define MONEDAS 5
float monedas[] = {5, 1, 0.50, 0.20, 0.10};
int solucion[MONEDAS] = {0, 0, 0, 0, 0};
int main(){
int i;
float devolucion;
float precio_prod;
float dinero_recibido;
// Valida input
while(1){
printf("Precio del producto: ");
scanf("%f", &precio_prod);
printf("Dinero a entregar: ");
scanf("%f", &dinero_recibido);
if (precio_prod <= dinero_recibido)break;
else printf("El dinero no le alcanza!\n");
}
devolucion = dinero_recibido - precio_prod;
// Calcula monedas para el cambio
for (i = 0; i < MONEDAS; i++)
while(devolucion >= monedas[i]){
solucion[i]++;
devolucion -= monedas[i];
}
// Muestra el cambio
if(devolucion)
printf("No hay monedas para devolver\n");
else
for(i = 0; i < MONEDAS; i++)
if(solucion[i])
printf("%d monedas de %.2f\n", solucion[i], monedas[i]);
return 0;
}
|
C
|
/**
* A morse code to english translator that uses the command line for input
*
* @author Wolfe, Conrad
* @assignment ICS 212 Assignment 15
* @date March 13, 2018
*/
#include <stdio.h> //io stuff
#include <string.h> //used to compare strings
#include <stdlib.h> //used to exit program
#define SIZE 36
#define MIN 2
const char *morseCode[SIZE] = {
"0 -----",
"1 .----",
"2 ..---",
"3 ...--",
"4 ....-",
"5 .....",
"6 -....",
"7 --...",
"8 ---..",
"9 ----.",
"a .-",
"b -...",
"c -.-.",
"d -..",
"e .",
"f ..-.",
"g --.",
"h ....",
"i ..",
"j .---",
"k -.-",
"l .-..",
"m --",
"n -.",
"o ---",
"p .--.",
"q --.-",
"r .-.",
"s ...",
"t -",
"u ..-",
"v ...-",
"w .--",
"x -..-",
"y -.--",
"z --..",
};
int main(int argc, char *argv[]) {
int i, j;
//error checking
if(argc >= MIN){
//loop through the commandline input (argc)
for(i = 1; i < argc; i++){
//loops through j and compares it to the current i
for(j = 0; j < SIZE; j++){
//if a match is found, convert Morse Code to letter
if(!strcmp(argv[i], (morseCode[j] + 2))){
printf("%c", morseCode[j][0]);
}
}//end j
}//end i
printf("\n");
//error handling
}else{
printf("Error: At least 2 commandline arguments are expected, only %i present.\nEnter Morse Code on the commandline.\n", argc);
exit(EXIT_SUCCESS);
}
return 0;
}//end main
|
C
|
#include <string.h>
#include <stdio.h>
void lshift(int *a, int n) {
memmove(a+n, a, 4*sizeof(int));
memset(a, 0, n*sizeof(int));
}
int main() {
int a[] = {1, 2, 3, 4, 0, 0, 0, 0, 0};
int i;
lshift(a, 0);
for (i=0; i < sizeof(a)/sizeof(int); ++i)
printf("%d ", a[i]);
printf("\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "fizz.h"
/* Add function signatures here */
int main(int argc, char **argv) {
/* Start your code here */
int n;
printf("What is the number that you want to calculate:\n" );
scanf("%d", &n);
fizzBuzz(n);
return 0;
}
|
C
|
#include<stdio.h>
int adjlist[10][10],stack[100],queue[100],visited[10];
int front =0; int rear = -1;
int top = -1;
int n;
int main()
{
printf("enter the number of nodes: ");
scanf("%d",&n);
int choice;
while(1)
{
printf("\n1) Create an adjacency list for the graph\n2) BFS\n3) DFS\n4) Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1: createlist(); break;
case 2:
{
int i,v;
for(i=0;i<n;i++)
{visited[i] = 0;}
printf("enter starting vertex: ");
scanf("%d",&v);
bfs(v);
}
break;
case 3:
{
int i,v;
for(i=0;i<n;i++)
{visited[i]=0;}
printf("enter starting vertex: ");
scanf("%d",&v);
dfs(v);
}
break;
case 4: exit(0);
default: printf("Invalid choice, try again: ");
}
}
}
void createlist()
{
int i,j,x;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
adjlist[i][j]=0;
else
{
printf("\n%d to %d",i,j);
printf("\npress 1: connected\npress 0:not connected\nEnter:");
scanf("%d",&x);
adjlist[i][j]=x;
}
}
}
}
void bfs(int vertex)
{
if(visited[vertex]==0)
{
printf("%d",vertex);
visited[vertex]=1;
}
int i;
for(i=0;i<n;i++)
{
if(adjlist[vertex][i]==1 && visited[i]==0)
queue[++rear] = i;
}
if(front<=rear)
{
bfs(queue[front++]);
}
}
void dfs(int vertex)
{
if(visited[vertex] == 0)
{
visited[vertex] = 1;
printf("%d",vertex);
stack[++top] = vertex;
}
int i; int v =0;
for(i=0;i<n;i++)
{
if(adjlist[vertex][i]==1)
{
dfs(i);
v = 1;
}
}
if(v==0 && top>=-1)
dfs(stack[top--]);
}
|
C
|
#include<stdio.h>
#include<math.h>
void main(){
float a=0,b=2*M_PI,x,delta_x=1.e-2;//0.001
printf("\tx\t\te^-x\t\t(e^-x)\'\n");
x = a;
while(x<b){
printf("%10.2f\t%10.2f\t%10.2f\n",x,exp(-x),/*-exp(-x));*/(-exp(-x+delta_x)+exp(-x))/delta_x);
x += delta_x;//x = x + delta_x;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "mascotas.h"
#include "ac_getFunciones.h"
#include "menus.h"
#include "funciones_adicionales.h"
#include "razas.h"
int getEmptySlotRaza(e_Raza vec[],int size)
{
int lugar = -1;
int flag = 0;
for (int i = 0; i<size && flag == 0; i++)
{
if (vec[i].isFull == 0)
{
lugar = i;
flag = 1;
}
}
return lugar;
}
int buscarRaza (int id,e_Raza vec[],int size)
{
int lugar = -1;
for (int i= 0; i<size; i++)
{
if (vec[i].id == id && vec[i].isFull == 1)
{
lugar = i;
break;
}
}
return lugar;
}
void mostrarTamanios (e_Tamanio vec[],int size){
printf("TAMANIOS DE MASCOTA:\n");
for (int i = 0;i<size; i++){
printf("%d. %20s\n",i+1,vec[i].descripcion);
}
}
void mostrarRazas (e_Raza razas[],int size){
printf("RAZAS :\n");
for (int i = 0;i<size; i++){
if (razas[i].isFull == 1){
printf("%d. %20s\n",i+1,razas[i].descripcion);
}
}
}
int conseguirIndiceTamanioPorRaza (e_Raza raza,e_Tamanio tamanios[],int sizeTam){
int indice;
for (int i = 0; i<sizeTam;i++){
if (raza.size == tamanios[i].size){
indice = i;
break;
}
}
return indice;
}
void inicializarRazas (e_Raza vec[],int size)
{
for (int i = 0; i<size; i++)
{
vec[i].isFull = 0;
}
}
|
C
|
#include "common.h"
#include "descriptor_tables.h"
#include "monitor.h"
#include "syscall.h"
static void gdt_set_gate(unsigned int,unsigned int,unsigned int,unsigned char,unsigned char);
static void write_tss(unsigned int num, unsigned short ss0,unsigned int esp0);
extern void tss_flush();
void init_gdt();
gdt_entry gdt_entries[6];//定义5个段
gdt_ptr the_gdt_ptr; //定义段表开始地址及长度
tss_t tss_entry;//定义一个tss段
void init_gdt()
{
the_gdt_ptr.limit=(sizeof(gdt_entry)*6)-1;
the_gdt_ptr.base=(unsigned int)&gdt_entries;
gdt_set_gate(0, 0, 0, 0, 0); // Null segment
gdt_set_gate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); // Code segment
gdt_set_gate(2, 0, 0xFFFFFFFF, 0x92, 0xCF); // Data segment
gdt_set_gate(3, 0, 0xFFFFFFFF, 0xFA, 0xCF); // User mode code segment
gdt_set_gate(4, 0, 0xFFFFFFFF, 0xF2, 0xCF); // User mode data segment
write_tss(5,0x10,0x0);//add tss段
gdt_flush((unsigned int)&the_gdt_ptr);
tss_flush();
}
static void gdt_set_gate(unsigned int num,unsigned int base,unsigned int limit,unsigned char access,unsigned char gran)
{
//用了定义entry具体内容的函数
gdt_entries[num].base_low = (base & 0xFFFF);
gdt_entries[num].base_middle = (base >> 16) & 0xFF;
gdt_entries[num].base_high = (base >> 24) & 0xFF;
gdt_entries[num].limit_low = (limit & 0xFFFF);
gdt_entries[num].granularity = (limit >> 16) & 0x0F;
gdt_entries[num].granularity |= gran & 0xF0;
gdt_entries[num].access = access;
}
static void write_tss(unsigned int num, unsigned short ss0, unsigned int esp0)
{
unsigned int base = (unsigned int) &tss_entry;
unsigned int limit=base+sizeof(tss_t);
gdt_set_gate(num,base,limit,0xE9,0x00);
memset(&tss_entry,0,sizeof(tss_t));
tss_entry.ss0=ss0;
tss_entry.esp0=esp0;
//因为首先是内核模式,所以代码段是0x08数据段是0x10
//将后两位(rpl)置1,所以是0x0b和0x13
tss_entry.ss=tss_entry.ds=tss_entry.es=tss_entry.gs=tss_entry.fs=0x13;
//代码段
tss_entry.cs=0x0b;
}
void set_kernel_stack(unsigned int stack)
{
tss_entry.esp0=stack;
}
|
C
|
#ifndef ITEM_H
#define ITEM_H
#include "player.h"
#include <stdlib.h>
struct player;
typedef void (*effect)(struct player*);
enum _item_type;
struct item;
struct actionable;
struct weapon;
struct consumable;
struct potion;
typedef enum item_type {
actionable_type,
weapon_type,
consumable_type,
potion_type,
} item_type;
typedef struct item {
char* name;
item_type type;
void* item;
} item;
typedef struct actionable {
} actionable;
typedef struct weapon {
int damage;
} weapon;
typedef struct consumable {
int health;
int mana;
} consumable;
typedef struct potion {
effect effect_function;
} potion;
item* new_item(char* name, item_type type, void* item);
actionable* new_actionable();
weapon* new_weapon(int damage);
consumable* new_consumable(int health, int mana);
potion* new_potion(effect effect_function);
item* get_item(item* items[], int item_size, char* name);
void print_item(item* item);
void delete_item(item* item);
#endif
|
C
|
//
// Copyright (C) BlockWorks Consulting Ltd - All Rights Reserved.
// Unauthorized copying of this file, via any medium is strictly prohibited.
// Proprietary and confidential.
// Written by Steve Tickle <Steve@BlockWorks.co>, September 2014.
//
#include "ErrorHandling.h"
#include "TimedEvents.h"
#include "BoardSupport.h"
struct
{
Handler handler;
uint32_t interval;
uint32_t firingTime;
} timedEventHandlers[8] = {0};
void CallEvery_ms( Handler handler, uint32_t interval )
{
for(uint32_t i=0; i<NUMBER_OF_ELEMENTS(timedEventHandlers); i++)
{
if( timedEventHandlers[i].handler == 0 )
{
timedEventHandlers[i].handler = handler;
timedEventHandlers[i].interval = interval;
timedEventHandlers[i].firingTime = CurrentTimestamp_ms() + interval;
break;
}
}
}
void CallAfter_ms( Handler handler, uint32_t interval )
{
for(uint32_t i=0; i<NUMBER_OF_ELEMENTS(timedEventHandlers); i++)
{
if( timedEventHandlers[i].handler == 0 )
{
timedEventHandlers[i].handler = handler;
timedEventHandlers[i].interval = 0;
timedEventHandlers[i].firingTime = CurrentTimestamp_ms() + interval;
break;
}
}
}
void CheckTimedEventHandlers()
{
uint32_t timestamp = CurrentTimestamp_ms();
for(uint32_t i=0; i<NUMBER_OF_ELEMENTS(timedEventHandlers); i++)
{
if( timedEventHandlers[i].handler != 0 )
{
if( timestamp >= timedEventHandlers[i].firingTime )
{
Call( timedEventHandlers[i].handler );
if(timedEventHandlers[i].interval == 0)
{
timedEventHandlers[i].handler = 0;
}
else
{
timedEventHandlers[i].firingTime = timestamp + timedEventHandlers[i].interval;
}
}
}
}
}
|
C
|
void ft_sort_int_tab(int *tab, int size)
{
int aux;
int i;
i = 0;
while (i < size)
{
if (tab[i] > tab[i+1])
{
aux = tab[i];
tab[i] = tab[i+1];
tab[i+1] = aux;
i = -1;
}
i++;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../pfa-src/interface_mm.h"
#include "../pfa-src/db_manager.h"
struct AllData * init_AllData(void)
{
struct AllData * d;
d = malloc(sizeof(struct AllData));
d->id_party = INIT_VAR_INT;
d->mod.name = NULL;
d->bot.id = INIT_VAR_INT;
d->bot.name = NULL;
d->date.day = INIT_VAR_INT;
d->date.month = INIT_VAR_INT;
d->date.year = INIT_VAR_INT;
d->door_lvl = INIT_VAR_INT;
d->door_disc = INIT_VAR_INT;
d->steps = INIT_VAR_INT;
d->depth = INIT_VAR_INT;
return d;
}
void assign_id_party(struct AllData * d, const int id)
{
d->id_party = id;
}
void assign_mod(struct AllData * d, const char * name, const int id )
{
d->mod.id = id;
d->mod.name = malloc((strlen(name) + 1) * sizeof(char));
strcpy(d->mod.name, name);
}
void assign_bot(struct AllData * d, const char * name, const int id)
{
d->bot.id = id;
d->bot.name = malloc((strlen(name) + 1) * sizeof(char));
strcpy(d->bot.name, name);
}
void assign_date(struct AllData * d, const struct Date dt)
{
d->date.day = dt.day;
d->date.month = dt.month;
d->date.year = dt.year;
}
void assign_nb_steps(struct AllData * d, const int nb)
{
d->steps = nb;
}
void assign_nb_door_discovered(struct AllData * d, const int nb)
{
d->door_disc = nb;
}
void assign_nb_door_level(struct AllData * d, const int nb)
{
d->door_lvl = nb;
}
void assign_nb_monsters_generated(struct AllData * d, const int nb)
{
d->steps = nb;
}
void assign_nb_monsters_killed(struct AllData * d, const int nb)
{
d->steps = nb;
}
int destroy_AllData(struct AllData * d)
{
if (d == NULL)
{
printf("Erreur, le pointeur passé en argument n'est pas assigné\n");
return EXIT_FAILURE;
}
else
{
if (d->mod.name == NULL)
{
printf("Erreur, le champ mod_name n'est pas assigné\n");
return EXIT_FAILURE;
}
if (d->bot.name == NULL)
{
printf("Erreur, le champ bot_name n'est pas assigné\n");
return EXIT_FAILURE;
}
else
{
free(d->mod.name);
free(d->bot.name);
}
free(d);
}
return EXIT_SUCCESS;
}
/*
* Given a structure "All Data", write the name of the table where it has to be stored
*/
int get_table_name(char * buffer, struct AllData * d)
{
sprintf(buffer, "table_bot_%s_%d_mod_%s_%d", d->bot.name, d->bot.id, d->mod.name, d->mod.id);
return EXIT_SUCCESS;
}
// A compléter avec les fonctions de gestion de la bd de Louis L
int write_into_database(struct AllData * d)
{
FILE * log = fopen("log_pfa.txt", "w+");
char * table_name;
table_name = malloc(MAX_CHAR * sizeof(char));
char * args;
args = malloc(MAX_CHAR * sizeof(char));
time_t timestamp;
struct tm * t;
timestamp = time(NULL);
t = localtime(×tamp);
d->date.year = t->tm_year + 1900;
d->date.month = t->tm_mon;
d->date.day = t->tm_mday;
// Tester les erreurs d'assignations dans les valeurs toujours utilisées
if (d->id_party == INIT_VAR_INT)
{
fprintf(log, "Error, id_party has not been assigned properly\n");
return EXIT_FAILURE;
}
if (d->mod.name == NULL)
{
fprintf(log, "Error, mod informations have not been assigned properly\n");
return EXIT_FAILURE;
}
if (d->bot.name == NULL)
{
fprintf(log, "Error, bot informations have not been assigned properly\n");
return EXIT_FAILURE;
}
get_table_name(table_name, d);
if ((strcmp(d->bot.name, "AdvancedRandomBot") == 0) | (strcmp(d->bot.name, "RandomBot") == 0))
{
void *db = init_DB("Netbot_highscores");
create_table(db, table_name, "DAY INT, MONTH INT, YEAR INT, DOORLVL INT, DOORDISC INT, DEPTH INT", NULL);
sprintf(args, "%d, %d, %d, %d, %d, %d", d->date.day, d->date.month, d->date.year, d->door_lvl, d->door_disc, d->depth);
write_DB(db, table_name, "DAY, MONTH, YEAR, DOORLVL, DOORDISC, DEPTH", args, NULL);
}
else
{
printf("Non-recognized bot name\n");
}
free(table_name);
free(args);
return 0;
}
|
C
|
/*
* Author: Cobbliu
* Email: cobblau@gmail.com
*/
/*
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
*/
/*
* Hint:
* F[i][j] = min(F[i-1][j], F[i][j-1]) + grid[i][j]
*/
int minPathSum(int** grid, int gridRowSize, int gridColSize) {
int sum = 0;
for (int i = 0; i < gridRowSize; i++) {
grid[i][0] = sum + grid[i][0];
sum = grid[i][0];
}
sum = 0;
for (int i = 0; i < gridColSize; i++) {
grid[0][i] = sum + grid[0][i];
sum = grid[0][i];
}
for (int i = 1; i < gridRowSize; i++) {
for (int j = 1; j < gridColSize; j++) {
int min = grid[i][j-1] > grid[i-1][j] ? grid[i-1][j] : grid[i][j-1];
grid[i][j] += min;
}
}
return grid[gridRowSize-1][gridColSize-1];
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100
int
comp_func (const void *c1, const void *c2)
{
int i1 = *(int *)c1;
int i2 = *(int *)c2;
return i1 - i2;
}
void
fyshuffle(int* v, int n)
{
srand((unsigned)time(NULL));
for (int i = 0; i < n; i++) {
v[i] = i;
}
for (int i = n - 1; i >= 0 ; i--) {
int rnd = rand() % n;
int tmp = v[i];
v[i] = v[rnd];
v[rnd] = tmp;
}
}
int
main(int argc, char *argv[])
{
int seed[N];
fyshuffle(seed, N);
qsort(seed, N, sizeof(int), comp_func);
for (int i = 0; i < N; i++) {
printf("%d\n", seed[i]);
}
return 0;
}
|
C
|
#include <stdint.h>
#include "lab1.h"
void TurnOff(void) {
volatile unsigned short delay = 0;
RCGCGPIO |= 0x1020; // Enable PortF(led3, 4) and PortN(led1, 2) GPIO
delay++; // Delay 2 more cycles before access Timer registers
delay++; // Refer to Page. 756 of Datasheet for info
GPIODIR_F = 0x11; // Set PF0, PF4 to output
GPIODEN_F = 0x11; // Set PF0, PF4 to digital port
GPIODIR_N = 0x3; // Set PN1, PN0 to output
GPIODEN_N = 0x3; // Set PN1, PN0 to digital port
GPIODATA_N_1 = 0x0;
GPIODATA_N_0 = 0x0;
GPIODATA_F_0 = 0x0;
GPIODATA_F_4 = 0x0; // Turn off all LEDs
}
int main(void) {
TurnOff();
while (1) {
}
return 0;
}
|
C
|
#include<stdio.h>
void array_invert(void){
unsigned short i, j;
float aux, my_array[20];
for(i = 0; i < 20; i++){
scanf("%f", &my_array[i]);
}
j = 20;
for(i = 0; i < 10; i++){
aux = my_array[i];
my_array[i] = my_array[j-1];
my_array[j-1] = aux;
j--;
}
for(i = 0; i < 20; i++){
printf("N[%d] = %.0f\n", i, my_array[i]);
}
}
int main(void){
array_invert();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <time.h>
#define MAXIMUS 10 //̴С
#define SLARY 10000
#define PLAYERS 4
int p[MAXIMUS][MAXIMUS];//洢Ϣ
char buff[MAXIMUS * 3 + 1][MAXIMUS * 6 + 1] = { 0 };//
int wi=0, wj=0;//ǰд뻺λ
char* showText="̣";
char* showAnwser="Ϸʼո·";
char* tip1 = "дĸΪƶ";
char* tip2 = "СдĸΪ˵ķ";
char* tip3 = "1000500300";
int count=0;//غ
int money[PLAYERS] = { 0 };
int wherePlayer[4][2] = { {1,1}, {1,9}, {9,9}, {9,1} };
void Initialize(void);
void doStep(int player);
int buyHouse(int i, int j, int player);
int check(int i, int j, int player);
int getWiner(void);
int runGame(void);
void setPan(void);
void setSqr(void);
void showGame(void);
char* copyStr(char* strDel , const char* string);
void setSpace(void);
void setWord(void);
void setPlayer(void);
void setWhose(void);
int main(void)
{
system("title ״");//ñ
system("mode con cols=70 lines=34");//ôڴС
system("color E0");//ɫ
runGame();
return 0;
}
void Initialize(void)//ʼһԾֺ
{
int i, j, e;
for (e =0; e < PLAYERS; e++)
{
money[e] = SLARY;
}
for (i = 0; i < MAXIMUS; i++)//öԾ
{
for (j = 0; j < MAXIMUS; j++)
{
if (i == 1 || i == 9 || j == 1 || j == 9)
p[i][j] = 9;
else
p[i][j] = 0;
}
}
}
void doStep(int player) //ѡֱţȻҵѡֽƶ
{
int step,count=0,i,j,i1,j1;//ĵĸ
i = wherePlayer[player-1][0];
j = wherePlayer[player-1][1];
srand(time(NULL));
step = (rand() % 6 + 1);
while (count < step)
{
if (i >= 1 && i < 9 && j == 1)//·
{
i1 = i + 1;
j1 = j;
}
else if (i == 9 && j >= 1 && j < 9)
{
i1 = i;
j1 = j + 1;
}
else if (i <= 9 && j == 9 && i > 1)
{
i1 = i - 1;
j1 = j;
}
else if (i == 1 && j <= 9 && j > 1)
{
i1 = i;
j1 = j - 1;
}
i = i1;
j = j1;
count++;
}
wherePlayer[player - 1][0]=i;
wherePlayer[player - 1][1]=j;
}
int buyHouse(int i, int j,int player) //ұ+10˵ӱ
{
if (p[i][j] == 9 && money[player - 1] > 1000)
{
money[player - 1] -= 1000;
p[i][j] = player + 10;
return 1;
}
else
return 0;
}
int check(int i, int j,int player)
{
int input;
while (1)//Ƕ̫ˣԸĽ
{
showGame();
input = getch();
if (input == ' ')
{
setPan();
setWord();
setWhose();
setPlayer();
showGame();
if (p[i][j] == 9)
{
showText = "ûˣǷҪ";
showAnwser = "yһǧԪn";
setWord();
showGame();
input = getch();
while (1)
{
if (input == 'y')
{
showText = "أ ";
showAnwser = "һҲ ";
setWord();
showGame();
buyHouse(i, j, player);
break;
}
else if (input == 'n')
{
showText = "ûйأ ";
showAnwser = "һҲ ";
setWord();
showGame();
break;
}
else
{
showText = " ";
showAnwser = " ";
setWord();
showGame();
input = getch();
}
}
}
else if (p[i][j] >= 10)
{
money[player-1] -= 500;
money[p[i][j] - 11] += 300;
showText = "㱻ٵ500Ǯ";
showAnwser = "ӵ˵õ300ǮʣµĽ˰ˣ";
setWord();
showGame();
return 1;
}
else
printf("check() WRONG!");
return 0;
}
else
{
showText = "ȴ";
showAnwser = "밴¿ո";
showGame();
}
}
}
int getWiner(void)
{
int i;
for (i = 0; i < PLAYERS; i++)
{
if (money[i] <= 0)
{
showText = "Ϸ ";
setWord();
return i + 1;
}
}
return 0;
}
int runGame(void)
{
int player=1,result;
Initialize();
setPan();
while (1)
{
setPan();
setWord();
setWhose();
setPlayer();
showGame();
doStep(player);
check(wherePlayer[player - 1][0], wherePlayer[player - 1][1], player);
result = getWiner();
player += 1;
count++;
if (player == 5)
player = 1;
if (result == 0)
;
else
{
showAnwser = "Ϸ ";
setWord();
showGame();
return 0;
}
}
}
void setSqr(void)//wi,wjΪϽһ
{
copyStr(&buff[wi][wj], " ");
wi += 1;
copyStr(&buff[wi][wj], " ");
wi += 1;
copyStr(&buff[wi][wj], " ");
wi -= 2;
wj += 6;
}
void setSpace(void)
{
copyStr(&buff[wi][wj], " ");
wi += 1;
copyStr(&buff[wi][wj], " ");
wi += 1;
copyStr(&buff[wi][wj], " ");
wi -= 2;
wj += 6;
}
void setPan(void)
{
int i;
wi = 0, wj = 0;
for (i = 0; i < 9; i++)//ظǵ'\0'
{
setSqr();
}
for (i = 0, wi = 3, wj = 0; i < 8; wi += 3, i++, wj = 0)
{
setSqr();
for (int e = 1; e < 8; e++)
{
setSpace();
}
setSqr();
}
for (i = 0,wi = 24,wj=0; i < 9; i++)
{
setSqr();
}
}
void setWord(void)
{
wi = 4;
wj = 8;
copyStr(&buff[wi][wj], tip1);
wi = 5;
wj = 8;
copyStr(&buff[wi][wj], tip2);
wi = 6;
wj = 8;
copyStr(&buff[wi][wj], tip3);
wj = 8;// û֤м
wi = 12;
copyStr(&buff[wi][wj], showText);
wj = 8 ;
wi = 15;
copyStr(&buff[wi][wj], showAnwser);
}
void setPlayer(void)
{
int i;
for (i = 0; i < PLAYERS; i++)
{
wi = (wherePlayer[i][0]-1) * 3 + 1;
wj = (wherePlayer[i][1]-1) * 6 + 3;
buff[wi][wj] = 'A'+i;
}
}
void setWhose(void)
{
int i, j;
for (i = 0; i < MAXIMUS; i++)
{
for (j = 0; j < MAXIMUS; j++)
{
wi = (i - 1) * 3 + 1;
wj = (j - 1) * 6 + 2;
if (p[i][j] == 9)
buff[wi][wj] = ' ';
else if (p[i][j] % 10 == 1)//ȡȷԺܵ
buff[wi][wj] = 'a';
else if (p[i][j] % 10 == 2)
buff[wi][wj] = 'b';
else if (p[i][j] % 10 == 3)
buff[wi][wj] = 'c';
else if (p[i][j] % 10 == 4)
buff[wi][wj] = 'd';
else if (p[i][j] == 0)
;
else
printf("setWho is WORONG!");
}
}
}
void showGame(void)
{
int i;
system("cls");
for (i = 0; i < MAXIMUS*3+1; i++)
{
printf("%s", buff[i]);
putchar('\n');
}
printf("AǮ%d ", money[0]);
printf("BǮ%d ", money[1]);
printf("CǮ%d ", money[2]);
printf("DǮ%d \n", money[3]);
printf("ڽ%dغ", count);
}
char* copyStr(char* strDel, const char* string)
{
char* pz = strDel;
while (*string != '\0')
{
*strDel++ = *string++;//Ƴ\0ַ
}
return pz;
}
|
C
|
#ifndef RBT_H
#define RBT_H
#include "..\Utilities\utils.h"
#define RED 0
#define BLACK 1
#define UNVISITED 0
#define VISITED 1
#define FREE 1
typedef struct rbt_node rbt_node_t;
typedef struct rbt rbt_t;
struct rbt_node{
void* data;
unsigned int colour: 1;
unsigned int visited: 1;
int frequency;
rbt_node_t* left;
rbt_node_t* right;
rbt_node_t* parent;
};
struct rbt{
rbt_node_t* root;
int (*cmp)(const void*, const void*);
void (*in_order_traversal)(rbt_t* tree, void action(void* data));
void (*post_order_traversal)(rbt_t* tree, void action(void* data));
void (*insert)(rbt_t* tree, void* data);
void* (*in)(rbt_t* tree, void* key);
void* (*min)(rbt_t* tree);
void* (*max)(rbt_t* tree);
int (*get_frequency)(rbt_t* tree, void* key);
int (*get_colour)(rbt_t* tree, void* key);
int (*len)(rbt_t* tree);
void (*print)(rbt_t* tree, void print(void* data));
void (*destroy)(rbt_t* tree, void free_data(void* data));
};
rbt_t* create_rbt(int cmp_func(const void*, const void*));
#endif //RBT_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "List.h"
void PrintList(list *list){
node *curNode = list->listHead;
unsigned int id = 1;
// Viene verificato se la lista non è vuota
if(curNode == NULL){
fprintf(stderr,"Errore: impossibile stampare la lista\n");
exit(EXIT_FAILURE);
}
while(curNode != NULL){
printf("%d:%f -> ", id++, curNode->value);
curNode = curNode->nextNode;
}
puts("NULL");
}
|
C
|
/*
** EPITECH PROJECT, 2018
** my_rpg_2017
** File description:
** draw_inventory
*/
#include <stdint.h>
#include "render_window.h"
#include "render.h"
#include "inventory.h"
#include "xml.h"
#include "nb_utils.h"
static void draw_droped_items(win_t *win, inventory_t *inventory)
{
for (uint8_t i = 0; i < (NB_ITEMS - 1); i++) {
if (inventory->item_list[i].droped &&
inventory->item_list[i].pos.x != 0) {
render_object(win->sf_win, SPRITE,
inventory->item_list[i].sprite);
}
}
}
static void draw_selected_item(win_t *win, item_t *item, inventory_t *inventory,
sfVector2f pos)
{
sfFloatRect rect;
sfText_setString(inventory->text, item->name);
sfText_setCharacterSize(inventory->text, 25);
pos.y += 30;
rect = sfText_getGlobalBounds(inventory->text);
sfText_setOrigin(inventory->text,
(sfVector2f){rect.width / 2, rect.height / 2});
sfText_setPosition(inventory->text, pos);
sfSprite_setScale(item->sprite, (sfVector2f){1.2, 1.2});
render_object(win->sf_win, SPRITE, item->sprite);
render_object(win->sf_win, TEXT, inventory->text);
sfSprite_setScale(item->sprite, (sfVector2f){1.0, 1.0});
}
static void draw_item(win_t *win, item_t *item)
{
sfSprite_setColor(item->sprite, sfColor_fromRGBA(255, 255, 255, 90));
render_object(win->sf_win, SPRITE, item->sprite);
sfSprite_setColor(item->sprite, sfColor_fromRGBA(255, 255, 255, 255));
}
static void draw_selected(win_t *win, uint8_t i, inventory_t *inventory,
sfVector2f pos)
{
if (i == inventory->selected)
draw_selected_item(win, inventory->item[i], inventory, pos);
else
draw_item(win, inventory->item[i]);
}
void draw_inventory(win_t *win, inventory_t *inventory)
{
sfVector2f pos = {1400, 1010};
for (int8_t i = 0; i < INVENTORY_NB; i++) {
if (inventory->item[i] && !inventory->item[i]->droped) {
sfSprite_setPosition(inventory->item[i]->sprite, pos);
draw_selected(win, i, inventory, pos);
}
pos.x += 150;
}
draw_droped_items(win, inventory);
if (inventory->display_message)
render_object(win->sf_win, TEXT, inventory->message);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** mdr
** File description:
** mdr
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include "serveur.h"
int g_loop = 0;
void ctrlc(int s)
{
(void) s;
g_loop = 1;
}
int init_signal(void)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = ctrlc;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
return 0;
}
void case_data(t_serveur *client, FILE *file, char *prev_buff, int cmd)
{
switch (cmd) {
case 0:
get_list(client, file, &prev_buff[4]);
break;
case 1:
get_retr(client, file, &prev_buff[4]);
break;
case 2:
get_stor(client, file, &prev_buff[4]);
break;
}
}
int lopo_next(t_serveur *client, FILE *file, char *buff)
{
static char *prev_buff = NULL;
size_t size;
static int cmd = 0;
if (strlen(buff) >= 4 && strncmp(buff, "221", 3) == 0)
return (1);
else if (strlen(buff) >= 4 && strncmp(buff, "227", 3) == 0)
get_pasv(client, &buff[27], 0);
if (strlen(buff) >= 4 && strncmp(buff, "150", 3) == 0)
case_data(client, file, prev_buff, cmd);
getline(&buff, &size, stdin);
prev_buff = strdup(buff);
if (strncmp(buff, "LIST", 4) == 0)
cmd = 0;
else if (strncmp(buff, "RETR", 4) == 0)
cmd = 1;
else if (strncmp(buff, "STOR", 4) == 0)
cmd = 2;
write(client->socket_fd, buff, strlen(buff));
return (0);
}
int loop(t_serveur *client)
{
FILE *file;
char *buff = NULL;
size_t size;
int state = 0;
file = fdopen(client->socket_fd, "rwx");
if (file == NULL)
return (fprintf(stderr, "Fdopen failed !\n"), 0);
while (g_loop == 0) {
if (state == 1) {
if (lopo_next(client, file, buff) == 1)
break;
state = 0;
} else {
getline(&buff, &size, file);
write(1, buff, strlen(buff));
state = check_read(buff);
}
}
return (1);
}
|
C
|
#include <stdio.h>
#include <windows.h>
#include <string.h>
#define length 50
#define k_length 8
void Init();
void Encry();
void Decry();
int Playfair()
{
while (1)
{
Init();
}
return 0;
}
void Init()
{
int answer;
printf(">>Playfairȣ α<<\n");
printf("ȣȭ(0), ȣȭ(1), (2) : ");
scanf("%d", &answer);
system("cls");
switch (answer)
{
case 0:
Encry();
break;
case 1:
Decry();
break;
case 2:
exit(0);
break;
default:
Playfair();
break;
}
}
void Encry()
{
char M[length]; //
int E[length]; //ȣȭ
char C[length]; //ȣ
char K[k_length] = { 0 }; //Ű
char K_arr[25] = { 0 }; //Ű迭
char Karr[5][5] = { 0 }; //2 Ű迭
int M_len;
int K_len;
int i;
int j;
char alpha[25] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
int len = 0;
int si = 0;
printf(">>Playfair ȣȭ<<\n");
printf(" Է(ҹ) : ");
scanf("%s", M);
M_len = strlen(M);
if (M_len % 2 == 1)
{
M[M_len] = 'x';
}
M[M_len + 1] = '\0';
M_len = strlen(M);
for (i = 0; i < M_len; i++)
{
if ('j' == M[i])
{
M[i] = 'i';
}
}
printf("Ű Է(빮 and 7 ) : ");
scanf("%s", K);
K_len = strlen(K);
for (i = 0; i < K_len; i++)
{
if ('J' == K[i])
{
K[i] = 'I';
}
}
for (i = 0; i < K_len; i++)
{
for (j = 0; j < 25; j++)
{
if (K[i] == alpha[j])
{
K_arr[si] = alpha[j];
alpha[j] = 0;
si++;
break;
}
}
}
for (i = 0;i < 25; i++)
{
if (0 != alpha[i])
{
K_arr[si] = alpha[i];
alpha[i] = 0;
si++;
}
}
si = 0;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
Karr[i][j] = K_arr[si];
si++;
}
}
printf(">>key table<<\n");
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("%c ", Karr[i][j]);
}
printf("\n");
}
for (si = 0; si < M_len; si+=2)
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (M[si] - 97 == Karr[i][j] - 65)
{
for (int a = 0; a < 5; a++)
{
for (int b = 0; b < 5; b++)
{
if (M[si + 1] - 97 == Karr[a][b] - 65)
{
if (i == a)
{
E[si] = Karr[i][(j + 1) % 5] - 65;
E[si + 1] = Karr[a][(b + 1) % 5] - 65;
}
else if (j == b)
{
E[si] = Karr[(i + 1) % 5][j] - 65;
E[si + 1] = Karr[(a + 1) % 5][b] - 65;
}
else
{
E[si] = Karr[i][b] - 65;
E[si + 1] = Karr[a][j] - 65;
}
}
}
}
}
}
}
}
printf("ȣ (빮) : ");
for (i = 0; i < M_len; i++)
{
C[i] = E[i] + 65;
printf("%c", C[i]);
}
printf("\n");
system("pause");
system("cls");
}
void Decry()
{
char M[length]; //
int D[length]; //ȣȭ
char C[length]; //ȣ
char K[k_length] = { 0 }; //Ű
char K_arr[25] = { 0 }; //Ű迭
char Karr[5][5] = { 0 }; //2 Ű迭
int C_len;
int K_len;
int i;
int j;
char alpha[25] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
int len = 0;
int si = 0;
printf(">>Playfair ȣȭ<<\n");
printf("ȣ Է(빮) : ");
scanf("%s", C);
C_len = strlen(C);
if (C_len % 2 == 1)
{
M[C_len] = 'X';
}
M[C_len + 1] = '\0';
C_len = strlen(C);
for (i = 0; i < C_len; i++)
{
if ('J' == M[i])
{
M[i] = 'I';
}
}
printf("Ű Է(빮 and 7 ) : ");
scanf("%s", K);
K_len = strlen(K);
for (i = 0; i < K_len; i++)
{
if ('J' == K[i])
{
K[i] = 'I';
}
}
for (i = 0; i < K_len; i++)
{
for (j = 0; j < 25; j++)
{
if (K[i] == alpha[j])
{
K_arr[si] = alpha[j];
alpha[j] = 0;
si++;
break;
}
}
}
for (i = 0; i < 25; i++)
{
if (0 != alpha[i])
{
K_arr[si] = alpha[i];
alpha[i] = 0;
si++;
}
}
si = 0;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
Karr[i][j] = K_arr[si];
si++;
}
}
printf(">>key table<<\n");
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("%c ", Karr[i][j]);
}
printf("\n");
}
for (si = 0; si < C_len; si += 2)
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (C[si] - 65 == Karr[i][j] - 65)
{
for (int a = 0; a < 5; a++)
{
for (int b = 0; b < 5; b++)
{
if (C[si + 1] - 65 == Karr[a][b] - 65)
{
if (i == a)
{
D[si] = Karr[i][((j - 1) + 5) % 5] - 65;
D[si + 1] = Karr[a][((b - 1) + 5) % 5] - 65;
}
else if (j == b)
{
D[si] = Karr[((i - 1) + 5) % 5][j] - 65;
D[si + 1] = Karr[((a - 1) + 5) % 5][b] - 65;
}
else
{
D[si] = Karr[i][b] - 65;
D[si + 1] = Karr[a][j] - 65;
}
}
}
}
}
}
}
}
printf(" (ҹ) : ");
for (i = 0; i < C_len; i++)
{
M[i] = D[i] + 97;
printf("%c", M[i]);
}
printf("\n");
system("pause");
system("cls");
}
|
C
|
#include<stdio.h>
int main()
{
int i=1,n;
printf("inter the limit:-");
scanf("%d",&n);
abc:
printf("%d\n",i);
i+=1;
if (i<=n)
{
goto abc;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "LinkedList.h"
#include "bicicletas.h"
#include "parser.h"
#include "utn_lemos.h"
int controller_List(LinkedList* pArrayList)
{
int retorno=-1;
int tam=ll_len(pArrayList);
eBicicleta* auxBike;
if(pArrayList!=NULL)
{
if(ll_isEmpty(pArrayList)==0)
{
printf("ID NOMBRE TIPO TIEMPO\n");
for(int i=0;i<tam;i++)
{
auxBike = (eBicicleta*) ll_get(pArrayList,i);
if( auxBike != NULL)
{
mostrarBicicleta (auxBike);
retorno=1;
}
}
}
else
{
printf("No hay bicicletas que mostrar\n\n");
retorno=0;
}
}
return retorno;
}
int controller_load(char* path , LinkedList* pArrayList)
{
int retorno=1;
FILE* pFile;
ll_clear(pArrayList);
pFile = fopen(path, "r");
if(path!=NULL && pArrayList!=NULL && pFile!=NULL)
{
if(!parser_FromText(pFile,pArrayList))
retorno=0;
}
fclose(pFile);
return retorno;
}
int controller_save(char* path , LinkedList* pArrayList)
{
int retorno=1;
int tam=ll_len(pArrayList);
FILE* pFile;
eBicicleta* aux;
if(pArrayList!=NULL)
{
pFile = fopen(path,"w");
if(pFile!=NULL)
{
fprintf(pFile,"id,nombre,tipo,tiempo\n");
for(int i=0;i<tam;i++)
{
aux = (eBicicleta*) ll_get(pArrayList,i);
fprintf(pFile,"%d,%s,%s,%d\n",aux->id_bike,aux->nombre,aux->tipo,aux->tiempo);
}
retorno=0;
}
fclose(pFile);
}
return retorno;
}
int lastId(LinkedList* pArrayList)
{
int retorno=-1;
int mayor=0;
int flag=0;
eBicicleta* aux;
int tam=ll_len(pArrayList);
if(pArrayList!=NULL)
{
for(int i=0;i<tam;i++)
{
aux = (eBicicleta*) ll_get(pArrayList,i);
if(aux!=NULL)
{
if(aux->id_bike > mayor || flag==0)
{
mayor = aux->id_bike;
flag = 1;
}
}
}
retorno = mayor;
}
return retorno;
}
int compareTipo (void* datoA , void* datoB)
{
int retorno=0;
if(strcmp(((eBicicleta*) datoA)->tipo,((eBicicleta*) datoB)->tipo) > 0)
retorno=1;
if(strcmp(((eBicicleta*) datoA)->tipo,((eBicicleta*) datoB)->tipo) < 0)
retorno=-1;
return retorno;
}
int compareTiempo (void* datoA , void* datoB)
{
int retorno=0;
if(((eBicicleta*) datoA)->tiempo > ((eBicicleta*) datoB)->tiempo)
retorno=1;
if(((eBicicleta*) datoA)->tiempo < ((eBicicleta*) datoB)->tiempo)
retorno=-1;
return retorno;
}
int controller_sort(LinkedList* pArrayList)
{
int retorno=1;
LinkedList* auxLinkedList;
auxLinkedList = ll_newLinkedList();
if(pArrayList!=NULL && auxLinkedList!=NULL)
{
auxLinkedList=ll_clone(pArrayList);
printf("Ordenando. Aguarde un momento...\n");
if(!ll_sort(auxLinkedList,compareTiempo,1))
{
if(!ll_sort(auxLinkedList,compareTipo,1))
{
controller_List(auxLinkedList);
retorno=0;
}
else
printf("Error. Operacion cancelada\n");
}
}
return retorno;
}
int getRandom ()
{
int aleatorio;
aleatorio = rand()% 21 + 50; //aleatorio entre 50 y 70
return aleatorio;
}
void* add_randomTime (void* bicicleta)
{
((eBicicleta*) bicicleta)->tiempo = getRandom();
return bicicleta;
}
int controller_asignTime (LinkedList* pArrayList)
{
int retorno=1;
if(pArrayList!=NULL)
{
pArrayList=ll_map(pArrayList, add_randomTime);
retorno=0;
}
return retorno;
}
int filtrarTipoBMX (void* element)
{
int retorno=0;
eBicicleta* aux;
aux = (eBicicleta*) element;
if(strcmp(aux->tipo,"BMX")==0)
{
retorno=1;
}
return retorno;
}
int filtrarTipoPlayera (void* element)
{
int retorno=0;
eBicicleta* aux;
aux = (eBicicleta*) element;
if(strcmp(aux->tipo,"PLAYERA")==0)
{
retorno=1;
}
return retorno;
}
int filtrarTipoMTB (void* element)
{
int retorno=0;
eBicicleta* aux;
aux = (eBicicleta*) element;
if(strcmp(aux->tipo,"MTB")==0)
{
retorno=1;
}
return retorno;
}
int filtrarTipoPaseo (void* element)
{
int retorno=0;
eBicicleta* aux;
aux = (eBicicleta*) element;
if(strcmp(aux->tipo,"PASEO")==0)
{
retorno=1;
}
return retorno;
}
int controller_filterByType(LinkedList* pArrayList)
{
int retorno=1;
int opcion=0;
LinkedList* auxLinkedList;
auxLinkedList = ll_newLinkedList();
if(pArrayList!=NULL && auxLinkedList!=NULL)
{
if(utn_getNumeroInt(&opcion, "Ingrese tipo: \n1.bmx\n2.playera\n3.mtb\n4.paseo\n", "Error", 1, 4, 2)==0)
{
switch(opcion)
{
case 1:
auxLinkedList = ll_filter(pArrayList, filtrarTipoBMX);
if(controller_save("bicicletasXtipo.csv",auxLinkedList))
printf("Error al guardar el listado\n");
else
printf("Datos guardados\n");
break;
case 2:
auxLinkedList = ll_filter(pArrayList, filtrarTipoPlayera);
if(controller_save("bicicletasXtipo.csv",auxLinkedList))
printf("Error al guardar el listado\n");
else
printf("Datos guardados\n");
break;
case 3:
auxLinkedList = ll_filter(pArrayList, filtrarTipoMTB);
if(controller_save("bicicletasXtipo.csv",auxLinkedList))
printf("Error al guardar el listado\n");
else
printf("Datos guardados\n");
break;
case 4:
auxLinkedList = ll_filter(pArrayList, filtrarTipoPaseo);
if(controller_save("bicicletasXtipo.csv",auxLinkedList))
printf("Error al guardar el listado\n");
else
printf("Datos guardados\n");
break;
}
}
else
printf("Operacin cancelada");
}
return retorno;
}
|
C
|
/*
* File: queue.c
* Author: THE MASTER
*
* Created on April 26, 2018, 11:40 AM
*/
#include "config.h"
#include "queue.h"
/*
*
*/
void q_add_cmd(uint8_t cmd)
{
queue[++q_index];
}
void q_clear()
{
}
bool q_is_empty()
{
return true;
}
uint8_t q_read(uint8_t index)
{
uint8_t i = 0;
return i;
}
/* The following function returns not q_point but the index of the next command
* with the highest priority. Priority is assigned as follows (highest being #1):
*
* 1. Internal alarm (smoke detection from motherboard)
* 2. Internal tamper
* Any non-supervisory message from receiver (alarm, tamper, low batt on a FIFO
* basis)
* Internal low battery
* Internal supervisory
* EOL (YET TO BE IMPLEMENTED FOR ANY DEVICE IN THIS PROTOCOL)
* Any supervisory message received over RF
* 3. Listen Mode/test
*/
uint8_t q_get_next_index()
{
// if (queue_cmd.contains(q_alarm)){}
return 0;
}
bool q_contains(uint8_t cmd)
{
return true;
}
void init_queue()
{
q_clear();
}
|
C
|
#include "libmorse.h"
const char morse_table[45][MORSE_LENGTH] PROGMEM = {
"._._._", // .
"_.._.", // /
"_____", // 0
".____", // 1
"..___", // 2
"...__", // 3
"...._", // 4
".....", // 5
"_....", // 6
"__...", // 7
"___..", // 8
"____.", // 9
"___...", // :
"_._._.", // ;
"", // <
"_..._", // =
"", // >
"..__..", // ?
".__._.", // @
"._", // A
"_...", // B
"_._.", // C
"_..", // D
".", // E
".._.", // F
"__.", // G
"....", // H
"..", // I
".___", // J
"_._", // K
"._..", // L
"__", // M
"_.", // N
"___", // O
".__.", // P
"__._", // Q
"._.", // R
"...", // S
"_", // T
".._", // U
"..._", // V
".__", // W
"_.._", // X
"_.__", // Y
"__.." // Z
};
char temp_string[MESSAGE_LENGTH];
char morse_code[MESSAGE_LENGTH*MORSE_LENGTH];
void init_morse(int string_index) {
// Initialize the upper string
temp_string[0] = '\0';
strcat(temp_string, messages[string_index]);
convert_case();
// Initialize morse code as empty
morse_code[0] = '\0';
translate_message();
// Play the morse code
play_morse();
}
// Convert the message to uppercase
void convert_case() {
int i;
for (i = 0; temp_string[i] != '\0'; i++ ) {
if (temp_string[i] >= 0x61 && temp_string[i] <= 0x7A) { // if letter is lowercase
temp_string[i] = temp_string[i] - 0x33; // change it to uppercase
} else {
temp_string[i] = temp_string[i]; // if not lowercase just copy character over
}
}
}
// Translate the message into morse code
void translate_message() {
int i; // initalize the index variable
for ( i = 0; temp_string[i] != '\0'; i++ ) { // loop until the null terminator
if(temp_string[i] == ' ') { // check for space
strcat(morse_code, (char*) "/"); // add space character for morse
} else { // if not a space
strcat(morse_code, (char*) ":"); // add new character symbol and add the character code
uint8_t lookup_index = temp_string[i] - 0x2E;
strcat_P(morse_code, morse_table[lookup_index]);
}
}
}
// Play back the morse code on the buzzer
void play_morse() {
for (int i = 0; morse_code[i] != '\0'; i++ ) {
if ( morse_code[i] == '.') {
dot();
} else if ( morse_code[i] == '_' ) { dash(); }
else if ( morse_code[i] == '/') { space_silence(); }
else if ( morse_code[i] == ':') { letter_silence(); }
if ( ( morse_code[i+1] == '/' ) || ( morse_code[i+1] == ':') ) {}
if ( ( morse_code[i] != '/' ) || ( morse_code[i+1] != ':') ) { unit_silence(); }
}
}
// Play a morse "dot"
void dot() {
set_buzzer(ON);
_delay_ms(UNIT_LENGTH);
set_buzzer(OFF);
}
// Play a morse "Dash"
void dash() {
set_buzzer(ON);
for (int i = 0; i < 3; i++) {
_delay_ms(UNIT_LENGTH);
}
set_buzzer(OFF);
}
// Play the morse space
void space_silence() {
set_buzzer(OFF);
for (int i = 0; i < 7; i++) {
_delay_ms(UNIT_LENGTH);
}
}
// Play the space between letters
void letter_silence() {
set_buzzer(OFF);
for (int i = 0; i < 3; i++) {
_delay_ms(UNIT_LENGTH);
}
}
// Place the space between units
void unit_silence() {
set_buzzer(OFF);
_delay_ms(UNIT_LENGTH);
}
// Set the buzzer state
void set_buzzer(bool state) {
/*switch (state) {
case ON:
DDR(PORT_BUZZER) |= (1<<PIN_BUZZER);
case OFF:
DDR(PORT_BUZZER) &= ~(1<<PIN_BUZZER);
}*/
if( state == ON ){
DDR(PORT_BUZZER) |= (1<<PIN_BUZZER);
PORT(PORT_LED) |= (1<<PIN_LED);
//DDRD |= (1<<PORTD5);
} else if ( state == OFF ) {
DDR(PORT_BUZZER) &= ~(1<<PIN_BUZZER);
PORT(PORT_LED) &= ~(1<<PIN_LED);
//DDRD &= ~(1<<PORTD5);
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct bisect_terms {char* term_good; char* term_bad; } ;
/* Variables and functions */
char* _ (char*) ;
int error (char*,...) ;
scalar_t__ get_terms (struct bisect_terms*) ;
scalar_t__ one_of (char const*,char*,char*,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ printf (char*,char*,...) ;
__attribute__((used)) static int bisect_terms(struct bisect_terms *terms, const char *option)
{
if (get_terms(terms))
return error(_("no terms defined"));
if (option == NULL) {
printf(_("Your current terms are %s for the old state\n"
"and %s for the new state.\n"),
terms->term_good, terms->term_bad);
return 0;
}
if (one_of(option, "--term-good", "--term-old", NULL))
printf("%s\n", terms->term_good);
else if (one_of(option, "--term-bad", "--term-new", NULL))
printf("%s\n", terms->term_bad);
else
return error(_("invalid argument %s for 'git bisect terms'.\n"
"Supported options are: "
"--term-good|--term-old and "
"--term-bad|--term-new."), option);
return 0;
}
|
C
|
// Implements a dictionary's functionality
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include "dictionary.h"
#include <string.h>
#include <strings.h>
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int TABLE_SIZE = 50000;
// Hash table //set N to a higher number to capture data.
node *table[TABLE_SIZE];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
//returns true if found else return false.
int index = hash(word);
//make a cursor node which points to the head of the hash table
node *cursor = table[index];
//for loop to go through the list until the final node is reached.
for (node *temp = cursor; temp != NULL; temp = temp->next)
{
if (strcasecmp(temp->word,word) == 0)
{
return true;
}
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
//for this hash get the lengh of the string then we will sum the value of the characters.
unsigned int hashvalue = 0;
for (int i = 0; i < strlen(word); i++)
{
hashvalue += tolower(word[i]);
hashvalue = (hashvalue * tolower(word[i])) % TABLE_SIZE;
}
return hashvalue;
}
int counter = 0;
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// this function returns true if all data loaded into hash table, - false if there is an error.
// Stores all data in a hash table, the hash function assigns an index to each word.
// First, to add new data to hash table, allocate memory for nodes then add data to the node. this format copies words into the character array strcpy(n->word, "hello"); to set next pointer n->next = NULL;
// OPEN DICTIONARY FILE and read the contents.
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
fprintf(stderr, "There has been an error");
return false;
}
//wordlist is a character array of the words.
char wordlist[LENGTH + 1];
//while fscanf != EOF print the words into the character array word
while (fscanf(file, "%s", wordlist) != EOF)
{
//Keep track of how many nodes are being made
counter++;
//for each new node allocate memory.
node *newNode = malloc(sizeof(node));
//check for null
if (newNode == NULL)
{
return 1;
}
//initialize the new node by copying the word to the next node.
strcpy(newNode->word, wordlist);
newNode->next = NULL;
//add to hash table each element of the hashtable is a linked list!
//if index != NULL newNode->word points to the old head of the list
int index = hash(wordlist);
//if the index is not yet assigned, put the newest node at the head of this index.
if (table[index] == NULL)
{
table[index] = newNode;
}
//if the index is assigned point the existing head node at the table[index] and then make the new node the head.
else
{
//makes the next the new head
newNode->next = table[index];
//head points to the new node.
table[index] = newNode;
}
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// keep track of how many nodes have been added.
return counter;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// for each of hash table 'buckets' the memory must be free'd.
//make a cursor which points to the head node. this cursor will work through the linked lists making each = NULL, freeing the memory.
node *tmp = NULL;
node *cursor = NULL;
for (int i = 0; i < TABLE_SIZE; i++)
{
cursor = table[i];
while (cursor != NULL)
{
tmp = cursor;
cursor = cursor->next;
free(tmp);
}
}
return true;
}
|
C
|
//
// Created by miguelchauca on 05/05/19.
//
#include "listaMemoria.h"
void *serealizarDataMemoria(st_memoria *memoria, size_t *size_buffer) {
st_size_memoria sizeMemoria;
sizeMemoria.ip = strlen(memoria->ip) + 1;
sizeMemoria.puerto = strlen(memoria->puerto) + 1;
sizeMemoria.numero = sizeof(memoria->numero);
size_t sizeBuffer = sizeMemoria.ip + sizeMemoria.puerto + sizeMemoria.numero + sizeof(sizeMemoria);
*size_buffer = sizeBuffer;
void *buffer = malloc(sizeBuffer);
int offset = 0;
memcpy(buffer, &sizeMemoria, sizeof(sizeMemoria));
offset += sizeof(sizeMemoria);
memcpy((buffer + offset), memoria->ip, sizeMemoria.ip);
offset += sizeMemoria.ip;
memcpy((buffer + offset), memoria->puerto, sizeMemoria.puerto);
offset += sizeMemoria.puerto;
memcpy((buffer + offset), &memoria->numero, sizeMemoria.numero);
return buffer;
}
st_memoria *deserealizarDataMemoria(void *buffer, size_t *size_buffer) {
st_size_memoria sizeMemoria;
st_memoria *dataMemoria = malloc(sizeof(st_memoria));
int offset = 0;
memcpy(&sizeMemoria, buffer, sizeof(sizeMemoria));
offset += sizeof(sizeMemoria);
dataMemoria->ip = malloc(sizeMemoria.ip);
memcpy(dataMemoria->ip, (buffer + offset), sizeMemoria.ip);
offset += sizeMemoria.ip;
dataMemoria->puerto = malloc(sizeMemoria.puerto);
memcpy(dataMemoria->puerto, (buffer + offset), sizeMemoria.puerto);
offset += sizeMemoria.puerto;
memcpy(&dataMemoria->numero, (buffer + offset), sizeMemoria.numero);
offset += sizeMemoria.numero;
if (size_buffer) {
*size_buffer = offset;
}
return dataMemoria;
}
st_data_memoria *deserealizarMemoria(void *buffer, size_t size_buffer) {
st_data_memoria * dataMemoria = malloc(sizeof(st_memoria));
dataMemoria->listaMemorias = list_create();
size_t offset = sizeof(int);
memcpy(&dataMemoria->numero,buffer, sizeof(int));
size_t sizeBufferAux = 0;
st_memoria *memoria;
while (offset < size_buffer) {
memoria = deserealizarDataMemoria((buffer + offset), &sizeBufferAux);
list_add(dataMemoria->listaMemorias, memoria);
offset += sizeBufferAux;
}
return dataMemoria;
}
void destroyMemoria(st_memoria *memoria) {
free(memoria->ip);
free(memoria->puerto);
free(memoria);
}
void destroyListaDataMemoria(st_data_memoria * memoria) {
int i;
st_memoria *memoriaAux;
for (i = 0; i < memoria->listaMemorias->elements_count; i++) {
memoriaAux = list_remove(memoria->listaMemorias, i);
destroyMemoria(memoriaAux);
}
list_destroy(memoria->listaMemorias);
free(memoria);
}
void * serealizarMemoria(st_data_memoria * memoria, size_t * size_buffer){
st_memoria *memoriaAux;
int i;
int offset = sizeof(int);
void *bufferAux = NULL;
void *buffer = NULL;
size_t *sizebufferAux;
size_t sizebuffer = sizeof(int);
t_list *listaBuffes = list_create();
t_list *listaSizeBuffer = list_create();
for (i = 0; i < memoria->listaMemorias->elements_count; i++) {
sizebufferAux = malloc(sizeof(size_t));
*sizebufferAux = 0;
memoriaAux = list_get(memoria->listaMemorias, i);
bufferAux = serealizarDataMemoria(memoriaAux, sizebufferAux);
sizebuffer += *sizebufferAux;
list_add(listaSizeBuffer, sizebufferAux);
list_add(listaBuffes, bufferAux);
}
//juntar todos los pedacitos del buffer
buffer = malloc(sizebuffer);
memcpy(buffer,&memoria->numero, sizeof(int));
for (i = 0; i < listaBuffes->elements_count; i++) {
sizebufferAux = list_get(listaSizeBuffer, i);
bufferAux = list_get(listaBuffes, i);
memcpy((buffer + offset), bufferAux, *sizebufferAux);
offset += *sizebufferAux;
free(bufferAux);
free(sizebufferAux);
}
*size_buffer = sizebuffer;
list_destroy(listaBuffes);
list_destroy(listaSizeBuffer);
return buffer;
}
|
C
|
#include <stdio.h>
#include <string.h>
// Pedro Antonio Estévez Pérez
// Ejercicio 9
/* Realizar una función que reciba por parámetro dos cadenas de caracteres
* y debe concatenar la segunda a la primera. El programa principal imprimirá
* el resultado de la concatenación.*/
/* Para pasar cadenas de caracteres a una función es imprescindible usar
* punteros. Una vez pasada la dificultad de donde ponerlos, el problema
* es trivial. Introducimos las cadenas, llamamos a lafunción, la concatenamos
* y la devolvemos.*/
// La función es un puntero puesto que devuelvo un puntero.
char *concatenar(char *cadena1, char *cadena2) // Lo recibo como valor
{
strcat(cadena1, cadena2); // La nueva cadena sobreescribe a la cadena uno
return cadena1; // Envío el puntero de vuelta
}
int main(void)
{
char *cadena1, *cadena2, *salida;
cadena1 = (char*) malloc(sizeof(char)*100); //Reservo la memoria
cadena2 = (char*) malloc(sizeof(char)*100);
printf("Introduce la primera cadena: ");
gets(cadena1);
printf("Introduce la segunda cadena: ");
gets(cadena2);
//int longitud = strlen(cadena1);
//*(cadena1+longitud) = ' ';
salida = concatenar(cadena1, cadena2); // Envío el puntero y recibo como valor
printf("La union es: %s\n\n", salida);
}
|
C
|
#include <stdio.h>
/**
*int_index - function that searches for an integer
*@array: array pointer to int
*@size: number of element in the array
*@cmp: pointer to a function that receives an int
*Return: int
**/
int int_index(int *array, int size, int (*cmp)(int))
{
int el;
int index;
if (array != NULL && cmp != NULL)
{
if (size <= 0)
return (-1);
for (el = 0; el < size; el++)
{
index = cmp(array[el]);
if (index > 0)
return (el);
}
}
return (-1);
}
|
C
|
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "capnp_c.h"
#include "demo.capnp.h"
#define TRANSFER_LENGTH_MAX (4096)
#define ASSERT_EQ(x, y) do {if(x == y) { } else {printf("Fatal error, Function:%s Line:%d\n", __func__, __LINE__);for(;;) {} }} while(0)
#define EXPECT_BASE(true) \
do { \
printf("[%d] Verifying... Result: ", __LINE__); \
if(true) { \
printf("Successful!\n"); \
} else { \
printf("Error, Function:%s Line:%d\n", __func__, __LINE__); \
} \
} while(0)
#define EXPECT_EQ(x, y) EXPECT_BASE(x == y)
#define EXPECT_CAPN_TEXT_EQ(std, ans) EXPECT_BASE(strcmp(std, (ans).str) == 0 && strlen(std) == (ans).len)
static capn_text chars_to_text(const char *chars) {
capn_text t;
t.len = (int) strlen(chars);
t.str = chars;
t.seg = NULL;
return (t);
}
int main(int argc, char* argv[])
{
uint8_t buf[TRANSFER_LENGTH_MAX];
ssize_t sz = 0;
const char *name = "Jan";
const char *email = "jeehong2015@gmail.com";
const struct Date birth = {
.year = 1992,
.month = 2,
.day = 5,
};
const int16_t phone_numbers = 2;
const char *phone0 = "17717032991";
const char *phone1 = "03922819473";
const struct Person_PhoneNumber pn0 = {
.number = chars_to_text(phone0),
.type = Person_PhoneNumber_Type_mobile,
};
const struct Person_PhoneNumber pn1 = {
.number = chars_to_text(phone1),
.type = Person_PhoneNumber_Type_home,
};
printf("Start!\nBuild time: %s,%s\n", __DATE__, __TIME__);
/* Serializing */
{
struct capn c;
capn_init_malloc(&c);
capn_ptr cr = capn_root(&c);
struct capn_segment *cs = cr.seg;
struct Person p;
p.name = chars_to_text(name);
p.email = chars_to_text(email);
p.birthdate = new_Date(cs);
write_Date(&birth, p.birthdate);
p.phones = new_Person_PhoneNumber_list(cs, 2);
set_Person_PhoneNumber(&pn0, p.phones, 0);
set_Person_PhoneNumber(&pn1, p.phones, 1);
Person_ptr pp = new_Person(cs);
write_Person(&p, pp);
int setp_ret = capn_setp(capn_root(&c), 0, pp.p);
ASSERT_EQ(0, setp_ret);
sz = capn_write_mem(&c, buf, TRANSFER_LENGTH_MAX, 0 /* packed */);
capn_free(&c);
}
printf("Final data length is %d byte(s).\n", sz);
/* Deserializing */
{
struct capn rc;
int init_mem_ret = capn_init_mem(&rc, buf, TRANSFER_LENGTH_MAX, 0 /* packed */);
ASSERT_EQ(0, init_mem_ret);
Person_ptr rroot;
struct Person rp;
rroot.p = capn_getp(capn_root(&rc), 0 /* off */, 1 /* resolve */);
read_Person(&rp, rroot);
EXPECT_CAPN_TEXT_EQ(name, rp.name);
EXPECT_CAPN_TEXT_EQ(email, rp.email);
struct Date birthday;
read_Date(&birthday, rp.birthdate);
EXPECT_EQ(birth.year, birthday.year);
EXPECT_EQ(birth.month, birthday.month);
EXPECT_EQ(birth.day, birthday.day);
EXPECT_EQ(phone_numbers, capn_len(rp.phones));
struct Person_PhoneNumber rpn0;
get_Person_PhoneNumber(&rpn0, rp.phones, 0);
EXPECT_CAPN_TEXT_EQ(phone0, rpn0.number);
EXPECT_EQ(pn0.type, rpn0.type);
struct Person_PhoneNumber rpn1;
get_Person_PhoneNumber(&rpn1, rp.phones, 1);
EXPECT_CAPN_TEXT_EQ(phone1, rpn1.number);
EXPECT_EQ(pn1.type, rpn1.type);
capn_free(&rc);
}
printf("Finish!\n");
return(0);
}
|
C
|
#ifndef JOB_LIST_H
#define JOB_LIST_H
#include <stdlib.h>
#include <stdio.h>
typedef struct list_element
{
int val;
char* command;
char* stat;
struct list_element* next;
} list_element;
typedef enum
{
LIST_OKAY,
LIST_EMPTY,
LIST_HEAD_NULL,
LIST_ELEMENT_NOT_FOUND
} LIST_STATUS;
struct list_element* init_list_head();
LIST_STATUS insert_head(struct list_element** head, int val, char* command, char* stat);
LIST_STATUS insert_tail(struct list_element* head, int val, char* command, char* stat);
LIST_STATUS peek_tail(struct list_element* head, struct list_element** tail);
LIST_STATUS pop_head(struct list_element** head);
LIST_STATUS pop_tail(struct list_element* head);
LIST_STATUS delete_element(struct list_element** head, int val);
LIST_STATUS clear_list(struct list_element* head);
LIST_STATUS update_status(struct list_element* head, int val, char* stat);
const char* convert_list_status_to_enum(LIST_STATUS status);
void print_list(struct list_element* head);
#endif
|
C
|
#include "ArrayEmployees.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int menuEmp()
{
int opcion;
system("cls");
printf("--------Menu de opciones ABM--------\n\n");
printf("1. ALTAS\n");
printf("2. MODIFICAR\n");
printf("3. BAJA\n");
printf("4. INFORMAR\n");
printf("5. Salir del programa.\n\n");
printf("Ingrese opcion: ");
fflush(stdin);
scanf("%d", &opcion);
return opcion;
}
int formateoNombre(char nombre[])
{
int i=0;
int ret=0;
if(nombre!=NULL&&strlen(nombre)>0)
{
ret=1;
strlwr(nombre);
nombre[0]=toupper(nombre[0]);
while(nombre[i]!='\0')
{
if(isspace(nombre[i]))
{
nombre[i+1]=toupper(nombre[i+1]);
}
i++;
}
}
return ret;
}
void mostrarEmpleado(Employee x)
{
printf("[ID]: %d \nNOMBRE: %s \nAPELLIDO: %s \nSALARIO: %.2f \nSECTOR: %d \n",
x.id,
x.name,
x.lastName,
x.salario,
x.sector);
// x.isEmpty);
}
int mostrarEmpleados(Employee vec[], int tam)
{
int ret=0;
if(vec!=NULL&&tam>0)
{
ret=1;
system("cls");
printf("---------LISTA DE EMPLEADOS---------\n");
for(int i=0; i<tam; i++)
{
if(vec[i].isEmpty==0)
{
mostrarEmpleado(vec[i]);
printf("------------------------------------\n");
}
}
}
return ret;
}
int initEmployees(Employee vec[], int tam)
{
int ret=0;
if(vec!=NULL&&tam>0)
{
for(int i=0; i<tam; i++)
{
vec[i].isEmpty=1;
}
ret=1;
}
return ret;
}
int buscarLibre(Employee vec[], int tam)
{
int libre=-1;
if(vec!=NULL&&tam>0)
{
for(int i=0; i<tam; i++)
{
if(vec[i].isEmpty==1)
{
libre=i;
break;
}
}
}
return libre;
}
int ingresarStr(char texto[],char* campo,int tam)
{
int ret=0;
char auxStr[100];
if(texto!=NULL&&campo!= NULL&&tam>0)
{
printf("Ingrese %s:\n",texto);
fflush(stdin);
gets(auxStr);
while(strlen(auxStr)==0 || strlen(auxStr)>tam)
{
printf("Invalido. Reingresar %s:\n",texto);
fflush(stdin);
gets(auxStr);
}
strcpy(campo, auxStr);
formateoNombre(campo);
ret=1;
}
return ret;
}
int ingresarIntPos(char texto[],int* campo,int limite)
{
int ret=0;
int auxInt;
if(limite==0)
{
limite=2147483647;
}
if(texto!=NULL&&campo!=NULL&&limite >(-1))
{
printf("Ingrese %s: \n",texto);
fflush(stdin);
scanf("%d",&auxInt);
while(auxInt<0||auxInt>limite)
{
printf("Invalido. Reingresar %s.\n",texto);
fflush(stdin);
scanf("%d",&auxInt);
}
*campo=auxInt;
ret=1;
}
return ret;
}
int ingresarFloatPos(char texto[],float* campo,int limite)
{
int ret=0;
float auxFloat;
if(limite==0)
{
limite=2147483647;
}
if(texto!=NULL&&campo!=NULL&&limite >(-1) )
{
printf("Ingrese %s: \n",texto);
fflush(stdin);
scanf("%f",&auxFloat);
while(auxFloat<0||auxFloat>limite)
{
printf("Invalido. Reingresar %s.\n",texto);
fflush(stdin);
scanf("%f",&auxFloat);
}
*campo=auxFloat;
ret=1;
}
return ret;
}
int addEmployee(Employee* list, int tam, int* nextId)
{
int ret=0;
if(list!=NULL&&tam>0&&nextId!=NULL)
{
int actualIndex;
system("cls");
actualIndex=buscarLibre(list,tam);
printf("\nEl ID del nuevo usuario es %d.\n",*nextId);
list[actualIndex].id=(*nextId);
(*nextId)++;
system("pause");
system("cls");
ingresarStr("nombre",list[actualIndex].name,51);
ingresarStr("apellido",list[actualIndex].lastName,51);
ingresarFloatPos("salario",&list[actualIndex].salario,0);
ingresarIntPos("sector",&list[actualIndex].sector,0);
list[actualIndex].isEmpty=0;
printf("\nEmpleado cargado con exito.\n");
system("pause");
ret=1;
}
return ret;
}
int editEmployee(Employee* list, int tam, int index)
{
int ret=0;
if(list!=NULL&&tam>0&&index>-1)
{
int opcion;
printf("------------------------------------\n");
mostrarEmpleado(list[index]);
printf("------------------------------------\n");
printf("Que desea modificar?\n[1]-Nombre\n[2]-Apellido\n[3]-Salario\n[4]-Sector\n");
fflush(stdin);
scanf("%d",&opcion);
switch(opcion)
{
case 1:
ingresarStr("nombre",list[index].name,51);
printf("\nNombre cambiado exitosamente. \n");
system("pause");
break;
case 2:
ingresarStr("apellido",list[index].lastName,51);
printf("\nApellido cambiado exitosamente. \n");
system("pause");
break;
case 3:
ingresarFloatPos("salario",&list[index].salario,0);
printf("\nSalario cambiado exitosamente. \n");
system("pause");
break;
case 4:
ingresarIntPos("sector",&list[index].sector,0);
printf("\nSector cambiado exitosamente. \n");
system("pause");
break;
}
ret=1;
}
return ret;
}
int findEmployeeByID(Employee* list, int tam)
{
int posicion=-1;
if(list!=NULL&&tam>0)
{
int userInput;
printf("Ingrese ID que desea modificar: ");
fflush(stdin);
scanf("%d",&userInput);
for(int i=0; i<tam; i++)
{
if(list[i].isEmpty==1)
{
continue;
}
else if(list[i].id==userInput)
{
posicion=i;
break;
}
}
if(posicion==(-1))
{
printf("No se encontro dicho ID.\t");
system("pause");
}
}
return posicion;
}
int removeEmployee(Employee* list,int tam, int index)
{
int ret=0;
if(list!=NULL && tam>0 && index>(-1))
{
char rta;
ret=1;
printf("------------------------------------\n");
mostrarEmpleado(list[index]);
printf("------------------------------------\n");
printf("\n Desea eliminar permanentemente este empleado? s/n \n");
fflush(stdin);
scanf("%c",&rta);
if(rta=='s')
{
list[index].isEmpty=1;
strcpy(list[index].name,"");
strcpy(list[index].lastName,"");
list[index].sector= 0;
list[index].salario= 0;
printf("Empleado eliminado exitosamente.\n");
system("pause");
}
else
{
printf("No se eliminara al empleado.\n");
system("pause");
}
}
return ret;
}
int checkEmpleadoCargado(Employee* list,int tam)
{
int check=0;
if(list!= NULL && tam>0)
{
for(int i=0; i<tam; i++)
{
if(list[i].isEmpty==0)
{
check=1;
return check;
break;
}
}
}
return check;
}
int sortEmployees(Employee* list, int tam,int orden)
{
int ret=0;
if(list!=NULL&&tam>0&&(orden==1||orden==2))
{
Employee aux;
int ordenado;
if(orden==2)
{
ordenado=-1;
}
else
{
ordenado=orden;
}
int i, j;
for(i=0; i<tam-1; i++)
{
for(j=i+1; j<tam; j++)
{
if(list[i].isEmpty==1||list[j].isEmpty==1) // si alguna ubicacion esta vacia, no la somete a comparacion y salta a la siguiente
{
continue;
}
else if((strcmp(list[i].lastName,list[j].lastName)==ordenado)||(strcmp(list[i].lastName,list[j].lastName)==0&&
list[i].sector>list[j].sector)) // ordena por apellido con el orden dependiendo del usuario (
{
aux=list[i];
list[i]=list[j];
list[j]=aux;
}
}
}
ret=1;
}
return ret;
}
int promedioSalarios(Employee* list, int tam)
{
int totalSalarios=0;
int totalAsalariados=0;
int promedio;
int empleadosBienRemunerados=0;
for(int i=0; i<tam; i++)
{
if(list[i].isEmpty==1)
{
continue;
}
totalSalarios+=list[i].salario;
totalAsalariados++;
}
promedio=totalSalarios/totalAsalariados;
for(int i=0; i<tam; i++)
{
if(list[i].isEmpty==1)
{
continue;
}
if(list[i].salario>promedio)
{
empleadosBienRemunerados++;
}
}
printf("\n SUMA TOTAL DE SUELDOS: $%d\n CANTIDAD DE ASALARIADOS: %d\n\n %d empleados superan el sueldo promedio de $%d.\n\n",totalSalarios,totalAsalariados,empleadosBienRemunerados,promedio);
return totalAsalariados;
}
int menuInformar(Employee* list,int tam)
{
int ret=0;
if(list!=NULL&&tam>0)
{
int orden;
printf("Desea ordenar de forma ascendente (1) o descendente (2)?\n");
fflush(stdin);
scanf("%d",&orden);
sortEmployees(list,tam,orden);
mostrarEmpleados(list,tam);
promedioSalarios(list,tam);
system("pause");
ret=1;
}
return ret;
}
int salirABM()
{
char rta;
printf("\nDesea salir del programa? s/n \n");
fflush(stdin);
scanf("%c",&rta);
rta=tolower(rta);
if(rta=='s')
{
return 1;
}
else
{
return 0;
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#define MAX 8
int main(){
int n;
char jogador1[MAX], jogador2[MAX];
scanf("%d", &n);
while(n > 0){
setbuf(stdin, NULL);
scanf("%s", &jogador1);
setbuf(stdin, NULL);
scanf("%s", &jogador2);
if(strcmp(jogador1, jogador2) == 0){
if(strcmp(jogador1, "pedra") == 0){
printf("Sem ganhador\n");
}else if(strcmp(jogador1, "papel") == 0){
printf("Ambos venceram\n");
}else if(strcmp(jogador1, "ataque") == 0){
printf("Aniquilacao mutua\n");
}
}else{
if(strcmp(jogador1, "pedra") == 0){
if(strcmp(jogador2, "ataque") == 0){
printf("Jogador 2 venceu\n");
}else{
printf("Jogador 1 venceu\n");
}
}else if(strcmp(jogador1, "papel") == 0){
printf("Jogador 2 venceu\n");
}else if(strcmp(jogador1, "ataque") == 0){
printf("Jogador 1 venceu\n");
}
}
n--;
}
return(0);
}
|
C
|
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include "fastcommon/logger.h"
#include "fastcommon/hash.h"
#include "fastcommon/shared_func.h"
#include "keyword_hashtable.h"
#include "server_global.h"
#include "wordsegment.h"
#define MAX_KEYWORD_CHARS 16 //Note: an english word as a char
int word_segment_next_word(const char **pp, const char *end, string_t *ch,
const bool silence)
{
ch->str = (char *)*pp;
if (*pp >= end) {
return ENOENT;
}
while ((*pp < end) && (FC_IS_LOWER_LETTER(**pp) ||
FC_IS_DIGITAL(**pp)))
{
(*pp)++;
}
ch->len = (char *)*pp - ch->str;
if (ch->len > 0) {
return 0;
}
if ((((unsigned char)**pp) & 0xF0) == 0xE0) { //Chinese character
ch->len = end - *pp;
if (ch->len < 3) {
logError("file: "__FILE__", line: %d, "
"invalid Chinese characters length: %d",
__LINE__, ch->len);
*pp += 1;
return EINVAL;
}
if (!(((((unsigned char)ch->str[1]) & 0xC0) == 0x80) &&
((((unsigned char)ch->str[2]) & 0xC0) == 0x80)))
{
logError("file: "__FILE__", line: %d, "
"invalid Chinese characters: %.*s",
__LINE__, ch->len, ch->str);
*pp += 1;
return EINVAL;
}
ch->len = 3;
*pp += 3;
return 0;
} else {
if (**pp != ' ' && !silence) {
logWarning("file: "__FILE__", line: %d, "
"invalid character: %c(0x%02x)",
__LINE__, **pp, ((unsigned char)**pp) & 0xFF);
}
*pp += 1; //skip unknown char
return EINVAL;
}
}
static void remove_spaces_after_chinese(string_t *input)
{
unsigned char *p;
unsigned char *end;
unsigned char *dest;
dest = (unsigned char *)input->str;
p = (unsigned char *)input->str;
end = (unsigned char *)input->str + input->len;
while (p < end) {
if (FC_IS_CHINESE_UTF8_CHAR(p, end)) {
*dest++ = *p++;
*dest++ = *p++;
*dest++ = *p++;
while (p < end && *p == ' ') {
p++;
}
} else {
*dest++ = *p++;
}
}
input->len = dest - (unsigned char *)input->str;
}
void keyword_normalize(string_t *keyword, string_t *formatted,
string_t *concated)
{
char *p;
char *end;
char *dest;
int chinses_count;
chinses_count = 0;
p = keyword->str;
end = keyword->str + keyword->len;
while (p < end) {
if (FC_IS_CHINESE_UTF8_CHAR(p, end)) {
chinses_count++;
p += 3;
} else {
if (*p == '-' && ((p > keyword->str) && (p + 1 < end))) {
if (FC_IS_LETTER(*(p-1)) && FC_IS_LETTER(*(p+1))) {
*p = ' ';
}
}
p++;
}
}
word_segment_normalize(keyword, formatted);
FC_STRING_TRIM(formatted);
if ((chinses_count > 0) || (memchr(formatted->str, ' ',
formatted->len) == NULL))
{
concated->len = 0;
return;
}
dest = concated->str;
end = formatted->str + formatted->len;
for (p=formatted->str; p<end; p++) {
if (*p != ' ') {
*dest++ = *p;
}
}
concated->len = dest - concated->str;
}
void word_segment_normalize(const string_t *input, string_t *output)
{
unsigned char *p;
unsigned char *end;
unsigned char *dest;
int space_count;
int chinses_count;
space_count = chinses_count = 0;
dest = (unsigned char *)output->str;
p = (unsigned char *)input->str;
end = (unsigned char *)input->str + input->len;
while (p < end) {
if (FC_IS_UPPER_LETTER(*p)) { //uppercase letter
*dest++ = *p++ + 32; //to lowercase
} else if (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n' ||
*p == '\f' || *p == '\a' || *p == '\b' || *p == '\v')
{ //space chars
*dest++ = ' ';
space_count++;
p++;
} else if (*p == '-') {
*dest++ = *p;
if ((p > (unsigned char *)input->str) && (p + 1 < end)) {
if (FC_IS_LETTER(*(p-1)) && FC_IS_LETTER(*(p+1))) {
dest--; //ignore -
}
}
p++;
} else if (FC_IS_CHINESE_UTF8_CHAR(p, end)) {
int old_char;
old_char = ((*p & 0x1F) << 12) | ((*(p + 1) & 0x3F) << 6) | (*(p + 2) & 0x3F);
if (old_char == 0x3000) { //blank char
*dest++ = ' ';
space_count++;
} else if (old_char >= 0xFF01 && old_char <= 0xFF5E) { //full char
*dest = old_char - 0xFEE0;
if (FC_IS_UPPER_LETTER(*dest)) {
*dest += 32;
}
dest++;
} else {
*dest++ = *p;
*dest++ = *(p + 1);
*dest++ = *(p + 2);
chinses_count++;
}
p += 3;
} else {
*dest++ = *p++;
}
}
output->len = dest - (unsigned char *)output->str;
if (space_count > 0 && chinses_count > 0) {
remove_spaces_after_chinese(output);
}
}
static int compare_offset(const void *p1, const void *p2)
{
return ((CombineKeywordInfo *)p1)->offset.start -
((CombineKeywordInfo *)p2)->offset.start;
}
static int compare_combo_keywords(const void *p1, const void *p2)
{
int i;
int result;
const CombineKeywordInfo *key1;
const CombineKeywordInfo *key2;
key1 = (const CombineKeywordInfo *)p1;
key2 = (const CombineKeywordInfo *)p2;
if (key1->karray.count < key2->karray.count) {
return 1;
} else if (key1->karray.count > key2->karray.count) {
return -1;
} else {
for (i=0; i<key1->karray.count; i++) {
if ((result=fc_string_compare(key1->karray.keywords + i,
key2->karray.keywords + i)) != 0)
{
return result;
}
}
}
return 0;
}
static bool combo_keywords_equals(CombineKeywordInfo *combo1,
CombineKeywordInfo *combo2)
{
int i;
if (combo1->karray.count != combo2->karray.count) {
return false;
}
if (!(combo1->offset.start == combo2->offset.start &&
combo1->offset.end == combo2->offset.end))
{
return false;
}
for (i=0; i<combo1->karray.count; i++) {
if (!fc_string_equal(combo1->karray.keywords + i,
combo2->karray.keywords + i))
{
return false;
}
}
return true;
}
static bool combo_keywords_exist(ComboKeywordGroup *group,
CombineKeywordInfo *combo_keyword)
{
int i;
for (i=0; i<group->count; i++) {
if (combo_keywords_equals(group->rows + i, combo_keyword)) {
return true;
}
}
return false;
}
static void combine_nearby_two_keywords(ComboKeywordGroup *group,
ComboKeywordGroup *combined, ComboKeywordGroup *single)
{
int i, k;
int keyword_count;
CombineKeywordInfo *row;
CombineKeywordInfo overlapps[MAX_KEYWORDS_COUNT];
keyword_count = combined->count;
memcpy(overlapps, combined->rows,
sizeof(CombineKeywordInfo) * keyword_count);
combined->count = 0;
for (i=0; i<keyword_count; i++) {
for (k=0; k<single->count; k++) {
if (!combo_keyword_is_overlapp(overlapps + i,
single->rows + k))
{
if (combined->count >= MAX_KEYWORDS_COUNT) {
logWarning("file: "__FILE__", line: %d, "
"keywords exceeds %d",
__LINE__, MAX_KEYWORDS_COUNT);
break;
}
row = combined->rows + combined->count++;
*row = overlapps[i];
combo_keywords_append(row, single->rows + k);
break;
}
}
if (k == single->count) {
if (group->count < MAX_KEYWORDS_COUNT) {
if (!combo_keywords_exist(group, overlapps + i)) {
group->rows[group->count++] = overlapps[i];
}
} else {
logWarning("file: "__FILE__", line: %d, "
"keywords exceeds %d",
__LINE__, MAX_KEYWORDS_COUNT);
}
}
}
}
static void word_segment_combine_nearby_keywords(ComboKeywordGroup *group)
{
int i, k;
bool matched[MAX_KEYWORDS_COUNT];
ComboKeywordGroup combined;
ComboKeywordGroup single;
CombineKeywordInfo *row;
single = *group;
combined.count = 0;
group->count = 0;
memset(matched, 0, sizeof(matched));
for (i=0; i<single.count; i++) {
for (k=i+1; k<single.count; k++) {
if (!combo_keyword_is_overlapp(single.rows + i,
single.rows + k))
{
matched[i] = matched[k] = true;
row = combined.rows + combined.count++;
*row = single.rows[i];
combo_keywords_append(row, single.rows + k);
break;
}
}
if (!matched[i]) {
if (group->count < MAX_KEYWORDS_COUNT) {
group->rows[group->count++] = single.rows[i];
} else {
logWarning("file: "__FILE__", line: %d, "
"keywords exceeds %d",
__LINE__, MAX_KEYWORDS_COUNT);
}
}
}
//logInfo("combined count ===== %d", combined.count);
while (combined.count > 0) {
combine_nearby_two_keywords(group, &combined, &single);
//logInfo("combined count ===== %d", combined.count);
}
}
void keywords_unique(KeywordArray *karray)
{
string_t *p;
string_t *end;
string_t *dest;
end = karray->keywords + karray->count;
p = dest = karray->keywords + 1;
while (p < end) {
if (fc_string_compare(p, p - 1) != 0) {
if (dest != p) {
*dest = *p;
}
dest++;
}
p++;
}
karray->count = dest - karray->keywords;
}
static void sorted_keyword_records_unique(KeywordRecords *results)
{
KeywordArray *p;
KeywordArray *end;
end = results->rows + results->count;
for (p=results->rows; p<end; p++) {
if (p->count > 1) {
keywords_unique(p);
}
}
}
void keyword_records_unique(KeywordRecords *results)
{
KeywordArray *p;
KeywordArray *end;
end = results->rows + results->count;
for (p=results->rows; p<end; p++) {
if (p->count > 1) {
qsort(p->keywords, p->count, sizeof(string_t),
(int (*)(const void *p1, const void *p2))fc_string_compare);
keywords_unique(p);
}
}
}
static void output_results_unique(ComboKeywordGroup *combo_results,
KeywordRecords *results)
{
CombineKeywordInfo *p;
CombineKeywordInfo *end;
KeywordArray *dest;
end = combo_results->rows + combo_results->count;
for (p=combo_results->rows; p<end; p++) {
qsort(p->karray.keywords,
p->karray.count,
sizeof(string_t),
(int (*)(const void *p1, const void *p2))fc_string_compare);
}
qsort(combo_results->rows, combo_results->count,
sizeof(CombineKeywordInfo), compare_combo_keywords);
dest = results->rows;
*dest++ = combo_results->rows[0].karray;
p = combo_results->rows + 1;
while (p < end) {
if (compare_combo_keywords(p, p - 1) != 0) {
*dest++ = p->karray;
}
p++;
}
results->count = dest - results->rows;
sorted_keyword_records_unique(results);
}
static int word_segment_output(CombineKeywordInfo *keywords, const int count,
WordSegmentArray *output)
{
CombineKeywordInfo *p;
CombineKeywordInfo *end;
KeywordIterator iterator;
ComboKeywordGroup *group;
ComboKeywordGroup combo_results;
int end_offset;
int end_offset1;
int end_offset2;
int max_end_offset;
int min_end_offset;
int i;
if (count == 0) {
output->results.count = 0;
return ENOENT;
} else if (count == 1) {
output->results.count = 1;
output->results.rows[0] = keywords->karray;
return 0;
}
qsort(keywords, count, sizeof(CombineKeywordInfo), compare_offset);
/*
logInfo("keyword count: %d", count);
for (i=0; i<count; i++) {
logInfo("offset: %d, %.*s(%d)", keywords[i].offset.start,
FC_PRINTF_STAR_STRING_PARAMS(keywords[i].karray.keywords[0]),
keywords[i].karray.keywords[0].len);
}
*/
p = keywords;
end = keywords + count;
memset(&iterator, 0, sizeof(iterator));
group = iterator.groups - 1;
while (p < end) {
group++;
if (group - iterator.groups >= MAX_KEYWORDS_COUNT) {
logWarning("file: "__FILE__", line: %d, "
"keywords group exceeds %d",
__LINE__, MAX_KEYWORDS_COUNT);
break;
}
group->rows[group->count++] = *p; //first keyword
end_offset1 = p->offset.end;
p++;
if (p == end) {
break;
}
if (p->offset.start >= end_offset1) { //next group
continue;
}
group->rows[group->count++] = *p; //second keyword
end_offset2 = p->offset.end;
p++;
if (end_offset1 > end_offset2) {
max_end_offset = end_offset1;
min_end_offset = end_offset2;
} else {
max_end_offset = end_offset2;
min_end_offset = end_offset1;
}
while (p < end && (p->offset.start < min_end_offset ||
p->offset.end <= max_end_offset))
{
end_offset = p->offset.end;
if (end_offset < min_end_offset) {
min_end_offset = end_offset;
} else if (end_offset > max_end_offset) {
max_end_offset = end_offset;
}
if (group->count < MAX_KEYWORDS_COUNT) {
group->rows[group->count++] = *p;
} else {
logWarning("file: "__FILE__", line: %d, "
"keywords exceeds %d",
__LINE__, MAX_KEYWORDS_COUNT);
}
p++;
}
if (group->count > 2) {
word_segment_combine_nearby_keywords(group);
}
}
iterator.count = (group - iterator.groups) + 1;
logInfo("iterator.count: %d", iterator.count);
for (i=0; i<iterator.count; i++) {
int k;
int m;
logInfo("group[%d], count: %d", i, iterator.groups[i].count);
for (k=0; k<iterator.groups[i].count; k++) {
printf("start: %d, end: %d, keywords: ",
iterator.groups[i].rows[k].offset.start,
iterator.groups[i].rows[k].offset.end);
for (m=0; m<iterator.groups[i].rows[k].karray.count; m++) {
printf("%.*s, ", FC_PRINTF_STAR_STRING_PARAMS(
iterator.groups[i].rows[k].karray.keywords[m]));
}
printf("\n");
}
}
keyword_iterator_expand(&iterator, &combo_results);
output_results_unique(&combo_results, &output->results);
return 0;
}
#define SET_KEYWORD_INFO(kinfo, hentry) \
do { \
if (hentry->similar.len == 0) { \
break; \
} \
if (kinfo - keywords >= MAX_KEYWORDS) { \
logWarning("file: "__FILE__", line: %d, " \
"too many keywords exceeds %d", \
__LINE__, MAX_KEYWORDS); \
p = save_point = end; \
break; \
} \
kinfo->offset.start = start - output->holder.str; \
kinfo->offset.end = p - output->holder.str; \
kinfo->karray.keywords[0] = hentry->similar; \
kinfo->karray.count = 1; \
kinfo++; \
} while (0)
static int word_segment_do_split(WordSegmentArray *output)
{
#define MAX_KEYWORDS (MAX_KEYWORDS_COUNT * MAX_KEYWORDS_COUNT)
string_t word;
string_t chrs[MAX_KEYWORD_CHARS];
CombineKeywordInfo keywords[MAX_KEYWORDS];
CombineKeywordInfo *kinfo;
KeywordHashEntry *hentry;
const char *p;
const char *end;
const char *start;
const char *save_point;
int chr_count;
int key_count;
kinfo = keywords;
p = output->holder.str;
end = output->holder.str + output->holder.len;
while (p < end) {
start = p;
if (word_segment_next_word(&p, end, &word, false) != 0) {
continue;
}
chrs[0] = word;
chr_count = 1;
save_point = p;
while (true) {
/*
logInfo("finding: %.*s(%d), chr_count: %d",
(int)(p - start), start, (int)(p - start), chr_count);
*/
if ((hentry=keyword_hashtable_find_ex(&g_server_vars.kh_context,
chrs, chr_count)) != NULL)
{
SET_KEYWORD_INFO(kinfo, hentry);
} else {
break;
}
while ((p < end) && (*p == ' ')) {
p++;
}
if (word_segment_next_word(&p, end, &word, false) != 0) {
break;
}
if (chr_count == MAX_KEYWORD_CHARS) {
logWarning("file: "__FILE__", line: %d, "
"too many keyword chars exceed %d, keywords: %.*s",
__LINE__, MAX_KEYWORD_CHARS, (int)(p - start), start);
break;
}
chrs[chr_count++] = word;
}
p = save_point; //rewind
}
key_count = kinfo - keywords;
//logInfo("found keyword key_count: %d", key_count);
return word_segment_output(keywords, key_count, output);
}
int word_segment_split(const string_t *input, WordSegmentArray *output)
{
if (input->len <= sizeof(output->buff)) {
output->holder.str = output->buff;
} else {
output->holder.str = (char *)malloc(input->len);
if (output->holder.str == NULL) {
logError("file: "__FILE__", line: %d, "
"malloc %d bytes fail", __LINE__, input->len);
return ENOMEM;
}
}
word_segment_normalize(input, &output->holder);
return word_segment_do_split(output);
}
void word_segment_free_result(WordSegmentArray *array)
{
if (array->holder.str != NULL && array->holder.str != array->buff) {
free(array->holder.str);
array->holder.str = NULL;
}
}
static int word_segment_find_slink_keyword(const char **p,
const char *end, const int64_t current_id, string_t *keyword)
{
string_t word;
string_t chrs[MAX_KEYWORD_CHARS];
KeywordHashEntry *hentry;
QAEntry qa;
const char *save_point;
int chr_count;
while (*p < end) {
keyword->str = (char *)*p;
if (word_segment_next_word(p, end, &word, true) != 0) {
continue;
}
chrs[0] = word;
chr_count = 1;
save_point = *p;
while (true) {
/*
logInfo("finding: %.*s(%d), chr_count: %d",
(int)(*p - keyword->str), keyword->str, (int)(*p - keyword->str), chr_count);
*/
if ((hentry=keyword_hashtable_find_ex(&g_server_vars.kh_context,
chrs, chr_count)) != NULL)
{
if (hentry->similar.len > 0) {
if (question_index_find_single_keyword(&g_server_vars.
ki_context, &hentry->similar, &qa) == 0)
{
if (qa.answer->id != current_id) {
keyword->len = (char *)*p - keyword->str;
return 0;
}
}
}
} else {
break;
}
while ((*p < end) && (**p == ' ')) {
(*p)++;
}
if (word_segment_next_word(p, end, &word, true) != 0) {
break;
}
if (chr_count == MAX_KEYWORD_CHARS) {
logWarning("file: "__FILE__", line: %d, "
"too many keyword chars exceed %d, keywords: %.*s",
__LINE__, MAX_KEYWORD_CHARS, (int)(*p - keyword->str), keyword->str);
break;
}
chrs[chr_count++] = word;
}
*p = save_point; //rewind
}
return ENOENT;
}
int word_segment_add_slinks(const string_t *origin,
const int64_t current_id, FastBuffer *output)
{
#define SLINK_START_TAG_STR "[[slink]]"
#define SLINK_START_TAG_LEN (sizeof(SLINK_START_TAG_STR) - 1)
#define SLINK_CLOSE_TAG_STR "[[/slink]]"
#define SLINK_CLOSE_TAG_LEN (sizeof(SLINK_CLOSE_TAG_STR) - 1)
const char *p;
const char *end;
const char *start;
string_t keyword;
int result;
fast_buffer_clear(output);
p = origin->str;
end = origin->str + origin->len;
while (p < end) {
start = p;
if (word_segment_find_slink_keyword(&p, end, current_id,
&keyword) != 0)
{
if ((result=fast_buffer_append_buff(output, start,
end - start)) != 0)
{
return result;
}
break;
}
if ((result=fast_buffer_append_buff(output, start,
keyword.str - (char *)start)) != 0)
{
return result;
}
if ((result=fast_buffer_append_buff(output, SLINK_START_TAG_STR,
SLINK_START_TAG_LEN)) != 0)
{
return result;
}
if ((result=fast_buffer_append_string2(output,
&keyword)) != 0)
{
return result;
}
if ((result=fast_buffer_append_buff(output, SLINK_CLOSE_TAG_STR,
SLINK_CLOSE_TAG_LEN)) != 0)
{
return result;
}
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a[100],N,i,e;
printf("鳤\n");
scanf("%d",&N);
printf("\n");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
printf("Ԫ\n");
scanf("%d",&a[N]);
N++;
for(i=0;i<N;i++)
{
printf("%d ",a[i]);
}
printf("\n");
printf("ɾԪ\n");
a[N-1]=0;
N--;
for(i=0;i<N;i++)
{
printf("%d ",a[i]);
}
printf("\n");
printf("ֵԪ\n");
printf("ҪҵԪֵ");
scanf("%d",&e);
for(i=0;i<N;i++)
{
if(a[i]==e)
{
printf("ԪλΪ%d\n",i+1);
break;
}
}
printf("λòԪ\n");
printf("Ҫҵλã");
scanf("%d",&e);
printf("λԪΪ%d",a[e-1]);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jzeybel <jzeybel@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/27 18:40:20 by jzeybel #+# #+# */
/* Updated: 2021/02/09 19:21:28 by jzeybel ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/ft_printf.h"
void init_flags(t_flags *flags, int i)
{
flags->c = 0;
if (i)
flags->i = 0;
flags->n = 1;
flags->sign = 1;
flags->minus = 0;
flags->zero = 0;
flags->width = 0;
flags->prec = -1;
}
void ft_parsing(va_list ap, const char *format, t_flags *flags)
{
while (format[flags->i])
{
if ((format[flags->i] == '%') && format[flags->i + 1])
ft_parse_flag(ap, format, flags);
else
writec_buf(format[flags->i]);
if (format[flags->i] == '\0')
break ;
flags->i++;
}
}
int ft_printf(const char *format, ...)
{
va_list ap;
t_flags flags;
init_buf();
init_flags(&flags, 1);
va_start(ap, format);
ft_parsing(ap, format, &flags);
va_end(ap);
return (display_buf(1));
}
|
C
|
#ifndef RIO_H
#define RIO_H
/* RIO -- Robust I/O, 减少低字节IO时用户态和内核态的切换 */
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/errno.h>
#include <stdio.h>
#include <event2/event.h>
#define RIO_BUFSIZE 4096
typedef struct _Rio{
int rioFd; //与缓冲区绑定的文件描述符的编号
size_t rioCnt; //缓冲区中还未读取的字节数
char *rioBufptr; //当前下一个未读取字符的地址
char rioBuf[RIO_BUFSIZE];
struct event* ev;
ssize_t (*readn)(struct _Rio *rp, void *usrbuf, size_t n);
ssize_t (*readline)(struct _Rio *rp, void *usrbuf, size_t maxlen);
ssize_t (*writen)(struct _Rio *rp, void *usrbuf, size_t n);
ssize_t (*full_readline)(struct _Rio *rp, void *usrbuf, size_t maxlen);
} Rio;
Rio* newRio(int fd, struct event* ev);
void freeRio(Rio *rp);
#endif
/*
Rio * rio = newRio(fd);
int n =rio -> readn(rio, userbuf, n);
free(rio);
*/
|
C
|
#include <stdio.h>
int main()
{
int n;
while(1)
{
long long int ans[80]={0};
scanf("%d",&n);
if(n==0)
break;
for(int i=0;i<=n;i++)
{
if(i<=2)
ans[i]=i;
else
ans[i]=ans[i-1]+ans[i-2];
}
printf("%lld\n",ans[n]);
}
return 0;
}
|
C
|
// markov chain estimation of pi
// ahc : andy c.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "markov_pi.h"
#define TRIAL_COUNT 500000
int main()
{
int i, hits = 0;
double pi;
Posn ctr;
ctr.x = ctr.y = 0.5;
for (i=0; i<TRIAL_COUNT; i++) {
Posn p = getPosn();
if (dist(p,ctr) <= 0.5)
hits++;
}
pi = 4.0 * (double)hits / (double)TRIAL_COUNT;
printf("%f\n",pi);
return 0;
}
Posn getPosn()
{
Posn p;
p.x = (double)rand() / (double)RAND_MAX;
p.y = (double)rand() / (double)RAND_MAX;
return p;
}
double dist(Posn a, Posn b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx*dx + dy*dy);
}
|
C
|
#include "key.h"
#include "delay.h"
//
//ذֵ
//mode:0,֧;1,֧;
//0ûκΰ
//1WKUP WK_UP
//ע˺Ӧȼ,KEY0>KEY1>KEY2>WK_UP!!
uint8_t KEY_Scan(uint8_t mode)
{
static uint8_t key_up=1; //ɿ־
if(mode==1)key_up=1; //֧
if(key_up&&(KEY0==0||KEY1==0||KEY2==0||WK_UP==1))
{
delay_ms(10);
key_up=0;
if(KEY0==0) return KEY0_PRES;
else if(KEY1==0) return KEY1_PRES;
else if(KEY2==0) return KEY2_PRES;
else if(WK_UP==1) return WKUP_PRES;
}else if(KEY0==1&&KEY1==1&&KEY2==1&&WK_UP==0)key_up=1;
return 0; //ް
}
|
C
|
#include <stdio.h>
void printArray(const int []);
int main(void)
{
int iNumbers[3] = {2, 4, 6};
printArray(iNumbers);
} // end main
void printArray(const int num[]) // pass by reference, but read-only
{
int x;
printf("\nArray contents are: ");
for (x = 0; x < 3; x++)
{
printf("%d ", num[x]);
}
} // end printArray
|
C
|
#include <stdio.h>
main(){
char *s = "#include <stdio.h>%cmain(){%c%cchar *s = %c%s%c;%c%cint i = %i;%c%cchar file[10] = %cSully_X.c%c;%c%cwhile (i >= 0){%c%c%cfile[6] = 48 + i;%c%c%cfprintf(fopen(file, %cw%c), s, 10, 10, 9, 34, s, 34, 10, 9, i, 10, 9, 34, 34, 10, 9, 10, 9, 9, 10, 9, 9, 34, 34, 10, 9, 9, 10, 9, 10, 10);%c%c%ci--;%c%c}%c}%c";
int i = 5;
char file[10] = "Sully_X.c";
while (i >= 0){
file[6] = 48 + i;
fprintf(fopen(file, "w"), s, 10, 10, 9, 34, s, 34, 10, 9, i, 10, 9, 34, 34, 10, 9, 10, 9, 9, 10, 9, 9, 34, 34, 10, 9, 9, 10, 9, 10, 10);
i--;
}
}
|
C
|
/*OS homework1-1 Finding the highest value */
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define INF 1000000
int arr[10][10];
int maxs[30];
int blocknum[10];
int result;
int x[9] = { 0, 0, 0, 3, 3, 3, 6, 6, 6};
int y[9] = { 0, 3, 6, 0, 3, 6, 0, 3, 6}; //arr[x[blocknum + i]][y[blocknum + j]]) (0<=i<3, 0<=j<3)로 블록 내부에 있는 9개의 수에 접근한다.
void* findmax(void* data)
{
int maxx = -INF;
int num = *(int*)data;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(maxx < arr[x[num] + i][y[num] + j])
maxx = arr[x[num] + i][y[num] + j]; //update highest value of block #num
pthread_exit((void*)maxx);
}
void* findmax2(void* data)
{
int rst = -INF;
for(int i=0;i<9;i++)
if(rst<maxs[i])
rst = maxs[i]; //update highest value
pthread_exit((void*) rst);
}
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout); //파일 입출력
pthread_t t[10];
for(int i=0;i<9;i++)
blocknum[i] = i; //blocknum setting
for(int i=0;i<10;i++)
maxs[i] = 0; // 각 블록의 최댓값을 0으로 초기화
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
scanf("%d",&arr[i][j]);
for(int i=0;i<9;i++)
pthread_create(&t[i],NULL,findmax,(void *)&blocknum[i]); //thread create
for(int i=0;i<9;i++)
pthread_join(t[i],&maxs[i]);
pthread_create(&t[9],NULL,findmax2,NULL);
pthread_join(t[9],&result);
// for(int i=0;i<9;i++)
// printf("Highest value of Block %d : %d\n",i,maxs[i]);
printf("Highest number : %d\n",result);
}
|
C
|
//quick utility to adjust keyboard backlight brightness on Asus UX32VD
//assumes range 0-3
#include <stdio.h>
#include <fcntl.h>
#define PATH "/sys/class/leds/asus::kbd_backlight/brightness"
#define MAX '3'
int main(int argc, char* argv[]) {
if(argc < 2) {
return -1;
}
int brightness = open(PATH, O_RDWR);
if(brightness == -1) {
return -1;
}
char currentLevel = '0';
read(brightness, ¤tLevel, 1);
if(argv[1][0] == '+' && currentLevel != MAX) {
currentLevel += 1;
}
else if(argv[1][0] == '-' && currentLevel != '0') {
currentLevel -= 1;
}
else {
return -1;
}
write(brightness, ¤tLevel, 1);
close(brightness);
return 0;
}
|
C
|
#ifndef FILE_WAITVERBOSE_H
#define FILE_WAITVERBOSE_H
#include <syscall.h>
#include <errno.h>
// Comme wait mais imprime sur stderr un message clair.
// valeur renvoyée:
// -1: pas de processus fils.
// >0: le processus # s'est terminé.
int waitendverbose(int*status)
{
int ret,etat;
int thid=syscall(SYS_gettid); // le pid dans tous les cas
ret = wait(&etat);
if ( ret<0 ) {
fprintf(stderr,"%d: no event to wait for: %s\n",
thid,strerror(errno));
return -1;
}
if ( WIFEXITED(etat) ) {
fprintf(stderr,"%d: child %d exited with status %d\n",
thid,ret, WEXITSTATUS(etat));
if (status) *status=etat;
return ret;
}
if ( WIFSIGNALED(etat) ) {
fprintf(stderr,"%d: child %d exited due to signal %d\n",
thid,ret, WTERMSIG(etat));
if (status) *status=etat;
return ret;
}
fprintf(stderr,"%d: child %d terminated for a ? reason\n",
thid,ret);
if (status) *status=etat;
return ret;
}
// Attend les événements fin, suspension et réveil d'un fils,
// Renvoie le pid du fils dans *fils et imprime sur stderr
// un message clair.
// valeur renvoyée:
// -1: pas de processus fils.
// 0: le processus fils s'est terminé.
// 1: le processus fils est stoppé.
// 2: le processus fils est réactivé.
int waitallverbose(int*fils)
{
int ret,status;
int thid=syscall(SYS_gettid); // le pid dans tous les cas
ret = waitpid(-1,&status,WUNTRACED|WCONTINUED);
if ( ret<0 ) {
fprintf(stderr,"%d: no event to wait for: %s\n",
thid,strerror(errno));
return -1;
}
if ( WIFEXITED(status) ) {
fprintf(stderr,"%d: child %d exited with status %d\n",
thid,ret, WEXITSTATUS(status));
if (fils) *fils=ret;
return 0;
}
if ( WIFSIGNALED(status) ) {
fprintf(stderr,"%d: child %d exited due to signal %d\n",
thid,ret, WTERMSIG(status));
if (fils) *fils=ret;
return 0;
}
if ( WIFSTOPPED(status) ) {
fprintf(stderr,"%d: child %d stoped due to signal %d\n",
thid,ret, WSTOPSIG(status));
if (fils) *fils=ret;
return 1;
}
if ( WIFCONTINUED(status) ) {
fprintf(stderr,"%d: child %d resumed by signal %d\n",
thid,ret, SIGCONT);
if (fils) *fils=ret;
return 2;
}
fprintf(stderr,"%d: child %d terminated for a ? reason\n",
thid,ret);
if (fils) *fils=ret;
return 0;
}
#endif
|
C
|
#include <stdio.h>
int main()
{
char*cptr = NULL;
float*fptr = NULL;
double*dptr = NULL;
int*iptr = NULL;
printf("Pointer to character takes %d bytes\n",sizeof(cptr));
printf("Pointer to float takes %d bytes\n",sizeof(fptr));
printf("Pointer to double takes %d bytes\n",sizeof(dptr));
printf("Pointer to integer takes %d bytes\n",sizeof(iptr));
return 0;
}
|
C
|
/**
* eCow-logic - Embedded probe main firmware
*
* Copyright (c) 2016 Saint-Genest Gwenael <gwen@agilack.fr>
*
* This file may be distributed and/or modified under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation. (See COPYING.GPL for details.)
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "libc.h"
int atoi(char *s)
{
int result;
int len;
int v;
int i;
/* Get the number of digit */
len = strlen(s);
/* Get highest 10's power factor */
v = 1;
for (i = 1; i < len; i++)
v = v * 10;
/* Compute the value */
result = 0;
for (i = 0; i < len; i++)
{
result = result + ((*s - '0') * v);
s++;
v = v / 10;
}
return result;
}
void *memcpy(void *dst, const void *src, int n)
{
u8 *s;
u8 *d;
s = (u8*)src;
d = (u8*)dst;
while(n)
{
*d = *s;
s ++;
d ++;
n --;
}
return(dst);
}
void *memset(void *dst, int value, int n)
{
u8 *d;
d = (u8 *)dst;
while(n)
{
*d = value;
d++;
n --;
}
return(dst);
}
char * strcat (char *dest, const char *src)
{
char *s1 = dest;
const char *s2 = src;
char c;
/* Find the end of the string. */
do
c = *s1++;
while (c != '\0');
/* Make S1 point before the next character, so we can increment
it while memory is read (wins on pipelined cpus). */
s1 -= 2;
do
{
c = *s2++;
*++s1 = c;
}
while (c != '\0');
return dest;
}
char *strchr(const char *s, int c)
{
char *ptr;
for (ptr = (char *)s; ptr != 0; ptr++)
{
if (*ptr == 0)
break;
if (*ptr == c)
return ptr;
}
return 0;
}
int strcmp(const char *p1, const char *p2)
{
register const unsigned char *s1 = (const unsigned char *) p1;
register const unsigned char *s2 = (const unsigned char *) p2;
unsigned char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
int strncmp(const char *p1, const char *p2, int len)
{
register const unsigned char *s1 = (const unsigned char *) p1;
register const unsigned char *s2 = (const unsigned char *) p2;
unsigned char c1, c2;
do
{
if (len == 0)
return 0;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
len --;
}
while (c1 == c2);
return c1 - c2;
}
char *strcpy(char *dest, const char *src)
{
char *dsave = dest;
while(*src)
{
*dest = *src;
src++;
dest++;
}
*dest = 0;
return dsave;
}
char *strncpy (char *s1, const char *s2, int n)
{
char c;
char *s = s1;
--s1;
if (n >= 4)
{
int n4 = n >> 2;
for (;;)
{
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
if (--n4 == 0)
goto last_chars;
}
n = n - (s1 - s) - 1;
if (n == 0)
return s;
goto zero_fill;
}
last_chars:
n &= 3;
if (n == 0)
return s;
do
{
c = *s2++;
*++s1 = c;
if (--n == 0)
return s;
}
while (c != '\0');
zero_fill:
do
*++s1 = '\0';
while (--n > 0);
return s;
}
int strlen(char *str)
{
int count;
count = 0;
while(*str)
{
count ++;
str++;
}
return(count);
}
/* EOF */
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
void create(struct node **);
void display(struct node *);
int survivor(struct node **, int);
int main()
{
struct node *head = NULL;
int survive, skip;
create(&head);
printf("The persons in circular list are:\n");
display(head);
printf("Enter the position of person to be killed: ");
scanf("%d", &skip);
skip+=1;
survive = survivor(&head, skip);
printf("The person to survive is : %d\n\n", survive);
free(head);
return 0;
}
int survivor(struct node **head, int k)
{
struct node *p, *q;
int i;
q = p = *head;
while (p->next != p)
{
for (i = 0; i < k - 1; i++)
{
q = p;
p = p->next;
}
q->next = p->next;
printf("%d has been killed.\n", p->num);
free(p);
p = q->next;
}
*head = p;
return (p->num);
}
void create (struct node **head)
{
struct node *temp, *rear;
int a,n, ch;
printf("\nEnter number of persons: ");
scanf("%d", &n);
for(int i=1;i<n+1;i++)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->num = i;
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
}
rear = temp;
}
rear->next = *head;
}
void display(struct node *head)
{
struct node *temp;
temp = head;
printf("%d ", temp->num);
temp = temp->next;
while (head != temp)
{
printf("%d ", temp->num);
temp = temp->next;
}
printf("\n");
}
|
C
|
#include "monty.h"
/**
* pall - Print all values in the stack
* @stack: Double pointer to the top of the stack
* @n_line: The line of the file the command was found
*/
void pall(stack_t **stack, unsigned int n_line)
{
stack_t *tmp;
(void) n_line;
tmp = *stack;
while (tmp != NULL)
{
printf("%d\n", tmp->n);
tmp = tmp->next;
}
}
/**
* pint - Print the top element of the stack
* @stack: Double pointer to the top of the stack
* @n_line: The line of the file the command was found
*/
void pint(stack_t **stack, unsigned int n_line)
{
if (*stack == NULL)
{
printf("L%u: can't pint, stack empty\n", n_line);
rq.opcode = 1;
}
if (rq.opcode != 1)
printf("%d\n", (*stack)->n);
}
/**
* pop - removes the top element of the stack
* @stack: pointer to the stack
* @n_line: current line number
*/
void pop(stack_t **stack, unsigned int n_line)
{
stack_t *kill_node, *tmp;
tmp = *stack;
if (tmp == NULL)
{
printf("L%u: can't pop an empty stack\n", n_line);
rq.opcode = 1;
}
if (rq.opcode != 1)
{
kill_node = tmp;
*stack = tmp->next;
if (tmp != NULL)
tmp->prev = NULL;
free(kill_node);
}
}
/**
* swap - swap elemnts into the list
* @stack: Double pointer to the top the stack
* @n_line: The line of the file the command was found
*/
void swap(stack_t **stack, unsigned int n_line)
{
stack_t *tmp;
int flag;
tmp = *stack;
if (tmp == NULL || tmp->next == NULL)
{
printf("L%u: can't swap, stack too short\n", n_line);
rq.opcode = 1;
}
if (rq.opcode != 1)
{
flag = tmp->n;
tmp->n = tmp->next->n;
tmp->next->n = flag;
}
}
/**
* add - add the top 2 values of the stack, store sum in second position,
* set *stack to second node, and remove top node
* @stack: Double pointer to the top the stack
* @n_line: The line of the file the command was found
*/
void add(stack_t **stack, unsigned int n_line)
{
stack_t *flag = *stack;
if (flag == NULL || flag->next == NULL)
{
printf("L%u: can't add, stack too short\n", n_line);
rq.opcode = 1;
}
if (rq.opcode != 1)
{
flag->next->n += flag->n;
pop(stack, n_line);
}
}
|
C
|
#ifndef VM_H
#define VM_H
#include <math.h>
#define VM_PI 3.14159265358979323846264338327950288
#define VM_PI_2 1.57079632679489661923132169163975144
#define VM_PI_4 0.785398163397448309615660845819875721
#define VM_PIf ((float)VM_PI)
#define VM_PI_2f ((float)VM_PI_2)
#define VM_PI_4f ((float)VM_PI_4)
/* #############################################################################
* # TYPE DEFINITIONS
* #############################################################################
*/
typedef struct vec3 {
float x;
float y;
float z;
} vec3;
typedef struct mat4 {
float m[4][4];
} mat4;
/* #############################################################################
* # COMMON MATH FUNCTIONS
* #############################################################################
*/
extern float vm_invsqrt(float number) {
union {
float f;
uint32_t i;
} conv;
float x2;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
conv.f = number;
conv.i = 0x5f3759df - (conv.i >> 1);
conv.f = conv.f * (threehalfs - (x2 * conv.f * conv.f));
return conv.f;
}
extern float vm_rad(float degree) {
return degree * VM_PIf / 180.0f;
}
extern float vm_deg(float radians) {
return radians * 180.0f / VM_PIf;
}
/* #############################################################################
* # VECTOR 3 FUNCTIONS
* #############################################################################
*/
extern vec3 vm_vec3_add(vec3 a, vec3 b) {
vec3 res = {};
res.x = a.x + b.x;
res.y = a.y + b.y;
res.z = a.z + b.z;
return res;
}
extern vec3 vm_vec3_addf(vec3 a, float b) {
vec3 res = {};
res.x = a.x + b;
res.y = a.y + b;
res.z = a.z + b;
return res;
}
extern vec3 vm_vec3_sub(vec3 a, vec3 b) {
vec3 res = {};
res.x = a.x - b.x;
res.y = a.y - b.y;
res.z = a.z - b.z;
return res;
}
extern vec3 vm_vec3_subf(vec3 a, float b) {
vec3 res = {};
res.x = a.x - b;
res.y = a.y - b;
res.z = a.z - b;
return res;
}
extern vec3 vm_vec3_mul(vec3 a, vec3 b) {
vec3 res = {};
res.x = a.x * b.x;
res.y = a.y * b.y;
res.z = a.z * b.z;
return res;
}
extern vec3 vm_vec3_mulf(vec3 a, float b) {
vec3 res = {};
res.x = a.x * b;
res.y = a.y * b;
res.z = a.z * b;
return res;
}
extern vec3 vm_vec3_div(vec3 a, vec3 b) {
vec3 res = {};
res.x = a.x / b.x;
res.y = a.y / b.y;
res.z = a.z / b.z;
return res;
}
extern vec3 vm_vec3_divf(vec3 a, float b) {
float inv = 1.0f / b;
vec3 res = {};
res.x = a.x * inv;
res.y = a.y * inv;
res.z = a.z * inv;
return res;
}
extern vec3 vm_vec3_normalize(vec3 a) {
float scalar = vm_invsqrt(fmaf(a.x, a.x, fmaf(a.y, a.y, a.z * a.z)));
vec3 res = {};
res.x = a.x * scalar;
res.y = a.y * scalar;
res.z = a.z * scalar;
return res;
}
extern vec3 vm_vec3_cross(vec3 a, vec3 b) {
vec3 res = {};
res.x = fmaf(a.y, b.z, -a.z * b.y);
res.y = fmaf(a.z, b.x, -a.x * b.z);
res.z = fmaf(a.x, b.y, -a.y * b.x);
return res;
}
extern vec3 vm_vec3_lerp(vec3 a, vec3 b, float t) {
vec3 res = {};
res.x = fmaf(b.x - a.x, t, a.x);
res.y = fmaf(b.y - a.y, t, a.y);
res.z = fmaf(b.z - a.z, t, a.z);
return res;
}
extern float vm_vec3_length(vec3 a) {
return sqrtf(fmaf(a.x, a.x, fmaf(a.y, a.y, a.z * a.z)));
}
extern float vm_vec3_dot(vec3 a, vec3 b) {
return fmaf(a.x, b.x, fmaf(a.y, b.y, a.z * b.z));
}
/* #############################################################################
* # MATRIX 4x4 FUNCTIONS
* #############################################################################
*/
extern mat4 vm_mat4_zero() {
mat4 res;
res.m[0][0] = 0.0f;
res.m[0][1] = 0.0f;
res.m[0][2] = 0.0f;
res.m[0][3] = 0.0f;
res.m[1][0] = 0.0f;
res.m[1][1] = 0.0f;
res.m[1][2] = 0.0f;
res.m[1][3] = 0.0f;
res.m[2][0] = 0.0f;
res.m[2][1] = 0.0f;
res.m[2][2] = 0.0f;
res.m[2][3] = 0.0f;
res.m[3][0] = 0.0f;
res.m[3][1] = 0.0f;
res.m[3][2] = 0.0f;
res.m[3][3] = 0.0f;
return res;
}
extern mat4 vm_mat4_identity() {
mat4 res;
res.m[0][0] = 1.0f;
res.m[0][1] = 0.0f;
res.m[0][2] = 0.0f;
res.m[0][3] = 0.0f;
res.m[1][0] = 0.0f;
res.m[1][1] = 1.0f;
res.m[1][2] = 0.0f;
res.m[1][3] = 0.0f;
res.m[2][0] = 0.0f;
res.m[2][1] = 0.0f;
res.m[2][2] = 1.0f;
res.m[2][3] = 0.0f;
res.m[3][0] = 0.0f;
res.m[3][1] = 0.0f;
res.m[3][2] = 0.0f;
res.m[3][3] = 1.0f;
return res;
}
extern mat4 vm_mat4_mul(mat4 a, mat4 b) {
mat4 res = {};
int i = 0;
for (; i < 4; ++i) {
int j = 0;
for (; j < 4; ++j) {
res.m[i][j] = a.m[i][0] * b.m[0][j] + a.m[i][1] * b.m[1][j] + a.m[i][2] * b.m[2][j] + a.m[i][3] * b.m[3][j];
}
}
return res;
}
extern mat4 vm_mat4_perspective(float fov, float aspectRatio, float zNear, float zFar) {
float f = 1.0f / tanf(fov * 0.5f);
float fn = 1.0f / (zNear - zFar);
mat4 res = vm_mat4_zero();
res.m[0][0] = f / aspectRatio;
res.m[1][1] = f;
res.m[2][2] = (zNear + zFar) * fn;
res.m[3][2] = -1.0f;
res.m[2][3] = 2.0f * zNear * zFar * fn;
return res;
}
extern mat4 vm_mat4_translate(mat4 src, vec3 b) {
mat4 res = src;
res.m[0][3] = b.x;
res.m[1][3] = b.y;
res.m[2][3] = b.z;
return res;
}
extern mat4 vm_mat4_rotate(mat4 src, float angle, vec3 axis) {
float c = cosf(angle);
vec3 axisn = vm_vec3_normalize(axis);
vec3 v = vm_vec3_mulf(axisn, 1.0f - c);
vec3 vs = vm_vec3_mulf(axisn, sinf(angle));
mat4 rot = vm_mat4_zero();
vec3 a = vm_vec3_mulf(axisn, v.x);
rot.m[0][0] = a.x;
rot.m[1][0] = a.y;
rot.m[2][0] = a.z;
vec3 b = vm_vec3_mulf(axisn, v.y);
rot.m[0][1] = b.x;
rot.m[1][1] = b.y;
rot.m[2][1] = b.z;
vec3 f = vm_vec3_mulf(axisn, v.z);
rot.m[0][2] = f.x;
rot.m[1][2] = f.y;
rot.m[2][2] = f.z;
rot.m[0][0] += c;
rot.m[0][1] -= vs.z;
rot.m[0][2] += vs.y;
rot.m[1][0] += vs.z;
rot.m[1][1] += c;
rot.m[1][2] -= vs.x;
rot.m[2][0] -= vs.y;
rot.m[2][1] += vs.x;
rot.m[2][2] += c;
rot.m[3][0] = 0.0f;
rot.m[3][1] = 0.0f;
rot.m[3][2] = 0.0f;
rot.m[0][3] = 0.0f;
rot.m[1][3] = 0.0f;
rot.m[2][3] = 0.0f;
rot.m[3][3] = 1.0f;
return vm_mat4_mul(src, rot);
}
extern mat4 vm_mat4_lookAt(vec3 eye, vec3 target, vec3 up) {
vec3 f = vm_vec3_normalize(vm_vec3_sub(target, eye));
vec3 s = vm_vec3_normalize(vm_vec3_cross(f, up));
vec3 u = vm_vec3_cross(s, f);
mat4 res = {};
res.m[0][0] = s.x;
res.m[0][1] = s.y;
res.m[0][2] = s.z;
res.m[0][3] = -vm_vec3_dot(s, eye);
res.m[1][0] = u.x;
res.m[1][1] = u.y;
res.m[1][2] = u.z;
res.m[1][3] = -vm_vec3_dot(u, eye);
res.m[2][0] = -f.x;
res.m[2][1] = -f.y;
res.m[2][2] = -f.z;
res.m[2][3] = vm_vec3_dot(f, eye);
res.m[3][3] = 1.0f;
return res;
}
#endif /* VM_H */
|
C
|
#ifndef __MSCHEDULER_H__
#define __MSCHEDULER_H__
#include "../kernel1/OSDefine.h"
#include "mList.h"
#include "task.h"
#define TASK_COUNT_MAX 512
#define TASK_RUNNINGTIME_MAX 20
#define TASKPOOL_ADDRESS 0x2d000
#define TASK_FLAGS_RUN 0x0001 //실행중인 태스크
#define TASK_FLAGS_END 0x0002 //종료 대기중인 태스크
#pragma pack(push, 1)
typedef struct _Task{
WORD taskID; //3~515
WORD flags; //실행중 또는 준비큐에 들어있으면 1, 사용중이 아니면 0
TSS* tss;
void* stackAddress; //스택 주소
int stackSize; //스택 크기
}Task;
struct _TaskManager{
Task* currentTask;
int runningTime; //태스크가 실행되고 경과한 시간
mLList readyTasks; //data:Task*
} g_taskManager;
#pragma pack(pop)
BOOL setEnableScheduler(BOOL enabled);
void initTaskPool(DWORD address);
void schedule();
int createTask(void* handlerAddress, void* stackAddress, int stackSize); //생성한 태스크 ID를 반환. 실패 시 -1를 반환
int deleteTask(WORD taskID);
#endif /*__MSCHEDULER_H__*/
|
C
|
#include"milibreria.h"
/** f1 = fila inicial y c1= columna inicial
f2= fila final y c2 columna finalD
*/
/// valida el movimiento del peon
int mov_peon(char tablero[TAM][TAM], int f1, int c1,int f2,int c2, int setup)
{
/*verificacion si la casilla destino esta en las diagonales
superiores izquierda o derecha adyacente a la casilla origen del peon*/
if ( (((f1-1==f2 && c1-1==c2)|| (f1-1==f2 && c1+1==c2) )&&(c1!=c2 &&f1!=f2)) &&(tablero[f2][c2]!=' ') )
{
return 1;
}
else
{
if (setup==1)
{
printf("\t\t\tNo es valido ese movimiento para el peon.\n");
getch();
};
return 0;
}
}
/// valida el movimiento del caballo
int mov_caballo(char tablero[TAM][TAM],int f1, int c1, int f2, int c2, int setup)
{
//verifica mov L grande
if ( (((f1-2==f2 || f1+2==f2)&&( c1-1==c2 ||c1+1==c2 )) &&(c1!=c2 &&f1!=f2)) &&(tablero[f2][c2]!=' ') )
{
return 1;
}
else
{
//verifica mov L pequea
if( ((( f1-1==f2 ||f1+1==f2)&&(c1-2==c2 ||c1+2==c2)) &&(c1!=c2 &&f1!=f2 )) &&(tablero[f2][c2]!=' ') )
{
return 1;
}
else
{
if (setup==1)
{
printf("\t\t\t\tNo es valido ese movimiento para el caballo\n");
getch();
};
return 0;
}
}
}
/// valida el movimiento del alfil
int mov_alfil(char tablero[TAM][TAM], int f1, int c1, int f2, int c2, int Setup)
{
/* f1 = fila inicial y c1= columna inicial
f2= fila final y c2 columna finalD*/
int dy= abs(f2-f1); // calcula la distancia entre las dos filas escogidas
int dx=abs(c2-c1); // calcula la distancia entre las columnas escogidas en alor absoluto
///condicion de diagonalidad : n1 ==n2
if (((dx == dy) && ( c1!=c2 && f1!=f2) )&&(tablero[f2][c2]!=' '))
{
///verifca las diagonales superiores derecha e izquerda
if ( ( f1-dy==f2) &&( ( c1+dx==c2) || (c1-dx==c2) ) )
{
return 1;
}
else
{
///verifca las diagonales inferiores derecha e izquerda
if (( f1+dy==f2) &&( ( c1+dx==c2) || (c1-dx==c2) ))
{
return 1;
}
else
{
if (Setup==1)
{
printf("\t\t\tNo es valido ese movimiento para el alfil.\n");
getch();
};
return 0;
}
}
}
else
{
if (Setup==1)
{
printf("\t\t\tNo es valido ese movimiento para el alfil.\n");
getch();
};
return 0;
}
//////////////
}
/// valida el movimiento de la torre
int mov_torre(char tablero[TAM][TAM], int f1, int c1, int f2, int c2, int setup)
{
int validacion=1;
int n1= f2-f1;
int n2= c2-c1;
if (tablero[f2][c2]!=' ')
{
/// Caso que se encuentre en la misma fila
if (f1==f2 &&c1!=c2)
{
return 1;
}
else
{
/// Caso que se encuentre en la misma columna
if (c1==c2 && f1!=f2)
{
return 1;
}
else
{
if (setup==1)
{
printf("\t\t\tNo es valido ese movimiento para el Torre.\n");
getch();
};
return 0;
}
}
}
else
{
if (setup==1)
{
printf("\t\t\tNo es valido ese movimiento para el Torre o esta vacia la casilla seleccionada.\n");
getch();
};
return 0;
}
}
/// valida el movimiento del Reina
int mov_reina(char tablero[TAM][TAM], int f1, int c1, int f2, int c2, int setup)
{
/* f1 = fila inicial y c1= columna inicial
f2= fila final y c2 columna finalD */
int dy= abs(f2-f1); // calcula la distancia entre las dos filas escogidas
int dx=abs(c2-c1); // calcula la distancia entre las columnas escogidas en alor absoluto
/* // verificacion si la casilla destino esta en las diagonales superiores e e inferior de la parte izquierda o derecha
o sino comprueba que la casilla destino este en la misma columna o fila que la casilla origen.
en resumen verifica los condiciones de movimientos de la torre y el alfil al mismo tiempo. */
/// Verifica que haya una pieza alli
if (tablero[f2][c2]!=' ' )
{
/// Seccion de verificacion Horizontal y vertical
// Caso de mov horizontal
if ((f1==f2) && (c1!=c2))
{
return 1;
}
else
{
// Caso mov vertical
if ((c1 ==c2) && (f1!= f2))
{
return 1;
}
else
{
/// Seccion de movimiento diagonales
//condicion de diagonalidad : n1 ==n2
gotoxy(0, 0);
printf("dx: %d y dy: %d\n", dx, dy);
getch();
if ( (dx == dy) )
{
///verifca las diagonales superiores derecha e izquerda
if ( ( f1-dy==f2) &&( ( c1+dx==c2) || (c1-dx==c2) ) )
{
return 1;
}
else
{
///verifca las diagonales inferiores derecha e izquerda
if (( f1+dy==f2) &&( ( c1+dx==c2) || (c1-dx==c2) ))
{
return 1;
}
else
{
if (setup==1)
{
printf("\t\t\tNo es valido ese movimiento para el reina.\n");
getch();
};
return 0;
}
}
}
}
}
}
else
{
if (setup==1)
{
printf("\t\t\tNo es valido ese movimiento ya que la casilla selecionada esta vacia.\n");
getch();
};
return 0;
}
///
}
/// valida el movimiento del rey
int mov_rey(char tablero[TAM][TAM], int f1, int c1, int f2, int c2, int setup)
{
if ( (tablero[f2][c2]!=' '))
{
if ((f1-1==f2)&&(c1==c2)) // caso A
{
return 1;
}
else
{
if ((f1-1==f2)&&(c1+1==c2)) //Caso B
{
return 1;
}
else
{
if ((f1==f2)&&(c1+1==c2))//caso C
{
return 1;
}
else
{
if ((f1+1==f2)&&(c1+1==c2) )//CASO D
{
return 1;
}
else
{
if ((f1+1==f2)&&(c1==c2)) // Caso E
{
return 1;
}
else
{
if ((f1+1==f2)&&(c1-1==c2)) // Caso F
{
return 1;
}
else
{
if ((f1==f2)&&(c1-1==c2))// Caso G
{
return 1;
}
else
{
if ((f1-1==f2)&&(c1-1==c2)) //Caso H
{
return 1;
}
else
{
if (setup==1)
{
printf("\tNo es valido el movimiento para el rey\n");
getch();
};
return 0;
}
}
}
}
}
}
}
}
}
else
{
if (setup==1)
{
printf("\tla casilla seleccionada esta vacia y/0 no es valido el movimiento\n");
getch();
};
return 0;
}
}
///Revisa el estado del tablero para comprobar si hay mov posibles y si no, se pierde la partida
int Verifica_perdida(char tablero[TAM][TAM])
{
int contador=0;
int confirmacion=0;
for(int fila=0 ; fila<TAM ; fila++ )
{
for(int columna=0 ; columna<TAM ; columna++ )
{
Verificacion_posiblemovimientos(tablero, fila,columna, &confirmacion);
/*if ( confirmacion!=0)
{
return 1;
}*/
}
}
///nota
// gotoxy(45, 42);
// system("pause");
if (confirmacion==1 || confirmacion!=0)
{
return 1;
}
else
{
///marca de tiempo
gotoxy(45,30);
printf("Ha salido un %d de perder", confirmacion);
gotoxy(45,31);
system("pause");
//
return 0;
}
}
/**
////////////////////////////
///**Parte dle codigo que se verificar si hay movimiento posible al momento de jugar */
///////////////////////////*/
///NOTA: Hay bugs en cuanto a perder cuando realmente si hay posibles mov. pendiente arreglar
/**funcion que identifica el tipo de movimiento que hay una casilla seleccionada
y posteriormente analizar los posibles movimientso de acuerda al tipo de pieza */
void Verificacion_posiblemovimientos(char tablero[TAM][TAM], int fila_inicial,int columna_inicial, int *confirmacion1)
{
int aux=0;
switch (tablero[fila_inicial][columna_inicial])
{
case 'P':
*confirmacion1+= posible_mov_peon(tablero, fila_inicial, columna_inicial);
//marca de tiempo
// gotoxy(0,35);
// printf("\a%d es numero de mov disponibles para el peon\n",posible_mov_peon( tablero, fila_inicial,columna_inicial) );
break;
/// verifica los posible mov del "Peon"
case 'C':
*confirmacion1+= posible_mov_caballo( tablero, fila_inicial,columna_inicial);
//marca de tiempo
// gotoxy(0, 36);
// printf("\a%d es numero de mov disponibles para el caballo\n",posible_mov_caballo( tablero, fila_inicial,columna_inicial) );
break; /// verifica los posible mov del "caballo"
case 'A':
*confirmacion1+= posible_mov_alfil( tablero, fila_inicial,columna_inicial);
//marca de tiempo
// gotoxy(0, 37);
//printf("\a%d es numero de mov disponibles para el alfil\n",posible_mov_alfil( tablero, fila_inicial,columna_inicial) );;
break; /// verifica los posible mov del "ALfil"
case 'T':
{
*confirmacion1+= posible_mov_torre( tablero, fila_inicial,columna_inicial);
//marca de tiempo
// gotoxy(0, 38);
// printf("\a%d es numero de mov disponibles para el torre\n",posible_mov_torre( tablero, fila_inicial,columna_inicial));
break; /// verifica los posible mov del "Torre"
}
case 'D':
*confirmacion1+= posible_mov_reina( tablero, fila_inicial,columna_inicial);
//marca de tiempo
//gotoxy(0, 39);
// printf("\a\%d es numero de mov disponibles para el reina\n",posible_mov_reina( tablero, fila_inicial,columna_inicial) );
break; /// verifica los posible mov del "reina"
case 'R':
*confirmacion1+= posible_mov_rey( tablero, fila_inicial,columna_inicial);
//marca de tiempo
// gotoxy(0, 40);
// printf("\a%d es numero de mov disponibles para el rey\n",posible_mov_rey( tablero, fila_inicial,columna_inicial), *confirmacion1 );
break;
/// verifica los posible mov del "Rey"
case ' ':
break;
/** Si da confirmacion con valor =0, entonces significa que o hya posible movs y se pierde y se manda
ese dato a una funcion que indica que se perdio.
De lo contrario valor 1 indica que sigue el juego y hay hay movimientos disponibles*/
}
}
///verifica si hay posible movimientos si hay un peon en el tablero
/** Revisa desde la posicion que se encuentra e indica si hay piezas posibles a capturar segun si tipo de movimiento*/
int posible_mov_peon(char tablero[TAM][TAM], int f1, int c1)
{
int confirmacion =0;
for(int f2=0 ; f2<TAM ; f2++)
{
for(int c2=0; c2<TAM; c2++ )
{
confirmacion+= mov_peon(tablero, f1, c1, f2, c2, 0);
}
}
return confirmacion;
}
/// verifica si hay posible movimientos si hay un caballo en el tablero //
/** Revisa desde la posicion que se encuentra e indica si hay
piezas posibles a capturar segun si tipo de movimiento*/
int posible_mov_caballo(char tablero[TAM][TAM], int f1, int c1)
{
int confirmacion =0;
for(int f2=0 ; f2<TAM ; f2++)
{
for(int c2=0; c2<TAM; c2++ )
{
confirmacion+= mov_caballo(tablero, f1, c1, f2, c2, 0);
}
}
return confirmacion;
}
///verifica si hay posible movimientos si hay un alfil en el tablero //
/** Revisa desde la posicion que se encuentra e indica si hay
piezas posibles a capturar segun si tipo de movimiento*/
int posible_mov_alfil(char tablero[TAM][TAM], int f1, int c1)
{
int confirmacion =0;
for(int f2=0 ; f2<TAM ; f2++ )
{
for(int c2=0 ; c2<TAM ; c2++ )
{
confirmacion+= mov_alfil(tablero, f1, c1, f2, c2, 0);
}
}
return confirmacion;
}
/// verifica si hay posible movimientos si hay un torre en el tablero //
/** Revisa desde la posicion que se encuentra e indica si hay piezas posibles a capturar segun si tipo de movimiento*/
int posible_mov_torre(char tablero[TAM][TAM], int f1, int c1)
{
int confirmacion =0;
for(int f2=0 ; f2<TAM ; f2++ )
{
for(int c2=0 ; c2<TAM ; c2++ )
{
int registro=0;
confirmacion +=mov_torre(tablero,f1,c1, f2, c2, 0);
registro= mov_torre(tablero, f1, c1, f2, c2, 0);
/// nota de tiempo
// gotoxy(1, 45);
// printf("confirmacion en este momennto en el torre es: %d y posicion es (f1,c1)=(%d, %d) y (f2, c2)=(%d, %d) ",registro, f1, c1, f2, c2);
// system("pause");
}
}
return confirmacion;
}
/// verifica si hay posible movimientos si hay un reina en el tablero //
/** Revisa desde la posicion que se encuentra e indica si hay piezas
posibles a capturar segun si tipo de movimiento*/
int posible_mov_reina(char tablero[TAM][TAM], int f1, int c1)
{
int confirmacion =0;
for(int f2=0 ; f2<TAM ; f2++ )
{
for(int c2=0 ; c2<TAM ; c2++ )
{
confirmacion+= mov_reina(tablero,f1, c1, f2, c2, 0 );
}
}
return confirmacion;
}
/// verifica si hay posible movimientos si hay un rey en el tablero //
/** Revisa desde la posicion que se encuentra e indica si hay piezas
posibles a capturar segun si tipo de movimiento*/
int posible_mov_rey(char tablero[TAM][TAM], int f1, int c1)
{
int confirmacion =0;
for(int f2=0 ; f2<TAM ; f2++ )
{
for(int c2=0 ; c2<TAM ; c2++ )
{
int registro=0;
confirmacion+= mov_rey(tablero, f1, c1, f2, c2, 0);
registro= mov_rey(tablero, f1, c1, f2, c2, 0);
/// nota de tiempo
// gotoxy(1, 45);
// printf("confirmacion en este momennto en el rey es: %d y posicion es (f1,c1)=(%d, %d) y (f2, c2)=(%d, %d) ",registro, f1, c1, f2, c2);
// system("pause");
}
}
return confirmacion ;
}
|
C
|
/** @file BIL105 Spring 2016 HomeWork 1
*
* A program that produces random numbers by two different
* methods. First method is MID-PRNG and the second one is
* LSD-PRNG. User chooses one of the methods the create number.
*
* @author
*
* Name: Yunus Güngör
*
* Student no: 150150701
*
* Date: 09/04/2016
*
* E-Mail: yunusgnr@gmail.com
*
* Tested on: (ITU SSH Server)
*
* Compiler: GCC 4.8.5 20150623
*
* Operating System: Red Hat 4.8.5-4
*
* IDE: None
*
* Operating System: Linux Red Hat 4.8.5-4
*/
#include <stdio.h>
#include <stdlib.h>
void mid_rng(long *number);
void lsd_rng(long *number);
void take_samples (int whichRNG,int *range1,int *range2,int *range3,int *range4,int *range5);
void draw_histogram (int *range1,int *range2,int *range3,int *range4,int *range5);
void map(int number, int *range1,int *range2,int *range3,int *range4,int *range5);
int main ()
{
int whichRNG /* determines which algortihym to use*/;
int range1=0 ,range2=0 ,range3=0 ,range4=0 ,range5=0;//stores mapped data.
int i;
do
{
printf("Which PRNG Algorithm?\n 1.MID-PNRG\n 2.LSD-PNRG\n");
scanf("%d",&whichRNG);
}
while(whichRNG!=1 && whichRNG!=2);
take_samples(whichRNG,&range1,&range2,&range3,&range4,&range5); //get input and create random variables
draw_histogram(&range1,&range2,&range3,&range4,&range5);
return 0;
}
/*creates random variable by mid-rng
MID-RNG:
take the square of number,
Pick out the middle five digits of the square as a random number
*/
void mid_rng(long *number) //creates random variable by mid-rng
{
long long square;
square=(*number)*(*number);
if (square<1000000000) //square has 9 digits
*number=(square/100)%100000; //skip first two digits and take the following five digit
else //square has 10 digits
*number=(square/1000)%100000; //skip first three digits and take the following five digits
return;
}
/*creates random variable by lsd-rng
LSD-RNG:
multiply the number with 73 to get a product.
Pick out the low-order five digits of the product as a random number.
*/
void lsd_rng(long *number)
{
long long product;
product=(*number)*73;
*number=product%100000; //get low-order five digits
return;
}
/*Creates random numbers based on desired method*/
void take_samples(int whichRNG,int *range1,int *range2,int *range3,int *range4,int *range5)
{
int i,num_samples;
long number;
if(whichRNG==1)//mid-rng
{
do
{
printf("Enter the seed:");
scanf("%li",&number);
}
while(number<10000 || number>99999); //check if seed has 5 digits or not
printf("Enter the Number of Samples:");
scanf("%d",&num_samples);
for(i=0;i<num_samples;i++)
{
mid_rng(&number);
map(number%500,range1,range2,range3,range4,range5);
}
}
else //lsd-rng
{
do
{
printf("Enter the seed:");
scanf("%li",&number);
}
while(number<10000 || number>99999 || number%2==0 || number%5==0); //check if seed has 5 digits and its odd and does not end with '5'
printf("Enter the Number of Samples:");
scanf("%d",&num_samples);
for(i=0;i<num_samples;i++)
{
lsd_rng(&number);
map(number%500,range1,range2,range3,range4,range5);
}
}
return;
}
/** Draws histogram based on range array on the screen
*/
void draw_histogram (int *range1,int *range2,int *range3,int *range4,int *range5)
{
int i,sum;
sum=*range1+*range2+*range3+*range4+*range5;
*range1=(float)*range1/sum*100;
printf("0...100");
for(i=0;i<*range1;i++)
printf("*");
printf("(%%");
printf("%d)\n",*range1);
*range2=(float)*range2/sum*100;
printf("101..200");
for(i=0;i<*range2;i++)
printf("*");
printf("(%%");
printf("%d)\n",*range2);
*range3=(float)*range3/sum*100;
printf("201...130");
for(i=0;i<*range3;i++)
printf("*");
printf("(%%");
printf("%d)\n",*range3);
*range4=(float)*range4/sum*100;
printf("301...400");
for(i=0;i<*range4;i++)
printf("*");
printf("(%%");
printf("%d)\n",*range4);
*range5=(float)*range5/sum*100;
printf("401...500");
for(i=0;i<*range5;i++)
printf("*");
printf("(%%");
printf("%d)\n",*range5);
return;
}
/** maps number such as
range1=1..100,
range2=101..200,
range3=201..300,
range4=301..400,
and range5=401..500
*/
void map(int number,int* range1,int* range2,int* range3,int* range4,int* range5)
{
if(number<=100)
*range1+=1;
else if(number<=200)
*range2+=1;
else if(number<=300)
*range3+=1;
else if(number<=400)
*range4+=1;
else if(number<=500)
*range5+=1;
return;
}
|
C
|
#include "my.h"
void string_formatting(char* first_name, char* last_name, int age){
printf("Hello, my name is %s %s, I'm %d.", first_name, last_name, age);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "ryujilib.h"
/* (C) 1992 Ryuji Suzuki (JF7WEX) */
static unsigned char
RCS_ID[] = "$Header: rjslib.cv 1.1 92/09/17 04:11:26 jf7wex Exp $";
/* strtoke() is like strtok(). */
char *
strtoke(char *src, const char *sep)
{
register char const *r;
register char *q;
char *p;
static char *srcptr = NULL;
if (!(srcptr || src ) || !sep) {
srcptr = NULL;
return NULL;
}
if (src) {
srcptr = src;
p = src;
} else {
p = srcptr;
}
for (q = p; *q; q++) {
for (r = sep; *r; r++) {
if (*q == *r) {
*q = NULL;
if (*++q != '\0') {
srcptr = q;
} else {
srcptr = NULL;
}
return p;
}
}
}
return p;
}
/* strcntchr counts that how many key characters does src string includes. */
unsigned
strcntchr(const char *src, const char key)
{
register unsigned i;
register unsigned char j;
register unsigned n = 0;
for (i = 0; (j = src[i]) != (char)'\0'; i++) {
if (j == key) n++;
}
return n;
}
/* fgetsb() is like fgets() but ignores CR */
char *
fgetsb(char buf[], const int n, FILE *fp)
{
register unsigned i;
unsigned char c;
buf[--n] = '\0';
for (i = 0; i <= n; i++) {
if (1 != fread(&c, 1, 1, fp)) {
buf[i] = '\0';
return NULL;
} else buf[i] = c;
if (c == 0x0a) {
buf[++i] = '\0';
break;
}
}
buf[i] = '\0';
return buf;
}
/* getmline() is also like fgets() */
/* principal differences from fgets() is that escape character ('\'), */
/* which can escape CR-LF, is available. */
char *
getmline(FILE *fp)
{
register unsigned i;
register int c;
static unsigned size = 0;
static char *ptr;
if (0 == size) {
size = 512;
ptr = (char *)malloc(size + 1);
if (ptr == NULL) return NULL;
}
if (feof(fp)) return NULL;
for (i = 0;;) {
if (EOF == (c = fgetc(fp))) {
ptr[i] = '\0';
return ptr;
} else if (c == '\\') {
if (EOF == (c = fgetc(fp))) {
ptr[i] = '\0';
return ptr;
} else if (c == '\n') {
while (EOF != (c = fgetc(fp))) {
if (' ' != c && '\t' != c) {
ungetc(c, fp);
break;
}
}
if (c == EOF || feof(fp)) {
ptr[i] = NULL;
return ptr;
}
} else if (c == '\\') {
ptr[i++] = '\\';
} else if (c == ' ') {
ptr[i++] = ' ';
} else if (c == '\t') {
ptr[i++] = '\t';
}
} else {
ptr[i++] = c;
}
if (c == '\n') {
ptr[i] = '\0';
return ptr;
}
if (i + 3 >= size) {
size += 128;
ptr = realloc(ptr, size + 1);
if (ptr == NULL) return NULL;
}
if (feof(fp)) {
ptr[i] = '\0';
return ptr;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp1;
FILE* fp2;
FILE* fpad;
unsigned int header[138];
unsigned int data1[179916];
unsigned int data2[179916];
int ctr;
fp1 = fopen("enc1.bmp","r");
fread((void*)header, 1, 138, fp1);
fread((void*)data1, 1, 179916, fp1);
fclose(fp1);
fp2 = fopen("enc2.bmp","r");
fseek(fp2, 138, SEEK_SET);
fread((void*)data2, 1, 179916, fp2);
fclose(fp2);
fpad = fopen("pad.bmp","w");
for (ctr = 0; ctr < 179916; ctr++) {
data1[ctr] = data1[ctr] ^ data2[ctr];
}
fwrite((void*)header, 1, 138, fpad);
fwrite((void*)data1, 1, 179916, fpad);
fclose(fpad);
return 0;
}
|
C
|
#include "buffer.h"
#include "exit.h"
#include "strerr.h"
#define puts2(s) buffer_puts(buffer_2,s);
void strerr_warn(const char *x1,const char *x2,const char *x3,const char *x4,const char *x5,const char *x6,const struct strerr *se)
{
strerr_sysinit();
if (x1) puts2(x1);
if (x2) puts2(x2);
if (x3) puts2(x3);
if (x4) puts2(x4);
if (x5) puts2(x5);
if (x6) puts2(x6);
while(se) {
if (se->x) puts2(se->x);
if (se->y) puts2(se->y);
if (se->z) puts2(se->z);
se = se->who;
}
puts2("\n");
buffer_flush(buffer_2);
}
void strerr_die(int e,const char *x1,const char *x2,const char *x3,const char *x4,const char *x5,const char *x6,const struct strerr *se)
{
strerr_warn(x1,x2,x3,x4,x5,x6,se);
_exit(e);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jflorent <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/07 13:24:57 by jflorent #+# #+# */
/* Updated: 2019/09/10 12:26:14 by jflorent ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char const *s, char c)
{
int words;
words = 0;
while (*s)
{
while (*s == c && *s)
s++;
if (*s)
words++;
while (*s != c && *s)
s++;
}
return (words);
}
static char *create_word(char const *s, char c)
{
char *word;
int len;
char *temp;
temp = (char*)s;
len = 0;
while (*s && *s != c)
{
len++;
s++;
}
word = (char*)malloc(sizeof(char) * (len + 1));
if (!word)
return (NULL);
ft_strncpy(word, temp, len);
word[len] = '\0';
return (word);
}
static void free_all(char **arr)
{
int i;
i = 0;
while (arr[i])
{
free(arr[i]);
arr[i] = NULL;
i++;
}
}
static int create_array(char **arr, char const *s, char c)
{
int i;
int j;
i = 0;
j = 0;
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (s[i])
{
arr[j] = create_word(&s[i], c);
if (arr[j] == NULL)
{
free_all(arr);
return (0);
}
j++;
}
while (s[i] != c && s[i])
i++;
}
arr[j] = NULL;
return (1);
}
char **ft_strsplit(char const *s, char c)
{
char **arr;
if (!s)
return (NULL);
arr = (char**)malloc(sizeof(char*) * (count_words(s, c) + 1));
if (!arr)
return (NULL);
if (!create_array(arr, s, c))
{
free(arr);
arr = NULL;
}
return (arr);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Item.h"
#include "pq.h"
#define N 20
int main(void) {
int i;
PQ a, b;
srand(time(NULL));
a = PQinit();
b = PQinit();
for (i = 0; i < N; ++i) {
PQinsert(a, (rand() % N));
}
PQcopy(a, b);
while (!PQempty(b)) {
printf("%i ", PQdelmax(b));
}
printf("\n");
PQdestroy(a);
PQdestroy(b);
return 0;
}
|
C
|
#include "../../testing.h"
#include "avltree.h"
#define STATIC_ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
static int compare_total_count = 0;
#define RESET_COUNTS() \
do { \
compare_total_count = 0; \
} while (0)
static int compare_string(void const *v0, void const *v1) {
assert(v0 != NULL);
assert(v1 != NULL);
compare_total_count++;
return (strcmp(v0, v1));
}
DEF_TEST(string) {
struct {
char *key;
char *value;
} cases[] = {
{"Eeph7chu", "vai1reiV"}, {"igh3Paiz", "teegh1Ee"},
{"caip6Uu8", "ooteQu8n"}, {"Aech6vah", "AijeeT0l"},
{"Xah0et2L", "gah8Taep"}, {"BocaeB8n", "oGaig8io"},
{"thai8AhM", "ohjeFo3f"}, {"ohth6ieC", "hoo8ieWo"},
{"aej7Woow", "phahuC2s"}, {"Hai8ier2", "Yie6eimi"},
{"phuXi3Li", "JaiF7ieb"}, {"Shaig5ef", "aihi5Zai"},
{"voh6Aith", "Oozaeto0"}, {"zaiP5kie", "seep5veM"},
{"pae7ba7D", "chie8Ojo"}, {"Gou2ril3", "ouVoo0ha"},
{"lo3Thee3", "ahDu4Zuj"}, {"Rah8kohv", "ieShoc7E"},
{"ieN5engi", "Aevou1ah"}, {"ooTe4OhP", "aingai5Y"},
};
c_avl_tree_t *t;
RESET_COUNTS();
CHECK_NOT_NULL(t = c_avl_create(compare_string));
/* insert */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++) {
char *key;
char *value;
CHECK_NOT_NULL(key = strdup(cases[i].key));
CHECK_NOT_NULL(value = strdup(cases[i].value));
CHECK_ZERO(c_avl_insert(t, key, value));
EXPECT_EQ_INT((int)(i + 1), c_avl_size(t));
}
/* Key already exists. */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++)
EXPECT_EQ_INT(1, c_avl_insert(t, cases[i].key, cases[i].value));
/* get */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++) {
char *value_ret = NULL;
CHECK_ZERO(c_avl_get(t, cases[i].key, (void *)&value_ret));
EXPECT_EQ_STR(cases[i].value, value_ret);
}
/* iterator */
int count = 0;
c_avl_iterator_t *iter;
char *key = NULL;
char *value = NULL;
CHECK_NOT_NULL(iter = c_avl_get_iterator(t));
while (c_avl_iterator_next(iter, (void *)&key, (void *)&value) == 0) {
++count;
}
EXPECT_EQ_INT(count, c_avl_size(t));
while (c_avl_iterator_prev(iter, (void *)&key, (void *)&value) == 0) {
++count;
}
EXPECT_EQ_INT(count + 1, 2 * c_avl_size(t));
c_avl_iterator_destroy(iter);
/* remove half */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases) / 2; i++) {
char *key = NULL;
char *value = NULL;
int expected_size = (int)(STATIC_ARRAY_SIZE(cases) - (i + 1));
CHECK_ZERO(c_avl_remove(t, cases[i].key, (void *)&key, (void *)&value));
EXPECT_EQ_STR(cases[i].key, key);
EXPECT_EQ_STR(cases[i].value, value);
free(key);
free(value);
EXPECT_EQ_INT(expected_size, c_avl_size(t));
}
/* pick the other half */
for (size_t i = STATIC_ARRAY_SIZE(cases) / 2; i < STATIC_ARRAY_SIZE(cases);
i++) {
char *key = NULL;
char *value = NULL;
int expected_size = (int)(STATIC_ARRAY_SIZE(cases) - (i + 1));
EXPECT_EQ_INT(expected_size + 1, c_avl_size(t));
EXPECT_EQ_INT(0, c_avl_pick(t, (void *)&key, (void *)&value));
free(key);
free(value);
EXPECT_EQ_INT(expected_size, c_avl_size(t));
}
c_avl_destroy(t);
return (0);
}
static int compare_int(void const *v0, void const *v1) {
assert(v0 != NULL);
assert(v1 != NULL);
compare_total_count++;
return (*(int *)v0 - *(int *)v1);
}
DEF_TEST(int) {
struct {
int key;
char *value;
} cases[] = {
{20, "vai1reiV"}, {84, "teegh1Ee"},
{52, "ooteQu8n"}, {38, "AijeeT0l"},
{22, "gah8Taep"}, {89, "oGaig8io"},
{14, "ohjeFo3f"}, {63, "hoo8ieWo"},
{27, "phahuC2s"}, {42, "Yie6eimi"},
{93, "JaiF7ieb"}, {70, "aihi5Zai"},
{71, "Oozaeto0"}, {19, "seep5veM"},
{92, "chie8Ojo"}, {56, "ouVoo0ha"},
{57, "ahDu4Zuj"}, {95, "ieShoc7E"},
{76, "Aevou1ah"}, {55, "aingai5Y"},
};
c_avl_tree_t *t;
RESET_COUNTS();
CHECK_NOT_NULL(t = c_avl_create(compare_int));
/* insert */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++) {
char *value;
CHECK_NOT_NULL(value = strdup(cases[i].value));
CHECK_ZERO(c_avl_insert(t, &cases[i].key, value));
EXPECT_EQ_INT((int)(i + 1), c_avl_size(t));
}
/* Key already exists. */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++)
EXPECT_EQ_INT(1, c_avl_insert(t, &cases[i].key, cases[i].value));
/* get */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++) {
char *value_ret = NULL;
CHECK_ZERO(c_avl_get(t, &cases[i].key, (void *)&value_ret));
EXPECT_EQ_STR(cases[i].value, value_ret);
}
/* remove half */
for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases) / 2; i++) {
int *key = NULL;
char *value = NULL;
int expected_size = (int)(STATIC_ARRAY_SIZE(cases) - (i + 1));
CHECK_ZERO(c_avl_remove(t, &cases[i].key, (void *)&key, (void *)&value));
EXPECT_EQ_INT(cases[i].key, *key);
EXPECT_EQ_STR(cases[i].value, value);
free(value);
EXPECT_EQ_INT(expected_size, c_avl_size(t));
}
/* pick the other half */
for (size_t i = STATIC_ARRAY_SIZE(cases) / 2; i < STATIC_ARRAY_SIZE(cases);
i++) {
int *key = NULL;
char *value = NULL;
int expected_size = (int)(STATIC_ARRAY_SIZE(cases) - (i + 1));
EXPECT_EQ_INT(expected_size + 1, c_avl_size(t));
EXPECT_EQ_INT(0, c_avl_pick(t, (void *)&key, (void *)&value));
free(value);
EXPECT_EQ_INT(expected_size, c_avl_size(t));
}
c_avl_destroy(t);
return (0);
}
int main(void) {
RUN_TEST(string);
RUN_TEST(int);
END_TEST;
}
/* vim: set sw=2 sts=2 et : */
|
C
|
/*
* Marcel Kredzel - M00540191
* Operating Systems Project 1 - Shell
*/
#ifndef MYSHELL_H_
#define MYSHELL_H_
#include "utility.c"
// change directory
// in: new directory
extern void cmd_cd(char *directory);
// clear shell
// no input/output
extern void cmd_clr(void);
// list directory contents
// in: directory to be listed
// out: contents of directory
extern void cmd_dir();
// list environment settings
// out: environment settings
extern void cmd_environ(void);
// display comment
// in: comment to be displayed
// out: comment to be displayed
extern void cmd_echo(char *comment);
// display user manual - help file
// out: user manual - help file
extern void cmd_help(char help_dir[]);
// pause shell until "Enter" is pressed
extern void cmd_pause(void);
#endif /* UTILITY_H_ */
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include "game_structs.h"
#include "deps/socket.h"
#include "deps/cJSON.h"
#include "deps/uthash.h"
#include "deps/levenshtein.h"
// Parsing JSON variables
category_t* category_hashmap = NULL;
// Creating game variables
game_t game;
pthread_mutex_t add_player_lock;
int remaining_questions = 25;
// Checking of submitted answers
pthread_mutex_t answer_list_lock;
answer_t* answers_head = NULL;
// Syncing threads
pthread_mutex_t sync_lock_a;
pthread_mutex_t sync_lock_g;
int sync_threads_a = 0;
int sync_threads_g = 0;
int last_thread_a = 0;
int last_thread_g = 0;
/**
* Takes in a JSON file and outputs a new file of the first num_lines_wanted
* lines of the file in order to have a reasonably sized file
*/
void truncate_questions_file() {
FILE* read = fopen("JEOPARDY_QUESTIONS1.json","r");
FILE* write = fopen("questions.json","w");
int num_lines_wanted = 1000;
for (int i=0; i<num_lines_wanted; i++) {
char line[100];
fgets(line, 100, read);
fprintf(write, "%s", line);
}
fclose(read);
fclose(write);
}
/**
* Convert a value amount of $NUMBER string format into an integer
*
* \param val_str - the string that should be parsed
*/
int parseValue(char* val_str) {
int val = 0;
if (val_str == NULL) return val;
val_str[0] = ' ';
char* end;
val = (int)strtol(val_str, &end, 10);
return val;
}
/**
* Takes in a string and returns the string in all lower case
*
* \param string - the string to make lower case
*/
char* str_tolower(char* string) {
int len = strlen(string);
char *ret = (char*) malloc(sizeof(char) * len);
for(int i = 0; i < len; i++) {
ret[i] = tolower(string[i]);
}
return ret;
}
/**
* Uses the levenshtein algorithm to determine if a guess is close
* enough to the answer to be considered correct
*
* \param guess - the user's guess
* \param answer - the correct answer
*/
int check_answer(char* guess, char* answer) {
int is_correct = 0;
char* guess_formatted = str_tolower(guess);
char* answer_formatted = str_tolower(answer);
size_t difference = levenshtein(guess, answer);
int cutoff_factor = 2;
if (difference-1 < strlen(answer)/cutoff_factor) is_correct = 1;
free(guess_formatted);
free(answer_formatted);
return is_correct;
}
/**
* Given a json string for a single board square (containing the question,
* answer, value, and category) create a new square and add it to the hashmap
*
* \param json_str - the json string to parse as a square
*/
int add_square_from_json(char* json_str) {
cJSON* json_category;
cJSON* json_question;
cJSON* json_value;
cJSON* json_answer;
cJSON* json = cJSON_Parse(json_str);
if (json == NULL) {
return 0;
}
// Get JSON objects
json_question = cJSON_GetObjectItem(json, "question");
json_answer = cJSON_GetObjectItem(json, "answer");
json_value = cJSON_GetObjectItem(json, "value");
json_category = cJSON_GetObjectItem(json, "category");
// Copy the string versions of the JSON objects into a new struct
square_t new_square;
strncpy(new_square.question, cJSON_GetStringValue(json_question), MAX_QUESTION_LENGTH-1);
new_square.question[MAX_QUESTION_LENGTH-1] = '\0';
strncpy(new_square.answer, cJSON_GetStringValue(json_answer), MAX_ANSWER_LENGTH-1);
new_square.answer[MAX_ANSWER_LENGTH-1] = '\0';
new_square.value = parseValue(cJSON_GetStringValue(json_value));
new_square.is_answered = 0;
char category[MAX_ANSWER_LENGTH];
strncpy(category, cJSON_GetStringValue(json_category), MAX_ANSWER_LENGTH-1);
category[MAX_ANSWER_LENGTH-1] = '\0';
/*
Try to find the category of the question in the hashmap. If it's there,
add the square to the existing category. If the category isn't not there,
create a new hashmap entry and add it
*/
category_t* query;
HASH_FIND_STR(category_hashmap, category, query);
if (query == NULL) {
query = malloc(sizeof(category_t));
strncpy(query->title, category, MAX_ANSWER_LENGTH-1);
query->title[MAX_ANSWER_LENGTH-1] = '\0';
query->questions[0] = new_square;
query->num_questions = 1;
HASH_ADD_STR(category_hashmap, title, query);
} else if (query->num_questions < NUM_QUESTIONS_PER_CATEGORY) {
query->questions[query->num_questions] = new_square;
query->num_questions++;
}
cJSON_Delete(json);
return 1;
}
/**
* Read in a JSON file object by object and pass each object to the parser
*
* \param input - the JSON file to read from
*/
int parse_json(FILE* input) {
int max_file_size = 100000;
char buffer[max_file_size];
fgets(buffer, max_file_size, input);
char token[2] = "}";
char* next = strtok(buffer, token);
// Loop over each JSON object
while (next != '\0') {
char json_buffer[max_file_size];
strcpy(json_buffer, next);
strcat(json_buffer, "}");
if (json_buffer[0] == ',') {
json_buffer[0] = ' ';
}
int success = add_square_from_json(json_buffer);
if (!success) return 1;
next = strtok(NULL, token);
}
return 0;
}
/**
* Adds a new player to the game with the given name and id if there is room
*
* \param name - the name of the player
* \param args - contains the (unique) id of the player and the socket number
* that can be used to send network data to them
* \return - boolean, True if player was succesfully added, else False
*/
int add_player(char* name, input_t* args) {
pthread_mutex_lock(&add_player_lock);
// only add player if the max number has not yet been reached
if (game.num_players == MAX_NUM_PLAYERS) return 0;
// fill in necessary player data
player_t new_player;
strncpy(new_player.name, name, MAX_ANSWER_LENGTH);
new_player.score = 0;
new_player.id = args->id;
new_player.socket_fd = args->socket_fd;
game.players[game.num_players] = new_player;
game.num_players++;
pthread_mutex_unlock(&add_player_lock);
return 1;
}
/**
* Iterates through the hashmap 'index' times to get the entry at 'index'
*
* \param index - the index we want to get
* \return c - the entry at position index in the category_hashmap
*/
category_t* get_category_at_index(int index) {
category_t* c = category_hashmap;
for (int i=0; i<index; i++) {
c = c->hh.next;
}
return c;
}
/**
* Creates an empty game, including filling out the Jeopardy board
*
* \return game - a filled out game_t struct containing categories parsed
* randomly to make the game different *every time
*/
game_t create_game() {
game_t game;
game.num_players = 0;
game.is_over = 0;
game.id_of_player_turn = 0;
category_t* c;
category_t* temp;
// Get rid of all non-completely filled categories (gets rid of final
// jeopardy too as a consequence)
HASH_ITER(hh, category_hashmap, c, temp) {
if (c->num_questions != NUM_QUESTIONS_PER_CATEGORY) {
HASH_DEL(category_hashmap, c);
}
}
int map_size = HASH_COUNT(category_hashmap);
// Selects five random categories next to each other to create a game
int r = rand() % (map_size-5);
for (int i=0; i<NUM_CATEGORIES; i++) {
category_t* c = get_category_at_index(r+i);
game.categories[i] = *c;
}
return game;
}
/**
* Adds the answer ans to the list of answers to be checked later (thread safe)
*
* param ans - the answer struct submitted by a user
*/
void add_answer_to_list(answer_t* ans) {
pthread_mutex_lock(&answer_list_lock);
if (answers_head == NULL) {
// adding first answer as head
answers_head = ans;
answers_head->next = NULL;
} else {
// add new node to front of the list
ans->next = answers_head;
answers_head = ans;
}
pthread_mutex_unlock(&answer_list_lock);
}
/**
* Returns the user id of the client who correctly answered the question the quickest.
* Returns -1 if no user answered correctly (or at all) in time
*
* \param answer - the correct answer to check against all users' answers
* \return correct_answer_id - the id number of the client who answered
* the question correctly the earliest, or
* if no one answered correctly/at-all, -1
*/
int get_quickest_answer(char* answer) {
int correct_answer_id = -1;
time_t best_time = -1;
// get client id of fastest correct answer
while (answers_head != NULL) {
printf("checking answer \"%s\". Did answer:%d correctness:%d\n", answers_head->answer, answers_head->did_answer, check_answer(answers_head->answer, answer));
if (answers_head->did_answer && check_answer(answers_head->answer, answer)) {
if (best_time == -1 || answers_head->time < best_time) {
correct_answer_id = answers_head->id;
best_time = answers_head->time;
}
}
// free node
answer_t* temp = answers_head;
answers_head = answers_head->next;
free(temp);
}
printf("Correct answer id: %d\n", correct_answer_id);
return correct_answer_id;
}
/**
* Syncs up the threads running handle_client so that none of the clients
* get out of sync with each other. This one uses syncing variables for
* the beginning of the loop, right before the game_t struct is sent.
*
* \param args - struct containing ID information for the thread that is
* running it. (and less importantly, communication info
* for the client the thread handles)
*/
void wait_for_sync_game(input_t* args) {
// show that the client this thread handles is ready
pthread_mutex_lock(&sync_lock_g);
sync_threads_g++;
last_thread_g++; // for preventing deadlock in this function
pthread_mutex_unlock(&sync_lock_g);
while(1) {
// check if other threads are ready for next portion of game
pthread_mutex_lock(&sync_lock_g);
// if all threads have synced, continue with game play
if(sync_threads_g == MAX_NUM_PLAYERS) {
last_thread_g--;
pthread_mutex_unlock(&sync_lock_g);
break;
} else {
pthread_mutex_unlock(&sync_lock_g);
}
}
// last thread to exit the function must clean up
if(last_thread_g < 1) {
pthread_mutex_lock(&sync_lock_g);
sync_threads_g = 0;
pthread_mutex_unlock(&sync_lock_g);
}
}
/**
* Syncs up the threads running handle_client so that none of the clients
* get out of sync with each other. This one uses syncing variables for
* right before the client submitted answers are to be checked.
*
* \param args - struct containing ID information for the thread that is
* running it. (and less importantly, communication info
* for the client the thread handles)
*/
void wait_for_sync_answers(input_t* args) {
// show that the client this thread handles is ready
pthread_mutex_lock(&sync_lock_a);
sync_threads_a++;
last_thread_a++; // for preventing deadlock in this function
pthread_mutex_unlock(&sync_lock_a);
while(1) {
// check if other threads are ready for next portion of game
pthread_mutex_lock(&sync_lock_a);
// if all threads have synced, continue with game play
if(sync_threads_a == MAX_NUM_PLAYERS) {
last_thread_a--;
pthread_mutex_unlock(&sync_lock_a);
break;
} else {
pthread_mutex_unlock(&sync_lock_a);
}
}
// last thread to exit the function must clean up
if(last_thread_a < 1) {
pthread_mutex_lock(&sync_lock_a);
sync_threads_a = 0;
pthread_mutex_unlock(&sync_lock_a);
}
}
/**
* Thread function to handle each client that connected to the game
*
* \param input - an input struct that contains all necessary info (name, fd, etc.)
* for networking with a designated client
*/
void* handle_client(void* input) {
// Parse username
input_t* args = (input_t*) input;
char username[MAX_ANSWER_LENGTH];
int user_len = 0 ;
if (read(args->socket_fd, &user_len, sizeof(int)) != sizeof(int)) {
perror("Couldn't read username length");
}
if (read(args->socket_fd, &username, sizeof(char)*user_len) < 0) {
char* placeholder = "Anonymous";
strncpy(username, placeholder, strlen(placeholder)+1);
}
// add player to board
add_player(username, args);
if (write(args->socket_fd, &args->id, sizeof(int)) != sizeof(int)) {
perror("Unable to send id to client!");
}
// Wait for enough players to have connected to play game
while (game.num_players < MAX_NUM_PLAYERS) {
usleep(500);
}
char* coords = (char*) malloc(sizeof(char)*2);
// communication loop with designated client
while (1) {
// sync threads so everyone starts the round at the same time
wait_for_sync_game(args);
// send the latest game state to client
if (write(args->socket_fd, &game, sizeof(game_t)) != sizeof(game_t)) {
perror("Writing game didn't work");
return NULL;
}
// only exit if game is over after game_t is sent to clients so
// that clients also know that game is over.
if (game.is_over) break;
// get next question
int question_value = 0;
char* correct_ans;
int coord_size = 3; //2 coord chars, null char
int row, col;
printf("Waiting on coords selection from user\n");
// get question coordinates from the client
if (game.id_of_player_turn == args->id) {
// read char type coords from client
if (read(args->socket_fd, coords, sizeof(char)*coord_size) != sizeof(char)*coord_size) {
perror("Reading in question selection didn't work");
exit(2);
}
// convert coordinates to int
col = coords[0] - 'A'; //range A-E
row = coords[1] - '0' - 1; //range 1-5
// get the answer and question value
question_value = game.categories[col].questions[row].value;
correct_ans = game.categories[col].questions[row].answer;
// mark the question as done so it cannot be done again
game.categories[col].questions[row].is_answered = 1;
game.categories[col].questions[row].value = -1;
// decrement global count of remaining questions
remaining_questions--;
// send coords to all clients from this thread
for(int player = 0; player < MAX_NUM_PLAYERS; player++) {
if(write(game.players[player].socket_fd, coords, sizeof(char)*coord_size) !=
sizeof(char)*coord_size) {
perror("Unable to send question coords!");
}
}
}
// get answer and buzz-time from the client
answer_t* ans = (answer_t*)malloc(sizeof(answer_t));
while (read(args->socket_fd, ans, sizeof(answer_t)) != sizeof(answer_t)) {
fprintf(stderr, "Answer was not read properly by server from client %d\n", args->id);
}
// add the read information to the list of answers for this round
ans->id = args->id;
add_answer_to_list(ans);
// sync up threads so that all the answers are in
// before checking for the fastest one
wait_for_sync_answers(args);
// thread whose turn it is responsible for updating scores and board
int correct_answer_id = -1;
if (game.id_of_player_turn == args->id) {
if(remaining_questions == 0) game.is_over = 1;
// check the answers' correctness in order
correct_answer_id = get_quickest_answer(correct_ans);
if (correct_answer_id != -1) {
game.players[correct_answer_id].score += question_value;
game.id_of_player_turn = correct_answer_id;
}
// build answer struct containing results of the answereing round
ans->id = game.id_of_player_turn;
memcpy(ans->answer, correct_ans, MAX_ANSWER_LENGTH); //write in correct answer
if (correct_answer_id == -1) {
ans->did_answer = 0;
} else {
ans->did_answer = 1;
}
for(int player = 0; player < MAX_NUM_PLAYERS; player++) {
if (write(game.players[player].socket_fd, ans, sizeof(answer_t)) != sizeof(answer_t)) {
perror("Sending correct answer doesn't work!");
}
}
}
}
free(input);
free(coords);
return NULL;
}
/**
* Runs the game loop including waiting for clients to connect and setting up
* the appropriate file streams
*
* \param server_socket_fd - the fd of the server
* \param num_connections_allowed - the number of connections the server should allow
*/
void run_game(int server_socket_fd, int num_connections_allowed) {
// threads to handle each of the clients that connects
pthread_t thrd_arr[num_connections_allowed];
// launch threads to handle each client
for(int client = 0; client < num_connections_allowed; client++) {
// Wait for a client to connect
int client_socket_fd = server_socket_accept(server_socket_fd);
if(client_socket_fd == -1) {
perror("accept failed");
exit(2);
}
printf("Client %d connected!\n", client);
// Set up file streams to access the socket
FILE* to_client = fdopen(dup(client_socket_fd), "wb");
if(to_client == NULL) {
perror("Failed to open stream to client");
exit(2);
}
FILE* from_client = fdopen(dup(client_socket_fd), "rb");
if(from_client == NULL) {
perror("Failed to open stream from client");
exit(2);
}
// Set up arguments and spin up new thread
input_t* in = (input_t*) malloc(sizeof(input_t));
in->to = to_client;
in->from = from_client;
in->socket_fd = client_socket_fd;
in->id = client;
printf("Starting thread to handle new client \n");
if (pthread_create(&thrd_arr[client], NULL, handle_client, in)) {
perror("PTHREAD CREATE FAILED:");
}
}
// join threads as each one exits at the end of the game
for(int i = 0; i < num_connections_allowed; i++) {
if(pthread_join(thrd_arr[i], NULL) != 0) {
perror("Failed to join thread");
}
}
}
/**
* Free all the heap memory in the hashmap allocated at the beginning
* of the game to store the parsed JSON data.
*/
void clean_up_game() {
// Free category hashmap
category_t* c = category_hashmap;
while (c != NULL) {
category_t* temp = c;
c = c->hh.next;
free(temp);
}
}
/**
* Sets up the server and starts running the game
*/
int main() {
// Initialize everything
srand(time(NULL));
pthread_mutex_init(&add_player_lock, NULL);
pthread_mutex_init(&answer_list_lock, NULL);
// Parse JSON and create a new game
FILE* read = fopen("questions.json","r");
parse_json(read);
game = create_game();
// Open a (arbitrary cpu chosen) server socket
unsigned short port = 0;
int server_socket_fd = server_socket_open(&port);
if(server_socket_fd == -1) {
perror("Server socket was not opened");
exit(2);
}
printf("Server listening on port %u\n", port);
// Start listening for connections
int num_connections_allowed = MAX_NUM_PLAYERS;
if(listen(server_socket_fd, num_connections_allowed)) {
perror("listen failed");
exit(2);
}
// Run the game
run_game(server_socket_fd, num_connections_allowed);
// Clean everything up
printf("Game is over, server exiting\n");
close(server_socket_fd);
clean_up_game();
return 0;
}
|
C
|
/*
*
*Author: Chas Shipman
*CS201
*Assignment 0
*Anderson
*Due: 1/30/18
*
*
*This file acts as
*an abstract singly-linked
*data structure.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "sll.h"
typedef struct node{
void *value;
struct node *next;
} NODE;
struct sll{
void (*display)(void *, FILE *);
void (*free)(void *);
NODE *head;
NODE *tail;
int size;
};
static NODE *newNODE(){
NODE *node = malloc(sizeof(NODE));
node->value = 0;
node->next = 0;
return node;
}
extern SLL *newSLL(void (*d)(void *,FILE *),void (*f)(void *)){
//d is display function;
//f is free fucntion;
SLL *items = malloc(sizeof(SLL));
assert(items != 0);
items->head = 0;
items->tail = 0;
items->size = 0;
items->display = d;
items->free = f;
return items;
}
extern void insertSLL(SLL *items,int index,void *value){
assert(index >= 0 && index <= items->size);
NODE *newNode= newNODE();
newNode->value = value;
if(items->size == 0){
items->head = items->tail = newNode;
newNode->next = 0;
}//if list is empty
else if(index == 0){
newNode->next = items->head;
items->head = newNode;
}//if adding to the front
else if(index == items->size){
items->tail->next = newNode;
newNode->next = 0;
items->tail = newNode;
}//if adding to the end;
else{ //if adding in the middle
int i = 0;//for index in list
NODE *prevTemp = items->head;//start at head
while(i < index-1){//loop until on node before insertion
prevTemp = prevTemp->next;
i++;
}
NODE *afterTemp = prevTemp->next; //puts temp node on insertion.
newNode->next = afterTemp;//newNode points to insertion
prevTemp->next = newNode;//previous node points to new node, which points to...do I need to update where newNode->next points to? TEST!
}
items->size++;
return;
}
extern void *removeSLL(SLL *items,int index){
assert(items->size > 0 && index >= 0 && index < items->size);
void *valueHolder = 0;
if(items->size == 1){
valueHolder= items->head->value;
NODE *tempNode = items->head;
items->head = items->head->next;
free(tempNode);
}
else if(index == 0){
valueHolder= items->head->value;
NODE *tempHead = items->head;
items->head = items->head->next;
free(tempHead);
}//if removing from the front
else if(index == (items->size-1)){
valueHolder= items->tail->value;
NODE *prevTemp = items->head;//start at head
NODE *tempTail = items->head->next;
while(tempTail->next != 0 ){//loop until on last node
prevTemp = tempTail;//move previous Node to node before tempTail
tempTail = tempTail->next;//advance temptail;
}
items->tail = prevTemp;//repoint tail to previous Node
items->tail->next = 0;//repoint node before tail to 0
free(tempTail);
}//if removing from the end;
else{ //if removing from the middle
int i = 0;//for index in list
NODE *prevTemp = items->head;//start at head
NODE *afterTemp = items->head;//start at head
while(i < index){//loop until on node before deletion;
prevTemp = afterTemp;//move previous node to node before deletion
afterTemp = afterTemp->next;//move afterTemp to node to be deleted
i++;
}
prevTemp->next = afterTemp->next; //repoints previous node to node after the noede to be deleted
valueHolder= afterTemp->value;
free(afterTemp);
}
items->size--;
return valueHolder;
}
extern void unionSLL(SLL *recipient,SLL *donor){
if(recipient->size == 0 && donor->size == 0){//if both lists are empty
recipient->head = recipient->tail = donor->head = donor->tail= 0;
return;
}
else if(recipient->size == 0 && donor->size != 0){//if recipient list is empty and donor is not
recipient->size += donor->size;
recipient->head = donor->head;
recipient->tail = donor->tail;
donor->head = donor->tail = 0;
donor->size = 0;
}
else if(recipient->size != 0 && donor->size == 0){//if the donor is empty
return;
}
else{//if both have stuff in them
recipient->size += donor->size;
recipient->tail->next = donor->head;
recipient->tail = donor->tail;
donor->head = donor->tail = 0;
donor->size = 0;
}
return;
}
extern void *getSLL(SLL *items,int index){
assert(index >= 0 && index < items->size);
void *valueHolder = 0;
if(items->head == 0 && items->tail == 0 && items->size == 0){
return valueHolder;
}//if list is empty
else if(index == 0){
return items->head->value;
}//if getting first value;
else if(index == (items->size -1)){
return items->tail->value;
}//if getting last value
else{ //if getting value from middle
int i = 0;//for index in list
NODE *tempNode = items->head;//start at head
while(i != index){//loop until on index
tempNode = tempNode->next;
i++;
}
return tempNode->value;
}
}
extern void *setSLL(SLL *items,int index,void *value){
assert(index >= 0 && index <= items->size);
void *valueHolder = 0;
if(items->head == 0 && items->tail == 0 && items->size == 0){
return valueHolder;
}//if list is empty
else if(index == 0){
valueHolder = items->head->value;
items->head->value = value;
return valueHolder;
}//if setting first value;
else if(index == items->size){
insertSLL(items, index, value);
return items->tail->next;
}//if getting last value
else{ //if getting value from middle
int i = 0;//for index in list
NODE *tempNode = items->head->next;//start at head
while(i < index - 1){//loop until on index
tempNode = tempNode->next;
i++;
}
valueHolder = tempNode->value;
tempNode->value = value;
return valueHolder;
}
}
extern int sizeSLL(SLL *items){
return items->size;
}
extern void displaySLL(SLL *items,FILE *fp){
NODE *tempNode = items->head;
if (items->size == 0){
fprintf(fp,"{}");
return;
}
else {
fprintf(fp, "{");
while (tempNode->next != 0){
items->display(tempNode->value, fp);
fprintf(fp,",");
tempNode = tempNode->next;
}
items->display(tempNode->value, fp);
fprintf(fp,"}");
return;
}
}
extern void displaySLLdebug(SLL *items,FILE *fp){
NODE *tempHead = items->head;
NODE *tempTail = items->tail;
if (items->size == 0){
fprintf(fp,"head->{},tail->{}");
return;
}
else{
fprintf(fp, "head->{");
while(tempHead->next != 0){
items->display(tempHead->value, fp);
fprintf(fp,",");
tempHead = tempHead->next;
}
items->display(tempHead->value, fp);
fprintf(fp, "},");
fprintf(fp, "tail->{");
items->display(tempTail->value,fp);
fprintf(fp, "}");
return;
}
return;
}
extern void freeSLL(SLL *items){
if (items == 0 || items->head == 0 || items->tail == 0){
free(items);
return;
}
else{
while (items->head){
NODE *freeNode = items->head;
freeNode->value = items->head->value;
items->head = items->head->next;
free(freeNode->value);
free(freeNode);
}
}
free(items);
return;
}
|
C
|
#include "barman.h"
//Global variables
int closed;
//States
int *clients_states;
int **barman_states;
int *bottle_states;
int nb_barman;
int nb_client;
int nb_bottles;
Choice_bottles *client_choices;
//Condition
pthread_cond_t cv_all_barmans;
pthread_cond_t *cv_clients;
pthread_cond_t *cv_barmans;
pthread_cond_t *cv_bottles;
//Mutex
pthread_mutex_t mb; //Mutex barman
pthread_mutex_t mbo; //Mutex bottles
static void print()
{
int i;
printf("\n* Clients *\n");
for (i = 0; i < nb_client; i++) {
switch(clients_states[i]) {
case THINKING :
printf("T ");
break;
case DRINKING :
printf("D ");
break;
case WAITING :
printf("W ");
break;
case SERVED :
printf("S ");
break;
default :
break;
}
}
printf("\n* Barmans *\n");
for (i = 0; i < nb_barman; i++) {
switch(barman_states[i][0]) {
case WAITING :
printf("W ");
break;
case BUSY :
printf("B ");
break;
case DISPONIBLE :
printf("D ");
break;
default :
break;
}
}
printf("\n* Bottles *\n");
for (i = 0; i < nb_bottles; i++) {
switch(bottle_states[i]) {
case AVAILABLE :
printf("A ");
break;
case UNAVAILABLE :
printf("U ");
break;
default :
break;
}
}
printf("\n_______________\n");
}
void finishDrink(int id)
{
clients_states[id] = THINKING;
}
void init(int n_clients, int m_barmans, int k_bottles, int **states_barmans, int *states_bottles, int *states_clients)
{
closed = 0;
pthread_mutex_init (&mb, NULL);
pthread_mutex_init (&mb, NULL);
clients_states = states_clients;
barman_states = states_barmans;
bottle_states = states_bottles;
cv_clients = (pthread_cond_t*)(malloc(n_clients*sizeof(pthread_cond_t)));
cv_barmans = (pthread_cond_t*)(malloc(m_barmans*sizeof(pthread_cond_t)));
cv_bottles = (pthread_cond_t*)(malloc(k_bottles*sizeof(pthread_cond_t)));
client_choices = (Choice_bottles*)(malloc(n_clients*sizeof(Choice_bottles)));
//Initialisation pthread_cond
pthread_cond_init (&cv_all_barmans, NULL);
int i;
for (i = 0; i < m_barmans; i++) {
pthread_cond_init (&cv_barmans[i], NULL);
barman_states[i][0] = DISPONIBLE;
barman_states[i][1] = -1;
}
for (i = 0; i < n_clients; i++) {
pthread_cond_init (&cv_clients[i], NULL);
clients_states[i] = THINKING;
}
for (i = 0; i < k_bottles; i++) {
pthread_cond_init (&cv_bottles[i], NULL);
bottle_states[i] = AVAILABLE;
}
nb_client = n_clients;
nb_barman = m_barmans;
nb_bottles = k_bottles;
print();
}
void take_barman(int id_client, Choice_bottles str_set_bottles)
{
pthread_mutex_lock (&mb);
clients_states[id_client] = WAITING;
//Show states tables
printf("Client %d wait a barman \n",id_client);
print();
//Check if one barman is free
int i = 0; // index of barman
while (i < nb_barman && barman_states[i][0] != DISPONIBLE) {
if (i == nb_barman - 1) {
pthread_cond_wait (&cv_all_barmans,&mb);
i = -1;
}
i++;
}
// Barman state : [i][0] = state of barman, [i][1] = id client
barman_states[i][0] = WAITING;
barman_states[i][1] = id_client;
clients_states[id_client] = SERVED;
printf("Client %d have a barman %d now\n",id_client,i);
print();
//The client choice is saved
client_choices[id_client] = str_set_bottles;
pthread_cond_signal(&cv_barmans[i]); // signal barman serve drink to client
printf("sent signal to barman %d\n",i);
pthread_cond_wait(&cv_clients[id_client],&mb); // client is waiting for his/her drink
//Show states tables
clients_states[id_client] = DRINKING;
printf("Client %d drink\n",id_client);
print();
pthread_mutex_unlock (&mb);
}
// barman has nothing to do
int ready(int id_barman)
{
pthread_mutex_lock (&mb);
if (barman_states[id_barman][0] == WAITING) {
pthread_mutex_unlock (&mb);
return closed;
}
//Waiting for a job
while (barman_states[id_barman][0] == DISPONIBLE && !closed) {
pthread_cond_wait(&cv_barmans[id_barman],&mb);
}
pthread_mutex_unlock (&mb);
return closed;
}
void go_home()
{
pthread_mutex_lock (&mb);
closed = 1;
int i;
for(i = 0; i < nb_barman; i++) {
pthread_cond_signal(&cv_barmans[i]);
}
pthread_mutex_unlock (&mb);
}
void take_bottles(int id_barman)
{
pthread_mutex_lock (&mbo);
//Check if nb_bottles are free
int i; // index of bottle in the set of clients choice
int my_id_client = barman_states[id_barman][1];
int *set_bottles = client_choices[my_id_client].set_bottles;
printf("bottles chosen by client %d and wanted by barman %d\n",my_id_client,id_barman);
for (i = 0; i < client_choices[my_id_client].nb_bottles; i++) {
printf("%d ",set_bottles[i]);
}
printf("\n");
//Try to takes bottles
for (i = 0; i < client_choices[my_id_client].nb_bottles; i++) {
while (bottle_states[set_bottles[i]] != AVAILABLE) {
pthread_cond_wait(&cv_bottles[set_bottles[i]],&mbo); // barman waiting for bottle i
}
bottle_states[set_bottles[i]] = UNAVAILABLE;
}
//Prepare the drink
barman_states[id_barman][0] = BUSY;
//Show states tables
printf("Barman %d prepare the coktail\n",id_barman);
print();
pthread_mutex_unlock (&mbo);
}
void put_botlles_free_barman(int id_barman)
{
pthread_mutex_lock (&mbo);
//Announce all you collegue the botlles are avaible
int i; // index of bottles choices
int my_id_client = barman_states[id_barman][1];
int *set_bottles = client_choices[my_id_client].set_bottles;
for (i = 0; i < client_choices[my_id_client].nb_bottles; i++) {
bottle_states[set_bottles[i]] = AVAILABLE;
pthread_cond_signal (&cv_bottles[set_bottles[i]]); // telling other barmans that bottle is free
}
pthread_mutex_unlock (&mbo);
pthread_mutex_lock (&mb); // lock barmans
barman_states[id_barman][0] = DISPONIBLE;
pthread_cond_signal (&cv_clients[my_id_client]); // hey, client, your drink is ready!
//Show states tables
printf("Barman %d finish prepare the drink, he is ready\n",id_barman);
print();
//Prevent they are a new barman free
pthread_cond_signal (&cv_all_barmans);
pthread_mutex_unlock (&mb);
}
void bar_close(void)
{
free(cv_clients);
free(cv_barmans);
free(cv_bottles);
free(client_choices);
}
|
C
|
/**
* @file cod.c
* @brief ficheiro com funções para ler os ficheiros .COD
* @author Emanuel João Conceição Lopes <2140825@student.estg.ipleiria.pt>
*/
#include "cod.h"
#include "errors.h"
#include "common.h"
#include "debug.h"
#include "memory.h"
/**
* @brief Abrir ficheiro cod
*
* @param path - caminho do ficheiro
* @param codFile estrutura do ficheiro
*
* @return !=0 in case os error
*/
int open_file_cod(char *path, cod_t *codFile) {
FILE *stream = fopen(path, "r");
if (stream == NULL) {
WARNING("fopen() failed");
return ERR_OPEN_FAILED;
}
//read header
int status = read_header_cod(stream, path, &(codFile->header));
if (status != 0) {
fclose(stream);
return status;
}
//read body
status = read_body_cod(stream, codFile);
if (status != 0) {
fclose(stream);
return status;
}
fclose(stream);
return 0;
}
/**
* @brief lê o cabeçalho do ficheiro
*
* @param stream - ficheiro
* @param path - name of file
* @param header - estrutura do ficheiro
* @return 0=Succefull ou !=0 em caso de erro
*/
int read_header_cod(FILE *stream, char *path, header_cod_t *header) {
char *line = NULL;
strncpy(header->filename, path, MAX_FILENAME + 1);
WARNING("teste");
//versao
line = read_line(stream);
int versiontmp = is_cod_file(line, &(header->type));
free(line);
if (versiontmp) return versiontmp;
//largura e altura
line = read_line(stream);
if (!get_size(line, &(header->width), &(header->height))) {
return ERR_INVALID_SIZE;
}
free(line);
//valor maximo
line = read_line(stream);
if (!max_value(line, &(header->max_value))) return ERR_INVALID_MAX_VALUE;
free(line);
if ((header->max_value < 1) || (header->max_value >= 65536)) return ERR_INVALID_MAX_VALUE;
//tamanho dos blocos
line = read_line(stream);
if (!get_cod_blocks(line, &(header->block_width), &(header->block_height))) {
return ERR_INVALID_BLOCK_W_H;
}
FREE(line);
//verifica se os blocos estão correctos
int checkBls = check_blocks(header->width, header->height, header->block_width, header->block_height);
if(checkBls) return checkBls;
return 0;
}
/**
* @brief lê o corpo do ficheiro
*
* @param stream
* @param codFile
*
* @return !=0 erro 0=ok
*/
int read_body_cod(FILE *stream, cod_t *codFile) {
int lines = codFile->header.width / codFile->header.block_width;
int columns = codFile->header.height / codFile->header.block_height;
//alloca memoria
codFile->indexes = MALLOC(sizeof(unsigned short *) * codFile->header.width);
unsigned short *data = MALLOC(sizeof(unsigned short) * codFile->header.width * codFile->header.height);
unsigned int i;
for (i = 0; i < codFile->header.width; ++i) {
codFile->indexes[i] = &data[i * codFile->header.height];
}
if (codFile->indexes == NULL) {
WARNING("Filed to alloc memory");
return ERR_ALLOC_MEMORY;
}
int counterBlocks = 0;
//lê os ficheiros do tipo Z2
if (codFile->header.type == Z2) {
int columnsNumber = 0;
int lineNumber = 0;
char *line=NULL;
//lê as linhas do ficheiro
while (strcmp((line = read_line(stream)), "EOF") != 0) {
char *token;
char *endptr = NULL;
errno = 0;
token = strtok(line, SPACE);
while (token != NULL) {
long value = strtol(token, &endptr, 10);
if (*endptr != '\0' && *endptr != '\n') {
return ERR_INVALID_BLOCKS_NUMBER;
}
if (errno != 0) {
return ERR_INVALID_BLOCKS_NUMBER;
}
if (value < 0 || value > (codFile->header.max_value)) return ERR_INVALID_BLOCKS_NUMBER;
codFile->indexes[lineNumber][columnsNumber] = (unsigned int)value;
columnsNumber++;
counterBlocks++;
if (columnsNumber >= columns) {
columnsNumber = 0;
lineNumber++;
}
token = strtok(NULL, SPACE);
}
FREE(line);
FREE(token);
}
if ((lines * columns) == counterBlocks)return 0;
//lê os ficheiros do tipo Z5
} else if (codFile->header.type == Z5) {
int i, j;
unsigned int index = 0;
for (i = 0; i < lines; i++) {
for (j = 0; j < columns; j++) {
counterBlocks++;
unsigned int data_size = (codFile->header.max_value <= 255) ? 1 : 2;
if (fread(&index, data_size, 1, stream) != 1) {
WARNING("saiu aqui cod 2");
return ERR_INVALID_BLOCKS_NUMBER;
}
if ((short)(index) < 0 || (short)(index) > (int)codFile->header.max_value) {
return ERR_INVALID_BLOCKS_NUMBER;
}
codFile->indexes[i][j] = index;
}
}
//verifica se tem valores a mais no ficheiro
char ch;
fread(&ch, 1, 1, stream);
if (!feof(stream)) {
return ERR_INVALID_BLOCKS_NUMBER;
}
if ((lines * columns) == counterBlocks) return 0;
}
return ERR_INVALID_BLOCKS_NUMBER;
}
/**
* @brief verifica e devolve a versao do ficheiro Z2 ou Z5
*
* @param line - linha do ficheiro de texto
* @param version - versao do ficheiro
*
* @return 0-succefull, !=0 em caso de erro
*/
int is_cod_file(char *line, file_cod_t *version) {
char *token;
int counter = -1;
token = strtok(line, SPACE);
while (token != NULL) {
counter++;
token = strtok(NULL, SPACE);
}
FREE(token);
if (counter > 0)return ERR_MISSING_HEADER;
if (line[0] == 'Z') {
if (strcmp(line, "Z2") == 0) {
*version = Z2;
return 0;
} else if (strcmp(line, "Z5") == 0) {
*version = Z5;
return 0;
} else {
return ERR_INVALID_FORMAT;
}
} else {
return ERR_MISSING_HEADER;
}
return ERR_MISSING_HEADER;
}
/**
* @brief grava os bloco largura e altura
*
* @param line linha do ficheiro de texto
* @param width - largura
* @param height - altura
* @return 1=succefull 0=error
*/
int get_cod_blocks(char *line, unsigned int *width, unsigned int *height) {
return get_size(line, width, height);
}
/**
* @brief verifica se os blocos são correctos
*
* @param width largura da imagem
* @param height altura da imagem
* @param blockRows largura dos blocos
* @param blockColumns altura dos blocos
* @return 0=succefull and !=0 is error
*/
int check_blocks(int width, int height, int blockRows, int blockColumns) {
if (width % blockRows != 0 || height % blockColumns != 0)
return ERR_INVALID_BLOCK_MISMATCH;
if ((width * height) % (blockRows * blockColumns))
return ERR_INVALID_BLOCKS_NUMBER;
return 0;
}
|
C
|
/*
* Name: Matthew Olsen
* Lab: Lab 4 Lexical Analysis
* Date: 02/20/18
*/
#include "scanner.h"
/*
* SUBMIT THE FSM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
TOKEN *ungottenToken = NULL; // used by parser
//
// return token to the input, so it can be analyzed again
//
void ungetToken(TOKEN **token) {
ungottenToken = *token;
*token = NULL;
}
//
// clean up the token structure
//
void freeToken(TOKEN **token) {
if (token == NULL)
return;
if (*token == NULL)
return;
if ((*token)->strVal != NULL)
free((*token)->strVal);
free(*token);
*token = NULL;
}
//
// check if a collected sequence of characters is a keyword
//
bool isKeyword(TOKEN *token, char *str) {
if (strcmp(str, "repeat") == 0)
token->type = REPEAT_TOKEN;
else if (strcmp(str, "print") == 0)
token->type = PRINT_TOKEN;
else
return false;
return true;
}
//
// scan input for a token using the nested case method
//
TOKEN *scannerNestedCases() {
if (ungottenToken != NULL) {
TOKEN *tok = ungottenToken;
ungottenToken = NULL;
return tok;
}
// temporary buffer for collecting characters
char tempString[BUF_SIZE];
// acquire space for the new token
TOKEN *token = (TOKEN *) malloc(sizeof(TOKEN));
token->type = INVALID_TOKEN; // assume that the token is invalid to start with
token->strVal = NULL;
// analyze the input character by character figuring out what kind of token they constitute
char c;
int i = 0;
int state = 1;
while ((token->type == INVALID_TOKEN) && ((c = getchar()))) {
switch (state) {
case 1:
switch (c) {
case '*':
/* ventures toward ad hoc but prevents wordy code */
token->type = MULT_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case '+':
token->type = PLUS_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case '-':
token->type = MINUS_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case '/':
token->type = DIV_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case '%':
token->type = MOD_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case '(':
token->type = LPAREN_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case ')':
token->type = RPAREN_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case ';':
token->type = SEMICOLON_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case '=':
token->type = ASSIGNMENT_TOKEN;
token->strVal = malloc(sizeof(char) + 1);
token->strVal[0] = c;
token->strVal[1] = '\0';
return token;
case EOF:
token->type = END_OF_INPUT_TOKEN;
token->strVal = malloc((strlen("EOF") * sizeof(char)) + 1);
strncpy(token->strVal, "EOF", 4);
return token;
case '0'...'9':
state = 12;
// want to read all of it in the case statement
ungetc(c, stdin);
break;
case 'a'...'z':
state = 13;
ungetc(c, stdin);
break;
case ' ': // skip whitespace
case '\t':
case '\n':
break;
//default:
//puts("wat");
}
break;
case 12:
switch (c) {
case '0'...'9':
tempString[i++] = c;
break;
default:
ungetc(c, stdin);
tempString[i] = '\0';
token->type = NUMBER_TOKEN;
token->strVal = malloc(strlen(tempString) + 1);
strcpy(token->strVal, tempString);
return token;
}
break;
case 13:
switch (c) {
case 'a'...'z':
tempString[i++] = c;
break;
default:
ungetc(c, stdin);
tempString[i] = '\0';
if (!isKeyword(token, tempString)) {
token->type = IDENT_TOKEN;
token->strVal = malloc(strlen(tempString) + 1);
strcpy(token->strVal, tempString);
}
return token;
}
break;
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#define dim 50
int main ()
{
char ingreso [dim];
printf ("Hola Mundo\n");
printf ("Escriba algo: \n");
gets(ingreso);
printf ("%s",ingreso);
return(0);
}
|
C
|
//һĶƵλżλ
//#define _CRT_SECURE_NO_WARNINGS
//#include <stdio.h>
//void print_binary(int n)
//{
// int ret = n;
// int i = 0;
// printf("żλΪ");
// for(i = 16; i > 0; i--)
// {
// printf("%d ", n & 1);
// n = n >> 2;
// }
// printf("\n");
// printf("λΪ");
// for(i = 16; i > 0; i--)
// {
// ret=ret >> 1;
// printf("%d ", ret & 1);
// ret=ret >> 1;
// }
//}
//int main()
//{
// int n = 0;
// printf("һ ");
// scanf("%d", &n);
// print_binary(n);
// return 0;
//}
|
C
|
/*
* lesson12.2.c
*
* Write a program that declares an integer array of size 20, and then with a loop,
* initializes all of its values to random numbers between 50 and 100.
* You can use the rand() function from stdlib.h to generate an arbitrary int,
* and then mod it by m to fall within the range 0 to m-1. Create another loop that
* prints out all of its values to the console window.
*
* July 14, 2019
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
int main(void) {
int array[20];
int i;
for (i = 0; i < 20; i++) {
array[i] = rand() % 50 + 50;
printf("array[%d] = %d\n", i, array[i]);
}
return 0;
}
|
C
|
/* gcc -lpthread | -pthread */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#define MSG_SIZE 1024
struct msg_stru {
char msg1[MSG_SIZE], msg2[MSG_SIZE], msg3[MSG_SIZE];
}; /* global variable */
static void *runner1(void *);
static void *runner2(void *);
int main(void)
{
pthread_t tid1, tid2;
pthread_attr_t attr = {0};
struct msg_stru msg; /* storage in main-thread stack */
sprintf(msg.msg1, "message 1 by parent");
sprintf(msg.msg2, "message 2 by parent");
sprintf(msg.msg3, "message 3 by parent");
printf("\nparent say:\n%s\n%s\n%s\n", msg.msg1, msg.msg2, msg.msg3);
pthread_attr_init(&attr);
if(pthread_create(&tid1, &attr, &runner1, (void *)&msg) != 0) {
perror("pthread_create()");
return 1;
}
if(pthread_create(&tid2, &attr, &runner2, (void *)&msg) != 0) {
perror("pthread_create()");
return 1;
}
if(pthread_join(tid1, NULL) != 0) {
perror("pthread_join()");
return 1;
}
if(pthread_join(tid2, NULL) != 0) {
perror("pthread_join()");
return 1;
}
printf("\nparent say:\n%s\n%s\n%s\n", msg.msg1, msg.msg2, msg.msg3);
return 0;
}
static void *runner1(void *param)
{
struct msg_stru *ptr = (struct msg_stru *)param;
sprintf(ptr->msg1, "message 1 changed by child1");
pthread_exit(0);
}
static void *runner2(void *param)
{
struct msg_stru *ptr = (struct msg_stru *)param;
sprintf(ptr->msg2, "message 2 changed by child2");
pthread_exit(0);
}
|
C
|
/*
* LowlevelGraphicsTestMain.c
* baselib
*
* Created by Martin on 8/15/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#include <allegro.h>
#include "Common.h"
#include "SystemGraphics.h"
#include "ZoneAllocator.h"
#include "WadFile.h"
#include "FixedPointNumber.h"
#include "StaticGraphicsData.h"
#include "LowlevelGraphics.h"
#include "TestMainCommon.h"
const char *testScaledPatchName;
const char *testScaledTextureName;
static void testScaledPatch(int destinationHeight) {
int i;
unsigned char *patch = getWadFileLumpContentsByName(testScaledPatchName);
int patchWidth = fromLittleEndian16u(DESERIALIZE(patch, 0, unsigned short));
int patchHeight = fromLittleEndian16u(DESERIALIZE(patch, 2, unsigned short));
int *serializedPostTable = (int*)(patch + 8);
acquire_screen();
clear(screen);
for (i=0; i<patchWidth; i++) {
unsigned char *post = patch + fromLittleEndian16u(serializedPostTable[i]);
drawScaledPatchColumnOnScreen(i, 0, patchHeight, destinationHeight, post);
}
release_screen();
readkey();
}
static void testScaledTexture(int destinationHeight) {
int textureIndex = getTextureIndexForName(testScaledTextureName);
struct TextureDescriptor *texture = getTexture(textureIndex);
int i;
acquire_screen();
clear(screen);
for (i=0; i<texture->width; i++) {
unsigned char *column = getTextureColumnTexels(texture, i);
drawScaledTextureColumnOnScreen(i, 0, texture->height, destinationHeight, column);
}
release_screen();
readkey();
}
/**
* Main function.
*/
int main(int argc, const char *argv[]) {
initializeAllegroStuff();
zoneAllocatorInitialize();
initializeWadFile(WAD_FILE_PATH);
initializeStaticGraphicsData();
systemGraphicsSetPalette((unsigned char *)getWadFileLumpContentsByName("PLAYPAL"));
acquire_screen();
clear(screen);
drawPatchOnScreen(320, 240, getWadFileLumpContentsByName("SARGA2A8"));
release_screen();
readkey();
testScaledPatchName = "DOOR2_4";
testScaledPatch(10);
testScaledPatch(50);
testScaledPatch(100);
testScaledPatch(200);
testScaledPatch(400);
testScaledPatchName = "W113_1";
testScaledPatch(10);
testScaledPatch(50);
testScaledPatch(100);
testScaledPatch(200);
testScaledPatch(400);
testScaledTextureName = "SW1BRCOM";
testScaledTexture(10);
testScaledTexture(50);
testScaledTexture(100);
testScaledTexture(200);
testScaledTexture(400);
return 0;
}
END_OF_MAIN()
|
C
|
/*
* @Date: 2020-05-06 15:18:47
* @LastEditors: litelte
* @LastEditTime: 2020-05-06 16:02:05
* @FilePath: /CProject/zju_c/week4PatTask/12.c
* @Description: 兔子繁衍问题&斐波那契数列问题
* 题目链接:https://pintia.cn/problem-sets/13/problems/444
*/
/*
* 斐波那契数列数列
* 1,1,2,3,5,8,13......
*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
int rabbitOri = 0;
int loadCount = 0;
int sumCount = 1;
int userInputCount = 0;
int month = 1;
scanf("%d", &userInputCount);
while (sumCount < userInputCount)
{
loadCount = rabbitOri;
rabbitOri = sumCount;
sumCount = loadCount + rabbitOri;
month++;
/* if (sumCount == userInputCount)
{
find = 0;
} */
}
printf("%d\n", month);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.