language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include "bib.h"
int main()
{
setlocale(LC_ALL, "Portuguese");
int op;
char nomeArquivo[256];
FILE *file;
int N;
dados_cov *D;
indexacao *I;
int achou;
do{
op = menu();
switch (op){
case 1: //Ler Arquivo
printf("Digite o nome do arquivo a ser lido:");
scanf("%s", nomeArquivo);
setbuf(stdin,NULL);
file = fopen(nomeArquivo, "r");
if(file){
N = tamfile(file);
D = (dados_cov*) malloc(sizeof(dados_cov) * N);
file = fopen(nomeArquivo, "r");
PreencheStruct(N, file, D);
printf("Arquivo Lido e carregado com %d linhas!\n", N);
}
else
printf("arquivo n abriu");
break;
case 2: //Indexar Dados
I = (indexacao*) malloc(sizeof(dados_cov) * N);
Indexar(I,D,N);
break;
case 3: //Consulta
printf("Insira o termo de busca do tipo: UFAA/MM/DD\nPor exemplo, para:\nEstado: Goiás, dia: 25/03/2019\nDigite: GO19/03/25\n");
achou = Consulta(D,I,N);
if(achou == -1)
printf("Termo de busca não encontrado!\n");
break;
case 0: //Sair
printf("Até mais!\n");
break;
default :
printf("Opção Inválida, por falor seleciona uma opção válida!\n");
break;
}
}while(op != 0);
free(D);
free(I);
fclose(file);
return 0;
}
|
C
|
/*Създайте test1.txt файл в избрана от вас директория. Сложете някакви
данни в него на латиница - име, поздрав, брой. Отворете за четене.
Използвайте fgetc() , която взема само един char от файла. Направете
while цикъл, за да изпишете всички символи, проверявайте за край на
файл с EOF. Проверявайте дали файловият пойнтер не е NULL, ако е
NULL, изпишете грешка.*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char c;
FILE *pfile = NULL;
char *filename = "test1.txt";
pfile = fopen (filename, "r");
if(pfile == NULL)
printf("Failed to open %s.\n", filename);
while((c = fgetc(pfile)) != EOF) {
printf("%c", c);
}
fclose(pfile);
pfile = NULL;
return 0;
}
|
C
|
#include<stdio.h>
void DisplayRangeRev(int iStart,int iEnd)
{
int iCnt=0;
for(iCnt=iEnd;iCnt>=iStart;iCnt--)
{
printf("%d\n",iCnt);
}
}
int main(int argc,char * argv[])
{
int iFirst=0,iLast=0,iRet;
printf("Enter the first and last number->");
scanf("%d%d",&iFirst,&iLast);
printf("reverse order between %d to %d->\n",iFirst,iLast);
DisplayRangeRev(iFirst,iLast);
return 0;
}
|
C
|
int main()
{
int n,count=0;
scanf("%d",&n);
char s[100];
scanf("%s",s);
for(int i=0;i<n-1;i++)
{
if(s[i]==s[i+1])
{
count++;
}
}
printf("%d",count);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lists.h"
List* List_Concatenate(List* firstList, List* secondList)
{
if(firstList->count == 0){
firstList->first = secondList->first;
firstList->last = secondList->last;
firstList->count = secondList->count;
return secondList;
}
else if(secondList->count == 0){
return firstList;
}
firstList->count = firstList->count + secondList->count;
Node_Link(firstList->last, secondList->first);
firstList->last = secondList->last;
free(secondList);
return firstList;
}
int List_Contains(List* list, void* value)
{
for (Node* node = list->first; node != NULL; node = node->next) {
if (node->value == value)
{
return 1;
}
}
return 0;
}
List* List_Remove_At_Index(List* list, int index){
if(list->count == 0){
return list;
}
else if(list->count < index + 1 || index < 0 ){
printf("Index out of range!");
exit(1337);
}
if(list->count == 1){
free(list->first);
list->first = NULL;
list->last = NULL;
list->count = 0;
}
else if(index == 0){
list->first = list->first->next;
free(list->first->prev);
list->first->prev = NULL;
list->count--;
}
else if(index + 1 == list->count){
list->last = list->last->prev;
free(list->last->next);
list->last->next = NULL;
list->count--;
}
else {
Node *current_node = list->first;
while (index > 0) {
current_node->next;
index--;
}
current_node->prev->next = current_node->next;
current_node->next->prev = current_node->prev;
free(current_node);
list->count--;
}
return list;
}
List* List_Remove_First(List* list){
if(list->count == 0){
return list;
}
else if(list->count == 1){
free(list->first);
list->first = NULL;
list->last = NULL;
list->count = 0;
}
else{
list->first = list->first->next;
free(list->first->prev);
list->first->prev = NULL;
list->count--;
}
return list;
}
List* List_Append(List* list, void* value)
{
if (list->count == 0)
{
list->count = 1;
Node* node = Node_Create(value);
list->first = node;
list->last = node;
return list;
}
else
{
Node* appended_node = Node_Append(list->last, value);
list->count++;
list->last = appended_node;
return list;
}
}
List* List_Prepend(List* list, void* value)
{
if (list->count == 0)
{
return List_Initialize(list, value);
}
else
{
Node* prepended_node = Node_Prepend(list->first, value);
list->first = prepended_node;
list->count++;
return list;
}
}
void List_Iterate(List* list, void (*f)(void*)) {
for (Node* node = list->first; node != NULL; node = node->next) {
f(node->value);
}
}
List* List_InsertAtIndex(List* list, int index, void* value)
{
if (index == 0) // If index is first element
{
return List_Prepend(list, value);
}
else if (index < list->count) // If index out of range, or index is last element.
{
return List_Append(list, value);
}
else
{
return List_UnsafeInsertAtIndex(list, index, value);
}
}
List* List_UnsafeInsertAtIndex(List* list, int index, void* value)
{
Node* node = list->first;
for (int i = 0; i < index; i++)
{
node = node->next;
}
Node_Insert(node->prev, value);
list->count++;
return list;
}
void List_ClearAndDestroy(List* list)
{
List_ClearContent(list);
List_Destroy(list);
}
void List_Destroy(List* list)
{
for (Node* node = list->first; node != NULL; node = node->next) {
free(node->prev);
}
free(list->last);
free(list);
}
void List_ClearContent(List* list){
for (Node* node = list->first; node != NULL; node = node->next) {
Node_ClearContent(node);
}
}
List* List_Initialize(List* list, void* value)
{
Node* node = Node_Create(value);
list->first = node;
list->last = node;
list->count = 1;
return list;
}
List* List_Create() {
List* list = malloc(sizeof(struct List));
//List* list = calloc(1, sizeof(struct List));
list->count = 0;
list->first = NULL;
list->last = NULL;
return list;
}
// NODE LOGIC
Node* Node_Prepend(Node* originalNode, void* value)
{
Node* newNode = Node_Create(value);
Node_Link(newNode, originalNode);
return newNode;
}
Node* Node_Append(Node* originalNode, void* value)
{
Node* newNode = Node_Create(value);
Node_Link(originalNode, newNode);
return newNode;
}
Node* Node_Insert(Node* beginNode, void* value)
{
Node* endingNode = beginNode->next;
Node* insertedNode = Node_Create(value);
Node_Link(beginNode, insertedNode);
Node_Link(insertedNode, endingNode);
return beginNode;
}
Node* Node_Link(Node* firstNode, Node* secondNode)
{
firstNode->next = secondNode;
secondNode->prev = firstNode;
return firstNode;
}
Node* Node_Create(void* value)
{
Node* node = malloc(sizeof(struct Node));
//Node* node = calloc(1, sizeof(struct Node));
node->value = value;
node->next = NULL;
node->prev = NULL;
return node;
}
void Node_ClearContent(Node* node){
free(node->value);
}
|
C
|
/*************************************************************************
> File Name: 2.75.c
> Author: hcwang
> Mail: [email protected]
> Created Time: Thu 30 Apr 2015 10:21:55 PM CST
************************************************************************/
#include<stdio.h>
unsigned unsigned_high_prod(unsigned x, unsigned y){
int x_highest = 1 && (x & INT_MIN);
int y_highest = 1 && (x & INT_MIN);
return signed_high_prod(x, y) + y_highest*x + x_highest*y;
}
|
C
|
#include "assemble.h"
#include "instr.h"
#include "register.h"
#include <string.h>
#include <stdlib.h>
// Three static char buffers to put the params in while assembling
static char param1[MAX_PARAM_LENGTH + 1] = { [MAX_PARAM_LENGTH] = '\0' };
static char param2[MAX_PARAM_LENGTH + 1] = { [MAX_PARAM_LENGTH] = '\0' };
static char param3[MAX_PARAM_LENGTH + 1] = { [MAX_PARAM_LENGTH] = '\0' };
static inline void clear_params() {
param1[MAX_PARAM_LENGTH] = '\0';
param2[MAX_PARAM_LENGTH] = '\0';
param3[MAX_PARAM_LENGTH] = '\0';
}
static inline int iswhitespace(char c) { return c == ' ' || c == '\n' || c == '\t' || c == -1; }
static inline int buffer_past_whitespace(FILE *fp) {
char c;
while ((c = fgetc(fp)) != EOF && iswhitespace(c)); // read one byte, if it's whitespace, continue, else break
if (c == EOF)
return EOF;
fseek(fp, -1, SEEK_CUR); // move the file pointer back one byte
return 0;
}
/**
* next_str function
* @param fp File pointer
* @param buffer string buffer pointer
* @param len Max length of buffer
* @param terminator char that ends the search for the string
* @return 0 if successfully found string, -1 if EOF, and -2 if a different char was found
*/
#define STR_NOT_FOUND (-2)
// just use the null terminator to denote whitespace as a terminator
#define WHITESPACE ('\0')
static int next_str(FILE *fp, char *buffer, int len, char terminator) {
if (len <= 0) return -1;
int start = ftell(fp); // get starting position of pointer
int i = 0;
char c;
while ((c = fgetc(fp)) != terminator && c != EOF && i < len) {
if (terminator == WHITESPACE && iswhitespace(c))
break;
// if char is whitespace, just skip it (advance fp but don't add to buffer)
if (!iswhitespace(c)) {
*buffer++ = c;
i++;
}
}
*buffer = '\0'; // set last character to zero (overwrite terminator)
if (i + 1 == len) {
fseek(fp, start, SEEK_CUR);
return STR_NOT_FOUND;
}
if (c == EOF) {
fseek(fp, start, SEEK_SET);
return EOF;
}
// fseek(fp, -1, SEEK_CUR); // skip back to before the terminator
return 0;
}
typedef struct {
int line;
int col;
} fp_pos_t;
static inline fp_pos_t get_fp_pos(FILE *fp) {
int pos = ftell(fp);
fseek(fp, 0, SEEK_SET); // go to the beginning of the file
char c;
int line_count = 1;
int col_count = 1;
for (int i = 0; i < pos; i++) {
col_count++;
c = fgetc(fp);
if (c == '\n') {
line_count++;
col_count = 1; // reset column counter
}
}
// we've calculated line/col count and fp is now in the same position as before
return (fp_pos_t) { line_count, col_count };
}
static void print_error(FILE *fp, const char *error_str, const char *other) {
fp_pos_t pos = get_fp_pos(fp);
printf("Error: '%s%s' at %d:%d\n", error_str, other, pos.line, pos.col);
}
static int try_find_register(FILE *fp, const char *buffer) {
int reg = find_register(buffer);
if (reg == -1)
print_error(fp, "Malformatted register ", buffer);
else if (reg == -2)
print_error(fp, "Unknown register ", buffer);
return reg;
}
#define FIND_IMM_ERR (UINT32_MAX)
static uint32_t try_find_immediate(FILE *fp, const char *buffer) {
char* end;
long number = strtol(buffer, &end, 0);
if (*end == '\0') {
if (number < ((1 << 16) - 1))
return number;
else
print_error(fp, "Immediate value too large!", buffer);
} else
print_error(fp, "Value is not a valid number", buffer);
return FIND_IMM_ERR;
}
// fills the param1 char buffer
static int get_one_param(FILE *fp) {
clear_params();
if (buffer_past_whitespace(fp) == EOF)
return -1;
// get next string into param1
if (next_str(fp, param1, MAX_PARAM_LENGTH, ' ') == 0)
return 0;
else {
print_error(fp, "Param not found", "");
return -1;
}
}
static int get_two_params(FILE *fp) {
clear_params();
// skip any whitespace after instruction
if (buffer_past_whitespace(fp) == EOF)
return -1;
// look for a comma
int ret = next_str(fp, param1, MAX_PARAM_LENGTH, ',');
if (ret == EOF) {
if (feof(fp))
print_error(fp, "Missing param separator", "");
else
print_error(fp, "Param is too long!", "");
return -1;
} else if (ret == STR_NOT_FOUND) {
// if string not found, we found another character
char c[2] = { fgetc(fp), '\0' };
print_error(fp, "Random character", c);
return -1;
} else {
// else we found the comma, find the next param
buffer_past_whitespace(fp);
// find whitespace
ret = next_str(fp, param2, MAX_PARAM_LENGTH, WHITESPACE);
if (ret == EOF) {
if (feof(fp))
print_error(fp, "Missing param separator", "");
else
print_error(fp, "Param is too long!", "");
return -1;
} else if (ret == STR_NOT_FOUND) {
// if string not found, we found another character
char c[2] = { fgetc(fp), '\0' };
print_error(fp, "Random character", c);
return -1;
}
}
return 0;
}
static int get_three_params(FILE *fp) {
clear_params();
// skip any whitespace after instruction
if (buffer_past_whitespace(fp) == EOF)
return -1;
// look for a comma
int ret = next_str(fp, param1, MAX_PARAM_LENGTH, ',');
if (ret == EOF) {
if (feof(fp))
print_error(fp, "Missing param separator", "");
else
print_error(fp, "Param is too long!", "");
return -1;
} else if (ret == STR_NOT_FOUND) {
// if string not found, we found another character
char c[2] = { fgetc(fp), '\0' };
print_error(fp, "Random character", c);
return -1;
} else {
// else we found the comma, find the next param
buffer_past_whitespace(fp);
// look for comma
ret = next_str(fp, param2, MAX_PARAM_LENGTH, ',');
if (ret == EOF) {
if (feof(fp))
print_error(fp, "Missing param separator", "");
else
print_error(fp, "Param is too long!", "");
return -1;
} else if (ret == STR_NOT_FOUND) {
// if string not found, we found another character
char c[2] = { fgetc(fp), '\0' };
print_error(fp, "Random character", c);
return -1;
} else {
// else we found the comma, find the next param
buffer_past_whitespace(fp);
// find whitespace
ret = next_str(fp, param3, MAX_PARAM_LENGTH, WHITESPACE);
if (ret == EOF) {
if (feof(fp))
print_error(fp, "Missing param separator", "");
else
print_error(fp, "Param is too long!", "");
return -1;
} else if (ret == STR_NOT_FOUND) {
// if string not found, we found another character
char c[2] = { fgetc(fp), '\0' };
print_error(fp, "Random character", c);
return -1;
}
}
}
return 0;
}
static int get_one_reg(FILE *fp, uint8_t *reg) {
// try to get one param into param1
if (get_one_param(fp) != 0)
return -1;
int res = try_find_register(fp, param1);
if (res > -1)
*reg = res;
else
return -1;
return 0;
}
static int get_two_regs(FILE *fp, uint8_t *reg1, uint8_t *reg2) {
// try to get two params
if (get_two_params(fp) != 0)
return -1;
int res = try_find_register(fp, param1);
if (res > -1)
*reg1 = res;
else
return -1;
res = try_find_register(fp, param2);
if (res > -1)
*reg2 = res;
else
return -1;
return 0;
}
static int get_three_regs(FILE *fp, uint8_t *reg1, uint8_t *reg2, uint8_t *reg3) {
// try to get two params
if (get_three_params(fp) != 0)
return -1;
int res = try_find_register(fp, param1);
if (res > -1)
*reg1 = res;
else
return -1;
res = try_find_register(fp, param2);
if (res > -1)
*reg2 = res;
else
return -1;
res = try_find_register(fp, param3);
if (res > -1)
*reg3 = res;
else
return -1;
return 0;
}
static int get_two_regs_and_imm(FILE *fp, uint8_t *reg1, uint8_t *reg2, int16_t *imm) {
// try to get three params
if (get_three_params(fp) != 0)
return -1;
int res = try_find_register(fp, param1);
if (res > -1)
*reg1 = res;
else
return -1;
res = try_find_register(fp, param2);
if (res > -1)
*reg2 = res;
else
return -1;
res = try_find_immediate(fp, param3);
if (res != FIND_IMM_ERR)
*imm = res;
else
return -1;
return 0;
}
static int get_regs_and_offset(FILE *fp, uint8_t *reg1, uint8_t *reg2, int16_t *offs) {
// try to get two params
if (get_two_params(fp) != 0)
return -1;
// first param is the first reg
int res = try_find_register(fp, param1);
if (res > -1)
*reg1 = res;
else
return -1;
// second param looks like this: offs(reg), so we just find the opening parenthesis and have fun
// read from param2 start to index of (
char *open_paren = strchr(param2, '(');
if (open_paren == NULL) {
print_error(fp, "Malformatted offset", param2);
return -1;
}
*open_paren = '\0'; // turn the ( into a null terminator so we can read an immediate from it
res = try_find_immediate(fp, param2);
if (res != FIND_IMM_ERR)
*offs = res;
else
return -1;
// read the register
// first we find the closing parenthesis by starting at the opening one
char *close_paren = strchr(open_paren + 1, ')');
if (open_paren == NULL) {
print_error(fp, "Malformatted source register", param2);
return -1;
}
*close_paren = '\0'; // turn the ( into a null terminator so we can read an immediate from it
// second register is between the open and close parenthesis
res = try_find_register(fp, open_paren + 1);
if (res > -1)
*reg2 = res;
else
return -1;
return 0;
}
static int get_one_reg_and_imm(FILE *fp, uint8_t *reg1, int16_t *imm) {
// try to get three params
if (get_two_params(fp) != 0)
return -1;
int res = try_find_register(fp, param1);
if (res > -1)
*reg1 = res;
else
return -1;
res = try_find_immediate(fp, param2);
if (res != FIND_IMM_ERR)
*imm = res;
else
return -1;
return 0;
}
static int set_params(InstrID id, FILE *fp, instr_t *instr) {
ParamOrder order = PARAM_ORDERS[id];
// if no params, just return, don't set any params
if (order == NONE)
return 0;
int ret = 0;
// Get param order based on id, parse params
switch (order) {
case RS: ret = get_one_reg(fp, &instr->rs); break;
case RD: ret = get_one_reg(fp, &instr->rd); break;
case RD_RS: ret = get_two_regs(fp, &instr->rd, &instr->rs); break;
case RS_RT: ret = get_two_regs(fp, &instr->rs, &instr->rt); break;
case RD_RS_RT: ret = get_three_regs(fp, &instr->rd, &instr->rs, &instr->rt); break;
case RD_RT_RS: ret = get_three_regs(fp, &instr->rd, &instr->rt, &instr->rd); break;
case RD_RT_SA: ret = get_two_regs_and_imm(fp, &instr->rd, &instr->rt, &instr->shamt); break;
case LABEL: break;
case RT_RS_IMM: ret = get_two_regs_and_imm(fp, &instr->rt, &instr->rs, &instr->imm); break;
case RS_RT_LABEL: break;
case RS_LABEL: break;
case RT_IMM_RS: ret = get_regs_and_offset(fp, &instr->rt, &instr->rs, &instr->imm); break;
case RT_IMM: ret = get_one_reg_and_imm(fp, &instr->rt, &instr->imm); break;
}
return ret;
}
/**
* Takes a file pointer to the assembly file, advances the pointer, and returns a packed instruction
* Assume we've read the instruction from the file already, so we have the id
*/
static int64_t construct_instruction(FILE *fp) {
instr_t instr;
char c;
char instr_str[10];
// from current position to the next space
next_str(fp, instr_str, 10, WHITESPACE);
InstrID id = find_instr(instr_str);
if (id == INVALID) {
print_error(fp, "Unknown instruction ", instr_str);
return -1;
}
// populate fields that we can after instruction
instr.opcode = get_opcode(id);
instr.funct = get_funct(id);
instr.type = get_type(id);
instr.rs = 0;
instr.rt = 0;
instr.rd = 0;
instr.shamt = 0;
instr.imm = 0;
if (set_params(id, fp, &instr) == -1)
return -1; // error occurred
return pack_instr(&instr);
}
/**
* Takes the paths of input and output files
*/
int assemble(const char *infile, const char *outfile) {
FILE *fin = fopen(infile, "r");
FILE *fout = fopen(outfile, "w");
if (fin == NULL || fout == NULL)
return -1;
uint32_t pc = 0;
while (1) {
// assume we're looking for an instruction or label
if (buffer_past_whitespace(fin) == EOF) {
printf("Reached end of file.\n");
break;
}
// we've found something, read the string
char str[100];
// look for a label
if (next_str(fin, str, sizeof(str), ':') > 0) {
// we found a label
// do something with the label, then continue
continue;
}
// label was not found, try to decode as instruction
int64_t instr_code = construct_instruction(fin);
if (instr_code == -1) {
printf("Reached end of file but something bad happened :(\n");
break;
} else {
uint32_t instr_code_packed = instr_code;
fwrite(&instr_code_packed, sizeof(uint32_t), 1, fout);
}
}
fclose(fin);
fclose(fout);
return 0;
}
|
C
|
#include <stdio.h>
#define SQR_SIZE 5
#define AUG_SQR_SIZE (SQR_SIZE + 4)
int main()
{
int magicSqr[SQR_SIZE][SQR_SIZE] = {0};
int augSqr[AUG_SQR_SIZE][AUG_SQR_SIZE] = {0};
int currNum = 1;
int iM, jM;
for (int n = 0; n < SQR_SIZE; n++)
{
for (int i = 0; i < SQR_SIZE; i++)
{
augSqr[SQR_SIZE - 1 - i + n][i + n] = currNum;
currNum++;
}
}
for (int i = 0; i < AUG_SQR_SIZE; i++)
{
iM = i - 2;
if (iM < 0) iM += SQR_SIZE;
else if (iM >= SQR_SIZE) iM -= SQR_SIZE;
for (int j = 0; j < AUG_SQR_SIZE; j++)
{
if (!augSqr[i][j]) continue;
jM = j - 2;
if (jM < 0) jM += SQR_SIZE;
else if (jM >= SQR_SIZE) jM -= SQR_SIZE;
magicSqr[iM][jM] = augSqr[i][j];
}
}
for (int i = 0; i < SQR_SIZE; i++)
{
for (int j = 0; j < SQR_SIZE; j++)
{
printf("%d\t", magicSqr[i][j]);
}
puts("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <malloc.h>
typedef int QElemType;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front,rear;/*头、尾两个指针*/
}LinkQueue;
/***********************************
*入队列
*入口参数:队列链表指针,入队列元素
***********************************/
int EnQueue(LinkQueue *Q,QElemType e)
{
QueuePtr s= (QueuePtr)malloc(sizeof(QNode));
if(NULL==s)
return -1;
s->data = e;
s->next = NULL;
Q->rear->next = s; /*当前链表尾指针指向添加的链表指针*/
Q->rear = s; /*尾指针为新添加的链表指针*/
return 0;
}
/**************************************
*出队列
*入口参数:队列链表指针,出队列元素指针
**************************************/
int DeQueue(LinkQueue *Q,QElemType *e)
{
QueuePtr P;
if(Q->front== Q->rear)
return -1;
P = Q->front->next; /*将要删除的队列头赋值于P*/
*e = P->data; /*出队列*/
Q->front->next =P->next;/*删除队列头*/
if(Q->rear==P) /*如果队头等于队尾,则将Q的队头队尾指向同一元素*/
Q->rear == Q->front;
free(P);
return 0;
}
|
C
|
/**
* \addtogroup USARTInterface.c
* @{
*
* @file USARTInterface.c
* @author p344575
* @brief USART interface for using TI USART spi driver
* @copyright © 2016 Porsche Engineering Services GmbH
*
* @internal
* $LastChangedDate: 2017-11-14 12:44:56 +0100 (Di, 14 Nov 2017) $
* $LastChangedBy: ksteingass $
* $Revision: 16315 $
* $Id: USARTInterface.c 16315 2017-11-14 11:44:56Z ksteingass $
*
*/
#include "USARTInterface.h"
#include "hal_uart.h"
#include "npi.h"
#include "bcomdef.h"
#include "OSAL.h"
typedef struct
{
uint8_t rxBuffer[USART_IFF_MAX_BUFF_LEN];
uint8_t rxBufferLength;
uint8_t rxBufferCounter;
uint8_t isTxComplete;
} USARTInterfaceAttributes_t;
/* private functions */
static void cSerialPacketParser(uint8 port, uint8 event);
static void onTxComplete(void);
/* module attributes */
static USARTInterfaceAttributes_t attr;
/***
* @brief Module initialization
*/
void USARTInterfaceInit(void)
{
NPI_InitTransport(&cSerialPacketParser); /* Initializing NPI */
attr.rxBufferLength = 0;
attr.rxBufferCounter = 0;
attr.isTxComplete = 1;
/* Transmission complete callback */
HalUART_SetTxCompleteCB(&onTxComplete);
}
/**
* @brief Pushed data to sent over the USARTSPI interface
* @param data
* @param dataLength
* @return 0: pushed correctly
* 1: could not sent correctly
* 2: cannot push until previous data has not been sent
*/
uint8_t USARTInterfacePush(uint8_t data[], uint8_t dataLength)
{
uint8_t ret = SUCCESS;
uint8_t bytesSent;
if (attr.isTxComplete == 0)
{
ret = 2; /* transmission still ongoing, cannot push */
}
else
{
attr.isTxComplete = 0;
bytesSent = HalUARTWrite(NPI_UART_PORT, data, dataLength);
if (bytesSent != dataLength)
{
ret = 1;
}
}
return ret;
}
/**
* @brief private callback called when transmissions are completed
*/
static void onTxComplete(void)
{
attr.isTxComplete = 1;
}
/**
* @brief Getter for the transmission complete state
* @return TRUE: yes - transmission complete
* FALSE: no
*/
uint8_t USARTInterfaceIsTxComplete(void)
{
return (attr.isTxComplete == 1) ? TRUE : FALSE;
}
/**
* @brief It retrieves a byte from the RX buffer
* @param byte: pointer to where value will be stored
* @return 0: No byte is available for retrieval
* SPI_HAS_DATA: a valid byte has been copied to the destination byte
*/
unsigned char USARTInterfaceGetRxByte(unsigned char * byte)
{
unsigned char cRet = 0;
if (attr.rxBufferCounter < attr.rxBufferLength)
{
*byte = attr.rxBuffer[attr.rxBufferCounter++];
cRet = SPI_HAS_DATA;
if (attr.rxBufferCounter >= attr.rxBufferLength)
{
/* all bytes available have been retrieved */
attr.rxBufferCounter = 0;
attr.rxBufferLength = 0;
}
}
return cRet;
}
/**
* @brief Called by the NPI interface when new data has been received over the
* USARTSPI interface
* @param port
* @param event
*/
static void cSerialPacketParser(uint8 port, uint8 event)
{
(void) port; /* not used */
(void) event; /* not used */
/* only use data read when previous received buffer has been feteched */
if (attr.rxBufferLength == 0 && attr.rxBufferCounter == 0)
{
/* get the number of available bytes to process */
attr.rxBufferLength = NPI_RxBufLen();
/* loading data from the serial interface */
if (NPI_ReadTransport(attr.rxBuffer, attr.rxBufferLength) != attr.rxBufferLength)
{
/* Failed to retrieve all data available */
attr.rxBufferLength = 0;
}
}
}
/** @}*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <time.h>
#include "golibroda.h"
int semid, waiting;
void get_time() {
struct timespec tp;
if(clock_gettime(CLOCK_MONOTONIC, &tp)==-1) {
perror("clock_gettime");
}
printf(" %ld\n", tp.tv_sec * 1000000 + tp.tv_nsec/1000);
}
int is_empty(int* queue) {
if (queue[0] == 0) return 1;
else return 0;
}
int is_full(int *queue, int N) {
if(queue[0]==N) {
return 1;
}
else {
return 0;
}
}
void put(int *queue, int elem) {
queue[0]++;
int pos = queue[0];
queue[pos] = elem;
}
void do_action(int *queue, int id, char* announ) {
put(queue, id);
printf("%d: %s", id, announ);
get_time();
struct sembuf sops;
sops.sem_num = 1;
sops.sem_flg = 0;
sops.sem_op = 1;
if(semop(semid, &sops, 1)==-1) {
perror("semop");
}
waiting = 1;
}
void handler(int signum) {
waiting = 0;
}
int main(int argc, char **argv) {
if(argc!=3) {
printf("Wrong number of arguments.\n");
return 1;
}
struct sigaction act;
act.sa_handler = handler;
sigemptyset(&act.sa_mask);
act.sa_flags=0;
sigaction(SIGRTMIN, &act, NULL);
char *homedir;
int K, S, shmid;
pid_t pid;
K = atoi(argv[1]);
S = atoi(argv[2]);
char *wake_up = "Obudzilem golibrode";
char *take_seat = "Zajalem miejsce w poczekalni";
waiting = 0;
homedir = getenv("HOME");
key_t key = ftok(homedir, PROJ);
if(key == -1) {
perror("Error with ftok");
return 1;
}
if((shmid = shmget(key, 0, 0))==-1) {
perror("Error with shmget");
return 1;
}
key = ftok(homedir, PROJ2);
if(key == -1) {
perror("Error with ftok");
return 1;
}
if((semid = semget(key, 0, 0))==-1) {
perror("Error with semget");
return 1;
}
for(int i=0; i<K; i++) {
pid = fork();
if(pid==0) {
int *addr, id;
if((addr = shmat(shmid, NULL, 0)) == (void*) -1) {
perror("Error with shmat");
return 1;
}
id = getpid();
int b=1;
struct sembuf sops;
sops.sem_num=0;
sops.sem_flg=SEM_UNDO;
for(int j=0; j<S && b; j++) {
sops.sem_op=-1;
if(semop(semid, &sops, 1)==-1) {
perror("semop");
}
if(is_empty(addr+2) && addr[1]) {
do_action(addr+2, id, wake_up);
}
else if(!is_full(addr+2, addr[0])) {
do_action(addr+2, id, take_seat);
}
else {
printf("%d: Brak wolnych miejsc- opuszczam zaklad", id);
get_time();
b=0;
}
sops.sem_op = 1;
if(semop(semid, &sops, 1)==-1) {
perror("semop");
}
while(waiting);
}
if(b) {
printf("%d: Zakonczylem strzyzenie- opuszczam zaklad", id);
get_time();
}
shmdt(addr);
exit(0);
}
else if(pid == -1) {
perror("Error with fork");
return 1;
}
}
for(int i = 0; i < K; i++){
int status;
wait(&status);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
float p, l;
printf("Masukkan panjang persegi (m) = ");
scanf("%f", &p);
printf("Masukkan lebar persegi (m) = ");
scanf("%f", &l);
printf("Luas persegi adalah (m2) = %.2f \n", p * l);
return 0;
}
|
C
|
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
//variable for the maximum number of processes that can be run by program
#define maxProcesses 5
//global variable for foreground only mode
bool foregroundOnly = false;
//global variable to access the terminating signal from the sigint signal
int sigExit = 0;
//struct that stores all of a commands arguments, the count of arguments entered
//the input file specified, the output file if specified, and a boolean indicating
//if the command is a foreground or background process
struct userCmd{
char* args[512];
int nArgs;
char* inputFile;
char* outputFile;
bool foreground;
};
//struct that store the active background processes id values
//and the count of the number of active background processes
struct activePids{
pid_t pids[maxProcesses];
int nPids;
};
//function to kill all running background processes
//no need to pass in exitMethod because we only call this function
//when exiting the shell
void killBackProcesses(struct activePids* processes){
int n;
int status = -5;
//loop through all background processes, kill them, and restore their pid value to -1
for(n = 0; n < processes->nPids; n++){
kill(processes->pids[n], SIGTERM);
waitpid(processes->pids[n], &status, 0);
processes->pids[n] = -1;
}
}
//helper function to make sure that I dont accidentally make too many processes
//is check before each fork() call
void checkPids(struct activePids* processes){
//if adding another process would put the program over the maximum number of
//processes then print an error message, kill all background processes, and exit the current process
if((processes->nPids + 1) > maxProcesses){
killBackProcesses(processes);
perror("Too many processes running at once\n");
exit(1);
}
}
//add a background process id to the struct that stores all background process process ids
//assumes that the checkPids func has been called already so we know we are in bounds of our array
void addPid(struct activePids* processes, pid_t pid){
//add pid to the end of the array and increment the number of pids in the array
processes->pids[processes->nPids] = pid;
processes->nPids++;
}
//remove a process id from the struct that stores the background process ids
void removePid(struct activePids* processes, pid_t pid){
int n, m;
//loop through the list of process ids to find the relevant pid
for(n = 0; n < processes->nPids; n++){
//once found replace the current index of the pid with the next in line
if(processes->pids[n] == pid){
for(m = n; m < (processes->nPids - 1); m++){
processes->pids[m] = processes->pids[m+1];
}
//replace the last pid stored with -1 because it has been copied in the previous slot
//in the for loop above
processes->pids[processes->nPids - 1] = -1;
break;
}
}
processes->nPids--;
}
//initiate the values for the struct that stores the process ids of all background processes
void initProcesses(struct activePids* processes){
int n;
//each pid is initialized to -1 so that it will throw an error if accessed
for(n = 0; n < maxProcesses; n++){
processes->pids[n] = -1;
}
//initial number of pids stored is zero
processes->nPids = 0;
}
//helper function to get the number of characters in a string
//was having problems with accessing the built in strlen so I created my own
int strLen(char* string){
int n = 0;
//count the number of characters until the null terminator is reached
while(string[n] != '\0'){
n++;
};
return(n+1);
}
//reset the command values for each iteration of shell
void resetCmd(struct userCmd* command){
command->nArgs = 0;
command->inputFile = NULL;
command->outputFile = NULL;
command->foreground = true;
}
//prompt the user for input and store the input appropriately in the command struct
void getUserCommand(struct userCmd* command){
char* input;
int n = 0;
int sizeInput;
bool boolInput = false;
bool boolOutput = false;
//initialize buffer size and intialize memory and contents
int bufSize = 2048;
char* buffer = (char*) malloc(bufSize*sizeof(char));
memset(buffer, '\0', bufSize);
//prompt the shell
fflush(stdout);
printf(": ");
fflush(stdout);
//recieve input
clearerr(stdin);
fgets(buffer, bufSize, stdin);
//parse through the input seperated by spaces
input = strtok(buffer, " \n");
//if thers are values from the input continue parsing until there is no more
if(input != NULL){
while(input != NULL){
//if the input does not indicate an input or output file allocate memory for the command struct and store
//the input in args array
if(strcmp(input, "$$") == 0){
command->args[command->nArgs] = (char*) malloc(10*sizeof(char));
memset(command->args[command->nArgs], '\0', 10);
sprintf(command->args[command->nArgs], "%i", getpid());
command->nArgs++;
} else if ((strcmp(input, "<") != 0) && (strcmp(input, ">") != 0)){
//printf("input: %s accessing arg: %i size of input: %i\n", input, command->nArgs, strLen(input)) ;
command->args[command->nArgs] = (char*) malloc(strLen(input)*sizeof(char));
strcpy(command->args[command->nArgs], input);
command->nArgs++;
//the input indicates a input or output file
} else {
//the input indicates an input or output file. parse one more time to get the name of the file
//then store it in the inputFile or outputFile variable.
if (strcmp(input, "<") == 0){
input = strtok(NULL, " \n");
command->inputFile = (char*) malloc(strLen(input)*sizeof(char));
strcpy(command->inputFile, input);
} else{
input = strtok(NULL, " \n");
command->outputFile = (char*) malloc(strLen(input)*sizeof(char));
strcpy(command->outputFile, input);
}
//Parse again because the file names are not included in the exec function that will be called later
}
input = strtok(NULL, " \n");
};
//if there is an apperand in the last arg then remove it
//if the program is not in foreground only mode then change the command
//forground status to false indicating to run the command in the background
if(strcmp(command->args[command->nArgs - 1], "&") == 0){
free(command->args[command->nArgs - 1]);
command->nArgs--;
if(foregroundOnly == false){
command->foreground = false;
}
}
}
//add the NULL value as the last argument and increment the number of args again
command->args[command->nArgs] = NULL;
command->nArgs++;
free(buffer);
}
//function to print the the last exit or signal status of our shell
void printStatus(int* exitMethod){
//if the exit method from the last process was exited
//print the exit status
if(sigExit != 0){
*exitMethod = sigExit;
sigExit = 0;
}
if(WIFEXITED(*exitMethod)){
printf("exit value %i\n", WEXITSTATUS(*exitMethod));
}else{
//if the process wasnt exited than is was terminated by a signal
//print out the signal value
if(WIFSIGNALED(*exitMethod)){
printf("terminated by signal %i\n", WTERMSIG(*exitMethod));
} else {
//this else statement should never execute but is used just to be sure
//nothing weird is happening
printf("terminated for unknown reason\n");
}
}
}
//free the memory that is allocated to the command struct
void freeCommand(struct userCmd* command){
int n;
//for the memory allocated for each argument
for(n = 0; n < command->nArgs; n++){
free(command->args[n]);
}
//if there was an input of output value stored then free the
//memory allcocated for its name
if(command->inputFile != NULL){
free(command->inputFile);
}
if(command->outputFile != NULL){
free(command->outputFile);
}
}
void printCommand(struct userCmd* command){
int n;
for(n = 0; n < (command->nArgs - 1); n++){
printf("command %i: %s\n",n+1, command->args[n]);
}
if(command->inputFile != NULL){
printf("inputFile: %s\n", command->inputFile);
}
if(command->outputFile != NULL){
printf("inputFile: %s\n", command->outputFile);
}
if(command->foreground){
printf("printcommand: Operating in foreground\n");
}else{
printf("Operating in background\n");
}
}
//function to execute a completed command struct
void executeCommand(struct userCmd* command, struct activePids* processes, int* exitMethod){
//if there was no arguments added to the command then the first arg will be null
//if the first character of the first arg is '#' then it is a comment
//both of these cases result in nothing happening so return the function
if((command->args[0] == NULL) || (command->args[0][0] == '#')){
return;
//if the first argument is cd then we will be changing the current directory
} else if(strcmp(command->args[0], "cd") == 0){
int status;
//if there are only two arguments then cd was the only thing entered
//thus we change to directory to the home directory
if(command->nArgs == 2){
//use the getenv function to get the name of the home directory and call the change directory function
status = chdir(getenv("HOME"));
//check for error during directory change
if(status != 0){
fflush(stdout);
printf("Error changing directory\n");
}
// if the command has three arguments then we are changing to a specfied directory
} else if (command->nArgs == 3) {
//first assume an absolute path has been entered
status = chdir(command->args[1]);
//if directory change failed then test is the path is a relative path
//and add the extension of the current directory to the path
if(status != 0){
char cwd[256];
memset(cwd, '\0',256);
char relPath[512];
memset(cwd, '\0',512);
getcwd(cwd, sizeof(cwd));
//copy in current dir path
strcpy(relPath, cwd);
//add forward slash after dir path
strcat(relPath, "/");
//add in desired path after the forward slash
strcat(relPath, command->args[1]);
//attempt to change directory again
status = chdir(relPath);
}
//if the directory change failed again then the directory does not exist in the current dir
if(status != 0){
fflush(stdout);
printf("No such file or directory\n");
}
}
//if the first arg is exit then kill all background processes and then exit the shell
} else if(strcmp(command->args[0], "exit") == 0){
killBackProcesses(processes);
freeCommand(command);
printf("Exiting smallsh\n");
exit(0);
//if the first arg is status then print the exit status or teminating signal of the last process
} else if(strcmp(command->args[0], "status") == 0){
printStatus(exitMethod);
} else { //Command is a non built in function
pid_t childPid = -5;
pid_t spawnID = -5;
int inputDesc, outputDesc, dupDesc;
//make sure that there are not too many process running
checkPids(processes);
spawnID = fork();
if(spawnID == -1){ //error in fork
perror("Error in fork\n");
*exitMethod = 1;
} else if(spawnID == 0){ //child process
*exitMethod = 0;
//if there is an inut file or the process is running in the foreground then we have to
//alter the input path
if((command->inputFile != NULL) || (command->foreground == false)){
//indicated that the process is running in the background
if(command->inputFile == NULL){
//route input from dev/null to ensure that nothing is written in but correctly
//exits process
inputDesc = open("/dev/null", O_RDONLY);
//there is a specified input file
} else {
//open the file for reading only
inputDesc = open(command->inputFile, O_RDONLY);
}
//if the file could not be opened print error message and exit process with exit status 1
if(inputDesc == -1){
printf("cannot open %s for input\n",command->inputFile);
fflush(stdout);
*exitMethod = 1;
exit(1);
}
//duplicate the input file descriptor
dupDesc = dup2(inputDesc, 0);
//error check for dup 2
//exit with status 1 if error occured
if(dupDesc == -1){
perror("failed dup2 for input file\n");
fflush(stdout);
*exitMethod = 1;
exit(1);
}
//close file for exec
fcntl(inputDesc, F_SETFD, FD_CLOEXEC);
}
//if there is an output file or if the process is operating in the background
if((command->outputFile != NULL) || (command->foreground == false)){
//indicate background process
//use dev/null to ensure that output is sent nowhere but the exit status indicates
//successful execution
if(command->outputFile == NULL){
outputDesc = open("/dev/null", O_WRONLY | O_CREAT | O_TRUNC, 0664);
//there is a specified output file
} else {
//open output file for writing only
//if no file matches path then create it
outputDesc = open(command->outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0664);
}
//error handle for opening file
if(outputDesc == -1){
printf("failed to open %s for output\n", command->outputFile);
fflush(stdout);
*exitMethod = 1;
exit(1);
}
//duplicate file descriptor
dupDesc = dup2(outputDesc, 1);
//error handle for duplication
if(dupDesc == -1){
perror("failed dup2 for output file\n");
fflush(stdout);
*exitMethod = 1;
exit(1);
}
//close file for exec
fcntl(outputDesc, F_SETFD, FD_CLOEXEC);
}
//attempt execution of the command
//if execvp returns -1 then the function failed due to invalid commands
//print error message if needed
if(execvp(command->args[0],command->args) == -1){
if(command->nArgs == 2){
printf("%s: no such file or directory\n", command->args[0]);
} else {
printf("invalid command\n");
}
fflush(stdout);
*exitMethod = 1;
exit(1);
}
} else { //parent process
//if the command is a foreground process wait until child has finished termination
//before reprompting user
if(command->foreground){
childPid = waitpid(spawnID, exitMethod, 0);
//command is a background process
//add to array of background processes and print process id of child
} else {
addPid(processes, spawnID);
printf("Background PID: %i\n", spawnID);
fflush(stdout);
}
}
}
}
//check to see if any background processes have terminated with wait nohang
void waitBackground(struct activePids* processes, int* exitMethod){
int backgroundPid;
//check for a terminated process
backgroundPid = waitpid(-1, exitMethod, WNOHANG);
//if a process has been terminated print its process id, status, and indicator that it finished
//also remove it from the background process array
while(backgroundPid > 0){
if(backgroundPid > 0){
printf("background pid %i is done: ", backgroundPid);
printStatus(exitMethod);
removePid(processes, backgroundPid);
}
backgroundPid = waitpid(-1, exitMethod, WNOHANG);
};
}
//signal handler function for sigint (%C)
//signal should allow all child processes of the current process to terminate
//on their own. the parent should then print the terminating signal for the child
//processes
void catchSIGINT(int signo){
pid_t spawnID;
int exitMethod;
//wait to see if child processes have terminated
//if there are no child processes for the current process
//then wait returns -1
spawnID = wait(&exitMethod);
//while there is a child process for the current process
//print the terminating signal using the write command
if(spawnID == -1){
printf("\n");
} else {
while(spawnID != -1){
if(WIFSIGNALED(exitMethod)){
char message[24];
sprintf(message, "terminated by signal %i\n", WTERMSIG(exitMethod));
write(STDOUT_FILENO, message, 24);
} else {
write(STDOUT_FILENO, "terminated for unknown reason\n", 31);
}
spawnID = wait(&exitMethod);
}
}
sigExit = exitMethod;
}
//signal handler function for the sigtstp (%Z) signal
//should switch the shell in and out of foreground-only mode
void catchSIGTSTP(int signo){
//if the shell is in foreground only mode then switch it out and print
//the indicator message to the user
if(foregroundOnly){
foregroundOnly = false;
write(STDOUT_FILENO,"Exiting foreground-only mode\n", 29);
} else {
//if the shell is not i foreground only mode then switch in into it and
//print the indicator message to the user
foregroundOnly = true;
write(STDOUT_FILENO,"Entering foreground-only mode (& is now ignored)\n", 49);
}
}
void printProcesses(struct activePids* processes){
int n;
printf("Process\tPID\n");
for(n = 0; n < processes->nPids; n++){
printf("%i\t%i\n",n+1, processes->pids[n]);
}
}
int main(){
//initialize signal action stucts and set the signals to trigger
//the signal handle functions instead of their default values
struct sigaction actionSIGINT = {0};
actionSIGINT.sa_handler = catchSIGINT;
sigfillset(&actionSIGINT.sa_mask);
actionSIGINT.sa_flags = 0;
sigaction(SIGINT, &actionSIGINT, NULL);
struct sigaction actionSIGTSTP = {0};
actionSIGTSTP.sa_handler = catchSIGTSTP;
sigfillset(&actionSIGTSTP.sa_mask);
actionSIGTSTP.sa_flags = 0;
sigaction(SIGTSTP, &actionSIGTSTP, NULL);
//initialize the command struct and background process id struct
struct userCmd command;
struct activePids processes;
int exitMethod = 0;
initProcesses(&processes);
while(1){
fflush(stdout);
resetCmd(&command);
//printProcesses(&processes);
getUserCommand(&command);
//printCommand(&command);
executeCommand(&command, &processes, &exitMethod);
waitBackground(&processes, &exitMethod);
freeCommand(&command);
};
return(0);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
* STRUCTURE D'UNE NODE
* La node contient un symbole (char) et une fréquence d'apparition dans le code
*/
typedef struct node_s{
char symbol;
int freq;
struct node_s* fg;
struct node_s* fd;
}node;
/*
* STRUCTURE DU TAS MIN
* int n permet de connaître le nombre d'arguments dans le tas
*/
typedef struct tas_s{
int max;
int n;
node** tab;
}tas;
#define TRUE 1
#define FALSE 0
/*
* PROTOTYPES DE FONCTIONS
*/
node* creer_node(int, char);
tas* init_tas(int);
int est_vide_tas(tas*);
int est_feuille(node*);
tas* saisie_alphabet();
tas* saisie_alphabet2();
void inserer_tas(tas*, node*);
node* supprimer_tas(tas*);
node* creer_arbre(tas*);
void imprimer_arbre(node*);
void imprimer_codes(node*, char*, int i);
void supprimer_arbre(node*);
void liberer_memoire_tas(tas*);
void codage_manuel();
void codage_fichier();
void afficher_tas(tas*);
tas* nombre_caractere_fichier(FILE*);
/*
* FONCTIONS
*/
/*
* Fonction permettant d'allouer la mémoire pour un node. les valeurs pour le caractère et la fréquence
* passées en paramètre sont ensuite attribuées aux variables contenues dans le node (char symbol et int freq)
*/
node* creer_node(int f, char s){
// Allocation de mémoire
node* res = (node*)malloc(sizeof(node));
res->freq = f;
res->symbol = s;
res->fd = NULL;
res->fg = NULL;
return res;
}
/*
* Cette fonction permet d'afficher de manière claire tous les éléments contenus dans
* le tableau de *node du tas.
*/
void afficher_tas(tas* T){
// Si on veut afficher un tas ne contenant aucun élément
if(est_vide_tas(T)){
printf("Le tas est vide.\n");
return ;
}
int i = 0;
// affichage de tous les éléments du tas
while(i <= T->n-1){
printf(" %d : (%c %d) \n", i, T->tab[i]->symbol, T->tab[i]->freq);
i++;
}
printf("\n");
}
/*
* Fonction permettant d'initialiser un pointeur sur un tas en allouant exactement la quantité de
* mémoire requise.
*/
tas* init_tas(int nombre){
// Allocation du tas
tas* res = (tas*)malloc(sizeof(tas));
res->max = nombre;
res->n = 0;
// Allocation du tableau de pointeurs de node contenant le nombre "nombre" passé en paramètre de *node
res->tab = (node**)malloc(nombre*sizeof(node*));
return res;
}
/*
* Fonction permettant de tester si un tas est vide, c'est à dire que le nombre d'élément T->n est 0
*/
int est_vide_tas(tas* T){
if(T->n == 0){
return TRUE;
}
// Si le tas n'est pas vide
return FALSE;
}
/*
* Fonction permettant de tester si un node est une feuille
*/
int est_feuille(node* A){
if((A->fd == NULL) && (A->fg == NULL)){
return TRUE;
}
// Si ce n'est pas une feuille
return FALSE;
}
/*
* Cette fonction récursive permet d'imprimer l'arbre de manière infixe, c'est à dire qu'on va à
* gauche, ensuite on effectue le traitement pour ensuite aller à droite
*/
void imprimer_arbre(node* A){
// Tant que le node n'est pas nul on effectue les instructions dans le bloc ci dessous
if(A != NULL){
imprimer_arbre(A->fg);
// TRAITEMENT INFIXE
if(est_feuille(A)){
printf(" ( %c : %d ) ", A->symbol, A->freq);
}
else if(!est_feuille(A)){
printf(" ( %d ) ", A->freq);
}
imprimer_arbre(A->fd);
}
}
/*
* Fonction permettant d'inserer un node dans un tas min. L'insertion respecte les caractéristiques
* du tas min.
*/
void inserer_tas(tas* T, node* A){
// initialisation de variable temporaire
node* temp;
// On récupère le nombre d'éléments
int i = T->n;
// On insère l'élément à ajouter à la fin du tas
T->tab[i] = A;
/*
* Tant que le père du node que l'on ajoute a un fréquence plus élevée que celle de celui-ci,
* on réalise un swap entre le père en (i-1)/2 et le node que l'on ajoute
*/
while(T->tab[i]->freq < T->tab[(i-1)/2]->freq){
temp = T->tab[i];
T->tab[i] = T->tab[(i-1)/2];
T->tab[(i-1)/2] = temp;
i = ((i-1)/2);
}
// On incrémente le nombre d'éléments contenus dans le tas
T->n++;
}
/*
* Cette fonction permet de récuperer les éléments du tas min pour ensuite contruire l'arbre
* qui permettra de coder les éléments. Le pseudo code fourni nous à aidé à coder cette fonction
*/
node* creer_arbre(tas* T){
// On récupère le nombre d'arguments
int C = T->n-1;
// On crée un nouveau tas avec le nombre d'arguments
tas* F = init_tas(C);
// Variable permettant de créer l'arbre en ajoutant les fils droits et gauches
node* tempGauche;
node* tempDroit;
// Insertion dans le nouveau tas
for(int j = 1; j <= C; j++){
inserer_tas(F, T->tab[j]);
}
for(int i = 1; i <= C; i++){
// On crée un noeud interne ayant ' ' pour caractère
node* racine = creer_node(0, ' ');
// On récupère les valeurs à insérer à gauche et à droite du noeud interne
tempGauche = supprimer_tas(T);
tempDroit = supprimer_tas(T);
// On attribut les noeuds au noeud interne/ à la racine
racine->fg = tempGauche;
racine->fd = tempDroit;
// On additionne les fréquences
racine->freq = tempDroit->freq + tempGauche->freq;
// On insére ensuite la racine/ le noeud interne dans l'arbre et affiche le tas
inserer_tas(T, racine);
afficher_tas(T);
}
// On renvoit la racine de l'arbre
return T->tab[0];
}
/*
* Fonction permettant de supprimer le plus petit élément du tas, qui est à la racine
* Le tas est ensuite retrié pour que le plus petit élément soit de nouveau au début
*/
node* supprimer_tas(tas* T)
{
// Si le tas n'est pas vide
if(est_vide_tas(T)){
printf("\nLe tas est vide, impossible de supprimer un élément\n");
return NULL;
}
// Création de deux variables temporaires
node* temp = T->tab[0];
node* temp2;
// Le dernier element du tableau est mis à la fin
T->tab[0] = T->tab[T->n-1];
// Décrémente le nombre d'éléments
T->n--;
int n = T->n;
int succes = TRUE;
int k;
// compteiur
int i = 0;
while( (2*i + 1 < n ) && succes)
{
if(2*i + 2 < n)
{
if(T->tab[2*i + 1]->freq <= T->tab[2*i + 2]->freq)
k = 2*i + 1;
else
k = 2*i + 2;
}
else
k = 2*i + 1;
if(T->tab[i]->freq > T->tab[k]->freq)
{
// Réalisation du swap
temp2 = T->tab[i];
T->tab[i] = T->tab[k];
T->tab[k] = temp2;
i=k;
}
else
succes = FALSE;
}
return temp;
}
/*
* Cette fonction nous permet de savoir si le caractère que nous avons entré existe déja dans le tas
*/
int existe(tas* T, char c){
for(int i = 0; i < T->n; i++){
// Si le caractère est déjà présent, on renvoie l'indice d'où il se trouve
if(c == T->tab[i]->symbol){
return i;
}
}
// Sinon on return -1
return -1;
}
/*
* Fonction permettant à l'utilisateur de choisir le nombre de caractères qu'il veut
* Cette fonction va également lui permettre d'entrer un par un les caractères et leurs
* fréquence qui seront insérés un à un dans le tas
*/
tas* saisie_alphabet2(){
printf("\nVous avez choisis de prendre en compte les caractères identiques\n\n");
int nombre_elements;
char carac;
int frequence;
int indice;
printf("Combien de caractères différents contient votre code ? : \n");
scanf("%d", &nombre_elements);
node* temp; // node qui sera utiliser pour inserer les données dans le tas
tas* T = init_tas(nombre_elements);
for(int i = 0; i < nombre_elements; i++){
// Tant que le caractère n'est pas une lettre minuscule entre a et z
do{
printf("%d caractere : \n", i+1);
scanf(" %c", &carac);
}while(carac < 97 || carac > 122);
// Tant que la fréquence entrée est inférieur à 0
do{
printf("frequence du %d caractère : ", i+1);
scanf("%d", &frequence);
}while(frequence <= 0);
indice = existe(T, carac);
if(indice >= 0){
T->tab[indice]->freq = frequence + T->tab[indice]->freq;
}
else{
// On crée un node avec la fréquence et le caractère choisi
temp = creer_node(frequence, carac);
// On insére le node dans le tas
inserer_tas(T, temp);
}
}
printf("\n");
// On retourne le tas
return T;
}
/*
* Fonction permettant à l'utilisateur de choisir le nombre de caractères qu'il veut
* Cette fonction va également lui permettre d'entrer un par un les caractères et leurs
* fréquence qui seront insérés un à un dans le tas
*/
tas* saisie_alphabet(){
printf("\nVous avez choisis de ne pas prendre en compte les caractères identiques\n\n");
int nombre_elements;
char carac;
int frequence;
printf("Combien de caractères différents contient votre code ? : \n");
scanf("%d", &nombre_elements);
node* temp; // node qui sera utiliser pour inserer les données dans le tas
tas* new = init_tas(nombre_elements);
for(int i = 0; i < nombre_elements; i++){
// Tant que le caractère n'est pas une lettre minuscule entre a et z
do{
printf("%d caractere : \n", i+1);
scanf(" %c", &carac);
}while((carac < 97 || carac > 122));
// Tant que la fréquence entrée est inférieur à 0
do{
printf("frequence du %d caractère : ", i+1);
scanf("%d", &frequence);
}while(frequence <= 0);
// On crée un node avec la fréquence et le caractère choisi
temp = creer_node(frequence, carac);
// On insére le node dans le tas
inserer_tas(new, temp);
}
printf("\n");
// On retourne le tas
return new;
}
/*
* Fonction récursive permettant de parcourir l'arbre et de coder chaque caractère entrés par l'utilisateur
* Lorsque que l'on visite le fils gauche on ajoute 0 à la chaine de caractère, 1 quand on visite le fils droit
*/
void imprimer_codes(node* A, char* string, int i){
if(A != NULL){
// TRAITEMENT PREFIXE
if(est_feuille(A)){
string[i] = '\0';
printf("%c = %s ; frequence = %d\n",A->symbol, string, A->freq);
}
// Va à gauche si possible et ajoute 1 à string
if(A->fg != NULL){
string[i] = '0';
imprimer_codes(A->fg, string, i+1);
}
// Va à droite si possible et ajoute 0 à string
if(A->fd != NULL){
string[i] = '1';
imprimer_codes(A->fd, string, i+1);
}
}
}
/*
* Fonction récursive permettant de libérer les cases mémoire allouées pour créer l'arbre
*/
void supprimer_arbre(node* A){
if(A != NULL){
supprimer_arbre(A->fg);
supprimer_arbre(A->fd);
// TRAITEMENT POSTFIXE
free(A);
}
}
/*
* Fonction récursive permettant de libérer un tas allouée, on supprimer l'arbre crée avec ce tas
* puis on libère le tableau et ensuite le tas
*/
void liberer_memoire_tas(tas* T){
// On supprime tous les éléments du tas
for(int i = T->n-1; i > 0; i--){
free(T->tab[i]);
}
// On supprime tous les éléments de l'arbre car la racine de l'arbre est également le premier élément
supprimer_arbre(T->tab[0]);
// Suppression du tableau
free(T->tab);
free(T);
// free le tas
}
/*
* Cette fonction va récuperer tous les caractères, les mettre dans un tableau puis les inserer dans le tas de manière
* ordonnée
*/
tas* nombre_caractere_fichier(FILE* stream){
// Tab qui va récuperer tous les éléments
node** tab = (node**)malloc(sizeof(node)*26);
// Tas que l'on va renvoyer
tas* T;
char symbole;
int succes = FALSE;
int distinct = 0;
fseek(stream, 0, SEEK_SET);
printf("Voici la chaine de caractère présente dans le fichier : \n\n");
// Je préfère récupérer le nombre de caractère tout d'abord
int n = fseek(stream, 0, SEEK_END);
n = ftell(stream);
printf("Ce fichier contient %ld caractères au total\n\n", ftell(stream));
fseek(stream, 0, SEEK_SET);
// Tant qu'il y a des caractères
while((symbole = fgetc(stream)) != EOF){
succes = FALSE;
printf("%c", symbole);
// On récupère les éléments et les mets dans le tableau
if(tab[0] == NULL){
tab[0] = creer_node(1, symbole);
distinct++;
}
else{
for(int i = 0; tab[i] != NULL && succes == FALSE; i++){
if(tab[i]->symbol == symbole){
tab[i]->freq+=1;
succes = TRUE;
}
else if(tab[i+1] == NULL){
tab[i+1] = creer_node(1, symbole);
distinct++;
succes = TRUE;
}
}
}
}
// Init le tas avec exactement le bon nombre d'élément
T = init_tas(distinct);
printf("\n\n");
printf("Le fichier contient %d caractères distincts.\n\n", distinct);
// On insère un à un dans le tas
for(int i = 0; i < distinct; i++){
inserer_tas(T, tab[i]);
}
printf("\n\nFin de l'insertion\n\n");
afficher_tas(T);
return T;
}
/*
* Fonction principale permettant l'ouverture du fichier, elle fait appelle a la fonction qui va récuperer les
* caractères et les mettre dans le tas, le tas va être récupéré ici et l'arbre sera crée
*/
void codage_fichier(){
FILE* stream = NULL;
// Déclaration pour ouverture de fichiers
char nom_fich[50];
char nom_final[100] = "fichiers/";
char* fich = (char*)malloc(150*sizeof(char));
// FORMALITE
printf("\nQuel fichier souhaitez vous ouvrir ? (Le fichier doit être contenu dans le répertoire fichiers)\n\n");
scanf("%s", nom_fich);
// On concat pour avoir le chemin et aller au fichier
fich = strcat(nom_final, nom_fich);
printf("\nVous avez choisi l'ouverture du fichier %s .\n", fich);
printf("\nOuverture du fichier \n\n");
// Ouverture du fichier
stream = fopen(fich, "r");
// Si le fichier existe et s'ouvre
if(stream != NULL){
tas* T = nombre_caractere_fichier(stream);
// Récupération de la racine de l'arbre
node* racine = creer_arbre(T);
// Initialisation de la chaîne de caractères permettant de récupérer les fréquences des caractères
char* str = (char*)malloc(T->n+1*sizeof(char));
afficher_tas(T);
printf("----------------------------------------------------------------------------\n\n");
printf(" IMPRIMER ARBRE \n\n");
// L'affichage du tas se fait de manière infixe
imprimer_arbre(racine);
printf("\n\n");
printf("----------------------------------------------------------------------------\n\n");
printf(" IMPRIMER CODES \n\n");
// On affiche les caractères et leurs fréquences
imprimer_codes(racine, str, 0);
printf("\n\n");
// On libère la chaîne et ferme le fichier
liberer_memoire_tas(T);
free(str);
fclose(stream);
}
// Si le fichier ne s'ouvre pas
else if(stream == NULL){
printf("\n\nERREUR LORS DE L'OUVERTURE DU FICHIER OU FICHIER INEXISTANT\n\n");
}
}
/*
* Si l'utilisateur choisit le codage manuel, cette fonction va permettre de réaliser
* l'intégralité des opérations afin de créer l'arbre et
* de générer le code des caractères entrés par l'utilisteur
*/
void codage_manuel(){
int choix;
tas* Tas;
do{
printf("Quelle type d'insertion voulez-vous effectuer ?\n\n");
printf("1) Insertion sans prise en compte de plusieurs occurences du même élément\n");
printf("2) Insertion avec la prise en compte des éléments distincts\n\n");
scanf("%d", &choix);
printf("\n");
}while(choix > 2 || choix < 1);
// On récupère les caractères et leurs fréquence
if(choix == 1){
Tas = saisie_alphabet();
}
else{
Tas = saisie_alphabet2();
}
// Premier affichage du tas
afficher_tas(Tas);
// Récupération de la racine de l'arbre
node* racine = creer_arbre(Tas);
// Initialisation de la chaîne de caractères permettant de récupérer les fréquences des caractères
char* str = (char*)malloc(Tas->n+1*sizeof(char));
afficher_tas(Tas);
printf("----------------------------------------------------------------------------\n\n");
printf(" IMPRIMER ARBRE \n\n");
// L'affichage du tas se fait de manière infixe
imprimer_arbre(racine);
printf("\n\n");
printf("----------------------------------------------------------------------------\n\n");
printf(" IMPRIMER CODES \n\n");
// On affiche les caractères et leurs fréquences
imprimer_codes(racine, str, 0);
printf("\n\n");
// On libère la mémoire allouée pour la chaîne de caractère
free(str);
// On libère le tas qui va également libérer l'arbre
liberer_memoire_tas(Tas);
}
/*
* FONCTION MAIN
* Lance le programme et continue tant que l'utilisateur ne choisit pas de quitter
*/
int main(){
// Variable permettant à l'utilisateur de choisir ce qu'il veut faire
int choix;
int exit = FALSE;
printf("\n--------------------------------------------------------------------------------\n");
printf("\nBIENVENUE DANS LE PROGRAMME DE CODAGE REALISE PAR THOMAS CIMAN ET ARTHUR LEGOFF\n");
printf("\n--------------------------------------------------------------------------------\n");
// Le programme continu tant que l'utilisateur ne choisit pas de quitter
while(exit == FALSE){
do{
printf("\n\t\t\tQue voulez-vous faire ?\n\n");
printf("1) Codage par saisie manuelle\n");
printf("2) Codage par fichier\n");
printf("3) Quitter\n\n");
scanf("%d", &choix);
if(choix == 1){
printf("\n\t\t\tVOUS AVEZ CHOISI LE CODAGE MANUEL\n\n\n");
codage_manuel();
printf("\n\n\n\n");
}
if(choix == 2){
printf("\n\t\t\tVOUS AVEZ CHOISI LE CODAGE PAR FICHIER\n\n\n");
codage_fichier();
printf("\n\n\n\n");
}
if(choix == 3){
printf("\nNous vous remercions d'avoir utilisé notre programme\n\n");
exit = TRUE;
}
// Le panel de choix que peut réaliser l'utilisateur est compris entre 1 et 3 inclus
}while((choix > 3) || (choix < 1));
}
return EXIT_SUCCESS;
}
/*
* RAPPORT
*/
/*
Nous avons implémenté les principales fonctions demandées. Nous avons également crée un script compiler.bash afin de
rendre plus rapide et pratique la compilation et l'execution du programme.
La fonction alphabet2 a été implémenté afin de gérer l'insertion de plusieurs caractères identiques mais l'utilisateur
garde le choix de ne pas utiliser ce mode d'insertion, plus gourmand
La fonction existe() va renvoyer l'indice ou se trouve le caractère déjà présent dans le tableau
La fonction codage_manuel() va être lancé depuis le main et va permettre à l'utilisateur de rentrer manuellement les
caractères et leurs fréquence tout en gardant le choix du mode d'insertion
La fonction codage_fichier() va permettre à l'utilisateur de récupérer les codes de caractères dans un fichier et
de les inserer dans un tas min à l'aide de la fonction nombre_caractere_fichier()
Un amélioration possible serait de recoder en binaire le fichier en entré dans un autre fichier
Pour cela il faudrait réecrir un équivalent d'imprimer code qui retourne chaque chaine de caractère
La fonction afficher_tas(tas*) permet d'afficher le tas dans toutes les étapes de la création. Cela nous permet de
contrôler de vérifier ce qu'il se passe à chaque étape (et en plus c'est jolie)
Nous nous sommes posé beaucoup de questions lors de la réalisation de ce projet par rapport à la complexité de certaines
fonction, nous avons notamment rencontré certains dilemmes comme le choix entre allouer de la mémoire peut-être inutile
ou augmenter la complexité de notre programme mais en controlant les allocation de mémoire.
Nous aimerions vous en faire part de manière plus approfondie lors de la soutenance de projet
*/
|
C
|
#include <stdio.h> //printf(). scanf(), fopen(), fscanf(), fprintf() 등 실행에 주가 되는 함수를 위함
#include <string.h> //체스판과 데이터를 저장하고 변경하는 과정에 있어서 필요한 strcpy(), strcat(), strcmp(), strlen()를 위함
#include <stdlib.h> //system("clear")를 위함
#include <termio.h> // getch() 함수를 정의하기 위해 필요한 tcgetattr(), ICANON, ECHO, VMIN, VTIME, tcsetattr(), TCSAFLUSH를 위함
char board[17][34]; //실행중인 체스판
char backupBoard[17][34]; //되돌리기 위한 백그라운드 저장용 체스판
char backupCheckBoard[17][34]; //check여부 확인 시 사용할 체스판
char boardFile[100] = "C:\\Users\\SoHyun Kim\\Desktop\\chess.txt"; // 새 게임용 체스판
char boardSaveFile[100] = "C:\\Users\\SoHyun Kim\\Desktop\\chess_save.txt"; // 저장된 체스판
char deadPiece1[20] = {""}, deadPiece2[20] = {""}; // 죽은 말을 저장할 배열
static int startPlayer; // 시작하는 player 확인용
static int winner; // 승리한 player 확인용 (1 : player 1 승, 2 : player 2 승)
static int countStar = 0; // 선택한 말이 움직일 수 있는 위치의 수, countStar == 0 -> 다시 말 선택
static int kingX1 = 14, kingY1 = 1; // player 1의 King 좌표 (check여부 확인시 이용)
static int kingX2 = 14, kingY2 = 15; // player 2의 King 좌표 (check여부 확인시 이용)
static int kingX3 = -1, kingY3 = -1; // King을 이동시킬 때 check 확인 좌표
static int longCastlingCheck[2] = {0,0}, shortCastlingCheck[2] = {0,0}; // 캐슬링 가능 여부 확인용
static int enPassant1[4]= {-1, -1, -1, -1}, enPassant2[4] = {-1, -1, -1, -1}; // 앙파상 가능 위치 확인용 좌표
void LoadChessGame(int); // 게임을 시작하기 전 필요한 과정
void PrintRule(void); // 도움말 출력
void PrintBoard(void); // 현재 판 출력
void BackupBoard(void); // 되돌리기용 판 저장
void BackupCheckBoard(void); // 되돌리기용 판 저장
void ReturnCheckBoard(void); // 판 되돌리기
void SaveGame(void); // 저장
void DeleteStar(void); // *표시 원래(. 또는 말)로 돌리기
void MovePiece1(void); // Player1 이동
void MovePiece2(void); // Player2 이동
void Pawn(int, int); // P 선택시 이동 가능 위치 *로 표시
void Rook(int, int); // R 선택시 이동 가능 위치 *로 표시
void Knight(int, int); // N 선택시 이동 가능 위치 *로 표시
void Bishop(int, int); // B 선택시 이동 가능 위치 *로 표시
void Queen(int, int); // Q 선택시 이동 가능 위치 *로 표시
void King(int, int); // K 선택시 이동 가능 위치 *로 표시
int Check(int, int); // check 여부 확인
int Checkmate(int); // 종료 조건
void Promotion(int, int, int, int); // 프로모션 (특수룰)
void Castling(int); // 캐슬링 (특수룰)
void Clear(void);
int getch(void);
void ChangePiece(int, int, char, char, char);
int main() {
int menu = 0; // 메뉴 선택용 변수
while (1) {
Clear(); // 화면정리
if (winner == 1 || winner == 2) {
printf("\nPlayer %d WIN!\n\n", winner);
winner = 0;
} // 이전 판 승리자 표시 (처음 게임 실행 시 프린트 되지 않음)
printf("+---- MENU ----+\n| 1. 새 게임 |\n| 2. 이어하기 |\n| 3. 도움말 |\n| 4. 종료 |\n+--------------+\n");
printf("Meun Number : ");
scanf("%d", &menu);
Clear(); // 메뉴 선택
if (menu == 1 || menu == 2)
{
if (menu == 1) { LoadChessGame(1); }
else { LoadChessGame(2); }
PrintRule();
PrintBoard(); // 새 게임 판을 로드하여 프린트
while (1)
{
if (startPlayer == 1)
{
MovePiece1(); // player 1 이동
if (winner == 1 || winner == 2)
{ // 만약 king이 잡히거나 checkmate 상태가 되거나 기권을 하면 게임 종료
break;
}
else
{
PrintBoard(); // 이동 후 변경된 체스판을 정리된 화면에 프린트
startPlayer = 2;
}
}
if (startPlayer == 2)
{
MovePiece2(); // player 2 이동
if (winner == 1 || winner == 2)
{ // 만약 king이 잡히거나 checkmate 상태가 되거나 기권을 하면 게임 종료
break;
}
else
{
PrintBoard(); // 이동 후 변경된 체스판을 정리된 화면에 프린트
startPlayer = 1;
}
}
}
}
else if (menu == 3) { PrintRule(); }
else if (menu == 4) {
printf("게임을 종료합니다. 감사합니다.");
break; // while문 종료
}
else continue;
}
return 0;
}
/**
함수 이름 : Clear
함수 설명 : 화면을 깨끗하게 정리해준다.
**/
void Clear()
{ system("clear"); }
/**
함수 이름 : getch
함수 설명 : 도움말 출력 시 사용자가 페이지를 넘기기 위해 누르는 엔터를 입력받기 위함 (getch 구현)
**/
int getch()
{
int ch;
struct termios buf, save;
tcgetattr(0, &save); // 현재 터미널 설정 읽음
buf = save;
buf.c_lflag &= ~(ICANON | ECHO); // CANONICAL과 ECHO 끔
buf.c_cc[VMIN] = 1; // 최소 입력 문자 수를 1로 설정
buf.c_cc[VTIME] = 0; // 최소 읽기 대기 시간을 0으로 설정
tcsetattr(0, TCSAFLUSH, &buf); // 터미널에 설정 입력
ch = getchar(); // 키보드 입력 읽음
tcsetattr(0, TCSAFLUSH, &save); // 원래의 설정으로 복구
return ch;
}
/**
함수 이름 : LoadChessGame
함수 설명 : 게임을 시작하기 위해 필요한 과정을 수행한다. (텍스트 파일에서 체스판을 읽어 지정된 배열에 정보를 저장한다)
파라미터 이름 : mode
파라미터 설명
mode : 1이면 새 게임, 2면 저장된 게임
**/
void LoadChessGame(int mode )
{
FILE *fp = NULL; // 체스판이 저장된 텍스트 파일을 저장할 공간 선언
char input[50]; // 파일 속 문자열을 읽어서 배열에 저장하기 위한 중간 문자열
int I = -1; // while문 사용
if (mode == 1) { fp = fopen(boardFile, "r"); } // 새 게임
else
{ // 저장된 게임용 텍스트파일 실행
fp = fopen(boardSaveFile, "r");
if (fp == NULL)
{ // 만약 저장된 게임(체스판)이 없으면 새 게임 실행
fp = fopen(boardFile, "r");
}
}
while (fscanf(fp, "%s", input) != EOF)
{ // 파일이 끝날 때까지 한줄 씩 읽어서 input에 저장
if (I == -1)
{
strcpy(deadPiece2, input);
I++;
}
else if (I >= 0 && I < 17)
{
strcpy(board[I], input); // input에 저장된 문자열 체스판 배열 (board)에 저장
I++; // 다음 줄을 읽고 저장하기 위함
}
else if (I == 17)
{
strcpy(deadPiece1, input);
I++;
}
else if (I == 18)
{
startPlayer = input[0] - 48;
longCastlingCheck[0] = input[2] - 48;
longCastlingCheck[1] = input[4] - 48;
shortCastlingCheck[0] = input[6] - 48;
shortCastlingCheck[1] = input[8] - 48;
}
}
fclose(fp); // 파일 닫기
}
/**
함수 이름 : PrintRule
함수 설명 : 게임진행 방법과 규칙을 출력한다.
참조 함수들 : getch() - 출력 후 메뉴로 돌아가기 위해 엔터 입력, Clear() - 출력 전 화면 정리
**/
void PrintRule()
{
getch();
printf("\n게임 진행 방법\n");
printf("\n< > :Player 1, [ ] : Player 2\n");
printf("\n1. 이동 시키길 원하는 말의 좌표를 입력한다.");
printf("\n2. * 표시(이동 가능 공간) 중 원하는 곳의 좌표를 입력한다.\n\n\n(엔터를 눌러주세요)");
getch(); // 사용자가 Enter 누르면 종료
Clear();
}
/**
함수 이름 : PrintBoard
함수 설명 : 배열에 저장된 체스판 출력
**/
void PrintBoard(void)
{ // 체스판 출력
int pnum = 0;
Clear();
printf("%s\n", deadPiece2); // player1이 잡은 말 출력
printf(" A B C D E F G H\n"); // 열 표시
for (int i = 0; i < 17; i++)
{ // 체스판이 저장된 배열(board)을 한줄 씩 출력
if (i % 2 == 0)
{
printf(" %s\n", board[i]);
} // 행 표시
else
{
printf("%d %s\n", pnum, board[i]);
pnum++;
}
}
printf("%s\n", deadPiece1); // player2가 잡은 말 출력
}
/**
함수 이름 : BackupBoard
함수 설명 : 현재 플레이 중인 게임판을 백업용 게임판에 저장한다.
**/
void BackupBoard(void)
{ // 백그라운드 체스판에 현재 판 복사
for (int i = 0; i < 17; i++)
{ strcpy(backupBoard[i], board[i]); } // 한줄 씩 board를 backupBoard에 복사한다
}
/**
함수 이름 : BackupCheckBoard
함수 설명 : 체크여부 확인시 임의로 이동시킨 말을 원래 위치로 되돌려놓기 위해 게임판을 백업한다.
**/
void BackupCheckBoard(void)
{ // 체크여부확인 체스판에 현재 판 복사
for (int i = 0; i < 17; i++)
{ strcpy(backupCheckBoard[i], board[i]); }
}
/**
함수 이름 : ReturnCheckBoard
함수 설명 : 체크여부 확인 후 게임판을 원상복귀 시킨다.
**/
void ReturnCheckBoard(void)
{ // 현재 판에 체크여부확인 체스판 복사
for (int i = 0; i < 17; i++)
{ strcpy(board[i], backupCheckBoard[i]); }
}
/**
함수 이름 : DeleteStar
함수 설명 : 이동 가능 위치를 표시를 위해 사용한 '*'을 말 이동 이후 원상복귀 시킨다.
**/
void DeleteStar(void)
{ // 이동 후 이동 가능 여부 체크했던 *표시 원래대로 돌려놓음
char Back; // 돌려놓을 문자 저장용 변수
for (int i = 0; i < 17; i++)
{
for (int j = 0; j < 49; j++)
{
if (board[i][j] == '*')
{ board[i][j] = backupBoard[i][j]; } // 모든 판을 체크하여 *표시를 backupBoard에 저장된 원래 문자로 돌려놓음
}
}
}
/**
함수 이름 : ChangePiece
함수 설명 : 말을 이동시킨다.
파라미터 이름 : y, x, one, two, three
파라미터 설명
y, x : 이동시킬 말의 y, x좌표
one, two, three : x좌표를 중심으로 바꿀 3개의 문자
**/
void ChangePiece(int y, int x, char one, char two, char three) {
board[y][x-1] = one;
board[y][x] = two;
board[y][x+1] = three;
}
/**
함수 이름 : MovePiece1
함수 설명 : A - player1이 말을 움직이기 전 체크메이트 여부를 확인하여 체크메이트인 경우 패배로 인지하여 게임을 종료한다.
B - player1이 이동을 원하는 말의 좌표를 입력받는다.
(SAVE 입력시 현재 게임 상황을 저장, GG 입력시 기권패 처리하여 게임을 종료한다.)
C - 입력 받은 문자열을 각각 열과 행의 인덱스 번호로 변환한다.
(만약 입력받은 위치에 상대방의 말이 있거나 빈 공간인 경우 이동시킬 말의 좌표를 다시 입력받는다.)
D - 선택한 말의 종류에 따라 정의된 함수를 이용하여 이동 가능한 위치를 표시한다.
E - 이동이 가능한 위치 중 이동 후 체크 상태가 되는 곳은 이동을 제한한다.
F - 이동 가능한 위치가 없다면 이동시킬 말의 좌표를 다시 입력받는다.
G - 이동 시킬 위치의 좌표를 입력받아 이동가능 여부를 확인한 후 이동시키거나 좌표를 다시 입력받는다.
(상대방의 말을 잡은 경우 해당 배열에 정보를 저장하여 이후 출력시킬 수 있도록 한다.)
참조 함수들 : Pawn, Rook, King, Knight, Bishop, Queen - 각 말을 선택했을 때 이동 가능한 위치 *표시
Castling, Check - 캐슬링 가능여부나 체크여부 확인
ChangePiece - 말 이동시키기
**/
void MovePiece1(void)
{ // player 1 이동함수
char before[5], after[3]; // 이동시킬 말, 위치 입력받을 변수 ( save나 exit 입력받아야하는 경우가 있어서 크기 5 )
int nowY = 0, nowX = 0, afterY = 0, afterX = 0; // 이동시킬 말의 행, 열, 이동시킬 위치의 행, 열
int didCastling = 0, didEnPassant = 0; // 캐슬링 할 경우 1
BackupBoard();
// 이동시킬 말 입력받아 이동할 수 있는 경로 *로 표시하기
while (1)
{
/** A **/
if (Checkmate(1) == 0)
{ // 만약 player1이 움직일 수 있는 말이 없는 경우 player2 승리, 게임 종료
winner = 2;
break;
}
else
{
for (int k = 0; k < 17; k++)
{
strcpy(board[k], backupBoard[k]);
}
} // 아니면 다시 실행중인 판 복구
/** B **/
printf("\n< Player 1 >\n(SAVE: save game, GG: give up)\nWhat? : ");
scanf("%s", before);
if (strcmp(before, "SAVE") == 0)
{ // 사용자가 save입력 시 현재 체스판 텍스트 파일에 저장
SaveGame();
printf("S A V E . . . !\n");
continue;
}
else if (strcmp(before, "GG") == 0)
{ // 사용자가 GG입력 시 기권패
winner += 2;
break;
}
else if (strlen(before) == 2)
{ /** C **/
nowY = 2 * (before[1] - 48) + 1; // 입력 받은 숫자(문자열 변수에 저장) 아스키 코드를 이용해서 행 인덱스로 변경
nowX = 4 * (before[0] - 64) - 2; // 입력 받은 대문자 알파벳 아스키 코드를 이용해서 열 인덱스로 변경
if ( (nowX < 0 || nowX > 32) || (nowY < 0 || nowY > 16) )
{
printf("again!\n");
continue;
}
if (board[nowY][(nowX - 1)] == '[')
{
printf("It is not yours\n\n");
continue;
} // 상대방 말 선택시 다시 선택
if (board[nowY][nowX] == '.')
{
printf("There are nothing\n\n");
continue;
} // 비어있는 위치 선택시 다시 선택
else
{ // 선택한 말의 종류에 따라 이동 가능한 곳 *으로 표시
switch (board[nowY][nowX])
{ /** D **/
case 'P':
{ Pawn(nowY, nowX); break; }
case 'R':
{ Rook(nowY, nowX); break; }
case 'N':
{ Knight(nowY, nowX); break;}
case 'B':
{ Bishop(nowY, nowX); break; }
case 'Q':
{ Queen(nowY, nowX); break; }
case 'K':
{ King(nowY, nowX); Castling(1);
break;
}
}
/** E **/
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
BackupCheckBoard(); // 확인이 끝난 후 돌려놓을 판을 위해 저장해놓음 (백업용)
int checkx = -1, checky = -1; // 이동을 금지시킬 행과 열 인덱스 저장용
if (board[2 * i + 1][4 * j + 2] == '*')
{ // 이동 가능하다고 표시된 곳으로 이동시키기 (임시)
ChangePiece( 2*i+1, 4*j+2, '<', board[nowY][nowX], '>');
ChangePiece( nowY, nowX, '.', '.', '.');
DeleteStar();
if (board[2 * i + 1][4 * j + 2] != 'K')
{
if (Check(1, 0) == 1)
{
checkx = 4 * j + 2;
checky = 2 * i + 1;
} // check인 경우 좌표 저장
}
else
{
kingX3 = 4 * j + 2;
kingY3 = 2 * i + 1; // 움직일 말이 King이면 Check함수에서 이용할 변수값도 바꿔야 함
if (Check(1, 1) == 1)
{
checkx = 4 * j + 2;
checky = 2 * i + 1;
} // check인 경우 좌표 저장
}
ReturnCheckBoard(); //다시 현재 판으로 돌려놓음
if (checkx >= 0)
{ // 만약 check인 경우가 있어서 checkx, checky에 인덱스 값이 저장되어있으면 * -> . (이동 못함)
board[checky][checkx] = '.';
}
}
}
}
/** F **/
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (board[2 * i + 1][4 * j + 2] == '*')
{ countStar += 1; } // countStar >= 1 이면 이동 시킬 수 있다
}
}
if (countStar == 0)
{ // 이동시킬 수 있는 위치가 없으면 위치 다시 입력 받기
printf("You can not move that!\n\n");
continue;
}
else
{ // 이동 시킬 수 있는 위치가 있는 경우
countStar = 0; // 다음 이용을 위해 초기화
PrintBoard(); // 이동 가능 위치 표시된 체스판 출력
break;
}
}
}
else
{
printf("again\n");
PrintBoard();
continue;
}
}
/** G **/
while (1)
{
if (winner == 2) {break;} // 앞에서 exit을 입력받았거나 종료 조건이 만족된 경우 종료
printf("\n< Player 1 >\nWhere? : ");
scanf("%s", after);
if (strlen(after) == 2)
{
afterY = 2 * (after[1] - 48) + 1; // 입력 받은 숫자(문자열 변수에 저장) 아스키 코드를 이용해서 행 인덱스로 변경
afterX = 4 * (after[0] - 64) - 2; // 입력 받은 대문자 알파벳 아스키 코드를 이용해서 열 인덱스로 변경
Promotion(nowX, nowY, afterY, 1); // 특수룰
/**캐슬링 할 수 있는데 안하는 경우**/
if (board[afterY][afterX] != 'a' ) {
if (board[kingY1][kingX1 + 8] == 'a') {
ChangePiece(kingY1, kingX1 + 8, '.', '.', '.');
}
if (board[kingY1][kingX1 - 8] == 'a') {
ChangePiece(kingY1, kingX1 - 8, '.', '.', '.');
}
}
/**앙파상 할 수 있는데 안하는 경우**/
if (board[afterY][afterX] != 'n') {
if ( board[enPassant1[0]][enPassant1[1]] == 'n') {
ChangePiece(enPassant1[0], enPassant1[1], '.', '.', '.');
enPassant1[0] = enPassant1[2] = -1;
}
if ( board[enPassant1[2]][enPassant1[3]] == 'n') {
ChangePiece(enPassant1[2], enPassant1[3], '.', '.', '.');
enPassant1[2] = enPassant1[3] = -1;
}
}
/**캐슬링 하는 경우**/
if (board[afterY][afterX] == 'a') {
didCastling = 1;
ChangePiece(afterY, afterX, '.', '.', '.');
break;
}
/**앙파상 하는 경우**/
else if (board[afterY][afterX] == 'n') {
didEnPassant = 1;
DeleteStar();
break;
}
if (board[afterY][afterX] != '*')
{
printf("again\n");
continue;
} // 선택한 위치가 이동 불가능 한 위치면 다시 입력
if (board[afterY][(afterX - 1)] == '<')
{
printf("again\n");
continue;
} // 본인 말이 있는 위치 선택 시 다시 입력
else
{
DeleteStar();
break;
} // 이동할 위치 정해졌으니 *표시 모두 제거
}
else
{
printf("again\n");
PrintBoard();
continue;
}
}
if (winner != 2)
{ // 게임이 종료되는 경우가 아니면 실행
/**캐슬링 실행**/
if (didCastling == 1) { //longcastling
if (afterX == 22) {
ChangePiece(1, 18, '<', 'R', '>');
ChangePiece(1, 30, '.', '.', '.');
}
else if (afterX == 6) {
ChangePiece(1, 10, '<', 'R', '>');
ChangePiece(1, 2, '.', '.', '.');
}
DeleteStar();
}
/**앙파상 실행 시**/
if (didEnPassant == 1) {
strcat(deadPiece2, "[P]");
ChangePiece( afterY - 2, afterX, '.', '.', '.');
}
/**앙파상으로 먹을 수 있는 좌표 저장**/
if (board[nowY][nowX] == 'P' && afterY == nowY + 4) {
if (board[afterY][afterX+3] == '[' && board[afterY][afterX+4] == 'P') {
enPassant2[0] = afterY-2;
enPassant2[1] = afterX;
}
if (board[afterY][afterX-5] == '[' && board[afterY][afterX-4] == 'P') {
enPassant2[2] = afterY-2;
enPassant2[3] = afterX;
}
}
// 이동시킬 말이 King인 경우 변경될 좌표 저장 (for check확인)
if (board[nowY][nowX] == 'K')
{
kingX1 = afterY;
kingY1 = afterX;
longCastlingCheck[0] = shortCastlingCheck[0] = 1;
}
// 왕 잡으면 end
if (board[afterY][afterX] == 'K') {winner = 1;}
// 상대말 말을 잡은 경우 체스판 프린트시 표시
if (board[afterY][(afterX - 1)] == '[')
{
switch (backupBoard[afterY][afterX])
{ // "DIE-" 뒤에 이어서 저장 (strcat() 이용)
case 'P':
{ strcat(deadPiece2, "[P]"); break; }
case 'R':
{ strcat(deadPiece2, "[R]"); break; }
case 'B':
{ strcat(deadPiece2, "[B]"); break; }
case 'N':
{ strcat(deadPiece2, "[N]"); break; }
case 'Q':
{ strcat(deadPiece2, "[Q]"); break; }
}
}
// R 움직이면 그 이후 캐슬링 불가
if (board[nowY][nowX] == 'R' && nowX == 2) {
shortCastlingCheck[0] = 1;
}
else if (board[nowY][nowX] == 'R' && nowX == 30) {
longCastlingCheck[0] = 1;
}
// 자리 옮기기
ChangePiece(afterY, afterX, '<', board[nowY][nowX], '>');
ChangePiece(nowY, nowX, '.', '.', '.');
}
if ( board[enPassant1[0]][enPassant1[1]] == 'n' ) {
ChangePiece(enPassant1[0], enPassant1[1], '.', '.', '.');
enPassant1[0] = enPassant1[1] =-1;
}
if ( board[enPassant1[2]][enPassant1[3]] == 'n' ) {
ChangePiece(enPassant1[2], enPassant1[3], '.', '.', '.');
enPassant1[2] = enPassant1[3] = -1;
}
}
/**
함수 이름 : MovePiece2
함수 설명 : player2 차례에 실행시키며 MovePiece1과 실행방식이 동일하다.
참조 함수들 : Pawn, Rook, King, Knight, Bishop, Queen - 각 말을 선택했을 때 이동 가능한 위치 *표시
Castling, Check - 캐슬링 가능여부나 체크여부 확인
ChangePiece - 말 이동시키기
**/
void MovePiece2(void)
{ // player 2 이동함수
char before[5], after[3]; //이동시킬 말, 위치 입력받을 변수 (save나 exit 입력받아야하는 경우가 있어서 크기: 5)
int afterY = 0, afterX = 0, nowY = 0, nowX = 0; //이동시킬 말의 행, 열, 이동시킬 위치의 행, 열
int didCastling = 0, didEnPassant = 0;
BackupBoard();
// 이동시킬 말 입력받아 이동할 수 있는 경로 *로 표시하기
while (1)
{
if (Checkmate(2) == 0)
{
winner = 1;
break;
} // 만약 player2가 움직일 수 있는 말이 없는 경우 player1 승리, 게임 종료
for (int k = 0; k < 17; k++) { strcpy(board[k], backupBoard[k]); } // 아니면 다시 실행중인 판 복구
printf("\n[ Player 2 ]\n(SAVE: save game, GG: give up)\nWhat? : ");
scanf("%s", before);
if (strcmp(before, "SAVE") == 0)
{ // 사용자가 save입력 시 현재 체스판 텍스트 파일에 저장
SaveGame();
printf("S A V E . . . !\n");
continue;
}
else if (strcmp(before, "GG") == 0)
{ // 사용자가 exit입력 시 게임 종료 후 메뉴로 돌아감
winner += 1;
break;
}
else if (strlen(before) == 2)
{
nowY = 2 * (before[1] - 48) + 1; // 입력 받은 숫자(문자열 변수에 저장) 아스키 코드를 이용해서 행 인덱스로 변경
nowX = 4 * (before[0] - 64) - 2; // 입력 받은 대문자 알파벳 아스키 코드를 이용해서 열 인덱스로 변경
if ( (nowX < 0 || nowX > 32) || (nowY < 0 || nowY > 16) )
{
printf("again!\n");
continue;
}
if (board[nowY][(nowX - 1)] == '<')
{
printf("It is not yours\n\n");
continue;
} // 상대방 말 선택시 다시 선택
if (board[nowY][nowX] == '.')
{
printf("There are nothing\n\n");
continue;
} // 비어있는 위치 선택시 다시 선택
else
{
// 선택한 말의 종류에 따라 이동 가능한 곳 *으로 표시
switch (board[nowY][nowX])
{
case 'P':
{ Pawn(nowY, nowX); break; }
case 'R':
{ Rook(nowY, nowX); break; }
case 'N':
{ Knight(nowY, nowX); break; }
case 'B':
{ Bishop(nowY, nowX); break; }
case 'Q':
{ Queen(nowY, nowX); break; }
case 'K':
{ King(nowY, nowX); Castling(2);
shortCastlingCheck[1] = longCastlingCheck[1] = 1;
break;
}
}
// 이동 후 check 상태가 되는 곳은 .으로 변경
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
BackupCheckBoard(); // 확인이 끝난 후 돌려놓을 판을 위해 저장해놓음 (백업용)
int checkx = -1, checky = -1; // 이동을 금지시킬 행과 열 인덱스 저장용
if (board[2 * i + 1][4 * j + 2] == '*')
{ // 이동 가능하다고 표시된 곳으로 이동시키기 (임시)
ChangePiece( 2*i+1, 4*j+2, '[', board[nowY][nowX], ']');
ChangePiece( nowY, nowX, '.', '.', '.');
DeleteStar();
if (board[2 * i + 1][4 * j + 2] != 'K')
{
if (Check(2, 0) == 1)
{
checkx = 4 * j + 2;
checky = 2 * i + 1;
} // check인 경우 좌표 저장
}
else
{
kingX3 = 4 * j + 2;
kingY3 = 2 * i + 1; // 움직일 말이 King이면 Check함수에서 이용할 변수값도 바꿔야 함
if (Check(2, 1) == 1)
{
checkx = kingX3;
checky = kingY3;
} // check인 경우 좌표 저장
}
ReturnCheckBoard(); // 다시 현재 판으로 돌려놓음
if (checkx >= 0) { board[checky][checkx] = '.'; }
// 만약 check인 경우가 있어서 checkx, checky에 인덱스 값이 저장되어있으면 * -> . (이동 금지 시키기)
}
}
}
// 선택된 말이 움질일 수 있는 경로가 있는지 확인
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (board[2 * i + 1][4 * j + 2] == '*')
{countStar += 1;} // countStar >= 1 이면 이동 시킬 수 있다
}
}
if (countStar == 0)
{ // 이동시킬 수 있는 위치가 없으면 위치 다시 입력 받기
printf("You can not move that!\n");
continue;
}
else
{ // 이동 시킬 수 있는 위치가 있는 경우
countStar = 0; //다음 이용을 위해 초기화
PrintBoard(); // 이동 가능 위치 표시된 체스판 출력
break;
}
}
}
else
{
printf("again\n");
PrintBoard();
continue;
}
}
// 선택된 말 이동시킬 경로 입력받아 이동시키기
while (1)
{
if (winner == 1) {break;}// 앞에서 exit을 입력받았거나 종료 조건이 만족된 경우 종료
printf("\n[ Player 2 ]\nWhere? : ");
scanf("%s", after);
if (strlen(after) == 2)
{
afterY = 2 * (after[1] - 48) + 1; // 입력 받은 숫자(문자열 변수에 저장) 아스키 코드를 이용해서 행 인덱스로 변경
afterX = 4 * (after[0] - 64) - 2; // 입력 받은 대문자 알파벳 아스키 코드를 이용해서 열 인덱스로 변경
Promotion(nowX, nowY, afterY, 2);
/**캐슬링 할 수 있는데 안하는 경우**/
if (board[afterY][afterX] != 'a' ) {
if (board[kingY2][kingX2 + 8] == 'a') {
ChangePiece(kingY2, kingX2 + 8, '.', '.', '.');
}
if (board[kingY2][kingX2 - 8] == 'a') {
ChangePiece(kingY2, kingX2 - 8, '.', '.', '.');
}
}
/**앙파상 할 수 있는데 안하는 경우**/
if (board[afterY][afterX] != 'n') {
if ( board[enPassant2[0]][enPassant2[1]] == 'n') {
ChangePiece(enPassant2[0], enPassant2[1], '.', '.', '.');
enPassant2[0] = enPassant2[1] = -1;
}
if ( board[enPassant2[2]][enPassant2[3]] == 'n') {
ChangePiece(enPassant2[2], enPassant2[3], '.', '.', '.');
enPassant2[2] = enPassant2[3] = -1;
}
}
/**캐슬링 하는 경우**/
if (board[afterY][afterX] == 'a') {
didCastling = 1;
DeleteStar();
break;
}
/**앙파상 하는 경우**/
else if (board[afterY][afterX] == 'n') {
didEnPassant = 1;
DeleteStar();
break;
}
if (board[afterY][afterX] != '*')
{
printf("again\n");
continue;
} // 선택한 위치가 이동 불가능 한 위치면 다시 입력
if (board[afterY][(afterX - 1)] == '[')
{
printf("again\n");
continue;
} // 본인 말이 있는 위치 선택 시 다시 입력
else
{
DeleteStar();
break;
} // 이동할 위치 정해졌으니 *표시 모두 제거
}
else
{
printf("again\n");
PrintBoard();
continue;
}
}
if (winner != 1)
{ // 게임이 종료되는 경우가 아니면 실행
/**캐슬링 실행 시**/
if (didCastling == 1) {
if (afterX == 22) {
ChangePiece(15, 18, '[', 'R', ']');
ChangePiece( 15, 30, '.', '.', '.');
}
else if (afterX == 6) {
ChangePiece(15, 10, '[', 'R', ']');
ChangePiece( 15, 2, '.', '.', '.');
}
DeleteStar();
}
/**앙파상 실행 시**/
if (didEnPassant == 1) {
strcat(deadPiece1, "<P>");
ChangePiece( afterY + 2, afterX, '.', '.', '.');
}
/**앙파상으로 먹을 수 있는 좌표 저장**/
if (board[nowY][nowX] == 'P' && afterY == nowY - 4) {
if (board[afterY][afterX+3] == '<' && board[afterY][afterX+4] == 'P') {
enPassant1[0] = afterY + 2;
enPassant1[1] = afterX;
}
if (board[afterY][afterX-5] == '<' && board[afterY][afterX-4] == 'P') {
enPassant1[2] = afterY + 2;
enPassant1[3] = afterX;
}
}
// 이동시킬 말이 King인 경우 변경될 좌표 저장 (for check확인)
if (board[nowY][nowX] == 'K')
{
kingX2 = afterY;
kingY2 = afterX;
longCastlingCheck[1] = shortCastlingCheck[1] = 1;
}
// 왕 잡으면 end
if (board[afterY][afterX] == 'K') winner = 2;
// 자리 옮기기
if (board[afterY][(afterX - 1)] == '<')
{ // 상대말 말을 잡은 경우 체스판 프린트 시 표시
switch (backupBoard[afterY][afterX])
{ // "DIE-" 뒤에 이어서 저장 (strcat() 이용)
case 'P':
{ strcat(deadPiece1, "<P>"); break; }
case 'R':
{ strcat(deadPiece1, "<R>"); break; }
case 'B':
{ strcat(deadPiece1, "<B>"); break; }
case 'N':
{ strcat(deadPiece1, "<N>"); break; }
case 'Q':
{ strcat(deadPiece1, "<Q>"); break; }
}
}
/** R 움직이면 그 이후 캐슬링 불가 **/
if (board[nowY][nowX] == 'R' && nowX == 2) {
shortCastlingCheck[1] = 1;
}
else if (board[nowY][nowX] == 'R' && nowX == 30) {
longCastlingCheck[1] = 1;
}
// 위치 변경
ChangePiece(afterY, afterX, '[', board[nowY][nowX], ']');
ChangePiece(nowY, nowX, '.', '.', '.');
}
if ( board[enPassant2[0]][enPassant2[1]] == 'n' ) {
ChangePiece(enPassant2[0], enPassant2[1], '.', '.', '.');
enPassant2[0] = enPassant2[1] = -1;
}
if ( board[enPassant2[2]][enPassant2[3]] == 'n' ) {
ChangePiece(enPassant2[2], enPassant2[3], '.', '.', '.');
enPassant2[2] = enPassant2[3] = -1;
}
}
/**
함수 이름 : Pawn
함수 설명 : 이동시킬 말이 Pawn인 경우 이동 가능 위치에 '*'로 표시한다.
Pawn은 이동하려는 위치에 말이 존재하지 않을 경우 한 칸(처음 이동시키는 경우 두 칸)전진 가능하다.
대각선(한 칸 차이)에 상대방의 말이 있을 경우 그 위치로 이동하여 잡는 것이 가능하다.
파라미터 이름 : nowY, nowX
파라미터 설명
nowY : 이동시킬 pawn의 현재 y좌표
nowX : 이동시킬 pawn의 현재 x좌표
**/
void Pawn(int nowY, int nowX)
{ // Pawn 선택 시 이동 가능 위치 *로 표시
if (board[nowY][(nowX - 1)] == '<')
{ // player1의 경우
if (board[nowY + 2][nowX] == '.')
{ // Pawn은 앞 칸이 이어있는 경우 앞으로 한 칸 전진(행 인덱스 2 증가) 가능 하다
board[nowY + 2][nowX] = '*';
if (nowY == 3)
{ // 처음 이동 시키는 경우 두 칸 전진도 가능하다
board[nowY + 4][nowX] = '*';
}
}
if (board[nowY + 2][nowX - 4] != '.' && board[nowY + 2][nowX - 5] == '[')
{ // 한 칸 대각선에 상대말 말이 있는 경우 이동하여 잡는 것이 가능하다
board[nowY + 2][nowX - 4] = '*';
}
if (board[nowY + 2][nowX + 4] != '.' && board[nowY + 2][nowX + 5] == ']')
{ // 한 칸 대각선에 상대말 말이 있는 경우 이동하여 잡는 것이 가능하다
board[nowY + 2][nowX + 4] = '*';
}
/** 앙파상 **/
if (enPassant1[0] >= 0 && nowX == enPassant1[1] + 4 && nowY == enPassant1[0] + 2) {
ChangePiece(enPassant1[0], enPassant1[1], 'E', 'n', 'P');
}
if (enPassant1[2] >= 0 && nowX == enPassant1[3] - 4 && nowY == enPassant1[2] + 2) {
ChangePiece(enPassant1[2], enPassant1[3], 'E', 'n', 'P');
}
}
else
{ // player2의 경우
if (board[nowY - 2][nowX] == '.')
{ // Pawn은 앞 칸이 이어있는 경우 앞으로 한 칸 전진(행 인덱스 2 감소) 가능 하다
board[nowY - 2][nowX] = '*';
if (nowY == 13)
{
board[nowY - 4][nowX] = '*';
} // 처음 이동 시키는 경우 두 칸 전진도 가능하다
}
if (board[nowY - 2][nowX - 4] != '.' && board[nowY - 2][nowX - 5] == '<')
{ // 한 칸 대각선에 상대말 말이 있는 경우 이동하여 잡는 것이 가능하다
board[nowY - 2][nowX - 4] = '*';
}
if (board[nowY - 2][nowX + 4] != '.' && board[nowY - 2][nowX + 3] == '<')
{ // 한 칸 대각선에 상대말 말이 있는 경우 이동하여 잡는 것이 가능하다
board[nowY - 2][nowX + 4] = '*';
}
/** 앙파상 **/
if (enPassant2[0] >= 0 && nowX == enPassant2[1] + 4 && nowY == enPassant2[0] - 2) {
ChangePiece(enPassant2[0], enPassant2[1], 'E', 'n', 'P');
}
if (enPassant2[2] >= 0 && nowX == enPassant2[3] - 4 && nowY == enPassant2[2] - 2) {
ChangePiece(enPassant2[2], enPassant2[3], 'E', 'n', 'P');
}
}
}
/**
함수 이름 : Rook
함수 설명 : 이동시킬 말이 Rook인 경우 이동 가능 위치에 '*'로 표시한다.
Rook은 이동하려는 경로에 말이 존재하지 않을 경우 사방으로 이동이 가능하다.
파라미터 이름 : nowY, nowX
파라미터 설명
nowY : 이동시킬 Rook의 현재 y좌표
nowX : 이동시킬 Rook의 현재 x좌표
**/
void Rook(int nowY, int nowX)
{ // Rook 선택 시 이동 가능 위치 *로 표시
int copyNowY = nowY, copyNowX = nowX; // 변동이 있을 때 초기화를 위함
if (board[copyNowY][copyNowX - 1] == '<')
{ // Player 1의 경우
while (1)
{ // 앞으로 이동 가능
copyNowY += 2;
if (copyNowY > 16) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '[')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;}// 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY; // 다시 원래 자리로
while (1)
{ // 뒤로 이동 가능
copyNowY -= 2;
if (copyNowY < 0) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '[')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY; // 다시 원래 자리로
while (1)
{ // 오른쪽으로 이동 가능
copyNowX += 4;
if (copyNowX > 33) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '[')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // 왼쪽으로 이동 가능
copyNowX -= 4;
if (copyNowX < 0) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '[')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
}
else
{ // Player 2의 경우
while (1)
{ // 뒤로 이동 가능
copyNowY += 2;
if (copyNowY > 16) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '<')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY; // 다시 원래 자리로
while (1)
{ // 앞으로 이동 가능
copyNowY -= 2;
if (copyNowY < 0) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '<')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY; // 다시 원래 자리로
while (1)
{ // 오른쪽으로 이동 가능
copyNowX += 4;
if (copyNowX > 33) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '<')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // 왼쪽으로 이동 가능
copyNowX -= 4;
if (copyNowX < 0) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.') {board[copyNowY][copyNowX] = '*';} // 비어있는 칸이면 계속 이동 가능
else if (board[copyNowY][copyNowX - 1] == '<')
{
// 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
}
}
/**
함수 이름 : Bishop
함수 설명 : 이동시킬 말이 Bishop인 경우 이동 가능 위치에 '*'로 표시한다.
Bishop은 이동하려는 경로에 말이 존재하지 않을 경우 대각선으로 이동이 가능하다.
파라미터 이름 : nowY, nowX
파라미터 설명
nowY : 이동시킬 Bishop의 현재 y좌표
nowX : 이동시킬 Bishop의 현재 x좌표
**/
void Bishop(int nowY, int nowX)
{ // Bishop 선택 시 이동 가능 위치 *로 표시
int copyNowY = nowY, copyNowX = nowX; // 변동이 있을 때 초기화를 위함
if (board[copyNowY][copyNowX - 1] == '<')
{ // player1의 경우
while (1)
{ // ↘
copyNowY += 2;
copyNowX += 4;
if (copyNowY > 16 || copyNowX > 33) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '[')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY;
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // ↙
copyNowY += 2;
copyNowX -= 4;
if (copyNowY > 16 || copyNowX < 0) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '[')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY;
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // ↗
copyNowY -= 2;
copyNowX += 4;
if (copyNowY < 0 || copyNowX > 33) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '[')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY;
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // ↖
copyNowY -= 2;
copyNowX -= 4;
if (copyNowY < 0 || copyNowX < 0) {break;} // 체스판 끝까지 확인
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '[')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
}
else
{ //player2의 경우
while (1)
{ // ↘
copyNowY += 2;
copyNowX += 4;
if (copyNowY > 16 || copyNowX > 33) {break;}
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '<')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY;
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // ↙
copyNowY += 2;
copyNowX -= 4;
if (copyNowY > 16 || copyNowX < 0) {break;}
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '<')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY;
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // ↗
copyNowY -= 2;
copyNowX += 4;
if (copyNowY < 0 || copyNowX > 33) {break;}
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '<')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
copyNowY = nowY;
copyNowX = nowX; // 다시 원래 자리로
while (1)
{ // ↖
copyNowY -= 2;
copyNowX -= 4;
if (copyNowY < 0 || copyNowX < 0) {break;}
else if (board[copyNowY][copyNowX] == '.')
{ // 비어있는 칸이면 계속 이동 가능
board[copyNowY][copyNowX] = '*';
continue;
}
else if (board[copyNowY][copyNowX - 1] == '<')
{ // 상대방 말이 있으면 그 칸까지 이동 가능
board[copyNowY][copyNowX] = '*';
break;
}
else {break;} // 본인 말이 있으면 그 칸부터 이동 불가능
}
}
}
/**
함수 이름 : Knight
함수 설명 : 이동시킬 말이 Knight인 경우 이동 가능 위치에 '*'로 표시한다.
Knight은 직선한칸, 대각선 한칸으로 한번에 이동이 가능하다.
이동 경로에 말이 있어도 상관없이 넘어서 이동할 수 있다.
파라미터 이름 : nowY, nowX
파라미터 설명
nowY : 이동시킬 Knight의 현재 y좌표
nowX : 이동시킬 Knight의 현재 x좌표
**/
void Knight(int nowY, int nowX)
{ // Knight 선택 시 이동 가능 위치 *로 표시
// 비어있는 칸이거나 상대방 말이 있는 경우 이동 가능
if (board[nowY][nowX - 1] == '<')
{ // player1의 경우 (상대방의 말이 있거나 비어있으면 이동가능)
if (board[nowY + 4][nowX + 3] == '[' || board[nowY + 4][nowX + 3] == '.')
{ board[nowY + 4][nowX + 4] = '*'; } // ↓ ↓ -→
if (board[nowY + 4][nowX - 5] == '[' || board[nowY + 4][nowX - 5] == '.')
{ board[nowY + 4][nowX - 4] = '*'; } // ←- ↓ ↓
if (board[nowY + 2][nowX + 7] == '[' || board[nowY + 2][nowX + 7] == '.')
{ board[nowY + 2][nowX + 8] = '*'; } // ↓ -→ -→
if (board[nowY + 2][nowX - 9] == '[' || board[nowY + 2][nowX - 9] == '.')
{ board[nowY + 2][nowX - 8] = '*'; } // ←- ←- ↓
if (board[nowY - 4][nowX + 3] == '[' || board[nowY - 4][nowX + 3] == '.')
{ board[nowY - 4][nowX + 4] = '*'; } // ↑ ↑ -→
if (board[nowY - 4][nowX - 5] == '[' || board[nowY - 4][nowX - 5] == '.')
{ board[nowY - 4][nowX - 4] = '*'; } // ←- ↑ ↑
if (board[nowY - 2][nowX + 7] == '[' || board[nowY - 2][nowX + 7] == '.')
{ board[nowY - 2][nowX + 8] = '*'; } // ↑ -→ -→
if (board[nowY - 2][nowX - 9] == '[' || board[nowY - 2][nowX - 9] == '.')
{ board[nowY - 2][nowX - 8] = '*'; } // ←- ←- ↑
}
else
{ // player2의 경우 (상대방의 말이 있거나 비어있으면 이동가능)
if (board[nowY + 4][nowX + 3] == '<' || board[nowY + 4][nowX + 3] == '.')
{ board[nowY + 4][nowX + 4] = '*'; } // ↓ ↓ -→
if (board[nowY + 4][nowX - 5] == '<' || board[nowY + 4][nowX - 5] == '.')
{ board[nowY + 4][nowX - 4] = '*'; } // ←- ↓ ↓
if (board[nowY + 2][nowX + 7] == '<' || board[nowY + 2][nowX + 7] == '.')
{ board[nowY + 2][nowX + 8] = '*'; } // ↓ -→ -→
if (board[nowY + 2][nowX - 9] == '<' || board[nowY + 2][nowX - 9] == '.')
{ board[nowY + 2][nowX - 8] = '*'; } // ←- ←- ↓
if (board[nowY - 4][nowX + 3] == '<' || board[nowY - 4][nowX + 3] == '.')
{ board[nowY - 4][nowX + 4] = '*'; } // ↑ ↑ -→
if (board[nowY - 4][nowX - 5] == '<' || board[nowY - 4][nowX - 5] == '.')
{ board[nowY - 4][nowX - 4] = '*'; } // ←- ↑ ↑
if (board[nowY - 2][nowX + 7] == '<' || board[nowY - 2][nowX + 7] == '.')
{ board[nowY - 2][nowX + 8] = '*'; } // ↑ -→ -→
if (board[nowY - 2][nowX - 9] == '<' || board[nowY - 2][nowX - 9] == '.')
{ board[nowY - 2][nowX - 8] = '*'; } // ←- ←- ↑
}
}
/**
함수 이름 : Queen
함수 설명 : 이동시킬 말이 Queen인 경우 이동 가능 위치에 '*'로 표시한다.
Queen은 이동하려는 경로에 말이 있지 않는 한 사방, 대각선으로 이동이 가능하다.
파라미터 이름 : nowY, nowX
파라미터 설명
nowY : 이동시킬 Queen의 현재 y좌표
nowX : 이동시킬 Queen의 현재 x좌표
참조 함수들 : Rook(), Bishop()
**/
void Queen(int nowY, int nowX)
{ // Queen 선택 시 이동 가능 위치 *로 표시
Rook(nowY, nowX); // 사방으로 이동 가능 = Rook
Bishop(nowY, nowX); // 대각선으로 이동 가능 = Bishop
}
/**
함수 이름 : King
함수 설명 : 이동시킬 말이 King인 경우 이동 가능 위치에 '*'로 표시한다.
King은 이동하려는 경로에 말이 있지 않는 한 사방, 대각선으로 한 칸 이동이 가능하다.
파라미터 이름 : nowY, nowX
파라미터 설명
nowY : 이동시킬 King의 현재 y좌표
nowX : 이동시킬 King의 현재 x좌표
**/
void King(int nowY, int nowX)
{ // King 선택 시 이동 가능 위치 *로 표시
if (board[nowY][nowX - 1] == '<')
{ //player1의 경우
if (board[nowY + 2][nowX - 1] != '<') {board[nowY + 2][nowX] = '*';} // ↓
if (board[nowY - 2][nowX - 1] != '<') {board[nowY - 2][nowX] = '*';} // ↑
if (board[nowY][nowX + 3] != '<') {board[nowY][nowX + 4] = '*';} // -→
if (board[nowY][nowX - 5] != '<') {board[nowY][nowX - 4] = '*';} // ←-
if (board[nowY + 2][nowX + 3] != '<') {board[nowY + 2][nowX + 4] = '*';} // ↓ -→
if (board[nowY + 2][nowX - 5] != '<') {board[nowY + 2][nowX - 4] = '*';} // ←- ↓
if (board[nowY - 2][nowX + 3] != '<') {board[nowY - 2][nowX + 4] = '*';} // ↑ -→
if (board[nowY - 2][nowX - 5] != '<') {board[nowY - 2][nowX - 4] = '*';} // ←- ↑
}
else
{ //player2의 경우
if (board[nowY + 2][nowX - 1] != '[') {board[nowY + 2][nowX] = '*';} // ↓
if (board[nowY - 2][nowX - 1] != '[') {board[nowY - 2][nowX] = '*';} // ↑
if (board[nowY][nowX + 3] != '[') {board[nowY][nowX + 4] = '*';} // -→
if (board[nowY][nowX - 5] != '[') {board[nowY][nowX - 4] = '*';} // ←-
if (board[nowY + 2][nowX + 3] != '[') {board[nowY + 2][nowX + 4] = '*';} // ↓ -→
if (board[nowY + 2][nowX - 5] != '[') {board[nowY + 2][nowX - 4] = '*';} // ←- ↓
if (board[nowY - 2][nowX + 3] != '[') {board[nowY - 2][nowX + 4] = '*';} // ↑ -→
if (board[nowY - 2][nowX - 5] != '[') {board[nowY - 2][nowX - 4] = '*';} // ←- ↑
}
}
/**
함수 이름 : SaveGame
함수 설명 : 현재 게임 상황(게임보드, 순서, 죽은 말)을 지정한 파일에 저장한다. (파일이 존재하지 않는 경우 생성하여 저장한다.)
**/
void SaveGame(void)
{ // 현재 실행중인 체스판 저장
FILE *fp = NULL; // 저장용 텍스트 파일 저장할 공간
fp = fopen(boardSaveFile, "w+"); // chess_save.txt파일 열기 (없으면 만들어서 열기)
for (int i = -1; i < 19; i++)
{ // 한줄씩 파일에 입력하기
if (i == -1) {
fprintf(fp, "%s \n", deadPiece2);
}
else if (i == 17) {
fprintf(fp, "%s \n", deadPiece1);
}
else if (i == 18) {
fprintf(fp, "%d,%d,%d,%d,%d", startPlayer, longCastlingCheck[0], longCastlingCheck[1],
shortCastlingCheck[0], shortCastlingCheck[1]);
}
else {
fprintf(fp, "%s \n", board[i]);
}
}
fclose(fp); // 파일 닫기
}
/**
함수 이름 : Check
함수 설명 : 현재 왕의 좌표를 기준으로 체크 상태 여부를 확인한다.
1. 사방 기준으로 상대방의 말 Q 또는 R이 있는 경우 체크이다.
2. 대각선 기준으로 상대방의 말 B 또는 Q가 있는 경우 체크이다.
(한 칸 대각선 위치에 상대방의 말 P가 있는 경우 체크이다.)
3. 상대방 말의 Knight에 의한 체크여부를 확인한다.
파라미터 이름 : player, king
파라미터 설명
player : 체크 여부를 확인하는 player ( player는 1 또는 2)
king : 이동 시킬 말이 King인 경우 이동 후 좌표를 이용하여 체크 여부를 확인하기 위해 이동 여부를 알린다. (king 이동 시 1)
**/
int Check(int player, int king)
{ // 모든 말이 움직일 수 있는 경우의 수를 계산하고 그 중 check상태가 될 수 있는 경우가 있는지 확인하기
int c = 0; // check가 될 수 있는 경우의 수
int x, y;
if (player == 1)
{ // player1의 경우
if (king == 1) { x = kingX3, y = kingY3; } // 현재 king의 좌표 저장
else { x = kingX1, y = kingY1; } // 현재 king의 좌표 저장
// 오른쪽
for (int i = (x + 4); i < 34; i += 4)
{ // 체스판 끝까지 확인
if (board[y][i - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][i - 1] == '[')
{ // 상대방 R이나 Q가 있으면 check
if (board[y][i] == 'R' || board[y][i] == 'Q')
{
c++;
break;
}
}
}
//왼쪽
for (int i = (x - 4); i >= 0; i -= 4)
{ // 체스판 끝까지 확인
if (board[y][i - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][i - 1] == '[')
{ // 상대방 R이나 Q가 있으면 check
if (board[y][i] == 'R' || board[y][i] == 'Q')
{
c++;
break;
}
}
}
//위
for (int i = (y + 2); i < 17; i += 2)
{ // 체스판 끝까지 확인
if (board[i][x - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[i][x - 1] == '[')
{ // 상대방 R이나 Q가 있으면 check
if (board[i][x] == 'R' || board[i][x] == 'Q')
{
c++;
break;
}
}
}
//아래
for (int i = (y - 2); i >= 0; i -= 2)
{ // 체스판 끝까지 확인
if (board[i][x - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[i][x - 1] == '[')
{ // 상대방 R이나 Q가 있으면 check
if (board[i][x] == 'R' || board[i][x] == 'Q')
{
c++;
break;
}
}
}
//대각선1
int pp = 0; // pawn 확인용 (대각선 기준 몇 칸 차이인지)
while (1)
{
x += 4;
y += 2;
pp++;
if (board[y][x - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '[')
{
if (board[y][x] == 'P' && pp == 1)
{ // 한 칸 대각선에 상대방 P가 있으면 check
c++;
break;
}
else if (board[y][x] == 'Q' || board[y][x] == 'B')
{ // 상대방 B나 Q가 있으면 check
c++;
break;
}
}
if (x > 33 || y > 16) { break; } // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX1, y = kingY1; } // 좌표 원래대로 돌려놓기
//대각선2
pp = 0; // pawn 확인용 (대각선 기준 몇 칸 차이인지)
while (1)
{
x -= 4;
y += 2;
pp++;
if (board[y][x - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '[')
{
if (board[y][x] == 'P' && pp == 1)
{ // 한 칸 대각선에 상대방 P가 있으면 check
c++;
break;
}
else if (board[y][x] == 'Q' || board[y][x] == 'B')
{ // 상대방 B나 Q가 있으면 check
c++;
break;
}
}
if (x < 0 || y > 16) {break;} // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX1, y = kingY1; } // 좌표 원래대로 돌려놓기
// 대각선3
while (1)
{
x -= 4;
y -= 2;
if (board[y][x - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '[')
{ // 상대방 B나 Q가 있으면 check
if (board[y][x] == 'Q' || board[y][x] == 'B')
{
c++;
break;
}
}
if (x < 0 || y < 0) {break;} // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX1, y = kingY1; } // 좌표 원래대로 돌려놓기
//대각선4
while (1)
{
x += 4;
y -= 2;
if (board[y][x - 1] == '<') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '[')
{ // 상대방 B나 Q가 있으면 check
if (board[y][x] == 'Q' || board[y][x] == 'B')
{
c++;
break;
}
}
if (x > 33 || y < 0) break; // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX1, y = kingY1; } // 좌표 원래대로 돌려놓기
//knight
if (board[y + 4][x + 3] == '[' && board[y + 4][x + 4] == 'N') {
if ((x + 3) < 33 && (y + 4) < 17) {c++;} // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y + 4][x - 5] == '[' && board[y + 4][x - 4] == 'N') {
if ((x - 5) >= 0 && (y + 4) < 17) {c++;} // ←- ↓ ↓ 위치에 상대방 N있으면 check
}
if (board[y - 2][x - 9] == '[' && board[y - 2][x - 8] == 'N') {
if ((x - 9) >= 0 && (y - 2) >= 0) {c++;} // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y + 2][x + 7] == '[' && board[y + 2][x + 8] == 'N') {
if ((x + 7) < 33 && (y + 2) < 17) {c++;} // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y + 2][x - 9] == '[' && board[y + 2][x - 8] == 'N') {
if ((x - 9) >= 0 && (y + 2) < 17) {c++;} // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y - 4][x + 3] == '[' && board[y - 4][x + 4] == 'N') {
if ((x + 3) < 33 && (y - 4) >= 0) {c++;} // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y - 4][x - 5] == '[' && board[y - 4][x - 4] == 'N') {
if ((x - 5) >= 0 && (y - 4) >= 0) {c++;} // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y - 2][x + 7] == '[' && board[y - 2][x + 8] == 'N') {
if ((x + 7) < 33 && (y - 2) >= 0) {c++;} // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
}
else
{ // player2의 경우
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX2, y = kingY2; } // 현재 king의 좌표 저장
//오른쪽
for (int i = (x + 4); i < 34; i += 4)
{ // 체스판 끝까지 확인
if (board[y][i - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][i - 1] == '<') { // 상대방 R이나 Q가 있으면 check
if (board[y][i] == 'R' || board[y][i] == 'Q')
{
c++;
break;
}
}
}
//왼쪽
for (int i = (x - 4); i >= 0; i -= 4)
{ // 체스판 끝까지 확인
if (board[y][i - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][i - 1] == '<')
{ // 상대방 R이나 Q가 있으면 check
if (board[y][i] == 'R' || board[y][i] == 'Q')
{
c++;
break;
}
}
}
//위
for (int i = (y + 2); i < 17; i += 2)
{ // 체스판 끝까지 확인
if (board[i][x - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[i][x - 1] == '<')
{ // 상대방 R이나 Q가 있으면 check
if (board[i][x] == 'R' || board[i][x] == 'Q')
{
c++;
break;
}
}
}
//아래
for (int i = (y - 2); i >= 0; i -= 2)
{ // 체스판 끝까지 확인
if (board[i][x - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[i][x - 1] == '<')
{ // 상대방 R이나 Q가 있으면 check
if (board[i][x] == 'R' || board[i][x] == 'Q')
{
c++;
break;
}
}
}
//대각선1
while (1)
{
x += 4;
y += 2;
if (board[y][x - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '<')
{ // 상대방 B나 Q가 있으면 check
if (board[y][x] == 'Q' || board[y][x] == 'B')
{
c++;
break;
}
}
if (x > 33 || y > 16) {break;} // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX2, y = kingY2; } // 좌표 원래대로 돌려놓기
//대각선2
while (1)
{
x -= 4;
y += 2;
if (board[y][x - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '<')
{ // 상대방 B나 Q가 있으면 check
if (board[y][x] == 'Q' || board[y][x] == 'B')
{
c++;
break;
}
}
if (x < 0 || y > 16) {break;} // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX2, y = kingY2; } // 좌표 원래대로 돌려놓기
//대각선3
int pp = 0; // pawn 확인용 (대각선 기준 몇 칸 차이인지)
while (1)
{
x -= 4;
y -= 2;
pp++;
if (board[y][x - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '<')
{
if (board[y][x] == 'P' && pp == 1)
{ // 한 칸 대각선에 상대방 P가 있으면 check
c++;
break;
}
else if (board[y][x] == 'Q' || board[y][x] == 'B')
{ // 상대방 B나 Q가 있으면 check
c++;
break; // 체스판 끝까지 확인
}
}
if (x < 0 || y < 0) {break;} // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX2, y = kingY2; } // 좌표 원래대로 돌려놓기
//대각선4
pp = 0; // pawn 확인용 (대각선 기준 몇 칸 차이인지)
while (1)
{
x += 4;
y -= 2;
pp++;
if (board[y][x - 1] == '[') {break;} // 본인 말이 가장 가까이에 있으면 check 아님
else if (board[y][x - 1] == '<')
{
if (board[y][x] == 'P' && pp == 1)
{ // 한 칸 대각선에 상대방 P가 있으면 check
c++;
break;
}
else if (board[y][x] == 'Q' || board[y][x] == 'B')
{ // 상대방 B나 Q가 있으면 check
c++;
break;
}
}
if (x > 33 || y < 0) {break;} // 체스판 끝까지 확인
}
if (king == 1) { x = kingX3, y = kingY3; }
else { x = kingX2, y = kingY2; } // 좌표 원래대로 돌려놓기
//knight
if (board[y + 4][x + 3] == '<' && board[y + 4][x + 4] == 'N') {
if ((x + 3) < 33 && (y + 4) < 17) c++; // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y + 4][x - 5] == '<' && board[y + 4][x - 4] == 'N') {
if ((x - 5) >= 0 && (y + 4) < 17) c++; // ←- ↓ ↓ 위치에 상대방 N있으면 check
}
if (board[y - 2][x - 9] == '<' && board[y - 2][x - 8] == 'N') {
if ((x - 9) >= 0 && (y - 2) >= 0) c++; // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y + 2][x + 7] == '<' && board[y + 2][x + 8] == 'N') {
if ((x + 7) < 33 && (y + 2) < 17) c++; // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y + 2][x - 9] == '<' && board[y + 2][x - 8] == 'N') {
if ((x - 9) >= 0 && (y + 2) < 17) c++; // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y - 4][x + 3] == '<' && board[y - 4][x + 4] == 'N') {
if ((x + 3) < 33 && (y - 4) >= 0) c++; // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y - 4][x - 5] == '<' && board[y - 4][x - 4] == 'N') {
if ((x - 5) >= 0 && (y - 4) >= 0) c++; // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
if (board[y - 2][x + 7] == '<' && board[y - 2][x + 8] == 'N') {
if ((x + 7) < 33 && (y - 2) >= 0) c++; // ↓ ↓ -→ 위치에 상대방 N있으면 check
}
}
if (c != 0) {return 1;} // check인 경우가 있다
else {return 0;} // check인 경우가 없다
}
/**
함수 이름 : Checkmate
함수 설명 : 체크메이트 여부를 확인하여 체크메이트인 경우 해당 player를 패배처리한다.
파라미터 이름 : nowY, nowX
파라미터 설명
nowY : 이동시킬 King의 현재 y좌표
nowX : 이동시킬 King의 현재 x좌표
참조 함수들 : Check - 이동 가는 한 곳으로 임시 이동 시킨 후 체크여부를 확인
**/
int Checkmate(int player)
{
if (player == 1)
{
BackupBoard(); // 확인 후 체스판을 처음 상태로 돌려놓기 위해 저장 (백업)
for (int I = 1; I < 17; I += 2)
{
for (int J = 2; J < 34; J += 4)
{
if (board[I][J - 1] == '<')
{ // 판에 있는 모든 player1의 말을 대상으로 확인
switch (board[I][J])
{ // 말의 종류에 따라 이동 가능한 위치 표시
case 'P': { Pawn(I, J); break; }
case 'R': { Rook(I, J); break; }
case 'N': { Knight(I, J); break; }
case 'B': { Bishop(I, J); break; }
case 'Q': { Queen(I, J); break;}
case 'K': { King(I, J); break; }
}
// 이동 후 check 상태가 되는 곳은 .으로 변경
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
BackupCheckBoard(); //확인이 끝난 후 돌려놓을 판을 위해 저장해놓음 (백업용)
int checkx = -1, checky = -1; // 이동을 금지시킬 행과 열 인덱스 저장용
if (board[2 * i + 1][4 * j + 2] == '*')
{ // 이동 가능하다고 표시된 곳으로 이동시키기 (임시)
ChangePiece(2*i+1, 4*j+2, '<', board[I][J], '>');
ChangePiece(I, J, '.', '.', '.');
DeleteStar();
if (board[2 * i + 1][4 * j + 2] != 'K')
{
if (Check(1, 0) == 1)
{
checkx = 4 * j + 2;
checky = 2 * i + 1;
} // check인 경우 좌표 저장
}
else
{
kingX3 = 4 * j + 2;
kingY3 = 2 * i + 1; // 움직일 말이 King이면 Check함수에서 이용할 변수값도 바꿔야 함
if (Check(1, 1) == 1)
{
checkx = 4 * j + 2;
checky = 2 * i + 1;
} // check인 경우 좌표 저장
}
ReturnCheckBoard(); //다시 현재 판으로 돌려놓음
if (checkx >= 0) { board[checky][checkx] = '.'; }
// 만약 check인 경우가 있어서 checkx, checky에 인덱스 값이 저장되어있으면 * -> . (이동 못함)
}
}
}
// 선택된 말이 움질일 수 있는 경로가 있는지 확인
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (board[2 * i + 1][4 * j + 2] == '*') { countStar += 1; } // countStar >= 1이면 말이 움질일 수 있다는 것을 의미
}
}
if (countStar != 0)
{ // 이동할 수 있는 곳이 적어도 하나 있으면 checkmate아님
countStar = 0;
return 1;
}
else
{
for (int k = 0; k < 17; k++) { strcpy(board[k], backupBoard[k]); }
}
}
}
}
if (countStar == 0) {return countStar;}
}
else
{
BackupBoard(); // 확인 후 체스판을 처음 상태로 돌려놓기 위해 저장 (백업)
for (int I = 1; I < 17; I += 2)
{
for (int J = 2; J < 34; J += 4)
{
if (board[I][J - 1] == '[')
{ // 판에 있는 모든 player2의 말을 대상으로 확인
switch (board[I][J])
{ // 말의 종류에 따라 이동 가능한 위치 표시
case 'P': { Pawn(I, J); break; }
case 'R': { Rook(I, J); break; }
case 'N': { Knight(I, J); break; }
case 'B': { Bishop(I, J); break; }
case 'Q': { Queen(I, J); break; }
case 'K': { King(I, J); break; }
}
// 이동 후 check 상태가 되는 곳은 .으로 변경
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
BackupCheckBoard(); // 확인이 끝난 후 돌려놓을 판을 위해 저장해놓음 (백업용)
int checkx = -1, checky = -1; // 이동을 금지시킬 행과 열 인덱스 저장용
if (board[2 * i + 1][4 * j + 2] == '*')
{ // 이동 가능하다고 표시된 곳으로 이동시키기 (임시)
ChangePiece(2*i+1, 4*j+2, '[', board[I][J], ']');
ChangePiece(I, J, '.', '.', '.');
DeleteStar();
if (board[2 * i + 1][4 * j + 2] != 'K')
{
if (Check(2, 0) == 1)
{
checkx = 4 * j + 2;
checky = 2 * i + 1;
} // check인 경우 좌표 저장
}
else
{
kingX3 = 4 * j + 2;
kingY3 = 2 * i + 2; // 움직일 말이 King이면 Check함수에서 이용할 변수값도 바꿔야 함
if (Check(2, 1) == 1)
{
checkx = 4 * j + 2;
checky = 2 * i + 1;
} // check인 경우 좌표 저장
}
ReturnCheckBoard(); //다시 현재 판으로 돌려놓음
if (checkx >= 0) { board[checky][checkx] = '.'; }
// checkx, checky에 인덱스 값이 저장되어있으면 * -> . (이동 못함)
}
}
}
// 선택된 말이 움질일 수 있는 경로가 있는지 확인
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (board[2 * i + 1][4 * j + 2] == '*') { countStar += 1; } // countStar >= 1이면 말이 움질일 수 있다는 것을 의미
}
}
if (countStar != 0)
{
countStar = 0;
return 1;
} // 이동할 수 있는 곳이 적어도 하나 있으면 checkmate아님
else
{
for (int k = 0; k < 17; k++) { strcpy(board[k], backupBoard[k]); }
}
}
}
}
if (countStar == 0) {return countStar;} // checkmate인 경우 return 0;
}
}
/**
함수 이름 : Promotion
함수 설명 : 특수룰(프로모션), 상대방 진영 끝에 Pawn이 도달했을 경우 Pawn을 Q, B, N, R 중 하나로 바꿀 수 있다.
파라미터 이름 : beforex, beforey, aftery, player
파라미터 설명
beforex : player가 이동시킬 말의 x좌표
beforey : player가 이동시킬 말의 y좌표
aftery : 말을 이동시킬 위치의 y좌표
player : 실행시킬 player (1 or 2)
**/
void Promotion(int beforex, int beforey, int aftery, int player) {
if (player == 1) {
if (board[beforey][beforex] == 'P' && aftery == 15) { // 프로모션 - Pawn이 상대측 체스판 끝에 도달 시 Q, B, N, R 중 하나로 변경
char Change[2];
Clear();
printf("change P to ? (Q or B or N or R) : ");
scanf("%s", Change);
if (Change[0] == 'Q' || Change[0] == 'B' || Change[0] == 'N' || Change[0] == 'R') {
board[beforey][beforex] = Change[0]; // 입력받은 문자열로 변경
}
else { // 다른 문자 입력하면 PASS!
printf("You can not change P to %c\n", Change[0]);
}
}
}
else {
if (board[beforey][beforex] == 'P' && aftery == 1) { // 프로모션 - Pawn이 상대측 체스판 끝에 도달 시 Q, B, N, R 중 하나로 변경
char Change[2];
Clear();
printf("change P to ? (Q or B or N or R) : ");
scanf("%s", Change);
if (Change[0] == 'Q' || Change[0] == 'B' || Change[0] == 'N' || Change[0] == 'R')
{
board[beforey][beforex] = Change[0]; // 입력받은 문자열로 변경
}
else
{ // 다른 문자 입력하면 PASS!
printf("You can not change P to %c\n", Change[0]);
}
}
}
}
/**
함수 이름 : Castling
함수 설명 : 특수룰(캐슬링), 다음과 같은 조건이 성립할 때 K와 R을 정해진 위치로 동시에 이동시킬 수 있다.
파라미터 이름 : player
파라미터 설명
player : 실행시키는 player 번호 (1 or 2)
**/
void Castling(int player) {
int piece = 0;
if (player == 1) {
/**longcastling**/
if (longCastlingCheck[0] == 0) { // K과 R이 모두 움직이지 않았다.
for (int i = (kingX1 + 4) ; i < 29 ; i += 4)
{
if (board[kingY1][i] != '.' && board[kingY1][i] != '*')
{
piece += 1;
break;
}
}
if (piece == 0) {
ChangePiece( kingY1, kingX1 + 8, 'C', 'a', 's');
}
}
piece = 0;
/**shortcasting**/
if (shortCastlingCheck[0] == 0) {
for (int i = (kingX1 - 4) ; i > 2 ; i -= 4)
{
if (board[kingY1][i] != '.' && board[kingY1][i] != '*')
{ piece += 1; break; }
}
if (piece == 0) {
ChangePiece(kingY1, kingX1 - 8, 'C', 'a', 's');
}
}
}
else if (player == 2) {
/**longcastling**/
if (longCastlingCheck[1] == 0) { // K과 R이 모두 움직이지 않았다.
for (int i = (kingX2 + 4) ; i < 29 ; i += 4)
{
if (board[kingY2][i] != '.' && board[kingY2][i] != '*')
{
piece += 1;
break;
}
}
if (piece == 0)
{ ChangePiece(kingY2, kingX2 + 8, 'C', 'a', 's'); }
}
piece = 0;
/**shortcasting**/
if (shortCastlingCheck[1] == 0) {
for (int i = (kingX2 - 4) ; i > 2 ; i -= 4)
{
if (board[kingY2][i] != '.' && board[kingY2][i] != '*')
{ piece += 1; break; }
}
if (piece == 0) {
{ ChangePiece(kingY2, kingX2 - 8, 'C', 'a', 's'); }
}
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "uthash.h"
typedef struct {
int key;
int data;
UT_hash_handle hh;
} item;
int main()
{
item *i, *j, *items=NULL;
int k;
/* first item */
k = 12345;
i = (item*)malloc(sizeof(item));
if (i == NULL) {
exit(-1);
}
i->key = k;
i->data = 0;
HASH_ADD_INT(items,key,i);
/* second item */
k = 6789;
i = (item*)malloc(sizeof(item));
if (i == NULL) {
exit(-1);
}
i->key = k;
i->data = 0;
HASH_ADD_INT(items,key,i);
/* third item */
k = 98765;
i = (item*)malloc(sizeof(item));
if (i == NULL) {
exit(-1);
}
i->key = k;
i->data = 0;
HASH_ADD_INT(items,key,i);
/* look them all up */
k = 12345;
HASH_FIND_INT(items, &k, j);
if (j != NULL) {
printf("found %d\n",k);
}
k = 6789;
HASH_FIND_INT(items, &k, j);
if (j != NULL) {
printf("found %d\n",k);
}
k = 98765;
HASH_FIND_INT(items, &k, j);
if (j != NULL) {
printf("found %d\n",k);
}
/* delete them not the way we prefer but it works */
for(j=items; j != NULL; j=(item*)j->hh.next) {
printf("deleting %d\n", j->key);
HASH_DEL(items,j);
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void){
int N,D,K;
scanf("%d%d%d",&N,&D,&K);
int L[D],R[D];
for(int i = 0;i < D;i++) scanf("%d%d",&L[i],&R[i]);
int S,T;
for(int i = 0;i < K;i++){
scanf("%d%d",&S,&T);
for(int j = 0;;j++){
if(S < T){
if(L[j] <= S && S < R[j]){
if(L[j] <= T && T <= R[j]){
printf("%d\n",j+1);
break;
}
S = R[j];
}
}else{
if(L[j] < S && S <= R[j]){
if(L[j] <= T && T <= R[j]){
printf("%d\n",j+1);
break;
}
S = L[j];
}
}
}
}
return 0;
} ./Main.c: In function main:
./Main.c:5:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d%d",&N,&D,&K);
^
./Main.c:8:28: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
for(int i = 0;i < D;i++) scanf("%d%d",&L[i],&R[i]);
^
./Main.c:12:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d",&S,&T);
^
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "../fila/Fila_interface.h"
#include "../pilha/Pilha_interface.h"
#include "Fila_pilha_interface.h"
#include "Fila_pilha_privado.h"
#define TRUE 1
#define FALSE 0
p_fila_pilha criar(int quantidade_dado_pilha, int tamanho_dado_pilha) {
p_fila_pilha pfp = malloc(sizeof(Fila_Pilha));
if (pfp == NULL || quantidade_dado_pilha <= 0 || tamanho_dado_pilha <= 0) {
return NULL;
}
pPilha pPilhaV = criaPilha(quantidade_dado_pilha, tamanho_dado_pilha);
if (pPilhaV == NULL) {
return NULL;
}
fFila pFila = criarFila(sizeof(pPilha));
if (pFila == NULL) {
return NULL;
}
if (enfileirar(pFila, pPilhaV) == FALSE) {
return NULL;
}
pfp->fila = pFila;
pfp->quantidade_dado_pilha = quantidade_dado_pilha;
pfp->tamanho_dado_pilha = tamanho_dado_pilha;
return pfp;
}
int insereNovaPilha(p_fila_pilha pfp, void* elemento) {
pPilha pPilha = criaPilha(pfp->quantidade_dado_pilha, pfp->tamanho_dado_pilha);
if (pPilha == NULL) {
return FALSE;
}
if (empilha(pPilha, elemento) == FALSE) {
return FALSE;
}
return enfileirar(pfp->fila, pPilha);
}
int insere(p_fila_pilha pfp, void* elemento) {
if (pfp == NULL || pfp->fila == NULL) {
return FALSE;
}
pPilha fimFilaPilha = fimFila(pfp->fila);
if (fimFilaPilha == NULL) {
return insereNovaPilha(pfp, elemento);
}
if (empilha(fimFilaPilha, elemento) == TRUE) {
return TRUE;
}
return insereNovaPilha(pfp, elemento);
}
void* retira(p_fila_pilha pfp) {
if (pfp == NULL || pfp->fila == NULL) {
return NULL;
}
pPilha inicioFilaPilha = inicioFila(pfp->fila);
if (inicioFilaPilha == NULL) {
return NULL;
}
void* dados = desempilha(inicioFilaPilha);
if (dados != NULL) {
return dados;
}
if (desenfileira(pfp->fila) == NULL) {
return NULL;
}
return retira(pfp);
}
int destruir(p_fila_pilha pfp) {
if (pfp == NULL) {
return FALSE;
}
pPilha pilhaDesenfileirada = desenfileira(pfp->fila);
while (pilhaDesenfileirada != NULL) {
destroiPilha(pilhaDesenfileirada);
pilhaDesenfileirada = desenfileira(pfp->fila);
}
destroiFila(pfp->fila);
free(pfp);
return TRUE;
}
|
C
|
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <asm/uaccess.h>
// 定义设备文件名
#define DEVICE_NAME "wordcount"
static unsigned char mem[10000]; // 保存向设备文件写入的数据
static char read_flag = 'y'; //y:設備已讀取 n:設備未讀取
static int written_count = 0;
//當設備文件讀取時會被呼叫的函數
//file:指向設備文件 buf:保存可讀取的資訊 count:可讀取的字數 ppos:讀取的偏移量
static ssize_t word_count_read(struct file *file, char __user *buf,size_t count, loff_t *ppos)
{
if( read_flag == 'n')
{
copy_to_user(buf,(void*)mem,written_count);
printk("read count %d\n",(int) written_count);
read_flag = 'y';
return written_count;
}
//讀取過一次不能再讀取
else
{
return 0;
}
}
//當設備文件寫入時會被呼叫的函數
//file:指向設備文件 buf:保存可讀取的資訊 count:可讀取的字數 ppos:讀取的偏移量
static ssize_t word_count_write(struct file *file, const char __user *buf,size_t count, loff_t *ppos)
{
copy_from_user(mem, buf, count);
read_flag = 'n';
written_count = count;
printk("write:written count:%d\n", (int) written_count);
return written_count;
}
// 描述与设备文件触发的事件对应的回调函数指针
// owner 指定整個模組都是驅動程式
//read API對應函數設定
//write API對應函數設定
static struct file_operations dev_fops =
{ .owner = THIS_MODULE, .read = word_count_read, .write = word_count_write };
// 描述设备文件的信息
//name 指定驅動程式名稱
//minor 動態版號
static struct miscdevice misc =
{ .minor = MISC_DYNAMIC_MINOR, .name = DEVICE_NAME, .fops = &dev_fops };
// 初始化Linux驱动
static int __init word_count_init(void)
{
int ret;
// 建立设备文件
ret = misc_register(&misc);
// 输出日志信息
printk("word_count_init_success\n");
return ret;
}
// 卸载Linux驱动
static void __exit word_count_exit(void)
{
// 删除设备文件
misc_deregister(&misc);
// 输出日志信息
printk("word_count_init_exit_success\n");
}
// 注册初始化Linux驱动的函数
module_init( word_count_init);
// 注册卸载Linux驱动的函数
module_exit( word_count_exit);
MODULE_AUTHOR("jash.liao");
MODULE_DESCRIPTION("statistics of word count.");
MODULE_ALIAS("word count module.");
MODULE_LICENSE("GPL");
|
C
|
/* handling keyboard interrupt
* get the correct character from corresponding scan value */
//#define ASM 1
#include "keyScan2ascii.h"
#include "lib.h"
#define ARRAY_LEN 256
#define NULL 0
#define CAPS_LOCK 0x3A
/* constants for keyboard ascii*/
#define ESC 27
#define BACKSPACE 8
#define TAB 9
#define NEWLINE 10
#define S_QUOTATION 39
#define BACKSLASH 92
#define SPACE 32
#define L 0x26
#define LEFT_CTRL 0x1D
#define CTRL_RELEASE 0x9D
#define BACKSPACE_PRESS 0x0E
#define CLEAN 0XFF
int caps_flag = 0;
int ctrl_flag = 0;
static char k2a_arr[ARRAY_LEN] = {
NULL, ESC, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-',
'=', BACKSPACE, TAB, 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
'[', ']', NEWLINE, NULL, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
';', S_QUOTATION, '`', NULL, BACKSLASH, 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',',
'.', '/', NULL, '*', NULL, SPACE, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
'7', '8', '9', '-', '4', '5', '6', '+', '1', '2', '3', '0', '.',
NULL, NULL};
/*
* char scan2ascii(char scan)
* DESCRIPTION:
* get the ascii value of the character typed from keyboard
* INPUT:
* char scan -- input from keyboard
* OUTPUT:
* none
* Return value : correct correspoing character
*/
#define Lower_to_Upper 32
#define KEY_RELEASE 0x58
unsigned char scan2ascii(char scan)
{
char ascii;
if (scan == CAPS_LOCK) // check if caps lock key is pressed
{
if (caps_flag)
{
caps_flag = 0;
}
else
{
caps_flag = 1;
}
}
if(scan == LEFT_CTRL){
ctrl_flag = 1;
// putc(LEFT_CTRL);
}
else if(scan == CTRL_RELEASE){
ctrl_flag = 0;
// putc(CTRL_RELEASE);
}
if(scan == L && ctrl_flag == 1)
return CLEAN;
if(scan == BACKSPACE_PRESS)
return BACKSPACE;
if (scan > KEY_RELEASE) // if the number is larger than 0x58, it means release
{
return NULL;
}
ascii = k2a_arr[(int)scan]; // get the corresponding ascii value of the key pressed
if (ascii >= 'A' && ascii <= 'Z' && !caps_flag) // for alphabets that are not capitalized
{
ascii += Lower_to_Upper; // add 32 to make it not capitalized
}
return ascii;
}
|
C
|
//This file contains functions pertaining to getting and implementing action by user
#include <stdio.h>
#include <stdlib.h>
#include "struct_def.h"
#include "input.h"
#include "move.h"
//recursive function to reveal all appropriate tiles
void RevealTiles(Board* board, int row, int col) {
int i, j;
if (row < 1 || row > board->num_rows || col < 1 || col > board->num_cols) { //stop when going out of bounds
return;
}
if (board->the_board[row][col].visibility != 0) { //stop if tile is not concealed
return;
}
else if (board->the_board[row][col].num_mines_around != 0) { //reveal and then stop if tile has 1 more more mines around it
board->the_board[row][col].visibility = 4;
}
else {
board->the_board[row][col].visibility = 4; //reveal and then run function again on all tiles around it if there are 0 mines
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i == row && j == col) {
continue;
}
RevealTiles(board, i, j);
}
}
}
}
//implements the user action on tile
void ImplementAction(Board* board, int action, UserMove move) {
if (board->the_board[move.move_row][move.move_col].visibility == 0) { //for hidden tiles, either reveal, mark, or question tiles based on action
if (action == 0) {
RevealTiles(board, move.move_row, move.move_col);
}
else if (action == 1) {
board->the_board[move.move_row][move.move_col].visibility = 2;
}
else if (action == 2) {
board->the_board[move.move_row][move.move_col].visibility = 1;
board->num_mines = board->num_mines - 1; //the counter for number of mines remaining goes down everytime user marks a tile
}
}
else if (board->the_board[move.move_row][move.move_col].visibility == 1) { //unmark or unquestion tile
board->the_board[move.move_row][move.move_col].visibility = 0;
board->num_mines = board->num_mines + 1; //the counter for number of mines remaining goes up everytime user unmarks a tile
}
else if (board->the_board[move.move_row][move.move_col].visibility == 2) {
board->the_board[move.move_row][move.move_col].visibility = 0;
}
}
//Asks user for tile they want to take action on and check if it's valid
void GetMove(Board board, UserMove* move) {
int numArgsRead;
do {
printf("Enter row a row between 0-%d and a column between 0-%d: ", board.num_rows - 1, board.num_cols - 1);
numArgsRead = scanf("%d %d", &(move->move_row), &(move->move_col));
} while (!IsValidMove(numArgsRead, 2, board, *move));
move->move_row = board.num_rows - move->move_row; //convert the user row and col to the appropriate row and col corresponding to location on board
move->move_col = move->move_col + 1;
}
//Give user appropriate action options depending on visibility of tile they selected
void GetAction(Board board, UserMove* move, int* action) {
do {
GetMove(board, move);
if (board.the_board[move->move_row][move->move_col].visibility == 0) { //if tile is still hidden give them 4 options
printf("Enter Action\n");
printf("0. Reveal\n1. Question\n2. Mark\n3. Cancel\n");
printf("Action: ");
scanf("%d", action);
}
else if (board.the_board[move->move_row][move->move_col].visibility == 1) { //if tile is marked or questioned, they can unmark/question it or cancel
printf("Enter Action\n");
printf("0. UnMark\n1. Cancel\n");
printf("Action: ");
scanf("%d", action);
}
else if (board.the_board[move->move_row][move->move_col].visibility == 2) {
printf("Enter Action\n");
printf("0. UnQuestion\n1. Cancel\n");
printf("Action: ");
scanf("%d", action);
}
else {
printf("This tile is already revealed.\n");
}
} while ((board.the_board[move->move_row][move->move_col].visibility == 0 && *action == 3) || //while user hasn't canceled and action is valid
(board.the_board[move->move_row][move->move_col].visibility == 1 && *action == 1) ||
(board.the_board[move->move_row][move->move_col].visibility == 2 && *action == 1) ||
board.the_board[move->move_row][move->move_col].visibility == 4 || !ValidAction(board, *move, *action));
}
|
C
|
#include "cc.h"
int pos = 0;
int code_pos = 0;
Token tokens[100];
void tokenize(char *p) {
int i = 0;
while(*p){
if (isspace(*p)){
p++;
continue;
}
if(*p == '+' || *p == '-' || *p == '*' || *p == '/' || *p == '(' || *p == ')' || *p == '=' || *p == ';' ){
tokens[i].ty = *p;
tokens[i].input = p;
i++;
p++;
continue;
}
if(isdigit(*p)){
tokens[i].ty = TK_NUM;
tokens[i].input = p;
tokens[i].val = strtol(p, &p, 10);
i++;
continue;
}
if(*p >= 'a' && *p <= 'z')
{
tokens[i].ty = TK_IDENT;
tokens[i].input = p;
i++;
p++;
continue;
}
fprintf(stderr, "cannot tokenize: %s\n", p);
exit(1);
}
tokens[i].ty = TK_EOF;
tokens[i].input = p;
}
Node *new_node(int ty, Node *lhs, Node *rhs){
Node *node = malloc(sizeof(Node));
node->ty = ty;
node->lhs = lhs;
node->rhs = rhs;
return node;
}
Node *new_node_num(int val){
Node *node = malloc(sizeof(Node));
node->ty = ND_NUM;
node->val = val;
return node;
}
Node *new_node_ident(char name){
Node *node = malloc(sizeof(Node));
node->ty = ND_IDENT;
node->name = name;
return node;
}
Node *term(){
if(tokens[pos].ty == TK_NUM)
return new_node_num(tokens[pos++].val);
if(tokens[pos].ty == TK_IDENT)
return new_node_ident(*tokens[pos++].input);
if(tokens[pos].ty == '(')
{
pos++;
Node *node = expr();
if(tokens[pos].ty != ')')
error(*tokens[pos].input);
pos++;
return node;
}
error(*tokens[pos].input);
return NULL;
}
Node *expr() {
Node *lhs = mul();
if(tokens[pos].ty == '+'){
pos++;
return new_node('+', lhs, expr());
}
if(tokens[pos].ty == '-'){
pos++;
return new_node('-', lhs, expr());
}
return lhs;
}
Node *mul(){
Node *lhs = term();
if(tokens[pos].ty == '*'){
pos++;
return new_node('*', lhs, mul());
}
if(tokens[pos].ty == '/'){
pos++;
return new_node('/', lhs, mul());
}
return lhs;
}
void program(){
if(tokens[pos].ty == TK_EOF)
{
code[code_pos] = NULL;
return;
}
Node *lhs = assign();
code[code_pos] = lhs;
code_pos++;
program();
}
Node* assign(){
Node *lhs = expr();
if(tokens[pos].ty == '='){
pos++;
return new_node('=', lhs, assign());
}
if(tokens[pos].ty == ';'){
pos++;
return lhs;
} else {
fprintf(stderr, "not found semicolon.\n");
exit(EXIT_FAILURE);
}
error(*tokens[pos].input);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void change_ptr(int * const );
int main(void)
{
int var1 = 0, var2 = 0;
/* the ptr is const, not the data */
int * const ptr = &var1;
/* ptr = &var2; */
change_ptr(&var1);
printf("%d\n", *ptr);
return EXIT_SUCCESS;
}
void change_ptr(int * const ptr)
{
*ptr=42;
}
|
C
|
/*
============================================================================
Name : PrefixSums.c //SERIAL
Author : David Katz
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
/*-------------------------------------------------------------------
* SERIAL VERSION of the prefix sums function
* Guides the user in building an array.
* First asks the user to choose a size, and then asks the user to
* fill the array with values.
* Once the array is created, the array of prefix sums is printed.
*/
int* calculatePrefix(int size, int *arr);
void printPrefixSums(int size, int *arr);
int main(void) {
printf("Let's calculate the prefix sum for an array of your choosing.\n");
printf("Choose an array size: ");
int size;
scanf("%d", &size);
int *arr = malloc(size);
for (int i=0; i<size; i++) {
printf("Provide a value for index %d of your array: ", i);
int num;
scanf("%d", &num);
arr[i] = num;
}
int* r = calculatePrefix(size, arr);
printPrefixSums(size, r);
return EXIT_SUCCESS;
}
/*-------------------------------------------------------------------
* Function: calculatePrefix
* Purpose: Calculate the prefix values for an array
* In args: int size: the size of the argued array
* int *arr: the array of values to calculate the prefix
* sums for
* Outputs: Returns the array of prefix sums
*/
int* calculatePrefix(int size, int *arr) {
int *psums = malloc(size);
for (int i=0; i<size; i++) {
int t=0;
for (int j=0; j<=i; j++) {
t += arr[j];
}
psums[i] = t;
}
return psums;
}
/*-------------------------------------------------------------------
* Function: printPrefixSums
* Purpose: print the values of an array of prefix sums
* In args: int size: the size of the argued array
* int *arr: the array of values to print the values of
* Outputs: No returned output
*/
void printPrefixSums(int size, int *arr) {
printf("Printing the prefix sums of your array:\n");
for (int p=0; p<size; p++) {
printf("ps[%d] = %d \n", p, arr[p]);
}
}
|
C
|
#pragma once
#include "gc.h"
#include "header.h"
/// This header:
/// struct Map;
/// Map*map_insert(Map*,SinObj*,SinObj*);
/// SinObj*map_keys(Map*);
/// SinObj*map_get(Map*,SinObj*);
extern "C" {
/// Map is defined as a linked list of keys and values.
/// Not hashed at all, thats too hard... Oh well.
typedef struct Map {
Map* next;
SinObj* key;
SinObj* value;
} Map;
Map* insert_update(Map* m, SinObj* k, SinObj* v);
Map* insert_copy(Map* m);
Map* map_insert(Map* m, SinObj* k, SinObj* v);
SinObj* map_keys(Map* m);
SinObj* map_get(Map* m, SinObj* key);
bool map_has_key(Map* m, SinObj* key);
u64 map_count(Map* m);
// hash hash-keys hash-ref hash-set
Map* insert_update(Map* m, SinObj* k, SinObj* v) {
if (m == nullptr) {
// made it all the way through the map and didnt find the val
// So just add the entry to update at the end of the map.
Map* final_val = reinterpret_cast<Map*>(GC_MALLOC(sizeof(Map)));
final_val->next = nullptr;
final_val->key = k;
final_val->value = v;
return final_val;
}
Map* new_map = reinterpret_cast<Map*>(GC_MALLOC(sizeof(Map)));
if (eq_helper(m->key, k) == 1) {
new_map->key = k;
new_map->value = v;
// dont need to check for an update anymore
new_map->next = insert_copy(m->next);
} else {
new_map->key = m->key;
new_map->value = m->value;
// need to keep looking for the value to update.
new_map->next = insert_update(m->next, k, v);
}
return new_map;
}
// Shallowly copies each element into a new Map*.
Map* insert_copy(Map* m) {
if (m == nullptr) {
return nullptr;
}
Map* new_map = reinterpret_cast<Map*>(GC_MALLOC(sizeof(Map)));
new_map->key = m->key;
new_map->value = m->value;
new_map->next = insert_copy(m->next);
return new_map;
}
/// Inserts an Entry into the map m.
Map* map_insert(Map* m, SinObj* k, SinObj* v) {
return insert_update(m, k, v);
}
/// Returns a Vector SinObj
/// Where the 0th spot is the size, and the others are the keys.
SinObj* map_keys(Map* m) {
if (m == nullptr) {
return const_init_null();
}
SinObj* car = (m->key);
SinObj* cdr = map_keys(m->next);
SinObj* cons = prim_cons(car, cdr);
return cons;
}
/// Returns a SinObj that is the value of the map.
/// If the key is not found, nullptr is returned.
SinObj* map_get(Map* m, SinObj* key) {
while (m != nullptr) {
if (eq_helper(key, m->key) == 1) {
return m->value;
}
m = m->next;
}
return nullptr;
}
bool map_has_key(Map* m, SinObj* key) {
while (m != nullptr) {
if (eq_helper(m->key, key) == 1) {
return true;
}
m = m->next;
}
return false;
}
u64 map_count(Map* m) {
u64 count = 0;
while (m != nullptr) {
count++;
m = m->next;
}
return count;
}
} // end extern "C"
|
C
|
#include <stdio.h>
#include <string.h>
#include <uloop.h>
void f1_cb(struct uloop_timeout *t)
{
int msec = 1000;
printf("%s: %d\n", __func__, msec);
uloop_timeout_cancel(t);
}
void f2_cb(struct uloop_timeout *t)
{
int msec = 2000;
printf("%s: %d\n", __func__, msec);
uloop_timeout_set(t, msec);
}
void f3_cb(struct uloop_timeout *t)
{
int msec = 3000;
printf("%s: %d\n", __func__, msec);
uloop_timeout_set(t, msec);
}
void f4_cb(struct uloop_timeout *t __attribute__((unused)))
{
printf("%s: cancel uloop\n", __func__);
uloop_end();
}
int main(void)
{
struct uloop_timeout f1, f2, f3, f4;
memset(&f1, 0, sizeof(f1));
f1.cb = f1_cb;
memset(&f2, 0, sizeof(f2));
f2.cb = f2_cb;
memset(&f3, 0, sizeof(f3));
f3.cb = f3_cb;
memset(&f4, 0, sizeof(f4));
f4.cb = f4_cb;
uloop_init();
uloop_timeout_set(&f1, 1000);
uloop_timeout_set(&f2, 2000);
uloop_timeout_set(&f3, 3000);
uloop_timeout_set(&f4, 10000);
printf("f1 remaining time: %d\n", uloop_timeout_remaining(&f1));
uloop_run();
uloop_done();
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
struct node
{ int info;
struct node *next;
}*start;
void main(){
int ch;
clrscr();
printf("A Program By CHANPREET SINGH");
printf("\n\t\t\tMAIN MENU");
printf("\n\t\t\t1 Create a linked list");
printf("\n\t\t\t2 Insert into linked list");
printf("\n\t\t\tDelete from linked list");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch){
case 1:
}
getch();
}
|
C
|
#include<stdio.h>
void towers(int n, char a, char b, char c)
{
if (n == 1)
{
printf("\Muta discul 1 de pe tija %c pe tija %c", a, b);
return;
}
towers(n - 1, a, c, b);
printf("\nMuta discul %d de pe tija %c pe tija %c", n, a, b);
towers(n - 1, c, b, a);
}
int main()
{
int nr;
printf("nr:");
scanf("%d", &nr);
printf("The sequence of moves involved in the Tower of Hanoi are:\n");
towers(nr, 'A', 'B', 'C');
return 0;
}
|
C
|
#include "Scheduler.h"
Semaphore *s_hello;
int main()
{
scheduler = new RoundRobinScheduler();
s_hello = new Semaphore(0);
scheduler->start(new Thread(hello, NULL));
scheduler->start(new Thread(world, NULL));
// three threads are active now!
scheduler->running->wait_all();
delete scheduler; // optional
}
void hello()
{
printf("Hello, ");
s_hello->signal();
}
void world()
{
s_hello->wait();
printf("World!\n");
}
|
C
|
/* Copyright (C) 2016 Evan Christensen
|
| 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. */
#pragma once
#include "MoeTypes.h"
#include <limits.h>
struct BigInt // tag = bint
{
BigInt()
:m_nAbs(0)
,m_fIsNegative(false)
{ ; }
s64 S64Coerce() const
{
MOE_ASSERT(m_nAbs <= LLONG_MAX, "int too large to be signed value");
if (m_fIsNegative)
return -(s64)m_nAbs;
return (s64)m_nAbs;
}
u64 U64Coerce() const
{
MOE_ASSERT(!m_fIsNegative, "negative value being coerced into an unsigned value");
return m_nAbs;
}
u64 m_nAbs;
bool m_fIsNegative;
};
inline BigInt BintFromInt(s64 nSigned)
{
BigInt bint;
bint.m_nAbs = llabs(nSigned);
bint.m_fIsNegative = nSigned < 0;
return bint;
}
inline BigInt BintFromUint(u64 nUnsigned, bool fIsNegative = false)
{
BigInt bint;
bint.m_nAbs = nUnsigned;
bint.m_fIsNegative = fIsNegative;
return bint;
}
inline bool FAreEqual(const BigInt & bintLhs, const BigInt & bintRhs)
{
bool fIsAbsSame = bintLhs.m_nAbs == bintRhs.m_nAbs;
bool fIsSignSame = bintLhs.m_fIsNegative == bintRhs.m_fIsNegative;
fIsSignSame |= (fIsAbsSame & (bintLhs.m_nAbs == 0));
return fIsAbsSame & fIsSignSame;
}
// NOTE: I'm opting away from operator overloading for Signed65 because I want it to be explicit
inline BigInt BintAdd(const BigInt & bintLhs, const BigInt & bintRhs)
{
u64 nLhs = bintLhs.m_nAbs;
u64 nRhs = bintRhs.m_nAbs;
if (bintLhs.m_fIsNegative == bintRhs.m_fIsNegative)
{
return BintFromUint(nLhs + nRhs, bintLhs.m_fIsNegative);
}
// one of the operands is negative, if it's the larger one the result is negative
if (nLhs > nRhs)
{
return BintFromUint(nLhs - nRhs, bintLhs.m_fIsNegative);
}
return BintFromUint(nRhs - nLhs, bintRhs.m_fIsNegative);
}
inline BigInt BintSub(const BigInt & bintLhs, const BigInt & bintRhs)
{
u64 nLhs = bintLhs.m_nAbs;
u64 nRhs = bintRhs.m_nAbs;
bool fIsRhsNegative = !bintRhs.m_fIsNegative;
if (bintLhs.m_fIsNegative == fIsRhsNegative)
{
return BintFromUint(nLhs + nRhs, bintLhs.m_fIsNegative);
}
// one of the operands is negative, if it's the larger one the result is negative
if (nLhs > nRhs)
{
return BintFromUint(nLhs - nRhs, bintLhs.m_fIsNegative);
}
return BintFromUint(nRhs - nLhs, fIsRhsNegative);
}
inline BigInt BintMul(const BigInt & bintLhs, const BigInt & bintRhs)
{
return BintFromUint(bintLhs.m_nAbs * bintRhs.m_nAbs, bintLhs.m_fIsNegative != bintRhs.m_fIsNegative);
}
inline BigInt BintDiv(const BigInt & bintLhs, const BigInt & bintRhs)
{
return BintFromUint(bintLhs.m_nAbs / bintRhs.m_nAbs, bintLhs.m_fIsNegative != bintRhs.m_fIsNegative);
}
inline BigInt BintRemainder(const BigInt & bintLhs, const BigInt & bintRhs)
{
// NOTE: The sign of c++'s % operator is determined by the sign of the numerator:
// % is defined as: a == (a/b) * b + a%b, where a/b truncates towards zero.
// so with a - (a/b)*b == a%b we know that (a/b)*b is smaller than a, thus a determines the sign.
return BintFromUint(bintLhs.m_nAbs % bintRhs.m_nAbs, bintLhs.m_fIsNegative);
}
inline u64 NTwosCompliment(u64 n, bool fIsNegative)
{
return (fIsNegative) ? (~n + 1) : n;
}
inline BigInt BintBitwiseOr(const BigInt & bintLhs, const BigInt & bintRhs)
{
u64 nLhs = NTwosCompliment(bintLhs.m_nAbs, bintLhs.m_fIsNegative);
u64 nRhs = NTwosCompliment(bintRhs.m_nAbs, bintRhs.m_fIsNegative);
bool fIsOutNegative = bintLhs.m_fIsNegative | bintRhs.m_fIsNegative;
u64 nOut = NTwosCompliment(nLhs | nRhs, fIsOutNegative);
return BintFromUint(nOut, fIsOutNegative);
}
inline BigInt BintBitwiseAnd(const BigInt & bintLhs, const BigInt & bintRhs)
{
u64 nLhs = NTwosCompliment(bintLhs.m_nAbs, bintLhs.m_fIsNegative);
u64 nRhs = NTwosCompliment(bintRhs.m_nAbs, bintRhs.m_fIsNegative);
bool fIsOutNegative = bintLhs.m_fIsNegative & bintRhs.m_fIsNegative;
u64 nOut = NTwosCompliment(nLhs & nRhs, fIsOutNegative);
return BintFromUint(nOut, fIsOutNegative);
}
inline BigInt BintBitwiseNot(const BigInt & bintOp)
{
u64 nLhs = NTwosCompliment(bintOp.m_nAbs, bintOp.m_fIsNegative);
bool fIsOutNegative = !bintOp.m_fIsNegative;
u64 nOut = NTwosCompliment(~nLhs, fIsOutNegative);
return BintFromUint(nOut, fIsOutNegative);
}
inline BigInt BintBitwiseXor(const BigInt & bintLhs, const BigInt & bintRhs)
{
u64 nLhs = NTwosCompliment(bintLhs.m_nAbs, bintLhs.m_fIsNegative);
u64 nRhs = NTwosCompliment(bintRhs.m_nAbs, bintRhs.m_fIsNegative);
bool fIsOutNegative = bintLhs.m_fIsNegative ^ bintRhs.m_fIsNegative;
u64 nOut = NTwosCompliment(nLhs ^ nRhs, fIsOutNegative);
return BintFromUint(nOut, fIsOutNegative);
}
inline BigInt BintShiftRight(const BigInt & bintLhs, const BigInt & bintRhs)
{
u64 nLhs = NTwosCompliment(bintLhs.m_nAbs, bintLhs.m_fIsNegative);
if (bintRhs.m_fIsNegative)
{
return BintFromUint(NTwosCompliment(nLhs << bintRhs.m_nAbs, bintLhs.m_fIsNegative), bintLhs.m_fIsNegative);
}
else if (!bintLhs.m_fIsNegative)
{
return BintFromUint(nLhs >> bintRhs.m_nAbs, false);
}
else
{
u64 nSignExtend = (bintRhs.m_nAbs > 0) ? 0xFFFFFFFFFFFFFFFF << (64 - bintRhs.m_nAbs) : 0; // shift right by 64 bits is undefined behavior (doesn't work on x64)
return BintFromUint(NTwosCompliment((nLhs >> bintRhs.m_nAbs) | nSignExtend, bintLhs.m_fIsNegative), bintLhs.m_fIsNegative);
}
}
inline BigInt BintShiftLeft(const BigInt & bintLhs, const BigInt & bintRhs)
{
u64 nLhs = NTwosCompliment(bintLhs.m_nAbs, bintLhs.m_fIsNegative);
if (bintRhs.m_fIsNegative)
{
u64 nSignExtend = (bintLhs.m_fIsNegative) ? 0x8000000000000000 : 0;
return BintFromUint(NTwosCompliment((nLhs >> bintRhs.m_nAbs) | nSignExtend, bintLhs.m_fIsNegative), bintLhs.m_fIsNegative);
}
else
{
return BintFromUint(NTwosCompliment(nLhs << bintRhs.m_nAbs, bintLhs.m_fIsNegative), bintLhs.m_fIsNegative);
}
}
inline BigInt BintNextPowerOfTwo(const BigInt & bint)
{
u64 n = bint.m_nAbs; // compute the next highest power of 2 of 32-bit v
// smear the bits down and then add one
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n |= n >> 32;
n++;
return BintFromUint(n);
}
inline bool operator ==(const BigInt & bintLhs, const BigInt & bintRhs)
{
return (bintLhs.m_nAbs == bintRhs.m_nAbs) & (bintLhs.m_fIsNegative == bintRhs.m_fIsNegative);
}
inline bool operator !=(const BigInt & bintLhs, const BigInt & bintRhs)
{
return !(bintLhs == bintRhs);
}
inline bool operator<(const BigInt & bintLhs, const BigInt & bintRhs)
{
if (bintLhs.m_fIsNegative != bintRhs.m_fIsNegative)
return bintLhs.m_fIsNegative;
return (bintLhs.m_nAbs < bintRhs.m_nAbs) != bintLhs.m_fIsNegative;
}
inline bool operator<=(const BigInt & bintLhs, const BigInt & bintRhs)
{
return (bintLhs == bintRhs) | (bintLhs < bintRhs);
}
inline bool operator >(const BigInt & bintLhs, const BigInt & bintRhs)
{
return !(bintLhs <= bintRhs);
}
inline bool operator >=(const BigInt & bintLhs, const BigInt & bintRhs)
{
return !(bintLhs < bintRhs);
}
|
C
|
#include<stdio.h>
int main()
{
int x=0;
int y=0;
printf("enter the x");
scanf("%d\n",&x);
printf("enter the y");
scanf("%d\n",&y) ;
return 0;
}
|
C
|
#include "fitz-internal.h"
#define MAX4(a,b,c,d) fz_max(fz_max(a,b), fz_max(c,d))
#define MIN4(a,b,c,d) fz_min(fz_min(a,b), fz_min(c,d))
/* Matrices, points and affine transformations */
const fz_matrix fz_identity = { 1, 0, 0, 1, 0, 0 };
fz_matrix
fz_concat(fz_matrix one, fz_matrix two)
{
fz_matrix dst;
dst.a = one.a * two.a + one.b * two.c;
dst.b = one.a * two.b + one.b * two.d;
dst.c = one.c * two.a + one.d * two.c;
dst.d = one.c * two.b + one.d * two.d;
dst.e = one.e * two.a + one.f * two.c + two.e;
dst.f = one.e * two.b + one.f * two.d + two.f;
return dst;
}
fz_matrix
fz_scale(float sx, float sy)
{
fz_matrix m;
m.a = sx; m.b = 0;
m.c = 0; m.d = sy;
m.e = 0; m.f = 0;
return m;
}
fz_matrix
fz_shear(float h, float v)
{
fz_matrix m;
m.a = 1; m.b = v;
m.c = h; m.d = 1;
m.e = 0; m.f = 0;
return m;
}
fz_matrix
fz_rotate(float theta)
{
fz_matrix m;
float s;
float c;
while (theta < 0)
theta += 360;
while (theta >= 360)
theta -= 360;
if (fabs(0 - theta) < FLT_EPSILON)
{
s = 0;
c = 1;
}
else if (fabs(90.0f - theta) < FLT_EPSILON)
{
s = 1;
c = 0;
}
else if (fabs(180.0f - theta) < FLT_EPSILON)
{
s = 0;
c = -1;
}
else if (fabs(270.0f - theta) < FLT_EPSILON)
{
s = -1;
c = 0;
}
else
{
s = sin(theta * (float)M_PI / 180);
c = cos(theta * (float)M_PI / 180);
}
m.a = c; m.b = s;
m.c = -s; m.d = c;
m.e = 0; m.f = 0;
return m;
}
fz_matrix
fz_translate(float tx, float ty)
{
fz_matrix m;
m.a = 1; m.b = 0;
m.c = 0; m.d = 1;
m.e = tx; m.f = ty;
return m;
}
fz_matrix
fz_invert_matrix(fz_matrix src)
{
float det = src.a * src.d - src.b * src.c;
if (det < -FLT_EPSILON || det > FLT_EPSILON)
{
fz_matrix dst;
float rdet = 1 / det;
dst.a = src.d * rdet;
dst.b = -src.b * rdet;
dst.c = -src.c * rdet;
dst.d = src.a * rdet;
dst.e = -src.e * dst.a - src.f * dst.c;
dst.f = -src.e * dst.b - src.f * dst.d;
return dst;
}
return src;
}
int
fz_is_rectilinear(fz_matrix m)
{
return (fabs(m.b) < FLT_EPSILON && fabs(m.c) < FLT_EPSILON) ||
(fabs(m.a) < FLT_EPSILON && fabs(m.d) < FLT_EPSILON);
}
float
fz_matrix_expansion(fz_matrix m)
{
return sqrt(fabs(m.a * m.d - m.b * m.c));
}
float
fz_matrix_max_expansion(fz_matrix m)
{
float max = fabs(m.a);
float x = fabs(m.b);
if (max < x)
max = x;
x = fabs(m.c);
if (max < x)
max = x;
x = fabs(m.d);
if (max < x)
max = x;
return max;
}
fz_point
fz_transform_point(fz_matrix m, fz_point p)
{
fz_point t;
t.x = p.x * m.a + p.y * m.c + m.e;
t.y = p.x * m.b + p.y * m.d + m.f;
return t;
}
fz_point
fz_transform_vector(fz_matrix m, fz_point p)
{
fz_point t;
t.x = p.x * m.a + p.y * m.c;
t.y = p.x * m.b + p.y * m.d;
return t;
}
/* Rectangles and bounding boxes */
const fz_rect fz_infinite_rect = { 1, 1, -1, -1 };
const fz_rect fz_empty_rect = { 0, 0, 0, 0 };
const fz_rect fz_unit_rect = { 0, 0, 1, 1 };
const fz_bbox fz_infinite_bbox = { 1, 1, -1, -1 };
const fz_bbox fz_empty_bbox = { 0, 0, 0, 0 };
const fz_bbox fz_unit_bbox = { 0, 0, 1, 1 };
#define SAFE_INT(f) ((f > INT_MAX) ? INT_MAX : ((f < INT_MIN) ? INT_MIN : (int)f))
fz_bbox
fz_bbox_covering_rect(fz_rect f)
{
fz_bbox i;
f.x0 = floor(f.x0);
f.y0 = floor(f.y0);
f.x1 = ceil(f.x1);
f.y1 = ceil(f.y1);
i.x0 = SAFE_INT(f.x0);
i.y0 = SAFE_INT(f.y0);
i.x1 = SAFE_INT(f.x1);
i.y1 = SAFE_INT(f.y1);
return i;
}
fz_bbox
fz_round_rect(fz_rect f)
{
fz_bbox i;
f.x0 = floor(f.x0 + 0.001);
f.y0 = floor(f.y0 + 0.001);
f.x1 = ceil(f.x1 - 0.001);
f.y1 = ceil(f.y1 - 0.001);
i.x0 = SAFE_INT(f.x0);
i.y0 = SAFE_INT(f.y0);
i.x1 = SAFE_INT(f.x1);
i.y1 = SAFE_INT(f.y1);
return i;
}
fz_rect
fz_intersect_rect(fz_rect a, fz_rect b)
{
fz_rect r;
if (fz_is_infinite_rect(a)) return b;
if (fz_is_infinite_rect(b)) return a;
if (fz_is_empty_rect(a)) return fz_empty_rect;
if (fz_is_empty_rect(b)) return fz_empty_rect;
r.x0 = fz_max(a.x0, b.x0);
r.y0 = fz_max(a.y0, b.y0);
r.x1 = fz_min(a.x1, b.x1);
r.y1 = fz_min(a.y1, b.y1);
return (r.x1 < r.x0 || r.y1 < r.y0) ? fz_empty_rect : r;
}
fz_rect
fz_union_rect(fz_rect a, fz_rect b)
{
fz_rect r;
if (fz_is_infinite_rect(a)) return a;
if (fz_is_infinite_rect(b)) return b;
if (fz_is_empty_rect(a)) return b;
if (fz_is_empty_rect(b)) return a;
r.x0 = fz_min(a.x0, b.x0);
r.y0 = fz_min(a.y0, b.y0);
r.x1 = fz_max(a.x1, b.x1);
r.y1 = fz_max(a.y1, b.y1);
return r;
}
fz_bbox
fz_intersect_bbox(fz_bbox a, fz_bbox b)
{
fz_bbox r;
if (fz_is_infinite_rect(a)) return b;
if (fz_is_infinite_rect(b)) return a;
if (fz_is_empty_rect(a)) return fz_empty_bbox;
if (fz_is_empty_rect(b)) return fz_empty_bbox;
r.x0 = fz_maxi(a.x0, b.x0);
r.y0 = fz_maxi(a.y0, b.y0);
r.x1 = fz_mini(a.x1, b.x1);
r.y1 = fz_mini(a.y1, b.y1);
return (r.x1 < r.x0 || r.y1 < r.y0) ? fz_empty_bbox : r;
}
fz_bbox
fz_union_bbox(fz_bbox a, fz_bbox b)
{
fz_bbox r;
if (fz_is_infinite_rect(a)) return a;
if (fz_is_infinite_rect(b)) return b;
if (fz_is_empty_rect(a)) return b;
if (fz_is_empty_rect(b)) return a;
r.x0 = fz_mini(a.x0, b.x0);
r.y0 = fz_mini(a.y0, b.y0);
r.x1 = fz_maxi(a.x1, b.x1);
r.y1 = fz_maxi(a.y1, b.y1);
return r;
}
fz_rect
fz_transform_rect(fz_matrix m, fz_rect r)
{
fz_point s, t, u, v;
if (fz_is_infinite_rect(r))
return r;
s.x = r.x0; s.y = r.y0;
t.x = r.x0; t.y = r.y1;
u.x = r.x1; u.y = r.y1;
v.x = r.x1; v.y = r.y0;
s = fz_transform_point(m, s);
t = fz_transform_point(m, t);
u = fz_transform_point(m, u);
v = fz_transform_point(m, v);
r.x0 = MIN4(s.x, t.x, u.x, v.x);
r.y0 = MIN4(s.y, t.y, u.y, v.y);
r.x1 = MAX4(s.x, t.x, u.x, v.x);
r.y1 = MAX4(s.y, t.y, u.y, v.y);
return r;
}
fz_bbox
fz_transform_bbox(fz_matrix m, fz_bbox b)
{
fz_point s, t, u, v;
if (fz_is_infinite_bbox(b))
return b;
s.x = b.x0; s.y = b.y0;
t.x = b.x0; t.y = b.y1;
u.x = b.x1; u.y = b.y1;
v.x = b.x1; v.y = b.y0;
s = fz_transform_point(m, s);
t = fz_transform_point(m, t);
u = fz_transform_point(m, u);
v = fz_transform_point(m, v);
b.x0 = MIN4(s.x, t.x, u.x, v.x);
b.y0 = MIN4(s.y, t.y, u.y, v.y);
b.x1 = MAX4(s.x, t.x, u.x, v.x);
b.y1 = MAX4(s.y, t.y, u.y, v.y);
return b;
}
|
C
|
int test(int a, int b) {
int x = 1 / a;
int i, j;
for (i = 0; i < b; i++) {
j = j + x;
}
return j;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* redirections_2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user42 <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/14 11:50:43 by user42 #+# #+# */
/* Updated: 2020/12/16 17:22:55 by user42 ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/minishell.h"
void update_cmd(char **cmd, int i, int flag)
{
if (flag)
{
free(cmd[i]);
if (cmd[i + 1])
{
free(cmd[i + 1]);
cmd[i] = cmd[i + 2];
}
else
cmd[i] = NULL;
cmd[i + 1] = NULL;
}
}
int handle_min_sup(char **cmd, int i, int flag)
{
int fd;
if (ft_strequ(cmd[i], "<>") && cmd[i + 1] && !ft_strchr(cmd[i + 1], '>')
&& !ft_strchr(cmd[i + 1], '<'))
{
if ((fd = open(cmd[i + 1], O_CREAT | O_RDWR | O_APPEND, 0644)) < 0)
{
ft_error("minishell: syntax error near unexpected token `newline'",
NULL, 2, NULL);
flag == 1 ? exit(EXIT_FAILURE) : 0;
}
else
close(fd);
update_cmd(cmd, i, flag);
return (1);
}
return (0);
}
|
C
|
/***********************************************************************
/
/ SUBTRACT MASS FROM STAR AFTER FEEDBACK
/
/ written by: Ji-hoon Kim
/ date: January, 2010
/ modified1:
/
/ PURPOSE: Currently this file is not being used; now the functionality
/ of this file has moved to
/
/ MBH_THERMAL -> no need to do this because EjectaDensity = 0
/ MBH_JETS -> now done in Grid_AddFeedbackSphere.C
/
************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "ErrorExceptions.h"
#include "macros_and_parameters.h"
#include "typedefs.h"
#include "global_data.h"
#include "Fluxes.h"
#include "GridList.h"
#include "ExternalBoundary.h"
#include "Grid.h"
#include "Hierarchy.h"
#include "CosmologyParameters.h"
#include "TopGridData.h"
#include "LevelHierarchy.h"
#include "phys_constants.h"
int FindField(int field, int farray[], int numfields);
int GetUnits(float *DensityUnits, float *LengthUnits,
float *TemperatureUnits, float *TimeUnits,
float *VelocityUnits, FLOAT Time);
int Star::RemoveMassFromStarAfterFeedback(float &Radius, double &EjectaDensity,
float DensityUnits, float LengthUnits,
int &CellsModified)
{
double old_mass;
/* Check if the star type is correct */
if ((ABS(this->type) != MBH) ||
(this->FeedbackFlag != MBH_THERMAL && this->FeedbackFlag != MBH_JETS))
return SUCCESS;
/* Check if there really was a feedback; this is crucial for MBH_JETS
because if the jet mass doesn't exceed the threshold it won't do any feedback */
if (EjectaDensity != 0 ||
CellsModified == 0 ||
this->CurrentGrid == NULL)
return SUCCESS;
float BubbleVolume = (4.0 * pi / 3.0) * Radius * Radius * Radius;
old_mass = this->Mass;
// printf("star::RMFSAF: before: old_mass = %lf\n", old_mass);
// printf("star::RMFSAF: vel = %"FSYM" %"FSYM" %"FSYM"\n",
// this->vel[0], this->vel[1], this->vel[2]);
/* Now let's start working! Because we injected the mass in Grid_AddFeedbackSphere,
we should subtract the mass from the star */
switch (this->FeedbackFlag) {
case MBH_THERMAL:
//this actually would not do anything because EjectaDensity = 0 for MBH_THERMAL
//unless one changes the current scheme - Ji-hoon Kim, Jan.2010
this->Mass -= EjectaDensity * DensityUnits * BubbleVolume * pow(LengthUnits,3.0) / SolarMass;
break;
case MBH_JETS:
//remove the mass; and now that we injected the NotEjectedMass, set it to zero
this->Mass -= this->NotEjectedMass;
this->NotEjectedMass = 0.0;
break;
} //ENDSWITCH
/* Because the mass is subtracted out with zero net momentum,
increase the velocity accordingly */
this->vel[0] *= old_mass / this->Mass;
this->vel[1] *= old_mass / this->Mass;
this->vel[2] *= old_mass / this->Mass;
// printf("star::RMFSAF: after : this->Mass = %lf\n", this->Mass);
// printf("star::RMFSAF: vel = %"FSYM" %"FSYM" %"FSYM"\n",
// this->vel[0], this->vel[1], this->vel[2]);
return SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
#define TRUE 1
#define FALSE 0
#define Maxsize 20
typedef int ElemType;
typedef struct {
ElemType Data[Maxsize];
ElemType length;
} SqList;
typedef int Status;
Status GetElem(SqList L, int i, ElemType *e){
if(L.length < i || L.length == 0 || i < 1)
return ERROR;
*e = L.Data[i-1];
return 0;
}
Status ListInsert(SqList *L, int i, ElemType e){
int p;
if(L->length > Maxsize || L->length + 1 < i || i < 1)
return ERROR;
if(i <= L->length){
for(p = L.length-1; p >= i-1; p--)
L->Data[p+1] = L->Data[p];
}
L->Data[i-1] = e;
L->length++;
return 0;
}
Status ListDelete(SqList *L, int i, ElemType *e){
int p;
if(L->length < i || i < 1 || L->length == 0)
return ERROR;
*e = L->Data[i-1];
if(i != L->length){
for(p = i-1; p < L->length-1; p++)
L->Data[p] = L->Data[p+1];
}
L->length--;
return 0;
}
int UnionL(List *La, List Lb){
int lengtha, lengthb, i;
ElemType e;
lengtha = ListLength(*La);
lengthb = ListLength(Lb);
for( i=1; i <= lengthb; i++){
GetElem(Lb, i, &e);
if(!LocateElem(La,e)){
ListInsert(La, ++lengtha, e);
}
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "main.h"
typedef unsigned char byte;
typedef int error_code;
#define ERROR (-1)
#define HAS_ERROR(code) ((code) < 0)
#define HAS_NO_ERROR(code) ((code) >= 0)
/**
* Cette fonction compare deux chaînes de caractères.
* @param p1 la première chaîne
* @param p2 la deuxième chaîne
* @return le résultat de la comparaison entre p1 et p2. Un nombre plus petit que
* 0 dénote que la première chaîne est lexicographiquement inférieure à la deuxième.
* Une valeur nulle indique que les deux chaînes sont égales tandis qu'une valeur positive
* indique que la première chaîne est lexicographiquement supérieure à la deuxième.
*/
int strcmp(char *p1, char *p2) {
char *s1 = (char *) p1;
char *s2 = (char *) p2;
char c1, c2;
do {
c1 = (char) *s1++;
c2 = (char) *s2++;
if (c1 == '\0')
return c1 - c2;
} while (c1 == c2);
return c1 - c2;
}
/**
* Ex. 1: Calcul la longueur de la chaîne passée en paramètre selon
* la spécification de la fonction strlen standard
* @param s un pointeur vers le premier caractère de la chaîne
* @return le nombre de caractères dans le code d'erreur, ou une erreur
* si l'entrée est incorrecte
*/
error_code strlen2(char *s) {
int i = 0;
while(s[i] != '\0'){
i++;
}
return i;
}
/**
* Ex.2 :Retourne le nombre de lignes d'un fichier sans changer la position
* courante dans le fichier.
* @param fp un pointeur vers le descripteur de fichier
* @return le nombre de lignes, ou -1 si une erreur s'est produite
*/
error_code no_of_lines(FILE *fp) {
int no_lines = 1;
fpos_t pos;
fgetpos(fp, &pos);
int char_read = fgetc(fp);
if (fp == NULL){
no_lines = -1;
} else if(char_read == EOF){
no_lines = 0;
} else {
while (char_read != EOF){
if (char_read == '\n'){
no_lines++;
}
char_read = fgetc(fp);
}
}
fsetpos(fp, &pos);
return no_lines;
}
/**
* Ex.3: Lit une ligne au complet d'un fichier
* @param fp le pointeur vers la ligne de fichier
* @param out le pointeur vers la sortie
* @param max_len la longueur maximale de la ligne à lire
* @return le nombre de caractère ou ERROR si une erreur est survenue
*/
error_code readline(FILE *fp, char **out, size_t max_len) {
int no_chars = 0;
char *line = malloc(sizeof(char) * max_len+2);
if (!fp) {
return ERROR;
} else {
char car = fgetc(fp);
while (car != EOF && car != '\n') {
line[no_chars] = car;
no_chars++;
car = fgetc(fp);
}
line[no_chars] = '\0';
*out = line;
}
return no_chars;
}
/**
* Ex.4: Copie un bloc mémoire vers un autre
* @param dest la destination de la copie
* @param src la source de la copie
* @param len la longueur (en byte) de la source
* @return nombre de bytes copiés ou une erreur s'il y a lieu
*/
error_code memcpy2(void *dest, void *src, size_t len) {
//code inspiré de geeksforgeeks.org/write-memcpy
//commentaire pour commit
char *d = dest;
char *s = src;
int no_bytes = 0;
for(int i=0; i<len; i++){
d[i] = s[i];
no_bytes++;
}
return no_bytes;
}
/**
* Ex.5: Analyse une ligne de transition
* @param line la ligne à lire
* @param len la longueur de la ligne
* @return la transition ou NULL en cas d'erreur
*/
transition *parse_line(char *line, size_t len) {
//Si la ligne n'est pas une transition, on retourne null
if (len < 3) {
return NULL;
} else {
transition *resultat = malloc( sizeof(transition) );
if(!resultat){
return NULL;
}
int head = 1; //on skip le premier char, qui est un '('
int tail;
for( tail = 2 ; tail <= 6 ; tail++){
if( *(line+tail) == ',' ){
char *current_state_read = malloc(sizeof(char)*(tail-head+1));
if(!current_state_read){
return NULL;
}
//le -1 c'est pour ne pas compter le char ','
current_state_read[tail-head] = '\0';
memcpy2(current_state_read,(line+head),tail-head);
resultat->current_state = current_state_read;
break;
}
}
tail++; //on passe au prochain char "read"
resultat->read = line[tail];
tail += 5;
head = tail;
for( tail++ ; tail-head <= 5 ; tail++){
if( *(line+tail) == ',' ){
char *next_state_read = malloc(sizeof(char)*(tail-head+1));
if(!next_state_read){
return NULL;
}
//le -1 c'est pour ne pas compter le char ','
next_state_read[tail-head] = '\0';
memcpy2(next_state_read,(line+head),tail-head);
resultat->next_state = next_state_read;
break;
}
}
tail++;
resultat->write = line[tail];
tail += 2;
char move;
if(line[tail] == 'D') {
move = 1;
}else if(line[tail] == 'G'){
move = -1;
} else {
move = 0;
}
resultat->movement = move;
return resultat;
}
}
/* Fonction qui copie un ruban et double la taille
*
* */
char *doubler(char *ruban, int length){
char *temp = malloc(sizeof(char)*length);
memcpy2(temp, ruban, length);
char *newptr = realloc(ruban, length*2);
if(!newptr){
return NULL;
} else {
ruban = newptr;
}
memcpy2(ruban, temp, length);
for (int i = length; i<(2*length); i++){
ruban[length] = ' ' ;
}
free(temp);
return ruban;
}
/**
* Ex.6: Execute la machine de turing dont la description est fournie
* @param machine_file le fichier de la description
* @param input la chaîne d'entrée de la machine de turing
* @return le code d'erreur
*/
error_code execute(char *machine_file, char *input) {
FILE *fp = fopen(machine_file, "r");
if(!fp){
return ERROR;
}
int no_lines = no_of_lines(fp);
int length_word = strlen2(input);
if(length_word == 0){
length_word = 1;
};
char *ruban = malloc((sizeof(char)*2*length_word));
if(!ruban){
fclose(fp);
return ERROR;
}
memcpy2(ruban, input, length_word);
doubler(ruban , length_word);
transition *table_transition[no_lines-3];
char **str_temp = malloc(sizeof(char *));
if(!str_temp){
fclose(fp);
free(ruban);
return ERROR;
}
char *current = malloc (sizeof (char)*4);
if(!current){
fclose(fp);
free(ruban);
free(str_temp);
return ERROR;
}
for (int i=0; i<no_lines; i++){
readline(fp, str_temp, 19);
if(i<3 && i>0){
continue;
}else if(i==0){
memcpy2(current, *str_temp, 3);
current[2] = '\0';
}else {
int len = strlen2(*str_temp);
table_transition[i-3] = parse_line(*str_temp, len);
}
free(*str_temp);
}
free(str_temp);
fclose(fp);
transition *current_trans;
char read_char;
int position = 0;
while(position > -1 && strcmp(current, "R") && strcmp(current, "A")){
read_char = ruban[position];
for (int i=0; i<no_lines-3; i++){
transition *dum = table_transition[i];
if(!strcmp((dum->current_state), current)){
if(((dum->read) == read_char) || (dum->read == ' ' && read_char==0)){
current_trans = dum;
break;
}
}
}
if(!current_trans){
return ERROR;
}
free(current);
current = current_trans->next_state;
ruban[position] = current_trans->write;
int movement = (int)(current_trans->movement);
position = position + movement;
current_trans = NULL;
if(position >= (length_word)){
char current_char = ruban[position];
length_word = length_word*2;
ruban = doubler(ruban, length_word);
if(!ruban){
for(int i = no_lines-4; i>=0; i--){
char *current_state_f = table_transition[i]->current_state;
char *next_state_f = table_transition[i]->next_state;
table_transition[i]->read = '0';
table_transition[i]->write = '0';
table_transition[i]->movement = '0';
free(table_transition[i]);
table_transition[i] = NULL;
free(current_state_f);
free(next_state_f);
}
free(table_transition);
return ERROR;
} else {
ruban[position] = current_char;
}
for(int i=(position+1); i<(length_word*2); i++){
ruban[i] = ' ';
}
}
}
char *final_state = malloc(sizeof(char)*5);
int lenfinal_state = strlen2(current);
memcpy2(final_state, current, lenfinal_state);
final_state[lenfinal_state] = '\0';
free(ruban);
for (int i=(no_lines-4); i>=10; i--){
char *current_state_f = table_transition[i]->current_state;
char *next_state_f = table_transition[i]->next_state;
table_transition[i]->read = '0';
table_transition[i]->write = '0';
table_transition[i]->movement = '0';
free(table_transition[i]);
table_transition[i] = NULL;
free(current_state_f);
free(next_state_f);
}
for(int i=8; i>0; i--){
if(i%3 == 0 && i!=0){
free(table_transition[i]);
table_transition[i] = NULL;
} else {
char *current_state_f = table_transition[i]->current_state;
char *next_state_f = table_transition[i]->next_state;
table_transition[i]->read = '0';
table_transition[i]->write = '0';
table_transition[i]->movement = '0';
free(table_transition[i]);
table_transition[i] = NULL;
free(current_state_f);
free(next_state_f);
}
}
error_code ret;
if(!strcmp("R", final_state)){
ret = HAS_ERROR(-1);
} else if(!strcmp("A", final_state)) {
ret = HAS_NO_ERROR(1);
} else {
ret = ERROR;
}
free(final_state);
return ret;
}
// ATTENTION! TOUT CE QUI EST ENTRE LES BALISES ༽つ۞﹏۞༼つ SERA ENLEVÉ! N'AJOUTEZ PAS D'AUTRES ༽つ۞﹏۞༼つ
// ༽つ۞﹏۞༼つ
int main() {
// ous pouvez ajouter des tests pour les fonctions ici
char *temp = "22";
printf("%d", strlen2(temp));
printf("\n");
FILE *fp = fopen("../five_lines", "r");
printf("%d", no_of_lines(fp));
fclose(fp);
printf("\n");
FILE *fp2 = fopen("../six_lines", "r");
printf("%d", no_of_lines(fp2));
fclose(fp2);
printf("\n");
char **str = malloc(sizeof (char*));
FILE *fp3 = fopen("../five_lines", "r");
printf("%d", readline(fp3, str, 10));
printf("\n");
printf("%s", *str);
free(*str);
free(str);
fclose(fp3);
printf("\n");
char *before = malloc(sizeof(char) * 19);
char *after = "bbbbbbbbbbbbbbbbb";
memcpy2(before, after, 19);
printf("%s", before);
free(before);
printf("\n");
printf("\n");
int val = execute("../youre_gonna_go_far_kid", " ");
printf("%d", val);
return 0;
}
// ༽つ۞﹏۞༼つ
|
C
|
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <stdlib.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 100;
// Number of words
long word_count = 0;
bool loaded = false;
// Hash table
node *table[N];
// Node variables
node *n;
node *cursor;
node *tmp;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int h = hash(word);
bool found = false;
cursor = malloc(sizeof(node));
if (cursor == NULL)
{
return false;
}
cursor->word[0] = '\0';
cursor->next = table[h];
while(cursor->next != NULL)
{
if (strcasecmp(word, cursor->word))
{
found = true;
break;
}
else
{
cursor = cursor->next;
}
}
free(cursor);
return found;
}
// Hashes word to a number
// Hash function: first two letters
unsigned int hash(const char *word)
{
int sum = 0;
int len = strlen(word);
for (int i = 0; i < len; i++)
{
sum += tolower(word[i]);
}
return sum % N;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
char scan[LENGTH];
FILE *dict = fopen(dictionary, "r");
if (dict == NULL)
{
return false;
}
n = malloc(sizeof(node));
if (n == NULL)
{
return false;
}
tmp = malloc(sizeof(node));
if (tmp == NULL)
{
return false;
}
// Read strings from file "one at a time"
while(fscanf(dict, "%s", scan) != EOF)
{
strcpy(n->word, scan);
n->next = NULL;
// Hash word to obtain a hash value
int h = hash(n->word);
// Insert node to hash table at that location
if (table[h] == NULL)
{
table[h] = n;
}
else
{
tmp->next = n;
n->next = table[h]->next;
table[h]->next = n;
tmp->next = NULL;
}
word_count++;
}
fclose(dict);
free(tmp);
loaded = true;
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
long s = 0;
if (loaded == true)
{
s = word_count;
}
else
{
s = 0;
}
return s;
}
// Unloads dictionary from memory, returning true if successful else false
// DEBUGGING THIS FUNCTION TO COMPLETE ALL
bool unload(void)
{
long loop = 0;
for (int i = 0; i < N; i++)
{
cursor = table[i];
tmp = table[i];
while(cursor != NULL)
{
cursor = cursor->next;
tmp->next = NULL;
tmp = cursor;
}
}
free(n);
free(tmp);
free(cursor);
return true;
}
|
C
|
#include "bsp_adc.h"
__IO uint16_t ADC_ConvertedValue[5]={0,0,0,0,0};
float ADC_Value[5];
/**
* @brief ADC GPIO ʼ
* @param
* @retval
*/
static void ADCx_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
// ADC IO˿ʱ
ADC_GPIO_APBxClock_FUN ( ADC_GPIO_CLK, ENABLE );
// ADC IO ģʽ
// Ϊģ
GPIO_InitStructure.GPIO_Pin = ADC_PIN0|ADC_PIN1|ADC_PIN2|ADC_PIN3|ADC_PIN4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
// ʼ ADC IO
GPIO_Init(ADC_PORT, &GPIO_InitStructure);
}
/**
* @brief ADCģʽ
* @param
* @retval
*/
static void ADCx_Mode_Config(void)
{
ADC_InitTypeDef ADC_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
// ADCʱ
ADC_APBxClock_FUN ( ADC_CLK, ENABLE );
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
DMA_DeInit(ADC_DMA_CHANNEL);
// DMA ʼṹ
// ַΪADC ݼĴַ
DMA_InitStructure.DMA_PeripheralBaseAddr = ( u32 ) ( & ( ADC1->DR ) );
// 洢ַ
DMA_InitStructure.DMA_MemoryBaseAddr = (u32)ADC_ConvertedValue;
// Դ
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
// СӦõĿĵصĴС
DMA_InitStructure.DMA_BufferSize = 5;
// Ĵֻһַõ
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
// 洢ַ
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
// ݴСΪֽ֣
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
// ڴݴСҲΪ֣ݴСͬ
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
// ѭģʽ
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
// DMA ͨȼΪߣʹһDMAͨʱȼòӰ
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
// ֹ洢洢ģʽΪǴ赽洢
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
// ʼDMA
DMA_Init(ADC_DMA_CHANNEL, &DMA_InitStructure);
// ʹ DMA ͨ
DMA_Cmd(ADC_DMA_CHANNEL , ENABLE);
// ADC ģʽ
// ֻʹһADCڶģʽ
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
// ֹɨģʽͨҪͨҪ
ADC_InitStructure.ADC_ScanConvMode = ENABLE ;
// תģʽ
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
// ⲿת
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
// תҶ
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
// תͨ1
ADC_InitStructure.ADC_NbrOfChannel = 5;
// ʼADC
ADC_Init(ADCx, &ADC_InitStructure);
// ADCʱΪPCLK28Ƶ9MHz
RCC_ADCCLKConfig(RCC_PCLK2_Div8);
// ADC ͨת˳Ͳʱ
ADC_RegularChannelConfig(ADCx, ADC_CHANNEL0, 0, ADC_SampleTime_55Cycles5);
ADC_RegularChannelConfig(ADCx, ADC_CHANNEL1, 1, ADC_SampleTime_55Cycles5);
ADC_RegularChannelConfig(ADCx, ADC_CHANNEL2, 2, ADC_SampleTime_55Cycles5);
ADC_RegularChannelConfig(ADCx, ADC_CHANNEL3, 3, ADC_SampleTime_55Cycles5);
ADC_RegularChannelConfig(ADCx, ADC_CHANNEL4, 4, ADC_SampleTime_55Cycles5);
// ʹADC DMA
ADC_DMACmd(ADCx, ENABLE);
// // ADC תжϣжϷжȡתֵ
// ADC_ITConfig(ADCx, ADC_IT_EOC, ENABLE);
// ADC ʼת
ADC_Cmd(ADCx, ENABLE);
// ʼADC УĴ
ADC_ResetCalibration(ADCx);
// ȴУĴʼ
while(ADC_GetResetCalibrationStatus(ADCx));
// ADCʼУ (ȷȵĹϵ ҪУ)
ADC_StartCalibration(ADCx);
// ȴУ
while(ADC_GetCalibrationStatus(ADCx));
// ûвⲿʹADCת
ADC_SoftwareStartConvCmd(ADCx, ENABLE);
}
/**
* @brief ADCʼ
* @param
* @retval
*/
void ADCx_Init(void)
{
ADCx_GPIO_Config();
ADCx_Mode_Config();
}
|
C
|
#ifndef LCD_H_
#define LCD_H_
#define DL_4 0
#define DL_8 1
#define ONE_LINE 0
#define TWO_LINE 1
#define FONT_SMALL 0
#define FONT_BIG 1
//LCD_voidInit
//Initiate LCD as per configuration in lcd_config.h
//return:
void LCD_voidInit();
//LCD_voidClrDisp
//Clear LCD display
//return:
void LCD_voidClrDisp();
//LCD_voidWriteChar
//Write a single character to the display
//ch: the character to be written
//return:
void LCD_voidWriteChar(uint8_t ch);
//LCD_voidWriteStr
//Write a null terminated string to the display
//str: pointer to the first character in the string to be written
//return:
void LCD_voidWriteStr(uint8_t *str);
//LCD_voidRetHome
//Place the cursor at the beginning of the display
//return:
void LCD_voidRetHome();
//LCD_voidSetPos
//Place the cursor at desired position
//line: the desired line, either 0 or 1
//col: the desired position in the line, 0 to 15
//return:
void LCD_voidSetPos(uint8_t line, uint8_t col);
#endif /* LCD_H_ */
|
C
|
#include <stdio.h>
/***
1. Sum of all numbers less than or equal to n and also co-prime to n = (phi(n) * n) / 2
2. Lagrange's Polnomial:
A polynomial of degree n can be uniquely represented and evaluated from it's value in n + 1 distinct points (x_i, y_i)
For the function f(x) = x ^2, given three points
x_0 = 1, f(x_0) = 1
x_1 = 2, f(x_1) = 4
x_2 = 3, f(x_2) = 9
The interpolating polynomial is:
1*(x-2)(x-3) + 4*(x-1)(x-3) + 9*(x-1)(x-2)
L(x) = ---------- ---------- ---------- = x^2
(1-2)(1-3) (2-1)(2-3) (3-1)(3-2)
3. Eulerian Numbers, E(n, k): Number of permutations from 1 to n such that
P_i < P_(i+1) (or P_i > P_(i + 1) since symmetric) in exactly k positions.
Recurrence: E(n, k) = (k+1)E(n - 1, k) + (n - k)(n - 1, k - 1)
***/
int main(){
}
|
C
|
//
// main.c
// Labs
//
// Created by Warren Seto on 1/23/17.
// Copyright © 2017 Warren Seto. All rights reserved.
//
#include "types.h"
#include "stat.h"
#include "user.h"
void outputPrimeFactor(int* input);
int pid;
int main(int argc, const char * argv[])
{
// Declare an integer to find its prime factors
int numChildren =3;
int forkReturn;
for(int i = 1; i <=numChildren; i++){
//create children
forkReturn = fork();
if(forkReturn == 0){//child
break;//do not create more children
}
}
int startTime = uptime();
pid = getpid();
int num = 30000000;//suitably long enough to see effects of round robin scheduler
printf(2, "\nGCD(%d) The prime factorization of %d = \n", pid,num);
// Call the outputPrimeFactor procedure with the address of the desired integer
outputPrimeFactor(&num);
if(forkReturn > 0){
for(int i = 1; i <=numChildren;i++)
wait();
}
printf(2, "\nGCD(%d) finished.\n",pid);
int endTime = uptime();
printf(2, "\nGCD(%d) time: %d.\n",pid, endTime-startTime);
exit();
}
/** Displays the prime factors for a given integer input */
void outputPrimeFactor(int* input)
{
// Counter variable to conrol the loops
int count;
//"For" loop for finding the prime factors
for (count = 2; count <= (*input); count++) //This will count from 2 to the inputted number
{
while ((*input) % count == 0) //It will check if the inputted number and count is divisible, then loop the statement if is true
{
(*input) = (*input) / count; //This will divide the number by count
if ((*input) / count >= 1) //This will add the time symbol, when the expression is greater to or equal to one
{
printf(2, "GCD(%d): %d x ", pid, count);
}
else //If (num / count < 0) is true, then show the last number in the statement
{
printf(2, "GCD(%d): %d x ", pid, count);
}
}
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
struct acl_entry {int dummy; } ;
struct acl {int acl_cnt; int /*<<< orphan*/ * acl_entry; } ;
typedef TYPE_1__* acl_t ;
struct TYPE_3__ {scalar_t__ ats_cur_entry; struct acl ats_acl; } ;
/* Variables and functions */
int ACL_MAX_ENTRIES ;
int /*<<< orphan*/ EINVAL ;
int /*<<< orphan*/ bzero (int /*<<< orphan*/ *,int) ;
int /*<<< orphan*/ errno ;
int
acl_delete_entry_np(acl_t acl, int offset)
{
struct acl *acl_int;
int i;
if (acl == NULL) {
errno = EINVAL;
return (-1);
}
acl_int = &acl->ats_acl;
if (offset < 0 || offset >= acl_int->acl_cnt) {
errno = EINVAL;
return (-1);
}
if ((acl->ats_acl.acl_cnt < 1) ||
(acl->ats_acl.acl_cnt > ACL_MAX_ENTRIES)) {
errno = EINVAL;
return (-1);
}
/* ...shift the remaining entries... */
for (i = offset; i < acl->ats_acl.acl_cnt - 1; ++i)
acl->ats_acl.acl_entry[i] =
acl->ats_acl.acl_entry[i+1];
/* ...drop the count and zero the unused entry... */
acl->ats_acl.acl_cnt--;
bzero(&acl->ats_acl.acl_entry[i],
sizeof(struct acl_entry));
acl->ats_cur_entry = 0;
return (0);
}
|
C
|
/*
* Autor: Cristobal Liendo I.
* Fecha: 09/10/17
* Descripcion: Parametros de funciones
*/
#include <stdio.h>
int cuadrado(int);
int main() {
int numero, resultado;
numero = 5;
resultado = cuadrado(numero);
printf("El cuadrado del numero es %d", resultado);
printf(" y el de 3 es %d\n", cuadrado(3));
return 0;
}
int cuadrado(int n) {
return n * n;
}
|
C
|
//Realizar programa para controlar varias bibliotecas usando estructuras dentro de estructuras
#include<stdio.h>
#include<string.h>
#define N 50
typedef struct{
char nombre[N];
char autor[N];
int lleno;
}libro;
typedef struct{
libro lib[10];
char nombre[N];
int lleno;
}biblioteca;
biblioteca bi[3];
void anadebi();
void anadeli();
void consulta();
void vacio();
int main()
{
int op;
char elegir;
vacio();
op=0;
do{
elegir='N';
do{
printf("Elige una opcion a realizar: \n");
printf("(1)Aadir una nueva biblioteca\n");
printf("(2)Aadir un nuevo libro\n");
printf("(3)Consultar libro\n");
printf("(4)Salir\n");
scanf("%i",&op);
}while(op<1 || op>4);
switch(op){
case 1: {
anadebi();
break;
}
case 2:{
anadeli();
break;
}
case 3:{
consulta();
break;
}
}
printf("\nQuiere hacer alguna otra consulta?(S/N): ");
fflush(stdin);
scanf("%c",&elegir);
op=0;
system("cls");
}while(elegir=='S' || elegir=='s');
system("pause");
return 0;
}
void vacio() //inicializamos las bibliotecas y los libros de las mismas
{
int i, j;
for(i=0;i<3;i++)
{
bi[i].lleno=0;
for(j=0;j<10;j++)
{
bi[i].lib[j].lleno=0;
}
}
}
void anadebi() //Aadimos biblioteca con su respectivo nombre
{
int i, aux;
aux=0;
for(i=0;i<3 && aux==0;i++)
{
if(bi[i].lleno==0)
{
printf("Introduce un nombre a la biblioteca: ");
fflush(stdin);
fgets(bi[i].nombre,N,stdin);
bi[i].lleno=1;
aux=1;
}
}
if(aux==0)
{
printf("SORRY! No queda ningun hueco libre para la biblioteca\n");
}
}
void anadeli() //Vamos a aadir libro
{
int i, j, aux, aux2, op;
aux=0;
aux2=0;
for(i=0;bi[i].lleno==1 && i<3;i++) //aqu solo queremos saber si existe alguna biblioteca
{
if(bi[i].lleno==1)
{
printf("\n%i %s",i+1, bi[i].nombre);
aux2=1;
}
}
if(aux2==1) //si existe alguna vamos a aadir libro
{
printf("\nEn que biblioteca lo aadimos?");
fflush(stdin);
scanf("%i", &op);
for(i=0;i<3 && aux==0;i++)
{
if(op-1==i)
{
for(j=0;j<10 && aux==0;j++) //recorremos los 10 huecos que tenemos para aadir en el que est libre nuestro libro
{
if(bi[i].lib[j].lleno==0)
{
printf("\nIntroduce un nombre del libro: ");
fflush(stdin);
fgets(bi[i].lib[j].nombre,N,stdin);
printf("\nIntroduce el nombre del autor: ");
fflush(stdin);
fgets(bi[i].lib[j].autor,N,stdin);
bi[i].lib[j].lleno=1;
aux=1;
}
}
}
}
if(aux==0)
{
printf("SORRY! No queda ningun hueco libre para el libro\n");
}
}
else
{
printf("\nNo existe ninguna biblioteca\n");
}
}
void consulta()
{
int op, i, j, aux, aux2;
char palabra[N];
aux=0;
aux2=0;
for(i=0;i<3 && aux2==0;i++) //recorremos los vectores para ver si existen libros en nuestras bibliotecas
{
for(j=0;j<10 && aux2==0;j++)
{
if(bi[i].lib[j].lleno==1)
{
aux2=1;
}
}
}
if(aux2==1)
{
do
{
printf("\nQue quieres buscar: ");
printf("\n(1)Por Nombre libro?");
printf("\n(2)Por Nombre de autor?");
scanf("%i",&op);
switch(op){
case 1:{
printf("\nIntroduce el nombre del libro: ");
fflush(stdin);
fgets(palabra,N,stdin);
for(i=0;i<3 && aux==0;i++)
{
for(j=0;j<10 && aux==0;j++)
{
if(strcmp(palabra,bi[i].lib[j].nombre)==0) //compara palabras entre strings devolviendo 0 en caso de que lo encuentre
{
printf("\nEl libro %s se encuentra en la biblioteca %s", palabra, bi[i].nombre);
aux=1;
}
}
}
break;
}
case 2:{
printf("\nIntroduce el nombre del autor: ");
fflush(stdin);
fgets(palabra,N,stdin);
for(i=0;i<3 && aux==0;i++)
{
for(j=0;j<10 && aux==0;j++)
{
if(strcmp(palabra,bi[i].lib[j].autor)==0)
{
printf("\nEl libro %s se encuentra en la biblioteca %s", bi[i].lib[j].nombre, bi[i].nombre);
aux=1;
}
}
}
break;
}
}
}while(op<1 || op>2);
}
else
{
printf("\nNo insertaste ningun libro");
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<time.h>
int thread_num;
long long int number_of_tosses,batch;
long long int number_in_circle[5];
void* toss(void * bank)
{
long mybank=(long)bank;
long long int sample_num=0;
long long int i=0;
srand(time(NULL));
unsigned seed=rand();
long long int rMax = RAND_MAX/2;
long long int rMaxsquare = rMax*rMax;
long long int x,y;
for(;i<batch;i++)
{
x = rand_r(&seed)-rMax;
y = rand_r(&seed)-rMax;
if(x*x+y*y<=rMaxsquare)
{
sample_num++;
}
}
number_in_circle[mybank]+=sample_num;
return NULL;
}
int main(int argc,char* argv[])
{
long thread;
double pi;
thread_num=get_nprocs();
int i=0;
for(;i<thread_num;i++)
number_in_circle[i]=0;
number_of_tosses=strtoll(argv[1],NULL,10);
batch=number_of_tosses/thread_num;
pthread_t* handler;
handler=malloc(thread_num*sizeof(pthread_t));
for(thread=0;thread<thread_num;thread++)
pthread_create(&handler[thread],NULL,toss,(void*)thread);
//thrad join
for(thread=0;thread<thread_num;thread++)
pthread_join(handler[thread],NULL);
i=1;
for(;i<thread_num;i++)
number_in_circle[0]+=number_in_circle[i];
pi=4*number_in_circle[0]/(double)number_of_tosses;
free(handler);
printf("pi:%f\n",pi);
return 0;
}
|
C
|
#ifndef _SYS_FUTEX_H
#define _SYS_FUTEX_H
#include <sys/types.h>
typedef struct {
/* futex ID */
long id;
/*
* val==0 - futex free
* val==1 - futex locked, but noone is waiting
* val==2 - futex locked, someone is waiting
*/
short val;
} futex_t;
/* Futex initialize and destroy functions */
_PROTOTYPE( int futex_init, (futex_t *futex));
_PROTOTYPE( int futex_destroy, (futex_t *futex));
/* Lock and unlock futex */
_PROTOTYPE( int futex_lock, (futex_t *futex));
_PROTOTYPE( int futex_unlock, (futex_t *futex));
#endif /* _SYS_FUTEX_H */
|
C
|
#include <stdio.h>
int main() {
int dividers[] = {3, 5, 7, 13};
char messages[4][10] = {"Fizz", "Buzz", "Tapioca", "Kefir"};
for (int i = 1; i <= 100; i++) {
int dividerExist = 0;
for (int j = 0; j < 4; j++) {
if (i % dividers[j] == 0) {
printf("%s", messages[j]);
dividerExist = 1;
}
}
if (dividerExist == 0) {
printf("%d", i);
}
printf("\n");
}
return 0;
}
|
C
|
#include "Handlers.h"
#include "estructuras.h"
#include "globales.h"
extern cpSpace * modChipmunk_cpEspacio;
extern int modChipmunk_Crear;
extern modChipmunkStruct_nodo * modChipmunk_ListaHandlers;
typedef struct {int a,b;} modChipmunkStruct_param2d;
modChipmunkStruct_param2d modChipmunkParam(int a,int b){
modChipmunkStruct_param2d v;
v.a=a;
v.b=b;
return v;
}
int compara(void *a, void* bp){
modChipmunkStruct_param2d* am=a;
Hands* bm=bp;
if ((am->a == bm->a && am->b == bm->b) || (am->b == bm->a && am->a == bm->b))
return 1;
return 0;
}
int modChipmunkBeginCall(cpArbiter *arb, struct cpSpace *space, void *data){
int ret=1;
INSTANCE * r ;
Hands * d=data;
r = instance_new ((d->funciones)[0], 0) ; // Create Function
PRIDWORD(r, 0) = (int)arb ; // Argument 1
PRIDWORD(r, 4) = (d->parametros)[0] ; // Argument 2
ret = instance_go(r) ; // Call Function
return ret;
}
int modChipmunkPreSolveCall(cpArbiter *arb, struct cpSpace *space, void *data){
int ret=1;
INSTANCE * r ;
Hands * d=data;
r = instance_new ((d->funciones)[1], 0) ; // Create Function
PRIDWORD(r, 0) = (int)arb ; // Argument 1
PRIDWORD(r, 4) = (d->parametros)[1] ; // Argument 2
ret = instance_go(r) ; // Call Function
return ret;
}
void modChipmunkPostSolveCall(cpArbiter *arb, struct cpSpace *space, void *data){
INSTANCE * r ;
Hands * d=data;
r = instance_new ((d->funciones)[2], 0) ; // Create Function
PRIDWORD(r, 0) = (int)arb ; // Argument 1
PRIDWORD(r, 4) = (d->parametros)[2] ; // Argument 2
instance_go(r) ; // Call Function
}
void modChipmunkSeparateCall(cpArbiter *arb, struct cpSpace *space, void *data){
INSTANCE * r ;
Hands * d=data;
r = instance_new ((d->funciones)[3], 0) ; // Create Function
PRIDWORD(r, 0) = (int)arb ; // Argument 1
PRIDWORD(r, 4) = (d->parametros)[3] ; // Argument 2
instance_go(r) ; // Call Function
}
Hands * modChipmunkNuevoHandler(){
Hands * h=malloc(sizeof(Hands));
memset(h->funciones,0,sizeof(PROCDEF *)*4); //setear enteros
memset(h->parametros,0,sizeof(void *)*4);
return h;
}
void modChipmunkFalloHandler(int * params,Hands * h){
string_discard(params[2]);
string_discard(params[3]);
string_discard(params[4]);
string_discard(params[5]);
free (h);
}
int modcpSpaceAddCollisionHandler(INSTANCE * my, int * params){
modChipmunkStruct_param2d par=modChipmunkParam(params[0], params[1]);
if (LLbusca(modChipmunk_ListaHandlers, &par, compara)){
printf("Se intent crear un handler a (%d, %d), pero ya existe uno \n",params[0],params[1]);
return -1;
}
Hands * handler = modChipmunkNuevoHandler();
char * begins = string_get(params[2]);
char * preSolves = string_get(params[3]);
char * postSolves = string_get(params[4]);
char * separates = string_get(params[5]);
modChipmunk_mayusStr(begins);
modChipmunk_mayusStr(preSolves);
modChipmunk_mayusStr(postSolves);
modChipmunk_mayusStr(separates);
handler->a=params[0];
handler->b=params[1];
PROCDEF * proc;
if (strlen(begins)!=0){
proc = procdef_get_by_name (begins); // Get definition function (name must be in uppercase)
if (!proc)
{
printf ("Funcin %s no encontrada\n", begins) ;
modChipmunkFalloHandler(params,handler);
return -1 ;
}
handler->funciones[0]=proc;
handler->parametros[0]=(void *)params[6];
}else{
handler->funciones[0]=NULL;
handler->parametros[0]=NULL;
}
if (strlen(preSolves)!=0){
proc = procdef_get_by_name (preSolves); // Get definition function (name must be in uppercase)
if (!proc)
{
printf ("Funcin %s no encontrada\n", preSolves) ;
modChipmunkFalloHandler(params,handler);
return -1 ;
}
handler->funciones[1]=proc;
handler->parametros[1]=(void *)params[7];
}else{
handler->funciones[1]=NULL;
handler->parametros[1]=NULL;
}
if (strlen(postSolves)!=0){
proc = procdef_get_by_name (postSolves); // Get definition function (name must be in uppercase)
if (!proc)
{
printf ("Funcin %s no encontrada\n", postSolves) ;
modChipmunkFalloHandler(params,handler);
return -1 ;
}
handler->funciones[2]=proc;
handler->parametros[2]=(void *)params[8];
}else{
handler->funciones[2]=NULL;
handler->parametros[2]=NULL;
}
if (strlen(separates)!=0){
proc = procdef_get_by_name (separates); // Get definition function (name must be in uppercase)
if (!proc)
{
printf ("Funcin %s no encontrada\n", separates) ;
modChipmunkFalloHandler(params,handler);
return -1 ;
}
handler->funciones[3]=proc;
handler->parametros[3]=(void *)params[9];
}else{
handler->funciones[3]=NULL;
handler->parametros[3]=NULL;
}
cpSpaceAddCollisionHandler(
modChipmunk_cpEspacio,
handler->a,handler->b,
handler->funciones[0]? modChipmunkBeginCall : NULL, //si la string es null, poner null, de lo contrario poner beginCall
handler->funciones[1]? modChipmunkPreSolveCall : NULL,
handler->funciones[2]? modChipmunkPostSolveCall : NULL,
handler->funciones[3]? modChipmunkSeparateCall : NULL,
(void *)handler
);
string_discard(params[2]);
string_discard(params[3]);
string_discard(params[4]);
string_discard(params[5]);
LLagrega(modChipmunk_ListaHandlers,handler);
return 1;
}
int modcpSpaceRemoveCollisionHandler(INSTANCE * my, int * params){
//cpSpaceRemoveCollisionHandler(modChipmunk_cpEspacio, params[0], params[1],funcionElmHand);
modChipmunkStruct_param2d par=modChipmunkParam(params[0], params[1]);
LLelimina(modChipmunk_ListaHandlers, &par, compara,funcionElmHand,1);
return 1;
}
void funcionElmHand(void * v){
Hands * h=v;
cpSpaceRemoveCollisionHandler(modChipmunk_cpEspacio, h->a, h->b);
free (h);
}
void recogeColisionHandler(cpArbiter *arb, cpSpace *space, void *dat)
{
modChipmunkStruct_colHand* col= (modChipmunkStruct_colHand*)dat;
cpArray* arr= col->arr;
CP_ARBITER_GET_SHAPES(arb, a, b);
cpContactPointSet set = cpArbiterGetContactPointSet(arb);
cpContactPointSetM * setM =(cpContactPointSetM*) malloc(sizeof(cpContactPointSetM));
int i;
for (i=0; i<set.count; i++)
{
setM->points[i].Point.x=set.points[i].point.x;
setM->points[i].Point.y=set.points[i].point.y;
setM->points[i].normal.x=set.points[i].normal.x;
setM->points[i].normal.y=set.points[i].normal.y;
setM->points[i].dist=set.points[i].dist;
}
setM->count=set.count;
DataPointer dato=(DataPointer)a->body->data;
if (dato)
setM->id1=dato->father;
else
setM->id1=0;
setM->shape1=a;
dato=(DataPointer)b->body->data;
if (dato)
setM->id2=dato->father;
else
setM->id2;
setM->shape2=b;
modChipmunk_ArregloPush(arr, setM);
//printf("%p",setM);
}
void buscaABCol(void *ptr, void *data)
{
modChipmunkStruct_colHand* cla=(modChipmunkStruct_colHand*) ptr;
int * arr=(int *)data;
if (cla->a==arr[0] && cla->b==arr[1])
{
modChipmunk_Crear=0;
}
}
int modcrearHandler(INSTANCE * my, int * params)
{
modChipmunk_Crear=1;
int par[2];
par[0]=params[0];
par[1]=params[1];
modChipmunk_arregloItera(HandlerColisions, buscaABCol, &par);
if (!modChipmunk_Crear)
return 0;
cpArray* arr=modChipmunk_nuevoArreglo(10);
cpArray* arr2=modChipmunk_nuevoArreglo(10);
modChipmunkStruct_colHand* col= malloc(sizeof(modChipmunkStruct_colHand));
col->arr=arr;
col->colisiones=arr2;
col->a=params[0];
col->b=params[1];
modChipmunk_ArregloPush(HandlerColisions, col);
cpSpaceAddCollisionHandler(modChipmunk_cpEspacio, params[0], params[1], NULL, NULL, recogeColisionHandler, NULL, col);
return (int) col;
}
int modremoveHandler(INSTANCE * my, int * params)
{
modChipmunkStruct_colHand* col=(modChipmunkStruct_colHand*)params[0];
cpSpaceRemoveCollisionHandler(modChipmunk_cpEspacio, col->a, col->b);
cpArrayDeleteObj(HandlerColisions, col);
// modChipmunk_arregloItera(col->arr, (cpArrayIter)eliminaContactPointSetM, NULL);
modChipmunk_destruyeArreglo(&col->arr,1);
//modChipmunk_arregloItera(col->colisiones, (cpArrayIter)eliminaContactPointSetM, NULL);
modChipmunk_destruyeArreglo(&col->colisiones,1);
free(col);
return 0;
}
|
C
|
/*
* Queue.h
*
* Created on: Apr 9, 2019
* Author: WINNGUYEN
*/
#ifndef QUEUE_H_
#define QUEUE_H_
#include <msp430.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 16
typedef int bool;
#define true 1
#define false 0
#define FULL_KEY 2
#define EMPTY_KEY false
#define SUCCESS_KEY true
struct Queue
{
char *buffer;
int rear, front;
int numChar;
int size;
};
struct Queue createQueue(int);
bool isEmpty(const struct Queue*);
bool isFull(const struct Queue*);
uint16_t enqueue(struct Queue*,char);
uint16_t dequeue(struct Queue*,char*);
#endif /* QUEUE_H_ */
|
C
|
/*
* TWI_Funcoes.c
*
* Created: 17/01/2018 14:35:23
* Author: Henrique
*/
#include "TWI_Header.h"
int nCounter = 0;
// funo para iniciar o SCL ou o clock de oscilao
void initTWI(void)
{
// para calcular o Two Wire Bit Rate, usar a seguinte formula:
// SCL frequency = CPU Clock frequency / 16 + 2*(TWBR) * PrescalerValue
//TWSR = 0; // sem prescaler
TWBR = 72; // para setar a velocidade de transferncia
// habilitar o TWI
TWCR |= (1 << TWEN);
}
// funo para o TWI aguardar a sua transferncia de dados
uint8_t TwiAguardar(void)
{
while(!(TWCR & (1 << TWINT))){
nCounter++;
if(nCounter > AGUARDO_TWI)
{
nCounter = 0; // zerar o contador
return 0; // retorno 0 - indica erro de envio de dados
}
}
nCounter = 0;
return 1;
}
// comear a transferncia de dados
uint8_t TwiStart(uint8_t nEndereco) {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTA);
if(!TwiAguardar()) // deu erro de aguardo?
{ // erro
SerialPrintString("Erro Start!\n");
return 0;
}
// acessar o registrador com o endereo x em modo de escrita
TwiWrite(nEndereco);
return 1;
}
void TwiStop(void)
{
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
}
int TwiReadAck(void) {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
if(!TwiAguardar()) // deu erro de aguardo?
{ // erro
SerialPrintString("Erro TwiReadAck!\n");
return 0;
}
return (TWDR);
}
int TwiReadNAck(void) {
TWCR = (1 << TWINT) | (1 << TWEN);
if(!TwiAguardar()) // deu erro de aguardo?
{ // erro
SerialPrintString("Erro TwiReadNAck!\n");
return 0;
}
return (TWDR);
}
uint8_t TwiWrite(uint8_t data) {
TWDR = data;
TWCR = (1 << TWINT) | (1 << TWEN); /* iniciar e habilitar */
if(!TwiAguardar()) // deu erro de aguardo?
{ // erro
SerialPrintString("Erro TwiWrite!\n");
return 0;
}
return 1;
}
|
C
|
/*
author: Joselito_Junior
date: 14/10/2017
version: 1.0
Descrição: Essa uma implementação simples de uma fila sequencial circular
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 5
// Tipo base dos elementos da lista
typedef struct elementos{
char nome[50];
}t_elemento;
typedef struct fila{
t_elemento vetor[MAX];
int inicio;
int fim;
int qtd_elements;
}t_fila;
//////FUNÇÔES DE MANIPULAÇÂO DA PILHA///////////
t_fila criar_fila();
int is_vazia_fila(t_fila * fila);
int is_cheia_fila(t_fila * fila);
int inserir_fila(t_fila * fila, t_elemento elemento);
t_elemento remover_fila(t_fila * fila);
void exibir_fila(t_fila * fila);
int exibicao_ordenada_fila(t_fila * fila);
/////////////FUNÇOES DE GERENCIAMENTO//////////
int menu_principal(t_fila * fila);
int saida_fila(t_fila * fila)
{
int opcao = 0;
t_elemento chamado;
printf("\nDeseja chamar o primeiro da fila? \n");
printf("1 - SIM\n");
printf("0 - NAO\n");
printf("Digite: ");
scanf("%d", &opcao);
if(opcao && !is_vazia_fila(fila))
{
chamado = remover_fila(fila);
printf("%s saiu da fila. \n", chamado.nome);
}
//else if(opcao && is_vazia_fila(fila));
exibir_fila(fila);
exibicao_ordenada_fila(fila);
}
////////////////FUNÇÃO PRINCIPAL///////////////
int main()
{
t_fila fila;
t_elemento elemento;
int opcao = 0;
fila = criar_fila();
do{
if(!is_cheia_fila(&fila))
{
opcao = menu_principal(&fila);
if(opcao == -1)
break;
if(opcao)
{
printf("Digite um identificador: ");
scanf("%s", &elemento);
inserir_fila(&fila, elemento);
exibir_fila(&fila);
exibicao_ordenada_fila(&fila);
}
else
if(is_vazia_fila(&fila))
printf("Nao ha ninguem na fila\n");
else
saida_fila(&fila);
}
else
{
printf("\n===============================\n");
printf(" FILA LOTADA \n");
printf("===============================\n");
saida_fila(&fila);
}
}while(opcao != -1);
return 0;
}
//////FUNÇÔES DE MANIPULAÇÂO DA PILHA///////////
/**
* Cria uma nova fila, aloca a sua regiao de memoria,
* inicializa o inicio, fim e a quantidade de elementos.
* Por fim, retorna a fila criada.
*
* @return Fila inicializada
*/
t_fila criar_fila()
{
t_fila fila;
int i = 0;
fila.inicio = 0;
fila.fim =-1;
fila.qtd_elements = 0;
for(i = 0; i < MAX; i++)
strcpy(fila.vetor[i].nome, "\0");
return fila;
}
/**
* Verifica se a fila esta vazia ou nao.
*
* @param fila ponteiro para a fila, a fila ja deve ter sido inicializada
*
* @return Verdadeiro (1) se a fila estiver vazia, ou falso (0) caso contrario.
*/
int is_vazia_fila(t_fila * fila)
{
return(fila->qtd_elements == 0);
}
/**
* Verifica se a fila esta cheia ou nao.
*
* @param fila ponteiro para a fila, a fila ja deve ter sido inicializada
*
* @return Verdadeiro (1) se a fila estiver cheia, ou falso (0) caso contrario.
*/
int is_cheia_fila(t_fila * fila)
{
return(fila->qtd_elements == MAX);
}
/**
* Insere um elemento (valor) no final da fila.
*
* @param fila ponteiro para a fila, a fila ja deve ter sido inicializada
* @param valor elemento a ser inserido na fila
*
* @return Falso(0) se a fila estiver cheia, caso contrario, retorna Verdadeiro(1)
*/
int inserir_fila(t_fila * fila, t_elemento elemento)
{
if(is_cheia_fila(fila))
return 0;
//Entra nessa parte caso a fila não esteja cheia
(fila->qtd_elements)++;
fila->fim = (fila->fim + 1) % MAX;
fila->vetor[fila->fim] = elemento;
return 1;
}
/**
* Remove um elemento do inicio da fila.
*
* @param fila ponteiro para a fila, a fila ja deve ter sido inicializada
*
* @return o elemento removido.
*/
t_elemento remover_fila(t_fila * fila)
{
t_elemento elemento = {"\0"};
if(is_vazia_fila(fila))
return elemento;
elemento = fila->vetor[fila->inicio];
strcpy(fila->vetor[fila->inicio].nome, "\0");
(fila->qtd_elements)--;
fila->inicio = (fila->inicio + 1) % MAX;
return elemento;
}
/**
* Exibe todos os elementos da fila
*
* @param fila ponteiro para a fila, a fila ja deve ter sido inicializada
*/
void exibir_fila(t_fila * fila) {
int i;
if (is_vazia_fila(fila)) {
printf("Fila vazia\n");
return;
}
printf("\nExibindo ordem da fila circular:\n");
printf("inicio: %d\n", fila->inicio);
printf("fim: %d\n", fila->fim);
for (i=0 ; i<MAX ; i++) {
printf("%d::%s\n", i, fila->vetor[i].nome);
}
}
int exibicao_ordenada_fila(t_fila * fila)
{
int i = 0;
if(is_vazia_fila(fila))
return 0;
printf("\nExibindo fila circular ordenada:\n");
for(i = 0; i <fila->qtd_elements; i++)
printf("%d::%s\n", i + 1, fila->vetor[(fila->inicio + i) % MAX].nome);
//Metodo do professor
//for (i = fila->inicio; i != fila->fim + 1; i = (i + 1) % MAX)
// printf("%d\t", fila->vetor[i]);
}
//////FUNÇÕES DE GERENCIAMENTO DA FILA////////
int menu_principal(t_fila * fila)
{
int opcao = 0;
printf("\n===============================\n");
printf("Deseja entrar ou sair \n");
printf("1 - ENTRAR\n");
printf("0 - SAIR \n");
printf("-1 - EXIT PROGRAMA\n");
printf("===============================\n");
printf("Digite: ");
scanf("%d", &opcao);
printf("===============================\n");
return opcao;
}
|
C
|
#include <stdio.h>
int main()
{
float sal,pres,cond;
printf("Digite o valor do salario:");
fflush(stdout);
scanf("%f", &sal);
printf("Digite o valor da prestacao do emprestimo: ");
fflush(stdout);
scanf("%f", &pres);
cond = sal * 0.2;
if (cond > pres)
{
printf("Emprestimo concedido!");
}
else
{
printf("Emprestimo negado!");
}
return 0;
}
|
C
|
#include <stdio.h>
int res(int n,int m){
int a=0;
for(int i=2;i<=n;i++){
a=(a+m)%i;
}
a = a + 1;
return a;
}
int main(){
int m,n;
while(scanf("%d %d",&n,&m)==2){
if (m == 0 && n == 0)
{
break;
}
printf("%d\n",res(n,m));
}
return 0;
}
|
C
|
/* Filename: ubertooth-rssi.c
* Version: 2
* Date: Jan 2015
* Authors: Daniel Holmes & Dylan Jaconbsen (mostly borrowed and edited code from existing ubertooth functions)
* Description: Code that gets the RSSI data with an associated complete local name and outputs to the terminal
* Notes: This code can be run from the terminal, as with other Ubertooth terminal commands. Refer to ubertooth-setup.txt
* for information on how this is all set up.
*/
#include "ubertooth.h"
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define RSSI_BASE -54
// from bluetooth_le_packet.h
#define MAX_LE_SYMBOLS 64
#define ADV_IND 0
#define ADV_DIRECT_IND 1
#define ADV_NONCONN_IND 2
#define SCAN_REQ 3
#define SCAN_RSP 4
#define CONNECT_REQ 5
#define ADV_SCAN_IND 6
// from bluetooth_le_packet.h
typedef struct _le_packet_t {
// raw unwhitened bytes of packet, including access address
uint8_t symbols[MAX_LE_SYMBOLS];
uint32_t access_address;
// channel index
uint8_t channel_idx;
// number of symbols
int length;
uint32_t clk100ns;
// advertising packet header info
uint8_t adv_type;
int adv_tx_add;
int adv_rx_add;
} le_packet_t;
// from bluetooth_le_packet.c
void decode_le(uint8_t *stream, uint16_t phys_channel, uint32_t clk100ns, le_packet_t *p) {
memcpy(p->symbols, stream, MAX_LE_SYMBOLS);
p->channel_idx = le_channel_index(phys_channel);
p->clk100ns = clk100ns;
p->access_address = 0;
p->access_address |= p->symbols[0];
p->access_address |= p->symbols[1] << 8;
p->access_address |= p->symbols[2] << 16;
p->access_address |= p->symbols[3] << 24;
if (le_packet_is_data(p)) {
// data PDU
p->length = p->symbols[5] & 0x1f;
} else {
// advertising PDU
p->length = p->symbols[5] & 0x3f;
p->adv_type = p->symbols[4] & 0xf;
p->adv_tx_add = p->symbols[4] & 0x40 ? 1 : 0;
p->adv_rx_add = p->symbols[4] & 0x80 ? 1 : 0;
}
}
// from bluetooth_le_packet.c
int le_packet_is_data(le_packet_t *p) {
return p->channel_idx < 37;
}
// from bluetooth_le_packet.c
static void _dump_scan_rsp_data(uint8_t *buf, int len) {
int pos = 0;
int sublen, i;
uint8_t type;
while (pos < len) {
sublen = buf[pos];
++pos;
if (pos + sublen > len) {
printf("Error: attempt to read past end of buffer (%d + %d > %d)\n", pos, sublen, len);
return;
}
if (sublen == 0) {
printf("Early return due to 0 length\n");
return;
}
type = buf[pos];
if (type == 0x09){
printf("Complete Local Name: ");
for (i = 1; i < sublen; ++i)
printf("%c", isprint(buf[pos+i]) ? buf[pos+i] : '.');
}
pos += sublen;
}
}
// from bluetooth_le_packet.c
void le_print(le_packet_t *p) {
int i;
if (!le_packet_is_data(p)) {
if (p->adv_type == ADV_IND){
if (p->length-6 > 0) {
_dump_scan_rsp_data(&p->symbols[12], p->length-6);
}
}
}
}
// should go to ubertooth.c, which then calls functions from ubertrooth_le_packet.c
void display_rssi(usb_pkt_rx* rx)
{
int i;
int8_t rssi;
rssi = rx->rssi_max + RSSI_BASE;
le_packet_t p;
decode_le(rx->data, rx->channel + 2402, rx->clk100ns, &p);
le_print(&p);
printf("\t RSSI: %d \n", rssi);
return;
}
int main(int argc, char *argv[])
{
char ubertooth_device = -1;
struct libusb_device_handle *devh = NULL;
int r;
devh = ubertooth_start(ubertooth_device);
if (devh == NULL) {
printf("No ubertooth found.");
return 1;
}
usb_pkt_rx pkt;
cmd_set_modulation(devh, MOD_BT_LOW_ENERGY);
u16 channel;
channel = 2402; // channel 37
cmd_set_channel(devh, channel);
cmd_btle_sniffing(devh, 2);
while (1) {
int r = cmd_poll(devh, &pkt);
if (r < 0) {
printf("USB error\n");
break;
}
if (r == sizeof(usb_pkt_rx))
display_rssi(&pkt);
usleep(500);
}
ubertooth_stop(devh);
return 0;
}
|
C
|
#include <stdlib.h>
/**
* _calloc - allocates an array to memory, with each value zero'ed out
* @nmemb: elements to allocate
* @size: size of each element
* Return: pointer to array of allocated memory
*/
void *_calloc(unsigned int nmemb, unsigned int size)
{
char *array;
unsigned int count;
void *ptr;
count = 0;
if (nmemb == 0 || size == 0)
return (NULL);
array = malloc(size * nmemb);
if (array == NULL)
{
free(array);
return (NULL);
}
while (count < nmemb * size)
{
array[count] = 0;
count++;
}
ptr = array;
return (ptr);
}
|
C
|
/**
* @file lv_qrcode
*
*/
#ifndef LV_QRCODE_H
#define LV_QRCODE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_QRCODE
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/*Data of qrcode*/
typedef struct {
lv_canvas_t canvas;
lv_color_t dark_color;
lv_color_t light_color;
} lv_qrcode_t;
extern const lv_obj_class_t lv_qrcode_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create an empty QR code (an `lv_canvas`) object.
* @param parent point to an object where to create the QR code
* @return pointer to the created QR code object
*/
lv_obj_t * lv_qrcode_create(lv_obj_t * parent);
/**
* Set QR code size.
* @param obj pointer to a QR code object
* @param size width and height of the QR code
*/
void lv_qrcode_set_size(lv_obj_t * obj, lv_coord_t size);
/**
* Set QR code dark color.
* @param obj pointer to a QR code object
* @param color dark color of the QR code
*/
void lv_qrcode_set_dark_color(lv_obj_t * obj, lv_color_t color);
/**
* Set QR code light color.
* @param obj pointer to a QR code object
* @param color light color of the QR code
*/
void lv_qrcode_set_light_color(lv_obj_t * obj, lv_color_t color);
/**
* Set the data of a QR code object
* @param obj pointer to a QR code object
* @param data data to display
* @param data_len length of data in bytes
* @return LV_RES_OK: if no error; LV_RES_INV: on error
*/
lv_res_t lv_qrcode_update(lv_obj_t * obj, const void * data, uint32_t data_len);
/**********************
* MACROS
**********************/
#endif /*LV_USE_QRCODE*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_QRCODE_H*/
|
C
|
#include <stdio.h>
int main()
{
int a, b, c1 = 0, c2 = 0, c3 = 0, c4 = 0;
for (a = 0; a < 5; a++)
{
scanf("%d", &b);
if (b % 2 == 0)
c1++;
if (b % 2 == 1 || b % 2 == -1)
c2++;
if (b > 0)
c3++;
if (b < 0)
c4++;
}
printf("%d valor(es) par(es)\n", c1);
printf("%d valor(es) impar(es)\n", c2);
printf("%d valor(es) positivo(s)\n", c3);
printf("%d valor(es) negativo(s)\n", c4);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,i;
scanf("%d",&a);
printf("INPUT \n %d \n",a);
printf("Output \n");
for(i=0;i<a;i++)
{
printf("HELLO\n");
}
return 0;
}
|
C
|
/*
# Name: Irvin Samuel
# Date: Tuesday, 26 Jan 2021
# Title: Lab4 Part 3 (TCP/IP Socket programming)
# Description: This program implements socket programming and simulates a multi-thread client
*/
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h> /* printf, stderr */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
void* connect_client(void* n);
int main(int argc, char* argv[]){
int port = atoi(argv[1]);
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address; //stores IP address, port #
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
int bind_val = bind(sockfd, (struct sockaddr*) &address, sizeof(address)); // binds socket to a port and address
int listen_val = listen(sockfd,5); // checks for TCP connection, if so, returns TCP ack
int address_size = sizeof(address);
pthread_t t[5];
int conn_fd[5];
int j = 0;
while(j < 5){
printf("Awaiting source file %d...\n", j);
int connectionfd = accept(sockfd,(struct sockaddr*) &address, (socklen_t*) &address_size);
if(connectionfd > 0){
conn_fd[j] = pthread_create(&t[j], NULL, connect_client, (void*) connectionfd); // launches thread for every one connection it receives
j++;
}
}
for(int k = 0; k < 5; k++){
pthread_join(t[k], NULL); //ends the threads before ending the main program
}
close(sockfd);
}
void* connect_client(void* n){
char* thread_dest_filename = "thread_dest";
char* thread_ext = ".dat";
static int x = 0;// made static so the variable can update everytime the program is written
char num = (x) +'0';
int file_descriptor = (int) n;
size_t len1 = strlen(thread_dest_filename) + strlen(&num) + strlen(thread_ext) + 1;
char* file_dest = (char *) malloc(sizeof(char)*len1); //allocates sufficient size for the destination file name
snprintf(file_dest,len1,"%s%c%s", thread_dest_filename, num, thread_ext);
char message;
FILE* dest = fopen(file_dest, "w");
if(dest == NULL){
printf("ERROR opening destination file\n");
exit(0);
}
while(recv(file_descriptor, &message, 1,0) > 0){ // loops until there are no more bytes to receive from that connection
fwrite(&message,1,1,dest);
}
printf("File %d successfully received.\n", x++);
fclose(dest);
close(file_descriptor);
}
|
C
|
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "common.h"
int
open_next_file(struct picam_ctx *ctx, char *last_fname, int len)
{
char dir[1024];
struct tm now, *pnow;
time_t tm_now;
/* create directory based on todays date */
tm_now = time(NULL);
pnow = localtime_r(&tm_now, &now);
snprintf(dir, sizeof(dir), "%s/%02d-%02d-%04d",
ctx->path, pnow->tm_mon+1, pnow->tm_mday, pnow->tm_year+1900);
if (access(dir, 0) != 0) {
LOG_INF("creating dir %s", dir);
mkdir(dir, 0777);
}
/* save the current path if its new or different */
if (!ctx->curr_dir || (0 != strncmp(dir, ctx->curr_dir, strlen(dir)))) {
if (ctx->curr_dir)
free(ctx->curr_dir);
ctx->curr_dir = strdup(dir);
}
/* if we have a file open; close it */
if (ctx->video_fp) {
if (last_fname)
snprintf(last_fname, len, "%s", ctx->fname);
fclose(ctx->video_fp);
}
/* open the file with next index */
snprintf(ctx->fname, PATH_MAX, "%s/mov-%02d%02d%02d.h264",
ctx->curr_dir, pnow->tm_hour,
pnow->tm_min, pnow->tm_sec);
LOG_INF("Opening file: %s", ctx->fname);
ctx->video_fp = fopen(ctx->fname, "w");
return (ctx->video_fp == NULL);
}
void
h264_write_frames(struct picam_ctx *ctx)
{
struct picam_frame *frame = ctx->frame_buffers.frames[ctx->frame_buffers.last];
int ii = 0;
int key_frame = -1;
time_t last_frame_tm = frame->tm;
/* find last key frame pre-cap seconds before current */
LOG_DBG("lfi=%d, cfi=%d", ctx->frame_buffers.last, ctx->frame_buffers.curr);
for (ii = ctx->frame_buffers.last;
ii != ctx->frame_buffers.curr; ii--)
{
frame = ctx->frame_buffers.frames[ii];
if (frame->keyframe) {
LOG_DBG("ii=%d - kf=%d, ft=%lu delta=%lu", ii, frame->keyframe,
frame->tm, last_frame_tm - ctx->nsec_pre_cap);
if ((key_frame == -1) ||
(frame->tm <= (last_frame_tm - ctx->nsec_pre_cap)))
{
LOG_DBG("lft=%lu, ft=%lu, kfi=%d", last_frame_tm,
frame->tm, key_frame);
key_frame = ii;
break;
}
}
if (ii == 0)
ii = ctx->frame_buffers.nalloc-1;
}
/* write file header */
fwrite(ctx->h264_hdr, 1, ctx->h264_hdr_pos, ctx->video_fp);
LOG_DBG("Final lft=%lu, kfi=%d", last_frame_tm, key_frame);
/* write all frames from the key frame to last frame */
for (ii = key_frame; ii != ctx->frame_buffers.last; ii++) {
if (ii == ctx->frame_buffers.nalloc)
ii = 0;
frame = ctx->frame_buffers.frames[ii];
fwrite(frame->data, 1, frame->len, ctx->video_fp);
}
frame = ctx->frame_buffers.frames[ctx->frame_buffers.last];
fwrite(frame->data, 1, frame->len, ctx->video_fp);
}
void
h264_write_frame(struct picam_ctx *ctx, int frame_idx)
{
struct picam_frame *frame = ctx->frame_buffers.frames[frame_idx];
fwrite(frame->data, 1, frame->len, ctx->video_fp);
}
|
C
|
/*
** EPITECH PROJECT, 2021
** minishell
** File description:
** functions for the exit command
*/
#include "minishell.h"
int get_exit_status(param_t *params)
{
int status = 0;
int tmp = 0;
int i = 0;
if (is_int(params->input[1]) != 1) {
my_putstr("Invalid Syntax\n");
return (256);
}
status = my_getnbr(params->input[1]);
if (status < 255 && status > 0)
return (status);
tmp = status;
while (i <= tmp) {
if (status > 255)
status = 0;
status++;
i++;
}
return (status);
}
int do_exit(param_t *params)
{
if (my_strcmp(params->input[0], "exit") != 0)
return (0);
if (my_arrsize(params->input) == 2) {
params->is_exit = get_exit_status(params);
return (0);
}
params->is_exit = 0;
return (0);
}
|
C
|
#include "common.h"
int main()
{
//declare the vars
qlist *front = NULL;
data_t data, n_data, g_data;
int opt, status, num;
//run an infinite while loop
while(1)
{
//print the user options
printf("\n1.ENQ\n2.DEQ\n3.print\n4.EXIT\n");
scanf("%d", &opt);
printf("\n");
switch(opt)
{
//enqueue
case 1:
{
//prompt + read user
printf("Enter the data\n");
scanf("%d",&data);
//call the function
status = ENQ(&front, data);
//check the status
if(status == SUCCESS)
{
printf("Data inserted in queue\n");
}
else
{
printf("Data insertion unsuccessful\n");
}
break;
}
//dequeue
case 2:
{
//call the function
status = DEQ(&front, &data);
//check the status
if(status == SUCCESS)
{
printf("First member of the queue was: %d\n", data);
}
else if(status == Q_EMPTY)
{
printf("queue empty");
}
else
{
printf("Data insertion in queue unsuccessful\n");
}
break;
}
//print the elements
case 3:
{
print(front);
break;
}
//exit
case 4:
{
exit(0);
break;
}
default:
{
printf("Enter the correct option\n");
}
}
}
}
|
C
|
#include "turtle.h"
#include "tensor3D.h"
/* Note that depth is the first indices and that the indices were pernutated
with respect to NR */
/*-----------------------------------------------------------------------*/
double ***d3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh)
/* allocate a double 3tensor with range t[nrl..nrh][ncl..nch][ndl..ndh] */
{
long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1,ndep=ndh-ndl+1;
double ***t;
/* allocate pointers to pointers to rows */
t=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double**)));
if (!t) t_error("allocation failure 1 in d3tensor()");
t += NR_END;
t -= nrl;
/* allocate pointers to rows and set pointers to them */
t[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double*)));
if (!t[nrl]) t_error("allocation failure 2 in d3tensor()");
t[nrl] += NR_END;
t[nrl] -= ncl;
/* allocate rows and set pointers to them */
t[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*ndep+NR_END)*sizeof(double)));
if (!t[nrl][ncl]) t_error("allocation failure 3 in d3tensor()");
t[nrl][ncl] += NR_END;
t[nrl][ncl] -= ndl;
for(j=ncl+1;j<=nch;j++) t[nrl][j]=t[nrl][j-1]+ndep;
for(i=nrl+1;i<=nrh;i++) {
t[i]=t[i-1]+ncol;
t[i][ncl]=t[i-1][ncl]+ncol*ndep;
for(j=ncl+1;j<=nch;j++) t[i][j]=t[i][j-1]+ndep;
}
/* return pointer to array of pointers to rows */
return t;
}
/*-----------------------------------------------------------------------*/
DOUBLETENSOR *new_doubletensor(long ndh,long nrh,long nch)
{
DOUBLETENSOR *m;
m=(DOUBLETENSOR *)malloc(sizeof(DOUBLETENSOR));
if (!m) t_error("allocation failure in new_doubletensor()");
m->isdynamic=isDynamic;
m->nrl=NL;
m->nrh=nrh;
m->ncl=NL;
m->nch=nch;
m->ndl=NL;
m->ndh=ndh;
m->co=d3tensor(m->ndl,m->ndh,m->nrl,m->nrh,m->ncl,m->nch);
return m;
}
DOUBLETENSOR *new_doubletensor0(long ndh,long nrh,long nch)
{
DOUBLETENSOR *m;
m=(DOUBLETENSOR *)malloc(sizeof(DOUBLETENSOR));
if (!m) t_error("allocation failure in new_doubletensor()");
m->isdynamic=isDynamic;
m->nrl=NL;
m->nrh=nrh;
m->ncl=NL;
m->nch=nch;
m->ndl=0;
m->ndh=ndh;
m->co=d3tensor(m->ndl,m->ndh,m->nrl,m->nrh,m->ncl,m->nch);
return m;
}
/*-----------------------------------------------------------------------*/
void free_d3tensor(double ***t, long nrl, long ncl, long ndl)
{
free((FREE_ARG) (t[nrl][ncl]+ndl-NR_END));
free((FREE_ARG) (t[nrl]+ncl-NR_END));
free((FREE_ARG) (t+nrl-NR_END));
}
/*-----------------------------------------------------------------------*/
void free_doubletensor( DOUBLETENSOR *m)
{
if(m==NULL || m->co==NULL){
t_error("This matrix was never allocated");
}else if(m->isdynamic==1){
free_d3tensor(m->co,m->ndl,m->nrl,m->ncl);
m->isdynamic=m->nrl=m->ncl=m->nrh=m->nch=m->ndl=m->ndh=-1;
free(m);
return;
}else{
printf("\nWarning::An attemp was made to free a non dynamic tensor\n");
}
}
/*---------------------------------------------------------------------------*/
void initialize_doubletensor(DOUBLETENSOR *L, double sign)
{
long i,j,k;
if(L!=NULL){
if(L->isdynamic==1){
for(k=L->ndl;k<=L->ndh;k++){
for(i=L->nrl;i<=L->nrh;i++){
for(j=L->ncl;j<=L->nch;j++){
L->co[k][i][j]=sign;
}
}
}
}else{
t_error("This tensor was no properly allocated");
}
}else{
t_error("A null tensor was addressed");
}
}
|
C
|
#include <stdio.h>
int taille (int nb)
{
int i;
int tab[100];
for(i=0;tab[i]!='\0';i++)
{
if (nb>=0 && nb<=9)
{
tab[i]=nb;
}
}
return i;
}
int main ()
{
int nb;
scanf("%d",&nb);
printf("%d\n",taille(nb));
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
const int MAX = 100;
int arr[100];
int found = 0;
int t;
int n;
void *search_l(void *arg){
int *s = (int *)arg;
int key = *s;
for(int i = 0; i < n;i++){
if(found == 0 && arr[i] == key){
t = 1;
found = 1;
break;
}
else if(found==1){
break;
}
}
pthread_exit(0);
}
void *search_r(void *arg){
int *s = (int *)arg;
int key = *s;
for(int i = n-1; i >= 0;i--){
if(found == 0 && arr[i] == key){
t = 2;
found = 1;
break;
}
else if(found == 1){
break;
}
}
pthread_exit(0);
}
int main(int argc, char ** argv){
if(argc<2 || argc > 101){
exit(-1);
}
n = argc-2;
for(int i =0; i < n;i++){
arr[i] = atoi(argv[i+1]);
}
int key = atoi(argv[n+1]);
pthread_t left;
pthread_t right;
pthread_create(&left,NULL,search_l,&key);
pthread_create(&right,NULL,search_r,&key);
pthread_join(left,NULL);
pthread_join(right,NULL);
if(found == 1){
printf("FOUND BY ");
if(t == 1){
printf("LEFT\n");
}
else{
printf("RIGHT\n");
}
}
else{
printf("NOT FOUND\n");
}
}
|
C
|
#ifndef __SE_BEENAKKER_DECOMP
#define __SE_BEENAKKER_DECOMP
#include <math.h>
double self_coeff(double xi)
{
return -8*xi/sqrt(PI);
}
double C1(double r)
{
double r2 = r*r;
return erfc(r) + 2*(2*r2 - 3)*r*exp(-r2)/sqrt(PI);
}
double C2(double r)
{
double r2 = r*r;
return erfc(r) + 2*(1 - 2*r2)*r*exp(-r2)/sqrt(PI);
}
void op_A(double A[3][3], double x[3], double xi)
{
double r = sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);
double c1 = C1(xi*r)/r;
double c2 = C2(xi*r)/(r*r*r);
int i,j;
for(i=0; i<3; i++)
for(j=0; j<3; j++)
A[i][j] = c1*(i==j) + c2*x[i]*x[j];
}
void op_B(double B[3][3], double k[3], double xi)
{
double nk=sqrt(k[0]*k[0] + k[1]*k[1] + k[2]*k[2]);
double w2 = (nk/xi)*(nk/xi);
double k2 = nk*nk;
double c = 8*PI*( 1.0/(w2*w2) + 1.0/(4.0*w2) + 1.0/8.0 )*
exp(-w2/4.0)/(xi*xi*xi*xi);
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++)
B[i][j] = c*( k2*(i==j) - k[i]*k[j] );
}
void op_BB(double B[3][3], double k[3], double xi)
{
double nk=sqrt(k[0]*k[0] + k[1]*k[1] + k[2]*k[2]);
double w2 = (nk/xi)*(nk/xi);
double k2 = nk*nk;
double c = 8*PI*( 1.0/(w2*w2) + 1.0/(4.0*w2) + 1.0/8.0 )/(xi*xi*xi*xi);
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++)
B[i][j] = c*( k2*(i==j) - k[i]*k[j] );
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
long long int cycle_length(long long int);
int main()
{
long long int i, j, cycle, iter, result, firsttime = 1;
while(scanf("%lld %lld", &i, &j) != EOF){
if(firsttime != 1)
printf("\n");
else
firsttime = 0;
cycle = 0;
if(i >= j){
for(iter = j; iter <= i; iter++){
result = cycle_length(iter);
if(result > cycle)
cycle = result;
}
printf("%lld %lld %lld", i, j, cycle);
}
else if(j > i){
for(iter = i; iter <= j; iter++){
result = cycle_length(iter);
if(result > cycle)
cycle = result;
}
printf("%lld %lld %lld", i, j, cycle);
}
}
return 0;
}
long long int cycle_length(long long int n)
{
long long int cycle = 1;
while(n != 1){
cycle++;
if(n % 2 == 1)
n = 3 * n + 1;
else
n /= 2;
}
return cycle;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;do{printf("n(odd number)-> ");scanf("%d",&n);}while(n%2==0);
for(int i=0;i<(n/2+1);i++)
{
printf("*");
for (int j=0;j<=(i-2);j++)
{
printf(" ");
}
if(i-1>=0){printf("*");}
for (int j=0;j<(n-2-2*i);j++)
{
printf(" ");
}
if(i<n/2)
{if(i-1>=0){printf("*");}}
for (int j=0;j<=(i-2);j++)
{
printf(" ");
}
printf("*\n");
}
for(int i=(n/2);i>0;i--)
{
printf("*");
for(int j=0;j<i-2;j++)
{
printf(" ");
}
if(i-1>0){printf("*");}
for(int j=0;j<(1+2*((n/2)-i));j++)
{
printf(" ");
}
if(i-1>0){printf("*");}
for(int j=0;j<i-2;j++)
{
printf(" ");
}
printf("*\n");
}
return 0;
}
|
C
|
/*
Row = 4
Column = 4
# # # #
# * * #
# * * #
# # # #
1,1 1,2 1,3 1,4
2,1 2,2 2,3 2,4
3,1 3,2 3,3 3,4
4,1 4,2 4,3 4,4
*/
#include<stdio.h>
void Pattern(unsigned int iRow,unsigned int iCol)
{
int i = 0,j = 0;
if (iRow != iCol)
{
return ;
}
printf("\n");
for (i = 1;i <= iRow;i++)
{
for (j = 1;j <= iCol;j++)
{
if ((i==1)||(i==iRow)||(j==1)||(j==iCol))
{
printf("#\t");
}
else
{
printf("*\t");
}
}
printf("\n");
}
}
int main()
{
unsigned int iRow = 0,iCol = 0;
printf("Enter a number of Rows:");
scanf("%u",&iRow);
printf("Enter a number of Columns:");
scanf("%u",&iCol);
Pattern(iRow,iCol);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define N 100
int TOP = -1;
char S[N];
void PUSH(char ITEM)
{
if(TOP >= N-1)
{
printf("\nStack Overflow.");
}
else
{
TOP = TOP+1;
S[TOP] = ITEM;
}
}
char POP()
{
char ITEM ;
if(TOP <0)
{
printf("\nStack Underflow!");
exit(1);
}
else
{
ITEM = S[TOP];
TOP = TOP-1;
return(ITEM);
}
}
int oper(char op)
{
if(op == '*' || op == '/' || op == '+' || op == '-')
{
return 1;
}
else
{
return 0;
}
}
int precedence(char op)
{
if(op == '*' || op == '/')
{
return 2;
}
else if(op == '+' || op == '-')
{
return 1;
}
else
{
return 0;
}
}
void infixToPostfix(char infix[], char postfix[])
{
char X, ITEM;
int i = 0, j = 0;
PUSH('(');
strcat(infix, ")");
ITEM = infix[i];
while(ITEM != '\0')
{
if(ITEM == '(')
{
PUSH(ITEM);
}
else if(isdigit(ITEM) || isalpha(ITEM))
{
postfix[j] = ITEM;
j++;
}
else if(oper(ITEM) == 1)
{
X = POP();
while(oper(X) == 1 && precedence(ITEM) <= precedence(X))
{
postfix[j] = X;
j++;
X = POP();
}
PUSH(X);
PUSH(ITEM);
}
else if(ITEM == ')')
{
X = POP();
while(X != '(')
{
postfix[j] = X;
j++;
X = POP();
}
}
else
{
printf("\nInvalid expression!");
exit(1);
}
i++;
ITEM = infix[i];
}
postfix[j] = '\0';
}
int main()
{
char infix[N], postfix[N];
printf("Enter infix expression: ");
gets(infix);
infixToPostfix(infix, postfix);
printf("\nPostfix expression is %s", postfix);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define N 8
/* preenche o tabuleiro com peças e printa */
void printMatriz(char **M){
int i,j;
printf(" 0 1 2 3 4 5 6 7\n");
for(i=0;i<N;i++){
printf("%d",i);
for(j=0;j<N;j++){
printf("[%c]",M[i][j]);
}
printf("\n");
}
}
char **initialize () {
/* alocação das linhas e colunas */
char **M;
int i,j;
M = (char **)calloc(N, sizeof(char *));
for(i = 0; i < N; i++)
M[i] = (char *)calloc(N, sizeof(char));
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
if (i == 0 || i == 2)
{
if(j%2 == 0)
{
M[i][j]=' ';
}
else
{
M[i][j]='B';
}
}
else if (i == 1)
{
if (j%2 == 0)
{
M[i][j]='B';
}
else
{
M[i][j]=' ';
}
}
if (i == 5 || i == 7)
{
if(j%2 == 0)
{
M[i][j]='P';
}
else
{
M[i][j]=' ';
}
}
else if (i == 6)
{
if (j%2 == 0)
{
M[i][j]=' ';
}
else
{
M[i][j]='P';
}
}
if (i == 4 || i == 3)
{
M[i][j]=' ';
}
}
}
return M;
}
/*condições para a realização de jogadas e condições para poder comer */
int step (char **M, int linha,int coluna,int linhadest,int coldest, char jogador) {
int i,j;
//para mover não deve retornar 0
if (linha < 0 || linhadest < 0 ||
coluna < 0 || coldest < 0 ||
linha >= N || linhadest >= N ||
coluna >= N || coldest >= N)
{
return 0;
}
if ((linha+coluna)%2 == 0 || (linhadest+coldest)%2 == 0)
{
return 0;
}
if (jogador == 'B')
{
if (
linha > linhadest ||
M[linha][coluna] == 'P' ||
M[linhadest][coldest] !=' ')
{
return 0;
}
else if(linhadest > linha+1)//condições de B para poder comer
{
if (M[linha+2][coluna+2] ==' ' && M[linha+1][coluna+1] =='P')
{
M[linha][coluna] =' ';
M[linha+1][coluna+1] =' ';
M[linhadest][coldest] ='B';
return 1;
}
if (M[linha+2][coluna-2] ==' ' && M[linha+1][coluna-1] =='P')
{
M[linha][coluna] =' ';
M[linha+1][coluna-1] =' ';
M[linhadest][coldest] ='B';
return 1;
}
}
}
if (jogador == 'P')
{
if(linhadest < linha-1 ||
linha < linhadest ||
M[linha][coluna] == 'B' ||
M[linhadest][coldest] !=' ')
return 0;
}
M[linha][coluna] = ' ';
M[linhadest][coldest] = jogador;
return 1;
}
void game () {
char **tabuleiro;
int linha, coluna,lind,cold;
char jogador = 'B';
int jogoativo = -1;
tabuleiro = initialize();
printf("\nBem vindo ao jogo!!\n");
while (jogoativo==-1)
{
printMatriz(tabuleiro);
if (jogador == 'B')
printf("\nVamos jogador B,faça seus movimentos\n");
if (jogador == 'P')
printf("\nVamos jogador P,faça seus movimentos\n");
scanf("%d %d", &linha, &coluna);
printf("Destino: ");
scanf("%d %d", &lind, &cold);
// caso a jogada seja errada
if (!step(tabuleiro,linha, coluna, lind, cold, jogador)) {
printf("Jogada Invalida!jogue novamente\n");
continue;
}
//alternancia de jogador
if (jogador == 'B')
jogador = 'P';
else jogador = 'B';
}
}
int main (void) {
game();
}
|
C
|
#ifndef __UTILITIES_H
#define __UTILITIES_H
//macros
#define BIT(n) (0x01<<(n))
//generic functions
/**
* @brief returns the absolute value of a number
*
*
* @param n number whose absolute value we want to know
*
* @return Absolute value of n
*/
int abs(int n);
/**
* @brief returns sign of a number
*
*
* @param n number whose sign we want to know
*
* @return sign of n
*/
int sgn(int n);
/**
* @brief checks if two number have the same sign
*
*
* @param x, y numbers whose signs we want to compare
*
* @return Returns 1 if both numbers have the same sign, 0 otherwise
*/
int samesign(int x, int y);
/**
* @brief checks if all the elements of an array have the same sign
*
*
* @param size size of an array
*
* @return Returns 1 if all numbers have the same sign, 0 otherwise
*/
int samesignarray(int size, int * arr);
/**
* @brief returns the opposite number in two complement to c
*
*
* @param c value whose symetric in two complement we want to know
*
* @return the symetric in two_complement for c
*/
char two_complement_sym(char c);
/**
* @brief converts a char to decimal
*
*
* @param c char to be converted to decimal
*
* @return Returns the conversion of c to decimal
*/
int conv_to_decimal(char c);
#endif
|
C
|
/*
// file: /std/player/history.c
// author: Portals (wayfarer and huthar)
// last modified: 1992/03/08 - Truilkan@TMI
*/
#include <security.h>
private nosave string *history_queue;
private nosave int cmd_num, ptr;
private nosave int max;
int query_cmd_num() { return cmd_num ? cmd_num : 1; }
int query_ptr() { return ptr; }
int query_max() { return max; }
string *query_history() {
if(geteuid(previous_object()) != geteuid() &&
geteuid(previous_object()) != UID_USERACCESS) return ({});
return history_queue;
}
void alloc(int size)
{
max = size;
if (max)
history_queue = allocate(max);
cmd_num = 1;
}
void enqueue(string str)
{
if(!max)
return;
history_queue[ptr++] = str;
cmd_num++;
if(ptr == max)
ptr = 0;
}
string handle_history(string str)
{
int tmp;
string *tmpq;
string *lines;
string cmd;
if(str[0] != '!' || str == "!")
{
enqueue(str);
return str;
}
if(!history_queue || sizeof(history_queue) == 1)
{
write(str[1 .. strlen(str) - 1]+": Event not found.\n");
return "";
}
if(str == "!!")
{
if((tmp = ptr - 1) < 0)
tmp = max - 1;
cmd = history_queue[tmp];
}
else
if(sscanf(str,"!%d",tmp))
{
if(tmp > 0)
tmp -= cmd_num;
if(tmp >= 0 || (-tmp) >= max)
{
write(tmp+": Event not found.\n");
return "";
}
if((tmp = ptr + tmp) < 0)
tmp = max + tmp;
cmd = history_queue[tmp];
}
else
{
str = str[1..strlen(str)];
if(!ptr)
tmpq = history_queue;
else
tmpq = history_queue[ptr .. (max - 1)] +
history_queue[0 .. ptr - 1];
lines = regexp(tmpq,"^"+str);
if(!sizeof(lines))
{
write(str+": Event not found.\n");
return "";
}
cmd = lines[sizeof(lines) - 1];
}
write(cmd+"\n");
enqueue(cmd);
return cmd;
}
|
C
|
/*************************************************************************
> File Name: server.c
> Author:
> Mail:
> Created Time: Sat 29 Apr 2017 10:47:45 AM CST
************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <arpa/inet.h>
#include <errno.h>
#include "server.h"
/*
* 将文件描述符设置成非阻塞的
*/
int setnonblocking(int fd)
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
/*
* 将文件描述符fd上的EPOLLIN注册到epollfd指示的内核事件表中
* 参数enable_fd指定是否对fd启用ET模式
*/
void addfd(int epollfd, int fd, bool enable_et)
{
struct epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN;
if(enable_et) {
event.events |= EPOLLET;
}
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
//setnonblocking(fd);
}
void lt(struct epoll_event* events, int number, int epollfd, int listenfd)
{
char buf[BUFFER_SIZE];
for(int i = 0; i < number; i++)
{
int sockfd = events[i].data.fd;
if(listenfd == sockfd) {
struct sockaddr_in client_address;
socklen_t client_addrlen = sizeof(client_address);
int connfd = accept(listenfd, (struct sockaddr*)&client_address, &client_addrlen);
addfd(epollfd, connfd, FALSE);
}
else if(events[i].events & EPOLLIN) {
/*只要socket读缓存中还有未读出的数据,这段代码就被触发*/
printf("event trigger once\n");
memset(buf, '\0', BUFFER_SIZE);
int ret = recv(sockfd, buf, BUFFER_SIZE, 0);
if(ret <= 0) {
close(sockfd);
continue;
}
printf("get %d bytes of content: %s\n", ret, buf);
}
else {
printf("something else happened\n");
}
}
}
void et(struct epoll_event* events, int number, int epollfd, int listenfd)
{
char buf[BUFFER_SIZE];
for(int i = 0; i < number; i++)
{
int sockfd = events[i].data.fd;
if(listenfd == sockfd) {
struct sockaddr_in client_address;
socklen_t client_addrlen = sizeof(client_address);
int connfd = accept(listenfd, (struct sockaddr*)&client_address, &client_addrlen);
addfd(epollfd, connfd, TRUE); /*对connfd开启ET模式*/
setnonblocking(connfd);
}
else if(events[i].events & EPOLLIN) {
/*这段代码不会重复触发,所以我们循环读取数据,以确保把socket读缓存所有数据读出*/
printf("event trigger once\n");
while(1)
{
memset(buf, '\0', BUFFER_SIZE);
int ret = recv(sockfd, buf, BUFFER_SIZE, 0);
if(ret < 0) {
/*对于非阻塞IO,下面条件成立表示数据已经全部读取完毕,此后,epoll就能再次触发sockfd上的EPOLLIN事件,以驱动下一次读操作*/
if((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
printf("read later\n");
break;
}
close(sockfd);
break;
}
else if(0 == ret) {
close(sockfd);
}
else {
printf("get %d bytes of content: %s\n", ret, buf);
}
}
#if 0
memset(buf, '\0', BUFFER_SIZE);
int ret = recv(sockfd, buf, BUFFER_SIZE, 0);
if(ret <= 0) {
close(sockfd);
continue;
}
else {
printf("get %d bytes of content: %s\n", ret, buf);
}
#endif
}
else {
printf("something else happened\n");
}
}
}
int main(int argc, char* argv[])
{
if(argc != 2){
fprintf(stderr, "usage: %s <port>.\n", argv[0]);
exit(-1);
}
int ret = 0, connfd = 0;
socklen_t addrlen = 0;
unsigned short port = atoi(argv[1]);
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
assert(-1 != listenfd);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
ret = bind(listenfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
assert(-1 != ret);
ret = listen(listenfd, 5);
assert(-1 != ret);
struct epoll_event events[MAX_EVENT_SIZE];
int epollfd = epoll_create(5);
assert(-1 != epollfd);
addfd(epollfd, listenfd, TRUE);
while(1)
{
int ret = epoll_wait(epollfd, events, MAX_EVENT_SIZE, -1);
if(ret < 0) {
printf("epoll failure\n");
break;
}
//lt(events, ret, epollfd, listenfd); /*使用LT模式*/
et(events, ret, epollfd, listenfd); /*使用ET模式*/
}
close(listenfd);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
typedef struct list{
int nu;
double a,b,c,d,ave;
}lis;
int main()
{
lis a[3];
int i;
for(i=0;i<3;i++){
scanf("%d%lf%lf%lf%lf",&a[i].nu,&a[i].a,&a[i].b,&a[i].c,&a[i].d);
a[i].ave=(a[i].a+a[i].b+a[i].c+a[i].d)/4.0;}
for(i=0;i<3;i++)
printf("%d %.2f\n",a[i].nu,a[i].ave);
return 0;
}
|
C
|
#include <stdio.h>
int kadane(int a[],int n){
int i,max_so_far = 0,max_end_here=0;
for (i=0;i<n;i++){
max_end_here=max_end_here + a[i];
if (max_end_here <0)
max_end_here = 0;
if (max_end_here > max_so_far)
max_so_far = max_end_here;
}
return max_so_far;
}
int main()
{
int i,arr[7]={-1,-2,4,-1,-2,5,-3};
printf("the array is ");
for (i=0;i<7;i++){
printf("%d\t",arr[i]);
}
printf ("the longest sub seqeunce %d \n",kadane(arr,7));
}
|
C
|
/**
* $Id: lcd.c 672 2013-04-12 10:30:44Z klugeflo $
*/
/******************************************************************************
File: lcd.c
Project: Roomba Embedded Systems Training
Description: LCD text output
Author: Florian Kluge <[email protected]>
Universität Augsburg
Created: 21.02.2011
*******************************************************************************
Modification history:
---------------------
21.02.2011 (FAK) Created from RTOS Training
*/
/****************************************************************** Includes */
#include <lcd.h>
#include <board.h>
#include <tools.h>
#include <stddef.h>
#ifdef HAVE_LCD
/******************************************************************* Defines */
#define CHAR_SPACE 0x20
#define NUM_TABCHARS 4
#define TABCHAR CHAR_SPACE
#define LCD_LINES 2 /*!< number of lines the display provides */
#define LCD_LEN 0x10 /*!< chars per line */
#define LCD_BUSY (0x00000080u)
// LCD commands from ALTERA file
enum /* Write to character RAM */
{
LCD_CMD_WRITE_DATA = 0x80
/* Bits 6:0 hold character RAM address */
};
enum /* Write to character generator RAM */
{
LCD_CMD_WRITE_CGR = 0x40
/* Bits 5:0 hold character generator RAM address */
};
enum /* Function Set command */
{
LCD_CMD_FUNCTION_SET = 0x20,
LCD_CMD_8BIT = 0x10,
LCD_CMD_TWO_LINE = 0x08,
LCD_CMD_BIGFONT = 0x04
};
enum /* Shift command */
{
LCD_CMD_SHIFT = 0x10,
LCD_CMD_SHIFT_DISPLAY = 0x08,
LCD_CMD_SHIFT_RIGHT = 0x04
};
enum /* On/Off command */
{
LCD_CMD_ONOFF = 0x08,
LCD_CMD_ENABLE_DISP = 0x04,
LCD_CMD_ENABLE_CURSOR = 0x02,
LCD_CMD_ENABLE_BLINK = 0x01
};
enum /* Entry Mode command */
{
LCD_CMD_MODES = 0x04,
LCD_CMD_MODE_INC = 0x02,
LCD_CMD_MODE_SHIFT = 0x01
};
enum /* Home command */
{
LCD_CMD_HOME = 0x02
};
enum /* Clear command */
{
LCD_CMD_CLEAR = 0x01
};
/******************************************************* Function prototypes */
/*!
Select the line, where you want your output to appear
\param l < #LCD_LINES
*/
int32_t lcd_setline(uint32_t l);
/*!
Move the cursor to the first position in line
*/
void lcd_home(void);
/*!
Simply write one char onto the display. Will NOT check for newlines,
overflows and similar. Just writes on and on and......
*/
int32_t __lcd_putchar(int32_t c);
/*!
Initialise buffered output
*/
void lcd_init_buf(void);
/************************************************************** Global const */
/********************************************************** Global variables */
/*************************************************************** Local const */
/*********************************************************** Local variables */
static char lcd_line_adr[2] = { 0x00, 0x40 }; /*!< line adresses */
// handle a buffer to write to LCD
static int8_t lcd_pos = 0; /*!< Current position in line */
static int8_t lcd_cline = 0; /*!< Current line */
static int8_t lcd_line_buf[LCD_LINES][LCD_LEN]; /*!< Lines Buffer; array
for faster buffer handling */
/******************************************************************** Macros */
/********************************************************** Global functions */
void lcd_init(void) {
// enable LCD
LCD_ON = 0x1;
// Wait for 15 ms then reset
my_usleep(15000);
LCD_CMD = LCD_CMD_FUNCTION_SET | LCD_CMD_8BIT;
// Wait for another 4.1ms and reset again
my_usleep(4100);
LCD_CMD = LCD_CMD_FUNCTION_SET | LCD_CMD_8BIT;
// Wait a further 1 ms and reset a third time
my_usleep(1000);
LCD_CMD = LCD_CMD_FUNCTION_SET | LCD_CMD_8BIT;
// Setup interface parameters: 8 bit bus, 2 rows, 5x7 font
while(LCD_ST == LCD_BUSY){}
my_usleep(1000);
LCD_CMD = LCD_CMD_FUNCTION_SET | LCD_CMD_8BIT | LCD_CMD_TWO_LINE;
// Turn display off
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
LCD_CMD = LCD_CMD_ONOFF;
// Clear display
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
LCD_CMD = LCD_CMD_CLEAR;
// Set mode: increment after writing, don't shift display
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
LCD_CMD = LCD_CMD_MODES | LCD_CMD_MODE_INC;
// Turn display on
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
//LCD_CMD = LCD_CMD_ONOFF | LCD_CMD_ENABLE_DISP | LCD_CMD_ENABLE_CURSOR | LCD_CMD_ENABLE_BLINK;
LCD_CMD = LCD_CMD_ONOFF | LCD_CMD_ENABLE_DISP | LCD_CMD_ENABLE_BLINK;
lcd_init_buf();
}
int32_t lcd_putchar(int32_t c) {
uint32_t i;
uint32_t savepos;
// newline/line full
// if line was full, an immediate newline is automatically ignored!
if ( (lcd_pos & 0x10) || (c == '\n') || (c == '\r') || (c == '\f') ) {
savepos = lcd_pos;
lcd_pos = 0;
if (lcd_cline) {
lcd_clear();
lcd_home();
lcd_setline(0);
for (i = 0; i < LCD_LEN; i++){
lcd_line_buf[0][i] = lcd_line_buf[1][i];
__lcd_putchar(lcd_line_buf[0][i]);
lcd_line_buf[1][i] = CHAR_SPACE;
}
}
lcd_cline = 1;
lcd_setline(lcd_cline);
if ((c == '\f')) { // set new position
lcd_pos = savepos;
for (i=0; i<savepos; ++i) {
__lcd_putchar(lcd_line_buf[1][i]);
}
}
}
if (c == '\b') { // backspace
--lcd_pos;
lcd_line_buf[lcd_cline][lcd_pos] = CHAR_SPACE;
// rewrite display
lcd_clear();
lcd_home();
lcd_setline(0);
for (i=0; i<(lcd_cline?LCD_LEN:lcd_pos); ++i) {
__lcd_putchar(lcd_line_buf[0][i]);
}
if (lcd_cline) {
lcd_setline(1);
for (i=0; i<lcd_pos; ++i) {
__lcd_putchar(lcd_line_buf[1][i]);
}
}
}
else if (c == '\f') {
// do nothing (already done above)
}
else if (c == '\n') {
// do nothing (already done above)
}
else if (c == '\r') {
// do nothing (already done above)
}
else if (c == '\t') { // tab
int i = 0;
for (i = 0; i < NUM_TABCHARS; i++) __lcd_putchar(TABCHAR);
}
else { // just a char
__lcd_putchar(c);
lcd_line_buf[lcd_cline][lcd_pos] = c;
++lcd_pos;
}
return (uint8_t)c;
}
int32_t lcd_puts(char * p) {
uint32_t ctr = 0;
if (p == NULL) {
return 0;
}
do {
lcd_putchar(*p);
++p;
++ctr;
} while (*p);
return ctr;
}
void lcd_clear(void) {
// Clear display
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
LCD_CMD = LCD_CMD_CLEAR;
}
/*********************************************************** Local functions */
void lcd_init_buf(void) {
lcd_clear();
lcd_home();
lcd_cline = 0;
lcd_pos = 0;
lcd_setline(0);
uint32_t i;
for (i = 0; i < LCD_LEN; i++){
lcd_line_buf[0][i] = CHAR_SPACE;
lcd_line_buf[1][i] = CHAR_SPACE;
}
}
int32_t lcd_setline(uint32_t l) {
if (l >= LCD_LINES) {
return -1;
}
else {
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
LCD_CMD = 0x80 | lcd_line_adr[l];
return 0;
}
}
void lcd_home(void) {
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
LCD_CMD = LCD_CMD_HOME;
}
int32_t __lcd_putchar(int32_t c) {
while(LCD_ST == LCD_BUSY);
my_usleep(1000);
LCD_WR = (uint8_t)c;
return (uint8_t)c;
}
#endif /* HAVE_LCD */
|
C
|
#include <stdio.h>
#include <cs50.h>
typedef struct node
{
int n;
struct node* next;
}
node;
bool insert_node (int value, node* list)
{
// create a new node
node* new_node = malloc(sizeof(node));
if (new_node == NULL)
{
return false;
}
new_node->n = value;
// create curr and prev pointers
node* curr_point = list;
node* prev_point = NULL;
// for an empty list
if (head == NULL)
{
head = new_node;
new_node->next = NULL;
return true;
}
// go through list
while (curr_point != NULL)
{
// if value < this node
if (value < curr_point->n)
{
// insert before
if (prev_point == NULL)
{
head = new_node;
}
else
{
prev_point->next = new_node;
}
new_node->next = curr_point;
// if value > this node
if (value > curr_point->n)
{
// go to next node
prev_point = cur_point;
curr_point = curr_point->next;
// update pointers
}
// if value == node
if (value == curr_point->n)
{
// free new node
free(new_node);
// return false
return false;
}
// must be at end of list
new_node->next = NULL;
prev_point = new_node;
return true;
}
|
C
|
/*
* Copyright (c) 2002, Intel Corporation. All rights reserved.
* This file is licensed under the GPL license. For the full content
* of this license, see the COPYING file at the top level of this
* source tree.
* Test that pthread_rwlock_timedwrlock(pthread_rwlock_t *rwlock)
*
* Under no circumstances shall the function fail with a timeout if the lock can be
* acquired immediately. The abs_timeout parameter need not be checked if the lock
* can be immediately acquired.
*
* Steps:
* 1. Main thread create a thread.
* 2. Child thread lock 'rwlock' for writing with pthread_rwlock_timedwrlock(),
* should not fail with timeout
* 3. The child thread unlocks the 'rwlock' and exit.
* 4. Main thread create another thread.
* 5. The child thread lock 'rwlock' for write, with pthread_rwlock_timedwrlock(),
* specifying a 'abs_timeout'. The thread sleeps untile 'abs_timeout' expires.
* 6. The thread call pthread_rwlock_timedwrlock(). Should not get ETIMEDOUT.
*/
#define _XOPEN_SOURCE 600
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include "posixtest.h"
#define TIMEOUT 1
static int thread_state;
static int currsec1;
static int expired;
/* thread_state indicates child thread state:
1: not in child thread yet;
2: just enter child thread ;
3: just before child thread exit;
*/
#define NOT_CREATED_THREAD 1
#define ENTERED_THREAD 2
#define EXITING_THREAD 3
static void* fn_wr_1(void *arg)
{
thread_state = ENTERED_THREAD;
struct timespec abs_timeout;
int rc;
pthread_rwlock_t rwlock;
if(pthread_rwlock_init(&rwlock, NULL) != 0)
{
printf("thread1: Error at pthread_rwlock_init\n");
exit(PTS_UNRESOLVED);
}
currsec1 = time(NULL);
/* Absolute time, not relative. */
abs_timeout.tv_sec = currsec1 + TIMEOUT;
abs_timeout.tv_nsec = 0;
printf("thread1: attempt timed lock for writing\n");
rc = pthread_rwlock_timedwrlock(&rwlock, &abs_timeout);
if(rc == ETIMEDOUT)
{
printf("thread1: timer expired\n");
expired = 1;
}
else if(rc == 0)
{
printf("thread1: acquired write lock\n");
expired = 0;
printf("thread1: unlock write lock\n");
if(pthread_rwlock_unlock(&rwlock) != 0)
{
printf("thread1: failed to release write lock\n");
exit(PTS_UNRESOLVED);
}
}
else
{
printf("thread1: Error in pthread_rwlock_timedwrlock().\n");
exit(PTS_UNRESOLVED);
}
if(pthread_rwlock_destroy(&rwlock) != 0)
{
printf("thread1: Error at pthread_rwlockattr_destroy()");
exit(PTS_UNRESOLVED);
}
thread_state = EXITING_THREAD;
pthread_exit(0);
return NULL;
}
static void* fn_wr_2(void *arg)
{
thread_state = ENTERED_THREAD;
struct timespec abs_timeout;
int rc;
pthread_rwlock_t rwlock;
if(pthread_rwlock_init(&rwlock, NULL) != 0)
{
printf("thread2: Error at pthread_rwlock_init\n");
exit(PTS_UNRESOLVED);
}
currsec1 = time(NULL);
/* Absolute time, not relative. */
abs_timeout.tv_sec = currsec1 - TIMEOUT;
abs_timeout.tv_nsec = 0;
printf("thread2: attempt timed lock for writing\n");
rc = pthread_rwlock_timedwrlock(&rwlock, &abs_timeout);
if(rc == ETIMEDOUT)
{
printf("thread2: timer expired\n");
expired = 1;
}
else if(rc == 0)
{
printf("thread2: acquired write lock\n");
expired = 0;
printf("thread2: unlock write lock\n");
if(pthread_rwlock_unlock(&rwlock) != 0)
{
printf("thread2: failed to release write lock\n");
exit(PTS_UNRESOLVED);
}
}
else
{
printf("thread2: Error in pthread_rwlock_timedwrlock().\n");
exit(PTS_UNRESOLVED);
}
if(pthread_rwlock_destroy(&rwlock) != 0)
{
printf("thread2: Error at pthread_rwlock_destroy()\n");
exit(PTS_UNRESOLVED);
}
thread_state = EXITING_THREAD;
pthread_exit(0);
return NULL;
}
int main()
{
int cnt = 0;
pthread_t thread1, thread2;
thread_state = NOT_CREATED_THREAD;
printf("main: create thread1\n");
if(pthread_create(&thread1, NULL, fn_wr_1, NULL) != 0)
{
printf("Error when creating thread1\n");
return PTS_UNRESOLVED;
}
/* If the shared data is not altered by child after 5 seconds,
we regard it as blocked */
/* we expect thread1 NOT to block */
cnt = 0;
do{
sleep(1);
}while (thread_state !=3 && cnt++ < 5);
if(thread_state == 3)
{
/* the child thread does not block, check the time expired or not */
if(expired == 1)
{
printf("Test FAILED: thread1 got ETIMEOUT when get the lock\n");
return PTS_FAIL;
}
}
else if(thread_state == ENTERED_THREAD)
{
printf("Test FAILED: thread1 blocked\n");
return PTS_FAIL;
}
else
{
printf("Unexpected state for thread1 %d\n", thread_state);
return PTS_UNRESOLVED;
}
if(pthread_join(thread1, NULL) != 0)
{
printf("Error when joining thread1\n");
return PTS_UNRESOLVED;
}
thread_state = ENTERED_THREAD;
printf("main: create thread2\n");
if(pthread_create(&thread2, NULL, fn_wr_2, NULL) != 0)
{
printf("Error when creating thread2\n");
return PTS_UNRESOLVED;
}
/* If the shared data is not altered by child after 5 seconds,
we regard it as blocked */
/* we expect thread2 NOT to block */
cnt = 0;
do{
sleep(1);
}while (thread_state !=EXITING_THREAD && cnt++ < 3);
if(thread_state == EXITING_THREAD)
{
/* the child thread does not block, check the time expired or not */
if(expired == 1)
{
printf("Test FAILED: thread2 got ETIMEOUT\n");
return PTS_FAIL;
}
}
else if(thread_state == ENTERED_THREAD)
{
printf("Test FAILED: thread2 blocked\n");
return PTS_FAIL;
}
else
{
printf("Unexpected state for thread2 %d\n", thread_state);
return PTS_UNRESOLVED;
}
if(pthread_join(thread2, NULL) != 0)
{
printf("Error when join thread2\n");
return PTS_UNRESOLVED;
}
printf("Test PASSED\n");
return PTS_PASS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tableau
{
int taille;
int T[1500];
};
typedef struct tableau tableau;
int comp_selection;
int comp_insertion;
int comp_bulle;
int alea(int n)
{
return rand()%n;
}
void ini_struct_tab(tableau *a,int tail)
{
int i;
(*a).taille=tail;
for(i=0;i<(*a).taille;i++) (*a).T[i]=alea(20);
}
void affiche_tableau_struct_tab(tableau b)
{
printf("\n");
int i;
for(i=0;i<b.taille;i++) printf("%d\n",b.T[i]);
}
int decale_droite_tableau_struct_tab_modif(tableau *e,int rang)
{
if(rang>(*e).taille)return -1;
int i;
for(i=(*e).taille;i>rang;i--)
{
(*e).T[i]=(*e).T[i-1];
}
(*e).T[rang]=0;
(*e).taille++;
return 1;
}
int inser_tableau_struct_tab(tableau *g,int x)
{
int i;
for(i=0;i<(*g).taille;i++)
{
if((*g).T[i]>x)
{
decale_droite_tableau_struct_tab_modif(g,i);
(*g).T[i]=x;
//(*g).taille++;
return 1;
}
}
(*g).T[(*g).taille]=x;
(*g).taille++;
return 1;
}
void min_tableau_struct_tab_modif(tableau *d,int debut,int fin)
{
int min=debut;
int i;
int tmp;
comp_selection++;
for(i=debut+1;i<(*d).taille;i++)
{
comp_selection+=2;
if((*d).T[i]<(*d).T[min]) min=i;
}
tmp=(*d).T[debut];
(*d).T[debut]=(*d).T[min];
(*d).T[min]=tmp;
}
void tri_selection_tableau_struct_tab(tableau *k,int debut,int fin)
{
comp_selection++;
if(debut == fin);
else
{
min_tableau_struct_tab_modif(k,debut,fin);
tri_selection_tableau_struct_tab(k,debut+1,fin);
//affiche_tableau_struct_tab(*k);
}
}
void inser_tableau_struct_tab_modif(tableau *g,int x)
{
int a = (*g).T[x];
int i,j;
comp_insertion++;
for(i=0;i<x;i++)
{
comp_insertion+=2;
if((*g).T[i]>(*g).T[x])
{
comp_insertion++;
for(j=x;j>i;j--)
{
comp_insertion++;
(*g).T[j] = (*g).T[j-1];
}
(*g).T[i]=a;
}
}
}
void tri_insertion_tableau_struct_tab(tableau *l,int n)
{
comp_insertion++;
if(!(n>((*l).taille-1)))
{
inser_tableau_struct_tab_modif(l,n);
tri_insertion_tableau_struct_tab(l,n+1);
}
}
void tri_bulle_tableau_struct_tab(tableau *m)
{
int tmp;
int i,j;
comp_bulle++;
for(i=0;i<(*m).taille;i++)
{
comp_bulle+=2;
for(j=0;j<(*m).taille-1;j++)
{
comp_bulle+=2;
if((*m).T[j]>(*m).T[j+1])
{
tmp=(*m).T[j];
(*m).T[j]=(*m).T[j+1];
(*m).T[j+1]=tmp;
}
}
}
}
void re_init_cont()
{
comp_selection = 0;
comp_insertion = 0;
comp_bulle = 0;
}
void affiche_comp()
{
printf("nombre de comparaison moyen du tri par selection : %d\n",comp_selection);
printf("nombre de comparaison moyen du tri par insertion : %d\n",comp_insertion);
printf("nombre de comparaison moyen du tri a bulle : %d\n",comp_bulle);
}
void moy_comp(int n)
{
comp_selection /= n;
comp_insertion /= n;
comp_bulle /= n;
}
int main()
{
srand(time(NULL));
tableau tab;
int nombre_tri = 10;
int i,j;
printf("sizeof(tableau) : %lu\n\n",sizeof(tableau));
//printf("%d\n",alea(100));
//ini_struct_tab(&tab,10);
//affiche_tableau_struct_tab(tab);
printf("taille\ttri_selection\ttri_insertion\ttri_bulle\n");
printf("\n");
for(j=100;j<=1500;j+=100)
{
re_init_cont();
for(i=0;i<nombre_tri;i++)
{
ini_struct_tab(&tab,j);
tri_selection_tableau_struct_tab(&tab,0,tab.taille-1);
ini_struct_tab(&tab,j);
tri_insertion_tableau_struct_tab(&tab,1);
ini_struct_tab(&tab,j);
tri_bulle_tableau_struct_tab(&tab);
}
moy_comp(i);
printf("%d\t%d\t%d\t%d\n",j,comp_selection,comp_insertion,comp_bulle);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct fib_test{
int id;
void *point;
// char point[0];
};
int main()
{
struct fib_test *ft;
ft=malloc(sizeof(struct fib_test)+10);
printf("sizeof(struct fib_test)=%d\n",sizeof(struct fib_test));
memset(ft->point,0,10);
printf("memset\n");
sprintf(ft->point,"for test\n");
printf("%s\n",ft->point);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void buildMAX(int arr[],int n);
void heapify(int arr[],int n, int i);
void Swap(int arr[],int a,int b);
int main()
{
int arr[]={4,10,3,5,1};
buildMAX(arr,5);
for(int i=4;i>0;--i){
Swap(arr,i,0);
buildMAX(arr,i);}
}
void buildMAX(int arr[],int n){
int i = n/2;
while(i>0) heapify(arr,n,--i);
}
void heapify(int arr[],int n, int i){
int left=-1,right=-1,large=-1;
if(2*i +1< n) //left
left = 2*i+1;
if(2*i +2<n) //right
right = 2*i+2;
// tree
if(left <0 && right<0) return;
if(left <0) left=right;
if(right <0) right=left;
//jp
large = i;
if(arr[left]>arr[large]) large = left;
if(arr[right]>arr[large]) large = right;
if(large != i){
Swap(arr,large,i);
heapify(arr,n,large);
}
}
void Swap(int arr[],int a,int b){
int tmp;
tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
|
C
|
#include<stdio.h>
main()
{
int n1=5,n2=10;
n1=n1^n2;
n2=n1^n2;
n1=n1^n2;
printf("%d %d",n1,n2);
}
|
C
|
#include <stdlib.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <string.h>
#include "clients.h"
union semun { /* Used in calls to semctl() */
int val;
struct semid_ds * buf;
unsigned short * array;
#if defined(__linux__)
struct seminfo * __buf;
#endif
};
Channel *init_client_manager(){
int shmid = shmget(IPC_PRIVATE, sizeof(Channel), S_IRUSR | S_IWUSR);
Channel *channel;
if(shmid == -1){
perror("shmget");
exit(EXIT_FAILURE);
}
channel = (Channel*)shmat(shmid, NULL, 0);
channel->shmid = shmid;
channel->n = channel->clients;
return channel;
}
/*
* Armazena na memória compartilhada um cliente com seu nickname,
* host e username.
* Retorna -1 caso exceda o numero máximo de inserções e
* 0 se for sucesso.
*/
int insert_client(Channel *channel, char *nickname, char *host){
Client *client = channel->n;
/* Vendo se cabe mais um cliente */
if(client >= channel->clients + MAXCLIENTS)
return -1;
/* Faz a atribuição */
strcpy(client->nickname, nickname);
strcpy(client->host, host);
/* O número de clientes aumenta mais um */
channel->n = client + 1;
return 0;
}
Client *search_client(Channel *channel, char *nickname){
Client *client;
for(client = channel->clients; client < channel->n; client++)
if(!strcmp(client->nickname, nickname))
break;
/* Vendo se não achou o cliente */
if(client == channel->n)
return (Client*) -1;
return client;
}
|
C
|
#include <stdlib.h>
int main(){
int* p = malloc(50);
free(p);
// 'til here, everything fine
int y = 5;
int* x = realloc(&y, 50); // trying to realloc non existing pointer
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
enum position{START_ROOM, MID_ROOM, END_ROOM};
struct Room
{
int id;
char* name;
int numOutboundConnections;
enum position roomLocation;
struct Room *outboundConnections[6];
};
struct Room *allRooms[10];
struct Room *rooms[7];
//int iterableRooms = 10;
//struct Room *remainingRooms[10];
bool IsGraphFull();
void AddRandomConnection();
struct Room *GetRandomRoom();
bool CanAddConnectionFrom(struct Room *x);
bool ConnectionAlreadyExists(struct Room* x, struct Room* y);
void ConnectRoom(struct Room* x, struct Room* y);
bool IsSameRoom(struct Room* x, struct Room* y);
void resizeRoomsArr(struct Room *x);
bool IsGraphFull()
{
int i;
int j;
for (i = 0; i < 7; i++){
if (rooms[i]->numOutboundConnections < 3)
return false;
}
return true;
}
void AddRandomConnection()
{
int i;
struct Room *A;
struct Room *B;
while(true)
{
A = GetRandomRoom();
if (CanAddConnectionFrom(A) == true)
break;
}
do
{
B = GetRandomRoom();
}
while(CanAddConnectionFrom(B) == false || IsSameRoom(A, B) == true || ConnectionAlreadyExists(A, B) == true);
ConnectRoom(A, B); // TODO: Add this connection to the real variables,
ConnectRoom(B, A); // because this A and B will be destroyed when this function terminates
}
struct Room *GetRandomRoom()
{
int random = rand() % 7;
return rooms[random];
}
bool CanAddConnectionFrom(struct Room* x)
{
if (x->numOutboundConnections < 6)
return true;
else
return false;
}
bool ConnectionAlreadyExists(struct Room* x, struct Room* y)
{
int xlength = x->numOutboundConnections;
int ylength = y->numOutboundConnections;
int i;
for (i = 0; i < xlength; i++)
{
if (x->outboundConnections[i]->id == y->id)
return true;
}
for (i = 0; i < ylength; i++)
{
if (y->outboundConnections[i]->id == x->id)
return true;
}
return false;
}
void ConnectRoom(struct Room* x, struct Room* y)
{
x->outboundConnections[x->numOutboundConnections] = y;
x->numOutboundConnections++;
/*if (!CanAddConnectionFrom(x))
resizeRoomsArr(x);*/
}
bool IsSameRoom(struct Room* x, struct Room* y)
{
if (x->id == y->id)
return true;
return false;
}
int main()
{
srand(time(0));
char roomsDir[256];
memset(roomsDir, '\0', 256);
strcpy(roomsDir, "shielcon.rooms.");
int pid = getpid();
char process[20];
sprintf(process, "%d", pid);
strcat(roomsDir, process);
int result = mkdir(roomsDir, 0755);
struct Room theHall;
struct Room Conservatory;
struct Room Kitchen;
struct Room BilliardRoom;
struct Room Lounge;
struct Room Library;
struct Room Study;
struct Room DiningRoom;
struct Room Ballroom;
struct Room MrBoddysGrave;
allRooms[0] = &theHall;
allRooms[1] = &Conservatory;
allRooms[2] = &Kitchen;
allRooms[3] = &BilliardRoom;
allRooms[4] = &Lounge;
allRooms[5] = &Library;
allRooms[6] = &Study;
allRooms[7] = &DiningRoom;
allRooms[8] = &Ballroom;
allRooms[9] = &MrBoddysGrave;
int i;
for (i = 0; i < 10; i++){
allRooms[i]->name = calloc(16, sizeof(char));
allRooms[i]->numOutboundConnections=0;
allRooms[i]->id = i;
}
theHall.name = "Hall";
Conservatory.name = "Conserve";
Kitchen.name = "Kitchen";
BilliardRoom.name = "Billiard";
Lounge.name = "Lounge";
Study.name = "Study";
DiningRoom.name = "Dining";
Ballroom.name = "Ballroom";
MrBoddysGrave.name = "Grave";
Library.name = "Library";
i = 0;
int j;
int roomsAdded = 0;
int random;
bool alreadyAdded;
while (i < 7){
alreadyAdded = false;
random = rand() % 10;
for (j = 0; j < roomsAdded; j++){
if (allRooms[random]->id == rooms[j]->id){
alreadyAdded = true;
break;
}
}
if (!alreadyAdded){
rooms[i] = allRooms[random];
i++;
roomsAdded++;
}
}
rooms[rand() % 7]->roomLocation = 0;
// Create all connections in graph
while (IsGraphFull() == false)
{
AddRandomConnection();
}
for (i = 0; i < 7; i++)
rooms[i]->roomLocation = 1;
rooms[rand() % 7]->roomLocation = 0;
while (true){
random = rand() % 7;
if (rooms[random]->roomLocation != 0){
rooms[random]->roomLocation = 2;
break;
}
}
strcat(roomsDir, "/");
int dirNameLen = strlen(roomsDir);
int roomNameLen;
int file_descriptor;
char connectionNumber[1];
for (i = 0; i < 7; i++){
roomNameLen = strlen(rooms[i]->name);
strcat(roomsDir, rooms[i]->name);
file_descriptor = open(roomsDir, O_WRONLY | O_CREAT, 0600);
write(file_descriptor, "ROOM NAME: ", 11);
write(file_descriptor, rooms[i]->name, roomNameLen);
write(file_descriptor, "\n", 1);
j=0;
while (j < rooms[i]->numOutboundConnections){
sprintf(connectionNumber, "%d", j);
write(file_descriptor, "CONNECTION ", 11);
write(file_descriptor, connectionNumber, sizeof(j));
write(file_descriptor, ": ", 2);
write(file_descriptor, rooms[i]->outboundConnections[j]->name, strlen(rooms[i]->outboundConnections[j]->name));
write(file_descriptor, "\n", 1);
j++;
}
switch(rooms[i]->roomLocation){
case 0 :
write(file_descriptor, "ROOM TYPE: START_ROOM\n", 22);
break;
case 1 :
write(file_descriptor, "ROOM TYPE: MID_ROOM\n", 20);
break;
case 2 :
write(file_descriptor, "ROOM TYPE: END_ROOM\n", 20);
break;
}
close(file_descriptor);
memset(roomsDir + dirNameLen, '\0', roomNameLen);
}
return 0;
}
|
C
|
#include <stdio.h>
void arrays_are_pointers(){
printf("\nArray names are pointers\n\n");
char arr[3] = { 'A','B','C'};
printf("%p %c", &arr, *arr);
printf("Address of arr[0]: \n&arr[0] %p \n\n",&arr[0]);
printf("Value of arr[0]:\n *(&arr[0]) %c or arr[0] %c \n", *(&arr[0]), arr[0]);
}
int main(){
int numbers[5];
int* ptr = numbers; // or &numbers[0]
int base= 2;
// iterate over with pointer
// ptr++ will give us the next box
for (;ptr<&numbers[5]; ptr++ ){
// . *ptr is the value it points
*ptr= base;
base=base*2;
}
for(int i = 0 ; i < 5 ; i++){
printf("%i\n", numbers[i]);
}
arrays_are_pointers();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
char ANSWER_OK[] = "HTTP/1.1 200\n";
char ANSWER_WRONG[] = "HTTP/1.1 404\n";
char CONTENT_IMG[] = "content-type: image\n";
#define OK_LEN sizeof(ANSWER_OK)
#define WRONG_LEN sizeof(ANSWER_WRONG)
int img_num = 1;
enum errors {
OK,
ERR_INCORRECT_ARGS,
ERR_SOCKET,
ERR_CONNECT
};
enum requests {
GET,
POST
};
int init_socket(const char *ip, int port) {
//open socket, result is socket descriptor
int server_socket = socket(PF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
perror("Fail: open socket");
_exit(ERR_SOCKET);
}
//connection
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = inet_addr(ip);
if (connect(server_socket, (struct sockaddr*) &sin, (socklen_t) sizeof(sin)) < 0) {
perror("Fail: connect");
return -1;
}
return server_socket;
}
int str_cmp(char *str1, char *str2) { // 0 - eq, 1 - s1 < s2, 2 - s1 > s2
int i = -1;
do {
i++;
if (str1[i] < str2[i])
return 1;
if (str1[i] > str2[i])
return 2;
} while (str1[i] && str2[i]);
return 0;
}
char *get_ext(char *request_path) {
char *ext = NULL;
int len = 0;
int i;
for (i = 0; request_path[i] != '.' && request_path[i] != '\0'; i++) {
}
for (; request_path[i] != '\0'; i++) {
ext = realloc(ext, (len + 1) * sizeof(char));
ext[len] = request_path[i];
len++;
}
if (len > 0) {
ext = realloc(ext, (len + 1) * sizeof(char));
ext[len] = '\0';
} else
ext = NULL;
return ext;
}
char *recieve_line(int server) {
char ch = 1, *line = NULL;
int len = 1;
int res = read(server, &ch, 1);
if (res <= 0)
return NULL;
line = malloc(sizeof(char));
line[0] = ch;
while (ch != '\n') {
res = read(server, &ch, 1);
if (res <= 0)
break;
line = realloc(line, (len + 1) * sizeof(char));
line[len] = ch;
len++;
}
line = realloc(line, (len + 1) * sizeof(char));
line[len] = '\0';
return line;
}
int recieve_header(int server) {
char *line = NULL;
char *content_type = NULL;
char *content_len = NULL, *buf = NULL;
int is_image = 0;
line = recieve_line(server);
puts(line);
if (str_cmp(line, ANSWER_OK) == 0) {
content_type = recieve_line(server);
content_len = recieve_line(server);
buf = recieve_line(server);
printf("%s%s", content_type, content_len);
if (str_cmp(content_type, CONTENT_IMG) == 0) {
is_image = 1;
}
free(buf);
free(content_type);
free(content_len);
}
free(line);
return is_image;
}
int recieve_img(int server, char *filename) {
int fd, size = 1;
char ch = 1;
char name[] = "image%d%s";
size_t name_len = (strlen(name) + 10) * sizeof(char);
char *ext = get_ext(filename);
char *new_file = malloc(name_len);
snprintf(new_file,name_len, name, img_num, ext);
fd = open(new_file, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR);
img_num++;
free(ext);
free(new_file);
while(1) {
size = read(server, &ch, 1);
if (size <= 0) {
return 0;
}
write(fd, &ch, 1);
}
return 0;
}
void reciever(int server, char *name) {
char ch = 1;
int size = 1, is_img = 0;
is_img = recieve_header(server);
if (is_img) {
recieve_img(server, name);
} else {
while(ch > 0) {
size = read(server, &ch, 1);
if (size <= 0) {
return;
}
putchar(ch);
}
}
}
char *get_text(char end_ch) {
int len = 0;
char ch = 0;
char *text = malloc(sizeof(char));
do {
ch = getchar();
text = realloc(text, (len + 1) * sizeof(char));
text[len] = ch;
len++;
} while (ch != '\n' && ch != end_ch);
text[len - 1] = '\0';
return text;
}
void send_get_request(int server, char *filename, char *host) {
char *message = malloc((15 + strlen(filename)) * sizeof(char));
char *str_host = "host: %s", *host_send = NULL;
host_send = malloc(strlen(str_host) + strlen(host));
sprintf(host_send, str_host, host);
sprintf(message, "GET %s HTTP/1.1\n", filename);
write(server, message, strlen(message));
write(server, host_send, strlen(host_send));
write(server, "\n\n", 2);
free(message);
return;
}
void send_post_request(int server, char *filename, char *host) {
int pos = 0;
while (filename[pos] != '%') {
pos++;
}
size_t msg_size = (17 + pos) * sizeof(char);
char *message = malloc(msg_size), *new_name = malloc((pos + 1) * sizeof(char));
char *str_host = "host: %s\n", *host_send = NULL;
host_send = malloc(strlen(str_host) + strlen(host));
memcpy(new_name, filename, pos);
new_name[pos] = '\0';
sprintf(host_send, str_host, host);
sprintf(message, "POST %s HTTP/1.1\n", new_name);
write(server, message, strlen(message));
write(server, host_send, strlen(host_send));
write(server, filename + pos + 1, strlen(filename) - pos);
write(server, "\n\n", 2);
free(message);
return;
}
char *add_slash(char *filename) {
char *new = NULL;
new = malloc((strlen(filename) + 2) * sizeof(char));
new[0] = '/';
memcpy(new + 1, filename, strlen(filename));
new[strlen(filename) + 1] = '\0';
return new;
}
int get_request_type(char *name) {
for (int i = 0; name[i] != '\0'; i++) {
if (name[i] == '%') {
return POST;
}
}
return GET;
}
int request(char **name) {
char *str_port = NULL;
int port;
char *ip = NULL, *filename = NULL;
int server, request_type = GET;
ip = get_text(':');
str_port = get_text('/');
port = atoi(str_port);
server = init_socket(ip, port);
filename = get_text(' ');
request_type = get_request_type(filename);
*name = filename;
filename = add_slash(filename);
if (server < 0) {
printf("Connection error\n");
printf("%s %s\n", ip, str_port);
return -1;
}
if (request_type == GET) {
send_get_request(server, filename, ip);
} else if (request_type == POST) {
send_post_request(server, filename, ip);
}
free(ip);
free(str_port);
free(filename);
return server;
}
int main() {
while (1) {
int server;
char *name = NULL;
server = request(&name);
if (server < 0) {
close(server);
continue;
}
reciever(server, name);
free(name);
close(server);
}
return OK;
}
|
C
|
#include <stdlib.h>
typedef struct {
int userData1;
int userData2;
} Object;
typedef struct {
Object o;
int privateData;
} ObjectWrapper;
void * cache;
Object* allocate(int u1, int u2) {
ObjectWrapper *ret = malloc(sizeof(ObjectWrapper));
ret->privateData = 0;
ret->o.userData1 = u1;
ret->o.userData2 = u2;
cache = &ret->o;
return &ret->o;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
struct empleado{
char nombre[20];
float salario;
}emple[100],*pemple=emple;
void ingresar_empleados();
void imprimir();
float mayor=0;
float menor=999999;
int posmayor,posmenor;
int empleadon;
int main(){
ingresar_empleados(emple);
imprimir(emple);
return 0;
}
//ingresando usuarios
void ingresar_empleados(){
int numempleados;
printf("ingrese el numero de empleados: ");
scanf("%d",&numempleados);
for(int i=0;i<numempleados;i++){
printf("---------------------------------------------\n");
printf("EMPLEADO #%d\n",i+1);
printf("%d.ingrese su nombre: ",i+1);
fflush(stdin);
fgets((pemple+i)->nombre,20,stdin);
printf("%d.digite su salario: ",i+1);
scanf("%f",&(pemple+i)->salario);
//sacar el mayor salario
if((pemple+i)->salario>mayor){
mayor=(pemple+i)->salario;
posmayor=i;
}
//sacando el menor salario
if((pemple+i)->salario<menor){
menor=(pemple+i)->salario;
posmenor=i;
}
}
}
//imprimiendo el menor y el mayor salario
void imprimir(){
printf("---------------------------------------------\n");
printf("el empleado con mayor salario es:\n");
printf("nombre: %s",(pemple+posmayor)->nombre);
printf("salario: %f",(pemple+posmayor)->salario);
printf("\n---------------------------------------------\n");
printf("el empleado con menor salario es:\n");
printf("nombre: %s",(pemple+posmenor)->nombre);
printf("salario: %f",(pemple+posmenor)->salario);
printf("\n---------------------------------------------\n");
}
|
C
|
#include<stdio.h>
int nhap()
{
int n;
do{
printf("nhap so phan tu mang: ");
scanf("%d",&n);
}
while(n<=0||n>30);
return n;
}
void NhapMang(int a[], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("a[%d]= ",i);
scanf("%d", &a[i]);
}
}
void XuatMang(int a[], int n)
{
int i;
printf("\nMang: ");
for(i=0;i<n;i++)
{
printf("\t%d", a[i]);
}
}
void Chen(int a[], int &n , int VT, int sochen)
{
int i;
for(i=n;i>=VT;i--)
{
a[i]=a[i-1];
}
a[VT]=sochen;
n++;
}
void ChenX(int a[], int &n)
{
int x,VT;
printf("\nnhap so x: ");
scanf("%d",&x);
int i,dem;
for(i=0;i<n;i++)
{
if(a[i]>x)
{
dem++;
VT=i;
break;
}
}
if(dem==0)
{
VT=n;
Chen(a,n,VT,x);
for(i=0;i<n;i++)
{
printf("\t%d", a[i]);
}
}
else
{
Chen(a,n,VT,x);
for(i=0;i<n;i++)
{
printf("\t%d", a[i]);
}
}
}
int main()
{
int n,k;
int a[100];
n=nhap();
NhapMang(a,n);
XuatMang(a,n);
ChenX(a,n);
return 0;
}
|
C
|
/*
* heap.h
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdlib.h>
#include "heap.h"
struct heap_s {
size_t allocated; // number of allocated elements
size_t count; // number of used elements
const void** data; // array of pointers to elements
int (*comparator)(const void* a, const void* b); // elements comparator function
};
heap_t* heap_create(size_t size, int (*comparator)(const void* a, const void* b)) {
heap_t* h = malloc(sizeof(*h));
if (!h) {
return NULL;
}
if (!(h->data = calloc(size, sizeof(*h->data)))) {
free(h);
return NULL;
}
h->allocated = size;
h->count = 0;
h->comparator = comparator;
return h;
}
void heap_destroy(heap_t* h) {
free(h->data);
free(h);
}
bool heap_push(heap_t* h, const void* const elem) {
// Resize the heap if it is too small to hold all the data
if (h->count == h->allocated) {
h->allocated <<= 1;
const void** tmp = realloc(h->data, sizeof(*h->data) * h->allocated);
if (!tmp) {
return false;
}
h->data = tmp;
}
// Find out where to put the element
size_t index, parent;
for (index = h->count++; index; index = parent) {
parent = (index - 1) >> 1;
if (h->comparator(h->data[parent], elem) < 0) {
break;
}
h->data[index] = h->data[parent];
}
h->data[index] = elem;
return true;
}
void* heap_pop(heap_t* h) {
if (h->count == 0) {
return NULL;
}
const void* first = h->data[0];
const void* temp = h->data[--h->count];
// Reorder the elements
size_t index, swap;
for (index = 0; 1; index = swap) {
// Find the child to swap with
swap = (index << 1) + 1;
if (swap >= h->count) {
break; // if there are no children, the heap is reordered
}
const size_t other = swap + 1;
if ((other < h->count) && h->comparator(h->data[other], h->data[swap]) < 0) {
swap = other;
}
if (h->comparator(temp, h->data[swap]) < 0) {
// if the bigger child is bigger than or equal to its parent, the heap is reordered
break;
}
h->data[index] = h->data[swap];
}
h->data[index] = temp;
return (void*)first;
}
size_t heap_size(const heap_t* const h) {
return h->count;
}
|
C
|
/*
* filetable.c
* Author: Gregory Venezia
* Date: 4/27/2015
* Course: CSC3320
* Description: This file provides a file table data structure.
*/
#include "filetable.h"
/*
Creates the table
Pre: None
Post: Adds a table to the volume with a reference in memory.
*/
table_t * filetable_create()
{
table_t * table = (table_t *) malloc(sizeof(table_t));
/* find the last descriptor block */
table->firstFileBlock = descriptorBlock_create(0);
/* TODO: Add condition for empty file table */
table->lastFileBlock = table->firstFileBlock;
return table;
}
/*
Frees up the memory used for the table
Pre: None
Post: Adds a table to the volume with a reference in memory.
*/
void filetable_destroy(table_t * table)
{
if(table->firstFileBlock != NULL)
free(table->firstFileBlock);
if(table->lastFileBlock != NULL)
free(table->lastFileBlock);
if(table != NULL)
free(table);
}
table_t * filetable_load()
{
table_t * table = (table_t *) malloc(sizeof(table_t));
/* find the last descriptor block */
table->firstFileBlock = descriptorBlock_load(0);
/* TODO: Add condition for empty file table */
if(table->firstFileBlock->nextBlock != 0)
table->lastFileBlock = descriptorBlock_load_last();
else
table->lastFileBlock = table->firstFileBlock;
return table;
}
/*
Adds a file to the table
Pre: table must be created, name length must be less than or equal to NAME_LENGTH.
Post: Adds a file to the table.
*/
int filetable_add_file(table_t * table, char * name, unsigned int blockCount)
{
int index = descriptorBlock_add_file(table->lastFileBlock, name, blockCount);
if(index == -1)
{
/* a new block needs to be created to add this file */
descriptorBlock_t * newBlock = descriptorBlock_create(descriptorBlock_find_last_free(table->lastFileBlock));
descriptorBlock_attach(table->lastFileBlock, newBlock);
index = descriptorBlock_add_file(newBlock, name, blockCount);
/* update the blocks on the disk */
descriptorBlock_store(table->lastFileBlock);
descriptorBlock_store(newBlock);
free(table->lastFileBlock);
table->lastFileBlock = newBlock;
return newBlock->descriptors[index]->start;
}
else
{
return table->lastFileBlock->descriptors[index]->start;
}
}
/*
Lists the files in the table
Pre: table has been created
Post: Lists the files int the table.
*/
void filetable_list_files(table_t * table)
{
descriptorBlock_t * current = table->firstFileBlock;
if(current != NULL)
{
do {
descriptorBlock_list_files(current);
if(current->nextBlock != 0)
current = descriptorBlock_load(current->nextBlock);
} while(current->nextBlock != 0);
}
}
/*
Displays all information about the files in the table
Pre: table has been created
Post: Lists all information about the files in the table.
*/
void filetable_display_details(table_t * table)
{
descriptorBlock_t * current = table->firstFileBlock;
if(current != NULL)
{
do {
descriptorBlock_display_details(current);
if(current->nextBlock != 0)
current = descriptorBlock_load(current->nextBlock);
} while(current->nextBlock != 0);
}
}
/*
Removes a file from the table
Pre: table has been created, name is less than or equal to NAME_LENGTH
Post: The file is removed from the table.
*/
int filetable_remove_file(table_t * table, char * name)
{
descriptorBlock_t * current = table->firstFileBlock;
int index = -1; /* the index of the file once its found */
do {
index = descriptorBlock_find_file(current, name);
if(current->nextBlock != 0)
current = descriptorBlock_load(current->nextBlock);
} while(current->nextBlock != 0 && index == -1);
if(index != -1)
{
strcpy(current->descriptors[index]->name, "*removed*");
descriptorBlock_store(current);
}
return index;
}
/*
Finds a file by name in the table
Pre: table has been created, name is less than or equal to NAME_LENGTH
Post: The file found is returned.
*/
file_t * filetable_find_file(table_t * table, char * name)
{
descriptorBlock_t * current = table->lastFileBlock;
int index = -1; /* the index of the file once its found */
do {
current = descriptorBlock_load(current->nextBlock);
index = descriptorBlock_find_file(current, name);
} while(current->nextBlock != 0 && index == -1);
return current->descriptors[index];
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc >= 3){
FILE* a;
FILE* b;
int i=0;
int n;
int sum=0;
a = fopen(argv[1], "r");
b = fopen(argv[2], "w");
while(fscanf(a, "%d", &n) != EOF)
sum += n;
fprintf(b, "%d", sum);
fclose(a);
fclose(b);
}
else
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include<stdint.h>
#include<stdlib.h>
#define WID 1920
#define HEI 1080
#pragma pack(push,1)
typedef struct tagBITMAPFILEHEADER
{
unsigned short bfType;
uint32_t bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
uint32_t bf0ffBits;
}BITMAPFILEHEADER;
#pragma pack(pop)
typedef struct tagBITMAPINFOHEADER
{
uint32_t biSize;
int32_t biWidth;
int32_t biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
uint32_t biCompression;
uint32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
uint32_t biCirUsed;
uint32_t biCirImportant;
}BITMAPINFOHEADER;
typedef struct tagRGBQUAD
{
unsigned char rgbBlue;
unsigned char rgbGreen;
unsigned char rgbRed;
unsigned char rgbReserved;
}RGBQUAD;
typedef struct tagBITMAPINFO
{
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[1];
}BITMAPINFO;
double distance_horo_objects(double xj,double yj,double zj,double xa,double ya){
double r_ja;
double dx;
double dy;
double dz;
dx=xa-xj;
dy=ya-yj;
dz=zj;
r_ja=sqrt(dx*dx+dy*dy+dz*dz); //暗黙の型変換 doubleで計算されてるはず
return r_ja;
}
int main(){
int tensuu;
BITMAPFILEHEADER BmpFileHeader;
BITMAPINFOHEADER BmpInfoHeader;
RGBQUAD RGBQuad[256];
FILE *fp;
int i,j,k;
BmpFileHeader.bfType =19778;
BmpFileHeader.bfSize =14+40+1024+(256*256);
BmpFileHeader.bfReserved1 =0;
BmpFileHeader.bfReserved2 =0;
BmpFileHeader.bf0ffBits =14+40+1024;
BmpInfoHeader.biSize =40;
BmpInfoHeader.biWidth =WID;
BmpInfoHeader.biHeight =HEI;
BmpInfoHeader.biPlanes =1;
BmpInfoHeader.biBitCount =8; //256階調
BmpInfoHeader.biCompression =0L;
BmpInfoHeader.biSizeImage =0L;
BmpInfoHeader.biXPelsPerMeter =0L;
BmpInfoHeader.biYPelsPerMeter =0L;
BmpInfoHeader.biCirUsed =0L;
BmpInfoHeader.biCirImportant =0L;
/*
char filename[20]={};
printf("ファイル名を入力してください : ");
scanf("%s",filename);
*/
fp=fopen("cube284.3d","rb");
if(fp==NULL){
printf("ファイルオープンエラー\n");
}
fread(&tensuu,sizeof(int),1,fp);
printf("物体点数は%dです\n",tensuu);
int *x,*y;
double *z;
x = (int *)malloc(sizeof(int) * tensuu);
y = (int *)malloc(sizeof(int) * tensuu);
z = (double *)malloc(sizeof(double) * tensuu);
int x_buf,y_buf,z_buf;
for(i=0;i<tensuu;i++){
fread(&x_buf,sizeof(int),1,fp);
fread(&y_buf,sizeof(int),1,fp);
fread(&z_buf,sizeof(int),1,fp);
x[i]=x_buf*40;
y[i]=y_buf*40;
z[i]=((double)z_buf)*40;
}
fclose(fp);
/*
for(i=0;i<tensuu;i++){
printf("%d %d %d %f\n",i,x[i],y[i],z[i]);
}
*/
double *img_buf;
img_buf=(double *)malloc(sizeof(double)*WID*HEI);
for(i=0;i<WID*HEI;i++){
img_buf[i]=0.0;
}
double lamda,goukei;
lamda=0.633;
goukei=2.0*M_PI/lamda;
for(i=0;i<HEI;i++){
for(j=0;j<WID;j++){
for(k=0;k<tensuu;k++){
img_buf[i*HEI+j]=img_buf[i*HEI+j]+cos(goukei*distance_horo_objects(x[k],y[k],z[k],j,i));
}
}
}
printf("%f\n",img_buf[15]);
free(img_buf);
free(x);
free(y);
free(z);
return 0;
}
|
C
|
///////////////////////////////////////////////////////////////////////
//Problem Statment: Write a program which accept file name from user and read whole file.
//Developed By : Ashwini Sharad Palve
//Input : File name
//Output : All file containts
//Date : 10-09-2020
//////////////////////////////////////////////////////////////////////
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc, char* argv[])
{
int fd=0;
char buffer[30];
int ret=0, offset=0;
if(argc != 3)
{
printf("Error:Invalid argument!\n");
return -1;
}
if((strcmp(argv[2],"-h") ==0)|| (strcmp(argv[2],"-H") ==0))
{
printf("Usage: ./a.out Executable_Name File_Name");
return 0;
}
fd = open(argv[2],O_RDONLY);
if(fd==-1)
{
printf("Unable to open file!\n");
return -1;
}
else
{
ret = read(fd,buffer,sizeof(buffer));
if(ret != 20)
{
printf("Unable to read contents\n");
}
printf("Read contents are :%s\n",buffer);
// After reading 20 bytes current offset is changed by 20 bytes
offset = lseek(fd,0,SEEK_CUR);
printf("After reading 20 bytes current byte offset is %d\n",offset);
}
close(fd);
return 0;
}
|
C
|
#include "lib_rcc.h"
/**
* @brief Enable MCO (Microcontroller Clock Output).
* @param mco_config: CFGR register MCO configuration 3 bits.
* @retval None
*/
void RCC_MCOEnable(uint8_t mco_config)
{
/* Set 24-26 bits in CFGR regestry */
uint32_t mask = ~(((0x01U << 3) - 0x01U) << 24);
RCC->CFGR = (RCC->CFGR & mask) | (uint32_t)(mco_config << 24);
}
/**
* @brief Set SYSCLK prescaler.
* @param prescaler: CFGR register HPRE 4 bits.
* @note SYSCLK can not exeed 72 MHz.
* @retval None:
*/
void RCC_SetSyclkPrescaler(uint8_t prescaler)
{
uint32_t mask = ~(((0x01U << 4) - 0x01U) << 4);
RCC->CFGR = (RCC->CFGR & mask) | (uint32_t)(prescaler << 4);
}
/**
* @brief Set APB1 (Advanced Peripheral Bus) prescaler.
* @param prescaler: CFGR register PPRE1 3 bits.
* @note APB1 can not exeed 36 MHz.
* @retval None
*/
void RCC_SetAPB1Prescaler(uint8_t prescaler)
{
uint32_t mask = ~(((0x01U << 3) - 0x01U) << 8);
RCC->CFGR = (RCC->CFGR & mask) | (uint32_t)(prescaler << 8);
}
/**
* @brief Set APB2(Advanced Peripheral Bus) prescaler.
* @param prescaler: CFGR register PPRE2 3 bits.
* @retval None
*/
void RCC_SetAPB2Prescaler(uint8_t prescaler)
{
uint32_t mask = ~(((0x01U << 3) - 0x01U) << 11);
RCC->CFGR = (RCC->CFGR & mask) | (uint32_t)(prescaler << 11);
}
/**
* @brief Configure 3 prescalers: SYSCLK, AHB1, AHB2.
* @param clock_config: a pointer to RCC_HSCLKConfig_TypeDef struct containing needed
* prescalers.
* @note SYSCLK can not exeed 72 Mhz.
* @note AHB1 can not exeed 36 MHz.
* @retval None
*/
void RCC_SetPrescalers(RCC_HSCLKConfig_TypeDef * clock_config)
{
RCC_SetSyclkPrescaler(clock_config->RCC_SYSCLK_Prescaler);
RCC_SetAPB1Prescaler(clock_config->RCC_APB1CLK_Prescaler);
RCC_SetAPB2Prescaler(clock_config->RCC_APB2CLK_Prescaler);
}
/**
* @brief Set or reset FLASH_ACR prefetched buffer bit.
* @param state: new state of the prefetched buffer bit.
* @note Prefetched buffer state can be changed only when SYSCLK is lower than 24 MHz.
* and no prescaler is applied on AHB (SYSCLK)
* @retval None
*/
void RCC_SetFlashPrefetchedBuffer(FunctionalState state)
{
uint32_t mask = ~(0x01U << 4);
FLASH->ACR = (FLASH->ACR & mask) | (uint32_t)(state << 4);
}
/**
* @brief Set FLASH memory latency.
* @param latency: new FLASH access latency.
* @note 0x00U, if 0 MHz < SYSCLK ≤ 24 MHz
* 0x01U, if 24 MHz < SYSCLK ≤ 48 MHz
* 0x02U, if 48 MHz < SYSCLK ≤ 72 MHz
* @retval None
*/
void RCC_SetFlashLatency(uint8_t latency)
{
uint32_t mask = ~(0x07U);
FLASH->ACR = (FLASH->ACR & mask) | (uint32_t)(latency);
}
/**
* @brief Configure HSI clock state.
* @param state: new state of HLI clock source.
* @note it will not switch SYSCLK to HLI.
* @todo: rename later when below functions are refactored.
* @retval None
*/
void RCC_ConfigHSI(FunctionalState state)
{
/* if new state is DISABLE, disable HSI and exit */
if (state == DISABLE)
{
RCC->CR &= ~(0x01U);
return;
}
/* Set HSION (High Speed Internal) bit to enable internal generator */
RCC->CR |= 0x01U;
/* Wait for HSI to stabilize */
/* It should be always fine since it's crystal's guts */
for(; ;)
{
/* As soon as HSE is ready it sets 17th bit in RCC_RC regestry. */
if (RCC->CR & (0x01U << 1))
{
break;
}
}
}
/**
* @brief Configure HSE clock state.
* @param state: new state of HSE clock source.
* @note it will not switch SYSCLK to HSE.
* @todo split into several independent functions to actually config and enable/disable
* @retval None
*/
uint32_t RCC_ConfigHSE(FunctionalState state)
{
uint32_t counter;
/* if new state is DISABLE, disable and exit */
if (state == DISABLE)
{
RCC->CR &= ~(0x01U << 16);
return 0x00U;
}
/* Set HSEON (Hight Speed External) bit to enable external generator */
RCC->CR |= 0x01U << 16;
/* Wait for HSE to stabilize */
for (counter = 0; counter < LOOPS_TO_STABILIZE; counter++)
{
/* As soon as HSE is ready it sets 17th bit in RCC_RC regestry. */
if (RCC->CR & (0x01U << 17))
{
return (uint32_t)0x00U;
}
}
/* normally we should not be here. */
/* Let's reset HSEON */
RCC->CR &= ~(0x01U << 16);
/* End return error. */
return (uint32_t)0x01U;
}
/**
* @brief Config PLL source clock.
* @param config: a pointer to RCC_PLLCLKConfig_TypeDef structure.
* @note it will not switch SYSCLK to PLL
* @todo split into several independent functions to actually config and enable/disable
* @retval None
*/
void RCC_ConfigPLL(RCC_PLLCLKConfig_TypeDef * config)
{
uint32_t mask;
switch(config->RCC_PLLCLK_Source)
{
/* if PLL source is HSI. HSI is always divided by 2 */
case RCC_PLLCLKSource_HSI:
/* Reset 16th bit to use HSI PLL source */
RCC->CFGR &= ~(0x01U << 16);
/* Reset HSE PLL prescaler bit */
RCC->CFGR &= ~(0x01U << 17);
break;
/* if PLL source is HSE */
case RCC_PLLCLKSource_HSE_Div1:
/* Reset HSE PLL prescaler bit */
RCC->CFGR &= ~(0x01U << 17);
/* Set 16th bit to use HSE PLL source */
RCC->CFGR |= 0x01U << 16;
break;
/* if PLL source is HSE divided by 2 */
case RCC_PLLCLKSource_HSE_Div2:
/* Set 17th bit to prescale HSE PLL source */
RCC->CFGR |= 0x01U << 17;
/* set 16th bit to use HSE PLL source */
RCC->CFGR |= 0x01U << 16;
break;
default:
/* We should not get here */
return;
}
/* configure PLL multiplication */
mask = ~(((0x01U << 4) - 0x01U) << 18);
RCC->CFGR = (RCC->CFGR & mask) | (uint32_t)(config->RCC_PLLMul_Coef << 18);
// Turn on PLL
RCC->CR |= (0x01U << 24);
/**
* @todo get rid of infinite loop
*/
/* Wait for PLL to init */
for(; ;)
{
/* check PLLRDY flag in RCC_RC */
if(RCC->CR & (0x01U << 25))
{
break;
}
}
}
/**
* @brief Switch SYSCLK to the chosen clock source.
* @param source: clock source to switch to.
* @retval uint32_t: status code. failed if not 0x00U
*/
uint32_t RCC_SelectSysCLKSource(uint8_t source)
{
uint32_t check_flag;
switch(source)
{
case RCC_SYSCLKSource_HSI:
RCC->CFGR &= ~(0x03U);
check_flag = (uint32_t)(RCC_SYSCLKSource_HSI << 2);
break;
case RCC_SYSCLKSource_HSE:
RCC->CFGR = (RCC->CFGR & ~(0x03U)) | (uint32_t)RCC_SYSCLKSource_HSE;
check_flag = (uint32_t)(RCC_SYSCLKSource_HSE << 2);
break;
case RCC_SYSCLKSource_PLL:
RCC->CFGR = (RCC->CFGR & ~(0x03U)) | (uint32_t)RCC_SYSCLKSource_PLL;
check_flag = (uint32_t)(RCC_SYSCLKSource_PLL << 2);
break;
default:
/* We should not get here */
return 0x01U;
}
for (uint32_t counter = 0; counter < LOOPS_TO_STABILIZE; counter++)
{
if ((RCC->CFGR & (0x03U << 2)) == check_flag)
{
return 0x00U;
}
}
/* normally we should not get here*/
return 0x01U;
}
/**
* @brief Configure High Speed clock sources.
* @param clock_config: a pointer to RCC_HSCLKConfig_TypeDef struct.
* @retval uint32_t: non zero, in case of errors.
*/
uint32_t RCC_ConfigHSCLK(RCC_HSCLKConfig_TypeDef * clock_config)
{
/* let's set FLASH registers. Prefetch buffer and latency*/
/* Prefetched buffer is normally on */
RCC_SetFlashPrefetchedBuffer(ENABLE);
/* latency depends on a SYSCLK speed*/
switch(clock_config->RCC_SYSCLK_Frequency)
{
case 0 ... 24:
RCC_SetFlashLatency(FLASH_ACR_LATENCY_0);
break;
case 25 ... 48:
RCC_SetFlashLatency(FLASH_ACR_LATENCY_1);
break;
case 49 ... 72:
RCC_SetFlashLatency(FLASH_ACR_LATENCY_2);
break;
default:
/* we should not get here. We can't exeed 72 MHz */
return 0x01U;
}
/* Let's take care of Prescalers */
RCC_SetPrescalers(clock_config);
if (clock_config->RCC_SYSCLK_Source == RCC_SYSCLKSource_PLL)
{
switch(clock_config->PLLClockConfig->RCC_PLLCLK_Source)
{
case RCC_PLLCLKSource_HSI:
RCC_ConfigHSI(ENABLE);
break;
case RCC_PLLCLKSource_HSE_Div1 ... RCC_PLLCLKSource_HSE_Div2:
RCC_ConfigHSE(ENABLE);
break;
default:
/* we should not get here */
return 0x02U;
}
RCC_ConfigPLL(clock_config->PLLClockConfig);
RCC_SelectSysCLKSource(RCC_SYSCLKSource_PLL);
}
if (clock_config->RCC_SYSCLK_Source == RCC_SYSCLKSource_HSI)
{
RCC_ConfigHSI(ENABLE);
RCC_SelectSysCLKSource(RCC_SYSCLKSource_HSI);
}
if (clock_config->RCC_SYSCLK_Source == RCC_SYSCLKSource_HSE)
{
RCC_ConfigHSE(ENABLE);
RCC_SelectSysCLKSource(RCC_SYSCLKSource_HSE);
}
return 0x00U;
}
|
C
|
#include "sorts.h"
#include <stdlib.h> /*< malloc >*/
#include <stdint.h> /*< uint8_t >*/
#include <string.h> /*< memscpy >*/
static int _CheckSortInputParameters(
void* _arrayOfDataToSort,
size_t _dataSizeInByte,
size_t _arrayDataToSortInByte,
CompareFunc _compareOperation,
SwapFunc _swapOperation,
Sort_Result* _retval
);
Sort_Result BubbleSortOnData(
void* _arrayOfDataToSort,
size_t _dataSizeInByte,
size_t _arrayDataToSortInByte,
CompareFunc _compareOperation,
SwapFunc _swapOperation) {
size_t i = 0;
size_t j = 0;
int isSwapOccur = 0;
size_t maxIters = 0;
uint8_t* arrayRunner = (uint8_t*)_arrayOfDataToSort;
Sort_Result retval;
int checkerResult = _CheckSortInputParameters(
_arrayOfDataToSort,
_dataSizeInByte,
_arrayDataToSortInByte,
_compareOperation,
_swapOperation,
&retval);
if (checkerResult != 0) {
return retval;
}
maxIters = _arrayDataToSortInByte - _dataSizeInByte;
if (NULL == _compareOperation ||
NULL == _swapOperation ||
NULL == _arrayOfDataToSort ||
0 == _dataSizeInByte ||
0 == _arrayDataToSortInByte ||
_arrayDataToSortInByte < _dataSizeInByte) {
return SORT_UNINITIALIZED_ERROR;
}
for (i = 0; i < maxIters ; i += _dataSizeInByte) {
for (j = 0; j < (maxIters - i) ; j += _dataSizeInByte) {
if (_compareOperation(arrayRunner + j, arrayRunner + j + _dataSizeInByte) == BIGGER) {
_swapOperation(arrayRunner + j, arrayRunner + j + _dataSizeInByte);
isSwapOccur = -1;
}
}
if (0 == isSwapOccur) {
return SORT_SUCCESS;
}
}
return SORT_SUCCESS;
}
Sort_Result MergeSortOnData(
void* _arrayOfDataToSort,
size_t _dataSizeInByte,
size_t _arrayDataToSortInByte,
CompareFunc _compareOperation,
SwapFunc _swapOperation
) {
Sort_Result retval;
int checkerResult = _CheckSortInputParameters(
_arrayOfDataToSort,
_dataSizeInByte,
_arrayDataToSortInByte,
_compareOperation,
_swapOperation,
&retval);
if (checkerResult != 0) {
return retval;
}
return SORT_SUCCESS;
}
static int _CheckSortInputParameters(
void* _arrayOfDataToSort,
size_t _dataSizeInByte,
size_t _arrayDataToSortInByte,
CompareFunc _compareOperation,
SwapFunc _swapOperation,
Sort_Result* _retval
) {
if (NULL == _arrayOfDataToSort) {
*_retval = SORT_UNINITIALIZED_ARRAY_DATA_ERROR;
return -1;
}
if (_dataSizeInByte > _arrayDataToSortInByte) {
*_retval = SORT_TOO_SMALL_ARRAY_SIZE_ERROR;
return -1;
}
if (_arrayDataToSortInByte % _dataSizeInByte != 0) {
*_retval = SORT_ARRAY_SIZE_UNELINED_ERROR;
return -1;
}
return 0;
}
|
C
|
#include<STC15.h>
//״̬
typedef unsigned char uchar;
typedef unsigned int uint;
typedef enum Key1_State{Init1_State,Affirm1_State,Single1_State,Repeat1_State};
sbit KEY1 = P3^3;
sbit KEY2 = P3^2;
sbit KEY3 = P3^1;
sbit Led1 = P3^5;
//
//#define key Key1
void KEY_Init(uchar k)
{
static uchar Key1_StateValue = 0; //1״̬־
static uchar Time = 0;
uchar Key1_Value = k; //ȡ1
switch (Key1_StateValue)
{
case Init1_State: //ʼ״̬
{
if(!Key1_Value)
{
Key1_StateValue = Affirm1_State; //´νȷ״̬
}
else{Key1_StateValue = Init1_State;} //ʼ״̬
}
break;
case Affirm1_State: //ȷ״̬
{
if(!Key1_Value)
{
Time = 0;
Key1_StateValue = Single1_State; //´ν뵥δ״̬
}
else{Key1_StateValue = Init1_State;} //ʼ״̬
}
break;
case Single1_State: //δ״̬
{
Time++; //10ms һ
if(Key1_Value) //ſLEDȡصʼ״̬
{
Led1 = ~Led1;
Key1_StateValue = Init1_State;
}
else if(Time == 100) //ʱ1S
{
Time = 0;
Key1_StateValue = Repeat1_State;
}
}
break;
case Repeat1_State: //״̬
{
Time++;
if(10 == Time)
{
Time = 0;
Led1 = ~Led1;
}
else if(Key1_Value)
{
Key1_StateValue = Init1_State;
}
}
break;
default:Key1_StateValue = Init1_State;
break;
}
}
void Timer0_Init(void)
{
TMOD = 0x01;
TH0 = 0xD8;
TL0 = 0xF0;
TR0 = 1;
}
void main(void)
{
Timer0_Init();
P3M1 = 0x00;
P3M0 = 0x00;
while(1)
{
if(TF0) //
{
TF0 = 0;
TH0 = 0xD8;
TL0 = 0xF0;
// if(KEY1)
KEY_Init(KEY1);
// else if(KEY2)
// KEY_Init(KEY2);
// else if(KEY3)
// KEY_Init(KEY3);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.