language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
//Worst Case Time Complexity: O(n*n)
//Best Case Time Complexity: O(n)
//Average Case Time Complexity: O(n*n)
//Space Complexity: O(1)
#include<stdio.h>
void swap(int *first, int *second)
{
int temp = *first;
*first = *second;
*second = temp;
}
int main()
{
int n,i,j,temp,arr[1000];
printf("\n---Bubble Sorting---\n\n\n");
printf("Enter the Number of Elements = ");
scanf("%d",&n);
printf("Enter %d element \n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{
int flag=0;
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
swap(&arr[j], &arr[j+1]);
flag=1;
}
}
if(flag==0)
break;
}
printf("Sorted list in Ascending order :\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
}
|
C
|
//
// alloc.h
// SortingAlgorithms
//
// Created by Takahiro on 2014/12/24.
// Copyright (c) 2014 Takahiro Ishikawa. All rights reserved.
//
// Reference "C Programming Language (2nd Edition)", Brian Kernighan and Dennis Ritchie.
//
#ifndef __SortingAlgorithms__alloc__
#define __SortingAlgorithms__alloc__
#define ALLOCSIZE 5000000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* strage for alloc */
static char *allocp = allocbuf; /* next free position */
char *alloc(int n); /* return pointer to n characters */
void afree(char *p); /* free strage pointed to by p */
#endif /* defined(__SortingAlgorithms__alloc__) */
|
C
|
/* Practical 9: Variable Scope and Functions
program to take in a value and ouput the cube of that value
Exercise 20 */
/* Joe O'Regan */
/* 26-10-2015 */
#include<stdio.h>
// Global Variables
int input,output;
main() // main is a function
{
getValue();
cube();
getch();
return(0);
} // end of main
// Function: Get Value
getValue()
{
printf("Please Enter Value to be cubed: ");
scanf("%d",&input);
}
// Fuction: Cube
cube()
{
output=input*input*input;
printf("The Cubed Value of %d is %d",input,output);
//return(output);
}
|
C
|
// Copyright (c) 2019 Roland Bernard
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "netio.h"
#include "cipher.h"
#include "hash.h"
error_t net_sendmsg(int sock, const msgbuf_t* msg) {
len_t namelen = strlen(msg->name);
len_t grouplen;
if(msg->group == NULL)
grouplen = 0;
else
grouplen = strlen(msg->group);
len_t totallen = namelen+1; // <id><len><name>\0
if(msg->group != NULL)
totallen += 1+grouplen; // <id><len><name>[@<group>]\0
if(msg->flag & FLAG_MSG_ENC)
totallen += 11; // <id><len>[~:ENCRYPTED]<name>[@<group>]\0
if(msg->flag & FLAG_MSG_TYP)
totallen += 4; // <id><len>[~<ind>:KEY]<name>[@<group>][|TYP]\0
else if(msg->flag & FLAG_MSG_ENT)
totallen += 4; // <id><len>[~<ind>:KEY]<name>[@<group>][|ENT]\0
else if(msg->flag & FLAG_MSG_EXT)
totallen += 4; // <id><len>[~<ind>:KEY]<name>[@<group>][|EXT]\0
else if(msg->flag & FLAG_MSG_IMG)
totallen += 4; // <id><len>[~<ind>:KEY]<name>[@<group>][|IMG]\0
if(msg->data != NULL)
totallen += msg->data_len; // <id><len>[~<ind>:KEY]<name>[@<group>][|TYP]\0[<data>]
uint8_t* buffer = (uint8_t*)malloc(sizeof(id_t)+sizeof(len_t)+2*totallen+sizeof(data256_t)); // +2*sizeof(data256_t) to be sure everything fits even after encryption
len_t buflen = 0;
len_t enc_start;
if(msg->flag & FLAG_MSG_ENC) /* add indicator and encryption string */ {
buffer[sizeof(id_t)+sizeof(len_t)+buflen++] = '~';
enc_start = buflen;
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, ":ENCRYPTED", 10);
buflen += 10;
}
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, msg->name, namelen); /* add user name */
buflen += namelen;
if(msg->group != NULL) /* add group name */ {
buffer[sizeof(id_t)+sizeof(len_t)+buflen++] = '@';
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, msg->group, grouplen);
buflen += grouplen;
}
if(msg->flag & FLAG_MSG_TYP) /* add typping identifier */ {
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, "|TYP", 4);
buflen += 4;
} else if(msg->flag & FLAG_MSG_ENT) /* add enter identifier */ {
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, "|ENT", 4);
buflen += 4;
} else if(msg->flag & FLAG_MSG_EXT) /* add exit identifier */ {
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, "|EXT", 4);
buflen += 4;
} else if(msg->flag & FLAG_MSG_IMG) /* add image identifier */ {
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, "|IMG", 4);
buflen += 4;
}
buffer[sizeof(id_t)+sizeof(len_t)+buflen++] = 0;
if(msg->data != NULL) {
memcpy(buffer+sizeof(id_t)+sizeof(len_t)+buflen, msg->data, msg->data_len); /* Add data */
buflen += msg->data_len;
}
if(msg->flag & FLAG_MSG_ENC) /* encrypt the data after the indicator */ {
buflen = cipher_encryptdata(buffer+sizeof(id_t)+sizeof(len_t)+enc_start, buffer+sizeof(id_t)+sizeof(len_t)+enc_start, buflen-enc_start, msg->ind, msg->key)+enc_start;
}
for(len_t i = 0; i < sizeof(id_t); i++) /* add the id of the client at the start */
buffer[i] = (msg->cid >> (i*8)) & 0xff;
for(len_t i = 0; i < sizeof(len_t); i++) /* add the length of the message at the start after the id */
buffer[sizeof(id_t)+i] = (buflen >> (i*8)) & 0xff;
/* send the message */
len_t len_send = 0;
while(len_send < buflen+sizeof(len_t)) {
len_t tmp_len = send(sock, buffer+len_send, sizeof(id_t)+sizeof(len_t)+buflen-len_send, 0);
if(tmp_len == -1) {
free(buffer);
return ERROR;
} else
len_send += tmp_len;
}
free(buffer);
return OK;
}
// no field in msg will be freed by this function!
error_t net_recvmsg(int sock, msgbuf_t* msg) {
uint8_t bufferhead[sizeof(id_t)+sizeof(len_t)];
len_t len = recv(sock, bufferhead, sizeof(id_t)+sizeof(len_t), MSG_DONTWAIT); /* recv the id and length of the message */
if(len >= 1) {
len_t tmp_len = recv(sock, bufferhead+len, sizeof(id_t)+sizeof(len_t)-len, MSG_WAITALL); /* recv the rest of the id and length */
len += tmp_len;
if(len == sizeof(id_t)+sizeof(len_t)) {
msg->cid = 0;
for(len_t i = 0; i < sizeof(id_t); i++)
msg->cid |= (id_t)bufferhead[i] << (i*8);
len_t buflen = 0;
for(len_t i = 0; i < sizeof(len_t); i++)
buflen |= (len_t)bufferhead[sizeof(id_t)+i] << (i*8);
uint8_t* buffer = (uint8_t*)malloc(buflen);
tmp_len = recv(sock, buffer, buflen, MSG_WAITALL); /* recv the actual message */
if(tmp_len == buflen) {
msg->flag = 0;
char* msgre = (char*)buffer;
if(*msgre == '~') /* the message is encrypted */ {
msgre++;
buflen = cipher_decryptdata((uint8_t*)msgre, (uint8_t*)msgre, buflen-1, msg->ind, msg->key);
if(strncmp(msgre, ":ENCRYPTED", 10) != 0) /* couldn't decrypt the data */ {
free(buffer);
return ENC_DATA;
}
msgre += 10;
buflen -= 10;
msg->flag |= FLAG_MSG_ENC;
}
/* extract the header information */
len_t headlen = strlen(msgre);
if(headlen >= buflen) {
free(buffer);
return ERROR;
}
len_t atpos = strfndchr(msgre, '@');
len_t pipepos = strfndchr(msgre, '|');
len_t datalen = buflen-headlen-1;
len_t namelen;
if(atpos != -1)
namelen = atpos;
else if(pipepos != -1)
namelen = pipepos;
else
namelen = headlen;
len_t grouplen;
if(atpos == -1)
grouplen = 0;
else if(pipepos != -1)
grouplen = pipepos-atpos-1;
else
grouplen = headlen-atpos-1;
/* fill the message buffer */
msg->name = (char*)malloc(namelen+1);
memcpy(msg->name, msgre, namelen);
msg->name[namelen] = 0;
if(grouplen != 0) {
msg->group = (char*)malloc(grouplen+1);
memcpy(msg->group, msgre+atpos+1, grouplen);
msg->group[grouplen] = 0;
} else
msg->group = NULL;
if(pipepos != -1 && strcmp(msgre+pipepos+1, "TYP") == 0) /* the message only contains typing information */
msg->flag |= FLAG_MSG_TYP;
else if(pipepos != -1 && strcmp(msgre+pipepos+1, "ENT") == 0) /* the message only contains enter information */
msg->flag |= FLAG_MSG_ENT;
else if(pipepos != -1 && strcmp(msgre+pipepos+1, "EXT") == 0) /* the message only contains exit information */
msg->flag |= FLAG_MSG_EXT;
else if(pipepos != -1 && strcmp(msgre+pipepos+1, "IMG") == 0) /* the message is a image */
msg->flag |= FLAG_MSG_IMG;
if(datalen == 0) {
msg->data_len = 0;
msg->data = NULL;
} else {
msg->data_len = datalen;
msg->data = (char*)malloc(datalen);
memcpy(msg->data, msgre+headlen+1, datalen);
}
free(buffer);
} else {
free(buffer);
if(tmp_len == 0) {
return CONNECTION_CLOSED;
} else {
return ERROR;
}
}
} else if(tmp_len == 0)
return CONNECTION_CLOSED;
else /* if(tmp_len == -1) */
return ERROR;
} else if(len == 0)
return CONNECTION_CLOSED;
else /* if(len == -1) */
return NO_DATA;
return OK;
}
|
C
|
#ifndef QUEUE_H
#define QUEUE_H
#include<stdlib.h>
#include<stdio.h>
typedef int Queue_ElemType;
typedef struct Node
{
Queue_ElemType data;
struct Node *next;
}QueueNode,*PQueueNode;
typedef struct
{
QueueNode *front;
QueueNode *rear;
}Queue,*PQueue;
void initQueue(Queue *pq);
void destroyQueue(Queue *pq);
void clearQueue(Queue *pq);
int emptyQueue(Queue q);
int QueueLength(Queue q);
Queue_ElemType getHead(Queue q);
void enQueue(Queue *pq,Queue_ElemType elem);
Queue_ElemType deQueue(Queue *pq);
//assist function
void createQueue(Queue *pq,Queue_ElemType array[],int n);
void displayQueue(Queue q);
#endif
|
C
|
#ifndef __UTILS_BITS_H__
#define __UTILS_BITS_H__
/*
*----------------------------------------------------------------------------
* Miscellaneous defines
*----------------------------------------------------------------------------
*/
#define BIT_MSK(b) (1 << (b))
#define BIT0 (BIT_MSK(0))
#define BIT1 (BIT_MSK(1))
#define BIT2 (BIT_MSK(2))
#define BIT3 (BIT_MSK(3))
#define BIT4 (BIT_MSK(4))
#define BIT5 (BIT_MSK(5))
#define BIT6 (BIT_MSK(6))
#define BIT7 (BIT_MSK(7))
#define BIT8 (BIT_MSK(8))
#define BIT9 (BIT_MSK(9))
#define BIT10 (BIT_MSK(10))
#define BIT11 (BIT_MSK(11))
#define BIT12 (BIT_MSK(12))
#define BIT13 (BIT_MSK(13))
#define BIT14 (BIT_MSK(14))
#define BIT15 (BIT_MSK(15))
#define BIT16 (BIT_MSK(16))
#define BIT17 (BIT_MSK(17))
#define BIT18 (BIT_MSK(18))
#define BIT19 (BIT_MSK(19))
#define BIT20 (BIT_MSK(20))
#define BIT21 (BIT_MSK(21))
#define BIT22 (BIT_MSK(22))
#define BIT23 (BIT_MSK(23))
#define BIT24 (BIT_MSK(24))
#define BIT25 (BIT_MSK(25))
#define BIT26 (BIT_MSK(26))
#define BIT27 (BIT_MSK(27))
#define BIT28 (BIT_MSK(28))
#define BIT29 (BIT_MSK(29))
#define BIT30 (BIT_MSK(30))
#define BIT31 (BIT_MSK(31))
/* bit map related macros */
#ifndef setbit
#ifndef NBIT
#define NBIT 32 /* 32 bits per byte */
#endif /* #ifndef NBIT */
#define setbit(reg, pos) (((u32 *)reg)[(pos) / NBIT] |= 1 << ((pos) % NBIT))
#define clrbit(reg, pos) (((u32 *)reg)[(pos) / NBIT] &= ~(1 << ((pos) % NBIT)))
#define isset(reg, pos) (((const u32 *)reg)[(pos) / NBIT] & (1 << ((pos) % NBIT)))
#define isclr(reg, pos) ((((const u32 *)reg)[(pos) / NBIT] & (1 << ((pos) % NBIT))) == 0)
#define MAKE_MASK(pos,len) (((0x1 << len) -1) <<pos) //MAKE_MASK(4,2) 0x0000110000
#define SET_BIT2VAL(dst,val,start,end) ( ((val<<start)& MAKE_MASK(start,(end-start+1))) | (dst & ~MAKE_MASK(start,(end-start+1)) ) )
#define GET_BITS(dst,start,end) ((dst & (MAKE_MASK(start,(end-start+1)))) >>start )
#endif /* setbit */
#define isbitset(a, i) (((a) & (1 << (i))) != 0)
#endif
|
C
|
/*
用数组存或者直接map存
*/
bool canConstruct(string ransomNote, string magazine) {
if (magazine.length()==0)
{
if (ransomNote.length() == 0)
return true;
else
return false;
}
unordered_map<char, int> mmap;
for (int i = 0; i < magazine.size(); i++)
{
mmap[magazine[i]]++;
}
for (int i = 0; i < ransomNote.size(); i++)
{
if (mmap[ransomNote[i]]==0)
{
return false;
}
else
{
mmap[ransomNote[i]]--;
}
}
return true;
}
|
C
|
#include<stdio.h>
int main()
{
int N,a[10],i,t,s;
scanf("%d",&N);
for(i=1;i<=N;i++)
{
scanf("%d",&a[i]);
}
t=s=a[1];
for(i=1;i<=N;i++)
{
if(t>a[i])
{
t=a[i];
}
if(s<a[i])
{
s=a[i];
}
}
printf("%d %d",t,s);
return 0;
}
|
C
|
#include <stdio.h>
typedef struct
{
int id;
char name[30];
} employee;
int main(int argc, char** argv)
{
employee e1 = {1, "Simon"};
printf("ID: %d, Name: %s\n", e1.id, e1.name);
printf("Size of employee: %zu, size of employee.id: %zu, size of employee.name: %zu\n", sizeof(e1), sizeof(e1.id), sizeof(e1.name));
return 0;
}
|
C
|
#include "fast_pcst.h"
int comp(const void *a, const void *b) {
return (*(int *) a - *(int *) b);
}
typedef struct {
int n;
int m;
int root;
double *costs;
EdgePair *edges;
double *prizes;
} Data;
void print_result(Array *result_nodes, Array *result_edges, int number) {
qsort(result_edges->array, (size_t) result_edges->size, sizeof(int), comp);
qsort(result_nodes->array, (size_t) result_nodes->size, sizeof(int), comp);
printf(" ------------------- test %d-result ------------------- \n",
number);
printf("nodes: ");
for (int i = 0; i < result_nodes->size; i++) {
printf(" %d", result_nodes->array[i]);
}
printf("\nedges: ");
for (int i = 0; i < result_edges->size; i++) {
printf(" %d", result_edges->array[i]);
}
printf("\n");
}
int
_is_passed(Array *result_nodes, Array *result_edges, const int *_result_nodes,
const int *_result_edges, int n_, int m_) {
for (int i = 0; i < result_nodes->size; i++) {
if (result_nodes->array[i] != _result_nodes[i]) {
return 0;
}
}
if (result_nodes->size != n_) {
return 0;
}
if (result_edges->size != m_) {
return 0;
}
for (int i = 0; i < result_edges->size; i++) {
if (result_edges->array[i] != _result_edges[i]) {
return 0;
}
}
printf("test passed!\n");
return 1;
}
int test_1() {
int root = 0, target_num_active_clusters = 0, n = 3, m = 2, verbose = 0;
PruningMethod pruning = NoPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int _result_nodes[] = {0, 1, 2}, _result_edges[] = {0, 1};;
int edge_u[] = {0, 1};
int edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
double prizes[] = {0., 5., 6.};
double costs[] = {3., 4.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 1);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
3, 2);
}
int test_2() {
int root = -1, target_num_active_clusters = 1, n = 3, m = 2, verbose = 0;
PruningMethod pruning = NoPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int _result_nodes[] = {1, 2}, _result_edges[] = {1};;
int edge_u[] = {0, 1}, edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
double prizes[] = {0., 5., 6.};
double costs[] = {3., 4.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 2);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
2, 1);
}
int test_3() {
int root = -1, target_num_active_clusters = 1, n = 3, m = 2, verbose = 0;
PruningMethod pruning = GWPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int _result_nodes[] = {1, 2}, _result_edges[] = {1};;
int edge_u[] = {0, 1}, edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
double prizes[] = {0., 5., 6.};
double costs[] = {3., 4.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 3);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
2, 1);
}
int test_4() {
int root = -1, target_num_active_clusters = 1, n = 3, m = 2, verbose = 0;
PruningMethod pruning = StrongPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int edge_u[] = {0, 1}, edge_v[] = {1, 2};
int _result_nodes[] = {1, 2}, _result_edges[] = {1};;
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
double prizes[] = {0., 5., 6.};
double costs[] = {3., 4.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 4);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
2, 1);
}
int test_5() {
int root = 0, target_num_active_clusters = 0, n = 4, m = 3, verbose = 0;
PruningMethod pruning = NoPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * 4);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * 4);
int edge_u[] = {0, 1, 2}, edge_v[] = {1, 2, 3};
int _result_nodes[] = {0, 1, 2, 3}, _result_edges[] = {1, 2};;
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
double prizes[] = {10., 0., 1., 10.};
double costs[] = {10., 4., 3.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 5);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
4, 2);
}
int test_6() {
int root = 0, target_num_active_clusters = 0, n = 4, m = 3, verbose = 0;
PruningMethod pruning = GWPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * 4);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * 4);
int edge_u[] = {0, 1, 2};
int edge_v[] = {1, 2, 3};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0}, _result_edges[] = {};
double prizes[] = {10., 0., 1., 10.};
double costs[] = {10., 4., 3.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 6);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
1, 0);
}
int test_7() {
int root = 0, target_num_active_clusters = 0, n = 4, m = 3, verbose = 0;
PruningMethod pruning = NoPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int edge_u[] = {0, 1, 2};
int edge_v[] = {1, 2, 3};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 1, 2, 3}, _result_edges[] = {0, 1, 2};
double prizes[] = {10., 10., 1., 10.};
double costs[] = {10., 6., 5.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 7);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
4, 3);
}
int test_8() {
int root = 0, target_num_active_clusters = 0, n = 4, m = 3, verbose = 0;
PruningMethod pruning = GWPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int edge_u[] = {0, 1, 2};
int edge_v[] = {1, 2, 3};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 1, 2, 3}, _result_edges[] = {0, 1, 2};
double prizes[] = {10., 10., 1., 10.};
double costs[] = {10., 6., 5.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 8);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
4, 3);
}
int test_9() {
int root = 0, target_num_active_clusters = 0, n = 3, m = 2, verbose = 0;
PruningMethod pruning = NoPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * 4);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * 4);
int edge_u[] = {0, 1};
int edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 1, 2}, _result_edges[] = {1};
double prizes[] = {10., 3., 3.};
double costs[] = {100., 2.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 9);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
3, 1);
}
int test_10() {
int root = 0, target_num_active_clusters = 0, n = 3, m = 2, verbose = 0;
PruningMethod pruning = GWPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int edge_u[] = {0, 1};
int edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0}, _result_edges[] = {};
double prizes[] = {10., 3., 3.};
double costs[] = {100., 2.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 10);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
1, 0);
}
int test_11() {
int root = -1, target_num_active_clusters = 2, n = 3, m = 2, verbose = 0;
PruningMethod pruning = GWPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int edge_u[] = {0, 1};
int edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 1, 2}, _result_edges[] = {1};
double prizes[] = {10., 3., 3.};
double costs[] = {100., 2.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 11);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
3, 1);
}
int test_12() {
int root = -1, target_num_active_clusters = 1, n = 3, m = 2, verbose = 0;
PruningMethod pruning = GWPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int edge_u[] = {0, 1};
int edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0}, _result_edges[] = {};
double prizes[] = {10., 3., 3.};
double costs[] = {100., 2.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 12);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
1, 0);
}
int test_13() {
int root = -1, target_num_active_clusters = 2, n = 4, m = 3, verbose = 0;
PruningMethod pruning = GWPruning;
double eps = 1e-6;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->array = malloc(sizeof(int) * n);
int edge_u[] = {0, 1, 2};
int edge_v[] = {1, 2, 3};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (int i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 2, 3}, _result_edges[] = {2};
double prizes[] = {10., 0., 6., 6.};
double costs[] = {100., 2., 5.};
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 13);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
3, 1);
}
int test_14() {
int i, root = 3, target_num_active_clusters = 0;
int n = 10, m = 24, verbose = 0;
int edge_u[] = {0, 1, 2, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4,
4, 4, 5, 6};
int edge_v[] = {1, 2, 3, 9, 2, 3, 5, 9, 3, 5, 7, 8, 3, 4, 5, 6, 7, 8, 9, 5,
6, 7, 8, 8};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {3, 4, 6, 7, 8}, _result_edges[] = {16, 20, 21, 23};
double prizes[] = {0.032052554364677466, 0.32473378289799926,
0.069699345546302638, 0,
0.74867253235151754, 0.19804330340026255,
0.85430521133171622, 0.83819939651391351,
0.71744625276884877, 0.016798567754083948};
double costs[] = {0.8, 0.8, 0.8800000000000001, 0.8, 0.8,
0.8800000000000001, 0.8,
0.8, 0.8800000000000001, 0.8, 0.8, 0.8,
0.8800000000000001,
0.8800000000000001, 0.8800000000000001,
0.8800000000000001, 0.8800000000000001,
0.8800000000000001, 0.8800000000000001, 0.8, 0.8, 0.8,
0.8, 0.8};
double eps = 1e-6;
PruningMethod pruning = GWPruning;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->size = 0;
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->size = 0;
result_edges->array = malloc(sizeof(int) * n);
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 14);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
5, 4);
}
int test_15() {
int i, root = -1, target_num_active_clusters = 1, n = 8, m = 7, verbose = 0;
int edge_u[] = {0, 1, 2, 3, 4, 5, 6};
int edge_v[] = {1, 2, 3, 4, 5, 6, 7};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 1, 2, 3, 4, 5, 6, 7};
int _result_edges[] = {0, 1, 2, 3, 4, 5, 6};
double prizes[] = {100., 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 100.0};
double costs[] = {0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9};
double eps = 1e-6;
PruningMethod pruning = GWPruning;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->size = 0;
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->size = 0;
result_edges->array = malloc(sizeof(int) * n);
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 15);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
8, 7);
}
int test_16() {
int i, root = -1, target_num_active_clusters = 1;
int n = 5, m = 4, verbose = 0;
int edge_u[] = {0, 0, 2, 3};
int edge_v[] = {1, 2, 3, 4};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {1}, _result_edges[] = {};
double prizes[] = {0., 2.2, 0.0, 0.0, 2.1};
double costs[] = {1.0, 1.0, 1.0, 1.0};
double eps = 1e-6;
PruningMethod pruning = StrongPruning;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->size = 0;
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->size = 0;
result_edges->array = malloc(sizeof(int) * n);
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 16);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
1, 0);
}
int test_17() {
int i, root = -1, target_num_active_clusters = 1;
int n = 5, m = 4, verbose = 0;
int edge_u[] = {0, 0, 2, 3};
int edge_v[] = {1, 2, 3, 4};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 1, 2, 3, 4}, _result_edges[] = {0, 1, 2, 3};
double prizes[] = {0., 2.2, 0.0, 0.0, 2.1};
double costs[] = {1.0, 1.0, 1.0, 1.0};
double eps = 1e-6;
PruningMethod pruning = GWPruning;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->size = 0;
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->size = 0;
result_edges->array = malloc(sizeof(int) * n);
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 17);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
5, 4);
}
int test_18() {
int i, root = -1, target_num_active_clusters = 1;
int n = 3, m = 2, verbose = 0;
int edge_u[] = {0, 1};
int edge_v[] = {1, 2};
EdgePair *edges = malloc(sizeof(EdgePair) * m);
for (i = 0; i < m; i++) {
edges[i].first = edge_u[i];
edges[i].second = edge_v[i];
}
int _result_nodes[] = {0, 1}, _result_edges[] = {0};
double prizes[] = {2., 2., 2.};
double costs[] = {0.0, 5.0};
double eps = 1e-6;
PruningMethod pruning = GWPruning;
Array *result_nodes = malloc(sizeof(Array));
result_nodes->size = 0;
result_nodes->array = malloc(sizeof(int) * n);
Array *result_edges = malloc(sizeof(Array));
result_edges->size = 0;
result_edges->array = malloc(sizeof(int) * n);
PCST *pcst = make_pcst(edges, prizes, costs, root,
target_num_active_clusters, eps, pruning, n, m,
verbose);
run_pcst(pcst, result_nodes, result_edges);
print_result(result_nodes, result_edges, 18);
return _is_passed(result_nodes, result_edges, _result_nodes, _result_edges,
2, 1);
}
void test_on_simu() {
int num_passed = 0;
num_passed += test_1() + test_2() + test_3() + test_4();
num_passed += test_5() + test_6() + test_7() + test_8();
num_passed += test_9() + test_10() + test_11() + test_12();
num_passed += test_13() + test_14() + test_15() + test_16();
num_passed += test_17() + test_18();
printf("total number of passed: %d / 18\n", num_passed);
}
int main() {
test_on_simu();
return (EXIT_SUCCESS);
}
|
C
|
#include <esp_sleep.h>
#include "dexcom_g6_reader.h"
#include "esp32/rom/crc.h"
#define BUFFER_SIZE 420 // 28 bytes * 15
#define BUFFER_TYPE RINGBUF_TYPE_NOSPLIT
RTC_DATA_ATTR StaticRingbuffer_t buffer_struct;
RTC_DATA_ATTR uint8_t buffer_storage[BUFFER_SIZE];
RTC_DATA_ATTR RingbufHandle_t rbuf_handle;
RTC_DATA_ATTR uint32_t last_sequence = 0;
static const char *tag_stg = "[Dexcom-G6-Reader][storage]";
void
dgr_init_ringbuffer() {
rbuf_handle = xRingbufferCreateStatic(BUFFER_SIZE, BUFFER_TYPE, (uint8_t*)&buffer_storage, &buffer_struct);
}
/**
* Saves the given values in the ringbuffer
*
* @param timestamp Timestamp of a glucose reading
* @param glucose Glucose value of a reading
* @param calibration_state Calibration state of a reading
* @param trend Trend value of a reading
*/
void
dgr_save_to_ringbuffer(uint32_t timestamp, uint16_t glucose, uint8_t calibration_state, uint8_t trend) {
size_t free_size = xRingbufferGetCurFreeSize(rbuf_handle);
// 8 bytes data + 8 byte header
if(free_size >= 16) {
uint8_t in[8];
write_u32_le(in, timestamp);
write_u16_le(&in[4], glucose);
in[6] = calibration_state;
in[7] = trend;
UBaseType_t res = xRingbufferSend(rbuf_handle, in, 8, pdMS_TO_TICKS(5000));
if (res != pdTRUE) {
ESP_LOGE(tag_stg, "Error while writing into ringbuffer. rc = 0x%04x", res);
dgr_error();
}
} else {
ESP_LOGE(tag_stg, "Ringbuffer is full. Printing debug info.");
dgr_print_rbuf(false);
//TODO: maybe do something more useful
}
}
/**
* After a glucose reading was received, this function checks if backfill is needed.
*
* @param conn_handle Connection handle
* @param sequence Sequence number of the last glucose reading
*/
void
dgr_check_for_backfill_and_sleep(uint16_t conn_handle, uint32_t sequence) {
// dont do backfill after the first reading
uint32_t sequence_diff = last_sequence == 0 ? 0 : sequence - last_sequence;
last_sequence = sequence;
if(sequence_diff == 1) {
// tear down bt?
ESP_LOGI(tag_stg, "No Backfill necessary. Going to deep sleep for %d seconds", SLEEP_BETWEEN_READINGS);
dgr_print_rbuf(true);
esp_deep_sleep(SLEEP_BETWEEN_READINGS * 1000000); // time is in microseconds
} else if(sequence_diff > 1 || sequence_diff == 0) {
// enable backfill notifications
ESP_LOGI(tag_stg, "Sequence difference is : %d. Starting backfill.", sequence_diff);
dgr_enable_server_side_updates_msg(conn_handle, &backfill_uuid.u, dgr_send_backfill_enable_notif_cb, 2);
} else {
ESP_LOGE(tag_stg, "Unexpected difference between sequences : %d", sequence_diff);
dgr_error();
}
}
/**
* After all backfill data is received, parse and save all of it in the ringbuffer.
*/
void
dgr_parse_backfill() {
int i = 0;
ESP_LOGI(tag_stg, "Starting to parse Backfill data.");
while(i < backfill_buffer_pos) {
uint32_t timestamp = make_u32_from_bytes_le(&backfill_buffer[i]);
uint16_t glucose = make_u16_from_bytes_le(&backfill_buffer[i + 4]);
uint8_t calibration_state = backfill_buffer[i + 6];
uint8_t trend = backfill_buffer[i + 7];
ESP_LOGI(tag_stg, "[=========== Backfill Data ===========]");
ESP_LOGI(tag_stg, "\ttimestamp = 0x%x", timestamp);
ESP_LOGI(tag_stg, "\tglucose = %d", glucose);
ESP_LOGI(tag_stg, "\tcalibration state = %s (0x%x)",
translate_calibration_state(calibration_state), calibration_state);
ESP_LOGI(tag_stg, "\ttrend = 0x%x", trend);
i += 8;
dgr_save_to_ringbuffer(timestamp, glucose, calibration_state, trend);
}
}
/**
* Prints content of the ringbuffer for debug purposes.
*
* @param keep_items true if all ringbuffer items should be kept in the ringbuffer,
* false if ringbuffer items should be discarded after output
*/
void
dgr_print_rbuf(bool keep_items) {
uint8_t buffer_save[BUFFER_SIZE];
int i = 0;
size_t item_size;
uint8_t *data = (uint8_t *)xRingbufferReceive(rbuf_handle, &item_size, pdMS_TO_TICKS(1000));
xRingbufferPrintInfo(rbuf_handle);
while(data != NULL) {
uint32_t timestamp = make_u32_from_bytes_le(data);
uint16_t glucose = make_u16_from_bytes_le(&data[4]);
uint8_t calibration_state = data[6];
uint8_t trend = data[7];
ESP_LOGI(tag_stg, "[=========== RingbufItem (size=%d) ===========]", item_size);
ESP_LOGI(tag_stg, "\ttimestamp = 0x%x", timestamp);
ESP_LOGI(tag_stg, "\tglucose = %d", glucose);
ESP_LOGI(tag_stg, "\tcalibration state = %s",
translate_calibration_state(calibration_state));
ESP_LOGI(tag_stg, "\ttrend = 0x%x", trend);
if(keep_items) {
memcpy(&buffer_save[i++ * item_size], data, item_size);
}
vRingbufferReturnItem(rbuf_handle, data);
data = (uint8_t *)xRingbufferReceive(rbuf_handle, &item_size, pdMS_TO_TICKS(1000));
}
// resave items
if(keep_items) {
for (int j = 0; j < i; j++) {
UBaseType_t res = xRingbufferSend(rbuf_handle, &buffer_save[j * item_size], 8, pdMS_TO_TICKS(5000));
if (res != pdTRUE) {
ESP_LOGE(tag_stg, "Error while writing into ringbuffer. rc = 0x%04x", res);
dgr_error();
}
}
}
}
|
C
|
#include "stack_arry.h"
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
Stack CreateStack(unsigned capacity){
Stack s = (Stack)malloc(sizeof(struct StackRecord));
s->capacity = capacity;
s->top = EMPTYTOS;
s->array = (int *)malloc(sizeof(int) * capacity);
return s;
}
int IsEmpty(Stack s){
return (s->top == EMPTYTOS);
}
int IsFull(Stack s){
return (s->top == s->capacity-1);
}
void push(Stack s, int e){
if (IsFull(s))
return;
s->array[++s->top] = e;
}
int pop(Stack s){
if (IsEmpty(s))
return INT_MIN;
return s->array[s->top--];
}
int top(Stack s){
if (IsEmpty(s))
return INT_MIN;
return s->array[s->top];
}
void MakeEmpty(Stack *s){
if (*s != NULL){
free((*s)->array);
free(*s);
*s = NULL;
}
}
int main()
{
Stack stack = CreateStack(100);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));
printf("Top item is %d\n", top(stack));
printf("%d\n", stack == NULL);
MakeEmpty(&stack);
printf("%d\n", stack == NULL);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** my_getnbr.c
** File description:
** ?
*/
int my_getnbr(char const *str)
{
int i = 0;
int n = 0;
if (str[0] == '-' && str[1] != '\0')
i++;
while (str[i] != '\0') {
n = n + str[i] - 48;
n = n * 10;
i++;
}
n /= 10;
if (str[0] == '-')
return (-1 * n);
else
return (n);
}
|
C
|
#ifndef UTITERATOR_H
#define UTITERATOR_H
#include "term.h"
#include "struct.h"
#include "variable.h"
#include "atom.h"
#include "number.h"
#include "list.h"
#include "iterator.h"
TEST(iterator, first) {
Number one(1);
Variable X("X");
Variable Y("Y");
Number two(2);
Struct t(Atom("t"), { &X, &two });
Struct s(Atom("s"), { &one, &t, &Y });
// StructIterator it(&s);
Iterator <Term *> *itStruct = s.createIterator();
// Iterator& itStruct = it;
// ASSERT_EQ(it.first()->symbol());
itStruct->first();
ASSERT_EQ("1", itStruct->currentItem()->symbol());
ASSERT_FALSE(itStruct->isDone());
itStruct->next();
ASSERT_EQ("t(X, 2)", itStruct->currentItem()->symbol());
ASSERT_FALSE(itStruct->isDone());
itStruct->next();
ASSERT_EQ("Y", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_TRUE(itStruct->isDone());
}
TEST(iterator, nested_iterator) {
Number one(1);
Variable X("X");
Variable Y("Y");
Number two(2);
Struct t(Atom("t"), { &X, &two });
Struct s(Atom("s"), { &one, &t, &Y });
Iterator <Term *> *itStruct = s.createIterator();
//StructIterator it(&s);
itStruct->first();
itStruct->next();
Struct *s2 = dynamic_cast<Struct *>(itStruct->currentItem());
Iterator <Term *> *itStruct2 = s2->createIterator();
//StructIterator it2(s2);
itStruct2->first();
ASSERT_EQ("X", itStruct2->currentItem()->symbol());
ASSERT_FALSE(itStruct2->isDone());
itStruct2->next();
ASSERT_EQ("2", itStruct2->currentItem()->symbol());
ASSERT_FALSE(itStruct2->isDone());
itStruct2->next();
ASSERT_TRUE(itStruct2->isDone());
}
TEST(iterator, firstList) {
Number one(1);
Variable X("X");
Variable Y("Y");
Number two(2);
Struct t(Atom("t"), { &X, &two });
List l({ &one, &t, &Y });
//ListIterator <Term *> *it(&l);
Iterator <Term *> *itList = l.createIterator();
itList->first();
ASSERT_EQ("1", itList->currentItem()->symbol());
ASSERT_FALSE(itList->isDone());
itList->next();
ASSERT_EQ("t(X, 2)", itList->currentItem()->symbol());
ASSERT_FALSE(itList->isDone());
itList->next();
ASSERT_EQ("Y", itList->currentItem()->symbol());
itList->next();
ASSERT_TRUE(itList->isDone());
}
TEST(iterator, NullIterator){
Number one(1);
NullIterator <Term *> nullIterator(&one);
nullIterator.first();
ASSERT_TRUE(nullIterator.isDone());
Iterator <Term *> *it = one.createIterator();
it->first();
ASSERT_TRUE(it->isDone());
}
// Struct DFS test1
TEST(iterator, createDFSIterator1){
Number one(1);
Variable X("X");
Variable Y("Y");
Number two(2);
Struct t(Atom("t"), { &X, &two }); // t(X,2)
Struct s(Atom("s"), { &one, &t, &Y }); // s(1, t(X, 2), Y)
Iterator <Term *> *itStruct = s.createDFSIterator();
itStruct->first();
ASSERT_EQ("1", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("t(X, 2)", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("X", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("2", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("Y", itStruct->currentItem()->symbol());
}
// Struct DFS test2
TEST(iterator, createDFSIterator2){
Number one(1);
Number two(2);
Atom tom("tom");
Variable X("X");
vector<Term *> args = { &one, &two};
List l(args);
Struct u(Atom("u"), { &X }); // u(X)
Struct t(Atom("t"), { &u, &one }); // t(u(X), 1)
Struct s(Atom("s"), { &t, &tom, &l }); // s(t(u(X),1), tom, [1, 2])
Iterator <Term *> *itStruct = s.createDFSIterator();
itStruct->first();
ASSERT_EQ("t(u(X), 1)", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("u(X)", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("X", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("1", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("tom", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("[1, 2]", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("1", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("2", itStruct->currentItem()->symbol());
}
// Struct BFS test1
TEST(iterator, createBFSIterator1){
Number one(1);
Variable X("X");
Variable Y("Y");
Number two(2);
Struct t(Atom("t"), { &X, &two }); // t(X,2)
Struct s(Atom("s"), { &one, &t, &Y }); // s(1, t(X, 2), Y)
Iterator <Term *> *itStruct = s.createBFSIterator();
itStruct->first();
ASSERT_EQ("1", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("t(X, 2)", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("Y", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("X", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("2", itStruct->currentItem()->symbol());
}
// Struct BFS test2
TEST(iterator, createBFSIterator2){
Number one(1);
Number two(2);
Atom tom("tom");
Variable X("X");
vector<Term *> args = { &one, &two};
List l(args);
Struct u(Atom("u"), { &X }); // u(X)
Struct t(Atom("t"), { &u, &one }); // t(u(X), 1)
Struct s(Atom("s"), { &t, &tom, &l }); // s(t(u(X),1), tom, [1, 2])
Iterator <Term *> *itStruct = s.createBFSIterator();
itStruct->first();
ASSERT_EQ("t(u(X), 1)", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("tom", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("[1, 2]", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("u(X)", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("1", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("1", itStruct->currentItem()->symbol());
itStruct->next();
ASSERT_EQ("2", itStruct->currentItem()->symbol());
}
// List BFS test1
TEST(iterator, createBFSIteratorList1){
Number one(1);
Number two(2);
Variable X("X");
Variable Y("Y");
vector<Term *> args1 = {&one, &X, &Y};
List l1(args1); // [1, X, Y]
vector<Term *> args2 = {&l1, &two};
List l2(args2); // [[1, X, Y], 2]
Iterator <Term *> *itList = l2.createBFSIterator();
itList->first();
ASSERT_EQ("[1, X, Y]", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("2", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("1", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("X", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("Y", itList->currentItem()->symbol());
}
// List BFS test2
TEST(iterator, createBFSIteratorList2){
Number one(1);
vector<Term *> args1 = { &one};
List l1(args1); // [1]
Number two(2);
Atom tom("tom");
Variable X("X");
vector<Term *> args2 = { &one, &two};
List l2(args2); // [1, 2]
Struct u(Atom("u"), { &X }); // u(X)
Struct t(Atom("t"), { &u, &one }); // t(u(X), 1)
vector<Term *> args3 = { &l1, &l2, &t};
List l3(args3); // [[1], [1, 2], t(u(X), 1)]
Iterator <Term *> *itList = l3.createBFSIterator();
itList->first();
ASSERT_EQ("[1]", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("[1, 2]", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("t(u(X), 1)", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("1", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("1", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("2", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("u(X)", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("1", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("X", itList->currentItem()->symbol());
}
// List DFS test1
TEST(iterator, createDFSIteratorList1){
Number one(1);
Variable X("X");
Variable Y("Y");
Number two(2);
Struct t(Atom("t"), { &X, &two }); // t(X,2)
Struct s(Atom("s"), { &one, &t, &Y }); // s(1, t(X, 2), Y)
Iterator <Term *> *itList = s.createDFSIterator();
itList->first();
ASSERT_EQ("1", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("t(X, 2)", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("X", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("2", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("Y", itList->currentItem()->symbol());
}
// List DFS test2
TEST(iterator, createDFSIteratorList2){
Number one(1);
Number two(2);
Atom tom("tom");
Variable X("X");
vector<Term *> args = { &one, &two};
List l(args);
Struct u(Atom("u"), { &X }); // u(X)
Struct t(Atom("t"), { &u, &one }); // t(u(X), 1)
Struct s(Atom("s"), { &t, &tom, &l }); // s(t(u(X),1), tom, [1, 2])
Iterator <Term *> *itList = s.createDFSIterator();
itList->first();
ASSERT_EQ("t(u(X), 1)", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("u(X)", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("X", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("1", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("tom", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("[1, 2]", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("1", itList->currentItem()->symbol());
itList->next();
ASSERT_EQ("2", itList->currentItem()->symbol());
}
#endif
|
C
|
// Strcatint
char *strcatint (char *str, int x)
{
char z, a[2];
z = x;
a[0] = z;
a[1] = 0;
strcat(str, a);
return str;
}
//______________________ Guardar ____________________//
bool ex=true;
void guardar(tipo *lista, FILE *Archivo){
tipo n, p=*lista;
char pala[100], a[100], z, vars[30][100], name[100], value[100];
int x,y, i=0, s=0, type=0, dot=0, eq=0;
//printf("Archivo original: \n");
// while(!feof(Archivo)){
// fputc(fgetc(Archivo), stdout);
// }
//printf("\n\nSeparado en: \n");
rewind(Archivo);
x = fgetc(Archivo);
pala[0] = 0;
if(lista){
while(!feof(Archivo)){
back:
//function
if(AToken(pala) == 335){
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
for(s = 0; s<30; s++) vars[s][0]='\0';
s=0;
if(x == 32){ // espacio despues del funcion para el nombre
x = fgetc(Archivo);
// Obtenemos el nombre de la funcion hasta encontrar espacio o (
while(x != 32 && x != 40){
strcatint(pala, x); //Concatenamos un valor INT a la cadena pala
x = fgetc(Archivo);
}
a[0]=0;
strcpy(a, pala);
pala[0] = 0;
//Avanzamos hasta los parametros de la funcion quitando espacios si es que hay
while(x != 40){
x = fgetc(Archivo);
if(x != 40 && x != 32){
printf("Error en la linea %i\n", i+1, pala);
goto END;
}
}
//Obtenemos la cantidad de parametros de la funcion
x = fgetc(Archivo);
while(x != 41){
if(x == 36){ // si es igual a $
while(x != 41 && x != 44){
strcatint(pala, x);
x = fgetc(Archivo);
}
strcpy(vars[s], pala); // se une el argumento al arreglo bidimencional
s++;
pala[0] = 0;
if(x == 44){ // si es igual a ,
x = fgetc(Archivo);
while(x == 32){
x = fgetc(Archivo);
}
if(x != 36){
printf("Error en la linea %i\n", i+1, pala);
ex = false;
goto END;
}
}
}else{
printf("Error en la linea %i\n", i+1);
ex = false;
goto END;
}
}
insertarFuncion(&Funciones, i, a, vars, s);
insertar(&*lista, i, a, NoF);
goto next;
}else{
printf("Error en la linea %d cerca de function\n", i);
goto END;
}
}
// MATH SENTENCES
// < = > ! & % * + - / ^ [ ] { } | , . ;
if( x == 60 || x == 61 || x == 62|| x == 33 || x == 37 || x == 38 || x == 42 || x == 43 || x == 45 || x == 47 || x == 94 || x == 91 || x == 93 || x == 123 || x == 125 || x == 124 || x == 44 || x == 46 || x == 59 ){
if(strlen(pala))
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
strcatint(pala, x);
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
x = fgetc(Archivo);
goto back;
}
//espacio
if(x == 32){
if(strlen(pala) >= 1)
insertar(&*lista, i, pala, AToken(pala));
x = fgetc(Archivo);
pala[0] = 0;
goto back;
}
//Salto de linea
if(x == 10){
if(strlen(pala) > 1)
insertar(&*lista, i, pala, AToken(pala));
i = i + 1;
x = fgetc(Archivo);
pala[0] = 0;
goto back;
}
//Tabulacion
if(x == 9){
if(strlen(pala) > 1)
insertar(&*lista, i, pala, AToken(pala));
x = fgetc(Archivo);
pala[0] = 0;
goto back;
}
//Parentesis
if(x == 40 || x == 41){
if(pala[0] != 0){
insertar(&*lista, i, pala, AToken(pala));
}
pala[0] = 0;
strcatint(pala, x);
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
x = fgetc(Archivo);
goto back;
}
//Numeros
if(x >= 48 && x <= 57){
if(strlen(pala) > 1)
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
strcatint(pala, x);
x = fgetc(Archivo);
while(x >= 48 && x <= 57){
strcatint(pala, x);
x = fgetc(Archivo);
}
insertar(&*lista, i, pala, 89);
pala[0] = 0;
goto back;
}
//Comillas
if(x == 34){
pala[0] = 34;
insertar(&*lista, i, pala, 34);
pala[0] = 0;
x = fgetc(Archivo);
while(x != 34){
strcatint(pala, x);
x = fgetc(Archivo);
}
insertar(&*lista, i, pala, 88);
pala[0] = 0;
strcatint(pala, x);
insertar(&*lista, i, pala, 34);
x = fgetc(Archivo);
pala[0] = 0;
goto back;
}
// Plabras reservadas
if(x != 10 && x != 32 && x != 34 && x != 9 && x != 40 && x != 41 ){
strcatint(pala, x);
y = 0;
//Variable
if(AToken(pala) == 51 || AToken(pala) == 52 || AToken(pala) == 53 || AToken(pala) == 54 ){
// Char INT FLOAT DOUBLE
switch(AToken(pala)){ case 51: type=51; break; case 52: type=52; break; case 53: type=53; break; case 54: type=54; break;}
x = fgetc(Archivo);
if(x == 32){
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
variablename:
name[0] = 0;
//Removing spaces
while(x == 32)
x = fgetc(Archivo);
//Name of variable(s)
if(x >= 48 && x <= 57){
ex=false;
printf("Sorry but variable names cant start with numbers.");
goto END;
}
// SPACE = , [ ;
while( x != 32 && x != 61 && x != 44 && x != 91 && x != 59){
if(x >= 65 && x <=90 || x >= 97 && x <=122 || x >= 48 && x <= 57){ //This condition indicates that the variables' name are only letters
strcatint(pala, x);
x = fgetc(Archivo);
}else{
if(x != 32 || x == 61 || x != 44 || x != 59){//If the condition is false, the varible 'ex' indicates that an error was found in the code
ex=false;
printf("Sorry but you can't asign special caracters to variable name.");
goto END;
}
}
}
//Insert the variable name to the list with the Token #87
insertar(&*lista, i, pala, 87);
strcpy(name, pala);
pala[0] = 0;
//After variable name
aftervariablename:
switch(x){
//Removing spaces
case 32:
while(x == 32)
x = fgetc(Archivo);
goto aftervariablename;
break;
//Equal
case 61:
eq=1;
strcatint(pala, x);
insertar(&*lista, i, pala, AToken(pala));
x = fgetc(Archivo);
pala[0] = 0;
//Removing spaces
while(x == 32)
x = fgetc(Archivo);
switch(x){
case 34:
//If the variable is char can asign strings
if(type == 51){
strcatint(pala, x);
insertar(&*lista, i, pala, AToken(pala));
x = fgetc(Archivo);
pala[0] = 0;
//Getting whole string
while(x != 34){
strcatint(pala, x);
x=fgetc(Archivo);
}
//After String
insertar(&*lista, i, pala, 88);
insertarType(&types, i, name, 89, pala);
pala[0] = 0;
strcatint(pala, x);
insertar(&*lista, i, pala, AToken(pala));
x = fgetc(Archivo);
pala[0] = 0;
goto aftervariablename;
//Else will end the code with the error mark
}else{
ex=false;
printf("Its not char type.");
goto END;
}
break;
case 48: // 0
case 49: // 1
case 50: // 2
case 51: // 3
case 52: // 4
case 53: // 5
case 54: // 6
case 55: // 7
case 56: // 8
case 57: // 9
case 46: // .
if(type == 52 || type == 53 || type == 54){
//While x get the value of , or ;
while(x != 44 && x != 59){
//If the x value is number or dot, continue, else error
if(x >= 48 && x <= 57 || x == 46){
//Concat the value
strcatint(pala,x);
x = fgetc(Archivo);
//If the value have decimal
if(x == 46){
//Increase the dot count
dot++;
//If the value of dot is more than 1 or the type of the variable is INT make the error
if(dot > 1 || type == 52){
ex=false;
printf("So many dots in the value.");
goto END;
}
}
}else{
ex=false;
printf("Error");
goto END;
}
}
//After getting the whole value
insertar(&*lista, i, pala, 89);
strcpy(value, pala);
if(type == 52) //INT
insertarType(&types, i, name, 90, value);
if(type == 53) //FLOAT
insertarType(&types, i, name, 91, value);
if(type == 54) //double
insertarType(&types, i, name, 92, value);
pala[0] = 0;
dot = 0;
goto aftervariablename;
}else{
ex=false;
printf("Error");
goto END;
}
break;
}
break;
//Coma
case 44:
if(!eq){
if(type==51){
insertarType(&types, i, name, 89, "");
}else{
if(type == 52) //INT
insertarType(&types, i, name, 90, "0");
if(type == 53) //FLOAT
insertarType(&types, i, name, 91, "0");
if(type == 54) //double
insertarType(&types, i, name, 92, "0");
}
}
eq=0;
strcatint(pala, x);
insertar(&*lista, i, pala, AToken(pala));
x = fgetc(Archivo);
pala[0] = 0;
goto variablename;
break;
//DotComa
case 59:
if(!eq){
if(type==51){
insertarType(&types, i, name, 89, "");
}else{
if(type == 52) //INT
insertarType(&types, i, name, 90, "0");
if(type == 53) //FLOAT
insertarType(&types, i, name, 91, "0");
if(type == 54) //double
insertarType(&types, i, name, 92, "0");
}
}
eq=0;
strcatint(pala, x);
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
goto next;
break;
default:
ex=false;
printf("\nSyntax error!\n On line [%d] near to [%s]\n", i+1, pala);
goto END;
break;
}
}
}
while(y < 80){
if(strcmp(atoken[y].carc, pala) == 0){
if(AToken(pala) == 51 || AToken(pala) == 52 || AToken(pala) == 53 || AToken(pala) == 54 ){}
insertar(&*lista, i, pala, AToken(pala));
pala[0] = 0;
}
y++;
}
}
next:
x = fgetc(Archivo);
}
END:
printf("");
}
}
|
C
|
#include <pebble.h>
static Window *s_main_window;
static TextLayer *s_current_time_layer;
static TextLayer *s_next_time_layer;
static PropertyAnimation *s_next_property_animation;
static GFont s_font;
const int WIDTH = 144;
const int HEIGHT = 168;
const int ANIM_DULATION = 300;
const int ANIM_DELAY = 100;
static int calculate_next_hour(int tm_hour) {
int next_hour;
if(tm_hour == 23) {
next_hour = 0;
} else {
next_hour = tm_hour + 1;
}
return next_hour;
}
static PropertyAnimation *make_animation(TextLayer *text_layer, int y) {
PropertyAnimation *animation;
Layer *layer_text_layer = text_layer_get_layer(text_layer);
GRect from_frame = layer_get_frame(layer_text_layer);
GRect to_frame = GRect(0, y, WIDTH, HEIGHT);
animation = property_animation_create_layer_frame(layer_text_layer, &from_frame, &to_frame);
animation_set_duration((Animation *)animation, ANIM_DULATION);
animation_set_delay((Animation *)animation, ANIM_DELAY);
animation_set_curve((Animation*)animation, AnimationCurveEaseInOut);
return animation;
}
static void update_time_buffer(struct tm *tick_time) {
// Create long-lived buffer;
static char current_hour_buffer[] = "00";
static char next_hour_buffer[] = "00";
int next_hour = calculate_next_hour(tick_time->tm_hour);
if(clock_is_24h_style() == true) {
snprintf(current_hour_buffer, sizeof("00"), "%02d", 12); //tick_time->tm_hour);
snprintf(next_hour_buffer, sizeof("00"), "%02d", next_hour);
} else {
snprintf(current_hour_buffer, sizeof("00"), "%02d", tick_time->tm_hour % 12);
snprintf(next_hour_buffer, sizeof("00"), "%02d", next_hour % 12);
}
text_layer_set_text(s_current_time_layer, current_hour_buffer);
text_layer_set_text(s_next_time_layer, next_hour_buffer);
}
static void update_time() {
// Get a tm structure
time_t temp = time(NULL);
struct tm *tick_time = localtime(&temp);
// Animate
s_next_property_animation = make_animation(s_next_time_layer,
HEIGHT - HEIGHT * tick_time->tm_min / 60);
// animation_schedule((Animation*) s_next_property_animation);
// Update time string
update_time_buffer(tick_time);
}
static void tick_handler(struct tm *tick_time, TimeUnits units_changed) {
update_time();
}
static TextLayer *make_text_layer(int x, int y, int w, int h, GColor back, GColor text) {
// Create main Window element and assign to pointer
TextLayer *text_layer;
text_layer = text_layer_create(GRect(x, y, w, h));
text_layer_set_background_color(text_layer, back);
text_layer_set_text_color(text_layer, text);
text_layer_set_text(text_layer, "00");
// Improve the layout to be more like a watchface
text_layer_set_font(text_layer, s_font);
text_layer_set_text_alignment(text_layer, GTextAlignmentCenter);
return text_layer;
}
static void main_window_load(Window *window) {
s_font = fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_BONK_OFFSET_62));
s_current_time_layer = make_text_layer(0, 0, WIDTH, HEIGHT,
GColorCyan, GColorRed);
s_next_time_layer = make_text_layer(0, HEIGHT, WIDTH, HEIGHT,
GColorYellow, GColorMagenta);
// Add it as a child layer to the Window's root layer
layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_current_time_layer));
layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_next_time_layer));
}
static void main_window_unload(Window *window) {
fonts_unload_custom_font(s_font);
text_layer_destroy(s_current_time_layer);
text_layer_destroy(s_next_time_layer);
}
static void init() {
s_main_window = window_create();
window_set_background_color(s_main_window, GColorBlack);
// Set handlers to manage the elements inside the Window
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
// Show the Window on the watch, with animated=true
window_stack_push(s_main_window, true);
time_t temp = time(NULL);
struct tm *tick_time = localtime(&temp);
update_time_buffer(tick_time);
// Register with TickTimeService
tick_timer_service_subscribe(MINUTE_UNIT, tick_handler);
}
static void deinit() {
// Destroy Window
animation_unschedule_all();
window_destroy(s_main_window);
}
int main(void) {
init();
app_event_loop();
deinit();
}
|
C
|
#include "sort.h"
#include "sortprivate.h"
#include <string.h>
int
Select(int *array, int begin, int end, int n)
{
if (n < 1 || n > end - begin)
return -1;
int a[end-begin];
memcpy(a, array+begin, sizeof(int)*(end-begin));
int target = n-1; // index from 0, so a[n-1] is the n'th smallest element.
int b = 0;
int e = end-begin;
int mid = Partition(a, b, e);
while (mid != target) {
if (mid > target) {
e = mid;
mid = Partition(a, b, e);
}
else {
b = mid+1;
mid = Partition(a, b, e);
}
}
return a[mid];
}
|
C
|
/**
* @file
* @brief
* @warning
* @details
*
* Copyright (c) Smart Sense d.o.o 2018. All rights reserved.
*
**/
/*------------------------- INCLUDED FILES ************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "sys/errno.h"
#include "sys/select.h"
#include "FreeRTOS.h"
#include "cmsis_os.h"
#include "assert.h"
#include "ssDevMan.h"
#include "ssSocket.h"
#include "ssLogging.h"
#include "fifo.h"
/*------------------------- MACRO DEFINITIONS --------------------------------*/
#define MODEM_SOCKET 1
#define WIFI_SOCKET 2
/*------------------------- TYPE DEFINITIONS ---------------------------------*/
/************************************************************************
* Structure per socket.
*************************************************************************/
struct socket_t {
/* Socket state */
socket_state_t state;
/* Data that was left from the previous read */
FifoHandle_t rxfifo;
/* Offset in the data that was left from the previous read */
uint16_t lastoffset;
#ifdef SOCKETS_DEBUG
/* Number of times data was received */
int16_t rcevent;
/* Number of times data was sent */
uint16_t sendevent;
/* Socket flags */
uint16_t flags;
/* Last error that occured on this socket */
int8_t err;
#endif /* SOCKETS_DEBUG */
/* Status of socket */
uint8_t taken;
uint8_t protocol;
socket_type_t type;
struct netif_t *interface;
};
/*------------------------- PUBLIC VARIABLES ---------------------------------*/
/* The global array of available sockets */
struct socket_t sockets[NUM_SOCKETS];
extern int errno;
/*------------------------- PRIVATE VARIABLES --------------------------------*/
/*------------------------- PRIVATE FUNCTION PROTOTYPES ----------------------*/
/*------------------------- PRIVATE FUNCTION DEFINITIONS ---------------------*/
static struct addrinfo *allocaddrinfo(void);
/*------------------------- PUBLIC FUNCTION DEFINITIONS ----------------------*/
static struct socket_t *get_socket(int16_t s)
{
struct socket_t *sock;
if ((s < 0) || (s >= NUM_SOCKETS)) {
return NULL;
}
sock = &sockets[s];
return sock;
}
/* Create a socket and return the descriptor to the app */
int16_t socket(int domain, int type, int protocol)
{
int8_t i;
netif_t *net_dev;
net_dev = get_device();
i = net_dev->socket_open(domain, type, protocol);
if(i > -1 && !sockets[i].taken)
{
ssLoggingPrint(ESsLoggingLevel_Debug, 0, "socket created id=%d (domain=%d, type=%d, protocol=%d)", i, domain, type, protocol);
sockets[i].state = SS_UNCONNECTED;
sockets[i].rxfifo = fifo_create(NULL, SOCKBUF_SIZE);;
sockets[i].lastoffset = 0;
#ifdef SOCKETS_DEBUG
sockets[i].rcevent = 0;
sockets[i].sendevent = 0;
sockets[i].flags = 0;
sockets[i].err = 0;
#endif /* SOCKETS_DEBUG */
sockets[i].taken = 1;
sockets[i].protocol = protocol;
sockets[i].type = type;
sockets[i].interface = net_dev;
return i;
}
return i;
}
int32_t connect(int s, const struct sockaddr *name, socklen_t namelen)
{
uint8_t result = -1;
struct socket_t *sock;
sock = get_socket(s);
if (!sock)
{
return result;
}
/* TODO - not in POSIX style but makes working with ublox modems easier */
if (sock->state == SS_CONNECTED)
{
ssLoggingPrint(ESsLoggingLevel_Error, 0, "socket %d is already connected", s);
return result;
}
result = sock->interface->socket_connect(sock->interface, s, name, namelen);
if (result == 0)
{
sock->state = SS_CONNECTED;
}
return result;
}
int32_t sendto(int s, const void *data, size_t size, int8_t flags, const struct sockaddr *to, socklen_t tolen)
{
struct socket_t *sock;
int32_t result = -1;
sock = get_socket(s);
if (!sock)
return -1;
result = sock->interface->socket_sendto(sock->interface, s, (char *)data, size, 0, (const struct sockaddr_in *)to, tolen);
//ssLoggingPrintRawStr(ESsLoggingLevel_Debug, 0, data, size, "socket sendto s=%d to=0x%x:%d =>", s, ((const struct sockaddr_in *)to)->sin_addr.s_addr, ((const struct sockaddr_in *)to)->sin_port);
#ifdef SOCKETS_DEBUG
if (result)
{
//sock->sendevent += 1;
}
#endif
return result;
}
int32_t send(int s, const void *data, size_t size, int8_t flags)
{
struct socket_t *sock;
int8_t result = -1;
sock = get_socket(s);
if (!sock)
return result;
if (sock->state == SS_CONNECTED)
{
result = sock->interface->socket_send(sock->interface, s, data, size, 0);
}
#ifdef SOCKETS_DEBUG
if (result)
{
sock->sendevent += 1;
}
#endif
return result;
}
int32_t recvfrom(int s, void *mem, size_t len, int8_t flags, struct sockaddr *from, socklen_t *from_len)
{
struct socket_t *sock;
int32_t recv_length = -1;
char buf[SOCKBUF_SIZE] = {0};
uint16_t copylen = 0;
sock = get_socket(s);
if(!sock)
{
return -1;
}
copylen = fifo_length(sock->rxfifo);
if (copylen)
{
/* There is data left from the last recv operation */
fifo_read(sock->rxfifo, mem, copylen, 0);
recv_length = copylen;
}
else
{
recv_length = sock->interface->socket_recvfrom(sock->interface, s, buf, len, 0, (struct sockaddr_in *)from, from_len);
if(recv_length > 0)
{
ssLoggingPrintRawStr(ESsLoggingLevel_Debug, 0, mem, recv_length, "socket recvfrom s=%d from=0x%x:d =>", s, ((const struct sockaddr_in *)from)->sin_addr.s_addr, ((const struct sockaddr_in *)from)->sin_port);
memcpy(mem, buf, recv_length);
if (recv_length > len)
{
/* If all data doesn't fit into provided buffer, we'll copy what we can and the rest we'll save for later */
fifo_write(sock->rxfifo, buf+len, recv_length-len, 0);
}
#ifdef SOCKETS_DEBUG
sock->rcevent += 1;
#endif
}
}
return recv_length;
}
int32_t recv(int s, void *mem, size_t len, int8_t flags)
{
struct socket_t *sock;
int32_t length = -1;
sock = get_socket(s);
if(!sock)
{
return -1;
}
length = sock->interface->socket_recv(sock->interface, s, mem, len, 0);
#ifdef SOCKETS_DEBUG
if (length > 0)
{
sock->rcevent += 1;
}
#endif
return length;
}
int8_t close (int16_t s)
{
struct socket_t *sock;
sock = get_socket(s);
if(!sock)
{
return -1;
}
else if (sock->state == SS_CONNECTED)
{
/* Higher libs will sometimes close the socket after it is connected */
/* Ublox modems can't tell the difference so we won't close the socket in that case */
return 0;
}
else
{
sock->interface->socket_close(sock->interface, s);
fifo_destroy(sock->rxfifo);
sock->rxfifo = NULL;
sock->lastoffset = 0;
sock->taken = 0;
sock->state = SS_UNCONNECTED;
return 0;
}
}
/* @TODO: not finished - DO NOT USE! */
struct hostent *gethostbyname(const char *hostname)
{
netif_t *net_dev;
uint32_t ipaddr;
struct hostent *data;
if(!hostname)
{
return NULL;
}
data = pvPortMalloc(sizeof(struct addrinfo));
if(data)
{
struct in_addr addr;
const char *p;
/* Check for all-numeric hostname with no trailing dot. */
if (isdigit(hostname[0]))
{
p = hostname;
while (*p && (isdigit(*p) || *p == '.'))
{
p++;
}
if (!*p && p[-1] != '.')
{
/* Looks like an IP address; convert it. */
if (inet_aton(hostname, &addr) == 0)
{
/* invalid ip address */
return NULL;
}
/* @TODO: fill hostent */
return data;
}
}
net_dev = get_device();
net_dev->gethostbyname(hostname, &ipaddr);
/* @TODO: fill hostent */
}
return data;
}
/* Merkat -- still working on it */
int getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res)
{
netif_t *net_dev = NULL;
struct in_addr addr;
struct addrinfo *ai = NULL;
struct sockaddr_in sin = {0};
bool is_numeric = false;
bool is_found = false;
if (res == NULL)
{
return -1;
}
*res = NULL;
if ((node == NULL) && (service == NULL))
{
return -1;
}
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
/* Check for all-numeric hostname with no trailing dot.
* No need to query network device in that case, just copy to output structure.
*/
if (isdigit(node[0]))
{
const char *p = node;
while (*p && (isdigit(*p) || *p == '.'))
{
p++;
}
if (!*p && p[-1] != '.')
{
/* Looks like an IP address; convert it. */
if (inet_aton(node, &addr) != 0)
{
sin.sin_addr = addr;
is_numeric = true;
is_found = true;
}
}
}
if((!is_found) && (!is_numeric))
{
/* try network device */
net_dev = get_device();
if(net_dev->gethostbyname(node, &addr.s_addr) == 0)
{
sin.sin_addr = addr;
is_found = true;
}
}
if(is_found)
{
ai = allocaddrinfo();
if(ai)
{
ai->ai_family = AF_INET;
if (hints != NULL)
{
/* copy socktype & protocol from hints if specified */
ai->ai_socktype = hints->ai_socktype;
ai->ai_protocol = hints->ai_socktype; /* Merkat also waakama TODO */
}
if (service)
{
sin.sin_port = htons(atoi(service));
}
ai->ai_addr->sa_family = AF_INET;
ai->ai_addrlen = sizeof(struct sockaddr); // Merkat temp -DBG
if(is_numeric)
{
strcpy(ai->ai_addr->sa_data, node);
}
else
{
if(inet_ntop(AF_INET, &addr, ai->ai_addr->sa_data, sizeof(ai->ai_addr->sa_data)) != ai->ai_addr->sa_data)
{
freeaddrinfo(ai);
ai = NULL;
}
else
{
memcpy(ai->ai_addr->sa_data, ((struct sockaddr *) &sin)->sa_data, sizeof((ai->ai_addr->sa_data)));
}
}
memcpy(ai->ai_addr, &sin, sizeof(sin));
}
}
*res = ai;
return 0;
}
void freeaddrinfo(struct addrinfo *res)
{
vPortFree(res);
}
/* Convert string to integer */
/*
static int32_t atoi(const char *str)
{
int res = 0;
int i = 0;
for(; str[i] != '\0'; ++i)
{
res = res*10 + str[i] - '0';
}
return res;
}
*/
/* dots and numbers string to unsigned long */
uint32_t inet_addr(const char *cp)
{
struct in_addr val;
if (inet_aton(cp, &val))
{
return val.s_addr;
}
return NULL;
}
/* Not supported for now -- TODO */
int select (int __nfds, fd_set *restrict __readfds, fd_set *restrict __writefds, fd_set *restrict __exceptfds, struct timeval *restrict __timeout)
{
return 1;
}
/*------------------------- PRIVATE FUNCTION DEFINITIONS ---------------------*/
static struct addrinfo *allocaddrinfo()
{
void *res = NULL;
struct addrinfo *ai = NULL;
struct sockaddr *sa = NULL;
res = pvPortMalloc(sizeof(struct addrinfo) + sizeof(struct sockaddr));
if(res)
{
memset(res, 0, sizeof(struct addrinfo) + sizeof(struct sockaddr));
ai = (struct addrinfo *)res;
sa = (struct sockaddr *)((uint8_t *)res + sizeof(struct addrinfo));
ai->ai_addr = sa;
/* Canonname not supported */
ai->ai_canonname = NULL;
/* Only single address per host is supported */
ai->ai_next = NULL;
}
return ai;
}
|
C
|
#include <stdio.h>
#include "../include/fila2.h"
#define ERROR_EMPTY_QUEUE -1
#define ERROR_CREATION -1
#define ERROR_INVALID_IT -2
PFILA2 globalQueue;
int CreateFila2(PFILA2 pFila){
globalQueue = (PFILA2) malloc(sizeof(FILA2));
if(pFila == NULL){
return ERROR_CREATION;
}
pFila->first = NULL;
pFila->last = NULL;
pFila->it = NULL;
pFila = globalQueue;
return 0;
}
int FirstFila2(PFILA2 pFila){
if(pFila->first == NULL) {
return ERROR_EMPTY_QUEUE;
}
pFila->it = pFila->first;
return 0;
}
int LastFila2(PFILA2 pFila){
if(pFila->last == NULL){
return ERROR_EMPTY_QUEUE;
}
pFila->it = pFila->last;
return 0;
}
int NextFila2(PFILA2 pFila){
pFila->it = pFila->it->next;
return 0;
}
void *GetAtIteratorFila2(PFILA2 pFila){
if(pFila != NULL){
return pFila->it->node;
}
return NULL;
}
int AppendFila2(PFILA2 pFila, void *content){
if(pFila->first == NULL){
pFila->first = (PNODE2) malloc(sizeof(NODE2));
pFila->first->node = content;
pFila->first->ant = NULL;
pFila->first->next = NULL;
pFila->last = pFila->first;
pFila->it = pFila->first;
}
else {
pFila->last->next = (PNODE2) malloc(sizeof(NODE2));
pFila->last->next->ant = pFila->last;
pFila->last = pFila->last->next;
pFila->last->node = content;
}
return 0;
}
int InsertAfterIteratorFila2(PFILA2 pFila, void *content){
if(pFila->it == NULL){
return ERROR_EMPTY_QUEUE;
}
if(pFila->it == pFila->last){
return AppendFila2(pFila,content);
}
pFila->it->next->ant = (PNODE2) malloc(sizeof(NODE2));
pFila->it->next->ant->ant = pFila->it;
pFila->it->next->ant->next = pFila->it->next;
pFila->it->next = pFila->it->next->ant;
pFila->it->next->node = content;
return 0;
}
int DeleteAtIteratorFila2(PFILA2 pFila){
if(pFila == NULL){
return ERROR_EMPTY_QUEUE;
}
else if(pFila->it == NULL){
return ERROR_INVALID_IT;
}
else if(pFila->first == pFila->last){
pFila->it = NULL;
pFila->first = NULL;
pFila->last = NULL;
}
else if(pFila->it == pFila->last){
pFila->it = pFila->it->ant;
free(pFila->it->next);
pFila->last = pFila->it;
}
else if(pFila->it == pFila->first){
pFila->it = pFila->it->next;
free(pFila->it->ant);
pFila->first = pFila->it;
}
else {
pFila->it = pFila->it->next;
pFila->it->ant->ant->next = pFila->it;
free(pFila->it->ant);
pFila->it->ant = pFila->it->ant->ant;
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,i=1;
while (i<51)
{
a=2*i;
printf("%d\n",a);
i++;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE *fp1, *fp2; //ļָ
char fileName1[100], fileName2[100]; //ļ
printf("ܣȽıļӡǵһͬС\n"); //˵
printf("ҪȽϵļļļΪ1.txt2.txt\n");
scanf("%s%s", fileName1, fileName2);
if ((fp1 = fopen(fileName1, "r")) != NULL && (fp2 = fopen(fileName2, "r")) != NULL) //жļǷɹ
{
char ch1[80], ch2[80]; //ʱ洢ÿеַ
for (int i = 1; !feof(fp1) && !feof(fp2); i++)
{
//ÿ
fgets(ch1, 100, fp1);
fgets(ch2, 100, fp2);
//Ƚϲӡͬ
if (strcmp(ch1, ch2))
{
printf("ļ%dвһ\n", i);
printf("ļ%sΪ%s\n", fileName1, ch1);
printf("ļ%sΪ%s\n", fileName2, ch2);
break; //ҵһͬкѭ
}
}
//رļ
fclose(fp1);
fclose(fp2);
}
else
printf("ļʧܡ\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
/* use to pass the arguments to the thread function.*/
typedef struct
{
int **resultMat;
int **Mat_One;
int **Mat_Two;
int beginHeight;
int beginWidth;
int workload;
int resultSize[2];
int calSize;
}package;
int **readFiles(const char *path, int matrix_Size[2], int** matrix);
void makeArgs(int **resultMat, int **Mat_One, int **Mat_Two, int index[2], int workload, int resultSize[2], int calSize, package *args);
void updateBeginEle(int workerNum, int workload, int rowsize, int eleArr[2]);
void* calMatrix(void* args);
int calElement(int **Mat_One, int **Mat_Two, int h, int w, int size);
void resultToFile(const char *path, int **result, int size[2]);
void validation(int sizeOne[2], int sizeTwo[2], int threadNum);
int stoi(char const str[]);
void printError(char *str);
int main(int argc, char const *argv[])
{
if (argc != 8)
{
printf("The parameter number %d is incorrect.\n", argc);
printError("");
}
int matrix_One_Size[2] = {stoi(argv[1]), stoi(argv[2])};
int matrix_Two_Size[2] = {stoi(argv[2]), stoi(argv[3])};
int THREAD_NUM = stoi(argv[7]);
validation(matrix_One_Size, matrix_Two_Size, THREAD_NUM);
int *matrix_One[matrix_One_Size[0]];
readFiles(argv[4], matrix_One_Size, matrix_One);
int *matrix_Two[matrix_Two_Size[0]];
readFiles(argv[5], matrix_Two_Size, matrix_Two);
int result_Size[2] = {matrix_One_Size[0], matrix_Two_Size[1]};
int *resultMat[result_Size[0]];
for (size_t i = 0; i < result_Size[0]; i++)
{
resultMat[i] = (int *)malloc(result_Size[1] * sizeof(int));
for (size_t j = 0; j < result_Size[1]; j++)
{
resultMat[i][j] = 0;
}
}
pthread_t workers[THREAD_NUM];
int workload = result_Size[0] * result_Size[1] / THREAD_NUM;
int beginEle[2] = {0, 0};
for (size_t i = 0; i < THREAD_NUM; i++)
{ if(i == THREAD_NUM-1)
{
workload = result_Size[0] * result_Size[1] - workload*i;
}
package *args = malloc(sizeof *args);
makeArgs(resultMat, matrix_One, matrix_Two, beginEle, workload, result_Size, matrix_One_Size[1], args);
pthread_create(&workers[i], NULL, calMatrix, (void*) args);
updateBeginEle(i+1, workload, result_Size[1], beginEle);
}
for (size_t i = 0; i < THREAD_NUM; i++)
{
pthread_join(workers[i], NULL);
}
resultToFile(argv[6], resultMat, result_Size);
return 0;
}
void makeArgs(int **resultMat, int **Mat_One, int **Mat_Two, int index[2], int workload, int resultSize[2], int calSize, package *args)
{
args->beginHeight = index[0];
args->beginWidth = index[1];
args->calSize = calSize;
args->Mat_One = Mat_One;
args->Mat_Two = Mat_Two;
args->resultMat = resultMat;
args->resultSize[0] = resultSize[0];
args->resultSize[1] = resultSize[1];
args->workload = workload;
}
void updateBeginEle(int workerNum, int workload, int rowsize, int eleArr[2])
{
eleArr[0] = workerNum * workload / rowsize;
eleArr[1] = workerNum * workload % rowsize;
// printf("The h become %d, and the width become %d.\n", eleArr[0], eleArr[1]);
}
void *calMatrix(void* ptr)
{
package *args = (package *)ptr;
int height = args->beginHeight;
int width = args->beginWidth;
for (int i = 0; i < args -> workload; i++)
{
args -> resultMat[height][width] = calElement(args -> Mat_One, args -> Mat_Two, height, width, args -> calSize);
width++;
if(width == args->resultSize[1])
{
width =0;
height++;
}
}
return NULL;
}
int calElement(int **Mat_One, int **Mat_Two, int h, int w, int size)
{
int res = 0;
for (int i = 0; i < size; i++)
{
res += Mat_One[h][i] * Mat_Two[i][w];
}
return res;
}
void resultToFile(const char *path, int **result, int size[2])
{
FILE *file = fopen(path, "w");
if (file == NULL)
{
printf("The file at %s fails to open.\n", path);
printError("");
}
for (int i = 0; i < size[0]; i++)
{
for (int j = 0; j < size[1]; j++)
{
fprintf(file, "%d ", result[i][j]);
}
fprintf(file, "\n");
}
fclose(file);
}
void validation(int sizeOne[2], int sizeTwo[2], int threadNum)
{
if (sizeOne[0] <= 0 || sizeOne[1] <= 0 || sizeTwo[1] <= 0)
{
printError("Invalid matrix size.\n");
}
//too many worker will make them not do work as 1/2 = 1, and then last worker will do all the work.
if (threadNum <= 0 || threadNum > sizeOne[0]*sizeTwo[1])
{
printError("Invalid thread worker number.\n");
}
}
int **readFiles(const char *path, int matrix_Size[2] , int** matrix)
{
FILE *file = fopen(path, "r");
if (file == NULL)
{
printf("The file at %s fails to open.\n", path);
printError("");
}
int height = matrix_Size[0];
int width = matrix_Size[1];
for (size_t h = 0; h < height; h++)
{
matrix[h] = (int *)malloc(width * sizeof(int));
for (size_t w = 0; w < width; w++)
{
fscanf(file, "%d", &matrix[h][w]);
//printf("The number read in is %d.\n", matrix[h][w]);
}
}
fclose(file);
return matrix;
}
int stoi(char const str[])
{
if (str == NULL || str[0] == 0)
{
printError("The string is empty.\n");
}
int negative = (str[0] == '-');
int i = 0;
if (str[0] == '+' || str[0] == '-')
{
i++;
}
int result = 0;
while (str[i] != 0)
{
if (str[i] < '0' || str[i] > '9')
{
printError("The string contains non-digit.\n");
}
result *= 10;
result += str[i] - '0';
i++;
//printf("%d\n", result);
}
return negative ? -result : result;
}
void printError(char *str)
{
printf("%s", str);
exit(1);
}
|
C
|
/*
* l3g.c
*
* Created on: 15.04.2018
* Author: wojta
*/
#include "l3g.h"
ZYROS_DrvTypeDef l3gyroDRV =
{
L3GYRO_Init,
L3GYRO_DeInit,
L3GYRO_ReadID,
L3GYRO_RebootCmd,
L3GYRO_LowPower,
L3GYRO_INT1InterruptConfig,
L3GYRO_EnableIT,
L3GYRO_DisableIT,
0,
0,
L3GYRO_FilterConfig,
L3GYRO_FilterCmd,
L3GYRO_ReadXYZAngRate
};
////inicjalizacja obiektu l3gyro za pomoc wskanika InitStruct, ktry wskazuje na InitTypeDef, struktur do konfiguracji l3gyro
void L3GYRO_Init(uint16_t InitStruct)
{
uint8_t ctrl = 0x00;
//Konfiguracja podstawowego interfejsu
ZYROS_SPI_INIT();
//zapis danej MEME do adresu CTRL_REG1
ctrl = (uint8_t) InitStruct;
ZYROS_SPI_WRITE(&ctrl, L3GYRO_CTRL_REG1_ADDR, 1);
//zapis danej MEME do adresu CTRL_REG4
ctrl = (uint8_t) (InitStruct >> 8);
ZYROS_SPI_WRITE(&ctrl, L3GYRO_CTRL_REG4_ADDR, 1);
}
void L3GYRO_DeInit(void)
{
}
//Czytanie ID obiektu yroskopu L3GYRO
uint8_t L3GYRO_ReadID(void)
{
uint8_t tmp;
//Inicjujemy NISKI interfejs do komunikacji sPI
ZYROS_SPI_INIT();
///WANE odczytujemy adres Who I am?
ZYROS_SPI_READ(&tmp, L3GYRO_WHO_AM_I_ADDR, 1);
//przekazuje do tymczasowgo wskanika adres ID
return (uint8_t)tmp;
}
void L3GYRO_RebootCmd(void)
{
uint8_t tmpreg;
//Odczyt danej z MEME CTRL_REG5
ZYROS_SPI_READ(&tmpreg, L3GYRO_CTRL_REG5_ADDR, 1);
//Wyczanie lub waczanie resetu pamici
tmpreg |= L3GYRO_BOOT_REBOOTMEMORY;
//zapis danej MEME do CTRL_REG5
ZYROS_SPI_WRITE(&tmpreg, L3GYRO_CTRL_REG5_ADDR, 1);
}
//Ustawic obiekt w stan niski
void L3GYRO_LowPower(uint16_t InitStruct)
{
uint8_t ctrl = 0x00;
//zapis danej z MEMES do CTRL_REG1
ctrl = (uint8_t) InitStruct;
ZYROS_SPI_WRITE(&ctrl, L3GYRO_CTRL_REG1_ADDR, 1);
}
//Konfiguracja przerwania dla obiektu
void L3GYRO_INT1InterruptConfig(uint16_t Int1Config)
{
uint8_t ctrl_cfr = 0x00, ctrl3 = 0x00;
// odczyt adresu INT1_CFG
ZYROS_SPI_READ(&ctrl_cfr, L3GYRO_INT1_CFG_ADDR, 1);
//odczyt danej z CTRL_REG3
ZYROS_SPI_READ(&ctrl3, L3GYRO_CTRL_REG3_ADDR, 1);
ctrl_cfr &= 0x80;
ctrl_cfr |= ((uint8_t) Int1Config >> 8);
ctrl3 &= 0xDF;
ctrl3 |= ((uint8_t) Int1Config);
// zapis danej do adresu INT1_CFG
ZYROS_SPI_WRITE(&ctrl_cfr, L3GYRO_INT1_CFG_ADDR, 1);
// odczyt adresu CTRL_REG3
ZYROS_SPI_WRITE(&ctrl3, L3GYRO_CTRL_REG3_ADDR, 1);
}
//Zaaczenie ktrego przerwania, gdzie Int Sel jest wybrem ktre [ZAWARTOC METDY OGARN]
void L3GYRO_EnableIT(uint8_t IntSel)
{
uint8_t tmpreg;
//odczyt adresu CTRL_REG3
ZYROS_SPI_READ(&tmpreg, L3GYRO_CTRL_REG3_ADDR, 1);
if(IntSel == L3GYRO_INT1)
{
tmpreg &= 0x7F;
tmpreg |= L3GYRO_INT1INTERRUPT_ENABLE;
}
else if(IntSel == L3GYRO_INT2)
{
tmpreg &= 0xF7;
tmpreg |= L3GYRO_INT2INTERRUPT_ENABLE;
}
//zapis danej do CTRL_REG3
ZYROS_SPI_WRITE(&tmpreg, L3GYRO_CTRL_REG3_ADDR, 1);
}
////Wyczenie ktrego przerwania, gdzie Int Sel jest wybrem ktre [ZAWARTOC METDY OGARN]
void L3GYRO_DisableIT(uint8_t IntSel)
{
uint8_t tmpreg;
///odczyt adresu CTRL_REG3
ZYROS_SPI_READ(&tmpreg, L3GYRO_CTRL_REG3_ADDR, 1);
if(IntSel == L3GYRO_INT1)
{
tmpreg &= 0x7F;
tmpreg |= L3GYRO_INT1INTERRUPT_DISABLE;
}
else if(IntSel == L3GYRO_INT2)
{
tmpreg &= 0xF7;
tmpreg |= L3GYRO_INT2INTERRUPT_DISABLE;
}
//zapis danej do CTRL_REG3
ZYROS_SPI_WRITE(&tmpreg, L3GYRO_CTRL_REG3_ADDR, 1);
}
//Konfiguracja filtru dla obiektu
void L3GYRO_FilterConfig(uint8_t FilterStruct)
{
uint8_t tmpreg;
//zapis danej do CTRL_REG2
ZYROS_SPI_READ(&tmpreg, L3GYRO_CTRL_REG2_ADDR, 1);
tmpreg &= 0xC0;
//Konfiguracja filtru
tmpreg |= FilterStruct;
//zapis danej do CTRL_REG2
ZYROS_SPI_WRITE(&tmpreg, L3GYRO_CTRL_REG2_ADDR, 1);
}
//wyczanie i wczanie filtru
void L3GYRO_FilterCmd(uint8_t HighPassFilterState)
{
uint8_t tmpreg;
//zapis danej do CTRL_REG5
ZYROS_SPI_READ(&tmpreg, L3GYRO_CTRL_REG5_ADDR, 1);
tmpreg &= 0xEF;
tmpreg |= HighPassFilterState;
//zapis danej do CTRL_REG5
ZYROS_SPI_WRITE(&tmpreg, L3GYRO_CTRL_REG5_ADDR, 1);
}
//Pobierz dane o stanie L3GYRO
uint8_t L3GYRO_GetDataStatus(void)
{
uint8_t tmpreg;
//odczyt statusu REG dla L3(...)
ZYROS_SPI_READ(&tmpreg, L3GYRO_STATUS_REG_ADDR, 1);
return tmpreg;
}
//Odczytuje dane kta z yroskopu
void L3GYRO_ReadXYZAngRate(float *wfTdane)
{
uint8_t tmpbuffer[6] ={0};
int16_t RawData[3] = {0};
uint8_t tmpreg = 0;
float sensitivity = 0;
int i =0;
ZYROS_SPI_READ(&tmpreg,L3GYRO_CTRL_REG4_ADDR,1);
ZYROS_SPI_READ(tmpbuffer,L3GYRO_OUT_X_L_ADDR,6);
//sprawdza sposb adrsowania danych, czy to Big Endian czy Little Endian
if(!(tmpreg & L3GYRO_BLE_MSB))
{
for(i=0; i<3; i++)
{
RawData[i]=(int16_t)(((uint16_t)tmpbuffer[2*i+1] << 8) + tmpbuffer[2*i]);
}
}
else
{
for(i=0; i<3; i++)
{
RawData[i]=(int16_t)(((uint16_t)tmpbuffer[2*i] << 8) + tmpbuffer[2*i+1]);
}
}
//Ustaw czuoc yroskopu. Zostawiem do wyboru, by w testach wyonic odpowiedni
switch(tmpreg & L3GYRO_FULLSCALE_SELECTION)
{
case L3GYRO_FULLSCALE_250:
sensitivity=L3GYRO_SENSITIVITY_250DPS;
break;
case L3GYRO_FULLSCALE_500:
sensitivity=L3GYRO_SENSITIVITY_500DPS;
break;
case L3GYRO_FULLSCALE_2000:
sensitivity=L3GYRO_SENSITIVITY_2000DPS;
break;
}
for(i=0; i<3; i++)
{
wfTdane[i]=(float)(RawData[i] * sensitivity);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int a[50];
void baseMinusTwo(int n)
{
int i=-2,flag=1,j=0;
while( n>1 || -1*n>1)
{
if(n%i<0)
{
n=n/i;
n++;
a[j++]=1;
continue;
}
a[j++]=n%i;
n=n/i;
if(n%2 == 0)
flag=1;
else
flag=0;
}
if(n == -1)
{
if(flag == 1)
{
a[j++]=0;
a[j++]=1;
}
else
{
a[j++]=1;
a[j++]=1;
}
n=n/i;
}
else if(n == 1)
{
a[j++]=1;
n=n/i;
}
for(flag=j-1; flag>=0; flag--)
printf("%d",a[flag]);
}
int main()
{
baseMinusTwo(11);
return 0;
}
|
C
|
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//structures
typedef struct pot { //structure of each hole in the board
int x; //horizontal location of the pot
int y; //vertical location of the pot
int filled; //0 means not filled, 1 means filled by p1, 2 means filled by p2
struct pot* neighbor[5]; //array of pointers to the placed piece's children
} pot;
pot* newPot(){ //creation/attributes of each hole in the board
pot* newpot = malloc(sizeof(pot)); //allocate memory for new hole
newpot->filled = 0; //0 indicates blank space
newpot->x = 0; //each x is assigned to 0 or ' ', by default
newpot->y = 0;//each y is assigned to 0 or ' ', by default
for (int i = 0; i < 5; i++) newpot->neighbor[i] = NULL; //assign neighbor pointers for AI
return newpot;
}
//structure of board will contain columns, rows, and an outline of the map based around the row and column sizes
typedef struct board { //structure of the board dimensions(mapping of the board, as well as its row and columns)
int cols;
int rows;
pot*** map;
} board;
//prototypes
board* newBoard(int, int);
void freePot(pot*);
void freeBoard(board*);
void welcomeScreen();
char chooseGameMode();
void getCount(int*, int*);
char getFilled(board*, int, int);
board* setFilled(board*, int, int, int);
void printBoard(board*, char, int, int, int, int);
void freeBoard(board*);
void welcomeScreen();
char chooseGameMode();
void getCount(int*, int*);
char playerTurn(board*, int);
char aiTurn(board*, int);
int checkForWinner(board*, int, int);
void declareWinner(int, board*, int, int);
int horizontal(board*, int);
int vertical(board*, int);
int diagonal(board*);
int tieGame(board*);
char rematchGame(int);
int aiBehavior(board*);
void c4Iterative(pot*, int, int*);
board* newBoard(int row, int column) { //function to allocate memory for a custom board size
board *newboard = malloc(sizeof(board)); //allocate memory for board
pot*** newmap = (pot***)malloc(row * sizeof(pot**)); //allocate memory for pot and its attributes
int rowCount, columnCount = 0; //declarations to allocate memory for 2d array
for (rowCount = 0; rowCount < row; rowCount++) {
//board[rowCount] = (char*)malloc(column * sizeof(char));
newmap[rowCount] = (pot**)malloc(column * sizeof(pot*));
}
//for every 2d array index, give it newPot attributes (filled condition, x, y, and neighbor pointers for AI functionality)
//There are 5 neighbor pointers (left, bottom left, bottom, bottom right, and right pointers to help determine next best move)
for (rowCount = 0 ; rowCount < row ; rowCount++) {
for (columnCount = 0 ; columnCount < column; columnCount++) {
newmap[rowCount][columnCount] = newPot(); //for each [row][column], it will contain the attributes of pot
newmap[rowCount][columnCount]->filled = 0; //the [row][column] will initally be filled to 0, or in other words, blank
newmap[rowCount][columnCount]->x = rowCount; //row indices are counted
newmap[rowCount][columnCount]->y = columnCount; //column indices are counted
//NEIGHBOR 1: LEFT
newmap[rowCount][columnCount]->neighbor[0] = (columnCount == 0) ? NULL : newmap[rowCount][columnCount - 1];
//NEIGHBOR 2: BOTTOM LEFT
newmap[rowCount][columnCount]->neighbor[1] = ((rowCount == row - 1) || (columnCount == 0)) ? NULL : newmap[rowCount + 1][columnCount - 1];
//NEIGHBOR 3: BOTTOM
newmap[rowCount][columnCount]->neighbor[2] = (rowCount == row - 1) ? NULL : newmap[rowCount + 1][columnCount];
//neighbor 4 [bottom right]
newmap[rowCount][columnCount]->neighbor[3] = ((rowCount == row - 1) || (columnCount == column - 1)) ? NULL : newmap[rowCount + 1][columnCount + 1];
//neighbor 5 [right]
newmap[rowCount][columnCount]->neighbor[4] = (columnCount == column - 1) ? NULL : newmap[rowCount][columnCount + 1];
}
}
newboard->cols = column; //total column count of the board is assigned to newboard
newboard->rows = row; //total row count of the board is assigned to newboard
newboard->map = newmap; //structure of newmap is assigned to map
return newboard; //return newboard attributes
}
void freePot(pot *pot){ //free memory of board slot
free(pot);
}
void freeBoard(board* board){ //free memory of board and board size. Prevent memory leaks
int i, j = 0;
for(i = 0; i< board->rows; i++){
for(j = 0; j< board->cols; j++){
freePot(board->map[i][j]); //free every row and every column combination of board parts
}
free(board->map[i]);
}
free(board->map); //free board dimensions
free(board); //free board
}
int main (int argc, char *argv[]) { //begin main************************************************************
int row = 0; //used to help get user input row count
int column = 0; //used to help get user input column count
int turnChange = 0; //player turn
char gameMode; //single or multiplayer decision
int playerOneScore = 0; //tally player 1 score
int playerTwoScore = 0; //tally player 2 score
int returning = 1; //returning is used to loop any rematches
time_t t; //time_t is used to randomize AI column selection if a column is full
srand((unsigned)time(&t)); //srand function used in DFS for helping AI choose next best move
welcomeScreen(); //Print welcome screen
gameMode = chooseGameMode();//Choose Single or Multiplayer function. Character is assigned to gameMode
while (returning != 0) { //while loop executes if rematch game is confirmed
row = 0;
column = 0; //count for user-input 2D array size
getCount(&row, &column); //function to get dynamic count of board row and column
board *board = newBoard(row, column); //create board
int pt = 0; //pt is used to indicate which player wins the game
if (gameMode == 'A') { //singleplayer
printBoard(board, gameMode, row, column, playerOneScore, playerTwoScore);//print initial board
while (pt == 0) { //while no winner is found, execute player turn
pt = playerTurn(board, (turnChange % 1) + 1); //modulus operator is used to help switch between 1 and 2
printBoard(board, gameMode, row, column, playerOneScore, playerTwoScore);
}
if (pt == 1) { //if player 1 wins, increment score
playerOneScore++;
}
else if (pt == 2) { //if player 2 wins, increment score
playerTwoScore++;
}
declareWinner(pt, board, playerOneScore, playerTwoScore); //call a function to print game results
}
else if (gameMode == 'B') { //multiplayer (human), SEE SINGLE PLAYER (ABOVE) FOR DOCUMENTATION
printBoard(board, gameMode, row, column, playerOneScore, playerTwoScore);//print initial board
while (pt == 0) {
pt = playerTurn(board, (turnChange % 2) + 1); //pt starts with player 1
turnChange++; //move up to player 2 when while executes again
printBoard(board, gameMode, row, column, playerOneScore, playerTwoScore);
}
if (pt == 1) {
playerOneScore++;
}
else if (pt == 2) {
playerTwoScore++;
}
//turnChange = 0; //reset player turn back to player 1 for the next round
declareWinner(pt, board, playerOneScore, playerTwoScore);
}
else if (gameMode == 'C') { //multiplayer (computer), SEE SINGLE PLAYER (ABOVE) FOR DOCUMENTATION
printBoard(board, gameMode, row, column, playerOneScore, playerTwoScore); //print initial board
while (pt == 0) {
if ((turnChange % 2) + 1 == 1) { //player turn
pt = playerTurn(board, (turnChange % 2) + 1); //player 1 turn
turnChange++;
}
else if ((turnChange % 2) + 1 == 2) { //ai turn *
pt = aiTurn(board, (turnChange % 2) + 1);
turnChange++;
}
printBoard(board, gameMode, row, column, playerOneScore, playerTwoScore);
} //end while
if (pt == 1) { //if player one wins
playerOneScore++;
}
else if (pt == 2) { //if AI wins
playerTwoScore++;
}
declareWinner(pt, board, playerOneScore, playerTwoScore); //state the results
}
//turnChange = 0; //reset player turn back to player 1 for the next round
rematchGame(returning); //offer rematch
}
return 0;
}
//end main***********************************************************************************************
//program greets user with welcome screen function
void welcomeScreen() {
system("clear");
printf("==============================================================================\n");
printf("==============================================================================\n");
printf("========================= Welcome to Connect 4 ===============================\n");
printf("=================================================== By Jake Williams =========\n");
printf("================================================================= V1.00 ======\n\n");
return;
} //end void
//The user then uses a char Gamechoice (A, B, or C) to choose game mode. The selection is then returned to main.
char chooseGameMode() {
char gameChoice = ' ';
printf("Please choose a following game mode:\n"); //prints game mode options
printf("\tSingleplayer: A \n");
printf("\tMultiplayer (Human): B \n");
printf("\tMultiplayer (Computer): C \n\n");
printf("\tExit Game: Q\n\n");
while (gameChoice != 'A' && gameChoice != 'B' && gameChoice != 'C') { //while loop to choose game mode
printf("Game Mode: ");
scanf(" %c", &gameChoice); //scan user input for character
gameChoice = toupper(gameChoice); //convert to uppercase
while(getchar() != '\n'); //prevent infinite loop if string
if (gameChoice == 'Q') { //if user decides to not play the game
printf("Thank you for playing!\n");
exit(0);
}
else if (gameChoice != 'A' && gameChoice != 'B' && gameChoice != 'C' && gameChoice != 'Q') { //if invalid character is chosen
printf("Please choose a valid game mode!\n");
}
}
printf("\n");
return gameChoice; //return character choice
} //end char
//void function to determine the dynamix board size input by the user. The row and columns are saved through pointers
void getCount(int* row, int* column) { //void function to get user input of dynamic board size
int rowInput = 0;
int columnInput = 0; //ints to store custom row and custom columns sizes
system("clear");
printf("==============================================================================\n");
printf("========================= Choose Your Board Size ========================");
printf("\n==============================================================================\n");
printf ("WARNING: Any board size smaller 4x4 will result in an impossible to win match!");
printf("\n\t - Also, any arbitrarily large board will wrap around the \n\t terminal and will cause formatting issues!\n");
printf("\t - Stay below 44 rows, 44 columns to avoid formatting issues!\n\t");
printf("\n\t - ALSO, in multiplayer, the loser of a round will\n\t go FIRST in the next round!!\n\n\t");
printf ("Note: The standard board size is 6x7 [6 rows, 7 columns].\n");
while (rowInput <= 0) { //while loop for user to enter Connect 4 Row Size
printf ("\tEnter number of rows: ");
scanf ("%d", &rowInput);
while(getchar() != '\n'); //prevent infinite loop if string
if (rowInput <= 0) {
printf ("\n\tEnter a valid number!! [must be greater than 0]\n");
}//end if
}//end while
while (columnInput <= 0) { //while loop for user to enter Connect 4 Column Size
printf ("\tEnter number of columns: ");
scanf ("%d", &columnInput);
while(getchar() != '\n'); //prevent infinite loop if string
if (columnInput <= 0) {
printf ("\n\tEnter a valid number!! [must be greater than 0]\n");
}//end if
}//end while
printf("\n");
*row = rowInput; //assign integer input to parameter pointer
*column = columnInput; //assign integer input to parameter pointer
return;
} //end void
//char function to choose what to fill a board index with -- a character (piece)
char getFilled(board *board, int x, int y){
if(board->map[x][y]->filled == 1) return 'X'; //player1
if(board->map[x][y]->filled == 2) return 'O'; //player2
if(board->map[x][y]->filled == 0) return ' '; //assigned blank by default
} //end char
//board* function to fill the board index with the chosen, returned character from getFilled(board*, int ,int)
board* setFilled(board *board, int x, int y, int fill){
board->map[x][y]->filled = fill; //the piece is now placed
//printf("FILLED, Filled %d, %d with %d. Proof: %d\n", x, y, fill, board->map[x][y]->filled);
return board;
} //end board*
//void function to display game mode statistics while playing the game
//the function also prints the board format accordingly based on the user-input row and column sizes
void printBoard(board *board, char gameMode, int row, int column, int playerOne, int playerTwo) { //function to print dynamic board
int rowCount, columnCount, line, label = 0;
system("clear");//clear screen***************
printf("==============================================================================\n");
if (gameMode == 'A') { //if singleplayer, print singleplayer title
printf("===== Game Mode: Singleplayer =============================================\n");
}//end if
else if (gameMode == 'B') { //if multiplayer (human), print multiplayer (human) title
printf("===== Game Mode: Multiplayer (Human) ======================================\n");
}//end else if
else if (gameMode == 'C') { //if multiplayer (computer), print multiplayer (computer) title
printf("===== Game Mode: Multiplayer (Computer) ===================================\n");
}//end else if
printf("===== Board size: %d rows, %d columns =======================================\n", row, column);
printf("===== Scoreboard (Player 1: [%d], Player 2: [%d]) ===========================\n", playerOne, playerTwo);
printf("==============================================================================\n\n"); //ui printing
//Note: The print design was initally inspired from an external source, but the board had to be configured to work with a 2D array structure rather than a singular array
//Source: https://codereview.stackexchange.com/questions/27446/connect-four-game
for (rowCount = 0 ; rowCount < board->rows; rowCount++) { //for rowCount is less than the actual board's rows
for (columnCount = 0 ; columnCount < board->cols; columnCount++) { //for columnCount is less than the acutal board's columns
printf("|"); //print divider separating the pieces
printf(" %c ", getFilled(board, rowCount, columnCount)); //print blank character pieces initally
}//end inner for
puts("|"); //print last divider on the row
for (line = 0; line < board->cols; line++) { //for line less than board's actual column count, line will format the lining between each row
if (line == 1) {
printf("-----");
} //end if
else {
printf("----");
} //end else
}//end inner for
printf("\n");
}//end outer for
for (label = 1; label <= board->cols; label++) { //for loop to format numbers below columns correctly
if (label == 1) { //if 1
printf(" %d", label);
}//end if
else if (label < 10) { //if 2 to 9
printf(" %d", label);
}//end else if
else if (label >= 10 && label < 100) { //if 10 to 99
printf(" %d", label);
}//end else if
else if (label >= 100) {//if 100 onwards (numbers will become too big for the boxes once it reaches 1000...)
printf(" %d", label);
}//end else if
} //end for
printf("\n");
} //end void
//char function to call aiBehavior in order for the AI to determine its next best move
//then, once it finds an optimal blank spot, it will place its piece, and then checkForWinner will check to see if the move results in victory
char playerTurn(board* board, int turnChange) { //char function to let player choose a column to place next piece
int ro, co = 0; //integers to help navigate where the piece will be placed
int retry = 0;
while (retry != 1) {
printf("Choose a column (from 1 to %d)", board->cols);
printf(", Player %d: ", turnChange); // turnChange indicates which player goes next. Refer back to main() for modulus operation
while(1) { //while will execute until it is broken out of
if (1 != scanf("%d", &co) || co < 1 || co > board->cols) { //if the player does not choose a valid column on the board
while(getchar() != '\n'); //while will check to make sure that an invalid will not crash the program
puts ("\nCannot place piece. Out of bounds!");
printf("Choose a column (from 1 to %d)", board->cols);//board->cols == total number of columns
printf(", Player %d: ", turnChange); //error message to prompt user to choose a correct column
}//end if
else { //if the player chooses a valid column, escape the while loop
break;
}//end else
}//end inner while
co--; //decrement because the count technically starts from 0, not 1
for (ro = board->rows - 1; ro >= 0; ro--) { //for loop to check that the bottom of the board is empty, if not, move up and check again
//if(board->map[ro][co]->filled == 0 ) { //***
if(getFilled(board, ro, co) == ' ') { //is the spot at the bottom blank?
retry = 1;
board = setFilled(board, ro, co, turnChange); //if so, place the player piece within the board spot
return checkForWinner(board, ro, co); //check to see if the player won after placing the new piece
}//end if
else if (getFilled(board, 0, co) != ' ') { //its printing off based on the amount of columns
printf("\nThe column is full! Choose a different column!\n");
//return checkForWinner(board, ro, co);
retry = 0;
break;
}//end else if
}//end for
}//end while
return 0;
}//end char
//char function to let ai place piece
char aiTurn(board* board, int turnChange) {
int columnChoice = aiBehavior(board); //ai chooses column to place piece
int ro;//row counter to place at the bottom most piece that is not already filled
//checking***
for (ro = board->rows - 1; ro >= 0; ro--) { //for loop to check that the bottom of the board is empty, if not, move up and check again
//if(board->map[ro][co]->filled == 0 ) { //***
if (getFilled(board, ro, columnChoice) == ' ') { //is the spot at the bottom blank?
board = setFilled(board, ro, columnChoice, turnChange); //if so, place the player piece within the board spot
return checkForWinner(board, ro, columnChoice); //check to see if the player won after placing the new piece
}//end if
}//end for
return 0;
}//end char
//each time the player or ai makes a move, the checkForWinner function is called to call all functions that could possibly end the game
int checkForWinner(board* board, int row, int column) { //function to call winner check functions
if(horizontal(board, row) != 0) return horizontal(board, row); //check if horizontal win
if(vertical(board, column) != 0) return vertical(board, column); //check if vertical win
if(diagonal(board) != 0) return diagonal(board); //check if diagonal win
if(tieGame(board) != 0) return tieGame(board); //check if tie
return 0;
}//end int
//void function to print ui that shows which player wins the round
void declareWinner(int which, board *board, int playerOneScore, int playerTwoScore){ //function to print player scores before end of match
if (which == 1 || which == 2) { //if winner is player 1 or player 2, print the winner
printf("==============================================================================\n");
printf("===== Congrats! Player %d has won! ========================================\n", which);
printf("==============================================================================\n");
printf("Current scores:\n\tPlayer One: %d\n\tPlayer Two: %d\n\n", playerOneScore, playerTwoScore);
}//end if
else if (which == 3) { //if neither player wins by filling up the board
printf("The game is a tie! No winner!\n");
}//end else if
freeBoard(board); //free memory used by the board when the game ends
}//end void
//int function to scan the board for four of the same character in a row consecutively, ends game if true for, == 1 (X), == 2 (O)
int horizontal(board* board, int row) {
int win = 0; //win counter... if win increments to four, we have detected four in a row
int i = 0; //iterator
for (i = 0; i < board->cols; i++) { //increment i to board column size
if (board->map[row][i]->filled == 1) { //check if player one shape (X) is at specific index
win++; //if so, increment the win counter
if (win >= 4) { //if 4 in a row is achieved
return 1;//return player 1 victory
break;
}//end inner if
}//end outer if
else {//if not 4 in a row, reset counter
win = 0;
}//end else
}//end for
win = 0, i = 0; //reinitialize counter and iterator
for (i = 0; i < board->cols; i++) { //see previous loop, but only difference is that it is a check for 4 in a row for P2 (O)
if (board->map[row][i]->filled == 2) { //check player two
win++;
if (win >= 4) {
return 2;
break;
}//end inner if
}//end outer if
else {
win = 0;
}//end else
}//end for
return 0;
}//end int
//int function to scan the board for four of the same character in a column consecutively, ends game if true for, == 1 (X), == 2 (O)
int vertical(board* board, int column) {
int win = 0; //win counter
int i = 0; //iterator
for (i = 0; i < board->rows; i++) { //for when i is less than the total board's rows //**** SHOULD BE =
if (board->map[i][column]->filled == 1) { //if the specific position contains 'X'
win++; //increment win counter
if (win >= 4) { //if 4 in a row are detected
return 1; //player 1 wins
break;
}//end inner if
}//end outer if
else {
win = 0; //if there is not 4 in a row, reset counter to 0
}//end else
}//end for//
win = 0, i = 0; //reinitialize
for (i = 0; i < board->rows; i++) { //see previous loop, but only difference is that it is a check for 4 in a row for P2 (O)
if (board->map[i][column]->filled == 2) { //check player two
win++;
if (win >= 4) {
return 2;
break;
}
}
else {
win = 0;
}
}
return 0;
}//end int
//int function to scan for front diagonal and back diagonals
int diagonal(board* board) {
int winFront1 = 0; //win counter
int winBack1 = 0;
int winFront2 = 0;
int winBack2 = 0;
int i = 0;//iterator
int j = 0;//iterator
int k = 0;
//Check Front-Right Diagonal: (Working)
//we compare j to board columns minus 3, because if we compare to minus 2,
//it would be impossible to obtain a diagonal 4 in a row, because we go too far along the board
//LOOP 1: Forward-Right Check (WORKING)
for (j = 0; j < (board->cols - 3); j++) {
for (i = 0; ((board->rows-i-1) >= 0) && ((i+j) < board->cols); i++) { //check front right player 1 ((board->rows-i-1) >= 0)******* WORKING
//printf("Check sides j:%d, i:%d, map[%d][%d]\n",j,i, board->rows-i-1, i+j);
if (board->map[board->rows-i-1][i+j]->filled == 1) { //if the bottom-left child of placed piece is the same 'X'
//if (board->map[board->rows-i-1][i+j]->filled == 1)
winFront1++; //increment
//printf("Win\n");
if (winFront1 >= 4) { //if 4 in a row, player 1 wins
//printf("Winner\n");
return 1;
break;
}
}
else winFront1 = 0; //if not 4 in a row, restart counter
if (board->map[board->rows-i-1][i+j]->filled == 2) { //if the bottom-left child of placed piece is the same 'O'
//if (board->map[board->rows-i-1][i+j]->filled == 1)
winFront2++; //increment
//printf("Win\n");
if (winFront2 >= 4) { //if 4 in a row, player 1 wins
//printf("Winner\n");
return 2;
break;
}
}
else winFront2 = 0; //if not 4 in a row, restart counter
}//end inner for
winFront1 = 0; //redeclare to 0.... if you dont, it will wrap to next diagonal and count is as part of the four consecutive pieces
winFront2 = 0;
}//end outer for
winFront1 = 0, winBack1 = 0, winFront2 = 0, winBack2 = 0, i = 0, j = 0, k = 0; //reinitialize
k = 1; //increment k to one, as we will need to find the front forward diagonals above the bottom left index of the board
//LOOP 2: Forward-up(WORKING)
for (j = 0; j < (board->rows - 4); j++) {
for (i = 0; ((board->rows-i-k-1) >= 0) && ((i) < board->cols); i++) { //check front up player 1 ((board->rows-i-1) >= 0)******* WORKING
//printf("Check up j:%d, i:%d, map[%d][%d]\n",j,i, board->rows-i-k-1, i);
if (board->map[board->rows-i-k-1][i]->filled == 1) { //Check forward up for Player 1
//if (board->map[board->rows-i-1][i+j]->filled == 1)
winFront1++; //increment
//printf("Win\n");
if (winFront1 >= 4) { //if 4 in a row, player 1 wins
//printf("Winner\n");
return 1;
break;
}
}
else winFront1 = 0; //if not 4 in a row, restart counter
if (board->map[board->rows-i-k-1][i]->filled == 2) { //Check forward up for Player 2
//if (board->map[board->rows-i-1][i+j]->filled == 1)
winFront2++; //increment
//printf("Win\n");
if (winFront2 >= 4) { //if 4 in a row, player 1 wins
//printf("Winner\n");
return 2;
break;
}
}
else winFront2 = 0; //if not 4 in a row, restart counter
}//end inner for
k++; //increment k to move up the board
winFront1 = 0; //redeclare to 0.... if you dont, it will wrap to next diagonal and count is as part of the four consecutive pieces
winFront2 = 0;
}//end outer for
winFront1 = 0, winBack1 = 0, winFront2 = 0, winBack2 = 0, i = 0, j = 0, k = 0; //reinitialize
//start the scan from the end!!!!!!!!!
//LOOP 3: Back-left(WORKING)
for (j = 0; j < (board->cols - 3); j++) { //see previous loop for logic
for (i = 0; ((board->rows-i-k-1) >= 0) && ((i+j) < board->cols); i++) { //check back-left player 1
if (board->map[board->rows-i-k-1][board->cols-i-j-1]->filled == 1) { //Check back-left player 1
winBack1++;
//printf("Win\n");
if (winBack1 >= 4) {
//printf("Winner\n");
return 1;
break;
}
}
else winBack1 = 0; //restart counter
if (board->map[board->rows-i-k-1][board->cols-i-j-1]->filled == 2) { //Check back-left player 2
winBack2++;
//printf("Win\n");
if (winBack2 >= 4) {
//printf("Winner\n");
return 2;
break;
}
}
else winBack2 = 0; //restart counter
} //end inner for loop
winBack1 = 0;//redeclare to 0.... if you dont, it will wrap to next diagonal and count is as part of the four consecutive pieces
winBack2 = 0;
}//end outer for loop
winFront1 = 0, winBack1 = 0, winFront2 = 0, winBack2 = 0, i = 0, j = 0, k = 0; //reinitialize
k = 1;
//LOOP 4: Back-up
for (j = 0; j < (board->rows - 4); j++) { //see previous loop for logic
for (i = 0; ((board->rows-i-k-1) >= 0) && ((i+j) < board->cols); i++) { //check back-left player 1
if (board->map[board->rows-i-k-1][board->cols-i-1]->filled == 1) { //check back-up Player 1
//printf("Win\n");
if (winBack1 >= 4) {
////printf("Winner\n");
return 1;
break;
}
}
else winBack1 = 0; //restart counter
if (board->map[board->rows-i-k-1][board->cols-i-1]->filled == 2) { //check back-up Player 2
winBack2++;
//printf("Win\n");
if (winBack2 >= 4) {
//printf("Winner\n");
return 2;
break;
}
}
else winBack2 = 0; //restart counter
}
k++;
winBack1 = 0;//redeclare to 0.... if you dont, it will wrap to next diagonal and count is as part of the four consecutive pieces
winBack2 = 0;
}//end for
winFront1 = 0, winBack1 = 0, winFront2 = 0, winBack2 = 0, i = 0, j = 0, k = 0; //reinitialize
return 0;
} //end int diagonal
//int function to check whether the iterators 'tie' and 'i' can detect whether every index on the top row --
//can detect whether each column contains a character that is not blank ('X' or 'O')
//if so, iterate tie, and if tie equals the amount of columns, the board is considered full.
//if no 4 in a row is detected on the last turn, the game is tied -- no winner.
int tieGame(board* board) {
int tie = 0;
int i = 0;
for (i = 0; i < board->cols; i++) {
if (board->map[0][i]->filled != 0) {
tie++;
if (tie == board->cols) {
return 3; //tie game
}
}
else tie = 0;
}
return 0;
} //end int
//char function to let the user use char 'rematchGame' to decide whether he wants to play another match in the same game mode.
//the function makes sure input is properly converted to uppercase, while avoiding possible crashing issues if a strange value is entered
char rematchGame(int returning) {
char returner;
while (returner != 'Y' && returner != 'N') {
printf("Would you like to play another round (rematch)?\n\tYes [Y], No [N]: ");
scanf(" %c", &returner);
returner = toupper(returner);
if (returner == 'Y') {
returning = 1;
return returning;
break;
}
else if (returner == 'N') { //quit game after rejecting rematch
printf("=======================================================================\n");
printf("===== Thank You For Playing! ============================================\n");
printf("===========================================================================\n");
exit(0);
}
if (returner != 'Y' && returner != 'N') { //check to make sure a valid charaxter is entered
printf("Please enter a valid character!\n");
}
}
printf("\n");
}//end char
//int function to determine the AI behavior.
//The depth first seach takes place here... based on the "->filled" operation and the "indice of the board" serving as the depth search
//the function collaborates with the iterative DFS function to determine what is the next best move based on --
//the pointer attributes of the current piece and the previous piece placed
int aiBehavior(board* board) {
//LAST THING: Let AI check horizontal and vertical pieces, iterative, check last piece placed
//row and column will be used to pinpoint where the piece is placed, and then we will evaluate its neighbor (children)
//int nbm = 0; //next best move
int nbm_column = -1; //next best move column
int i = 0; //iterator for rows
int j = 0; //iterator for cols
//pot* piece; //pot containing the structure attributes of each hole in the board
//int c = 0;//replaces longest streak if bigger
//int k = 0; //iterator for neighbor pointers
//int p = 0;
for (j = 0; j < board->cols; j++) { //for when j is less than the board's column size
for (i = 0; i < board->rows; i++) { //search a column, and go down until you find the first filled piece
if (board->map[i][j]->filled == 1) {// || board->map[i][j]->filled == 2) { //if the first piece found is X********
break;
}//end if
}//end for
if (i == board->rows) continue; //if i becomes equivalent to the total number of rows, continue
/*
p = board->map[i][j]->filled; //p contains the integer value of filled state (0 if ' ', 1 if 'X', 2 if 'O')
if (p == 2) { //if P is 'O'
for (k = 0; k < 5; k++) { //iterate k and assign the children neighbors
piece = board->map[i][j]->neighbor[k]; //piece is a pot pointer
if (piece == NULL) continue; //BASE CASE check
if (piece->filled == 2) { //if piece is populated by 'O' ///////////
c = 1;
//c4Iterative(piece, k, &c); //pot* piece, k, &c
if (board->map[0][j]->filled != 0) {//if top of the column is populated by 'X' or 'O'
//c4Iterative(piece, k, &c);//iterate
}//end if
else if (board->map[0][j]->filled == 0) { // if top of the column is not populated
if (c > nbm) { //if c is greater than nbm
nbm = c; //c replaces next best move
if (k == 0 || k == 1) nbm_column = (j == board->cols - 1) ? j : j + 1; //left and bottom left children
else if (k == 2) nbm_column = j; //bottom child
else nbm_column = (j == 0) ? j : j - 1; //thus, the next best column is updated, bottom right and right child
} //end innest if
}//end else if
}//end if
} //end inner for
if (i != 0) { //previou
pot* prev = board->map[i - 1][j];
for (k = 0; k < 5; k++) {
piece = prev->neighbor[k];
if (piece == NULL) continue;
if (piece->filled == 2) {
c = 1;
//c4Iterative(piece, k, &c);
if (board->map[0][j]->filled != 0) {//TEST BELOW HERE
//c4Iterative(piece, k, &c);
}//TEST ABOVE HERE
else if (board->map[0][j]->filled == 0) { // ORIGINALLY == 0
if (c > nbm) {
nbm = c;
if (k == 0 || k == 1) nbm_column = (j == board->cols - 1) ? j : j + 1; // if j is equal to the board columns, place at last column
else if (k == 2) nbm_column = j;
else nbm_column = (j == 0) ? j : j - 1; //thus, the next best column is updated
}//end if
}//end else if
}//end if
}//end for
}//end if]
}//end outer if*/
} //end outer for
if (nbm_column == -1) {//if a next best move cannot be located, we will randomize the column selection to allow it to continue functioning
nbm_column = rand() % board->cols; //if nbm is not calculated, a random column is selected
while (board->map[0][nbm_column]->filled != 0) { //while loop to make sure the AI is not placing in a full column
nbm_column = rand() % board->cols; //if the column is full, randomly select a new column
}//end while
}//end if
return nbm_column; //return next best move column
//play at saved column
}//end int function//
//DFS Pseudocode Source of Inspiration: https://en.wikipedia.org/wiki/Depth-first_search
void c4Iterative(pot* piece, int j, int* c) { //seg fault reading in j and c
if (piece == NULL) return; //BASE CASE
pot* child = piece->neighbor[j]; //from the perspective of the placed piece's neighbor, we will determine if it the shapes match.
if (piece->filled == 2) { //if the piece is 'O'
*(c) = *(c)+1; //iterate ****
c4Iterative(child, j, c); //rerun the iterative process
} //end if
}//end void
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "bmp_milton.h"
#include "bmp_agris.h"
#define ext ".bmp"
#define ext2 ".txt"
int main() {
int fc[3], c, tm, i, j;
char nombre1[64], nombre2[64];
//-----------------memoria dinamica
// filas y columnas
int m = 1000, n = 1000;
int **mat = NULL;
mat = Matrix_Alloc(mat, m, n);
int function = 1;
//-----------------------------------
printf("Ingrese archivo orígen:");
scanf("%s", nombre1);
strcat(nombre1, ext);
c = bmp256(nombre1, mat, fc); //fc[fil,col,numero de ceros]
if (c == 0) {
printf("No se pudo abrir el archivo!! \n");
return 0;
}
// Función para capturar el tipo de operación y sus respectivos parámetros
readFunction(&function);
///
printf("Ingrese archivo destino: ");
scanf("%s", nombre2);
for (i = 0; i < fc[0]; i++) {
for (j = 0; j < fc[1]; j++) {
// Calcula el valor del pixel dependiendo del operador seleccionado
mat[i][j] = getTransformedPixel(mat[i][j], function);
}
}
///////////////////////////////////////////////////////////////////////////////
strcat(nombre2, ext);
salvar(nombre1, nombre2, mat, fc);
printf("Finalizado....\n");
getchar();
Matrix_Free(mat, m);
if (function == 9) {
free(ulist);
}
return 1;
}
|
C
|
//area and perimeter of rectangle
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
int main()
{
float A,P,length,width;
printf("Enter the length of rectangle : ");
scanf("%f",&length);
printf("Enter the width of rectangle : ");
scanf("%f",&width);
A = length * width;
P = 2 *(length + width);
printf("\n");
printf("Area of rectangle : %.2f\n",A);
printf("Perimeter of rectangle : %.2f",P);
return 0;
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
#include "msgs.h"
#include<time.h>
int global_ID=0;
Semaphore_t sem_global;
char** files;
int No_Of_Clients;
#define FILE_EXT ".server"
int SERVER_PORT = 0;
void Sever_Thread(void){
struct message *recv_message;
struct message *send_message;
char client_files[No_Of_Clients][256];
int current_client_count = 0;
while(1){
//sleep(1);
char filename[22];
strcpy(filename,"");
printf("Sever listening messages on server port %d \n",SERVER_PORT);
recv_message = receive(SERVER_PORT);
int reply_port = recv_message->arr_message[0];
send_message = (struct message*) malloc(sizeof(struct message));
if (recv_message->arr_message[1] == 1){
if(current_client_count == 3){
send_message->arr_message[0] = 3;
}else{
current_client_count++;
send_message->arr_message[0] = 2;
}
printf("Sever sending reply on client port %d \n",reply_port);
send(reply_port,send_message);
}else if(recv_message->arr_message[1] == 4 || recv_message->arr_message[1] == 11){
int terminate = 1;
memset(filename,0,sizeof(filename));
strcpy(filename,client_files[reply_port]);
int file_len = strlen(filename);
for(int i = 2; i < 10;i++){
if(recv_message->arr_message[i] != -1){
if(file_len >= 15){
send_message->arr_message[0] = 6;
terminate = 0;
current_client_count--;
break;
}else{
filename[file_len++] = recv_message->arr_message[i];
}
}
}
if (terminate){
send_message->arr_message[0] = 5;
if(recv_message->arr_message[1] == 11){
strcat(filename,FILE_EXT);
}
}
strcpy(client_files[reply_port],filename);
printf("Sever sending reply on client port %d \n",reply_port);
send(reply_port,send_message);
}else if (recv_message->arr_message[1] == 7 || recv_message->arr_message[1] == 8){
strcat(filename,client_files[reply_port]);
int terminate = 1;
FILE * file;
file = fopen(filename, "a");
for(int i = 2; i < 10;i++){
if(recv_message->arr_message[i] != -1){
int results = fputc(recv_message->arr_message[i], file);
}
fseek(file, 0, SEEK_END); // seek to end of file
unsigned long size = ftell(file); // get current file pointer
if(size > 1048576){
send_message->arr_message[0] = 10;
fclose(file);
int err = remove(filename);
current_client_count--;
terminate = 0;
break;
}
}
if(terminate){
send_message->arr_message[0] = 9;
fclose(file);
if(recv_message->arr_message[1] == 8){
current_client_count--;
}
}
printf("Sever sending reply on client port %d \n",reply_port);
send(reply_port,send_message);
}else{
printf("Unknown request type - Discarding message \n");
}
}
}
void Client_Thread(void){
int ID;
int client_port;
P(&sem_global);
ID = global_ID++;
client_port = ID;
char *filename = files[ID];
printf("Client : %d | File : %s - Port assigned %d \n",ID,filename,client_port);
V(&sem_global);
struct message *recv_message;
struct message *send_message;
/* Establishing server connection - Sending file name */
send_message = (struct message*) malloc(sizeof(struct message));
send_message->arr_message[0] = client_port;
send_message->arr_message[1] = 1;
printf("Client : %d | File : %s - Trying to establish connection with server\n",ID,filename);
while(1){
send(SERVER_PORT,send_message);
recv_message = receive(client_port);
if (recv_message->arr_message[0] == 2){
printf("Client : %d | File : %s - Server accepted transfer request\n",ID,filename);
break;
}else if (recv_message->arr_message[0] == 3){
printf("Client : %d | File : %s - Server rejected transfer request because it is serving 3 clients already, Will retry later\n",ID,filename);
//sleep(2);
printf("Client : %d | File : %s - Retrying to establish connection with server\n",ID,filename);
continue;
}else{
printf("Client : %d | File : %s - Unknown response from server for establishing connection request \n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}
}
/* Server connection successfull - Sending file name */
send_message->arr_message[1] = 4;
int msg_pointer = 2;
for(int i = 0;i<strlen(filename);i++){
send_message->arr_message[msg_pointer++] = filename[i];
if(msg_pointer == 10){
printf("Client : %d | File : %s - Client sending file content \n",ID,filename);
send(SERVER_PORT,send_message);
recv_message = receive(client_port);
if (recv_message->arr_message[0] == 5){
printf("Client : %d | File : %s - Server added file name \n",ID,filename);
msg_pointer = 2;
}else if (recv_message->arr_message[0] == 6){
printf("Client : %d | File : %s - File name exceeded 15 characters limit, aborting file transfer\n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}else{
printf("Client : %d | File : %s - Unknown response from server for file transfer request \n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}
}
}
while(msg_pointer != 10){
send_message->arr_message[msg_pointer++] = -1;
}
send_message->arr_message[1] = 11;
send(SERVER_PORT,send_message);
recv_message = receive(client_port);
if (recv_message->arr_message[0] == 5){
}else if (recv_message->arr_message[0] == 6){
printf("Client : %d | File : %s - File name exceeded 15 characters limit, aborting file transfer\n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}else{
printf("Client : %d | File : %s - Unknown response from server for file transfer request \n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}
/* Server connection successfull - Starting file transfer */
printf("Client : %d | File : %s - Starting file transfer to server\n",ID,filename);
send_message->arr_message[0] = client_port;
send_message->arr_message[1] = 7;
msg_pointer = 2;
FILE* file = fopen(filename, "r");
int file_char;
while ((file_char = fgetc(file)) != EOF) {
if(msg_pointer == 10){
send(SERVER_PORT,send_message);
recv_message = receive(client_port);
if (recv_message->arr_message[0] == 9){
printf("Client : %d | File : %s - Server added file content \n",ID,filename);
msg_pointer = 2;
}else if (recv_message->arr_message[0] == 10){
printf("Client : %d | File : %s - File size exceeded 1MB, aborting file transfer\n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}else{
printf("Client : %d | File : %s - Unknown response from server for file transfer request \n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}
}
send_message->arr_message[msg_pointer++] = file_char;
}
while(msg_pointer != 10){
send_message->arr_message[msg_pointer++] = -1;
}
send_message->arr_message[1] = 8;
send(SERVER_PORT,send_message);
recv_message = receive(client_port);
if (recv_message->arr_message[0] == 9){
}else if (recv_message->arr_message[0] == 10){
printf("Client : %d | File : %s - File size exceeded 1MB, aborting file transfer\n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}else{
printf("Client : %d | File : %s - Unknown response from server for file transfer request \n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}
fclose(file);
printf("Client : %d | File : %s - Transfer complete\n",ID,filename);
printf("Terminating client %d\n", ID);
thread_exit();
}
int main(int argc, char* argv[])
{
srand(time(0));
ReadyQ = newQueue(ReadyQ);
CreateSem(&sem_global,1);
No_Of_Clients = atoi(argv[1]);
for(int i = 0; i < No_Of_Clients; i++){
init_port(i);
}
SERVER_PORT = No_Of_Clients;
init_port(SERVER_PORT);
printf("Number of files passed %d \n", No_Of_Clients);
start_thread(Sever_Thread);
printf("Welcome Sever Thread (Server Thread created)\n");
files = malloc((No_Of_Clients) * sizeof *files);
for(int i = 0; i < No_Of_Clients; i++){
if(argv[i+2]){
files[i] = malloc(strlen(argv[i+2])+1);
strcpy(files[i], argv[i+2]);
}
}
for(int i = 0; i < No_Of_Clients; i++){
FILE * file;
file = fopen(argv[i+2], "r");
if(file) {
printf("Creating client for file %s\n", argv[i+2]);
start_thread(Client_Thread);
} else {
if(argv[i+2]){
printf("File %s does not exists \n", argv[i+2]);
printf("No Client Created ...\n");
}
}
}
run();
while(1)
{
sleep(1);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split_copy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thile <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/18 01:25:51 by thile #+# #+# */
/* Updated: 2018/07/22 01:35:51 by thile ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
int ft_is_space(char c)
{
if (c == ' ' || c == '\n' || c == '\t')
return (1);
else
return (0);
}
int ft_get_nb_words(char *str)
{
int nwords;
int i;
i = 0;
nwords = 0;
while (str[i])
{
while (ft_is_space(str[i]))
i++;
if (str[i] == '\0')
return (nwords);
nwords++;
while (!ft_is_space(str[i]) && str[i])
i++;
if (!str[i])
return (nwords);
}
return (nwords);
}
int ft_len_word(char *str, int i)
{
int count;
count = 0;
while (!ft_is_space(str[i]) && str[i])
{
count++;
i++;
}
return (count);
}
char **ft_split_whitespaces(char *str)
{
char **tab;
int i;
int j;
int k;
if (!(tab = malloc(sizeof(char *) * (ft_get_nb_words(str) + 1))) || !tab)
return (0);
i = 0;
j = 0;
while (str[i] != 0)
{
while (str[i] && ft_is_space(str[i]))
i++;
if (str[i])
{
k = 0;
if (!(tab[j] = malloc(sizeof(char) * (ft_len_word(str, i) + 1))))
return (0);
while (str[i] && !ft_is_space(str[i]))
tab[j][k++] = str[i++];
tab[j++][k] = 0;
}
}
tab[j] = NULL;
return (tab);
}
int main(int argc, char **argv)
{
// char str[] = " jfk wjjk jslss fkjfsdf jfsdjlfsdf fajhslfs ";
char **tab;
argc--;
argc++;
// printf("%d\n", ft_get_nb_words(argv[1]));
// printf("%d\n", ft_len_word(str, 19));
// if (argc == 2)
tab = ft_split_whitespaces(argv[1]);
for (int i = 0; tab[i] != 0; i++)
printf("%s\n", tab[i]);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,i=0;
scanf("%d",&n);
while(n!=0)
{
n/=10;
i++;
}
printf("%d",i);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
/*
TODO:
If player is first, then they get the option to choose the attribute, then the npc chooses
After attribute is selected, the winner is declared
The winner is the player who has all the cards, any players with 0 cards will be eliminated.
*/
typedef struct CardStructure
{
int Attack;
int RangedAttack;
} Card;
//We can create a method to build the deck, then deal them to the player and bot
void generateDeck(Card *deck[]);
void dealCards(Card *playerCards[], Card *ComputerCards[], Card *Deck[]);
//checks who wins
int compareResults(int playerValue, int compValue);
//winner is given the other player's card, then all cards are moved forward. also checks if player has won the game too.
int checkWin(Card *playerCards[], Card *compCards[], int winner);
int checkDecks(Card * playerDeck[], Card * compDeck[]);
//used to handle the computer's moves based on its mode
int computerMove(Card *card, int mode);
int main(void)
{
//inintialize decks/
Card *deck[60];
Card *playerDeck[60];
Card *compDeck[60];
srand(time(NULL));
//holds name
char name[50];
//gets the mode for the computer
int mode;
//declares the winner of the game, is used to also break out of the first loop.
int winner = 0;
//print welcome and how-to
printf("Welcome to warfare! In this game mode, each player will be given half a deck, the player that starts the round can choose the Attack and Ranged Attack attributes before going to war. When going to war, whoever has the stronger attribute will win the war! If it is a tie, then the cards are returned to the deck.\n");
//get name
printf("Please give a name, spaces are not allowed: ");
scanf("%s", name);
//add main loop here
while (1)
{
/* code */
//get cpu mode
printf("Please select mode 1 for a predictable computer, or select mode 2 for a random computer, or mode 3 for a smart computer: ");
scanf("%d", &mode);
//makes sure the mode is valid
while (mode < 1 || mode > 3)
{
printf("Mode choice is invalid, please choose 1, 2, or 3: ");
scanf("%d", &mode);
}
printf("Welcome %s, generating deck and distributing cards...\n", name);
//create a deck to use
generateDeck(deck);
//deal cards for the game
dealCards(playerDeck, compDeck, deck);
//vars to set the round player, the human goes first
int currentPlayer = 0;
while (winner == 0)
{
//display current card counts per deck
int playerCardsCount = 0;
for (int i = 0; i < 60; i++)
{
Card *card = playerDeck[i];
if (card != NULL)
{
playerCardsCount++;
}
}
int compCardsCount = 0;
for (int i = 0; i < 60; i++)
{
Card *card = compDeck[i];
if (card != NULL)
{
compCardsCount++;
}
}
printf("\nName: %s\nCards in deck: %d\nComputer's cards: %d\n\n", name, playerCardsCount, compCardsCount);
//used to get the rusult of the winner. Set to -1 if error occurs in results methods
if (currentPlayer == 0)
{
//get top card and display it
Card topCard = *playerDeck[0];
printf("You go first! here's the top card in your deck:\nAttack: %d\nRanged Attack: %d\n",
topCard.Attack, topCard.RangedAttack);
//get input from player and use it to make a move
int action;
printf("Please select attribute 1 (Attack) or 2 (Ranged Attack) to battle with: ");
scanf("%d", &action);
if (action == 1)
{
printf("Player has chosen the Attack attribute! Go to war!\n");
int result = compareResults(playerDeck[0]->Attack, compDeck[0]->Attack);
checkWin(playerDeck, compDeck, result);
}
else
{
printf("Player has chosen the Ranged Attack attribute! Go to war!\n");
int result = compareResults(playerDeck[0]->RangedAttack, compDeck[0]->RangedAttack);
checkWin(playerDeck, compDeck, result);
}
}
else
{
printf("The computer goes first this round.\n");
//computer makes a move
int compMove = computerMove(deck[0], mode);
if (compMove == 1)
{
printf("Computer has chosen the Attack attribute! Go to war!\n");
int result = compareResults(playerDeck[0]->Attack, compDeck[0]->Attack);
checkWin(playerDeck, compDeck, result);
}
else if (compMove == 2)
{
printf("Computer has chosen the Ranged Attack attribute! Go to war!\n");
int result = compareResults(playerDeck[0]->RangedAttack, compDeck[0]->RangedAttack);
checkWin(playerDeck, compDeck, result);
}
}
winner = checkDecks(playerDeck, compDeck);
currentPlayer = (currentPlayer == 0) ? 1 : 0;
}
//display who won the round
if (winner == 1)
{
printf("Player wins the game!\n");
}
else if (winner == 2)
{
printf("Computer wins the game!\n");
}
else
{
printf("ERR: NUM IS %d\n", winner);
}
//ask if the player wants to play again. If not, end program
char choice;
printf("Would you like to play again? enter Y for yes, enter anything else to end game: ");
scanf("%s", &choice);
if (toupper(choice) != 'Y')
{
return 0;
}
}
return 0;
}
//controls the computer
int computerMove(Card *card, int mode)
{
switch (mode)
{
//returns the first attribute to play
case 1:
return 1;
//returns one of the attibutes to play
case 2:
return (rand() % 2) + 1;
//returns the highest attribute to play
case 3:
if(card->Attack == card->RangedAttack)
{
return rand() % 2 + 1;
}
if (card->Attack > card->RangedAttack)
{
return 1;
}
else
{
return 2;
}
}
}
//compares the cards
int compareResults(int playerValue, int compValue)
{
printf("The player's strength is %d, the computer's is %d\n", playerValue, compValue);
if (playerValue > compValue)
{
return 1;
}
else if (playerValue == compValue)
{
return 0;
}
else
{
return 2;
}
}
//here, we deal the card to the players
void dealCards(Card *playerCards[], Card *ComputerCards[], Card *Deck[])
{
//keeps track of the while loop, can also be used as the deck index
int count = 0;
//Handles how the deck is divided among the players before starting.
//goes up by 1 when they recieve a card to help with the index.
int playerDeckIndex = 0;
int compDeckIndex = 0;
//controls who gets the card
int playerDealt = 0;
while (count < 60)
{
//if the playerDealt is 0, then we give the card to the player and up his deck index
if (playerDealt == 0)
{
playerCards[playerDeckIndex] = Deck[count];
playerDeckIndex++;
playerDealt = 1;
}
else //else, we give it to the computer
{
ComputerCards[compDeckIndex] = Deck[count];
compDeckIndex++;
playerDealt = 0;
}
count++;
}
for (int index = 30; index < 60; index++) // Set the non-existent cards to NULL
{
playerCards[index] = NULL;
ComputerCards[index] = NULL;
}
}
//generates the deck
void generateDeck(Card *Deck[])
{
Card card;
for (int i = 0; i < 60; i++)
{
//use the template to make the cards. Randomize attributes.
card.Attack = rand() % 10;
card.RangedAttack = rand() % 10;
Deck[i] = (Card *)malloc(sizeof(Card));
//Assign card to deck
Deck[i]->Attack = card.Attack;
Deck[i]->RangedAttack = card.RangedAttack;
}
}
//gives the winner its cards and gives fixes the cards up. Also check how many cards are in each player's deck,
//and sees which one cannot play anymore.
int checkWin(Card *playerCards[], Card *compCards[], int winner)
{
// use the winner variable to get the correct winner of the round
//display who won the round
if (winner == 1)
{
printf("Player wins the round!\n");
}
else if (winner == 2)
{
printf("Computer wins the round!\n");
}
else
{
printf("It was a tie!\n");
}
//use a case to see who won. if player 1 won, give them the cards, if bot won, give him the cards,
//if a tie, move the top card to the bottom, then shift all cards to the left
int playerCardMoved = 0;
int compCardMoved = 0;
switch (winner)
{
//A tie
case 0:
//its a tie, put top card at the bottom of the deck
for (int i = 0; i < 60; i++)
{
if (playerCards[i] == NULL && playerCardMoved == 0)
{
playerCards[i] = playerCards[0];
playerCardMoved++;
}
if (compCards[i] == NULL && compCardMoved == 0)
{
compCards[i] = compCards[0];
compCardMoved++;
}
}
break;
//player wins
case 1:
for (int i = 0; i < 60; i++)
{
if (playerCards[i] == NULL)
{
playerCards[i] = compCards[0];
playerCards[i + 1] = playerCards[0];
break;
}
}
break;
//computer wins
case 2:
for (int i = 0; i < 60; i++)
{
if (compCards[i] == NULL)
{
compCards[i] = playerCards[0];
compCards[i + 1] = compCards[0];
break;
}
}
}
//shift all cards over
for (int i = 1; i < 60; i++)
{
playerCards[i - 1] = playerCards[i];
compCards[i - 1] = compCards[i];
}
}
//check if deck is empty, returns winner;
int checkDecks(Card *playerDeck[], Card *compDeck[])
{
int isEmpty = 1;
//check if deck is empty
for (int i = 0; i < 60; i++)
{
if (playerDeck[i] != NULL)
{
isEmpty = 0;
}
}
if (isEmpty == 1)
{
return 2;
}
//do the same for the computer
isEmpty = 1;
for (int i = 0; i < 60; i++)
{
if (compDeck[i] != NULL)
{
isEmpty = 0;
}
}
if (isEmpty == 1)
{
return 1;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int ch;
char file[80];
FILE *fp;
unsigned long count = 0;
do {
printf("Plz type in the file name\n");
} while (scanf("%s", file) != 1);
if ((fp = fopen(file, "r")) == NULL) {
printf("Can't open %s\n", file);
exit(EXIT_FAILURE);
}
while ((ch = getc(fp)) != EOF) {
putc(ch, stdout);
count++;
}
fclose(fp);
printf("\nFile %s has %lu chars\n", file, count);
return 0;
}
|
C
|
#include <stdbool.h>
#include <stddef.h>
#include <fllib/Cstring.h>
#include <fllib/Mem.h>
#include <fllib/Std.h>
#include "char.h"
FlutAssertResult* flut__assert_char_equals(char expected, char actual) {
struct FlutAssertResult *result = flut_assert_result_new();
result->success = expected == actual;
if (!result->success) {
result->message = fl_cstring_vdup("Expecting char to be equals to '%c', actually '%c'", expected, actual);
}
return result;
}
FlutAssertResult* flut__assert_char_not_equals(char expected, char actual) {
struct FlutAssertResult *result = flut_assert_result_new();
result->success = expected != actual;
if (!result->success) {
result->message = fl_cstring_vdup("Expecting string to be not-equals to '%c', actually '%c'", expected, actual);
}
return result;
}
|
C
|
#include <stdio.h>
#include <string.h>
struct course {
int id;
char title[40];
float hours;
};
int main() {
struct course cs1 = {341279,
"intro to C++", 12.5};
struct course cs2;
/*initialize cs2*/
cs2.id = 341281;
strcpy(cs2.title, "Advanced C++");// String assignment requires strcpy() from the string.h library.
cs2.hours = 14.25;
/*display course info*/
printf("%d\t%s\t%4.2f\n", cs1.id, cs1.title, cs1.hours);// Also note the format specifiers %4.2f include width and precision options.
printf("%d\t%s\t%4.2f\n", cs2.id, cs2.title, cs2.hours);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_type.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mobounya <mobounya@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/14 12:56:11 by mobounya #+# #+# */
/* Updated: 2021/05/19 12:33:56 by mobounya ### ########.fr */
/* */
/* ************************************************************************** */
#include "forty_two_sh.h"
/*
** Lookup name type in the default order.
** Output format is either [WORD_OUTPUT] or [DEFAULT_OUTPUT].
*/
int default_lookup(char *name, int format)
{
int cmd_type;
char *value;
cmd_type = get_cmdtype(name, &value);
if (cmd_type == HASH)
return (ft_print_type_hash(name, value, format));
else if (cmd_type == ALIAS)
return (ft_print_type_alias(name, value, format));
else if (cmd_type == KEYWORD)
return (ft_print_type_keyword(name, format));
else if (cmd_type == BUILTIN)
return (ft_print_type_builtin(name, format));
else if (cmd_type == FILE)
return (ft_print_type_binary(name, value, format));
ft_type_not_found(name);
return (1);
}
/*
** Lookup name type, print all if name is multiple types
** Output format is either [WORD_OUTPUT] or [DEFAULT_OUTPUT].
*/
int lookup_all_types(char *name, int format)
{
char *value;
int status;
status = 1;
value = is_alias(name);
if (value)
{
ft_print_type_alias(name, value, format);
status = 0;
}
if (check_builtins(name))
{
ft_print_type_builtin(name, format);
status = 0;
}
value = is_binary(name);
if (value)
{
ft_print_type_binary(name, value, format);
status = 0;
}
if (status)
ft_type_not_found(name);
return (status);
}
/*
** Return path of name, if (type -t NAME) return file.
*/
int ft_type_check_if_file(char *name, int flag)
{
char *valueue;
int type;
type = get_cmdtype(name, &valueue);
if (type == 0)
return (1);
if (type == FILE)
{
if (flag & (1 << LOW_T_FLAG))
ft_putendl("file");
else
ft_putendl(valueue);
}
return (0);
}
/*
** Return path of name, even if (type -t NAME) doesn't return file.
*/
int ft_type_force_path_search(char *name, int flag)
{
char *value;
value = is_binary(name);
if (value != NULL)
{
if (flag & (1 << LOW_T_FLAG))
ft_putendl("file");
else
ft_putendl(value);
return (0);
}
return (1);
}
int ft_type(char **command)
{
unsigned int i;
unsigned int flag;
i = 1;
flag = 0;
while (command[i] && command[i][0] == '-')
{
if (ft_strncmp(command[i], "--", 2) == 0)
{
i++;
break ;
}
if (ft_parse_type_options(command[i], &flag))
return (1);
i++;
}
if (command[i] == NULL)
return (0);
return (ft_execute_type(command + i, flag));
}
|
C
|
#include <stdio.h>
#define D_S_MAIN 1
#define D_S 0
#if D_S
void strclr(void);
#endif
int strend(char*, char*);
int strend(char* s, char* t){
s = &s[strlen(s) - strlen(t)];
while(*s++ == *t++)
;
if (*t == '\0') return 1;
else return 0;
}
#if D_S_MAIN
int main(){
char a[25] = "Hello World!\n";
char b[30] = "World\0World!\n";
clrscr();
printf("strend(%s , %s) = %d\n", a, b, strend(a, b));
printf("strend(%s , %s) = %d\n", a, &b[6], strend(a, &b[6]));
return 0;
}
#endif
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#define CLOCKID CLOCK_REALTIME
#define SIG SIGALRM
FILE *fp = NULL;
static void
handler(int sig)
{
printf("Hello World!!!\n");
fflush(fp);
fprintf(fp, "Hello World\n");
system("date");
}
int
main(int argc, char *argv[])
{
fp = fopen("test.log", "a");
timer_t timerid;
struct sigevent sev;
struct itimerspec its;
long long freq_nanosecs;
signal(SIGALRM, handler);
/* Create the timer */
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGALRM;
sev.sigev_value.sival_ptr = &timerid;
timer_create(CLOCKID, &sev, &timerid);
/* Start the timer */
freq_nanosecs = atoll("3000000000");
its.it_value.tv_sec = (size_t)3;
its.it_value.tv_nsec = (long)0;
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;
timer_settime(timerid, 0, &its, NULL);
while(1);
}
|
C
|
/**
* @file header.h
* @author Prerna Agrawal
* @brief Header file for Contact Management System
* @version 0.1
* @date 2021-04-10
*
* @copyright Copyright (c) 2021
*
*/
#ifndef __HEADER_H__
#define __HEADER_H__
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
/**
* @brief Structure to store name, address, email and phone number of a person
*
*/
struct contact
{
long long ph;
char name[20],add[20],email[20];
} list;
/**
* @brief two file pointers to store values to and retrieve values from the actual file
*
*/
FILE *fp, *ft;
/**
* @brief function to display the main menu
*
* @return displayed menu
*/
void main_menu();
/**
* @brief function to add new entries to the existing database
*
* @param ph
* @param name
* @param add
* @param email
* @return int
*/
int add(long long int ph, char name[], char add[], char email[]);
/**
* @brief function to check for the validity of the city
*
* @param ch
* @return int
*/
int validity(char ch[]);
/**
* @brief function to check for validity of email id
*
* @param test
* @return int
*/
int isValid(char test[]);
/**
* @brief function to check for the validity of phone
*
* @param n
* @return int
*/
int checkPh(long long n);
/**
* @brief function to edit existing database
*
* @param ph
* @param name
* @param add
* @param email
* @param edit_name
* @return int
*/
int edit(long long int ph, char name[20], char add[20], char email[20], char edit_name[20]);
/**
* @brief function to search for entries in the existing database
*
* @param edit_name
* @return int
*/
int search(char edit_name[20]);
/**
* @brief function to view list of entries in the existing database
*
* @return list of contacts present in the database
*/
int view();
/**
* @brief function to delete an entry from the existing database
*
* @param edit_name
* @return int
*/
int del(char edit_name[20]);
/**
* @brief function to input values for add and edit functions
*
*/
void inputDet();
#endif /* #define __HEADER_H__ */
|
C
|
/*
** EPITECH PROJECT, 2020
** ex04
** File description:
** main
*/
#include "string.h"
int main(void)
{
string_t s;
string_t test;
printf("-----init-----\n");
string_init(&s, "tout le monde");
string_init(&test, "Bonjour Tout le monde");
printf("%s\n", s.str);
printf("%s\n", test.str);
printf("-----assign_s-----\n");
test.assign_s(&test, &s);
printf("%s\n", test.str);
printf("-----assign_c-----\n");
test.assign_c(&test, "Ca va");
printf("%s\n", test.str);
printf("-----append_s-----\n");
test.append_s(&test, &s);
printf("%s\n", test.str);
printf("-----append_c-----\n");
test.append_c(&test, "haha");
printf("%s\n", test.str);
string_destroy(&s);
string_destroy(&test);
return (0);
}
|
C
|
/*
============================================================================
Name : practicaExamen1.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
#include "Controller.h"
#include "sale.h"
#include "menu.h"
#define MOVIE "data.csv"
int main(void) {
LinkedList* movieList = ll_newLinkedList();
LinkedList* moviesAmount=NULL;
int cont;
do {
cont = menu();
switch (cont) {
case 1:
if(!controller_loadFromText(MOVIE, movieList))
{
moviesAmount=ll_map(movieList, soldMap);
}
break;
case 2:
controller_add(moviesAmount);
break;
case 3:
controller_edit(moviesAmount);
break;
case 4:
controller_remove(moviesAmount);
break;
case 5:
controller_List(moviesAmount);
break;
case 6:
controller_sort(moviesAmount);
break;
case 7:
controller_report(moviesAmount);
break;
case 8:
controller_saveAsText(MOVIE, moviesAmount);
break;
case 9:
ll_deleteLinkedList(movieList);
ll_deleteLinkedList(moviesAmount);
break;
}
} while (cont != 8);
return EXIT_SUCCESS;
}
|
C
|
/*
*simple FS Driver for zBL
*(c) 2017 Zachary James Schlotman
*/
#include "lib.h"
#include "mem.h"
#include "simpfs.h"
#include "libc/include/environment.h"
#include <stdint.h>
/*
*Finds free block and returns the lba of that block
*/
uint32_t find_free(){
uint32_t ret = 1;
uint8_t *buf = malloc(1024);
_ata_read_master(buf,ret,0);
while(buf[0]){
ret++;
_ata_read_master(buf,ret,0);
}
return ret;
}
/*
*Opens a file returns a file descriptor
*ONLY SUPPORTS READING AS OF NOW
*/
int open(const char *fname,int options){
struct fd *tbl = (struct fd *)0x00007E00;
int i = 0;
while(tbl->alloc){
i++;
tbl+=sizeof(*tbl);
}
if(!(options >> 1 & 1)){
struct fd *n = getInfo(fname);
if(!n){
// kprintf("Failed to open file\n");
bzero(n,sizeof(*n));
return -1;
}
n->type = options;
memcpy(tbl,n,sizeof(*tbl));
return i;
}
}
/*
*Gets file descriptor pointer from fd
*/
struct fd *getFd(int n){
struct fd *tbl = (struct fd *)0x00007E00;
int i = 0;
while(i < n){
i++;
tbl+=sizeof(*tbl);
}
return tbl;
}
int tell(int fd){
struct fd *f = getFd(fd);
return f->pos;
}
int lseek(int fd,int n,int mode){
struct fd *pntr = getFd(fd);
if(mode == SEEK_CUR);
else if (mode == SEEK_END){
pntr->pos = fsize(fd);
}else if(mode == SEEK_SET){
pntr->pos = n;
}
return pntr->pos;
}
/*
*Gets info from disk to store in a pointer that can be accessed through a file descriptor
*/
void ddump(DIR *d){
kprintf("ENT:\n");
kprintf("[alloc]%d [type]%d [nxtLba]%d\n",d->ent->alloc,d->ent->type,d->ent->nxtLba);
kprintf("FHDR:\n");
kprintf("[alloc]%d [namelen]%d [name]%s\n",d->fhdr->alloc,d->fhdr->namelen,d->fhdr->name);
kprintf("DHDR:\n");
kprintf("[nxtTreeLba]%d\n",d->dhdr->nxtTreeLba);
}
void dent(struct tree_ent *e){
kprintf("ENT:\n");
kprintf("[alloc]%d [type]%d [nxtLba]%d\n",e->alloc,e->type,e->nxtLba);
}
struct fd *getInfo(const char *str){
char **s = sep(str,'/');
char *dpath = malloc(strlen(str));
int i = 0;
strcpy(dpath,"/");
while(s[i + 1] != 0){
strcat(dpath,s[i]);
strcat(dpath,"/");
i++;
}
DIR *d = opendir(dpath);
if(!d){
kprintf("Error opening dir\n");
return 0;
}
struct tree_ent *ent = malloc(sizeof(*ent));
uint8_t *buf = malloc(512);
struct tree_dirhdr *dhdr = malloc(sizeof(*dhdr));
_ata_read_master(buf,d->dhdr->nxtTreeLba,0);
memcpy(ent,buf,sizeof(*ent));
int prevLba = d->dhdr->nxtTreeLba;
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
while(ent->alloc){
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
memcpy(dhdr,buf + sizeof(*ent) + sizeof(*fhdr),sizeof(*dhdr));
if(ent->type == __TYPE_FILE && strcmp(fhdr->name,s[i]) == 0){
struct fd *ret = malloc(sizeof(*ret));
bzero(ret,sizeof(*ret));
ret->alloc = 1;
ret->tLba = prevLba;
ret->pos = 0;
memcpy(ret->name,str,strlen(str));
return ret;
}
prevLba = ent->nxtLba;
if(ent->nxtLba == 0)
break;
_ata_read_master(buf,ent->nxtLba,0);
memcpy(ent,buf,sizeof(*ent));
}
return 0;
}
/*
*Returns 1 if the file system is present on the disk and 0 when it is not
*/
int isSimpfs(){
uint8_t * buf = malloc(512);
_ata_read_master(buf,0,0);
return buf[0] == 0x7f && buf[1] == 'S' && buf[2] == 'I' && buf[3] == 'M' && buf[4] == 'P';
}
void setenv(char *name,char *val){
struct envVar *top = (struct envVar *)0x00900000;
while(top->nxt != 0)
top = top->nxt;
struct envVar *env = malloc(sizeof(*env));
strcpy(env->name,name);
strcpy(env->val,val);
env->nxt = 0;
top->nxt = env;
}
char *getenv(char *name){
struct envVar *top = (struct envVar *)0x00900000;
while(top != 0){
if(strcmp(top->name,name) == 0)
return top->val;
top = top->nxt;
}
return 0;
}
/*
*Creates the file system
*/
int mkfs(){
uint8_t *buf = malloc(512);
buf[0] = 0x7f;
buf[1] = 'S';
buf[2] = 'I';
buf[3] = 'M';
buf[4] = 'P';
struct tree_ent *head = malloc(512);
head->alloc = 1;
head->type = __TYPE_DIR;
head->nxtLba = 1;
memcpy(buf + 5,head,sizeof(*head));
_ata_write_master(buf,0);
mkdir("/");
}
/*
*Zeros out pointer
*/
void bzero(void *vpntr,int n){
uint8_t *pntr = (uint8_t*)vpntr;
for(int i = 0; i < n;i++)
pntr[i] = 0;
}
/*
*Creates dir by the name of name
*returns 0 on failure and 1 on success
*/
int f = 0;
int mkdir(const char *name){
uint8_t **s = sep(name,'/');
int i = 0;
uint8_t *buf = malloc(512);
struct tree_ent *ent = malloc(sizeof(*ent));
bzero(ent,sizeof(*ent));
_ata_read_master(buf,0,0);
memcpy(ent,buf + 5,sizeof(*ent));
int prevLba = ent->nxtLba;
struct tree_dirhdr *dhdr = malloc(sizeof(*dhdr));
bzero(dhdr,sizeof(*dhdr));
_ata_read_master(buf,ent->nxtLba,0);
if(strcmp(name,"/") != 0){
memcpy(ent,buf,sizeof(*ent));
memcpy(dhdr,buf + sizeof(*ent) + sizeof(struct tree_filehdr),sizeof(*dhdr));
_ata_read_master(buf,dhdr->nxtTreeLba,0);
memcpy(ent,buf,sizeof(*ent));
bzero(dhdr,sizeof(*dhdr));
}
int svLba = 0;
while(s[i+1] != 0){
_ata_read_master(buf,ent->nxtLba,f);
memcpy(ent,buf,sizeof(*ent));
int prevAlloc = 1;
while(ent->alloc){
if(ent->type == __TYPE_DIR){
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
if(strcmp(fhdr->name,s[i]) == 0){
memcpy(dhdr,buf + sizeof(*ent) + sizeof(*fhdr),sizeof(*dhdr));
prevAlloc = ent->alloc;
prevLba = ent->nxtLba;
_ata_read_master(buf,dhdr->nxtTreeLba,f);
memcpy(ent,buf,sizeof(*ent));
if(s[i + 2] == 0)
svLba = dhdr->nxtTreeLba;
break;
}
}
prevAlloc = ent->alloc;
_ata_read_master(buf,ent->nxtLba,f);
memcpy(ent,buf,sizeof(*ent));
}if(!prevAlloc){
return 0;
}
i++;
}
struct tree_filehdr *tfhdr = buf + sizeof(*ent);
if(strcmp(tfhdr->name,s[i]) == 0 && strlen(s[i]) > 0){
kprintf("[0]Error: Directory exists!\n");
return 0;
}
while(ent->nxtLba != 0){
prevLba = ent->nxtLba;
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
if(strcmp(fhdr->name,s[i]) == 0 && strlen(s[i]) > 0){
kprintf("[1]Error: Directory %s exists!\n",s[i]);
return 0;
}
_ata_read_master(buf,ent->nxtLba,f);
memcpy(ent,buf,sizeof(*ent));
}
ent->nxtLba = find_free(f);
char *pntr = malloc(512);
_ata_read_master(pntr,prevLba,0);
memcpy(pntr,ent,sizeof(*ent));
_ata_write_master(pntr,prevLba);
free(ent);
ent = malloc(sizeof(*ent));
bzero(ent,sizeof(*ent));
ent->alloc = 1;
ent->type = __TYPE_DIR;
ent->nxtLba = 0;
free(dhdr);
dhdr = malloc(sizeof(*dhdr));
struct tree_filehdr *fhdr = malloc(1024);
fhdr->alloc = 1;
bzero(fhdr->name,80);
if(strcmp(name,"/") != 0){
fhdr->namelen = strlen(s[i]);
memcpy(fhdr->name,s[i],fhdr->namelen);
}else{
fhdr->namelen = strlen(name);
memcpy(fhdr->name,name,strlen(name));
}
dhdr->nxtTreeLba = 0;
buf = malloc(512);
bzero(buf,512);
uint32_t lba = find_free(f);
memcpy(buf,ent,sizeof(*ent));
_ata_write_master(buf,find_free(f));
ent->nxtLba = 0;
memcpy(buf,ent,sizeof(*ent));
memcpy(buf + sizeof(*ent),fhdr,sizeof(*fhdr));
memcpy(buf + sizeof(*ent) + sizeof(*fhdr),dhdr,sizeof(*dhdr));
_ata_write_master(buf,lba);
dhdr->nxtTreeLba = find_free(f);
memcpy(buf + sizeof(*ent) + sizeof(*fhdr),dhdr,sizeof(*dhdr));
_ata_write_master(buf,lba);
struct tree_ent *nent = malloc(sizeof(*nent));
struct tree_filehdr *nfhdr = malloc(sizeof(*nfhdr));
struct tree_dirhdr *ndhdr = malloc(sizeof(*ndhdr));
ndhdr->nxtTreeLba = dhdr->nxtTreeLba;
nent->alloc = 1;
nent->type = __TYPE_DIR;
nent->nxtLba = 0;
nfhdr->alloc = 1;
nfhdr->namelen = 1;
bzero(nfhdr->name,80);
strcpy(nfhdr->name,".");
uint8_t *b = malloc(512);
memcpy(b,nent,sizeof(*nent));
_ata_write_master(b,dhdr->nxtTreeLba);
nent->nxtLba = find_free(f);
int wrlba = nent->nxtLba;
memcpy(b,nent,sizeof(*nent));
memcpy(b + sizeof(*nent),nfhdr,sizeof(*nfhdr));
memcpy(b + sizeof(*nent) + sizeof(*nfhdr),ndhdr,sizeof(*ndhdr));
_ata_write_master(b,dhdr->nxtTreeLba);
nent = malloc(sizeof(*nent));
nfhdr = malloc(sizeof(*nfhdr));
ndhdr = malloc(sizeof(*ndhdr));
bzero(nent,sizeof(*nent));
bzero(nfhdr,sizeof(*nfhdr));
bzero(ndhdr,sizeof(*ndhdr));
ndhdr->nxtTreeLba = svLba;
nent->alloc = 1;
nent->type = __TYPE_DIR;
nent->nxtLba = 0;
nfhdr->alloc = 1;
nfhdr->namelen = 2;
bzero(nfhdr->name,80);
strcpy(nfhdr->name,"..");
b = malloc(512);
memcpy(b,nent,sizeof(*nent));
memcpy(b + sizeof(*nent),nfhdr,sizeof(*nfhdr));
memcpy(b + sizeof(*nent) + sizeof(*nfhdr),ndhdr,sizeof(*ndhdr));
_ata_write_master(b,wrlba);
return 1;
}
/*
*Returns DIR pointer that holds all the info currently needed for I/O on directories or 0 on error
*/
DIR *opendir(const char *name){
uint8_t **s = sep(name,'/');
struct tree_ent *ent = malloc(sizeof(*ent));
bzero(ent,sizeof(*ent));
uint8_t *buf = malloc(1024);
_ata_read_master(buf,0,f);
memcpy(ent,buf + 5,sizeof(*ent));
_ata_read_master(buf,ent->nxtLba,f);
struct tree_dirhdr *dhdr = malloc(sizeof(*dhdr));
bzero(dhdr,sizeof(*dhdr));
if(strcmp(name,"/") != 0){
memcpy(ent,buf,sizeof(*ent));
memcpy(dhdr,buf + sizeof(*ent) + sizeof(struct tree_filehdr),sizeof(*dhdr));
_ata_read_master(buf,dhdr->nxtTreeLba,f);
memcpy(ent,buf,sizeof(*ent));
bzero(dhdr,sizeof(*dhdr));
}
int i = 0;
int prevLba = 0;
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
if(strcmp(name,"/") != 0){
while(s[i] != 0 && s[i][0]!= 0){
_ata_read_master(buf,ent->nxtLba,f);
memcpy(ent,buf,sizeof(*ent));
int prevAlloc = 1;
while(ent->alloc == 1){
if(ent->type == __TYPE_DIR){
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
if(strcmp(fhdr->name,s[i]) == 0){
memcpy(dhdr,buf + sizeof(*ent) + sizeof(*fhdr),sizeof(*dhdr));
prevAlloc = ent->alloc;
prevLba = ent->nxtLba;
_ata_read_master(buf,dhdr->nxtTreeLba,f);
memcpy(ent,buf,sizeof(*ent));
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
memcpy(dhdr,buf + sizeof(*ent) + sizeof(*fhdr),sizeof(*dhdr));
break;
}
}
prevAlloc = ent->alloc;
_ata_read_master(buf,ent->nxtLba,f);
memcpy(ent,buf,sizeof(*ent));
}if(!prevAlloc){
return 0;
}
i++;
}
}else{
_ata_read_master(buf,ent->nxtLba,f);
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
memcpy(dhdr,buf + sizeof(*ent) + sizeof(*fhdr),sizeof(*dhdr));
}
struct __DIR *ret = malloc(sizeof(*ret));
ret->ent = malloc(sizeof(*ent));
memcpy(ret->ent,ent,sizeof(*ent));
ret->fhdr = malloc(sizeof(*fhdr));
memcpy(ret->fhdr,fhdr,sizeof(*fhdr));
ret->dhdr = malloc(sizeof(*dhdr));
memcpy(ret->dhdr,dhdr,sizeof(*dhdr));
return ret;
}
/*
*Returns the size of the file
*/
int fsize(const char *name){
char **arr = sep(name,'/');
char *path = malloc(1024);
int i = 0;
strcpy(path,"/");
while(arr[i+1] != 0){
strcat(path,arr[i]);
strcat(path,"/");
i++;
}
DIR *d = opendir(path);
if(!d)
return -1;
uint32_t lba = d->dhdr->nxtTreeLba;
struct tree_ent *ent = malloc(sizeof(*ent));
bzero(ent,sizeof(*ent));
uint8_t *buf = malloc(512);
_ata_read_master(buf,lba,0);
memcpy(ent,buf,sizeof(*ent));
int prevLba = 0;
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
while(ent->alloc){
if(ent->type == __TYPE_FILE){
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
if(strcmp(fhdr->name,arr[i]) == 0){
return ent->size;
}
}
lba = ent->nxtLba;
if(lba == 0)
return -1;
prevLba = ent->nxtLba;
_ata_read_master(buf,ent->nxtLba,0);
memcpy(ent,buf,sizeof(*ent));
}
return -1;
}
/*
*Reads from n bytes from fd into buf
*Returns bytes read
*/
int read(int fd,void *pntr,int n){
struct fd *f = getFd(fd);
if(f->type & 1){
char **arr = sep(f->name,'/');
char *path = malloc(1024);
int i = 0;
strcpy(path,"/");
while(arr[i+1] != 0){
strcat(path,arr[i]);
strcat(path,"/");
i++;
}
DIR *d = opendir(path);
if(!d)
return 0;
uint32_t lba = d->dhdr->nxtTreeLba;
struct tree_ent *ent = malloc(sizeof(*ent));
bzero(ent,sizeof(*ent));
uint8_t *buf = malloc(512);
bzero(buf,512);
_ata_read_master(buf,lba,0);
memcpy(ent,buf,sizeof(*ent));
int prevLba = 0;
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
while(ent->alloc){
if(ent->type == __TYPE_FILE){
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
if(strcmp(fhdr->name,arr[i]) == 0){
break;
}
}
lba = ent->nxtLba;
if(lba == 0)
return -1;
prevLba = ent->nxtLba;
_ata_read_master(buf,ent->nxtLba,0);
memcpy(ent,buf,sizeof(*ent));
}
if(!ent->alloc){
return -1;
}
i = 0;
uint32_t offset = 0;
/*
*This loop makes it so that we start at the correct lba and offset
*by looping through until we meet or exceed the offset set by the
*file descriptor
*/
_ata_read_master(buf,prevLba,0);
struct tree_fexclusive *fex = malloc(sizeof(*fex));
memcpy(fex,buf + sizeof(*ent) + sizeof(struct tree_filehdr),sizeof(*fex));
lba = fex->nxtFLba;
i = 0;
while(i < f->pos){
_ata_read_master(buf,lba,0);
struct tree_ent *tent = malloc(sizeof(*tent));
memcpy(tent,buf,sizeof(*tent));
memcpy(fex,buf + sizeof(*tent),sizeof(*fex));
if(512-sizeof(*ent)-sizeof(*fex)>(f->pos-i)){
break;
}
lba = fex->nxtFLba;
i+=512-sizeof(*ent)-sizeof(*fex);
}
/*
*Reads the data from the file into the pointer
*/
offset = 0;
i = 0;
int init = 1;
int remaining = n;
while(offset < n){
_ata_read_master(buf,lba,0);
struct tree_ent *tent = malloc(sizeof(*tent));
memcpy(tent,buf,sizeof(*tent));
memcpy(fex,buf + sizeof(*ent),sizeof(*fex));
lba = fex->nxtFLba;
if(lba != 0){
if(remaining < 512-sizeof(*ent)-sizeof(*fex)){
if(!init)
memcpy(pntr + offset,buf + sizeof(*tent) + sizeof(*fex),n-offset);
else{
memcpy(pntr + offset,buf + sizeof(*tent) + sizeof(*fex) + f->pos%(512-sizeof(*tent)-sizeof(*fex)),n-offset);
init = 0;
}offset+=n-offset;
f->pos +=offset;
remaining = 0;
return offset;
}else if(!init)
memcpy(pntr + offset,buf + sizeof(*tent) + sizeof(*fex),512-sizeof(*tent)-sizeof(*fex));
else{
memcpy(pntr + offset,buf+sizeof(*tent)+sizeof(*fex)+f->pos%(512-sizeof(*tent)-sizeof(*fex)),512-sizeof(*tent)-sizeof(*fex)-f->pos);
init=0;
}if(!init){
offset+=512-sizeof(*ent)-sizeof(*fex);
remaining-=512-sizeof(*ent)-sizeof(*fex);
}else{
offset+=512-sizeof(*ent)-sizeof(*fex)-f->pos;
init = 0;
remaining-=512-sizeof(*ent)-sizeof(*fex)-f->pos;
}
}else{
struct tree_fend *fend = malloc(sizeof(*fend));
memcpy(fend,buf + sizeof(*tent) + sizeof(*fex),sizeof(*fend));
if(!init)
memcpy(pntr + offset,buf + sizeof(*fex) + sizeof(*fend),fend->finalBytes);
else
memcpy(pntr + offset,buf + sizeof(*fex) + sizeof(*fend)+f->pos,fend->finalBytes);
offset+=fend->finalBytes;
f->pos = f->pos+offset;
return offset;
}
}
f->pos += offset;
return offset;
}else
return -2;
}
int write(int fd,void *pntr,int n){
struct fd *f = getFd(fd);
if(f->type >> 1 & 1){
char **s = sep(f->name,'/');
char *path = malloc(1024);
int i = 0;
strcat(path,"/");
while(s[i + 1] != 0){
strcat(path,s[i]);
strcat(path,"/");
i++;
}
DIR *d = opendir(path);
if(!d)
return -1;
uint32_t lba = d->dhdr->nxtTreeLba;
struct tree_ent *ent = malloc(sizeof(*ent));
bzero(ent,sizeof(*ent));
uint8_t *buf = malloc(512);
bzero(buf,512);
_ata_read_master(buf,lba,0);
memcpy(ent,buf,sizeof(*ent));
int prevLba = lba;
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
while(ent->alloc){
if(ent->type == __TYPE_FILE){
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
if(strcmp(fhdr->name,s[i]) == 0){
break;
}
}
lba = ent->nxtLba;
if(lba == 0)
break;
prevLba = ent->nxtLba;
_ata_read_master(buf,ent->nxtLba,0);
memcpy(ent,buf,sizeof(*ent));
}
if(!ent->alloc || lba == 0){
ent->nxtLba = find_free();
memcpy(buf,ent,sizeof(*ent));
_ata_write_master(buf,prevLba);
int initLba = ent->nxtLba;
free(ent);
ent = malloc(sizeof(*ent));
ent->alloc = 1;
ent->size = n;
ent->nxtLba = 0;
ent->type = __TYPE_FILE;
free(fhdr);
fhdr = malloc(sizeof(*fhdr));
fhdr->alloc = 1;
struct fd *f = getFd(fd);
memcpy(fhdr->name,f->name,strlen(f->name));
fhdr->namelen = strlen(fhdr->name);
struct tree_fexclusive *fex = malloc(sizeof(*fex));
fex->nxtFLba = 0;
free(buf);
buf = malloc(1024);
memcpy(buf,ent,sizeof(*ent));
memcpy(buf + sizeof(*ent),fhdr,sizeof(*fhdr));
memcpy(buf + sizeof(*ent) + sizeof(*fhdr),fex,sizeof(*fex));
_ata_write_master(buf,initLba);
fex->nxtFLba = find_free();
memcpy(buf + sizeof(*ent) + sizeof(*fhdr),fex,sizeof(*fex));
_ata_write_master(buf,initLba);
}
i = 0;
uint32_t offset = 0;
/*
*This loop makes it so that we start at the correct lba and offset
*by looping through until we meet or exceed the offset set by the
*file descriptor
*/
_ata_read_master(buf,prevLba,0);
struct tree_fexclusive *fex = malloc(sizeof(*fex));
memcpy(fex,buf + sizeof(*ent) + sizeof(struct tree_filehdr),sizeof(*fex));
lba = fex->nxtFLba;
i = 0;
int size = 0;
while(i < f->pos){
_ata_read_master(buf,lba,0);
struct tree_ent *tent = malloc(sizeof(*tent));
memcpy(tent,buf,sizeof(*tent));
tent->size+=n;
if(i == 0)
size = tent->size;
memcpy(fex,buf + sizeof(*tent),sizeof(*fex));
_ata_write_master(buf,lba);
if(512-sizeof(*ent)-sizeof(*fex)>(f->pos-i)){
break;
}
lba = fex->nxtFLba;
i+=512-sizeof(*ent)-sizeof(*fex);
}
int j = 0;
while(j < n){
struct tree_ent *ent = malloc(sizeof(*ent));
struct tree_fexclusive *fex = malloc(sizeof(*fex));
ent->size=size;
ent->alloc = 1;
ent->type = __TYPE_FILE;
ent->nxtLba = 0;
fex->nxtFLba = find_free();
uint8_t *buf = malloc(512);
memcpy(buf,ent,sizeof(*ent));
memcpy(buf + sizeof(*ent),fex,sizeof(*fex));
if(j + 512-sizeof(*ent)-sizeof(*fex) < n){
memcpy(buf + sizeof(*ent) + sizeof(*fex),pntr + j,512-sizeof(*ent)-sizeof(*fex));
f->pos+=512-sizeof(*ent)-sizeof(*fex);
j+=512-sizeof(*ent)-sizeof(*fex);
_ata_write_master(buf,lba);
}else{
memcpy(buf + sizeof(*ent) + sizeof(*fex),pntr + j,n%(512-sizeof(*ent)-sizeof(*fex)));
f->pos+=n%(512-sizeof(*ent)-sizeof(*fex));
j+=n%(512-sizeof(*ent)-sizeof(*fex));
_ata_write_master(buf,lba);
return j;
}
}
return j;
}
}
int close(int fd){
struct fd *f = getFd(fd);
f->alloc = 0;
bzero(f,sizeof(*f));
return 1;
}
int __exec(const char *path){
uint8_t *buf = malloc(fsize(path));
bzero(buf,fsize(path));
int fd = open(path,O_RDONLY);
if(fd < 0){
kprintf("Error opening\n");
return -1;
}
int r = read(fd,buf,fsize(path));
int (*main)() = exec_elf(0,buf);
t_writevals();
main();
}
int exec(const char *path,const char **argv){
uint8_t *buf = malloc(fsize(path));
int fd = open(path,O_RDONLY);
if(fd < 0)
return -1;
read(fd,buf,fsize(path));
int argc = 0;
while(argv[argc] != 0)
argc++;
int (*main)(int argc,char **argv) = exec_elf(0,buf);
t_writevals();
main(argc,argv);
t_readvals();
}
void list(const char *path){
kprintf("LS %s:\n",path);
struct __DIR *d = opendir(path);
if(!d){
kprintf("I/O Error\n");
}
uint8_t *buf = malloc(512);
_ata_read_master(buf,d->dhdr->nxtTreeLba,0);
struct tree_ent *ent = malloc(sizeof(*ent));
struct tree_filehdr *fhdr = malloc(sizeof(*fhdr));
struct tree_dirhdr *dhdr = malloc(sizeof(*dhdr));
memcpy(ent,buf,sizeof(*ent));
while(ent->alloc){
memcpy(fhdr,buf + sizeof(*ent),sizeof(*fhdr));
kprintf("%s\n",fhdr->name);
_ata_read_master(buf,ent->nxtLba,0);
if(ent->nxtLba == 0)
break;
memcpy(ent,buf,sizeof(*ent));
}
}
|
C
|
#ifndef __VFS_H_
#define __VFS_H_
#include <stdint.h>
#include <stdbool.h>
#include "list.h"
#include "spinlock.h"
#define VNODE_UNDEF 0
// oridinary file
#define VNODE_FILE 1
// a directory
#define VNODE_DIR 2
// mount point, a mount point must be a directory
#define VNODE_MP 3
// device file
#define VNODE_DEV 4
struct vfs_backend {
//
// all the functions below return int as error code
// 0 for success, other for failed
//
struct list_head list;
void *lfs;
uint64_t lfs_obj_size;
// get root object
int (*root)(void *lfs, void *lobj);
// create a file, return error code
int (*create)(void *lfs, void *p_lobj, char *name);
// delete the file
int (*unlink)(void *lfs, void *lobj);
// flush the whole fs
int (*flush)(void *lfs);
// make a dir
int (*mkdir)(void *lfs, void *p_lobj, char *name);
// remove a dir
int (*rmdir)(void *lfs, void *p_lobj, void *lobj);
// read from file
uint64_t (*read)(void *lfs, void *lobj, uint64_t offset, void *buf, uint64_t buf_len);
// write to file
uint64_t (*write)(void *lfs, void *lobj, uint64_t offset, void *buf, uint64_t buf_len);
int (*trunate)(void *lfs, void *lobj, uint64_t new_sz);
int (*enlarge)(void *lfs, void *lobj, uint64_t new_sz);
// get file size
uint64_t (*size)(void *lfs, void *lobj);
// get file name
char *(*name)(void *lfs, void *lobj);
// get file type
uint32_t (*type)(void *fs, void *lobj);
// iterate through directory
// while the iterate , this function will fill the memory to which the obj points
void *(*iterate)(void *lfs, void *dir_obj, void *iter_obj, void *lobj);
// end the iterate, release the resources
void (*end_iterate)(void *lfs, void *iter_obj);
void (*lock)(void *lfs);
void (*unlock)(void *lfs);
};
struct vnode {
struct list_head list;
uint64_t ref_cnt;
// block buffer
struct list_head bbf;
// parent vnode
// if parent is NULL, it is a root node
// root node has no name, no size, no name_len and
// must be a mount point type
struct vnode *parent;
// children vnode
struct list_head children;
int64_t child_cnt;
// max size is 4GiB
uint32_t size;
uint32_t type;
// vnode name
char *name;
// THE FOLLOWING IS FOR backend
// lower fs
void *lfs_obj;
struct vfs_backend *bkd;
};
#define VFS_BLOCK_SIZE (PAGE_SIZE)
struct vfs_block {
// used by vfs
struct list_head list_vfs;
// used by vnode
struct list_head list_vnode;
void *buf;
struct vnode *node;
// number in block
uint32_t blkoff;
// 0 is clean, 1 is dirty
uint32_t dirty;
};
struct vfs_t {
struct vnode root;
struct list_head bkd;
// in vfs, one buffer is 4KiB
struct list_head bbf_used;
struct list_head bbf_free;
uint32_t bbf_used_cnt;
uint32_t bbf_free_cnt;
uint32_t bbf_total_max;
struct spinlock lock;
};
extern struct vfs_t *global_vfs;
// only alloc the memory, other things are not touched, only called by vbf_* series functions
struct vfs_block *vblk_alloc();
// only free the memory, other things are not touched, only called by vbf_* series functions
void vblk_free(struct vfs_block *blk);
// this function is called after vbf_borrow
void vbf_bind(struct vfs_block *blk, struct vnode *node, uint32_t blkoff);
struct vfs_block *vbf_chkbufed(struct vfs_t *vfs, struct vnode *node, uint32_t blkoff);
// this function is called before vbf_return
void vbf_unbind(struct vfs_block *blk);
// flush the block into backend
void vbf_flush(struct vfs_block *blk);
void vbf_activate(struct vfs_t *vfs, struct vfs_block *blk);
// bind must be called after this function call
// use this function to get a unbind vfs_block
struct vfs_block *vbf_borrow(struct vfs_t *vfs);
// unbind must be called before this function call
// use this function to return a unbind vfs_block
void vbf_return(struct vfs_t *vfs, struct vfs_block *blk);
// free all free block
void vbf_shrink(struct vfs_t *vfs);
void vnode_add(struct vnode* node, struct vnode *parent, void *lfs_obj);
void vfs_buffer(struct vfs_t *vfs, struct vnode *node, uint32_t blkoff);
void vfs_unbuffer(struct vfs_t *vfs, struct vfs_block *blk);
void vfs_unbuffer_all(struct vfs_t *vfs, struct vnode *node);
struct vfs_t *vfs_init(uint32_t buffer_max);
struct vnode *vfs_root(struct vfs_t *vfs);
// the node must be empty
int64_t vfs_mount(struct vfs_t *vfs, struct vnode *node, struct vfs_backend bkd);
int64_t vfs_umount(struct vfs_t *vfs, struct vnode *node);
void vfs_create(struct vfs_t *vfs, struct vnode *parent, char *name);
struct vnode *vfs_get(struct vfs_t *vfs, struct vnode *parent, const char *name);
struct vnode *vfs_get_recursive(struct vfs_t *vfs, struct vnode *parent, const char *path);
struct vnode *vfs_open(struct vfs_t *vfs, struct vnode *parent, const char *path);
struct vnode *vfs_reopen(struct vfs_t *vfs, struct vnode *node);
void vfs_close(struct vfs_t *vfs, struct vnode *node);
void vfs_unlink(struct vfs_t *vfs, struct vnode *node);
void *vfs_access(struct vfs_t *vfs, struct vnode *node, uint64_t offset);
uint64_t vfs_read(struct vfs_t *vfs, struct vnode *node, uint64_t offset, void *buf, uint64_t buf_len);
uint64_t vfs_write(struct vfs_t *vfs, struct vnode *node, uint64_t offset, void *buf, uint64_t buf_len);
// if last == NULL, it indicates a iteration start
// if last != NULL, it indicates a iteration next
// if it returns NULL, the iteration is done
struct vnode* vfs_iterate(struct vfs_t *vfs, struct vnode *parent, struct vnode *last);
void vfs_mkdir(struct vfs_t *vfs, struct vnode *node, char *name);
void vfs_rmdir(struct vfs_t *vfs, struct vnode *node);
// if node == NULL, flush all vfs
// do writeback on specifed node
void vfs_flush(struct vfs_t *vfs, struct vnode *node);
// release some of the buffer
void vfs_shrink(struct vfs_t *vfs);
#endif // __VFS_H_
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
typedef scalar_t__ bfd_vma ;
typedef int /*<<< orphan*/ bfd_boolean ;
struct TYPE_3__ {char const* name; scalar_t__ size; scalar_t__ vma; struct TYPE_3__* next; } ;
typedef TYPE_1__ asection ;
/* Variables and functions */
int /*<<< orphan*/ FALSE ;
int /*<<< orphan*/ TRUE ;
scalar_t__ strcmp (char const*,char const*) ;
unsigned int strlen (char const*) ;
scalar_t__ strncmp (char*,char const*,int) ;
__attribute__((used)) static bfd_boolean
resolve_section (const char * name,
asection * sections,
bfd_vma * result)
{
asection * curr;
unsigned int len;
for (curr = sections; curr; curr = curr->next)
if (strcmp (curr->name, name) == 0)
{
*result = curr->vma;
return TRUE;
}
/* Hmm. still haven't found it. try pseudo-section names. */
for (curr = sections; curr; curr = curr->next)
{
len = strlen (curr->name);
if (len > strlen (name))
continue;
if (strncmp (curr->name, name, len) == 0)
{
if (strncmp (".end", name + len, 4) == 0)
{
*result = curr->vma + curr->size;
return TRUE;
}
/* Insert more pseudo-section names here, if you like. */
}
}
return FALSE;
}
|
C
|
#include "../../NABinaryData.h"
#include "../../NAMemory.h"
// ////////////////////////////
// PNG CRC implementation
//
// Based on the polynom sum x^[32 26 23 22 16 12 11 10 8 7 5 4 2 1 0]
//
// Code stolen and adapted from the PNG reference:
// http://www.w3.org/TR/PNG/#D-CRCAppendix
typedef struct NAChecksumCRC NAChecksumCRC;
struct NAChecksumCRC{
uint32 value;
uint32 table[256];
};
NA_HIDEF void na_PrepareCRCPNG(NAChecksumCRC* checksumcrc){
int n, k;
for (n = 0; n < 256; n++) {
uint32 c = (uint32) n;
for (k = 0; k < 8; k++) {
if (c & 1)
c = 0xedb88320 ^ (c >> 1);
else
c = c >> 1;
}
checksumcrc->table[n] = c;
}
}
NA_HIDEF void na_AccumulateCRCPNG(NAChecksumCRC* checksumcrc, const NAByte* buf, size_t byteSize){
uint32 c = checksumcrc->value;
for(size_t n = 0; n < byteSize; n++){
c = checksumcrc->table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
}
checksumcrc->value = c;
}
// ////////////////////////////
// Adler 32 Checksum implementation
//
// Code stolen and adapted from the RFC 1950:
// http://www.ietf.org/rfc/rfc1950.txt
#include "../../../NAMath/NAMathConstants.h"
#define NA_CHECKSUM_ADLER_BASE NA_PRIME_BEFORE_2_16;
typedef struct NAChecksumAdler NAChecksumAdler;
struct NAChecksumAdler{
uint32 s1;
uint32 s2;
};
NA_HIDEF void na_AccumulateAdler(NAChecksumAdler* checksumadler, const NAByte* buf, size_t byteSize){
for(size_t n = 0; n < byteSize; n++){
checksumadler->s1 = (checksumadler->s1 + buf[n]) % NA_CHECKSUM_ADLER_BASE;
checksumadler->s2 = (checksumadler->s2 + checksumadler->s1) % NA_CHECKSUM_ADLER_BASE;
}
}
// /////////////////////////////
// General NAChecksum implementation
NA_DEF NAChecksum* naInitChecksum(NAChecksum* checksum, NAChecksumType type){
checksum->type = type;
switch(type){
case NA_CHECKSUM_TYPE_CRC_PNG:
checksum->data = naAlloc(NAChecksumCRC);
na_PrepareCRCPNG((NAChecksumCRC*)(checksum->data));
break;
case NA_CHECKSUM_TYPE_ADLER_32:
checksum->data = naAlloc(NAChecksumAdler);
//naPrepareAdler((NAChecksumAdler*)(checksum->data)); // nothing to be prepared
break;
default:
#if NA_DEBUG
naError("Checksum type invalid");
#endif
break;
}
naResetChecksum(checksum);
return checksum;
}
NA_DEF void naClearChecksum(NAChecksum* checksum){
naFree(checksum->data);
}
NA_DEF void naResetChecksum(NAChecksum* checksum){
switch(checksum->type){
case NA_CHECKSUM_TYPE_CRC_PNG:
((NAChecksumCRC*)(checksum->data))->value = 0xffffffff;
break;
case NA_CHECKSUM_TYPE_ADLER_32:
((NAChecksumAdler*)(checksum->data))->s1 = 1 & 0xffff;
((NAChecksumAdler*)(checksum->data))->s2 = (1 >> 16) & 0xffff;
break;
default:
#if NA_DEBUG
naError("Checksum type invalid");
#endif
break;
}
}
NA_DEF void naAccumulateChecksum(NAChecksum* checksum, const NAByte* buf, size_t byteSize){
switch(checksum->type){
case NA_CHECKSUM_TYPE_CRC_PNG:
na_AccumulateCRCPNG(((NAChecksumCRC*)(checksum->data)), buf, byteSize);
break;
case NA_CHECKSUM_TYPE_ADLER_32:
na_AccumulateAdler(((NAChecksumAdler*)(checksum->data)), buf, byteSize);
break;
default:
#if NA_DEBUG
naError("Checksum type invalid");
#endif
break;
}
}
NA_DEF uint32 naGetChecksumResult(NAChecksum* checksum){
uint32 retValue;
switch(checksum->type){
case NA_CHECKSUM_TYPE_CRC_PNG:
retValue = ((NAChecksumCRC*)(checksum->data))->value ^ 0xffffffff;
break;
case NA_CHECKSUM_TYPE_ADLER_32:
retValue = (((NAChecksumAdler*)(checksum->data))->s2 << 16) + ((NAChecksumAdler*)(checksum->data))->s1;
break;
default:
#if NA_DEBUG
naError("Checksum type invalid");
#endif
retValue = 0;
break;
}
return retValue;
}
// This is free and unencumbered software released into the public domain.
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// For more information, please refer to <http://unlicense.org/>
|
C
|
//
// leaf_path_weight.c
// BST_Revision
//
// Created by Surya Sahukar on 8/2/16.
// Copyright © 2016 Surya Sahukar. All rights reserved.
//
#include "leaf_path_weight.h"
int path_weight = 0;
int leaf_array[10];
int idx = 0;
int leaf_path_weight(struct node *root, int leaf_value)
{
path_weight = 0;
if (!root)
return 0;
if ( (root -> left || root -> right) && (root -> data == leaf_value) )
{
path_weight = 0;
return 0;
}
if (!(root ->left) && !(root -> right))
return ( path_weight + root -> data);
if (root -> data > leaf_value)
path_weight = path_weight + root -> data + leaf_path_weight(root -> left, leaf_value);
else
path_weight = path_weight + root -> data + leaf_path_weight(root -> right, leaf_value);
return path_weight;
}
int find_all_leaves (struct node *root)
{
if (!root)
return 0;
if (!root -> left && !root -> right)
{
leaf_array[idx] = root -> data;
idx++;
return idx;
}
if (root -> left)
{
find_all_leaves(root -> left);
}
if (root -> right)
{
find_all_leaves(root -> right);
}
return idx;
}
struct node *find_leaf_of_given_path_weight (struct node *root, int given_path_weight)
{
int leaf_array_size;
struct node *found_leaf_node;
found_leaf_node = (struct node *) malloc(sizeof(struct node));
leaf_array_size = 0;
leaf_array_size = find_all_leaves(root);
for (int j = 0; j < leaf_array_size; j++)
{
if ( leaf_path_weight(root, leaf_array[j]) == given_path_weight )
{
found_leaf_node = search_bst(root, leaf_array[j]);
break;
}
}
return found_leaf_node;
}
|
C
|
//
// main.c
// algonrithm_2
//
// Created by sdx on 2018/5/11.
// Copyright © 2018年 sdx. All rights reserved.
// 栈,队列,链表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 队列结构体
struct queue {
int data[1000]; // 队列主体,用于存储数据
int head; // 队列头
int tail; // 队列尾
};
/**
其中 top 用来存储栈顶,数组 data 用来存储栈中的元素,大小设置为 10。因为只有 9 种不同的牌面,所以桌上最多可能有 9 张牌,因此数组大小设置为 10 就够了。
*/
struct stack {
int data[10];
int top;
};
/***
每一个结点都由两个部分组成。左边的部分用来存放具体的数值,那么用一个整型变量 就可以;右边的部分需要存储下一个结点的地址,可以用指针来实现(也称为后继指针)。 这里我们定义一个结构体类型来存储这个结点,如下。
***/
struct node {
int data;
struct node *next;
};
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
#pragma mark --- 队列的使用 先进先出 FIFO (first in first out)
/**
新学期开始了,小哈是小哼的新同桌(小哈是个小美女哦~),小哼向小哈询问 QQ 号, 小哈当然不会直接告诉小哼啦,原因嘛你懂的。所以小哈给了小哼一串加密过的数字,同时 小哈也告诉了小哼解密规则。规则是这样的:首先将第 1 个数删除,紧接着将第 2 个数放到 这串数的末尾,再将第 3 个数删除并将第 4 个数放到这串数的末尾,再将第 5 个数删除...... 直到剩下最后一个数,将最后一个数也删除。按照刚才删除的顺序,把这些删除的数连在一 起就是小哈的 QQ 啦。现在你来帮帮小哼吧。小哈给小哼加密过的一串数是“6 3 1 7 5 8 9 2 4”。
解释: 正确qq号 : 615947283
现在有 9 个数,9 个数全部放入队列之后 head=1;tail=10;此时 head 和 tail 之间的数就是
目前队列中“有效”的数。如果要删除一个数的话,就将 head++就 OK 了,这样仍然可以保 持 head 和 tail 之间的数为目前队列中“有效”的数。这样做虽然浪费了一个空间,却节省了 大量的时间,这是非常划算的。新增加一个数也很简单,把需要增加的数放到队尾即 q[tail] 之后再 tail++就 OK 啦。
**/
/*
int q[102] = {6,3,1,7,5,8,9,2,4} ,head,tail; // 头下标,尾下
head = 0; // head指向第一个元素
tail = 9; // 队列里面有九个元素,tail 指向最后一个
while (head < tail) { // 当队列不为空的时候执行该方法
// 打印队首,并将队首移除队列
printf("%d",q[head]);
head ++;
// 将新的队首移动到队列末尾
q[tail] = q[head];
tail ++;
// 再将队首移除队列
head ++;
}
getchar();
*/
// 结构体的队列操作
/**
struct queue q;
int i;
// 初始化队列
q.head = 1;
q.tail = 1;
for (i = 0; i < 9;i++) {
printf("输入一个数:"); // 分别输入 6,3,1,7,5,8,9,2,4
scanf("%d",&q.data[q.tail]);
q.tail++;
}
while (q.head < q.tail) {
printf("%d",q.data[q.head]);
q.head ++;
q.data[q.tail] = q.data[q.head]; // 新队首 移动到队尾
q.tail ++;
q.head ++ ;
}
// 打印得到的值是 615947283
getchar();
**/
#pragma mark -- 解密回文-- 栈 后进先出 LIFO (last in first out)
/**
栈究竟有哪些作用呢?我们来看一个例子。“xyzyx”是一个回文字符串,所谓回文字符 串就是指正读反读均相同的字符序列,如“席主席”、“记书记”、“aha”和“ahaha”均是回 文,但“ahah”不是回文。通过栈这个数据结构我们将很容易判断一个字符串是否为回文。
首先我们需要读取这行字符串,并求出这个字符串的长度。
需要导入下列库
#include <string.h>
**/
/***
char a[101], s[101];
int i ,len ,mid,next,top;
printf("请输入一行字符串:");
gets(a); // 读入一行的字符串
len = (int)strlen(a); // 求字符串的长度
printf("len ===%d a == %s\n",len,a);
mid = len/2 - 1; // 求字符串的中点
printf("mid ===%d \n",mid);
top = 0 ; // 初始化栈
// 将mid前的字符串依次入栈
for (i = 0; i <= mid; i++) {
top ++;
s[top] = a[i];
// s[++top] = a[i]; // 这个是上面的简写
}
// 判断是奇数还是偶数
if (len%2 == 0) {
// 偶数
next = mid + 1; // next mid右边的数的下标 abccba (mid = 6/2 - 1 = 2) (next = 2 + 1 = 3) ,下标为3就是第二个c
}else{
// 奇数
next = mid + 2; // next mid右边的数的下标 abcba (mid = 5/2 - 1 = 1) (next = 1 + 1 = 2) ,下标为2就是c
}
// 开始匹配
for (i = next; i <= len-1; i ++) {
if (a[i] != s[top]) {
break;
}
top--;
}
// 如果top值 等于 0 ,说明所有字符都被一一匹配了
if (top == 0) printf("YES");
else printf("NO");
getchar();
***/
#pragma mark -- 纸牌游戏 小猫钓鱼
/***
星期天小哼和小哈约在一起玩桌游,他们正在玩一个非常古怪的扑克游戏——“小猫钓 鱼”。游戏的规则是这样的:将一副扑克牌平均分成两份,每人拿一份。小哼先拿出手中的 第一张扑克牌放在桌上,然后小哈也拿出手中的第一张扑克牌,并放在小哼刚打出的扑克牌 的上面,就像这样两人交替出牌。出牌时,如果某人打出的牌与桌上某张牌的牌面相同,即
啊哈!算法
可将两张相同的牌及其中间所夹的牌全部取走,并依次放到自己手中牌的末尾。当任意一人 手中的牌全部出完时,游戏结束,对手获胜。
假如游戏开始时,小哼手中有 6 张牌,顺序为 2 4 1 2 5 6,小哈手中也有 6 张牌,顺序 为 3 1 3 5 6 4,最终谁会获胜呢?现在你可以拿出纸牌来试一试。接下来请你写一个程序来 自动判断谁将获胜。这里我们做一个约定,小哼和小哈手中牌的牌面只有 1~9。
分析:
小哼有两种操作,分别是出牌和赢牌。这恰 好对应队列的两个操作,出牌就是出队,赢牌就是入队。小哈的操作和小哼是一样的。而桌 子就是一个栈,每打出一张牌放到桌上就相当于入栈。当有人赢牌的时候,依次将牌从桌上 拿走,这就相当于出栈。
所以,两个人对应两个队列,桌面上的牌对应一个栈
**/
/****
struct queue q1, q2;
struct stack s;
int i, t;
int book[10];
// 初始化 队列 为空 ,两个人手中都没有牌
q1.head = 0; q1.tail = 0;
q2.head = 0; q2.tail = 0;
// 初始化栈为空,桌面上也没有牌
s.top = 0;
//初始化用来标记的数组,用来标记那些牌已经在桌子上
for (i = 0;i < 9 ; i ++) {
book[i] = 0;
}
// 分别读入 两个人初始化的牌,每个人6张
// 小恒的六张牌
for (i = 0; i < 6; i++) {
printf("小恒请输入一张牌,0-10:");
scanf("%d",&q1.data[q1.tail]);
q1.tail ++;
}
printf("\n\n");
// 小哈的六张牌
for (i = 0; i < 6; i ++) {
printf("小哈请输入一张牌,0-10:");
scanf("%d",&q2.data[q2.tail]);
q2.tail ++;
}
while (q1.head < q1.tail && q2.head < q2.tail) // 当队列不为空的时候执行循环
{
t = q1.data[q1.head]; // 小恒出一张牌
printf("\n小恒出一张牌:%d ",t);
// 判断小恒是否赢牌
if (book[t] == 0) { // 有桶(桌面)里面是否有为t的牌
// 小恒此轮没有赢牌
q1.head ++ ; // 小恒打出一张牌, 说以这张牌要出队列
s.top ++;
s.data[s.top] = t; // 刚刚打出的牌入栈
//book[t] ++; // 两个方法的意义一样,因为游戏规则,桌子只可能有一张一样的牌,所以使用等于1
book[t] = 1; //标记桌面上有的牌
}
else
{
printf("小恒夹到了牌 \n");
// 小恒此轮可以赢牌
q1.head ++ ; // 小恒打出一张牌, 说以这张牌要出队列
q1.data[q1.tail] = t; // 吧打出的牌放在末尾
q1.tail ++;
while (s.data[s.top] != t) {
book[s.data[s.top]] = 0; // 取消标记
q1.data[q1.tail] = s.data[s.top]; //依次放入队尾
printf("%d ",s.data[s.top]);
q1.tail ++;
s.top --; // 栈中少了牌,所以要减一
}
// 作者源代码有问题 需要加入下列demo
book[s.data[s.top]] = 0; // 取消标记
q1.data[q1.tail] = s.data[s.top]; //依次放入队尾
printf("%d ",s.data[s.top]);
q1.tail ++;
s.top --; // 栈中少了牌,所以要减一
}
t = q2.data[q2.head]; // 小哈出一张牌
printf("\n小哈出一张牌:%d ",t);
// 判断小哈是否赢牌
if (book[t] == 0) {
// 小哈此轮没有赢牌
q2.head ++;
s.top ++;
s.data[s.top] = t;
book[t] = 1;
}
else
{
printf("小哈夹到了牌 \n");
// 小哈此轮可以赢牌
q2.head ++;
q2.data[q2.tail] = t;
q2.tail ++;
while (s.data[s.top] != t) {
book[s.data[s.top]] = 0;
q2.data[q2.tail] = s.data[s.top];
printf("%d ",s.data[s.top]);
q2.tail ++;
s.top --;
}
// 作者源代码有问题 需要加入下列demo
book[s.data[s.top]] = 0;
q2.data[q2.tail] = s.data[s.top];
printf("%d ",s.data[s.top]);
q2.tail ++;
s.top --;
}
}
if (q2.head == q2.tail) {
printf("小恒 win \n");
printf("小恒手上的牌是:");
for (i = q1.head; i < q1.tail; i ++) {
printf("%d ",q1.data[i]);
}
if (s.top > 0) { // 如果桌上有牌,依次输出桌上的牌
printf("\n桌上的牌是:");
for (i = 1; i < s.top + 1 ; i ++) {
printf("%d ",s.data[i]);
}
}
else
{
printf("\n桌面上没有牌");
}
}
else
{
printf("小哈 win \n");
printf("小哈手上的牌是:");
for (i = q2.head; i < q2.tail; i ++) {
printf("%d ",q2.data[i]);
}
if (s.top > 0) { // 如果桌上有牌,依次输出桌上的牌
printf("\n桌上的牌是:");
for (i = 1; i < s.top + 1; i ++) {
printf("%d ",s.data[i]);
}
}
else
{
printf("\n桌面上没有牌");
} //365432 145322 小恒win 4 3 桌面 3
}
getchar();
***/
#pragma -- mark 指针 链表
// 使用 malloc方法需要导入 #include <stdlib.h>
/**
int * p; // 定义一个指针p
p = (int *)malloc(sizeof(int)); // 指针p动态获取分配内存地址(动态申请空间)
*p = 10; // 向指针p指向的内存空间 输入10
printf("%d",*p); // 打印指针指向内存的值
getchar();
**/
/***
每一个结点都由两个部分组成。左边的部分用来存放具体的数值,那么用一个整型变量 就可以;右边的部分需要存储下一个结点的地址,可以用指针来实现(也称为后继指针)。 这里我们定义一个结构体类型来存储这个结点,如下。
如何建立链表呢?首先我们需要一个头指针 head 指向链表的最开始。当链表还没有建 立的时候头指针 head 为空(也可以理解为指向空结点)。
***/
/***
int a,i,n;
struct node *head,*p = NULL,*q = NULL,*t = NULL;
head = NULL; // 头指针初始为空
printf("输入数字n,代表之后需要输入n个数:");
scanf("%d",&n);
for (i = 0; i < n; i ++) { // 循环读入n个数
printf("输入一个链表节点数据:");
scanf("%d",&a);
// 动态申请空间,用来存放一个节点,并用临时指针p指向这个节点
p = (struct node*)malloc(sizeof(struct node));
p->data = a; // 将数据存储到当前的·data域里面
p->next = NULL; // 设置当前的后继指针指向空,也就是当前节点的下一个节点为空
if (head == NULL) {
head = p; // 如果是第一个节点,将头指针指向这个节点
}
else
{
q->next = p; // 如果不是第一次创建的节点,则将上一个的后继指针指向当前节点
}
q = p; // 指针q也指向当前节点
}
t = head;
printf("插入一个数:");
scanf("%d",&a);
while (t != NULL) { // 当没有达到链表尾部得时候循环
if (t->next->data > a) { // 如果当前节点的下一个节点值大于待插入得数,将插入到中间存放新增节点
p = (struct node *)malloc(sizeof(struct node));
p->data = a;
p->next = t->next; // 新增节点的后继指针指向当前节点的后继指针指向的节点
t->next = p; // 当前节点的后继指针指向新增节点
break; // 插入完毕,退出循环
}
t = t->next; // 继续下一个节点
}
// 输出链表里面的所有数
t = head;
while (t != NULL) {
printf("%d ",t->data);
t = t->next; // 继续下一个节点
}
free(p);
// 初始9个数 1 4 6 7 8 9 12 33 45 ,插入 11 得到 1 4 6 7 8 9 11 12 33 45
getchar();
***/
#pragma mark --- 模拟链表
/*
第一个整型数组 data 是用来存放序列中具体数字的,另外一个整型 数组 right 是用来存放当前序列中每一个元素右边的元素在数组 data 中位置的
**/
int data [101], right[101];
int i,n,t,len; // t 为下一个节点 len 为长度
// 读入已有得数
printf("输入要读的个数:");
scanf("%d",&n);
for (i = 1; i < n+1; i++) {
printf("输入一个链表节点数据:");
scanf("%d",&data[i]);
}
len = n;
// 初始化数组right
for (i = 1; i < n+1; i ++) {
if (i != n) {
right[i] = i +1;
}
else
{
right[i] = 0;
}
}
/// 直接在数组末尾添加一个数
len ++; // 长度加一
printf("插入一个数:");
scanf("%d",&data[len]);
// 重链表头部开始便利
t = 1;
while (t != 0) {
if (data[right[t]] > data[len]) { //如果当前节点的下一个节点值大于待插入得数,将插入到中间存放新增节点
right[len] = right[t]; // 新插入的下一个节点 等于 当前节点的下一个节点编号
right[t] = len; // 当前节点的下一个编号,就是新插入的编号
break;
}
t = right[t];
}
// 输出链表所有得数
t = 1;
while (t != 0) {
printf("%d ",data[t]);
t=right[t];
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "error.h"
#include "gen_ninja.h"
#include "list.h"
#include "strset.h"
void emit_ninja_list(FILE *m, struct List *l) {
struct ListNode *node = list_first(l);
while (node != NULL) {
fprintf(m, " %s", node->value);
node = list_next(node);
}
}
void emit_ninja_rule_name(FILE *m, const char *rule) {
size_t len = strlen(rule);
char buf[len + 1];
for (size_t i = 0; i < len; i++) {
if ((rule[i] >= 'A' && rule[i] <= 'Z') ||
(rule[i] >= 'a' && rule[i] <= 'z') ||
(rule[i] >= '0' && rule[i] <= '9')) {
buf[i] = rule[i];
} else {
buf[i] = '_';
}
}
buf[len] = '\0';
fprintf(m, "r__%s", buf);
}
void emit_ninja_rule(FILE *m, const char *name, struct List *commands) {
fprintf(m, "rule ");
emit_ninja_rule_name(m, name);
fprintf(m, "\n command =");
struct ListNode *cmd = list_first(commands);
while (cmd != NULL) {
if (cmd != list_first(commands)) {
fprintf(m, " &&");
}
fprintf(m, " %s", cmd->value);
cmd = list_next(cmd);
}
fprintf(m, "\n");
}
void ninja_generate(struct BuildGraph *graph, struct NinjaOpts *opts, struct Error **err) {
FILE *m = fopen(opts->ninja_file, "w");
if (m == NULL) {
return error_fmt(err, "Unable to open %s", opts->ninja_file);
}
struct StringSet defaults;
sset_init(&defaults);
struct StringSet phonys;
sset_init(&phonys);
struct StringSet dirs;
sset_init(&dirs);
struct List empty;
list_init(&empty);
// First: collect phonys, dirs, and default targets
struct TargetList *tlist = graph->list;
while (tlist != NULL) {
const char *name = tlist->target->name;
// Make a note of the target if it's maked as default
if (tlist->target->primary) {
sset_insert(&defaults, name);
}
// Create a phony target if it is listed as phony, of if the target name
// is not already an output in the project
if (tlist->target->phony ||
(graph_dep_search(graph, name) == NULL && tlist->target->alias)) {
sset_insert(&phonys, name);
}
// Keep track of all the dirs we will ever need
struct ListNode *dir = list_first(&tlist->target->rule->dirs);
while (dir != NULL) {
sset_insert(&dirs, dir->value);
dir = list_next(dir);
}
tlist = tlist->next;
}
// Second: Check phonys for collisions with dirs and outputs
struct ListNode *phony = list_first(phonys.values);
while (phony != NULL) {
const char *name = phony->value;
if (sset_has(&dirs, name)) {
return error_fmt(err, "Directory '%s' collides with phony target '%s'",
name, name);
}
struct Target *tcoll = graph_dep_search(graph, name);
if (tcoll != NULL) {
return error_fmt(err, "Target '%s' output collides with phony target '%s'",
tcoll->name, name);
}
phony = list_next(phony);
}
// Third: Check dirs for collisions against outputs
struct ListNode *dir = list_first(dirs.values);
while (dir != NULL) {
const char *name = dir->value;
struct Target *tcoll = graph_dep_search(graph, name);
if (tcoll != NULL) {
return error_fmt(err, "Target '%s' output collides with directory '%s'",
tcoll->name, name);
}
dir = list_next(dir);
}
// Fourth: Emit the normal targets
tlist = graph->list;
while (tlist != NULL) {
const char *name = tlist->target->name;
struct List* tins = &tlist->target->rule->inputs;
struct List* touts = &tlist->target->rule->outputs;
struct List* tcmds = &tlist->target->rule->commands;
if (tlist->target->phony && !list_empty(tcmds)) {
// If the true phony has commands, it needs a rule
emit_ninja_rule(m, name, tcmds);
fprintf(m, "\n");
fprintf(m, "build %s: ", name);
emit_ninja_rule_name(m, name);
emit_ninja_list(m, tins);
fprintf(m, "\n\n");
} else if (tlist->target->phony) {
// If it's a true phony with no commands,
// we skip the rule part and use the ninja phony rule
fprintf(m, "build %s: phony", name);
emit_ninja_list(m, tins);
fprintf(m, "\n\n");
} else if (sset_has(&phonys, name)) {
// If it's a virtual phony then we use the ninja phony rule
fprintf(m, "build %s: phony", name);
emit_ninja_list(m, touts);
fprintf(m, "\n\n");
}
if (!tlist->target->phony) {
emit_ninja_rule(m, name, tcmds);
fprintf(m, "\n");
fprintf(m, "build");
emit_ninja_list(m, touts);
fprintf(m, ": ");
emit_ninja_rule_name(m, name);
emit_ninja_list(m, tins);
fprintf(m, "\n\n");
}
tlist = tlist->next;
}
fprintf(m, "\n\n");
// Sixth: Emit the default target if needed
if (!list_empty(defaults.values)) {
struct ListNode *def = list_first(defaults.values);
while (def != NULL) {
fprintf(m, "default %s\n", def->value);
def = list_next(def);
}
fprintf(m, "\n");
}
sset_free(&defaults);
sset_free(&phonys);
sset_free(&dirs);
list_free(&empty);
}
|
C
|
#include <stdio.h>
int main(){
int sexo = 0;
int idade = 0;
int estado_civil = 0;
int quantidade_total_mulheres = 0, quantidade_total_homens = 0;
double percentual_mulheres_solteiras, percentual_homens_solteiros;
int quantidade_mulheres_divorciadas = 0;
int quantidade_homens = 0 , quantidade_mulheres = 0;
int soma_idade_mulheres = 0, soma_idade_homens = 0;
int quantidade_homens_solteiros = 0, quantidade_mulheres_solteiras = 0 ;
// media idade mulheres = (total_idades) / quantidade_total_mulheres ;
// media idade homens = (total_idades) / quantidade_total_homens ;
// percentual homens solteiros = ((quantidade_homens_solteiros) / quantidade_total_homens) * 100 ;
// percentual mulheres solteiros = ((quantidade_mulheres_solteiras) / quantidade_total_mulheres) * 100 ;
for (int i = 1; i <= 3; i++){
printf("Digite o sexo (1=Masculino, 2=Feminino): ");
scanf("%d",&sexo);
printf("Digite a idade: ");
scanf("%d",&idade);
printf("Digite o estado civil (1=Casado, 2=Solteiro, 3=Divorciado, 4=Viuvo): ");
scanf("%d",&estado_civil);
printf("\n");
if (sexo == 2){
quantidade_total_mulheres++;
if (estado_civil == 2){ // se for solteira
quantidade_mulheres_solteiras++;
}
if (estado_civil == 3 && idade > 30){ // se for divorciada
quantidade_mulheres_divorciadas++;
}
soma_idade_mulheres += idade;
}else if(sexo == 1){
quantidade_total_homens++;
if (estado_civil == 2){ // se for solteiro
quantidade_homens_solteiros++;
}
soma_idade_homens += idade;
}
//percentual_mulheres_solteiras = (percentual_mulheres_solteiras / 100) * 100;
}
printf("%d\n",quantidade_mulheres_solteiras);
printf("%d\n",quantidade_total_mulheres);
//printf("%d\n",quantidade_total_homens);
printf("\n");
//printf("%d\n",quantidade_total_homens);
double media_idade_mulheres = ( quantidade_total_mulheres != 0 ? soma_idade_mulheres / quantidade_total_mulheres : 0 );
double media_idade_homens = ( quantidade_total_homens != 0 ? soma_idade_homens / quantidade_total_homens : 0 );
percentual_homens_solteiros = (quantidade_total_homens !=0 ? ((double) quantidade_homens_solteiros / quantidade_total_homens) * 100 : 0);
percentual_mulheres_solteiras = (quantidade_total_mulheres !=0 ? ((double) quantidade_mulheres_solteiras / quantidade_total_mulheres) * 100 : 0);
printf("A media da idade dos homens eh: %2.f\n",media_idade_homens);
printf("A media da idade das mulheres eh: %2.f\n",media_idade_mulheres);
printf("O percentual de homens solteiros eh: %2.f\n",percentual_homens_solteiros);
printf("O percentual de mulheres solteiras eh: %2.f\n",percentual_mulheres_solteiras);
printf("A quantidade de mulheres divorciadas eh: %d",quantidade_mulheres_divorciadas);
return 0;
}
|
C
|
#include "sort.h"
/**
* sort_deck - sorts an array of integers with shell sorting
*
* @deck: linked list with decks
* Return: Void
*/
void sort_deck(deck_node_t **deck)
{
if (deck == NULL || *deck == NULL)
return;
}
|
C
|
#pragma once
#define MAX_SIZE (100)
#include <stdbool.h>
typedef int Element;
/*
typedef struct {
bool isQuestion;
char msg[100];
}Element;
//*/ //Ҷ
typedef struct {
Element data[MAX_SIZE];
int size;
}BinaryTree;
void init(BinaryTree* bt);
int leftChild(const BinaryTree* bt, const int pos);
int rightChild(const BinaryTree* bt, const int pos);
int parent(const BinaryTree* bt, const int pos);
Element value(const BinaryTree* bt, const int pos);
void insert(BinaryTree* bt, const Element e);
int skewedTree(const BinaryTree* bt, const int pos);
|
C
|
#include <stdio.h>
int main(){
float x;
int cnt=1;
// for(x=100000001.0f;x<=1000000010.0f;x+=1.0f)
// printf("%d. x = %.30f\n",cnt++, x);
// 위 코드는 1이라는 값이 float형의 유효정밀도 자리수의 밖에 있기 떄문에
// 1이 더해지지 않고 무시되기 때문에 x값은 1억으로 유지되고 무한루프 발생.
//사실 for문에 iterator로써 정수가 아닌 실수를 넣는거 자체가 오류지만,
//학습 + 실험의 목적으로 코드 작성.
for(x=0.1f;x<=1.0f;x+=0.1f)
printf("%d. x = %.10f\n",cnt++,x);
return 0;
}
|
C
|
/** @file
* Interface for functions for dealing with fields owners on
* find-and-union level.
*/
#ifndef FAU_H
#define FAU_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
/** @brief Change given field's owner to player
* Changes field's owner and if necessary joins areas in find-and-union.
* Complexity O(log n) where n stands for number of fields in joined areas.
* @param[in] g - pointer to structure holding game status,
* @param[in] player - number of a new owner,
* @param[in] x - horizontal position on board,
* @param[in] y - vertical position on board.
*/
void place(gamma_t *g, uint32_t player, uint32_t x, uint32_t y);
/** @brief Frees given field
* Frees given field and if necessary disjoins areas in find-and-union.
* Complexity O(n) where n stands for number of fields in disjoined areas.
* @param[in] g - pointer to structure holding game status,
* @param[in] x - horizontal position on board,
* @param[in] y - vertical position on board.
*/
void delete_field(gamma_t* g, uint32_t x, uint32_t y);
#endif /* FAU_H */
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int count = 0;
void dfs(int n, int matrix[][n], int j, bool visited[]){
if(count == n) return;
visited[j] = true;
printf("%d\t",j);
count++;
for(int i=0; i<n; i++){
if(!visited[i] && matrix[j][i] != 0){
dfs(n,matrix,i,visited);
}
}
}
int main(){
int n,e;
printf("enter number of vertices and edges\n");
scanf("%d%d",&n,&e);
int matrix[n][n];
bool visited[n];
for (int i = 0; i < n; ++i)
{
visited[i] = false;
for (int j = 0; j < n; ++j)
{
matrix[i][j] = 0;
}
}
printf("enter vertice1 vertice2 weight\n");
for(int i=0; i<e; i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
matrix[u][v] = matrix[v][u] = w;
}
dfs(n,matrix,3,visited);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
signed int binarysearch(int *, uint32_t, int32_t);
int main(void)
{
int32_t position = 0;
int arr[10] = {1, 3, 6, 7, 11, 13, 14, 16, 19, 22};
position = binarysearch(arr, 10, 16);
printf("answer: %d\n", position);
return EXIT_SUCCESS;
}
/*
*n0<n1<n2...
*/
signed int binarysearch(int *arr, uint32_t arr_size, int32_t search)
{
//array has one or less elements
if(!arr_size)
{
return -1;
}
uint32_t low, middle, high;
low = 0;
high = arr_size - 1;
while(low <= high)
{
middle = low + (high - low) / 2;
if(arr[middle] < search)
{
low = middle +1;
}
else if(arr[middle] > search)
{
high = middle -1;
}
else
{
return middle;
}
}
return -1;
}
|
C
|
#include <stdio.h>
void itob(int n, char s[], int b);
int size(char s[]);
void reverse(char s[]);
int abs();
int main(void) {
char s[1000];
int i = 0xf83fa833;
printf("0x%x\n", i);
itob(i, s, 16);
printf("0x%s\n", s);
return 0;
}
void itob(int n, char s[], int b) {
unsigned un = 0 | n;
int i = 0, k = n;
do {
s[i++] = (un % b) < 10 ?
(un % b) + '0' : (un % b) - 10 + 'A';
} while ((un /= b) != 0);
s[i] = '\0';
reverse(s);
}
int size(char s[]) {
int i = 0;
for(i = 0; s[i] != '\0'; ++i);
return i;
}
int abs(int a) {
return (a < 0) ? -a : a;
}
void reverse(char s[]) {
int i = 0, len = size(s);
char temp;
for(i = 0, len = size(s); i < len; ++i, --len){
temp = s[i];
s[i] = s[len - 1];
s[len - 1] = temp;
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
int nodeheight;
}node;
node *insert(node *tree,int element);
node *Delete(node *tree,int element);
int search(node *tree,int element);
void preorder(node *tree);
void inorder(node *tree);
int height(node *tree);
node *rotateright(node *tree);
node *rotateleft(node *tree);
node *R(node *tree);
node *L(node *tree);
node *LR(node *tree);
node *RL(node *tree);
int balancefactor(node *tree);
|
C
|
#include<stdio.h>
int main(){
int x, y, z;
printf("Enter three Integer numbers for x, y, z : ");
scanf("%d %d %d", &x, &y, &z);
if((x < y)&&(x < z))
printf("%d is smallest",x);
else
{
if(y < z)
printf("%d is smallest",y);
else
printf("%d is smallest",z);
}
return(0);
}
|
C
|
/*
Trabalho feito por:
Arthur De Bellis - 03503
Saulo Miranda Silva - 03475
Pablo Ferreira - 03480
*/
#include "Libs/TAD_Patricia.h"
#include "Libs/IndInverso.h"
#include "Libs/tst.h"
#include "Libs/menu.h"
#include "Libs/ConversaoPalavras.h"
int ni = 0;
int main(){
//Inicialização de estruturas necessarias
Apontador arvore;
LBusca busca;
IniciaListaBusca(&busca);
LRelevancia relevancia;
NoTST* head = NULL;
InicializaPatricia(&arvore);
IniciaListaRelevancia(&relevancia);
//Variaveis utilizadas para criação do programa
int opcao;
int contBusca=0;
int quantidadeTextos;
int quantidadePalavras;
char *palavraPesquisa;
char *prefixo;
char nomeArquivo[100], nomeArquivoBusca[100], palavra[100], palavraBusca[100];;
char *aux = NULL;
char *auxBusca = NULL;
palavraPesquisa = (char*)malloc(sizeof(char));
prefixo = (char*)malloc(sizeof(char));
menu_de_entradas();
scanf("%d", &opcao);
while(opcao != 4){
if(opcao == 1){ //Criação do indice invertido
FILE *arquivo;
printf("Digite a quantidade de arquivos a serem lidos: ");
scanf("%d", &quantidadeTextos);
for(int i = 0; i < quantidadeTextos; i++){ // lendo todos os arquivos
char path[100] = "arquivos/";
printf("Nome do Arquivo (com extensão .txt): ");
scanf("%s", nomeArquivo);
strcat(path, nomeArquivo);
arquivo = fopen(path, "r");
if(!arquivo){
printf("Fim da Leitura");
}
else {
while(feof(arquivo) != 1){ // lendo todas as palavras até terminar
fscanf(arquivo, "%s ", palavra);
aux = palavra;
aux = ConverteMaiusculo(aux);
aux = IgnoraPontuacao(aux);
arvore = Insere(aux, &arvore, i+1);
head = InserirNoTST(aux, head);
}
}
}
fclose(arquivo);
menu_de_entradas();
scanf("%d", &opcao);
}
if(opcao == 2){ //Busca do indice invertido
FILE *arquivo2;
char path[100] = "arquivos/";
printf("Nome do Arquivo de Busca (com extensão .txt): ");
scanf("%s", nomeArquivoBusca);
strcat(path, nomeArquivoBusca);
arquivo2 = fopen(path, "r");
if(!arquivo2){
printf("Fim da Leitura");
}
while(feof(arquivo2) != 1){ //lendo o arquivo de busca
fscanf(arquivo2, "%s ", palavraBusca);
auxBusca = palavraBusca;
auxBusca = ConverteMaiusculo(auxBusca);
auxBusca = IgnoraPontuacao(auxBusca);
InserirNovoBusca(&busca, auxBusca);
contBusca++;
}
fclose(arquivo2);
for(int i = 0; i < quantidadeTextos; i++){
RelevanciaFinal(arvore, contBusca, auxBusca, &relevancia, quantidadeTextos, i+1, &busca, i);
}
ImprimirListaRelevancia(relevancia);
menu_de_entradas();
scanf("%d", &opcao);
}
if(opcao == 3){ //Auto Completar palavras
printf("Digite o prefixo a ser pesquisado: \n");
scanf("%s", prefixo);
AutoComplete(head, prefixo, prefixo);
menu_de_entradas();
scanf("%d", &opcao);
}
}
menu_de_saida();
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<string.h>
#define N 1005
typedef struct node
{
char data;
struct node* left;
struct node* right;
}node;
void print(node* head)
{
if(head == NULL) return;
if(!(head -> data >= '0' && head -> data <= '9'))
{
printf("(");
print(head->left);
printf("%c", head->data);
print(head->right);
printf(")");
}
else
{
print(head->left);
printf("%c",head->data);
print(head->right);
}
}
int evaluate(node* head)
{
if(head != NULL)
{
int res;
int left = evaluate(head->left);
int right = evaluate(head->right);
if(head->data == '+')
res = left + right;
else if(head->data == '-')
res = left - right;
else if(head->data == '*')
res = left * right;
else if(head->data == '/')
res = left/right;
else
res = head->data - '0';
return res;
}
return 0;
}
int main()
{
node* stack[5000];
char str[500000];
scanf("%s", str);
int len = strlen(str);
int top = -1;
for(int i = 0; i < len; i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
node* new_node = malloc(sizeof(node));
new_node->data = str[i];
new_node->left = NULL;
new_node->right = NULL;
stack[++top] = new_node;
}
else
{
node* new_node = malloc(sizeof(node));
new_node->data = str[i];
new_node->right = stack[top--];
new_node->left =stack[top--];
stack[++top] = new_node;
}
}
node* head = stack[0];
printf("%d\n", evaluate(head));
print(head);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define MAX 50
int size;
int isEmpty(struct stack *ptr);
int isFull(struct stack *ptr);
struct stack
{
int top;
int arr[MAX];
};
void init_stack(struct stack *ptr)
{
ptr->top = -1;
}
void push(struct stack *ptr)
{
int ele;
if(isFull(ptr))
{
printf("Stack overflow, cannot PUSH");
return;
}
else
{
printf("Enter Element\t");
scanf("%d",&ele);
ptr->top++;
ptr->arr[ptr->top] = ele;
}
return;
}
int pop(struct stack *ptr)
{
int val;
if(isEmpty(ptr))
{
printf("Stack underflow, cannot POP");
return -1;
}
else
{
val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
int isEmpty(struct stack *ptr)
{
if(ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct stack *ptr)
{
if(ptr->top == size - 1)
{
return 1;
}
else
{
return 0;
}
}
int peek(struct stack *ptr)
{
int pos,x;
if(isEmpty(ptr))
{
printf("Stack is empty");
}
else
{
printf("Enter Position\t");
scanf("%d",&pos);
if(pos<0)
{
printf("Not a valid position");
return -1;
}
else
{
x = ptr->arr[pos-1];
printf("The value at position %d is %d\n",pos,x);
}
}
}
int top(struct stack *ptr)
{
if(isEmpty(ptr))
{
printf("Stack is empty");
}
else
{
printf("Top element = %d\n",ptr->arr[ptr->top]);
}
}
int bottom(struct stack *ptr)
{
if(isEmpty(ptr))
{
printf("Stack is empty\n");
}
else
{
printf("Bottom element = %d\n",ptr->arr[0]);
}
}
int display(struct stack *ptr)
{
int i;
if(isEmpty(ptr))
{
printf("Stack is empty\n");
}
else
{
for(i=ptr->top; i>=0; i--)
{
printf("%d ", ptr->arr[i]);
}
}
printf("\n");
}
int main()
{
int choice,ele,pos;
struct stack s;
char option ='y';
init_stack(&s);
printf("Enter stack size\t");
scanf("%d",&size);
while(option=='y'||option=='Y')
{
printf("1. PUSH\n2. POP\n3. Display\n4. PEEK\n");
printf("5. Top Element\n6. Bottom Element\n7. EXIT\n");
printf("Enter Choice\t");
scanf("%d",&choice);
switch (choice)
{
case 1: push(&s);
break;
case 2: pop(&s);
break;
case 3: display(&s);
break;
case 4: peek(&s);
break;
case 5: top(&s);
break;
case 6: bottom(&s);
break;
case 7: exit(0);
break;
default: printf("Wrong Choice! Try Again");
break;
}
fflush(stdin);
printf("Do you want to continue (y or n)? \t");
scanf("%c",&option);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <png.h>
#include "export_png.h"
void export_grayscale_png (
double data[],
long window,
long width,
long height,
char filename[]
) {
FILE *file = fopen (filename, "wb");
unsigned char *pixels = malloc (width * height * sizeof (unsigned char));
for (long x = 0; x < width; x++) {
for (long y = 0; y < height; y++) {
long pos_data = x * window + y * (((float)height)/((float)window));
//unsigned char value = (255 * data[x * window + y * (height/window)][0]);
double value = (data[pos_data]);
pixels [(height-y-1)*width + x] = (unsigned char)(255 * (value));
}
}
write_png (pixels, width, height, file, false);
free (pixels);
fclose (file);
}
void export_color_png (
double data[],
long window,
long width,
long height,
char filename[]
) {
FILE *file = fopen (filename, "wb");
unsigned char *pixels = malloc (3 * width * height * sizeof (unsigned char));
for (long x = 0; x < width; x++) {
for (long y = 0; y < height; y++) {
int pos_data = x * window + y * (((float)height)/((float)window));
//unsigned char value = (255 * data[x * window + y * (height/window)][0]);
double r = (data[3*pos_data]);
double g = (data[3*pos_data+1]);
double b = (data[3*pos_data+2]);
pixels [3*((height-y-1)*width + x)] = (unsigned char)(255 * (r));
pixels [3*((height-y-1)*width + x)+1] = (unsigned char)(255 * (g));
pixels [3*((height-y-1)*width + x)+2] = (unsigned char)(255 * (b));
}
}
write_png (pixels, width, height, file, true);
free (pixels);
fclose (file);
}
void write_png (unsigned char *data, long width, long height, FILE *file, unsigned color) {
png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
fprintf (stderr, "Error, invalid png pointer");
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
fprintf (stderr, "Error invalid info pointer");
}
png_init_io (png_ptr, file);
int colortype = color? PNG_COLOR_TYPE_RGB: PNG_COLOR_TYPE_GRAY;
png_set_IHDR (
png_ptr, info_ptr,
width, height,
8, // color depth
colortype,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT
);
png_write_info (png_ptr, info_ptr);
if (color) {
// Allocate memory for one row (3 bytes per pixel - RGB)
png_byte *buf = malloc(4 * width * sizeof(png_byte));
// Write image data
long col, row;
for (row=0 ; row < height; row++) {
for (col=0 ; col < width; col++) {
buf[3*col] = data[3*(row*width + col)];
buf[3*col + 1] = data[3*(row*width + col)+1];
buf[3*col + 2] = data[3*(row*width + col)+2];
}
png_write_row(png_ptr, buf);
}
free (buf);
} else {
png_byte *buf = (png_byte*) malloc (sizeof (png_byte) * width);
int row, col;
for (row = 0; row < height; row++) {
for (col = 0; col < width; col++) {
buf[col] = data[row*width + col];
}
png_write_row (png_ptr, buf);
}
free (buf);
}
png_write_end (png_ptr, NULL);
png_free_data (png_ptr, info_ptr, PNG_FREE_ALL, -1);
png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define Max_row 3
#define Max_col 3
char arr[Max_row][Max_col];
//ӡϷ˵
int menu()
{
printf("---------------\n");
printf("--1.ʼϷ---\n");
printf("--0.˳Ϸ---\n");
printf("---------------\n");
printf("ѡ0 or 1:");
int choice;
scanf("%d", &choice);
return choice;
}
//жǷ
int isFull()
{
for (int row = 0; row < Max_row; ++row)
{
for (int col = 0; col < Max_col; ++col)
{
if (arr[row][col] == ' ')
{
return 0;//ʾû
}
}
}
return 1;//ʾ
}
//ʼ
void init()
{
for (int row = 0; row < Max_row; ++row)
{
for (int col = 0; col < Max_col; ++col)
{
arr[row][col] = ' ';
}
}
}
//Ϸж,ѡӦķֵ
char check()
{
for (int row = 0; row < Max_row; ++row)
{
if (arr[row][0] == arr[row][1] && arr[row][0] == arr[row][2])
{
return arr[row][0];
}
}
for (int col=0; col < Max_col; ++col)
{
if (arr[0][col] == arr[1][col] && arr[0][col] == arr[2][col])
{
return arr[0][col];
}
}
if (arr[0][0] == arr[1][1] && arr[0][0] == arr[2][2])
{
return arr[0][0];
}
if (arr[0][2] == arr[1][1] && arr[0][2] == arr[2][0])
{
return arr[0][2];
}
if (isFull())
{
return 'z';
}
return ' ';
}
//,ӡÿºԼʼ
void print()
{
for (int row = 0; row < Max_row; row++)
{
printf("| %c | %c | %c |\n", arr[row][0], arr[row][1], arr[row][2]);
if (row != Max_row - 1)
{
printf("|---|---|---|\n");
}
}
}
//
playerMove()
{
while (1)
{
printf("һ(row,col):");
int row; int col;
scanf("%d %d", &row, &col);
if (row >= Max_row || row < 0 && col >= Max_col || col < 0)
{
printf("겻Ϸ\n");
continue;
}
if (arr[row][col] != ' ')
{
printf("ѱռ\n");
continue;
}
arr[row][col] = 'x';
break;
}
}
//Ƶ
computerMove()
{
while (1)
{
int row = rand() % Max_row;
int col = rand() % Max_col;
if (arr[row][col] != ' ')//겿λ' ',֤ѱռ
{
continue;
}
arr[row][col] = 'o';
break;
}
}
//Ϸй
void game()
{
init();
char winer;//Ӧķֵ,ϷӦ
while (1)
{
system("cls");
print();
playerMove();
winer = check();
if (winer != ' ')
{
break;
}
computerMove();
winer = check();
if (winer != ' ')
{
break;
}
}
system("cls");
if (winer == 'x')
{
printf("һʤ\n");
}
else if (winer == 'o')
{
printf("Իʤ\n");
}
else if(winer == 'z')
{
printf("ƽ\n");
}
else
{
printf("\n");
}
print();
}
int main()
{
while (1)
{
int choice = menu();
if (choice == 1)
{
game();
}
else if (choice == 0)
{
printf("ݰ!\n");
}
else
{
printf("\n");
}
}
system("pause");
return 0;
}
|
C
|
#include "stringHelpers.h"
#include "secretDecoder.h"
#include "fileReader.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Get the number in between two brackets in an encoded message
int getNumber(char *secretMessage, int *index) {
bool end = false;
int this_index = 1;
char number_arry[100] = {};
while (!end) {
char c = secretMessage[*index + this_index];
if (c == ']') {
// If char is end-square bracket, we are finished getting number
end = true;
} else {
// Add current char to array
number_arry[this_index - 1] = c;
this_index++;
}
}
// Increase original index, so its outside of the brackets
*index += this_index;
// Parse number to int, and return it
int number_represented = -1;
sscanf(number_arry, "%d", &number_represented);
return number_represented;
}
// Decode secretMessage with Keyfile
char *decode(char *keyFile, char *secretMessage, int *status) {
// Allocate some space for cracked message
char *crackedMessage = malloc(strlen(secretMessage) / 3 * sizeof(char));
int crackedMessageIndex = 0;
// Get size of keyfile
int keyFileSize = strlen(keyFile);
// Get size of secret message
int secretMessageSize = strlen(secretMessage);
// Loop through secret message
for (int i = 0; i < secretMessageSize - 1; i++) {
char currentCrackedChar = secretMessage[i];
// If we meet square brackets, get the number inside it and decode with
if (currentCrackedChar == '[') {
int number = getNumber(secretMessage, &i);
if (number > keyFileSize) {
*status = 1;
} else {
if (number >= 0) {
crackedMessage[crackedMessageIndex++] = keyFile[number];
}
else {
// If number is negative, it's an indication that it's ment to be high-case. Make number positive
number *= -1;
// add number as highcase (Unicode conv low->high = +32)
crackedMessage[crackedMessageIndex++] = keyFile[number] - 32;
}
}
}
// If not a square bracket, its not encoded. Just add it
else {
crackedMessage[crackedMessageIndex++] = currentCrackedChar;
}
}
// Add breack character at end
crackedMessage[crackedMessageIndex] = '\0';
printf("%s\n%s\n", crackedMessage, secretMessage);
return crackedMessage;
}
|
C
|
#include <stdlib.h>
#include "structs.h"
#include "functions.h"
int search(int curves_sum, struct curve *curves, struct curve query, double *distanceTrue){
int i, j, min, min_pos;
double dist;
min=1000000;
min_pos=-1;
for(i=0; i<curves_sum; i++){ // Vriskoume ton actual kontinotero geitona tou query
dist = dtw(curves[i], query);
if(min>dist && dist!=0){
min=dist;
min_pos=i;
}
}
*distanceTrue=min; // Ekxwroume tin actual min distance
return min_pos; // Epistrefoume to pos tou actual neighbor
}
|
C
|
#include <stdio.h>
int main() {
int a,b,c,d;
int x1,x2,x3;
int winner1,winner2,bigWinner;
char firtwinner, secondwinner;
scanf("%d %d %d",&x1,&a,&b);
scanf("%d %d %d",&x2,&c,&d);
scanf("%d %d %d",&x3,&winner1,&winner2);
int result = a + b;
if (x1 == 0 && (result)%2 == 0 || x1 != 0 && (result)%2 != 0) {
firtwinner = 'A';
} else {
firtwinner = 'B';
}
result = c + d;
if (x2 == 0 && (result)%2 == 0 || x2 != 0 && (result)%2 != 0) {
secondwinner = 'C';
} else {
secondwinner = 'D';
}
result = winner1 + winner2;
if (x3 == 0 && (result)%2 == 0 || x3 != 0 && (result)%2 != 0) {
printf("%c\n",firtwinner);
} else {
printf("%c\n",secondwinner);
}
return 0;
}
|
C
|
//-----------------------------------------------------------------------------
//lcd_rot.c
//-----------------------------------------------------------------------------
//
// Program Description:
//
// This program interfaces with DS1307 ( Real time clock ) via the i2c communication protocal.
// It sets the time & calender registers and runs the clock.
//
// How To Test:
//
// 1) Download code to the Pt-51 board
// 2) Connect LCD at the slot provided
// 3) You should see a scrolling display of the following text " This is a string message " from right to left only
//
//
// Author: P.Anusri
// Target: C8051F38x
// Tool chain: Keil / Raisonance
// Command Line: None
//
//
// Release 1.0 - 10-JUNE-2013 (PKC)
// -Initial Revision
//
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include <at89c5131.h>
//-----------------------------------------------------------------------------
// Global Constants
//-----------------------------------------------------------------------------
Sbit ( RW , P0 , 1 ) ;
Sbit ( RS , P0 , 0 ) ;
Sbit ( EN , P0 , 2 ) ;
Sfr ( Dt , 0xA0 ) ;
unsigned char msg_size=24;
code unsigned char message[24]="This is a string message"; // write message to be displayed here
//-----------------------------------------------------------------------------
// Global Variables
//-----------------------------------------------------------------------------
signed char p;
unsigned long i;
unsigned char temp;
unsigned char count;
signed char boundary;
//-----------------------------------------------------------------------------
// Function Prototypes
//-----------------------------------------------------------------------------
void delay();
void status ();
void command ( unsigned char a );
void display (unsigned char a);
//-----------------------------------------------------------------------------
// main() Routine
//-----------------------------------------------------------------------------
void main()
{
command(0x38); // function set command
command(0x0c); // display switch command
command(0x06); // input set command
command(0x01); // clear screen command
boundary=0; // new character in text message to be displayed
/* boundary pointer decides the character to be displayed at the extreme right of the LCD screen and p is another pointer that runs
from the boundary character back to the first charcter in the text message */
while(1)
{
for(boundary=0;boundary<=(msg_size-1);boundary++) // incrementing the position of character to be displayed in text
{
command(0x01); // clear screen command
p=boundary;
count=0;
while(p>=0 && count<=15) // display all characters that come before the boundary character and that can fit on to the screen
{
command(0x8f-count); // decides the postion of text on LCD screen ( from right of the LCD screen )
display(message[p]); // display corresponding character from text at the position decided in the prev command
p=p-1;
count=count+1;
}
delay(); // controls the scrolling speed
}
/* P is pointer that decides the position of the last charcter in the text and boundary pointer runs from last
character to either the first character or to the charcter that last can fit on the screen */
p=1;
while(p<=15)
{
command(0x01); // clear screen command
boundary=msg_size-1;
count=p; // decides the position,from the right of the screen,of the last character in text message
while(boundary>=0 && count<=15)
{
/* routine to display all characters, that can fit on the sreen,running back from the last charcter
in text message*/
command(0x8f-count);
display(message[boundary]);
boundary=boundary-1;
count=count+1;
}
delay();
p=p+1;
}
}
}
//-----------------------------------------------------------------------------
// Initialization Subroutines
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// delay
//-----------------------------------------------------------------------------
//
// Return Value : None
// Parameters : None
//
//
// This function is used to control the scrolling speed of the text
//
//-----------------------------------------------------------------------------
void delay() {
for(i=0;i<9000;i=i+1)
{}
}
//-----------------------------------------------------------------------------
// status
//-----------------------------------------------------------------------------
//
// Return Value : None
// Parameters : None
//
// This function checks if the LCD is busy.
//
//-----------------------------------------------------------------------------
void status()
{
EN = 0 ;
RS = 0 ;
RW = 1 ; // read mode of LCD
Dt = 0xFF ; // configuring port pins as inputs
EN = 1 ;
while (P2_7==1) {} ; // wait if the lcd uC is busy
EN=0 ;
}
//-----------------------------------------------------------------------------
// command
//-----------------------------------------------------------------------------
//
// Return Value : None
// Parameters :
// 1) Unsigned char a - 8 bit command value to the LCD
//
// This function transmits the desired command to the LCD uC
//
//-----------------------------------------------------------------------------
void command ( unsigned char a )
{
status(); // checks the status of the LCD
EN = 0;
RS = 0;
RW = 0; // write mode of LCD
EN = 1;
Dt = a; // command transfered to port pins
EN = 0;
}
//-----------------------------------------------------------------------------
// display
//-----------------------------------------------------------------------------
//
// Return Value : None
// Parameters :
// 1) Unsigned char a - 8 bit ascii value (hex value) of the character to be displayed
//
// This function transmits the ascii value of the character to be displayed ti LCD uC
//
//-----------------------------------------------------------------------------
void display (unsigned char a)
{
status(); // checks the status of the LCD
EN = 0;
RS = 1;
RW = 0; // write mode of LCD
EN = 1;
Dt = a; // 8 bit hex value of character transfered to port pins
EN = 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fractol.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gsinged <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/25 20:31:56 by gsinged #+# #+# */
/* Updated: 2020/11/25 20:31:57 by gsinged ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FRACTOL_H
# define FRACTOL_H
# include "libft.h"
# include "keys.h"
# include <mlx.h>
# include <math.h>
# include <stdlib.h>
# include <errno.h>
# define WIDTH 1000
# define HEIGHT 1000
# define ITER 50
typedef struct s_mouse
{
int x;
int y;
int on;
} t_mouse;
typedef struct s_complex
{
double re;
double im;
} t_complex;
typedef struct s_color
{
int r;
int g;
int b;
} t_color;
typedef struct s_fractol {
char *name;
t_mouse mouse;
int julia;
int color;
int help;
void *mlx_ptr;
void *win_ptr;
void *img_ptr;
char *data_addr;
int bits_per_pixel;
int size_line;
int endian;
t_complex min;
t_complex max;
t_complex c;
t_complex k;
t_complex fact;
int max_iter;
int (*fractal)(struct s_fractol *f);
} t_fractol;
int ft_fractol(char *name);
t_complex init_complex(double re, double im);
void init_init(t_fractol *f);
void draw_map(t_fractol *f);
void ft_fractol_del(t_fractol *f);
int fract_julia(t_fractol *f);
int fract_mandelbrot(t_fractol *f);
int fract_julia4(t_fractol *f);
int fract_mandelbrot4(t_fractol *f);
int fract_mandelbar(t_fractol *f);
int fract_celtic_mandelbar(t_fractol *f);
int fract_burning_ship(t_fractol *f);
void draw(t_fractol *f);
void draw_help(t_fractol *f);
void control_keys(t_fractol *f);
int mouse_press(int mouse, int x, int y, t_fractol *f);
int mouse_release_hook(int mouse, int x, int y, t_fractol *f);
int motion_hook(int x, int y, t_fractol *f);
int press_key(int key, t_fractol *f);
void ft_printerror_mlx(t_fractol *f);
void print_error(void);
#endif
|
C
|
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ether.h>
#include <pcap.h>
#include <ifaddrs.h>
#include <ctype.h>
#include <netdb.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <stdbool.h>
#include <errno.h>
#ifndef SETTINGS_H
#include "settings.h"
#endif
#ifndef FUNCTIONS_H
#include "functions.h"
#endif
#ifndef PING_H
#include "ping.h"
#endif
/*********************************************************************************************
*
* checksum
*
*********************************************************************************************/
unsigned short csum(unsigned short *ptr,int nbytes) {
long sum;
unsigned short oddbyte;
short answer;
sum=0;
while(nbytes>1) {
sum+=*ptr++;
nbytes-=2;
}
if(nbytes==1) {
oddbyte=0;
*((u_char*)&oddbyte)=*(u_char*)ptr;
sum+=oddbyte;
}
sum = (sum>>16)+(sum & 0xffff);
sum = sum + (sum>>16);
answer=(short)~sum;
return(answer);
}
/*********************************************************************************************
*
* ziskej mac adresu
* https://www.stev.org/post/clinuxgetmacaddressfrominterface
*
*********************************************************************************************/
void get_mac(char *mac, char *dev) {
int sock = socket(PF_INET, SOCK_DGRAM, 0);
struct ifreq req;
int i = 0;
if (sock < 0)
{
fprintf(stderr, "Chyba pri zakladani socketu.\n");
exit(1);
}
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, dev, IF_NAMESIZE - 1);
if (ioctl(sock, SIOCGIFHWADDR, &req) < 0)
{
fprintf(stderr, "CIoctl error.\n");
exit(1);
}
snprintf(mac, 18, "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X", (unsigned char)req.ifr_hwaddr.sa_data[0], (unsigned char)req.ifr_hwaddr.sa_data[1], (unsigned char)req.ifr_hwaddr.sa_data[2], (unsigned char)req.ifr_hwaddr.sa_data[3], (unsigned char)req.ifr_hwaddr.sa_data[4], (unsigned char)req.ifr_hwaddr.sa_data[5]);
close(sock);
}
/*********************************************************************************************
*
* vygeneruj novou mac adresu
*
*********************************************************************************************/
void change_mac(char *dev) {
struct ifreq ifr = {0};
int s;
char mac[18];
time_t rtime;
char val[16] = "0123456789abcdef";
sprintf(mac,"%c8:%c%c:%c%c:%c%c:%c%c:%c%c",val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)],val[rndmstr(0,15)]);
sscanf(mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &ifr.ifr_hwaddr.sa_data[0], &ifr.ifr_hwaddr.sa_data[1],
&ifr.ifr_hwaddr.sa_data[2], &ifr.ifr_hwaddr.sa_data[3], &ifr.ifr_hwaddr.sa_data[4], &ifr.ifr_hwaddr.sa_data[5]);
s = socket(AF_INET, SOCK_DGRAM, 0);
if(s == -1) {
return;
}
strcpy(ifr.ifr_name, dev);
ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
if(ioctl(s, SIOCSIFHWADDR, &ifr) != -1)
;//printf("* new mac: %s on %s\n",mac, dev);
}
/*********************************************************************************************
*
* odeslani syn paketu z jedne domeny konkretniho interface
* inspirace v enderunix.org/docs/en/rawipspoof
*
*********************************************************************************************/
void send_syn(int spoofed_port, int target_port, char *spoofed_address, char *target_address, int client) {
//Data to be appended at the end of the tcp header
char *data;
char data_rand[40] = "Z toho stringu se generuji nahodna data";
data_rand[rndmstr(0,39)] = '\0';
//Ethernet header + IP header + TCP header + data
char packet[PCKT_LEN];
//Pseudo TCP header to calculate the TCP header's checksum
struct pseudoTCPPacket pTCPPacket;
//Pseudo TCP Header + TCP Header + data
char *pseudo_packet;
struct sockaddr_in din;
din.sin_family = AF_INET;
din.sin_port = htons(target_port);
din.sin_addr.s_addr = inet_addr(target_address);
int one = 1;
if (setsockopt(client, IPPROTO_IP, IP_HDRINCL, &one, sizeof(one)) < 0) {
fprintf(stderr, "setsockopt() error.\n");
exit(1);
}
//Allocate mem for ip and tcp headers and zero the allocation
memset(packet, 0, sizeof(packet));
struct iphdr *ip = (struct iphdr *) packet;
struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct iphdr));
data = (char *)(packet + sizeof(struct iphdr) + sizeof(struct tcphdr));
strcpy(data,data_rand);
ip->ihl = 5;
ip->version = 4;
ip->tos = 0;
ip->tot_len = sizeof (struct iphdr) + sizeof (struct tcphdr) + strlen(data); /* no payload */
ip->id = htons(54321); /* the value doesn't matter here */
ip->frag_off = 0x00;
ip->ttl = 0xFF;
ip->protocol = IPPROTO_TCP;
ip->check = 0;
ip->saddr = inet_addr(spoofed_address);
ip->daddr = inet_addr(target_address);
ip->check = csum((unsigned short *) packet, ip->tot_len);
tcp->source = htons(spoofed_port);
tcp->dest = htons(target_port);
tcp->seq = rndmsleep(1,ULONG_MAX);
tcp->ack_seq = 0x0;
tcp->doff = 5;
tcp->res1 = 0;
tcp->urg = 0;
tcp->ack = 0;
tcp->psh = 0;
tcp->rst = 0;
tcp->syn = 1;
tcp->fin = 0; //Terminates the connection
tcp->window = htons(155);//0xFFFF; //16 bit max number of databytes
tcp->check = 0; //16 bit check sum. Can't calculate at this point
tcp->urg_ptr = 0; //16 bit indicate the urgent data. Only if URG flag is set
//Now we can calculate the checksum for the TCP header
pTCPPacket.srcAddr = inet_addr(spoofed_address); //32 bit format of source address
pTCPPacket.dstAddr = inet_addr(target_address); //32 bit format of source address
pTCPPacket.zero = 0; //8 bit always zero
pTCPPacket.protocol = IPPROTO_TCP; //8 bit TCP protocol
pTCPPacket.TCP_len = htons(sizeof(struct tcphdr) + strlen(data)); // 16 bit length of TCP header
//Populate the pseudo packet
pseudo_packet = (char *) malloc((int) (sizeof(struct pseudoTCPPacket) + sizeof(struct tcphdr) + strlen(data)));
memset(pseudo_packet, 0, sizeof(struct pseudoTCPPacket) + sizeof(struct tcphdr) + strlen(data));
//Copy pseudo header
memcpy(pseudo_packet, (char *) &pTCPPacket, sizeof(struct pseudoTCPPacket));
//Copy tcp header + data to fake TCP header for checksum
memcpy(pseudo_packet + sizeof(struct pseudoTCPPacket), tcp, sizeof(struct tcphdr) + strlen(data));
//Set the TCP header's check field
tcp->check = (csum((unsigned short *) pseudo_packet, (int) (sizeof(struct pseudoTCPPacket) +
sizeof(struct tcphdr) + strlen(data))));
if (sendto(client, packet, ip->tot_len, 0, (struct sockaddr *)&din, sizeof(din)) < 0)
{
fprintf(stderr, "Chyba pri odesilani dat pres socket. %s\n",strerror(errno));
exit(1);
}
}
/*********************************************************************************************
*
* obo sniffer co zachycuje postupne odpovedi na udp datagramy
*
*********************************************************************************************/
void *obo_sniffer(void *arg)
{
struct obo_sniffer_arguments *args = (struct obo_sniffer_arguments *)arg;
char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
bpf_u_int32 mask; /* Our netmask */
bpf_u_int32 net; /* Our IP */
struct pcap_pkthdr header; /* The header that pcap gives us */
const unsigned char *packet; /* The actual packet */
if (pcap_lookupnet(args->ifc, &net, &mask, errbuf) == -1)
{
fprintf(stderr, "Couldn't get netmask for device %s: %s\n", args->ifc, errbuf);
net = 0;
mask = 0;
}
pcap_t *ifc_sniff = pcap_open_live(args->ifc, BUFSIZ, 1, 1000, errbuf); // 1514, 4000
if (ifc_sniff == NULL)
{
fprintf(stderr, "Couldn't open device %s: %s\n", args->ifc, errbuf);
exit(1);
}
int retv;
// argumenty pro interface callback
struct obo_callback_arguments *obo_callback_arg = malloc(sizeof(struct obo_callback_arguments));
if (obo_callback_arg == NULL)
{
fprintf(stderr, "Chyba alokaci pameti.\n");
exit(1);
}
obo_callback_arg->end_of_evangelion = malloc(sizeof(bool *));
if (obo_callback_arg->end_of_evangelion == NULL)
{
fprintf(stderr, "Chyba alokaci pameti.\n");
exit(1);
}
obo_callback_arg->sniff = malloc(sizeof(pcap_t *));
if (obo_callback_arg->sniff == NULL)
{
fprintf(stderr, "Chyba alokaci pameti.\n");
exit(1);
}
memset(obo_callback_arg->target, '\0', 16);
strcpy(obo_callback_arg->target, args->target);
obo_callback_arg->end_of_evangelion = args->end_of_evangelion;
obo_callback_arg->sniff = ifc_sniff;
obo_callback_arg->response_received = args->response_received;
obo_callback_arg->decoy_count = args->decoy_count;
retv = pcap_loop(ifc_sniff, -1, (pcap_handler)obo_callback, (unsigned char *)obo_callback_arg);
// z callbacku byl zavolan breakloop
if (retv != -2 && retv < 0)
{
fprintf(stderr, "cannot get raw packet: %s\n", pcap_geterr(ifc_sniff));
exit(1);
}
pcap_close(ifc_sniff);
free(obo_callback_arg);
return NULL;
}
/*********************************************************************************************
*
* odeslani udp datagramu z jedne domeny konkretniho interface
* inspirace v enderunix.org/docs/en/rawipspoof
*
*********************************************************************************************/
void send_udp(int spoofed_port, int target_port, char *spoofed_address, char *target_address, int client) {
char *data;
//Ethernet header + IP header + UDP header + data
char packet[PCKT_LEN];
//Pseudo UDP header to calculate the TCP header's checksum
struct pseudoUDPPacket pUDPPacket;
//Pseudo UDP Header + UDP Header + data
char *pseudo_packet;
struct sockaddr_in din;
din.sin_family = AF_INET;
din.sin_port = htons(target_port);
din.sin_addr.s_addr = inet_addr(target_address);
int one = 1;
if (setsockopt(client, IPPROTO_IP, IP_HDRINCL, &one, sizeof(one)) < 0) {
fprintf(stderr, "setsockopt() error.\n");
exit(1);
}
//Allocate mem for ip and tcp headers and zero the allocation
memset(packet, 0, sizeof(packet));
struct iphdr *ip = (struct iphdr *) packet;
struct udphdr *udp = (struct udphdr *) (packet + sizeof(struct iphdr));
data = (char *)(packet + sizeof(struct iphdr) + sizeof(struct udphdr));
strcpy(data,"");
ip->ihl = 5;
ip->version = 4;
ip->tos = 0;
ip->tot_len = sizeof (struct iphdr) + sizeof (struct udphdr) + strlen(data); /* no payload */
ip->id = htons(54321); /* the value doesn't matter here */
ip->frag_off = 0x00;
ip->ttl = 0xFF;
ip->protocol = IPPROTO_UDP; //TCP protocol
ip->check = 0; /* set it to 0 before computing the actual checksum later */
ip->saddr = inet_addr(spoofed_address);/* SYN's can be blindly spoofed */
ip->daddr = inet_addr(target_address);
//Now we can calculate the check sum for the IP header check field
ip->check = csum((unsigned short *) packet, ip->tot_len);
udp->uh_sum = 0;
udp->uh_dport = htons(target_port);
udp->uh_sport = htons(spoofed_port);
udp->uh_ulen = htons(sizeof(udp) + strlen(data)); // nemelo by tu byt sizeof udphdr? mozna bug
//Now we can calculate the checksum for the UDP header
pUDPPacket.srcAddr = inet_addr(spoofed_address); //32 bit format of source address
pUDPPacket.dstAddr = inet_addr(target_address); //32 bit format of source address
pUDPPacket.zero = 0; //8 bit always zero
pUDPPacket.protocol = IPPROTO_UDP; //8 bit TCP protocol
pUDPPacket.UDP_len = htons(sizeof(struct udphdr) + strlen(data)); // 16 bit length of TCP header
//Populate the pseudo packet
pseudo_packet = (char *) malloc((int) (sizeof(struct pseudoUDPPacket) + sizeof(struct udphdr) + strlen(data)));
memset(pseudo_packet, 0, sizeof(struct pseudoUDPPacket) + sizeof(struct udphdr) + strlen(data));
//Copy pseudo header
memcpy(pseudo_packet, (char *) &pUDPPacket, sizeof(struct pseudoUDPPacket));
//Copy udp header + data to fake UDP header for checksum
memcpy(pseudo_packet + sizeof(struct pseudoUDPPacket), udp, sizeof(struct udphdr) + strlen(data));
//Set the TCP header's check field
udp->uh_sum = (csum((unsigned short *) pseudo_packet, (int) (sizeof(struct pseudoUDPPacket) +
sizeof(struct udphdr) + strlen(data))));
if (sendto(client, packet, ip->tot_len, 0, (struct sockaddr *)&din, sizeof(din)) < 0)
{
fprintf(stderr, "Chyba pri odesilani dat pres socket. %s\n",strerror(errno));
exit(1);
}
}
/*********************************************************************************************
*
* sniffer co zachycuje na konkretnim rozhrani pakety jdouci na jeho konkretni rozhrani
*
*********************************************************************************************/
void *xxp_sniffer(void *arg)
{
struct xxp_sniffer_arguments *args = (struct xxp_sniffer_arguments *)arg;
char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
bpf_u_int32 mask; /* Our netmask */
bpf_u_int32 net; /* Our IP */
struct pcap_pkthdr header; /* The header that pcap gives us */
const unsigned char *packet; /* The actual packet */
if (pcap_lookupnet(args->ifc, &net, &mask, errbuf) == -1)
{
fprintf(stderr, "Couldn't get netmask for device %s: %s\n", args->ifc, errbuf);
net = 0;
mask = 0;
}
pcap_t *ifc_sniff = pcap_open_live(args->ifc, BUFSIZ, 1, 1000, errbuf); // 1514, 4000
if (ifc_sniff == NULL)
{
fprintf(stderr, "Couldn't open device %s: %s\n", args->ifc, errbuf);
exit(1);
}
int retv;
// argumenty pro interface callback
struct xxp_callback_arguments *xxp_callback_arg = malloc(sizeof(struct xxp_callback_arguments));
if (xxp_callback_arg == NULL)
{
fprintf(stderr, "Chyba alokaci pameti.\n");
exit(1);
}
xxp_callback_arg->end_of_evangelion = malloc(sizeof(bool *));
if (xxp_callback_arg->end_of_evangelion == NULL)
{
fprintf(stderr, "Chyba alokaci pameti.\n");
exit(1);
}
xxp_callback_arg->sniff = malloc(sizeof(pcap_t *));
if (xxp_callback_arg->sniff == NULL)
{
fprintf(stderr, "Chyba alokaci pameti.\n");
exit(1);
}
memset(xxp_callback_arg->target, '\0', 16);
strcpy(xxp_callback_arg->target, args->target);
xxp_callback_arg->end_of_evangelion = args->end_of_evangelion;
xxp_callback_arg->sniff = ifc_sniff;
xxp_callback_arg->min_port = args->min_port;
xxp_callback_arg->port_count = args->port_count;
xxp_callback_arg->decoy_count = args->decoy_count;
retv = pcap_loop(ifc_sniff, -1, (pcap_handler)xxp_callback, (unsigned char *)xxp_callback_arg);
// z callbacku byl zavolan breakloop
if (retv != -2 && retv < 0)
{
fprintf(stderr, "cannot get raw packet: %s\n", pcap_geterr(ifc_sniff));
exit(1);
}
pcap_close(ifc_sniff);
free(xxp_callback_arg);
return NULL;
}
/*********************************************************************************************
*
* callback interface snifferu
*
*********************************************************************************************/
void xxp_callback(struct xxp_callback_arguments *arg, const struct pcap_pkthdr *header, const unsigned char *packet)
{
arg = (struct xxp_callback_arguments *)arg;
// jeste neni konec
if (!(*arg->end_of_evangelion))
{
struct ether_header* eth;
struct iphdr *ip;
packet += sizeof(struct ether_header);
ip = (struct iphdr*)packet;
char srcname[16];
inet_ntop(AF_INET, &ip->saddr, srcname, INET_ADDRSTRLEN);
if (!strcmp(srcname, arg->target))
{
char dstname[16];
inet_ntop(AF_INET, &ip->daddr, dstname, INET_ADDRSTRLEN);
for (int i = 0; i < arg->decoy_count; i++)
{
if (!strcmp(dstname, addresses[i].ip))
{ // jestli je cilova adresa v poli lokalnich adres
// start analyzy obsahu paketu
if (ip->protocol == 6) { // tcp
struct tcphdr *tcp = (struct tcphdr*)(packet+ ip->ihl * 4);
if (tcp->th_flags & TH_SYN)
{ // SYN i ACK SYN
unsigned short srcport = ntohs(tcp->th_sport);
if (global_list_tcp[srcport - arg->min_port].port != 0) {
global_list_tcp[srcport - arg->min_port].passed = true;
}
}
else if (tcp->th_flags & TH_RST)
{
unsigned short srcport = ntohs(tcp->th_sport);
if(global_list_tcp[srcport - arg->min_port].port != 0) {
(global_list_tcp[srcport - arg->min_port].rst)++;
global_list_tcp[srcport - arg->min_port].passed = true;
}
}
}
break; // skonci
}
}
}
}
else
pcap_breakloop(arg->sniff);
}
/*********************************************************************************************
*
* callback obo snifferu, hleda vhodna ICMP a nastavuje response_received pro obo looper
*
*********************************************************************************************/
void obo_callback(struct obo_callback_arguments *arg, const struct pcap_pkthdr *header, const unsigned char *packet)
{
arg = (struct obo_callback_arguments *)arg;
// jeste neni konec
if (!(*arg->end_of_evangelion))
{
struct ether_header* eth;
struct iphdr *ip;
packet += sizeof(struct ether_header);
ip = (struct iphdr*)packet;
char srcname[16];
inet_ntop(AF_INET, &ip->saddr, srcname, INET_ADDRSTRLEN);
if (!strcmp(srcname, arg->target))
{
char dstname[16];
inet_ntop(AF_INET, &ip->daddr, dstname, INET_ADDRSTRLEN);
if (!strcmp(dstname, addresses[arg->decoy_count-1].ip))
{
// start analyzy obsahu paketu
if (ip->protocol == 1) { // tcp
struct icmphdr *icmp = (struct icmphdr*)(packet + ip->ihl * 4);
if(icmp->type == 3 && icmp->code == 3)
(*arg->response_received) = true;
}
}
}
}
else
pcap_breakloop(arg->sniff);
}
/*********************************************************************************************
*
* ziskej vsechna rozhrani
* http://man7.org/linux/man-pages/man3/getifaddrs.3.html pro pokrocile moznosti a ipv6
*
*********************************************************************************************/
struct single_interface *getInterface(int *interfaces_count)
{
// vytvor argumenty co pujdou do *interfaces
struct single_interface *interfaces = malloc(10 * sizeof(struct single_interface)); // pole max. deseti interfaces
if (interfaces == NULL)
{
fprintf(stderr, "Chyba alokace pameti.\n");
exit(1);
}
struct ifaddrs *ifaddr, *ifa;
int family, s, n, m;
char host[16];
char mask[16];
if (getifaddrs(&ifaddr) == -1)
{
fprintf(stderr, "Chyba pri getifaddress.\n");
exit(1);
}
for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++)
{
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
if (family == AF_INET)
{
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, 16, NULL, 0, NI_NUMERICHOST);
m = getnameinfo(ifa->ifa_netmask, sizeof(struct sockaddr_in), mask, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s != 0)
{
fprintf(stderr, "Getnameinfo() failed: %s.s\n", gai_strerror(s));
exit(1);
}
if (host[0] == '1' && host[1] == '2' && host[2] == '7')
continue;
// napln konkretni rozhrani
memset(interfaces[*interfaces_count].mask, '\0', 16);
memset(interfaces[*interfaces_count].name, '\0', 10);
memset(interfaces[*interfaces_count].ip, '\0', 16);
strcpy(interfaces[*interfaces_count].mask, mask);
strcpy(interfaces[*interfaces_count].ip, host);
strcpy(interfaces[*interfaces_count].name, ifa->ifa_name);
interfaces[*interfaces_count].usable = false;
(*interfaces_count)++;
}
}
freeifaddrs(ifaddr);
return interfaces;
}
/*********************************************************************************************
*
* vygeneruj decoy pro jedno konkretni rozhrani
* pocet dalsich pripadnych pouzitych rozhrani osetri post. nahrazovanim v **addresses z funkce main()
*
*********************************************************************************************/
void generate_decoy_ips(struct single_interface interface, int *passed_interfaces, struct single_address *addresses, int *decoy_count, char *target, struct sockaddr_in *target_struct)
{ // https://stackoverflow.com/questions/44295654/print-all-ips-based-on-ip-and-mask-c
struct in_addr ipaddress, subnetmask;
inet_pton(AF_INET, interface.ip, &ipaddress);
inet_pton(AF_INET, interface.mask, &subnetmask);
unsigned long xxp_ip = ntohl(ipaddress.s_addr);
unsigned long first_ip = ntohl(ipaddress.s_addr & subnetmask.s_addr);
unsigned long last_ip = ntohl(ipaddress.s_addr | ~(subnetmask.s_addr));
char decoy[16]; // decoy adresa
// pro kazdou subadresu v siti spust decoy ping test
for (unsigned long ip = first_ip; ip <= last_ip; ++ip)
{
// skonci kdyz mas dost adres
if(*decoy_count == DECOYS)
break;
// obcas nejakou tu adresu zahod
if(rndmstr(0,1))
continue;
unsigned long theip = htonl(ip);
if (ip == first_ip || ip == last_ip || ip == xxp_ip) // sit ani broadcast nechces
continue;
inet_ntop(AF_INET, &theip, decoy, INET_ADDRSTRLEN);
decoy_ping_succ = false; // pokud je adresa pouzivana, vrati true
// argumenty pro decoy ping
struct ping_arguments *ping_arg = malloc(sizeof(struct ping_arguments));
ping_arg->target_struct = malloc(sizeof(struct sockaddr_in *));
if (ping_arg == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.");
exit(1);
}
ping_arg->ok = malloc(sizeof(bool *));
if (ping_arg->ok == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.");
exit(1);
}
if (ping_arg->target_struct == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.");
exit(1);
}
memset(ping_arg->target, '\0', 16);
memset(ping_arg->ifc, '\0', 10);
memset(ping_arg->ip, '\0', 16);
strcpy(ping_arg->target, decoy);
strcpy(ping_arg->ip, interface.ip);
strcpy(ping_arg->ifc, interface.name);
ping_arg->ok = &decoy_ping_succ;
// decoy target override
struct hostent *hname;
struct sockaddr_in decoy_target;
hname = gethostbyname(decoy);
memset(&decoy_target, '\0', sizeof(decoy_target));
decoy_target.sin_family = hname->h_addrtype;
decoy_target.sin_port = 0;
decoy_target.sin_addr.s_addr = *(long *)hname->h_addr_list[0];
ping_arg->target_struct = &decoy_target;
ping(ping_arg);
if (decoy_ping_succ) { // pingovana adresa je pouzivana, pokracuj
decoy_ping_succ = false;
}
else
{
memset(addresses[*decoy_count].ip, '\0', 16);
strcpy(addresses[*decoy_count].ip, decoy);
addresses[*decoy_count].cider = cidr(interface.mask);
memset(addresses[*decoy_count].ifc, '\0', 10);
strcpy(addresses[*decoy_count].ifc, interface.name);
printf("* %s decoy ip %s\n",addresses[*decoy_count].ifc,addresses[*decoy_count].ip);
(*decoy_count)++; // globalni iterator decoy adres
}
}
}
/*********************************************************************************************
*
* prevod masky site na cidr
* https://stackoverflow.com/questions/6657475/netmask-conversion-to-cidr-format-in-c
*
*********************************************************************************************/
unsigned short cidr(char* ipAddress)
{
unsigned short netmask_cidr;
int ipbytes[4];
netmask_cidr=0;
sscanf(ipAddress, "%d.%d.%d.%d", &ipbytes[0], &ipbytes[1], &ipbytes[2], &ipbytes[3]);
for (int i=0; i<4; i++)
{
switch(ipbytes[i])
{
case 0x80:
netmask_cidr+=1;
break;
case 0xC0:
netmask_cidr+=2;
break;
case 0xE0:
netmask_cidr+=3;
break;
case 0xF0:
netmask_cidr+=4;
break;
case 0xF8:
netmask_cidr+=5;
break;
case 0xFC:
netmask_cidr+=6;
break;
case 0xFE:
netmask_cidr+=7;
break;
case 0xFF:
netmask_cidr+=8;
break;
default:
return netmask_cidr;
break;
}
}
return netmask_cidr;
}
/*********************************************************************************************
*
* vyber random port
*
*********************************************************************************************/
int rndm(int lower, int upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
/*********************************************************************************************
*
* vyber cekaci cas v microsec
*
*********************************************************************************************/
unsigned long rndmsleep(unsigned long lower, unsigned long upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
/*********************************************************************************************
*
* vyber nahodnou delku retezce
*
*********************************************************************************************/
unsigned short rndmstr(unsigned short lower, unsigned short upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
/*********************************************************************************************
*
* rizeni celeho jednoho interface
*
*********************************************************************************************/
void *xxp_looper(void *arg)
{
pthread_t xxp_sniff;
pthread_t xxp_hand;
struct xxp_arguments *args = (struct xxp_arguments *)arg;
int local_counter = 0; // lokalni counter portu v listu
// zda je globalni seznam prazdny - zapne to handler, zacne konec xxp
bool xxp_killer = false;
// zapne to interface, zacne konec snifferu
bool komm_susser_todd = false;
// vytvor argumenty interface snifferu
struct xxp_sniffer_arguments *xxp_sniff_arg = malloc(sizeof(struct xxp_sniffer_arguments));
if (xxp_sniff_arg == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
xxp_sniff_arg->end_of_evangelion = malloc(sizeof(bool *));
if (xxp_sniff_arg->end_of_evangelion == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
memset(xxp_sniff_arg->ifc, '\0', 10);
strcpy(xxp_sniff_arg->ifc, args->ifc);
memset(xxp_sniff_arg->target, '\0', 16);
strcpy(xxp_sniff_arg->target, args->target_address);
xxp_sniff_arg->end_of_evangelion = &komm_susser_todd;
xxp_sniff_arg->min_port = args->min_port;
xxp_sniff_arg->port_count = args->port_count;
// tohle je kvuli posledni adrese, pouziva se jen na udp. Pokud je jen jedna adresa udp se provede az po ukonceni tcp..
xxp_sniff_arg->decoy_count = args->decoy_count;
// vytvor argumenty interface handleru
struct xxp_handler_arguments *xxp_handler_arg = malloc(sizeof(struct xxp_handler_arguments));
if (xxp_handler_arg == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
xxp_handler_arg->xxp_killer = malloc(sizeof(bool *));
if (xxp_handler_arg->xxp_killer == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
xxp_handler_arg->xxp_killer = &xxp_killer;
xxp_handler_arg->port_count = args->port_count;
xxp_handler_arg->local_counter = &local_counter;
// vytvor port sniffer a nahraj do nej argumenty
if (pthread_create(&xxp_sniff, NULL, xxp_sniffer, (void *)xxp_sniff_arg))
{
fprintf(stderr, "Chyba pri vytvareni vlakna.\n");
exit(1);
}
// vytvor port handler a nahraj do nej argumenty
if (pthread_create(&xxp_hand, NULL, xxp_handler, (void *)xxp_handler_arg))
{
fprintf(stderr, "Chyba pri vytvareni vlakna.\n");
exit(1);
}
// vytvor vlakna z decoy domen, pocet domen v interface
pthread_t domain[args->decoy_count];
void *retval[args->decoy_count];
int c = 0; // vnitrni pocitadlo generatoru vlaken
for (int i = 0; i < args->decoy_count; i++)
{
struct domain_arguments *domain_arg = malloc(sizeof(struct domain_arguments));
domain_arg->end_of_evangelion = malloc(sizeof(bool *));
if (domain_arg->end_of_evangelion == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
domain_arg->local_counter = malloc(sizeof(int *));
if (domain_arg == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
if (domain_arg->local_counter == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
domain_arg->local_counter = &local_counter;
domain_arg->min_port = args->min_port;
domain_arg->client = args->client;
memset(domain_arg->target_address, '\0', 16);
strcpy(domain_arg->target_address, args->target_address);
memset(domain_arg->ip, '\0', 16);
strcpy(domain_arg->ip, addresses[i].ip);
domain_arg->end_of_evangelion = &komm_susser_todd;
domain_arg->port_count = args->port_count;
memset(domain_arg->ifc, '\0', 10);
strcpy(domain_arg->ifc, args->ifc);
pthread_create(&domain[c++], NULL, domain_loop, (void *)domain_arg);
}
// smycka rozhrani ceka na local_list_empty of handleru
// ifc se vypne kdyz je lokalni seznam i globalni seznam prazdny
// muzeme jen doufat ze se nevypnou uplne vsechny zaraz i kdyz nekde neco bude
while (true)
{
sleep(5);
if (xxp_killer && queue_isEmpty(global_queue_tcp->count))
{
break;
}
}
komm_susser_todd = true; // ukonci sniffer
// pockej na zbytek deti
for (int i = 0; i < args->decoy_count; i++)
pthread_join(domain[i], &retval[i]);
// pockej na port sniffer
pthread_join(xxp_sniff, NULL);
free(xxp_sniff_arg);
free(xxp_handler_arg);
return NULL;
}
/*********************************************************************************************
*
* obo looper pro odesilani udp po jednom portu
*
*********************************************************************************************/
void *obo_looper(void *arg)
{
pthread_t obo_sniff;
struct xxp_arguments *args = (struct xxp_arguments *)arg;
// zapne to interface, zacne konec snifferu
bool komm_susser_todd = false;
// zda byla obdrzena odpoved na udp datagram ve snifferu
bool response_received;
// vytvor argumenty interface snifferu
struct obo_sniffer_arguments *obo_sniff_arg = malloc(sizeof(struct obo_sniffer_arguments));
if (obo_sniff_arg == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
obo_sniff_arg->end_of_evangelion = malloc(sizeof(bool *));
if (obo_sniff_arg->end_of_evangelion == NULL)
{
fprintf(stderr, "Chyba pri alokaci pameti.\n");
exit(1);
}
memset(obo_sniff_arg->ifc, '\0', 10);
strcpy(obo_sniff_arg->ifc, args->ifc);
memset(obo_sniff_arg->target, '\0', 16);
strcpy(obo_sniff_arg->target, args->target_address);
obo_sniff_arg->end_of_evangelion = &komm_susser_todd;
obo_sniff_arg->decoy_count = args->decoy_count;
obo_sniff_arg->response_received = &response_received;
// vytvor port sniffer a nahraj do nej argumenty
if (pthread_create(&obo_sniff, NULL, obo_sniffer, (void *)obo_sniff_arg))
{
fprintf(stderr, "Chyba pri vytvareni vlakna.\n");
exit(1);
}
// odesli na vsechny porty postupne udp datagram a cekej na odpoved od callbacku jeslti to doslo
for(int i = 0; i < args->port_count; i++) {
response_received = false;
for(int j = 0; j < 2; j++) {
send_udp(rndm(PORT_RANGE_START, PORT_RANGE_END), pu_arr[i].port, addresses[args->decoy_count-1].ip, args->target_address, args->client);
usleep(rndmsleep(UDPMINWAIT,UDPMAXWAIT));
if(response_received) {
printf("UDP\t%i\tCLOSED\n",pu_arr[i].port);
break;
}
}
if(!response_received) {
printf("UDP\t%i\tOPEN|FILTERED\n",pu_arr[i].port);
}
}
komm_susser_todd = true; // ukonci sniffer
// pockej na port sniffer
pthread_join(obo_sniff, NULL);
free(obo_sniff_arg);
return NULL;
}
/*********************************************************************************************
*
* interface handler
*
*********************************************************************************************/
void *xxp_handler(void *arg)
{
// rozbal argumenty
struct xxp_handler_arguments *args = (struct xxp_handler_arguments *)arg;
// 1. varovani, pockej dalsich pet sekund..
bool semi_empty = false;
// casova znamka jednoho prubehu handleru
struct timeval timestamp;
// dokud v lokalnim listu neco je
while (true)
{
sleep(SLEEP_TIME);
if (semi_empty)
{
if (*args->local_counter == 0)
break;
else
semi_empty = false;
}
if (*args->local_counter == 0)
{
semi_empty = true;
continue;
}
// tady zacina standartni prochazeni seznamu
gettimeofday(×tamp, NULL);
for (int i = 0; i < args->port_count; i++)
{
if (global_list_tcp[i].port != 0 && ((timestamp.tv_sec - global_list_tcp[i].time.tv_sec) >= SLEEP_TIME))
{
if (global_list_tcp[i].passed)
{ // aktivni port | zavreny port
if (global_list_tcp[i].rst > 0)
{ // dejme tomu ze je port zavreny, a server se nas nesnazi obejit poslanim RST
printf("TCP\t%i\tCLOSED\n", global_list_tcp[i].port);
global_list_tcp[i].port = 0;
(*args->local_counter)--;
}
else {
printf("TCP\t%i\tOPEN\n", global_list_tcp[i].port);
global_list_tcp[i].port = 0;
(*args->local_counter)--;
}
}
else
{ // neaktivni port
if (global_list_tcp[i].count < 2)
{ // posli ho zpet do fronty
(global_list_tcp[i].count)++;
queue_insert(global_list_tcp[i], &(global_queue_tcp->rear), args->port_count, global_queue_tcp->q, &(global_queue_tcp->count));
global_list_tcp[i].port = 0;
(*args->local_counter)--;
}
else
{
// pri nejakem pokusu napriklad nevratil nic
printf("TCP\t%i\tFILTERED\n", global_list_tcp[i].port);
global_list_tcp[i].port = 0;
(*args->local_counter)--;
}
}
}
}
}
(*args->xxp_killer) = true; // timhle rikas interface aby vypnulo sniffer
return NULL;
}
/*********************************************************************************************
*
* konkretni domena na rozhrani
*
*********************************************************************************************/
void *domain_loop(void *arg)
{
time_t s;
srand(time(&s));
struct timeval timestamp;
int spoofed_port;
// rozbal argumenty
struct domain_arguments *args = (struct domain_arguments *)arg;
// mel by to vypnout handler
while (!(*args->end_of_evangelion))
{
// spoofed port ze kteryho odesles SYN
spoofed_port = rndm(PORT_RANGE_START, PORT_RANGE_END);
// z fronty vezmi port
if (!queue_isEmpty(global_queue_tcp->count))
{
if(MACSPOOF) {
// zmen mac adresu. pojede pouze na ethernetech, na wlan se musi rozhrani vypnout nejprve!
int i = rndmstr(1,3);
if(i == 2)
change_mac(args->ifc);
}
struct port worked_port = queue_removeData(global_queue_tcp->q, &(global_queue_tcp->front), args->port_count, &(global_queue_tcp->count));
// v pripade ze zpracovavam nesouvisly seznam portu: 60, 75, 87 atd..
if(worked_port.port != 0) {
// zpracovany port dej do local listu
global_list_tcp[worked_port.port - args->min_port].count = worked_port.count;
global_list_tcp[worked_port.port - args->min_port].port = worked_port.port;
global_list_tcp[worked_port.port - args->min_port].passed = worked_port.passed;
gettimeofday(×tamp, NULL);
global_list_tcp[worked_port.port - args->min_port].time.tv_sec = timestamp.tv_sec;
// zvys citatc lokalniho seznamu
(*args->local_counter)++;
// odesli na port
send_syn(spoofed_port, worked_port.port, args->ip, args->target_address, args->client);
usleep(rndmsleep(MIN_WAITING, MAX_WAITING));
}
}
}
free(args);
return NULL;
}
/*********************************************************************************************
*
* randomizuj pole portu
*
*********************************************************************************************/
void randomize(struct port *array, int n)
{
if (n > 1)
{
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
struct port t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
/*********************************************************************************************
*
* zkontroluj argumenty programu
*
*********************************************************************************************/
int checkArg(char *argument, int len)
{
int range = 0; // -
int col = 0; // ,
for (int i = 0; i < len; i++)
{
if (isdigit(argument[i]))
{
continue;
}
else if (argument[i] == '-')
{
range++;
}
else if (argument[i] == ',') {
col++;
}
else
return 0;
}
if (range > 1 || !isdigit(argument[len - 1]) || (range > 0 && col > 0))
{
return 0;
}
if (range == 1)
{
return 1; // je tam jedna pomlcka
}
else if (col >= 1) {
return 2; // jsou tam carky
}
else
return 3; // jsou tam jen cisla
}
/*********************************************************************************************
*
* parsovani argumentu programu
*
*********************************************************************************************/
int getCharCount(char *str, char z, int len)
{
int c = 0;
for (int i = 0; i < len; i++)
{
if (str[i] == z) {
c++;
}
}
return c;
}
/*********************************************************************************************
*
* funkce ke globalni fronte portu
*
*********************************************************************************************/
bool queue_isEmpty(int count)
{
return count == 0;
}
bool queue_isFull(int count, int max)
{ // prebytecne, k preplneni nedojde
return count == max;
}
int queue_size(int count)
{ // dat mutex
pthread_mutex_lock(&mutex_queue_size);
return count;
pthread_mutex_unlock(&mutex_queue_size);
}
void queue_insert(struct port data, int *rear, int max, struct port *q, int *count)
{
pthread_mutex_lock(&mutex_queue_insert);
if (!queue_isFull(*count, max))
{
if (*rear == max - 1)
{
*rear = -1;
}
q[++(*rear)] = data;
(*count)++;
}
pthread_mutex_unlock(&mutex_queue_insert);
}
struct port queue_removeData(struct port *q, int *front, int max, int *count)
{ // dat mutex
pthread_mutex_lock(&mutex_queue_remove);
struct port data = q[(*front)++];
if (*front == max)
{
*front = 0;
}
(*count)--;
pthread_mutex_unlock(&mutex_queue_remove);
return data;
}
/*********************************************************************************************
*
* funkce ke zprocesovani argumentu pt a pu
*
*********************************************************************************************/
void processArgument(int ret_px, struct port **px_arr, int *px_arr_size, char *px)
{
// pocet clenu portu
int size = 0;
if (ret_px == 1)
{ // hledas -
struct port *px_arr_subst = malloc(sizeof(struct port) * 2);
if (px_arr_subst == NULL)
{
fprintf(stderr, "Chyba pri alokaci.\n");
exit(1);
}
int i = 0;
char *end;
char *p = strtok(px, "-");
while (p)
{
px_arr_subst[i].port = (int)strtol(p, &end, 10);
p = strtok(NULL, "-");
i++;
}
size = px_arr_subst[1].port - px_arr_subst[0].port + 1;
*px_arr_size = size;
*px_arr = malloc(sizeof(struct port) * size);
if (*px_arr == NULL)
{
fprintf(stderr, "Chyba pri alokaci.\n");
exit(1);
}
for (int j = 0; j < *px_arr_size; j++)
{
px_arr[j]->port = px_arr_subst[0].port + j;
px_arr[j]->count = 0;
px_arr[j]->passed = false;
}
//free(px_arr_subst);
}
else if (ret_px == 2)
{ // hledas ,
int l = getCharCount(px, ',',strlen(px));
*px_arr = malloc(sizeof(struct port) * (l + 1));
size = l + 1;
if (px_arr == NULL)
{
fprintf(stderr, "Chyba pri alokaci.\n");
exit(1);
}
int i = 0;
char *end;
char *p = strtok(px, ",");
while (p)
{
px_arr[i]->port = (int)strtol(p, &end, 10);
px_arr[i]->count = 0;
px_arr[i]->passed = false;
px_arr[i]->rst = 0;
p = strtok(NULL, ",");
i++;
}
*px_arr_size = size;
}
else
{ // vkladas cely cislo do pole
*px_arr = malloc(sizeof(struct port));
char *end;
if (px_arr == NULL)
{
fprintf(stderr, "Chyba pri alokaci.\n");
exit(1);
}
px_arr[0]->port = (int)strtol(px, &end, 10);
px_arr[0]->count = 0;
px_arr[0]->passed = false;
size = 1;
*px_arr_size = 1;
}
for (int i = 0; i < size; i++)
{
if (px_arr[i]->port > 65535 || px_arr[i]->port < 0)
{
fprintf(stderr, "Spatny rozsah cisla portu (0 - 65535).\n");
exit(1);
}
}
}
/*********************************************************************************************
*
* funkce ke zprocesovani argumentu pt a pu
* //https://gist.github.com/jirihnidek/bf7a2363e480491da72301b228b35d5d
*
*********************************************************************************************/
char *host_to_ip(const char *host) {
struct addrinfo hint, *res;
char *ip = malloc(sizeof(char) * 16);
if(ip == NULL) {
fprintf(stderr,"Chyba pri alokaci pameti.\n");
exit(1);
}
void *ptr;
memset (&hint, 0, sizeof (hint));
hint.ai_family = PF_UNSPEC;
hint.ai_socktype = SOCK_STREAM;
hint.ai_flags |= AI_CANONNAME;
if (getaddrinfo(host, NULL, &hint, &res) != 0) {
fprintf(stderr,"Host neexistuje nebo nelze prevest adresu.\n");
exit(1);
}
switch (res->ai_family) {
case AF_INET:
ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
break;
case AF_INET6:
printf("IPV6 nepodporujeme.\n");
exit(1);
}
inet_ntop (res->ai_family, ptr, ip, 100);
return ip;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "sort.h"
/**
* siftDown - uses heap sort algorithm to sort int array
* @array: array to be sorted
* @start: start of array
* @end: end of array
* @size: size of array
* Return: Nothing
*/
void siftDown(int *array, int start, int end, size_t size)
{
int root = start, child, swap_hold, val_hold;
while (2 * root <= end)
{
child = 2 * root;
swap_hold = root;
if (array[swap_hold] < array[child])
swap_hold = child;
if (child + 1 <= end && array[swap_hold] < array[child + 1])
swap_hold = child + 1;
if (swap_hold == root)
return;
val_hold = array[root];
array[root] = array[swap_hold];
array[swap_hold] = val_hold;
root = swap_hold;
print_array(array, size);
}
}
/**
* heapify - constructs heap
* @array: array to be sorted
* @size: size of array
* Return: Nothing
*/
void heapify(int *array, size_t size)
{
int start = (size - 1) / 2;
while (start >= 0)
{
siftDown(array, start, size - 1, size);
start -= 1;
}
}
/**
* heap_sort - uses heap sort algorithm to sort int array
* @array: array to be sorted
* @size: size of array
* Return: Nothing
*/
void heap_sort(int *array, size_t size)
{
int end = size - 1;
int hold;
heapify(array, size);
while (end > 0)
{
if (array[0] != array[end])
{
hold = array[end];
array[end] = array[0];
array[0] = hold;
print_array(array, size);
}
end -= 1;
siftDown(array, 0, end, size);
}
}
|
C
|
#include <stdio.h>
#define MAX_N 10
//begin是待排列元素位置,当begin达到数组的最大下标时,一个排列结果就出来了。
//data是数组中所有元素,n是数组大小
void Permutation(int n, int data[], int begin)
{
int i, t;
//begin达到数组最大下标,打印一个排列结果
if(begin==n-1)
{
for(i=0; i<n; ++i)
{
if(i!=0)
printf(" ");
printf("%d", data[i]);
}
printf("\n");
return;
}
//把每一个数字挑出来放在最左边,递归调用结束后再还原回原来位置
for(i=begin; i<n; ++i)
{
//贪心:将当前data[i]交换到最前面的data[begin]
t = data[begin];
data[begin] = data[i];
data[i] = t;
//递归排列下一个元素,待排列位置是begin+1
Permutation(n, data, begin+1);
//回溯:将data[i]和data[begin]再交换回来
t = data[begin];
data[begin] = data[i];
data[i] = t;
}
}
//为了保持字典序,通过右移的方式递归排列
void Permutation2(int n, int data[], int begin)
{
int i, j, t;
//begin达到数组最大下标,打印一个排列结果
if(begin==n-1)
{
for(i=0; i<n; ++i)
printf("%d", data[i]);
printf("\n");
return;
}
//把每一个数字挑出来放在最左边,递归调用结束后再还原回原来位置
for(i=begin; i<n; ++i)
{
//贪心:将当前data[i]交换到最前面的data[begin], [begin,i)之间的右移
t = data[i];
for(j=i; j>begin; --j)
data[j] = data[j-1];
data[begin] = t;
//递归排列下一个元素,待排列位置是begin+1
Permutation2(n, data, begin+1);
//回溯:将当前data[i]交换回最前面的data[begin], (begin,i]之间的左移
t = data[begin];
for(j=begin; j<i; ++j)
data[j] = data[j+1];
data[i] = t;
}
}
int main()
{
int n, data[MAX_N], i;
scanf("%d", &n);
for(i=0; i<n; ++i)
data[i] = i+1;
Permutation2(n, data, 0);
return 0;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main(void)
{
printf("Minutes: ");
int a = get_int();
printf("\nBottles: %i\n", (a * 192) / 16);
}
|
C
|
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>
int main(void)
{
string name =GetString();
int flag = 1;
for(int i =0, n = strlen(name); i<n ; i++)
{
int lower = name[i];
if(flag==1)
{
name[i] = (char)toupper(lower);
flag =0;
printf("%c", name[i]);
}
if(name[i]==' ')
{
flag =1;
}
}
printf("\n");
}
|
C
|
//
// 1008.c
// algorithm_2019
//
// Created by bomin jung on 2019. 1. 3..
// Copyright © 2019년 bomin jung. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[])
{
long double A,B;
/* A,B 입력받기 */
scanf("%Lf", &A);
scanf("%Lf", &B);
printf("%.9Lf\n", A/B);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct list//定义链表结构
{
int data;
struct list *next;
};
struct list *creat_list()//创建单个链表空间
{
return calloc(sizeof(struct list), 1);
}
void traverse(struct list *ls)//遍历链表
{
struct list *p = ls;
while (p)
{
printf("%d\n", p->data);
p = p->next;
}
}
int count_list(struct list *ls)//返回链表元素个数
{
struct list *p = ls;
int count = 0;
while (p)
{
count++;
p = p->next;
}
return count;
}
int main(void)
{
struct list *first = creat_list();
struct list *second = creat_list();
struct list *third = creat_list();
first->next = second;
second->next = third;
third->next = NULL;
first->data = 10;
second->data = 20;
third->data = 30;
printf("%d\n", count_list(first));
traverse(first);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* find_col_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mle-roy <mle-roy@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/03/09 20:02:21 by mle-roy #+# #+# */
/* Updated: 2014/03/09 20:04:36 by mle-roy ### ########.fr */
/* */
/* ************************************************************************** */
#include "puissance4.h"
static int is_play_line(t_map *s_map, int line, int col, int add)
{
if (can_i_play(s_map, line, col + 1))
return (col + 1);
else if (can_i_play(s_map, line, col - add))
return (col - add);
return (-1);
}
static int check_flag(int flag, char c)
{
if (c == P_TWO)
return (flag + 1);
return (0);
}
int find_line(t_map *s_map, int nb)
{
int i;
int j;
int flag;
int play;
i = 0;
flag = 0;
play = -1;
while (i < s_map->line)
{
j = 0;
while (j < s_map->col)
{
flag = check_flag(flag, s_map->map[i][j]);
if (flag == nb)
{
if ((play = is_play_line(s_map, i, j, nb)) > -1)
return (play);
}
j++;
}
i++;
}
return (play);
}
static int is_play_col(t_map *s_map, int line, int col, int add)
{
if ((line - add) >= 0 && s_map->map[line - add][col] == EMPTY
&& s_map->map[line - (add - 1)][col] != EMPTY)
return (col);
return (-1);
}
int find_col(t_map *s_map, int nb)
{
int i;
int j;
int flag;
int play;
j = 0;
flag = 0;
play = -1;
while (j < s_map->col)
{
i = 0;
while (i < s_map->line)
{
flag = check_flag(flag, s_map->map[i][j]);
if (flag == nb)
{
if ((play = is_play_col(s_map, i, j, nb)) > -1)
return (play);
}
i++;
}
j++;
}
return (play);
}
|
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 */
/* Variables and functions */
int /*<<< orphan*/ _IONBF ;
char* __progname ;
int /*<<< orphan*/ data_dir ;
int /*<<< orphan*/ exit (int) ;
int /*<<< orphan*/ fprintf (int /*<<< orphan*/ ,char*,...) ;
int getopt (int,char**,char*) ;
int /*<<< orphan*/ optarg ;
int /*<<< orphan*/ printf (char*,...) ;
int quiet_mode ;
int /*<<< orphan*/ setvbuf (int /*<<< orphan*/ ,int /*<<< orphan*/ *,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ stderr ;
int /*<<< orphan*/ stdout ;
char* strdup (char*) ;
char* strrchr (char*,char) ;
int test_number ;
int /*<<< orphan*/ tests () ;
int verbose_mode ;
int
main(int argc, char **argv)
{
int ch;
/* Handle systems without __progname */
if (__progname == NULL) {
__progname = strrchr(argv[0], '/');
if (__progname == NULL || __progname[1] == '\0')
__progname = argv[0];
else
__progname++;
if ((__progname = strdup(__progname)) == NULL) {
fprintf(stderr, "strdup failed\n");
exit(1);
}
}
while ((ch = getopt(argc, argv, "vqd:")) != -1) {
switch (ch) {
case 'd':
data_dir = optarg;
break;
case 'q':
verbose_mode = 0;
quiet_mode = 1;
break;
case 'v':
verbose_mode = 1;
quiet_mode = 0;
break;
default:
fprintf(stderr, "Unrecognised command line option\n");
fprintf(stderr, "Usage: %s [-v]\n", __progname);
exit(1);
}
}
setvbuf(stdout, NULL, _IONBF, 0);
if (!quiet_mode)
printf("%s: ", __progname);
if (verbose_mode)
printf("\n");
tests();
if (!quiet_mode)
printf(" %u tests ok\n", test_number);
return 0;
}
|
C
|
//
// CS210 Fall 2015
// Cache Lab Primer
//
// The intention of this primer is to bootstrap the cachelab by
// providing the initial ability to 1) parse the command line arguments, and
// 2) read in the tracefile line-by-line.
#include <stdio.h> // printf, fgets, gputs
#include <stdlib.h> // atoi
#include <string.h> // strcmp
#include <math.h> // pow
#include "cachelab.h"
FILE *f; // input file descriptor
int main(int argc, char *argv[])
{
// Command line arguments are retrieved through the argv[] array. Each
// entry contains a pointer to a string that contains an argument.
//
// The first entry in argv points to the program name:
// *argv[0] = program name
// *argv[1] = first argument
// *argv[2] = second argument
// *argv[n] = nth argument
//
printf( "executable: %s \n", argv[0] );
//
// Example for the following line:
// ./csim-ref -s 4 -E 1 -b 4 -t mufile.log
// *argv[0] = "csim-ref"
// *argv[1] = "-s"
// *argv[2] = "4"
// *argv[3] = "-E"
// *argv[4] = "1"
// *argv[5] = "-b"
// *argv[6] = "4"
// *argv[7] = "-t"
// *argv[8] = "mufile.log"
//
// The integer 'argc' contains a count of the entries of argv[]
printf("There are %d arguments\n", argc-1);
// The following code extracts the '-E', '-s', '-b' and '-t' values from the
// input arguments, and prints the corresponding cache properties to the
// screen.
//
// c-standard library helper functions:
// int strcmp(string1, string2); //compare two string
// int atoi(string); //convert string to integer
for(int i=0; i<argc; i++){
printf( ">%s\n", argv[i] );
if(strcmp(argv[i], "-E")==0){
if(atoi(argv[i+1]) > 0){
printf("Cache associativity: %d\n", atoi(argv[i+1]));
}
}else if(strcmp(argv[i], "-s")==0){
if(atoi(argv[i+1]) > 0){
printf("Cache set count: %d\n", (int)(pow(2.0,atoi(argv[i+1]))));
}
}else if(strcmp(argv[i], "-b")==0){
if(atoi(argv[i+1]) > 0){
printf("Cache block size: %d\n", (int)(pow(2.0,atoi(argv[i+1]))));
}
}else if(strcmp(argv[i], "-t")==0){
printf("Tracefile: %s\n", argv[i+1]);
// Here we open the trace file
f = fopen ( argv[i+1], "r" );
}
}
// Next I read through the trace file line-by-line, and print out each line
if(f != NULL){
char line [ 128 ]; /* read buffer */
while ( fgets ( line, sizeof line, f ) != NULL ) /* read a line from f */
{ fputs ( line, stdout ); /* print the line */ }
fclose ( f );
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
//varibles
int c, i, j;
int flag;
int fread_size;
unsigned char times_read;
unsigned char size_read;
unsigned char char_buf[257];
int int_buf[256];
double dbl_buf[256];
//init flag
flag = 0;
while ((c = getchar()) != EOF) {
switch (c) {
case 'n':
printf("\n");
flag = 0;
break;
case 's':
//read count
times_read = getchar();
//check space printing
if (flag > 0) { printf(" "); }
flag = 1;
//print
for (i = 0; i < (int)times_read + 1; i++) {
size_read = getchar();
fread_size = fread(char_buf, 1, (int)size_read + 1, stdin);
//error catch
if (fread_size != (int)size_read + 1) {
if ((int)size_read == 255) {
fprintf(stderr, "Input error: no string size\n");
exit(1);
}
fprintf(stderr, "Input error: not enough chars\n");
exit(1);
}
for (j = 0; j < (int)size_read + 1; j++) { printf("%c", char_buf[j]); }
if (i != (int)times_read) { printf(" "); }
}
break;
case 'i':
//read count and bytes
times_read = getchar();
fread_size = fread(int_buf, 4, (int)times_read + 1, stdin);
//error catch
if (fread_size != (int)times_read + 1) {
fprintf(stderr, "Input error: not enough ints\n");
exit(1);
}
//check space printing
if (flag > 0) { printf(" "); }
flag = 1;
//print
for (i = 0; i < (int)times_read + 1; i++) {
printf("%d", int_buf[i]);
if (i != (int)times_read) { printf(" "); }
}
break;
case 'd':
//read count and bytes
times_read = getchar();
fread_size = fread(dbl_buf, 8, (int)times_read + 1, stdin);
//error catch
if (fread_size != (int)times_read + 1) {
fprintf(stderr, "Input error: not enough doubles\n");
exit(1);
}
//check space printing
if (flag > 0) { printf(" "); }
flag = 1;
//print
for (i = 0; i < (int)times_read + 1; i++) {
printf("%.10lg", dbl_buf[i]);
if (i != (int)times_read) { printf(" "); }
}
break;
default:
fprintf(stderr, "Input error: bad type\n");
exit(1);
break;
}
}
exit(0);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <utils.h>
int countAndCoverSquares(Grid *g, int x, int y, int width, int height) {
int upperX = x + width;
if (g->width < upperX) {
expandWidth(g, upperX - g->width);
}
int upperY = y + height;
if (g->height < upperY) {
expandHeight(g, upperY - g->height);
}
int ret = 0;
for (int i=x; i<(x + width); i++) {
for (int j=y; j<(y + height); j++) {
if (g->grid[i][j] == (short) 1) ret++;
if (g->grid[i][j] < 2) g->grid[i][j]++;
}
}
return ret;
}
int main(int argc, char *argv[]) {
assert(argc == 2);
FILE *f;
f = fopen(argv[1], "r");
assert(f);
Grid *grid = newGrid();
int result = 0;
int id = 0, x = 0, y = 0, w = 0, h = 0;
while(fscanf(f, "#%d @ %d,%d: %dx%d\n", &id, &x, &y, &w, &h) != EOF) {
result += countAndCoverSquares(grid, x, y, w, h);
}
freeGrid(grid);
fclose(f);
printf("%d\n", result);
return 0;
}
|
C
|
/*
* g722_1 - a library for the G.722.1 and Annex C codecs
*
* bitstream.c
*
* Copyright (C) 2006 Steve Underwood
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
/*! \file */
#if defined(HAVE_CONFIG_H)
#include <config.h>
#endif
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "g722_1/g722_1.h"
#include "bitstream.h"
void g722_1_bitstream_put(g722_1_bitstream_state_t *s, uint8_t **c, uint32_t value, int bits)
{
if (bits < 32)
value &= ((1 << bits) - 1);
if (bits > 24)
{
/* We can't deal with this many bits in one go. Split up the operation */
bits -= 8;
s->bitstream = (s->bitstream << bits) | (value >> 8);
s->residue += bits;
while (s->residue >= 8)
{
s->residue -= 8;
*(*c)++ = (uint8_t) ((s->bitstream >> s->residue) & 0xFF);
}
bits = 8;
value &= 0xFF;
}
s->bitstream = (s->bitstream << bits) | value;
s->residue += bits;
while (s->residue >= 8)
{
s->residue -= 8;
*(*c)++ = (uint8_t) ((s->bitstream >> s->residue) & 0xFF);
}
}
/*- End of function --------------------------------------------------------*/
uint32_t g722_1_bitstream_get(g722_1_bitstream_state_t *s, const uint8_t **c, int bits)
{
uint32_t x;
if (bits > 24)
{
/* We can't deal with this many bits in one go. Split up the operation */
while (s->residue < 24)
{
s->bitstream = (s->bitstream << 8) | ((uint32_t) *(*c)++);
s->residue += 8;
}
s->residue -= 24;
bits -= 24;
x = ((s->bitstream >> s->residue) & 0xFFFFFF) << bits;
while (s->residue < bits)
{
s->bitstream = (s->bitstream << 8) | ((uint32_t) *(*c)++);
s->residue += 8;
}
s->residue -= bits;
x |= (s->bitstream >> s->residue) & ((1 << bits) - 1);
}
else
{
while (s->residue < bits)
{
s->bitstream = (s->bitstream << 8) | ((uint32_t) *(*c)++);
s->residue += 8;
}
s->residue -= bits;
x = (s->bitstream >> s->residue) & ((1 << bits) - 1);
}
return x;
}
/*- End of function --------------------------------------------------------*/
void g722_1_bitstream_flush(g722_1_bitstream_state_t *s, uint8_t **c)
{
if (s->residue > 0)
{
*(*c)++ = (uint8_t) ((s->bitstream << (8 - s->residue)) & 0xFF);
s->residue = 0;
}
}
/*- End of function --------------------------------------------------------*/
g722_1_bitstream_state_t *g722_1_bitstream_init(g722_1_bitstream_state_t *s)
{
if (s == NULL)
return NULL;
s->bitstream = 0;
s->residue = 0;
return s;
}
/*- End of function --------------------------------------------------------*/
/*- End of file ------------------------------------------------------------*/
|
C
|
typedef struct
{
int n;
rect* prev_rects;
rect* rects;
int* matrix; // matrix, linear, but 2d
int m;
schedule_data_t schedule;
tween_data_t tween;
bool player_dead;
} death_data_t;
death_data_t death_data;
color death_color = {0.9f, 0.5f, 0.7f};
void reset_killing()
{
death_data.n = 0;
memset(death_data.matrix, -1, death_data.m * sizeof(int));
}
const float killing_length = 3.0f;
void show_killing(const float t)
{
// reset_schedule(&death_data.schedule);
add_schedule(&death_data.schedule, t + killing_length, reset_killing);
death_data.tween.start_t = t;
death_data.tween.end_t = t + killing_length;
death_data.tween.start_v = 0.0f;
death_data.tween.end_v = 1.0f;
}
static const float death_tween_subpart = 0.25f;
void show_death(const float t)
{
death_data.tween.start_t = t;
death_data.tween.end_t = t + killing_length * death_tween_subpart;
death_data.tween.start_v = 0.0f;
death_data.tween.end_v = 1.0f * death_tween_subpart;
}
void reset_death()
{
reset_killing();
reset_schedule(&death_data.schedule);
death_data.player_dead = false;
}
void init_death()
{
death_data.m = map_data.m;
death_data.prev_rects = (rect*)malloc(death_data.m * sizeof(rect));
death_data.rects = (rect*)malloc(death_data.m * sizeof(rect));
death_data.matrix = (int*)malloc(death_data.m * sizeof(int));
death_data.tween.fn = lerp_tween;
reset_death();
}
void update_death(const float t)
{
update_tween(&death_data.tween, t);
execute_schedule(&death_data.schedule, t);
for (int i = 0; i < death_data.n; ++i) {
death_data.rects[i].a = death_data.tween.v;
}
}
void draw_death(const float frame_fraction)
{
add_rects(&death_bo, death_data.rects, death_data.prev_rects, death_data.n, frame_fraction);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include "types.h"
#include "util.h"
static void timer_event (int event_id, siginfo_t *event_info, void *unused)
{
timer_info_t *timer_info = event_info->si_value.sival_ptr;
timer_info->callback (timer_info);
if (!(timer_info->periodic))
{
timer_delete ((timer_t)(timer_info->handle));
free (timer_info);
}
}
int32 timer_start (int32 millisec, int32 event, int32 periodic,
void (*callback)(void *), timer_info_t **timer_info)
{
struct sigaction timer_action;
struct sigevent signal_event;
timer_t timer_id;
int status;
*timer_info = (timer_info_t *)malloc (sizeof (**timer_info));
/* Fill timer info */
(*timer_info)->millisec = millisec;
(*timer_info)->event = event;
(*timer_info)->periodic = periodic;
(*timer_info)->callback = callback;
/* Establish handler for timer signal */
timer_action.sa_flags = SA_SIGINFO;
timer_action.sa_sigaction = timer_event;
sigemptyset (&timer_action.sa_mask);
status = sigaction (SIGRTMIN, &timer_action, NULL);
if (status == 0)
{
/* Create the timer */
signal_event.sigev_notify = SIGEV_SIGNAL;
signal_event.sigev_signo = SIGRTMIN;
signal_event.sigev_value.sival_ptr = *timer_info;
status = timer_create (CLOCK_MONOTONIC, &signal_event, &timer_id);
if (status == 0)
{
struct itimerspec timer_spec;
(*timer_info)->handle = (void *)timer_id;
timer_spec.it_value.tv_sec = millisec / 1000;
timer_spec.it_value.tv_nsec = (millisec % 1000) * 1000000;
if ((*timer_info)->periodic)
{
timer_spec.it_interval.tv_sec = timer_spec.it_value.tv_sec;
timer_spec.it_interval.tv_nsec = timer_spec.it_value.tv_nsec;
}
else
{
timer_spec.it_interval.tv_sec = 0;
timer_spec.it_interval.tv_nsec = 0;
}
/* Start timer */
status = timer_settime (timer_id, 0, &timer_spec, NULL);
if (status != 0)
{
timer_delete (timer_id);
printf ("Unable to start timer\n");
}
}
else
{
printf ("Unable to create timer\n");
}
}
else
{
printf ("Unable to set timer expiry handler\n");
}
if (status != 0)
{
free (*timer_info);
}
return status;
}
int32 timer_status (timer_info_t *timer_info)
{
int current_count = -1;
struct itimerspec timer_spec;
if ((timer_gettime ((timer_t)(timer_info->handle), &timer_spec)) == 0)
{
current_count = timer_info->millisec
- ((timer_spec.it_value.tv_sec * 1000)
+ (timer_spec.it_value.tv_nsec / 1000000));
}
return current_count;
}
int32 timer_stop (timer_info_t *timer_info)
{
timer_t timer_id = (timer_t)(timer_info->handle);
free (timer_info);
return timer_delete (timer_id);
}
int32 clock_get_count (void)
{
int millisec = -1;
struct timespec current_time;
if ((clock_gettime (CLOCK_MONOTONIC, ¤t_time)) == 0)
{
millisec = (current_time.tv_sec * 1000)
+ (current_time.tv_nsec / 1000000);
}
return millisec;
}
int8 * clock_get_time (void)
{
char current_time[50];
time_t utc;
struct tm *utc_tm;
utc = time (NULL);
utc_tm = localtime (&utc);
strftime(current_time, 50, "%F %T", utc_tm);
return strdup (current_time);
}
#ifdef UTIL_TIMER_TEST
#include <unistd.h>
static int timer_expiry_count = 0;
void callback (void *timer_info)
{
timer_expiry_count++;
printf ("Timer expired %d\n", timer_expiry_count);
}
int main (void)
{
timer_info_t *timer_info = NULL;
int status;
status = timer_start (1000, 0, 1, callback, &timer_info);
while (timer_expiry_count < 10)
{
}
status = timer_stop (timer_info);
status = timer_start (3000, 0, 0, callback, &timer_info);
sleep (5);
status = timer_start (3000, 0, 0, callback, &timer_info);
sleep (2);
status = timer_stop (timer_info);
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "racional.h"
struct no{
int info;
struct no *prox;
};
Lista inicializar_lista(){
return NULL;
}
int lista_vazia(Lista lst){
if(lst == NULL)
return 1;
else
return 0;
}
int insere_final(Lista *lst, int elem){
Lista N = (Lista)malloc(sizeof(struct no));
if(N == NULL){
return 0;
}
N->info = elem;
if(*lst == NULL){
N->prox = N;
*lst = N;
return 1;
}
else{
N->prox = (*lst)->prox;
(*lst)->prox = N;
*lst = N;
return 1;
}
}
int remove_inicio(Lista *lst, int *elem){
if(lista_vazia(*lst) == 1)
return 0;
Lista aux = (*lst)->prox;
*elem = aux->info;
if((*lst)->prox == *lst)
*lst = NULL;
else
(*lst)->prox = aux->prox;
free(aux);
return 1;
}
int imprime_lista(Lista lst){
if(lista_vazia(lst) == 1){
printf("*LISTA VAZIA*");
return 0;
}
else{
Lista aux = lst->prox;
while(aux->prox != lst->prox){
printf("%d, ", aux->info);
aux = aux->prox;
}
printf("%d.\n", aux->info);
}
return 1;
}
int tamanho(Lista lst){
Lista aux = lst->prox;
int t = 1;
if(lista_vazia(lst) == 1){
printf("*LISTA VAZIA*");
}
else{
while(aux->prox != lst->prox){
aux = aux->prox;
t++;
}
printf("Tamanho: %d", t);
}
return 1;
}
|
C
|
#include "zdd_cudd.h"
static DdManager* manager =NULL;
BB_bdd
BB_false()
{
return NULL; // LAMb: what is false?
}
BB_bdd
BB_true()
{
BB_bdd bdd = Cudd_ReadZddOne(manager, 0);
Cudd_Ref(bdd);
return bdd;
}
BB_bdd
BB_not(BB_bdd bdd)
{
return BB_addref(Cudd_zddComplement(manager, bdd)); // transforms to bdd, inverts and converts back to zdd
}
static BB_bdd
zdd_xor(BB_bdd lhs, BB_bdd rhs)
{
BB_bdd ldiff = BB_addref(Cudd_zddDiff(manager, lhs, rhs));
BB_bdd rdiff = BB_addref(Cudd_zddDiff(manager, rhs, lhs));
BB_bdd bdd = BB_addref(Cudd_zddUnion(manager, ldiff, rdiff));
BB_delref(ldiff);
BB_delref(rdiff);
return bdd;
}
BB_bdd
BB_apply(BB_bdd lhs, BB_bdd rhs, BB_op_type op)
{
BB_bdd bdd;
switch(op)
{
case BB_AND:
bdd = Cudd_zddIntersect(manager, lhs, rhs);
BB_addref(bdd);
break;
case BB_OR:
bdd = Cudd_zddUnion(manager, lhs, rhs);
BB_addref(bdd);
break;
case BB_XOR:
bdd = zdd_xor(lhs, rhs);
break;
}
return bdd;
}
BB_bdd
BB_addref(BB_bdd bdd)
{
Cudd_Ref(bdd);
return bdd;
}
BB_bdd
BB_delref(BB_bdd bdd)
{
Cudd_RecursiveDerefZdd(manager, bdd);
return bdd;
}
void
BB_setvarnum(int vars)
{
for (int i=0; i < vars; i++) {
Cudd_zddIthVar(manager, i);
}
}
BB_bdd
BB_ithvar(int var)
{
return BB_addref(Cudd_zddIthVar(manager, var-1));
}
int
BB_satcount(BB_bdd bdd)
{
return 0; //LAMb
}
void
BB_print_dot(int n, BB_bdd bdd)
{
char file_name[256];
sprintf(file_name, "%d.dot", n);
FILE* file = fopen(file_name, "w");
Cudd_zddDumpDot(manager, 1, &bdd, NULL, NULL, file);
fflush(file);
fclose(file);
}
void
BB_save(BB_bdd bdd, char* name)
{
// FILE* file = fopen(name, "w");
// Cudd_DumpBlif(manager, 1, &bdd, NULL, NULL, NULL, file, 0);
// fclose(file);
}
void
BB_init(struct arg_t* args, int inputs, int outputs)
{
manager = Cudd_Init(0, 0, CUDD_UNIQUE_SLOTS, CUDD_CACHE_SLOTS, 0);
}
void
BB_done()
{
Cudd_Quit(manager);
}
|
C
|
/*1253 - Cifra de César - Victor*/
#include <stdio.h>
#include <string.h>
int main(void)
{
int n, i, j, k, tam;
char frase[51];
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%s", frase);
tam = strlen(frase);
scanf("%d", &k);
for (j = 0; j < tam; j++)
{
if (frase[j] - k < 65)
{
frase[j] = frase[j] - k + 26;
}
else
{
frase[j] = frase[j] - k;
}
}
printf("%s\n", frase);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <GL/glut.h>
#include "importar.h"
int habilita=0;
void CriaRegPoints (tRegPoints *SA_faces) {
*SA_faces = NULL;
}
void VaziaRegPoints (tRegPoints SA_faces,int *ret) {
if(SA_faces == NULL){
*ret=1;
}else{
*ret=0;
}
}
void TamanhoRegPoints (tRegPoints SA_faces,int *qtd) {
tRegPoints p = SA_faces;
int qtde = 0;
while(p != NULL){
p = p -> proximo;
qtde++;
}
*qtd = qtde;
}
void DestroiRegPoints (tRegPoints *SA_faces){
tRegPoints pfaces;
while (*SA_faces != NULL) {
pfaces = *SA_faces;
*SA_faces = (*SA_faces)->proximo;
free(pfaces);
} // while
*SA_faces = NULL;
}
void InsereRegPoints (tRegPoints *SA_faces,tTipoPoint tipo)
{
tRegPoints p, novo;
int n,parar=0;
// inserção em lista vazia
if (*SA_faces == NULL) {
novo = (tRegPoints)malloc(sizeof(tNoRegPoints));
if (novo == NULL){
printf("Erro\n");
parar=1; // erro: memória insuf.
}else{
novo -> ponto=tipo;
*SA_faces = novo;
novo->proximo=NULL;
parar=1;
}
}else{
// inserção após primeira posição em lista não vazia
p = *SA_faces;
while (p->proximo != NULL){
p = p -> proximo;
}
novo = (tRegPoints)malloc(sizeof(tNoRegPoints));
if (novo == NULL){
printf("Erro\n");
parar=1; // erro: memória insuficiente
}else{
novo -> ponto=tipo;
novo->proximo = p->proximo;
p -> proximo = novo;
}
}
parar=1;
} // fim da função insere
void elementoRegPoints (tRegPoints SA_faces,int pos,tTipoPoint *tipo)
{
tRegPoints p = SA_faces;
int n = 1,parar=0;
if ( SA_faces == NULL){
printf("Erro\n");
parar =1; //erro: lista vazia
}
while ((p != NULL) && (n < pos) && parar==0){
p = p -> proximo;
n++;
}
if ( p == NULL){
//printf("erro Ponto: posição inválida\n");
parar=1; //erro: posição inválida
}else{
*tipo = p -> ponto;
}
parar=1;
}
void CriaRegFaces (tRegFaces *SA_faces) {
*SA_faces = NULL;
}
void VaziaRegFaces (tRegFaces SA_faces,int *ret) {
if(SA_faces == NULL){
*ret =1;
}else{
*ret =0;
}
}
void TamanhoRegFaces (tRegFaces SA_faces,int *qtd) {
tRegFaces p = SA_faces;
int qtde = 0;
while(p != NULL){
p = p -> proximo;
qtde++;
}
*qtd = qtde;
}
void DestroiRegFaces (tRegFaces *SA_faces){
tRegFaces pfaces;
while (*SA_faces != NULL) {
pfaces = *SA_faces;
*SA_faces = (*SA_faces)->proximo;
free(pfaces);
} // while
*SA_faces = NULL;
}
void InsereRegFaces (tRegFaces *SA_faces,tTipo tipo,int qtd)
{
tRegFaces p, novo;
int n,parar=0;
// inserção em lista vazia
if (*SA_faces == NULL) {
novo = (tRegFaces )malloc(sizeof(tNoRegFaces));
if (novo == NULL){
printf("Erro\n");
parar=1; // erro: memória insuf.
}else{
novo -> face=tipo;
novo -> qtd = qtd;
*SA_faces = novo;
novo->proximo=NULL;
}
parar=1;
}else{
// inserção após primeira posição em lista não vazia
p = *SA_faces;
while (p->proximo != NULL){
p = p -> proximo;
}
novo = (tRegFaces)malloc(sizeof(tNoRegFaces));
if (novo == NULL){
printf("Erro\n");
parar=1; // erro: memória insuficiente
}else{
novo -> face=tipo;
novo -> qtd = qtd;
novo->proximo = p->proximo;
p -> proximo = novo;
}
parar=1;
}
} // fim da função insere
void elementoRegFaces (tRegFaces SA_faces,int pos,tTipo *tipo,int *qtd)
{
tRegFaces p = SA_faces;
int n = 1,parar=0;
if ( SA_faces == NULL) parar=1; //erro: lista vazia
while ((p != NULL) && (n < pos) && parar==0){
p = p -> proximo;
n++;
}
if ( p == NULL || parar==1){
printf("Erro Face posição inválida\n");
parar=1; //erro: posição inválida
}else{
*tipo = p -> face;
*qtd = p-> qtd;
}
parar=1;
}
void PegarCoordenadas3(FILE *file,char *mystring,tRegPoints *points){
float p1,p2,p3;
int i,d;
char *aux;
tTipoPoint tipo;
do{
fgets(mystring , 10000 , file);
aux = mystring;
while(*aux=='\t'||*aux==' '){
aux++;
}
if(memcmp(aux,"]",1)==0 ){ //|| memcmp(aux,"}",1)==0
break;
}
d=sscanf(aux,"%f %f %f",&tipo.x,&tipo.y,&tipo.z);
//printf("pontos: %f %f %f\n",tipo.x,tipo.y,tipo.z);
InsereRegPoints(points,tipo);
}while(1);
}
void PegarCoordIndex(FILE *file,char *mystring,tRegFaces *SA_faces){
int c1,c2,c3,c4,c5;
int i,d;
char *aux;
tTipo tipo;
do{
fgets(mystring , 10000 , file);
aux = mystring;
while(*aux=='\t'||*aux==' '){
aux++;
}
if(memcmp(aux,"]",1)==0){
break;
}
d=sscanf(aux,"%d %d %d %d %d",&tipo.point1,&tipo.point2,&tipo.point3,&tipo.point4,&tipo.point5);
/*if(habilita)
printf("SA_faces: %d %d %d %d %d d=%d \n",tipo.point1,tipo.point2,tipo.point3,tipo.point4,tipo.point5,d);*/
InsereRegFaces(SA_faces,tipo,d == 3? d : (d-1));
}while(1);
}
void importarBlenderWrl(char *nomeArq,tRegFaces *SA_faces,tRegPoints *points){
FILE *file;
int numero;
char mystring [10000],*aux;
CriaRegFaces(SA_faces);
CriaRegPoints(points);
file= fopen(nomeArq,"r");
if(!file){
printf("Arquivo nao aberto\n");
}
for(;;){
if(feof(file)){
break;
}
if(fgets(mystring , 10000 , file) == NULL){
break;
}
mystring[strlen(mystring)-1]='\0';
aux=mystring;
while(*aux=='\t' || *aux==' '){
aux++;
}
if(aux == NULL || *aux == '\0'){
continue;
}
if(memcmp(aux,"Coordinate",10)==0){
//numero=atoi(aux+10);
}
if(memcmp(aux,"point",5)==0){
PegarCoordenadas3(file,mystring,points);
}
//printf("face: %s\n",aux);
if(memcmp(aux,"coordIndex",10)==0){
PegarCoordIndex(file,mystring,SA_faces);
}
}
Imprimir(*SA_faces,*points);
}
void Imprimir(tRegFaces SA_faces,tRegPoints points){
int i,qtd_f,qtd;
tTipoPoint tipo2;
Point3D p1,p2,p3;
tTipo tipo;
Point3D n;
TamanhoRegFaces(SA_faces,&qtd_f);
//glBegin(GL_LINES);
for(i=0;i<qtd_f;i++){
elementoRegFaces (SA_faces,i+1,&tipo,&qtd);
switch (qtd){
case 4:
glBegin(GL_QUADS);
//normal ponto 1
/* elementoRegPoints (points,tipo.point1+1,&tipo2);
p1.x= tipo2.x;
p1.y = tipo2.y;
p1.z = tipo2.z;
elementoRegPoints (points,tipo.point2+1,&tipo2);
p2.x= tipo2.x;
p2.y = tipo2.y;
p2.z = tipo2.z;
elementoRegPoints (points,tipo.point3+1,&tipo2);
p3.x= tipo2.x;
p3.y = tipo2.y;
p3.z = tipo2.z;
NormalTriangulo(p1, p2, p3, &n);*/
elementoRegPoints (points,tipo.point1+1,&tipo2);
p1.x =tipo2.x;
p1.y = tipo2.y;
p1.z = tipo2.z;
elementoRegPoints (points,tipo.point2+1,&tipo2);
p2.x =tipo2.x;
p2.y = tipo2.y;
p2.z = tipo2.z;
elementoRegPoints (points,tipo.point3+1,&tipo2);
p3.x =tipo2.x;
p3.y = tipo2.y;
p3.z = tipo2.z;
NormalTriangulo(p1, p2, p3, &n);
glBegin(GL_QUADS);
glNormal3f(n.x, n.y, n.z);
//printf("ponto 1\n");
elementoRegPoints (points,tipo.point1+1,&tipo2);
glVertex3d(tipo2.x,tipo2.y,tipo2.z);
// printf("ponto 2\n");
elementoRegPoints (points,tipo.point2+1,&tipo2);
glVertex3d(tipo2.x,tipo2.y,tipo2.z);
//printf("ponto 3\n");
elementoRegPoints (points,tipo.point3+1,&tipo2);
glVertex3d(tipo2.x,tipo2.y,tipo2.z);
//printf("ponto 4\n");
elementoRegPoints (points,tipo.point4+1,&tipo2);
glVertex3d(tipo2.x,tipo2.y,tipo2.z);
glEnd();
break;
case 3:
elementoRegPoints (points,tipo.point1+1,&tipo2);
p1.x =tipo2.x;
p1.y = tipo2.y;
p1.z = tipo2.z;
elementoRegPoints (points,tipo.point2+1,&tipo2);
p2.x =tipo2.x;
p2.y = tipo2.y;
p2.z = tipo2.z;
elementoRegPoints (points,tipo.point3+1,&tipo2);
p3.x =tipo2.x;
p3.y = tipo2.y;
p3.z = tipo2.z;
NormalTriangulo(p1, p2, p3, &n);
glBegin(GL_TRIANGLES);
glNormal3f(n.x, n.y, n.z);
//printf("ponto 1\n");
elementoRegPoints (points,tipo.point1+1,&tipo2);
glVertex3d(tipo2.x,tipo2.y,tipo2.z);
//printf("ponto 2\n");
elementoRegPoints (points,tipo.point2+1,&tipo2);
glVertex3d(tipo2.x,tipo2.y,tipo2.z);
//printf("ponto 3\n");
elementoRegPoints (points,tipo.point3+1,&tipo2);
glVertex3d(tipo2.x,tipo2.y,tipo2.z);
glEnd();
break;
}
}//for
//glEnd();
}
void NormalTriangulo(Point3D p1, Point3D p2, Point3D p3, Point3D *n){
Point3D v1, v2;
double len;
/* Encontra vetor v1 */
v1.x = p2.x - p1.x;
v1.y = p2.y - p1.y;
v1.z = p2.z - p1.z;
/* Encontra vetor v2 */
v2.x = p3.x - p1.x;
v2.y = p3.y - p1.y;
v2.z = p3.z - p1.z;
/* Calculo do produto vetorial de v1 e v2 */
n->x = (v1.y * v2.z) - (v1.z * v2.y);
n->y = (v1.z * v2.x) - (v1.x * v2.z);
n->z = (v1.x * v2.y) - (v1.y * v2.x);
/* normalizacao de n */
len = sqrt(n->x*n->x + n->y*n->y + n->z*n->z);
n->x /= len;
n->y /= len;
n->z /= len;
}
int InitEsferas(tEsfera *esfera){
int i=0,num_esfera=0;
//printf("inicializando linha 1\n");
//Esferas devastadoras linha 1
if(QTD_LINHAS >= 4){
for(i=0;i<QTD_LINHA_ESFERA;i++,num_esfera++){
esfera[num_esfera].x = LINHA_CIMA_ESFERA-((DIST_X_ESFERA*i)+1);
esfera[num_esfera].y = LINHA_CIMA_ESFERA;
esfera[num_esfera].z = 0;
esfera[num_esfera].status = DISPONIVEL;
}
}
//printf("inicializando linha 2\n");
//Esferas devastadoras linha 2
if(QTD_LINHAS >= 3){
for(i=0;i<QTD_LINHA_ESFERA;i++,num_esfera++){
esfera[num_esfera].x = LINHA_CIMA_ESFERA-((DIST_X_ESFERA*i)+1);
esfera[num_esfera].y = LINHA_CIMA_ESFERA-(DIST_Y_ESFERA);
esfera[num_esfera].z = 0;
esfera[num_esfera].status = DISPONIVEL;
}
}
//printf("inicializando linha 3\n");
//Esferas devastadoras linha 3
if(QTD_LINHAS >= 2){
for(i=0;i<QTD_LINHA_ESFERA;i++,num_esfera++){
esfera[num_esfera].x = LINHA_CIMA_ESFERA-((DIST_X_ESFERA*i)+1);
esfera[num_esfera].y = LINHA_CIMA_ESFERA-(DIST_Y_ESFERA*2);
esfera[num_esfera].z = 0;
esfera[num_esfera].status = DISPONIVEL;
}
}
//printf("inicializando linha 4\n");
//Esferas devastadoras linha 4
if(QTD_LINHAS >= 1){
for(i=0;i<QTD_LINHA_ESFERA;i++,num_esfera++){
esfera[num_esfera].x = LINHA_CIMA_ESFERA-((DIST_X_ESFERA*i)+1);
esfera[num_esfera].y = LINHA_CIMA_ESFERA-(DIST_Y_ESFERA*3);
esfera[num_esfera].z = 0;
esfera[num_esfera].status = DISPONIVEL;
}
}
}
|
C
|
#include "adc.h"
#include "fet.h"
#include "phase.h"
#include "datatypes.h"
static void _init_phase(PhaseName name, FetName high, FetName low, AdcName adc_n){
struct Phase* p = &_phase[name];
p->high = fet[high];
p->low = fet[low];
p->adc = adc[adc_n];
phase_set_state(p, OFF, 0);
phase[name] = p;
}
void phase_set_mode(struct Phase* phase, PhaseMode mode){
phase->mode = mode;
switch(mode){
case COMP:
fet_enable(phase->high);
fet_enable(phase->low);
fet_set_polarity(phase->low, NORMAL);
fet_set_polarity(phase->high, NORMAL);
break;
case HIGH:
fet_enable(phase->high);
fet_disable(phase->low);
fet_set_polarity(phase->high, NORMAL);
break;
case LOW:
fet_disable(phase->high);
fet_enable(phase->low);
fet_set_polarity(phase->low, INVERTED);
break;
case OFF:
default:
fet_disable(phase->high);
fet_disable(phase->low);
phase->mode = OFF;
break;
}
}
void phase_update_state(){
fet_update();
}
void phase_set_duty(struct Phase* phase, float duty){
if (duty < 0.0)
duty = 0.0;
if (duty > 100.0)
duty = 100.0;
fet_set_duty(phase->high, duty);
phase->duty = duty;
}
void phase_init(void){
fet_init();
adc_init();
/* phase, high fet, low fet, adc */
_init_phase(APHASE, AH_FET, AL_FET, ADC_VA);
_init_phase(BPHASE, BH_FET, BL_FET, ADC_VB);
_init_phase(CPHASE, CH_FET, CL_FET, ADC_VC);
fet_update();
}
void phase_set_state(struct Phase* phase, PhaseMode mode, float duty){
phase_set_mode(phase, mode);
phase_set_duty(phase, duty);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bwayfare <bwayfare@student.21-schoo> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/17 00:51:59 by bwayfare #+# #+# */
/* Updated: 2020/11/17 00:52:00 by bwayfare ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char **ft_free(char **res, size_t i)
{
while ((int)i >= 0)
{
free(res[i]);
res[i] = NULL;
i--;
}
free(res);
res = NULL;
return (NULL);
}
size_t ft_column(const char *s, char c)
{
size_t i;
size_t f;
size_t j;
i = 0;
f = 0;
j = 0;
while (s[i])
{
if (s[i] == c && f == 1)
f = 0;
if (s[i] != c && f == 0)
{
f = 1;
j++;
}
i++;
}
return (j);
}
char **ft_creat(char **res, const char *s, char c, size_t col)
{
size_t end;
size_t i;
size_t beg;
end = 0;
i = 0;
beg = 0;
while (s[end++] != '\0')
{
if (s[beg] == c)
{
beg++;
end = beg;
}
else if (s[end] == c || s[end] == '\0')
{
res[i] = ft_substr(s, beg, end - beg);
if (res[i] == NULL)
return (ft_free(res, col));
beg = end;
i++;
}
}
res[i] = NULL;
return (&res[0]);
}
char **ft_split(char const *s, char c)
{
size_t column;
char **res;
if (!s)
return (NULL);
column = ft_column(s, c);
res = (char **)malloc((column + 1) * sizeof(char *));
if (!res)
return (NULL);
res = ft_creat(res, s, c, column);
return (res);
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
int compare(const void *a,const void *b)
{
return (*(int*)b-*(int*)a);
}
const int inf = 1e8;
int N,S;
int arr[55];
int dp[55][305];
int vis[55][305],True;
bool path[55][305];
int call(int pos,int sum){
if(sum < 0) return inf;
if(sum == 0) return 0;
if(pos == N) return inf;
if(vis[pos][sum] == True) return dp[pos][sum];
vis[pos][sum] = True;
dp[pos][sum]=inf;
int tmp = call(pos,sum-arr[pos])+1;
if(dp[pos][sum]>tmp){
dp[pos][sum]=tmp;
path[pos][sum] = true;
}
tmp = call(pos+1,sum);
if(dp[pos][sum]>tmp){
dp[pos][sum]=tmp;
path[pos][sum] = false;
}
return dp[pos][sum];
}
void printPath(int pos,int sum){
if(sum == 0) return;
if(path[pos][sum]){
printf(" %d",arr[pos]);
printPath(pos,sum-arr[pos]);
}else{
printPath(pos+1,sum);
}
}
int main()
{
char input[500],*z;
int cases=1,i,t;
gets(input);
t=atoi(input);
while(t--)
{
gets(input);
N=atoi(strtok(input," "));
S=atoi(strtok(NULL," "));
gets(input);
for(i=0,z=strtok(input," "); z ; z=strtok(NULL," "))
arr[i++]=atoi(z);
qsort(arr,N,sizeof(int),compare);
True=cases;
printf("Case %d:",cases++);
int counts=call(0,S);
if(counts!=inf)
{
printf(" [%d]",counts);
printPath(0,S);
puts("");
}
else puts(" impossible");
}
return 0;
}
|
C
|
#include<stdio.h>
main(){
int b[30],i,a,num,loc;
printf("Input Number of array : "); scanf("%d",&a);
printf("Input number of those array : ");
for(i=0; i<a; i++){
scanf("%d",&b[i]);
}
printf("Input number to be inserted : ");
scanf("%d",&num);
printf("Input the location to be changed : ");
scanf("%d",&loc);
if(loc>a){
printf("Not possible to add");
}
else{
for(i=a-1; i>=loc-1; i--){
b[i+1]=b[i];
}
b[loc-1]=num;
}
for(i=0;i<=a;i++){
printf("%d\n",b[i]);
}
}
|
C
|
/* Write a function invert(x,p,n) that returns x
* with the n bits that begin at position p
* inverted (i.e., 1 changed into 0 and vice versa),
* leaving the others unchanged.
*/
#include <stdio.h>
int invert(unsigned x, int p, int n);
int main() {
printf("%d\n", invert(222, 2, 2)); // => 216
printf("%d\n", invert(555, 5, 5)); // => 533
printf("%d\n", invert(7777, 7, 7)); // => 7839
return 0;
}
int invert(unsigned x, int p, int n) {
unsigned r;
unsigned m = ~(~0 << n) << (p - n + 1);
r = m & ~x;
x &= ~m;
return (r | x);
}
|
C
|
#include <stdio.h>
int main()
{
int n1,n2,temp=0;
printf("\nenter two numbers:");
scanf("%d%d",&n1,&n2);
temp=n1;
n1=n2;
n2=temp;
printf("the swaped numbers are:%d\n%d",n1,n2);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
int fd1[2];
int fd2[2];
pid_t p;
int myInt = 0;
int buffer = 0;
int status;
scanf("%d", &myInt);
fflush(stdout);
while (myInt != EOF)
{
pipe(fd1);
pipe(fd2);
p = fork();
if (p < 0)
{
fprintf(stderr, "fork Failed");
return 1;
}
else if (p == 0) /*child*/
{
close(fd1[1]);
int buffer2 = 0;
read(fd1[0], &buffer2, sizeof(int));
printf("buffer[0]: %d \n", buffer2);
int newInt = buffer2 + 1;
close(fd1[0]);
printf("Result%i\n", newInt);
fflush(stdout);
write(fd2[1], &newInt, sizeof(int));
exit(0);
}
else if (p > 0)
{
close(fd1[0]);
fflush(stdout);
int myNew = myInt * myInt;
write(fd1[1], &myNew, sizeof(int));
printf("Input Value from Parent: %d \n", myNew);
close(fd1[1]);
wait(NULL);
printf("Child process exited with %d status\n", WEXITSTATUS(status));
fflush(stdout);
read(fd2[0], &buffer, sizeof(int));
printf("Here is the final result: %i\n", buffer);
fflush(stdout);
close(fd2[1]);
}
scanf("%d", &myInt);
}
}
|
C
|
#include<stdio.h>
char*my_strstr(char*s1,char*s2)
{
char *p,*q,*m;
for(p=s1;*p!='\0';p++)
{
m=p;
for(q=s2;(*q==*p)&&(*p!='\0')&&(*q!='\0');p++,q++);
if(*q=='\0')
return m;
}
return NULL;
}
int main()
{
char a[100],b[100];
scanf("%s%s",a,b);
puts(my_strstr(a,b));
return 0;
}
|
C
|
#include<stdio.h>
#include<time.h>
#include<math.h>
#include<stdlib.h>
#define pi 3.142857
int main() {
srand(time(NULL));
int m,i,k;
scanf("%d",&m);
float matd[m],dct[m];
float ci,dct1,sum;
for(i=0;i<m;i++) {
matd[i]=(rand()%256)-128;
}
for(i=0;i<m;i++) {
printf("%f\t",matd[i]);
}
for(i=0;i<m;i++) {
if(i==0)
ci=1/sqrt(m);
else
ci=sqrt(2)/sqrt(m);
sum=0;
for(k=0;k<m;k++) {
dct1 = matd[k] * cos((2*k+1)*i*pi/(2*m));
sum = sum+dct1;
}
dct[i]=ci* sum;
}
printf("\n\n");
for(i=0;i<m;i++) {
printf("%f\t",dct[i]);
}
return 0;
}
|
C
|
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <time.h>
#define MAXVECT 10
#define MAXPROC 5
#define imprimirvector(v,n) printf("Mi vista (%d) del vector, \n",myrank); for (k = 0 ; k < n; k++) printf("[%d: %d] ",myrank,v[k]); printf("\n");
int main(int argc, char *argv[])
{
int myrank, worldsize;
int i,a,k;
int tag = 0;
int root;
// int *vector;
int vector[MAXVECT];
char hostname[HOST_NAME_MAX + 1];
MPI_Status status;
root = 0;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &worldsize);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
int scatter_vector[MAXVECT/worldsize];
if (myrank == root) {
// vector = (int*) malloc(sizeof(int)*MAXVECT);
for (i = 0; i < MAXVECT; i++) {
vector[i] = i;
}
imprimirvector(vector, MAXVECT);
for (a = 1; a < worldsize; a++) {
for (i = 0; i < MAXVECT/worldsize; i++) {
scatter_vector[i] = vector[(MAXVECT/worldsize)*a +i];
}
MPI_Send (&scatter_vector, MAXVECT/worldsize, MPI_INT, a, tag, MPI_COMM_WORLD);
}
for(i = 0; i < MAXVECT/worldsize; i++){
scatter_vector[i] = vector[(MAXVECT/worldsize)*myrank +i];
}
imprimirvector(scatter_vector, MAXVECT/worldsize);
// free(vector);
// vector = NULL;
}
/////////////////////////////////////////////////////////////////////////////////////////
for (a = 1; a < worldsize; a++) {
if (myrank == a) {
printf("\n antes de recivir: \n");
imprimirvector(scatter_vector, MAXVECT/worldsize);
MPI_Recv (&scatter_vector, MAXVECT/worldsize, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
printf("\n despues de recivir: \n");
imprimirvector(scatter_vector, MAXVECT/worldsize);
}
}
MPI_Finalize();
return 0;
}
|
C
|
/* C Program to Check if nth Bit in a 32-bit Integer is Set or not */
#include <stdio.h>
/* global variables */
int result, position;
/* function prototype */
int n_bit_position(int x, int position);
void main()
{
unsigned int number;
printf("Enter the unsigned integer:\n");
scanf("%d", &number);
printf("enter position\n");
scanf("%d", &position);
n_bit_position(i, position);
if (result & 1)
printf("YES\n");
else
printf("NO\n");
}
/* function to check whether the position is set to 1 or not */
int n_bit_position(int number, int position)
{
result = (number >> (position));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char data;
struct node* next;
};
struct node* make_node(char data){
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
struct node* append_node(struct node* first, char data){
struct node* new_node = make_node(data);
if(first==NULL){
first = new_node;
return first;
}
struct node* trav = first;
while(trav->next!=NULL)
trav = trav->next;
trav->next = new_node;
return first;
}
void display(struct node* first){
while(first!=NULL){
printf("%c ", first->data);
first = first->next;
}
}
struct node* make_ll(struct node* first, char* str){
int i=0;
while(i<strlen(str)){
first = append_node(first, str[i]);
i++;
}
return first;
}
int isVowel(char c){
switch(c){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 1;
default:
return 0;
}
}
struct node* delete_vowels(struct node* first){
struct node* trail = first;
struct node* temp = NULL;
while(isVowel(first->data)){
temp = first;
first = first->next;
free(temp);
}
while(trail->next!=NULL){
if(isVowel(trail->next->data)){
temp = trail->next;
trail->next = trail->next->next;
free(temp);
}
else
trail = trail->next;
}
return first;
}
int main(){
printf("enter string\n");
char* buff;
scanf("%ms", &buff);
struct node* first = NULL;
first = make_ll(first, buff);
first = delete_vowels(first);
display(first);
printf("\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* find_block_unique.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tcynthia <tcynthia@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/09 18:38:19 by tcynthia #+# #+# */
/* Updated: 2021/05/22 17:50:49 by tcynthia ### ########.fr */
/* */
/* ************************************************************************** */
#include "math.h"
t_collis get_collis(t_coord_uniq coord, t_vars *vars, t_sprite **sprite)
{
int x;
int y;
t_collis collis;
x = coord.ax / 64;
y = coord.ay / 64;
while (vars->map[y][x] != '1')
{
if (vars->map[y][x] == '2')
{
if (add_sprite(sprite, x * 64 + 32, y * 64 + 32, vars->player) == 0)
{
collis.err = 1;
return (collis);
}
}
coord.ax += coord.dx;
coord.ay += coord.dy;
x = coord.ax / 64;
y = coord.ay / 64;
}
collis.x = coord.ax;
collis.y = coord.ay;
return (collis);
}
t_collis find_block_unique(double phi, t_vars *vars, t_sprite **sprite)
{
t_coord_uniq coord;
t_collis collis;
coord.ax = receive_ax(vars->player, phi);
coord.ay = receive_ay(vars->player, phi);
coord.dx = receive_dx(phi);
coord.dy = receive_dy(phi);
collis = get_collis(coord, vars, sprite);
if (phi == 0 || phi == M_PI)
collis.offset = vars->player.y % 64 / 64.0;
else
collis.offset = vars->player.x % 64 / 64.0;
return (collis);
}
|
C
|
/**
* \file minmax_heap.c
* \author wzj
* \brief
* \version
* \note
* \date: Tue Nov 8 07:28:44 AEST 2016
*
* discript your detail info.
*/
#include <stdio.h>
#include <stdlib.h>
#include "minmax_heap.h"
struct heap_node{
int capacity;
int size;
int *elements;
};
mmheap initialize(int capacity)
{
mmheap mh;
mh = (mmheap)calloc(1, sizeof(*mh));
mh->capacity = capacity;
mh->elements = (int*)calloc(capacity, sizeof(int));
mh->size = 0;
return mh;
}
static int get_fa(int idx)
{
return (idx-1)/2;
}
static int get_gfa(int idx)
{
if(idx <= 2) {
return -1;
}
return ((idx-1)/2 - 1)/2;
}
int is_empty(mmheap mh)
{
if(mh->size == 0)
return 1;
else
return 0;
}
int is_full(mmheap mh)
{
if (mh->capacity == mh->size)
return 1;
else
return 0;
}
int get_depth(int idx)
{
int depth = 0;
while(idx > 0) {
idx = (idx-1)/2;
depth++;
}
return depth;
}
int is_odd_level(int idx)
{
int level = 0;
level = get_depth(idx);
return (level%2);
}
/*
* 1 偶数层节点,关键字小于父亲但是大于祖父
* 2 奇数层节点,关键字大于父亲但是小于祖父
* 使用 percolate up策略,调整一个节点后,继续调整被修改的节点,
* 保证树的属性
* */
void insert(mmheap mh, int x)
{
int idx;
int fa, gfa;
if(is_full(mh))
return ;
fa = gfa = 0;
for (idx = mh->size++; idx > 0; ) {
fa = get_fa(idx);
gfa = get_gfa(idx);
if (gfa == -1) {
if (x < mh->elements[fa]){
idx = fa;
}
break;
}
if (is_odd_level(idx)) {
if (x >= mh->elements[fa] &&
x <= mh->elements[gfa]) {
break;
}
if (x > mh->elements[gfa]) {
mh->elements[idx] = mh->elements[gfa];
idx = gfa;
continue;
}
if (x < mh->elements[fa]) {
mh->elements[idx] = mh->elements[fa];
idx = fa;
continue;
}
} else {
if(x <= mh->elements[fa] &&
x >= mh->elements[gfa]){
break;
}
if(x > mh->elements[fa]){
mh->elements[idx] = mh->elements[fa];
idx = fa;
continue;
}
if(x < mh->elements[gfa]) {
mh->elements[idx] = mh->elements[gfa];
idx = gfa;
continue;
}
}
}
mh->elements[idx] = x;
}
/**
* 使用percolate down 策略,将孩子和孙子节点中最小的值向上调整就可以了
* 1 先检查是否有孩子节点
* 2 在检查是否有孙子节点
* 3 有孙子节点,选择最小的孙子,继续调整。
* */
int deletemin(mmheap mh)
{
int i = 0,j;
int min_element;
int last_element;
int tmp_min, gchild;
int tmp_idx;
if (is_empty(mh))
return -1;
min_element = mh->elements[0];
last_element = mh->elements[--mh->size];
for(i = 0; (2*i+1) < mh->size; i = gchild) {
tmp_min = 100000;
gchild = (4*i+2)+1;
if (gchild >= mh->size) {
gchild = 2*i+1;
if (gchild+1 < mh->size &&
mh->elements[gchild+1] < mh->elements[gchild]) {
gchild++;
}
} else {
for (j = 1; j <= 4; j++) {
tmp_idx = (4*i+2)+j;
if (tmp_idx >= mh->size)
break;
if (mh->elements[tmp_idx] < tmp_min) {
tmp_min = mh->elements[tmp_idx];
gchild = tmp_idx;
}
}
}
if (last_element > mh->elements[gchild]) {
mh->elements[i] = mh->elements[gchild];
} else {
break;
}
}
mh->elements[i] = last_element;
return min_element;
}
/**
* 1基本思想同deletemin.这里每次调整最大值就可以
* */
int deletemax(mmheap mh)
{
int i,j;
int max_element;
int last_element;
int tmp_max, gchild;
int tmp_idx = 0;
if (is_empty(mh))
return -1;
max_element = -1;
for (i = 0; i < mh->size && i < 3; i++) {
if (mh->elements[i] > max_element) {
max_element = mh->elements[i];
tmp_idx = i;
}
}
last_element = mh->elements[--mh->size];
for (i = tmp_idx; (2*i+1) < mh->size; i = gchild) {
tmp_max = -1;
tmp_idx = -1;
gchild = (4*i+2)+1;
if (gchild >= mh->size) {
gchild = 2*i+1;
if (gchild+1 < mh->size &&
mh->elements[gchild+1] > mh->elements[gchild]) {
gchild++;
}
} else {
for (j = 1; j<=4; j++) {
tmp_idx = (4*i+2)+j;
if (tmp_idx >=mh->size)
break;
if (mh->elements[tmp_idx] < tmp_max) {
tmp_max = mh->elements[tmp_idx];
gchild = tmp_idx;
}
}
}
if (last_element < mh->elements[gchild]) {
mh->elements[i] = mh->elements[gchild];
} else {
break;
}
}
mh->elements[i] = last_element;
return max_element;
}
#if 0
int main()
{
int i;
mmheap mh;
mh = initialize(1000);
for (i = 0; i < 100; i++) {
printf("%d ", i);
insert(mh, i);
}
printf("\n");
for (i = 0; i < 100; i++) {
printf("%d ", deletemin(mh));
}
printf("\n");
return 0;
}
#endif
#if 1
int main()
{
int i;
mmheap mh;
mh = initialize(100);
insert(mh, 13);
insert(mh, 14);
insert(mh, 16);
insert(mh, 19);
insert(mh, 21);
insert(mh, 19);
insert(mh, 68);
insert(mh, 65);
insert(mh, 26);
insert(mh, 32);
insert(mh, 31);
for (i = 0; i < 5; i++) {
printf("%d %d\n", deletemin(mh), deletemax(mh));
}
printf("\n");
return 0;
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.