language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "printformat.h"
void printLogo(){
printf("\n");
printf("\n");
printf(" ██████╗ █████╗██████████████████╗ ███████╗ ███████╗██████╗██████╗\n " );
printf(" ██╔══████╔══██╚══██╔══╚══██╔══██║ ██╔════╝ ██╔════██╔═══████╔══██╗\n " );
printf(" ██████╔███████║ ██║ ██║ ██║ █████╗ █████╗ ██║ ████████╔╝\n " );
printf(" ██╔══████╔══██║ ██║ ██║ ██║ ██╔══╝ ██╔══╝ ██║ ████╔══██╗\n " );
printf(" ██████╔██║ ██║ ██║ ██║ ██████████████╗ ██║ ╚██████╔██║ ██║\n " );
printf(" ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╚══════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝\n " );
printf(" \n " );
printf(" ██████╗██╗ ██╗ █████╗ █████████╗██╗█████╗\n " );
printf(" ██╔═══████║ ╚██╗ ██╔████╗ ██████╔══██████╔══██╗\n " );
printf(" ██║ ████║ ╚████╔╝██╔████╔████████╔█████████║\n " );
printf(" ██║ ████║ ╚██╔╝ ██║╚██╔╝████╔═══╝████╔══██║\n " );
printf(" ╚██████╔█████████║ ██║ ╚═╝ ████║ ████║ ██║\n " );
printf(" ╚═════╝╚══════╚═╝ ╚═╝ ╚═╚═╝ ╚═╚═╝ ╚═╝\n " );
printf("\n" );
}
void clearScreen(){
#ifdef _WIN32
system("cls");
#endif
#ifdef __unix__
system("clear");
#endif
}
void printCanAttack(Unit U){
if (canAttack(U)){
printf("YES");
}
else{
printf("NO");
}
}
void printUnitbyType(Unit U){
if (U.type==KING_TYPE){
printf("KING");
}
else if (U.type == ARCHER_TYPE){
printf("ARCHER");
}
else if (U.type == SWORDSMAN_TYPE){
printf("SWORDSMAN");
}
else if (U.type == MAGE_TYPE){
printf("MAGE" );
}
}
void printAttackType(Unit U){
if (U.attackType == MELEE){
printf("MELEE");
}
else if (U.attackType==RANGED) {
printf("RANGED");
}
};
void printPlayerInfo(Queue *Q){
Player currPlayer = InfoHead(*Q);
Unit currentUnit = UnitInfo(currPlayer.currentUnit);
Point position = getUnitLocation(currentUnit);
printf("\n" );
printf("Player %d's Turn\n",currPlayer.ID);
printf("Cash : %dG",currPlayer.gold);
printf(" | Income : %dG",currPlayer.income);
printf(" | Upkeep : %dG",currPlayer.upkeep);
printf("\n");
printf("Unit : ");
printUnitbyType(currentUnit);
printf(" (%d,%d)",position.X,position.Y);
printf(" | Health : ");
printf("%d",currentUnit.health );
printf(" | " );
printAttackType(currentUnit);
printf(" | Movement Point : ");
printf("%d",currentUnit.movementPoint );
printf(" | Can Attack : ");
printCanAttack(currentUnit);
printf("\n");
}
void printUnitFormat(Unit U){
printUnitbyType(U);
printf(" (%d,%d)",U.location.X,U.location.Y);
printf(" | " );
printAttackType(U);
printf(" | Health : ");
printf("%d",U.health );
printf(" | Movement Point : ");
printf("%d",U.movementPoint );
printf(" | Can Attack : ");
printCanAttack(U);
}
void printUnitInfo(UnitList L){
address P = FirstUL(L);
int idx = 0;
if (!IsEmptyUL(L)){
idx++;
printf("%d. ",idx);printUnitFormat(UnitInfo(P));printf("\n" );
P = NextUL(P);
while (P!=FirstUL(L)) {
idx++;
printf("%d. ",idx);printUnitFormat(UnitInfo(P));printf("\n" );
P = NextUL(P);
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "math1.h"
#include "stringutils.h"
void reset(char *c, int len) {
int i;
for (i = 0; i < len; i++) {
c[i] = '\0';
}
}
int length (char *c) {
int len = 0;
while (c[len] != '\0') {
len++;
}
return len;
}
string new_string (char *s) {
string string = {length(s), s};
return string;
}
int valueOf_char(char c) {
switch(c) {
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case '0': return 0;
default: return -1;
}
}
int num_char(string s, char ch) {
int n = 0;
int c = 0;
while (c < s.len) {
if (s.str[c] == ch) {
n++;
}
c++;
}
return n;
}
int find_char(string s, char c) {
int i;
for (i = 0; i < s.len; i++) {
if (s.str[i] == c) {
return i;
}
}
return -1;
}
double valueOf(string s) {
int p = num_char(s, '.');
int i;
double val = 0;
if (p == 1) {
int point = find_char(s, '.');
for (i = 0; i < point; i++) {
val += pow(10,point-i-1)*valueOf_char(s.str[i]);
}
for (i = point+1; i < s.len; i++) {
val += pow(0.1,i-point)*valueOf_char(s.str[i]);
}
return val;
}
for (i = 0; i < s.len; i++) {
val += pow(10,s.len-i-1)*valueOf_char(s.str[i]);
}
return val;
}
string *divide(char c, string str, int skip) {
char** s = (char **) malloc(2*sizeof(char*));
int i, found = 0, d = 0;
s[0] = (char*) malloc(str.len*sizeof(char));
s[1] = (char*) malloc(str.len*sizeof(char));
for (i = 0; i < str.len; i++) {
if (str.str[i] == c && !found) {
if (skip > 1) {
skip--;
s[0][i] = str.str[i];
}
else {
found = 1;
s[0][i] = '\0';
}
}
else {
if (found) {
s[1][d] = str.str[i];
d++;
}
else {
s[0][i] = str.str[i];
}
}
}
s[1][d] = '\0';
string *result = (string *) malloc(2*sizeof(string));
result[0] = new_string(s[0]);
result[1] = new_string(s[1]);
return result;
}
|
C
|
/*************************************************************************
> File Name: waitofWNOHANG.c
> Author: huangjia
> Mail: 605635529@qq.com
> Created Time: 2017年07月18日 星期二 02时55分05秒
************************************************************************/
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
pid_t pid;
pid = fork();
if(pid < 0)
{
perror("fork error\n");
return 1;
}
else if(pid == 0)
{
printf("child is run, pid is :%d\n",getpid() ) ;
sleep(5);
exit(1);
}
else
{
int status = 0;
pid_t ret = 0;
do
{
ret = waitpid(-1, &status, WNOHANG); // 非阻塞等待
if(ret == 0)
{
printf("child is running\n");
}
sleep(1);
}while(ret == 0);
if(WIFEXITED(status) && ret == pid)
{
printf("wiat child 5s success,child return code is:%d\n",WEXITSTATUS(status));
}
else
{
printf("wait child failed, return \n");
return 1;
}
}
}
|
C
|
#include "holberton.h"
/**
* cap_string - check the code for Holberton School students.
* @p: pointer
* Return: string.
*/
char *cap_string(char *p)
{
int i;
i = 0;
while (p[i] != '\0')
{
if (p[i] == ' ' || p[i] == ';' || p[i] == '\n' || p[i] == '\t'
|| p[i] == ',' || p[i] == '.' || p[i] == '!' || p[i] == '?'
|| p[i] == '"' || p[i] == '(' || p[i] == ')' ||
p[i] == '{' || p[i] == '}')
if (p[i + 1] >= 'a' && p[i + 1] <= 'z')
p[i + 1] = p[i + 1] - 32;
i++;
}
if (p[0] >= 'a' && p[0] <= 'z')
p[0] = p[0] - 32;
return (p);
}
|
C
|
#ifndef MENU_H
#define MENU_H
#include <stdbool.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "game.h"
#include "app.h"
//Menu button creation struct consisting of SDL_Rect, SDL_Texture and SDL_Color.
typedef struct Screen_item {
SDL_Rect rect;
SDL_Texture *texture, *background;
SDL_Color color;
} Screen_item;
//Numreric values to determine menu outcome.
enum Menu_selection {
MAIN_MENU = 0,
SELECT_GAME = 10,
HOST_MULTIPLAYER = 11,
JOIN_MULTIPLAYER = 12,
HIGH_SCORE = 20,
SETTINGS = 30,
START_GAME = 100
};
//Standard dimensions for menu button backgrounds and texts.
enum Button_dimensions {
BUTTON_X = 300,
BUTTON_Y = 400,
BUTTON_W = 360,
BUTTON_H = 150,
TEXT_X = 337,
TEXT_Y = 430,
TEXT_W = 290,
TEXT_H = 90,
};
void menu_init(App* app, SDL_Texture* background, SDL_Texture* newGame, SDL_Texture* exit);
SDL_Color color_select (int selection);
Screen_item* menu_button_background (App* app, char resource[]);
Screen_item* menu_button_text(App* app, char* text, TTF_Font* font, SDL_Color color);
Screen_item* input_text(App* app, Screen_item* item);
bool hover_state (Screen_item* button, int Mx, int My);
void menu(App* app);
int main_menu (App* app);
int select_game_menu (App* app);
int join_multiplayer (App* app);
int host_multiplayer (App* app);
int high_score (App* app);
int settings (App* app);
#endif
|
C
|
#pragma once
#include "SDL_gpu.h"
#include "../src/anim_data.h"
struct AnimationData
{
const int frames;
const GPU_Rect rect[16];
const int timer[16];
};
extern AnimationData anim_lib[];
struct Animation
{
AnimationType anim_type;
int anim_timer;
int current_frame;
bool loopable = true;
bool complete = false;
Animation(AnimationType initial_anim)
: anim_type(initial_anim)
{
Reset();
}
AnimationType GetCurrentAnim() const {
return anim_type;
}
void Update(int dt)
{
anim_timer += dt;
AnimationData* anim_data = &anim_lib[(int)anim_type];
if (current_frame >= anim_data->frames && !loopable)
{
current_frame = anim_data->frames - 1;
return;
}
if (anim_timer > anim_data->timer[current_frame])
{
anim_timer -= anim_data->timer[current_frame];
if (current_frame < anim_data->frames-1)
{
current_frame++;
}
else if (loopable)
{
current_frame = 0;
anim_timer = anim_timer % anim_data->timer[0];
}
else {
complete = true;
}
}
}
int GetCurrentAnimDuration() const {
AnimationData* anim_data = &anim_lib[(int)anim_type];
return anim_data->timer[current_frame];
}
void Reset()
{
anim_timer = 0;
current_frame = 0;
loopable = true;
complete = false;
}
void Ensure(AnimationType type)
{
if (anim_type != type)
{
anim_type = type;
Reset();
}
}
void EnsureNoReset(AnimationType type)
{
if (anim_type != type)
{
anim_type = type;
}
}
const GPU_Rect& CurrentFrame() const
{
AnimationData* anim_data = &anim_lib[(int)anim_type];
return anim_data->rect[current_frame];
}
static const GPU_Rect& AnimFrame(AnimationType type, int timer)
{
AnimationData* anim_data = &anim_lib[(int)type];
int time_total = 0;
for (int i = 0; i < anim_data->frames; ++i)
{
time_total += anim_data->timer[i];
}
timer = timer % time_total;
int current_frame = 0;
while (timer > anim_data->timer[current_frame])
{
timer -= anim_data->timer[current_frame];
current_frame++;
}
return anim_data->rect[current_frame];
}
};
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<malloc/malloc.h>
struct node
{
struct node * left ;
int data ;
struct node * right ;
};
struct node * root = NULL;
struct node * insert(struct node * , int );
void preorder(struct node *);
void inorder(struct node *);
void postorder(struct node *);
void smallest(struct node * );
struct node * largest(struct node *);
int totalnodes(struct node * );
struct node * delete(struct node * ,int );
int main()
{
root = insert(root,51);
root =insert(root,27);
root =insert(root,64);
root =insert(root,77);
root =insert(root,46);
preorder(root);
printf("\n");
root = delete(root,51);
printf("\n");
inorder(root);
printf("\n");
postorder(root);
printf("\n");
smallest(root);
//largest(root);
int n = totalnodes(root);
printf("\n%d",n);
}
struct node *insert(struct node *root ,int val )
{
if(root == NULL)
{
root =(struct node *)malloc(sizeof(struct node ));
root->left =root->right = NULL;
root->data = val;
}
else
{
if(val < root->data )
root->left = insert(root->left,val);
else if(val >root->data)
root->right = insert(root->right,val);
else
printf("DUPLICATE ELEMENT NOT ALLOWED");
}
return root;
}
void preorder(struct node *root)
{
if(root != NULL)
{
printf("%d\n",root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(struct node * root)
{
if(root != NULL)
{
inorder(root->left);
printf("%d\n",root->data);
inorder(root->right);
}
}
void postorder(struct node *root)
{
if( root != NULL)
{
postorder(root->left);
postorder(root->right);
printf(" %d ",root->data);
}
}
void smallest(struct node * root )
{
if(root->left == NULL)
printf("%d",root->data);
else
smallest(root->left);
}
struct node * largest(struct node *root)
{
if(root->right == NULL)
return root ;
else
return largest(root->right);
}
int totalnodes(struct node * root )
{
if(root == NULL)
{ return 0;}
else
{
return (totalnodes(root->left) + totalnodes(root->right) + 1 );
}
}
struct node * delete(struct node * root,int val)
{
struct node * ptr ;
ptr = root ;
if(root == NULL)
printf("not found ");
else if (val < root ->data)
delete(root->left,val);
else if( val >root->data)
delete(root->right,val);
else if (root->left != NULL && root->right != NULL)//2 child
{
ptr = largest(root->left);
root->data = ptr->data;
delete(root->left ,ptr->data);
}
else
{
ptr = root ;
if(root->left == NULL && root->right == NULL )
root = NULL ;
else if ( root->left != NULL)
root = root->left ;
else
root = root->right ;
free(ptr);
}
return root ;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** rra_action.c
** File description:
** rra_action.c
*/
#include "my.h"
#include "pushswap.h"
list_info rra_action(list_info list)
{
int tmp = 0;
int i = 0;
tmp = list.list_a[list.size_a - 1];
i = list.list_a[list.size_a - 1];
while (i > 0) {
list.list_a[i] = list.list_a[i - 1];
i--;
}
list.list_a[0] = tmp;
my_putstr("rra ");
return (list);
}
|
C
|
// shape.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "image.h"
#include "array.h"
#include "shape.h"
#include "constant.h"
// Helper functions to compute the shape area, perimeter, and shape index
void loadData(ShapeAnalyser* ana, double** data);
void computeCM(Image* image, double* xcm, double* ycm);
void radialCoords(int npts, Point* points, double xcm, double ycm,
double* rad, double* theta);
void shapeGradient(int len, double* x, double* y, double* yprime);
void threePtGradient(int len, double* x, double* y, double* yprime);
int computePixelArea(int lx, int ly, double threshold, double** field);
double computeChainPerimeter(int npts, int* chain);
double computeArea(int npts, double* theta, double* r);
double computePerimeter(int npts, double* theta, double* r, double* dr);
double trapzInt(int nbins, double* x, double* y);
void insertSort(int npts, double* key, double* value);
ShapeAnalyser* createShapeAnalyser(int scale, int dataLx, int dataLy,
int kernelLen, double sigma,
int sgolayDegree, int sgolayLen,
double threshold) {
ShapeAnalyser* ana = malloc(sizeof(*ana));
ana->scale = scale;
ana->dataLx = dataLx;
ana->dataLy = dataLy;
ana->lx = dataLx*scale;
ana->ly = dataLy*scale;
ana->threshold = threshold;
// Create the image required for the analysis
ana->rawImage = createEmptyImage(ana->lx, ana->ly);
ana->intermImage = createEmptyImage(ana->lx, ana->ly);
ana->convImage = createEmptyImage(ana->lx, ana->ly);
// Create the Gaussian blurring kernels (two 1-D kernels)
ana->gaussX = createGaussianKernel(kernelLen, 1, sigma);
ana->gaussY = createGaussianKernel(1, kernelLen, sigma);
// Create Sgolay filters
ana->sgolayDegree = sgolayDegree;
ana->sgolayLength = sgolayLen; // Frame length should be an odd number
ana->sgolayRad = createSgolayFilter(ana->sgolayDegree,
ana->sgolayLength);
ana->sgolayDrad = createSgolayFilter(ana->sgolayDegree,
ana->sgolayLength);
return ana;
}
void deleteShapeAnalyser(ShapeAnalyser* ana) {
deleteImage(ana->rawImage);
deleteImage(ana->intermImage);
deleteImage(ana->convImage);
deleteImage(ana->gaussX);
deleteImage(ana->gaussY);
deleteSgolayFilter(ana->sgolayRad);
deleteSgolayFilter(ana->sgolayDrad);
free(ana);
}
ShapeInfo* getShapeInfo(ShapeAnalyser* ana, double** data) {
double twopi = 2.0*PF_PI;
// Rescale the phase field data to the image
loadData(ana, data);
// Blur the image using a Gaussian filter
conv(ana->gaussX, ana->rawImage, ana->intermImage);
conv(ana->gaussY, ana->intermImage, ana->convImage);
// Find centre of mass
double xcm, ycm;
computeCM(ana->convImage, &xcm, &ycm);
// Trace the boundary
Boundary* boundary = traceBoundary(ana->threshold, ana->convImage);
int npts = boundary->npoints; // Total number of boundary points
int nptsp1 = npts+1;
Point* boundpts = boundary->points;
// Determine the radial coordinates
double* theta = create1DDoubleArray(nptsp1); // +1 for endpt = starpt
double* rad = create1DDoubleArray(nptsp1);
radialCoords(npts, boundpts, xcm, ycm, rad, theta);
// Create a periodic extension so that the smoothing process
// can handle the boundary points as well
int extLen = ana->sgolayLength-1; // sgolayLength should be odd
int halfExtLen = extLen/2;
int fullLen = extLen+npts;
double* radExt = create1DDoubleArray(fullLen);
int ext = (halfExtLen/npts+1)*npts;
for (int i = 0; i < fullLen; i++) {
int j = (ext+i-halfExtLen)%npts;
radExt[i] = rad[j];
}
// Smooth radial data using Sgolay filter
double* radExtFiltered = create1DDoubleArray(fullLen);
sgolayFilt(ana->sgolayRad, fullLen, radExt, radExtFiltered);
// Extract the non-extended part of the filtered result
for (int i = 0; i < npts; i++) {
rad[i] = radExtFiltered[i+halfExtLen];
}
// Add in the endpt = startpt
theta[npts] = twopi;
rad[npts] = rad[0];
// Compute the first derivative (dr/dtheta)
double* drad = create1DDoubleArray(nptsp1);
shapeGradient(nptsp1, theta, rad, drad);
drad[npts] = drad[0]; // An approximation of the gradient at the boundary
// Identify numerically unstable points
int nbadpts = 0;
const int unstableThreshold = 100;
double* smoothRad = create1DDoubleArray(nptsp1);
for (int i = 0; i < npts; i++) { // Ignore endpt (which is equal to startpt)
smoothRad[i] = rad[i];
if (fabs(drad[i]) > unstableThreshold) {
rad[i] = -1.0;
nbadpts++;
}
}
// Do Lagrange interpolation if there are numerically unstable points
if (nbadpts > 0) {
int twonpts = 2*npts;
int threenpts = 3*npts;
const int ninter = 4;
int nmid = ninter/2;
double xint[ninter];
double yint[ninter];
double lagcoeffs[ninter];
for (int i = 0; i < npts; i++) {
// Find the unstable points
if (rad[i] < 0.0) {
int j = npts+i-1;
// Find the interpolation points
for (int k = 1; k <= nmid; k++) {
while (rad[j%npts] < 0.0 && j > 0.0) j--;
xint[nmid-k] = theta[j%npts];
yint[nmid-k] = rad[j%npts];
// Get the correct angle if the point
// crosses the periodic boundary
if (j < npts) xint[nmid-k] -= twopi;
j--;
}
j = npts+i+1;
for (int k = nmid; k < ninter; k++) {
while (rad[j%npts] < 0.0 && j < threenpts-1) j++;
xint[k] = theta[j%npts];
yint[k] = rad[j%npts];
// Get the correct angle if the point
// crosses the periodic boundary
if (j >= twonpts) xint[k] += twopi;
j++;
}
// Calculate the interpolation coefficients
for (int k = 0; k < ninter; k++) {
lagcoeffs[k] = yint[k];
for (int l = 0; l < ninter; l++) {
if (k != l) lagcoeffs[k] /= (xint[k]-xint[l]);
}
}
// Calculate interpolated value
smoothRad[i] = 0.0;
for (int k = 0; k < ninter; k++) {
double temp = 1.0;
for (int l = 0; l < ninter; l++) {
if (k != l) temp *= (theta[i]-xint[l]);
}
smoothRad[i] += temp*lagcoeffs[k];
}
}
}
smoothRad[npts] = smoothRad[0]; // Make sure endpt = startpt
// Recompute dr/dtheta
shapeGradient(nptsp1, theta, smoothRad, drad);
drad[npts] = drad[0];
}
double scale = ana->scale;
double scale2 = scale*scale;
ShapeInfo* info = malloc(sizeof *info);
info->pixels = computePixelArea(ana->dataLx, ana->dataLy,
ana->threshold, data);
info->area = computeArea(nptsp1, theta, smoothRad) / scale2;
info->perimeter = computePerimeter(nptsp1, theta, smoothRad, drad) / scale;
info->pixelArea = computePixelArea(ana->lx, ana->ly, ana->threshold,
ana->convImage->data) / scale2;
info->chainPerimeter = computeChainPerimeter(npts, boundary->chain) / scale;
// Clean up resources
if (boundary != NULL) {
deleteBoundary(boundary);
}
free(theta);
free(rad);
free(radExt);
free(radExtFiltered);
free(drad);
free(smoothRad);
return info;
}
void deleteShapeInfo(ShapeInfo* shapeInfo) {
free(shapeInfo);
}
void loadData(ShapeAnalyser* ana, double** data) {
for (int i = 0; i < ana->lx; i++) {
for (int j = 0; j < ana->ly; j++) {
ana->rawImage->data[i][j] = data[i/ana->scale][j/ana->scale];
}
}
}
void computeCM(Image* image, double* xcm, double* ycm) {
*xcm = 0.0;
*ycm = 0.0;
double mass;
double totalMass = 0.0;
double** data = image->data;
for (int i = 0; i < image->lx; i++) {
for (int j = 0; j < image->ly; j++) {
mass = data[i][j];
*xcm += (i+0.5)*mass;
*ycm += (j+0.5)*mass;
totalMass += mass;
}
}
*xcm /= totalMass;
*ycm /= totalMass;
}
void radialCoords(int npts, Point* boundpts, double xcm, double ycm,
double* rad, double* theta) {
// Get start angle
double angle, nextAngle, startAngle, dangle;
double pi = PF_PI;
double twopi = 2.0*pi;
int iangle = 0; // For counting the number of times crossed the branch cut
double dx = boundpts[0].x+0.5-xcm;
double dy = boundpts[0].y+0.5-ycm;
startAngle = atan2(-dy,-dx)+pi; // Range from 0 to 2 pi
angle = startAngle;
theta[0] = 0.0;
rad[0] = sqrt(dx*dx+dy*dy);
for (int i = 1; i < npts; i++) {
dx = boundpts[i].x+0.5-xcm;
dy = boundpts[i].y+0.5-ycm;
nextAngle = atan2(-dy,-dx)+pi-startAngle+twopi*iangle;
// Check if crossed the branch cut
dangle = nextAngle-angle;
if (fabs(dangle) > 1.95*pi) {
if (dangle < 0.0) {
nextAngle += twopi;
iangle++;
} else {
nextAngle -= twopi;
iangle--;
}
}
angle = nextAngle;
theta[i] = angle;
rad[i] = sqrt(dx*dx+dy*dy);
}
// Sort the angles
insertSort(npts, theta, rad);
}
void shapeGradient(int len, double* x, double* y, double* yprime) {
// Note that the size of yprime should be one less than that of y
// len should be the array length of x (or y)
// The algorithm for calculating the derivative is based on the
// finite difference method presented in the paper "A simple
// finite-difference grid with non-constant intervals" by Sundqvist and
// Veronis, Tellus 22 (1970)
int iu, id;
int yprimeLen = len-1;
double* dx = create1DDoubleArray(yprimeLen);
for (int i = 0; i < yprimeLen; i++) {
dx[i] = x[i+1]-x[i];
}
double dxRatio, dxRatio2;
for (int i = 0; i < yprimeLen; i++) {
iu = (i+1+yprimeLen)%yprimeLen;
id = (i-1+yprimeLen)%yprimeLen;
dxRatio = dx[i]/dx[id];
dxRatio2 = dxRatio*dxRatio;
yprime[i] = (y[iu]-dxRatio2*y[id]-(1-dxRatio2)*y[i])/(dx[i]*(1+dxRatio));
}
free(dx);
}
void threePtGradient(int len, double* x, double* y, double* yprime) {
int i, iu, id, idd;
int dxLen = len-1;
double* dx = create1DDoubleArray(dxLen);
for (i = 0; i < dxLen; i++) {
dx[i] = x[i+1]-x[i];
}
double dxsum = dx[0]+dx[1];
// Start point
yprime[0] = -(dxsum+dx[0])/(dx[0]*dxsum)*y[0] + dxsum/(dx[0]*dx[1])*y[1] -
dx[0]/(dx[1]*dxsum)*y[2];
for (i = 1; i < len-1; i++) {
iu = i+1;
id = i-1;
dxsum = dx[id]+dx[i];
yprime[i] = -dx[i]/(dx[id]*dxsum)*y[id] -
(dx[id]-dx[i])/(dx[id]*dx[i])*y[i] + dx[id]/(dx[i]*dxsum)*y[iu];
}
// End point
i = len-1;
id = len-2;
idd = len-3;
dxsum = dx[id]+dx[idd];
yprime[i] = dx[id]/(dx[idd]*dxsum)*y[idd] - dxsum/(dx[idd]*dx[id])*y[id] +
(dxsum+dx[id])/(dx[id]*dxsum)*y[i];
free(dx);
}
int computePixelArea(int lx, int ly, double threshold, double** field) {
int sum = 0;
for (int i = 0; i < lx; i++)
for (int j = 0; j < ly; j++)
if (field[i][j] > threshold) sum++;
return sum;
}
double computeChainPerimeter(int npts, int* chain) {
// Estimate the perimeter based on corner count algorithm by
// Proffitt and Rosen (Computer Graphics and Image Processing 20(4):347 1982)
int nnorm = 0;
int ndiag = 0;
int ncorner = 0;
for (int i = 0; i < npts; i++) {
if (chain[i] % 2 == 0) {
nnorm++;
} else {
ndiag++;
}
if (chain[(i+1)%npts] != chain[i]) ncorner++;
}
return nnorm*0.980 + ndiag*1.406 - ncorner*0.091;
}
double computeArea(int npts, double* theta, double* r) {
// Compute the area by A = 0.5 * int_0^{2pi} dtheta r^2(theta)
double* r2 = create1DDoubleArray(npts);
for (int i = 0; i < npts; i++) {
r2[i] = r[i]*r[i];
}
double area = fabs(trapzInt(npts, theta, r2))/2.0;
free(r2);
return area;
}
double computePerimeter(int npts, double* theta, double* r, double* dr) {
// Compute the perimeter by P = int_0^{2pi} dtheta sqrt(r^2+dr^2)
double* dl = create1DDoubleArray(npts);
for (int i = 0; i < npts; i++) {
dl[i] = sqrt(r[i]*r[i]+dr[i]*dr[i]);
}
double perimeter = fabs(trapzInt(npts, theta, dl));
free(dl);
return perimeter;
}
double trapzInt(int nbins, double* x, double* y) {
// Numerical integration using the trapezoidal method
double total = 0.0;
for (int i = 0; i < nbins-1; i++) {
total += (y[i+1]+y[i])*(x[i+1]-x[i]);
}
return total/2.0;
}
void insertSort(int npts, double* key, double* value) {
// An implementation of the insertion sort algorithm for
// sorting a key-value pair array based on the key values
double tmpKey, tmpValue;
int j;
for (int i = 1; i < npts; i++) {
tmpKey = key[i];
tmpValue = value[i];
j = i-1;
while (j >= 0 && key[j] > tmpKey) {
key[j+1] = key[j];
value[j+1] = value[j];
j--;
}
key[j+1] = tmpKey;
value[j+1] = tmpValue;
}
}
|
C
|
/*
* Licensed to Systerel under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Systerel licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "sopc_array.h"
#include "sopc_mem_alloc.h"
#include <assert.h>
#include <stdint.h>
#include <stdlib.h> /* qsort */
#include <string.h>
#define ARRAY_ELT(a, idx) ((void*) (a->data + idx * a->element_size))
struct _SOPC_Array
{
uint8_t* data;
size_t element_size;
size_t sz;
size_t cap;
SOPC_Array_Free_Func free_func;
};
static bool array_grow(SOPC_Array* a, size_t min_size)
{
assert(a != NULL);
if (a->cap >= min_size)
{
return true;
}
size_t cap = (a->cap != 0 ? a->cap : 1);
while (cap < min_size)
{
cap *= 2;
}
void* data = SOPC_Realloc(a->data, a->cap * a->element_size, cap * a->element_size);
if (data == NULL)
{
return false;
}
a->data = data;
a->cap = cap;
return true;
}
SOPC_Array* SOPC_Array_Create(size_t element_size, size_t initial_capacity, SOPC_Array_Free_Func free_func)
{
SOPC_Array* a = SOPC_Calloc(1, sizeof(SOPC_Array));
if (a == NULL)
{
return NULL;
}
a->element_size = element_size;
a->free_func = free_func;
if (!array_grow(a, initial_capacity))
{
SOPC_Free(a);
return NULL;
}
return a;
}
SOPC_Array* SOPC_Array_Copy(const SOPC_Array* array)
{
assert(array != NULL);
SOPC_Array* copy = SOPC_Array_Create(array->element_size, array->sz, array->free_func);
if (copy == NULL)
{
return NULL;
}
if (copy->data != NULL)
{
memcpy(copy->data, array->data, array->element_size * array->sz);
}
copy->sz = array->sz;
return copy;
}
void SOPC_Array_Delete(SOPC_Array* array)
{
if (array == NULL)
{
return;
}
if (array->free_func != NULL)
{
for (size_t i = 0; i < array->sz; ++i)
{
array->free_func(ARRAY_ELT(array, i));
}
}
SOPC_Free(array->data);
SOPC_Free(array);
}
bool SOPC_Array_Append_Values(SOPC_Array* array, const void* data, size_t n_elements)
{
assert(array != NULL);
if (n_elements == 0)
{
return true;
}
if (!array_grow(array, array->sz + n_elements))
{
return false;
}
if (data != NULL)
{
memcpy(ARRAY_ELT(array, array->sz), data, n_elements * array->element_size);
}
else
{
memset(ARRAY_ELT(array, array->sz), 0, n_elements * array->element_size);
}
array->sz += n_elements;
return true;
}
void* SOPC_Array_Get_Ptr(const SOPC_Array* array, size_t index)
{
assert(array != NULL);
assert(index < array->sz);
return ARRAY_ELT(array, index);
}
size_t SOPC_Array_Size(const SOPC_Array* array)
{
assert(array != NULL);
return array->sz;
}
void SOPC_Array_Sort(SOPC_Array* array, SOPC_Array_Compare_Func compare_func)
{
assert(array != NULL);
qsort(array->data, array->sz, array->element_size, compare_func);
}
void* SOPC_Array_Into_Raw(SOPC_Array* array)
{
assert(array != NULL);
void* data = array->data;
if (array->sz < array->cap)
{
data = SOPC_Realloc(data, array->cap * array->element_size, array->sz * array->element_size);
}
SOPC_Free(array);
return data;
}
SOPC_Array_Free_Func SOPC_Array_Get_Free_Func(SOPC_Array* array)
{
assert(array != NULL);
return array->free_func;
}
void SOPC_Array_Set_Free_Func(SOPC_Array* array, SOPC_Array_Free_Func func)
{
assert(array != NULL);
array->free_func = func;
}
|
C
|
#include "graph.h"
/**
* print_graph - prints the graph information
*/
void print_graph(struct graph *g)
{
int i, j;
struct node *n;
printf("graph size: %d\n", g->sz);
printf("graph roots:");
for (i = 0; i < g->root_count; i++)
printf("%d ", g->roots[i]->id);
printf("\ngraph root_count: %d\n\n", g->root_count);
for (i = 0; i < g->sz; i++) {
n = g->procs[i];
printf("[node %d] prog: %s\n", n->id, n->prog);
printf("[node %d] children: ", n->id);
for (j = 0; j < n->child_count; j++)
printf("%d ", n->children[j]);
printf("\n[node %d] child_count: %d\n", n->id, n->child_count);
printf("[node %d] input: %s\n", n->id, n->input);
printf("[node %d] output: %s\n", n->id, n->output);
printf("[node %d] status: %d\n\n", n->id, n->status);
}
}
/**
* graph_has_cycles - checks for cycle starting from node n
*
* Returns 1 if a cycle exists, and 0 otherwise.
*/
static int
graph_has_cycles(struct graph *g, struct node *n, int *visited, int visits)
{
if (contains(n->id, visited, visits)) return 1;
visited[visits++] = n->id;
int i;
int ret = 0;
for (i = 0; i < n->child_count; i++) {
ret |= graph_has_cycles(g, g->procs[n->children[i]], visited, visits);
}
return ret;
}
/**
* has_cycles - checks for cycle starting from all roots
*
* returns 1 if a graph contains cycle, and 0 otherwise.
*/
int has_cycles(struct graph *g)
{
int i;
int visited[g->sz];
for (i = 0; i < g->root_count; i++) {
if (graph_has_cycles(g, g->roots[i], visited, 0)) return 1;
}
return 0;
}
/**
* has_roots - checks whether the graph(s) is rooted or not
*
* returns 1 if the graph has at least one root, and 0 otherwise.
*/
int has_roots(struct graph *g)
{
return g->root_count > 0;
}
/**
* is_valid_graph - checks the validity of the graph (no cycles)
*
* returns 1 if the graph is valid, and 0 otherwise.
*/
int is_valid_graph(struct graph *g)
{
return has_roots(g) && !has_cycles(g);
}
|
C
|
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include "pokemon_trainer.h"
#define POKEMON_TRAINER_MIN_LENGTH_LOCAL 1
#define POKEMON_TRAINER_MIN_LENGTH_REMOTE 0
/**
* Create an empty PokemonList, with the given max and min length properties.
* The min property is only enforced by pokemonListRemove, so the list can
* have length lower than that until enough pokemon are added.
*
* @returns:
* PokemonList object. if max_length or min_length aren't positive or a
* memory allocation occured, return NULL.
*/
static PokemonList pokemonListCreate(int max_length, int min_length) {
PokemonList base;
if (max_length < min_length || min_length < 0 || max_length <= 0)
return NULL;
base = malloc(sizeof(struct pokemon_list_t));
if (NULL == base) return NULL;
base->list = malloc(max_length * sizeof(Pokemon*));
if (NULL == base->list) {
free(base);
return NULL;
}
base->max_length = max_length;
base->min_length = min_length;
base->length = 0;
return base;
}
/**
* Destroy a list without destroying the pokemon within. You shouldn't normally
* use this, use pokemonListDestroy unless you're absolutely sure you won't
* be leaking memory.
*
* If the given list is NULL, no action is taken.
*/
static void pokemonListShallowDestroy(PokemonList base) {
if (NULL == base) return;
free(base->list);
free(base);
}
/**
* Destroy a list and its pokemon.
*/
static void pokemonListDestroy(PokemonList base) {
if (NULL == base) return;
// Free all of the trainer's pokemon
for (int i=0; i < base->length; i++) {
pokemonDestroy(base->list[i]);
}
pokemonListShallowDestroy(base);
}
/**
* Append a pokemon to the given list, unless the list is full. The pokemon
* is NOT copied, so don't destroy it yourself.
*
* @returns:
* POKEMON_TRAINER_SUCCESS - successful run
* POKEMON_TRAINER_PARTY_FULL - list's length is already max_length
*/
static PokemonTrainerResult pokemonListAppend(PokemonList base,
Pokemon pokemon) {
// Boundry checks
if (base->length == base->max_length)
return POKEMON_TRAINER_PARTY_FULL;
// Add pokemon to list
base->length++;
base->list[base->length - 1] = pokemon;
return POKEMON_TRAINER_SUCCESS;
}
/**
* Remove a pokemon from the list, given its _one-based_ index, and move all
* pokemon with a higher index one index back. Unless keep is true, the pokemon
* will be destroyed. The pokemon won't be removed if the list is already at
* its min_length.
*
* @returns:
* POKEMON_TRAINER_SUCCESS - successful run
* POKEMON_TRAINER_INVALID_INDEX - given index is not-positive or more than
* the current list's length.
* POKEMON_TRAINER_REMOVE_LAST - trying to shrink the list past its min length
*/
static PokemonTrainerResult pokemonListRemove(PokemonList base, int index,
bool keep) {
if (index < 1 || index > base->length)
return POKEMON_TRAINER_INVALID_INDEX;
if (base->length <= base->min_length)
return POKEMON_TRAINER_REMOVE_LAST;
if (!keep) {
pokemonDestroy(base->list[index -1]);
}
for (int i=index; i < base->length; i++) {
base->list[i - 1] = base->list[i];
}
base->length--;
return POKEMON_TRAINER_SUCCESS;
}
/**
* Returns the pokemon at the requested index. Index is one based.
*
* @returns:
* Pokemon object. If given list is NULL or index is invalid, return NULL.
*/
static Pokemon pokemonListGet(PokemonList base, int index) {
if (NULL == base) return NULL;
if (index < 1 || index > base->length) return NULL;
return base->list[index - 1];
}
/**
* Copy and append all pokemon from the source list (starting from
* source_offset) to the dest list. Note that pokemon are copied here.
*
* @returns:
* POKEMON_TRAINER_SUCCESS - successful run
* POKEMON_TRAINER_OUT_OF_MEM - memory allocation error
*/
static PokemonTrainerResult pokemonListCopy(PokemonList dest,
PokemonList source, int source_offset) {
int amount_to_copy;
amount_to_copy = source->length - source_offset;
for (int i=1; i <= amount_to_copy; i++) {
PokemonTrainerResult append_result;
Pokemon current_pokemon, current_copy;
current_pokemon = pokemonListGet(source, i + source_offset);
current_copy = pokemonCopy(current_pokemon);
if (NULL == current_copy) {
return POKEMON_TRAINER_OUT_OF_MEM;
}
append_result = pokemonListAppend(dest, current_copy);
if (append_result != POKEMON_TRAINER_SUCCESS) {
pokemonDestroy(current_copy);
return append_result;
}
}
return POKEMON_TRAINER_SUCCESS;
}
/**
* Overwrite the dest list, starting from dest_offset, with pokemon from
* source list, starting from source_offset, until either dest is full or
* we've reached the end of source. Don't use this function unless you know
* what you're doing! Pokemon are moved, so you'll probably need to use
* shallowDestroy on one of the lists. Also dest can lose some pokemon, so
* there's danger of memory leaks.
*
* If source_offset or dest_offset are negative or go beyong their respective
* list's length, do nothing.
*/
static void pokemonListMove(PokemonList dest, PokemonList source,
int dest_offset, int source_offset) {
// Check for valid args and no-op cases
if (dest_offset < 0 || dest_offset > dest->length) return;
if (source_offset < 0 || source_offset > source->length) return;
// Calculate how much to move and space required
int amount_to_move, target_length;
amount_to_move = source->length - source_offset;
target_length = dest_offset + amount_to_move;
// Move less items if we'd go past dest's max length
if (target_length > dest->max_length) {
target_length = dest->max_length;
amount_to_move = target_length - dest_offset;
}
// Move items and update dest's length
for (int i=0; i < amount_to_move; i++) {
dest->list[dest_offset + i] = source->list[source_offset + i];
}
dest->length = target_length;
return;
}
/**
* Sort the list based on pokemon rank. Lower indexes are preferred to higher.
*/
static void pokemonListSort(PokemonList base) {
bool sorted = false;
while (!sorted) {
sorted = true;
for (int i=0; i < base->length - 1; i++) {
int rank1, rank2;
rank1 = pokemonGetRank(base->list[i]);
rank2 = pokemonGetRank(base->list[i+1]);
if (rank1 < rank2) {
Pokemon temp;
temp = base->list[i];
base->list[i] = base->list[i+1];
base->list[i+1] = temp;
sorted = false;
}
}
}
}
PokemonTrainer pokemonTrainerCreate(char* name, Pokemon initial_pokemon,
int max_num_local, int max_num_remote) {
// Check arguments are valid
if ((NULL == name) || (strlen(name) == 0) || (NULL == initial_pokemon)
|| (max_num_local <= 0) || (max_num_remote <= 0)) return NULL;
// Allocate memory
PokemonTrainer trainer;
trainer = malloc(sizeof(struct pokemon_trainer_t));
if (NULL == trainer) return NULL;
trainer->name = malloc(strlen(name) + 1);
trainer->local_pokemon = pokemonListCreate(max_num_local,
POKEMON_TRAINER_MIN_LENGTH_LOCAL);
trainer->remote_pokemon = pokemonListCreate(max_num_remote,
POKEMON_TRAINER_MIN_LENGTH_REMOTE);
if ((NULL == trainer->name) || (NULL == trainer->local_pokemon) ||
(NULL == trainer->remote_pokemon)) {
pokemonTrainerDestroy(trainer);
return NULL;
}
// Fill trainer object
Pokemon initial_pokemon_copy;
PokemonTrainerResult result;
strcpy(trainer->name, name);
initial_pokemon_copy = pokemonCopy(initial_pokemon);
result = pokemonListAppend(trainer->local_pokemon, initial_pokemon_copy);
if (result != POKEMON_TRAINER_SUCCESS) {
pokemonDestroy(initial_pokemon_copy);
pokemonTrainerDestroy(trainer);
return NULL;
}
return trainer;
}
void pokemonTrainerDestroy(PokemonTrainer trainer) {
if (NULL == trainer) return;
if (NULL != trainer->name) {
free(trainer->name);
}
pokemonListDestroy(trainer->local_pokemon);
pokemonListDestroy(trainer->remote_pokemon);
free(trainer);
}
PokemonTrainer pokemonTrainerCopy(PokemonTrainer trainer) {
// Check given trainer is valid
if (NULL == trainer) return NULL;
// Create a trainer using the given trainer's first pokemon
PokemonTrainer new_trainer;
Pokemon first_pokemon;
int max_num_local, max_num_remote;
first_pokemon = pokemonListGet(trainer->local_pokemon, 1);
max_num_local = trainer->local_pokemon->max_length;
max_num_remote = trainer->remote_pokemon->max_length;
new_trainer = pokemonTrainerCreate(trainer->name, first_pokemon,
max_num_local, max_num_remote);
if (NULL == new_trainer) return NULL;
// Add the rest of the pokemon
PokemonTrainerResult local_result, remote_result;
local_result = pokemonListCopy(new_trainer->local_pokemon,
trainer->local_pokemon, 1);
remote_result = pokemonListCopy(new_trainer->remote_pokemon,
trainer->remote_pokemon, 0);
if (local_result != POKEMON_TRAINER_SUCCESS ||
remote_result != POKEMON_TRAINER_SUCCESS) {
pokemonTrainerDestroy(new_trainer);
return NULL;
}
return new_trainer;
}
PokemonTrainerResult pokemonTrainerAddPokemon(PokemonTrainer trainer,
Pokemon pokemon) {
// Check args
if (NULL == trainer || NULL == pokemon) return POKEMON_TRAINER_NULL_ARG;
Pokemon pokemon_copy = pokemonCopy(pokemon);
PokemonTrainerResult append_result;
if (NULL == pokemon_copy) return POKEMON_TRAINER_OUT_OF_MEM;
append_result = pokemonListAppend(trainer->local_pokemon, pokemon_copy);
if (append_result != POKEMON_TRAINER_SUCCESS) {
pokemonDestroy(pokemon_copy);
}
return append_result;
}
Pokemon pokemonTrainerGetPokemon(PokemonTrainer trainer, int pokemon_index) {
// Check args
if (NULL == trainer) return NULL;
// Return pokemon
return pokemonListGet(trainer->local_pokemon, pokemon_index);
}
PokemonTrainerResult pokemonTrainerRemovePokemon(PokemonTrainer trainer,
int pokemon_index) {
// Check args
if (NULL == trainer) return POKEMON_TRAINER_NULL_ARG;
return pokemonListRemove(trainer->local_pokemon, pokemon_index, false);
}
PokemonTrainerResult pokemonTrainerDepositPokemon(PokemonTrainer trainer,
int pokemon_index) {
if (NULL == trainer) return POKEMON_TRAINER_NULL_ARG;
Pokemon pokemon_to_deposit;
PokemonTrainerResult result;
pokemon_to_deposit = pokemonListGet(trainer->local_pokemon, pokemon_index);
if (NULL == pokemon_to_deposit) return POKEMON_TRAINER_INVALID_INDEX;
// Perform the move via append from one list and remove from the other
result = pokemonListAppend(trainer->remote_pokemon, pokemon_to_deposit);
if (result != POKEMON_TRAINER_SUCCESS) {
// Translate error codes to the deposit use case.
if (result == POKEMON_TRAINER_PARTY_FULL)
return POKEMON_TRAINER_DEPOSIT_FULL;
return result;
}
result = pokemonListRemove(trainer->local_pokemon, pokemon_index, true);
if (result != POKEMON_TRAINER_SUCCESS) {
// Undo the append above in case of error when removing from
// local_pokemon list
int last_pokemon = trainer->remote_pokemon->length;
pokemonListRemove( trainer->remote_pokemon, last_pokemon, true);
// Translate error codes for the deposit use case.
if (result == POKEMON_TRAINER_REMOVE_LAST)
return POKEMON_TRAINER_DEPOSIT_LAST;
}
return result;
}
PokemonTrainerResult pokemonTrainerWithdrawPokemon(PokemonTrainer trainer,
int pokemon_index) {
if (NULL == trainer) return POKEMON_TRAINER_NULL_ARG;
Pokemon pokemon_to_withdraw;
PokemonTrainerResult result;
pokemon_to_withdraw = pokemonListGet(trainer->remote_pokemon,
pokemon_index);
if (NULL == pokemon_to_withdraw) return POKEMON_TRAINER_INVALID_INDEX;
// Perform the move via append from one list and remove from the other
result = pokemonListAppend(trainer->local_pokemon, pokemon_to_withdraw);
if (result != POKEMON_TRAINER_SUCCESS) return result;
result = pokemonListRemove(trainer->remote_pokemon, pokemon_index, true);
if (result != POKEMON_TRAINER_SUCCESS) {
// Undo the append above if there was an error removing from the
// remote_pokemon list
int last_pokemon = trainer->local_pokemon->length;
pokemonListRemove(trainer->local_pokemon, last_pokemon, true);
}
return result;
}
int pokemonTrainerGetNumberOfPokemons(PokemonTrainer trainer) {
assert(NULL != trainer);
return trainer->local_pokemon->length + trainer->remote_pokemon->length;
}
Pokemon pokemonTrainerGetMostRankedPokemon(PokemonTrainer trainer) {
if (NULL == trainer) return NULL;
int max_rank = -1;
Pokemon max_rank_pokemon;
for (int i=1, rank; i <= trainer->local_pokemon->length; i++) {
Pokemon current_pokemon = pokemonListGet(trainer->local_pokemon, i);
rank = pokemonGetRank(current_pokemon);
if (rank > max_rank) {
max_rank = rank;
max_rank_pokemon = current_pokemon;
}
}
for (int i=1, rank; i <= trainer->remote_pokemon->length; i++) {
Pokemon current_pokemon = pokemonListGet(trainer->remote_pokemon, i);
rank = pokemonGetRank(current_pokemon);
if (rank > max_rank) {
max_rank = rank;
max_rank_pokemon = current_pokemon;
}
}
return max_rank_pokemon;
}
PokemonTrainerResult pokemonTrainerMakeMostRankedParty(PokemonTrainer trainer) {
if (NULL == trainer) return POKEMON_TRAINER_NULL_ARG;
// Create a combined list of local and remote pokemon, we'll sort that.
int combined_party_length, local_length, remote_length;
local_length = trainer->local_pokemon->length;
remote_length = trainer->remote_pokemon->length;
combined_party_length = local_length + remote_length;
PokemonList combined_party = pokemonListCreate(combined_party_length, 0);
if (NULL == combined_party) return POKEMON_TRAINER_OUT_OF_MEM;
pokemonListMove(combined_party, trainer->local_pokemon, 0, 0);
pokemonListMove(combined_party, trainer->remote_pokemon, local_length, 0);
// Sort
pokemonListSort(combined_party);
// Fill up the local_pokemon list up to the max
pokemonListMove(trainer->local_pokemon, combined_party, 0, 0);
local_length = trainer->local_pokemon->length;
// Put the remaining pokemon in the remote_pokemon list
pokemonListMove(trainer->remote_pokemon, combined_party, 0, local_length);
// Free the combined_party list. Use ShallowDestroy because we didn't copy
// the actual pokemon while moving them.
pokemonListShallowDestroy(combined_party);
return POKEMON_TRAINER_SUCCESS;
}
PokemonTrainerResult pokemonTrainerPrintEnumeration(PokemonTrainer trainer,
FILE* file) {
if (NULL == trainer || NULL == file) return POKEMON_TRAINER_NULL_ARG;
PokemonResult ret;
for (int i = 1; i <= trainer->local_pokemon->length; i++) {
Pokemon pokemon = pokemonListGet(trainer->local_pokemon, i);
fprintf(file, "%s: ", trainer->name);
ret = pokemonPrintName(pokemon, file);
if (POKEMON_OUT_OF_MEM == ret) return POKEMON_TRAINER_OUT_OF_MEM;
fprintf(file, "\n");
ret = pokemonPrintName(pokemon, file);
if (POKEMON_OUT_OF_MEM == ret) return POKEMON_TRAINER_OUT_OF_MEM;
fprintf(file, ": ");
ret = pokemonPrintVoice(pokemon, file);
if (POKEMON_OUT_OF_MEM == ret) return POKEMON_TRAINER_OUT_OF_MEM;
fprintf(file, "\n");
}
return POKEMON_TRAINER_SUCCESS;
}
|
C
|
#ifndef PROJECT_UTILS_H
#define PROJECT_UTILS_H
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
typedef uint32_t ui;
typedef uint64_t ul;
typedef uint8_t uc;
typedef uint16_t us;
#ifndef EXTERN
#define EXTERN extern
#endif
// Logger of a simple message
#define log(message) printf((message));
// Logger of a message with a parameter
#define log_param(message, param) printf((message), param);
// Logger in the stderr of a message error
#define log_error(message) fprintf(stderr, message);
// All the errors to output if something has gone wrong
enum{ERROR_ARGUMENTS=1, ERROR_INPUT_OUTPUT_FILE=(1<<1), ERROR_OPTION=(1|1<<1)}errors;
/**
* strcpy does not copy the '\0'
* so I wrote method to copy from
* one array of char to the other. Included
* all the null terminator
* @param dest destination of the copy
* @param source of the string to copy
* @param str_length the length of the string to copy
*/
EXTERN void copy_string(uc* dest, const uc* source,us str_length);
/**
* strcmp does not compare the '\0'
* so I wrote method to compare an
* array of char with the other
* taking into account the null
* terminator as well
* @param dest the destination string to compare
* @param source string to compare
* @param str_length length of the source and destination string
* @return 0 if the string are equals otherwise 1
*/
EXTERN us compare_string(const uc* dest, const uc* source,us str_length);
#endif //PROJECT_UTILS_H
|
C
|
// The code is adapted from https://github.com/imsure/parallel-programming/blob/master/matrix-multiplication/mpi-mm.c
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int TAG = 777;
int main(int argc, char ** argv) {
double **A, **B, **C, *tmp;
double elapsed_time;
int numElements, offset, stripSize, rank, size, N, i, j, k;
// Set up MPI
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Size of the matrix
N = atoi(argv[1]);
if (rank == 0) {
printf("\n***** Starting Test 3: Matrix-by-Matrix Multiplication *****\n");
printf("Matrix size is %d, number of processes is %d.\n", N, size);
}
// Allocate A on main and worker processes
if (rank == 0) {
tmp = (double *) malloc (sizeof(double ) * N * N);
A = (double **) malloc (sizeof(double *) * N);
for (i = 0; i < N; i++) A[i] = &tmp[i * N];
}
else {
tmp = (double *) malloc (sizeof(double ) * N * N / size);
A = (double **) malloc (sizeof(double *) * N / size);
for (i = 0; i < N / size; i++) A[i] = &tmp[i * N];
}
// Allocate B on all processes
tmp = (double *) malloc (sizeof(double ) * N * N);
B = (double **) malloc (sizeof(double *) * N);
for (i = 0; i < N; i++) B[i] = &tmp[i * N];
// Allocate C on main and worker processes
if (rank == 0) {
tmp = (double *) malloc (sizeof(double ) * N * N);
C = (double **) malloc (sizeof(double *) * N);
for (i = 0; i < N; i++) C[i] = &tmp[i * N];
}
else {
tmp = (double *) malloc (sizeof(double ) * N * N / size);
C = (double **) malloc (sizeof(double *) * N / size);
for (i = 0; i < N / size; i++) C[i] = &tmp[i * N];
}
// Init A and B with random numbers
if (rank == 0) {
srand(time(NULL));
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
A[i][j] = rand() / RAND_MAX;
B[i][j] = rand() / RAND_MAX;
}
}
}
stripSize = N / size;
// Init C with zeros for each process
for (i = 0; i < stripSize; i++) {
for (j = 0; j < N; j++) {
C[i][j] = 0.0;
}
}
if (rank == 0) {
elapsed_time = MPI_Wtime();
}
if (rank == 0) {
// Send parts of A to workers
offset = stripSize;
numElements = stripSize * N;
for (i=1; i<size; i++) {
MPI_Send(A[offset], numElements, MPI_DOUBLE, i, TAG, MPI_COMM_WORLD);
offset += stripSize;
}
}
else {
// Receive parts of A
MPI_Recv(A[0], stripSize * N, MPI_DOUBLE, 0, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
// Send B to every process
MPI_Bcast(B[0], N*N, MPI_DOUBLE, 0, MPI_COMM_WORLD);
// Matrix multiplication
for (i = 0; i < stripSize; i++) {
for (j = 0; j < N; j++) {
for (k = 0; k < N; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Main process receives results
if (rank == 0) {
offset = stripSize;
numElements = stripSize * N;
for (i=1; i<size; i++) {
MPI_Recv(C[offset], numElements, MPI_DOUBLE, i, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
offset += stripSize;
}
}
else {
// Send results to the main process
MPI_Send(C[0], stripSize * N, MPI_DOUBLE, 0, TAG, MPI_COMM_WORLD);
}
if (rank == 0) {
elapsed_time = MPI_Wtime() - elapsed_time;
printf("Parallel ijk: %f milliseconds.\n", elapsed_time * 1000);
}
MPI_Finalize();
return 0;
}
|
C
|
//Program in C to reverse a linked list of size n
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *link;
};
void main()
{
//user input to take size of linked list
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
//user input to take first element of the liked list
int f1;
printf("Enter the first element in the linked list: ");
scanf("%d", &f1);
//Creating a pointer by type-casting
struct Node *A;
A = (struct Node *) malloc(sizeof(struct Node));
A->data = f1;
A->link = NULL;
//declaring head and pointers
struct Node *head, *p;
head = A;
p = head;
//loop to input next nodes from user
for(int i = 1; i<n; ++i)
{
printf("Enter the next element in the linked list: ");
scanf("%d", &f1);
A = (struct Node *) malloc(sizeof(struct Node));
A->data = f1;
A->link = NULL;
//linking the notes
p->link = A;
//jumping to the current node
p = p->link;
}
//displaying to the linked list
p = head;
printf("-------------------------------------------\n");
printf("These are the elements in the linked list:\n");
while(p != NULL)
{
printf("%d \t", p->data);
p = p->link;
}
//reversing the list
struct Node *p_node, *c_node, *n_node;
p_node = NULL;
c_node = head;
n_node = NULL;
while(c_node != NULL)
{
n_node = c_node->link;
c_node->link = p_node;
p_node = c_node;
c_node = n_node;
}
head = p_node;
//displaying the reversed linked list
p = head;
printf("\n-------------------------------------------\n");
printf("These are the elements in the reversed linked list:\n");
while(p != NULL)
{
printf("%d \t", p->data);
p = p->link;
}
}
|
C
|
/*
* (c) copyright 1995 by the Vrije Universiteit, Amsterdam, The Netherlands.
* For full copyright and restrictions on use see the file COPYRIGHT in the
* top level of the Panda distribution.
*/
#include "pan_sys_cache.h"
#include "pan_sys.h"
#include <assert.h>
#define TAIL (entry_p)1 /* Illegal pointer at tail */
void
pan_sys_cache_start(void)
{
}
void
pan_sys_cache_end(void)
{
}
void
pan_sys_cache_init(cache_p cache, int max)
{
cache->max = max;
cache->nr = 0;
cache->head = TAIL;
cache->lock = pan_mutex_create();
}
void
pan_sys_cache_clear(cache_p cache)
{
assert(cache->nr == 0);
assert(cache->head == TAIL);
cache->max = -1;
pan_mutex_clear(cache->lock);
}
entry_p
pan_sys_cache_get(cache_p cache)
{
entry_p e = TAIL;
pan_mutex_lock(cache->lock);
if (cache->nr != 0){
e = cache->head;
cache->head = e->next;
cache->nr--;
}
pan_mutex_unlock(cache->lock);
if (e == TAIL) return NULL;
e->next = NULL;
return e;
}
int
pan_sys_cache_put(cache_p cache, entry_p entry)
{
int ret = 0;
assert(entry->next == NULL);
pan_mutex_lock(cache->lock);
if (cache->nr < cache->max){
entry->next = cache->head;
cache->head = entry;
cache->nr++;
ret = 1;
}
pan_mutex_unlock(cache->lock);
return ret;
}
|
C
|
#include <stdio.h>
#include<stdbool.h>
#define MAX 10
/*
Author: Bhoj Bahadur Karki
purpose : Selection Sort algorithm.
date: 2020-March-26th
*/
// array initialization
int array_storage[MAX] = {2,99,33,44,11,55,55676,77,85,6};
void DisplayItem(){
printf("[");
int c;
for(c = 0; c < MAX;c++){
printf("%d, ",array_storage[c]);
}
printf("]\n");
}
void SelectionSort(){
for(int i=0;i<MAX-1;i++){
int min = i;
for(int j =i+1;j< MAX;j++){
if (array_storage[min]>array_storage[j]){
min = j;
}
}
if(min != i){
// swap values
printf("\nItems swapped: [ %d, %d ]\n" , array_storage[i], array_storage[min]);
int temp = array_storage[min];
array_storage[min]=array_storage[i];
array_storage[i]=temp;
}
printf("\nIteriation : %d ",i+1);
DisplayItem();
}
}
int main(){
DisplayItem();
SelectionSort();
DisplayItem();
}
|
C
|
#include "buf.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NOVERLAP(buf, b, n) \
if (b + n >= (buf)->buf && b < (buf)->last) { \
errno = EINVAL; \
return -1; \
}
#define NOVERFLOW(buf, n) \
if ((buf)->next_write + n > (buf)->last) { \
errno = EINVAL; \
return -1; \
}
void buf_init_values(buf_t* buf, char* cbuf, size_t cap)
{
buf->buf = cbuf;
buf->init_cap = cap;
buf->cap = cap;
buf->last = cbuf + cap;
buf_reset_offsets(buf);
}
int buf_init(buf_t* buf, size_t cap)
{
char* cbuf;
if (buf == NULL) {
errno = EINVAL;
return -1;
}
if ((cbuf = malloc(cap * sizeof(char))) == NULL)
return -1;
buf_init_values(buf, cbuf, cap);
return 0;
}
buf_t* buf_create(size_t cap)
{
buf_t* buf;
if ((buf = calloc(1, sizeof(buf_t))) == NULL)
return NULL;
if (buf_init(buf, cap) == -1) {
free(buf);
return NULL;
}
return buf;
}
void buf_reset(buf_t* buf)
{
if (buf->cap > buf->init_cap &&
(buf->buf = realloc(buf->buf, buf->init_cap)) == NULL) {
perror("realloc");
abort();
}
buf_init_values(buf, buf->buf, buf->init_cap);
}
int buf_reserve(buf_t* buf, size_t additional)
{
size_t read_offset = buf->next_read - buf->buf;
size_t write_offset = buf->next_write - buf->buf;
if ((buf->buf = realloc(buf->buf, buf->cap + additional)) == NULL)
return -1;
buf->next_write = buf->buf + write_offset;
buf->next_read = buf->buf + read_offset;
buf->cap += additional;
buf->last = buf->buf + buf->cap;
return 0;
}
int buf_write(buf_t* buf, const char* b, int n)
{
if (n < 0) {
errno = EINVAL;
return -1;
}
NOVERFLOW(buf, n);
NOVERLAP(buf, b, n);
buf->next_write = memcpy(buf->next_write, b, n);
return n;
}
int buf_read(const buf_t* buf, char* b, int n)
{
int read;
if (n < 0) {
errno = EINVAL;
return -1;
}
NOVERLAP(buf, b, n);
read = buf_readable(buf);
read = n > read ? read : n;
memcpy(b, buf->next_read, read);
return read;
}
void buf_free(buf_t* buf)
{
if (buf != NULL && buf->buf != NULL) {
free(buf->buf);
free(buf);
}
}
bool buf_compact(buf_t* buf)
{
if (buf->next_read == buf->buf)
return 0;
int len = buf_readable(buf);
memmove(buf->buf, buf->next_read, len);
buf->next_write = buf->buf + len;
buf->next_read = buf->buf;
return 1;
}
|
C
|
/**
******************************************************************************
* @file drv_iic.cpp
* @author Sweet
* @brief STM32F4gpioģiic
* @version 1.0
* @date 2019.06.23
* @editby
==============================================================================
##### How to use this conf #####
==============================================================================
1bsp_iic.h
2ʵ hiic
һIIC_HandleTypeDefָ
3 IIC_Config io
4 IIC_Init ʼ
5ⲿ
******************************************************************************
* @attention
******************************************************************************
*/
/* Includes ----------------------------------------------------------------------*/
#include "drv_iic.h"
#include "drv_timer.h"
GPIO_TypeDef *SDA_GPIOx;
uint16_t SDA_PIN;
GPIO_TypeDef *SCL_GPIOx;
uint16_t SCL_PIN;
/* Private function prototypes -----------------------------------------------*/
/**
* @brief IICʼ
* @param void
* @return void
*/
void IIC_Init(void)
{
//ʼSCL
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = SCL_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(SCL_GPIOx, &GPIO_InitStruct);
HAL_GPIO_WritePin(SCL_GPIOx, SCL_PIN, GPIO_PIN_SET);
IIC_SCL(1);
IIC_SDA(1);
}
/**
* @brief IICʼź
* @param mode ѡIICģ
* @return void
*/
void IIC_Start(void)
{
SDA_OUT();//sda
IIC_SDA(1);
IIC_SCL(1);
delay_us(1);
IIC_SDA(0);//START:when CLK is high,DATA change form high to low
delay_us(1);
IIC_SCL(0);//ǯסI2Cߣͻ
}
/**
* @brief IICֹͣź
* @param mode ѡIICģ
* @return void
*/
void IIC_Stop(void)
{
SDA_OUT();//sda
IIC_SCL(0);
IIC_SDA(0);//STOP:when CLK is high DATA change form low to high
delay_us(1);
IIC_SCL(1);
IIC_SDA(1);//I2C߽ź
delay_us(1);
}
/**
* @brief ȴӦźŵ
* @param mode ѡIICģ
* @return 1Ӧʧ
* 0Ӧɹ
*/
uint8_t IIC_Wait_Ack(void)
{
uint8_t flag=0;
uint8_t ucErrTime=0;
SDA_IN(); //SDAΪ
IIC_SDA(1);
delay_us_nos(1);
IIC_SCL(1);
delay_us_nos(1);
while(READ_SDA()) {
ucErrTime++;
if(ucErrTime>250) {
IIC_Stop();
flag = 1;
break;
}
}
IIC_SCL(0);//ʱ0
return flag;
}
/**
* @brief ACKӦ
* @param void
* @return void
*/
void IIC_Ack(void)
{
IIC_SCL(0);
SDA_OUT();
IIC_SDA(0);
delay_us(1);
IIC_SCL(1);
delay_us(1);
IIC_SCL(0);
}
/**
* @brief ACKӦ
* @param void
* @return void
*/
void IIC_NAck(void)
{
IIC_SCL(0);
SDA_OUT();
IIC_SDA(1);
delay_us(1);
IIC_SCL(1);
delay_us(1);
IIC_SCL(0);
}
/**
* @brief IICһֽ
* @param mode ѡIICģ
* txd
* @return void
*/
void IIC_Send_Byte(uint8_t txd)
{
uint8_t t;
SDA_OUT();
IIC_SCL(0);//ʱӿʼݴ
for(t=0; t<8; t++) {
IIC_SDA((txd&0x80)>>7);
txd<<=1;
delay_us(1); //TEA5767ʱDZ
IIC_SCL(1);
delay_us(1);
IIC_SCL(0);
delay_us(1);
}
}
/**
* @brief IICȡһֽ
* @param mode ѡIICģ
* ack 1ACK
* 0nACK
* @return receive ȡֽ
*/
uint8_t IIC_Read_Byte(unsigned char ack)
{
unsigned char i,receive=0;
SDA_IN();//SDAΪ
for(i=0; i<8; i++ ) {
IIC_SCL(0);
delay_us(1);
IIC_SCL(1);
receive<<=1;
if(READ_SDA())receive++;
delay_us(1);
}
if (!ack)
IIC_NAck();//nACK
else
IIC_Ack(); //ACK
return receive;
}
/**
* @brief SCL ݣͬioӦļĴ
* @param const char x
* @retval void
*/
void IIC_SCL(const char x)
{
/* ipߵ͵ƽ */
(x!=0)?HAL_GPIO_WritePin(SCL_GPIOx,SCL_PIN,GPIO_PIN_SET):\
HAL_GPIO_WritePin(SCL_GPIOx,SCL_PIN,GPIO_PIN_RESET);
}
/**
* @brief SDA ͬioӦļĴ
* @param const char x
* @retval void
*/
void IIC_SDA(const char x)
{
/* ipߵ͵ƽ */
(x!=0)?HAL_GPIO_WritePin(SDA_GPIOx,SDA_PIN,GPIO_PIN_SET):\
HAL_GPIO_WritePin(SDA_GPIOx,SDA_PIN,GPIO_PIN_RESET);
}
/**
* @brief SDAΪģʽͬioӦļĴ
* @param void
* @retval void
*/
void SDA_IN(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = SDA_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(SDA_GPIOx, &GPIO_InitStruct);
}
/**
* @brief SDAΪģʽͬIOӦļĴ
* @param void
* @retval void
*/
void SDA_OUT(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = SDA_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(SDA_GPIOx, &GPIO_InitStruct);
HAL_GPIO_WritePin(SDA_GPIOx, SDA_PIN, GPIO_PIN_RESET);
}
/**
* @brief IOֱճhalread
* @param void
* @retval GPIO_PinState
*/
GPIO_PinState READ_SDA(void)
{
return HAL_GPIO_ReadPin(SDA_GPIOx, SDA_PIN);
}
/************************ COPYRIGHT SCUT-ROBOTLAB *****END OF FILE*************/
|
C
|
#include <stdio.h>
#include "utils.h"
/*
[3, 8, 2, 1, 5, 4, 6, 7]
*/
int
partition(int *arr, int left, int right, int pivot)
{
int i, j;
swap(arr, pivot, right);
i = left;
j = right - 1;
while (1) {
while (arr[i] < arr[right]) i++;
while (arr[j] > arr[right]) j--;
if (i <= j)
swap(arr, i, j);
else
break;
}
swap(arr, i, right);
return i;
}
void
quick_sort(int *arr, int left, int right)
{
if (left >= right) {
return; /* already sorted */
}
int pivot = left + (((right - left)%2 == 0) ? (right - left)/2: ((right - left)/2 + 1));
pivot = partition(arr, left, right, pivot);
quick_sort(arr, left, pivot - 1);
quick_sort(arr, pivot + 1, right);
}
int
main()
{
int arr[] = {3, 8, 2, 1, 5, 4 , 6, 7};
output_arr(arr, sizeof(arr)/sizeof(arr[0]));
quick_sort(arr, 0, sizeof(arr)/sizeof(arr[0]) - 1);
output_arr(arr, sizeof(arr)/sizeof(arr[0]));
}
|
C
|
#include "libft.h"
#include <stdio.h>
int main(void)
{
t_llst *pt_begin;
pt_begin = NULL;
st_put(&pt_begin, "cactus", 10);
st_put(&pt_begin, "moonlight", 8);
st_put(&pt_begin, "thunder dragon", 777);
print_st(pt_begin);
st_destroy(&pt_begin);
print_st(pt_begin);
printf("%s\n", (pt_begin == NULL) ? "PASS" : "FAIL");
return (0);
}
|
C
|
#ifndef INTER_CODE_HEAD
#define INTER_CODE_HEAD
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include"semantic.h"
typedef struct Operand Operand;
typedef struct InterCode InterCode;
typedef struct InterCodes InterCodes;
typedef struct ValueList ValueList;
typedef struct ArgsList ArgsList;
typedef enum{EQ,NEQ,G,GE,L,LE}RELOP;
struct Operand{
enum {VAR,CONSTANT,TEMP,LABEL,FUNC,ADDR,STAR,VADDR}kind;
union{
int id;//存储第几个变量、标号等
int value;
char* func_name;
}u;
struct Type* tp;//represent the type of "*x"
};
struct InterCode{
enum {LABELDEC,FUNCDEC,ASSIGN,ADD,SUB,MUL,DIV,ADDR_ASSIGN,CONTENT_ASSIGN,ASSIGN_CONTENT,GOTO,RELOP_GOTO,RETURN,DEC,ARG,CALL,PARAM,READ,WRITE}kind;
union{
struct Operand *op;
struct{Operand *right,*left;}assign;
struct{Operand *result,*op1,*op2;}binop;
struct{Operand *op1,*op2, *dst;RELOP relop;}relop_goto;
struct{Operand *op;int size;}dec;
}u;
};
struct InterCodes{
InterCode *code;
InterCodes *prev,*next;
};
struct ValueList{
int id;
char* name;
struct Type* tp;
int dimension;
int isParamStruct;
ValueList* next;
};
struct ArgsList{
Operand* op;
ArgsList* next;
};
extern InterCodes* CodeHead;
extern ValueList* ValueHead;
extern int ValueNum;
extern int TempNum;
extern int LabelNum;
extern int firstFunc;
extern RELOP getRelop(char* a);
extern int InsertValue(char* name,struct Type* tp,int dimension,int isParamStruct);
extern ValueList* findValue(char* name);
extern ValueList* findValue2(int id);
extern int checkValue(int id);
extern void InsertCode(InterCode* node);
extern void CreateLabel(Operand* op);
extern void CreateFunction(Operand* op);
extern void CreateAssign(Operand* dst,Operand* src);
extern void CreateAdd(Operand* dst,Operand* src1,Operand* src2);
extern void CreateSub(Operand* dst,Operand* src1,Operand* src2);
extern void CreateMul(Operand* dst,Operand* src1,Operand* src2);
extern void CreateDiv(Operand* dst,Operand* src1,Operand* src2);
extern void CreateAddressAssign(Operand* dst,Operand* src);
extern void CreateContentAssign(Operand* dst,Operand* src);
extern void CreateAssignContent(Operand* dst,Operand* src);
extern void CreateGoto(Operand* op);
extern void CreateRelopGoto(Operand* dst,Operand* src1,Operand* src2,RELOP relop);
extern void CreateReturn(Operand* op);
extern void CreateDec(Operand* op,int size);
extern void CreateArg(Operand* op);
extern void CreateCall(Operand* dst,Operand* f);
extern void CreateParam(Operand* op);
extern void CreateRead(Operand* op);
extern void CreateWrite(Operand* op);
extern void printCodes();
extern void printOp(FILE* fp,Operand* op);
extern void printCode(FILE* fp,InterCode* x);
extern void printRelop(FILE* fp,RELOP r);
extern void testCreateCode();
extern Operand* CreateOpVar(int id);
extern Operand* CreateOpVaddr(int id);
extern Operand* CreateOpConst(int value);
extern Operand* CreateOpTemp(int id);
extern Operand* CreateOpLabel(int id);
extern Operand* CreateOpFunc(char fname[]);
extern Operand* CreateOpAddr(int id);
extern Operand* CreateOpStar(int id,struct Type* tp);
#endif
|
C
|
#include<stdio.h>
int main()
{
int a,b;
printf("insert two number");
scanf("%d %d",&a, &b);
if(a>b)
printf("a is greatest number ");
else if(b>a)
printf("b is the greatest number");
else
printf("leave");
return 0;
}
|
C
|
#import <stdio.h>
void main() {
int a = 5, b = 4, c = 2;
printf("%s", a>b || a<c && !c!=4?"Verdadeiro":"Falso");
}
|
C
|
/* this is the second example from the permutations chapter in
* the GSL reference manual */
// The next example program steps forwards through all possible third order permutations, starting from the identity,
#include <stdio.h>
#include <gsl/gsl_permutation.h>
int main (void)
{
gsl_permutation *p = gsl_permutation_alloc(4);
gsl_permutation_init (p);
do {
gsl_permutation_fprintf (stdout, p, " %u");
printf ("; ");
} while (gsl_permutation_next(p) == GSL_SUCCESS);
printf ("\n");
gsl_permutation_free (p);
return 0;
}
/* Expected output:
Here is the output from the program,
$ ./a.out
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
*/
|
C
|
#include <stdio.h>
#include <omp.h>
static long num_steps = 100000;
double step;
#define NUM_THREADS 2
void main ()
{
int i;
double pi=0.0;
double sum=0.0;
double x=0.0;
step = 1.0/(double) num_steps;
omp_set_num_threads(NUM_THREADS); //设置2线程
#pragma omp parallel for reduction(+:sum) private(x) //每个线程保留一份私有拷贝sum,x为线程私有,最后对线程中所以sum进行+规约,并更新sum的全局值
for(i=1;i<= num_steps; i++){
x = (i-0.5)*step;
sum += 4.0/(1.0+x*x);
}
pi = sum * step;
printf("%lf\n",pi);
}
|
C
|
#include<stdio.h>
int C(int n,int r)
{
if(r==n || r==0)
return 1;
return C(n-1,r-1)+C(n-1,r);
}
int main()
{
int n,r;
printf("Enter 'n' and 'r' :");
scanf("%d %d",&n,&r);
printf("%dC%d = %d\n",n,r,C(n,r));
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "graphic.h"
#include "helper_function.h"
#define SELF(name) GRAPHIC_##name
static Style_Access SELF(malloc) (Style_Pool_Access pool_access) {
int8_t start = pool_access->max_size - pool_access->current_size;
Style_Access result = &(pool_access->pool[start]);
pool_access->current_size -= 1;
return result;
}
static Style_Access SELF(find) (Style_Pool_Access pool_access, String name) {
uint8_t count = 0;
uint8_t used = pool_access->max_size - pool_access->current_size;
Style_Access result = NULL;
for (count; count < used; count++) {
result = &(pool_access->pool[count]);
if(STRCMP(result->name, name)) {
return result;
}
}
result = NULL;
return result;
}
static void print_graph(Style_Pool_Access pool_access) {
uint8_t count = 0;
uint8_t used = pool_access->max_size - pool_access->current_size;
Style_Access result = NULL;
printf("---- graph ----\n");
for (count; count < used; count++) {
result = &(pool_access->pool[count]);
printf("%s : %s\n", result->name, result->mark);
}
printf("---- graph done ----\n");
}
static Style_Access SELF(next) (Style_Pool_Access pool_access, uint8_t * current_counter) {
uint8_t counter = *current_counter;
uint8_t used = pool_access->max_size - pool_access->current_size;
Style_Access result = NULL;
if (counter < used) {
result = &(pool_access->pool[counter]);
*current_counter += 1;
}
return result;
}
static Style_Pool_Access SELF(start) (int size) {
Style_Access style_memory = calloc(size, sizeof(Style));
Style_Pool_Access pool_access = calloc(1, sizeof(Style_Pool));
pool_access->pool = style_memory;
pool_access->max_size = size;
pool_access->current_size = size;
return pool_access;
}
static void SELF(gc) (Style_Pool_Access pool_access) {
uint8_t count = 0;
uint8_t used = pool_access->max_size - pool_access->current_size;
Style_Access result = NULL;
for (count; count < used; count++) {
result = &(pool_access->pool[count]);
SDL_DestroyTexture(result->access);
result->access = NULL;
}
}
static void SELF(stop) (Style_Pool_Access pool_access) {
free(pool_access->pool);
free(pool_access);
}
STYLE_POOL_INTERFACE Style_Pool_Interface = {
.start = SELF(start),
.stop = SELF(stop),
.malloc = SELF(malloc),
.gc = SELF(gc),
.find = SELF(find),
.next = SELF(next),
.debug = print_graph
};
#undef SELF
|
C
|
//ܣ༭ؼĩβı
//1༭
//2ַָ
//3ӺǷ
BOOL AddTextToEdit(HWND hEdit,char *szTxt,BOOL bNextLine)
{
static char NextLine[]={13,10,0};
SendMessage(hEdit,EM_SETSEL,-2,-1);
SendMessage(hEdit,EM_REPLACESEL,0,(long)szTxt);
if(bNextLine)
SendMessage(hEdit,EM_REPLACESEL,0,(long)NextLine);
return 1;
}
//ܣִCMDܵţִһԵ̣
//1ַָ
//2ָһŻԵ
//ֵԵֽ
int CmdShell(char *command,char *pOutBuf)
{
char szBuf[5*1024];
char str[256];
STARTUPINFO si;
SECURITY_ATTRIBUTES sa;
PROCESS_INFORMATION pi;
HANDLE hRead,hWrite;
DWORD dwRead,Count=0;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
//ܵcmd
if(!CreatePipe(&hRead,&hWrite,&sa,0))
MessageBox(NULL,"ܵʧ","Message",MB_OK);
//ϵͳĿ¼
GetSystemDirectory(szBuf,256);
lstrcat(szBuf,"\\cmd.exe /c ");
lstrcat(szBuf,command);
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
CreateProcess(NULL,szBuf,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi);
//һһҪڶ֮ܵǰڶ֮ǰreadfile᷵
//TMDbug˷һʱ|||
CloseHandle(hWrite);
//ѭӹܵķϢ
szBuf[0]=0;
szBuf[1]=0;
if (!pOutBuf)//pOutBufΪNULLָд
return 0;
while(1)
{
//ReadFile(hRead,rBuffer,1024,&dwRead,NULL)
ReadFile(hRead,str,255,&dwRead,NULL);
if(dwRead)
{
Count+=dwRead;
str[dwRead]=0;
str[dwRead+1]=0; //ַܵ0Լ
lstrcat(szBuf,str);
continue;
}
else
break;
}
lstrcpy(pOutBuf,szBuf);
pOutBuf[Count+1]=0;
pOutBuf[Count+2]=0;
CloseHandle(hRead);
return lstrlen(szBuf);
}
//ֱܵӺSocket
//1IPַַ
//2˿ں
//3ָ̾룬ﷵcmd̵ľ
//ֵ
SOCKET CmdShellS(char *szIPAdrees,int Port,HANDLE *hProcess)
{
char szBuf[5*1024];
STARTUPINFO si;
PROCESS_INFORMATION pi;
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2),&wsaData))
MessageBox(NULL,"ʼʧ","Message",MB_OK);
SOCKET sClient = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,NULL,0,0);
if(sClient == INVALID_SOCKET)
{
MessageBox(NULL,"ֽʧ","Message",MB_OK);
}
// sockaddr_inṹװ˵ַϢ
sockaddr_in servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(Port);
servAddr.sin_addr.S_un.S_addr =inet_addr(szIPAdrees);//ip
//ӷ
connect(sClient,(sockaddr*)&servAddr,sizeof(servAddr));
//ϵͳĿ¼
GetSystemDirectory(szBuf,256);
lstrcat(szBuf,"\\cmd.exe");
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError=(void *)sClient;
si.hStdInput=(void *)sClient;
si.hStdOutput =(void *)sClient;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
CreateProcess(NULL,szBuf,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi);
(*hProcess)=pi.hProcess;
return sClient;
}
//ܣļչļ ַ
//1Դļ
//2ļչĻָ
void GetFileTypeSz(char *pszFile,char *pszExp)
{
char *p;
p=pszFile;
while((*p)!='.')
{
p++;
if(*p==0)
return;
}
p++;
lstrcpy(pszExp,p);
GetFileTypeSz(p,pszExp);//ݹãҳһչ
}
//ΪбͼؼһĿ/Ŀ
//1бͼؼ
//2ӵĿţУ
//3ӵĿţУ
//4Ŀı
BOOL AddListVeiwItem(HWND hList,int ItemIndex,int SubItemIndex,char *pszText)
{
char str[MAX_PATH]={0};
LVITEM lvi;
ZeroMemory(&lvi,sizeof(lvi));
lvi.mask=LVIF_TEXT;
lvi.iItem=ItemIndex;
lvi.cchTextMax=MAX_PATH;
lvi.pszText=pszText;
lvi.iSubItem=SubItemIndex;
return SendMessage(hList,LVM_INSERTITEM,0,(long)&lvi);
}
//༭бͼؼһĿ/Ŀ
//ͬAddListVeiwItem
BOOL SetListVeiwItem(HWND hList,int ItemIndex,int SubItemIndex,char *pszText)
{
char str[MAX_PATH]={0};
LVITEM lvi;
ZeroMemory(&lvi,sizeof(lvi));
lvi.mask=LVIF_TEXT;
lvi.iItem=ItemIndex;
lvi.cchTextMax=MAX_PATH;
lvi.pszText=pszText;
lvi.iSubItem=SubItemIndex;
return SendMessage(hList,LVM_SETITEM,0,(long)&lvi);
}
//ͼؼһĿĿ
void AddChildItem(HWND hTree,HTREEITEM hParent,char *pszText)
{
TVINSERTSTRUCT ti;
ZeroMemory(&ti,sizeof(ti));
ti.item.mask=TVIF_TEXT|TVIF_HANDLE;
ti.hParent=hParent;
ti.hInsertAfter =TVI_LAST;
ti.item.pszText=pszText;
SendMessage(hTree,TVM_INSERTITEM,0,(long)&ti);
}
//õͼؼһĿı
int GetTreeItemText(HWND hTree,HTREEITEM hItem,char *pszText)
{
TVITEMEX tvi;
tvi.mask=TVIF_TEXT|TVIF_HANDLE;
tvi.hItem=hItem;
tvi.pszText=pszText;
tvi.cchTextMax=MAX_PATH;
int b;
b=TreeView_GetItem(hTree,&tvi);
//SendMessage(hTree,TVM_GETITEM,0,(long)&tvi);
return lstrlen(pszText);
}
//ͼؼijһĿĿ
void CleanTreeItem(HWND hTree,HTREEITEM hPItem)
{
HTREEITEM hItem;
a: hItem=(HTREEITEM)SendMessage(hTree,TVM_GETNEXTITEM,TVGN_CHILD,(long)hPItem);
if(hItem)
{
SendMessage(hTree,TVM_DELETEITEM,0,(long)hItem);
goto a;
}
}
//бͼؼĿ
void CleanListItem(HWND hList)
{
SendMessage(hList,LVM_DELETEALLITEMS,0,0);
}
//бͼؼĸĿıá/ӳ·ʽ
int GetWholePath(HWND hTree,HTREEITEM hCurSel,char *pszPath)
{
int nPathLen=0;
char szBuf[MAX_PATH]={0};
HTREEITEM hParent;
//ĿļĿı
nPathLen+=GetTreeItemText(hTree,hCurSel,szBuf);
lstrcat(szBuf,"\\");
lstrcat(szBuf,pszPath);
lstrcpy(pszPath,szBuf);
hParent=(HTREEITEM)SendMessage(hTree,TVM_GETNEXTITEM,TVGN_PARENT,(long)hCurSel);
if(hParent)
{
//ݹ
nPathLen+=GetWholePath(hTree,hParent,pszPath);
}
return nPathLen+1;
}
//"ļ"Ի
//1
//2ļִ
//3ļȫ·
BOOL OpenFileDlg(HWND hWnd,char *szFilter,char *pszFile)
{
OPENFILENAME of;
ZeroMemory(&of,sizeof(of));
ZeroMemory(pszFile,MAX_PATH);
of.lStructSize=sizeof(of);
of.hwndOwner=hWnd;
of.lpstrFilter=szFilter;
of.lpstrFile=pszFile;
of.nMaxFile=MAX_PATH;
of.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST;
return GetOpenFileName(&of);
}
//ط
//1
//2ִļλ
//3ͬʱǷ
bool InstallService(char *szDriver,char *szFile,bool bStart)
{
SC_HANDLE sh=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if(!sh)return false;
SC_HANDLE rh=CreateService(sh,szDriver,szDriver,SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
szFile,NULL,NULL,NULL,
NULL,NULL);
if(!rh)
{
if(GetLastError()==ERROR_SERVICE_EXISTS)
{
//Ѱװ
rh=OpenService(sh,szDriver,SERVICE_ALL_ACCESS);
if(!rh)
{
CloseServiceHandle(sh);
return false;
}
}
else
{
CloseServiceHandle(sh);
return false;
}
}
if(bStart) //ǷҪ
StartService(rh,0,NULL);
CloseServiceHandle(sh);
CloseServiceHandle(rh);
return true;
}
//жط
//
bool UnInstall(char *szService)
{
SC_HANDLE sh=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if(!sh)return false;
SC_HANDLE rh=OpenService(sh,szService,SERVICE_ALL_ACCESS);
if(DeleteService(rh))return true;
return false;
}
|
C
|
/* pvwrite2 -- write an HDF vdata
*
* returns -1 on error, 0 on success
*
* H. Motteler
* 12 Jan 01
*/
#include <stdio.h>
#include "hdf.h"
#include "pvdefs.h"
int pvwrite2(int32 vdata_id, /* HDF vdata ID IN */
int nrec, /* number of records in buffer IN */
char *buf /* output data buffer IN */
) {
int i, j, k;
/* write out the vdata buffer */
k = VSwrite (vdata_id, (uint8 *) buf, nrec, FULL_INTERLACE);
if (k != nrec) {
fprintf(stderr, "pvwrite2(): VSwrite bad count = %d\n", k);
return (-1);
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Compara.h"
int main(){
struct aluno a[LETRAS] = {{"A"}, {"C"}, {"C"}, {"A"}};
Pilha* x = cria_Pilha();
Pilha* y = cria_Pilha();
int i;
for(i = 0; i < LETRAS; i++)
insere_Pilha(x, a[i]);
printf("Pilha X = ");
imprime_Pilha(x);
printf("\n");
for(i = LETRAS -1 ; i >= 0; i--)
inverte_Pilha(y , a[i]);
printf("Pilha Y = ");
imprime_Pilha(y);
compara_Pilha(x, y);
printf("\n\n");
libera_Pilha(x);
libera_Pilha(y);
return 0;
}
|
C
|
/*-------------------------------------------------------------------------
*
* network_spgist.c
* SP-GiST support for network types.
*
* We split inet index entries first by address family (IPv4 or IPv6).
* If the entries below a given inner tuple are all of the same family,
* we identify their common prefix and split by the next bit of the address,
* and by whether their masklens exceed the length of the common prefix.
*
* An inner tuple that has both IPv4 and IPv6 children has a null prefix
* and exactly two nodes, the first being for IPv4 and the second for IPv6.
*
* Otherwise, the prefix is a CIDR value representing the common prefix,
* and there are exactly four nodes. Node numbers 0 and 1 are for addresses
* with the same masklen as the prefix, while node numbers 2 and 3 are for
* addresses with larger masklen. (We do not allow a tuple to contain
* entries with masklen smaller than its prefix's.) Node numbers 0 and 1
* are distinguished by the next bit of the address after the common prefix,
* and likewise for node numbers 2 and 3. If there are no more bits in
* the address family, everything goes into node 0 (which will probably
* lead to creating an allTheSame tuple).
*
* Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* src/backend/utils/adt/network_spgist.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <sys/socket.h>
#include "access/spgist.h"
#include "catalog/pg_type.h"
#include "utils/builtins.h"
#include "utils/inet.h"
#include "varatt.h"
static int inet_spg_node_number(const inet *val, int commonbits);
static int inet_spg_consistent_bitmap(const inet *prefix, int nkeys,
ScanKey scankeys, bool leaf);
/*
* The SP-GiST configuration function
*/
Datum
inet_spg_config(PG_FUNCTION_ARGS)
{
/* spgConfigIn *cfgin = (spgConfigIn *) PG_GETARG_POINTER(0); */
spgConfigOut *cfg = (spgConfigOut *) PG_GETARG_POINTER(1);
cfg->prefixType = CIDROID;
cfg->labelType = VOIDOID;
cfg->canReturnData = true;
cfg->longValuesOK = false;
PG_RETURN_VOID();
}
/*
* The SP-GiST choose function
*/
Datum
inet_spg_choose(PG_FUNCTION_ARGS)
{
spgChooseIn *in = (spgChooseIn *) PG_GETARG_POINTER(0);
spgChooseOut *out = (spgChooseOut *) PG_GETARG_POINTER(1);
inet *val = DatumGetInetPP(in->datum),
*prefix;
int commonbits;
/*
* If we're looking at a tuple that splits by address family, choose the
* appropriate subnode.
*/
if (!in->hasPrefix)
{
/* allTheSame isn't possible for such a tuple */
Assert(!in->allTheSame);
Assert(in->nNodes == 2);
out->resultType = spgMatchNode;
out->result.matchNode.nodeN = (ip_family(val) == PGSQL_AF_INET) ? 0 : 1;
out->result.matchNode.restDatum = InetPGetDatum(val);
PG_RETURN_VOID();
}
/* Else it must split by prefix */
Assert(in->nNodes == 4 || in->allTheSame);
prefix = DatumGetInetPP(in->prefixDatum);
commonbits = ip_bits(prefix);
/*
* We cannot put addresses from different families under the same inner
* node, so we have to split if the new value's family is different.
*/
if (ip_family(val) != ip_family(prefix))
{
/* Set up 2-node tuple */
out->resultType = spgSplitTuple;
out->result.splitTuple.prefixHasPrefix = false;
out->result.splitTuple.prefixNNodes = 2;
out->result.splitTuple.prefixNodeLabels = NULL;
/* Identify which node the existing data goes into */
out->result.splitTuple.childNodeN =
(ip_family(prefix) == PGSQL_AF_INET) ? 0 : 1;
out->result.splitTuple.postfixHasPrefix = true;
out->result.splitTuple.postfixPrefixDatum = InetPGetDatum(prefix);
PG_RETURN_VOID();
}
/*
* If the new value does not match the existing prefix, we have to split.
*/
if (ip_bits(val) < commonbits ||
bitncmp(ip_addr(prefix), ip_addr(val), commonbits) != 0)
{
/* Determine new prefix length for the split tuple */
commonbits = bitncommon(ip_addr(prefix), ip_addr(val),
Min(ip_bits(val), commonbits));
/* Set up 4-node tuple */
out->resultType = spgSplitTuple;
out->result.splitTuple.prefixHasPrefix = true;
out->result.splitTuple.prefixPrefixDatum =
InetPGetDatum(cidr_set_masklen_internal(val, commonbits));
out->result.splitTuple.prefixNNodes = 4;
out->result.splitTuple.prefixNodeLabels = NULL;
/* Identify which node the existing data goes into */
out->result.splitTuple.childNodeN =
inet_spg_node_number(prefix, commonbits);
out->result.splitTuple.postfixHasPrefix = true;
out->result.splitTuple.postfixPrefixDatum = InetPGetDatum(prefix);
PG_RETURN_VOID();
}
/*
* All OK, choose the node to descend into. (If this tuple is marked
* allTheSame, the core code will ignore our choice of nodeN; but we need
* not account for that case explicitly here.)
*/
out->resultType = spgMatchNode;
out->result.matchNode.nodeN = inet_spg_node_number(val, commonbits);
out->result.matchNode.restDatum = InetPGetDatum(val);
PG_RETURN_VOID();
}
/*
* The GiST PickSplit method
*/
Datum
inet_spg_picksplit(PG_FUNCTION_ARGS)
{
spgPickSplitIn *in = (spgPickSplitIn *) PG_GETARG_POINTER(0);
spgPickSplitOut *out = (spgPickSplitOut *) PG_GETARG_POINTER(1);
inet *prefix,
*tmp;
int i,
commonbits;
bool differentFamilies = false;
/* Initialize the prefix with the first item */
prefix = DatumGetInetPP(in->datums[0]);
commonbits = ip_bits(prefix);
/* Examine remaining items to discover minimum common prefix length */
for (i = 1; i < in->nTuples; i++)
{
tmp = DatumGetInetPP(in->datums[i]);
if (ip_family(tmp) != ip_family(prefix))
{
differentFamilies = true;
break;
}
if (ip_bits(tmp) < commonbits)
commonbits = ip_bits(tmp);
commonbits = bitncommon(ip_addr(prefix), ip_addr(tmp), commonbits);
if (commonbits == 0)
break;
}
/* Don't need labels; allocate output arrays */
out->nodeLabels = NULL;
out->mapTuplesToNodes = (int *) palloc(sizeof(int) * in->nTuples);
out->leafTupleDatums = (Datum *) palloc(sizeof(Datum) * in->nTuples);
if (differentFamilies)
{
/* Set up 2-node tuple */
out->hasPrefix = false;
out->nNodes = 2;
for (i = 0; i < in->nTuples; i++)
{
tmp = DatumGetInetPP(in->datums[i]);
out->mapTuplesToNodes[i] =
(ip_family(tmp) == PGSQL_AF_INET) ? 0 : 1;
out->leafTupleDatums[i] = InetPGetDatum(tmp);
}
}
else
{
/* Set up 4-node tuple */
out->hasPrefix = true;
out->prefixDatum =
InetPGetDatum(cidr_set_masklen_internal(prefix, commonbits));
out->nNodes = 4;
for (i = 0; i < in->nTuples; i++)
{
tmp = DatumGetInetPP(in->datums[i]);
out->mapTuplesToNodes[i] = inet_spg_node_number(tmp, commonbits);
out->leafTupleDatums[i] = InetPGetDatum(tmp);
}
}
PG_RETURN_VOID();
}
/*
* The SP-GiST query consistency check for inner tuples
*/
Datum
inet_spg_inner_consistent(PG_FUNCTION_ARGS)
{
spgInnerConsistentIn *in = (spgInnerConsistentIn *) PG_GETARG_POINTER(0);
spgInnerConsistentOut *out = (spgInnerConsistentOut *) PG_GETARG_POINTER(1);
int i;
int which;
if (!in->hasPrefix)
{
Assert(!in->allTheSame);
Assert(in->nNodes == 2);
/* Identify which child nodes need to be visited */
which = 1 | (1 << 1);
for (i = 0; i < in->nkeys; i++)
{
StrategyNumber strategy = in->scankeys[i].sk_strategy;
inet *argument = DatumGetInetPP(in->scankeys[i].sk_argument);
switch (strategy)
{
case RTLessStrategyNumber:
case RTLessEqualStrategyNumber:
if (ip_family(argument) == PGSQL_AF_INET)
which &= 1;
break;
case RTGreaterEqualStrategyNumber:
case RTGreaterStrategyNumber:
if (ip_family(argument) == PGSQL_AF_INET6)
which &= (1 << 1);
break;
case RTNotEqualStrategyNumber:
break;
default:
/* all other ops can only match addrs of same family */
if (ip_family(argument) == PGSQL_AF_INET)
which &= 1;
else
which &= (1 << 1);
break;
}
}
}
else if (!in->allTheSame)
{
Assert(in->nNodes == 4);
/* Identify which child nodes need to be visited */
which = inet_spg_consistent_bitmap(DatumGetInetPP(in->prefixDatum),
in->nkeys, in->scankeys, false);
}
else
{
/* Must visit all nodes; we assume there are less than 32 of 'em */
which = ~0;
}
out->nNodes = 0;
if (which)
{
out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
for (i = 0; i < in->nNodes; i++)
{
if (which & (1 << i))
{
out->nodeNumbers[out->nNodes] = i;
out->nNodes++;
}
}
}
PG_RETURN_VOID();
}
/*
* The SP-GiST query consistency check for leaf tuples
*/
Datum
inet_spg_leaf_consistent(PG_FUNCTION_ARGS)
{
spgLeafConsistentIn *in = (spgLeafConsistentIn *) PG_GETARG_POINTER(0);
spgLeafConsistentOut *out = (spgLeafConsistentOut *) PG_GETARG_POINTER(1);
inet *leaf = DatumGetInetPP(in->leafDatum);
/* All tests are exact. */
out->recheck = false;
/* Leaf is what it is... */
out->leafValue = InetPGetDatum(leaf);
/* Use common code to apply the tests. */
PG_RETURN_BOOL(inet_spg_consistent_bitmap(leaf, in->nkeys, in->scankeys,
true));
}
/*
* Calculate node number (within a 4-node, single-family inner index tuple)
*
* The value must have the same family as the node's prefix, and
* commonbits is the mask length of the prefix. We use even or odd
* nodes according to the next address bit after the commonbits,
* and low or high nodes according to whether the value's mask length
* is larger than commonbits.
*/
static int
inet_spg_node_number(const inet *val, int commonbits)
{
int nodeN = 0;
if (commonbits < ip_maxbits(val) &&
ip_addr(val)[commonbits / 8] & (1 << (7 - commonbits % 8)))
nodeN |= 1;
if (commonbits < ip_bits(val))
nodeN |= 2;
return nodeN;
}
/*
* Calculate bitmap of node numbers that are consistent with the query
*
* This can be used either at a 4-way inner tuple, or at a leaf tuple.
* In the latter case, we should return a boolean result (0 or 1)
* not a bitmap.
*
* This definition is pretty odd, but the inner and leaf consistency checks
* are mostly common and it seems best to keep them in one function.
*/
static int
inet_spg_consistent_bitmap(const inet *prefix, int nkeys, ScanKey scankeys,
bool leaf)
{
int bitmap;
int commonbits,
i;
/* Initialize result to allow visiting all children */
if (leaf)
bitmap = 1;
else
bitmap = 1 | (1 << 1) | (1 << 2) | (1 << 3);
commonbits = ip_bits(prefix);
for (i = 0; i < nkeys; i++)
{
inet *argument = DatumGetInetPP(scankeys[i].sk_argument);
StrategyNumber strategy = scankeys[i].sk_strategy;
int order;
/*
* Check 0: different families
*
* Matching families do not help any of the strategies.
*/
if (ip_family(argument) != ip_family(prefix))
{
switch (strategy)
{
case RTLessStrategyNumber:
case RTLessEqualStrategyNumber:
if (ip_family(argument) < ip_family(prefix))
bitmap = 0;
break;
case RTGreaterEqualStrategyNumber:
case RTGreaterStrategyNumber:
if (ip_family(argument) > ip_family(prefix))
bitmap = 0;
break;
case RTNotEqualStrategyNumber:
break;
default:
/* For all other cases, we can be sure there is no match */
bitmap = 0;
break;
}
if (!bitmap)
break;
/* Other checks make no sense with different families. */
continue;
}
/*
* Check 1: network bit count
*
* Network bit count (ip_bits) helps to check leaves for sub network
* and sup network operators. At non-leaf nodes, we know every child
* value has greater ip_bits, so we can avoid descending in some cases
* too.
*
* This check is less expensive than checking the address bits, so we
* are doing this before, but it has to be done after for the basic
* comparison strategies, because ip_bits only affect their results
* when the common network bits are the same.
*/
switch (strategy)
{
case RTSubStrategyNumber:
if (commonbits <= ip_bits(argument))
bitmap &= (1 << 2) | (1 << 3);
break;
case RTSubEqualStrategyNumber:
if (commonbits < ip_bits(argument))
bitmap &= (1 << 2) | (1 << 3);
break;
case RTSuperStrategyNumber:
if (commonbits == ip_bits(argument) - 1)
bitmap &= 1 | (1 << 1);
else if (commonbits >= ip_bits(argument))
bitmap = 0;
break;
case RTSuperEqualStrategyNumber:
if (commonbits == ip_bits(argument))
bitmap &= 1 | (1 << 1);
else if (commonbits > ip_bits(argument))
bitmap = 0;
break;
case RTEqualStrategyNumber:
if (commonbits < ip_bits(argument))
bitmap &= (1 << 2) | (1 << 3);
else if (commonbits == ip_bits(argument))
bitmap &= 1 | (1 << 1);
else
bitmap = 0;
break;
}
if (!bitmap)
break;
/*
* Check 2: common network bits
*
* Compare available common prefix bits to the query, but not beyond
* either the query's netmask or the minimum netmask among the
* represented values. If these bits don't match the query, we can
* eliminate some cases.
*/
order = bitncmp(ip_addr(prefix), ip_addr(argument),
Min(commonbits, ip_bits(argument)));
if (order != 0)
{
switch (strategy)
{
case RTLessStrategyNumber:
case RTLessEqualStrategyNumber:
if (order > 0)
bitmap = 0;
break;
case RTGreaterEqualStrategyNumber:
case RTGreaterStrategyNumber:
if (order < 0)
bitmap = 0;
break;
case RTNotEqualStrategyNumber:
break;
default:
/* For all other cases, we can be sure there is no match */
bitmap = 0;
break;
}
if (!bitmap)
break;
/*
* Remaining checks make no sense when common bits don't match.
*/
continue;
}
/*
* Check 3: next network bit
*
* We can filter out branch 2 or 3 using the next network bit of the
* argument, if it is available.
*
* This check matters for the performance of the search. The results
* would be correct without it.
*/
if (bitmap & ((1 << 2) | (1 << 3)) &&
commonbits < ip_bits(argument))
{
int nextbit;
nextbit = ip_addr(argument)[commonbits / 8] &
(1 << (7 - commonbits % 8));
switch (strategy)
{
case RTLessStrategyNumber:
case RTLessEqualStrategyNumber:
if (!nextbit)
bitmap &= 1 | (1 << 1) | (1 << 2);
break;
case RTGreaterEqualStrategyNumber:
case RTGreaterStrategyNumber:
if (nextbit)
bitmap &= 1 | (1 << 1) | (1 << 3);
break;
case RTNotEqualStrategyNumber:
break;
default:
if (!nextbit)
bitmap &= 1 | (1 << 1) | (1 << 2);
else
bitmap &= 1 | (1 << 1) | (1 << 3);
break;
}
if (!bitmap)
break;
}
/*
* Remaining checks are only for the basic comparison strategies. This
* test relies on the strategy number ordering defined in stratnum.h.
*/
if (strategy < RTEqualStrategyNumber ||
strategy > RTGreaterEqualStrategyNumber)
continue;
/*
* Check 4: network bit count
*
* At this point, we know that the common network bits of the prefix
* and the argument are the same, so we can go forward and check the
* ip_bits.
*/
switch (strategy)
{
case RTLessStrategyNumber:
case RTLessEqualStrategyNumber:
if (commonbits == ip_bits(argument))
bitmap &= 1 | (1 << 1);
else if (commonbits > ip_bits(argument))
bitmap = 0;
break;
case RTGreaterEqualStrategyNumber:
case RTGreaterStrategyNumber:
if (commonbits < ip_bits(argument))
bitmap &= (1 << 2) | (1 << 3);
break;
}
if (!bitmap)
break;
/* Remaining checks don't make sense with different ip_bits. */
if (commonbits != ip_bits(argument))
continue;
/*
* Check 5: next host bit
*
* We can filter out branch 0 or 1 using the next host bit of the
* argument, if it is available.
*
* This check matters for the performance of the search. The results
* would be correct without it. There is no point in running it for
* leafs as we have to check the whole address on the next step.
*/
if (!leaf && bitmap & (1 | (1 << 1)) &&
commonbits < ip_maxbits(argument))
{
int nextbit;
nextbit = ip_addr(argument)[commonbits / 8] &
(1 << (7 - commonbits % 8));
switch (strategy)
{
case RTLessStrategyNumber:
case RTLessEqualStrategyNumber:
if (!nextbit)
bitmap &= 1 | (1 << 2) | (1 << 3);
break;
case RTGreaterEqualStrategyNumber:
case RTGreaterStrategyNumber:
if (nextbit)
bitmap &= (1 << 1) | (1 << 2) | (1 << 3);
break;
case RTNotEqualStrategyNumber:
break;
default:
if (!nextbit)
bitmap &= 1 | (1 << 2) | (1 << 3);
else
bitmap &= (1 << 1) | (1 << 2) | (1 << 3);
break;
}
if (!bitmap)
break;
}
/*
* Check 6: whole address
*
* This is the last check for correctness of the basic comparison
* strategies. It's only appropriate at leaf entries.
*/
if (leaf)
{
/* Redo ordering comparison using all address bits */
order = bitncmp(ip_addr(prefix), ip_addr(argument),
ip_maxbits(prefix));
switch (strategy)
{
case RTLessStrategyNumber:
if (order >= 0)
bitmap = 0;
break;
case RTLessEqualStrategyNumber:
if (order > 0)
bitmap = 0;
break;
case RTEqualStrategyNumber:
if (order != 0)
bitmap = 0;
break;
case RTGreaterEqualStrategyNumber:
if (order < 0)
bitmap = 0;
break;
case RTGreaterStrategyNumber:
if (order <= 0)
bitmap = 0;
break;
case RTNotEqualStrategyNumber:
if (order == 0)
bitmap = 0;
break;
}
if (!bitmap)
break;
}
}
return bitmap;
}
|
C
|
#ifndef lint
static const char RCSid[] = "$Id: ra_skel.c,v 2.13 2006/03/10 19:40:13 schorsch Exp $";
#endif
/*
* Skeletal 24-bit image conversion program. Replace "skel"
* in this file with a more appropriate image type identifier.
*
* The Rmakefile entry should look something like this:
* ra_skel: ra_skel.o
* cc $(CFLAGS) -o ra_skel ra_skel.o -lrtrad -lm
* ra_skel.o: ../common/color.h ../common/resolu.h
*
* If you like to do things the hard way, you can link directly
* to the object files "color.o colrops.o resolu.o header.o" in
* the common subdirectory instead of using the -lrtrad library.
*/
#include <stdio.h>
#include <math.h>
#include <time.h>
#include "platform.h"
#include "color.h"
#include "resolu.h"
double gamcor = 2.2; /* gamma correction */
int bradj = 0; /* brightness adjustment */
char *progname;
int xmax, ymax;
main(argc, argv)
int argc;
char *argv[];
{
int reverse = 0;
int i;
progname = argv[0];
for (i = 1; i < argc; i++)
if (argv[i][0] == '-')
switch (argv[i][1]) {
case 'g': /* gamma correction */
gamcor = atof(argv[++i]);
break;
case 'e': /* exposure adjustment */
if (argv[i+1][0] != '+' && argv[i+1][0] != '-')
goto userr;
bradj = atoi(argv[++i]);
break;
case 'r': /* reverse conversion */
reverse = 1;
break;
default:
goto userr;
}
else
break;
if (i < argc-2)
goto userr;
if (i <= argc-1 && freopen(argv[i], "r", stdin) == NULL) {
fprintf(stderr, "%s: can't open input \"%s\"\n",
progname, argv[i]);
exit(1);
}
if (i == argc-2 && freopen(argv[i+1], "w", stdout) == NULL) {
fprintf(stderr, "%s: can't open output \"%s\"\n",
progname, argv[i+1]);
exit(1);
}
SET_FILE_BINARY(stdin);
SET_FILE_BINARY(stdout);
setcolrgam(gamcor); /* set up gamma correction */
if (reverse) {
/* get their image resolution */
read_skel_head(&xmax, &ymax);
/* put our header */
newheader("RADIANCE", stdout);
printargs(i, argv, stdout);
fputformat(COLRFMT, stdout);
putchar('\n');
fprtresolu(xmax, ymax, stdout);
/* convert file */
skel2ra();
} else {
/* get our header */
if (checkheader(stdin, COLRFMT, NULL) < 0 ||
fgetresolu(&xmax, &ymax, stdin) < 0)
quiterr("bad picture format");
/* write their header */
write_skel_head(xmax, ymax);
/* convert file */
ra2skel();
}
exit(0);
userr:
fprintf(stderr,
"Usage: %s [-r][-g gamma][-e +/-stops] [input [output]]\n",
progname);
exit(1);
}
quiterr(err) /* print message and exit */
char *err;
{
if (err != NULL) {
fprintf(stderr, "%s: %s\n", progname, err);
exit(1);
}
exit(0);
}
skel2ra() /* convert 24-bit scanlines to Radiance picture */
{
COLR *scanout;
register int x;
int y;
/* allocate scanline */
scanout = (COLR *)malloc(xmax*sizeof(COLR));
if (scanout == NULL)
quiterr("out of memory in skel2ra");
/* convert image */
for (y = ymax-1; y >= 0; y--) {
for (x = 0; x < xmax; x++) {
scanout[x][RED] = getc(stdin);
scanout[x][GRN] = getc(stdin);
scanout[x][BLU] = getc(stdin);
}
if (feof(stdin) | ferror(stdin))
quiterr("error reading skel image");
/* undo gamma */
gambs_colrs(scanout, xmax);
if (bradj) /* adjust exposure */
shiftcolrs(scanout, xmax, bradj);
if (fwritecolrs(scanout, xmax, stdout) < 0)
quiterr("error writing Radiance picture");
}
/* free scanline */
free((void *)scanout);
}
ra2skel() /* convert Radiance scanlines to 24-bit */
{
COLR *scanin;
register int x;
int y;
/* allocate scanline */
scanin = (COLR *)malloc(xmax*sizeof(COLR));
if (scanin == NULL)
quiterr("out of memory in ra2skel");
/* convert image */
for (y = ymax-1; y >= 0; y--) {
if (freadcolrs(scanin, xmax, stdin) < 0)
quiterr("error reading Radiance picture");
if (bradj) /* adjust exposure */
shiftcolrs(scanin, xmax, bradj);
colrs_gambs(scanin, xmax); /* gamma correction */
for (x = 0; x < xmax; x++) {
putc(scanin[x][RED], stdout);
putc(scanin[x][GRN], stdout);
putc(scanin[x][BLU], stdout);
}
if (ferror(stdout))
quiterr("error writing skel file");
}
/* free scanline */
free((void *)scanin);
}
|
C
|
#include <stdio.h>
extern int mymin(int a , int b , int c ) ;
int main() {
int a;
int b;
int c;
alarm(2);
a = 1;
b = 0;
c = -1;
mymin(a, b, c);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
* Typedef: node / node_t
* ----------------------
* used as one piece of the linked list
*
* int data
* - data stored in the node
* struct node *next
* - pointer to next node in the chain
* - set to NULL if this is the last node in the list
* struct node *prev
* - pointer to previous node in the chain
* - set to NULL if this is the first node in the list
*/
typedef struct node
{
int data;
struct node *next;
struct node *prev;
} node_t;
/*
* Function: get_last
* ------------------
* returns pointer to the last node in the list
*
* input:
* - node_t *node - pointer to any node in the list
*
* return value:
* - pointer to last node in the list
* - NULL if input is NULL
*/
node_t *get_last(node_t *node)
{
if (node == NULL)
return NULL;
while (node->next != NULL)
{
node = node->next;
}
return node;
}
/*
* Function: get_first
* -------------------
* returns pointer to the first node in the list
*
* input:
* - node_t *node - pointer to any node in the list
*
* return value:
* - pointer to first node in the list
* - NULL if input is NULL
*/
node_t *get_first(node_t *node)
{
if (node == NULL)
return NULL;
while (node->prev != NULL)
{
node = node->prev;
}
return node;
}
/*
* Function: insert
* ----------------
* add a new node to the list at specified index
*
* input:
* - node_t **head - pointer to the head pointer
* - int index - index of the list, where the new node will sit, -1 means last
* - int data - data to be stored in the new node
*
* return value:
* - error codes:
* - 0 - success
* - 1 - index error
* - 2 - allocation error
*/
int insert(node_t **head, int index, int data)
{
node_t *new_node;
node_t *prev_node;
node_t *next_node;
// invalid index
if (index < -1)
return 1;
// allocate a new node and set its data
// return error if allocation fails
new_node = (node_t *)malloc(sizeof(node_t));
if (new_node == NULL)
return 2;
new_node->data = data;
// set prev_node and next_node to the right values
if (index >= 0)
{
prev_node = NULL;
next_node = *head;
for (int i = 0; i < index; i++)
{
// index out of range
if (next_node == NULL)
{
free(new_node);
return 1;
}
prev_node = next_node;
next_node = next_node->next;
}
}
else // index == -1
{
next_node = NULL;
prev_node = get_last(*head);
}
// set link new node to its previous and next nodes
new_node->prev = prev_node;
new_node->next = next_node;
// link the adjacent nodes to the new one, if they exist
if (prev_node != NULL)
{
prev_node->next = new_node;
}
else
{
*head = new_node;
}
if (next_node != NULL)
{
next_node->prev = new_node;
}
return 0;
}
/*
* Function: erase
* ---------------
* erases node of the list at specified index
*
* input:
* - node **head - pointer to the head pointer
* - int index - index of the list, from where should be the node deleted,
* => -1 means last
*
* return value:
* - error codes:
* - 0 - success
* - 1 - index error
*/
int erase(node_t **head, int index)
{
node_t *node;
// invalid index
if (index < -1)
return 1;
// set node to point on the specified index
if (index >= 0)
{
node = *head;
for (int i = 0; i < index; i++)
{
// index out of range
if (node == NULL)
return 1;
node = node->next;
}
}
else // index == -1
{
node = get_last(*head);
}
// link adjacent nodes to point to each other instead of this node
if (node->prev != NULL)
{
node->prev->next = node->next;
}
else
{
*head = node->next;
}
if (node->next != NULL)
{
node->next->prev = node->prev;
}
// free the unlinked node
free(node);
return 0;
}
/*
* Function: append
* ----------------
* add a new node at the end of the list
*
* input:
* - node_t **node - pointer to the head pointer
* - int data - data to be stored in the new node
*
* return value:
* - error codes:
* - 0 - success
* - 2 - allocation error
*/
int append(node_t **head, int data)
{
return insert(head, -1, data);
}
/*
* Function: pop
* -------------
* removes last node from the list and returns its data
* does not check if head is NULL
*
* input:
* - node_t **head - pointer to the head pointer
*
* return value:
* - data of the deleted node
*/
int pop(node_t **head)
{
int rv;
rv = get_last(*head)->data;
erase(head, -1);
return rv;
}
/*
* Function: print_list
* --------------------
* prints all elements of the list as comma separated values enclosed
* in brackets
* each line is of format "index: value"
* prints "empty" if there are no nodes in the list
*
* input:
* - node_t *head - pointer to head of the list
*/
void print_list(node_t *head)
{
node_t *node;
node = head;
if (node == NULL)
{
printf("empty\n");
return;
}
printf("[ ");
while (node != NULL)
{
printf("%d%s", node->data, (node->next != NULL) ? ", " : " ]\n");
node = node->next;
}
}
int main(int argc, char const *argv[])
{
// showcase code for the functions above
// this code does not check for errors that may occur during runtime
node_t *head;
head = NULL;
append(&head, 1);
append(&head, 2);
append(&head, 3);
insert(&head, 2, 4);
print_list(head);
// Output: [ 1, 2, 4, 3 ]
erase(&head, 2);
print_list(head);
// Output: [ 1, 2, 3 ]
pop(&head);
pop(&head);
pop(&head);
print_list(head);
// Output: empty
return 0;
}
|
C
|
/*
2
0̻ 100 ߿ ¦ ϴ α ϵ,
do~while غ. 2550 Ǿ Ѵ.
*/
#include <stdio.h>
int main()
{
int num = 0, total = 0;
do {
total += num;
num += 2; // num 0 ϰ 2 ָ鼭 ¦ ǥ
} while (num <= 100);
printf("0 100 ¦ : %d\n", total);
return 0;
}
|
C
|
/* djikstra-graph.c */
// Michael Mei
// Linux Mint 18(Sarah) with gcc
// U. of Illinois, Chicago
// CS251, Fall 2016
// HW #14
//
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <limits.h>
#include "avl.h"
#include "stack.h"
#include "queue.h"
#include "set.h"
#include "graph.h"
#include "mymem.h"
#include "dijkstra-graph.h"
//
// Performs Dijkstra's shortest path algorithm to find the shortest path
// from src to dest. Returns a dynamically-allocated array of vertices
// denoting this path; the array will start with src, contain 0 or more
// vertices that lead to dest, followed by dest, and ending with -1.
// If there is no pat from src to dest, the array will contain only -1.
//
// NOTE: returns NULL if src or dest are not valid vertex ids.
//
// NOTE: it is the responsibility of the CALLER to free the
// returned array when they are done.
//
int PopMin(Queue *unvisitedQ, int distance[])
{
int N = unvisitedQ->NumElements;
Stack *S = CreateStack(N);
assert(!isEmptyQueue(unvisitedQ));
//
// search for smallest vertex distance in the queue,
// saving other elements in a stack so we can put back
// later:
//
int minV = Dequeue(unvisitedQ); // assume first vertex is the min:
while (!isEmptyQueue(unvisitedQ)) // look for smaller vertex:
{
int v = Dequeue(unvisitedQ);
if (distance[v] < distance[minV])
{
Push(S, minV); // save so we can put back in queue:
minV = v; // our new min:
}
else // not smaller, so save to enqueue later:
{
Push(S, v);
}
}
//
// empty the stack back into the queue:
//
while (!isEmptyStack(S))
{
Enqueue(unvisitedQ, Pop(S));
}
// NOTE: at this point queue is now one smaller, with
// min element removed. Let's confirm:
assert(unvisitedQ->NumElements == (N - 1));
//
// done:
//
DeleteStack(S);
return minV;
}
Vertex *Dijkstra(Graph *G, Vertex src, Vertex dest)
{
int INF = INT_MAX;
if (src < 0 || src >= G->NumVertices) // invalid vertex #:
return NULL;
if (dest < 0 || dest >= G->NumVertices) // invalid vertex #:
return NULL;
//
// allocate distances array:
//
int N = G->NumVertices;
int *distance = (int *)mymalloc(N * sizeof(int));
if (distance == NULL)
{
printf("\n**Error in Dijkstra: malloc failed to allocate\n\n");
exit(-1);
}
Vertex *predecessor = (Vertex *)mymalloc(N * sizeof(Vertex));
if (predecessor == NULL)
{
printf("\n**Error in Dijkstra: malloc failed to allocate\n\n");
exit(-1);
}
//
// for each vertex, add to Queue to be visited,
// initialize distance to Infinity, and set predecessor
// to -1:
//
Queue *unvisitedQ = CreateQueue(N);
int currentV;
for (currentV = 0; currentV < N; ++currentV)
{
Enqueue(unvisitedQ, currentV);
distance[currentV] = INF;
predecessor[currentV] = -1;
}
//
// starting vertex has a distance of 0 from itself:
//
distance[src] = 0;
//
// Now run Dijkstra's algorithm:
//
while (!isEmptyQueue(unvisitedQ))
{
//
// find the vertex with the smallest distance from
// the start, that's the vertex to explore next:
//
currentV = PopMin(unvisitedQ, distance);
// is there a path to the current vertex? if not,
// there's no point in looking at neighbors...
if (distance[currentV] == INF)
break;
//
// now see if we have found any shorter paths for minV's
// neighboring vertices:
//
Vertex *neighbors = Neighbors(G, currentV);
int i = 0;
while (neighbors[i] != -1) // for each neighbor:
{
int adjV = neighbors[i];
int edgeWeight = getEdgeWeight(G, currentV, adjV);
int altDistance = distance[currentV] + edgeWeight;
if (altDistance < distance[adjV])
{
distance[adjV] = altDistance;
predecessor[adjV] = currentV;
}
++i;
}
myfree(neighbors);
}
//
// Okay, algorithm has run to completion, and the path (if
// any) is stored backwards in predecessor array. So let's
// use a stack to reverse it:
//
Stack *S = CreateStack(N);
int v = dest;
while (predecessor[v] != -1)
{
Push(S, v);
v = predecessor[v];
}
// loop stops when it gets to src, so push src to finish:
Push(S, src);
//
// at this point we have the path on the stack, or if there's
// no path, just src is on the stack. Allocated an array and
// fill with path, or if no path, just -1:
//
Vertex *path;
if (S->NumElements == 1) // just src on stack, no path:
{
N = 1; // just the -1:
path = (Vertex *)mymalloc(N * sizeof(Vertex));
if (path == NULL)
{
printf("\n**Error in Dijkstra: malloc failed to allocate\n\n");
exit(-1);
}
path[0] = -1; // no path from src to dest:
}
else
{
N = S->NumElements + 1; // path + -1 at the end
path = (Vertex *)mymalloc(N * sizeof(Vertex));
if (path == NULL)
{
printf("\n**Error in Dijkstra: malloc failed to allocate\n\n");
exit(-1);
}
// now empty the stack into the path array:
int i = 0;
while (!isEmptyStack(S))
{
path[i] = Pop(S);
++i;
}
path[i] = -1; // need -1 terminator at the end:
}
//
// done!
//
DeleteStack(S);
DeleteQueue(unvisitedQ);
myfree(distance);
myfree(predecessor);
return path;
}
|
C
|
//Program that converts a string like "124" to an integer 124.
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int i;
printf("Enter the string: \n");
gets(str);
i=atoi(str); //"atoi" is a function to convert a string into an integer.
printf("integer=%d",i);
getch();
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
char str[10];
printf("Enter name of the card\n");
scanf("%s", &str);
if (strcmp(str, "J") == 0 || strcmp(str, "Q") == 0 || strcmp(str, "K") == 0 || strcmp(str, "10") == 0)
printf("10\n");
else if (strcmp(str, "A") == 0)
printf("11\n");
else if (strlen(str) == 1 && str[0] >= '2' && str[0] <= '9')
printf("%s", &str);
else
printf("No such card");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <ctype.h>
int fOption = 0;
int cmpCount = 0;
// Uses XOR 42 and makes uppercase if F option
char decode(char x){
x = (x ^ 42);
if(fOption)
x = toupper((unsigned char)x);
return x;
}
// Compares different inputs based on their decoded values
int frobcmp(char const * a, char const * b){
for(; *a != ' ' || *b != ' '; a++, b++){
if(decode(*a) > decode(*b) || (*b == ' ' && *a != ' '))
return 1;
if(decode(*a) < decode(*b) || (*a == ' ' && *b != ' '))
return -1;
}
return 0;
}
// Checks input and output errors (if error message occurs)
void checkError(ssize_t status){
if(status < 0){
char* errorMsg = "Error in input\n";
write(2, errorMsg, strlen(errorMsg));
exit(1);
}
}
// The compare function for qsort, uses frobcmp
int compare(const void * a, const void * b){
cmpCount++;
return frobcmp(*(const char**)a, *(const char**)b);
}
int main(int argc, char* argv[]){
if(argc > 2){
char* errorMsg = "Too many arguments\n";
write(2, errorMsg, strlen(errorMsg));
exit(1);
}
if(argc == 2){
if(!strncmp(argv[1], "-f", 2))
fOption = 1;
}
struct stat sta;
ssize_t status = fstat(0, &sta);
checkError(status);
char* input = NULL;
char** wordArray = NULL;
int numWords = 0;
int ongoing = 0;
size_t filesizewn = sta.st_size + 1;
// If file is regular
if(S_ISREG(sta.st_mode)){
// Allocates and reads
input = (char*)malloc(sizeof(char) * filesizewn);
size_t filesizeb = sta.st_size;
status = read(0, input, sizeof(char) * filesizeb);
checkError(status);
int k = 0;
int count = 0;
// Counts number of words in input
for(; k < filesizeb; k++){
if(k == filesizeb - 1 && input[k] != ' '){
input = (char*)realloc(input, (filesizewn)*sizeof(char));
input[k+1] = ' ';
count++;
break;
}
if(input[k] == ' ')
count++;
}
// Distributes words into array
wordArray = (char**)malloc(sizeof(char*) * count);
int l = 0;
for(; l < filesizeb; l++){
if(!ongoing){
wordArray[numWords] = &input[l];
numWords++;
ongoing = 1;
}
if(input[l] == ' ')
ongoing = 0;
}
ongoing = 0;
lseek(0, filesizeb, SEEK_SET);
}
char * stanInput = NULL;
size_t si_len = 0;
char current[1];
// Standard Input section, very similar to regular file, but
// reads byte-by-byte
while((read(0, current, 1)) > 0){
if(stanInput == NULL)
stanInput = (char*)malloc(sizeof(char));
else
stanInput = (char*)realloc(stanInput, (si_len + 1)*sizeof(char));
stanInput[si_len] = current[0];
si_len++;
}
int h = 0;
int count2 = 0;
for(; h < si_len; h++){
if(h == si_len - 1 && stanInput[h] != ' '){
stanInput = (char*)realloc(stanInput, (si_len + 1)*sizeof(char));
stanInput[h+1] = ' ';
count2++;
break;
}
if(stanInput[h] == ' ')
count2++;
}
if(wordArray == NULL)
wordArray = (char**)malloc(sizeof(char*) * count2);
else
wordArray = (char**)realloc(wordArray, sizeof(char*) * (count2 + numWords));
int q = 0;
for(; q < si_len; q++){
if(!ongoing){
wordArray[numWords] = &stanInput[q];
numWords++;
ongoing = 1;
}
if(stanInput[q] == ' ')
ongoing = 0;
}
// Sorts resulting array of words
qsort(wordArray, numWords, sizeof(char*), compare);
// free memory
int i;
int j;
for(i = 0; i < numWords; i++){
for(j = 0; wordArray[i][j] != ' '; j++){
putchar(wordArray[i][j]);
}
putchar(' ');
}
if(S_ISREG(sta.st_mode))
free(input);
free(stanInput);
return 0;
}
|
C
|
//header che rappresenta strutture e operazioni su una coda generica
typedef struct n{
void *info; //contenuto informativo del nodo
struct n *next; //puntatore al successivo
}GenericNode; //nodo generico
typedef struct q{
GenericNode *head; //testa della coda
GenericNode *tail; //fine della coda
}Queue; //per avere inserimento in coda e rimozione in testa in O(1) mi mantengo i puntatori alla testa ed alla fine della coda
typedef struct a{
Queue queue; //struttura che rappresenta la coda
int (*comparison) (void*, void*); //funzione di comparazione tra 2 elementi(ritorna 1 se uguali, 0 altrimenti)
void (*printFunct) (void*); //funzione di stampa delle info di un singolo nodo
void (*freeFunct) (void*); //funzione di liberazione della memoria del contenuto informativo di un singolo nodo
int size; //cardinalità attuale della coda
}GenericQueue;
//in quanto generica nella coda va specificata la funzione di comparazione di due elementi,
// la funzione di stampa di un elemento e la procedura di liberazione della memoria
// del campo info del nodo
//funzione di comparazione di default(interpreta gli elementi come interi)
//restituisce 1 in caso di elementi uguali, 0 altrimenti
int defaultComparison(void*, void*);
//funzione di default per la stampa di un elemento(intero)
void defaultPrinter(void*);
//funzione di liberazione di memoria di default(intero)
void defaultFreeFunct(void*);
/*
crea e ritorna una coda generica e
se comp == NULL usa come funzione di comparazione "defaultComparison",
se print == NULL usa come funzione di stampa "defaultPrinter",
se fr == NULL usa come funzione di liberazione "defaultFreeFunct"
*/
GenericQueue createQueue(int (*) (void*, void*), void (*) (void*), void (*) (void*));
/*
Crea un nodo generico restituendone il puntatore
in caso di successo. In caso di errore(fallimento della malloc
oppure parametro == NULL), ritorna NULL
*/
static GenericNode* createNode(void *);
/*
Inserimento in coda di un nuovo elemento:
restituisce -1 se la malloc fallisce oppure se
il secondo parametro è NULL, 1 altrimenti
*/
int push(GenericQueue*, void *);
/*estrazione in testa:
ritorna NULL se la coda è vuota, il
contenuto informativo dell'elemento di testa altrimenti
*/
void* pop(GenericQueue*);
//cancella un elemento ricercato dalla coda(se non è presente la coda è inalterata)
void deleteElement(GenericQueue*, void*);
//cerca un elemento nella coda(1 se lo trova, -1 altrimenti)
int findElement(GenericQueue, void*);
//verifica se la coda è vuota o meno(1 se lo è, 0 altrimenti)
int isEmpty(GenericQueue);
//stampa della coda
void printQueue(GenericQueue);
//pulizia della coda
void freeQueue(GenericQueue*);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "combinaisons.h"
int valeur_combinaison(int iCartes_joueur[2], int iCartes_communes[5])
{
int iValeur_combinaison = 0;
int iTableau_cartes[7];
// Remplissage du tableau avec les valeurs de chaque cartes.
for(int i = 0; i < 2; i++)
{
iTableau_cartes[i] = iCartes_joueur[i];
}
for(int i = 0; i < 5; i++)
{
iTableau_cartes[i+2] = iCartes_communes[i];
}
for(int i = 0; i < 7; i++)
{
printf("\nCarte %i : %i",i+1 , iTableau_cartes[i]);
}
// On test ici toutes les combinaisons en commenant par les plus hautes.
// Si lon trouve une combinaison la valeur de celle-ci est enregistre dans la variable iValeur_combinaison
if(iValeur_combinaison == 0)
{
iValeur_combinaison = quinte_royale(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = quinte_flush(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = carre(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = full(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = couleur(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = suite(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = brelan(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = double_paire(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = simple_paire(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
iValeur_combinaison = carte_haute(iTableau_cartes, 7);
}
if(iValeur_combinaison == 0)
{
return -1;
}
else
{
return iValeur_combinaison;
}
}
int quinte_royale(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int quinte_flush(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int carre(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int full(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int couleur(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int suite(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int brelan(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int double_paire(int iTableau_cartes[], int iNombre_cartes)
{
return 0;
}
int simple_paire(int iTableau_cartes[], int iNombre_cartes)
{
if (iNombre_cartes > 0)
{
int iValeur_combinaison = 0;
int iValeur_combinaison_temp = 0;
int iNombre_cartes_restantes = iNombre_cartes;
int * iTableau_cartes_restantes;
iTableau_cartes_restantes = malloc( iNombre_cartes_restantes * sizeof(int));
if(iTableau_cartes_restantes == NULL)
{
printf("Allocation impossible");
exit(EXIT_FAILURE);
}
for(int i = 0; i < iNombre_cartes_restantes; i++)
{
iTableau_cartes_restantes[i] = iTableau_cartes[i];
}
while(iNombre_cartes_restantes != 0)
{
for(int i = 1; i < iNombre_cartes_restantes; i++)
{
// On test sil sagit dune paire avec la premire carte du tableau
// Sil sagit dune paire, on rentre la valeur de la carte dans iValeur_combinaison_temp
// sinon on lui donne la valeur 0
iValeur_combinaison_temp = iTableau_cartes_restantes[0] == iTableau_cartes_restantes[i] ? iTableau_cartes_restantes[i] : 0;
// On modifie iValeur_combinaison uniquement si on a une meilleure paire.
if((iValeur_combinaison_temp != 0) & (iValeur_combinaison < iValeur_combinaison_temp))
{
iValeur_combinaison = iValeur_combinaison_temp;
}
}
iNombre_cartes_restantes -= 1;
if (iNombre_cartes_restantes > 0)
{
free(iTableau_cartes_restantes);
iTableau_cartes_restantes = malloc( iNombre_cartes_restantes * sizeof(int));
if(iTableau_cartes_restantes == NULL)
{
printf("Allocation impossible");
exit(EXIT_FAILURE);
}
for(int i = 0; i < iNombre_cartes_restantes; i++)
{
iTableau_cartes_restantes[i] = iTableau_cartes[iNombre_cartes - iNombre_cartes_restantes + i];
}
}
}
int iCartes_joueur[2];
int iCartes_communes[5];
for(int i = 0; i < 2; i++)
{
if(iTableau_cartes[i] == iValeur_combinaison)
{
iCartes_joueur[i] = 0;
}
else
{
iCartes_joueur[i] = iTableau_cartes[i];
}
}
for(int i = 0; i < 5; i++)
{
if(iTableau_cartes[i+2] == iValeur_combinaison)
{
iCartes_communes[i] = 0;
}
else
{
iCartes_communes[i] = iTableau_cartes[i+2];
}
}
// Lordre de grandeur dune paire est de 10000 ajout la valeur dune combinaison et de la carte haute.
// On dfinit la carte haute soit partir de la main du joueur si le joueur dispose dune paire partir dune
// ou aucune carte de sa main soit partir des cartes communes uniquement si le joueur sa paire dans
// sa propre main.
// Exemple de valeur : Paire de dames avec 10 comme carte haute -> 11210.
if((iTableau_cartes[0] != iTableau_cartes[1]) & (iValeur_combinaison !=0))
{
iValeur_combinaison = 10000 + iValeur_combinaison*100 + carte_haute(iCartes_joueur, 2)/100;
}
else if(iValeur_combinaison !=0)
{
iValeur_combinaison = 10000 + iValeur_combinaison*100 + carte_haute(iCartes_communes, 5)/100;
}
return iValeur_combinaison;
}
else
{
printf("Nombre de cartes invalide");
exit(EXIT_FAILURE);
}
}
int carte_haute(int iTableau_cartes[], int iNombre_cartes)
{
if (iNombre_cartes > 0)
{
int iValeur_combinaison = 0;
int iValeur_combinaison_temp = 0;
for(int i = 0; i < iNombre_cartes; i++)
{
iValeur_combinaison_temp = iTableau_cartes[0] <= iTableau_cartes[i] ? iTableau_cartes[i] : 0;
// On modifie iValeur_combinaison uniquement si on a une meilleure carte.
if((iValeur_combinaison_temp != 0) & (iValeur_combinaison < iValeur_combinaison_temp))
{
iValeur_combinaison = iValeur_combinaison_temp;
}
}
return (iValeur_combinaison*100)+iValeur_combinaison;
}
else
{
printf("Nombre de cartes invalide");
exit(EXIT_FAILURE);
}
}
|
C
|
#include "extname.h"
#include <string.h>
const char *extname(const char *filename)
{
const char *slash = strrchr(filename, '/');
const char *loc = strrchr(slash? slash : filename, '.');
return loc? loc : "";
}
|
C
|
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "node.h"
struct janus_node *janus_node_alloc (struct janus_node *parent,
const char *name, int value)
{
struct janus_node *n;
assert (parent != NULL);
assert (name != NULL);
if ((n = malloc (sizeof (*n))) == NULL)
goto no_node;
n->parent = parent;
n->next = parent->child;
n->child = NULL;
if ((n->name = strdup (name)) == NULL)
goto no_name;
n->value = value;
n->black = 0;
n->red = 1;
parent->child = n;
return n;
no_name:
free (n);
no_node:
return NULL;
}
static void janus_node_unlink (struct janus_node *n)
{
struct janus_node **p;
if (n->parent == NULL)
return;
for (p = &n->parent->child; *p != NULL; p = &(*p)->next)
if (*p == n) {
*p = n->next;
return;
}
}
void janus_node_free (struct janus_node *n)
{
struct janus_node *p, *next;
if (n == NULL)
return;
janus_node_unlink (n);
for (p = n->child; p != NULL; p = next) {
next = p->next;
janus_node_free (p);
}
free (n->name);
free (n);
}
struct janus_node *janus_node_find (struct janus_node *parent,
const char *name)
{
struct janus_node *p;
assert (parent != NULL);
assert (name != NULL);
for (p = parent->child; p != NULL; p = p->next)
if (strcmp (name, p->name) == 0)
return p;
errno = ENOENT;
return NULL;
}
void janus_node_black (struct janus_node *n)
{
struct janus_node *p;
assert (n != NULL);
if (n->red) {
janus_node_free (n);
return;
}
n->black = 1;
for (p = n->child; p != NULL; p = p->next)
janus_node_black (p);
}
int janus_node_commit (struct janus_node *root)
{
struct janus_node *p, *next;
assert (root != NULL);
for (p = root->child; p != NULL; p = next) {
next = p->next;
if (p->black) {
janus_node_free (p);
continue;
}
if (p->red)
p->red = 0;
janus_node_commit (p);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* client.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cgay <cgay@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/04/29 00:14:43 by cgay #+# #+# */
/* Updated: 2015/04/29 00:14:46 by cgay ### ########.fr */
/* */
/* ************************************************************************** */
#include "../INCLUDE/paquet.h"
#include "../INCLUDE/client.h"
void usage(char *str)
{
ft_putstr(C_CYAN);
ft_putstr("Usage: ");
ft_putstr(str);
ft_putstr(" <addr> <port>\n");
ft_putstr(C_RESET);
exit(-1);
}
int create_client(char *addr, int port)
{
int sock;
struct protoent *proto;
struct sockaddr_in sin;
proto = getprotobyname("tcp");
if (proto == 0)
return (-1);
sock = socket(PF_INET, SOCK_STREAM, proto->p_proto);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = inet_addr(addr);
if (connect(sock, (const struct sockaddr *)&sin, sizeof(sin)) == -1)
error("Connect error", 1);
return (sock);
}
void ft_read(int sock)
{
int r;
char buf[1024];
t_list paquet;
init_paquet(&paquet);
while ((r = read(0, buf, 1023)) > 0)
{
buf[r] = '\0';
write(sock, buf, r);
if (ft_strcmp(ft_strtrim(buf), "quit") == 0)
break ;
else if (ft_strcmp(ft_strtrim(buf), "ls") == 0
|| ft_strcmp(ft_strtrim(buf), "pwd") == 0)
ft_aff(sock);
else if (ft_strncmp(ft_strtrim(buf), "cd ", 3) == 0
|| ft_strcmp(ft_strtrim(buf), "cd..") == 0)
success("Path changer");
else
read_paquet(&paquet, buf);
if (paquet.get == 1)
ft_get(sock, buf, &paquet);
if (paquet.put == 1)
ft_put(sock, buf, &paquet);
ft_putstr("->");
}
}
int main(int ac, char **av)
{
int port;
int sock;
if (ac != 3)
usage(av[0]);
port = atoi(av[2]);
sock = create_client(av[1], port);
ft_putstr("->");
ft_read(sock);
close(sock);
return (0);
}
|
C
|
#include "pilaestatica.h"
int
main (int argc, char *argv[])
{
struct Pila pila;
crear (&pila);
agregar (&pila, 9);
agregar (&pila, 8);
agregar (&pila, 7);
agregar (&pila, 6);
agregar (&pila, 5);
agregar (&pila, 4);
agregar (&pila, 3);
agregar (&pila, 2);
agregar (&pila, 1);
agregar (&pila, 0);
mostrar (&pila);
eliminar (&pila);
printf ("El ultimo dato de la pila es: %d\n", ultimo (&pila));
return 0;
}
|
C
|
/*
* A blinker that uses the systick interrupt
* to be a bit more accurate.
*
* Copyright (C) 2018, Charles McManis
* Contributed to the Public Domain, July 2018 by Charles McManis
*/
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include "../util/clock.h"
int
main(void)
{
/* Call clock setup from the clock code */
clock_setup();
/* enable GPIOA clock */
rcc_periph_clock_enable(RCC_GPIOA);
/* set up pin 5 of GPIO A as an output */
gpio_mode_setup(GPIOA, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO5);
/* Set the logic state to 'high' for GPIO5 */
gpio_set(GPIOA, GPIO5);
while (1) {
/* toggle the state of GPIO5 */
gpio_toggle(GPIOA, GPIO5);
/* sleep for 500 milleseconds */
msleep(500);
}
}
|
C
|
#include <stdio.h>
int main()
{
int n;
int i;
for (n = 1; n <= 100; n++)
{
for (i = 2; i < n; i++)
{
if (n%i == 0)
{
break;
}
}
if (i == n)
{
printf("%3d", i);
}
}
printf("\n");
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<conio.h>
void tabs(FILE *fp) {
char c;
if (fp == NULL) { printf("error opening"); }
c = fgetc(fp);
while (c != feof(fp)) {
if (c == '\t')
{
fputc(fp, "/t");
}
c = fgetc(fp);
}
}
|
C
|
/*
--------------------------------------------
Up to 20% marks will be allotted for good programming practice. These include
- Comments: for non-trivial code
- Indentation: align your code properly
- Function use and modular programming
- Do not include anything in the header other than what is already given in the template.
- You are required to allocate memory Dynamically instead of static memory allocation otherwise you might get 0
- TAs: Please ensure that the submission is doing Comb Sort and not any other sorting routine.
---------------------------------------------
This question introduces you to new algorithms to sort n positive integers (in a non-decreasing order).
In bubble sort, when any two elements are compared, they always have a gap (distance from each other in the array) of 1. The basic idea of comb sort is that the gap can be much more than 1.
The basic idea is to eliminate turtles, or small values near the end of the list, since in a bubble sort these slow down the sorting tremendously. Rabbits, large values around the beginning of the list, do not pose a problem in bubble sort.
In other words, the inner loop, which does the actual swap, is modified such that the gap between swapped elements goes down (for each iteration of outer loop) in steps of shrink factor. i.e. [ n/shrink , n/shrink^2, n/shrink^3, ...., 1 ]. Unlike in bubble sort, where the gap is constant i.e. 1.
The gap starts out as the length of the list being sorted divided by the shrink factor (generally 1.3; see below), and the list is sorted with that value (rounded down to an integer if needed) as the gap. Then the gap is divided by the shrink factor again, the list is sorted with this new gap, and the process repeats until the gap is 1. At this point, comb sort continues using a gap of 1 until the list is fully sorted. The final stage of the sort is thus equivalent to a bubble sort, but by this time most turtles have been dealt with, so a bubble sort will be efficient.
The algorithm is described in the following pseudocode:
1. Choose the gap = n/shrink.
2a. If the gap is *strictly greater* than 1, do a single pass on the list, such that in the pass, you compare the i-th element with (i+gap)-th element and swapping these elements if arr[i] > arr[i+gap]. You do this for all i, from i=0, till i+gap>=n.
2b. If the gap is equal to 1, do a pass (of swaps, the same as in 2a) over the whole list and since gap==1, i+gap is the same as i+1, i.e. you compare the adjacent elements throughout the pass. If there are no swaps in this pass, exit and return the now sorted list.
3. Decrease the gap by dividing it by the shrink factor and do step 2 again. If the gap is less than 1, set gap equal to 1 and do step 2 again.
(Please note that when gap==1, you are essentially doing a bubble sort on the whole list! Hence the list is bound to be sorted at the end of this subroutine. However, the wonderful thing about this sorting algorithm is that it is much faster than bubble sort, in general!)
Note: Use a shrink factor of 1.3 for this assignment.
Input: A positive integer n followed by a line containing n positive integers separated by space.
Output: Space separated sorted list of integers.
*/
#include<stdio.h>
#include<stdlib.h>
void CombSort(int* arr, int n){
int gap = n;
float shrink = 1.3;
int swapped = 1;
while(gap>=1 && swapped==1){
gap = (int) ((float)gap)/shrink;
if(gap<1) gap=1;
int i=0;
if(gap==1)
swapped=0;
while((i+gap)<n){
if(arr[i]>arr[i+gap]){
int temp = arr[i];
arr[i]=arr[i+gap];
arr[i+gap]=temp;
if(gap==1)
swapped=1;
}
i++;
}
}
}
int main(){
int n;
scanf("%d",&n);
int* arr;
arr = (int*) malloc(n*sizeof(int));
int i;
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
CombSort(arr,n);
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
printf("\n");
return 0;
}
|
C
|
#if defined(T) && defined(T_EQUALS)
#define OOC_V1
#include "ooc_template.h"
//can't define this as Set since name collision
#define SET CAT(Set, T)
#define SETNODE CAT(SetNode, T)
#define SetVFTable CAT(SET, VFTable)
#define setVFTable CAT(CAT(Set, T), vfTable)
SetVFTable setVFTable =
{
NULL_OBJECT_VFTABLE,
.add = NULL,
.clear = NULL,
.remove = NULL,
.contains = NULL,
.copy = NULL,
.isEmpty = NULL,
.size = NULL,
.set = NULL,
.insert = NULL,
.find = NULL,
.replace = NULL
};
TypeDescriptor CAT(setTypeDescriptor, T) =
{
.pVFTable = &setVFTable,
//necessary for checking type Upcast macro (can't print pretty)
.name = STRINGIFY(SET)
//print pretty vvvv
//.name = STRINGIFY(Set(T))
};
BaseClassDescriptor CAT(setBaseClassArray, T)[] =
{
ContainerBaseClassDescriptor,
SetBaseClassDescriptor(T)
};
ClassHierarchyDescriptor CAT(setClassHierarchyDescriptor, T) =
{
.attributes = CLASS_HIERARCHY_VIRTUAL_INHERITENCE,
.numBaseClasses = 2,
.pBaseClassArray = CAT(setBaseClassArray, T)
};
CompleteObjectLocator CAT(setCompleteObjectLocator, T) =
{
.signature = 0x48454845,
.pTypeDescriptor = &CAT(setTypeDescriptor, T),
.pClassHierarchyDescriptor = &CAT(setClassHierarchyDescriptor, T)
};
/*============================================================================
| Helper functions
*===========================================================================*/
static int CAT(SetIsRed, T)(SETNODE node)
{
return (node != NULL && node->color) ? (RED) : (BLACK);
}
#define IsRed(node) CAT(SetIsRed, T)(node)
/*============================================================================
| Example Rotate left
| 1
| 2 4
| 3 5
|
| first line
| 1 <--- old root
| 2 4 <--- new root
| 3 5
|
| second line
| 1 <--- old root
| 2 3 4 <--- new root
| 5
|
| third line
| 4 <--- new root
| 1 5
| 2 3
|*===========================================================================*/
static SETNODE CAT(SetSingleRotate, T)(SETNODE root, int direction)
{
//get the opposite node
SETNODE new_root = root->children[!direction];
//switch over opposite node's child as old root's child
root->children[!direction] = new_root->children[direction];
//update the new root to set the old root as its child
new_root->children[direction] = root;
//update the colors, so the tree is valid
root->color = RED;
new_root->color = BLACK;
return new_root;
}
#define SingleRotate(root, direction) CAT(SetSingleRotate, T)(root, direction)
/*============================================================================
| Example Double rotate left
| 5 <--- old root
| / \
| 3 7
| / \ / \
| 2 4 6 9
| / \
| 8 10
|
| first line
| 5
| / \
| 3 7 <--- current root
| / \ / \
| 2 4 6 9
| / \
| 8 10
|
| 5 <---old root sets new current root to be its child
| / \
| 3 6 <--- new current root
| / \ \
| 2 4 7
| \
| 9
| / \
| 8 10
|
| second line
| 6 <--- new current root
| / \
| old root ---> 5 7
| / \
| 3 9
| / \ / \
| 2 4 8 10
|*===========================================================================*/
static SETNODE CAT(SetDoubleRotate, T)(SETNODE root, int direction)
{
//opposite rotate child?
root->children[!direction] = SingleRotate(root->children[!direction], !direction);
//rotate root
return SingleRotate(root, direction);
}
#define DoubleRotate(root, direction) CAT(SetDoubleRotate, T)(root, direction)
static SETNODE CAT(SetNewMoveNode, T)(T* data_ptr)
{
SETNODE new_node = check_calloc(sizeof(struct CAT(Set_Node, T)));
new_node->data = *data_ptr;
new_node->children[LEFT] = NULL;
new_node->children[RIGHT] = NULL;
new_node->color = RED;
return new_node;
}
#define NewMoveNode(data_ptr) CAT(SetNewMoveNode, T)(data_ptr)
static SETNODE CAT(SetNewNode, T)(T* data_ptr)
{
SETNODE new_node = check_calloc(sizeof(struct CAT(Set_Node, T)));
new_node->data = T_COPY(data_ptr);
new_node->children[LEFT] = NULL;
new_node->children[RIGHT] = NULL;
new_node->color = RED;
return new_node;
}
#define NewNode(data_ptr) CAT(SetNewNode, T)(data_ptr)
static SETNODE CAT(SetCopyNode, T)(SETNODE node)
{
SETNODE new_node = check_calloc(sizeof(struct CAT(Set_Node, T)));
new_node->data = T_COPY(&node->data);
new_node->children[LEFT] = NULL;
new_node->children[RIGHT] = NULL;
new_node->color = node->color;
return new_node;
}
#define CopyNode(node) CAT(SetCopyNode, T)(node)
/*
int CAT(SetTest, T)(CAT(SetNode, T) root, int indent)
{
if (root == NULL)
{
return 1;
}
else
{
SETNODE left = root->children[LEFT];
SETNODE right = root->children[RIGHT];
if (IsRed(root))
{
if (IsRed(left) || IsRed(right))
{
puts("RED VIOLATION");
return 0;
}
}
if ((left != NULL && T_COMPARE_TO(left->data, root->data) >= 0) || (right != NULL && T_COMPARE_TO(right->data, root->data) <= 0))
{
puts("BINARY TREE VIOLATION");
return 0;
}
int right_height = CAT(SetTest, T)(right, indent + 4);
for (int i = 0; i < indent; i++)
{
printf(" ");
}
if (right)
{
printf(" /\n");
for (int i = 0; i < indent; i++)
{
printf(" ");
}
}
//print root
//printf("%d\n", root->data);
if (left)
{
for (int i = 0; i < indent; i++)
{
printf(" ");
}
printf(" \\\n");
}
int left_height = CAT(SetTest, T)(left, indent + 4);
if (left_height != 0 && right_height != 0 && left_height != right_height)
{
puts("BLACK VIOLATION");
return 0;
}
if (left_height != 0 && right_height != 0)
{
return IsRed(root) ? left_height : left_height + 1;
}
else
{
return 0;
}
}
}
*/
/*============================================================================
| New Operator
*===========================================================================*/
SET CAT(NewSet, T)()
{
//allocate a new set
SET this = check_calloc(sizeof(struct CAT(Set_, T)));
//cast to set
SET this_set = (SET)this;
//allocate vftable
this_set->container.object.pVFTable = check_calloc(sizeof(SetVFTable));
//call constructor to set up string
CAT(SetConstruct, T)(this);
return this;
}
/*============================================================================
| Delete Operator
*===========================================================================*/
void CAT(DeleteSet, T)(SET this)
{
CHECK_NULL_NO_RET(this);
//cast to set
SET this_set = (SET)this;
//call destructor
CAT(SetDestruct, T)(this);
//null the (casted) vftable
this_set->container.object.pVFTable = NULL;
//free vftable
free(this_set->container.object.objectpVFTable);
//free the string's resources
free(this);
}
/*============================================================================
| Constructor
*===========================================================================*/
void CAT(SetConstruct, T)(SET this)
{
CHECK_NULL_NO_RET(this);
//call super class's constructor (ObjectConstruct)
ContainerConstruct(this);
//Override Object's methods
//=========================
//Set the vtable's complete object locator to complete the RTTI circle
setVFTable.pCompleteObjectLocator = &CAT(setCompleteObjectLocator, T);
setVFTable.delete = &CAT(DeleteSet, T);
setVFTable.copy = &CAT(SetCopy, T);
setVFTable.equals = &CAT(SetEquals, T);
setVFTable.compareTo = &CAT(SetCompareTo, T);
setVFTable.toString = &CAT(SetToString, T);
//Override Container's methods
//==========================
setVFTable.add = &CAT(SetAdd, T);
setVFTable.clear = &CAT(SetClear, T);
setVFTable.remove = &CAT(SetRemove, T);
setVFTable.contains = &CAT(SetContains, T);
setVFTable.isEmpty = &CAT(SetIsEmpty, T);
setVFTable.size = &CAT(SetSize, T);
//Initialize class member methods
//==========================
setVFTable.set = &CAT(SetSet_, T);
setVFTable.move_insert = &CAT(SetMoveInsert, T);
setVFTable.insert = &CAT(SetInsert, T);
setVFTable.find = &CAT(SetFind, T);
setVFTable.replace = &CAT(SetReplace, T);
setVFTable.begin = &CAT(SetBegin, T);
setVFTable.next = &CAT(SetNext, T);
setVFTable.end = &CAT(SetEnd, T);
//cast to set
SET this_set = (SET)this;
//Initialize the vtable to a copy of this object's vtable
memcpy(this_set->container.object.pVFTable, &setVFTable, sizeof(SetVFTable));
//Make the objectpVFTable point to the same table initially
this_set->container.object.objectpVFTable = this_set->container.object.pVFTable;
//Initialize member variables
//set size
this_set->size = 0;
//set root to NULL
this_set->root = NULL;
}
/*============================================================================
| Copy Constructor
*===========================================================================*/
static SETNODE CAT(SetCopyHelper, T)(SETNODE node, SETNODE copy_node)
{
if (node != NULL)
{
copy_node = CopyNode(node);
copy_node->children[LEFT] = CAT(SetCopyHelper, T)(node->children[LEFT], copy_node->children[LEFT]);
copy_node->children[RIGHT] = CAT(SetCopyHelper, T)(node->children[RIGHT], copy_node->children[RIGHT]);
return copy_node;
}
return NULL;
}
SET CAT(SetCopyConstruct, T)(SET this)
{
CHECK_NULL(this, NULL);
//cast to set
SET this_set = (SET)this;
//allocate a new set
SET copy = CAT(NewSet, T)();
//cast to set
SET copy_set = (SET)copy;
//copy the contents of the string to the copied set except for vftable (which is contained in Container struct inside the String struct)
copy_set->size = this_set->size;
//copy tree
copy_set->root = CAT(SetCopyHelper, T)(this_set->root, copy_set->root);
return copy;
}
/*============================================================================
| Destructor
*===========================================================================*/
void CAT(SetDestruct, T)(SET this)
{
CHECK_NULL_NO_RET(this);
//call super destructor
ContainerDestruct(this);
//call clear
CAT(SetClear, T)(this);
}
/*============================================================================
| Overridden member function definitions
*===========================================================================*/
static bool CAT(SetEqualsHelper, T)(SETNODE node1, SETNODE node2)
{
//if either are null, quit
if (node1 == NULL && node2 == NULL)
{
return true;
}
return (T_EQUALS(node1->data, node2->data) &&
CAT(SetEqualsHelper, T)(node1->children[LEFT], node2->children[LEFT]) &&
CAT(SetEqualsHelper, T)(node1->children[RIGHT], node2->children[RIGHT]));
}
bool CAT(SetEquals, T)(SET this, SET other)
{
CHECK_NULL(this, false);
CHECK_NULL(other, false);
//cast to set
SET this_set = (SET)this;
//cast to set
SET other_set = (SET)other;
//Check if the sizes are the same
if (this_set->size != other_set->size)
{
return false;
}
return CAT(SetEqualsHelper, T)(this_set->root, other_set->root);
}
static int CAT(SetCompareToHelper, T)(SETNODE node1, SETNODE node2)
{
//if either are null, quit
if (node1 == NULL && node2 == NULL)
{
return 0;
}
return (T_COMPARE_TO(node1->data, node2->data) &&
CAT(SetEqualsHelper, T)(node1->children[LEFT], node2->children[LEFT]) &&
CAT(SetEqualsHelper, T)(node1->children[RIGHT], node2->children[RIGHT]));
}
int CAT(SetCompareTo, T)(SET this, SET other)
{
CHECK_NULL(this, false);
CHECK_NULL(other, false);
//cast to set
SET this_set = (SET)this;
//cast to set
SET other_set = (SET)other;
//Check if the sizes are the same
if (this_set->size != other_set->size)
{
//should work?
return (int)this_set->size - (int)other_set->size;
}
return CAT(SetCompareToHelper, T)(this_set->root, other_set->root);
}
char* CAT(SetToString, T)(SET this)
{
CHECK_NULL(this, NULL);
return ContainerToString(this);
}
bool CAT(SetAdd, T)(SET this, T item)
{
return CAT(SetInsert, T)(this, item);
}
void CAT(SetClear, T)(SET this)
{
CHECK_NULL_NO_RET(this);
//cast to set
SET this_set = (SET)this;
this_set->size = 0;
SETNODE node = this_set->root;
SETNODE save = NULL;
while (node != NULL)
{
if (node->children[LEFT] == NULL)
{
//destroy and move to right
save = node->children[RIGHT];
T_DELETE(&node->data);
free(node);
node = NULL;
}
else
{
//rotate to right
save = node->children[LEFT];
node->children[LEFT] = save->children[RIGHT];
save->children[RIGHT] = node;
}
node = save;
}
this_set->root = NULL;
}
bool CAT(SetRemove, T)(SET this, T item)
{
CHECK_NULL(this, false);
SET this_set = (SET)this;
if (this_set->root == NULL)
{
return false;
}
//imaginary parent's root
struct CAT(Set_Node, T) parent_root = { .data = 0, .children = { NULL, NULL }, .color = BLACK };
parent_root.children[RIGHT] = this_set->root;
SETNODE grandparent = NULL;
SETNODE parent = NULL;
SETNODE current_node = &parent_root;
SETNODE found_node = NULL;
int direction = RIGHT;
int last_direction = 0;
while (current_node->children[direction] != NULL)
{
//update
last_direction = direction;
grandparent = parent;
parent = current_node;
current_node = current_node->children[direction];
direction = T_COMPARE_TO(current_node->data, item) < 0;
if (T_EQUALS(current_node->data, item))
{
found_node = current_node;
}
if (!IsRed(current_node) && !IsRed(current_node->children[direction]))
{
if (IsRed(current_node->children[!direction]))
{
parent = parent->children[last_direction] = SingleRotate(current_node, direction);
}
else if (!IsRed(current_node->children[!direction]))
{
SETNODE other = parent->children[!last_direction];
if (other != NULL)
{
if (!IsRed(other->children[!last_direction]) && !IsRed(other->children[last_direction]))
{
parent->color = BLACK;
other->color = RED;
current_node->color = RED;
}
else
{
int is_violation_on_right = grandparent->children[RIGHT] == parent;
if (IsRed(other->children[last_direction]))
{
grandparent->children[is_violation_on_right] = DoubleRotate(parent, last_direction);
}
else if (IsRed(other->children[!last_direction]))
{
grandparent->children[is_violation_on_right] = SingleRotate(parent, last_direction);
}
current_node->color = grandparent->children[is_violation_on_right]->color = RED;
grandparent->children[is_violation_on_right]->children[LEFT]->color = BLACK;
grandparent->children[is_violation_on_right]->children[RIGHT]->color = BLACK;
}
}
}
}
}
if (found_node != NULL)
{
T_DELETE(&found_node->data);
found_node->data = current_node->data;
parent->children[parent->children[RIGHT] == current_node] = current_node->children[current_node->children[LEFT] == NULL];
free(current_node);
}
this_set->root = parent_root.children[RIGHT];
if (this_set->root != NULL)
{
this_set->root->color = BLACK;
}
this_set->size--;
return true;
}
bool CAT(SetContains, T)(SET this, T item)
{
CHECK_NULL(this, false);
SET this_set = (SET)this;
if (this_set->root == NULL)
{
//empty tree
return false;
}
else
{
SETNODE current_node = this_set->root;
int direction = 0;
while (current_node != NULL)
{
//if data is equal, then we stop
if (T_EQUALS(current_node->data, item))
{
return true;
}
direction = T_COMPARE_TO(current_node->data, item) < 0;
current_node = current_node->children[direction];
}
}
return false;
}
SET CAT(SetCopy, T)(SET this)
{
CHECK_NULL(this, NULL);
return CAT(SetCopyConstruct, T)(this);
}
bool CAT(SetIsEmpty, T)(SET this)
{
CHECK_NULL(this, false);
//cast to set
SET this_set = (SET)this;
return this_set->size == 0;
}
size_t CAT(SetSize, T)(SET this)
{
CHECK_NULL(this, false);
//cast to set
SET this_set = (SET)this;
return this_set->size;
}
bool CAT(SetSet_, T)(SET this, const T* item, size_t num_elements)
{
CHECK_NULL(this, false);
//clear the set
CAT(SetClear, T)(this);
//insert items
//loop until null
for (size_t i = 0; i < num_elements; i++)
{
CAT(SetMoveInsert, T)(this, item[i]);
}
return true;
}
bool CAT(SetMoveInsert, T)(SET this, T item)
{
CHECK_NULL(this, false);
SET this_set = (SET)this;
//check if we need to update size
bool inserted_node = false;
if (this_set->root == NULL)
{
//empty tree
this_set->root = NewMoveNode(&item);
inserted_node = true;
}
else
{
//imaginary parent's root
struct CAT(Set_Node, T) parent_root = { .data = 0, .children = { NULL, NULL }, .color = BLACK };
parent_root.children[RIGHT] = this_set->root;
SETNODE greatgrandparent = &parent_root;
SETNODE grandparent = NULL;
SETNODE parent = NULL;
SETNODE current_node = this_set->root;
int direction = 0;
int last_direction = 0;
while (true)
{
//case when we reach a NULL, we insert item
if (current_node == NULL)
{
parent->children[direction] = current_node = NewMoveNode(&item);
inserted_node = true;
}
//color flip parent and children
if (IsRed(current_node->children[LEFT]) && IsRed(current_node->children[RIGHT]))
{
current_node->color = RED;
current_node->children[LEFT]->color = BLACK;
current_node->children[RIGHT]->color = BLACK;
}
//other red violation
if (IsRed(parent) && IsRed(current_node))
{
//check which side the violation is on
int is_violiation_on_right = (greatgrandparent->children[RIGHT] == grandparent);
//check if single or double rotate
if (parent->children[last_direction] == current_node)
{
greatgrandparent->children[is_violiation_on_right] = SingleRotate(grandparent, !last_direction);
}
else
{
greatgrandparent->children[is_violiation_on_right] = DoubleRotate(grandparent, !last_direction);
}
}
//if data is equal, then we stop
if (T_EQUALS(current_node->data, item))
{
if (!inserted_node)
{
//replace node with moved item
T_DELETE(¤t_node->data);
current_node->data = item;
}
break;
}
//move on to next node
last_direction = direction;
direction = T_COMPARE_TO(current_node->data, item) < 0;
if (grandparent != NULL)
{
greatgrandparent = grandparent;
}
grandparent = parent;
parent = current_node;
current_node = current_node->children[direction];
}
//update root
this_set->root = parent_root.children[RIGHT];
}
//make root black
this_set->root->color = BLACK;
if (inserted_node)
{
this_set->size++;
}
return true;
}
bool CAT(SetInsert, T)(SET this, T item)
{
CHECK_NULL(this, false);
SET this_set = (SET)this;
//check if we need to update size
bool inserted_node = false;
if (this_set->root == NULL)
{
//empty tree
this_set->root = NewNode(&item);
inserted_node = true;
}
else
{
//imaginary parent's root
struct CAT(Set_Node, T) parent_root = { .data = 0, .children = { NULL, NULL }, .color = BLACK };
parent_root.children[RIGHT] = this_set->root;
SETNODE greatgrandparent = &parent_root;
SETNODE grandparent = NULL;
SETNODE parent = NULL;
SETNODE current_node = this_set->root;
int direction = 0;
int last_direction = 0;
while (true)
{
//case when we reach a NULL, we insert item
if (current_node == NULL)
{
parent->children[direction] = current_node = NewNode(&item);
inserted_node = true;
}
//color flip parent and children
if (IsRed(current_node->children[LEFT]) && IsRed(current_node->children[RIGHT]))
{
current_node->color = RED;
current_node->children[LEFT]->color = BLACK;
current_node->children[RIGHT]->color = BLACK;
}
//other red violoation
if (IsRed(parent) && IsRed(current_node))
{
//check which side the violation is on
int is_violiation_on_right = (greatgrandparent->children[RIGHT] == grandparent);
//check if single or double rotate
if (parent->children[last_direction] == current_node)
{
greatgrandparent->children[is_violiation_on_right] = SingleRotate(grandparent, !last_direction);
}
else
{
greatgrandparent->children[is_violiation_on_right] = DoubleRotate(grandparent, !last_direction);
}
}
//if data is equal, then we stop
if (T_EQUALS(current_node->data, item))
{
if (!inserted_node)
{
//replace node with moved item
T_DELETE(¤t_node->data);
current_node->data = T_COPY(&item);
}
break;
}
//move on to next node
last_direction = direction;
direction = T_COMPARE_TO(current_node->data, item) < 0;
if (grandparent != NULL)
{
greatgrandparent = grandparent;
}
grandparent = parent;
parent = current_node;
current_node = current_node->children[direction];
}
//update root
this_set->root = parent_root.children[RIGHT];
}
//make root black
this_set->root->color = BLACK;
if (inserted_node)
{
this_set->size++;
}
return true;
}
T* CAT(SetFind, T) (SET this, T item)
{
CHECK_NULL(this, NULL);
SET this_set = (SET)this;
if (this_set->root == NULL)
{
//empty tree
return NULL;
}
else
{
SETNODE current_node = this_set->root;
int direction = 0;
while (current_node != NULL)
{
//if data is equal, then we stop
if (T_EQUALS(current_node->data, item))
{
return ¤t_node->data;
}
direction = T_COMPARE_TO(current_node->data, item) < 0;
current_node = current_node->children[direction];
}
}
return NULL;
}
bool CAT(SetReplace, T)(SET this, T to_replace, T replacement)
{
CHECK_NULL(this, false);
SET this_set = (SET)this;
if (this_set->root == NULL)
{
//empty tree
return false;
}
else
{
SETNODE current_node = this_set->root;
int direction = 0;
while (current_node != NULL)
{
//if data is equal, then we stop
if (T_EQUALS(current_node->data, to_replace))
{
//delete and move the result in place
T_DELETE(¤t_node->data);
current_node->data = replacement;
return true;
}
direction = T_COMPARE_TO(current_node->data, to_replace) < 0;
current_node = current_node->children[direction];
}
}
return false;
}
static T* CAT(GetSetInOrderTraversalByIndex, T)(SETNODE node, int* current_index, int wanted_index)
{
if (node != NULL)
{
T* left_data = CAT(GetSetInOrderTraversalByIndex, T)(node->children[LEFT], current_index, wanted_index);
if (left_data != NULL)
{
return left_data;
}
if (*current_index == wanted_index)
{
return &node->data;
}
(*current_index)++;
return CAT(GetSetInOrderTraversalByIndex, T)(node->children[RIGHT], current_index, wanted_index);
}
return NULL;
}
CAT(CAT(Set, T), Iterator) CAT(SetBegin, T)(SET this)
{
CHECK_NULL(this, NULL);
SET this_set = (SET)this;
//allocate a iterator
CAT(CAT(Set, T), Iterator) iterator = check_calloc(sizeof(struct CAT(CAT(Set_, T), Iterator)));
iterator->index = 0;
int start_index = 0;
iterator->data = CAT(GetSetInOrderTraversalByIndex, T)(this_set->root, &start_index, iterator->index);
return iterator;
}
bool CAT(SetNext, T)(SET this, CAT(CAT(Set, T), Iterator) iterator)
{
CHECK_NULL(this, false);
CHECK_NULL(iterator, false);
SET this_set = (SET)this;
//search for child node that has the value...
//(This is inefficient, but it follows how iterators work in the design)
iterator->index++;
int start_index = 0;
iterator->data = CAT(GetSetInOrderTraversalByIndex, T)(this_set->root, &start_index, iterator->index);
return true;
}
CAT(CAT(Set, T), Iterator) CAT(SetEnd, T)(SET this, CAT(CAT(Set, T), Iterator) iterator)
{
CHECK_NULL(this, NULL);
CHECK_NULL(iterator, NULL);
SET this_set = (SET)this;
//check if iterator is at the end
if (iterator->index == (int)this_set->size)
{
iterator->index = NPOS;
iterator->data = NULL;
free(iterator);
return NULL;
}
return iterator;
}
/*============================================================================
| Class member definitions
*===========================================================================*/
#undef IsRed
#undef SingleRotate
#undef DoubleRotate
#undef NewMoveNode
#undef NewNode
#undef SET
#undef SETNODE
#undef SetVFTable
#undef setVFTable
#endif
|
C
|
#include "tm4c123gh6pm.h"
#include "keypad.h"
#include "lcd.h"
#include <stdint.h>
#include <stdbool.h>
unsigned char exp[5];
bool flag = false;
int i ;
bool calc =false;
bool contact= false;
bool isOperand(unsigned char c) {
return (c >= '0' && c <= '9');
}
// utility function to find value of and operand
int value( unsigned char c) {
return (c - '0');
}
// This function evaluates simple expressions. It returns -1 if the
// given expression is invalid.
int evaluate( unsigned char *exp)
{
// Base Case: Given expression is empty
if (*exp == '\0') return -1;
// The first character must be an operand, find its value
int res = value(exp[0]);
// Traverse the remaining characters in pairs
for (int i = 1; exp[i]; i += 2)
{
// The next character must be an operator, and
// next to next an operand
char opr = exp[i], opd = exp[i+1];
// If next to next character is not an operand
if (!isOperand(opd)) return -1;
// Update result according to the operator
if (opr == '+') res += value(opd);
else if (opr == '-') res -= value(opd);
else if (opr == '*') res *= value(opd);
else if (opr == '/') res /= value(opd);
// If not a valid operator
else return -1;
}
return res;
}
void inttochar(int x1)
{
int y = x1%10;
int z = x1/10;
if(z!=0)
lcd_data(z+'0');
lcd_data(y+'0');
}
void GPIO_PORTC_Handler(void){
if(calc)
{
if(!flag)
{
lcd_clear();
i=0;
flag = true;
}
delayMs(200);
unsigned char character = keypad_getkey();
if( character !=0)
{
if ( character == '=')
{
exp[i]='\0';
lcd_data(character);
int x = evaluate(exp);
inttochar(x);
delayMs(1000);
flag =false;
}
else
{
lcd_data(character);
exp[i] = character;
i++;
}
}
}
if(contact)
{
}
if(!contact && !calc)
{
delayMs(200);
unsigned char character = keypad_getkey();
if(character == '1')
{
calc= true;
lcd_clear();
}
else if (character == '2')
{
contact=true;
lcd_clear();
}
}
}
|
C
|
/******************************************************************************
* @file FlashManager.h
* @author Adam Johnson
* @remarks Contains functions for EEPROM emulation using two pages of
* Flash memory. Based on code from NXP's app note AN11008,
* titled "Flash based non-volatile storage." Originally
* developed for MSP430.
*****************************************************************************/
#ifndef MEM_MANAGER_H
#define MEM_MANAGER_H
// Initialize access to non-volatile memory.
bool FlashManInit(void);
// Set the value of a variable.
bool FlashManSetVariable(uint16_t id, uint8_t *value, uint16_t size);
// Get the value of a variable.
bool FlashManGetVariable(uint16_t id, uint8_t *value, uint16_t size);
// Get the number of variables Flash will hold.
uint32_t FlashManGetMaxVariables(void);
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void clean_stdin(void) {
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
char *read_stdin(char * str, size_t size) {
char *result = fgets(str, size, stdin);
if (result != NULL) {
char *lf = strchr(str, '\n'); /* On cherche le caractere '\n'. */
if (lf != NULL) {
*lf = '\0';
}
}
return result;
}
|
C
|
#pragma once
#include "memory.h"
#include "geometry.h"
struct Monster;
struct Bullet;
struct Weapon;
struct EntityModel;
Pool<ConvexInSector, 0x10000> convexInSectorPool;
struct EntityPoint : Point3D
{
Point3D initialP;
float tx,ty;
};
struct Entity
{
int inProcess;
SPoint center;
Matrix3D position;
mslice <Convex> convexes;
Monster* monster;
Bullet* bullet;
Weapon* weapon;
mslice <EntityPoint> entityPoints;
EntityModel* model;
void Create (Sector* s, EntityModel* model);
static ConvexInSector*& PFNC (const ConvexInSector &cs) { return cs.nc ? cs.nc->pc : cs.sector->lConvex; }
static ConvexInSector*& PFPC (const ConvexInSector &cs) { return cs.pc ? cs.pc->nc : cs.sector->fConvex; }
static ConvexInSector*& PFNS (const ConvexInSector &cs) { return cs.ns ? cs.ns->ps : cs.convex->lSector; }
static ConvexInSector*& PFPS (const ConvexInSector &cs) { return cs.ps ? cs.ps->ns : cs.convex->fSector; }
static bool NoInThisSector(const Sector& s, Convex* c)
{
for (ConvexInSector* pcs=s.fConvex; pcs; pcs=pcs->nc)
if (pcs->convex==c)
return false;
return true;
}
void PutToSectors ()
{
marray<CheckPtr<Sector> > a(0,maxSectors,PK_TEMP);
for (int i=convexes.low(); i<convexes.high(); ++i)
{
Convex& c=convexes[i];
c.GetSectors(a);
assert(a.high()<=a.low()+10);
for (int j=a.low(); j<a.high(); ++j)
{
assert(NoInThisSector(*a[j], &c));
ConvexInSector* pcs = convexInSectorPool.NewPtr();
pcs->convex = &c;
pcs->sector = a[j];
(c.fSector ? c.lSector->ns : c.fSector)=pcs;
pcs->ps = c.lSector;
c.lSector = pcs;
(a[j]->fConvex ? a[j]->lConvex->nc : a[j]->fConvex)=pcs;
pcs->pc = a[j]->lConvex;
a[j]->lConvex = pcs;
pcs->ns = NULL;
pcs->nc = NULL;
}
}
}
void FreeAndNextS (ConvexInSector*&cs)
{
ConvexInSector* next = cs->ns;
convexInSectorPool.FreePtr(cs);
cs = next;
}
void DelFromSectors ()
{
for (int i=convexes.low(); i<convexes.high(); ++i)
{
for (ConvexInSector* cs = convexes[i].fSector; cs; FreeAndNextS(cs) )
{
ConvexInSector *&nc = PFNC(*cs), *&pc = PFPC(*cs);
nc = cs->pc;
pc = cs->nc;
ConvexInSector *&ns = PFNS(*cs), *&ps = PFPS(*cs);
ns = cs->ps;
ps = cs->ns;
}
assert (convexes[i].fSector==NULL);
assert (convexes[i].lSector==NULL);
}
}
void MovePoints ()
{
for (int i = entityPoints.low(); i<entityPoints.high(); ++i)
static_cast<Point3D&>(entityPoints[i]) = position.RotateP(entityPoints[i].initialP);
for (int i=convexes.low(); i<convexes.high(); ++i)
{
convexes[i].center = center;
convexes[i].center.Trace(position.RotatePNoTr(convexes[i].shift));
}
}
void RegroupTxr ()
{
MovePoints ();
for (int i=convexes.low(); i<convexes.high(); ++i)
{
Convex&c = convexes[i];
c.g.InitNormals();
for (int j = c.g.faces.low(); j<c.g.faces.high(); ++j)
{
Face& f = c.g.faces[j];
EntityPoint
&ep1 = *static_cast<EntityPoint*>(f.points[f.points.low()+0]),
&ep2 = *static_cast<EntityPoint*>(f.points[f.points.low()+1]),
&ep3 = *static_cast<EntityPoint*>(f.points[f.points.low()+2]);
const Point3D
tpx(ep1.tx, ep2.tx, ep3.tx),
tpy(ep1.ty, ep2.ty, ep3.ty),
s12(ep2-ep1),
s13(ep3-ep1);
const float
a11b = Dot(s12,s12),
a12b = Dot(s12,s13),
a22b = Dot(s13,s13),
v = 1.0f / (a11b*a22b-a12b*a12b),
a11 = a11b*v,
a12 = a12b*v,
a22 = a22b*v;
tblib::carray<Point3D, 3> rev;
for (int k=0; k<3; ++k)
rev[k] = Point3D(
s12[k]*(-a22+a12) + s13[k]*(-a11+a12),
s12[k]*(+a22 ) + s13[k]*( -a12),
s12[k]*( -a12) + s13[k]*(+a11 ));
for (int k=0; k<3; ++k)
f.vtx[k] = Dot(rev[k], tpx);
f.vtxc = Dot(ep1, f.vtx) - ep1.tx;
for (int k=0; k<3; ++k)
f.vty[k] = Dot(rev[k], tpy);
f.vtyc = Dot(ep1, f.vty) - ep1.ty;
}
}
}
void Update ();
~Entity() {DelFromSectors(); }
};
|
C
|
const unsigned int Bitime = 104; //9600 Baud, SMCLK=1MHz (1MHz/9600)=104
unsigned char BitCnt; // Bit count, used when transmitting byte
// Function Transmits Character from TXByte
void Transmit()
{
CCTL0 = OUT; // TXD Idle as Mark
TACTL = TASSEL_2 + MC_2; // SMCLK, continuous mode
BitCnt = 0xA; // Load Bit counter, 8 bits + ST/SP
CCR0 = TAR;
CCR0 += Bitime; // Set time till first bit
TXByte |= 0x100; // Add stop bit to TXByte (which is logical 1)
TXByte = TXByte << 1; // Add start bit (which is logical 0)
CCTL0 = CCIS0 + OUTMOD0 + CCIE; // Set signal, intial value, enable interrupts
while ( CCTL0 & CCIE ); // Wait for TX completion
TACTL = TASSEL_2; // SMCLK, timer off (for power consumption)
}
// Timer A0 interrupt service routine
interrupt (TIMERA0_VECTOR) Timer_A (void)
{
CCR0 += Bitime; // Add Offset to CCR0
if ( BitCnt == 0) // If all bits TXed, disable interrupt
CCTL0 &= ~ CCIE ;
else
{
CCTL0 |= OUTMOD2; // TX Space
if (TXByte & 0x01)
CCTL0 &= ~ OUTMOD2; // TX Mark
TXByte = TXByte >> 1;
BitCnt --;
}
}
|
C
|
#include<stdio.h>
#define S 10
void insertion(int *, int);
int main()
{
int n, i, a[S];
printf("Enter the size: ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
insertion(a, n);
printf("The sorted elements: ");
for(i=0; i<n; i++)
printf("%d ", a[i]);
return 0;
}
void insertion(int *a, int n)
{
int i, j, k;
for(i=1; i<n; i++)
{
k = a[i];
for(j = i-1; (j>=0) && (a[j] > k); j--)
{
a[j+1] = a[j];
}
a[j+1] = k;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* readline.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mgolban <mgolban@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/31 11:43:05 by mgolban #+# #+# */
/* Updated: 2017/02/27 12:43:30 by mgolban ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
char *sh_read_line(void)
{
int bufsize;
int position;
char *buffer;
int c;
bufsize = LSH_RL_BUFSIZE;
position = 0;
buffer = (char *)malloc(sizeof(char) * bufsize);
while (1)
{
c = ft_getchar();
if (c == EOF || c == '\n')
{
buffer[position] = '\0';
ft_checkquote(&buffer);
return (buffer);
}
else
buffer[position] = c;
position++;
if (position >= bufsize - 1)
ft_buf_realloc(&buffer, bufsize += LSH_RL_BUFSIZE);
}
}
void ft_buf_realloc(char **buffer, int bufsize)
{
*buffer = (char *)ft_realloc(*buffer, bufsize * sizeof(char));
if (!*buffer)
{
ft_putstr_fd("minishell: ft_realloc error", 2);
exit(EXIT_FAILURE);
}
}
void ft_checkquote(char **buffer)
{
int quote;
int dquote;
int position;
int q;
quote = 0;
dquote = 0;
q = 0;
position = -1;
while ((*buffer)[++position])
{
if (dquote == 0 && (*buffer)[position] == '\'')
quote = (quote + 1) % 2;
if (quote == 0 && (*buffer)[position] == '\"')
dquote = (dquote + 1) % 2;
}
if (quote)
q = '\'';
if (dquote)
q = '\"';
if (q)
{
ft_waitquote(q, buffer, position);
ft_checkquote(buffer);
}
}
void ft_waitquote(int quote, char **buffer, int position)
{
int c;
int bufsize;
(*buffer)[position++] = '\\';
(*buffer)[position++] = 'n';
bufsize = position;
(quote == '\'') ? ft_putstr("quote>") : ft_putstr("dquote>");
while (1)
{
if (position >= bufsize)
ft_buf_realloc(buffer, bufsize += LSH_RL_BUFSIZE);
c = ft_getchar();
if (c == '\n')
{
(*buffer)[position] = '\0';
if (!g_sigint)
{
ft_get_last_cmd(buffer);
g_sigint = 1;
}
return ;
}
(*buffer)[position] = c;
position++;
}
}
void ft_get_last_cmd(char **buffer)
{
char *tofree;
tofree = *buffer;
while (ft_strstr(*buffer, "\\n"))
*buffer = ft_strstr(*buffer, "\\n") + 2;
*buffer = ft_strdup(*buffer);
free(tofree);
}
|
C
|
#include<stdio.h>
#define R 2
#define C 3
void input(char arr[][C])
{
printf("size:%d\n",sizeof(arr)); //4
int i,j;
printf("please input:\n");
for(i=0;i<R;i++)
{
for(j=0;j<C;j++)
{
scanf("%d",&arr[i][j]);
}
printf("\n");
}
}
void output(int arr[][C])
{
int i,j;
for(i=0;i<R;i++)
{
for(j=0;j<C;j++)
{
printf("arr[%d][%d]:%d ",i,j,arr[i][j]);
}
printf("\n");
}
}
int main()
{
int i,j;
int a[R][C];
char string[2][3];
//input(a);
input(string);
output(a);
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int num_visitors[3][7] = {
{50, 10, 14, 7, 25, 30, 70},
{30, 24, 14, 9, 87, 63, 25},
{100, 52, 82, 89, 36, 78, 22}
};
char * day_names[7] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
for(int week_index = 0; week_index < 3; week_index++){ // 有3個星期的資料,因此是0,1,2
// 以下這個printf()屬於外層迴圈
printf("第%d個星期\n", week_index + 1);
for(int day_index = 0; day_index < 7; day_index++){
// 以下這個printf()屬於內層迴圈
printf("%s%d人\n", day_names[day_index], num_visitors[week_index][day_index]);
}
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pf_signed.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abaudot <abaudot@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/28 22:57:37 by abaudot #+# #+# */
/* Updated: 2021/01/28 22:57:39 by abaudot ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static void print(t_prntf *p, const char *num, int len)
{
if (!(p->flags & ZERO && (p->preciz = p->width)))
while (p->width > 0)
{
buffer(" ", (p->width > 10) ? 10 : p->width, 0);
p->width -= 10;
}
if (p->flags & ISNEG)
buffer("-", 1, 0);
else if (p->flags & PLUS)
buffer("+", 1, 0);
else if (p->flags & SPACE)
buffer(" ", 1, 0);
while (p->preciz > 0)
{
buffer("0000000000", (p->preciz > 10) ? 10 : p->preciz, 0);
p->preciz -= 10;
}
buffer(num, len, 0);
}
static void print_minus(t_prntf *p, const char *num, int len)
{
if (p->flags & ISNEG)
buffer("-", 1, 0);
else if (p->flags & PLUS)
buffer("+", 1, 0);
else if (p->flags & SPACE)
buffer(" ", 1, 0);
while (p->preciz > 0)
{
buffer("0000000000", (p->preciz > 10) ? 10 : p->preciz, 0);
p->preciz -= 10;
}
buffer(num, len, 0);
while (p->width > 0)
{
buffer(" ", (p->width > 10) ? 10 : p->width, 0);
p->width -= 10;
}
}
static void itoa_pf(unsigned long long n, t_prntf *p)
{
int i;
int len;
char tmp[21];
i = 21;
if (!n)
tmp[--i] = '0';
while (n)
{
tmp[--i] = '0' + (n % 10);
n /= 10;
}
len = 21 - i;
if (p->flags & PRECIZ)
{
if (!p->preciz && tmp[i] == '0')
len = 0;
p->preciz -= len;
if (p->preciz > 0)
p->width -= p->preciz;
}
p->width -= len;
if (p->flags & MINUS)
return (print_minus(p, tmp + i, len));
print(p, tmp + i, len);
}
void pf_putnbr(t_prntf *p)
{
long long n;
unsigned long long nn;
if (p->flags & PRECIZ)
p->flags &= ~ZERO;
if (p->flags & CHAR)
n = (long long)((char)va_arg(p->ap, int));
else if (p->flags & SHORT)
n = (long long)((short)va_arg(p->ap, int));
else if (p->flags & LONG)
n = (long long)va_arg(p->ap, long);
else if (p->flags & LLONG)
n = va_arg(p->ap, long long);
else
n = (long long)va_arg(p->ap, int);
nn = n;
if (n < 0)
{
nn = n * -1;
p->flags |= ISNEG;
--p->width;
}
else if (p->flags & PLUS || p->flags & SPACE)
--p->width;
itoa_pf(nn, p);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void main(){
int* arr;
int size=7;
// on some systems, malloc will assign garbage values to the array
arr=(int*)malloc(size*sizeof(int));
for(int i=0; i<size; i++){
printf("%d\n", arr[i]);
}
free(arr);
// on some system, calloc will assign 0 to all the values of the array
arr=(int*)calloc(size, sizeof(int));
for(int i=0; i<size; i++){
printf("%d\n", arr[i]);
}
free(arr);
}
// on this system, both malloc and calloc assign 0 to all values of the array
// however, malloc is prefered as it always runs faster than calloc, since it
// assigns garbage values.
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_float2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rbeaufre <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/10 15:20:45 by rbeaufre #+# #+# */
/* Updated: 2019/09/14 17:21:30 by rbeaufre ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_put_extra_zeros(t_data *data, int prec)
{
while (prec > 1)
{
ft_fill_buffer(data, "0", 1);
prec--;
}
}
void ft_putfloat_ext_one(t_data *data, long double db)
{
if (data->zero == 1)
ft_put_sign_float(data, db);
ft_put_space_float(data, db);
ft_put_left_spaces_whole_float(data);
if (data->zero == 0)
ft_put_sign_float(data, db);
}
void ft_putfloat_ext_two(t_data *data, long double db,\
long long nb, int prec)
{
if (prec != -1337)
ft_putlong(nb, data);
if ((data->precision != 0 || (data->precision == 0 &&\
data->sharp == 1)) && prec != -1337)
ft_prec_zero(data, db);
ft_put_right_spaces(data);
}
void ft_prec_zero(t_data *data, long double db)
{
ft_fill_buffer(data, ".", 1);
if (data->precision != 0)
ft_put_dec(data, db);
}
void ft_put_dec(t_data *data, long double db)
{
int prec;
long double db2;
long double db3;
unsigned long long mult;
long double offset;
offset = ((db >= 0) ? 0.4999999999999999999999999 :\
-0.4999999999999999999999999);
mult = 1;
db2 = db - (long long)db;
prec = (int)data->precision;
while ((long long)(db2 * 10 + (offset / 10)) == 0 && prec > 0)
{
ft_fill_buffer(data, "0", 1);
db2 = db2 * 10;
if (prec == 1)
return ;
prec--;
}
while (prec-- > 0)
mult = mult * 10;
db3 = (db2 * mult);
if ((long long)db3 == 0 && prec >= 0)
ft_put_extra_zeros(data, prec);
ft_putlong((long long)(db3 + offset), data);
}
|
C
|
#include<stdio.h> // header file
int main(){
int a,b,c;
printf("Enter 3 no.");
scanf("%d %d %d",a,b,c); // enter 3 no.
if(a>b&&a>c){
printf("A is the greatest");
}
else {
if (b>c)
{
printf("b is the greater");
}
else{
printf("c is the greater");
}
}
return 0;
}
|
C
|
#include "message.h"
void sigHandle(int sigNo);
void listenMsg();
void excuteRequest();
int insertRequest(int floor);
void nextRequest();
void changeRequest();
void sendCurrentfloor();
int requests[MAX_REQUEST], requests_size = 0, current_floor = 1, can_send = 1,
old_begin_floor, old_end_floor;
int main(int argc, char const *argv[]) {
int i;
for (i = 0; i < MAX_REQUEST; i++) {
requests[i] = 0;
}
signal(SIGINT, sigHandle);
listenMsg();
return 0;
}
// Khi an ctrl + c thi tat het tien trinh lien quan toi floor
void sigHandle(int sigNo) {
system("killall ./lift_manager");
return;
}
// Lang nghe yeu cau
void listenMsg() {
int msqid;
msg rcvbuffer;
while(1) {
msqid = msgget(MSG_KEY_M, PERMISSION);
if(msgrcv(msqid, &rcvbuffer, MSG_SIZE, 1, 0) >= 0) {
excuteRequest(rcvbuffer.mtext);
}
}
}
// Thuc hien yeu cau tu ben floor, ctrl
void excuteRequest(char *str) {
if(str[0] == 'f') {
int begin_floor = str[1] - '0';
int end_floor = str[2] - '0';
printf("Receive a request, from FLOOR %d to FLOOR %d\n", begin_floor,
end_floor);
if(!insertRequest(begin_floor * 10 + end_floor)) {
int req_key = str[1] - '0';
msg s;
s.mtype = 1;
s.mtext[0] = 'r';
sendMessage(req_key, s);
}
} else if(str[0] == 'c') {
current_floor = str[1] - '0';
sendCurrentfloor();
if(current_floor == 1) {
printf("Finish the request, from FLOOR %d to FLOOR %d\n",
old_begin_floor, old_end_floor);
can_send = 1;
if(requests_size)
nextRequest();
}
} else {
system("killall ./lift_manager");
}
}
// Chen request vao hang doi
int insertRequest(int floor) {
if(requests_size < MAX_REQUEST) {
requests[requests_size] = floor;
requests_size++;
if(requests_size)
nextRequest();
return 1;
}
return 0;
}
// Thuc hien request tiep theo
void nextRequest() {
if(can_send) {
int num = requests[0];
old_begin_floor = num / 10;
old_end_floor = num % 10;
msg s;
s.mtype = 1;
s.mtext[0] = 'm';
s.mtext[1] = old_begin_floor + '0';
s.mtext[2] = old_end_floor + '0';
s.mtext[3] = '\0';
sendMessage(MSG_KEY_C, s);
changeRequest();
printf("Excuting the request, from FLOOR %d to FLOOR %d\n",
old_begin_floor, old_end_floor);
can_send = 0;
}
}
//Giam hang doi xuong sau khi da xu li
void changeRequest() {
int i;
for (i = 0; i < MAX_REQUEST - 1; i++) {
requests[i] = requests[i + 1];
}
requests[MAX_REQUEST - 1] = 0;
requests_size--;
}
// Gui cho cac tang vi tri thang may hien tai
void sendCurrentfloor() {
msg sndbuffer;
sndbuffer.mtype = 1;
sndbuffer.mtext[0] = 'm';
sndbuffer.mtext[1] = current_floor + '0';
sndbuffer.mtext[2] = '\0';
sendAll(sndbuffer);
}
|
C
|
//Modular or Procedural Programming
int add(int a,int b)
{
int c;
c = a + b;
return c;
}
int main(){
int x,y,z;
x=10;
y=5;
z=add(x,y);
printf("Sum is %d",z);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define SIZE 4000
#define MAX 200
#define R 35
#define ARR 15
typedef struct node {
int adr;
struct node* next;
}node;
typedef struct {
char *name;
node* head;
int value;
}ht;
typedef struct {
int *queue;
int *parent;
int rear;
int front;
}que;
typedef unsigned long long int lint;
void enque(que *q, int x) {
q->queue[q->rear++] = x;
}
int deque(que *q) {
return q->queue[q->front++];
}
node* createNode(int adr) {
node* root = (node*) calloc(1, sizeof(node));
if (root == NULL) {
printf("Yer Acilamadi \n");
}
root->adr = adr;
root->next = NULL;
return root;
}
void createHash(ht* hashTable, lint M) {
int i;
for (i = 0; i < M; i++) {
hashTable[i].name = (char*) calloc(MAX, sizeof(char));
hashTable[i].name[0] = '\0';
hashTable[i].value = 0;
}
}
void createQue(que *q, lint M) {
q->queue = (int*) calloc(M, sizeof(int));
q->parent = (int*) calloc(M, sizeof(int));
q->rear = 0;
q->front = 0;
}
int double_hashing(lint key, int i, lint M) {
int h1 = key % M;
int h2 = 1 + (key % (M - 1));
return (h1 + i * h2) % M;
}
lint find_key(char *str) {
int i = 0;
lint key = 0;
int N = strlen(str);
while (i < N) {
key += str[i] * pow(R, N - i - 1);
i++;
}
return key;
}
int insert_to_table(lint key, char* cursor, ht* hashTable, lint M) {
int adr, i = 0;
int same = 0;
adr = double_hashing(key, i, M);
while( (!same) && (hashTable[adr].name[0] != '\0') && (i < M) ) {
if (strcmp(cursor, hashTable[adr].name) == 0)
same = 1;
else {
i++;
adr = double_hashing(key, i, M);
}
}
if (same) {
return adr;
}
else if (hashTable[adr].name[0] == '\0') {
strcpy(hashTable[adr].name, cursor);
hashTable[adr].head = NULL;
return adr;
}
else if (hashTable[adr].name[0] != '\0') {
printf("Tabloda Bos Yer Bulunamadi \n");
return -1;
}
return -1;
}
void insert_node(ht* hashTable, int adr1, int adr2) {
node* temp_node = createNode(adr2);
node* root;
if (hashTable[adr1].head == NULL) {
hashTable[adr1].head = temp_node;
}
else {
root = hashTable[adr1].head;
while (root->next) {
root = root->next;
}
root->next = temp_node;
}
}
void get_elements(char* line, ht* hashTable, lint M) {
char *cursor, temp1[200], temp2[200];
int i, j, aktor_adr = 0, movie_adr = 0;
lint key = 0;
for (cursor = strtok(line, "/"); cursor != NULL; cursor = strtok(NULL, "/")) {
if (strcmp(cursor, "S\n") == 0) {
continue;
}
i = 0;
while((i < strlen(cursor) && ((cursor[i] < '0') || (cursor[i] > '9')))) {
i++;
}
if (i < strlen(cursor)) {
key = find_key(cursor);
movie_adr = insert_to_table(key, cursor, hashTable, M);
}
else {
i = 0;
while (cursor[i] != ',') {
temp1[i] = cursor[i];
i++;
} temp1[i] = '\0';
i+= 2;
j = 0;
while ( (i < strlen(cursor)) && (cursor[i] != '\n')) {
temp2[j] = cursor[i];
i++;
j++;
} temp2[j] = '\0';
strcat(temp2, " ");
strcat(temp2, temp1);
key = find_key(temp2);
aktor_adr = insert_to_table(key, temp2, hashTable, M);
if (aktor_adr != -1) {
insert_node(hashTable, movie_adr, aktor_adr);
insert_node(hashTable, aktor_adr, movie_adr);
}
}
}
}
int search(char* aktor, ht* hashTable, lint M) {
int i = 0;
while ((i < M) && (strcmp(hashTable[i].name, aktor) != 0)) {
i++;
}
if (i < M)
return i;
else {
printf("%s isimli aktor listede bulunamadi!\n", aktor);
return -1;
}
}
int bfs(que *q, char* aktor1, char* aktor2, ht* hashTable, lint M, int select) {
int i = 0, flag = 0, j = 0, count = 0;
int adr1 = search(aktor1, hashTable, M);
int adr2 = search(aktor2, hashTable, M);
if ((adr1 == -1) || (adr2 == -1))
return;
if(adr1==adr2){
if(select==1)
printf("Kevin Bacon's Kevin Bacon number is 0\n");
return 0;
}
int tmp = adr1;
node* root;
int *path = (int*) calloc(M, sizeof(int));
int* visited = (int*) calloc(M, sizeof(int));
q->front = 0;
q->rear = 0;
q->parent[tmp] = -1;
visited[tmp] = 1;
enque(q, tmp);
while ((!flag) && (q->front < q->rear)) {
tmp = deque(q);
if (hashTable[tmp].head) {
root = hashTable[tmp].head;
while (root) {
if (visited[root->adr] != 1) {
q->parent[root->adr] = tmp;
visited[root->adr] = 1;
enque(q, root->adr);
if (root->adr == adr2) {
flag = 1;
}
}
root = root->next;
}
}
}
if (flag == 1) {
i = adr2;
j = 0;
while (i != adr1) {
path[j++] = i;
i = q->parent[i];
}
path[j] = adr1;
while (j > 0) {
if(select==1)
printf("%s - ", hashTable[path[j]].name);
j = j - 2;
if(select==1){
printf("%s '", hashTable[path[j++]].name);
printf("%s'\n", hashTable[path[j--]].name);
}
count++;
}
if (select==1)
printf("\n%s 's Kevin Bacon Number is %d\n",hashTable[adr2].name, count);
return count;
}
else{
if(select==1)
printf("%s ile Kevin Bacon arasinda Baglantisi Yoktur.\n",aktor2);
return ARR;
}
}
void file_reader(ht* hashTable, lint M, int input)
{
FILE *fp;
char line[SIZE];
switch(input){
case 1:
fp = fopen("input-1.txt", "r");
if (fp == NULL) {
printf("File could not opened !!\n");
return;
}
break;
case 2:
fp = fopen("input-2.txt", "r");
if (fp == NULL) {
printf("File could not opened !!\n");
return;
}
break;
case 3:
fp = fopen("input-3.txt", "r");
if (fp == NULL) {
printf("File could not opened !!\n");
return;
}
break;
}
while ( fgets(line, SIZE - 1, fp) ) {
get_elements(line, hashTable, M);
}
}
void Menu_Yazdir(int input){
system("cls");
printf("...input-%d.txt Dosyasindan Graf Basariyla Olusturuldu...\n",input);
printf("!!!'Firstname Lastname' Seklinde Giriniz -> Ornek input: Kevin Bacon\n\n");
printf("1 - HER KEVIN BACON SAYISINDAKI AKTOR SAYISI \n");
printf("2 - AKTORUN KEVIN BACON BAGLANTISI \n");
printf("3 - EXIT");
}
int main()
{
char aktor1[100], aktor2[100];
lint M=3001;
int bacon_num[ARR]={0};
que q;
int i=0, j=0, flag=1, input, mode;
printf("1 - input-1.txt\n");
printf("2 - input-2.txt\n");
printf("3 - input-3.txt\n");
printf("Acmak istediginiz input dosyasinin numarasini giriniz: ");
scanf("%d",&input);
if(input==2)
M = 8001;
else if(input==3)
M = 323541;
ht* hashTable = (ht*) calloc(M, sizeof(ht));
createHash(hashTable, M);
createQue(&q, M);
file_reader(hashTable, M, input);
Menu_Yazdir(input);
printf("\n***Islem Yapmak Istediginiz Fonksiyonu Seciniz : ");
scanf("%d", &mode);
do {
switch(mode) {
case 1:
Menu_Yazdir(input);
printf("\n\n--- HER KEVIN BACON SAYISINDAKI AKTOR SAYISI ---\n");
strcpy(aktor1, "Kevin Bacon");
for(i = 0; i < M; i++) {
if (hashTable[i].name[0] != '\0') {
j=0;
while(hashTable[i].name[j] != '\0'){
if(hashTable[i].name[j] == '('){
break;
}
j++;
}
if(hashTable[i].name[j] == '\0'){
bacon_num[bfs(&q, aktor1, hashTable[i].name, hashTable, M, 0)]++;
}
}
}
printf("\n");
for(i=0;i<ARR;i++){
if(bacon_num[i]!=0)
printf("Kevin Bacon Sayisi %d olan aktor sayisi: %d\n",i,bacon_num[i]);
}
printf("Kevin Bacon Sayisi Sonsuz olan aktor sayisi: %d\n",bacon_num[ARR]);
for(i=0;i<=ARR;i++)
bacon_num[i]=0;
printf("\n***Islem Yapmak Istediginiz Fonksiyonu Seciniz : ");
scanf("%d", &mode);
break;
case 2:
Menu_Yazdir(input);
printf("\n\n--- AKTORUN KEVIN BACON BAGLANTISI ---\n");
strcpy(aktor1, "Kevin Bacon");
printf("Aktorun Adini ve Soyadini Giriniz: ");
scanf(" %[^\n]s", aktor2);
printf("\n");
int adr = search(aktor2, hashTable, M);
if (adr != -1){
flag=1;
if(hashTable[adr].value!=0){
printf("--- Onceden Aranan Eleman Bulundu ---\n\n");
printf("%s 's Kevin Bacon Number is: %d\n",hashTable[adr].name,hashTable[adr].value);
flag=0;
}
if(flag==1){
hashTable[adr].value = bfs(&q, aktor1, aktor2, hashTable, M, 1);
if(hashTable[adr].value==ARR) hashTable[adr].value=0;
}
}
printf("\n***Islem Yapmak Istediginiz Fonksiyonu Seciniz : ");
scanf("%d", &mode);
break;
}
} while(mode != 3);
printf("Program Sonlandi...");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <memory.h>
#include <time.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <assert.h>
#include "Init.h"
#include "convNum.h"
#include "stringConv.h"
#include "fastpbkdf2.h"
#include "hashFct.h"
void choice1(char* hexInput){
int* tabDec = Init(12);
int* tabBin = Init(132);
int** bin= InitTab(12,11);
char *binC=(char*)malloc(sizeof(char)*132);
char** resultChar = (char**)malloc(12 * sizeof(char*));
for (int i = 0; i < 12; i++) {
resultChar[i] = (char*)malloc(sizeWordMax * sizeof(char));
}
char* stringF = (char*)malloc(sizeof(char)*12*sizeWordMax);
printf("Hex Input: ");
for(unsigned int i=0; i<strlen(hexInput); i++){
printf("%c",hexInput[i]);
}
printf("\n\n");
printf("Convert binary : ");
tabBin = HexToBin(hexInput);
display(tabBin, 128);
printf("\nConvert To String : ");
char *tmp = (char*)malloc(sizeof(char)*2);
for (unsigned int i = 0; i < 128; i++){
sprintf(tmp, "%d", tabBin[i]);
strcat(binC, tmp );
}
printf("%s\n", binC);
printf("\n####hashage####");
unsigned char *d = SHA256(binC, strlen(binC), 0);
char** string = (char**)malloc(sizeof(char*)*32);
for(int i =0; i<32; i++){
string[i] = (char*)malloc(sizeof(char)*4);
}
printf("\nhashage : ");
for (unsigned int i = 0; i < SHA256_DIGEST_LENGTH; i++){
printf("%02x", d[i]);
}
putchar('\n');
for (unsigned int i = 0; i < SHA256_DIGEST_LENGTH; i++){
sprintf(string[i],"%x",d[i]);
}
int* h = (int*)malloc(sizeof(int)*4);
printf("\nConvert the first Hex carac : ");
h=HexToBinC(string[0][0]);
printf("\n");
display(h,4);
printf("\nChecksum :");
cpyTab(&tabBin[128], h,4);
display(tabBin, 132);
printf("\nSplit in 11 parts:\n");
split(bin,tabBin,12,11);
displayBin(bin,12,11);
binArrayToDecArray(bin,12,11,tabDec);
printf("\nDecimal Array: ");
display(tabDec, 12);
printf("\n");
resultChar = findWord(tabDec,"wordlist.txt", resultChar);
conv(resultChar, stringF);
Seed(stringF,strlen(string),"mnemonic",8,1,64);
}
void choice2(char* binInput){
int* tabDec = Init(12);
int* tabBin = Init(132);
int** bin= InitTab(12,11);
char *binC=(char*)malloc(sizeof(char)*132);
char** resultChar = (char**)malloc(12 * sizeof(char*));
for (int i = 0; i < 12; i++) {
resultChar[i] = (char*)malloc(sizeWordMax * sizeof(char));
}
char* stringF = (char*)malloc(sizeof(char)*12*sizeWordMax);
printf("Bin Input: ");
for(unsigned int i=0; i<strlen(binInput); i++){
printf("%c",binInput[i]);
}
printf("\n");
binStringToInt(binInput,tabBin);
display(tabBin, 128);
strcpy(binC, binInput);
printf("\n####hashage####");
unsigned char *d = SHA256(binC, strlen(binC), 0);
char** string = (char**)malloc(sizeof(char*)*32);
for(int i =0; i<32; i++){
string[i] = (char*)malloc(sizeof(char)*4);
}
printf("\nhashage : ");
for (unsigned int i = 0; i < SHA256_DIGEST_LENGTH; i++){
printf("%02x", d[i]);
}
putchar('\n');
for (unsigned int i = 0; i < SHA256_DIGEST_LENGTH; i++){
sprintf(string[i],"%x",d[i]);
}
int* h = (int*)malloc(sizeof(int)*4);
printf("\nConvert the first Hex carac : ");
h=HexToBinC(string[0][0]);
printf("\n");
display(h,4);
printf("\nChecksum :");
cpyTab(&tabBin[128], h,4);
display(tabBin, 132);
printf("\nSplit in 11 parts:\n");
split(bin,tabBin,12,11);
displayBin(bin,12,11);
binArrayToDecArray(bin,12,11,tabDec);
printf("\nDecimal Array: ");
display(tabDec, 12);
printf("\n");
resultChar = findWord(tabDec,"wordlist.txt", resultChar);
conv(resultChar, stringF);
Seed(stringF,strlen(string),"mnemonic",8,1,64);
}
void choice3(char ** mnemonic){
int ** binArray = InitTab(12,11);
int ** hexArray = InitTab(32,4);
int * decArray = Init(12);
int *bin=Init(132);
int *hexBin=Init(128);
decArray = StringToInt("wordlist.txt",mnemonic,decArray);
printf("\nDisplay dec : ");
display(decArray, 12);
printf("\nConvert to Bin :");
decArrayToBinArray(decArray,12,binArray);
displayBin(binArray, 12, 11);
printf("\n\nDisplay Row :");
unsplit(bin, binArray, 12);
printf("\n\nRemove last 4 bits : ");
cpyTab(hexBin,bin,128);
display(hexBin,128);
printf("\n\nSplit in 32 parts : ");
split(hexArray,hexBin,32,4);
displayBin(hexArray,32,4);
printf("\n\nConvert To Hex : ");
binToHex(hexBin,128);
}
void choice4(char** mnemonic, char* seedInput){
char* seed = (char*)malloc(sizeof(char)*strlen(seedInput));
conv(mnemonic,seed);
printf("mnemonic ");
Seed(seed, strlen(seed), "mnemonic", 8, 1 ,64);
printf("cmp : %d", strcmp(seedInput,seed));
if(strcmp(seedInput,seed) == 0){printf("\nOK");}
else{printf("\nNOT OK");}
}
|
C
|
#include "ush.h"
/*
* Splits string (arg) in array {NAME,VALUE}
* Splits by equal sign.
*/
char **mx_splitter(char *arg) {
char **arr = mx_new_strarr(2);
int index_eq_sign = mx_char_index(arg, '=');
// If no '=' in arg or '=' is last element
// Case: export a= || export a
if (index_eq_sign == -1) {
arr[0] = mx_string_copy(arg);
arr[1] = mx_strnew(1);
}
else if (arg[mx_strlen(arg) - 1] == '=') {
arr[0] = mx_substr_retriever(arg, 0, mx_strlen(arg) - 2);
arr[1] = mx_strnew(1);
}
else {
arr[0] = mx_substr_retriever(arg, 0, index_eq_sign - 1);
arr[1] = mx_substr_retriever(arg, index_eq_sign+1, mx_strlen(arg) - 1);
}
return arr;
}
|
C
|
/************************************************************************
Author: Eyal Noy
Creation date: 11.11.12
Last modified date: 13.11.12
Description: my malloc implementation memmory management insert and remove
Text Editor: gVim
***********************************************************************/
/* standard libaries */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
/*local libaries*/
/*initilize the memmory, allign the memmory to a word clussters the first word is memmory size
last word is zero value stub to end memmory */
void MyMallocInit(void * _memBlock,int _nBytes)
{
/* allign memmory up by a word*/
int nBytes=_nBytes + -(_nBytes%sizeof(int));
#ifdef DEBUG
printf("initilize size byte after initilzation = %d\n",(int)(nBytes - 2*sizeof(int)));
#endif
/*insert the size to the first word*/
*(int*)(_memBlock) = _nBytes;
/*the avilable memmory after decrease the first word and last word*/
*((int*)(_memBlock)+sizeof(int)) = nBytes - 2*sizeof(int) ;
/*memmory initilize stub*/
*((int*)(_memBlock) + nBytes-sizeof(int)) =0;
}
/*allocate a new chunk if avilable*/
void* MyMalloc(void* _memBlock,int _nBytes)
{
/*the first position*/
int* pos= (int*)_memBlock +sizeof(int) ;
/*allign the requested bytes up to a word*/
int nBytes;
assert(_memBlock);
assert(_nBytes > 0);
if (_nBytes%sizeof(int))
{
nBytes=_nBytes + sizeof(int)-(_nBytes%sizeof(int));
}
else
{
nBytes=_nBytes;
}
#ifdef DEBUG
printf("bytes to write = %d\n",nBytes);
#endif
/*boundry check all memmory smaller than requested*/
if (*(int*)_memBlock <nBytes)
{
return NULL;
}
/*searchs for the first avilable memmory until reached stub*/
while(*pos != 0)
{
#ifdef DEBUG
printf("status before insert %d\n",*pos);
#endif
/*value positive means free*/
if(*pos > 0 )
{
/*check is there is enough memmory to insert*/
if (*pos - sizeof(int) > nBytes )
{
/*update the next jump*/
*(pos + nBytes/sizeof(int) +sizeof(int))= *pos -(sizeof(int)+ nBytes);
/*update the current position to occuppied*/
*pos = -(nBytes+sizeof(int));
#ifdef DEBUG
printf("status after insert %d\n\n",*pos);
#endif
/*return address of the allocated position*/
return (void*)(pos );
}
}
/*next address to search if occuppied or not enough memmory */
pos += abs(*pos);
}
#ifdef DEBUG
puts("End of memmory\n");
#endif
return NULL;
}
/*free the memmory only to a valid pointer defrag if there free memmory after the current memmory*/
void MyFree(void* _currAlloc)
{
/*word size*/
int* pos= (int*)_currAlloc;
/*counts how much to defrag*/
int counter=0;
assert(_currAlloc);
/*cant free 0*/
if (!*pos)
{
return ;
}
/*free allready*/
if (*pos>0)
{
return ;
}
/*changes to positive value means free*/
*pos*=-1;
/*counts chunks until memmory is occupied or reached end*/
while( *(pos+counter/sizeof(int))>0 )
{
counter+=*(pos+counter/sizeof(int));
}
/*updates after defragment*/
*pos=counter;
#ifdef DEBUG
printf("status after free %d\n",*pos);
#endif
return ;
}
|
C
|
/* Nama/ NIM : Dharma Kurnia Septialoka/ 13514028
* Nama file : queue.h
* Topik : ADT QUEUE
* Tanggal : 3 November 2015
* Deskripsi : List linier queue
*/
#ifndef QUEUE_H
#define QUEUE_H
#include "boolean.h"
#include <stdio.h>
#include <stdlib.h>
/* Modul Queue
Direpresentasikan dengan list linier, secara fisik dengan pointer
Queue direpresentasikan sebagai list dengan first dan last
Definisi Queue kosong: head dan tail adalah Nil
*/
#define Nil NULL
/* Definisi Type Queue */
typedef int Infotype;
typedef struct tElmtQueue *Address;
typedef struct tElmtQueue {
Infotype info;
Address next;
} ElmtQueue;
typedef struct {
Address head;
Address tail;
} Queue;
//selektor
#define Head(Q) (Q).head
#define Tail(Q) (Q).tail
#define Info(Q) (Q)->info
#define Next(Q) (Q)->next
#define InfoHead(Q) Info(Head(Q))
/** Konstruktor/Kreator **/
void CreateEmpty (Queue *Q);
/* I.S. sembarang
F.S. Sebuah Q kosong terbentuk
*/
/* Prototype manajemen memori */
void Alokasi (Address *P, Infotype X);
/* I.S. P sembarang, X terdefinisi
F.S. Alamat P dialokasi, jika berhasil maka Info(P) = X dan Next(P) = Nil
P = Nil jika alokasi gagal
*/
void Dealokasi (Address *P);
/* I.S. P adalah hasil alokasi, P <> Nil
F.S. Alamat P didealokasi, dikembalikan ke sistem
*/
/* Predikat Pemeriksaan Kondisi Queue */
boolean IsEmpty (Queue Q);
/* Mengirim true jika Q kosong: HEAD(Q) = Nil and TAIL(Q) = Nil */
int NbElmt (Queue Q);
/* Mengirimkan banyaknya elemen queue. Mengirimkan 0 jika Q kosong. */
/*** Primitif Add/Delete **/
void Add (Queue *Q, Infotype X);
/* Proses : Mengalokasi X dan menambahkan X pada bagian TAIL dari Q jika alokasi
berhasil; jika alokasi gagal Q tetap
I.S. Q mungkin kosong
F.S. X menjadi TAIL, TAIL "maju"
*/
void Del (Queue *Q, Infotype *X);
/* Proses : Menghapus X pada bagian HEAD dari Q dan mendealokasi elemen HEAD
I.S. Q tidak mungkin kosong
F.S. X = nilai elemen HEAD pd I.S., HEAD "mundur"
*/
#endif
|
C
|
//
//
//
// Created by NAMAN GARG on 10/20/20.
//
#include <openssl/aes.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <assert.h>
extern int OPENSSL_cleanse(void *ptr, size_t len);
u_int32_t OPENSSL_ia32cap_P[4] = { 0 };
unsigned char const_Rb[16] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87
};
static void xor_block(unsigned char *a, unsigned char *b, unsigned char *out)
{
int i;
for (i=0;i<16; i++)
{
out[i] = a[i] ^ b[i];
}
}
char *substring(char *string, int position, int length)
{
char *p;
int c;
p = malloc(length+1);
if (p == NULL)
{
printf("Unable to allocate memory.\n");
exit(1);
}
for (c = 0; c < length; c++)
{
*(p+c) = *(string+position-1);
string++;
}
*(p+c) = '\0';
return p;
}
//prints the ouput in form of 128 bits
static void print128(unsigned char *bytes)
{
int j;
for (j=0; j<16;j++) {
printf("%02x",bytes[j]);
if ( (j%4) == 3 ) printf(" ");
}
}
// removes white space between strings
void remove_spaces (unsigned char* str_trim, const unsigned char* str_untrim)
{
while (*str_untrim != '\0')
{
if(!isspace(*str_untrim))
{
*str_trim = *str_untrim;
str_trim++;
}
str_untrim++;
}
*str_trim = '\0';
}
//generate byte array of hex from hex string
int hex2data(unsigned char *bytearray, unsigned char *hexstring, int length)
{
for (int i = 0; i < (length/2); i++) {
sscanf((char *)hexstring + 2*i, "%02x",(unsigned int*) &bytearray[i]);
}
return 0;
}
/* AES-CMAC Generation Function */
void shift_left(unsigned char *in ,unsigned char *out)
{
int i;
unsigned char overflow = 0;
for ( i=15; i>=0; i-- ) {
out[i] = in[i] << 1;
out[i] |= overflow;
overflow = (in[i] & 0x80)?1:0;
}
}
void generateSubkeys(AES_KEY AESkey, unsigned char *K1, unsigned char *K2)
{
unsigned char keystream_block[16];
unsigned char Zero_Array[16];
unsigned char tmp[16];
int i;
for ( i=0; i<16; i++ ) Zero_Array[i] = 0;
AES_encrypt(Zero_Array, keystream_block, &AESkey);
if ( (keystream_block[0] & 0x80) == 0 ) { /* If MostSignificantBit(L) = 0, then K1 = Lkeystream_block << 1 */
shift_left(keystream_block,K1);
} else { /* Else K1 = ( Lkeystream_block << 1 ) (+) Rb */
shift_left(keystream_block,tmp);
xor_block(tmp,const_Rb,K1);
}
if ( (K1[0] & 0x80) == 0 ) {
shift_left(K1,K2);
} else {
shift_left(K1,tmp);
xor_block(tmp,const_Rb,K2);
}
}
void padding ( unsigned char *dataBlock, unsigned char *pad, int length )
{
int j;
/* original last block */
for ( j=0; j<16; j++ ) {
if ( (j+1)*8 < length)
{
pad[j] = dataBlock[j];
}
else if ((j+1)*8 > length && j*8 < length)
{
pad[j] = dataBlock[j];
pad[j] |= (unsigned char)(1<<((j+1)*8 - length - 1));
}
else if ( (j+1)*8 == length )
{
pad[j] = dataBlock[j];
j++;
pad[j] = 0x80;
}
else if( (j+1)*8 > length )
{
pad[j] = 0x00;
}
}
}
void cmac_generate( unsigned char *key, unsigned char *dataIn, int length, unsigned char *mac, int rem)
{
unsigned char cipher_block[16],message[16], last_message[16], padded[16];
unsigned char K1[16], K2[16];
int n, i, last_block;
AES_KEY AESkey;
AES_set_encrypt_key(key, 128, &AESkey);
generateSubkeys(AESkey,K1,K2);
n = (length+15) / 16; /* n is number of rounds */
if ( n == 0 ) {
n = 1;
last_block = 0;
} else {
if ( (length%16) == 0 && rem == 0) { /* last block is a complete block */
last_block = 1;
} else { /* last block is not complete block */
last_block = 0;
}
}
if ( last_block ) { /* last block is complete block */
xor_block(&dataIn[16*(n-1)],K1,last_message);
} else {
padding(&dataIn[16*(n-1)],padded,rem);
xor_block(padded,K2,last_message);
}
for ( i=0; i<16; i++ ) cipher_block[i] = 0;
for ( i=0; i<n-1; i++ ) {
xor_block(cipher_block,&dataIn[16*i],message); /* message := Mi (+) cipher_block */
/* cipher_block := AES(KEY, message); */
AES_encrypt(message, cipher_block, &AESkey);
}
xor_block(cipher_block,last_message,message);
AES_encrypt(message, cipher_block, &AESkey); // generate keystream for the last block
for ( i=0; i<4; i++ ) {
mac[i] = cipher_block[i];
}
}
void cmac_eia2(unsigned char *key, int count, int bearer, int dir, unsigned char *data, int length, unsigned char *outMac)
{
int BLENGTH = (length+64+7)/8;
int rem = (length+64)%128;
int i = 0, j = 0;
unsigned char * MessageBlock;
MessageBlock = (unsigned char*)malloc(BLENGTH);
/* from count & bearer & dir & data generate M*/
for(i=0;i<BLENGTH;i++)
{
if (i<4)//count
{
MessageBlock[i] = (unsigned char)(count>>(8*(3-i)));
}
else if (i == 4)//bearer+dir
{
MessageBlock[i] = ((unsigned char)bearer<<3) | ((unsigned char)dir<<2);
}
else if(i < 8)//0x00
{
MessageBlock[i] = 0;
}
else
{
MessageBlock[i] = data[j];
j++;
}
}
cmac_generate(key,MessageBlock,BLENGTH,outMac,rem);
printf("LAST CIPHERTEXT BLOCK : ");
print128(outMac);
printf("\n");
printf("MAC: ");
for(int i=0; i<4; i++) printf("%02x",outMac[i]);
printf("\n");
free(MessageBlock);
}
int main(int argc, char* argv[1]){
if (argc != 2)
{
printf( "Usage: ./Integrity_check input_file.txt \n" );
return 0;
}
FILE* fp;
fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("Failed: ");
return 1;
}
int i =0;
int MAX_LEN = 2048;
char ln[6][MAX_LEN];
// -1 to allow room for NULL terminator for really long string
while (fgets(ln[i], sizeof(ln[i]), fp)) i++; // get lines from input file
char* count = substring(ln[0], 11, strlen(ln[0]));
unsigned int COUNT;
if(( unsigned int) sscanf(count, "%x", &COUNT)==0)
printf("String Count %x ", COUNT);
char * Bearer = (char *)substring(ln[1], 10, strlen(ln[1]));
unsigned int BEARER;
int y =(unsigned int) sscanf(Bearer, "%x", &BEARER);
unsigned int DIRECTION = atoi(substring(ln[2], 13, strlen(ln[2])));
const unsigned char* enc_key = (const unsigned char *)substring(ln[3], 6, strlen(ln[3]));
int length = (int)atoi(substring(ln[4], 10, strlen(ln[4])));
unsigned char * message = (unsigned char *)substring(ln[5], 11, strlen(ln[5]));
fclose(fp);
int newLength = (length+3)/4;
unsigned char newData[newLength];
remove_spaces(newData, message);
unsigned char dataIn[newLength];
hex2data(dataIn, newData, (length+3)/4);
unsigned char dataOut[128];
unsigned char newKey[16];
remove_spaces(newKey, enc_key);
unsigned char key[16];
hex2data(key, newKey,strlen((char*)newKey));
cmac_eia2(key, COUNT, BEARER, DIRECTION, dataIn, length, dataOut);
return 0;
}
|
C
|
#include <stdio.h>
void main()
{
int rec[10][10];
int att = 0, cls = 0;
int name = "Ram"; //Error in structure
flat rat; //Misspelled keywords
while(cls <= 40)
{
cls++;
rec[cls][0]] = 0; //Unbalanced paranthesis
rat = (float)att / cls * 100;
if(rat < 80)
{
att+; //Missing operator
rec[cls] = 1;
}
}; //Error in structure
cls = 0;
while(cls <= 40)
{
printf("%d - ", rec[cls]);
cls++;
}
}
|
C
|
#include "c01/ex00/ft_ft.c"
#include "c01/ex07/ft_rev_int_tab.c"
#include "c01/ex08/ft_sort_int_tab.c"
#include <stdio.h>
int main()
{
/*
* ft_rev
int i = 0;
int size = 15;
int str[15] = {1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15};
ft_rev_int_tab(str, size);
while(i < size)
{
printf("rev tab 1 = %d\n", str[i]);
i++;
}
*/
/*
* ft_ft
int b = 10;
int *pb = &b;
ft_ft(pb);
printf("Pointeur = %d", *pb);
return(0);
*/
int i = 0;
int size = 13;
int str[13] = {10, 255, 3, -10, 0, -1564, 50, 87, 89, 78, 5, 34, 100};
ft_sort_int_tab(str, size);
while(i < size)
{
printf("sort tab = %d\n", str[i]);
i++;
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main ()
{
// clescr();
float a, b, sum, avg;
printf("write any two numbers");
scanf("%f%f", &a, &b);
sum = a+b;
avg = (a+b)/2;
printf("sum = %f", sum);
printf("average = %f", avg);
getch();
}
|
C
|
#include "killzone.h"
static Killzone *killzoneHead = NULL;
const SDL_Color killzoneColor = {155, 0, 155, 255};
void initKillzone(Entity where)
{
where.color = killzoneColor;
Killzone *newKillzone = malloc(sizeof(Killzone));
newKillzone->structure = where;
newKillzone->next = killzoneHead;
killzoneHead = newKillzone;
}
void drawKillzones()
{
for (Killzone *pointer = killzoneHead; pointer != NULL; pointer = pointer->next)
{
drawEntity(pointer->structure);
}
}
bool checkKillzoneCollision(Entity *object)
{
for (Killzone *pointer = killzoneHead; pointer != NULL; pointer = pointer->next)
{
if (checkCollision(pointer->structure, *object))
{
return true;
}
}
return false;
}
void freeAllKillzones()
{
Killzone *tmp;
while (killzoneHead != NULL)
{
tmp = killzoneHead;
killzoneHead = killzoneHead->next;
free(tmp);
}
}
|
C
|
#include<stdio.h>
main()
{
int arr[]={1,2,3,4,5,12,7,8,9,10};
int i,j;
int num=;
int sum=0,kum=0;
for(i=0;i<10;i++)
{
if(arr[i]==num){
printf("%d",arr[i]);
printf("\n%d is index ",i+1);
break;
}
}
for(i=0;i<10;i++)
{
if(arr[i] != num )
{
sum = sum+i+1;}
}
for(i=0;i<10;i++)
{
kum=kum+i+1;
}
if(sum == kum)
printf("\n%d is not in array ",num);
getch();
}
|
C
|
#include <stdio.h>
#include <string.h>
void trof_pripew(char *a1)
{
char *s; // [rsp+8h] [rbp-18h]
char *i; // [rsp+18h] [rbp-8h]
s = (char *)a1;
if ( a1 )
{
for ( i = (char *)&a1[strlen(a1) - 1]; s < i; --i )
{
*s ^= *i;
*i ^= *s;
*s++ ^= *i;
}
}
}
int main(int argc, char const *argv[])
{
char tmp[100] = {0};
int x;
scanf("%d", &x);
sprintf(tmp, "%o", x);
trof_pripew(tmp);
printf("%s", tmp);
return 0;
}
|
C
|
#include "header.h"
void min_max(int data[], int jumlah_data, int *min, int *max){
int i;
*min=data[0];
*max=data[0];
for(i=0;i<jumlah_data;i++){
if(*max<data[i]){
*max=data[i];
}
else if(*min>data[i]){
*min=data[i];
}
}
}
int min_max_gap(int data[], int jumlah_data){
int min,max;
min_max(data,jumlah_data,&min,&max);
return max-min;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "timedate.h"
#include "tools.h"
#include "datastructure.h"
#include "escapesequenzen.h"
TTime *addTime(TTime start, TTime * Duration)
{
TTime * endTime = calloc( 1, sizeof( TTime ));
if( !endTime )
return NULL;
int checkTime = 0,
endH = start.Hour,
endM = start.Minute,
endS = start.Second;
if( Duration )
{
endS += Duration->Second;
endM += Duration->Minute;
endH += Duration->Hour;
}
if( endS >= 60 )
{
endM ++;
endS = endS - 60;
}
if( endM >= 60 )
{
endH ++;
endM = endM - 60;
}
if( endH >= 24 )
endH = endH - 24;
if( ((endS < 60) && (endS >=0) ) && ((endM < 60) && (endM >= 0)) && ((endH < 24) && (endH >= 0)) )
checkTime = 1;
if( checkTime )
{
endTime->Hour = endH;
endTime->Minute = endM;
endTime->Second = endS;
return endTime;
}
else
return NULL;
return NULL;
}
int getDayOfWeek(TDate dateStruct)
{
int y = dateStruct.Year;
int m = dateStruct.Month;
int d = dateStruct.Day;
if (m < 3)
y = y - 1;
int w = (int)((d + (int)floor(2.6 * ((m + 9) % 12 + 1) - 0.2) + y % 100 + (int)floor(y % 100 / 4) + (int)floor(y / 400) - 2 * (int)floor(y / 100) - 1) % 7 + 7) % 7 + 1;
return w;
}
int isLeapYear(TDate * date)
{
if(date->Year % 400 == 0)
return 1;
else if(date->Year % 100 == 0)
return 0;
else if(date->Year % 4 == 0)
return 1;
else
return 0;
}
int checkthirty(TDate * date)
{
if((date->Day < 31) && (date->Day > 0))
return 1;
else
return 0;
}
int ckeckthirtyone(TDate * date)
{
if((date->Day < 32) && (date->Day > 0))
return 1;
else
return 0;
}
int checkfebr(TDate * date)
{
int leapyear = isLeapYear(date);
if(leapyear == 0)
{
if((date->Day < 29) && (date->Day > 0))
return 1;
else
return 0;
}
else if(leapyear == 1)
{
if((date->Day < 30) && (date->Day > 0))
return 1;
else
return 0;
}
else
return 0;
}
int isDateValid(TDate * date)
{
int valid = 0;
switch(date->Month)
{
case 4:
case 6:
case 9:
case 11: valid = checkthirty(date);
break;
case 2: valid = checkfebr(date);
break;
default: valid = ckeckthirtyone(date);
}
return valid;
}
int isTimeValid(TTime * time)
{
int validhour = 0,
validminute = 0,
validsecond = 0;
if((time->Hour < 24) && (time->Hour >= 0))
validhour = 1;
if((time->Minute < 60) && (time->Minute >= 0))
validminute = 1;
if((time->Second < 60) && (time->Second >= 0))
validsecond = 1;
if((validhour == 1) && (validminute == 1) && (validsecond == 1))
return 1;
else
return 0;
}
int getDateFromString(char *Input, TDate *date)
{
TDate tmpDate;
char * day = Input;
char * month = NULL;
char * year = NULL;
int valid = 0,
i = 0;
while((*(Input+i) != '.') && (*(Input+i) != '\0'))
i++;
month = Input+ ++i;
while((*(Input+i) != '.') && (*(Input+i) != '\0'))
i++;
year = Input+ ++i;
tmpDate.Day = atoi(day);
tmpDate.Month = atoi(month);
tmpDate.Year = atoi(year);
if((tmpDate.Month < 1) || (tmpDate.Month > 12))
return 0;
if(isDateValid(&tmpDate))
{
date->Day = tmpDate.Day;
date->Month = tmpDate.Month;
date->Year = tmpDate.Year;
date->weekDay = getDayOfWeek(tmpDate);
valid = 1;
}
else
valid = 0;
return valid;
}
int getTimeFromString(char *Input, TTime *time)
{
TTime tmpTime;
char * hour = Input;
char * minute = NULL;
char * second = NULL;
int valid = 0,
i = 0;
if( time == NULL)
return 0;
while((*(Input+i) != ':') && (*(Input+i) != '\0'))
i++;
minute = Input+ ++i;
if(*minute == '\0')
return 0;
while((*(Input+i) != ':') && (*(Input+i) != '\0'))
i++;
second = Input+ ++i;
tmpTime.Hour = atoi(hour);
tmpTime.Minute = atoi(minute);
tmpTime.Second = atoi(second);
if(isTimeValid(&tmpTime))
{
time->Hour = tmpTime.Hour;
time->Minute = tmpTime.Minute;
time->Second = tmpTime.Second;
valid = 1;
}
else
valid = 0;
return valid;
}
int getDate(char * text, TDate * dateStruct)
{
int valid = 0;
char * input = NULL;
getText(text, 10, &input, 0);
valid = getDateFromString(input, dateStruct);
free(input);
return valid;
}
int getTime(char * text, TTime * timeStruct, int Leer)
{
int valid = 0;
char * input = NULL;
getText(text, 10, &input, Leer);
if (input != NULL)
valid = getTimeFromString(input, timeStruct);
else
valid = 1;
free(input);
return valid;
}
void printDate(TDate dateStruct)
{
char * tmpday[] = {"NotADay", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"};
printf("%s, %02d.%02d.%04d:\n", tmpday[dateStruct.weekDay], dateStruct.Day, dateStruct.Month, dateStruct.Year);
printLine('-', 15);
}
void printTime(TTime timeStruct, TTime * Duration)
{
TTime * endTime = addTime(timeStruct, Duration);
if( !endTime )
{
perror("endTime fail.");
return;
}
if( (timeStruct.Hour == endTime->Hour) && (timeStruct.Minute == endTime->Minute) && (timeStruct.Second == endTime->Second))
printf("%02d:%02d -> ", timeStruct.Hour, timeStruct.Minute);
else
printf("%02d:%02d - %02d:%02d -> ", timeStruct.Hour, timeStruct.Minute, endTime->Hour, endTime->Minute);
free(endTime);
}
|
C
|
#include <stdio.h>
int main(void)
{
printf("%d", 15 + 37 );
printf("%d", 15 - 37 );
printf("15と37の和は%dです", 15 + 37 );
printf("15と37の差は%dです\a\a\a\n\n\n", 15 - 37);
printf("天\n地\n人\n");
int vx = 57;
int vy = vx + 10;
printf("vxの値は%dです\n", vx);
printf("vyの値は%dです\n", vy);
int xx = 3.14;
int yy = 5.7;
printf("%d\n", xx);
printf("%d\n", yy);
int no;
printf("整数値を入力して下さい:");
scanf("%d", &no);
printf("その数の五倍は%dです\n", 5 * no);
int nn;
printf("整数値を入力してください:");
scanf("%d" , &nn);
printf("その数に12足した数は%dです\n", nn + 12 );
printf("その数から6引いた数は%d です\n", nn - 6 );
int n1, n2;
int wa; /* 和*/
puts("二つの整数を入力してください");
printf("整数1:"); scanf("%d", &n1);
printf("整数2:"); scanf("%d", &n2);
wa = n1 + n2;
printf("それらの和は%dです \n", wa);
puts("天");
puts("地");
puts("人");
int n3, n4;
puts("二つの整数を入力してください");
printf("整数:"); scanf("%d", &n3);
printf("整数:"); scanf("%d", &n4);
printf("それらの積は%dです\n",n3 * n4);
int n5, n6, n7;
puts("三つの整数を入力してください");
printf("整数1:"); scanf("%d", &n5);
printf("整数2:"); scanf("%d", &n6);
printf("整数3:"); scanf("%d", &n7);
printf("それらの合計は%dです\n",n5 + n6 + n7);
return 0;
}
|
C
|
#include<stdio.h>
#include "../list.h"
void green(){
printf("\033[1;30m");
}
void red(){
printf("\033[0;31m");
}
void white(){
printf("\033[1;0m");
}
void print_result(int passed,char *message){
if(passed){
green();
printf(" ✔ %s\n",message);
}else{
red();
printf(" ✘ %s\n",message);
}
white();
}
void test_add_to_end(){
printf("\nadd_to_end\n");
List_ptr list = create_list();
Status status = add_to_end(list,2);
char message[] = "should add given number in list at end, increment count and return 1";
int passed = status == 1 && list->count == 1 && list->last->value == 2;
print_result(passed,message);
}
void test_add_to_start(){
printf("\nadd_to_start\n");
List_ptr list = create_list();
Status status = add_to_start(list,2);
char message[] = "should add given number in list at begining, increment count and return 1";
int passed = status == 1 && list->count == 1 && list->head->value == 2;
print_result(passed,message);
destroy_list(list);
}
void test_insert_at(){
printf("\ninsert_at\n");
List_ptr list = create_list();
add_to_end(list,2);
add_to_end(list,3);
add_to_end(list,6);
Status status = insert_at(list,4,2 );
char message[] = "should insert given number at given position in list and return 1";
int passed = status == 1 && list->count == 4 && is_num_on_position(list,4,2)==1;
print_result(passed,message);
destroy_list(list);
}
void test_search(){
printf("\nsearch\n");
List_ptr list = create_list();
add_to_end(list,2);
add_to_end(list,3);
add_to_end(list,4);
int status = search(list, 3);
char message[] = "should return the index of element if exists";
int passed = status == 1;
print_result(passed,message);
char message2[] = "should return the -1 if element does not exists";
int status2 = search(list,99);
int passed2 = status2 == -1;
print_result(passed2,message2);
destroy_list(list);
}
void test_add_unique(){
printf("\nadd_unique\n");
List_ptr list = create_list();
add_to_end(list,2);
Status status = add_unique(list,99);
char message[] = "should add a unique item on the list at the end";
int passed = status == 1 && list->count == 2 && list->last->value == 99;
print_result(passed,message);
Status status2 = add_unique(list,2);
char message2[] = "should not add item if it is not unique";
int passed2 = status2 == 0 && list->count == 2;
print_result(passed2,message2);
destroy_list(list);
}
void test_remove_from_start(){
printf("\nremove_from_start\n");
List_ptr list = create_list();
add_to_end(list,1);
add_to_end(list,2);
Status status = remove_from_start(list);
char message[] = "should remove a number from the beginning of the list";
int passed = status == 1 && list->count == 1 && list->head->value == 2;
print_result(passed,message);
destroy_list(list);
List_ptr list2 = create_list();
Status status2 = remove_from_start(list2);
char message2[] = "should not remove a number from the beginning of the list";
int passed2 = status2 == 0 && list->count == 0 && list->head==NULL;
print_result(passed2,message2);
destroy_list(list2);
}
void test_remove_from_end(){
printf("\nremove_from_end\n");
List_ptr list = create_list();
add_to_end(list,1);
add_to_end(list,2);
Status status = remove_from_end(list);
char message[] = "should remove a number from the end of the list";
int passed = status == 1 && list->count == 1 && list->last->value == 1;
print_result(passed,message);
destroy_list(list);
List_ptr list2 = create_list();
Status status2 = remove_from_end(list2);
char message2[] = "should not remove a number from the end of the list";
int passed2 = status2 == 0 && list->count == 0 && list->last==NULL;
print_result(passed2,message2);
destroy_list(list2);
}
void test_remove_at(){
printf("\nremove_at\n");
List_ptr list = create_list();
add_to_end(list,1);
add_to_end(list,2);
Status status = remove_at(list,1);
char message[] = "should remove a number from given position in list";
int passed = status == 1 && list->count == 1;
print_result(passed,message);
destroy_list(list);
List_ptr list2 = create_list();
int count = list->count;
Status status2 = remove_at(list2,99);
char message2[] = "should not remove if position is invalid";
int passed2 = status2 == 0 && count == list->count;
print_result(passed2,message2);
destroy_list(list2);
}
void test_remove_first_occurrence(){
printf("\nremove_first_occurrence\n");
List_ptr list = create_list();
add_to_end(list,1);
add_to_end(list,1);
add_to_end(list,2);
int count = list->count;
Status status = remove_first_occurrence(list,1);
char message[] = "should remove a first occurrence of given number from list";
int passed = status == 1 && list->count == count - 1;
print_result(passed,message);
destroy_list(list);
List_ptr list2 = create_list();
int count2 = list->count;
Status status2 = remove_first_occurrence(list2,99);
char message2[] = "should not remove if number does not exists";
int passed2 = status2 == 0 && count2 == list->count;
print_result(passed2,message2);
destroy_list(list2);
}
void test_remove_all_occurrences(){
printf("\nremove_all_occurrences\n");
List_ptr list = create_list();
add_to_end(list,1);
add_to_end(list,1);
add_to_end(list,2);
int count = list->count;
Status status = remove_all_occurrences(list,1);
char message[] = "should remove all occurrence of given number from list";
int passed = status == 1 && list->count == count - 2 && search(list,1) == -1;
print_result(passed,message);
destroy_list(list);
List_ptr list2 = create_list();
int count2 = list->count;
Status status2 = remove_all_occurrences(list2,99);
char message2[] = "should not remove if number does not exists";
int passed2 = status2 == 0 && count2 == list->count;
print_result(passed2,message2);
destroy_list(list2);
}
void test_clear_list(){
printf("\nclear_list\n");
List_ptr list = create_list();
add_to_end(list,1);
add_to_end(list,2);
Status status = clear_list(list);
char message[] = "should clear whole list";
int passed = status == 1 && list->count == 0 && list->head == NULL && list->last == NULL;
print_result(passed,message);
destroy_list(list);
}
void test_is_num_on_position(){
printf("\nis_num_on_position\n");
List_ptr list = create_list();
add_to_end(list,1);
int status = is_num_on_position(list,1,0);
char message[] = "should return 1 if given num is on the given position in list";
print_result(status == 1, message);
destroy_list(list);
List_ptr list2 = create_list();
int status2 = is_num_on_position(list2,1,0);
char message2[] = "should return 0 if given num is not on the given position in list";
print_result(status2 == 0, message2);
destroy_list(list2);
}
int main(){
test_add_to_end();
test_add_to_start();
test_insert_at();
test_search();
test_add_unique();
test_remove_from_start();
test_remove_from_end();
test_remove_at();
test_remove_first_occurrence();
test_remove_all_occurrences();
test_clear_list();
test_is_num_on_position();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef enum{
FALSE,
TRUE
}BOOL;
typedef struct{
int *entryArray; //用于指向对内存的数组指针
int arrayLen; //保存数组的最大长度
int heapLen; //保存堆长度
}*Heap_t;
//二叉堆初始化
void initHeapEntry(Heap_t heap, int len)
{
heap->entryArray = (int *)malloc(sizeof(int)*len);
if(heap->entryArray == NULL){
printf("malloc error\n");
exit(1);
}
heap->arrayLen = len;
heap->heapLen = 0;
}
//二叉堆判空/清空
BOOL isEmptyHeap(Heap_t heap)
{
if(heap->arrayLen == 0)
return TRUE;
return FALSE;
}
void cleanHea(Heap_t heap)
{
if(heap != NULL)
{
free(heap->entryArray);
heap->arrayLen = 0;
heap->heapLen = 0;
}
}
//元素插入,向上调整法,这里是最小堆
void insertHeap(Heap_t heap, int ele)
{
//如果堆满,将堆数组长度扩展到原来的两倍
if(heap->heapLen == heap->arrayLen){
heap->entryArray = (int *)realloc(heap, sizeof(int)*2*heap->arrayLen);
heap->arrayLen = 2*heap->arrayLen;
}
//对尾添加新元素
heap->entryArray[heap->heapLen] = ele;
heap->heapLen ++;
int i = heap->heapLen-1; //i指向待调整元素的位置
/*最小堆向上调整算法*/
while(i != 0){
int j = (i - 1) / 2;
if(ele >= heap->entryArray[j]) //如果新加入的元素大于父节点,跳出循环
break;
heap->entryArray[i] = heap->entryArray[j];
i = j;
}
heap->entryArray[i] = ele;
}
//二叉堆的删除
void deleteHeapTop(Heap_t heap)
{
if(heap->heapLen == 0){
printf("heap empty\n");
exit(0); //正常运行程序退出 exit(1):异常终止
}
int temp = heap->entryArray[0]; //取出堆顶元素
heap->heapLen --;
if(heap->heapLen == 0)
exit(1);
int lastData = heap->entryArray[heap->heapLen]; //删除了一个元素,最后一个元素的位置需要调整
int i = 0;
int j = 2*i + 1; //j指向i的左孩子的位置
//最小堆的向下调整算法
while(j <= heap->heapLen - 1){
if(j < heap->heapLen && heap->entryArray[j] > heap->entryArray[j + 1])
j++;
if(lastData < heap->entryArray[j]) //最后一个元素小于孩子节点,那莫位置找到了
break;
heap->entryArray[i] = heap->entryArray[j]; //将孩子元素放到父节点的位置
i = j;
j = 2*i + 1;
}
heap->entryArray[i] = lastData;
}
//二叉堆删除指定的元素
//查找指定元素的位置
int GetIndex(Heap_t heap, int ele)
{
for(int i = 0; i < heap->heapLen; ++i){
if(heap->entryArray[i] == ele)
return i;
}
return -1;
}
//元素删除函数
BOOL removeHeadEle(Heap_t heap, int ele)
{
int index;
if(heap->heapLen == 0)
return FALSE;
index = GetIndex(heap, ele);
if(index == -1)
return FALSE;
int temp = heap->entryArray[index]; //记录要删除的元素
int lastdata = heap->entryArray[heap->heapLen-1];
heap->heapLen --;
int i = index;
int j = 2<<1|1;
//最小堆的向下调整算法
while(j <= heap->heapLen-1)
{
if(j < heap->heapLen && heap->entryArray[j] > heap->entryArray[j + 1])
j ++;
if(lastdata < heap->entryArray[j])
break;
heap->entryArray[i] = heap->entryArray[j];
i = j;
j = 2*i+1;
}
heap->entryArray[i] = lastdata;
return FALSE;
}
|
C
|
#include <brdkSTR_func.h>
signed long brdkStrAppendUdintToA(unsigned long value, unsigned long pString, unsigned char base, signed long position) {
signed long i,cnt=0,len = brdkStrLen(pString);
signed long start = position > -1 ? position :len+position+1;
unsigned char tmp;
i=start;
tmp = 0x30;
base = !base ? 10 : base; /* make sure base is not 0 */
if (value != 0) {
while (value > 0) {
unsigned long rem = value % base;
unsigned char tmp = (rem > 9)? (rem-10) + 0x41 : rem + 0x30; /* 0x41 = A, 0x30 = 0*/
brdkStrFill(pString,1,(unsigned long)&tmp,i++);
value = value/base;
cnt++;
}
brdkStrReverse(pString,start,--i);
return len+cnt;
}
else {
brdkStrFill(pString,1,(unsigned long)&tmp,i);
return len+1;
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
void _strcpy(char m[],char n[]){
int a;
for(a=0;n[a]!='\0';m[a]=n[a],a++);
m[a]='\0';
}
void main(){
char str1[100],str2[100];
clrscr();
printf("\nEnter any two string:");
fflush(stdin);
gets(str1);
fflush(stdin);
gets(str2);
_strcpy(str1,str2);
printf("\nCoppyed string=%s",str1);
getch();
}
|
C
|
#include <stdio.h>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
int *ptr=&arr[4];
int i, sum=0;
for(i=0; i<5; i++)
{
sum += *ptr;
*ptr--;
}
printf("합 계 : %d \n", sum);
return 0;
}
|
C
|
#include "hcsr04.h"
extern int echo_time;
static void Hcsr04_GPIO_Config()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(HCSR04_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = Trig_Pin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(Trig_Port, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = Echo_Pin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(Echo_Port, &GPIO_InitStructure);
}
static float Hcsr04_Get_ONE_Distance()
{
float temp_distance = 0;
//printf("High start\n");
Trig_High;
delay_us(20);
Trig_Low;
//printf("high done\n");
//printf("echo status:%d\n", Echo_Status);
//̽ߵƽ˳ѭ,ʼ
while(Echo_Status == 0);
TIM_Cmd(Echo_TIM , ENABLE);
//printf("Echo Start\n");
//̽͵ƽ˳ѭֹͣ
while(Echo_Status == 1);
TIM_Cmd(Echo_TIM , DISABLE);
//printf("Echo Done\n");
temp_distance = echo_time/58;
echo_time = 0;
return temp_distance;
}
float Hcsr04_Get_Distance()
{
float temp_distance = 0;
float sum = 0;
int count = 0;
for(count = 0; count < 5; count++)
{
temp_distance = Hcsr04_Get_ONE_Distance();
sum += temp_distance;
}
return sum/5;
}
// жȼ
static void Echo_TIM_NVIC_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
// жΪ0
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
// жԴ
NVIC_InitStructure.NVIC_IRQChannel = Echo_TIM_IRQ ;
// ȼΪ 0
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
// ռȼΪ3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
static void Echo_TIM_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
// ʱʱ,ڲʱCK_INT=72M
Echo_TIM_APBxClock_FUN(Echo_TIM_CLK, ENABLE);
// ԶװؼĴֵۼTIM_Period+1Ƶʺһ»ж
// ʱʱ = (psr+1)/72M * arr+1
// ʱʱΪ һʱ*arr(s), 1ms
TIM_TimeBaseStructure.TIM_Period = Echo_TIM_Period;
// ʱԤƵΪ
// һεʱΪ (psr+1)/72M(s), 1*10^(-6)
TIM_TimeBaseStructure.TIM_Prescaler = Echo_TIM_Prescaler;
// ʱӷƵ ʱûУù
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
// ģʽʱֻϼûмģʽ
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
// ظֵʱûУù
TIM_TimeBaseStructure.TIM_RepetitionCounter=0;
// ʼʱ
TIM_TimeBaseInit(Echo_TIM, &TIM_TimeBaseStructure);
// жϱ־λ
TIM_ClearFlag(Echo_TIM, TIM_FLAG_Update);
// ж
TIM_ITConfig(Echo_TIM,TIM_IT_Update,ENABLE);
// ʹܼ
TIM_Cmd(Echo_TIM, ENABLE);
}
static void Echo_TIM_Init(void)
{
Echo_TIM_NVIC_Config();
Echo_TIM_Config();
}
void HCSR04_Init(void)
{
Hcsr04_GPIO_Config();
Echo_TIM_Init();
}
|
C
|
#include <stdio.h>
float average(int a, int b, int c);
int main()
{
float result;
result = average(4, 6, 9);
printf("Average : %f", result);
return 0;
}
float average(int a, int b, int c)
{
float avg = (a + b + c)/3.0;
return avg;
}
|
C
|
<Recipe> ::=
<Recipe Title>
[<Comments>]
<Ingredient List>
<Method>
<Recipe Title> ::= <String>.
<Comments> ::= <String>.
<Ingredient List> ::=
Ингредиенты.
{<ingredient-name> <initial-value> [<measure>]}
<ingredient-name> ::= <String>
<initial-value> ::= <Integer>
<measure> ::= г | кг | ч.л. | шт. // сухие
<measure> ::= мл | л | ст.л. // жидкие
// Переменные типизируются: сухие - int, жидкие - char
<Method> ::=
Способ приготовления.
<Method statement>
<Method statement> := Возьмите из холодильника <ingredient>. //STDIN -> ingredient
<Method statement> ::= Положите в холодильник <ingredient> . //ingredient -> STDOUT
<Method statement> ::= Отправте блюдо в холодильник часа на <Integer>. // Integer элементов стэка -> STDOUT
<Method statement> := Добавте <ingredient>. // push
<Method statement> := Положите <ingredient>. // pop
<Method statement> := Почистите <ingredient>. // + с top и push в стэк
<Method statement> := Натрите на тёрке <ingredient>. // - с top и push в стэк
<Method statement> := Замешайте <ingredient>. // * с top и push в стэк
<Method statement> := Нарежте <ingredient>. // / с top и push в стэк
<Method statement> := Вымочить <ingredient>. // каст ingredient к жидкому (ASCII)
<Method statement> := Добавте воды. // каст стэка к жидкому
<Method statement> := Подготовте чистую посуду. // очистит стэк
// Петли
<Method statement> :=
Начинайте <Verb> <ingredient>. // начало цикла while ingredient != 0
{<Method statement>} // тело цикла
<Verb> <ingredient> до <String>. // конец цикла, ingredient--, String - комментарий
// Пример:
// Начинайте резать марковь. [тело цикла] Резать марковь до круглых колечек.
// Начинайте курить сигареты. [тело цикла] Курить сигареты до посинения.
<Method statement> := Отложите всё в сторону. // break
|
C
|
/*
* main.c
*
* Created on: 2015年5月1日
* Author: zjh
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include "relay.h"
int main(int argc, const char *argv[])
{
char group = 0;
char ioport = 0;
char i = 0;
if (argc != 3)
{
printf("Usage:\n");
printf("\trelay_test <group> <ioport>\n");
printf("\n");
return 1;
}
group = atoi(argv[1]);
ioport = atoi(argv[2]);
printf("main group %d ioport %d \n", group, ioport );
BoneRelayInit(group, ioport);
sleep(1);
for(i =0; i < 5; i++)
{
printf("relay switch to on\n");
BoneRelayOnOff(group, ioport, 1);
sleep(1);
printf("relay switch to off\n");
BoneRelayOnOff(group, ioport, 0);
sleep(1);
}
BoneRelayDeinit(group,ioport);
return 0;
}
|
C
|
/*
编写一个程序,用来模拟称为“掷双骰”游戏。程序要通过随机选择1到6之间的两个数来“滚动”一对
模拟的骰子。如果两个数的和是7或11,那么程序显示信息 player wins 。如果和为2、3或12,则
显示 Player lose 。否则,程序要重复滚动骰子直到再一次达到原始和(Player wins)或者骰子
合计为7(Player lose)为止。程序需要在每次模拟滚动后显示一下骰子的值。
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char const *argv[])
{
/* 开始,定义变量,设置随机种子 */
int num1, num2, sum;
srand(time(NULL));
/* 接受一次输入,滚动一次骰子,并判断结果 */
while (1) {
printf("Press any key to start rolling ...");
getchar();
num1 = rand() % 6 + 1;
num2 = rand() % 6 + 1;
printf("numbers: {%d %d}\n", num1, num2);
sum = num1 + num2;
if (sum == 7 || sum == 11) {
printf("Player win\n");
return 0;
}
else if (sum == 2 || sum == 3 || sum == 12) {
printf("Player lose\n");
return 0;
}
}
return 0;
}
|
C
|
#include<stdio.h>
main()
{
char grade;
int mark;
printf("Enter the mark of the student:\n");
scanf("%d",&mark);
if(mark>=85)
{
grade='A';
}
else if(mark>=70)
{
grade='B';
}
else if(mark>=55)
{
grade='C';
}
else if(mark>=40)
{
grade='D';
}
else
{
grade='F';
}
printf("The grade of the student is %c",grade);
}
|
C
|
#include "djxattr.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/xattr.h>
#include <linux/xattr.h>
#include <sys/types.h>
void ListXAttr(const char * path, char* buffer[MAX_XATTR])
{
char* lst = NULL;
char* chr = NULL;
char* start = NULL;
ssize_t cnt = 0;
ssize_t lstsize = 0;
lstsize = listxattr(path, NULL, 0);
if(lstsize < 0){
perror("listxattr error");
fprintf(stderr, "path = %s\n", path);
exit(EXIT_FAILURE);
}
/* Malloc space for list items */
lst = malloc(sizeof(*lst)*lstsize);
if(!lst){
perror("malloc of 'lst' error");
exit(EXIT_FAILURE);
}
/* Call xattr list to get data */
lstsize = listxattr(path, lst, lstsize);
if(lstsize < 0 || !lst){
perror("listxattr error");
fprintf(stderr, "path = %s\n", path);
exit(EXIT_FAILURE);
}
///* Tokenize null seperated array on \0 */
int at = 0;
chr = start = lst;
cnt = 0;
while(cnt < lstsize){
/* Print attribute names, one per line */
buffer[at++] = start;
while(*chr != '\0'){
chr++;
cnt++;
}
start = ++chr;
cnt++;
}
buffer[at]='\0';
return;
}
void GetXAttr(const char * path, char* key, char* buffer)
{
ssize_t valsize;
char* tmpstr = malloc(strlen(key) + XATTR_USER_PREFIX_LEN + 1);
strcpy (tmpstr, XATTR_USER_PREFIX);
strcat(tmpstr, key);
valsize = getxattr(path, tmpstr, NULL, 0);
if(valsize < 0)
{
if(errno == ENOATTR)
{
buffer[0] = '\0';
free(tmpstr);
return;
}
else {
fprintf(stderr, "GetXAttr Error");
abort();
}
}
if(!buffer) {
fprintf(stderr, "GetXAttr Malloc Error");
abort();
}
valsize = (getxattr(path, tmpstr, buffer, valsize));
if( valsize < 0) {
if(errno == ENOATTR)
{
buffer[0] = '\0';
free(tmpstr);
return;
}
else {
fprintf(stderr, "GetXAttr Error");
abort();
}
}
buffer[valsize] = '\0';
free(tmpstr);
return;
}
void SetXAttr(const char * path, char* key, char* val)
{
char* tmpstr = malloc(strlen(key) + XATTR_USER_PREFIX_LEN + 1);
strcpy(tmpstr, XATTR_USER_PREFIX);
strcat(tmpstr, key);
if(setxattr(path, tmpstr, val, strlen(val), 0)) {
fprintf(stderr, "Error setting attributes");
abort();
}
free(tmpstr);
}
void RemoveXAttr(const char * path, char* key)
{
char* tmpstr = malloc(strlen(path) + XATTR_USER_PREFIX_LEN + 1);
if(!tmpstr) {
fprintf(stderr, "Error malloc");
abort();
}
strcpy (tmpstr, XATTR_USER_PREFIX);
strcat (tmpstr, path);
if(removexattr(key, tmpstr))
{
if(errno == ENOATTR) {
return;
} else {
fprintf(stderr, "Error removing attr");
abort();
}
}
free(tmpstr);
}
bool SetEncryptedFlag(const char * path, bool isSet)
{
// This function sets the xattr flag for our encryption scheme //
// Has nothing to do with actual ecryption //
SetXAttr(path, ENC_ATTR_NAME, isSet ? "true" : "false");
return IsEncrypted(path);
}
bool IsEncrypted(const char * path)
{
char* list[MAX_XATTR];
ListXAttr(path, list);
char enc_val[256];
char* appended_key = "user."ENC_ATTR_NAME;
int i = 0;
while (list[i] != '\0')
{
if(strcmp(appended_key, list[i++]) == 0)
{
GetXAttr(path, ENC_ATTR_NAME, enc_val);
if (strcmp(enc_val, "true") == 0)
{
return 1;
}
}
}
return 0;
}
|
C
|
/* while-enter */
#include <stdio.h>
#include <stdlib.h>
#include <conio.h> //ϥgetche
int main(void)
{
int number=0;
printf("@Ӧr@ӦrJ([Enter]~):");
while(getche() != '\r'){ // \r[Enter] , ]iאּ^r,p Q
number = number + 1; // whileu@, iٲ { }
}
printf("\n@J%dӦr\n", number);
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int t, v[10], i, max = -1, j;
char web[10][101];
scanf("%d", &t);
for( i = 0; i < t; ++i ){
max = -1;
for( j = 0; j < 10; ++j ){
scanf("%s %d", web[j], &v[j]);
if( max < v[j] ) max = v[j];
}
printf("Case #%d:\n", i+1);
for( j = 0; j < 10; ++j ){
if( v[j] == max ) printf("%s\n", web[j]);
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
// 宣言と同時に初期化する方法
int int_arr1[5] = {0, 1, 2, 3, 4};
// 全ての要素をゼロで初期化する方法
int int_arr2[5] = {};
for(int i = 0; i < 5; i++) {
if(i < 4) {
printf("%d,", int_arr2[i]);
} else {
printf("%d\n", int_arr2[i]);
}
}
// 途中まで初期化
int int_arr3[5] = {0, 1, 2};
for(int i = 0; i < 5; i++) {
if(i < 4) {
printf("%d,", int_arr3[i]);
} else {
printf("%d\n", int_arr3[i]);
}
}
// ひとつの要素だけゼロ以外を指定
int int_arr4[5] = {[2] = 2};
for(int i = 0; i < 5; i++) {
if(i < 4) {
printf("%d,", int_arr4[i]);
} else {
printf("%d\n", int_arr4[i]);
}
}
// 要素数の記述を省略
char char_arr1[] = {'H', 'e', 'l', 'l', 'o'};
printf("%s\n", char_arr1);
// 文字列で初期化
char char_arr2[16] = "Hello";
// 要素の型の範囲外で初期化する場合
signed char schar_arr1[200];
for(int i = 0; i < 200; i++) {
schar_arr1[i] = i;
}
printf("%d\n", schar_arr1[199]);
return 0;
}
|
C
|
#include "latin.h"
/*#define NUM_TYPE unsigned short int
void setBit(NUM_TYPE *LSVector,int n,int i,int j);
int Isbit(NUM_TYPE *LSVector,int n,int i,int j);*/
int pickcols(NUM_TYPE *tempcolsx,NUM_TYPE *tempcolsy,NUM_TYPE *S,NUM_TYPE *P,NUM_TYPE *LSVector1,NUM_TYPE *LSVector2,NUM_TYPE *Jx,NUM_TYPE *Jy,int *lev,int n)
{
int t,it1,count1=0;
for (t=0;t<=n-1;t++){/*Picks the x rows to look at*/
if (Isbit(S,n,lev[0]-1,t)==1){
for(it1=0;it1<=n-1;it1++){/*Decides whether x columns in rows contain 1's*/
if (lev[0] % 2 ==1)
{
if (Isbit(LSVector1,n,t,it1)==1 && Isbit(tempcolsx,n,0,it1)==0 && Isbit(Jx,n,0,it1)==0)
{
setBit(tempcolsx,n,0,it1);
count1++;
}
}
else
{
if (Isbit(LSVector1,n,it1,t)==1 && Isbit(tempcolsx,n,0,it1)==0 && Isbit(Jx,n,0,it1)==0)
{
setBit(tempcolsx,n,0,it1);
count1++;
}
}
}
}
}
/*No need to change*/
for (t=0;t<=n-1;t++){/*Finds the Y row index*/
if (Isbit(P,n,lev[0]-1,t)==1){
for (it1=0;it1<=n-1;it1++){/*Finds the y cols to look at*/
if (lev[0] % 2 ==1)
{
if (Isbit(LSVector2,n,t,it1)==1 && Isbit(tempcolsy,n,0,it1)==0 && Isbit(Jy,n,0,it1)==0)
{
setBit(tempcolsy,n,0,it1);
}
}
else
{
if (Isbit(LSVector2,n,it1,t)==1 && Isbit(tempcolsy,n,0,it1)==0 && Isbit(Jy,n,0,it1)==0)
{
setBit(tempcolsy,n,0,it1);
}
}
}
}
}
return(count1);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 1000
#define M 10000000
typedef struct Nameval Nameval;
struct Nameval{
int value;
Nameval *left;
Nameval *right;
};
Nameval *create(int n){
Nameval *newp =(Nameval*)malloc(sizeof(Nameval));
newp->value = n;
newp->left = NULL;
newp->right = NULL;
return newp;
}
Nameval *insert(Nameval *treep, int num){
if(treep == NULL){
treep = create(num);
}
else if(treep->value >= num)
treep->left = insert(treep->left, num);
else
treep->right = insert(treep->right, num);
return treep;
}
/*lookup*/
Nameval *lookup(Nameval *treep, int n){
if(treep == NULL)
return NULL;
int cmp = treep->value - n;
if(cmp== 0){
return treep;
}
else if(cmp<0){
return lookup(treep->left, n);
}
else {
return lookup(treep->right, n);
}
}
/*nrlookup*/
Nameval *nrlookup(Nameval *treep, int n){
while(treep!=NULL){
int cmp = treep->value - n;
if(cmp == 0)
return treep;
else if(cmp<0)
treep = treep->left;
else
treep = treep->right;
}
return NULL;
}
int main(){
int arr[N];
clock_t begin,end;
Nameval *treep=NULL;
for(int i=0;i<N;i++){
arr[i] = i;
}
for(int i=0;i<N;i++){
treep = insert(treep,i);
}
begin = clock();
for(int j=0;j<M;j++){
for(int i=0; i<N; i++){
lookup(treep, arr[i]);
}
}
end = clock();
printf("Lookup: %.8f seconds\n",(double)(end-begin)/CLOCKS_PER_SEC);
begin = clock();
for(int j=0;j<M;j++){
for(int i=0;i<N;i++){
nrlookup(treep,arr[i]);
}
}
end = clock();
printf("Nrlookup: %.8f seconds\n",(double)(end-begin)/CLOCKS_PER_SEC);
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int prev, next;
prev = getchar();
if (prev != EOF) {
while ((next = getchar()) != EOF) {
if (prev == ' ' && prev == next)
continue;
putchar(prev);
prev = next;
}
putchar(prev);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "include/leveldb_queue.h"
#include "src/leveldb/structs.h"
#include "src/scheme.h"
#include "src/errors.h"
kvqueue_leveldb_queue_t* kvqueue_leveldb_queue_create()
{
kvqueue_leveldb_queue_t* self = malloc(sizeof(kvqueue_leveldb_queue_t));
self->parent = NULL;
self->name = NULL;
self->error_message = NULL;
self->order = kvqueue_queue_orders_unknown;
return self;
}
void kvqueue_leveldb_queue_destroy(kvqueue_leveldb_queue_t* handler)
{
if (NULL != handler->error_message) {
leveldb_free(handler->error_message);
handler->error_message = NULL;
}
if (NULL != handler->name) {
free(handler->name);
handler->name = NULL;
}
free(handler);
}
const char* kvqueue_leveldb_queue_attach( kvqueue_leveldb_storage_t* handler
, kvqueue_leveldb_queue_t* queue
, const char* name
, kvqueue_queue_orders_e order )
{
queue->parent = handler;
queue->order = order;
queue->name = malloc(strlen(name) + 1);
strcpy(queue->name, name);
return NULL;
}
const char* kvqueue_leveldb_storage_queue_number( kvqueue_leveldb_storage_t* handler
, uint16_t* queue_number )
{
size_t queue_number_size = 0;
char* queue_number_ptr = leveldb_get( handler->storage
, handler->read_options
, queue_num_key_value()
, queue_num_key_len()
, &queue_number_size
, &handler->error_message );
if (NULL != handler->error_message) {
return handler->error_message;
}
if (NULL == queue_number_ptr) {
*queue_number = 0;
return NULL;
}
if ((NULL != queue_number_ptr) && (queue_number_size != sizeof(uint16_t))) {
leveldb_free(queue_number_ptr);
handler->error_message = malloc(strlen(WRONG_QUEUE_NUM_SIZE_ERROR) + 1);
strcpy(handler->error_message, WRONG_QUEUE_NUM_SIZE_ERROR);
return handler->error_message;
}
if ((NULL != queue_number_ptr) && (sizeof(uint16_t) == queue_number_size)) {
*queue_number = *(uint16_t*)queue_number_ptr;
leveldb_free(queue_number_ptr);
return NULL;
}
}
const char* kvqueue_leveldb_queue_push( kvqueue_leveldb_queue_t* queue
, uint16_t priority
, uint16_t size
, const char* body )
{
return NULL;
}
const char* kvqueue_leveldb_queue_pop( kvqueue_leveldb_queue_t* queue
, uint16_t* size
, char** body )
{
return NULL;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.