language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZ2 156
int main( ) {
FILE *pfile = NULL;
char*filename = "exercise_11.txt";
fpos_t position;
pfile = fopen (filename, "a");
if(pfile==NULL)
printf("Failed to open %s.\n",filename);
char str[60] = "\ntest of ftell()";
fputs(str,pfile);
long fpos = ftell(pfile);
printf("position: %ld\n",fpos);
fputs(str,pfile);
fgetpos(pfile, &position);
fsetpos(pfile, &position);
char str2[60] = "\nnew string";
fputs(str2,pfile);
printf("position: %ld\n",fpos);
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/* Lowercases all letters in str */
void toLower(char* str) {
int i, length;
length = strlen(str);
for (i = 0; i < length; ++i)
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] += 'a' - 'A';
}
/* Returns allocated string */
char* removeAll(char* original, char* toRemove) {
int original_length, remove_length, new_length;
int i, j;
char* result;
original_length = strlen(original);
remove_length = strlen(toRemove);
result = calloc(original_length, 1);
new_length = 0;
for (i = 0; i < original_length; ++i) {
for (j = 0; j < remove_length; ++j) {
if (original[i] == toRemove[j])
break;
}
if (j == remove_length) {
result[new_length] = original[i];
++new_length;
}
}
result[new_length] = 0;
return result;
}
int main(void) {
char *original, *disemvoweled, *vowels;
size_t sentence_length;
/* Initialize variables */
original = NULL;
sentence_length = 0;
/* Request and receive input */
printf("Enter sentence to disemvowel!\n");
getline(&original, &sentence_length, stdin);
toLower(original);
/* Make new strings with removed letters */
disemvoweled = removeAll(original, "aeiou !\n");
vowels = removeAll(original, "bcdfghjklmnpqrstvwxyz \n");
/* Print results */
printf("%s\n", disemvoweled);
printf("%s\n", vowels);
free(original);
free(disemvoweled);
free(vowels);
return 0;
}
|
C
|
//Fail - Partial Solution
#include "ft_list.h"
int ft_list_size(t_list *begin_list){
int counter = 1;
while(begin_list->next != 0){
counter++;
begin_list = begin_list->next;
}
return(counter);
}
//*Testing Only
|
C
|
#include <stdio.h>
#define YAMIDI_IMPLEMENTATION
#include "yamidi.h"
void printMsg(struct midiMsg_s msg) {
switch(msg.status) {
case midiStatusNoteOff:
printf("Note Off, chan=%d, key=%d, vel=%d\n",
msg.params.midiParamNoteOff.chan,
msg.params.midiParamNoteOff.key,
msg.params.midiParamNoteOff.vel);
break;
case midiStatusNoteOn:
printf("Note On, chan=%d, key=%d, vel=%d\n",
msg.params.midiParamNoteOn.chan,
msg.params.midiParamNoteOn.key,
msg.params.midiParamNoteOn.vel);
break;
case midiStatusPolyAT:
printf("PolyAT, chan=%d, key=%d, vel=%d\n",
msg.params.midiParamPolyAT.chan,
msg.params.midiParamPolyAT.key,
msg.params.midiParamPolyAT.vel);
break;
case midiStatusCC:
printf("CC, chan=%d, ctrl=%d, vll=%d\n",
msg.params.midiParamCC.chan,
msg.params.midiParamCC.ctrl,
msg.params.midiParamCC.val);
break;
case midiStatusProgramChange:
printf("ProgramChange, chan=%d, prog=%d\n",
msg.params.midiParamProgramChange.chan,
msg.params.midiParamProgramChange.prog);
break;
case midiStatusChannelAT:
printf("ChannelAT, chan=%d, vel=%d\n",
msg.params.midiParamChannelAT.chan,
msg.params.midiParamChannelAT.vel);
break;
case midiStatusPitchBend:
printf("Pitch Bend, chan=%d, val=%d\n",
msg.params.midiParamPitchBend.chan,
msg.params.midiParamPitchBend.val);
break;
default:
printf("unknown midi msg\n");
}
}
int main() {
struct midiBytes_s raw;
raw = genMidiMessage(
(struct midiMsg_s) {
.status = midiStatusNoteOn,
.params.midiParamNoteOn = {.chan=5, .key=10, .vel=60}});
for (int i=0; i<raw.len; i++) {
printf ("%02x ",raw.data[i]);
}
printf("\n");
int state = 0;
struct midiMsg_s msg;
if (parseMidiByte(0x85, &msg, &state)) {printf("error on line %d\n", __LINE__);}
if (parseMidiByte(0x01, &msg, &state)) {printf("error on line %d\n", __LINE__);}
if (!parseMidiByte(0x02, &msg, &state)) {printf("error on line %d\n", __LINE__);}
printMsg(msg);
return 0;
}
|
C
|
// 13 -wap to create array 10 elements accept 10 no. from the user and store it in an array
// then accept a no. from the user to search in an array.(linear search)
#include<stdio.h>
int main(){
int num[10]={1,2,3,4,5,6,7,8,9,10};
int cnt;
int usernumber;
printf("Enter number to be serched in an array\n");
scanf("%d",&usernumber);
for(cnt=0;cnt<10;cnt++)
{
if(usernumber == num[cnt])
{
printf("no.%dfound in an array at position : %d\n",usernumber,cnt);
break;
}
if(cnt == 10)
{
printf("no.not found in an array\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
union A
{
short c;
char buf[4];
}x;
int main()
{
union A x;
//x.buf={'0x02','0x01','0x03','0x04'};
x.buf[0] = 0x02;
x.buf[1] = 0x01;
x.buf[2] = 0x03;
x.buf[3] = 0x04;
printf("%p\n",x.c);
return 0;
}
|
C
|
/* b = A*x
* A: lower triangular of matrix A
* irow: row index
* pcol: col pointer
* val: matrix val
* diag: diag value of A
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void smv(int *irow, int *pcol, double *val, double *x, double *b, int n){
int i, j;
double sum;
for(i=0; i<n; i++){
b[i] = 0.0;
}
for(i=0; i<n; i++){
sum = val[pcol[i]]*x[i];
for(j=pcol[i]+1; j<pcol[i+1]; j++){
b[irow[j]] += val[j]*x[i];
sum += val[j]*x[irow[j]];
}
b[i] += sum;
}
}
|
C
|
#include "sim.h"
#include <stdlib.h>
struct device * new_device(struct sim_state *s)
{
struct device_list *d = calloc(1, sizeof *d);
d->next = NULL;
struct device_list ***p = &s->machine.last_device;
**p = d;
*p = &d->next;
return &d->device;
}
static int devices_does_match(const int32_t *addr, const struct device *device)
{
if (*addr <= device->bounds[1]) {
if (*addr >= device->bounds[0]) {
return 0;
} else {
return -1;
}
} else {
return 1;
}
}
int dispatch_op(void *ud, int op, int32_t addr, int32_t *data)
{
struct sim_state *s = ud;
struct device *device = NULL;
for (struct device_list *dl = s->machine.devices; dl && !device; dl = dl->next)
if (devices_does_match(&addr, &dl->device) == 0)
device = &dl->device;
if (device == NULL) {
fprintf(stderr, "No device handles address %#x\n", addr);
return -1;
}
// TODO don't send in the whole simulator state ? the op should have
// access to some state, in order to redispatch and potentially use other
// machine.devices, but it shouldn't see the whole state
int result = device->ops.op(device->cookie, op, addr, data);
if (s->conf.verbose > 2) {
fprintf(stderr, "%-5s @ 0x%08x = 0x%08x\n",
(op == OP_WRITE) ? "write" : "read", addr, *data);
}
return result;
}
int devices_setup(struct sim_state *s)
{
s->machine.devices = NULL;
s->machine.last_device = &s->machine.devices;
return 0;
}
int devices_finalise(struct sim_state *s)
{
int rc = 0;
for (struct device_list *d = s->machine.devices; d; d = d->next)
rc |= d->device.ops.init(&s->plugin_cookie, &d->device, &d->device.cookie);
return rc;
}
int devices_teardown(struct sim_state *s)
{
int rc = 0;
for (struct device_list *d = s->machine.devices, *e; d; d = e) {
e = d->next;
int result = d->device.ops.fini(d->device.cookie);
if (result)
debug(1, "Finalising device %p (cookie %p) returned %d",
d, d->device.cookie, result);
rc |= !!result;
free(d);
}
return rc;
}
int devices_dispatch_cycle(struct sim_state *s)
{
int rc = 0;
for (struct device_list *d = s->machine.devices; d; d = d->next)
if (d->device.ops.cycle)
rc |= !!d->device.ops.cycle(d->device.cookie);
return rc;
}
/* vi: set ts=4 sw=4 et: */
|
C
|
#include <stdio.h>
#include "priority_queue.h"
int main() {
priority_queue idade;
int opcao = 1, valor;
T item;
inicializar(&idade);
while(opcao){
printf("Escolha uma das opcoes para manipular a Heap:\n");
printf("1 - Inserir Elemento\n");
printf("2 - Remover elemento\n");
printf("3 - Elemento com maior prioridade\n");
printf("4 - Tamanho\n");
printf("5 - Imprimir\n");
printf("6 - Sair\n");
scanf("%d", &opcao);
switch(opcao){
case 1:
printf("Escolha o valor do item: ");
scanf("%d", &item.idade);
printf("\n\n");
inserir(&idade, item);
break;
case 2:
remover(&idade, &item);
break;
case 3:
prioritario(&idade, &item);
if(item.idade == -1){
printf("A Heap não tem elemento(s)!\n\n");
} else {
printf("O elemento %d tem maior prioridade na Heap!\n\n", item.idade);
}
break;
case 4:
valor = tamanho(&idade);
printf("O tamanho da Heap é %d!\n\n", valor);
break;
case 5:
imprimir(&idade);
printf("\n");
break;
case 6:
printf("O programa será fechado!\n\n");
return 0;
default:
printf("Escolha uma opcao válida!\n\n");
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
* Author: Guilherme Henrique Loureno
* ltima Modificao: 29/08/2014
* Language: C
*/
int negativos(int n, float* vet);
void main(int argc, char *argv[]){
int tamanho,i;
float *vetor;
printf("Digite o tamanho do vetor: ");
scanf("%d",&tamanho);
vetor = (float *)malloc(tamanho*sizeof(float));
if(vetor==NULL){
printf("Memria Insuficiente!!!");
exit(1);
}
for(i=0;i<tamanho;i++){
printf("Digite um numero para o vetor: ");
scanf("%f",&vetor[i]);
}
printf("Numero de numeros negativos: %d ",negativos(tamanho,vetor));
free(vetor);
}
int negativos(int n,float* vet){
int i,contador=0;
for(i=0;i<n;i++){
if(vet[i]<0) contador++;
//printf("%f ",vet[i]);
}
return(contador);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cases.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apetrech <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/31 17:17:53 by apetrech #+# #+# */
/* Updated: 2018/07/31 17:19:25 by apetrech ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void ft_dashtable(t_fun *f)
{
f['x'] = &ft_print_hex;
f['X'] = &ft_print_hex;
f['s'] = &ft_print_str;
f['S'] = &ft_print_wstr;
f['i'] = &ft_print_nbr;
f['d'] = &ft_print_nbr;
f['D'] = &ft_print_nbr;
f['o'] = &ft_print_octal;
f['O'] = &ft_print_octal;
f['c'] = &ft_print_char;
f['C'] = &ft_print_char;
f['p'] = &ft_print_point;
f['b'] = &ft_print_binary;
f['u'] = &ft_print_unbr;
f['U'] = &ft_print_unbr;
}
t_fun ft_function(char c)
{
static t_fun *f;
int i;
if (!f)
{
f = ft_memalloc(sizeof(*f) * 256);
if (f)
ft_dashtable(f);
}
i = (int)c;
return (f[i]);
}
int ft_type(t_format *format, va_list *arg)
{
char *val;
t_fun f;
int temp;
f = ft_function(format->convert);
if (f)
val = f(format, arg);
else if (format->width != 0)
{
format->len = format->width;
val = ft_strnew(format->width);
ft_memset(val, ' ', format->width);
temp = (format->flag.minus) ? 0 : format->width - 1;
ft_memset(val + temp, format->convert, 1);
}
else
{
format->len = 1;
val = ft_strnew(1);
ft_memset(val, format->convert, 1);
}
temp = write(1, val, format->len);
ft_memdel((void **)&val);
return (temp);
}
|
C
|
// name: Luke Heary
// file: main.h
// date: 11/14/17
#include <stdbool.h>
typedef struct {
int robotNumber;
int num;
int initialR;
int initialC;
int currentR;
int currentC;
int numberOfMoves;
int rows;
int columns;
int *cellsAround;
int **grid;
int targetR;
int targetC;
bool atTarget;
bool touchingRobot;
} robot;
// main.c
int **createGrid(int rows, int columns, int targetR, int targetC);
void printGrid(int length, int width, int **grid);
robot * createRobots(int numberOfRobots, int length, int width, int **grid, pthread_t *robots);
//robot.c
void moveRobot(robot *r, int numberOfRobots);
bool robotSearchAround(robot *r);
void alert(robot *robots, int numberOfRobots, int targetR, int targetC);
void moveRobotsToTarget(robot *r,int numberOfRobots);
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
int /*<<< orphan*/ PAGE (void*) ;
int PROT_EXEC ;
int PROT_READ ;
int PROT_WRITE ;
void* malloc (int) ;
int /*<<< orphan*/ memcpy (void*,long*,int) ;
int /*<<< orphan*/ memset (void*,int,int) ;
int /*<<< orphan*/ mprotect (int /*<<< orphan*/ ,int,int) ;
__attribute__((used)) static void *hook (void *hfunc, int len, void *wfunc) {
void *newmem = malloc(len+5);
long rel32;
// copy 'len' bytes of instruction from 'hfunc' to 'newmem' and a 'jmp *hfunc' instruction after it
memcpy(newmem, hfunc, len);
memset(newmem+len, 0xe9, 1); // e9 - jmp rel32
rel32 = hfunc - (newmem+5);
memcpy(newmem+len+1, &rel32, sizeof rel32);
// make 'hfunc's address writable & executable
mprotect(PAGE(hfunc), 4096, PROT_READ|PROT_WRITE|PROT_EXEC);
// change the start of 'hfunc' to a 'jmp *wfunc' instruction
memset(hfunc, 0xe9, 1); // e9 - jmp rel32
rel32 = wfunc - (hfunc+5);
memcpy(hfunc+1, &rel32, sizeof rel32);
return newmem;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void main(){
int i;
int *m,*c;
m= (int*)malloc(5*sizeof(int));
c= (int*)calloc(5,sizeof(int));
for(i=0;i<5;i++){
printf("%d %d",m[i],c[i]);
}
}
|
C
|
#include <stdio.h>
int main(int argc, char* argv[])
{
int x = 2, y = 3, z = 5;
int* x_ptr = &x;
int* y_ptr = &y;
int* z_ptr = &z;
printf("x == %d, y == %d, z == %d\n", x, y, z);
printf("x_ptr == %p\n", x_ptr);
printf("y_ptr == %p\n", y_ptr);
printf("z_ptr == %p\n", z_ptr);
printf("The address of x is %p\n", x_ptr);
printf("The value stored in %p is %d\n", x_ptr, *x_ptr);
printf("\nThe value stored in y, %p, is %d\n", y_ptr, y);
printf("Doing '*y_ptr = x * z'\n");
*y_ptr = x * z;
printf("The value stored in y, %p, is %d\n", y_ptr, y);
printf("\nx == %d\n", x);
printf("Doing 'x = (*y_ptr) * (*z_ptr)'\n");
x = (*y_ptr) * (*x_ptr);
printf("Now x == %d\n", x);
printf("\nz == %d\n", z);
printf("Doing 'z = *x_ptr'\n");
z = *x_ptr;
printf("Now, z == %d\n", z);
printf("\nz_ptr == %p, the value there is %d\n", z_ptr, *z_ptr);
printf("Doing 'z_ptr = y_ptr'\n");
z_ptr = y_ptr;
printf("Now, z_ptr == %p, the value there is %d\n", z_ptr, *z_ptr);
}
|
C
|
/* CONVERT (A+B)*C/D TO ITS POSTFIX EXPRESSION i.e. AB+C*D/
and TO ITS PREFIX EXPRESSION i.e. *+AB/CD */
#include <stdio.h>
void main()
{
int c,l;
char infix[30],infix1[30];
printf("\n\n\tENTER THE EXPRESSION TO FINDS ITS POSTFIX AND PREFIX EXPRESSION=");
printf("\n\nEnter the expression:");
gets(infix);
c=strlen(infix);l=c;
strcpy(infix1,infix);
getch();
post(infix,c);
pre(infix1,c);
}
void post(char postfix[],int c)
{
int i=0;
char temp;
if(postfix[0]=='('&& postfix[4]==')')
{
temp=postfix[2];
postfix[2]=postfix[3];
postfix[3]=temp;
}
while(postfix[i]!='\0')
{
postfix[i]=postfix[i+1];
i++;
}
i=0;
while(postfix[i]!='\0')
{
if(postfix[i]==')')
{
while(postfix[i]!='\0')
{
postfix[i]=postfix[i+1];
i++;
}
break;
}
i++;
}
i=0;
while(postfix[i]!='\0')
{
if(postfix[i]=='*')
{
temp=postfix[i];
postfix[i]=postfix[i+1];
postfix[i+1]=temp;
i++;
}
i++;
}
i=0;
while(postfix[i]!='\0')
{
if(postfix[i]=='/')
{
temp=postfix[i];
postfix[i]=postfix[i+1];
postfix[i+1]=temp;
i++;
}
i++;
}
postfix[i]='\0';
printf("\nSO POSTFIX EXPRESSION IS:\n");
printf("\t%s\n",postfix);
}
void pre(char prefix[],int l)
{
int i=0,c=0;
char temp;
if(prefix[0]=='('&& prefix[4]==')')
{
temp=prefix[1];
prefix[1]=prefix[2];
prefix[2]=temp;
}
while(prefix[i]!='\0')
{
prefix[i]=prefix[i+1];
i++;
}
i=0;
while(prefix[i]!='\0')
{
if(prefix[i]==')')
{
while(prefix[i]!='\0')
{
prefix[i]=prefix[i+1];
i++;
}
break;
}
i++;
}
i=0;
while(prefix[i]!='\0')
{
c++;
if(prefix[i]=='*')
{
temp=prefix[i];
for(i=c-1;i>0;i--)
prefix[i]=prefix[i-1];
prefix[i]=temp;
break;
}
i++;
}
for(i=l-1;i>=0;i--)
{
if(prefix[i]=='/')
{
temp=prefix[i];
for(;prefix[i]!='\0';i++)
prefix[i]=prefix[i+1];
}
else
prefix[i+1]=prefix[i];
}
prefix[0]='/';
prefix[l-2]='\0';
printf("THE PREFIX EXPRESSIN IS:\n %s",prefix);
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdbool.h>
enum {INIT_STATE, COMMENT_STATE1, ONE_LINE_COMMENT_STATE, MULTI_LINE_COMMENT_BEGIN_STATE, MULTI_LINE_COMMENT_WAIT_END_STATE};
int handle_file(const char* path)
{
FILE* fp = fopen(path, "r");
if(fp == NULL)
return 0;
int no_of_line = 0;
int c;
bool need_count = false;
int state = INIT_STATE;
while((c = fgetc(fp)) != EOF){
switch(state){
case INIT_STATE:
if(c == '/')
state = COMMENT_STATE1;
else if(!isspace(c))
need_count = true;
else if(c == '\n'){
if(need_count){
no_of_line++;
need_count = false;
}
}
else{
// do nothing
}
break;
case COMMENT_STATE1:
if(c == '/')
state = ONE_LINE_COMMENT_STATE;
else if(c == '*')
state = MULTI_LINE_COMMENT_BEGIN_STATE;
else {
state = INIT_STATE;
if(c == '\n'){
no_of_line++;
need_count = false;
}
}
break;
case ONE_LINE_COMMENT_STATE:
if(c == '\n'){
if(need_count){
no_of_line++;
need_count = false;
}
state = INIT_STATE;
}else{
// do nothing
}
break;
case MULTI_LINE_COMMENT_BEGIN_STATE:
if(c == '*')
state = MULTI_LINE_COMMENT_WAIT_END_STATE;
else if(c == '\n'){
if(need_count){
no_of_line++;
need_count = false;
}
// note: no need to change state
}
else{
// do nothing
}
break;
case MULTI_LINE_COMMENT_WAIT_END_STATE:
if(c == '/') // comment end
state = INIT_STATE;
else if(c == '\n'){
if(need_count){
no_of_line++;
need_count = false;
}
state = MULTI_LINE_COMMENT_BEGIN_STATE;
}
else
state = MULTI_LINE_COMMENT_BEGIN_STATE;
break;
default:
fprintf(stderr, "unkown state: %d\n", state);
break;
}
}
return no_of_line;
}
int tranverse(const char* path)
{
struct stat s;
if(stat(path, &s) < 0){
fprintf(stderr, "path not exist or permission denied, path:%s\n", path);
return 0;
}
int no_of_line = 0;
if(s.st_mode & S_IFDIR){
DIR* dir = opendir(path);
if(!dir){
fprintf(stderr, "opendir error, dir: %s\n", path);
return 0;
}
struct dirent* entp;
while((entp = readdir(dir)) != NULL){
if(!strcmp(entp->d_name, ".") || !strcmp(entp->d_name, "..")){
continue;
}
char sub_path[1024];
strcpy(sub_path, path);
strcat(sub_path, "/");
strcat(sub_path, entp->d_name);
no_of_line += tranverse(sub_path);
}
}
else if(s.st_mode & S_IFREG){
no_of_line += handle_file(path);
}
else{
// other type, ignore
}
return no_of_line;
}
int main(int argc, char* argv[])
{
if(argc != 2){
fprintf(stderr, "usage: ./a.out <path>\n");
return 0;
}
const char* path = argv[1];
int no_of_line = tranverse(path);
printf("number of line: %d\n", no_of_line);
return 0;
}
|
C
|
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "clickhouse-client.h"
#define driver "/home/vagrant/percona/clickhouse-odbc/driver/libclickhouseodbc.so"
int select()
{
int r;
int deptno;
const char *dname;
const char *loc;
int errno;
char error[256];
r = odbc_init();
if (r < 0)
{
printf("\nERROR: unable to initalize");
return -1;
}
Conn *conn = odbc_connect((char*)driver,(char*) "127.0.0.1", 8123, (char*)"default111", (char*)"", (char*)"", error);
if (conn == 0)
{
printf("\nERROR: failed to connect\n %s\n", error);
return -1;
}
r = odbc_prepare(conn, (char*)"SELECT * FROM dept");
if (r < 0)
{
printf("\nERROR: failed to prepare\n %s\n",conn->error);
return -1;
}
r = odbc_execute(conn);
if (r < 0)
{
printf("\nERROR: failed to execute\n %s\n", conn->error);
return -1;
}
while(1)
{
char str[256];
int len = 256;
bool is_null = false;
r = odbc_fetch(conn);
if(r == 0)
break;
else if (r < 0)
{
printf("\nERROR: failed to fetch\n %s\n", conn->error);
break;
}
deptno = odbc_get_int(conn, 1, &errno);
dname = odbc_get_string(conn, 2, str, len, &is_null);
loc = odbc_get_string(conn, 3, str, len, &is_null);
printf("\n%d, %s, %s\n", deptno, dname, loc);
}
r = odbc_disconnect(conn);
if (r < 0)
return -1;
printf("\nall test passed\n");
return 0;
}
int insert()
{
int r;
int deptno;
const char *dname;
const char *loc;
int errno;
char error[256];
r = odbc_init();
if (r < 0)
{
printf("\nERROR: unable to initalize");
return -1;
}
Conn *conn = odbc_connect((char*)driver,(char*) "127.0.0.1", 8123, (char*)"default", (char*)"", (char*)"", error);
if (conn == 0)
{
printf("\nERROR: failed to connect\n %s\n", error);
return -1;
}
r = odbc_prepare(conn, (char*)"INSERT INTO dept(deptno, dname, loc) VALUES(1, 2, 3)");
if (r < 0)
{
printf("\nERROR: failed to prepare\n %s\n", conn->error);
return -1;
}
if (odbc_bind_int(conn, 1, 100, false) < 0)
{
printf("\nERROR: failed to bind deptno\n %s\n", conn->error);
return -1;
}
if (odbc_bind_string(conn, 2, (char*)"100", false) < 0)
{
printf("\nERROR: failed to bind dname\n %s\n", conn->error);
return -1;
}
if (odbc_bind_string(conn, 3, (char*)"100", false) < 0)
{
printf("\nERROR: failed to bind loc\n %s\n", conn->error);
return -1;
}
r = odbc_execute(conn);
if (r < 0)
{
printf("\nERROR: failed to execute\n %s\n", conn->error);
return -1;
}
r = odbc_disconnect(conn);
if (r < 0)
return -1;
printf("\nall test passed\n");
return 0;
}
int main()
{
//insert();
select();
}
|
C
|
#include <stdio.h>
void hanoi(char dep, char dest, char temp, int n)
{
if(n==1)
{
printf ("deplacez %c vers %c\n",dep,dest);
}
else
{
hanoi( dep, temp, dest, n-1);
hanoi( dep, dest, temp, 1);
hanoi(temp, dest, dep, n-1);
}
}
void main()
{
int n;
printf("Dans ce jeux il y a 3 tours qu'on va appeler a b c\nnombre de disque: ");
scanf("%d",&n);
hanoi('a','c','b',n);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* board.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sgouifer <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/02 20:24:07 by sgouifer #+# #+# */
/* Updated: 2019/03/03 21:27:50 by zamazzal ### ########.fr */
/* */
/* ************************************************************************** */
#include "alum1.h"
int is_looser(int nb)
{
if ((nb % 10 == 1 || nb % 10 == 5 || nb % 10 == 9) && ((((nb % 100) / 10)
% 2) == 0))
return (1);
if ((nb % 10 == 3 || nb % 10 == 7) && ((((nb % 100) / 10) % 2) == 1))
return (1);
return (0);
}
void read_number(int *n, char *msg)
{
char data[6];
ft_putstr(msg);
read(0, data, 6);
*n = ft_atoi(data);
}
int read_number2(int *n, char *msg)
{
char data[6];
int r;
ft_putstr(msg);
if ((r = read(0, data, 6)) == -1)
return (-1);
data[r] = '\0';
*n = ft_atoi(data);
if (*n == 0 && ft_strcmp(data, "\n") != 0)
return (-1);
return (*n);
}
int copy_table_to_tab(int *tab1, int **tab2, int size)
{
int i;
i = 0;
while (is_valid_number(tab1[i]))
{
(*tab2)[i] = tab1[i];
i++;
}
if (size != i)
return (1);
return (0);
}
int *init_board1(int *line_numbers)
{
int *board;
int i;
int board_max[133742];
int x;
i = 0;
splash();
while (i < 10000)
{
ft_putstr(" ");
x = read_number2(&board_max[i], "");
if (x == -1)
return (NULL);
if (!(x >= 1 && x <= 10000))
break ;
i++;
}
if (i == 0)
return (NULL);
*line_numbers = i;
board = (int *)malloc(sizeof(int) * (i));
if (copy_table_to_tab(board_max, &board, i))
return (NULL);
return (board);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <Windows.h>
//#include "codecs.h"
//#include "format.h"
#include "colours.h"
int main()
{
bool IncTrue = 0;
bool FinTrue = 0;
bool SecTrue = false;
int menuOpcion = 0;
int menuOpcionH = 0;
int menuOpcionAv = 0;
int menuOpcionSt = 0;
int menuOpcionRec = 0;
char InFile[200] = "|indefinido|";
char OutFile[200] = "|indefinido|";
char FileFormat[100] = "|indefinido|";
char cmd[500];
char agree[2];
char temp[100];
char map1[20] = "";
char map2[20] = "";
char map3[20] = "";
char map4[20] = "";
char map5[20] = "";
char Vcodec[20] = "";
char Acodec[20] = "";
char Scodec[20] = "";
char IncTime[100] = "00:00:00";
char FinTime[100] = "";
char SecFile[200] = "";
//menu principal
menu:
system("cls");
SetColour(9);
printf("-------------------------------------MENU--------------------------------------\n");
MenuOpMain(1, "Seleccionar ubicacion del archivo de entrada:", InFile);
MenuOpMain(2, "Seleccionar ubicacion del archivo de salida:", OutFile);
MenuOpMain(3, "Seleccionar formato de archivo:", FileFormat);
MenuOpMain(4, "Opciones avanzadas", "");
MenuOpMain(5, "Convertir", "");
MenuOpMain(6, "Ayuda", "");
SetColour(9);
printf("-------------------------------------MENU--------------------------------------\n\n");
SetColour(7);
printf("Archivo de entrada: %s\n", InFile);
printf("Archivo de salida: %s.%s\n\n", OutFile, FileFormat);
scanf("%d", &menuOpcion);
system("cls");
//opciones del menu principal
switch(menuOpcion)
{
//seleccion de archivo de entrada
case 1:
printf("Escriba la ubicacion de su archivo incluyendo el nombre del archivo y su formato\n");
printf("Ej: c:\\carpeta\\video.mp4\n");
scanf("%c", &temp);
scanf("%[^\n]", InFile);
goto menu;
break;
//seleccion de archivo de salida
case 2:
printf("Escriba la ubicacion donde desea guardar su archivo convertido incluyendo el nombre de su archivo\n");
printf("Ej: c:\\carpeta\\videoConvertido\n");
scanf("%c", &temp);
scanf("%[^\n]", OutFile);
goto menu;
break;
//seleccion formato de archivo de salida
case 3:
printf("Seleccione a que formato desea convertir su archivo de entrada\n");
printf("Ej: avi\nSi desea ver una lista de los archivos soportados vaya a ayuda\n");
scanf("%c", &temp);
scanf("%[^\n]", FileFormat);
goto menu;
break;
//---------------------------------------------------------------------------------------------------
//Opciones avanazadas
//seleccion de codecs, sub, etc
case 4:
menuAv:
system("cls");
SetColour(5);
printf("----------------------------Opciones Avanzadas---------------------------------\n");
MenuOpAdv(1, "Recortar video/audio", "");
MenuOpAdv(2, "Seleccionar streams a convertir", "");
MenuOpAdv(3, "Anadir stream de video por archivo externo", "");
MenuOpAdv(4, "Seleccionar codec de video:", Vcodec);
MenuOpAdv(5, "Seleccionar codec de audio:", Acodec);
MenuOpAdv(6, "Seleccionar codec de subtitulo:", Scodec);
MenuOpAdv(7, "Volver al menu principal", "");
SetColour(5);
printf("----------------------------Opciones Avanzadas---------------------------------\n");
SetColour(7);
scanf("%d", &menuOpcionAv);
system("cls");
//opciones avanzadas
switch(menuOpcionAv)
{
//recortar video/audio
// -ss start 00:00:00 -t end 00:00:01 -async 1 (obligatorio)
case 1:
menuRec:
system("cls");
SetColour(5);
printf("---------------------------------Recortar--------------------------------------\n");
MenuOpAdv(1, "Seleccionar donde desea que comience su archivo:", IncTime);
MenuOpAdv(2, "Seleccionar donde desea que termine su archivo:", FinTime);
MenuOpAdv(3, "Volver a las opciones avanzadas", "");
SetColour(5);
printf("---------------------------------Recortar--------------------------------------\n");
SetColour(7);
scanf("%d", &menuOpcionRec);
system("cls");
switch(menuOpcionRec)
{
//Comienzo de archivo
case 1:
printf("Escriba el tiempo donde quiere que comienze su archivo\n");
printf("(Ej: 00:01:15) El archivo comenzara en los 15 Seg. 1 Min.\nEscriba c para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", IncTime);
if((IncTime[0] == 'c') || (IncTime[0] == 'C')) strcpy(IncTime, " ");
else IncTrue = true;
goto menuRec;
break;
//Fin de archivo
case 2:
printf("Escriba el tiempo donde terminara su archivo\n");
printf("(Ej: 00:02:30) El archivo terminara a los 2 Min. 30 Seg.\nEscriba c para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", FinTime);
if((FinTime[0] == 'c') || (FinTime[0] == 'C')) strcpy(FinTime, " ");
else FinTrue = true;
goto menuRec;
break;
//Volver a opciones avanzadas
case 3:
goto menuAv;
break;
default:
goto menuRec;
break;
}
break;
//Seleccionar streams (map)
case 2:
streams:
system("cls");
SetColour(5);
printf("----------------------------------Streams--------------------------------------\n");
MenuOpAdv(1 ,"Modificar stream:", map1);
MenuOpAdv(2 ,"Modificar stream:", map2);
MenuOpAdv(3 ,"Modificar stream:", map3);
MenuOpAdv(4 ,"Modificar stream:", map4);
MenuOpAdv(5 ,"Modificar stream:", map5);
MenuOpAdv(6 ,"Volver a las opciones avanzadas", "");
SetColour(5);
printf("----------------------------------Streams--------------------------------------\n");
SetColour(7);
scanf("%d", &menuOpcionSt);
system("cls");
//opcines stream
switch(menuOpcionSt)
{
//Stream 1
case 1:
printf("Elija que stream de entrada usar y en que stream de salida se guardara\n");
printf("(Ej: map 0:1) para 0 siendo el numero del archivo de entrada y stream 1 siendo el numero de stream en el archivo 0\nEscriba c para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", map1);
if(map1[0] == 'c')map1[0] = ' ';
else{
sprintf(temp,"-%s",map1);
strcpy(map1, temp);
}
goto streams;
break;
//Stream 2
case 2:
printf("Elija que stream de entrada usar y en que stream de salida se guardara\n");
printf("(Ej: map 0:1) para 0 siendo el numero del archivo de entrada y stream 1 siendo el numero de stream en el archivo 0\nEscriba c para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", map2);
if(map2[0] == 'c')map2[0] = ' ';
else{
sprintf(temp,"-%s",map2);
strcpy(map2, temp);
}
goto streams;
break;
//Stream 3
case 3:
printf("Elija que stream de entrada usar y en que stream de salida se guardara\n");
printf("(Ej: map 0:1) para 0 siendo el numero del archivo de entrada y stream 1 siendo el numero de stream en el archivo 0\nEscriba c para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", map3);
if(map3[0] == 'c')map3[0] = ' ';
else{
sprintf(temp,"-%s",map3);
strcpy(map3, temp);
}
goto streams;
break;
//Stream 4
case 4:
printf("Elija que stream de entrada usar y en que stream de salida se guardara\n");
printf("(Ej: map 0:1) para 0 siendo el numero del archivo de entrada y stream 1 siendo el numero de stream en el archivo 0\nEscriba c para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", map4);
if(map4[0] == 'c')map4[0] = ' ';
else{
sprintf(temp,"-%s",map4);
strcpy(map4, temp);
}
goto streams;
break;
//Stream 5
case 5:
printf("Elija que stream de entrada usar y en que stream de salida se guardara\n");
printf("(Ej: map 0:1) para 0 siendo el numero del archivo de entrada y stream 1 siendo el numero de stream en el archivo 0\nEscriba c para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", map5);
if(map5[0] == 'c')map5[0] = ' ';
else{
sprintf(temp,"-%s",map5);
strcpy(map5, temp);
}
goto streams;
break;
//Volver a menu avanzado
case 6:
goto menuAv;
break;
default:
goto streams;
break;
}
break;
//Añadir stream o sub externo
case 3:
printf("Escriba la ubicacion del archivo secundario que quiere agregar\n");
printf("Ej: c:\\subtitulos.srt\nEscriba X para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", SecFile);
if((SecFile[0] == 'x') || (SecFile[0] == 'X')) strcpy(SecFile, " ");
else SecTrue = true;
goto menuAv;
break;
//Seleccionar codec de video
case 4:
printf("Escriba el codec de video que desea usar\n");
printf("Ej: h264\nEscriba C para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", Vcodec);
sprintf(temp,"-c:v %s",Vcodec);
strcpy(Vcodec, temp);
goto menuAv;
break;
//Seleccionar codec de audio
case 5:
printf("Escriba el codec de audio que desea usar\n");
printf("Ej: mp3\nEscriba C para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", Acodec);
sprintf(temp,"-c:a %s",Acodec);
strcpy(Acodec, temp);
goto menuAv;
break;
//Seleccionar codec de sub
case 6:
printf("Escriba el codec de subtitulos que desea usar\n");
printf("Ej: mov_text\nEscriba C para cancelar\n");
scanf("%c", &temp);
scanf("%[^\n]", Scodec);
sprintf(temp,"-c:s %s",Scodec);
strcpy(Scodec, temp);
goto menuAv;
break;
//Volver al menu principal
case 7:
goto menu;
break;
default:
goto menuAv;
break;
}
break;
//Escribir comandos
case 5:
//comando si se corta el tiempo de inicio
if(SecTrue == true)
{
if(IncTrue == true)sprintf(cmd,"ffmpeg -i \"%s\" -i \"%s\" -ss %s %s %s %s %s %s %s %s %s -async 1 \"%s.%s\"", InFile, SecFile, IncTime, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
//comando si se corta el tiempo de fin
if(FinTrue == true)sprintf(cmd,"ffmpeg -i \"%s\" -i \"%s\" -to %s %s %s %s %s %s %s %s %s -async 1 \"%s.%s\"", InFile, SecFile, FinTime, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
//comando si se corta el tiempo de inicio y de fin
if((IncTrue == true) && (FinTrue == true))sprintf(cmd,"ffmpeg -i \"%s\" -i \"%s\" -ss %s -to %s %s %s %s %s %s %s %s %s -async 1 \"%s.%s\"", InFile, SecFile, IncTime, FinTime, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
//comando si no se corta nada
if((IncTrue == false) && (FinTrue == false))sprintf(cmd,"ffmpeg -i \"%s\" -i \"%s\" %s %s %s %s %s %s %s %s \"%s.%s\"", InFile, SecFile, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
}
else{
if(IncTrue == true)sprintf(cmd,"ffmpeg -i \"%s\" -ss %s %s %s %s %s %s %s %s %s -async 1 \"%s.%s\"", InFile, IncTime, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
//comando si se corta el tiempo de fin
if(FinTrue == true)sprintf(cmd,"ffmpeg -i \"%s\" -to %s %s %s %s %s %s %s %s %s -async 1 \"%s.%s\"", InFile, FinTime, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
//comando si se corta el tiempo de inicio y de fin
if((IncTrue == true) && (FinTrue == true))sprintf(cmd,"ffmpeg -i \"%s\" -ss %s -to %s %s %s %s %s %s %s %s %s -async 1 \"%s.%s\"", InFile, IncTime, FinTime, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
//comando si no se corta nada
if((IncTrue == false)&&(FinTrue == false))sprintf(cmd,"ffmpeg -i \"%s\" %s %s %s %s %s %s %s %s \"%s.%s\"", InFile, map1, map2, map3, map4, map5, Vcodec, Acodec, Scodec, OutFile, FileFormat);
}
printf("Se ejecutara el siguiente comando\n%s",cmd);
printf("\nEsta usted de acuerdo (S/N)?");
scanf("%s", agree);
if((agree[0] == 'S') || (agree[0] == 's'))system(cmd);
if(agree[0] == 'n' || 'N')goto menu;
return 0;
break;
//menu de ayuda
case 6:
menuHelp:
system("cls");
SetColour(5);
printf("-------------------------------Menu de ayuda-----------------------------------\n");
MenuOpAdv(1 ,"Lista de formatos", "");
MenuOpAdv(2 ,"Lista de codecs", "");
MenuOpAdv(3 ,"Autores de FFMPEG", "");
MenuOpAdv(4 ,"Volver al menu principal", "");
SetColour(5);
printf("-------------------------------Menu de ayuda-----------------------------------\n\n");
SetColour(7);
scanf("%d", &menuOpcionH);
//opciones del menu de ayuda
system("cls");
switch(menuOpcionH)
{
//Lista de formatos de archivo
case 1:
printf("Los diferentes formatos estan listados en esta pagina\n\n");
printf("https://ffmpeg.org/ffmpeg-all.html#Supported-File-Formats_002c-Codecs-or-Features");
printf("\n\nEscriba cualquier caracter para salir\n");
scanf("%s");
goto menuHelp;
break;
//Lista de codecs
case 2:
printf("Los diferentes codecs estan listados en esta pagina\n\n");
printf("https://ffmpeg.org/ffmpeg-all.html#Video-Codecs\n");
printf("\n\nEscriba cualquier caracter para salir\n");
scanf("%s");
goto menuHelp;
break;
//Info sobre los creadores de FFMPEG
case 3:
printf("FFMPEG fue creado por el ffmpeg team, y fue lanzado el 20 de diciembre");
printf("del 2000. Puedes encontrar mas informacion en ffmpeg.org\nEscriba cualquier caracter para salir\n");
scanf("%s");
goto menu;
break;
//Volver al menu principal
case 4:
goto menu;
break;
default:
goto menuHelp;
break;
}
break;
default :
goto menu;
break;
}
return 0;
}
|
C
|
//-------------------------------------------------------------------------------------------------
/**
* @file gpioSample.c
*
* Sample app making use of the helper lib (gpio_iot) to drive CF3-GPIO on IoT0 card for mangOH Green/Red
* Scenario :
* GPIO_2 and GPIO_4 drive 2 LEDs to blink alternatively
* GPIO_1 is configured as an input (switch) to toggle another LED driven by GPIO_3
* This app can drive IoT0card's GPIOs on mangOH Green or Red (config tree) without changing the code nor IoT0 wiring.
*
* NC - March 2018
*/
//-------------------------------------------------------------------------------------------------
#include "legato.h"
#include "interfaces.h"
#include "gpio_iot.h" //use the gpio_iot helper lib
//Callback to handle level transition on GPIO_1
static void OnGpio1Change(bool state, void *ctx)
{
LE_INFO("GPIO_1 State change %s", state?"TRUE":"FALSE");
//GPIO_1 button/switch has been pressed, just toggle the LED driven by GPIO_3
bool status = gpio_iot_Read(3);
status = !status;
gpio_iot_SetOutput(3, status);
}
//This implements the led blink scenario
void Blink()
{
//Blink scenario (driven by timer) : alternating the GPIO_2 and GPIO_4 (they blink oppositely)
//Retrieve the output level of GPIO_2
bool state = gpio_iot_Read(2);
gpio_iot_Read(4); //just trace the output level of GPIO_4 to logread
//Set GPIO_4 output to be the same level as GPIO_2
gpio_iot_SetOutput(4, state);
//Reverse the output of GPIO_2
state = !state;
gpio_iot_SetOutput(2, state);
//just trace the output level of GPIO_1 & GPIO_3 to logread
gpio_iot_Read(1);
gpio_iot_Read(3);
LE_INFO(" ");
}
COMPONENT_INIT
{
//Initialize gpio_iot helper lib : Will be using IoT0 slot of the mangOH board
//this will set the target mangOH board type: setting in config tree : "/gpio_iot/mangohType"
gpio_iot_Init();
//GPIO_1 as an input : connect a switch/PushButton to GPIO_1 (Pin24 of IoT card) and GND
gpio_iot_SetInput(1, true);
gpio_iot_EnablePullUp(1); //enable the internal pull-up resistor
//if the button is pushed, then call OnGpio1Change callback function
gpio_iot_AddChangeEventHandler(1, GPIO_IOT_EDGE_RISING, OnGpio1Change, NULL, 100);
//GPIO_2 is an output : Use a transistor to drive the LED.
gpio_iot_SetPushPullOutput(2, true, true);
//GPIO_3 is an output : Use a transistor to drive a LED/Motor.
gpio_iot_SetPushPullOutput(3, true, true);
//GPIO_4 is an output : Use a transistor to drive the LED.
gpio_iot_SetPushPullOutput(4, true, true);
//Set timer to animate LEDs
le_timer_Ref_t ledTimerRef = le_timer_Create("ledTimer"); //create timer
le_clk_Time_t interval = { 2, 0 }; //timer to expire every 2 seconds
le_timer_SetInterval(ledTimerRef, interval);
le_timer_SetRepeat(ledTimerRef, 0); //set repeat to always
//set callback function to handle timer expiration event
le_timer_SetHandler(ledTimerRef, Blink);
//start timer
le_timer_Start(ledTimerRef);
}
|
C
|
/**
* code stolen from ocfs2-tools/libocfs2/openfs.c
*
* gcc ocfs2-dump-super.c -o ocfs2-dump-super
* ./ocfs2-dump-super /dev/sda
*
* */
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BLOCK_SIZE 4096
static int unix_io_read_block(char *dev, int64_t blkno, int count, char *data)
{
int ret;
ssize_t size, total, rd;
uint64_t location;
int dev_fd;
dev_fd = open64(dev, O_RDONLY);
if (dev_fd < 0)
return -1;
size = count * BLOCK_SIZE; // default block size 4096 bytes
location = blkno * BLOCK_SIZE;
total = 0;
while (total < size) {
/*
Q: pread64和read有什么区别?
A:pread64的p应该指pthread,二者的区别很明显,前者多一个参数offset,后者没有这个参数,默认是从头部开始读取的。
Q: pread64调用一次,发起一次disk io?一次可以读多少?
A:简单地说,pread64/read不用考虑这个问题,因为它们在内核中是调用vfs_read读取的。
我用“python write_file.py -f file-1g -s 1073741824”创建一个文件,写文件的方式不是direct io,
再用“./hugeread file-1g”调用pread64读取,一次就读完1G了。
所以pread64调用多少次,一次读多少,简单的说不是它的问题,它只是一个“傀儡”。
但对于块设备文件,open时没有指定O_DIRECT,难道就会读page cache了?不一定,因为page cache凭什么缓存你设备的raw内容?
--[10-29 update] 还真会,参考ULK3 ch15 “The page cache”. page cache中的raw内容属于设备文件的inode。
<del>所以,我理解对于块设备,如果只有读取操作,open没有必要指定O_DIRECT。</del>
如果有写操作,如果不是O_DIRECT,那么就很可能没有真正写 ======> to be exampled
注1:write_file.py在python-misc库下。
注2:hugeread的代码放到本例最后的注释中。
*/
rd = pread64(dev_fd, data + total, size - total, location + total);
if (rd < 0) {
close(dev_fd);
return -1;
}
if (rd == 0)
return 0;
total += rd;
printf("pread64, size(read/total): %d / %d, new offset: %d\n", total, size, location + total);
}
close(dev_fd);
return 0;
}
static void malloc_blocks(int num_blocks, void **ptr)
{
int ret;
size_t bytes = num_blocks * BLOCK_SIZE;
// int posix_memalign(void **memptr, size_t alignment, size_t size);
ret = posix_memalign(ptr, BLOCK_SIZE, bytes);
if (ret)
abort();
}
int main(int argc, char *argv[])
{
void *blk;
#define NUM_BLOCKS 1 // superblock takes 1 block of disk space
malloc_blocks(NUM_BLOCKS, &blk);
// default start block # 2
printf("read block: %d\n", unix_io_read_block(argv[1], 2, NUM_BLOCKS, blk));
return 0;
}
/* huge-read.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd;
#define COUNT 1024*1024*1024
char* buf = malloc(COUNT);
if (!buf) {
fprintf(stderr, "malloc failed\n");
return 1;
}
fd = open(argv[1], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open failed\n");
return 1;
}
// printf("pread64: %d\n", pread64(fd, buf, COUNT, 0));
printf("read: %d\n", read(fd, buf, COUNT));
return 0;
}
*/
|
C
|
#include <stdio.h>
int main(void) {
int score1, score2, score3;
scanf("%d %d %d", &score1, &score2, &score3);
printf("%.1f\n", ((float)(score1 + score2 + score3) / 3));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double kaiseki(double *a, double *b);
int main(int argc, char **argv) {
double a = strtod(argv[1], NULL);
double b = strtod(argv[2], NULL);
double a1;
a1 = kaiseki(&a, &b);
printf("%.8lf\n", a1);
return 0;
}
double kaiseki(double *a, double *b) {
return ( -2 * cos((*b)/2) + 0.5 * sin(2*(*b)) ) - ( -2 * cos((*a)/2) + 0.5 * sin(2*(*a)) );
}
|
C
|
/* printfʽ Ƚ putcharַ ܸǿ*/
/* ʽΪ printf("ʽ",ֵ) */
/* %d %f %cַ */
#include <stdio.h>
void main()
{
int a=88, b=89; /* abΪͻa88 b89 */
printf("%d,%d\n", a, b);
printf("%f,%f\n", a, b);
printf("%c,%c\n", a, b);
printf("a=%d,b=%d", a, b);/* ""ڳ%d֮ⶼҪӡ */
/* %d%f%c */
}
|
C
|
#include <stdio.h>
int main() {
for(int x = 1; x < 10; x++){
for(int y = 1; y<10; y++){
int a = x * y;
printf("%d ",a);
}
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define INT_MAX ((unsigned int)(1 << 31) - 1)
int reverse(int x) {
long long res = 0, sign = 1, num = x;
if (num < 0) {sign = -1; num = -num;}
while (num) {
res *= 10;
if (res > INT_MAX) return 0;
res += (num % 10);
num /= 10;
}
return res * sign;
}
int main (int argc, char **argv) {
return printf ("%d\n", reverse(atoi(argv[1])));
}
|
C
|
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
int size = nums.size();
sort(nums.begin(), nums.end());
for(int i = 0; i < size; i++)
{
int target = 0 - nums[i];
int left = i+1;
int right = size-1;
while( left < right )
{
if(nums[left]+nums[right] == target){
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[left]);
tmp.push_back(nums[right]);
result.push_back(tmp);
while( left < right && (nums[left] == nums[++left]));
while( left < right && nums[right] == nums[--right]);
} else if (nums[left]+nums[right] < target){
left++;
} else
right--;
}
while( i < size-2 && nums[i] == nums[i+1])
i++;
}
return result;
}
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char t;
int a = 0;
char nome[40];
char nome2[40];
int id, hp, mana, atk;
int id2, hp2, mana2, atk2;
FILE *pick;
FILE *pick2;
FILE *pick3;
FILE *pick4;
FILE *pickaux;
pick2 = fopen("picks2.txt","rt");
pick3 = fopen("picks3.txt","rt");
pick4 = fopen("picks4.txt","rt");
printf ("Weeeeeeeeee\n");
pick = fopen ("NewPick.txt","wt");
pickaux = fopen ("Auxpick.txt", "wt");
fscanf(pick2, "%d %s %d %d %d", &id, nome, &hp, &mana, &atk);
fscanf(pick3, "%d %s %d %d %d", &id2, nome2, &hp2, &mana2, &atk2);
printf ("%d %s %d %d %d\n", id, nome, hp, mana, atk);
printf ("%d %s %d %d %d\n", id2, nome2, hp2, mana2, atk2);
printf ("Weeeeeeeeeeeeeeeeeeee\n");
while (!feof(pick2) && !feof(pick2))
{
printf ("Weeee?\n");
if (!feof(pick2))
{
if (!feof(pick3))
{
if (id < id2)
{
fprintf (pickaux,"%d %s %d %d %d\n", id, nome, hp, mana, atk);
fscanf (pick2, "%d %s %d %d %d", &id, nome, &hp, &mana, &atk);
printf ("%d %s %d %d %d\n", id, nome, hp, mana, atk);
printf ("Vamos!\n");
}
else
{
printf ("chegou else \n");
fprintf (pickaux,"%d %s %d %d %d\n", id2, nome2, hp2, mana2, atk2);
printf ("aqui?\n");
fscanf (pick3, "%d %s %d %d %d", &id2, nome2, &hp2, &mana2, &atk2);
printf ("Quase la\n");
}
}
else
{
fprintf (pickaux, "%d %s %d %d %d\n", id, nome, hp, mana, atk);
fscanf (pick2, "%d %s %d %d %d", &id, nome, &hp, &mana,&atk);
printf ("Maybe!\n");
}
}
else
{
fprintf (pickaux,"%d %s %d %d %d\n", id2, nome2, hp2, mana2, atk2);
fscanf (pick3, "%d %s %d %d %d", &id2, nome2, &hp2, &mana2, &atk2);
printf ("Quase!\n");
}
}
fclose (pickaux);
pickaux = fopen("Auxpick.txt", "rt");
while (!feof(pickaux) && !feof(pick4))
{
printf ("Weeee?\n");
if (!feof(pickaux))
{
if (!feof(pick4))
{
if (id < id2)
{
fprintf (pick,"%d %s %d %d %d\n", id, nome, hp, mana, atk);
fscanf (pickaux, "%d %s %d %d %d", &id, nome, &hp, &mana, &atk);
printf ("%d %s %d %d %d\n", id, nome, hp, mana, atk);
printf ("Vamos!\n");
}
else
{
printf ("chegou else \n");
fprintf (pick,"%d %s %d %d %d\n", id2, nome2, hp2, mana2, atk2);
printf ("aqui?\n");
fscanf (pick4, "%d %s %d %d %d", &id2, nome2, &hp2, &mana2, &atk2);
printf ("Quase la\n");
}
}
else
{
fprintf (pick, "%d %s %d %d %d\n", id, nome, hp, mana, atk);
fscanf (pickaux, "%d %s %d %d %d", &id, nome, &hp, &mana,&atk);
printf ("Maybe!\n");
}
}
else
{
fprintf (pick,"%d %s %d %d %d\n", id2, nome2, hp2, mana2, atk2);
fscanf (pick4, "%d %s %d %d %d", &id2, nome2, &hp2, &mana2, &atk2);
printf ("Quase!\n");
}
}
printf ("SAIU\n");
fclose (pick2);
fclose (pick3);
fclose (pick4);
fclose (pick);
fclose (pickaux);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** mylinkedlist
** File description:
** Source code
*/
#ifndef MY_LINKED_LIST_H
#define MY_LINKED_LIST_H
typedef struct linked_list {
struct linked_list *next;
} linked_list_t;
#define HEAD(node) \
((void **)&node)
int my_count_nodes(void **head);
void *my_find_previous_node(void **head, void *element);
void *my_get_last_node(void **head);
int my_get_node_index(void **head, void *element);
void my_insert_node(void **head, int index, void *element);
void my_pop_node(void **head);
void my_push_node(void **head, void *element);
void my_detach_node(void **head, void *element_ptr);
void my_remove_node(void **head, void *element);
void my_reverse_node(void **head);
void my_shift_node(void **head);
void my_swap_node_and_next(void **head, void *a);
void my_unshift_node(void **head, void *element);
static inline void my_prepend_node(void **head, void *element)
{
my_unshift_node(head, element);
}
static inline void my_append_node(void **head, void *element)
{
my_push_node(head, element);
}
#endif //MY_LINKED_LIST_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fa, *fb;
int ca, cb;
char prep[]={"#include","#define"};
char buff[100];
fa = fopen("in.c", "r");
fb = fopen("out.c", "w");
if (fa == NULL || fb==NULL){
printf("Cannot open file \n");
exit(0); }
ca = getc(fa);
while (ca != EOF)
{
memset(buff,0,sizeof(buff));
if(ca=='#')
{
int i=0;
while(ca!=' '){
buff[i++]=ca;
ca = getc(fa);
}
buff[i]='\0';
puts(buff);
for(int j=0; j<2;j++){
if(strcmp(buff,prep[j])==0)
{
while(ca!='\n')
ca = getc(fa);
i=0;
break;
}
}if(i==0)
continue;
else
{
for(int j=0;j<i;j++)
putc(buff[j],fb);
}
}
else
putc(ca,fb);
ca = getc(fa);
}
fclose(fa);
fclose(fb);
return 0;
}
|
C
|
/*File Name:assignment10.c
Author:K.S.Krishna Chandran
Description:To calculate x to the power of y, where y can be either negative or positive.
Date:13|11|14*/
#include<stdio.h>
void power(int,int);
int main()
{
system("clear");
int x,y,i;
printf("Input the value of X and Y\n");
scanf("%d%d",&x,&y);
power(x,y);
printf("\n\n");
return 0;
}
void power(int x,int y)
{
float res=1.0;
int i,r=1;
if(y>0)
{
for(i=1;i<=y;i++)
{
r*=x;
}
printf("\nThe result of %d ^ %d is:%d\n",x,y,r);
}
else if(y<0)
{
for(i=y;i<0;i++)
{
res*=x;
}
printf("\nThe result of %d ^ %d is:%f\n",x,y,1/res);
}
else
{
printf("\nThe result of %d ^ %d is:%d\n",x,y,x);
}
}
|
C
|
#include "unity.h"
#include "disassembler.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "Exception.h"
#include "CException.h"
#include "CExceptionConfig.h"
#include <stdarg.h>
#include <string.h>
void setUp(void)
{
}
void tearDown(void)
{
}
void test_mulwf(void)
{
CEXCEPTION_T ex;
uint8_t memory[]={0x02,0x55,0x03,0x88,0x03,0x5F,0x02,0x8A};
uint8_t *codePtr = memory;
printf("=============================================================================================");
printf("\nTEST mulwf :\n");
printf("OUTPUT:\n");
printf("\n");
Try {
char *result = disassembleNBytes(&codePtr,4); // the last value represent how many instruction we display
TEST_ASSERT_EQUAL(8, codePtr - memory); //compare number of bytes which been successfully been disassemble
TEST_ASSERT_EQUAL_STRING("mulwf 0x55 ACCESS\nmulwf 0x88 BANKED\nmulwf 0x5f BANKED\nmulwf 0x8a ACCESS\n",result);
} Catch(ex) {
dumpException(ex);
//printf("Error instruction: 0x%2x",ex->errorCode);
}
// freeException(ex);
}
void test_mullw(void)
{
CEXCEPTION_T ex;
uint8_t memory[]={0x0D,0x55,0x0D,0x88};
uint8_t *codePtr = memory;
printf("=============================================================================================");
printf("\nTEST mulwf :\n");
printf("OUTPUT:\n");
printf("\n");
Try {
char *result = disassembleNBytes(&codePtr,2); // the last value represent how many instruction we display
TEST_ASSERT_EQUAL(4, codePtr - memory); //compare number of bytes which been successfully been disassemble
TEST_ASSERT_EQUAL_STRING("mullw 0x55\nmullw 0x88\n",result);
} Catch(ex) {
dumpException(ex);
//printf("Error instruction: 0x%2x",ex->errorCode);
}
// freeException(ex);
}
|
C
|
/*
*@FileName:Example_16_12.c
*@Author: Liu Yang
*@Date: 2020/6/8 10:17
*@Email:[email protected]
*@Last Modified time: 2020/6/8 10:17
*/
//ԤԤʶ
#include "stdio.h"
void why_me(void);
int main(void) {
printf("The file is %s.\n",__FILE__);
printf("The date is %s.\n",__DATE__);
printf("The time is %s.\n",__TIME__);
printf("The version is %ld.\n",__STDC_VERSION__);
printf("This is line %d.\n",__LINE__);
printf("The function is %s.\n",__func__);
why_me();
return 0;
}
void why_me(void )
{
printf("This function is %s.\n",__func__);
printf("This is line %d.\n",__LINE__);
}
|
C
|
#include <criterion/criterion.h> // No borrar esto!
#include "lista.h" // Modificar con el nombre de la api que se le entrega al alumno!
Test(misc, test_k_1) {
int data[6] = {1,5,10,3,6,8};
lista_t* lista = lista_crear();
for (int i=5; i>=0; i--) {
lista_insertar_primero(lista, (void*) &data[i]);
}
int r = *(int*) lista_ante_k_ultimo(lista, 1);
cr_assert(r == 8);
}
Test(misc, test_k_2) {
int data[6] = {1,5,10,3,6,8};
lista_t* lista = lista_crear();
for (int i=5; i>=0; i--) {
lista_insertar_primero(lista, (void*) &data[i]);
}
int r = *(int*) lista_ante_k_ultimo(lista, 2);
cr_assert(r == 6);
}
Test(misc, test_k_3) {
int data[6] = {1,5,10,3,6,8};
lista_t* lista = lista_crear();
for (int i=5; i>=0; i--) {
lista_insertar_primero(lista, (void*) &data[i]);
}
int r = *(int*) lista_ante_k_ultimo(lista, 3);
cr_assert(r == 3);
}
Test(misc, test_k_largo) {
int data[6] = {1,5,10,3,6,8};
lista_t* lista = lista_crear();
for (int i=5; i>=0; i--) {
lista_insertar_primero(lista, (void*) &data[i]);
}
int r = *(int*) lista_ante_k_ultimo(lista, 6);
cr_assert(r == 1);
}
|
C
|
#include <stdio.h>
#include "common.h"
// 结构体
struct MyStruct{
int a;
int b;
int c;
};
// 用指针来遍历数组
void traverseArr(int arr[], int n){
int *p = arr;
for(int i = 0; i < n; i++){
// (*p)++;
printf("%d\n", *p);
p++;
}
}
int main(){
int arr[10];
int len = sizeof(arr)/sizeof(int);
// getArr(arr, len);
// printArr(arr, len);
// traverseArr(arr, len);
// 声明了结构体对象 ss
struct MyStruct ss = {11, 22, 33};
struct MyStruct *p = &ss;
int *p1 = (int*)&ss;
printf("%d\n", (*p).a);
printf("%d\n", *p1+2);
return 0;
}
|
C
|
/*
* =====================================================================================
*
* Filename: main.c
*
* Description: TCP Server Demo
*
* Version: 1.0
* Created: 01/25/2012 10:09:52 PM
* Revision: none
* Compiler: gcc
*
* Author: D.N. Amerasinghe (Niva), [email protected]
* Company: HobbyWorks
*
* =====================================================================================
*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#define PORT_NUM 3333
#define BACK_LOG 5
#define BUFF_SIZE 255
int
main( int argc, char *argv[] )
{
int fd, ret, cli_fd, num_bytes;
struct sockaddr_in svr, cli;
char buff[ BUFF_SIZE ];
memset( &svr, 0, sizeof(struct sockaddr_in) );
svr.sin_family = AF_INET;
svr.sin_port = htons( PORT_NUM );
//inet_aton( "127.0.0.1", ( struct in_addr * )&svr.sin_addr.s_addr );
svr.sin_addr.s_addr = INADDR_ANY;
/*
* For Server Side
* socket()
* bind()
* listen()
* accept()
*/
fd = socket( AF_INET, SOCK_STREAM, 0 );
if( fd == -1 ){
perror("socket");
return -1;
}
ret = bind( fd, (struct sockaddr *)&svr,
sizeof( struct sockaddr ) );
if( ret == -1 ){
perror("bind");
return -1;
}else{
printf("bind() Succeeded...\n");
}
ret = listen( fd, 5 );
if( ret == -1 ){
perror("listen");
return -1;
}else{
printf("listen() Succeeded...\n");
}
int f = sizeof(struct sockaddr_in);
for(;;){
/*
cli_fd = accept( fd, (struct sockaddr *)&cli,
( socklen_t * )sizeof(struct sockaddr_in) );
*/
cli_fd = accept( fd, (struct sockaddr *)&cli, &f );
if( cli_fd == -1 ){
return -1;
break;
}else{
printf("Accepting Connections...\n");
}
while( (num_bytes = recv( cli_fd, buff, BUFF_SIZE, 0 )) > 0 ){
printf("reading bytes...\n");
buff[ BUFF_SIZE ] = '\0';
printf( "%s\n", buff );
}
if( num_bytes == -1 ){
perror("read");
break;
}
if( close(cli_fd) == -1 ){
perror("close");
//break;
}
}
}
|
C
|
#ifdef __cplusplus
extern "C" {
#endif
/************************************************************************
*
* MDV_HANDLE.H
*
* MDV handle struct header file
*
* May 1997
*************************************************************************/
# ifndef MDV_HANDLE_H
# define MDV_HANDLE_H
#include "mdv_file.h"
/**************
* MDV_handle_t
*
* The MDV_handle_handle_t is a container class for an entire
* volume.
*
* It is initialized by MDV_init_handle(), and freed by
* MDV_free_handle().
*/
typedef struct {
MDV_master_header_t master_hdr;
MDV_field_header_t *fld_hdrs; /* array of field headers */
MDV_vlevel_header_t *vlv_hdrs; /* array of vlevel headers */
MDV_chunk_header_t *chunk_hdrs; /* array of chunk headers */
void **chunk_data; /* array of pointers to chunk data */
void ***field_plane; /* array of field plane pointers -
* field_plane[ifield][iplane] */
/*
* memory allocation
*/
int n_fields_alloc;
int n_chunks_alloc;
int n_levels_alloc;
/*
* read_all flag - gets set after a read_all
*/
int read_all_done;
} MDV_handle_t;
/*
* prototypes
*/
/*************************************************************************
*
* MDV_init_handle
*
* initializes the memory associated with handle
*
* Returns 0 on success, -1 on failure.
*
**************************************************************************/
extern int MDV_init_handle(MDV_handle_t *mdv);
/*************************************************************************
*
* MDV_free_handle
*
* Frees the memory associated with handle
*
**************************************************************************/
extern void MDV_free_handle(MDV_handle_t *mdv);
/*****************************************************************************
*
* MDV_set_volume3d: get a volume of mdv data and return it as a
* three-dimensional array.
*
* The MDV_handle_t stores field data as a 2-d array.
*
* NOTE: the caller is responsible for freeing the 3d dataset
* by calling MDV_free_dataset3d()
*
****************************************************************************/
extern void *** MDV_set_volume3d( MDV_handle_t *mdv, int field_index,
int return_type, int nrepeat_beams );
/*****************************************************************************
*
* MDV_free_volume3d: free memory associated with 3-d pointers
*
****************************************************************************/
extern void MDV_free_volume3d(void ***three_d_array, int nrepeat_beams );
/*************************************************************************
*
* MDV_alloc_handle_arrays()
*
* allocates memory for handle arrays
*
**************************************************************************/
extern void MDV_alloc_handle_arrays(MDV_handle_t *mdv,
int n_fields,
int n_levels,
int n_chunks);
/*************************************************************************
*
* MDV_field_name_to_pos
*
* Returns field position to match the name.
* Returns -1 on error (name not in file).
*
* NOTE: must use MDV_read_all() before using this function.
*
**************************************************************************/
extern int MDV_field_name_to_pos(MDV_handle_t *mdv,
char *field_name);
#endif /* MDV_HANDLE_H */
#ifdef __cplusplus
}
#endif
|
C
|
#include "abb.h"
#include "testing.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
/* ******************************************************************
* PRUEBAS UNITARIAS ALUMNO
* *****************************************************************/
int cmp(const char* c1, const char* c2){
if (atoi(c1) == atoi(c2))return 0;
else if(atoi(c1) > atoi(c2))return 1;
return -1;
}
void pruebas_abb_alumno() {
//CREAR ARBOL VACIO
abb_t* arbol_vacio = abb_crear(cmp,NULL);
print_test("se creo el arbol vacio", abb_cantidad(arbol_vacio) == 0);
abb_destruir(arbol_vacio);
//INSERTAR ELEMENTOS ESTATICOS EN EL ARBOL Y BORRARLOS
abb_t* arbol_1= abb_crear(cmp,NULL);
char* val_1= "1";
char* val_2= "3";
char* val_3= "2";
abb_guardar(arbol_1,val_1,val_1);
print_test("se guardo un elemento en el arbol",abb_cantidad(arbol_1) == 1 );
print_test("pertenece el 1",abb_pertenece(arbol_1,val_1));
abb_guardar(arbol_1,val_2,val_2);
print_test("se guardo dos elemento en el arbol",abb_cantidad(arbol_1) == 2 );
print_test("pertenece el 2",abb_pertenece(arbol_1,val_2));
abb_guardar(arbol_1,val_3,val_3);
print_test("se guardo tres elemento en el arbol",abb_cantidad(arbol_1) == 3 );
print_test("pertenece el 3",abb_pertenece(arbol_1,val_3));
char* dato = abb_obtener(arbol_1,val_2);
print_test("el dato es el val_2", atoi(dato)==atoi(val_2));
char* val_4= "5";
char* val_5= "4";
abb_guardar(arbol_1,val_4,val_4);
abb_guardar(arbol_1,val_5,val_5);
print_test("la cantidad es 5", abb_cantidad(arbol_1) == 5);
abb_borrar(arbol_1,val_1);
printf("cantidad es %zu\n",abb_cantidad(arbol_1));
abb_borrar(arbol_1,val_2);
printf("cantidad es %zu\n",abb_cantidad(arbol_1));
abb_borrar(arbol_1,val_3);
printf("cantidad es %zu\n",abb_cantidad(arbol_1));
abb_borrar(arbol_1,val_5);
printf("cantidad es %zu\n",abb_cantidad(arbol_1));
abb_borrar(arbol_1,val_4);
printf("cantidad es %zu\n",abb_cantidad(arbol_1));
abb_destruir(arbol_1);
//PRUEBAS REMPLAZAR
//PRUEBAS ITERADOR
abb_t* arbol_2 = abb_crear(cmp,NULL);
char* valor_1= "1";
char* valor_2= "3";
char* valor_3= "2";
abb_guardar(arbol_2,valor_1,valor_1);
abb_guardar(arbol_2,valor_2,valor_2);
abb_guardar(arbol_2,valor_3,valor_3);
abb_iter_t* iter= abb_iter_in_crear(arbol_2);
print_test("esta al final es falso",!abb_iter_in_al_final(iter));
print_test("el actual es 1",atoi(abb_iter_in_ver_actual(iter)) == 1);
abb_iter_in_avanzar(iter);
print_test("esta al final es falso",!abb_iter_in_al_final(iter));
print_test("el actual es 2",atoi(abb_iter_in_ver_actual(iter)) == 2);
abb_iter_in_avanzar(iter);
print_test("esta al final es falso",!abb_iter_in_al_final(iter));
print_test("el actual es 3",atoi(abb_iter_in_ver_actual(iter)) == 3);
abb_iter_in_avanzar(iter);
print_test("esta al final",abb_iter_in_al_final(iter));
abb_destruir(arbol_2);
abb_iter_in_destruir(iter);
}
|
C
|
#include <stdio.h>
#include <math.h>
#define num_input_first_line 3
float Find_Hypotenuse(int a, float b );
void Do_Matches_Fit(int n, float hyp );
int main()
{
int i, num_lines_of_input, width;
float length, hypotenuse;
//get how many consecutive lines of input there will be
//get dimensions of container
scanf("%d", &num_lines_of_input);
scanf("%d", &width);
scanf("%f", &length);
hypotenuse = Find_Hypotenuse(width, length);
//check all matches — see if fit — print results
Do_Matches_Fit(num_lines_of_input, hypotenuse);
return 0;
}
//----------------------------------------------------------
float Find_Hypotenuse(int a, float b )
{
return sqrt( pow(a, 2) + pow(b, 2) );
}
//----------------------------------------------------------
void Do_Matches_Fit(int n, float hyp )
{
int i;
short match_length;
//check all matches
for(i=0; i<n; i++)
{
scanf("%hu", &match_length);
//print DA if match fits in container —otherwise NE
printf( "%s\n", (match_length <= hyp) ? "DA": "NE");
}
}
|
C
|
#pragma once
struct Vector2;
struct Vector4;
struct Vector3
{
static Vector3 Forward;
static Vector3 Up;
static Vector3 Right;
static Vector3 Zero;
static Vector3 One;
static Vector3 Epsilon;
static Vector3 cMin;
static Vector3 cMax;
union
{
struct
{
float x, y, z;
};
struct
{
float r, g, b;
};
float v[3];
};
/*
This union lets us access the data in multiple ways
All of these are modifying the same location in memory
Vector3 vec;
vec.z = 1.0f;
vec.b = 2.0f;
vec.v[2] = 3.0f;
*/
// Non-Default constructor, self explanatory
Vector3(float xx = 0.0f, float yy = 0.0f, float zz = 0.0f);
// Copy constructor
Vector3(const Vector3 &other);
// Move constructor
Vector3(const Vector3 &&other);
Vector3(const Vector2 &other);
Vector3(const Vector4 &other);
// Assignment operator, does not need to handle self assignment
Vector3 &operator=(const Vector3& rhs);
// Unary negation operator, negates all components and returns a copy
Vector3 operator-(void) const;
// Basic Vector math operations. Add Vector to Vector B, or Subtract Vector A
// from Vector B, or multiply a vector with a scalar, or divide a vector by
// that scalar
Vector3 operator+(const Vector3& rhs) const;
Vector3 operator-(const Vector3& rhs) const;
Vector3 operator*(const float rhs) const;
Vector3 operator*(const Vector3 &rhs) const;
Vector3 operator/(const float rhs) const;
// Same as above, just stores the result in the original vector
Vector3 &operator+=(const Vector3& rhs);
Vector3 &operator-=(const Vector3& rhs);
Vector3 &operator*=(const float rhs);
Vector3 &operator/=(const float rhs);
// Returns this vector normalized
Vector3 Normalized() const;
// Computes the true length of the vector
float Length() const;
// Computes the squared length of the vector
float LengthSq() const;
// Comparison operators which should use an epsilon defined in
// Utilities.h to see if the value is within a certain range
// in which case we say they are equivalent.
bool operator==(const Vector3& rhs) const;
bool operator!=(const Vector3& rhs) const;
// Computes the dot product with the other vector.
static float Dot(const Vector3 &lhs, const Vector3& rhs);
// Computes the cross product with the other vector.
static Vector3 Cross(const Vector3 &lhs, const Vector3& rhs);
// Normalizes the vector to make the final vector be of length 1. If the length is zero
// then this function should not modify anything.
static void Normalize(Vector3 &out, const Vector3 &in);
//
static void Negate(Vector3 &out);
static Vector3 Min(const Vector3 &a, const Vector3 &b);
static Vector3 Max(const Vector3 &a, const Vector3 &b);
bool operator<(const Vector3 & n) const
{
//return (this->x < n.x && this->y < n.y && this->z < n.z);
return this < &n;
}
static Vector3 &&All(float val);
};
typedef Vector3 Vec3;
typedef const Vector3 &Vec3Param;
|
C
|
#include <stdio.h>
#include <unistd.h>
#include "sense.h"
#include <stdbool.h>
bool checkmate(char *position, int player, bool EP, int EPL){
char dummy[]="----------------------------------------------------------------";
for(int i=0; i<64; i++){
dummy[i]=position[i];
}
//printf("%s\n",dummy);
char holder='-';
if(player==1){
for(int i=0; i<64; i++){
if(position[i]>'A' & position[i]<'Z'){
for(int j=0; j<64; j++){
if(isValid(position, i, j, 0, EP, EPL)){
holder=dummy[j];
dummy[j]=dummy[i];
dummy[i]='-';
if(!check(dummy, player)){
//printf("%s\n",dummy);
return false;
}
dummy[i]=dummy[j];
dummy[j]=holder;
}
}
}
}
}
if(player==2){
for(int i=0; i<64; i++){
if(position[i]>'a' & position[i]<'z'){
for(int j=0; j<64; j++){
if(isValid(position, i, j, 0, EP, EPL)){
holder=dummy[j];
dummy[j]=dummy[i];
dummy[i]='-';
if(!check(dummy, player)){
return false;
}
dummy[i]=dummy[j];
dummy[j]=holder;
}
}
}
}
}
return true;
}
|
C
|
#include <stdio.h>
int main() {
int a = ~(1 << 31);
for (int b = 0; b < 10; b += a)
printf("a\n");
}
|
C
|
/*
** manage_system_memory.c
**
** Made by oleszkiewicz Jonathan
** Email <[email protected]>
**
** Started on Sun Feb 16 22:02:09 2014 oleszkiewicz
** Last update Sun Feb 16 22:19:33 2014 oleszkiewicz
*/
#include "malloc.h"
/**
* Si la zone mémoire contenue entre list.pnt_end_list et list.pnt_end_mem est supérieure ou égale à x pagesize on rend la mémoire au system en utilisant la fonction sbrk()
* @param void
* @return void
*/
void deallocate_pageSize_memory()
{
size_t size;
size_t tmp_size;
if ((size_t)(list.pnt_end_mem - list.pnt_end_list) >= list.sizePage)
{
tmp_size = list.pnt_end_mem - list.pnt_end_list;
size = (tmp_size / list.sizePage) * list.sizePage;
list.pnt_end_mem -= size;
if (sbrk((int)size * -1) == (void *)-1) exit(0);
}
}
/**
* Si la zone mémoire contenue entre list.pnt_end_list et list.pnt_end_mem est inferieur à sizeof(t_block) + size on alloue x pagesize en utilisant la fonction sbrk()
* @param size: taille de l'allocation mémoire demandée
* @return void
*/
void allocate_pageSize_memory(size_t size)
{
size_t memory_wanting;
size_t memory_takes;
if (sizeof(t_block) + size > (size_t)(list.pnt_end_mem - list.pnt_end_list))
{
memory_wanting = (sizeof(t_block) + size - (list.pnt_end_mem - list.pnt_end_list));
memory_takes = (memory_wanting / list.sizePage + 1) * list.sizePage;
if (sbrk(memory_takes) == (void *)-1) exit(0);
list.pnt_end_mem += (memory_takes);
}
}
|
C
|
#include <stdio.h>
#define datatype int
typedef struct loopnode {
datatype data;
struct loopnode *next;
} loopnode;
typedef struct loopnode * looplist_t;
int is_empty_looplist(looplist_t h)
{
return h->next == h ? 1:0;
}
int insert_head_looplist(looplist_t h, datatype x)
{
looplist_t temp;
temp = (looplist_t)malloc(sizeof(loopnode));
temp->data = x;
temp->next = h->next;
h->next = temp;
return 0;
}
datatype delete_head_looplist(looplist_t h)
{
datatype x;
looplist_t temp;
if(is_empty_looplist(h)){
printf("linklist is NULL.\n");
return -1;
}
temp = h->next;
h->next = temp->next;
x = temp->data;
free(temp);
temp = NULL;
return x;
}
int delete_all_looplist(looplist_t h)
{
int i=0;
looplist_t t = h;
looplist_t temp;
if(is_empty_looplist(h)){
printf("linklist is NULL.\n");
return -1;
}
//h = h->next;
while(h->next != t){
temp = h;
h = h->next;
temp->next = NULL;
free(temp);
i++;
}
free(h);
h = NULL;
//printf("i = %d\n", i);
return 0;
}
looplist_t cut_head_looplist(looplist_t h)
{
looplist_t p = h;
if(is_empty_looplist(h)){
printf("linklist is NULL.\n");
return -1;
}
while(h->next != p){
h = h->next;
}
h->next = p->next;
free(p);
p = NULL;
return h->next;
}
void print_looplist(looplist_t h, int new_head)
{
int i = 0;
looplist_t temp = h;
if(is_empty_looplist(h) || h->next == NULL){
printf("linklist is NULL or freed.\n");
return -1;
}
if(new_head)
printf("%d: h->data=%d\t", i, h->data);
while(h->next != temp){
printf("%d: h->next->data=%d\t", i, h->next->data);
h = h->next;
i++;
}
printf("\n");
}
int main(int argc, const char **argv)
{
int i;
looplist_t demo;
looplist_t new_head;
demo = (looplist_t)malloc(sizeof(loopnode));
demo->next = demo;
demo->data = 0;
for(i=0; i<5; i++){
insert_head_looplist(demo, i);
}
print_looplist(demo, 0);
delete_head_looplist(demo);
print_looplist(demo, 0);
new_head = cut_head_looplist(demo);
print_looplist(new_head, 1);
delete_all_looplist(new_head);
print_looplist(new_head, 1);
return 0;
}
|
C
|
#include "sort.h"
#include "unity.h"
#include "unity_fixture.h"
#include <stdlib.h>
#include <string.h>
TEST_GROUP(sort);
TEST_SETUP(sort){
}
TEST_TEAR_DOWN(sort){
}
TEST(sort, TestSort1){
int v[] = {5,6,7,10,3,4,5,1,6,9,8};
int size = 11;
qsort(v, size, sizeof(int), comp_int);
//printf("\n");
for (int i=0; i<size-1; i++) {
//printf("i: %d\t i+1: %d\n", v[i], v[i+1]);
if (v[i] != v[i+1])
TEST_ASSERT_GREATER_THAN(v[i], v[i+1]);
}
}
TEST(sort, TestSort2) {
float v[] = {5.2, 6.3, 7.0, 10.0, 3.2, 4.1, 5.5, 1.0, 6.6, 9.3, 8.7};
int size = 11;
qsort(v, size, sizeof(float), comp_int);
//printf("\n");
for (int i=size-1; i>0; i--) {
//printf("i: %d\t i-1: %d\n", v[i], v[i-1]);
if (v[i] != v[i-1])
TEST_ASSERT((v[i] > v[i-1]) ? 1:0);
}
}
TEST(sort, TestSort3) {
char v[] = {'a', 'd', 'b', 'a'};
int size = 5;
qsort(v, size, sizeof(char), comp_char);
//printf("\n");
for (int i=size+1; i<size-2; i++) {
//printf("i: %c\t i+1: %c\n", v[i], v[i+1]);
if (v[i] != v[i+1])
TEST_ASSERT_GREATER_THAN(v[i], v[i+1]);
}
}
TEST(sort, TestSort4) {
char *v[] = {"aa", "ee", "dd", "bb"};
int size = 4;
qsort(v, size, sizeof(char*), comp_str);
for (int i=1; i<size-2; i++) {
if(strcmp(v[i], v[i+1]) != 0)
TEST_ASSERT((strcmp(v[i], v[i+1]) < 0) ? 1:0);
}
}
|
C
|
/*
** my_list_swap.c for libmy in /home/raphy/Developement/Libraries/libmy/list
**
** Made by raphael defreitas
** Login <[email protected]>
**
** Started on Mon Jan 28 11:36:56 2013 raphael defreitas
** Last update Mon Jan 28 11:55:46 2013 raphael defreitas
*/
#include <stdlib.h>
#include "my.h"
int my_list_swap(t_list_item *item1, t_list_item *item2)
{
void *tmp;
int id;
if (item1 == NULL || item2 == NULL)
return (RET_FAILURE);
tmp = item1->data;
id = item1->id;
item1->data = item2->data;
item1->id = item2->id;
item2->data = tmp;
item2->id = id;
return (RET_SUCCESS);
}
|
C
|
#ifndef _TREE_C
#define _TREE_C
#include "tree.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
//does smth for each node in subtree
struct Visitor{
struct Node* node;
FILE* file;
};
//FIRST FUNC(LEFT) FUNC(RIGHT) THEN FUNC(NODE)
int VisitorLRN(struct Node* node, int (*func)(struct Node*)) {
assert(func != NULL);
assert(node != NULL);
if (node -> left != NULL) {
if (VisitorLRN(node -> left, func) == 0)
return 0;
}
if (node -> right != NULL) {
if (VisitorLRN(node -> right, func) == 0)
return 0;
}
return func(node);
}
//returns 0 on success
//otherwise 1
int TreeDump(struct Node* node, FILE* file) {
if (node == NULL)
return 1;
else {
fprintf(file, "{\n");
if ((node -> data)[strlen(node -> data) - 1] != '\n') {
fprintf(file, "%s\n", node -> data);
}
else
fprintf(file, "%s", node -> data);
if (node -> left != NULL)
TreeDump(node -> left, file);
if (node -> right != NULL)
TreeDump(node -> right, file);
fprintf(file, "}\n");
return 0;
}
return 1;
}
//returns 0 on success
//otherwise 1
int NodeDump(struct Node* node) {
printf("\n---------------\n");
if (node == NULL) {
printf("*node = NULL\n");
return 1;
}
printf("*(node): %p\n", node);
printf("node -> data: %s\n", node -> data);
printf("*(node -> parent): %p\n", node -> parent);
printf("*(node -> left): %p\n", node -> left);
printf("*(node -> right): %p\n", node -> right);
printf("\n---------------\n");
return 0;
}
int SubTreeDestroy(struct Node* node) {
free(node);
return 1;
}
//returns 1 on success
//otherwise 0
int TreeDestroy(struct Node* node) {
assert(node != NULL);
int ret = VisitorLRN(node, SubTreeDestroy);
return ret;
}
enum Flags{
NONE, // 0
LEFT, // 1
RIGHT // 2
};
//retruns Node* on success
//otherwise returns NULL
struct Node* HeadInit(const char* data) {
struct Node* new = calloc(1, sizeof(struct Node));
if (new == NULL)
return NULL;
strncpy(new -> data, data, STR_LEN);
return new;
}
//If flag == NONE, copies string from *data to node -> data
//and returns strutc Node* node.
//If *node == NULL returns HeadInit(data).
//Otherwise returns Node* on succes and NULL if error appeared.
//If flag == LEFT, creates Node* new: new -> parent = node
//and node -> left = new.
//If flag == RIGHT, creates Node* new: new -> parent = node
//and node -> right = new.
struct Node* AddNode(const char* data, struct Node* node, int flag) {
if (node == NULL) {
return HeadInit(data);
}
if (flag == NONE) {
strncpy(node -> data, data, STR_LEN);
return node;
}
struct Node* new = calloc(1, sizeof(struct Node));
if (new == NULL)
return NULL;
if (flag == LEFT) {
(node) -> left = new;
}
if (flag == RIGHT) {
(node) -> right = new;
}
strncpy(new -> data, data, STR_LEN);
new -> left = NULL;
new -> right = NULL;
new -> parent = node;
return new;
}
//Recursively reads file, pointed by FILE* in and creates a tree by nodes.
//*node rewrites: it now points at the head of subtree.
//returns *node on success and NULL otherwise.
struct Node* FileAddNode(struct Node** node, FILE* in) {
assert(in != NULL);
assert(node != NULL);
char* buffer = calloc(STR_LEN, sizeof(char));
fgets(buffer, STR_LEN, in); //node -> data value
AddNode(buffer, *node, NONE);
fgets(buffer, STR_LEN, in); // expect {
if (buffer[0] == '}') {
free(buffer);
return NULL;
}
struct Node* left = calloc(1, sizeof(struct Node));
(*node) -> left = left;
left -> parent = (*node);
FileAddNode(&left, in);
fgets(buffer, STR_LEN, in); // expect {
if (buffer[0] == '}') {
free(buffer);
return NULL;
}
struct Node* right = calloc(1, sizeof(struct Node));
right -> parent = (*node);
(*node) -> right = right;
FileAddNode(&right, in);
fgets(buffer, STR_LEN, in); // expect }
free(buffer);
return *node;
}
//Reads file, pointed by FILE* in and creates a tree.
//Creates and returns head of this tree.
//If error appeared returns NULL.
struct Node* TreeInit(FILE* in) {
struct Node* head = calloc(1, sizeof(struct Node));
char* buffer = calloc(STR_LEN, 1);
fgets(buffer, STR_LEN, in); //expect {
if (buffer[0] != '{') {
free(buffer);
free(head);
return NULL;
}
FileAddNode(&head, in);
printf("%p\n", head);
fflush(stdout);
free(buffer);
return head;
}
//*node points at the leaf that needs to be separated
//Creates 2 nodes: separeting and second leaf
//separating -> left = second leaf
//separating -> right = separated(aka node)
//Returns NULL if error appeared
//Returns Node* sep of the separating node
struct Node* SplitNode(struct Node* node, const char* separating,
const char* data) {
assert(node != NULL);
struct Node* sep = HeadInit(separating);
struct Node* new = HeadInit(data);
if (new == NULL || sep == NULL)
return NULL;
sep -> parent = node -> parent;
sep -> left = new;
sep -> right = node;
new -> parent = sep;
if (node -> parent -> left == node) {
node -> parent -> left = sep;
}
else {
node -> parent -> right = sep;
}
node -> parent = sep;
return sep;
}
#endif //_TREE_C
|
C
|
void reverseArray(int *a, int size)
{
int arr[size];
int i = 0, j = size - 1;
while(i < size && j >= 0)
{
arr[i] = a[j];
i++;
j--;
}
for(i = 0; i < size; i++)
a[i] = arr[i];
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m=0, n, i=0, j=0, a=0, b=0, number, q;
scanf("%d", &n);
for (m=0;m<n;m++){
scanf("%d", &number);
q=number%2;
if (q==0){
i=i+1;
a=a+number;}
else{
j=j+1;
b=b+number;
}
}
printf("%d/n%d/n%d/n%d/n", j, b, a, i);
return 0;
}
|
C
|
int check_palindrome_recursive(char *start, char *end);
int _strlen_recursion(char *s);
/**
* is_palindrome - checks if string is palindrome
*
* @s: string to check
*
* Return: 1 if palindrome, 0 otherwise
*/
int is_palindrome(char *s)
{
char *end;
int sLength;
if (!*s) /* empty string */
return (1);
sLength = _strlen_recursion(s);
end = (s + (sLength - 1)); /* set end to char before null byte */
return (check_palindrome_recursive(s, end));
}
/**
* check_palindrome_recursive - checks if string is palindrome
*
* @start: starting point of string to check
* @end: last valid character in string before null byte
*
* Return: 1 if palindrome, 0 if failure (not palindrome)
*/
int check_palindrome_recursive(char *start, char *end)
{
if (*start != *end)
return (0);
if (start > end) /* checked all chars up to middle */
return (1);
return (check_palindrome_recursive(start + 1, end - 1));
}
/**
* _strlen_recursion - gets strlen of s via recursive algorithm
*
* @s: string to check length of
*
* Return: int containing length of string
*/
int _strlen_recursion(char *s)
{
if (!*s)
return (0);
return (1 + _strlen_recursion(s + 1));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_width.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gschaetz <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/09 16:19:15 by gschaetz #+# #+# */
/* Updated: 2017/04/12 12:17:47 by gschaetz ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
char *ft_stock_in_tmp(t_printf *var, int j, int i, char *tmp)
{
int k;
char *st;
k = 0;
st = var->format_split[i].stock;
while (ft_isdigit(st[j]) == 1)
tmp[k++] = st[j++];
tmp[k] = '\0';
return (tmp);
}
void ft_identifi_width(int i, int j, t_printf *var)
{
char *tmp;
int k;
char *st;
k = 0;
st = var->format_split[i].stock;
tmp = ft_strnew(10);
var->format_split[i].width = 0;
while (ft_isdigit(st[j]) != 1 && st[j] != '\0')
j++;
if (st[j] == '\0' || st[j - 1] == '.')
{
free(tmp);
return ;
}
while (st[j] == '0' || st[j] == ' ' || st[j] == '+' || st[j] == '-')
j++;
if (ft_isdigit(st[j]) == 1)
tmp = ft_stock_in_tmp(var, j, i, tmp);
if (tmp[0] == '\0')
var->format_split[i].width = 0;
else
var->format_split[i].width = ft_atoi(tmp);
free(tmp);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <signal.h>
ssize_t yh_printf(const char *format, ...) {
va_list vl;
va_start(vl, format);
char buf[4096] = { 0 };
vsnprintf(buf, sizeof(buf), format, vl);
buf[strlen(buf)] = '\n';
ssize_t bytes = 0;
for (bytes = 0; bytes < strlen(buf); bytes++)
if (write(STDOUT_FILENO, buf + bytes, 1) != 1) /* 让内核态切换更加频繁 */
break;
va_end(vl);
return bytes;
}
typedef void(*sig_handler)(int);
sig_handler yh_signal(int signo, sig_handler handler) {
struct sigaction new_act, old_act;
bzero(&new_act, sizeof(new_act));
if (signo == SIGALRM) {
#ifdef SA_INTERRUPT
new_act.sa_flags |= SA_INTERRUPT;
#endif
} else {
new_act.sa_flags |= SA_RESTART;
}
sigemptyset(&new_act.sa_mask);
new_act.sa_handler = handler;
if (sigaction(signo, &new_act, &old_act) < 0)
return SIG_ERR;
return old_act.sa_handler;
}
void sig_internal_handler(int signo) { /* do nothing */ }
void PREPARE() {
sigset_t new_mask;
sigemptyset(&new_mask);
sigaddset(&new_mask, SIGUSR1);
sigaddset(&new_mask, SIGUSR2);
if (sigprocmask(SIG_BLOCK, &new_mask, NULL) < 0) {
perror("sigprocmask error");
exit(1);
}
if (yh_signal(SIGUSR1, sig_internal_handler) == SIG_ERR) {
perror("yh_signal error");
exit(1);
}
if (yh_signal(SIGUSR2, sig_internal_handler) == SIG_ERR) {
perror("yh_signal error");
exit(1);
}
}
void WAIT_PARENT() {
sigset_t mask;
sigemptyset(&mask);
sigfillset(&mask);
sigdelset(&mask, SIGUSR1);
sigsuspend(&mask);
}
void TELL_CHILD(pid_t pid) {
kill(pid, SIGUSR1);
}
void WAIT_CHILD() {
sigset_t mask;
sigfillset(&mask);
sigdelset(&mask, SIGUSR2);
sigsuspend(&mask);
}
void TELL_PARENT(pid_t pid) {
kill(pid, SIGUSR2);
}
int main(int argc, char *argv[]) {
PREPARE();
pid_t pid;
if ((pid = fork()) < 0) {
perror("fork error");
exit(1);
} else if (pid == 0) {
WAIT_PARENT();
char buf[20];
memset(buf, 'A', sizeof(buf));
buf[sizeof(buf) - 1] = 0;
yh_printf(buf);
TELL_PARENT(getppid());
} else {
char buf[20];
memset(buf, 'O', sizeof(buf));
buf[sizeof(buf) - 1] = 0;
yh_printf(buf);
TELL_CHILD(pid);
WAIT_CHILD();
}
return 0;
}
|
C
|
// Write a function with prototype
// int arr_norm(int *arr, int len)
// which returns the norm of the array arr defined as the sum of the
// square of each of the elements of the array arr, which has length len.
#include <stdio.h>
// begin question
int arr_norm(int* arr, int len) {
int ret = 0;
for (int i = 0; i < len; i++) {
ret += arr[i] * arr[i];
}
return ret;
}
// end question
int main() {
#define ARR_LENGTH 3
int arr[ARR_LENGTH] = {1, 2, 3};
printf("%i\n", arr_norm(arr, ARR_LENGTH));
return 0;
}
|
C
|
/*-----------------------------+
プログラミング及び演習II 第2回
問題 B-1
キーボード入力された1~255までの数値
(unsigned int型の10進数)を16進数
で表示するプログラムを作れ
+-----------------------------*/
#include <stdio.h>
#define RADIX 16
void print16(int n);
int main(int argc, const char* argv[])
{
unsigned int n; // 入力値を格納する変数
printf("1~255の整数値を入力してください: ");
scanf("%d", &n);
if(n < 1 || 255 < n){
printf("入力値が範囲外です");
}else{
print16(n / RADIX);
print16(n % RADIX);
printf("\n");
}
return(0);
}
//--------------------------------
//0~15の10進数nを16進数で表示する関数
//--------------------------------
void print16(int n)
{
if(n <= 9){
printf("%d", n);
}else{
switch (n) {
case 10: printf("A"); break;
case 11: printf("B"); break;
case 12: printf("C"); break;
case 13: printf("D"); break;
case 14: printf("E"); break;
case 15: printf("F"); break;
}
}
return;
}
|
C
|
#pragma once
#include<Windows.h>
#include<stdio.h>
/*
ʂ̃NA␔A̓͂Ȃǂ̔ėp̂VXe
*/
//̓͂܂
int GetKeyInput() {
int key;
while (1) {
key = getchar();
//͂ꂽL[s̏ꍇAs
if (key == '\n')printf("Illegal Input(Enter)\n");
//sȊȌꍇAȉ̏
else {
//ɓǂݍsȂA
if (getchar() == '\n') {
//printf("Success\n");
break;
}
//ȊO̕ĂAs
//̌Aobt@NA
else {
while (getchar() != '\n');
printf("Illegal Input(not 1 char)\n");
}
}
}
return key;
}
//̓͂܂
int GetNumberInput() {
int key;
while (1) {
key = getchar()-'0';
//͂ꂽL[s̏ꍇAs
if (key == '\n')printf("Illegal Input(Enter)\n");
else if (0 >= key || key >= 9) {while (getchar() != '\n'); printf("l͂ȂĂ\n"); continue; }
//sȊȌꍇAȉ̏
else {
//ɓǂݍsȂA
if (getchar() == '\n') {
//printf("Success\n");
break;
}
//ȊO̕ĂAs
//̌Aobt@NA
else {
while (getchar() != '\n');
printf("Illegal Input(not 1 char)\n");
}
}
}
return (int)key;
}
//EnterĂʂV܂
void Renew() {//EnterƉʂXV܂
int c;
printf("enterƎɐi݂܂");
if ((c = getchar()) == '\n') {}
else { while (getchar() != '\n'); }
system("cls");
}
//Enteri݂܂
void Pause() {//Enter܂Őɐi݂܂
int c;
printf("enterƎɐi݂܂");
if ((c = getchar()) == '\n') {}
else { while (getchar() != '\n'); }
}
//vC[̎ԂĂ܂
void Player(int player_id) {
if (player_id == 0) {printf("player1̎ԂłB\n");}
else if(player_id == 1){printf("player2̎ԂłB\n");}
}
//̎ԂQƂ܂
int Enemy(int player_id) {
if (player_id == 1) {
return 0;
}
else if (player_id == 0) {
return 1;
}
else { printf("error!\n"); return 10; }
}
|
C
|
#include <stdio.h>
int main() {
int f = 16;
f = sqrt(f); // please square root f's value
printf("%d \n", f);
return 0;
}
qrt(f); // please square root f's value
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
bool IsPrime(int num);
int main(void){
int r1, r0, r_1, f1, f0, f_1, g1, g0, g_1, d, e, L, i, q, tmp, counter;
int lcm = 0;
//bool primeFlag1, primeFlag2;
tmp= 0;
counter = 1;
printf("異なる整数を二つ入力してください\n");
printf("整数1:\n>>");
scanf("%d", &e);
printf("整数2:\n>>");
scanf("%d", &L);
/*
primeFlag1 = IsPrime(e);
primeFlag2 = IsPrime(L);
*/
if(e == L){
printf("エラー: 異なる整数を入力してください\n");
return 1;
}/*else if(primeFlag1 == false || primeFlag2 == false){
printf("素数を入力してください\n");
return 1;
}*/else if(e < L){
tmp = L;
L = e;
e = tmp;
}
r_1 = e;
r0 = L;
r1 = 1;
f_1 = 1;
f0 = 0;
g_1 = 0;
g0 = 1;
while(r1 > 0){
r1 = r_1 % r0;
q = (r_1 - r1)*1.0/r0;
f1 = f_1 -q*f0;
g1 = g_1 -q*g0;
d = f1*e + g1*L;
printf("r%d(f*a + g*b) = %d\n", counter, d);
printf("f%d = %d\n",counter, f1);
printf("g%d = %d\n",counter, g1);
printf("r%d = %d\n", counter, r1);
printf("q%d = %d\n\n", counter, q);
tmp = r0 % r1;
if(tmp == 0){break;}
r_1 = r0;
r0 = r1;
f_1 = f0;
f0 = f1;
g_1 = g0;
g0 = g1;
counter = counter + 1;
}
printf("d_%d = %d\n",e, f1);
printf("gcd(%d, %d) = %d\n", e, L, r1);
return 0;
}
/*
bool IsPrime(int num){
if (num < 2) return false;
else if (num == 2) return true;
else if (num % 2 == 0) return false; // 偶数はあらかじめ除く
int i;
double sqrtNum;
sqrtNum = sqrt(num);
for (i = 3; i <= sqrtNum; i += 2)
{
if (num % i == 0)
{
// 素数ではない
return false;
}
}
// 素数である
return true;
}
*/
|
C
|
/*
Задача 7.
Заделяне на памет с calloc
Заделете динамична памет за масив от елементи, като извикате функция, която нулира заделената памет.
Преписал съм си кода от първа задача, защото ползвах calloc там, вместо malloc.
*/
#include <stdio.h>
#include <stdlib.h>
int EnterElements(int *p, int MaxElem);
int main(){
//Variables go here:
short NrElements = 0;
//Methods go here:
printf("Please enter how many elements do you need: \n");
scanf("%d", &NrElements);
int *Pointy = calloc(NrElements, sizeof(int));
if (Pointy == NULL){
printf("I am terribly sorry, Sir! Something went wrong. Have a jolly afternoon.\n");
return 1;
}
EnterElements(Pointy, NrElements);
free(Pointy);
//return partameters go here (if any):
}
int EnterElements(int *p, int MaxElem){
printf("Please enter the desired elements of the array:\n");
for(int i=0; i < MaxElem; i++){
scanf("%d", &p[i]);
}
for(int i=0; i < MaxElem; i++){
printf("%d ", p[i]);
}
}
|
C
|
//第2次课堂作业
//启动线程计算2*N
#include<stdio.h>
#include<pthread.h>
void*calculate(void*ptr_n)
{
printf("%d\n",2*(*(int*)ptr_n));
return NULL;
}
int main()
{
int n;
pthread_t th;
while(scanf("%d",&n)!=EOF){
if(pthread_create(&th,NULL,calculate,&n)!=0){
printf("pthread error\n");
return 1;
}
pthread_join(th,NULL);
}
return 0;
}
|
C
|
/* Fig. 12.13: fig12_13.c
Operating and maintaining a queue */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "encrypt.h"
/* self-referential structure */
struct Node {
char data[50]; /* define data as a char */
char pass[50];
struct Node *nextPtr; /* Node pointer */
}; /* end structure Node */
typedef struct Node Node;
typedef Node *NodePtr;
/* function prototypes */
bool search(struct Node* topPtr, char data[50], char pass[50]);
bool searchUser(struct Node* topPtr, char data[50]);
void push( NodePtr *topPtr, char info[50], char pass[50] );
void pop( NodePtr *topPtr );
int isEmpty( NodePtr topPtr );
void printStack( NodePtr currentPtr );
void instructions( void );
/* display program instructions to user */
void instructions( void )
{
printf("\t\t\t\t==============================\n");
printf("\t\t\t\t| 1. Add User |\n");
printf("\t\t\t\t| 2. Delete User |\n");
printf("\t\t\t\t| 3. Search User |\n");
printf("\t\t\t\t| 4. Print Users |\n");
printf("\t\t\t\t| 5. Go to Dencryptor Menu |\n");
printf("\t\t\t\t| 6. Admin logout |\n");
printf("\t\t\t\t| 7. Exit Program |\n");
printf("\t\t\t\t==============================\n");
printf("\t\t\t\tSelect Your Choice : ");
} /* end function instructions */
/* insert a node a queue tail */
void push( NodePtr *topPtr, char info[50], char pass[50] )
{
NodePtr newPtr; /* pointer to new node */
newPtr = malloc( sizeof( Node ) );
/* insert the node at stack top */
if ( newPtr != NULL )
{ /* is space available */
strcpy(newPtr->data,info);
strcpy(newPtr->pass,pass);
newPtr->nextPtr = *topPtr;
*topPtr = newPtr;
} /* end if */
else
{
printf( "%s not inserted. No memory available.\n", info );
} /* end else */
} /* end function push */
/* remove node from queue head */
void pop( NodePtr *topPtr )
{
NodePtr tempPtr; /* temporary node pointer */
char popValue[50]; /*node value*/
tempPtr = *topPtr;
strcpy(popValue,( *topPtr )->data);
*topPtr = ( *topPtr )->nextPtr;
free( tempPtr );
printf( "\n\t\t\t\tThe user poped is %s.\n", popValue );
} /* end function pop */
/* Return 1 if the list is empty, 0 otherwise */
int isEmpty( NodePtr topPtr )
{
return topPtr == NULL;
} /* end function isEmpty */
/* Checks whether the value x is present in linked list */
bool search(struct Node* topPtr, char data[50], char pass[50])
{
struct Node* current = topPtr; // Initialize current
while (current != NULL)
{
if ((strcmp(current->data,data)==0)&&(strcmp(current->pass,pass)==0))
return true;
current = current->nextPtr;
}
return false;
}
bool searchUser(struct Node* topPtr, char data[50])
{
struct Node* current = topPtr; // Initialize current
while (current != NULL)
{
if ((strcmp(current->data,data)==0))
return true;
current = current->nextPtr;
}
return false;
}
/* Print the queue */
void printStack( NodePtr currentPtr )
{
/* if queue is empty */
if ( currentPtr == NULL )
{
printf( "\n\t\t\t\tUser is empty.\n" );
} /* end if */
else
{
printf( "\n\t\t\t\tUser, Pass\n" );
/* while not end of queue */
while ( currentPtr != NULL )
{
printf( "\t\t\t\t- %s, %s\n",currentPtr->data,currentPtr->pass);
currentPtr = currentPtr->nextPtr;
} /* end while */
//printf( "NULL\n\n" );
} /* end else */
} /* end function printStack */
void printStackFile( NodePtr currentPtr )
{
FILE *fp; //deklarasi sebuah pointer dari tipe file
fp=fopen("account.txt","w");
fclose(fp);
fp=fopen("account.txt","w");
while ( currentPtr != NULL )
{
fprintf( fp,"%s %s\n",encrypt(currentPtr->data,2),currentPtr->pass); //cetak ke file setelah diencrypt
currentPtr = currentPtr->nextPtr;
} /* end while */
fclose(fp);
} /* end function printStack */
static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
while (current != NULL)
{
// Store next
next = current->nextPtr;
// Reverse current node's pointer
current->nextPtr = prev;
// Move pointers one position ahead.
prev = current;
current = next;
}
*head_ref = prev;
}
|
C
|
#include<stdio.h>
void total(int mins[], int secs[], int n, int *sum_m, int *sum_s){
for (int i = 0; i < n; i++)
{
printf("Enter mins: ");
scanf("%d", &mins[i]);
printf("Enter secs:");
scanf("%d", &secs[i]);
*sum_m += mins[i];
*sum_s += secs[i];
while (*sum_s >= 60)
{
*sum_m += 1;
*sum_s -= 60;
}
}
printf("MIN : %d || SECS : %d\n", *sum_m, *sum_s);
}
int main(){
int min[100];
int sec[100];
int n;
int total_m;
int total_s;
scanf("%d", &n);
total(min, sec, n, &total_m, &total_s);
return 0;
}
|
C
|
void imprimeMatriz(char **m, int nL, int nC)
{
int i, j;
for (i = 0; i < nL; i++)
{
for (j = 0; j < nC; j++)
{
printf(" %c", m[i][j]);
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define KERNEL 0
#define STEP 10
#define WIDTH 10.0
#define GAUSSIAN 0
#define SQUARED 1
char *kernels[] = { "gaussian", "squared" };
#define ROWS 250000
#define COLS 31
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
char line[4096];
double x[ROWS][COLS];
double y[ROWS],w[ROWS];
double sx[ROWS][COLS];
int main() {
char *p,fname[256];
int r,c;
FILE *fp,*out;
fp=fopen("training.csv","r");
p = fgets(line,4096,fp);
sprintf(fname,"smooth_%s_%f_%d.csv",kernels[KERNEL],WIDTH,STEP);
out=fopen(fname,"w");
fprintf(out,"%s",p);
r=0;
while(fgets(line,4096,fp)) {
p=strtok(line,",");
for(c=0;c<COLS;c++) {
x[r][c] = atof(p);
p=strtok(NULL,",");
}
w[r] = atof(p);
p=strtok(NULL,",");
if(p[0]=='s')
y[r]=1;
else
y[r]=0;
r+=1;
}
fclose(fp);
if(r!=ROWS) {
fprintf(stderr,"ERROR: incorrect rows %d vs %d\n",ROWS,r);
exit(1);
}
#pragma omp parallel for
for(c=0;c<COLS;c++) {
double sd,avg,wsum,wtot,dst;
int rows,r1,r2;
avg = 0;
rows = 0;
for(r1=0;r1<ROWS;r1++) {
if(x[r1][c]!=-999.0) {
avg += x[r1][c];
rows++;
}
}
avg /= rows;
sd = 0;
rows = 0;
for(r1=0;r1<ROWS;r1++) {
if(x[r1][c]!=-999.0) {
sd += (avg - x[r1][c]) * (avg - x[r1][c]);
rows++;
}
}
sd = sqrt(sd/rows);
if(sd>0.00001) {
for(r1=0;r1<ROWS;r1++) {
if(x[r1][c]!=-999.0) {
x[r1][c] = (x[r1][c] - avg) / sd;
}
}
}
//for(r=35700;r<35701;r++) {
for(r1=0;r1<ROWS;r1++) {
wtot=0;
wsum=0;
if(x[r1][c]==-999.0) {
for(r2=0;r2<ROWS;r2+=STEP) {
if(r1!=r2) {
if(x[r2][c]==-999.0) {
wsum += y[r2];
wtot += 1;
}
}
}
} else {
if(KERNEL==SQUARED) {
for(r2=0;r2<ROWS;r2+=STEP) {
if(r1!=r2 && x[r2][c]!=-999.0) {
dst = max(0.01,1-(WIDTH*(x[r1][c] - x[r2][c])*(x[r1][c] - x[r2][c])));
wsum += dst * y[r2];
wtot += dst;
}
}
} else {
for(r2=0;r2<ROWS;r2+=STEP) {
if(r1!=r2 && x[r2][c]!=-999.0) {
dst = 1/exp(min(15,WIDTH*(x[r1][c] - x[r2][c])*(x[r1][c] - x[r2][c])));
//printf("%f %f %f %f %f\n",x[r1][c],x[r2][c],dst,wsum,wtot);
wsum += dst * y[r2];
wtot += dst;
}
}
}
}
sx[r1][c]=log(wsum/wtot) - log(1-wsum/wtot);
}
}
for(r=0;r<ROWS;r++) {
for(c=0;c<COLS;c++) {
fprintf(out,"%f,",sx[r][c]);
}
fprintf(out,"%f,%f\n",w[r],y[r]);
}
fclose(out);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void ArrayItemDel(int arr[], int index, int size)
{
if(index >= size)
{
printf("Please enter the correct index number");
}
else
{
for(int i = index; i < size + 1; i++)
{
arr[i]=arr[i+1];
}
printf("The element in the array has been deleted successfully...\n");
for(int i=0; i<size-1; i++)
{
printf("%d\t",arr[i]);
}
}
}
int main()
{
int size,index;
printf("How Many Will Be Produced?: ");
scanf("%d",&size);
int array[size];
srand(time(0));
for(int i=0; i<size; i++)
{
array[i]=rand()%100+1;
printf("%d\t",array[i]);
}
printf("\n\n");
printf("Enter the Sequence Number of the Value to be deleted from the array: ");
scanf("%d", &index);
ArrayItemDel(array,index - 1,size);
return 0;
}
|
C
|
#include <stdio.h>
int main (){
double A, B, C, MEDIA, wa, wb, wc;
scanf("%lf%lf%lf", &A, &B, &C);
wa = 2.0/10;
wb = 3.0/10;
wc = 5.0/10;
MEDIA = (A*wa + B*wb + C*wc);
printf("MEDIA = %.1lf\n", MEDIA);
return 0;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#define DIM_MIN 3
#define DIM_MAX 9
#define TRUE 1
#define FALSE 0
int board[DIM_MAX][DIM_MAX];
void draw(int d)
{
for(int i = 0; i < d; i++){
for(int j = 0; j < d; j++){
printf("%i\t", board[i][j]);
}
printf("\n");
}
}
void init(int d) // Pass in the dimension of the matrix
{
int num_tiles = d*d-1; // Calculate the highest number tile
for( int i = 0; i < d; i++){ // For every row...
for( int j = 0; j < d; j++){ // For every column of that row...
if( num_tiles > 2 ){ // If not on the last row and
// not in the last, second last
// or third last position of
// the last row...
board[i][j] = num_tiles; // Initialize current position
// with value of num_tiles
num_tiles--; // decrement num_tiles
}
else{ // If on the last row
if(d%2 == 0){ // Check if board dimensions are even
if(j == (d-3))
board[i][j] = 1;
else if(j == (d-2))
board[i][j] = 2;
else
board[i][j] = 0;
}
else{
if(j == (d-3))
board[i][j] = 2;
else if(j == (d-2))
board[i][j] = 1;
else
board[i][j] = 0;
}
}
}
}
}
int main(int argc, char* argv[]){
int d = atoi(argv[1]);
init(d);
draw(d);
printf("Enter test tile to find:");
int tile = GetInt();
bool found = FALSE;
int curr_row = -1;
int curr_col = 0;
while(!found){
curr_row++;
for(curr_col = 0; (curr_col < d) && !found; curr_col++){
if(board[curr_row][curr_col] == tile){
found = TRUE;
break;
}
}
}
printf("Tile selected is on row %i, column %i\n", curr_row, curr_col);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char **load_array(char *input_string){
char **array_mem = malloc(3*(sizeof(char *)));
for(int x=0;x<3;x++){
array_mem[x] = malloc(sizeof(char *));
printf("Allocation at %p\n",array_mem[x]);
strcpy(array_mem[x],input_string);
};
return array_mem;
};
int main(int argc, char *argv[]){
char *my_string = "Hello world, this is me";
char **returned_array = load_array(my_string);
for(int x=0;x<3;x++){
printf("%s\n",returned_array[x]);
free(returned_array[x]);
}
return 0;
};
|
C
|
#include <string.h>
#include <stdio.h>
#include "dictionary.h"
static unsigned long hash_function(const char * str) {
unsigned long hash = 0;
#if 0
#define MULTIPLIER 97
for (unsigned const char * us = (unsigned const char *) str; *us; us++) {
hash = hash * MULTIPLIER + *us;
}
#else
// sdbm
unsigned char c;
while ((c = *str++)) {
hash = c + (hash << 6) + (hash << 16) - hash;
}
#endif
return hash;
}
CO_Struct(KVPair) {
char * key;
Type value;
};
static KVPair * KVPairNew(const char * key, Type value, Type (*retainer)(Type t)) {
if (key == NULL || key[0] == 0 || value == NULL) {
return NULL;
}
KVPair * e = CO_New(KVPair, 1);
if (e) {
e->key = strdup(key);
e->value = retainer ? retainer(value) : value;
}
return e;
}
static void KVPairFree(KVPair * e, void (*releaser)(Type t)) {
if (e) {
free(e->key);
if (releaser) {
releaser(e->value);
}
CO_Free(e);
}
}
static KVPair * KVPairCopy(KVPair * e, Type (*retainer)(Type t)) {
return KVPairNew(e->key, e->value, retainer);
}
#define INITIAL_SIZE (10)
#define GROWTH_FACTOR (2)
static KVPair * DictionaryGetInternal(Dictionary * d, const char * key);
static Type DictionaryGet(Dictionary * d, const char * key);
static Dictionary * DictionarySet(Dictionary * d, const char * key, Type value);
static Dictionary * DictionaryRemove(Dictionary * d, const char * key);
static Dictionary * DictionaryInsertPair(Dictionary * d, KVPair * e);
static Dictionary * DictionaryAddPair(Dictionary * d, KVPair * e);
static String * DictionaryDescription(Dictionary * d);
static void DictionaryDealloc(Dictionary * d);
static Dictionary * DictionaryAllocInternal(int size);
static Dictionary * DictionaryGrowTable(Dictionary * d);
Dictionary * DictionaryAlloc(void);
static KVPair * DictionaryGetInternal(Dictionary * d, const char * key) {
if (key == NULL || key[0] == 0) {
return NULL;
}
KVPair ** table = (KVPair **)d->data;
return table[hash_function(key) % d->size];
}
static Type DictionaryGet(Dictionary * d, const char * key) {
KVPair * e = DictionaryGetInternal(d, key);
if (e) {
if (!strcmp(e->key, key)) {
return e->value;
}
}
return NULL;
}
static Dictionary * DictionarySet(Dictionary * d, const char * key, Type value) {
if (key == NULL || key[0] == 0) {
return d;
}
if (value == NULL) {
DictionaryRemove(d, key);
} else {
DictionaryAddPair(d, KVPairNew(key, value, d->retainer));
}
return d;
}
static Dictionary * DictionaryRemove(Dictionary * d, const char * key) {
KVPair * e = DictionaryGetInternal(d, key);
if (e) {
KVPairFree(e, d->releaser);
d->n--;
KVPair ** table = (KVPair **)d->data;
table[hash_function(key) % d->size] = NULL;
}
return d;
}
static Dictionary * DictionaryInsertPair(Dictionary * d, KVPair * e) {
if (e) {
KVPair ** table = (KVPair **)d->data;
table[hash_function(e->key) % d->size] = e;
d->n++;
}
return d;
}
static Dictionary * DictionaryAddPair(Dictionary * d, KVPair * e) {
if (e == NULL || e->value == NULL) {
return NULL;
}
KVPair * ep = DictionaryGetInternal(d, e->key);
if (ep) { // Existing value for hash(key)
if (!strcmp(ep->key, e->key)) { // Keys are equal, replace
KVPairFree(ep, d->releaser);
d->n--;
} else { // Keys are different, grow dictionary
DictionaryGrowTable(d);
}
}
DictionaryInsertPair(d, e);
return d;
}
static String * DictionaryDescription(Dictionary * d) {
if (d) {
KVPair ** table = (KVPair **)d->data;
printf("%d pairs {\n", d->n);
for (ssize_t i = 0; i < d->size; i++) {
KVPair * e = table[i];
if (e) {
printf("\t\"%s\" : %s\n", e->key, d->descriptor ? d->descriptor(e->value) : e->value);
}
}
printf("}\n");
}
return NULL;
}
/* dictionary initialization code used in both DictionaryAlloc and grow */
static Dictionary * DictionaryAllocInternal(int size) {
Dictionary * d = CO_New(Dictionary, 1);
if (d) {
d->n = 0;
d->size = size;
d->data = CO_New(KVPair *, d->size);
if (d->data == NULL) {
CO_Free(d);
return NULL;
}
}
return d;
}
static Dictionary * DictionaryGrowTable(Dictionary * d) {
if (d) {
Dictionary * d2 = DictionaryAllocInternal(d->size * GROWTH_FACTOR);
if (d2 != NULL) {
KVPair ** table = (KVPair **)d->data;
for (size_t i = 0; i < d->size; i++) {
KVPair * e = table[i];
if (e) {
DictionaryInsertPair(d2, KVPairCopy(e, d->retainer));
}
}
SWAP(d->data, d2->data);
SWAP(d->size, d2->size);
DictionaryDealloc(d2);
}
}
return d;
}
void DictionaryDealloc(Dictionary * d) {
if (d) {
if (d->data) {
KVPair ** table = (KVPair **)d->data;
for (size_t i = 0; i < d->size; i++) {
KVPairFree(table[i], d->releaser);
}
}
CO_Free(d->data);
CO_Free(d);
}
}
Dictionary * DictionaryAlloc(void) {
Dictionary * d = DictionaryAllocInternal(INITIAL_SIZE);
if (d) {
d->get = DictionaryGet;
d->set = DictionarySet;
d->remove = DictionaryRemove;
d->description = DictionaryDescription;
d->dealloc = DictionaryDealloc;
}
return d;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(){
float valor, desconto;
printf("Valor do produto: ");
scanf("%f",&valor);
desconto=valor - valor*0.12;
printf("Valor com desconto: %.2f",desconto);
return 0;
}
|
C
|
#ifndef COMPARISION_H
#define COMPARISION_H
#endif // COMPARISION_H
#include<stdlib.h>
#include<stdio.h>
/*
* TLS parsing
* author: Samsuddin Sikder
* email: [email protected]
* www.zafaco.de
* site documentation: http://blog.fourthbit.com/2014/12/23/traffic-analysis-of-an-ssl-slash-tls-session
*
*/
// dumps raw memory in hex byte and printable split format
void compare_dump(const unsigned char *data_buffer, const unsigned int length) {
unsigned char byte;
unsigned int i, j, c,s;
int tcp_header_length, total_header_size, pkt_data_len;
int rest = 16; //i need to print last 16-bytes
int print = pkt_data_len-rest ;
//const u_char *pkt_data;
const struct tcp_hdr *tcp_header;
unsigned short tcp_dest_port; // destination TCP port
for(i=0; i < length; i++) {
byte = data_buffer[i];
/*
printf("%02x ", data_buffer[i]); // display byte in hex
printf(" INT:%d ", data_buffer[i]);
if(((i%16)==15) || (i==length-1)) {
for(j=0; j < 15-(i%16); j++)
printf(" ");
/*
/*
* content type: HANDSHAKE 0X16 i=0
* VERSION: TLS 1.0 0x0301 or TLS 1.2 0x0303 i=1,2
* Handshake protocol: CLIENT HELLO 0x01 i.e. i =5
* VERSION: TLS 1.0 0x0301 or TLS 1.2 0x0303 i=9,10
*
*/
if(data_buffer[i]== 0x16 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03) && data_buffer[i+5]==0x01 && data_buffer[i+9]==0x03 && (data_buffer[i+10]==0x01 || data_buffer[i+10]==0x03 )){
printf("\nHandshake Type: CLIENT HELLO (0x%02x)\n", data_buffer[i+5]);
//which TLS version is using
if( data_buffer[i+10]==0x01) printf("VERSION: TLS 1.0 (0x0301) \n", data_buffer[i+10] );
else printf("VERSION: TLS 1.2 (0x0303)\n",data_buffer[i+10] );
printf("length: %4d \n",data_buffer[i+8]);
//to generate random no.
printf("Random(32-bytes): ");
for(c=11;c<43;c++){
printf("%02x",data_buffer[i+c]);
}
printf("\n\n");
//exit(1);
/*
* content type: HANDSHAKE 0X16 i=0
* VERSION: TLS 1.0 0x0301 or TLS 1.2 0x0303 i=1,2
* Handshake protocol: SERVER HELLO 0x02 i.e. i =5
* VERSION: TLS 1.0 0x0301 or TLS 1.2 0x0303 i=9,10
*
*/
if(data_buffer[j]== 0x16 && data_buffer[j+1]== 0x03 && (data_buffer[j+2]==0x01 ||data_buffer[j+2]==0x03) && data_buffer[j+5]==0x02 && data_buffer[j+9]==0x03 && (data_buffer[j+10]==0x01 || data_buffer[j+10]==0x03 )){
printf("\nHandshake Type: SERVER HELLO (0x%02x)\n", data_buffer[i+5]);
//which TLS version is using
if( data_buffer[j+10]==0x01) printf("VERSION: TLS 1.0 (0x0301) \n", data_buffer[j+10] );
else printf("VERSION: TLS 1.2 (0x0300)\n",data_buffer[j+10] );
printf("length: %4d \n",data_buffer[j+8]);
//to generate random no.
printf("Random(32-bytes): ");
for(c=11;c<43;c++){
printf("%02x",data_buffer[j+c]);
}
printf("\n");
exit(1);
/*
* content type: Change Cipher Spec 0X16 i=0
* VERSION: TLS 1.0 0x0301 or TLS 1.2 0x0303 i=1,2
* length: i= 3-4
* change cipher spec message i = 01
*
*/
if(data_buffer[i]== 0x14 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03) && data_buffer[i+3]==0x00 && data_buffer[i+4]==0x01 && data_buffer[i+5]==0x01 ){
printf("\n[CLIENT SIDE]\n");
if(data_buffer[i==0x14])printf("Change Cipher Spec: (0x%02x)\n", data_buffer[i]);
//which TLS version is using
if( data_buffer[i+2]==0x01) printf("VERSION: TLS 1.0 (0x0301) \n", data_buffer[i+2] );
else printf("VERSION: TLS 1.2 (0x0303)\n",data_buffer[i+2] );
printf("length: %d \n",data_buffer[i+4]);
//if(data_buffer[i]== 0x16 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03) && data_buffer[i+3]==0x00 ){
if (data_buffer[i]==0x16 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03) && data_buffer[i+3]== 0x00 && (data_buffer[i+4]== 0x30|| data_buffer[i+4]== 0x28)){
printf("\n[CLIENT SIDE]\n");
printf("Handshake Type: Encrypted Handshake Message (0x%02x)\n", data_buffer[i]);
if( data_buffer[i+2]==0x01) printf("VERSION: TLS 1.0 (0x0301) \n", data_buffer[i+2] );
else printf("VERSION: TLS 1.2 (0x0303)\n",data_buffer[i+2] );
printf("length: %d \n",data_buffer[i+4]);
printf("Encrypted Handshake Message: ");
for(print;print<pkt_data_len; print++){
printf("%02x ",data_buffer[i+print]);
}
printf("\n");
/* SERVER SIDE Change Cipher Spec & Encrypted Handshake Message
* content type: Change Cipher Spec 0X14 i=0
* VERSION: TLS 1.0 0x0301 or TLS 1.2 0x0303 i=1,2
* length: i= 3-4
* change cipher spec message i = 5
*
*/
if(data_buffer[i]== 0x14 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03 ) && data_buffer[i+3]==0x00 && data_buffer[i+4]==0x01 && data_buffer[i+5]==0x01 && data_buffer[i+6]==0x16 && data_buffer[i+7]==0x03 && data_buffer[i+8]==0x01 && data_buffer[i+9]==0x00){
printf("\n[SERVER SIDE]\n");
printf("Handshake Type: Encrypted Handshake Message (0x%02x)\n", data_buffer[i+6]);
if( data_buffer[i+2]==0x01) printf("VERSION: TLS 1.0 (0x0301) \n", data_buffer[i+2] );
else printf("VERSION: TLS 1.2 (0x0303)\n",data_buffer[i+2] );
printf("length: %d \n",data_buffer[i+10]);
printf("Encrypted Handshake Message: ");
for(print;print<=pkt_data_len; print++){
printf("%02x ",data_buffer[i+print]);
}
printf("\n");
/* content type:Application data 0x17 i=0
* VERSION: TLS 1.0 0x0301 or TLS 1.2 0x0303 i=1,2
* length: i= 3-4
* i=from 5... start application data
*
*/
if(data_buffer[i]==23 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03 )){
//if(data_buffer[i]== 23 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03 )) {
printf("\nContent Type: Application Data (0x%02x)\n", data_buffer[i]);
if( data_buffer[i+2]==0x01) printf("VERSION: TLS 1.0 (0x0301) \n", data_buffer[i+2] );
else printf("VERSION: TLS 1.2 (0x0303)\n",data_buffer[i+2] );
printf("length: %d%d \n",data_buffer[i+3],data_buffer[i+4]);
printf("Application Data: ");
for(int data =5;data<=pkt_data_len; data++){
printf("%02x ",data_buffer[i+data]);
}
printf("\n");
}
}
}
}
exit(1);
}
}
// Magenta cloud download
/* if( tcp_dest_port== 443 && data_buffer[i]== 0x14 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03) && data_buffer[i+3]==0x00 && data_buffer[i+4]==0x01 && data_buffer[i+5]==0x01 ){
//if(pkt_data_len ==data_buffer== 6){
printf("\n[CLIENT SIDE]\n");
if(data_buffer[i==0x14])printf("Change Cipher Spec: (0x%02x)\n", data_buffer[i]);
//which TLS version is using
if( data_buffer[i+2]==0x01) printf("VERSION: TLS 1.0 (0x0301) \n", data_buffer[i+2] );
else printf("VERSION: TLS 1.2 (0x0303)\n",data_buffer[i+2] );
}
*/
/* if( data_buffer[i]== 0x16 && data_buffer[i+1]== 0x03 && (data_buffer[i+2]==0x01 ||data_buffer[i+2]==0x03) && data_buffer[i+3]==0x00 ){
printf("\n[CLIENT SIDE]\n");
printf("Encrypted Handshake Message: ");
for(print;print<pkt_data_len; print++){
printf("%02x ",data_buffer[i+print]);
}
printf("\n\n");
exit(1);
}
*/
// if(pkt_data==0) exit(1);
}//END of FOR LOOP
}
|
C
|
#include <time.h>
#define CONSUMER_A_SLEEP_TIME 2000000
#define CONSUMER_B_SLEEP_TIME 3000000
#define PRODUCER_A_SLEEP_TIME 8000000
#define PRODUCER_B_SLEEP_TIME 7800000
#define producerA 10
#define producerB 20
#define consumerA 30
#define consumerB 40
void producer(sharedData* data, int type);
void consumer(sharedData* data, int type);
int produceItem();
void consumer(sharedData* data, int type)
{
int semSetId = data->semaphoreSetId;
printf("New consumer added\n");
while(!data->shouldExit) {
printf("Przyszedl konsument %s\n", type == consumerA ? "A" : "B");
down(semSetId, SIZE_REQUIREMENT_FOR_READING);
down(semSetId, FULL);
down(semSetId, MUTEX);
pop(&data->buffer);
if(getElementsNo(&data->buffer) > 3)
up(semSetId, SIZE_REQUIREMENT_FOR_READING); // set semaphore to 1, because we still have enough elements
up(semSetId, EMPTY);
if(getElementsSum(&data->buffer) <= 20)
downNoWait(semSetId, SUM_REQUIREMENT_FOR_PRODUCER_A_WRITING); // set semaphore to 0, because condition is no longer met
printf("Consumer%s removed elem\n", type == consumerA ? "A" : "B");
printBuffer(&data->buffer);
up(semSetId, MUTEX);
usleep(type == consumerA ? CONSUMER_A_SLEEP_TIME : CONSUMER_B_SLEEP_TIME);
}
}
void producer(sharedData* data, int type)
{
int semSetId = data->semaphoreSetId;
printf("New producer added\n");
while (!data->shouldExit) {
int item = produceItem();
printf("Przyszedl producent %s z %d\n", type == producerA ? "A" : "B", item);
if(type == producerA)
down(semSetId, SUM_REQUIREMENT_FOR_PRODUCER_A_WRITING);
down(semSetId, EMPTY);
down(semSetId, MUTEX);
put(&data->buffer, item);
up(semSetId, FULL);
if(getElementsNo(&data->buffer) == 4) // ALTERNATIVE: >=4 and not increase but explicitly set to 1
up(semSetId, SIZE_REQUIREMENT_FOR_READING); // set semaphore to 1, after our put the size condition is met
// ALTERNATIVE: if sum condition is met, explicitly set to 1
downNoWait(semSetId, SUM_REQUIREMENT_FOR_PRODUCER_A_WRITING); // set semaphore to 0
if(getElementsSum(&data->buffer) > 20)
up(semSetId, SUM_REQUIREMENT_FOR_PRODUCER_A_WRITING); // if the sum condition is met, set semaphore to 1
printf("Producer%s added elem\n", type == producerA ? "A" : "B");
printBuffer(&data->buffer);
up(semSetId, MUTEX);
usleep(type == producerA ? PRODUCER_A_SLEEP_TIME : PRODUCER_B_SLEEP_TIME);
}
}
int produceItem()
{
return( rand() % 10 + 3);
}
|
C
|
strchr(查找字符串中第一个出现的指定字符)
相关函数 index,memchr,rinex,strbrk,strsep,strspn,strstr,strtok strpbrk
#include<string.h>
char * strchr (const char *s,int c);
----strchr()用来找出参数s字符串中第一个出现的参数c地址,然后将该字符出现的地址返回。
返回值: 如果找到指定的字符则返回该字符所在地址,否则返回0。
#include<string.h>
int main()
{
char *s="0123456789012345678901234567890";
char *p;
p=strchr(s,'5');
printf("%s\n",p);
return 0;
}
hy@hy-K53BE:~/桌面$ ./ff
56789012345678901234567890
|
C
|
///Name:Priyanka P.Khandagale
///Write a program which accept number from user and return summation of all its non factors.
///Input : 12
///Output : 50
///Input : 10
///Output : 37
////////////////////////////////////////////////////////////////////
#include<stdio.h>
int NonFactorsummation(int iNo)
{
int i,sum=0;
if(iNo<0)
{
return;
}
for(i=iNo;i>=i;i--)
{
if(iNo%i!=0)
{
sum=sum+i;
}
}
return sum;
}
int main()
{
int number,ires;
printf("enter number=");
scanf("%d",&number);
ires= NonFactorsummation(number);
printf("summation=%d",ires);
return 0;
}
|
C
|
#include "out_funcs.h"
static void ft_offset_int(t_list **integer, t_list **decimal)
{
t_list *decimal_end;
uint8_t symbs_amount;
uint8_t first_int_symb;
if (count_symbs(ft_lstlast(*integer)->value, 10) == 1)
return ;
decimal_end = ft_lstlast(*decimal);
symbs_amount = count_symbs(decimal_end->value, 10);
ft_bignummultiply(decimal, 10, 10 - symbs_amount);
free(decimal_end->next);
(*integer)->prev = decimal_end;
decimal_end->next = *integer;
decimal_end = ft_lstlast(decimal_end);
symbs_amount = count_symbs(decimal_end->value, 10) - 1;
*integer = NULL;
ft_lstadd_front(integer,
ft_lstnew(decimal_end->value / ft_power(10, symbs_amount)));
first_int_symb = decimal_end->value
/ ft_power(10, count_symbs(decimal_end->value, 10) - 1);
decimal_end->value -= ft_power(10, count_symbs(decimal_end->value, 10) - 1)
* (first_int_symb - 1);
}
static void ft_exclude_zeros(t_list *integer, t_list *decimal)
{
uint16_t cur_zeros;
uint8_t first_int_symb;
decimal = ft_lstlast(decimal);
cur_zeros = count_symbs(decimal->value, 10) - 1;
while (decimal->value % ft_power(10, cur_zeros) == 0)
{
if (decimal->prev)
{
decimal = decimal->prev;
free(decimal->next);
decimal->next = NULL;
}
else
break ;
cur_zeros = 9;
}
if (cur_zeros < count_symbs(decimal->value, 10) && cur_zeros--)
decimal->value -= ft_power(10, cur_zeros + 1);
first_int_symb = decimal->value
/ ft_power(10, count_symbs(decimal->value, 10) - 1);
decimal->value = decimal->value - ft_power(10,
count_symbs(decimal->value, 10) - 1) * (first_int_symb - 1);
integer->value = first_int_symb;
ft_lstnormalizer(decimal);
}
int16_t ft_change_to_exp(t_list **integer,
t_list **decimal, t_specifier *specifier)
{
uint16_t integer_symbs;
uint16_t decimal_zeros;
integer_symbs = integer_symbs_count(*integer);
decimal_zeros = decimal_zeros_count(*decimal) + 1;
if (integer_symbs == 1
&& (*integer)->value == 0
&& (*decimal)->value)
{
ft_exclude_zeros(*integer, *decimal);
ft_round_decimal(integer, decimal, specifier);
while ((*integer)->value >= 10 && decimal_zeros--)
(*integer)->value /= 10;
return (decimal_zeros * (-1));
}
else
{
ft_offset_int(integer, decimal);
ft_round_decimal(integer, decimal, specifier);
while ((*integer)->value >= 10 && integer_symbs++)
(*integer)->value /= 10;
return (integer_symbs - 1);
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int field[MAX_SIZE][MAX_SIZE];
int N;
int count = 0;
int MazePath(int x, int y, int dist) {
if (x < 0 || y < 0 || x >= N || y >= N || field[x][y] != 0)
return 0;
else if (x == N - 1 && y == N - 1) {
return 1;
}
else {
int ret = 0;
field[x][y] = 2;
ret += MazePath(x - 1, y, dist + 1);
ret += MazePath(x, y + 1, dist + 1);
ret += MazePath(x + 1, y, dist + 1);
ret += MazePath(x, y - 1, dist + 1);
field[x][y] = 0;
return ret;
}
}
int main() {
int result = 0;
while (1) {
/*custom size
scanf("%d", &N);
*/
N = 8;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
field[i][j] = (rand() % 2) ? 0 : 1;
/*custom maze
scanf("%d", &field[i][j]);
*/
}
}
field[0][0] = 0;
field[N - 1][N - 1] = 0;
/*visualizing code
system("cls");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%s", (field[i][j] ? "" : ""));
}
printf("\n");
}
*/
result = MazePath(0, 0, 0);
printf("result : %d\n", result);
/*skip when random generated maze is blocking way
if(result)
*/
getchar();
}
}
|
C
|
/*
date.c -- date utility operations
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <utime.h>
#include <sys/time.h>
#include "constants.h"
char *get_month();
char *get_day();
char *get_year();
char *get_date();
/**************************** DATE MODULES **********************************/
#define NUM_MONTHS 12
static char *date,timestring[9],month[4],day[3],year[3];
static char months[NUM_MONTHS][4]=
{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
static int date_init=0;
/**************************** INIT_DATE() **********************************/
void init_date()
{
long clock;
struct timeval *tp;
struct timezone *tzp;
struct tm *time;
tp = (struct timeval *)malloc(sizeof(struct timeval));
tzp = (struct timezone *)malloc(sizeof(struct timezone));
gettimeofday(tp,tzp);
clock=(long)tp->tv_sec;
time=localtime(&clock);
date=asctime(time);
/* put leading zero on days 1 through 9
*/
if (date[8]==' ')
date[8]='0';
date_init=1;
(void)free(tp);
(void)free(tzp);
}
/**************************** GET_MONTH() **********************************/
char *
get_month()
{
if (!(date_init))
init_date();
(void)strncpy(month,&date[4],3);
return (month);
}
/*****************************************************************************/
int GetMonthNum(char *month)
{
int m;
for (m=0; m<NUM_MONTHS; m++)
if (!(strcmp(month,months[m])))
break;
return m;
}
/**************************** GET_MONTH_NUM() ******************************/
int get_month_num()
{
int m;
char *month;
month=get_month();
for (m=0; m<NUM_MONTHS; m++)
if (!(strcmp(month,months[m])))
break;
return m+1;
}
/**************************** GET_DAY() **********************************/
char *
get_day()
{
if (!(date_init))
init_date();
(void)strncpy(day,&date[8],2);
return (day);
}
/**************************** GET_YEAR() **********************************/
char *
get_year()
{
if (!(date_init))
init_date();
(void)strncpy(year,&date[22],2);
return (year);
}
/**************************** GetTime() **********************************/
char *
GetTime()
{
if (!(date_init))
init_date();
(void)strncpy(timestring,&date[11],8);
return (timestring);
}
/**************************** GET_DATE() **********************************/
char *
get_date()
/* since this returns the current time, always call init_date() first to
get current time
*/
{
init_date();
return (date);
}
/************************* GetYYMMDDfromBase() ****************************/
char *GetYYMMDDfromBase(long basetime)
/*
given a base time, return a string formatted as YYMMDD representing the
year-month-day, with leading zero if needed
*/
{
struct tm *time_info;
static char base_date[16];
time_info=(struct tm *)gmtime(&basetime);
(void)snprintf(base_date,16,"%02d%02d%02d",
time_info->tm_mon+1,time_info->tm_mday,time_info->tm_year);
return base_date;
}
/************************ GET_DATE_FROM_BASE() ******************************/
char *
get_date_from_base(long base)
/*
given a base time since the epoch, initialize a tm struct with
integers representing date and time and return a string with formatted date
*/
{
static char base_date[16];
long basetime;
struct tm *time_info;
basetime=base;
time_info=(struct tm *)gmtime(&basetime);
(void)snprintf(base_date,16,"%s-%02d-%02d",
months[time_info->tm_mon],time_info->tm_mday,time_info->tm_year);
return base_date;
}
/************************ GET_TIME_FROM_BASE() ******************************/
char *
get_time_from_base(long base)
/*
given a base time since the epoch, initialize a tm struct with
integers representing date and time and return a string with formatted time
*/
{
static char time[16];
long basetime;
struct tm *time_info;
basetime=base;
time_info=(struct tm *)gmtime(&basetime);
(void)snprintf(time,16,"%02d:%02d:%02d",
time_info->tm_hour,time_info->tm_min,time_info->tm_sec);
return time;
}
/*******************************************************************/
int GetTimeIntFromHMS(int hr,int min,int sec)
{
return hr*10000+min*100+sec;
}
/*******************************************************************/
int GetTimeIntFromBase(long base)
{
long basetime;
struct tm *time_info;
basetime=base;
time_info=(struct tm *)gmtime(&basetime);
return time_info->tm_hour*10000+time_info->tm_min*100+time_info->tm_sec;
}
static char TZstring[16];
/*******************************************************************/
int GetBaseFromMDYHMS(int month,int day,int year,int hr,int min,int sec)
{
struct tm time_info;
int basetime;
time_info.tm_mon=month;
time_info.tm_mday=day;
time_info.tm_year=year;
time_info.tm_hour=hr;
time_info.tm_min=min;
time_info.tm_sec=sec;
(void)snprintf(TZstring,16,"%s","TZ=GMT");
(void)putenv(TZstring);
basetime=(int)mktime(&time_info);
return basetime;
}
/************************ HMS2SEC() ******************************/
int
hms2sec(int hr,int minut,int sec)
/* convert integer hour,minutes,seconds to total seconds
*/
{
if (hr<0 || minut<0 || sec<0)
return ERROR;
if (hr>23 || minut>59 || sec>59)
return ERROR;
return hr*3600 + minut*60 + sec;
}
void
sec2hms(int total,int *hr,int *minut,int *sec)
/* convert integer total seconds to hour, minutes, and seconds
*/
{
if (total<0)
/* midnite crossover
*/
total+=24*3600;
*hr=total/3600;
*minut=(int)(((float)total/3600-*hr)*60);
*sec=total%60;
/* midnite crossover
*/
*hr=*hr%24;
}
int
next_end_period(int total,int interval)
/* given a total seconds (from midnite) and desired interval, return the next
total seconds that lands "evenly" at the end of a period as prescribed
by interval.
*/
{
if (total<0 || interval <=0)
return ERROR;
return (total+(interval-(total%interval)));
}
int last_start_period(int total,int rate,int interval)
/* given a total seconds (from midnite), an update rate, and interval, return
previous total seconds that lands "evenly" at the start of a period as
prescribed by rate and interval.
*/
{
if (total<0 || interval <=0 || rate <=0)
return ERROR;
if (!(total%interval))
return total-(rate*interval)+1;
else {
int temp;
temp=total-interval*rate;
if (temp < 0)
/* midnite crossover
*/
temp+=24*3600;
return next_end_period(temp,interval)+1;
}
}
/***
main(int argc, char **argv)
{
int basetime;
***/
/*** uncomment this, make date.o, then use gcc date.o -o gethhmmss to create
that binary
***/
/***
basetime=atoi(argv[1]);
printf("%s",get_time_from_base(basetime));
}
***/
/**
while (1) {
printf("enter basetime: ");
scanf("%d",&basetime);
printf("%s (%s)",
GetYYMMDDfromBase((long)basetime),get_date_from_base((long)basetime));
}
***/
/***
uncomment this part, make (date.o), then use
gcc date.o -o getmmyydd
...to create getmmyydd binary
basetime=atoi(argv[1]);
printf("%s",GetYYMMDDfromBase((long)basetime));
}
***/
/***
uncomment this part, make (date.o), then use
gcc date.c -o getMMM-dd-yy
...to create getMMM-dd-yy binary
***/
/***
basetime=atoi(argv[1]);
printf("%s",get_date_from_base((long)basetime));
}
***/
|
C
|
#include <stdio.h>
//int main() { printf("\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\v\w\y\z"); }
int main() { printf("\a\bcd\e\fghijklm\nopq\rs\t\vwyz"); }
//int main() { printf("A:\DATA\ZORK1.DAT\n"); }
// No null terminator
//void main1() {
// //char v1[] = {'S','t','r','i','n','g','\0'}; // Correct line
// char v1[] = {'S','t','r','i','n','g','\O'};
//
// printf("%s\n", v1);
//}
//void main2() {
// printf("\c\n");
//}
|
C
|
/* splitline.c - command reading and parsing functions for smsh
*
* char * next_cmd(char *prompt,FILE *fp) - get next command
* char ** splitline(char *str); - parse a string
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "smsh.h"
/*
* purpose: read next command line from fp
*
* returns: dynamically allocated string holding command line
*
* errors: NULL at EOF (not really an error)
* calls fatal from emalloc()
*
* notes: alloctes space in BUFSIZ chunks.
*/
char * next_cmd(char * prompt,FILE *fp) {
char *buf; // the buffer
int bufspace = 0; // total size
int pos = 0; // current position
int c; // input char
printf("%s",prompt); // prompt user
while((c = getc(fp)) != EOF) {
// need space?
if(pos + 1 >= bufspace) { // 1 for \0
if(bufspace == 0) // y: 1st time
buf = emalloc(BUFSIZ);
else // or spand
buf = erealloc(buf,bufspace + BUFSIZ);
bufspace += BUFSIZ; // update size
}
// end of command
if(c == '\n')
break;
// no, add to buffer
buf[pos++] = c;
}
if(c == EOF && pos == 0) // EOF and no input
return NULL; // say so
buf[pos] = '\0';
return buf;
}
/*
* splitline ( parse a line into an array of strings)
*/
#define is_delim(x) ((x) == ' ' || (x) == '\t')
/*
* purpose: spilt a line into asrray of white -space sperated tokens
*
* returns: a NULL -terminated array of pointers to copies fo the
* tokens or NULL if line if no tokens ont the line
*
* actioin: travers the array, loacat strings, make copies
*
* note: strtok() should work, but we want to add quotes later
*/
char ** splitline(char *line) {
char *newstr();
char **args;
int spots = 0; // spots in table
int bufspace = 0; // bytes in table`
int argnum = 0; // slots used
char *cp = line; // pos in string
char *start;
int len;
if(line == NULL) // handle special case
return NULL;
args = emalloc(BUFSIZ); // initialize array
bufspace = BUFSIZ;
spots = BUFSIZ / sizeof(char *);
while(*cp != '\0') {
while(is_delim(*cp)) // skip leading spaces
cp++;
if(*cp == '\0') // quit at end -o string
break;
// make sure the array has room (+1 for NULL)
if(argnum + 1 >= spots) {
args = erealloc(args,bufspace + BUFSIZ);
bufspace += BUFSIZ;
spots += (BUFSIZ / sizeof(char*));
}
// mark start, then find end of word
start = cp;
len = 1;
while(*++cp != '\0' && !(is_delim(*cp)))
++len;
args[argnum++] = newstr(start,len);
}
args[argnum] = NULL;
return args;
}
/*
* purpose: constructor for strings
*
* returns: a string,nenver NULL
*/
char *newstr(char *s,int l) {
char *rv = emalloc(l + 1);
rv[l] = '\0';
strncpy(rv,s,l);
return rv;
}
/*
* purpose: free the list returned by splitline
*
* returns: nothing
*
* action: free all strings in list and then free list
*/
void freelist(char **list) {
char **cp = list;
while(*cp)
free(*cp++);
free(list);
}
void *emalloc(size_t n) {
void *rv;
if((rv = malloc(n)) == NULL)
fatal("out of memory","",1);
return rv;
}
void * erealloc(void *p,size_t n) {
void *rv;
if((rv = realloc(p,n)) == NULL)
fatal("realloc() failed","",1);
return rv;
}
|
C
|
#include<bits/stdc++.h>
using namespace std;
int n,m,cot=0;
void dfs(int x,int y)
{
int i,j;
if(x+1==y)
{
cot++;
return;
}
int mc=0;
for(i=x+1;i<y;i++)
{
dfs(x,i-1);
dfs(i+1,y);
}
return mc;
}
int main()
{
int i,j,k,T,fk;
scanf("%d",&T);
while(T--)
{
cot=0;
fk=-1;
scanf("%d %d",&n,&m);
dfs(0,n+1);
printf("%d\n",cot);
}
}
|
C
|
#include <stdio.h>
int main()
{
int bt[20],wt[20],p[20],tat[20],priority[20];
float avwt=0,avtat=0;
int i,j,n,temp,key;
printf("\nEnter the number of the processes: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the burst time and priority of the process P[%d]: ",i);
scanf("%d",&bt[i]);
scanf("%d",&priority[i]);
p[i]=i;
}
for(i=0;i<n;i++)
{
key=i;
for(j=i+1;j<n;j++)
{
if(priority[j]<priority[key])
{
key=j;
}
}
temp=bt[i];
bt[i]=bt[key];
bt[key]=temp;
temp=priority[i];
priority[i]=priority[key];
priority[key]=temp;
temp=p[i];
p[i]=p[key];
p[key]=temp;
}
wt[0]=0;
tat[0]=bt[0];
avtat=tat[0];
for(i=1;i<n;i++)
{
wt[i]=wt[i-1]+bt[i-1];
tat[i]=tat[i-1]+bt[i];
avwt+=wt[i];
avtat+=tat[i];
}
avwt=avwt/n;
avtat=avtat/n;
printf("\n\nPROCESS\t\twaiting time\tburst time\tTurnaround time\n");
printf("\n");
for(i=0;i<n;i++)
{
printf("P[%d]\t\t%d\t\t%d\t\t%d\n",p[i],wt[i],bt[i],tat[i]);
}
printf("\n\nAverage waiting time: %.2f",avwt);
printf("\n\nAverage Turn around time is: %.2f",avtat);
printf("\n");
return 0;
}
|
C
|
#ifndef DYNET_C_GRAPH_H_
#define DYNET_C_GRAPH_H_
#include <dynet_c/define.h>
#include <dynet_c/tensor.h>
typedef struct dynetExpression dynetExpression_t;
/**
* Opaque type of ComputationGraph.
*/
typedef struct dynetComputationGraph dynetComputationGraph_t;
/**
* Creates a new ComputationGraph object.
* @param newobj Pointer to receive a handler.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetCreateComputationGraph(
dynetComputationGraph_t **newobj);
/**
* Deletes the ComputationGraph object.
* @param cg Pointer of a handler.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetDeleteComputationGraph(
dynetComputationGraph_t *cg);
/**
* Resets the ComputationGraph to a newly created state.
* @param cg Pointer of a handler.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetClearComputationGraph(
dynetComputationGraph_t *cg);
/**
* Sets a checkpoint for the ComputationGraph.
* @param cg Pointer of a handler.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetSetComputationGraphCheckpoint(
dynetComputationGraph_t *cg);
/**
* Reverts the ComputationGraph to the last checkpoint.
* @param cg Pointer of a handler.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetRevertComputationGraph(
dynetComputationGraph_t *cg);
/**
* Runs complete forward pass from first node to given one, ignoring all
* precomputed values.
* @param cg Pointer of a handler.
* @param last Expression up to which the forward pass must be computed.
* @param retval Pointer to receive a calculated value.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetForwardExprOnComputationGraph(
dynetComputationGraph_t *cg, const dynetExpression_t *last,
const dynetTensor_t **retval);
/**
* Runs forward pass from first node to given one.
* @param cg Pointer of a handler.
* @param last Expression up to which the forward pass must be computed.
* @param retval Pointer to receive a calculated value.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetForwardExprIncrementallyOnComputationGraph(
dynetComputationGraph_t *cg, const dynetExpression_t *last,
const dynetTensor_t **retval);
/**
* Get forward value for the given expression.
* @param cg Pointer of a handler.
* @param expr Expression to evaluate.
* @param retval Pointer to receive a calculated value.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetGetExprValueFromComputationGraph(
dynetComputationGraph_t *cg, const dynetExpression_t *expr,
const dynetTensor_t **retval);
/**
* Gets the gradient for the given expression.
* @param cg Pointer of a handler.
* @param expr Expression to evaluate.
* @param retval Pointer to receive a calculated value.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetGetExprGradientFromComputationGraph(
dynetComputationGraph_t *cg, const dynetExpression_t *expr,
const dynetTensor_t **retval);
/**
* Clears caches.
* @param cg Pointer of a handler.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetInvalidateComputationGraph(
dynetComputationGraph_t *cg);
/**
* Computes backward gradients from the front-most evaluated node.
* @param cg Pointer of a handler.
* @param last Expression from which to compute the gradient.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetBackwardExprOnComputationGraph(
dynetComputationGraph_t *cg, const dynetExpression_t *last);
/**
* Visualizes the ComputationGraph.
* @param cg Pointer of a handler.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetPrintComputationGraphViz(
const dynetComputationGraph_t *cg);
/**
* Dump the ComputationGraph to a file.
* @param cg Pointer of a handler.
* @param show_values Show internal values.
* @param show_gradients Show gradient values.
* @param nan_check_only Only check whether each gradient is nan.
* @return Status code.
*/
DYNET_C_API DYNET_C_STATUS dynetDumpComputationGraph(
dynetComputationGraph_t *cg, const char *filename,
DYNET_C_BOOL show_values, DYNET_C_BOOL show_gradients,
DYNET_C_BOOL nan_check_only);
#endif // DYNET_C_GRAPH_H_
|
C
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
char s[80];
int i;
sscanf("I still miss","%4s",s);
printf("%s\n", strerror(errno));
for(i=0;i<80 && s[i]!='\0';i++)
printf("%c\n", s[i]);
return 0;
}
|
C
|
# include <stdio.h>
# include <stdlib.h>
int main (int argc, char **argv) {
if (argc != 3) {
printf("Usage: removevocal <sourcefile> <destfile>");
exit (1);
}
FILE *openFile = NULL;
FILE *newFile = NULL;
if ( NULL == (openFile = fopen(argv[1], "rb"))) {
perror ("Cannot open source file");
exit (1);
}
if ((newFile = fopen (argv[2], "wb")) == NULL) {
perror ("Cannot write/create target file");
exit (1);
}
//Check if file is stereo
int monoOrStereo = 0;
fseek (openFile, 22, SEEK_SET);
fread (&monoOrStereo, 2, 1, openFile);
if (monoOrStereo != 2){
printf("The input file is not stereo.\n");
exit (1);
}
//printf("%d\n", monoOrStereo);
//This section checks the size of each sample
int sampleSize = 0;
fseek (openFile, 34, SEEK_SET);
fread (&sampleSize, 2, 1, openFile);
//printf("%d\n", sampleSize);
//Fiding data block size
int fileSize = 0;
fseek (openFile, 40, SEEK_SET);
fread (&fileSize, 4, 1, openFile);
//printf("%d\n", fileSize);
fseek (openFile, 0, SEEK_SET);
//Put code here to copy the 44 bytes header
short *headerBytes;
headerBytes = malloc (44);
fread (headerBytes, 44, 1, openFile);
fwrite (headerBytes, 44, 1, newFile);
free (headerBytes);
headerBytes = NULL;
//Checking the placment of things
//printf("%ld, %ld\n", ftell(openFile), ftell(newFile));
//Put code here to read L and R channel
/*Each sample is 16 bites == 2bytes
*ie:
*sample 1 channel 0
*sample 1 channel 1*/
short *read0, *read1, *noVocal;
int sampleSize_bytes = sampleSize / 8;
if ((read0 = malloc(sampleSize_bytes)) == NULL){
perror("Can't allocate memmery for read0");
exit (1);
}
if ((read1 = malloc(sampleSize_bytes)) == NULL){
perror("Can't allocate memmery for read1");
exit (1);
}
*read0 = 0;
*read1 = 0;
if ((noVocal = malloc(sampleSize_bytes)) == NULL) {
perror("Can't allocate memmery for noVocal");
exit (1);
}
while ((fread(read0, sampleSize_bytes, 1, openFile)) != 0) {
//while ((ftell(openFile)) != (fileSize+44)) {
//fread(read0, 1, 2, openFile);
fread(read1, sampleSize_bytes, 1, openFile);
// printf("%d\n", *read0);
//printf("%d\n", *read1);
*noVocal = (*read0 - *read1)/2;
//printf("%d\n", *noVocal);
fwrite(noVocal, sampleSize_bytes, 1, newFile);
fwrite(noVocal, sampleSize_bytes, 1, newFile);
//printf("%ld, %ld\n", ftell(openFile), ftell(newFile));
}
fclose (newFile);
fclose (openFile);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int my_strlen(char* str);
int main () {
int len = strlen("hello, world");
printf("Length of \"hello, world\" is %d \n", len);
len = my_strlen("hello, world");
printf("Length of \"hello, world\" is %d \n", len);
}
int my_strlen(char* str) {
char* ptr = str; // aliasing
int len = 0;
while (*ptr != 0) {
len = len + 1;
ptr = ptr + 1; // pointer + integer = pointer arithmetic
}
return len;
}
|
C
|
#include <stdbool.h>
char *ft_strlowcase(char *str)
{
int i;
char tmp;
i = 0;
while (true)
{
tmp = str[i];
if (str[i] == '\0')
{
break ;
}
if (str[i] >= 'A' && str[i] <= 'Z')
{
str[i] = tmp + 32;
}
i++;
}
return (str);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* screenshot.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: maearly <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/30 20:19:49 by maearly #+# #+# */
/* Updated: 2021/04/30 20:19:51 by maearly ### ########.fr */
/* */
/* ************************************************************************** */
#include "cub3d.h"
static int pixel_color(t_win *win, int x, int y)
{
int color;
char *dst;
dst = win->addr + (y * win->line_length + x * (win->bits_per_pixel / 8));
color = *(unsigned int *)dst;
return (color);
}
static void a_write(int fd, int c, int s)
{
write(fd, &c, s);
}
static void bmp_header(int fd, int x, int y, int bpp)
{
write(fd, "BM", 2);
a_write(fd, ((x * y) * 4 + 58), 4);
write(fd, "\0\0\0\0", 4);
a_write(fd, 58, 4);
a_write(fd, 40, 4);
a_write(fd, x, 4);
a_write(fd, y, 4);
a_write(fd, 1, 2);
a_write(fd, bpp, 2);
write(fd, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 28);
}
int screenshot(t_head *head, t_win *win)
{
int x;
int y;
int fd;
int sx;
x = (int)head->screen.x;
y = (int)head->screen.y;
sx = 0;
fd = open("screenshot.bmp", O_CREAT | O_RDWR);
if (fd < 0)
return (ft_exit(head));
bmp_header(fd, x, y, win->bits_per_pixel);
while (y != 0)
{
while (sx != x)
{
a_write(fd, pixel_color(win, sx, y), 4);
++sx;
}
sx = 0;
--y;
}
close(fd);
return (1);
}
void make_screenshot(t_head *head)
{
set_position(head);
mlx_clear_window(head->win.mlx, head->win.win);
head->win.img = mlx_new_image(head->win.mlx, head->screen.x,
head->screen.y);
head->win.addr = mlx_get_data_addr(head->win.img,
&head->win.bits_per_pixel, &head->win.line_length,
&head->win.endian);
draw_map(head);
mlx_put_image_to_window(head->win.mlx, head->win.win, head->win.img, 0, 0);
if (!screenshot(head, &head->win))
ft_error(head, "Error\nScreenshot error!\n");
mlx_destroy_image(head->win.mlx, head->win.img);
ft_exit(head);
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#define BELL '\a'
#define DEALER 0
#define PLAYER 1
#define ACELOW 0
#define ACEHIGH 1
int askedForName = 0 /* False initially */
/* Prototypes */ void dispTitle(void);
void initCardsScreen(int cards[52], int playerPoints[2],
int dealerPoints[2], int total[2],
int * numCards);
int dealCard(int * numCards, int cards[52]);
void dispCard(int cardDrawn, int points[2]);
void totalIt(int points[2], int total[2], int who);
void dealerGetsCard(int *numCards, int cards[52],
int dealerPoints[2]);
void playerGetsCard(int *numCards, int cards[52],
int playerPoints[2]);
char getAns(char mesg[]);
void findWinner(int total[2]);
/* C uses main here */
main()
{
int numCards;
int cards[52], playerPoints[2], dealerPoints[2], total[2];
char ans;
do{ initCardsScreen(cards, playerPoints, dealerPoints, total, &numCards;
dealerGetsCard(&numCards, cards, dealerPoints);
printf("\n");
playerGetsCard(&numCards, cards, playerPoints);
do {
ans = getAns("Hit or Stand (H/S)?");
if (ans == 'H')
{ playerGetsCards(&numCards, cards, playerPoints);
}
|
C
|
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include "../utils.h"
void show_single_char(const char* s) {
for (size_t i = 0; i < strlen(s); i++) {
printf("%2c ", s[i]);
}
printf(" (%ldb)\n", strlen(s));
}
void show_int(int x) {
printf("As Integer:\t");
show_bytes((bp)&x, sizeof(int));
}
void show_float(float x) {
printf("As Float:\t");
show_bytes((bp)&x, sizeof(float));
}
void show_pointer(void* x) {
printf("As Pointer:\t");
show_bytes((bp)&x, sizeof(void*));
}
void show_original(int* pval) {
int val = *pval;
// 这里是按实际值从高位到低位打印
// high bit to low bit (littble endian)
printf("Int ORG: dec:%d hex:0x%x addr:%p\n", val, val, pval);
printf("Int HEX: %4x %4x %4x %4x %4x %4x %4x %4x\n", val >> 28 & 0x0f,
val >> 24 & 0x0f, val >> 20 & 0x0f, val >> 16 & 0x0f, val >> 12 & 0x0f,
val >> 8 & 0x0f, val >> 4 & 0x0f, val & 0x0f);
printf("Int BIN: " BYTE_TO_BIN " " BYTE_TO_BIN " " BYTE_TO_BIN " " BYTE_TO_BIN
"\n",
BIN_FMT(val >> 24), BIN_FMT(val >> 16), BIN_FMT(val >> 8),
BIN_FMT(val));
}
void test_show_bytes(int val) {
int ival = val;
float fval = (float)ival;
int* pval = &ival;
show_original(&val);
show_binary(&val);
show_int(ival);
show_float(fval);
show_pointer(pval);
}
void test_show_bytes2() {
int val = 0x87654321;
bp p = (bp)&val;
show_bytes(p, 1);
show_bytes(p, 2);
show_bytes(p, 3);
show_bytes(p, 4);
const char* s = "123456";
show_single_char(s);
show_bytes((bp)s, strlen(s));
s = "abcdef";
show_single_char(s);
show_bytes((bp)s, strlen(s));
}
int main(int argc, const char* argv[]) {
test_show_bytes(0x123456);
show_endian();
}
|
C
|
// Example of type-unsafe I/O in C
// Produces a compiler warning, but still compiles
#include <stdio.h>
typedef struct {
int age;
char* first_name;
char* last_name;
} person_t;
main() {
person_t p;
p.age = 99;
p.first_name = "Bob";
p.last_name = "Caygeon";
printf("%s\n", p);
printf("%s\n", p.age); // Segmentation fault (why?)
}
|
C
|
/*
** basic_functions.c for basic_functions.c in /home/frostiz/CPE_2016_BSQ
**
** Made by thibaut trouve
** Login <[email protected]>
**
** Started on Wed Dec 14 19:28:35 2016 thibaut trouve
** Last update Wed Dec 14 20:20:04 2016 thibaut trouve
*/
#include "my.h"
void my_putchar(char c)
{
write(1, &c, 1);
}
int my_strlen(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
i++;
return (i);
}
int lign_lenght(char *str)
{
int i;
i = beginning_of_file(str);
while (str[i] != '\0')
{
if (str[i] == '\n')
return (i - beginning_of_file(str));
i++;
}
return (0);
}
int beginning_of_file(char *buffer)
{
int i;
i = 0;
while (buffer[i] != '\0')
{
if (buffer[i] == 'o' || buffer[i] == '.')
return (i);
i++;
}
return (0);
}
int beginning(char **argv)
{
int i;
int fd;
char buffer[100000];
fd = open(argv[1], O_RDONLY);
read(fd, buffer, 100000);
i = 0;
while (buffer[i] != '\0')
{
if (buffer[i] == 'o' || buffer[i] == '.')
return (i);
i++;
}
close(fd);
return (0);
}
|
C
|
/*һ֪ȣдһҵмڵλ*/
/*һʵٶһͬʱ
·̵е㡣Ծԭд*/
typedef struct node
{
int data;
struct node *next;
}*Node_t;
Node_t find_mid_of_list(Node_t head) {
if(head == NULL || head->next == NULL)
return NULL;
Node_t p_fast = head->next;
Node_t p_slow = head->next;
while(p_fast->next != NULL && p_fast != NULL) {
p_slow = p_slow->next;
p_fast = p_fast->next->next;
}
return p_slow;
}
|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: afnd.c
* Author: Sergio Castellano y Francisco Andreu
*
* Created on 29 de septiembre de 2016, 18:20
*/
#include <inttypes.h>
#include "afnd.h"
short num_id = 0;
typedef struct _Transicion {
Estado* origen;
Estado* destino;
Simbolo* simbolo;
} Transicion;
typedef struct _TransicionLambda {
Estado* origen;
Estado* destino;
} TransicionLambda;
typedef struct _AFND {
char nombre[100];
/* ESTADOS */
Estado* estados;
int num_estados;
int num_estados_insertados;
Estado* estado_inicial; /*Apuntara a su respectivo estado*/
Estado** estado_final; /*Apuntara a sus respectivos estados*/
int num_estado_final;
Estado** estado_actual; /*Apuntara a sus respectivos estados*/
int num_estado_actual;
/* ALFABETO Y PALABRA */
Simbolo* alfabeto;
int longitud_alfabeto;
int num_simbolos_insertados;
Simbolo* palabra;
int longitud_palabra;
/* TRANSICIONES */
Transicion* transiciones;
int num_transiciones_insertadas;
/* TRANSICIONES LAMBDA*/
TransicionLambda* transiciones_l;
int num_transiciones_l_insertadas;
/* ID DEL AUTOMATA*/
int id;
} AFND;
AFND * AFNDNuevo(char * nombre, int num_estados, int num_simbolos) {
if (!nombre || num_estados <= 0 || num_simbolos <= 0)
return NULL;
/* Reservamos memoria para la estructura y le copiamos el nombre */
AFND* afnd = (AFND*) malloc(sizeof (AFND));
if (strcpy(afnd->nombre, nombre) == NULL)
return NULL;
/* ESTADOS */
/* Al principio no hay estados insertados, actuales, ni finales. Pero reservamos memoria para ellos */
afnd->num_estados = num_estados;
afnd->num_estados_insertados = 0;
afnd->num_estado_final = 0;
afnd->num_estado_actual = 0;
afnd->estados = (Estado*) malloc(sizeof (Estado) * num_estados);
afnd->estado_actual = (Estado**) malloc(sizeof (Estado*) * NUM_ESTADOS_ACTUALES);
afnd->estado_final = (Estado**) malloc(sizeof (Estado*) * NUM_ESTADOS_FINALES);
/* ALFABETO (alfabeto+palabra a procesar) */
/* Al principio no hay simbolos en el alfabeto ni en la palabra a procesar. Pero reservamos memoria para ellos */
afnd->longitud_alfabeto = num_simbolos;
afnd->num_simbolos_insertados = 0;
afnd->alfabeto = (Simbolo*) malloc(sizeof (Simbolo) * num_simbolos);
afnd->longitud_palabra = 0;
afnd->palabra = (Simbolo*) malloc(sizeof (Simbolo) * LONG_PALABRA);
/* TRANSICIONES */
/* Al principio no hay transiciones. Pero reservamos memoria para ellas */
afnd->num_transiciones_insertadas = 0;
afnd->transiciones = (Transicion*) malloc(sizeof (Transicion) * NUM_TRANSICIONES);
afnd->num_transiciones_l_insertadas = 0;
afnd->transiciones_l = (TransicionLambda*) malloc(sizeof (TransicionLambda) * NUM_TRANSICIONES);
/* ASIGNAMOS EL ID DEL AUTOMATA */
afnd->id = num_id++;
return afnd;
}
void AFNDElimina(AFND * p_afnd) {
if (!p_afnd)
return;
int i = 0;
/* ALFABETO y palabra */
for (i = 0; i < p_afnd->num_simbolos_insertados; i++) {
free(p_afnd->alfabeto[i]);
p_afnd->alfabeto[i] = NULL;
}
for (i = 0; i < p_afnd->longitud_palabra; i++)
free(p_afnd->palabra[i]);
/* ESTADOS */
for (i = 0; i < p_afnd->num_estado_final; i++)
free(p_afnd->estado_final[i]);
free(p_afnd->estado_inicial);
for (i = 0; i < p_afnd->num_estado_actual; i++)
free(p_afnd->estado_actual[i]);
for (i = 0; i < p_afnd->num_estados_insertados; i++)
free(p_afnd->estados[i]);
/* El resto de punteros */
free(p_afnd->transiciones);
free(p_afnd->transiciones_l);
free(p_afnd->palabra);
free(p_afnd->estado_final);
free(p_afnd->estado_actual);
free(p_afnd->estados);
free(p_afnd->alfabeto);
free(p_afnd);
p_afnd = NULL;
}
void AFNDImprimeMatrizL(FILE * fd, AFND* p_afnd) {
int i, j;
fprintf(fd, "\tRL++*={\n\t\t");
/* Imprimimos los indices de las columnas */
for (i = 0; i < p_afnd->num_estados_insertados; i++)
fprintf(fd, "\t[%d]", i);
fprintf(fd, "\n");
/* Y para cada estado, imprimimos su indice, y, un 1 si existe transicion, 0 si no */
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
fprintf(fd, "\t\t[%d]", i);
for (j = 0; j < p_afnd->num_estados_insertados; j++) {
if (AFNDExisteTransicionL(p_afnd, i, j) == 1)
fprintf(fd, "\t1");
else
fprintf(fd, "\t0");
}
fprintf(fd, "\n");
}
fprintf(fd, "\t}\n\n");
}
void AFNDImprime(FILE * fd, AFND* p_afnd) {
if (!fd || !p_afnd)
return;
int i, j, k, flag1, flag2;
fprintf(fd, "%s={\n", p_afnd->nombre);
/* Imprimimos el alfabeto */
fprintf(fd, "\tnum_simbolos = %d \n\n\tA={ ", p_afnd->num_simbolos_insertados);
for (i = 0; i < p_afnd->num_simbolos_insertados; i++) {
fprintf(fd, "%s ", p_afnd->alfabeto[i]);
}
fprintf(fd, "}\n\n");
/* Imprimimos los estados */
fprintf(fd, "\tnum_estados = %d \n\n\tQ={", p_afnd->num_estados_insertados);
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
flag1 = 0;
flag2 = 0;
/* Detectamos si es estado final */
for (j = 0; j < p_afnd->num_estado_final; j++) {
if (p_afnd->estados[i] == *p_afnd->estado_final[j]) {
flag1++;
break;
}
}
/* Detectamos si es estado inicial */
if (p_afnd->estados[i] == *p_afnd->estado_inicial)
flag2++;
/* Imprimimos los estados segun el tipo */
if (flag1 == 1 && flag2 == 1) /*Estado final e inicial*/
fprintf(fd, "->%s* ", p_afnd->estados[i]);
else if (flag1 == 0 && flag2 == 1) /*Estado inicial*/
fprintf(fd, "->%s ", p_afnd->estados[i]);
else if (flag1 == 1 && flag2 == 0) /*Estado final*/
fprintf(fd, "%s* ", p_afnd->estados[i]);
else
fprintf(fd, "%s ", p_afnd->estados[i]);
}
fprintf(fd, "}\n\n");
/* Imprimimos la matriz */
AFNDImprimeMatrizL(fd, p_afnd);
/* Imprimimos las transiciones */
/* Para cada estado y simbolo, escribimos el destino de esa transicion (si la hay) */
fprintf(fd, "\tFuncion de transicion = {\n");
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
for (j = 0; j < p_afnd->num_simbolos_insertados; j++) {
fprintf(fd, "\t\tf(%s,%s)={ ", p_afnd->estados[i], p_afnd->alfabeto[j]);
for (k = 0; k < p_afnd->num_transiciones_insertadas; k++) {
if ((p_afnd->transiciones[k].origen == &p_afnd->estados[i]) && (p_afnd->transiciones[k].simbolo == &p_afnd->alfabeto[j])) {
fprintf(fd, "%s ", *p_afnd->transiciones[k].destino);
}
}
fprintf(fd, "}\n");
}
}
fprintf(fd, "\t}\n}");
}
AFND * AFNDInsertaSimbolo(AFND * p_afnd, char * simbolo) {
if (!p_afnd || !simbolo)
return NULL;
/* Comprobamos el numero de simbolos insertados*/
if (p_afnd->num_estados_insertados == p_afnd->num_estados) {
printf("El numero de simbolos insertados no puede ser mayor que el máximo establecido");
return NULL;
}
/* Reservamos memoria y copiamos el simbolo en el alfabeto. Tambien aumentamos el numero de simbolos insertados */
p_afnd->alfabeto[p_afnd->num_simbolos_insertados] = (Simbolo) malloc(sizeof (char) * (strlen(simbolo) + 1));
strcpy(p_afnd->alfabeto[p_afnd->num_simbolos_insertados], simbolo);
p_afnd->num_simbolos_insertados++;
return p_afnd;
}
AFND * AFNDInsertaEstado(AFND * p_afnd, char * nombre, int tipo) {
if (!p_afnd || !nombre)
return NULL;
/* Reservamos memoria para el "nombre del estado+id" y lo creamos */
char id[MAX_LEN_ESTADO] = "";
sprintf(id, "%d", p_afnd->id);
p_afnd->estados[p_afnd->num_estados_insertados] = (Estado) malloc(sizeof (char)*(strlen(nombre) + strlen(id) + 1 + 1));
sprintf(p_afnd->estados[p_afnd->num_estados_insertados], "%s_%d", nombre, p_afnd->id);
/* Si es de algun tipo en específico, hacemos que un puntero de ese array apunte al estado */
/* Si es de tipo final, hacemos que un puntero del array estado_final apunte a dicho estado. Y asi con todos los tipos */
if (tipo == FINAL) {
p_afnd->estado_final[p_afnd->num_estado_final] = (Estado*) malloc(sizeof (Estado));
*(p_afnd->estado_final[p_afnd->num_estado_final]) = (p_afnd->estados[p_afnd->num_estados_insertados]);
p_afnd->num_estado_final++;
} else if (tipo == INICIAL) {
p_afnd->estado_inicial = (Estado*) malloc(sizeof (Estado));
*(p_afnd->estado_inicial) = (p_afnd->estados[p_afnd->num_estados_insertados]);
}
if (tipo == INICIALFINAL) {
p_afnd->estado_inicial = (Estado*) malloc(sizeof (Estado));
p_afnd->estado_final[p_afnd->num_estado_final] = (Estado*) malloc(sizeof (Estado));
*(p_afnd->estado_inicial) = p_afnd->estados[p_afnd->num_estados_insertados];
*(p_afnd->estado_final[p_afnd->num_estado_final]) = (p_afnd->estados[p_afnd->num_estados_insertados]);
p_afnd->num_estado_final++;
}
/* Finalmente, aumentamos el numero de estados insertados */
p_afnd->num_estados_insertados++;
return p_afnd;
}
AFND * AFNDInsertaTransicion(AFND * p_afnd, char * nombre_estado_i, char * nombre_simbolo_entrada, char * nombre_estado_f) {
if (!p_afnd || !nombre_estado_i || !nombre_simbolo_entrada || !nombre_estado_f)
return NULL;
int i = 0;
char nombre_estado_i_id[MAX_LEN_ESTADO] = "";
char nombre_estado_f_id[MAX_LEN_ESTADO] = "";
sprintf(nombre_estado_i_id, "%s_%d", nombre_estado_i, p_afnd->id);
sprintf(nombre_estado_f_id, "%s_%d", nombre_estado_f, p_afnd->id);
/* Comprobramos que el estado de inicio y final de esa transicion esten en nuestro AFND. Y si es asi, insertamos la transicion */
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
if (strcmp(p_afnd->estados[i], nombre_estado_i_id) == 0)
p_afnd->transiciones[p_afnd->num_transiciones_insertadas].origen = &p_afnd->estados[i];
if (strcmp(p_afnd->estados[i], nombre_estado_f_id) == 0)
p_afnd->transiciones[p_afnd->num_transiciones_insertadas].destino = &p_afnd->estados[i];
}
/* Tambien comprobamos que la letra este en el alfabeto del AFND */
for (i = 0; i < p_afnd->num_simbolos_insertados; i++) {
if (strcmp(p_afnd->alfabeto[i], nombre_simbolo_entrada) == 0) {
p_afnd->transiciones[p_afnd->num_transiciones_insertadas].simbolo = &p_afnd->alfabeto[i];
break;
}
}
/* Si alguna de las 3 condiciones anteriores no se ha cumplido, devolvemos error */
if (!p_afnd->transiciones[p_afnd->num_transiciones_insertadas].origen || !p_afnd->transiciones[p_afnd->num_transiciones_insertadas].destino || !p_afnd->transiciones[p_afnd->num_transiciones_insertadas].simbolo) {
printf("Transicion no insertada correctamente\n");
return NULL;
}
/* E incrementamos el numero de transiciones insertadas en nuestro AFND */
p_afnd->num_transiciones_insertadas++;
return p_afnd;
}
AFND * AFNDInsertaLetra(AFND * p_afnd, char * letra) {
if (!p_afnd || !letra)
return NULL;
int i;
/* Si la letra esta incluida en nuestro alfabeto, reservamos memoria para copiar la letra al final de la palabra */
for (i = 0; i < p_afnd->longitud_alfabeto; i++) {
if (strcmp(p_afnd->alfabeto[i], letra) == 0) {
p_afnd->palabra[p_afnd->longitud_palabra] = (Simbolo) malloc(sizeof (char) * (strlen(letra) + 1));
strcpy(p_afnd->palabra[p_afnd->longitud_palabra], letra);
p_afnd->longitud_palabra++;
break;
}
}
return p_afnd;
}
void AFNDImprimeConjuntoEstadosActual(FILE * fd, AFND * p_afnd) {
if (!fd || !p_afnd)
return;
int i = 0, j, flag1, flag2;
fprintf(fd, "\nACTUALMENTE EN {");
/* Tenemos que comprobar de que tipo son cada uno de los estados en los que estamos */
for (i = 0; i < p_afnd->num_estado_actual; i++) {
flag1 = 0;
flag2 = 0;
/* Detectamos si estamos en un estado final */
for (j = 0; j < p_afnd->num_estado_final; j++) {
if (*p_afnd->estado_actual[i] == *p_afnd->estado_final[j]) {
flag1++;
break;
}
}
/* Detectamos si estamos en el estado inicial */
if (*p_afnd->estado_actual[i] == *p_afnd->estado_inicial)
flag2++;
/* E imprimimos los estados segun el tipo */
if (flag1 == 1 && flag2 == 1) /*Estado final e inicial*/
fprintf(fd, "->%s* ", *p_afnd->estado_actual[i]);
else if (flag1 == 0 && flag2 == 1) /*Estado inicial*/
fprintf(fd, "->%s ", *p_afnd->estado_actual[i]);
else if (flag1 == 1 && flag2 == 0) /*Estado final*/
fprintf(fd, "%s* ", *p_afnd->estado_actual[i]);
else
fprintf(fd, "%s ", *p_afnd->estado_actual[i]);
}
fprintf(fd, "}\n");
return;
}
void AFNDImprimeCadenaActual(FILE *fd, AFND * p_afnd) {
if (!fd || !p_afnd)
return;
int i;
/* Imprimimos cada una de las letras de la palabra */
fprintf(fd, "[(%d)", p_afnd->longitud_palabra);
for (i = 0; i < p_afnd->longitud_palabra; i++)
fprintf(fd, " %c", *p_afnd->palabra[i]);
fprintf(fd, "]\n");
return;
}
AFND * AFNDInicializaEstado(AFND * p_afnd) {
if (!p_afnd)
return NULL;
int i;
/* Asignamos el estado inicial como estado actual al principio del automata */
p_afnd->estado_actual[p_afnd->num_estado_actual] = (Estado*) malloc(sizeof (Estado));
*p_afnd->estado_actual[p_afnd->num_estado_actual] = *(p_afnd->estado_inicial);
p_afnd->num_estado_actual++;
/* Comprobamos los estados a los que puede llegar mediante transiciones landa, y los insertamos al conjuntos de estados actuales */
for (i = 0; i < p_afnd->num_transiciones_l_insertadas; i++) {
if (*p_afnd->transiciones_l[i].origen == *p_afnd->estado_actual[0] && *p_afnd->transiciones_l[i].destino != *p_afnd->estado_actual[0]) {
p_afnd->estado_actual[p_afnd->num_estado_actual] = (Estado*) malloc(sizeof (Estado));
*p_afnd->estado_actual[p_afnd->num_estado_actual] = *p_afnd->transiciones_l[i].destino;
p_afnd->num_estado_actual++;
}
}
return p_afnd;
}
int estaEnEstadosActuales(AFND* p_afnd, Estado estado) {
if (!p_afnd || !estado)
return -1;
int i;
Estado e1;
for (i = 0; i < p_afnd->num_estado_actual; i++) {
e1 = *p_afnd->estado_actual[i];
if (strcmp(e1, estado) == 0)
return 1;
}
return 0;
}
void AFNDTransita(AFND * p_afnd) {
if (!p_afnd)
return;
int i, j, k = 0;
Estado **estados_aux = (Estado**) malloc(sizeof (Estado*)*50);
/* Comprobamos en todos los estados actuales si hay alguna transicion posible desde dicho estado al procesar el siguiente simbolo */
for (i = 0; i < p_afnd->num_transiciones_insertadas; i++) {
for (j = 0; j < p_afnd->num_estado_actual; j++) {
if ((*p_afnd->transiciones[i].origen == *p_afnd->estado_actual[j]) && (strcmp(p_afnd->palabra[0], *p_afnd->transiciones[i].simbolo) == 0)) {
/* Copiamos el estado de destino de la transicion en estados_aux */
estados_aux[k] = (Estado*) malloc(sizeof (Estado));
*estados_aux[k] = *(p_afnd->transiciones[i].destino);
k++;
}
}
}
/* Borramos los estados actuales (de antes de procesar el simbolo) */
for (i = 0; i < p_afnd->num_estado_actual; i++) {
free(p_afnd->estado_actual[i]);
p_afnd->estado_actual[i] = NULL;
}
p_afnd->num_estado_actual = 0;
/* Y copiamos en los estados actuales los estados_aux */
for (i = 0; i < k; i++) {
p_afnd->estado_actual[i] = (Estado*) malloc(sizeof (Estado));
*p_afnd->estado_actual[i] = *estados_aux[i];
p_afnd->num_estado_actual++;
}
/* Finalmente, liberamos los estados_aux */
for (i = 0; i < k; i++)
free(estados_aux[i]);
free(estados_aux);
/* Tambien realizamos las transiciones landa posibles desde los nuevos estados. Comprobamos el estado de origen de todas las transiciones landa insertadas. Y que el destino no sea uno de los estados actuales */
for (i = 0; i < p_afnd->num_transiciones_l_insertadas; i++)
for (j = 0; j < p_afnd->num_estado_actual; j++) {
if ((*p_afnd->transiciones_l[i].origen == *p_afnd->estado_actual[j]) && (*p_afnd->transiciones_l[i].destino != *p_afnd->estado_actual[j])) {
if (estaEnEstadosActuales(p_afnd, *p_afnd->transiciones_l[i].destino) != 1) {
p_afnd->estado_actual[p_afnd->num_estado_actual] = (Estado*) malloc(sizeof (Estado));
*p_afnd->estado_actual[p_afnd->num_estado_actual] = *p_afnd->transiciones_l[i].destino;
p_afnd->num_estado_actual++;
}
}
}
return;
}
void AFNDProcesaEntrada(FILE * fd, AFND * p_afnd) {
if (!fd || !p_afnd)
return;
int i, long_palabra_original;
Simbolo* palabra_aux = p_afnd->palabra; /*Guardamos el puntero para no perder la referencia*/
long_palabra_original = p_afnd->longitud_palabra;
/* Procesamos los simbolos uno por uno (transitando), e imprimimos en cada paso los estados actuales y la cadena restante por procesar
* Recorremos el bucle siempre y cuando el num de estados actuales sea mayor que */
for (i = 0; (i < long_palabra_original) && (p_afnd->num_estado_actual != 0); i++) {
AFNDImprimeConjuntoEstadosActual(fd, p_afnd);
AFNDImprimeCadenaActual(fd, p_afnd);
AFNDTransita(p_afnd);
free(p_afnd->palabra[0]);
p_afnd->palabra++;
p_afnd->longitud_palabra--;
}
/* Imprimimos los estados actuales y la cadena */
AFNDImprimeConjuntoEstadosActual(fd, p_afnd);
AFNDImprimeCadenaActual(fd, p_afnd);
/* Liberamos la palabra restante en caso de que el conjunto de estados actuales sea vacio */
while (p_afnd->longitud_palabra != 0) {
free(p_afnd->palabra[0]);
p_afnd->palabra++;
p_afnd->longitud_palabra--;
}
/* Al acabar de procesar dicha palabra en el automata, liberamos los estados actuales y la palabra procesada */
for (i = 0; i < p_afnd->num_estado_actual; i++) {
free(p_afnd->estado_actual[i]);
p_afnd->estado_actual[i] = NULL;
}
p_afnd->num_estado_actual = 0;
p_afnd->palabra = palabra_aux; /*Realocamos "palabra" a su pos. de memoria original*/
return;
}
AFND * AFNDInsertaLTransicionActualizada(AFND * p_afnd, char * nombre_estado_i, char * nombre_estado_f) {
if (!p_afnd || !nombre_estado_i || !nombre_estado_f)
return NULL;
int i;
/* Comprobamos que dicha transcion no este ya insertada */
for (i = 0; i < p_afnd->num_transiciones_l_insertadas; i++)
if ((*p_afnd->transiciones_l[i].origen == nombre_estado_i) && (*p_afnd->transiciones_l[i].destino == nombre_estado_f))
return p_afnd;
/* Insertamos la transicion */
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
if (strcmp(p_afnd->estados[i], nombre_estado_i) == 0)
p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].origen = &p_afnd->estados[i];
if (strcmp(p_afnd->estados[i], nombre_estado_f) == 0)
p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].destino = &p_afnd->estados[i];
}
/* Si alguna de las 3 condiciones anteriores no se ha cumplido, devolvemos error */
if (!p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].origen || !p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].destino) {
printf("Transicion lambda no insertada correctamente\n");
return NULL;
}
/* E incrementamos el numero de transiciones insertadas en nuestro AFND */
p_afnd->num_transiciones_l_insertadas++;
return p_afnd;
}
AFND * AFNDInsertaLTransicion(AFND * p_afnd, char * nombre_estado_i, char * nombre_estado_f) {
if (!p_afnd || !nombre_estado_i || !nombre_estado_f)
return NULL;
int i;
char nombre_estado_i_id[MAX_LEN_ESTADO] = "";
char nombre_estado_f_id[MAX_LEN_ESTADO] = "";
sprintf(nombre_estado_i_id, "%s_%d", nombre_estado_i, p_afnd->id);
sprintf(nombre_estado_f_id, "%s_%d", nombre_estado_f, p_afnd->id);
/* Comprobamos que dicha transcion no este ya insertada */
for (i = 0; i < p_afnd->num_transiciones_l_insertadas; i++)
if ((*p_afnd->transiciones_l[i].origen == nombre_estado_i_id) && (*p_afnd->transiciones_l[i].destino == nombre_estado_f_id))
return p_afnd;
/* Insertamos la transicion */
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
if (strcmp(p_afnd->estados[i], nombre_estado_i_id) == 0)
p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].origen = &p_afnd->estados[i];
if (strcmp(p_afnd->estados[i], nombre_estado_f_id) == 0)
p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].destino = &p_afnd->estados[i];
}
/* Si alguna de las 3 condiciones anteriores no se ha cumplido, devolvemos error */
if (!p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].origen || !p_afnd->transiciones_l[p_afnd->num_transiciones_l_insertadas].destino) {
printf("Transicion lambda no insertada correctamente\n");
return NULL;
}
/* E incrementamos el numero de transiciones insertadas en nuestro AFND */
p_afnd->num_transiciones_l_insertadas++;
return p_afnd;
}
AFND* AFNDCierreTransitivo(AFND * p_afnd) {
if (!p_afnd)
return NULL;
/* Utilizamos el algoritmo de Dijkstra para comprobar todas las transiciones posibles entre los nodos */
if (!AFNDCierreDijkstra(p_afnd))
return NULL;
return p_afnd;
}
AFND* AFNDCierreReflexivo(AFND * p_afnd) {
if (!p_afnd)
return NULL;
int i;
/* Cada estado tendra una transicion landa hacia si mismo */
for (i = 0; i < p_afnd->num_estados_insertados; i++)
AFNDInsertaLTransicionActualizada(p_afnd, p_afnd->estados[i], p_afnd->estados[i]);
return p_afnd;
}
AFND* AFNDCierraLTransicion(AFND * p_afnd) {
if (!p_afnd)
return NULL;
/* Realizamos el cierre reflexivo de los estados */
if (!AFNDCierreReflexivo(p_afnd))
return NULL;
/* Realizamos el cierre transitivo de los estados */
if (!AFNDCierreTransitivo(p_afnd))
return NULL;
return p_afnd;
}
AFND* AFNDInicializaCadenaActual(AFND * p_afnd) {
/* Nosotros reservamos en AFNDInsertaLetra, y liberamos memoria en AFNDProcesaEntrada */
return p_afnd;
}
AFND* AFNDCierreDijkstra(AFND* p_afnd) {
if (!p_afnd)
return NULL;
int i, j, k;
int matriz_dijkstra[p_afnd->num_estados_insertados][p_afnd->num_estados_insertados][(p_afnd->num_estados_insertados) + 1]; /*N+1 matrices de N*N*/
/* Primero inicializamos todas las matrices a 0 */
for (k = 0; k < p_afnd->num_estados_insertados + 1; k++) {
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
for (j = 0; j < p_afnd->num_estados_insertados; j++) {
matriz_dijkstra[i][j][k] = 0;
}
}
}
/* Ahora ponemos un 1 si existe transicion landa, en la primera de las matrices */
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
for (j = 0; j < p_afnd->num_estados_insertados; j++) {
if (AFNDExisteTransicionL(p_afnd, i, j) == 1)
matriz_dijkstra[i][j][0] = 1;
else
matriz_dijkstra[i][j][0] = 0;
}
}
/* Ahora insertamos en las matrices de dijkstra y en el automata las transiciones transitivas */
for (k = 0; k < p_afnd->num_estados_insertados + 1; k++) {
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
for (j = 0; j < p_afnd->num_estados_insertados; j++) {
/* Tanto si existe transicion directa(i->j), o indirecta (i->k->j), insertamos la nueva transicion */
if ((matriz_dijkstra[i][j][k] == 1) || ((matriz_dijkstra[i][k][k] == 1) && (matriz_dijkstra[k][j][k] == 1))) {
matriz_dijkstra[i][j][k + 1] = 1;
AFNDInsertaLTransicionActualizada(p_afnd, p_afnd->estados[i], p_afnd->estados[j]);
}
}
}
}
return p_afnd;
}
int AFNDExisteTransicionL(AFND * p_afnd, int x, int y) {
int i;
/* Comprobamos si existe transicion landa entre el estado de origen x al destino y. Si existe, devolvemos 1 */
for (i = 0; i < p_afnd->num_transiciones_l_insertadas; i++)
if ((*p_afnd->transiciones_l[i].origen == p_afnd->estados[x]) && (*p_afnd->transiciones_l[i].destino == p_afnd->estados[y]))
return 1;
return 0;
}
int estaEnEstadosFinales(AFND* p_afnd, Estado estado) {
if (!p_afnd || !estado)
return -1;
int i;
Estado e1;
for (i = 0; i < p_afnd->num_estado_final; i++) {
e1 = *p_afnd->estado_final[i];
if (strcmp(e1, estado) == 0)
return 1;
}
return 0;
}
void AFNDADot(AFND * p_afnd) {
if (!p_afnd)
return;
int i;
/* Creamos el archivo */
FILE* pf = fopen("AFNDDot.txt", "w+");
if (!pf)
return;
fprintf(pf, "digraph %s { rankdir=LR;\n", p_afnd->nombre);
fprintf(pf, "\t_invisible [style=\"invis\"];\n");
/* Imprimimos todos los estados excepto los finales */
for (i = 0; i < p_afnd->num_estados_insertados; i++)
if (estaEnEstadosFinales(p_afnd, p_afnd->estados[i]) != 1)
fprintf(pf, "\t%s;\n", p_afnd->estados[i]);
/* Imprimimos ahora los estados finales con el formato pedido*/
for (i = 0; i < p_afnd->num_estado_final; i++)
fprintf(pf, "\t%s [penwidth=\"2\"];\n", *p_afnd->estado_final[i]);
fprintf(pf, "\t_invisible -> %s ;\n", *p_afnd->estado_inicial);
for (i = 0; i < p_afnd->num_transiciones_insertadas; i++)
fprintf(pf, "\t%s -> %s [label=\"%s\"];\n", *p_afnd->transiciones[i].origen, *p_afnd->transiciones[i].destino, *p_afnd->transiciones[i].simbolo);
for (i = 0; i < p_afnd->num_transiciones_l_insertadas; i++)
fprintf(pf, "\t%s -> %s [label=\"λ\"];\n", *p_afnd->transiciones_l[i].origen, *p_afnd->transiciones_l[i].destino);
fprintf(pf, "}");
fclose(pf);
pf = NULL;
return;
}
AFND * AFND1ODeSimbolo(char * simbolo) {
if (!simbolo)
return NULL;
/* Creamos el AFND símbolo */
AFND* p_afnd = AFNDNuevo("AFNDSimbolo", 100, 100);
if (!p_afnd)
return NULL;
/* Insertamos el simbolo en el alfabeto */
if (!AFNDInsertaSimbolo(p_afnd, simbolo))
return NULL;
/* Insertamos los dos estados y la transicion con el simbolo del argumento
* y devolvemos este AFND
*/
AFNDInsertaEstado(p_afnd, "q0", INICIAL);
AFNDInsertaEstado(p_afnd, "q1", FINAL);
AFNDInsertaTransicion(p_afnd, "q0", simbolo, "q1");
AFNDInicializaEstado(p_afnd);
return p_afnd;
}
AFND * AFND1ODeLambda() {
/* Creamos el AFND Lambda */
AFND* p_afnd = AFNDNuevo("AFNDLambda", 2, 1);
if (!p_afnd)
return NULL;
/* Insertamos los dos estados y la transicion lambda y devolvemos este AFND */
AFNDInsertaEstado(p_afnd, "q0", INICIAL);
AFNDInsertaEstado(p_afnd, "q1", FINAL);
AFNDInsertaLTransicion(p_afnd, "q0", "q1");
AFNDInicializaEstado(p_afnd);
return p_afnd;
}
AFND * AFND1ODeVacio() {
/* Creamos el AFND vacio */
AFND* p_afnd = AFNDNuevo("AFNDVacio", 2, 1);
if (!p_afnd)
return NULL;
/* Insertamos los dos estados y devolvemos este AFND */
AFNDInsertaEstado(p_afnd, "q0", INICIAL);
AFNDInsertaEstado(p_afnd, "q1", FINAL);
return p_afnd;
}
AFND * AFNDAAFND1O(AFND * p_afnd) {
if (!p_afnd)
return NULL;
int i;
char inicial[MAX_LEN_ESTADO] = "INICIAL10";
char final[MAX_LEN_ESTADO] = "FINAL10";
Estado* estado;
char nombre[256] = "";
char id[256] = "";
sprintf(nombre, "%s_10", p_afnd->nombre);
AFND* p_afndret = AFNDNuevo(nombre, p_afnd->num_estados + 2, p_afnd->longitud_alfabeto);
sprintf(inicial, "INICIAL10_%d", p_afndret->id);
sprintf(final, "FINAL10_%d", p_afndret->id);
/*Copiamos alfabeto en el AFND de retorno*/
for (i = 0; i < p_afnd->num_simbolos_insertados; i++) {
p_afndret->alfabeto[p_afndret->num_simbolos_insertados] = (Simbolo) malloc(sizeof (char) * (strlen(p_afnd->alfabeto[i]) + 1));
strcpy(p_afndret->alfabeto[p_afndret->num_simbolos_insertados], p_afnd->alfabeto[i]);
p_afndret->num_simbolos_insertados++;
}
/*Copiamos estados en el AFND de retorno*/
sprintf(id, "%d", p_afndret->id);
for (i = 0; i < p_afnd->num_estados_insertados; i++) {
p_afndret->estados[p_afndret->num_estados_insertados] = (Estado) malloc(sizeof (char)*(strlen(p_afnd->estados[i]) + strlen(id) + 1));
sprintf(p_afndret->estados[p_afndret->num_estados_insertados], "%s_%d", p_afnd->estados[i], p_afndret->id);
p_afndret->num_estados_insertados++;
}
/*Copiamos transiciones en el AFND de retorno*/
for (i = 0; i < p_afnd->num_transiciones_insertadas; i++) {
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].origen = getEstado(p_afndret, *p_afnd->transiciones[i].origen, 0);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].simbolo = getSimbolo(p_afndret, *p_afnd->transiciones[i].simbolo);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].destino = getEstado(p_afndret, *p_afnd->transiciones[i].destino, 0);
p_afndret->num_transiciones_insertadas++;
}
/*Copiamos transiciones lambda en el AFND de retorno*/
for (i = 0; i < p_afnd->num_transiciones_l_insertadas; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd->transiciones_l[i].origen, 1);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd->transiciones_l[i].destino, 1);
p_afndret->num_transiciones_l_insertadas++;
}
AFNDInsertaEstado(p_afndret, "INICIAL10", INICIAL);
AFNDInsertaEstado(p_afndret, "FINAL10", FINAL);
for (i = 0; i < p_afnd->num_estado_final; i++)
if ((estado = getEstado(p_afndret, *p_afnd->estado_final[i], 0)) != NULL)
AFNDInsertaLTransicionActualizada(p_afndret, *estado, final);
estado = getEstado(p_afndret, *p_afnd->estado_inicial, 0);
AFNDInsertaLTransicionActualizada(p_afndret, inicial, *estado);
return p_afndret;
}
AFND * AFND1OUne(AFND * p_afnd1O_1, AFND * p_afnd1O_2) {
if (!p_afnd1O_1 || !p_afnd1O_2)
return NULL;
int i;
char nombre[256] = "";
char id[256] = "";
sprintf(nombre, "%sU%s", p_afnd1O_1->nombre, p_afnd1O_2->nombre);
AFND* p_afnd;
p_afnd = p_afnd1O_1;
p_afnd = p_afnd1O_2;
AFND* p_afndret = AFNDNuevo(nombre, p_afnd1O_1->num_estados + p_afnd1O_2->num_estados + 2, p_afnd1O_1->longitud_alfabeto + p_afnd1O_2->longitud_alfabeto);
p_afnd = p_afndret;
/* Copiamos alfabeto de AFND1 y 2 en el AFND union*/
for (i = 0; i < p_afnd1O_1->num_simbolos_insertados; i++) {
p_afndret->alfabeto[p_afndret->num_simbolos_insertados] = (Simbolo) malloc(sizeof (char) * (strlen(p_afnd1O_1->alfabeto[i]) + 1));
strcpy(p_afndret->alfabeto[p_afndret->num_simbolos_insertados], p_afnd1O_1->alfabeto[i]);
p_afndret->num_simbolos_insertados++;
}
/*¿Es necesario eliminar duplicados?*/
for (i = 0; i < p_afnd1O_2->num_simbolos_insertados; i++) {
p_afndret->alfabeto[p_afndret->num_simbolos_insertados] = (Simbolo) malloc(sizeof (char) * (strlen(p_afnd1O_2->alfabeto[i]) + 1));
strcpy(p_afndret->alfabeto[p_afndret->num_simbolos_insertados], p_afnd1O_2->alfabeto[i]);
p_afndret->num_simbolos_insertados++;
}
/* Copiamos Estados de AFND 1 y 2 en AFND Union*/
sprintf(id, "%d", p_afndret->id);
for (i = 0; i < p_afnd1O_1->num_estados_insertados; i++) {
p_afndret->estados[p_afndret->num_estados_insertados] = (Estado) malloc(sizeof (char)*(strlen(p_afnd1O_1->estados[i]) + strlen(id) + 1 + 4)); /*EL 4 es por "_ _A1" o "_A2"*/
sprintf(p_afndret->estados[p_afndret->num_estados_insertados], "%s_%s_A1", p_afnd1O_1->estados[i], id);
p_afndret->num_estados_insertados++;
}
for (i = 0; i < p_afnd1O_2->num_estados_insertados; i++) {
p_afndret->estados[p_afndret->num_estados_insertados] = (Estado) malloc(sizeof (char)*(strlen(p_afnd1O_2->estados[i]) + strlen(id) + 1 + 4)); /*EL 4 es por "_A1" o "_A2"*/
sprintf(p_afndret->estados[p_afndret->num_estados_insertados], "%s_%s_A2", p_afnd1O_2->estados[i], id);
p_afndret->num_estados_insertados++;
}
/* Copiamos Transiciones y Transiciones Lambda de AFND1 y AFND2 en AFND Union*/
for (i = 0; i < p_afnd1O_1->num_transiciones_insertadas; i++) {
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->transiciones[i].origen, 1);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].simbolo = getSimbolo(p_afndret, *p_afnd1O_1->transiciones[i].simbolo);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->transiciones[i].destino, 1);
p_afndret->num_transiciones_insertadas++;
}
for (i = 0; i < p_afnd1O_2->num_transiciones_insertadas; i++) {
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].origen = getEstado(p_afndret, *p_afnd1O_2->transiciones[i].origen, 2);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].simbolo = getSimbolo(p_afndret, *p_afnd1O_2->transiciones[i].simbolo);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].destino = getEstado(p_afndret, *p_afnd1O_2->transiciones[i].destino, 2);
p_afndret->num_transiciones_insertadas++;
}
/* Ahora transiciones Lambda */
for (i = 0; i < p_afnd1O_1->num_transiciones_l_insertadas; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->transiciones_l[i].origen, 1);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->transiciones_l[i].destino, 1);
p_afndret->num_transiciones_l_insertadas++;
}
for (i = 0; i < p_afnd1O_2->num_transiciones_l_insertadas; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_2->transiciones_l[i].origen, 2);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_2->transiciones_l[i].destino, 2);
p_afndret->num_transiciones_l_insertadas++;
}
AFNDInsertaEstado(p_afndret, "INICIAL10UNION", INICIAL);
AFNDInsertaEstado(p_afndret, "FINAL10UNION", FINAL);
/* Transicion del nuevo estado inicial a los iniciales de los automatas del arg. */
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = p_afndret->estado_inicial;
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->estado_inicial, 1);
p_afndret->num_transiciones_l_insertadas++;
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = p_afndret->estado_inicial;
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_2->estado_inicial, 2);
p_afndret->num_transiciones_l_insertadas++;
/* Lo mismo para transiciones_l_iniciales */
/* Transicion de los estados finales(1 por automata al estar ya formalizados) al estado final del nuevo automata */
for (i = 0; i < p_afnd1O_1->num_estado_final; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->estado_final[i], 1);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = p_afndret->estado_final[0];
p_afndret->num_transiciones_l_insertadas++;
}
for (i = 0; i < p_afnd1O_2->num_estado_final; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_2->estado_final[i], 2);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = p_afndret->estado_final[0];
p_afndret->num_transiciones_l_insertadas++;
}
/* Hacemos el cierre transitivo y reflexivo */
p_afndret = AFNDCierraLTransicion(p_afndret);
return p_afndret;
}
AFND * AFND1OConcatena(AFND * p_afnd1O_1, AFND * p_afnd1O_2) {
if (!p_afnd1O_1 || !p_afnd1O_2)
return NULL;
int i, j, flag = 0;
/* Reservamos memoria para el "nombre del estado+id" y lo creamos */
char nombre[256] = "";
char id[256] = "";
sprintf(nombre, "%sU%s", p_afnd1O_1->nombre, p_afnd1O_2->nombre);
AFND* p_afndret = AFNDNuevo(nombre, p_afnd1O_1->num_estados + p_afnd1O_2->num_estados + 2, p_afnd1O_1->longitud_alfabeto + p_afnd1O_2->longitud_alfabeto);
/* Copiamos alfabeto de AFND1 y 2 en el AFND union*/
for (i = 0; i < p_afnd1O_1->num_simbolos_insertados; i++) {
p_afndret->alfabeto[p_afndret->num_simbolos_insertados] = (Simbolo) malloc(sizeof (char) * (strlen(p_afnd1O_1->alfabeto[i]) + 1));
strcpy(p_afndret->alfabeto[p_afndret->num_simbolos_insertados], p_afnd1O_1->alfabeto[i]);
p_afndret->num_simbolos_insertados++;
}
/*¿Es necesario eliminar duplicados?*/
for (i = 0; i < p_afnd1O_2->num_simbolos_insertados; i++) {
flag = 0;
for (j= 0; j < p_afndret->num_simbolos_insertados; j++){
if ( strcmp(p_afndret->alfabeto[j], p_afnd1O_2->alfabeto[i]) == 0)
flag = 1;
}
if (flag == 0){
p_afndret->alfabeto[p_afndret->num_simbolos_insertados] = (Simbolo) malloc(sizeof (char) * (strlen(p_afnd1O_2->alfabeto[i]) + 1));
strcpy(p_afndret->alfabeto[p_afndret->num_simbolos_insertados], p_afnd1O_2->alfabeto[i]);
p_afndret->num_simbolos_insertados++;
}
}
/* Copiamos Estados de AFND 1 y 2 en AFND Union*/
sprintf(id, "%d", p_afndret->id);
for (i = 0; i < p_afnd1O_1->num_estados_insertados; i++) {
p_afndret->estados[p_afndret->num_estados_insertados] = (Estado) malloc(sizeof (char)*(strlen(p_afnd1O_1->estados[i]) + strlen(id) + 1 + 4)); /*EL 4 es por "_A1" o "_A2"*/
sprintf(p_afndret->estados[p_afndret->num_estados_insertados], "%s_%s_A1", p_afnd1O_1->estados[i], id);
p_afndret->num_estados_insertados++;
}
for (i = 0; i < p_afnd1O_2->num_estados_insertados; i++) {
p_afndret->estados[p_afndret->num_estados_insertados] = (Estado) malloc(sizeof (char)*(strlen(p_afnd1O_2->estados[i]) + strlen(id) + 1 + 4)); /*EL 4 es por "_A1" o "_A2"*/
sprintf(p_afndret->estados[p_afndret->num_estados_insertados], "%s_%s_A2", p_afnd1O_2->estados[i], id);
p_afndret->num_estados_insertados++;
}
/* Copiamos Transiciones y Transiciones Lambda de AFND1 y AFND2 en AFND Union*/
for (i = 0; i < p_afnd1O_1->num_transiciones_insertadas; i++) {
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->transiciones[i].origen, 1);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].simbolo = getSimbolo(p_afndret, *p_afnd1O_1->transiciones[i].simbolo);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->transiciones[i].destino, 1);
p_afndret->num_transiciones_insertadas++;
}
for (i = 0; i < p_afnd1O_2->num_transiciones_insertadas; i++) {
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].origen = getEstado(p_afndret, *p_afnd1O_2->transiciones[i].origen, 2);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].simbolo = getSimbolo(p_afndret, *p_afnd1O_2->transiciones[i].simbolo);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].destino = getEstado(p_afndret, *p_afnd1O_2->transiciones[i].destino, 2);
p_afndret->num_transiciones_insertadas++;
}
/* TRANSICIONES LAMBDA DE LOS DOS AUTOMATAS */
for (i = 0; i < p_afnd1O_1->num_transiciones_l_insertadas; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->transiciones_l[i].origen, 1);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->transiciones_l[i].destino, 1);
p_afndret->num_transiciones_l_insertadas++;
}
for (i = 0; i < p_afnd1O_2->num_transiciones_l_insertadas; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_2->transiciones_l[i].origen, 2);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_2->transiciones_l[i].destino, 2);
p_afndret->num_transiciones_l_insertadas++;
}
AFNDInsertaEstado(p_afndret, "INICIAL1CONCATENA", INICIAL);
AFNDInsertaEstado(p_afndret, "FINAL10CONCATENA", FINAL);
/* Transicion del nuevo estado inicial al estado inicial del primer automata(En transiciones Lambda y transiciones Lambda iniciales) */
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = p_afndret->estado_inicial;
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->estado_inicial, 1);
p_afndret->num_transiciones_l_insertadas++;
/* Transicion del estado final del primer automata al estado inicial del segundo (En transiciones Lambda y transiciones Lambda iniciales)*/
for (i = 0; i < p_afnd1O_1->num_estado_final; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->estado_final[i], 1);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_2->estado_inicial, 2);
p_afndret->num_transiciones_l_insertadas++;
}
/* Transiciones de los estados finales del segundo al estado final mediante lambdas (En transiciones Lambda y transiciones Lambda iniciales)*/
for (i = 0; i < p_afnd1O_2->num_estado_final; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_2->estado_final[i], 2);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = p_afndret->estado_final[0];
p_afndret->num_transiciones_l_insertadas++;
}
/* Hacemos el cierre transitivo y reflexivo */
p_afndret = AFNDCierraLTransicion(p_afndret);
return p_afndret;
}
AFND * AFND1OEstrella(AFND * p_afnd1O_1) {
if (!p_afnd1O_1)
return NULL;
int i;
/* Reservamos memoria para el "nombre del estado+id" y lo creamos */
char nombre[256] = "";
char id[256] = "";
sprintf(nombre, "ESTRELLA_%s", p_afnd1O_1->nombre);
AFND* p_afndret = AFNDNuevo(nombre, p_afnd1O_1->num_estados + 2, p_afnd1O_1->longitud_alfabeto);
/* Copiamos alfabeto de AFND1 y 2 en el AFND union*/
for (i = 0; i < p_afnd1O_1->num_simbolos_insertados; i++) {
p_afndret->alfabeto[p_afndret->num_simbolos_insertados] = (Simbolo) malloc(sizeof (char) * (strlen(p_afnd1O_1->alfabeto[i]) + 1));
strcpy(p_afndret->alfabeto[p_afndret->num_simbolos_insertados], p_afnd1O_1->alfabeto[i]);
p_afndret->num_simbolos_insertados++;
}
/* Copiamos Estados de AFND 1 y 2 en AFND Union*/
sprintf(id, "%d", p_afndret->id);
for (i = 0; i < p_afnd1O_1->num_estados_insertados; i++) {
p_afndret->estados[p_afndret->num_estados_insertados] = (Estado) malloc(sizeof (char)*(strlen(p_afnd1O_1->estados[i]) + strlen(id) + 1 + 4)); /*EL 3 es por "_A1" o "_A2"*/
sprintf(p_afndret->estados[p_afndret->num_estados_insertados], "%s_%s_A1", p_afnd1O_1->estados[i], id);
p_afndret->num_estados_insertados++;
}
/* Copiamos Transiciones y Transiciones Lambda de AFND1 y AFND2 en AFND Union*/
for (i = 0; i < p_afnd1O_1->num_transiciones_insertadas; i++) {
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->transiciones[i].origen, 1);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].simbolo = getSimbolo(p_afndret, *p_afnd1O_1->transiciones[i].simbolo);
p_afndret->transiciones[p_afndret->num_transiciones_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->transiciones[i].destino, 1);
p_afndret->num_transiciones_insertadas++;
}
for (i = 0; i < p_afnd1O_1->num_transiciones_l_insertadas; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->transiciones_l[i].origen, 1);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->transiciones_l[i].destino, 1);
p_afndret->num_transiciones_l_insertadas++;
}
AFNDInsertaEstado(p_afndret, "INICIAL10ESTRELLA", INICIAL);
AFNDInsertaEstado(p_afndret, "FINAL10ESTRELLA", FINAL);
/* Transicion del nuevo estado inicial al estado inicial del primer automata. */
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = p_afndret->estado_inicial;
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = getEstado(p_afndret, *p_afnd1O_1->estado_inicial, 1);
p_afndret->num_transiciones_l_insertadas++;
/* Transicion del estado final del primer automata al estado inicial del segundo */
for (i = 0; i < p_afnd1O_1->num_estado_final; i++) {
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = getEstado(p_afndret, *p_afnd1O_1->estado_final[i], 1);
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = p_afndret->estado_final[0];
p_afndret->num_transiciones_l_insertadas++;
}
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = p_afndret->estado_inicial;
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = p_afndret->estado_final[0];
p_afndret->num_transiciones_l_insertadas++;
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].origen = p_afndret->estado_final[0];
p_afndret->transiciones_l[p_afndret->num_transiciones_l_insertadas].destino = p_afndret->estado_inicial;
p_afndret->num_transiciones_l_insertadas++;
/* Hacemos el cierre transitivo y reflexivo */
p_afndret = AFNDCierraLTransicion(p_afndret);
return p_afndret;
}
Simbolo* getSimbolo(AFND * p_afnd, char* nombreSimbolo) {
if (!p_afnd || !nombreSimbolo)
return NULL;
int i;
for (i = 0; i < p_afnd->num_simbolos_insertados; i++)
if (strcmp(nombreSimbolo, p_afnd->alfabeto[i]) == 0)
return &p_afnd->alfabeto[i];
return NULL;
}
Estado* getEstado(AFND * p_afnd, char* nombreEstado, int numautomata) {
if (!p_afnd || !nombreEstado)
return NULL;
int i;
char nombre[256] = "";
if (numautomata == 1)
sprintf(nombre, "%s_%d_A1", nombreEstado, p_afnd->id);
else if (numautomata == 2)
sprintf(nombre, "%s_%d_A2", nombreEstado, p_afnd->id);
else
sprintf(nombre, "%s_%d", nombreEstado, p_afnd->id);
for (i = 0; i < p_afnd->num_estados_insertados; i++)
if (strcmp(nombre, p_afnd->estados[i]) == 0)
return &p_afnd->estados[i];
return NULL;
}
|
C
|
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
typedef struct {
double phase;
int t;
} state_t;
void msg(void *instance, int sig) {
}
int run(void *instance, double **param, int ix) {
double *out = param[0] + ix;
double amp = *(param[2]);
state_t *state = (state_t *)instance;
double t = state->t;
state->t++;
double bot = 30.0;
double top = 120.0;
double falling = top - (top-bot)*(t/3500.0);
if (falling < bot) {
falling = bot;
}
double fr = falling * (1.0 + 0.5*sin(2.0 * M_PI * 25.0 * t/44100.0));
state->phase += fr / 44100.0;
if (state->phase > 1) state->phase--;
double rv = sin(2.0 * M_PI * state->phase);
double hold = 2000;
double env = 1.0;
if (t > hold) {
env = exp(-(t - hold) / 2500.0) - 0.01;
}
if (env < 0) {
return 1;
}
else {
*out += env * amp * rv;
return 0;
}
}
void *create() {
state_t *res = (state_t *)malloc(sizeof(state_t));
res->phase = 0.0;
res->t = 0;
return (void *)res;
}
void destroy(void *instance) {
free(instance);
}
|
C
|
// /bin/dev/_unbundle.c
// A command to unbundle bundle files. similar to tar, but bundle files
// can be unbundled on unix by "sh"ing the file.
// By Valodin
#include <std.h>
inherit DAEMON;
void unpack(string path)
{
string *lines;
string current_file, tmp;
int i, lsz;
lines = read_database(path);
i = 0; lsz = sizeof(lines);
while(i < lsz)
{
if(sscanf(lines[i++], "echo %s 1>&2", tmp) != 1)
continue;
current_file = absolute_path((string)this_player()->get_path(), tmp);
write("Unpacking " + current_file + "\n");
i++; /* skip sed line */
rm(current_file);
while(lines[i][0] == '-')
{
write_file(current_file, lines[i][1..strlen(lines[i])] + "\n");
i++;
}
i++; /* skip End line */
}
}
int cmd_unbundle(string str)
{
string tmp;
notify_fail("Usage: unbundle <file>\n");
if(!str)
return 0;
tmp = absolute_path((string)this_player()->get_path(), str);
write("Trying to unbundle " + tmp + "\n");
unpack(tmp);
return 1;
}
int help()
{
write("Command: unbundle\n"
"Syntax: unbundle <filename>\n\n"
"This unpacks files that have been created using bundle. They can "
"also be\nunpacked on a unix system by \"sh\"ing the file.\n");
return 1;
}
|
C
|
#include "scelib.h"
double sce_dot
(
const int N,
const double * X,
const int INCX,
const double * Y,
const int INCY
)
{
double dot = 0,x,y;
int i;
for (i=0;i<N;i++){
x=(*X);
y=(*Y);
dot += x*y;
X+=INCX;
Y+=INCY;
}
return dot;
}
|
C
|
# FilaDeque
Implementando Fila em C
#include <stdio.h>
#include <stdlib.h>
#include "FilaDeque.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void inicializa_fila (Fila *p, int c){ //Recebe ponteiro de fila e a capacidade da fila
p->dados=malloc(sizeof(int)*c);
p->capacidade = c;
p->inicio = 1;
p->fim=p->num_ele=0;
}
int fila_vazia(Fila f){
return f.num_ele==0;
}
int fila_cheia (Fila f){ //Recebe fila
return f.num_ele==f.capacidade;
}
int inserirDireita(Fila *p, int info){ //Recebe ponteiro de fila e o valor a ser inserido
if(fila_cheia(*p))
return ERRO_FILA_CHEIA;
p->num_ele++;
if(p->fim == p->capacidade-1){
p->fim=0;
}
else{
p->fim++;
}
p->dados[p->fim]=info;
return 1;
}
int inserirEsquerda(Fila *p, int info){ //Recebe ponteiro de fila e o valor a ser inserido
if(fila_cheia(*p))
return ERRO_FILA_CHEIA;
p->num_ele++;
if(p->inicio == 0){
p->inicio=p->capacidade-1;
}
else{
p->inicio--;
}
p->dados[p->inicio-1]=info;
return 1;
}
int removerEsquerda(Fila *p, int *info){ // Recebe o ponteiro de fila e o valor a ser removido;
if(fila_vazia(*p))
return ERRO_FILA_VAZIA;
p->num_ele--;
*info = p->dados[p->inicio];
if(p->inicio == p->capacidade-1)
p->inicio = 0;
else
p->inicio++;
return 1;
}
int removerDireita(Fila *p, int *info){ // Recebe o ponteiro de fila e o valor a ser removido;
if(fila_vazia(*p))
return ERRO_FILA_VAZIA;
p->num_ele--;
*info = p->dados[p->fim];
if(p->fim == 0)
p->fim = p->capacidade-1;
else
p->fim--;
return 1;
}
void mostra_fila(Fila p){
int i;
if(fila_vazia(p))
printf("Fila vazia!\n");
else{
printf("Dados da fila:\n");
if(p.inicio<p.fim){
for(i=p.inicio; i<=p.fim; i++){
printf("%d\n", p.dados[i]);
}
}
else{
for(i=p.inicio;i<p.capacidade;i++){
printf("%d\n", p.dados[i]);
}
for(i=0;i<=p.fim;i++){
printf("%d\n",p.dados[i]);
}
}
}
}
void desaloca_fila(Fila *p){
free(p->dados);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void){
{
char str1[] = "123456789";
char str2[] = "def";
/*
str2Ƹstr1
strcpystr2ָĴСǷĺstr1
str2ַָôԤˣΪstrcpyһֱƵһַΪֹ
ᳬԽstr1ָı߽
*/
strcpy(str1,str2);
printf("strcpy÷%s\n",str1);
printf("=========================\n");
}
{
/*
strlen:
ַȣԭ£
size_t strlen(const char *s);
strlenַsijȣsеһַ֮ǰַ(ַ)
*/
int len;
char str3[] = "adfasfasljfl";
len = strlen(str3);
printf("str1ij:%d\n",len);
printf("==========================\n");
}
{
/*
strcat:ַƴӣԭ£
char *strcat(char *s1, const char *s2);
s2ӵַs1ĩβҷַs1
*/
char str1[]="";
strcpy(str1,"132323");
strcat(str1,"---asfs");
printf("str1Ľ:%s\n",str1);
printf("=====================");
}
{
/*
strcmp:ַȽϣԭ£
int strcmp(const char *s1, const char *s2);
Ƚַs1ַs2,Ȼs1Сڣڣߴs2һСڣڻߴ0ֵ
*/
char str1[] = "bc";
char str2[] = "123";
if(strcmp(str1,str2) == 0){
printf("str1str2\n");
}else if(strcmp(str1,str2) > 0){
printf("str1str2\n");
}else if(strcmp(str1,str2) < 0){
printf("str1Сstr2\n");
}else{
printf("error\n");
}
}
}
|
C
|
/* https://issues.dlang.org/show_bug.cgi?id=22972
*/
int printf(const char *, ...);
void exit(int);
void assert(int b, int line)
{
if (!b)
{
printf("failed test %d\n", line);
exit(1);
}
}
struct op {
char text[4];
};
struct op ops[] = {
{ "123" },
{ "456" }
};
char *y = ops[1].text;
char *x[] = { ops[0].text };
int main()
{
//printf("%c %c\n", *y, *x[0]);
assert(*y == '4', 1);
assert(*x[0] == '1', 2);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.