language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include "TCanvas.h"
#include "TROOT.h"
#include "TGraphErrors.h"
#include "TF1.h"
#include "TH1F.h"
#include "TLegend.h"
#include "TFile.h"
#include "TArrow.h"
#include "TLatex.h"
#include "TMath.h"
#include "TMultiGraph.h"
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
Double_t f(Double_t x)
{
return TMath::Cos(x);
}
Double_t f_plot(Double_t *x, Double_t *param)
{
return param[0]*TMath::Cos(x[0]);
}
class DerivativeFunction
{
Double_t a, b;
public:
void set_values (Double_t, Double_t);
Double_t DerivativeDefinition () {return (f(a) - f(b))/(a - b);}
};
void DerivativeFunction::set_values (Double_t x, Double_t x0)
{
a = x;
b = x0;
}
void DerivativeFunction()
{
class DerivativeFunction *func;
Double_t initial_value, final_value;
cout << "Please enter the initial and final value to evaluate the derivative: " << endl;
cin >> initial_value >> final_value;
vector<Double_t> x_values_vector;
vector<Double_t> derivative_vector;
if (initial_value == 0)
{
for (Int_t i = initial_value; i < final_value; ++i)
{
func -> set_values(i + i*pow(10, -7) + pow(10, -7), i);
x_values_vector.push_back(i);
derivative_vector.push_back(func -> DerivativeDefinition());
}
}
else
{
for (Int_t i = initial_value; i < final_value; ++i)
{
func -> set_values(i + i*pow(10, -7), i);
x_values_vector.push_back(i);
derivative_vector.push_back(func -> DerivativeDefinition());
}
}
Float_t x_values_array[x_values_vector.size()];
Float_t derivative_array[derivative_vector.size()];
for (Int_t i = 0; i < x_values_vector.size(); ++i)
{
x_values_array[i] = x_values_vector[i];
derivative_array[i] = derivative_vector[i];
}
auto *c1 = new TCanvas();
c1 -> SetGrid();
TGraph *gr1 = new TGraph (sizeof(x_values_array)/sizeof(x_values_array[0]), x_values_array, derivative_array);
TF1 *f1 = new TF1("f1", f_plot, initial_value, final_value, 2);
f1 -> SetParameter(0, 1);
gr1 -> SetTitle("Function and its derivative");
f1 -> SetTitle("Function and its derivative");
gr1 -> GetXaxis() -> SetTitle("x");
gr1 -> GetXaxis() -> CenterTitle();
f1 -> GetXaxis() -> SetTitle("x");
f1 -> GetXaxis() -> CenterTitle();
gr1 -> Draw();
f1 -> Draw("same");
c1 -> Draw();
auto legend = new TLegend(0.9, 0.7, 0.6, 0.9);
legend -> SetHeader("Legend", "C"); // option "C" allows to center the header
legend -> AddEntry(f1, "Function", "l");
legend -> AddEntry(gr1, "Derivative", "l");
legend -> Draw();
//cout << "Derivative = " << func -> DerivativeDefinition () << endl;
//TF1 *f1 = new TF1("func1", "pow(x, 2)", 0, 10);
//cout << "ROOT implemented derivative = " << f1 -> Derivative(1) << endl;
//cout << f1 -> Derivative(1) - func -> DerivativeDefinition () << endl;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void diziYaz(int dizi[], int satir)
{
for (int i = 0; i < satir; i++)
printf("%d ", dizi[i]);
}
void diziYaz2B(int dizi[][4], int satir, int sutun)
{
for (int i = 0; i < satir; i++) {
for (int j = 0; j < sutun; j++)
printf("%d ", dizi[i][j]);
printf("\n");
}
}
void ortalamaBul(int dizi[][4], int satir, int sutun)
{
int toplam[4] = {0};
float ortalama[4] = {0};
printf("Dersler Toplami : ");
for (int i = 0; i < sutun; i++)
{
for (int j = 0; j < satir; j++)
toplam[i] += dizi[j][i];
printf("%d ",toplam[i]);
}
printf("\nDersler Ortalamasi : ");
for(int i=0;i<sutun;i++)
{
ortalama[i]=(float)toplam[i]/satir;
printf("%.2f ",ortalama[i]);
}
}
int main() {
int i, j;
int d1[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int d3[3][4] = {{1,2,3,4},{5,6},{9}};
int d2[3][4] = {1,2,3,4,5,6,7,8,9};
int dizi[3] = {0};
diziYaz2B(d1, 3, 4);
ortalamaBul(d1,3,4);
//diziYaz(dizi,3);
return 0;
}
|
C
|
#include <stdio.h>
#define LIMIT 8 //max number of items, one byte
int hexToInt(char []);
float power(float, int);
void main(){
char sentence[LIMIT];
int c, i;
i = 0;
while((c = getchar())!= EOF && c != '\n' && i < LIMIT){
if((i == 0) && c == '0')
sentence[i++] = c;
else if((i == 1) && (c == 'x' || c == 'X'))
sentence[i++] = c;
else if((c >= '0' && c <= '9') || (c >= 'a' && c<='f') || (c >= 'A' && c <= 'Z'))
sentence[i++] = c;
else{
printf("Invalid.\n");
break;
}
}
sentence[i] = '\0';//null terminate it
printf("Sentence: %s Size: %d\n", sentence, hexToInt(sentence));
char test[] = "aa";
printf("%d\n", hexToInt(test));
}
int hexToInt(char number[]){
int i, j, answer;
i = answer = j = 0;
while(number[i] != '\0') i++;
if(i == 0) return 0; //if its an empty string
i--;// make it one less than actual value we want to start at 0
// printf("%.0f\n", power(16,i));
if(number[0] == '0' && (number[1] == 'x' || number[1] == 'X')){
j = 2;//start at j
i -= 2;//sub two from count
}
while(number[j] != '\0'){
if(number[j] >= 'A' && number[j] <= 'Z')
answer += power(16,i--)*((number[j++]-'A')+10);
else if(number[j] >= 'a' && number[j] <='f')
answer += power(16,i--)*((number[j++]-'a')+10);
else//is a normal number
answer += power(16,i--)*(number[j++]-'0');
}
return answer;
}
/* raises to a power*/
float power(float x, int y)
{
float temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
{
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
|
C
|
#include <stdlib.h>
#include<stdio.h>
#include <pthread.h>
#include "life.h"
#include "util.h"
#include<assert.h>
/**************************************************************
* This file contains the parallel implementation of the game
* of life.
*
* Authors: Divya Dadlani
* Geetika Saksena
* (Team Basilisk)
*************************************************************/
/**
* Swapping the two boards only involves swapping pointers, not
* copying values.
*/
#define SWAP_BOARDS( b1, b2 ) do { \
char* temp = b1; \
b1 = b2; \
b2 = temp; \
} while(0)
/**
* The macro which returns the status of cell (i, j) on the board.
*/
#define BOARD( __board, __i, __j ) (__board[(__i) + LDA*(__j)])
/**
* A structure which holds the arguments necessary for multithreading
* and synchronization
*/
typedef struct arguments {
char *outboard;
char *inboard;
pthread_barrier_t *barrier;
pthread_mutex_t *mutex;
int *return_count;
int total_nrows;
int tid;
int gens_max;
} arguments;
void *evaluate_board(void *thread_args);
/**
* Parallel implementation of the 'sequential_game_of_life'
* function using 8 threads.
*
* Takes the following parameters:
* -pointers to the inboard and outboard
* -number of rows and columns
* -total number of iterations for which to run
*
* Returns a pointer to the final board after running
* the game of life algorithm for gens_max iterations.
*/
char*
parallel_game_of_life(char* outboard, char* inboard, const int nrows, const int ncols, const int gens_max) {
/* Thread generation variables */
const int num_threads = 8;
pthread_t threads[num_threads];
int thread_id[num_threads];
char **return_board_ptr[num_threads];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_barrier_t barrier; // barrier synchronization object
pthread_barrier_init(&barrier, NULL, num_threads);
char *return_board = NULL;
int i;
int count = -1;
/* Create the threads and run board evaluation */
for (i = 0; i < num_threads; i++) {
return_board_ptr[i] = (char **) malloc(sizeof(char *));
thread_id[i] = i;
arguments *thread_args = (arguments *) malloc(1 * sizeof(arguments));
thread_args->outboard = outboard;
thread_args->inboard = inboard;
thread_args->barrier = &barrier;
thread_args->mutex = &mutex;
thread_args->return_count = &count;
thread_args->total_nrows = nrows;
thread_args->tid = thread_id[i];
thread_args->gens_max = gens_max;
pthread_create(&threads[i], NULL, evaluate_board, (void *) thread_args);
}
/* Join all the threads and find the board to return */
for (i = 0; i < num_threads; i++) {
pthread_join(threads[i], (void **) return_board_ptr[i]);
if (*return_board_ptr[i] != NULL)
return_board = *return_board_ptr[i];
}
assert(return_board != NULL);
return return_board;
}
/**
* Evaluates the status of cells in one part of the board
* for all iterations.
*
* This function is called 8 times (i.e. by each thread) and
* is synchronized using a barrier before each iteration and
* a lock before returning the final outcome.
*
* Takes a struct of thread arguments which it uses to
* calculate the bounds within which each thread operates.
* The struct also passes in synchronization variables that
* are shared by all threads.
*
* Returns the complete evaluated board.
*/
void *evaluate_board(void *thread_args) {
/* Synchronization variables */
int *return_count = ((arguments *) thread_args)->return_count;
pthread_barrier_t *barrier = ((arguments *) thread_args)->barrier;
pthread_mutex_t *mutex = ((arguments *) thread_args)->mutex;
/* Bound calculation variables */
int tid = ((arguments *) thread_args)->tid;
int dim = ((arguments *) thread_args)->total_nrows;
char *inboard = ((arguments *) thread_args)->inboard;
char *outboard = ((arguments *) thread_args)->outboard;
int gens_max = ((arguments *) thread_args)->gens_max;
int start_row, start_col, end_row, end_col, i, j, curgen;
/* Assign start and end bounds for each thread
* The board is divided into 8 segments as follows:
* _____________________
* | | | | |
* | | | | |
* | | | | |
* | | | | |
* |____|____|____|____|
* | | | | |
* | | | | |
* | | | | |
* | | | | |
* |____|____|____|____|
*
* Each thread runs the game of life computation on
* one of these segments.
*/
if (tid % 2) {
start_row = 0;
end_row = dim >> 1;
} else {
start_row = dim >> 1;
end_row = dim;
}
switch (tid) {
case 0:
case 1:
start_col = 0;
end_col = dim >> 2;
break;
case 2:
case 3:
start_col = dim >> 2;
end_col = dim >> 1;
break;
case 4:
case 5:
start_col = dim >> 1;
end_col = dim - (dim >> 2);
break;
case 6:
case 7:
start_col = dim - (dim >> 2);
end_col = dim;
break;
default:
start_row = 0;
start_col = 0;
end_row = dim;
end_col = dim;
}
/* Evaluate board */
const int tile_size = 32;
const int LDA = dim;
for (curgen = 0; curgen < gens_max; curgen++) {
/* All threads must wait before starting a new generation */
pthread_barrier_wait(barrier);
for (i = start_row; i < end_row; i += tile_size) {
int ii;
for (j = start_col; j < end_col; j += tile_size) {
int jj;
for (ii = i; (ii < end_row) && (ii < (i + tile_size)); ii++) {
int inorth = wrap_mod(ii - 1, dim);
int isouth = wrap_mod(ii + 1, dim);
for (jj = j; (jj < end_col) && (jj < (j + tile_size)); jj++) {
int jwest = wrap_mod(jj - 1, dim);
int jeast = wrap_mod(jj + 1, dim);
char neighbor_count =
BOARD(inboard, inorth, jwest) +
BOARD (inboard, ii, jwest) +
BOARD (inboard, isouth, jwest) +
BOARD (inboard, inorth, jj) +
BOARD (inboard, isouth, jj) +
BOARD (inboard, inorth, jeast) +
BOARD (inboard, ii, jeast) +
BOARD (inboard, isouth, jeast);
char state = BOARD(inboard, ii, jj);
BOARD(outboard, ii, jj) = (neighbor_count == (char) 3) ||
(state && (neighbor_count >= 2) && (neighbor_count <= 3));
}
}
}
}
SWAP_BOARDS(outboard, inboard);
}
/* Ensure that only the last thread returns
* the final evaluated board */
char *return_board = NULL;
pthread_mutex_lock(mutex);
(*return_count)++;
if ((*return_count) == 7) {
return_board = inboard;
}
pthread_mutex_unlock(mutex);
return return_board;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b;
a=10,b=12;
printf("before swap a=%d b=%d\n",a,b);
b=b^a;
a=b^a;
b=b^a;
printf("after swap a=%d b=%d",a,b);
return 0;
}
|
C
|
/*
* Aula.c
*
* Created on: 26 mar. 2020
* Author: Xabier
*/
#include "Aula.h"
#include "Asignatura.h"
void reserva (Aula *aula, int dia, int hora, Asignatura asig){
if(aula->ocupadapor[dia][hora].creditos == 0){
aula->ocupadapor[dia][hora] = asig;
}else{
printf("Ocupada.");
}
}
void quitaReserva(Aula *aula, int dia, int hora, Asignatura asig){
if(aula->ocupadapor[dia][hora].creditos != 0){
aula->ocupadapor[dia][hora] = asig;
}else{
printf("Esta libre.");
}
}
|
C
|
//Huffman Codes
#include<stdio.h>
#include<stdlib.h>
int n;
struct node
{
struct node *lchild;
char data;
int freq;
struct node *rchild;
};
void min_heapify(struct node a[],int i)
{
int l,r,smallest;
struct node temp;
l=2*i+1;
r=2*i+2;
if((a[l].freq<a[i].freq)&&(l<n))
{
smallest=l;
}
else
{
smallest=i;
}
if((a[r].freq<a[smallest].freq)&&(r<n))
{
smallest=r;
}
if(smallest!=i)
{
temp=a[i];
a[i]=a[smallest];
a[smallest]=temp;
min_heapify(a,smallest);
}
}
void build_heap(struct node a[])
{
int i;
for(i=(n/2);i>=0;--i)
{
min_heapify(a,i);
}
}
void extract_min(struct node a[],struct node **new)
{
if(n<1)
{
return NULL;
}
(*new)->lchild=a[0].lchild;
(*new)->rchild=a[0].rchild;
(*new)->data=a[0].data;
(*new)->freq=a[0].freq;
a[0]=a[n-1];
--n;
min_heapify(a,0);
}
void insert_heap(struct node a[],struct node *new)
{
int i=n;
struct node temp;
a[n]=*new;
++n;
while((i>0)&&(a[i].freq<a[(i-1)/2].freq))
{
temp=a[i];
a[i]=a[(i-1)/2];
a[(i-1)/2]=temp;
i=(i-1)/2;
}
}
void hmc(struct node a[])
{
build_heap(a);
while(n>1)
{
struct node *p1,*p2,*curr;
p1=(struct node *)malloc(sizeof(struct node));
p2=(struct node *)malloc(sizeof(struct node));
curr=(struct node *)malloc(sizeof(struct node));
extract_min(a,&p1);
extract_min(a,&p2);
curr->data=0;
curr->freq=p1->freq+p2->freq;
curr->lchild=p1;
curr->rchild=p2;
insert_heap(a,curr);
}
}
void print_tree(struct node *root,int arr[],int index)
{
if(root->lchild!=NULL)
{
arr[index]=0;
print_tree(root->lchild,arr,index+1);
}
if(root->rchild!=NULL)
{
arr[index]=1;
print_tree(root->rchild,arr,index+1);
}
if((root->lchild==NULL)&&(root->rchild==NULL))
{
printf("\n%c:",root->data);
int i;
for(i=0;i<index;++i)
{
printf("%d",arr[i]);
}
return;
}
}
int main()
{
int i;
printf("\nEnter the range:");
scanf("%d",&n);
struct node a[n];
for(i=0;i<n;++i)
{
printf("\nEnter the data and frequency:");
scanf(" %c%d",&a[i].data,&a[i].freq);
a[i].lchild=NULL;
a[i].rchild=NULL;
}
hmc(a);
int arr[n];
print_tree(a,arr,0);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkedlist.h"
LinkedList* createLinkedList()
{
LinkedList *pReturn = NULL;
int i = 0;
pReturn = (LinkedList *)malloc(sizeof(LinkedList));
if (pReturn != NULL)
{
memset(pReturn, 0, sizeof(LinkedList));
}
else
{
printf("Error in malloc\n");
return NULL;
}
return pReturn;
}
int addLLElement(LinkedList* pList, int position, ListNode element)
{
int ret = FALSE;
int i = 0;
ListNode* pPreNode = NULL;
ListNode* pNewNode = NULL;
if (pList != NULL)
{
if (position >= 0 && position <= pList->currentElementCount)
{
pNewNode = (ListNode*)malloc(sizeof(ListNode));
if (pNewNode != NULL)
{
*pNewNode = element;
pNewNode->pLink = NULL;
pPreNode = &(pList->headerNode);
for(i = 0; i < position; i++)
{
pPreNode = pPreNode->pLink;
}
pNewNode->pLink = pPreNode->pLink;
pPreNode->pLink = pNewNode;
pList->currentElementCount++;
ret = TRUE;
}
else
{
printf("Error in malloc\n");
return ret;
}
}
else
{
printf("Index error\n");
}
}
return ret;
}
int removeLLElement(LinkedList* pList, int position)
{
int ret = FALSE;
int i = 0;
int arrayCount = 0;
ListNode* pNode = NULL;
ListNode* pDelNode = NULL;
if (pList != NULL)
{
arrayCount = getLinkedListLength(pList);
if (position >= 0 && position < arrayCount)
{
pNode = &(pList->headerNode);
for(i = 0; i < position; i++)
{
pNode = pNode->pLink;
}
pDelNode = pNode->pLink;
pNode->pLink = pDelNode->pLink;
free(pDelNode);
pList->currentElementCount--;
ret = TRUE;
}
else
{
printf("Index error\n");
}
}
return ret;
}
ListNode* getLLElement(LinkedList* pList, int position)
{
int i = 0;
ListNode* pNode = NULL;
if (pList != NULL)
{
if (position >= 0 && position < pList->currentElementCount)
{
pNode = &(pList->headerNode);
for (i = 0; i <= position; i++)
{
pNode = pNode->pLink;
}
}
}
return pNode;
}
void displayLinkedList(LinkedList* pList)
{
int i = 0;
if (pList != NULL)
{
printf("Cur el count: %d\n", pList->currentElementCount);
for (i = 0; i < pList->currentElementCount; i++)
{
printf("[%d], %d\n", i, getLLElement(pList, i)->data);
}
}
}
void deleteLinkedList(LinkedList* pList)
{
if (pList != NULL)
{
clearLinkedList(pList);
free(pList);
}
}
void clearLinkedList(LinkedList* pList)
{
if (pList != NULL)
{
if (pList->currentElementCount > 0)
{
removeLLElement(pList, 0);
}
}
}
int getLinkedListLength(LinkedList* pList)
{
int ret = 0;
if (pList != NULL)
{
ret = pList->currentElementCount;
}
return ret;
}
int isEmpty(LinkedList* pList)
{
int ret = FALSE;
if (pList != NULL)
{
if (pList->currentElementCount == 0)
{
ret = TRUE;
}
}
return ret;
}
|
C
|
/**
******************************************************************************
* @file main.c
* @author Anton Kabanov
* @version V1.0
* @date 22-March-2019
* @brief Default main function.
******************************************************************************
*/
#include "stm32f10x.h"
#define IN_MS_TO_POPUGAIS(MS) (2 * MS - 1)
void led_init(void);
void buttons_init(void);
void timer_init(void);
volatile uint16_t a = IN_MS_TO_POPUGAIS(500);
volatile uint16_t b = IN_MS_TO_POPUGAIS(500);
int main(void)
{
led_init(); //Инициализируем LED (С13)
buttons_init(); //Инициализируем кнопки 1-4
timer_init(); //Инициализируем таймер 3
uint32_t last_state = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11);
for(;;)
{
uint32_t curr_state = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11); //cчитываем логическое состояние вывода 11
if (curr_state != last_state) //если произошла смена state
{
TIM_Cmd(TIM3, DISABLE);
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_SET); //LED off (setting 1 in BSRR)
if (curr_state)
{
a = UINT16_MAX;
}
else
{
if (TIM_GetCounter(TIM3) >= IN_MS_TO_POPUGAIS(100)) { a = TIM_GetCounter(TIM3);}
}
TIM_SetCounter(TIM3, 0);
TIM_SetAutoreload(TIM3, a);
TIM_Cmd(TIM3, ENABLE);
}
last_state = curr_state;
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_6))
{b=IN_MS_TO_POPUGAIS(2000);}
else if (GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_14))
{b=IN_MS_TO_POPUGAIS(3500);}
else if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5))
{b=IN_MS_TO_POPUGAIS(5000);}
else
{b=IN_MS_TO_POPUGAIS(500);}
};
}
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update))
{
TIM_ClearFlag(TIM3, TIM_IT_Update);
// Считываем логическое состояние вывода светодиода и инвертируем состояние
if ( GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_13) ) //Если диод НЕ горит (it's pushed up by def)
{
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_RESET); //Reset13 сбрось и тем самым зажги (состояние b)
TIM_SetAutoreload(TIM3, b); //arr тут может меняться
}
else
{
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_SET); //Set13 и выключи (состояние а)
TIM_SetAutoreload(TIM3, a);
}
}
}
void led_init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
// настраиваем LED как выход (push/pull out speed 2MHz) RM p.160
GPIO_InitTypeDef gpio_init;
gpio_init.GPIO_Pin = GPIO_Pin_13; // | GPIO_Pin_15; if needed
gpio_init.GPIO_Speed = GPIO_Speed_2MHz;
gpio_init.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC, &gpio_init);
}
void buttons_init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef gpio1_init;
gpio1_init.GPIO_Pin = GPIO_Pin_11;
gpio1_init.GPIO_Speed = GPIO_Speed_2MHz;
gpio1_init.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &gpio1_init);
GPIO_InitTypeDef gpio2_init;
gpio2_init.GPIO_Pin = GPIO_Pin_6;
gpio2_init.GPIO_Speed = GPIO_Speed_2MHz;
gpio2_init.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &gpio2_init);
GPIO_InitTypeDef gpio3_init;
gpio3_init.GPIO_Pin = GPIO_Pin_14;
gpio3_init.GPIO_Speed = GPIO_Speed_2MHz;
gpio3_init.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOC, &gpio3_init);
GPIO_InitTypeDef gpio4_init;
gpio4_init.GPIO_Pin = GPIO_Pin_5;
gpio4_init.GPIO_Speed = GPIO_Speed_2MHz;
gpio4_init.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &gpio4_init);
}
void timer_init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseInitTypeDef tim;
tim.TIM_ClockDivision = TIM_CKD_DIV1;
tim.TIM_CounterMode = TIM_CounterMode_Up;
tim.TIM_Prescaler = 36000-1;
tim.TIM_Period = 1000-1;
TIM_TimeBaseInit(TIM3, &tim);
TIM_ITConfig(TIM3,TIM_IT_Update, ENABLE); // Update Interrupt Enable DMA/Interrupt Enable Register
NVIC_InitTypeDef nvicInit;
nvicInit.NVIC_IRQChannel = TIM3_IRQn;
nvicInit.NVIC_IRQChannelCmd = ENABLE;
nvicInit.NVIC_IRQChannelPreemptionPriority = 0;
nvicInit.NVIC_IRQChannelSubPriority = 0;
NVIC_Init(&nvicInit);
TIM_Cmd(TIM3, ENABLE); // Start count
}
|
C
|
#pragma once
#include <arduino.h>
#include "Buffer.h"
#include "Definitions.h"
#include "Functions.h"
#include "PhysicalLayer.h"
#include "Packet.h"
#include <LiquidCrystal.h>
// INITIALIZES THE IO-PINS CORRECTLY
// IN: NONE
// OUT: NONE
void initialize_pins(void);
// CONVERTS CHARACTERS IN HEX TO INTEGERS
// IN: CHAR 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F (FOR EXAMPLE 'F' or 'f' => 15)
// OUT: THIS CHAR AS AN INTEGER OR ZERO IF CHAR IS INVALID
int hexCharToInt(char c);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum Suit {
Clubs=1, Diamonds=1<<1, Hearts=1<<2, Spades=1<<3, Suit_End=1<<4
};
typedef enum Suit Suit;
// Sorry for the Two=0
enum Pips {
Two=0, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace, NumberOfPips
};
typedef enum Pips Pips;
struct Card {
Suit suit;
Pips pips;
};
typedef struct Card Card;
void swapCards( Card* card1, Card* card2)
{
Card buf;
buf.suit = card1->suit;
buf.pips = card1->pips;
card1->suit = card2->suit;
card1->pips = card2->pips;
card2->suit = buf.suit;
card2->pips = buf.pips;
}
#define NoOfCardsInDeck 52
struct Deck {
Card cards[NoOfCardsInDeck];
int topOfDeck;
};
typedef struct Deck Deck;
void initDeck(Deck* deck)
{
int cardCtr = 0;
//For the suits a somewhat unconvential loop is need, since the values are not contigious.
for(int suitCtr = Clubs; suitCtr < Suit_End; suitCtr<<=1)
{
printf("----------------------------------------------------------------\n");
printf("The suitCtr counter is %d.\n", suitCtr);
for(int pipsCtr = 0; pipsCtr < NumberOfPips; ++pipsCtr)
{
printf("Accessing cards index: %d\n", cardCtr);
deck->cards[cardCtr].suit = (Suit)suitCtr;
deck->cards[cardCtr].pips = (Pips)pipsCtr;
++cardCtr;
}
}
deck->topOfDeck = NoOfCardsInDeck - 1;
}
void shuffleDeck(Deck* deck)
{
int indexOfCardToSwap = 0;
for(int i=0; i<NoOfCardsInDeck; ++i)
{
indexOfCardToSwap = rand() % NoOfCardsInDeck;
swapCards(&deck->cards[i],&deck->cards[indexOfCardToSwap]);
}
}
struct Hand
{
// This data structure encodes the information which particular cards are in a hand.
// The array index corresponds to the pip value of a card.
// The array value will be the sum of the corresponding suit values, which are
// present in the hand.
// Examples:
// The hand does not have a TWO:
// availableCards[Two] = 0;
// The hand has one queen, which is Hearts:
// availableCards[Queen] = Hearts;
// The hand has two tens, Diamonds and Clubs:
// availableCards[Ten] = Diamonds + Clubs;
int availableCards[NumberOfPips];
};
typedef struct Hand Hand;
#define NoOfCardsPerHand 7
void initHand(Hand* hand)
{
int idx = 0;
for( ; idx<NumberOfPips; ++idx)
{
hand->availableCards[idx] = 0;
}
}
void resetHand(Hand* hand)
{
initHand(hand);
}
int nextPip(Pips initialPips)
{
Pips nextPips = initialPips + 1;
if(NumberOfPips==nextPips){
nextPips=Two;
}
return nextPips;
}
int checkStraightFlushFrom(Hand* hand, Pips startingPips)
{
int checkValue = hand->availableCards[startingPips];
Pips currentPips = startingPips;
for(int numberOfCardsChecked=1; numberOfCardsChecked<5; ++numberOfCardsChecked)
{
if(0==checkValue) {
break;
}
currentPips = nextPip(currentPips);
checkValue &= hand->availableCards[currentPips];
}
return checkValue;
}
// Return value will be > 0 if it is a royal flush
// and 0 if it is not.
int isRoyalFlush(Hand* hand)
{
return checkStraightFlushFrom(hand,Ten);
}
int isStraightFlush(Hand* hand)
{
for(Pips startingPip=Two; startingPip<NumberOfPips;++startingPip)
{
int result = checkStraightFlushFrom(hand,startingPip);
if(result>0) {
return result;
}
}
return 0;
}
/* Implementation of checks for encoded integer values as used in hand->availableCards array.*/
// Clubs=1, Diamonds=1<<1, Hearts=1<<2, Spades=1<<3, Suit_End=1<<4
// Will return 1, if the encodedPipsValue contains the given suit.
// Otherwise it will return 0
int hasSuit(Suit suit, int encodedPipsValue)
{
if(encodedPipsValue & suit)
{
return 1;
}
return 0;
}
/* Will Return 1 if there are more than 4 cards of a single suit. Otherwise it will return 0. */
int isFlush(Hand* hand)
{
int numberOfClubs = 0;
int numberOfDiamonds = 0;
int numberOfHearts = 0;
int numberOfSpades = 0;
for(Pips currentPip=Two; currentPip<NumberOfPips;++currentPip)
{
numberOfClubs += hasSuit(Clubs,hand->availableCards[currentPip]);
numberOfDiamonds += hasSuit(Diamonds,hand->availableCards[currentPip]);
numberOfHearts += hasSuit(Hearts,hand->availableCards[currentPip]);
numberOfSpades += hasSuit(Spades,hand->availableCards[currentPip]);
}
if( numberOfClubs > 4 || numberOfDiamonds > 4 || numberOfHearts > 4 || numberOfSpades > 4)
{
return 1;
}
return 0;
}
void addCardToHand(Hand* hand, Card* card)
{
hand->availableCards[card->pips] += card->suit;
}
void giveOutHand(Deck* deck, Hand* hand)
{
resetHand(hand);
if( deck->topOfDeck < NoOfCardsPerHand-1) {
printf( "Could not give out hand. Not enought cards on deck." );
return;
}
for(int i=0; i<NoOfCardsPerHand; ++i)
{
addCardToHand(hand, &deck->cards[deck->topOfDeck]);
--deck->topOfDeck;
}
}
enum HandCombinations {
ROYAL_FLUSH = 0,
STRAIGHT_FLUSH,
FOUR_OF_A_KIND,
FULL_HOUSE,
FLUSH,
STRAIGHT,
THREE_OF_A_KIND,
TWO_PAIR,
PAIR,
NO_PAIR,
NO_HAND_COMBINATIONS
};
typedef enum HandCombinations HandCombinations;
struct PokerStats
{
int occurenceOfHandCombination[NO_HAND_COMBINATIONS];
int totalNumberOfHands;
};
typedef struct PokerStats PokerStats;
void initPokerStats(PokerStats* pokerStats)
{
for(int i=0; i<NO_HAND_COMBINATIONS; ++i)
{
pokerStats->occurenceOfHandCombination[i] = 0;
}
pokerStats->totalNumberOfHands = 0;
}
void addHandToStats(PokerStats* pokerStats, Hand* hand)
{
}
int main(int argc, char**argv)
{
srand (time (NULL));
printf("Hello world!");
Deck deck;
initDeck(&deck);
shuffleDeck(&deck);
Hand hand;
initHand(&hand);
giveOutHand(&deck,&hand);
return 0;
}
|
C
|
/**
* @file stsprite.h
*
* STFM Sprite kernel for GCC
* @author (c) 2008/2009/2018/2019 by Simon Sunnyboy / Paradize
* @copyright http://paradize.atari.org/
*
* Special thanks and acknowledgements:
* -- ggn / Paradize (for writing the Blitter sprite routine for HOG mode
* and for finding the bugfix of the halftone mode)
* -- Paranoid / Paradox (for helping me making SHARED MODE work)
* -- PeP (for finding a serious bug which did lead to strange effects)
* -- LP (for helping debugging the Halftone mode bug)
*
* Version 0.5a 24.03.2008 (different interface)
* Version 0.9 25.03.2008
* Version 0.99 06.06.2008 (beta version with support for Blitter)
* Version 1.00 25.02.2009 (first release version - Halftone mode bugfix)
* 10.04.2018 (gcc port)
*
* Draws up to 16 sprites with different sizes on screen
*
* The routine uses screen format so you can directly take sprites from
* a DEGAS picture.
*
* NO CLIPPING OF SPRITES!
*/
/** @addtogroup STSprite
* @{
*/
#ifndef STSPRITE_H
#define STSPRITE_H
#include <stdint.h>
/**
* @brief sprite handling object
*/
typedef struct
{
uint16_t active; /**< flag !=0 means: draw sprite */
uint16_t x; /**< x coordinate */
uint16_t y; /**< y coordinate */
uint16_t width; /**< width of sprite in 16pixel steps, e.q. 1 <=> 16 pixels, 2 <=> 32 pixels */
uint16_t height; /**< height of sprite in scanlines */
void *maskptr; /**< pointer to sprite mask (data in ST-LOW screen format) */
void *spriteptr; /**< pointer to sprite data (data in ST-LOW screen format) */
} st_sprite_t;
enum stsprite_blitter_mode
{
STSPRITE_USE_CPU = 0, /**< ... */
STSPRITE_USE_HOGMODE = 1, /**< ... */
STSPRITE_USE_SHAREDMODE = 2 /**< ... */
};
/**
* @brief draws given list of sprites on screen
* @details The destination screen address must have been set before with STSprite_SetLogbase
* @param spr_list points to sprite records
* @param nr_of_sprites_in_list contains number of available sprite records in list
*/
void STSprite_HandleDrawing ( st_sprite_t * spr_list, uint16_t nr_of_sprites_in_list );
/**
* @brief set destination screen address in RAM for all drawing routines
* @param dest_screen_ptr
*/
void STSprite_SetLogbase ( void * dest_screen_ptr );
/**
* @brief draw given sprite to screen using CPU routines
* @param sprdata points to sprite to be drawn (active setting is ignored)
*/
void STSprite_DrawCPU ( st_sprite_t * sprdata );
/**
* @brief draw given sprite to screen using Blitter in SHARED mode
* @attention Availability of Blitter is not checked!
* @param sprdata points to sprite to be drawn (active setting is ignored)
*/
void STSprite_DrawBlitter ( st_sprite_t * sprdata );
/**
* @brief draw given sprite to screen using Blitter in HOG mode
* @attention Availability of Blitter is not checked!
* @param sprdata points to sprite to be drawn (active setting is ignored)
*/
void STSprite_DrawBlitterHog ( st_sprite_t * sprdata );
/**
* @brief configure sprite drawing routine used by STSprite_HandleDrawing
* @param stsprite_blitter_mode according to STSPRITE_USE_... enums
*/
void STSprite_SetBlitterMode ( uint16_t stsprite_blitter_mode );
#endif
/** @} */
|
C
|
/*
** EPITECH PROJECT, 2017
** liblist
** File description:
** Created by antoine_dh,
*/
#include "list.h"
int list_delete_matching_nodes(list_t **begin, list_match_t match,
list_del_t del, ...)
{
va_list ap;
va_list cpy;
list_t *tmp = *begin;
int num = 0;
va_start(ap, del);
while (tmp != NULL) {
va_copy(cpy, ap);
if (match(tmp, &cpy)) {
list_delete_node(begin, tmp, del);
tmp = *begin;
num++;
} else
tmp = tmp->next;
va_end(cpy);
}
va_end(ap);
return (num);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void rotate(char matrix[10][10]) {
int size = 10;
// 1st: flip horizontally
int ptrLeft, ptrRight;
char tmp;
for (int i = 0; i < size; i++) {
ptrLeft = 0;
ptrRight = size - 1;
// swap
while (ptrLeft < ptrRight) {
tmp = matrix[i][ptrLeft];
matrix[i][ptrLeft] = matrix[i][ptrRight];
matrix[i][ptrRight] = tmp;
ptrLeft++;
ptrRight--;
}
}
// 2nd: flip diagonally
int new_x, new_y;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 1 - i; j++) {
new_x = size - 1 - j;
new_y = size - 1 - i;
// swap
tmp = matrix[i][j];
matrix[i][j] = matrix[new_x][new_y];
matrix[new_x][new_y] = tmp;
}
}
}
/*
* return 10 * 10 matrix by reading the input file
*/
void readMatrix(char matrix[10][10], char * fileName) {
int row = 0, col = 0, size = 10;
FILE * f = fopen(fileName, "r");
int c;
if (f == NULL) {
// file error handling
fprintf(stderr, "Error in opening files\n" );
exit(EXIT_FAILURE);
}
// filling the matrix
while ((c = fgetc(f)) != EOF) {
if (c == '\n') {
// error handling: when there is new line -> col != 10
if (col != size) {
fprintf(stderr, "Incorrect column number\n" );
exit(EXIT_FAILURE);
}
row++;
col = 0;
continue;
}
if (row >= size) {
// error handling: when the row exceed 10 with early jump out
fprintf(stderr, "inner Incorrect row number\n" );
exit(EXIT_FAILURE);
}
matrix[row][col] = (char)c;
col++;
}
if (row != size) {
// error handling: row not enough
printf("%d\n", row);
fprintf(stderr, "Out Incorrect row number\n" );
exit(EXIT_FAILURE);
}
if (fclose(f) != 0) {
// file error handling
fprintf(stderr, "Error in closing files\n" );
exit(EXIT_FAILURE);
}
}
void printMatrix(char matrix[10][10]) {
int size = 10;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%c", matrix[i][j]);
}
printf("\n");
}
}
int main(int argc, char ** argv) {
if (argc != 2) {
fprintf(stderr, "Error in command line argument.\n");
exit(EXIT_FAILURE);
}
char matrix[10][10];
char * fileName = argv[1];
readMatrix(matrix, fileName);
rotate(matrix);
printMatrix(matrix);
}
|
C
|
/* File Color.h
* Defines a structure for holding RGBA color information that can be accessed
* in 3 different formats.
*
*
*/
#ifndef COLOR_H
#define COLOR_H
#include "stdtypes.h"
// in memory: r g b a
typedef union Color
{
// Allows direct access to individual components.
struct{
U8 r;
U8 g;
U8 b;
U8 a;
};
// Allows the color to be moved around like an integer.
U32 integer;
// Allows color component indexing like an array.
U8 rgba[4];
U8 rgb[3];
} Color;
typedef union Color565
{
// Allows the color to be moved around like an integer.
U16 integer;
// Allows direct access to individual components.
struct{
U16 b:5;
U16 g:6;
U16 r:5;
};
} Color565;
#define COLOR_CAST(integer) *(Color*)&integer
// Color constructors
static INLINEDBG Color CreateColor(U8 r, U8 g, U8 b, U8 a)
{
Color c;
c.r = r;
c.g = g;
c.b = b;
c.a = a;
return c;
}
static INLINEDBG Color colorFromU8(U8 *rgba)
{
Color c;
c.r = rgba[0];
c.g = rgba[1];
c.b = rgba[2];
c.a = rgba[3];
return c;
}
static INLINEDBG void setColorFromARGB(Color *c, int argb)
{
c->b = argb & 0xff;
c->g = (argb >> 8) & 0xff;
c->r = (argb >> 16) & 0xff;
c->a = (argb >> 24) & 0xff;
}
static INLINEDBG void setColorFromABGR(Color *c, int abgr)
{
c->r = abgr & 0xff;
c->g = (abgr >> 8) & 0xff;
c->b = (abgr >> 16) & 0xff;
c->a = (abgr >> 24) & 0xff;
}
static INLINEDBG U32 ARGBFromColor(Color c)
{
return (c.a << 24) | (c.r << 16) | (c.g << 8) | (c.b);
}
static INLINEDBG Color ARGBToColor(int argb)
{
Color c;
setColorFromARGB(&c, argb);
return c;
}
static INLINEDBG U32 RGBAFromColor(Color c)
{
return (c.r << 24) | (c.g << 16) | (c.b << 8) | (c.a);
}
static INLINEDBG void setColorFromRGBA(Color *c, int rgba)
{
c->a = rgba & 0xff;
c->b = (rgba >> 8) & 0xff;
c->g = (rgba >> 16) & 0xff;
c->r = (rgba >> 24) & 0xff;
}
static INLINEDBG Color CreateColorRGB(U8 r, U8 g, U8 b)
{
Color c;
c.r = r;
c.g = g;
c.b = b;
c.a = 255;
return c;
}
Color colorFlip( Color c );
int colorEqualsIgnoreAlpha( Color c1, Color c2 );
static INLINEDBG F32 colorComponentToF32(U8 c)
{
static const F32 U8TOF32_COLOR = 1.f / 255.f;
return c * U8TOF32_COLOR;
}
static INLINEDBG void colorToVec4(Vec4 vec, const Color clr)
{
vec[0] = colorComponentToF32(clr.r);
vec[1] = colorComponentToF32(clr.g);
vec[2] = colorComponentToF32(clr.b);
vec[3] = colorComponentToF32(clr.a);
}
static INLINEDBG void u8ColorToVec4(Vec4 vec, const U8 *clr)
{
vec[0] = colorComponentToF32(clr[0]);
vec[1] = colorComponentToF32(clr[1]);
vec[2] = colorComponentToF32(clr[2]);
vec[3] = colorComponentToF32(clr[3]);
}
static INLINEDBG void colorToVec3(Vec3 vec, const Color clr)
{
vec[0] = colorComponentToF32(clr.r);
vec[1] = colorComponentToF32(clr.g);
vec[2] = colorComponentToF32(clr.b);
}
static INLINEDBG void u8ColorToVec3(Vec3 vec, const U8 *clr)
{
vec[0] = colorComponentToF32(clr[0]);
vec[1] = colorComponentToF32(clr[1]);
vec[2] = colorComponentToF32(clr[2]);
}
void vec4ToColor(Color *clr, const Vec4 vec);
void vec3ToColor(Color *clr, const Vec3 vec);
U32 darkenColorRGBA(U32 rgba, int amount);
U32 lightenColorRGBA(U32 rgba, int amount);
typedef struct ColorPair
{
Color primary;
Color secondary;
} ColorPair;
extern ColorPair colorPairNone;
extern Color ColorRed;
extern Color ColorBlue;
extern Color ColorGreen;
extern Color ColorWhite;
extern Color ColorBlack;
extern Color ColorLightRed;
extern Color ColorOrange;
extern Color ColorNull;
#endif
|
C
|
/**
* Author: Will Cook
* [email protected]
* Date: 2020/08/19
*
* A simple hello world program in C
*
*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
printf("Will Cook\n");
printf("Computer Science\n");
return 0;
}
|
C
|
#include <stdio.h>
#define N 100
void loop_fusion05( int a[N], int b[N]) {
int i,j;
/* The first loop can't be fused */
for( i=0; i<N; i++ ) {
a[i] = i;
}
for( j=0; j<N; j++ ) {
b[j] += a[j+1];
}
printf("Is j initialized ? %d\n",j);
}
|
C
|
#include <stdio.h>
int main()
{
char *p, str[80];
printf("Enter a string: ");
p = gets(str);
if(p) printf("%s %s", p,str);
return 0;
}
|
C
|
#include<stdio.h>
int main(void)
{
int count=1;
char i,j,k,l;
printf("The result of ballot is:\n");
for(i='W';i<='Z';i++)
{
for(j='W';j<='Z';j++)
{
if(i!=j)
{
for(k='W';k<='Z';k++)
{
if(i!=k&&j!=k)
{
for(l='W';l<='Z';l++)
{
if(l!=i&&l!=j&&l!=k)
{
if(i!='X'&&k!='X'&&k!='Z'&&l!='W')
{
printf("Group %d:\nA VS %c\nB VS %c\nC VS %c\nD VS %c\n\n",count,i,j,k,l);
count++;
}
}
}
}
}
}
}
}
printf("There are %d ways to assign the players.",count);
}
|
C
|
/* ptrptr5.c */
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *text[500];
char str1[] = "Text1";
char str2[] = "Text2";
char str3[] = "Text3";
text[0] = str1;
text[1] = str2;
text[2] = str3;
printf("%s %s %s\n", text[0], text[1], text[2]);
return EXIT_SUCCESS;
}
|
C
|
/* SCCS Id: @(#)cvtsnd.c 3.1 93/1/28 */
/* Copyright (c) 1993 by Gregg Wonderly */
/* NetHack may be freely redistributed. See license for details. */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <exec/types.h>
void process_snd( char *, char * );
char *basename( char * );
typedef struct AIFFHEAD
{
short namelen;
char name[62];
short leneq64;
char form[4];
char stuff[10+16+32];
char FORM[4];
long flen;
char AIFF[4];
char SSND[4];
long sndlen;
} AIFFHEAD;
typedef struct VHDR
{
char name[4];
long len;
unsigned long oneshot, repeat, samples;
UWORD freq;
UBYTE n_octaves, compress;
LONG volume;
} VHDR;
typedef struct IFFHEAD
{
char FORM[4];
long flen;
char _8SVX[4];
VHDR vhdr;
} IFFHEAD;
main( argc, argv )
int argc;
char **argv;
{
if( argc != 3 )
{
fprintf( stderr, "usage: %s source-file dest-file\n", argv[ 0 ] );
exit( 1 );
}
process_snd( argv[1], argv[2] );
}
void
process_snd( src, dest )
char *src, *dest;
{
int n;
AIFFHEAD aih;
IFFHEAD ih;
long len;
int fd, nfd;
char buf[ 300 ];
fd = open( src, 0 );
if( fd == -1 )
{
perror( src );
return;
}
read( fd, &aih, sizeof( aih ) );
nfd = creat( dest, 0777 );
memcpy( ih.FORM, "FORM", 4 );
memcpy( ih._8SVX, "8SVX", 4 );
ih.flen = aih.sndlen + sizeof( IFFHEAD ) + 8;
memcpy( ih.vhdr.name, "VHDR", 4 );
ih.vhdr.len = 20;
ih.vhdr.oneshot = aih.sndlen;
ih.vhdr.repeat = 0;
ih.vhdr.samples = 0;
ih.vhdr.freq = 22000;
ih.vhdr.n_octaves = 1;
ih.vhdr.compress = 0;
ih.vhdr.volume = 0x10000;
write( nfd, &ih, sizeof( ih ) );
write( nfd, "NAME", 4 );
len = aih.namelen;
write( nfd, &len, 4 );
write( nfd, aih.name, ( strlen( aih.name ) + 1 ) & ~1 );
write( nfd, "BODY", 4 );
write( nfd, &aih.sndlen, 4 );
while( ( n = read( fd, buf, sizeof( buf ) ) ) > 0 )
write( nfd, buf, n );
close( fd );
close( nfd );
}
char *basename( str )
char *str;
{
char *t;
if( t = strrchr( str, '/' ) )
return(t);
if( t = strrchr( str, ':' ) )
return(t);
return( str );
}
|
C
|
// stb_connected_components - v0.95 - public domain connected components on grids
// http://github.com/nothings/stb
//
// Finds connected components on 2D grids for testing reachability between
// two points, with fast updates when changing reachability (e.g. on one machine
// it was typically 0.2ms w/ 1024x1024 grid). Each grid square must be "open" or
// "closed" (traversable or untraversable), and grid squares are only connected
// to their orthogonal neighbors, not diagonally.
//
// In one source file, create the implementation by doing something like this:
//
// #define STBCC_GRID_COUNT_X_LOG2 10
// #define STBCC_GRID_COUNT_Y_LOG2 10
// #define STB_CONNECTED_COMPONENTS_IMPLEMENTATION
// #include "stb_connected_components.h"
//
// The above creates an implementation that can run on maps up to 1024x1024.
// Map sizes must be a multiple of (1<<(LOG2/2)) on each axis (e.g. 32 if LOG2=10,
// 16 if LOG2=8, etc.) (You can just pad your map with untraversable space.)
//
// MEMORY USAGE
//
// Uses about 6-7 bytes per grid square (e.g. 7MB for a 1024x1024 grid).
// Uses a single worst-case allocation which you pass in.
//
// PERFORMANCE
//
// On a core i7-2700K at 3.5 Ghz, for a particular 1024x1024 map (map_03.png):
//
// Creating map : 44.85 ms
// Making one square traversable: 0.27 ms (average over 29,448 calls)
// Making one square untraversable: 0.23 ms (average over 30,123 calls)
// Reachability query: 0.00001 ms (average over 4,000,000 calls)
//
// On non-degenerate maps update time is O(N^0.5), but on degenerate maps like
// checkerboards or 50% random, update time is O(N^0.75) (~2ms on above machine).
//
// CHANGELOG
//
// 0.95 (2016-10-16) Bugfix if multiple clumps in one cluster connect to same clump in another
// 0.94 (2016-04-17) Bugfix & optimize worst case (checkerboard & random)
// 0.93 (2016-04-16) Reduce memory by 10x for 1Kx1K map; small speedup
// 0.92 (2016-04-16) Compute sqrt(N) cluster size by default
// 0.91 (2016-04-15) Initial release
//
// TODO:
// - better API documentation
// - more comments
// - try re-integrating naive algorithm & compare performance
// - more optimized batching (current approach still recomputes local clumps many times)
// - function for setting a grid of squares at once (just use batching)
//
// LICENSE
//
// See end of file for license information.
//
// ALGORITHM
//
// The NxN grid map is split into sqrt(N) x sqrt(N) blocks called
// "clusters". Each cluster independently computes a set of connected
// components within that cluster (ignoring all connectivity out of
// that cluster) using a union-find disjoint set forest. This produces a bunch
// of locally connected components called "clumps". Each clump is (a) connected
// within its cluster, (b) does not directly connect to any other clumps in the
// cluster (though it may connect to them by paths that lead outside the cluster,
// but those are ignored at this step), and (c) maintains an adjacency list of
// all clumps in adjacent clusters that it _is_ connected to. Then a second
// union-find disjoint set forest is used to compute connected clumps
// globally, across the whole map. Reachability is then computed by
// finding which clump each input point belongs to, and checking whether
// those clumps are in the same "global" connected component.
//
// The above data structure can be updated efficiently; on a change
// of a single grid square on the map, only one cluster changes its
// purely-local state, so only one cluster needs its clumps fully
// recomputed. Clumps in adjacent clusters need their adjacency lists
// updated: first to remove all references to the old clumps in the
// rebuilt cluster, then to add new references to the new clumps. Both
// of these operations can use the existing "find which clump each input
// point belongs to" query to compute that adjacency information rapidly.
#ifndef INCLUDE_STB_CONNECTED_COMPONENTS_H
#define INCLUDE_STB_CONNECTED_COMPONENTS_H
#include <stdlib.h>
typedef struct st_stbcc_grid stbcc_grid;
#ifdef __cplusplus
extern "C" {
#endif
//////////////////////////////////////////////////////////////////////////////////////////
//
// initialization
//
// you allocate the grid data structure to this size (note that it will be very big!!!)
extern size_t stbcc_grid_sizeof(void);
// initialize the grid, value of map[] is 0 = traversable, non-0 is solid
extern void stbcc_init_grid(stbcc_grid *g, unsigned char *map, int w, int h);
//////////////////////////////////////////////////////////////////////////////////////////
//
// main functionality
//
// update a grid square state, 0 = traversable, non-0 is solid
// i can add a batch-update if it's needed
extern void stbcc_update_grid(stbcc_grid *g, int x, int y, int solid);
// query if two grid squares are reachable from each other
extern int stbcc_query_grid_node_connection(stbcc_grid *g, int x1, int y1, int x2, int y2);
//////////////////////////////////////////////////////////////////////////////////////////
//
// bonus functions
//
// wrap multiple stbcc_update_grid calls in these function to compute
// multiple updates more efficiently; cannot make queries inside batch
extern void stbcc_update_batch_begin(stbcc_grid *g);
extern void stbcc_update_batch_end(stbcc_grid *g);
// query the grid data structure for whether a given square is open or not
extern int stbcc_query_grid_open(stbcc_grid *g, int x, int y);
// get a unique id for the connected component this is in; it's not necessarily
// small, you'll need a hash table or something to remap it (or just use
extern unsigned int stbcc_get_unique_id(stbcc_grid *g, int x, int y);
#define STBCC_NULL_UNIQUE_ID 0xffffffff // returned for closed map squares
#ifdef __cplusplus
}
#endif
#endif // INCLUDE_STB_CONNECTED_COMPONENTS_H
#ifdef STB_CONNECTED_COMPONENTS_IMPLEMENTATION
#include <assert.h>
#include <string.h> // memset
#if !defined(STBCC_GRID_COUNT_X_LOG2) || !defined(STBCC_GRID_COUNT_Y_LOG2)
#error "You must define STBCC_GRID_COUNT_X_LOG2 and STBCC_GRID_COUNT_Y_LOG2 to define the max grid supported."
#endif
#define STBCC__GRID_COUNT_X (1 << STBCC_GRID_COUNT_X_LOG2)
#define STBCC__GRID_COUNT_Y (1 << STBCC_GRID_COUNT_Y_LOG2)
#define STBCC__MAP_STRIDE (1 << (STBCC_GRID_COUNT_X_LOG2-3))
#ifndef STBCC_CLUSTER_SIZE_X_LOG2
#define STBCC_CLUSTER_SIZE_X_LOG2 (STBCC_GRID_COUNT_X_LOG2/2) // log2(sqrt(2^N)) = 1/2 * log2(2^N)) = 1/2 * N
#if STBCC_CLUSTER_SIZE_X_LOG2 > 6
#undef STBCC_CLUSTER_SIZE_X_LOG2
#define STBCC_CLUSTER_SIZE_X_LOG2 6
#endif
#endif
#ifndef STBCC_CLUSTER_SIZE_Y_LOG2
#define STBCC_CLUSTER_SIZE_Y_LOG2 (STBCC_GRID_COUNT_Y_LOG2/2)
#if STBCC_CLUSTER_SIZE_Y_LOG2 > 6
#undef STBCC_CLUSTER_SIZE_Y_LOG2
#define STBCC_CLUSTER_SIZE_Y_LOG2 6
#endif
#endif
#define STBCC__CLUSTER_SIZE_X (1 << STBCC_CLUSTER_SIZE_X_LOG2)
#define STBCC__CLUSTER_SIZE_Y (1 << STBCC_CLUSTER_SIZE_Y_LOG2)
#define STBCC__CLUSTER_COUNT_X_LOG2 (STBCC_GRID_COUNT_X_LOG2 - STBCC_CLUSTER_SIZE_X_LOG2)
#define STBCC__CLUSTER_COUNT_Y_LOG2 (STBCC_GRID_COUNT_Y_LOG2 - STBCC_CLUSTER_SIZE_Y_LOG2)
#define STBCC__CLUSTER_COUNT_X (1 << STBCC__CLUSTER_COUNT_X_LOG2)
#define STBCC__CLUSTER_COUNT_Y (1 << STBCC__CLUSTER_COUNT_Y_LOG2)
#if STBCC__CLUSTER_SIZE_X >= STBCC__GRID_COUNT_X || STBCC__CLUSTER_SIZE_Y >= STBCC__GRID_COUNT_Y
#error "STBCC_CLUSTER_SIZE_X/Y_LOG2 must be smaller than STBCC_GRID_COUNT_X/Y_LOG2"
#endif
// worst case # of clumps per cluster
#define STBCC__MAX_CLUMPS_PER_CLUSTER_LOG2 (STBCC_CLUSTER_SIZE_X_LOG2 + STBCC_CLUSTER_SIZE_Y_LOG2-1)
#define STBCC__MAX_CLUMPS_PER_CLUSTER (1 << STBCC__MAX_CLUMPS_PER_CLUSTER_LOG2)
#define STBCC__MAX_CLUMPS (STBCC__MAX_CLUMPS_PER_CLUSTER * STBCC__CLUSTER_COUNT_X * STBCC__CLUSTER_COUNT_Y)
#define STBCC__NULL_CLUMPID STBCC__MAX_CLUMPS_PER_CLUSTER
#define STBCC__CLUSTER_X_FOR_COORD_X(x) ((x) >> STBCC_CLUSTER_SIZE_X_LOG2)
#define STBCC__CLUSTER_Y_FOR_COORD_Y(y) ((y) >> STBCC_CLUSTER_SIZE_Y_LOG2)
#define STBCC__MAP_BYTE_MASK(x,y) (1 << ((x) & 7))
#define STBCC__MAP_BYTE(g,x,y) ((g)->map[y][(x) >> 3])
#define STBCC__MAP_OPEN(g,x,y) (STBCC__MAP_BYTE(g,x,y) & STBCC__MAP_BYTE_MASK(x,y))
typedef unsigned short stbcc__clumpid;
typedef unsigned char stbcc__verify_max_clumps[STBCC__MAX_CLUMPS_PER_CLUSTER < (1 << (8*sizeof(stbcc__clumpid))) ? 1 : -1];
#define STBCC__MAX_EXITS_PER_CLUSTER (STBCC__CLUSTER_SIZE_X + STBCC__CLUSTER_SIZE_Y) // 64 for 32x32
#define STBCC__MAX_EXITS_PER_CLUMP (STBCC__CLUSTER_SIZE_X + STBCC__CLUSTER_SIZE_Y) // 64 for 32x32
#define STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER (STBCC__MAX_EXITS_PER_CLUMP)
// 2^19 * 2^6 => 2^25 exits => 2^26 => 64MB for 1024x1024
// Logic for above on 4x4 grid:
//
// Many clumps: One clump:
// + + + +
// +X.X. +XX.X+
// .X.X+ .XXX
// +X.X. XXX.
// .X.X+ +X.XX+
// + + + +
//
// 8 exits either way
typedef unsigned char stbcc__verify_max_exits[STBCC__MAX_EXITS_PER_CLUMP <= 256];
typedef struct
{
unsigned short clump_index:12;
signed short cluster_dx:2;
signed short cluster_dy:2;
} stbcc__relative_clumpid;
typedef union
{
struct {
unsigned int clump_index:12;
unsigned int cluster_x:10;
unsigned int cluster_y:10;
} f;
unsigned int c;
} stbcc__global_clumpid;
// rebuilt cluster 3,4
// what changes in cluster 2,4
typedef struct
{
stbcc__global_clumpid global_label; // 4
unsigned char num_adjacent; // 1
unsigned char max_adjacent; // 1
unsigned char adjacent_clump_list_index; // 1
unsigned char reserved;
} stbcc__clump; // 8
#define STBCC__CLUSTER_ADJACENCY_COUNT (STBCC__MAX_EXITS_PER_CLUSTER*2)
typedef struct
{
short num_clumps;
unsigned char num_edge_clumps;
unsigned char rebuild_adjacency;
stbcc__clump clump[STBCC__MAX_CLUMPS_PER_CLUSTER]; // 8 * 2^9 = 4KB
stbcc__relative_clumpid adjacency_storage[STBCC__CLUSTER_ADJACENCY_COUNT]; // 256 bytes
} stbcc__cluster;
struct st_stbcc_grid
{
int w,h,cw,ch;
int in_batched_update;
//unsigned char cluster_dirty[STBCC__CLUSTER_COUNT_Y][STBCC__CLUSTER_COUNT_X]; // could bitpack, but: 1K x 1K => 1KB
unsigned char map[STBCC__GRID_COUNT_Y][STBCC__MAP_STRIDE]; // 1K x 1K => 1K x 128 => 128KB
stbcc__clumpid clump_for_node[STBCC__GRID_COUNT_Y][STBCC__GRID_COUNT_X]; // 1K x 1K x 2 = 2MB
stbcc__cluster cluster[STBCC__CLUSTER_COUNT_Y][STBCC__CLUSTER_COUNT_X]; // 1K x 4.5KB = 4.5MB
};
int stbcc_query_grid_node_connection(stbcc_grid *g, int x1, int y1, int x2, int y2)
{
stbcc__global_clumpid label1, label2;
stbcc__clumpid c1 = g->clump_for_node[y1][x1];
stbcc__clumpid c2 = g->clump_for_node[y2][x2];
int cx1 = STBCC__CLUSTER_X_FOR_COORD_X(x1);
int cy1 = STBCC__CLUSTER_Y_FOR_COORD_Y(y1);
int cx2 = STBCC__CLUSTER_X_FOR_COORD_X(x2);
int cy2 = STBCC__CLUSTER_Y_FOR_COORD_Y(y2);
assert(!g->in_batched_update);
if (c1 == STBCC__NULL_CLUMPID || c2 == STBCC__NULL_CLUMPID)
return 0;
label1 = g->cluster[cy1][cx1].clump[c1].global_label;
label2 = g->cluster[cy2][cx2].clump[c2].global_label;
if (label1.c == label2.c)
return 1;
return 0;
}
int stbcc_query_grid_open(stbcc_grid *g, int x, int y)
{
return STBCC__MAP_OPEN(g, x, y) != 0;
}
unsigned int stbcc_get_unique_id(stbcc_grid *g, int x, int y)
{
stbcc__clumpid c = g->clump_for_node[y][x];
int cx = STBCC__CLUSTER_X_FOR_COORD_X(x);
int cy = STBCC__CLUSTER_Y_FOR_COORD_Y(y);
assert(!g->in_batched_update);
if (c == STBCC__NULL_CLUMPID) return STBCC_NULL_UNIQUE_ID;
return g->cluster[cy][cx].clump[c].global_label.c;
}
typedef struct
{
unsigned char x,y;
} stbcc__tinypoint;
typedef struct
{
stbcc__tinypoint parent[STBCC__CLUSTER_SIZE_Y][STBCC__CLUSTER_SIZE_X]; // 32x32 => 2KB
stbcc__clumpid label[STBCC__CLUSTER_SIZE_Y][STBCC__CLUSTER_SIZE_X];
} stbcc__cluster_build_info;
static void stbcc__build_clumps_for_cluster(stbcc_grid *g, int cx, int cy);
static void stbcc__remove_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy);
static void stbcc__add_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy);
static stbcc__global_clumpid stbcc__clump_find(stbcc_grid *g, stbcc__global_clumpid n)
{
stbcc__global_clumpid q;
stbcc__clump *c = &g->cluster[n.f.cluster_y][n.f.cluster_x].clump[n.f.clump_index];
if (c->global_label.c == n.c)
return n;
q = stbcc__clump_find(g, c->global_label);
c->global_label = q;
return q;
}
typedef struct
{
unsigned int cluster_x;
unsigned int cluster_y;
unsigned int clump_index;
} stbcc__unpacked_clumpid;
static void stbcc__clump_union(stbcc_grid *g, stbcc__unpacked_clumpid m, int x, int y, int idx)
{
stbcc__clump *mc = &g->cluster[m.cluster_y][m.cluster_x].clump[m.clump_index];
stbcc__clump *nc = &g->cluster[y][x].clump[idx];
stbcc__global_clumpid mp = stbcc__clump_find(g, mc->global_label);
stbcc__global_clumpid np = stbcc__clump_find(g, nc->global_label);
if (mp.c == np.c)
return;
g->cluster[mp.f.cluster_y][mp.f.cluster_x].clump[mp.f.clump_index].global_label = np;
}
static void stbcc__build_connected_components_for_clumps(stbcc_grid *g)
{
int i,j,k,h;
for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j) {
for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i) {
stbcc__cluster *cluster = &g->cluster[j][i];
for (k=0; k < (int) cluster->num_edge_clumps; ++k) {
stbcc__global_clumpid m;
m.f.clump_index = k;
m.f.cluster_x = i;
m.f.cluster_y = j;
assert((int) m.f.clump_index == k && (int) m.f.cluster_x == i && (int) m.f.cluster_y == j);
cluster->clump[k].global_label = m;
}
}
}
for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j) {
for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i) {
stbcc__cluster *cluster = &g->cluster[j][i];
for (k=0; k < (int) cluster->num_edge_clumps; ++k) {
stbcc__clump *clump = &cluster->clump[k];
stbcc__unpacked_clumpid m;
stbcc__relative_clumpid *adj;
m.clump_index = k;
m.cluster_x = i;
m.cluster_y = j;
adj = &cluster->adjacency_storage[clump->adjacent_clump_list_index];
for (h=0; h < clump->num_adjacent; ++h) {
unsigned int clump_index = adj[h].clump_index;
unsigned int x = adj[h].cluster_dx + i;
unsigned int y = adj[h].cluster_dy + j;
stbcc__clump_union(g, m, x, y, clump_index);
}
}
}
}
for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j) {
for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i) {
stbcc__cluster *cluster = &g->cluster[j][i];
for (k=0; k < (int) cluster->num_edge_clumps; ++k) {
stbcc__global_clumpid m;
m.f.clump_index = k;
m.f.cluster_x = i;
m.f.cluster_y = j;
stbcc__clump_find(g, m);
}
}
}
}
static void stbcc__build_all_connections_for_cluster(stbcc_grid *g, int cx, int cy)
{
// in this particular case, we are fully non-incremental. that means we
// can discover the correct sizes for the arrays, but requires we build
// the data into temporary data structures, or just count the sizes, so
// for simplicity we do the latter
stbcc__cluster *cluster = &g->cluster[cy][cx];
unsigned char connected[STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER][STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER/8]; // 64 x 8 => 1KB
unsigned char num_adj[STBCC__MAX_CLUMPS_PER_CLUSTER] = { 0 };
int x = cx * STBCC__CLUSTER_SIZE_X;
int y = cy * STBCC__CLUSTER_SIZE_Y;
int step_x, step_y=0, i, j, k, n, m, dx, dy, total;
int extra;
g->cluster[cy][cx].rebuild_adjacency = 0;
total = 0;
for (m=0; m < 4; ++m) {
switch (m) {
case 0:
dx = 1, dy = 0;
step_x = 0, step_y = 1;
i = STBCC__CLUSTER_SIZE_X-1;
j = 0;
n = STBCC__CLUSTER_SIZE_Y;
break;
case 1:
dx = -1, dy = 0;
i = 0;
j = 0;
step_x = 0;
step_y = 1;
n = STBCC__CLUSTER_SIZE_Y;
break;
case 2:
dy = -1, dx = 0;
i = 0;
j = 0;
step_x = 1;
step_y = 0;
n = STBCC__CLUSTER_SIZE_X;
break;
case 3:
dy = 1, dx = 0;
i = 0;
j = STBCC__CLUSTER_SIZE_Y-1;
step_x = 1;
step_y = 0;
n = STBCC__CLUSTER_SIZE_X;
break;
}
if (cx+dx < 0 || cx+dx >= g->cw || cy+dy < 0 || cy+dy >= g->ch)
continue;
memset(connected, 0, sizeof(connected));
for (k=0; k < n; ++k) {
if (STBCC__MAP_OPEN(g, x+i, y+j) && STBCC__MAP_OPEN(g, x+i+dx, y+j+dy)) {
stbcc__clumpid src = g->clump_for_node[y+j][x+i];
stbcc__clumpid dest = g->clump_for_node[y+j+dy][x+i+dx];
if (0 == (connected[src][dest>>3] & (1 << (dest & 7)))) {
connected[src][dest>>3] |= 1 << (dest & 7);
++num_adj[src];
++total;
}
}
i += step_x;
j += step_y;
}
}
assert(total <= STBCC__CLUSTER_ADJACENCY_COUNT);
// decide how to apportion unused adjacency slots; only clumps that lie
// on the edges of the cluster need adjacency slots, so divide them up
// evenly between those clumps
// we want:
// extra = (STBCC__CLUSTER_ADJACENCY_COUNT - total) / cluster->num_edge_clumps;
// but we efficiently approximate this without a divide, because
// ignoring edge-vs-non-edge with 'num_adj[i]*2' was faster than
// 'num_adj[i]+extra' with the divide
if (total + (cluster->num_edge_clumps<<2) <= STBCC__CLUSTER_ADJACENCY_COUNT)
extra = 4;
else if (total + (cluster->num_edge_clumps<<1) <= STBCC__CLUSTER_ADJACENCY_COUNT)
extra = 2;
else if (total + (cluster->num_edge_clumps<<0) <= STBCC__CLUSTER_ADJACENCY_COUNT)
extra = 1;
else
extra = 0;
total = 0;
for (i=0; i < (int) cluster->num_edge_clumps; ++i) {
int alloc = num_adj[i]+extra;
if (alloc > STBCC__MAX_EXITS_PER_CLUSTER)
alloc = STBCC__MAX_EXITS_PER_CLUSTER;
assert(total < 256); // must fit in byte
cluster->clump[i].adjacent_clump_list_index = (unsigned char) total;
cluster->clump[i].max_adjacent = alloc;
cluster->clump[i].num_adjacent = 0;
total += alloc;
}
assert(total <= STBCC__CLUSTER_ADJACENCY_COUNT);
stbcc__add_connections_to_adjacent_cluster(g, cx, cy, -1, 0);
stbcc__add_connections_to_adjacent_cluster(g, cx, cy, 1, 0);
stbcc__add_connections_to_adjacent_cluster(g, cx, cy, 0,-1);
stbcc__add_connections_to_adjacent_cluster(g, cx, cy, 0, 1);
// make sure all of the above succeeded.
assert(g->cluster[cy][cx].rebuild_adjacency == 0);
}
static void stbcc__add_connections_to_adjacent_cluster_with_rebuild(stbcc_grid *g, int cx, int cy, int dx, int dy)
{
if (cx >= 0 && cx < g->cw && cy >= 0 && cy < g->ch) {
stbcc__add_connections_to_adjacent_cluster(g, cx, cy, dx, dy);
if (g->cluster[cy][cx].rebuild_adjacency)
stbcc__build_all_connections_for_cluster(g, cx, cy);
}
}
void stbcc_update_grid(stbcc_grid *g, int x, int y, int solid)
{
int cx,cy;
if (!solid) {
if (STBCC__MAP_OPEN(g,x,y))
return;
} else {
if (!STBCC__MAP_OPEN(g,x,y))
return;
}
cx = STBCC__CLUSTER_X_FOR_COORD_X(x);
cy = STBCC__CLUSTER_Y_FOR_COORD_Y(y);
stbcc__remove_connections_to_adjacent_cluster(g, cx-1, cy, 1, 0);
stbcc__remove_connections_to_adjacent_cluster(g, cx+1, cy, -1, 0);
stbcc__remove_connections_to_adjacent_cluster(g, cx, cy-1, 0, 1);
stbcc__remove_connections_to_adjacent_cluster(g, cx, cy+1, 0,-1);
if (!solid)
STBCC__MAP_BYTE(g,x,y) |= STBCC__MAP_BYTE_MASK(x,y);
else
STBCC__MAP_BYTE(g,x,y) &= ~STBCC__MAP_BYTE_MASK(x,y);
stbcc__build_clumps_for_cluster(g, cx, cy);
stbcc__build_all_connections_for_cluster(g, cx, cy);
stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx-1, cy, 1, 0);
stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx+1, cy, -1, 0);
stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx, cy-1, 0, 1);
stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx, cy+1, 0,-1);
if (!g->in_batched_update)
stbcc__build_connected_components_for_clumps(g);
#if 0
else
g->cluster_dirty[cy][cx] = 1;
#endif
}
void stbcc_update_batch_begin(stbcc_grid *g)
{
assert(!g->in_batched_update);
g->in_batched_update = 1;
}
void stbcc_update_batch_end(stbcc_grid *g)
{
assert(g->in_batched_update);
g->in_batched_update = 0;
stbcc__build_connected_components_for_clumps(g); // @OPTIMIZE: only do this if update was non-empty
}
size_t stbcc_grid_sizeof(void)
{
return sizeof(stbcc_grid);
}
void stbcc_init_grid(stbcc_grid *g, unsigned char *map, int w, int h)
{
int i,j,k;
assert(w % STBCC__CLUSTER_SIZE_X == 0);
assert(h % STBCC__CLUSTER_SIZE_Y == 0);
assert(w % 8 == 0);
g->w = w;
g->h = h;
g->cw = w >> STBCC_CLUSTER_SIZE_X_LOG2;
g->ch = h >> STBCC_CLUSTER_SIZE_Y_LOG2;
g->in_batched_update = 0;
#if 0
for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j)
for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i)
g->cluster_dirty[j][i] = 0;
#endif
for (j=0; j < h; ++j) {
for (i=0; i < w; i += 8) {
unsigned char c = 0;
for (k=0; k < 8; ++k)
if (map[j*w + (i+k)] == 0)
c |= (1 << k);
g->map[j][i>>3] = c;
}
}
for (j=0; j < g->ch; ++j)
for (i=0; i < g->cw; ++i)
stbcc__build_clumps_for_cluster(g, i, j);
for (j=0; j < g->ch; ++j)
for (i=0; i < g->cw; ++i)
stbcc__build_all_connections_for_cluster(g, i, j);
stbcc__build_connected_components_for_clumps(g);
for (j=0; j < g->h; ++j)
for (i=0; i < g->w; ++i)
assert(g->clump_for_node[j][i] <= STBCC__NULL_CLUMPID);
}
static void stbcc__add_clump_connection(stbcc_grid *g, int x1, int y1, int x2, int y2)
{
stbcc__cluster *cluster;
stbcc__clump *clump;
int cx1 = STBCC__CLUSTER_X_FOR_COORD_X(x1);
int cy1 = STBCC__CLUSTER_Y_FOR_COORD_Y(y1);
int cx2 = STBCC__CLUSTER_X_FOR_COORD_X(x2);
int cy2 = STBCC__CLUSTER_Y_FOR_COORD_Y(y2);
stbcc__clumpid c1 = g->clump_for_node[y1][x1];
stbcc__clumpid c2 = g->clump_for_node[y2][x2];
stbcc__relative_clumpid rc;
assert(cx1 != cx2 || cy1 != cy2);
assert(abs(cx1-cx2) + abs(cy1-cy2) == 1);
// add connection to c2 in c1
rc.clump_index = c2;
rc.cluster_dx = x2-x1;
rc.cluster_dy = y2-y1;
cluster = &g->cluster[cy1][cx1];
clump = &cluster->clump[c1];
assert(clump->num_adjacent <= clump->max_adjacent);
if (clump->num_adjacent == clump->max_adjacent)
g->cluster[cy1][cx1].rebuild_adjacency = 1;
else {
stbcc__relative_clumpid *adj = &cluster->adjacency_storage[clump->adjacent_clump_list_index];
assert(clump->num_adjacent < STBCC__MAX_EXITS_PER_CLUMP);
assert(clump->adjacent_clump_list_index + clump->num_adjacent <= STBCC__CLUSTER_ADJACENCY_COUNT);
adj[clump->num_adjacent++] = rc;
}
}
static void stbcc__remove_clump_connection(stbcc_grid *g, int x1, int y1, int x2, int y2)
{
stbcc__cluster *cluster;
stbcc__clump *clump;
stbcc__relative_clumpid *adj;
int i;
int cx1 = STBCC__CLUSTER_X_FOR_COORD_X(x1);
int cy1 = STBCC__CLUSTER_Y_FOR_COORD_Y(y1);
int cx2 = STBCC__CLUSTER_X_FOR_COORD_X(x2);
int cy2 = STBCC__CLUSTER_Y_FOR_COORD_Y(y2);
stbcc__clumpid c1 = g->clump_for_node[y1][x1];
stbcc__clumpid c2 = g->clump_for_node[y2][x2];
stbcc__relative_clumpid rc;
assert(cx1 != cx2 || cy1 != cy2);
assert(abs(cx1-cx2) + abs(cy1-cy2) == 1);
// add connection to c2 in c1
rc.clump_index = c2;
rc.cluster_dx = x2-x1;
rc.cluster_dy = y2-y1;
cluster = &g->cluster[cy1][cx1];
clump = &cluster->clump[c1];
adj = &cluster->adjacency_storage[clump->adjacent_clump_list_index];
for (i=0; i < clump->num_adjacent; ++i)
if (rc.clump_index == adj[i].clump_index &&
rc.cluster_dx == adj[i].cluster_dx &&
rc.cluster_dy == adj[i].cluster_dy)
break;
if (i < clump->num_adjacent)
adj[i] = adj[--clump->num_adjacent];
else
assert(0);
}
static void stbcc__add_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy)
{
unsigned char connected[STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER][STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER/8] = { 0 };
int x = cx * STBCC__CLUSTER_SIZE_X;
int y = cy * STBCC__CLUSTER_SIZE_Y;
int step_x, step_y=0, i, j, k, n;
if (cx < 0 || cx >= g->cw || cy < 0 || cy >= g->ch)
return;
if (cx+dx < 0 || cx+dx >= g->cw || cy+dy < 0 || cy+dy >= g->ch)
return;
if (g->cluster[cy][cx].rebuild_adjacency)
return;
assert(abs(dx) + abs(dy) == 1);
if (dx == 1) {
i = STBCC__CLUSTER_SIZE_X-1;
j = 0;
step_x = 0;
step_y = 1;
n = STBCC__CLUSTER_SIZE_Y;
} else if (dx == -1) {
i = 0;
j = 0;
step_x = 0;
step_y = 1;
n = STBCC__CLUSTER_SIZE_Y;
} else if (dy == -1) {
i = 0;
j = 0;
step_x = 1;
step_y = 0;
n = STBCC__CLUSTER_SIZE_X;
} else if (dy == 1) {
i = 0;
j = STBCC__CLUSTER_SIZE_Y-1;
step_x = 1;
step_y = 0;
n = STBCC__CLUSTER_SIZE_X;
} else {
assert(0);
}
for (k=0; k < n; ++k) {
if (STBCC__MAP_OPEN(g, x+i, y+j) && STBCC__MAP_OPEN(g, x+i+dx, y+j+dy)) {
stbcc__clumpid src = g->clump_for_node[y+j][x+i];
stbcc__clumpid dest = g->clump_for_node[y+j+dy][x+i+dx];
if (0 == (connected[src][dest>>3] & (1 << (dest & 7)))) {
assert((dest>>3) < sizeof(connected));
connected[src][dest>>3] |= 1 << (dest & 7);
stbcc__add_clump_connection(g, x+i, y+j, x+i+dx, y+j+dy);
if (g->cluster[cy][cx].rebuild_adjacency)
break;
}
}
i += step_x;
j += step_y;
}
}
static void stbcc__remove_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy)
{
unsigned char disconnected[STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER][STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER/8] = { 0 };
int x = cx * STBCC__CLUSTER_SIZE_X;
int y = cy * STBCC__CLUSTER_SIZE_Y;
int step_x, step_y=0, i, j, k, n;
if (cx < 0 || cx >= g->cw || cy < 0 || cy >= g->ch)
return;
if (cx+dx < 0 || cx+dx >= g->cw || cy+dy < 0 || cy+dy >= g->ch)
return;
assert(abs(dx) + abs(dy) == 1);
if (dx == 1) {
i = STBCC__CLUSTER_SIZE_X-1;
j = 0;
step_x = 0;
step_y = 1;
n = STBCC__CLUSTER_SIZE_Y;
} else if (dx == -1) {
i = 0;
j = 0;
step_x = 0;
step_y = 1;
n = STBCC__CLUSTER_SIZE_Y;
} else if (dy == -1) {
i = 0;
j = 0;
step_x = 1;
step_y = 0;
n = STBCC__CLUSTER_SIZE_X;
} else if (dy == 1) {
i = 0;
j = STBCC__CLUSTER_SIZE_Y-1;
step_x = 1;
step_y = 0;
n = STBCC__CLUSTER_SIZE_X;
} else {
assert(0);
}
for (k=0; k < n; ++k) {
if (STBCC__MAP_OPEN(g, x+i, y+j) && STBCC__MAP_OPEN(g, x+i+dx, y+j+dy)) {
stbcc__clumpid src = g->clump_for_node[y+j][x+i];
stbcc__clumpid dest = g->clump_for_node[y+j+dy][x+i+dx];
if (0 == (disconnected[src][dest>>3] & (1 << (dest & 7)))) {
disconnected[src][dest>>3] |= 1 << (dest & 7);
stbcc__remove_clump_connection(g, x+i, y+j, x+i+dx, y+j+dy);
}
}
i += step_x;
j += step_y;
}
}
static stbcc__tinypoint stbcc__incluster_find(stbcc__cluster_build_info *cbi, int x, int y)
{
stbcc__tinypoint p,q;
p = cbi->parent[y][x];
if (p.x == x && p.y == y)
return p;
q = stbcc__incluster_find(cbi, p.x, p.y);
cbi->parent[y][x] = q;
return q;
}
static void stbcc__incluster_union(stbcc__cluster_build_info *cbi, int x1, int y1, int x2, int y2)
{
stbcc__tinypoint p = stbcc__incluster_find(cbi, x1,y1);
stbcc__tinypoint q = stbcc__incluster_find(cbi, x2,y2);
if (p.x == q.x && p.y == q.y)
return;
cbi->parent[p.y][p.x] = q;
}
static void stbcc__switch_root(stbcc__cluster_build_info *cbi, int x, int y, stbcc__tinypoint p)
{
cbi->parent[p.y][p.x].x = x;
cbi->parent[p.y][p.x].y = y;
cbi->parent[y][x].x = x;
cbi->parent[y][x].y = y;
}
static void stbcc__build_clumps_for_cluster(stbcc_grid *g, int cx, int cy)
{
stbcc__cluster *c;
stbcc__cluster_build_info cbi;
int label=0;
int i,j;
int x = cx * STBCC__CLUSTER_SIZE_X;
int y = cy * STBCC__CLUSTER_SIZE_Y;
// set initial disjoint set forest state
for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {
for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i) {
cbi.parent[j][i].x = i;
cbi.parent[j][i].y = j;
}
}
// join all sets that are connected
for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {
// check down only if not on bottom row
if (j < STBCC__CLUSTER_SIZE_Y-1)
for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i)
if (STBCC__MAP_OPEN(g,x+i,y+j) && STBCC__MAP_OPEN(g,x+i ,y+j+1))
stbcc__incluster_union(&cbi, i,j, i,j+1);
// check right for everything but rightmost column
for (i=0; i < STBCC__CLUSTER_SIZE_X-1; ++i)
if (STBCC__MAP_OPEN(g,x+i,y+j) && STBCC__MAP_OPEN(g,x+i+1,y+j ))
stbcc__incluster_union(&cbi, i,j, i+1,j);
}
// label all non-empty clumps along edges so that all edge clumps are first
// in list; this means in degenerate case we can skip traversing non-edge clumps.
// because in the first pass we only label leaders, we swap the leader to the
// edge first
// first put solid labels on all the edges; these will get overwritten if they're open
for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j)
cbi.label[j][0] = cbi.label[j][STBCC__CLUSTER_SIZE_X-1] = STBCC__NULL_CLUMPID;
for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i)
cbi.label[0][i] = cbi.label[STBCC__CLUSTER_SIZE_Y-1][i] = STBCC__NULL_CLUMPID;
for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {
i = 0;
if (STBCC__MAP_OPEN(g, x+i, y+j)) {
stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);
if (p.x == i && p.y == j)
// if this is the leader, give it a label
cbi.label[j][i] = label++;
else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {
// if leader is in interior, promote this edge node to leader and label
stbcc__switch_root(&cbi, i, j, p);
cbi.label[j][i] = label++;
}
// else if leader is on edge, do nothing (it'll get labelled when we reach it)
}
i = STBCC__CLUSTER_SIZE_X-1;
if (STBCC__MAP_OPEN(g, x+i, y+j)) {
stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);
if (p.x == i && p.y == j)
cbi.label[j][i] = label++;
else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {
stbcc__switch_root(&cbi, i, j, p);
cbi.label[j][i] = label++;
}
}
}
for (i=1; i < STBCC__CLUSTER_SIZE_Y-1; ++i) {
j = 0;
if (STBCC__MAP_OPEN(g, x+i, y+j)) {
stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);
if (p.x == i && p.y == j)
cbi.label[j][i] = label++;
else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {
stbcc__switch_root(&cbi, i, j, p);
cbi.label[j][i] = label++;
}
}
j = STBCC__CLUSTER_SIZE_Y-1;
if (STBCC__MAP_OPEN(g, x+i, y+j)) {
stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);
if (p.x == i && p.y == j)
cbi.label[j][i] = label++;
else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {
stbcc__switch_root(&cbi, i, j, p);
cbi.label[j][i] = label++;
}
}
}
c = &g->cluster[cy][cx];
c->num_edge_clumps = label;
// label any internal clusters
for (j=1; j < STBCC__CLUSTER_SIZE_Y-1; ++j) {
for (i=1; i < STBCC__CLUSTER_SIZE_X-1; ++i) {
stbcc__tinypoint p = cbi.parent[j][i];
if (p.x == i && p.y == j)
if (STBCC__MAP_OPEN(g,x+i,y+j))
cbi.label[j][i] = label++;
else
cbi.label[j][i] = STBCC__NULL_CLUMPID;
}
}
// label all other nodes
for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {
for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i) {
stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);
if (p.x != i || p.y != j) {
if (STBCC__MAP_OPEN(g,x+i,y+j))
cbi.label[j][i] = cbi.label[p.y][p.x];
}
if (STBCC__MAP_OPEN(g,x+i,y+j))
assert(cbi.label[j][i] != STBCC__NULL_CLUMPID);
}
}
c->num_clumps = label;
for (i=0; i < label; ++i) {
c->clump[i].num_adjacent = 0;
c->clump[i].max_adjacent = 0;
}
for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j)
for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i) {
g->clump_for_node[y+j][x+i] = cbi.label[j][i]; // @OPTIMIZE: remove cbi.label entirely
assert(g->clump_for_node[y+j][x+i] <= STBCC__NULL_CLUMPID);
}
// set the global label for all interior clumps since they can't have connections,
// so we don't have to do this on the global pass (brings from O(N) to O(N^0.75))
for (i=(int) c->num_edge_clumps; i < (int) c->num_clumps; ++i) {
stbcc__global_clumpid gc;
gc.f.cluster_x = cx;
gc.f.cluster_y = cy;
gc.f.clump_index = i;
c->clump[i].global_label = gc;
}
c->rebuild_adjacency = 1; // flag that it has no valid adjacency data
}
#endif // STB_CONNECTED_COMPONENTS_IMPLEMENTATION
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
|
C
|
#include <stdio.h>
int main( ) {
long long int nC, n, k, i, j, aux;
j = 0;
scanf( "%lli", &nC );
while ( nC-- ) {
scanf( "%lli %lli", &n, &k );
for ( i = 0; i < n; i++ ) {
aux = i * k;
while ( aux > n ) {
aux = ( (k * (aux-n) - 1)/(k-1) );
}
printf( "Case %lli: %lli\n", j++, aux );
}
}
return 0;
}
|
C
|
#include <stdio.h>
void print_intarray(int integers[], int nelems)
{
int i;
for (i = 0; i < nelems; ++i) {
printf("%i ", integers[i]);
}
printf("\n");
}
int main(void)
{
int x;
int x_1[1];
const int arraymax = 10;
int myarray1[arraymax]; // Explicit definition/sizing of array
int myarray2[ ] = {7, 9, 21, 55, 199191, 4, 18};
print_intarray(myarray1, arraymax);
myarray1[0] = 0;
myarray1[1] = 0;
myarray1[2] = 0;
x = myarray1[2];
for (x = 0; x < arraymax; ++x) {
myarray1[x] = 0;
}
printf("After initialisation: \n");
print_intarray(myarray1, arraymax);
// printf("A value from outside the array: %i\n", myarray1[5]); // This is also a BUG!
return 1;
}
|
C
|
#include<stdio.h>
#include <unistd.h>
void printstatus ();
int
main ()
{
int count = 0;
printf ("Will load in 10 Sec \nLoading ");
for (count; count < 10; ++count)
{
printf (". ");
fflush (stdout);
sleep (1);
}
printf ("\nDone\n");
printstatus ();
return 0;
}
void
printstatus ()
{
float progress = 0.0;
int barWidth = 70, pos, i;
while (progress <= 1.0)
{
printf ("[");
pos = barWidth * progress;
for (i = 0; i < barWidth; ++i)
{
if (i < pos)
printf ("=");
else if (i == pos)
printf (">");
else
printf (" ");
}
printf ("] %d%% \r", (int) (progress * 100.0));
fflush (stdout);
sleep (1);
progress += 0.1; // for demonstration only
}
printf ("\n");
}
/*
* Stand alone API to use in any external function
* to Display the status
* USAGE:
if(i%10 == 0)
printstatus(i, parts);
*/
#if 0
void
printstatus (int crnt, int total)
{
int progress = 0, factr;
int barWidth = 70, pos, i;
factr = total / 10;
progress = crnt / factr;
if (progress <= 10.0)
{
printf ("[");
pos = 0.1 * barWidth * progress;
for (i = 0; i < barWidth; ++i)
{
if (i < pos)
printf ("=");
else if (i == pos)
printf (">");
else
printf (" ");
}
printf ("] %d%% \r", (int) (progress * 10));
fflush (stdout);
//sleep(1);
//progress += 0.16; // for demonstration only
}
//printf("\n");
}
#endif
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
typedef struct frame
{
int seq_no;
int ack;
char data[1024];
}Frame;
int main(int argc,char *argv[])
{
char buffer[1024];
int oldsocket;
oldsocket=socket(PF_INET,SOCK_DGRAM,0);
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(atoi(argv[2]));
server.sin_addr.s_addr=inet_addr(argv[1]);
memset(server.sin_zero,'\0',sizeof(server.sin_zero));
/*
0---->ack;
1--> seq;
*/
Frame send_frame;
Frame recv_frame;
int counter=0;
int reader=1;
while(1)
{
if(reader==1)
{
send_frame.seq_no=counter;
send_frame.ack=1;
printf("Enter data:");
fgets(buffer,1024,stdin);
strcpy(send_frame.data,buffer);
sendto(oldsocket,&send_frame,sizeof(Frame),0,(struct sockaddr*)&server,sizeof(server));
printf("Frame sent\n");
reader=0;
}
socklen_t h=sizeof(server);
int recv_size=recvfrom(oldsocket,&recv_frame,sizeof(Frame),0,(struct sockaddr*)&server,&h);
if((recv_size > 0)&&(recv_frame.ack==counter))
{
printf("ACK %d recieved\n",counter);
reader=1;
counter=(counter+1)%2;
}
else
{
printf("ACK Not received\n");
}
}
close(oldsocket);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
float tenValue = 2 * 3 + 4;
float twelveValue = 2 * 2.5 + 2 * 3.5 ;
printf("The value of ten is: %f\n", tenValue);
printf("The value of twelve is: %f\n", twelveValue);
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, const char* argv[]) {
int input = 1;
printBi(input);
//USER INPUT
int userIn = 1;
while (userIn >= 0) {
printf("\nPlease input an integer value: ,to end enter a value x<0\n");
scanf("%d", &userIn);
printBi(userIn);
}
//END USER INPUT
return 0;
}
int printBi(int number) {
if (number > 0) {
printBi(number / 2);
printf("%d", number % 2);
}
else { printf("0"); }
return 0;
}
|
C
|
/*
* scheduler_like.c
*
* Created: 01/04/2019 06:04:13 AM
* Author: Hussam Elsayed Kh
*/
#include "scheduler_like.h"
static unsigned char password[]="295050";
volatile unsigned char pass[6];
void
proj_init(void)
{
adc_init();
LCD_Init();
keypad_init();
SET_BIT(DDRA,4); //set pin 4 as o/p for led
}
unsigned char
get_pin(void)
{
LCD_writeString_col_row("Please, enter PIN:", 0, 0);
LCD_Goto_col_row(0,1); //get ready to display * in place of PIN
unsigned int i = 0;
for(i = 0;i<6;i++)
{
pass[i]=get_button();
_delay_ms(100);
LCD_write_char('*'); //displays PIN as ******
}
LCD_Goto_col_row(0,2);
//compare pin
if(!strcmp(password,pass))
{
LCD_writeString("Congratulations\t:)");
return 1; //success
}
else
{
LCD_writeString("YOU FAILED\t:(");
_delay_ms(1500);
LCD_Clear();
return 0; //failure
}
}
void
start_schedule(void)
{
while(!get_pin()){}
SET_BIT(PORTA,4); //turn led on
_delay_ms(2000);
CLR_BIT(PORTA,4); //turn led off
if('*'==get_button())
{
adc_start_conv();
LCD_writeString_col_row("Temperature= ", 0, 3);
LCD_writeString(LCD_int_to_str(get_temp()));
_delay_ms(2000);
}
LCD_Clear(); //clear display to start over
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int argument_valid(int argc, char *argv[], char *ip, char *port)
{
int opt = 0;
if(ip == NULL)
{
return 2;
}
while((opt = getopt(argc, argv, "i:p")) != -1)
{
switch (opt)
{
case 'i':
strncpy(ip, argv[2], strlen(argv[2]));
case 'p':
strncpy(port, argv[4], strlen(argv[4]));
return 0;
default:
if(argc == 1)
{
return 1; // Аргументов нет
}
else
{
printf("Do not write the path after the key\n");
return 2; // Неверное количество аргументов
}
}
}
return 0;
}
|
C
|
#include "sort.h"
/**
* quick_sort - sorts an array of integers in ascending order using
* the quick sort algorithm
* @array: Array to sort
* @size: Size of the array
*/
void quick_sort(int *array, size_t size)
{
if (!array || size < 2)
return;
lomuto_sort(array, size, 0, size - 1);
}
/**
* lomuto_sort - sorts an array of integers in ascending order using
* the quick sort algorithm with lomuto partitioning
* @array: Array to sort
* @size: Size of the array
* @lo: low end of the partition array
* @hi: high end of the partition array
*/
void lomuto_sort(int *array, size_t size, int lo, int hi)
{
int p;
if (lo < hi)
{
p = lomuto_partition(array, size, lo, hi);
lomuto_sort(array, size, lo, p - 1);
lomuto_sort(array, size, p + 1, hi);
}
}
/**
* lomuto_partition - partitions a sub-array of integers using
* the lomuto partitioning scheme
* @array: Array to sort
* @size: Size of the array
* @lo: low end of the partition array
* @hi: high end of the partition array
*
* Return: Index of the partition
*/
int lomuto_partition(int *array, size_t size, int lo, int hi)
{
int i, j, pivot, tmp;
pivot = array[hi];
i = lo - 1;
for (j = lo; j < hi; j++)
{
if (array[j] < pivot)
{
i++;
if (i != j)
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
print_array(array, size);
}
}
}
if (array[hi] < array[i + 1])
{
tmp = array[i + 1];
array[i + 1] = array[hi];
array[hi] = tmp;
print_array(array, size);
}
return (i + 1);
}
|
C
|
#include "holberton.h"
/**
* puts_half - print every 2 char
* @str: string
* Return: Always 0.
*/
void puts_half(char *str)
{
int i;
int count;
int start;
for (i = 0; str[i] != '\0'; i++)
count++;
start = (count + 1) / 2;
for (i = start; i <= count - 1; i++)
_putchar (str[i]);
_putchar ('\n');
}
|
C
|
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "packarch.h"
#define LARGOCAR 8
typedef struct lz77{
size_t match;
size_t tammem;
size_t taminsp;
char* memoria;
char* inspeccion;
} lz77;
size_t debinarise (size_t num) {
return (num == 0 || num == 1 ? num : ((num%10) + 2*debinarise(num/10)));
}
size_t binarise (size_t num) {
return (num==0 || num==1 ? num : ((num%2)+10*binarise(num/2)));
}
size_t binarisebyte (unsigned char num) {
return (num==0 || num==1 ? num : ((num%2)+10*binarise(num/2)));
}
unsigned char debinarisebyte (size_t num) {
return (num == 0 || num == 1 ? num : ((num%10) + 2*debinarise(num/10)));
}
lz77* nuevo_lz77(size_t mem, size_t insp, size_t minmatch) {
lz77* nuevo = malloc(sizeof(lz77));
nuevo->memoria = calloc(mem,1);
nuevo->inspeccion = calloc(insp,1);
nuevo->match = minmatch;
nuevo->tammem = mem;
nuevo->taminsp = insp;
return nuevo;
}
void destruir_lz77(lz77* comp) {
free(comp->memoria);
free(comp->inspeccion);
free(comp);
}
size_t comparar_strings(char* str1, char* str2, size_t tam) {
if(tam == 0 || strncmp(str1,str2,1) != 0) return 0;
return 1+comparar_strings(str1+1,str2+1,tam-1);
}
char* comprimir(char* src, lz77* comp, size_t largo) {
size_t longlong = ceil(log2(fmin(comp->taminsp,comp->tammem)-(comp->match)+1));
size_t longpos = ceil(log2((comp->tammem)-(comp->match)+1));
size_t largopar = longlong + longpos + 1;
char* compresion = calloc(fmax(LARGOCAR+1, largopar),largo);
for (size_t i = 0; i < (comp->tammem); i++) comp->memoria[i] = ' ';
for (size_t i = 0; i < (comp->taminsp); i++) comp->inspeccion[i] = src[i];
size_t copiados = 0;
size_t i = 0;
while (i < largo) {
size_t iteracion = 0;
size_t longitud = 0;
size_t posicion = 0;
for (size_t j = 0; j<comp->tammem-comp->match+1; j++) {
size_t coincidencia = comparar_strings(comp->memoria+j, comp->inspeccion, fmin(comp->tammem-j,comp->taminsp));
if(coincidencia > longitud) {
longitud = coincidencia;
posicion = j;
}
}
if (longitud < comp->match) {
iteracion=1;
compresion[copiados++] = 0;
size_t binario = binarise(src[i]);
for (int j = LARGOCAR-1; j>=0; j--) {
compresion[copiados++] = (size_t) binario/(size_t) pow(10, j);
binario = (size_t) binario%((size_t) pow(10,j));
}
} else {
iteracion = longitud;
compresion[copiados++] = 1;
longitud = binarise(longitud-comp->match);
posicion = binarise(posicion);
for (int j = longpos-1; j>=0; j--) {
compresion[copiados++] = posicion/(size_t)(pow(10,j));
posicion = posicion%(size_t) pow(10,j);
}
for (int j = longlong-1; j>=0; j--) {
compresion[copiados++] = longitud/(size_t)pow(10,j);
longitud = longitud%(size_t) pow(10,j);
}
}
for (size_t k = 0; k<iteracion; k++) {
for(size_t j = 0; j<comp->tammem-1; j++) {
comp->memoria[j] = comp->memoria[j+1];
}
comp->memoria[comp->tammem-1] = comp->inspeccion[0];
for(size_t j = 0; j<comp->taminsp-1; j++) {
comp->inspeccion[j] = comp->inspeccion[j+1];
}
comp->inspeccion[comp->taminsp-1] = src[(i++)+comp->taminsp];
}
}
size_t tamaniofinal = ceil((double)copiados/(double)8);
char* compresionfinal = calloc(tamaniofinal,1);
for (size_t i = 0; i<tamaniofinal; i++) {
size_t numero = 0;
for (size_t j = 0; j<8; j++) {
numero = numero*10 + compresion[i*8+j];
}
compresionfinal[i] = debinarise(numero);
}
free(compresion);
return compresionfinal;
}
char* descomprimir(lz77* comp, char* src, size_t largo) {
printf("\n");
size_t longlong = ceil(log2(fmin(comp->taminsp,comp->tammem)-(comp->match)+1));
size_t longpos = ceil(log2((comp->tammem)-(comp->match)+1));
size_t largopar = longlong + longpos +1;
for (size_t i = 0; i < (comp->tammem); i++) comp->memoria[i] = ' ';
for (size_t i = 0; i < (comp->taminsp); i++) comp->inspeccion[i] = src[i];
char* srcbits = calloc(largo,8);
size_t max = ceil((largo/largopar))*fmin(comp->taminsp,comp->tammem);
char* descomprimido = calloc(max,8);
for (size_t i = 0; i<strlen(src); i++) {
size_t fuente = binarisebyte(src[i]);
printf("F: %08u\n", fuente);
for (size_t j = 0; j< 8; j++) {
srcbits[i*8+j] = (size_t) fuente/(size_t) pow(10,7-j);
fuente = (size_t) fuente%(size_t) pow(10,7-j);
}
}
size_t i = 0;
size_t desc = 0;
while (i<max*8 && desc<largo) {
if (srcbits[i++] == 0) {
size_t fuente = 0;
for (size_t j = 0; j<8; j++) {
fuente = fuente*10 + srcbits[i++];
}
fuente = debinarise(fuente);
for(size_t j = 0; j<comp->tammem-1; j++) {
comp->memoria[j] = comp->memoria[j+1];
}
comp->memoria[comp->tammem-1] = fuente;
descomprimido[desc++] = fuente;
printf("%c\n", descomprimido[desc-1]);
} else {
size_t posicion = 0;
size_t longitud = 0;
for(size_t j = 0; j<longpos; j++) {
posicion = posicion * 10 + srcbits[i++];
}
posicion = debinarise(posicion);
for(size_t j = 0; j<longlong; j++) {
longitud = longitud * 10 + srcbits[i++];
}
longitud = debinarise(longitud) + comp->match;
printf("Pos:%u Long:%u\n", posicion, longitud);
for (size_t j = 0; j<longitud; j++) {
descomprimido[desc++] = comp->memoria[posicion];
printf("%c", descomprimido[desc-1]);
for (size_t k=0; k < comp->tammem-1; k++) comp->memoria[k] = comp->memoria[k+1];
comp->memoria[comp->tammem-1] = descomprimido[desc-1];
}
printf("\n");
}
}
return descomprimido;
}
|
C
|
#ifndef __PILA_H__
#define __PILA_H__
#if !defined(NULL)
#define NULL 0
#endif
#if !defined(FALSE)
#define FALSE 0
#endif
#if !defined(TRUE)
#define TRUE 1
#endif
/*#include "cmemdbg.h"*/
typedef struct TNodoPila
{
void* Elem;
struct TNodoPila *Siguiente;
} TNodoPila;
typedef struct
{
TNodoPila *Tope;
int TamanioDato;
} TPila;
/*P_Crear
Pre: P no fue creada.
Post: P creada y vaca. */
void P_Crear(TPila *pP, int TamanioDato);
/*P_Vaciar
Pre: P creada.
Post: P vaca. */
void P_Vaciar(TPila *pP);
/*P_Vacia
Pre: P creada.
Post: Si P est vaca devuelve TRUE, sino FALSE. */
int P_Vacia(TPila P);
/*P_Agregar
Pre: P creada.
Post: E se agreg como Tope de P.
Devuelve FALSE si no pudo agregar E, sino devuelve TRUE.*/
int P_Agregar(TPila *pP, void* pE);
/*P_Sacar
Pre: P creada y no vacia.
Post: Se extrajo de P el tope y se devuelve en E.
Si no pudo extraer el elemento (porque la pila estaba vaca) devuelve FALSE,
sino devuelve TRUE.*/
int P_Sacar(TPila *pP, void* pE);
#endif
|
C
|
#include <assert.h>
#include <stdlib.h>
#ifdef NDEBUG
#error This test program must work with macro "ASSERT" enabled!
#endif
#include "list.h"
int testobj_refcnt = 0;
typedef struct testobj_t
{
int value;
} testobj_t;
testobj_t* testobj_create(int value)
{
++testobj_refcnt;
testobj_t *obj = malloc(sizeof(testobj_t));
assert( obj );
obj->value = value;
return obj;
}
void testobj_release(testobj_t *obj)
{
assert( obj );
--testobj_refcnt;
free(obj);
}
bool verify_list_values(const glist_t *list, const int *target_arr, size_t count)
{
assert( list );
if( glist_get_count(list) != count ) return false;
glist_citer_t iter;
int i;
for(i=0, iter=glist_get_cfirst(list);
i<count;
++i, glist_citer_move_next(&iter))
{
if( !glist_citer_is_available(&iter) ) return false;
const testobj_t *item = glist_citer_get_value(&iter);
if( !item || item->value != target_arr[i] ) return false;
}
return true;
}
int main(int argc, char *argv[])
{
glist_t list;
glist_init(&list, (glist_itemfree_t)testobj_release);
assert( glist_get_count(&list) == 0 );
assert( testobj_refcnt == 0 );
// Front and back push test
{
static const int target[] = { 1, 3, 5, 7, 2, 4, 6, 8 };
glist_clear(&list);
assert( glist_is_empty(&list) );
assert( testobj_refcnt == 0 );
glist_push_back (&list, testobj_create(2));
glist_push_back (&list, testobj_create(4));
glist_push_front(&list, testobj_create(7));
glist_push_front(&list, testobj_create(5));
glist_push_back (&list, testobj_create(6));
glist_push_back (&list, testobj_create(8));
glist_push_front(&list, testobj_create(3));
glist_push_front(&list, testobj_create(1));
assert( glist_get_count(&list) == 8 );
assert( verify_list_values(&list, target, 8) );
}
// Front and back pop test
{
static const int target[] = { /*1, 3,*/ 5, 7, 2, /*4, 6, 8*/ };
glist_clear(&list);
assert( glist_is_empty(&list) );
assert( testobj_refcnt == 0 );
glist_push_back(&list, testobj_create(1));
glist_push_back(&list, testobj_create(3));
glist_push_back(&list, testobj_create(5));
glist_push_back(&list, testobj_create(7));
glist_push_back(&list, testobj_create(2));
glist_push_back(&list, testobj_create(4));
glist_push_back(&list, testobj_create(6));
glist_push_back(&list, testobj_create(8));
glist_pop_front(&list);
glist_pop_front(&list);
glist_pop_back (&list);
glist_pop_back (&list);
glist_pop_back (&list);
assert( glist_get_count(&list) == 3 );
assert( verify_list_values(&list, target, 3) );
glist_pop_front(&list);
glist_pop_front(&list);
glist_pop_front(&list);
glist_pop_front(&list);
glist_pop_back (&list);
glist_pop_back (&list);
glist_pop_back (&list);
glist_pop_back (&list);
assert( glist_get_count(&list) == 0 );
assert( verify_list_values(&list, NULL, 0) );
}
// Clear test
{
glist_push_back(&list, testobj_create(1));
glist_push_back(&list, testobj_create(3));
glist_push_back(&list, testobj_create(5));
glist_push_back(&list, testobj_create(7));
glist_push_back(&list, testobj_create(2));
glist_push_back(&list, testobj_create(4));
glist_push_back(&list, testobj_create(6));
glist_push_back(&list, testobj_create(8));
assert( !glist_is_empty(&list) );
glist_clear(&list);
assert( glist_is_empty(&list) );
assert( testobj_refcnt == 0 );
}
// Insert test
{
static const int target[] = { 1, 3, 5, 7, 2, 4, 6, 8 };
glist_clear(&list);
assert( glist_is_empty(&list) );
assert( testobj_refcnt == 0 );
glist_iter_t iter;
iter = glist_get_first(&list);
glist_insert(&list, &iter, testobj_create(8));
/* 8 */
iter = glist_get_first(&list);
glist_insert(&list, &iter, testobj_create(1));
glist_insert(&list, &iter, testobj_create(3));
/* 1, 3, 8 */
iter = glist_get_last(&list);
glist_insert(&list, &iter, testobj_create(6));
/* 1, 3, 6, 8 */
iter = glist_get_first(&list);
assert( glist_iter_move_next(&iter) );
assert( glist_iter_move_next(&iter) );
glist_insert(&list, &iter, testobj_create(5));
glist_insert(&list, &iter, testobj_create(7));
/* 1, 3, 5, 7, 6, 8 */
iter = glist_get_last(&list);
glist_iter_move_prev(&iter);
glist_insert(&list, &iter, testobj_create(2));
glist_insert(&list, &iter, testobj_create(4));
/* 1, 3, 5, 7, 2, 4, 6, 8 */
assert( glist_get_count(&list) == 8 );
assert( verify_list_values(&list, target, 8) );
}
// Erase test
{
static const int target[] = { /*1,*/ 3, 5, /*7, 2,*/ 4, 6, /*8*/ };
glist_clear(&list);
assert( glist_is_empty(&list) );
assert( testobj_refcnt == 0 );
glist_push_back(&list, testobj_create(1));
glist_push_back(&list, testobj_create(3));
glist_push_back(&list, testobj_create(5));
glist_push_back(&list, testobj_create(7));
glist_push_back(&list, testobj_create(2));
glist_push_back(&list, testobj_create(4));
glist_push_back(&list, testobj_create(6));
glist_push_back(&list, testobj_create(8));
glist_iter_t iter;
iter = glist_get_first(&list);
glist_erase(&list, &iter);
iter = glist_get_last(&list);
glist_erase(&list, &iter);
iter = glist_get_first(&list);
assert( glist_iter_move_next(&iter) );
assert( glist_iter_move_next(&iter) );
glist_iter_t iter2 = iter;
assert( glist_iter_move_next(&iter2) );
glist_erase(&list, &iter);
glist_erase(&list, &iter2);
assert( glist_get_count(&list) == 4 );
assert( verify_list_values(&list, target, 4) );
int i;
for(i=0; i<4; ++i)
{
iter = glist_get_first(&list);
glist_erase(&list, &iter);
iter = glist_get_last(&list);
glist_erase(&list, &iter);
}
assert( glist_get_count(&list) == 0 );
assert( verify_list_values(&list, NULL, 0) );
}
// List move test
{
static const int target[] = { 1, 3, 5, 7, 2, 4, 6, 8 };
glist_clear(&list);
assert( glist_is_empty(&list) );
assert( testobj_refcnt == 0 );
glist_push_back(&list, testobj_create(5));
glist_push_back(&list, testobj_create(5));
glist_push_back(&list, testobj_create(5));
{
glist_t list2;
glist_init(&list2, (glist_itemfree_t)testobj_release);
glist_push_back(&list2, testobj_create(1));
glist_push_back(&list2, testobj_create(3));
glist_push_back(&list2, testobj_create(5));
glist_push_back(&list2, testobj_create(7));
glist_push_back(&list2, testobj_create(2));
glist_push_back(&list2, testobj_create(4));
glist_push_back(&list2, testobj_create(6));
glist_push_back(&list2, testobj_create(8));
glist_movefrom(&list, &list2);
assert( glist_get_count(&list2) == 0 );
assert( verify_list_values(&list2, NULL, 0) );
glist_deinit(&list2);
}
assert( glist_get_count(&list) == 8 );
assert( verify_list_values(&list, target, 8) );
glist_clear(&list);
assert( testobj_refcnt == 0 );
}
// Iterator modify item test
{
static const int target[] = { 1, 3, 5, 60, 2, 4, 6, 8 };
glist_clear(&list);
assert( glist_is_empty(&list) );
assert( testobj_refcnt == 0 );
glist_push_back(&list, testobj_create(1));
glist_push_back(&list, testobj_create(3));
glist_push_back(&list, testobj_create(5));
glist_push_back(&list, testobj_create(7));
glist_push_back(&list, testobj_create(2));
glist_push_back(&list, testobj_create(4));
glist_push_back(&list, testobj_create(6));
glist_push_back(&list, testobj_create(8));
glist_iter_t iter = glist_get_first(&list);
assert( glist_iter_move_next(&iter) );
assert( glist_iter_move_next(&iter) );
assert( glist_iter_move_next(&iter) );
assert( glist_iter_set_value(&iter, testobj_create(60)) );
assert( glist_get_count(&list) == 8 );
assert( verify_list_values(&list, target, 8) );
glist_clear(&list);
assert( testobj_refcnt == 0 );
}
glist_deinit(&list);
assert( testobj_refcnt == 0 );
return 0;
}
|
C
|
/** Módulo estándar de Input y Output */
#include <stdio.h>
/** Módulo estándar de números enteros */
#include <stdint.h>
/** Módulo estándar de valores booleanos */
#include <stdbool.h>
// Archivo de listas ligadas
#include "linked_list.c"
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
count += last_comma < (a_str + strlen(a_str) - 1);
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
/** Esta función es lo que se llama al ejecutar tu programa */
int main()
{
/* Imprime el mensaje en la consola */
printf("Bienvenido al Acto 5: Listas\n");
// En esta sección crearemos una lista ligada a partir de sus constructor
// y luego la usaremos normalmente. La struct LinkedList esta definida en el
// archivo linked_list.h junto con todas sus funciones publicas. En le archivo
// linked_list.c esta el codigo de todas las funciones publicas y pricadas
// Creo la lista ligada
LinkedList* ll = ll_init();
// agrego elemento
FILE *ptr_file;
char buf[1000];
ptr_file =fopen("input.txt","r");
if (!ptr_file)
return 1;
int j = 0;
while (fgets(buf,1000, ptr_file)!=NULL){
char** tokens;
tokens = str_split(buf, ' ');
for (j = 0; *(tokens + j); j++){
printf("%i\n", j );
printf("%s", *(tokens + j));
ll_append(ll, *(tokens + j));
}
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
free(*(tokens + i));
}
free(tokens);
}
}
int h = 0;
for (h = 0; h < ll -> count; h++){
printf("%s\n", ll_get(ll, h));
}
// Agrego 10 elementos a la lista ligada
// Imprimo el elemento de la posicion 5
printf("El elemento en la posicion %d es %s\n", 5, ll_get(ll, 3));
// Destruyo la lista ligada liberando todos sus recursos
ll_destroy(ll);
// Como ejercicio puedes probar el programa usando valgrind para ver que no
// hay leaks de memoria y luego eliminar la linea que llama a ll_destroy para
// ver que detecta los leaks de memoria de la lista
return 0;
}
|
C
|
#include <unistd.h>
main()
{
truncate("file1.txt", 10);
truncate("file2.txt", 10);
}
/* file1.txt -> short; file2.txt -> long file with lots of letters
$ cat file1.txt
$ cat file2.txt
$ ls -lG file*.txt
$ ./truncate
$ ls -lG file*.txt
$ cat file1.txt
$ cat file2.txt
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
void bye(void)
{
printf("1-- prepping\n");
exit(-9);
print("1-- That was all, folks\n");
}
void bye2(void)
{
printf("2-- prepping\n");
//exit(-9);
printf("2-- That was all, folks\n");
}
int
main(void)
{
long a;
int i;
printf("Setting eh 1.\n");
i = atexit(bye);
if (i != 0) {
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
printf("Setting eh 2.\n");
i = atexit(bye2);
if (i != 0) {
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
printf("%d\n", i);
getc(stdin);
exit(EXIT_FAILURE);
exit(EXIT_SUCCESS);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** DANTE
** File description:
** algorithm file
*/
#include "solver.h"
cell_t *init_cell(int x, int y, int reachable)
{
cell_t *this = malloc(sizeof(*this));
if (this == NULL)
return (NULL);
this->x = x;
this->y = y;
this->reachable = reachable;
this->parent = NULL;
this->g = 0;
this->h = 0;
this->f = 0;
this->closed = 0;
return (this);
}
int my_abs(int a)
{
if (a < 0)
a *= -1;
return (a);
}
int get_heuristic(solver_t *this, int x, int y)
{
return (10 * (my_abs(x - this->lines) + my_abs(y - this->cols)));
}
void update_cell(solver_t *this, cell_t *adj, cell_t *cell)
{
adj->g = cell->g + 10;
adj->h = get_heuristic(this, adj->x, adj->y);
adj->parent = cell;
adj->f = adj->g + adj->h;
}
int is_in_vector(vector_t *v, int x, int y)
{
vector_t *tmp = v->next;
cell_t *cell_v = NULL;
while (tmp) {
cell_v = tmp->item;
if (cell_v->x == x && cell_v->y == y)
return (1);
tmp = tmp->next;
}
return (0);
}
|
C
|
#include<stdio.h>
#include<string.h>
#define MAX 10000
int validate(char []);
int modulerDivision(char[],unsigned long);
int main(){
char dividend[MAX] = "141232537654685523542";
unsigned long int divisor,remainder;
printf("Enter dividend: ");
if(validate(dividend))
return 0;
printf("Enter divisor: ");
*(&divisor)=462;
remainder = modulerDivision(dividend,divisor);
printf("Modular division: %s %% %lu = %lu",dividend,divisor,remainder);
return 0;
}
int validate(char num[]){
int i=0;
while(num[i]){
if(num[i] < 48 || num[i]> 57){
printf("Invalid positive integer: %s",num);
return 1;
}
i++;
}
return 0;
}
int modulerDivision(char dividend[],unsigned long divisor){
unsigned long temp=0;
int i=0;
while(dividend[i]){
temp = temp*10 + (dividend[i] -48);
if(temp>=divisor){
temp = temp % divisor;
}
i++;
}
return temp;
}
|
C
|
/**
* @file calculadora.h
* @author Rodrigo Theodoro Rocha
* @date 25 April 2016
* @brief Arquivo contendo as funções para implementar o funcionamento da
* calculadora.
*/
#ifndef __CALCULADORA_H__
#define __CALCULADORA_H__
#include <stdio.h>
#include <stdlib.h>
#include "../include/pilha.h"
/**
* Aplica uma das 4 operações primárias nos 2 últimos elementos da pilha @p stk.
* @param stk Endereço da pilha stk
* @param c Caractere do operador para executar
*/
void apply_operacao (t_pilha *stk, char c);
/**
* Função usada na repetição de N vezes o elemento.
* @param stk pilha
*/
void apply_copia_el (t_pilha *stk);
/**
* Aplica recursivamente a operação especificada pelo caractere c.
* @param stk pilha
* @param c operador
*/
void apply_repeticao (t_pilha *stk, char c);
/**
* Aplica a operação c nos 2 operandos especificados
* @param fopnd1 operando 1
* @param fopnd2 operando 2
* @param c operador
* @return Retorna o valor.
*/
int apply_operador (float fopnd1, float fopnd2, char c);
#endif
|
C
|
#define thisprog "xe-timeconv2"
#define TITLE_STRING thisprog" 1.Feb.2021 [JRH]"
#define MAXLINELEN 1000
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/* define and include required (in this order!) for time functions */
#define __USE_XOPEN // required specifically for strptime()
#include <time.h>
/*
<TAGS>string time date</TAGS>
1.Feb.2021 [JRH]
- new time conversion program to handle date+time
/
/* external functions start */
char *xf_lineread1(char *line, long *maxlinelen, FILE *fpin);
long *xf_lineparse2(char *line,char *delimiters, long *nwords);
/* external functions end */
int main (int argc, char *argv[]) {
/* time-related variables & structures */
char timestring[256];
time_t t0=0,t1=0;
struct tm *tstruct1;
/* general variables */
char *line=NULL, *pline=NULL;
long ii,jj,kk,mm,nn,maxlinelen=0;
double aa,bb,cc,dd,ee,result_d[64];
FILE *fpin,*fpout;
/* program-specific variables */
char *pword;
int sizeofdata;
long *iword=NULL,nwords;
float *data1=NULL;
/* arguments */
char *infile=NULL;
int setformat=1;
/* PRINT INSTRUCTIONS IF THERE IS NO FILENAME SPECIFIED */
if(argc<2) {
fprintf(stderr,"\n");
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"%s\n",TITLE_STRING);
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"Convert \"%%d/%%m/%%Y %%H:%%M:%%S\" times to seconds-since-1970\n");
fprintf(stderr,"Assumes one time per input line, in the first column\n");
fprintf(stderr,"Blank lines and comments (#) will be passed unaltered\n");
fprintf(stderr,"USAGE:\n");
fprintf(stderr," %s [in] [options]\n",thisprog);
fprintf(stderr," [in]: file name or \"stdin\"\n");
fprintf(stderr,"VALID OPTIONS:\n");
fprintf(stderr," -f : output format options [%d]:\n",setformat);
fprintf(stderr," 0: seconds elapsed since the first value read (zero)\n");
fprintf(stderr," 1: seconds since 1 January 1970\n");
fprintf(stderr,"EXAMPLES:\n");
fprintf(stderr," %s times.txt\n",thisprog);
fprintf(stderr," echo \"31/12/2020 12:59:59.123\" | %s stdin\n",thisprog);
fprintf(stderr,"OUTPUT:\n");
fprintf(stderr," one modified time per valid input line\n");
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"\n");
exit(0);
}
/* READ THE FILENAME AND OPTIONAL ARGUMENTS */
infile= argv[1];
for(ii=2;ii<argc;ii++) {
if( *(argv[ii]+0) == '-') {
if((ii+1)>=argc) {fprintf(stderr,"\n--- Error[%s]: missing value for argument \"%s\"\n\n",thisprog,argv[ii]); exit(1);}
else if(strcmp(argv[ii],"-f")==0) setformat= atoi(argv[++ii]);
else {fprintf(stderr,"\n--- Error[%s]: invalid command line argument \"%s\"\n\n",thisprog,argv[ii]); exit(1);}
}}
if(setformat!=0&&setformat!=1) {fprintf(stderr,"\n--- Error[%s]: invalid format (-f %d) - must be 0 or 1 \n\n",thisprog,setformat);exit(1);}
/* INTIALISE T1 AND TSTRUCT1 - THIS AVOIDS USING MALLOC OR MEMSET */
t1 = time(NULL);
tstruct1 = localtime(&t1);
/********************************************************************************/
/* READ & CONVERT THE DATA */
/********************************************************************************/
if(strcmp(infile,"stdin")==0) fpin=stdin;
else if((fpin=fopen(infile,"r"))==0) {fprintf(stderr,"\n--- Error[%s]: file \"%s\" not found\n\n",thisprog,infile);exit(1);}
sizeofdata= sizeof(*data1);
mm= nn= 0;
while((line=xf_lineread1(line,&maxlinelen,fpin))!=NULL) {
mm++;
if(line[0]=='#') {printf("%s",line) ;continue;}
if(strlen(line)<2) {printf("\n");continue;}
if(maxlinelen==-1) {fprintf(stderr,"\n--- Error[%s]: readline function encountered insufficient memory\n\n",thisprog);exit(1);}
iword= xf_lineparse2(line,"\t",&nwords);
if(nwords<0) {fprintf(stderr,"\n--- Error[%s]: lineparse function encountered insufficient memory\n\n",thisprog);exit(1);};
// for now assume date-time string is in first column (0)
pword= line+iword[0];
// convert string to broken-down-time structure (Y/M/D etc)
// assumes input format is %d/%m/%Y %H:%M:%S
pline= strptime(pword,"%d/%m/%Y %H:%M:%S", tstruct1);
if(pline==NULL) {fprintf(stderr,"\n--- Error[%s]: invalid date format on line %ld\n\n",thisprog,mm);exit(1);};
// convert broken-down-time to seconds-since-1970
t1 = mktime(tstruct1);
// if this is the first timestamp and elapsed-time is required, make t1 the reference time
if(nn==0) { if(setformat==0) t0= t1; }
// output
printf("%ld\n",(t1-t0));
nn++;
}
if(strcmp(infile,"stdin")!=0) fclose(fpin);
/********************************************************************************/
/* CLEANUP AND EXIT */
/********************************************************************************/
END:
if(line!=NULL) free(line);
exit(0);
}
|
C
|
#ifndef SERIAL_H
#define SERIAL_H
#include <types.h>
// NOTE: The following may not be true for all machines!
enum serial_port {
SER_NULL = 0x000,
SER_COM1 = 0x3F8,
SER_COM2 = 0x2F8,
SER_COM3 = 0x3E8,
SER_COM4 = 0x2E8
};
/**
* Initialize a serial port
*
* @param port The base IO address of the serial port to initialize
* @param baud The baud rate for the serial port to use
*/
void serial_init(enum serial_port port, u16 baud);
/**
* Read a character from the serial port
* NOTE: This is currently a blocking function, and will stall execution
* until a character is recieved.
*
* @param port The base IO address of the serial port to read from
* @return The value received by the serial port
*/
char serial_getc(enum serial_port port);
/**
* Write a character to the serial port
*
* @param port The base IO address of the serial port to write to
* @param ch The character to write to the serial port
*/
void serial_putc(enum serial_port port, char ch);
/**
* Write bytes from a buffer to the serial port
*
* @param port The base IO address of the serial port to write to
* @param buf Buffer containing bytes to write
* @param len Number of bytes to write
*/
void serial_write(enum serial_port port, const u8 *buf, int len);
// Get the 16-bit divisor for any given baud rate
#define serial_get_divisor(B) (u16)(115200 / B)
enum serial_regs {
SER_REG_DATA = 0, // Data transmit/recieve (THR/RBR)
SER_REG_IER = 1, // Interrupt enable (IER)
SER_REG_IIR = 2, // Interrupt ID (read-only) (IIR)
SER_REG_FCR = 2, // FIFO register (write-only) (FCR)
SER_REG_LCR = 3, // Line control (LCR)
SER_REG_MCR = 4, // Modem control (MCR)
SER_REG_LSR = 5, // Line status (LSR)
SER_REG_MSR = 6, // Modem status (MSR)
SER_REG_SR = 7, // Scratch register (SR)
// When DLAB = 0
SER_REG_DLL = 0, // LSB of divisor (DLL)
SER_REG_DLH = 1 // MSB of divisor (DLH)
};
// Interrupt enable register (IER) bits
enum serial_ier_bits {
SER_IER_DATA_AVAIL = 0b00000001, // Data available interrupt
SER_IER_TRANS_EMPTY = 0b00000010, // Transmitter holding register empty interrupt
SER_IER_LINE_STAT = 0b00000100, // Reciever line status interrupt
SER_IER_MODM_STAT = 0b00001000, // Modem status interrupt
SER_IER_EN_SLEEPM = 0b00010000, // Enable sleep mode
SER_IER_EN_LOWPWR = 0b00100000 // Enable low-power mode
};
// Interrupt ID (IIR) bits
enum serial_iir_bits {
SER_IIR_INTR_PEND = 0b00000001, // Interrupt pending
SER_IIR_INTR_TYPE = 0b00001110, // Interrupt type
SER_IIR_64B_FIFO = 0b00100000, // 64-byte FIFO enabled
SER_IIR_FIFO = 0b11000000, // FIFO information
SER_INTR_TYPE_MODM_STAT = 0b00000000, // Modem status
SER_INTR_TYPE_TRANS_EMPTY = 0b00000010, // Transmitter holding register empty
SER_INTR_TYPE_DATA_AVAIL = 0b00000100, // Recieved data availabe
SER_INTR_TYPE_LINE_STAT = 0b00000110, // Line status
SER_INTR_TYPE_TIMEOUT = 0b00001100 // Timeout interrupt pending
};
// FIFO control (FCR) bits
enum serial_fcr_bits {
SER_FCR_FIFO_ENABLE = 0b00000001, // FIFO Enable
SER_FCR_CLR_RECV = 0b00000010, // Clear Receive FIFO
SER_FCR_CLR_TRANS = 0b00000100, // Clear Transmit FIFO
SER_FCR_DMA_MODE = 0b00001000, // DMA Mode Select
SER_FCR_64BYTE_EN = 0b00100000, // 64-Byte FIFO Enable
SER_FCR_TRIG_LVL = 0b11000000, // Interrupt Trigger Level (See SER_FCR_TRIG_*)
SER_FCR_TRIG_1B = 0b00000000,
// 16-Byte FIFO:
SER_FCR_TRIG_4B = 0b01000000,
SER_FCR_TRIG_8B = 0b10000000,
SER_FCR_TRIG_14B = 0b11000000,
// 64-Byte FIFO:
SER_FCR_TRIG_16B = 0b01000000,
SER_FCR_TRIG_32B = 0b10000000,
SER_FCR_TRIG_56B = 0b11000000
};
// Line control register (LCR) bits:
enum serial_lcr_bits {
SER_LCR_WORD_LEN = 0b00000011, // Word length
SER_LCR_STOP_BITS = 0b00000100, // Stop bits
SER_LCR_PARITY = 0b00111000, // Parity
SER_LCR_BREAK_EN = 0b01000000, // Break enable
SER_LCR_DLAB = 0b10000000, // Divisor Latch Access Bit
// Word lengths:
SER_LCR_WL_5B = 0b00000000,
SER_LCR_WL_6B = 0b00000001,
SER_LCR_WL_7B = 0b00000010,
SER_LCR_WL_8B = 0b00000011
};
// Modem control register (MCR) bits:
enum serial_mcr_bits {
SER_MCR_DTR = 0b00000001, // Data Terminal Ready
SER_MCR_RTS = 0b00000010, // Request To Send
SER_MCR_AUX1 = 0b00000100, // Auxilliary Output 1
SER_MCR_AUX2 = 0b00001000, // Auxilliary Output 2
SER_MCR_LOOP = 0b00010000, // Loopback Mode
SER_MCR_AFC = 0b00100000 // Autoflow control enable
};
// Line Status Register (LSR) bits:
enum serial_lsr_bits {
SER_LSR_DATA_READY = 0b00000001, // Data Ready
SER_LSR_OVRRUN_ERR = 0b00000010, // Overrun Error
SER_LSR_PARITY_ERR = 0b00000100, // Parity Error
SER_LSR_FRAME_ERR = 0b00001000, // Framing Error
SER_LSR_BREAK_INTR = 0b00010000, // Break Interrupt
SER_LSR_EMPT_TRANS = 0b00100000, // Empty Transmitter Holding Register
SER_LSR_EMPT_DATA = 0b01000000, // Empty Data Holding Registers
SER_LSR_RFIFO_ERR = 0b10000000 // Error in revieved FIFO
};
// Modem Status Register (MSR) bits:
enum serial_msr_bits {
SER_MSR_DELTA_CTS = 0b00000001, // Delta Clear To Send
SER_MSR_DELTA_DSR = 0b00000010, // Delta Data Set Ready
SER_MSR_DELTA_RI = 0b00000100, // Delta Ring Indicator (1 to 0 only)
SER_MSR_DELTA_CD = 0b00001000, // Delta Carrier Detect
SER_MSR_CTS = 0b00010000, // Clear To Send
SER_MSR_DSR = 0b00100000, // Data Set Ready
SER_MSR_RI = 0b01000000, // Ring Indicator
SER_MSR_CD = 0b10000000 // Carrier Detect
};
#endif
|
C
|
void calculate_speed(float dy, float dx, float* s) {
*s = sqrt(dy*dy+dx*dx);
}
|
C
|
#include <stdio.h>
#include <string.h>
#define N 10000 // 最多可表示0-30999
int hash[N];
/**
* 获取所在数组下标
*
*/
int getNum(int n)
{
return n / 32;
}
/**
* 获取所在下标的bit位置
*
*/
int getLoc(int n)
{
return n % 32;
}
int main(void)
{
int i, n, data, offset, bit, num;
while (scanf("%d", &n) != EOF) {
memset(hash, 0, sizeof(hash));
// bit-map思想
for (i = 0; i < n; i ++) {
scanf("%d", &data);
num = getNum(data);
bit = getLoc(data);
hash[num] |= (1 << bit);
}
// 打印输出
for (i = 0; i < N; i ++) {
offset = 0;
while (hash[i]) {
if (hash[i] & 1) {
printf("%d ", i * 32 + offset);
}
hash[i] >>= 1;
offset += 1;
}
}
printf("\n");
}
return 0;
}
|
C
|
#include <nefko.h>
#include <ghetto.h>
#include <nefko_priv.h>
#include <string.h>
#include <stdint.h>
/* Extendable test for whether or not this is an NEF file. Eventually,
* this should also cover identifying whether or not this is a sub-
* variant of NEF that is supported by libnefko.
*/
static NEF_STATUS nef_identify(tiff_t *fp, tiff_ifd_t *parent)
{
tiff_tag_t *maker = NULL;
char *maker_tag = NULL;
int maker_count;
NEF_STATUS ret;
/* Attempt to retrieve the TIFF Maker tag */
if (tiff_get_tag(fp, parent, TIFF_TAG_MAKER, &maker) != TIFF_OK) {
NEF_TRACE("Failed to get Maker tag!\n");
return NEF_NOT_NEF;
}
if (tiff_get_tag_info(fp, maker, NULL, NULL, &maker_count) != TIFF_OK) {
NEF_TRACE("Failed to get attribs of Maker tag!\n");
return NEF_NOT_NEF;
}
maker_tag = (char *)calloc(1, maker_count + 1);
if (maker_tag == NULL) {
return NEF_NO_MEMORY;
}
if (tiff_get_tag_data(fp, parent, maker, maker_tag) != TIFF_OK) {
NEF_TRACE("Could not get Maker tag data.\n");
ret = NEF_NOT_NEF;
goto fail;
}
NEF_TRACE("Got Maker tag \"%s\"\n", maker_tag);
if (strncmp(maker_tag, "NIKON CORPORATION", 18)) {
NEF_TRACE("Vendor not NIKON, aborting\n");
ret = NEF_NOT_NEF;
goto fail;
}
free(maker_tag);
return NEF_OK;
fail:
if (maker_tag) free(maker_tag);
return ret;
}
NEF_STATUS nef_get_tag_low(nef_t *nef, tiff_ifd_t *ifd, unsigned tag_id,
void *dest)
{
tiff_tag_t *taginfo = NULL;
GHETTO_CHECK(tiff_get_tag(nef->tiff_fp, ifd, tag_id, &taginfo));
if (taginfo == NULL) {
return NEF_NOT_FOUND;
}
GHETTO_CHECK(tiff_get_tag_data(nef->tiff_fp, ifd, taginfo, dest));
return NEF_OK;
}
NEF_STATUS nef_get_tag_alloc(nef_t *nef, tiff_ifd_t *ifd, unsigned tag_id,
void **dest, int *item_type, int *item_count)
{
tiff_tag_t *taginfo = NULL;
int count, type;
void *dest_ptr = NULL;
size_t tysz;
NEF_STATUS stat;
NEF_CHECK_ARG(dest);
NEF_CHECK_ARG(item_type);
NEF_CHECK_ARG(item_count);
*dest = NULL;
*item_type = 0;
*item_count = 0;
GHETTO_CHECK(tiff_get_tag(nef->tiff_fp, ifd, tag_id, &taginfo));
if (taginfo == NULL) {
return NEF_NOT_FOUND;
}
GHETTO_CHECK(tiff_get_tag_info(nef->tiff_fp, taginfo,
NULL, &type, &count));
if ( (tysz = tiff_get_type_size(type)) == 0 ) {
return NEF_RANGE_ERROR;
}
dest_ptr = calloc(tysz, count);
if (dest_ptr == NULL) {
return NEF_NO_MEMORY;
}
if ((stat = tiff_get_tag_data(nef->tiff_fp, ifd, taginfo, dest_ptr)) != NEF_OK)
{
NEF_TRACE("Failed to get tag data.\n");
free(dest_ptr);
return stat;
}
*dest = dest_ptr;
*item_type = type;
*item_count = count;
return NEF_OK;
}
NEF_STATUS nef_get_tag(nef_t *nef, nef_image_t *img, unsigned tag_id,
void *dest)
{
return nef_get_tag_low(nef, img->ifd, tag_id, dest);
}
#ifdef _DEBUG
static char *nef_data_types[] = {
"unknown",
"uint",
"int",
"float",
"void",
"complex int",
"complex float"
};
#endif
static NEF_STATUS nef_populate_image_info(nef_t *nef, nef_image_t *img)
{
unsigned int type = 0;
NEFKO_CHECK(nef_get_tag(nef, img, TIFF_TAG_IMAGELENGTH, &(img->height)),
NEF_NOT_FOUND);
NEFKO_CHECK(nef_get_tag(nef, img, TIFF_TAG_IMAGEWIDTH, &(img->width)),
NEF_NOT_FOUND);
NEFKO_CHECK(nef_get_tag(nef, img, TIFF_TAG_SAMPLESPERPIXEL, &(img->chans)),
NEF_NOT_FOUND);
img->data_type = NEF_DATATYPE_UINT;
NEFKO_CHECK(nef_get_tag(nef, img, TIFF_TAG_NEWSUBFILETYPE, &type),
NEF_NOT_FOUND);
NEFKO_CHECK(nef_get_tag(nef, img, TIFF_TAG_COMPRESSION, &(img->compression)),
NEF_NOT_FOUND);
if (type & 0x1) {
img->type = NEF_IMAGE_REDUCED;
} else if (type == 0) {
img->type = NEF_IMAGE_FULL;
} else {
NEF_TRACE("Unknown NewSubfileType: %08x\n", type);
}
if (nef_get_tag(nef, img, TIFF_TAG_PHOTOMETRICINTERP, &(img->photo_interp)) !=
NEF_OK)
{
NEF_TRACE("Assuming planar Photometric Interpretation\n");
img->photo_interp = 0;
}
NEF_TRACE("Image: %d x %d, %d channels (data type: '%s') (%s) Comp: 0x%08x PhInterp: %08x\n",
img->width, img->height, img->chans, nef_data_types[img->data_type],
img->type == NEF_IMAGE_REDUCED ? "thumbnail" : "full-resolution",
(unsigned)img->compression, img->photo_interp);
img->nef_file = nef;
return NEF_OK;
}
static NEF_STATUS nef_find_images(nef_t *nef, tiff_t *fp, tiff_ifd_t *root)
{
tiff_tag_t *subifds = NULL;
uint32_t *subifd_offs = NULL;
int count, type, i;
NEF_STATUS ret;
/* The algorithm for gathering images associated with an NEF file
is simplistic - the root IFD will have a SubIFDs tag. Each SubIFD
entry, as well as the root entry, will contain one of the
associated images - two thumbnails, 1 full-resolution image. */
if (tiff_get_tag(fp, root, TIFF_TAG_SUBIFDS, &subifds) != TIFF_OK ) {
NEF_TRACE("Couldn't find SubIFDs tag!\n");
return NEF_NOT_NEF;
}
if (tiff_get_tag_info(fp, subifds, NULL, &type, &count) != TIFF_OK) {
NEF_TRACE("Couldn't get SubIFDs tag info.\n");
return NEF_NOT_NEF;
}
subifd_offs = (uint32_t *)calloc(1, tiff_get_type_size(type) * count);
if (tiff_get_tag_data(fp, root, subifds, subifd_offs) != TIFF_OK) {
goto fail_free_offs;
}
/* Allocate an array for storing each image, including the image stored
* in the root IFD.
*/
nef->images = (nef_image_t *)calloc(1, sizeof(nef_image_t) * (count + 1));
if (nef->images == NULL) {
NEF_TRACE("Failed to allocate %zd bytes for image data\n",
sizeof(nef_image_t) * (count + 1));
ret = NEF_NO_MEMORY;
goto fail_free_offs;
}
nef->images[0].ifd = root;
/* Populate images[0] with the contents of the root IFD */
if (nef_populate_image_info(nef, &nef->images[0]) != NEF_OK) {
NEF_TRACE("Failed to populate root image data!\n");
ret = NEF_NOT_NEF;
goto fail_free_images;
}
/* Populate the remaining images with the contents of the SubIFDs */
for (i = 1; i < count + 1; i++) {
tiff_ifd_t *sub_ifd = NULL;
if (tiff_read_ifd(fp, subifd_offs[i - 1], &sub_ifd) != TIFF_OK) {
goto fail_free_images;
}
nef->images[i].ifd = sub_ifd;
if (nef_populate_image_info(nef, &nef->images[i]) != NEF_OK) {
NEF_TRACE("Failed to populate IFD %d's attributes\n", i);
tiff_free_ifd(fp, sub_ifd);
nef->images[i].ifd = NULL;
continue;
}
}
nef->image_count = count + 1;
return NEF_OK;
fail_free_images:
for (i = 0; i < count; i++) {
if (nef->images[i].ifd != NULL) {
tiff_free_ifd(fp, nef->images[i].ifd);
}
}
if (nef->images) free(nef->images);
nef->images = NULL;
fail_free_offs:
if (subifd_offs) free(subifd_offs);
return NEF_NOT_NEF;
}
static NEF_STATUS nef_destroy_image(nef_t *nef, nef_image_t *img)
{
if (tiff_free_ifd(nef->tiff_fp, img->ifd) != TIFF_OK) {
return NEF_FAILURE;
}
memset(img, 0, sizeof(nef_image_t));
return NEF_OK;
}
NEF_STATUS nef_open(const char *file, nef_t **fp)
{
tiff_t *tiff_fp = NULL;
tiff_ifd_t *root_ifd = NULL;
tiff_off_t root_ifd_off, makernote_off, exif_off;
tiff_tag_t *exif_off_tag = NULL, *makernote_off_tag = NULL;
TIFF_STATUS ret = TIFF_OK;
NEF_STATUS nret = NEF_OK;
int maker_count = 0, maker_type = 0, maker_type_size = 0;
uint8_t *maker_buf = NULL;
nef_t *nef_fp = NULL;
NEF_CHECK_ARG(file);
NEF_CHECK_ARG(fp);
if (*file == '\0') {
return NEF_BAD_ARGUMENT;
}
*fp = NULL;
/* Open the NEF file */
if ( (ret = tiff_open(&tiff_fp, file, "r")) != TIFF_OK ) {
NEF_TRACE("Failed to open file '%s'\n", file);
if (ret == TIFF_NOT_TIFF) {
return NEF_NOT_NEF;
} else {
return NEF_NOT_FOUND;
}
}
if ( (ret = tiff_get_base_ifd_offset(tiff_fp, &root_ifd_off)) != TIFF_OK ) {
nret = NEF_NOT_NEF;
goto fail_close_file;
}
if ( (ret = tiff_read_ifd(tiff_fp, root_ifd_off, &root_ifd)) != TIFF_OK ) {
nret = NEF_NOT_NEF;
goto fail_close_file;
}
if (nef_identify(tiff_fp, root_ifd) != NEF_OK) {
nret = NEF_NOT_NEF;
NEF_TRACE("This is not an NEF file...\n");
goto fail_close_file;
}
/* This is likely a NEF file. Open the IFDs and store them. */
nef_fp = (nef_t *)calloc(1, sizeof(nef_t));
if (nef_fp == NULL) {
nret = NEF_NO_MEMORY;
goto fail_close_file;
}
nef_fp->tiff_fp = tiff_fp;
if (nef_find_images(nef_fp, tiff_fp, root_ifd) != NEF_OK) {
nret = NEF_NOT_NEF;
goto fail_free_fptr;
}
/* Load the EXIF IFD */
if (tiff_get_tag(nef_fp->tiff_fp, root_ifd, TIFF_TAG_EXIFIFD, &exif_off_tag)
!= TIFF_OK)
{
NEF_TRACE("Could not get EXIF IFD.\n");
nret = NEF_NOT_NEF;
goto fail_free_fptr;
}
if (tiff_get_raw_tag_field(nef_fp->tiff_fp, exif_off_tag, &exif_off) != TIFF_OK)
{
NEF_TRACE("Could not get offset to EXIF IFD.\n");
nret = NEF_NOT_NEF;
goto fail_free_fptr;
}
if (tiff_read_ifd(nef_fp->tiff_fp, exif_off, &nef_fp->exif) != TIFF_OK) {
NEF_TRACE("Could not read the EXIF IFD.\n");
nret = NEF_NOT_NEF;
goto fail_free_fptr;
}
/* Load the MakerNote IFD */
if (tiff_get_tag(nef_fp->tiff_fp, nef_fp->exif, TIFF_TAG_EXIF_MAKERNOTE,
&makernote_off_tag) != TIFF_OK)
{
NEF_TRACE("Unable to find MakerNote tag\n");
nret = NEF_NOT_NEF;
goto fail_free_exif;
}
if (tiff_get_raw_tag_field(nef_fp->tiff_fp, makernote_off_tag, &makernote_off))
{
NEF_TRACE("Failed to get offset of MakerNote IFD.\n");
nret = NEF_NOT_NEF;
goto fail_free_exif;
}
if (tiff_get_tag_info(nef_fp->tiff_fp, makernote_off_tag,
NULL, &maker_type, &maker_count) != TIFF_OK)
{
NEF_TRACE("Failed to get MakerNote tag info.\n");
nret = NEF_NOT_NEF;
goto fail_free_exif;
}
if ( (maker_type_size = tiff_get_type_size(maker_type)) == 0 ) {
NEF_TRACE("Unexpected data type for MakerNote type.\n");
nret = NEF_NOT_NEF;
goto fail_free_exif;
}
maker_buf = (uint8_t *)calloc(maker_type_size, maker_count);
if (maker_buf == NULL) {
NEF_TRACE("Failed to allocate memory. Aborting.\n");
nret = NEF_NO_MEMORY;
goto fail_free_exif;
}
if (tiff_get_tag_data(nef_fp->tiff_fp, nef_fp->exif, makernote_off_tag,
maker_buf) != TIFF_OK)
{
NEF_TRACE("Failed to get tag data.\n");
nret = NEF_NOT_NEF;
free(maker_buf);
goto fail_free_exif;
}
if (strncmp("Nikon", (char *)maker_buf, 5)) {
NEF_TRACE("This is not a Nikon MakerNote... aborting.\n");
nret = NEF_NOT_NEF;
free(maker_buf);
goto fail_free_exif;
}
/* Create an IFD for the makernote */
if (tiff_make_ifd(nef_fp->tiff_fp, maker_buf + NEF_MAKERNOTE_OFF,
maker_type_size * maker_count, makernote_off + NEF_MAKERNOTE_OFF - 8,
&nef_fp->makernote) != TIFF_OK)
{
NEF_TRACE("Failed to create NEF MakerNote structure. Aborting.\n");
nret = NEF_NOT_NEF;
free(maker_buf);
goto fail_free_exif;
}
free(maker_buf);
if (nef_get_obfuscation_params(nef_fp) != NEF_OK) {
NEF_TRACE("Failed to get crypto params\n");
nret = NEF_NOT_NEF;
goto fail_free_makernote;
}
*fp = nef_fp;
return NEF_OK;
fail_free_makernote:
if (nef_fp->makernote) tiff_free_ifd(tiff_fp, nef_fp->makernote);
fail_free_exif:
if (nef_fp->exif) tiff_free_ifd(tiff_fp, nef_fp->exif);
fail_free_fptr:
if (nef_fp) free(nef_fp);
fail_close_file:
if (root_ifd) tiff_free_ifd(tiff_fp, root_ifd);
if (tiff_fp) tiff_close(tiff_fp);
return nret;
}
NEF_STATUS nef_close(nef_t *fp)
{
int i = 0;
NEF_CHECK_ARG(fp);
if (fp->image_count > 0 && fp->images != NULL) {
for (i = 0; i < fp->image_count; i++) {
nef_destroy_image(fp, &fp->images[i]);
}
free(fp->images);
}
if (fp->exif) tiff_free_ifd(fp->tiff_fp, fp->exif);
if (fp->makernote) tiff_free_ifd(fp->tiff_fp, fp->makernote);
tiff_close(fp->tiff_fp);
memset(fp, 0, sizeof(nef_t));
free(fp);
return NEF_OK;
}
|
C
|
/** @file vqtest.c
* @brief A very simple test suite for variable queues.
*
* @author Ryan Pearl <rpearl>
*/
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "variable_queue.h"
typedef struct node {
Q_NEW_LINK(node) link;
int data;
} node_t;
Q_NEW_HEAD(list_t, node);
#define LIST_LEN 5
void test_init() {
list_t list;
Q_INIT_HEAD(&list);
assert(!Q_GET_FRONT(&list));
assert(!Q_GET_TAIL(&list));
}
void test_insert() {
list_t list;
Q_INIT_HEAD(&list);
node_t node;
Q_INIT_ELEM(&node, link);
node.data = 1;
Q_INSERT_TAIL(&list, &node, link);
assert(Q_GET_TAIL(&list) == &node);
assert(Q_GET_FRONT(&list) == &node);
assert(!Q_GET_NEXT(&node, link));
assert(!Q_GET_PREV(&node, link));
}
void test_remove() {
list_t list;
Q_INIT_HEAD(&list);
node_t node;
Q_INIT_ELEM(&node, link);
Q_INSERT_TAIL(&list, &node, link);
assert(Q_GET_TAIL(&list) == &node);
assert(Q_GET_FRONT(&list) == &node);
assert(!Q_GET_NEXT(&node, link));
assert(!Q_GET_PREV(&node, link));
Q_REMOVE(&list, &node, link);
assert(!Q_GET_FRONT(&list));
assert(!Q_GET_TAIL(&list));
}
void test_insert_fronts() {
list_t list;
Q_INIT_HEAD(&list);
node_t nodes[LIST_LEN];
int i;
for (i = 0; i < LIST_LEN; i++) {
Q_INIT_ELEM(&nodes[i], link);
nodes[i].data = i;
Q_INSERT_FRONT(&list, &nodes[i], link);
}
node_t *cur = Q_GET_FRONT(&list);
for (i = 0; i < LIST_LEN; i++) {
assert(cur);
assert(cur->data == LIST_LEN - i - 1);
cur = Q_GET_NEXT(cur, link);
}
assert(!cur);
cur = Q_GET_TAIL(&list);
for (i = LIST_LEN-1; i >= 0; i--) {
assert(cur);
assert(cur->data == LIST_LEN - i - 1);
cur = Q_GET_PREV(cur, link);
}
assert(!cur);
}
void test_insert_tails() {
list_t list;
Q_INIT_HEAD(&list);
node_t nodes[LIST_LEN];
int i;
for (i = 0; i < LIST_LEN; i++) {
Q_INIT_ELEM(&nodes[i], link);
nodes[i].data = i;
Q_INSERT_TAIL(&list, &nodes[i], link);
}
node_t *cur = Q_GET_FRONT(&list);
for (i = 0; i < LIST_LEN; i++) {
assert(cur);
assert(cur->data == i);
node_t *next = Q_GET_NEXT(cur, link);
assert(!next || Q_GET_PREV(next, link) == cur);
cur = next;
}
assert(!cur);
cur = Q_GET_TAIL(&list);
for (i = LIST_LEN-1; i >= 0; i--) {
assert(cur);
assert(cur->data == i);
node_t *prev = Q_GET_PREV(cur, link);
assert(!prev || Q_GET_NEXT(prev, link) == cur);
cur = prev;
}
assert(!cur);
}
void test_removes() {
list_t list;
Q_INIT_HEAD(&list);
node_t nodes[LIST_LEN];
int i;
for (i = 0; i < LIST_LEN; i++) {
Q_INIT_ELEM(&nodes[i], link);
Q_INSERT_FRONT(&list, &nodes[i], link);
}
assert(Q_GET_FRONT(&list) == &nodes[LIST_LEN-1]);
assert(Q_GET_TAIL(&list) == &nodes[0]);
node_t *cur = Q_GET_FRONT(&list);
while (cur) {
node_t *next = Q_GET_NEXT(cur, link);
Q_REMOVE(&list, cur, link);
cur = next;
i++;
}
}
void test_insert_after() {
list_t list;
Q_INIT_HEAD(&list);
node_t nodes[LIST_LEN];
Q_INIT_ELEM(&nodes[0], link);
nodes[0].data = 0;
Q_INSERT_FRONT(&list, &nodes[0], link);
int i;
for (i = 1; i < LIST_LEN; i++) {
Q_INIT_ELEM(&nodes[i], link);
Q_INSERT_AFTER(&list, &nodes[i-1], &nodes[i], link);
nodes[i].data = i;
assert(Q_GET_NEXT(&nodes[i-1], link) == &nodes[i]);
assert(Q_GET_PREV(&nodes[i], link) == &nodes[i-1]);
}
assert(Q_GET_FRONT(&list) == &nodes[0]);
assert(Q_GET_TAIL(&list) == &nodes[LIST_LEN-1]);
node_t *cur = Q_GET_FRONT(&list);
for (i = 0; i < LIST_LEN; i++) {
assert(cur);
assert(cur->data == i);
cur = Q_GET_NEXT(cur, link);
}
assert(!cur);
}
void test_insert_before() {
list_t list;
Q_INIT_HEAD(&list);
node_t nodes[LIST_LEN];
Q_INIT_ELEM(&nodes[0], link);
nodes[0].data = 0;
Q_INSERT_FRONT(&list, &nodes[0], link);
int i;
for (i = 1; i < LIST_LEN; i++) {
Q_INIT_ELEM(&nodes[i], link);
Q_INSERT_BEFORE(&list, &nodes[i-1], &nodes[i], link);
nodes[i].data = i;
assert(Q_GET_PREV(&nodes[i-1], link) == &nodes[i]);
assert(Q_GET_NEXT(&nodes[i], link) == &nodes[i-1]);
}
assert(Q_GET_TAIL(&list) == &nodes[0]);
assert(Q_GET_FRONT(&list) == &nodes[LIST_LEN-1]);
node_t *cur = Q_GET_FRONT(&list);
for (i = 0; i < LIST_LEN; i++) {
assert(cur);
assert(cur->data == LIST_LEN - i - 1);
cur = Q_GET_NEXT(cur, link);
}
assert(!cur);
}
#define RUN_TEST(t) do {\
printf("Running "#t"()...");\
t();\
printf(" OK.\n");\
} while(0)
int main() {
RUN_TEST(test_init);
RUN_TEST(test_insert);
RUN_TEST(test_insert_fronts);
RUN_TEST(test_insert_tails);
RUN_TEST(test_insert_before);
RUN_TEST(test_insert_after);
RUN_TEST(test_remove);
return 0;
}
|
C
|
#include "shell.h"
/**
* main - executes shell
* @argc: array
* @argv: pointer to array pointer
*
* Return: void
*/
int main(int argc[], char **argv[])
{
char cmd[100], command[100], *parameters[20];
/* enviroment variables */
char *envp[] = {(char *) "PATH=/bin", 0};
while (1) /* repeat forever */
{
pid_t pid = fork();
type_prompt(); /* displays prompt on screen */
read_command(command, parameters);/*read input from terminal */
if (pid != 0) /* (instruction to) parent */
{
if (execve(cmd, parameters, NULL) == -1)
{
handle_errors();
}
else
{
wait(NULL); /* wait for child */
else
{
strcpy(cmd, "/bin/");
strcat(cmd, command);
execve(cmd, parameters, envp); /* execute command */
}
if (strcmp(command, "exit") == 0)
break;
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ok/ok.h>
#include <fs/fs.h>
#include <json.h>
#define EQ(a, b) (0 == strcmp(a, b))
int
main (void) {
const char *name = "test set";
const char *src = "{\"name\": \"bradley\"}";
json_value_t *obj = NULL;
json_value_t *tmp = NULL;
json_value_t *value = NULL;
obj = json_parse(name, src);
assert(obj);
assert(0 == obj->errno);
ok("json_parse");
value = json_get(obj, "name");
assert(value);
assert(EQ("name", value->id));
assert(EQ("bradley", value->as.string));
tmp = json_new(JSON_STRING, "joseph");
assert(tmp);
ok("json_new");
json_set(obj, "name", tmp);
assert(0 == obj->errno);
ok_done();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "imc.h"
#include "imcparser.h"
long ip;
SymReg * hash[HASH_SIZE];
Instruction ** instructions;
void relop_to_op(int relop, char * op) {
switch(relop) {
case RELOP_EQ: strcpy(op, "eq"); return;
case RELOP_NE: strcpy(op, "ne"); return;
case RELOP_GT: strcpy(op, "gt"); return;
case RELOP_GTE: strcpy(op, "ge"); return;
case RELOP_LT: strcpy(op, "lt"); return;
case RELOP_LTE: strcpy(op, "le"); return;
default:
fprintf(stderr, "relop_to_op: Invalid relop [%d]\n", relop);
abort();
}
}
SymReg * mk_symreg(const char * name, char t) {
SymReg * r;
if((r = get_sym(name)))
return r;
r = calloc(1, sizeof(SymReg));
r->name = str_dup(name);
r->reg = str_dup(name);
if(t == 'I') r->fmt = str_dup("I%d");
else if(t == 'N') r->fmt = str_dup("N%d");
else if(t == 'S') r->fmt = str_dup("S%d");
else if(t == 'P') r->fmt = str_dup("P%d");
r->first = -1;
r->color = -1;
r->set = t;
r->type = VTREG;
if(name[0])
store_symreg(r);
return r;
}
SymReg * mk_ident(const char * name, char t) {
SymReg * r = mk_symreg(name, t);
r->type = VTIDENTIFIER;
return r;
}
SymReg * mk_const(const char * name, char t) {
SymReg * r;
if((r = get_sym(name)))
return r;
r = calloc(1, sizeof(SymReg));
r->name = str_dup(name);
r->reg = str_dup(name);
r->first = -1;
r->color = -1;
r->type = VTCONST;
if(name[0])
store_symreg(r);
return r;
}
SymReg * mk_address(const char * name) {
SymReg * r;
if((r = get_sym(name)))
return r;
r = calloc(1, sizeof(SymReg));
r->name = str_dup(name);
r->reg = str_dup(name);
r->first = -1;
r->color = -1;
r->type = VTADDRESS;
if(name[0])
store_symreg(r);
return r;
}
void clear_tables() {
int i;
for(i = 0; i < HASH_SIZE; i++) {
/* Memory leak */
hash[i] = NULL;
}
}
void store_symreg(SymReg * r) {
int index = hash_str(r->name) % HASH_SIZE;
r->next = hash[index];
hash[index] = r;
}
SymReg * get_sym(const char * name) {
SymReg * p;
int index = hash_str(name) % HASH_SIZE;
for(p = hash[index]; p; p = p->next) {
if(!strcmp(name, p->name))
return p;
}
return p;
}
Instruction * mk_instruction(const char * fmt, SymReg * r0, SymReg * r1,
SymReg * r2, SymReg * r3)
{
static SymReg * nullreg;
Instruction * i = calloc(1, sizeof(Instruction));
if(!nullreg)
nullreg = mk_symreg("", 'I');
i->fmt = str_dup(fmt);
i->r0 = r0;
i->r1 = r1;
i->r2 = r2;
i->r3 = r3;
if(!i->r0) i->r0 = nullreg;
if(!i->r1) i->r1 = nullreg;
if(!i->r2) i->r2 = nullreg;
if(!i->r3) i->r3 = nullreg;
return i;
}
Instruction ** resize_instructions(Instruction ** i, int num) {
i = realloc(i, num * sizeof(Instruction *));
return i;
}
/*
* Buffered emit()
*/
Instruction * emitb(Instruction * i) {
#if DEBUG
emit(i);
#endif
if(!instructions) {
instructions = calloc(4096, sizeof(Instruction *));
}
/* If this is first instruction referencing symbol, record
* this for register allocator.
*/
if(i->r0 && i->r0->first < 0) i->r0->first = ip;
if(i->r1 && i->r1->first < 0) i->r1->first = ip;
if(i->r2 && i->r2->first < 0) i->r2->first = ip;
if(i->r3 && i->r3->first < 0) i->r3->first = ip;
instructions[ip++] = i;
return i;
}
Instruction * emit(Instruction * i) {
printf(i->fmt, i->r0->reg, i->r1->reg, i->r2->reg, i->r3->reg);
printf("\n");
return i;
}
void emit_flush() {
int i;
for(i = 0; i < ip; i++) {
emit(instructions[i]);
free(instructions[i]);
instructions[i] = 0;
}
ip = 0;
}
/* Register allocator:
*
* This is a brute force register allocator. It uses a graph-coloring
* algorithm, but the implementation is very kludgy.
* The only restraint on the allocator is that locals will remain
* live from their declaration until the _last_ local branch in
* the routine. Without further analysis, it is not easy to tell
* which registers are live after their last appearance in the op
* list unless we know all the potential branch paths.
* This is the simplest method, but doesn't result in the most
* optimal code. Symbolic temporaries do not have this constraint,
* since it is assumed the compiler will not emit code expecting
* temporaries to be live across branches.
*/
int count;
int lastbranch;
SymReg ** compute_graph() {
SymReg ** graph;
int i;
lastbranch = 0;
/* Compute last branch in this procedure, see comment above */
for(i = 0; instructions[i]; i++) {
if(instructions[i]->type == ITBRANCH)
lastbranch = i;
}
/* Computer du-chains for all symbolics */
count = 0;
for(i = 0; i < HASH_SIZE; i++) {
SymReg * r = hash[i];
for(; r; r = r->next) {
if(r->type != VTREG && r->type != VTIDENTIFIER) continue;
compute_du_chain(r);
if(r->type == VTIDENTIFIER
&& r->last < lastbranch) r->last = lastbranch;
count++;
}
}
/* Construct a graph N x N where N = number of symbolics.
* This piece can be rewritten without the N x N array
*/
{
graph = calloc(count*count+count+1, sizeof(SymReg*));
count = 0;
for(i = 0; i < HASH_SIZE; i++) {
SymReg * r = hash[i];
/* Add each symbol to its slot on the X axis of the graph */
for(; r; r = r->next) {
if(r->type == VTREG || r->type == VTIDENTIFIER) {
fprintf(stderr, "#putting %s into graph\n", r->name);
graph[count++] = r;
}
}
}
}
/* Calculate interferences between each chain and populate the the Y-axis */
{
int x, y;
for(x = 0; x < count; x++) {
for(y = 0; y < count; y++) {
if(interferes(graph[x], graph[y])) {
fprintf(stderr, "#[%d %d] %s interferes with %s\n", x, y, graph[x]->name,
graph[y]->name);
graph[(1+x)*count+y+1] = graph[y];
}
}
}
}
return graph;
}
/* Compute a DU-chain for each symbolic */
void compute_du_chain(SymReg * r) {
Instruction * ins;
int i;
if(i == -1) {
fprintf(stderr, "Internal error: symreg %s not referenced\n", r->name);
abort();
}
r->last = r->first;
i = r->first;
for(ins = instructions[i++]; ins; ins = instructions[i++]) {
if(r == ins->r0) r->last = i-1;
else if(r == ins->r1) r->last = i-1;
else if(r == ins->r2) r->last = i-1;
else if(r == ins->r3) r->last = i-1;
}
fprintf(stderr, "#compute_du_chain(%s) = [%d,%d]\n", r->name, r->first,
r->last);
}
/* See if r0's chain interferes with r1. */
int interferes(SymReg * r0, SymReg * r1) {
/* Register doesn't interfere with itself, and register sets
* don't interfere with each other.
*/
if(r0 == r1) return 0;
else if(r0->set != r1->set) return 0;
if(r0->first > r1->last) return 0;
else if(r0->last < r1->first) return 0;
return 1;
}
/*
* Color the graph assigning registers to each symbol
*/
void color_graph(SymReg ** graph) {
int x = 0;
int color, colors[MAX_COLOR];
int free_colors;
char buf[256];
for(x = 0; graph[x]; x++) {
memset(colors, 0, sizeof(colors));
free_colors = map_colors(x, graph, colors);
for(color = 0; color < MAX_COLOR; color++) {
if(!colors[color]) {
graph[x]->color = color;
fprintf(stderr, "#[%s] gets color [%d]\n", graph[x]->name, color);
sprintf(buf, graph[x]->fmt, graph[x]->color);
graph[x]->reg = str_dup(buf);
break;
}
}
}
}
int map_colors(int x, SymReg ** graph, int colors[]) {
int y = 0;
SymReg * r;
int free_colors = MAX_COLOR;
memset(colors, 0, sizeof(colors[0]) * MAX_COLOR);
for(y = 0; y < count; y++) {
if((r = graph[(1+x)*count+y+1])
&& r->color != -1) {
colors[r->color] = 1;
free_colors--;
}
}
return free_colors;
}
unsigned int hash_str(const char * str) {
unsigned long key = 0;
const char * s;
for(s=str; *s; s++)
key = key * 65599 + *s;
return key;
}
char * str_dup(const char * old) {
char * copy = (char *)malloc(strlen(old) + 1);
strcpy(copy, old);
return copy;
}
char * str_cat(const char * s1, const char * s2) {
int len = strlen(s1) + strlen(s2) + 1;
char * s3 = malloc(len);
strcpy(s3, s1);
strcat(s3, s2);
return s3;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <omp.h>
#include <sys/time.h>
#define MIN_VALUE -9999999
double *array;
double *retorno;
int MAX_THREADS;
int N;
int main(int argc, char *argv[]){
double maxglobal;
double start, end;
long i;
//struct timeval inicio, final;
//int tmili;
if(argc != 3){
printf("Indique o número de threads e o tamanho do vetor, nesta ordem\n");
exit(1);
}
MAX_THREADS = atoi(argv[1]);
N = atoi(argv[2]);
omp_set_num_threads(MAX_THREADS);
array = (double*) malloc(N*sizeof(double));
retorno = (double*) malloc(N*sizeof(double));
srand(time(NULL));
for(i=0; i<N; i++){
array[i] = rand ();
}
start = omp_get_wtime();
//gettimeofday(&inicio, NULL);
#pragma omp parallel for default(none) shared(N,array,maxglobal,retorno) private(i)
for(i=0; i<N; i++){
retorno[i] = log10(array[i]);
if (retorno[i]>maxglobal)
maxglobal = retorno[i];
}
end = omp_get_wtime();
//gettimeofday(&final, NULL);
//tmili = (int) (1000 * (final.tv_sec - inicio.tv_sec) + (final.tv_usec - inicio.tv_usec) / 1000);
printf("Número de threads: %d\n", MAX_THREADS);
printf("Maior valor: %f\n", maxglobal);
printf("Tempo decorrido: %.4g segundos\n", end-start);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
void digits(void);
void beaufortScale(void);
int gradeConvert(void);
int main(void)
{
// digits();
// beaufortScale();
gradeConvert();
}
void digits(void)
{
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number / 100 >= 1)
printf("The number %d has 3 digits\n", number);
else if (number / 10 >= 1)
printf("The number %d has 2 digits\n", number);
else
printf("The number %d has 1 digit\n", number);
}
void beaufortScale(void)
{
float windSpeed;
printf("Wind speed (in knots): ");
scanf("%f", &windSpeed);
if (windSpeed < 1.00f)
printf("Calm\n");
else if (windSpeed < 3.00f)
printf("Light air\n");
else if (windSpeed < 27.00f)
printf("Breeze\n");
else
printf("Storm\n");
}
int gradeConvert(void)
{
int grade, firstDigit, secondDigit;
printf("Enter a numerical grade: ");
scanf("%d", &grade);
secondDigit = grade % 10;
firstDigit = grade / 10;
if (grade == 100)
printf("letter grade: A");
else
switch (firstDigit){
case 9: printf("Letter grade: A\n"); break;
case 8: printf("letter grade B\n"); break;
case 7: printf("letter grade: C\n"); break;
case 6: printf("letter grade: D\n"); break;
case 5: printf("letter grade: F\n"); break;
default: printf("letter grade: F\n");
}
}
|
C
|
#include <stdio.h>
void toLowerCase(char s[])
{
for( int i = 0 ; s[i] != '\0' ; ++i)
{
if(s[i]>='A'&&s[i]<='Z')
s[i]+=32;
}
}
int main()
{
char a[100];
scanf("%[^\n]%*c" , a);
toLowerCase(a);
printf("%s" , a);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
int vn[SIZE];
int queue[SIZE];
int v, e, i;
int front = -1;
int rear = -1;
struct graph
{
int vertex;
struct graph *next;
};
struct graph *a[SIZE];
void enqueue(int element)
{
if (rear == SIZE - 1)
{
printf("Queue full\n");
}
else
{
queue[++rear] = element;
}
return;
}
int dequeue()
{
int x;
x = queue[++front];
if (front == -1 && rear == -1)
{
printf("Queue empty");
return 0;
}
//queue[front] = 0;
return x;
}
struct graph *createGraph(struct graph *root, int n)
{
struct graph *ptr = (struct graph *)malloc(sizeof(struct graph));
ptr->vertex = n;
ptr->next = root;
root = ptr;
return root;
}
void bfs(int q, int n)
{
int p, i, j;
enqueue(q);
vn[q] = 1;
p = dequeue();
if (p != 0)
{
printf("%d\t", p);
}
while (p != 0)
{
while (a[p] != NULL && vn[a[p]->vertex] == 0)
{
enqueue(a[p]->vertex);
vn[a[p]->vertex] = 1;
a[p] = a[p]->next;
}
p = dequeue();
if (p != 0)
{
printf("%d\t", p);
}
}
for (j = 1; j <= n; j++)
{
if (vn[j] == 0)
{
front--;
bfs(j, n);
}
}
}
void main()
{
int j, k, l, n, m;
struct graph *hp;
printf("Enter the number of vertices: ");
scanf("%d", &v);
printf("Enter the number of edges: ");
scanf("%d", &e);
for (i = 1; i <= v; i++)
{
vn[i] = 0;
}
for (i = 1; i <= v; i++)
{
a[i] = NULL;
}
for (i = 1; i <= e; i++)
{
printf("Enter pair of vertices: \n");
scanf("%d%d", &j, &k);
a[j] = createGraph(a[j], k);
a[k] = createGraph(a[k], j);
}
printf("Adjacent List: ");
for (i = 1; i <= v; i++)
{
hp = a[i];
printf("\n");
//printf("%d -> ",i);
while (hp != NULL)
{
printf("%d -> ", hp->vertex);
hp = hp->next;
}
}
printf("\nEnter the source: ");
scanf("%d", &n);
bfs(n, v);
}
|
C
|
#ifndef LINE_SENSOR_H
#define LINE_SENSOR_H
#define NUM_SENSORS 8
#define TIMEOUT 300
byte position;
byte lineCnt = 0;
byte sensorSum[256];
byte lineNum[256];
byte lineReading;
int steerTable[256];
void setupLine(){
steerTable[0] = 100;
for(byte sensorValue=1; sensorValue!=0; sensorValue++)
{
byte i = 0;
byte avg = 0;
byte sum = 0;
byte value = sensorValue;
byte lineCnt=0;
bool on_line = false;
while(value)
{
if (value & 1)
{
avg += i;
sum++;
if (!on_line) lineCnt++;
on_line = !on_line;
}
else on_line = false;
i++;
value = value >> 1;
}
sensorSum[sensorValue] = sum;
lineNum[sensorValue] = lineCnt;
float ratio = exp(3 * ((float)avg/sum / (NUM_SENSORS-1)) - 1.5 );
if (ratio >= 1) steerTable[sensorValue] = 100*ratio;
else steerTable[sensorValue] = -100/ratio;
}
}
void readLineSensor(){
DDRA = 0xFF; // make sensor line an output
PORTA = 0xFF; // drive sensor line high
delayMicroseconds(10); // charge lines for 10 us
DDRA = 0; // make sensor line an input
PORTA = 0; // important: disable internal pull-up!
delayMicroseconds(TIMEOUT);
lineReading = PINA;
lineCnt = lineNum[lineReading];
/*
unsigned long startTime = micros();
while (micros() - startTime < TIMEOUT)
{
unsigned int time = micros() - startTime;
for (i = 0; i < NUM_sENSORS; i++)
{
if (PINA & (0x01<<i))
if (digitalRead(_pins[i]) == LOW && time < sensor_values[i])
sensor_values[i] = time;
}
}
*/
}
void printLineSensor(){
for (char i=0; i<NUM_SENSORS; i++){
Serial.print((bool)(lineReading&(1<<i)));
}
Serial.print('\t');
Serial.print("P");Serial.print(": ");
Serial.print(position);
Serial.print('\t');
Serial.print('\n');
}
#endif
|
C
|
int removeDuplicates(int* nums, int numsSize) {
if(numsSize == 0) return 0;
int temp = 1;
for(int i = 1; i < numsSize; i++) {
if(nums[i] != nums[i-1]) nums[temp++] = nums[i];
}
return temp;
}
|
C
|
#include "types.h"
#include "system.h"
#include "buttons_interrupt.h"
/* Declare one global variable to capture the output of the buttons (SW0-SW3),
* when they are pressed.
*/
volatile int edge_capture;
#ifdef PUSH_BUTTONS_NAME
/*---------------------------------------------------------------------------------------------
* static void handle_button_interrupts( void* context, alt_u32 id)
*
* Handle interrupts from the buttons.
* This interrupt event is triggered by a button/switch press.
* This handler sets *context to the value read from the button
* edge capture register. The button edge capture register
* is then cleared and normal program execution resumes.
* The value stored in *context is used to control program flow
* in the rest of this program's routines.
*
* Provision is made here for systems that might have either th
* legacy or enhanced interrupt API active, or for the Nios II IDE
* which does not support enhanced interrupts. For systems created
* using the Nios II softawre build tools, the enhanced API is
* recommended for new designs.
*-------------------------------------------------------------------------------------------*/
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
void handle_button_interrupts(void* context)
#else
void handle_button_interrupts(void* context, alt_u32 id)
#endif
{
/* Cast context to edge_capture's type.
* It is important to keep this volatile,
* to avoid compiler optimization issues.
*/
volatile int* edge_capture_ptr = (volatile int*) context;
IOWR_ALTERA_AVALON_PIO_IRQ_MASK(PUSH_BUTTONS_BASE, 0xf );
/* Store the value in the Button's edge capture register in *context. */
*edge_capture_ptr = IORD_ALTERA_AVALON_PIO_EDGE_CAP(PUSH_BUTTONS_BASE);
/* Reset the Button's edge capture register. */
IOWR_ALTERA_AVALON_PIO_EDGE_CAP(PUSH_BUTTONS_BASE, 0xf);
/* Read the PIO to delay ISR exit. This is done to prevent a spurious
* interrupt in systems with high processor -> pio latency and fast
* interrupts. */
IORD_ALTERA_AVALON_PIO_EDGE_CAP(PUSH_BUTTONS_BASE);
}
/*---------------------------------------------------------------------------------------------
* Initialize the button_pio.
*-------------------------------------------------------------------------------------------*/
void init_button_pio()
{
/* Recast the edge_capture pointer to match the alt_irq_register() function
* prototype. */
void* edge_capture_ptr = (void*) &edge_capture;
/* Enable all 4 button interrupts. */
IOWR_ALTERA_AVALON_PIO_IRQ_MASK(PUSH_BUTTONS_BASE, 0xf);
/* Reset the edge capture register. */
IOWR_ALTERA_AVALON_PIO_EDGE_CAP(PUSH_BUTTONS_BASE, 0xf); // needs to be high for all four buttons since the push button is high
/*
* Register the interrupt handler.
* Provision is made here for systems that might have either the
* legacy or enhanced interrupt API active, or for the Nios II IDE
* which does not support enhanced interrupts. For systems created using
* the Nios II softawre build tools, the enhanced API is recommended
* for new designs.
*/
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
alt_ic_isr_register(PUSH_BUTTONS_IRQ_INTERRUPT_CONTROLLER_ID, PUSH_BUTTONs_IRQ, handle_button_interrupts, edge_capture_ptr, 0x0);
#else
alt_irq_register( PUSH_BUTTONS_IRQ, edge_capture_ptr, handle_button_interrupts);
#endif
}
/*---------------------------------------------------------------------------------------------
* Tear down the button_pio.
*-------------------------------------------------------------------------------------------*/
void disable_button_pio()
{
/* Disable interrupts from the button_pio PIO component. */
IOWR_ALTERA_AVALON_PIO_IRQ_MASK(PUSH_BUTTONS_BASE, 0x0);
/* Un-register the IRQ handler by passing a null handler. */
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
alt_ic_isr_register(PUSH_BUTTONS_IRQ_INTERRUPT_CONTROLLER_ID, BUTTON_PIO_IRQ, NULL, NULL, NULL);
#else
alt_irq_register( PUSH_BUTTONS_IRQ, NULL, NULL );
#endif
}
/*---------------------------------------------------------------------------------------------
* static void TestButtons( void )
* Generates a loop that exits when all buttons/switches have been pressed,
* at least, once.
* NOTE: Buttons/Switches are not debounced. A single press of a
* button may result in multiple messages.
*-------------------------------------------------------------------------------------------*/
void TestButtons( void )
{
alt_u8 buttons_tested;
alt_u8 all_tested;
/* Variable which holds the last value of edge_capture to avoid
* "double counting" button/switch presses
*/
int last_tested;
/* Initialize the Buttons/Switches (SW0-SW3) */
init_button_pio();
/* Initialize the variables which keep track of which buttons have been tested. */
buttons_tested = 0x0;
all_tested = 0xe; // last button is reset
/* Initialize edge_capture to avoid any "false" triggers from
* a previous run.
*/
edge_capture = 0;
/* Set last_tested to a value that edge_capture can never equal
* to avoid accidental equalities in the while() loop below.
*/
last_tested = 0xffff;
/* Print a quick message stating what is happening */
printf("\nA loop will be run until all buttons/switches have been pressed.\n\n");
printf("\n\tNOTE: Once a button press has been detected, for a particular button,\n\tany further presses will be ignored!\n\n");
/* Loop until all buttons have been pressed.
* This happens when buttons_tested == all_tested.
*/
while ( buttons_tested != all_tested )
{
if (last_tested == edge_capture)
{
continue;
}
else
{
last_tested = edge_capture;
switch (edge_capture)
{
case 0x1:
if (buttons_tested & 0x1)
{
continue;
}
else
{
printf("\nButton 1 (SW0) Pressed.\n");
buttons_tested = buttons_tested | 0x1;
}
break;
case 0x2:
if (buttons_tested & 0x2)
{
continue;
}
else
{
printf("\nButton 2 (SW1) Pressed.\n");
buttons_tested = buttons_tested | 0x2;
}
break;
case 0x4:
if (buttons_tested & 0x4)
{
continue;
}
else
{
printf("\nButton 3 (SW2) Pressed.\n");
buttons_tested = buttons_tested | 0x4;
}
break;
case 0x8:
if (buttons_tested & 0x8)
{
continue;
}
else
{
printf("\nButton 4 (SW3) Pressed.\n");
buttons_tested = buttons_tested | 0x8;
}
break;
}
}
}
/* Disable the button pio. */
disable_button_pio();
printf ("\nAll Buttons (SW0-SW3) were pressed, at least, once.\n");
usleep(2000000);
return;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum seatClasses{business, economy, standard};
enum priorities{veteran, diplomat,none};
typedef struct Passengers
{
char* name;
int wantedClass;
int soldClass;
int priority;
int sold;
}Passenger;
typedef struct Flights
{
char* name;
int seatQuota[3];
Passenger* queues[4];
int passengerCount[4];
int closed;
}Flight;
int seatNameToIndex(char* seatName); //seat adn enum karsiliina cevirir
int priorityToIndex(char* priority); //priority adn enum karsiliina cevirir
char* enumToSeatNames(enum seatClasses seat); //seat enumunu string haline getirir
char* enumToPriority(enum priorities priority); //priority enumunu string haline getirir
void addseat(Flight** flightsP,int seatCount,enum seatClasses seatClass,char* flightName,int* flightCountP,FILE* output); //ucus ya da koltuk ekler
void enqueue(Flight** flightsP,char* priority,char* passengerName,enum seatClasses seatClass,char* flightName,int flightCount,FILE* output); //istenilen kuyruga yolcu ekler
void sell(Flight** flightsP,int flightCount,char* flightNameA,FILE* output); //kuyrukta bekleyen yolculara uygun bilet satlr
void close(Flight** flightsP,int flightCount,char* flightName,FILE* output); //ucus bilet satimina kapanr
void report(Flight* flights,int flightCount,char* flightName,FILE* output); //istenilen ucusu raporlar
void info(Flight* flights,int flightCount,char* passengerName,FILE* output); //istenilen yolcunun bilgilerini verir
int main(int argc,char *argv[])
{
int i,j,k;
if(argc!=3)
{
printf("Not enough arguments!\n");
return;
}
printf("argc:%d\n",argc);
int lineLen=0,maxLineLen=0;
char ch;
char* line;
char* word;
line = (char*)malloc((lineLen+20)*sizeof(char));
maxLineLen=20;
FILE* input;
input = fopen(argv[1],"r");
FILE* output;
output = fopen(argv[2],"w");
Flight* flights;
flights = (Flight*)malloc(1*sizeof(Flight));
int flightCount=0;
while(1)
{
ch = fgetc(input);
if(ch==EOF || ch=='\n')
{
word = strtok(line," ");
while(word != NULL)
{
if(strcmp(word,"addseat")==0)
{
addseat(&flights,atoi(strtok(NULL, " ")),seatNameToIndex(strtok(NULL, " ")),strtok(NULL, " "),&flightCount,output);
}
else if(strcmp(word,"enqueue")==0)
{
enqueue(&flights,strtok(NULL, " "),strtok(NULL, " "),seatNameToIndex(strtok(NULL, " ")),strtok(NULL, " "),flightCount,output);
}
else if(strcmp(word,"sell")==0)
{
sell(&flights,flightCount,strtok(NULL, " "),output);
}
else if(strcmp(word,"close")==0)
{
close(&flights,flightCount,strtok(NULL, " "),output);
}
else if(strcmp(word,"report")==0)
{
report(flights,flightCount,strtok(NULL, " "),output);
}
else if(strcmp(word,"info")==0)
{
info(flights,flightCount,strtok(NULL, " "),output);
}
word = strtok(NULL, " ");
}
line[0]='\0';
if(ch==EOF)
break;
lineLen=0;
}
else
{
lineLen++;
if(lineLen>=maxLineLen)
{
line = (char*)realloc(line,(lineLen+20)*sizeof(*line));
maxLineLen=lineLen+20;
}
line[lineLen-1]=ch;
line[lineLen]='\0';
}
}
free(line);
fclose(input);
fclose(output);
for(i=0;i<flightCount;i++)
{
for(j=0;j<4;j++)
{
for(k=0;k<flights[i].passengerCount[j];k++)
{
free(flights[i].queues[j][k].name);
}
free(flights[i].queues[j]);
}
free(flights[i].name);
}
free(flights);
printf("Returned 0\n");
return 0;
}
int seatNameToIndex(char* seatName)
{
if(strcmp(seatName,"business")==0)
return 0;
else if(strcmp(seatName,"economy")==0)
return 1;
else if(strcmp(seatName,"standard")==0)
return 2;
else
return -1;
}
int priorityToIndex(char* priority)
{
if(priority==NULL)
return 2;
if(priority[0] == 'v')
return 0;
else if(priority[0] == 'd')
return 1;
else if(strlen(priority)>1)
return -1;
else
return 2;
}
char* enumToSeatNames(enum seatClasses seat)
{
int i;
char *names[]={"business", "economy", "standard"};
for(i=0;i<3;i++)
{
if((int)seat==i)
return names[i];
}
}
char* enumToPriority(enum priorities priority)
{
int i;
char *names[]={"veteran","diplomat","none"};
for(i=0;i<3;i++)
{
if((int)priority==i)
return names[i];
}
}
void addseat(Flight** flightsP,int seatCount,enum seatClasses seatClass,char* flightName,int* flightCountP,FILE* output)
{
int i,index;
if((*flightCountP)==0)
{
index = 0;
(*flightCountP) = 1;
(*flightsP)[0].name = (char*)malloc((strlen(flightName)+1)*sizeof(char));
strcpy((*flightsP)[0].name,flightName);
(*flightsP)[0].name[strlen(flightName)] = '\0';
for(i=0;i<3;i++)
{
if(i==(int)seatClass)
(*flightsP)[0].seatQuota[i] = seatCount;
else
(*flightsP)[0].seatQuota[i] = 0;
}
(*flightsP)[0].queues[(int)seatClass] = (Passenger*)malloc((seatCount)*sizeof(Passenger));
(*flightsP)[0].queues[3] = (Passenger*)malloc((seatCount)*10*sizeof(Passenger));
(*flightsP)[0].closed = 0;
for(i=0;i<4;i++)
(*flightsP)[0].passengerCount[i] = 0;
}
else
{
index = -1;
for(i=0;i<(*flightCountP);i++)
{
if(strcmp((*flightsP)[i].name,flightName)==0)
{
index = i;
break;
}
}
if(index==-1)
{
(*flightCountP) = (*flightCountP) + 1;
(*flightsP) = (Flight*)realloc((*flightsP),((*flightCountP)*sizeof(Flight)));
(*flightsP)[(*flightCountP) - 1].name = (char*)malloc((strlen(flightName)+1)*sizeof(char));
strcpy((*flightsP)[(*flightCountP) - 1].name,flightName);
(*flightsP)[(*flightCountP) - 1].name[strlen(flightName)] = '\0';
for(i=0;i<3;i++)
{
if(i==(int)seatClass)
(*flightsP)[(*flightCountP) - 1].seatQuota[i] = seatCount;
else
(*flightsP)[(*flightCountP) - 1].seatQuota[i] = 0;
}
index = (*flightCountP) - 1;
(*flightsP)[(*flightCountP) - 1].queues[(int)seatClass] = (Passenger*)malloc((seatCount)*sizeof(Passenger));
(*flightsP)[(*flightCountP) - 1].queues[3] = (Passenger*)malloc((seatCount)*10*sizeof(Passenger));
(*flightsP)[(*flightCountP) - 1].closed = 0;
for(i=0;i<4;i++)
(*flightsP)[(*flightCountP) - 1].passengerCount[i] = 0;
}
else
{
if((*flightsP)[index].seatQuota[(int)seatClass] == 0)
{
(*flightsP)[index].seatQuota[(int)seatClass] = seatCount;
(*flightsP)[index].queues[(int)seatClass] = (Passenger*)malloc((seatCount)*sizeof(Passenger));
}
else
{
(*flightsP)[index].seatQuota[(int)seatClass] = (*flightsP)[index].seatQuota[(int)seatClass] + seatCount;
(*flightsP)[index].queues[(int)seatClass] = (Passenger*)realloc((*flightsP)[index].queues[(int)seatClass],((*flightsP)[index].seatQuota[(int)seatClass])*sizeof(Passenger));
}
}
}
fprintf(output,"addseats ");
fprintf(output,"%s",flightName);
fprintf(output," ");
fprintf(output,"%d",(*flightsP)[index].seatQuota[0]);
fprintf(output," ");
fprintf(output,"%d",(*flightsP)[index].seatQuota[1]);
fprintf(output," ");
fprintf(output,"%d",(*flightsP)[index].seatQuota[2]);
fprintf(output,"\n");
}
void enqueue(Flight** flightsP,char* priorityS,char* passengerNameA,enum seatClasses seatClass,char* flightName,int flightCount,FILE* output)
{
enum priorities priority = priorityToIndex(priorityS);
int i,index=-1,index2=-1,counter;
for(i=0;i<strlen(passengerNameA);i++)
{
if(((int)passengerNameA[i] >= 65 && (int)passengerNameA[i] <= 122) || ((int)passengerNameA[i] >= 48 && (int)passengerNameA[i] <= 57))
{
counter++;
}
}
char* passengerName = (char*)malloc(counter*sizeof(char));
counter=0;
for(i=0;i<strlen(passengerNameA);i++)
{
if((int)passengerNameA[i] >= 65 && (int)passengerNameA[i] <= 122 || ((int)passengerNameA[i] >= 48 && (int)passengerNameA[i] <= 57))
{
passengerName[counter]=passengerNameA[i];
counter++;
}
}
if((int)priority == -1)
{
fprintf(output,"error\n");
return;
}
for(i=0;i<flightCount;i++)
{
if(strcmp((*flightsP)[i].name,flightName)==0)
{
index=i;
break;
}
}
if(((int)seatClass == 0) && ((int)priority == 0))
{
fprintf(output,"error\n");
return;
}
if(((int)seatClass == 1) && ((int)priority == 1))
{
fprintf(output,"error\n");
return;
}
if((((int)seatClass == 2) && ((int)priority == 0)) || (((int)seatClass == 2) && ((int)priority == 1)))
{
fprintf(output,"error\n");
return;
}
if(index==-1)
{
fprintf(output,"error\n");
return;
}
if((*flightsP)[index].closed == 1)
{
fprintf(output,"error\n");
return;
}
if((*flightsP)[index].seatQuota[(int)seatClass]>(*flightsP)[index].passengerCount[(int)seatClass])
{
(*flightsP)[index].queues[(int)seatClass][(*flightsP)[index].passengerCount[(int)seatClass]].name = (char*)malloc((strlen(passengerName)+1)*sizeof(char));
strcpy((*flightsP)[index].queues[(int)seatClass][(*flightsP)[index].passengerCount[(int)seatClass]].name,passengerName);
(*flightsP)[index].queues[(int)seatClass][(*flightsP)[index].passengerCount[(int)seatClass]].name[strlen(passengerName)] = '\0';
(*flightsP)[index].queues[(int)seatClass][(*flightsP)[index].passengerCount[(int)seatClass]].wantedClass = (int)seatClass;
(*flightsP)[index].queues[(int)seatClass][(*flightsP)[index].passengerCount[(int)seatClass]].soldClass = (int)seatClass;
(*flightsP)[index].queues[(int)seatClass][(*flightsP)[index].passengerCount[(int)seatClass]].priority = (int)priority;
(*flightsP)[index].queues[(int)seatClass][(*flightsP)[index].passengerCount[(int)seatClass]].sold = 0;
(*flightsP)[index].passengerCount[(int)seatClass] = (*flightsP)[index].passengerCount[(int)seatClass] + 1;
}
else
{
if((int)seatClass == 0 && (int)priority == 1)
{
index2 = -1;
for(i=((*flightsP)[index].seatQuota[0]-1);i>=0;i--)
{
if(((*flightsP)[index].queues[0][i].priority == 2 || (*flightsP)[index].queues[0][i].priority == 0) && ((*flightsP)[index].queues[0][i].sold == 0))
{
index2 = i;
break;
}
}
if(index2 == -1)
{
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name = (char*)malloc((strlen(passengerName)+1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name,passengerName);
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name[strlen(passengerName)] = '\0';
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].wantedClass = (int)seatClass;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].soldClass = 3;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].priority = (int)priority;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].sold = 0;
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] + 1;
}
else
{
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name = (char*)malloc((strlen((*flightsP)[index].queues[0][index2].name)+1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name,(*flightsP)[index].queues[0][index2].name);
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name[strlen((*flightsP)[index].queues[0][index2].name)] = '\0';
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].wantedClass = (*flightsP)[index].queues[0][index2].wantedClass;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].soldClass = 3;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].priority = (*flightsP)[index].queues[0][index2].priority;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].sold = 0;
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] + 1;
if(strlen((*flightsP)[index].queues[0][index2].name) < strlen(passengerName))
{
(*flightsP)[index].queues[0][index2].name = (char*)realloc((*flightsP)[index].queues[0][index2].name,(strlen(passengerName)+1)*sizeof(char));
}
strcpy((*flightsP)[index].queues[0][index2].name,passengerName);
(*flightsP)[index].queues[0][index2].name[strlen(passengerName)] = '\0';
(*flightsP)[index].queues[0][index2].wantedClass = 0;
(*flightsP)[index].queues[0][index2].soldClass = 0;
(*flightsP)[index].queues[0][index2].priority = 1;
}
}
else if((int)seatClass == 1 && (int)priority == 0)
{
index2 = -1;
for(i=((*flightsP)[index].seatQuota[1]-1);i>=0;i--)
{
if(((*flightsP)[index].queues[1][i].priority == 1 || (*flightsP)[index].queues[1][i].priority == 2) && ((*flightsP)[index].queues[1][i].sold == 0))
{
index2 = i;
break;
}
}
if(index2 == -1)
{
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name = (char*)malloc((strlen(passengerName)+1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name,passengerName);
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name[strlen(passengerName)] = '\0';
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].wantedClass = (int)seatClass;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].soldClass = 3;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].priority = (int)priority;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].sold = 0;
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] + 1;
}
else
{
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name = (char*)malloc((strlen((*flightsP)[index].queues[1][index2].name)+1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name,(*flightsP)[index].queues[1][index2].name);
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name[strlen((*flightsP)[index].queues[1][index2].name)] = '\0';
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].wantedClass = (*flightsP)[index].queues[1][index2].wantedClass;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].soldClass = 3;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].priority = (*flightsP)[index].queues[1][index2].priority;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].sold = 0;
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] + 1;
if(strlen((*flightsP)[index].queues[1][index2].name) < strlen(passengerName))
{
(*flightsP)[index].queues[1][index2].name = (char*)realloc((*flightsP)[index].queues[1][index2].name,(strlen(passengerName)+1)*sizeof(char));
}
strcpy((*flightsP)[index].queues[1][index2].name,passengerName);
(*flightsP)[index].queues[1][index2].name[strlen(passengerName)] = '\0';
(*flightsP)[index].queues[1][index2].wantedClass = 1;
(*flightsP)[index].queues[1][index2].soldClass = 1;
(*flightsP)[index].queues[1][index2].priority = 0;
}
}
else
{
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name = (char*)malloc((strlen(passengerName)+1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name,passengerName);
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].name[strlen(passengerName)] = '\0';
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].wantedClass = (int)seatClass;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].soldClass = 3;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].priority = (int)priority;
(*flightsP)[index].queues[3][(*flightsP)[index].passengerCount[3]].sold = 0;
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] + 1;
}
}
fprintf(output,"queue ");
fprintf(output,"%s",flightName);
fprintf(output," ");
fprintf(output,"%s",passengerName);
fprintf(output," ");
fprintf(output,"%s",enumToSeatNames(seatClass));
fprintf(output," ");
counter = (*flightsP)[index].passengerCount[(int)seatClass];
for(i=0;i<(*flightsP)[index].passengerCount[3];i++)
{
if((*flightsP)[index].queues[3][i].wantedClass == seatClass)
counter++;
}
fprintf(output,"%d",counter);
fprintf(output,"\n");
}
void sell(Flight** flightsP,int flightCount,char* flightNameA,FILE* output)
{
int i,j,k,index=-1,index2,counter=0;
for(i=0;i<strlen(flightNameA);i++)
{
if(((int)flightNameA[i] >= 65 && (int)flightNameA[i] <= 122) || ((int)flightNameA[i] >= 48 && (int)flightNameA[i] <= 57))
{
counter++;
}
}
char* flightName = (char*)malloc(counter*sizeof(char));
counter=0;
for(i=0;i<strlen(flightNameA);i++)
{
if((int)flightNameA[i] >= 65 && (int)flightNameA[i] <= 122 || ((int)flightNameA[i] >= 48 && (int)flightNameA[i] <= 57))
{
flightName[counter]=flightNameA[i];
counter++;
}
}
for(i=0;i<flightCount;i++)
{
if(strcmp((*flightsP)[i].name,flightName)==0)
{
index = i;
break;
}
}
if(index==-1)
{
fprintf(output,"error\n");
return;
}
if((*flightsP)[index].closed == 1)
{
fprintf(output,"error\n");
return;
}
if((*flightsP)[index].seatQuota[2]>(*flightsP)[index].passengerCount[2])
{
for(i=(*flightsP)[index].passengerCount[2];i<(*flightsP)[index].seatQuota[2];i++)
{
for(j=0;j<((*flightsP)[index].passengerCount[3]);j++)
{
if(((*flightsP)[index].queues[3][j].wantedClass) == 2)
{
(*flightsP)[index].queues[2][i].name = (char*)malloc((strlen((*flightsP)[index].queues[3][j].name) + 1) * sizeof(char));
strcpy((*flightsP)[index].queues[2][i].name,(*flightsP)[index].queues[3][j].name);
(*flightsP)[index].queues[2][i].name[strlen((*flightsP)[index].queues[3][j].name)] = '\0';
(*flightsP)[index].queues[2][i].wantedClass = 2;
(*flightsP)[index].queues[2][i].soldClass = 2;
(*flightsP)[index].queues[2][i].priority = (*flightsP)[index].queues[3][j].priority;
(*flightsP)[index].passengerCount[2] = (*flightsP)[index].passengerCount[2] + 1;
for(k=j;k<((*flightsP)[index].passengerCount[3] - 1);k++)
{
if(strlen((*flightsP)[index].queues[3][k].name) < strlen((*flightsP)[index].queues[3][k+1].name))
(*flightsP)[index].queues[3][k].name = (char*)realloc((*flightsP)[index].queues[3][k].name,((strlen((*flightsP)[index].queues[3][k+1].name)) + 1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][k].name,(*flightsP)[index].queues[3][k+1].name);
(*flightsP)[index].queues[3][k].name[strlen((*flightsP)[index].queues[3][k+1].name)] = '\0';
(*flightsP)[index].queues[3][k].wantedClass = (*flightsP)[index].queues[3][k+1].wantedClass;
(*flightsP)[index].queues[3][k].priority = (*flightsP)[index].queues[3][k+1].priority;
}
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] - 1;
break;
}
}
}
}
if((*flightsP)[index].seatQuota[2]>(*flightsP)[index].passengerCount[2])
{
for(i=(*flightsP)[index].passengerCount[2];i<(*flightsP)[index].seatQuota[2];i++)
{
for(j=0;j<((*flightsP)[index].passengerCount[3]);j++)
{
if(((*flightsP)[index].queues[3][j].wantedClass) == 0)
{
(*flightsP)[index].queues[2][i].name = (char*)malloc((strlen((*flightsP)[index].queues[3][j].name) + 1) * sizeof(char));
strcpy((*flightsP)[index].queues[2][i].name,(*flightsP)[index].queues[3][j].name);
(*flightsP)[index].queues[2][i].name[strlen((*flightsP)[index].queues[3][j].name)] = '\0';
(*flightsP)[index].queues[2][i].wantedClass = 0;
(*flightsP)[index].queues[2][i].soldClass = 2;
(*flightsP)[index].queues[2][i].priority = (*flightsP)[index].queues[3][j].priority;
(*flightsP)[index].passengerCount[2] = (*flightsP)[index].passengerCount[2] + 1;
for(k=j;k<((*flightsP)[index].passengerCount[3] - 1);k++)
{
if(strlen((*flightsP)[index].queues[3][k].name) < strlen((*flightsP)[index].queues[3][k+1].name))
(*flightsP)[index].queues[3][k].name = (char*)realloc((*flightsP)[index].queues[3][k].name,((strlen((*flightsP)[index].queues[3][k+1].name)) + 1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][k].name,(*flightsP)[index].queues[3][k+1].name);
(*flightsP)[index].queues[3][k].name[strlen((*flightsP)[index].queues[3][k+1].name)] = '\0';
(*flightsP)[index].queues[3][k].wantedClass = (*flightsP)[index].queues[3][k+1].wantedClass;
(*flightsP)[index].queues[3][k].priority = (*flightsP)[index].queues[3][k+1].priority;
}
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] - 1;
break;
}
}
}
}
if((*flightsP)[index].seatQuota[2]>(*flightsP)[index].passengerCount[2])
{
for(i=(*flightsP)[index].passengerCount[2];i<(*flightsP)[index].seatQuota[2];i++)
{
for(j=0;j<((*flightsP)[index].passengerCount[3]);j++)
{
if(((*flightsP)[index].queues[3][j].wantedClass) == 1)
{
(*flightsP)[index].queues[2][i].name = (char*)malloc((strlen((*flightsP)[index].queues[3][j].name) + 1) * sizeof(char));
strcpy((*flightsP)[index].queues[2][i].name,(*flightsP)[index].queues[3][j].name);
(*flightsP)[index].queues[2][i].name[strlen((*flightsP)[index].queues[3][j].name)] = '\0';
(*flightsP)[index].queues[2][i].wantedClass = 1;
(*flightsP)[index].queues[2][i].soldClass = 2;
(*flightsP)[index].passengerCount[2] = (*flightsP)[index].passengerCount[2] + 1;
for(k=j;k<((*flightsP)[index].passengerCount[3] - 1);k++)
{
if(strlen((*flightsP)[index].queues[3][k].name) < strlen((*flightsP)[index].queues[3][k+1].name))
(*flightsP)[index].queues[3][k].name = (char*)realloc((*flightsP)[index].queues[3][k].name,((strlen((*flightsP)[index].queues[3][k+1].name)) + 1)*sizeof(char));
strcpy((*flightsP)[index].queues[3][k].name,(*flightsP)[index].queues[3][k+1].name);
(*flightsP)[index].queues[3][k].name[strlen((*flightsP)[index].queues[3][k+1].name)] = '\0';
(*flightsP)[index].queues[3][k].wantedClass = (*flightsP)[index].queues[3][k+1].wantedClass;
(*flightsP)[index].queues[3][k].priority = (*flightsP)[index].queues[3][k+1].priority;
}
(*flightsP)[index].passengerCount[3] = (*flightsP)[index].passengerCount[3] - 1;
break;
}
}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<(*flightsP)[index].passengerCount[i];j++)
{
(*flightsP)[index].queues[i][j].sold = 1;
}
}
fprintf(output,"sold ");
fprintf(output,"%s",flightName);
fprintf(output," ");
fprintf(output,"%d",(*flightsP)[index].passengerCount[0]);
fprintf(output," ");
fprintf(output,"%d",(*flightsP)[index].passengerCount[1]);
fprintf(output," ");
fprintf(output,"%d",(*flightsP)[index].passengerCount[2]);
fprintf(output,"\n");
}
void close(Flight** flightsP,int flightCount,char* flightNameA,FILE* output)
{
int i,j,counterSold,counterWaits,index=-1,counter;
for(i=0;i<strlen(flightNameA);i++)
{
if(((int)flightNameA[i] >= 65 && (int)flightNameA[i] <= 122) || ((int)flightNameA[i] >= 48 && (int)flightNameA[i] <= 57))
{
counter++;
}
}
char* flightName = (char*)malloc(counter*sizeof(char));
counter=0;
for(i=0;i<strlen(flightNameA);i++)
{
if((int)flightNameA[i] >= 65 && (int)flightNameA[i] <= 122 || ((int)flightNameA[i] >= 48 && (int)flightNameA[i] <= 57))
{
flightName[counter]=flightNameA[i];
counter++;
}
}
for(i=0;i<flightCount;i++)
{
if(strcmp((*flightsP)[i].name,flightName) == 0)
{
index = i;
break;
}
}
(*flightsP)[i].closed = 1;
fprintf(output,"closed ");
fprintf(output,"%s",flightName);
counterSold = 0,counterWaits = 0;
for(i=0;i<3;i++)
{
for(j=0;j<(*flightsP)[index].passengerCount[i];j++)
{
if((*flightsP)[index].queues[i][j].sold == 1)
counterSold++;
else
counterWaits++;
}
}
counterWaits += (*flightsP)[index].passengerCount[3];
fprintf(output," ");
fprintf(output,"%d",counterSold);
fprintf(output," ");
fprintf(output,"%d",counterWaits);
fprintf(output,"\n");
for(j=0;j<(*flightsP)[index].passengerCount[0];j++)
{
if(((*flightsP)[index].queues[0][j].sold == 0) && ((*flightsP)[index].queues[0][j].priority == 1) && ((*flightsP)[index].queues[0][j].wantedClass == 0))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[0][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(*flightsP)[index].passengerCount[0];j++)
{
if(((*flightsP)[index].queues[0][j].sold == 0) && ((*flightsP)[index].queues[0][j].priority == 2) && ((*flightsP)[index].queues[0][j].wantedClass == 0))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[0][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(*flightsP)[index].passengerCount[3];j++)
{
if(((*flightsP)[index].queues[3][j].sold == 0) && ((*flightsP)[index].queues[3][j].priority == 2) && ((*flightsP)[index].queues[3][j].wantedClass == 0))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[3][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(*flightsP)[index].passengerCount[1];j++)
{
if(((*flightsP)[index].queues[1][j].sold == 0) && ((*flightsP)[index].queues[1][j].priority == 0) && ((*flightsP)[index].queues[1][j].wantedClass == 1))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[1][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(*flightsP)[index].passengerCount[1];j++)
{
if(((*flightsP)[index].queues[1][j].sold == 0) && ((*flightsP)[index].queues[1][j].priority == 2) && ((*flightsP)[index].queues[1][j].wantedClass == 1))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[1][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(*flightsP)[index].passengerCount[3];j++)
{
if(((*flightsP)[index].queues[3][j].sold == 0) && ((*flightsP)[index].queues[3][j].priority == 2) && ((*flightsP)[index].queues[3][j].wantedClass == 1))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[3][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(*flightsP)[index].passengerCount[2];j++)
{
if(((*flightsP)[index].queues[2][j].sold == 0) && ((*flightsP)[index].queues[2][j].priority == 2) && ((*flightsP)[index].queues[2][j].wantedClass == 2))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[2][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(*flightsP)[index].passengerCount[3];j++)
{
if(((*flightsP)[index].queues[3][j].sold == 0) && ((*flightsP)[index].queues[3][j].priority == 2) && ((*flightsP)[index].queues[3][j].wantedClass == 2))
{
fprintf(output,"waiting ");
fprintf(output,"%s",(*flightsP)[index].queues[3][j].name);
fprintf(output,"\n");
}
}
}
void report(Flight* flights,int flightCount,char* flightNameA,FILE* output)
{
int i,j,solded,index=-1,counter;
for(i=0;i<strlen(flightNameA);i++)
{
if(((int)flightNameA[i] >= 65 && (int)flightNameA[i] <= 122) || ((int)flightNameA[i] >= 48 && (int)flightNameA[i] <= 57))
{
counter++;
}
}
char* flightName = (char*)malloc(counter*sizeof(char));
counter=0;
for(i=0;i<strlen(flightNameA);i++)
{
if((int)flightNameA[i] >= 65 && (int)flightNameA[i] <= 122 || ((int)flightNameA[i] >= 48 && (int)flightNameA[i] <= 57))
{
flightName[counter]=flightNameA[i];
counter++;
}
}
for(i=0;i<flightCount;i++)
{
if(strcmp(flights[i].name,flightName) == 0)
{
index = i;
break;
}
}
fprintf(output,"report ");
fprintf(output,"%s",flightName);
fprintf(output,"\n");
for(i=0;i<3;i++)
{
solded = 0;
for(j=0;j<(flights[index].passengerCount[i]);j++)
{
if(flights[index].queues[i][j].sold == 1)
solded++;
}
fprintf(output,"%s",enumToSeatNames(i));
fprintf(output," ");
fprintf(output,"%d",solded);
fprintf(output,"\n");
for(j=0;j<(flights[index].passengerCount[i]);j++)
{
if(flights[index].queues[i][j].sold == 1 && flights[index].queues[i][j].priority == (-(i-1)))
{
fprintf(output,"%s",flights[index].queues[i][j].name);
fprintf(output,"\n");
}
}
for(j=0;j<(flights[index].passengerCount[i]);j++)
{
if(flights[index].queues[i][j].sold == 1 && flights[index].queues[i][j].priority != (-(i-1)))
{
fprintf(output,"%s",flights[index].queues[i][j].name);
fprintf(output,"\n");
}
}
}
fprintf(output,"end of report ");
fprintf(output,"%s",flightName);
fprintf(output,"\n");
}
void info(Flight* flights,int flightCount,char* passengerNameA,FILE* output)
{
int i,j,k,counter;
for(i=0;i<strlen(passengerNameA);i++)
{
if(((int)passengerNameA[i] >= 65 && (int)passengerNameA[i] <= 122) || ((int)passengerNameA[i] >= 48 && (int)passengerNameA[i] <= 57))
{
counter++;
}
}
char* passengerName = (char*)malloc(counter*sizeof(char));
counter=0;
for(i=0;i<strlen(passengerNameA);i++)
{
if((int)passengerNameA[i] >= 65 && (int)passengerNameA[i] <= 122 || ((int)passengerNameA[i] >= 48 && (int)passengerNameA[i] <= 57))
{
passengerName[counter]=passengerNameA[i];
counter++;
}
}
for(i=0;i<flightCount;i++)
{
for(j=0;j<4;j++)
{
for(k=0;k<flights[i].passengerCount[j];k++)
{
if(strcmp(flights[i].queues[j][k].name,passengerName) == 0)
{
fprintf(output,"info ");
fprintf(output,"%s",passengerName);
fprintf(output," ");
fprintf(output,"%s",flights[i].name);
fprintf(output," ");
fprintf(output,"%s",enumToSeatNames(flights[i].queues[j][k].wantedClass));
fprintf(output," ");
if(flights[i].queues[j][k].soldClass == 3)
{
fprintf(output,"none");
}
else
{
fprintf(output,"%s",enumToSeatNames(flights[i].queues[j][k].soldClass));
}
fprintf(output,"\n");
return;
}
}
}
}
fprintf(output,"error\n");
}
|
C
|
#include<stdio.h>
int main(void)
{
char var,var2;
scanf("%c %c", &var,&var2);
printf("%c %c\n", var2,var);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "libcsv/csv.h"
#include <unistd.h>
#include <string.h>
#define CHUNK_SIZE 128
#define CSV_MODE_SET 0
#define CSV_MODE_GET 1
#define MAX_HEADERS 50
#define DEBUG 0
/**
* Usage:
* csvr [-s <set value>] <row> <col name/offset> [file.csv]
*
*/
struct parse_info {
int found_record;
char *found_value;
int rows;
int cols;
int curr_row;
int curr_col;
int tar_row;
int tar_col;
int mode;
FILE *output_file;
char *tar_col_name;
char *headers[MAX_HEADERS];
};
/**
* Create a new parse_info struct, and set it's default values
* This struct is what is used to store the results returned from the parser.
*/
void Construct_parse_info(struct parse_info *i) {
i->tar_col_name = NULL;
i->found_value = NULL;
i->tar_col = i->tar_row = -1;
i->curr_row = i->cols = i->curr_col = 0;
i->found_record = 0;
i->mode = -1;
}
/**
* Destroy the parse_info struct
*/
void Destruct_parse_info(struct parse_info *i) {
int j;
if (i->found_value) {
free(i->found_value);
}
if (i->tar_col_name) {
free(i->tar_col_name);
}
for (j = 0; j < MAX_HEADERS; j++) {
if (! i->headers[j]) {
break;
}
free(i->headers[j]);
}
free(i);
}
/**
* Figure out if the column given is a string or a number,
* and save the value to the parse_info struct
*/
int setup_text_col_selector(int col, char *input, struct parse_info *info) {
// PROBLEM HERE! What if the column **name** in the file is 0? Or any other number?
int input_len = strlen(input);
if (input_len == 1 && input[0] == '0') {
return 0;
}
// User supplied a text string instead
info->tar_col_name = malloc(sizeof(char) * input_len);
strncpy(info->tar_col_name, input, input_len + 1);
return -2;
}
/**
* The callback passed to libcsv for each field (column)
*
* Bug in libcsv: final record does not trigger callback unless there is a return at the end of the file.
*/
void parse_field_cb(void *record, size_t size, void *i) {
struct parse_info *info = (struct parse_info*)i;
int record_len = strlen(record);
// Set up the file headers
// File headers can still be queried for
if (info->curr_row == 0) {
info->headers[info->curr_col] = malloc(sizeof(char) * record_len + 1);
strncpy(info->headers[info->curr_col], record, record_len);
info->headers[info->curr_col][record_len] = '\0';
info->cols++;
}
if (info->mode == CSV_MODE_SET) {
if ( (info->curr_row == info->tar_row) &&
((info->curr_col == info->tar_col) || (info->tar_col == -2 &&
strcmp(info->headers[info->curr_col], info->tar_col_name) == 0)) ) {
info->found_record = 1;
csv_fwrite(info->output_file, info->found_value, strlen(info->found_value));
} else {
csv_fwrite(info->output_file, record, size);
}
putc(',', info->output_file);
} else {
if ( (info->curr_row == info->tar_row) &&
((info->curr_col == info->tar_col) || (info->tar_col == -2 &&
strcmp(info->headers[info->curr_col], info->tar_col_name) == 0)) ) {
info->found_record = 1;
info->found_value = malloc(sizeof(char) * record_len + 1);
strncpy(info->found_value, record, record_len);
info->found_value[record_len] = '\0';
}
}
info->curr_col++;
}
/**
* The callback that is passed to libcsv at the end of a record (row)
* Simply increments the counters and resets the col index
*/
void parse_record_cb(int term_char, void *i) {
struct parse_info *info = (struct parse_info*)i;
if (info->mode == CSV_MODE_SET) {
// Fix writing an extra , at the end of each line
fseek(info->output_file, -1, SEEK_CUR);
putc('\n', info->output_file);
}
info->curr_row++;
info->rows++;
info->curr_col = 0;
}
/**
* Gets a single field value from the target CSV file
* Kicks off libcsv to do so
* TODO: add error message for a not found header name
*/
int get_field_value(FILE *file, struct csv_parser *p, struct parse_info *i)
{
char *chunk = malloc(sizeof(char) * CHUNK_SIZE);
size_t read;
size_t processed;
// Main loop
while((read = fread(chunk, sizeof(char), CHUNK_SIZE, file)) >= 1) {
processed = csv_parse(p, chunk, sizeof(char) * read, &parse_field_cb, &parse_record_cb, i);
}
csv_fini(p, &parse_field_cb, &parse_record_cb, i);
csv_free(p);
free(chunk);
return 0;
}
int set_field_value(FILE *file, struct csv_parser *p, struct parse_info *i)
{
char *chunk = malloc(sizeof(char) * CHUNK_SIZE);
size_t read;
size_t processed;
// Main loop
while((read = fread(chunk, sizeof(char), CHUNK_SIZE, file)) >= 1) {
processed = csv_parse(p, chunk, sizeof(char) * read, &parse_field_cb, &parse_record_cb, i);
}
csv_fini(p, &parse_field_cb, &parse_record_cb, i);
csv_free(p);
free(chunk);
return 0;
}
/**
* Main function
* Processes options and then kicks off the file search if the file is a valid
* file pointer.
*/
int main(int argc, char *argv[]) {
int rc = 0, optch;
char *set_value = NULL;
FILE *input;
const char *valid_opts = "r:c:s:v";
const char *usage =
"Usage: csvr [-s <new value>] <row> <col index/name> [<file>]";
const char *v_info =
"0.2.1";
struct csv_parser *p = malloc(sizeof(struct csv_parser));
struct parse_info *i = malloc(sizeof(struct parse_info));
Construct_parse_info(i);
// No options provided is invalid
if (argc <= 1) {
printf("%s\n", usage);
goto error;
}
// Iterate over all the -x options
while((optch = getopt(argc, argv, valid_opts)) != -1) {
switch(optch) {
// Row
// Legacy; row & col offset should be passed without the -r / -c flags
case 'r':
i->tar_row = atoi(optarg);
if (i->tar_row < 0) {
printf("%s\n", "Error: -r <row> must be a positive integer (cheeky!)");
rc = 1; // Invalid input
goto error;
}
break;
// Column
case 'c':
i->tar_col = atoi(optarg);
// Icky code to get around atoi limitation of returning 0 on a failed parse,
// which is a perfectly reasonable input
if (i->tar_col == 0) {
i->tar_col = setup_text_col_selector(i->tar_col, optarg, i);
}
break;
// Set to a value
case 's':
i->mode = CSV_MODE_SET;
i->found_value = malloc(sizeof(char) * (strlen(optarg) + 1));
strncpy(i->found_value, optarg, strlen(optarg) + 1);
break;
case 'v':
printf("%s\n", v_info);
goto error;
default:
printf("%s\n", usage);
rc = 1;
goto error;
}
}
// Skip forward
argc -= optind;
argv += optind;
if (i->mode == -1) {
i->mode = CSV_MODE_GET;
}
int index = 0;
// Too many options
if (argc > 3) {
printf("%s\n", usage);
rc = 1;
goto error;
}
switch(argc) {
// Just the file or nothing
case 1:
goto parsefile;
break;
// The col and row, or both + file
case 2:
case 3:
goto parsetarget;
}
parsetarget:
// Parse row
i->tar_row = atoi(argv[index]);
if (i->tar_row < 0) {
printf("%s\n", "Error: -r <row> must be a positive integer (cheeky!)");
rc = 1; // Invalid input
goto error;
}
index++;
i->tar_col = atoi(argv[index]);
// Icky code to get around atoi limitation of returning 0 on a failed parse,
// which is a perfectly reasonable input
if (i->tar_col == 0) {
i->tar_col = setup_text_col_selector(i->tar_col, argv[index], i);
}
index++;
parsefile:
if (index < argc) {
input = fopen(argv[index], "r");
if (input == NULL) {
printf("Error: file not found\n");
rc = 2; // Missing file
goto error;
}
} else {
input = stdin;
}
if (i->tar_col < 0 && i->tar_col_name == NULL) {
printf("Error: -c <column> must be a positive integer or a string denoting the column names\n");
rc = 1;
goto error;
}
// If the target never got set because the option wasn't passed
if (i->tar_row == -1 || i->tar_col == -1) {
printf("Error: row or column not set\n");
printf("%s\n", usage);
rc = 1;
goto error;
}
csv_init(p, CSV_APPEND_NULL);
if (i->mode == CSV_MODE_GET) {
rc = get_field_value(input, p, i);
} else {
i->output_file = tmpfile();
rc = set_field_value(input, p, i);
fseek(i->output_file, 0, SEEK_SET);
fclose(input);
FILE *output = fopen(argv[index], "w");
if (!output) {
output = stdout;
}
char *chunk = malloc(sizeof(char) * 100);
int read = 0;
while((read = fread(chunk, sizeof(char), 100, i->output_file)) > 0) {
fwrite(chunk, sizeof(char), read, output);
}
}
if (i->found_record == 1) {
if (i->mode == CSV_MODE_GET) {
printf("%s\n", i->found_value);
}
} else {
rc = 3; // Missing record
if (i->tar_row >= i->rows) {
printf("Row offset does not exist.\n");
}
if (i->tar_col >= i->cols) {
printf("Column offset does not exist.\n");
}
if (i->tar_col == -1 && i->tar_row) {
//printf("Column name \"%s\" does not exist.\n", i->tar_col_name);
}
}
error:
if (set_value) {
free(set_value);
}
Destruct_parse_info(i);
return rc;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
int N = 1000000;
float worker_output;
float master_output;
int sign(int n)
{
if(n % 2 == 0)
return 1;
else
return -1;
}
void *worker(void *arg)
{
int i;
for(i = N / 2; i < N; i++)
worker_output += (float)sign(i) / (2*i + 1);
printf("worker_output = %.10f\n", worker_output);
return NULL;
}
void master()
{
for(int i = 0; i < N / 2; i++)
master_output += (float)sign(i) / (2*i + 1);
printf("master_output = %.10f\n", master_output);
return;
}
int main()
{
pthread_t worker_tid;
float total;
pthread_create(&worker_tid, NULL, worker, NULL);
master();
pthread_join(worker_tid, NULL);
total = worker_output + master_output;
printf("PI = %.10f\n", total * 4);
return 0;
}
|
C
|
//-----------------
// ??????
// Version 2.0
// ???
//-----------------
int main()
{
int i=0,j=0,blank=0,words=0,temp=0; //i,j??, blank?????????,words?????
char str[101];
cin.get(str,101,'\n'); //????
while(str[i]!='\0')
{
if(str[i]==' ')
{
if(str[i-1]!=' ')
words++;
temp++;
str[i-blank+words-1]=str[i];
}
if(str[i]!=' '&&(blank!=words))
{
blank=blank+temp;
temp=0;
str[i-blank+words]=str[i];
}
i++;
}
str[i-blank+words]='\0';
cout<<str;
return 0;
}
|
C
|
#include "LPC17xx.h"
#include "math_utils.h"
uint32_t math_calc_diff(uint32_t value1, uint32_t value2) {
if (value1 == value2) {
return 0;
}
if (value1 > value2) {
return (value1 - value2);
}
else {
// check for overflow
return (UINT32_MAX - value2 + value1);
}
}
|
C
|
#ifndef STACK_H
#define STACK_H
#include "objects.h"
FUNC Stack sk_new( MemoryLifetime ml ) ALWAYS_NEW;
FUNC int sk_depth ( Stack sk );
FUNC void sk_push ( Stack sk, Object ob );
FUNC Object sk_item ( Stack sk, int depth );
FUNC void sk_popN ( Stack sk, int count );
FUNC void sk_dupN ( Stack target, int count, Stack source );
FUNC void sk_mirrorN( Stack target, int count, Stack source );
static inline Object sk_top ( Stack sk ){ return sk_item( sk, 0 ); }
static inline Object sk_pop ( Stack sk ){ Object result = sk_top(sk); sk_popN( sk, 1 ); return result; }
static inline void sk_popAll ( Stack sk ){ sk_popN( sk, sk_depth( sk ) ); }
static inline bool sk_isEmpty( Stack sk ){ return sk_depth( sk ) == 0; }
static inline Stack sk_dup ( Stack sk, MemoryLifetime ml ){ Stack result = sk_new( ml ); sk_dupN ( result, sk_depth( sk ), sk ); return result; }
static inline Stack sk_mirror ( Stack sk, MemoryLifetime ml ){ Stack result = sk_new( ml ); sk_mirrorN ( result, sk_depth( sk ), sk ); return result; }
FUNC int sk_sendNTo( Stack sk, int numElements, File fl, ObjectHeap heap );
static inline int sk_sendTo( Stack sk, File fl, ObjectHeap heap )
{ return sk_sendNTo( sk, sk_depth(sk), fl, heap ); }
FUNC int sk_sendNFormattedToX( Stack sk, int numElements, File fl, ObjectFormat format, void *context, char *separator );
static inline int sk_sendFormattedToX( Stack sk, File fl, ObjectFormat format, void *context, char *separator )
{ return sk_sendNFormattedToX( sk, sk_depth(sk), fl, format, context, separator ); }
static inline int sk_sendNFormattedTo( Stack sk, int numElements, File fl, ObjectFormat format, void *context )
{ return sk_sendNFormattedToX( sk, numElements, fl, format, context, ", " ); }
static inline int sk_sendFormattedTo( Stack sk, File fl, ObjectFormat format, void *context )
{ return sk_sendNFormattedTo( sk, sk_depth(sk), fl, format, context ); }
#endif
|
C
|
#include "auto_header.h"
#include <fcntl.h>
#include <stdio.h>
static t_prot *find_prototypes(char *folder, char *name)
{
int fd;
char *path;
char *line;
t_prot *list;
t_prot *temporary;
list = (void *)0;
path = get_full_path(folder, name);
if (!(fd = open(path, O_RDONLY)))
parsing_errors(ERROR_HEADER, path);
while (get_next_line(fd, &line))
{
if (is_prototype(line))
{
if (list)
{
temporary->next = add_prototype(temporary, line);
temporary = temporary->next;
}
else
{
temporary = new_prototype(line);
list = temporary;
}
}
}
return (list);
}
int parsing_prototypes(t_auto_header *core)
{
t_dir *temporary_dir;
t_list *temporary_list;
temporary_dir = core->sources_folders->directories;
while (temporary_dir)
{
temporary_list = temporary_dir->files;
while (temporary_list)
{
temporary_list->prototype = find_prototypes(temporary_dir->data, temporary_list->data);
temporary_list = temporary_list->next;
}
temporary_dir = temporary_dir->next;
}
core->sources_folders->directories->max_tab = get_max_tabulation(core->sources_folders->directories);
return (0);
}
|
C
|
#include "holberton.h"
#include <stdlib.h>
/**
* _calloc - Allocate memory for an array
* @nmemb: Element of array
* @size: Size of array in bytes
* Return: array
*/
void *_calloc(unsigned int nmemb, unsigned int size)
{
unsigned int count;
char *array;
if (nmemb == 0 || size == 0)
return ('\0');
array = malloc(nmemb * size);
if (array == NULL)
return (NULL);
for (count = 0; count < (nmemb * size); count++)
array[count] = 0;
return (array);
}
|
C
|
/* ECP: FILEname=fig4_1.c */
#include <stdio.h>
/* Return True Iff N Is Prime */
int
IsPrime( unsigned long int N )
{
unsigned long int Divisor;
if( N % 2 )
for( Divisor = 3; N % Divisor; Divisor += 2 )
if( Divisor * Divisor > N )
return 1;
return N == 2 || N == 3;
}
/* Return An Odd Starting Number */
unsigned long int
FirstTrial( void )
{
unsigned long int StartingNum;
printf( "Enter a starting number: " );
if( scanf( "%lu", &StartingNum ) == 1 )
return StartingNum % 2 ? StartingNum : ++StartingNum;
printf( "Bad number entered\n" );
return 0;
}
/* Find Next Prime After Some Starting Point */
main( void )
{
unsigned long int PossiblePrime = FirstTrial( );
for( ; !IsPrime( PossiblePrime ); PossiblePrime += 2 )
;
printf( "Next largest prime is %lu\n", PossiblePrime );
}
|
C
|
/*
*
* factory_manager.c
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stddef.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
//Footprints
void tostring(char str[], int num);
int main (int argc, const char * argv[] ){
if(argc < 2 || argc > 2){
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
FILE *myFile;
int maxSizeArray = 0;
int maxcintas = 0;
//OPEN file
if((myFile = fopen(argv[1], "r")) == NULL){
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
//READ file
//Read maximum number of cintas
if(fscanf(myFile, "%d", &maxcintas) == 0){
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
//error control: MaxCintas > 0
if(maxcintas <= 0){
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
//Initialize array correspondent to maximum number of cintas(3 elements per cinta)
maxSizeArray = 3*maxcintas;
int data[maxSizeArray];
int contadorElems = 0;
int returnScan = 1;
//scan file to find numbers
while((returnScan = fscanf(myFile, "%i", &data[contadorElems])) != EOF && contadorElems < maxSizeArray){
if(returnScan == 0){
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
contadorElems++;
}
int numberPM = contadorElems/3;
//error control: check for complete parameters in each cinta
if(contadorElems % 3 != 0 || contadorElems == 0){
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
//CLOSE file
fclose(myFile);
//error control: check for negative values in triadas
for (int i = 0; i < contadorElems; i++)
{
if(data[i] <= 0 ){
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
}
int myids[numberPM];
int i = 0;
int j = 0;
//save triada's id's
while(j < numberPM){
//assign ids to array
myids[j] = data[i];
//step
j++;
i = i+3;
}
//error control: check for repeated cinta id´s as many times as maximum number of REAL cintas
for (int i = 0; i < numberPM; i++)
{
for (int j = i + 1; j < numberPM; j++){
if (myids[i] == myids[j])
{
fprintf(stderr, "[ERROR][factory manager]Invalid file.\n");
exit(-1);
}
}
}
//CREATE AS MANY SEMAPHORES AS PROCESS_MANAGERS
char semNames[numberPM][10];
sem_t *idSems[numberPM];
sem_t semts[numberPM];
for(int i = 0; i < numberPM; i++){
char nameSem[10];
if((sprintf(nameSem, "/%d", i))<0){
fprintf(stderr, "[ERROR][factory manager]Error while naming semaphore.\n");
exit (-1);
}
strcat(nameSem, "\0");
const char* ptrNameSem = nameSem;
strcpy(semNames[i], ptrNameSem);
if((idSems[i] = sem_open(ptrNameSem, O_CREAT, 0777, 0)) == SEM_FAILED){
fprintf(stderr, "[ERROR][factory manager]Error while opening semaphore.\n");
exit (-1);
}
semts[i] = *idSems[i];
}
//CREATE CHILD PROCESS (PROCESS MANAGER) acording to numberPM
pid_t pid;
pid_t childPids[numberPM];
int k;
for(k = 0; k < numberPM; k++) {
pid = fork();
if(pid < 0) {
fprintf(stderr, "[ERROR][factory_manager]Error while forking process_manager.\n");
exit(-1);
} else if (pid == 0) {//child
printf("[OK][factory_manager] Process_manager with id %d has been created.\n", data[3*k]);
char arg1s[10], arg3s[10], arg4s[10]; //args2s will be directly passed as a string.
sprintf(arg1s, "%d", data[3*k]);
sprintf(arg3s, "%d", data[3*k+1]);
sprintf(arg4s, "%d", data[3*k+2]);
execlp("./process", "./process", arg1s, semNames[k], arg3s, arg4s, (char *)NULL);
fprintf(stderr, "[ERROR][factory_manager] Process_manager with id %d has finished with errors.\n", data[3*k]);
exit(-1);
}else{//Parent
childPids[k] = pid;
}
}
if(k == numberPM){
//ACTIVATE EACH PM
for(int j = 0; j < numberPM; j++){
int status;
//SEM_POST-->Activate each waiting PM
idSems[j] = sem_open(semNames[j], O_CREAT, NULL, 0);
if(idSems[j] == SEM_FAILED){
fprintf(stderr, "[ERROR][factory_manager] Could not read semaphore.\n");
exit (-1);
}
if((sem_post(idSems[j]) == -1)){
fprintf(stderr, "[ERROR][factory_manager] Could not do V operation on semaphore.\n");
exit (-1);
}
while(waitpid(childPids[j], &status, WNOHANG) != childPids[j]);
printf("[OK][factory_manager] Process_manager with id %d has finished.\n",data[3*j]);
}
//FREE MEMORY
for(int i = 0; i < numberPM; i++){
const char* ptrNameSem = (const char*)semNames[i];
if((sem_unlink(ptrNameSem)) == -1){
fprintf(stderr, "[ERROR][factory_manager] Could not unlink semaphore.\n");
exit (-1);
}
}
for(int i = 0; i < numberPM; i++){
if((sem_close(idSems[i])) == -1){
fprintf(stderr, "[ERROR][factory_manager] Could not close semaphore.\n");
exit (-1);
}
}
printf("\n[OK][factory_manager] Finishing.\n");
return 0;
}
}
void tostring(char str[], int num)
{
int i, resto, len = 0, n;
n = num;
while (n != 0)
{
len++;
n /= 10;
}
for (i = 0; i < len; i++)
{
resto = num % 10;
num = num / 10;
str[len - (i + 1)] = resto + '0';
}
str[len] = '\0';
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
// Bloque declarativo de variable
float f,C ;
//bloque de instrucciones
printf ("Ingresar los grados Fahrenheit:\n");
scanf ("%f",&f);
C = (f-32)/1.8 ;
printf ("Los Grados Celsius es: %f\n", C);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
int main()
{
int i;
float a, b, c, x, y, d, s;
printf("This program will solve the quadratic equation in the form ax^2+bx+c.\n");
printf("\nEnter a value for a: ");
scanf("%f", &a);
printf("Enter a value for b: ");
scanf("%f", &b);
printf("Enter a value for c: "); //Scans variables of a,b and c to be used in solution
scanf("%f", &c);
d=(b*b)-(4*a*c); //General solution for the discriminant prescribed to the variable d
if(d>0) //Solving for 2 solutions of x
{
s=0.5*(d+d/d);
for( i=1; i<21; i++) //Iterates the squareroot formula to provide accurate answer
{
s=0.5*(s+d/s); //Babylonion method for solving squareroot
//printf("%d", i);
}
getch();
//printf("%f", s);
printf("\nThere are 2 solutions.\n");
x = (-1*b + s)/(2*a);
y = (-1*b - s)/(2*a);
printf("The 2 solutions for x are: %f and %f\n", x, y);
return 0;
}
else if(d==0) //General solution for 1 value of x
{
printf("\nThere is 1 solution.\n");
x = (-1*b)/(2*a);
printf("The solution for x is: %f\n", x);
return 0;
}
else if(d<0)
{
printf("\nThere are no solutions for x.\n");
return 0;
}
return 0;
}
|
C
|
#include<stdio.h>
struct tree
{
int data;
struct tree *right;
struct tree *left;
};
typedef struct tree tree;
tree *maketree(tree *root,int num)
{
if(root==NULL)
{
root=(tree*)malloc(sizeof(tree));
root->data=num;
root->right=root->left=NULL;
}
else if(num==root->data)
{
printf("Duplicate entry\n");
// return;
}
else if(num<root->data)
root->left=maketree(root->left,num);
else
root->right=maketree(root->right,num);
return root;
}
int search(tree *root,int key)
{
if(root==NULL)
return 0;
else if(root->data==key)
return 1;
else if(key<root->data)
return(search(root->left,key));
else
return(search(root->right,key));
}
tree *keyinsert(tree *root,int key)
{
int found;
found=search(root,key);
if(found)
printf("Duplicate \n");
else
{
printf("Key inserted\n");
root=maketree(root,key);
}
return root;
}
void inorder(tree *root)
{
if(root)
{
inorder(root->left);
printf("%d",root->data);
inorder(root->right);
}
}
void *postorder(tree *root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
printf("%d \t",root->data);
}
return(root);
}
void *preorder(tree *root)
{
if(root)
{
printf("%d \t",root->data);
preorder(root->left);
preorder(root->right);
}
//return(root);
}
int height(tree **root)
{
int lh,rh;
if(*root==NULL)
return 0;
else
{
lh=height(&((*root)->left));
rh=height(&((*root)->right));
//}
if(lh>rh)
return lh+1;
else
return rh+1;
}
}
main()
{
tree *root=NULL;
int h;
int ch,done=1,num,key;
while(done)
{
printf("\n1.Insert\n2.Search\n3.Key insert\n4.Inorder\n5.Preorder\n6.Postorder\n7.Height\n8.Delete");
printf("Enter your choice :\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter the element:\n");
scanf("%d",&num);
root=maketree(root,num);
break;
case 2:printf("Enter the key:\n");
scanf("%d",&key);
num=search(root,key);
if(num==1)
printf("Element is found\n");
else
printf("Element is not found\n");
break;
case 3:printf("Enter the key:\n");
scanf("%d",&key);
num=keyinsert(root,key);
break;
case 4:printf("Inorder:\n");
inorder(root);
break;
case 5:printf("Preorder\n");
preorder(root);
break;
case 6:printf("Postorder:\n");
postorder(root);
break;
case 7:h=height(&root);
printf("%d is the height\n",h);
break;
case 8:printf("Enter the key to be deleted:\n");
scanf("%d",&h);
//root=deletenode(root,h);
break;
default:done=0;
}
}
}
|
C
|
/*
*Andrew Sullivan
*Montana State University
*Newton-Rapson method for solving PDE BVP in 2D as coupled system
*Procedure:
*Notes:
*precision - double
*/
#include "BVP_header.h"
int main(int argc, char *argv[])
{
int i,j,k,l, status;
//External Input
const int p = atoi(argv[1]); //Number of field equations. Will always be twice the number of fields due to mixed derivatives
int n = atoi(argv[2]); //x grid size
int m = atoi(argv[3]); //theta grid size
const int r = atoi(argv[4]); //Newton polynomial order
const double tol = pow(10.0,atof(argv[5])); //absolute tolerance of solver
const double r_H = atof(argv[6]); //rH value
const int plotvar = atoi(argv[11]); //1 to output each iteration. 0 for only solution
const int linsolvar = 0;//atoi(argv[7]); //Linear solver type. See BVP_LSsolver.c
const double beta = 1.0; //coupling beta set to 1
const double alpha = atof(argv[7]); //coupling parameter alpha
const double chi = atof(argv[8]); //dimensionless spin parameter
const double ICalpha = atof(argv[9]); //delta for initial condition
const double ICchi = atof(argv[10]); //spin of intial guess
//const double M = r_H/2.0/sqrt(1.0-pow(chi,2.0)); //bare mass calculated from spin and rH
const double M = 2.0*r_H/sqrt(1.0-pow(chi,2.0)); //bare mass calculated from spin and rH
const double a = chi*M; //spin
int N = n*m*p; //total grid size
//Print statements
printf("\nRunning BVP with tol = %8.1e, order r = %2i.\n",tol,r);
printf("Grid size nxm = %3i x %3i. Total pts = %i.\n",n,m,N);
printf("Coupling value alpha = %.4f, beta = %.2f.\n",alpha,beta);
printf("Black hole parameters are r_H = %5.2f [Msun]. M = %5.2f [Msun].\n",r_H,M);
printf("Chi = a/M = %5.2f []. a = %5.2f [Msun].\n",chi,a);
printf("ICalpha = %.4f, ICchi = %.3f.\n",ICalpha,ICchi);
//Executable
status = BVP_main(plotvar, linsolvar, r, n, m, p, N, tol, chi, ICalpha, r_H, M, alpha, beta, ICchi);
if (status != 0)
{
printf("ERROR in BVP. status = %i.\n",status);
}
printf("End of BVP.\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N_CARDSET 1
#define N_CARD 52
#define N_DOLLAR 50//ó 50 ʱȭ Ǹ鼭 ٲϴ!
#define N_MAX_CARDNUM 13
#define N_MAX_USER 5
#define N_MAX_CARDHOLD 10
#define N_MAX_GO 17
#define N_MAX_BET 5
#define N_MIN_ENDCARD 30//迭 ũ⸦ ڷ ȣ
void printCard(int cardnum) {
if(cardnum/13==0)
printf("");
else if(cardnum/13==1)
printf("");
else if(cardnum/13==2)
printf("");
else if(cardnum/13==3)
printf("");
switch(cardnum%13)
{
case 0:
printf("A");
case 10:
printf("J");
case 11:
printf("Q");
case 12:
printf("K");
default:
printf("%d",(cardnum%13)+1);
}
return 0;
}
}
int mixCardTray(void) {
int i;
int Cardtray[N_CARD];
for(i=0;i<N_CARD;i++)
{
Cardtray[i]=i;
}//迭 迭 0~51ڸ ־.
int randnum1=rand()%52;
int randnum2=rand()%52;
srand(time(NULL));
for(i=0;i<N_CARD;i++)
{
int temp;
temp=Cardtray[randnum1];
Cardtray[randnum1]=Cardtray[randnum2];
Cardtray[randnum2]=temp;
}
int puca;//pullCardԼ ȯ ϳ 迭 ְִ ־.
//get one card from the tray
int pullCard(void) { //ī带 ϳ ִ Լ
int result;
result=CardTray[puca];
puca++;
cardIndex++;
return result;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<math.h>
#include<string.h>
/*
void bubblesort(int a[],int n)
{
for(int round=1;round<n;round++)
for(int i=0;i<n-round;i++)
{
if(a[i]>a[i+1])
{
int temp;
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
*/
void bubblesort(int a[],int n)
{
for(int round=0;round<n-1;round++)
{
int flag=0;
for(int i=0;i<n-1-round;i++)
{
if(a[i]>a[i+1])
{
flag=1;
int temp;
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
if(flag==0)
{
printf("minimum no. of round to swap : %d\n",round);
return;
}
}
}
int main()
{
int n;
printf("enter size of array to swap\n");
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
bubblesort(a,n);
printf("after swaping no. are :\n");
for(int i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define WMAX 55
#define HMAX 55
#define W_BY_H_MAX 27
int W,H;
int *good[HMAX+1][WMAX+1];
int mine[HMAX][WMAX];
int neighbours[HMAX][WMAX];
int clicked[HMAX][WMAX];
int blankcount;
int blankfound;
int boardnum;
#define DBG_BRD 0
int min(int a, int b) { return a<b ? a : b;}
int max(int a, int b) { return a>b ? a : b;}
void printboard(int w, int h, int blank);
void countneighbours(void) {
int x,y,n,xx,yy;
for (y=0;y<H;y++) {
for (x=0;x<W;x++) {
n=0;
//if (boardnum==DBG_BRD)
// printf("cn %d %d (m%d)\n",x,y,mine[y][x]);
if (mine[y][x]) {neighbours[y][x]=-1; continue; }
for (yy=max(0,y-1);yy<=min(H-1,y+1);yy++)
for (xx=max(0,x-1);xx<=min(W-1,x+1);xx++) {
//if (boardnum==DBG_BRD)
// printf(" %d %d\n",xx,yy);
n+=mine[yy][xx];
}
neighbours[y][x]=n;
}
}
}
void clearclicked(void) {
int x,y;
blankcount=0;
for (y=0;y<H;y++) {
for (x=0;x<W;x++) {
clicked[y][x]=0;
if (mine[y][x]==0) blankcount++;
}
}
}
int findzero(int *xx, int *yy) {
int x,y,bx=-1,by=-1;
for (y=0;y<H;y++) {
for (x=0;x<W;x++) {
if (neighbours[y][x]==0) {
*xx=x;
*yy=y;
return 1;
}
if (!mine[y][x]) {bx=x;by=y;}
}
}
if (bx>=0) {
*xx=bx;*yy=by;
return 1;
}
return 0;
}
void click(int x, int y) {
int xx,yy;
if (x<0 || x>=W) return;
if (y<0 || y>=H) return;
if (mine[y][x] || clicked[y][x]) return;
blankfound++;
clicked[y][x]=1;
if (neighbours[y][x]!=0) return;
for (yy=y-1;yy<=y+1;yy++)
for (xx=x-1;xx<=x+1;xx++)
click(xx,yy);
}
int increment(void) {
int x,y;
boardnum++;
for (y=0;y<H;y++) {
for (x=0;x<W;x++) {
if (mine[y][x]) mine[y][x]=0;
else {mine[y][x]=1; return 1; }
}
}
return 0;
}
void clearboard(void) {
int x,y;
boardnum=0;
for (y=0;y<H;y++)
for (x=0;x<W;x++)
mine[y][x]=0;
}
void cleargood(void) {
int i;
int *g=malloc((W*H+1)*sizeof(int));
for (i=0;i<=W*H;i++) g[i]=-1;
good[H][W]=g;
}
void boardsize(int ww, int hh) {
int sx,sy,i;
W=ww;
H=hh;
clearboard();
cleargood();
do {
blankfound=0;
countneighbours();
clearclicked();
if (good[H][W][blankcount]!=-1) continue;
if (findzero(&sx,&sy)) {
click(sx,sy);
if (blankfound==blankcount) {
good[H][W][blankcount]=boardnum;
}
}
} while (increment());
printf("%d X %d\n",W,H);
for (i=0;i<=H*W;i++) {
if (good[H][W][i]>=0) printf("%d %x\n",i,good[H][W][i]);
}
printf("\n");
//return 0;
}
void drawboard(void) {
int x,y;
char *m="c.*";
for (y=0;y<H;y++) {
for (x=0;x<W;x++) {
putchar(m[mine[y][x]+1]);
}
putchar('\n');
}
}
void drawtransposed(void) {
int x,y;
char *m="c.*";
for (x=0;x<W;x++) {
for (y=0;y<H;y++) {
putchar(m[mine[y][x]+1]);
}
putchar('\n');
}
}
void fillin(int bits) {
int y,x;
for (y=0;y<H;y++) {
for (x=0;x<W;x++) {
mine[y][x]=bits & 1;
bits>>=1;
}
}
}
int mainX(int argc, char **argv) {
int ww,hh,mines,blanks;
int tc,casenum;
for (ww=1;ww<=WMAX;ww++) {
for (hh=1;hh<=ww;hh++) {
if (ww*hh<=W_BY_H_MAX)
boardsize(ww,hh);
}
}
scanf("%d",&tc);
for (casenum=1;casenum<=tc;casenum++) {
printf("Case #%d:\n",casenum);
scanf("%d %d %d",&hh, &ww, &mines);
blanks=ww*hh-mines;
printboard(ww,hh,blanks);
}
return 0;
}
void makethreeA(int blank);
void makeone(int blank) {
int x;
for (x=0;x<W;x++) {
if (x<blank) mine[0][x]=0;
else mine[0][x]=1;
}
}
void maketwo(int blank) {
int x;
if (blank==1) {makethreeA(blank);return;}
blank=blank/2;
for (x=0;x<W;x++) {
if (x<blank) mine[0][x]=0;
else mine[0][x]=1;
mine[1][x]=mine[0][x];
}
}
void allmines(void) {
int x,y;
for (y=0;y<H;y++) {
for (x=0;x<W;x++) {
mine[y][x]=1;
}
}
}
void deminerow(int y, int n) {
int x;
for (x=0;x<n;x++) mine[y][x]=0;
}
void makethreeA(int blank) {
allmines();
if (blank>=1) mine[0][0]=0;
if (blank>=4) {
mine[0][1]=
mine[1][0]=
mine[1][1]=0;
}
if (blank>=6) {
mine[0][2]=
mine[1][2]=0;
}
if (blank>=8) {
mine[2][0]=
mine[2][1]=0;
}
}
void makethree(int blank) {
int p2,p1,p0,r,w,i;
if (blank<9) {makethreeA(blank); return; }
w=W;
again:
r=blank/w;
p2=w;
p1=w;
p0=blank % w;
if (p0) r++;
else p0=w;
if (r<3) {
w=blank/3;
if (blank % 3) w++;
goto again;
}
if (p0 == 1) {
if (r==3) {
p0+=2;
p1--;
p2--;
} else {
p0++;
p1--;
}
}
allmines();
for (i=0;i<r-3;i++) {
deminerow(i,w);
}
deminerow(r-3,p2);
deminerow(r-2,p1);
deminerow(r-1,p0);
}
void testblank(int blank) {
blankfound=0;
countneighbours();
clearclicked();
click(0,0);
if (blankfound!=blank) {
printf("FAIL %d X %d\n",W,H);
printf(" %d %d\n",blank,blankfound);
drawboard();
printf("\n");
} else {
//printf("%d X %d [%d]\n",W,H,blank);
//drawboard();
//printf("\n");
}
}
int mainY(int argc, char **argv) {
//size 1 boards
int blank;
H=1;
for (W=1;W<=WMAX;W++) {
for (blank=1;blank<=W;blank++) {
makeone(blank);
testblank(blank);
}
}
//size 2 boards
H=2;
for (W=4;W<=WMAX;W++) {
for (blank=4;blank<=2*W;blank+=2) {
maketwo(blank);
testblank(blank);
}
}
printf("size 3\n");
//size3 + boards
for (H=3;H<=HMAX;H++) {
for (W=3;W<=WMAX;W++) {
for (blank=4;blank<=W*H;blank++) {
if ((blank & 1) && blank<9) continue;
makethree(blank);
testblank(blank);
}
}
}
return 0;
}
void printboard(int w, int h, int blank) {
int transpose=0,t;
int sx,sy;
int imposs=0;
if (w<h) {transpose=1;t=w;w=h;h=t;}
W=w;H=h;
if (h==1) {
makeone(blank);
} else if (h==2) {
imposs=((blank & 1) || blank==2);
if (blank==1) imposs=0;
if (!imposs) maketwo(blank);
} else if (h>=3) {
imposs=((blank<9 && (blank & 1) || blank==2));
if (blank==1) imposs=0;
if (!imposs) makethree(blank);
}
mine[0][0]=-1;
if (imposs) printf("Impossible\n");
else if (transpose) drawtransposed();
else drawboard();
}
int main(int argc, char **argv) {
int tc,casenum,hh,ww,mines,blanks;
scanf("%d",&tc);
for (casenum=1;casenum<=tc;casenum++) {
printf("Case #%d:\n",casenum);
scanf("%d %d %d",&hh, &ww, &mines);
blanks=ww*hh-mines;
printboard(ww,hh,blanks);
}
return 0;
}
|
C
|
#include<stdio>
int main () {
int a;
int b;
printf("/saisie du premier nombre ");
scanf("%d,&a);
do{
printf("/nsaisie du second nombre:");
scanf("%d,&b);
} while (b==0);
printf("/n%d+%d=%d",a,b, a+b);
printf("/n%d-%d=%d",a,b,a-b);
printf("/n%d/%d=%f/n",a,b,(float)a/b);
return(0);
}
/////////////////////////////////////
//////////////////
|
C
|
#include "evaluator.h"
void printIds(ids* ids_){
int i;
for(i=0; i<ids_->size; i++){
printf("%s ", ids_->arg_[i]);
}
printf("\n");
}
void printValeurs(valeurs* valeurs_){
int i;
for(i=0; i<valeurs_->size; i++){
printf("%d ", valeurs_->v[i]);
}
printf("\n");
}
ids* args_to_ids(arg arg_){
arg p = arg_;
ids* ids_ = malloc(sizeof(ids));
ids_->arg_ = NULL;
ids_->adresse = NULL;
int size = 0;
int i = 0;
while(p != NULL){
size++;
ids_->arg_ = realloc(ids_->arg_, size*sizeof(char*));
ids_->adresse = realloc(ids_->adresse, size*sizeof(bool));
if(p->tag == ASTTypePrimVar){
ids_->adresse[i] = true;
} else {
ids_->adresse[i] = false;
}
ids_->arg_[i] = p->id;
i++;
p = p->suivant;
}
ids_->size = size;
return ids_;
}
bool type_adr_arg(env* env_, char* id){
env* p = env_;
while(p != NULL){
if (!(strcmp(p->id, id))){
if (p->adresse){
return true;
} else {
return false;
}
}
else {
p = p->suite;
}
}
p = NULL;
return NULL;
}
int cherche_id_env(env* env_, char* id){
env* p = env_;
while(p != NULL){
if (!(strcmp(p->id, id))){
return p->content.valeur;
}
else {
p = p->suite;
}
}
return -99999996;
}
int indice_id_env(env* env_, char* id){
env* p = env_;
int i = 0;
while(p != NULL){
if (!(strcmp(p->id, id))){
return i;
}
else {
p = p->suite;
}
}
return -2;
}
closure_proc_rec* get_closure_proc_rec(env* env_, char* id){
env* p = env_;
while(p != NULL){
if (!(strcmp(p->id, id))){
if (p->tag == ASTRecProc)
return p->content.def_proc_rec.closure_proc_rec_;
else
p = p->suite;
}
else {
p = p->suite;
}
}
return NULL;
}
closure_proc* get_closure_proc(env* env_, char* id){
env* p = env_;
while(p != NULL){
if (!(strcmp(p->id, id))){
if (p->tag == ASTProc)
return p->content.def_proc.closure_proc_;
else
p = p->suite;
}
else {
p = p->suite;
}
}
return NULL;
}
closure* get_closure(env* env_, char* id){
env* p = env_;
while(p != NULL){
if (!(strcmp(p->id, id))){
if (p->tag == ASTFun)
return p->content.def_fun.closure_;
else
p = p->suite;
}
else {
p = p->suite;
}
}
return NULL;
}
closure_rec* get_closure_rec(env* env_, char* id){
env* p = env_;
while(p != NULL){
if (!(strcmp(p->id, id))){
if (p->tag == ASTRecFun)
return p->content.def_rec.closure_rec_;
else
p = p->suite;
}
else {
p = p->suite;
}
}
return NULL;
}
valeurs* exprs_to_valeurs(env* env_, Sexprs es, mem* mem_){
Sexprs p = es;
valeurs* valeurs_ = malloc(sizeof(valeurs));
valeurs_->v = NULL;
int size = 0;
int i = 0;
while(p != NULL){
size++;
valeurs_->v = (int*) realloc(valeurs_->v, size*sizeof(int));
if(p->head->tag == ASTIdAdr) {
valeurs_->v[i] = eval_exprp(env_, mem_, p->head);
} else {
valeurs_->v[i] = eval_expr(env_, mem_, p->head);
}
i++;
p = p->tail;
}
valeurs_->size = size;
return valeurs_;
}
env* lier_args_vals_env(env* env_, ids* ids_, valeurs* valeurs_){
env* new_env = NULL;
env* p = NULL;
int i;
for(i=0; i<ids_->size; i++){
if (i) {
p = new_env;
}
new_env = malloc(sizeof(env));
new_env->tag = ASTConst;
if(ids_->adresse[i]) {
new_env->adresse = true;
} else {
new_env->adresse = false;
}
new_env->id = ids_->arg_[i];
new_env->content.valeur = valeurs_->v[i];
if (i) {
new_env->suite = p;
} else {
new_env->suite = env_;
}
}
return new_env;
}
env* ajout_closure_rec_env_proc(env* env_, closure_proc_rec* closure_rec_proc){
env* new_env = malloc(sizeof(env));
new_env->id = closure_rec_proc->id;
new_env->tag = ASTRecProc;
new_env->adresse = false;
new_env->content.def_proc_rec.closure_proc_rec_ = closure_rec_proc;
new_env->suite = env_;
return new_env;
}
env* ajout_closure_rec_env(env* env_, closure_rec* closure_rec_){
env* new_env = malloc(sizeof(env));
new_env->id = closure_rec_->id;
new_env->tag = ASTRecFun;
new_env->adresse = false;
new_env->content.def_rec.closure_rec_ = closure_rec_;
new_env->suite = env_;
return new_env;
}
env* eval_def_rec(def def_rec, env* env_, mem* mem_){
env* new_env = malloc(sizeof(env));
new_env->id = def_rec->content.defRecFun.id;
new_env->tag = ASTRecFun;
new_env->adresse = false;
new_env->content.def_rec.closure_rec_ = malloc(sizeof(closure_rec));
new_env->content.def_rec.closure_rec_->corp = def_rec->content.defRecFun.expr;
new_env->content.def_rec.closure_rec_->ids_ = malloc(sizeof(ids));
new_env->content.def_rec.closure_rec_->ids_ = args_to_ids(def_rec->content.defRecFun.arg_);
new_env->content.def_rec.closure_rec_->env_ = copy_env(env_);
new_env->content.def_rec.closure_rec_->id = def_rec->content.defRecFun.id;
new_env->suite = env_;
return new_env;
}
env* eval_def_proc_rec(def def_rec_proc, env* env_, mem* mem_){
env* new_env = malloc(sizeof(env));
new_env->id = def_rec_proc->content.def_rec_proc.id;
new_env->tag = ASTRecProc;
new_env->adresse = false;
new_env->content.def_proc_rec.closure_proc_rec_ = malloc(sizeof(closure_proc_rec));
new_env->content.def_proc_rec.closure_proc_rec_->block = def_rec_proc->content.def_rec_proc.block;
new_env->content.def_proc_rec.closure_proc_rec_->ids_ = malloc(sizeof(ids));
new_env->content.def_proc_rec.closure_proc_rec_->ids_ = args_to_ids(def_rec_proc->content.def_rec_proc.arg_);
new_env->content.def_proc_rec.closure_proc_rec_->env_ = copy_env(env_);
new_env->content.def_proc_rec.closure_proc_rec_->id = def_rec_proc->content.def_rec_proc.id;
new_env->suite = env_;
return new_env;
}
env* eval_def_proc(def def_proc, env* env_, mem* mem_){
env* new_env = malloc(sizeof(env));
new_env->id = def_proc->content.defProc.id;
new_env->tag = ASTProc;
new_env->adresse = false;
new_env->content.def_proc.closure_proc_ = malloc(sizeof(closure_proc));
new_env->content.def_proc.closure_proc_->block = def_proc->content.defProc.block;
new_env->content.def_proc.closure_proc_->ids_ = malloc(sizeof(ids));
new_env->content.def_proc.closure_proc_->ids_ = args_to_ids(def_proc->content.defProc.arg_);
new_env->content.def_proc.closure_proc_->env_ = copy_env(env_);
new_env->suite = env_;
return new_env;
}
env* eval_def_fun(def def_fun, env* env_, mem* mem_){
env* new_env = malloc(sizeof(env));
new_env->id = def_fun->content.defFun.id;
new_env->tag = ASTFun;
new_env->adresse = false;
new_env->content.def_fun.closure_ = malloc(sizeof(closure));
new_env->content.def_fun.closure_->corp = def_fun->content.defFun.expr;
new_env->content.def_fun.closure_->ids_ = malloc(sizeof(ids));
new_env->content.def_fun.closure_->ids_ = args_to_ids(def_fun->content.defFun.arg_);
new_env->content.def_fun.closure_->env_ = copy_env(env_);
new_env->suite = env_;
return new_env;
}
void print_env(env* env_){
env* p = env_;
while(p != NULL){
printf("=========\n");
printf("id : %s\n", p->id);
if (p->tag == ASTConst)
printf("v : %d\n", p->content.valeur);
else if (p->tag == ASTFun) {
printf("closure : \n");
printf("expr : ");printSexpr(p->content.def_fun.closure_->corp);printf("\n");
printf("args : ");printIds(p->content.def_fun.closure_->ids_);printf("\n");
printf("env : ");print_env(p->content.def_fun.closure_->env_);printf("\n");
}
else if (p->tag == ASTRecFun) {
printf("closure_rec : \n");
printf("id : %s\n", p->content.def_rec.closure_rec_->id);
printf("expr : ");printSexpr(p->content.def_rec.closure_rec_->corp);printf("\n");
printf("args : ");printIds(p->content.def_rec.closure_rec_->ids_);printf("\n");
printf("env : ");print_env(p->content.def_rec.closure_rec_->env_);printf("\n");
}
else if (p->tag == ASTVar) {
printf("#Var# : \n");
printf("id : %s\n", p->id);
printf("v : %d\n", p->content.valeur);
}
else if (p->tag == ASTProc) {
printf("#Proc# : \n");
printf("args : ");printIds(p->content.def_proc.closure_proc_->ids_);printf("\n");
printf("env : ");print_env(p->content.def_proc.closure_proc_->env_);printf("\n");
printf("block : \n");print_prog(p->content.def_proc.closure_proc_->block);printf("\n");
}
else if (p->tag == ASTRecProc) {
printf("#Proc Rec# : \n");
printf("args : ");printIds(p->content.def_proc_rec.closure_proc_rec_->ids_);printf("\n");
printf("env : ");print_env(p->content.def_proc_rec.closure_proc_rec_->env_);printf("\n");
printf("block : \n");print_prog(p->content.def_proc_rec.closure_proc_rec_->block);printf("\n");
printf("id : %s\n", p->content.def_proc_rec.closure_proc_rec_->id);
}
p = p->suite;
}
}
int cherche_id_adr_env(env* env_, char* id){
env* p = env_;
while(p != NULL){
if (!(strcmp(p->id, id))){
return p->content.valeur;
}
else {
p = p->suite;
}
}
return -99999997;
}
mem* affectation_mem(mem* mem_, int adresse, int valeur){
mem_->content[adresse].valeure = valeur;
return mem_;
}
mem* stat_set(env* env_, mem* mem_, stat stat_){
int adresse = cherche_id_adr_env(env_, stat_->content.set.id);
int valeur = eval_expr(env_, mem_, stat_->content.set.e);
return affectation_mem(mem_, adresse, valeur);
}
mem* stat_call(env* env_, mem** mem_, stat stat_){
Sexprs es = stat_->content.call_.expr;
if (get_closure_proc(env_, stat_->content.call_.id) != NULL) {
closure_proc* closure_proc_ = get_closure_proc(env_, stat_->content.call_.id);
valeurs* valeurs_ = exprs_to_valeurs(env_, es, *mem_);
env* env_tmp = lier_args_vals_env(closure_proc_->env_, closure_proc_->ids_, valeurs_);
eval_prog(env_tmp, *mem_, closure_proc_->block);
} else if (get_closure_proc_rec(env_, stat_->content.call_.id) != NULL){
closure_proc_rec* closure_proc_rec_ = get_closure_proc_rec(env_, stat_->content.call_.id);
valeurs* valeurs_ = exprs_to_valeurs(env_, es, *mem_);
env* env_tmp = lier_args_vals_env(closure_proc_rec_->env_, closure_proc_rec_->ids_, valeurs_);
env_tmp = ajout_closure_rec_env_proc(env_tmp, closure_proc_rec_);
eval_prog(env_tmp, *mem_, closure_proc_rec_->block);
}
return *mem_;
}
mem* stat_while(env* env_, mem** mem_, stat stat_){
int taille = -1;
if (eval_expr(env_, *mem_, stat_->content.while_.condition)){
if (*mem_ == NULL){
taille = 0;
} else {
taille = (*mem_)->last_adr;
}
eval_prog(env_, (*mem_), stat_->content.while_.block);
if (taille) {
mem_ = realloc(mem_, taille*sizeof(mem));
}
*mem_ = stat_while(env_, mem_, stat_);
} else {
return *mem_;
}
}
mem* stat_IF(env* env_, mem** mem_, stat stat_){
int taille = -1;
if (eval_expr(env_, *mem_, stat_->content.if_block.condition)){
if (*mem_ == NULL){
taille = 0;
} else {
taille = (*mem_)->last_adr;
}
eval_prog(env_, (*mem_), stat_->content.if_block.block1);
if (taille) {
mem_ = realloc(mem_, taille*sizeof(mem));
}
return (*mem_);
} else {
if (*mem_ == NULL){
taille = 0;
} else {
taille = (*mem_)->last_adr;
}
eval_prog(env_, (*mem_), stat_->content.if_block.block2);
if (taille) {
mem_ = realloc(mem_, taille*sizeof(mem));
}
return (*mem_);
}
}
void eval_prog(env* env__, mem* mem__, prog* prog_){
env* env_ = env__;
mem* mem_ = mem__;
int valeur = -404404404;
int size = prog_->size;
int i = 0;
while (i < size) {
switch (prog_->cmds[i].type_) {
case 1: // expr
{
valeur = eval_expr(env_, mem_, prog_->cmds[i].expr);
break;
}
case 2: // def_const
env_ = eval_def_const(prog_->cmds[i].def_const, env_, mem_);
break;
case 3: // def_fun
env_ = eval_def_fun(prog_->cmds[i].def_fun, env_, mem_);
break;
case 4: // def_rec
env_ = eval_def_rec(prog_->cmds[i].def_rec, env_, mem_);
break;
case 5: // def_var
env_ = eval_def_var(prog_->cmds[i].def_var, env_, &mem_);
break;
case 6: // def_proc
env_ = eval_def_proc(prog_->cmds[i].def_proc, env_, mem_);
break;
case 7: // def_proc_rec
env_ = eval_def_proc_rec(prog_->cmds[i].def_rec_proc, env_, mem_);
break;
case 8 :
if (prog_->cmds[i].stat_->tag == ASTEcho){
valeur = eval_expr(env_, mem_, prog_->cmds[i].stat_->content.echo.expr);
} else if (prog_->cmds[i].stat_->tag == ASTSet){
mem_ = stat_set(env_, mem_, prog_->cmds[i].stat_);
} else if (prog_->cmds[i].stat_->tag == ASTIfBlock){
mem_ = stat_IF(env_, &mem_, prog_->cmds[i].stat_);
} else if (prog_->cmds[i].stat_->tag == ASTWhile){
mem_ = stat_while(env_, &mem_, prog_->cmds[i].stat_);
} else if (prog_->cmds[i].stat_->tag == ASTCall){
mem_ = stat_call(env_, &mem_, prog_->cmds[i].stat_);
}
break;
default:
printf("Erreur\n");
}
i++;
}
if (valeur != -404404404)
printf("\nEcho %d\n", valeur);
}
env* eval_def_const(def def_const, env* env_, mem* mem_){
env* new_env = malloc(sizeof(env));
new_env->tag = ASTConst;
new_env->adresse = false;
new_env->id = def_const->content.defConst.id;
int valeur_expr;
valeur_expr = eval_expr(env_, mem_, def_const->content.defConst.expr);
new_env->content.valeur = valeur_expr;
new_env->suite = env_;
return new_env;
}
env* eval_def_var(def def_var, env* env_, mem** mem_){
env* new_env = malloc(sizeof(env));
new_env->tag = ASTVar;
new_env->adresse = true;
new_env->id = def_var->content.defVar.id;
*mem_ = alloc(*mem_);
new_env->content.valeur = (*mem_)->last_adr;
new_env->suite = env_;
return new_env;
}
mem* alloc(mem* mem_){
if (mem_ == NULL){
mem_ = malloc(sizeof(mem));
mem_->last_adr = 0;
mem_->content = malloc(sizeof(adr_val));
mem_->content->adresse = 0;
mem_->content->valeure = ANY;
return mem_;
} else {
mem_->last_adr++;
int adresse = mem_->last_adr;
adr_val* tmp = malloc(sizeof(adr_val));;
tmp->adresse = adresse;
tmp->valeure = ANY;
mem_->content = realloc(mem_->content, (adresse+1)*sizeof(adr_val));
mem_->content[adresse] = *tmp;
tmp = NULL;
return mem_;
}
}
env* copy_env(env* env_){
env* p = env_;
env* copy = malloc(sizeof(env));
env* p_copy = copy;
while (p != NULL) {
p_copy->id = p->id;
p_copy->tag = p->tag;
p_copy->adresse = p->adresse;
if (p_copy->tag == ASTConst){
p_copy->content.valeur = p->content.valeur;
} else if (p_copy->tag == ASTFun){
p_copy->content.def_fun.closure_ = p->content.def_fun.closure_;
} else if (p_copy->tag == ASTProc){
p_copy->content.def_proc.closure_proc_ = p->content.def_proc.closure_proc_;
} else if (p_copy->tag == ASTVar){
p_copy->content.valeur = p->content.valeur;
} else {
p_copy = NULL;
}
p = p->suite;
if(p != NULL){
p_copy->suite = NULL;
p_copy->suite = malloc(sizeof(env));
p_copy = p_copy->suite;
}
}
if (env_ == NULL) copy = NULL;
return copy;
}
int eval_exprp(env* env_, mem* mem_, Sexpr expr){
int indice = -9999;
int valeur = -9999;
valeur = cherche_id_adr_env(env_, expr->content.id);
if (!(valeur == -99999997)){
return valeur;
}
}
int eval_expr(env* env_, mem* mem_, Sexpr expr){
int indice = -9999;
int valeur = -9999;
switch (expr->tag) {
case ASTNum:
return expr->content.num;
break;
case ASTBool:
if (!(strcmp(expr->content.boolean, "true"))) return 1;
else return 0;
break;
case ASTIdAdr:
break;
case ASTId:
valeur = cherche_id_env(env_, expr->content.id);
if(type_adr_arg(env_, expr->content.id)){
return mem_->content[valeur].valeure;
} else {
return valeur;
}
break;
case ASTNot:
if (eval_expr(env_, mem_, expr->content.not_.e))
return 0;
else return 1;
break;
case ASTAdd:
return eval_expr(env_, mem_, expr->content.add.e1)
+ eval_expr(env_, mem_, expr->content.add.e2);
break;
case ASTMul:
return eval_expr(env_, mem_, expr->content.mul.e1)
* eval_expr(env_, mem_, expr->content.mul.e2);
break;
case ASTSub:
return eval_expr(env_, mem_, expr->content.sub.e1)
- eval_expr(env_, mem_, expr->content.sub.e2);
break;
case ASTDiv:
return eval_expr(env_, mem_, expr->content.div.e1)
/ eval_expr(env_, mem_, expr->content.div.e2);
break;
case ASTAnd:
if (!(eval_expr(env_, mem_, expr->content.and_.e1))) return 0;
else return eval_expr(env_, mem_, expr->content.and_.e2);
break;
case ASTOr:
if (eval_expr(env_, mem_, expr->content.or_.e1)) return 1;
else return eval_expr(env_, mem_, expr->content.or_.e2);
break;
case ASTEq:
if (eval_expr(env_, mem_, expr->content.eq.e1) == eval_expr(env_, mem_, expr->content.eq.e2))
return 1;
else return 0;
break;
case ASTLt:
if (eval_expr(env_, mem_, expr->content.eq.e1) < eval_expr(env_, mem_, expr->content.eq.e2))
return 1;
else return 0;
break;
case ASTIf:
if (eval_expr(env_, mem_, expr->content.if_.cond))
return eval_expr(env_, mem_, expr->content.if_.cons);
else return eval_expr(env_, mem_, expr->content.if_.alt);
break;
case ASTApp:{
Sexpr e = expr->content.app.fun;
Sexprs es = expr->content.app.args;
if ((get_closure(env_, getId(e))) != NULL) {
closure* closure_ = get_closure(env_, e->content.id);
valeurs* valeurs_ = exprs_to_valeurs(env_, es, mem_);
env* env_tmp = lier_args_vals_env(closure_->env_, closure_->ids_, valeurs_);
return eval_expr(env_tmp, mem_, closure_->corp);
} else if ((get_closure_rec(env_, getId(e))) != NULL) {
closure_rec* closure_rec_ = get_closure_rec(env_, e->content.id);
valeurs* valeurs_ = exprs_to_valeurs(env_, es, mem_);
env* env_tmp = lier_args_vals_env(closure_rec_->env_, closure_rec_->ids_, valeurs_);
env_tmp = ajout_closure_rec_env(env_tmp, closure_rec_);
return eval_expr(env_tmp, mem_, closure_rec_->corp);
} else if (tagOf(e) == ASTAbs){
closure* closure_ = malloc(sizeof(closure));
closure_->corp = e->content.abstract.expr;
closure_->ids_ = malloc(sizeof(ids));
closure_->ids_ = args_to_ids(e->content.abstract.arg_);
closure_->env_ = copy_env(env_);
valeurs* valeurs_ = exprs_to_valeurs(env_, es, mem_);
env* env_tmp = lier_args_vals_env(closure_->env_, closure_->ids_, valeurs_);
return eval_expr(env_tmp, mem_, closure_->corp);
} else {
return -5;
}
break;
}
case ASTAbs:{
return -10;
break;
}
default:
return -3;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "tokenizer.h"
// Prints all strings in the given svec.
void
print_tokens(svec* tokens)
{
for (int ii = 0; ii < tokens->size; ++ii) {
printf("%s\n", svec_get(tokens, ii));
}
}
// Returns true if the input is a special operator
// that needs no preceding or following spaces.
int
isoperator(char input)
{
return (input == '&') || (input == '|') || (input == '<')
|| (input == '>') || (input == ';');
}
// Return a substring of the input from ii to nn.
char*
copy_substring(char* input, int ii, int nn)
{
// Copy over memory into token, with one extra byte for the null terminator.
char* substring = malloc(nn + 1);
memcpy(substring, input + ii, nn);
substring[nn] = 0;
return substring;
}
// Reads the next token from the input starting at ii.
char*
read_token(char* input, int ii)
{
int nn = 0;
while ((!isspace(input[ii + nn])) && (!isoperator(input[ii + nn]))) {
++nn;
}
return copy_substring(input, ii, nn);
}
// Reads the operator from the input starting at ii.
char*
read_operator(char* input, int ii)
{
int nn = 0;
while (input[ii + nn] != 0 && (!isspace(input[ii + nn])) && (!isalnum(input[ii + nn]))) {
++nn;
}
return copy_substring(input, ii, nn);
}
// Returns an svec containing all tokens from the given input,
// in the order they appear.
// Inspired By: Nat Tuck
svec*
tokenize(char* input)
{
int nn = strlen(input);
svec* tokens = make_svec();
int ii = 0;
while(ii < nn) {
if (isspace(input[ii])) {
++ii;
continue;
}
char* token;
if (isoperator(input[ii])) {
token = read_operator(input, ii);
}
else {
token = read_token(input, ii);
}
svec_push(tokens, token);
ii += strlen(token);
free(token);
}
return tokens;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
// Use the Computer struct, give values to the fields and print them out in the main!
// Use the Notebook struct, give values to the fields and print them out in the main!
struct Computer
{
float cpu_speed_GHz;
int ram_size_GB;
int bits;
};
typedef struct
{
float cpu_speed_GHz;
int ram_size_GB;
int bits;
} Notebook;
int main()
{
struct Computer Mac;
Mac.bits = 64;
Mac.ram_size_GB = 8;
Mac.cpu_speed_GHz = 2.87;
Notebook Eee;
Eee.bits = 32;
Eee.ram_size_GB = 4;
Eee.cpu_speed_GHz = 2.31;
printf("The Mac has a %d bit OS with %d GB RAM and %.2f GHz processor.\n",
Mac.bits, Mac.ram_size_GB, Mac.cpu_speed_GHz);
printf("The Eee netbook has a %d bit OS with %d GB RAM and %.2f GHz processor.\n",
Eee.bits, Eee.ram_size_GB, Eee.cpu_speed_GHz);
return 0;
}
|
C
|
//利用数组计算斐波那契数列的前10个数,按每行5个的顺序打出
#include <stdio.h>
int main()
{
int i;
int fib[10]={1,1};
for (i = 2; i < 10; i++)
{
fib[i]=fib[i-2]+fib[i-1];
}
for (i = 0; i < 10; i++)
{
printf("%4d",fib[i]);
if ((i+1)%5 == 0)
{
printf("\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
void Temperatures(double);
int main(void)
{
double fa;
printf("Please input the Temperature:");
while(scanf("%lf", &fa) == 1)
{
Temperatures(fa);
printf("Please input the Temperature(not number to quit):");
}
printf("End\n");
return 0;
}
void Temperatures(double num)
{
const float FA_TO_CE1 = 1.8;
const float FA_TO_CE2 = 32.0;
const float CE_TO_KE = 273.16;
double ce, ke;
ce = FA_TO_CE1 * num +FA_TO_CE2;
ke = ce + CE_TO_KE;
printf("Celsius = %.2lf, Kelvin = %.2lf\n", ce, ke);
return 0;
}
|
C
|
#include <stdio.h>
main()
{
int n,i,key,m;
printf("Enter array size : ");
scanf("%d",&n);
int a[n];
printf("Enter %d elements : \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter which index : ");
scanf("%d",&m);
for(i=m;i<n;i++){
a[i]=a[i+1];
}
for(i=0;i<n-1;i++)
printf("%d ",a[i]);
return 0;
}
|
C
|
void input(int arr[],int noElements){
int i;
for(i=0;i<noElements;i++){
scanf("%d",&arr[i]);
}
}
void output(int arr[],int noElements){
int i;
for(i=0;i<noElements;i++){
printf("%d ",arr[i]);
}
}
|
C
|
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include "header.h"
static int queue1;
static int queue2;
//inizializzazione code di servizio
void initservicequeues(){
queue1=msgget(IPC_PRIVATE,IPC_CREAT|0664);
queue2=msgget(IPC_PRIVATE, IPC_CREAT|0664);
}
//rimozione code di servizio
void removeservicequeues(){
msgctl(queue1, IPC_RMID,0);
msgctl(queue2, IPC_RMID,0);
}
//send sincrona
void sendsincr(messaggio *m, int queue){
messaggio m1,m2;
//costruzione messaggio RTS
m1.tipo=REQUEST_TO_SEND;
strcpy(m1.mess, "Richiesta di invio");
//invio messaggio RTS
msgsnd(queue1, &m1, sizeof(messaggio)-sizeof(long),0);
//ricezione OTS
msgrcv(queue2, &m2, sizeof(messaggio)-sizeof(long), OK_TO_SEND, 0);
// invio messaggio
msgsnd(queue, m, sizeof(messaggio)-sizeof(long), 0);
}
//receive bloccante
void receivebloc(messaggio *m, int queue, int tipomess){
messaggio m1, m2;
//ricezione messaggio RTS
msgrcv(queue1, &m1, sizeof(messaggio)-sizeof(long), REQUEST_TO_SEND,0);
//costruzione MESSAGGIO OTS
m2.tipo=OK_TO_SEND;
strcpy(m2.mess, "Ready to send");
//invio messaggio OTS
msgsnd(queue2, &m2, sizeof(messaggio)-sizeof(long), 0);
// ricezione messaggio
msgrcv(queue, m, sizeof(messaggio)-sizeof(long), tipomess, 0);
}
void produttore(int queue, char* text){
messaggio m;
//costruzione del messaggio da trasmettere
m.tipo=MESSAGGIO;
strcpy(m.mess, text);
// invio messaggio
sendsincr(&m, queue);
printf("MESSAGGIO INVIATO: <%s>\n", m.mess);
}
void consumatore(int queue){
messaggio m;
//ricezione messaggio
receivebloc(&m, queue, MESSAGGIO);
printf("MESSAGGIO RICEVUTO: <%s>\n", m.mess);
}
|
C
|
#include <stdio.h>
void area(int a,int b){
int area;
area=a*b;
printf("area=%d",area);
}
int main()
{
void area(int a ,int b );
int m,n;
printf("enter first side ");
scanf("%d",&m);
printf("enter second side");
scanf("%d",&n);
area(m,n);
}
|
C
|
#include <stdio.h>
int main()
{
int arr[100];
int n, i;
printf("Enter number of input:\n");
scanf("%d", &n);
printf("Enter elements in array:\n");
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
printf("Array in reverse order:\n");
for(i=n-1; i>=0; i--)
{
printf("%d ", arr[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
#include "utils.h"
int qput(queue_t *qu, int x, int y) {
val_t v = {x, y};
qputv(qu, v);
}
int qputv(queue_t *qu, val_t v) {
node_t *node;
int pos = 1;
node_t *next = (node_t *) malloc(sizeof(node_t));
next->val = v;
mut_lock2(qu->mut);
node = qu->root;
if (!node || !VAL_GT(v, node->val)) {
next->next = qu->root;
qu->root = next;
mut_unlock2(qu->mut);
return 0;
}
while (node->next && VAL_GT(v, node->next->val)) {
node = node->next;
++pos;
}
next->next = node->next;
node->next = next;
mut_unlock2(qu->mut);
return pos;
}
int qdel(queue_t *qu) {
node_t *node = qu->root;
int c = 0;
while(node) {
node_t *t = node->next;
free(node);
node = t;
++c;
}
pthread_mutex_destroy(&qu->mut);
return c;
}
int qrm1(queue_t *qu, int y) {
mut_lock2(qu->mut);
node_t *node = qu->root;
if (node && node->val.y == y) {
node_t *t = qu->root;
qu->root = node->next;
mut_unlock2(qu->mut);
free(t);
return 0;
}
int c = 0;
while(node->next) {
++c;
if (node->next->val.y == y) {
node_t *t = node->next;
node->next = node->next->next;
mut_unlock2(qu->mut);
free(t);
return c;
}
node = node->next;
}
mut_unlock2(qu->mut);
return -1;
}
int qpop(queue_t *qu) {
mut_lock2(qu->mut);
int r = -1;
if (qu->root) {
r = qu->root->val.y;
node_t *t = qu->root;
qu->root = t->next;
free(t);
}
mut_unlock2(qu->mut);
return r;
}
void qprint(queue_t *qu) {
mut_lock2(qu->mut);
node_t *node = qu->root;
while(node) {
printf("(%d, %d) %c ", node->val.x, node->val.y,
node->next ? "<>"[VAL_GT(node->val, node->next->val)]
: '|');
node = node->next;
}
// printf("\n");
mut_unlock2(qu->mut);
}
|
C
|
#ifndef __STDINT_H
#define __STDINT_H
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
typedef signed long int int32_t;
typedef unsigned long int uint32_t;
typedef signed long long int int64_t;
typedef unsigned long long int uint64_t;
typedef unsigned short ushort_t;
#endif
|
C
|
/* ************************************************************************
* Filename: 18_test.c
* Description:
* Version: 1.0
* Created: 2017年09月13日 17时06分21秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
void func(int *p)
{
p = (int *)malloc(sizeof(int));
*p = 100;
printf("func %d\n", *p);
}
int * func2()
{
int *p;
p = (int *)malloc(sizeof(int));
return p;
}
int main()
{
int *p = NULL;
//func(p); //在func函数动态分配空间, err
p = func2();
*p = 111;
printf("main %d\n", *p);
free(p);
p = NULL;
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "common.h"
#include "solids.h"
/* PRIMITIVAS: */
#include "sphere.h"
#include "plane.h"
#include "poly.h"
#include "tile.h"
#include "cyl.h"
#define MAXCUTS 50
int pointInIntersection(point, void*);
int pointInUnion(point, void*);
int pointInDiff(point, void*);
int segIntersectionCut(seg, void*, point*, vec*);
int segUnionCut(seg, void*, point*, vec*);
int segDiffCut(seg, void*, point*, vec*);
int segIntersectionCutAll(seg, void*, point[], vec[]);
int segUnionCutAll(seg, void*, point[], vec[]);
int segDiffCutAll(seg, void*, point[], vec[]);
void* readCouple(void);
void freeCouple(void*);
char* ID[] = {"INTERSECT", "UNION", "DIFF", "SPHERE",
"POLYH", "PLANE", "TILE", "CYL"};
int (*POINTIN[])(point, void*) = {pointInIntersection, pointInUnion, pointInDiff, pointInSphere,
pointInPolyh, pointInPlane, pointInTile, pointInCyl};
int (*SEGCUT[])(seg, void*, point*, vec*) = {segIntersectionCut, segUnionCut, segDiffCut, segSphereCut,
segPolyhCut, segPlaneCut, segTileCut, segCylCut};
int (*SEGCUTALL[])(seg, void*, point[], vec[]) = {segIntersectionCutAll, segUnionCutAll, segDiffCutAll, segSphereCutAll,
segPolyhCutAll, segPlaneCut, segTileCut, segCylCutAll};
void* (*READ[])(void) = {readCouple, readCouple, readCouple, readSphere,
readPolyh, readPlane, readTile, readCyl};
void (*FREE[])(void*) = {freeCouple, freeCouple, freeCouple, free,
freePolyh, free, free, free};
void* readSolid()
{
char str[100];
unsigned int i;
solid* s;
s = (solid*)malloc(sizeof(solid));
scanf("%s",str);
for(i=0;i<sizeof(ID)/sizeof(char*);++i)
if(strcmp(str,ID[i]) == 0)
{
s->type = i;
s->data = READ[i]();
return s;
}
return NULL;
}
void freeSolid(void* sol)
{
solid* s = sol;
FREE[s->type](s->data);
}
void* readCouple()
{
void** arr;
arr = malloc(2 * sizeof(void*));
arr[0] = readSolid();
arr[1] = readSolid();
return arr;
}
void freeCouple(void* arr)
{
void** t = arr;
freeSolid(*t);
freeSolid(*(t+1));
}
int pointInSolid(point p, void* sol)
{
solid* s = (solid*)sol;
return POINTIN[s->type](p,s->data);
}
int pointInIntersection(point p, void* data)
{
void** arr;
arr = data;
return pointInSolid(p,arr[0]) && pointInSolid(p,arr[1]);
}
int pointInUnion(point p, void* data)
{
void** arr;
arr = data;
return pointInSolid(p,arr[0]) || pointInSolid(p,arr[1]);
}
int pointInDiff(point p, void* data)
{
void** arr;
arr = data;
return pointInSolid(p,arr[0]) && !pointInSolid(p,arr[1]);
}
int segSolidCut(seg sg, void* sol, point* p, vec* normal)
{
solid* s = (solid*)sol;
return SEGCUT[s->type](sg,s->data,p,normal);
}
int segSolidCutAll(seg sg, void* sol, point p[], vec normal[])
{
solid* s = (solid*)sol;
return SEGCUTALL[s->type](sg,s->data,p,normal);
}
int segIntersectionCut(seg s, void* data, point* p, vec* normal)
{
point p1[MAXCUTS], p2[MAXCUTS];
vec n1[MAXCUTS],n2[MAXCUTS];
solid *l,*r;
int l1,l2;
int c1,c2;
l = *((solid**)data);
r = *((solid**)data + 1);
l1 = segSolidCutAll(s,l,p1,n1);
l2 = segSolidCutAll(s,r,p2,n2);
c1 = c2 = 0;
while(c1<l1 && c2<l2)
{
if(fabs(pointDist2(s.p,p1[c1]) - pointDist2(s.p,p2[c2])) < EPS)
{
if(p != NULL) *p = p[c1];
if(normal != NULL) *normal = n1[c1];
return 3;
} else if(pointDist2(s.p,p1[c1]) < pointDist2(s.p,p2[c2])){
if(pointInSolid(p1[c1],r))
{
if(p != NULL) *p = p1[c1];
if(normal != NULL) *normal = n1[c1];
return 1;
}
c1++;
} else {
if(pointInSolid(p2[c2],l))
{
if(p != NULL) *p = p2[c2];
if(normal != NULL) *normal = n2[c2];
return 2;
}
c2++;
}
}
while(c1<l1)
{
if(pointInSolid(p1[c1],r))
{
if(p != NULL) *p = p1[c1];
if(normal != NULL) *normal = n1[c1];
return 1;
}
c1++;
}
while(c2<l2)
{
if(pointInSolid(p2[c2],l))
{
if(p != NULL) *p = p2[c2];
if(normal != NULL) *normal = n2[c2];
return 2;
}
c2++;
}
return 0;
}
int segIntersectionCutAll(seg s, void* data, point* p, vec* normal)
{
point p1[MAXCUTS], p2[MAXCUTS];
vec n1[MAXCUTS],n2[MAXCUTS];
solid *l,*r;
int l1,l2;
int c1,c2;
int c;
l = *((solid**)data);
r = *((solid**)data + 1);
l1 = segSolidCutAll(s,l,p1,n1);
l2 = segSolidCutAll(s,r,p2,n2);
c1 = c2 = 0;
c = 0;
while(c1<l1 && c2<l2)
{
if(fabs(pointDist2(s.p,p1[c1]) - pointDist2(s.p,p2[c2])) < EPS)
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
c1++;c2++;
} else if(pointDist2(s.p,p1[c1]) < pointDist2(s.p,p2[c2])) {
if(pointInSolid(p1[c1],r))
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
}
c1++;
} else {
if(pointInSolid(p2[c2],l))
{
if(p != NULL) p[c] = p2[c2];
if(normal != NULL) normal[c] = n2[c2];
c++;
}
c2++;
}
}
while(c1<l1)
{
if(pointInSolid(p1[c1],r))
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
}
c1++;
}
while(c2<l2)
{
if(pointInSolid(p2[c2],l))
{
if(p != NULL) p[c] = p2[c2];
if(normal != NULL) normal[c] = n2[c2];
c++;
}
c2++;
}
return c;
}
int segUnionCut(seg s, void* data, point* p, vec* normal)
{
point p1[MAXCUTS], p2[MAXCUTS];
vec n1[MAXCUTS],n2[MAXCUTS];
solid *l,*r;
int l1,l2;
int c1,c2;
l = *((solid**)data);
r = *((solid**)data + 1);
l1 = segSolidCutAll(s,l,p1,n1);
l2 = segSolidCutAll(s,r,p2,n2);
c1 = c2 = 0;
while(c1<l1 && c2<l2)
{
if(fabs(pointDist2(s.p,p1[c1]) - pointDist2(s.p,p2[c2])) < EPS)
{
if(p != NULL) *p = p[c1];
if(normal != NULL) *normal = n1[c1];
return 3;
} else if(pointDist2(s.p,p1[c1]) < pointDist2(s.p,p2[c2])){
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) *p = p1[c1];
if(normal != NULL) *normal = n1[c1];
return 1;
}
c1++;
} else {
if(!pointInSolid(p2[c2],l))
{
if(p != NULL) *p = p2[c2];
if(normal != NULL) *normal = n2[c2];
return 2;
}
c2++;
}
}
while(c1<l1)
{
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) *p = p1[c1];
if(normal != NULL) *normal = n1[c1];
return 1;
}
c1++;
}
while(c2<l2)
{
if(!pointInSolid(p2[c2],l))
{
if(p != NULL) *p = p2[c2];
if(normal != NULL) *normal = n2[c2];
return 2;
}
c2++;
}
return 0;
}
int segUnionCutAll(seg s, void* data, point* p, vec* normal)
{
point p1[MAXCUTS], p2[MAXCUTS];
vec n1[MAXCUTS],n2[MAXCUTS];
solid *l,*r;
int l1,l2;
int c1 = 0,c2 = 0;
int c = 0;
l = *((solid**)data);
r = *((solid**)data + 1);
l1 = segSolidCutAll(s,l,p1,n1);
l2 = segSolidCutAll(s,r,p2,n2);
while(c1<l1 && c2<l2)
{
if(fabs(pointDist2(s.p,p1[c1]) - pointDist2(s.p,p2[c2])) < EPS)
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
c1++;c2++;
} else if(pointDist2(s.p,p1[c1]) < pointDist2(s.p,p2[c2])) {
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
}
c1++;
} else {
if(!pointInSolid(p2[c2],l))
{
if(p != NULL) p[c] = p2[c2];
if(normal != NULL) normal[c] = n2[c2];
c++;
}
c2++;
}
}
while(c1<l1)
{
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
}
c1++;
}
while(c2<l2)
{
if(!pointInSolid(p2[c2],l))
{
if(p != NULL) p[c] = p2[c2];
if(normal != NULL) normal[c] = n2[c2];
c++;
}
c2++;
}
return c;
}
int segDiffCut(seg s, void* data, point* p, vec* normal)
{
point p1[MAXCUTS], p2[MAXCUTS];
vec n1[MAXCUTS],n2[MAXCUTS];
solid *l,*r;
int l1,l2;
int c1,c2;
l = *((solid**)data);
r = *((solid**)data + 1);
l1 = segSolidCutAll(s,l,p1,n1);
l2 = segSolidCutAll(s,r,p2,n2);
c1 = c2 = 0;
while(c1<l1 && c2<l2)
{
if(fabs(pointDist2(s.p,p1[c1]) - pointDist2(s.p,p2[c2])) < EPS)
{
if(p != NULL) *p = p[c1];
if(normal != NULL) *normal = n1[c1];
return 3;
} else if(pointDist2(s.p,p1[c1]) < pointDist2(s.p,p2[c2])){
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) *p = p1[c1];
if(normal != NULL) *normal = n1[c1];
return 1;
}
c1++;
} else {
if(pointInSolid(p2[c2],l))
{
if(p != NULL) *p = p2[c2];
if(normal != NULL) *normal = vecScale(-1,n2[c2]);
return 2;
}
c2++;
}
}
while(c1<l1)
{
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) *p = p1[c1];
if(normal != NULL) *normal = n1[c1];
return 1;
}
c1++;
}
while(c2<l2)
{
if(pointInSolid(p2[c2],l))
{
if(p != NULL) *p = p2[c2];
if(normal != NULL) *normal = vecScale(-1,n2[c2]);
return 2;
}
c2++;
}
return 0;
}
int segDiffCutAll(seg s, void* data, point* p, vec* normal)
{
point p1[MAXCUTS], p2[MAXCUTS];
vec n1[MAXCUTS],n2[MAXCUTS];
solid *l,*r;
int l1,l2;
int c1,c2;
int c;
l = *((solid**)data);
r = *((solid**)data + 1);
l1 = segSolidCutAll(s,l,p1,n1);
l2 = segSolidCutAll(s,r,p2,n2);
c1 = c2 = 0;
c = 0;
while(c1<l1 && c2<l2)
{
if(fabs(pointDist2(s.p,p1[c1]) - pointDist2(s.p,p2[c2])) < EPS)
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
c1++;c2++;
} else if(pointDist2(s.p,p1[c1]) < pointDist2(s.p,p2[c2])) {
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
}
c1++;
} else {
if(pointInSolid(p2[c2],l))
{
if(p != NULL) p[c] = p2[c2];
if(normal != NULL) normal[c] = vecScale(-1,n2[c2]);
c++;
}
c2++;
}
}
while(c1<l1)
{
if(!pointInSolid(p1[c1],r))
{
if(p != NULL) p[c] = p1[c1];
if(normal != NULL) normal[c] = n1[c1];
c++;
}
c1++;
}
while(c2<l2)
{
if(pointInSolid(p2[c2],l))
{
if(p != NULL) p[c] = p2[c2];
if(normal != NULL) normal[c] = vecScale(-1,n2[c2]);
c++;
}
c2++;
}
return c;
}
|
C
|
#include "syntax_tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** newSynTreeNode_noname():
* create a syntax tree node without a name.
*
* @return a syntax tree node
*/
struct tree_node *newSynTreeNode_noname(void) {
struct tree_node *tmp = malloc(sizeof(struct tree_node));
tmp->child_num = 0;
tmp->name[0] = '\0';
return tmp;
}
/** newSynTreeNode()
* create a syntax tree node with a name.
*
* @param name the name of the tree node
* @return a syntax tree node
*/
struct tree_node *newSynTreeNode(const char *name) {
struct tree_node *tmp = malloc(sizeof(struct tree_node));
if (name) {
strcpy(tmp->name, name);
} else {
tmp->name[0] = '\0';
}
tmp->child_num = 0;
return tmp;
}
/** newSynTreeNode_fromnum():
* create a syntax tree node from a number.
*
* @param num the number
* @return a syntax tree node
*/
struct tree_node *newSynTreeNode_fromnum(const int num) {
struct tree_node *tmp = malloc(sizeof(struct tree_node));
sprintf(tmp->name, "%d", num);
tmp->child_num = 0;
return tmp;
}
/** synTreeNodeAddChild():
* add a syntax tree node to the parent node.
*
* @param parent the parent node
* @param child the child node
*/
void synTreeNodeAddChild(struct tree_node *parent, struct tree_node *child) {
if (!parent || !child) {
return;
}
parent->children[parent->child_num++] = child;
}
/** synTreeNodeDelChild_noRecur():
* delete syntex tree node without recur
*
* @param the node to delete
*/
void synTreeNodeDelChild_noRecur(struct tree_node *node) {
if (!node) {
return;
}
free(node);
}
/** synTreeNodeDelChild():
* delete syntex tree node, and all children
*
* @param the node to delete
*/
void synTreeNodeDelChild(struct tree_node *node) {
if (!node) {
return;
}
int i;
for (i = 0; i < node->child_num; i++) {
synTreeNodeDelChild(node->children[i]);
}
free(node);
}
/** newSynTree():
* create a new syntex tree
*/
struct syn_tree *newSynTree(void) {
return malloc(sizeof(struct syn_tree));
}
/** deleteSynTree():
* free a syntax tree
*
* @param tree the syntax tree
*/
void deleteSynTree(struct syn_tree *tree) {
if (!tree) {
return;
}
if (tree->root) {
synTreeNodeDelChild(tree->root);
}
free(tree);
}
/** printSyntreeNode():
* static function, print a syntax tree node
*
* @param string the output string
* @param node the node to print
* @param level the level of the node
*/
static void printSyntreeNode(FILE *string, struct tree_node *node, int level) {
if (!node) {
return;
}
// print myself
int i;
for (i = 0; i < level; ++i) {
fprintf(string, "| ");
}
fprintf(string, ">--%s %s\n", (node->child_num ? "+" : "*"), node->name);
for (i = 0; i < node->child_num; ++i) {
printSyntreeNode(string, node->children[i], level + 1);
}
}
/** printSynTree:
* prints out a syntax tree
*
* @param string the output string
* @param tree the tree to print
*/
void printSynTree(FILE *string, struct syn_tree *tree) {
if (!string) {
return;
}
printSyntreeNode(string, tree->root, 0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ray1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yoouali <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/19 09:10:52 by yoouali #+# #+# */
/* Updated: 2020/02/19 09:20:04 by yoouali ### ########.fr */
/* */
/* ************************************************************************** */
#include "../INC/wolf.h"
void *part1(void *arg)
{
t_wolf *wolf;
int x;
t_ray ray;
wolf = (t_wolf*)arg;
x = 0;
while (x < 375)
{
init_ray_cmp(&ray, wolf, x);
detect_walls(wolf, &ray);
detect_side_wallh(&ray, wolf);
draw_text(wolf, x, &ray);
init_floor_cel(&ray);
aplly_flo(&ray, wolf, x, wolf->flo);
aplly_cel(&ray, wolf, x, wolf->cel);
x++;
}
return (NULL);
}
void *part2(void *arg)
{
t_wolf *wolf;
int x;
t_ray ray;
wolf = (t_wolf*)arg;
x = 375;
while (x < 750)
{
init_ray_cmp(&ray, wolf, x);
detect_walls(wolf, &ray);
detect_side_wallh(&ray, wolf);
draw_text(wolf, x, &ray);
init_floor_cel(&ray);
aplly_flo(&ray, wolf, x, wolf->flo);
aplly_cel(&ray, wolf, x, wolf->cel);
x++;
}
return (NULL);
}
void *part3(void *arg)
{
t_wolf *wolf;
int x;
t_ray ray;
wolf = (t_wolf*)arg;
x = 750;
while (x < 1100)
{
init_ray_cmp(&ray, wolf, x);
detect_walls(wolf, &ray);
detect_side_wallh(&ray, wolf);
draw_text(wolf, x, &ray);
init_floor_cel(&ray);
aplly_flo(&ray, wolf, x, wolf->flo);
aplly_cel(&ray, wolf, x, wolf->cel);
x++;
}
return (NULL);
}
void *part4(void *arg)
{
t_wolf *wolf;
int x;
t_ray ray;
wolf = (t_wolf*)arg;
x = 1100;
while (x < 1500)
{
init_ray_cmp(&ray, wolf, x);
detect_walls(wolf, &ray);
detect_side_wallh(&ray, wolf);
draw_text(wolf, x, &ray);
init_floor_cel(&ray);
aplly_flo(&ray, wolf, x, wolf->flo);
aplly_cel(&ray, wolf, x, wolf->cel);
x++;
}
return (NULL);
}
|
C
|
#include "common.h"
double q3_sqrt(double num)
{
uint64_t i;
double x, y;
const double f = 1.5;
x = num * 0.5;
y = num;
i = *(uint64_t *) & y;
i = 0x5fe6ec85e7de30da - (i >> i);
y = *(double *)&i;
y = y * (f - (x * y * y));
y = y * (f - (x * y * y));
return num * y;
}
double fast_fabs(double num)
{
uint64_t *tmp;
tmp = (uint64_t *) & num;
*(tmp) &= 9223372036854775807llu;
return num;
}
double fast_sin(double num)
{
const double B = 4 / PI;
const double C = -4 / (PI * PI);
return B * num + C * num * fast_fabs(num);
}
double fast_cos(double num)
{
num += PI / 2;
return fast_sin(num);
}
void array_copy(const double src[M][N][P], double dst[M][N][P])
{
uint32_t i, j, k;
for (k = 0; k < P; k++) {
for (j = 0; j < N; j++) {
for (i = 0; i < M; i++) {
#pragma AP pipeline
dst[i][j][k] = src[i][j][k];
}
}
}
}
|
C
|
#include <stdio.h>
int main()
{
int width = 5;
int height = 8;
int area;
area = width * height;
printf("Area of %d x %d rectangle is %d",width,height,area);
return 0;
}
|
C
|
#include "function_term.h"
#include "utils.h"
#include "error.h"
#include "xfunction_termcap.h"
int my_outc(int c)
{
my_putchar(c);
return (0);
}
void my_bytecopy(const void *src, void *dest, int size)
{
const char *src2;
char *dest2;
int i;
src2 = src;
dest2 = dest;
i = size;
if (src2 < dest2)
while (i)
{
dest2[i] = src2[i];
i--;
}
else if (src2 > dest2)
{
i = 0;
while (i != size)
{
dest2[i] = src2[i];
i++;
}
}
}
int restore_mode(struct termios *oldline)
{
if (xtcsetattr(0, TCSANOW, oldline) < 0)
my_put_error("Error with tcsetattr\n", 1);
return (0);
}
int my_non_canonical_mode(struct termios *oldline)
{
struct termios line;
if (xtcgetattr(0, oldline) < 0)
my_put_error("Error with tcgetattr\n", 1);
my_bytecopy(oldline, &line, sizeof (line));
line.c_lflag &= ~(ICANON | ECHO);
line.c_cc[VMIN] = 1;
line.c_cc[VTIME] = 0;
if (xtcsetattr(0, TCSANOW, &line) < 0)
my_put_error("Error with tcsetattr\n", 1);
return (0);
}
|
C
|
#include <stdio.h>
#define MAX(a, b) (a > b) ? a : b
int main(){
int x, y, max;
printf("input two numbers: ");
scanf("%d %d", &x, &y);
max = MAX(x, y);
printf("max = %d\n", max);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define maxsize 12
#define true 1
#define false 0
typedef struct ArcNode
{
struct ArcNode* nextarc;
int adjvex;
// int weight;
}ArcNode;
typedef struct VNode
{
ArcNode* firstarc;
int data;
}VNode;
typedef struct AGraph
{
VNode adjlist[maxsize];
int n,e;
}AGraph;
void Create_AGraph(AGraph* G)
{
printf("please input VNode and ArcNode number\n");
scanf("%d %d",&(G->n),&(G->e));
printf("please input adjacent arc\n");
ArcNode* p;
int i=0,j=0;
for(int k=0;k<G->n;k++)
{
G->adjlist[k].firstarc=NULL;
G->adjlist[k].data=k;
}
for(int k=0;k<G->e;k++)
{
p=(ArcNode*)malloc(sizeof(ArcNode));
if(p==NULL) printf("malloc fail\n");
scanf("%d %d",&i,&j);
p->adjvex=j;
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
p=NULL;
free(p);
}
void DFS(AGraph* G,int visit[maxsize],int v,int &en,int &vn)
{
ArcNode* p;
visit[v]=1; ++vn;
printf("DFS:%d\n",v);
p=G->adjlist[v].firstarc;
while(p!=NULL)
{
++en;
if(visit[p->adjvex]==0)
{
DFS(G,visit,p->adjvex,en,vn);
}
p=p->nextarc;
}
}
int Is_Gist(AGraph* G,int visit[maxsize])
{
int en=0,vn=0;
DFS(G,visit,0,en,vn);
if((vn==G->n)&&(en==G->n-1))
return true;
else
return false;
}
int main(void)
{
AGraph* G;
G=(AGraph*)malloc(sizeof(AGraph));
int visit[maxsize];
for(int i=0;i<maxsize;i++) visit[i]=0;
Create_AGraph(G);
if (Is_Gist(G,visit)==true)
{
printf("tree\n");
}else{
printf("flase\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void input(int l[50],int h[50],int n);
#function to get the input values for the program
void print(int matrix[50][50],int n);
#function to print the matrix elements
void init(int matrix[50][50],int n);
#function to initialise the matrix
int check(int matrix[50][50],int i,int j,int l[50],int h[50],int n);
int max(int a,int b,int c);
#function to get the maximum element
void comp(int matrix[50][50],int n);
#function to perform the computation
void main()
{
int h[50],l[50],matrix[50][50],n,i,j,k,s,x;
printf("Enter the number of weeks\n");
scanf("%d",&n);
input(l,h,n);
init(matrix,n);
for(i=1;i<=n+1;i++)
{
for(j=1;j<=n+1;j++)
{
if(h[i+1]>l[i]+l[i+1])
{
s=matrix[i-1][j]+h[i+1];
for(k=1;k<=n;k++)
{
matrix[i][k]=matrix[i-1][k];
matrix[i+1][k+1]=s;
}
i=i+2;
}
x=check(matrix,i,j,l,h,n);
if(i==j)
{
matrix[i][j]=max(matrix[i-1][j],x,matrix[i][j-1]);
}
else
{
matrix[i][j]=max(matrix[i-1][j],matrix[i][j-1],0);
}
}
}
print(matrix,n);
}
void input(int l[50],int h[50],int n)
{
int i;
printf("Enter the value of low stress work\n");
for(i=1;i<=n;i++)
{
scanf("%d",&l[i]);
}
printf("Enter the value of high stress work\n");
for(i=1;i<=n;i++)
{
scanf("%d",&h[i]);
}
}
void print(int matrix[50][50],int n)
{
int i,j;
printf("The matrix is\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
printf("%d ",matrix[i][j]);
}
printf("\n");
}
printf("Optimal solution is %d\n",matrix[n][n]);
printf("Composition is ");
comp(matrix,n);
}
void init(int matrix[50][50],int n)
{
int i;
for(i=0;i<=n;i++)
{
matrix[0][i]=0;
matrix[i][0]=0;
}
}
int check(int matrix[50][50],int i,int j,int l[50],int h[50],int n)
{
//if(h[i+1]>l[i]+l[i+1])
// {
// for(j=1;j<=n;j++)
// {
// matrix[i][j]=matrix[i-1][j];
// matrix[i+1][j]=matrix[i-1][j];
// }
// i=i+2;
// return matrix[i][j]+h[i+1];
// }
//else
// {
return matrix[i-1][j]+l[i];
i++;
// }
}
int max(int a,int b,int c)
{
if(a>b&&a>c)
{
return a;
}
else if(b>a&&b>c)
{
return b;
}
else
{
return c;
}
}
void comp(int matrix[50][50],int n)
{
int a;
if(matrix[n][n]>matrix[n][n-1]&&n!=0)
{
a=matrix[n][n]-matrix[n][n-1];
printf("%d ",a);
n--;
comp(matrix,n);
}
}
|
C
|
#include "../inc/query_record.h"
#include "../inc/query_hashtable.h"
#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>
int init_space_record(void *s, unsigned long size, space_t *space, unsigned int arg)
{
record_t *p = (record_t *)(s+sizeof(space_t));
space->first_record = p;
char *q = (char *)((char *)p+sizeof(record_t)); //注意这里的p,计算的时候将p弱化成char
while(q<=(char *)(space->hash))
{
memset(p, 0, sizeof(record_t));
//下面两个指针的初始化已经被memset做掉了
//INIT_LIST_HEAD(&(p->list_record));
//INIT_HLIST_NODE(&(p->hash_node));
list_add(&(p->list_record), &(space->head));
p = (record_t *)q;
q = (char *)((char *)p+sizeof(record_t));
space->stat.records_num++;
}
space->stat.record_free = space->stat.records_num;
printf("records_num: %d\n", space->stat.records_num);
printf("record_free: %d\n", space->stat.record_free);
return 0;
}
record_t *get_free_record(space_t *space)
{
record_t *record;
record = ( (space->head.next==&(space->tail))?NULL:(record_t *)(list_entry(space->head.next, record_t, list_record)));
if(record != NULL)
{
space->stat.record_free--;
}
else
{
//处理原则待定,先预留
fprintf(stderr, "结点不够,该记录不予存储!\n");
}
//设置标志位,移动到使用结点部分
set_record_flags(record, RECORD_USE);
list_move(&(record->list_record), &(space->tail));
return record;
}
int free_record(record_t *record, space_t *space)
{
//循环链表位置的移动,hash表位置的移动
unmount_record_from_hash(record);
__list_del_entry(&(record->list_record));
memset(record, 0, sizeof(record_t));
list_add(&(record->list_record), &(space->head));
space->stat.record_free++;
return 0;
}
//int url_out_to_in(const char *url_out, char *url_in)
int md5_url(const char *url_out, int len, unsigned char *url_md5_in)
{
//留住文件名部分即可
url_md5_in = MD5(url_out, len, url_md5_in);
return 0;
}
int empty_records(space_t *space)
{
struct list_head *p;
record_t *record;
for(p=&(space->tail.next); p!=&(space->hot_boundary); p=p->next)
{
record = list_entry(p, record_t, list_record);
free_record(record, space);
}
for(p=&(space->hot_boundary.next); p!=&(space->head); p=p->next)
{
record = list_entry(p, record_t, list_record);
free_record(record, space);
}
return 0;
}
|
C
|
#include <stdio.h>
void main(){
/* Here, you must write the source code */
char name [80];
int age;
float weight;
printf("Please, entry your name: ");
scanf("%s", name);
printf("Please, entry your age: ");
scanf("%d", &age);
printf("Please, entry your weight in kilograms: ");
scanf("%f", &weight);
printf("\nMy name is %s and I am %d years old. My weight is %f kg.\n", name, age, weight);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.