language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
int main(){
// create user buffer to store user string
char user_buff[10];
printf("created buffer...\n");
// copy string into buffer
memcpy( user_buff, "hello cody", strlen("hello cody"));
printf("copied into buffer...\n");
// open file
FILE *fp;
fp = fopen("/dev/simp_char_dev", "w");
printf("opened device file...\n");
// write to file
fwrite(user_buff, sizeof(char), strlen("hello cody"), fp);
printf("successfully wrote to file...\n");
// close file
fclose(fp);
printf("closed file.\n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse_arg_dlr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: afaddoul <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/08 19:03:25 by afaddoul #+# #+# */
/* Updated: 2019/08/02 18:21:09 by afaddoul ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libftprintf.h"
void parse_arg_dlr(t_tmp_data **tab, va_list *ap, int index)
{
if (tab[index]->conv == 'c')
tab[index]->c = va_arg(*ap, int);
else if (tab[index]->conv == 's')
tab[index]->s = va_arg(*ap, char*);
else if (tab[index]->conv == 'p')
tab[index]->p = va_arg(*ap, void*);
else if (tab[index]->conv == 'd')
tab[index]->d = va_arg(*ap, long long);
else if (tab[index]->conv == 'u')
tab[index]->u = va_arg(*ap, unsigned long long);
else if (tab[index]->conv == 'o')
tab[index]->o = va_arg(*ap, unsigned long long);
else if (tab[index]->conv == 'x')
tab[index]->x = va_arg(*ap, unsigned long long);
else if (tab[index]->conv == 'X')
tab[index]->big_x = va_arg(*ap, unsigned long long);
else if ((tab[index]->conv == 'f') ||
(tab[index]->conv == 'f' && tab[index]->lm[2]))
tab[index]->dbl = va_arg(*ap, double);
else if (tab[index]->conv == 'f' && tab[index]->lm[4])
tab[index]->l_dbl = va_arg(*ap, long double);
else if (tab[index]->conv == '%')
tab[index]->s = ft_strdup("%");
}
t_tmp_data **fill_sorted_arr(t_tmp_data **tab, va_list *ap)
{
int i;
i = 0;
while (tab[i])
{
parse_arg_dlr(tab, ap, i);
i++;
}
return (tab);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "employee.h"
/*
unsigned int employee_get_num (struct employee* list)
{
unsigned int i;
for (i = 0; list[i].name[0]; i++);
return i;
}
*/
void employee_print (struct employee* e)
{
printf ("Name: %s\n", e->name);
printf (" Age: %u\n", e->age);
printf ("Wage: %u\n", e->wage);
}
void employee_print_all (struct employee* list) {
// print all employee info
unsigned int i, id;
printf("--------------\n");
for (i = 0, id = 0; i < NUM_ELEMENTS; i++)
if (list[i].age) {
printf("Employee #%u\n", id);
employee_print(list + i); // print data for each employee
printf("--------------\n");
id++; // next person in list
}
}
void employee_sort (struct employee* list) {
// bubble sorting alrogithm
unsigned int i, j;
struct employee tmp;
for (i = 0; i < (NUM_ELEMENTS - 1); i++)
for (j = 0; j < (NUM_ELEMENTS - 1); j++)
if (list[j].age > list[j+1].age) { // if the current age entry is greater than the next one
tmp = list[j]; // store it in tmp
list[j] = list[j+1]; // swap current and next
list[j+1] = tmp; // assign temp to next entry
}
}
int employee_add (struct employee* list) {
// add employee to record
char firstname[128], lastname[128];
struct employee new;
//unsigned int* age; // debugging
//unsigned int* wage; // debugging
unsigned int i;
printf("First Name: "); // prompt user
scanf("%s", firstname); // get user input
printf("Last Name: "); // prompt user
scanf("%s", lastname); // get user input
strcat(strcat(firstname, " "), lastname); // combine first and last name (with space)
strcpy(new.name, firstname); // store name as "name" member of struct
//printf("%s\n", list->name); // debugging
printf("Age: "); // prompt user
scanf("%u", &new.age); // get user input
//list->age = *age; // debugging: store user input "age" as "age" member of struct
//printf("%u years old\n", age); // debugging
printf("Wage: "); // prompt user
scanf("%u", &new.wage); // get user input
//list->wage = wage; // debugging: store user input "wage" as "wage" member of struct
//printf("$%u\n", list->wage); // debugging
for (i = 0; i < NUM_ELEMENTS; i++)
if (list[i].age == 0) { // if there is no entry
list[i] = new; // make the that entry the new entry
employee_sort(list); // sort the list in age ascending order
return 0;
}
return 1;
}
int employee_delete (struct employee* list) {
unsigned int sel_id, id;
unsigned int i;
printf("Enter ID # to delete: ");
scanf("%u", &sel_id);
for (i = 0, id = 0; i < NUM_ELEMENTS; i++) {
if (list[i].age) {
if (id == sel_id) {
memset(&list[i], 0, sizeof *list); // set memory of selected employee to 0
employee_sort(list); // sort employees
printf("** Employee #%u Deleted **\n", sel_id);
return 0;
}
id++;
}
}
printf("** Invalid Selection **\n");
// return to menu
return 1;
}
|
C
|
#include<stdio.h>
#define TRUE 1
#define FALSE 0
#define SIZE 4
int n = SIZE;
int W[SIZE][SIZE] = {
{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}
};
int vindex[SIZE];
int promising(int i){
int j; int swt;
if (i == n - 1 && !W[vindex[n - 1]][vindex[0]]){ // n-1 ΰ
swt = FALSE;
}
else if (i > 0 && !W[vindex[i - 1]][vindex[i]]){// ̾
swt = FALSE;
}
else{
swt = TRUE;
j = 0;
while (j < i && swt){
if (vindex[i] == vindex[j]) swt = FALSE; // ռ FALSE
j++;
}
}
return swt; //
}
void hamiltonian(int i){
int j;
if (promising(i)){
if (i == n - 1){ //
for (j = 0; j < SIZE; j++) printf("%d ", vindex[j]); //
printf("\n");
}
else{
for (j = 1; j < n; j++){ // ִ´.
vindex[i + 1] = j;
hamiltonian(i + 1);// عϾ Լ ȣ
}
}
}
}
int main(void){
vindex[0] = 0; // 0
hamiltonian(0);
return 0;
}
|
C
|
extern int __VERIFIER_nondet_int();
/** Find a number greater than seed that is divisble by 3 */
int generateNumberDiv3(int seed){
int old;
do{
old = seed;
seed++;
} while (old%3 != 0);
return seed;
}
int main(){
// Generate a number that is divisible by 3
int seed = __VERIFIER_nondet_int();
int div3 = generateNumberDiv3(seed);
// POST-CONDITION check if the number is divisble by 3
if(div3 % 3 != 0)
goto ERROR;
EXIT: return 0;
ERROR: return 1;
}
|
C
|
/*
Feladat: Keresse meg a legnagyobb olyan 2003-nál kisebb egész számot, amely 123-mal osztható.
*/
// Horváth András József megoldása
#include <stdio.h>
int main()
{
for (int i = 2003; i >= 0; --i)
{
if (i % 123 == 0)
{
printf("%i\n", i);
break;
}
}
return 0;
}
|
C
|
#include "transaction_manager.h"
#include "operations.h"
#include "site_data.h"
#include <ctype.h>
#include <sys/select.h>
#define SITE_FAILED_WAIT
#define WRITE_PENDING 1
#define IS_WRITE_FINISHED 0
#define WRITE_FAILED -1
#define SLEEP_DURATION 200
void abortTrx(struct trx_opn *opn);
void Sleep_ms(int time_ms);
/***************parseInputFile function:***************
* parses the file received in input
* stores the individual operations like begin, end, read, write etc into the transaction queue
* assigns timestamp to each operation
* *************************************************************/
int parseInputFile(char *inputfile)
{
int status = 0;
int time_stamp = 0 ;
int i;
int trx_id;
FILE *fp;
T[OTHER_TRX_ID].trxType = OTHER_TRX ;
/* Open the file in read mode to read the input operations and store them in order of their requests */
fp = fopen(inputfile, "r") ;
if(fp == NULL) {
printf("parseInputFile: failed to open file") ;
return -1 ;
}
printf("file opened successfully\n");
while(!feof(fp))
{
char opn_data[100];
char *temp_opn;
char *temp_tok;
char *temp_tok1;
char temp_token[100];
const char s[2] = ";";
memset(opn_data,0,100) ;
memset(temp_token,0,100) ;
fscanf(fp, "%s", opn_data) ;
if(opn_data[0] == '/' || opn_data[0] == '#')
{
fgets(opn_data,100,fp);
continue;
}
printf("operation data extracted from file is |%s|\n",opn_data);
temp_tok1 = strstr(opn_data,s);
if(temp_tok1 != NULL)
{
temp_tok = strtok(opn_data,";");
while(temp_tok != NULL)
{
printf("\n token string = %s",temp_tok);
memset(temp_token,0,100);
strncpy(temp_token,temp_tok,100);
if(strncmp(temp_token,"begin", strlen("begin")) == 0
|| strncmp(temp_token,"R", strlen("R")) == 0
|| strncmp(temp_token,"W", strlen("W")) == 0
|| strncmp(temp_token,"fail", strlen("fail")) == 0
|| strncmp(temp_token,"recover", strlen("recover")) == 0
|| strncmp(temp_token,"dump", strlen("dump")) == 0
|| strncmp(temp_token,"end", strlen("end")) == 0
|| strncmp(temp_token,"querystate", strlen("querystate")) == 0)
{
status = addOpn(temp_token, time_stamp);
if(status == -1)
{
printf("\n parseInputFile: AddOpn failed for operation %s",opn_data);
return -1;
}
}
temp_tok = strtok(NULL,";");
}
time_stamp++;
}
else
{
if(strncmp(opn_data,"begin", strlen("begin")) == 0
|| strncmp(opn_data,"R", strlen("R")) == 0
|| strncmp(opn_data,"W", strlen("W")) == 0
|| strncmp(opn_data,"fail", strlen("fail")) == 0
|| strncmp(opn_data,"recover", strlen("recover")) == 0
|| strncmp(opn_data,"dump", strlen("dump")) == 0
|| strncmp(opn_data,"end", strlen("end")) == 0
|| strncmp(opn_data, "querystate", strlen("querystate")) == 0)
{
status = addOpn(opn_data, time_stamp);
if(status == -1)
{
printf("\n parseInputFile: AddOpn failed for operation %s",opn_data);
return -1;
}
/* Check if the line has more than one operation occuring concurrently */
temp_opn = strstr(opn_data, ";");
if(temp_opn == NULL)
{
time_stamp++;
}
}
}
}
return 0;
}
/***************addOpn Function******************
* creates a new transaction for begin operation
* prepares operation info for all other operation
* Adds the operation to the transaction Queue
* *********************************************/
int addOpn(char *opn_str, int ts)
{
int trx_id = -1;
int status;
int opn_type;
char *temp_str;
int trx_type;
struct trx_opn *temp_opn = (struct trx_opn *)malloc(sizeof(struct trx_opn ));
if(temp_opn == NULL)
{
printf("addOpn: critical failure") ;
return -1 ;
}
if(strncmp(opn_str,"beginRO", strlen("beginRO")) == 0)
{
temp_str = opn_str;
while(!isdigit(*temp_str))
temp_str++;
trx_id = atoi(temp_str);
trx_type = RO_TRX;
status = generateTrx(trx_id, trx_type, ts);
if(status == -1)
{
printf("addOpn: generateTrx returns error for new transaction tid %d\n", trx_id) ;
return -1 ;
}
}
else if(strncmp(opn_str,"begin", strlen("begin")) == 0)
{
temp_str = opn_str;
while(!isdigit(*temp_str))
temp_str++;
trx_id = atoi(temp_str);
trx_type = RW_TRX;
status = generateTrx(trx_id, trx_type, ts);
if(status == -1)
{
printf("addOpn: generateTrx returns error for new transaction tid %d\n", trx_id) ;
return -1 ;
}
}
else if(strncmp(opn_str,"dump", strlen("dump")) == 0)
{
int var_num = -1;
int write_val = -1;
int site_no;
trx_id = OTHER_TRX_ID;
temp_str = strstr(opn_str, "(") ;
if(temp_str == NULL)
{
return -1;
}
while(*temp_str != ')' && !isalpha(*temp_str) && !isdigit(*temp_str))
temp_str++;
if(*temp_str == ')') /* Check if dump operation needs to be performed on all variables of all sites */
{
var_num = ALL_VARS;
site_no = ALL_SITES;
}
else if(isdigit(*temp_str))
{
var_num = ALL_VARS;
site_no = atoi(temp_str);
}
else if(isalpha(*temp_str))
{
while(!isdigit(*temp_str))
temp_str++;
var_num = atoi(temp_str);
site_no = ALL_SITES;
}
opn_type = DUMP;
status = prepOpnInfo(trx_id, opn_type, var_num, write_val, site_no, ts, temp_opn);
if(status == -1)
{
printf("addOpn:: prepOpnInfo returns error for dump operation\n") ;
return -1 ;
}
addToQueue(trx_id, temp_opn) ;
}
else if(strncmp(opn_str,"end", strlen("end")) == 0)
{
int var_num = -1;
int write_val = -1;
int site_no = -1;
temp_str = opn_str;
while(!isdigit(*temp_str))
temp_str++;
trx_id = atoi(temp_str);
opn_type = END;
status = prepOpnInfo(trx_id, opn_type, var_num, write_val, site_no, ts, temp_opn);
if(status == -1)
{
printf("prepOpnInfo failed to add end operation to queue %d\n", trx_id);
return -1;
}
addToQueue(trx_id, temp_opn);
}
else if(strncmp(opn_str,"R", strlen("R")) == 0)
{
int var_num = -1;
int write_val = -1;
int site_no = -1;
temp_str = opn_str;
while(!isdigit(*temp_str))
temp_str++ ;
trx_id = atoi(temp_str) ;
while(isdigit(*temp_str))
temp_str++ ;
while(!isdigit(*temp_str))
temp_str++ ;
var_num = atoi(temp_str);
opn_type = READ;
status = prepOpnInfo(trx_id, opn_type, var_num, write_val, site_no, ts, temp_opn);
if(status == -1) {
printf("addOpn: prepOpnInfo returns error for new operation\n") ;
return -1 ;
}
addToQueue(trx_id, temp_opn);
}
else if(strncmp(opn_str,"W", strlen("W")) == 0)
{
int var_num = -1;
int write_val = -1;
int site_no = -1;
temp_str = opn_str;
while(!isdigit(*temp_str))
temp_str++ ;
trx_id = atoi(temp_str);
while(isdigit(*temp_str))
temp_str++ ;
while(!isdigit(*temp_str))
temp_str++ ;
var_num = atoi(temp_str) ;
while(isdigit(*temp_str))
temp_str++ ;
while(!isdigit(*temp_str) && *temp_str != '-')
temp_str++ ;
write_val = atoi(temp_str);
opn_type = WRITE;
status = prepOpnInfo(trx_id, opn_type, var_num, write_val, site_no, ts, temp_opn);
if(status == -1)
{
printf("storeOperation: prepareOperationNode returns error for new operation\n") ;
return -1 ;
}
addToQueue(trx_id, temp_opn);
}
else if(strncmp(opn_str,"fail", strlen("fail")) == 0)
{
int site_no = 0;
int var_num = -1;
int write_val = -1 ;
trx_id = OTHER_TRX_ID;
temp_str = strstr(opn_str, "(") ;
if(temp_str == NULL) {
printf("addOpn: prepOpnInfo returns error for fail operation ") ;
return -1 ;
}
while(!isdigit(*temp_str))
temp_str++;
site_no = atoi(temp_str) ;
opn_type = FAIL;
status = prepOpnInfo(trx_id, opn_type, var_num, write_val, site_no, ts, temp_opn);
if(status == -1)
{
printf("prepOpnInfo failed to add fail operation to queue %d\n", trx_id);
return -1;
}
addToQueue(trx_id, temp_opn);
}
else if(strncmp(opn_str,"recover", strlen("recover")) == 0)
{
int site_no = 0;
int var_num = -1;
int write_val = -1;
trx_id = OTHER_TRX_ID ;
temp_str = strstr(opn_str, "(") ;
if(temp_str == NULL)
{
printf("addOpn: Could not parse recover operation %s\n", opn_str) ;
return -1 ;
}
while(!isdigit(*temp_str))
temp_str++ ;
site_no = atoi(temp_str);
opn_type = RECOVER;
status = prepOpnInfo(trx_id, opn_type, var_num, write_val, site_no, ts, temp_opn);
if(status == -1)
{
printf("addOpn: prepOpnInfo returns error for recover operation\n") ;
return -1 ;
}
addToQueue(trx_id, temp_opn);
}
else if(strncmp(opn_str,"querystate", strlen("querystate")) == 0)
{
int site_no = 0;
int var_num = -1;
int write_val = -1;
trx_id = OTHER_TRX_ID;
site_no = ALL_SITES;
var_num = ALL_VARS;
opn_type = QUERY_STATE;
status = prepOpnInfo(trx_id, opn_type, var_num, write_val, site_no, ts, temp_opn);
if(status == -1)
{
printf("addOpn: prepOpnInfo returns error for querystate operation\n") ;
return -1 ;
}
addToQueue(trx_id, temp_opn);
}
}
/*************initTransMngr Function:***************
* initializes all values of the transaction stucture
* Initializes site information for all sites
* ***********************************************/
void initTransMngr()
{
int trx_id, site_no, var_num;
for(trx_id = 0; trx_id < MAX_TRANSACTIONS; trx_id++)
{
T[trx_id].timestamp = -1 ;
T[trx_id].trxType = -1 ;
T[trx_id].trxStatus = -1 ;
T[trx_id].inactiveTickNo = -1 ;
T[trx_id].valid_trx_ind = 0 ;
T[trx_id].first_opn = NULL;
T[trx_id].last_opn = NULL;
T[trx_id].current_opn = NULL ;
for(site_no = 0; site_no < MAX_SITES; site_no++)
{
T[trx_id].sites_accessed[site_no].tick_first_access = -1 ;
T[trx_id].sites_accessed[site_no].W_site_accessed = 0 ;
}
}
for(var_num = 1; var_num < MAX_VARS ; var_num++)
{
if(var_num % 2 == 1)
{
site_no = (var_num % 10) + 1 ;
siteInfo[site_no].var_exists_flag[var_num] = 1 ;
}
else
{
for(site_no = 1; site_no < MAX_SITES ; site_no++ )
{
siteInfo[site_no].var_exists_flag[var_num] = 1 ;
}
}
}
for(site_no = 1; site_no < MAX_SITES; site_no++)
{
siteInfo[site_no].site_up = 1 ; /* We assume that all sites will be up initially */
siteInfo[site_no].up_ts = 0 ;
}
}
/* Creates a new transaction for each begin or beginRO operation */
int generateTrx(int trx_id, int trx_type, int timestamp)
{
if(trx_id >= MAX_TRANSACTIONS)
{
printf("generateTrx: Transaction limit exceeded.....abort\n");
return -1;
}
if(T[trx_id].timestamp != -1)
{
printf("generateTrx: duplicate transaction ..... aborting\n");
return -1;
}
T[trx_id].timestamp = timestamp ;
T[trx_id].trxType = trx_type ;
T[trx_id].valid_trx_ind = 1 ;
return 0;
}
/***********prepOpnInfo Function:****************
* Set operation paramters for each operation
* set status for each operation as pending
* Assigns transaction type to corresponding operation's timestamp
* **************************************************************/
int prepOpnInfo(int trx_id, int opn_type, int var_num, int write_val, int site_no, int timestamp, struct trx_opn *opn)
{
int siteNum = 0;
opn->trx_id = trx_id;
opn->opn_type = opn_type;
opn->opn_ts = timestamp;
opn->next_opn = NULL;
opn->var_num = var_num;
opn->write_val = write_val;
opn->site_num = site_no;
opn->opn_tick_num = -1;
for(siteNum = 1; siteNum < MAX_SITES; siteNum++)
{
opn->site_opn_sts[siteNum] = OPERATION_PENDING;
}
if(T[trx_id].timestamp == -1 && trx_id == OTHER_TRX_ID)
{
T[trx_id].timestamp = timestamp;
}
opn->trx_type = T[trx_id].trxType;
opn->trx_ts = T[trx_id].timestamp;
return 0;
}
/************ addToQueue Function: *************************************
* Adds current operation to the respective transaction's queue
* Assign current operation to Transaction's first, current and last operation
* ***************************************************************************/
void addToQueue(int trx_id, struct trx_opn *opr)
{
if(T[trx_id].first_opn == NULL)
{
T[trx_id].first_opn = opr;
T[trx_id].last_opn = opr;
T[trx_id].current_opn = opr;
}
else
{
T[trx_id].last_opn->next_opn = opr;
T[trx_id].last_opn = opr;
}
return;
}
/*************** startTrxMngr Function***************************
* Fetches the operations from transaction queue
* Calls perform operation function to perform each of the operations in the queue
* In case of conflict, blocks the operation and adds it to the waitlist
* At every tick, tries to perform the blocked operation
* Commits each transaction on receipt of end operation
* Sleeps every 200 milliseconds before the next tick
* ************************************************************/
void startTrxMngr()
{
int tick_no = 0;
int trx_id;
int isPending = 1;
int opn_status;
int siteNum;
while(isPending != 0)
{
printf("\n\n\n*******startTransactionManager: tick number %d************\n", tick_no) ;
isPending = 0;
while(T[OTHER_TRX_ID].current_opn != NULL)
{
if(isPending == 0)
isPending = 1;
if(T[OTHER_TRX_ID].current_opn->opn_ts > tick_no) /* transaction operation doesn't belong to current tick so we break */
{
break;
}
if(T[OTHER_TRX_ID].timestamp <= tick_no && T[OTHER_TRX_ID].current_opn->opn_ts <= tick_no)
{
struct trx_opn *opr = T[OTHER_TRX_ID].current_opn ;
if(opr->opn_type == DUMP)
{
if(opr->var_num == ALL_VARS)
{
if(opr->site_num == ALL_SITES)
{
int i;
for(i = 1; i < MAX_SITES; i++)
{
if(siteInfo[i].site_up == 0) /* If site is not up then do not send dump operation to it */
continue;
/* Calling function to perform the dump operation */
perfOpn(opr, i);
opn_status = opr->site_opn_sts[i];
if(opn_status != OPERATION_COMPLETE)
{
printf("dump operation did not complete at site %d\n", i);
opr->site_opn_sts[i] = OPERATION_COMPLETE; /* Set operation to complete to free the site for access by other transactions */
}
}
}
else if(opr->site_num != ALL_SITES)
{
if(siteInfo[opr->site_num].site_up == 0)
{
printf("Dump operation cannot be performed as site %s is down\n",opr->site_num);
}
else
{
perfOpn(opr, opr->site_num);
opn_status = opr->site_opn_sts[opr->site_num];
if(opn_status != OPERATION_COMPLETE)
{
printf("dump operation did not complete at site %d\n", opr->site_num);
opr->site_opn_sts[opr->site_num] = OPERATION_COMPLETE;
}
}
}
}
else if(opr->var_num != ALL_VARS)
{
if(opr->var_num % 2 == 1)
{
siteNum = (opr->var_num % 10) + 1;
if(siteInfo[siteNum].site_up == 0)
{
printf("Dump operation cannot be performed on variable %d as site %d is down\n",opr->var_num,siteNum);
}
else
{
perfOpn(opr, siteNum);
opn_status = opr->site_opn_sts[siteNum];
if(opn_status != OPERATION_COMPLETE)
{
printf("dump operation did not complete at site %d\n", siteNum);
opr->site_opn_sts[siteNum] = OPERATION_COMPLETE;
}
}
}
else
{
for(siteNum = 1; siteNum < MAX_SITES; siteNum++)
{
if(siteInfo[siteNum].site_up == 0)
{
printf("Dump operation cannot be performed on variable %d as site %d is down\n",opr->var_num,siteNum);
continue;
}
perfOpn(opr, siteNum);
opn_status = opr->site_opn_sts[siteNum];
if(opn_status != OPERATION_COMPLETE)
{
printf("dump operation did not complete at site %d\n", siteNum);
opr->site_opn_sts[siteNum] = OPERATION_COMPLETE;
}
}
}
}
}
else if(opr->opn_type == FAIL )
{
perfOpn(opr, opr->site_num);
siteInfo[opr->site_num].site_up = 0; /* Make site unavailable for read or write */
}
else if(opr->opn_type == RECOVER)
{
perfOpn(opr, opr->site_num);
if(siteInfo[opr->site_num].site_up == 0)
{
siteInfo[opr->site_num].site_up = 1;
siteInfo[opr->site_num].up_ts = tick_no;
}
}
else if(opr->opn_type == QUERY_STATE)
{
int site_num;
int opn_status = 0;
int tid;
for(site_num = 1 ; site_num < MAX_SITES; site_num++)
{
if(siteInfo[site_num].site_up == 0)
continue;
perfOpn(opr, site_num);
opn_status = opr->site_opn_sts[site_num] ;
if(opn_status == OPERATION_REJECTED)
{
printf("Query state operation rejected at site %d\n", site_num);
}
if(opn_status == OPERATION_BLOCKED)
{
printf("Query state operation blocked at site %d\n", site_num);
}
if(opn_status != OPERATION_COMPLETE)
{
printf("Query state operation failed to complete at site %d\n", site_num);
opr->site_opn_sts[site_num] = OPERATION_COMPLETE;
}
}
for(tid = 0; tid < MAX_TRANSACTIONS ; tid++)
{
if(tid == OTHER_TRX_ID || T[tid].timestamp > tick_no || T[tid].timestamp == -1)
continue ;
if(T[tid].current_opn == NULL)
{
if(T[tid].trxStatus == TRX_COMMITED)
{
printf("startTrxMngr: querystate - Transaction ID: %d COMMITED\n", tid) ;
}
else
{
printf("startTrxMngr: querystate - Transaction ID: %d ABORTED\n", tid) ;
}
}
else if(T[tid].current_opn->opn_ts < tick_no)
{
if(T[tid].current_opn->opn_type == READ)
{
printf("startTrxMngr: querystate - Transaction ID: %d is waiting for operation read on variable %d arrived at tick No. %d to be completed\n", tid, T[tid].current_opn->var_num, T[tid].current_opn->opn_ts) ;
}
else if(T[tid].current_opn->opn_type == WRITE)
{
printf("startTrxMngr: querystate - Transaction ID: %d is waiting for operation write on variable %d with value %d arrived at tick No. %d to be completed\n", tid, T[tid].current_opn->var_num, T[tid].current_opn->write_val, T[tid].current_opn->opn_ts) ;
}
}
else if(T[tid].current_opn->opn_ts >= tick_no)
{
printf("startTrxMngr: querystate - Transaction ID: %d is waiting for new operation to arrive from input Sequence\n", tid, T[tid].current_opn->var_num, T[tid].current_opn->write_val, T[tid].current_opn->opn_ts);
}
}
}
T[OTHER_TRX_ID].current_opn = T[OTHER_TRX_ID].current_opn->next_opn;
}
}
for(trx_id = 0 ; trx_id < MAX_TRANSACTIONS ; trx_id++)
{
if(trx_id == OTHER_TRX_ID)
continue;
if(T[trx_id].current_opn != NULL)
{
if(isPending == 0)
isPending = 1;
if(T[trx_id].timestamp > tick_no)
continue;
if(T[trx_id].current_opn->opn_ts <= tick_no)
{
struct trx_opn *temp_opr = T[trx_id].current_opn;
if(temp_opr->opn_type == READ)
{
if(temp_opr->var_num % 2 == 1)
{
int siteNo = (temp_opr->var_num % 10) + 1 ;
temp_opr->site_num = siteNo;
if(temp_opr->site_opn_sts[siteNo] == OPERATION_PENDING )
{
if(siteInfo[siteNo].site_up == 0 )
{
#ifdef ABORT_SITE_FAIL
printf("Transaction ID: %d Aborted since read on variable %d failed due to site %d failure\n", trx_id, temp_opr->var_num, temp_opr->site_num);
T[trx_id].current_opn = NULL;
#endif
#ifdef SITE_FAILED_WAIT
if(temp_opr->opn_tick_num == -1)
temp_opr->opn_tick_num = tick_no;
temp_opr->site_opn_sts[siteNo] = OPERATION_PENDING;
printf("Transaction ID: %d blocked at read on variable %d since site %d has temporarily failed. Retrying on next tick\n", trx_id, temp_opr->var_num, siteNo);
continue;
#endif
}
else
{
temp_opr->site_num = siteNo ;
temp_opr->opn_tick_num = -1 ;
perfOpn(temp_opr, siteNo) ;
if(temp_opr->site_opn_sts[siteNo] == OPERATION_REJECTED)
{
printf("Transaction ID: %d will abort as read on var_num %d is rejected by site %d\n", trx_id, temp_opr->var_num, temp_opr->site_num);
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
}
else if(temp_opr->site_opn_sts[siteNo] == OPERATION_BLOCKED)
{
printf("Transaction ID: %d is blocked for read on var_num %d at site %d\n", trx_id, temp_opr->var_num, temp_opr->site_num);
}
else if(temp_opr->site_opn_sts[siteNo] == OPERATION_COMPLETE)
{
if(T[trx_id].sites_accessed[siteNo].tick_first_access == -1)
T[trx_id].sites_accessed[siteNo].tick_first_access = tick_no;
T[trx_id].current_opn = T[trx_id].current_opn->next_opn;
printf("Transaction ID: %d Read operation on var_num %d returns %d value from site %d\n", trx_id, temp_opr->var_num, temp_opr->read_val, temp_opr->site_num);
}
} /* End of else condition */
} /* End of if condition for OPERATION_PENDING */
else if(temp_opr->site_opn_sts[siteNo] == OPERATION_BLOCKED)
{
if(siteInfo[siteNo].site_up == 0)
{
#ifdef ABORT_SITE_FAIL
printf("Transaction ID: %d will abort as read on var_num %d at site %d timed out\n", trx_id, temp_opr->var_num, temp_opr->site_num);
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
#endif
#ifdef SITE_FAILED_WAIT
if(temp_opr->opn_tick_num == -1)
temp_opr->opn_tick_num = tick_no;
printf("Transaction ID: %d has been blocked at read on var_num %d as site %d has failed\n", trx_id, temp_opr->var_num, temp_opr->site_num);
temp_opr->site_opn_sts[siteNo] = OPERATION_PENDING;
}
#endif
} /* End of else if condition for OPERATION_BLOCKED */
else if(temp_opr->site_opn_sts[siteNo] == OPERATION_COMPLETE)
{
if(T[trx_id].sites_accessed[siteNo].tick_first_access == -1)
T[trx_id].sites_accessed[siteNo].tick_first_access = tick_no;
T[trx_id].current_opn = T[trx_id].current_opn->next_opn;
printf("Transaction ID: %d Read operation on var_num %d returns %d value from site %d\n", trx_id, temp_opr->var_num, temp_opr->read_val, temp_opr->site_num);
}
} /* End of if condition for check of var_num % 2 */
else
{
ATTEMPT_READ_AGAIN:
if(temp_opr->site_num == -1)
temp_opr->site_num = 1;
if(siteInfo[temp_opr->site_num].site_up == 0)
{
while(siteInfo[temp_opr->site_num].site_up == 0 && temp_opr->site_num < MAX_SITES)
{
temp_opr->site_num++;
}
if(temp_opr->site_num == MAX_SITES)
{
#ifdef ABORT_SITE_FAIL
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
continue;
#endif
#ifdef SITE_FAILED_WAIT
if(temp_opr->opn_tick_num == -1)
temp_opr->opn_tick_num = tick_no;
temp_opr->site_opn_sts[temp_opr->site_num] = OPERATION_PENDING;
for(int i = 1; i < MAX_SITES; i++)
temp_opr->site_opn_sts[temp_opr->site_num] = OPERATION_PENDING;
temp_opr->site_num = 1;
printf("Transaction ID: %d is blocked at read on var_num %d as all sites have failed. Retrying on the sites at the next tick\n", trx_id, temp_opr->var_num);
continue;
#endif
}
}
if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_PENDING)
{
temp_opr->opn_tick_num = -1;
perfOpn(temp_opr, temp_opr->site_num);
if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_REJECTED)
{
temp_opr->site_num++;
if(temp_opr->site_num == MAX_SITES)
{
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
continue;
}
else
{
goto ATTEMPT_READ_AGAIN;
}
}
else if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_BLOCKED)
{
printf("Transaction ID: %d blocked for read on var %d at site %d since site could not provide the lock\n", trx_id, temp_opr->var_num, temp_opr->site_num);
}
else if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_COMPLETE)
{
if(T[trx_id].sites_accessed[temp_opr->site_num].tick_first_access == -1)
T[trx_id].sites_accessed[temp_opr->site_num].tick_first_access = tick_no;
printf("Transaction ID: %d Read operation on var_num %d returns %d value from site %d\n", trx_id, temp_opr->var_num, temp_opr->read_val, temp_opr->site_num);
T[trx_id].current_opn = T[trx_id].current_opn->next_opn;
}
}
else if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_BLOCKED)
{
if(siteInfo[temp_opr->site_num].site_up == 0)
{
temp_opr->site_num++;
if(temp_opr->site_num == MAX_SITES)
{
#ifdef ABORT_SITE_FAIL
printf("Transaction ID: %d will abort as read on var_num %d at site %d timed out\n", trx_id, temp_opr->var_num, temp_opr->site_num) ;
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
continue;
#endif
#ifdef SITE_FAILED_WAIT
if(temp_opr->opn_tick_num == -1)
temp_opr->opn_tick_num = tick_no;
for(int i = 1; i < MAX_SITES; i++)
{
temp_opr->site_opn_sts[i] == OPERATION_PENDING;
}
temp_opr->site_num = 1;
printf("Transaction ID: %d blocked at read on var_num %d as all sites have failed. Retrying on the sites at the next tick\n", trx_id, temp_opr->var_num);
continue;
#endif
}
}
else
printf("\n Transaction %d waiting to read from site %d for variable x%d",trx_id, temp_opr->site_num, temp_opr->var_num);
}
else if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_COMPLETE)
{
if(T[trx_id].sites_accessed[temp_opr->site_num].tick_first_access == -1)
T[trx_id].sites_accessed[temp_opr->site_num].tick_first_access = tick_no;
printf("Transaction ID: %d Read operation on var_num %d returns %d value from site %d\n", trx_id, temp_opr->var_num, temp_opr->read_val, temp_opr->site_num);
T[trx_id].current_opn = T[trx_id].current_opn->next_opn;
}
}
} /* End of if condition for READ operation */
else if(temp_opr->opn_type == WRITE)
{
if(temp_opr->var_num %2 == 1)
{
int siteNo = (temp_opr->var_num % 10) + 1 ;
temp_opr->site_num = siteNo;
if(temp_opr->site_opn_sts[siteNo] == OPERATION_PENDING)
{
if(siteInfo[siteNo].site_up == 0)
{
#ifdef ABORT_SITE_FAIL
printf("Transaction: %d will abort as write on variable x%d with value %d failed at site %d \n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
T[trx_id].current_opn = NULL ;
#endif
#ifdef SITE_FAILED_WAIT
if(temp_opr->opn_tick_num == -1)
temp_opr->opn_tick_num = tick_no;
temp_opr->site_opn_sts[siteNo] = OPERATION_PENDING ;
printf("Transaction %d blocked for write on variable x%d with value %d as site %d is down\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
#endif
}
else
{
temp_opr->site_num = siteNo ;
temp_opr->opn_tick_num = -1 ;
perfOpn(temp_opr, siteNo);
if(temp_opr->site_opn_sts[siteNo] == OPERATION_REJECTED )
{
printf("Transaction %d will abort as write on variable %d with value %d is rejected by site %d\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
abortTrx(temp_opr) ;
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
}
else if(temp_opr->site_opn_sts[siteNo] == OPERATION_BLOCKED)
{
printf("Transaction ID: %d blocked for write on variable x%d with value %d at site %d as lock not granted\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
}
else if(temp_opr->site_opn_sts[siteNo] == OPERATION_COMPLETE)
{
printf("Transaction %d write on variable x%d with value %d done at site %d\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
T[trx_id].current_opn = T[trx_id].current_opn->next_opn ;
if(T[trx_id].sites_accessed[siteNo].tick_first_access == -1)
T[trx_id].sites_accessed[siteNo].tick_first_access = tick_no;
if(T[trx_id].sites_accessed[siteNo].W_site_accessed == 0)
T[trx_id].sites_accessed[siteNo].W_site_accessed = 1 ; //Set a flag indicating transaction has accessed the site for write operation
}
}
}
else if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_BLOCKED)
{
if(siteInfo[temp_opr->site_num].site_up == 0)
{
#ifdef ABORT_SITE_FAIL
printf("Transaction: %d will abort as write on variable x%d with value %d failed at site %d due to timeout\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
#endif
#ifdef SITE_FAILED_WAIT
if(temp_opr->opn_tick_num == -1)
temp_opr->opn_tick_num = tick_no;
temp_opr->site_opn_sts[siteNo] = OPERATION_PENDING ;
printf("Transaction %d blocked for write on variable x%d with value %d as site %d is down\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
#endif
}
else
{
printf("Transaction %d waiting for write on variable x%d with value %d at site %d\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num);
}
}
else if(temp_opr->site_opn_sts[temp_opr->site_num] == OPERATION_COMPLETE)
{
printf("Transaction %d write on variable x%d with value %d done\n", trx_id, temp_opr->var_num, temp_opr->write_val, temp_opr->site_num) ;
T[trx_id].current_opn = T[trx_id].current_opn->next_opn;
}
}
else
{
int site_num;
int write_status = IS_WRITE_FINISHED;
int write_done = 0 ;
for(site_num = 1; site_num < MAX_SITES; site_num++)
{
if(temp_opr->site_opn_sts[site_num] == OPERATION_IGNORE || temp_opr->site_opn_sts[site_num] == OPERATION_COMPLETE)
{
continue;
}
else if(temp_opr->site_opn_sts[site_num] == OPERATION_PENDING)
{
if(siteInfo[site_num].site_up == 0)
{
temp_opr->site_opn_sts[site_num] = OPERATION_IGNORE;
continue;
}
else
{
temp_opr->opn_tick_num = -1 ;
perfOpn(temp_opr, site_num) ;
if(temp_opr->site_opn_sts[site_num] == OPERATION_REJECTED)
{
printf("Transaction %d write on variable x%d with value %d is rejected by site %d\n", trx_id, temp_opr->var_num, temp_opr->write_val, site_num);
write_status = WRITE_FAILED;
break;
}
else if(temp_opr->site_opn_sts[site_num] == OPERATION_BLOCKED)
{
printf("Transaction %d blocked for write on variable x%d with value %d at site %d as lock\n", trx_id, temp_opr->var_num, temp_opr->write_val, site_num);
if(write_status != WRITE_PENDING)
{
write_status = WRITE_PENDING;
}
}
else if(temp_opr->site_opn_sts[site_num] == OPERATION_COMPLETE)
{
if(write_done == 0)
{
write_done = 1;
}
if(T[trx_id].sites_accessed[site_num].tick_first_access == -1)
{
T[trx_id].sites_accessed[site_num].tick_first_access = tick_no;
}
if(T[trx_id].sites_accessed[site_num].W_site_accessed == 0)
{
T[trx_id].sites_accessed[site_num].W_site_accessed = 1 ;
}
printf("Transaction %d write on variable %d with value %d at site %d finished\n", trx_id, temp_opr->var_num, temp_opr->write_val, site_num);
}
}
}
else if(temp_opr->site_opn_sts[site_num] == OPERATION_BLOCKED)
{
if(siteInfo[site_num].site_up == 0)
{
temp_opr->site_opn_sts[site_num] = OPERATION_IGNORE;
}
else
{
printf("Transaction %d waiting for write on variable x%d with value %d at site %d\n", trx_id, temp_opr->var_num, temp_opr->write_val, site_num);
if(write_status != WRITE_PENDING)
write_status = WRITE_PENDING;
}
}
else if(temp_opr->site_opn_sts[site_num] == OPERATION_COMPLETE)
{
if(T[trx_id].sites_accessed[site_num].tick_first_access == -1)
T[trx_id].sites_accessed[site_num].tick_first_access = tick_no;
if(T[trx_id].sites_accessed[site_num].W_site_accessed == 0)
T[trx_id].sites_accessed[site_num].W_site_accessed = 1;
if(write_done == 0)
write_done = 1;
printf("Transaction %d write on variable x%d with value %d at site %d finished\n", trx_id, temp_opr->var_num, temp_opr->write_val, site_num);
}
}
if(write_status == IS_WRITE_FINISHED)
{
if(write_done == 1)
{
T[trx_id].current_opn = T[trx_id].current_opn->next_opn ;
printf("Transaction %d write on variable %d with value %d completed at all available sites\n", trx_id, temp_opr->var_num, temp_opr->write_val);
}
else
{
#ifdef ABORT_SITE_FAIL
printf("Transaction %d will be aborted as write on var_num %d with value %d could not be completed at any of the sites\n", trx_id, temp_opr->var_num, temp_opr->write_val) ;
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED ;
T[trx_id].current_opn = NULL ;
#endif
#ifdef SITE_FAILED_WAIT
if(temp_opr->opn_tick_num == -1)
{
temp_opr->opn_tick_num = tick_no;
}
for(int i = 1; i < MAX_SITES; i++)
{
temp_opr->site_opn_sts[i] = OPERATION_PENDING ;
}
printf("Transaction ID: %d blocked at write on variable x%d with value %d as all sites have failed. Retrying on the sites at the next tick\n", trx_id, temp_opr->var_num, temp_opr->write_val) ;
#endif
}
}
else if(write_status == WRITE_FAILED)
{
printf("Transaction %d ABORTED since write on varNo %d with value to be written %d rejected by site %d\n", trx_id, temp_opr->var_num, temp_opr->write_val, site_num) ;
abortTrx(temp_opr) ;
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL;
}
}
}
else if(temp_opr->opn_type == END)
{
int siteNo;
int commit_ind = 1 ;
for(siteNo = 1; siteNo < MAX_SITES && commit_ind == 1 && T[trx_id].trxType != RO_TRX; siteNo++)
{
if(T[trx_id].sites_accessed[siteNo].tick_first_access != -1)
{
if(siteInfo[siteNo].up_ts > T[trx_id].sites_accessed[siteNo].tick_first_access)
{
commit_ind = 0;
abortTrx(temp_opr);
T[trx_id].trxStatus = TRX_ABORTED;
T[trx_id].current_opn = NULL ;
}
}
}
if(commit_ind == 1)
{
printf("\n Transaction %d commited at tick number %d\n",trx_id, tick_no);
for(siteNo = 1; siteNo < MAX_SITES; siteNo++)
{
if(T[trx_id].sites_accessed[siteNo].tick_first_access != -1 && siteInfo[siteNo].site_up == 1)
{
perfOpn(T[trx_id].current_opn,siteNo);
}
}
T[trx_id].current_opn = NULL ;
T[trx_id].trxStatus = TRX_COMMITED;
}
}
} /* End of if condition for operation time stamp <= tick_no */
}
else if(T[trx_id].current_opn == NULL && (T[trx_id].trxStatus == -1 && T[trx_id].valid_trx_ind == 1))
{
if(isPending == 0)
{
isPending = 1;
}
if(T[trx_id].inactiveTickNo == -1)
{
T[trx_id].inactiveTickNo = tick_no;
}
else
{
printf("\nTransaction %d still WAITING for a new operation from the input for over %d ticks\n",trx_id, (tick_no - T[trx_id].inactiveTickNo));
}
}
}
Sleep_ms(SLEEP_DURATION);
tick_no++;
}
}
/********** abortTrx Function: **************
* Aborts the current transaction
* sets all its operations to NULL
* Clear all the site information for the transaction
* ******************************************/
void abortTrx(struct trx_opn *opn)
{
struct trx_opn abort_opr;
int site_no ;
int trx_id = opn->trx_id;
memcpy(&abort_opr, opn, sizeof(struct trx_opn));
abort_opr.opn_type = ABORT;
for(site_no = 1; site_no < MAX_SITES; site_no++)
{
abort_opr.site_num = site_no;
abort_opr.next_opn_site = NULL ;
if(T[trx_id].sites_accessed[site_no].tick_first_access != -1 && siteInfo[site_no].site_up == 1)
{
perfOpn(&abort_opr, site_no) ;
}
}
return ;
}
/* Function to make the transaction manager sleep for 200 milliseconds */
void Sleep_ms(int time_ms)
{
struct timeval tv ;
tv.tv_sec = 0 ;
tv.tv_usec = time_ms * 1000 ;
select(0, NULL , NULL, NULL, &tv) ;
return ;
}
|
C
|
#include <stdio.h>
int contains(int x1, int y1, int x2, int y2, int x3, int y3)
{
double det, lambda1, lambda2, lambda3;
det = 1.0 / ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
lambda1 = det * ((y2 - y3) * (-x3) + (x3 - x2) * (-y3));
if (lambda1 <= 0.0 || lambda1 >= 1.0)
return 0;
lambda2 = det * ((y3 - y1) * (-x3) + (x1 - x3) * (-y3));
if (lambda2 <= 0.0 || lambda2 >= 1.0)
return 0;
lambda3 = 1.0 - lambda1 - lambda2;
return lambda3 > 0.0 && lambda3 < 1.0;
}
int main(int argc, char **argv)
{
FILE *file = fopen("problem102.txt", "r");
if (!file)
return 1;
int c = 0;
do {
int x1, y1, x2, y2, x3, y3;
fscanf(file, "%d,%d,%d,%d,%d,%d", &x1, &y1, &x2, &y2, &x3, &y3);
if (feof(file))
break;
c += contains(x1, y1, x2, y2, x3, y3);
} while (1);
printf("%d\n", c);
return 0;
}
|
C
|
//
// Created by Ruochen Xie on 2019-07-25.
//
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MaxVertexNum 100
#define INFINITY 65535
typedef int Vertex;
typedef int WeightType;
typedef struct GNode * PtrToGNode;
struct GNode {
int Nv; // 顶点
int Ne; // 边
WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;
typedef struct ENode * PtrToENode;
struct ENode {
Vertex V1, V2;
WeightType Weight;
};
typedef PtrToENode Edge;
int D[100][100] = {0};
bool Floyd( MGraph Graph, WeightType D[][MaxVertexNum] );
MGraph BuildGraph();
void FindAnimal (MGraph Graph);
WeightType FindMaxDist(WeightType D[][MaxVertexNum], Vertex i, int N);
MGraph CreateGraph( int VertexNum );
void InsertEdge( MGraph Graph, Edge E);
int main(void) {
MGraph G = BuildGraph();
FindAnimal(G);
return 0;
}
MGraph BuildGraph() {
MGraph Graph;
Edge E;
int Nv, i;
scanf("%d", &Nv);
Graph = CreateGraph(Nv);
scanf("%d", &(Graph->Ne));
E = (Edge)malloc(sizeof(struct ENode));
for (i = 0; i < Graph->Ne; i++) {
scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
E->V1--;
E->V2--;
InsertEdge(Graph, E);
}
return Graph;
}
// 模块1,2: 建造图以及插入边
MGraph CreateGraph( int VertexNum ) {
Vertex V, W;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (V = 0; V<Graph->Nv; V++) {
for (W=0; W<Graph->Nv; W++) {
Graph->G[V][W] = INFINITY;
}
}
return Graph;
}
void InsertEdge( MGraph Graph, Edge E) {
Graph->G[E->V1][E->V2] = E->Weight;
Graph->G[E->V2][E->V1] = E->Weight;
}
void FindAnimal (MGraph Graph) {
WeightType D[MaxVertexNum][MaxVertexNum], MaxDist, MinDist;
Vertex Animal, i;
Floyd(Graph, D); //设定矩阵
MinDist = INFINITY;
for ( i = 0; i < Graph->Nv; i++) {
MaxDist = FindMaxDist( D, i, Graph->Nv); //寻找每一行的最大值
if (MaxDist == INFINITY) {
printf("0\n");
return;
}
if (MinDist > MaxDist) {
MinDist = MaxDist;
Animal = i+1;
}
}
printf("%d %d\n", Animal, MinDist);
}
// 建造最小路径矩阵以及
bool Floyd( MGraph Graph, WeightType D[][MaxVertexNum] )
{
Vertex i, j, k;
/* 初始化 */
for ( i=0; i<Graph->Nv; i++ )
for( j=0; j<Graph->Nv; j++ ) {
D[i][j] = Graph->G[i][j];
}
for( k=0; k<Graph->Nv; k++ )
for( i=0; i<Graph->Nv; i++ )
for( j=0; j<Graph->Nv; j++ )
if( D[i][k] + D[k][j] < D[i][j] ) {
D[i][j] = D[i][k] + D[k][j];
}
}
WeightType FindMaxDist(WeightType D[][MaxVertexNum], Vertex i, int N) {
WeightType MaxDist;
Vertex j;
MaxDist = 0;
for( j=0; j<N; j++) {
if (i != j && D[i][j] > MaxDist) {
MaxDist = D[i][j];
}
}
return MaxDist;
}
|
C
|
/*
============================================================================
Name : secondProject.c
Author : Arion Almond
Version :
Copyright : Open Source
Description : This project dynamically allocates an array
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main(void)
{
int a;
int *p_array;
int i;
printf("Enter the number of bytes to dynamically allocate:");
scanf("%d", &a);
printf("Numbers in dynamically allocated memory: %d\n", a);
p_array = (int *)malloc(a * sizeof(int));
for(i=0; i<a; i++)
{
p_array[i]=i;
}
for(i=0;i<a;i++)
{
printf("%10d", p_array[i]);
if ((i+1)%10 == 0)
printf("\n");
}
return 0;
}
|
C
|
/****************************************************************************/
/* */
/* MAINLOOP */
/* Main Program Loop */
/* Digital Oscilloscope Project */
/* EE/CS 52 */
/* */
/****************************************************************************/
/*
This file contains the main processing loop (background) for the Digital
Oscilloscope project. The only global function included is:
main - background processing loop
The local functions included are:
key_lookup - get a key and look up its keycode
The locally global variable definitions included are:
none
Revision History
3/8/94 Glen George Initial revision.
3/9/94 Glen George Changed initialized const arrays to static
(in addition to const).
3/9/94 Glen George Moved the position of the const keyword in
declarations of arrays of pointers.
3/13/94 Glen George Updated comments.
3/13/94 Glen George Removed display_menu call after plot_trace,
the plot function takes care of the menu.
3/17/97 Glen George Updated comments.
3/17/97 Glen George Made key_lookup function static to make it
truly local.
3/17/97 Glen George Removed KEY_UNUSED and KEYCODE_UNUSED
references (no longer used).
5/27/08 Glen George Changed code to only check for sample done if
it is currently sampling.
*/
/* library include files */
/* none */
/* local include files */
#include "interfac.h"
#include "scopedef.h"
#include "keyproc.h"
#include "menu.h"
#include "tracutil.h"
/* local function declarations */
static enum keycode key_lookup(void); /* translate key values into keycodes */
/*
main
Description: This procedure is the main program loop for the Digital
Oscilloscope. It loops getting keys from the keypad,
processing those keys as is appropriate. It also handles
starting scope sample collection and updating the LCD
screen.
Arguments: None.
Return Value: (int) - return code, always 0 (never returns).
Input: Keys from the keypad.
Output: Traces and menus to the display.
Error Handling: Invalid input is ignored.
Algorithms: The function is table-driven. The processing routines
for each input are given in tables which are selected
based on the context (state) the program is operating in.
Data Structures: Array (process_key) to associate keys with actions
(functions to call).
Global Variables: None.
Author: Glen George
Last Modified: May 27, 2008
*/
int main()
{
/* variables */
enum keycode key; /* an input key */
enum status state = MENU_ON; /* current program state */
unsigned char *sample; /* a captured trace */
/* key processing functions (one for each system state type and key) */
static enum status (* const process_key[NUM_KEYCODES][NUM_STATES])(enum status) =
/* Current System State */
/* MENU_ON MENU_OFF Input Key */
{ { menu_key, menu_key }, /* <Menu> */
{ menu_up, no_action }, /* <Up> */
{ menu_down, no_action }, /* <Down> */
{ menu_left, no_action }, /* <Left> */
{ menu_right, no_action }, /* <Right> */
{ no_action, no_action } }; /* illegal key */
/* first initialize everything */
clear_display(); /* clear the display */
init_trace(); /* initialize the trace routines */
init_menu(); /* initialize the menu system */
/* infinite loop processing input */
while(TRUE) {
/* check if ready to do a trace */
if (trace_rdy())
/* ready for a trace - do it */
do_trace();
/* check if have a trace to display */
if (is_sampling() && ((sample = sample_done()) != NULL)) {
/* have a trace - output it */
plot_trace(sample);
/* done processing this trace */
trace_done();
}
/* now check for keypad input */
if (key_available()) {
/* have keypad input - get the key */
key = key_lookup();
/* execute processing routine for that key */
state = process_key[key][state](state);
}
}
/* done with main (never should get here), return 0 */
return 0;
}
/*
key_lookup
Description: This function gets a key from the keypad and translates
the raw keycode to an enumerated keycode for the main
loop.
Arguments: None.
Return Value: (enum keycode) - type of the key input on keypad.
Input: Keys from the keypad.
Output: None.
Error Handling: Invalid keys are returned as KEYCODE_ILLEGAL.
Algorithms: The function uses an array to lookup the key types.
Data Structures: Array of key types versus key codes.
Global Variables: None.
Author: Glen George
Last Modified: Mar. 17, 1997
*/
static enum keycode key_lookup()
{
/* variables */
const static enum keycode keycodes[] = /* array of keycodes */
{ /* order must match keys array exactly */
KEYCODE_MENU, /* <Menu> */ /* also need an extra element */
KEYCODE_UP, /* <Up> */ /* for unknown key codes */
KEYCODE_DOWN, /* <Down> */
KEYCODE_LEFT, /* <Left> */
KEYCODE_RIGHT, /* <Right> */
KEYCODE_ILLEGAL /* other keys */
};
const static int keys[] = /* array of key values */
{ /* order must match keycodes array exactly */
KEY_MENU, /* <Menu> */
KEY_UP, /* <Up> */
KEY_DOWN, /* <Down> */
KEY_LEFT, /* <Left> */
KEY_RIGHT, /* <Right> */
};
int key; /* an input key */
int i; /* general loop index */
/* get a key */
key = getkey();
/* lookup key in keys array */
for (i = 0; ((i < (sizeof(keys)/sizeof(int))) && (key != keys[i])); i++);
/* return the appropriate key type */
return keycodes[i];
}
|
C
|
#include<stdio.h>
void main()
{
int i,j;
printf("enter i & j : ");
scanf("%d",&i);
scanf("%d",&j);
i=i+j-(i%j);
printf("i =%d",i);
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "locationList.h"
#include "location.h"
#include "../common/2d/2d.h"
#include "../common/error/error.h"
#include "../common/io/outputStream.h"
#include "../common/io/printWriter.h"
#include "../common/string/cenString.h"
void initLocationList(LocationList* locationList, Location(*locationListArray)[], unsigned int locationListSize) {
if (locationList == NULL) {
writeError(LOCATION_LIST_NULL);
return;
}
locationList->locations = locationListArray;
locationList->maxSize = locationListSize;
}
void clearLocationList(LocationList* locationList) {
locationList->size = 0;
}
bool isEmptyLocationList(LocationList* locationList) {
return locationList->size == 0;
}
Location* getLocation(LocationList* locationList, unsigned int index) {
if (locationList == NULL || locationList->maxSize == 0) {
writeError(LOCATION_LIST_NOT_INITIALIZED);
return NULL;
}
if (index < 0 || index >= locationList->maxSize) {
writeError(LOCATION_LIST_INDEX_OUT_OF_BOUNDS);
return NULL;
}
Location* result = (Location*) locationList->locations;
// we don't need use sizeof because our pointer is a Location* pointer, so the shift
// is already of the structure, we just have to shift of index.
result += index;
return result;
}
void copyLocation(Location* sourceLocation, Location* targetLocation) {
copyFixedCharArray(&(sourceLocation->name), &(targetLocation->name));
targetLocation->label = sourceLocation->label;
targetLocation->computedCost = sourceLocation->computedCost;
targetLocation->computedHandled = sourceLocation->computedHandled;
targetLocation->computedNextLocation = sourceLocation->computedNextLocation;
targetLocation->computedPreviousLocation = sourceLocation->computedPreviousLocation;
targetLocation->x = sourceLocation->x;
targetLocation->y = sourceLocation->y;
}
void initLocation(Location* location, enum LocationUsageType usageType, char* name, char* label, float x, float y) {
location->usageType = usageType;
FixedCharArray* existingLocationName = &(location->name);
stringToFixedCharArray(name, existingLocationName);
location->x = x;
location->y = y;
location->label = label;
location->computedCost = NO_COMPUTED_COST;
location->computedHandled = false;
location->computedNextLocation = NULL;
location->computedPreviousLocation = NULL;
}
Location* addNamedLocation(LocationList* locationList, enum LocationUsageType locationUsageType, char* name, char* label, float x, float y) {
if (locationList == NULL || locationList->maxSize == 0) {
writeError(LOCATION_LIST_NOT_INITIALIZED);
return NULL;
}
unsigned int size = locationList->size;
if (size < locationList->maxSize) {
Location* location = getLocation(locationList, size);
initLocation(location, locationUsageType, name, label, x, y);
locationList->size++;
return location;
} else {
writeError(TOO_MUCH_LOCATIONS);
return NULL;
}
}
Location* addLocation(LocationList* locationList, enum LocationUsageType locationUsageType, FixedCharArray* name, char* label, float x, float y) {
Location* result = addNamedLocation(locationList, locationUsageType, NULL, label, x, y);
if (result != NULL) {
FixedCharArray* target = &(result->name);
copyFixedCharArray(name, target);
}
return NULL;
}
Location* findLocationByStringName(LocationList* locationList, char* name) {
FixedCharArray tempFixedCharArray;
stringToFixedCharArray(name, &tempFixedCharArray);
Location* result = findLocationByName(locationList, &tempFixedCharArray);
return result;
}
Location* findLocationByName(LocationList* locationList, FixedCharArray* locationName) {
unsigned int i;
unsigned int size = locationList->size;
for (i = 0; i < size; i++) {
Location* location = getLocation(locationList, i);
FixedCharArray* locationName2 = &(location->name);
if (fixedCharArrayEquals(locationName, locationName2)) {
return location;
}
}
return NULL;
}
bool containsLocation(LocationList* locationList, Location* locationToFind, bool handled) {
if (locationToFind == NULL) {
return false;
}
int i;
int size = locationList->size;
for (i = 0; i < size; i++) {
Location* location = getLocation(locationList, i);
if (location->computedHandled != handled) {
continue;
}
if (locationEquals(location, locationToFind)) {
return true;
}
}
return false;
}
void removeFirstLocation(LocationList* locationList) {
// TODO : Implementation is not Optimized ! Use linked list ?
int size = locationList->size;
if (size == 0) {
return;
}
int i;
for (i = 1; i < size; i++) {
Location* location1 = getLocation(locationList, i - 1);
Location* location2 = getLocation(locationList, i);
copyLocation(location2, location1);
}
size--;
locationList->size = size;
}
unsigned int getLocationCount(LocationList* locationList) {
return locationList->size;
}
unsigned int getLocationNotHandledCount(LocationList* locationList) {
unsigned int result = 0;
unsigned int i;
unsigned int size = locationList->size;
for (i = 0; i < size; i++) {
Location* location = getLocation(locationList, i);
if (location->usageType != LOCATION_USAGE_TYPE_PERMANENT) {
continue;
}
if (location->computedHandled) {
result++;
}
}
return result;
}
// CLEAR
// https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
void clearLocationTmpInfo(LocationList* locationList) {
unsigned int i;
unsigned int size = locationList->size;
for (i = 0; i < size; i++) {
Location* location = getLocation(locationList, i);
location->computedCost = MAX_COST;
location->computedNextLocation = NULL;
location->computedPreviousLocation = NULL;
location->computedHandled = false;
}
}
// TEMPORARY LOCATIONS
Location* addTemporaryLocation(LocationList* locationList, float x, float y) {
Location* result = findLocationToRecycleIfAny(locationList);
if (result == NULL) {
result = addNamedLocation(locationList, LOCATION_USAGE_TYPE_TEMPORARY, "TMP", "TMP", x, y);
} else {
result->x = x;
result->y = y;
result->usageType = LOCATION_USAGE_TYPE_TEMPORARY;
}
return result;
}
void locationListClearTemporaryLocations(LocationList* locationList) {
unsigned int i;
unsigned int size = locationList->size;
for (i = 0; i < size; i++) {
Location* location = getLocation(locationList, i);
if (location->usageType == LOCATION_USAGE_TYPE_TEMPORARY) {
location->usageType = LOCATION_USAGE_TYPE_TO_BE_REUSE;
}
}
}
Location* findLocationToRecycleIfAny(LocationList* locationList) {
unsigned int i;
unsigned int size = locationList->size;
for (i = 0; i < size; i++) {
Location* location = getLocation(locationList, i);
if (location->usageType == LOCATION_USAGE_TYPE_TO_BE_REUSE) {
return location;
}
}
return NULL;
}
|
C
|
/**
*char *ecvt(double number, int ndigtis, int *decpt, int *sign);
*ecvt()用来将参数number转换成ASCII码字符串。
*参数ndigits:表示显示的位数;
*若转换成功,参数decpt指针所指向的变量会返回数值中小数点的地址(从左至右算起);
*而参数sign指针所指的变量则代表数值的正负,若数值为正,返回0,否则返回1.
*
*返回值:返回一字符串指针,此字符串声明为static,若再次调用ecvt()或fcvt(),
*此字符串的内容会被覆盖!!!
*
*注1:请尽量使用sprintf()做转换,而不是使用ecvt()。
*注2:ecvt()和fcvt()均为宏定义,需要glibc库的支持。
*
**/
#include <stdio.h>
#include <stdlib.h>
void main(){
double a = 123.45;
double b = 1234.56;
char *ptr1, *ptr2;
int decpt, sign;
ptr1 = ecvt(a, 5, &decpt, &sign);
printf("decept = %d, sign = %d, a value = %s\n", decpt, sign, ptr1);
ptr2 = ecvt(b, 6, &decpt, &sign);
printf("decept = %d, sign = %d, b value = %s\n", decpt, sign, ptr2);
printf("!!!! a value = %s\n", ptr1);
}
/**
decept = 3, sign = 0, a value = 12345
decept = 4, sign = 0, b value = 123456
!!!! a value = 123456
**/
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
long long int d;
long long int sum;
} node;
int main()
{
int t, n, i, num, j, N;
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
node *arr, *out;
arr = (node *)malloc(sizeof(node) * n);
out = (node *)malloc(sizeof(node) * n);
for (i = 0 ; i < n ; i++)
{
scanf("%lld", &arr[i].d);
arr[i].sum = 0;
}
i = 0;
j = 0;
N = n;
while(n)
{
num = arr[j].d;
if (num < 0)
{
if (i-1 >= 0)
if (out[i-1].d > num)
break;
out[i] = arr[j];
i++;
j++;
}
else
{
if (i == 0)
break;
else if (i-1 >= 0 && out[i-1].d * -1 != num)
break;
else
{
if (i-2 >= 0)
out[i-2].sum += num;
if(i-1 >= 0)
if (out[i-1].sum >= -1 * out[i-1].d)
break;
else
{
out[i-1].sum = 0;
out[i-1].d = 0;
}
i--;
j++;
}
}
if (i == 0 && j != N)
break;
n--;
}
if (n == 0)
printf(":-) Matrioshka!\n");
else
printf(":-( Try again.\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct ll
{
int data;
struct ll *link;
}link_l;
link_l *head = NULL;
int cnt =0;
void insert(int n)
{
link_l *d =NULL;
link_l *c = NULL;
c = malloc(sizeof(link_l));
c->data = n;
c->link = NULL;
if(head == NULL)
{
head = c;
}
else
{
d = head;
while(d->link != NULL)
{
d = d-> link;
}
d-> link = c;
}
cnt++;
}
void search(int n)
{
link_l *c =head;
while(head != NULL && c->data != n)
{
c=c->link;
}
printf(" search=%d ",c->data);
}
void display()
{
link_l *c = head;
while(c!=NULL)
{
printf(" %d ",c->data);
c=c->link;
}
printf("\n");
}
main()
{
insert(2);
insert(9);
insert(4);
insert(5);
// st_delete();
display();
search(9);
printf(" cnt = %d ",cnt);
}
|
C
|
/*
* =====================================================================================
*
* Filename: Hogwarts_Mod8_task2.c
* Usage: ./Hogwarts_Mod8_task2.c
* Description: Generate a random Array
*
* Version: 1.0
* Created: 03/21/2017 02:34:57 PM
* Compiler: gcc -Wall -Werror
* Author: Tyler Madsen (), [email protected]
* =====================================================================================
*/
#include <stdio.h> /* For Standard I/O */
#include <stdlib.h>
#include <time.h>
#define NUMV 10
/* Function Prototypes */
void MaxMin(int numvals, int vals[], int* min, int* max);
/* Main Program */
int main(int argc, char *argv[])
{
int nums[NUMV] = {0,0,0,0,0,0,0,0,0,0};
int min = 0, max = 0;
//int check;
srand(time(NULL));
printf("The List is:\n");
for(int i = 0; i < NUMV; i++)
{
nums[i] = (rand() %100) + 1;
for(int j = 0; j < NUMV; j++)
{
if(nums[j] == nums[i])
{
nums[i] = (rand() %100) + 1;
}
}
printf("%d ", nums[i]);
}
printf("\n");
MaxMin(NUMV, nums, &min, &max);
printf("The minimum value is: %d\n", min);
printf("The maximum value is: %d\n", max);
return 0;
}
/* Function Definitions */
void MaxMin(int numvals, int vals[], int* min, int* max)
{
(*min) = vals[0];
(*max) = vals[0];
for(int i = 1; i < numvals; i++)
{
if(*min > vals[i])
{
*min = vals[i];
}
if(*max < vals[i])
{
*max = vals[i];
}
}
return;
}
|
C
|
#include <stdio.h>
void dump(FILE *);
// Cat prints each file in the argument list to the standard output.
int main(int argc, char **argv) {
FILE *f;
if (argc == 1) {
dump(stdin);
return 0;
}
while (*++argv) {
f = fopen(*argv, "r");
if (f == NULL) {
fprintf(stderr, "cat: %s: No such file or directory\n", *argv);
continue;
}
dump(f);
fclose(f);
}
}
// Dump prints the content of f to stdout.
void dump(FILE *f) {
int c;
while ((c = fgetc(f)) != EOF) {
putchar(c);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kchahid <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/08 22:50:49 by ebatchas #+# #+# */
/* Updated: 2019/12/11 20:56:56 by kchahid ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../incs/vm.h"
int print_exec_code_error(int err_code)
{
if (err_code == HM_ERROR)
ft_putendl("Error : exec code -> head magic error");
else if (err_code == NLB_ERROR)
ft_putendl("Error : exec code -> null byte error");
else if (err_code == PSIZE_ERROR)
ft_putendl("Error : exec code -> prog size error");
return (0);
}
void print_contestants(t_vm *vm)
{
t_player *p;
p = vm->player;
ft_printf("Introducing contestants...\n");
while (p)
{
printf("* Player %d, weighing %d bytes, \"%s\" (\"%s\") !\n",
p->number, p->exec->head.prog_size,
p->exec->head.prog_name, p->exec->head.comment);
p = p->next;
}
}
void print_winner(t_vm *vm)
{
if (vm->winner && !vm->visu)
ft_printf("Contestant %d, \"%s\", has won !\n", vm->winner->number,
vm->winner->exec->head.prog_name);
}
int print_corewar_usage(void)
{
ft_putstr("Usage: ./corewar [(-dump|-d) ");
ft_putendl("<num> -l <num>] [-v] [-n <num>] <champion.cor> <...>");
ft_putstr(" -dump <num> : Dump memory ");
ft_putendl("(32 octets per line) after <num> cycles and exit");
ft_putstr(" -d <num> : Dump memory ");
ft_putendl("(64 octets per line) after <num> cycles and exit");
ft_putendl(" -l <num> : Log levels");
ft_putendl(" 1 : Show cycles");
ft_putendl(" 2 : Show deaths");
ft_putendl(" -v : Run visualizer");
ft_putendl(" -n <num> : Set <num> of the next player");
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct BST_NODE {
struct BST_NODE *l;
struct BST_NODE *r;
int pos;
int v;
}BST_NODE, *PBST_NODE;
PBST_NODE BST_create(int v)
{
PBST_NODE n = (PBST_NODE) malloc (sizeof(BST_NODE));
if (n)
n->v = v;
return n;
}
void BST_insert (PBST_NODE root, int v)
{
if (root) {
if ( v <= root->v) {
if (root->l) {
BST_insert(root->l, v);
} else {
root->l = BST_create(v);
}
} else {
if (root->r) {
BST_insert(root->r, v);
} else {
root->r = BST_create(v);
}
}
}
}
void mark_nodes (PBST_NODE root, int *num)
{
if (root) {
if (root->l)
mark_nodes(root->l, num);
root->pos = (*num)++;
if(root->r)
mark_nodes(root->r, num);
}
}
void display_nth_largest(PBST_NODE root, int pos)
{
if (root) {
display_nth_largest(root->l, pos);
if (pos == root->pos)
printf("%dth Largest node has: %d ",pos, root->v);
display_nth_largest(root->r, pos);
}
}
void BST_display (PBST_NODE root)
{
if (root) {
BST_display(root->l);
printf("%d ", root->v);
BST_display(root->r);
}
}
int main()
{
int num = 0;
PBST_NODE root = BST_create(10);
BST_insert(root, 8);
BST_insert(root, 15);
BST_insert(root, 7);
BST_insert(root, 9);
BST_insert(root, 13);
BST_insert(root, 17);
BST_display(root);
mark_nodes(root, &num);
printf("num nodes: %d\n", num);
display_nth_largest(root, num-5);
printf("\n");
display_nth_largest(root, num-2);
printf("\n");
display_nth_largest(root, num-6);
printf("\n");
display_nth_largest(root, num-9);
printf("\n");
}
|
C
|
#include <stdio.h>
#include <string.h>
int get(unsigned short num, int n){
if((num & (1 << n)) != 0)
return 1;
else
return 0;
}
unsigned short set(unsigned short num, unsigned short n, unsigned short bit){
if(bit == 0){
return num & (~(1 << n));
}
else{
return num | (1 << n);
}
}
unsigned short comp(unsigned short num, unsigned short n){
return num ^ (1 << n);
}
int main(int argc, char* argv[])
{
FILE *fp = fopen(argv[1], "r");
unsigned short x;
fscanf(fp, "%hu\n", &x);
char c[5];
while(fscanf(fp, "%s\t", &c[0]) != EOF){
unsigned short n;
unsigned short bit;
if(strcmp("set", c) == 0){
fscanf(fp, "%hu\t", &n);
fscanf(fp, "%hu\n", &bit);
x = set(x,n,bit);
printf("%hu\n",x);
}
else if(strcmp("get", c) == 0){
fscanf(fp, "%hu\t", &n);
fscanf(fp, "%hu\n", &bit); // added to go to the new line
if(get(x,n) != 0)
printf("1\n");
else
printf("0\n");
}
else{
fscanf(fp, "%hu\t", &n);
fscanf(fp, "%hu\n", &bit); // added to go to the new line
x = comp(x,n);
printf("%hu\n", x);
}
}
fclose(fp);
return 0;
}
|
C
|
/*--------------------------------------
Herman Vanstapel
ex02\ser.c
Un serveur recevant une structure et lié à un client particulier
----------------------------------------*/
#include <stdio.h>
#include <string.h>
#include "../physlib/physlib.h"
#include "structure.h"
int main(int argc, char *argv[])
{
int rc;
int Desc;
struct sockaddr_in psoo; /* o = origine */
struct sockaddr_in psos; /* s = serveur */
struct sockaddr_in psor; /* r = remote */
int tm;
struct Requete UneRequete;
memset(&psoo, 0, sizeof(struct sockaddr_in));
memset(&psos, 0, sizeof(struct sockaddr_in));
memset(&psor, 0, sizeof(struct sockaddr_in));
printf("Ceci est le serveur\n");
if (argc!=5)
{
printf("ser ser port cli port\n");
exit(1);
}
Desc = CreateSockets(&psoo, &psos, argv[1], atoi(argv[2]), argv[3], atoi(argv[4]));
if (Desc == -1)
perror("CreateSockets");
else
printf(" CreateSockets : %d \n", Desc);
tm = sizeof(struct Requete);
rc = ReceiveDatagram(Desc, &UneRequete, tm, &psor);
if (rc == -1)
perror("ReceiveDatagram");
else
fprintf(stderr, "bytes:%d:%s\n", rc, UneRequete.Message);
/* reponse avec psos */
UneRequete.Type = Reponse;
strcat(UneRequete.Message, " Client");
rc = SendDatagram(Desc, &UneRequete, sizeof(struct Requete), &psos);
if (rc == -1)
perror("SendDatagram:");
else
fprintf(stderr, "bytes:%d\n", rc);
/* reponse avex psor r = remote */
strcat(UneRequete.Message, "X2");
rc = SendDatagram(Desc, &UneRequete, sizeof(struct Requete), &psor);
if (rc == -1)
perror("SendDatagram:");
else
fprintf(stderr, "bytes:%d\n", rc);
}
|
C
|
//Nick Sells, 2021
//level.c
#include <stdlib.h>
#include "level.h"
//=============================================================================
// GLOBALS
//=============================================================================
//NOTE: used to store rooms and hallways when generating a level. gets malloc'd
//when needed and free'd when done. necessary because rooms and hallways need
//to know about one another to be placed in ways that don't suck.
static Room* rooms;
static Hall* halls;
//used to track which index to put a room or hall in
static size_t numRooms = 0;
static size_t numHalls = 0;
//=============================================================================
// CONSTRUCTORS/DESTRUCTORS
//=============================================================================
//allocates all the memory needed for a Level
Level* lvl_create(void) {
Level* this = calloc(1, sizeof(*this));
this->tiles = calloc(LVL_HEIGHT * LVL_WIDTH, sizeof(*this->tiles));
this->terrain = calloc(LVL_HEIGHT * LVL_WIDTH, sizeof(*this->terrain));
return this;
}
//deallocates the level
void lvl_destroy(Level* this) {
for(u32 i = MAX_ACTORS; i > 0; i--)
actor_destroy(this->actors[i]);
free(this);
}
void lvl_setPlayer(Level* this, Player* plr) {
this->player = plr;
//TODO: set the player to the center of the level
}
//claims the next available actor slot, sets it up, and returns a pointer to it
Actor* lvl_createActor(Level* this, ActorType type, u32 x, u32 y) {
for(size_t i = 0; i < MAX_ACTORS; i++) {
if(this->actors[i] == NULL) {
//claim the slot and set up the actor
this->actors[i] = actor_create(type);
this->actors[i]->lvl = this;
actor_setPos(this->actors[i], this, x, y);
return this->actors[i];
}
}
//if no slot was available
DEBUG_BLOCK(
mgba_printf(LOG_ERR, "failed to create actor: no actor slots available");
);
return NULL;
}
//relinquishes an actor slot
void lvl_destroyActor(Level* this, Actor* actor) {
actor_destroy(actor);
actor = NULL;
}
//=============================================================================
//FUNCTION DEFINITIIONS
//=============================================================================
//scrolls a level around. also moves sprites and stops at edges
void lvl_scroll(Level* this) {
s32 dx = 16 * key_tri_horz();
s32 dy = 16 * key_tri_vert();
//if we can move without going out of bounds
if(in_range(this->offset.x + dx, 0, LVL_WIDTH * 16 - SCREEN_WIDTH + 1)
&& in_range(this->offset.y + dy, 0, LVL_HEIGHT * 16 - SCREEN_HEIGHT + 1)) {
this->offset.x += dx;
this->offset.y += dy;
REG_BG_OFS[BG_LVL] = this->offset;
//move the actors along with it
for(size_t i = 0; i < MAX_ACTORS; i++)
if(this->actors[i] != NULL)
spr_move(this->actors[i]->sprite, -dx, -dy);
}
}
//plots a level to the level sbb defined in config.h
void lvl_draw(const Level* this) {
for(size_t y = 0; y < LVL_HEIGHT; y++) {
for(size_t x = 0; x < LVL_WIDTH; x++) {
bg_plot_m(SBB_LVL, x, y, lvl_getTile(this, x, y));
}}
}
//erases a level so that the next level can be drawn
void lvl_erase(void) {
for(size_t i = 0; i < 4; i++)
SBB_CLEAR(SBB_LVL + i);
}
//=============================================================================
// LEVEL-BUILDING FUNCTIONS
//=============================================================================
//FIXME: hallways need to be prevented from intersecting a room at it's edge.
//this causes complications with the placement logic for actors, items, and
//doors and can create an ugly "missing corner" look where the hall ends, OR
//adjust each hallway's start and endpoint to where they intersect a room. i
//think either solution will work
//FIXME: prevent rooms connected by a door from touching each other; sharing a
//wall is okay, and so is being completely separate, but two connected room's
//walls can't be allowed to touch. it makes for ugly door placement
//TODO: special room types
//TODO: entry and exit rooms must be as far from each other as possible
//***TODO:*** limit what tiles hall floors can overwrite so that they don't cut so deeply between rooms
//this will allow me to rely on tile types to know where hallways apprarent stop and start
static void lvl_design(Level* this, RECT* rect, size_t numIterations);
static void lvl_deferRoom(const RECT* rect);
static void lvl_deferHall(const Hall* hall);
static void lvl_tweakRooms(void);
static void lvl_buildRooms(Level* this);
static void lvl_buildHalls(Level* this);
static void lvl_placeDoors(Level* this);
static void lvl_placeItems(Level* this);
static void lvl_placeActors(Level* this);
static void lvl_splitRect(const RECT* original, RECT* p1, RECT* p2, size_t numAttempts);
//places rooms, hallways, items, and enemies
void lvl_build(Level* this) {
DEBUG_BLOCK(
profile_start();
//NOTE: this just lets me cycle through level layouts quicker
for(size_t y = 0; y < LVL_HEIGHT; y++) {
for(size_t x = 0; x < LVL_WIDTH; x++) {
lvl_setTile(this, x, y, TILE_NONE);
}}
for(size_t i = 0; i < MAX_ACTORS; i++) {
if(this->actors[i] != NULL)
lvl_destroyActor(this, this->actors[i]);
}
);
//allocate the temp arrays to store things until they can be built
rooms = calloc(1 << NUM_RECUR, sizeof(*rooms));
halls = calloc((1 << NUM_RECUR) - 1, sizeof(*halls));
//design the level, using an initial BSP partition
RECT temp = {0, 0, LVL_WIDTH, LVL_HEIGHT};
lvl_design(this, &temp, NUM_RECUR);
//build the level
lvl_tweakRooms();
lvl_buildRooms(this);
lvl_buildHalls(this);
lvl_placeDoors(this);
lvl_placeItems(this);
lvl_placeActors(this);
//deallocate the temp arrays now that everything is built
free(rooms);
free(halls);
//reset the indices for those
numRooms = 0;
numHalls = 0;
DEBUG_BLOCK(
size_t numCycles = profile_stop();
mgba_printf(LOG_INFO, "level generated in %u cycles", numCycles);
);
}
//recursively divides an initial surface using BSP and queues up rooms and hallways to be carved later
static inline void lvl_design(Level* this, RECT* rect, size_t numIterations) {
//recursive case: if we are not on the last iteration
if(numIterations > 0) {
//split rect into r1 and r2
RECT r1, r2;
lvl_splitRect(rect, &r1, &r2,SPLIT_ATTEMPTS);
//recurse with the two pieces
lvl_design(this, &r1, numIterations - 1);
lvl_design(this, &r2, numIterations - 1);
//calculate the hallway which will connect the two halves
Hall hall = {
.start = {(r1.left + r1.right) / 2, (r1.top + r1.bottom) / 2},
.end = {(r2.left + r2.right) / 2, (r2.top + r2.bottom) / 2}
};
//queue up the hallway to be built later
lvl_deferHall(&hall);
}
//base case: if we are on the last iteration (AKA: a leaf of the tree)
else
//queue up the rect to be built as a room later
lvl_deferRoom(rect);
}
//takes a rectangle and copies it as the bounds of a room in the next slot of the room array
static inline void lvl_deferRoom(const RECT* rect) {
rooms[numRooms++] = (Room) {.bounds = *rect};
}
//takes a hallway and copies it to the next slot of the hall array
static inline void lvl_deferHall(const Hall* hall) {
halls[numHalls++] = *hall;
}
//iterates over the room array and adjusts each room to be a bit more visually appealing
static inline void lvl_tweakRooms(void) {
//for every room in the temp array
for(size_t i = 0; i < numRooms; i++) {
u32 vertShrink = qran_range(0, rc_height(&rooms[i].bounds) / 2);
u32 horzShrink = qran_range(0, rc_width(&rooms[i].bounds) / 2);
//if shrinking would make the room too small, don't bother
if(rc_height(&rooms[i].bounds) - vertShrink < MIN_ROOM_HEIGHT) vertShrink = 0;
if(rc_width(&rooms[i].bounds) - horzShrink < MIN_ROOM_WIDTH) horzShrink = 0;
//recede the left or right edge
if(qran_range(0, 2))
rooms[i].bounds.left += horzShrink;
else
rooms[i].bounds.right -= horzShrink;
//recede the top or bottom edge
if(qran_range(0, 2))
rooms[i].bounds.top += vertShrink;
else
rooms[i].bounds.bottom -= vertShrink;
}
}
//iterates over the room array and plots each room's tiles to the level
static inline void lvl_buildRooms(Level* this) {
//for every room in the temp array
for(size_t i = 0; i < numRooms; i++) {
//place floor tiles
for(size_t y = rooms[i].bounds.top + 1; y < rooms[i].bounds.bottom - 1; y++) {
for(size_t x = rooms[i].bounds.left + 1; x < rooms[i].bounds.right - 1; x++) {
lvl_setTile(this, x, y, TILE_FLOOR_ROOM);
}}
//place north and south wall tiles
for(size_t x = rooms[i].bounds.left; x < rooms[i].bounds.right; x++) {
lvl_setTile(this, x, rooms[i].bounds.top, TILE_WALL);
lvl_setTile(this, x, rooms[i].bounds.bottom - 1, TILE_WALL);
}
//place west and east wall tiles
for(size_t y = rooms[i].bounds.top + 1; y < rooms[i].bounds.bottom - 1; y++) {
lvl_setTile(this, rooms[i].bounds.left, y, TILE_WALL);
lvl_setTile(this, rooms[i].bounds.right - 1, y, TILE_WALL);
}
}
}
//iterates over the hall array and plots each one's tiles to the level
static inline void lvl_buildHalls(Level* this) {
//for every hall in the temp array
for(size_t i = 0; i < numHalls; i++) {
//vertical hallway
if(halls[i].start.x == halls[i].end.x) {
for(size_t y = halls[i].start.y; y < halls[i].end.y; y++) {
//left wall
if(lvl_getTile(this, halls[i].start.x - 1, y) == TILE_NONE)
lvl_setTile(this, halls[i].start.x - 1, y, TILE_WALL);
//floor (middle)
if(lvl_getTile(this, halls[i].start.x, y) != TILE_FLOOR_ROOM)
lvl_setTile(this, halls[i].start.x, y, TILE_FLOOR_HALL);
//right wall
if(lvl_getTile(this, halls[i].start.x + 1, y) == TILE_NONE)
lvl_setTile(this, halls[i].start.x + 1, y, TILE_WALL);
}
}
//horizontal hallway
else if(halls[i].start.y == halls[i].end.y){
for(size_t x = halls[i].start.x; x < halls[i].end.x; x++) {
//top wall
if(lvl_getTile(this, x, halls[i].start.y - 1) == TILE_NONE)
lvl_setTile(this, x, halls[i].start.y - 1, TILE_WALL);
//floor (middle)
if(lvl_getTile(this, x, halls[i].start.y) != TILE_FLOOR_ROOM)
lvl_setTile(this, x, halls[i].start.y, TILE_FLOOR_HALL);
//bottom wall
if(lvl_getTile(this, x, halls[i].start.y + 1) == TILE_NONE)
lvl_setTile(this, x, halls[i].start.y + 1, TILE_WALL);
}
}
DEBUG_BLOCK(
else
mgba_printf(LOG_ERR, "diagonal hallways are not supported");
);
}
}
//iterates over the hall array and
static inline void lvl_placeDoors(Level* this) {
//for every hall in the temp array
for(size_t i = 0; i < numHalls; i++) {
//vertical hallway
if(halls[i].start.x == halls[i].end.x) {
//for every tile in the hallway, from top to bottom
for(size_t y = halls[i].start.y; y < halls[i].end.y; y++) {
//if there is a wall to the left and right
if((lvl_getTile(this, halls[i].start.x - 1, y) == TILE_WALL)
&& (lvl_getTile(this, halls[i].start.x + 1, y) == TILE_WALL)) {
//place a door and abort the loop
lvl_setTile(this, halls[i].start.x, y, TILE_DOOR_CLOSED);
break;
}
}
}
//horizontal hallway
else if(halls[i].start.y == halls[i].end.y){
//for every tile in the hallway, from left to right
for(size_t x = halls[i].start.x; x < halls[i].end.x; x++) {
//if there is a wall above and below
if((lvl_getTile(this, x, halls[i].start.y - 1) == TILE_WALL)
&& (lvl_getTile(this, x, halls[i].start.y + 1) == TILE_WALL)) {
//place a door and abort the loop
lvl_setTile(this, x, halls[i].start.y, TILE_DOOR_CLOSED);
break;
}
}
}
DEBUG_BLOCK(
else
mgba_printf(LOG_ERR, "diagonal hallways are not supported");
);
}
}
//iterates over the room array and places items in accordance with the loot tables
static void lvl_placeItems(Level* this) {
//TODO:
}
//iterates over the room array and places enemies where the conditions are right
//NOTE: this will need significant reworking after the jam
static void lvl_placeActors(Level* this) {
#define SPAWN_CHANCE 153 //60%
u32 numActors = 0;
for(size_t i = 0; i < numRooms; i++) {
if(numActors < MAX_ACTORS) {
u32 spawnX, spawnY;
do {
spawnX = qran_range(rooms[i].bounds.left, rooms[i].bounds.right + 1);
spawnY = qran_range(rooms[i].bounds.top, rooms[i].bounds.bottom + 1);
}
while(lvl_getTile(this, spawnX, spawnY) != TILE_FLOOR_ROOM);
lvl_createActor(this, ACTOR_SKELETON, spawnX, spawnY);
}
}
//TODO:
}
//splits original rect in half and stores the halves in p1 and p2. attempts to
//satisfy the ratio specified by DISCARD_RATIO, but gives up after numAttempts
static inline void lvl_splitRect(const RECT* original, RECT* p1, RECT* p2, size_t numAttempts) {
//as long as there are attempts remaining
for(size_t i = numAttempts; i > 0; i--) {
//the halvles must start the same size as the original
*p1 = *original;
*p2 = *original;
//choose vertical or horizontal axis
BOOL axis = qran_range(0, 2);
if(axis) { //vertical
u32 cutPosition = qran_range(0, rc_width(p1));
p1->right -= cutPosition;
p2->left = p1->right - 1;
}
else { //horizontal
u32 cutPosition = qran_range(0, rc_height(p1));
p1->bottom -= cutPosition;
p2->top = p1->bottom - 1;
}
//calculate the w/h or h/w ratios of each piece
FIXED p1Ratio, p2Ratio;
if(axis) { //vertical
p1Ratio = fxdiv(int2fx(rc_width(p1)), int2fx(rc_height(p1)));
p2Ratio = fxdiv(int2fx(rc_width(p2)), int2fx(rc_height(p2)));
}
else { //horizontal
p1Ratio = fxdiv(int2fx(rc_height(p1)), int2fx(rc_width(p1)));
p2Ratio = fxdiv(int2fx(rc_height(p2)), int2fx(rc_width(p2)));
}
//if neither ratio is too small, return
if((p1Ratio > DISCARD_RATIO) && (p2Ratio > DISCARD_RATIO))
return;
}
DEBUG_BLOCK(
mgba_printf(LOG_WARN, "failed to satisfy split ratio: too many attempts made");
);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
//int main()
//{
// char arr[] = { 'b','i','t','\0' };
// printf("%d\n", strlen(arr));
//
// return 0;
//};
//void bubble_sort(int arr[10],int i,int sz)
//{
// int n = 0;
// int tmp = 0;
// for (n = 0; n < sz - i; n++)
// {
// if (arr[n] > arr[n + 1])
// {
// tmp = arr[n];
// arr[n] = arr[n + 1];
// arr[n + 1] = tmp;
// }
// }
//}
//int main()
//{
// int arr[] = {10,9,8,47,6,11,878,8888,2,1 };
// int i = 0;
// int sz = sizeof(arr) / sizeof(arr[0]);
// for (i = 1; i < sz; i++)
// {
// bubble_sort(arr, i, sz);
// /* int n = 0;
// int tmp = 0;
// for (n = 0; n < sz - i; n++)
// {
// if (arr[n] > arr[n + 1])
// {
// tmp = arr[n];
// arr[n] = arr[n + 1];
// arr[n + 1] = tmp;
// }
// }*/
// }
// for (i = 0; i < sz; i++)
// {
// printf("%d ", arr[i]);
// }
// return 0;
//}
void Init(int arr[10],int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
arr[i] = 0;
}
}
void Print(int arr[], int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void Reverse(int arr[], int sz)
{
int tmp = 0;
int left = 0;
int right = sz - 1;
while (left < right)
{
tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
}
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
//Init(arr,sz);
Print(arr,sz);
Reverse(arr,sz);
Print(arr, sz);
return 0;
}
|
C
|
/*
Name: Bryan Fernandez
A C program that initializes clock speed at 4 MHz.
&= Bitwise AND asignment operator. C &= 2 is same C = C & 2
^= Bitwise exclusive OR operator C ^= 2 is same C = C ^ 2
|= Bitwise inclusive OR operator C |= 2 is same C = C | 2
& is AND 1 0001
| is OR 2 0010
^ is XOR 3 0011
~ is inverse 4 0100
<< is shift LEFT 5 0101
>> is shift RIGHT 6 0110
7 0111
Initially, LED1 is blinking @ 2 Hz (0.25 secs on, 0.25 secs off)) LED2 is off.
While SW1 == 0, double blinking frequency of LED1. LED2 should be on.
While SW2 == 0, LED2 should blink at half the frequency. LED1 should be on.
While SW1 & SW2 == 0, both LEDs should blink alternately @ double the blinking freq.
When released, the clock speed is reset to 4 MHz, both LEDs on. Use interrupt for switches */
#include <msp430xG46x.h>
#define SW1 BIT0&P1IN
#define SW2 BIT1&P1IN
int b=0; //Global, setting my own flag
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; //stop watchdog
FLL_CTL0 |= XCAP18PF; //set capacitance to 8pF
SCFI0 |= FN_4; //set DCO range to 2.8 - 26.6 MHz
SCFQCTL = 121; // ( [0111_1001) +1] x 32768 = 4 MHz
//P1DIR |= 0x32; //P1.1,P1.4,P1.5 to outputs
//P1SEL |= 0x32; //output to MCLK, SMCLK, & ACLK
P2DIR |= 0x06; // P2.1,P2.2 to output ports
P2OUT = 0x04; //(0000_0100) turn on
_EINT(); //Enable interrupts
P1IE |= BIT0; //P1.0 interrupt enabled
P1IES |= BIT0; //P1.0 hi/low edge
P1IFG &= ~BIT0; //P1.0 IFG cleared
P1IE |= BIT1; //P1.0 interrupt enabled
P1IES |= BIT1; //P1.0 hi/low edge
P1IFG &= ~BIT1; //P1.0 IFG cleared
for(;;) //Infinite loop for blinking
{
P2OUT ^= 0x04; //LED1 is blinking
unsigned int i;
i = 50000; // Delay
do
{
i--;
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
} while (i != 0);
//------ If switch(es) are/is presssed -----------------------------------------
if(b == 1) //Only = 1 when it comes out of an interrupt
{ //Enter another infinite loop
for(;;)
{
FLL_CTL0 |= XCAP18PF; //set capacitance to 8pF
SCFI0 |= FN_4; //Reset the range
SCFQCTL = 121; //Reset the clocks to 4 MHz
P2OUT = 0x06; //Turn on both LEDs
}
}
}
}
//Port 1 interrupt service routine
#pragma vector = PORT1_VECTOR
__interrupt void Port1_ISR (void)
{
P1IFG &= ~BIT0; //P1.0 IFG cleared
P1IFG &= ~BIT1; //P1.1 IFG cleared
P2OUT = 0x06; //Turn on both LEDs
//==============================================================================
while((SW1) == 0)
{ //Want to double frequency to 8 MHz
FLL_CTL0 |= DCOPLUS + XCAP18PF; //Enable modulation and 8pF
SCFI0 |= FN_4; //set DCO range to 2.8 - 26.6 MHz
SCFQCTL = 121; // (121+1] x 32768 x 2 = 8 MHz
P2OUT ^= 0x04; //Blink only LED1 (0000_0100) (0000_ 0 LED1 LED2 0)
unsigned int i = 50000; // Delay ^^^^^^ xor 00
do
{
(i--);
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
} while (i != 0);
b = 1; //Turn on my flag
if((SW2) == 0)
{
goto SWBoth;
}
}
//=============================================================================
while((SW2) == 0)
{ //Want half the frequency to 2 MHz
FLL_CTL0 |= XCAP18PF;
SCFI0 |= FN_2;
SCFQCTL = 60; //(60 + 1) x 32768 = 2 MHz
P2OUT ^= 0x02; //(0000_0010) LED2 blink only. LED1 on
unsigned int i = 50000; // Delay
do
{
(i--);
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
} while (i != 0);
b = 1; //Turn on my flag
if((SW1) == 0)
{
goto SWBoth;
}
}
SWBoth:
while((SW1)== 0 && (SW2)== 0)
{
FLL_CTL0 |= DCOPLUS + XCAP18PF; //Enable modulation and 8pF
SCFI0 |= FN_4; //set DCO range to 2.8 - 26.6 MHz
SCFQCTL = 121; // (121+1] x 32768 x 2 = 8 MHz
P2OUT ^= 0x06; //Blink both LEDs
unsigned int i = 50000; // Delay
do
{
(i--);
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
} while (i != 0);
}
P2OUT &= ~0x06; //Turn off LEDs
}
|
C
|
#include "gla.h"
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
gla_determinant * gla_determinant_alloc(const size_t n)
{
gla_determinant * d ;
if(0 == n) PrintErr("Determinant dimension should be a positive integer" , GLA_EINVAL) ;
d = (gla_determinant *) malloc(sizeof(gla_determinant)) ;
if(0 == d) PrintErr("Determinant alloc failure" , GLA_ENOMEM) ;
d->dat = (type *) malloc(n * n * sizeof(type)) ;
if(0 == d->dat) PrintErr("Determinant dat alloc failure" , GLA_ENOMEM) ;
d->n = n ;
return d ;
}
gla_determinant * gla_determinant_cpy(gla_determinant * c , const gla_determinant * d)
{
if(0 == d || 0 == c) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
if(c->n != d->n) PrintErr("Dest gla_determinant 's size doesn't match src gla_determinant 's size" , GLA_EINVAL) ;
memcpy(c->dat , d->dat , d->n * d->n * sizeof(type)) ;
return c ;
}
void gla_determinant_set(gla_determinant * d , const size_t i , const size_t j , const type elem)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
if(d->n <= i || d->n <= j) PrintErr("Determinant doesn't have this elem" , GLA_EINVAL) ;
d->dat[i * d->n + j] = elem ;
}
type gla_determinant_get(const gla_determinant * d , const size_t i , const size_t j)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
if(d->n <= i || d->n <= j) PrintErr("Determinant doesn't have this elem" , GLA_EINVAL) ;
return d->dat[i * d->n + j] ;
}
void gla_determinant_free(gla_determinant * d)
{
if(d)
{
if(d->dat) free(d->dat) ;
free(d) ;
}
}
void gla_determinant_multiplication(gla_determinant * d , const type k , const size_t i)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
if(i >= d->n) PrintErr("Row num should be smaller than gla_determinant dimension" , GLA_EINVAL) ;
size_t j ;
for(j = 0 ; j < d->n ; ++j)
d->dat[i*d->n+j] *= k ;
}
void gla_determinant_addition(gla_determinant * d , const size_t des , const size_t src)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
if(des >= d->n || src >= d->n)
PrintErr("Row num should be smaller than gla_determinant dimension" , GLA_EINVAL) ;
size_t j ;
type temp ;
for(j = 0 ; j < d->n ; ++j)
{
temp = gla_determinant_get(d , des , j) + gla_determinant_get(d , src , j) ;
gla_determinant_set(d , des , j , temp) ;
}
}
void gla_determinant_swap(gla_determinant * d , const size_t i , const size_t i2)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
if(i >= d->n || i2 >= d->n)
PrintErr("Row num should be smaller than gla_determinant dimension" , GLA_EINVAL) ;
size_t j ;
type temp ;
for(j = 0 ; j < d->n ; ++j)
{
temp = gla_determinant_get(d , i , j) ;
gla_determinant_set(d , i , j , gla_determinant_get(d , i2 , j)) ;
gla_determinant_set(d , i2 , j , temp) ;
}
}
type gla_determinant_alge_complement(const gla_determinant * d , const size_t i , const size_t j)
{
type result ;
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
if(d->n <= i || d->n <= j) PrintErr("Determinant doesn't have this elem" , GLA_EINVAL) ;
if(1 == d->n) PrintErr("Determinant doesn't has alge complement" , GLA_EINVAL) ;
gla_determinant * c = gla_determinant_alloc(d->n - 1) ;
size_t x , y ;
for(x = 0 , y = 0 ; x < d->n * d->n ; ++x)
{
if(i != x / d->n && j != x % d->n)
{
gla_determinant_set(c , y / c->n , y % c->n , gla_determinant_get(d , x / d->n , x % d->n)) ;
++y ;
}
}
assert(y == c->n * c->n) ;
result = gla_determinant_value(c) ;
if((i + j) % 2)
result *= -1 ;
gla_determinant_free(c) ;
return result ;
}
type gla_determinant_value(const gla_determinant * d)
{
type result = 1 ;
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
gla_determinant * c = gla_determinant_alloc(d->n) ;
c = gla_determinant_cpy(c , d) ;
size_t i , j , k ;
for(i = 0 ; i < c->n ; ++i)
{
type temp1 , temp2 , mul ;
temp1 = gla_determinant_get(c , i , i) ;
for(j = c->n - 1 ; j != i ; --j)
{
temp2 = gla_determinant_get(c , j , i) ;
mul = -1 * temp2 / temp1 ;
for(k = i ; k < c->n ; ++k)
{
gla_determinant_set(c , j , k , mul * gla_determinant_get(c , i , k) + gla_determinant_get(c , j , k)) ;
}
}
for(j = i + 1 ; j < c->n ; ++j)
assert(0 == gla_determinant_get(c , j , i)) ;
result *= gla_determinant_get(c , i , i) ;
}
gla_determinant_free(c) ;
return result ;
}
int gla_determinant_is_diagonal(const gla_determinant * d)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
return gla_determinant_is_upper_triangular(d) && gla_determinant_is_lower_triangular(d) ;
}
int gla_determinant_is_upper_triangular(const gla_determinant * d)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
size_t i , j ;
for(i = 0 ; i < d->n ; ++i)
{
for(j = i + 1 ; j < d->n ; ++j)
{
if(0 != gla_determinant_get(d , i , j)) return 0 ;
}
}
return 1 ;
}
int gla_determinant_is_lower_triangular(const gla_determinant * d)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
size_t i , j ;
for(i = 0 ; i < d->n ; ++i)
{
for(j = 0 ; j < i ; ++j)
{
if(0 != gla_determinant_get(d , i , j)) return 0 ;
}
}
return 1 ;
}
void gla_determinant_transpose(const gla_determinant * d)
{
if(0 == d) PrintErr("Determinant can't be null" , GLA_EINVAL) ;
size_t i , j ;
type temp ;
for(i = 0 ; i < d->n ; ++i)
{
for(j = 0 ; j < i ; ++j)
{
temp = gla_determinant_get(d , i , j) ;
gla_determinant_set(d , i , j , gla_determinant_get(d , j , i)) ;
gla_determinant_set(d , j , i , temp) ;
}
}
}
//******************************************************
gla_vector * gla_vector_alloc(const size_t n)
{
gla_vector * result ;
if(0 == n) PrintErr("Num should be a positive integer" , GLA_EINVAL) ;
result = (gla_vector *) malloc(sizeof(gla_vector)) ;
if(0 == result) PrintErr("Malloc failure" , GLA_EINVAL) ;
result->dat = (type *) malloc(n * sizeof(type)) ;
if(0 == result->dat) PrintErr("Malloc failure" , GLA_EINVAL) ;
result->n = n ;
return result ;
}
void gla_vector_set(gla_vector * v , const size_t j , type value)
{
if(0 == v) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
if(v->n <= j) PrintErr("Subscript should be smaller than Vector dimension" , GLA_EINVAL) ;
v->dat[j] = value ;
}
type gla_vector_get(const gla_vector * v , const size_t j)
{
if(0 == v) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
if(v->n <= j) PrintErr("Subscript should be smaller than Vector dimension" , GLA_EINVAL) ;
return v->dat[j] ;
}
void gla_vector_free(gla_vector * v)
{
if(v)
{
if(v->dat) free(v->dat) ;
free(v) ;
}
}
gla_vector * gla_vector_cpy(gla_vector * des , const gla_vector * src)
{
if(0 == des || 0 == src) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
if(des->n != src->n) PrintErr("Des dimension's size isn't equal to src dimension's size" , GLA_EINVAL) ;
memcpy(des->dat , src->dat , des->n * sizeof(type)) ;
return des ;
}
void gla_vector_multiplication(gla_vector * v , const type k)
{
if(0 == v) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
size_t j ;
for(j = 0 ; j < v->n ; ++j)
v->dat[j] *= k ;
}
void gla_vector_addition(gla_vector * des , const gla_vector * src)
{
if(0 == des || 0 == src) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
if(des->n != src->n) PrintErr("Des dimension's size isn't equal to src dimension's size" , GLA_EINVAL) ;
size_t j ;
for(j = 0 ; j < des->n ; ++j)
des->dat[j] += src->dat[j] ;
}
void gla_vector_swap(gla_vector * v1 , gla_vector * v2)
{
if(0 == v1 || 0 == v2) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
if(v1->n != v2->n) PrintErr("V1 dimension's size isn't equal to V2 dimension's size" , GLA_EINVAL) ;
size_t j ;
type temp ;
for(j = 0 ; j < v1->n ; ++j)
{
temp = v1->dat[j] ;
v1->dat[j] = v2->dat[j] ;
v2->dat[j] = temp ;
}
}
type gla_vector_dot_multiplication(const gla_vector * v1 , const gla_vector * v2)
{
type result = 0 ;
if(0 == v1 || 0 == v2) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
if(v1->n != v2->n) PrintErr("V1 dimension's size isn't equal to V2 dimension's size" , GLA_EINVAL) ;
size_t j ;
for(j = 0 ; j < v1->n ; ++j)
result += v1->dat[j] * v2->dat[j] ;
return result ;
}
gla_vector * gla_vector_cross_multiplication(const gla_vector * v1 , const gla_vector * v2 , gla_vector * des)
{
if(0 == v1 || 0 == v2 || 0 == des) PrintErr("Vector can't be a null" , GLA_EINVAL) ;
if(3 != v1->n || 3 != v2->n || 3 != des->n) PrintErr("Size isn't 3" , GLA_EINVAL) ;
des->dat[0] = v1->dat[1] * v2->dat[2] - v1->dat[2] * v2->dat[1] ;
des->dat[1] = -1 * (v1->dat[0] * v2->dat[2] - v1->dat[2] * v2->dat[0]) ;
des->dat[2] = v1->dat[0] * v2->dat[1] - v1->dat[1] * v2->dat[0] ;
return des ;
}
gla_matrix * gla_matrix_alloc(const size_t n , const size_t m)
{
gla_matrix * result ;
if(0 == n || 0 == m) PrintErr("Matrix dimension should be a positive integer" , GLA_EINVAL) ;
result = (gla_matrix *) malloc(sizeof(gla_matrix)) ;
if(0 == result) PrintErr("Malloc Failure" , GLA_ENOMEM) ;
result->dat = (type *) malloc(n * m * sizeof(type)) ;
if(0 == result->dat) PrintErr("Malloc Failure" , GLA_ENOMEM) ;
result->n = n ;
result->m = m ;
return result ;
}
void gla_matrix_set(gla_matrix * m , const size_t i , const size_t j , const type ele)
{
if(0 == m) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(i >= m->n || j >= m->m) PrintErr("Matrix doesn't have this elem" , GLA_EINVAL) ;
m->dat[i*m->m+j] = ele ;
}
type gla_matrix_get(const gla_matrix * m , const size_t i , const size_t j)
{
if(0 == m) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(i >= m->n || j >= m->m) PrintErr("Matrix doesn't have this elem" , GLA_EINVAL) ;
return m->dat[i*m->m+j] ;
}
void gla_matrix_free(gla_matrix * m)
{
if(m)
{
if(m->dat) free(m->dat) ;
free(m) ;
}
}
gla_matrix * gla_matrix_cpy(gla_matrix * des , const gla_matrix * src)
{
if(0 == des || 0 == src) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(des->n != src->n || des->m != src->m) PrintErr("Matrix size doesn't match" , GLA_EINVAL) ;
memcpy(des->dat , src->dat , src->n * src->m * sizeof(type)) ;
return des ;
}
void gla_matrix_addition(gla_matrix * des , const gla_matrix * src)
{
if(0 == des || 0 == src) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(des->n != src->n || des->m != src->m) PrintErr("Matrix size doesn't match" , GLA_EINVAL) ;
size_t i , j ;
for(i = 0 ; i < des->n ; ++i)
{
for(j = 0 ; j < des->m ; ++j)
des->dat[i*des->m+j] += src->dat[i*des->m+j] ;
}
}
void gla_matrix_multiplication(gla_matrix * m , const type k)
{
if(0 == m) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
size_t i , j ;
for(i = 0 ; i < m->n ; ++i)
{
for(j = 0 ; j < m->m ; ++j)
m->dat[i*m->m+j] *= k ;
}
}
gla_matrix * gla_matrix_matrix_multiplication(gla_matrix * des , const gla_matrix * m1 , const gla_matrix * m2)
{
if(0 == des || 0 == m1 || 0 == m2) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(m1->m != m2->n || m1->n != des->n || des->m != m2->m)
PrintErr("Matrixs can't do multiplication operator" , GLA_EINVAL) ;
size_t i , j , k ;
for(i = 0 ; i < des->n ; ++i)
{
for(j = 0 ; j < des->m ; ++j)
{
des->dat[i*des->m+j] = 0 ;
for(k = 0 ; k < m1->m ; ++k)
des->dat[i*des->m+j] += m1->dat[i*m1->m+k] * m2->dat[k*m2->m+j] ;
}
}
return des ;
}
gla_matrix * gla_matrix_square(gla_matrix * m)
{
if(0 == m) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(m->n != m->m) PrintErr("Matrix 's row size != col size" , GLA_EINVAL) ;
gla_matrix * mcopy = gla_matrix_alloc(m->n , m->m) ;
gla_matrix_cpy(mcopy , m) ;
m = gla_matrix_matrix_multiplication(m , mcopy , mcopy) ;
gla_matrix_free(mcopy) ;
return m ;
}
gla_matrix * gla_matrix_power(gla_matrix * m , const size_t k)
{
if(0 == m) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(m->n != m->m) PrintErr("Matrix can't do this operator" , GLA_EINVAL) ;
gla_matrix * temp = gla_matrix_alloc(m->n , m->m) ;
temp = gla_matrix_cpy(temp , m) ;
size_t i ;
for(i = k ; i > 0 ; i >>= 1)
gla_matrix_square(m) ;
if(k % 2)
{
gla_matrix * des = gla_matrix_alloc(m->n , m->m) ;
des = gla_matrix_matrix_multiplication(des , m , temp) ;
gla_matrix_cpy(m , des) ;
gla_matrix_free(des) ;
}
gla_matrix_free(temp) ;
return m ;
}
void gla_matrix_transpose(gla_matrix * m)
{
if(0 == m) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
size_t i , j ;
type temp ;
for(i = 0 ; i < m->n ; ++i)
{
for(j = 0 ; j < i ; ++j)
{
temp = m->dat[i*m->m+j] ;
m->dat[i*m->m+j] = m->dat[j*m->m+i] ;
m->dat[j*m->m+i] = temp ;
}
}
}
gla_vector * gla_matrix_rvector(const gla_matrix * m , gla_vector * v , const size_t i)
{
if(0 == m || 0 == v) PrintErr("Matrix and Vector can't be a null" , GLA_EINVAL) ;
if(m->m != v->n) PrintErr("Size doesn't match" , GLA_EINVAL) ;
size_t j ;
for(j = 0 ; j < m->m ; ++j)
v->dat[j] = m->dat[i*m->m+j] ;
return v ;
}
gla_vector * gla_matrix_cvector(const gla_matrix * m , gla_vector * v , const size_t j)
{
if(0 == m || 0 == v) PrintErr("Matrix and Vector can't be a null" , GLA_EINVAL) ;
if(m->m != v->n) PrintErr("Size doesn't match" , GLA_EINVAL) ;
size_t i ;
for(i = 0 ; i < m->n ; ++i)
v->dat[i] = m->dat[i*m->m+j] ;
return v ;
}
gla_matrix * gla_matrix_from_rvector(gla_matrix * m , const gla_vector * v)
{
if(0 == m || 0 == v) PrintErr("Matrix and Vector can't be a null" , GLA_EINVAL) ;
if(m->m != v->n) PrintErr("Size doesn't match" , GLA_EINVAL) ;
size_t i , j ;
for(i = 0 ; i < m->n ; ++i)
{
for(j = 0 ; j < m->m ; ++j)
{
m->dat[i*m->m+j] = v[i].dat[j] ;
}
}
return m ;
}
gla_matrix * gla_matrix_from_cvector(gla_matrix * m , const gla_vector * v)
{
if(0 == m || 0 == v) PrintErr("Matrix and Vector can't be a null" , GLA_EINVAL) ;
if(m->n != v->n) PrintErr("Size doesn't match" , GLA_EINVAL) ;
size_t i , j ;
for(j = 0 ; j < m->m ; ++j)
{
for(i = 0 ; i < m->n ; ++i)
m->dat[i*m->m+j] = v[j].dat[i] ;
}
return m ;
}
int gla_matrix_is_invertible(const gla_matrix * m)
{
if(0 == m) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(m->n != m->m) PrintErr("Size doesn't match" , GLA_EINVAL) ;
gla_determinant * d = gla_determinant_alloc(m->n) ;
memcpy(d->dat , m->dat , m->n * m->n * sizeof(type)) ;
type result = gla_determinant_value(d) ;
gla_determinant_free(d) ;
if(result > 0 || result < 0) return 1 ;
else return 0 ;
}
gla_matrix * gla_matrix_adjoint(const gla_matrix * m , gla_matrix * ad)
{
if(0 == m || 0 == ad) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(m->n != m->m || ad->n != ad->m || m->n != ad->n) PrintErr("Size doesn't match" , GLA_EINVAL) ;
gla_determinant * temp = gla_determinant_alloc(m->n) ;
memcpy(temp->dat , m->dat , m->n * m->m * sizeof(type)) ;
size_t i , j ;
for(i = 0 ; i < m->n ; ++i)
{
for(j = 0 ; j < m->m ; ++j)
ad->dat[i*ad->m+j] = gla_determinant_alge_complement(temp , i , j) ;
}
gla_determinant_free(temp) ;
return ad ;
}
gla_matrix * gla_matrix_invertible(gla_matrix * des , const gla_matrix * src)
{
if(0 == des || 0 == src) PrintErr("Matrix can't be a null" , GLA_EINVAL) ;
if(des->n != des->m || src->n != src->m || des->n != src->n)
PrintErr("Size doesn't match" , GLA_EINVAL) ;
gla_matrix_adjoint(src , des) ;
gla_determinant * d = gla_determinant_alloc(src->n) ;
memcpy(d->dat , src->dat , src->n * src->n * sizeof(type)) ;
type val = gla_determinant_value(d) ;
gla_matrix_multiplication(des , 1 / val) ;
gla_determinant_free(d) ;
return des ;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int print_matrix(int arr[3][3])
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
printf("\n\n");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* render_sprites.c :+: :+: */
/* +:+ */
/* By: dsalaman <[email protected]> +#+ */
/* +#+ */
/* Created: 2020/08/25 08:29:41 by dsalaman #+# #+# */
/* Updated: 2020/08/28 10:27:46 by dsalaman ######## odam.nl */
/* */
/* ************************************************************************** */
#include "../cub3d_bonus.h"
int ft_render_sprites(t_game *game)
{
int i;
t_sprite_cast s_cast;
i = 0;
ft_sort_sprites(&game->map, game->player.current_pos);
while (i < game->map.num_sprites)
{
ft_inverse_camera(game->map.sprites[i], &s_cast, game->player,
game->screen.resolution.width);
ft_calc_sprite_limits(&s_cast, game->screen.resolution,
game->player.ray);
ft_vertical_stripes(&s_cast, game->screen, game->map.zbuffer,
game->map.sprites[i]);
i++;
}
return (0);
}
/*
** 'inv_camera' = required for correct matrix multiplication.
** 'sprite_relative' = translate sprite position to relative to camera.
** 'transform y' = /this is the depth inside the screen.
*/
void ft_inverse_camera(t_sprite sprite, t_sprite_cast *s_cast,
t_player player, int w)
{
double inv_camera;
t_position sprite_relative;
sprite_relative.x = sprite.position.x - player.current_pos.x;
sprite_relative.y = sprite.position.y - player.current_pos.y;
inv_camera = 1.0 / (player.plane.x * player.orientation.y -
player.orientation.x * player.plane.y);
s_cast->transform.x = inv_camera * (player.orientation.y *
sprite_relative.x - player.orientation.x * sprite_relative.y);
s_cast->transform.y = inv_camera * (-player.plane.y * sprite_relative.x +
player.plane.x * sprite_relative.y);
s_cast->screen_x = (int)((w / 2) *
(1 + s_cast->transform.x / s_cast->transform.y));
}
/*
** Calculate height of the sprite on screen using 'transform y' instead of
** the real distance prevents fisheye.
*/
void ft_calc_sprite_limits(t_sprite_cast *s_cast,
t_size resolution, t_ray ray)
{
s_cast->move_screen = (int)(V_MOVE / s_cast->transform.y) + ray.pitch +
ray.pos_z / s_cast->transform.y;
s_cast->size.height = abs((int)(resolution.height / s_cast->transform.y));
s_cast->draw_start.y = (int)(-s_cast->size.height / 2 +
resolution.height / 2) + s_cast->move_screen;
if (s_cast->draw_start.y < 0)
s_cast->draw_start.y = 0;
s_cast->draw_end.y = (int)(s_cast->size.height / 2 +
resolution.height / 2) + s_cast->move_screen;
if (s_cast->draw_end.y >= resolution.height)
s_cast->draw_end.y = resolution.height - 1.0;
s_cast->size.width = abs((int)(resolution.height / s_cast->transform.y));
s_cast->draw_start.x = (int)(-s_cast->size.width / 2 + s_cast->screen_x);
if (s_cast->draw_start.x < 0)
s_cast->draw_start.x = 0;
s_cast->draw_end.x = (int)(s_cast->size.width / 2 + s_cast->screen_x);
if (s_cast->draw_end.x >= resolution.width)
s_cast->draw_end.x = resolution.width - 1.0;
}
/*
** ZBuffer is 1D, because it only contains the distance to the wall of
** every vertical stripe, instead of having this for every pixel.
*/
void ft_vertical_stripes(t_sprite_cast *s_cast, t_screen screen,
double *zbuffer, t_sprite sprite)
{
int stripe;
stripe = s_cast->draw_start.x;
while (stripe < s_cast->draw_end.x)
{
s_cast->draw_pos.x = (int)(256 * (stripe - (-s_cast->size.width / 2 +
s_cast->screen_x)) *
screen.sprite[sprite.type].width / s_cast->size.width) / 256;
if (s_cast->transform.y > 0 && stripe > 0 &&
stripe < screen.resolution.width &&
s_cast->transform.y < zbuffer[stripe])
ft_draw_stripes(s_cast, screen, stripe, sprite);
stripe++;
}
}
void ft_draw_stripes(t_sprite_cast *s_cast, t_screen screen,
int stripe, t_sprite sprite)
{
int color;
int y;
int d;
y = s_cast->draw_start.y;
while (y < s_cast->draw_end.y)
{
d = (y - s_cast->move_screen) * 256 - screen.resolution.height * 128 +
s_cast->size.height * 128;
s_cast->draw_pos.y = ((d *
screen.sprite[sprite.type].height) / s_cast->size.height) / 256;
color = ft_get_color(screen.sprite[sprite.type], s_cast->draw_pos);
if ((color & 0x00FFFFFF) != 0)
ft_put_pixel(&screen.win_data, stripe, y, color);
y++;
}
}
|
C
|
/**********************************************************
*
* scscan/src/c/scan.c
*
*/
int
beginScan(OPTIONS *options)
{
if (options->flags & SCAN_HRANGE)
return _beginRangeScan(options);
else
return _beginListScan(options);
}
int
_beginRangeScan(OPTIONS *options)
{
int _return_value = PERR_OK;
int _loct_status;
char *_direction = "forward";
char *_scan_type = "port list";
unsigned int _start_port;
unsigned int _end_port;
int _ports = options->ports.items;
char *_hostname;
OCTETS _from = octetsNew(options->hosts.item[0]);
OCTETS _to = octetsNew(options->hosts.item[1]);
FILE *_err = options->stream_err;
if (_from.err)
fperr(_err, PERR_FAILURE, "Invalid IP address: %`bright`%`:cyan`%s%`reset`\n", options->hosts.item[0]);
if (_to.err)
fperr(_err, PERR_FAILURE, "Invalid IP address: %`bright`%`:cyan`%s%`reset`\n", options->hosts.item[1]);
_loct_status = octetsCompare(&_from, &_to);
if (_loct_status == OCTETS_LLTR)
{
if (options->flags & SCAN_HINVRT)
_direction = "reverse";
}
else if (_loct_status == OCTETS_LGTR)
{
_direction = "reverse";
if (options->flags & SCAN_HINVRT)
_direction = "forward";
}
if (options->flags & SCAN_PRANGE)
{
_scan_type = "port range";
_start_port = (int) atol(options->ports.item[0]);
_end_port = (int) atol(options->ports.item[1]);
if (_start_port < _end_port)
_ports = ((_end_port - _start_port) + 1);
else if (_start_port > _end_port)
_ports = ((_start_port - _end_port) + 1);
else
_ports = 1;
if (options->flags & SCAN_PINVRT) {
_scan_type = "port range (inverted)";
_ports = ((65536 - _ports) + 1);
}
}
options->_out("\nBeginning %`bright`range%`reset` scan from %`bright`%`:cyan`%s%`reset` to %`bright`%`:cyan`%s%`reset` in a %`bright`%s%`reset` direction\n\n", options->hosts.item[0], options->hosts.item[1], _direction);
while (1)
{
options->_out("\tScanning %`bright`%s%`reset` (%`bright`%d%`reset` ports) on host %`bright`%`:cyan`%s%`reset`", _scan_type, _ports, _from.ip);
if ((_hostname = getHostName(_from.ip)) != NULL)
options->_out(" (%`bright`%`:green`%s%`reset`)", _hostname);
options->_out("\n\n");
// if (! (options->flags & SCAN_NOTCP)) {
if (strcmp(_scan_type, "port list") == 0)
__scanPortList(options, "TCP", _from.ip);
else
__scanPortRange(options, _from.ip, _start_port, _end_port, _scan_type, "TCP");
// }
if (octetsCompare(&_from, &_to) == OCTETS_LEQR)
break;
if (strcmp(_direction, "forward") == 0)
octetsNext(&_from);
else
octetsPrevious(&_from);
}
return PERR_OK;
}
/**
* _beginListScan()
*
* This is a little simpler than the range scan - in
* this instance, the given ports/port range will be
* scanned for each host IP in the list.
*
*/
int
_beginListScan(OPTIONS *options)
{
int _return_value = PERR_OK;
char *_scan_type = "port list";
unsigned int _start_port;
unsigned int _end_port;
int _host_no;
int _ports = options->ports.items;
char *_hostname;
FILE *_err = options->stream_err;
if (options->flags & SCAN_PRANGE)
{
_scan_type = "port range";
_start_port = (int) atol(options->ports.item[0]);
_end_port = (int) atol(options->ports.item[1]);
if (_start_port < _end_port)
_ports = ((_end_port - _start_port) + 1);
else if (_start_port > _end_port)
_ports = ((_start_port - _end_port) + 1);
else
_ports = 1;
if (options->flags & SCAN_PINVRT) {
_scan_type = "port range (inverted)";
_ports = ((65536 - _ports) + 1);
}
}
options->_out("\nBeginning %`bright`list%`reset` scan (%`bright`%d%`reset`hosts)\n\n", options->hosts.items);
for (_host_no = 0; _host_no < options->hosts.items; _host_no++)
{
options->_out("\tScanning %`bright`%s%`reset` (%`bright`%d%`reset` ports) on host %`bright`%`:cyan`%s%`reset`\n\n", _scan_type, _ports, options->hosts.item[_host_no]);
// if (! (options->flags & SCAN_NOTCP)) {
if (strcmp(_scan_type, "port list") == 0)
__scanPortList(options, "TCP", options->hosts.item[_host_no]);
else
__scanPortRange(options, options->hosts.item[_host_no], _start_port, _end_port, _scan_type, "TCP");
// }
}
return PERR_OK;
}
/**
* __scanPortRange()
*
* Scans a range of ports.
*
*/
int
__scanPortRange(OPTIONS *options, char *host, int start, int end, char *direction, char *protocol)
{
int _port = start;
int _sock;
char *_service;
while (1)
{
_service = __getServiceName(_port, "TCP");
options->_out("\t\tScanning %`bright`%s%`reset` Port %`bright`%`:cyan`%d%`reset` (%`bright`%`:cyan`%s%`reset`): ", protocol, _port, _service);
if (strcmp(protocol, "TCP") == 0)
_sock = tcpConnect(host, _port, options->timeout);
if (_sock < 0)
{
fprintf(stderr, "%s\n", strerror(errno));
options->_out("\n");
}
else {
if (_sock == 0)
options->_out("%`bright`%`:red`CLOSED%`reset`\n");
else
{
if (_sock == 2)
options->_out("%`bright`%`:magenta`TIMEOUT%`reset`\n");
else
options->_out("%`bright`%`:green`OPEN%`reset`\n");
}
}
if (_port == end)
break;
// Next port...
//
if (options->flags & SCAN_PINVRT)
{
if (start < end)
{
if (--_port < 1)
_port = 65535;
}
else
{
if (++_port > 65535)
_port = 1;
}
}
else
{
if (start < end)
{
if (++_port > 65535)
_port = 1;
}
else
{
if (--_port < 1)
_port = 65535;
}
}
}
options->_out("\n");
}
/**
* __scanPortList()
*
* Scan a list of ports as opposed to a range.
*
*/
int
__scanPortList(OPTIONS *options, char *protocol, char *host)
{
unsigned int _port;
int _port_no;
char *_service;
char _str_port[8];
int _sock;
if (options->flags & SCAN_PINVRT)
{
for (_port_no = 1; _port_no < 65535; _port_no++)
{
_service = __getServiceName(_port_no, "TCP");
snprintf(_str_port, 8, "%d", _port_no);
if (list_find(&options->ports, _str_port) >= PERR_OK)
continue;
options->_out("\t\tScanning %`bright`%s%`reset` Port %`bright`%`:cyan`%d%`reset` (%`bright`%`:green`%s%`reset`): \n", protocol, _port_no, _service);
if (strcmp(protocol, "TCP") == 0)
_sock = tcpConnect(host, _port, options->timeout);
if (_sock < 0)
{
fprintf(stderr, "%s\n", strerror(errno));
options->_out("\n");
}
else {
if (_sock == 0)
options->_out("%`bright`%`:red`CLOSED%`reset`\n");
else
{
if (_sock == 2)
options->_out("%`bright`%`:magenta`TIMEOUT%`reset`\n");
else
options->_out("%`bright`%`:green`OPEN%`reset`\n");
}
}
}
return 0;
}
for (_port_no = 0; _port_no < options->ports.items; _port_no++)
{
_port = (unsigned int) atol(options->ports.item[_port_no]);
_service = __getServiceName(_port, "TCP");
options->_out("\t\tScanning %`bright`%s%`reset` Port %`bright`%`:cyan`%d%`reset` (%`bright`%`:green`%s%`reset`): \n", protocol, _port, _service);
}
options->_out("\n");
}
|
C
|
#include "uart.h"
void UsartInit(u32 baud){
u16 DIV_M = 0, DIV_F = 0;
float DIV;
// 串口、端口时钟使能
USARTx_CLK_EN = 1;
IOPx_CLK_EN = 1;
#if UART_5
// 配置TX复用推挽输出
TX_GPIOx->TX_CRx &= TX_RESET;
TX_GPIOx->TX_CRx |= TXIO_Config;
// 配置RX端浮空输入
RX_GPIOx->RX_CRx &= RX_RESET;
RX_GPIOx->RX_CRx |= RXIO_Config;
#else
// 配置TX端复用推挽输出,RX端浮空输入
GPIOx->CRx &= RESET;
GPIOx->CRx |= IO_Config;
#endif
// 发送、接受位使能
USARTx_RE = 1;
USARTx_TE = 1;
// 设置波特率
DIV = (float)FCK / (16*baud);
DIV_M = DIV;
DIV_F = (DIV-DIV_M) * 16;
USARTx->BRR |= (DIV_M<<4) | DIV_F;
// 中断初始化
NVIC_Configration();
// 使能中断
USARTx_RXNEIE = 1;
// 工作在半双工模式
USARTx_HDSEL = 1;
// 串口外设使能
USARTx_UE = 1;
}
// 中断服务函数
void USARTx_IRQHandler(void){
u8 ch;
while(!USARTx_RXNE);
ch = USARTx->DR;
switch (ch)
{
case 1: BEEP = !BEEP;
LED_Red = !LED_Red;
puts("LED_red&Beep switch changed\r");
break;
case 2: BEEP = 0;
LED_Red = 1;
puts("LED_red&Beep turn off\r");
break;
}
}
void NVIC_Configration(void){
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = USARTx_IRQ; // 设置中断源
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01; // 抢占优先级1
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01; // 响应优先级1
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; // 使能接收串口接受中断通道
NVIC_Init(&NVIC_InitStructure); // 根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器
}
|
C
|
#include <stdio.h>
#define PI 3.14
void main()
{
int rayon = 5, DiametreDuCercle = 0;
double perimetre = 0, AireDuCercle = 0;
DiametreDuCercle = rayon*2;
perimetre = 2*PI*rayon;
AireDuCercle = PI*rayon*rayon;
printf("rayon : %d\n,Diametre du cercle : %d\n,Perimetre : %lf\n,Aire du cercle : %lf", rayon, DiametreDuCercle, perimetre, AireDuCercle);
}
|
C
|
/*AA*/
# include <stdio.h>
void main()
{
int i,j;
i=1; /*ѭʼǰIֵ1*/
do
{ /*ڲѭʼǰJֵ1*/
j=1;
while(j<=10)
{
printf("A");
j++; /*ڲѭJֵ1*/
}
printf("\n");
i++; /*ѭIֵ1*/
}while(i<=5);
}
|
C
|
#include <sys/defs.h>
#include <sys/memory/kmalloc.h>
#include <sys/kprintf.h>
#define INPUT_BUFFER_LENGTH 256
char* terminal_buffer;
int terminal_buffer_end = 0;
void init_terminal(){
terminal_buffer = sf_malloc(INPUT_BUFFER_LENGTH);
}
void terminal_input_ascii(char ascii){
if(terminal_buffer_end == INPUT_BUFFER_LENGTH) return;
terminal_buffer[terminal_buffer_end++] = ascii;
if(ascii == '\n'){
terminal_buffer[terminal_buffer_end] = 0;
kprintf("terminal receives: %s", terminal_buffer);
terminal_buffer_end = 0;
}
if(ascii == 0x8){
if(terminal_buffer_end > 1)terminal_buffer_end-=2;
else terminal_buffer_end--;
}
print_terminal_input_line(terminal_buffer, terminal_buffer_end);
}
|
C
|
#include "ft_dlist.h"
t_dlist *ft_dlist_pop_back(t_dlist *lst, t_dlist_it **item)
{
(*item) = 0;
if (lst->end)
{
if (lst->end->prev)
lst->end->prev->next = 0;
*item = lst->end;
lst->end = lst->end->prev;
if (!lst->end)
lst->begin = lst->end;
(*item)->prev = 0;
--lst->size;
}
return (lst);
}
|
C
|
//
// Created by suitm on 2020/12/26.
//
#ifndef ISTIME_H
#define ISTIME_H
#include <inttypes.h>
#include <time.h>
#include <sys/time.h>
#define ISTIME_VERSION_NO "21.08.1"
char * istime_version();
/** 取当前时间的毫秒数 **/
uint64_t istime_us();
/** 根据time_us微秒信息,生成ISO8601的标准日期时间格式, 其实秒以下是舍弃的 **/
char * istime_iso8601(char * strtime, uint32_t maxsize, uint64_t time_us);
/*
* format格式内容
%a 星期几的简写 %A 星期几的全称 %b 月份的简写 %B 月份的全称 %c 标准的日期的时间串 %C 年份的后两位数字
%d 十进制表示的每月的第几天 %D 月/天/年 %e 在两字符域中,十进制表示的每月的第几天 %F 年-月-日
%g 年份的后两位数字,使用基于周的年 %G 年份,使用基于周的年 %h 简写的月份名 %H 24小时制的小时
%I 12小时制的小时 %j 十进制表示的每年的第几天 %m 十进制表示的月份 %M 十时制表示的分钟数
%n 新行符 %p 本地的AM或PM的等价显示 %r 12小时的时间 %R 显示小时和分钟:hh:mm
%S 十进制的秒数 %t 水平 制表符 %T 显示时分秒:hh:mm:ss %u 每周的第几天,星期一为第一天 (值从1到7,星期一为1)
%U 第年的第几周,把星期日作为第一天(值从0到53) %V 每年的第几周,使用基于周的年 %w 十进制表示的星期几(值从0到6,星期天为0)
%W 每年的第几周,把星期一做为第一天(值从0到53) %x 标准的日期串 %X 标准的时间串 %y 不带世纪的十进制年份(值从0到99)
%Y 带世纪部分的十制年份 %z,%Z 时区名称,如果不能得到时区名称则返回空字符。 %% 百分号
*/
uint32_t istime_strftime(char * strtime, uint32_t maxsize, const char * format, uint64_t time_us);
/** 获取当日的时间信息,6位长 **/
long istime_longtime();
/** 获取当日的日期,8位长 **/
long istime_longdate();
/** 获取当前时区的信息 **/
unsigned long istime_timezone(void) {
#if defined(__linux__) || defined(__sun)
printf("timezone\n\n");
return timezone;
#else
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return tz.tz_minuteswest * 60UL;
#endif
}
#endif //ISTIME_H
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* d12.c :+: :+: */
/* +:+ */
/* By: jjacobs <[email protected]> +#+ */
/* +#+ */
/* Created: 2020/12/12 14:17:43 by jjacobs #+# #+# */
/* Updated: 2020/12/12 20:22:17 by jjacobs ######## odam.nl */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define MAXBUF 30
typedef struct ds
{
char str[MAXBUF];
int val; // Steps to take for this instruction
int wpx;
int wpy;
int x; // x after the instruction
int y; // y after the instruction
} step;
void getdata(char *file, int lines, struct ds *groups);
int getmeta(char *file, int *maxline);
int main(int argc, char **argv)
{
int ft = 0;
char *file0 = "input.txt";
char *file1 = "example.txt";
char *file;
if (argc > 1)
ft = atoi(argv[1]);
if (ft == 1)
file = file1;
else
file = file0;
printf("= INPUT CHECK ================================================\n");
int lines;
int maxline;
lines = getmeta(file, &maxline);
printf("Number of lines: %i\n", lines);
printf("(Max) line length: %i\n", maxline);;
printf("= ALLOC MEMORY & READING DATA ================================\n");
printf("Allocating data array...\n");
step *data2;
data2 = calloc(lines, sizeof(step));
if (data2 == NULL)
printf("Allocation for data array failed");
printf("Start reading input (pt 2)...\n");
data2[0].wpx = 10;
data2[0].wpy = 1;
getdata(file, lines, data2 + 1);
printf("= CHECKS EXTRA ===============================================\n");
printf("= PRINT TEST DATA ============================================\n");
int lastprint = 5;
int i = 0;
if (argc > 2)
lastprint = atoi(argv[2]);
printf("= PRINT TEST DATA (PT2) ======================================\n");
i = 0;
while (i < lastprint)
{
printf("inst %i = \"%-4s\" (val = %-2i) -> NewPos = (%-3i, %-3i) -> NextWP = (%-3i, %-3i)\n", i, data2[i].str, \
data2[i].val, data2[i].x, data2[i].y, data2[i].wpx, data2[i].wpy);
i++;
}
printf("= PT2 ANALYSIS ===============================================\n");
int a2 = 0;
int fin_x = data2[lines].x;
int fin_y = data2[lines].y;
a2 += (fin_x > 0) ? fin_x : -fin_x;
a2 += (fin_y > 0) ? fin_y : -fin_y;
printf("Answer part 2 = %i\n", a2);
//Freeing data
free(data2);
printf("= END ========================================================\n");
return (0);
}
/*
** Functions 'test reads' the data and returns number of lines. Also via pointer, it can provide
** + stores number of 'parts/files' (for example sep. by newline)
** + stores max line length
*/
int getmeta(char *file, int *ptmaxline)
{
FILE *in_file = fopen(file, "r");
if (in_file == NULL)
printf("File read failed\n");
char line[MAXBUF];
char *lpt;
int lines = 0;
int linesize = -1;
*ptmaxline = linesize;
while (fgets(line, sizeof(line), in_file) != NULL)
{
lines++;
lpt = line;
linesize = 0;
while (*lpt != '\n' && lpt++ != NULL)
linesize++;
if (linesize > *ptmaxline)
*ptmaxline = linesize;
}
fclose(in_file);
return (lines);
}
void move_to_wp_steps(step *legs, int legnum)
{
int x_old = legs[legnum - 1].x;
int y_old = legs[legnum - 1].y;
int steps = legs[legnum].val;
legs[legnum].x = x_old + legs[legnum].wpx * steps;
legs[legnum].y = y_old + legs[legnum].wpy * steps;
}
step rotate_wp(step leg)
{
int wpx0 = leg.wpx;
int wpy0 = leg.wpy;
step ret = leg;
int rot;
int cosZ;
int sinZ;
rot = (leg.str[0] == 'R') ? 1 : -1;
rot = leg.val * rot + 360;
if (rot % 180 == 0)
{
cosZ = (rot % 360 == 0) ? 1 : -1;
sinZ = 0;
}
if (rot % 180 == 90)
{
cosZ = 0;
sinZ = (rot % 360 == 90) ? -1 : 1;
}
ret.wpx = wpx0 * cosZ - wpy0 * sinZ;
ret.wpy = wpx0 * sinZ + wpy0 * cosZ;
return (ret);
}
step move_wp(step leg)
{
char dir = leg.str[0];
int steps = leg.val;
step ret = leg;
if (dir == 'E' || dir == 'W')
ret.wpx += (dir == 'E') ? steps : -steps;
else if (dir == 'N' || dir == 'S')
ret.wpy += (dir == 'N') ? steps : -steps;
return (ret);
}
// To do
// Split the 2nd part off, sep for pt 1 and pt 2.
void getdata(char *file, int lines, struct ds *dat)
{
FILE *in_file;
char str[MAXBUF];
int line = 0;
in_file = fopen(file, "r");
if (in_file == NULL)
printf("File read failed\n");
while (line < lines && fgets(str, MAXBUF, in_file) != NULL)
{
//printf("reading: %s", str);
dat[line] = dat[line - 1]; // initialize step N = step N - 1;
bzero(dat[line].str, 3); // remove old bytes from str
strncpy(dat[line].str, str, strchr(str, '\n') - str); // store new instrucion - can be handy / not req;
dat[line].val = atoi(str + 1); // get arg value
if (str[0] == 'F')
move_to_wp_steps(dat, line);
if (str[0] == 'L' || str[0] == 'R')
dat[line] = rotate_wp(dat[line]);
if (str[0] == 'N' || str[0] == 'E' || str[0] == 'S' || str[0] == 'W')
dat[line] = move_wp(dat[line]);
line++;
}
fclose(in_file);
}
|
C
|
# include<stdio.h>
int main(){
int m,n;
printf("Enter order of matrix : ");
scanf("%d%d",&m,&n);
int i,j;
int a[m][n];
printf("Enter elements for array\n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The entered array is :\n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("The entered array is :\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d\t",a[j][i]);
}
printf("\n");
}
return 0;
}
|
C
|
#include "holberton.h"
/**
* _strcpy - Copy a string into other
* @dest: String to copy.
* @src: Buffer string
* _putchar - Write characters
* Return: 0
*/
char *_strcpy(char *dest, char *src)
{
int i = 0, j = 0;
while (src[i] != '\0')
i++;
for (; j <= i; j++)
dest[j] = src[j];
return (dest);
}
|
C
|
/*
* Project: Drivers development tutorial
* Target MCU: STM32F401XE
* Author: Jakub Standarski
*
*/
#include "nvic_irq.h"
#include <stdint.h>
/*****************************************************************************/
/* NVIC IRQ API DEFINITIONS */
/*****************************************************************************/
void nvic_irq_priority_config(nvic_irq_number_t irq_number,
nvic_irq_priority_t irq_priority)
{
const uint8_t priority_bits_amount = 4;
uint8_t ipr_register_number = irq_number / 4;
uint8_t ipr_register_section = irq_number % 4;
uint8_t shift_in_register = (8 * ipr_register_section) + (8 -
priority_bits_amount);
*(NVIC_IPR0_BASE_ADDRESS + ipr_register_number) |= (irq_priority <<
shift_in_register);
}
void nvic_irq_enable(nvic_irq_number_t irq_number)
{
if(irq_number <= 31) {
*NVIC_ISER0_BASE_ADDRESS |= (1 << irq_number);
} else if(irq_number > 31 && irq_number <= 63) {
*NVIC_ISER1_BASE_ADDRESS |= (1 << (irq_number % 32));
} else if(irq_number > 63 && irq_number <= 95) {
*NVIC_ISER2_BASE_ADDRESS |= (1 << (irq_number % 64));
}
}
void nvic_irq_disable(nvic_irq_number_t irq_number)
{
if(irq_number <= 31) {
*NVIC_ICER0_BASE_ADDRESS |= (1 << irq_number);
} else if(irq_number > 31 && irq_number <= 63) {
*NVIC_ICER1_BASE_ADDRESS |= (1 << (irq_number % 32));
} else if(irq_number > 63 && irq_number <= 95) {
*NVIC_ICER2_BASE_ADDRESS |= (1 << (irq_number % 64));
}
}
|
C
|
#include "ft.h"
#include "ft_test.h"
int main(int argc, char **argv)
{
t_list **list;
t_list *n1;
t_list *n2;
// t_list *n3;
if (argc || argv)
printf("./test_lstnew <n1> <n2> <n3>\n");
n1 = ft_lstnew((void *)argv[1]);
list = &n1;
n2 = ft_lstnew((void *)argv[2]);
ft_lstadd_front(list, n2);
while ((*list)->next)
{
printf("%s\n", (char *)(*list)->content);
*list = (*list)->next;
}
return (0);
}
|
C
|
/* xmpl7.c
* program to find prime numbers
*/
#include <stdio.h>
#include <stdbool.h>
int main(void) {
/* Initialise our counter */
int i = 1;
while (i <= 10000) {
/* Initialise prime flag */
bool prime_flag = true;
int j = 2;
/* Test divisibility of i from [0, i/2] */
while (j <= i/2) {
printf(" i ==> %d j ==> %d\n", i, j);
if (i % j == 0) {
prime_flag = false;
printf(" %d is a factor of %d\n", j, i);
printf("%d is not prime.\n", i);
break;
}
j = j + 1;
}
/* We found a prime! */
if (prime_flag)
printf("Prime ==> %d\n", i);
/* Increment the counter */
i += 1;
}
}
|
C
|
#include "model/service_list.h"
#include <stdlib.h>
int pat2services(pat_table_t *pat, service_table_t *srv)
{
puts("pat2services");
srv->cnt = 0;
srv->items = malloc(sizeof(service_item_t)*pat->programs_cnt);
program_desc_t *current = pat->programs;
int i;
for(i = 0; i < pat->programs_cnt; i++)
{
printf("in the loop\n");
printf("program_number_hdr: %d\n", current->program_number);
if(current->program_number != 0u && current->program_number < 1024u)
{
srv->items[srv->cnt].position = i;
srv->items[srv->cnt].program_number = current->program_number;
srv->items[srv->cnt].pmt_pid = current->program_pid;
printf("prog_number: %d - pmt pid: %d\n",
srv->items[srv->cnt].program_number, srv->items[srv->cnt].pmt_pid);
srv->cnt++;
}
current = current->next;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
char converte(char c,int shift){
c=c-97;
if(c>=0&&c<=26){
c=c+shift;
c=c%26;
if(c<0)c=26+c;
}
return c+97;
}
int main(){
char string[100];
int shift;
fgets(string,100,stdin);
scanf("%d",&shift );
for(int i=0;i<strlen(string)-1;i++){
printf("%c",converte(string[i],shift));
}
}
|
C
|
/*Задача 2 Създайте нов потребителски тип
към тип long long int. Използвайте го във функцията
printf, отпечатайте размера.
Задача 3. Дефинирайте потребителски тип към
указател.Създайте променлива, насочете указателя
към нея, използвайки новия потребителски тип.*/
#include <stdio.h>
int main(){
typedef long long int t_Lint;
t_Lint num = 1234506987657654364;
printf("%lld",num);
typedef t_Lint* t_prtint;
t_prtint prtnum = #
printf("\n%lld",*prtnum);
return 0;
}
|
C
|
/*Sean Kee*/
/*Dynamic Allocation Sorting System v1.0.1*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sortAsc(int *output, int size) {
int i; /*Number of Passes*/
int j;
int temp;
int *ptr = output;
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - 1; j++) {
if (ptr[j] > ptr[j + 1]) { /*if the current number being checked is greater than the next one, swap places)*/
temp = ptr[j];
ptr[j] = ptr[j + 1];
ptr[j + 1] = temp;
}
}
}
}
int *sortDes(int *output, int size) {
int i; /*Number of Passes*/
int j;
int temp;
int *ptr = output;
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - 1; j++) {
if (ptr[j] < ptr[j + 1]) { /*Same thing as ascending, just backwards*/
temp = ptr[j];
ptr[j] = ptr[j + 1];
ptr[j + 1] = temp;
}
}
}
}
int main() {
int *original; /*Creates original pointer*/
original = (int *) malloc(10 * sizeof(int)); /*Assigns Dynamic memory,10 ints of 4 bytes each*/
int size; /*User input for array size*/
printf("Input the array size\n#: ");
scanf("%d", &size);
original = (int *) realloc(original, size * sizeof(int)); /*Reallocates enough space based on the size inputted by the user*/
int *ascending = (int *) malloc(size * sizeof(int));
int *descending = (int *) malloc(size * sizeof(int));
int i; /*counter*/
srand(time(NULL));
for(i = 0; i < size; i++) { /*Fills the original with random numbers between 1 and 100 */
original[i] = (rand() % 100);
ascending[i] = original[i];
descending[i] = original[i];
}
sortAsc(ascending, size);
sortDes(descending, size);
printf("Original Numbers\n");
for (i = 0; i < size; i++) {
printf("%d\n", original[i]);
}
printf("****\n");
printf("Numbers in Ascending order\n");
for (i = 0; i < size; i++) {
printf("%d\n", ascending[i]);
}
printf("****\n");
printf("Numbers in Descending order\n");
for (i = 0; i < size; i++) {
printf("%d\n", descending[i]);
}
free(original); /*Frees dynamic memory*/
free(ascending);
free(descending);
return 0;
}
|
C
|
/* -*- coding: iso-latin-1-unix; -*- */
/* DECLARO QUE SOU O UNICO AUTOR E RESPONSAVEL POR ESTE PROGRAMA.
// TODAS AS PARTES DO PROGRAMA, EXCETO AS QUE FORAM FORNECIDAS
// PELO PROFESSOR OU COPIADAS DO LIVRO OU DAS BIBLIOTECAS DE
// SEDGEWICK OU ROBERTS, FORAM DESENVOLVIDAS POR MIM. DECLARO
// TAMBEM QUE SOU RESPONSAVEL POR TODAS AS COPIAS DESTE PROGRAMA
// E QUE NAO DISTRIBUI NEM FACILITEI A DISTRIBUICAO DE COPIAS.
//
// Autor: Matheus de Mello Santos Oliveira
// Numero USP: 8642821
// Sigla: MATHEUSD
// Data: 2015-10-12
//
// Este arquivo faz parte da tarefa G
// da disciplina MAC0121.
//
////////////////////////////////////////////////////////////// */
#include <stdio.h>
#include <stdlib.h>
#include "ordenacao.h"
/* Versao alternativa do malloc, printa um erro caso nao consiga
alocar memoria.
*/
static void *
mallocc (size_t nbytes)
{
void *ptr;
ptr = malloc (nbytes);
if (ptr == NULL) {
printf ("Socorro! malloc devolveu NULL!\n");
exit (EXIT_FAILURE);
}
return ptr;
}
/* Esta funo rearranja o vetor v[0..n-1] em ordem crescente.
*/
static void
insercao (int n, int v[])
{
int i, j, x;
for (j = 1; j < n; ++j) {
x = v[j];
for (i = j - 1; i >= 0 && v[i] > x; --i)
v[i + 1] = v[i];
v[i + 1] = x;
}
}
/* A funo recebe vetores crescentes v[p..q-1] e v[q..r-1]
e rearranja v[p..r-1] em ordem crescente.
*/
static void
intercala (int p, int q, int r, int v[])
{
int i, j, k, *w;
w = mallocc ((r - p) * sizeof (int));
i = p; j = q;
k = 0;
while (i < q && j < r) {
if (v[i] <= v[j]) w[k++] = v[i++];
else w[k++] = v[j++];
}
while (i < q) w[k++] = v[i++];
while (j < r) w[k++] = v[j++];
for (i = p; i < r; ++i) v[i] = w[i - p];
free (w);
}
/* A funo mergesort rearranja o vetor v[p..r-1]
em ordem crescente.
*/
static void
mergeSort (int p, int r, int v[])
{
if (p < r - 1) {
int q = (p + r) / 2;
mergeSort (p, q, v);
mergeSort (q, r, v);
intercala (p, q, r, v);
}
}
/* Recebe vetor v[p..r] com p < r. Rearranja os elementos
do vetor e devolve j em p..r tal que
v[p..j-1] <= v[j] < v[j+1..r].
*/
static int
separa (int v[], int p, int r)
{
int c = v[p], i = p + 1, j = r, t;
while (i <= j) {
if (v[i] <= c) ++i;
else if (c < v[j]) --j;
else {
t = v[i], v[i] = v[j], v[j] = t;
++i; --j;
}
}
v[p] = v[j], v[j] = c;
return j;
}
/* A funo rearranja o vetor v[p..r], com p <= r+1, de modo
que ele fique em ordem crescente.
*/
static void
quickSort (int v[], int p, int r)
{
int j;
while (p < r) {
j = separa (v, p, r);
if (j - p < r - j) {
quickSort (v, p, j - 1);
p = j + 1;
} else {
quickSort (v, j + 1, r);
r = j - 1;
}
}
}
/* Recebe p em 1..m e rearranja o vetor v[1..m] de modo que o
"subvetor" cuja raiz p seja um heap. Supe que os "subvetores"
cujas razes so filhos de p j so heaps.
*/
static void
peneira (int p, int m, int v[])
{
int f = 2 * p, x = v[p];
while (f <= m) {
if (f < m && v[f] < v[f + 1]) ++f;
if (x >= v[f]) break;
v[p] = v[f];
p = f, f = 2 * p;
}
v[p] = x;
}
/* Rearranja os elementos do vetor v[1..n] de modo que
fiquem em ordem crescente.
*/
static void
heapSort (int n, int v[])
{
int p, m, x;
for (p = n / 2; p >= 1; --p)
peneira (p, n, v);
for (m = n; m >= 2; --m) {
x = v[1], v[1] = v[m], v[m] = x;
peneira (1, m - 1, v);
}
}
/* Rearranja os elementos do vetor v[0..n-1] de modo que
fiquem em ordem crescente.
*/
void
heap_sort (int *v, int n)
{
heapSort (n, v - 1);
}
/* Rearranja os elementos do vetor v[0..n-1] de modo que
fiquem em ordem crescente.
*/
void
quick_sort (int *v, int n)
{
quickSort (v, 0, n-1);
}
/* Rearranja os elementos do vetor v[0..n-1] de modo que
fiquem em ordem crescente.
*/
void
merge_sort (int *v, int n)
{
mergeSort (0, n, v);
}
/* Rearranja os elementos do vetor v[0..n-1] de modo que
fiquem em ordem crescente.
*/
void
insertion_sort (int *v, int n)
{
insercao (n, v);
}
|
C
|
/*
* initialize two global integer arrays x[10] and y[10]
* when S2 us pushed an ISR will:
* -calculate y[n] = 2*x[n] - x[n-1]
*/
#include <msp430.h>
int x[10] = {5, 3, 7, 10, 4, 9, 2, 12, 7 ,8};
int y[10] = {0};
void main(void)
{
WDTCTL = WDTPW | WDTHOLD;
P1OUT = 0x00;
P1SEL = 0x00;
P1DIR = 0xF7;
P1REN = 0x00;
P1IES = BIT3;
P1IFG = 0x00;
P1IE = BIT3;
_enable_interrupt();
while(1);
}
#pragma vector = PORT1_VECTOR
__interrupt void PORT1_ISR(void)
{
static int n = 0;
if (n == 0)
y[n] = 2*x[n];
else if (n < 10)
y[n] = 2*x[n] - x[n-1];
n++;
P1IFG &= ~BIT3;
}
|
C
|
/* ***************************************************************
* Filename: matrix.c
* Description: Matrix Multiply code for Host.
* Author: Unknown
* ***************************************************************/
#include <accelerator.h>
#include <matrix.h>
#include <htconst.h>
Hint poly_matrix_mul (void * a_ptr, void * b_ptr, void * c_ptr, Huint a_rows, Huint a_cols, Huint b_cols) {
return sw_matrix_multiply (a_ptr, b_ptr, c_ptr, a_rows, a_cols, b_cols);
}
Hint sw_matrix_multiply (void * a_ptr, void * b_ptr, void * c_ptr, Huint a_rows, Huint a_cols, Huint b_cols) {
Hint * a = a_ptr;
Hint * b = b_ptr;
Hint * c = c_ptr;
assert( a_cols == a_rows);
char i, j, k=0;
int sum= 0;
for (i=0; i<a_rows; i++){
for (j=0; j<b_cols; j++){
sum = 0;
for (k=0; k<a_cols; k++){
sum += a[i*a_cols+k] * b[k*b_cols+j];
}
c[i*b_cols+j] = sum;
}
}
return SUCCESS;
}
|
C
|
//
// main.c
// 找数组中的最小值和次小值并输出
//
// Created by mac on 15/12/3.
// Copyright © 2015年 mac. All rights reserved.
//
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int a[10],i;
int s1,s2 = 0;
s1=9;
srand((unsigned)time(NULL));
for (i=0; i<10; i++) {
a[i]=(unsigned)rand()%10;
}
for (i=0; i<10; i++)
printf(" %d ",a[i]);
printf("\n");
for (i=0; i<8; i++) {
if (a[i]<=a[s1]) {
s2=s1;
s1=i;
}else if (a[i]<=a[s2]) {
s2=i;
}
}
printf("%d,%d,%d,%d\n",s1,s2,a[s1],a[s2]);
// insert code here...
printf("Hello, World!\n");
return 0;
}
|
C
|
/*
tarea9.c
Compilacin: gcc -o tarea9 tarea9.c
Este programa ignora las interrupciones por teclado.
*/
#include <stdio.h>
#include <signal.h>
int main(){
struct sigaction sa;
sa.sa_handler = SIG_IGN; // ignora la seal
sigemptyset(&sa.sa_mask); // inicializa a vaco
//Reiniciar las funciones que hayan sido interrumpidas por un manejador
sa.sa_flags = SA_RESTART;
/*
* La llamada al sistema sigaction se emplea para
* cambiar la accin tomada por un proceso cuando
* recibe una determinada seal.
*/
if (sigaction(SIGINT, &sa, NULL) == -1){
printf("error en el manejador");
}
while(1);
}
|
C
|
#include <stdio.h>
#include <string.h>
#define max 20
int main() {
char mes[max];
printf("Introduce el nombre de un mes: ");
gets(mes);
if (strcmp(mes,"febrero")==0){
printf("%s tiene 28/29 días\n",mes);}
else if (strcmp(mes,"abril")==0||strcmp(mes,"junio")==0||strcmp(mes,"septiembre")==0||strcmp(mes,"noviembre")==0){
printf("%s tiene 30 días\n",mes);}
else{
printf("%s tiene 31 días\n",mes);}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_base64.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kvignau <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/09/03 12:59:45 by kvignau #+# #+# */
/* Updated: 2018/09/03 12:59:49 by kvignau ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_ssl.h"
char g_base64[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'};
void ft_print_base(int save, int size, t_opts opt)
{
while (size >= 0)
{
ft_putchar_fd(g_base64[(save >> (6 * size)) & 0x3F], opt.fd);
size--;
}
}
char *ft_invalid_char(void)
{
print_errors("Invalid character in input stream.\n");
return (NULL);
}
int ft_get_letter(char c)
{
int i;
i = -1;
while (++i < 64)
{
if (c == g_base64[i])
return (i);
}
return (-1);
}
char *ft_cleanspace(char *str, char *tmp)
{
int i;
int j;
i = -1;
j = 0;
while (str[++i])
{
if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
continue ;
tmp[j] = str[i];
j++;
}
return (tmp);
}
int ft_base64_string(char *val, t_opts opt, char *name, int hash_choice)
{
name = NULL;
hash_choice = 0;
if (opt.opt & OPT_E || !(opt.opt & OPT_D))
return (ft_encode_base(val, opt));
if (opt.opt & OPT_D)
return (ft_decode_base(val, opt));
return (EXIT_FAILURE);
}
|
C
|
/*Values incorrects to big numbers like C(99,50), but for this problem is good enougth*/
#include<stdio.h>
#define MAXN 100
#define MAXK 100
long int C[MAXN + 1][MAXK + 1];
void binCoeff(int, int);
int min(int, int);
int main(void) {
int n, k;
binCoeff(MAXN, MAXK);
scanf("%d %d\n", &n, &k);
while (n && k) {
printf("%d things taken %d at a time is %ld exactly.\n", n, k, C[n][k]);
scanf("%d %d\n", &n, &k);
}
return 0;
}
void binCoeff(int n, int k) {
int i, j;
for (i = 0; i <= n; i++) {
for (j = 0; j <= min(i, k); j++){
if (j == 0 || j == i) {
C[i][j] = 1;
} else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
}
}
int min(int a, int b) {
return a < b? a : b;
}
|
C
|
#include "binary_trees.h"
/**
* count - Count the nodes in a tree.
* @tree: Pointer to the root node of the tree to traverse
* Return: Number of nodes in a tree.
*/
int count(const binary_tree_t *tree)
{
if (!tree)
return (0);
if (tree->left || tree->right)
return (count(tree->left) + count(tree->right) + 1);
else
return (count(tree->left) + count(tree->right));
}
/**
* binary_tree_nodes - Count nodes with at least 1 child in a binary tree.
* @tree: Pointer to the root node of the tree to traverse
* Return: Number of nodes in a tree.
*/
size_t binary_tree_nodes(const binary_tree_t *tree)
{
if (!tree)
return (0);
return (count(tree));
}
|
C
|
#include <stdio.h>
#include <string.h>
typedef struct{
int id; // 学生番号
int kokugo; // 国語の点数
int sansu; // 算数の点数
int rika; // 理科の点数
int shakai; // 社会の点数
int eigo; // 英語の点数
}student_data;
void setData(student_data*,int,int,int,int,int,int);
void main(){
int i;
double k_point = 0;
double s_point = 0;
double r_point = 0;
double sh_point = 0;
double e_point = 0;
student_data data[5];
int id[5] = { 1001,1002,1003,1004,1005 };
int kokugo[5] = { 82,92,43,72,99 };
int sansu[5] = { 43,83,32,73,72 };
int rika[5] = { 53,88,53,71,82 };
int shakai[5] = { 84,79,45,68,91 };
int eigo[5] = { 45,99,66,59,94 };
for(i = 0; i < 5; i++){
setData(&data[i],id[i],kokugo[i],sansu[i],rika[i],shakai[i],eigo[i]);
}
// 学生のデータの表示
for(i = 0; i < 5; i++){
k_point += data[i].kokugo;
s_point += data[i].sansu;
r_point += data[i].rika;
sh_point += data[i].shakai;
e_point += data[i].eigo;
}
printf("国語の平均点 = %.2f\n",k_point / 5);
printf("数学の平均点 = %.2f\n",s_point / 5);
printf("理科の平均点 = %.2f\n",r_point / 5);
printf("社会の平均点 = %.2f\n",sh_point / 5);
printf("英語の平均点 = %.2f\n",e_point / 5);
}
void setData(student_data* data,int id,int kokugo,int sansu,int rika,int shakai,int eigo){
data -> id = id;
data -> kokugo = kokugo;
data -> sansu = sansu;
data -> rika = rika;
data -> shakai = shakai;
data -> eigo = eigo;
}
|
C
|
/*
random.c - random generator
Copyright (C) 2007 Uncle Mike
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 3 of the License, 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.
*/
//#include "common.h"
#include <time.h>
static long idum = 0;
#define MAX_RANDOM_RANGE 0x7FFFFFFFUL
#define IA 16807
#define IM 2147483647
#define IQ 127773
#define IR 2836
#define NTAB 32
#define NDIV (1+(IM-1)/NTAB)
#define AM (1.0/IM)
#define EPS 1.2e-7
#define RNMX (1.0 - EPS)
void SeedRandomNumberGenerator( long lSeed )
{
if( lSeed ) idum = lSeed;
else idum = -time( NULL );
if( 1000 < idum ) idum = -idum;
else if( -1000 < idum ) idum -= 22261048;
}
long lran1( void )
{
int j;
long k;
static long iy = 0;
static long iv[NTAB];
if( idum <= 0 || !iy )
{
if(-(idum) < 1) idum=1;
else idum = -(idum);
for( j = NTAB + 7; j >= 0; j-- )
{
k = (idum) / IQ;
idum = IA * (idum - k * IQ) - IR * k;
if( idum < 0 ) idum += IM;
if( j < NTAB ) iv[j] = idum;
}
iy = iv[0];
}
k = (idum)/IQ;
idum = IA * (idum - k * IQ) - IR * k;
if( idum < 0 ) idum += IM;
j = iy / NDIV;
iy = iv[j];
iv[j] = idum;
return iy;
}
// fran1 -- return a random floating-point number on the interval [0,1)
float fran1( void )
{
float temp = (float)AM * lran1();
if( temp > RNMX ) return (float)RNMX;
else return temp;
}
float RandomFloat( float flLow, float flHigh )
{
float fl;
if( idum == 0 ) SeedRandomNumberGenerator(0);
fl = fran1(); // float in [0, 1)
return (fl * (flHigh - flLow)) + flLow; // float in [low, high)
}
long RandomLong( long lLow, long lHigh )
{
unsigned long maxAcceptable;
unsigned long n, x = lHigh-lLow + 1;
if( idum == 0 ) SeedRandomNumberGenerator(0);
if( x <= 0 || MAX_RANDOM_RANGE < x-1 )
return lLow;
// The following maps a uniform distribution on the interval [0, MAX_RANDOM_RANGE]
// to a smaller, client-specified range of [0,x-1] in a way that doesn't bias
// the uniform distribution unfavorably. Even for a worst case x, the loop is
// guaranteed to be taken no more than half the time, so for that worst case x,
// the average number of times through the loop is 2. For cases where x is
// much smaller than MAX_RANDOM_RANGE, the average number of times through the
// loop is very close to 1.
maxAcceptable = MAX_RANDOM_RANGE - ((MAX_RANDOM_RANGE+1) % x );
do
{
n = lran1();
} while( n > maxAcceptable );
return lLow + (n % x);
}
|
C
|
/* gcc -o aufgabe sched.c matrix.c -lpthread
./aufgabe 322 131 3
Initializing...
Starting...
Thread 0 beendet: 23 ms
Thread 1 beendet: 29 ms
Thread 2 beendet: 27 ms
Langsamster Thread war 1: 29 ms
Schnellster Thread war 0: 23 ms
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include "matrix.h"
typedef struct eters{
long long* matrixA;
long long* matrixB;
int rows;
int cols;
}parameter;
void setprio( pthread_t id, int policy, int prio ) {
struct sched_param param;
param.sched_priority = prio;
if((pthread_setschedparam( id, policy, ¶m)) != 0 ) {
printf("error: scheduling strategy konnte nicht geaendert werden. Vielleicht kein root?\n");
pthread_exit((void *)id);
}
}
/* second thread */
void* my_thread(void* data) {
long* ret = (long*) malloc(sizeof(long));
long long* matrixA = ((parameter*) data)->matrixA;
long long* matrixB = ((parameter*) data)->matrixB;
int rows = ((parameter*) data)->rows;
int columns = ((parameter*) data)->cols;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
long long* matrixC = (long long*)calloc(rows * columns, sizeof(long long));
if (ret == NULL || matrixC == NULL) {
printf("Allocation error!");
exit(EXIT_FAILURE);
}
multiplyMatrices(matrixA, matrixB, matrixC, rows, columns, columns);
clock_gettime(CLOCK_MONOTONIC, &end);
*ret = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_nsec - start.tv_nsec) / 1000 / 1000;
free(matrixC);
return (void*) ret;
}
int main(int argc, const char* argv[]) {
if(argc != 4){
printf("ERROR: zu wenig argumente");
}
const int zeileAnz = strtol(argv[1], NULL, 10);
const int spalteAnz = strtol(argv[2], NULL, 10);
const int anzThreads = strtol(argv[3], NULL, 10);
if (zeileAnz < 0 || zeileAnz > INT_MAX) {
printf("Ungueltige Zeilenanzahl: %d\n", zeileAnz);
exit(EXIT_FAILURE);
}
if (spalteAnz < 0 || spalteAnz > INT_MAX) {
printf("Ungueltige Spaltenanzahl: %d\n", spalteAnz);
exit(EXIT_FAILURE);
}
if (anzThreads < 0 || anzThreads > 16) {
printf("Ungueltige Anzahl Threads: %d\n", anzThreads);
exit(EXIT_FAILURE);
}
printf("Initializing...\n");
long long* matrixA = (long long*) malloc(zeileAnz * spalteAnz * sizeof(long long));
long long* matrixB = (long long*) malloc(zeileAnz * spalteAnz * sizeof(long long));
parameter* params = (parameter*) malloc(sizeof(parameter));
if (matrixA == NULL || matrixB == NULL) {
printf("Allokations error!");
exit(EXIT_FAILURE);
}
srand (time( NULL));
initializeMatrix(matrixA, zeileAnz, spalteAnz);
initializeMatrix(matrixB, zeileAnz, spalteAnz);
printf("Starting...\n");
params->matrixA = matrixA;
params->matrixB = matrixB;
params->rows = zeileAnz;
params->cols = spalteAnz;
pthread_t threads[anzThreads];
for (int i = 0; i < anzThreads; i++)
{
if (pthread_create(&threads[i], NULL, my_thread, params)!= 0) {
printf("error: Thread erstellen fehlgeschlagen.\n");
return EXIT_FAILURE;
}
if (i == anzThreads - 1) {
setprio(threads[i], SCHED_FIFO, 99);
}
}
long min = INT_MAX;
long max = 0;
int min_index = -1;
int max_index = -1;
void* ret_ptr = NULL;
for (int i = 0; i < anzThreads; i++) {
pthread_join(threads[i], &ret_ptr);
long value = *((long*) ret_ptr);
printf("Thread %d beendet: %ld ms\n", i, value);
if (value >= max) {
max = value;
max_index = i;
}
if (value <= min) {
min = value;
min_index = i;
}
free(ret_ptr);
}
printf("Langsamster Thread war %d: %ld ms\n", max_index, max);
printf("Schnellster Thread war %d: %ld ms\n", min_index, min);
free(matrixA);
free(matrixB);
free(params);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
//void main()
//{
// int n1, n2, i, gcd;
//
// printf("Կոָ");
// scanf("%d %d", &n1, &n2);
//
// for (i = 1; i <= n1 && i <= n2; i++)
// {
// if (n1 % i == 0 && n2 % i == 0)
// {
// gcd = i;
// printf("Լ%d\n", i);
// }
// }
//
// printf("%d %d Լ %d", n1, n2, gcd);
//
// system("pause");
//}
//void main()
//{
// int n1, n2;
//
// printf("Կոָ");
// scanf("%d %d", &n1, &n2);
//
// n1 = (n1 > 0) ? n1 : -n1;
// n2 = (n2 > 0) ? n2 : -n2;
//
// while (n1 != n2)
// {
// if (n1 > n2)
// n1 -= n2;
// else
// n2 -= n1;
// printf("n1 = %d n2 = %d\n", n1, n2);
// }
// printf("GCD = %d", n1);
//
// system("pause");
//}
int hcf(int n1, int n2);
void main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("%d %d ԼΪ %d", n1, n2, hcf(n1, n2));
system("pause");
}
int hcf(int n1, int n2)
{
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
|
C
|
/* Program for reading/controlling CryoTel GT with AVC controller */
/* and putting said readings in to a mysql database. */
/* defined below. */
/* D.Norcini, UChicago, 2020*/
#include "SC_db_interface.h"
#include "SC_aux_fns.h"
#include "SC_sensor_interface.h"
#include "ethernet.h"
// This is the default instrument entry, but can be changed on the command line when run manually.
// When called with the watchdog, a specific instrument is always given even if it is the same
// as the default.
#define INSTNAME "CryoTelGT_AVC"
int inst_dev;
#define _def_set_up_inst
int set_up_inst(struct inst_struct *i_s, struct sensor_struct *s_s_a)
{
char cmd_string[64];
if ((inst_dev = connect_tcp(i_s)) < 0)
{
fprintf(stderr, "Connect failed. \n");
my_signal = SIGTERM;
return(1);
}
return(0);
}
#define _def_clean_up_inst
void clean_up_inst(struct inst_struct *i_s, struct sensor_struct *s_s_a)
{
close(inst_dev);
}
#define _def_read_sensor
int read_sensor(struct inst_struct *i_s, struct sensor_struct *s_s, double *val_out)
{
char cmd_string[64];
char ret_string[64];
if (strncmp(s_s->subtype, "tc", 2) == 0) // Read out value for temp sensor
{
sprintf(cmd_string, "TC\r");
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
msleep(200);
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
// output in TC\n<temp>
int data_length = ret_string[0]-ret_string[1];
memmove(&ret_string[0], &ret_string[2], sizeof(ret_string)-data_length);
if(sscanf(ret_string, "%lf", val_out) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read temperature!\n", ret_string);
return(1);
}
}
else if (strncmp(s_s->subtype, "pwout", 1) == 0) // Read out value for power (by controller)
{
sprintf(cmd_string, "P\r");
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
msleep(200);
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
// output in P\n<power>
int data_length = ret_string[0]-ret_string[0];
memmove(&ret_string[0], &ret_string[1], sizeof(ret_string)-data_length);
if(sscanf(ret_string, "%lf", val_out) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read temperature!\n", ret_string);
return(1);
}
}
else if (strncmp(s_s->subtype, "ttarget", 7) == 0) // Read out value for target temp
{
sprintf(cmd_string, "TTARGET\r");
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
msleep(200);
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
// output in TTARGET\n<power>
int data_length = ret_string[0]-ret_string[6];
memmove(&ret_string[0], &ret_string[7], sizeof(ret_string)-data_length);
if(sscanf(ret_string, "%lf", val_out) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read temperature!\n", ret_string);
return(1);
}
}
else if (strncmp(s_s->subtype, "treject", 7) == 0) // Read out value for target temp
{
sprintf(cmd_string, "TEMP RJ\r");
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
msleep(200);
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
// output in TTARGET\n<power>
int data_length = ret_string[0]-ret_string[6];
memmove(&ret_string[0], &ret_string[7], sizeof(ret_string)-data_length);
if(sscanf(ret_string, "%lf", val_out) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read temperature!\n", ret_string);
return(1);
}
}
else // Print an error if invalid subtype is entered
{
fprintf(stderr, "Wrong type for %s \n", s_s->name);
return(1);
}
msleep(600);
return(0);
}
#define _def_set_sensor
int set_sensor(struct inst_struct *i_s, struct sensor_struct *s_s)
{
char cmd_string[64];
char ret_string[64];
double ret_val;
if (strncmp(s_s->subtype, "setttarget", 10) == 0) // Set the target temp
{
sprintf(cmd_string, "TTARGET=%f\r", s_s->new_set_val);
write_tcp(inst_dev, cmd_string, strlen(cmd_string));
sleep(1);
sprintf(cmd_string, "TTARGET\r"); //queries set target temp
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
msleep(200);
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
// output in TTARGET\n<power>
int data_length = ret_string[0]-ret_string[6];
memmove(&ret_string[0], &ret_string[7], sizeof(ret_string)-data_length);
if(sscanf(ret_string, "%lf", &ret_val) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read set target temp!\n", ret_string);
return(1);
}
if (s_s->new_set_val != 0)
if (fabs(ret_val - s_s->new_set_val)/s_s->new_set_val > 0.1)
{
fprintf(stderr, "New set target temp of: %f is not equal to read out value of %f\n", s_s->new_set_val, ret_val);
return(1);
}
if(sscanf(ret_string, "%lf", &ret_val) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read set target temp!\n", ret_string);
return(1);
}
}
else if (strncmp(s_s->subtype, "setpwout", 8) == 0) // Set output cooling power
{
sprintf(cmd_string, "PWOUT=%f\r", s_s->new_set_val);
write_tcp(inst_dev, cmd_string, strlen(cmd_string));
sleep(1);
sprintf(cmd_string, "PWOUT\r"); //queries set cooling power
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
msleep(200);
query_tcp(inst_dev, cmd_string, strlen(cmd_string), ret_string, sizeof(ret_string)/sizeof(char));
// output in PWOUT\n<power>
int data_length = ret_string[0]-ret_string[4];
memmove(&ret_string[0], &ret_string[5], sizeof(ret_string)-data_length);
if(sscanf(ret_string, "%lf", &ret_val) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read set cooling power!\n", ret_string);
return(1);
}
if (s_s->new_set_val != 0)
if (fabs(ret_val - s_s->new_set_val)/s_s->new_set_val > 0.1)
{
fprintf(stderr, "New set cooling power of: %f is not equal to read out value of %f\n", s_s->new_set_val, ret_val);
return(1);
}
if(sscanf(ret_string, "%lf", &ret_val) != 1)
{
fprintf(stderr, "Bad return string: \"%s\" in read set cooling power!\n", ret_string);
return(1);
}
}
else if (strncmp(s_s->subtype, "setcooler", 9) == 0) // Set the control mode
{
if (s_s->num < 0 || s_s->num > 2) // Checks correct Loop number
{
fprintf(stderr, "%d is an incorrect value for num. Must be 0, 1, or 2. \n", s_s->num);
return(1);
}
if ((int)s_s->new_set_val == 0) sprintf(cmd_string, "COOLER=OFF\r");
else if ((int)s_s->new_set_val == 1) sprintf(cmd_string, "COOLER=ON\r");
else if ((int)s_s->new_set_val == 2) sprintf(cmd_string, "COOLER=POWER\r");
write_tcp(inst_dev, cmd_string, strlen(cmd_string));
sleep(1);
// no check if it returns right value, more complicated because not constant size string
}
else // Print an error if invalid subtype is entered
{
fprintf(stderr, "Wrong type for %s \n", s_s->name);
return(1);
}
return(0);
}
#include "main.h"
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <mbx.h>
MBX_Handle MBX_create(int number)
{
MBX_Handle handle;
handle = (MBX_Handle)malloc(sizeof(MBX_Obj));
pthread_mutex_init(&(handle->lock),NULL);
pthread_cond_init(&(handle->cond),NULL);
handle->buf = malloc(number * sizeof(SUB_MBX_Handle));
handle->wpos = 0;
handle->rpos = 0;
handle->cnt = 0;
handle->number = number;
return handle;
}
void MBX_delete(MBX_Handle handle)
{
pthread_mutex_destroy(&(handle->lock));
pthread_cond_destroy(&(handle->cond));
if(handle->buf != NULL)
{
free(handle->buf);
}
free(handle);
}
void MBX_post(MBX_Handle handle, void *value, int sz)
{
pthread_mutex_lock(&(handle->lock));
if(handle->cnt != handle->number)
{
handle->buf[handle->wpos] = (SUB_MBX_Handle)malloc(sizeof(SUB_MBX_Obj));
handle->buf[handle->wpos]->buf = (unsigned char*)malloc(sz);
memcpy(handle->buf[handle->wpos]->buf, value, sz);
handle->buf[handle->wpos]->size = sz;
handle->wpos = (handle->wpos + 1) % handle->number;
if(handle->cnt == 0)
{
pthread_cond_signal(&(handle->cond));
}
handle->cnt ++;
}
pthread_mutex_unlock(&(handle->lock));
}
void MBX_pend(MBX_Handle handle,void *value)
{
pthread_mutex_lock(&(handle->lock));
if(handle->cnt == 0)
{
pthread_cond_wait(&(handle->cond),&(handle->lock));
}
handle->cnt --;
memcpy(value, handle->buf[handle->rpos]->buf, handle->buf[handle->rpos]->size);
free(handle->buf[handle->rpos]->buf);
free(handle->buf[handle->rpos]);
handle->rpos = (handle->rpos + 1) % handle->number;
pthread_mutex_unlock(&(handle->lock));
}
|
C
|
/*
* 4_1_pwd.c
* this is the file base on <understanding Unix/Linux Programing> P97
* based on the commander: pwd
* useage: pwd
* 2012-12-02 [email protected]
*/
#include<errno.h> // perror(); errno,
#include<stdio.h> // printf();
#include<stdlib.h> // exit();
#include<string.h> // strcpy();
#include<dirent.h> // readdir();
#include<sys/types.h>
#include<sys/stat.h> //stat(); get the files info
#include<unistd.h> // chdir();
extern int errno; //define in "/usr/include/errno.h"
int oops( char *string1, char *string2 );
void path_to_inode( char *path, ino_t *p_inode );
void inode_to_dir( ino_t * p_inode );
int main( int argc, char *argv[] )
{
ino_t inode;
printf("\n******************************************************\n");
printf(" pwd commander will print user current dir path\n");
printf(" useage: 4_1_pwd.o \n\n" );
path_to_inode( ".", &inode );
inode_to_dir( &inode );
printf("\n\n");
/*
is_root_dir = inode_to_dir( &inode, path_name );
while( is_root_dir != 2 )
{
if( chdir("..") == -1 )
oops("can not change directory","");
path_to_inode( ".", &inode );
is_root_dir = inode_to_dir( &inode, path_name );
}
*/
return 1;
}
//=========================================================
// from dir path to get inode number
// the dir path is unkonwn, so path always is "."
void path_to_inode( char *path, ino_t * p_inode )
{
struct stat stat_buf;
//stat_buf = NULL;
if( path == NULL )
oops("input dir path is null","");
if( ( stat(path, &stat_buf) ) ==-1 )
oops("can not get struct stat form dir path","");
else
{
// printf("stat inode is %d\n", stat_buf.st_ino );
*p_inode = stat_buf.st_ino;
// printf("get current dir's inode is %d\n", (int)*p_inode );
}
}
//==========================================================
// from inod to get the directory's path name
// if this dir is root dir, return 2, otherwise return 1;
void inode_to_dir( ino_t * p_inode)
{
DIR *dirp;
struct dirent *dirent;
ino_t current_inode, parent_inode;
ino_t inode;
char name[256];
current_inode = 0;
parent_inode = 0;
if( (dirp=opendir( ".." )) == NULL )
oops("can not open dir","");
while( ( dirent=readdir( dirp )) != NULL )
{
if( strcmp( dirent->d_name, "." ) == 0 )
current_inode = dirent->d_ino;
if( strcmp( dirent->d_name, "..") == 0)
parent_inode = dirent->d_ino;
if( dirent->d_ino == *p_inode )
{
//printf("[CAUTION!]success get current dir name:%s\n",
// dirent->d_name );
strcpy( name, dirent->d_name);
//path_name = dirent->d_name;
//printf(" name= %s, path_name=%s \n", name, path_name );
}
}
if( (closedir( dirp ) == -1) )
oops("can not close dir","");
if( current_inode != parent_inode )
{
if( chdir("..") == -1 )
oops("can not change directory","");
path_to_inode( ".", &inode );
inode_to_dir( &inode );
}
printf("/%s", name );
}
/*
int inode_to_dir( ino_t * p_inode, char *path_name)
{
DIR *dirp;
struct dirent *dirent;
ino_t current_inode, parent_inode;
current_inode = 0;
parent_inode = 0;
if( (dirp=opendir( ".." )) == NULL )
oops("can not open dir","");
while( ( dirent=readdir( dirp )) != NULL )
{
//printf("inode:%-8d, type:%2d, name:%.12s \n",
// (int)dirent->d_ino, dirent->d_type, dirent->d_name );
//if( dirent->d_name == "." )
if( strcmp( dirent->d_name, "." ) == 0 )
current_inode = dirent->d_ino;
//if( dirent->d_name == ".." )
if( strcmp( dirent->d_name, "..") == 0)
parent_inode = dirent->d_ino;
if( dirent->d_ino == *p_inode )
printf("[CAUTION!]success get current dir name:%s\n",
dirent->d_name );
}
//printf(" inode is %d\n", (int)*p_inode );
if( (closedir( dirp ) == -1) )
oops("can not close dir","");
//printf("current_inode=%d, parent_inode=%d \n",
// current_inode, parent_inode);
if( current_inode == parent_inode && current_inode != 0)
return 2;
else
return 1;
}
*/
//=========================================================
// error determin function
// string1: error operation,as "can not open file"...
// string2: error reason, as"No such file"
int oops( char *string1, char *string2 )
{
//as printf() is to write output to stdout
//fprintf() is to write output to the given output stream
fprintf( stderr, "Error: %s ; ", string1 );
perror( string2 );
exit(1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
static void
dump_regs_and_stack()
{
int i;
register int eax asm("eax");
register int ebx asm("ebx");
register int ecx asm("ecx");
register int edx asm("edx");
register int esp asm("esp");
register int ebp asm("ebp");
register int esi asm("esi");
register int edi asm("edi");
printf("Registers:\n");
printf(" | EAX: 0x%x | EBX: 0x%x | ECX: 0x%x | EDX: 0x%x |\n",
eax, ebx, ecx, edx);
printf(" | ESI: 0x%x | EDI: 0x%x | ESP: 0x%x | EDI: 0x%x|\n",
esi, edi, esp, ebp);
printf("Stack trace:\n");
for (i = esp-16; i < esp; i++) {
printf("[0x%x] 0x%x\n", i, (int)(((int *)i)[0]));
}
}
/**
* This function is not ment to be directly called.
* Nothing prevents you from doing so though.
*/
__attribute__((__noreturn__))
void
__panic(char *msg, char *file, int line)
{
printf("*** kernel panic: %s\n", msg);
printf(" at line: %d\n", line);
printf(" in file: %s\n", file);
printf("stack trace:\n");
dump_regs_and_stack();
while (1) { }
__builtin_unreachable();
}
__attribute__((__noreturn__))
void
abort(void)
{
printf("abort()\n");
while (1) { }
__builtin_unreachable();
}
|
C
|
#include<stdio.h>
#define Max_N 200001
int N;
long int A[Max_N];
int M;
long int B[Max_N];
long int Lvl[Max_N];
int L;
long int Max, Min;
void readCase() {
int i;
int j = 0;
L = 0;
int temp;
Max = 0;
Min = 1000000000;
scanf("%d", &N);
for (i = 0; i < N; i++) {
scanf("%ld", &A[i]);
if (A[i] > Max) {
Max = A[i];
}
if (A[i] < Min) {
Min = A[i];
}
temp = A[i];
if (i > 0 && temp != Lvl[j]) {
j++;
L++;
Lvl[j] = temp;
}
if (i == 0) {
Lvl[j] = temp;
}
}
scanf("%d", &M);
for (i = 0; i < M; i++) {
scanf("%ld", &B[i]);
}
}
void solveCase() {
int i, j;
int k;
for (i = 0; i < M; i++) {
k = 0;
for (j = L; j >= 0; j--) {
if (B[i] >= Max) {
printf("1\n");
break;
}
if (B[i] <= Min) {
printf("%d\n", L+2);
break;
}
if (B[i] < Lvl[j]) {
printf("%d\n", j + 2);
break;
}
}
}
}
void printCase() {
int i;
for (i = 0; i <= L; i++) {
printf("%ld ", Lvl[i]);
}
}
int main() {
readCase();
solveCase();
//printCase();
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int n,f=0;
clrscr();
scanf("%d",&n);
while(n%2!=0)
{
if(n%2==0)
{
f=1;
break;
}
}
if(f==1)
{
printf("yes");
}
else
{
printf("no");
}
getch();
}
|
C
|
#include <stdio.h>
#define PSQR(x) printf("The square of " #x " is %d.\n", ((x)*(x)))
int main(void)
{
int y = 5;
PSQR(y); //printf("The square of " "y" "is %d.\n", (y*y));
PSQR(2+4); //printf("The square of " "2 + 4" "is %d.\n",((2+4)*(2+4)));
return 0;
}
|
C
|
// shop.c
inherit F_CLEAN_UP;
#include <ansi.h>
int help(object me);
int main(object me, string arg)
{
string name, id;
seteuid(getuid());
if (! arg)
{
SHOP_D->list_shop(me);
return 1;
}
if (! wizardp(me))
return notify_fail("你没有权力使用店铺管理指令。\n");
switch (arg)
{
case "all" : SHOP_D->do_listall(me); break;
case "open" : SHOP_D->open_all(me); break;
case "close" : SHOP_D->close_all(me); break;
case "reset" : SHOP_D->reset_all(me); break;
default :
if (sscanf(arg, "open %s", name))
{
SHOP_D->open_shop(me, name);
break;
}
if (sscanf(arg, "close %s", name))
{
SHOP_D->close_shop(me, name);
break;
}
if (sscanf(arg, "reset %s", name))
{
SHOP_D->reset_shop(me, name);
break;
}
if (sscanf(arg, "owner %s %s", name, id))
{
SHOP_D->change_owner(me, name, id);
break;
}
else return help(me);
}
return 1;
}
int help (object me)
{
write(@HELP
指令格式:shop [ open [店铺名称] ] | [ close [店铺名称] ] |
[ reset [店铺名称] ] | [ owner <店铺名称> <店主ID> ]
[ all ]
玩家查看当前游戏中的店铺经营状况。
巫师可以用于管理店铺:
使用 open 参数开放指定的一个店铺或者所有店铺。
使用 close 参数将关闭指定的一个店铺或者所有店铺。
使用 reset 参数重新初始化指定的一个店铺或者所有店铺。
而使用owner 参数则是设置店主的 id。
使用 all 则显示所有商店货物。
HELP);
return 1;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my_hunter
** File description:
** mathstick
*/
#include "../../include/my.h"
void add_bn_at_end(char *str)
{
str[my_strlen(str)] = '\n';
str[my_strlen(str) + 1] = '\0';
}
int exec_with_text(info_shell_t *sh, linked_list_t *list_env, char *text)
{
pid_t pid = fork();
int ret;
int tmp[2];
pipe(tmp);
my_putstr_redir(text, tmp);
if (pid == -1)
perror("fork");
else if (pid == 0) {
dup2(tmp[0], 0);
close(tmp[1]);
case_others(sh, list_env);
exit (0);
} else {
close(tmp[0]);
close(tmp[1]);
my_wait(&pid);
}
}
int check_error_dleft(info_shell_t *sh, char *fp, char ** tab)
{
if (my_strcmp(fp, "no command") == 0) {
my_putstr("Invalid null command.\n");
return (0);
}
sh->tab = my_str_to_word_array(tab[0], ' ');
if (fp == NULL) {
my_puter("Missing name for redirect.\n");
return (0);
}
return (1);
}
int case_dredir_left(info_shell_t *sh, linked_list_t *list_env)
{
char **tab = my_str_to_word_array(sh->command, '<');
char *fp = search_fp(sh->command, '<');
char *text = NULL;
char *str;
if (check_error_dleft(sh, fp, tab) == 0)
return (0);
if ((str = get_next_line(0)) == NULL)
return (0);
while (my_strcmp(fp, str) != 0) {
if (text == NULL)
text = str;
else
text = my_strcat_bn(text, str);
if ((str = get_next_line(0)) == NULL)
return (0);
}
add_bn_at_end(text);
exec_with_text(sh, list_env, text);
return (1);
}
|
C
|
#include <unistd.h>
#include <stdio.h>
// unsigned char reverse_bits(unsigned char octet)
// {
// int i;
// int r;
// i = 0;
// r = 0;
// while (i < 8)
// {
// r |= (((octet >> i) & 1)) << (7 - i);
// i++;
// }
// return (r);
// }
unsigned char reverse_bits(unsigned char octet)
{
return (((octet >> 0) & 1) << 7) | \
(((octet >> 1) & 1) << 6) | \
(((octet >> 2) & 1) << 5) | \
(((octet >> 3) & 1) << 4) | \
(((octet >> 4) & 1) << 3) | \
(((octet >> 5) & 1) << 2) | \
(((octet >> 6) & 1) << 1) | \
(((octet >> 7) & 1) << 0);
}
unsigned char print_bits(unsigned char octet)
{
int i = 128;
while (i)
{
(octet & i) ? write(1, "1", 1) : write(1, "0", 1);
i = i / 2;
}
write(1, "\n", 1);
return (0);
}
int main()
{
unsigned char c,d;
unsigned char octet = 3;
unsigned char octet2 = 'a';
c = reverse_bits(octet);
printf("%c %c %d\n %d\n ", print_bits(octet), print_bits(c), octet, reverse_bits(octet));
return 0;
}
//int main(void)
//{
// unsigned char c;
//
// c = '.';
// write(1, &c, 1);
// write(1, "\n", 1);
// c = reverse_bits(c);
// write(1, &c, 1);
// write(1, "\n", 1);
//// c = reverse_bits2(c);
//// write(1, &c, 1);
//// write(1, "\n", 1);
//// c = reverse_bits3(c);
//// write(1, &c, 1);
//// write(1, "\n", 1);
// return (0);
//}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "reply.h"
#include "channels.h"
#include "structs.h"
#include "functions.h"
#include "handlers.h"
#include "list.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
/* The strategy for the I/O of handlers:
take in message that is complete & split into three parts
* the parts will be split into a command, a value and a message
* all three will be stored in the cmdValueStruct, typedef'd to cmdValueStruct
- so just leave off the "struct" when declaring an instance
also input connection information, specifically three items:
* hostname, that is, where the server main is
* clientIP, the ipaddress of the target client
- may or may not be used, depending on type of message
* clientSocket, where the client is connected
when a response is needed, for example for RPL_WELCOME,
* info from USER and NICK is passed into a USERstruct
- use messageInfo struct to pass data internally
* when both USER and NICK are decided, reply_to_one recieves
- a messageInfoStruct with NICK and USER, and
- a connectionStruct with connection info
every handler will pass off its data to a function, and then will return an integer
* positive if successful (maybe zero?)
* negative if failure
*/
int handle_NICK(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char *newNick = (cmdValueInstance.value ? cmdValueInstance.value : "");
printf("handling nick:%s\n",newNick);
if (!strcmp(newNick,""))
{
messageInfoStruct messageInfo = {"431","* :No nickname given"};
int returnval = reply_to_one(messageInfo, userInfo);
return returnval;
}
// If the nickname is present already
if (is_nick_present(userList, newNick))
{
printf("nickname in use!\n");
char msg[128];
snprintf(msg, 128, "%s :Nickname is already in use",newNick);
messageInfoStruct messageInfo = {ERR_NICKNAMEINUSE, msg};
int returnval = reply_to_one(messageInfo, userInfo);
return returnval;
}
// if the user is changing their nickname,,,
if(userInfo->nick != "")
{
char msg[128];
snprintf(msg, 128, ":%s!%s@%s NICK :%s",userInfo->nick, userInfo->username, userInfo->clientIP, newNick);
messageInfoStruct messageInfo = {"NICK", msg};
int returnval = reply_to_all(messageInfo, userInfo, userInfo->userChannels);
}
// because userInfo is passed in, we know that the socket is connected to a user and that the user wants a new nick.
userInfo->nick = strdup(newNick);
// If they haven't been welcomed
// and if the user's nick isn't blank
// and if the user's username isn't blank
if ((userInfo->welcomed) == 0 && strcmp((userInfo->nick),"") && strcmp((userInfo->username),"") )
{
//greet the user with the 4 required messages (done in user_connected)
int returnval = handle_internal_WELCOME(cmdValueInstance, userInfo, userList);
return returnval;
}
return 0;
}
int handle_USER(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char *newUser = (cmdValueInstance.value ? cmdValueInstance.value : "");
char *fullName = (cmdValueInstance.message ? cmdValueInstance.message : "");
int welcomed = userInfo->welcomed;
printf("handling USER: %s\n",newUser);
if (!strcmp(newUser,""))
{
messageInfoStruct messageInfo = {ERR_NEEDMOREPARAMS,"* USER :Not enough parameters"};
int returnval = reply_to_one(messageInfo, userInfo);
return returnval;
}
// What does the * * : mean? I have no idea. but it's necessary.
//begin full name requirement
char *saveptr;
char* stars = "* * ";
char* tryStars = strtok_r(fullName, ":", &saveptr);
char* trueFullName = strtok_r(NULL, "", &saveptr);
// if the fullname is not given
// or if try stars != "* * "
if(!strcmp(fullName,"") || strcmp(tryStars, stars))
{
messageInfoStruct messageInfo = {ERR_NEEDMOREPARAMS,"USER :Not enough parameters"};
int returnval = reply_to_one(messageInfo, userInfo);
return returnval;
}
userInfo->fullName = strdup(trueFullName);
// end fullname requirement
printf("handling user:%s\n",newUser);
// if the username is present already, or if the user already has a username
if (is_username_present(userList, newUser) || strcmp(userInfo->username,""))
{
messageInfoStruct messageInfo = {ERR_ALREADYREGISTRED,"Unauthorized command (already registered)"};
int returnval = reply_to_one(messageInfo, userInfo);
return returnval;
}
// because userInfo is passed in, we know that the socket is connected to a user.
// by the above if, it would be impossible to change your username using this (you would already have returned).
userInfo->username = strdup(newUser);
// If the user hasn't seen the welcome message and both their nick and username are not \0, welcome them.
if (welcomed == 0 && strcmp(userInfo->nick, "") && strcmp(userInfo->username,"") )
{
int returnval = handle_internal_WELCOME(cmdValueInstance, userInfo, userList);
return returnval;
}
return 0;
}
// what to send once NICK and USER have been recieved
// This used to be in functions, but it really is more like a handler that is called by our own code.
// Therefore it will live here, but won't be included in the dispatch table.
int handle_internal_WELCOME(cmdValueStruct cmdValueInstance,user* userInfo,list* userList)
{
char *clientIP = userInfo->clientIP;
char *hostname = userInfo->hostname;
char *nick = userInfo->nick;
char *username = userInfo->username;
char* version = "chirc-6.6.6"; //user defined?
time_t mytime;
struct tm *timeinfo;
time(&mytime);
timeinfo = localtime(&mytime);
char* server_time = asctime(timeinfo);
// RPL_WELCOME
char msg1[128];
snprintf(msg1, 128, ":Welcome to the Internet Relay Network %s!%s@%s",nick,username,clientIP);
messageInfoStruct messageInfo1 = {RPL_WELCOME, msg1};
int returnval = reply_to_one(messageInfo1,userInfo);
// RPL_YOURHOST
char msg2[128];
snprintf(msg2, 128, ":Your host is %s, running version %s",hostname,version);
messageInfoStruct messageInfo2 = {RPL_YOURHOST, msg2};
returnval += reply_to_one(messageInfo2,userInfo);
//RPL_CREATED
char msg3[128];
snprintf(msg3, 128, ":This server was created %s",server_time);
messageInfoStruct messageInfo3 = {RPL_CREATED, msg3};
returnval += reply_to_one(messageInfo3,userInfo);
//RPL_MYINFO
char msg4[128];
snprintf(msg4, 128, "%s %s ao mtov",hostname,version);
messageInfoStruct messageInfo4 = {RPL_MYINFO, msg4};
returnval += reply_to_one(messageInfo4,userInfo);
userInfo->welcomed = 1;
returnval += handle_LUSERS(cmdValueInstance,userInfo,userList);
returnval += handle_MOTD(cmdValueInstance,userInfo,userList);
return returnval;
}
int handle_QUIT(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
printf("handling QUIT from: %s",userInfo->nick);
char *clientMsg = (cmdValueInstance.message ? cmdValueInstance.message : "");
char *value = (cmdValueInstance.value ? cmdValueInstance.value : "Client Quit");
char msg[512];
snprintf(msg, 512, ":%s!%s@%s QUIT %s%s%s%s",userInfo->nick,userInfo->username,userInfo->clientIP,(value[0]==':' ? "" : ":"),value,(clientMsg ? " " : ""),clientMsg);
//char msg[128];
//snprintf(msg, 128, "Closing Link: %s (%s %s)",hostname,value,clientMsg);
messageInfoStruct messageInfo = {"QUIT", msg};
int returnval = reply_to_one(messageInfo, userInfo);
returnval += reply_to_all(messageInfo, userInfo, userInfo->userChannels);
leave_all_channels(userInfo->userChannels, userInfo);
leave_all_channels(global_channel_clist, userInfo);
remove_from_list(userList, userInfo);
close(userInfo->clientSocket);
pthread_exit(NULL);
return returnval;
}
int handle_PRIVMSG(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char *targetNick = cmdValueInstance.value;
printf("handling PRIVMSG from %s to %s\n",userInfo->nick, targetNick);
char *message = cmdValueInstance.message;
int returnval = 0;
channel* targetChannel = NULL;
char *targetCname = strdup(targetNick);
user* targetUser = NULL;
char msg[1023];
messageInfoStruct messageInfo = {"", ""};
// if they're sending the message to a channel
if (targetNick[0] == '#' || targetNick[0] == '&' || targetNick[0] == '!' || targetNick[0] == '+')
{
channel *targetUserChannel = fetch_channel_by_cname(userInfo->userChannels, targetCname);
channel *targetGlobalChannel = fetch_channel_by_cname(global_channel_clist, targetCname);
// If there is no channel wwith the given cName
if (!is_cname_present(global_channel_clist, targetCname))
{
snprintf(msg, 1023, "%s :No such nick/channel",targetCname);
messageInfo.messageType = ERR_NOSUCHNICK;
messageInfo.messageContents = msg;
targetUser = userInfo;
returnval += reply_to_one(messageInfo,targetUser);
}
// If the user is trying to send a message to a channel they're not connected to
else if ((!is_cname_present(userInfo->userChannels, targetCname)) || (!is_char_present(targetUserChannel->umode,'v') && is_char_present(targetGlobalChannel->cmode,'m') && (!is_char_present(targetUserChannel->umode,'o') && userInfo->mode !='o')))
{
snprintf(msg, 1023, "%s :Cannot send to channel",targetCname);
messageInfo.messageType = ERR_CANNOTSENDTOCHAN;
messageInfo.messageContents = msg;
targetUser = userInfo;
returnval += reply_to_one(messageInfo,targetUser);
}
else
{
char hostname[128];
snprintf(hostname, 128, ":%s!%s@%s",userInfo->nick,userInfo->username,userInfo->clientIP);
targetChannel = fetch_channel_by_cname(userInfo->userChannels, targetCname);
snprintf(msg, 1023, "%s %s %s %s",hostname, "PRIVMSG", targetCname, message);
messageInfo.messageType = "PRIVMSG";
messageInfo.messageContents = msg;
returnval += reply_to_channel(messageInfo,userInfo,targetChannel);
}
return returnval;
}
else
{
// If there are no users or if the username is not present
if (is_empty(userList) || !(is_nick_present(userList, targetNick)))
{
snprintf(msg, 1023, "%s :No such nick/channel",targetNick);
messageInfo.messageType = ERR_NOSUCHNICK;
messageInfo.messageContents = msg;
targetUser = userInfo;
}
else
{
char hostname[128];
snprintf(hostname, 128, ":%s!%s@%s",userInfo->nick,userInfo->username,userInfo->clientIP);
targetUser = fetch_user_by_nick(userList, targetNick);
snprintf(msg, 1023, "%s %s %s %s",hostname, "PRIVMSG", targetNick, message);
messageInfo.messageType = "PRIVMSG";
messageInfo.messageContents = msg;
}
int returnval = reply_to_one(messageInfo, targetUser);
// RPL_AWAY
if(targetUser->mode == 'a') {
char msg2[1023];
snprintf(msg2, 1023, "%s %s", targetUser->nick, targetUser->away_message);
messageInfo.messageType = RPL_AWAY;
messageInfo.messageContents = msg2;
returnval += reply_to_one(messageInfo, userInfo);
}
return returnval;
}
}
int handle_NOTICE(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
printf("handling NOTICE from %s\n",userInfo->nick);
// I think this is the functionality of NOTICE... there was very little documentation on how it should work
char *targetNick = cmdValueInstance.value;
char *message = cmdValueInstance.message;
int returnval = 0;
channel* targetChannel = NULL;
char *targetCname = strdup(targetNick);
user* targetUser = NULL;
char msg[1023];
messageInfoStruct messageInfo = {"", ""};
if (targetNick[0] == '#' || targetNick[0] == '&' || targetNick[0] == '!' || targetNick[0] == '+')
{
if (!is_cname_present(global_channel_clist, targetCname) || !is_cname_present(userInfo->userChannels, targetCname))
return 1;
else
{
char hostname[128];
snprintf(hostname, 128, ":%s!%s@%s",userInfo->nick,userInfo->username,userInfo->clientIP);
targetChannel = fetch_channel_by_cname(userInfo->userChannels, targetCname);
snprintf(msg, 1023, "%s %s %s %s",hostname, "NOTICE", targetCname, message);
messageInfo.messageType = "NOTICE";
messageInfo.messageContents = msg;
returnval += reply_to_channel(messageInfo,userInfo,targetChannel);
}
return returnval;
}
else
{
if (is_empty(userList) || !(is_nick_present(userList, targetNick)))
{
return 1;
}
else
{
char hostname[128];
snprintf(hostname, 128, ":%s!%s@%s",userInfo->nick,userInfo->username,userInfo->clientIP);
targetUser = fetch_user_by_nick(userList, targetNick);
snprintf(msg, 1023, "%s %s %s %s",hostname, "NOTICE", targetNick, message);
messageInfo.messageType = "NOTICE";
messageInfo.messageContents = msg;
}
returnval += reply_to_one(messageInfo, targetUser);
return returnval;
}
}
int handle_PING(cmdValueStruct cmdValueInstance, user* userInfo, list* l)
{
char msg[128];
snprintf(msg,128,"PONG %s",userInfo->hostname);
int clientSocket = userInfo->clientSocket;
send(clientSocket, msg, strlen(msg), 0);
return 1;
}
int handle_PONG(cmdValueStruct cmdValueInstance, user* userInfo, list* l)
{
printf("pong received");
return 1;
}
int handle_MOTD(cmdValueStruct cmdValueInstance, user* userInfo, list* l)
{
char msg[1023];
messageInfoStruct messageInfoh = {"",""}; //header
messageInfoStruct messageInfo = {"",""};
messageInfoStruct messageInfof = {"",""}; //footer
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("motd.txt", "r");
if (fp == NULL)
{
snprintf(msg, 1023, ":MOTD File is missing");
messageInfo.messageType = ERR_NOMOTD;
messageInfo.messageContents = msg;
reply_to_one(messageInfo,userInfo);
return 1;
}
else
{
char header[128];
snprintf(header,128,":- %s Message of the day - ",userInfo->hostname);
messageInfoh.messageType = RPL_MOTDSTART;
messageInfoh.messageContents = header;
reply_to_one(messageInfoh,userInfo);
while ((read = getline(&line, &len, fp)) != -1) {
snprintf(msg, 512, ":- %s",line);
messageInfo.messageType = RPL_MOTD;
messageInfo.messageContents = msg;
reply_to_one(messageInfo,userInfo);
}
char footer[128];
snprintf(footer,128,":End of MOTD command");
messageInfof.messageType = RPL_ENDOFMOTD;
messageInfof.messageContents = footer;
reply_to_one(messageInfof,userInfo);
if (line)
free(line);
return 1;
}
}
int handle_LUSERS(cmdValueStruct cmdValueInstance, user* userInfo, list* l)
{
int knownUsers = 0;
int unknownUsers = 0;
int services = 0;
int servers = 1;
int channels = 0;
node *iter = l->head;
// if empty list, userstats stay at 0. this shouldn't happen ever though.
// iterate through list to find the user location
while (iter != NULL)
{
// welcomed is the attribute of choice for this function - if the user is fully registered,
// with a username and nickname, welcomed is automatically tripped to 1. If not, it's defaulted to 0.
if (iter->user->welcomed == 0)
unknownUsers += 1;
else if (iter->user->welcomed == 1)
knownUsers += 1;
iter = iter->next;
}
// RPL_LUSERCLIENT
char msg1[128];
messageInfoStruct messageInfo1 = {"", ""};
snprintf(msg1, 128, ":There are %d users and %d services on %d servers",knownUsers,services,servers);
messageInfo1.messageType = RPL_LUSERCLIENT;
messageInfo1.messageContents = msg1;
int returnval = reply_to_one(messageInfo1, userInfo);
// RPL_LUSEROP
char msg2[128];
messageInfoStruct messageInfo2 = {"", ""};
snprintf(msg2, 128, "0 :operator(s) online");
messageInfo2.messageType = RPL_LUSEROP;
messageInfo2.messageContents = msg2;
returnval += reply_to_one(messageInfo2, userInfo);
// RPL_LUSERUNKNOWN
char msg3[128];
messageInfoStruct messageInfo3 = {"", ""};
snprintf(msg3, 128, "%d :unknown connection(s)",unknownUsers);
messageInfo3.messageType = RPL_LUSERUNKNOWN;
messageInfo3.messageContents = msg3;
returnval += reply_to_one(messageInfo3, userInfo);
//RPL_LUSERCHANNELS
char msg4[128];
messageInfoStruct messageInfo4 = {"", ""};
snprintf(msg4, 128, "%d :channels formed",channels);
messageInfo4.messageType = RPL_LUSERCHANNELS;
messageInfo4.messageContents = msg4;
returnval += reply_to_one(messageInfo4, userInfo);
//RPL_LUSERME
char msg5[128];
messageInfoStruct messageInfo5 = {"", ""};
snprintf(msg5, 128, ":I have %d clients and %d servers",(knownUsers + unknownUsers), servers);
messageInfo5.messageType = RPL_LUSERME;
messageInfo5.messageContents = msg5;
returnval += reply_to_one(messageInfo5, userInfo);
return returnval;
}
int handle_WHOIS(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char *whoisNick = cmdValueInstance.value;
if (!(is_nick_present(userList, whoisNick)))
{
char msg1[128];
messageInfoStruct messageInfo1 = {"",""};
snprintf(msg1, 128, "%s :No such nick/channel",whoisNick);
messageInfo1.messageType = ERR_NOSUCHNICK;
messageInfo1.messageContents = msg1;
return reply_to_one(messageInfo1, userInfo);
}
else
{
user *myUser = fetch_user_by_nick(userList, whoisNick);
// RPL_WHOISUSER
char msg1[128];
messageInfoStruct messageInfo1 = {"",""};
snprintf(msg1, 128, "%s %s %s * :%s",myUser->nick,myUser->username,myUser->hostname,myUser->fullName);
messageInfo1.messageType = RPL_WHOISUSER;
messageInfo1.messageContents = msg1;
int returnval = reply_to_one(messageInfo1, userInfo);
// RPL_WHOISSERVER
char msg2[128];
messageInfoStruct messageInfo2 = {"",""};
snprintf(msg2, 128, "%s %s :this server sucks and i hate it.",myUser->nick,myUser->hostname);
messageInfo2.messageType = RPL_WHOISSERVER;
messageInfo2.messageContents = msg2;
returnval += reply_to_one(messageInfo2, userInfo);
// RPL_ENDOFWHOIS
char msg3[128];
messageInfoStruct messageInfo3 = {"", ""};
snprintf(msg3, 128, "%s :End of WHOIS list",myUser->nick);
messageInfo3.messageType = RPL_ENDOFWHOIS;
messageInfo3.messageContents = msg3;
returnval += reply_to_one(messageInfo3, userInfo);
return returnval;
}
}
int handle_UNKNOWN(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char msg[128];
messageInfoStruct messageInfo = {"",""};
snprintf(msg,128,"%s :Unknown command",cmdValueInstance.cmd);
messageInfo.messageType = ERR_UNKNOWNCOMMAND;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
//******* 1c *******//
int handle_JOIN(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char msg[1023];
printf("handling JOIN from %s\n",userInfo->nick);
// prob not gonna use this variable but I just feel better knowing
// add_new_channel is returning something and I can see it
channel *global_channel;
char *cname = (cmdValueInstance.value ? cmdValueInstance.value : "");
if(!strcmp(cname,""))
{
messageInfoStruct messageInfo = {"461","JOIN :Not enough parameters"};
int returnval = reply_to_one(messageInfo, userInfo);
return returnval;
}
int isnew= 0;
// if channel does not exist, create it
if(!is_cname_present(global_channel_clist, cname))
{
fprintf(stderr,"adding new channel to global channel list\n");
isnew = 1;
global_channel = add_new_channel(global_channel_clist, cname);
//userInfo->mode = 'o';
}
// if the user is already in this channel, just return silently
if(is_cname_present(userInfo->userChannels, cname))
return 0;
// ADDING NEW CHANNEL
// add user to global_channel_clist's user list
channel *userChannel = fetch_channel_by_cname(global_channel_clist, cname);
add_to_list(userChannel->userList, userInfo);
// add new channel to user's channel list
// and add user to that channel's user list
channel *newChannel = add_new_channel(userInfo->userChannels, cname);
// copy the list of users from the global channel list onto the user's own list
userInfo->userChannels->head->channel->userList = userChannel->userList;
userInfo->userChannels->head->channel->topic = userChannel->topic;
//if the channel was newly created, make the user an operator
if (isnew)
add_mode(userInfo->userChannels->head->channel->umode, 'o');
// JOIN MESSAGE
fprintf(stderr, "Sending JOIN messages\n");
char hostname[128];
snprintf(hostname, 128, ":%s!%s@%s",userInfo->nick,userInfo->username,userInfo->clientIP);
snprintf(msg, 1023, "%s %s %s", hostname, "JOIN", cname);
messageInfoStruct messageInfo = {"", ""};
messageInfo.messageType = "JOIN";
messageInfo.messageContents = msg;
int returnval = reply_to_one(messageInfo, userInfo);
returnval += reply_to_channel(messageInfo, userInfo, userChannel);
//RPL_TOPIC
// only send if the channel topic is not empty
if (!(!strcmp(newChannel->topic,"") || !strcmp(newChannel->topic,":")))
{
printf("RPL_TOPIC ON JOIN\n");
char msg1[512];
messageInfoStruct messageInfo1 = {"", ""};
snprintf(msg1, 512, "%s %s",newChannel->cname,newChannel->topic);
messageInfo1.messageType = RPL_TOPIC;
messageInfo1.messageContents = msg1;
returnval += reply_to_one(messageInfo1, userInfo);
}
//RPL_NAMREPLY
char msg2[1023];
messageInfoStruct messageInfo2 = {"", ""};
char *usersString = fetch_users(newChannel->userList);
snprintf(msg2, 1023, "= %s :%s",newChannel->cname, usersString);
messageInfo2.messageType = RPL_NAMREPLY;
messageInfo2.messageContents = msg2;
returnval += reply_to_one(messageInfo2, userInfo);
//RPL_ENDOFNAMES
char msg3[128];
messageInfoStruct messageInfo3 = {"", ""};
snprintf(msg3, 128, "%s :End of NAMES list",newChannel->cname);
messageInfo3.messageType = RPL_ENDOFNAMES;
messageInfo3.messageContents = msg3;
returnval += reply_to_one(messageInfo3, userInfo);
return 1;
}
// this only handles one channel at the minute, but the reference server only handles one...
int handle_PART(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
printf("handling PART from %s\n",userInfo->nick);
channel* targetChannel = NULL;
char msg[128];
messageInfoStruct messageInfo = {"",""};
char* targetCname = cmdValueInstance.value;
char* message = cmdValueInstance.message ? cmdValueInstance.message : "";
fprintf(stderr, "checking if the channel doesn't exist\n");
// if the channel doesn't exist
if (!is_cname_present(global_channel_clist,targetCname))
{
snprintf(msg,128,"%s :No such channel",targetCname);
messageInfo.messageType = ERR_NOSUCHCHANNEL;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_NOSUCHCHANNEL\n");
return reply_to_one(messageInfo, userInfo);
}
// if the channel does exist, but the user isn't connected
else if (!is_cname_present(userInfo->userChannels, targetCname))
{
fprintf(stderr, "checked that channel existed but user wasn't connected\n");
snprintf(msg,128,"%s :You're not on that channel",targetCname);
messageInfo.messageType = ERR_NOTONCHANNEL;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_NOTONCHANNEL\n");
return reply_to_one(messageInfo, userInfo);
}
// otherwise, if they're allowed to part, do it.
else
{
targetChannel = fetch_channel_by_cname(global_channel_clist, targetCname);
if (!strcmp(message,""))
snprintf(msg,128,":%s!%s@%s PART %s",userInfo->nick, userInfo->username, userInfo->clientIP, targetCname);
else
snprintf(msg,128,":%s!%s@%s PART %s %s",userInfo->nick, userInfo->username, userInfo->clientIP, targetCname, message);
messageInfo.messageType = "PART";
messageInfo.messageContents = msg;
int returnval = reply_to_channel(messageInfo, userInfo, targetChannel);
char* removing = remove_from_clist(userInfo->userChannels, targetChannel);
remove_from_list(targetChannel->userList, userInfo);
if (is_empty(targetChannel->userList))
{
printf("removing from global list\n");
remove_from_clist(global_channel_clist, targetChannel);
}
return returnval;
}
return 1;
}
int handle_TOPIC(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
printf("handling TOPIC from %s\n",userInfo->nick);
channel* targetChannel = NULL;
channel* targetUserChannel = NULL;
char msg[128];
messageInfoStruct messageInfo = {"",""};
char* targetCname = cmdValueInstance.value;
char* message = cmdValueInstance.message ? cmdValueInstance.message : "";
if (!is_cname_present(userInfo->userChannels, targetCname))
{
fprintf(stderr, "checked that channel existed but user wasn't connected\n");
snprintf(msg,128,"%s :You're not on that channel",targetCname);
messageInfo.messageType = ERR_NOTONCHANNEL;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_NOTONCHANNEL\n");
return reply_to_one(messageInfo, userInfo);
}
targetChannel = fetch_channel_by_cname(global_channel_clist,targetCname);
targetUserChannel = fetch_channel_by_cname(userInfo->userChannels,targetCname);
char* topic = targetChannel->topic ? targetChannel->topic : "";
// if they're changing the topic
if (message[0]==':')
{
// if they're not allowed
if(is_char_present(targetChannel->cmode,'t') && !is_char_present(targetUserChannel->umode,'o') && userInfo->mode != 'o')
{
snprintf(msg,128,"%s :You're not channel operator",targetCname);
messageInfo.messageType = ERR_CHANOPRIVSNEEDED;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_CHANOPRIVSNEEDED\n");
return reply_to_one(messageInfo, userInfo);
}
targetChannel->topic = strdup(message);
snprintf(msg,128,":%s!%s@%s TOPIC %s %s",userInfo->nick, userInfo->username, userInfo->clientIP, targetCname, targetChannel->topic);
messageInfo.messageType = "TOPIC";
messageInfo.messageContents = msg;
return reply_to_channel(messageInfo, userInfo, targetChannel);
}
// if they just want to read the topic
else
{
if (!strcmp(topic,"") || !strcmp(topic,":"))
{
snprintf(msg,128,"%s :No topic is set",targetCname);
messageInfo.messageType = RPL_NOTOPIC;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
else
{
messageInfo.messageType = RPL_TOPIC;
snprintf(msg,128,"%s %s",targetCname, targetChannel->topic);
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
}
return 1;
}
int handle_OPER(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
printf("handling OPER from %s\n",userInfo->nick);
char msg[128];
messageInfoStruct messageInfo = {"",""};
char* name = cmdValueInstance.value;
char* trypassword = cmdValueInstance.message ? cmdValueInstance.message : "";
if(strcmp(trypassword, userInfo->password))
{
snprintf(msg,128,":Password incorrect");
messageInfo.messageType = ERR_PASSWDMISMATCH;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
userInfo->mode = 'o';
snprintf(msg,128,":You are now an IRC operator");
messageInfo.messageType = RPL_YOUREOPER;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
int handle_MODE(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
/*
This is the deal.
OPER makes users operators on the server. this fact is stored in userInfo->mode
channel modes (cMODE)s are stored in global_channel_clist->node->channel->cmode
ex. moderated or not
global_channels_clist->node->channel->umode should be empty
user modes (uModes) are stored in userInfo->userChannels->node->channel->umode
ex. voice privilages
userInfo->userChannels->node->channel->cmode should be empty
*/
printf("handling MODE from %s\n",userInfo->nick);
char msg[128];
messageInfoStruct messageInfo = {"",""};
char *target = cmdValueInstance.value;
char *modeflags = cmdValueInstance.message ? cmdValueInstance.message : "";
if(target[0]=='#')
{
if (!is_cname_present(global_channel_clist, target))
{
snprintf(msg,128,"%s :No such channel",target);
messageInfo.messageType = ERR_NOSUCHCHANNEL;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_NOSUCHCHANNEL\n");
return reply_to_one(messageInfo, userInfo);
}
channel *targetGlobalChannel = fetch_channel_by_cname(global_channel_clist,target);
channel *targetUserChannel = fetch_channel_by_cname(userInfo->userChannels,target);
if((is_char_present(targetGlobalChannel->cmode,'m') && !is_char_present(targetUserChannel->umode, 'o') && userInfo->mode != 'o') || !targetUserChannel)
{
snprintf(msg,128,"%s :You're not channel operator",target);
messageInfo.messageType = ERR_CHANOPRIVSNEEDED;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_CHANOPRIVSNEEDED\n");
return reply_to_one(messageInfo, userInfo);
}
printf("handling channel MODE %s %s\n",cmdValueInstance.value, cmdValueInstance.message);
return handle_internal_MODE_at_channel(cmdValueInstance,userInfo,userList);
}
else
{
if (strlen(modeflags) != 2)
{
printf("modeflag not two chars: '%s'\n",modeflags);
snprintf(msg,128,":unknown MODE flag");
messageInfo.messageType = ERR_UMODEUNKNOWNFLAG;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
if (strcmp(userInfo->nick, target))
{
snprintf(msg,128,":Cannot change mode for other users");
messageInfo.messageType = ERR_USERSDONTMATCH;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_USERSDONTMATCH\n");
return reply_to_one(messageInfo, userInfo);
}
printf("handling user MODE\n");
return handle_internal_MODE_at_user(cmdValueInstance,userInfo,userList);
}
return 1;
}
int handle_internal_MODE_at_channel(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char msg[128];
messageInfoStruct messageInfo = {"",""};
char *targetCname = cmdValueInstance.value;
char *modeflags = cmdValueInstance.message ? cmdValueInstance.message : "";
channel *targetGlobalChannel = fetch_channel_by_cname(global_channel_clist,targetCname);
channel *targetUserChannel = fetch_channel_by_cname(userInfo->userChannels,targetCname);
if(!strcmp(modeflags,""))
{
printf("no modeflag set, sending channel modes\n");
snprintf(msg,128,"%s +%s",targetCname, targetGlobalChannel->cmode);
messageInfo.messageType = RPL_CHANNELMODEIS;
messageInfo.messageContents = msg;
int returnval = reply_to_one(messageInfo, userInfo);
returnval += reply_to_channel(messageInfo, userInfo, targetGlobalChannel);
return returnval;
}
char *saveptr;
char *modeflagsCopy = strdup(modeflags);
char *mode = strtok_r(modeflagsCopy, " ", &saveptr);
char *targetNick = strtok_r(NULL,"",&saveptr);
printf("targetNick:'%s'\n",targetNick);
if(!is_char_present(targetUserChannel->umode,'o') && userInfo->mode != 'o')
{
snprintf(msg,128,"%s :You're not channel operator",targetCname);
messageInfo.messageType = ERR_CHANOPRIVSNEEDED;
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply ERR_CHANOPRIVSNEEDED\n");
return reply_to_one(messageInfo, userInfo);
}
//if it is a uMODE
if (modeflags[1] == 'v' || modeflags[1] == 'o')
{
printf("changing user's channel mode\n");
if(targetNick == '\0')
{
snprintf(msg,128,"%c :is unknown mode char to me for %s",modeflags[1],targetCname);
messageInfo.messageType = ERR_UNKNOWNMODE;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
else if (!(is_nick_present(targetGlobalChannel->userList, targetNick)))
{
char msg1[128];
messageInfoStruct messageInfo1 = {"",""};
snprintf(msg1, 128, "%s %s :They aren't on that channel",targetNick,targetCname);
messageInfo1.messageType = ERR_USERNOTINCHANNEL;
messageInfo1.messageContents = msg1;
return reply_to_one(messageInfo1, userInfo);
}
else
{
printf("user (target): %s, %s\n",mode, targetNick);
user *targetUser = fetch_user_by_nick(userList, targetNick);
channel *targetNickChannel =fetch_channel_by_cname(targetUser->userChannels,targetCname);
if(modeflags[0] == '-')
{
remove_mode(targetNickChannel->umode,modeflags[1]);
printf("modes:%s\n",targetNickChannel->umode);
}
else if(modeflags[0] == '+')
{
add_mode(targetNickChannel->umode,modeflags[1]);
printf("modes:%s\n",targetNickChannel->umode);
}
}
snprintf(msg,128,":%s!%s@%s MODE %s %s",userInfo->nick, userInfo->username, userInfo->clientIP,targetCname, modeflags);
messageInfo.messageType = "MODE";
messageInfo.messageContents = msg;
int returnval = 0;//reply_to_one(messageInfo, userInfo);
returnval += reply_to_channel(messageInfo, userInfo, targetGlobalChannel);
return returnval;
}
//if it is a cMODE
else if ((modeflags[1] == 'm' || modeflags[1] == 't') && !targetNick)
{
printf("changing global channel mode\n");
if(modeflags[0] == '-')
{
printf("removing...");
remove_mode(targetGlobalChannel->cmode, modeflags[1]);
printf("removed\n");
}
else if(modeflags[0] == '+')
{
printf("adding\n");
add_mode(targetGlobalChannel->cmode,modeflags[1]);
}
}
else
{
snprintf(msg,128,"%c :is unknown mode char to me for %s",modeflags[1],targetCname);
messageInfo.messageType = ERR_UNKNOWNMODE;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
snprintf(msg,128,":%s!%s@%s MODE %s %s",userInfo->nick, userInfo->username, userInfo->clientIP, targetCname, modeflags);
messageInfo.messageType = "MODE";
messageInfo.messageContents = msg;
fprintf(stderr, "sending reply from cMODE\n");
return reply_to_channel(messageInfo, userInfo,targetGlobalChannel);
return 1;
}
int handle_internal_MODE_at_user(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
char msg[128];
messageInfoStruct messageInfo = {"",""};
char *modeflags = cmdValueInstance.message;
if(!strcmp(modeflags,"+o") || modeflags[1] == 'a')
return 0;
else if (modeflags[1] == 'i' || modeflags[1] == 'w' || modeflags[1] == 'r' || modeflags[1] == 'o' || modeflags[1] == 'O' || modeflags[1] == 's')
{
printf("user %s %c->",userInfo->nick,userInfo->mode);
if(modeflags[0] == '-')
userInfo->mode = '\0';
else if(modeflags[0] == '+')
userInfo->mode = modeflags[1];
printf("%c\n",userInfo->mode);
snprintf(msg,128,":%s MODE %s :%s",userInfo->nick, userInfo->nick, modeflags);
messageInfo.messageType = "MODE";
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
else
{
snprintf(msg,128,":Unknown MODE flag");
messageInfo.messageType = ERR_UMODEUNKNOWNFLAG;
messageInfo.messageContents = msg;
return reply_to_one(messageInfo, userInfo);
}
return 1;
}
int handle_AWAY(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
fprintf(stderr, "handling AWAY\n");
int returnval;
char msg[1023];
messageInfoStruct messageInfo = {"", ""};
char *part1 = (cmdValueInstance.value ? strdup(cmdValueInstance.value) : "");
char *part2 = (cmdValueInstance.message ? strdup(cmdValueInstance.message) : "");
int len = strlen(part1) + strlen(part2) + 2;
char *away_message = (char*)malloc(len*sizeof(char) +2);
snprintf(away_message, len, "%s %s",part1,part2);
// RPL_UNAWAY
if (!strcmp(part1,"") || !strcmp(part2,"")) {
// set user's away message, and reset mode
userInfo->away_message = away_message;
userInfo->mode = '\0';
snprintf(msg, 1023, ":You are no longer marked as being away");
messageInfo.messageType = RPL_UNAWAY;
messageInfo.messageContents = msg;
returnval = reply_to_one(messageInfo, userInfo);
}
// RPL_NOWAWAY
else {
userInfo->away_message = away_message;
userInfo->mode = 'a';
snprintf(msg, 1023, ":You have been marked as being away");
messageInfo.messageType = RPL_NOWAWAY;
messageInfo.messageContents = msg;
returnval = reply_to_one(messageInfo, userInfo);
}
return 1;
}
int handle_NAMES(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
fprintf(stderr, "handling NAMES\n");
int returnval = 0;
char *cname = (cmdValueInstance.value ? cmdValueInstance.value : "");
// If channel param was given
if(strcmp(cname, "") != 0) {
channel *targetChannel = fetch_channel_by_cname(global_channel_clist, cname);
//RPL_NAMREPLY
char msg1[1023];
messageInfoStruct messageInfo1 = {"", ""};
char *usersString = fetch_users(targetChannel->userList);
snprintf(msg1, 1023, "= %s :%s",cname, usersString);
messageInfo1.messageType = RPL_NAMREPLY;
messageInfo1.messageContents = msg1;
returnval = reply_to_one(messageInfo1, userInfo);
//RPL_ENDOFNAMES
char msg2[128];
messageInfoStruct messageInfo2 = {"", ""};
snprintf(msg2, 128, "%s :End of NAMES list",cname);
messageInfo2.messageType = RPL_ENDOFNAMES;
messageInfo2.messageContents = msg2;
returnval += reply_to_one(messageInfo2, userInfo);
}
// NO PARAM GIVEN
else {
cnode *citer = global_channel_clist->head;
while(citer != NULL) {
list *userList = citer->channel->userList;
//RPL_NAMREPLY
char msg1[1023];
messageInfoStruct messageInfo1 = {"",""};
char *usersString = fetch_users(userList);
snprintf(msg1, 1023, "= %s :%s",citer->channel->cname, usersString);
messageInfo1.messageType = RPL_NAMREPLY;
messageInfo1.messageContents = msg1;
returnval += reply_to_one(messageInfo1, userInfo);
citer = citer->next;
}
char *not_in_channel = fetch_users_notJoined(global_user_list);
// All users JOIN'ed a channel
if(strcmp(not_in_channel, "") == 0)
{
//RPL_ENDOFNAMES
char msg2[128];
messageInfoStruct messageInfo2 = {"", ""};
snprintf(msg2, 128, "* :End of NAMES list");
messageInfo2.messageType = RPL_ENDOFNAMES;
messageInfo2.messageContents = msg2;
returnval += reply_to_one(messageInfo2, userInfo);
}
else // There are un-JOINED users
{
//RPL_NAMREPLY
char message[1023];
messageInfoStruct messageInfo3 = {"", ""};
snprintf(message, 1023, "* * :%s", not_in_channel);
messageInfo3.messageType = RPL_NAMREPLY;
messageInfo3.messageContents = message;
returnval += reply_to_one(messageInfo3, userInfo);
//RPL_ENDOFNAMES
char msg3[128];
messageInfoStruct messageInfo4 = {"", ""};
snprintf(msg3, 128, "* :End of NAMES list");
messageInfo4.messageType = RPL_ENDOFNAMES;
messageInfo4.messageContents = msg3;
returnval += reply_to_one(messageInfo4, userInfo);
}
}
return 1;
}
int handle_LIST(cmdValueStruct cmdValueInstance, user* userInfo, list* userList)
{
fprintf(stderr, "handling LIST\n");
int returnval = 0;
char *cname = (cmdValueInstance.value ? cmdValueInstance.value : "");
// If channel param was given
if(strcmp(cname, "") != 0) {
channel *targetChannel = fetch_channel_by_cname(global_channel_clist, cname);
//RPL_LIST
char msg1[1023];
messageInfoStruct messageInfo1 = {"", ""};
int num_users = list_size(targetChannel->userList);
char *top = targetChannel->topic;
char *topic = top + 1;
snprintf(msg1, 1023, ":%s %s %s %s %d :%s",userInfo->hostname, RPL_LIST, userInfo->nick, cname, list_size, topic);
messageInfo1.messageType = RPL_LIST;
messageInfo1.messageContents = msg1;
returnval = reply_to_one(messageInfo1, userInfo);
// RPL_LISTEND
char msg2[1023];
messageInfoStruct messageInfo2 = {"", ""};
snprintf(msg2, 1023, ":End of LIST");
messageInfo2.messageType = RPL_LISTEND;
messageInfo2.messageContents = msg2;
returnval += reply_to_one(messageInfo2, userInfo);
}
else { // NO PARAM GIVEN
cnode *citer = global_channel_clist->head;
while (citer != NULL) {
channel *lChannel = citer->channel;
char *name = lChannel->cname;
int csize = list_size(lChannel->userList);
char *topic = lChannel->topic;
//RPL_LIST
char message[1023];
messageInfoStruct messageInfo = {"", ""};
char *top = topic + 1;
snprintf(message, 1023, ":%s %s %s %s %d :%s",userInfo->hostname, RPL_LIST, userInfo->nick, name, csize, top);
messageInfo.messageType = RPL_LIST;
messageInfo.messageContents = message;
returnval = reply_to_one(messageInfo, userInfo);
citer = citer->next;
}
//RPL_LISTEND
char message2[1023];
messageInfoStruct messageInfo3 = {"", ""};
snprintf(message2, 1023, ":End of LIST");
messageInfo3.messageType = RPL_LISTEND;
messageInfo3.messageContents = message2;
returnval += reply_to_one(messageInfo3, userInfo);
}
return 1;
}
int handle_WHO(cmdValueStruct cmdValueInstance, user* userInfo, list* userList){return 1;}
|
C
|
#include <stdio.h>
#include <string.h>
typedef struct alunos{
char nome[21];
int prob_res;
} alunos;
int main(){
int i, i1, aux, n;
char aux_char[21];
scanf("%d", &n);
alunos aluno[n];
for(i=0; i<n; i++){
scanf("%s %d", &aluno[i].nome, &aluno[i].prob_res);
}
//ordena os alunos
//por nota
for(i=0; i<n; i++){
for(i1=i; i1<n; i1++){
if(aluno[i1].prob_res>aluno[i].prob_res){
aux=aluno[i1].prob_res;
aluno[i1].prob_res=aluno[i].prob_res;
aluno[i].prob_res=aux;
strcpy(aux_char, aluno[i1].nome);
strcpy(aluno[i1].nome, aluno[i].nome);
strcpy(aluno[i].nome, aux_char);
}
}
}
//por ordem alfabética
for(i=0; i<n; i++){
for(i1=i; i1<n; i1++){
if(aluno[i].prob_res==aluno[i1].prob_res){
if(strcmp(aluno[i].nome, aluno[i1].nome)>0){
strcpy(aux_char, aluno[i1].nome);
strcpy(aluno[i1].nome, aluno[i].nome);
strcpy(aluno[i].nome, aux_char);
}
}
}
}
for(i=0; i<n; i++){
if(i==(n-1)){
printf("%s %d #reprovado(a)\n", aluno[i].nome, aluno[i].prob_res);
}
else{
printf("%s %d\n", aluno[i].nome, aluno[i].prob_res);
}
}
}
|
C
|
#include<stdio.h>
/**
*binary_to_uint - converst a binary number into an unsigned integer
*@b:pointer to a string with 0 and 1
*Return:An unsigned integer
*/
unsigned int binary_to_uint(const char *b)
{
int i = 0;
int j = 0;
int m = 0;
int k;
unsigned int elem = 1;
unsigned int ret = 0;
if (b == NULL)
return (0);
while (b[i] != '\0')
{
i++;
}
for (j = (i - 1); j >= 0; j--)
{
if (b[j] == '1')
{
for (k = 0; k < m; k++)
{
elem = elem * 2;
}
ret = ret + elem;
elem = 1;
}
m++;
if (!(b[j] == '0' || b[j] == '1'))
return (0);
}
return (ret);
}
|
C
|
/* Date : 2017.08.04
* Author : NYB
* Intro : 多线程,每个线程都调用函数A,函数A中访问全局变量,加锁访问。
* Result : global从0自增到MAX_COUNT
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#define MAX_COUNT 5000000
#define SLEEP_TIME (1)
void err_quit(const char *api);
void thread_fun(void *arg);
void cnt_plus_one();
int global = 0;
pthread_mutex_t mutex;
int main()
{
if(pthread_mutex_init(&mutex, NULL) < 0)
err_quit("pthread_mutex_init");
int i = 0;
for(i = 0; i < 3; i++)
{
pthread_t th;
if(pthread_create(&th, NULL, (void *)thread_fun, NULL) != 0)
err_quit("pthread_create");
}
while(1)
{
pthread_mutex_lock(&mutex);
if(global > MAX_COUNT)
break;
pthread_mutex_unlock(&mutex);
}
pthread_mutex_destroy(&mutex);
return 0;
}
void err_quit(const char *api)
{
perror(api);
exit(1);
}
void thread_fun(void *arg)
{
int retval;
pthread_t tid = pthread_self();
pthread_detach(tid);
while(1)
{
//printf("tid->%ld ", tid);
cnt_plus_one();
//usleep(SLEEP_TIME);
}
printf("tid->%ld exit\n", tid);
pthread_exit(&retval);
}
void cnt_plus_one()
{
pthread_mutex_lock(&mutex);
global++;
printf("global=%d\n", global);
pthread_mutex_unlock(&mutex);
}
|
C
|
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#ifndef BACKLOG
#define BACKLOG 8
#endif
#ifndef DUMB_RESPONSE
// Show me some love, I could Rick Roll you!
#define DUMB_RESPONSE "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nHi there! I am a dumb web server\r\n"
#endif
int main() {
// Heroku needs to get port from env
char * PORT = getenv("PORT");
if (errno) return errno;
if (PORT == NULL) return EINVAL;
int port = atoi(PORT);
if (errno) return errno;
// Open up socket; ref: socket(2)
int sd = socket(PF_INET, SOCK_STREAM, 0);
if (sd < 0) return errno;
// Initialize internet socket address
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
// Bind the socket with an address; ref: bind(2)
if (bind(sd, (struct sockaddr*)&addr, sizeof(addr))) return errno;
// Maximum length for the queue of pending connections = BACKLOG; ref listen(2)
if (listen(sd, BACKLOG)) return errno;
// Dumb response can stay in stack
char response[] = DUMB_RESPONSE;
// Not gonna log anything
while (1) {
// Open up incoming descriptor; ref: accept(2)
int cd = accept(sd, NULL, NULL);
if (cd < 0) continue;
// You know what?
// I'm not gonna listen to whatever you are saying!
// dumb response here I come
write(cd, response, sizeof(response));
// Good boy stuff
close(cd);
}
return 0;
}
|
C
|
#include <stdio.h>
void swap(int,int);
void main()
{
int x=10,y=20;
printf("(1)a=%d y=%d\n",x,y);
swap(x,y);
printf("(4)x=%d y=%d\n",x,y);
}
void swap (int a,int b)
{
int t;
printf("(2)a=%d b=%d\n",a,b);
t=a;
a=b;
b=t;
printf("(3)a=%d b=%d\n",a,b);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE {
int value;
struct NODE *next;
} Node;
int main(void) {
Node *root = NULL;
Node *tail;
Node *node;
int n;
for(n = 1; n < 5; n++) {
Node *node = malloc(sizeof(Node)); // If you not define Node *node here, then you have to define node = node->next at the end of the loop
node->value = n;
node->next = NULL;
if(root == NULL)
root = node;
else
tail->next = node;
tail = node;
}
tail = root;
while(tail != NULL) {
printf("%d\n", tail->value);
tail = tail->next;
}
/**
Note: If you do this, then it will destroy the root and you cannot again traverse the list
while(root != NULL) {
printf("%d\n", root->value);
root = root->next;
}
**/
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n;
system("clear");
printf("Enter any number:");
scanf("%d",&n);
if(n<0)
{
n=(-1)*n;
printf("Absolute value is %d",n);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "VG/openvg.h"
#include "VG/vgu.h"
#include "./../src/fontinfo.h"
#include "./../src/libshapes.h"
int main() {
const char msg[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', 0 };
int width, height;
char s[3];
/* We have to initialise the OpenVG canvas and renderer by using
* `init(&w, &h)`.
*/
evgInit(&width, &height);
evgBegin(width, height);
{
evgBackground(0, 0, 0);
evgFill(44, 77, 232, 1);
evgCircle(width / 2, 0, width);
evgFill(255, 255, 255, 1);
evgTextMid(width / 2,
height * 0.7,
msg,
SansTypeface,
width / 15);
}
evgEnd();
// We can use `fgets` to wait for user input before ending the program. This
// is a neat way of keeping the rendered assets on screen until the user
// presses a key.
fgets(s, 2, stdin);
evgFinish();
exit(0);
}
|
C
|
/*
<The C programming language> - 2nd Edition by K&R
Exercise 1.13. Write a program to print a histogram of the lengths of words in
its input. It is easy to draw the histogram with the bars horizontal; a vertical
orientation is more challenging
Compiler: MinGW.org GCC-8.2.0-3
by Gabe Gu
2019-4-4
*/
#include <stdio.h>
#include <stdbool.h>
#define MAX_N_WORDS 20
int main() {
int c, row, col, maxHeight = -2, nWords = 0;
int lWord[MAX_N_WORDS];
bool inTheWord = false;
/* calculate the length of the first nWords words */
while((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n' || c == 26) {
if (inTheWord) {
inTheWord = false;
if (nWords < MAX_N_WORDS) {
nWords++;// pointer to next subscript of array
}
}
/* print the horizonal histogram of the first nWords words */
if (c == '\n' || c == 26) {
for (row = 0; row < nWords; row++) {
if (row == 0) {
printf("--------------------------------------------------------------------------------------------------\n");
}
if (row + 1 < 10) {
printf("0");
}
printf("%d|", row + 1);
for (col = 0; col < lWord[row]; col++) {
printf("X ");
}
printf("\n");
}
/* print the vertical histogram of the first nWords words */
for (row = 0; row < nWords; row++) {
if (lWord[row] > maxHeight) {
maxHeight = lWord[row];
}
}
for (row = maxHeight; row >= -1; row--) {
if (row == maxHeight) {
printf("--------------------------------------------------------------------------------------------------\n");
}
for (col = 0; col < nWords; col++) {
if (row == -1) {
if (col != 0) {
printf(" ");
}
printf("%d", (col + 1) / 10);
printf("%d", (col + 1) % 10);
printf(" ");
}
else if (row == 0) {
if (col != 0) {
printf("--");
}
printf("---");
}
else {
if (col != 0) {
printf(" ");
}
printf(" ");
if (lWord[col] >= row) {
printf("X");
}
else {
printf(" ");
}
printf(" ");
}
}
printf("\n");
if (row == -1) {
printf("--------------------------------------------------------------------------------------------------\n");
}
}
nWords = 0;
maxHeight = -2;
}
}
else {
if (!inTheWord) {
inTheWord = true;
lWord[nWords] = 0;
}
if (nWords < MAX_N_WORDS) {
lWord[nWords]++;
}
}
}
return 0;
}
|
C
|
int main()
{
int inta=0,i,a=0,b=0;//inta????????i?????
cin>>inta;
for(i=0;;i++)
{
if(inta%2==0)
{
a=inta/2;
cout<<inta<<"/2="<<a<<endl;
inta=a;
}
if(inta%2!=0&&inta!=1)
{
b=inta*3+1;
cout<<inta<<"*3"<<"+1="<<b<<endl;
inta=b;
}
if(inta==1)
{
break;
}
}
cout<<"End";
cin.get();cin.get();cin.get();cin.get();
return 0;
}
|
C
|
/*
file: scoreboard.c
student email(s): [email protected], [email protected], [email protected],
[email protected], [email protected], [email protected],
group #: Group 3 (Section 2)
date: November 3, 2017
description: File containing the source code for accessor and mutator functions
for User ADT
Refactored By: Israa Sinan
*/
/*Standard/User Defined Libraries*/
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include "scoreboard.h"
/*
* Finds and returns a pointer to the User in the linked list beginning with
* head which has the name nameToFind. If such a User is not in the Linked
* List, it will return NULL. Helper function to increment_score.
*/
User *findUserWithName(User *head, char *nameToFind) {
if (head == NULL) {
return head;
}
User *current = head;
while (current != NULL) {
if (strcmp(current->name, nameToFind) == 0) {
return current;
}
current = current->next;
}
return NULL;
}
// freeAll: This function frees the memory of all elements of the linked list.
void freeAll(User *head) {
if (head->next == NULL) {
free(head);
}
else {
User *current = head->next;
User *previous = head;
while (current != NULL) {
free(previous);
previous = current;
current = current->next;
}
}
}
// getUserAtIndex: Finds and returns a the User in the linked list at a specified index
User *getUserAtIndex(User *head, int index) {
if (head == NULL) {
return NULL;
}
User *current = head;
int count = 0;
while (current != NULL) {
if (count == index + 1) {
return current;
}
current = current->next;
count++;
}
return NULL;
}
/*
getIndexOfUserWithName: Finds and returns a the index in the linked list based on the specified
name of user
*/
int getIndexOfUserWithName(User *head, char *nameToFind) {
if (head == NULL && head->name != nameToFind) {
return -1;
}
User *current = head;
int count = 0;
while (current != NULL) {
if (strcmp(current->name, nameToFind)) {
return count;
}
current = current->next;
count++;
}
return -1;
}
/*
userIsInList: Finds whether or not a an existing user is already in the list. If they are,
returns 1. If not, returns 0.
*/
int userIsInList(User *head, char *nameToFind) {
User *current = head;
while (current != NULL) {
if (strcmp(current->name, nameToFind) == 0) {
return 1;
}
current = current->next;
}
return 0;
}
// getLength: Finds and returns the amount of User nodes in the linked list
int getLength(User *head) {
if (head == NULL) {
return 0;
}
User *current = head;
int count = 0;
while (current != NULL) {
count++;
if (current->next == NULL) {
return count;
}
current = current->next;
}
return 0;
}
/*
getLastNode: Finds the last node in the linked list and returns it. Returns NULL if called
with an empty head, although such a case is not used in the main function addNode. Helper function.
*/
User *getLastNode(User *head) {
if (head == NULL) {
return head;
}
User *current = head;
while (current != NULL) {
if (current->next == NULL) {
return current;
}
current = current->next;
}
return NULL;
}
// printScoreboard: Outputs the player name, high score, games played, total score in an organized format
void printScoreboard(User *head) {
fprintf(stdout, "\n");
fprintf(stdout, "---- SCORE BOARD ---- \n");
if (head->next != NULL) {
User *current = head->next;
while (current != NULL) {
printf("\n");
printf("Player name: %s \n", current->name);
printf("High score: %d \n", current->maxScore);
printf("Games played: %d \n", current->totalGames);
printf("Total score: %d \n", current->totalScore);
printf("\n");
printf("--------------------- \n");
if (current->next == NULL) {
break;
}
current = current->next;
}
}
}
// addNode: Initializes a User Node and inserts it at the tail of the linked list
void addNode(User *head, char *name, int maxScore) {
User *userPtr = NULL;
if (head != NULL) {
userPtr = malloc(sizeof(User));
}
strcpy(userPtr->name, name);
userPtr->maxScore = maxScore;
userPtr->totalGames = 1;
userPtr->totalScore = maxScore;
userPtr->next = NULL;
if (head == NULL) {
head = userPtr;
}
else {
getLastNode(head)->next = userPtr;
}
}
// updateNodeWithName: Updates the User score by finding the user in the linked list by it's name.
void updateNodeWithName(User *head, char *name, int currentScore) {
if (userIsInList(head, name) == 1) {
User *userPtr = findUserWithName(head, name);
if (currentScore > (userPtr->maxScore)) {
userPtr->maxScore = currentScore;
}
userPtr->totalGames += 1;
userPtr->totalScore += currentScore;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 10
int main()
{
int *array = calloc(sizeof(int), ARRAY_SIZE);
for(int i = 0; i < ARRAY_SIZE; i++)
{
//array[i] = i;
*(array + i) = i;
}
for(int i = 0; i < ARRAY_SIZE; i++)
{
printf("%d\n", array[i]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>
int compareFiles(int fd1, int fd2){
// 대소문자, 공백 허용
char ch1, ch2;
int isSame = 0, res1, res2;
// ch1 : ANS, ch2 : STD
while(1){
printf("isSame1 = %d\n",isSame);
if((res1 = read(fd1, &ch1, 1)) > 0 && (res2 = read(fd2, &ch2, 1)) > 0){
isSame = 0;
if(ch1 == ' '){
while(1){
read(fd1, &ch1, 1);
if(ch1 != ' ')
break;
}
}
if(ch2 == ' '){
while(1){
read(fd2, &ch2, 1);
if(ch2 != ' ')
break;
}
}
printf("%c %c\n",ch1,ch2);
if(isalpha(ch1) && isalpha(ch2)){
if(ch1 == ch2 || ch1 + 32 == ch2 || ch1 - 32 == ch2){
isSame = 1;
}
}
else{
if(ch1 == ch2){
isSame = 1;
}
}
}
printf("isSame2 = %d\n",isSame);
if(res1 == 0 || res2 == 0){
if(isSame == 1)
return 1;
else
return 0;
}
printf("isSame3 = %d\n",isSame);
if(isSame == 0){
break;
}
}
if(isSame == 1){
return 1;
}
else{
printf("wrong\n");
return 0;
}
}
int main(void){
int res;
int fd1, fd2;
fd1 = open("1.txt", O_RDONLY);
fd2 = open("2.txt", O_RDONLY);
res = compareFiles(fd1, fd2);
printf("res = %d\n",res);
return 0;
}
|
C
|
/**
* @file stack.c
* @author Gonzalo Arcas & Ciro Alonso
* @date 14 March 2020
* @brief ADT Stack
*
* @details definicion de las funciones stack.h
*
* @see
*/
#include "stack.h"
#include <errno.h>
extern int errno;
#define MAXSTACK 1024
struct _Stack{
int top;
Element *item[MAXSTACK];
};
Stack * stack_init (){
Stack *aux = NULL;
aux = (Stack *) malloc (sizeof(Stack));
if (!aux ) return NULL;
for (int i=0; i<MAXSTACK; i++){
aux->item[i] = NULL;
}
aux->top = -1;
return aux;
}
void stack_free(Stack *s){
if (!s) return ;
for (int i=0; i<MAXSTACK; i++){
element_free(s->item[i]);
}
free(s);
}
Status stack_push(Stack *s,const Element *ele){
Element *aux = NULL;
if (!s || !ele || stack_isFull(s)==TRUE) return ERROR;
aux = element_copy(ele);
if (!aux) return ERROR;
s->top++;
s->item[s->top] = aux;
return OK;
}
Element * stack_pop(Stack *s){
Element *aux = NULL;
if (!s || stack_isEmpty(s)==TRUE) return NULL;
aux = s->item[s->top];
s->item[s->top] = NULL;
s->top--;
return aux;
}
Element * stack_top(const Stack *s){
if (!s || stack_isEmpty(s)==TRUE) return NULL;
return s->item[s->top];
}
Bool stack_isEmpty(const Stack *s){
if (s->top == -1) return TRUE;
return FALSE;
}
Bool stack_isFull(const Stack *s){
if (s->top == MAXSTACK-1) return TRUE;
return FALSE;
}
int stack_print(FILE *pf,const Stack *s){
int cont = 0;
if (!pf || !s){
fprintf(stderr, "%s", strerror(errno));
return -1;
}
for (int i=s->top; i>=0; i--){
cont = element_print(pf, s->item[i]);
}
return cont;
}
int stack_size(Stack *s){
if (!s) return -1;
return s->top+1;
}
|
C
|
/*
Name: Sunil giri
Subject: Programming fundamentals.
Program:to print pascals triangle.
Roll no.:
Bcs Sem:1st
Date:jan 12 2017
*/
#include<stdio.h>
int factorial(int a);
int main()
{
int z,n,i,fact,j;
printf("Enter number of terms to print pascal triangle:");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
fact=1;
for(z=0;z<=n-i;z++)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
fact=(factorial(i)/(factorial(j)*factorial((i-j))));
printf("%d ",fact);
}
printf("\n\n");
}
}
int factorial(int a)
{
int fact1=1,i;
for(i=a;i>=1;i--)
{
fact1*=i;
}
return (fact1);
}
|
C
|
//
// Created by adrian on 09.09.2019.
//
/*
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given a 32-bit integer, return the number with its bits reversed.
For example, given the binary number 1111 0000 1111 0000 1111 0000 1111 0000,
return 0000 1111 0000 1111 0000 1111 0000 1111.
*/
#include "day37.h"
int reverseBits(int number)
{
return ~number;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main(void){
int a,b,c;
float real=0,imag=0;
int disc;
printf("Enter the coefficients\n");
scanf("%d %d %d",&a,&b,&c);
disc = b*b - (4*a*c);
if(disc>0){
real = (-b + sqrt(disc))/(2*a);
imag = (-b - sqrt(disc))/(2*a);
}
if(disc==0){
real=-b/(2*a);
}
else{
real = -b/(2*a);
imag = sqrt(-disc)/(2*a);
}
printf("The real value is %.2f\n",real);
printf("The imaginary value is %.2f",imag);
return 0;
}
|
C
|
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
int main(){
sigset_t blk_set;
sigemptyset(&blk_set);
sigaddset(&blk_set, SIGINT);
sigaddset(&blk_set, SIGTSTP);
sigprocmask(SIG_BLOCK, &blk_set,NULL);
//Obtener variable del entorno
char *sleep_secs = getenv("SLEEP_SECS");
int secs = atoi(sleep_secs);
printf("El proceso se dormira durante: %d segundos\n", secs);
sleep(secs);
//Señales pendientes
sigset_t pendientes;
sigpending(&pendientes);
//Comprobamos si la señal ha llegado
if(sigismember(&pendientes, SIGINT)== 1){//SEÑAL SIGINT
printf("Se recibio la señal SIGINT\n");
sigdelset(&blk_set, SIGINT);
}else{
printf("No se recibio la señal SIGINT\n");
}
if(sigismember(&pendientes, SIGTSTP)== 1){//SEÑAL SIGTSTP
printf("Se recibio la señal SIGTSTP\n");
sigdelset(&blk_set, SIGTSTP);
}else{
printf("No se recibio la señal SIGTSTP\n");
}
sigprocmask(SIG_UNBLOCK, &blk_set, NULL);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
if (argc <= 1) {
printf("Something is wrong with the arguments");
exit(1);
}
char *buffer[2048];
int counter = 0;
while(scanf("%c", &buffer[counter]) != EOF) {
counter++;
}
FILE *dest;
if (strcmp(argv[1], "-a") == 0) {
dest = fopen(argv[argc-1], "a");
if (dest < 0) {
ferror(dest);
}
} else {
dest = fopen(argv[argc-1], "w");
if (dest < 0) {
ferror(dest);
}
}
for (int j = 0; j < counter; ++j) {
fprintf(dest, "%c", buffer[j]);
}
return 0;
}
|
C
|
// clearerr_ex.c : clearerr() example
// -------------------------------------------------------------
#include <stdio.h> // void clearerr(FILE *fp);
#include <stdlib.h>
int main()
{
FILE *fp;
int c;
if ((fp = fopen("infile.dat", "r")) == NULL)
fprintf(stderr, "Couldn't open input file.\n");
else
{
c = fgetc(fp); // fgetc() returns a character on success;
if (c == EOF) // EOF means either an error or end-of-file.
{
if ( feof(fp))
fprintf(stderr, "End of input file reached.\n");
else if ( ferror(fp))
fprintf(stderr, "Error on reading from input file.\n");
clearerr(fp); // Same function clears both conditions.
}
else
{ // Process the character that we read.
/* ... */
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "libc/brk.h"
void *realloc(void *old, size_t size)
{
void *top;
void *now = __cur_brk;
size = ((size + 15) / 16) * 16;
top = sbrk(size);
if (top == (void *)-1)
return NULL;
if (old)
memmove(now, old, size);
return now;
}
|
C
|
//---------------------------rail way reservation project by using c programming language--------------------------
//---------------------------------------header file start-----------------------------------------
#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
#include<string.h>
//---------------------------------------header file close-------------------------------------------
//---------------------------------------user define function start----------------------------------
void viewinfo();
void bookticket();
void cancelticket();
void admin();
void password();
void viewpassenger();
void addtrain();
void dlttrain();
void awrite();
void aread();
void bookticket_write();
void viewpassengers_read();
//-----------------------------------------user define function close-----------------------------------
//-----------------------------------------structure start----------------------------------------------
struct adddata
{
char si[10];
char train_number[10];
char train_name[20];
char start[10];
char destination[10];
char price[10];
int seat;
char time[10];
} add[1000];
struct bookticket
{
char train_number[20];
char name[20];
char phone[20];
char date[20];
int seat;
}book[1000];
//---------------------------------------structure close----------------------------------------------
//---------------------------------------global variable----------------------------------------------
int k=0,u=0;
char trn_nmbr[100],name[100],phn[100];
//---------------------------------------main function start------------------------------------------
int main()
{
aread();
viewpassengers_read();
system("COLOR 0f");
int ch;
time_t currentTime;
time(¤tTime);
printf("\n\t\t\t %s\n",ctime(¤tTime));
printf("\n\t\t\t*********************************\n");
printf("\t\t\t*******RAILWAY RESERVATION SYSTEM*******\n");
printf("\t\t\t*********************************\n");
printf("\n\t\t\t<<<<<<<<<<WELCOME USERS>>>>>>>>>>\n");
printf("\n\n\t\t\t\t MENU\n");
printf("\t\t\t ******");
printf("\n\t\t\t[1] VIEW INFORMATION\n");
printf("\n\t\t\t[2] BOOK TICKET\n");
printf("\n\t\t\t[3] CANCEL TICKET\n");
printf("\n\t\t\t[4] ADMIN");
printf("\n\n\t\t\t[5] EXIT\n");
printf("\n\t\t\t********************************");
printf("\n\t\t\t********************************");
printf("\n\t\t\tENTER YOUR CHOICE: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
viewinfo();
break;
case 2:
bookticket();
break;
case 3:
cancelticket();
break;
case 4:
password();
break;
case 5:
system("cls");
printf("\n\t\t\t =========================================\n");
printf("\t\t\t *******RAILWAY RESERVATION SYSTEM*******\n");
printf("\t\t\t ===============================================\n");
printf("\n\n\t\t\tBMROUGHT TO YOU BY\n\n");
printf("\t\t\t\t***Learnprogramo***\n");
getch();
exit(0);
break;
default:
system("cls");
printf("\n\t\t\t==============================================\n");
printf("\t\t\t *******RAILWAY RESERVATION SYSTEM*******\n");
printf("\t\t\t ==============================================\n");
printf("\n\n\t\t\t<<<<<<<<YOU ENTERED WRONG CHOICE>>>>>>>>\n");
printf("\t\t\t<<<<<<<<PLEASE ENTER RIGHT THING>>>>>>>>\n");
getch();
system("cls");
main();
}
return 0;
}
//---------------------------------------main function close--------------------------------------------------
//---------------------------------------book ticket function-----------------------------------------------
void bookticket()
{
int c,j,n,i,found=-1;
char v,train_number[10];
system ("cls");
aread();
printf("\n\n\t\t\t============================================");
printf("\n\t\t\t**********RAILWAY RESERVATION SYSTEM**********\n");
printf("\t\t\t==================================================");
printf("\n\n\t\t\thow many ticket do you want to buy: ");
scanf("%d",&n);
for(j=u;j<u+n;j++)
{
printf("\n\n\t\t\tEnter train number: ");
scanf("%s", book[j].train_number);
for(i=0;i<k;i++)
{
if(strcmp(book[j].train_number,add[i].train_number)==0)
{
if(add[i].seat==0)
{
printf("\n\n\t\t\tnot available seat");
getch();
system("cls");
main();
}
else
{
found=1;
printf("\n\t\t\tenter book %d no ticket: ",j+1);
printf("\n\t\t\tenter date: ");
scanf("%s",book[j].date);
printf("\n\t\t\tenter your name: ");
scanf("%s",book[j].name);
printf("\n\t\t\tenter your phone number: ");
scanf("%s",book[j].phone);
printf("\n\t\t\tseat number : %d",add[i].seat );
book[j].seat=add[i].seat;
bookticket_write();
add[i].seat--;
awrite();
}
}
}
if(found==-1)
{
printf("\n\n\t\t\ttrain not found!!!");
getch();
system("cls");
main();
}
}
u=j;
bookticket_write();
printf("\n\n\t\t\tenter '1' for main menu & press any key to exit: ");
scanf("%d",&c);
if(c==1)
{
system("cls");
main();
}
if(c!=1)
{
exit;
}
}
//---------------------------------------cancel ticket function---------------------------------------------
void cancelticket()
{
viewpassengers_read();
char pnnmbr[100];
int location = -1,e;
printf ("\n\n\t\t\tenter phone number: ");
scanf ("%s",pnnmbr);
for (e=0;e<u;e++)
{
if (strcmp(pnnmbr,book[e].phone)==0)
{
location=e;
break;
}
}
if (location==-1)
{
printf ("\n\n\t\t\t<<<<<<<<<<<<<<Data Not Found>>>>>>>>>>>>>>>>> \n");
getch();
system("cls");
main();
}
else
{
for (e=location;e<u;e++)
{
strcpy(book[e].date,book[e+1].date);
strcpy(book[e].train_number,book[e+1].train_number);
strcpy(book[e].name,book[e+1].name);
strcpy(book[e].phone,book[e+1].phone);
bookticket_write();
}
u--;
bookticket_write();
printf("\n\n\t\t\t<<<<<<<<<<<<<<<ticket cancelled successfully>>>>>>>>>>>>");
getch();
system("cls");
main();
}
}
//-------------------------------------admin portal function----------------------------------------
void admin()
{
int chhh;
system("cls");
printf("\n ==================================================================");
printf("\n ********************RAILWAY RESERVATION SYSTEM*******************");
printf("\n ====================================================================");
printf("\n\n");
printf(" <<<<<<<<<<<<<<<WELCOME_ADMIN>>>>>>>>>>>>>>>\n");
printf("\n\n");
printf(" ************************************\n");
printf(" || CHOOSE YOUR OPERATION ||\n");
printf(" ||--------------------------------||\n");
printf(" || [1] VIEW PASSENGERS ||\n");
printf(" || [2] ADD TRAIN ||\n");
printf(" || [3] DELETE TRAIN ||\n");
printf(" || [4] BACK ||\n");
printf(" || ||\n");
printf(" ************************************\n\n");
printf(" **********************************************************\n");
printf("\n\t\tENTER YOUR CHOICE: ");
scanf("%d",&chhh);
switch(chhh)
{
case 1:
viewpassenger();
break;
case 2:
addtrain();
break;
case 3:
dlttrain();
break;
case 4:
system("cls");
getch();
main();
break;
default:
getch();
printf("\n\t\t\tyou entered wrong KEY!!!!");
getch();
system("cls");
main();
}
getch();
}
//-----------------------------password function----------------------------------
void password()
{
int number=1234567;
int pass;
printf("\n\t\t\tenter password: ");
scanf("%d",&pass);
if(pass==number)
{
printf("\n\n\t\t\t<<<<<login successfully>>>>>");
getch();
system("cls");
admin();
}
else
{
printf("\n\n\t\t\t\t ERROR!!!!!");
printf("\n\n\t\t\t<<<<<<<<wrong password>>>>>>>>");
getch();
system("cls");
main();
}
}
//------------------------------------delete train function----------------------------------------------
void dlttrain()
{
aread();
char train[100];
int location = -1,f;
printf ("\n\n\tenter train number: ");
scanf ("%s",train);
for (f=0;f<k;f++)
{
if (strcmp(train,add[f].train_number)==0)
{
location=f;
break;
}
}
if (location==-1)
{
printf ("\n\n\t<<<<<<<<<<<<<<Data Not Found>>>>>>>>>>>>>>>>> \n");
getch();
system("cls");
admin();
}
else
{
for (f=location;f<k;f++)
{
strcpy(add[f].si,add[f+1].si);
strcpy(add[f].train_number,add[f+1].train_number);
strcpy(add[f].train_name,add[f+1].train_name);
strcpy(add[f].start,add[f+1].start);
strcpy(add[f].destination,add[f+1].destination);
strcpy(add[f].price,add[f+1].price);
strcpy(add[f].time,add[f+1].time);
awrite();
}
k--;
awrite();
printf("\n\n\t<<<<<<<<<<<<<train deleted successfully>>>>>>>>>>>>>");
getch();
system("cls");
admin();
}
}
//--------------------------------------view passengers function----------------------------------------
void viewpassenger()
{
int a,j;
system("cls");
viewpassengers_read();
printf("\n\t\t\t **********************************************************");
printf("\n\t\t\t ********************RAILWAY RESERVATION SYSTEM********************");
printf("\n\t\t\t **********************************************************");
printf("\n\n\t\t\ttrain number\t\tname\t\tphone number\t\tdate\t\tseat\n");
printf("\n\t\t\t**********************************************************************************\n");
for(j=0;j<u;j++)
{
printf("\n\t\t\t%s\t\t\t%s\t\t%s\t\t%s\t%d",book[j].train_number,book[j].name,book[j].phone,book[j].date,book[j].seat);
book[j].seat++;
}
printf("\n\t\t\t**********************************************************************************\n");
printf("\n\n\t\t\tenter '1' for main menu & enter '0' for back: ");
scanf("%d",&a);
if(a==1)
{
system("cls");
main();
}
if(a==0)
{
system("cls");
admin();
}
}
//--------------------------------------add train function--------------------------------------------
void addtrain()
{
system("cls");
int ch;
aread();
int i,a;
printf("\n\t\t **********************************************************");
printf("\n\t\t ********************RAILWAY RESERVATION SYSTEM********************");
printf("\n\t\t **********************************************************");
printf("\n\n\t\t\thow many trains do you want to add: ");
scanf("%d",&a);
for(i=k;i<k+a;i++)
{
printf("\n\t\t\tenter %d train details: ",i+1);
printf("\n\t\t\tenter serial number: ");
scanf("%s",add[i].si);
printf("\n\t\t\tenter train number: ");
scanf("%s",add[i].train_number);
printf("\n\t\t\tenter train name: ");
scanf("%s",add[i].train_name);
printf("\n\t\t\tenter start place: ");
scanf("%s",add[i].start);
printf("\n\t\t\tenter destination place: ");
scanf("%s",add[i].destination);
printf("\n\t\t\t enter price: ");
scanf("%s",add[i].price);
printf("\n\t\t\t enter seat: ");
scanf("%d", & add[i].seat);
printf("\n\t\t\t enter time: ");
scanf("%s",add[i].time);
}
printf("\n\n\t\t\tconfirm train: (y=1/n=0):- ");
scanf("%d",&ch);
if(ch==1)
{
awrite();
k=i;
awrite();
system("cls");
printf("\n\n\t\t\t**********************************************************");
printf("\n\t\t\t********************RAILWAY RESERVATION SYSTEM********************");
printf("\n\t\t\t**********************************************************");
printf("\n\n");
printf("\n\t\t\t\t **********************************");
printf("\n\t\t\t\t *<<<<<train add successfully>>>>>*");
printf("\n\t\t\t\t **********************************");
getch();
system("cls");
main();
}
if(ch==0)
{
system("cls");
admin();
}
if((ch!=1)&&(ch!=0))
{
system("cls");
main();
}
}
//-----------------------------------view information function--------------------------------------
void viewinfo()
{
int ch,i;
system("cls");
aread();
printf("\n\t\t **********************************************************");
printf("\n\t\t ********************RAILWAY RESERVATION SYSTEM********************");
printf("\n\t\t **********************************************************");
printf("\n\n\n SI\ttrain number\ttrain name\tstart place\tdestination place\tprice\tseat\ttime\n\n");
for(i=0;i<k;i++)
{
printf(" %s\t%s\t\t%s\t\t%s\t\t%s\t\t\t%s\t%d\t%s\n",add[i].si,add[i].train_number,add[i].train_name,add[i].start,add[i].destination,add[i].price,add[i].seat,add[i].time);
}
printf(" ***********************************************************************************************\n");
printf("\n\t\t\tpress '1' for main menu & press any key for exit: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
system("cls");
main();
break;
default:
exit(0);
}
}
//------------------------------------------book ticket file start-----------------------------------------
void bookticket_write()
{
FILE *booklist;
booklist=fopen("booklist.txt","w");
fwrite(&book,sizeof(book),1,booklist);
fclose(booklist);
FILE *booklistreport;
booklistreport=fopen("booklistreport.txt","w");
fwrite(&u,sizeof(u),1,booklistreport);
fclose(booklistreport);
}
void viewpassengers_read()
{
FILE *booklist;
booklist=fopen("booklist.txt","r");
fread(&book,sizeof(book),1,booklist);
fclose(booklist);
FILE *booklistreport;
booklistreport=fopen("booklistreport.txt","r");
fread(&u,sizeof(u),1,booklistreport);
fclose(booklistreport);
}
//-----------------------------------------add train file start---------------------------------------------------
void awrite()
{
FILE *train_details;
train_details = fopen("train_details.txt","w");
fwrite(&add,sizeof(add),1,train_details);
fclose(train_details);
FILE *train_report;
train_report = fopen("train_report.txt","w");
fwrite(&k,sizeof(k),1,train_report);
fclose(train_report);
}
void aread()
{
FILE *train_details;
train_details = fopen("train_details.txt","r");
fread(&add,sizeof(add),1,train_details);
fclose(train_details);
FILE *train_report;
train_report = fopen("train_report.txt","r");
fread(&k,sizeof(k),1,train_report);
fclose(train_report);
}
//----------------------------------------------------file close----------------------------------------------
//----------------------------------------------------program close----------------------------------------
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "random_cache.h"
//
// A simple data store with cache
//
#define DATA_SIZE 1000
#define CACHE_SIZE 10
//
// Data is stored in array data[]
//
float data[DATA_SIZE];
int nhits = 0;
int nmisses = 0;
CACHE *cache;
// initialize the data array
void init() {
int i;
// initialize data
for (i = 0; i < DATA_SIZE; i++) {
data[i] = ((float)i)/2.0;
}
// create cache
cache = cache_new(CACHE_SIZE);
}
// get the ith data value
float get(int i) {
if (i < 0 || i >= DATA_SIZE) {
fprintf(stderr, "get: no data element %d\n", i);
exit(EXIT_FAILURE);
}
float x = cache_lookup(cache, i);
if (x >= 0) {
// cache hit
nhits++;
return x;
} else {
// cache miss
nmisses++;
x = data[i];
cache_insert(cache, i, x);
return data[i];
}
}
// set the ith data value to x
void set(int i, float x) {
if (i < 0 || i >= DATA_SIZE) {
fprintf(stderr, "set: no data element %d\n", i);
exit(EXIT_FAILURE);
}
data[i] = x;
// clear cache entry
cache_clear(cache, i);
}
// simulate a lot of data accesses
int main(int argc, char *argv[]) {
// simulation parameters
int num_accesses = 100000;
int dist_size = 10;
int move_size1[] = {-3,-2,-1,0,0,0,0,1,2,3};
int move_size2[] = {-5,-4,-3,-2,-1,1,2,3,4,5};
init();
int i,j,delta;
j = 0;
for (i = 0; i < num_accesses; i++) {
// randomly get a new data element j to access, based
// on a change from the last element that was accessed
delta = move_size1[rand() % dist_size];
j += delta;
if (j < 0) {
j = 0;
} else if (j >= DATA_SIZE) {
j = DATA_SIZE - 1;
}
get(j);
}
printf("Hits: %d\n", nhits);
printf("Miss: %d\n", nmisses);
exit(0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#define to_str(XX) (#XX)
void perform (const char buf[80]) {
const int size = strnlen (buf, 80);
for (int i = 0; i < size; i++) printf ("%c", buf[i]);
printf ("\nrest:\n");
for (int i = size; i < 80; i++) printf ("%i", buf[i]);
}
int main (void) {
const int blackVal = 10;
const char buf[] = "blackVal";
const char str[] = to_str(blackVaL);
printf ("buf>\t%s\nstr>\t%s\n", buf, str);
printf ("s1>\t%i\ts2>\t%i\n", sizeof(buf), strlen(buf));
perform (to_str(blackVal));
return 0;
}
|
C
|
//
// BMMeasurementBuffer.c
// AudioFiltersXcodeProject
//
// Created by Hans on 11/3/20.
// This file is public domain. No restrictions.
//
#include "BMMeasurementBuffer.h"
#include "Constants.h"
#include <stdlib.h>
#include <Accelerate/Accelerate.h>
void BMMeasurementBuffer_init(BMMeasurementBuffer *This, size_t lengthInSamples){
TPCircularBufferInit(&This->buffer, (uint32_t)lengthInSamples*sizeof(float)*2);
uint32_t bytesAvailable;
float *head = TPCircularBufferHead(&This->buffer, &bytesAvailable);
assert(bytesAvailable > lengthInSamples * sizeof(float));
vDSP_vclr(head, 1, lengthInSamples);
TPCircularBufferProduce(&This->buffer, (uint32_t)(lengthInSamples*sizeof(float)));
}
void BMMeasurementBuffer_free(BMMeasurementBuffer *This){
TPCircularBufferCleanup(&This->buffer);
}
void BMMeasurementBuffer_inputSamples(BMMeasurementBuffer *This,
const float* input,
size_t numSamples){
// We set the desired buffer length at init time and then we always consume
// as many bytes as we produce after that.
while(numSamples > 0){
// check how much space is available
uint32_t spaceAvailable;
TPCircularBufferHead(&This->buffer, &spaceAvailable);
// how many samples can we write?
size_t samplesWriting = BM_MIN(spaceAvailable,numSamples);
uint32_t bytesWriting = (uint32_t)(numSamples * sizeof(float));
// write into the buffer
TPCircularBufferProduceBytes(&This->buffer, input, bytesWriting);
// consume as many bytes as we just wrote
TPCircularBufferConsume(&This->buffer, bytesWriting);
numSamples -= samplesWriting;
}
}
float* BMMeasurementBuffer_getCurrentPointer(BMMeasurementBuffer *This){
uint32_t spaceAvailable;
float* output = TPCircularBufferHead(&This->buffer, &spaceAvailable);
return output;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int MaxOfSum(int *arr, int sz, int *idx_min, int *idx_max)
{
int *dp = (int *)malloc(sz * sizeof(int));
memset(dp, 0, sz * sizeof(int));
for(int i = 0; i < sz; i++)
{
if(i == 0)
{
dp[i] = arr[i];
}
else
{
dp[i] = dp[i - 1] + arr[i];
}
}
int max = 0;
//int idx_min = 0;
//int idx_max = 0;
for(int i = 0; i < sz; i++)
{
int min = INT_MAX;
for(int j = 0; j <= i; j++)
{
if(dp[j] < min)
{
min = dp[j];
*idx_min = j;
}
}
if(dp[i] - min > max)
{
max = dp[i] - min;
*idx_max = i;
}
}
return max;
}
int main(int argc, char *argv[])
{
int arr[] = {1,-2,3,10,-4,7,2,-5};
int size = sizeof(arr)/sizeof(int);
int idx_min = 0;
int idx_max = 0;
int r = MaxOfSum(arr, size, &idx_min, &idx_max);
printf("max = %d, idx_min = %d, idx_max = %d\n", r, idx_min, idx_max);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_makestr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amurakho <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/14 12:24:29 by amurakho #+# #+# */
/* Updated: 2018/04/14 12:24:31 by amurakho ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char **ft_makestr(int word_count, char **new_str, char const *s, char c)
{
int first;
int len;
int counter;
first = ft_wordlen(s, c, 0, 1);
len = ft_wordlen(s, c, first, 0);
counter = 0;
*new_str = (char*)malloc(sizeof(char) * (len + 1));
new_str[counter] = ft_strsub(s, first, len);
new_str[counter][len] = '\0';
len = len + first;
counter++;
while (counter != word_count)
{
first = ft_wordlen(s, c, len, 1);
len = ft_wordlen(s, c, first, 0);
new_str[counter] = (char*)malloc(sizeof(char) * (len + 1));
new_str[counter] = ft_strsub(s, first, len);
new_str[counter][len] = '\0';
len = len + first;
counter++;
}
new_str[counter] = NULL;
return (new_str);
}
|
C
|
//
// stickman.c
// Fighting Game
//
// Created by Daniel Keller on 9/1/16.
// Copyright © 2016 Daniel Keller. All rights reserved.
//
#include "character_internal.h"
#include "objects/stickman.h"
#include "engine.h"
#include <math.h>
#include <assert.h>
enum stickman_states {
top, bottom, overhead, forward, block,
top_step, bottom_step,
swing, swingup,
lift, unlift, big_swing_1, big_swing_2,
lunge, unlunge, lunge_recover,
poke, drop, poke_recover,
hi_block, lo_block, hi_dodge, lo_dodge,
hi_unblock, lo_unblock,
NUM_STICKMAN_STATES
};
static const float speed = .015;
static const float dodge_dist = .3;
#if FAST_ATTACK
#define UP_FRAMES 7
#define DN_FRAMES 9
#else
#define DN_FRAMES 12
#define UP_FRAMES 13
#endif
//For attacks that give defense/momentum buffs, used symmetrically:
//If the attack is before the midpoint of the animation, advantage goes to the
//first player. After the midpoint, it goes to the second. If it is at the midpoint
//either both attacks land or neither.
//To make dodging make sense, the player must be stationary or slow during attacks
// frames next speed balance hi lo
static const struct state states[NUM_STICKMAN_STATES] = {
[top] = {40, top, 0, {10, {{8, MIDDLE}, {0, WEAK}}}},
[top_step] = {7, top, speed, {10, {{8, MIDDLE}, {0, WEAK}}}},
[bottom] = {40, bottom, 0, {8, {{0, WEAK}, {8, MIDDLE}}}},
[bottom_step] = {7, bottom, speed, {8, {{0, WEAK}, {8, MIDDLE}}}},
[swing] = {DN_FRAMES, bottom, 0, {5, {{10, HEAVY}, {0, WEAK}}}},
[swingup] = {DN_FRAMES, top, 0, {20, {{0, WEAK}, {10, HEAVY}}}},
#define UNSTEADY {4, {{0, WEAK}, {0, WEAK}}}
[lift] = {10, overhead, 0, UNSTEADY},
[unlift] = {6, top, 0, UNSTEADY},
[overhead] = {40, overhead, 0, UNSTEADY},
[big_swing_1] = {4, big_swing_2, 0, UNSTEADY},
[big_swing_2] = {7, bottom, 0, {5, {{10, HEAVY}, {0, WEAK}}}},
//Can't have knockback here, otherwise the drop-punish is too weak
#define REACHING {50, {{0, WEAK}, {0, WEAK}}}
[lunge] = {4, lunge_recover, speed*20./4., REACHING},
[lunge_recover] = {6, forward, 0, REACHING},
[forward] = {40, forward, 0, REACHING},
[poke] = {4, poke_recover, 0, REACHING},
[poke_recover] = {6, forward, 0, REACHING},
[unlunge] = {5, bottom, 0, REACHING},
//Knockback would look weird here
[drop] = {30, top, 0, {50, {{0, WEAK}, {0, WEAK}}}},
#define BLOCKED {10, {{20, HEAVY}, {20, HEAVY}}}
#define UNBLOCKED {10, {{0, WEAK}, {0, WEAK}}}
[hi_block] = {3, block, 0, BLOCKED},
[lo_block] = {5, block, 0, BLOCKED},
[hi_dodge] = {3, block, -dodge_dist/3., BLOCKED},
[lo_dodge] = {5, block, -dodge_dist/5., BLOCKED},
[block] = {6, hi_unblock, 0, BLOCKED},
[hi_unblock] = {5, top, 0, UNBLOCKED},
[lo_unblock] = {5, bottom, 0, UNBLOCKED},
};
static const frame_t cancel_frames[NUM_STICKMAN_STATES] = {
[swing] = 4, [swingup] = 6,
[lo_block] = 3, [hi_block] = 3,
[lift] = 5, [big_swing_1] = 4,
};
//Attacks should obviously come after the cancel frame.
static struct attack
// frame target min- range damage knock force
down_attack = {6, HI, .2, .6, 14, 15, MIDDLE},
up_attack = {7, LO, .2, .6, 10, 30, MIDDLE},
overhead_attack = {1, HI, .2, .6, 20, 20, HEAVY},
lunge_attack = {4, LO, .4, .8, 10, 0, MIDDLE},
poke_attack = {2, LO, .7, .8, 8, 0, LIGHT};
//Note that new actions are considered to start epsilon after the previous frame,
//as opposed to on the start of the next frame. (the previous frame is stored in anim_start)
//So the states and transitions for a 2-frame state look like this:
// _____#-----=-----=.....@
// anim_start ^ +1 ^ +2 ^
// where '=' are calls to _actions() in the '-' state
int stickman_actions(struct stickman* sm)
{
struct character* c = sm->character;
assert(cancel_frames[c->prev.state] <= states[c->prev.state].frames
&& "Cancel frame is after the end of the state");
frame_t frame = game_time.frame - c->anim_start;
int is_last_frame = frame == states[c->prev.state].frames;
int is_cancel_frame = frame == cancel_frames[c->prev.state];
//Remember not to call shift_button_press until we're really ready to use the input
switch (c->prev.state) {
case top:
if (c->buttons.fwd.down)
goto_state(c, top_step);
case top_step:
if (shift_button_press(&c->buttons.dodge))
goto_state(c, c->buttons.back.down ? hi_dodge : hi_block);
else if (shift_button_press(&c->buttons.attack))
goto_state(c, swing);
else if (shift_button_press(&c->buttons.special))
goto_state(c, lift);
break;
case swing:
if (is_cancel_frame && shift_button_press(&c->buttons.dodge))
goto_state(c, c->buttons.back.down ? hi_dodge : hi_block);
else if (is_cancel_frame && shift_button_cancel(&c->buttons.attack))
goto_state(c, top);
attack(c, &down_attack);
if (c->next.attack_result & PARRIED) push_effect(&effects, make_parry_effect(sm, .6));
break;
case bottom:
if (c->buttons.fwd.down)
goto_state(c, bottom_step);
case bottom_step:
if (shift_button_press(&c->buttons.dodge))
goto_state(c, c->buttons.back.down ? lo_dodge : lo_block);
else if (shift_button_press(&c->buttons.attack))
goto_state(c, swingup);
else if (shift_button_press(&c->buttons.special))
goto_state(c, lunge);
break;
case swingup:
if (is_cancel_frame && shift_button_press(&c->buttons.dodge))
goto_state(c, c->buttons.back.down ? lo_dodge : lo_block);
else if (is_cancel_frame && shift_button_cancel(&c->buttons.attack))
goto_state(c, bottom);
attack(c, &up_attack);
if (c->next.attack_result & PARRIED) push_effect(&effects, make_parry_effect(sm, .7));
break;
case lift:
if (is_cancel_frame && (shift_button_cancel(&c->buttons.special) || c->buttons.dodge.down))
goto_state(c, top);
break;
case overhead:
if (shift_button_press(&c->buttons.attack))
goto_state(c, big_swing_1);
else if (shift_button_press(&c->buttons.special) || c->buttons.dodge.down)
goto_state(c, unlift);
break;
case big_swing_1:
if (is_cancel_frame && shift_button_cancel(&c->buttons.attack))
goto_state(c, overhead);
break;
case big_swing_2:
attack(c, &overhead_attack);
if (c->next.attack_result & LANDED) push_effect(&effects, make_hit_effect(sm));
if (c->next.attack_result & PARRIED) push_effect(&effects, make_parry_effect(sm, .7));
break;
case lunge:
//Lunge isn't cancellable, otherwise it would be a "run" technique
attack(c, &lunge_attack);
break;
case forward:
if (shift_button_press(&c->buttons.special) || c->buttons.dodge.down)
goto_state(c, unlunge);
else if (shift_button_press(&c->buttons.attack))
goto_state(c, poke);
//fall thru to other state with drop effect
case lunge_recover:
case poke_recover:
if (c->other->prev.attack_result & (KNOCKED | LANDED))
goto_state(c, drop);
break;
case poke:
attack(c, &poke_attack);
break;
case unlift:
case unlunge:
//don't begin dodging if the player dodge-cancelled from a special state
if (shift_button_cancel(&c->buttons.dodge))
shift_button_press(&c->buttons.dodge);
break;
case lo_block:
if (is_cancel_frame && shift_button_cancel(&c->buttons.dodge))
goto_state(c, lo_unblock);
break;
case hi_block:
if (is_cancel_frame && shift_button_cancel(&c->buttons.dodge))
goto_state(c, hi_unblock);
break;
case block:
if (is_last_frame && shift_button_press(&c->buttons.attack))
goto_state(c, lo_unblock);
break;
default:
break;
}
next_state(c);
move_character(c);
return 0;
}
BINDABLE(stickman_actions, struct stickman)
static animation_t animations[NUM_STICKMAN_STATES] = {
[top] = &stickman_top, [bottom] = &stickman_bottom,
[top_step] = &stickman_step_top, [bottom_step] = &stickman_step_bottom,
[swing] = &stickman_swing, [swingup] = &stickman_swing_up,
[lift] = &stickman_lift, [overhead] = &stickman_overhead, [unlift] = &stickman_unlift,
[big_swing_1] = &stickman_big_swing, [big_swing_2] = &stickman_big_swing,
[hi_block] = &stickman_hi_block, [lo_block] = &stickman_lo_block,
[hi_dodge] = &stickman_hi_dodge, [lo_dodge] = &stickman_lo_dodge,
[block] = &stickman_block, [hi_unblock] = &stickman_hi_unblock, [lo_unblock] = &stickman_lo_unblock,
[lunge] = &stickman_lunge, [lunge_recover] = &stickman_lunge, [unlunge] = &stickman_unlunge,
[forward] = &stickman_forward,
[poke] = &stickman_poke, [poke_recover] = &stickman_forward, [drop] = &stickman_drop,
};
//'frame' is also the number of the previous frame here.
int draw_stickman(struct stickman* sm)
{
struct character* c = sm->character;
int state = c->next.state;
draw_health_bar(c);
const struct animation* anim = animations[state];
float frame = game_time.frame - c->anim_start + game_time.alpha;
if (state == big_swing_2)
frame += states[big_swing_1].frames;
else if (state == lunge_recover)
frame += states[lunge].frames;
else if (anim == &stickman_top || anim == &stickman_bottom
|| anim == &stickman_overhead || anim == &stickman_forward)
frame /= 10.;
flip_fbos(&fbos);
glUseProgram(sm->blur_program.program);
set_character_draw_state(c, &sm->blur_program, stickman, anim, frame);
if (state == swing || state == swingup || state == big_swing_1 || state == big_swing_2)
glUniform1i(sm->attacking_unif, 1);
else
glUniform1i(sm->attacking_unif, 0);
glUniform1f(sm->ground_speed_unif, c->next.ground_pos - c->prev.ground_pos);
draw_blur_object(&sm->object);
glUseProgram(sm->program.program);
set_character_draw_state(c, &sm->program, stickman, anim, frame);
draw_object(&sm->object);
if (learning_mode)
draw_state_indicator(c);
return 0;
}
BINDABLE(draw_stickman, struct stickman)
int free_stickman(struct stickman* sm)
{
struct character* c = sm->character;
free_health_bar(&c->health_bar);
free_state_indicator(&c->state_indicator);
free_program(&sm->hit_effect);
free_program(&sm->parry_effect);
free_object(&sm->object);
free_program(&sm->program);
free_program(&sm->blur_program);
free(sm);
return 0;
}
BINDABLE(free_stickman, struct stickman)
void make_simulation_stickman(struct stickman* sm, character_t* c, character_t* other)
{
sm->character = c;
sm->character->other = other;
c->actions = ref_bind_stickman_actions(sm);
c->states = states;
c->hitbox_width = stickman_hitbox_width;
c->buttons = no_key_events;
c->prev = c->next = (struct character_state){
.ground_pos = -1.f,
.health = 100,
.state = top,
};
goto_state(c, top);
}
void make_stickman(character_t* c, character_t* other, enum direction direction)
{
struct stickman* sm = malloc(sizeof(struct stickman));
make_simulation_stickman(sm, c, other);
c->draw = ref_bind_draw_stickman(sm);
c->free = ref_bind_free_stickman(sm);
c->direction = direction;
make_heath_bar(&c->health_bar, direction);
make_state_indicator(&c->state_indicator);
load_shader_program(&sm->hit_effect, screenspace_vert, blast_frag);
load_shader_program(&sm->parry_effect, particles_vert, color_frag);
make_anim_obj(&sm->object, stickman);
load_shader_program(&sm->program, anim_vert, color_frag);
sm->color_unif = glGetUniformLocation(sm->program.program, "main_color");
glUniform3f(sm->color_unif, 1., 1., 1.);
load_shader_program(&sm->blur_program, stickman_blur_vert, stickman_blur_frag);
sm->attacking_unif = glGetUniformLocation(sm->blur_program.program, "attacking");
sm->ground_speed_unif = glGetUniformLocation(sm->blur_program.program, "ground_speed");
}
|
C
|
/*
** EPITECH PROJECT, 2019
** eval_expr_test_2.c
** File description:
** Will test the return of several expression
*/
#include <criterion/criterion.h>
#include <stdlib.h>
#include "my.h"
Test(eval_expr, simple_addition)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3+3"};
unsigned int size;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "6");
}
Test(eval_expr, simple_addition_w_brackets)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3+(3+3)"};
unsigned int size = 7;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "9");
}
Test(eval_expr, simple_mul)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3*3"};
unsigned int size = 3;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "9");
}
Test(eval_expr, simple_mul_w_brackets)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3+(3*3)"};
unsigned int size = 7;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "12");
}
Test(eval_expr, expr_starting_w_brackets)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"(3*3)"};
unsigned int size = 5;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "9");
}
Test(eval_expr, expr_ending_w_brackets)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3+(3*3)"};
unsigned int size = 7;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "12");
}
Test(eval_expr, simple_exp_w_nested_brackets)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3+(3+(3*3))"};
unsigned int size = 11;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "15");
}
Test(eval_expr, hard_exp_w_nested_brackets)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3*(3+(2*1))"};
unsigned int size = 11;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "15");
}
Test(eval_expr, complex_exp_w_nested_brackets)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3*(3*3+(2*1))"};
unsigned int size = 13;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "33");
}
Test(eval_expr, brackets_with_several_args_w_no_priority)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3*(1+1+1)"};
unsigned int size = 9;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "9");
}
Test(eval_expr, brackets_with_several_args_w_priority)
{
char const *base = "0123456789";
char const *ops ="()+-*/%";
char const str[] = {"3*(1+1*1)"};
unsigned int size = 9;
char *res = eval_expr(base, ops, str, size);
cr_assert_str_eq(res, "6");
}
|
C
|
/*
Copyright (c) 2010, Jeremy Cole <[email protected]>
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 of the License, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <led_charlieplex.h>
#include "led_sequencer.h"
led_sequencer_t *sequencer_global = NULL;
/**
* Dump the current animation sequence as a series of Sequence and Step lines
* using printf. This is used only for debugging (mostly debugging the this
* library itself).
*/
void led_sequencer_dump_sequence()
{
led_sequence_t *sequence;
led_sequence_step_t *step;
for(sequence = sequencer_global->sequence; sequence; sequence = sequence->next)
{
printf_P(PSTR("Sequence 0x%04x, %s\n"),
(uint16_t)sequence, sequence->name);
for(step = sequence->step; step; step = step->next)
{
printf_P(PSTR(" Step 0x%04x, JIT 0x%04x, %i ticks\n"),
(uint16_t)step, (uint16_t)step->jit_function, step->ticks_remaining);
}
}
}
/**
* Interrupt handler for "tick" interrupt set up by led_sequencer_timer_init().
*/
ISR(TIMER0_COMPA_vect)
{
led_sequencer_tick();
}
/**
* Initialize Timer 0 to fire "hz" times per second.
*/
void led_sequencer_timer_init(uint16_t hz)
{
/* Set pre-scaler to /256 */
TCCR0B |= _BV(CS02);
/* Force Output Compare A */
TCCR0B |= _BV(FOC0A);
/* Output Compare Interrupt Enable A */
TIMSK0 |= _BV(OCIE0A);
/* Set initial counter value */
TCNT0 = 0;
/* Set Output Compare Register to aim for 1ms interrupt */
OCR0A = (F_CPU / 256) / hz ;
}
/**
* Initialize the sequencer library, including the timer and memory structures.
*/
led_sequencer_t *led_sequencer_init(uint16_t hz)
{
sequencer_global = malloc(sizeof(led_sequencer_t));
led_sequencer_timer_init(hz);
sequencer_global->matrix = NULL;
sequencer_global->sequence = NULL;
sequencer_global->status = LED_SEQUENCER_HALTED;
return sequencer_global;
}
void led_sequencer_halt()
{
if(sequencer_global)
sequencer_global->status = LED_SEQUENCER_HALTED;
}
void led_sequencer_run()
{
if(sequencer_global)
sequencer_global->status = LED_SEQUENCER_RUNNING;
}
/**
* For a given sequence step, if ticks_remaining has reached zero, free
* the step. Then, if the current step isn't perpetual, subtract a tick
* from the step's ticks_remaining.
*/
void led_sequencer_tick_sequence_step(led_sequence_t *sequence)
{
led_sequence_step_t *free_step;
if(sequence->step->ticks_remaining == 0)
{
if(sequence->step->jit_function
&& ((*sequence->step->jit_function)(sequence->step, LED_SEQUENCER_JIT_EMPTY) == LED_SEQUENCER_JIT_CONTINUE)
&& (sequence->step->ticks_remaining > 0))
goto refilled;
free_step = sequence->step;
sequence->step = sequence->step->next;
free(free_step);
if(sequence->step && sequence->step->jit_function)
(*sequence->step->jit_function)(sequence->step, LED_SEQUENCER_JIT_INITIAL);
}
refilled:
if(sequence->step && sequence->step->ticks_remaining != 0 && sequence->step->ticks_remaining != 0xff)
{
sequence->step->ticks_remaining--;
}
}
/**
* Iterate through all sequences in the global sequence list, for each of them,
* call led_sequencer_tick_sequence_step.
*/
void led_sequencer_tick_sequence()
{
led_sequence_t *sequence;
uint8_t sequence_steps = 0;
for(sequence = sequencer_global->sequence; sequence; sequence = sequence->next)
{
if(sequence->step != NULL)
{
led_sequencer_tick_sequence_step(sequence);
sequence_steps++;
}
}
}
/**
* Progress the animation sequence by one tick, often 1ms, but depends on
* the value 'hz' passed to led_sequencer_init(). Normally called by the
* Timer 0 Output Compare A interrupt (TIMER0_COMPA_vect). This function
* really just does the housekeeping and sanity checking and then calls out
* to led_sequencer_tick_sequence() to do the real work.
*/
void led_sequencer_tick()
{
TCNT0 = 0;
if(sequencer_global && sequencer_global->status == LED_SEQUENCER_RUNNING)
{
led_sequencer_tick_sequence();
}
}
/**
* Play through one cycle of the LEDs which should currently be illuminated.
* Normally this function is called during all spare time in the main loop,
* and most other functions are called between runs of led_sequencer_run() or
* through interrupts.
*/
void led_sequencer_display()
{
led_sequence_t *sequence;
if(sequencer_global->status != LED_SEQUENCER_RUNNING)
return;
for(sequence = sequencer_global->sequence; sequence; sequence = sequence->next)
{
if(sequence->step && sequence->step->type == LED_SEQUENCER_STEP_SHOW)
{
led_charlieplex_set_by_index(sequence->step->matrix->charlieplex, sequence->step->matrix_index);
_delay_us(20);
led_charlieplex_unset_last(sequence->step->matrix->charlieplex);
}
}
}
/**
* Find a matrix in the global matrix list by its name.
*/
led_matrix_t *led_sequencer_find_matrix_by_name(char *matrix_name)
{
led_matrix_t *matrix = sequencer_global->matrix;
for(; matrix != NULL; matrix = matrix->next)
{
if(strcmp(matrix->name, matrix_name) == 0)
return matrix;
}
return NULL;
}
/**
* Push a matrix to the global matrix list.
*/
led_matrix_t *led_sequencer_push_front_matrix(char *matrix_name, led_charlieplex_t *charlieplex)
{
led_matrix_t *matrix;
if((matrix = malloc(sizeof(led_matrix_t))))
{
matrix->name = malloc(strlen(matrix_name)+1);
strcpy(matrix->name, matrix_name);
matrix->charlieplex = charlieplex;
matrix->next = sequencer_global->matrix;
sequencer_global->matrix = matrix;
}
return matrix;
}
/**
* Find a sequence in the global sequence list by name.
*/
led_sequence_t *led_sequencer_find_sequence_by_name(char *sequence_name)
{
led_sequence_t *sequence = sequencer_global->sequence;
for(; sequence != NULL; sequence = sequence->next)
{
if(strcmp(sequence->name, sequence_name) == 0)
return sequence;
}
return NULL;
}
/**
* Add a sequence to the global sequence list, and return a pointer to it.
*/
led_sequence_t *led_sequencer_push_back_sequence(char *sequence_name)
{
led_sequence_t *sequence, *last_sequence;
if((sequence = malloc(sizeof(led_sequence_t))))
{
sequence->name = malloc(strlen(sequence_name)+1);
strcpy(sequence->name, sequence_name);
sequence->step = NULL;
sequence->next = NULL;
}
if(sequencer_global->sequence)
{
for(last_sequence = sequencer_global->sequence; last_sequence->next; last_sequence = last_sequence->next);
last_sequence->next = sequence;
}
else
{
sequencer_global->sequence = sequence;
}
return sequence;
}
void led_sequencer_sequence_push_back_jit(char *sequence_name, led_sequence_step_type_t type, char *matrix_name, led_sequencer_jit_function_t *jit_function)
{
led_sequence_step_t *step;
step = led_sequencer_sequence_push_back_step(sequence_name, type, matrix_name, NULL, 254);
step->jit_function = jit_function;
(*step->jit_function)(step, LED_SEQUENCER_JIT_INITIAL);
}
/**
* Push a step on to the end of a sequence.
*/
led_sequence_step_t *led_sequencer_sequence_push_back_step(char *sequence_name, led_sequence_step_type_t type, char *matrix_name, char *led_name, uint8_t ticks)
{
led_sequence_t *sequence;
led_sequence_step_t *step, *last_step;
if((step = malloc(sizeof(led_sequence_step_t))))
{
sequence = led_sequencer_find_sequence_by_name(sequence_name);
step->type = type;
step->matrix = led_sequencer_find_matrix_by_name(matrix_name);
if(led_name)
{
step->matrix_index = led_charlieplex_find_index_by_name(step->matrix->charlieplex, led_name);
}
step->ticks_remaining = ticks;
step->next = NULL;
if(sequence->step)
{
for(last_step = sequence->step; last_step->next; last_step = last_step->next) {}
last_step->next = step;
}
else
{
sequence->step = step;
}
return step;
}
return NULL;
}
/**
* Modify a step in place within a sequence. This is mostly useful for steps
* with a 'ticks' value of 255 (never ending).
*/
void led_sequencer_sequence_modify_step(led_sequence_step_t *step, char *led_name, uint8_t ticks)
{
step->matrix_index = led_charlieplex_find_index_by_name(step->matrix->charlieplex, led_name);
step->ticks_remaining = ticks;
}
/**
* Clear an entire sequence of any steps remaining.
*/
void led_sequencer_sequence_clear(char *sequence_name)
{
led_sequence_t *sequence;
sequence = led_sequencer_find_sequence_by_name(sequence_name);
for(; sequence->step; sequence->step = sequence->step->next)
{
free(sequence->step);
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
float gastos[12];
int x;
main()
{
for(x=1;x<13;x++)
{
printf("Dame los gastos del mes [%d]: ",x);
scanf("%f",&gastos[x]);
}
for(x=1;x<13;x++)
{
printf("Los gastos almacenados en el mes [%d] son: %.2f\n",x,gastos[x]);
}
getch();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.