language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #pragma once
#include "Point.h"
#include <cstdlib>
struct polar_point;
typedef struct
{
void (*point) (struct point*);
polar_point* (*make_polar_point) (double x, double y);
} polar_point_func_table;
typedef struct polar_point
{
point* inherited;
polar_point_func_table* vmt;
} polar_point;
polar_point* polar_point_make_polar_point(double x, double y);
polar_point_func_table polar_point_vmt = {point_point, polar_point_make_polar_point};
inline void polar_point_polar_point(polar_point* p)
{
point_point(p->inherited);
p->vmt = &polar_point_vmt;
}
inline polar_point* polar_point_make_polar_point(const double x, const double y)
{
const auto p = static_cast<polar_point*>(malloc(sizeof(struct polar_point)));
p->inherited->x = x;
p->inherited->y = y;
return p;
}
|
C | /*
ssortdir.c - performs a selection sort on the given directory.
Copyright (C) 2002 Imre Leber
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
If you have any questions, comments, suggestions, or fixes please
email me at: [email protected]
*/
#include <string.h>
#include <stdlib.h>
#include "fte.h"
#include "sortcfgf.h"
#include "expected.h"
/*
** Generic routine to sort entries in a directory.
**
** Different implementatiotions should give the possibility
** to both make use of all available memory and still allow
** for VERY low (< 8Kb) memory conditions.
**
** Returns FALSE if not been able to sort, TRUE otherwise.
**
** The reasons why I use a selection sort is:
** - It is a simple algorithm, so less can go wrong.
** - When assuming that we use a write-through cache, the time
** to sort is mostly determined by the number of writes. With
** selection sort the number of writes is at most 2*n (with n
** the number of entries in the directory).
*/
/* First see if we should be sorting at all, we should not be sorting
if this directory contains:
- system files not all located at the start of the disk.
- entries of different length.
*/
static int DirectoryMaybeSorted(void* entries, int totalentries)
{
int systemfilefound = FALSE, nonsystemfilefound=FALSE, differentlength = FALSE;
unsigned previouslength=0, currentlength, i;
struct DirectoryEntry* entry = (struct DirectoryEntry*)
malloc(sizeof(struct DirectoryEntry));
if (!entry) return -1;
for (i = 0; i < totalentries; i++)
{
/* Count the number of slots in this entry. */
for (currentlength = 0; currentlength < totalentries; currentlength++)
{
if (!GetSlotToSort(entries, i, currentlength, entry))
{
free(entry);
return -1;
}
if (!IsLFNEntry(entry))
break;
}
if (entry->attribute & FA_SYSTEM)
{
if (nonsystemfilefound)
{
systemfilefound = TRUE;
}
}
else
{
nonsystemfilefound = TRUE;
}
if (i == 0)
{
previouslength = currentlength;
}
else if (previouslength != currentlength)
{
differentlength = TRUE;
}
}
free(entry);
return !(differentlength && systemfilefound);
}
static int SkipLFNs(void* entries,
int entry, int totalentries,
struct DirectoryEntry* result)
{
unsigned j;
for (j=0; j < totalentries; j++)
{
if (!GetSlotToSort(entries, entry, j, result))
return FALSE;
if (!IsLFNEntry(result))
break;
}
return TRUE;
}
int SelectionSortEntries(void* entries, int amountofentries)
{
int i, j, pos;
struct DirectoryEntry seeker, min;
switch (DirectoryMaybeSorted(entries, amountofentries))
{
case -1:
return FALSE;
case FALSE:
return TRUE;
}
for (i = 0; i < amountofentries; i++)
{
pos = i;
if (!GetEntryToSort(entries, i, &min))
return FALSE;
if (!SkipLFNs(entries, i, amountofentries, &min))
return FALSE;
if ((min.attribute & FA_SYSTEM) == 0)
{
if ((i % 2) == 0) /* Cache optimization */
{
for (j = i; j < amountofentries; j++)
{
/* Update the interface */
UpdateInterfaceState();
if (!GetEntryToSort(entries, j, &seeker))
return FALSE;
if (!SkipLFNs(entries, j, amountofentries, &seeker))
return FALSE;
if ((seeker.attribute & FA_SYSTEM) == 0)
{
if (FilterSortResult(CompareEntriesToSort(&seeker, &min))
== -1)
{
pos = j;
memcpy(&min, &seeker, sizeof(struct DirectoryEntry));
}
}
}
}
else
{
for (j = amountofentries-1; j >= i; j--)
{
/* Update the interface */
UpdateInterfaceState();
if (!GetEntryToSort(entries, j, &seeker))
return FALSE;
if (!SkipLFNs(entries, j, amountofentries, &seeker))
return FALSE;
if ((seeker.attribute & FA_SYSTEM) == 0)
{
if (FilterSortResult(CompareEntriesToSort(&seeker, &min))
== -1)
{
pos = j;
memcpy(&min, &seeker, sizeof(struct DirectoryEntry));
}
}
}
}
if (pos != i)
if (!SwapEntryForSort(entries, i, pos)) /* 2n writes */
return FALSE;
}
}
return TRUE;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
// a slow dumb fib function
int fib(int n) {
if (n == 0 || n == 1) {
return 1;
}
else {
return fib(n-1) + fib(n-2);
}
}
int main(int argc, char *argv[]) {
char *a;
long x;
long f;
if (argc > 1) {
a = argv[1];
//x = atoi(a);
printf("%d\n",fib(atoi(a)));
//f = fib(x);
//printf("%s\n", a);
//printf("%ld\n", f);
}
else {
printf("more args plz\n");
}
}
|
C | #pragma once
struct Node {
int value;
struct Node *next;
};
typedef struct Node Node;
//
#define nodeLinkToNode(node, anotherNode) \
node.next = &anotherNode;
//
#define getValueByNodeAddress(node) \
node->value
//
#define getNextNodeByNodeAddress(node) \
node->next
//
#define moveToNextNodeByNodeAddress(node) \
node = getNextNodeByNodeAddress(node);
//
#define moveToNextNodeByNodeAddress_Safe(node) \
if(node != NULL){ \
moveToNextNodeByNodeAddress(node) \
}
//
#define newNode(name) \
Node* name = (Node*)malloc(sizeof(Node));
//
#define newNodeByValue(name, inValue) \
newNode(name); \
if(name){ \
(*name).value = inValue; \
(*name).next = NULL; \
}
//
#define newNodeByNode(newNodeName, inNode) \
newNode(name) \
*name = inNode;
//
#define createNode(name) \
Node name = {.value = 0, .next = NULL};
//
#define createNodeByValue(name, inValue) \
createNode(name); \
name.value = inValue;
//
#define createNodeByNode(name, inNode) \
createNode(name); \
name = inNode;
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_free.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sdremora <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/27 12:12:27 by sdremora #+# #+# */
/* Updated: 2019/02/06 11:47:18 by sdremora ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Освобождает память от всех ссылок из аргументов.
** count_param указывает количество ссылок.
** Всем значениям ссылок присваивается ноль.
*/
void *ft_free(int count_param, ...)
{
va_list ref_list;
void **reference;
va_start(ref_list, count_param);
while (count_param > 0)
{
reference = va_arg(ref_list, void **);
free(*reference);
*reference = NULL;
count_param--;
}
va_end(ref_list);
return (NULL);
}
|
C | /**********************
*** CstTool.c ***
**********************/
#include <string.h>
#include <stdlib.h>
#include "Uigp/igp.h"
#include "CstType.h"
#include "Ubst/BstType.h"
cst_type *
cst_alloc( int byte_no )
{
cst_type *cst;
cst = (cst_type *)malloc( sizeof(cst_type) );
cst->BYTE_NO = byte_no;
if( cst->BYTE_NO > 0 )
cst->data = (u_char *) calloc( cst->BYTE_NO, 1 );
else cst->data = NULL;
// cst->byte_no = 0;
cst->rp = cst->data;
cst->wp = cst->data;
return( cst );
}
void
cst_realloc( cst_type *cst, int byte_no )
{
if( byte_no > cst->BYTE_NO ){
free( cst->data );
cst->BYTE_NO = byte_no;
cst->data = (u_char *) calloc( cst->BYTE_NO, 1 );
}
// cst->byte_no = 0;
cst->rp = cst->data;
cst->wp = cst->data;
}
void
cst_extend(cst_type *cst, int byte_extention)
{
u_char* buf = cst->data;
int location = (int)(cst->rp - cst->data);
int last_byte = (int)(cst->wp - cst->data);
if ( byte_extention > 0 ){
cst->BYTE_NO += byte_extention;
cst->data = (u_char *) calloc( cst->BYTE_NO, 1 );
memcpy(cst->data,buf, last_byte );
free(buf);
cst->rp = &cst->data[location];
cst->wp = &cst->data[last_byte];
}
/*
u_char* buf = cst->data;
int location = (int)(cst->rp - cst->data);
int old_byte_no = cst->BYTE_NO;
if ( byte_extention > 0 )
{
cst->BYTE_NO += byte_extention;
cst->data = (u_char *) calloc( cst->BYTE_NO, 1 );
memcpy(cst->data,buf,old_byte_no);
free(buf);
cst->rp = &cst->data[location];
}
*/
}
void
cst_clear( cst_type *cst )
{
// cst->byte_no = 0;
cst->rp = cst->data;
cst->wp = cst->data;
}
void
cst_free( cst_type *cst )
{
if( cst->data != NULL )
free( cst->data );
free( cst );
}
void
cst_rewind( cst_type *cst )
{
cst->rp = cst->data;
}
int
cst_get_buffer( cst_type *cst, u_char buf[], int byte_no )
{
int i;
// if( CST_BYTE_INDEX(cst) + byte_no > cst->byte_no )
// byte_no = cst->byte_no - CST_BYTE_INDEX( cst );
if( cst->rp + byte_no > cst->wp )
byte_no = cst->wp - cst->rp;
for( i = 0 ; i < byte_no ; i++ )
buf[i] = CST_GET_UCHAR( cst );
return( byte_no );
}
int
cst_put_buffer_int( cst_type *cst, u_char buf[], int byte_no )
{
int i;
for( i = 0 ; i < byte_no ; i++ )
CST_PUT_CHAR( cst , buf[i]);
// cst->byte_no = cst->rp - cst->data;
return byte_no;
}
int
cst_put_buffer( cst_type *cst, char buf[], int byte_no )
{
char *p;
int i;
for( p= buf, i = 0 ; i < byte_no ; i++, p++ )
CST_PUT_CHAR( cst , *p);
// cst->byte_no = cst->rp - cst->data;
return byte_no;
}
int
cst_put_string( cst_type *cst, char buf[] )
{
char *p;
if (!buf)
return (1);
for( p = buf ; *p != 0 ; p++ )
CST_PUT_CHAR( cst , *p);
return( 1 );
}
void
cst_put_stringA( cst_type *cst, int align, char *name )
{
char *p;
int i;
for( i = 0 ; i < align ; i++ )
CST_PUT_CHAR( cst , '\t' );
for( p = name ; *p != 0 ; p++ )
CST_PUT_CHAR( cst , *p);
}
cst_type *
cst_make_copy( cst_type *cst )
{
cst_type *ccst;
ccst = cst_create( (char *)cst->data, CST_BYTES(cst), 1 ); //cst->byte_no, 1 );
return( ccst );
}
cst_type *
cst_create( char data[], int byte_no, int FCopydata )
{
cst_type *cst;
if( FCopydata == 1 ){
cst = cst_alloc(byte_no);
memcpy( cst->data, data, byte_no );
}
else
{
cst = (cst_type *)malloc( sizeof(cst_type) );
cst->data = (unsigned char *)data;
}
cst->BYTE_NO = byte_no;
// cst->byte_no = cst->BYTE_NO;
cst->rp = cst->data;
cst->wp = cst->data + byte_no;
return cst;
}
void
cst_destroy( cst_type *cst, int FDeletedata )
{
if( FDeletedata )
free( cst->data );
free( cst );
}
struct bst_type *cst2bst(cst_type* cst, int byte_no)
{
bst_type *bst = bst_alloc( byte_no );
memcpy( bst->data, cst->data, byte_no );
bst->byte_no = bst->BYTE_NO;
return bst;
}
void
cst_insert( cst_type *cst, char *data, int bytes )
{
char *buf;
if( cst->BYTE_NO - (cst->wp - cst->data ) > bytes + 1 ){
memcpy( cst->wp, data, bytes );
cst->wp += bytes;
return;
}
if( cst->BYTE_NO - (cst->wp - cst->rp) > bytes + 1 ){
memcpy( cst->data, cst->rp, cst->wp - cst->rp );
cst->wp -= (cst->rp - cst->data);
cst->rp = cst->data;
memcpy( cst->wp, data, bytes );
cst->wp += bytes;
return;
}
cst->BYTE_NO = (cst->wp - cst->rp) + bytes +1;
buf = (char *)malloc( cst->BYTE_NO );
memcpy (buf, cst->rp, cst->wp - cst->rp );
free( cst->data );
cst->data = buf;
cst->wp = cst->data + (cst->wp - cst->rp);
cst->rp = cst->data;
memcpy( cst->wp, data, bytes );
cst->wp += bytes;
}
void
cst_rewind_data( cst_type *cst )
{
int n;
if( cst->wp == cst->rp ){
cst->wp = cst->rp = cst->data;
return;
}
if( cst->rp != cst->data ){
n = cst->wp - cst->rp;
memcpy( cst->data, cst->rp, n );
cst->rp = cst->data;
cst->wp = cst->rp + n;
//memcpy( cst->data, cst->rp, cst->wp - cst->rp );
//cst->wp -= (cst->rp - cst->data);
//cst->rp = cst->data;
}
} |
C | #include <stdio.h>
struct things
{
char itemcode[6];
char itemname[20];
int qty;
};
int main()
{
int option,iterate;
char find;
char file[100];
FILE *f,*f2;
struct things things1;
struct things things2;
printf("do you want to add item or get item list?\npress number\n 1 = add\n 2 = list\n");
scanf("%d",&option);
switch(option)
{
case 1:
f=fopen("inorder.txt","a+");
if(f==0)
{
printf("file error");
}
printf("item code : ");
scanf("%s",things1.itemcode);
printf("item name (first letter must be capital): ");
scanf("%s",things1.itemname);
printf("Qty : ");
scanf("%d",&things1.qty);
fwrite(&things1,sizeof(things1),1,f);
if(fwrite!=0)
{
printf("Data stored");
}
else
{
printf("Error");
}
fclose(f);
break;
case 2:
f=fopen("inorder.txt","r");
if(f==0)
{
printf("File error");
}
for(iterate=65;iterate<=90;iterate++)
{
while(fread(&things1, sizeof(struct things), 1, f))
{
find=things1.itemname[0];
if(find==iterate)
{
f2=fopen("ordered.c","a");
fprintf(f2,"%s %s %d\n",things1.itemcode,things1.itemname,things1.qty);
printf("%s\n",things1.itemname);
fclose(f2);
}
}
rewind(f);
}
fclose(f);
break;
}
}
|
C | /*
el primer d´ıa le dar´a un
c´entimo de euro, el segundo otro c´entimo de euro y a partir del tercero siempre le dar´a el doble de lo que
le dio dos d´ıas antes m´as lo que le dio justo el d´ıa antes. Jaime calcula cu´antos d´ıas tardar´a en tener el
dinero suficiente, pero... a veces se pregunta cu´anto tardar´ıa en hacerse millonario
g++ -std=c++11 main.c -o main
*/
#include <iostream>
#include <fstream>
using namespace std;
#ifndef DOMJUDGE
ifstream in("test.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
void solve( int moneyToGet ){
int s = 0, s0,s1,s2;
int days = 0;
while( s < moneyToGet ){
switch(days){
case 0:{
s0 = 1;
break;
}
case 1:{
s1 = s0;
s0 = 1;
break;
}
default:{
s2 = s1;
s1 = s0;
s0 = 2 * s2 + s1;
break;
}
}
s = s + s0;
days++;
}
cout << days << endl;
}
int main(){
int numCasos, pos = 0;
int money = 0;
cin >> numCasos;
while( pos < numCasos ){
cin >> money;
solve( money );
pos++;
}
return 0;
} |
C | #include "header.h"
#include "std.h"
#include "std_io.h"
struct Type INT_TYPE() {
struct Type t;
t.type_category = INT_;
return t;
}
struct Type
CHAR_TYPE() {
struct Type t;
t.type_category = CHAR_;
return t;
}
int is_struct_or_union(const struct Type *t)
{
return t->type_category == STRUCT_NOT_UNION || t->type_category == UNION;
}
int size_of_basic(const struct Type *ref_type, const char *msg)
{
switch (ref_type->type_category) {
case INT_:
case ENUM_:
return 4;
case PTR_:
return 8;
case CHAR_:
return 1;
case ARRAY:
case FN:
case STRUCT_NOT_UNION:
case UNION:
fprintf(
stderr,
"array, function, struct, or union type is not a basic type.\n");
fprintf(stderr, "context: %s\n", msg);
exit(EXIT_FAILURE);
case VOID_:
fprintf(stderr, "size of `void` is never known\n");
fprintf(stderr, "context: %s\n", msg);
exit(EXIT_FAILURE);
}
fprintf(stderr,
"****************************\n"
"* INTERNAL COMPILER ERROR @ %s\n"
"* Unexpected value of TypeCategory: `ref_type->type_category` is `%d`\n"
"****************************\n",
__func__, ref_type->type_category);
exit(EXIT_FAILURE);
}
void debug_print_type(const struct Type *ref_type)
{
struct Type type = *ref_type;
switch (type.type_category) {
case PTR_:
fprintf(stderr, "pointer to ");
debug_print_type(type.derived_from);
return;
case VOID_:
fprintf(stderr, "void");
return;
case INT_:
fprintf(stderr, "int");
return;
case CHAR_:
fprintf(stderr, "char");
return;
case STRUCT_NOT_UNION:
fprintf(stderr, "struct %s", type.s.struct_or_union_tag);
return;
case UNION:
fprintf(stderr, "union %s", type.s.struct_or_union_tag);
return;
case ENUM_:
fprintf(stderr, "enum %s", type.e.enum_tag);
return;
case ARRAY:
fprintf(stderr, "array (length %d) of ", type.array_length);
debug_print_type(type.derived_from);
return;
case FN:
fprintf(stderr, "function (");
switch (type.param_infos_validity) {
case INVALID: {
fprintf(stderr, "param: no info");
break;
}
case VALID: {
if (type.param_infos.length == 0) {
fprintf(stderr, "no params");
} else if (type.param_infos.length < 2) {
const struct TypeAndIdent *vec_0 = type.param_infos.vector[0];
fprintf(stderr,
"%s: ", vec_0->ident_str ? vec_0->ident_str : "@anon");
debug_print_type(&vec_0->type);
} else {
fprintf(stderr, "params: \n");
for (int i = 0; i < type.param_infos.length; i++) {
const struct TypeAndIdent *ptr_paraminfo =
type.param_infos.vector[i];
fprintf(stderr, " %s: ",
ptr_paraminfo->ident_str ? ptr_paraminfo->ident_str
: "@anon");
debug_print_type(&ptr_paraminfo->type);
fprintf(stderr, "\n");
}
}
break;
}
case VA_ARGS: {
if (type.param_infos.length == 0) {
fprintf(stderr, "no params varg");
} else {
fprintf(stderr, "params: \n");
for (int i = 0; i < type.param_infos.length; i++) {
const struct TypeAndIdent *ptr_paraminfo =
type.param_infos.vector[i];
fprintf(stderr, " %s: ",
ptr_paraminfo->ident_str ? ptr_paraminfo->ident_str
: "@anon");
debug_print_type(&ptr_paraminfo->type);
fprintf(stderr, "\n");
}
fprintf(stderr, ", ...");
}
break;
}
}
fprintf(stderr, ") returning ");
debug_print_type(type.derived_from);
}
}
struct Type deref_type(const struct Type *ref_type)
{
if (ref_type->type_category == PTR_) {
return *ref_type->derived_from;
}
fprintf(stderr, "Unmatched type: expected a pointer, but got `");
debug_print_type(ref_type);
fprintf(stderr, "`.\n");
exit(EXIT_FAILURE);
}
void if_array_convert_to_ptr_(struct Type *ptr_type)
{
if (ptr_type->type_category == ARRAY) {
ptr_type->type_category = PTR_;
}
}
struct Type ptr_to_type(const struct Type *ref_type)
{
struct Type *ptr_type = calloc(1, sizeof(struct Type));
*ptr_type = *ref_type;
struct Type type;
type.type_category = PTR_;
type.derived_from = ptr_type;
return type;
}
struct Type arr_of_type(const struct Type *ref_type, int length)
{
struct Type *ptr_type = calloc(1, sizeof(struct Type));
*ptr_type = *ref_type;
struct Type type;
type.type_category = ARRAY;
type.derived_from = ptr_type;
type.array_length = length;
return type;
}
|
C |
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
void manejador(int signum)
{
switch (signum)
{
case SIGUSR1:
printf("He recibido la señal ejecuto P1 \n");
break;
case SIGUSR2:
printf("He recibido la señal ejecuto P2 \n");
break;
}
}
int main(int argc, char const *argv[])
{
pid_t p1,p2,p3,p4,p5,status;
bool validador = true;
int var1;
p1=fork();
if(p1 == -1){
printf("ERROR");
exit(0);
}else if (p1 == 0){
p2=fork();
if(p2 == -1){
printf("ERROR");
exit(0);
}else if (p2==0){
do
{
printf("Pulsa 1 para generar nuevo hijo, pulsa 2 para salir \n");
scanf("%d", &var1);
switch (var1){
case 1:
p3=fork();
if(p3==-1){
}else if (p3==0){
printf("Soy el hijo generado\n");
exit(EXIT_SUCCESS);
}else{
waitpid(p3, &status, 0);
}
break;
case 2:
validador = false;
break;
}
} while (validador==true);
kill(getppid(), SIGUSR2);
exit(EXIT_SUCCESS);
}else{
signal(SIGUSR2, manejador);
pause();
bool validador = true;
do{
printf("Pulsa 1 para generar nuevo nieto, pulsa 2 para salir \n");
scanf("%d", &var1);
switch (var1){
case 1:
p4 = fork();
if (p4 == 0){
p5 = fork();
if (p5 == 0){
printf("Soy el hijo nieto con pid: %d,con padre:%d\n", getpid(), getppid());
exit(EXIT_SUCCESS);
}else{
// p2child code
printf("Soy el hijo generado con pid: %d,con padre:%d\n", getpid(), getppid());
waitpid(p5, &status, 0);
exit(EXIT_SUCCESS);
}
}else{
waitpid(p4, &status, 0);
}
break;
case 2:
validador = false;
break;
}
}while (validador);
//PID DEL RECEPTOR Y SEÑAL
kill(getppid(), SIGUSR1);
exit(EXIT_SUCCESS);
}
}else{
signal(SIGUSR1, manejador);
pause();
printf("Soy el padre, he generado un hijo,\n un nieto,ellos han creado otros procesos, \nyo me he esperado hasta el final,\n se han muerto y aquí sigo yo. Saludo");
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_put_pixel.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jledieu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/29 02:09:32 by jledieu #+# #+# */
/* Updated: 2016/04/23 17:15:01 by jledieu ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/visu.h"
static int ft_get_color(t_mlx *e, int y, int x)
{
if (e->mapxyz[y][x] == 1)
return (0xFF0000);
else if (e->mapxyz[y][x] == 10)
return (0x550000);
else if (e->mapxyz[y][x] == 2)
return (0x0000FF);
else if (e->mapxyz[y][x] == 20)
return (0x000055);
else
return (0xFFFFFF);
}
int ft_put_pixel_first_round(t_mlx *e, size_t y, size_t x)
{
size_t tmpx;
size_t tmpy;
if ((e->mapxyz[y][x] >= e->mapxyz[y][x + 1] ||
e->mapxyz[y][x] < e->mapxyz[y][x + 1]) && x < ft_strlen(e->map[y]) - 1)
{
tmpx = (x * 10);
while (tmpx < ((x + 1) * 10))
mlx_pixel_put(e->mlx, e->win, 200 + tmpx++, 200 + (y * 10),
ft_get_color(e, y, x));
}
if (y < e->nbline - 1 && (e->mapxyz[y][x] >= e->mapxyz[y + 1][x] ||
e->mapxyz[y][x] < e->mapxyz[y + 1][x]) && x < ft_strlen(e->map[y + 1]))
{
tmpy = (y * 10);
while (tmpy < ((y + 1) * 10))
mlx_pixel_put(e->mlx, e->win, 200 + (x * 10), 200 + tmpy++,
ft_get_color(e, y, x));
}
return (++x);
}
int ft_put_pixel_other_round(t_mlx *e, size_t y, size_t x)
{
size_t tmpx;
size_t tmpy;
if (x + 1 < ft_strlen(e->map[y]) && e->mapxyz[y][x] != 0 &&
e->mapxyz[y][x + 1] != 0)
if ((e->mapxyz[y][x] >= e->mapxyz[y][x + 1] ||
e->mapxyz[y][x] < e->mapxyz[y][x + 1]) &&
x < ft_strlen(e->map[y]) - 1)
{
tmpx = (x * 10);
while (tmpx < ((x + 1) * 10))
mlx_pixel_put(e->mlx, e->win, 200 + tmpx++, 200 + (y * 10),
ft_get_color(e, y, x));
}
if (y + 1 < e->nbline && e->mapxyz[y][x] != 0 && e->mapxyz[y + 1][x] != 0)
if (y < e->nbline - 1 && (e->mapxyz[y][x] >= e->mapxyz[y + 1][x] ||
e->mapxyz[y][x] < e->mapxyz[y + 1][x]) &&
x < ft_strlen(e->map[y + 1]))
{
tmpy = (y * 10);
while (tmpy < ((y + 1) * 10))
mlx_pixel_put(e->mlx, e->win, 200 + (x * 10), 200 + tmpy++,
ft_get_color(e, y, x));
}
return (++x);
}
void ft_put_pixel(t_mlx *e)
{
size_t y;
size_t x;
y = 0;
while (y < e->nbline)
{
x = 0;
while (x < ft_strlen(e->map[0]))
{
if (e->firstround == 0)
x = ft_put_pixel_first_round(e, y, x);
else
x = ft_put_pixel_other_round(e, y, x);
}
y++;
}
}
|
C | #include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stddef.h>
#define DEBUG 0
#define debug_print(...) \
do { if (DEBUG) fprintf(stderr, ##__VA_ARGS__); } while (0)
#define ALIGNMENT 8
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~(ALIGNMENT-1))
typedef struct list_t list_t;
struct list_t {
unsigned in_use: 1; /* if the block is used or not */
size_t order; /* current order of block (2^order) */
list_t* succ; /* right child block in tree */
list_t* pred; /* left child block in tree */
};
#define K_MAX 22
#define K_MAX_SIZE (1 << K_MAX)
#define ORDER_0 4
// Size of the node metadata
#define META_SIZE (ALIGN(sizeof(list_t)))
static list_t* find_block(size_t);
static size_t get_order(size_t);
static list_t* split(list_t*, size_t);
/* Array of pointers to first block of order k at free_list[k] */
static list_t* freelist[K_MAX + 1];
static void* start = NULL;
static void print_freelist()
{
debug_print("Freelist: [");
for (int i = ORDER_0; i <= K_MAX; i++) {
int f = 0;
int j = 0;
list_t* current = freelist[i];
while (current) {
if (!current->in_use) {
f++;
}
j++;
debug_print("%p -> ", current);
current = current->succ;
}
debug_print("%d/%d, ", f, j);
}
debug_print("]\n");
}
void *malloc(size_t requested_size)
{
debug_print("*******************MY MALLOC(%zu)\n", requested_size);
print_freelist();
if (requested_size <= 0) {
return NULL;
}
if (!start) {
// First allocation ever, grab memory and root the tree
start = sbrk(K_MAX_SIZE);
list_t* top = start;
top->order = K_MAX;
top->in_use = 0;
top->succ = NULL;
top->pred = NULL;
freelist[K_MAX] = top;
}
/* E.g. if requested size is 56 bytes, k = 6 (2^6=64)*/
size_t k = get_order(ALIGN(requested_size + META_SIZE));
debug_print("Order: %zu\n", k);
list_t* r = find_block(k);
if (r) {
r->in_use = 1;
print_freelist();
debug_print("****** Malloc returned %p\n", (r + 1));
return (r + 1);
} else {
return NULL;
}
}
/* Find the smallest power of 2 larger than k */
static size_t get_order(size_t v)
{
int k = ORDER_0;
while ((1 << k) < v) {
k++;
}
return k;
}
// finds a suitable block of order k. if not found return null
static list_t* find_block(size_t k)
{
if (k > K_MAX)
return NULL;
list_t* current = freelist[k];
while (current) {
if (!current->in_use)
return current;
current = current->succ;
}
list_t* big_block = find_block(k + 1);
if (big_block) {
current = split(big_block, k);
}
return current;
}
static void remove_from_freelist(list_t* item)
{
size_t k = item->order;
if (freelist[k] == item)
freelist[k] = item->succ;
if (item->pred)
item->pred->succ = item->succ;
if (item->succ)
item->succ->pred = item->pred;
item->pred = NULL;
item->succ = NULL;
}
static void add_to_freelist(list_t* item)
{
size_t k = item->order;
if (!freelist[k]) {
freelist[k] = item;
item->succ = NULL;
item->pred = NULL;
return;
}
item->pred = NULL;
item->succ = freelist[k];
freelist[k]->pred = item;
freelist[k] = item;
}
static list_t* split(list_t* src, size_t new_order)
{
while (src->order > new_order) {
/* src becomes left buddy */
remove_from_freelist(src);
// set new order
src->order = src->order - 1;
// calculate half size of old block, aka size of new order.
size_t size = 1 << src->order;
list_t* right = ((void*) src) + size;
right->order = src->order;
right->in_use = 0;
add_to_freelist(right);
add_to_freelist(src);
}
return src;
}
static void merge(list_t* block)
{
if (block->in_use || block->order == K_MAX)
return;
list_t* buddy = start + ((((void*)block) - start) ^ (1 << block->order));
if (buddy->in_use || buddy->order != block->order)
return;
list_t* left = block;
list_t* right = buddy;
if (block > buddy) {
left = buddy;
right = block;
}
remove_from_freelist(right);
remove_from_freelist(left);
left->order++;
add_to_freelist(left);
merge(left);
}
void free(void *ptr)
{
debug_print("***************************Free (%p)\n", ptr);
print_freelist();
if (!ptr)
return;
list_t* block = (((list_t*)ptr) - 1);
assert(block->in_use);
block->in_use = 0;
merge(block);
debug_print("***************************Free -- exit (%p)\n", ptr);
print_freelist();
}
void *calloc(size_t nbr_elements, size_t element_size) {
debug_print( "***************************CALLOC(%zu, %zu)\n", nbr_elements, element_size);
size_t size = nbr_elements * element_size;
void* ptr = malloc(size);
if (ptr == NULL)
return NULL;
memset(ptr, 0, size);
return ptr;
}
void *realloc(void *ptr, size_t size)
{
debug_print("***************************REALLOC(%p, %zu)\n", ptr, size);
if (!ptr) {
return malloc(size);
}
list_t* block = (((list_t*) ptr) - 1);
if ((1 << block->order) - META_SIZE >= size) {
return ptr;
}
void* new_ptr = malloc(size);
if (!new_ptr) {
return NULL;
}
memcpy(new_ptr, ptr, (1 << block->order) - META_SIZE);
free(ptr);
return new_ptr;
}
|
C | #include <mintpl/substitute.h>
#include <mintpl/generators.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
inline static bool is_whitespace(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
static mtpl_result perform_substitution(
mtpl_generator generator,
const mtpl_allocators* allocators,
mtpl_readbuffer* source,
mtpl_hashtable* generators,
mtpl_hashtable* properties,
mtpl_buffer* out_buffer,
bool nested
) {
mtpl_generator sub_generator;
mtpl_result result;
mtpl_buffer* gen_name;
result = mtpl_buffer_create(allocators, MTPL_DEFAULT_BUFSIZE, &gen_name);
if (result != MTPL_SUCCESS) {
return result;
}
mtpl_buffer* arg_buffer;
result = mtpl_buffer_create(allocators, MTPL_DEFAULT_BUFSIZE, &arg_buffer);
if (result != MTPL_SUCCESS) {
goto cleanup_gen_name;
}
memset(arg_buffer->data, 0, MTPL_DEFAULT_BUFSIZE);
while (true) {
switch (source->data[source->cursor]) {
case '[':
source->cursor++;
// Lookup generator name and begin new substitution.
result = mtpl_buffer_extract(
'>',
allocators,
(mtpl_buffer*) source,
gen_name
);
const char c = source->data[source->cursor - 1];
if (result != MTPL_SUCCESS) {
goto cleanup_arg_buffer;
} else if (c != '>' && !is_whitespace(c)) {
result = MTPL_ERR_SYNTAX;
goto cleanup_arg_buffer;
}
sub_generator = mtpl_htable_search(gen_name->data, generators);
if (!sub_generator) {
result = MTPL_ERR_UNKNOWN_KEY;
goto cleanup_arg_buffer;
}
gen_name->cursor = 0;
result = perform_substitution(
*(void**) sub_generator,
allocators,
source,
generators,
properties,
arg_buffer,
true
);
if (result != MTPL_SUCCESS) {
goto cleanup_arg_buffer;
}
break;
case '{':
result = mtpl_buffer_extract_sub(
allocators,
false,
(mtpl_buffer*) source,
arg_buffer
);
if (result != MTPL_SUCCESS) {
goto cleanup_arg_buffer;
}
if (source->data[source->cursor] == '}') {
source->cursor++;
} else {
result = MTPL_ERR_SYNTAX;
goto cleanup_arg_buffer;
}
break;
case '}':
result = MTPL_ERR_SYNTAX;
goto cleanup_arg_buffer;
case ']':
if (!nested) {
result = MTPL_ERR_SYNTAX;
goto cleanup_arg_buffer;
}
source->cursor++;
nested = false;
// Fall through.
case '\0':
// End current substitution and return to parent.
goto finish_substitution;
case '\\':
// If next character is whitespace, don't read it.
if (is_whitespace(source->data[source->cursor + 1])) {
source->cursor += 2;
break;
}
// Escape next character if not 0.
if (!source->data[++(source->cursor)]) {
result = MTPL_ERR_SYNTAX;
goto cleanup_arg_buffer;
}
// Fall through.
default:
// Read into the arg buffer.
if (arg_buffer->cursor >= arg_buffer->size) {
MTPL_REALLOC_CHECKED(
allocators,
arg_buffer->data,
arg_buffer->size * 2, {
result = MTPL_ERR_MEMORY;
goto cleanup_arg_buffer;
}
);
arg_buffer->size *= 2;
}
arg_buffer->data[arg_buffer->cursor++]
= source->data[source->cursor++];
break;
}
}
finish_substitution:
if (nested) {
result = MTPL_ERR_SYNTAX;
goto cleanup_arg_buffer;
}
arg_buffer->cursor = 0;
result = generator(
allocators,
arg_buffer,
generators,
properties,
out_buffer
);
cleanup_arg_buffer:
mtpl_buffer_free(allocators, arg_buffer);
cleanup_gen_name:
mtpl_buffer_free(allocators, gen_name);
return result;
}
mtpl_result mtpl_substitute(
const char* source,
const mtpl_allocators* allocators,
mtpl_hashtable* generators,
mtpl_hashtable* properties,
mtpl_buffer* out_buffer
) {
mtpl_readbuffer buffer = {
.data = source,
.cursor = 0,
.size = 0
};
return perform_substitution(
mtpl_generator_copy,
allocators,
&buffer,
generators,
properties,
out_buffer,
false
);
}
|
C | #include <windows.h>
#include <stdio.h>
#define MAILSLOT_FORMAT "\\\\%s\\mailslot\\theslot"
void main(void)
{
HANDLE hSlot;
char aBuffer[50];
char aMailslotName[100];
DWORD dwWritten;
printf("Mailslot name: ");
scanf("%s", aBuffer);
sprintf(aMailslotName, MAILSLOT_FORMAT, aBuffer);
hSlot = CreateFile(aMailslotName, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hSlot)
return;
while (TRUE)
{
printf("Your command: ");
scanf("%s", aBuffer);
WriteFile(hSlot, aBuffer, strlen(aBuffer) + 1, &dwWritten, NULL);
if (!strcmp(aBuffer, "exit"))
break;
}
}
|
C | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <regex.h>
#include "cJSON.c"
#define MAX 80
#define PORT 12345
#define SA struct sockaddr
int grid[3][3];
regex_t regex;
int print_grid()
{
puts("");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
if (!grid[i][j])
printf(".");
else if (grid[i][j] == 1)
printf("X");
else
printf("O");
puts("");
}
puts("");
// Determine the winner
for (int i = 0; i < 3; i++)
{
if (grid[i][0] == grid[i][1] && grid[i][1] == grid[i][2] && grid[i][0] != 0)
return grid[i][0];
if (grid[0][i] == grid[1][i] && grid[1][i] == grid[2][i] && grid[0][i] != 0)
return grid[0][i];
}
if (grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2] && grid[1][1] != 0)
return grid[1][1];
if (grid[0][2] == grid[1][1] && grid[1][1] == grid[2][0] && grid[1][1] != 0)
return grid[1][1];
int sum = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
sum += grid[i][j];
if (sum == 13)
return -1;
return 0;
}
bool game_ended()
{
int winner = print_grid();
if (winner == 1)
{
puts("You lose.");
return true;
}
else if (winner == -1)
{
puts("Draw");
return true;
}
else if (winner == 2)
{
puts("You win.");
return true;
}
return false;
}
void play(int client_socket)
{
int n, match, x, y, winner;
char buffer[MAX], *message;
cJSON *coordinates;
while (true)
{
bzero(buffer, sizeof(buffer));
// Read the message from client and copy it to buffer
recv(client_socket, buffer, sizeof(buffer), 0);
// If the message starts with "exit" then server exits and chat ends
if ((strncmp(buffer, "exit", 4)) == 0)
{
printf("Server stopping...\n");
return;
}
// Interpret the message containing the coordinates
coordinates = cJSON_Parse(buffer);
x = cJSON_GetObjectItemCaseSensitive(coordinates, "x")->valueint;
y = cJSON_GetObjectItemCaseSensitive(coordinates, "y")->valueint;
grid[x][y] = 1;
cJSON_Delete(coordinates);
// See if game has ended
if (game_ended())
return;
bzero(buffer, sizeof(buffer));
while (true)
{
// Copy server message to the buffer
n = 0;
while ((buffer[n++] = getchar()) != '\n')
;
if (strncmp("exit", buffer, 4) == 0)
{
send(client_socket, buffer, sizeof(buffer), 0);
printf("Server stopping...\n");
return;
}
match = regexec(®ex, buffer, 0, NULL, 0);
if (!match)
{
x = buffer[0] - '1';
y = buffer[2] - '1';
if (!grid[x][y])
break;
}
}
grid[x][y] = 2;
// Create the message to transmit coordinates
coordinates = cJSON_CreateObject();
cJSON_AddNumberToObject(coordinates, "x", x);
cJSON_AddNumberToObject(coordinates, "y", y);
message = cJSON_Print(coordinates);
// Send the message to client
send(client_socket, message, strlen(message), 0);
cJSON_Delete(coordinates);
// See if game has ended
if (game_ended())
return;
}
}
// Driver function
int main()
{
regcomp(®ex, "[1-3],[1-3]", REG_EXTENDED);
int server_socket, client_socket;
struct sockaddr_in server, client;
// Create and verify socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1)
{
printf("Socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
// Assign IP and port
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(PORT);
// Bind newly created socket to given IP and verify
if ((bind(server_socket, (SA *)&server, sizeof(server))) != 0)
{
printf("Socket binding failed...\n");
exit(0);
}
else
printf("Socket successfully bound..\n");
// Now server is ready to listen and verify
if ((listen(server_socket, 5)) != 0)
{
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
// Accept the data packet from client and verify
socklen_t len = sizeof(client);
client_socket = accept(server_socket, (SA *)&client, &len);
if (client_socket < 0)
{
printf("Server accceptance failed...\n");
exit(0);
}
else
printf("Server acccepted the client..\n");
// Function for chatting between client and server
play(client_socket);
// Close the socket
shutdown(server_socket, SHUT_RDWR);
} |
C | #include "unicode/unum.h"
#include "unicode/ustring.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
UErrorCode status = U_ZERO_ERROR;
UNumberFormat *fmt = unum_open(UNUM_CURRENCY, NULL, 0, "en_GB", 0, &status);
int num;
UChar ures[255];
char res[255];
UChar gbp[] = { 'G', 'B', 'P', 0};
UChar eur[] = { 'E', 'U', 'R', 0};
if (U_FAILURE(status)) {
printf("FAIL: unum_open\n");
exit(1);
}
unum_setAttribute(fmt, UNUM_FRACTION_DIGITS, 4);
num = unum_getAttribute(fmt, UNUM_FRACTION_DIGITS);
printf("Digits: %d\n", num);
unum_formatDoubleCurrency(fmt, 123.45, gbp, ures, 254, NULL, &status);
if (U_FAILURE(status)) {
printf("FAIL: unum_formatDoubleCurrency\n");
exit(1);
}
u_strToUTF8(res, 254, NULL, ures, -1, &status);
printf("GBP: %s\n", res);
num = unum_getAttribute(fmt, UNUM_FRACTION_DIGITS);
printf("Digits: %d\n", num);
unum_formatDoubleCurrency(fmt, 123.45, eur, ures, 254, NULL, &status);
if (U_FAILURE(status)) {
printf("FAIL: unum_formatDoubleCurrency\n");
exit(1);
}
u_strToUTF8(res, 254, NULL, ures, -1, &status);
printf("EUR: %s\n", res);
num = unum_getAttribute(fmt, UNUM_FRACTION_DIGITS);
printf("Digits: %d\n", num);
}
|
C | /********************************************
* Pointer Arithemetic operations
* (a) Array elements are always stored in contiguous memory locations.
* (b) A pointer when incremented always points to an immediately next
* location of its type.
**************************************/
# include <stdio.h>
void proof();
int main()
{
int i = 3, *x;
float j = 1.5, *y;
char k = 'c', *z;
printf("\nValue of i = %d\n", i);
printf("Value of j = %f\n", j);
printf("Value of k = %c\n\n", k);
x = &i; // 1000
y = &j; // 2000
z = &k; // 3000
printf("Original address in x = %u\n", x);
printf("Original address in y = %u\n", y);
printf("Original address in z = %u\n\n", z);
x++; // == x = x + 1
y++;
z++;
printf("New address in x = %u\n", x);
printf("New address in y = %u\n", y);
printf("New address in z = %u\n\n", z);
printf("\n\n");
proof();
printf("\n");
return 0;
}
void proof(){
int num[] = { 24, 34, 12, 44, 56, 17 };
int i;
for ( i = 0 ; i <= 5 ; i++ )
{
printf("element %d at index %d ",num[i], i);
printf("address = %u\n", &num[i]);
}
} |
C | #include <stdlib.h>
#include "utone.h"
int ut_progress_create(ut_progress **p)
{
*p = malloc(sizeof(ut_progress));
return UT_OK;
}
int ut_progress_destroy(ut_progress **p)
{
free(*p);
return UT_OK;
}
int ut_progress_init(ut_data *ut, ut_progress *p)
{
p->nbars = 40;
p->skip = 1000;
p->counter = 0;
p->len = (uint32_t) ut->len;
return UT_OK;
}
int ut_progress_compute(ut_data *ut, ut_progress *p, UTFLOAT *in, UTFLOAT *out)
{
if(p->counter == 0 || ut->pos == p->len - 1) {
int n;
UTFLOAT slope = 1.0 / p->nbars;
if(ut->pos == 0) fprintf(stderr, "\e[?25l");
UTFLOAT percent = ((UTFLOAT)ut->pos / p->len);
fprintf(stderr, "[");
for(n = 0; n < p->nbars; n++) {
if(n * slope <= percent) {
fprintf(stderr, "#");
}else {
fprintf(stderr, " ");
}
}
fprintf(stderr, "] %.2f%%\t\r", 100 * percent);
}
if(ut->pos == p->len - 1) fprintf(stderr, "\n\e[?25h");
fflush(stderr);
p->counter++;
p->counter %= p->skip;
return UT_OK;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int bucket_union(int **, int cols, const int [cols]);
int **dynamic_alloc_2darray(int);//generate a 1 * cols 2D array
int **add_1_row(int**, int, int);//add a row to 2D array (must given cuurent size)
//(array name, how "many" rows it has, cols)
void scanfile(FILE *, int *, int *);//read the maximum cols needed and total rows
void Print(int, int cols, int[][cols]); //print DirectMapping only
int main()
{
int rows = 0, cols = 0, i = 0, j = 0;
char ch;
FILE *fp;
fp = fopen("bucket.in", "r");
if (fp == NULL)
{
printf("file cannot open");
exit(1);
}
scanfile(fp, &rows, &cols);//determine the size of array
rewind(fp);
printf("%d %d \n", rows, cols);
int DirectMapping[rows][cols], *p,
**NewMapping = dynamic_alloc_2darray(cols);
for (p = &DirectMapping[0][0]; p <= &DirectMapping[rows - 1][cols - 1]; p++)
*p = 0;//initalize to 0
add_1_row(NewMapping, 1, cols);
//store data into two dimensional array
while (fscanf(fp, "%d%c", &DirectMapping[i][j], &ch) != EOF)
{
j++;
if (ch == '\n') {j = 0; i++;} //change to '\r'for file generated in windows
}
Print(rows, cols, DirectMapping);
for (i = 0; i < 2; i++)
{
for (j = 0; j < cols; j++)
printf("%d ", NewMapping[i][j]);
printf("\n");
}
fclose(fp);
for (i = 0; i < 2; i++)
free(NewMapping[i]);
free(NewMapping);
// printf("\n");
return 0;
}
int bucket_union(int **NewMapping, int cols, const int DirectMapping[cols])
{
int i;
for (i = 0; i < cols; i++)
{
}
}
int new_mapping()
{
}
void print_result()
{
}
int ** dynamic_alloc_2darray(int cols)
{
int **array;
array = calloc(1 , sizeof(int *));
if (array == NULL)
{
printf("out of memory(1)\n");
exit(1);
}
array[0] = calloc(cols , sizeof(int));
if (array[0] == NULL)
{
printf("out of memory(2)\n");
exit(1);
}
return array;
}
int ** add_1_row(int ** array, int size, int cols)
{
array = realloc(array, (size + 1) * sizeof(int *));
array[size] = calloc(cols, sizeof(int));
if (array[size] == NULL)
{
printf("out of memory(3)\n");
exit(1);
}
return array;
}
void scanfile(FILE *fp, int *count_rows, int *max_cols)
{
int count_cols = 0;
char ch;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == ' ')
count_cols++;
if (ch == '\n')
{
(*count_rows)++;
if (count_cols > *max_cols)
*max_cols = count_cols;
count_cols = 0;
}
}
// (*count_rows)++; //delete it on linux
(*max_cols)++;
}
void Print(int rows, int cols , int array[][cols])
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
printf("%d ", array[i][j]);
printf("\n");
}
}
|
C | void moveZeroes(int* nums, int numsSize) {
// 效率不高的算法,多余计算量很多
/*
int i = 0, j;
while(nums[i] != 0 && i < numsSize)
i++;
if(i < numsSize - 1)
{
j = i + 1;
while(nums[j] == 0 && j < numsSize)
j++;
if(j != numsSize)
{
nums[i] = nums[j];
nums[j] = 0;
i++;
moveZeroes(nums+i, numsSize-i);
}
}
*/
// 效率较高的算法
int i = 0, j = 0;
while(j < numsSize)
{
if(nums[j] != 0)
{
nums[i] = nums[j]; //不需要在这里就将nums[i+1]赋为0,这个操作是多余的,因为现在赋为0之后,在后面的过程中有可能会被非零值覆盖掉,造成多余操作!!!
i++;
}
j++;
}
while(i < numsSize)
{
nums[i] = 0;
i++;
}
/* 下面的代码参考于网站:http://www.jianshu.com/p/f82a3dda76b8
int index = 0;
for(int i = 0;i<numsSize;i++)
{
if(nums[i] !=0)
{
nums[index++] = nums[i];
}
}
for(int i = index;i<numsSize;i++) {
nums[i] = 0;
}
*/
}
|
C | // binaschex - A library that supports converting ASCII/BINARY/HEX values
// expressed as strings. E.g. the form of '4142434445' (hex) is taken
// and converted to the binary represented by the hex digits. e.g.
// 'abcde'.
//
// (C) 2015 KB4OID Labs, A division of Kodetroll Heavy Industries
// File: binaschex.c - C Source file for binaschex
// Author: Kodetroll
// Date: April 2015
// Version: 0.99a (First to receive a version number)
//
// Includes code from strrep.c - C substring replacement by Drew Hess <[email protected]>.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "binaschex.h"
//=== Global Definitions ====================================================================================
//=== Global Variables ======================================================================================
char sbuf[250]; // for string processing (rpad, lpad, etc)
char tmpbuf[250]; // for file & printf operations
//=== Global Prototypes =====================================================================================
char* ucase(const char * s);
char* lcase(const char * s);
char* lpad(const char * s, int c, int len);
char* rpad(const char * s, int c, int len);
char* chomp(const char * s);
//=== Start of Utility functions ============================================================================
/* This method will convert any lowercase chars in a string
* to uppercase and return the string
*
*/
char*
ucase(const char * s)
{
//string n,y;
char x[250];
int c,i;
memset(x,0x00,sizeof(x));
strcpy(x,s);
memset(sbuf,0x00,sizeof(sbuf));
for (i=0;i<strlen(x);i++)
sbuf[i] = toupper(x[i]);
return(sbuf);
}
/* This method will convert any uppercase chars in a string
* to lowercase and return the string
*
*/
char*
lcase(const char * s)
{
//string n,y;
char x[250];
int c,i;
memset(x,0x00,sizeof(x));
strcpy(x,s);
memset(sbuf,0x00,sizeof(sbuf));
for (i=0;i<strlen(x);i++)
sbuf[i] = tolower(x[i]);
return(sbuf);
}
/* This method will pad the provided char string to the
* left, out to the specified length using the specified
* padding char. Returns the char string.
*/
char*
lpad(const char * s, int c, int len)
{
strcpy(sbuf,s);
if (len <= strlen(s))
return(sbuf);
do
{
memset(tmpbuf,0x00,sizeof(tmpbuf));
strcpy(tmpbuf,sbuf);
memset(sbuf,0x00,sizeof(sbuf));
sbuf[0] = c;
strcat(sbuf,tmpbuf);
} while(strlen(sbuf) <= len-1);
return(sbuf);
}
/* This method will pad the provided char string to the
* right, out to the specified length using the specified
* padding char. Returns the char string.
*/
char*
rpad(const char * s, int c, int len)
{
int i = strlen(s);
memset(sbuf,0x00,sizeof(sbuf));
//printf("s: %s\n",s);
if (len < strlen(s))
{
strncpy(sbuf,s,len);
//printf("sbuf1: %s\n",sbuf);
return(sbuf);
}
if (c == 0)
c = 0x20;
strcpy(sbuf,s);
//printf("sbuf2: %s\n",sbuf);
do { sbuf[i++] = c; } while (i < len);
//printf("sbuf3: %s\n",sbuf);
return(sbuf);
}
char*
chomp(const char * s)
{
int l = strlen(s);
int i = 0;
int num_ws;
char * y;
//memset(y,0x00,sizeof(y));
if ((strlen(s) == 0) || (s == NULL) || (s == ""))
return("");
y = strdup(s);
//printf("s: '%s' (%d)\n",s,strlen(s));
//printf("y: '%s' (%d)\n",y,strlen(y));
//show_hexdump("y",y);
int ws[] = { 0x00, 0x0a, 0x0d, '\t', ' ' };
//printf("sizeof: %d\n",sizeof(ws));
num_ws = sizeof(ws) / 4;
//printf("num_ws: %d\n",num_ws);
int o = 0;
do
{
o = 0;
//printf("l: %d, y[%d]: '%c' (%d)\n",l,l,y[l],y[l]);
for (i=0;i<num_ws;i++)
if (y[l] == ws[i])
o = 1;
//printf("o: %d\n",o);
if (o == 1)
y[l] = 0x00;
l--;
} while (o == 1);
//printf("y: '%s' (%d)\n",y,strlen(y));
//show_hexdump("y",y);
return(y);
}
/*
* This function returns string s1 if string s2 is an empty string, or
* if s2 is not found in s1. If s2 is found in s1, the function
* returns a new null-terminated string whose contents are identical
* to s1, except that all occurrences of s2 in the original string s1
* are, in the new string, replaced by the string s3. The caller owns
* the new string.
*
* Strings s1, s2, and s3 must all be null-terminated strings. If any
* of s1, s2, or s3 are NULL, the function returns NULL, indicating an
* error condition. If any other error occurs, the function returns
* NULL.
*
* This code is written pedantically, primarily so that asserts can be
* used liberally. The code could certainly be optimized and/or made
* less verbose, and I encourage you to do that if you use strstr in
* your production code, once you're comfortable that it functions as
* intended. Each assert makes plain an invariant condition that is
* assumed to be true by the statement(s) that immediately follow the
* assert. Some of the asserts are trivially true, as written, but
* they're included, nonetheless, in case you, in the process of
* optimizing or adapting the code for your own purposes, make a
* change that breaks an assumption made downstream by the original
* code.
*/
// strrep() substring replacement by Drew Hess <[email protected]>.
char*
strrep(const char *s1, const char *s2, const char *s3)
{
if (!s1 || !s2 || !s3)
return 0;
size_t s1_len = strlen(s1);
if (!s1_len)
return (char *)s1;
size_t s2_len = strlen(s2);
if (!s2_len)
return (char *)s1;
/*
* Two-pass approach: figure out how much space to allocate for
* the new string, pre-allocate it, then perform replacement(s).
*/
size_t count = 0;
const char *p = s1;
assert(s2_len); /* otherwise, strstr(s1,s2) will return s1. */
do {
p = strstr(p, s2);
if (p) {
p += s2_len;
++count;
}
} while (p);
if (!count)
return (char *)s1;
/*
* The following size arithmetic is extremely cautious, to guard
* against size_t overflows.
*/
assert(s1_len >= count * s2_len);
assert(count);
size_t s1_without_s2_len = s1_len - count * s2_len;
size_t s3_len = strlen(s3);
size_t newstr_len = s1_without_s2_len + count * s3_len;
if (s3_len &&
((newstr_len <= s1_without_s2_len) || (newstr_len + 1 == 0)))
/* Overflow. */
return 0;
char *newstr = (char *)malloc(newstr_len + 1); /* w/ terminator */
if (!newstr)
/* ENOMEM, but no good way to signal it. */
return 0;
char *dst = newstr;
const char *start_substr = s1;
size_t i;
for (i = 0; i != count; ++i) {
const char *end_substr = strstr(start_substr, s2);
assert(end_substr);
size_t substr_len = end_substr - start_substr;
memcpy(dst, start_substr, substr_len);
dst += substr_len;
memcpy(dst, s3, s3_len);
dst += s3_len;
start_substr = end_substr + s2_len;
}
/* copy remainder of s1, including trailing '\0' */
size_t remains = s1_len - (start_substr - s1) + 1;
assert(dst + remains == newstr + newstr_len + 1);
memcpy(dst, start_substr, remains);
assert(strlen(newstr) == newstr_len);
return newstr;
}
unsigned int
cvt2int(char* ibuf)
{
char *p;
int sum = 0;
int i,k,n,b;
//printf("ibuf(%d): '%s'\n",strlen(ibuf),ibuf);
p = strdup(lpad(ibuf,'0',8));
//printf("p(%d): '%s'\n",strlen(p),p);
for (i=0;i<strlen(ibuf);i++)
{
k = strlen(ibuf)-i-1;
n = hex2int(ibuf[i]);
b = pow (16, k);
//printf("i: %d, k: %d, strlen(ibuf): %d, ibuf[%d]: '%c' (0x%02x), n: %d, b: 0x%02x \n",i,k,strlen(ibuf),k,ibuf[i],ibuf[i],n,b);
sum+= n * b;
//printf("sum: '%d' 0x%02x\n",sum,sum);
}
//printf("sum: '%d' 0x%02x\n",sum,sum);
return(sum);
}
/* Converts a single char representing a hex number '0-9,A-F,a-f'
* to it's numeric integer value. e.g. '1' (0x31) returns 0x01
*
*/
int
hex2int(char c)
{
switch(c)
{
case '0':
return(0);
break;
case '1':
return(1);
break;
case '2':
return(2);
break;
case '3':
return(3);
break;
case '4':
return(4);
break;
case '5':
return(5);
break;
case '6':
return(6);
break;
case '7':
return(7);
break;
case '8':
return(8);
break;
case '9':
return(9);
break;
case 'a':
return(10);
break;
case 'b':
return(11);
break;
case 'c':
return(12);
break;
case 'd':
return(13);
break;
case 'e':
return(14);
break;
case 'f':
return(15);
break;
case 'A':
return(10);
break;
case 'B':
return(11);
break;
case 'C':
return(12);
break;
case 'D':
return(13);
break;
case 'E':
return(14);
break;
case 'F':
return(15);
break;
default:
return(0);
break;
}
}
/* This function takes the contents of the input buffer (ibuf) and copies them to
* the output buffer (obuf), converting the expressed hexadecimal value of the
* input buffer to it's ASCII character, on the fly. E.g. '41424364' becomes
* 'ABCd'. The return value of the function is the number of characters in the
* output buffer after conversion (obuf length).
*
*/
int
hex2asc(char * ibuf, char * obuf)
{
int i,j,c;
//char c;
// Convert string from Hex ASCII chars to binary form
memset(obuf,0x00,sizeof(obuf));
i = 0;
j = 0;
do
{
c = hex2int(ibuf[i++]) * 16;
c += hex2int(ibuf[i++]);
if (unpar_flag == 1)
if (c > 0x7f)
c -= 0x80;
if (print_flag == 1)
if ((c < 0x20) || (c > 0x7f))
c = 0x2e;
obuf[j++] = (char)c;
} while(i < strlen(ibuf));
return(j);
}
/* This function takes the contents of the input buffer (ibuf) and copies them to
* the output buffer (obuf), converting the integer value of the ASCII character
* in the input buffer to it's hex representation, on the fly. E.g. 'ABCd' becomes
* '41424364'. The return value of the function is the number of characters converted
* to the output buffer (ibuf length).
*
*/
int
asc2hex(char * ibuf, char * obuf)
{
int i,j,k;
char tmp[4];
memset(obuf,0x00,sizeof(obuf));
i = 0;
j = 0;
do
{
k = ibuf[i++];
if (unpar_flag == 1)
if (k > 0x7F)
k -= 0x80;
sprintf(tmp,"%02x",k);
strncat(obuf,tmp,strlen(tmp));
} while (i<strlen(ibuf));
return(i);
}
/*
* This function provides a generalized hexdump facility. Data to be displayed should be provided
* via the *Data pointer. The length of the data string should be included in DataLen. Making this
* zero will use the strlen value, making this -1 will use the sizeof value. This value must be
* provided if there are ASCII NULs in the string, as string processing will be terminated at the
* first NULL ('\0') found, unless the DataLen value is provided with a non-zero positive value.
* Output to the screen will be od the standard hexdump Format:
* 'MMMM: HH HH HH ... HH |ASCII.STRING VALUES|'
*
*/
void
HexDataDump(int DataLen, unsigned char * Data)
{
int n,i,j;
unsigned char tmp[15];
unsigned char tmp1[100];
unsigned char tmp2[100];
i = 0;
do
{
memset(tmp1,0x00,sizeof(tmp1));
memset(tmp2,0x00,sizeof(tmp2));
sprintf(tmp1,"%04x: ",i);
for (n=0;n<HEXDUMP_LINE_SIZE;n++)
{
if (i >= DataLen)
sprintf(tmp,"%s"," ");
else
sprintf(tmp,"%02x ",Data[i]);
strcat(tmp1,tmp);
if ((Data[i] < 0x20) || (Data[i] > 0x7F))
sprintf(tmp2+strlen(tmp2),"%c",'.');
else
sprintf(tmp2+strlen(tmp2),"%c",Data[i]);
i++;
}
printf("%s",tmp1);
printf("|%s|",tmp2);
printf("\n");
} while (i < DataLen);
printf("\n");
}
|
C | #include "libft.h"
void ft_putnbr(int nb)
{
if (nb < 0){
ft_putchar('-');
nb = -nb;
}
if (nb == 0)
ft_putchar('0');
if (nb / 10)
ft_putnbr(nb / 10);
ft_putchar(nb%10 + '0');
}
/*int main()
{
int nb;
int res;
nb = 42;
ft_putnbr(nb);
}
if (nb == (0))
{
int nb = 48;
return ft_putchar(nb);
}
if (nb == (1))
{
int nb = 49;
return ft_putchar(nb);
}
if (nb == (2))
{
int nb = 50;
return ft_putchar(nb);
}
if (nb == (3))
{
int nb = 51;
return ft_putchar(nb);
}
if (nb == (4))
{
int nb = 52;
return ft_putchar(nb);
}
if (nb == (5))
{
int nb = 53;
return ft_putchar(nb);
}
if (nb == (6))
{
int nb = 54;
return ft_putchar(nb);
}
if (nb == (7))
{
int nb = 55;
return ft_putchar(nb);
}
if (nb == (8))
{
int nb = 56;
return ft_putchar(nb);
}
if (nb == (9))
{
int nb = 57;
return ft_putchar(nb);
}
*/
|
C | #include <stdio.h>
#define XMAX 80
#define YMAX 24
unsigned char cells[YMAX][XMAX];
static void
consoleclear(void)
{
printf("\033[2J\033[2H");
}
static void
display(void)
{
int x, y;
consoleclear();
y = 0;
while (y < YMAX) {
x = 0;
while (x < XMAX) {
putchar(cells[y][x]);
x = x + 1;
}
putchar('\n');
y = y + 1;
}
}
int
main(int argc, char *argv[])
{
int x, y;
y = 0;
while (y < YMAX) {
x = 0;
while (x < XMAX) {
cells[y][x] = ' ';
x = x + 1;
}
y = y + 1;
}
consoleclear();
cells[3][8] = 'X';
cells[3][9] = 'X';
cells[3][10] = 'X';
cells[3][11] = 'X';
cells[3][12] = 'X';
cells[3][13] = 'X';
cells[3][14] = 'X';
cells[3][15] = 'X';
display();
return 0;
}
|
C | /*
this program initializes 2 signal actions, assigns same handler to both actions.
while action1 is handled, SIGUSR2 will be blocked on delivery.
*/
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <wait.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#define MAXCHILD 5
#define MAXIMUM 100
int total=0;
char path[20];
pid_t pid[MAXCHILD];
// "handler1" is handler function for action1 and action2, returns void
void handler1(int signo)
{
int pipe;
char buffer[20];
switch(signo)
{
/* handling SIGUSR1 takes one second
during this time if SIGUSR2 will be blocked on delivery. */
case SIGUSR1:
pipe=open(path,O_RDWR);
read(pipe,buffer,20);
total += atoi(buffer);
if(total >= MAXIMUM)
{
for (int i=0;i<MAXCHILD;i++)
{
kill(pid[i],SIGKILL);
printf("child %d killed \n", i);
}
printf("program has finished successfully \n");
exit(0);
}
printf("SIGUSR1 received and total is : %d \n", total);
break;
}
}
int main()
{
int pipe;
//initializing sigaction structures, action1 and action2 both use handler1
struct sigaction action1;
sigset_t set1;
sigemptyset(&set1);
//define signal set named "set1"
//making set1 empty
//adding SIGUSR2 to set1
action1.sa_handler = handler1;
action1.sa_mask = set1;
//set1 includes SIGUSR2, it means if during handling action1
//SIGUSR2 will be blocked on delivery.
action1.sa_flags = 0;
int inchild=0;
//initializng parent process before fork()
sigaction(SIGUSR1,(struct sigaction *) &action1,NULL);
pid_t parent=getpid();
sprintf(path,"Question2");
mkfifo(path,0777);
for ( int i=0;i<MAXCHILD;i++)
{
pid[i]=fork();
if(pid[i]==0)
{
inchild=1;
break;
}
}
srand(time(NULL));
while(inchild)
{
//child sends SIGUSR1 and immediately SIGUSR2 to parent every one second
pipe = open(path,O_RDWR);
int t = rand()%10;
sleep(t);
char buf[20];
sprintf(buf,"%d",t);
write(pipe,buf,20);
kill(parent,SIGUSR1);
}
while(inchild==0);
return 0;
}
|
C | #include "ioAT89C51.h"
#include "intrinsics.h"
//#include "reg52.h"
// Define pins
#define Dirctl (P0_bit.P0_7)
#define runctl (P3_bit.P3_0) // run/stop
#define run (P3_bit.P3_1) // run/stop control
#define Dir1 (P3_bit.P3_2) // direction-1
#define Dir2 (P3_bit.P3_3) // direction-2
#define Inc (P3_bit.P3_4) // speed up
#define Dec (P3_bit.P3_5) // speed down
#define Dir (P3_bit.P3_6) // motor direction control
#define PWM (P3_bit.P3_7) // PWM control
// Define new types
typedef unsigned int u16;
typedef unsigned char u8;
void delay(u16);
void main(void){
int speed;
// Select initial direction and speed.
speed = 250;
Dirctl = 0;
run = 1;
Dir1 = 1;
Dir = 1;
// Main control loop
while(1){
// Read from keyboard
if(!runctl){
delay(1000);
if(!runctl){
run = 1 - run;
}
}
if(!Dir1){
delay(1000);
if(!Dir1){
Dirctl = 1;
speed = 250;
}
}
if(!Dir2){
delay(1000);
if(!Dir2){
Dirctl = 0;
speed = 250;
}
}
if(!Inc){
delay(1000);
if(!Inc){
if(Dir){
speed = speed > 0 ? speed - 50 : 0;
}
else{
speed = speed < 500 ? speed + 50 : 500;
}
}
}
if(!Dec){
delay(1000);
if(!Dec){
if(Dir){
speed = speed < 500 ? speed + 50 : 500;
}
else{
speed = speed > 0 ? speed - 50 : 0;
}
}
}
// PWM
PWM=1;
delay(speed);
PWM=0;
delay(500-speed);
}
}
void delay(u16 i){
while(i--);
}
|
C | #include <stdio.h>
#include <stdlib.h>
/* Defines a tf abstract data type (ADT) */
typedef struct timeFormat tf;
/* It receives a double 'seconds' that represents an amount of time
and returns a tf ADT pointer. In the backgrounds it partitionalizes
theses seconds into days, hours, minutes, seconds, miliseconds and microseconds */
tf *timeInit(double seconds);
/* It receives a tf pointer 'time' and
prints the time*/
void printTime(tf *time);
/* It kills a tf time */
void timeKill(tf *time);
/* It receives a tf time pointer
and returns the its number of days */
int getDays(tf *time);
/* It receives a tf time pointer
and returns the its number of hours */
int getHours(tf *time);
/* It receives a tf time pointer
and returns the its number of minutes */
int getMins(tf *time);
/* It receives a tf time pointer
and returns the its number of seconds */
int getSecs(tf *time);
/* It receives a tf time pointer
and returns the its number of miliseconds */
int get_ms(tf *time);
/* It receives a tf time pointer
and returns the its number of microseconds */
int get_us(tf *time); |
C | #include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int my_atoi(const char *str) {
int i;
int result = 0;
int bit = 1; // 初始化為個位,即乘以 1
// 檢查是否包含非數字字符,若找到則返回 0
for (i = 0; str[i] != '\0'; i++) {
if (!isdigit(str[i])) {
return 0;
}
}
// 此時,str[i - 1]即是個位上的數字
for (int j = i - 1; j >= 0; j--, bit *= 10) {
result += (str[j] - '0') * bit;
}
return result;
}
int main(void) {
printf("%d\n", my_atoi("1994") + 1);
return 0;
} |
C | #include<stdio.h>
void calcular_media (int *A, int *B){
if(*A<*B){
int aux = *A;
*A = (*A+*B)/2;
*B = (aux+*B)%2;
}else{
int aux = *B;
*B = (*A+*B)/2;
*A = (*A+aux)%2;
}
}
void main(void){
int A, B;
scanf("%d %d", &A, &B);
calcular_media (&A, &B);
printf("A = %d\nB = %d", A, B);
} |
C | #include <stdio.h>
void mergeSort(int arr[], int temp[], int start, int end);
void merge(int arr[], int temp[], int start, int mid, int end);
int main(){
int arr[5] = {5,3, 6, 0, 1};
int temp[5];
mergeSort(arr, temp, 0, 4);
for(int i =0; i < 5; i++)
printf("%d ", arr[i]);
}
void mergeSort(int arr[], int temp[], int start, int end){
if(start < end){
int mid = (start+end)/2;
mergeSort(arr, temp, start, mid);
mergeSort(arr, temp, mid+1, end);
merge(arr, temp, start, mid, end);
}
}
void merge(int arr[], int temp[], int start, int mid, int end){
for(int i = start; i <= end; i++)
temp[i] = arr[i];
int index = start;
int part1 = start;
int part2 = mid+1;
while(part1<= mid && part2<=end){
if(temp[part1] < temp[part2]){
arr[index] = temp[part1];
part1++;
}else{
arr[index] = temp[part2];
part2++;
}
index++;
}
for(int i = 0; i <= mid-part1;i++)
arr[index+i] = temp[i+part1];
}
|
C | /* Check stack variations */
#include <stdio.h>
#include <stdlib.h>
/* $begin scheck-c */
int main() {
int local;
printf("local at %p\n", &local);
return 0;
}
/* $end scheck-c */
|
C | #include <stdio.h>
#include <string.h>
#define MAX_C (105)
#define infty (0x3f3f3f3f)
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
int c,s,q;
int custo[MAX_C][MAX_C];
void floyd()
{
int i,j,k;
int temp;
for (i=0; i<MAX_C; ++i)
custo[i][i]=0;
for (k=0; k<c; ++k)
for (i=0; i<c; ++i)
for (j=0; j<c; ++j)
{
temp = max(custo[j][k],custo[k][i]);
custo[i][j] = min(custo[i][j],temp);
}
}
int main()
{
int i,x,y,z;
int v=0;
/*printf("%d %#x",0x3f3f3f3f,0x3f3f3f3f);*/
memset(custo,infty,sizeof (custo));
while (scanf("%d%d%d",&c,&s,&q) == 3)
{
if (!(c || s || q))
break;
if(v)
printf("\n");
for (i=0; i<s; ++i)
{
scanf("%d%d%d",&x,&y,&z);
--x,--y;
custo[x][y]=z;
}
floyd();
printf("Case #%d\n",++v);
for (i=0; i<q-1; ++i)
{
scanf("%d%d",&x,&y);
--x,--y;
custo[x][y]==infty ? puts("no path") : printf("%d\n",custo[x][y]);
}
scanf("%d%d",&x,&y);
x--,y--;
custo[x][y]==infty? printf("no path\n") : printf("%d\n",custo[x][y]);
memset(custo,infty,sizeof (custo));
}
return 0;
}
|
C | #include <stdio.h>
#include "calc.h"
#include <time.h>
const int width = 15; // 横幅
const int height = 15; // 縦幅
const int start_x = 0; // 開始x
const int start_y = 7; // 開始y
const int goal_x = 14; // 終点x
const int goal_y = 7; // 終点y
int main (void) {
clock_t start = clock();
// グリッドを生成
Grid* board_start = generate_board(width, height, start_x, start_y, goal_x, goal_y);
// 壁を描く部分
for (int i = 1; i < 14; i++) {
set_obstacle(13, i);
set_obstacle(i, 13);
}
for (int i = 8; i < 13; i++) {
set_obstacle(1, i);
}
for (int i = 2; i < 13; i++) {
set_obstacle(i, 8);
}
for (int i = 0; i < 12; i++) {
set_obstacle(i, 6);
set_obstacle(i+1, 4);
set_obstacle(i, 2);
}
// 計算する
int d = calc_distance(board_start);
if (d > 0) {
printf("%s, min distance: %d\n", mode, d);
traverse();
printf("\nBOARD:\n");
printf("\033[036mIn exlpore queue: \t(Number)\n");
printf("\033[033mExplored Terrain: \t(Number)\n");
printf("\033[031mOptimized Path: \t(Number)(Arrow)\n");
printf("\033[35mObstacle:\t\t++++\033[00m\n");
printf("Unexplored Terrain:\t*\n");
print_board();
} else {
printf("%s: no path found!\n", mode);
}
clear_board();
printf("total execution time: %f\n", (float)(clock() - start) / CLOCKS_PER_SEC);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
int numero1=9;
float numero2;
char letra;
float suma;
printf("Ingrese un numero entero:");
scanf("%d", & numero1);
printf("Ingrese UN numero con Coma: ");
scanf("%f", & numero2);
printf("indique una letra: ");
letra=getche();
scanf("%c",&letra);
suma= numero1+numero2;
printf("el Numero entero Es: %d y el numero flotante es: %.0f",numero1,numero2);
printf("\n resultado de la suma es de: %.2f",suma);
printf("\n la letra indicada es: %c",letra);
return 0;
}
|
C |
#include <unistd.h>
#include <stdio.h>
#include <dart.h>
#include "../utils.h"
#define REPEAT 5
int main(int argc, char* argv[])
{
int i;
char buf[200];
dart_ret_t ret;
dart_unit_t myid;
size_t size;
dart_init(&argc, &argv);
dart_myid(&myid);
dart_size(&size);
fprintf(stderr, "Hello World, I'm %d of %d\n",
myid, size);
dart_gptr_t gptr = DART_GPTR_NULL;
for( i=0; i<REPEAT; i++ ) {
ret = dart_memalloc( 100, &gptr );
if( ret==DART_OK ) {
GPTR_SPRINTF(buf, gptr);
fprintf(stderr, "dart_memalloc worked: %s\n", buf);
}
if( ret!=DART_OK ) {
fprintf(stderr, "dart_memalloc did not work!\n");
}
}
dart_exit();
}
|
C | #include "Params.h"
#include "Misc.h"
#include "Sonar.h"
#include <errno.h> // gestion minimale des erreurs
#include <fcntl.h> // Pour le flag NON_BLOCK
#include <stdio.h>
int atoi(const char * str);
float atof(const char * str);
void close(int id);
int system(const char *string);
void usleep(int us);
char *strerror(int errnum);
int read(int id, unsigned char* buf, int length);
void lireTrameSonar();
//
// Variables statiques du sonar
//
int derniereAltitudeMoyenneEstValable;
int nbValeursValables;
int indexDerniereAltitude;
int fdSonar;
int indexEcritureSonar;
int indexLectureSonar;
int estInitialiseSonar;
unsigned char bufferCircuSonar[32]; // > SONAR_TAILLE_BUFFER
unsigned char bufferPortSonar[32]; // > SONAR_TAILLE_TRAME
float derniereAltitudeMoyenne;
float dernieresAltitudes[32]; // >= DUREE_MOYENNAGE_ALTITUDE
//
// Variables prédéclarés pour éviter les temps d'allocation, elles sont initialisé avant chaque utilisation
//
float alti;
char valChar[4]; // Stocke temporairement la valeur sous forme char
int ret;
int donneesDisponibles;
int ancAltiPouces;
int altiPouces;
void Sonar_Initialise(int dev) {
printf("Création serveur sonar...\n");
// /usr/local/sbin/
if (SONAR_IRQ == 200) {
system("xuartctl --port=1 --speed=9600 --server --irq=200hz");
} else if (SONAR_IRQ == 300) {
system("xuartctl --port=1 --speed=9600 --server --irq=300hz");
} else if (SONAR_IRQ == 400) {
system("xuartctl --port=1 --speed=9600 --server --irq=400hz");
} else {
system("xuartctl --port=1 --speed=9600 --server");
}
usleep(100000);
if (dev == -1) { // Laisser l'utilisateur choisir
dev = askIntValue("Numéro device ci dessus");
}
char* adresse;
if (dev == 0) {
adresse = "/dev/pts/0";
} else if (dev == 1) {
adresse = "/dev/pts/1";
} else if (dev == 2) {
adresse = "/dev/pts/2";
} else if (dev == 3) {
adresse = "/dev/pts/3";
} else {
printf("ERREUR GRAVE: DEVICE NON DANS LA LISTE");
return;
}
printf("Device sonar: %i\n", dev);
printf("Ouverture port sonar...");
fdSonar = open(adresse, O_NONBLOCK); // O_RDWR |
printf(" OK\n");
fflush(stdout);
indexEcritureSonar = 0;
indexLectureSonar = 0;
freqSonar = 0;
valChar[3] = '\0';
altiPouces = 0;
ancAltiPouces = 0;
nbValeursValables = 0;
indexDerniereAltitude = 0;
derniereAltitudeMoyenne = 0.0;
derniereAltitudeMoyenneEstValable = 0;
estInitialiseSonar = 1;
}
void Sonar_Termine() {
if (estInitialiseSonar) {
printf("Fermeture port sonar...");
close(fdSonar);
printf(" OK\n");
estInitialiseSonar = 0;
}
}
void Sonar_CheckData(int keepIt) {
if (!estInitialiseSonar) {
return;
}
if (!Misc_HasData(fdSonar)) {
return;
} // Pas optimal
ret=read(fdSonar, bufferPortSonar, SONAR_TAILLE_TRAME);
if (!keepIt) {
return;
}
if (ret<0 && ret !=EAGAIN) {
// errno==11 correspond a "ressource indisponible" = pas de données !
//
// ERREUR GRAVE - Gestion é faire
//
printf("\nERREUR LECTURE SONAR: %s (errno=%i)\n", strerror(errno),
errno);
} else if (ret==EAGAIN) {
//
// Pas de données, pas grave on retourne
//
} else {
//
// On a des données
//
//--Etape 1: Recopions les dans bufferCircuSonar
for (i = 0; i < ret; i++) {
bufferCircuSonar[indexEcritureSonar] = bufferPortSonar[i];
indexEcritureSonar++;
if (indexEcritureSonar == SONAR_TAILLE_BUFFER) {
indexEcritureSonar = 0;
}
}
//--Etape 2: Calculons le nombre de données disponibles
donneesDisponibles = indexEcritureSonar - indexLectureSonar;
if (donneesDisponibles < 0)
donneesDisponibles += SONAR_TAILLE_BUFFER;
//--Etape 3: Recherchons la trame
while (donneesDisponibles >= SONAR_TAILLE_TRAME) {
// La trame est de type 82, A, B, C, 13
// avec A,B,C l'écriture de la dist en ASCII(13 = "\n")
if (bufferCircuSonar[indexLectureSonar] == 82) {
// 82 ASCII == 'R'
//--Début d'une trame
lireTrameSonar();
indexLectureSonar += SONAR_TAILLE_TRAME;
freqSonar++;
} else {
//--Pas le début d'une trame
indexLectureSonar++; // Avanéons l'index d'un cran
recherchesSonar++; // pour trouver le début
}
//--Maj des index
if (indexLectureSonar >= SONAR_TAILLE_BUFFER) {
indexLectureSonar -= SONAR_TAILLE_BUFFER;
}
if (0 && NouvelleTrameSonar) {
// Arretons ici la boucle
donneesDisponibles = - 1;
} else {
// Recalculs le nombre de données disponibles
donneesDisponibles = indexEcritureSonar - indexLectureSonar;
if (donneesDisponibles < 0) {
donneesDisponibles += SONAR_TAILLE_BUFFER;
}
}
}
}
}
void lireTrameSonar() {
if (NouvelleTrameSonar) {
erreursSonar++;
}
valChar[0] = bufferCircuSonar[(indexLectureSonar + 1) % SONAR_TAILLE_BUFFER];
valChar[1] = bufferCircuSonar[(indexLectureSonar + 2) % SONAR_TAILLE_BUFFER];
valChar[2] = bufferCircuSonar[(indexLectureSonar + 3) % SONAR_TAILLE_BUFFER];
altiPouces = atoi(valChar);
if (altiPouces == 0) {
erreursSonar++;
}
//
// Saut maxi: MAX_SONAR_JUMP
//
if (altiPouces > ancAltiPouces + SONAR_SAUT_MAXI) {
altiPouces = ancAltiPouces + SONAR_SAUT_MAXI;
} else if (altiPouces < ancAltiPouces - SONAR_SAUT_MAXI) {
altiPouces = ancAltiPouces - SONAR_SAUT_MAXI;
}
ancAltiPouces = altiPouces;
SonarTropBas = 0;
SonarTropHaut = 0;
if (altiPouces <= 6) {
// Le sonar est trop proche du sol
SonarTropBas = 1;
nbValeursValables = 0;
VitLRTA[3] = 0.0;
PosLRTA[3] = 0.0;
derniereAltitudeMoyenneEstValable = 0;
} else if (altiPouces >= 250) { // En réalité c'est 254,
// mais on prend 250 pour etre tranquille
// Le sonar est trop loin du sol
SonarTropHaut = 1;
nbValeursValables = 0;
VitLRTA[3] = 0.0;
PosLRTA[3] = 0.01 * 2.54 * 250.0;
derniereAltitudeMoyenneEstValable = 0;
} else {
// Le sonar est dans sa plage de fonctionnement
//
//
//--Sytéme de moyenne sur l'altitude
//
alti = 0.01F * 2.54F * (float)altiPouces; // Conversion de pouces en métres
nbValeursValables++;
dernieresAltitudes[indexDerniereAltitude] = alti;
indexDerniereAltitude++;
if (indexDerniereAltitude == DUREE_MOYENNAGE_ALTITUDE) {
indexDerniereAltitude = 0;
}
if (nbValeursValables >= DUREE_MOYENNAGE_ALTITUDE) {
// Obtention de l'altitude par moyennage
PosLRTA[3] = 0.0;
for (i = 0; i < DUREE_MOYENNAGE_ALTITUDE; i++) {
PosLRTA[3] += dernieresAltitudes[i];
}
PosLRTA[3] /= (float)DUREE_MOYENNAGE_ALTITUDE;
PosLRTA[3] -= SONAR_ALTI_MINI;
if (derniereAltitudeMoyenneEstValable) {
// Obtention de la vitesse par dérivation sur les 2 dernieres moyennes
VitLRTA[3] = INVERSE_INTERVALLE_TEMPS_DERIVATION_SONAR
* (PosLRTA[3] - derniereAltitudeMoyenne);
} else {
VitLRTA[3] = 0.0F;
}
derniereAltitudeMoyenne = PosLRTA[3];
derniereAltitudeMoyenneEstValable = 1;
nbValeursValables = DUREE_MOYENNAGE_ALTITUDE; // Empeche le compteur d'exploser
} else {
// On a pas encore assez de valeurs valables, attendons...
// On garde l'ancienne valeur de la position !!
// (Sinon on remettrai a zéro en cas de trop haut !!)
VitLRTA[3] = 0.0;
}
}
NouvelleTrameSonar = 1;
}
|
C | /**
* This file, alder_file_mkdir.c, is part of alder-file.
*
* Copyright 2013 by Sang Chul Choi
*
* alder-file is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alder-file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with alder-file. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include "bstrlib.h"
#include "alder_cmacro.h"
#include "alder_file_exist.h"
#include "alder_file_isfile.h"
#include "alder_file_getcwd.h"
#include "alder_file_mkdir.h"
/* This function creates directories.
* returns
* 0 on success
* 1 if an error occurs.
*/
int alder_file_mkdir(const char *path)
{
int s = 0;
mode_t mode = ALDER_FILE_DEFAULT_MODE;
bstring bpath = bfromcstr(path);
if (bpath == NULL) {
return ALDER_STATUS_ERROR;
}
if (bpath->data[0] != '/') {
// Get the current directory.
// The following four lines can tolerate any errors.
bstring bbuf = alder_file_getcwd();
bconchar(bbuf, '/');
bconcat(bbuf, bpath);
s = bassign(bpath, bbuf);
if (s == BSTR_ERR) {
bdestroy(bpath);
return ALDER_STATUS_ERROR;
}
bdestroy(bbuf);
}
bstring bslash = bfromcstr("/");
if (bslash == NULL) {
bdestroy(bpath);
return ALDER_STATUS_ERROR;
}
int pslash = binstr(bpath, 1, bslash);
while (pslash != BSTR_ERR) {
// Check if the directory exists.
bpath->data[pslash] = '\0';
int s = alder_file_exist((const char*)bpath->data);
if (s == 0) {
if(mkdir((const char*)bpath->data, mode) == -1 && errno != EEXIST) {
bdestroy(bslash);
bdestroy(bpath);
return ALDER_STATUS_ERROR;
}
}
bpath->data[pslash] = '/';
pslash = binstr(bpath, pslash + 1, bslash);
}
bdestroy(bslash);
s = alder_file_exist(bdata(bpath));
if (s == 0) {
if(mkdir(bdata(bpath), mode) == -1 && errno != EEXIST) {
bdestroy(bpath);
return ALDER_STATUS_ERROR;
}
} else {
s = alder_file_isfile(bdata(bpath));
if (s == 1) {
fprintf(stderr, "Not a directory: %s\n", bdata(bpath));
bdestroy(bpath);
return ALDER_STATUS_ERROR;
}
}
bdestroy(bpath);
return ALDER_STATUS_SUCCESS;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <omp.h>
int compare(double* a, double* b, int n){
for(int i = 0; i < n; i++){
if( a[i] != b[i] )
return 0;
}
return 1;
}
int main(int argc, char const *argv[]){
printf("\nMultiplicación de vectores elemento a elemento\n--------------------\n");
int num_hilos = atoi(argv[1]);
omp_set_num_threads(num_hilos);
printf("\nSe ejecuta con %i hilo(s)\n", num_hilos);
int size = 100000000;
double* a = malloc(size*sizeof(double));
double* b = malloc(size*sizeof(double));
double* c = malloc(size*sizeof(double));
double* d = malloc(size*sizeof(double));
for( int i = 0 ; i < size ; i++ ){
d[i]=a[i]*b[i];
}
double t_ini = omp_get_wtime();
#pragma omp parallel for
for( int i = 0 ; i < size ; i++ ){
c[i]=a[i]*b[i];
}
double t_fin = omp_get_wtime();
// Verifica que ambas soluciones son correctas
if( compare(c, d, size) == 0 )
printf("\nError in parallel operation\n\n");
else
printf("\nDuración de la operación: %f segundos con vectores de tamaño %d\n\n", t_fin - t_ini, size);
free(a);
free(b);
free(c);
free(d);
return 0;
}
|
C | #include <kernel/kheap.h>
#include <kernel/paging.h>
#include "frame.h"
#include <kernel/tty.h>
//static functions
static void expandHeap(uint32_t new_size, heap_t* heap);
static uint32_t contractHeap(uint32_t new_size, heap_t* heap);
static uint32_t kmalloc_internal(uint32_t size, uint32_t align, uint32_t* physical_address);
static int findSmallestHole(uint32_t size, uint8_t page_align, heap_t* heap);
static uint8_t headerLessThanComparison(void* a, void* b);
//global variables
extern uint32_t end;
uint32_t placement_addr = (uint32_t)&end;
heap_t* kheap= 0;
//heap functions
heap_t* createHeap(uint32_t start, uint32_t end, uint32_t max, uint8_t isSupervisorMode, uint8_t isReadOnly){
heap_t* heap_local = (heap_t*) kmalloc(sizeof(heap_t));
if( (start % 0x1000) != 0 || (end % 0x1000) != 0){
return; // if not page aligned, return NULL
}
heap_local->index = placeOrderedArray((void*)start, KHEAP_INDEX_SIZE, &headerLessThanComparison);
start += sizeof(any_type_t) * KHEAP_INDEX_SIZE;
if((start & 0xFFFFF000) != 0){
start &= 0xFFFFF000;
start += 0x1000;
}
heap_local->start_address = start;
heap_local->end_address = end;
heap_local->max_address = max;
heap_local->isSupervisorMode = isSupervisorMode;
heap_local->isReadOnly = isReadOnly;
header_t* hole = (header_t*)start;
hole->size = end - start;
hole->magic = KHEAP_MAGIC;
hole->isHole = 1;
insertOrderedArray((void*)hole, &heap_local->index ); //insert hole into heap that spans the full heap
return heap_local;
}
static void expandHeap(uint32_t new_size, heap_t* heap){
if(new_size <= (heap->end_address - heap->start_address) ){ //if new size is less than or equal to current size, do nothing
return;
}
if( (new_size & 0xFFFFF000) != 0){
new_size &= 0xFFFFF000;
new_size += 0x1000;
}
if(heap->start_address + new_size > heap->max_address ){ //check that new size doesn't extend past max address
return;
}
uint32_t old_size = heap->end_address - heap->start_address;
uint32_t index = old_size;
while(index < new_size){
allocFrame( getPage(heap->start_address + index, CREATE_PAGE_IF_NONEXISTENT, kernel_directory),
(heap->isSupervisorMode) ? 1 : 0,
(heap->isReadOnly) ? 0: 1
);
index += 0x1000;
}
heap->end_address = heap->start_address + new_size;
}
static uint32_t contractHeap(uint32_t new_size, heap_t* heap){
if(new_size >= heap->end_address - heap->start_address){
return heap->end_address - heap->start_address; //return current size
}
//align on page boundary
if(new_size & 0x1000){
new_size &= 0x1000;
new_size += 0x1000;
}
if(new_size < KHEAP_MIN_SIZE){
new_size = KHEAP_MIN_SIZE;
}
uint32_t old_size = heap->end_address - heap->start_address;
uint32_t bound = old_size - 0x1000;
while(new_size < bound){
freeFrame(getPage(heap->start_address + bound, DO_NOT_CREATE_PAGE_IF_NONEXISTENT, kernel_directory));
bound -= 0x1000;
}
heap->end_address = heap->start_address + new_size;
return new_size;
}
void* allocHeap(uint32_t size, uint8_t pageAligned, heap_t* heap){
uint32_t new_size = size + sizeof(header_t) + sizeof(footer_t);
int iterator = findSmallestHole(new_size, pageAligned, heap);
if(iterator == -1){ //if couldn't find a suitable hole
uint32_t old_length = heap->end_address - heap->start_address;
uint32_t old_end_address = heap->end_address;
expandHeap(old_length+new_size, heap); //expand heap
//find the endmost header available
uint32_t new_length = heap->end_address - heap->start_address;
iterator = 0;
int index = -1;
uint32_t value = 0x0;
while(iterator < (int) heap->index.size){
uint32_t tmp = (uint32_t) lookupItemInOrderedArray(iterator, &heap->index);
if(tmp > value){
value = tmp;
index = iterator;
}
iterator++;
}
if(index == -1){ //if no headers were found, create a header
header_t* header = (header_t*)old_end_address;
header->magic = KHEAP_MAGIC;
header->size = new_length - old_length;
header->isHole = 1;
footer_t* footer = (footer_t*)((uint32_t)header+ header->size - sizeof(footer_t));
footer->header_ref = header;
footer->magic = KHEAP_MAGIC;
} else{
// The last header needs adjusting.
header_t *header = lookupItemInOrderedArray(index, &heap->index);
header->size += new_length - old_length;
// Rewrite the footer.
footer_t *footer = (footer_t *) ( (uint32_t)header + header->size - sizeof(footer_t) );
footer->header_ref = header;
footer->magic = KHEAP_MAGIC;
}
//recursive call now that space has been made
return allocHeap(size,pageAligned,heap);
}
header_t* original_hole_header = (header_t*) lookupItemInOrderedArray(iterator, &heap->index);
uint32_t original_hole_pos = (uint32_t)original_hole_header;
uint32_t original_hole_size = original_hole_header->size;
//check if filling the new hole doesn't leave enough room for a new hole to be made from
if(original_hole_size - new_size < sizeof(header_t) + sizeof(footer_t)){
size += original_hole_size - new_size;
new_size = original_hole_size;
}
if(pageAligned && original_hole_pos & 0xFFFFF000){ //if page aligned, make a new hole in front our new block
uint32_t new_location = original_hole_pos + 0x1000 - (original_hole_pos & 0xFFF) - sizeof(header_t);
header_t* hole_header = (header_t*)original_hole_pos;
hole_header->size = 0x1000 - (original_hole_pos & 0xFFF) - sizeof(header_t);
hole_header->magic = KHEAP_MAGIC;
hole_header->isHole = 1;
footer_t* hole_footer = (footer_t*)((uint32_t)new_location - sizeof(footer_t));
hole_footer->magic = KHEAP_MAGIC;
hole_footer->header_ref = hole_header;
original_hole_pos = new_location;
original_hole_size = original_hole_size - hole_header->size;
} else {
removeItemInOrderedArray(iterator, &heap->index); //remove hole
}
//create a block of memory at position of hole
header_t* block_header = (header_t*)original_hole_pos;
block_header->magic = KHEAP_MAGIC;
block_header->isHole = 0;
block_header->size = new_size;
footer_t* block_footer = (footer_t*)(original_hole_pos+sizeof(header_t)+size);
block_footer->magic = KHEAP_MAGIC;
block_footer->header_ref = block_header;
if(original_hole_size - new_size > 0){ //if leftover space from original hole, create a new hole
header_t* hole_header = (header_t*)(original_hole_pos + sizeof(header_t) + size + sizeof(footer_t));
hole_header->magic = KHEAP_MAGIC;
hole_header->isHole = 1;
hole_header->size = original_hole_size - new_size;
footer_t* hole_footer = (footer_t*)( (uint32_t)hole_header + original_hole_size - new_size - sizeof(footer_t) );
if((uint32_t)hole_footer < heap->end_address){
hole_footer->magic = KHEAP_MAGIC;
hole_footer->header_ref = hole_header;
}
insertOrderedArray((void*)hole_header,&heap->index);
}
return (void*) ((uint32_t)block_header + sizeof(header_t));
}
void freeHeap(void*p, heap_t* heap){
if(p == NULL){
return;
}
header_t* header = (header_t*)( (uint32_t)p -sizeof(header_t) );
footer_t* footer = (footer_t*)( (uint32_t)header + header->size - sizeof(footer_t));
if(header->magic != KHEAP_MAGIC || footer->magic != KHEAP_MAGIC ){
return;
}
header->isHole = 1;
uint8_t do_add = 1; //boolean to control whether to add a header to the heap index
//check if there's a hole in the memory before the current header, combine them
footer_t* test_footer = (footer_t*)((uint32_t)header - sizeof(footer_t));
if(test_footer->magic == KHEAP_MAGIC && test_footer->header_ref->isHole == 1){
uint32_t cache_size = header->size;
header = test_footer->header_ref; //change header reference to previous header;
footer->header_ref = header; //update footer's header reference
header->size += cache_size; //update size to be the size of both blocks of memory
do_add = 0; //since this was a merge, no need to add a new entry
}
header_t* test_header = (header_t*)((uint32_t)footer + sizeof(footer_t));
if(test_header->magic == KHEAP_MAGIC && test_header->isHole){
header->size += test_header->size;
test_footer = (footer_t*)((uint32_t)test_header + test_header->size - sizeof(footer_t));
footer = test_footer;
//loop through heap blocks to find header
uint32_t iterator = 0;
while( (iterator < heap->index.size) && (lookupItemInOrderedArray(iterator,&heap->index) != (void*)test_header )){
iterator++;
}
if(iterator > heap->index.size){
return; // iterator should not exceed index size
}
removeItemInOrderedArray(iterator, &heap->index);
}
if((uint32_t)footer+ sizeof(footer_t) == heap->end_address){
uint32_t old_length = heap->end_address - heap->start_address;
uint32_t new_length = contractHeap((uint32_t)header - heap->start_address, heap);
if( ( (header->size - (old_length - new_length)) > 0)){
header->size -= old_length - new_length;
footer = (footer_t*)((uint32_t)header + header->size - sizeof(footer_t));
footer->magic = KHEAP_MAGIC;
footer->header_ref = header;
} else {
uint32_t iterator = 0;
while( (iterator < heap->index.size) && (lookupItemInOrderedArray(iterator, &heap->index) != (void*)test_header)){
iterator++;
}
if(iterator < heap->index.size){
removeItemInOrderedArray(iterator, &heap->index);
}
}
}
if(do_add == 1){
insertOrderedArray((void*) header, &heap->index);
}
}
static uint8_t headerLessThanComparison(void* a, void* b){
return ( ((header_t*)a)->size < ((header_t*)b)->size ) ? 1 : 0;
}
static int findSmallestHole(uint32_t size, uint8_t page_align, heap_t* heap){
uint32_t iterator = 0;
while(iterator < heap->index.size){
header_t* header = (header_t*) lookupItemInOrderedArray(iterator,&(heap->index));
if(page_align > 0){
uint32_t location = (uint32_t)header;
int offset = 0;
if( ( (location + sizeof(header_t)) & 0xFFFFF000) != 0 ){
offset = 0x1000 - (location + sizeof(header_t)) % 0x1000;
}
int hole_size = (int) header->size - offset; //header does not count toward hole's size
if(hole_size >= (int)size ){
break;
}
} else if(header->size >= size){
break;
}
iterator++;
}
if(iterator == heap->index.size){ //couldn't find a hole
return -1;
} else {
return iterator;
}
}
//wrapper functions for public use
uint32_t kmalloc_a(uint32_t size){
return kmalloc_internal(size, KHEAP_ALIGNED, NULL);
}
uint32_t kmalloc_p(uint32_t size, uint32_t* phys_addr){
return kmalloc_internal(size, KHEAP_NOT_ALIGNED, phys_addr);
}
uint32_t kmalloc_ap(uint32_t size, uint32_t* phys_addr){
return kmalloc_internal(size, KHEAP_ALIGNED, phys_addr);
}
uint32_t kmalloc(uint32_t size){
return kmalloc_internal(size, KHEAP_NOT_ALIGNED, NULL);
}
static uint32_t kmalloc_internal(uint32_t size, uint32_t isAligned, uint32_t* physical_address){
if(kheap != 0){
terminalWriteString("\nAllocating ");
terminalPutNumber(size);
terminalWriteString(" bytes");
void* addr = allocHeap(size,(uint8_t)isAligned,kheap); //allocate memory based on provided size
if(physical_address != NULL){
page_t* page = getPage((uint32_t)addr,DO_NOT_CREATE_PAGE_IF_NONEXISTENT,kernel_directory);
*physical_address = (page->frame * 0x1000 )+ ((uint32_t)addr & 0xFFF);
}
return (uint32_t)addr;
} else{
if(isAligned == 1 && (placement_addr & 0xFFFFF000) ){ //if address is not already page aligned
placement_addr &= 0xFFFFF000; //mask off values less than 4KB
placement_addr += 0x1000; //advance pointer to 4 KB multiple
}
if(physical_address){ //if pointer exists, set to placement address
*physical_address = placement_addr;
}
uint32_t addr = placement_addr; //set to memory address that pointer is referring to
placement_addr += size; //increment pointer by size
return addr;
}
}
void kfree(void* p){
freeHeap(p,kheap);
} |
C | /*
* =====================================================================================
*
* Filename: 010-ivenvd.c
*
* Description: Calculate the sum of all the primes below two million.
*
* Version: 1.0
* Created: 2009年10月31日 03时37分21秒
* Revision: none
* Compiler: gcc
*
* Author: Xu Lijian (ivenvd), [email protected]
* Company: CUGB, China
*
* =====================================================================================
*/
#include <stdio.h>
#define MAX 2000000 /* */
/*
* === FUNCTION ======================================================================
* Name: main
* Description: main function
* =====================================================================================
*/
int
main (int argc, char *argv[])
{
char is_prime;
register int i, n, cnt = 3;
int prime[MAX / 2] = {2, 3, 5}; /* 质数库 */
unsigned long sum = 10;
for (n = 7; n < MAX; n += 2) { /* 从 7 开始验证 */
if (n % 5 == 0) {
continue;
}
is_prime = 1;
for (i = 0; prime[i] * prime[i] <= n; i++) {
if (n % prime[i] == 0) {
is_prime = 0;
break;
}
}
if (is_prime) {
prime[cnt++] = n; /* 存入质数库 */
sum += n;
}
}
printf ("%ld\n", sum);
return 0;
} /* ---------- end of function main ---------- */
|
C |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Max 100
typedef struct char10 { char c[10]; } String;
char* Roman_Numeral_Converter(int num){
String *Roman;
Roman = malloc (sizeof (String));
strcpy(Roman->c, "");
while(num != 0)
{
if (num >= 1000) // 1000 - m
{
strncat(Roman->c,"M",1);
num -= 1000;
}
else if (num >= 900) // 900 - cm
{
strncat(Roman->c,"CM", 2);
num -= 900;
}
else if (num >= 500) // 500 - d
{
strncat(Roman->c,"D", 1);
num -= 500;
}
else if (num >= 400) // 400 - cd
{
strncat(Roman->c,"CD", 2);
num -= 400;
}
else if (num >= 100) // 100 - c
{
strncat(Roman->c,"C", 2);
num -= 100;
}
else if (num >= 90) // 90 - xc
{
strncat(Roman->c,"XC", 2);
num -= 90;
}
else if (num >= 50) // 50 - l
{
strncat(Roman->c,"I", 1);
num -= 50;
}
else if (num >= 40) // 40 - xl
{
strncat(Roman->c,"XI", 2);
num -= 40;
}
else if (num >= 10) // 10 - x
{
strncat(Roman->c,"X", 1);
num -= 10;
}
else if (num >= 9) // 9 - ix
{
strncat(Roman->c,"IX", 2);
num -= 9;
}
else if (num >= 5) // 5 - v
{
strncat(Roman->c,"V", 1);
num -= 5;
}
else if (num >= 4) // 4 - iv
{
strncat(Roman->c,"IV",2);
num -= 4;
}
else if (num >= 1) // 1 - i
{
strncat(Roman->c,"I", 1);
num -= 1;
}
}
return Roman;
}
int main(void)
{
int i=0,count=0;
FILE *InputFile;
char pathofinput[Max],pathofoutput[Max];
printf("============Roman Numeral Converter==========\n");
printf("Enterd a valid number should be from 1 to 3,999\n\n");
printf("Enter The path of input file");
printf("\n For Example /Users/dabbaghie/Desktop/input.txt");
printf("\nHere ==> ");
scanf("%s",pathofinput);
printf("============Roman Numeral Converter==========\n");
printf("Enterd a valid number should be from 1 to 3,999\n\n");
printf("Enter The path of output file");
printf("\n For Example /Users/dabbaghie/Desktop/output.txt");
printf("\nHere ==> ");
scanf("%s",pathofoutput);
strncat(pathofoutput,"/output.txt",11);
InputFile =fopen(pathofinput,"r");
char *Roman;
int numberArray[Max];
if (InputFile == NULL){ //Condition statement for the path and file
printf("Error Reading File\n");
exit (0);//Exit form the App
}
for (int i = 0; i < Max; i++){ // get The numbers by using ((,)) which Separated numbers
fscanf(InputFile, "%d,", &numberArray[i] );
}
fclose(InputFile);
while (numberArray[i]!=0){ //Count The Numbers
count++;
i++;
}
for (int i = 0; i < count; i++){ //
Roman=Roman_Numeral_Converter(numberArray[i]);
printf("%d.%d ==>%s\n",i+1,numberArray[i],Roman);
}
InputFile =fopen(pathofoutput,"w"); //Writing the result on file.txt
for (int i = 0; i < count; i++){
fprintf(InputFile,"%s,",
Roman_Numeral_Converter(numberArray[i])); //For Example :XV,IV,II
}
fprintf(InputFile,"\n\n\n The Count of Numbers is: %d.",count);
fprintf(InputFile,"\n\n\n Ali.Almanea</>");
fclose(InputFile);
return 0;
}
|
C | #include<stdio.h>
void main()
{
int i;
int a=0,b=1,c=2,sum;
printf("Tribonacci series upto 20\n");
printf("%d\t%d\t%d\t",a,b,c);
for(i=0;i<=17;i++)
{
sum=a+b+c;
printf("%d\t",sum);
a=b;
b=c;
c=sum;
}
}
|
C | #include<stdio.h>
int facto(int c)
{
if(c<1)
return 1;
return c*facto(c-1);
}
int Combo(int a,int b)
{
int x;
x = facto(a)/(facto(b)*facto(a-b));
return x;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
printf("\n");
for(int k=1;k<n-i;k++)
{
printf(" ");
}
for(int j=0;j<=i;j++)
{
printf("%d ",Combo(i,j));
}
printf("\n");
}
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
char c1;
printf("пJ@Ӧr:");
scanf(" %c",&c1);/* sJ@Ӧr */
printf("c1=%c ASCIIX=%d\n",c1,c1); /* XrASCIIX */
system("pause");
return 0;
}
|
C | #include "DicoInstruct.h"
int sizeDico = 0;
INSTRUCTION* AllocateDico(FILE *file, int* sizeDico)
{
if(!fscanf(file, "%d", sizeDico))
return 0;
return (INSTRUCTION*)malloc(*sizeDico * sizeof(INSTRUCTION));
}
INSTRUCTION*InitializeDicoInstruct(char *nameDicoFile)
{
FILE *file = NULL;
int index = 0;
INSTRUCTION* dictionary;
if (!(file = fopen(nameDicoFile, "r")))
{
printf("ERROR the dictionary file doesn't exist");
return NULL;
}
if(!(dictionary = AllocateDico(file, &sizeDico)))
{
printf("ERROR not enought memory");
return NULL;
}
while(index<sizeDico && !feof(file))
{
char bitString[32];
fscanf(file, "%s %s %d %s %s %s %c", (dictionary[index].id), (dictionary[index].operands), &(dictionary[index].hasPseudoInstruction), bitString, dictionary[index].details.order, dictionary[index].details.modificable, &(dictionary[index].details.type));
if(dictionary[index].operands[0] == '0')
{
dictionary[index].typeNumber = 0;
}
else
{
dictionary[index].typeNumber = strlen(dictionary[index].operands);
}
dictionary[index].bitField.intInst = (unsigned int)strtol(bitString,NULL,2);
index++;
}
if(index != sizeDico)
{
printf("WARNING the dictionary's size is not the real one");
sizeDico = index;
}
fclose(file);
return dictionary;
}
int IndexInstruction(INSTRUCTION* dictionary, char *instructionName)
{
int index = 0;
int isNotEqual = 0;
StringUpper(instructionName);
while (index < sizeDico && (isNotEqual = strcmp(dictionary[index].id, instructionName) != 0))
{
index++;
}
if(isNotEqual)
return -1;
return index;
} |
C | #include "queue_array.h"
#include "array.h"
#include "graph_nav.h"
//Strukt ni ska anvnda fr noderna om ni tnkt anvnda generate matrix
typedef struct {
bool visited; //br vara false fr ny nod
char *cityName; //minnet fr strngen br ha allokerats dynamiskt
} mapvertice;
//Struct fr resultatet frn generateMatrixRepresentation
typedef struct arrayResult {
array *verticeData; //innehller stadsnamnen (p samma index som de svarar
//mot i frbindelsematrisen)
array *matrix; //innehller frbindelsematris
} arrayResult;
/*
Syfte: Generera en frbindelsematris med pekare int-vrden som innehller avstnd
mellan noderna finns ingen frbindelse s har motsvarande position vrdet 0.
Parametrar: g- grafen. Grafen ska ha pekare till int vrden p kanterna och mapVertice
pekare som vrden fr noderna. Minne fr dessa ska vara allokerat
dynamiskt (funktionen avallokerar sedan detta minne)
numNodes - antalet noder i grafen
Returvrde: Ett vrde av typen arrayresultat (en struct) som innehller en frbindelsematris
(numNodes x numNodes stor indexerad frn 0) och en array (numNodes stor indexerat
frn 0) som innehller stadsnamnen i grafen fr respektive index
i frbindelsematrisen (eg p index 0 ligger stadsnamnet som hr till index 0 i
matrisen osv).
Kommentarer: Frbindelsematrisen och arrayen med stadsnamnen har bda minneshanterare satta.
Grafen kommer efter anrop att vara borttagen.
Minneshaterare stts internt fr grafen s detta behver ej gras innan anrop av
funktionen.
*/
arrayResult generateMatrixRepresentation(graph *g,int numNodes);
//Funktion som behvs fr att skapa en graf med mapVertice-noder
bool mapVerticeEqual(vertice v1,vertice v2);
/********************Hjlpfunktioner*********************************/
//Anvnds internt i generateMatrixRepresentation
int indexOfVertice(array *a,vertice v,int maxIndex,equalityFunc *verticeEQ);
bool mapVerticeIsVisited(vertice v);
void mapVerticeVisit(vertice v);
void mapVerticeFree(vertice v);
bool strcmp2(void *str1,void *str2);
//strdup not available in c99 so providing my own implementation
/* Memory is allocated for the copy. Users of this function is responsible
* for deallocating this memory */
char *strdup(const char *str);
|
C | /*
A 42
{1, f}
{b, a, r, {2, g}}
A 84
{1, f}
{b, a, r, {2, g}}
B 126
{1, f}
{b, a, r, {2, g}}
*/
#include <stdio.h>
char g_char;
int g_int;
struct foo {
int a;
char b;
} g_foo;
struct bar {
char c, d, e;
struct foo f;
} g_bar;
int main() {
char c = 'A';
int a = 42;
struct foo f = { 1, 'f'};
struct bar b = {'b', 'a', 'r', {2, 'g'}};
g_char = c;
g_int = a;
g_foo = f;
g_bar = b;
printf("%c %d\n", g_char, g_int);
printf("{%d, %c}\n", g_foo.a, g_foo.b);
printf("{%c, %c, %c, {%d, %c}}\n",
g_bar.c, g_bar.d, g_bar.e, g_bar.f.a, g_bar.f.b);
g_char = g_char;
g_int += g_int;
g_foo = g_foo;
g_bar = g_bar;
printf("%c %d\n", g_char, g_int);
printf("{%d, %c}\n", g_foo.a, g_foo.b);
printf("{%c, %c, %c, {%d, %c}}\n",
g_bar.c, g_bar.d, g_bar.e, g_bar.f.a, g_bar.f.b);
c = g_char + 1;
a += g_int;
f = g_foo;
b = g_bar;
printf("%c %d\n", c, a);
printf("{%d, %c}\n", f.a, f.b);
printf("{%c, %c, %c, {%d, %c}}\n",
b.c, b.d, b.e, b.f.a, b.f.b);
return 0;
}
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
long XDF_IGNORE_CR_AT_EOL ;
long XDF_IGNORE_WHITESPACE ;
long XDF_IGNORE_WHITESPACE_AT_EOL ;
long XDF_IGNORE_WHITESPACE_CHANGE ;
long XDF_WHITESPACE_FLAGS ;
scalar_t__ XDL_ISSPACE (char const) ;
scalar_t__ ends_with_optional_cr (char const*,long,int) ;
int /*<<< orphan*/ memcmp (char const*,char const*,long) ;
int xdl_recmatch(const char *l1, long s1, const char *l2, long s2, long flags)
{
int i1, i2;
if (s1 == s2 && !memcmp(l1, l2, s1))
return 1;
if (!(flags & XDF_WHITESPACE_FLAGS))
return 0;
i1 = 0;
i2 = 0;
/*
* -w matches everything that matches with -b, and -b in turn
* matches everything that matches with --ignore-space-at-eol,
* which in turn matches everything that matches with --ignore-cr-at-eol.
*
* Each flavor of ignoring needs different logic to skip whitespaces
* while we have both sides to compare.
*/
if (flags & XDF_IGNORE_WHITESPACE) {
goto skip_ws;
while (i1 < s1 && i2 < s2) {
if (l1[i1++] != l2[i2++])
return 0;
skip_ws:
while (i1 < s1 && XDL_ISSPACE(l1[i1]))
i1++;
while (i2 < s2 && XDL_ISSPACE(l2[i2]))
i2++;
}
} else if (flags & XDF_IGNORE_WHITESPACE_CHANGE) {
while (i1 < s1 && i2 < s2) {
if (XDL_ISSPACE(l1[i1]) && XDL_ISSPACE(l2[i2])) {
/* Skip matching spaces and try again */
while (i1 < s1 && XDL_ISSPACE(l1[i1]))
i1++;
while (i2 < s2 && XDL_ISSPACE(l2[i2]))
i2++;
continue;
}
if (l1[i1++] != l2[i2++])
return 0;
}
} else if (flags & XDF_IGNORE_WHITESPACE_AT_EOL) {
while (i1 < s1 && i2 < s2 && l1[i1] == l2[i2]) {
i1++;
i2++;
}
} else if (flags & XDF_IGNORE_CR_AT_EOL) {
/* Find the first difference and see how the line ends */
while (i1 < s1 && i2 < s2 && l1[i1] == l2[i2]) {
i1++;
i2++;
}
return (ends_with_optional_cr(l1, s1, i1) &&
ends_with_optional_cr(l2, s2, i2));
}
/*
* After running out of one side, the remaining side must have
* nothing but whitespace for the lines to match. Note that
* ignore-whitespace-at-eol case may break out of the loop
* while there still are characters remaining on both lines.
*/
if (i1 < s1) {
while (i1 < s1 && XDL_ISSPACE(l1[i1]))
i1++;
if (s1 != i1)
return 0;
}
if (i2 < s2) {
while (i2 < s2 && XDL_ISSPACE(l2[i2]))
i2++;
return (s2 == i2);
}
return 1;
} |
C | #include<stdio.h>
int main()
{
int a,sum=0;
for(a=2;a<=100;a++)
{
if (a%2==0)
{
sum=sum+a;
}
}
printf("sum=%d\n",sum);
return 0;
}
|
C | #include "graph.h"
#include "config.h"
void printGraph(AdjGraph g)
{
for (int i = 0; i < MAXV; i++) {
if (g->adj[i].outDegree != -1) {
printf("%d (%d, %d): ", i, g->adj[i].inDegree, g->adj[i].outDegree);
Anode *p;
p = g->adj[i].firstarc;
while (p != NULL) {
printf("-> %d(%d) ", p->no, p->weight);
p = p->nextarc;
}
printf("\n");
}
}
}
void printGraphList(AdjGraph g)
{
for (int i = 0; i < MAXV; i++) {
if (g->adj[i].outDegree > 0) {
Anode *p;
p = g->adj[i].firstarc;
while (p != NULL) {
printf("%d %d %d\n", i, p->no, p->weight);
p = p->nextarc;
}
}
}
}
AdjGraph createAdj(char *name)
{
AdjGraph g = (AdjGraph)malloc(sizeof(adjGraph));
num_type n = 0, m = 0;
for (int i = 0; i < MAXV; i++) {
g->adj[i].firstarc = NULL;
g->adj[i].outDegree = -1;
g->adj[i].inDegree = 0;
}
FILE *file;
file = fopen(name, "r");
if (file == NULL) {
printf("file open error!!!\n");
exit(1);
}
id_type u, v;
weight_type w;
Anode *p;
while (fscanf(file, "%d%d%d", &u, &v, &w) != EOF) {
m++;
if (g->adj[u].outDegree == -1) {
n++;
g->adj[u].outDegree = 0;
}
if (g->adj[v].outDegree == -1) {
n++;
g->adj[v].outDegree = 0;
}
g->adj[u].outDegree++;
g->adj[v].inDegree++;
p = (Anode *)malloc(sizeof(Anode));
p->no = v; p->weight = w;
p->nextarc = g->adj[u].firstarc;
g->adj[u].firstarc = p;
}
g->m = m;
g->n = n;
//printf("%d %d\n", m, n);
fclose(file);
return g;
}
|
C | #include <curses.h>
int main()
{
int key;
initscr();
keypad(stdscr,1);
while(1){
key = getch();
switch(key){
case KEY_DOWN:
printw("DOWN\n");
break;
case KEY_UP:
printw("UP\n");
break;
case KEY_LEFT:
printw("LEFT\n");
break;
case KEY_RIGHT:
printw("RIGHT\n");
break;
}
}
endwin();
return 0;
}
|
C | #include <stdio.h>
int main() {
int num, foundEven = 6;
scanf("%d", &num);
while (foundEven) {
if (num % 2 !=0){
printf("%d\n", num);
foundEven--;
}
num++;
}
} |
C | #include <stdio.h>
/*
Nicolas Marcondes Molina
RA:743584
exercicio lab2
*/
//escolhi usar o bubble sorte pela simples implementacao para ordenar o vetor
void insertionsort(int vetor[], int n){
int i, j, aux;
for (int i = 1; i < n; i++){
aux = vetor[i];
j = i - 1;
while ((j >= 0) && (vetor[j] > aux)) {
vetor[j + 1] = vetor[j];
j = j - 1;
}
vetor[j + 1] = aux;
}
}
/*int bb(int vetor[], int tam, int x){
int e = -1, d = tam;
while (e < d-1){
int m = (e + d)/2;
if(vetor[m] < x)
e = m;
else
d = m;
}
return d;
}*/
//busca binaria para achar o elemento que estamos procurando como foi passado nos slides
int bb(int vetor[], int tam, int key){
int imin = 0;
int imax = tam-1;
int imid;
while(imax >= imin){
imid = imin + ((imax - imin) / 2);
if(key > vetor[imid]){
imin = imid+1;
} else if(key < vetor[imid]){
imax = imid-1;
} else {
return key;
}
}
return -1;
}
//busca binaria retorna um indice
int main(){
int qtd, qtdgar, tamemb[10000], tamgar[1000000], i, j, aux, x, menor = 0;
scanf("%d", &qtd);
if (qtd > 10000 || qtd < 1){
return 0;
}//condicionais
for (i=0; i < qtd; i++){
scanf("%d", &tamemb[i]);
if (tamemb[i] < menor)
menor = tamemb[i];
}
scanf("%d", &qtdgar);
if (qtdgar > 1000000 || qtdgar < 1){
return 0;
}//condicionais
for (j=0; j < qtdgar; j++){
scanf("%d", &tamgar[j]);
}
insertionsort(tamemb,qtd);
/*for (int k = 0; k < qtd; k++)
printf("%d ", tamemb[k]);
testes
for (int l = 0; l < qtdgar; l++)
printf("%d ", tamgar[l]);*/
for (i=0; i < qtdgar; i++){
x = tamgar[i];
if (x >= menor) {
while (x >= menor){
aux = bb(tamemb, qtd, x);
if (aux == -1)
x--;
else
x = menor - 1;// condicao para retornar = ou > o tamanho da embalagem
}
if (aux == -1)
printf("descartar");
else
printf("%d", aux);
printf("\n");
aux = 0;
}
else
printf("descartar\n");
}
return 0;
}
|
C |
#ifndef PIO_H
#define PIO_H
//------------------------------------------------------------------------------
// Headers
//------------------------------------------------------------------------------
#include <board.h>
//------------------------------------------------------------------------------
// Global Definitions
//------------------------------------------------------------------------------
/// The pin is controlled by the associated signal of peripheral A.
#define PIO_PERIPH_A 0
/// The pin is controlled by the associated signal of peripheral B.
#define PIO_PERIPH_B 1
/// The pin is an input.
#define PIO_INPUT 2
/// The pin is an output and has a default level of 0.
#define PIO_OUTPUT_0 3
/// The pin is an output and has a default level of 1.
#define PIO_OUTPUT_1 4
/// Default pin configuration (no attribute).
#define PIO_DEFAULT (0 << 0)
/// The internal pin pull-up is active.
#define PIO_PULLUP (1 << 0)
/// The internal glitch filter is active.
#define PIO_DEGLITCH (1 << 1)
/// The pin is open-drain.
#define PIO_OPENDRAIN (1 << 2)
//------------------------------------------------------------------------------
// Global Macros
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// Calculates the size of an array of Pin instances. The array must be defined
/// locally (i.e. not a pointer), otherwise the computation will not be correct.
/// \param pPins Local array of Pin instances.
/// \return Number of elements in array.
//------------------------------------------------------------------------------
#define PIO_LISTSIZE(pPins) (sizeof(pPins) / sizeof(Pin))
//------------------------------------------------------------------------------
// Global Types
//------------------------------------------------------------------------------
typedef struct _ExtIntMode {
///indicate which pin to enable/disable additional Interrupt mode
///each of 32 bit field represents one PIO line.
unsigned int itMask;
///select Edge or level interrupt detection source
///each of 32 bit field represents one PIO line, 0 is Edge, 1 is Level
unsigned int edgeLvlSel;
///select rising/high or falling/low detection event
///each of 32 bit field represents one PIO line:
///0 is Falling Edge detection event (if selected Edge interrupt
/// detection source, or Low Level detection (if selected
/// Level interrupt detection source;
///1 is Rising Edge detection(if selected Edge interrupt
/// source, or Low Level detection event(if selected Level
/// interrupt detection source.
unsigned int lowFallOrRiseHighSel;
} ExtIntMode;
typedef struct _GlitchDeBounceFilter {
///Select Glitch/Debounce filtering for PIO input
///each of 32 bit field represents one PIO line
///0 is Glitch, 1 is Debouncing
unsigned int filterSel;
///slow clock divider selection for Debouncing filter
unsigned int clkDivider:14;
} GlitchDebounceFilter;
//------------------------------------------------------------------------------
/// Describes the type and attribute of one PIO pin or a group of similar pins.
/// The #type# field can have the following values:
/// - PIO_PERIPH_A
/// - PIO_PERIPH_B
/// - PIO_OUTPUT_0
/// - PIO_OUTPUT_1
/// - PIO_INPUT
///
/// The #attribute# field is a bitmask that can either be set to PIO_DEFAULt,
/// or combine (using bitwise OR '|') any number of the following constants:
/// - PIO_PULLUP
/// - PIO_DEGLITCH
/// - PIO_OPENDRAIN
//------------------------------------------------------------------------------
typedef struct {
/// Bitmask indicating which pin(s) to configure.
unsigned int mask;
/// Pointer to the PIO controller which has the pin(s).
AT91S_PIO *pio;
/// Peripheral ID of the PIO controller which has the pin(s).
unsigned char id;
/// Pin type.
unsigned char type;
/// Pin attribute.
unsigned char attribute;
#if defined(AT91C_PIOA_AIMMR)
///Additional Interrupt Mode
ExtIntMode itMode;
#endif
#if defined(AT91C_PIOA_IFDGSR)
///Glitch/Debouncing filter
GlitchDebounceFilter inFilter;
#endif
} Pin;
//------------------------------------------------------------------------------
// Global Access Macros
//------------------------------------------------------------------------------
//Get Glitch input filter enable/disable status
#define PIO_GetIFSR(pPin) ((pPin)->pio->PIO_IFSR)
//Get Glitch/Deboucing selection status
#define PIO_GetIFDGSR(pPin) ((pPin)->pio->PIO_IFDGSR)
//Get Additional PIO interrupt mode mask status
#define PIO_GetAIMMR(pPin) ((pPin)->pio->PIO_AIMMR)
//Get Interrupt status
#define PIO_GetISR(pPin) ((pPin)->pio->PIO_ISR)
//Get Edge or Level selection status
#define PIO_GetELSR(pPin) ((pPin)->pio->PIO_ELSR)
//Get Fall/Rise or Low/High selection status
#define PIO_GetFRLHSR(pPin) ((pPin)->pio->PIO_FRLHSR)
//Get PIO Lock Status
#define PIO_GetLockStatus(pPin) ((pPin)->pio->PIO_LOCKSR)
//------------------------------------------------------------------------------
// Global Functions
//------------------------------------------------------------------------------
extern unsigned char PIO_Configure(const Pin *list, unsigned int size);
extern void PIO_Set(const Pin *pin);
extern void PIO_Clear(const Pin *pin);
extern unsigned char PIO_Get(const Pin *pin);
//extern unsigned int PIO_GetISR(const Pin *pin);
extern unsigned char PIO_GetOutputDataStatus(const Pin *pin);
#endif //#ifndef PIO_H
|
C | #include <stdio.h>
#include <stdlib.h>
struct Jogador{
int passe;
int drible;
union{
int finalizacao;
int defesa;
}posicao;
};
struct Player{
char nome[20];
struct Jogador p;
};
void preenche(struct Jogador* p1,int esc){
printf("Quantos de passe[0-100]?: ");
scanf("%d",&(*p1).passe);
printf("Quanto de drible[0-100]?: ");
scanf("%d",&(*p1).drible);
if(esc==1){
printf("Quanto de finalizacao[0-100]: ");
scanf("%d",&(*p1).posicao.finalizacao);
}else{
printf("Quanto de defesa[0-100]: ");
scanf("%d",&(*p1).posicao.defesa);
}
}
void preenche2(struct Player* p1,int e){
printf("Nome do jogador: ");
scanf("%s",(*p1).nome);
preenche(&(*p1).p,e);
}
int main(void){
int escolha;
printf("Jogador de linha ou goleiro?[1/2]: ");
scanf("%d",&escolha);
struct Player player;
preenche2(&player,escolha);
printf("NOME: %s\n",player.nome);
printf("PASSE: %d\n",player.p.passe);
printf("DRIBLE: %d\n",player.p.drible);
if(escolha==1){
printf("FINALIZACAO: %d\n",player.p.posicao.finalizacao);
}else{
printf("DEFESA: %d\n",player.p.posicao.defesa);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#define UPPER_LIMIT 100
int main()
{
// Stores whether or not the number
// If an entry is non zero, then that entry is a prime
int primes[100];
// Initialize the array
int i;
for(i = 1; i <= UPPER_LIMIT; i++) {
primes[i - 1] = i;
}
// 1 is not a prime number
primes[1 - 1] = 0;
// 2 IS a prime number
primes[2 - 1] = 1;
// Iterate through the primes
for(i = 2; i <= UPPER_LIMIT; i++) {
// For each prime, strike out the unneeded primes
int j;
for(j = i + 1; j <= UPPER_LIMIT; j++) {
if (primes[j - 1] != 0 && primes[j - 1] % i == 0) {
primes[j - 1] = 0;
}
}
}
// Display non zero numbers (primes) in the array
for(i = 1; i <= UPPER_LIMIT; i++) {
if (primes[i - 1] != 0) {
printf("%d\n", i);
}
}
return 0;
}
|
C | /*
* string_util.c
*
* Created on: 2013-7-19
*/
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
/*
Checks if char* q starts with char* p
*/
int strstarts(const char *p, const char *q)
{
while(*p && *p == *q){
++p;
++q;
}
// if *p is null return false else return diff
return *p ? *p - *q: 0;
}
int getTimeDiffer(struct timeval start, struct timeval end)
{
long mtime, seconds, useconds;
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
return mtime;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
enum {
Size = 40,
};
char buffer[Size];
int num;
int conv(int start){
int t;
int ret = 0;
for(t = start; t < start + 8 ; t++){
ret *= 2;
ret += buffer[t] -'0';
}
return ret;
}
int fun(){
int i;
int t;
for(i=0;i<32;i+=8){
if(i)
printf(".");
t= conv(i);
printf("%d",t);
}
printf("\n");
}
int main(){
scanf("%d", &num);
while(num -- ){
scanf("%s", buffer);
fun();
}
return 0;
}
|
C | #include <stdio.h>
int main()
{
int n,m;
scanf("%d %d",&n,&m);
int mat[n][m];
int mat1[2][2];
int max=0;
int zbir=0;
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<n-1;i++)
{
for(j=0;j<m-1;j++)
{
zbir=0;
zbir+=mat[i][j];
zbir+=mat[i][j+1];
zbir+=mat[i+1][j];
zbir+=mat[i+1][j+1];
if(zbir>max)
{
max=zbir;
mat1[0][0]=mat[i][j];
mat1[0][1]=mat[i][j+1];
mat1[1][0]=mat[i+1][j];
mat1[1][1]=mat[i+1][j+1];
}
}
}
printf("%d %d\n",mat1[0][0],mat1[0][1]);
printf("%d %d",mat1[1][0],mat1[1][1]);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
float x,y;
printf("x=");
scanf("%f",&x);
if(x>0)
printf("y=1");
else if(x=0)
printf("y=0");
else printf("y=-1");
return 0;
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <float.h>
void cpp4_8_1() {
char name[40];
char family_name[40];
printf("ֺ:");
scanf("%s", name);
scanf("%s", family_name);
printf("%s%s\n", name, family_name);
}
void cpp4_8_2() {
char name[20];
char f_name[20];
int len_name;
int len_fname;
printf("ֺ:");
scanf("%s%s", name,f_name);
len_name = strlen(name);
len_fname = strlen(f_name);
printf("your name have %d charactor and fname have %d charator\n", len_name, len_fname);
printf("a.\"%s %s\"\n", name,f_name);
printf("b.\"%20s %20s\"\n", name,f_name);
printf("c.\"%-20s %-20s\"\n", name, f_name);
printf("d.%*s %*s", len_name+3, name, len_fname+3, f_name);
}
void cpp4_8_3() {
float num;
printf("һ\n");
scanf("%f", &num);
printf("num = %f and num =%E", num, num);
}
void cpp4_8_4() {
float height;
char name[20];
printf("ߺ\n");
scanf("%f%s", &height, name);
printf("%s, you are %f feet tall", name, height);
}
void cpp4_8_5() {
float download_speed;
float file_size;
float download_time;
printf("ٶȣMb/s)ļСMB)]:\n");
scanf("%f%f", &download_speed, &file_size);
download_time = file_size * 8.0 / download_speed;
printf("At %.2f megabits per second,a file of %.2f megabytes\n downloads in %.2f seconds",
download_speed, file_size, download_time);
}
void cpp4_8_6() {
char first_name[20];
char last_name[20];
int len_f;
int len_l;
printf("\n");
scanf("%s", first_name);
len_f = strlen(first_name);
printf("գ\n");
scanf("%s", last_name);
len_l = strlen(last_name);
printf("%s %s\n", first_name, last_name);
printf("%*d %*d\n", len_f, len_f,len_l, len_l);
printf("%s %s\n", first_name, last_name);
printf("%-*d %-*d\n", len_f, len_f, len_l, len_l);
}
void cpp4_8_7() {
double num1 = 1.0 / 3.0;
float num2 = 1.0 / 3.0;
printf("num1 = %.6f num2 = %.6f\n", num1, num2);
printf("num1 = %.12f num2 = %.12f\n", num1, num2);
printf("num1 = %.16f num2 = %.16f\n", num1, num2);
printf("FLT_DIG = %d DBL_DIG = %d\n", FLT_DIG, DBL_DIG);
}
void cpp4_8_8() {
const float galon_to_litre = 3.785;
const float mile_to_km = 1.609;
float num_mileage;
float num_gasoline;
float mile_per_galon;
float litre_per_handred_km;
printf("̣Ӣأ:\n");
scanf("%f%f", &num_mileage, &num_gasoline);
mile_per_galon = num_mileage / num_gasoline;
litre_per_handred_km = (num_gasoline * galon_to_litre) * 100 / (num_mileage * mile_to_km);
printf("ÿͿʻ %.1f Ӣ\nÿ100 %.1f ", mile_per_galon, litre_per_handred_km);
} |
C | #include<stdio.h>
int main () {
int mat[3][3], INT_MENOR = 10000;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
scanf("%i", &mat[i][j]);
}
}
printf("\n\nExibindo Matriz\n\n");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("[ %i ]", mat[i][j]);
}
printf("\n");
}
//Pegando o menor valor da matriz
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(INT_MENOR > mat[i][j]) {
INT_MENOR = mat[i][j];
}
}
}
printf("\nMenor Valor %i\nPosição do menor valor", INT_MENOR);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(INT_MENOR == mat[i][j]) {
printf("\n[%i] [%i] ", i, j);
}
}
}
} |
C | /*************************************************************************
> File Name: fork3.c
> Author:
> Mail:
> Created Time: 2018年07月28日 星期六 14时28分48秒
************************************************************************/
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
pid = fork();
switch(pid){
case 0:
while(1){
printf("A background process,PID:%d\n,ParentID:%d\n",getpid(),getppid());
sleep(3);
}
case -1:
perror("Process creation failed\n");
exit(-1);
default:
printf("I am parent process,my pid is %d\n",getpid());
exit(0);
}
return 0;
}
|
C | #include "../includes/push_swap.h"
/*
** this function adds elements at the beginning of the list
*/
t_node *ps_add_node_front(t_node *stk, int nb)
{
t_node *element;
if ((element = (t_node *)malloc(sizeof(t_node))) == NULL)
return (NULL);
element->nb = nb;
element->next = element;
if (stk == NULL)
return (element);
element->next = stk;
return (element);
}
/*
** this function adds elements at the end of the list and checks if
** there happens to be a duplicate number
*/
t_node *ps_add_node_back(t_node *stka, int nb)
{
t_node *element;
t_node *tmp;
if ((element = (t_node *)malloc(sizeof(t_node))) == NULL)
return (NULL);
tmp = stka;
element->nb = nb;
element->next = NULL;
if (stka == NULL)
return (element);
while (tmp->next != NULL)
{
if (nb == tmp->nb)
return (NULL);
tmp = tmp->next;
}
if (nb == tmp->nb)
return (NULL);
tmp->next = element;
return (stka);
}
/*
** this function frees the stka list
*/
void ps_free_stka(t_ctrl *ctrl, t_node *stka)
{
t_node *tmp;
if (ctrl->size_a == 1)
free(stka);
while (ctrl->size_a > 1)
{
tmp = stka;
stka = stka->next;
ctrl->size_a--;
free(tmp);
if (stka == ctrl->tail_a)
{
free(stka);
break ;
}
}
}
/*
** this function frees the stkb list
*/
void ps_free_stkb(t_ctrl *ctrl, t_node *stkb)
{
t_node *tmp;
while (ctrl->size_b > 1)
{
tmp = stkb;
stkb = stkb->next;
ctrl->size_b--;
free(tmp);
if (stkb == ctrl->tail_b)
{
free(stkb);
break ;
}
}
}
/*
** this function sets the head_a, tail_a, and size_a for the control struct
*/
void ps_fill_ctrl(t_ctrl **ctrl, t_node *stka)
{
t_node *tmp;
tmp = stka;
(*ctrl)->head_a = tmp;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = (*ctrl)->head_a;
(*ctrl)->tail_a = tmp;
}
|
C | #ifndef __STACKS_H__
#define __STACKS_H_
/* stack_int_ptr definitions */
typedef struct stack_int_ptr{
int** elems;
int ptr;
int size;
}stack_int_ptr;
stack_int_ptr* stack_int_ptr_alloc(int elems);
void stack_int_ptr_free(stack_int_ptr* pstack);
int stack_int_ptr_len(stack_int_ptr* pstack);
int* stack_int_ptr_pop(stack_int_ptr* pstack);
void stack_int_ptr_push(stack_int_ptr* pstack,int* elem);
void stack_int_ptr_push_tail(stack_int_ptr* pstack,int* elem);
void stack_int_ptr_print(stack_int_ptr* pstack);
/* stack_int definitions */
typedef struct stack_int{
int* elems;
int ptr;
int size;
}stack_int;
stack_int* stack_int_alloc(int elems);
void stack_int_free(stack_int* pstack);
int stack_int_len(stack_int* pstack);
int stack_int_pop(stack_int* pstack);
void stack_int_push(stack_int* pstack,int elem);
void stack_int_push_tail(stack_int* pstack,int elem);
void stack_int_print(stack_int* pstack);
#endif
|
C | /*************
Compile: g++ -o sender sender.c
run: ./sender -h localhost -p 1234 -f sender.c -d .1 -l .01 -j 10
************/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <queue>
#include <assert.h>
#include <list>
#define QUEUE_LENGTH 10
#define PACKET_DATA_LENGTH 1448
#define TRANSMISSION_TIME 0.00001448 //1448 byte packet at 100 Mbs
typedef struct {
char data[PACKET_DATA_LENGTH];
double deadline;
double read_time;
double rto_time;
int sequence;
int data_size;
} packet;
double delay = 0;
double loss = 0;
double jitter = 0;
double inter_packet_delay = 0;
double rto = 0.1;
FILE *pFile;
double deadline_time = 0;
int current_sequence_number = 0;
double get_deadline();
void get_packet(packet* my_packet, double now_time);
using namespace std;
int main(int argc, char **argv) {
int sockfd, n;
struct sockaddr_in serv_addr;
struct hostent *server;
unsigned int serverlen;
char buffer[PACKET_DATA_LENGTH];
char *file;
char *host;
int port;
queue<packet> q;
list<packet> rtx_queue;
list<packet>::iterator p = rtx_queue.begin();
/**********Command line args *******************/
int c;
opterr = 0;
while ((c = getopt(argc, argv, "d:j:l:p:h:f:i:r:")) != -1)
switch (c) {
case 'd':
delay = atof(optarg);
break;
case 'j':
jitter = atof(optarg);
break;
case 'l':
loss = atof(optarg);
break;
case 'p':
port = atoi(optarg);
break;
case 'h':
host = optarg;
break;
case 'f':
file = optarg;
break;
case 'i':
inter_packet_delay = atof(optarg);
break;
case 'r':
rto = atof(optarg);
break;
default:
abort();
}
// printf("inter_packet_delay: %f\tjitter: %f\n", inter_packet_delay, jitter);
assert(inter_packet_delay >= jitter);
assert(inter_packet_delay >= TRANSMISSION_TIME);
pFile = fopen(file, "rb");
// pFile = fopen ( "core.bin" , "rb" );
/*************Fill Queue************/
struct timeval now;
double now_time;
packet *my_packet;
my_packet = (packet*) malloc(sizeof (packet));
gettimeofday(&now, NULL);
deadline_time = now.tv_sec + (now.tv_usec / 1000000.0);
deadline_time = deadline_time + delay;
memset(my_packet, 0, sizeof (*my_packet));
get_packet(my_packet, deadline_time);
if (my_packet->deadline != 0)
q.push(*my_packet);
for (int i = 0; i < QUEUE_LENGTH - 1; i++) {
memset(my_packet, 0, sizeof (*my_packet));
get_packet(my_packet, get_deadline());
if (my_packet->deadline != 0)
q.push(*my_packet);
}
/***************
Print the Queue
****************
char tmp[1449];
while( !q.empty() )
{
memset(my_packet, 0, sizeof(*my_packet));
*my_packet = q.front();
q.pop();
bzero((char *) &tmp, sizeof(tmp));
strncpy(tmp, my_packet->data, 1448);
tmp[1449] = '\0';
printf("seq: %d\t %d bytes.\n", my_packet->sequence, my_packet->data_size);
printf("data: %s\n\n", tmp);
}
return 0;
*/
/*************Set up socket******************/
sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd < 0) perror("ERROR opening socket");
server = gethostbyname(host);
if (server == NULL) {
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port);
fd_set rfds;
fd_set wfds;
int received = 0;
int num = 0;
char seq[6];
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
int retval = 0;
/************Write to socket*****************/
while (1) {
gettimeofday(&now, NULL);
printf("%f\n %d\n", now.tv_sec + (now.tv_usec / 1000000.0), rtx_queue.size());
FD_ZERO(&rfds);
FD_SET(sockfd, &rfds);
FD_ZERO(&wfds);
FD_SET(sockfd, &wfds);
retval = select(sockfd + 1, &rfds, &wfds, NULL, &timeout);
if (retval == -1)
perror("select()");
p = rtx_queue.begin();
if ((q.empty()) && (p->sequence == 0) && (rtx_queue.size() == 1)) {
printf("done here\n");
break;
}
if (FD_ISSET(sockfd, &rfds)) {
/************* Receive ACK and get sequence number **********************/
bzero(buffer, sizeof (buffer));
received = recvfrom(sockfd, buffer, 5, 0, (struct sockaddr *) &serv_addr, &serverlen);
//printf("received: %d \n", received);
//printf("buffer: %s \n", buffer);
strncpy(seq, buffer, 6);
num = atoi(seq);
//printf("seq: %d \n", num);
p = rtx_queue.begin();
p++;
while (p != rtx_queue.end()) {
//printf("p->sequence: %d sequence: %d \n", p->sequence, num);
if (p->sequence == num) {
rtx_queue.erase(p);
break; // erase() mutates the list, so the iterator is now invalid
}
p++;
}
}
/************* If rtx queue is not empty ************************/
//if (FD_ISSET(sockfd, &wfds)) {
if (!rtx_queue.empty()) {
p = rtx_queue.begin();
p++;
while (p != rtx_queue.end()) {
gettimeofday(&now, NULL);
//printf("p rto: %f \n now time %f \n", p->rto_time, (now.tv_sec + (now.tv_usec / 1000000.0)));
if (p->rto_time > (now.tv_sec + (now.tv_usec / 1000000.0))) {
my_packet->rto_time = p->rto_time;
my_packet->sequence = p->sequence;
my_packet->deadline = p->deadline;
goto fast_path;
}
p++;
/****** Find the first packet in the rtx_queue that has RTO'd *************/
/****** If you find one jump out of here to fast_path *********************/
/****** You can do this any way you want, but, I used a goto ;^) **********/
}
}
if (!q.empty()) {
//if (FD_ISSET(sockfd, &wfds)) {
memset(my_packet, 0, sizeof (*my_packet));
*my_packet = q.front();
q.pop();
//printf("got here \n");
fast_path:
gettimeofday(&now, NULL);
now_time = now.tv_sec + (now.tv_usec / 1000000.0);
while (now_time < my_packet->deadline) {
gettimeofday(&now, NULL);
now_time = now.tv_sec + (now.tv_usec / 1000000.0);
}
my_packet->rto_time = now_time + rto;
//printf("rto_time %f \n", my_packet->rto_time);
bzero(buffer, 1448);
sprintf(buffer, "%.5d %s", my_packet->sequence, my_packet->data);
if ((double) rand() / RAND_MAX > loss) {
n = sendto(sockfd, buffer, PACKET_DATA_LENGTH, 0, (struct sockaddr *) &serv_addr, sizeof (serv_addr));
if (n < 0) perror("ERROR writing to socket");
rtx_queue.push_back(*my_packet);
}
memset(my_packet, 0, sizeof (*my_packet));
get_packet(my_packet, get_deadline());
if (my_packet->deadline != 0)
q.push(*my_packet);
}
//}
}
fclose(pFile);
close(sockfd);
}
double get_deadline() {
deadline_time += inter_packet_delay; //Advance current time pointer
return deadline_time + ( ( ( (double) rand()/RAND_MAX) * 2 * jitter) - jitter );
}
void get_packet(packet* my_packet, double deadline) {
size_t result = fread(&my_packet->data, 1, PACKET_DATA_LENGTH, pFile);
if (result) {
my_packet->deadline = deadline;
// my_packet->read_time = now_time;
my_packet->sequence = current_sequence_number;
// my_packet->data_size = result;
}
current_sequence_number++;
}
|
C | /* Author: Andrew Peklar
* Title: Assingment 5 - csc60mshell
* Teacher: Prof. Nguyen
* Date: 11/25/2015
*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/wait.h>
#include <sys/types.h>
#define MAXPATH 256
#define MAXLINE 80
#define MAXARGS 20
#define MAXJOBS 20
void process_input(int argc, char **argv);
int parseline(char *cmdline, char **argv);
void _exit_error(char* s, bool __exit);
// Declare job array struct
struct job_array {
char command[80];
int process_id;
int job_number;
};
/*Array declaration */
struct job_array myJobs[MAXJOBS];
/* Number of entries in array */
int processes = 0;
/*Returns flag to indicate jobs are/are not running*/
int jobsActive()
{
int i, flag = 0;
for (i = 0; i < processes; i++)
if (myJobs[i].process_id != 0) {
flag = 1;
break;
}
return (flag);
}
/* Loops through jobs then marks finished ones with new pid = 0 */
void childHandler(int sig){
int i,status;
pid_t pid;
while ((pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
for(i = 0; i < processes; i++){
if(myJobs[i].process_id == pid){
if (WIFEXITED(status))
printf("\n[%i] Finished. %s", myJobs[i].job_number, myJobs[i].command);
else if (WIFSIGNALED(status))
printf("\n[%i] Killed. %s", myJobs[i].job_number, myJobs[i].command);
else if (WIFSTOPPED(status))
printf("\n[%i] Stopped. %s", myJobs[i].job_number, myJobs[i].command);
/* Mark for deletion pid = 0 */
myJobs[i].process_id = 0;
}
}
}
}
int main(void) {
pid_t pid;
int argc=0;
int status;
int background = 0;
char cmdline[MAXLINE];
char *argv[MAXARGS];
char path[MAXPATH];
printf("Welcome to csc60mshell!\n");
/* Initialize jobs array */
int i;
for (i=0;i < MAXJOBS;i++)
myJobs[i].process_id = 0;
/* Cntrl-C cmdline (ignore SIGINT signal) */
struct sigaction handler;
handler.sa_handler = SIG_IGN;
sigemptyset(&handler.sa_mask);
handler.sa_flags = 0;
sigaction(SIGINT, &handler, NULL);
/* SIGCHLD ==> signal handler*/
struct sigaction childaction;
childaction.sa_handler = childHandler;
sigemptyset(&childaction.sa_mask);
childaction.sa_flags = 0;
sigaction(SIGCHLD, &childaction, NULL);
for (;;) {
printf("[csc60mshell]> ");
while (fgets(cmdline, MAXLINE, stdin) == NULL) continue;
/*Copy command text for printing use */
char tcmdline[80];
strcpy(tcmdline,cmdline);
argc = parseline(cmdline, argv);
/* This is where the background/foreground assingment happens */
/* Checks input for '&' to mean background process */
if(argc==0) continue; //no argument ==> continue
if(argc > 1 && strcmp(argv[argc-1],"&")==0){ //checks for background
if (processes == MAXJOBS) { //checking to see if more jobs can fit
printf("Max jobs number reached\n");
printf("Run job in front ground\n");
background = 0; //Front gound
}
else
background = 1; //Run job in background
argv[argc-1] = NULL;
argc--;
} else
background = 0;
/* Exit Command; checks if jobs are active before letting user exit */
/* Will prevent user from exiting if jobs are active*/
if(strcmp(argv[0],"exit")==0) {
if (jobsActive()) {
printf("\nERROR: You have %i active processes.",processes);
printf("\nPlease terminate them before exiting\n");
}
else
exit(EXIT_SUCCESS);
}
/* Jobs command */
else if(strcmp(argv[0],"jobs")==0){
if (jobsActive()) { //Checking if there are active jobs to print
printf("Current Jobs:\n");
printf("Num Status Entry \n");
int i;
for(i = 0; i < MAXJOBS; i++){
if (myJobs[i].process_id != 0)
printf("[%d] Running \t %s \n", myJobs[i].job_number, myJobs[i].command);
}
}
}
/* Null input loop */
if (*argv == NULL) continue;
/* cmdline print working directory */
if (strcmp("pwd", argv[0]) == 0) {
printf("%s\n", getenv("PWD"));
continue;
}
/* error handling for invalid cmdlines */
if (*argv[0] == '<' || *argv[0] == '>') {
_exit_error("No cmdline.", false);
continue;
}
/* cmdline cd */
if (strcmp("cd", argv[0]) == 0) {
// Not home
if (argc > 1) chdir(argv[1]);
// Home
else chdir(getenv("HOME"));
/* Updates pwd */
getcwd(path, MAXPATH);
setenv("PWD", path, 1);
continue;
}
else {
pid = fork();
if(pid == -1) perror("Shell programming error, unable to fork.\n");
/* Here is the child process */
else if( pid == 0) {
/* Sigaction handler for child process */
/* Default setting of SIGINT ==> enables termination */
struct sigaction interrupt;
interrupt.sa_handler = SIG_DFL;
sigemptyset(&interrupt.sa_mask);
interrupt.sa_flags = 0;
sigaction(SIGINT, &interrupt, NULL);
/* If background ==> give new process group */
/* Prevents user from accidently killing it */
if(background) setpgid(0,0);
process_input(argc, argv);
}
/* Here the parent process begins */
else if(background) {
/* Logs jobs infor to array and removes */
tcmdline[strlen(tcmdline)-2] = '\0';
strcpy(myJobs[processes].command,tcmdline);
myJobs[processes].job_number = processes;
myJobs[processes].process_id = pid;
processes++;
}else{
if (wait(&status) == -1 ) perror("Shell Program error");
else printf("Child returned status: %d\n",status);
}
}
}
return 0;
}
void process_input(int argc, char **argv) {
int fd;
bool flag = false;
for (int i = 0; i < argc; i++) {
if (argv[i][0] == '<') {
// error checking
if (flag) _exit_error("Can't have two input redirects.", true);
if (argv[i + 1] == NULL) _exit_error("No input redictions file specified.", true);
// open a fd
if((fd = open(argv[i + 1], O_RDONLY)) < 0) perror("open");
// dup the fd and close the fd
if(dup2(fd, 0) < 0) perror("dup2");
close(fd);
argv[i] = NULL;
flag = true;
} else if (strcmp(">", argv[i]) == 0) {
if (argv[i + 1] == NULL) _exit_error("No output file specified.", true);
if ((fd = open(argv[i + 1], O_TRUNC | O_WRONLY | O_CREAT, 0666)) < 0) perror("open");
if (dup2(fd, 1) < 0) perror("dup2");
close(fd);
argv[i] = NULL;
} else if (strcmp(">>", argv[i]) == 0) {
if (argv[i + 1] == NULL) _exit_error("No output file specified.", true);
if ((fd = open(argv[i + 1], O_APPEND | O_WRONLY | O_CREAT, 0666)) < 0) perror("open");
if (dup2(fd, 1) < 0) perror("dup2");
close(fd);
argv[i] = NULL;
}
}
if (execvp(*argv, argv) == -1) {
//perror("process_input, shell program.");
_exit(0);
}
}
/*needed to reference _exit_error */
void _exit_error(char* s, bool __exit) {
printf("ERROR: %s\n", s);
if (__exit) _exit(1);
}
int parseline(char *cmdline, char **argv) {
int count = 0;
char *separator = " \n\t";
argv[count] = strtok(cmdline, separator);
while ((argv[count] != NULL) && (count + 1 < MAXARGS)) {
argv[++count] = strtok((char *) 0, separator);
}
return count;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "Callback.h"
#include "2dArrayCall.h"
double multiply(double x, double y)
{
return x * y;
}
double sinufy(double x, double y)
{
return sin(x) * sin(y);
}
double maxify(double x, double y)
{
return (x > y) ? x : y;
}
void func(double schrittweite, double min, double max, double (*function)(double, double))
{
int size = (max - min) / schrittweite + 1;
double data[size][size];
fillMatrixWithResults(size, min, max, size, min, max, data, function);
print2dArray(size, size, data);
}
int main(void)
{
printf("Beginning Function f:\n");
func(0.5, -1, 1, &multiply);
printf("\nBeginning Function g:\n");
func(M_PI/4, 0, M_PI, &sinufy);
printf("\nBeginning Function h:\n");
func(1, 0, 10, &maxify);
return 0;
}
|
C | #include "function_pointers.h"
/**
* print_name - Function that prints a name.
* @name: Name variable to print
* @f: name of the function pointer
*/
void print_name(char *name, void (*f)(char *))
{
if (f == NULL)
return;
if (name == NULL)
return;
f(name);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: raubert <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/04 19:21:18 by raubert #+# #+# */
/* Updated: 2020/01/09 15:19:21 by raubert ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static int ft_free(char **contain, int k)
{
if (*contain)
{
free(*contain);
*contain = NULL;
}
return (k);
}
static int ft_is_bn(char *str)
{
int i;
i = 0;
while (str[i])
{
if (str[i] == '\n')
return (i);
i++;
}
return (-1);
}
static int ft_modif(char **line, char **contain)
{
char *tmp;
int index;
index = ft_is_bn(*contain);
if (index == (-1))
{
*line = ft_strdup(*contain);
return (ft_free(contain, 0));
}
*line = ft_substr(*contain, 0, index);
tmp = ft_substr(*contain, index + 1, ft_strlen(*contain) - index - 1);
free(*contain);
*contain = tmp;
return (1);
}
int get_next_line(int fd, char **line)
{
static char *contain;
char *buff;
ssize_t read_ret;
if ((!(line)) || (fd < 0) || (BUFFER_SIZE < 1) ||
(!(buff = malloc(sizeof(char) * (BUFFER_SIZE + 1)))))
return (ft_free(&contain, -1));
while ((read_ret = read(fd, buff, BUFFER_SIZE)) > 0)
{
buff[read_ret] = '\0';
if (!(ft_strjoin(&contain, buff)))
return (ft_free(&contain, 0));
if (ft_is_bn(contain) != (-1))
break ;
}
free(buff);
if (read_ret < 0)
return (ft_free(&contain, -1));
if ((ft_strncmp(contain, "", ft_strlen(contain)) == 0) && read_ret == 0)
{
*line = ft_strdup("");
return (ft_free(&contain, 0));
}
return (ft_modif(line, &contain));
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void print_arr(int*arr, int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%2d", arr[i]);
}
printf("\n");
}
void bubble_sort(int* arr, int sz)
{
int i = 0;
for(i=0; i<sz-1; i++)
{
int j = 0;
for(j=0; j<sz-1-i; j++)
{
if(arr[j] > arr[j+1])
{
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
int main()
{
int arr[] = {9,8,7,6,5,4,3,2,1,0};
int sz = sizeof(arr)/sizeof(arr[0]);
bubble_sort(arr, sz);
print_arr(arr, sz);
return 0;
}
|
C | /*
Victor Andres Villarreal
A01039863
13/03/2020
Convert the sequence of hexadecimal numbers that the user inputs using the command line to the
corresponding decimals. User may input as many numbers as desired and any invalid number is
not converted and outputs an error message.
*/
#include <stdio.h>
#include <stdbool.h>
#include <float.h>
#include <string.h>
#include <math.h>
#include<stdlib.h>
void asciiHEXToInt(char *s);
int hexCharValue(char c);
//main function
//inputs a string contianing an hexadecimal number to convert
int main(){
char hex[33];
while(1==1){
printf ("Enter a hexadecimal number.\n");
scanf("%s", hex);
asciiHEXToInt(hex);
}
}
//Function that receives a string representing an hexadecimal number and prints the decimal equivalent value
void asciiHEXToInt(char *s){
bool valid = true;
int res = 0;
for(int i=0; i<strlen(s); i++){
long unsigned int exp = strlen(s)-i-1;
//while it is receiving a valid character
if((s[i]>='0' && s[i]<='9') || (s[i]>='a'&&s[i]<='f') || (s[i]>='A' && s[i]<='F')){
res = res + pow(16,exp) * hexCharValue(s[i]);
}
else{
//if invalid character is received
printf("Error: Invalid number \n \n");
valid = false;
return;
}
}
//print converted value if the string was valid
if(valid){
printf("Hexadecimal number has the decimal value of %d \n \n", res);
}
}
//converts a single char to its equivalent value from hexadecimal to decimal number
int hexCharValue(char c){
if(c>'9'){
if(c>='a'){
return (int)(c - 'a' + 10);
}
else{
return (int)(c - 'A' + 10);
}
}
else{
return (int)(c - '0');
}
}
|
C |
#include <stdio.h>
enum weekday {
Monday=1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
};
char *nazwa[] =
{ "",
"poniedziałek", "wtorek", "środa", "czwartek", "piątek",
"sobota", "niedziela" };
int main() {
enum weekday d;
d=Thursday;
printf("%d. dzień tygodnia to %s\n", d, nazwa[d]);
return 0;
}
|
C | /*
* thomas_alg.c
*
* Copyright 2019 Suraj Pawar <[email protected]>
*
* This program solves the tridogonal matrix Ax = b using Thomas algorithm. The three basic steps are
* 1. LU decomposition
* 2. Forward substitution
* 3. Backward substitution
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void ThomasAlgorithm(int N, double *b, double *a, double *c, double *x, double *q)
{
int i;
double *l = malloc( sizeof(double) * N);
double *d = malloc( sizeof(double) * N);
double *u = malloc( sizeof(double) * N);
double *y = malloc( sizeof(double) * N);
// c++ syntax
//double *l, *u, *d, *y;
//l = new double[N];
//u = new double[N];
//d = new double[N];
//y = new double[N];
/* LU decomposition A = LU*/
d[0] = a[0];
u[0] = c[0];
for (i=0;i<N-2;i++)
{
l[i] = b[i]/d[i];
d[i+1] = a[i+1]-l[i]*u[i];
u[i+1] = c[i+1];
}
l[N-2] = b[N-2]/d[N-2];
d[N-1] = a[N-1] - l[N-2]*u[N-2];
/* Forward substitution Ly = q */
y[0] = q[0];
for (i=1;i<N;i++)
{
y[i] = q[i]-l[i-1]*y[i-1];
}
/* Backward substitution Ux = y */
x[N-1] = q[N-1]/d[N-1];
for (i = N-2; i>=0; i--)
{
x[i] = (y[i]-u[i]*x[i+1])/d[i];
}
free( l );
free( u );
free( d );
free( y );
// c++ syntax
//delete[] l;
//delete[] d;
//delete[] u;
//delete[] y;
return;
}
int main()
{
int N;
N = 5;
double a[N], b[N], c[N], x[N], q[N];
double *p;
p = &b[0];
int i;
a[0] = 1.0;
c[0] = 0.0;
q[0] = 100.0; // left boundary
x[0] = 0.0;
for(i=0; i<N-2; i++)
{
b[i] = 1.0;
a[i+1] = -2.0;
c[i+1] = 1.0;
q[i+1] = 0.0;
x[i+1] = 0.0;// initial condition
}
// printf("pointer = %g", p[1]);
b[N-2] = 0.0;
a[N-1] = 1.0;
q[N-1] = 50.0; // right boundary
x[N-1] = 0.0;
ThomasAlgorithm(N, a, b, c, x, q);
// print arrays a,b,c
for (i = 0;i<N; i++)
{
printf("a[%d] = %g\n", i, x[i]);
printf("b[%d] = %g\n", i, q[i]);
//printf("c[%d] = %g\n", i, c[i]);
}
return 0;
}
|
C | #include <stdio.h>
#define MAX 30
#define MIN 20
int main() {
#if defined(MAX) // if MAX
printf("The maximum value : %d",MAX);
#else
printf("The minimum value : %d",MAX);
#endif
printf("\n");
#if MIN // if !defined(MIN)
printf("The minimum value : %d",MIN);
#else
printf("The minimum value : %d",MIN);
#endif
return 0;
}
|
C | /*
1. Faça um programa que possua um vetor denominado A que armazene 6 numeros intei- ´
ros. O programa deve executar os seguintes passos:
(a) Atribua os seguintes valores a esse vetor: 1, 0, 5, -2, -5, 7.
(b) Armazene em uma variavel inteira (simples) a soma entre os valores das posic¸ ´ oes ˜
A[0], A[1] e A[5] do vetor e mostre na tela esta soma.
(c) Modifique o vetor na posic¸ao 4, atribuindo a esta posic¸ ˜ ao o valor 100. ˜
(d) Mostre na tela cada valor do vetor A, um em cada linha.
*/
#include <stdio.h>
int main() {
int a[6] = {1, 0, 5, -2, -5, 7}, sum = a[0] + a[1] + a[5];
printf("Resultado da soma: %d", sum);
a[4] = 100;
for (int i = 0; i < 6; ++i) {
printf("\nA[%d] = %d", i, a[i]);
}
} |
C | // print the transition probability table of action : 4(down) to ./action_4.csv
#include <stdio.h>
#include <stdlib.h>
int main() {
float action_1[100][100] = {{0}};
int i = 0;
int j = 0;
FILE *fp;
for(i = 10; i <= 99; ++i) // assume all get into the down cell when taking action : 4(down)
action_1[i][i - 10] = 1;
for (i = 0; i <= 9; ++i) // down edge
action_1[i][i] = 1;
for(i = 0; i < 100; ++i) { // down barrier
if(i == 18 || i == 19 || i == 60 || i == 61 || i == 87) { // discard i == 31 (cell a)
action_1[i][i - 10] = 0;
action_1[i][i] = 1;
}
}
action_1[99][89] = 0; // final state
action_1[31][21] = 0; // a
action_1[41][31] = 0;
action_1[41][71] = 0.6;
action_1[41][9] = 0.4;
action_1[14][4] = 0; // b
action_1[24][14] = 0;
action_1[24][57] = 0.4;
action_1[24][12] = 0.6;
action_1[48][38] = 0; // c
action_1[58][48] = 0;
action_1[58][96] = 0.7;
action_1[58][25] = 0.3;
fp = fopen("action_4.csv", "w");
for (i = 0; i < 100; ++i) {
for (j = 0; j < 100; ++j) {
if(action_1[i][j] != 0 && action_1[i][j] != 0)
fprintf(fp, "%.1f", action_1[i][j]);
else
fprintf(fp, "%.0f", action_1[i][j]);
if(j != 99)
fprintf(fp, ",");
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
|
C | #include <stdio.h>
#define STOP_MAX_PASS 10000
#define PRINT_LIST 0
#define BUS_MAX_PASS 250
#define MAX_STOPS 500
#define PASS_STATUS_END_LIST 255
#define PASS_STATUS_EMPTY 0
#define PASS_STATUS_TO_ARRIVE 1
#define PASS_STATUS_ARRIVED 2
#define PASS_STATUS_IN_BUS 3
#define PASS_STATUS_ALIGHTED 4
#define FALSE 0
#define TRUE 1
typedef struct {
unsigned int pass_id;
unsigned short orig_stop;
unsigned short dest_stop;
unsigned short arrival_time;
unsigned short alight_time;
unsigned char status;
} __attribute__ ((packed)) PassType;
// Stop Passengers Struct List (SPSL)
typedef struct {
unsigned short stop_num;
unsigned int total;
unsigned int last_empty;
unsigned int w_index;
PassType spl[STOP_MAX_PASS];
} __attribute__ ((packed)) SpslType;
// Bus Passengers Struct List (BPSL)
typedef struct {
unsigned short curr_stop;
unsigned short last_stop_i;
unsigned short total_stops;
unsigned short stops_num[MAX_STOPS];
unsigned int total;
unsigned int last_empty;
unsigned int w_index;
PassType bpl[BUS_MAX_PASS];
} __attribute__ ((packed)) BpslType;
void move_pass(
SpslType *pass_list,
SpslType *pass_arrival_list,
unsigned int stops_size,
unsigned int sim_time
)
{
for (int i = 0; i < stops_size; ++i) {
#if PRINT_LIST
printf("\nPost stop %d, total %d, wIndex %d\n" ,
pass_arrival_list[i].stop_num, pass_arrival_list[i].total, pass_arrival_list[i].w_index);
for (int j = 0; j < pass_arrival_list[i].total; ++j) {
printf("passId %d, origStop %d, destStop %d, arrivalTime %d, alightTime %d, status %d\n",
pass_arrival_list[i].spl[j].pass_id,
pass_arrival_list[i].spl[j].orig_stop,
pass_arrival_list[i].spl[j].dest_stop,
pass_arrival_list[i].spl[j].arrival_time,
pass_arrival_list[i].spl[j].alight_time,
pass_arrival_list[i].spl[j].status);
}
#endif
unsigned int w;
//printf("In i %d total: %d\n", i, pass_arrival_list[i].total);
if(pass_arrival_list[i].total > 0){
#if 1
//printf("sim_time: %d\n", sim_time);
while(1){
//printf("pass_id(%d): %d\n", pass_arrival_list[i].w_index, pass_arrival_list[i].spl[pass_arrival_list[i].w_index].pass_id);
w = pass_arrival_list[i].w_index;
if(w >= STOP_MAX_PASS){
break;
}
if(pass_arrival_list[i].spl[w].status != 1){
break;
}
if(sim_time < pass_arrival_list[i].spl[w].arrival_time){
break;
}
//printf("In i %d moving pass_id(%d): %d\n", i, w, pass_arrival_list[i].spl[w].pass_id);
pass_list[i].spl[pass_list[i].last_empty] = pass_arrival_list[i].spl[w];
pass_list[i].spl[pass_list[i].last_empty].status = 2;
#if 1
for (int k = 0; k < STOP_MAX_PASS; ++k) {
pass_list[i].spl[pass_list[i].last_empty].alight_time *=
pass_list[i].spl[pass_list[i].last_empty].pass_id;
}
#endif
pass_list[i].last_empty ++;
pass_list[i].total ++;
pass_arrival_list[i].spl[w].status = 0;
pass_arrival_list[i].w_index ++;
pass_arrival_list[i].total --;
pass_arrival_list[i].last_empty --;
if(pass_arrival_list[i].total == 0){
break;
}
//printf("2 pass_id(%d): %d\n", pass_arrival_list[i].w_index, pass_arrival_list[i].spl[pass_arrival_list[i].w_index].arrival_time);
}
#endif
}
}
}
|
C | #ifndef _AMF_H
# define _AMF_H
#include <stdint.h>
#include "endian.h"
#define AMF_NUMBER (0x00)
#define AMF_BOOLEAN (0x01)
#define AMF_STRING (0x02)
#define AMF_OBJECT (0x03)
#define AMF_NULL (0x05)
#define AMF_UNDEFINED (0x06)
#define AMF_ARRAY (0x08)
#define AMF_OAEND (0x09)
#define AMF_TYPEDOBJECT (0x10)
struct amf_kvlist;
struct amf_vlist;
struct amf_typed_object;
struct amf_string {
uint16_t length;
char *value;
};
struct amf_array {
uint32_t count;
struct amf_vlist *first;
};
struct amf_object {
struct amf_value *type;
struct amf_kvlist *first;
};
struct amf_value {
int retain_count;
char type;
union {
double number;
char boolean;
struct amf_string string;
struct amf_object object;
struct amf_array array;
} v;
};
struct amf_kv {
struct amf_value *key;
struct amf_value *value;
};
struct amf_kvlist {
struct amf_kv entry;
struct amf_kvlist *next;
};
struct amf_vlist {
struct amf_value *value;
struct amf_vlist *next;
};
typedef struct amf_value *AMFValue;
typedef double AMFNumber;
typedef char AMFBoolean;
typedef struct {
struct amf_value *array;
struct amf_vlist *current;
} AMFArrayIter;
typedef struct {
struct amf_value *object;
struct amf_kvlist *current;
} AMFObjectIter;
typedef struct amf_kv AMFKeyValuePair;
AMFValue amf_retain(AMFValue v);
void amf_release(AMFValue v);
AMFValue amf_new_number(double number);
AMFValue amf_new_boolean(char boolean);
AMFValue amf_new_string(const char *string, int length);
AMFValue amf_new_object();
AMFValue amf_new_null();
AMFValue amf_new_undefined();
AMFValue amf_new_array();
AMFValue amf_new_typed_object(AMFValue classname);
const char *amf_cstr(AMFValue v);
int amf_strlen(AMFValue v);
int amf_strcmp(AMFValue a, AMFValue b);
AMFValue amf_object_get(AMFValue v, AMFValue key);
AMFValue amf_object_set(AMFValue v, AMFValue key, AMFValue value);
void amf_objectiter_init(AMFObjectIter *it, AMFValue v);
void amf_objectiter_cleanup(AMFObjectIter *it);
void amf_objectiter_next(AMFObjectIter *it);
AMFKeyValuePair *amf_objectiter_current(AMFObjectIter *it);
AMFValue amf_array_push(AMFValue v, AMFValue e);
void amf_arrayiter_init(AMFArrayIter *it, AMFValue v);
void amf_arrayiter_cleanup(AMFArrayIter *it);
void amf_arrayiter_next(AMFArrayIter *it);
AMFValue amf_arrayiter_current(AMFArrayIter *it);
AMFValue amf_parse_value(const char *data, int length, int *left);
void amf_dump(AMFValue v);
#endif
|
C | /******************************************************************************
*
* Copyright 2019 Barun Corechips All Rights Reserved
*
* Project : 12_IF
* Filename : main.c
* Author : sj.yang
* Version : 1.0
*
*******************************************************************************/
#include <stdio.h>
int main(void)
{
char ch='a';
char CH;
if(ch =='a') CH='A';
else if(ch =='b') CH='B';
else if(ch =='c') CH='C';
else CH=' ';
printf("\nThe capital of %c is %c\n",ch,CH);
/*
int phy = 50;
int che = 100;
int cal = 90;
float ave=0;
char grade;
ave=(phy+che+cal)/3;
if(ave>=90) grade='A';
else if(ave>=80) grade='B';
else if(ave>=70) grade='C';
else if(ave>=60) grade='D';
else grade='F';
printf("\nAVERAGE : %0.2f\n", ave);
printf(" GRADE : %c\n",grade);
*/
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
void main() {
int A;
int B;
int C;
printf("veuillez entrer un cote AB:");
scanf_s("%d", &A);
printf("veuillez entrer un cote BC:");
scanf_s("%d", &B);
printf("veuillez entrer un cote CA:");
scanf_s("%d", &C);
if ((A + C >= B) && (B + C >= A) && (B + A >= C)) {
printf("il existe un triangle ABC");
}
else {
printf("il n'existe pas de triangle ABC");
}
} |
C | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Slabs memory allocation, based on powers-of-N. Slabs are up to 1MB in size
* and are divided into chunks. The chunk sizes start off at the size of the
* "item" structure plus space for a small key and value. They increase by
* a multiplier factor from there, up to half the maximum slab size. The last
* slab size is always 1MB, since that's the maximum item size allowed by the
* memcached protocol.
*/
#ifndef __WIN32__
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <sys/resource.h>
#include <netinet/in.h>
#endif
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
#include <inttypes.h>
#include <stdarg.h>
#include "compress_engine.h"
/*
* Forward Declarations
*/
static int do_slabs_newslab(struct compress_engine *engine, const unsigned int id);
static void *memory_allocate(struct compress_engine *engine, size_t size);
#ifndef DONT_PREALLOC_SLABS
/* Preallocate as many slab pages as possible (called from slabs_init)
on start-up, so users don't get confused out-of-memory errors when
they do have free (in-slab) space, but no space to make new slabs.
if maxslabs is 18 (POWER_LARGEST - POWER_SMALLEST + 1), then all
slab types can be made. if max memory is less than 18 MB, only the
smaller ones will be made. */
static void slabs_preallocate (const unsigned int maxslabs);
#endif
/*
* Figures out which slab class (chunk size) is required to store an item of
* a given size.
*
* Given object size, return id to use when allocating/freeing memory for object
* 0 means error: can't store such a large object
*/
unsigned int slabs_clsid(struct compress_engine *engine, const size_t size) {
int res = POWER_SMALLEST;
if (size == 0)
return 0;
while (size > engine->slabs.slabclass[res].size)
if (res++ == engine->slabs.power_largest) /* won't fit in the biggest slab */
return 0;
return res;
}
/**
* Determines the chunk sizes and initializes the slab class descriptors
* accordingly.
*/
ENGINE_ERROR_CODE slabs_init(struct compress_engine *engine,
const size_t limit,
const double factor,
const bool prealloc) {
int i = POWER_SMALLEST - 1;
unsigned int size = sizeof(hash_item) + engine->config.chunk_size;
engine->slabs.mem_limit = limit;
if (prealloc) {
/* Allocate everything in a big chunk with malloc */
engine->slabs.mem_base = malloc(engine->slabs.mem_limit);
if (engine->slabs.mem_base != NULL) {
engine->slabs.mem_current = engine->slabs.mem_base;
engine->slabs.mem_avail = engine->slabs.mem_limit;
} else {
return ENGINE_ENOMEM;
}
}
memset(engine->slabs.slabclass, 0, sizeof(engine->slabs.slabclass));
while (++i < POWER_LARGEST && size <= engine->config.item_size_max / factor) {
/* Make sure items are always n-byte aligned */
if (size % CHUNK_ALIGN_BYTES)
size += CHUNK_ALIGN_BYTES - (size % CHUNK_ALIGN_BYTES);
engine->slabs.slabclass[i].size = size;
engine->slabs.slabclass[i].perslab = engine->config.item_size_max / engine->slabs.slabclass[i].size;
size *= factor;
if (engine->config.verbose > 1) {
fprintf(stderr, "slab class %3d: chunk size %9u perslab %7u\n",
i, engine->slabs.slabclass[i].size, engine->slabs.slabclass[i].perslab);
}
}
engine->slabs.power_largest = i;
engine->slabs.slabclass[engine->slabs.power_largest].size = engine->config.item_size_max;
engine->slabs.slabclass[engine->slabs.power_largest].perslab = 1;
if (engine->config.verbose > 1) {
fprintf(stderr, "slab class %3d: chunk size %9u perslab %7u\n",
i, engine->slabs.slabclass[i].size, engine->slabs.slabclass[i].perslab);
}
/* for the test suite: faking of how much we've already malloc'd */
{
char *t_initial_malloc = getenv("T_MEMD_INITIAL_MALLOC");
if (t_initial_malloc) {
engine->slabs.mem_malloced = (size_t)atol(t_initial_malloc);
}
}
#ifndef DONT_PREALLOC_SLABS
{
char *pre_alloc = getenv("T_MEMD_SLABS_ALLOC");
if (pre_alloc == NULL || atoi(pre_alloc) != 0) {
slabs_preallocate(power_largest);
}
}
#endif
return ENGINE_SUCCESS;
}
#ifndef DONT_PREALLOC_SLABS
static void slabs_preallocate (const unsigned int maxslabs) {
int i;
unsigned int prealloc = 0;
/* pre-allocate a 1MB slab in every size class so people don't get
confused by non-intuitive "SERVER_ERROR out of memory"
messages. this is the most common question on the mailing
list. if you really don't want this, you can rebuild without
these three lines. */
for (i = POWER_SMALLEST; i <= POWER_LARGEST; i++) {
if (++prealloc > maxslabs)
return;
do_slabs_newslab(i);
}
}
#endif
static int grow_slab_list (struct compress_engine *engine, const unsigned int id) {
slabclass_t *p = &engine->slabs.slabclass[id];
if (p->slabs == p->list_size) {
size_t new_size = (p->list_size != 0) ? p->list_size * 2 : 16;
void *new_list = realloc(p->slab_list, new_size * sizeof(void *));
if (new_list == 0) return 0;
p->list_size = new_size;
p->slab_list = new_list;
}
return 1;
}
static int do_slabs_newslab(struct compress_engine *engine, const unsigned int id) {
slabclass_t *p = &engine->slabs.slabclass[id];
int len = p->size * p->perslab;
char *ptr;
if ((engine->slabs.mem_limit && engine->slabs.mem_malloced + len > engine->slabs.mem_limit && p->slabs > 0) ||
(grow_slab_list(engine, id) == 0) ||
((ptr = memory_allocate(engine, (size_t)len)) == 0)) {
return 0;
}
memset(ptr, 0, (size_t)len);
p->end_page_ptr = ptr;
p->end_page_free = p->perslab;
p->slab_list[p->slabs++] = ptr;
engine->slabs.mem_malloced += len;
return 1;
}
/*@null@*/
static void *do_slabs_alloc(struct compress_engine *engine, const size_t size, unsigned int id) {
slabclass_t *p;
void *ret = NULL;
if (id < POWER_SMALLEST || id > engine->slabs.power_largest) {
return NULL;
}
p = &engine->slabs.slabclass[id];
#ifdef USE_SYSTEM_MALLOC
if (engine->slabs.mem_limit && engine->slabs.mem_malloced + size > engine->slabs.mem_limit) {
return 0;
}
engine->slabs.mem_malloced += size;
ret = malloc(size);
return ret;
#endif
/* fail unless we have space at the end of a recently allocated page,
we have something on our freelist, or we could allocate a new page */
if (! (p->end_page_ptr != 0 || p->sl_curr != 0 ||
do_slabs_newslab(engine, id) != 0)) {
/* We don't have more memory available */
ret = NULL;
} else if (p->sl_curr != 0) {
/* return off our freelist */
ret = p->slots[--p->sl_curr];
} else {
/* if we recently allocated a whole page, return from that */
assert(p->end_page_ptr != NULL);
ret = p->end_page_ptr;
if (--p->end_page_free != 0) {
p->end_page_ptr = ((caddr_t)p->end_page_ptr) + p->size;
} else {
p->end_page_ptr = 0;
}
}
if (ret) {
p->requested += size;
}
return ret;
}
static void do_slabs_free(struct compress_engine *engine, void *ptr, const size_t size, unsigned int id) {
slabclass_t *p;
if (id < POWER_SMALLEST || id > engine->slabs.power_largest)
return;
p = &engine->slabs.slabclass[id];
#ifdef USE_SYSTEM_MALLOC
mem_malloced -= size;
free(ptr);
return;
#endif
if (p->sl_curr == p->sl_total) { /* need more space on the free list */
int new_size = (p->sl_total != 0) ? p->sl_total * 2 : 16; /* 16 is arbitrary */
void **new_slots = realloc(p->slots, new_size * sizeof(void *));
if (new_slots == 0)
return;
p->slots = new_slots;
p->sl_total = new_size;
}
p->slots[p->sl_curr++] = ptr;
p->requested -= size;
return;
}
void add_statistics(const void *cookie, ADD_STAT add_stats,
const char* prefix, int num, const char *key,
const char *fmt, ...) {
char name[80], val[80];
int klen = 0, vlen;
va_list ap;
assert(cookie);
assert(add_stats);
assert(key);
va_start(ap, fmt);
vlen = vsnprintf(val, sizeof(val) - 1, fmt, ap);
va_end(ap);
if (prefix != NULL) {
klen = snprintf(name, sizeof(name), "%s:", prefix);
}
if (num != -1) {
klen += snprintf(name + klen, sizeof(name) - klen, "%d:", num);
}
klen += snprintf(name + klen, sizeof(name) - klen, "%s", key);
add_stats(name, klen, val, vlen, cookie);
}
/*@null@*/
static void do_slabs_stats(struct compress_engine *engine, ADD_STAT add_stats, const void *cookie) {
int i, total;
/* Get the per-thread stats which contain some interesting aggregates */
#ifdef FUTURE
struct conn *conn = (struct conn*)cookie;
struct thread_stats thread_stats;
threadlocal_stats_aggregate(c, &thread_stats);
#endif
total = 0;
for(i = POWER_SMALLEST; i <= engine->slabs.power_largest; i++) {
slabclass_t *p = &engine->slabs.slabclass[i];
if (p->slabs != 0) {
uint32_t perslab, slabs;
slabs = p->slabs;
perslab = p->perslab;
add_statistics(cookie, add_stats, NULL, i, "chunk_size", "%u",
p->size);
add_statistics(cookie, add_stats, NULL, i, "chunks_per_page", "%u",
perslab);
add_statistics(cookie, add_stats, NULL, i, "total_pages", "%u",
slabs);
add_statistics(cookie, add_stats, NULL, i, "total_chunks", "%u",
slabs * perslab);
add_statistics(cookie, add_stats, NULL, i, "used_chunks", "%u",
slabs*perslab - p->sl_curr - p->end_page_free);
add_statistics(cookie, add_stats, NULL, i, "free_chunks", "%u",
p->sl_curr);
add_statistics(cookie, add_stats, NULL, i, "free_chunks_end", "%u",
p->end_page_free);
add_statistics(cookie, add_stats, NULL, i, "mem_requested", "%zu",
p->requested);
#ifdef FUTURE
add_statistics(cookie, add_stats, NULL, i, "get_hits", "%"PRIu64,
thread_stats.slab_stats[i].get_hits);
add_statistics(cookie, add_stats, NULL, i, "cmd_set", "%"PRIu64,
thread_stats.slab_stats[i].set_cmds);
add_statistics(cookie, add_stats, NULL, i, "delete_hits", "%"PRIu64,
thread_stats.slab_stats[i].delete_hits);
add_statistics(cookie, add_stats, NULL, i, "cas_hits", "%"PRIu64,
thread_stats.slab_stats[i].cas_hits);
add_statistics(cookie, add_stats, NULL, i, "cas_badval", "%"PRIu64,
thread_stats.slab_stats[i].cas_badval);
#endif
total++;
}
}
/* add overall slab stats and append terminator */
add_statistics(cookie, add_stats, NULL, -1, "active_slabs", "%d", total);
add_statistics(cookie, add_stats, NULL, -1, "total_malloced", "%zu",
engine->slabs.mem_malloced);
add_stats(NULL, 0, NULL, 0, cookie);
}
static void *memory_allocate(struct compress_engine *engine, size_t size) {
void *ret;
if (engine->slabs.mem_base == NULL) {
/* We are not using a preallocated large memory chunk */
ret = malloc(size);
} else {
ret = engine->slabs.mem_current;
if (size > engine->slabs.mem_avail) {
return NULL;
}
/* mem_current pointer _must_ be aligned!!! */
if (size % CHUNK_ALIGN_BYTES) {
size += CHUNK_ALIGN_BYTES - (size % CHUNK_ALIGN_BYTES);
}
engine->slabs.mem_current = ((char*)engine->slabs.mem_current) + size;
if (size < engine->slabs.mem_avail) {
engine->slabs.mem_avail -= size;
} else {
engine->slabs.mem_avail = 0;
}
}
return ret;
}
void *slabs_alloc(struct compress_engine *engine, size_t size, unsigned int id) {
void *ret;
pthread_mutex_lock(&engine->slabs.lock);
ret = do_slabs_alloc(engine, size, id);
pthread_mutex_unlock(&engine->slabs.lock);
return ret;
}
void slabs_free(struct compress_engine *engine, void *ptr, size_t size, unsigned int id) {
pthread_mutex_lock(&engine->slabs.lock);
do_slabs_free(engine, ptr, size, id);
pthread_mutex_unlock(&engine->slabs.lock);
}
void slabs_stats(struct compress_engine *engine, ADD_STAT add_stats, const void *c) {
pthread_mutex_lock(&engine->slabs.lock);
do_slabs_stats(engine, add_stats, c);
pthread_mutex_unlock(&engine->slabs.lock);
}
|
C | // Author: Walerij Hrul
//
// Imitation of worker class implementation
//
#ifndef WORKERS_H
#define WORKERS_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include "sort.h"
#include "projects.h"
#include "project_worker.h"
#include "managers.h"
// return workerHead
Worker* addWorker( Worker* workerHead, char surname[], char name[], int id, bool* badAlloc );
// return the highest id among workers, 0 if empty
unsigned long long maxWorkerId( Worker* workerHead );
// return NULL if there is non
Worker* searchWorkerById( Worker* workerHead, int id );
// return wokerHead; show info in output stream if there is no one with such id
Worker* dropWorker( Worker* workerHead, int id, Project_Worker** project_workerHead );
// display list of workers (id & surname & name) / info that it is empty
void showWorkers( Worker* workerHead );
// display list of workers (id & surname & name & projects) / info that it is empty
void showFullWorkers( Project* projectHead, Worker* workerHead, Project_Worker* project_workerHead, char id );
// free allocated memory; set workerHead as NULL
void clearWorkers( Worker** workerHead );
#endif
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sub.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apion <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/16 18:19:35 by apion #+# #+# */
/* Updated: 2019/06/14 11:35:11 by jkettani ### ########.fr */
/* */
/* ************************************************************************** */
#include "bigint.h"
static unsigned int compute_substraction(unsigned long alpha,
unsigned long beta, unsigned long *carry, int no_carry)
{
unsigned int result;
if (no_carry)
{
result = (unsigned int)(alpha - beta - *carry);
*carry = 0;
}
else
{
result = (unsigned int)(
(1UL << BIGINT_SIZE_BLOCK) + alpha - beta - *carry);
*carry = 1;
}
return (result);
}
static void sub_and_shrink_length(t_bigint *result,
t_bigint *a, t_bigint *b)
{
unsigned int i;
int n_null_block;
unsigned long alpha;
unsigned long beta;
unsigned long carry;
n_null_block = 0;
carry = 0;
i = 0;
while (i < a->length)
{
alpha = (unsigned long)a->blocks[i];
beta = (unsigned long)b->blocks[i];
if (alpha >= beta + carry)
result->blocks[i] = compute_substraction(alpha, beta, &carry, 1);
else
result->blocks[i] = compute_substraction(alpha, beta, &carry, 0);
n_null_block = (result->blocks[i] == 0 && i) ? n_null_block + 1 : 0;
++i;
}
result->length -= n_null_block;
}
void bigint_sub_int(t_bigint *result, t_bigint *a,
unsigned int n)
{
t_bigint b;
bigint_init_int(&b, n);
bigint_sub(result, a, &b);
}
void bigint_sub(t_bigint *result, t_bigint *a, t_bigint *b)
{
t_bigint temp;
if (bigint_is_underflow(a) || bigint_is_underflow(b)
|| bigint_cmp(a, b) < 0)
result->blocks[BIGINT_N_BLOCKS] = BIGINT_UNDERFLOW;
else
{
bigint_init_null(&temp);
temp.length = a->length;
sub_and_shrink_length(&temp, a, b);
bigint_copy(result, &temp);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define HIGH 3
#define MEDIUM 2
#define LOW 1
struct node{
int val;
int priority;
struct node* next;
};
struct node *head = NULL;
void insert(int val, int priority){
// Flag is unset when the element is added to its proper position
int flag = 1;
struct node *new_node = malloc(sizeof(struct node));
struct node *temp, *prev;
new_node->val = val;
new_node->priority = priority;
new_node->next = NULL;
if (head == NULL){
head = new_node;
return;
}
else if(head->priority < priority){
new_node->next = head;
head = new_node;
return;
}
prev = temp = head;
while(flag != 0 && temp != NULL){
if (temp->next == NULL && priority == temp->priority)
{
temp->next = new_node;
flag = 0;
}
else if (priority <= temp->priority && temp->next != NULL){
prev = temp;
// temp->next = new_node;
temp = temp->next;
}
else{
prev->next = new_node;
new_node->next = temp;
flag = 0;
}
}
}
// Print entire list
void display(){
struct node *temp = head;
// printf("Head val: %d", temp->val);
while (temp != NULL)
{
printf("%d -> ", temp->val);
temp = temp->next;
}
printf("NULL\n");
}
int main(int argc, char const *argv[])
{
insert(1, LOW);
insert(1, LOW);
insert(1, LOW);
insert(2, MEDIUM);
insert(2, MEDIUM);
insert(3, HIGH);
insert(3, HIGH);
insert(3, HIGH);
display();
return 0;
}
|
C | /* NAME : FNU SHIVA SANDESH
Email : [email protected]
UID : 111111111
Project 2A - Summer 2017 - CS 111 */
#include <stdio.h> // for stadard in and out
#include <stdlib.h> // for Standard in
#include <string.h> // for strerror
#include <pthread.h>
#include "SortedList.h"
#include <sched.h>
/*
struct SortedListElement {
struct SortedListElement *prev;
struct SortedListElement *next;
const char *key;
};
*/
void SortedList_insert(SortedList_t *list, SortedListElement_t *element){
if(element == NULL) return;
SortedListElement_t *ptr = list;
while(ptr->next != NULL ){
if(strcmp(element->key,ptr->next->key) > 0) {
ptr = ptr -> next;
}
//if(strcmp(element->key,ptr->key) <= 0)
else break;
}
if (opt_yield & INSERT_YIELD)
pthread_yield();
if(ptr->next != NULL)
ptr->next->prev = element;
element->next = ptr->next;
element->prev = ptr;
//ptr->prev->next = element;
ptr->next = element;
}
int SortedList_delete( SortedListElement_t *element){
if(element == NULL) return 1;
SortedListElement_t *prev_Node = element->prev;
SortedListElement_t *next_Node = element->next;
if(next_Node != NULL){
if(next_Node->prev != element ) return 1;
}
if(prev_Node->next != element) return 1;
if(next_Node != NULL)
element->next->prev = prev_Node;
if(opt_yield & DELETE_YIELD)
pthread_yield();
element->prev->next = next_Node;
// free(element); //do it in the client. Client should be responsible for memmory deallocation.
//if(next != NULL) element->next->prev = elemetn->prev; <---- this is problem gdb pointed here.
// can't do this pointer set incorrectly
return 0;
}
SortedListElement_t *SortedList_lookup(SortedList_t *list, const char *key){
if(key == NULL ) return NULL;
SortedListElement_t *curr_Node = list->next;
while(curr_Node != NULL){
if(strcmp(curr_Node->key, key) == 0)
return curr_Node;
if (opt_yield & LOOKUP_YIELD)
pthread_yield();
curr_Node = curr_Node->next;
}
return NULL;
}
int SortedList_length(SortedList_t *list){
// empty list
if(list == NULL) return -1;
SortedListElement_t *prev_Node = NULL;
SortedListElement_t *curr_Node = list;
SortedListElement_t *next_Node = curr_Node->next;
int count = 0;
while(curr_Node->next != NULL) {
if(next_Node->prev != curr_Node) return -1;
// we will be in the beginnig of the string
if(prev_Node != NULL){
if(prev_Node->next != curr_Node) return -1;
}
count++;
if(opt_yield & LOOKUP_YIELD)
pthread_yield();
// update the pointers in the fashion that you always
// traverse the list in incremental fashion one step
// at a time.
curr_Node = curr_Node->next;
prev_Node = curr_Node->prev;
next_Node = curr_Node->next;
}
return count;
}
|
C | #include <stdio.h>
#include "holberton.h"
/**
* print_rev - Prints a string in reverse
* @s: The string to be reversed
*/
void print_rev(char *s)
{
while (*s != '\0')
s++;
s--;
while (*s)
{
_putchar(*s);
s--;
}
_putchar('\n');
}
|
C | #include "elf32.h"
#include "color.h"
#include "stdlib.h"
void read_Elf32_Ehdr(FILE *fp) {
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
printf("\n");
printf(GRAY" 展示 ELF32文件内容 之 ELF头(Ehdr) 结构\n");
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
Elf32_Ehdr ehdr;
fseek(fp, 0, 0);
fread(&ehdr, sizeof(ehdr), 1, fp);
printf("\n\n");
// e_ident
printf(L_BLACK"// elf32.e_ident"NONE);
printf("\n"L_RED"[16字节] "NONE""GRAY"elf32.e_ident"NONE);
printf("\n "L_BLACK"// 表示 'DEL' 'E' 'L' 'F' 的ANSI 值"NONE);
printf("\n "L_BLUE"[00-03]: 0x%02x 0x%02x 0x%02x 0x%02x" NONE, ehdr.e_ident[0], ehdr.e_ident[1],
ehdr.e_ident[2], ehdr.e_ident[3]);
printf("\n "L_BLACK"// 04: 指示ELF文件类型, 0 表示无效文件类型, 1 表示elf32文件类型, 2 表示elf64文件类型"NONE);
printf("\n "L_BLACK"// 05: 指示字节序, 0 表示无效格式, 1 表示小端序, 2 表示大端序"NONE);
printf("\n "L_BLACK"// 06: 指示ELF主版本, ELF自1.2之后未更新,没有太大意义"NONE);
printf("\n "L_BLUE"[04-06]: 0x%02x 0x%02x 0x%02x" NONE, ehdr.e_ident[4], ehdr.e_ident[5],
ehdr.e_ident[6]);
printf("\n "L_BLACK"// 后面9个字节ELF标准没有定义,一般是0,有些系统会使用后面9位作为扩展标志"NONE);
printf("\n "L_BLUE"[07-15]: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x" NONE,
ehdr.e_ident[7], ehdr.e_ident[8], ehdr.e_ident[9], ehdr.e_ident[10],
ehdr.e_ident[11], ehdr.e_ident[12], ehdr.e_ident[13], ehdr.e_ident[14],
ehdr.e_ident[15]);
printf("\n\n");
// e_type
printf(L_BLACK"// elf32.e_type 可使用的常量以 'ET' 开头,如下所示\n"NONE);
printf(L_BLACK"\
#define ET_NONE 0 /* No file type */ \n\
#define ET_REL 1 /* Relocatable file */\n\
#define ET_EXEC 2 /* Executable file */\n\
#define ET_DYN 3 /* Shared object file */\n\
#define ET_CORE 4 /* Core file */\n\
#define ET_NUM 5 /* Number of defined types */\n\
#define ET_LOOS 0xfe00 /* OS-specific range start */\n\
#define ET_HIOS 0xfeff /* OS-specific range end */\n\
#define ET_LOPROC 0xff00 /* Processor-specific range start */\n\
#define ET_HIPROC 0xffff /* Processor-specific range end */\
"NONE);
printf(L_BLACK"\n// ELF 包括:可执行文件、可重定位文件、动态库、coredump\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_type"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_type);
printf("\n\n");
// e_machine
printf(L_BLACK"// elf32.e_machine 可使用的常量以 'EM'\n"NONE);
printf(L_BLACK"// 常用的 EM_386=3, EM_X86_64=62\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_machine"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_machine);
printf("\n\n");
printf(L_BLACK"// elf32.e_version ELF 版本号,在 e_ident 中也有存在 'EM'\n"NONE);
printf(L_RED"[4字节] "NONE""GRAY"elf32.e_version"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_version);
printf("\n\n");
printf(L_BLACK"// elf32.e_entry 程序入口的偏移地址\n"NONE);
printf(L_RED"[4字节] "NONE""GRAY"elf32.e_entry"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_entry);
printf("\n\n");
printf(L_BLACK"// elf32.e_phoff program header 的入口\n"NONE);
printf(L_RED"[4字节] "NONE""GRAY"elf32.e_phoff"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_phoff);
printf("\n\n");
printf(L_BLACK"// elf32.e_shoff program header 的入口\n"NONE);
printf(L_RED"[4字节] "NONE""GRAY"elf32.e_shoff"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_shoff);
printf("\n\n");
printf(L_BLACK"// elf32.e_flags 处理相关的标志 的入口\n"NONE);
printf(L_RED"[4字节] "NONE""GRAY"elf32.e_flags"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_flags);
printf("\n\n");
printf(L_BLACK"// elf32.e_flags 处理相关的标志 的入口\n"NONE);
printf(L_RED"[4字节] "NONE""GRAY"elf32.e_flags"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_flags);
printf("\n\n");
printf(L_BLACK"// ehdr 的大小(字节单位)\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_ehsize"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_ehsize);
printf("\n\n");
printf(L_BLACK"// program header 的每个条目大小(字节单位)\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_phentsize"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_phentsize);
printf("\n\n");
printf(L_BLACK"// program header 的条目数量(字节单位)\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_phnum"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_phnum);
printf("\n\n");
printf(L_BLACK"// section header 的每个条目大小(字节单位)\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_shentsize"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_shentsize);
printf("\n\n");
printf(L_BLACK"// section header 的条目数量(字节单位)\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_shnum"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_shnum);
printf("\n\n");
printf(L_BLACK"// 段表字符串表(shstrtab)段在段(section)表中的下标, readelf -h xx 中第一列\n"NONE);
printf(L_RED"[2字节] "NONE""GRAY"elf32.e_shstrndx"NONE);
printf("\n "L_BLUE"0x%04x" NONE, ehdr.e_shstrndx);
printf("\n\n");
}
void read_Elf32_Shdr(FILE *fp) {
Elf32_Ehdr ehdr;
fseek(fp, 0, 0);
fread(&ehdr, sizeof(ehdr), 1, fp);
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
printf("\n");
printf(GRAY" 展示 ELF32文件内容 之 Section Header(Shdr) 结构\n");
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
Elf32_Shdr* shdr; // 存储 section header
shdr = malloc(ehdr.e_shnum * sizeof(Elf32_Shdr));
if (fseek(fp, ehdr.e_shoff, SEEK_SET) == 0) {
fread(shdr, sizeof(Elf32_Shdr), ehdr.e_shnum, fp);
}
Elf32_Shdr shstrtab; // 段表字符串表内容
char* shstrtab_content;
shstrtab = shdr[ehdr.e_shstrndx];
shstrtab_content = malloc(shstrtab.sh_size);
if (fseek(fp, shstrtab.sh_offset, SEEK_SET) == 0) {
fread(shstrtab_content, 1, shstrtab.sh_size, fp);
// for (int i = 0; i < shstrtab.sh_size; i++) {
// printf("%c", shstrtab_content[i]);
// }
}
printf("%-4s\t%-10s\t%-20s\t%-10s\t%-8s\n", "[NO]", "sh_addr", "sh_name", "sh_size", "sh_type");
for (int i = 0; i < ehdr.e_shnum; i++) {
printf("[%2d]\t0x%08x\t%-20s\t0x%-08x\t%x\n", i, shdr[i].sh_addr,
shstrtab_content + shdr[i].sh_name, shdr[i].sh_size, shdr[i].sh_type);
}
free(shstrtab_content);
free(shdr);
}
void read_Elf32_rel(FILE *fp) {
Elf32_Ehdr ehdr;
fseek(fp, 0, 0);
fread(&ehdr, sizeof(ehdr), 1, fp);
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
printf("\n");
printf(GRAY" 展示 ELF32文件内容 之 重定位表 结构\n");
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
Elf32_Shdr* shdr; // 存储 section header
shdr = malloc(ehdr.e_shnum * sizeof(Elf32_Shdr));
if (fseek(fp, ehdr.e_shoff, SEEK_SET) == 0) {
fread(shdr, sizeof(Elf32_Shdr), ehdr.e_shnum, fp);
}
Elf32_Shdr shstrtab; // 段表字符串表内容
char* shstrtab_content;
shstrtab = shdr[ehdr.e_shstrndx];
shstrtab_content = malloc(shstrtab.sh_size);
if (fseek(fp, shstrtab.sh_offset, SEEK_SET) == 0) {
fread(shstrtab_content, 1, shstrtab.sh_size, fp);
// for (int i = 0; i < shstrtab.sh_size; i++) {
// printf("%c", shstrtab_content[i]);
// }
}
printf("%-4s\t%-10s\t%-20s\t%-10s\t%-8s\n", "[NO]", "sh_addr", "sh_name", "sh_size", "sh_type");
for (int i = 0; i < ehdr.e_shnum; i++) {
printf("[%2d]\t0x%08x\t%-20s\t0x%-08x\t%x\n", i, shdr[i].sh_addr,
shstrtab_content + shdr[i].sh_name, shdr[i].sh_size, shdr[i].sh_type);
}
free(shstrtab_content);
free(shdr);
}
void read_Elf32_str(FILE *fp) {
Elf32_Ehdr ehdr;
fseek(fp, 0, 0);
fread(&ehdr, sizeof(ehdr), 1, fp);
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
printf("\n");
printf(GRAY" 展示 ELF32文件内容 之 字符串表 结构\n");
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
Elf32_Shdr* shdr; // 存储 section header
shdr = malloc(ehdr.e_shnum * sizeof(Elf32_Shdr));
if (fseek(fp, ehdr.e_shoff, SEEK_SET) == 0) {
fread(shdr, sizeof(Elf32_Shdr), ehdr.e_shnum, fp);
}
// 查找类型为符号表的段
for (int i = 0; i < ehdr.e_shnum; i++) {
if (shdr[i].sh_type == SHT_STRTAB) {
printf("\n");
Elf32_Shdr strtab; // 段表字符串表内容
char* strtab_content;
strtab = shdr[i];
strtab_content = malloc(strtab.sh_size);
if (fseek(fp, strtab.sh_offset, SEEK_SET) == 0) {
fread(strtab_content, 1, strtab.sh_size, fp);
for (int i = 0; i < strtab.sh_size; i++) {
printf("%c", strtab_content[i]);
}
}
free(strtab_content);
printf("\n");
}
}
free(shdr);
}
void read_Elf32_sym(FILE *fp) {
Elf32_Ehdr ehdr;
fseek(fp, 0, 0);
fread(&ehdr, sizeof(ehdr), 1, fp);
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
printf("\n");
printf(GRAY" 展示 ELF32文件内容 之 符号表 结构\n");
printf("\n");
printf(GRAY"##############################################################################################\n"NONE);
Elf32_Shdr* shdr; // 存储 section header
shdr = malloc(ehdr.e_shnum * sizeof(Elf32_Shdr));
if (fseek(fp, ehdr.e_shoff, SEEK_SET) == 0) {
fread(shdr, sizeof(Elf32_Shdr), ehdr.e_shnum, fp);
}
// 找到 strtab
Elf32_Shdr strtab = shdr[ehdr.e_shstrndx - 1];
char* strtab_content;
strtab_content = malloc(strtab.sh_size);
if (fseek(fp, strtab.sh_offset, SEEK_SET) == 0) {
fread(strtab_content, 1, strtab.sh_size, fp);
// for (int i = 0; i < strtab.sh_size; i++) {
// printf("%c", strtab_content[i]);
// }
// 查找类型为符号表的段
for (int i = 0; i < ehdr.e_shnum; i++) {
if (shdr[i].sh_type == SHT_SYMTAB) {
printf("\n");
Elf32_Shdr symtab; // 段表字符串表内容
Elf32_Sym* syms;
uint32_t count;
symtab = shdr[i];
count = symtab.sh_size / symtab.sh_entsize; // 得到条目数量
syms = malloc(count*sizeof(Elf32_Sym));
printf("%-4s\t%-10s\t%-20s\n", "[NO]", "sh_addr", "sh_name");
if (fseek(fp, symtab.sh_offset, SEEK_SET) == 0) {
fread(syms, 1, symtab.sh_size, fp);
for (int i = 0; i < count; i++) {
printf("[%2d]\t0x%08x\t%-10s\n", i, syms[i].st_value, strtab_content + syms[i].st_name);
// if (syms[i].st_name!=0) {
// printf("%s\n", strtab_content + syms[i].st_name);
// }
}
}
free(syms);
printf("\n");
}
}
}
free(shdr);
}
|
C | /*
* William Beasley, Chris Ragan, William Boatman, Mike Dozier, Jeff Grabowski
* Client.c
* UDP Client
*
*/
#include "Common.h"
#define RECBUFSIZE 65535
int commands[22] = {1, 2, 3, 4, 6, 4, 1, 2, 5, 4, 1,
2, 6, 4, 1, 2, 3, 4, 6, 4, 1, 2};
int sleepTimes[6] = {5, 1, 1, 1, 5, 1};
/* Args: ./client <UDP Hostname> <UDP Port> */
int main(int argc, char **argv){
int sock, port;
char *Servername;
void *buffer = malloc(sizeof(robot_cmd));
void *recvbuffer = malloc(RECBUFSIZE);
struct sockaddr_in serveraddr;
struct sockaddr_in returnaddr;
unsigned int returnsize;
robot_cmd *command = buffer;
if(argc != 3){
perror("Error: Client Syntax: ./Client <UDP Hostname> <UDP Port>\n");
exit(0);
}
port = atoi(argv[2]);
Servername = argv[1];
if((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
perror("Error creating socket, please panic.\n");
exit(1);
}
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(Servername);
serveraddr.sin_port = htons(port);
//int validcommand = 0;
int cmdcode;
int cmdvalue = 0;
int j = 0;
for(int i = 0; i < 22; ++i){
cmdcode = commands[i];
if(cmdcode == 4){
sleep(sleepTimes[j]);
j++;
continue;
}
command->command = cmdcode;
command->value = cmdvalue;
sendto(sock, buffer, sizeof(command), 0,
(struct sockaddr *) &serveraddr, sizeof(serveraddr));
//printf("Sent %d bytes\n",i);
returnsize = sizeof(returnaddr);
recvfrom(sock, recvbuffer, RECBUFSIZE, 0, NULL, NULL);
if(cmdcode < 3) //cmd is gps or dgps
{
printf("%s\n",(char*)recvbuffer);
}
}
return 0;
}
|
C | /*
һջ֪ԪصĽջУжһջԪɵǷǿܵijջС
磬ջΪ1 2 3 4ܵijջ4 3 2 11 4 3 2ȡ1 4 2 3Ͳǡ
ʽ
ӱȡ롣
һһN3N10NԪأջ1 2 3 N
ڶԿոָ1~NֵһС
ʽ
ӡ
ǿܵijջУӡYESӡNOĩҪһس
4
1 4 3 2
YES
ʱޡ
1
*/
#include<stdio.h>
enum {MAX = 10};
main()
{
int standard[MAX] = {0}, array[MAX] = {0}, i, j = 0, n;
int stack[MAX] = {0}, top = -1;
scanf("%d", &n);
for(i = 0;i < n;i++){
standard[i] = i + 1;
scanf("%d", &array[i]);
}
i = 0;
while(i < n && j < n){
if(array[j] != standard[i]){
stack[++top] = standard[i];
i++;
}
else{
i++;j++;
}
}
while(j < n && top >= 0 && stack[top] == array[j]){
j++;top--;
}
if(top == -1)
printf("YES\n");
else
printf("NO\n");
}
|
C | //
// lab-4.server.c
// CIS 075B
//
// Created by John Towler on 5/31/11.
// Copyright 2011. All rights reserved.
//
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <setjmp.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "mysignal.h"
#define PASSIVE_MAX 1
#define FIRST_PORT 3071
sigjmp_buf env;
int main(){
int passive[PASSIVE_MAX], curport = FIRST_PORT, i;
fd_set rds, savefds;
void reaper(int signum);
int set_up_passive_socket(short port);
void callexec(int *passive, fd_set ready);
FD_ZERO(&savefds);
for(i = 0; i < PASSIVE_MAX; i++, curport++){
passive[i] = set_up_passive_socket((short) curport);
FD_SET(passive[i], &savefds);
}
handleSignal(SIGCHLD, reaper);
while(1){
sigsetjmp(env, 1);
FD_COPY(&savefds, &rds);
select(FD_SETSIZE, &rds, NULL, NULL, NULL);
callexec(passive, rds);
}
}
int makeNonBlocking(int socket){
long flags;
if ((flags = fcntl(socket, F_GETFL, 0)) < 0)
exit(1);
if (fcntl(socket, F_SETFL, flags | O_NONBLOCK) < 0)
exit(1);
return socket;
}
int set_up_passive_socket(short port){
struct sockaddr_in sin;
int passive, makeNonBlocking(int passive);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
passive = Socket(AF_INET,SOCK_STREAM,0);
Bind(passive, (struct sockaddr *) &sin, sizeof(sin));
Listen(passive, 5);
passive = makeNonBlocking(passive);
return passive;
}
void reaper(int signum){
int status;
while(waitpid(-1, &status, WNOHANG) > 0);
siglongjmp(env, 1);
}
void callexec(int *passive, fd_set ready){
int active, sock;
pid_t pid;
char active_sock[10];
for(int i = 0; i < PASSIVE_MAX; i++){
if(FD_ISSET(passive[i], &ready)){
sock = passive[i];
active = accept(passive[i], NULL, NULL);
pid = Fork();
if(pid > 0){ // Parent
close(active);
continue;
}
else{ // Child
for(int j = 0; j < PASSIVE_MAX; j++)
close(passive[j]);
if (sock == passive[0])
sprintf(active_sock, "%d", active);
execl("./who2", "who2", active_sock, NULL);
exit(0);
}
}
}
} |
C | //heap sort try#2
#include<stdio.h>
int heap[100];
void heapify(int n,int i)
{
int temp;
int root=i;
int lchild=2*i+1;
int rchild=2*i+2;
if(lchild<n&&heap[lchild]>heap[root])
root=lchild;
if(rchild<n&&heap[rchild]>heap[root])
root=rchild;
if(root!=i)
{
temp=heap[i];
heap[i]=heap[root];
heap[root]=temp;
heapify(n,root);
}
}
void heapSort(int n)
{
int i;
int temp;
for(i=(n/2)-1;i>=0;i--)
heapify(n,i);
for(i=n-1;i>=0;i--)
{
temp=heap[0];
heap[0]=heap[i];
heap[i]=temp;
heapify(i,0);
}
}
void Display(int n)
{
int i;
printf("The Sorted array:");
for(i=0;i<n;i++)
printf("%d\t",heap[i]);
printf("\n");
}
void main()
{
int i;
int n;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter the elements:");
for(i=0;i<n;i++)
scanf("%d",&heap[i]);
printf("The original array:");
for(i=0;i<n;i++)
printf("%d\t",heap[i]);
printf("\n");
heapSort(n);
Display(n);
} |
C | #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
void *thread1(void *arg)
{
while (1) {
}
}
void *thread2(void *arg)
{
while (1) {
}
}
int main()
{
pthread_t pid1, pid2;
pthread_create(&pid1, NULL, thread1, NULL);
pthread_create(&pid2, NULL, thread2, NULL);
while (1) {
}
return 0;
}
|
C | /*****************************************************************************
*Author Calvin Zhuoqun Huang
*Licence MIT Licence
*File Name poly_bbst.c
*Space for Tab YES
*Tab size 4
*Time Created 30 April 2018 (Monday)
*Last Edited 30 April 2018 (Monday)
*Brief:
Polymophical Balance binary search tree
*It's not supposed to be shared without permission of author.
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include "../Node/node.h"
#include "poly_bbst.h"
/* <MacroDefs> */
#define TRUE 1
#define FALSE 0
#define INVALID -1
#define POS 0
#define NITEM 1
#define NCHILD 2
#define LEFT 0
#define RIGHT 1
#define CHILDNULL -1
#define MAXITER 1000
#define CLEAF 0
#define CLEFT 1
#define CRIGHT 2
#define CLEFTRIGHT 3
#define CRIGHTLEFT 4
/* </MacroDefs> */
/* <TypeDefs> */
struct tree_s {
size_t skey,
sdata;
int nele;
Node *root;
int (*cmp)(void*, void*);
};
/* </TypeDefs> */
/* <FunctionPrototypes> */
static Node *new_tree_node(Tree *tree);
static Node *rotate_nodes(Node *node, int dir);
static int get_nchild(Node *node);
static int get_diff(Node *node);
static int std_diff(int n, int thresh);
static Node *retrieve_node(Tree *t, void *key)
static void recursive_retrieve_node(Node *node, Node *ary[], int *ind);
/*
* Replace the keys and values of node a with node b's
* but not childs
*/
static void replace_node(Node *a, Node *b);
/*
* Helper function for returning the case integer in deleting nodes
*/
static int check_case(Node *node)
/* </FunctionPrototypes> */
Tree *new_tree(size_t skey, size_t sdata, int (*cmp)(void*, void*)) {
Tree *t = (Tree*)malloc(sizeof*t);
assert(t != NULL);
t->skey = skey;
t->sdata = sdata;
t->nele = 0;
t->root = NULL;
t->cmp = cmp;
return t;
}
void free_tree(Tree *t) {
assert(t != NULL);
recursive_free_node(t->root);
free(t);
}
static void recursive_free_node(Node *node) {
if (node == NULL) return;
recursive_free_node(cc(node, LEFT));
recursive_free_node(cc(node, RIGHT));
free_node(node);
}
void tree_insert(Tree *t, void *key, void *data) {
assert(t != NULL);
/* update number of element in the tree */
t->nele++;
int log_nele = 0,
nele = t->nele;
while (nele >>= 1) ++log_nele;
log_nele += 2;
int dirs[log_nele],
dir = INVALID,
blce = INVALID,
diff = 0,
prev_dir = 0,
head = 0,
nchild = CHILDNULL;
bool found = FALSE;
Node *stack[log_nele],
*node = new_tree_node(t),
*parent = NULL,
*tmp = t->root;
/* Prepare the new node */
ai(node, key, data, POS);
aw(node, CHILDNULL + 1);
/* Add the root to heap */
if (t->root != NULL) {
tmp = t->root;
} else {
t->root = node;
return;
}
/* Iterative insert to correct position */
while (tmp != NULL && found == FALSE) {
dir = t->cmp(ck(node, POS), ck(tmp, POS)) > 0 ? RIGHT : LEFT;
stack[head] = tmp;
dirs[head] = dir;
head++;
parent = tmp;
tmp = cc(tmp, dir);
}
tmp = node;
ac(parent, node, dir);
/* now update the height of the tree and balance the tree */
while (head) {
ac(stack[head - 1], tmp, dirs[head - 1]);
tmp = stack[head - 1];
diff = get_diff(tmp);
blce = std_diff(diff, 1);
if (blce != INVALID) {
if (prev_dir != blce) {
ac(tmp, rotate_nodes(cc(tmp, blce), prev_dir), blce);
}
tmp = rotate_nodes(tmp, blce);
}
if ((nchild = get_nchild(tmp)) == cw(tmp)) {
// The child is not updated, So we can break here
break;
}
aw(tmp, nchild);
prev_dir = std_diff(diff, 0);
head--;
}
t->root = tmp;
}
/* Still not finished */
void *delete_key(Tree *t, void *key) {
assert(t != NULL);
int log_nele = 0,
nele = t->nele;
while (nele >>= 1) ++log_nele;
log_nele += 2;
int dirs[log_nele],
dir = INVALID,
blce = INVALID,
diff = 0,
prev_dir = 0,
head = 0,
nchild = CHILDNULL;
bool found = FALSE;
Node *stack[log_nele],
*parent = NULL,
*tmp = t->root;
void *data = NULL;
/* Iterative find position of the element with such key */
while (tmp != NULL) {
if ((dir = t->cmp(ck(node, POS), ck(tmp, POS))) > 0) {
dir = RIGHT;
} else if (dir < 0) {
dir = LEFT;
} else {
// found the element
break;
}
// record the path
stack[head] = tmp;
dirs[head] = dir;
head++;
parent = tmp;
tmp = cc(tmp, dir);
}
// Cant find such key
if (tmp == NULL) return NULL;
/* now starts the cycle of replace and delete */
while (TRUE) {
stack[head] = tmp;
// These in the case
// dirs[head] = dir;
// head++;
switch(check_case(tmp)) {
case CLEAF:
if (t->nele == 1) {
t->root = NULL;
return cd(tmp, POS);
// free_node(tmp); since the data is stored in node
}
break; /* optional */
case CLEFT:
/* statement(s) */
break; /* optional */
case CRIGHT:
/* statement(s) */
break; /* optional */
case CLEFTRIGHT:
/* statement(s) */
break; /* optional */
case CRIGHTLEFT:
/* statement(s) */
break; /* optional */
default:
printf("ERROR! case goes to bottom\n");
/* statement(s) */
}
}
/* now update the height of the tree and balance the tree */
while (head) {
ac(stack[head - 1], tmp, dirs[head - 1]);
tmp = stack[head - 1];
diff = get_diff(tmp);
blce = std_diff(diff, 1);
if (blce != INVALID) {
if (prev_dir != blce) {
ac(tmp, rotate_nodes(cc(tmp, blce), prev_dir), blce);
}
tmp = rotate_nodes(tmp, blce);
}
if ((nchild = get_nchild(tmp)) == cw(tmp)) {
// The child is not updated, So we can break here
break;
}
aw(tmp, nchild);
prev_dir = std_diff(diff, 0);
head--;
}
t->root = tmp;
}
void *retrieve_data(Tree *t, void *key) {
assert(t != NULL);
assert(key != NULL);
return cd(retrieve_node(t, key), POS);
}
int retrieve_tree(Tree *t, void *key, void *data) {
static int head;
static Node *stack[MAXITER];
static Node *tmp = NULL;
if (key == NULL || data == NULL) {
head = 0;
if (t->root != NULL) {
recursive_retrieve_node(t->root, stack, &head);
}
return TRUE;
}
if (head != 0) {
tmp = stack[head - 1];
head--;
memcpy((char*)key, ck(tmp, POS), t->skey);
memcpy((char*)data, cd(tmp, POS), t->sdata);
return TRUE;
}
return INVALID;
}
int tree_nele(Tree *t) {
assert(t!= NULL);
return t->nele;
}
/* =========================Static functions======================== */
static void recursive_retrieve_node(Node *node, Node *ary[], int *ind) {
if (node == NULL) {
return;
}
recursive_retrieve_node(cc(node, RIGHT), ary, ind);
ary[*ind] = node;
(*ind)++;
recursive_retrieve_node(cc(node, LEFT), ary, ind);
}
static Node *retrieve_node(Tree *t, void *key) {
Node *node = t->root;
void *node_key = NULL;
while (node != NULL) {
node_key = ck(node, POS);
if (t->cmp(key, node_key) > 0) {
node = cc(node, RIGHT);
} else if (t->cmp(key, node_key) == 0) {
return node;
} else {
node = cc(node, LEFT);
}
}
return NULL;
}
static Node *new_tree_node(Tree *t) {
Node *node = new_node(NITEM, t->skey, t->sdata, NCHILD);
assert(node != NULL);
return node;
}
static Node *rotate_nodes(Node *node, int dir) {
assert(node != NULL);
Node *child = cc(node, dir);
assert(child != NULL);
ac(node, cc(child, !dir), dir);
ac(child, node, !dir);
/* Update the previous parent first, since it's now a child (The new
parent's data is dependent on this) */
aw(node, get_nchild(node));
/* Then update the previous child now parent */
aw(child, get_nchild(child));
return child;
}
static int get_nchild(Node *node) {
Node *leftc = cc(node, LEFT),
*rightc = cc(node, RIGHT);
int num_leftc = leftc != NULL ? cw(leftc) : CHILDNULL,
num_rightc = rightc != NULL ? cw(rightc) : CHILDNULL;
return (num_leftc > num_rightc ? num_leftc : num_rightc) + 1;
}
static int get_diff(Node *node) {
Node *leftc = cc(node, LEFT),
*rightc = cc(node, RIGHT);
int num_leftc = leftc != NULL ? cw(leftc) : CHILDNULL,
num_rightc = rightc != NULL ? cw(rightc) : CHILDNULL;
return num_leftc - num_rightc;
}
static int std_diff(int n, int thresh) {
if (n > thresh) return LEFT;
else if (n < -thresh) return RIGHT;
else return INVALID;
}
static void replace_node(Node *a, Node *b) {
ak(a, ck(b, POS), POS);
ad(a, cd(b, POS), POS);
}
static int check_case(Node *node) {
Node *left = cc(node, LEFT),
*right = cc(node, RIGHT),
*lright = NULL,
*rleft = NULL;
int nleft = CHILDNULL,
nright = CHILDNULL,
diff = get_diff(node);
if (left == NULL && right == NULL) {
return CLEAF;
} else if (left == NULL) {
return CRIGHT;
} else if (RIGHT == NULL) {
return CLEFT;
} else {
lright = cc(left, RIGHT);
rleft = cc(right, LEFT);
if (lright != NULL) {
return CLEFTRIGHT;
} else if (rleft != NULL) {
return CRIGHTLEFT
} else {
return CLEFT;
}
}
}
void test_tree(Tree *t) {
int start = 0, end = 0, num = t->nele+1;
Node *queue[num],
*tmp = NULL;
if (t->root != NULL) {
queue[end] = t->root;
end = (end + 1)%(num + 1);
}
while (start != end) {
tmp = queue[start];
start = (start + 1)%num;
if (cc(tmp, LEFT) != NULL) {
queue[end] = cc(tmp, LEFT);
end = (end + 1)%num;
}
if (cc(tmp, RIGHT) != NULL) {
queue[end] = cc(tmp, RIGHT);
end = (end + 1)%num;
}
printf("------------------------------------------------\n");
printf("Node: address %p key= %d, weight= %d\n",tmp,
*(int*)ck(tmp, POS), cw(tmp));
printf(" Left child %p, Right child %p\n", cc(tmp, LEFT),
cc(tmp, RIGHT));
}
} |
C | /*
author :: Durwasa Chakraborty
programming language :: C
programming organization :: Codechef
*/
#include <stdio.h>
#include <stdlib.h>
#define gc getchar_unlocked
long long int get_i() {
char c = gc();
while(c<'0' || c>'9') c = gc();
long long int ret = 0;
while(c>='0' && c<='9') {
ret = 10 * ret + c - 48;
c = gc();
}
return ret;
}
int main( int argc, char const *argv[])
{
long long int t=get_i();
while(t--)
{
long long int i=0;
long long int n = get_i();
long long int a[n];
long long int sum=0;
long long int current_memory=0;
for(i=0;i<n;i++)
{
a[i]=get_i();
if(a[i]>current_memory)
{
sum+=a[i]-current_memory;
current_memory=a[i];
}
else
current_memory=a[i];
}
printf("%lld\n",sum );
}
return 0;
} |
C | // A. Compile fib objects
// cc -Wall -g -c -o fib1.o fib1.c
// cc -Wall -g -c -o fib2.o fib2.c
// B. Compile and link main
// cc -Wall -g main.c fib1.o -o main # OK
// cc -Wall -g main.c fib2.o -o main # OK
// cc -Wall -g main.c fib1.o fib2.o -o main # This will barf
#include <stdio.h>
int fib(int n); // Linker will find definition of this function.
// But.... if there are multiple definitions (i.e. B line 3), linker will barf
int main(int argc, char *argv[])
{
int n = 5;
int res = fib(n);
printf("res(%d): %d\n", n, res);
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include "ppmio.h"
#include "blurfilter-pthreads.h"
#include "gaussw.h"
#include "image_utils.h"
#define MAX_RAD 1000
#define ROOT 0
/* Mutex object to use for critical section locks */
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
/* Thread data struct */
typedef struct thread_data_struct
{
uint thread_id; /* Thread-ID allocated */
int x_start; /* Where at X coordinate to start */
int y_start; /* Where at Y coordinate to start */
int x_end; /* Where at X coordinate to end */
int y_end; /* Where at Y coordinate to end */
int x_size; /* How many horizontal pixels */
int radius; /* The radius to use */
double * w; /* The gaussian weight array */
pixel * data_to_process;/* Pointer containing the starting address of
the image */
} tdata_t;
/* Threads call this starting routine to process rows */
void * blurf_x_wrapper(void * data)
{
tdata_t * thread_data = (tdata_t *) data;
uint id = thread_data->thread_id;
int xstart = thread_data->x_start;
int ystart = thread_data->y_start;
int xend = thread_data->x_end;
int yend = thread_data->y_end;
int xsize = thread_data->x_size;
int radius = thread_data->radius;
double * weights = thread_data->w;
pixel * image = thread_data->data_to_process;
pthread_mutex_lock(&mutex);
printf("[T%u] hz (xs=%d,ys=%d,xe=%d,ye=%d)\n", id,
xstart,ystart,xend,yend);
pthread_mutex_unlock(&mutex);
// Call the filter in the horizontal direction
blurfilter_x(xstart, ystart,
xend, yend,
xsize,
image, radius, weights);
pthread_exit(NULL);
return NULL;
}
/* Threads call this starting routine to process columns */
void * blurf_y_wrapper(void * data)
{
tdata_t * thread_data = (tdata_t *) data;
uint id = thread_data->thread_id;
int xstart = thread_data->x_start;
int ystart = thread_data->y_start;
int xend = thread_data->x_end;
int yend = thread_data->y_end;
int xsize = thread_data->x_size;
int radius = thread_data->radius;
double * weights = thread_data->w;
pixel * image = thread_data->data_to_process;
pthread_mutex_lock(&mutex);
printf("[T%u] vt (xs=%d,ys=%d,xe=%d,ye=%d])\n", id,
xstart,ystart,xend,yend);
pthread_mutex_unlock(&mutex);
// Call the filter in the horizontal direction
blurfilter_y(xstart, ystart, xend, yend, xsize, image, radius, weights);
pthread_exit(NULL);
return NULL;
}
int main (int argc, char ** argv) {
int radius;
int xsize, ysize, colmax;
pixel * src = (pixel *) malloc (sizeof*src * MAX_PIXELS);
double w[MAX_RAD];
uint nr_threads;
struct timespec stime, etime;
/* Take care of the arguments */
if (argc != 5)
{
fprintf(stderr, "Usage: %s radius infile outfile nr_threads\n", argv[0]);
exit(1);
}
nr_threads = atoi(argv[4]);
radius = atoi(argv[1]);
if (radius > MAX_RAD || radius < 1)
{
fprintf(stderr, "Radius (%d) must be greater than zero and less then %d\n", radius, MAX_RAD);
exit(1);
}
int my_id;
int max_size;
/* read file */
if (read_ppm (argv[2], &xsize, &ysize, &colmax, (char *) src) != 0)
exit(1);
if (colmax > 255)
{
fprintf(stderr, "Too large maximum color-component value\n");
exit(1);
}
max_size = xsize * ysize;
printf("[ROOT] Has read the image, generating coefficients\n");
/* Gaussian weights */
get_gauss_weights(radius, w);
pthread_t threads[nr_threads];
/* Calculate how many rows/colums each thread needs to process */
/* The first part of the filter runs "horizontally", i.e.,
* the gaussian weights are applied to horizontally contiguous
* pixels. Hence, by taking `ysize` and dividing it by `nr_threads`
* we will obtain how many horizontal blocks each thread will take
* care of simultaneously. The same applies for the "vertical"
* filter, where each thread will process a group of columns specified
* by `nr_threads` and `size`*/
int hz_block_count = ysize / nr_threads;
int vt_block_count = xsize / nr_threads;
tdata_t t[nr_threads];
clock_gettime(CLOCK_REALTIME, &stime);
/* Now, create the threads to work on the horizontal filter */
for (my_id = 1; my_id <= nr_threads; ++my_id)
{
t[my_id-1].thread_id = my_id;
t[my_id-1].x_start = 0;
t[my_id-1].y_start = (my_id-1)*hz_block_count;
t[my_id-1].x_end = xsize;
t[my_id-1].y_end = my_id*hz_block_count; // We want divide the work horizontally
t[my_id-1].x_size = xsize;
t[my_id-1].radius = radius;
t[my_id-1].w = w;
t[my_id-1].data_to_process = src;
if (pthread_create(&threads[my_id-1], NULL, blurf_x_wrapper, (void *)&t[my_id-1]) != 0)
{
perror("Error creating thread.");
exit(1);
}
}
/* Next, wait for them to finish and return */
for (my_id = 1; my_id <= nr_threads; ++my_id)
{
if (pthread_join(threads[my_id-1], NULL) != 0)
{
perror("Error joining thread.");
exit(2);
}
}
printf("[T0] Applied horizontal filter, now applying vertical\n");
/* Finally, perform the same process for the "vertical" filter */
for (my_id = 1; my_id <= nr_threads; ++my_id)
{
t[my_id-1].thread_id = my_id;
t[my_id-1].x_start = (my_id-1)*vt_block_count;
t[my_id-1].y_start = 0;
t[my_id-1].x_end = my_id*vt_block_count;
t[my_id-1].y_end = ysize; // We want divide the work horizontally
t[my_id-1].x_size = xsize;
t[my_id-1].radius = radius;
t[my_id-1].w = w;
t[my_id-1].data_to_process = src;
if (pthread_create(&threads[my_id-1], NULL, blurf_y_wrapper, (void *)&t[my_id-1]) != 0)
{
perror("Error creating thread.");
exit(1);
}
}
/* Next, wait for them to finish and return */
for (my_id = 1; my_id <= nr_threads; ++my_id)
{
if (pthread_join(threads[my_id-1], NULL) != 0)
{
perror("Error joining thread.");
exit(2);
}
}
clock_gettime(CLOCK_REALTIME, &etime);
printf("Filtering took: %g secs\n", (etime.tv_sec - stime.tv_sec) +
1e-9*(etime.tv_nsec - stime.tv_nsec)) ;
/* write result */
printf("Writing output file\n");
if(write_ppm (argv[3], xsize, ysize, (char *)src) != 0)
exit(1);
free(src);
return 0;
}
|
C | #include "holberton.h"
/**
* rev_string(:)? (- rev string)?
*
* @s: input string
* Return: 0 or 1
*/
void rev_string(char *s)
{
char k;
int i = 0, j, l;
while (s[i] != '\0')
{
i++;
}
l = i - 1;
for (j = 0 ; j < (i / 2); j++)
{
k = s[l];
s[l] = s[j];
s[j] = k;
l--;
}
}
|
C | /* CSC 435
* Final - Diffusion openmp
*
* Author: GnuForce
*
*
*/
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<omp.h>
//declaration of the variables that define the system at the beginning
// and will be used throughout the program
double mTotal, currTime, urms, D, rSize, rDiv, tStep, hval, conMax, conMin, hsqrd;
//An int that will be used in a fashion similar to a boolean to
// control when the partition in activated
int partition;
//declaration of the step function that will perform a single iteration
// of the simulation
void step (double* room, double* roomCopy, int* mask, int N);
int main(){
int nTemp = 0;
char pValue;
printf("How many divisions do want for the room?\n");
scanf("%d",&nTemp);
printf("Do you want a partition to be used?(y/n)\n");
scanf(" %c",&pValue);
int N = nTemp;
double lRoom = 5;
if(pValue == 'y'){
partition = 1;
}else{
partition = 0;
}
//cal for time objects that will tell us wall time at end of program
time_t start;
time_t end;
//Give start the time of program starting execution
start = time(NULL);
//Initializing all of the necessary variables for the simulation to start
mTotal = 1000000000000000000000.0;
urms = 250.0;
hval = (double) lRoom/N;
D = 0.175;
conMax = mTotal;
conMin = 0.0;
tStep = (double) (lRoom/urms)/N;
hsqrd = (hval*hval);
//declaration of for loop counter variables
int i,j,k;
//This represents the total molecules left after running the simulation
// used to check if matter consistency is held
double tot = 0.0;
//A 3 dimensional array that will operate as a rank 3 tensor used
// to represent the room
double *room = calloc( 1, (N+2)*(N+2)*(N+2)*sizeof(double));
double *roomCopy = calloc( 1, (N+2)*(N+2)*(N+2)*sizeof(double));
int *mask = calloc( 1, (N+2)*(N+2)*(N+2)*sizeof(int));
//Following for loops will initialize the room tensor with 0 values
// when partioning is turned off, otherwise locations that
// represent the partion in the room will be initialized
// to the value -1
for (i=1; i<N+1; i++) {
for (j=1; j<N+1; j++){
for (k=1; k<N+1; k++){
if(k == ((N+2)/2) && i >= ((N+2)/2)-1 && partition){
mask[i*(2+N)*(2+N)+j*(2+N)+k] = 0;
}else{
mask[i*(2+N)*(2+N)+j*(2+N)+k] = 1;
}
}
}
}
for( i=0;i<N+2;i++){
// printf("\n");
for(j =0;j<N+2;j++){
// printf("\n");
for(k=0;k<N+2;k++){
// printf("%d ", mask[i*(2+N)*(2+N)+j*(2+N)+k]);
}
}
}
//Provides the room with the gas material to be dispersed
// to be understood as the "upper corner" of the room
room[1*(2+N)*(2+N)+1*(2+N)+1] = mTotal;
//We want the simulation to stop when the room has become sufficiently
// diffuse with the gas, thus we check if the ratio of lowest
// concentration to highest is less than 0.99, and when it is
// higher we know the gas has diffused
double* temp;
while((conMin/conMax) < 0.99){
currTime = currTime + tStep;
// step(room, roomCopy, mask, N);
//Every time we check to see the flux of gas between cells
// we would also need to multiply several values,
// slowing the speed of computation. By calculating the
// value once we only need to perform a single
// multiplication each time afterwards for each cell
// instead of several
double coefficient = ((tStep*D) / (hsqrd) );
omp_set_num_threads(1);
#pragma omp parallel shared(room,roomCopy,N) private(i,j,k)
{
#pragma omp for
for (i=1; i<N+1; i++){
for (j=1; j<N+1; j++){
for (k=1; k<N+1; k++){
roomCopy[i*(2+N)*(2+N)+j*(2+N)+k] = room[i*(2+N)*(2+N)+j*(2+N)+k] +
(room[i*(2+N)*(2+N)+j*(2+N)+k+1] * mask[i*(2+N)*(2+N)+j*(2+N)+k+1] + room[i*(2+N)*(2+N)+j*(2+N)+k-1] * mask[i*(2+N)*(2+N)+j*(2+N)+k-1] +
room[i*(2+N)*(2+N)+j*(2+N)+k+(2+N)] * mask[i*(2+N)*(2+N)+j*(2+N)+k+(2+N)] + room[i*(2+N)*(2+N)+j*(2+N)+k-(2+N)] * mask[i*(2+N)*(2+N)+j*(2+N)+k-(2+N)] +
room[i*(2+N)*(2+N)+j*(2+N)+k+((2+N)*(2+N))] * mask[i*(2+N)*(2+N)+j*(2+N)+k+((2+N)*(2+N))] + room[i*(2+N)*(2+N)+j*(2+N)+k-((2+N)*(2+N))] * mask[i*(2+N)*(2+N)+j*(2+N)+k-((2+N)*(2+N))] -
((mask[i*(2+N)*(2+N)+j*(2+N)+k+1] + mask[i*(2+N)*(2+N)+j*(2+N)+k-1] + mask[i*(2+N)*(2+N)+j*(2+N)+k+(2+N)] + mask[i*(2+N)*(2+N)+j*(2+N)+k-(2+N)] + mask[i*(2+N)*(2+N)+j*(2+N)+k+((2+N)*(2+N))] + mask[i*(2+N)*(2+N)+j*(2+N)+k-((2+N)*(2+N))])
* room[i*(2+N)*(2+N)+j*(2+N)+k])) * 2 * coefficient;
}
}
}
}
//after resetting the concentration values we then find the values of min and max
// in order to tell when the loop shall end
conMin = roomCopy[1*(2+N)*(2+N)+1*(2+N)+1];
conMax = roomCopy[1*(2+N)*(2+N)+1*(2+N)+1];
for (i=1; i<N+1; i++) {
for (j=1; j<N+1; j++){
for (k=1; k<N+1; k++){
if (roomCopy[i*(2+N)*(2+N)+j*(2+N)+k] < conMin) {
conMin = roomCopy[i*(2+N)*(2+N)+j*(2+N)+k];
}
if (roomCopy[i*(2+N)*(2+N)+j*(2+N)+k] > conMax) {
conMax = roomCopy[i*(2+N)*(2+N)+j*(2+N)+k];
}
}
}
}
temp = room;
room = roomCopy;
roomCopy = temp;
}
//Here we total the values stored in all of the cells to check
// for any signifcant amount of lost or gained matter
for (i=0; i<N+2; i++) {
for (j=0; j<N+2; j++){
for (k=0; k<N+2; k++){
tot = tot + room[i*(2+N)*(2+N)+j*(2+N)+k];
}
}
}
//output of the simulation detailing 5 vaules
// How many molecules did we start with
// How many molecules did we end with
// The total amount of time it took for the room to become diffused
// The minimum concentration in the room
// the maximum concentration in the room
end = time(NULL);
double seconds = difftime(end,start);
printf("Total molecules starting: %f\n", mTotal);
printf("Total molecules left: %f\n", tot);
printf("Time Simulated: %f\n", currTime);
printf("min concentration: %f\n", conMin);
printf("max concentration: %f\n", conMax);
printf("Wall time: %f\n", seconds);
//free the memory held by the array
free(room);
free(roomCopy);
free(mask);
}
|
C | # include <stdio.h>
char pole[9] = { '1','2','3','4','5','6','7','8','9' };
int b = 1;
int p;
int a;
void tab(b)
{
int i;
if (b != 2) {
for (i = 0; i <= 9; i++)
{
if (i == 2 || i == 5 || i == 9)
printf("%2c\n", pole[i]);
else
printf("%2c", pole[i]);
}
}
}
void czyX(p)
{
switch (p)
{
case 1:
pole[p - 1] = 'X';
tab();
break;
case 2:
pole[p - 1] = 'X';
tab();
break;
case 3:
pole[p - 1] = 'X';
tab();
break;
case 4:
pole[p - 1] = 'X';
tab();
break;
case 5:
pole[p - 1] = 'X';
tab();
break;
case 6:
pole[p - 1] = 'X';
tab();
break;
case 7:
pole[p - 1] = 'X';
tab();
break;
case 8:
pole[p - 1] = 'X';
tab();
break;
case 9:
pole[p - 1] = 'X';
tab();
break;
default:
break;
}
}
void czyO(p)
{
switch (p)
{
case 1:
pole[p - 1] = 'O';
tab();
break;
case 2:
pole[p - 1] = 'O';
tab();
break;
case 3:
pole[p - 1] = 'O';
tab();
break;
case 4:
pole[p - 1] = 'O';
tab();
break;
case 5:
pole[p - 1] = 'O';
tab();
break;
case 6:
pole[p - 1] = 'O';
tab();
break;
case 7:
pole[p - 1] = 'O';
tab();
break;
case 8:
pole[p - 1] = 'O';
tab();
break;
case 9:
pole[p - 1] = 'O';
tab();
break;
default:
break;
}
}
int koniec()
{
if ((pole[0] == pole[1] && pole[1] == pole[2]) || (pole[3] == pole[4] && pole[3] == pole[5]) || (pole[6] == pole[7] && pole[7] == pole[8]) || (pole[0] == pole[4] && pole[4] == pole[8]) || (pole[2] == pole[4] && pole[4] == pole[6]) || (pole[0] == pole[3] && pole[3] == pole[6]) || (pole[1] == pole[4] && pole[4] == pole[7]) || (pole[2] == pole[5] && pole[5] == pole[8]))
{
printf("Koniec gry.\n");
return 2;
}
}
void gra()
{
while (a <= 5 && b != 2) {
b = koniec();
printf("X:Podaj pole: ");
scanf_s("%d", &p);
system("cls");
czyX(p);
b = koniec();
if (b == 2)
break;
printf("O:Podaj pole: ");
scanf_s("%d", &p);
system("cls");
czyO(p);
a++;
}
b = 3;
}
int main(void) {
tab(b);
gra();
getchar();
getchar();
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
void Mensagem ( int x, char *Pomodoro [ ] ) {
printf ( "%s\n", Pomodoro [ x ] );
}
int main(){
int horas,minutos,tempoSOMADO,pomodori=0,intervalo=0,sobro,A,tempo,intervaloMaior=0,B;
char nomeT[500],pontos[1];
system(" title Tecnica Pomodoro ");
static char *Pomodoro [ ] = {
"\t|\t\t\tTecnica Pomodoro\t\t\t |",
"\t| A Tecnica Pomodoro e um metodo de gerenciamento de tempo\t |",
"\t| a tecnica consiste em dividir o trabalho em periodos de 25 minutos,|",
"\t| chamados de pomodori, a cada 1 pomodori(25 minutos)\t\t |",
"\t| voce faz uma pausa de 5 minutos,a cada 4 pomodoros depois |",
"\t| de 3 pausas, na quarta pausa vc descansa entre 15 e 30 minutos |",
"\tDigite o tempo de duracao dessa tarefa!!!\n",
"\tSeja mais produtivo e aumente a produtividade com a Tecnica Pomodoro. ",
"Obrigado por usar este programa !!!"};
printf("\t_____________________________________________________________________\n");
Mensagem(0,Pomodoro);
printf("\t|\t\t\t\t\t\t\t\t |\n");
Mensagem(1,Pomodoro);
Mensagem(2,Pomodoro);
Mensagem(3,Pomodoro);
Mensagem(4,Pomodoro);
Mensagem(5,Pomodoro);
printf("\t_____________________________________________________________________");
printf("\t\t\n");
printf("\tDigite o nome da tarefa que voce ira fazer: ");
scanf("%[^\n]s", &nomeT);
setbuf(stdin, NULL);
printf("\n");
Mensagem(6,Pomodoro);
printf("\t -Primeiro Digite as horas :");
scanf("%d",&horas);
printf("\n");
printf("\t -Agora Digite os minutos :");
scanf("%d",&minutos);
tempo=horas*60;
tempo+=minutos;
while(tempo >= 25){
for(A=1;A<=25;A++){
tempo--;
}
pomodori+=1;
//printf("%d\n",pomodori);
for(A=0;A<=5;A++){
tempo--;
}
intervalo+=1;
//printf("%d\n",intervalo);
for(B=0;B<720;B++){
if(intervalo == 3*B){
tempo=tempo-30;
intervaloMaior+=1;
}
}
}
printf("\n");
printf("\tQuantidade de Pomodoris = %d\n",pomodori);
printf("\tquantidades de intervalos de 5 Minutos = %d\n",intervalo);
printf("\tquantidades de intervalos de 15 a 30 Minutos = %d\n",intervaloMaior);
printf("\n");
printf("\t_____________________________________________________________________\n");
printf("\n");
Mensagem(7,Pomodoro);
printf("\t_____________________________________________________________________\n");
printf("\n");
Mensagem(8,Pomodoro);
printf("\n");
system("pause");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.