language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
//
// zadanie4.h
// lista4
//
// Created by Jan Śnieg on 03/04/2018.
// Copyright © 2018 Jan Śnieg. All rights reserved.
//
#ifndef zadanie4_h
#define zadanie4_h
int partition (int n, double t[])
{
int k = -1;
// int ile = n;
double x = t[n / 2];
while (true)
{
while (t[--n] > x);
while (t[++k] < x);
if (n > k)
{
double y = t[k];
t[k] = t[n];
t[n] = y;
}
else
return k;
}
}
int kty(int n, double t[], int k)
{
int L = partition(n,t);
if (k<=L)
return kty(L,t,k);
else
return kty(n-L, t+L, k-L);
}
#endif /* zadanie4_h */
|
C
|
/* Sieve of eratosthenes */
#include <mpi.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//#include "MyMPI.h"
#define MIN(a,b) ((a)<(b)?(a):(b))
#define OFFSET 3
#define SEED_SIZE(n) (int)ceil((((double)sqrt(n))/2))
#define SEED_OFFSET(n) ((SEED_SIZE(n)*2) + OFFSET)
#define SEED_HIGH(n) (SEED_OFFSET(n)-2)
#define BLOCK_LOW(id,p,n) ((((id) * ((((n)-1)/2) - SEED_SIZE(n))/(p)) * 2) + SEED_OFFSET(n))
#define BLOCK_HIGH(id,p,n) (BLOCK_LOW(((id)+1),p,n)-2)
#define BLOCK_SIZE(id,p,n) ((BLOCK_LOW(((id)+1),p,n))-(BLOCK_LOW(id,p,n)))/2
#define BLOCK_SXN_SIZE(n) ((((n)-1)/2) - SEED_SIZE(n))
#define BLOCK_OWNER(index,p,n) (((p)*(index)+1)-1)/(n))
// [SEED | | | ] [BLOCK_SXN | | | | ]
int main (int argc, char *argv[])
{
int count; /* local prime count */
double elapsed_time; /* execution time */
int first; /* index of the first sieve */
int global_count; /* global count of prime numbers */
int high_value; /* highest value assigned to this process */
int i; /* loop counter */
int id; /* this process id */
int index; /* index of the current sieve */
int low_value; /* lowest value assigned to this process */
int *marked; /* array elements to be marked */
int n; /* value of the largest number */
int p; /* number of processes */
int proc0_size; /* number of elements assigned to process zero */
/* this is to find if process zero has all primes */
int prime; /* current prime or sieve */
int size; /* elements in marked array */
int seed_size;
char cpu_name[MPI_MAX_PROCESSOR_NAME];
int namelen;
MPI_Init (&argc, &argv);
/* start timer */
MPI_Barrier(MPI_COMM_WORLD);
elapsed_time = -MPI_Wtime();
MPI_Comm_rank (MPI_COMM_WORLD, &id);
MPI_Comm_size (MPI_COMM_WORLD, &p);
MPI_Get_processor_name(cpu_name, &namelen);
if (argc != 2)
{
if (!id) printf ("Command line: %s <m>\n", argv[0]);
MPI_Finalize();
exit (1);
}
n = atoi(argv[1]);
/* find how many elements are assigned to this process */
low_value = BLOCK_LOW(id,p,n);
high_value = BLOCK_HIGH(id,p,n);
size = BLOCK_SIZE(id,p,n);
seed_size = SEED_SIZE(n);
proc0_size = (n-1)/(2*p);
// - main loop works only for prime * prime <= n
// - this means it only runs as long as
// prime <= sqrt(n)
// - In this setup, the program will exit if proc0 doesn't hold all starting primes (i.e.
// it will exit if a starting prime will need to be chosen from another process - which this
// program is not prepared to do.
/*
if ((OFFSET + proc0_size) < (int) sqrt((double) n))
{
if (!id) printf ("Too many processes\n");
MPI_Finalize();
exit (1);
}*/
// There is too many processes when we cannot split
// up what is left of the numbers after taking out
// the SEED section (which encloses sqrt(n))
if (BLOCK_SXN_SIZE(n) < p)
{
if (!id) printf ("Too many processes\n");
MPI_Finalize();
exit (1);
}
marked = (int *) malloc ((seed_size + size) * sizeof(int));
if (marked == NULL)
{
printf ("Cannot allocate enough memory\n");
MPI_Finalize();
exit (1);
}
for (i = 0; i < (seed_size + size); i++) marked[i] = 0;
index = 0;
prime = OFFSET;
if(!id) printf("[%d-%s] SEED: low[ 0]= 3, high[%6d]=%6d (%d)\n", id, cpu_name, (SEED_SIZE(n)-1), SEED_HIGH(n), seed_size);
MPI_Barrier(MPI_COMM_WORLD);
printf("[%d-%s] ARRAY: low[%6d]=%6d, high[%6d]=%6d (%d)\n", id, cpu_name, seed_size, low_value, seed_size + size-1, high_value, size);
do {
//printf("[%d] *prime: %d\n", id, prime);
// SEED marking - mark the multiples of the seed - within
// the seed block. Start marking from the value of
// the prime * prime, which is at the position
// index + prime
for (i = index + prime; i < seed_size; i += prime)
{
//printf("[%d] marked: %d\n", id, (OFFSET + (i * 2)));
marked[i] = 1;
}
// Now, we need to continue to the block section, and keep
// marking. But we first need to find out where to start.
// For each process, we need to find the first element to mark.
// The first number that we would have to mark is prime * prime
// If the first number to mark (prime * prime) is at least
// above the low bound of this process ...
if (prime * prime > low_value)
{
// ... Then the first index is that number (prime * prime)
// - the low_value. E.g:
// prime = 7
// low_value = 41
// first = [(7*7) - 41]/2 = (49 - 41)/2 = 8/2 = 4
// marked[4] will be marked first
first = (prime * prime - low_value)/2;
//printf("[%d] first(a): %d(%d)\n", id, first, low_value + (2 * first));
}
else
{
// This section is for "run-on" arrays, e.g.
// prime=3
// p0 [ 3| 5] 3*3 > 3
// p1 [ 7| 9] 3*3 !> 7 "run-on", need mark 9
// p2 [11|13] 3*3 !> 11 "run-on"
if (!(low_value % prime))
{
// If it is, then the first element of the
// array will be the starting place
first = 0;
//printf("[%d] first(b): %d(%d)\n", id, first, low_value + (2 * first));
}
else
{
// (3 - (11 % 3))/2
// (3 - (2))/2s
int tmp = prime - (low_value % prime);
first = tmp % 2 == 0 ? tmp/2 : (tmp + prime)/2;
//printf("[%d] first(c): %d(%d)\n", id, first, low_value + (2 * first));
}
}
// 0 sqrt(n)
// [SEED ][ BLOCK_SXN ]
// SEED_SIZE -------> ---> first
// ----------------------> first + SEED_SIZE
// Now, mark all multiples of the prime.
// 'first' is a multiple of the prime, so += prime
// is also a multiple.
for (i = first; i < size; i += prime)
{
//printf("[%d] marked: %d\n", id, (low_value + (i * 2)));
marked[i + seed_size] = 1;
}
// Increase 'index' which pointed to the last
// smallest prime, until it reaches the next
// smallest prime.
while (marked[++index]);
// Remember, each 'index' in process 0
// represents the number = index + 2
prime = (2 * index) + OFFSET;
} while (prime * prime <= n);
count = 0;
// Total up the amount of items that are not marked
// i.e. the number of local primes
// REMOVE LATER!!!!
//sleep(1);
MPI_Barrier(MPI_COMM_WORLD);
//
//printf("[%d] ", id);
if (!id)
{
for (i = 0; i < seed_size; i++)
{
if (!marked[i])
{
//printf("%d,", ((2*i)+low_value));
count++;
}
}
}
for (i = 0; i < size; i++)
{
if (!marked[i + seed_size])
{
//printf("%d,", ((2*i)+low_value));
count++;
}
}
//printf("\n");
// process 0 will receieve the sum of the number
// of local primes
MPI_Reduce (&count, &global_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
elapsed_time += MPI_Wtime();
if (!id) {
global_count++; // To account for 2
printf ("%d primes are less than or equal to %d\n",
global_count, n);
printf ("Total elapsed time: %10.6f\n", elapsed_time);
}
MPI_Finalize ();
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_file.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: srison <srison@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/04/28 08:25:38 by srison #+# #+# */
/* Updated: 2015/04/28 08:25:44 by srison ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int put_file_error(int error, char c)
{
if (error == 1)
{
ft_putstr("Invalid value for the map : \"");
ft_putchar(c);
ft_putendl("\".");
}
else if (error == 2)
ft_putendl("Lines are not well formated (different size).");
else if (error == 3)
ft_putendl("Empty file.");
else if (error == 4)
ft_putendl("Lines are not well formated (different number of int).");
return (0);
}
static int check_size(char **file)
{
int max_size;
int size;
int i;
int j;
i = -1;
while (file[++i])
{
j = -1;
size = 0;
while (file[i][++j])
if (file[i][j] >= '0' && file[i][j] <= '9' &&
(!j || file[i][j - 1] == ' ' || file[i][j - 1] == '-'))
size++;
if (!i)
max_size = size;
else if (size != max_size)
return (put_file_error(4, '0'));
}
return (1);
}
int check_file(char **file)
{
int valid;
int i;
int j;
i = -1;
valid = 0;
while (file[++i])
{
j = -1;
while (file[i][++j])
if ((file[i][j] < '0' || file[i][j] > '9') &&
file[i][j] != ' ' && file[i][j] != '-')
return (put_file_error(1, file[i][j]));
else if (!valid)
valid = 1;
}
if (!valid)
return (put_file_error(3, '0'));
return (check_size(file));
}
|
C
|
/*
* ISEL - DEETC - LEIC
* Programação em Sistemas Computacionais
* João Trindade
*
* Point: versão C da classe Point
*/
#include "Point.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const PointMethods Point_vtable = {
"Point",
sizeof(Point),
Point_magnitude,
Point_print
};
void init_Point_XY(Point * this, int x, int y, const char * name) {
this->vptr = &Point_vtable;
this->name = NULL;
if (name) { this->name = (char *)malloc(strlen(name) + 1); strcpy(this->name, name); }
this->x = x;
this->y = y;
}
void cleanup_Point(Point * this) {
if (this->name) {
free(this->name);
this->name = NULL; /* só por precaução */
}
}
void Point_translate(Point * this, int dx, int dy) {
this->x += dx;
this->y += dy;
}
double Point_magnitude(const Point * this) {
return sqrt((double)(this->x) * (this->x) + (double)(this->y) * (this->y));
}
void Point_print(const Point * this) {
printf("{ name = \"%s\"; x = %d; y = %d }\n",
this->name ? this->name : "",
this->x, this->y);
}
Point * new_Point(const char * name) {
Point * p = (Point *)malloc(sizeof(Point)); /* Alocação dinâmica do espaço. */
init_Point(p, name); /* Inicialização da instância. */
return p;
}
Point * new_Point_XY(int x, int y, const char * name) {
Point * p = (Point *)malloc(sizeof(Point)); /* Alocação dinâmica do espaço. */
init_Point_XY(p, x, y, name); /* Inicialização da instância. */
return p;
}
void delete_Point(Point * this) {
if (this != NULL) {
cleanup_Point(this); /* Finalização da instância. */
free(this); /* Libertação do espaço alocado. */
}
}
|
C
|
/**
* \file appl_generic_location_client.c
*
* \brief This file defines the Mesh Generic Location Model Application Interface
* - includes Data Structures and Methods for Client.
*/
/*
* Copyright (C) 2018. Mindtree Ltd.
* All rights reserved.
*/
/* --------------------------------------------- Header File Inclusion */
#include "appl_generic_location_client.h"
/* --------------------------------------------- Global Definitions */
/* --------------------------------------------- Static Global Variables */
static const char main_generic_location_client_options[] = "\n\
======== Generic_Location Client Menu ========\n\
0. Exit. \n\
1. Refresh. \n\
\n\
10. Send Generic Location Global Get. \n\
11. Send Generic Location Global Set. \n\
12. Send Generic Location Global Set Unacknowledged. \n\
13. Send Generic Location Local Get. \n\
14. Send Generic Location Local Set. \n\
15. Send Generic Location Local Set Unacknowledged. \n\
\n\
16. Get Model Handle. \n\
17. Set Publish Address. \n\
\n\
Your Option ? \0";
/* --------------------------------------------- External Global Variables */
static MS_ACCESS_MODEL_HANDLE appl_generic_location_client_model_handle;
/* --------------------------------------------- Function */
/* generic_location client application entry point */
void main_generic_location_client_operations(void)
{
int choice;
MS_ACCESS_ELEMENT_HANDLE element_handle;
static UCHAR model_initialized = 0x00;
/**
* Register with Access Layer.
*/
if (0x00 == model_initialized)
{
API_RESULT retval;
/* Use Default Element Handle. Index 0 */
element_handle = MS_ACCESS_DEFAULT_ELEMENT_HANDLE;
retval = MS_generic_location_client_init
(
element_handle,
&appl_generic_location_client_model_handle,
appl_generic_location_client_cb
);
if (API_SUCCESS == retval)
{
CONSOLE_OUT(
"Generic Location Client Initialized. Model Handle: 0x%04X\n",
appl_generic_location_client_model_handle);
}
else
{
CONSOLE_OUT(
"[ERR] Generic Location Client Initialization Failed. Result: 0x%04X\n",
retval);
}
model_initialized = 0x01;
}
MS_LOOP_FOREVER()
{
CONSOLE_OUT
("%s", main_generic_location_client_options);
CONSOLE_IN
("%d", &choice);
if (choice < 0)
{
CONSOLE_OUT
("*** Invalid Choice. Try Again.\n");
continue;
}
switch (choice)
{
case 0:
return;
case 1:
break;
case 10: /* Send Generic Location Global Get */
appl_send_generic_location_global_get();
break;
case 11: /* Send Generic Location Global Set */
appl_send_generic_location_global_set();
break;
case 12: /* Send Generic Location Global Set Unacknowledged */
appl_send_generic_location_global_set_unacknowledged();
break;
case 13: /* Send Generic Location Local Get */
appl_send_generic_location_local_get();
break;
case 14: /* Send Generic Location Local Set */
appl_send_generic_location_local_set();
break;
case 15: /* Send Generic Location Local Set Unacknowledged */
appl_send_generic_location_local_set_unacknowledged();
break;
case 16: /* Get Model Handle */
appl_generic_location_client_get_model_handle();
break;
case 17: /* Set Publish Address */
appl_generic_location_client_set_publish_address();
break;
}
}
}
/* Send Generic Location Global Get */
void appl_send_generic_location_global_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Location Global Get\n");
retval = MS_generic_location_global_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Location Global Set */
void appl_send_generic_location_global_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_LOCATION_GLOBAL_STRUCT param;
CONSOLE_OUT
(">> Send Generic Location Global Set\n");
CONSOLE_OUT
("Enter Global Latitude (32-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.global_latitude = (UINT32)choice;
CONSOLE_OUT
("Enter Global Longitude (32-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.global_longitude = (UINT32)choice;
CONSOLE_OUT
("Enter Global Altitude (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.global_altitude = (UINT16)choice;
retval = MS_generic_location_global_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Location Global Set Unacknowledged */
void appl_send_generic_location_global_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_LOCATION_GLOBAL_STRUCT param;
CONSOLE_OUT
(">> Send Generic Location Global Set Unacknowledged\n");
CONSOLE_OUT
("Enter Global Latitude (32-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.global_latitude = (UINT32)choice;
CONSOLE_OUT
("Enter Global Longitude (32-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.global_longitude = (UINT32)choice;
CONSOLE_OUT
("Enter Global Altitude (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.global_altitude = (UINT16)choice;
retval = MS_generic_location_global_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Location Local Get */
void appl_send_generic_location_local_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Location Local Get\n");
retval = MS_generic_location_local_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Location Local Set */
void appl_send_generic_location_local_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_LOCATION_LOCAL_STRUCT param;
CONSOLE_OUT
(">> Send Generic Location Local Set\n");
CONSOLE_OUT
("Enter Local North (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.local_north = (UINT16)choice;
CONSOLE_OUT
("Enter Local East (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.local_east = (UINT16)choice;
CONSOLE_OUT
("Enter Local Altitude (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.local_altitude = (UINT16)choice;
CONSOLE_OUT
("Enter Floor Number (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.floor_number = (UCHAR)choice;
CONSOLE_OUT
("Enter Uncertainty (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.uncertainty = (UINT16)choice;
retval = MS_generic_location_local_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Location Local Set Unacknowledged */
void appl_send_generic_location_local_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_LOCATION_LOCAL_STRUCT param;
CONSOLE_OUT
(">> Send Generic Location Local Set Unacknowledged\n");
CONSOLE_OUT
("Enter Local North (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.local_north = (UINT16)choice;
CONSOLE_OUT
("Enter Local East (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.local_east = (UINT16)choice;
CONSOLE_OUT
("Enter Local Altitude (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.local_altitude = (UINT16)choice;
CONSOLE_OUT
("Enter Floor Number (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.floor_number = (UCHAR)choice;
CONSOLE_OUT
("Enter Uncertainty (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.uncertainty = (UINT16)choice;
retval = MS_generic_location_local_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Get Model Handle */
void appl_generic_location_client_get_model_handle(void)
{
API_RESULT retval;
MS_ACCESS_MODEL_HANDLE model_handle;
retval = MS_generic_location_client_get_model_handle(&model_handle);
if (API_SUCCESS == retval)
{
CONSOLE_OUT
(">> Model Handle 0x%04X\n", model_handle);
}
else
{
CONSOLE_OUT
(">> Get Model Handle Failed. Status 0x%04X\n", retval);
}
return;
}
/* Set Publish Address */
void appl_generic_location_client_set_publish_address(void)
{
int choice;
API_RESULT retval;
MS_ACCESS_MODEL_HANDLE model_handle;
MS_ACCESS_PUBLISH_INFO publish_info;
/* Set Publish Information */
EM_mem_set(&publish_info, 0, sizeof(publish_info));
publish_info.addr.use_label = MS_FALSE;
CONSOLE_OUT
("Enter Model Handle (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
model_handle = (UINT16)choice;
CONSOLE_OUT
("Enter Generic_Location client Server Address (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
publish_info.addr.addr = (UINT16)choice;
CONSOLE_OUT
("Enter AppKey Index\n");
CONSOLE_IN
("%x", &choice);
publish_info.appkey_index = choice;
publish_info.remote = MS_FALSE;
retval = MS_access_cm_set_model_publication
(
model_handle,
&publish_info
);
if (API_SUCCESS == retval)
{
CONSOLE_OUT
(">> Publish Address is set Successfully.\n");
}
else
{
CONSOLE_OUT
(">> Failed to set publish address. Status 0x%04X\n", retval);
}
return;
}
/**
* \brief Client Application Asynchronous Notification Callback.
*
* \par Description
* Generic_Location client calls the registered callback to indicate events occurred to the application.
*
* \param [in] handle Model Handle.
* \param [in] opcode Opcode.
* \param [in] data_param Data associated with the event if any or NULL.
* \param [in] data_len Size of the event data. 0 if event data is NULL.
*/
API_RESULT appl_generic_location_client_cb
(
/* IN */ MS_ACCESS_MODEL_HANDLE * handle,
/* IN */ UINT32 opcode,
/* IN */ UCHAR * data_param,
/* IN */ UINT16 data_len
)
{
API_RESULT retval;
retval = API_SUCCESS;
CONSOLE_OUT (
"[GENERIC_LOCATION_CLIENT] Callback. Opcode 0x%04X\n", opcode);
appl_dump_bytes(data_param, data_len);
switch(opcode)
{
case MS_ACCESS_GENERIC_LOCATION_GLOBAL_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_LOCATION_GLOBAL_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_LOCATION_LOCAL_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_LOCATION_LOCAL_STATUS_OPCODE\n");
}
break;
}
return retval;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int ch;
int len = 0;
while( ( ch = getchar() ) != EOF )
{
if( ch =='{' )
len++;
else if( ch == '}' )
{
/* 如果此时len==0 说明此时都没有左花括号,因此肯定是错误的匹配 */
if(len == 0)
printf("Extra closing brace!\n");
else
len--;
}
}
if(len == 0)
printf ( "accept!\n" );
else
printf( "sorry!unmatched\n" );
return EXIT_SUCCESS;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
int sum(int *array, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
return sum;
}
int main(void) {
int *buffer = calloc(sizeof(int), 10);
buffer[0] = 10;
printf("before = %d\n", sum(buffer, 10));
buffer = realloc(buffer, sizeof(int) * 100);
printf("after = %d\n", sum(buffer, 100));
return 0;
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include <sched.h>
#include <string.h>
#define CLOCK_TYPE CLOCK_MONOTONIC_RAW
uint64_t getclock()
{
struct timespec ts;
if (clock_gettime(CLOCK_TYPE, &ts) != 0) {
perror("clock_gettime");
exit(1);
}
return (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}
#define N (500*1000*1000)
#define MAXTHREADS 16
#define ACCESS_ONCE(x) (*(volatile typeof(x) *)&(x))
struct list {
struct list *next;
long val;
};
struct thrarg {
double res;
void *arg;
};
static pthread_barrier_t barrier;
static char *mem;
static long (*benchmark)(struct list*);
long benchmark_v(struct list *l)
{
unsigned i;
for (i=0; i < N; i++) {
l->val += 1;
l = l->next;
}
return N;
}
long benchmark_a(struct list *l)
{
unsigned i;
long r;
for (i=0; i < N; i++) {
r = __atomic_load_n(&l->val, __ATOMIC_RELAXED);
__atomic_store_n(&l->val, r + 10, __ATOMIC_RELAXED);
}
return N;
}
long benchmark_s(struct list *l)
{
unsigned i;
unsigned n = N/10;
for (i=0; i < n; i++) {
__atomic_fetch_add(&l->val, 10, __ATOMIC_RELAXED);
}
return n;
}
long benchmark_r(struct list *l)
{
unsigned i;
long r;
for (i=0; i < N; i++) {
if (l == (struct list *)mem) {
r = __atomic_load_n(&l->val, __ATOMIC_RELAXED);
__atomic_store_n(&l->val, r + 10, __ATOMIC_RELAXED);
} else {
r = __atomic_load_n(&l->val, __ATOMIC_RELAXED);
}
}
(void)r;
return N;
}
static void *thread(void *arg)
{
uint64_t t1, t2;
long n;
struct thrarg *thrarg = (struct thrarg *)arg;
pthread_barrier_wait(&barrier);
t1 = getclock();
n = benchmark(thrarg->arg);
t2=getclock();
thrarg->res = (t2 - t1)/(n*1.0);
return NULL;
}
int main(int argc, char **argv)
{
unsigned i;
unsigned nthreads = 2;
unsigned pad;
pthread_t threads[MAXTHREADS];
struct thrarg thrargs[MAXTHREADS];
pthread_attr_t attr;
cpu_set_t c;
if (argc < 3)
return 1;
if ( sscanf(argv[1], "%u", &pad) < 1)
return 1;
if (pad < sizeof(struct list))
return 1;
switch(argv[2][0]) {
case 'v':
benchmark = benchmark_v;
break;
case 's':
benchmark = benchmark_s;
break;
case 'r':
benchmark = benchmark_r;
break;
case 'a':
benchmark = benchmark_a;
break;
default:
benchmark = NULL;
}
if (posix_memalign((void **)&mem, 128, nthreads*pad)) {
perror("posix_memalign");
return 1;
}
pthread_barrier_init(&barrier, NULL, nthreads);
pthread_attr_init(&attr);
memset(mem, 0, nthreads*pad);
for (i=0; i < nthreads; i++) {
struct list *l = (struct list *)&mem[i*pad];
l->next = l;
}
for (i = 0; i < nthreads; i++) {
CPU_ZERO(&c);
CPU_SET(i, &c);
pthread_attr_setaffinity_np(&attr, sizeof(c), &c);
thrargs[i].arg = &mem[i*pad];
pthread_create(&threads[i], &attr, thread, &thrargs[i]);
}
for (i = 0; i < nthreads; i++) {
pthread_join(threads[i], NULL);
printf(" %.2f", thrargs[i].res);
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,reverse=0;
printf("Please enter a number for palindrome check\n");
scanf("%d",&n);
int t=n;
while(t)
{
reverse=reverse*10+(t%10);
t/=10;
}
if(n==reverse)
printf("%d is a Palindrome",n);
else
printf("%d is not a Palindrome",n);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void insertatpos(int data,int pos)
{
int i;
struct node* temp=(struct node*)malloc(sizeof(struct node));
temp->data=data;
if(pos==1)
{
temp->link=head;
head=temp;
return;
}
struct node* next=head;
for(i=0;i<pos-1;i++)
{
next=next->link;
}
temp->link=next->link;
next->link=temp;
}
void print_ll()
{
struct node* manju=head;
while(manju->link!=NULL)
{
printf("%d",manju->data);
manju=manju->link;
}
printf("%d",manju->data);
}
int main()
{
head=NULL;
int i,n,data,pos;
printf("enter nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&data);
scanf("%d",&pos);
insertatpos(data,pos);
print_ll();
}
}
|
C
|
#include <stdio.h>
#include <unistd.h>
main(){
int i;
for(i=0;i<1030;i++)
printf("A");
sleep(3);
printf("BBB");
}
|
C
|
#include"SeqQueue.h"
#define _CTR_SECURE_NO_WARNINGS
typedef struct PERSON
{
char name[64];
int age;
}Person;
int main()
{
SeqQueue* queue = Init_SeqQueue();
printf("%d", queue->size);
Person p1 = { "aaa",10 };
Person p2 = { "bbb",20 };
Person p3 = { "ccc",30 };
Person p4 = { "ddd",40 };
Person p5 = { "eee",50 };
Push_SeqQueue(queue, &p1);
Push_SeqQueue(queue, &p2);
Push_SeqQueue(queue, &p3);
Push_SeqQueue(queue, &p4);
Push_SeqQueue(queue, &p5);
Person* backPerson = (Person*)Back_SeqQueue(queue);
printf("βԪ:Name:%s Age:%d\n", backPerson->name, backPerson->age);
while (Size_SeqQueue(queue) > 0)
{
Person* person = (Person*)Front_SeqQueue(queue);
printf("Name:%s Age:%d\n", person->name, person->age);
Pop_SeqQueue(queue);
}
FreeSpace_SeqQueue(queue);
system("pause");
return 0;
}
|
C
|
#include<stdio.h>
typedef struct log
{
char in_out;
int r;
}log;
int main()
{
int n,i,j;
scanf("%d",&n);
log a[n];
int ans[1000001];
for(i=0;i<1000001;i++)
ans[i]=-1;
int c=0;
int flag1=0;
for(i=0;i<n;i++)
{
int flag=0;
scanf("%c",&a[i].in_out);
getchar();
scanf("%d",&a[i].r);
if(a[i].in_out=='-')
{
if(flag1==0)
ans[a[i].r]=0;
else if(flag1!=0)
flag1=0;
}
else
{
for(j=0;j<1000001;j++)
{
if(ans[j]==0)
{
ans[j]=1;
flag=1;
flag1=1;
break;
}
}
printf("flag %d, flag1 %d\n",flag,flag1);
if(flag!=1)
ans[a[i].r]=1;
}
}
for(i=0;i<1000001;i++)
{
if(ans[i]!=-1)
c++;
}
printf("%d\n",c);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int n,k;
int a[5][5];
int sol(int x, int y,int num){
//printf("%d %d %d\n",x,y,num);
int ans=a[x][y]^num;
if(x==n-1){
if(ans==0){
return 1;
}
return 0;
}
int i;
for(i=0;i<k;i++){
if(sol(x+1,i,ans))return 1;
}
return 0;
}
int main(){
scanf("%d %d",&n,&k);
int i,j;
for(i=0;i<n;i++){
for(j=0;j<k;j++){
scanf("%d",&a[i][j]);
}
}
for(i=0;i<k;i++){
if(sol(0,i,0)){
printf("Found\n");
return 0;
}
}
printf("Nothing\n");
} ./Main.c: In function main:
./Main.c:21:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d %d",&n,&k);
^
./Main.c:26:13: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d",&a[i][j]);
^
|
C
|
/*
* Copyright (C) xianliang.li
*/
#include <string.h>
#include <stdlib.h>
#include "lxl_rbtree.h"
static inline void lxl_rbtree_left_rotate(lxl_rbtree_node_t **root, lxl_rbtree_node_t *sentinel, lxl_rbtree_node_t *node);
static inline void lxl_rbtree_right_rotate(lxl_rbtree_node_t **root, lxl_rbtree_node_t *sentinel, lxl_rbtree_node_t *node);
/*lxl_rbtree_t *
lxl_rbtree_create(lxl_rbtree_node_t *sentinel, lxl_rbtree_insert_pt insert)
{
lxl_rbtree_t *tree = (lxl_rbtree_t *) malloc(sizeof(lxl_rbtree_t));
if (!tree) {
return NULL;
}
lxl_rbt_black(sentinel);
tree->root = sentinel;
tree->sentinel = sentinel;
tree->insert = insert;
return tree;
}*/
void
lxl_rbtree_insert(lxl_rbtree_t *tree, lxl_rbtree_node_t *node)
{
lxl_rbtree_node_t **root, *temp, *sentinel;
root = (lxl_rbtree_node_t **) &tree->root;
sentinel = tree->sentinel;
if (*root == sentinel) {
node->parent = NULL;
node->left = sentinel;
node->right = sentinel;
lxl_rbt_black(node);
*root = node;
return;
}
tree->insert(*root, node, sentinel);
while (node != *root && lxl_rbt_is_red(node->parent)) {
if (node->parent == node->parent->parent->left) {
temp = node->parent->parent->right;
if (lxl_rbt_is_red(temp)) {
lxl_rbt_black(temp);
lxl_rbt_black(node->parent);
lxl_rbt_red(node->parent->parent);
node = node->parent->parent;
} else {
if (node == node->parent->right) {
node = node->parent;
lxl_rbtree_left_rotate(root, sentinel, node); /* node location chanage */
}
lxl_rbt_black(node->parent);
lxl_rbt_red(node->parent->parent);
lxl_rbtree_right_rotate(root, sentinel, node->parent->parent);
}
} else {
temp = node->parent->parent->left;
if (lxl_rbt_is_red(temp)) {
lxl_rbt_black(temp);
lxl_rbt_black(node->parent);
lxl_rbt_red(node->parent->parent);
node = node->parent->parent;
} else {
if (node == node->parent->left) {
node = node->parent;
lxl_rbtree_right_rotate(root, sentinel, node);
}
lxl_rbt_black(node->parent);
lxl_rbt_red(node->parent->parent);
lxl_rbtree_left_rotate(root, sentinel, node->parent->parent);
}
}
}
lxl_rbt_black(*root);
}
void
lxl_rbtree_insert_value(lxl_rbtree_node_t *temp, lxl_rbtree_node_t *node, lxl_rbtree_node_t *sentinel)
{
lxl_rbtree_node_t **p;
for (; ;) {
p = (node->key < temp->key) ? &temp->left : &temp->right;
if (*p == sentinel) {
break;
}
temp = *p;
}
*p = node;
node->parent = temp;
node->left = sentinel;
node->right = sentinel;
lxl_rbt_red(node);
}
void
lxl_rbtree_delete(lxl_rbtree_t *tree, lxl_rbtree_node_t *node)
{
unsigned char red;
lxl_rbtree_node_t **root, *sentinel, *subst, *temp, *w;
root = (lxl_rbtree_node_t **) &tree->root;
sentinel = tree->sentinel;
if (node->left == sentinel) {
subst = node;
temp = node->right;
} else if (node->right == sentinel) {
subst = node;
temp = node->left;
} else {
subst = lxl_rbtree_min(node->right, sentinel);
/*if (subst->left != sentinel) {
temp = subst->left;
} else {
temp = subst->right;
}*/
temp = subst->right;
}
if (subst == *root) {
*root = temp;
(*root)->parent = NULL; /* lxl add geng jia fuhe */
lxl_rbt_black(temp);
/*node->parent = NULL;
node->left = NULL;
node->right = NULL;
node->key = 0;*/
return;
}
red = lxl_rbt_is_red(subst);
if (subst == subst->parent->left) {
subst->parent->left = temp;
} else {
subst->parent->right = temp;
}
if (subst == node) {
temp->parent = subst->parent;
} else {
if (subst->parent == node) {
temp->parent = subst;
} else {
temp->parent = subst->parent;
}
subst->parent = node->parent;
subst->left = node->left;
subst->right = node->right;
lxl_rbt_copy_color(subst, node);
if (node == *root) {
*root = subst;
} else {
if (node == node->parent->left) {
node->parent->left = subst;
} else {
node->parent->right = subst;
}
}
if (subst->left != sentinel) {
subst->left->parent = subst;
}
if (subst->right != sentinel) {
subst->right->parent = subst;
}
}
/*
node->parent = NULL;
node->left = NULL;
node->parent = NULL;
node->key = 0;*/
if (red) {
return;
}
while (temp != *root && lxl_rbt_is_black(temp)) {
if (temp == temp->parent->left) {
w = temp->parent->right;
if (lxl_rbt_is_red(w)) {
lxl_rbt_black(w);
lxl_rbt_red(temp->parent);
lxl_rbtree_left_rotate(root, sentinel, temp->parent);
w = temp->parent->right;
}
if (lxl_rbt_is_black(w->left) && lxl_rbt_is_black(w->right)) {
lxl_rbt_red(w);
temp = temp->parent;
} else {
if (lxl_rbt_is_black(w->right)) {
lxl_rbt_black(w->left);
lxl_rbt_red(w);
lxl_rbtree_right_rotate(root, sentinel, w);
w = temp->parent->right;
}
lxl_rbt_copy_color(w, temp->parent);
lxl_rbt_black(temp->parent);
lxl_rbt_black(w->right);
lxl_rbtree_left_rotate(root, sentinel, temp->parent);
temp = *root;
}
} else {
w = temp->parent->left;
if (lxl_rbt_is_red(w)) {
lxl_rbt_black(w);
lxl_rbt_red(temp->parent);
lxl_rbtree_right_rotate(root, sentinel, temp->parent);
w = temp->parent->left;
}
if (lxl_rbt_is_black(w->left) && lxl_rbt_is_black(w->right)) {
lxl_rbt_red(w);
temp = temp->parent;
} else {
if (lxl_rbt_is_black(w->left)) {
lxl_rbt_black(w->right);
lxl_rbt_red(w);
lxl_rbtree_left_rotate(root, sentinel, w);
w = temp->parent->left;
}
lxl_rbt_copy_color(w, temp->parent);
lxl_rbt_black(temp->parent);
lxl_rbt_black(w->left);
lxl_rbtree_right_rotate(root, sentinel, temp->parent);
temp = *root;
}
}
}
lxl_rbt_black(temp);
}
static inline void
lxl_rbtree_left_rotate(lxl_rbtree_node_t **root, lxl_rbtree_node_t *sentinel, lxl_rbtree_node_t *node)
{
lxl_rbtree_node_t *temp;
temp = node->right;
node->right = temp->left;
if (temp->left != sentinel) {
temp->left->parent = node;
}
temp->parent = node->parent;
if (node == *root) {
*root = temp;
} else if (node == node->parent->left) {
node->parent->left = temp;
} else {
node->parent->right = temp;
}
temp->left = node;
node->parent = temp;
}
static inline void
lxl_rbtree_right_rotate(lxl_rbtree_node_t **root, lxl_rbtree_node_t *sentinel, lxl_rbtree_node_t *node)
{
lxl_rbtree_node_t *temp;
temp = node->left;
node->left = temp->right;
if (temp->right != sentinel) {
temp->right->parent = node;
}
temp->parent = node->parent;
if (node == *root) {
*root = temp;
} else if (node == node->parent->left) {
node->parent->left = temp;
} else {
node->parent->right = temp;
}
temp->right = node;
node->parent = temp;
}
#if 0
#include <stdio.h>
#include <stdlib.h>
#include "lxl_stack.h"
#include "lxl_queue.h"
void lxl_rbtree_order_in(lxl_rbtree_t *tree);
void lxl_rbtree_order_layer(lxl_rbtree_t *tree);
int main(int argc, char *argv[])
{
int i;
int array_key[] = {12, 1, 9, 2, 0, 11, 7, 19, 4, 15, 18, 5, 14, 13, 10, 16, 6, 3, 8, 17};
lxl_rbtree_node_t sentinel, *node;
// lxl_rbtree_t *tree = lxl_rbtree_create(&sentinel, lxl_rbtree_insert_value);
lxl_rbtree_t tree;
lxl_rbtree_init(&tree, &sentinel, lxl_rbtree_insert_value);
for (i = 0; i < 20; ++i) {
node = (lxl_rbtree_node_t *) malloc(sizeof(lxl_rbtree_node_t));
node->key = array_key[i];
lxl_rbtree_insert(&tree, node);
}
lxl_rbtree_order_in(&tree);
fprintf(stderr, "==========================================================\n");
lxl_rbtree_order_layer(&tree);
for (i = 0; i < 20; ++i) {
node = lxl_rbtree_search(&tree, array_key[i]);
if (node) {
fprintf(stderr, "===========delete %lu ========\n", node->key);
lxl_rbtree_delete(&tree, node);
free(node);
}
lxl_rbtree_order_layer(&tree);
}
/*for (i = 0; i < 50; ++i) {
node = (lxl_rbtree_node_t *) malloc(sizeof(lxl_rbtree_node_t));
node->key = i;
lxl_rbtree_insert(&tree, node);
}
lxl_rbtree_order_layer(&tree);*/
return 0;
}
void
lxl_rbtree_order_in(lxl_rbtree_t *tree)
{
lxl_stack_t *s = lxl_stack_create(20);
lxl_rbtree_node_t *node, *sentinel;
sentinel = tree->sentinel;
node = tree->root;
while (node != sentinel || !lxl_stack_empty(s)) {
while (node != sentinel) {
lxl_stack_push(s, node);
node = node->left;
}
if (!lxl_stack_empty(s)) {
node = lxl_stack_pop(s);
fprintf(stderr, "%lu\t", node->key);
node = node->right;
}
}
fprintf(stderr, "\n");
}
void
lxl_rbtree_order_layer(lxl_rbtree_t *tree)
{
if (tree->root == tree->sentinel) {
return;
}
lxl_uint_t top;
lxl_queue_t *q = lxl_queue_create(20);
lxl_rbtree_node_t *node, *sentinel;
sentinel = tree->sentinel;
lxl_queue_in(q, tree->root);
top = q->rear;
while (!lxl_queue_empty(q)) {
while (q->front != top) {
node = lxl_queue_out(q);
if (lxl_rbt_is_black(node)) {
fprintf(stderr, "%lu", node->key);
} else {
fprintf(stderr, "\033[31;49;1m%lu\033[0m", node->key);
//fprintf(stderr, "%lu(red)\t", node->key);
}
if (node->parent) {
fprintf(stderr, "(%lu)\t", node->parent->key);
} else {
fprintf(stderr, "\t");
}
if (node->left != sentinel) {
lxl_queue_in(q, node->left);
}
if (node->right != sentinel) {
lxl_queue_in(q, node->right);
}
}
top = q->rear;
fprintf(stderr, "===\n");
}
}
#endif
|
C
|
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MOD = 1000000007;
LL pow(LL a, int p) {
if(p==0) return 1;
if(p==1) return a;
LL ret = pow(a,p>>1);
(ret *= ret)%=MOD;
if(p&1) (ret *= a)%=MOD;
return ret;
}
int main()
{
int N; cin >> N;
int C[N];
map <int, int> M;
for(int i=0;i<N;i++)
{
cin >> C[i];
M[C[i]]++;
}
map <int, int> :: iterator it;
it = M.begin();
for (int k=1;k<=1000;k++)
{
int color = k;
}
cout << pow(2,1000) << endl;
return 0;
}
|
C
|
#include<stdio.h>
int main() {
float unit;
printf("Units : ");
scanf("%f", &unit);
if(unit >= 0) {
if(unit <= 50) {
printf("Bill : Rs %f", unit * 0.50);
} else if(unit > 50 && unit <= 100) {
printf("Bill : Rs %f", unit * 0.75);
} else if(unit > 100 && unit <= 250) {
printf("Bill : Rs %f", unit * 1.20);
} else {
printf("Bill : Rs %f", unit * 1.50);
}
} else {
printf("Enter valid input.");
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <kogata/mainloop.h>
mainloop_fd_t *mainloop_fds = 0;
bool mainloop_fds_change = false;
bool mainloop_must_exit = false;
void mainloop_add_fd(mainloop_fd_t* fd) {
mainloop_fds_change = true;
fd->next = mainloop_fds;
mainloop_fds = fd;
fd->rd_buf_filled = 0;
}
void mainloop_rm_fd(mainloop_fd_t* fd) {
mainloop_fds_change = true;
if (mainloop_fds == fd) {
mainloop_fds = fd->next;
} else {
for (mainloop_fd_t *it = mainloop_fds; it->next != 0; it = it->next) {
if (it->next == fd) {
it->next = fd->next;
break;
}
}
}
}
void mainloop_expect(mainloop_fd_t *fd, void* buf, size_t size, buf_full_callback_t cb) {
fd->rd_buf = buf;
fd->rd_on_full = cb;
fd->rd_buf_expect_size = size;
fd->rd_buf_filled = 0;
}
bool mainloop_nonblocking_write(mainloop_fd_t *fd, void* buf, size_t size, bool must_free_buf) {
for (int i = 0; i < MAINLOOP_MAX_WR_BUFS; i++) {
if (fd->wr_bufs[i].buf == 0) {
fd->wr_bufs[i].buf = buf;
fd->wr_bufs[i].written = 0;
fd->wr_bufs[i].size = size;
fd->wr_bufs[i].must_free = must_free_buf;
return true;
}
}
return false;
}
void mainloop_run() {
sel_fd_t *sel_arg = 0;
int nfds = 0;
mainloop_fds_change = true;
mainloop_must_exit = false;
while(!mainloop_must_exit) {
if (mainloop_fds_change) {
nfds = 0;
for (mainloop_fd_t *fd = mainloop_fds; fd != 0; fd = fd->next)
nfds++;
if (nfds == 0) return;
if (sel_arg != 0) free(sel_arg);
sel_arg = (sel_fd_t*)malloc(nfds * sizeof(sel_fd_t));
if (sel_arg == 0) {
dbg_printf("(mainloop) Out of memory.\n");
return;
}
mainloop_fds_change = false;
}
{ // Setup flags we are waiting for
int i = 0;
for (mainloop_fd_t *fd = mainloop_fds; fd != 0; fd = fd->next) {
sel_arg[i].fd = fd->fd;
sel_arg[i].req_flags =
(fd->rd_buf != 0 ? SEL_READ : 0)
| (fd->wr_bufs[0].buf != 0 ? SEL_WRITE : 0) | SEL_ERROR;
i++;
}
}
// ---- Do the select
/*dbg_printf("(mainloop) begin select\n");*/
bool ok = sc_select(sel_arg, nfds, -1);
if (!ok) {
dbg_printf("(mainloop) Failed to select.\n");
free(sel_arg);
return;
}
/*dbg_printf("(mainloop) end select\n");*/
{ // Parse result
int i = 0;
for (mainloop_fd_t *fd = mainloop_fds; fd != 0 && !mainloop_fds_change; fd = fd->next) {
if (sel_arg[i].got_flags & SEL_ERROR) {
ASSERT(fd->on_error != 0);
fd->on_error(fd);
} else if ((sel_arg[i].got_flags & SEL_READ) && fd->rd_buf != 0) {
fd->rd_buf_filled +=
sc_read(fd->fd, 0, fd->rd_buf_expect_size - fd->rd_buf_filled, fd->rd_buf + fd->rd_buf_filled);
if (fd->rd_buf_filled == fd->rd_buf_expect_size) {
/*dbg_printf("(mainloop) finish read %d\n", fd->rd_buf_expect_size);*/
fd->rd_buf_filled = 0;
ASSERT(fd->rd_on_full != 0);
fd->rd_on_full(fd);
}
} else if ((sel_arg[i].got_flags & SEL_WRITE) && fd->wr_bufs[0].buf != 0) {
size_t remain_size = fd->wr_bufs[0].size - fd->wr_bufs[0].written;
void* write_ptr = fd->wr_bufs[0].buf + fd->wr_bufs[0].written;
fd->wr_bufs[0].written += sc_write(fd->fd, 0, remain_size, write_ptr);
if (fd->wr_bufs[0].written == fd->wr_bufs[0].size) {
/*dbg_printf("(mainloop) finish write %d\n", fd->wr_bufs[0].size);*/
if (fd->wr_bufs[0].must_free) free(fd->wr_bufs[0].buf);
for (int i = 1; i < MAINLOOP_MAX_WR_BUFS; i++) {
fd->wr_bufs[i-1] = fd->wr_bufs[i];
}
fd->wr_bufs[MAINLOOP_MAX_WR_BUFS-1].buf = 0;
}
}
i++;
}
}
}
}
void mainloop_exit() {
mainloop_must_exit = true;
}
/* vim: set ts=4 sw=4 tw=0 noet :*/
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
FILE *output;
FILE *answer;
char command[100];
char buf[100];
char output_str[100];
char answer_str[100];
printf("initialize output? (y/n)\n");
scanf("%c", &(command[0]));
if(command[0] == 'y'){
system("java MainBst public/10words.txt public/10words.txt > output/10words.out");
printf("10words complete\n");
system("java MainBst public/1000words.txt public/2000words.txt > output/1000words.out");
printf("1000words complete\n");
system("java MainBst public/1000words.txt public/2000words2.txt > output/1000words2.out");
printf("1000words2 complete\n");
system("java -Xms1024m -Xmx4096m MainBst public/sawyer.txt public/sawyer.txt > output/sawyer.out");
printf("sawyer complete\n");
system("java -Xms1024m -Xmx4096m MainBst public/sawyer.txt public/mohicans.txt > output/sawyer-mohicans.out");
printf("sawyer-mohicans complete\n");
system("java -Xms1024m -Xmx4096m MainBst public/mohicans.txt public/mohicans.txt > output/mohicans.out");
printf("mohicans complete\n");
system("java -Xms1024m -Xmx4096m MainBst public/mohicans.txt public/sawyer.txt > output/mohicans-sawyer.out");
printf("mohicans-sawyer complete\n\n");
}
//i should've used python
while(1){
printf("Enter filename to check(---.out)\n(Enter q to quit, ls to show filenames. Right part is your answer)\n>");
scanf("%s", command);
if(!strcmp("q", command))
break;
if(!strcmp("ls", command)){
system("ls ./output");
continue;
}
strcat(command, ".out");
strcpy(buf, "output/");
strcat(buf, command);
output = fopen(buf, "r");
strcpy(buf, "public/cpu-i5/");
strcat(buf, command);
answer = fopen(buf, "r");
if(answer == NULL || output == NULL){
printf("cannot open file\n");
continue;
}
int block = 0;
while(fgets(output_str, 100, output) != NULL){
fgets(answer_str, 100, answer);
if(output_str[0] != '['){
if(block != 0){
printf("%d differences found on current tree\n", block);
block = 0;
}
}
if(strcmp(output_str, answer_str)){
strtok(answer_str,"\n");
if(output_str[0] != '[')
printf("difference in statistics: %-80s %s", answer_str, output_str);
else{
if(block == 0){
printf("difference in blocks: %s %s", answer_str, output_str);
printf("and so on..\n");
}
block++;
}
}
}
}
fclose(answer);
fclose(output);
return 0;
}
|
C
|
#include "stm32f4xx.h"
#include "sys.h"
#include <stdio.h>
#include "MFRC522.h"
//GPIOʼĽṹ
static GPIO_InitTypeDef GPIO_InitStructure;
static USART_InitTypeDef USART_InitStructure;
static NVIC_InitTypeDef NVIC_InitStructure;
struct __FILE { int handle; /* Add whatever you need here */ };
FILE __stdout;
FILE __stdin;
int fputc(int ch, FILE *f) {
//Ƿ
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
USART_SendData(USART1, ch);
//Ҫ͵ַ
return ch;
}
void _sys_exit(int return_code) {
label: goto label; /* endless loop */
}
//ʹϵͳʱӵ8ƵΪϵͳʱʱԴ
void delay_us(uint32_t n)
{
SysTick->CTRL = 0; // رϵͳʱ
SysTick->LOAD = n*21-1; //n
SysTick->VAL = 0; // count־λ
SysTick->CTRL = 1; // ʹϵͳʱʱԴΪϵͳʱ168MHz/8=21MHz
while ((SysTick->CTRL & 0x00010000)==0);// ȴcount־λλ
SysTick->CTRL = 0; // رϵͳʱ
}
void delay_ms(uint32_t n)
{
while(n--)
{
//1msʱ
SysTick->CTRL = 0; // رϵͳʱ
SysTick->LOAD = 168000-1; // Count from 167999 to 0 (168000 cycles)
SysTick->VAL = 0; // count־λ
SysTick->CTRL = 5; // ʹϵͳʱʱԴΪϵͳʱ168MHz
while ((SysTick->CTRL & 0x00010000)==0);// ȴcount־λλ
}
SysTick->CTRL = 0; // رϵͳʱ
}
void usart1_init(uint32_t baud)
{
//1Ӳʱʹ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
//˿AӲʱʹ
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
//PA9PA10Ϊùģʽ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_10; //9 10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //ùģʽ
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //ǿŵ
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //ŵٶΪ100MHz
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //ûʹڲ
GPIO_Init(GPIOA, &GPIO_InitStructure);
//PA9PA10ӵ1Ӳ
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);
//1ӲʡλֹͣλУλ.....
USART_InitStructure.USART_BaudRate = baud; //
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8λλ
USART_InitStructure.USART_StopBits = USART_StopBits_1; //1λֹͣλ
USART_InitStructure.USART_Parity = USART_Parity_No; //ҪУλ
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ҫ
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1,&USART_InitStructure);
//ʹܴ1Ӳ
USART_Cmd(USART1,ENABLE);
//һֽںʹж
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
/* Enable the USARTx Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
//MFRC522
u8 mfrc552pidbuf[18];
u8 card_pydebuf[2];
u8 card_numberbuf[5];
u8 card_key0Abuf[6]={0xff,0xff,0xff,0xff,0xff,0xff};
u8 card_writebuf[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
u8 card_readbuf[18];
//MFRC522Ժ
void MFRC522Test(void)
{
u8 i,status,card_size;
//
status=MFRC522_Request(0x52, card_pydebuf); //Ѱ
//
if(status==0) //
{
status=MFRC522_Anticoll(card_numberbuf); //ײ
card_size=MFRC522_SelectTag(card_numberbuf); //ѡ
status=MFRC522_Auth(0x60, 4, card_key0Abuf, card_numberbuf); //鿨
status=MFRC522_Write(4, card_writebuf); //ддҪСģرǸĿ3
status=MFRC522_Read(4, card_readbuf); //
//MFRC522_Halt(); //ʹ״̬
//ʾ
printf("card_pydebuf:%x %x\r\n",card_pydebuf[0],card_pydebuf[1]);
//кʾһֽΪУ
printf("card_numberbuf:%x %x %x %x %x\r\n",card_numberbuf[0],card_numberbuf[1],card_numberbuf[2],card_numberbuf[3],card_numberbuf[4]);
//ʾλΪKbits
printf("card_size:%x Kbits\r\n",card_size);
//״̬ʾΪ0
printf("status:%x\r\n",status);
//һʾ
printf("card_readbuf:");
for(i=0;i<18;i++) //ʾ
{
printf("%x ",card_readbuf[i]);
}
printf("\r\n");
printf("================================\r\n\r\n");
PFout(8)=1;PFout(9)=0;delay_ms(80);
PFout(8)=0;PFout(9)=1;delay_ms(80);
PFout(8)=1;PFout(9)=0;delay_ms(80);
PFout(8)=0;PFout(9)=1;delay_ms(80);
}
}
int main(void)
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8|GPIO_Pin_9; //8 9
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; //ģʽ
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //ǿŵ
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //ŵٶΪ100MHz
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //ûʹڲ
GPIO_Init(GPIOF, &GPIO_InitStructure);
PFout(8)=0;
PFout(9)=1;
//1ʼ115200
usart1_init(115200);
printf("This is spi rc522 test\r\n");
MFRC522_Initializtion(); //ʼMFRC522
while(1)
{
MFRC522_Initializtion();
MFRC522Test();
delay_ms(1000);
}
}
void USART1_IRQHandler(void)
{
uint8_t d=0;
//־λ
if(SET == USART_GetITStatus(USART1,USART_IT_RXNE))
{
//
d=USART_ReceiveData(USART1);
if(d == 'a')PFout(9)=0;
if(d == 'A')PFout(9)=1;
//ձ־
USART_ClearITPendingBit(USART1,USART_IT_RXNE);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* checker.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mapandel <mapandel@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/04 12:47:12 by mapandel #+# #+# */
/* Updated: 2017/09/14 18:38:22 by mapandel ### ########.fr */
/* */
/* ************************************************************************** */
#include "checker.h"
static int del_t_checker(t_checker *ck)
{
ft_tabdel(&ck->a);
ft_tabdel(&ck->b);
ft_memdel((void**)&ck->flags);
ft_memdel((void**)&ck);
return (1);
}
static t_checker *init_t_checker(t_checker *ck)
{
if (!(ck = ft_memalloc(sizeof(t_checker)))
|| !(ck->flags = ft_memalloc(sizeof(t_checker_flags)))
|| !(ck->a = ft_tabnew(1000000))
|| !(ck->b = ft_tabnew(1000000)))
return (NULL);
ck->flags->l = 0;
ck->flags->s = 1;
ck->flags->v = 0;
ck->argnb = 1;
ck->rotation = 0;
ck->nbrotations = 0;
ck->fd = 0;
ck->error = 0;
return (ck);
}
static int main2(t_checker *ck)
{
ck->a = ft_tabrev_leakless(ck->a);
ck = checker_movements(ck);
if (ck->error == -1 && del_t_checker(ck))
return (checker_display_result(KO));
else if (ck->error == 1 && del_t_checker(ck))
return (checker_display_result(ERROR));
del_t_checker(ck);
return (checker_display_result(OK));
}
int main(int argc, char **argv)
{
t_checker *ck;
ck = NULL;
if (argc < 2)
return (checker_display_usage());
if (!(ck = init_t_checker(ck)) && del_t_checker(ck))
return (checker_display_result(ERROR));
ck = checker_parsing_flags(ck, argc, argv);
if (!(ck->a->len = (size_t)(argc - ck->argnb)))
ck->error = -1;
if (ck->error && del_t_checker(ck))
return (checker_display_result(ERROR));
if (ck->a->len == 1)
ck = checker_parsing_bash_arg(ck, argv);
else
ck = checker_parsing_integers(ck, argc, argv);
if (ck->error && del_t_checker(ck))
return (checker_display_result(ERROR));
checker_parsing_doubles(ck);
if (ck->error && del_t_checker(ck))
return (checker_display_result(ERROR));
return (main2(ck));
}
|
C
|
/*
* bitarraytest.c
* testing the bit array implementation
*
* @author Steve Hoffmann
* @email steve@bioinf.uni-leipzig.de
* @date 07/15/2007 02:12:32 AM CEST
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "basic-types.h"
#include "memory.h"
#include "bitArray.h"
int
main(int argc, char**argv) {
bitarray a;
a = initbitarray(NULL, 10);
dumpbitarray(a, 10);
setbitarray(a, 10, 0);
dumpbitarray(a, 10);
setbit(a, 5, 1);
dumpbitarray(a, 10);
setbit(a, 9, 1);
dumpbitarray(a, 10);
return 0;
}
|
C
|
#include <stdio.h>
#include "arraypermutations_Permutations.h"
void permute(int *a, int size, int n){
if (size==1) {
//int number = sizeof(a)/sizeof(a[0]);
for (int i=0; i<n; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
else{
for (int i=0; i<size; i++) {
permute(a, size-1, n);
if (size%2==0) {
int temp = a[i];
a[i] = a[size-1];
a[size-1] = temp;
}
else{
int temp = a[0];
a[0] = a[size-1];
a[size-1] = temp;
}
}
}
}
JNIEXPORT void JNICALL Java_arraypermutations_Permutations_call(JNIEnv *env, jobject cl, jintArray a, jint size, jint n) {
permute((int *) (*env)->GetIntArrayElements(env, a, 0), (int) size, (int) n);
}
|
C
|
/*
Environment Variables via Context.
*/
TK_EnvContext *tk_envctx_free;
TK_EnvContext *TK_EnvCtx_AllocContext(void)
{
TK_EnvContext *tmp;
tmp=tk_envctx_free;
if(tmp)
{
tk_envctx_free=tmp->next;
memset(tmp, 0, sizeof(TK_EnvContext));
return(tmp);
}
tmp=tk_malloc(sizeof(TK_EnvContext));
memset(tmp, 0, sizeof(TK_EnvContext));
return(tmp);
}
void TK_EnvCtx_FreeContext(TK_EnvContext *ctx)
{
ctx->next=tk_envctx_free;
tk_envctx_free=ctx;
}
TK_EnvContext *TK_EnvCtx_CloneContext(TK_EnvContext *ctx)
{
TK_EnvContext *tmp;
int i, j, k;
tmp=TK_EnvCtx_AllocContext();
if(!ctx)
{
tk_dbg_printf("TK_EnvCtx_CloneContext: Clone Null Context\n");
return(tmp);
}
for(i=0; i<ctx->nenvlst; i++)
{
TK_EnvCtx_SetEnvVar(tmp,
ctx->envlst_var[i],
ctx->envlst_val[i]);
}
tk_dbg_printf("TK_EnvCtx_CloneContext: Cwd=%s\n", ctx->cwd);
TK_EnvCtx_SetCwd(tmp, ctx->cwd);
return(tmp);
}
char *TK_EnvCtx_SetEnvVarI_StrDup(TK_EnvContext *ctx, char *val)
{
char *ct;
int l;
if(!(ctx->envbufs))
{
ctx->envbufs=tk_malloc(4096);
ctx->envbufe=ctx->envbufs+4096;
ctx->envbufc=ctx->envbufs;
}
l=strlen(val);
if((ctx->envbufc+l)>=ctx->envbufe)
return(NULL);
ct=ctx->envbufc;
ctx->envbufc=ct+l+1;
strcpy(ct, val);
return(ct);
}
int TK_EnvCtx_RepackEnvbuf(TK_EnvContext *ctx)
{
char *oldenv;
char *cn0, *cv0, *cn1, *cv1;
int i, j, k;
oldenv=ctx->envbufs;
k=ctx->envbufe-ctx->envbufs;
k=k+(k>>1);
ctx->envbufs=tk_malloc(k);
ctx->envbufe=ctx->envbufs+k;
ctx->envbufc=ctx->envbufs;
for(i=0; i<ctx->nenvlst; i++)
{
cn0=ctx->envlst_var[i];
cv0=ctx->envlst_val[i];
cn1=TK_EnvCtx_SetEnvVarI_StrDup(ctx, cn0);
cv1=TK_EnvCtx_SetEnvVarI_StrDup(ctx, cv0);
ctx->envlst_var[i]=cn1;
ctx->envlst_val[i]=cv1;
}
tk_free(oldenv);
return(0);
}
int TK_EnvCtx_GetEnvVarIdx(TK_EnvContext *ctx, int idx,
char *bufn, char *bufv, int szn, int szv)
{
int i, j, k;
if(idx<0)
return(-1);
if(idx>=ctx->nenvlst)
return(-1);
strcpy(bufn, ctx->envlst_var[idx]);
strcpy(bufv, ctx->envlst_val[idx]);
return(1);
#if 0
for(i=0; i<ctx->nenvlst; i++)
{
if(!strcmp(ctx->envlst_var[i], varn))
{
strncpy(bufv, ctx->envlst_val[i], sz);
return(1);
}
}
#endif
return(-1);
}
int TK_EnvCtx_GetEnvVarI(TK_EnvContext *ctx, char *varn, char *bufv, int sz)
{
int i, j, k;
for(i=0; i<ctx->nenvlst; i++)
{
if(!strcmp(ctx->envlst_var[i], varn))
{
strncpy(bufv, ctx->envlst_val[i], sz);
return(1);
}
}
return(-1);
}
int TK_EnvCtx_SetEnvVarI(TK_EnvContext *ctx, char *varn, char *varv)
{
char *cn1, *cv1;
int i, j, k;
tk_dbg_printf("TK_EnvCtx_SetEnvVarI: %s=%s\n", varn, varv);
if(!ctx->envbufs)
{
ctx->envbufs=tk_malloc(65536);
ctx->envbufe=ctx->envbufs+65536;
ctx->envbufc=ctx->envbufs;
ctx->envlst_var=tk_malloc(256*sizeof(char *));
ctx->envlst_val=tk_malloc(256*sizeof(char *));
ctx->nenvlst=0;
ctx->menvlst=256;
}
for(i=0; i<ctx->nenvlst; i++)
{
if(!strcmp(ctx->envlst_var[i], varn))
{
cv1=TK_EnvCtx_SetEnvVarI_StrDup(ctx, varv);
if(cv1)
{
ctx->envlst_val[i]=cv1;
return(1);
}
break;
}
}
if(i>=ctx->nenvlst)
{
if((ctx->nenvlst+1)>=ctx->menvlst)
{
k=ctx->menvlst; k=k+(k>>1);
ctx->envlst_var=tk_realloc(
ctx->envlst_var, k*sizeof(char *));
ctx->envlst_val=tk_realloc(
ctx->envlst_val, k*sizeof(char *));
ctx->menvlst=k;
}
cn1=TK_EnvCtx_SetEnvVarI_StrDup(ctx, varn);
cv1=TK_EnvCtx_SetEnvVarI_StrDup(ctx, varv);
if(cn1 && cv1)
{
i=ctx->nenvlst++;
ctx->envlst_var[i]=cn1;
ctx->envlst_val[i]=cv1;
return(1);
}
}
TK_EnvCtx_RepackEnvbuf(ctx);
TK_EnvCtx_SetEnvVarI(ctx, varn, varv);
return(1);
}
int TK_EnvCtx_SetCwd(TK_EnvContext *ctx, char *cwd)
{
if(cwd)
ctx->cwd=TKMM_LVA_Strdup(cwd);
else
ctx->cwd=NULL;
}
char *TK_EnvCtx_GetCwd(TK_EnvContext *ctx, char *buf, int sz)
{
char *cwd;
int l;
// tk_dbg_printf("TK_EnvCtx_GetCwd env=%p\n", ctx);
cwd=NULL;
if(ctx)
{ cwd=ctx->cwd; }
if(!cwd)
{
// tk_dbg_printf("TK_EnvCtx_GetCwd env=%p, CWD was NULL\n", ctx);
cwd="/";
}else
{
// tk_dbg_printf("TK_EnvCtx_GetCwd env=%p, CWD=%s (%p)\n", ctx, cwd, cwd);
}
l=strlen(cwd);
if(!buf)
{
if(!sz)
sz=l+1;
if(l>=sz)
return(NULL);
buf=malloc(sz);
strcpy(buf, cwd);
return(buf);
}
if(strlen(cwd)>=sz)
return(NULL);
strcpy(buf, cwd);
return(buf);
}
int TK_EnvCtx_GetPathList(TK_EnvContext *ctx, char ***rlst, int *rnlst)
{
*rlst=ctx->pathlst;
*rnlst=ctx->npathlst;
return(1);
}
int TK_EnvCtx_SetPath(TK_EnvContext *ctx, char *path)
{
// char tb[1024];
char **tba;
int ntb;
char *cs, *ct, *csb, *ctb;
if(!ctx->pathbuf)
ctx->pathbuf=malloc(65536);
if(!ctx->pathlst)
ctx->pathlst=malloc(256*sizeof(char *));
tba=ctx->pathlst;
ctb=ctx->pathbuf;
cs=path; ct=ctb;
ntb=0;
while(*cs)
{
if(*cs==':')
{
cs++;
*ct++=0;
tba[ntb]=ctb;
ntb++;
ctb=ct;
continue;
}
*ct++=*cs++;
}
*ct=0;
if(*ctb)
{
tba[ntb]=ctb;
ntb++;
ctb=ct;
}
ctx->npathlst=ntb;
return(0);
}
int TK_EnvCtx_SplitVar(char *str, char *bvar, char **rval)
{
char *cs, *ct;
cs=str;
ct=bvar;
while(*cs && (*cs!='='))
{ *ct++=*cs++; }
*ct=0;
if(*cs=='=')
cs++;
*rval=cs;
return(0);
}
int TK_EnvCtx_GetEnvVar(TK_EnvContext *ctx, char *varn, char *bufv, int sz)
{
if(!strcmp(varn, "CWD"))
{
TK_EnvCtx_GetCwd(ctx, bufv, sz);
return(1);
}
if(!strcmp(varn, "PATH"))
{
TK_EnvCtx_GetEnvVarI(ctx, varn, bufv, sz);
return(1);
}
TK_EnvCtx_GetEnvVarI(ctx, varn, bufv, sz);
return(1);
}
int TK_EnvCtx_SetEnvVar(TK_EnvContext *ctx, char *varn, char *varv)
{
if(!strcmp(varn, "CWD"))
{
TK_EnvCtx_SetCwd(ctx, varv);
return(1);
}
if(!strcmp(varn, "PATH"))
{
TK_EnvCtx_SetPath(ctx, varv);
TK_EnvCtx_SetEnvVarI(ctx, varn, varv);
return(1);
}
TK_EnvCtx_SetEnvVarI(ctx, varn, varv);
}
int TK_EnvCtx_UpdateForSet(TK_EnvContext *ctx, char *estr)
{
char tbn[64];
char *tbv;
tbv=NULL;
TK_EnvCtx_SplitVar(estr, tbn, &tbv);
TK_EnvCtx_SetEnvVar(ctx, tbn, tbv);
return(0);
}
int TK_EnvCtx_GetEnvListBuffer(TK_EnvContext *ctx, void *buf, int szbuf)
{
char **env;
char *ct;
int menv;
env=buf;
menv=ctx->nenvlst;
ct=((char *)buf)+(menv+2)*sizeof(char *);
return(0);
}
int TK_EnvCtx_InitForEnv(TK_EnvContext *ctx, char **envv)
{
char **csa;
csa=envv;
while(*csa)
{
TK_EnvCtx_UpdateForSet(ctx, *csa++);
}
return(0);
}
|
C
|
/*estrategia de solucao
fazer uma função de busca em largura
em que se armazene 3 tempos minimos para chegar
na casa, um quando t %3 =0, t%3=1, t%3=2
Nessa busca em largura as arestas são dependentes do tempo (variavel t), podendo estar "abertas" ou "fechadas".
Após chegar na rotatória final, a busca em profundidade para, retornando o valor do tempo que demora para chegar
caso ela já tenha passado por todas as rotatórias possíveis para cada um dos t (==0, ==1, ==2) e não chegue na rotatória final, ela retorna -1
*/
#include <stdio.h>
#define max 502
int rot[max][max][3], foi[max][3], tempo[max][3], proximo[3*max], tempoaux[3*max];
int BFS(int ini, int n, int fim){ //vertice de inicio, quantidade de vertices, vertice de fim
int i, time, K, pont, b, t;
time=0;
t=2; //como ele sai dessa rotatoria no tempo %3 = 0, ele chega nela em um tempo %3 =2
foi[ini][t]=1;
tempo[ini][t]=0;
proximo[0]=ini;
tempoaux[0]=0;
pont=0;
b=0;
while( (!foi[fim][0]) && (!foi[fim][1]) && (!foi[fim][2]) && (b<=pont)){
K=proximo[b];
time = tempoaux[b++];
t=(time)%3;
/*//debug{
printf("K = %d ", K);
printf("b = %d ", b);
printf("time =%d ", time);
printf("pont= %d ", pont);
printf("t= %d \n", t);
// */ // }debug
for (i=0;i<n; i++){
if (!foi[i][t]){
if(rot[K][i][t]){
proximo[++pont]=i;
tempo[i][t]=time+1;
tempoaux[pont]=time+1;
foi[i][t]=1;
}
}
}
}
if(foi[fim][0])
return tempo[fim][0];
else if(foi[fim][1])
return tempo[fim][1];
else if(foi[fim][2])
return tempo[fim][2];
else return -1;
}
int main(){
int N,E,S,M,i,j,k, A,B,t;
scanf("%d %d %d %d", &N, &E, &S, &M);
//inicializando vetores e matrizes
for(i=0;i<N;i++){
for(k=0;k<3;k++){
foi[i][k]=0;
tempo[i][k]=0;
}
for(j=0;j<N;j++){
for(k=0;k<3;k++){
rot[i][j][k]=0;
}
}
}
//inicializados
//ler as arestas e colocar a dependencia temporal
for(i=0;i<M;i++){
scanf("%d %d %d", &A, &B, &t);
if (t==0){
rot[A][B][1]=rot[A][B][2]=1;
//rot[B][A][1]=rot[B][A][2]=1; //as ruas sao de mao unica
}else{
rot[A][B][0]=1;//rot[B][A][0]=1; //as ruas sao de mao unica
}
}
int x;
x=BFS(E, N, S);
if (x!=-1)
printf("%d",x );
else
printf("*");
//printf("passou");
return 0;
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <math.h>
//Global vars
int matrix1[25][25], matrix2[25][25], result[25][25];
int r1, c1, r2, c2, i, j, k; //throughout the program i and j are variables reserved for use in for loops
int initSetup()
{
printf("Enter the no. of rows in the first matrix and press the return key then proceed to enter the no. of coloumns \n");
scanf("%d", &r1);
printf("x\n");
scanf("%d", &c1);
printf("Enter the no. of rows in the second matrix and press the return key then proceed to enter the no. of coloumns \n");
scanf("%d", &r2);
printf("x\n");
scanf("%d", &c2);
}
int handleErr()
{
printf("Error! the matrices cannot be multiplied\n\nEnter new values\n");
initSetup();
}
int checkForErr()
{
if (c1 != r2)
{
return true;
}
}
getValues()
{
printf("\nEnter elements a[i][j] of the first matrix(%dx%d)\n", r1, c1);
for(i = 1; i <= r1; i++)
{
for(j = 1; j <= c1; j++)
{
// taking a[i][j] as general element of Ist matrix
printf("Element a[%d][%d]= ", i, j);
scanf("%d",&matrix1[i][j]);
}
}
printf("\nEnter elements b[i][j] of the second matrix(%dx%d)\n", r2, c2);
for(i = 1; i <= r2; i++)
{
for(j = 1; j <= c2; j++)
{
// taking b[i][j] as general element of IInd matrix
printf("Element b[%d][%d]= ", i, j);
scanf("%d",&matrix2[i][j]);
}
}
}
multiplyMatrices()
{
int sum=0;
for(i=1;i<=r1;i++){
for(j=1;j<=c2;j++){
for(k=1;k<=r2;k++){
sum+=matrix1[i][k]*matrix2[k][j];
}
result[i][j]=sum;
sum=0;
}
}
}
printResult()
{
for(i = 1; i <= c1; i++)
{
for(j = 1; j <= c2; j++)
{
printf("%d\t", result[i][j]);
}
printf("\n");
}
}
int main()
{
initSetup();
if (checkForErr() == true)
{
handleErr();
};
getValues();
multiplyMatrices();
printResult();
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ffrimpon <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/08 16:42:16 by ffrimpon #+# #+# */
/* Updated: 2016/02/10 12:53:56 by ffrimpon ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_get_right_size(char *str)
{
int i;
i = 0;
while (str[i] != '\n' && str[i] != '\0')
{
i++;
}
return (i);
}
static char *ft_get_position(char **line, char *str)
{
int i;
i = ft_get_right_size(str);
if (str[i] == '\0')
{
*line = ft_strdup(str);
return (NULL);
}
if (str[i] == '\n')
{
*line = ft_strndup(str, i);
str = ft_strchr(str, '\n');
}
return (str);
}
int get_next_line(const int fd, char **line)
{
static char *str;
char buffer[BUFF_SIZE + 1];
int ret;
if (fd < 0 || line == NULL)
return (-1);
*line = ft_strnew(1);
if (str != NULL)
str = ft_get_position(line, str + 1);
if (str == NULL)
{
while ((!(str = ft_strchr(*line, '\n'))) &&
(ret = read(fd, buffer, BUFF_SIZE)))
{
if (ret < 0)
return (-1);
buffer[ret] = '\0';
*line = ft_strjoin(*line, buffer);
}
if (ret == 0 && *line[0] == '\0')
return (0);
*line = ft_strndup(*line, ft_get_right_size(*line));
}
return (1);
}
|
C
|
//
// Created by Kushagra Kandpal on 03-07-2021.
//
/*
* Link to Problem : https://binarysearch.com/problems/Swap-Kth-Node-Values
*/
#ifndef DS_LLSWAPNODE_MED_H
#define DS_LLSWAPNODE_MED_H
#endif //DS_LLSWAPNODE_MED_H
#include "../DSAImplementation/linkedlists.h"
LLNode* solve(LLNode* node, int k) {
int size = 0;
LLNode* temp = node;
while(temp != 0) {temp = temp->next; size++;}
temp = node;
size-=1;
if (size-k != k){
for (int i = 0; i != k; i++) temp = temp -> next;
int temp1 = temp->val;
temp = node;
for (int i = 0; i != size-k; i++) temp = temp -> next;
int temp2 = temp-> val;
temp->val = temp1;
temp = node;
for (int i = 0; i != k; i++) temp = temp->next;
temp->val= temp2;
}
return node;
}
|
C
|
/**
* MPTCP Socket API Test App
* File Sender with Subflows Info (Client)
*
* @date : 2021-05-25(Thu)
* @author : Ji-Hun(INSLAB)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <time.h>
#include "../header/mptcp.h"
#define NIC_NUMBER 3 // 사용하는 NIC 개수 지정 (ex. 만약 사용중인 NIC가 eth0, wlan0, wlan1 일 시 -> 3)
void print_subflow_info(struct mptcp_info);
int get_fsize(FILE*);
/**
* 기존의 TCP Client는 { socket() -> connect() -> recv(), send() -> close() }순서로 흘러간다.
* 여기서 TCP Socket을 MPTCP Socket으로 설정하기 위해서는 socket()과 connect()사이에 setsockopt()을 사용한다.
**/
int main(int argc, char** argv)
{
char* ADDR;
int PORT;
char* FILE_PATH;
int sock;
struct sockaddr_in addr;
int ret;
FILE* file;
char send_buff[1024] = { '\0', };
int fsize = 0, nsize = 0;
int enable = 1;
int val = MPTCP_INFO_FLAG_SAVE_MASTER;
char *scheduler = "roundrobin";
struct mptcp_info minfo;
struct mptcp_meta_info meta_info;
struct tcp_info initial;
struct tcp_info others[NIC_NUMBER];
struct mptcp_sub_info others_info[NIC_NUMBER];
socklen_t len;
clock_t start_t, end_t;
/* mptcp subflow의 정보를 반환받기 위한 초기화 작업 */
minfo.tcp_info_len = sizeof(struct tcp_info);
minfo.sub_len = sizeof(others);
minfo.meta_len = sizeof(struct mptcp_meta_info);
minfo.meta_info = &meta_info;
minfo.initial = &initial;
minfo.subflows = others;
minfo.sub_info_len = sizeof(struct mptcp_sub_info);
minfo.total_sub_info_len = sizeof(others_info);
minfo.subflow_info = others_info;
len = sizeof(minfo);
if(argc != 4){
fprintf(stderr, "usage: %s [host_address] [port_number] [file_path]\n", argv[0]);
return -1;
}
ADDR = argv[1];
PORT = atoi(argv[2]);
FILE_PATH = argv[3];
/* create socket */
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0){
perror("[client] socket() ");
return -1;
}
/* setsockopt()함수와 MPTCP_ENABLED(=42)상수를 사용하여 MPTCP Socket으로 Setup */
ret = setsockopt(sock, SOL_TCP, MPTCP_ENABLED, &enable, sizeof(int));
if(ret < 0){
perror("[client] setsockopt(MPTCP_ENABLED) ");
return -1;
}
/* setsockopt()함수와 MPTCP_SCHEDULER(=43)상수를 사용하여 패킷스케줄러를 라운드로빈으로 Setup */
ret = setsockopt(sock, SOL_TCP, MPTCP_SCHEDULER, scheduler, strlen(scheduler));
if(ret < 0){
perror("[client] setsockopt(MPTCP_SCHEDULER) ");
return -1;
}
/* setsockopt()함수와 MPTCP_INFO(=45)상수와 MPTCP_INFO_FLAG_SAVE_MASTER 옵션 사용으로 초기 Subflow info 유지시키기 */
ret = setsockopt(sock, IPPROTO_TCP, MPTCP_INFO, &val, sizeof(val));
if(ret < 0){
perror("[client] setsockopt(MPTCP_INFO) ");
return -1;
}
memset(&addr, 0x00, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ADDR);
addr.sin_port = htons(PORT);
ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
if(ret < 0){
perror("[client] connect() ");
return -1;
}
printf("[client] connected\n");
file = fopen(FILE_PATH, "rb");
if(file == NULL){
perror("[client] fopen() ");
return -1;
}
fsize = get_fsize(file);
start_t = clock();
printf("[client] sending file...(%s)\n", FILE_PATH);
while(nsize!=fsize){
int fpsize = fread(send_buff, 1, 1024, file);
nsize += fpsize;
send(sock, send_buff, fpsize, 0);
/* 3초간격 getsockopt(MPTCP_INFO) */
end_t = clock();
if( 3.0 < (float)(end_t - start_t)/CLOCKS_PER_SEC){
start_t = clock();
getsockopt(sock, IPPROTO_TCP, MPTCP_INFO, &minfo, &len);
print_subflow_info(minfo); // Subflow 정보 출력
}
}
fclose(file);
close(sock);
return 0;
}
void print_subflow_info(struct mptcp_info minfo)
{
int subflows_info_len = minfo.total_sub_info_len;
int subflows_number = subflows_info_len / sizeof(struct mptcp_sub_info);
int i;
printf("-----------------------\n");
printf("[subflows number] %d\n", subflows_number);
for(i=0; i<subflows_number; i++){
printf("[subflow %d] %s:%d ", i, inet_ntoa(minfo.subflow_info[i].src_v4.sin_addr), ntohs(minfo.subflow_info[i].src_v4.sin_port));
printf("-> %s:%d", inet_ntoa(minfo.subflow_info[i].dst_v4.sin_addr), ntohs(minfo.subflow_info[i].dst_v4.sin_port));
printf(" { rto %d, ato %d , rtt %d, snd_mss %d, rcv_mss %d, total_retrans %d }\n",
minfo.subflows[i].tcpi_rto,
minfo.subflows[i].tcpi_ato,
minfo.subflows[i].tcpi_rtt,
minfo.subflows[i].tcpi_snd_mss,
minfo.subflows[i].tcpi_rcv_mss,
minfo.subflows[i].tcpi_total_retrans );
}
}
int get_fsize(FILE* file)
{
int fsize;
fseek(file, 0, SEEK_END);
fsize=ftell(file);
fseek(file, 0, SEEK_SET);
return fsize;
}
|
C
|
#ifndef _createTensor_h____
#define _createTensor_h____
// The function "createTensor" helps in allocating spaces to tensors in mempool.
// It starts with storing the "TensorDescriptor" in the mempool followed an empty
// space in mempool required to fill in the tensor.
void fillTensorDescriptor(Tensor *t);
//This method Takes input from user about the tensor's decription.
void printTensorDescriptor(Tensor *t);
// Prints the tensor descriptor.
int createTensor(Tensor *t,MemPool *mp, MemPoolRequest *mp_req,MemPoolResponse *mp_resp);
// Allocate spaces in the mempool for the tensor according to the description provided.
// Returns '0' if operation is successful, else '1'.
#endif
|
C
|
#include "mesh_bridge_utils.h"
/* INCLUDES */
// C STANDARD
#include <stdint.h> // uint16_t
// NRF
#include "boards.h" // bsp_board_led_off, bsp_board_led_on
// LUOS
#include "luos_utils.h" // LUOS_ASSERT
#include "routing_table.h" // routing_table_t, entry_mode_t
// CUSTOM
#include "mesh_bridge.h" // MESH_BRIDGE_MOD
/* STATIC VARIABLES & CONSTANTS */
// LED toggled to match provisioning/configuration state.
static const uint32_t DEFAULT_INIT_LED = 0;
// LED toggled to match Ext-RTB procedure state.
static const uint32_t DEFAULT_EXT_RTB_LED = 1;
/* STATIC FUNCTIONS */
// Returns the number of containers in the given node RTB entry.
static uint16_t find_nb_containers(routing_table_t* node_entry);
uint16_t find_mesh_bridge_container_id(routing_table_t* routing_table,
uint16_t nb_entries)
{
// Check parameter.
LUOS_ASSERT(routing_table != NULL);
for (uint16_t entry_idx = 0; entry_idx < nb_entries; entry_idx++)
{
routing_table_t entry = routing_table[entry_idx];
if (entry.mode == CONTAINER && entry.type == MESH_BRIDGE_MOD)
{
return entry.id;
}
}
// Not found.
return 0;
}
uint16_t find_mesh_bridge_node_id(routing_table_t* routing_table,
uint16_t nb_entries)
{
// Check parameter.
LUOS_ASSERT(routing_table != NULL);
for (uint16_t entry_idx = 0; entry_idx < nb_entries; entry_idx++)
{
routing_table_t* entry = routing_table + entry_idx;
if (entry->mode != NODE)
{
// Only look in node entries.
continue;
}
// Number of containers in the node entry.
uint16_t nb_containers = find_nb_containers(entry);
// Find Mesh Bridge ID in node.
uint16_t mesh_bridge_id;
mesh_bridge_id = find_mesh_bridge_container_id(entry,
nb_containers);
if (mesh_bridge_id != 0)
{
// Mesh Bridge container was found in the node.
return entry->node_id;
}
}
// Not found.
return 0;
}
__attribute__((weak)) void indicate_provisioning_begin(void)
{
bsp_board_led_on(DEFAULT_INIT_LED);
}
__attribute__((weak)) void indicate_configuration_end(void)
{
bsp_board_led_off(DEFAULT_INIT_LED);
}
__attribute__((weak)) void indicate_ext_rtb_engaged(void)
{
bsp_board_led_on(DEFAULT_EXT_RTB_LED);
}
__attribute__((weak)) void indicate_ext_rtb_complete(void)
{
bsp_board_led_off(DEFAULT_EXT_RTB_LED);
}
static uint16_t find_nb_containers(routing_table_t* node_entry)
{
// Check parameter.
LUOS_ASSERT(node_entry != NULL);
uint16_t nb_containers = 0;
routing_table_t* first_container_entry = node_entry + 1;
while (first_container_entry[nb_containers].mode == CONTAINER)
{
nb_containers++;
}
return nb_containers;
}
|
C
|
#include "json.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
static JSON_VALUE*
json_alloc_value(JSON_TYPE type)
{
JSON_VALUE* v = (JSON_VALUE*) malloc(sizeof(JSON_VALUE));
memset(v, 0, sizeof(JSON_VALUE));
v->type = type;
return v;
}
typedef struct JSON_BUFFER {
char* buf;
size_t n;
size_t alloced;
} JSON_BUFFER;
static void
json_append(JSON_BUFFER* buf, char ch)
{
if(buf->n >= buf->alloced) {
if(buf->alloced > 0)
buf->alloced *= 2;
else
buf->alloced = 8;
buf->buf = realloc(buf->buf, buf->alloced);
}
buf->buf[buf->n] = ch;
buf->n++;
}
static off_t
json_create_string(const char* input, off_t off, char** p_str)
{
JSON_BUFFER buf = { 0 };
off++; /* skip quot */
while(input[off] != '\"') {
if(input[off] == '\\') {
off++;
switch(input[off]) {
case 'n': json_append(&buf, '\n'); break;
case 'r': json_append(&buf, '\r'); break;
case 't': json_append(&buf, '\t'); break;
case '\"': json_append(&buf, '\"'); break;
case '\\': json_append(&buf, '\\'); break;
}
off++;
} else {
json_append(&buf, input[off]);
off++;
}
}
json_append(&buf, '\0');
off++; /* skip quot */
*p_str = buf.buf;
return off;
}
static off_t
json_create_unqoted_string(const char* input, off_t off, char** p_str)
{
JSON_BUFFER buf = { 0 };
while(strchr(" \t\r\n,]}", input[off]) == NULL) {
json_append(&buf, input[off]);
off++;
}
json_append(&buf, '\0');
*p_str = buf.buf;
return off;
}
static void
json_add_value(JSON_VALUE* parent, char* key, JSON_VALUE* v)
{
if(key != NULL && parent->type == JSON_OBJECT) {
if(parent->data.obj.n >= parent->data.obj.alloced) {
if(parent->data.obj.alloced > 0)
parent->data.obj.alloced *= 2;
else
parent->data.obj.alloced = 4;
parent->data.obj.keys = realloc(parent->data.obj.keys, sizeof(char*) * parent->data.obj.alloced);
parent->data.obj.values = realloc(parent->data.obj.values, sizeof(JSON_VALUE) * parent->data.obj.alloced);
}
parent->data.obj.keys[parent->data.obj.n] = key;
parent->data.obj.values[parent->data.obj.n] = v;
parent->data.obj.n++;
} else if(key == NULL && parent->type == JSON_ARRAY) {
if(parent->data.array.n >= parent->data.array.alloced) {
if(parent->data.array.alloced > 0)
parent->data.array.alloced *= 2;
else
parent->data.array.alloced = 4;
parent->data.array.values = realloc(parent->data.array.values, sizeof(JSON_VALUE) * parent->data.array.alloced);
}
parent->data.array.values[parent->data.array.n] = v;
parent->data.array.n++;
}
}
JSON_VALUE*
json_parse(const char* input)
{
off_t off = 0;
size_t len;
JSON_VALUE* stack[8];
int stack_top = 0;
len = strlen(input);
while(off < len) {
char* key = NULL;
JSON_VALUE* v = NULL;
after_key:
while(strchr(" \t\r\n", input[off]) != NULL)
off++;
switch(input[off]) {
case '{':
v = json_alloc_value(JSON_OBJECT);
off++;
break;
case '[':
v = json_alloc_value(JSON_ARRAY);
off++;
break;
case 'n':
v = json_alloc_value(JSON_NULL);
off += strlen("null");
break;
case 'f':
v = json_alloc_value(JSON_FALSE);
off += strlen("false");
break;
case 't':
v = json_alloc_value(JSON_TRUE);
off += strlen("true");
break;
case ']':
case '}':
off++;
stack_top--;
break;
case ',':
off++;
break;
case '"':
{
char* str;
off = json_create_string(input, off, &str);
while(strchr(" \t\r\n", input[off]) != NULL)
off++;
if(input[off] == ':') {
off++;
key = str;
goto after_key;
} else {
v = json_alloc_value(JSON_STRING);
v->data.str = str;
}
break;
}
default:
{
char* str;
off = json_create_unqoted_string(input, off, &str);
v = json_alloc_value(JSON_STRING);
v->data.str = str;
break;
}
}
while(strchr(" \t\r\n", input[off]) != NULL)
off++;
if(v != NULL) {
if(stack_top > 0)
json_add_value(stack[stack_top-1], key, v);
if(v->type == JSON_OBJECT || v->type == JSON_ARRAY) {
stack[stack_top] = v;
stack_top++;
}
}
}
return stack[0];
}
void
json_free(JSON_VALUE* tree)
{
unsigned i;
switch(tree->type) {
case JSON_STRING:
free(tree->data.str);
break;
case JSON_ARRAY:
for(i = 0; i < tree->data.array.n; i++)
json_free(tree->data.array.values[i]);
free(tree->data.array.values);
break;
case JSON_OBJECT:
for(i = 0; i < tree->data.obj.n; i++) {
free(tree->data.obj.keys[i]);
json_free(tree->data.obj.values[i]);
}
free(tree->data.obj.keys);
free(tree->data.obj.values);
break;
default:
/* noop */
break;
}
free(tree);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_digit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: twitting <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/11 15:26:02 by twitting #+# #+# */
/* Updated: 2018/12/15 15:58:39 by twitting ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int ft_digitalyzer(char *str, int fig[27][9], int fignum)
{
int x;
int y;
int count;
count = 0;
y = 0;
x = 0;
while (x + y * 5 < 20)
{
if (x == 4)
{
x = 0;
y++;
}
if (str[x + y * 5] == '#')
{
if (count > 7)
return (0);
fig[fignum][count] = y;
fig[fignum][count + 1] = x;
count += 2;
}
x++;
}
return (1);
}
void ft_tostart(int fig[27][9], int fignum)
{
while (fig[fignum][0] > 0)
{
fig[fignum][0]--;
fig[fignum][2]--;
fig[fignum][4]--;
fig[fignum][6]--;
}
while (fig[fignum][1] > 0)
{
fig[fignum][1]--;
fig[fignum][3]--;
fig[fignum][5]--;
fig[fignum][7]--;
}
fig[fignum][8] = fignum + 65;
}
int ft_digit(int fd, int fig[27][9])
{
ssize_t readed;
char buff[21];
int fignum;
int i;
fignum = 0;
while (fignum < 27)
fig[fignum++][8] = 0;
fignum = 0;
while ((readed = read(fd, buff, 21)) > 0)
{
i = -1;
while (++i < 20)
{
if (i != 4 && i != 9 && i != 14 && i != 19 &&
buff[i] != '.' && buff[i] != '#')
return (0);
}
if (!(ft_digitalyzer(buff, fig, fignum)))
return (0);
ft_tostart(fig, fignum);
fignum++;
}
return (1);
}
|
C
|
/* Doubly-linked list macros */
#ifndef _Iqueue
#define _Iqueue 1
#include "config.h"
/* Use this as first member of a structure to make it into a doubly linked
* list node.
*/
#define QITEM(type) type *next, *prev
/* Use this to make the base node of a doubly-linked list. Or if the item
* making up the structure is small enough, just use the structure itself */
#define QBASE(type) struct { QITEM(type); }
struct _qnode { QITEM(struct _qnode); };
extern struct _qnode *_queue, *_item, *_last;
#define IZQUE(item) \
( \
_queue=(void *)(item), \
(void *)(_queue->next=_queue->prev=_queue) \
)
#define DEQUE(item) \
( \
_queue=(void *)(item), \
_queue->prev->next=_queue->next, \
_queue->next->prev=_queue->prev, \
(void *)_queue \
)
#define QEMPTY(item) \
( \
_queue=(void *)(item), \
_queue==_queue->next \
)
#define ENQUEF(queue,item) \
( \
_item=(void *)(item), \
_queue=(void *)(queue), \
_item->next=_queue->next, \
_item->prev=_queue, \
_queue->next->prev=_item, \
_queue->next=_item, \
(void *)_item \
)
#define ENQUEB(queue,item) \
( \
_item=(void *)(item), \
_queue=(void *)(queue), \
_item->next=_queue, \
_item->prev=_queue->prev, \
_queue->prev->next=_item, \
_queue->prev=_item, \
(void *)_item \
)
#define PROMOTE(queue,item) ENQUEF(queue,DEQUE(item))
#define DEMOTE(queue,item) ENQUEB(queue,DEQUE(item))
#define SPLICEF(queue,chain) \
( \
_item=(void *)(chain), \
_last=_item->prev, \
_queue=(void *)(queue), \
_last->next=_queue->next, \
_item->prev=_queue, \
_queue->next->prev=_last, \
_queue->next=_item, \
(void *)_item \
)
#define SPLICEB(queue,chain) \
( \
_item=(void *)(chain), \
_last=_item->prev, \
_queue=(void *)(queue), \
_last->next=_queue, \
_item->prev=_queue->prev, \
_queue->prev->next=_item, \
_queue->prev=_last, \
(void *)_item \
)
#define SNIP(first,last) \
( \
_item=(void *)(first), \
_last=(void *)(last), \
_last->next->prev=_item->prev, \
_item->prev->next=_last->next, \
_item->prev=_last, \
_last->next=_item, \
(void *)_item \
)
/* Doubly linked list database */
typedef struct link LINK;
struct link { QITEM(LINK); void *data; };
void *alitem();
void fritem();
void izque();
LINK *newque();
LINK *enquef();
LINK *enqueb();
int qempty();
void *deque();
LINK *qfind();
int qfindn();
LINK *qnth();
int qno();
LINK *splicef();
LINK *spliceb();
LINK *snip();
#endif
|
C
|
/**************************************************************************
* Author : RebelIce 杨俊逸
* Email : yangrebelice@gmail.com
* Github : github.com/rebelice
* ************************************************************************/
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
/* We have implemented execl().
* You need to implement the other five */
pid_t pid;
char *arg[4];
void use_execl()
{
if ((pid = fork()) < 0)
{
printf("Fork error!\n");
exit(0);
}
else if (pid == 0)
{
printf("exec by execl() function:\n");
execl(arg[0], arg[1], arg[2], arg[3], arg[4]);
exit(0);
}
}
void use_execlp()
{
if ((pid = fork()) < 0)
{
printf("Fork error!\n");
exit(0);
}
else if (pid == 0)
{
printf("exec by execlp() function:\n");
/*TODO: use execlp() function */
exit(0);
}
}
void use_execle(char *env[])
{
/* Use "env" like execle(a, b, c, ... , env); */
if ((pid = fork()) < 0)
{
printf("Fork error!\n");
exit(0);
}
else if (pid == 0)
{
printf("exec by execle() function:\n");
/*TODO: use execle() function */
exit(0);
}
}
void use_execv()
{
if ((pid = fork()) < 0)
{
printf("Fork error!\n");
exit(0);
}
else if (pid == 0)
{
printf("exec by execv() function:\n");
/*TODO: use execv() function */
exit(0);
}
}
void use_execvp()
{
if ((pid = fork()) < 0)
{
printf("Fork error!\n");
exit(0);
}
else if (pid == 0)
{
printf("exec by execvp() function:\n");
/*TODO: use execvp() function */
exit(0);
}
}
void use_execvpe(char *env[])
{
/* Use "env" like execvpe(a, b, c, ... , env); */
if ((pid = fork()) < 0)
{
printf("Fork error!\n");
exit(0);
}
else if (pid == 0)
{
printf("exec by execvpe() function:\n");
/*TODO: use execvpe() function */
exit(0);
}
}
int main(int argc, char *argv[], char *env[])
{
/* Get the pointer of this string.
* strdup(3) for more details.*/
arg[0] = strdup("/bin/ls");
arg[1] = strdup("ls");
arg[2] = strdup("-al");
arg[3] = strdup(".");
arg[4] = (void *)NULL;
/* Implemented */
use_execl();
wait(NULL);
/* Implement the other five */
use_execlp();
wait(NULL);
use_execle(env);
wait(NULL);
use_execv();
wait(NULL);
use_execvp();
wait(NULL);
use_execvpe(env);
wait(NULL);
return 0;
}
|
C
|
#include "libft.h"
void *ft_memccpy(void *dst, const char *src, int c, size_t n)
{
size_t i;
unsigned char *str1;
unsigned char *str2;
unsigned char k;
k = (unsigned char)c;
i = 0;
str1 = (unsigned char *)src;
str2 = (unsigned char *)dst;
while (i < n)
{
str2[i] = str1[i];
if (str2[i] == k)
{
return (str2 + (i + 1));
}
i++;
}
return (0);
}
|
C
|
/*
5.4-C-11th-1:
结构体占用空间、结构体各成员变量对齐方式
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#pragma pack
//结构体成员对齐方式会影响到结构体的大小
//结构体成员都是以偶数字节开始存储,但是连续多个字符串会挨着存储
struct a_t{
char ch;
short s;
int i;
};
int main(void)
{
struct a_t a;
//&a.ch | &a.s
printf("sizeof(a) = %d\n", sizeof(a)); //打印结构体占用空间大小
printf("&a.ch = %p &a.s = %p\n", &a.ch, &a.s); //打印结构体成员的地址
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_strncpy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ryaoi <ryaoi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/10 16:07:07 by ryaoi #+# #+# */
/* Updated: 2018/07/10 17:49:04 by ryaoi ### ########.fr */
/* */
/* ************************************************************************** */
#include "test.h"
static void crash_test(void)
{
int status_mine;
int status_real;
char buffer[512];
pid_t p[2];
//real
p[0] = fork();
if ( p[0] == -1 ) {
perror("fork failed");
exit(EXIT_FAILURE);
}
else if ( p[0] == 0 ) {
strncpy(buffer, NULL, 10);
exit(EXIT_FAILURE);
}
waitpid(p[0], &status_real, 0);
//mine
p[1] = fork();
if ( p[1] == -1 ) {
perror("fork failed");
exit(EXIT_FAILURE);
}
else if ( p[1] == 0 ) {
ft_strncpy(buffer, NULL, 10);
exit(EXIT_FAILURE);
}
waitpid(p[1], &status_mine, 0);
if (status_real == status_mine)
printf("[CRASH TEST]\tSRC:NULL |\t%s",GOOD);
else
printf("[CRASH TEST]\tSRC:NULL |\t%s",BAD);
}
void test_strncpy(void)
{
char dst_mine[512];
char dst_real[512];
char *str = "COPYING THIS STRING?";
bzero(dst_mine, 512);
bzero(dst_real, 512);
ft_strncpy(dst_mine, str, 7);
strncpy(dst_real, str, 7);
printf("Src :%s length:%d | mine:%s\treal:%s\t", str, 7, dst_mine, dst_real);
if (strcmp(dst_mine, dst_real) == 0)
printf(GOOD);
else
printf(BAD);
ft_strncpy(dst_mine, str, strlen(str));
strncpy(dst_real, str, strlen(str));
printf("Src :%s length:%lu | mine:%s\treal:%s\t", str, strlen(str), dst_mine, dst_real);
if (strcmp(dst_mine, dst_real) == 0)
printf(GOOD);
else
printf(BAD);
crash_test();
}
|
C
|
#include <stdio.h>
void createArrayPointer(int *pointer) {
for(int zeile = 0; zeile < 8; zeile++) {
for(int spalte = 0; spalte < 8; spalte++) {
*pointer++ = (zeile+1) * 10 + spalte+1;
}
}
}
void showArray(int array[8][8]) {
for(int zeile = 0; zeile < 8; zeile++) {
for(int spalte = 0; spalte < 8; spalte++) {
printf("%d ",array[zeile][spalte]);
} printf("\n");
}
}
void showArrayPointer(int *pointerArray) {
for(int zeile = 0; zeile < 8; zeile++) {
for(int spalte = 0; spalte < 8; spalte++) {
printf("%d ", *pointerArray++);
} printf("\n");
}
}
int main(){
int myArray[8][8] = {0};
createArrayPointer(myArray);
/*
for(int zeile = 0; zeile < 8; zeile++) {
for(int spalte = 0; spalte < 8; spalte++) {
myArray[zeile][spalte] = (zeile+1) * 10 + spalte+1;
}
}*/
//Ausgabe mit Array
printf("Ausgabe über Array\n");
for(int zeile = 0; zeile < 8; zeile++) {
for(int spalte = 0; spalte < 8; spalte++) {
printf("%d ", myArray[zeile][spalte]);
} printf("\n");
}
//Ausgabe mit Pointer
int *pointerArray;
pointerArray = myArray;
printf("\nAusgabe über Pointer\n");
for(int zeile = 0; zeile < 8; zeile++) {
for(int spalte = 0; spalte < 8; spalte++) {
printf("%d ", *pointerArray++);
} printf("\n");
}
//Ausgabe mit Funktion
printf("\nAusgabe über Funktion\n");
showArray(myArray);
//Ausgabe mit Pointer und Funktion
printf("\nAusgabe über Pointer und Funktion\n");
showArrayPointer(myArray);
}
|
C
|
//
// main.c
// Lista(enDisco)
//
// Created by Victorio Scafati on 8/24/17.
// Copyright © 2017 Victorio Scafati. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "tree.h"
#include "abm.h"
/*
TO-DO list:
SOLVED - Agregar inOrden
SOLVED - Revisar las altas.
SOLVED - Revisar las bajas.
SOLVED - Hacer script para automatizar altas
SOLVED - Agregar un reset de los archivos para no generar conflictos
SOLVED - Revisar las opciones de las modificaciones
- Agregar treeView, muestre como esta formada la estructura del arbol
- Agregar busqueda individual de cuits
- Plantear solucion a la concurrencia
(usando un lock a nivel de archivos, cambiando f-io por io sin buffer (ie. fopen por open), etc)
*/
void usage();
void reset();
int main(int argc, const char * argv[]) {
# ifdef CODE_TEST
freopen("output.txt", "w+", stdout);
# endif
struct Arbol A;
actualizarArbol(&A);
if (argc == 2){
if ((argv[1][1] != 't') && (argv[1][1] != 'r')) {
usage();
exit(1);
}
}
if (argc >= 2){
switch (argv[1][1]) {
case 'a':
alta(argv[2]);
break;
case 'b':
baja(argv[2]);
break;
case 'm':
modi(argv[2]);
break;
case 't':
if (!esVacio(&A)) inOrden();
else {
reset();
perror("Arbol Vacio.");
}
break;
case 'r':
reset();
printf("Archivos reseteados correctamente.\n");
break;
default:
usage();
break;
}
} else {
usage();
exit(1);
}
# ifdef CODE_TEST
fclose(stdout);
# endif
return 0;
}
void usage(){
printf("Modo de Uso:\n");
printf("\t-a <cuit>\tDar de alta un <cuit>\n");
printf("\t-b <cuit>\tDar de baja un <cuit>\n");
printf("\t-m <cuit>\tModificar un <cuit>\n");
printf("\t-r \tResetear los archivos.\n");
printf("\t-t \tMostrar archivo de datos.\n");
}
void reset(){
FILE* fp = fopen(PATH_ABM,"w");
FILE* fa = fopen(PATH_ARBOL,"w");
fclose(fa);
fclose(fp);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* Faca um programa para ler um numero intiero positivo de tres digitos. Em seguida, calcule e mostre o numero formado pelos digitos invertidos do numero lido. */
int main() {
int numero, numero_invertido1, numero_invertido2, numero_invertido3;
printf("Digite um numero inteiro positivo de tres digitos: ");
scanf("%d", &numero);
numero_invertido1 = numero % 10;
numero = numero / 10;
numero_invertido2 = numero % 10;
numero = numero / 10;
numero_invertido3 = numero % 10;
printf("Invertido: %d%d%d", numero_invertido1, numero_invertido2, numero_invertido3);
return 0;
}
|
C
|
/*
============================================================================
Name : p284.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct island {
char *name;
char *opens;
char *closes ;
struct island *next ;
};
typedef struct island island ;
void display(island *start)
{
island *i = start ;
island *next = NULL;
for(; i!=NULL; i= next){
printf("Name:%s", i->name);
printf("Open: %s-%s\n", i->opens, i->closes);
next = i->next ;
}
}
void release(island *start)
{
island *i = start;
island *next = NULL;
for (; i != NULL; i = next) {
next = i->next ;
free(i->name);
free(i);
}
}
island* create(char *passin_name)
{
island *i = malloc(sizeof(island));
char *nameMem= malloc(sizeof(passin_name));
printf("...size is %d\n",sizeof(passin_name) );
strcpy(nameMem, passin_name) ;
i->name = nameMem ;
//i->name=name ;
//i->name = strdup(passin_name);
//allocate a completed copy of the string somewhere on the heap:
i->opens = "09:00";
i->closes = "17:00";
i->next = NULL;
return i;
}
int main(void) {
island *start = NULL;
island *i= NULL;
island *next= NULL ;
char org_name[80]; //"name1", "name2"
//char map[] = "taiwan.txt";
for(; fgets(org_name, 80, stdin); i=next)
{
next= create(org_name);
if(start == NULL) start = next ;
if(i != NULL)
i->next = next ;
}
display(start);
release(start);
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#include<math.h>
int mon[13];
int s,d;
int add(int i,int j){
int ans=0;
for(i=i;i<=j;i++){
if(mon[i]==1){
ans+=s;
}
else{
ans-=d;
}
}
return ans;
}
int main(){
int i,j;
while(~scanf("%d%d",&s,&d)){
for(i=1;i<=12;i++){
mon[i]=1;
}
for(i=1;i<=8;i++){
j=i+4;
while(add(i,i+4)>0){
mon[j]=0;
j--;
}
}
int ans=add(1,12);
if(ans>=0)
printf("%d\n",ans);
else
printf("Deficit\n");
}
return 0;
}
|
C
|
/*
* File: HW1.c
* Author: Tevin Taylor and Benjamin Valentino
*
* Created on February 8, 2017, 5:54 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char** argv) {
//Variable declarations
char *user_dir = malloc(sizeof(char)*100);
char *user_filename = malloc(sizeof(char)*100);
struct node {
char charID;
int fileCounter;
char files[100][50]; //[number of files][amount of allocated memory]
struct node *next;
} node;
//Making the 26 node linked list
struct node *head = malloc(sizeof(node));
struct node *current = head;
head -> charID = '0';
head -> next = NULL;
for (int i = 1; i < 26; i++) {
current -> next = malloc(sizeof(node));
current = current -> next;
current -> charID = '0';
current -> fileCounter = 0;
}
//Obtaining user provided directory
printf("Enter a folder name: ");
scanf("%s", user_dir);
//Read all file names in provided directory and sort into linked list
DIR *dir;
struct dirent *dirStruct;
dir = opendir(user_dir);
while ((dirStruct = readdir(dir)) != NULL) {
struct node *current = head;
int a;
a = 1;
while (a) {
if (current -> charID != '0') {
if (tolower(current -> charID) == tolower(dirStruct -> d_name[0])) {
//Place file in current node string array
strcpy(current -> files[current -> fileCounter], dirStruct -> d_name);
current -> fileCounter++;
a = 0;
}
current = current -> next;
} else {
//Define the current node charID as the first character of the file name
current -> charID = dirStruct -> d_name[0];
//Place file in current node string array
strcpy(current -> files[current -> fileCounter], dirStruct -> d_name);
current -> fileCounter++;
a = 0;
}
}
}
closedir(dir);
//Ask user for beginnings of file names until an empty string is entered and
//print matching file names to the screen
char *prefix = malloc(sizeof(char)*10);
fgets(prefix, sizeof(prefix), stdin);
prefix[strcspn(prefix, "\n")] = '\0';
do {
printf("\nEnter the beginning of a filename: ");
//fflush(stdin);
fgets(prefix, sizeof(prefix), stdin);
prefix[strcspn(prefix, "\n")] = '\0';
struct node *current1 = head;
while (current1 -> next != NULL) {
if (tolower(current1 -> charID) == tolower(prefix[0])) {
for (int j = 0; j < 50; j++) {
int b;
b = strncmp(prefix, current1 -> files[j], strlen(prefix));
if(b == 0) {
printf("\n%s",current1 -> files[j]);
}
}
break;
} else {
current1 = current1 -> next;
}
}
} while (strncmp(prefix, "", sizeof(prefix)));
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
/**
RTLD_LAZY:在dlopen返回前,对于动态库中的未定义的符号不执行解析(只对函数引用有效,对于变量引用总是立即解析)。
RTLD_NOW: 需要在dlopen返回前,解析出所有未定义符号,如果解析不出来,在dlopen会返回NULL,错误为:: undefined symbol: xxxx.......
*/
int main() {
void *libmhandler = NULL;
float (*cosf_method)(float) = NULL;
int (*maxhandle) (int, int, int);
int (*minHandle) (int, int);
char *errorInfo;
float result;
libmhandler = dlopen("./libmax.so", RTLD_LAZY);
// libmhandler = dlopen("./libmax.so", RTLD_LAZY);
if (libmhandler == NULL) {
printf("Open error:%s\n", dlerror());
return 0;
}
maxhandle = dlsym(libmhandler, "max");
if (maxhandle == NULL) {
printf("dlsym error: %s\n", dlerror());
return 0;
}
/*
minHandle = dlsym(libmhandler, "min");
if (minHandle == NULL) {
printf("dlsym error:%s\n", dlerror());
return 0;
}*/
int res = maxhandle(4, 7, 2);
printf("result : %d\n", res);
dlclose(libmhandler);
return 0;
}
|
C
|
/* Expand the stack by 32 bytes all at once using the PUSHA
instruction.
This must succeed. */
#include <string.h>
#include "tests/arc4.h"
#include "tests/cksum.h"
#include "tests/lib.h"
#include "tests/main.h"
void
test_main (void)
{
asm volatile
("movl %%esp, %%eax;" /* Save a copy of the stack pointer. */
"andl $0xfffff000, %%esp;" /* Move stack pointer to bottom of page. */
"pushal;" /* Push 32 bytes on stack at once. */
"movl %%eax, %%esp" /* Restore copied stack pointer. */
: : : "eax"); /* Tell GCC we destroyed eax. */
}
int
main (int argc UNUSED, char *argv[] UNUSED)
{
test_name = "pt-grow-pusha";
msg ("begin");
test_main();
msg ("end");
return 0;
}
|
C
|
#include <stdio.h>
void main(){
int num1, num2, suma;
printf("\nEste programa calcula la suma de dos numeros enteros.\n");
printf("\nIntroduce el valor del primer numero:\n");
scanf("%d",&num1);
printf("\nIntroduce el valor del segundo numero:\n");
scanf("%d",&num2);
suma = num1+num2;
printf("\nLa suma de %d y %d es %d.\n\n\n", num1,num2,suma);
}
|
C
|
#include <stdio.h>
int SomeOfElement(int A[], int size){
int sum=0;
for(int i=0; i<size;i++){
sum+=A[i];
}
return sum;
}
main(){
int A[]={2,3,4,5,6};
int size= sizeof(A)/sizeof(int);
//size= sizeof(A)/sizeof(A[0]);
int total=SomeOfElement(A,size);
printf("Some Of Element: %d",total);
}
|
C
|
// ±ȯ
#include <stdio.h>
int main(void)
{
int a = 33, b = 77;
int tmp;
puts("-----------------------");
puts(" * ±ȯ *");
puts("-----------------------");
printf(" a=%d, b=%d \n", a, b);
puts("-----------------------");
tmp = a;
a = b;
b = tmp;
printf("\n ȯ a=%d, b=%d \n", a, b);
puts("-----------------------");
printf(" ±ȯ ݵô ʿ");
puts("-----------------------");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "/lib/wizard.h"
void menu(){
int option=0;
do{
printf("\n------------------------------\n");
printf(" WIZARD\n\n");
printf("1. Jugar contra la máquina\n");
printf("2. Dos jugadores\n");
printf("3. Acerca del juego\n");
printf("4. Salir\n");
printf("------------------------------\n");
printf("Digite su opción: ");
scanf("%i", &option);
printf("\n");
switch(option){
case 1:
machine();
break;
case 2:
twoPlayers();
break;
case 3:
printf("El juego Wizard consiste en adivinar el número que da la máquina aleatoriamente o un jugador");
break;
case 4:
printf("Gracias por usar");
break;
default:
printf("Opción invalida");
}
printf("\n");
}while(option != 4);
}
int main(){
menu();
return 0;
}
|
C
|
/*
* 应用程序中打印call stack调用栈的方法
* 需要编译选项'-rdynamic'的支持
*/
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> /* open() */
#include <unistd.h> /* close() */
#include <string.h>
#include <errno.h> /* errno */
void dump_stack()
{
const size_t SIZE = 32;
void *buffer[SIZE]; /* 各个元素存储的是 栈帧 的地址, 并没有进一步的malloc空间 */
char **strings;
int n;
int i;
int err = 0;
/*
* backtrace指向的是stack frame, 打印出来不可读
*/
n = backtrace((void **)buffer, SIZE);
if (n == 0) {
printf("Empty calling stack\n");
return ;
}
/* 打印出来不是可读的字符 */
for (i = 0; i < n; i++) {
printf("%s\n", (char *)buffer[i]);
}
/*
* 将不可读的buffer转换为可读的symbol数组
*/
strings = backtrace_symbols((void *const *)buffer, n);
if (strings == NULL) {
printf("err = %d\n", err);
return ;
}
for (i = 0; i < n; i++) {
printf("%s\n", strings[i]);
}
free(strings);
/*
* 将调用栈信息打印到文件中
*/
char path[] = "/dev/shm/XXXXXX";
char *file_name = mktemp(path);
printf("file_name:%s\n", file_name);
if (strcmp(file_name, "")) {
int fd = open(file_name, O_RDWR | O_CREAT, S_IRWXU);
if (fd != -1) {
backtrace_symbols_fd((void *const *)buffer, n, fd);
close(fd);
} else {
printf("open() failed, Error:%s\n", strerror(errno));
}
}
}
static /* "static" means don't export the symbol... 就是dump_stack()无法打印出它的名字 */
void test()
{
dump_stack();
}
void test2()
{
test();
}
void test3()
{
test2();
}
int main(int argc, char **argv)
{
test3();
return 0;
}
|
C
|
/* exploit.c */
/* A program that creates a file containing code for launching shell*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* fix the shell code */
char shellcode[]= "eh?";
unsigned long get_sp(void)
{
__asm__("movl %esp,%eax");
}
void main(int argc, char **argv)
{
char buffer[1000];
FILE *badfile;
/*--------Initialize buffer with 0x90 (NOP instruction)--------*/
memset(buffer, 0x90, sizeof(buffer));
/*Add your changes to the buffer here */
/* Save the contents to the file "badfile" */
badfile = fopen("./badfile", "w");
fwrite(buffer,1000,1,badfile);
fclose(badfile);
}
|
C
|
#include "tree.h"
//////////////////////////////////////////////////////////////////////
//
// addnode() - place newNode into indicated tree at proper position.
//
// status code: this function can generate the following status codes
// DLT_SUCCESS: normal operation (success!)
// DLT_NULL: tree is NULL
// DLT_MAX: tried to add onto a full bounded
// tree (considered an error)
// DLT_ERROR: error encountered
// DLT_INVALID: tree pointer doesn't exist
//
// note: a max_height of 0 indicates an unbounded tree
//
// assumptions: duplicate values are allowed;
// nodes with values less than or equal to that of
// an analyzed node are placed to the left (back),
// where greater than are placed to the right (there).
//
// note: you are to have only ONE return statement for this
// entire function. Change the existing one as needed.
//
code_t addnode(Tree ** myTree, Node * newNode)
{
////////////////////////////////////////
//
// Iterative traversal for adding a node
//
////////////////////////////////////////
//
// Initialize a height variable to keep track of tree height,
// a tmp variable for traversing the tree, and a trigger variable to
// keep track of when to end iterations after adding a node
//
uc height = 0;
code_t status = DLT_ERROR;
Node *tmp = NULL;
int trigger = 0;
//
// If my tree does not exist, return an invalid error code because
// we cannot add a node to a non existant tree
//
if (myTree == NULL)
status = status | DLT_INVALID;
//
// If myTree pointer is NULL, it has not been created yet, return
// a null status code
//
else if (*myTree == NULL)
status = status | DLT_NULL;
//
// If tree exists and new Node is not Null, begin traversal
// Tree can now be added to
//
else if (myTree != NULL && newNode != NULL)
{
//
// If tree is empty, new node becomes the root of my tree
//
if ((*myTree)->root == NULL)
{
(*myTree)->root = newNode;
status = DLT_SUCCESS;
}
//
// If tree is not empty, traverse tree until area where new node
// shall be added
//
else
{
//
// Set beginning of search node at the root of tree
// Below is the iterative traversal logic for a tree
//
tmp = (*myTree)->root;
if ((*myTree)->max_height == 0)
{
while (trigger != 1)
{
//
// If newNode is less than the current
// traversed Value, tree traverses left, otherwise
// tree traverses right. if we approach a NULL point,
// add the node there
//
if (newNode->VALUE <= tmp->VALUE)
{
if (tmp->fro == NULL)
{
tmp->fro = newNode;
trigger = 1;
}
else
tmp = tmp->fro;
}
else if (newNode->VALUE > tmp->VALUE)
{
if (tmp->to == NULL)
{
tmp->to = newNode;
trigger = 1;
}
else
tmp = tmp->to;
}
}
}
//
// Tree has a max height
// Traversing over a tree iteratively with a set max height
// Traversal ends if we reach max height of the tree, and exits
// with a MAX limit reached status code
//
else
{
//
// Iterative traversal over the tree is the exact
// same as the previous loop, except it takes into account
// the height of the tree, so that the max height cannot
// be breached
//
while (trigger != 1)
{
if (height >= (*myTree)->max_height)
{
status = status | DLT_MAX;
break;
}
if (newNode->VALUE <= tmp->VALUE)
{
if (tmp->fro == NULL)
{
tmp->fro = newNode;
status = DLT_SUCCESS;
trigger = 1;
}
else
{
tmp = tmp->fro;
height++;
}
}
else if (newNode->VALUE > tmp->VALUE)
{
if (tmp->to == NULL)
{
tmp->to = newNode;
status = DLT_SUCCESS;
trigger = 1;
}
else
{
tmp = tmp->to;
height++;
}
}
}
}
}
}
else if (newNode == NULL)
status = status | DLN_NULL;
return (status);
}
|
C
|
#include <stdio.h>
#include <locale.h>
// CONVERSAO CELSIUS -> KELVIN
int main(){
int c;
scanf("%d", &c);
printf("%.2f", c + 273.15);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include<omp.h>
#include<time.h>
#define NUM_ITEMS 100000000
void mergeSort(int numbers[], int temp[], int array_size);
void m_sort(int numbers[], int temp[], int left, int right);
void merge(int numbers[], int temp[], int left, int mid, int right);
int numbers[NUM_ITEMS];
int temp[NUM_ITEMS];
int temps[NUM_ITEMS];
int s1, s2, s3;
clock_t start,end;
int main()
{
int i;
FILE *fp;
fp = fopen("Parallel.txt","r"); //ファイル読み込み
for (i = 0; i < NUM_ITEMS; i++)
fscanf(fp, "%d", &numbers[i]);
fclose(fp);
start = clock();
mergeSort(numbers, temp, NUM_ITEMS);
end = clock();
printf("%.2f秒かかりました\n",(double)(end-start)/CLOCKS_PER_SEC);
return 0;
}
void mergeSort(int numbers[], int temp[], int array_size)
{
s1 = array_size / 4;
s2 = array_size / 2;
s3 = (array_size / 4) * 3;
int mid ;
mid = array_size / 2;
#pragma omp parallel
{
if(omp_get_thread_num() == 0){
m_sort(numbers, temp, 0, s1 -1 );
} else if(omp_get_thread_num() == 1){
m_sort(numbers, temp, s1 , s2 -1 );
} else if(omp_get_thread_num() == 2){
m_sort(numbers, temp, s2, s3 - 1);
} else if(omp_get_thread_num() == 3){
m_sort(numbers, temp, s3 , array_size - 1);
}
}
#pragma omp parallel
{
if(omp_get_thread_num() == 0){
merge(numbers, temp, 0, s1, s2 - 1);
} else if(omp_get_thread_num() == 1){
merge(numbers, temps, s2 , s3, array_size - 1);
}
}
merge(numbers, temp, 0, mid+1, array_size);
}
void m_sort(int numbers[], int temp[], int left, int right)
{
int mid;
if (right > left)
{
mid = (right + left) / 2;
m_sort(numbers, temp, left, mid);
m_sort(numbers, temp, mid+1, right);
merge(numbers, temp, left, mid+1, right);
}
}
void merge(int numbers[], int temp[], int left, int mid, int right)
{
int i, left_end, num_elements, tmp_pos;
left_end = mid - 1;
tmp_pos = left;
num_elements = right - left + 1;
while ((left <= left_end) && (mid <= right))
{
if (numbers[left] <= numbers[mid])
{
temp[tmp_pos] = numbers[left];
tmp_pos = tmp_pos + 1;
left = left +1;
}
else
{
temp[tmp_pos] = numbers[mid];
tmp_pos = tmp_pos + 1;
mid = mid + 1;
}
}
while (left <= left_end)
{
temp[tmp_pos] = numbers[left];
left = left + 1;
tmp_pos = tmp_pos + 1;
}
while (mid <= right)
{
temp[tmp_pos] = numbers[mid];
mid = mid + 1;
tmp_pos = tmp_pos + 1;
}
for (i=0; i <= num_elements; i++)
{
numbers[right] = temp[right];
right = right - 1;
}
}
|
C
|
#include "GlobalDefine.h"
#include "Error.h"
#include "Stdio.h"
#include "Common.h"
#include "CommandManager.h"
typedef void(*ADDRESS)();
int do_go_exec(int(*entry)())
{
return entry();
}
/*******************************************************************
* Function Name: TestSn
* Inputs : argc, argv
* Outputs : Status
* Description: Print diags sn
* Author: Kevin
*******************************************************************/
MINI2440_STATUS TestGo(int argc, char* const* argv)
{
MINI2440_STATUS status = MINI2440_SUCCESS;
int address = 0;
if(argc == 2)
{
address = hex_string_to_int(argv[1]);
LogPrintf("address = 0x%x\n", address);
delay(1024);
do_go_exec((void *)address);
// ((ADDRESS)address)();
/* __asm__ __volatile__(
"mov r0, %[address1]\n"
"mov pc, r0\n"
:
:[address1] "r" (address)
:"r0"
);
*/
}
return status;
}
COMMAND_INSTALL(go, "\tgo address", TestGo);
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include "uart_driver.h"
static int array_iterator = 0;
static bool is_enabled = false;
void uart_driver_start_communication() {
/** dummy function, don't care about the code inside */
is_enabled = true;
}
void uart_driver_stop_communication() {
/** dummy function, don't care about the code inside */
is_enabled = false;
}
unsigned char uart_driver_get_byte() {
/** dummy function, the code inside is provided only for debug purposes */
if(is_enabled == false) {
printf("the uart communication has not been enabled. please call `uart_driver_start_communication` first\n");
return 0;
}
unsigned char data[] = {0x01, 0xFF, 0xA1, 0x00, 0x00, 0xFF, 0x13, 0x08};
array_iterator++;
return data[array_iterator - 1];
}
void uart_driver_send_byte(unsigned char data) {
/** dummy function, don't care about the code inside */
}
|
C
|
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
const char *semaphore_name = "semaforo";
sem_t mutex;
int turn;
void gravaNumeros() {
int i;
FILE *fp;
int value;
for (i = 1; i <= 26; i++) {
sem_wait(&mutex);
sem_getvalue(&mutex, &value);
if ((fp = fopen("abc123.x", "a")) != NULL) {
fprintf(fp, "%d", i);
} else
printf("Erro na abertura do arquivo.");
fclose(fp);
//i++;
printf("Valor do semaforo grava numeros: %d\n",value);
sem_post(&mutex);
}
}
void gravaLetras() {
int i;
FILE *fp;
int value;
char alfabeto[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (i = 0; i < strlen(alfabeto); i++) {
sem_wait(&mutex);
sem_getvalue(&mutex, &value);
if ((fp = fopen("abc123.x", "a")) != NULL) {
fprintf(fp, " %c\n", alfabeto[i]);
} else
printf("Erro na abertura do arquivo.");
fclose(fp);
printf("Valor do semaforo grava letras: %d\n",value);
sem_post(&mutex);
}
}
int main() {
pid_t pid, pid2;
sem_init(&mutex, 1, 10);
//mutex = sem_open(semaphore_name, O_CREAT, 0644, 1);
//fp = fopen("abc123.x", "a");
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid > 0) {
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork Failed\n");
return 1;
} else if (pid2 > 0) {
wait(NULL);
} else if (pid2 == 0) {
gravaLetras();
exit(1);
}
wait(NULL);
FILE *fp;
char c;
if ((fp = fopen("abc123.x", "r")) != NULL) {
while ((c = fgetc(fp)) != EOF) {
printf("%c", c);
}
fclose(fp);
}
sem_destroy(&mutex);
} else {
gravaNumeros();
exit(1);
}
}
|
C
|
#include "unit_test.h"
int main(){
printf("\n[-------- Unit tests --------]\n");
int result = 0;
//run the tests for all the units
result += interpreter_test();
result += tokenizer_test();
if(result != 0){
printf("Unit testing: %d tests FAILED\n", result);
} else {
printf("Unit testing: All tests PASSED\n");
}
return 0;
}
|
C
|
// Value of the polynomial ver 2
#include <stdio.h>
int main(void)
{
int x,f;
printf("Enter the value of x: ");
scanf("%d",&x);
f=((((3*x+2)*x-5)*x-1)*x+7)*x-6;
printf("Value of the polynomial: %d\n",f);
return 0;
}
|
C
|
/* Originally this program just generated uudmap.h
However, when we later wanted to generate bitcount.h, it was easier to
refactor it and keep the same name, than either alternative - rename it,
or duplicate all of the Makefile logic for a second program. */
#include <stdio.h>
#include <stdlib.h>
/* If it turns out that we need to make this conditional on config.sh derived
values, it might be easier just to rip out the use of strerrer(). */
#include <string.h>
/* If a platform doesn't support errno.h, it's probably so strange that
"hello world" won't port easily to it. */
#include <errno.h>
void output_block_to_file(const char *progname, const char *filename,
const char *block, size_t count) {
FILE *const out = fopen(filename, "w");
if (!out) {
fprintf(stderr, "%s: Could not open '%s': %s\n", progname, filename,
strerror(errno));
exit(1);
}
fputs("{\n ", out);
while (count--) {
fprintf(out, "%d", *block);
block++;
if (count) {
fputs(", ", out);
if (!(count & 15)) {
fputs("\n ", out);
}
}
}
fputs("\n}\n", out);
if (fclose(out)) {
fprintf(stderr, "%s: Could not close '%s': %s\n", progname, filename,
strerror(errno));
exit(1);
}
}
static const char PL_uuemap[]
= "`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
typedef unsigned char U8;
/* This will ensure it is all zeros. */
static char PL_uudmap[256];
static char PL_bitcount[256];
int main(int argc, char **argv) {
size_t i;
int bits;
if (argc < 3 || argv[1][0] == '\0' || argv[2][0] == '\0') {
fprintf(stderr, "Usage: %s uudmap.h bitcount.h\n", argv[0]);
return 1;
}
for (i = 0; i < sizeof(PL_uuemap) - 1; ++i)
PL_uudmap[(U8)PL_uuemap[i]] = (char)i;
/*
* Because ' ' and '`' map to the same value,
* we need to decode them both the same.
*/
PL_uudmap[(U8)' '] = 0;
output_block_to_file(argv[0], argv[1], PL_uudmap, sizeof(PL_uudmap));
for (bits = 1; bits < 256; bits++) {
if (bits & 1) PL_bitcount[bits]++;
if (bits & 2) PL_bitcount[bits]++;
if (bits & 4) PL_bitcount[bits]++;
if (bits & 8) PL_bitcount[bits]++;
if (bits & 16) PL_bitcount[bits]++;
if (bits & 32) PL_bitcount[bits]++;
if (bits & 64) PL_bitcount[bits]++;
if (bits & 128) PL_bitcount[bits]++;
}
output_block_to_file(argv[0], argv[2], PL_bitcount, sizeof(PL_bitcount));
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <byteswap.h>
#include "misc.h"
uint64_t htolell(uint64_t hostlong) {
#if !defined(__BYTE_ORDER__) || !defined(__ORDER_BIG_ENDIAN__)
#error unable to detect byte order! you will need to manually fix the code (and/or submit a bugreport?)
#endif
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return bswap_64(hostlong);
#else
return hostlong;
#endif
}
uint64_t htobell(uint64_t hostlong) {
#if !defined(__BYTE_ORDER__) || !defined(__ORDER_BIG_ENDIAN__)
#error unable to detect byte order! you will need to manually fix the code (and/or submit a bugreport?)
#endif
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return hostlong;
#else
return bswap_64(hostlong);
#endif
}
uint64_t htonll(uint64_t hostlong) {
#if !defined(__BYTE_ORDER__) || !defined(__ORDER_BIG_ENDIAN__)
#error unable to detect byte order! you will need to manually fix the code (and/or submit a bugreport?)
#endif
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return hostlong;
#else
return bswap_64(hostlong);
#endif
}
uint64_t ntohll(uint64_t netlong) {
//return htonll(netlong);...
#if !defined(__BYTE_ORDER__) || !defined(__ORDER_BIG_ENDIAN__)
#error unable to detect byte order! you will need to manually fix the code (and/or submit a bugreport?)
#endif
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return netlong;
#else
return bswap_64(netlong);
#endif
}
#define emsprintf(target,...){ \
target=realloc(target,(size_t)snprintf(NULL,0,__VA_ARGS__)+1); \
sprintf(target,__VA_ARGS__); \
}
#define emsprintferr(target,format,...){ \
emsprintf(target,format ". errno: %i. strerror: %s",__VA_ARGS__,errno,strerror(errno)); \
}
//free me. always.
char *get_process_name_by_pid(const int pid, char **unused) {
if (unused) {
*unused = ecalloc(1, 1);
}
char* name = ecalloc(1024, sizeof(char));
if (name) {
sprintf(name, "/proc/%d/cmdline", pid);
FILE* f = fopen(name, "r");
if (f) {
size_t size;
size = fread(name, sizeof(char), 1024, f);
if (size > 0) {
if ('\n' == name[size - 1])
name[size - 1] = '\0';
}
fclose(f);
}
}
return name;
}
////free me. always.
//char *get_process_name_by_pid(const int pid, char** warnings_and_errors) {
// char *failreason1 = NULL;
// do {
// printf("THE PID IS %i\n", pid);
// char name[snprintf(NULL, 0, "/proc/%i/cmdline", pid) + 1];
// sprintf(name, "/proc/%i/cmdline", pid);
// FILE *fd = fopen(name, "r");
// printf("%i\n", __LINE__);
// if (!fd) {
// if (warnings_and_errors) {
// emsprintferr(failreason1, "failed to open %s", name);
// }
// break;
// }
// //you can not use SEEK_END, nor can you use fstat() to get the file size of stuff in /proc
// // they just return 0. (no, not even -1 error, just 0)
// size_t read = 0;
// char* buf = NULL;
// while (true) {
// buf = erealloc(buf, read + 1); //<<could probably be optimized
// size_t newread = fread(buf, 1, 1, fd);
// if (newread != 1) {
// break;
// }
// ++read;
// }
// if (read <= 0) {
// if (warnings_and_errors) {
// emsprintferr(failreason1, "failed to read any data from %s",
// name)
// }
// free(buf);
// fclose(fd);
// break;
// }
// fclose(fd);
// buf[read - 1] = '\0';
// printf("RETURNING BUF %s\n", buf);
// return buf;
// } while (false);
// printf("%i\n", __LINE__);
// //failed to get name from /cmdline (which is sometimes empty regardless, idk why. for instance, btrfs-qgroup-re has empty cmdline)..
// // try /stat (even btrfs-qgroup-re has its name in /stat )
// char *failreason2 = NULL;
// do {
// char name[snprintf(NULL, 0, "/proc/%i/stat", pid) + 1];
// sprintf(name, "/proc/%i/stat", pid);
// FILE *fd = fopen(name, "r");
// if (!fd) {
// if (warnings_and_errors) {
// emsprintferr(failreason2, "failed to open %s", name);
// }
// break;
// }
// //you can not use SEEK_END, nor can you use fstat() to get the file size of stuff in /proc
// // they just return 0. (no, not even -1 error, just 0)
// size_t read = 0;
// char* buf = NULL;
// while (true) {
// buf = erealloc(buf, read + 1); //<<could probably be optimized
// size_t newread = fread(buf, 1, 1, fd);
// if (newread != 1) {
// break;
// }
// ++read;
// }
// if (read <= 0) {
// if (warnings_and_errors) {
// emsprintferr(failreason2, "failed to read any data from %s",
// name)
// }
// free(buf);
// fclose(fd);
// break;
// }
// fclose(fd);
// if (warnings_and_errors) {
// *warnings_and_errors = failreason1;
// } else {
// free(failreason1);
// }
// return buf;
// } while (false);
// //i give up.
// if (warnings_and_errors) {
// char* finalerr = NULL;
// emsprintf(finalerr,
// "failed to find name of pid for 2 reasons. reason 1: %s. reason 2: %s\n",
// failreason1, failreason2);
// *warnings_and_errors = finalerr;
// }
// free(failreason1);
// free(failreason2);
// return calloc(1, 1);
//}
|
C
|
#include <assert.h>
#include <limits.h>
#ifndef __GNUC__
int __builtin_ffs(int);
int __builtin_ffsl(long);
int __builtin_ffsll(long long);
#endif
int __VERIFIER_nondet_int();
long __VERIFIER_nondet_long();
long long __VERIFIER_nondet_long_long();
// http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
static const int multiply_de_bruijn_bit_position[32] = {
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
int main()
{
assert(__builtin_ffs(0) == 0);
assert(__builtin_ffs(-1) == 1);
assert(__builtin_ffs(INT_MIN) == sizeof(int) * 8);
assert(__builtin_ffsl(INT_MIN) == sizeof(int) * 8);
assert(__builtin_ffsl(LONG_MIN) == sizeof(long) * 8);
assert(__builtin_ffsll(INT_MIN) == sizeof(int) * 8);
assert(__builtin_ffsll(LLONG_MIN) == sizeof(long long) * 8);
assert(__builtin_ffs(INT_MAX) == 1);
int i = __VERIFIER_nondet_int();
__CPROVER_assume(i != 0);
__CPROVER_assume(sizeof(i) == 4);
__CPROVER_assume(i > INT_MIN);
assert(
multiply_de_bruijn_bit_position
[((unsigned)((i & -i) * 0x077CB531U)) >> 27] +
1 ==
__builtin_ffs(i));
return 0;
}
|
C
|
//
// xcmd.c
// XCMD
//
// Created by Bismarrck on 6/29/14.
// Copyright (c) 2014 TCCL. All rights reserved.
//
#include <stdio.h>
#include "xcmd.h"
#include "global.h"
#include "fileio.h"
#include "velocity.h"
#include "motion.h"
#include "potential.h"
#include "force.h"
#include "utilities.h"
#include "unit.h"
int xcmd_main(const char *input, const char *output)
{
// Init the global output stream.
xcmd_global_init(output);
// Read the input file.
xcmd_object_t *md = io_read_input(input);
// Set the initial velocities
velocity_init_random(md);
// Calculate the initial total energy of the system.
potential_lenard_jones(md);
velocity_kinetic_energy(md);
xcmd_energy_update(md);
// step : the number of simulation eclipsed.
// tims : the simulation time eclipsed.
int step = 0;
float time = 0.0;
// Main molecular simulation loop
while (step < md->nsteps) {
// Step forward
motion_anderson_thermostat_first(md);
force_lenard_jones(md);
motion_anderson_thermostat_second(md);
xcmd_energy_update(md);
step ++;
time += md->timestep;
// Rescale the velocity every 20 steps before equilibration
if (time > md->tequil && md->scale && step % 20 == 0) {
velocity_rescale(md);
}
// Sample averages for every step.
xcmd_sample_averages(md, step);
// Output the coordinates, forces and velocities.
if (step % md->outfreq == 0) {
io_output_coordinate(md, step);
io_output_force(md, step);
io_output_velocity(md, step);
}
}
// Calculate the final total energy of this system.
potential_lenard_jones(md);
velocity_kinetic_energy(md);
xcmd_energy_update(md);
// Release the main object.
xcmd_global_finalize();
xcmd_object_release(md);
return 1;
}
void xcmd_energy_update(xcmd_object_t *md)
{
md->etot = md->ekin + md->epot;
}
void xcmd_sample_averages(xcmd_object_t *md, int step)
{
float temp = 2.0 * md->ekin / (3.0 * md->nparticle);
float vol = md->box * md->box * md->box;
float rho = md->nparticle / vol;
float press = rho * temp + md->virial / (3.0 * vol);
float T = reducedTemperatureToSI(temp);
float P = reducedPressToSI(press);
float potE = reducedEnergyToSI(md->epot / md->nparticle);
float kinE = reducedEnergyToSI(md->ekin / md->nparticle);
float avgE = reducedEnergyToSI(md->etot / md->nparticle);
fprintf(xcmdout, "Sample averages on step %3d\n", step);
fprintf(xcmdout, "\tTemperature %4.0f K Pressure: %.6f MPa\n", T, P);
fprintf(xcmdout, "\tEnergy(Pot, Kin, Total): % 16.12f % 16.12f % 16.12f\n",
potE, kinE, avgE);
}
|
C
|
#include <stdio.h>
//#define SQUARE(X) X*X
// 비정상 계산을 막기 위해1
// #define SQUARE(X) (X)*(X)
// 비정상 계산을 막기 위해2
#define SQUARE(X) ((X)*(X))
/*
매크로 두줄이상 정의
#define SQUARE(X) \
((X)*(X))
*/
int main(void)
{
int num=20;
/* 정상적 결과 출력 */
printf("Square of num : %d \n", SQUARE(num));
printf("Square of -5 : %d \n", SQUARE(-5));
printf("Square of 2.5 : %g \n", SQUARE(2.5));
/* 비정상적 결과 출력 */
// 3+2 * 3+2
printf("Square of 3+2 : %d \n", SQUARE(3+2));
// (3+2)*(3+2)
printf("Square of (3+2) : %d \n", SQUARE((3+2)));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** args)
{
if (argc != 3)
{
fprintf(stderr, "The number of arguments is not enough. \n");
exit(1);
}
if (strlen(args[1]) != strlen(args[2]))
{
fprintf(stderr, "The length of the two strings does NOT match. \n");
exit(1);
}
int charCount[256] = {0};
int i = 0;
for (i = 0; i < strlen(args[1]); i++)
{
charCount[args[1][i]]++;
}
i = 0;
for (i = 0; i < 256; i++)
{
if (charCount[i] > 1)
{
fprintf(stderr, "From, the first argument after the program, has duplicate bytes. Please remove! \n");
exit(1);
}
}
char charMap[256] = "";
i = 0;
for (i = 0; i < strlen(args[1]); i++)
{
charMap[args[1][i]] = args[2][i];
}
int byte = getchar();
while (byte != EOF)
{
if (charMap[byte] == 0)
putchar(byte);
else
putchar(charMap[byte]);
byte = getchar();
}
}
|
C
|
#include <stdio.h>
void print_sample(char * str)
{
printf("%s\n",str);
print_sample("Done!");
}
int main()
{
for (int i=0; i<10; i++)
print_sample("printing...");
return 0;
}
|
C
|
#include <stdio.h>
#define MAXLEN 1000
#define TOSCREEN 80
int getline(FILE *f, char s[], int lim);
int main(int argc, char const *argv[])
{
FILE *myin, *myout;
myin=fopen("in.txt","r");
myout=fopen("out.txt","w");
int c;
char line[MAXLEN];
int len;
while((len=getline(myin,line,MAXLEN))>0)
if(len>TOSCREEN)
printf("%s",line);
fclose(myin);
fclose(myout);
return 0;
}
int getline(FILE *f, char s[], int lim)
{
int i=0;
int c;
while(i<lim-1 && (c=fgetc(f))!='\n' && c!=EOF)
s[i++]=c;
if(c=='\n')
s[i++]='\n';
s[i]='\0';
return i;
}
|
C
|
#include "strbuf.h"
#include <stdlib.h>
#include <stdio.h>
strbuf * strbuf_init() {
strbuf * buf = (strbuf *) malloc(sizeof (strbuf));
buf->tail = NULL;
buf->head = NULL;
buf->direct_out = NULL;
return buf;
}
void strbuf_free(strbuf * buf) {
strbuf_node * cur, * t;
cur = buf->tail;
while (cur != NULL) {
t = cur;
cur = cur->p;
free(t);
}
free(buf);
}
void strbuf_putchar(strbuf * buf, unsigned char c) {
if (buf->direct_out != NULL) {
// direct out is set: buffer is disabled
fputc(c, buf->direct_out);
} else if (buf->tail == NULL || buf->tail->l == STRBUF_LEN) {
// when there is no node or a node is full
// add to a new node
strbuf_node * bn = (strbuf_node *) malloc(sizeof (strbuf_node));
bn->l = 1;
bn->c[0] = c;
// link the node to others
bn->n = NULL;
bn->p = buf->tail;
buf->tail = bn;
if (bn->p != NULL) bn->p->n = bn;
if (buf->head == NULL) buf->head = bn;
} else {
// fill in the tail node
buf->tail->c[buf->tail->l++] = c;
}
}
void strbuf_dump_rev(strbuf * buf, FILE * fout) {
int i;
strbuf_node * bn = buf->tail;
while (bn != NULL) {
for (i = bn->l - 1; i > -1; i--)
fputc(bn->c[i], fout);
bn = bn->p;
}
}
void strbuf_dump(strbuf * buf, FILE * fout) {
int i;
strbuf_node * bn = buf->head;
while (bn != NULL) {
for (i = 0; i < bn->l; i++)
fputc(bn->c[i], fout);
bn = bn->n;
}
}
|
C
|
#pragma once
#include <stdbool.h>
#include <file_ops.h>
typedef struct AudioPlayerParam {
Entry *entries;
int n_entries;
int index;
const char *cwd;
bool play_all; // true -> play all songs in folder
} AudioPlayerParam;
/** Start the audio player at the file entry at index. */
int audio_player(AudioPlayerParam param);
|
C
|
#include <stdio.h>
#include <string.h>
char S[2][17]; // Направил съм го 17, а не 16 заради '\0'
char F(char x){
return S[0][x>>6] + S[1][x>>4];
}
void encrypt(char L, char R, char* out){
for(int i=0;i<16;i++){
R^=F(L);
L^=F(R);
}
out[0]=R;
out[1]=L;
}
void decrypt(char L, char R, char* out){
for(int i=0;i<16;i++){
R^=F(L);
L^=F(R);
}
out[0]=R;
out[1]=L;
}
/*
Два цикъла, чрез които се преработва глобалната променлива
според ключа. Взима се големината на ключа и когато той достигне краят си
се повтаря. Ако не се достигне краят на ключа през първата итерация,
то той при втората започва със следващия символ от там от където е свършил при първата.
*/
void init_boxes(char* key){
int length_of_key=strlen(key),k=0;
for(int i=0;i<2;i++){
for(int j=0;j<16;j++){
if(k==length_of_key) k=0;
S[i][j]=key[k];
k++;
}
}
}
/*
Взима се големината на текста и се създава временен стринг, който съдържа
в случая двата криптирани символа, като после се добавят към encrypted чрез конкатинация.
*/
void perform_encryption(char* text, char* key, char* encrypted){
int length_of_text=strlen(text);
char temporary_encrypted[2];
init_boxes(key);
for(int i=0;i<length_of_text;i+=2){
encrypt(text[i], text[i+1], temporary_encrypted);
strcat(encrypted, temporary_encrypted);
}
}
/*
Същото като при криптирането, но в случая с декриптиране.
*/
void perform_decryption(char* encrypted, char* decrypted){
int length_of_encrypted=strlen(encrypted);
char temporary_decrypted[2];
for(int i=0;i<length_of_encrypted;i+=2){
decrypt(encrypted[i], encrypted[i+1], temporary_decrypted);
strcat(decrypted, temporary_decrypted);
}
}
/*
Пример показващ работата на криптирането и декриптирането.
*/
int main(int argc, char* argv[]){
char encrypted[65];
char decrypted[65];
perform_encryption(argv[1], argv[2], encrypted);
puts(encrypted);
perform_decryption(encrypted,decrypted);
puts(decrypted);
return 0;
}
|
C
|
#include <stdio.h>
/* Multiplication Table */
void main(void)
{
int iterator, num;
printf("Enter the number to display its multiplication table : ");
scanf("%d", &num);
printf("\n");
for (iterator = 1; iterator <= num; iterator++)
{
printf("%d X %d = %d \n", num, iterator, num * iterator);
}
}
|
C
|
#include<stdio.h>
#include<string.h>
int main() {
char a[50];
printf("Enter word : "); gets(a);
int count;
for(int i=0; a[i]!='\0'; i++){
count=i;
if(a[i]=='a'){
while(a[count]!='\0'){
a[count] = a[count + 1];
count++;
}
}
}
if
printf("%s", a);
return 0;
}
|
C
|
#include<arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[]) {
unsigned char buf[sizeof(struct in6_addr)];
int domain, s;
char str[INET6_ADDRSTRLEN];
if(argc != 3) {
fprintf(stderr, "Usage : %s {i4 | i6| <num> } string \n", argv[0]);
exit(EXIT_FAILURE);
}
domain = (strcmp(argv[1], "i4") == 0) ? AF_INET : (strcmp(argv[1], "i6") == 0) ? AF_INET6 : atoi(argv[1]);
s = inet_pton(domain, argv[2], buf);
printf("%s\n", buf);
if(s <= 0) {
if(s == 0)
fprintf(stderr, "Not in presentation format\n");
else
perror("inet_pton\n");
exit(EXIT_FAILURE);
}
printf("%s\n", str);
exit(EXIT_SUCCESS);
}
|
C
|
#include "rsxtiny.h"
static s8 initialized = 0;
gcmConfiguration config;
void *heap_pointer;
extern void debugPrintf(const char* fmt, ...);
// Really dumb allocater, It will do until we start dealing with textures and vertex buffers.
void *rsxtiny_MemAlign(s32 alignment, s32 size) {
if (!initialized || alignment==-1 ) {
gcmGetConfiguration(&config);
initialized = 1;
#ifdef OLD_TINY3D
heap_pointer = (void *)(u64)config.localAddress;
#else
heap_pointer = (void *) config.localAddress;
#endif
if(alignment==-1) return NULL;
}
debugPrintf("config.localAddress: %p\n",config.localAddress);
void *pointer = heap_pointer;
pointer = (void *)((((u64) pointer) + (alignment-1)) & (-alignment)); // Align
#ifdef OLD_TINY3D
if ((u64) pointer + size > config.localAddress + config.localSize) // Out of memory?
return NULL;
#else
if ((u64) pointer + size > ((u64)(void *) config.localAddress) + config.localSize) // Out of memory?
return NULL;
#endif
heap_pointer = (void *)((u64) pointer + size);
debugPrintf("heap_pointer: %p\n",heap_pointer);
debugPrintf("pointer: %p\n",pointer);
return pointer;
}
void *rsxtiny_Mem(s32 size) {
return rsxtiny_MemAlign(64, size);
}
|
C
|
#include "sparse_crs.h"
int init_pattern(struct PATTERN *pattern, int n, int m, int nzmax)
{
int i, j;
pattern->n = n;
pattern->m = m;
if ((pattern->row = (int*)malloc(sizeof(int) * (n + 1))) == NULL ||
(pattern->col = (int*)malloc(sizeof(int) * (n * nzmax))) == NULL)
{
printf ("Out of memory!\n");
exit(-1);
}
for (i = 0; i < n; i++)
{
pattern->row[i] = i * nzmax;
pattern->col[pattern->row[i]] = i;
for (j = i * nzmax + 1; j < (i + 1) * nzmax; j++)
pattern->col[j] = -1;
}
pattern->row[n] = n * nzmax;
pattern->is_compressed = 0;
pattern->registed = NULL;
return 0;
};
int print_pattern(const struct PATTERN *pattern)
{
int i, j;
for (i = 0; i < pattern->n; i++)
for (j = pattern->row[i]; j < pattern->row[i + 1]; j++)
printf ("(%d, %d)\n", i, pattern->col[j]);
return 0;
};
int delete_pattern(struct PATTERN *pattern)
{
struct node *p = pattern->registed;
struct node *d; /**< pointer to delete. */
while (p != NULL)
{
d = p;
p = p->next;
free(d->mat->ele);
free(d);
}
free(pattern->col);
free(pattern->row);
};
int set_pattern(struct PATTERN *pattern, int pi, int pj)
{
int j, flag;
if (pi == pj)
return 0;
else
{
flag = 0;
for (j = pattern->row[pi] + 1; j < pattern->row[pi + 1]; j++)
{
if (pattern->col[j] == -1)
{
pattern->col[j] = pj;
flag = 1;
break;
}
}
if (flag == 0)
{
printf ("Pattern error!\n");
exit(-1);
}
}
return 0;
};
int compress_pattern(struct PATTERN *pattern)
{
int rp = 0;
int wp = 0;
int old_row = 0;
int i, j;
for (i = 0; i < pattern->n; i++)
{
for (j = old_row; j < pattern->row[i + 1]; j++)
{
if (pattern->col[j] != -1)
{
pattern->col[wp] = pattern->col[rp];
wp++;
rp++;
}
else
rp++;
}
old_row = pattern->row[i + 1];
pattern->row[i + 1] = wp;
}
pattern->is_compressed = 1;
return 0;
};
int init_matrix(struct MATRIX *mat, struct PATTERN *pattern)
{
int i;
if (pattern->is_compressed == 0)
{
printf ("The pattern have to be compressed first!\n");
exit(-1);
}
mat->pat = pattern;
/// 将自己加入模板注册列表.
struct node *p = pattern->registed;
while (p != NULL)
p = p->next;
if ((p = (struct node*)malloc(sizeof(struct node))) == NULL)
{
printf ("Out of memory!\n");
exit(-1);
}
p->mat = mat;
p->next = NULL;
if ((mat->ele = (double*)malloc(sizeof(double) * (pattern->row[pattern->n]))) == NULL)
{
printf ("Out of memory!\n");
exit(-1);
}
for (i = 0; i < pattern->n; ++i)
mat->ele[i] = 0.0;
return 0;
};
int print_matrix(const struct MATRIX *mat)
{
int i, j;
for (i = 0; i < mat->pat->n; i++)
for (j = mat->pat->row[i]; j < mat->pat->row[i + 1]; j++)
printf ("(%d, %d) = %lf\n", i, mat->pat->col[j], mat->ele[j]);
return 0;
};
int add_matrix(struct MATRIX *mat, int ai, int aj, double e)
{
int i, flag;
if (ai == aj)
{
mat->ele[mat->pat->row[ai]] += e;
return 0;
}
else
{
flag = 0;
for (i = mat->pat->row[ai] + 1; i < mat->pat->row[ai + 1]; i++)
{
if (mat->pat->col[i] == aj)
{
mat->ele[i] += e;
flag = 1;
break;
}
}
if (flag == 0)
{
printf ("Insert a non-zero element to a zero entry!\n");
exit(-1);
}
}
return 0;
};
int mat_m_vec(const struct MATRIX *mat, const double *iv, double *ov)
{
int i, j;
double s;
for (i = 0; i < mat->pat->n; i++)
{
s = 0;
for (j = mat->pat->row[i]; j < mat->pat->row[i + 1]; j++)
s += mat->ele[j] * iv[mat->pat->col[j]];
ov[i] = s;
}
return 0;
};
int gs_step(const struct MATRIX *mat, double *x, const double *b)
{
int n = mat->pat->n;
int *row = mat->pat->row;
int *col = mat->pat->col;
double *ele = mat->ele;
double s = 0;
int i, j;
for (i = 0; i < n; i++)
{
s = b[i];
for (j = row[i] + 1; j < row[i + 1]; j++)
s -= ele[j] * x[col[j]];
x[i] = s / ele[row[i]];
}
};
int sor_step(const struct MATRIX *mat, double *x, const double *b, double w)
{
int n = mat->pat->n;
int *row = mat->pat->row;
int *col = mat->pat->col;
double *ele = mat->ele;
double s = 0;
int i, j;
for (i = 0; i < n; i++)
{
s = b[i];
for (j = row[i] + 1; j < row[i + 1]; j++)
s -= ele[j] * x[col[j]];
x[i] = s / ele[row[i]] * w + x[i] * (1 - w);
}
};
double res_norm(const struct MATRIX *mat, const double *x, const double *b)
{
int n = mat->pat->n;
int *row = mat->pat->row;
int *col = mat->pat->col;
double *ele = mat->ele;
double e, err = 0;
int i, j;
for (i = 0; i < n; i++)
{
e = b[i];
for (j = row[i]; j < row[i + 1]; j++)
e -= ele[j] * x[col[j]];
err += e * e;
}
return sqrt(err);
};
double read_matrix(const struct MATRIX *mat, int ai, int aj)
{
int n = mat->pat->n;
int *row = mat->pat->row;
int *col = mat->pat->col;
double *ele = mat->ele;
int j;
for (j = row[ai]; j < row[ai + 1]; j ++)
if (col[j] == aj)
return ele[j];
return 0.0;
}
int res(const struct MATRIX *mat, const double *x, const double *b, double *r)
{
int n = mat->pat->n;
int *row = mat->pat->row;
int *col = mat->pat->col;
double *ele = mat->ele;
int i, j;
for (i = 0; i < n; i++)
{
r[i] = -b[i];
for (j = row[i]; j < row[i + 1]; j++)
r[i] += ele[j] * x[col[j]];
}
return 0;
};
int pc_id(const struct MATRIX *mat, const double *v, double *w)
{
int i;
int n = mat->pat->n;
for (i = 0; i < n; i++)
w[i] = v[i];
};
int pc_ssor(const struct MATRIX *mat, const double *v, double *w, double omg)
{
int i, j;
int n = mat->pat->n;
int *row = mat->pat->row;
int *col = mat->pat->col;
double *ele = mat->ele;
for (i = 0; i < n; i++)
{
w[i] = v[i];
for (j = row[i] + 1; j < row[i + 1]; j++)
{
if (col[j] > i)
continue;
else
w[i] -= omg * ele[j] * w[col[j]] / ele[row[col[j]]];
}
}
for (i = n - 1; i >= 0; i--)
{
for (j = row[i] + 1; j < row[i + 1]; j++)
{
if (col[j] < i)
continue;
else
w[i] -= omg * ele[j] * w[col[j]];
}
w[i] /= ele[row[i]];
}
return 0;
};
int pc_im0(const struct MATRIX *mat, const double *v, double *w)
{
return 0;
};
|
C
|
#include "todo.h"
/**
* Just like fgets except it omits the newline at the end if there is one! Check out the man page for fgets!
*/
char *fgets_no_newline(char *buffer, int buf_length, FILE *stream) {
char *result = fgets(buffer, buf_length, stream);
if (result == NULL) {
return 0;
}
int line_length = strlen(buffer);
if (line_length > 0 && buffer[line_length - 1] == '\n') {
buffer[line_length - 1] = '\0';
}
return result;
}
/**
* Reads a todo_list item from a file and appends it to the Todo_list for you!. Assumes that the todo_list item will
* have its fields separated by newlines in the order:
*
* title
* description
* is_done (0 or 1)
* due_day
* due_month
* due_year
*
* @param stream The file stream to read from.
* @return 0 If an error occurred or if we reached the end of the file.
*/
int read_todo_list_item(FILE *stream) {
if (Todo_list_length >= TODO_LIST_MAX) {
return 0;
}
if (fgets_no_newline(Todo_list[Todo_list_length].title, TITLE_LENGTH_MAX, stream) == NULL) {
return 0;
}
if (fgets_no_newline(Todo_list[Todo_list_length].description, DESCRIPTION_LENGTH_MAX, stream) == NULL) {
return 0;
}
char num_buffer[10];
if (fgets(num_buffer, 10, stream) == NULL) {
return 0;
}
Todo_list[Todo_list_length].is_done = atoi(num_buffer);
if (fgets(num_buffer, 10, stream) == NULL) {
return 0;
}
Todo_list[Todo_list_length].due_day = atoi(num_buffer);
if (fgets(num_buffer, 10, stream) == NULL) {
return 0;
}
Todo_list[Todo_list_length].due_month = atoi(num_buffer);
if (fgets(num_buffer, 10, stream) == NULL) {
return 0;
}
Todo_list[Todo_list_length].due_year = atoi(num_buffer);
Todo_list_length++;
return 1;
}
|
C
|
#include <stdio.h>
#include<string.h>
#include<math.h>
#define MAX 5000
int dp[MAX+1][MAX+1];
int LCS(char a[],char b[],int n,int m)
{
if(n==0||m==0)
return 0;
if(dp[n][m]!=-1)
return dp[n][m];
if(a[n-1]==b[m-1])
return dp[n][m]=1+LCS(a,b,n-1,m-1);
else
return dp[n][m]=fmax(LCS(a,b,n-1,m),LCS(a,b,n,m-1));
}
int main()
{
memset(dp,-1,sizeof(dp));
int n,m;
printf("Enter the length of first string: ");
scanf("%d",&n);
char a[n];
printf("Enter the first string: ");
scanf("%s",&a);
printf("Enter the length of second string: ");
scanf("%d",&m);
char b[m];
printf("Enter the second string: ");
scanf("%s",&b);
printf("\n\nLength of longest common subsequence is %d\n",LCS(a,b,n,m));
}
|
C
|
#pragma once
// 3.2.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define MAX(x,y) ((x > y) ? x : y)
#define MIN(x,y) ((x < y) ? x : y)
#define SUM_OF_ANGLES 180
#define RIGHT_ANGLE 90
//--------------------------------------------------------------------------------------------
// Identify The Triangle
// ------------------------
//
// General : The program checks if the info about the triangle is valid and his kind.
//
// Input : Three numbers (angles).
//
// Process : The program check if the info is valid, order the angles from big to smalland check.
//
// Output : Prints the kind of the triangle, and if the info is valid.
//
//--------------------------------------------------------------------------------------------
// Programmer : Dror Tal
// Student No : 322534793
// Date : 11.9.2019
//--------------------------------------------------------------------------------------------
void typeOfTriangle(void)
{
// Variable definition
float firstAngle;
float secondAngle;
float thirdAngle;
float biggestAngle;
float middleAngle;
float smallestAngle;
printf("Give three angles\n");
scanf("%f %f %f", &firstAngle, &secondAngle, &thirdAngle);
// Check if the angles can present a triangle.
if (firstAngle + secondAngle + thirdAngle == SUM_OF_ANGLES)
{
// Check what is the biggest angle
biggestAngle = firstAngle;
biggestAngle = MAX(MAX(biggestAngle, secondAngle), thirdAngle);
smallestAngle = MIN(MIN(firstAngle, secondAngle), thirdAngle);
middleAngle = firstAngle + secondAngle + thirdAngle;
middleAngle -= biggestAngle + smallestAngle;
// Find the types of the triangle
// Check if the angles are the same
if (biggestAngle == middleAngle)
{
// Equilateral
if (biggestAngle == smallestAngle)
{
printf("The triangle is equilateral\n");
}
// Isosceles
else
{
printf("The triangle is an isosceles\n");
}
}
else
{
// Isosceles
if (middleAngle == smallestAngle)
{
printf("The triangle is an isosceles\n");
}
// Scalene
else
{
printf("The triangle is scalene\n");
}
}
// Obtuse
if (biggestAngle > RIGHT_ANGLE)
{
printf("The triangle has obtuse angle\n");
}
else
{
// Sharp
if (biggestAngle < RIGHT_ANGLE)
{
printf("The triangle has sharp angle\n");
}
// Right
else
{
printf("The triangle has right angle\n");
}
}
}
else
{
printf("The angles does't suit");
}
scanf("%f %f %f", &firstAngle, &secondAngle, &thirdAngle);
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *fp = fopen("./tmp.txt","w+");
if(fp == NULL)
{
perror("fopen error");
return -1;
}
fseek(fp,10,SEEK_END);
char * ptr = "今天天气很好\n";
// char ptr[] = "冬天适合睡懒觉\n";
int ret = fwrite(ptr,1,strlen(ptr),fp);
if(ret <= 0)
{
perror("fwrite error");
return -1;
}
printf("ret:%d\n",ret);
printf("\n");
fseek(fp,0,SEEK_SET);
char buf[1024] = {0};
ret = fread(buf,1,1023,fp);
if(ret == 0)
{
perror("fread error");
return -1;
}
printf("read buf:[%s]-[%d]\n",buf+10,ret);
fclose(fp);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE (!TRUE)
#define SIZE_STACK 100
typedef int EType;
typedef struct stack Stack;
struct stack {
int top;
EType elems[SIZE_STACK];
};
void initStack(Stack* stack);
int isEmpty(Stack* stack);
int isFull(Stack* stack);
int push(Stack* stack, EType value);
int pop(Stack* stack, EType* value);
void printStack(Stack* stack);
int main(int argc, char* argv[])
{
EType val = 0;
Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
pop(&stack, &val);
return 0;
}
void initStack(Stack* stack)
{
stack->top = -1;
memset(stack->elems, 0, sizeof(EType) * SIZE_STACK);
}
int isEmpty(Stack* stack)
{
return (stack->top == -1);
}
int isFull(Stack* stack)
{
return (stack->top >= SIZE_STACK - 1);
}
int push(Stack* stack, EType value)
{
if (isFull(stack)) return -1;
stack->top++;
stack->elems[stack->top] = value;
return value;
}
int pop(Stack* stack, EType* value)
{
if (isEmpty(stack)) return -1;
*value = stack->elems[stack->top];
stack->top--;
return *value;
}
void printStack(Stack* stack)
{
int pos = stack->top;
while (pos >= 0)
{
printf("%d ", stack->elems[pos--]);
}
printf("\n");
}
|
C
|
#include<stdio.h>
#include<math.h>
void main()
{
int percent;
printf("\nType percentage: ");
scanf("%d",&percent);
while(percent>100)
{
printf("give your correct percentage");
scanf("%d",&percent);
}
switch(percent/10)
{
case 0:
case 1:
case 2:printf("\n fail");break;
case 3:
case 4:printf("\n third division");break;
case 5:printf("\n second division");break;
case 6:
case 7:
case 8:
case 9:
case 10:printf("\n first division");break;
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
//Ѱҵ
//һֻdzһΣֶΡ
//дһҳֻһε֡
int main()
{
int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 };
int size = sizeof(arr) / sizeof(arr[0]);
int i, j;
//ѭÿѡȡһԪ
for (i = 0; i < size; i++)
{
//ѭԪѡȡǸԪؽбȽ
for (j = 0; j < size; j++)
{
if (i != j && arr[i] == arr[j])
{
break;
}
}
//1֮ͬԪأbreakִУ2ҲûҵͬԪأʱj==size
if (j == size)
{
printf("%d ", arr[i]);
}
}
return 0;
}
//
//int main()
//{
// double a;
// double b;
// double ret;
// char c;
// scanf("%lf%c%lf", &a, &c, &b);
// switch (c)
// {
// case '+':
// ret = a + b;
// printf("%0.4lf+%0.4lf=%0.4lf", a, b, ret);
// break;
// case '-':
// ret = a - b;
// printf("%0.4lf-%0.4lf=%0.4lf", a, b, ret);
// break;
// case '*':
// ret = a*b;
// printf("%0.4lf*%0.4lf=%0.4lf", a, b, ret);
// break;
// case '/':
// if (b == 0.0)
// {
// printf("Wrong!Division by zero!");
// break;
// }
// else
// {
// ret = a / b;
// printf("%0.4lf/%0.4lf=%0.4lf", a, b, ret);
// break;
// }
//
// default:
// printf("Invalid operation!");
// break;
//
// }
// return 0;
//}
|
C
|
#include <stdio.h>
#include <assert.h>
#define MAXLINE 5
int romanToArabic( char *roman );
char* transformString(char s[], int size);
int returnnumb( char *roman, int y, int x, int lpctr);
void test();
int main(int argc, char **argv){
if( argc==2 ){
/*printf("The roman numeral %s is equal to %d\n", \*/
/*argv[1], romanToArabic(argv[1]));*/
romanToArabic(argv[1]);
}
else{
printf("ERROR: Incorrect usage, try e.g. %s XXI\n", argv[0]);
}
return 0;
}
void test(){
}
int romanToArabic( char *roman ){
int i;
int total=0;
for(i=0; roman[i] != '\0'; i++){
/* Double letters */
if(roman[i] == 'I'){
if(roman[i+1]== 'V'){
total=total+returnnumb(roman, 'V', 4, i+1);
i++;
printf("%d\n", 4);
}
else if(roman[i+1] == 'X'){
total=total+returnnumb(roman, 'X', 9, i+1);
i++;
printf("%d\n", 9);
}
else{
total=total+returnnumb(roman, 'I', 1, i);
printf("%d\n", 1);
}
}
else if(roman[i] == 'X'){
if(roman[i+1] == 'L'){
total=total+returnnumb(roman, 'L', 40, i+1);
i++;
printf("%d\n", 40);
}
else if(roman[i+1] == 'C'){
total=total+returnnumb(roman, 'C', 90, i+1);
i++;
printf("%d\n", 90);
}
else{
total=total+returnnumb(roman, 'X', 10, i);
printf("%d\n", 10);
}
}
else if(roman[i] == 'C'){
if(roman[i+1] == 'D'){
total=total+returnnumb(roman, 'D', 400, i+1);
printf("%d\n", 400);
i++;
}
else if(roman[i+1] == 'M'){
total=total+returnnumb(roman, 'M', 900, i+1);
printf("%d\n", 900);
i++;
}
else{
total=total+returnnumb(roman, 'C', 100, i);
printf("%d\n", 100);
}
}
/* Singles */
else if(roman[i] == 'V'){
total=total+returnnumb(roman, 'V', 5, i);
printf("%d\n", 5);
}
else if(roman[i] == 'L'){
total=total+returnnumb(roman, 'L', 50, i);
printf("%d\n", 50);
}
else if(roman[i] == 'D'){
total=total+returnnumb(roman, 'D', 500, i);
printf("%d\n", 500);
}
else if(roman[i] == 'M'){
total=total+returnnumb(roman, 'M', 1000, i);
printf("%d\n", 1000);
}
}
printf("%d\n", total);
return 0;
}
int returnnumb( char *roman, int y, int x, int lpctr){
if(roman[lpctr] == y){
return x;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Struct - this is the struct of the information
* that an account have. It collects the information of
* the customer in the bank.
*
*/
struct
{
char accountNumber[20];
char pinCode[20];
int balance;
char name[20];
char sex[10];
}information[1000];
/*int createCounter - It is used to show that which one
* is empty. And it is also used to create a new account.
*
*
* int presentCounter - It is used to indicate which
* account number is being operated on.
*/
int createCounter, presentCounter;
int Counter();
void clearBuffer(void);
void welcomePage();
void thanksPage();
void valueStruct();
void askBankAccount();
void accountYes();
void accountNo();
void createAccount();
void checkPin();
void updateFile(int studentCounter);
void introduce();
void function();
void balance(int *o);
void transfer(int *t, int *o, int m2);
void withdraw(int *w, int *o);
void deposit(int *d, int *o);
void changePin();
void backPage();
/* main - 1--Welcome the user to use it.
* 2--Ask the user whether he has the BankAccount.
* 3--Introduce the user he has Logged in successfully.
* 4--Operate the function.
* 5--Thanks to the user for using it.
* 6--Write the data which have updated back to the FILE.
*
*/
int main (void)
{
welcomePage();
askBankAccount();
introduce();
function();
thanksPage();
updateFile(Counter());
return (0);
}
/* clearBuffer - makes the computer clear something
* useless. Something like wrong input from the user and
* something like invalid input. It can reduce the possibility
* of the incidents of the ERROR.
*
*/
void clearBuffer(void)
{
while (fgetc(stdin) != '\n');
}
/* Counter - tells the computer how many accounts should
* be written back to the File. It is a (int) function. The
* function returns the result of the count++.
*
* Parameters(written in the detailed function):
* (int count && char copyString[20]
* - int: count++ in the internal function.
* - char: used to tell when is the computer should stop
* writing the data back to the File.
* It just like a mark. I used "*" in my function.
*
* Return value (int): the number is the result of count++.
*
*/
int Counter()
{
int count = 0;
char copyString[20] = {'*'};
strcpy(information[createCounter + 1].accountNumber, copyString);
while ((strcmp(information[count].accountNumber, information[createCounter + 1].accountNumber) != 0) && count != 1000)
{
count++;
}
return count;
}
/* welcomePage - The function displays the given sentence
* which is used to welcome person to use it on screen.
* It is a (void) function.
*
*/
void welcomePage()
{
printf("Welcome to choose our bank!\n\n");
}
/* thanksPage - The function displays the given sentence
* which is used to thanks the person to use it. It is a
* (void) function.
*
*/
void thanksPage()
{
printf("\nThanks for your Using!\n");
}
/* valueStruct - The function tells the route of the File
* which I need to use during the operation. It gives the
* values(data) to the Struct which is created by my own.
* It is a (void) function.
*
* Parameters(written in the detailed function):
* int i - It plays a role to count the lines in the File.
* int count - It is used to tell the computer when should
* it stopped to give the values to the Struct.
* FILE *fp - It used to show the computer which FILE should
* be opened to use.
*
*/
void valueStruct()
{
int i = 0, count;
FILE *fp;
if (!(fp = fopen("tests.txt","r")))
{
fp = fopen("tests.txt","r");
}
while(count != EOF)
{
count = fscanf(fp, "%s %s %d %s %s", information[i].accountNumber, information[i].pinCode,
&(information[i].balance), information[i].name, information[i].sex);
i++;
}
createCounter = i - 1;
fclose(fp);
}
/* askBankAccount - ask the user whether he or she has an
* Bank Account in our system. If user enter "Yes", he will
* be taken into the function "accountYes". While, he will
* enter into the function "accountNo". This function will
* just allow user enter "1" && "2". If he entered something
* useless. The function will let him try again till he entered
* the valid input.
*
* Parameters(written in the detailed function):
* int choice1 - asks the user to enter his answer and deposit it.
* char character1 and int status - used in the readInteger.
*
*/
void askBankAccount()
{
int choice1;
char character1;
int status1;
printf("\nDo you have an account of our bank?\n\n");
printf("1.Yes\t2.No > ");
do
{
while ((status1 = scanf("%d%c", &choice1, &character1)) == 0 || (2 == status1 && character1 != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
switch (choice1)
{
default:
{
printf("\nERROR! Please enter valid number. > ");
}break;
case 1:
{
accountYes();
if (createCounter != 0)
{
checkPin();
break;
}
}
case 2:
{
accountNo();
}break;
}
}while(choice1 != 1 && choice1 != 2);
}
/* accountYes - It will make the user to enter his account number.
* And then, the computer will search the struct whether the input does exist.
* If there is no data in the struct when you first use it, the program will tell
* you that you should create an account first. But if you have already use it,
* you do not need to do it. What's more, if your input dose not exist. It will ask
* you whether you want to create right now.
*
* Parameters(written in the detailed function)
* int kSearching - it is used to represent its operating number.
* int kTemp - it is used to get the number from kSearching.
* int choice2, status and char character - they are used in readInteger
* and readString.
* char bankAccount[20] - It used to deposit your input.
*
*/
void accountYes()
{
int kSearching = 0, kTemp = 0, choice2, status;
char bankAccount[20], character;
valueStruct();
if (createCounter == 0)
{
printf("\nThere are no Accounts in the system!\n");
printf("You should create an Account in the system first.\n");
}
if (createCounter != 0)
{
printf("\nPlease enter your Bank Account > ");
fgets(bankAccount, 20, stdin);
if (bankAccount[strlen(bankAccount)-1] == '\n')
bankAccount[strlen(bankAccount)-1] = '\0';
else
clearBuffer();
printf("\nWe are searching for you.\n\nPlease wait a minute ^_^ . . .\n");
for(kSearching = 0; kSearching < 1000; kSearching++)
{
if (strcmp(bankAccount, information[kSearching].accountNumber) == 0)
{
kTemp = kSearching;
presentCounter = kSearching;
printf("\nMatching Successfully!\n");
break;
}
}
if(kSearching != kTemp)
{
do
{
printf("\nThe account you entered does not exist in our system.\n");
printf("\nDo you want to correct your input?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice2, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
if (choice2 != 1 && choice2 != 2)
{
printf("\nERROR!\nPlease enter a valid number!\n\nDo you want to correct your input?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice2, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
}
if (choice2 == 2)
{
askBankAccount();
}
if (choice2 == 1)
{
printf("Please correct your input(Bank Account) > ");
fgets(bankAccount, 20, stdin);
if (bankAccount[strlen(bankAccount)-1] == '\n')
bankAccount[strlen(bankAccount)-1] = '\0';
else
clearBuffer();
}
for(kSearching = 0; kSearching < 1000; kSearching++)
{
if (strcmp(bankAccount, information[kSearching].accountNumber) == 0)
{
break;
}
}
}while(choice2 == 1 && (strcmp(bankAccount, information[kSearching].accountNumber) != 0));
}
}
}
/* accountNo - This function is used to ask you whether you want
* to create a Bank Account right now. If yes, it will lead you to
* the function "createAccount". If not, it will ask you whether continue
* to use it. If yes, you can still use it. While, exit the program.
*
* Parameter(written in the detailed function):
* int choice3 - used to deposit the input whether you want to create an account.
* int choice4 - used to deposit the input whether continue to use ATM.
* int status - combined with int choice3 && int choice4 && char character to readInteger.
*
*/
void accountNo()
{
int choice3, choice4, status;
char character;
printf("\nDo you want to create an account of our bank right now?\n\n1.Yes\t2.No > ");
do
{
while ((status = scanf("%d%c", &choice3, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
switch(choice3)
{
default:
{
printf("ERROR!\nPlease enter valid number!\n");
}break;
case 1:
{
createAccount();
}break;
case 2:
{
exit(0);
}break;
}
}while(choice3 != 1 && choice3 != 2);
do
{
printf("\nDo you want to continue to use our ATM?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice4, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
if(choice4 == 1)
{
askBankAccount();
break;
}
else if (choice4 == 2)
{
updateFile(Counter());
exit (0);
}
else if (choice4 != 1 && choice4 != 2)
{
printf("\nERROR!\nPlease enter a valid number!");
}
}while (choice4 != 1 && choice4 != 2);
}
/* createAccount - This function is used to create a new account. If
* the number you give has been registered by others. It will let you to
* change your number. If created successfully. It will mark the next empty BankAccount with "*".
*
* Parameters(written in the detailed function):
* int status && int choice && char character - used to readInteger and readString.
* int kSearching - used to search whether your input does exist in our system. If yes,
* it will let you to change your input. If not, move to next step.
* int kTemp - used to be the requirements to justice whether you need to change your input.
* char name[20], sex[20], bankAccount[20], pinCode[20] - used to deposit your input(information).
* char copyString[20] - to be a mark.
*
*/
void createAccount()
{
valueStruct();
int status, kSearching = 0, choice, kTemp = 0;
char name[20], sex[20], bankAccount[20], pinCode[20], copyString[20] = {'*'}, character;
printf("\nThis is the interface for creating an Account in our Bank!\n");
printf("\nPlease enter your Name > ");
fgets(name, 20, stdin);
if (name[strlen(name)-1] == '\n')
name[strlen(name)-1] = '\0';
else
clearBuffer();
strcpy(information[createCounter].name, name);
printf("\nPlease enter your Sex (Mr or Mrs) > ");
fgets(sex, 20, stdin);
if (sex[strlen(sex)-1] == '\n')
sex[strlen(sex)-1] = '\0';
else
clearBuffer();
strcpy(information[createCounter].sex, sex);
if (createCounter == 0)
{
printf("\nPlease give the number for your Bank Account > ");
fgets(bankAccount, 20, stdin);
if (bankAccount[strlen(bankAccount)-1] == '\n')
bankAccount[strlen(bankAccount)-1] = '\0';
else
clearBuffer();
strcpy(information[createCounter].accountNumber, bankAccount);
printf("\nPlease set your PIN > ");
fgets(pinCode, 20, stdin);
if (pinCode[strlen(pinCode)-1] == '\n')
pinCode[strlen(pinCode)-1] = '\0';
else
clearBuffer();
strcpy(information[createCounter].pinCode, pinCode);
}
if (createCounter != 0)
{
do
{
printf("\nPlease give the number for your Bank Account > ");
fgets(bankAccount, 20, stdin);
if (bankAccount[strlen(bankAccount)-1] == '\n')
bankAccount[strlen(bankAccount)-1] = '\0';
else
clearBuffer();
for (kSearching = 0; kSearching < 1000; kSearching++)
{
if(strcmp(information[kSearching].accountNumber, bankAccount) == 0)break;
}
kTemp = 1;
if(kSearching == 1000) kTemp = 2;
if (kTemp == 1)
{
printf("\nThis account has been registered by others.");
printf("\nDo you want to continue to create an Account?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
if (choice == 2)
{
exit(0);
}
while (1)
{
if (choice != 1 && choice != 2)
{
printf("\nPlease enter a valid number > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
}
if (choice == 1 || choice == 2) break;
}
}
if (kTemp != 1)
{
strcpy(information[createCounter].accountNumber, bankAccount);
printf("\nPlease set your PIN > ");
fgets(pinCode, 20, stdin);
if (pinCode[strlen(pinCode)-1] == '\n')
pinCode[strlen(pinCode)-1] = '\0';
else
clearBuffer();
strcpy(information[createCounter].pinCode, pinCode);
information[createCounter].balance = 0;
strcpy(information[createCounter + 1].accountNumber, copyString);
}
}while(choice == 1 && kTemp == 1);
}
updateFile(Counter());
}
/* checkPin - This function is used to check your input(Pin) whether it is the
* pin for the corresponding account.
*
* Parameter(written in the detailed function):
* int status && int choice && choice2 && char character - used to readInteger.
* int choice - used to deposit your input for whether you want to correct your input.
* int choice2 - used to deposit whether you want to continue to use ATM.
* char pinCode[20] - used to ask the user to enter the PIN and deposit it.
*
*/
void checkPin()
{
int status, choice, n = 2, choice2;
char pinCode[20], character;
printf("\nPlease enter your PIN > ");
fgets(pinCode, 20, stdin);
if (pinCode[strlen(pinCode)-1] == '\n')
pinCode[strlen(pinCode)-1] = '\0';
else
clearBuffer();
if (strcmp(pinCode, information[presentCounter].pinCode) == 0)
{
printf("\nMatching Successfully!\n");
}
else
{
printf("\nWrong PIN!\nPlease check your input.\n");
printf("\nDo you want to correct your PIN?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
if (choice != 1 && choice != 2)
{
printf("\nPlease enter a valid number!\n\nDo you want to correct your PIN?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
}
if (choice == 1)
{
do
{
printf("\nYou only have %d chance(s) left.\nPlease correct your PIN > ", n);
fgets(pinCode, 20, stdin);
if (pinCode[strlen(pinCode)-1] == '\n')
pinCode[strlen(pinCode)-1] = '\0';
else
clearBuffer();
if (strcmp(pinCode, information[presentCounter].pinCode) == 0)
{
printf("\nMatching Successfully!\n");
break;
}
if (strcmp(pinCode, information[presentCounter].pinCode) != 0)
{
printf("\nWrong PIN!\n");
}
n--;
}while (n > 0 && (strcmp(pinCode, information[presentCounter].pinCode) != 0));
if (n == 0 && (strcmp(pinCode, information[presentCounter].pinCode) != 0))
{
printf("\nYour Bank Account has been locked!\n");
do
{
printf("\nDo you want to continue to use ATM?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice2, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
if (choice2 != 1 && choice2 != 2)
{
printf("\nWrong number. Please enter a valid number!\n");
}
if (choice2 == 1)
{
askBankAccount();
}
if (choice2 == 2)
{
exit(0);
}
}while (choice2 != 1 && choice2 != 2);
}
}
if (choice == 2)
{
askBankAccount();
}
}
}
/* updateFile - Make the computer write the information from the struct back to the File.
* Its work just like updating the data in the File.
*
* Parameters*(written in the detailed function):
* int i - used to count the operation times.
* int studentCounter - used to be the mark of the end
* for writing the data back to the FILE.
*
*/
void updateFile(int studentCounter)
{
int i;
FILE *fp;
if(!(fp = fopen("tests.txt","w")))
{
printf("\nSorry!\nSystem has broken!\n");
}
for (i = 0; i < studentCounter; i++)
{
fprintf(fp, "%s %s %d %s %s\n", information[i].accountNumber, information[i].pinCode,
information[i].balance, information[i].name, information[i].sex);
}
fclose(fp);
}
/* introduce - The function displays the given sentence
* which is used to introduce the person to use it on screen.
*
*/
void introduce()
{
printf("\nDear %s %s :\n", information[presentCounter].sex, information[presentCounter].name);
}
/* function - It contains most functions that ATM should have.
* Such as 1--Withdraw money, 2--Check the balance, 3--Deposit money,
* 4--Transfer money to another BankAccount which has been registered
* in the system, 5--Change PIN, 6--Back to the page above.
*
* Parameters(written in the detailed function)
* int choice - asks the user to enter his service and deposit it.
* int withdraw1, balance1, deposit1, transfer1 - used to give its initial value
* in this function.
* int i1 - used to search the No. of the account you want to transfer
* int status - Combined with int choice && char character && char account[20]
* to readInteger and readString.
*
*/
void function()
{
int choice, status, withdraw1 = 0, balance1 = 0, deposit1 = 0, transfer1 = 0;
char character;
balance1 = information[presentCounter].balance;
while (1)
{
do
{
printf("\nPlease choose your business:\t\n\n1--Withdraw\t2--Balance\n3--Deposit\t4--Transfer\n5--Change PIN\t6--Back");
printf("\n > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("You did not enter an integer, try again > ");
}
if (choice != 1 && choice != 2 && choice != 3 && choice != 4 && choice != 5 && choice != 6) printf("\nERROR! Please enter the correct number.");
}while ( choice != 1 && choice != 2 && choice != 3 && choice != 4 && choice != 5 && choice != 6);
switch(choice)
{
case 1:
{
printf("\nPlease enter the amount of the money you want to withdraw: \n");
while ((status = scanf("%d%c", &withdraw1, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("You did not enter an integer, try again > ");
}
withdraw(&withdraw1, &balance1);
}break;
case 2:
{
balance(&balance1);
}break;
case 3:
{
printf("\nPlease enter the amount of the money you want to deposit: ");
while ((status = scanf("%d%c", &deposit1, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("You did not enter an integer, try again > ");
}
deposit(&deposit1, &balance1);
}break;
case 4:
{
int choice2, i, i1;
char account[20];
printf("\nPlease enter the account which you want to transfer: ");
fgets(account, 20, stdin);
if (account[strlen(account)-1] == '\n')
account[strlen(account)-1] = '\0';
else
clearBuffer();
for (i = 0; i < 1000; i++)
{
if (strcmp(account, information[i].accountNumber) == 0)
{
i1 = i;
break;
}
}
if (i1 == i && i1 != presentCounter)
{
printf("\nThe name of the account you transfered is > %s %s\n", information[i1].sex, information[i1].name);
printf("\nPlease enter the amount of the money you want to transfer: ");
while ((status = scanf("%d%c", &transfer1, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("You did not enter an integer, try again > ");
}
transfer(&transfer1, &balance1, i1);
}
if (i1 != i)
{
printf("\nThe account you want to transfer does not exist in our bank.Please check!\n");
}
if (i1 == presentCounter)
{
printf("\nYou cannot transfer to yourself!\n");
}
}break;
case 5:
{
changePin();
}break;
case 6:
{
backPage();
}
}
printf("\nDo you want to continue to use our ATM?\n\n1--Continue\t2--Finish > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("You did not enter an integer, try again > ");
}
if (choice != 1 && choice != 2)
{
do
{
printf("\nERROR! Please enter a valid number > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("You did not enter an integer, try again > ");
}
}while (choice != 1 && choice != 2);
}
if (choice == 2) break;
}
information[presentCounter].balance = balance1;
}
/* balance - Tells the user how much money does his account have.
*
* Parameter:
* int *o - It is the first letter of "original". Used to get the
* address from the function "&balance".
*
*/
void balance(int *o)
{
*o = *o;
printf("\nYour balance is %d Euro.\n", *o);
}
/* transfer - Used to transfer your money to another bank account.
*
* Parameter:
* int *t - It is the first letter of "transfer". Used to get the address
* from the function "&transfer1".
* int *o - It is the first letter of "original". Used to get the address
* from the function "&balance1".
* int m2 - used to get the value from the function "i1"(which has been explained above);
*
*/
void transfer(int *t, int *o, int m2)
{
if (*t > *o)
{
printf("\nYour balance is insufficient!\n");
}
if (*t < *o)
{
*o = *o - *t;
information[m2].balance = *t + information[m2].balance;
printf("\nYour balance is %d Euro.\n", *o);
}
}
/* withdraw - Used to withdraw money from the bank account, also
* show the balance to the user after withdrawing.
*
* Parameter:
* int *w - It is the first letter of "withdraw". Used to get the address
* from the function - "&withdraw1".
* int *o - It is the first letter of "original". Used to get the address
* from the function - "&balance1".
* int x, int y - show the numbers for 50 Euro, numbers for 20 Euro.
*
*/
void withdraw(int *w, int *o)
{
int x, y;
if (*o >= *w)
{
if(*w % 10 == 0 && *w != 30 && *w != 10)
{
if ((*w % 50) % 20 == 0)
{
x = *w/50;
y = (*w % 50)/20;
}
else if (*w % 50 == 0)
{
x = *w/50;
y = 0;
}
else
{
x = (*w/50) - 1;
y = (*w - (x * 50))/20;
} printf("\nYou will be given as--> %d * 50 and %d * 20\n", x, y);
printf("\nPlease collect your money.\n");
*o = *o - *w;
}
else
{
printf("\nPlease enter correct number!\n");
}
}
else printf("\nYour balance is insufficient.\n"); if(*o >= *w)printf("\nYour balance right now is %d Euro.\n", *o);
}
/* deposit - Used to deposit money, and tell the user how much money does
* he have after that.
*
* Parameters:
* int *d - It is the first letter of "deposit". Used to get address from the
* function - "&deposit1".
* int *o - It is the first letter of "original". Used to get address from the
* function - "&balance1"
*
*/
void deposit(int *d, int *o)
{
*o = *o + *d;
printf("\nYour balance right now is %d Euro.\n", *o);
}
/* changePin - This function can make the user change his PIN.
*
* Parameters(written in the detailed function)
* int choice3 - used to ask the user whether continue to change his PIN
* int chances - used to tell the user how many times does he can try his PIN
* char pin[20] - used to ask the user to enter his original pin and deposit it
* int status - combined with int choice3 && char character && char pin[20] to readInteger
* and readString
*
*/
void changePin()
{
int status;
int chances = 3, choice3;
char character, pin[20];
printf("\nThis is the interface for changing your PIN!\n");
printf("\nPlease enter your original PIN >");
fgets(pin, 20, stdin);
if (pin[strlen(pin)-1] == '\n')
pin[strlen(pin)-1] = '\0';
else
clearBuffer();
if (strcmp(pin, information[presentCounter].pinCode) == 0)
{
printf("\nPlease set your NEW PIN > ");
fgets(pin, 20, stdin);
if (pin[strlen(pin)-1] == '\n')
pin[strlen(pin)-1] = '\0';
else
clearBuffer();
strcpy(information[presentCounter].pinCode, pin);
printf("\nChanging Successfully!\n");
}
else
{
do
{
chances--;
printf("\nWrong PIN! Please check your original input (PIN)\nYou only have %d chance(s) left.\n", chances);
printf("\nDo you want to change your PIN?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice3, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("You did not enter an integer, try again > ");
}
if (choice3 == 1)
{
printf("\nPlease enter your original PIN > ");
fgets(pin, 20, stdin);
if (pin[strlen(pin)-1] == '\n')
pin[strlen(pin)-1] = '\0';
else
clearBuffer();
if (strcmp(pin, information[presentCounter].pinCode) == 0)
{
printf("\nPlease set your NEW PIN > ");
fgets(pin, 20, stdin);
if (pin[strlen(pin)-1] == '\n')
pin[strlen(pin)-1] = '\0';
else
clearBuffer();
strcpy(information[presentCounter].pinCode, pin);
printf("\nChanging Successfully!\n");
break;
}
}
else if (choice3 == 2)
{
break;
}
} while (chances != 0 && choice3 != 1 && choice3 != 2);
}
}
/* backPage - used to make the user get back to the page above
* int choice - asks the user to enter his option to whether continue to use ATM,
* and deposits it.
* int status - combined with int choice && char character to readInteger
*
*/
void backPage()
{
int choice, status;
char character;
do
{
printf("\nDo you want to continue to use ATM?\n\n1.Yes\t2.No > ");
while ((status = scanf("%d%c", &choice, &character)) == 0 || (2 == status && character != '\n')) {
clearBuffer();
printf("\nYou did not enter an integer, try again > ");
}
if (choice == 1)
{
introduce();
function();
}
if (choice == 2)
{
updateFile(Counter());
exit(0);
}
if (choice != 1 && choice != 2)
{
printf("\nPlease enter a valid number > ");
}
}while (choice != 1 && choice != 2);
}
|
C
|
#include <stdio.h>
#define N 10
int main(int argc, char *argv[])
{
int a,i,j,f[N]={0};
while(scanf("%d",&a)!=EOF)
{
for(i=0;a!=0;i++)
{
f[i]=a%10;
a=a/10;
}
for(j=0;j<=i-1;j++) printf("%d ",f[j]);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: juancarlosmartineznavas <juancarlosmart +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/16 00:04:01 by juancarlosm #+# #+# */
/* Updated: 2020/03/21 19:25:22 by juancarlosm ### ########.fr */
/* */
/* ************************************************************************** */
#include "philone.h"
static void *display_count(void *philosopher_status)
{
t_list *condition;
int i;
int total;
condition = (t_list*)philosopher_status;
total = 0;
while (total < condition->times_to_eat)
{
i = 0;
while (i < condition->total)
pthread_mutex_lock(&condition->philosophers[i++].main_eat);
total++;
}
show_text(&condition->philosophers[0], TYPE_OVER);
pthread_mutex_unlock(&condition->philosopher_dead);
return ((void*)0);
}
static void *take_display(void *philosopher_status)
{
t_listtwo *philosopher;
philosopher = (t_listtwo*)philosopher_status;
while (1)
{
pthread_mutex_lock(&philosopher->main_mutex);
if (!philosopher->eat && take_the_time() > philosopher->limit)
{
show_text(philosopher, TYPE_DIED);
pthread_mutex_unlock(&philosopher->main_mutex);
pthread_mutex_unlock(&philosopher->status->philosopher_dead);
return ((void*)0);
}
pthread_mutex_unlock(&philosopher->main_mutex);
usleep(1000);
}
}
static void *loop(void *philosopher_status)
{
t_listtwo *philosopher;
pthread_t tid;
philosopher = (t_listtwo*)philosopher_status;
philosopher->final_eat = take_the_time();
philosopher->limit = philosopher->final_eat + philosopher->status->dying;
if (pthread_create(&tid, NULL, &take_display, philosopher_status) != 0)
return ((void*)1);
pthread_detach(tid);
while (1)
{
run_forks(philosopher);
philosophers_eating(philosopher);
remove_forks(philosopher);
show_text(philosopher, TYPE_THINK);
}
return ((void*)0);
}
static int sons(t_list *condition)
{
int i;
void *philosopher;
pthread_t tid;
condition->start = take_the_time();
if (condition->times_to_eat > 0)
{
if (pthread_create(&tid, NULL, &display_count, (void*)condition) != 0)
return (1);
pthread_detach(tid);
}
i = 0;
while (i < condition->total)
{
philosopher = (void*)(&condition->philosophers[i]);
if (pthread_create(&tid, NULL, &loop, philosopher) != 0)
return (1);
pthread_detach(tid);
usleep(100);
i++;
}
return (0);
}
int main(int argc, char const **argv)
{
t_list p;
if (argc < 5 || argc > 6)
return (print_error("error: bad arguments\n"));
if (start(&p, argc, argv))
return (clean_semaphore(&p) && print_error("error: fatal\n"));
if (sons(&p))
return (clean_semaphore(&p) && print_error("error: fatal\n"));
pthread_mutex_lock(&p.philosopher_dead);
pthread_mutex_unlock(&p.philosopher_dead);
clean_semaphore(&p);
return (0);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}s_noode;
void main()
{
struct node *n1,*n2;
printf("enter the number \n");
n1= (s_noode*)malloc(sizeof( s_noode));
scanf("%d",&n1->data);
printf("enter the second the number : \n");
n2=(s_noode*)malloc(sizeof (s_noode));
scanf("%d",&n2->data);
printf("first number = %d\n",n1->data );
printf("second number=%d\n",n2->data );
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr1[10] = {1, 0, 0, 1, 0, 1, 1, 1, 0, 1};
int arr2[10] = {0, 0, 1, 1, 1, 1, 0, 0, 0, 1};
int arr3[10] = {0};
for(int i = 0; i < 10; i++) {
arr3[i] = arr1[i] & arr2[i];
}
for(int i = 0; i < 10; i++) {
printf("%d\n", arr3[i]);
}
return 0;
}
|
C
|
// Login Signup module
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct login_signup *ls;
struct login_signup
{
char name[30], email[30],dob[10],pwd[40],cnfrm_pwd[40], father[30];
char city[30];
int age;
char mobile[10], whatsup[10];
}details[2];
void signup(int);
void login(ls,char*, char*,int);
int validate(ls,int);
void display(ls,int);
int main()
{
int choice,i;
char lemail[30],lpwd[30];
printf("\t\t\tWelcome to Gomathi's website!!\n");
printf("\t\t\t\tSignup\t");
printf("Login\n");
for(i=0;i<2;i++)
{
printf("Enter a choice Signup or Login:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
signup(i);
break;
}
case 2:
{
printf("Enter your email id:\n");
scanf("%s",lemail);
printf("Enter your lpwd:\n");
scanf("%s",lpwd);
login(details,lemail,lpwd,i);
break;
}
case 3:
{
exit(1);
}
default:
{
printf("Please enter a valid operation!!");
}
}
}
}
//Collecting data from the user
void signup(int i)
{
int j;
printf("Enter your name:\n");
scanf("%s",details[i].name);
printf("----------------------\n");
printf("Enter your age:\n");
scanf("%d",&details[i].age);
printf("----------------------\n");
printf("Enter your mobile number:\n");
scanf("%s",details[i].mobile);
printf("----------------------\n");
printf("Enter your whatsup number:\n");
scanf("%s",details[i].whatsup);
printf("----------------------\n");
printf("Enter your father's name:\n");
scanf("%s",details[i].father);
printf("----------------------\n");
printf("Enter your date of birth:\n");
scanf("%s",details[i].dob);
printf("Enter your home town:\n");
scanf("%s",details[i].city);
printf("----------------------\n");
printf("Enter your email-id:\n");
scanf("%s",details[i].email);
printf("----------------------\n");
printf("Enter your password:\n");
scanf("%s",details[i].pwd);
printf("----------------------\n");
printf("Confirm password:\n");
scanf("%s",details[i].cnfrm_pwd);
printf("----------------------\n");
j = validate(details,i);
if(j)
{
printf("Welcome %s\n",details[i].name);
}
}
int validate(ls details, int i)
{
int j = 0,flag = 0;
for(j=0;details[i].name[j]!='\0';j++)
{
if(!((details[i].name[j] >= 'a' && details[i].name[j]!= 'z') || details[i].name[j] >= 'A' && details[i].name[j] <= 'Z' ))
{
printf("Enter a valid name!!\n");
break;
}
else
{
continue;
}
}
if(details[i].age <= 0 && details[i].age >= 100)
{
printf("Please enter a valid age!!\n");
}
if(strlen(details[i].mobile) <= 10)
{
printf("Please enter a valid mobile number!!\n");
}
if(strlen(details[i].whatsup) <= 0 && strlen(details[i].whatsup) > 10)
{
printf("Please enter a valid whatsup number!!\n");
}
for(j=0;details[i].father[j]!='\0';j++)
{
if(!((details[i].father[j] >= 'a' && details[i].father[j]!= 'z') || details[i].father[j] >= 'A' && details[i].father[j] <= 'Z' ))
{
printf("Enter a valid name!!\n");
break;
}
else
{
continue;
}
}
if(strlen(details[i].pwd) >= 8)
{
for(j=0;j < strlen(details[i].pwd);j++)
{
if(!((details[i].pwd[j] >= 'a' && details[i].pwd[j]!= 'z') || (details[i].pwd[j] >= 'A' && details[i].pwd[j] <= 'Z')) && (details[i].pwd[j] >= '!' && details[i].pwd[j] <= '9'))
{
flag = 1;
}
}
if(flag==1)
{
if((strcmp(details[i].pwd,details[i].cnfrm_pwd)))
{
printf("Please enter correct password!!\n");
}
else
{
return 1;
}
}
else
{
printf("Please give some alphanumeric characters for strong password!!");
return 0;
}
}
if(strlen(details[i].pwd) < 8)
{
printf("Please enter atlease 8 characters!!");
return 0;
}
return 1;
}
void login(ls details,char *lemail, char *lpwd,int i)
{
int j;
for(j = 0;j<i-1;j++)
{
if(!(strcmp(details[j].email,lemail)))
{
if(!(strcmp(details[j].pwd, lpwd)))
{
printf("Welcome %s",details[j].name);
}
else
{
printf("Invalid password!!");
}
}
else
{
printf("Account does not exist, please signup!!");
}
}
}
/*void display(ls details,int i)
{
printf("%s\n",details[i].name);
printf("%d\n",details[i].age);
printf("%s\n",details[i].mobile);
printf("%s\n",details[i].whatsup);
printf("%s\n",details[i].father);
printf("%s\n",details[i].dob);
printf("%s\n",details[i].email);
printf("%s\n",details[i].pwd);
printf("%s\n",details[i].cnfrm_pwd);
printf("%s\n",details[i].city);
}*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
* usando variaveis - do tipo char
* desenvolvido por Caio Marcandali
* 02/05/2016
*/
int main(int argc, char *argv[]) {
//declarando uma variavel do tipo char ( tabela ascii)
//nome -> nome da variavel [30] aceuta ate 30 caracteres
char nome[30];
printf("digite o seu nome\n");
// a linha abaixo captura o que foi digitado no console e armazena na variavel nome
gets(nome);
system("CLS");
system("color 1e");
// a linha abaixo concatena (juntar, unir) um texto com o conteudo da variavel nome
// % -> S <- se refere ao tipo da variavel (char)
printf("Bem vindo %s\n",nome);
system("pause");
return 0;
}
|
C
|
//sum of all numbers between m and n
#include<stdio.h>
int main()
{
int i,n,m,sum=0;
printf("\nEnter first number : ");
scanf("%d",&n);
printf("\nEnter second number : ");
scanf("%d",&m);
for(i=n;i<=m;i++)
sum=sum+i;
printf("\nSum of numbers between %d and %d is : %d \n",n,m,sum);
return 0;
}
|
C
|
#include <stdio.h>
int
main ()
{
int x = 3;
printf ("Hello\n");
x = x + 1;
printf ("x is %d\n", x);
x = x - 2;
printf ("bye");
return 0;
}
|
C
|
#include "buzzer.h"
TIM_HandleTypeDef htimer2;
uint8_t buzzer_melody; // This variable storage number of buzzer melody. Param: @BUZZER_MELODY
volatile uint32_t buzzer_freq; // This variable storage number of buzzer frequency. Param: @BUZZER_FREQUENCY
/*
* @fn - buzzer_init
*
* @return - None
*
* @Note - Buzzer initialization function
*/
void buzzer_init()
{
/*
* Timer 2 is initialized in OC mode
*/
TIM_OC_InitTypeDef tim2OC_init;
htimer2.Instance = TIM2;
htimer2.Init.Period = 0xFFFFFFFF;
htimer2.Init.Prescaler = 8 - 1; // 1MHz
if(HAL_TIM_OC_Init(&htimer2) != HAL_OK)
{
error_handler();
}
tim2OC_init.OCMode = TIM_OCMODE_TOGGLE;
tim2OC_init.OCPolarity = TIM_OCPOLARITY_HIGH;
tim2OC_init.Pulse = 1000;
if(HAL_TIM_OC_ConfigChannel(&htimer2, &tim2OC_init, TIM_CHANNEL_2) != HAL_OK)
{
error_handler();
}
/*
* Basic setting of buzzer melody and frequency
*/
buzzer_melody = BUZZER_MELODY_1;
buzzer_freq = BUZZER_250HZ;
}
/*
* @fn - buzzer_set_melody
*
* @param[in] - melody - param: @BUZZER_MELODY
*
* @return - None
*
* @Note - Set buzzer melody
*/
void buzzer_set_melody(uint8_t melody)
{
buzzer_melody = melody;
}
/*
* @fn - buzzer_start
*
* @return - None
*
* @Note - Buzzer start buzz
*/
void buzzer_start(void)
{
if(HAL_TIM_OC_Start_IT(&htimer2, TIM_CHANNEL_2) != HAL_OK)
{
error_handler();
}
}
/*
* @fn - buzzer_stop
*
* @return - None
*
* @Note - Buzzer stop buzz
*/
void buzzer_stop(void)
{
if(HAL_TIM_OC_Stop_IT(&htimer2, TIM_CHANNEL_2) != HAL_OK)
{
error_handler();
}
}
/*
* This callback is responsible for different frequency of buzzer melody (buzzer_freq variable inside)
*/
void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim)
{
uint32_t crr_content;
if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
{
crr_content = HAL_TIM_ReadCapturedValue(&htimer2, TIM_CHANNEL_2);
__HAL_TIM_SET_COMPARE(&htimer2, TIM_CHANNEL_2, crr_content + buzzer_freq);
}
}
|
C
|
#include<stdio.h>
int isPalindrome(char *arr,int size)
{
int start=0;
int end=size-1;
int i=0;
for(;i<(size/2);i++)
{
if(arr[start]!=arr[end])
{
return -1;
}
start++;
end--;
}
return 1;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <time.h>
// Forward Declarations
int install_handler(int sig, void (*handler)(int));
void sigint_handler(int sig);
void sigtstp_handler(int sig);
void sigquit_handler(int sig);
int read_and_echo();
/* main
* Install the necessary signal handlers, then call read_and_echo().
*/
int main(int argc, char** argv) {
sigset_t old;
sigset_t full;
sigfillset(&full);
printf("%d\n", getpid());
// Ignore signals while installing handlers
sigprocmask(SIG_SETMASK, &full, &old);
//Install signal handlers
if(install_handler(SIGINT, &sigint_handler))
perror("Warning: could not install handler for SIGINT");
if(install_handler(SIGTSTP, &sigtstp_handler))
perror("Warning: could not install handler for SIGTSTP");
if(install_handler(SIGQUIT, &sigquit_handler))
perror("Warning: could not install handler for SIGQUIT");
// Restore signal mask to previous value
sigprocmask(SIG_SETMASK, &old, NULL);
read_and_echo();
return 0;
}
int time_start = 0;
int signal_sum = 0;
/* install_handler
* Installs a signal handler for the given signal
* Returns 0 on success, -1 on error
*/
int install_handler(int sig, void (*handler)(int)) {
// TODO: Use sigaction() to install a the given function
// as a handler for the given signal.
struct sigaction my_sig;
my_sig.sa_handler = handler;
my_sig.sa_flags = SA_RESTART;
sigemptyset(&my_sig.sa_mask);
sigaddset(&my_sig.sa_mask, SIGINT);
sigaddset(&my_sig.sa_mask, SIGTSTP);
sigaddset(&my_sig.sa_mask, SIGQUIT);
return sigaction(sig, &my_sig, NULL);
}
/* sigint_handler
* Respond to SIGINT signal (CTRL-C)
*
* Argument: int sig - the integer code representing this signal
*/
void sigint_handler(int sig) {
printf("SIGINT CAUGHT %i\n", sig);
signal_sum = 1;
time_start = time(NULL);
}
/* sigtstp_handler
* Respond to SIGTSTP signal (CTRL-Z)
*
* Argument: int sig - the integer code representing this signal
*/
void sigtstp_handler(int sig) {
printf("SIGSTP CAUGHT %i\n", sig);
if( (signal_sum == 1) && ((time(NULL) -time_start ) < 2000) ){
signal_sum = 2;
}
else{
signal_sum = 0;
}
}
/* sigquit_handler
* Catches SIGQUIT signal (CTRL-\)
*
* Argument: int sig - the integer code representing this signal
*/
void sigquit_handler(int sig) {
printf("SIGQUIT CAUGHT %i\n", sig);
if( (signal_sum == 2) && ((time(NULL) -time_start ) < 2000) ){
printf("Foiled again!\n");
exit(0);
}
else{
signal_sum = 0;
}
}
/* read_and_echo
* Read input from stdin, echo to stdout.
* Return 0 on EOF, -1 on error
*/
int read_and_echo() {
// TODO: Read from stdin and write to stdout
// Use the async-signal-safe syscalls read() and write()
char buf[1024];
memset(buf, 0, sizeof(buf));
ssize_t n;
while( (n=read(STDIN_FILENO, buf, sizeof(buf) )) > 0 ){
printf("%i\n", signal_sum);
if( write(STDOUT_FILENO, buf, sizeof(buf) ) == -1){
(void)write(2, "lololol broke\n", 15);
exit(1);
}
}
return -1;
}
|
C
|
#include <stdio.h>
int main(){
double m, a, t, vel, espaco, trabalho;
scanf("%lf", &m);
scanf("%lf", &a);
scanf("%lf", &t);
vel= a * t * 3.6;
espaco= (a * t * t) / 2;
trabalho= ((m * 1000) * (a * t) * (a * t)) / 2;
printf("VELOCIDADE = %.2lf \n", vel);
printf("ESPACO PERCORRIDO = %.2lf \n", espaco);
printf("TRABALHO REALIZADO = %.2lf \n", trabalho);
return 0;
}
|
C
|
int putchar(int i);
void print(char *s) {
while (*s != '\0') {
putchar((int) *s);
s++;
}
}
void _start()
{
print("Hello, world\n");
}
|
C
|
#include<stdio.h>
#include<string.h>
void main() {
char info[20];
printf("Input : ");
scanf("%[^\n]",info);
printf("Output : ");
printf("%ld\n",strlen(info));
}
/*
* Input : India is my
Output : 11
*/
|
C
|
#include <stdio.h>
#define K 10
int matrix[K][K] =
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 9 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 9, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 8, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 7, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 6, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 5, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 4, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 3, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
void MatrixSort()
{
int col = 0, row = K - 1, col_now, row_now, col1 = 0, row1 = K - 1;
int N = 10;
for (int j = 0; j < 10; j++)
{
int counter = matrix[col1][row1];
for (int i = 0; i < N; i++)
{
if (matrix[col][row] <= counter)
{
counter = matrix[col][row];
col_now = col;
row_now = row;
}
col += 1;
row -= 1;
}
matrix[col_now][row_now] = matrix[col1][row1];
matrix[col1][row1] = counter;
N -= 1;
row1 -= 1;
col1 += 1;
row = row1;
col = col1;
}
}
void print(int A[][10], int N, int M)
{
for (int R = 0; R < N; R++) {
for (int C = 0; C < M; C++)
printf_s("%d", A[R][C]);
printf_s("\n");
}
}
int main()
{
print(matrix, K, K);
MatrixSort();
printf("\n");
print(matrix, K, K);
return 1;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.