language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include<stdio.h>
int main ()
{
int i=0,n,sum=0;
A:
i++;
sum=sum+i;
if(i==10)
{
printf("sum = %d",sum);
goto B;
}
goto A;
B:
return 0;
}
|
C
|
//
// main.c
// 1002
//
// Created by 摆线木偶 on 16/7/31.
// Copyright © 2016年 摆线木偶. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
int sum[10002], max = 0;
for (int i = 0; i < 10002; i++)
sum[i] = 0;
char input;
while (scanf("%c", &input)){
if (!(input <= '9' && input >= '0'))
break;
int in = input - '0';
int add = in;
int t = 0;
while (add != 0){
sum[t] += add;
if (sum[t] > 9){
sum[t] -= 10;
t++;
add = 1;
}
else
add = 0;
}
if (t > max)
max = t;
}
for (int i = max; i >= 0; i--){
switch(sum[i]){
case 0: printf("ling");break;
case 1: printf("yi");break;
case 2: printf("er");break;
case 3: printf("san");break;
case 4: printf("si");break;
case 5: printf("wu");break;
case 6: printf("liu");break;
case 7: printf("qi");break;
case 8: printf("ba");break;
case 9: printf("jiu");break;
default: printf("err");break;
}
if (i != 0)
printf(" ");
else
printf("\n");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sort_four_value.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hyeolee <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/17 19:29:44 by hyeolee #+# #+# */
/* Updated: 2021/05/18 15:51:08 by hyeolee ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../include/push_swap.h"
static int select_minimal_value(t_stack **a_stack)
{
int *sorted_temp;
int minimal;
sorted_temp = sort_temporary(a_stack, 4);
minimal = sorted_temp[0];
return (minimal);
}
void sort_four_value(t_stack **a_stack, t_stack **b_stack)
{
int minimal;
int i;
if (check_a_sorted(*a_stack, 4))
return ;
minimal = select_minimal_value(a_stack);
i = 0;
while (i < 4)
{
if ((*a_stack)->value == minimal)
push_cmd(a_stack, b_stack, "pb");
else
a_cmd(a_stack, "ra");
i++;
}
sort_a_three_value(a_stack);
push_cmd(a_stack, b_stack, "pa");
}
|
C
|
/// @file utsname.h
/// @brief Functions used to provide information about the machine & OS.
/// @copyright (c) 2014-2022 This file is distributed under the MIT License.
/// See LICENSE.md for details.
#pragma once
/// Maximum length of the string used by utsname.
#define SYS_LEN 257
/// @brief Holds information concerning the machine and the os.
typedef struct utsname_t {
/// The name of the system.
char sysname[SYS_LEN];
/// The name of the node.
char nodename[SYS_LEN];
/// Operating system release (e.g., "2.6.28").
char release[SYS_LEN];
/// The version of the OS.
char version[SYS_LEN];
/// The name of the machine.
char machine[SYS_LEN];
} utsname_t;
/// @brief Returns system information in the structure pointed to by buf.
/// @param buf Buffer where the info will be placed.
/// @return 0 on success, a negative value on failure.
int uname(utsname_t* buf);
|
C
|
/*
Class: CPSC 346-01 & CPSC 346-02
Team Member 1: Paul De Palma
Team Member 2: N/A
GU Username of project lead: depalma
Pgm Name: ex8.c
Pgm Desc: Demonstrates a system call to copy a file
Usage: ./a.out file_in file_out
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int inFile, outFile;
int len;
char ch;
if (argc != 3)
{
printf("Usage: copy f1 f2\n");
}
//FMI, google fntl.h
inFile = open(argv[1],O_RDONLY);
//FMI google sys/stat.h
//Silberschatz pp. 62-63
//"System calls provide an interace to the services made available by an o/s"
//Both open and read are system calls.
outFile = open(argv[2],O_WRONLY | O_CREAT, S_IRWXU);
//read/write 1 byte into buffer whose address is stored in ch
while ((len = read(inFile,&ch, 1)) > 0)
{
write(outFile,&ch,1);
}
close(inFile);
close(outFile);
return 0;
}
|
C
|
#include <stdio.h>
void main()
{
int m;
printf("Enter a number m: ");
scanf_s("%d", &m);
while (m <= 0)
{
printf("Number m must be greater, than 0. Re-enter m: \n");
scanf_s("%d", &m);
}
printf("Decimal form: 1 Binary form: 1\n");
for (int i = 3; i <= m; i += 2)
{
int i_rank; char is_sym = 1;
for (int j = 1;; j++)
{
if (i >> j) continue;
else
{
i_rank = j;
break;
}
}
for (int j = 2; j <= i_rank / 2; j++)
{
int rDigit = 1 & i >> j - 1;
int lDigit = 1 & i >> i_rank - j;
if (lDigit != rDigit)
{
is_sym = 0;
break;
}
}
if (is_sym)
{
i_rank -= 2;
printf("Decimal form: %d Binary form: 1", i);
for (i_rank; i_rank > 0; i_rank--)
{
if (i & 1 << i_rank) printf("1");
else printf("0");
}
printf("1\n");
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXINT 32767
#define maxcd 200
#define maxnum 2000
typedef struct
{
int weight;
int parent;
int lchild;
int rchild;
char data;
}HFTree;//0ŵԪʹ
int N;//Ҷ
int M;//
//==============================weight
int CalcuWeight(char code[],char letter[],int weight[])
{
int clen,i;
N=0;
int bl[26],sl[26],kong,ju,huan;
for(i=0;i<26;i++)
bl[i]=sl[i]=0;
kong=ju=huan=0;
clen=strlen(code);
for(i=0;i<clen-1;i++)
{
if(code[i]>='a'&&code[i]<='z') sl[code[i]-97]++;
else if(code[i]>='A'&&code[i]<='Z') bl[code[i]-65]++;
else if(code[i]==' ') kong++;
else if(code[i]=='.') ju++;
else huan++;
}
for(i=0;i<26;i++) weight[i+3]=bl[i];
for(i=0;i<26;i++) weight[26+i+3]=sl[i];
weight[0]=ju;
weight[1]=kong;
weight[2]=huan;
for(i=0;i<55;i++)
if(weight[i]!=0) N++;
return M=2*N-1;
}
//======================select
void select(int n,int *x,int *y,HFTree ht[])
{
int i,m1,m2;
m1=m2=MAXINT;
for(i=1;i<=n;i++)
{
if(ht[i].weight<m1&&ht[i].parent==0)
{
m2=m1;*y=*x;//ָСȨֵʱ
*x=i;
m1=ht[i].weight;
}
else if(ht[i].weight<m2&&ht[i].parent==0)
{
*y=i;
m2=ht[i].weight;
}
}
if(m2<m1) {
i=*x;*x=*y;*y=i;
}
// printf("min:%d nmin:%d\n",*x,*y);
}
//======================creat
void CrtHuffmanTree(int weight[],HFTree ht[],char letter[])
{
int i,j=0;
int min,nmin;
for(i=1;i<N+1;i++)//ǰNҶӽгʼ
{
for(j;j<55;j++)
if(weight[j]!=0)
{
ht[i].weight=weight[j];
ht[i].data=letter[j];
ht[i].parent=0;
ht[i].lchild=0;
ht[i].rchild=0;
j++;
break;
}
}
for(i=N+1;i<=M;i++)//ԿԪؽгʼ
{
ht[i].weight=0;
ht[i].parent=0;
ht[i].lchild=0;
ht[i].rchild=0;
ht[i].data='0';
}
for(i=N+1;i<=M;i++)
{
select(i-1,&min,&nmin,ht);
ht[i].weight=ht[min].weight+ht[nmin].weight;
ht[i].lchild=min;
ht[i].rchild=nmin;
ht[min].parent=i;
ht[nmin].parent=i;
}
}
//==============================
void CrtHuffmanCode(char letter[],HFTree ht[],char *hc[])
{
int i,j,p,cw;
char *cd;
cd=(char *)malloc(N*(sizeof(char)));
cd[N-1]='\0';
for(i=1;i<N+1;i++)
{ cw=i;
j=N-1;
p=ht[i].parent;
while(p!=0)
{ --j;
if(ht[p].lchild==cw) cd[j]='0';
else cd[j]='1';
cw=p;
p=ht[p].parent;
}
hc[i]=(char *)malloc((N-j)*sizeof(char));
strcpy(hc[i],&cd[j]);
// printf("letter:%c code:%s\n",ht[i].data,hc[i]);
}
}
//==============================letter to num
void TransLtoN(char *code,char letter[],char *hc[],int weight[],HFTree ht[])
{
char p;
int i,j=0,k;
p=code[j];
while(p!='\0')
{
for(i=1;i<=N;i++)
if(p==ht[i].data)
printf("%s",hc[i]);
j++;
p=code[j];
}
}
//==============================num to letter
void TransNtoL(char *num,char letter[],HFTree ht[])
{
int i=0,j=M;
char p=num[i];
while(p!='\0')
{
p=num[i];
i++;
if(ht[j].lchild==0&&ht[j].rchild==0)
{
printf("%c",ht[j].data);
j=M;
}
if(p=='0')
j=ht[j].lchild;
else //if(p=='1')
j=ht[j].rchild;
}
}
//test
void print(HFTree ht[],int weight[])
{
int i;
for(i=1;i<M+1;i++)
printf("%d letter:%c weight:%d parent:%d lchild:%d rchild:%d\n",i,ht[i].data,ht[i].weight,ht[i].parent,ht[i].lchild,ht[i].rchild);
}
void weiprint(int weight[],char letter[])
{
int i;
for(i=0;i<55;i++)
printf("%c:%d\n",letter[i],weight[i]);
}
//==============================aver
float aver(HFTree ht[],char *hc[])
{
int i,sum=0;
float average;
for(i=1;i<=N;i++)
sum+=ht[i].weight;
for(i=1;i<=N;i++)
{
average+=(ht[i].weight*1.0/sum*1.0)*(strlen(hc[i]));
}
return average;
}
//==============================main
int main()
{
int i=0,j=0,weight[55];
char letter[55]={'.',' ','\n','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char code[maxcd],text[maxnum];
code[i]=getchar();
while(code[i]!='#')
{
i++;
code[i]=getchar();
}
CalcuWeight(code,letter,weight);
HFTree ht[M+1];
char *hc[N+1];
CrtHuffmanTree(weight,ht,letter);
// weiprint(weight,letter);
// print(ht,weight);
// printf("M:%d N:%d",M,N);
CrtHuffmanCode(letter,ht,hc);
TransLtoN(code,letter,hc,weight,ht);
printf("\n");
scanf("%s",text);
TransNtoL(text,letter,ht);
printf("\n%.2f",aver(ht,hc));
}
|
C
|
// Scrivete una funzione con prototipo void scambia(int *p, int *q) che scambi i valori delle due variabili puntate da p e q.
#include <stdio.h>
void scambia(int *p, int *q){
int t = *p;
*p = *q;
*q = t;
}
int main() {
int p,q;
printf("Inserire due interi p e q: ");
scanf("%d %d",&p, &q);
scambia(&p,&q);
printf("p = %d q = %d\n",p,q);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define PI 3.14159265
int main(){
FILE *in;
float dt = 0.00001;
float dx;
float c = 250;
float r;
float *x;
float *phi_inic;
float *phi_prev;
float *phi_now;
float *phi_next;
int points;
int iter;
/*cuerda*/
points = 129;
x = malloc(points*sizeof(float));
phi_inic = malloc(points*sizeof(float));
phi_prev = malloc(points*sizeof(float));
phi_now = malloc(points*sizeof(float));
phi_next = malloc(points*sizeof(float));
/*extremos fijos*/
char filename1[100] = "cond_ini_cuerda.dat";
in = fopen(filename1, "r");
if(!in){
printf("No se pudo leer el archivo.\n");
exit(1);
}
for(int i = 0; i<points; i++){
fscanf(in, "%f %f\n", &x[i], &phi_inic[i]);
}
fclose(in);
dx = x[1];
r = c*(dt/dx);
/*primer paso*/
phi_now[0] = 0;
phi_now[128] = 0;
for(int i = 1; i<points-1; i++){
phi_now[i] = phi_inic[i] + (r*r/2)*(phi_inic[i+1] - 2*phi_inic[i] + phi_inic[i-1]);
}
for(int i = 0; i<points; i++){
phi_prev[i] = phi_inic[i];
}
/*evolucion temporal*/
iter = 1/dt;
phi_next[0] = 0;
phi_next[128] = 0;
for(int i = 0; i<iter-1; i++){
for(int j = 1; j<points-1; j++){
phi_next[j] = 2*(1 - r*r)*phi_now[j] - phi_prev[j] + r*r*(phi_now[j+1] + phi_now[j-1]);
}
for(int j = 0; j<points; j++){
phi_prev[j] = phi_now[j];
phi_now[j] = phi_next[j];
}
if(i == 50){
in = fopen("c1.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f,%f,%f\n", x[i], phi_inic[i], phi_now[i]);
}
fclose(in);
}
if(i == 100){
in = fopen("c2.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f,%f\n", x[i], phi_now[i]);
}
fclose(in);
}
if(i == 150){
in = fopen("c3.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f,%f\n", x[i], phi_now[i]);
}
fclose(in);
}
}
/*perturbacion periodica*/
for(int i = 0; i<points; i++){
phi_inic[i] = 0;
phi_now[i] = 0;
phi_prev[i] = phi_inic[i];
phi_next[i] = 0;
}
/*primer paso*/
phi_now[0] = sin((2*PI*c/0.64)*dt);
for(int i = 1; i<points-1; i++){
phi_now[i] = phi_inic[i] + (r*r/2)*(phi_inic[i+1] - 2*phi_inic[i] + phi_inic[i-1]);
}
/*evolucion temporal*/
for(int i = 2; i<iter+1; i++){
phi_next[0] = sin((2*PI*c/0.64)*(i*dt));
for(int j = 1; j<points-1; j++){
phi_next[j] = 2*(1 - r*r)*phi_now[j] - phi_prev[j] + r*r*(phi_now[j+1] + phi_now[j-1]);
}
for(int j = 0; j<points; j++){
phi_prev[j] = phi_now[j];
phi_now[j] = phi_next[j];
}
if(i == 52){
in = fopen("c4.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f,%f,%f\n", x[i], phi_inic[i], phi_now[i]);
}
fclose(in);
}
if(i == 102){
in = fopen("c5.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f,%f\n", x[i], phi_now[i]);
}
fclose(in);
}
if(i == 152){
in = fopen("c6.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f,%f\n", x[i], phi_now[i]);
}
fclose(in);
}
}
/*tambor*/
char filename2[100] = "cond_ini_tambor.dat";
int dim = 101;
points = dim*dim;
phi_inic = malloc(points*sizeof(float));
phi_prev = malloc(points*sizeof(float));
phi_now = malloc(points*sizeof(float));
phi_next = malloc(points*sizeof(float));
in = fopen(filename2, "r");
if(!in){
printf("No se pudo leer el archivo.\n");
exit(1);
}
for(int i = 0; i<points; i++){
fscanf(in, "%f", &phi_inic[i]);
}
fclose(in);
dx = 0.5/100;
r = c*(dt/dx);
/*primer paso*/
for(int i = 0; i<points; i++){
if(i<dim){
phi_now[i] = 0;
}
if(i>=(dim-1)*dim){
phi_now[i] = 0;
}
if(i%dim == 0){
phi_now[i] = 0;
phi_now[i-1] = 0;
}
}
for(int i = dim+1; i<(dim-1)*dim - 1; i++){
if(i%dim != 0 && i%dim != dim-1){
phi_now[i] = phi_inic[i] + r*r/2*(phi_inic[i+1] - 4*phi_inic[i] + phi_inic[i-1] + phi_inic[i+dim] + phi_inic[i-dim]);
}
}
for(int i = 0; i<points; i++){
phi_prev[i] = phi_inic[i];
}
/*evolucion temporal*/
for(int i = 0; i<points; i++){
if(i<dim){
phi_next[i] = 0;
}
if(i>=(dim-1)*dim){
phi_next[i] = 0;
}
if(i%dim == 0){
phi_next[i] = 0;
phi_next[i-1] = 0;
}
}
for(int j = 0; j<iter-1; j++){
for(int i = dim+1; i<(dim-1)*dim - 1; i++){
if(i%dim != 0 && i%dim != dim-1){
phi_next[i] = 2*(1 - 2*r*r)*phi_now[i] + r*r*(phi_now[i+1] + phi_now[i-1] + phi_now[i+dim] + phi_now[i-dim]) - phi_prev[i];
}
}
for(int i = 0; i<points; i++){
phi_prev[i] = phi_now[i];
phi_now[i] = phi_next[i];
}
if(j == 50){
in = fopen("t1.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f\n", phi_now[i]);
}
fclose(in);
}
if(j == 100){
in = fopen("t2.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f\n", phi_now[i]);
}
fclose(in);
}
if(j == 150){
in = fopen("t3.txt", "w");
for( int i = 0; i<points; i++ ){
fprintf(in, "%f\n", phi_now[i]);
}
fclose(in);
}
}
return 0;
}
|
C
|
#include "utilsStr.h"
#include "C99libs.h"
//CC hexNib[16] = "0123456789ABCDEF";
CC hexNib[16] = "0123456789abcdef";
U8 HexNibVal ( U8 nib )
{
if( (nib >= '0') && (nib <= '9') )
return nib - '0';
else
{
// nib = tolower( nib );
nib |= 0x20;
return (nib >= 'a') && ( nib <= 'f') ? nib - 'a' + 10 : 0;
}
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
Alphabet, and Alpha numeric character rotation functions.
*/
C AlphaRotN ( C c, S8 n )
{
C min, max;
if( (c >= 'A') && (c <= 'Z') )
min = 'A', max = 'Z';
else if( (c >= 'a') && (c <= 'z') )
min = 'a', max = 'z';
else
return c;
{
U8 no = (n >= 0) ? n : -n;
c += (n >= 0) ? no % 26 : - (no % 26);
}
if( c < min)
c += 26;
else if( c > max)
c -= 26;
return c;
}
C NumRotN ( C c, S8 n)
{
if( (c >= '0') && (c <= '9') )
{
U8 no = (n >= 0) ? n : -n;
c += (n >= 0) ? no % 10 : - (no % 10);
}
else
return c;
if( c < '0')
c += 10;
else if( c > '9')
c -= 10;
return c;
}
C AlphaNumRotN ( C c, S8 n )
{
C min, max, maxRot;
if( (c >= '0') && (c <= '9') )
min = '0', max = '9', maxRot = 10;
else if( (c >= 'A') && (c <= 'Z') )
min = 'A', max = 'Z', maxRot = 26;
else if( (c >= 'a') && (c <= 'z') )
min = 'a', max = 'z', maxRot = 26;
else
return c;
{
U8 no = (n >= 0) ? n : -n;
c += (n >= 0) ? no % maxRot : - (no % maxRot);
}
if( c < min)
c += maxRot;
else if( c > max)
c -= maxRot;
return c;
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
Ascii rot
*/
C AsciiRotN ( C c, S8 n)
{
return c + n;
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
USSD response handling
*/
C * StrToLower ( C * sp)
{
C *cp;
for( cp = sp; *cp; ++cp)
*cp = tolower( *cp);
return sp;
}
C * StrToUpper ( C * sp)
{
C *cp;
for( cp = sp; *cp; ++cp)
*cp = toupper( *cp);
return sp;
}
void StrReverse ( C * s)
{
int i;
ST j;
C c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
String utility functions, some of these destroy the string.
*/
/*
Remove all instances of a C in a string;
StrRemoveChar( "1234..5678", '.') => "12345678"
*/
V StrRemoveChar ( PC s, C c )
{
for( ; *s ; )
if( *s == c )
strcpy( s, s+1 );
else
++s;
}
V StrReplaceChar ( PC s, C frc, C toc )
{
for( ; *s ; )
if( *s == frc )
*s++ = toc;
else
++s;
}
PCC StrFirstDigit ( PCC s )
{
for( ; *s; ++s )
if( isdigit(*s) )
break;
return s;
}
U32 StrNumToInt ( PC s )
{
if( !(s = (PC)StrFirstDigit(s)) )
return 0;
StrRemoveChar( s, '.' );
return atoi(s);
}
// Shift the string n characters to the right
V StrShift ( PC s, S8 n )
{
C * sc = s;
C * sn;
while( *s ) s++; // Find end of string
sn = s+n;
do {
*sn-- = *s--;
} while( s >= sc );
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
String compare functions.
These Return the position of the trailing NULL. Not the target string.
*/
#if 0
PC StrNCmp ( PCC s, C * s1)
{
size_t s1l = strlen( s1 );
if( !strncmp(s, s1, s1l) )
return (C *)(s+s1l);
else
return NULL;
}
#endif
PCC StrChrAnyCase ( PCC s, I c )
{
C ch = toupper( (C)c );
for( ; toupper(*s) != ch; ++s )
if( *s == '\0' )
return NULL;
return s;
}
PCC StrCmp ( PCC s, PCC mts )
{
size_t mtsl = strlen(mts);
if( !strcmp( s, mts) )
return s + mtsl;
else
return (PCC)NULL;
}
PCC StrCmpAnyCase ( PCC s1, PCC s2 )
{
for( ; *s1 ; ++s1, ++s2 )
{
C c1 = *s1, c2 = *s2;
if( (c1 >= 'A') && (c1 <= 'Z') ) c1 += 'a' - 'A';
if( (c2 >= 'A') && (c2 <= 'Z') ) c2 += 'a' - 'A';
if( c1 != c2 )
return NULL;
}
return (*s1 == '\0') && (*s2 == '\0') ? s1 : NULL;
}
PCC StrStr ( PCC s, PCC mts )
{
size_t mtsl = 0;
if( (s = strstr(s, mts)) != NULL )
mtsl = strlen( mts );
return s + mtsl;
}
PCC StrStrAnyCase ( PCC s1, PCC s2 )
{
if( *s2 == '\0' )
return s1;
for( ;(s1 = StrChrAnyCase(s1, *s2)) != 0; ++s1 )
{
const C *sc1, *sc2;
for( sc1 = s1+1, sc2 = s2; ; ++sc1 )
if( *++sc2 == '\0' )
return s1;
else if( toupper(*sc1) != toupper(*sc2) )
break;
}
return NULL;
}
PCC StrNCmpN ( PCC s1, PCC s2, size_t s2l )
{ /* Returns end of string or NULL */
if( !strncmp(s1, s2, s2l) )
return s1 + s2l;
else
return (PCC)NULL;
}
PCC StrNCmpNAnyCase ( PCC s1, PCC s2, size_t s2l )
{ /* Returns end of string or NULL */
for( ; *s1 && s2l ; ++s1, ++s2, --s2l )
if( toupper(*s1) != toupper(*s2) )
return NULL;
return s2l == 0 ? s1 : NULL;
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
String copy functions.
These Return the position of the trailing NULL. Not the target string.
*/
PC StrCpy ( PC s1, PCC s2 )
{
strcpy( s1, s2 );
return s1 + strlen(s1);
}
/*
Like strncpy, except :
1. ALWAYS adds a trailing null character.
2. Returns the position of the trailing NULL. Not the target string.
*/
PC StrNCpy ( PC s1, PCC s2, size_t size )
{
strncpy( s1, s2, size );
s1[size] = '\0';
return s1 + strlen(s1);
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
String to number conversion functions.
Standard c string to number conversion functions are :-
double atof (const char *);
int atoi (const char *);
long atol (const char *);
long long atoll (const char *);
float strtof (const char *_Restrict, char **_Restrict);
double strtod (const char *_Restrict, char **_Restrict);
long double strtold (const char *_Restrict, char **_Restrict);
long strtol (const char *_Restrict, char **_Restrict, int);
unsigned long strtoul (const char *_Restrict, char **_Restrict, int);
long long strtoll (const char *_Restrict, char **_Restrict, int);
unsigned long long strtoull (const char *_Restrict, char **_Restrict, int);
intmax_t strtoimax(const char *_Restrict, char **_Restrict, int);
uintmax_t strtoumax(const char *_Restrict, char **_Restrict, int);
intmax_t wcstoimax(const _Wchart *_Restrict, _Wchart **_Restrict, int);
uintmax_t wcstoumax(const _Wchart *_Restrict, _Wchart **_Restrict, int);
*/
UI StrToU ( PC *s )
{
UI retval = 0;
/*
while( isdigit(**s)){
retval *= 10;
retval += **s - '0';
(*s)++;
}
*/
for( C c = **s; c >= '0' && c <='9'; ++(*s), c = **s )
retval *= 10, retval += c - '0';
return retval;
}
U32 StrToU32 ( PC *s )
{
U32 retval = 0;
for( C c = **s; c >= '0' && c <='9'; ++(*s), c = **s )
retval *= 10, retval += c - '0';
return retval;
}
U64 StrToU64 ( PC *s )
{
U64 retval = 0;
for( C c = **s; c >= '0' && c <='9'; ++(*s), c = **s )
retval *= 10, retval += c - '0';
return retval;
}
UI atoU ( PCC s )
{
UI retval = 0;
/*
while( isdigit(*s)){
retval *= 10;
retval += *s - '0';
s++;
}
*/
for( C c = *s; c >= '0' && c <='9'; c = *++s )
retval *= 10, retval += c - '0';
return retval;
}
U32 atoU32 ( PCC s )
{
U32 retval = 0;
for( C c = *s; c >= '0' && c <='9'; c = *++s )
retval *= 10, retval += c - '0';
return retval;
}
U64 atoU64 ( PCC s )
{
U64 retval = 0;
for( C c = *s; (c >= '0') && ( c <='9' ); c = *++s )
retval *= 10, retval += c - '0';
return retval;
}
U8 axtoU8 ( PCC hex )
{
return (HexNibVal(hex[0]) << 4) | HexNibVal(hex[1]);
}
/**
-----------------------------------------------------------------------------------------------------------------------------------
Number to string conversion functions.
*/
/*
C * llnum2str( C *s, unsigned long long n)
{
unsigned long long nc = n;
do{
s++;
nc /= 10;
}while( nc);
*s = 0;
do{
*--s = '0' + (n % 10);
n /= 10;
}while( n);
return( s);
}
*/
#if UTILS_STR_USE_XTOA
PC ltoa ( S32 n, PC s, I base )
{
S32 i, sign;
ldiv_t d;
if( (base < 2) || (base > 16) )
{
s[0] = '\0';
return s;
}
/* Record sign */
if( (sign = n) < 0 )
n = -n;
i = 0;
/* Generate digits in reverse order */
do {
d = ldiv( n, base);
s[i++] = hexNib[d.rem];
} while( (n = d.quot) > 0 );
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
StrReverse(s);
return s;
}
PC lltoa ( S64 n, PC s, I base )
{
S64 i, sign;
lldiv_t d;
if( (base < 2) || (base > 16) )
{
*s = '\0';
return s;
}
if ((sign = n) < 0)
n = -n;
i = 0;
do {
d = lldiv( n, base);
s[i++] = hexNib[ d.rem];
} while ((n = d.quot) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
StrReverse(s);
return s;
}
#endif
/* LToA == ltoa( n, s, 10) */
PC LToA ( S32 n, PC s )
{
S32 i, sign;
ldiv_t d;
if ((sign = n) < 0)
n = -n;
i = 0;
do {
d = ldiv( n, 10);
s[i++] = (C)(d.rem + '0');
} while ((n = d.quot) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
StrReverse(s);
return s;
}
/* LLToA == lltoa( n, s, 10) */
PC LLToA ( S64 n, PC s )
{
S64 i, sign;
lldiv_t d;
if ((sign = n) < 0)
n = -n;
i = 0;
do {
d = lldiv( n, 10);
s[i++] = (C)(d.rem + '0');
} while ((n = d.quot) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
StrReverse(s);
return s;
}
#if 0
// Deon. Check this, don't know if it works !!
/**
* C++ version 0.4 C * style "itoa":
* Written by Luks Chmela
* Released under GPLv3.
*/
PC itoa( I value, PC result, I base );
PC itoa( I value, PC result, I base )
{
if( base < 2 || base > 36 )
{
*result = '\0';
return result;
}
C *ptr = result, *ptr1 = result, tmp_char;
I tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35+(tmp_value-value*base)];
} while( value );
if( tmp_value < 0 )
*ptr++ = '-';
*ptr-- = '\0';
while( ptr1 < ptr )
{
tmp_char = *ptr;
*ptr-- = *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
#endif
UI GetIdFrZzStrAnyCase ( PCC pZzStr, PCC pPrmStr, UI maxStrId )
{
UI i;
for( i = 0; *pZzStr && i <= maxStrId; ++i )
{
UI slen = (UI)strlen(pZzStr);
if( StrNCmpAnyCase( pZzStr, pPrmStr ) )
break;
else
pZzStr += slen + (UI)1;
}
return i;
}
B GetIdFrStrLstAnyCase ( PUI pId, PCC *pStrLst, PCC pPrmStr, UI lstCnt )
{
for( UI i = 0; (i<lstCnt) && *pStrLst; ++i, ++pStrLst )
{
UI slen = (UI)strlen( *pStrLst );
// if( StrCmpAnyCase( *pStrLst, pPrmStr ) )
if( StrNCmpNAnyCase( *pStrLst, pPrmStr, slen ) )
{
*pId = i;
return true;
}
}
return false;
}
|
C
|
#include <door.h>
#include <stdlib.h>
#include <err.h>
#include <fcntl.h>
int main(int argc, char** argv) {
// Open the door
int door = open("server.door", O_RDONLY);
if (door == -1) err(1, "Could not open door");
// Call the server's "answer" function
int result = door_call(door, NULL);
if (result == -1) err(1, "My door request could not be placed");
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc, char** argv)
{
int infile, outfile;
char buf[1024];
int num;
if(argc != 3)
{
printf("The format must be:cp file_src file_des");
exit(0);
}
if((infile = open(argv[1], O_RDONLY)) == -1)
{
perror("open1");
exit(0);
}
if((outfile = open(argv[2], O_CREAT | O_EXCL | O_WRONLY, 0644)) == -1)
{
perror("open2");
exit(0);
}
do
{
num = read(infile, buf, 1024);
write(outfile, buf, num);
}while(num == 1024);
close(infile);
close(outfile);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "matr.h"
//Input: a - matrix (dim * dim), b - matrix (dim * dim)
//Output: none
//stdout: result ('res' matrix);
void matr(double **a, double **b, int dim)
{
//put your source code here
//
double **res;
int i = 0;
int j = 0;
for(;i<dim;i++)
{
for (;j<dim;j++)
printf("%lf ", res[i][j]);
printf("\n");
}
return;
}
|
C
|
#include<stdio.h>
int main(int argc,char **argv){
int (*(arr[])) = {
(int[]) {1,2,3,4,5} ,
(int[]) {6,7,8},
(int[]) {9,10,11,12},
(int[]) {13,14}
} ;
for(int i=0;i<4;i++){
for(int j=0;j<5;j++){
printf("arr[%d][%d] Address: %p Value: %d \n",i,j,&*(arr[i]+j),*(arr[i]+j));
}
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main () {
int Wa[32];
int F[32] = {0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0};
int i,j;
for(i=0;i<32;i++) {
if(F[i]==0)
Wa[i] = 1;
else
Wa[i] = -1;
printf("%2d",Wa[i]);
}
printf("\n");
int tmp1,tmp2,tmp3,tmp4;
for(i=0;i<16;i++) {
tmp1 = Wa[2*i];
tmp2 = Wa[2*i+1];
Wa[2*i] = tmp1+tmp2;
Wa[2*i+1] = tmp1-tmp2;
printf("%2d%2d",Wa[2*i],Wa[2*i+1]);
}
printf("\n");
for(i=0;i<8;i++) {
tmp1 = Wa[4*i];
tmp2 = Wa[4*i+1];
tmp3 = Wa[4*i+2];
tmp4 = Wa[4*i+3];
Wa[4*i] = tmp1+tmp3;
Wa[4*i+1] = tmp2+tmp4;
Wa[4*i+2] = tmp1-tmp3;
Wa[4*i+3] = tmp2-tmp4;
printf("%2d%2d%2d%2d",Wa[4*i],Wa[4*i+1],Wa[4*i+2],Wa[4*i+3]);
}
printf("\n");
for(i=0;i<4;i++) {
tmp1 = Wa[8*i];
tmp2 = Wa[8*i+4];
Wa[8*i] = tmp1+tmp2;
Wa[8*i+4] = tmp1-tmp2;
tmp1 = Wa[8*i+1];
tmp2 = Wa[8*i+5];
Wa[8*i+1] = tmp1+tmp2;
Wa[8*i+5] = tmp1-tmp2;
tmp1 = Wa[8*i+2];
tmp2 = Wa[8*i+6];
Wa[8*i+2] = tmp1+tmp2;
Wa[8*i+6] = tmp1-tmp2;
tmp1 = Wa[8*i+3];
tmp2 = Wa[8*i+7];
Wa[8*i+3] = tmp1+tmp2;
Wa[8*i+7] = tmp1-tmp2;
printf("%2d%2d%2d%2d%2d%2d%2d%2d",Wa[8*i],Wa[8*i+1],Wa[8*i+2],Wa[8*i+3],Wa[8*i+4],Wa[8*i+5],Wa[8*i+6],Wa[8*i+7]);
}
printf("\n");
for(i=0;i<2;i++) {
tmp1 = Wa[16*i];
tmp2 = Wa[16*i+8];
Wa[16*i] = tmp1+tmp2;
Wa[16*i+8] = tmp1-tmp2;
tmp1 = Wa[16*i+1];
tmp2 = Wa[16*i+9];
Wa[16*i+1] = tmp1+tmp2;
Wa[16*i+9] = tmp1-tmp2;
tmp1 = Wa[16*i+2];
tmp2 = Wa[16*i+10];
Wa[16*i+2] = tmp1+tmp2;
Wa[16*i+10] = tmp1-tmp2;
tmp1 = Wa[16*i+3];
tmp2 = Wa[16*i+11];
Wa[16*i+3] = tmp1+tmp2;
Wa[16*i+11] = tmp1-tmp2;
tmp1 = Wa[16*i+4];
tmp2 = Wa[16*i+12];
Wa[16*i+4] = tmp1+tmp2;
Wa[16*i+12] = tmp1-tmp2;
tmp1 = Wa[16*i+5];
tmp2 = Wa[16*i+13];
Wa[16*i+5] = tmp1+tmp2;
Wa[16*i+13] = tmp1-tmp2;
tmp1 = Wa[16*i+6];
tmp2 = Wa[16*i+14];
Wa[16*i+6] = tmp1+tmp2;
Wa[16*i+14] = tmp1-tmp2;
tmp1 = Wa[16*i+7];
tmp2 = Wa[16*i+15];
Wa[16*i+7] = tmp1+tmp2;
Wa[16*i+15] = tmp1-tmp2;
for(j=0;j<16;j++)
printf("%2d",Wa[16*i+j]);
}
printf("\n");
for(i=0;i<16;i++) {
tmp1 = Wa[i];
tmp2 = Wa[i+16];
Wa[i] = tmp1+tmp2;
Wa[i+16] = tmp1-tmp2;
}
for(i=0;i<32;i++)
printf("%2d",Wa[i]);
printf("\n");
float WA[32];
float max = 0;
int position;
for(i=0;i<32;i++)
WA[i] = (float)Wa[i]/(float)32;
for(i=0;i<32;i++) {
WA[i] = (WA[i]+1)/2;
if(WA[i]>max) {
max = WA[i];
position = i;
}
printf("%2d",(int)(100*WA[i]));
}
printf("\n");
printf("\nmax probability = %.2f with number",max,position);
int variables[5] = {0,0,0,0,0};
j = 4;
while(position>0) {
if(position%2==1) {
variables[j] = 1;
position /=2;
}
else {
variables[j] = 0;
position /=2;
}
j--;
}
for(i=0;i<5;i++) {
printf("%2d",variables[i]);
}
printf("\n");
printf("The best affine approximation is: ");
i = 0;
while(variables[i]==0 && i<5)
i++;
printf("X%d",i+1);
for(j=i+1;j<5;j++)
printf(" + X%d",j+1);
printf("\n");
return 0;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* _strncat - check the code for Holberton School students.
* @dest: destino
* @src: fuente
* @n: integer
* Return: Always 0.
*/
char *_strncat(char *dest, char *src, int n)
{
int contd;
int conts;
for (contd = 0; dest[contd] != '\0';)
{
contd++;
}
for (conts = 0; conts < n && src[conts] != '\0';)
{
dest[contd] = src[conts];
contd++;
conts++;
}
return (dest);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tokens_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bbelen <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/13 00:51:27 by bbelen #+# #+# */
/* Updated: 2021/01/16 19:30:24 by bbelen ### ########.fr */
/* */
/* ************************************************************************** */
#include "../minishell.h"
char *edit_arg(char *token, t_struct *conf)
{
int i;
char *tmp;
char *res;
tmp = NULL;
i = 0;
if (token[0] == '\'')
tmp = edit_arg_2(token, conf->env, 1);
else if (token[0] == '\"')
tmp = edit_arg_2(token, conf->env, 2);
else
tmp = edit_arg_2(token, conf->env, 0);
res = tmp;
return (res);
}
char *get_env_var(char *arg, char **env)
{
char *value;
int i;
i = 0;
value = NULL;
if (arg[0] == '?' && ft_strlen(arg) == 1)
{
value = ft_strdup(g_error);
return (value);
}
while (env[i])
{
if (ft_strcmp(arg, env[i]) == 0)
{
value = ft_strdup(env[i + 1]);
return (value);
}
i++;
}
return (NULL);
}
int if_command_name(char *token, char *path)
{
if (token && path)
return (1);
return (0);
}
void ft_comadd_back(t_command **lst, t_command *new)
{
t_command *current;
if (!(*lst))
*lst = new;
else
{
current = *lst;
while (current->next)
current = current->next;
current->next = new;
}
}
int is_command_end(char *token)
{
if (ft_strcmp(token, ";") == 0)
return (1);
if (ft_strcmp(token, "|") == 0)
return (1);
if (ft_strcmp(token, ">") == 0)
return (1);
if (ft_strcmp(token, "<") == 0)
return (1);
if (ft_strcmp(token, ">>") == 0)
return (1);
return (0);
}
|
C
|
#define Math_PI 3.1415926
double cot(double x)
{
return 1.0/tan(x);
}
double sec(double x)
{
return 1.0/cos(x);
}
double csc(double x)
{
return 1.0/sin(x);
}
double acot(double x)
{
return atan(1.0/x);
}
double asec(double x)
{
return acos(1.0/x);
}
double acsc(double x)
{
return asin(1.0/x);
}
double Log(double a,double x)
{
return log(x)/log(a);
}
double random()
{
int r=rand();
double d=(r+90.0)/(32767+90);
return d;
}
int factorial(int n)
{
int fact=1,i;
for(i=2;i<=n;i++)fact*=i;
return fact;
}
int permutation(int m,int n)
{
int perm=1,i;
for(i=0;i<n;i++)perm*=(m-i);
return perm;
}
int combination(int m,int n)
{
return permutation(m,n)/factorial(n);
}
double square(double x)
{
double d=x/(Math_PI*2);
double f=d-(int)d;
return f<=0.5?1:-1;
}
double unitSawtooth(double x,double k)
{
if(k==1)return x;
if(x<=-1||x>=1)return 0.0;
if(x>k)return 1-(x-k)/(1-k);
if(x<-k)return (-x-k)/(1-k)-1;
return x/k;
}
double sawtooth(double x,double k)
{
double d=x/(Math_PI*2);
double f=d-(int)d;
return -unitSawtooth(2*(f-0.5),k);
}
double sh(double x)
{
return (exp(x)-exp(-x))/2;
}
double ch(double x)
{
return (exp(x)+exp(-x))/2;
}
double th(double x)
{
return sh(x)/ch(x);
}
double cth(double x)
{
return ch(x)/sh(x);
}
double arsh(double x)
{
return log(x+sqrt(x*x+1));
}
double arch(double x)
{
return log(x+sqrt(x*x-1));
}
double arth(double x)
{
return 0.5*log((1+x)/(1-x));
}
double gauss(double x,double x0,double d)
{
double u=(x-x0)/d;
double k=sqrt(2*Math_PI)*d;
return exp(-u*u/2)/k;
}
double taylor(double x,double x0,double* df,int n)
{
double y=0,dx=1;int i;
for(i=0;i<n;i++)
{
y+=df[i]*dx/factorial(i);
dx*=(x-x0);
}
return y;
}
#define Vector struct Vector
Vector
{
double x;
double y;
double z;
};
Vector* newVector(double x,double y,double z)
{
Vector* vector=(Vector*)(malloc(sizeof(Vector)));
vector->x=x;
vector->y=y;
vector->z=z;
return vector;
}
Vector** newVectors(int length)
{
Vector** vectors=(Vector**)(malloc(length*sizeof(Vector*)));
int i;for(i=0;i<length;i++)vectors[i]=null;
return vectors;
}
void addVector(Vector* v0,Vector* v1)
{
v0->x+=v1->x;
v0->y+=v1->y;
v0->z+=v1->z;
}
void subVector(Vector* v0,Vector* v1)
{
v0->x-=v1->x;
v0->y-=v1->y;
v0->z-=v1->z;
}
double mulVector(Vector* v0,Vector* v1)
{
return v0->x*v1->x+v0->y*v1->y+v0->z*v1->z;
}
void mulDouble(Vector* v,double d)
{
v->x*=d;
v->y*=d;
v->z*=d;
}
double lengthOfVector(Vector* v)
{
return sqrt(mulVector(v,v));
}
void setVector(Vector* v,double x,double y,double z)
{
v->x=x;
v->y=y;
v->z=z;
}
void crossVector(Vector* v0,Vector* v1)
{
double x=v0->y*v1->z-v1->y*v0->z;
double y=v0->z*v1->x-v1->z*v0->x;
double z=v0->x*v1->y-v1->x*v0->y;
setVector(v0,x,y,z);
}
void projectVector(Vector* v0,Vector* v1)
{
double l0=lengthOfVector(v0);
double l1=lengthOfVector(v1);
double cosA=mulVector(v0,v1)/(l0*l1);
double k=l0*cosA/l1;
double x=v1->x*k;
double y=v1->y*k;
double z=v1->z*k;
setVector(v0,x,y,z);
}
double angleToVector(Vector* v0,Vector* v1)
{
double l0=lengthOfVector(v0);
double l1=lengthOfVector(v1);
return acos(mulVector(v0,v1)/(l0*l1));
}
boolean equalVectors(Vector* v0,Vector* v1)
{
return v0->x==v1->x&&v0->y==v1->y&&v0->z==v1->z;
}
Vector* scanVector()
{
Vector* v=newVector(0,0,0);
scanf("<%f,%f,%f>\n",&v->x,&v->y,&v->z);
return v;
}
void printVector(Vector* v)
{
printf("<%f,%f,%f>\n",v->x,v->y,v->z);
}
String vtoa(Vector* v)
{
String a=newChar(256);
sprintf(a,"<%f,%f,%f>",v->x,v->y,v->z);
return a;
}
void pushVector(List* stack,Vector* v)
{
if(v==null)
{
pushDouble(stack,0);
pushDouble(stack,0);
pushDouble(stack,0);
return;
}
pushDouble(stack,v->x);
pushDouble(stack,v->y);
pushDouble(stack,v->z);
}
Vector* popVector(List* stack)
{
double x=popDouble(stack);
double y=popDouble(stack);
double z=popDouble(stack);
return newVector(x,y,z);
}
void enQueueVector(List* queue,Vector* v)
{
enQueueDouble(queue,v->x);
enQueueDouble(queue,v->y);
enQueueDouble(queue,v->z);
}
Vector* deQueueVector(List* queue)
{
double x=deQueueDouble(queue);
double y=deQueueDouble(queue);
double z=deQueueDouble(queue);
return newVector(x,y,z);
}
|
C
|
#include<stdio.h>
#include<strings.h>
#include<stdlib.h>
#include "aes.h"
int main(int argc, char *argv[]){
/*
* Figure out how to read the test vectors and use them
* to validate AES. For now just a hardcoded one.
*/
unsigned int space[60];
unsigned char key[32];
unsigned char pt[16];
unsigned char ct[16];
memset(key, 0x00, 32);
bzero(space, 60*sizeof(int));
bzero(pt, 16);
aeskey(space, key);
aescrypt(ct, pt, space);
for(int i=0; i<16; i++){
printf("%02x", ct[i]);
}
printf("\n");
exit(0);
}
|
C
|
#include "conf.h"
typedef struct configure_t {
char name[50];
char passwd[50];
char ip[16];
short int port;
}configure;
int config_init(conf_t *conf,configure* myconfig){
int ret=0;
if( (ret= conf_getstr(conf, "user", "name", myconfig->name, 50))==-1){
printf("name not exist\n");
};
if((ret = conf_getstr(conf, "user", "passwd", myconfig->passwd,50))==-1){
printf("passwd not exist\n");
}
if((ret = conf_getstr(conf, "host", "ip", myconfig->ip,16))==-1){
printf("ip not exist\n");
}
if ((ret = conf_getshort(conf, "host", "port", &(myconfig->port)))==-1){
printf("port not exist\n");
}
}
print_config(configure* myconfig){
printf("[user]\n");
printf("name:%s\n",myconfig->name);
printf("passwd:%s\n",myconfig->passwd);
printf("[host]\n");
printf("ip:%s\n",myconfig->ip);
printf("port:%d\n",myconfig->port);
}
int main(int argc,char * argv[]){
char * filename="./config.ini";
int size=100;
conf_t *conf=NULL;
configure myconfig;
conf=conf_create(filename,size);
conf_load(conf);
config_init(conf,&myconfig);
print_config(&myconfig);
conf_destroy(conf);
return 0;
}
|
C
|
#include<string.h>
#include <stdlib.h>
#include"ENC.h"
int main(int argc, char** argv)
{
unsigned char *r = (unsigned char*)malloc(16),f[20],Key[17];
FILE *fp,*fq;
long l,t,size;
float per;
if(argc < 2)
{
printf("Enter The Filename to encrypt in the following format :\n\n\n ./enc <filename>\n");
return 0;
}
fp = fopen(argv[1],"rb+");
printf("Enter a key :\n");
scanf("%16[^\n]s",Key);
sprintf(Key,"%16s",Key);
fseek(fp,0,SEEK_END);
l = ftell(fp);
printf("size of file : %ld\n\n\n",l);
fseek(fp,0,SEEK_SET);
t=l>>4;
while(t-->0)
{
fread(r,1,16,fp);
fseek(fp,-16,SEEK_CUR);
r = logDual(r,Key);
fwrite(r,1,16,fp);
if(t%100==0)
{
size = l-(t<<4);
per = (100.0*size)/l;
printf("Progress : %8.2f%%\r",per);
fflush(stdout);
}
}
if(l&15L != 0L)
{
memset(r,' ',16);
t = fread(r,1,l&15L,fp);
fseek(fp,-t,SEEK_CUR);
r = logDual(r,Key);
fwrite(r,1,16,fp);
}
printf("Progress : %8.2f%% Completed !!\n",100.0);
fclose(fp);
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "rhhash.h"
struct entry {
struct rh_head rh_head;
char *key;
int val;
};
struct rh_head **buckets;
int bits;
struct entry *get(const char *key) {
struct entry *e;
int k;
long hash = rh_hash_str(key);
rh_for_each_possible_entry(e, k, hash, buckets, bits, rh_head) {
if (strcmp(e->key, key) == 0)
return e;
}
return NULL;
}
void put(const char *key, int val) {
struct entry *e;
int k;
long hash = rh_hash_str(key);
rh_for_each_possible_entry(e, k, hash, buckets, bits, rh_head) {
if (strcmp(e->key, key) == 0) {
e->val = val;
return;
}
}
e = malloc(sizeof *e);
e->key = strdup(key);
e->val = val;
INIT_RH_HEAD(&e->rh_head, hash);
rh_add(buckets, bits, &e->rh_head);
}
void del(const char *key) {
struct entry *e;
int k;
long hash = rh_hash_str(key);
rh_for_each_possible_entry(e, k, hash, buckets, bits, rh_head) {
if (strcmp(e->key, key) == 0) {
free(e->key);
free(e);
rh_del(buckets, bits, k);
return;
}
}
}
void clear(void) {
struct entry *e;
int k;
rh_for_each_entry (e, k, buckets, bits, rh_head) {
free(e->key);
free(e);
buckets[k] = NULL;
}
}
void show(void) {
struct entry *e;
int k;
rh_for_each_entry (e, k, buckets, bits, rh_head) {
printf("%s:\t\t%d\n", e->key, e->val);
}
}
int main() {
// Taken from course materials for "15-122 Principles of Imperative Computation" by Frank Pfenning
bits = 10;
int n = (1<<bits)-30;
int num_tests = 10;
printf("Testing array of size %d with %d values, %d times\n", (1 << bits), n, num_tests);
for (int j = 0; j < num_tests; j++) {
buckets = calloc(sizeof buckets[0], (1 << bits));
char key[256];
for (int i = 0; i < n; i++) {
sprintf(key, "%d", j*n+i);
int val = j*n+i;
put(key, val);
}
for (int i = 0; i < n; i++) {
sprintf(key, "%d", j*n+i);
assert(get(key)->val == j*n+i); /* "missed existing element" */
}
for (int i = 0; i < n; i++) {
sprintf(key, "%d", (j+1)*n+i);
assert(get(key) == NULL); /* "found nonexistent element" */
}
for (int i = 0; i < n / 2; i++) {
sprintf(key, "%d", j*n+i);
del(key);
}
for (int i = 0; i < n / 2; i++) {
sprintf(key, "%d", j*n+i);
assert(get(key) == NULL); /* "found nonexistent element" */
}
for (int i = n / 2; i < n; i++) {
sprintf(key, "%d", j*n+i);
assert(get(key)->val == j*n+i); /* "missed existing element" */
}
clear();
free(buckets);
}
printf("All tests passed!\n");
}
|
C
|
#include <stdio.h>
#include "matrixOperations.h"
#include "polynomialOperations.h"
void clearZeroes(float x[]) {
int i;
for(i = 0; i <= maxDegree; ++i) {
if (x[i] < precision && x[i] > -precision) {
x[i] = 0.0;
}
}
}
void add(float addTo[], float addFrom[]) {
int i;
for (i = 0; i <= maxDegree; ++i) {
addTo[i] += addFrom[i];
}
clearZeroes(addTo);
}
void subtract(float subTo[], float subFrom[]) {
int i, j;
for(i = 0; i <= maxDegree; ++i) {
subTo[i] -= subFrom[i];
}
clearZeroes(subTo);
// printf("tempA: ");
// printPoly(subTo);
// printf("b scaled: ");
// printPoly(subFrom);
}
// multiplies 2 polynomials, overwriting their product as the first argument
// this assumes that deg(a*b) <= maxDegree
void multiply(float a[], float b[], float c[]) {
int i, j;
setZero(c);
// int degA = degree(a);
// int degB = degree(b);
// int d = degA + degB;
for (i = maxDegree; i >= 0; --i) {
for (j = i; j >= 0; --j) {
c[i] += a[j] * b[i-j];
//printf("j = %i, i = %i, a[j] = %f, b[i-j] = %f\n", j, i, a[j], b[i-j]);
}
}
clearZeroes(c);
}
int degree(float x[]) {
int i;
int ret = 0;
for (i = maxDegree; i >= 0; --i) {
if (x[i] > precision || x[i] < -1*precision) {
ret = i;
break;
}
}
return ret;
}
// takes a vector a to b*a
void scale(float a[], float b) {
int i;
for (i = 0; i <= maxDegree; ++i) {
a[i] *= b;
}
}
int equalsZero(float poly[]) {
int ret = 1;
int i;
clearZeroes(poly);
for (i = 0; i <= maxDegree; ++i) {
if (poly[i] != 0) {
ret = 0;
break;
}
}
return ret;
}
void setZero(float x[]) {
int i;
for (i = 0; i <= maxDegree; ++i) {
x[i] = 0.0;
}
}
//sets arg1 equal to arg2
void setEquals(float x[], float y[]) {
int i;
for (i = 0; i <= maxDegree; ++i) {
x[i] = y[i];
}
}
void polyTimesXn(float a[], int power) {
if (degree(a) + power > maxDegree) {
printf("deg: %d, power: %d\n", degree(a), power);
printf("This would create a polynomial with degree greater than the maximum degree\n");
return;
}
int i;
if (power == 0) {
return;
}
else if (power > 0) {
for (i = maxDegree; i >= 0; --i) {
if (i >= power) {
a[i] = a[i-power];
}
else {
a[i] = 0;
}
}
}
else {
for (i = 0; i <= maxDegree; ++i) {
if (i - power <= maxDegree) {
a[i] = a[i - power];
}
else {
a[i] = 0;
}
}
}
}
void printPoly(float poly[], int line) {
int i;
for(i = 0; i <= maxDegree; ++i) {
if (i == 0) {
if (degree(poly) > 0) {
if (poly[i] != 0) {
printf("%1.2f", poly[i]);
printf(" + ");
}
}
else {
printf("%1.2f", poly[i]);
}
}
else if (i == degree(poly)) {
printf("%1.2f*x^%d", poly[i], i);
}
else {
if(poly[i] > precision || poly[i] < -precision) {
printf("%1.2f*x^%d + ", poly[i], i);
}
}
}
if (line == 1) {
printf("\n");
}
}
// returns 1 if x is in A, 0 if x is not in A
int contains(int A[], int len, int x) {
int i;
int ret = 0;
for(i = 0; i < len; ++i) {
if (A[i] == x) {
ret = 1;
break;
}
}
return ret;
}
int done(int A[], int B[], int lenA, int lenB) {
int i;
int ret = 1;
for(i = 0; i < lenA; ++i) {
if(contains(A, lenA, i) == 0) {
ret = 0;
break;
}
}
if (ret == 1) {
for(i = 0; i < lenB; ++i) {
if(contains(B, lenB, i) == 0) {
ret = 0;
break;
}
}
}
return ret;
}
void updateFinishedRows(float A[][M][maxDegree+1], int finishedRows[]) {
int tempCount, m, n;
for (n = 0; n < N; ++n) {
tempCount = 0;
for(m = 0; m < M; ++m) {
if(equalsZero(A[n][m]) == 0) { ++tempCount; }
}
if (tempCount < 2) { finishedRows[n] = n; }
else { finishedRows[n] = -1; }
}
}
void updateFinishedColumns(float A[][M][maxDegree+1], int finishedColumns[]) {
int tempCount, m, n;
for(m = 0; m < M; ++m) {
tempCount = 0;
for(n = 0; n < N; ++n) {
if(equalsZero(A[n][m]) == 0) { ++tempCount; }
}
if(tempCount < 2) { finishedColumns[m] = m; }
else { finishedColumns[m] = -1; }
}
}
void findLeastEntry(float A[][M][maxDegree+1], int finishedRows[], int finishedColumns[], int *tempN, int *tempM, int *finished) {
int m, n;
int boole = 0;
*finished = 0;
int tempMin = -1; // stores a minimum degree
// find one element that does not equal zero
for(n = 0; n < N; ++n) {
for(m = 0; m < M; ++m) {
if(contains(finishedRows, N, n) == 0 || contains(finishedColumns, M, m) == 0) {
if(equalsZero(A[n][m]) == 0) {
*tempN = n;
*tempM = m;
tempMin = degree(A[n][m]);
boole = 1;
break;
}
if (boole == 1) {
break;
}
}
}
}
if (tempMin == -1) {
printf("There is no valid least entry\n");
*finished = 1;
return;
}
for(n = 0; n < N; ++n) {
for (m = 0; m < M; ++m) {
if(contains(finishedRows, N, n) == 0 || contains(finishedColumns, M, m) == 0) {
if (equalsZero(A[n][m]) == 0) {
if(degree(A[n][m]) < tempMin) {
*tempN = n;
*tempM = m;
tempMin = degree(A[n][m]);
}
}
}
}
}
if (*tempM == -1 || *tempN == -1) { *finished = 1; }
}
int dividesRowAndCol(float A[][M][maxDegree+1], int tempN, int tempM) {
int m, n;
int ret = 1;
if (equalsZero(A[tempN][tempM]) == 1) {
printf("You have called this with A[i][j] = the zero vector\n");
return 0;
}
if (tempN == -1 || tempM == -1) {
printf("You have called this with tempN = -1 or tempM = -1\n");
return 0;
}
for(n = 0; n < N; ++n) {
if (n != tempN) {
if (dividesPoly(A[n][tempM], A[tempN][tempM]) == 0) {
ret = 0;
}
}
}
for(m = 0; m < M; ++m) {
if (m != tempM) {
if (dividesPoly(A[tempN][m], A[tempN][tempM]) == 0) {
ret = 0;
}
}
}
return ret;
}
int dividesPoly(float a[], float b[]) {
int i;
// creates tempA as a clone of a
float tempA[maxDegree+1];
setEquals(tempA, a);
float tempB[maxDegree+1];
setEquals(tempB, b);
float q[maxDegree+1];
setZero(q);
int degA = degree(a);
int degB = degree(b);
int d = degA - degB;
float tempQ;
// algorithm for euclidean division
for (i = d; i >= 0; --i) {
tempQ = tempA[degA + i - d] / tempB[degB];
q[i] = tempQ;
if (tempQ != 0) {
scale(tempB, tempQ);
polyTimesXn(tempB, i);
subtract(tempA, tempB);
polyTimesXn(tempB, -i);
scale(tempB, 1.0/tempQ);
}
}
multiply(b, q, tempA);
subtract(tempA, a);
clearZeroes(tempA);
if(equalsZero(tempA) == 1) {
return 1;
}
else {
return 0;
}
}
//the input for c will be tempA from eucdiv
// void ldMult(float b[], float q[], float c[]) {
// int i, j;
// for (i = maxDegree; i >= 0; --i) {
// for (j = i; j >= 0; --j) {
// c[i] -= b[j] * q[i-j];
// }
// }
// //eliminate inevitable floating point precision related errors
// clearZeroes(c);
// // printf("b: ");
// // printPoly(b);
// // printf("q: ");
// // printPoly(q);
// // printf("tempA: ");
// // printPoly(c);
// }
// sets q equal to the polynomial s.t. a = bq + r
void eucDiv(float a[], float b[], float q[]) {
if (equalsZero(a) == 1) {
printf("You are calling eucDiv with a equal to the zero vector\n");
return;
}
if (equalsZero(b) == 1) {
printf("You are calling a division by 0\n");
return;
}
// printf("a in eucdiv call: ");
// printPoly(a);
// printf("b in eucdiv call: ");
// printPoly(b);
int i;
// printf("\narg1 of eucdiv: ");
// printPoly(a);
// printf("\narg2 of eucdiv: ");
// printPoly(b);
int degA = degree(a);
int degB = degree(b);
//printf("\ndeg arg1: %d, deg arg2: %d\n", degA, degB);
int d = degA - degB;
if (d < 0) {
printf("This is a nonsensical call of eucDiv\n");
return;
}
float tempQ;
setZero(q);
// creates tempA as a clone of a
float tempA[maxDegree+1];
setEquals(tempA, a);
float tempB[maxDegree+1];
setEquals(tempB, b);
// float tempPoly[maxDegree+1];
// algorithm for euclidean division
for (i = d; i >= 0; --i) {
tempQ = tempA[degA + i - d] / tempB[degB];
q[i] = tempQ;
if (tempQ != 0) {
scale(tempB, tempQ);
polyTimesXn(tempB, i);
subtract(tempA, tempB);
polyTimesXn(tempB, -i);
scale(tempB, 1.0/tempQ);
}
}
}
void orderHelper(float A[][M][maxDegree+1], int *tempN, int *tempM, int counter) {
int m, n;
int tempMin = -1;
int boole = 0;
for(n = counter; n < N; ++n) {
for(m = counter; m < M; ++m) {
if(equalsZero(A[n][m]) == 0) {
*tempN = n;
*tempM = m;
tempMin = degree(A[n][m]);
boole = 1;
break;
}
if (boole == 1) {
break;
}
}
}
if (tempMin == -1) {
printf("This should not execute Error in orderHelper.\n");
return;
}
for(n = counter; n < N; ++n) {
for (m = counter; m < M; ++m) {
if (equalsZero(A[n][m]) == 0) {
if(degree(A[n][m]) < tempMin) {
*tempN = n;
*tempM = m;
tempMin = degree(A[n][m]);
}
}
}
}
if(*tempN == -1 || *tempM == -1) { printf("tempN or tempN is equal to -1\n"); }
// }
}
void orderDiagonals(float A[][M][maxDegree+1], float P[][N][maxDegree+1], float Pinv[][N][maxDegree+1], float Q[][M][maxDegree+1], float Qinv[][M][maxDegree+1]) {
int counter = 0;
int tempM, tempN;
while(counter < rank) {
tempM = -1;
tempN = -1;
orderHelper(A, &tempN, &tempM, counter);
if (tempN != counter || tempM != counter) {
rowOperations3(A, P, Pinv, tempN, counter);
columnOperations3(A, Q, Qinv, tempM, counter);
}
++counter;
}
}
|
C
|
#include<string.h>
#include <stdio.h>
void sanitizer(char* buf,char* out,int len){
for (i=0, i<len, i++){
if (buf[i] != '`' && buf[i] != '>' && buf[i] != ';' && buf[i] != '&'){
out[i] = buf[i];
}
else{
return 1;
}
}
return 0;
}
int main(){
char buf[0x20]={0};
char out[0x20]={0};
if(!sanitizer(buf,out,0x20)){
sprintf(cmd,"echo %s",out);
system(cmd);
}
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int i;
int int_ans = 1;
long long_ans = 1;
float float_ans = 1;
double double_ans = 1;
for (i = 1; i <= 100; i++) {
int_ans *= i;
long_ans *= i;
float_ans *= i;
double_ans *= i;
}
printf("Int ans = %d\n", int_ans);
printf("Long ans = %ld\n", long_ans);
printf("Float ans = %f\n", float_ans);
printf("Double ans = %f\n", double_ans);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
char str[100];
int i,n,j;
scanf("%d",&n);
if(n<=0||n>50) return 0;
for(i=0;i<n;i++)
{
scanf("%s",str);
printf("String #%d\n",i+1);
for(j=0;str[j]!='\0';j++)
if(str[j]=='Z') putchar('A');
else putchar(str[j]+1);
putchar('\n');
putchar('\n');
}
return 0;
}
|
C
|
/*
when 8-bits are there
LDR: 1-2-25
(rest dec with inc in intensity)
NTC:(31.00.31.50)-33.50-34.00 //-31.50-
(rest dec with inc in temp)
when 16-bits are there
LDR: 1-10-115
NTC:128-133-137
*/
#define F_CPU 16000000UL
#include<avr/io.h>
#include<util/delay.h>
#include<avr/interrupt.h>
void setup_adc();
int main()
{
DDRD = 0xA0; //Set Pin5 and Pin7 on arduino as output
sei(); //Enales global interrupt
setup_adc(); //Setup ADC according to the defined function
while(1) {} //Don't let the program to end
}
ISR(ADC_vect)
{
uint8_t adcl = ADCL; //This is an 8-bit varible used to store the value of ADLC
uint16_t adc_ten_bit_value = ADCH<<2 | adcl>>6; //This is an 16-bit varible use to store
//the 10-bit value of left adjusted result
int value_of_mux0= ADMUX & 1<<MUX0;
/************************************** NTC **********************/
if(adc_ten_bit_value>133 && (value_of_mux0==0))
{
PORTD|=1<<PD7;
}
else
{
PORTD&=(~(1<<PD7));
}
// Input from NTC is on A0, hence when value_of_mux0 is equal to zero and the
// recieved adc_ten_bit_value is greater than 133, then make Pin7 on arduino HIGH else make it LOW
/****************************************************************************/
/************************************** LDR **********************/
if(adc_ten_bit_value<10 && (value_of_mux0!=0))
{
PORTD|=1<<PD5;
} //LDR
else
{
PORTD&=(~(1<<PD5));
}
// Input from LDR is on A1, hence when value_of_mux0 is'nt equal to zero and the
// recieved adc_ten_bit_value is less than ten, then make Pin5 on arduino HIGH else make it LOW
/***********************************************************************************/
ADMUX ^= 1<<MUX0; //Toggles one of the select bit MUX0, i.e. toggling takes place in between A0 and A1 pin on arduino
ADCSRA |= 1<<ADSC; //Starts the conversion again
}
void setup_adc()
{
ADCSRA |= 1<<ADEN; //Enables ADC
ADCSRA |= 1<<ADPS2 | 1<<ADPS1 | 1<<ADPS0; //Sets ADC Prescalar as 128, i.e. my ADC frequency is 125KHz
ADCSRA |= 1<<ADIE | 1<<ADSC ; //Enables ADC interupt and Start the conversion
ADMUX |= 1<<ADLAR | 1<<REFS0; //ADLAR=1 for left adjusted result and REFS0=1 with REFS1=0
//to use Vcc as reference voltage
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stc/crandom.h>
#ifdef __cplusplus
#include <random>
#endif
#define NN 3000000000
int main(void)
{
clock_t difference, before;
uint64_t v;
crand_rng64_t stc = crand_rng64_init(time(NULL));
crand_uniform_i64_t idist = crand_uniform_i64_init(10, 20);
crand_uniform_f64_t fdist = crand_uniform_f64_init(10, 20);
c_forrange (30) printf("%02zd ", crand_uniform_i64(&stc, &idist));
puts("");
crand_rng32_t pcg = crand_rng32_init(time(NULL));
crand_uniform_i32_t i32dist = crand_uniform_i32_init(10, 20);
crand_uniform_f32_t f32dist = crand_uniform_f32_init(10, 20);
before = clock(); \
v = 0;
c_forrange (NN) {
//v += crand_i32(&pcg);
v += crand_uniform_i32(&pcg, &i32dist);
}
difference = clock() - before;
printf("pcg32: %.02f, %zu\n", (float) difference / CLOCKS_PER_SEC, v);
before = clock(); \
v = 0;
c_forrange (NN) {
//v += crand_i64(&stc) & 0xffffffff;
v += crand_uniform_i64(&stc, &idist);
}
difference = clock() - before;
printf("stc64: %.02f, %zu\n", (float) difference / CLOCKS_PER_SEC, v);
c_forrange (8) printf("%d ", crand_uniform_i32(&pcg, &i32dist));
puts("");
c_forrange (8) printf("%f ", crand_uniform_f32(&pcg, &f32dist));
puts("");
c_forrange (8) printf("%f ", crand_uniform_f64(&stc, &fdist));
puts("");
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "dk_tool.h"
int main() {
int d, a, f, c, q;
char s[100];
printf("Enter D:\n");
while(d < 1) {
checkD(&d);
}
printf("\nEnter A:\n");
while(a < 1) {
checkA(&a);
}
printf("\nEnter F in HEX system:\n");
do{
printf("F = ");
scanf("%s",&s);
f = transfer(s);
}
while(f != transfer(s));
printf("\nEnter C:\n");
checkC(&c);
q = (a * (f - c))*d;
printf("\n\nRezult:\n");
printf("Q = %i\n", q);
}
|
C
|
# DSA_Assignment_02
#include<stdio.h>
char * GetRomanNumber(char*numbers[],int i);
void main()
{
char *units[] = { "", "I","II","III","IV","V","VI","VII","VIII","IX" };
char *tens[] = { "", "X","XX","XXX","XL","L","LX","LXX","LXXX","XC" };
char *hundreds[] = {"", "C","CC","CCC","CD","D","DC","DCC","DCCC","CM" };
char *thousands[] = {"", "M","MM","MMM" };
int n;
printf("Enter number: ");
scanf("%d", &n);
int u,t,h,th;
u = n % 10;
t = (n / 10)%10;
h = (n / 100)%10;
th = (n / 1000)%10;
printf("%s",GetRomanNumber(thousands,th));
printf("%s",GetRomanNumber(hundreds,h));
printf("%s",GetRomanNumber(tens,t));
printf("%s",GetRomanNumber(units,u));
printf("\n");
}
char * GetRomanNumber(char*numbers[],int i)
{
return numbers[i];
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memmove.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mapandel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/04 05:40:58 by mapandel #+# #+# */
/* Updated: 2016/11/15 16:17:04 by mapandel ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_memmove(void *dest, const void *src, size_t n)
{
void *result;
result = dest;
if ((((char*)dest >= (char*)(unsigned long)src + n)) ||
(char*)dest <= (char*)(unsigned long)src)
{
while (n--)
{
*(char*)dest = *(char*)(unsigned long)src;
dest = (char*)dest + 1;
src = (char*)(unsigned long)src + 1;
}
}
else
{
dest = (char*)dest + n - 1;
src = (char*)(unsigned long)src + n - 1;
while (n--)
{
*(char*)dest = *(char*)(unsigned long)src;
dest = (char*)dest - 1;
src = (char*)(unsigned long)src - 1;
}
}
return (result);
}
|
C
|
/* String_Distance.c
Author: BSS9395
Update: 2021-09-03T14:57:00+08@China-Guangdong-Zhanjiang+08
Design: String Distance
Platform: Linux
Original: https://blog.csdn.net/shizheng163/article/details/50988023
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/* Dynamic Equation
dp[0][j] represents the Distance from "" to strY[0..j-1]. Insertion.
dp[i][0] represents the Distance from strX[0..i-1] to "". Deletion.
dp[i][j] represents the Distance between strX[0..i-1] and strY[0..j-1].
dp[i][j-1]+1 means inserting strY[i][j-1].
dp[i-1][j]+1 means deleting strX[i-1][j].
dp[i-1][j-1]+1 means revising strX[i-1] or strY[j-1].
----------------------------------------
case 1: i == 0
dp[0][j] = j
case 2: j == 0
dp[i][0] = i
case 3: 0 < i && 0 < j
case 31: strX[i-1] == strY[j-1] // no need to revise strX[i-1] and strY[j-1].
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]+1, dp[i][j-1]+1)
case 32: strX[i-1] != strY[j-1] // have to revise strX[i-1] to strY[j-1].
dp[i][j] = min(dp[i-1][j-1]+1, dp[i-1][j]+1, dp[i][j-1]+1)
*/
int String_Distance(char *strX, int lenX, char *strY, int lenY) {
int insert_cost = 1;
int delete_cost = 1;
int revise_cost = 1;
int dp[lenX + 1][lenY + 1];
dp[0][0] = 0;
for (int i = 1; i <= lenX; i += 1) {
dp[i][0] = i * delete_cost;
}
for (int j = 1; j <= lenY; j += 1) {
dp[0][j] = j * insert_cost;
}
for (int i = 1; i <= lenX; i += 1) {
for (int j = 1; j <= lenY; j += 1) {
if (strX[i - 1] == strY[j - 1]) {
dp[i][j] = (int)fmin(dp[i - 1][j - 1], (int)fmin(dp[i - 1][j] + delete_cost, dp[i][j - 1] + insert_cost));
}
else {
dp[i][j] = (int)fmin(dp[i - 1][j - 1] + revise_cost, (int)fmin(dp[i - 1][j] + delete_cost, dp[i][j - 1] + insert_cost));
}
}
}
return dp[lenX][lenY];
}
/* String Distance
s t r Y
0 1 2 3 4 5 6
b e a u t y
+---------------⇒ Insertion
0 |[0]1 2 3 4 5 6 |
s 1 b| 1[0|1]2 3 4 5 | "batyu" => "beatyu"
t 2 a| 2 1 1[1|2]3 4 | "beatyu" => "beautyu"
r 3 t| 3 2 2 2 2[2]3 |
X 4 y| 4 3 3 3 3 3[2]| "beautyu" => "beauty"
5 u| 5 4 4 4 3 4[3]|
⇓---------------⇘
Deletion Revision
*/
int main(int argc, char *argv[]) {
char *strX = (char *)"batyu";
char *strY = (char *)"beauty";
int lenX = (int)strlen(strX);
int lenY = (int)strlen(strY);
int dist = String_Distance(strX, lenX, strY, lenY);
fprintf(stdout, "%d""\n", dist);
return 0;
}
|
C
|
#include <stdio.h>
void main()
{
int rn[] = {1, 5, 10, 50, 100, 1000};
int *r;
int x;
for (x = 0; x < 6; x++)
{
r = rn;
printf("%i. %u = %i\n", x + 1, r, rn[x]);
r++;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "ft_list.h"
void ft_list_push_front(t_list **begin_list, void *data);
int ft_list_size(t_list *begin_list);
t_list *ft_list_last(t_list *begin_list);
void ft_list_push_back(t_list **begin_list, void *data);
t_list *ft_list_push_strs(int size, char **strs);
void ft_list_clear(t_list *begin_list, void (*free_fct)(void *));
void free_data(void *data)
{
free(data);
}
int main(void)
{
int size = 2;
char **strs = (char **)malloc(sizeof(char *) * size);
strs[0] = (char *)malloc(sizeof(char) * 6);
for (int i = 0; "hello"[i]; i++)
strs[0][i] = "hello"[i];
strs[0][5] = 0;
strs[1] = (char *)malloc(sizeof(char) * 6);
for (int i = 0; "world"[i]; i++)
strs[1][i] = "world"[i];
strs[1][5] = 0;
/*
strs[2] = "good";
strs[3] = "bye";
*/
t_list *begin_list = ft_list_push_strs(size, strs);
t_list *curr = begin_list;
while (curr)
{
printf("%s\n", curr->data);
curr = curr->next;
}
ft_list_clear(begin_list, &free_data);
return (0);
}
t_list *ft_create_elem(void *data)
{
t_list *elem;
elem = (t_list *)malloc(sizeof(t_list));
if (elem == 0)
return (0);
elem->data = data;
elem->next = 0;
return (elem);
}
void ft_list_push_front(t_list **begin_list, void *data)
{
t_list *new_elem;
new_elem = ft_create_elem(data);
if (new_elem == 0)
return ;
if (begin_list != 0)
new_elem->next = *begin_list;
*begin_list = new_elem;
}
int ft_list_size(t_list *begin_list)
{
int size;
t_list *curr;
if (begin_list == 0)
return (0);
size = 0;
curr = begin_list;
while (curr)
{
size++;
curr = curr->next;
}
return (size);
}
t_list *ft_list_last(t_list *begin_list)
{
t_list *curr;
if (begin_list == 0)
return (0);
curr = begin_list;
while (curr->next)
curr = curr->next;
return (curr);
}
void ft_list_push_back(t_list **begin_list, void *data)
{
t_list *new_list;
t_list *curr;
if (begin_list == 0)
return ;
new_list = ft_create_elem(data);
if (new_list == 0)
return ;
if (*begin_list == 0)
{
*begin_list = new_list;
return ;
}
curr = *begin_list;
while (curr->next)
curr = curr->next;
curr->next = new_list;
}
t_list *ft_list_push_strs(int size, char **strs)
{
int i;
t_list *begin_list;
if ((begin_list = ft_create_elem(strs[0])) == 0)
return (0);
i = 1;
while (i < size)
{
ft_list_push_front(&begin_list, strs[i]);
i++;
}
return (begin_list);
}
|
C
|
#include "Queue.h"
#include <stdlib.h>
#include <assert.h>
#define MAXQ 6
struct queue {
int nitems;
int head;
int tail;
int items[MAXQ];
};
// create a new empty Queue
Queue makeQueue() {
Queue q = malloc(sizof struct queue);
q->nitems = 0;
q->head = 0;
q->tail = 0;
return q;
}
// delete memory associated with a Queue
void freeQueue(Queue q) {
free(q);
}
// insert a new item at the tail of the Queue
void enterQueue(Queue q, int item) {
assert(q->nitems < MAXQ);
q->items[q->tail] = item;
q->tail = (q->tail + 1)%MAXQ;
q->nitems++;
}
// remove/return the item at the head of the Queue
int leaveQueue(Queue q) {
assert(q->nitems > 0);
int toReturn = q->items[q->head];
q->head = (q->head + 1)%MAXQ;
q->nitems--;
return toReturn;
}
// return the number of items currently in the Queue
int lengthQueue(Queue q) {
return q->nitems;
}
/*// create a new empty Queue
Queue makeQueue() {
Queue q = malloc(sizeof(struct queue));
q->nitems = 0;
q->head = 0;
q->tail = 0;
return q;
}
// delete memory associated with a Queue
void freeQueue(Queue q) {
free(q);
}
// insert a new item at the tail of the Queue
void enterQueue(Queue q, int item) {
assert(q->nitems < MAXQ);
q->nitems++;
q->items[q->tail] = item;
q->tail = (q->tail + 1) % MAXQ;
}
// remove/return the item at the head of the Queue
int leaveQueue(Queue q) {
assert(q->nitems > 0);
q->nitems--;
int toReturn = q->items[q->head];
q->head = (q->head + 1)% MAXQ;
return toReturn;
}
// return the number of items currently in the Queue
int lengthQueue(Queue q) {
return q->nitems;
}*/
|
C
|
/*********************************************************
Author: Benjamin R. Olson
Date: 2-25-17
Filename: ftserver.c
Description: OSU Networking CS 372, Project 2
simple FTP server
Usage: ftpserver <port number>
Once running, receives and responds to requests:
If a client requests "-l" (without the quotes),
then respond with directory listing of working directory.
If a client requests "-g <file name>",
then respond with the contents of that file.
A control connection remains running, and each request
is serviced by an additional data connection.
***********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "connectionController.h"
#include "fileManager.h"
int main (int argc, char **argv) {
/*check command line syntax */
if ( argc != 2 ) {
printf( "Usage:\nftpserver <port number>\nNote: Port numbers 30021 and 30020 not allowed\n" );
exit(1);
}
char* port = argv[1];
/* check <port number> arg */
/* adapted from http://stackoverflow.com/questions/16644906/how-to-check-if-a-string-is-a-number */
/**********************************************************/
int i = 0;
while ( i < strlen( port ) ) {
if( port[i] > '9' || port[i] < '0' ) {
printf( "<port number> must be a number" );
}
i++;
}
/**********************************************************/
if ( strcmp( port, "30021" ) == 0 || strcmp( port, "30020" ) == 0 ) {
printf( "<port number> cannot be 30021 or 30020" );
exit(1);
}
/* port number > 1024 and < 65535 */
int x;
sscanf( port, "%d", &x );
if ( x < 1024 || x > 65535 ) {
printf( "<port number> must be in range 1024 to 65535\n\n" );
exit(0);
}
// start things up
startup( port );
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
unsigned long int next = 1;
int rand(void)
{
next = next * 1103515245 + 12345;
return ((unsigned int)((next/65536) % 32768));
}
void srand(unsigned int seed)
{
next = seed;
}
int main(int argc, char **argv)
{
int idx = 0;
if (argc == 2)
srand((unsigned int)atoi(argv[1])); // set seed
while (idx < 10)
{
printf("%2dth rand: %u\n", idx + 1, rand());
idx++;
}
return (0);
}
|
C
|
// 习题10-7 十进制转换二进制 (15分)
// 本题要求实现一个函数,将正整数n转换为二进制后输出。
// 函数接口定义:
// void dectobin( int n );
// 函数dectobin应在一行中打印出二进制的n。建议用递归实现。
// 裁判测试程序样例:
// #include <stdio.h>
// void dectobin( int n );
// int main()
// {
// int n;
// scanf("%d", &n);
// dectobin(n);
// return 0;
// }
// /* 你的代码将被嵌在这里 */
// 输入样例:
// 10
// 输出样例:
// 1010
#include <stdio.h>
void dectobin( int n );
int main()
{
int n;
scanf("%d", &n);
dectobin(n);
return 0;
}
/* 你的代码将被嵌在这里 */
void dectobin( int n )
{
// 这个比较好理解
if(n==1)
printf("1");
if(n==0)
printf("0");
if(n>=2) // 大于2时没法直接用二进制表示
{
dectobin(n/2); //调用函数辗转相除每次除2直到n=1或0
printf("%d",n%2); //先除后余求进制位上的数字
}
}
// 这种方法不是很好理解
/*
void dectobin( int n )
{
// n/2是必须的
if(n/2>0)
{
dectobin(n / 2);
}
printf("%d", n % 2); // 一直递归完,这个才开始输出
}
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
typedef struct
{
int data[MAX];
int front, rear;
} queue;
void init(queue *queue)
{
queue->front = queue->rear = -1;
printf("Queue initiallized.\n\n");
}
queue *createQueue(int size)
{
if (size <= 0)
{
printf("Size can't be negative or zero.\n");
}
else
{
queue *queue = malloc(sizeof(size * sizeof(queue)));
queue->front = queue->rear = -1;
printf("\nQueue created of size %d.\n", size);
printf("Queue initiallized.\n\n");
return queue;
}
}
void enqueue(queue *queue, int val)
{
if (queue->rear == MAX - 1)
{
printf("\nQueue overflow.\n\n");
}
else if (queue->front && queue->rear == -1)
{
queue->front = queue->rear = 0;
queue->data[queue->rear] = val;
printf("\n%d enqueued !\n\n", val);
}
else
{
queue->rear++;
queue->data[queue->rear] = val;
printf("\n%d enqueued !\n\n", val);
}
}
int dequeue(queue *queue)
{
int val;
if (queue->front && queue->rear == -1 || queue->front > queue->rear)
{
printf("\nQueue underflow.\n\n");
return 0;
}
else
{
val = queue->data[queue->front];
queue->front++;
printf("\n%d dequeued !\n\n", val);
return val;
}
}
int peek(queue *queue)
{
int val;
if (queue->front && queue->rear == -1 || queue->front > queue->rear)
{
printf("\nQueue underflow.\n\n");
}
else
{
val = queue->data[queue->front];
printf("\nFront value is %d.\n\n", val);
return val;
}
}
void display(queue *queue)
{
printf("\n");
for (int i = queue->front; i <= queue->rear; i++)
{
printf("%d <- ", queue->data[i]);
}
printf("\n\n");
}
void change(queue *queue, int pos, int val)
{
int index = queue->front + pos - 1;
int bef;
if (index >= queue->front && index <= queue->rear)
{
bef = queue->data[index];
queue->data[index] = val;
printf("\nValue changed to %d from %d !\n\n", val,bef);
}
else
{
printf("\nInvalid position.\n\n");
}
}
void main()
{
queue *queue = malloc(sizeof(queue) * MAX);
init(queue);
// queue *queue = createQueue(3);
int en, deq, c, p, pos, val;
while (1)
{
printf("1.Enqueue\n2.Dequeue\n3.Peek\n4.Change\n5.Display\n6.Exit\n");
printf("\nWhich operation you want to perform ? : ");
scanf("%d", &c);
switch (c)
{
case 1:
printf("Enter value : ");
scanf("%d", &en);
enqueue(queue, en);
break;
case 2:
deq = dequeue(queue);
break;
case 3:
p = peek(queue);
break;
case 4:
printf("Enter position : ");
scanf("%d", &pos);
printf("Enter new value : ");
scanf("%d", &val);
change(queue, pos, val);
break;
case 5:
display(queue);
break;
case 6:
printf("\nYour final queue is : \n");
display(queue);
exit(0);
break;
default:
printf("\nInvalid entry !\n\n");
break;
}
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
/* Define a generic type that allows us to store any value inside the
hashtable */
typedef void *any_t;
typedef any_t map_t
/* Define a bucket */
/*
key: Hashing key
data: Value associated with the key
in_use: Whether the bucket is in use or not
*/
typedef struct _hashmap_elem{
int key;
any_t data;
int in_use
} hashmap_elem ;
/*Define Hashmap*/
/*
max_size: Maximum size of the hash table,
size: Current size of the hash table,
the data in the hash table
*/
typedef struct _hashmap_map{
int max_size;
int size;
hashmap_elem *data
} hashmap_map
map_t hashmap_new() {
hashmap_map* m = (hashmap_map*) malloc(sizeof(hashmap_map));
if (!m) goto error;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* uint.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sluetzen <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/24 15:31:06 by sluetzen #+# #+# */
/* Updated: 2019/07/06 14:46:17 by sluetzen ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "ft_printf.h"
int uint_precision(uintmax_t number, int fd, t_flags *flags)
{
int len;
len = 0;
if (!(MIN_FLAG))
len += pad_uint_prec(number, flags, fd);
else
len += pad_uint_prec(number, flags, fd);
return (len);
}
int uint_no_precision(uintmax_t number, int fd, t_flags *flags)
{
int len;
len = 0;
if (!(MIN_FLAG))
{
len += pad_uint(number, flags, fd);
ft_uitoa_base(number, 10, fd);
}
else
{
ft_uitoa_base(number, 10, fd);
len += pad_uint(number, flags, fd);
}
return (len);
}
int special_zero_u(int fd, t_flags *flags)
{
int len;
len = flags->field_width - (PLUS_FLAG || SPACE_FLAG ? 1 : 0);
if (len < 0)
len = 0;
if (((PLUS_FLAG) || (SPACE_FLAG)) && (MIN_FLAG))
{
if (PLUS_FLAG)
ft_putchar_fd('+', fd);
else if (SPACE_FLAG)
ft_putchar_fd(' ', fd);
}
pad_space(len, fd);
if (((PLUS_FLAG) || (SPACE_FLAG)) && !(MIN_FLAG))
{
if (PLUS_FLAG)
ft_putchar_fd('+', fd);
else if (SPACE_FLAG)
ft_putchar_fd(' ', fd);
len++;
}
if (((PLUS_FLAG) || (SPACE_FLAG)) && (MIN_FLAG))
len++;
return (len);
}
int special_convert_uint(uintmax_t number, int fd, t_flags *flags)
{
int full_len;
full_len = 0;
if (((PREC_FLAG) && flags->precision == 0) && number == 0)
return (special_zero_u(fd, flags));
else if (flags->precision || (PREC_FLAG))
full_len += uint_precision(number, fd, flags);
else
full_len += uint_no_precision(number, fd, flags);
return (full_len + ft_unbrlen(number));
}
int convert_uint(va_list args, int fd, t_flags *flags)
{
uintmax_t number;
if (HH_FLAG)
number = (unsigned char)va_arg(args, unsigned int);
else if (H_FLAG)
number = (unsigned short)va_arg(args, unsigned int);
else if (L_FLAG)
number = (unsigned long)va_arg(args, unsigned long);
else if (LL_FLAG)
number = (unsigned long long)va_arg(args, unsigned long long);
else
number = va_arg(args, unsigned int);
if (is_activated(flags) || PREC_FLAG)
return (special_convert_uint(number, fd, flags));
else
{
ft_uitoa_base(number, 10, fd);
}
return (ft_unbrlen(number));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sel1 = 0, i;
float s1, s2, s3, s4, s5;
while (sel1 != 3)
{
printf("f(x):ax^2+bx+c (1)\ng(x):ax^3+bx^2+cx+d (2)\nexit (3)\npls u select: ");
scanf("%d", &sel1);
switch (sel1)
{
case 1:
printf("pls u enter 'a' :");
scanf("%f", &s1);
printf("pls u enter 'b' :");
scanf("%f", &s2);
printf("pls u enter 'c' :");
scanf("%f", &s4);
printf("pls u enter 'x' :");
scanf("%f", &s3);
printf("u need this: %.3f\n", s1 * s3 * s3 + s2 * s3 + s4);
break;
case 2:
printf("pls u enter 'a' :");
scanf("%f", &s1);
printf("pls u enter 'b' :");
scanf("%f", &s2);
printf("pls u enter 'c' :");
scanf("%f", &s4);
printf("pls u enter 'd' :");
scanf("%f", &s5);
printf("pls u enter 'x' :");
scanf("%f", &s3);
printf("u need this: %.3f\n", (float)s1 * s3 * s3 * s3 + s2 * s3 * s3 + s4 * s3 + s5);
break;
case 3:
break;
default:
printf("pls try again");
break;
}
}
system("pause");
return (0);
}
|
C
|
/*
* Pydroponics
* CMPE129
* Collaborators
* [email protected]
* [email protected]
*
* File: sysSolenoid.c
* Author: Daniel Gunny
* Created: 05/14/13 8:31
*
*/
#include "GlobalGeneralDefines.h"
#include "sysSolenoid.h"
#include <avr/io.h>
#include <stdlib.h>
#include <util/delay.h>
/*******************************************************************************
* PRIVATE VARIABLES *
******************************************************************************/
unsigned int time;
unsigned int counter;
/*******************************************************************************
* PUBLIC FUNCTIONS *
******************************************************************************/
/****************************************************************************
Function:
sysSolenoidSetup
Parameters:
None.
Returns:
None.
Description:
Sets up all four solenoids.
Notes:
Uses pins 31, 33, 35, & 37
Sets output pins low
pH up solenoid = pin 31 = PC6
pH down solenoid = pin 33 = PC4
tds up solenoid = pin 35 = PC2
tds down solenoid = pin 37 = PC0
Authors:
Danny Gunny, 5/14/2013
****************************************************************************/
void sysSolenoidSetup(void) {
DDRC |= _BV(PC6) | _BV(PC4) | _BV(PC2) | _BV(PC0);
PORTC &= ~(_BV(PC6) | _BV(PC4) | _BV(PC2) | _BV(PC0));
}
/****************************************************************************
Function:
phUp
Parameters:
char* duration
Returns:
None.
Description:
Turns on pH Up solenoid for duration ms.
Notes:
None.
Authors:
Danny Gunny, 5/17/2013
****************************************************************************/
void phUp(char* duration) {
time = atoi(duration);
PORTC |= _BV(PC4);
for(counter = 0; counter < time; counter++) {
_delay_ms(1);
}
PORTC &= ~_BV(PC4);
}
/****************************************************************************
Function:
phDown
Parameters:
char* duration
Returns:
None.
Description:
Turns on pH Down solenoid for duration ms.
Notes:
None.
Authors:
Danny Gunny, 5/17/2013
****************************************************************************/
void phDown(char* duration) {
time = atoi(duration);
PORTC |= _BV(PC6);
for(counter = 0; counter < time; counter++) {
_delay_ms(1);
}
PORTC &= ~_BV(PC6);
}
/****************************************************************************
Function:
tdsUp
Parameters:
char* duration
Returns:
None.
Description:
Turns on tds Up solenoid for duration ms.
Notes:
None.
Authors:
Danny Gunny, 5/17/2013
****************************************************************************/
void tdsUp(char* duration) {
time = atoi(duration);
PORTC |= _BV(PC0);
for(counter = 0; counter < time; counter++) {
_delay_ms(1);
}
PORTC &= ~_BV(PC0);
}
/****************************************************************************
Function:
tdsDown
Parameters:
char* duration
Returns:
None.
Description:
Turns on tds Down solenoid for duration ms.
Notes:
None.
Authors:
Danny Gunny, 5/17/2013
****************************************************************************/
void tdsDown(char* duration) {
time = atoi(duration);
PORTC |= _BV(PC2);
for(counter = 0; counter < time; counter++) {
_delay_ms(1);
}
PORTC &= ~_BV(PC2);
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
long x=31, p=5209; // parameters for the hashing function
char *leftOver; // leftover charcters out of a name when reading from file
int leftOverSize = 0; // number of leftover characters
/* struct defines the element of a list from the hash table
* it holds its value (the name) and pointers to both
* the element after and before it. */
struct element
{
char *value;
struct element *next, *before;
};
/* struct defines the list from one slot of the hash table
* it hold its own address so it can be freed when done
* it holds pointers to the current element and the beginning of the list */
struct list
{
struct list *address;
struct element *current, *begin;
};
/* struct defining the hash table as an array of list elements */
struct table
{
struct list *array;
};
struct table *myTable; // pointer to the hash table which we will use
/* Function creates a new list by dyamically allocating memory
* @return pointer to the created list */
struct list *makeList(){
struct list *newList;
struct element *begin;
// dynamically allocate memory for both the list and its beginning element
newList = (struct list*)malloc(sizeof(struct list));
begin = (struct element*)malloc(sizeof(struct element));
if(newList == NULL || begin == NULL){
printf("Allocation of memory for the list failed\n");
return NULL;
}
// link the only element so far to both NULL pointers before and after it
begin->next = NULL;
begin->before = NULL;
begin->value = NULL; // default value
newList->begin = begin;
// keep track of the allocated address so it can be freed when done
newList->address = newList;
return newList;
}
/* Function creates the table by dynamically allocating memory for it.
* The table can use p slots max. The array is also initialized here. */
void createTable(){
myTable = (struct table*)malloc(sizeof(struct table));
myTable->array = (struct list*)malloc(p * sizeof(struct list));
if(myTable == NULL){
printf("Memory allocation for the table failed\n");
}
}
/* Function initializes the table by creating a list for
* each index of the array. */
void initializeTable(){
for(int index = 0; index < p; index++){
(*myTable).array[index] = *makeList();
}
}
/* Function returns the hash value of a character array.
* Using polinomyal hashing function.
* p - prime number
* @param name[] - array for which the hash value is generated;
* @return value - integer representing the hash value for the table. */
int hash(char name[]){
long index = 0, power = 1, value = 0;
while(name[index] != '\0'){
value += name[index] * power % p;
power *= x;
index++;
}
value%=p;
return value;
}
/* Funtion compares two characters arrays.
* @param name1, name2 - char arrays to be compared
* @return true if name1 = name2
* false otherwise*/
bool isEqual(char name1[], char name2[]){
int aux = 0;
// iterate through each letter and compare
while(*(name1 + aux) != '\0'){
if(*(name1 + aux) != *(name2 + aux)) return false;
if(*(name2 + aux) == '\0') return false;
aux++;
}
// check if name2 = name1 or name2 = name1 + some other characters
if(*(name2 + aux) != '\0') return false;
return true;
}
/* Function checks if a name is in the table or not.
@return true if the name exists
false otherwise */
bool search(char name[]){
int index = hash(name);
struct list target = (*myTable).array[index];
target.current = target.begin -> next;
// look for the name by comparing the values of the elements in the list
while(target.current != NULL){
if(isEqual(target.current->value, name)){
return true;
}
target.current = target.current->next;
}
return false;
}
/* Function adds a new name to the hash table. */
void add(char name[]){
// check that the name is not a duplicate
if(search(name)){
printf("The name already exists.\n");
return;
}
int index = hash(name);
struct list target = (*myTable).array[index];
// allocate memory for a new element and for the value of that element
struct element *newName = (struct element*)malloc(sizeof(struct element));
newName->value = (char*)malloc(sizeof(char));
if(newName == NULL || newName->value == NULL){
printf("Memory allocation for a new element failed\n");
return;
}
// navigate until the last element and add the new one
target.current = target.begin;
while(target.current -> next != NULL){
target.current = target.current->next;
}
// assign characters to the value of the element
int aux = 0;
while(*(name + aux) != '\0'){
*(newName->value + aux) = *(name + aux);
aux++;
}
// update the links between the elements
*(newName->value + aux) = '\0';
target.current->next = newName;
newName->before = target.current;
newName->next = NULL;
}
/* Function removes an element from the table. */
void myRemove(char name[]){
// check that the name exists
if(!search(name)){
printf("The name could not be found.\n");
return;
}
int index = hash(name);
struct list target = (*myTable).array[index];
// navigate to find the element
target.current = target.begin -> next;
while(target.current != NULL){
/* if found update the links between the
* elements and free the allocated memory */
if(isEqual(target.current->value, name)){
target.current->before->next = target.current->next;
// check if the found element is the last one in the list or not
if(target.current->next != NULL){
target.current->next->before = target.current->before;
}
struct element *tobeRemoved = target.current;
target.current = target.current->before;
free(tobeRemoved);
break;
}
target.current = target.current->next;
}
}
/* Function frees all alocated memory, in order:
* elements from lists, lists, the array and the table */
void freeAll(){
for(int index = 0; index < p; index++){
struct list tobeFreed = myTable->array[index];
tobeFreed.current = tobeFreed.begin -> next;
while(tobeFreed.current != NULL){
struct element *toFree = tobeFreed.current;
tobeFreed.current = tobeFreed.current->next;
//free(toFree->value); // free the value
free(toFree); // free each element
}
free(tobeFreed.begin); // free the first element
// find the address of the list
struct list *pList = (*myTable).array[index].address;
free(pList);
}
// free the array and the table
free(myTable->array);
free(myTable);
}
/* Function gets passed a char array (read characters from the buffer)
* and creates the names and adds them to the table. */
void addNames(char buffer[]){
char *name; // holds the characters from one name at a time
int nameLength = 0; // length of name
int beginningIndex; // index of first letter from name in buffer
int index = 0;
bool nameStarted = false; // keeps track if we are creating a name or not
while(buffer[index] != '\0'){
int asciiValue = buffer[index];
// if character is letter
if((asciiValue <= 90 && asciiValue >= 65) ||
(asciiValue >= 97 && asciiValue <= 122)){
nameLength++;
if(!nameStarted){
nameStarted = true;
beginningIndex = index;
}
}
else if (nameStarted){
// we have reached the end of a name and we are ready to add it
name = (char*)malloc(nameLength * sizeof(char));
if(name == NULL){
printf("Name memory allocation failed\n");
return;
}
for(int aux=0; aux<nameLength; aux++){
*(name + aux) = buffer[beginningIndex + aux];
}
// check to see if there are leftOver characters from the previous buffer
if(leftOverSize != 0){
char *newName = (char*)malloc((leftOverSize+nameLength) * sizeof(char));
if(newName == NULL){
printf("Name memory allocation failed\n");
return;
}
for(int aux=0; aux<leftOverSize;aux++){
*(newName+aux) = *(leftOver + aux);
}
for(int aux = 0; aux < nameLength; aux++){
*(newName+leftOverSize+aux) = *(name + aux);
}
add(newName);
// free all allocated memory here
newName = NULL;
name = NULL;
leftOver = NULL;
/* can free both name and newName since
* add function allocates memory for element->value */
free(newName);
free(name);
free(leftOver);
nameLength = 0;
nameStarted = false;
leftOverSize = 0;
}
else{
// there are no leftover characters
add(name);
name = NULL;
free(name);
nameLength = 0;
nameStarted = false;
}
}
index++;
}
/* we reached the end of the buffered but we are in the process of
* creating a new name. */
if(nameStarted){
// keep the left over characters in memory until the next buffer
leftOver = (char*)malloc(nameLength * sizeof(char));
for(int aux=0; aux<nameLength; aux++){
*(leftOver + aux) = buffer[beginningIndex + aux];
}
leftOverSize = nameLength;
}
}
/* Function opens the names.txt file and reads the names byte by byte.*/
void readFile(){
FILE *filein = fopen("names.txt", "r");
if(filein == NULL){
printf("Failed to open the file.\n");
return;
}
char *buf;
int nread = 1;
do{
if(nread == 0){
break;
}
buf = (char *)malloc(1024);
nread = fread(buf, sizeof(char), 1024, filein);
addNames(buf);
buf = NULL;
free(buf);
}while(nread > 0);
fclose(filein);
}
/* Function provides options for the user to add, search and remove
* names from the table. */
void menu(){
int option;
void (*fun_arr[])(char*) = {add, myRemove};
do{
printf("Input 1 to add a name, 2 to remove a name, 3 to search a");
printf(" name and 0 to exit: ");
scanf("%d", &option);
if(option == 0) break;
printf("Input the name: ");
char *name = (char*)malloc(sizeof(char));
scanf("%s", name);
if(option == 3){
if(search(name)) printf("%s is in the table\n", name);
else printf("%s is not in the table\n", name);
}
else{
fun_arr[option-1](name);
}
free(name);
} while(option != 0);
freeAll();
}
/* Main function */
int main(void){
createTable();
initializeTable();
readFile();
menu();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* Just putting the basic algorithm here. This uses BFS. Since all words at a certain level are checked in BFS mode, the first time the word is hit, the shortest length is also found there. */
int
word_ladder (start, end, dictionary) {
while (q not empty) {
Queue.add {start, 1}
curr = Queue.pop;
for words in dictionary {
if (isAdjacent(word, curr.word)) {
Queue.add {word, curr.len + 1}
if (word == end) {
return curr.len+1;
}
dictionary.remove (word);
}
}
}
return -1;
}
|
C
|
#include "stm32f10x.h"
#include "EIE3810_KEY.h"
void EIE3810_Key_Init(void){
//Enable PE clock
RCC->APB2ENR |=1<<6;
//Enable PA clock
RCC->APB2ENR |=1<<2;
//Configure button PE2
GPIOE->CRL &=0xFFFFF0FF;// (4-bit a register, starting from register 0) Clear up
GPIOE->CRL |=0x00000800;//Set register PE2's mode as input (xx00) pull-up/pull-down (10xx)
//Configure button PE3
GPIOE->CRL &=0xFFFF0FFF;
GPIOE->CRL |=0x00008000;
//Configure button PE4
GPIOE->CRL &=0xFFF0FFFF;
GPIOE->CRL |=0x00080000;
//Configure button PA0
GPIOA->CRL &=0xFFFFFFF0;
GPIOA->CRL |=0x00000008;
//Set both PE2, PE3 and PE4 as pull-up
GPIOE ->ODR = 0x0000001C;
//Set PA0 as pull-down
GPIOA ->ODR = 0x00000000;
}
|
C
|
int power(int a,int b){
int ans = 1;
int i;
for(i=1;i<b;i++){
ans *= a;
}
return ans;
}
|
C
|
#include <stdio.h>
/* MMU Level 1 Page Table Constants */
#define MMU_FULL_ACCESS (3 << 10)
#define MMU_DOMAIN (0 << 5)
#define MMU_SPECIAL (0 << 4)
#define MMU_CACHEABLE (1 << 3)
#define MMU_BUFFERABLE (1 << 2)
#define MMU_SECTION (2)
#define MMU_SECDESC (MMU_FULL_ACCESS | MMU_DOMAIN | \
MMU_SPECIAL | MMU_SECTION)
#define SZ_1M 0x00100000
#define SZ_32M 0x02000000
#define DRAM_BASE0 0xC0000000
#define DRAM_SIZE0 SZ_32M
#define UNCACHED_FLASH_BASE 0x50000000
#define FLASH_BASE 0x00000000
main() {
unsigned long int pageoffset;
int i;
i = 0;
printf("\ncached_flash_addr\n");
for (pageoffset = 0; pageoffset < SZ_32M; pageoffset += SZ_1M) {
unsigned long cached_flash_addr = FLASH_BASE + pageoffset;
unsigned long uncached_flash_addr = UNCACHED_FLASH_BASE + pageoffset;
if (cached_flash_addr != FLASH_BASE) {
if ((i % 8) == 0)
printf("\n%08lx: ", (cached_flash_addr >> 20));
printf("%08lx ", cached_flash_addr | MMU_SECDESC | MMU_CACHEABLE);
i++;
}
}
printf("\n");
i = 0;
printf("\nuncached_flash_addr\n");
for (pageoffset = 0; pageoffset < SZ_32M; pageoffset += SZ_1M) {
unsigned long cached_flash_addr = FLASH_BASE + pageoffset;
unsigned long uncached_flash_addr = UNCACHED_FLASH_BASE + pageoffset;
if ((i % 8) == 0)
printf("\n%08lx: ", (uncached_flash_addr >> 20));
printf("%08lx ", cached_flash_addr | MMU_SECDESC | MMU_CACHEABLE);
i++;
}
printf("\n");
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
/*
Flexible array member (struct hack in GCC)
*/
struct flex
{
size_t count;
double average;
double values[]; // flexible array member (last member!)
};
const size_t n = 3;
struct flex* pf = (struct flex*)malloc(sizeof(struct flex) + n * sizeof(double));
if (pf == NULL) exit(1);
printf("\nFlexible array member\n");
printf("Sizeof struct flex %zd\n", sizeof(struct flex));
printf("Sizeof *pf %zd\n", sizeof(*pf));
printf("Sizeof malloc %zd\n", sizeof(struct flex) + n * sizeof(double));
printf("%lld\n", (long long)pf);
printf("%lld\n", (long long)&pf->count);
printf("%zd\n", sizeof(pf->count));
printf("%lld\n", (long long)&pf->average);
printf("Address of pf->values %lld\n", (long long)&pf->values);
printf("Value of pf->values %lld\n", (long long)pf->values);
printf("Sizeof pf->values %zd\n", sizeof(pf->values));
pf->count = n;
pf->values[0] = 1.1;
pf->values[1] = 2.1;
pf->values[2] = 3.1;
pf->average = 0.0;
for (unsigned i = 0; i < pf->count; ++i)
pf->average += pf->values[i];
pf->average /= (double)pf->count;
printf("Average = %f\n", pf->average);
/*
struct nonflex
{
size_t count;
double average;
double *values; // Use malloc()
};
struct nonflex nf;
nf.value = (double*)malloc(sizeof(double) *n);
*/
/*
struct flex* pf2 = (struct flex*)malloc(sizeof(struct flex) + n * sizeof(double));
if (pf2 == NULL) exit(1);
*pf2 = *pf1; // Don't copy flexible members, use memcpy() instead
free(pf);
free(pf2);
*/
return 0;
}
|
C
|
#include "matrix.h"
matrix *transpose2(matrix * in);
matrix *sum2(matrix * mtx1, matrix * mtx2);
matrix *product2(matrix * mtx1, matrix * mtx2);
double dotProduct2(matrix * v1, matrix * v2);
matrix *identity2(int order);
double getElement2(matrix * mtx, int row, int col);
matrix *subtraction2(matrix *A, matrix *B);
matrix *division2(matrix *A, matrix *B);
matrix *sumByScalar2(matrix *A, double x);
matrix *subtractionByScalar2(matrix *A, double x);
matrix *productByScalar2(matrix *A, double x);
matrix *divisionByScalar2(matrix *A, double x);
matrix *getUpperTriangular2(matrix *A, int k);
matrix *getLowerTriangular2(matrix *A, int k);
int matrixSwapLines2(matrix *A, int x, int y);
matrix *menorPrincipal2(matrix *A, int n);
matrix *matrixAbs2(matrix *A);
matrix *subMatrix2(matrix *A, int startRow, int endRow, int startCol, int endCol);
matrix *diagonalToVector2(matrix *A);
int main() {
matrix *A, *B, *x, *b, *c, *d;
int n = 4;
A = newMatrix(n, n);
B = newMatrix(n, n);
x = newMatrix(n, 1);
b = newMatrix(n, 1);
c = newMatrix(n, 1);
d = newMatrix(1, n);
setElement(A, 1, 1, 1);
setElement(A, 1, 2, 2);
setElement(A, 1, 3, -1);
setElement(A, 1, 4, 0);
setElement(A, 2, 1, 0);
setElement(A, 2, 2, -1);
setElement(A, 2, 3, 1);
setElement(A, 2, 4, -1);
setElement(A, 3, 1, -2);
setElement(A, 3, 2, -1);
setElement(A, 3, 3, 4);
setElement(A, 3, 4, 2);
setElement(A, 4, 1, 4);
setElement(A, 4, 2, 3);
setElement(A, 4, 3, 0);
setElement(A, 4, 4, 1);
setElement(B, 1, 1, 1);
setElement(B, 1, 2, 2);
setElement(B, 1, 3, -1);
setElement(B, 1, 4, 0);
setElement(B, 2, 1, 0);
setElement(B, 2, 2, -1);
setElement(B, 2, 3, 1);
setElement(B, 2, 4, -5);
setElement(B, 3, 1, -4);
setElement(B, 3, 2, -5);
setElement(B, 3, 3, 6);
setElement(B, 3, 4, 7);
setElement(B, 4, 1, 8);
setElement(B, 4, 2, 9);
setElement(B, 4, 3, 10);
setElement(B, 4, 4, 21);
setElement(b, 1, 1, -4);
setElement(b, 2, 1, 0);
setElement(b, 3, 1, 7);
setElement(b, 4, 1, -10);
setElement(c, 1, 1, -4);
setElement(c, 2, 1, 0);
setElement(c, 3, 1, 7);
setElement(c, 4, 1, -10);
setElement(d, 1, 1, -4);
setElement(d, 1, 2, 0);
setElement(d, 1, 3, 7);
setElement(d, 1, 4, -10);
printMatrix2(A, "A");
// matrix **At;
// At = transpose2(A);
printMatrix2(transpose2(A), "At");
printMatrix2(sum2(b, c), "sum(b, c)");
printMatrix2(c, "c");
printMatrix2(d, "d");
printMatrix2(product2(c, d), "product2(c, d)");
printf("\ndotProduct(b, c) = %f\n", dotProduct2(b, c));
printMatrix2(identity2(5), "identity2(5)");
printf("\ngetElement2(A, 4, 2) = %f\n", getElement2(A, 4, 2));
double A_31 = getElement2(A, 3, 1);
printf("\ngetElement2(A, 3, 1) = %f\n", A_31);
printMatrix2(subtraction2(A, B), "subtraction2(A, B)");
printMatrix2(division2(A, B), "division2(A, B)");
printMatrix2(sumByScalar2(A, 10), "sumByScalar2(A, 10)");
printMatrix2(A, "A");
printMatrix2(getUpperTriangular2(A, 0), "getUpperTriangular2(A, 0)");
printMatrix2(getUpperTriangular2(A, 1), "getUpperTriangular2(A, 1)");
printMatrix2(getUpperTriangular2(A, -1), "getUpperTriangular2(A, -1)");
printMatrix2(getLowerTriangular2(A, 0), "getLowerTriangular2(A, 0)");
printMatrix2(getLowerTriangular2(A, 1), "getLowerTriangular2(A, 1)");
printMatrix2(getLowerTriangular2(A, -1), "getLowerTriangular2(A, -1)");
printMatrix2(A, "A");
matrixSwapLines2(A, 2, 3);
printMatrix2(A, "matrixSwapLines2(A, 2, 3)");
printMatrix2(menorPrincipal2(A, 1), "menorPrincipal2(A, 1)");
printMatrix2(menorPrincipal2(A, 2), "menorPrincipal2(A, 2)");
printMatrix2(menorPrincipal2(A, 3), "menorPrincipal2(A, 3)");
printMatrix2(menorPrincipal2(A, 4), "menorPrincipal2(A, 4)");
printf("Norma 2 de norma(menorPrincipal2(A, 4), 2): %f\n", norma(menorPrincipal2(A, 4), 2));
printMatrix2(A, "A");
printMatrix2(matrixAbs2(A), "matrixAbs2(A)");
printMatrix2(matrixRowToVector(A, 2), "matrixRowToVector(A, 2)");
printMatrix2(matrixColToVector(A, 3), "matrixColToVector(A, 3)");
printMatrix2(A, "A");
printMatrix2(subMatrix2(A, 2, 4, 2, 3), "subMatrix2(A, 2, 4, 2, 3)");
printMatrix2(diagonalToVector2(A), "diagonalToVector2(A)");
}
|
C
|
/**
* @file hw07.c
* @brief 십진수 -> 이진수
*/
#include <stdio.h>
#include <stdlib.h>
int get_user_input(void);
int * convert_10_to_2(int input);
void convert_10_to_2_test(int input, int * expected);
void convert_10_to_2_tests(void);
void print_result(int input, int * binary);
int get_digits_needed(int input);
void get_digits_needed_test(int input, int expected);
void get_digits_needed_tests(void);
int main() {
get_digits_needed_tests();
convert_10_to_2_tests();
int user_input = get_user_input();
print_result(user_input, convert_10_to_2(user_input));
return 0;
}
int get_user_input(void) {
int user_input = 0;
printf("enter a integer(10) : ");
scanf("%d", &user_input);
return user_input;
}
int * convert_10_to_2(int input) {
int size = get_digits_needed(input);
int * binary = (int *) malloc ( sizeof(int) * size );
for ( int i = size-1 ; i >= 0 ; i-- ) {
binary[i] = input%2;
input /= 2;
}
return binary;
}
/**
* @fn int get_digits_needed(int input)
* @details
* - 2진수를 표현하기 위해서 필요한 자리수를 리턴한다.
* - 예를 들어서, 8(1000) = 4를 리턴한다.
* - 예를 들어서, 18(10010) = 5를 리턴한다.
*/
int get_digits_needed(int input) {
int size = 1;
while ( input /= 2 ) {
size++;
}
return size;
}
void get_digits_needed_test(int input, int expected) {
printf("[%s] get_digits_needed(%d) should be [%d], and result is [%d]\n",
(get_digits_needed(input) == expected) ? "Success" : "Failed",
input, expected, get_digits_needed(input));
}
void get_digits_needed_tests(void) {
get_digits_needed_test(1, 1);
get_digits_needed_test(8, 4);
get_digits_needed_test(19, 5);
}
void print_result(int input, int * binary) {
int size = get_digits_needed(input);
for ( int i = 0 ; i < size ; i++ ) { printf("%d", binary[i]); }
}
void convert_10_to_2_test(int input, int * expected) {
int size = get_digits_needed(input);
int * binary = convert_10_to_2(input);
int is_valid = 1; // default : true(1)
for ( int i = 0 ; i < size ; i++ ) {
if ( binary[i] != expected[i] ) is_valid = 0;
}
free(binary);
// pretty result form
printf("[%s] ", (is_valid) ? "Success" : "Failed");
printf("%d(10) should be ", input);
print_result(input, expected);
printf("(2)\n");
}
void convert_10_to_2_tests(void) {
int foo[1] = {1}; // 1(10) = 1(2)
convert_10_to_2_test(1, foo);
int bar[4] = {1, 0, 0, 0}; // 8(10) = 1000(2)
convert_10_to_2_test(8, bar);
int baz[5] = {1, 0, 0, 1, 1}; // 19(10) = 10011(2)
convert_10_to_2_test(19, baz);
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int letterCount(string text);
int wordCount(string text);
int sentenceCount(string text);
int colemanLiau(float letters, float words, float sentences);
int main(void) {
string text = get_string("Text: ");
int letters = letterCount(text);
int words = wordCount(text);
int sentences = sentenceCount(text);
int index = colemanLiau(letters, words, sentences);
if(index < 1) {
printf("Before Grade 1\n");
} else if (index >= 16 ) {
printf("Grade 16+\n");
} else {
printf("Grade %i\n", index);
}
}
int letterCount(string text) {
int letterCount = 0;
int length = strlen(text);
for (int i = 0; i < length; i++) {
if(isalpha(text[i])) {
letterCount++;
}
}
return letterCount;
}
int wordCount(string text) {
int wordCount = 1;
int length = strlen(text);
for (int i = 0; i < length; i++) {
if(text[i] == ' ') {
wordCount++;
}
}
return wordCount;
}
int sentenceCount(string text) {
int sentenceCount = 0;
int length = strlen(text);
for (int i = 0; i < length; i++) {
switch(text[i]) {
case '.' :
sentenceCount++;
break;
case '!':
sentenceCount++;
break;
case '?':
sentenceCount++;
break;
}
}
return sentenceCount;
}
int colemanLiau(float letters, float words, float sentences) {
float numLetters100Words = (letters / words) * 100;
float numSentences100Words = (sentences / words) * 100;
float index = round((0.0588 * numLetters100Words) - (0.296 * numSentences100Words) - 15.8);
return index;
}
|
C
|
#include <stdio.h>
void str_cpy(char * dest, char * orig)
{
int i = 0;
while((dest[i] = orig[i]) != '\0')
i++;
}
int main()
{
char dest[10];
char orig[] = "elizabeth";
str_cpy(dest, orig);
printf("%s\n", dest);
return 0;
}
|
C
|
typedef struct
{
Int x;
Int y;
}
IntPoint;
typedef struct
{
UInt x;
UInt y;
}
UIntPoint;
STRUCT_NUBLE_TEMPLATE(IntPoint)
STRUCT_NUBLE_TEMPLATE(UIntPoint)
STRUCT_LIST_INTERFACE_TEMPLATE(IntPoint)
STRUCT_LIST_INTERFACE_TEMPLATE(UIntPoint)
NS_INLINE IntPoint IntPoint_create(Int x, Int y) { IntPoint result = { x, y }; return result; }
NS_INLINE UIntPoint UIntPoint_create(UInt x, UInt y) { UIntPoint result = { x, y }; return result; }
NS_INLINE NubleIntPoint IntPoint_createAsNuble(Int x, Int y) { return IntPoint_toNuble(IntPoint_create(x, y)); }
NS_INLINE NubleUIntPoint UIntPoint_createAsNuble(UInt x, UInt y) { return UIntPoint_toNuble(UIntPoint_create(x, y)); }
NS_INLINE void IntPoint_assert(IntPoint self, Int x, Int y) { ASSERT(self.x == x && self.y == y); }
NS_INLINE void UIntPoint_assert(UIntPoint self, UInt x, UInt y) { ASSERT(self.x == x && self.y == y); }
|
C
|
#include "header.h"
/*********************************************************************
expand_subtree expands the subtree pointed to by n into sum of
products form, and returns a pointer to the resulting subtree.
Note that the base and exponent subtrees of a POWER node will
not be expanded into sum of products form, which is fine since
they can't contain variables anyway, so they can't cause any
nonlinearity.
**********************************************************************/
struct node *expand_subtree(n)
struct node *n;
{
struct node *sumnode1;
struct node *sumnode2;
struct node *sumnode3;
struct node *prodnode1;
struct node *prodnode2;
struct node *prodnode3;
struct node *prodnode4;
struct node *left;
struct node *right;
switch (n->type) {
case CONSTANT: case COEFFICIENT: case VARIABLE:
return n;
break;
case SUM:
n->info.sum.summand1 = expand_subtree(n->info.sum.summand1);
n->info.sum.summand2 = expand_subtree(n->info.sum.summand2);
return n;
break;
case PRODUCT:
n->info.prod.multiplicand1 = expand_subtree(n->info.prod.multiplicand1);
n->info.prod.multiplicand2 = expand_subtree(n->info.prod.multiplicand2);
left = n->info.prod.multiplicand1;
right = n->info.prod.multiplicand2;
if ((left->type == SUM) && (right->type != SUM))
{
prodnode1 = create_product_node(left->info.sum.summand1, right);
prodnode2 = create_product_node(left->info.sum.summand2,
copy_subtree(right));
prodnode1 = expand_subtree(prodnode1);
prodnode2 = expand_subtree(prodnode2);
sumnode1 = create_sum_node(prodnode1, prodnode2);
free(left);
free(n);
return sumnode1;
}
else if ((left->type != SUM) && (right->type == SUM))
{
prodnode1 = create_product_node(left, right->info.sum.summand1);
prodnode2 = create_product_node(copy_subtree(left),
right->info.sum.summand2);
prodnode1 = expand_subtree(prodnode1);
prodnode2 = expand_subtree(prodnode2);
sumnode1 = create_sum_node(prodnode1, prodnode2);
free(right);
free(n);
return sumnode1;
}
else if ((left->type == SUM) && (right->type == SUM))
{
prodnode1 = create_product_node(left->info.sum.summand1,
right->info.sum.summand1);
prodnode2 =
create_product_node(copy_subtree(left->info.sum.summand1),
right->info.sum.summand2);
prodnode3 =
create_product_node(left->info.sum.summand2,
copy_subtree(right->info.sum.summand1));
prodnode4 =
create_product_node(copy_subtree(left->info.sum.summand2),
copy_subtree(right->info.sum.summand2));
sumnode1 = create_sum_node(prodnode1, prodnode2);
sumnode2 = create_sum_node(prodnode3, prodnode4);
sumnode1 = expand_subtree(sumnode1);
sumnode2 = expand_subtree(sumnode2);
sumnode3 = create_sum_node(sumnode1, sumnode2);
free(left);
free(right);
free(n);
return sumnode3;
}
else /* neither *left nor *right is a SUM node */
{
n->info.prod.multiplicand1 =
expand_subtree(n->info.prod.multiplicand1);
n->info.prod.multiplicand2 =
expand_subtree(n->info.prod.multiplicand2);
return n;
}
break;
case POWER:
return n;
break;
default:
fprintf(stderr, "In expand_subtree:");
error(INVALID_NODE_TYPE);
return NULL;
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sql.h>
#include <sqlext.h>
#include "odbc.h"
int main(int argc, char** argv){
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret; /* ODBC API return status */
char consulta[300];
FILE* pf;
int id_usuario, id_venta;
char p_ini[300],p_fin[300],fecha[300];
/* CONNECT */
ret = odbc_connect(&env, &dbc);
if (!SQL_SUCCEEDED(ret)) {
return EXIT_FAILURE;
}
/* Allocate a statement handle */
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
if(argc<3){
printf("ERROR EN LOS ARGUMENTOS\n");
printf("llena_ventas fichero de entrada\n");
/* DISCONNECT */
ret = odbc_disconnect(env, dbc);
if (!SQL_SUCCEEDED(ret)) {
return EXIT_FAILURE;
}
return EXIT_FAILURE;
}
pf=fopen(argv[2],"r");
if(!pf){
printf("ERROR EN LA LECTURA DEL FICHERO\n");
/* DISCONNECT */
ret = odbc_disconnect(env, dbc);
if (!SQL_SUCCEEDED(ret)) {
return EXIT_FAILURE;
}
return EXIT_FAILURE;
}
while(!feof(pf)){
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
fscanf(pf,"%d %s %s %d %s",&id_usuario,p_ini,p_fin,&id_venta,fecha);
sprintf(consulta,"INSERT INTO venta VALUES ('%d','%s','%s','%d','%s')",id_usuario,p_ini,p_fin,id_venta,fecha);
ret = SQLExecDirect(stmt, (SQLCHAR*) consulta, SQL_NTS);
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
if (!SQL_SUCCEEDED(ret)) {
fclose(pf);
/* DISCONNECT */
ret = odbc_disconnect(env, dbc);
if (!SQL_SUCCEEDED(ret)) {
return EXIT_FAILURE;
}
return EXIT_FAILURE;
}
}
/* DISCONNECT */
ret = odbc_disconnect(env, dbc);
if (!SQL_SUCCEEDED(ret)) {
fclose(pf);
return EXIT_FAILURE;
}
fclose(pf);
return EXIT_SUCCESS;
}
|
C
|
// This is a C program that compares strings
#include <stdio.h>
#include <string.h>
int main()
{
char a[100],b[100];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
/* strcmp(string,string):returns 0 if strings are equal else strings are unequal */
if(strcmp(a,b)==0)
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc , char *argv[])
{
int array[] = {5,2,7,3,1,6,9,8,0};
int len = sizeof(array)/sizeof(int);
printf("Old Array order:\n");
showSortArray(array,len);
/**********1*************
bubble_sort(array,len);
jiwei_sort(array,len);
SelectSort(array,len);
InsertSort(array,len);
Partition(array,0,len-1);
************************/
ShellSort(array,len);
showSortArray(array,len);
printf("\nSort end ......\n");
}
void swap(int array[],int i,int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
void showSortArray(int array[],int len)
{
int i=0;
for(i=0;i<len;i++)
{
printf("%d ",array[i]);
}
}
void bubble_sort(int array[],int len)
{
printf("\nBubble Sort Start.....\n");
int i,j=0;
int logol = 1;
for(i=0;i<len-1;i++)
{
logol = 0;
for(j=0;j<len-i-1;j++)
{
if(array[j]>array[j+1])
{
logol = 1;
swap(array,j,j+1);
}
}
if(logol == 0)
{
break;
}
}
}
void jiwei_sort(int array[],int len)
{
printf("\nJiwei Sort Start.....\n");
int left = 0;
int right = len-1;
int i,j=0;
int logol = 1;
while(left<right && logol)
{
logol = 0;
for(i=left;i<right;i++)
{
if(array[i] > array[i+1])
{
logol = 1;
swap(array,i,i+1);
}
}
right--;
for(j=right;j>left;j--)
{
if(array[j]<array[j-1])
{
logol = 1;
swap(array,j,j-1);
}
}
left++;
}
}
void SelectSort(int array[],int len)
{
printf("\nSelect Sort Start.....\n");
int i,j,min=0;
for(i=0;i<len-1;i++)
{
min = i;
for(j=i+1;j<len;j++)
{
if(array[j]<array[min])
{
min = j;
}
}
if(min!=i)
{
swap(array,min,i);
}
}
}
void InsertSort(int array[],int len)
{
printf("\nInsert Sort Start.....\n");
int i,j,get=0;
for(i=1;i<len;i++)
{
get = array[i];
j = i-1;
while(j>=0 && array[j]>get)
{
array[j+1] = array[j];
j--;
}
array[j+1] = get;
}
}
void Partition(int array[],int start,int end)
{
printf("\nQuick Sort Start.....\n");
int low = start;
int high = end;
int target = array[low];
if(low>=high)
{
return;
}
else
{
while(low < high)
{
while(low<high && array[high]>target)
{
high--;
}
array[low] = array[high];
while(low<high && array[low]<target)
{
low++;
}
array[high] = array[low];
}
array[low] = target;
}
showSortArray(array,end);
Partition(array,start,low-1);
Partition(array,low+1,end);
}
void ShellSort(int array[],int len)
{
printf("\nShell Sort Start.....\n");
int d = (len+1)/2;
int i = 0;
while(d)
{
for(i=0;i+d<len;i++)
{
if(array[i]>array[i+d])
{
swap(array,i,i+d);
}
}
d--;
}
}
|
C
|
/********************************************************************************
C implementation of four-parameter Least Squares sine fitting method proposed in
"A Computationally Efficient Non-iterative Four-parameter Sine Fitting Method,
IET Signal Processing, 2021
Input parameters:
- x: Data samples
- w_init: initial relative angular frequency estimate
- dw: deviation from w0, where the three-parameter
LS cost function is evaluated
- N: number of samples
- pM_vect: parameter vector containing A, B, C and relative
angular frequency
Output parameters: pM_vect will contain the optimal parameter set after the
evaluation
Written by: Vilmos Pálfi
Last modified: April 8, 2021
********************************************************************************/
void LS4p_parab(float32_t* x, float32_t w_init, float32_t dw, uint32_t N, float32_t* pM_vect)
{
float32_t pM_vect_0[9], pM_vect_opt[3], CF_opt;
float32_t dw_opt, w_opt;
/* Matrix M contains the elements of the matrix in (20) of the articla
which is needed to determine optimal parameters */
float32_t M_vect[9] = { 0.5, -1.0, 0.5, -0.5, 0.0, 0.5, 0.0, 1.0, 0.0 };
float32_t parab_vect[3], CF_vect[3]; // CF_vect contains 3 evaluations at 3 frequencies
arm_matrix_instance_f32 M, parab, CF;
arm_status status;
/* Three LS3p fitting is evaluated at three different frequencies: w_init, w_init-dw,
w_init+dw */
LS3p(x, w_init - dw, N, pM_vect_0, CF_vect);
LS3p(x, w_init, N, pM_vect_0 + 3, CF_vect + 1);
LS3p(x, w_init + dw, N, pM_vect_0 + 6, CF_vect + 2);
/* Matrix initialisation in order to be able to perform matrix operation in the ARM
environment */
arm_mat_init_f32(&M, 3, 3, M_vect);
arm_mat_init_f32(&CF, 3, 1, CF_vect);
arm_mat_init_f32(¶b, 3, 1, parab_vect);
/* We perform matrix operation in (20) in in the article */
status = arm_mat_mult_f32(&M, &CF, ¶b); // Check whether the operation was performed succesfully
if ( status != ARM_MATH_SUCCESS)
{
print_error_func("Error: LS4p_parab, status = arm_mat_mult_f32(&M, &CF, ¶b);");
}
dw_opt = -parab_vect[1]/2/parab_vect[0]*dw; // We perform (21) in the article
w_opt = w + dw_opt; // Optimal relative angular frequency is calculated
LS3p(x, w_opt, N, pM_vect_opt, NULL); // Another LS3p method is performed to obtain optimal parameters at the optimal frequency
pM_vect[0] = pM_vect_opt[0];
pM_vect[1] = pM_vect_opt[1];
pM_vect[2] = pM_vect_opt[2];
pM_vect[3] = w_opt;
}
|
C
|
/* ChickenOS - fs/deivce.c - generic block/char device layer
* Needs a bit of work
*/
//Ideally we'll have 2 classes of functions
//[block|char]_[read|write]_at -> takes offset/size
//block_[read|write] -> takes block only, used for lowlevel
//access
//then we can have a common struct device again
#include <kernel/common.h>
#include <kernel/memory.h>
#include <fs/vfs.h>
#include <mm/liballoc.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#define MAX_DEVICES 20
struct char_device {
dev_t dev;
char_read_fn read;
char_write_fn write;
char_ioctl_fn ioctl;
};
struct block_device {
dev_t dev;
block_read_fn read;
block_write_fn write;
void *pad;
};
struct block_device block_devices[MAX_DEVICES];
struct char_device char_devices[MAX_DEVICES];
void device_register(uint16_t device_type, dev_t dev, void *read, void *write, void *ioctl)
{
if(device_type == FILE_CHAR)
{
struct char_device *c = &char_devices[MAJOR(dev)];
c->read = (char_read_fn)read;
c->write = (char_write_fn)write;
c->ioctl = (char_ioctl_fn)ioctl;
c->dev = MAJOR(dev);
}
else if(device_type == FILE_BLOCK)
{
struct block_device *b = &block_devices[MAJOR(dev)];
b->read = (block_read_fn )read;
b->write = (block_write_fn )write;
b->dev = MAJOR(dev);
}
//printf("Registered device %x:%x\n", MAJOR(dev),MINOR(dev));
}
size_t block_device_read(uint16_t dev, void *buf, uint32_t block)
{
struct block_device *device = &block_devices[MAJOR(dev)];
if(device == NULL)
{
printf("invalid dev passed to block_device_read\n");
return 0;
}
if(device->read == NULL)
{
printf("device has no read function\n");
return 0;
}
return device->read(dev, buf, block);
}
size_t block_device_write(uint16_t dev, void *buf, uint32_t block)
{
struct block_device *device = &block_devices[MAJOR(dev)];
if(device == NULL)
{
printf("invalid dev passed to block_device_write\n");
return 0;
}
if(device->write == NULL)
{
printf("device has no write function\n");
return 0;
}
return device->write(dev, buf, block);
}
size_t block_device_readn(uint16_t dev, void *buf, uint32_t block, off_t offset, size_t nbyte)
{
return read_block_at(dev, buf, block,SECTOR_SIZE,
offset, nbyte);
}
size_t block_device_writen(uint16_t dev, void *buf, uint32_t block, off_t offset, size_t nbyte)
{
return write_block_at(dev, buf, block,SECTOR_SIZE,
offset, nbyte);
}
size_t char_device_read(dev_t dev, void *buf, off_t offset, size_t nbyte)
{
size_t ret = 0;
struct char_device *device = &char_devices[MAJOR(dev)];
ret = device->read(dev, buf, nbyte, offset);
return ret;
}
size_t char_device_write(dev_t dev, void *buf, off_t offset, size_t nbyte)
{
size_t ret = 0;
struct char_device *device = &char_devices[MAJOR(dev)];
ret = device->write(dev, buf, nbyte, offset);
return ret;
}
int char_device_ioctl(dev_t dev, int request, char *args)
{
size_t ret = 0;
struct char_device *device = &char_devices[MAJOR(dev)];
ret = device->ioctl(dev, request, args);
return ret;
}
int read_block(uint16_t dev, void * _buf, int block, int block_size)
{
uint8_t *buf = _buf;
uint32_t dblock = 0;
off_t count = 0;
if(block_size <= 0)
return -1;
dblock = (block * block_size) / SECTOR_SIZE;
while(block_size > 0)
{
if(block_device_read(dev, (void *)(buf + count), dblock) != SECTOR_SIZE)
{
return -1;
}
count += SECTOR_SIZE;
block_size -= SECTOR_SIZE;
dblock++;
}
return count;
}
int read_block_at(uint16_t dev, void * _buf, int block,
int block_size, off_t offset, size_t nbytes)
{
uint8_t *buf = _buf;
uint8_t *bounce = kmalloc(block_size);
int remaining = nbytes;
size_t count = 0;
int block_ofs, cur_block_size,
till_end;
int cur_size = offset;
while(remaining > 0)
{
block = (block*block_size + cur_size) / block_size;
block_ofs = offset % block_size;
cur_block_size = block_size - block_ofs;
// to_end = 1000000000;
// till_end = (to_end < cur_block_size) ? to_end: cur_block_size;
till_end = cur_block_size;
cur_size = remaining < till_end ? remaining : till_end;
if(cur_size <= 0)
break;
if(block_ofs == 0 && cur_size == block_size)
{
if(read_block(dev, buf + count, block,block_size) == 0)
{
count = -1;
goto done;
}
}
else
{
if(read_block(dev, buf + count, block,block_size) == 0)
{
count = -1;
goto done;
}
kmemcpy(buf + count, bounce + block_ofs,cur_size);
}
count += cur_size;
offset += cur_size;
remaining -= cur_size;
}
done:
if(bounce != NULL)
kfree(bounce);
return count;
}
int write_block(uint16_t dev, void * _buf, int block, int block_size)
{
uint8_t *buf = _buf;
uint32_t dblock = 0;
off_t count = 0;
if(block_size <= 0)
return -1;
dblock = (block * block_size) / SECTOR_SIZE;
while(block_size > 0)
{
if(block_device_write(dev, buf + count, dblock) != SECTOR_SIZE)
{
return -1;
}
count += SECTOR_SIZE;
block_size -= SECTOR_SIZE;
dblock++;
}
return count;
}
int write_block_at(uint16_t dev, void * _buf, int block,
int block_size, off_t offset, size_t nbytes)
{
uint8_t *buf = _buf;
uint8_t *bounce = kmalloc(block_size);
int remaining = nbytes;
size_t count = 0;
int block_ofs, cur_block_size,
till_end;
int cur_size = offset;
while(remaining > 0)
{
block = (block*block_size + cur_size) / block_size;
block_ofs = offset % block_size;
cur_block_size = block_size - block_ofs;
// to_end = 1000000000;
// till_end = (to_end < cur_block_size) ? to_end: cur_block_size;
till_end = cur_block_size;
cur_size = remaining < till_end ? remaining : till_end;
if(cur_size <= 0)
break;
if(block_ofs == 0 && cur_size == block_size)
{
if(write_block(dev, buf + count, block,block_size) == 0)
{
count = -1;
goto done;
}
}
else
{
//have to read the block in first
if(block_ofs > 0 || cur_size < cur_block_size)
{
read_block(dev, bounce, block, block_size);
}
kmemcpy(bounce + block_ofs,buf + count,cur_size);
if(write_block(dev, buf + count, block,block_size) == 0)
{
count = -1;
goto done;
}
}
count += cur_size;
offset += cur_size;
remaining -= cur_size;
}
done:
if(bounce != NULL)
kfree(bounce);
return count;
}
int read_block_generic(void * _buf, int size, int offset, int block_size, void *aux, block_access_fn f UNUSED)
{
uint8_t *buf = _buf;
uint8_t *bounce;
off_t count = 0;
if(block_size <= 0)
return -1;
if((bounce = kmalloc(block_size)) == NULL)
{
printf("memory allocation error in readblock\n");
return -1;
}
// printf("offset %i size%i block_size%i\n", offset, size,block_size);
// printf("block = %i\n",offset/block_size);
while(size > 0)
{
int block = offset / block_size;
int block_ofs = offset % block_size;
int cur_size = block_size - block_ofs;
// printf("reading block %i\n",block);
if(block_ofs == 0 && cur_size == block_size)
{
if(block_device_read((uint16_t)(uint32_t)aux, buf + count, block) == 0)
{
count = -1;
goto end;
}
}
else
{
if(block_device_read((uint16_t)(uint32_t)aux, bounce, block) == 0)
{
count = -1;
goto end;
}
kmemcpy(buf + count, bounce + block_ofs, cur_size);
}
count += cur_size;
offset += cur_size;
size -= cur_size;
}
end:
//FIXME
//kfree(bounce);
return count;
}
|
C
|
#ifndef _MATH_OPERATIONS_LIB_
#define _MATH_OPERATIONS_LIB_
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <stdint.h>
#include <stdbool.h>
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
//Get the sign of the k-th entry.
#define get_sign(M, entry_idx) (bool)(((M)->bit_sign_storage[(entry_idx) / 8] >> ((entry_idx) % 8)) & 0x1)
//Generate a random number with uniform distribution within 0 and 1.
#define rand_kiss() (float)(mars_kiss32() / 4294967296.0)
//Compute the rectified linear function of v in place.
#define relu_in_place(v, size_v) for(uint16_t kk = 0; kk < (size_v); kk++) if ((v)[kk] < 0) (v)[kk] = 0
//Make the substraction of two vectors
#define vector_substraction(a, size_a, b, size_b, result, size_result) for (uint16_t kk = 0; kk < (size_a); kk++) (result)[kk] = (a)[kk] - (b)[kk]
//Set the sign of the k-th entry in the matrix.
#define set_sign(M, entry_idx, val) \
if ((val)) (M)->bit_sign_storage[(entry_idx) / 8] |= 1 << ((entry_idx) % 8); \
else (M)->bit_sign_storage[(entry_idx) / 8] &= ~(1 << ((entry_idx) % 8))
//position(32bit)=row(16bit),col(bit)
#define get_flattened_position(M, entry) (uint32_t)(((M)->rows[(entry)] << 16) + (M)->cols[(entry)])
//row is the high 16 bits of position, if col = n_col, row++
#define get_row_from_position(M, position) (uint16_t)(((position)>>16)+((((position) & 0xffff)>=(M)->n_cols)?1:0))
//col is the low 16 bits of position, if col = n_col, col = 0
#define get_col_from_position(M, position) (uint16_t)((((position) & 0xffff) == (M)->n_cols)?0:((position) & 0xffff))
/**
* Random numbers
**/
uint32_t mars_kiss32( void );
float randn_kiss( void );
/**
* SPARSE MATRICES BASICS
*/
struct sparse_weight_matrix {
uint16_t max_entries;
uint16_t number_of_entries;
uint16_t n_rows;
uint16_t n_cols;
uint16_t *rows;
uint16_t *cols;
uint8_t *bit_sign_storage;
float *thetas;
};
typedef struct sparse_weight_matrix sparse_weight_matrix;
float get_weight_by_entry(sparse_weight_matrix *M, int k);
int is_entry_and_fetch(sparse_weight_matrix *M, int i, int j);
float get_theta_by_row_col_pair(sparse_weight_matrix *M, int i, int j);
int get_sign_by_row_col_pair(sparse_weight_matrix *M, int i, int j);
void set_dimensions(sparse_weight_matrix *M, uint16_t n_rows, uint16_t n_cols, float connectivity);
void check_sparse_matrix_format(sparse_weight_matrix *M);
void set_random_weights_sparse_matrix(sparse_weight_matrix *M, float connectivity);
void put_new_entry(sparse_weight_matrix *M, uint16_t row, uint16_t col, float value, bool sign, bool fail_if_exist);
void delete_entry(sparse_weight_matrix *M, uint16_t entry_idx);
void quickSort(sparse_weight_matrix *M, uint16_t entry_low, uint16_t entry_high);
void put_new_random_entries(sparse_weight_matrix *M, uint16_t n_new);
void delete_negative_entries(sparse_weight_matrix *M);
void print_weight_matrix(sparse_weight_matrix *M);
void print_sign_and_theta(sparse_weight_matrix *M);
void print_vector(float *v, uint size);
void check_order(sparse_weight_matrix *M, uint16_t entry_low, uint16_t entry_high);
void print_weight_matrix_containers(sparse_weight_matrix *M, bool print_non_assigned);
uint32_t rand_int_kiss(uint32_t low, uint32_t high);
/**
* MATH OPERATIONS
*/
void left_dot(sparse_weight_matrix *M, float *v, uint size_v, float *result, uint size_result);
void right_dot(float *v, uint size_v, sparse_weight_matrix *M, float *result, uint size_result);
void term_by_term_multiplication(float *a, uint size_a, float *b, uint size_b, float *result, uint size_result);
void back_prop_error_msg(sparse_weight_matrix *W, float *a_pre, uint size_a_pre, float *d_post,
uint size_d_post, float *d_pre, uint size_d_pre);
float gradient_wrt_theta_entry(sparse_weight_matrix *weight_matrix, float *a_pre, uint size_a_pre, float *d_post, uint size_d_post, uint16_t entry_idx);
void update_weight_matrix(sparse_weight_matrix *W, float *a_pre, uint size_a_pre, float *d_post, uint size_d_post, float learning_rate);
void rewiring(sparse_weight_matrix *W);
void softmax(float *a, uint size_a, float *result, uint size_result);
uint8_t argmax (float *prob, uint8_t size_prob);
void rewiring2(sparse_weight_matrix *M);
#endif
|
C
|
// TODO: Python-style order-preserving mapping https://www.youtube.com/watch?v=p33CVV29OG8
#include <assert.h>
#define EMPTY ((size_t)(-1))
MAPPING MAPPING_CTOR(void)
{
size_t n = 8; // TODO: experiment with different values
MAPPING map = malloc(sizeof(*map) + n*sizeof(map->flex[0]));
assert(map);
map->refcount = 1;
map->items = ITEM_LIST_CTOR();
map->itable = map->flex;
for (size_t i = 0; i < n; i++)
map->itable[i] = EMPTY;
map->itablelen = n;
return map;
}
void MAPPING_DTOR(void *ptr)
{
MAPPING map = ptr;
ITEM_LIST_DECREF(map->items);
if (map->itable != map->flex)
free(map->itable);
free(map);
}
static uint32_t hash(KEY key)
{
uint32_t h = (uint32_t)KEY_METHOD(hash)(key);
// 0 has special meaning in MappingItem
return h==0 ? 69 : h;
}
static size_t find_empty(MAPPING map, uint32_t keyhash)
{
size_t i;
for (i = keyhash % map->itablelen; map->itable[i] != EMPTY; i = (i+1) % map->itablelen) { }
return i;
}
static ITEM *find_item_or_empty(MAPPING map, KEY key, uint32_t keyhash, size_t *i)
{
for (*i = keyhash % map->itablelen; map->itable[*i] != EMPTY; *i = (*i + 1) % map->itablelen)
{
ITEM *inmap = &map->items->data[map->itable[*i]];
if (inmap->hash == keyhash && KEY_METHOD(equals)(inmap->memb_key, key))
return inmap;
}
// *i is what find_empty would return
return NULL;
}
static ITEM *find_item(MAPPING map, KEY key, uint32_t keyhash)
{
size_t dummy;
return find_item_or_empty(map, key, keyhash, &dummy);
}
static void grow_itable(MAPPING map)
{
size_t oldsz = map->itablelen;
map->itablelen *= 2;
if (map->itable == map->flex)
map->itable = malloc(map->itablelen * sizeof map->itable[0]);
else
map->itable = realloc(map->itable, map->itablelen * sizeof map->itable[0]);
assert(map->itable);
// Reindex everything lol
for (size_t i = 0; i < map->itablelen; i++)
map->itable[i] = EMPTY;
for (int64_t i = 0; i < map->items->len; i++)
map->itable[find_empty(map, map->items->data[i].hash)] = i;
}
void MAPPING_METHOD(set)(MAPPING map, KEY key, VALUE value)
{
float magic = 0.7; // TODO: do experiments to find best possible value
if (map->items->len+1 > magic*map->itablelen)
grow_itable(map);
uint32_t h = hash(key);
size_t i;
ITEM *inmap = find_item_or_empty(map, key, h, &i);
if (inmap == NULL) {
map->itable[i] = (size_t)map->items->len;
ITEM_LIST_METHOD(push)(map->items, (ITEM){ h, key, value });
} else {
VALUE_DECREF(inmap->memb_value);
inmap->memb_value = value;
VALUE_INCREF(inmap->memb_value);
}
}
// TODO: this sucked in python 2 and it sucks here too
bool MAPPING_METHOD(has_key)(MAPPING map, KEY key)
{
return find_item(map, key, hash(key)) != NULL;
}
#define ERROR(msg, key) panic_printf("%s: %s", (msg), string_to_cstr(KEY_METHOD(to_string)((key))))
VALUE MAPPING_METHOD(get)(MAPPING map, KEY key)
{
ITEM *it = find_item(map, key, hash(key));
if (!it)
ERROR("Mapping.get(): key not found", key);
VALUE_INCREF(it->memb_value);
return it->memb_value;
}
void MAPPING_METHOD(delete)(MAPPING map, KEY key)
{
size_t i;
if (find_item_or_empty(map, key, hash(key), &i) == NULL)
ERROR("Mapping.delete(): key not found", key);
// TODO: delete_at_index is slow
size_t delidx = map->itable[i];
ITEM deleted = ITEM_LIST_METHOD(delete_at_index)(map->items, delidx);
KEY_DECREF(deleted.memb_key);
VALUE_DECREF(deleted.memb_value);
map->itable[i] = EMPTY;
// Adjust the mess left behind by delete_at_index
for (size_t k = 0; k < map->itablelen; k++) {
if (map->itable[k] != EMPTY && map->itable[k] > delidx)
map->itable[k]--;
}
// Delete and add back everything that might rely on jumping over the item at i
for (size_t k = (i+1) % map->itablelen; map->itable[k] != EMPTY; k = (k+1) % map->itablelen)
{
size_t idx = map->itable[k];
map->itable[k] = EMPTY;
map->itable[find_empty(map, map->items->data[idx].hash)] = idx;
}
}
int64_t MAPPING_METHOD(length)(MAPPING map)
{
return map->items->len;
}
struct String MAPPING_METHOD(to_string)(MAPPING map)
{
struct String res = cstr_to_string("Mapping{");
for (int64_t i = 0; i < map->items->len; i++) {
struct String keystr = KEY_METHOD(to_string)(map->items->data[i].memb_key);
struct String valstr = VALUE_METHOD(to_string)(map->items->data[i].memb_value);
if (i)
oomph_string_concat_inplace_cstr(&res, ", ");
oomph_string_concat_inplace(&res, keystr);
oomph_string_concat_inplace_cstr(&res, ": ");
oomph_string_concat_inplace(&res, valstr);
decref_Str(keystr);
decref_Str(valstr);
}
oomph_string_concat_inplace_cstr(&res, "}");
return res;
}
bool MAPPING_METHOD(equals)(MAPPING a, MAPPING b)
{
if (a->items->len != b->items->len)
return false;
// Check that every key of a is also in b, and values match.
// No need to check in opposite direction, because lengths match.
for (int64_t i = 0; i < a->items->len; i++) {
ITEM aent = a->items->data[i];
ITEM *bent = find_item(b, aent.memb_key, aent.hash);
if (bent == NULL || !VALUE_METHOD(equals)(aent.memb_value, bent->memb_value))
return false;
}
return true;
}
// TODO: optimize?
MAPPING MAPPING_METHOD(copy)(MAPPING map)
{
MAPPING res = MAPPING_CTOR();
for (int64_t i = 0; i < map->items->len; i++) {
ITEM it = map->items->data[i];
MAPPING_METHOD(set)(res, it.memb_key, it.memb_value);
}
return res;
}
KEY_LIST MAPPING_METHOD(keys)(MAPPING map)
{
KEY_LIST res = KEY_LIST_CTOR();
for (int64_t i = 0; i < map->items->len; i++)
KEY_LIST_METHOD(push)(res, map->items->data[i].memb_key);
return res;
}
VALUE_LIST MAPPING_METHOD(values)(MAPPING map)
{
VALUE_LIST res = VALUE_LIST_CTOR();
for (int64_t i = 0; i < map->items->len; i++)
VALUE_LIST_METHOD(push)(res, map->items->data[i].memb_value);
return res;
}
ITEM_LIST MAPPING_METHOD(items)(MAPPING map)
{
return ITEM_LIST_METHOD(copy)(map->items);
}
|
C
|
#include <stdio.h>
/* count words lines characters etc */
#define INSIDE_WORD 1
#define OUTSIDE_WORD 0
main() {
int character, number_of_lines, number_of_words, number_of_characters,
current_state;
current_state = OUTSIDE_WORD;
number_of_lines = number_of_words = number_of_characters = 0;
while ( (character = getchar()) != EOF ) {
++number_of_characters;
if ( character == '\n' )
++number_of_lines;
if ( character == ' ' || character == '\n' || character == '\t' )
current_state = OUTSIDE_WORD;
else if ( current_state == OUTSIDE_WORD ) {
current_state = INSIDE_WORD;
++number_of_words;
}
}
printf("Lines: %d\tWords: %d\tCharacters: %d\n", number_of_lines, number_of_words, number_of_characters);
}
|
C
|
/*
* Copyright (c) 2016 Sean Parkinson ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "hash_sha1.h"
#include "hmac.h"
/** The size of a block that is processed. */
#define BLOCK_SIZE 64
/** The first constant k to use with SHA-1 block operation. */
#define HASH_SHA1_K_0 0x5A827999
/** The second constant k to use with SHA-1 block operation. */
#define HASH_SHA1_K_1 0x6ED9EBA1
/** The third constant k to use with SHA-1 block operation. */
#define HASH_SHA1_K_2 0x8F1BBCDC
/** The fourth constant k to use with SHA-1 block operation. */
#define HASH_SHA1_K_3 0xCA62C1D6
/**
* Boolean function operation for loop iterations 0-19.
*
* @param [in] b The second working state value.
* @param [in] c The third working state value.
* @param [in] d The fourth working state value.
* @return The boolean operation result.
*/
#define F00_19(b, c, d) (((b) & (c)) | ((~(b)) & d))
/**
* Boolean function operation for loop iterations 20-39.
*
* @param [in] b The second working state value.
* @param [in] c The third working state value.
* @param [in] d The fourth working state value.
* @return The boolean operation result.
*/
#define F20_39(b, c, d) ((b) ^ (c) ^ (d))
/**
* Boolean function operation for loop iterations 40-59.
*
* @param [in] b The second working state value.
* @param [in] c The third working state value.
* @param [in] d The fourth working state value.
* @return The boolean operation result.
*/
#define F40_59(b, c, d) (((b) & (c)) | ((b) & (d)) | ((c) & (d)))
/**
* Boolean function operation for loop iterations 60-79.
*
* @param [in] b The second working state value.
* @param [in] c The third working state value.
* @param [in] d The fourth working state value.
* @return The boolean operation result.
*/
#define F60_79(b, c, d) ((b) ^ (c) ^ (d))
#ifdef SHA3_NO_BSWAP
/**
* Convert 4 bytes of big-endian into a 32-bit number.
*
* @param [out] r The 32-bit number.
* @param [in] a The array of bytes.
* @param [in] c Count of 32-bit numbers into the array.
*/
#define M32(r, a, c) \
r = ((((uint32_t)a[c*4+0]) << 24) | \
(((uint32_t)a[c*4+1]) << 16) | \
(((uint32_t)a[c*4+2]) << 8) | \
(((uint32_t)a[c*4+3]) << 0))
#else
/**
* Convert 4 bytes of big-endian into a 32-bit number.
*
* @param [out] r The 32-bit number.
* @param [in] a The array of bytes.
* @param [in] c Count of 32-bit numbers into the array.
*/
#define M32(r, a, c) \
do \
{ \
register uint32_t t; \
t = ((const uint32_t *)a)[c]; \
asm volatile ("bswap %0" \
: \
: "r" (t)); \
r = t; \
} \
while (0)
#endif
/**
* Process one block of data (512 bits) for SHA-1.
*
* @param [in] ctx The SHA1 context object.
* @param [in] m The message data to digest.
*/
static void hash_sha1_block(HASH_SHA1 *ctx, const uint8_t *m)
{
uint8_t i;
uint32_t *h = ctx->h;
uint32_t w[77];
uint32_t t[6];
t[0] = h[0];
t[1] = h[1];
t[2] = h[2];
t[3] = h[3];
t[4] = h[4];
for (i=0; i<16; i++)
{
M32(w[i], m, i);
t[5] = t[4] + HASH_SHA1_K_0 + ROTL32(t[0], 5) + w[i] +
F00_19(t[1], t[2], t[3]);
t[4] = t[3];
t[3] = t[2];
t[2] = ROTL32(t[1], 30);
t[1] = t[0];
t[0] = t[5];
}
for (; i<20; i++)
{
w[i] = ROTL32(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
t[5] = t[4] + HASH_SHA1_K_0 + ROTL32(t[0], 5) + w[i] +
F00_19(t[1], t[2], t[3]);
t[4] = t[3];
t[3] = t[2];
t[2] = ROTL32(t[1], 30);
t[1] = t[0];
t[0] = t[5];
}
for (; i<40; i++)
{
w[i] = ROTL32(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
t[5] = t[4] + HASH_SHA1_K_1 + ROTL32(t[0], 5) + w[i] +
F20_39(t[1], t[2], t[3]);
t[4] = t[3];
t[3] = t[2];
t[2] = ROTL32(t[1], 30);
t[1] = t[0];
t[0] = t[5];
}
for (; i<60; i++)
{
w[i] = ROTL32(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
t[5] = t[4] + HASH_SHA1_K_2 + ROTL32(t[0], 5) + w[i] +
F40_59(t[1], t[2], t[3]);
t[4] = t[3];
t[3] = t[2];
t[2] = ROTL32(t[1], 30);
t[1] = t[0];
t[0] = t[5];
}
for (; i<77; i++)
{
w[i] = ROTL32(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
t[5] = t[4] + HASH_SHA1_K_3 + ROTL32(t[0], 5) + w[i] +
F60_79(t[1], t[2], t[3]);
t[4] = t[3];
t[3] = t[2];
t[2] = ROTL32(t[1], 30);
t[1] = t[0];
t[0] = t[5];
}
for (; i<80; i++)
{
t[5] = ROTL32(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
t[5] += t[4] + HASH_SHA1_K_3 + ROTL32(t[0], 5) +
F60_79(t[1], t[2], t[3]);
t[4] = t[3];
t[3] = t[2];
t[2] = ROTL32(t[1], 30);
t[1] = t[0];
t[0] = t[5];
}
h[0] += t[0];
h[1] += t[1];
h[2] += t[2];
h[3] += t[3];
h[4] += t[4];
}
/**
* Process the unused message bytes.
* Append 0x80 to add 1 bit after message.
* Put the length in the last 64 bits of a block of 512 bits even if we have
* to make a new block.
*
* @param [in] ctx The SHA1 context object.
*/
static void hash_sha1_fin(HASH_SHA1 *ctx)
{
uint8_t i;
uint8_t *m = ctx->m;
uint8_t o = ctx->o;
uint64_t len = ctx->len * 8;
m[o++] = 0x80;
if (o > 56)
{
memset(&m[o], 0, BLOCK_SIZE - o);
hash_sha1_block(ctx, m);
o = 0;
}
memset(&m[o], 0, 56-o);
for (i=0; i<8; i++)
m[56+i] = len >> ((7-i)*8);
hash_sha1_block(ctx, m);
}
/** The initial h0 value for SHA-1. */
#define SHA1_H0 0x67452301
/** The initial h1 value for SHA-1. */
#define SHA1_H1 0xEFCDAB89
/** The initial h2 value for SHA-1. */
#define SHA1_H2 0x98BADCFE
/** The initial h3 value for SHA-1. */
#define SHA1_H3 0x10325476
/** The initial h4 value for SHA-1. */
#define SHA1_H4 0xC3D2E1F0
/**
* Initialize the hash object calculating a SHA-1 digest.
*
* @param [in] ctx The SHA1 context object.
* @return 1 to indicate success.
*/
int hash_sha1_init(HASH_SHA1 *ctx)
{
ctx->h[0] = SHA1_H0;
ctx->h[1] = SHA1_H1;
ctx->h[2] = SHA1_H2;
ctx->h[3] = SHA1_H3;
ctx->h[4] = SHA1_H4;
ctx->o = 0;
ctx->len = 0;
return 1;
}
/**
* Update the message digest with more data.
*
* @param [in] ctx The SHA1 context object.
* @param [in] data The data to digest.
* @param [in] len The length of the data to digest.
* @return 1 to indicate success.
*/
int hash_sha1_update(HASH_SHA1 *ctx, const void *data, size_t len)
{
size_t i;
size_t l;
uint8_t *m = ctx->m;
uint8_t o = ctx->o;
const uint8_t *d = data;
uint8_t *t;
ctx->len += len;
if (o > 0)
{
l = BLOCK_SIZE - o;
if (len < l) l = len;
t = &m[o];
for (i=0; i<l; i++)
t[i] = d[i];
d += l;
len -= l;
o += l;
if (o == BLOCK_SIZE)
{
hash_sha1_block(ctx, m);
o = 0;
}
}
while (len >= BLOCK_SIZE)
{
hash_sha1_block(ctx, d);
d += BLOCK_SIZE;
len -= BLOCK_SIZE;
}
for (i=0; i<len; i++)
m[i] = d[i];
ctx->o = o + len;
return 1;
}
/**
* Finalize the message digest for SHA-1.
* Output 160 bits or 20 bytes.
*
* @param [in] md The message digest buffer.
* @param [in] ctx The SHA1 context object.
* @return 1 to indicate success.
*/
int hash_sha1_final(unsigned char *md, HASH_SHA1 *ctx)
{
uint8_t i, j;
uint32_t *h = ctx->h;
hash_sha1_fin(ctx);
for (i=0; i<5; i++)
for (j=0; j<4; j++)
md[i*4+j] = h[i] >> ((3-j)*8);
return 1;
}
/**
* Initialize the HMAC-SHA-1 operation with a key.
*
* @param [in] ctx The SHA1 context objects.
* @param [in] key The key data.
* @param [in] len The length of the key data.
* @return 1 to indicate success.
*/
int hmac_sha1_init(HASH_SHA1 *ctx, const void *key, size_t len)
{
HMAC_INIT(ctx, key, len, HASH_SHA1_LEN, hash_sha1_init, hash_sha1_update,
hash_sha1_final);
return 1;
}
/**
* Finalize the HMAC-SHA-1 operation.
* Output 160 bits or 20 bytes.
*
* @param [in] md The MAC data buffer.
* @param [in] ctx The SHA1 context objects.
* @return 1 to indicate success.
*/
int hmac_sha1_final(unsigned char *md, HASH_SHA1 *ctx)
{
HMAC_FINAL(md, ctx, HASH_SHA1_LEN, hash_sha1_update, hash_sha1_final);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
#include "utn.h"
#include "Bici.h"
#include "parcer.h"
int main()
{
int opcion = 0;
char salir[3];
char rta;
int opcionBici;
LinkedList* listaPrincipal = ll_newLinkedList();
LinkedList* listaOrdenada= NULL;
LinkedList* listaMap = NULL;
LinkedList* listaTipo = NULL;
do
{ strcpy(salir,"no");
getInt("\MENU\n 1) Cargar archivo bici.csv (modo texto)\n2) Imprimir lista\n3) Asignar tiempos\n4) Filtrar por tipo\n5) Mostrar posiciones \n6) Guardar posiciones\n7) Salir\n","Error\n", 1, 3, 0, &opcion);
printf("\n\n");
switch(opcion)
{
case 1:
if(cargarTexto("bicicletas.csv", listaPrincipal) == 0)
{
printf("Archivo cargado con exito\n");
}
else
{
printf("ERROR");
}
system("pause");
break;
case 2:
if(listarBicis(listaPrincipal))
{
printf("Lista cargada con exito\n");
}
else
{
printf("ERROR");
}
system("pause");
break;
case 3:
listaMap = ll_map(listaPrincipal, datosRandom);
listarBicis(listaMap);
system("pause");
break;
case 4:
getInt("- Elija opcion\n1. PASEO\n2. PLAYERA\n3. MTB\n4. BMX\n>","Error, escriba un numero del 1 al 4", 1,4,4, &opcionBici);
char temp[20];
switch(opcionBici)
{
case 1:
strcpy(temp,"PASEO");
break;
case 2:
strcpy(temp,"PLAYERA");
break;
case 3:
strcpy(temp, "MTB");
break;
case 4:
strcpy(temp, "BMX");
break;
}
listaTipo= ll_filter_parametro(listaPrincipal, filterTipo, temp);
guardarComoTexto("bicicletasPorTipo.csv", listaTipo);
system("pause");
break;
case 5:
listaOrdenada= ll_clone(listaPrincipal);
if(listaOrdenada!=NULL)
{
ll_sort(listaOrdenada, ordenarPorTipoXTiempo, 1);
}
listarBicis(listaOrdenada);
system("pause");
break;
case 6:
break;
case 7:
printf("Los datos no seran guardados\n Seguro que desea salir? ");
fflush(stdin);
scanf("%c", &rta);
while(rta != 's' && rta != 'n')
{
printf("Opcion incorrecta. Reingrese 's'(si) o 'n'(no)");
printf(" s/n : \n");
fflush(stdin);
scanf("%c", &rta);
}
if(rta == 's')
{
printf("Hasta luego!!!\n");
return 0;
}
system("pause");
break;;
default:
printf("Opcion incorrecta. Reingrese\n");
system("pause");
}
system("cls");
}
while(strcmp(salir,"si")!= 0);
ll_deleteLinkedList(listaMap);
ll_deleteLinkedList(listaOrdenada);
ll_deleteLinkedList(listaPrincipal);
ll_deleteLinkedList(listaTipo);
return 0;
}
|
C
|
#include <stdio.h>
/**
*main - prints from 1 to 100
* % of 3 with Fizz,
* % of 5 with Buzz
* and % of 3 and % 5 with FizzBuzz
*Return: cero
*/
int main(void)
{
int n;
for (n = 1; n <= 100; n++)
{
if (n % 3 == 0 && n % 5 == 0)
{
printf("FizzBuzz");
}
else if (n % 3 == 0)
{
printf("Fizz");
}
else if (n % 5 == 0)
{
printf("Buzz");
}
else
{
printf("%d", n);
}
if (n < 100)
{
printf(" ");
}
}
printf("\n");
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "project2.h"
/* ***************************************************************************
ALTERNATING BIT AND GO-BACK-N NETWORK EMULATOR: VERSION 1.1 J.F.Kurose
This code should be used for unidirectional or bidirectional
data transfer protocols from A to B and B to A.
Network properties:
- one way network delay averages five time units (longer if there
are other messages in the channel for GBN), but can be larger
- packets can be corrupted (either the header or the data portion)
or lost, according to user-defined probabilities
- packets may be delivered out of order.
Compile as gcc -g project2.c student2.c -o p2
**********************************************************************/
/***********************************************
PACKET QUEUE STUFF
************************************************/
struct PacketNode {
struct pkt *packet;
struct PacketNode *next;
};
void addToQueue(struct pkt *packet, struct PacketNode *packetQueue) {
if (!packetQueue->packet) { //if the packet queue is null, make it the head
packetQueue->packet = packet;
packetQueue->next = 0;
return;
}
struct PacketNode *current = packetQueue;
while (current->next) current = current->next;
struct PacketNode *adding = (struct PacketNode *) malloc(sizeof(struct PacketNode));
adding->packet = packet;
adding->next = 0;
current->next = adding;
}
struct pkt* getNextUp(struct PacketNode *packetQueue) {
if (!packetQueue->packet)
return 0;
return packetQueue->packet;
}
void removeHead(struct PacketNode *packetQueue) {
if (!packetQueue->packet)
return;
//get the next packet to go
struct PacketNode *next = packetQueue->next;
if (next->packet) {
packetQueue->packet = next->packet;
packetQueue->next = next->next;
}
else {
packetQueue->next = 0;
packetQueue->packet = 0;
}
}
int emptyQueue(struct PacketNode *packetQueue) {
return packetQueue->packet == 0;
}
/************************************************
GENERAL VARIABLES
*************************************************/
#define RTT_TIME 10000000000
struct Sender {
int currentSequenceNumber;
int queueSequenceNumber;
enum State state;
struct PacketNode *bufferQueue;
};
struct Receiver {
int expected_seq;
int received;
};
enum State { WAITING_FOR_ACK, WAITING_FOR_DATA };
struct Sender aSender;
struct Receiver aReceiver;
struct Sender bSender;
struct Receiver bReceiver;
/********* STUDENTS WRITE THE NEXT SEVEN ROUTINES *********/
/*
* The routines you will write are detailed below. As noted above,
* such procedures in real-life would be part of the operating system,
* and would be called by other procedures in the operating system.
* All these routines are in layer 4*/
int get_checksum(struct pkt *packet) {
int checksum = 0;
checksum += packet->seqnum;
checksum += packet->acknum;
for (int x = 0; x < MESSAGE_LENGTH; x++) {
checksum += (int) packet->payload[x] * (x + 1);
}
return checksum;
}
int check_sequenceNumber(int given, int expected) {
return given == expected;
}
int check_checksum(struct pkt *packet) {
return get_checksum(packet) == packet->checksum;
}
void NACK(int entity, int sequenceNumber) {
struct pkt *packet = (struct pkt *) malloc(sizeof(struct pkt));
packet->seqnum = sequenceNumber;
packet->acknum = 0; //change later
tolayer3(entity, *packet);
printf("send NACK%d\n", sequenceNumber);
}
void ACK(int entity, int sequenceNumber) {
struct pkt *packet = (struct pkt *) malloc(sizeof(struct pkt));
packet->seqnum = sequenceNumber;
packet->acknum = 1; //change later
tolayer3(entity, *packet);
printf("send ACK%d\n", sequenceNumber);
}
int isACK(struct pkt *packet, int sequenceNumber) {
return packet->seqnum == sequenceNumber && packet->acknum == 1; //will need to modify for alternative bit
}
void retransmit(int entity, struct PacketNode *packetQueue) {
startTimer(entity, RTT_TIME);
if(!emptyQueue(packetQueue))
tolayer3(entity, *getNextUp(packetQueue));
}
void transmitNext(int entity, struct PacketNode *packetQueue) {
startTimer(entity, RTT_TIME);
if (!emptyQueue(packetQueue))
tolayer3(entity, *getNextUp(packetQueue));
}
/*
* A_output(message), where message is a structure of type msg, containing
* data to be sent to the B-side. This routine will be called whenever the
* upper layer at the sending side (A) has a message to send. It is the job
* of your protocol to insure that the data in such a message is delivered
* in-order, and correctly, to the receiving side upper layer.
*/
void A_output(struct msg message) {
/*
Format into a packet and add to the queue
*/
struct pkt *packet = (struct pkt *) malloc(sizeof(struct pkt));
packet->seqnum = aSender.queueSequenceNumber;
packet->acknum = 0;
aSender.queueSequenceNumber++;
for (int x = 0; x < MESSAGE_LENGTH; x++) {
packet->payload[x] = message.data[x];
}
packet->checksum = get_checksum(packet);
addToQueue(packet, aSender.bufferQueue);
if (aSender.state == WAITING_FOR_DATA) { //send the packet
transmitNext(AEntity, aSender.bufferQueue);
aSender.state = WAITING_FOR_ACK;
printf("send pkt%d\n", getNextUp(aSender.bufferQueue)->seqnum);
}
}
/*
* Just like A_output, but residing on the B side. USED only when the
* implementation is bi-directional.
*/
void B_output(struct msg message) {
}
/*
* A_input(packet), where packet is a structure of type pkt. This routine
* will be called whenever a packet sent from the B-side (i.e., as a result
* of a tolayer3() being done by a B-side procedure) arrives at the A-side.
* packet is the (possibly corrupted) packet sent from the B-side.
*/
void A_input(struct pkt packet) {
stopTimer(AEntity);
if (isACK(&packet, aSender.currentSequenceNumber)) {
removeHead(aSender.bufferQueue);
aSender.currentSequenceNumber++;
if (!emptyQueue(aSender.bufferQueue)) {
transmitNext(AEntity, aSender.bufferQueue);
}
else {
aSender.state = WAITING_FOR_DATA;
}
}
else { //it is an NACK
retransmit(AEntity, aSender.bufferQueue);
}
}
/*
* A_timerinterrupt() This routine will be called when A's timer expires
* (thus generating a timer interrupt). You'll probably want to use this
* routine to control the retransmission of packets. See starttimer()
* and stoptimer() in the writeup for how the timer is started and stopped.
*/
void A_timerinterrupt() {
//printf("Luke: A_timerInterrupt() called\n");
retransmit(AEntity, aSender.bufferQueue);
}
/* The following routine will be called once (only) before any other */
/* entity A routines are called. You can use it to do any initialization */
void A_init() {
aSender.bufferQueue = (struct PacketNode *) malloc(sizeof(struct PacketNode));
aSender.bufferQueue->packet = 0;
aSender.bufferQueue->next = 0;
aSender.state = WAITING_FOR_DATA;
aSender.currentSequenceNumber = 1;
aSender.queueSequenceNumber = 1;
}
/*
* Note that with simplex transfer from A-to-B, there is no routine B_output()
*/
/*
* B_input(packet),where packet is a structure of type pkt. This routine
* will be called whenever a packet sent from the A-side (i.e., as a result
* of a tolayer3() being done by a A-side procedure) arrives at the B-side.
* packet is the (possibly corrupted) packet sent from the A-side.
*/
void B_input(struct pkt packet) {
if (!check_sequenceNumber(packet.seqnum, bReceiver.expected_seq) || !check_checksum(&packet)) {
printf("recv pkt%d, discard\n", packet.seqnum);
ACK(BEntity, bReceiver.expected_seq - 1); //need to change later
}
else {
printf("recv pkt%d, deliver\n", packet.seqnum);
if (bReceiver.expected_seq == packet.seqnum && bReceiver.received) {
bReceiver.received = 0;
}
struct msg *message = (struct msg *) malloc(sizeof(struct msg));
for (int x = 0; x < MESSAGE_LENGTH; x++) {
message->data[x] = packet.payload[x];
}
tolayer5(BEntity, *message);
ACK(BEntity, packet.seqnum); //need a way to send ACKS again and again
bReceiver.expected_seq++;
bReceiver.received = 1;
}
}
/*
* B_timerinterrupt() This routine will be called when B's timer expires
* (thus generating a timer interrupt). You'll probably want to use this
* routine to control the retransmission of packets. See starttimer()
* and stoptimer() in the writeup for how the timer is started and stopped.
*/
void B_timerinterrupt() {
}
/*
* The following routine will be called once (only) before any other
* entity B routines are called. You can use it to do any initialization
*/
void B_init() {
bReceiver.expected_seq = 1;
}
|
C
|
/*
* anSematico.c
*
* Created on: 10/09/2016
* Authors:
* Hugo Dionizio Santos
*/
#include "anSemantico.h"
SymbolTable typeChecking(ParseTree pTree) {
SymbolTable sTable;
printf ("Checando semântica da sequência e gerando tabela de símbolos...\n");
return sTable;
}
SymbolTable objectBinding(ParseTree pTree) {
SymbolTable sTable;
printf("Ligando código da árvore sintática para a tabela de símbolos...\n");
return sTable;
}
SymbolTable definitiveAssigment(ParseTree pTree) {
SymbolTable sTable;
printf("Atribuindo valores, definitivamente, da árvore sintática para a tabela de símbolos...\n");
return sTable;
}
|
C
|
//
// MergeSort.c
// MergeSort
//
// Created by T Moore on 4/2/15.
// // Pending Review 4/18/18
// Note on 14 April 19 - This merge sort algorithm is hard coded - need to re do for X amount of line merges
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <string.h>
// declare a struct for the line
typedef struct
{
int size;
int *line;
}SEGMENT;
typedef struct
{
SEGMENT segment1;
SEGMENT segment2;
}MERGESEGMENT;
// declare a global variable for the array size
static const int ARRAYSIZE = 50;
int SPLITSIZE;
// this function is a helper method to pass into the qsort function
// if return value is positive it will swap then go to next pair
// if its negative it does not swap
int qSortHelper(const void *x, const void *y)
{
int xPointer;
int yPointer;
xPointer = *(int*)x;// since parameter is void we must cast it
yPointer = *(int*)y;
return( xPointer-yPointer);
}
static void *sortingThread(void *arg)
{
int *arr = (int*)arg;
qsort(arr,SPLITSIZE,sizeof(int),qSortHelper); // last arg is a function pointer
printf("Sorted %d elements.\n",SPLITSIZE);
return (void*) arr;
}
static void *mergingThread(void *arg)
{
MERGESEGMENT segs = *(MERGESEGMENT*)arg;
// make local segment variables to be used for comparison
SEGMENT x, y, mergedSegment;
x.line = segs.segment1.line;
x.size = segs.segment1.size;
y.line = segs.segment2.line;
y.size = segs.segment2.size;
int offset =0; // to keep track of the next position to write to the new segment
int i ; // for the loop;
int dupCount = 0;
int sizeDifference = 0;
int differenceCounter =0;
int *sizeDifferencePointer;
// allocate memory for merged segment
mergedSegment.line = malloc((x.size*y.size)* sizeof(int));
mergedSegment.size = x.size+y.size;
// for the size of the new segment, place integers in specific memory location
if (x.size!= y.size)
{
sizeDifference =1;// true;
}
for (i = 0; i <x.size; i++)
{
int a = *(x.line+i);
int b = *(y.line+i);
// break out of loop if there is a size differece, assuming segment one is the larger one
if (differenceCounter== y.size)
{
// get location so we can tack the rest of segment one onto the final segment
sizeDifferencePointer = (x.line+i);
break;
}
// if they are equal
if (a == b )
{
dupCount++;
*(mergedSegment.line+offset) = a;
offset++;
*(mergedSegment.line+offset) = b;
offset++;
}
if (a < b)
{
*(mergedSegment.line+offset) = a;
offset++;
*(mergedSegment.line+offset) = b;
offset++;
}
if (a > b)
{
*(mergedSegment.line+offset) = b;
offset++;
*(mergedSegment.line+offset) = a;
offset++;
}
differenceCounter ++;
}
// if segments are different sizes, then tack on the remainder of segment one into the merged segment
for (i = 0; i < (mergedSegment.size-y.size); i++)
{
*(mergedSegment.line+offset+i)= *(x.line+(y.size)+i);
}
int temp;
// do a final swap to get one list of sorted elements after they have merged
for( i = 0; i < offset-1; i ++)
{
int leftElement = *(mergedSegment.line+i);
int rightElement = *(mergedSegment .line+i+1);
if (leftElement>rightElement) // if final merge out of order
{
// swap it
temp = leftElement;
*(mergedSegment.line+i) = rightElement;
*(mergedSegment .line+i+1) = temp;
}
}
printf("Merged %d elements with %d elements with %d duplicates\n",x.size,y.size,dupCount);
/*
for (i = 0; i <= mergedSegment.size-1; i++)
{
printf( "%d ",*(mergedSegment.line+i));
}
*/
//free(mergedSegment.line); was having an issued if i free the memory
return (void*)mergedSegment.line; // returns an integer pointer
}
int main(int argc, const char * argv[])
{
// make sure user entered a single command line argument
assert(argc==2);
// declare and initialize variables
int randArray[ARRAYSIZE]; // static array of size 50 with all values with an initial value of 0
int numOfSplits = atof(argv[1]); // number of threads required
pthread_t splitThreads[numOfSplits];
int i, j;// variables for loop
int arrPos = 0; // variable to keep count of index when splitting random array into segments
int sizeOfEachSegment = ARRAYSIZE/numOfSplits; // the length of each segment
SPLITSIZE = sizeOfEachSegment;
int splitArray[numOfSplits][sizeOfEachSegment]; //declare a 2D array to hold all of our numbers
int *sortedArr[numOfSplits];// an array of integer pointers to hold the sorted segments
int *sortedSegment; // temporary integer pointer to be put in sortedArr
int *finalSegment; // for the final list
SEGMENT segments[numOfSplits]; // array of structs to hold each segment
//test to see if valid command line arguments
if (numOfSplits != 2 && numOfSplits != 5 && numOfSplits != 10)
{
printf("ERROR:As instructed. You must test the program with 2, 5 or 10.");
exit(1);
}
//generates array with random numbers
for (i = 0; i < ARRAYSIZE; i++)
{
randArray[i]= rand()%100+1;
}
// split the random array into a 2D array , each row containing a different segement that will be sorted by threads
for (i = 0; i<numOfSplits; i++)
{
for (j = 0; j <sizeOfEachSegment; j++) {
splitArray[i][j] = randArray[arrPos];
arrPos++;// keep track of where we are in randArray
}
}
// print the array
printf("Original segments: \n");
for (i = 0; i<numOfSplits; i++)
{
for (j = 0; j <sizeOfEachSegment; j++) {
printf("%d ",splitArray[i][j]);
}
printf("\n");
}
// sort each individual segmentwith threads
for (i = 0; i<numOfSplits; i++)
{
sortedSegment = splitArray[i];
segments[i].line = sortedSegment;
segments[i].size = SPLITSIZE;
pthread_create(&splitThreads[i], NULL, &sortingThread,sortedSegment);
}
// wait for threads to finish, store each return value in an array in integer pointers
for(i = 0; i < numOfSplits; ++i)
pthread_join(splitThreads[i], (void**)&sortedArr[i]);
printf("Segments after multithreaded sort:\n");
// print segments
for (i = 0; i < numOfSplits; i++)
{
for (j = 0; j< sizeOfEachSegment; j++)
{
printf("%d ",segments[i].line[j]);
}
printf("\n");
}
// place the segments in their prespective mergeset structures to be merged.
// for this specific program, there are 3 test cases, implementation would need to be changed
// if program was tested with anything other than 2, 5, and 10 splits.
if (numOfSplits == 2)
{
pthread_t mergeThread; //for the number of threads
// create mergesegment
MERGESEGMENT newMerge;
SEGMENT final;
// allocate memory for the line
// newmerge.segment1.line = malloc(sizeOfEachSegment*sizeof(int));
newMerge.segment1.line = segments[0].line;
newMerge.segment1.size = segments[0].size;
// allocate memory for the line
// newmerge.segment2.line = malloc(sizeOfEachSegment*sizeof(int));
newMerge.segment2.line = segments[1].line;
newMerge.segment2.size = segments[1].size;
// allocate memory for the final segment that will be returned as an integer pointer from the thread function
finalSegment = malloc((2*SPLITSIZE)* sizeof(int));
// launch a thread to merge the two splits
pthread_create(&mergeThread, NULL,&mergingThread,(void*)&newMerge);
// wait for the thread to terminate, get value
pthread_join(mergeThread, (void**)&final.line);
final.size = 2*SPLITSIZE;
//print final sorted list
for (i = 0; i <final.size; i++)
{
printf( "%d\n",*(final.line+i));
}
}
else if (numOfSplits == 5)
{
pthread_t mergeThread[4]; //for the number of threads
SEGMENT roundOneResult;
SEGMENT roundTwoResult;
SEGMENT roundThreeResult;
SEGMENT finalResult;
MERGESEGMENT newMerge[4]; // for three threads to sort first four rows
// ROUND 1
newMerge[0].segment1.line = segments[0].line;
newMerge[0].segment2.line = segments[1].line;
newMerge[0].segment1.size = segments[0].size;
newMerge[0].segment2.size = segments[1].size;
// round one will sort first two rows and return sorted list
pthread_create(&mergeThread[0], NULL,&mergingThread,(void*)&newMerge[0]);
//ROUND 2
// do the same for rows 3 and 4 with a thread
newMerge[1].segment1.line = segments[2].line;
newMerge[1].segment2.line = segments[3].line;
newMerge[1].segment1.size = segments[2].size;
newMerge[1].segment2.size = segments[3].size;
// round two will sort first two rows and return sorted list
pthread_create(&mergeThread[1], NULL,&mergingThread,(void*)&newMerge[1]);
// wait for the first thread to terminate, get value
pthread_join(mergeThread[0], (void**)&roundOneResult.line);
// wait for the second thread to terminate, get value
pthread_join(mergeThread[1], (void**)&roundTwoResult.line);
// manually set the sizes for the new merged segment (bad implementation)
roundOneResult.size = SPLITSIZE+SPLITSIZE;
roundTwoResult.size = SPLITSIZE+SPLITSIZE;
//ROUND 3
// do the same for rows 3 and 4 with a thread
// store round one and two results in a new segment to be merged together
newMerge[2].segment1.line = roundOneResult.line;
newMerge[2].segment2.line = roundTwoResult.line;
newMerge[2].segment1.size = roundOneResult.size;
newMerge[2].segment2.size = roundTwoResult.size;
// round three will sort first two rows and return sorted list
pthread_create(&mergeThread[2], NULL,&mergingThread,(void*)&newMerge[2]);
// wait for the thread to terminate, get value
pthread_join(mergeThread[2], (void**)&roundThreeResult.line);
roundThreeResult.size= SPLITSIZE*4;
//FINAL ROUND, MERGING WITH LAST ROW
newMerge[3].segment1.line = roundThreeResult.line;
newMerge[3].segment2.line = segments[4].line;
newMerge[3].segment1.size = roundThreeResult.size;
newMerge[3].segment2.size = segments[4].size;
finalResult.line = malloc((SPLITSIZE*5) * sizeof(int));
// final will sort last two rows and return final sorted list
pthread_create(&mergeThread[3], NULL,&mergingThread,(void*)&newMerge[3]);
// wait for the thread to terminate, get value
pthread_join(mergeThread[3], (void**)&finalResult.line);
finalResult.size = (SPLITSIZE*4)+SPLITSIZE;
// print the return value
for (i = 0; i <finalResult.size; i++)
{
printf( "%d \n",*(finalResult.line+i));
}
}
else // num of splits has to be 10
{
// we will need 8 threads for this case
pthread_t mergeThread[9]; //for the number of threads
SEGMENT result[9];
MERGESEGMENT newMerge[9];// 8 merges 1 for each thread
// ROUND 1
// this round will have five consecutive threads merging the first 10 lines
//lines 1 and 2
newMerge[0].segment1.line = segments[0].line;
newMerge[0].segment2.line = segments[1].line;
newMerge[0].segment1.size = segments[0].size;
newMerge[0].segment2.size = segments[1].size;
//lines 3 and 4
newMerge[1].segment1.line = segments[2].line;
newMerge[1].segment2.line = segments[3].line;
newMerge[1].segment1.size = segments[2].size;
newMerge[1].segment2.size = segments[3].size;
//lines 5 and 6
newMerge[2].segment1.line = segments[4].line;
newMerge[2].segment2.line = segments[5].line;
newMerge[2].segment1.size = segments[4].size;
newMerge[2].segment2.size = segments[5].size;
//lines 7 and 8
newMerge[3].segment1.line = segments[6].line;
newMerge[3].segment2.line = segments[7].line;
newMerge[3].segment1.size = segments[6].size;
newMerge[3].segment2.size = segments[7].size;
//lines 9 and 10
newMerge[4].segment1.line = segments[8].line;
newMerge[4].segment2.line = segments[9].line;
newMerge[4].segment1.size = segments[8].size;
newMerge[4].segment2.size = segments[9].size;
pthread_create(&mergeThread[0], NULL,&mergingThread,(void*)&newMerge[0]);
pthread_create(&mergeThread[1], NULL,&mergingThread,(void*)&newMerge[1]);
pthread_create(&mergeThread[2], NULL,&mergingThread,(void*)&newMerge[2]);
pthread_create(&mergeThread[3], NULL,&mergingThread,(void*)&newMerge[3]);
pthread_create(&mergeThread[4], NULL,&mergingThread,(void*)&newMerge[4]);
pthread_join(mergeThread[0], (void**)&result[0].line);
// result[0].size = (numOfSplits/sizeOfEachSegment)*2;
// in a loop. wait for all threads to terminate and store the strings in an array
for (i = 0; i<5; i++)
{
// wait for the first thread to terminate, get value
pthread_join(mergeThread[i], (void**)&result[i].line);
// manually set the sizes for the new merged segment (bad implementation)
result[i].size = sizeOfEachSegment*2;
}
// ROUND 2
// entails two parallel threads which sort result 1 2 3 4.. (5 will be done with the last sort)
//lines 3 and 4
newMerge[5].segment1.line = result[0].line;
newMerge[5].segment2.line = result[1].line;
newMerge[5].segment1.size = result[0].size;
newMerge[5].segment2.size = result[1].size;
pthread_create(&mergeThread[5], NULL,&mergingThread,(void*)&newMerge[5]);
//lines 3 and 4
newMerge[6].segment1.line = result[2].line;
newMerge[6].segment2.line = result[3].line;
newMerge[6].segment1.size = result[2].size;
newMerge[6].segment2.size = result[3].size;
pthread_create(&mergeThread[6], NULL,&mergingThread,(void*)&newMerge[6]);
// wait for these two trheads to finish and store the result in array positoin 6 and 7
// wait for the first thread to terminate, get value
pthread_join(mergeThread[5], (void**)&result[5].line);
// wait for the second thread to terminate, get value
pthread_join(mergeThread[6], (void**)&result[6].line);
// manually set the sizes of the two lines
result[5].size = sizeOfEachSegment*4;
result[6].size = sizeOfEachSegment*4;
//ROUND 3
// lauch a single merge thread with rows 6 and 7 and store result in position 8,
// then merge 8 and 5 in round 6 to get final result
// store round one and two results in a new segment to be merged together
newMerge[7].segment1.line = result[5].line;
newMerge[7].segment2.line = result[6].line;
newMerge[7].segment1.size = result[5].size;
newMerge[7].segment2.size = result[6].size;
// round three will sort first two rows and return sorted list
pthread_create(&mergeThread[7], NULL,&mergingThread,(void*)&newMerge[7]);
// wait for the thread to terminate, get value
pthread_join(mergeThread[7], (void**)&result[7].line);
result[7].size = sizeOfEachSegment*8;
//FINAL ROUND, MERGING WITH LAST ROW
newMerge[8].segment1.line = result[7].line;
newMerge[8].segment2.line = result[4].line;
newMerge[8].segment1.size = result[7].size;
newMerge[8].segment2.size = result[4].size;
result[8].line = malloc((SPLITSIZE*10) * sizeof(int));
// final will sort last two rows and return final sorted list
pthread_create(&mergeThread[8], NULL,&mergingThread,(void*)&newMerge[8]);
// wait for the thread to terminate, get value
pthread_join(mergeThread[8], (void**)&result[8].line);
result[8].size = (SPLITSIZE*10);
// print the return value
for (i = 0; i <result[8].size; i++)
{
printf( "%d \n",*(result[8].line+i));
}
}
return 0;
}
|
C
|
#include "stdio.h"
// Lucas Marchesani
//4Feb19
//Lab4B.c
int main ()
{
int UserInput = 0;
printf("Please input a character please:"); // prompts for userinput
UserInput = getc(stdin); // saves the character and reads it in from stdin
printf("The previous character to your input is "); // prints it
putc((UserInput - 1), stdout);
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "insertion_sort.h"
void insertion_sort(int** numbers, size_t size){
size_t j;
for (j = 1; j < size; j++) {
int key = (*numbers)[j];
int i = j - 1;
while(i >= 0 && (*numbers)[i] > key) {
(*numbers)[i+1] = (*numbers)[i];
i--;
}
(*numbers)[i+1] = key;
}
}
|
C
|
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
void init(void)
{
GLfloat mat_specular[] = { 1.0, -1.0, -1.0, 1.0 };
GLfloat mat_diffuse[] = { 0.8, -1.0, -1.0, 1.0 };
GLfloat mat_ambient[] = { 0.2, -1.0, -1.0, 1.0 };
GLfloat mat_shininess[] = { 10.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
GLfloat light_ambient[] = {1.0, 1.0, 0.0, 1.0};
GLfloat light_diffuse[] = {1.0, 1.0, 0.0, 1.0};
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSolidSphere (1.0, 20, 16);
glFlush ();
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho (-1.5, 1.5, -1.5*(GLfloat)h/(GLfloat)w,
1.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0);
else
glOrtho (-1.5*(GLfloat)w/(GLfloat)h,
1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
|
C
|
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<map>
#include<vector>
#include<list>
#include<set>
#include<queue>
#include<cassert>
#include<sstream>
#include<string>
#include<cmath>
#include<algorithm>
using namespace std;
#define LET(x,a) __typeof(a) x(a)
#define IFOR(i,a,b) for(LET(i,a);i!=(b);++i)
#define EACH(it,v) IFOR(it,v.begin(),v.end())
#define FOR(i,a,b) for(int i=(int)(a) ; i < (int)(b);++i)
#define REP(i,n) FOR(i,0,n)
#define PB push_back
#define MP make_pair
#define EPS 1e-9
#define INF 2000000000
typedef vector<int> VI;
typedef long long LL;
typedef pair<int,int> PI;
#define BUFSIZE (200000)
char outputbuffer[BUFSIZE<<1],inputbuffer[BUFSIZE<<1];
char *outptr=outputbuffer,*ioptr=inputbuffer+BUFSIZE,*ioend=inputbuffer+BUFSIZE;
int input_eof=0;
#define putchar(c) (*outptr++ = (c))
#define getchar() ({if (ioptr >= ioend) init_input(); *ioptr++;})
#define eof() (ioptr>=ioend && input_eof)
#define eoln() ({if(ioptr >= ioend) init_input(); *ioptr == '\n';})
void init_input(){
if (input_eof)
return;
int existing = BUFSIZE - (ioend - inputbuffer);
memcpy(inputbuffer, ioend, existing);
int wanted = ioend - inputbuffer;
int count=fread(inputbuffer + existing, 1, wanted, stdin);
if (count < wanted)
input_eof = 1;
ioend = inputbuffer + BUFSIZE - (wanted - count);
while (*--ioend > ' ');
ioend++;
ioptr=inputbuffer;
}
inline void non_whitespace(){
for(;;){
if(ioptr>=ioend)
init_input();
if(*ioptr>' ')
return;
ioptr++;
}
}
void flush_output(){
fwrite(outputbuffer,1,outptr-outputbuffer,stdout);
outptr=outputbuffer;
}
inline void check_output(){
if(outptr>=outputbuffer+BUFSIZE)
flush_output();
}
inline int getint(){
non_whitespace();
int neg=0;
if(*ioptr=='-'){
ioptr++;
neg=1;
}
int n=0;
while(*ioptr>' ')
n=(n<<3)+(n<<1)+*ioptr++-'0';
ioptr++;
if(neg)
n=-n;
return n;
}
inline void putint(int n){
char buffer[12];
int i=0,n2;
do{
n2=n/10;
buffer[i++]=n-(n2<<3)-(n2<<1)+'0';
}while(n=n2);
while(i)
putchar(buffer[--i]);
check_output();
}
inline void putstr(char *str){
int i=0;
while(str[i]){putchar(str[i]);i++;}
check_output();
return;
}
int n,k,N,n1;
int arr[901][901];
LL row[1000][20],col[1000][20],grid[1000][20],max1,rowCnt[1000],colCnt[1000];
PI rowC[1000],colC[1000];
void update(int x,int y,int val){
val--;
int c=val/60,v=val%60;
row[x][c]|=(1LL<<v);
col[y][c]|=(1LL<<v);
grid[(x/n1)*n1+(y/n1)][c]|=(1LL<<v);
return;
}
int firstZero(LL x){
int cnt=0;
while(x){
if(!(x&1))return cnt;
cnt++;x/=2;
}
return cnt;
}
int getOption(int x,int y,int overlap){
int gr = (x/n1)*n1+(y/n1);
if(overlap==3){
REP(i,n){
LL tmp=(row[x][i])|(col[y][i])|(grid[gr][i]);
if(tmp==max1)continue;
int cal = firstZero(tmp);
if(60*i+cal>=N)return 0;
return 60*i+cal+1;
}
}
else if(overlap==2){
REP(i,n){
LL tmp1=row[x][i]|col[y][i],tmp2=row[x][i]|grid[gr][i],tmp3=col[y][i]|grid[gr][i];
if(tmp1==max1 && tmp2==max1 && tmp3==max1)continue;
LL tmp=min(tmp1,min(tmp2,tmp3));
int cal = firstZero(tmp);
if(60*i+cal>=N)return 0;
return 60*i+cal+1;
}
}
else if(overlap==1){
REP(i,n){
LL tmp1=row[x][i],tmp2=col[y][i],tmp3=grid[gr][i];
if(tmp1==max1 && tmp2==max1 && tmp3==max1)continue;
LL tmp;
if(tmp1!=max1)tmp=tmp1;
else if(tmp2!=max1)tmp=tmp2;
else if(tmp3!=max1)tmp=tmp3;
int cal = firstZero(tmp);
if(60*i+cal>=N)return 0;
return 60*i+cal+1;
}
}
return 0;
}
int main(){
max1=(1LL<<60)-1;
init_input();
n=getint();k=getint();
N=n*n;
n1=n;
n =(int)ceil(N/60.0);
REP(i,k){
int x,y,val;
x=getint();y=getint();
val=getint();
x--;y--;
arr[x][y]=val;
update(x,y,val);
}
int lim=N*N,sz=lim;
int p[lim+1];
REP(i,lim)p[i]=i;
REP(level,3){
sz = lim;
REP(times,lim){
int index = rand()%sz;
int x=p[index]/N,y=p[index]%N;
swap(p[index],p[sz-1]);
sz--;
if(!arr[x][y]){
int tmp = getOption(x,y,3-level);
arr[x][y]=tmp;
if(tmp)update(x,y,tmp);
}
}
}
REP(x,N){
REP(y,N){
putint(arr[x][y]);putchar(' ');
}
putchar('\n');
}
flush_output();
return 0;
}
|
C
|
/**
* @file
* @brief Main code of the client application
*/
#include "cli.h"
#include "multipath.h"
#include "mp_local.h"
#include "iniparser.h"
//#define exerror(c,z) {fprintf(stderr,"%s Errno: %d\n",c, z); exit(z);}
/**
* Main function of client application that parses the CLI input and sends that to the server.
*/
int main( int argc, char ** argv )
{
int i, sock6, st, port, off = 0, rv;
struct sockaddr_in6 sockaddr;
unsigned int socklen = sizeof(sockaddr);
char ccmd[SIZE_DGRAM];
char *cmd;
memset(ccmd, 0, SIZE_DGRAM);
ccmd[0]=CMD_LOCAL_REPLY;
cmd = ccmd+4;
long timeout = 5;
port = 65010;
dictionary* conf;
conf = iniparser_load("conf/interface.conf");
if(conf == NULL)
{
printf("Configuration file is not present, or it is invalid.\nDefault values:\tCMD_port: %d\n\t\tcmd_timeout: %ld\n",port,timeout);
}
else
{
port = iniparser_getint(conf,"general:cmdport_local", 60456);
timeout = iniparser_getint(conf, "general:cmd_timeout", 15);
printf("mpt configuration:\n\tLocal cmd port: %d\n\tcmd timeout: %ld\n",port,timeout);
}
timeout = timeout *1000; // convert to msec
if (argc == 1 || (argc==2 && (strncmp(argv[1], "-h", 2)==0 || !strcmp(argv[1], "--help")))) {
printf("\n");
printf(" Usage: mpt [-6] [-port_number] mpt_command mpt_args\n");
printf(" -6 : Use IPv6 to communicate with mptsrv\n");
printf(" -port_number : The port number of the mptsrv (default: %d)\n", port);
printf("\n");
printf(" Commands:\n\n");
printf(HELP);
return 1;
}
memset(&sockaddr, 0, socklen);
st = 1;
if (strcmp(argv[1], "-6")==0) {
inet_pton(AF_INET6, "::1", &(sockaddr.sin6_addr));
st = 2;
}
else
inet_pton(AF_INET6, "::FFFF:127.0.0.1", &(sockaddr.sin6_addr));
if (argc > st && argv[st][0]=='-') {
port = atoi(&argv[st][1]);
st += 1;
printf("Using CMD_port number from command line argument: %d \n", port);
}
sockaddr.sin6_port = htons(port);
sockaddr.sin6_family = AF_INET6;
if ((sock6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
exerror("Socket creation error.", errno);
setsockopt(sock6, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&off, sizeof off);
// IPV6_only is turned off, so this socket will be used for IPv4 too.
strcpy(cmd, "");
for (i=st; i<argc; i++) {
if (i != st) strcat(cmd, " ");
strcat(cmd, argv[i]);
}
if((rv = parse_cmd(cmd)) == PARSE_OK) {
sendto(sock6, ccmd, strlen(cmd)+5, 0, (struct sockaddr *)&sockaddr, socklen);
for(i=0; i<2; ) {
st = getcmd(sock6, ccmd, SIZE_DGRAM, 0, (struct sockaddr *)&sockaddr, &socklen, timeout);
// printf("i:%d st: %d ccmd0=%X\n",i, st, ccmd[0]);
if ((unsigned char)ccmd[0] == (unsigned char)CMD_LOCAL_REPLY_END) break;
if (st <= 4) { printf("ERROR: No answer from mptsrv - unsuccessful receive %d\n", ++i); }
if (st > 4) printf("%s\n", cmd);
}
}
iniparser_freedict(conf);
close(sock6);
return rv;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include "zone.h"
int main(int argc, char** argv) {
struct donnees maFile;
key_t clef;
int idFile;
int ret;
//creation de la file
clef = ftok("/tmp/5678", 'a'); // generation d'une clef
idFile = msgget(clef, IPC_CREAT | 0666);//Autorisation en R/W (Read/ write)
if (idFile==-1)
{
//le segment n'existe pas
if(errno!=EEXIST)
{
printf("pb msgget : %s\n",strerror(errno));
exit(errno);
}
}
//Mise a jour pression et temperature
while(1){
//lecture des temperatures
ret=msgrcv(idFile,(void *)&maFile,sizeof(maFile),2,IPC_NOWAIT);
if(ret!=-1) //pas d'erreur de lecture -> afficher le message
{
printf("temp : %s\n",maFile.texte);
}
//lecture des pressions
ret=msgrcv(idFile,(void *)&maFile,sizeof(maFile),4,IPC_NOWAIT);
if(ret!=-1) //pas d'erreur de lecture -> afficher le message
{
printf("temp : %s\n",maFile.texte);
}
//lecture des ordres
ret=msgrcv(idFile,(void *)&maFile,sizeof(maFile),3,IPC_NOWAIT);
if(ret!=-1) //pas d'erreur de lecture -> afficher le message
{
printf("temp : %s\n",maFile.texte);
}
sleep(1);
}
return (EXIT_SUCCESS);
}
|
C
|
/*
* Programador: Hernandez Rojas Mara Alexandra Practica 12
* Este programa define las estructuras de nodo y lista*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "e1.h"
void insertar(INFO info, LIST *l){
if(l!=NULL){
if(l->head == NULL){
l->head = crear_nodo();
l->head->info = info;
return;
}else{
NODE *nuevo = crear_nodo();
//strcpy(nuevo->info.nombre , info.nombre);
//strcpy(nuevo->info.apellido, info.apellido);
nuevo->info = info;
nuevo->next = l->head;
l->head->prev = nuevo;
l->head = nuevo;
}
}
}
LIST *crear_lista(){
LIST *l =(LIST*) malloc(sizeof(LIST));
l->head = NULL;
l->tail = NULL;
return l;
}
void eliminar(LIST *l){
if(l->head!=NULL){
borrar_nodos(l->head);
}else{
free(l);
}
}
NODE *crear_nodo(){
NODE *n =(NODE*) malloc(sizeof(NODE));
n->next = NULL;
n->prev = NULL;
strcpy(n->info.nombre , " ");
strcpy(n->info.apellido , " ");
return n;
}
void borrar_nodos(NODE *n){
if (n->next!=NULL ){ //Caso recursivo
borrar_nodos(n->next);
}else{
n->prev= NULL; //Caso base
free(n);
}
}
void imprimir(LIST *l){
for(NODE *i = l->head; i!=NULL; i = i->next){
printf("%s, %s\n", i->info.nombre, i->info.apellido);
}
}
/*Vamos a borrar los ultimos nodos hasta que ya no queda ninguno
*Caso base sirve para darle fin a las fnciones recursivas
*si no hay caso base nunca va a parar las llamadas recursivas
*NO sólo hay errores del código hay errores de lógica del programa
*Al momento de insetar funciona un poco como una pila
*/
|
C
|
//Copyright:LPH
//Author:
//Date:2020-11-26~2020-11-30
//Description:ƽĻܺ
#include"AVL.h"
AVLNode* CreateAVLNode(ElemType x) //ƽĽ㴴
{
AVLNode* s = (AVLNode*)malloc(sizeof(AVLNode));
assert(s != NULL);
s->BF = 0; //ʼƽ
s->lchild = s->rchild = NULL;
s->data = x;
return s;
}
void InitAVLTree(AVLTree* T) //ƽĸڵʼ
{
T->root = NULL;
}
void DestroyAVLTree(AVLTree* T) //ƽ
{
assert(T->root != NULL);
_DestroyAVLTree(T->root);
}
static void _DestroyAVLTree(AVLNode* p) //ƽӺ
{
if (p != NULL)
{
AVLNode* ptemp = p;
_DestroyAVLTree(ptemp->lchild);
_DestroyAVLTree(ptemp->rchild);
free(ptemp);
}
}
BOOL InsertAVLTree(AVLTree* T, ElemType x) // ƽIJ빹
{
return _InsertAVLTree(&(T->root), x);
}
static BOOL _InsertAVLTree(AVLNode** node, ElemType x) //빹Ӻ,ָҪָ
{
if (*node == NULL)
{
*node = CreateAVLNode(x);
return TRUE;
}
else
{
if ((*node)->data == x)
{
return FALSE; //ظ
}
else if ((*node)->data > x) //ֵСڽ
{
_InsertAVLTree(&((*node)->lchild), x);
}
else //ֵڽ
{
_InsertAVLTree(&((*node)->rchild), x);
}
}
return FALSE;
}
BOOL InsertAVLTreeIterate(AVLTree* T, ElemType x) // ƽĵ빹
{
return _InsertAVLTreeIterate(&(T->root), x);
}
static BOOL _InsertAVLTreeIterate(AVLNode** node, ElemType x) //빹Ӻ,ָҪָ
{
if (*node == NULL) //ûиڵ
{
*node = CreateAVLNode(x);
return TRUE;
}
else
{
LinkStack stack;
InitLinkStack(&stack); //ʼջ
AVLNode* ptemp = *node; //ѰҲλ
AVLNode* parent = NULL; //¼λõֱ˫
while (ptemp != NULL)
{
parent = ptemp; //¼һηʵĽ
Push_Stack(&stack, parent); //ڵ;Ƚջ
if (ptemp->data == x) //ظʧ
{
return FALSE;
}
ptemp = ((ptemp->data > x) ? ptemp->lchild : ptemp->rchild);
}
ptemp = CreateAVLNode(x);
if (parent->data > x) //ڵڲ
{
parent->lchild = ptemp;
}
else //ڵСڲ
{
parent->rchild = ptemp;
}
//Copyright:LPH
//Author:
//Date:2020-11-29
//Description: ջڵ;ƽBFֵBFֵ
AVLNode * ParentNode = NULL; //ParentNodeпܻᱻת
while (!isEmpty(stack))
{
Pop_Stack(&stack, &ParentNode);
//Copyright:LPH
//Author:
//Date:2020-11-29
//Description:ʵƽӸݷ֧仯Ķ̬
//Details:
//@֧˲(߶ȱ)BF = - ( + 1) = - - 1
//@ҷ֧˲(߶ȱ)BF = + 1 - = - + 1
if (ParentNode->lchild == ptemp) //ڵǡõڲ㣬Լ
{
ParentNode->BF--;
}
if (ParentNode->rchild == ptemp) //ڵǡõڲ㣬
{
ParentNode->BF++;
}
if (ParentNode->BF == 0) //ԭȵѾһڲһ
{
break; //ƽΪ0ֱ
}
if(abs(ParentNode->BF) == 1) //ƽӴ1-1
{
ptemp = ParentNode; //ڵеϼƽ
}
else //abs(ParentNode->BF)>14ת
{
/*תϵӦ*/
/*---------------------------------
- RR - RL -
- 0 - 1 -
--------------------------------
- LR - LL -
- 2 - 3 -
----------------------------------*/
int flag[2][2] = { 0,1,2,3 };
int flag_ParentNode = (ParentNode->BF > 0) ? 0 : 1; //жϵǰParentNodeƽӵ
int flag_Ptemp = (ptemp->BF > 0) ? 0 : 1; //жϵǰptempƽӵ
void (*Rotatefunc[4])(AVLNode**) =
{
AVLTreeRotateRR, //RR \ ת
AVLTreeRotateRL, //RL > ת
AVLTreeRotateLR, //LR < ת
AVLTreeRotateLL //LL / ת
};
Rotatefunc[flag[flag_ParentNode][flag_Ptemp]](&ParentNode); //ת
break; //ϣн
}
}
if (isEmpty(stack)) //жջǷֻһԪ
{
//ƽƽռ
*node = ParentNode; //ڵǰУParentNodeǸڵ
}
else
{
//ƽһDzƽ
AVLNode* Head = GetTop(stack); //ջûջȡջ
if (Head->data > ParentNode->data) //ݴС¸
{
Head->lchild = ParentNode;
}
else
{
Head->rchild = ParentNode;
}
}
DestroyLinkStack(&stack); //ݻջ
return TRUE;
}
return FALSE;
}
AVLNode* AVLTreeSearch(AVLTree T, ElemType key) //Ľ
{
assert(T.root != NULL);
return _AVLTreeSearch(T.root, key);
}
static AVLNode* _AVLTreeSearch(AVLNode* node, ElemType key) //ĽӺ
{
if (node != NULL)
{
AVLNode* ptemp = node;
while (ptemp != NULL)
{
if (ptemp->data > key)
{
ptemp = ptemp->lchild;
}
else if(ptemp->data < key)
{
ptemp = ptemp->rchild;
}
else
{
return ptemp;
}
}
}
return NULL;
}
BOOL JudgeAVLTree(AVLTree T) //ƽƽж
{
if (T.root == NULL)
{
return TRUE;
}
else
{
BOOL balance = 0;
_JudgeAVLTree(T.root, &balance);
return balance;
}
}
static void _JudgeAVLTree(AVLNode* T, BOOL* balance) //ƽƽжӺ
{
if (T == NULL) //
{
*balance = TRUE;
return;
}
else if((T->lchild == NULL) && (T->rchild == NULL)) //ΪҶӽ
{
*balance = TRUE;
return;
}
else
{
BOOL LeftBalance = FALSE, RightBalance = FALSE; //ƽ
_JudgeAVLTree(T->rchild, &RightBalance); //״̬
_JudgeAVLTree(T->lchild, &LeftBalance); //״̬
*balance = ((abs(T->BF) <= 1 && LeftBalance == RightBalance == TRUE) ? TRUE : FALSE);
}
}
|
C
|
/// Loads an image file and returns the block of data in 32 bit format. Must be deleted by caller.
char * loadPNG (const char * filename, int & width, int & height);
/// Loads several image files and packs them into a single texture from left to right.
char * loadAtlas (char * filenames [], int numfiles, int & width, int & height);
void savePNG (char * filename, char * data, int & width, int & height);
|
C
|
#include "lists.h"
/**
* delete_dnodeint_at_index - remove node at index of dlistint_t linked list.
* @head: pointer to the head of a linked list.
* @index: index of node that should be deleted, starts at 0.
*
* Return: 1 if it succeeded, -1 if it failed.
*/
int delete_dnodeint_at_index(dlistint_t **head, unsigned int index)
{
unsigned int i = 0;
dlistint_t *copy_head = *head;
if (head == NULL || *head == NULL)
return (-1);
for (; i < index && copy_head; i++)
copy_head = copy_head->next;
if (copy_head == NULL)
return (-1);
if (*head == copy_head)
{
*head = copy_head->next;
}
if (copy_head->next)
{
copy_head->next->prev = copy_head->prev;
}
if (copy_head->prev)
{
copy_head->prev->next = copy_head->next;
}
free(copy_head);
return (1);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 50
typedef struct{
char s_name[20];//스케줄 이름
int s_date[3];//시작일
int e_date[3];//종료일
int importance;//중요도
int complete;//완료유무
}Schedule;
int add_schedule(Schedule *p);//스케줄 추가하는 함수
void read_schedule(Schedule p);//스케줄 한개를 읽는 함수
void list_schedule(Schedule p[], int count);//스케줄을 한번에 다 보여주는 함수
int updata_schedule(Schedule *p);//스케줄을 수정하는 함수
int delete_schedule(Schedule *p);//스케줄 삭제
int select_No(Schedule *p, int count);//삭제나 수정을 하기 위해 제품을 선택하는 함수.(제품의 순서를 return한다.)
void saveFile(Schedule p[], int count);//파일을 저장하는 함수
int loadFile(Schedule p[]);//파일을 가져오는 함수
int complete(Schedule p[]);//파일 완성도를 입력하는 함수
int processivity(Schedule p[],int count);//현재 진행도를 나타내는 함수
void find(Schedule p[],int count);//일정을 찾는 함수
void sortedbyDate(Schedule p[],int count);//날짜별로 정렬하는 함수
void sortedbyImportance(Schedule p[],int count);//중요도별로 정렬하는 함수
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int palindromo(char str[]){
int i;
for(i=0; i < strlen(str)/2; ++i){
if(str[i] != str[strlen(str) - 1 -i]){
return 0;
}
}
return 1;
}
int main(int argc, char *argv[]){
char str[100];
scanf("%s",str);
printf("%s -> %d\n", str, palindromo(str));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* b_to_a.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agrodzin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/28 10:52:22 by agrodzin #+# #+# */
/* Updated: 2019/08/28 10:52:24 by agrodzin ### ########.fr */
/* */
/* ************************************************************************** */
#include "checker.h"
void small_b_to_a(t_args **stack_a, t_args **stack_b, int *sorted_arr)
{
int highest_b;
int check;
int pos;
highest_b = get_highest_arg(*stack_b);
if (highest_b == (*stack_b)->arg)
call_exec(stack_a, stack_b, "pa", 1);
else
{
check = get_value_after_last(*stack_a, sorted_arr, ((*stack_b) ?
(*stack_b)->num_args : 0) + (((*stack_a)) ? (*stack_a)->num_args : 0));
if ((*stack_b)->arg == check || (*stack_b)->arg == sorted_arr[0])
{
call_exec(stack_a, stack_b, "pa", 1);
call_exec(stack_a, stack_b, "ra", 1);
}
else
{
pos = get_pos_arg(*stack_b, get_highest_arg(*stack_b));
if (pos <= (*stack_b)->num_args / 2)
call_exec(stack_a, stack_b, "rrb", 1);
else
call_exec(stack_a, stack_b, "rb", 1);
}
}
}
void long_b_to_a(t_args **stack_a, t_args **stack_b,
int pivot, int *sorted_arr)
{
int check;
if (pivot <= (*stack_b)->arg)
call_exec(stack_a, stack_b, "pa", 1);
else
{
check = get_value_after_last(*stack_a, sorted_arr, ((*stack_b) ?
(*stack_b)->num_args : 0) + (((*stack_a)) ? (*stack_a)->num_args : 0));
if ((*stack_b)->arg == check || (*stack_b)->arg == sorted_arr[0])
{
call_exec(stack_a, stack_b, "pa", 1);
call_exec(stack_a, stack_b, "ra", 1);
}
else
call_exec(stack_a, stack_b, "rb", 1);
}
}
void go_to_a(t_args **stack_a, t_args **stack_b, int *sorted_arr)
{
int len;
int pivot;
if (!*stack_b)
return ;
pivot = get_average(*stack_b);
len = (*stack_b)->num_args;
while ((*stack_b) && len-- > 0)
{
if ((*stack_b)->num_args < 13)
small_b_to_a(stack_a, stack_b, sorted_arr);
else
long_b_to_a(stack_a, stack_b, pivot, sorted_arr);
}
}
|
C
|
/**
* Write a program to add two numbers.
*/
#include<stdio.h>
// #include<conio.h>
int main () {
int a, b, c;
printf("Enter two numbers :");
scanf("%d%d", &a , &b);
c = a + b;
printf("Sum of the two numbers is %d\n", c);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
long n,rv=0,temp; int r;
printf("Enter an Integer\t");
scanf("%ld",&n);
temp=n;
while(n>0)
{
r=n%10;
n=n/10;
rv=rv*10 + r;
}
if (rv==temp)
printf("No is Palindrome");
else
printf("No is Not Palindrome");
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int b=2;
void sec()
{
int a=5;
printf("a = %d\n",a*=a);
printf("b = %d\n\n",++b);
}
double kvadr(int a)
{
a*=a;
return a;
}
void main ()
{
int a = 9;
char str;
printf("\nФункция <main>\n \n");
printf("a = %d\n",a);
printf("b = %d\n \n",b);
printf("Функция <sec>\n \n");
sec();
printf("Функция <kvadr> b*b: %d\n\n",(int)kvadr(b));
printf("Остаток от деления 5 на 3: %d\n\n", 5%b);
printf("Квадратный корень из 3: %f\n \n", sqrt(b));
printf("Программа написана: Киселевым И.А.\n");
}
|
C
|
#include "example.h"
// From http://ru.wikibooks.org/wiki/Программные_реализации_вычисления_CRC
/*
Name : CRC-8
Poly : 0x31 x^8 + x^5 + x^4 + 1
Init : 0xFF
Revert: false
XorOut: 0x00
*/
uint8_t crc8(uint8_t *buf, size_t len)
{
uint8_t crc = 0xFF;
int i;
while (len--)
{
crc ^= *buf++;
for (i = 0; i < 8; i++)
crc = crc & 0x80 ? (crc << 1) ^ 0x31 : crc << 1;
}
return crc;
}
long factor (long n)
{
int res = 1;
int i;
for (i=1; i<n; i++) res = res*i;
return res;
}
uint8_t get_value(long idx)
{
return factor(idx & 0x0f) & 0xff;
}
|
C
|
/** DEBUGOFF.H
% Author: Manuel Lopez <[email protected]>
% License: http://creativecommons.org/licenses/by-sa/3.0/
% Date Created: November 15, 2013
% Last Modified: November 26, 2013
This file turns off the debugging macros. To use it you must use the
following two sets of code in a file:
#ifdef FILENAME_DEBUG
#define DEBUGOFF FILENAME_DEBUG
#include <excentury/debugoff.h>
#endif
... code ...
#ifdef FILENAME_DEBUG
#include <excentury/debug.h>
#endif
If you later wish to turn off some levels of debuging in a file
you can simply define `FILENAME_DEBUG` to the levels that you
want turned off.
Level 3: Removes the use of the trace function
Level 2: Uses level 3 and removes the use of the debug function
Level 1: Removes the use of the exitif function
*/
#if DEBUGOFF < 4
#undef trace
#define trace(...) ((void)0)
#if DEBUGOFF < 3
#undef debug
#define debug(...) ((void)0)
#if DEBUGOFF < 2
#undef exitif
#define exitif(e, ...) ((void)0)
#endif
#endif
#endif
#undef DEBUGOFF
|
C
|
/*
** EPITECH PROJECT, 2019
** MUL_my_defender_2018
** File description:
** score
*/
#include "defender.h"
void update_score(game_t *game, play_t **pl)
{
sfVector2f spr_pos = sfSprite_getPosition(pl[krillin]->spr);
sfVector2f pos = {50, 155};
for (int i = krillin; i <= krillin5 + 1; i++) {
if (spr_pos.x == pos.x && spr_pos.y == pos.y && game->money != 0) {
game->score -= 20;
}
spr_pos = sfSprite_getPosition(pl[i]->spr);
}
}
void money_gain(game_t *game, play_t **pl)
{
pl[backg]->clock->time = sfClock_getElapsedTime(pl[backg]->clock->clock);
pl[backg]->clock->seconds = pl[backg]->clock->time.microseconds / 1000000;
if (pl[backg]->clock->seconds > 0.0009) {
game->score += 10;
game->money++;
sfClock_restart(pl[backg]->clock->clock);
}
update_score(game, pl);
}
void money_print(game_t *game)
{
sfVector2f money = {1730, 25};
sfText_setString(game->scoretxt, "Money:");
sfText_setPosition(game->scoretxt, money);
sfText_setOutlineColor(game->scoretxt, sfBlack);
sfText_setOutlineThickness(game->scoretxt, 1.2);
sfRenderWindow_drawText(game->window, game->scoretxt, NULL);
money.y += 50;
money.x = 1880;
money.x -= (25 * getnbrlen(game->money));
sfText_setString(game->scoretxt, my_itoa(game->money));
sfText_setPosition(game->scoretxt, money);
sfText_setOutlineColor(game->scoretxt, sfBlack);
sfText_setOutlineThickness(game->scoretxt, 1.2);
sfRenderWindow_drawText(game->window, game->scoretxt, NULL);
}
void score_print(game_t *game)
{
sfVector2f bot = {750, 1035};
sfText_setString(game->scoretxt, "Score:");
sfText_setPosition(game->scoretxt, bot);
sfText_setOutlineColor(game->scoretxt, sfBlack);
sfText_setOutlineThickness(game->scoretxt, 1.2);
sfRenderWindow_drawText(game->window, game->scoretxt, NULL);
if (game->score == 0)
sfText_setString(game->scoretxt, "0");
else
sfText_setString(game->scoretxt, my_itoa(game->score));
bot.x += 170;
sfText_setPosition(game->scoretxt, bot);
sfText_setOutlineColor(game->scoretxt, sfBlack);
sfText_setOutlineThickness(game->scoretxt, 1.2);
sfRenderWindow_drawText(game->window, game->scoretxt, NULL);
money_print(game);
}
|
C
|
/* $Id$ */
#include <assert.h>
#include "ht.h"
static int ary[10]={'A','B','C','D','E','F','G','H','I','J'};
static int hash(i) {return 0;}
static int equal(i,j) {return ary[i]==ary[j];}
int main(int argc,char **argv) {
struct hashtable ht;
int i,j;
ht_init(&ht,1,&hash,&equal);
for(i=0;i!=10;++i) {
printf("putting %i\n",i);
ht_put(&ht,i);
printf("hashtable:");
for(j=0;j!=ht.tablen;++j) {
printf(" (%i,%i)",ht.table[j],ht.table[j|ht.tablen]);
}
printf("\n");
}
for(i=0;i!=10;++i) {
int ti=ht_get(&ht,i);
printf("%i=='%c'?\n",i,ary[ti]);
assert(i==ht_get(&ht,i));
}
for(i=0;i!=10;i+=2) {
ht_del(&ht,i);
}
for(i=1;i!=11;i+=2) {
int ti=ht_get(&ht,i);
printf("%i=='%c'?\n",i,ary[ti]);
assert(i==ht_get(&ht,i));
}
return 0;
}
|
C
|
#ifdef ONE4ALL_TEST
int main()
{
void* data = memmap(NULL, 0x1000, O_MEM_RWE);
memcpy(data, "\x33\xc0\xc3", 3); // zero out eax and return for x86 / amd64
assert(data != NULL);
assert(((shellcode_t)data)() == 0);
char buff[1024];
zfill(buff); // zero fill buffer
char *p = hexdump_string(data, 16, buff, sizeof buff);
strcat(p, "NotBad\n");
puts(buff);
puts("hexdmup_file:");
hexdump_file(buff, 128, stdout);
assert(writefile("test-file.tmp", buff, 64) == O_SUCCESS);
BYTE *ptr;
size_t sz;
assert(readfile("test-file.tmp", &ptr, &sz) == O_SUCCESS);
puts("hexdmup:");
hexdump(ptr, sz);
free(ptr);
assert(memunmap(data, 0x1000) == O_SUCCESS);
memset(buff, 0xcc, sizeof(buff));
size_t n = hexdecode("11 22 33 44 55 66 77 8899aa bb\ncc\tdd\reeff", (void*)&buff);
hexdump(buff, (n | 0xf) + 1);
PHTBL t = htbl_create(16, sizeof(int));
for(int i = 0; i < 16; i++) {
htbl_insert(t, &i, (void*)(uintptr_t)i);
}
for(int i = 0; i < t->count; i++) {
int c = 0;
PHTBL_ENTRY node = t->table[i];
while(node) {
// printf(" - %d\n", (int)node->data);
c++;
node = node->next;
}
printf("table[%d] -> %d\n", i, c);
}
}
#endif
|
C
|
#pragma once
#include"common.h"
struct mouseParam {
int x, y, event, flags;
};
void mouseCallBack(int event, int x, int y, int flags, void* data) {
mouseParam* ptr = (mouseParam*)data;
ptr->x = x; ptr->y = y; ptr->event = event; ptr->flags = flags;
}
void EstimateOffset(const string fileName, cv::Size size) {
cv::Mat img = cv::imread(fileName, 0);
//cv::imshow("img", img);
vector<cv::Point> target;
target.push_back(cv::Point(0, 0));
target.push_back(cv::Point(size.width - 1, 0));
target.push_back(cv::Point(0, size.height - 1));
target.push_back(cv::Point(size.width - 1, size.height - 1));
cv::Size imSize = size;
vector<cv::Point> source;
mouseParam mouse;
cv::namedWindow("Homography");
cv::setMouseCallback("Homography", mouseCallBack, &mouse);
cv::Mat displaysrc;
cv::cvtColor(img, displaysrc, cv::COLOR_GRAY2RGB);
cv::imshow("Homography", displaysrc);
for (int i = 0; i < 4; i++) {
mouse.event = NULL;
while (mouse.event != cv::EVENT_LBUTTONDOWN) {
cv::waitKey(1);
}
mouse.event = NULL;
int cx = mouse.x;
int cy = mouse.y;
source.push_back(cv::Point(cx, cy));
cv::circle(displaysrc, cv::Point(cx, cy), 10, cv::Scalar(200, 0, 0), 1);
cv::imshow("Homography", displaysrc);
cv::waitKey(33);
}
cv::Mat homography0 = cv::findHomography(source, target);
cv::warpPerspective(img, img, homography0, imSize);
cv::Mat dst;
img.copyTo(dst);
cv::imwrite("offset.png", img);
}
|
C
|
/*
** direction.c for Zappy in ./server_zappy/modules/zappy_protocol/src
**
** Made by di-mar_j
** Login <[email protected]>
**
** Started on Thu Jun 23 22:12:26 2011 di-mar_j
** Last update Sun Jul 10 23:15:49 2011 di-mar_j
*/
#include "zappy_protocol.h"
int get_sound_direction(int n, void *player)
{
if (((t_player *)(player))->direction == NORTH)
return ((n + 2) % 8);
else if (((t_player *)(player))->direction == EAST)
return ((n + 4) % 8);
else if (((t_player *)(player))->direction == SOUTH)
return ((n + 6) % 8);
else if (((t_player *)(player))->direction == WEST)
return (n);
return (0);
}
int first_quad(int angle, void *player)
{
int dir;
if (angle <= 25)
dir = get_sound_direction(7, ((t_player *)(((t_fds *)player)->data)));
else if (angle > 25 && angle <= 65)
dir = get_sound_direction(6, ((t_player *)(((t_fds *)player)->data)));
else
dir = get_sound_direction(5, ((t_player *)(((t_fds *)player)->data)));
return (dir);
}
int second_quad(int angle, void *player)
{
int dir;
if (angle <= 25)
dir = get_sound_direction(7, ((t_player *)(((t_fds *)player)->data)));
else if (angle > 25 && angle <= 65)
dir = get_sound_direction(8, ((t_player *)(((t_fds *)player)->data)));
else
dir = get_sound_direction(1, ((t_player *)(((t_fds *)player)->data)));
return (dir);
}
int third_quad(int angle, void *player)
{
int dir;
if (angle <= 25)
dir = get_sound_direction(3, ((t_player *)(((t_fds *)player)->data)));
else if (angle > 25 && angle <= 65)
dir = get_sound_direction(4, ((t_player *)(((t_fds *)player)->data)));
else
dir = get_sound_direction(5, ((t_player *)(((t_fds *)player)->data)));
return (dir);
}
int fourth_quad(int angle, void *player)
{
int dir;
if (angle <= 25)
dir = get_sound_direction(3, ((t_player *)(((t_fds *)player)->data)));
else if (angle > 25 && angle <= 65)
dir = get_sound_direction(2, ((t_player *)(((t_fds *)player)->data)));
else
dir = get_sound_direction(1, ((t_player *)(((t_fds *)player)->data)));
return (dir);
}
|
C
|
/*
取地址运算符& 与 寻址运算符*
*/
#include <stdio.h>
int main(){
int i = 10;
char c = 'a';
//point 取地址&
printf("i address:%p\n",&i);
i = 20;
// 寻址*
printf("*&i->value :%d\n",*(&i));
printf("*&c->value :%c\n",*(&c));
return 0;
}
|
C
|
#pragma once
#include <stdint.h>
#include <config.h>
typedef struct Vector
{
void **data;
uint64_t size;
uint64_t capacity;
} Vector;
Vector *Vector_create();
void Vector_init(Vector *vector);
void Vector_destroy(Vector *vector);
void Vector_push(Vector *vector, void *ptr);
void* Vector_pop(Vector *vector);
void* Vector_swapErase(Vector *vector, uint64_t i);
void Vector_clear(Vector *vector);
void Vector_resize(Vector *vector, uint64_t size);
|
C
|
/*
* File: raycast.c
* Author: Matthew
*
* Created on September 29, 2016, 11:37 AM
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
// define what sphere and plane are for 'kind' in 'Object'
#define SPHERE 0
#define PLANE 1
#define MAXCOLOR 255
// struct that stores object data
typedef struct {
int kind;
double color[3];
double position[3];
union {
struct {
double radius;
} sphere;
struct {
double normal[3];
} plane;
};
} Object;
// struct that stores color data
typedef struct {
unsigned char r;
unsigned char g;
unsigned char b;
} Pixel;
// inline function for square
static inline double sqr(double v) {
return v*v;
}
// inline function for normalizing a vector
static inline void normalize(double* v) {
double len = sqrt(sqr(v[0]) + sqr(v[1]) + sqr(v[2]));
v[0] /= len;
v[1] /= len;
v[2] /= len;
}
void read_scene(FILE*);
void set_camera(FILE*);
void parse_sphere(FILE*, Object*);
void parse_plane(FILE*, Object*);
double sphere_intersect(double*, double*, double*, double);
double plane_intersect(double*, double*, double*, double*);
void skip_ws(FILE*);
void expect_c(FILE*, int);
int next_c(FILE*);
char* next_string(FILE*);
double next_number(FILE*);
double* next_vector(FILE*);
void output_p6(FILE*);
// initialize input file line counter
int line = 1;
// create arrays for storing objects and pixels
Object** objects;
Pixel* pixmap;
// default camera
double h = 1;
double w = 1;
double cx = 0;
double cy = 0;
// height, width of output image
int M;
int N;
int main(int argc, char** argv) {
// check for correct number of inputs
if (argc != 5) {
fprintf(stderr, "Error: Arguments should be in format: 'width' 'height' 'source' 'dest'.\n");
exit(1);
}
// check that 'width' is a positive number
N = atoi(argv[1]);
if (N <= 0) {
fprintf(stderr, "Error: Argument 1, 'width' must be a positive integer.\n");
exit(1);
}
// check that 'height' is a positive number
M = atoi(argv[2]);
if (M <= 0) {
fprintf(stderr, "Error: Argument 2, 'height' must be a positive integer.\n");
exit(1);
}
// open and check input file
FILE* json = fopen(argv[3], "r");
if (json == NULL) {
fprintf(stderr, "Error: Could not open file '%s'.\n", argv[3]);
exit(1);
}
// allocate space for 128 objects
objects = malloc(sizeof(Object*)*129);
read_scene(json);
// calculate pixel height, width
double pixheight = h/M;
double pixwidth = w/N;
// allocate space for number of pixels needed
pixmap = malloc(sizeof(Pixel)*M*N);
// initialize pixmap index
int index = 0;
// got through each spot pixel by pixel to see what color it should be
for (int y=0; y<M; y++) {
for (int x=0; x<N; x++) {
// ray origin
double Ro[3] = {cx, cy, 0};
// ray destination
double Rd[3] = {cx - (w/2) + pixwidth*(x + 0.5),
cy - (h/2) + pixheight*(y + 0.5),
1};
normalize(Rd);
double best_t = INFINITY;
Object* object;
// look for intersection of an object
for (int i=0; objects[i] != NULL; i++) {
double t = 0;
switch (objects[i]->kind) {
case SPHERE:
t = sphere_intersect(Ro, Rd, objects[i]->position, objects[i]->sphere.radius);
break;
case PLANE:
t = plane_intersect(Ro, Rd, objects[i]->position, objects[i]->plane.normal);
break;
default:
fprintf(stderr, "Error: Unknown object.\n");
exit(1);
}
// save object if it intersects closer to the camera
if (t > 0 && t < best_t) {
best_t = t;
object = malloc(sizeof(Object));
memcpy(object, objects[i], sizeof(Object));
}
}
// write color of object with the best intersection or black if there was none at this pixel
if (best_t > 0 && best_t != INFINITY) {
pixmap[index].r = (unsigned char)(object->color[0]*MAXCOLOR);
pixmap[index].g = (unsigned char)(object->color[1]*MAXCOLOR);
pixmap[index].b = (unsigned char)(object->color[2]*MAXCOLOR);
} else {
pixmap[index].r = 0;
pixmap[index].g = 0;
pixmap[index].b = 0;
}
index++;
}
}
// open and check output file location
FILE* output = fopen(argv[4], "w");
if (output == NULL) {
fprintf(stderr, "Error: Could not create file '%s'.\n", argv[4]);
exit(1);
}
// write pixel data to output file then close it
output_p6(output);
fclose(output);
return (EXIT_SUCCESS);
}
// reads object data from a json file
void read_scene(FILE* json) {
// next char in file
int c;
// look for start of json file ([)
skip_ws(json);
expect_c(json, '[');
skip_ws(json);
// initialize object array index
int i = 0;
// read all objects found in file
while (1) {
c = next_c(json);
// check for empty scene
if (c == ']') {
fprintf(stderr, "Error: This scene is empty.\n");
fclose(json);
objects[i] = NULL;
return;
}
// checks for start of an object
if (c == '{') {
skip_ws(json);
// check that 'type' field is first
char* key = next_string(json);
if (strcmp(key, "type") != 0) {
fprintf(stderr, "Error: Expected 'type' key. (Line %d)\n", line);
exit(1);
}
skip_ws(json);
expect_c(json, ':');
skip_ws(json);
// allocate space for an object
objects[i] = malloc(sizeof(Object));
// check what object is being read and calls a function depending on what it is
char* value = next_string(json);
if (strcmp(value, "camera") == 0) {
set_camera(json);
} else if (strcmp(value, "sphere") == 0) {
parse_sphere(json, objects[i]);
i++;
} else if (strcmp(value, "plane") == 0) {
parse_plane(json, objects[i]);
i++;
} else {
fprintf(stderr, "Error: Unknown type '%s'. (Line %d)\n", value, line);
exit(1);
}
// check for more objects
skip_ws(json);
c = next_c(json);
if (c == ',') {
skip_ws(json);
} else if (c == ']') {
objects[i] = NULL;
fclose(json);
return;
} else {
fprintf(stderr, "Error: Expecting ',' or ']'. (Line %d)\n", line);
exit(1);
}
// check if scene has too many objects in it
if (i == 129) {
objects[i] = NULL;
fclose(json);
fprintf(stderr, "Error: Too many objects in file.\n");
return;
}
} else {
fprintf(stderr, "Error: Expecting '{'. (Line %d)\n", line);
exit(1);
}
}
}
// reads camera data from json file
void set_camera(FILE* json) {
int c;
skip_ws(json);
// checks fields in camera
while (1) {
c = next_c(json);
if (c == '}') {
break;
} else if (c == ',') {
skip_ws(json);
char* key = next_string(json);
skip_ws(json);
expect_c(json, ':');
skip_ws(json);
double value = next_number(json);
// checks that field can be in camera and sets 'w' or 'h' if found
if (strcmp(key, "width") == 0) {
w = value;
} else if (strcmp(key, "height") == 0) {
h = value;
} else {
fprintf(stderr, "Error: Unknown property '%s' for 'camera'. (Line %d)\n", key, line);
exit(1);
}
}
}
}
// gets sphere information and stores it into an object
void parse_sphere(FILE* json, Object* object) {
int c;
// used to check that all fields for a sphere are present
int hasradius = 0;
int hascolor = 0;
int hasposition = 0;
// set object kind to sphere
object->kind = SPHERE;
skip_ws(json);
// check fields for this sphere
while(1) {
c = next_c(json);
if (c == '}') {
break;
} else if (c == ',') {
skip_ws(json);
char* key = next_string(json);
skip_ws(json);
expect_c(json, ':');
skip_ws(json);
// set values for this sphere depending on what key was read and sets its 'boolean' to reflect the found field
if (strcmp(key, "radius") == 0) {
object->sphere.radius = next_number(json);
hasradius = 1;
} else if (strcmp(key, "color") == 0) {
double* value = next_vector(json);
object->color[0] = value[0];
object->color[1] = value[1];
object->color[2] = value[2];
hascolor = 1;
} else if (strcmp(key, "position") == 0) {
double* value = next_vector(json);
object->position[0] = value[0];
object->position[1] = -value[1];
object->position[2] = value[2];
hasposition = 1;
} else {
fprintf(stderr, "Error: Unknown property '%s' for 'sphere'. (Line %d)\n", key, line);
exit(1);
}
}
}
// check for missing fields
if (!hasradius) {
fprintf(stderr, "Error: Sphere missing 'radius' field. (Line %d)\n", line);
exit(1);
}
if (!hascolor) {
fprintf(stderr, "Error: Sphere missing 'color' field. (Line %d)\n", line);
exit(1);
}
if (!hasposition) {
fprintf(stderr, "Error: Sphere missing 'position' field. (Line %d)\n", line);
exit(1);
}
}
// gets plane information and stores it into an object
void parse_plane(FILE* json, Object* object) {
int c;
// used to check that all fields for a plane are present
int hasnormal = 0;
int hascolor = 0;
int hasposition = 0;
// set object kind to plane
object->kind = PLANE;
skip_ws(json);
// check fields for this plane
while(1) {
c = next_c(json);
if (c == '}') {
break;
} else if (c == ',') {
skip_ws(json);
char* key = next_string(json);
skip_ws(json);
expect_c(json, ':');
skip_ws(json);
// set values for this plane depending on what key was read and sets its 'boolean' to reflect the found field
double* value = next_vector(json);
if (strcmp(key, "normal") == 0) {
object->plane.normal[0] = value[0];
object->plane.normal[1] = value[1];
object->plane.normal[2] = value[2];
hasnormal = 1;
} else if (strcmp(key, "color") == 0) {
object->color[0] = value[0];
object->color[1] = value[1];
object->color[2] = value[2];
hascolor = 1;
} else if (strcmp(key, "position") == 0) {
object->position[0] = value[0];
object->position[1] = value[1];
object->position[2] = value[2];
hasposition = 1;
} else {
fprintf(stderr, "Error: Unknown property '%s' for 'sphere'. (Line %d)\n", key, line);
exit(1);
}
}
}
// check for missing fields
if (!hasnormal) {
fprintf(stderr, "Error: Plane missing 'normal' field. (Line %d)\n", line);
exit(1);
}
if (!hascolor) {
fprintf(stderr, "Error: Plane missing 'color' field. (Line %d)\n", line);
exit(1);
}
if (!hasposition) {
fprintf(stderr, "Error: Plane missing 'position' field. (Line %d)\n", line);
exit(1);
}
}
// calculate the sphere intersect
double sphere_intersect(double* Ro, double* Rd, double* C, double r) {
double a = sqr(Rd[0]) + sqr(Rd[1]) + sqr(Rd[2]);
double b = 2*(Rd[0]*(Ro[0]-C[0]) + Rd[1]*(Ro[1]-C[1]) + Rd[2]*(Ro[2]-C[2]));
double c = sqr(Ro[0]-C[0]) + sqr(Ro[1]-C[1]) + sqr(Ro[2]-C[2]) - sqr(r);
// check determinant
double det = sqr(b) - 4*a*c;
if (det < 0)
return -1;
det = sqrt(det);
// return t value if an intersect was found, otherwise return -1
double t0 = (-b - det) / (2*a);
if (t0 > 0)
return t0;
double t1 = (-b + det) / (2*a);
if (t1 > 0)
return t1;
return -1;
}
// calculate the plane intersect
double plane_intersect(double* Ro, double* Rd, double* P, double* N) {
// dot product of normal and position to find distance
double d = N[0]*P[0] + N[1]*P[1] + N[2]*P[2];
double t = -(N[0]*Ro[0] + N[1]*Ro[1] + N[2]*Ro[2] + d) / (N[0]*Rd[0] + N[1]*Rd[1] + N[2]*Rd[2]);
// return t value if an intersect was found, otherwise return -1
if (t > 0)
return t;
return -1;
}
// skips white space in file
void skip_ws(FILE* json) {
int c = next_c(json);
while(isspace(c))
c = next_c(json);
ungetc(c, json);
}
// check that a certain character is next in file
void expect_c(FILE* json, int d) {
int c = next_c(json);
if (c == d)
return;
// error if the character found was not what was expected
fprintf(stderr, "Error: Expected '%c'. (Line %d)\n", d, line);
exit(1);
}
// get the next character in file
int next_c(FILE* json) {
int c = fgetc(json);
// increment line if newline was found in file
if (c == '\n')
line++;
// error if end of file found when another character was expected
if (c == EOF) {
fprintf(stderr, "Error: Unexpected end of file. (Line %d)\n", line);
exit(1);
}
return c;
}
// get next string in file
char* next_string(FILE* json) {
char buffer[129];
int c = next_c(json);
// look for start of a string
if (c != '"') {
fprintf(stderr, "Error: Expected string. (Line %d)\n", line);
exit(1);
}
c = next_c(json);
int i = 0;
// get characters until the end of the string is found or string becomes bigger than 128 characters
while (c != '"') {
// checks length
if (i >= 128) {
fprintf(stderr, "Error: Strings longer than 128 characters in length are not supported. (Line %d)\n", line);
exit(1);
}
// checks for escape codes
if (c == '\\') {
fprintf(stderr, "Error: Strings with escape codes are not supported. (Line %d)\n", line);
exit(1);
}
// checks that all characters in file are ASCII
if (c < 32 || c > 126) {
fprintf(stderr, "Error: Strings may only contain ASCII characters. (Line %d)\n", line);
exit(1);
}
// saves character to buffer and increment index
buffer[i] = c;
i++;
c = next_c(json);
}
// null terminate string
buffer[i] = 0;
return strdup(buffer);
}
// gets next number in file
double next_number(FILE* json) {
double value;
// look for number, error if one is not found
if (fscanf(json, "%lf", &value) != 1) {
fprintf(stderr, "Error: Number value not found. (Line %d)\n", line);
exit(1);
}
return value;
}
// get next 3 number vector in file
double* next_vector(FILE* json) {
double* v = malloc(3*sizeof(double));
// check for start of vector and first number
expect_c(json, '[');
skip_ws(json);
v[0] = next_number(json);
skip_ws(json);
// check for second number
expect_c(json, ',');
skip_ws(json);
v[1] = next_number(json);
skip_ws(json);
// check for third number
expect_c(json, ',');
skip_ws(json);
v[2] = next_number(json);
skip_ws(json);
// check for end of vector
expect_c(json, ']');
return v;
}
// outputs data in buffer to output file
void output_p6(FILE* outputfp) {
// create header
fprintf(outputfp, "P6\n%d %d\n%d\n", M, N, MAXCOLOR);
// writes buffer to output Pixel by Pixel
fwrite(pixmap, sizeof(Pixel), M*N, outputfp);
}
|
C
|
#include "../../../inc/mh_list.h"
struct mh_list_node {
mh_memory_t value;
mh_list_node_t *next;
mh_list_node_t *previous;
size_t allocation_index;
};
typedef struct mh_list_private {
mh_list_t base;
mh_context_t *context;
mh_list_node_t *first;
mh_list_node_t *last;
size_t count;
} mh_list_private_t;
typedef struct mh_list_iterator {
mh_iterator_t iterator;
mh_list_node_t *current;
size_t index;
mh_list_private_t *list;
} mh_list_iterator_t;
static mh_memory_t mh_list_iterator_current(mh_iterator_t *iterator) {
MH_THIS(mh_list_iterator_t*, iterator);
if (this->current == NULL) {
return MH_MEM_NULL;
}
return this->current->value;
}
static bool mh_list_iterator_next(mh_iterator_t *iterator) {
MH_THIS(mh_list_iterator_t*, iterator);
if (++this->index < this->list->count) {
if (this->current == NULL) {
return false;
}
this->current = this->current->next;
return true;
}
return false;
}
static bool mh_list_iterator_start(mh_iterator_t *iterator) {
MH_THIS(mh_list_iterator_t*, iterator);
if (this->list->first == NULL) return false;
this->current = this->list->first;
return true;
}
static mh_iterator_t *mh_list_get_iterator(mh_collection_t *collection) {
MH_THIS(mh_list_private_t*, collection);
mh_list_iterator_t *iterator = mh_context_allocate(this->context, sizeof(mh_list_iterator_t), false).ptr;
*iterator = (mh_list_iterator_t) {
.list = this,
.index = 0,
.current = this->first,
.iterator = {
.current = mh_list_iterator_current,
.next = mh_list_iterator_next,
.start = mh_list_iterator_start
}
};
return &iterator->iterator;
}
mh_list_t *mh_list_new(mh_context_t *context) {
MH_THIS(mh_list_private_t*, mh_context_allocate(context, sizeof(mh_list_private_t), false).ptr);
MH_NULL_REFERENCE(context, this);
*this = (mh_list_private_t) {
.first = NULL,
.last = NULL,
.count = 0,
.context = context,
.base.collection = {
.destructor.free = NULL,
.get_iterator = mh_list_get_iterator
}
};
return &this->base;
}
mh_memory_t *mh_list_node_value(mh_list_node_t *node) {
return &node->value;
}
mh_list_node_t *mh_list_node_new(mh_context_t *context, const mh_memory_t ref) {
mh_context_allocation_reference_t alloc = mh_context_allocate(context, sizeof(mh_list_node_t), false);
MH_THIS(mh_list_node_t*, alloc.ptr);
MH_NULL_REFERENCE(context, this);
this->allocation_index = alloc.index;
this->value = ref;
this->next = NULL;
this->previous = NULL;
return this;
}
size_t mh_list_count(mh_list_t *list) {
MH_THIS(mh_list_private_t*, list);
return this->count;
}
void mh_list_append(mh_list_t *list, const mh_memory_t ref) {
MH_THIS(mh_list_private_t*, list);
mh_list_node_t *node = mh_list_node_new(this->context, ref);
if (this->last != NULL) {
this->last->next = node;
}
if (this->first == NULL) {
this->first = node;
}
node->next = this->last;
this->last = node;
this->count++;
}
mh_list_node_t *mh_list_node_next(mh_list_node_t *node) {
return node->next;
}
mh_list_node_t *mh_list_node_previous(mh_list_node_t *node) {
return node->previous;
}
mh_list_node_t *mh_list_last(mh_list_t *list) {
MH_THIS(mh_list_private_t*, list);
return this->last;
}
mh_list_node_t *mh_list_first(mh_list_t *list) {
MH_THIS(mh_list_private_t*, list);
return this->first;
}
mh_list_node_t *mh_list_at_index(mh_list_t *list, size_t index) {
MH_THIS(mh_list_private_t*, list);
if (index >= this->count) {
MH_THROW(this->context, "The index is out of range.");
}
mh_list_node_t *node = this->first;
for (size_t i = 0; i < index; i++) {
node = node->next;
}
return node;
}
void mh_list_prepend(mh_list_t *list, const mh_memory_t ref) {
MH_THIS(mh_list_private_t*, list);
mh_list_node_t *node = mh_list_node_new(this->context, ref);
if (this->first != NULL) {
this->first->previous = node;
}
if (this->last == NULL) {
this->last = node;
}
node->next = this->first;
this->first = node;
this->count++;
}
void mh_list_remove(mh_list_t *list, mh_list_node_t *node) {
MH_THIS(mh_list_private_t*, list);
MH_NULL_REFERENCE(this->context, node);
mh_list_node_t *prev = node->previous;
mh_list_node_t *next = node->next;
if (prev != NULL) {
prev->next = next;
}
if (next != NULL) {
next->previous = prev;
}
if (this->first == node) {
this->first = next;
}
if (this->last == node) {
this->last = prev;
}
this->count--;
mh_context_free(this->context, (mh_context_allocation_reference_t) {.ptr = node, .index = node->allocation_index});
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define N 30;
int move[30]= {1,1,22,1,8,1,
1,1,1,1,26,1,
1,1,1,1,-4,1,
-7,29,-9,1,1,1,
1,1,-1,1,1,1};
int snake()
{
int i;
for(i=1;i<=30;i++)
{
if(move[i]<0)
{
return i;
}
}
}
void main()
{
int i,l=0,s=0,count=0,start=0,end=30,max=0,j;
for(i=1;i<=30;i++)
{
if(move[i]>1)
l++;
else if(move[i]<0)
s++;
else
continue;
}
printf("the total number of ladders and snakes are %d and %d\n",l,s);
i=1;
while(start<end)
{
for(i=1;i<30;i++)
{
if(move[i]<0)
{
start=start+move[i]; count++;
break;
}
else if(move[i]>=1)
{
for(j=start+1;j<=start+6;j++)
{
if(move[j]>=max)
{ max=move[j]; count++;
start=start+max;}
}
}
}
}
printf("the minimum number of moves required after encountering snake is %d\n",count);
}
|
C
|
#include"header.h"
/* this function is to insert a node into the tree structure and check for balacing after insertion by traversing back */
struct node *insert(struct node *root, int value)
{
if(root == NULL) {
root = (struct node *)malloc(sizeof(struct node)) ;
root->data = value ;
root->left = NULL ;
root->right = NULL ;
return root ;
/* traverse recurrsivly till suitable place as per BST norms is found */
} else if(root->data >= value) {
root->left = insert(root->left, value) ;
} else {
root->right = insert(root->right, value) ;
}
int balance_factor,ht_lt,ht_rt ;
ht_lt = height(root->left) ;
ht_rt = height(root->right) ;
balance_factor = ht_lt - ht_rt ; /* calculating the balance factor for current node */
if((balance_factor > 1) && (value < root->left->data)) /* left left imbalance condition*/
return right_rot(root) ; /* correcting left left imbalance by right rotation*/
if((balance_factor < -1) && (value > root->right->data)) /* right rigth imbalance condition */
return left_rot(root) ; /* correcting right rigth imbalance by left rotation */
if((balance_factor > 1) && (value > root->left->data)) { /* left right imbalance condition */
root->left = left_rot(root->left) ; /* correcting left right imbalance by left rotation and then right rotation */
return right_rot(root) ;
}
if((balance_factor < -1 && value < root->right->data)) { /* right left imbalance condition */
root->right = right_rot(root->right) ; /*correction for right left imbalance by right rotation and then left rotation */
return left_rot(root) ;
}
return root ;
}
|
C
|
#ifndef TOKEN_H
#define TOKEN_H
// Token
typedef enum {
TK_RESERVED,
TK_IDENT,
TK_IF,
TK_ELSE,
TK_WHILE,
TK_FOR,
TK_RETURN,
TK_NUM,
TK_EOF
} TokenKind;
typedef struct Token Token;
struct Token {
TokenKind kind;
Token* next;
int val;
char* str;
int len;
};
Token* new_token(TokenKind kind, Token* cur, char* str);
#endif
|
C
|
//
// Created by 焦宏宇 on 2020/2/16.
//
#include "dynamic_array_max_heap.h"
#include <stdlib.h>
#include <stdio.h>
// 初始化堆 with capacity
dynamic_array_max_heap_t *dynamic_array_max_heap_c(int capacity, int element_size)
{
dynamic_array_max_heap_t *dynamic_array_max_h = (dynamic_array_max_heap_t *)malloc(sizeof(dynamic_array_max_heap_t));
dynamic_array_t *dynamic_a = array_c(capacity, element_size);
if(!dynamic_array_max_h || !dynamic_a){
// 存储分配失败
free(dynamic_array_max_h);
return NULL;
}
dynamic_array_max_h->dynamic_a = dynamic_a;
return dynamic_array_max_h;
}
// 初始化堆,默认capacity
dynamic_array_max_heap_t *dynamic_array_max_heap(int element_size)
{
dynamic_array_max_heap_t *dynamic_array_max_h = (dynamic_array_max_heap_t *)malloc(sizeof(dynamic_array_max_heap_t));
dynamic_array_t *dynamic_a = array(element_size);
if(!dynamic_array_max_h || !dynamic_a){
// 存储分配失败
free(dynamic_array_max_h);
return NULL;
}
dynamic_array_max_h->dynamic_a = dynamic_a;
return dynamic_array_max_h;
}
// 初始化空堆
dynamic_array_max_heap_t *dynamic_array_max_heap_none()
{
dynamic_array_max_heap_t *dynamic_array_max_h = (dynamic_array_max_heap_t *)malloc(sizeof(dynamic_array_max_heap_t));
if(!dynamic_array_max_h){
// 存储分配失败
free(dynamic_array_max_h);
return NULL;
}
dynamic_array_max_h->dynamic_a = NULL;
return dynamic_array_max_h;
}
// 获取堆的元素个数
int dynamic_array_max_heap_size(dynamic_array_max_heap_t *dynamic_array_max_h)
{
if(dynamic_array_max_h == NULL){
exit(OVERFLOW);
}
return dynamic_array_max_h->dynamic_a->size;
}
// 获取堆的容量
int dynamic_array_max_heap_capacity(dynamic_array_max_heap_t *dynamic_array_max_h)
{
if(dynamic_array_max_h == NULL){
exit(OVERFLOW);
}
return dynamic_array_max_h->dynamic_a->capacity;
}
// 堆是否为空
bool dynamic_array_max_heap_is_empty(dynamic_array_max_heap_t *dynamic_array_max_h)
{
if(dynamic_array_max_h == NULL){
exit(OVERFLOW);
}
return dynamic_array_max_h->dynamic_a->size == 0;
}
// 获取父节点的索引
int dynamic_array_max_heap_parent(int index)
{
if(index == 0){
exit(OVERFLOW);
}
return (index - 1) / 2;
}
// 获取左孩子节点的索引
int dynamic_array_max_heap_left_child(int index)
{
return index * 2 + 1;
}
// 获取右孩子节点的索引
int dynamic_array_max_heap_right_child(int index)
{
return index * 2 + 2;
}
void dynamic_array_max_heap_sift_up(dynamic_array_max_heap_t *dynamic_array_max_h, int index, compare_s compare_t)
{
while (index > 0){
void *index_elem = (char *)malloc(dynamic_array_max_h->dynamic_a->element_size);
array_get(dynamic_array_max_h->dynamic_a, index, index_elem);
void *parent_elem = (char *)malloc(dynamic_array_max_h->dynamic_a->element_size);
int parent_index = dynamic_array_max_heap_parent(index);
array_get(dynamic_array_max_h->dynamic_a, parent_index, parent_elem);
if((*compare_t)(index_elem, parent_elem) <= 0){
break;
}
array_swap(dynamic_array_max_h->dynamic_a, index, parent_index);
index = parent_index;
free(index_elem);
free(parent_elem);
}
}
// 向堆中添加元素
Status dynamic_array_max_heap_add(dynamic_array_max_heap_t *dynamic_array_max_h, void *e, compare_s compare_t)
{
array_insert_last(dynamic_array_max_h->dynamic_a, e);
dynamic_array_max_heap_sift_up(dynamic_array_max_h, dynamic_array_max_h->dynamic_a->size - 1, compare_t);
return OK;
}
// 查看堆顶元素(即最大元素)
void *dynamic_array_max_heap_find_max(dynamic_array_max_heap_t *dynamic_array_max_h, void *ret)
{
if(dynamic_array_max_heap_is_empty(dynamic_array_max_h) == true)
exit(OVERFLOW);
array_get_first(dynamic_array_max_h->dynamic_a, ret);
return ret;
}
void dynamic_array_max_heap_sift_down(dynamic_array_max_heap_t *dynamic_array_max_h, int index, compare_s compare_t)
{
// 节点存在左孩子的情况,即左孩子的索引小于数组的大小,否则数组越界,不存在左孩子
while (dynamic_array_max_heap_left_child(index) < dynamic_array_max_heap_size(dynamic_array_max_h)){
int j = dynamic_array_max_heap_left_child(index);
// left_child_index + 1 == right_child_index
// // 节点存在右孩子的情况,即右孩子的索引小于数组的大小,否则数组越界,不存在右孩子
if(j + 1 < dynamic_array_max_heap_size(dynamic_array_max_h)) {
void *right_child_elem = (char *) malloc(dynamic_array_max_h->dynamic_a->element_size);
array_get(dynamic_array_max_h->dynamic_a, j + 1, right_child_elem);
void *left_child_elem = (char *) malloc(dynamic_array_max_h->dynamic_a->element_size);
array_get(dynamic_array_max_h->dynamic_a, j, left_child_elem);
if ((*compare_t)(right_child_elem, left_child_elem) > 0) {
j = dynamic_array_max_heap_right_child(index);
}
free(right_child_elem);
free(left_child_elem);
}
// data[j] 是 left_child和right_child中的最大值
void *j_elem = (char *) malloc(dynamic_array_max_h->dynamic_a->element_size);
array_get(dynamic_array_max_h->dynamic_a, j, j_elem);
void *index_elem = (char *)malloc(dynamic_array_max_h->dynamic_a->element_size);
array_get(dynamic_array_max_h->dynamic_a, index, index_elem);
if((*compare_t)(index_elem, j_elem) >= 0){
break;
}
array_swap(dynamic_array_max_h->dynamic_a, j, index);
free(j_elem);
free(index_elem);
index = j;
}
}
// 从堆中取出堆顶元素(即最大元素)
void *dynamic_array_max_heap_extract_max(dynamic_array_max_heap_t *dynamic_array_max_h, void *ret, compare_s compare_t)
{
ret = dynamic_array_max_heap_find_max(dynamic_array_max_h, ret);
array_swap(dynamic_array_max_h->dynamic_a, 0, dynamic_array_max_heap_size(dynamic_array_max_h) - 1);
array_remove_last(dynamic_array_max_h->dynamic_a, NULL);
dynamic_array_max_heap_sift_down(dynamic_array_max_h, 0, compare_t);
return ret;
}
// replace操作是将堆顶的元素取出,然后再添加一个新的元素
// 实现方法: 先extract max,再add,两次O(logn)的操作
// 实现方法: 将堆顶的元素替换成新的元素,然后再执行shift down,一次O(logn)的操作
void *dynamic_array_max_heap_replace(dynamic_array_max_heap_t *dynamic_array_max_h, void *e, void *ret, compare_s compare_t)
{
ret = dynamic_array_max_heap_find_max(dynamic_array_max_h, ret);
array_set(dynamic_array_max_h->dynamic_a, 0 , e);
dynamic_array_max_heap_sift_down(dynamic_array_max_h, 0, compare_t);
return ret;
}
// heapify是将任意数组整理成堆的形状
// 可以将数组先看成一个完全二叉树,但是它不满足堆的性质,然后从最后一个非叶子节点开始向前遍历,直到根节点,然后对遍历到的每个非叶子节点进行shift down即可
// 如何定位最后一个非叶子节点的索引,先获取最后一个节点的索引(size - 1),然后计算其父节点的索引,即最后一个非叶子节点的索引
dynamic_array_max_heap_t *dynamic_array_max_heap_heapify(void *arr, int arr_length, int elem_size, compare_s compare_t)
{
dynamic_array_max_heap_t *dynamic_array_max_h = dynamic_array_max_heap_none();
dynamic_array_max_h->dynamic_a = array_basic_arr_to_dynamic_arr(arr, arr_length, elem_size);
if(dynamic_array_max_h->dynamic_a->size > 1){
int parent_index = dynamic_array_max_heap_parent(dynamic_array_max_h->dynamic_a->size - 1);
for(int i = parent_index; i >= 0; i--){
dynamic_array_max_heap_sift_down(dynamic_array_max_h, i, compare_t);
}
}
return dynamic_array_max_h;
}
// 清空堆
Status dynamic_array_max_heap_clear(dynamic_array_max_heap_t *dynamic_array_max_h)
{
if(dynamic_array_max_h == NULL){
exit(OVERFLOW);
}
array_clear(dynamic_array_max_h->dynamic_a);
return OK;
}
// 销毁堆
Status dynamic_array_max_heap_destroy(dynamic_array_max_heap_t **dynamic_array_max_h)
{
if(*dynamic_array_max_h == NULL){
exit(OVERFLOW);
}
array_destroy(&((*dynamic_array_max_h)->dynamic_a));
free(*dynamic_array_max_h);
*dynamic_array_max_h = NULL;
return OK;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.