language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_directory( char *dir_path, int f_flag, int r_flag);
void listAll(char *dir_path, int f_flag);
int main( int argc, char **argv) {
int c, f_flag = 0, r_flag = 0;
int index;
int nonOptCount = 0;
if(argc > 2){
printf("Usage: ./myls [-options]\n");
exit(1);
// input ./myls
} else if (argc == 1){
list_directory(NULL, 0, 0);
// input ./myls [options]
} else {
//get otions
while((c = getopt(argc, argv, "RF")) != -1){
switch(c){
case 'F':
f_flag = 1;
break;
case 'R':
r_flag = 1;
break;
default:
break;
}
}
// printf("f_flag = %d, r_flag = %d\n", f_flag, r_flag);
for(index = optind; index < argc; index++){
nonOptCount ++;
}
// specified directory
if(r_flag == 0 && f_flag == 0 && nonOptCount == 1){
list_directory(argv[1], 0, 0);
// current directory with options
} else if (r_flag != 0) {
listAll(".", f_flag);
} else {
list_directory(NULL, f_flag, r_flag);
}
}
return 0;
}
void list_directory( char *dir_path, int f_flag, int r_flag){
char path[100];
DIR *dirp;
struct dirent *dent;
struct stat buf;
if(dir_path == NULL){
if(getcwd(path, sizeof(path)) == NULL){
perror("getcwd()");
exit(1);
}
} else {
if(chdir(dir_path) == -1){
perror("getcwd()");
exit(1);
}
if(getcwd(path, sizeof(path)) == NULL){
perror("getcwd()");
exit(1);
}
}
printf("%s:\n", path);
//open dir
if((dirp = opendir(path)) == NULL){
perror("opendir()");
exit(1);
}
while(dent = readdir(dirp)){
//exclude . and ..
if(strcmp(dent -> d_name, ".") != 0 && strcmp(dent -> d_name, "..")){
if(f_flag == 1){
stat(dent -> d_name, &buf);
if(S_ISDIR(buf.st_mode)) printf("%s/\n", dent -> d_name);
else if (buf.st_mode & S_IXUSR) printf("%s*\n", dent -> d_name);
else printf("%s\n", dent -> d_name);
} else {
printf("%s\n", dent -> d_name);
}
}
}
(void)closedir(dirp);
}
void listAll(char *dir_path, int f_flag){
char path[100];
DIR *dirp;
struct dirent *dent;
struct stat buf;
char *subdir;
if((dirp = opendir(dir_path)) == NULL){
// perror("opendir()");
return;
}
chdir(dir_path);
if(getcwd(path, sizeof(path)) == NULL){
perror("getcwd()");
exit(1);
}
printf("\n%s : \n", path);
while((dent = readdir(dirp))){
stat(dent -> d_name, &buf);
if(S_ISDIR(buf.st_mode)){
if(strcmp(dent -> d_name, ".") == 0 || strcmp(dent -> d_name, "..") == 0) continue;
subdir = malloc(strlen(path) + strlen(dent -> d_name) + 2);
strcpy(subdir, path);
strcat(subdir, "/");
strcat(subdir, dent -> d_name);
if(f_flag) printf("%s/\n", dent -> d_name);
else printf("%s\n", dent -> d_name);
listAll(subdir, f_flag);
} else {
if(f_flag && buf.st_mode & S_IXUSR) printf("%s*\n", dent -> d_name);
else printf("%s\n", dent -> d_name);
}
}
(void)closedir(dirp);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* page_type.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gbersac <gbersac@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/01/28 21:14:10 by gbersac #+# #+# */
/* Updated: 2015/01/28 21:14:38 by gbersac ### ########.fr */
/* */
/* ************************************************************************** */
#include "malloc.h"
t_page_type page_type(size_t size)
{
if (size <= TINY_MAX_ALLOC)
return (TINY);
if (size <= SMALL_MAX_ALLOC)
return (SMALL);
return (LARGE);
}
size_t page_length(size_t size)
{
if (size <= TINY_MAX_ALLOC)
return (TINY_LENGTH);
if (size <= SMALL_MAX_ALLOC)
return (SMALL_LENGTH);
return (size + PAGE_SIZE);
}
size_t page_length_2(t_page_type size)
{
if (size == TINY)
return (TINY_LENGTH);
if (size == SMALL)
return (SMALL_LENGTH);
return (size);
}
|
C
|
#include <stdio.h>
/*
NAMA : Rizki Ramadhani
NIM : 160801087
JUDUL : Tipe Array
*/
int main(void)
{
int bilangan[5];
bilangan[0] = 6;
bilangan[1] = 9;
bilangan[2] = -8;
bilangan[3] = 24;
bilangan[4] = -99;
printf("Isi array bilangan pertama: %d \n",bilangan[0]);
printf("Isi array bilangan kedua: %d \n",bilangan[1]);
printf("Isi array bilangan ketiga: %d \n",bilangan[2]);
printf("Isi array bilangan keempat: %d \n",bilangan[3]);
printf("Isi array bilangan kelima: %d \n",bilangan[4]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
char *arguments[]={"expr", "1", "+", "2", NULL};
char *environnement[]={"LANG=fr",NULL};
printf("Exécution du processus %d\n",getpid());
printf("Exécution de /usr/bin/expr\n");
int err=execve("/usr/bin/expr", arguments, environnement);
if(err!=0) {
perror("execve");
exit(EXIT_FAILURE);
}
// jamais atteint
printf("Ce message ne sera jamais affiché\n");
return(EXIT_SUCCESS);
}
|
C
|
# include <stdio.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <dirent.h>
# include <stdlib.h>
ino_t get_inode( char * );
void printpathto( ino_t );
void inum_to_name( ino_t, char *, int );
int main()
{
printpathto(get_inode("."));
putchar('\n');
return 0;
}
void printpathto( ino_t this_inode )
{
ino_t my_inode;
char its_name[BUFSIZ];
if( get_inode("..") != this_inode )
{
chdir("..");
inum_to_name( this_inode, its_name, BUFSIZ );
my_inode = get_inode( "." );
printpathto( my_inode );
printf(" /%s", its_name );
}
}
void inum_to_name( ino_t inode_to_find, char * namebuf, int buflen )
{
DIR * dir_ptr;
struct dirent * direntp;
dir_ptr = opendir(".");
if( dir_ptr == NULL )
{
perror(".");
exit(1);
}
while(( direntp = readdir( dir_ptr)) != NULL )
if( direntp->d_ino == inode_to_find )
{
strncpy( namebuf, direntp->d_name, buflen );
namebuf[buflen - 1] = '\0';
closedir( dir_ptr );
return ;
}
fprintf( stderr, "error looking for inum %d\n", inode_to_find );
exit(1);
}
ino_t get_inode( char * fname )
{
struct stat info;
if( stat( fname, &info) == -1 )
{
fprintf( stderr,"Cannot stat ");
perror( fname );
exit(1);
}
return info.st_ino;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, division=2;
printf("Enter the number\n:");
scanf("%d",&x);
if(2<=x)
{
printf("%d=",x);
while(x>1)
{
if(x%division == 0)
{
printf("%d ",division);
x/=division;
}
else
{
++division;
}
}
printf("\n\n");
}
printf("\nWrite the numbers greater than 2 or 2\n\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include "crc.h"
unsigned long int my_hash(char* str,size_t len){
unsigned long int result = 0;
for ( int i = 0; i < len; i++){
result += str[i] * ( str[i] << (i % 4)) + str[i];
result += result * result << 6 ;
}
return result;
}
|
C
|
#include "apue.h"
#include <pthread.h>
/*
* 线程返回退出状态的两种方式 return 和 pthread_exit()
*/
void *thr_fn1(void * arg)
{
printf("thread 1 returning\n");
return ((void *) 10);
}
void * thr_fn2(void* arg)
{
printf("thread 2 exit\n");
pthread_exit((void *) 99);
}
int main()
{
int err;
pthread_t tid1,tid2;
void * tret;
//1
err = pthread_create(&tid1, NULL, thr_fn1,NULL);
if (err != 0)
printf("error\n");
err = pthread_join(tid1, &tret);
if (err != 0)
printf("error\n");
printf("thread 1 return %d\n" , (int)tret);
//2
err = pthread_create(&tid2, NULL, thr_fn2,NULL);
if (err != 0)
printf("error\n");
err = pthread_join(tid2, &tret);
if (err != 0)
printf("error\n");
printf("thread 2 exit %d\n" , (int)tret);
exit(0);
}
|
C
|
#include <stdio.h>
int main(){
int p, i, proc, clock;
char linha[51];
while(scanf("%[^\n]%*c",&linha) != EOF){
scanf("%d%*c",&p);
proc = clock = 0;
for(i = 0; linha[i] != '\0'; i++){
if(linha[i] == 'W'){
clock++;
if(proc > 0){
proc = 0;
clock++;
}
}
else {
proc++;
if(proc == p) {
clock++;
proc = 0;
}
}
}
if(proc > 0) clock ++;
printf("%d\n", clock);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
//minimize the absolute difference
// minimize(max(A[i],B[j],C[k])-min(A[i],B[j],C[k]))
//complexity : O(n1+n2+n3);
int findMin(int n1,int n2,int n3,int *x)
{
if((n1<=n2) && (n1<=n3))
{
*x=1;
return n1;
}
else if((n2<n1) && (n2<=n3))
{
*x=2;
return n2;
}
else
{
*x=3;
return n3;
}
}
int findMax(int n1,int n2,int n3)
{
if((n1>=n2) && (n1>=n3))
return n1;
else if((n2>n1) && (n2>=n3))
return n2;
else
return n3;
}
int solve(int* A, int n1, int* B, int n2, int* C, int n3) {
int i=0,j=0,k=0,X=1,diff=INT_MAX,min,max;
int *x=&X;
while((i<n1) && (j<n2) && (k<n3))
{
min=findMin(A[i],B[j],C[k],x);
max=findMax(A[i],B[j],C[k]);
if((max-min)<diff)
{
diff=max-min;
}
//increment the index of array where min is found
if(X==1)
i++;
if(X==2)
j++;
if(X==3)
k++;
}
return diff;
}
int main()
{
int N1;
printf("enter size of 1st array:\n");
scanf("%d",&N1);
int arr1[N1];
printf("enter elements:\n");
for(int i=0;i<N1;i++)
{
scanf("%d",&arr1[i]);
}
int N2;
printf("enter size of 2nd array:\n");
scanf("%d",&N2);
int arr2[N2];
printf("enter elements:\n");
for(int i=0;i<N2;i++)
{
scanf("%d",&arr2[i]);
}
int N3;
printf("enter size of 2nd array:\n");
scanf("%d",&N3);
int arr3[N3];
printf("enter elements:\n");
for(int i=0;i<N3;i++)
{
scanf("%d",&arr3[i]);
}
printf("minimum absolute diff is : %d ",solve(arr1,N1,arr2,N2,arr3,N3));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int player[5]= {10, 20, 30, 40, 50};
int goals[5]= {30, 21, 43, 26, 41};
int games[5]= {30,29,29,30,27};
float ppg[5];
float bestppg=0.0;
int bestplayer;
for (i=0; i<=4; i++){
ppg[i] = (float)goals[i]/(float)games[i];
printf("\n Player: %d \tGoals: %d \t Games: %d \t PPG: %.2f\n", player[i], goals[i], games[i], ppg[i]);
if (ppg[i]>bestppg);
bestppg = ppg[i];
bestplayer = player[i];
} printf("\n\nThe best player is: %d\n", player[i]);
return 0;
}
|
C
|
/****************************************************************************
* author: *
* Jonas Jansen *
* *
* description: *
* net.c and net.h implement a struct to represent a 2-dimensional net of *
* nodes and connecting lines forming a polygon (without crossings if valid)*
* interface functions are described below *
***************************************************************************/
#ifndef _NET_H_
#define _NET_H_
#include "../pointList/pointList.c"
#include "../lineList/lineList.c"
struct Net_s
{
PointList_t *nodes;
LineList_t *lines;
double maxX, maxY, minX, minY;
int numOfNodes;
};
typedef struct Net_s Net_t;
/*creates a new empty net, returning a pointer to it*/
Net_t *newNet();
/*fills the line list of the net using its points, also closes the line list (see lineList.h for further details)
*returns 1 on success and 0 on fail*/
int generateLines(Net_t*);
/*checks if th net is valid (without crossings), also generates lines if this was not already done
*returns 1 if the net is valid and 0 if it is invalid*/
int isValidNet(Net_t*);
/*prints all nodes of the net in a formatted table
*returns 1 on success and 0 on fail*/
int printNet(Net_t*);
/*appends a point to the node list of a net, the order of appending matters for generating the lines
*returns 1 on success and 0 on fail*/
int appendPoint(Net_t*, Point_t*);
/*checks if a Point is within a net, the net should be validated before
*returns 1 if the point is in the net and 0 if it is not*/
int isWithinNet(Net_t*, Point_t*);
/*needed for isWithinNet, returns the number of intersections between a line and all net-lines, where the
*given line is set between the point to be checked and a point that is definitely out of the net*/
int getRayCastIntersections(Net_t*, Point_t*);
#endif
|
C
|
#include <stdio.h>
#include <string.h>
int main () {
int n;
scanf("%d", &n);
char str[n][64];
int i, j;
for (i = 0; i < n; i++) {
scanf("%s", &str[i]);
}
int roll;
scanf("%d", &roll);
char temp[64];
for (i = 0; i < roll; i++) {
// Tampung elemen yang pertama
strcpy(temp, str[0]);
// Penggeseran
for (j = 0; j < n-1; j++) {
strcpy(str[j], str[j+1]);
}
// simpan tampungan ke akhir array
strcpy(str[n-1], temp);
}
for (i = 0; i < n; i++) {
printf("%d. %s\n", i+1, str[i]);
}
return 0;
}
|
C
|
/*
* =====================================================================================
*
* Filename: task3.c
*
* Description: Create a multiplication table 1 - 10 with for loops.
*
* Version: 1.0
* Created: 02/08/2018 08:52:08 AM
* Revision: none
* Compiler: gcc
*
* Author: Kenji Nakayu (), kenjinakayu@mail.weber.edu
* Organization: WSU
*
* =====================================================================================
*/
#include <stdio.h>
// Constants
const int ROW = 10;
const int COL = 10;
// Main Function
int main()
{
//To auto-align the text within a bracket,
//sit on a bracket and type =% on the command line
for(int r = 1; r <= ROW; r++)
{
for(int c = 1; c <= COL; c++)
{
printf("[%3d] ", r * c);
}
printf("\n");
}
return 0;
}
// Function Definitions
|
C
|
/*
* these two functions are ripped off from confuse.c ....
* for some reason there's no public function to add a
* section to the in-memory config
* ...
*/
#define _GNU_SOURCE
#include <string.h>
#include <malloc.h>
#include <confuse.h>
static cfg_opt_t *cfg_dupopts(cfg_opt_t *opts)
{
int n;
cfg_opt_t *dupopts;
for(n = 0; opts[n].name; n++)
/* do nothing */ ;
dupopts = (cfg_opt_t *)malloc(++n * sizeof(cfg_opt_t));
memcpy(dupopts, opts, n * sizeof(cfg_opt_t));
return dupopts;
}
void add_section(cfg_t *cfg, char *name, char *title) {
cfg_opt_t *opt;
cfg_value_t *val;
int i;
for (i = 0; cfg->opts[i].type != CFGT_NONE; i++) {
if (strncmp(cfg->opts[i].name, name, strlen(name)) == 0) {
opt = &cfg->opts[i];
}
}
opt->values = (cfg_value_t **)realloc(opt->values, (opt->nvalues+1) * sizeof(cfg_value_t *));
opt->values[opt->nvalues] = (cfg_value_t *)malloc(sizeof(cfg_value_t));
memset(opt->values[opt->nvalues], 0, sizeof(cfg_value_t));
val = opt->values[opt->nvalues++];
cfg_free(val->section);
val->section = (cfg_t *)malloc(sizeof(cfg_t));
memset(val->section, 0, sizeof(cfg_t));
val->section->opts = cfg_dupopts(opt->subopts);
val->section->flags = cfg->flags;
val->section->filename = cfg->filename ? strdup(cfg->filename) : 0;
val->section->line = cfg->line;
val->section->errfunc = cfg->errfunc;
val->section->name = strdup(opt->name);
val->section->title = strndup(title, strlen(title));
}
|
C
|
//
// main.c
// Inversions
//
// Created by fast-algo on 02/09/2018.
// Copyright © 2018 fast-algo. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <memory.h>
#include "funcTimer.h"
#define FILENAME "/Users/Shared/Data/IntegerArray.txt"
int loadData(int **data);
long int naive(int *data, int length);
long int countInversions(int *data, int length);
long int countSplitInversions(int *leftArray, int leftLength, int *rightArray, int rightLength);
void testCount(void);
void testFileLoad(void);
int main(int argc, const char * argv[])
{
int *data = NULL;
int lenData = loadData(&data);
if (lenData == 0)
return 0;
startFuncTimer(0);
long int numInversionsNaive = naive(data, lenData);
stopFuncTimer(0);
printf("Number of Inversions (Naive) = %ld\n", numInversionsNaive);
printf("Time Taken for %d length array = %lf seconds.\n", lenData, getFuncTime(0));
startFuncTimer(1);
long int numInversions = countInversions(data, lenData);
stopFuncTimer(1);
printf("Number of Inversions = %ld\n", numInversions);
printf("Time Taken for %d length array = %lf seconds.\n", lenData, getFuncTime(1));
if (data != NULL)
free(data);
return 0;
}
long int naive(int *data, int length)
{
long int numInversions = 0;
int i = 0, j = 0;
for (i = 0; i < length; i++)
{
for (j = i+1; j < length; j++)
{
if (data[i] > data[j])
numInversions++;
}
}
return numInversions;
}
void testFileLoad()
{
int *data = NULL;
int lenData = loadData(&data);
printf("Length = %d\n", lenData);
printf("Data %d = %d\n", 0, data[0]);
printf("Data %d = %d\n", 1, data[1]);
printf("Data %d = %d\n", 2, data[2]);
printf("Data %d = %d\n", lenData - 2, data[lenData - 3]);
printf("Data %d = %d\n", lenData - 1, data[lenData - 2]);
printf("Data %d = %d\n", lenData, data[lenData - 1]);
}
void testCount()
{
int test1[] = {1, 2, 3, 4, 5, 6};
long int numInversions = countInversions(test1, 6);
printf("Number of Inversions = %ld\n", numInversions);
}
long int countInversions(int *data, int length)
{
long int numInversions = 0;
int midPoint = 0;
if (length == 1)
return 0;
else
{
midPoint = length / 2;
numInversions = countInversions(data, midPoint);
numInversions += countInversions(data + midPoint, length - midPoint);
numInversions += countSplitInversions(data, midPoint, data + midPoint, length - midPoint);
}
return numInversions;
}
long int countSplitInversions(int *leftArray, int leftLength, int *rightArray, int rightLength)
{
int i = 0, j = 0, k = 0;
long int numInversions = 0;
int *tempArray = malloc((leftLength + rightLength) * sizeof(int));
bzero(tempArray, leftLength + rightLength);
while ( (i < leftLength) && (j < rightLength) )
{
if (leftArray[i] > rightArray[j])
{
tempArray[k++] = rightArray[j];
numInversions += (leftLength - i);
j++;
}
else
{
tempArray[k++] = leftArray[i];
i++;
}
}
while (i < leftLength)
tempArray[k++] = leftArray[i++];
while (j < rightLength)
tempArray[k++] = rightArray[j++];
for (i = 0; i < (leftLength + rightLength); i++)
leftArray[i] = tempArray[i];
return numInversions;
}
int loadData(int **data)
{
FILE *fp = NULL;
int count = 0;
int line = 0;
int i = 0;
fp = fopen(FILENAME, "r");
if (fp == NULL)
{
printf("Could not open file %s\n", FILENAME);
*data = NULL;
return 0;
}
while (!feof(fp))
{
fscanf(fp, "%d", &line);
count++;
}
fclose(fp);
count--;
//printf("File contains %d lines\n", count);
*data = malloc(count * sizeof(int));
bzero(*data, count);
fp = fopen(FILENAME, "r");
if (fp == NULL)
{
printf("Could not open file %s\n", FILENAME);
*data = NULL;
return 0;
}
for (i = 0; i < count; i++)
{
fscanf(fp, "%d", &line);
*(*data + i) = line;
}
fclose(fp);
return count;
}
|
C
|
/* Interface to hashtable implementations.
Copyright (C) 2006-2022 Free Software Foundation, Inc.
This file is part of libctf.
libctf is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not see
<http://www.gnu.org/licenses/>. */
#include <ctf-impl.h>
#include <string.h>
#include "libiberty.h"
#include "hashtab.h"
/* We have three hashtable implementations:
- ctf_hash_* is an interface to a fixed-size hash from const char * ->
ctf_id_t with number of elements specified at creation time, that should
support addition of items but need not support removal.
- ctf_dynhash_* is an interface to a dynamically-expanding hash with
unknown size that should support addition of large numbers of items, and
removal as well, and is used only at type-insertion time and during
linking.
- ctf_dynset_* is an interface to a dynamically-expanding hash that contains
only keys: no values.
These can be implemented by the same underlying hashmap if you wish. */
/* The helem is used for general key/value mappings in both the ctf_hash and
ctf_dynhash: the owner may not have space allocated for it, and will be
garbage (not NULL!) in that case. */
typedef struct ctf_helem
{
void *key; /* Either a pointer, or a coerced ctf_id_t. */
void *value; /* The value (possibly a coerced int). */
ctf_dynhash_t *owner; /* The hash that owns us. */
} ctf_helem_t;
/* Equally, the key_free and value_free may not exist. */
struct ctf_dynhash
{
struct htab *htab;
ctf_hash_free_fun key_free;
ctf_hash_free_fun value_free;
};
/* Hash and eq functions for the dynhash and hash. */
unsigned int
ctf_hash_integer (const void *ptr)
{
ctf_helem_t *hep = (ctf_helem_t *) ptr;
return htab_hash_pointer (hep->key);
}
int
ctf_hash_eq_integer (const void *a, const void *b)
{
ctf_helem_t *hep_a = (ctf_helem_t *) a;
ctf_helem_t *hep_b = (ctf_helem_t *) b;
return htab_eq_pointer (hep_a->key, hep_b->key);
}
unsigned int
ctf_hash_string (const void *ptr)
{
ctf_helem_t *hep = (ctf_helem_t *) ptr;
return htab_hash_string (hep->key);
}
int
ctf_hash_eq_string (const void *a, const void *b)
{
ctf_helem_t *hep_a = (ctf_helem_t *) a;
ctf_helem_t *hep_b = (ctf_helem_t *) b;
return !strcmp((const char *) hep_a->key, (const char *) hep_b->key);
}
/* Hash a type_key. */
unsigned int
ctf_hash_type_key (const void *ptr)
{
ctf_helem_t *hep = (ctf_helem_t *) ptr;
ctf_link_type_key_t *k = (ctf_link_type_key_t *) hep->key;
return htab_hash_pointer (k->cltk_fp) + 59
* htab_hash_pointer ((void *) (uintptr_t) k->cltk_idx);
}
int
ctf_hash_eq_type_key (const void *a, const void *b)
{
ctf_helem_t *hep_a = (ctf_helem_t *) a;
ctf_helem_t *hep_b = (ctf_helem_t *) b;
ctf_link_type_key_t *key_a = (ctf_link_type_key_t *) hep_a->key;
ctf_link_type_key_t *key_b = (ctf_link_type_key_t *) hep_b->key;
return (key_a->cltk_fp == key_b->cltk_fp)
&& (key_a->cltk_idx == key_b->cltk_idx);
}
/* Hash a type_id_key. */
unsigned int
ctf_hash_type_id_key (const void *ptr)
{
ctf_helem_t *hep = (ctf_helem_t *) ptr;
ctf_type_id_key_t *k = (ctf_type_id_key_t *) hep->key;
return htab_hash_pointer ((void *) (uintptr_t) k->ctii_input_num)
+ 59 * htab_hash_pointer ((void *) (uintptr_t) k->ctii_type);
}
int
ctf_hash_eq_type_id_key (const void *a, const void *b)
{
ctf_helem_t *hep_a = (ctf_helem_t *) a;
ctf_helem_t *hep_b = (ctf_helem_t *) b;
ctf_type_id_key_t *key_a = (ctf_type_id_key_t *) hep_a->key;
ctf_type_id_key_t *key_b = (ctf_type_id_key_t *) hep_b->key;
return (key_a->ctii_input_num == key_b->ctii_input_num)
&& (key_a->ctii_type == key_b->ctii_type);
}
/* The dynhash, used for hashes whose size is not known at creation time. */
/* Free a single ctf_helem with arbitrary key/value functions. */
static void
ctf_dynhash_item_free (void *item)
{
ctf_helem_t *helem = item;
if (helem->owner->key_free && helem->key)
helem->owner->key_free (helem->key);
if (helem->owner->value_free && helem->value)
helem->owner->value_free (helem->value);
free (helem);
}
ctf_dynhash_t *
ctf_dynhash_create (ctf_hash_fun hash_fun, ctf_hash_eq_fun eq_fun,
ctf_hash_free_fun key_free, ctf_hash_free_fun value_free)
{
ctf_dynhash_t *dynhash;
htab_del del = ctf_dynhash_item_free;
if (key_free || value_free)
dynhash = malloc (sizeof (ctf_dynhash_t));
else
dynhash = malloc (offsetof (ctf_dynhash_t, key_free));
if (!dynhash)
return NULL;
if (key_free == NULL && value_free == NULL)
del = free;
/* 7 is arbitrary and untested for now. */
if ((dynhash->htab = htab_create_alloc (7, (htab_hash) hash_fun, eq_fun,
del, xcalloc, free)) == NULL)
{
free (dynhash);
return NULL;
}
if (key_free || value_free)
{
dynhash->key_free = key_free;
dynhash->value_free = value_free;
}
return dynhash;
}
static ctf_helem_t **
ctf_hashtab_lookup (struct htab *htab, const void *key, enum insert_option insert)
{
ctf_helem_t tmp = { .key = (void *) key };
return (ctf_helem_t **) htab_find_slot (htab, &tmp, insert);
}
static ctf_helem_t *
ctf_hashtab_insert (struct htab *htab, void *key, void *value,
ctf_hash_free_fun key_free,
ctf_hash_free_fun value_free)
{
ctf_helem_t **slot;
slot = ctf_hashtab_lookup (htab, key, INSERT);
if (!slot)
{
errno = ENOMEM;
return NULL;
}
if (!*slot)
{
/* Only spend space on the owner if we're going to use it: if there is a
key or value freeing function. */
if (key_free || value_free)
*slot = malloc (sizeof (ctf_helem_t));
else
*slot = malloc (offsetof (ctf_helem_t, owner));
if (!*slot)
return NULL;
(*slot)->key = key;
}
else
{
if (key_free)
key_free (key);
if (value_free)
value_free ((*slot)->value);
}
(*slot)->value = value;
return *slot;
}
int
ctf_dynhash_insert (ctf_dynhash_t *hp, void *key, void *value)
{
ctf_helem_t *slot;
ctf_hash_free_fun key_free = NULL, value_free = NULL;
if (hp->htab->del_f == ctf_dynhash_item_free)
{
key_free = hp->key_free;
value_free = hp->value_free;
}
slot = ctf_hashtab_insert (hp->htab, key, value,
key_free, value_free);
if (!slot)
return errno;
/* Keep track of the owner, so that the del function can get at the key_free
and value_free functions. Only do this if one of those functions is set:
if not, the owner is not even present in the helem. */
if (key_free || value_free)
slot->owner = hp;
return 0;
}
void
ctf_dynhash_remove (ctf_dynhash_t *hp, const void *key)
{
ctf_helem_t hep = { (void *) key, NULL, NULL };
htab_remove_elt (hp->htab, &hep);
}
void
ctf_dynhash_empty (ctf_dynhash_t *hp)
{
htab_empty (hp->htab);
}
size_t
ctf_dynhash_elements (ctf_dynhash_t *hp)
{
return htab_elements (hp->htab);
}
void *
ctf_dynhash_lookup (ctf_dynhash_t *hp, const void *key)
{
ctf_helem_t **slot;
slot = ctf_hashtab_lookup (hp->htab, key, NO_INSERT);
if (slot)
return (*slot)->value;
return NULL;
}
/* TRUE/FALSE return. */
int
ctf_dynhash_lookup_kv (ctf_dynhash_t *hp, const void *key,
const void **orig_key, void **value)
{
ctf_helem_t **slot;
slot = ctf_hashtab_lookup (hp->htab, key, NO_INSERT);
if (slot)
{
if (orig_key)
*orig_key = (*slot)->key;
if (value)
*value = (*slot)->value;
return 1;
}
return 0;
}
typedef struct ctf_traverse_cb_arg
{
ctf_hash_iter_f fun;
void *arg;
} ctf_traverse_cb_arg_t;
static int
ctf_hashtab_traverse (void **slot, void *arg_)
{
ctf_helem_t *helem = *((ctf_helem_t **) slot);
ctf_traverse_cb_arg_t *arg = (ctf_traverse_cb_arg_t *) arg_;
arg->fun (helem->key, helem->value, arg->arg);
return 1;
}
void
ctf_dynhash_iter (ctf_dynhash_t *hp, ctf_hash_iter_f fun, void *arg_)
{
ctf_traverse_cb_arg_t arg = { fun, arg_ };
htab_traverse (hp->htab, ctf_hashtab_traverse, &arg);
}
typedef struct ctf_traverse_find_cb_arg
{
ctf_hash_iter_find_f fun;
void *arg;
void *found_key;
} ctf_traverse_find_cb_arg_t;
static int
ctf_hashtab_traverse_find (void **slot, void *arg_)
{
ctf_helem_t *helem = *((ctf_helem_t **) slot);
ctf_traverse_find_cb_arg_t *arg = (ctf_traverse_find_cb_arg_t *) arg_;
if (arg->fun (helem->key, helem->value, arg->arg))
{
arg->found_key = helem->key;
return 0;
}
return 1;
}
void *
ctf_dynhash_iter_find (ctf_dynhash_t *hp, ctf_hash_iter_find_f fun, void *arg_)
{
ctf_traverse_find_cb_arg_t arg = { fun, arg_, NULL };
htab_traverse (hp->htab, ctf_hashtab_traverse_find, &arg);
return arg.found_key;
}
typedef struct ctf_traverse_remove_cb_arg
{
struct htab *htab;
ctf_hash_iter_remove_f fun;
void *arg;
} ctf_traverse_remove_cb_arg_t;
static int
ctf_hashtab_traverse_remove (void **slot, void *arg_)
{
ctf_helem_t *helem = *((ctf_helem_t **) slot);
ctf_traverse_remove_cb_arg_t *arg = (ctf_traverse_remove_cb_arg_t *) arg_;
if (arg->fun (helem->key, helem->value, arg->arg))
htab_clear_slot (arg->htab, slot);
return 1;
}
void
ctf_dynhash_iter_remove (ctf_dynhash_t *hp, ctf_hash_iter_remove_f fun,
void *arg_)
{
ctf_traverse_remove_cb_arg_t arg = { hp->htab, fun, arg_ };
htab_traverse (hp->htab, ctf_hashtab_traverse_remove, &arg);
}
/* Traverse a dynhash in arbitrary order, in _next iterator form.
Mutating the dynhash while iterating is not supported (just as it isn't for
htab_traverse).
Note: unusually, this returns zero on success and a *positive* value on
error, because it does not take an fp, taking an error pointer would be
incredibly clunky, and nearly all error-handling ends up stuffing the result
of this into some sort of errno or ctf_errno, which is invariably
positive. So doing this simplifies essentially all callers. */
int
ctf_dynhash_next (ctf_dynhash_t *h, ctf_next_t **it, void **key, void **value)
{
ctf_next_t *i = *it;
ctf_helem_t *slot;
if (!i)
{
size_t size = htab_size (h->htab);
/* If the table has too many entries to fit in an ssize_t, just give up.
This might be spurious, but if any type-related hashtable has ever been
nearly as large as that then something very odd is going on. */
if (((ssize_t) size) < 0)
return EDOM;
if ((i = ctf_next_create ()) == NULL)
return ENOMEM;
i->u.ctn_hash_slot = h->htab->entries;
i->cu.ctn_h = h;
i->ctn_n = 0;
i->ctn_size = (ssize_t) size;
i->ctn_iter_fun = (void (*) (void)) ctf_dynhash_next;
*it = i;
}
if ((void (*) (void)) ctf_dynhash_next != i->ctn_iter_fun)
return ECTF_NEXT_WRONGFUN;
if (h != i->cu.ctn_h)
return ECTF_NEXT_WRONGFP;
if ((ssize_t) i->ctn_n == i->ctn_size)
goto hash_end;
while ((ssize_t) i->ctn_n < i->ctn_size
&& (*i->u.ctn_hash_slot == HTAB_EMPTY_ENTRY
|| *i->u.ctn_hash_slot == HTAB_DELETED_ENTRY))
{
i->u.ctn_hash_slot++;
i->ctn_n++;
}
if ((ssize_t) i->ctn_n == i->ctn_size)
goto hash_end;
slot = *i->u.ctn_hash_slot;
if (key)
*key = slot->key;
if (value)
*value = slot->value;
i->u.ctn_hash_slot++;
i->ctn_n++;
return 0;
hash_end:
ctf_next_destroy (i);
*it = NULL;
return ECTF_NEXT_END;
}
int
ctf_dynhash_sort_by_name (const ctf_next_hkv_t *one, const ctf_next_hkv_t *two,
void *unused _libctf_unused_)
{
return strcmp ((char *) one->hkv_key, (char *) two->hkv_key);
}
/* Traverse a sorted dynhash, in _next iterator form.
See ctf_dynhash_next for notes on error returns, etc.
Sort keys before iterating over them using the SORT_FUN and SORT_ARG.
If SORT_FUN is null, thunks to ctf_dynhash_next. */
int
ctf_dynhash_next_sorted (ctf_dynhash_t *h, ctf_next_t **it, void **key,
void **value, ctf_hash_sort_f sort_fun, void *sort_arg)
{
ctf_next_t *i = *it;
if (sort_fun == NULL)
return ctf_dynhash_next (h, it, key, value);
if (!i)
{
size_t els = ctf_dynhash_elements (h);
ctf_next_t *accum_i = NULL;
void *key, *value;
int err;
ctf_next_hkv_t *walk;
if (((ssize_t) els) < 0)
return EDOM;
if ((i = ctf_next_create ()) == NULL)
return ENOMEM;
if ((i->u.ctn_sorted_hkv = calloc (els, sizeof (ctf_next_hkv_t))) == NULL)
{
ctf_next_destroy (i);
return ENOMEM;
}
walk = i->u.ctn_sorted_hkv;
i->cu.ctn_h = h;
while ((err = ctf_dynhash_next (h, &accum_i, &key, &value)) == 0)
{
walk->hkv_key = key;
walk->hkv_value = value;
walk++;
}
if (err != ECTF_NEXT_END)
{
ctf_next_destroy (i);
return err;
}
if (sort_fun)
ctf_qsort_r (i->u.ctn_sorted_hkv, els, sizeof (ctf_next_hkv_t),
(int (*) (const void *, const void *, void *)) sort_fun,
sort_arg);
i->ctn_n = 0;
i->ctn_size = (ssize_t) els;
i->ctn_iter_fun = (void (*) (void)) ctf_dynhash_next_sorted;
*it = i;
}
if ((void (*) (void)) ctf_dynhash_next_sorted != i->ctn_iter_fun)
return ECTF_NEXT_WRONGFUN;
if (h != i->cu.ctn_h)
return ECTF_NEXT_WRONGFP;
if ((ssize_t) i->ctn_n == i->ctn_size)
{
ctf_next_destroy (i);
*it = NULL;
return ECTF_NEXT_END;
}
if (key)
*key = i->u.ctn_sorted_hkv[i->ctn_n].hkv_key;
if (value)
*value = i->u.ctn_sorted_hkv[i->ctn_n].hkv_value;
i->ctn_n++;
return 0;
}
void
ctf_dynhash_destroy (ctf_dynhash_t *hp)
{
if (hp != NULL)
htab_delete (hp->htab);
free (hp);
}
/* The dynset, used for sets of keys with no value. The implementation of this
can be much simpler, because without a value the slot can simply be the
stored key, which means we don't need to store the freeing functions and the
dynset itself is just a htab. */
ctf_dynset_t *
ctf_dynset_create (htab_hash hash_fun, htab_eq eq_fun,
ctf_hash_free_fun key_free)
{
/* 7 is arbitrary and untested for now. */
return (ctf_dynset_t *) htab_create_alloc (7, (htab_hash) hash_fun, eq_fun,
key_free, xcalloc, free);
}
/* The dynset has one complexity: the underlying implementation reserves two
values for internal hash table implementation details (empty versus deleted
entries). These values are otherwise very useful for pointers cast to ints,
so transform the ctf_dynset_inserted value to allow for it. (This
introduces an ambiguity in that one can no longer store these two values in
the dynset, but if we pick high enough values this is very unlikely to be a
problem.)
We leak this implementation detail to the freeing functions on the grounds
that any use of these functions is overwhelmingly likely to be in sets using
real pointers, which will be unaffected. */
#define DYNSET_EMPTY_ENTRY_REPLACEMENT ((void *) (uintptr_t) -64)
#define DYNSET_DELETED_ENTRY_REPLACEMENT ((void *) (uintptr_t) -63)
static void *
key_to_internal (const void *key)
{
if (key == HTAB_EMPTY_ENTRY)
return DYNSET_EMPTY_ENTRY_REPLACEMENT;
else if (key == HTAB_DELETED_ENTRY)
return DYNSET_DELETED_ENTRY_REPLACEMENT;
return (void *) key;
}
static void *
internal_to_key (const void *internal)
{
if (internal == DYNSET_EMPTY_ENTRY_REPLACEMENT)
return HTAB_EMPTY_ENTRY;
else if (internal == DYNSET_DELETED_ENTRY_REPLACEMENT)
return HTAB_DELETED_ENTRY;
return (void *) internal;
}
int
ctf_dynset_insert (ctf_dynset_t *hp, void *key)
{
struct htab *htab = (struct htab *) hp;
void **slot;
slot = htab_find_slot (htab, key, INSERT);
if (!slot)
{
errno = ENOMEM;
return -errno;
}
if (*slot)
{
if (htab->del_f)
(*htab->del_f) (*slot);
}
*slot = key_to_internal (key);
return 0;
}
void
ctf_dynset_remove (ctf_dynset_t *hp, const void *key)
{
htab_remove_elt ((struct htab *) hp, key_to_internal (key));
}
void
ctf_dynset_destroy (ctf_dynset_t *hp)
{
if (hp != NULL)
htab_delete ((struct htab *) hp);
}
void *
ctf_dynset_lookup (ctf_dynset_t *hp, const void *key)
{
void **slot = htab_find_slot ((struct htab *) hp,
key_to_internal (key), NO_INSERT);
if (slot)
return internal_to_key (*slot);
return NULL;
}
size_t
ctf_dynset_elements (ctf_dynset_t *hp)
{
return htab_elements ((struct htab *) hp);
}
/* TRUE/FALSE return. */
int
ctf_dynset_exists (ctf_dynset_t *hp, const void *key, const void **orig_key)
{
void **slot = htab_find_slot ((struct htab *) hp,
key_to_internal (key), NO_INSERT);
if (orig_key && slot)
*orig_key = internal_to_key (*slot);
return (slot != NULL);
}
/* Look up a completely random value from the set, if any exist.
Keys with value zero cannot be distinguished from a nonexistent key. */
void *
ctf_dynset_lookup_any (ctf_dynset_t *hp)
{
struct htab *htab = (struct htab *) hp;
void **slot = htab->entries;
void **limit = slot + htab_size (htab);
while (slot < limit
&& (*slot == HTAB_EMPTY_ENTRY || *slot == HTAB_DELETED_ENTRY))
slot++;
if (slot < limit)
return internal_to_key (*slot);
return NULL;
}
/* Traverse a dynset in arbitrary order, in _next iterator form.
Otherwise, just like ctf_dynhash_next. */
int
ctf_dynset_next (ctf_dynset_t *hp, ctf_next_t **it, void **key)
{
struct htab *htab = (struct htab *) hp;
ctf_next_t *i = *it;
void *slot;
if (!i)
{
size_t size = htab_size (htab);
/* If the table has too many entries to fit in an ssize_t, just give up.
This might be spurious, but if any type-related hashtable has ever been
nearly as large as that then somthing very odd is going on. */
if (((ssize_t) size) < 0)
return EDOM;
if ((i = ctf_next_create ()) == NULL)
return ENOMEM;
i->u.ctn_hash_slot = htab->entries;
i->cu.ctn_s = hp;
i->ctn_n = 0;
i->ctn_size = (ssize_t) size;
i->ctn_iter_fun = (void (*) (void)) ctf_dynset_next;
*it = i;
}
if ((void (*) (void)) ctf_dynset_next != i->ctn_iter_fun)
return ECTF_NEXT_WRONGFUN;
if (hp != i->cu.ctn_s)
return ECTF_NEXT_WRONGFP;
if ((ssize_t) i->ctn_n == i->ctn_size)
goto set_end;
while ((ssize_t) i->ctn_n < i->ctn_size
&& (*i->u.ctn_hash_slot == HTAB_EMPTY_ENTRY
|| *i->u.ctn_hash_slot == HTAB_DELETED_ENTRY))
{
i->u.ctn_hash_slot++;
i->ctn_n++;
}
if ((ssize_t) i->ctn_n == i->ctn_size)
goto set_end;
slot = *i->u.ctn_hash_slot;
if (key)
*key = internal_to_key (slot);
i->u.ctn_hash_slot++;
i->ctn_n++;
return 0;
set_end:
ctf_next_destroy (i);
*it = NULL;
return ECTF_NEXT_END;
}
/* ctf_hash, used for fixed-size maps from const char * -> ctf_id_t without
removal. This is a straight cast of a hashtab. */
ctf_hash_t *
ctf_hash_create (unsigned long nelems, ctf_hash_fun hash_fun,
ctf_hash_eq_fun eq_fun)
{
return (ctf_hash_t *) htab_create_alloc (nelems, (htab_hash) hash_fun,
eq_fun, free, xcalloc, free);
}
uint32_t
ctf_hash_size (const ctf_hash_t *hp)
{
return htab_elements ((struct htab *) hp);
}
int
ctf_hash_insert_type (ctf_hash_t *hp, ctf_dict_t *fp, uint32_t type,
uint32_t name)
{
const char *str = ctf_strraw (fp, name);
if (type == 0)
return EINVAL;
if (str == NULL
&& CTF_NAME_STID (name) == CTF_STRTAB_1
&& fp->ctf_syn_ext_strtab == NULL
&& fp->ctf_str[CTF_NAME_STID (name)].cts_strs == NULL)
return ECTF_STRTAB;
if (str == NULL)
return ECTF_BADNAME;
if (str[0] == '\0')
return 0; /* Just ignore empty strings on behalf of caller. */
if (ctf_hashtab_insert ((struct htab *) hp, (char *) str,
(void *) (ptrdiff_t) type, NULL, NULL) != NULL)
return 0;
return errno;
}
/* if the key is already in the hash, override the previous definition with
this new official definition. If the key is not present, then call
ctf_hash_insert_type and hash it in. */
int
ctf_hash_define_type (ctf_hash_t *hp, ctf_dict_t *fp, uint32_t type,
uint32_t name)
{
/* This matches the semantics of ctf_hash_insert_type in this
implementation anyway. */
return ctf_hash_insert_type (hp, fp, type, name);
}
ctf_id_t
ctf_hash_lookup_type (ctf_hash_t *hp, ctf_dict_t *fp __attribute__ ((__unused__)),
const char *key)
{
ctf_helem_t **slot;
slot = ctf_hashtab_lookup ((struct htab *) hp, key, NO_INSERT);
if (slot)
return (ctf_id_t) (uintptr_t) ((*slot)->value);
return 0;
}
void
ctf_hash_destroy (ctf_hash_t *hp)
{
if (hp != NULL)
htab_delete ((struct htab *) hp);
}
|
C
|
#include "main.h"
int insert_at_first(slist **head, data_t data)
{
//Create node
slist *new = malloc(sizeof(slist));
//Validation
if (new == NULL)
{
return FAILURE;
}
new->data = data;
new->link = *head;
*head = new;
return SUCCESS;
}
|
C
|
#include <stdint.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include "str2n.h" // MACROS
#include "macros.h" // is?digit()
//+===========================================================================
// str2d - convert string to dword {Bin, Oct, Dec, Hex}
//
// Binary: 10b
// Octal: 12345670o OR 012345670
// Decimal: 1234567890d OR 1234567890.
// Hex: 123456789ABCDEF0h OR 0x123456789ABCDEF0 OR $123456789ABCDEF0
//
// Multiplier suffies can be appended to any above number
//
// Kilo: 1024 (n *1024)
// Mega: 1024K (n *1024 *1024)
// Giga: 1024M (n *1024 *1024 *1024)
//
// (tera, peta, exa, zetta, yotta ...need >32bits)
//
// The OCTAL prefix can be over-ridden with a suffix
// ...This allows for zero padded numbers. E.G. 00110101b
// If you attempt to over-ride the HEX prefix, you will get an error
//
// Conversion is NOT case sensitive
//
// Any number of apostrophes (') may be embedded in to the number.
// The converter will simply ignore them.
//
//+====================================
static
s2dErr_t str2n_(char* s, S2D_TYPE* num, int* cnt)
{
S2D_TYPE val; // The number is built here for 'return fail'
int base; // Numeric base {2, 8, 10, 16}
S2D_TYPE mul; // Multipler {K, M, G}
bool suf; // Suffix base specifier used?
char* st; // start (after prefix)
char* nd; // end (first terminator)
char* chp;
char ch;
// Initialise stuff
*num = 0; // Zero the return number
st = s; // Assume no base-prefix
base = 0; // We work the base out later
if (cnt) *cnt = 0; // Zero the length (if requested)
// No number supplied
if ((!s) || (!*s)) return ERR_S2D_EMPTY ;
// Check for base prefix
if (s[0] == '$') {
base = 16;
st += 1;
} else if (s[0] == '0') {
if (tolower(s[1]) == 'x') {
base = 16;
st += 2;
} else {
base = 8;
st += 1;
}
}
// 0 and 0x == 0
if (!*st) {
if (cnt) *cnt = st - s ;
return ERR_S2D_OK;
}
// Locate the end of the number (search for a valid terminator)
for (nd = st; !(strchr(TERMINATORS, *nd)); nd++) ;
// Check for multiplier SUFFIX first
switch (tolower(*(nd-1))) {
case 'k': mul = 1024; nd--; break;
case 'm': mul = 1024*1024; nd--; break;
case 'g': mul = 1024*1024*1024; nd--; break;
default: mul = 1; break;
}
// Check base suffix
suf = false; // Assume no suffix
switch (ch = tolower(*(nd-1))) {
#define SUFFBASE(n) do { base = (n); suf = true; nd--; }while(0)
case 'b': if (base != 16) SUFFBASE(2) ;
break;
case 'd': if (base != 16) SUFFBASE(10) ;
break;
case 'o': if (base == 16) return ERR_S2D_BASE ;
SUFFBASE(8);
break;
case 'h': SUFFBASE(16);
break;
case '.': if (base != 0) return ERR_S2D_BASE ;
SUFFBASE(10);
break;
default: if (!base) base = DEFAULT_BASE ;
break;
#undef SUFFBASE
}
// Convert to long
for (val = 0, chp = st; chp < nd; chp++) {
S2D_TYPE x;
ch = toupper(*chp);
// Skip formatting character '
if (ch=='\'') continue ;
// Validate numeric character
switch (base) {
case 2: if (isbdigit(ch)) break; else return ERR_S2D_DIGIT;
case 8: if (isodigit(ch)) break; else return ERR_S2D_DIGIT;
case 10: if (isdigit (ch)) break; else return ERR_S2D_DIGIT;
case 16: if (isxdigit(ch)) break; else return ERR_S2D_DIGIT;
default: return ERR_S2D_BASE; // This should never happen
}
// Add to total
x = isdigit(ch) ? (ch - '0') : (ch - 'A' + 10) ;
if (x > S2D_MAX - (val * base)) return ERR_S2D_OVERFLOW ; // overflow
else val = (val * base) + x ;
}
// Set returned values
if (mul > S2D_MAX / val) return ERR_S2D_OVERFLOW ; // overflow
*num = val * mul;
if (cnt) *cnt = nd +((mul==1)?0:1) +((suf==true)?1:0) -s; // 's', *NOT* 'st'
return ERR_S2D_OK;
}
//+====================================
// Return simply true/false
//
bool str2n(char* s, S2D_TYPE* num)
{
return (str2n_(s, num, NULL) == 0) ? true : false ;
}
//+====================================
// Return error code
//
int str2ne(char* s, S2D_TYPE* num)
{
return (int)str2n_(s, num, NULL);
}
//+====================================
// Return number of chars consumed
//
int str2nn(char* s, S2D_TYPE* num)
{
int cnt;
str2n_(s, num, &cnt);
return cnt;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include "fact.h"
#include "prime.h"
#include "swap.h"
int main(int argc, char const *argv[]) {
unsigned int n;
do {
printf("Give me a number [0-20]: ");
scanf("%u", &n);
} while (n > 20);
printf("fact of %u = %llu\n", n, fact((unsigned char)n));
printf("%u is %s\n", n,
is_prime(n) ? "a prime" : "not a prime");
int _a = 1;
int _b = 2;
swap(&_a, &_b);
printf("_a = %d, _b = %d\n", _a, _b);
int i = 12;
int *ip = &i;
int *np = NULL;
printf("&i = %p\n", &i);
printf("ip = %p\n", ip);
printf("*ip = %d\n", *ip);
printf("np = %p\n", np);
printf("&np = %p\n", &np);
char s1[10] = "hello";
char s2[10] = "world";
swap_array(s1, s2, 10);
printf("s1 = %s, s2 = %s \n", s1, s2);
return 0;
}
|
C
|
#define START_BALLZ 5
#define MAX_BALLZ 20
#define BALL_SIZE 80
#define HALF_SIZE 40
#define BIG_SIZE 220
/**
* Tipo que representa a bola do jogo
*/
typedef struct ball {
int x, y, sindex, size;
bool released, picked;
double opacity;
} BALL;
/**
* Tipo que representa as bolas geradas no cenário
*/
typedef struct ballz{
GAME *game;
BALL ball[MAX_BALLZ];
int count, lastr;
}BALLZ;
/**
*Cria a bola do jogador
*/
BALL create_ball(){
BALL ball;
ball.x = 1000;
ball.y = 1000;
ball.sindex = 0;
ball.size = BALL_SIZE;
return ball;
}
/**
*Cria uma bola do cenário
*/
BALL create_pball(){
BALL pb;
pb.x = 0;
pb.size = BALL_SIZE;
pb.sindex = rand() % 4;
pb.picked = false;
pb.opacity = 1.0;
pb.released = false;
return pb;
}
/**
* Cria as bolas do cenário (Registro com o vetor)
*/
BALLZ create_ballz(GAME *game){
BALLZ ballz;
ballz.game = game;
ballz.count = START_BALLZ;
for (int i = 0; i < ballz.count; ++i){
ballz.ball[i] = create_pball();
}
ballz.lastr = 0;
return ballz;
}
/**
*Reinicia uma bola do cenário
*/
void reset_ball(BALLZ *ballz, int index){
ballz->ball[index].x = 0;
ballz->ball[index].sindex = rand() % 4;
ballz->ball[index].picked = false;
ballz->ball[index].opacity = 1.0;
ballz->ball[index].released = false;
}
/**
*Aumenta o número de bolas
*/
void inc_ball(BALLZ *ballz){
if (ballz->count >= MAX_BALLZ)
return;
ballz->ball[ballz->count] = create_pball();
ballz->count++;
}
/**
*Gera uma nova altura para a bola
*/
int gen_y(int heigth, int bsize){
int num_pos, gen_pos;
num_pos = heigth / bsize;
gen_pos = (rand()%num_pos)*bsize + (bsize / 2);
return gen_pos;
}
/**
* Lança uma bola na tela, nas posições que pode
*/
void release(BALLZ *ballz, int index){
ballz->ball[index].y = rand() % 500 + 40;
//ballz->ball[index].y = gen_y(ballz->game->height, ballz->ball[index].size);
ballz->ball[index].released = true;
ballz->lastr = 0;
}
/**
* Função que detecta a colisão entre a bola do jogador e outra bola do vetor
*/
bool colided(BALL ball, BALL pb) {
int csize = ball.size / 2;
if (pb.picked)
return false;
return ((pb.x > ball.x - csize && pb.x < ball.x + csize)&&(pb.y > ball.y - csize && pb.y < ball.y + csize));
}
void change(BALL *ball, int index){
//ball->sindex = ball->sindex < 3 ? ball->sindex + 1 : 0;
//ball->sindex = rand() % 4;
ball->sindex = index;
if (ball->sindex == 3)
ball->size = BIG_SIZE;
else
ball->size = BALL_SIZE;
}
int get_ball_space(int speed){
int space = BALL_SIZE / speed;
if (space == 0)
return space+1;
return space;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node *Nodeptr;
struct node{
int data;
Nodeptr left;
Nodeptr right;
};
Nodeptr getnode(){
Nodeptr temp = (Nodeptr)malloc(sizeof(struct node));
return temp;
}
typedef struct
{
Nodeptr queue[20];
int front;
int rear;
}QUEUE;
void insert(QUEUE *ptr, Nodeptr node)
{
if(ptr->rear == 19)
{
printf("queue full \n");
return;
}
else if(ptr->front == -1 && ptr->rear == -1)
{
ptr->front = 0;
ptr->rear = 0;
ptr->queue[ptr->rear] = node;
}
else
{
ptr->queue[++(ptr->rear)] = node;
}
}
Nodeptr delete(QUEUE *ptr)
{
if(ptr->front == -1 && ptr->rear == -1)
{
printf("queue is empty \n");
return NULL;
}
else if(ptr->front == ptr->rear)
{
Nodeptr temp = ptr->queue[ptr->front];
ptr->front = -1;
ptr->rear = -1;
return temp;
}
else
{
return ptr->queue[(ptr->front)++];
}
}
Nodeptr createbintree(int item)
{
int x;
if(item != -1)
{
Nodeptr temp = getnode();
temp->data = item;
printf("enter the left child of %d \n", item);
scanf(" %d", &x);
temp->left = createbintree(x);
printf("enter the right child of %d \n", item);
scanf(" %d", &x);
temp->right = createbintree(x);
return temp;
}
}
void levelorder(Nodeptr root)
{
Nodeptr temp;
QUEUE *q, q1;
q = &q1;
q->front = -1;
q->rear = -1;
insert(q,root);
while(!(q->front == -1 && q->rear == -1))
{
temp = delete(q);
printf("%d ", temp->data);
if(temp->left){insert(q,temp->left);}
if(temp->right){insert(q,temp->right);}
}
}
int main()
{
int item;
Nodeptr root = NULL;
printf("enter the root item : \n");
scanf(" %d", &item);
root = createbintree(item);
levelorder(root);
return 0;
}
|
C
|
/*
Copyright (c) 2005-2008, Simon Howard
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include "avl-tree.h"
/* malloc() / free() testing */
#ifdef ALLOC_TESTING
#include "alloc-testing.h"
#endif
/* AVL Tree (balanced binary search tree) */
struct _AVLTreeNode {
AVLTreeNode *children[2];
AVLTreeNode *parent;
AVLTreeKey key;
AVLTreeValue value;
int height;
};
struct _AVLTree {
AVLTreeNode *root_node;
AVLTreeCompareFunc compare_func;
int num_nodes;
};
AVLTree *avl_tree_new(AVLTreeCompareFunc compare_func)
{
AVLTree *new_tree;
new_tree = (AVLTree *) malloc(sizeof(AVLTree));
if (new_tree == NULL) {
return NULL;
}
new_tree->root_node = NULL;
new_tree->compare_func = compare_func;
new_tree->num_nodes = 0;
return new_tree;
}
static void avl_tree_free_subtree(AVLTree *tree, AVLTreeNode *node)
{
if (node == NULL) {
return;
}
avl_tree_free_subtree(tree, node->children[AVL_TREE_NODE_LEFT]);
avl_tree_free_subtree(tree, node->children[AVL_TREE_NODE_RIGHT]);
free(node);
}
void avl_tree_free(AVLTree *tree)
{
/* Destroy all nodes */
avl_tree_free_subtree(tree, tree->root_node);
/* Free back the main tree data structure */
free(tree);
}
int avl_tree_subtree_height(AVLTreeNode *node)
{
if (node == NULL) {
return 0;
} else {
return node->height;
}
}
/* Update the "height" variable of a node, from the heights of its
* children. This does not update the height variable of any parent
* nodes. */
static void avl_tree_update_height(AVLTreeNode *node)
{
AVLTreeNode *left_subtree;
AVLTreeNode *right_subtree;
int left_height, right_height;
left_subtree = node->children[AVL_TREE_NODE_LEFT];
right_subtree = node->children[AVL_TREE_NODE_RIGHT];
left_height = avl_tree_subtree_height(left_subtree);
right_height = avl_tree_subtree_height(right_subtree);
if (left_height > right_height) {
node->height = left_height + 1;
} else {
node->height = right_height + 1;
}
}
/* Find what side a node is relative to its parent */
static AVLTreeNodeSide avl_tree_node_parent_side(AVLTreeNode *node)
{
if (node->parent->children[AVL_TREE_NODE_LEFT] == node) {
return AVL_TREE_NODE_LEFT;
} else {
return AVL_TREE_NODE_RIGHT;
}
}
/* Replace node1 with node2 at its parent. */
static void avl_tree_node_replace(AVLTree *tree, AVLTreeNode *node1,
AVLTreeNode *node2)
{
int side;
/* Set the node's parent pointer. */
if (node2 != NULL) {
node2->parent = node1->parent;
}
/* The root node? */
if (node1->parent == NULL) {
tree->root_node = node2;
} else {
side = avl_tree_node_parent_side(node1);
node1->parent->children[side] = node2;
avl_tree_update_height(node1->parent);
}
}
/* Rotate a section of the tree. 'node' is the node at the top
* of the section to be rotated. 'direction' is the direction in
* which to rotate the tree: left or right, as shown in the following
* diagram:
*
* Left rotation: Right rotation:
*
* B D
* / \ / \
* A D B E
* / \ / \
* C E A C
* is rotated to: is rotated to:
*
* D B
* / \ / \
* B E A D
* / \ / \
* A C C E
*/
static AVLTreeNode *avl_tree_rotate(AVLTree *tree, AVLTreeNode *node,
AVLTreeNodeSide direction)
{
AVLTreeNode *new_root;
/* The child of this node will take its place:
for a left rotation, it is the right child, and vice versa. */
new_root = node->children[1-direction];
/* Make new_root the root, update parent pointers. */
avl_tree_node_replace(tree, node, new_root);
/* Rearrange pointers */
node->children[1-direction] = new_root->children[direction];
new_root->children[direction] = node;
/* Update parent references */
node->parent = new_root;
if (node->children[1-direction] != NULL) {
node->children[1-direction]->parent = node;
}
/* Update heights of the affected nodes */
avl_tree_update_height(new_root);
avl_tree_update_height(node);
return new_root;
}
/* Balance a particular tree node.
*
* Returns the root node of the new subtree which is replacing the
* old one. */
static AVLTreeNode *avl_tree_node_balance(AVLTree *tree, AVLTreeNode *node)
{
AVLTreeNode *left_subtree;
AVLTreeNode *right_subtree;
AVLTreeNode *child;
int diff;
left_subtree = node->children[AVL_TREE_NODE_LEFT];
right_subtree = node->children[AVL_TREE_NODE_RIGHT];
/* Check the heights of the child trees. If there is an unbalance
* (difference between left and right > 2), then rotate nodes
* around to fix it */
diff = avl_tree_subtree_height(right_subtree)
- avl_tree_subtree_height(left_subtree);
if (diff >= 2) {
/* Biased toward the right side too much. */
child = right_subtree;
if (avl_tree_subtree_height(child->children[AVL_TREE_NODE_RIGHT])
< avl_tree_subtree_height(child->children[AVL_TREE_NODE_LEFT])) {
/* If the right child is biased toward the left
* side, it must be rotated right first (double
* rotation) */
avl_tree_rotate(tree, right_subtree,
AVL_TREE_NODE_RIGHT);
}
/* Perform a left rotation. After this, the right child will
* take the place of this node. Update the node pointer. */
node = avl_tree_rotate(tree, node, AVL_TREE_NODE_LEFT);
} else if (diff <= -2) {
/* Biased toward the left side too much. */
child = node->children[AVL_TREE_NODE_LEFT];
if (avl_tree_subtree_height(child->children[AVL_TREE_NODE_LEFT])
< avl_tree_subtree_height(child->children[AVL_TREE_NODE_RIGHT])) {
/* If the left child is biased toward the right
* side, it must be rotated right left (double
* rotation) */
avl_tree_rotate(tree, left_subtree,
AVL_TREE_NODE_LEFT);
}
/* Perform a right rotation. After this, the left child will
* take the place of this node. Update the node pointer. */
node = avl_tree_rotate(tree, node, AVL_TREE_NODE_RIGHT);
}
/* Update the height of this node */
avl_tree_update_height(node);
return node;
}
/* Walk up the tree from the given node, performing any needed rotations */
static void avl_tree_balance_to_root(AVLTree *tree, AVLTreeNode *node)
{
AVLTreeNode *rover;
rover = node;
while (rover != NULL) {
/* Balance this node if necessary */
rover = avl_tree_node_balance(tree, rover);
/* Go to this node's parent */
rover = rover->parent;
}
}
AVLTreeNode *avl_tree_insert(AVLTree *tree, AVLTreeKey key, AVLTreeValue value)
{
AVLTreeNode **rover;
AVLTreeNode *new_node;
AVLTreeNode *previous_node;
/* Walk down the tree until we reach a NULL pointer */
rover = &tree->root_node;
previous_node = NULL;
while (*rover != NULL) {
previous_node = *rover;
if (tree->compare_func(key, (*rover)->key) < 0) {
rover = &((*rover)->children[AVL_TREE_NODE_LEFT]);
} else {
rover = &((*rover)->children[AVL_TREE_NODE_RIGHT]);
}
}
/* Create a new node. Use the last node visited as the parent link. */
new_node = (AVLTreeNode *) malloc(sizeof(AVLTreeNode));
if (new_node == NULL) {
return NULL;
}
new_node->children[AVL_TREE_NODE_LEFT] = NULL;
new_node->children[AVL_TREE_NODE_RIGHT] = NULL;
new_node->parent = previous_node;
new_node->key = key;
new_node->value = value;
new_node->height = 1;
/* Insert at the NULL pointer that was reached */
*rover = new_node;
/* Rebalance the tree, starting from the previous node. */
avl_tree_balance_to_root(tree, previous_node);
/* Keep track of the number of entries */
++tree->num_nodes;
return new_node;
}
/* Find the nearest node to the given node, to replace it.
* The node returned is unlinked from the tree.
* Returns NULL if the node has no children. */
static AVLTreeNode *avl_tree_node_get_replacement(AVLTree *tree,
AVLTreeNode *node)
{
AVLTreeNode *left_subtree;
AVLTreeNode *right_subtree;
AVLTreeNode *result;
AVLTreeNode *child;
int left_height, right_height;
int side;
left_subtree = node->children[AVL_TREE_NODE_LEFT];
right_subtree = node->children[AVL_TREE_NODE_RIGHT];
/* No children? */
if (left_subtree == NULL && right_subtree == NULL) {
return NULL;
}
/* Pick a node from whichever subtree is taller. This helps to
* keep the tree balanced. */
left_height = avl_tree_subtree_height(left_subtree);
right_height = avl_tree_subtree_height(right_subtree);
if (left_height < right_height) {
side = AVL_TREE_NODE_RIGHT;
} else {
side = AVL_TREE_NODE_LEFT;
}
/* Search down the tree, back towards the center. */
result = node->children[side];
while (result->children[1-side] != NULL) {
result = result->children[1-side];
}
/* Unlink the result node, and hook in its remaining child
* (if it has one) to replace it. */
child = result->children[side];
avl_tree_node_replace(tree, result, child);
/* Update the subtree height for the result node's old parent. */
avl_tree_update_height(result->parent);
return result;
}
/* Remove a node from a tree */
void avl_tree_remove_node(AVLTree *tree, AVLTreeNode *node)
{
AVLTreeNode *swap_node;
AVLTreeNode *balance_startpoint;
int i;
/* The node to be removed must be swapped with an "adjacent"
* node, ie. one which has the closest key to this one. Find
* a node to swap with. */
swap_node = avl_tree_node_get_replacement(tree, node);
if (swap_node == NULL) {
/* This is a leaf node and has no children, therefore
* it can be immediately removed. */
/* Unlink this node from its parent. */
avl_tree_node_replace(tree, node, NULL);
/* Start rebalancing from the parent of the original node */
balance_startpoint = node->parent;
} else {
/* We will start rebalancing from the old parent of the
* swap node. Sometimes, the old parent is the node we
* are removing, in which case we must start rebalancing
* from the swap node. */
if (swap_node->parent == node) {
balance_startpoint = swap_node;
} else {
balance_startpoint = swap_node->parent;
}
/* Copy references in the node into the swap node */
for (i=0; i<2; ++i) {
swap_node->children[i] = node->children[i];
if (swap_node->children[i] != NULL) {
swap_node->children[i]->parent = swap_node;
}
}
swap_node->height = node->height;
/* Link the parent's reference to this node */
avl_tree_node_replace(tree, node, swap_node);
}
/* Destroy the node */
free(node);
/* Keep track of the number of nodes */
--tree->num_nodes;
/* Rebalance the tree */
avl_tree_balance_to_root(tree, balance_startpoint);
}
/* Remove a node by key */
int avl_tree_remove(AVLTree *tree, AVLTreeKey key)
{
AVLTreeNode *node;
/* Find the node to remove */
node = avl_tree_lookup_node(tree, key);
if (node == NULL) {
/* Not found in tree */
return 0;
}
/* Remove the node */
avl_tree_remove_node(tree, node);
return 1;
}
AVLTreeNode *avl_tree_lookup_node(AVLTree *tree, AVLTreeKey key)
{
AVLTreeNode *node;
int diff;
/* Search down the tree and attempt to find the node which
* has the specified key */
node = tree->root_node;
while (node != NULL) {
diff = tree->compare_func(key, node->key);
if (diff == 0) {
/* Keys are equal: return this node */
return node;
} else if (diff < 0) {
node = node->children[AVL_TREE_NODE_LEFT];
} else {
node = node->children[AVL_TREE_NODE_RIGHT];
}
}
/* Not found */
return NULL;
}
AVLTreeValue avl_tree_lookup(AVLTree *tree, AVLTreeKey key)
{
AVLTreeNode *node;
/* Find the node */
node = avl_tree_lookup_node(tree, key);
if (node == NULL) {
return AVL_TREE_NULL;
} else {
return node->value;
}
}
AVLTreeNode *avl_tree_root_node(AVLTree *tree)
{
return tree->root_node;
}
AVLTreeKey avl_tree_node_key(AVLTreeNode *node)
{
return node->key;
}
AVLTreeValue avl_tree_node_value(AVLTreeNode *node)
{
return node->value;
}
AVLTreeNode *avl_tree_node_child(AVLTreeNode *node, AVLTreeNodeSide side)
{
if (side == AVL_TREE_NODE_LEFT || side == AVL_TREE_NODE_RIGHT) {
return node->children[side];
} else {
return NULL;
}
}
AVLTreeNode *avl_tree_node_parent(AVLTreeNode *node)
{
return node->parent;
}
int avl_tree_num_entries(AVLTree *tree)
{
return tree->num_nodes;
}
static void avl_tree_to_array_add_subtree(AVLTreeNode *subtree,
AVLTreeValue *array,
int *index)
{
if (subtree == NULL) {
return;
}
/* Add left subtree first */
avl_tree_to_array_add_subtree(subtree->children[AVL_TREE_NODE_LEFT],
array, index);
/* Add this node */
array[*index] = subtree->key;
++*index;
/* Finally add right subtree */
avl_tree_to_array_add_subtree(subtree->children[AVL_TREE_NODE_RIGHT],
array, index);
}
AVLTreeValue *avl_tree_to_array(AVLTree *tree)
{
AVLTreeValue *array;
int index;
/* Allocate the array */
array = malloc(sizeof(AVLTreeValue) * tree->num_nodes);
if (array == NULL) {
return NULL;
}
index = 0;
/* Add all keys */
avl_tree_to_array_add_subtree(tree->root_node, array, &index);
return array;
}
|
C
|
#include <stdio.h>
#include <locale.h>
int main()
{
setlocale(0,"Russian");
int N, k=1;
printf("Array size(N>0): ");
scanf("%d", &N);
int array[N];
for (int i=0; i<N; i++){
array[i]=k;
k+=2;
}
for (int i=0; i<N; i++){
printf("%d ", array[i]);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void *helper(void* arg) {
printf("Hello World! 1\n");
pthread_exit(0);
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, &helper, NULL);
/* pthread_join(thread, NULL); */
printf("Hello World! 2\n");
exit(0);
}
|
C
|
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#define KGRN "\x1B[32m"
#define KRED "\x1B[31m"
#define KWHT "\x1B[37m"
#define MSG_REQUEST 1 //request critical section
#define MSG_RELEASE 2 //release critical section
#define MSG_CONFIRM 3 //confirm that you got a request
#define MSG_SIZE 3 //size of msg buff
#define MAX_QUEUE_SIZE 50//max size of windmill queue array
typedef struct Knight
{
int rank;
int clock;
}Knight;
typedef struct Windmill
{
Knight queue[MAX_QUEUE_SIZE];
int queueSize;
}Windmill;
//send data to all other processes from 0 - processNum without yourself (myRank) (MPI_Bcast cant receive msg when sender is not known)
void myBcast(const void* msg, int msg_size, MPI_Datatype datatype,int msgTag, MPI_Comm comm, int processNum, int myRank){
for(int i=0; i<processNum; i++){
if(i!=myRank){
MPI_Send(msg, msg_size, datatype, i, msgTag, comm);
}
}
}
void insertSort(Knight knight, Windmill *windmill){
int index = -1;
for(int i=0; i<windmill->queueSize; i++){
if(knight.clock < windmill->queue[i].clock){
index = i;
break;
}
//if clocks are the same and there is a conflict sort by knights' rank
else if(knight.clock == windmill->queue[i].clock){
if(knight.rank < windmill->queue[i].rank){
index = i;
break;
}
else continue;
}
}
if(index<0){
windmill->queue[windmill->queueSize] = knight;
}
else{
int j = windmill->queueSize;
while(j > index){
windmill->queue[j] = windmill->queue[j-1];
j--;
}
windmill->queue[j] = knight;
}
windmill->queueSize++;
}
void removeSort(int knightRank, Windmill *windmill){
int index = -1;
for(int i=0; i<windmill->queueSize; i++){
if(windmill->queue[i].rank == knightRank){
index = i;
break;
}
}
if(index >= 0){
for(int i=index; i<windmill->queueSize-1; i++){
windmill->queue[i] = windmill->queue[i+1];
}
windmill->queueSize--;
}
}
void requestCritcalSection(int myRank, int *globalClock, Windmill *windmill, int windmillNum, int processesNum){
int msg[MSG_SIZE];
*globalClock += 1;
Knight k;
k.rank = myRank;
k.clock = *globalClock;
msg[0] = windmillNum;
msg[1] = myRank;
msg[2] = *globalClock;
myBcast(msg, MSG_SIZE, MPI_INT, MSG_REQUEST, MPI_COMM_WORLD, processesNum, myRank);
insertSort(k, windmill);
}
void receiveCriticalSectionRequest(int myRank, int whoRank, int whoClock, Windmill *windmill, int *globalClock, int windmillNum){
if(whoClock > *globalClock){
*globalClock = whoClock + 1;
}
else{
*globalClock += 1;
}
Knight k;
k.rank = whoRank;
k.clock = whoClock;
insertSort(k, windmill);
//send confirmation
int msg[MSG_SIZE];
msg[0] = windmillNum;
msg[1] = myRank;
msg[2] = *globalClock;
MPI_Send(msg, MSG_SIZE, MPI_INT, whoRank, MSG_CONFIRM, MPI_COMM_WORLD);
}
bool isFirstN(int rank, Windmill *windmill, int n){
for(int i=0; i<n; i++){
if(windmill->queue[i].rank == rank)
return true;
}
return false;
}
void waitToEnter(int *counter, int processesNum, sem_t *semaphore, int myRank, Windmill *windmill){
//wait for confirmation from other knights
while(1){
if(*counter == processesNum -1){
break;
}
}
*counter = 0;
//wait till I'm one of the first 4 in queue
while(1){
if(isFirstN(myRank, windmill, 4)){
sem_post(semaphore); //let knight into the critical section
break;
}
}
}
void releaseCriticalSection(int *globalClock, int myRank, int processesNum, int windmillNum, Windmill *windmill){
*globalClock += 1;
int msg[MSG_SIZE];
msg[0] = windmillNum;
msg[1] = myRank;
msg[2] = *globalClock;
removeSort(myRank, windmill);
myBcast(msg, MSG_SIZE, MPI_INT, MSG_RELEASE, MPI_COMM_WORLD, processesNum, myRank);
}
void receiveCriticalSectionRelease(Windmill *windmill, int whoRank, int *globalClock){
*globalClock += 1;
removeSort(whoRank, windmill);
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<locale.h>
#include<string.h>
#include<stdlib.h>
struct info1
{
char pat[7];
int rut;
int paqm;
float capm;
};
int validadato(int,int,int);
void main()
{
setlocale(LC_CTYPE,"Spanish");
struct info1 aux;
int i,rut,paqm;
float capm;
char pat[7];
FILE *pf;
i=0;
pf=fopen("vehiculos.dat","ab");
printf("\n Cargue los datos de los vehculos. Recuerde que tiene casi 1000 productos. \n\n");
printf("\n NUEVO VEHCULO \n\n");
printf("\n Ingrese el nmero de ruta (entre 1 y 200)(Finalice con ruta cero): \n\n\t\t");
do
{
scanf("%d",&rut);
}
while(!validadato(rut,0,200));
while(rut!=0&&i<1000)
{
aux.rut=rut;
printf("\n Ingrese la patente del vehculo (hasta 6 caracteres): \n\n\t\t");
fflush(stdin);
gets(pat);
strcpy(aux.pat,pat);
printf("\n Ingrese la cantidad mxima de paquetes que pueden ser transportados \n en este vehculo (entre 1 y 2000): \n\n\t\t");
do
{
scanf("%d",&paqm);
}
while(!validadato(paqm,1,2000));
aux.paqm=paqm;
printf("\n Ingrese la capacidad mxima a transportar por este vehculo: \n\n\t\t");
do
{
scanf("%f",&capm);
}
while(capm<=0);
aux.capm=capm;
fwrite(&aux,sizeof(struct info1),1,pf);
i++;
printf("\n NUEVO VEHCULO \n\n");
printf("\n Ingrese el nmero de ruta (entre 1 y 200)(Finalice con ruta cero): \n\n\t\t");
do
{
scanf("%d",&rut);
}
while(!validadato(rut,0,200));
}
fclose(pf);
printf("\n Archivo creado/actualizado... \n\n");
getch();
}
int validadato(int x,int li,int ls)
{
if(x>=li&&x<=ls)
return 1;
else
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 201000
typedef struct edge_def {
struct node_def *u;
struct node_def *v;
int cost;
} edge;
typedef struct node_def {
int vertex;
struct node_def *parent;
int rank;
} node;
edge *edge_heap[MAX + 1];
node *nodes[MAX];
int nv, ne;
int last;
void push_edge(node *u, node *v, int cost) {
edge_heap[last]->u = u;
edge_heap[last]->v = v;
edge_heap[last]->cost = cost;
int i = last;
edge *temp;
while (edge_heap[i / 2]->cost > edge_heap[i]->cost) {
temp = edge_heap[i];
edge_heap[i] = edge_heap[i / 2];
edge_heap[i / 2] = temp;
i = i / 2;
}
++last;
}
edge *pop_edge() {
int i = last - 1, ci;
edge *temp;
temp = edge_heap[i];
edge_heap[i] = edge_heap[1];
edge_heap[1] = temp;
i = 1;
while (i < last / 2) {
if ((edge_heap[2 * i]->cost < edge_heap[2 * i + 1]->cost) || (2 * i == (last - 2))) {
ci = 2 * i;
} else {
ci = 2 * i + 1;
}
if (edge_heap[i]->cost > edge_heap[ci]->cost) {
temp = edge_heap[i];
edge_heap[i] = edge_heap[ci];
edge_heap[ci] = temp;
} else {
break;
}
i = ci;
}
--last;
return edge_heap[last];
}
void make_set() {
int i;
for (i = 0; i < nv; ++i) {
nodes[i]->parent = nodes[i];
}
}
node *find_set(node *v) {
if (v != v->parent) {
v->parent = find_set(v->parent);
}
return v->parent;
}
int are_disjoint(node *u, node *v) {
node *parent_u = find_set(u);
node *parent_v = find_set(v);
int are_disjoint = parent_u != parent_v;
return are_disjoint;
}
void link(node *u, node *v) {
if (u->rank > v->rank) {
v->parent = u;
} else {
u->parent = v;
if (u->rank == v->rank) {
++v->rank;
}
}
}
void union_vertices(node *u, node *v) {
node *parent_u = find_set(u);
node *parent_v = find_set(v);
link(parent_u, parent_v);
}
int mst() {
int i;
int saved = 0;
for (i = 0; i < ne; ++i) {
edge *current_edge = pop_edge();
if (are_disjoint(current_edge->u, current_edge->v)) {
union_vertices(current_edge->u, current_edge->v);
} else {
saved += current_edge->cost;
}
}
return saved;
}
int main() {
register int i;
int u, v, cost;
for (i = 0; i < MAX; ++i) {
edge_heap[i] = malloc(sizeof(edge));
nodes[i] = malloc(sizeof(node));
}
scanf("%d %d", &nv, &ne);
while (nv != 0 && ne != 0) {
edge_heap[0]->cost = -1;
last = 1;
make_set();
node *node_u, *node_v;
for (i = 0; i < ne; ++i) {
scanf("%d %d %d", &u, &v, &cost);
node_u = nodes[u];
node_v = nodes[v];
push_edge(node_u, node_v, cost);
}
int saved = mst();
printf("%d\n", saved);
scanf("%d %d", &nv, &ne);
}
return 0;
}
|
C
|
#ifndef __SERVEUR_H__
#define __SERVEUR_H__
/** \file serveur.h
* \brief This file provides BEEP server functions
* This file provides some usual functions for a server like init, reception and emission.
* It also contains some other derivated functions to test and play with received requests
* plus response making functions like status line and header fields answering .
*/
/** \fn int Init(char *port)
* \brief initialise the server
* \param port is the port which will be used by the server
* \return status code of this operation.
*
*/
int Init(char * port);
/** \fn int connectWait()
* \brief wait for a client to connect, and then open the connection with him
* \return status code of this operation.
*
*/
int connectWait();
/** \fn int receiveBinary(char ** data)
* \brief receive data from the client
* \param data is the data received from the client
* \return status code for this operation.
*
*/
int receiveBinary(char ** data);
/** \fn int sendBinary(char * data, size_t size)
* \brief send binary data to the client
* \param data binary data to send to the client
* \param size data's size
* \return status code for this operation.
*
*/
int sendBinary(char * data, size_t size);
/** \fn int sendString(char * data)
* \brief send a string to the client
* \param data string to send to the client
* \return status code for this operation.
*
*/
int sendString(char * data);
/** \fn void endClient()
* \brief close properly the connection with the client
*
*/
void endClient();
/** \fn void endServer()
* \brief close properly the server process
*
*/
void endServer();
/** \fn int sendStatusLine(int statusCode)
* \brief send a status line as described in the RFC
* \param statusCode the status code to send to the client the rigth status line
* \return status code for this operation.
*
*/
int sendStatusLine(int statusCode);
/** \fn int sendHeaderField(int size, int type)
* \brief send header fileds as described in the RFC
* \param size size of the data which will be transfered
* \param type type of the data which will be transfered
* \return status code for this operation.
*
*/
int sendHeaderField(int size, int type);
/** \fn int isGetRequest(char* request, int size)
* \brief test if a message is a GET request
* \param request message to test
* \param size size of this messsage
* \return status code for this operation.
*
*/
int isGetRequest(char* request, int size);
/** \fn int isPutRequest(char* request, int size)
* \brief test if a message is a PUT request
* \param request message to test
* \param size size of this messsage
* \return status code for this operation.
*
*/
int isPutRequest(char* request, int size);
/** \fn int isConnectRequest(char* request, int size)
* \brief test if a message is a CONNECT request
* \param request message to test
* \param size size of this messsage
* \return status code for this operation.
*
*/
int isConnectRequest(char* request, int size);
/** \fn int isDeleteRequest(char* request, int size)
* \brief test if a message is a DELETE request
* \param request message to test
* \param size size of this messsage
* \return status code for this operation.
*
*/
int isDeleteRequest(char* request, int size);
/** \fn int splitGetRequest(char* request, int size, char* data, int* sizeData)
* \brief split a GET request to find and output the PDU
* \param request the message which is a GET request
* \param size size of this message
* \param data output data extracted from this GET request
* \param sizeData size of the output data
* \return status code for this operation.
*
*/
int splitGetRequest(char* request, int size, char* data, int* sizeData);
/** \fn int splitPutRequest(char* request, int size, char* data, int* sizeData)
* \brief split a PUT request to find and output the PDU
* \param request the message which is a PUT request
* \param size size of this message
* \param data output data extracted from this PUT request
* \param sizeData size of the output data
* \return status code for this operation.
*
*/
int splitPutRequest(char * request, int size, char * data, int * sizeData);
/** \fn int splitConnectRequest(char* request, int size, char* login, char* password, int* sizeLogin, int* sizePassword)
* \brief split a CONNECT request to find and output the login and the password
* \param request the message which is a DELETE request
* \param size size of this message
* \param login login extracted from this CONNECT request
* \param password password extracted from this CONNECT request
* \param sizeLogin length of the login
* \param sizePassword length of the password
* \return status code for this operation.
*
*/
int splitConnectRequest(char * request, int size, char * login, char * password, int * sizeLogin, int * sizePassword);
/** \fn int splitDeleteRequest(char* request, int size, char* data, int* sizeData)
* \brief split a DELETE request to find and output the PDU
* \param request the message which is a DELETE request
* \param size size of this message
* \param data output data extracted from this DELETE request
* \param sizeData size of the output data
* \return status code for this operation.
*
*/
int splitDeleteRequest(char * request, int size, char * data, int * sizeData);
/** \fn int answerUserAccount(UserAccount * account)
* \brief send an UserAccount to the client
* \param account the UserAccount to send to the client
* \return status code for this operation.
*
*/
int answerUserAccount(UserAccount * account);
/** \fn int answerObjectBid(ObjectBid * object)
* \brief send an ObjectBid to the client
* \param object the ObjectBid to send to the client
* \return status code for this operation.
*
*/
int answerObjectBid(ObjectBid * object);
/** \fn int answerObjectBidTable(ObjectBid * objects, int nbrObjects)
* \brief send an ObjectBid table to the client
* \param objects the ObjectBid table to send to the client
* \param nbrObjects number of this objects
* \return status code for this operation.
*
*/
int answerObjectBidTable(ObjectBid * objects, int nbrObjects);
#endif
|
C
|
/**************************************************************************//**
* @file
* @brief This example toggles between the VS2 and VS1 voltage scaling
* levels in EM0. When observed using Simplicity Studio's Energy
* Profiler, the power savings achieved by running at a DECOUPLE
* voltage of 1.1V (VS2) vs. 1.0V (VS1) can be observed.
*
* @version 0.0.1
******************************************************************************
* @section License
* <b>(C) Copyright 2019 Silicon Labs, http://www.silabs.com</b>
*******************************************************************************
*
* This file is licensed under the Silicon Labs Software License Agreement. See
* "http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt"
* for details. Before using this software for any purpose, you must agree to the
* terms of that agreement.
*
******************************************************************************/
#include <stdio.h>
#include "em_device.h"
#include "em_chip.h"
#include "em_cmu.h"
#include "em_emu.h"
#include "em_gpio.h"
#include "bsp.h"
/*
* Used to run the Fibonacci code from RAM, which makes the power
* savings from voltage scaling more obvious in Energy Profiler.
*/
#include "em_ramfunc.h"
/**************************************************************************//**
* For portability among radio boards, use GPIO_ODD_IRQn if
* BSP_GPIO_PB0_PIN is odd, otherwise use GPIO_EVEN_IRQn.
*****************************************************************************/
#if (BSP_GPIO_PB0_PIN & 1)
#define BUTTON_GPIO_IRQ GPIO_ODD_IRQn
#else
#define BUTTON_GPIO_IRQ GPIO_EVEN_IRQn
#endif
/**************************************************************************//**
* @brief GPIO initialization
*****************************************************************************/
void initGpio(void)
{
CMU_ClockEnable(cmuClock_GPIO, true);
// Configure PB0 as input
GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeInputPullFilter, 1);
// Enable rising-edge interrupts on the PB0 pin
GPIO_ExtIntConfig(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, BSP_GPIO_PB0_PIN, 1, 0, true);
NVIC_ClearPendingIRQ(BUTTON_GPIO_IRQ );
NVIC_EnableIRQ(BUTTON_GPIO_IRQ );
}
/**************************************************************************//**
* @brief GPIO IRQ handler
*
* For portability among radio boards, compile GPIO_ODD_IRQHandler if
* BSP_GPIO_PB0_PIN is odd, otherwise use GPIO_EVEN_IRQHandler.
*****************************************************************************/
#if (BSP_GPIO_PB0_PIN & 1)
void GPIO_ODD_IRQHandler(void)
#else
void GPIO_EVEN_IRQHandler(void)
#endif
{
EMU_EM01Init_TypeDef vsInit = EMU_EM01INIT_DEFAULT;
EMU_VScaleEM01_TypeDef vscale;
// Get the current voltage scaling
vscale = EMU_VScaleGet();
if (vscale == emuVScaleEM01_HighPerformance)
{
// Currently running at VS2 (high performance), so scale down
vsInit.vScaleEM01LowPowerVoltageEnable = true;
}
else
{
// Currently running at VS1 (low power), so scale up
vsInit.vScaleEM01LowPowerVoltageEnable = false;
}
/*
* Perform voltage scaling and set the appropriate number of flash
* wait states.
*/
EMU_EM01Init(&vsInit);
// Clear the PB0 pin interrupt flag
GPIO_IntClear(1 << BSP_GPIO_PB0_PIN);
}
/**************************************************************************//**
* @brief Calculates the n-th Fibonacci number recursively.
*****************************************************************************/
SL_RAMFUNC_DEFINITION_BEGIN
uint32_t fib(uint32_t n)
{
if (n < 2)
{
return 1;
}
return (fib(n-1) + fib(n-2));
}
SL_RAMFUNC_DEFINITION_END
/**************************************************************************//**
* @brief Exercise the CPU and RAM in order to observe the difference
* in current draw when core VDD is (not) scaled.
*****************************************************************************/
SL_RAMFUNC_DEFINITION_BEGIN
int fibLoop(void)
{
// Infinite loop
while(1)
{
volatile uint32_t temp;
for(uint32_t i = 0; i < 0x3FF; i++)
{
temp = fib(i);
}
(void)temp;
}
}
SL_RAMFUNC_DEFINITION_END
/**************************************************************************//**
* @brief Main function
*****************************************************************************/
int main(void)
{
CHIP_Init();
/*
* Run at 38 MHz, the highest preset frequency band common to both
* VS2 and VS1, in order to see the difference in current draw
* when not scaled vs. scaled.
*/
CMU_HFRCODPLLBandSet(cmuHFRCODPLLFreq_38M0Hz);
initGpio();
// Run the Fibonacci code to exercise the CPU and RAM subsystems.
fibLoop();
}
|
C
|
/* * * * * * *
* Module for creating and manipulating queues of integers
*
* created for COMP20007 Design of Algorithms 2017
*
*/
#include <stdbool.h>
#include "list.h"
// create a new queue and return a pointer to it
List* new_queue();
// destroy a queue and free its memory
void free_queue(List* list);
// add an element to the queue
// this operation is O(1)
void queue_enqueue(List* list, int data);
// remove and return an element from the queue
// this operation is O(1)
// error if the queue is empty (so first ensure queue_size() > 0)
int queue_dequeue(List* list);
// return the number of elements contained in a queue
int queue_size(List* list);
|
C
|
/*
* Copyright (c) 2003, Intel Corporation. All rights reserved.
* Created by: salwan.searty REMOVE-THIS AT intel DOT com
* This file is licensed under the GPL license. For the full content
* of this license, see the COPYING file at the top level of this
* source tree.
This program verifies that sigpause() returns -1 and sets errno to EINVAL
if passed an invalid signal number.
*/
#define _XOPEN_SOURCE 600
#include <pthread.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include "posixtest.h"
#define SIGTOTEST SIGABRT
int main()
{
int return_value = 0;
int result;
return_value = sigpause(-1);
if (return_value == -1) {
if (errno == EINVAL) {
printf ("Test PASSED: sigpause returned -1 and set errno to EINVAL\n");
result = 0;
} else {
printf ("Test FAILED: sigpause did not set errno to EINVAL\n");
result = 1;
}
} else {
printf ("Test FAILED: sigpause did not return -1\n");
if (errno == EINVAL) {
printf ("Test FAILED: sigpause did not set errno to EINVAL\n");
}
result = 1;
}
if(result == 2) {
return PTS_UNRESOLVED;
}
if(result == 1) {
return PTS_FAIL;
}
printf("Test PASSED\n");
return PTS_PASS;
}
|
C
|
#include <stdio.h>
int main()
{
int temp, sum=0, i, number;
printf("\n \t Enter the number =");
scanf("%d",&number);
for(i=0; 0<number;i++)
{
temp=number%10;
number =number/10;
sum=sum+temp;
}
printf("\n \t Sum of digits = %d",sum);
printf("\n\t Enjoy The Proggramming With Me ");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct record{
char name[12];
int age;
};
int main(int argc, char *argv[])
{
struct record array[2];
FILE *fp = fopen("recfile", "r");
if(fp == NULL){
perror("open file");
exit(1);
}
fread(array, sizeof(struct record), 2, fp);
printf("read name:%s, age:%d\n", array[0].name, array[0].age);
printf("read name:%s, age:%d\n", array[1].name, array[1].age);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
struct TYPE_2__ {int pagesize; } ;
/* Variables and functions */
unsigned int decodeInt32 (unsigned char*) ;
unsigned char* fileRead (int,int) ;
TYPE_1__ g ;
int /*<<< orphan*/ print_decode_line (unsigned char*,int,int,char*) ;
int /*<<< orphan*/ printf (char*,...) ;
int /*<<< orphan*/ sprintf (char*,char*,int) ;
int /*<<< orphan*/ sqlite3_free (unsigned char*) ;
__attribute__((used)) static void decode_trunk_page(
int pgno, /* The page number */
int detail, /* Show leaf pages if true */
int recursive /* Follow the trunk change if true */
){
int n, i;
unsigned char *a;
while( pgno>0 ){
a = fileRead((pgno-1)*g.pagesize, g.pagesize);
printf("Decode of freelist trunk page %d:\n", pgno);
print_decode_line(a, 0, 4, "Next freelist trunk page");
print_decode_line(a, 4, 4, "Number of entries on this page");
if( detail ){
n = (int)decodeInt32(&a[4]);
for(i=0; i<n; i++){
unsigned int x = decodeInt32(&a[8+4*i]);
char zIdx[10];
sprintf(zIdx, "[%d]", i);
printf(" %5s %7u", zIdx, x);
if( i%5==4 ) printf("\n");
}
if( i%5!=0 ) printf("\n");
}
if( !recursive ){
pgno = 0;
}else{
pgno = (int)decodeInt32(&a[0]);
}
sqlite3_free(a);
}
}
|
C
|
#include "header.h"
int bubblesort (int *array, int size) {
int i;
int j;
int temp;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
temp = *(array + i);
*(array + i) = *(array + j);
*(array + j) = temp;
}
}
return *array;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "stm32f30x_gpio.h"
#include "stm32f30x_usart.h"
void usart2_init() {
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// Datasheet -> Alternate functions for port D -> PD5
GPIO_PinAFConfig(GPIOD, GPIO_PinSource5, GPIO_AF_7);
// Configure pin in output push/pull mode
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStructure);
USART_InitTypeDef usart1_init_struct;
usart1_init_struct.USART_BaudRate = 9600;
usart1_init_struct.USART_WordLength = USART_WordLength_8b;
usart1_init_struct.USART_StopBits = USART_StopBits_1;
usart1_init_struct.USART_Parity = USART_Parity_No ;
usart1_init_struct.USART_Mode = USART_Mode_Tx;
usart1_init_struct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_Init(USART2, &usart1_init_struct);
USART_Cmd(USART2, ENABLE);
}
void usart_printf(USART_TypeDef *usart, const char * format, ...)
{
char buf[32];
va_list args;
va_start (args, format);
vsnprintf (buf, sizeof(buf), format, args);
va_end (args);
unsigned int i;
for(i = 0; i < strlen(buf); i++)
{
USART_SendData(usart, buf[i]);
while (!(usart->ISR & USART_ISR_TXE));
}
}
int main()
{
usart2_init();
usart_printf(USART2, "x=%d\n\r", 1);
// ...Or press 'Reset'
while (1) { }
}
|
C
|
//
// main.c
// lab_4_problem_1
//
// Created by Chris Miller on 7/8/18.
// Copyright © 2018 Chris Miller. All rights reserved.
//
#include <stdio.h>
#define SIZE 3
void change(int * const array, const size_t size);
void printArray(int * const array, const size_t size);
int main(int argc, const char * argv[]) {
// insert code here...
int nums[SIZE] = {1,2,3};
puts("The Array is:");
printArray(nums, SIZE);
puts("");
change(nums, SIZE);
puts("The change to array is:");
for (int i =0; i < SIZE; ++i) {
printf("%d ", nums[i]);
}
puts("");
return 0;
}
void change(int * const array, const size_t size) {
for (int i = 0; i < SIZE; ++i) {
array[i] = array[i] * 2;
}
}
void printArray(int * const array, const size_t size) {
for (int i = 0; i < SIZE; ++i) {
printf("%d ", array[i]);
}
}
|
C
|
//--------------------------------------------------------------------------
// Name: web_proxy.c
// Author: Adam Smrekar
// Date: November 22, 2019
// Description: HTTP-based GET web proxy that handles multiple
// simulatanous requests from users.
// Note: Some of this code is referenced from boiler plate
// code given for this assignment.
// usage: webproxy <port>
//--------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <linux/limits.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define MAXLINE 8192 // max text line length
#define MAXBUF 8192 // max I/O buffer size
#define LISTENQ 1024 // second argument to listen()
#define ERROR400 "HTTP/1.1 200 Document Follows\r\nContent-Type:text/html\r\nContent-Length:34\r\n\r\n<html><h1>HTTP 400 Bad Request</h1>"
//--------------------------------------------------------------------------
// @Name: http_parse_host_name
// @Description:
// Parses host name
//--------------------------------------------------------------------------
void http_parse_host_name(char *buf, char *hostname) {
const char host_buf[] = "Host: ";
char tmp_buf[MAXBUF] = { 0 };
char *str;
memcpy(tmp_buf, buf, MAXBUF);
// Parsing Host Name
if((str = strstr(tmp_buf, host_buf)) != NULL) {
char host_name[MAXBUF];
strtok(str, "\r\n");
snprintf(host_name, MAXBUF, "%s", str + sizeof(host_buf) - 1);
// Print
printf("host_name: %s\n", host_name);
memcpy(hostname, host_name, sizeof(host_name));
}
else {
// https://stackoverflow.com/questions/41286260/parse-http-request-line-in-c
// Referenced from stackoverflow user: Sanchke Dellowar
// Used to parse test
// Parse request
const char *start_of_host = strchr(buf, ' ') + 1;
const char *end_of_query;
// Check if port specified
if(strstr(start_of_host, ":") != NULL)
end_of_query = strchr(start_of_host, ':');
else
end_of_query = strchr(start_of_host, ' ');
// Initialize host_name with correct size of host
char host_name[end_of_query - start_of_host];
// Copy host name
strncpy(host_name, start_of_host, end_of_query - start_of_host);
// Add NULL terminator
host_name[sizeof(host_name)] = 0;
// Print
printf("host_name: %s\n", host_name);
memcpy(hostname, host_name, sizeof(host_name));
printf("hostname: %s\n", hostname);
}
}
//--------------------------------------------------------------------------
// @Name: http_parse_port
// @Description:
// Parses port of the address
//--------------------------------------------------------------------------
int http_parse_port(char *buf) {
const char host_buf[] = "Host: ";
char tmp_buf[MAXBUF] = { 0 };
char port[MAXBUF] = { 0 };
char *str;
int port_ret = 80;
memcpy(tmp_buf, buf, MAXBUF);
// Parsing Host Name
if((str = strstr(tmp_buf, host_buf)) != NULL) {
char host_name[MAXBUF];
strtok(str, "\r\n");
snprintf(host_name, MAXBUF, "%s", str + sizeof(host_buf) - 1);
// Print
printf("host_name: %s\n", host_name);
// Parse Port
memset(str, 0, sizeof(str));
if((str = strstr(host_name, ":")) != NULL) {
strtok(str, ":");
snprintf(port, MAXBUF, "%s", str + 1);
printf("Port: %s\n", port);
port_ret = atoi(port);
if(port_ret >= 1 && port_ret <= 65535)
printf("Port in range!\n");
else
port_ret = 80;
}
}
else {
// Used to parse test
// Parse request
const char *start_of_host = strchr(buf, ' ') + 1;
char *end_of_host;
// Check if port specified
if((str = strstr(start_of_host, ":")) != NULL) {
end_of_host = strchr(start_of_host, ':');
str = strtok(end_of_host, " ");
snprintf(port, MAXBUF, "%s", str + 1);
printf("Port: %s\n", port);
port_ret = atoi(port);
if(port_ret >= 1 && port_ret <= 65535)
printf("Port in range!\n");
else
port_ret = 80;
}
}
return port_ret;
}
//--------------------------------------------------------------------------
// @Name: http_valid_check
// @Description:
// Checks of HTTP is valid
//--------------------------------------------------------------------------
int http_valid_check(char *buf) {
char tmp_buf[MAXBUF] = { 0 };
strcpy(tmp_buf, buf);
// Check GET header
if(strtok(tmp_buf, "\r\n") == NULL) {
if( (strstr(tmp_buf, "GET") == NULL) ||
(strstr(tmp_buf, "/") == NULL) ||
((strstr(tmp_buf, "HTTP/1.1") == NULL) &&
(strstr(tmp_buf, "HTTP/1.0") == NULL)))
return false;
return false;
}
return true;
}
//--------------------------------------------------------------------------
// @Name: http_if_host_exists
// @Description:
// Checks if host exists
//--------------------------------------------------------------------------
int http_if_host_exists(char *buf) {
char tmp_buf[MAXBUF] = { 0 };
char host_name[MAXBUF] = { 0 };
struct hostent *host;
memcpy(tmp_buf, buf, MAXBUF);
http_parse_host_name(tmp_buf, host_name);
if((host = gethostbyname(host_name)) == NULL)
return false;
return true;
}
//--------------------------------------------------------------------------
// @Name: open_listenfd
// @Description:
// Creates TCP socket for listening
//--------------------------------------------------------------------------
int open_listenfd(int port) {
int listenfd, optval = 1;
struct sockaddr_in serveraddr;
// Create a socket descriptor
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
// Eliminates "Address already in use" error from bind.
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int)) < 0)
return -1;
// listenfd will be an endpoint for all requests to port
// on any IP address for this host
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
if (bind(listenfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
// Make it a listening socket ready to accept connection requests
if (listen(listenfd, LISTENQ) < 0)
return -1;
return listenfd;
}
//--------------------------------------------------------------------------
// @Name: connectfd
// @Description:
//
//--------------------------------------------------------------------------
int connectfd(int port, char *host_name) {
struct addrinfo hints, *res;
int sockfd;
char port_c[6] = { 0 };
// Convert port int to string
snprintf(port_c, 6, "%d", port);
// Load up address structs with getaddrinfo()
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo(host_name, port_c, &hints, &res);
// Create a socket descriptor
if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0)
return -1;
// Connect
if (connect(sockfd, res->ai_addr, res->ai_addrlen) < 0)
return -1;
return sockfd;
}
//--------------------------------------------------------------------------
// @Name: handle_requests
// @Description:
//
//--------------------------------------------------------------------------
void handle_requests(int connfd) {
size_t n;
int r, file_found, sockfd;
int host_exists = 0;
int valid = 0;
int port = 0;
int read_size = 0;
long file_size;
char content_type[MAXBUF] = { 0 };
char host_name[MAXBUF] = { 0 };
char buf[MAXLINE] = { 0 };
char recv_buf[MAXLINE] = { 0 };
FILE *fp;
// Clear Buffer
memset(buf, 0, MAXBUF);
// Read input
if(read(connfd, buf, MAXLINE) < 0)
printf("Error with read 1\n");
// Check if http method is valid
valid = http_valid_check(buf);
if(valid) {
printf("HTTP Valid!\n");
// Check if requested IP exists
host_exists = http_if_host_exists(buf);
}
else
printf("HTTP Invalid!\n");
if(host_exists) {
// Make TCP connection with server or client
// Depending on which side of the proxy
http_parse_host_name(buf, host_name);
printf("Host [%s] exists!\n", host_name);
// Get port number (if not specified, port = 80)
port = http_parse_port(buf);
printf("Port: %d\n", port);
// Connect to host_name
sockfd = connectfd(port, host_name);
printf("Sockfd: %d\n", sockfd);
// Send request to host_name
if(write(sockfd, buf, MAXBUF) < 0)
printf("Error with send to host\n");
// Read request from host_name
// Send to client
while((read_size = read(sockfd, buf, MAXBUF)) > 0) {
write(connfd, buf, read_size);
bzero(buf, MAXBUF);
}
close(sockfd);
}
else {
http_parse_host_name(buf, host_name);
printf("Host [%s] doesn't exist!\n", host_name);
write(connfd, ERROR400, sizeof(ERROR400));
}
}
//--------------------------------------------------------------------------
// @Name: thread
// @Description:
// Thread worker. Detaches thread and calls handle_requests function
//--------------------------------------------------------------------------
void *thread(void *vargp) {
int connfd = *((int *)vargp);
pthread_detach(pthread_self());
free(vargp);
handle_requests(connfd);
close(connfd);
return NULL;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
int main(int argc, char **argv) {
int listenfd, *connfdp, port;
int clientlen = sizeof(struct sockaddr_in);
struct sockaddr_in clientaddr;
pthread_t tid;
if (argc != 2) {
fprintf(stderr, "usage: webproxy <port>\n");
exit(0);
}
port = atoi(argv[1]);
listenfd = open_listenfd(port);
while (1) {
connfdp = malloc(sizeof(int));
*connfdp = accept(listenfd, (struct sockaddr*)&clientaddr, &clientlen);
pthread_create(&tid, NULL, thread, connfdp);
}
}
|
C
|
#ifndef RT_SPHERE
#define RT_SPHERE
#include "hittable.h"
struct sphere : public hittable
{
sphere() {}
sphere(point3 _center, double _radius, shared_ptr<material> _material) : center(_center), radius(_radius), material(_material) { }
point3 center;
double radius;
shared_ptr<material> material;
bool hit(const ray& ray, double t_min, double t_max, hit_record& rec) const override;
};
bool sphere::hit(const ray& ray, double t_min, double t_max, hit_record& rec) const
{
// quadratic equation
vec3 diff = ray.origin() - center;
double a = ray.direction().length_squared();
double half_b = dot(diff, ray.direction());
double c = diff.length_squared() - radius * radius;
double discriminant = half_b*half_b - a*c;
// discriminant: positive = two real solutions, zero = one real solution, negative = no real solutions
if (discriminant < 0)
{
return false;
}
double sqrtDisc = sqrt(discriminant);
double root = (-half_b - sqrtDisc) / a;
// find nearest root that lies in the acceptable range
if (root < t_min || t_max < root) {
root = (-half_b + sqrtDisc) / a;
if (root < t_min || t_max < root)
return false;
}
rec.time = root;
rec.point = ray.at(rec.time);
vec3 outward_normal = (rec.point - center) / radius;
rec.set_face_normal(ray, outward_normal);
rec.material = material;
return true;
}
#endif // RT_SPHERE
|
C
|
#include <stdio.h>
int printnum(int );
int main()
{
long int n;
printf("enter the value of n\n");
scanf("%i",&n);
printnum(n);
return 0;
}
long int printnum(long int n)
{
return printnum(printf("%d ",n));
}
|
C
|
#include <unistd.h>
void print_bits(unsigned char octet) {
int i;
char c;
for (i = 7; i >= 0; i--) {
c = (octet & (1 << i)) ? '1' : '0';
write(1, &c, 1);
}
}
|
C
|
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int fd, copyfd;
fd = open("./log.txt", O_RDWR|O_CREAT);
copyfd = dup(fd);
char buf1[] = "hello ";
char buf2[] = "world!";
if (write(fd, buf1, 6) != 6) {
printf("write error!");
}
printf("%d\n", (int)lseek(fd, 0, SEEK_CUR));
printf("%d\n", (int)lseek(copyfd, 0, SEEK_CUR));
if (write(copyfd, buf2, 6) != 6) {
printf("write error!");
}
return 0;
}
|
C
|
#include <esc64asm/mempool.h>
#include <stdlib.h>
void MemPoolInit(MemPool* pool, size_t size, void* mem)
{
pool->begin = mem;
pool->end = mem + size;
pool->head = mem;
}
void MemPoolClear(MemPool* pool)
{
pool->head = pool->begin;
}
void* MemPoolAlloc(MemPool* pool, size_t size)
{
size_t freeSize = pool->end - pool->head;
if(freeSize < size)
{
return NULL;
}
void* r = pool->head;
pool->head += size;
return r;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *fp;
int time1, time2, hour, min, sec, diff;
char h1[3], m1[3], s1[3], h2[3], m2[3], s2[3];
fp = fopen(argv[1], "r");
while(fscanf(fp, "%2s:%2s:%2s %2s:%2s:%2s\n",
h1, m1, s1, h2, m2, s2) == 6)
{
time1 = atoi(h1)*3600 + atoi(m1)*60 + atoi(s1);
time2 = atoi(h2)*3600 + atoi(m2)*60 + atoi(s2);
if(time1 > time2)
{
diff = time1-time2;
}
else
{
diff = time2-time1;
}
hour = diff/3600;
min = (diff%3600)/60;
sec = diff%60;
printf("%02i:%02i:%02i\n",
hour, min, sec);
}
return 0;
}
|
C
|
/* Upon finishing the first half of nand2tetris (and implementing the
* assembler for Project 6 in Python), I wanted to learn C to a basic level.
* After a little thought, I decided re-implementing the assembler in C would
* make for a decent milestone of basic competence and also give me something
* to focus on while integrating the new concepts.
*
* For all its reputation as a simple language, my experience learning basic C
* reminded me of my experience with Arch Linux. Technically, Arch is a very
* simple distribution, with a manual installer and no desktop environment
* by default, yet it's famously difficult for novices to get running.
* I think this is because "simplicity" in computer terms doesn't necessarily
* translate to "ease of use". In fact it often requires more expertise.
* The less the system does for you, the more you need to know and understand
* in order to direct it appropriately. A manual transmission in a car might be
* "simple", but it demands more of the user. Of course there are tradeoffs
* in the form of reduced control if you abstract out those demands, as well
* as the possibility for more frequent and difficult problems to arise.
*
* Thankfully, my experience with nand2tetris was very helpful in learning C,
* and some concepts which have a reputation for being challenging weren't so
* hard for me to pick up (pointers, for example, and memory allocation).
*
* I had two major struggles during this project. The first is the basic task
* of working with strings in C. Since they are implemented as arrays of chars,
* the modality is worlds apart from Python with its smorgasbord of convenient
* string manipulation methods. Even after adjusting my mental model to
* arrays, I ran into several confusing bugs related to terminating characters.
* The second major challenge was the overall mindset required. Coming from
* higher level languages, my instinct was to research built-in functionality
* for each use-case. Several times I found functions that were close to what
* I needed, and tried to bend my design around those functions. This mostly
* wasted time, and eventually I found working in C much easier when I started
* to default to "rolling my own" (ex. tobinary and lookup functions). Rather
* than looking for easy string split methods or using strtok, I instead
* learned what strtok does and then wrote my own barebones version that
* addressed my particular needs.
*
* Overall learning C and completing this project have been my most fruitful
* work yet in becoming a better coder.
*/
/* This project could have fit in one file, but splitting it up makes more
* organizational sense and helped me learn how best to modularize / DRY
* my code in C.
*/
#include "headers.h"
#include "data.c"
#include "table.c"
#include "parser.c"
/* Naturally, this was actually completed last. I had already grown comfortable
* working with strings while building second_pass(), so most of what I learned
* here was related to structs / data structures in C. Linked lists were
* already familiar to me in other languages, so it was mostly a question of
* syntax and also honing my fluency using pointers.
*/
int first_pass() {
char* line = (char*) malloc(100*sizeof(char));
int line_number = 0;
while (fgets(line, 1000, stdin) != NULL) {
line = cleanupLine(line);
char type = getCommandType(line);
if (type == 'L') {
char* symbol = (char*) malloc(100*sizeof(char));
char* val = (char*) malloc(100*sizeof(char));
stripParens(line, symbol);
sprintf(val, "%d", line_number);
symbol_table = s_install(symbol_table, symbol, val);
} else if (type == '?') {
;
} else {
line_number++;
}
}
}
/* This was a good lesson in planning. When I wrote the assembler in Python,
* I was able to treat everything as a class and write an easy skeleton up
* front. With more experience I could probably do the same in C, but for this
* project I had to spend a lot more time clarifying up front how I would
* structure my code.
*/
int second_pass() {
char* line = (char*) malloc(100*sizeof(char));
char type;
while (fgets(line, 1000, stdin) != NULL) {
line = cleanupLine(line);
char binline[] = "0000000000000000";
type = getCommandType(line);
if (type == '?' || type == 'L') {
;
} else if (type == 'A') {
encode_A(line, binline);
printf("%s\n", binline);
} else {
encode_C(line, binline);
printf("%s\n", binline);
}
}
}
/* rewind(stdin) is a neat trick :)
*/
int main() {
first_pass();
rewind(stdin);
second_pass();
}
|
C
|
#include<stdio.h>
#define ELEMENTI 4
#define CAPACITA 9
int zaino(const int *Capacity, const int *Weight, int *Profit, const int *n);
int max(int Value1, int Value2);
int main() {
int profit[] = {10, 7, 8, 6};
int weight[] = {4, 2, 3, 4};
int Capacita = CAPACITA;
int n = ELEMENTI;
printf("The solution is : %d", zaino(&Capacita, weight, profit, &n));
return 0;
}
/**
* @DP la matrice che deve contenere anche i valori zero per questo ha grandezza +1
* @i indice di riga che itera sul numero di elementi che posso prendere
* @c indice di colonna ovvero la capacità dello zaino che rimane */
int zaino(const int *Capacity, const int *Weight, int *Profit, const int *n) {
int i, c;
int DP[(*n) + 1][(*Capacity) + 1];
for (i = 0; i <= *n; i++) {
for (c = 0; c <= *Capacity; c++) {
if (i == 0 || c == 0)
DP[i][c] = 0;
else if (Weight[i - 1] <= c)
DP[i][c] = max(Profit[i - 1] + DP[i - 1][c - Weight[i - 1]], DP[i - 1][c]);
else
DP[i][c] = DP[i - 1][c];
}
}
/*Stama di una matrice */
for (i = 0; i <= *n; i++) {
for (c = 0; c <= *Capacity; c++) {
printf("%d ", DP[i][c]);
}
printf("\n");
}
printf("\n");
return DP[*n][*Capacity];
}
int max(int Value1, int Value2) {
if (Value1 > Value2) {
return Value1;
} else {
return Value2;
}
}
|
C
|
#include<stdio.h>
int main()
{
int n,i;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
int m=lcm(a,n);
printf("%d",m);
}
int lcm(int a[], int n)
{
// Initialize result
int ans = a[0];
// ans contains LCM of arr[0], ..arr[i]
// after i'th iteration,
for(int i=1;i<n;i++)
{
ans = (((a[i] * ans))
(gcd(a[i], ans)));
}
return ans;
}
|
C
|
#include <assert.h>
#include <string.h>
#include "map.h"
#include "aroma.h"
#include "army.h"
#define MIN_ARMY_SIZE 3
void enlist(point p) {
grid(army, p) = 0;
}
void promote(point p) {
if (map_has_friendly_ant(p)) {
grid(army, p) += 1;
}
}
void initial_inspection(point p) {
if (grid(army_aroma, p) == 0.0) return;
if (map_has_friendly_ant(p)) {
foreach_point_within_manhattan_distance(p, 1, promote);
}
}
void officer_promote_neighbors(point p) {
if (grid(army, p) < MIN_ARMY_SIZE) return;
if (map_has_friendly_ant(p)) {
foreach_point_within_manhattan_distance(p, 1, promote);
}
}
void final_inspection(point p) {
if (grid(army, p) < MIN_ARMY_SIZE) {
grid(army, p) = 0;
} else {
grid(army, p) = 1;
}
}
void army_calculate() {
foreach_point(enlist);
foreach_point(initial_inspection);
foreach_point(officer_promote_neighbors);
foreach_point(final_inspection);
}
char *army_to_string() {
static char buffer[MAX_ROWS * (MAX_COLS + 1)];
char *output = buffer;
point p;
for (p.row = 0; p.row < rows; p.row++) {
for (p.col = 0; p.col < cols; p.col++) {
if (map_has_land(p)) {
if (map_has_food(p)) {
*output++ = '*';
} else if (map_has_ant(p)) {
// *output++ = '0' + grid(army, p);
if (grid(army, p)) {
*output++ = 'A' + grid(owner, p);
} else {
*output++ = 'a' + grid(owner, p);
}
} else {
*output++ = '.';
}
} else if (map_has_water(p)) {
*output++ = '%';
} else {
*output++ = '?';
}
}
*output++ = '\n';
}
*--output = '\0';
return buffer;
}
#ifdef UNIT_TESTS
#undef UNIT_TESTS
#include "globals.c"
#include "map.c"
#include "aroma.c"
int main(int argc, char *argv[]) {
char *input, *expected;
input = "..aa..b.....*.............\n"
"...aa.b............a......\n"
"...........a..........a...\n"
"....a.......a.........a...\n"
".................aa...a...\n"
"..........................\n"
"....a..a.......aaaa.......\n"
"....aa.a..........a.......\n"
"................a.a.......\n"
"..................a.......\n"
"..........................";
expected = "..AA..b.....*.............\n"
"...AA.b............a......\n"
"...........a..........A...\n"
"....a.......a.........A...\n"
".................aa...A...\n"
"..........................\n"
"....A..a.......AAAA.......\n"
"....AA.a..........A.......\n"
"................a.A.......\n"
"..................A.......\n"
"..........................";
map_load_from_string(input);
aroma_stabilize();
army_calculate();
// puts(map_to_string());
// puts(army_to_string());
assert(strcmp(army_to_string(), expected) == 0);
puts("ok");
return 0;
}
#endif
|
C
|
/*************************************************************************
> File Name: 2.96.blog.c
> Author: sukong
> Mail: sukong@outlook.com
> Created Time: 2016年04月19日 星期二 09时41分42秒
************************************************************************/
#include<stdio.h>
#include<types.h>
int float_f2i(float_bits f){
unsigned sign = f>>31;
int exp = (f>>23) & 0xFF;
int frac = (f&0x7FFFFF) | (1<<23);
exp -= 127;
if(exp < 0) return 0;
if(exp >= 31) return 0x80000000; //绝对值不大于2^31(1<<31)
if(exp > 23) frac <<= (exp - 23);
else frac >>= (23 - exp);
return sign? -frac : frac;
}
int main() {
int x = 0;
do {
int i = float_f2i(x);
int j = (int)u2f(x);
if(i != j) {
printf("error in %x: %d %d",x,i,j);
return 0;
}
x++;
}while(x != 0);
printf("test ok!");
return 1;
}
|
C
|
/*
** song.c for in /home/sabour_f/rendu/ircbot/AI/src
**
** Made by Florian SABOURIN
** Login <sabour_f@epitech.net>
**
** Started on Wed May 6 18:18:18 2015 Florian SABOURIN
** Last update Wed May 6 18:18:18 2015 Florian SABOURIN
*/
#include "database.h"
#include <stdlib.h>
#include <string.h>
t_song* song_from_db(t_mapstring* res, unsigned int it)
{
t_vector* curr;
t_song* ret;
ret = malloc(sizeof(t_song));
if (!ret)
return (NULL);
memset(ret, 0, sizeof(t_song));
if ((curr = mapstring_findcstr(res, "id")))
ret->id = atoi(vector_at(curr, it));
if ((curr = mapstring_findcstr(res, "author")) && vector_at(curr, it))
ret->authid = atoi(vector_at(curr, it));
if ((curr = mapstring_findcstr(res, "code")) && vector_at(curr, it))
if (!(ret->code = strdup(vector_at(curr, it))))
return (NULL + song_delete(ret, true));
if ((curr = mapstring_findcstr(res, "title")) && vector_at(curr, it))
if (!(ret->title = strdup(vector_at(curr, it))))
return (NULL + song_delete(ret, true));
if ((curr = mapstring_findcstr(res, "category")) && vector_at(curr, it))
if (!(ret->category = strdup(vector_at(curr, it))))
return (NULL + song_delete(ret, true));
return (ret);
}
int song_delete(t_song* song, bool free_struct)
{
free(song->title);
song->title = 0;
free(song->code);
song->code = 0;
free(song->category);
song->category = 0;
song->id = 0;
song->authid = 0;
if (free_struct)
free(song);
return (0);
}
t_vector* song_tab_from_db(t_mapstring* res)
{
t_vector* ret;
t_song* song;
size_t len;
size_t it;
len = vector_size(mapstring_findcstr(res, "id"));
ret = malloc(sizeof(t_vector));
if (!ret)
return (NULL);
it = 0;
vector_new(ret);
while (it < len)
{
song = song_from_db(res, it);
if (!song)
{
vector_foreach(ret, &free);
vector_delete(ret, true);
return (NULL);
}
if (vector_push_back(ret, song))
{
song_delete(song, true);
vector_foreach(ret, &free);
vector_delete(ret, true);
return (NULL);
}
++it;
}
return (ret);
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_insert_left - insert node to left child of parent.
* @parent: parent node.
* @value: value of new node.
* Return: new node inserted to the left child.
*/
binary_tree_t *binary_tree_insert_left(binary_tree_t *parent, int value)
{
binary_tree_t *new, *search;
if (!parent)
return (NULL);
new = malloc(sizeof(binary_tree_t));
if (new == NULL)
return (NULL);
new->left = NULL;
new->right = NULL;
search = parent;
while (search)
{
if (!search->left)
{
new->parent = search;
search->left = new;
new->n = value;
return (new);
}
if (search->left->n < value)
{
new->parent = search;
new->left = search->left;
search->left->parent = new;
search->left = new;
new->n = value;
return (new);
}
search = search->left;
}
return (new);
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <math.h>
int a2i(char *s);
int main(){
char * words = (char *) malloc(sizeof(char)*20);
printf("Enter: ");
scanf("%s", words);
int rtn = atoi(words);
printf("%d",rtn);
}
|
C
|
/* parallel_dot1.c -- Computes a parallel dot product. Uses MPI_Allreduce.
*
* Input:
* n: order of vectors
* x, y: the vectors
*
* Output:
* the dot product of x and y as computed by each process.
*
* Note: Arrays containing vectors are statically allocated. Assumes that
* n, the global order of the vectors, is evenly divisible by p, the
* number of processes.
*
* See Chap 5, pp. 76 & ff in PPMPI.
*/
#include <stdio.h>
#include "mpi.h"
#define MAX_LOCAL_ORDER 100
void Print_results( float dot, int my_rank, int p )
{ int q;
float temp;
MPI_Status status;
if (my_rank == 0)
{ printf("dot = \n");
printf("Process 0 > %f\n", dot);
for (q = 1; q < p; q++)
{ MPI_Recv(&temp, 1, MPI_FLOAT, q, 0, MPI_COMM_WORLD, &status);
printf("Process %d > %f\n", q, temp);
}
}
else
MPI_Send(&dot, 1, MPI_FLOAT, 0, 0, MPI_COMM_WORLD); // making process 0 print the result! all process have same value i.e the dot product of entire array
}
float Serial_dot( float x[], float y[], int n )
{ int i;
float sum = 0.0;
for (i = 0; i < n; i++)
sum = sum + x[i]*y[i];
return sum;
}
float Parallel_dot( float local_x[], float local_y[], int n_bar )
{ float local_dot, dot = 0.0;
local_dot = Serial_dot(local_x, local_y, n_bar);
// where we find the value to be added-> MPI_AllReduce() but the change is reflected in variable in all the proceses NO ROOT HERE!
MPI_Allreduce(&local_dot, &dot, 1, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD); // no root here!
return dot;
}
void Read_vector( char *prompt, float local_v[], int n_bar, int p, int my_rank )
{ int i, q;
float temp[MAX_LOCAL_ORDER];
MPI_Status status;
if (my_rank == 0)
{ printf("Enter %s\n", prompt);
for (i = 0; i < n_bar; i++)
scanf("%f", &local_v[i]);
for (q = 1; q < p; q++)
{ for (i = 0; i < n_bar; i++)
scanf("%f", &temp[i]);
// MPI_Bcast() when from one process to all process same data!!
MPI_Send(temp, n_bar, MPI_FLOAT, q, 0, MPI_COMM_WORLD);
// send data to required process parallely. n_bar is the no. of locations being sent ( array of size _bar each location of tyoe MPI_FLOAT. No logn method here as data transfered to each process is different ad mutually exclusive
}
}
else
MPI_Recv(local_v, n_bar, MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &status);
}
int main(int argc, char* argv[])
{ float local_x[MAX_LOCAL_ORDER], local_y[MAX_LOCAL_ORDER], n_bar, dot;
int p, my_rank, n;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &p);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
if (my_rank == 0)
{ printf("Enter the order of the vectors\n");
scanf("%d", &n);
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
n_bar = n/p;
Read_vector("the first vector", local_x, n_bar, p, my_rank);
Read_vector("the second vector", local_y, n_bar, p, my_rank);
// apply dot product on the local_x[] and local_y[]
dot = Parallel_dot(local_x, local_y, n_bar);
Print_results(dot, my_rank, p); // value stored in all the processes
MPI_Finalize();
return 0;
}
|
C
|
#ifndef ls_h
#define ls_h
int ls(int x);
{
strcpy(str, "----------");
{
if(S_ISDIR(mode)) str[0] = 'd';//directory
if (S_ISCHR(mode)) str[0] = 'c';//character devices
if (S_ISBLK(mode)) str[0] = 'b';//block device
if (mode & S_IRUSR) str[1] = 'r';//owner read
if (mode & S_IWUSR) str[2] = 'w';//owner write
if (mode & S_IXUSR) str[3] = 'x';//owner execute
if (mode & S_IRGRP) str[4] = 'r';//group read
if (mode & S_WRGRP) str[5] = 'w';//group write
if (mode & S_IXGRP) str[6] = 'x';//group execute
if (mode & S_IROTH) str[7] = 'r';//other read
if (mode & S_IWOTH) str[8] = 'w';//other write
if (mode & S_IXOTH) str[9] = 'x';//other execute
}
#include <pwd.h>
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* push_swap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ljoly <ljoly@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/27 18:03:52 by ljoly #+# #+# */
/* Updated: 2017/07/06 16:50:20 by ljoly ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static void bonus(t_stack *e, char begin, char op, char algo)
{
if (begin)
{
if (e->bonus.refresh)
{
nanosleep(&(struct timespec){0, 100000000}, 0);
ft_putstr("\e[1;1H\e[2J");
}
if (begin && e->bonus.colors)
ft_putstr(RED);
else if (e->bonus.colors)
ft_putstr(NC);
}
else
{
if (e->bonus.colors)
ft_putstr(NC);
if (e->bonus.stacks)
display_stacks(e, e->bonus.colors, op);
if (algo)
e->bonus.moves++;
}
}
void send_op(t_stack *e, char op, char algo)
{
bonus(e, 1, op, 0);
if (op == SA)
ft_putendl("sa");
else if (op == SB)
ft_putendl("sb");
else if (op == SS)
ft_putendl("ss");
else if (op == PA)
ft_putendl("pa");
else if (op == PB)
ft_putendl("pb");
else if (op == RA)
ft_putendl("ra");
else if (op == RB)
ft_putendl("rb");
else if (op == RR)
ft_putendl("rr");
else if (op == RRA)
ft_putendl("rra");
else if (op == RRB)
ft_putendl("rrb");
else if (op == RRR)
ft_putendl("rrr");
bonus(e, 0, op, algo);
}
void proceed_op(t_stack *e, char op)
{
t_op *tmp;
if (op)
{
do_op(e, op);
store_op(e, op);
}
else
{
e->moves = 0;
delete_ops(e->op);
replace_ops(e->op);
tmp = *e->op;
while (tmp->prev)
tmp = tmp->prev;
while (tmp)
{
if (e->bonus.stacks)
do_op(e, tmp->op);
send_op(e, tmp->op, 0);
tmp = tmp->next;
e->bonus.moves++;
}
}
}
static void init_stack_a(t_stack *e)
{
int i;
i = 0;
while (i < e->param)
{
e->stack_a[i] = e->bonus.stack[i];
i++;
}
}
void push_swap(t_stack *e)
{
int algo;
algo = 0;
if (is_sorted(e->stack_a, e->len_a, 0, 1))
return ;
e->moves = 0;
if (e->param < 5 && (algo = 1))
simple_sort(e);
else
{
quick_sort(e);
if (e->bonus.stacks)
init_stack_a(e);
proceed_op(e, NOPE);
algo = 2;
}
if (e->bonus.is_moves || e->bonus.algo)
ft_putchar('\n');
if (e->bonus.is_moves)
ft_printf("Stack A was sorted in %d moves\n",
e->bonus.moves);
if (e->bonus.algo)
algo == 1 ? ft_putendl("Algorithm used: simple sort") :
ft_putendl("Algorithm used: quick sort\n");
}
|
C
|
#include "slots.h"
/*
* slot_board_vendor_info(kind, slot, string, size)
* int kind
* int slot;
* char *string;
* int size;
*
* Slot_board_vendor_info returns the requested vendor information
* string into "string." The request for "kind" is one of the vendor
* information list types (found in slots.h.) Size is the number of
* bytes that "string" can hold. Slot is the slot number or
* access address that the vendor information is requested for.
*
* The return possibilites are zero, for no string found, -1, for
* failure in access, and a positive integer for the number of bytes
* successfully read.
*/
slot_board_vendor_info(kind, slot, string, size)
int kind; /* Vendor information type */
int slot; /* Slot number or ROM base address */
char *string; /* String buffer */
int size; /* The size of the buffer */
{
struct rom_idoffset venlist[LISTLEN];
/* The vendor list storage area */
register char *romp; /* A ROM pointer */
register int i; /* A loop counter */
unsigned address; /* The calculated ROM base address */
/*
* Create the ROM base address
*/
if((address = slot_address(slot)) == 0)
return(-1);
/*
* Get the RBL_VINFO (vendor information resource list) from
* the RD_BOARD (board resource) in the resource directory.
*/
if((romp = slot_resource(address, RD_BOARD, RBL_VINFO,
venlist, LISTLEN*sizeof(struct rom_idoffset))) == 0)
return(-1);
/*
* Search the vendor information list for the "kind" item.
*/
for(i = 0;
((i < LISTLEN) && (venlist[i].r_id != RD_EOLIST));
i++) {
if(venlist[i].r_id == kind)
break;
}
if((i == LISTLEN) || (venlist[i].r_id == RD_EOLIST))
return(0);
/*
* move romp forward in the structure so that it points at the
* the vendor list entry in the structure in ROM.
*/
romp = slot_calc_pointer(romp, i*sizeof(struct rom_idoffset));
/*
* Then read the vendor information string requested.
*/
return(slot_structure(romp, venlist[i].r_offset, string, size));
}
|
C
|
/*
** EPITECH PROJECT, 2020
** My Hunter
** File description:
** Windows related function
*/
#include "include/my.h"
char *get_name(char *filepath)
{
int index = get_last_point(filepath);
char *name = my_strncpy(filepath, index);
char **map2 = my_str_to_word_array_char(name, '/');
return (map2[2]);
}
tetri_t init_tetri(char **map, char *filepath)
{
char **line1 = my_str_to_word_array_char(map[0], ' ');
tetri_t tetrimino;
tetrimino.name = get_name(filepath);
tetrimino.w = my_atoi(line1[0]);
tetrimino.h = my_atoi(line1[1]);
tetrimino.c = my_atoi(line1[2]);
tetrimino.data = ++map;
for (int i = 0; i < tetrimino.h; i++)
for (int j = 0; j < tetrimino.w; j++)
if (tetrimino.data[i][j] == ',')
tetrimino.data[i][j] = ' ';
free(line1);
return (tetrimino);
}
tetri_t tetris_info(char *filepath)
{
char *buffer = read_map(filepath);
char **map = my_str_to_word_array_char(buffer, '\n');
tetri_t tetrimino;
if (check_tetri_error(map) == -1)
tetrimino = error_tetri(filepath);
else
tetrimino = init_tetri(map, filepath);
return (tetrimino);
}
int get_total(char *str, char **av)
{
s_data data;
char *path = my_strcat("./", str);
int total = 0;
data.p_dir = opendir(path);
if (ENOTDIR != errno && (data.p_dir == NULL)) {
my_printf("Directory cannot be read\n");
print_help(av);
exit (84);
} else {
while ((data.p_dirent = readdir(data.p_dir)) != NULL) {
if (data.p_dirent->d_name[0] != '.') {
total += 1;
}
}
}
if (total == 0) {
print_help(av);
exit(84);
}
closedir(data.p_dir);
return (total);
}
tetri_t *print_list_l(char *str, char **av)
{
s_data data;
int index = 0;
char *r_p;
char *path = my_strcat("./", str);
tetri_t *list = malloc(sizeof(tetri_t) * ((get_total(str, av)) + 1));
list[get_total(str, av)].name = NULL;
data.p_dir = opendir(path);
if (ENOTDIR != errno && (data.p_dir == NULL)) {
my_printf("Directory cannot be read\n");
print_help(av);
exit (84);
} else {
while ((data.p_dirent = readdir(data.p_dir)) != NULL) {
if (my_strlen(data.p_dirent->d_name) > 2) {
r_p = my_strcat(my_strcat(path, "/"), data.p_dirent->d_name);
list[index++] = tetris_info(r_p);
}
}
}
closedir(data.p_dir);
return (sorted(list, str, av));
}
|
C
|
#include"Menu.h"
int SelectMenu(void){
int num = 1;
printf("-------------\n");
printf("1.л߰\n");
printf("2. \n");
printf("3.̸ \n");
printf("4.л ˻\n");
printf("0.\n");
printf("-------------\n");
printf(" : ");
scanf("%d", &num);
return num;
}
|
C
|
#include "Inf_uint_arr_type.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#define INITIAL_SIZE 4
#define SIZE_STEP 2
static int Add_to_inf_uint_arr(struct inf_uint_arr* inf_uint_arr, const inf_uint_arr_cell new_cell)
{
assert(inf_uint_arr);
if (inf_uint_arr->used_size >= inf_uint_arr->alloced_size)
{
inf_uint_arr_cell* temp = (inf_uint_arr_cell*) realloc(inf_uint_arr->array, (inf_uint_arr->alloced_size * SIZE_STEP) * sizeof(inf_uint_arr_cell));
if (NULL == temp)
{
return -1;
}
inf_uint_arr->array = temp;
inf_uint_arr->alloced_size *= SIZE_STEP;
}
inf_uint_arr->array[inf_uint_arr->used_size] = new_cell;
inf_uint_arr->used_size++;
return 0;
}
struct inf_uint_arr* Construct_inf_uint_arr(void)
{
struct inf_uint_arr* tmp_str = (struct inf_uint_arr*) malloc(sizeof(struct inf_uint_arr));
tmp_str->Add_cell = Add_to_inf_uint_arr;
inf_uint_arr_cell* tmp = (inf_uint_arr_cell*) calloc(INITIAL_SIZE, sizeof(inf_uint_arr_cell));
if (NULL == tmp)
{
free(tmp_str);
return NULL;
}
tmp_str->array = tmp;
tmp_str->alloced_size = INITIAL_SIZE;
tmp_str->used_size = 0;
return tmp_str;
}
void Destruct_inf_uint_arr(struct inf_uint_arr* inf_uint_arr)
{
if (NULL == inf_uint_arr)
{
return;
}
if (NULL != inf_uint_arr->array)
{
// for(unsigned int i = 0; i < inf_uint_arr->used_size; i++) //for data types made of pointers
// {
// free(inf_uint_arr->array[i]);
// }
free(inf_uint_arr->array);
}
free(inf_uint_arr);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <SDL2/SDL.h>
#include "Affichage.h"
#include "operation.h"
#include "rotation.h"
#include "resolution.h"
void Resolution (int faceB[3][3], int faceO[3][3], int faceG[3][3], int faceR[3][3], int faceY[3][3], int faceW[3][3], int nbEtapes, int *choixOperation, SDL_Window *fenetre, SDL_Renderer *interp,SDL_Rect rectangle, int *etat){
int tabop[15]; //tableau pour stocker les differentes operation a effectuer
int *nbop = malloc(sizeof(int));
*nbop = 0;
//on realise la croix bleue
CroixBleu (faceB, faceO, faceG, faceR, faceY, faceW, nbEtapes, choixOperation, tabop, nbop, fenetre, interp, rectangle, etat );
CoinsBleus (faceB, faceO, faceG, faceR, faceY, faceW, nbEtapes, choixOperation, tabop, nbop, fenetre, interp, rectangle, etat );
}
void RealisationOperation (int faceB[3][3], int faceO[3][3], int faceG[3][3], int faceR[3][3], int faceY[3][3], int faceW[3][3], int nbEtapes, int *choixOperation, int tabop[15], int *nbop, SDL_Window *fenetre, SDL_Renderer *interp, SDL_Rect rectangle, int *etat){
int i;
//on lit le tableau pour effectuer les operation
for (i=0; i < *nbop; i++){
*choixOperation = tabop[i];
operation(choixOperation,faceB, faceO, faceG, faceR, faceY, faceW);
//on affiche pas a pas la resolution
Affichage(faceB, faceO, faceG, faceR, faceY, faceW, fenetre, interp, rectangle, etat);
SDL_Delay (50);
}
}
void CroixBleu (int faceB[3][3], int faceO[3][3], int faceG[3][3], int faceR[3][3], int faceY[3][3], int faceW[3][3], int nbEtapes, int *choixOperation, int tabop[15], int *nbop, SDL_Window *fenetre, SDL_Renderer *interp,SDL_Rect rectangle, int *etat){
/**************************************************************************
*********************************milieu 12*********************************
**************************************************************************/
//cas de la piece sur la faceB *ok*
if (faceB[0][1] == 12){
tabop[0] = 0;
*nbop = 1;
}
else if(faceB[1][0] == 12){
tabop[0] = 6;
*nbop = 1;
}
else if(faceB[1][2] == 12){
tabop[0] = 66;
*nbop = 1;
}
else if(faceB[2][1] == 12){
tabop[0] = 6;
tabop[1] = 6;
*nbop = 2;
}
//cas de la piece sur la faceO *ok*
else if (faceO[0][1] == 12){
tabop[0] = 11;
*nbop = 1;
}
else if(faceO[1][0] == 12){
tabop[0] = 3;
tabop[1] = 11;
*nbop = 2;
}
else if(faceO[1][2] == 12){
tabop[0] = 33;
tabop[1] = 11;
*nbop = 2;
}
else if(faceO[2][1] == 12){
tabop[0] = 3;
tabop[1] = 3;
tabop[2] = 11;
*nbop = 3;
}
//cas de la piece sur la faceG *ok*
else if (faceG[0][1] == 12){
tabop[0] = 1;
tabop[1] = 1;
*nbop = 2;
}
else if(faceG[1][0] == 12){
tabop[0] = 5;
tabop[1] = 1;
tabop[2] = 1;
*nbop = 3;
}
else if(faceG[1][2] == 12){
tabop[0] = 55;
tabop[1] = 1;
tabop[2] = 1;
*nbop = 3;
}
else if(faceG[2][1] == 12){
tabop[0] = 5;
tabop[1] = 5;
tabop[2] = 1;
tabop[3] = 1;
*nbop = 4;
}
//cas de la piece sur la faceR *ok*
else if (faceR[0][1] == 12){
tabop[0] = 1;
*nbop = 1;
}
else if(faceR[1][0] == 12){
tabop[0] = 2;
tabop[1] = 1;
*nbop = 2;
}
else if(faceR[1][2] == 12){
tabop[0] = 22;
tabop[1] = 1;
*nbop = 2;
}
else if(faceR[2][1] == 12){
tabop[0] = 2;
tabop[1] = 2;
tabop[2] = 1;
*nbop = 3;
}
//cas de la piece sur la faceY *ok*
else if (faceY[0][1] == 12){
tabop[0] = 1;
tabop[1] = 22;
tabop[2] = 66;
*nbop = 3;
}
else if(faceY[1][0] == 12){
tabop[0] = 3;
tabop[1] = 6;
*nbop = 2;
}
else if(faceY[1][2] == 12){
tabop[0] = 22;
tabop[1] = 66;
*nbop = 2;
}
else if(faceY[2][1] == 12){
tabop[0] = 1;
tabop[1] = 3;
tabop[2] = 6;
*nbop = 3;
}
//cas de la piece sur la faceW *ok*
else if (faceW[0][1] == 12){
tabop[0] = 4;
tabop[1] = 2;
tabop[2] = 66;
*nbop = 3;
}
else if(faceW[1][0] == 12){
tabop[0] = 33;
tabop[1] = 6;
*nbop = 2;
}
else if(faceW[1][2] == 12){
tabop[0] = 2;
tabop[1] = 66;
*nbop = 2;
}
else if(faceW[2][1] == 12){
tabop[0] = 44;
tabop[1] = 2;
tabop[2] = 66;
*nbop = 3;
}
if (tabop[0] != 0)
RealisationOperation(faceB, faceO, faceG, faceR, faceY, faceW, nbEtapes, choixOperation, tabop, nbop, fenetre, interp, rectangle, etat);
/**************************************************************************
*********************************milieu 14*********************************
**************************************************************************/
//cas de la piece sur la faceB *ok*
if(faceB[1][0] == 14){
tabop[0] = 0;
*nbop = 1;
}
else if(faceB[1][2] == 14){
tabop[0] = 1;
tabop[1] = 6;
tabop[2] = 6;
tabop[3] = 11;
*nbop = 4;
}
else if(faceB[2][1] == 14){
tabop[0] = 1;
tabop[1] = 6;
tabop[2] = 11;
*nbop = 3;
}
//cas de la piece sur la faceO *ok*
else if (faceO[0][1] == 14){
tabop[0] = 11;
tabop[1] = 66;
tabop[2] = 1;
*nbop = 3;
}
else if(faceO[1][0] == 14){
tabop[0] = 3;
tabop[1] = 11;
tabop[2] = 66;
tabop[3] = 1;
*nbop = 4;
}
else if(faceO[1][2] == 14){
tabop[0] = 33;
tabop[1] = 11;
tabop[2] = 66;
tabop[3] = 1;
*nbop = 4;
}
else if(faceO[2][1] == 14){
tabop[0] = 66;
tabop[1] = 4;
tabop[2] = 6;
*nbop = 3;
}
//cas de la piece sur la faceG *ok*
else if (faceG[0][1] == 14){
tabop[0] = 5;
tabop[1] = 3;
tabop[2] = 3;
*nbop = 3;
}
else if(faceG[1][0] == 14){
tabop[0] = 5;
tabop[1] = 5;
tabop[2] = 3;
tabop[3] = 3;
*nbop = 4;
}
else if(faceG[1][2] == 14){
tabop[0] = 3;
tabop[1] = 3;
*nbop = 2;
}
else if(faceG[2][1] == 14){
tabop[0] = 55;
tabop[1] = 3;
tabop[2] = 3;
*nbop = 3;
}
//cas de la piece sur la faceR *ok*
else if (faceR[0][1] == 14){
tabop[0] = 1;
tabop[1] = 66;
tabop[2] = 11;
*nbop = 3;
}
else if(faceR[1][0] == 14){
tabop[0] = 2;
tabop[1] = 1;
tabop[2] = 66;
tabop[3] = 11;
*nbop = 4;
}
else if(faceR[1][2] == 14){
tabop[0] = 22;
tabop[1] = 1;
tabop[2] = 66;
tabop[3] = 11;
*nbop = 4;
}
else if(faceR[2][1] == 14){
tabop[0] = 66;
tabop[1] = 55;
tabop[2] = 6;
*nbop = 3;
}
//cas de la piece sur la faceY *ok*
else if (faceY[0][1] == 14){
tabop[0] = 11;
tabop[1] = 3;
tabop[2] = 1;
*nbop = 3;
}
else if(faceY[1][0] == 14){
tabop[0] = 3;
*nbop = 1;
}
else if(faceY[1][2] == 14){
tabop[0] = 1;
tabop[1] = 1;
tabop[2] = 3;
tabop[3] = 1;
tabop[4] = 1;
*nbop = 5;
}
//cas de la piece sur la faceW *ok*
else if (faceW[0][1] == 14){
tabop[0] = 44;
tabop[1] = 33;
*nbop = 2;
}
else if(faceW[1][0] == 14){
tabop[0] = 33;
*nbop = 1;
}
else if(faceW[1][2] == 14){
tabop[0] = 4;
tabop[1] = 4;
tabop[2] = 33;
*nbop = 3;
}
else if(faceW[2][1] == 14){
tabop[0] = 4;
tabop[1] = 33;
*nbop = 2;
}
if (tabop[0] != 0)
RealisationOperation(faceB, faceO, faceG, faceR, faceY, faceW, nbEtapes, choixOperation, tabop, nbop, fenetre, interp, rectangle, etat);
/**************************************************************************
*********************************milieu 16*********************************
**************************************************************************/
//cas de la piece sur la faceB *ok*
if(faceB[1][2] == 16){
tabop[0] = 0;
*nbop = 1;
}
else if(faceB[2][1] == 16){
tabop[0] = 44;
tabop[1] = 6;
tabop[2] = 4;
tabop[3] = 66;
*nbop = 4;
}
//cas de la piece sur la faceO *ok*
else if (faceO[0][1] == 16){
tabop[0] = 66;
tabop[1] = 11;
tabop[2] = 6;
*nbop = 3;
}
else if(faceO[1][0] == 16){
tabop[0] = 6;
tabop[1] = 33;
tabop[2] = 4;
tabop[3] = 66;
*nbop = 4;
}
//faceO[1][2] => impossible
else if(faceO[2][1] == 16){
tabop[0] = 6;
tabop[1] = 4;
tabop[2] = 66;
*nbop = 3;
}
//cas de la piece sur la faceG *ok*
else if (faceG[0][1] == 16){
tabop[0] = 55;
tabop[1] = 2;
tabop[2] = 2;
*nbop = 3;
}
else if(faceG[1][0] == 16){
tabop[0] = 2;
tabop[1] = 2;
*nbop = 2;
}
else if(faceG[1][2] == 16){
tabop[0] = 5;
tabop[1] = 5;
tabop[2] = 2;
tabop[3] = 2;
*nbop = 4;
}
else if(faceG[2][1] == 16){
tabop[0] = 5;
tabop[1] = 2;
tabop[2] = 2;
*nbop = 3;
}
//cas de la piece sur la faceR *ok*
else if (faceR[0][1] == 16){
tabop[0] = 66;
tabop[1] = 1;
tabop[2] = 6;
*nbop = 3;
}
else if(faceR[1][0] == 16){
tabop[0] = 2;
tabop[1] = 66;
tabop[2] = 1;
tabop[3] = 6;
*nbop = 4;
}
else if(faceR[1][2] == 16){
tabop[0] = 22;
tabop[1] = 66;
tabop[2] = 1;
tabop[3] = 6;
*nbop = 4;
}
else if(faceR[2][1] == 16){
tabop[0] = 2;
tabop[1] = 55;
tabop[2] = 66;
*nbop = 3;
}
//cas de la piece sur la faceY *ok*
else if (faceY[0][1] == 16){
tabop[0] = 1;
tabop[1] = 22;
tabop[2] = 11;
*nbop = 3;
}
else if(faceY[1][0] == 16){
tabop[0] = 6;
tabop[1] = 6;
tabop[2] = 3;
tabop[3] = 6;
tabop[4] = 6;
*nbop = 5;
}
else if(faceY[1][2] == 16){
tabop[0] = 22;
*nbop = 1;
}
//cas de la piece sur la faceW *ok*
else if (faceW[0][1] == 16){
tabop[0] = 4;
tabop[1] = 2;
*nbop = 2;
}
else if(faceW[1][0] == 16){
tabop[0] = 4;
tabop[1] = 4;
tabop[2] = 2;
*nbop = 3;
}
else if(faceW[1][2] == 16){
tabop[0] = 2;
*nbop = 1;
}
else if(faceW[2][1] == 16){
tabop[0] = 44;
tabop[1] = 2;
*nbop = 2;
}
if (tabop[0] != 0)
RealisationOperation(faceB, faceO, faceG, faceR, faceY, faceW, nbEtapes, choixOperation, tabop, nbop, fenetre, interp, rectangle, etat);
/**************************************************************************
*********************************milieu 18*********************************
**************************************************************************/
//cas de la piece sur la faceB *ok*
//faceB[1][2] => impossible
if(faceB[2][1] == 18){
tabop[0] = 0;
*nbop = 1;
}
//cas de la piece sur la faceO *ok*
else if (faceO[0][1] == 18){
tabop[0] = 6;
tabop[1] = 6;
tabop[2] = 11;
tabop[3] = 6;
tabop[4] = 6;
*nbop = 5;
}
else if(faceO[1][0] == 18){
tabop[0] = 33;
tabop[1] = 4;
tabop[2] = 3;
*nbop = 3;
}
//faceO[1][2] => impossible
else if(faceO[2][1] == 18){
tabop[0] = 4;
*nbop = 1;
}
//cas de la piece sur la faceG *ok*
else if (faceG[0][1] == 18){
tabop[0] = 5;
tabop[1] = 5;
tabop[2] = 4;
tabop[3] = 4;
*nbop = 4;
}
else if(faceG[1][0] == 18){
tabop[0] = 55;
tabop[1] = 4;
tabop[2] = 4;
*nbop = 3;
}
else if(faceG[1][2] == 18){
tabop[0] = 5;
tabop[1] = 4;
tabop[2] = 4;
*nbop = 3;
}
else if(faceG[2][1] == 18){
tabop[0] = 4;
tabop[1] = 4;
*nbop = 2;
}
//cas de la piece sur la faceR *ok*
else if (faceR[0][1] == 18){
tabop[0] = 6;
tabop[1] = 6;
tabop[2] = 1;
tabop[3] = 6;
tabop[4] = 6;
*nbop = 5;
}
//faceR[1][0] => impossible
else if(faceR[1][2] == 18){
tabop[0] = 66;
tabop[1] = 2;
tabop[2] = 6;
tabop[3] = 44;
*nbop = 4;
}
else if(faceR[2][1] == 18){
tabop[0] = 44;
*nbop = 1;
}
//cas de la piece sur la faceY *ok*
else if (faceY[0][1] == 18){
tabop[0] = 66;
tabop[1] = 55;
tabop[2] = 2;
tabop[3] = 6;
tabop[4] = 44;
*nbop = 5;
}
else if(faceY[1][0] == 18){
tabop[0] = 6;
tabop[1] = 3;
tabop[2] = 66;
*nbop = 3;
}
else if(faceY[1][2] == 18){
tabop[0] = 66;
tabop[1] = 22;
tabop[2] = 6;
*nbop = 3;
}
//faceY[2][1] => impossible
//cas de la piece sur la faceW *ok*
else if (faceW[0][1] == 18){
tabop[0] = 44;
tabop[1] = 6;
tabop[2] = 33;
tabop[3] = 66;
*nbop = 4;
}
else if(faceW[1][0] == 18){
tabop[0] = 6;
tabop[1] = 33;
tabop[2] = 66;
*nbop = 3;
}
else if(faceW[1][2] == 18){
tabop[0] = 66;
tabop[1] = 2;
tabop[2] = 6;
*nbop = 3;
}
else if(faceW[2][1] == 18){
tabop[0] = 4;
tabop[1] = 6;
tabop[2] = 33;
tabop[3] = 66;
*nbop = 4;
}
if (tabop[0] != 0)
RealisationOperation(faceB, faceO, faceG, faceR, faceY, faceW, nbEtapes, choixOperation, tabop, nbop, fenetre, interp, rectangle, etat);
}
void CoinsBleus (int faceB[3][3], int faceO[3][3], int faceG[3][3], int faceR[3][3], int faceY[3][3], int faceW[3][3], int nbEtapes, int *choixOperation, int tabop[15], int *nbop, SDL_Window *fenetre, SDL_Renderer *interp,SDL_Rect rectangle, int *etat){
/**************************************************************************
**********************************coins 11*********************************
**************************************************************************/
//cas de la faceB
if(faceB[0][0] == 11){
tabop[0] = 0;
*nbop = 1;
}
else if(faceB[0][2] == 11){
tabop[0] = 2;
tabop[1] = 5;
tabop[2] = 22;
tabop[3] = 11;
tabop[4] = 3;
tabop[15] = 1;
tabop[6] = 33;
*nbop = 7;
}
else if(faceB[2][0] == 11){
tabop[0] = 44;
tabop[1] = 55;
tabop[2] = 4;
tabop[3] = 3;
tabop[4] = 11;
tabop[15] = 33;
tabop[6] = 1;
*nbop = 7;
}
else if(faceB[2][2] == 11){
tabop[0] = 4;
tabop[1] = 2;
tabop[2] = 2;
tabop[3] = 44;
tabop[4] = 11;
tabop[15] = 3;
tabop[6] = 1;
tabop[7] = 33;
*nbop = 8;
}
//cas de la faceO
else if(faceO[0][0] == 11){
tabop[0] = 11;
tabop[1] = 3;
tabop[2] = 1;
tabop[3] = 33;
*nbop = 4;
}
else if(faceO[0][2] == 11){
tabop[0] = 33;
tabop[1] = 55;
tabop[2] = 3;
tabop[3] = 5;
tabop[4] = 11;
tabop[15] = 3;
tabop[6] = 1;
tabop[7] = 33;
*nbop = 8;
}
else if(faceO[2][0] == 11){
tabop[0] = 55;
tabop[1] = 3;
tabop[2] = 11;
tabop[3] = 33;
tabop[4] = 1;
*nbop = 5;
}
else if(faceO[2][2] == 11){
tabop[0] = 3;
tabop[1] = 5;
tabop[2] = 33;
tabop[3] = 5;
tabop[4] = 5;
tabop[15] = 3;
tabop[6] = 11;
tabop[7] = 33;
tabop[8] = 1;
*nbop = 9;
}
else
return;
if (tabop[0] != 0)
RealisationOperation(faceB, faceO, faceG, faceR, faceY, faceW, nbEtapes, choixOperation, tabop, nbop, fenetre, interp, rectangle, etat);
}
|
C
|
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "bloom.h"
unsigned int sax_hash(const char *key)
{
unsigned int h=0;
while(*key) h^=(h<<5)+(h>>2)+(unsigned char)*key++;
return h;
}
unsigned int sdbm_hash(const char *key)
{
unsigned int h=0;
while(*key) h=(unsigned char)*key++ + (h<<6) + (h<<16) - h;
return h;
}
int main( int argc ,char **argv )
{
FILE *fp ;
char line[1024] ;
char *p ;
bloom_t *bloom ;
if( argc < 2 )
{
fprintf(stderr,"Error: No word file specified.\n") ;
return -1 ;
}
if(!(bloom=bloomCreate(2500000, 2, sax_hash, sdbm_hash)))
{
fprintf(stderr, "Error: Could not create bloom filter.\n") ;
return -1 ;
}
if(!(fp=fopen(argv[1],"r")))
{
fprintf(stderr,"Error: Could not open file.\n") ;
return -1 ;
}
while(fgets(line,1024,fp))
{
if((p=strchr(line,'\r'))) *p = '\0' ;
if((p=strchr(line,'\n'))) *p = '\0' ;
bloomAdd(bloom,line) ;
}
fclose(fp) ;
while(fgets(line, 1024, stdin))
{
if((p=strchr(line,'\r'))) *p = '\0' ;
if((p=strchr(line,'\n'))) *p = '\0' ;
if(strcmp(line,"quit")==0)
{
break ;
}
p = strtok(line, "\t,.;:\r\n?!-/()") ;
while(p)
{
if(!bloomCheck(bloom,p))
{
printf("No match for word \"%s\"\n",p) ;
}
else
printf("%s is match.\n",p) ;
p = strtok(NULL, "\t,.;:\r\n?!-/()") ;
}
}
bloomDestroy(bloom) ;
return 1 ;
}
|
C
|
/*
* ---------- header ----------------------------------------------------------
*
* project kaneton
*
* license kaneton
*
* file /home/mycure/kane...ine/glue/ibm-pc.ia32/educational/clock.c
*
* created julien quintard [wed nov 24 19:11:47 2010]
* updated julien quintard [sat jan 15 06:10:00 2011]
*/
/*
* ---------- information -----------------------------------------------------
*
* this file implements the clock manager's glue.
*/
/*
* ---------- includes --------------------------------------------------------
*/
#include <kaneton.h>
/*
* ---------- globals ---------------------------------------------------------
*/
/*
* the clock dispatcher.
*/
d_clock glue_clock_dispatch =
{
NULL,
glue_clock_update,
glue_clock_current,
glue_clock_initialize,
glue_clock_clean
};
/*
* ---------- functions -------------------------------------------------------
*/
/*
* this function updates the clock with the given number of milliseconds.
*
* steps:
*
* 1) call the RTC update() function.
*/
t_status glue_clock_update(t_uint32 millisecond)
{
/*
* 1)
*/
if (platform_rtc_update(millisecond) != STATUS_OK)
MACHINE_ESCAPE("unable to update the RTC");
MACHINE_LEAVE();
}
/*
* this function returns the current date/time through the clock structure.
*
* steps:
*
* 1) call the RTC to retrieve the hardware information related to the date
* and time.
* 2) fill the clock structure with the RTC.
*/
t_status glue_clock_current(s_clock* clock)
{
ps_rtc_state* rtc;
/*
* 1)
*/
if (platform_rtc_state(&rtc) != STATUS_OK)
MACHINE_ESCAPE("unable to load the RTC date/time structure");
/*
* 2)
*/
clock->millisecond = rtc->millisecond;
clock->second = rtc->second;
clock->minute = rtc->minute;
clock->hour = rtc->hour;
clock->day = rtc->day;
clock->month = rtc->month;
clock->year = rtc->century * 100 + rtc->year;
MACHINE_LEAVE();
}
/*
* this function initializes the clock manager by setting up the
* platform's RTC.
*
* steps:
*
* 1) initialize the RTC.
*/
t_status glue_clock_initialize(void)
{
/*
* 1)
*/
if (platform_rtc_initialize() != STATUS_OK)
MACHINE_ESCAPE("unable to initialize the real time clock");
MACHINE_LEAVE();
}
/*
* this function cleans the clock.
*
* 1) clean the RTC
*/
t_status glue_clock_clean(void)
{
/*
* 1)
*/
if (platform_rtc_clean() != STATUS_OK)
MACHINE_ESCAPE("unable to clean the real time clock");
MACHINE_LEAVE();
}
|
C
|
#include "calc_message.h"
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <string.h>
#include <errno.h>
#include <sys/neutrino.h>
#include <pthread.h>
/***********************************************************************************
* File: Msg_Passing_Server.c
*
* Usage: ./Msg_Passing_Server
*
* Method: 1. Create a channel and assign the ID to 'chid'.
* 2. If the 'chid' equals -1, process failed and end program.
* 3. Print out the thread's and server's PID and a msg
* 4. Server begins an infinite loop; typical of servers
* 5. Gets the msg using MsgReceived()
* 6. Assign the 2 integers in to doubles for proper arithmetic
* 7. Takes the operator to determine how to handle the two numbers, and calculates
* 8. Prepare and send reply using MsgReply()
* 9. Destroy the channel when done
*
* Note the server's PID (required for client).
*
***********************************************************************************/
int main (int argc, char* argv[])
{
int rcvid; // Indicates who we should reply to (client ID)
int chid; // The channel ID (server establishes a Channel for msgs)
double leftSide, rightSide, tempAnswer; // Double values to handle the arithmetic involved in the calculations
server_response_t serverResponse; // Struct used to send a message to the client
client_send_t clientMessage; // Temporary holder for the client message received from the client
// 1. Create a channel and returns the Child ID ~~~~~~~~~~~~~~~~~~~~~~~~~
chid = ChannelCreate (0);
//(0) - changes how channel notifies the calling THREAD. For now, use 0.
// 2. If it fails it will go to -1 and end ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (chid == -1)
{
perror("failed to create the channel.");
exit (EXIT_FAILURE);
}
printf("%d\n", getpid());
// 3, Prints out the THREAD id and SERVER's PID ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//printf("[%d] %d\n", pthread_self(), getpid());
// 4. Server begins in an infinite loop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
while (1) {
// 5. Gets the message and assigns it to clientMesage ~~~~~~~~~~~~~~~
rcvid = MsgReceive (chid, &clientMessage, sizeof (clientMessage), NULL);
/* chid --> The channel ID for the comm channel
* message --> A buffer to receive msg in
* sizeof(message) --> The size of buffer to receive in
* NULL --> Don't worry about for now...
*
* Returns a receiver ID (rcvid) used to reply or -1 for ERROR.
* - rcvid gets the ID of the client so you can send a msg back
* */
// 6. Assign the 2 integers in to doubles for proper arithmetic
leftSide = clientMessage.left_hand;
rightSide = clientMessage.right_hand;
// 7. Takes the operator to determine how to handle the two numbers, and calculates
switch (clientMessage.operator) {
case '+':
tempAnswer= leftSide + rightSide;
serverResponse.answer = tempAnswer;
serverResponse.error = SRVR_OK;
break;
case '-':
tempAnswer = leftSide - rightSide;
serverResponse.answer = tempAnswer;
serverResponse.error = SRVR_OK;
break;
case 'x':
tempAnswer = leftSide * rightSide;
serverResponse.answer = tempAnswer;
serverResponse.error = SRVR_OK;
break;
case '/':
if (rightSide == 0) {
serverResponse.error = SRVR_UNDEFINED;
strcpy(serverResponse.errorMsg, "The server cannot calculate the answer as you cannot divide by ZERO.\n");
break;
}
tempAnswer = leftSide / rightSide;
serverResponse.answer = tempAnswer;
serverResponse.error = SRVR_OK;
break;
// If the operator is none of the above; it is an error.
default:
serverResponse.error = SRVR_INVALID_OPERATOR;
strcpy(serverResponse.errorMsg, "The server cannot calculate the answer as the operator is INVALID.\n");
break;
}
// 8. Prepare the reply. We reuse send the serverResponse struct, and send using MsgReply()
MsgReply (rcvid, EOK, &serverResponse, sizeof (serverResponse));
/* rcvid --> Receiver's ID (client ID)
* EOK --> STATUS
* msg --> The buffer you want to send
* size --> Size of the buffer being sent
* */
}
// 9. Destroy the channel when done ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ChannelDestroy(chid);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
void main ()
{
int a;
printf ("Enter the no: ");
scanf ("%d", &a);
switch (a)
{
case 1:
printf ("MONDAY");
break;
case 2:
printf ("TUESDAY");
break;
case 3:
printf ("WEDNESDAY");
break;
case 4:
printf ("THURSDAY");
break;
case 5:
printf ("FRIDAY");
break;
case 6:
printf ("SATURDAY");
break;
case 7:
printf ("SUNDAY");
break;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int hammingDistance(int x, int y)
{
int z = x ^ y;
int iCnt = 0;
while (z != 0)
{
if (z & 1)
{
++iCnt;
}
z = z >> 1;
}
return iCnt;
}
int main()
{
int x = 1;
int y = 4;
int iRes = hammingDistance(x, y);
printf("%d\n", iRes);
}
|
C
|
/********************************************************************/
/* Class: Computer Programming, Fall 2018 */
/* Author: ffE */
/* ID: 107820016 */
/* Date: 2018.12.12 */
/* Purpose: yz */
/* Change History: log the change history of the program */
/********************************************************************/
#include <stdio.h>
#include "read_line.h"
#define NAME_LEN 25
#define MAX_PARTS 100
int read_line(char str[], int n);
/* ]w */
struct part {
int number;
double price;
char name[NAME_LEN + 1];
int on_hand;
} inventory[MAX_PARTS];
/* w]0Ӫ */
int num_parts = 0;
/* wq禡 */
int find_part(int number);
void insert(void);
void search(void);
void update(void);
void print(void);
int main(void)
{
char code;
/* Ju@X */
for (;;) {
printf("Enter operation code: ");
scanf(" %c", &code);
while (getchar() != '\n')
;
switch (code) {
case 'i': insert(); /* J */
break;
case 's': search(); /* M䪫 */
break;
case 'u': update(); /* sT */
break;
case 'p': print(); /* XT */
break;
case 'q': return 0; /* { */
default:
printf("Illegal code\n");
}
}
printf("\n");
}
/* M䪫X, Y䤣, h^-1 */
int find_part(int number)
{
int i;
for (i = 0; i < num_parts; i++) {
if (inventory[i].number == number)
return i;
}
return -1;
}
/* J */
void insert(void)
{
int part_number;
double part_price;
/* YƮww, ǰeT */
if (num_parts == MAX_PARTS) {
printf("Database is full; can't add more parts.\n");
return;
}
/* JX */
printf("Enter part number: ");
scanf("%d", &part_number);
if (find_part(part_number) >= 0) {
printf("Part already exists.\n");
return;
}
inventory[num_parts].number = part_number;
/* JW */
printf("Enter part name: ");
read_line(inventory[num_parts].name, NAME_LEN);
/* J */
printf("Enter part price: $");
scanf("%lf", &part_price);
if (part_price < 0) {
printf("Invalid price");
return;
}
inventory[num_parts].price = part_price;
/* Jƶq */
printf("Enter quantity on hand: ");
scanf("%d", &inventory[num_parts].on_hand);
num_parts++;
}
/* M䪫 */
void search(void)
{
int i, number;
printf("Enter part number: ");
scanf("%d", &number);
i = find_part(number);
if (i >= 0) {
printf("Part name: %s\n", inventory[i].name);
printf("Part price: %f\n", inventory[i].price);
printf("Quantity on hand: %d\n", inventory[i].on_hand);
}
else
printf("Part not found.\n");
}
/* sT */
void update(void)
{
int i, number, change;
printf("Enter part number: ");
scanf("%d", &number);
i = find_part(number);
if (i >= 0) {
printf("Enter change in quantity on hand: ");
scanf("%d", &change);
inventory[i].on_hand += change;
}
else
printf("Part not found.\n");
}
/* XT */
void print(void)
{
int i;
printf("Part Number Part Name "
"Part Price Quantity on Hand\n");
for (i = 0; i < num_parts; i++)
printf("%7d %-25s$%7.2f%11d\n", inventory[i].number,
inventory[i].name, inventory[i].price, inventory[i].on_hand);
}
/* Ūr */
int read_line(char str[], int n)
{
int ch, i = 0;
while (isspace(ch = getchar()))
;
while (ch != '\n' && ch != EOF) {
if (i < n)
str[i++] = ch;
ch = getchar();
}
str[i] = '\0';
return i;
}
|
C
|
#include <stdio.h>
#define MAX 500
int multiply(int x, int res[], int res_size)
{
int i, carry = 0, prod = 0;
for (i=0;i < res_size;i++){
prod = res[i] * x + carry;
res[i] = prod % 10;
carry = prod / 10;
}
while(carry){
res[res_size] = carry%10;
carry = carry / 10;
res_size++;
}
return res_size;
}
int factorial(int n)
{
int res[MAX],x,res_size;
res[0] = 1;
res_size = 1;
for (x=2;x<=n;x++){
res_size = multiply(x,res,res_size);
}
printf("Factorial: ");
for(x = res_size -1;x >=0;x--)
printf("%d",res[x]);
printf("\n");
}
int main()
{
factorial(5);
factorial(100);
return 0;
}
|
C
|
/*
* Copyright (c) 2009 HLRS. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include <stdio.h>
#include <string.h>
#include "ADCL.h"
#include "ADCL_internal.h"
#include "mpi.h"
void dump_vector_1D ( double *data, int rank, int dim);
void dump_vector_1D_mpi ( double *data, int dim, MPI_Comm comm );
void set_data_1D ( double *data, int rank, int dim);
int check_data_1D ( double *data, int* rcounts, int *rdispl, int rank, int size);
/**********************************************************************/
/**********************************************************************/
int check_data_1D ( double *data, int *rcounts, int *rdispl, int rank, int size)
/**********************************************************************/
/**********************************************************************/
{
int proc, j;
int err = 0, gerr = 0;
for ( proc=0; proc<size; proc++) {
for (j=0; j<rcounts[proc]; j++){
if (data[ rdispl[proc]+j ] != proc ){
printf("Wrong data: proc %d, pos %d, value %lf, expected value %lf\n",
proc, rdispl[proc]+j, data[ rdispl[proc]+j ], (double) proc);
err++;
}
}
}
MPI_Allreduce ( &err, &gerr, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD );
if ( gerr == 0 ) {
//if ( rank == 0 ) printf("1-D testsuite passed\n");
}
else {
if ( rank == 0 ) printf("1-D testsuite failed\n");
err = 1;
}
return err;
}
/**********************************************************************/
/**********************************************************************/
void set_data_1D ( double *data, int value, int dim)
/**********************************************************************/
/**********************************************************************/
{
int i;
for ( i=0; i<dim; i++) {
data[i] = value;
}
return;
}
/**********************************************************************/
/**********************************************************************/
void dump_vector_1D ( double *data, int rank, int dim)
/**********************************************************************/
/**********************************************************************/
{
int i;
printf("%d : ", rank);
for (i=0; i<dim; i++) {
printf("%lf ", data[i]);
}
printf ("\n");
return;
}
/**********************************************************************/
void dump_vector_1D_mpi ( double *data, int dim, MPI_Comm comm )
/**********************************************************************/
{
int i, iproc;
int rank, size;
MPI_Comm_rank ( MPI_COMM_WORLD, &rank );
MPI_Comm_size ( MPI_COMM_WORLD, &size );
for ( iproc=0; iproc<size; iproc++ ) {
if ( iproc == rank ) {
printf("%d : ", rank);
for ( i=0; i<dim; i++ ) {
printf("%lf ", data[i]);
}
printf ("\n");
}
MPI_Barrier ( comm );
}
return;
}
|
C
|
#include <math.h>
int th;
int checkprime(int num){
if(num > th){
printf("Finished. \n");
}else{
int i,r;
for(i=3;i<th;i++){
r=num/i;
if(r*i == num)
}
}
}
int main(){
th=(int)(sqrt((double)(num))+1);
}
|
C
|
#include <stdio.h>
int n;
int dp[1001];
int main() {
scanf("%d", &n);
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
dp[i] %= 10007;
}
printf("%d\n", dp[n]);
return 0;
}
|
C
|
/********** A really minimal coroutine package for C **********
* By Armin Rigo
*/
#include "src/stacklet/stacklet.h"
#include <stddef.h>
#include <string.h>
#include <stdio.h>
/************************************************************
* platform specific code
*/
/* The default stack direction is downwards, 0, but platforms
* can redefine it to upwards growing, 1.
*/
#define STACK_DIRECTION 0
#define STATIC_NOINLINE __attribute__((noinline)) static
#include "src/stacklet/slp_platformselect.h"
#if STACK_DIRECTION != 0
# error "review this whole code, which depends on STACK_DIRECTION==0 so far"
#endif
/************************************************************/
/* #define DEBUG_DUMP */
#ifdef DEBUG_DUMP
#include <stdio.h>
#endif
/************************************************************/
struct stacklet_s {
/* The portion of the real stack claimed by this paused stacklet. */
char *stack_start; /* the "near" end of the stack */
char *stack_stop; /* the "far" end of the stack */
/* The amount that has been saved away so far, just after this struct.
* There is enough allocated space for 'stack_stop - stack_start'
* bytes.
*/
ptrdiff_t stack_saved; /* the amount saved */
/* Internally, some stacklets are arranged in a list, to handle lazy
* saving of stacks: if the stacklet has a partially unsaved stack,
* this points to the next stacklet with a partially unsaved stack,
* creating a linked list with each stacklet's stack_stop higher
* than the previous one. The last entry in the list is always the
* main stack.
*/
struct stacklet_s *stack_prev;
stacklet_thread_handle stack_thrd; /* the thread where the stacklet is */
};
struct stacklet_thread_s {
struct stacklet_s *g_stack_chain_head; /* NULL <=> running main */
char *g_current_stack_stop;
char *g_current_stack_marker;
struct stacklet_s *g_source;
struct stacklet_s *g_target;
};
#define _check(x) do { if (!(x)) _check_failed(#x); } while (0)
static void _check_failed(const char *check)
{
fprintf(stderr, "FATAL: stacklet: %s failed\n", check);
abort();
}
static void check_valid(struct stacklet_s *g)
{
_check(g->stack_saved >= 0);
}
/***************************************************************/
static void g_save(struct stacklet_s* g, char* stop
#ifdef DEBUG_DUMP
, int overwrite_stack_for_debug
#endif
)
{
/* Save more of g's stack into the heap -- at least up to 'stop'
In the picture below, the C stack is on the left, growing down,
and the C heap on the right. The area marked with xxx is the logical
stack of the stacklet 'g'. It can be half in the C stack (its older
part), and half in the heap (its newer part).
g->stack_stop |________|
|xxxxxxxx|
|xxx __ stop .........
|xxxxxxxx| ==> : :
|________| :_______:
| | |xxxxxxx|
| | |xxxxxxx|
g->stack_start | | |_______| g+1
*/
ptrdiff_t sz1 = g->stack_saved;
ptrdiff_t sz2 = stop - g->stack_start;
check_valid(g);
_check(stop <= g->stack_stop);
if (sz2 > sz1) {
char *c = (char *)(g + 1);
#if STACK_DIRECTION == 0
memcpy(c+sz1, g->stack_start+sz1, sz2-sz1);
# ifdef DEBUG_DUMP
if (overwrite_stack_for_debug)
memset(g->stack_start+sz1, 0xdb, sz2-sz1);
# endif
#else
xxx;
#endif
g->stack_saved = sz2;
}
}
/* Allocate and store in 'g_source' a new stacklet, which has the C
* stack from 'old_stack_pointer' to 'g_current_stack_stop'. It is
* initially completely unsaved, so it is attached to the head of the
* chained list of 'stack_prev'.
*/
static int g_allocate_source_stacklet(void *old_stack_pointer,
struct stacklet_thread_s *thrd)
{
struct stacklet_s *stacklet;
ptrdiff_t stack_size = (thrd->g_current_stack_stop -
(char *)old_stack_pointer);
thrd->g_source = malloc(sizeof(struct stacklet_s) + stack_size);
if (thrd->g_source == NULL)
return -1;
stacklet = thrd->g_source;
stacklet->stack_start = old_stack_pointer;
stacklet->stack_stop = thrd->g_current_stack_stop;
stacklet->stack_saved = 0;
stacklet->stack_prev = thrd->g_stack_chain_head;
stacklet->stack_thrd = thrd;
thrd->g_stack_chain_head = stacklet;
return 0;
}
/* Save more of the C stack away, up to 'target_stop'.
*/
static void g_clear_stack(struct stacklet_s *g_target,
struct stacklet_thread_s *thrd)
{
struct stacklet_s *current = thrd->g_stack_chain_head;
char *target_stop = g_target->stack_stop;
check_valid(g_target);
/* save and unlink stacklets that are completely within
the area to clear. */
while (current != NULL && current->stack_stop <= target_stop) {
struct stacklet_s *prev = current->stack_prev;
check_valid(current);
current->stack_prev = NULL;
if (current != g_target) {
/* don't bother saving away g_target, because
it would be immediately restored */
g_save(current, current->stack_stop
#ifdef DEBUG_DUMP
, 1
#endif
);
}
current = prev;
}
/* save a partial stack */
if (current != NULL && current->stack_start < target_stop)
g_save(current, target_stop
#ifdef DEBUG_DUMP
, 1
#endif
);
thrd->g_stack_chain_head = current;
}
/* This saves the current state in a new stacklet that gets stored in
* 'g_source', and save away enough of the stack to allow a jump to
* 'g_target'.
*/
static void *g_save_state(void *old_stack_pointer, void *rawthrd)
{
struct stacklet_thread_s *thrd = (struct stacklet_thread_s *)rawthrd;
if (g_allocate_source_stacklet(old_stack_pointer, thrd) < 0)
return NULL;
g_clear_stack(thrd->g_target, thrd);
return thrd->g_target->stack_start;
}
/* This saves the current state in a new stacklet that gets stored in
* 'g_source', but returns NULL, to not do any restoring yet.
*/
static void *g_initial_save_state(void *old_stack_pointer, void *rawthrd)
{
struct stacklet_thread_s *thrd = (struct stacklet_thread_s *)rawthrd;
if (g_allocate_source_stacklet(old_stack_pointer, thrd) == 0)
g_save(thrd->g_source, thrd->g_current_stack_marker
#ifdef DEBUG_DUMP
, 0
#endif
);
return NULL;
}
/* Save away enough of the stack to allow a jump to 'g_target'.
*/
static void *g_destroy_state(void *old_stack_pointer, void *rawthrd)
{
struct stacklet_thread_s *thrd = (struct stacklet_thread_s *)rawthrd;
thrd->g_source = EMPTY_STACKLET_HANDLE;
g_clear_stack(thrd->g_target, thrd);
return thrd->g_target->stack_start;
}
/* Restore the C stack by copying back from the heap in 'g_target',
* and free 'g_target'.
*/
static void *g_restore_state(void *new_stack_pointer, void *rawthrd)
{
/* Restore the heap copy back into the C stack */
struct stacklet_thread_s *thrd = (struct stacklet_thread_s *)rawthrd;
struct stacklet_s *g = thrd->g_target;
ptrdiff_t stack_saved = g->stack_saved;
check_valid(g);
_check(new_stack_pointer == g->stack_start);
#if STACK_DIRECTION == 0
memcpy(g->stack_start, g+1, stack_saved);
#else
memcpy(g->stack_start - stack_saved, g+1, stack_saved);
#endif
thrd->g_current_stack_stop = g->stack_stop;
g->stack_saved = -13; /* debugging */
free(g);
return EMPTY_STACKLET_HANDLE;
}
STATIC_NOINLINE
void *_stacklet_switchstack(void *(*save_state)(void*, void*),
void *(*restore_state)(void*, void*),
void *extra)
{
return slp_switch(save_state, restore_state, extra);
}
STATIC_NOINLINE
void g_initialstub(struct stacklet_thread_s *thrd,
stacklet_run_fn run, void *run_arg)
{
struct stacklet_s *result;
/* The following call returns twice! */
result = (struct stacklet_s *) _stacklet_switchstack(g_initial_save_state,
g_restore_state,
thrd);
if (result == NULL && thrd->g_source != NULL) {
/* First time it returns. Only g_initial_save_state() has run
and has created 'g_source'. Call run(). */
thrd->g_current_stack_stop = thrd->g_current_stack_marker;
result = run(thrd->g_source, run_arg);
/* Then switch to 'result'. */
check_valid(result);
thrd->g_target = result;
_stacklet_switchstack(g_destroy_state, g_restore_state, thrd);
_check_failed("we should not return here");
abort();
}
/* The second time it returns. */
}
/************************************************************/
stacklet_thread_handle stacklet_newthread(void)
{
struct stacklet_thread_s *thrd;
thrd = malloc(sizeof(struct stacklet_thread_s));
if (thrd != NULL)
memset(thrd, 0, sizeof(struct stacklet_thread_s));
return thrd;
}
void stacklet_deletethread(stacklet_thread_handle thrd)
{
free(thrd);
}
stacklet_handle stacklet_new(stacklet_thread_handle thrd,
stacklet_run_fn run, void *run_arg)
{
long stackmarker;
_check((char *)NULL < (char *)&stackmarker);
if (thrd->g_current_stack_stop <= (char *)&stackmarker)
thrd->g_current_stack_stop = ((char *)&stackmarker) + 1;
thrd->g_current_stack_marker = (char *)&stackmarker;
g_initialstub(thrd, run, run_arg);
return thrd->g_source;
}
stacklet_handle stacklet_switch(stacklet_handle target)
{
long stackmarker;
stacklet_thread_handle thrd = target->stack_thrd;
check_valid(target);
if (thrd->g_current_stack_stop <= (char *)&stackmarker)
thrd->g_current_stack_stop = ((char *)&stackmarker) + 1;
thrd->g_target = target;
_stacklet_switchstack(g_save_state, g_restore_state, thrd);
return thrd->g_source;
}
void stacklet_destroy(stacklet_handle target)
{
check_valid(target);
if (target->stack_prev != NULL) {
/* 'target' appears to be in the chained list 'unsaved_stack',
so remove it from there. Note that if 'thrd' was already
deleted, it means that we left the thread and all stacklets
still in the thread should be fully copied away from the
stack --- so should have stack_prev == NULL. In this case
we don't even read 'stack_thrd', already deallocated. */
stacklet_thread_handle thrd = target->stack_thrd;
struct stacklet_s **pp = &thrd->g_stack_chain_head;
for (; *pp != NULL; pp = &(*pp)->stack_prev) {
check_valid(*pp);
if (*pp == target) {
*pp = target->stack_prev;
break;
}
}
}
target->stack_saved = -11; /* debugging */
free(target);
}
char **_stacklet_translate_pointer(stacklet_handle context, char **ptr)
{
char *p = (char *)ptr;
long delta;
if (context == NULL)
return ptr;
check_valid(context);
delta = p - context->stack_start;
if (((unsigned long)delta) < ((unsigned long)context->stack_saved)) {
/* a pointer to a saved away word */
char *c = (char *)(context + 1);
return (char **)(c + delta);
}
if (((unsigned long)delta) >=
(unsigned long)(context->stack_stop - context->stack_start)) {
/* out-of-stack pointer! it's only ok if we are the main stacklet
and we are reading past the end, because the main stacklet's
stack stop is not exactly known. */
_check(delta >= 0);
_check(((long)context->stack_stop) & 1);
}
return ptr;
}
|
C
|
#include <stdio.h>
int main(){
int mult = 0;
printf("Os multiplos de 3:\n");
for(int i = 1; i <= 5; i++){
mult = i * 3;
printf("%d ", mult);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct Student{
char number[20];
char name[20];
char gender[5];
unsigned age;
char address[100];
};
struct Node {
struct Student data;
struct Node* next;
};
//struct Student* create_list(struct Student head)
int main() {
// Initialize the example data
struct Student student1;
strcpy(student1.number,"1111111");
strcpy(student1.name,"ChopperCP");
strcpy(student1.gender,"Male");
student1.age=21;
strcpy(student1.gender,"Earth");
// Init array;
struct Student students_arr[10];
for (int i=0;i<10;++i){
students_arr[i]=student1;
}
// Init list
struct Node head;
head.data=student1;
head.next=NULL;
struct Node* curr=&head;
for (int i=0;i<9;++i){
struct Node* new_node=malloc(sizeof(struct Node));
struct Student* student1_clone=malloc(sizeof(struct Student));
memcpy(student1_clone,&student1,sizeof(struct Student));
new_node->data=*student1_clone;
new_node->next=NULL;
curr->next=new_node;
curr=new_node;
}
// Print out the address.
for (int i=0;i<10;++i){
printf("[Array] the %dth element is at: 0x%x\n",i,&students_arr[i]);
}
curr=&head;
for (int i=0;i<10;++i){
// for (int deref=i;deref>0;--deref) {
// curr=curr->next;
// }
printf("[List] the %dth element is at: 0x%x\n", i, &(curr->data));
curr=curr->next;
}
return 0;
}
|
C
|
/*
* @lc app=leetcode id=958 lang=c
*
* [958] Check Completeness of a Binary Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int count_node(struct TreeNode *root)
{
if (!root)
return 0;
return 1 + count_node(root->left) + count_node(root->right);
}
bool dfs(struct TreeNode *root, int index, int total)
{
if (!root)
return true;
if (index > total)
return false;
return dfs(root->left, 2 * index, total) && dfs(root->right, 2 * index + 1, total);
}
bool isCompleteTree(struct TreeNode *root)
{
int node_count = count_node(root);
return dfs(root, 1, node_count);
}
// @lc code=end
// Note: BFS
|
C
|
#include "lists.h"
#include <string.h>
/**
* add_nodeint_end - a function that adds a new node at the end of
* a listint_t list.
* @head: points to the address of the first node.
* @n: the value int.
* Return: the address of the new element, or NULL if it failed.
*/
listint_t *add_nodeint_end(listint_t **head, const int n)
{
listint_t *new_node, *tmp;
tmp = *head;
new_node = malloc(sizeof(listint_t));
if (new_node == NULL)
return (NULL);
new_node->n = n;
new_node->next = NULL;
if (*head == NULL)
*head = new_node;
else
{
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = new_node;
}
return (new_node);
}
|
C
|
/* --------------------------------------------------------------------
-- Company: TEIS AB
-- Engineer: Lasse Karagiannis
--
-- Create Date: 2016-10-01
-- Design Name: uppgift_4a
-- Target Devices: BeMicro Max 10 board
-- Tool versions: Quartus v16 and Eclipse
--
-- In_signals:
-- key_in -- button input button-0,-1,-2,3-
Out_signals:
-- LED -- D1 - D3
-------------------------------------------------------------------
*/
#include <io.h>
#include <alt_types.h>
#include <system.h>
#include "altera_avalon_pio_regs.h"
#include <stdio.h>
int main()
{
alt_u32 key_in, LEDs,temp;
// States in the design
enum state {Input_KEY_state, Working_State,
Output_LED_State_0,
Output_LED_State_1,Output_LED_State_2,
End_state};
enum state current_state;
//Initialization
current_state = Input_KEY_state;
IOWR_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE,0xFF);//Turn off LEDs
while(1) // Loop for ever
{
key_in = IORD_ALTERA_AVALON_PIO_DATA(PIO_IN_KEY_BASE);
switch (current_state)
{
//Start
case Input_KEY_state:
// Om en knapp r nertryckt byt till tillstndet working_state* annars
//stanna kvar i samma tillstnd.
if(((key_in & 0xFF) == 0xFE) ||((key_in & 0xFF) ==0xFD) ||((key_in & 0xFF) ==0xFB))
current_state = Working_State;
break;
case Working_State:
// Byt till tillstndet Output_LED_State_X (Beroende av vilken knapp som r tryckt)
if ((key_in & 0xFF) == 0xFE)
current_state = Output_LED_State_0;
if ((key_in & 0xFF) == 0xFD)
current_state = Output_LED_State_1;
if ((key_in & 0xFF) == 0xFB)
current_state = Output_LED_State_2;
break;
case Output_LED_State_0:
// Toggla enbart den lysdioden det gller, de vriga ska inte pverkas
// byt till tillstndet End_state
LEDs = IORD_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE);
LEDs ^= 0x01;
IOWR_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE,LEDs);
if(LEDs & 0b00000001)
printf("Led0 lyser ej");
else
printf("Led0 lyser");
current_state = End_state;
break;
case Output_LED_State_1:
// Toggla enbart den lysdioden det gller, de vriga ska inte pverkas
// byt till tillstndet End_state
LEDs = IORD_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE);
LEDs ^= 0x02;
IOWR_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE,LEDs);
if(LEDs & 0b00000010)
printf("Led1 lyser ej");
else
printf("Led1 lyser");
current_state = End_state;
break;
case Output_LED_State_2:
// Toggla enbart den lysdioden det gller, de vriga ska inte pverkas
// byt till tillstndet End_state
LEDs = IORD_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE);
LEDs ^= 0x04;
IOWR_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE,LEDs);
//if(LEDs == 0Xfb)
if(LEDs &0b00000100)
printf("Led2 lyser ej");
else
printf("Led2 lyser");
current_state = End_state;
break;
case End_state:
// Om ingen tryckknapp r nertryckt, byt till Input_key_state annars stanna
//kvar i End_state.
if(((key_in & 0xFF) == 0xFE) ||((key_in & 0xFF) ==0xFD) ||((key_in & 0xFF) ==0xFB))
current_state = End_state;
else
current_state = Input_KEY_state;
break;
};//end switch
}; // End loop
return 0;
}
/*
void delay_function(int time_delay)
{
int i;
for(i=1; i<time_delay;i++);
for(i=1; i<time_delay;i++);
}
int main()
{
alt_u32 led_value;
// if you get error, please lock into the file alt_types.h
// loop for ever
while(1)
{
led_value = 0;
alt_printf("Led: %x\n", led_value);
printf("Led: %x\n", led_value);
IOWR_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE, led_value);
delay_function(500000);
led_value = 0xF;
alt_printf("Led: %x\n", led_value);
printf("Led: %x\n", led_value);
IOWR_ALTERA_AVALON_PIO_DATA(PIO_OUT_LED_BASE, led_value);
delay_function(500000);
}
return 0;
}
*/
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define STACK_SIZE 100
#define MAZE_SIZE 6
typedef struct StackObjectRec {
short r;
short c;
}StackObject;
StackObject stack[STACK_SIZE];
int top = -1;
StackObject here = { 1,0 }, entry = { 1,0 };
char maze[MAZE_SIZE][MAZE_SIZE] = {
{'1','1','1','1','1','1'},
{'e','0','1','0','0','1'},
{'1','0','0','0','1','1'},
{'1','0','1','0','1','1'},
{'1','0','1','0','0','x'},
{'1','1','1','1','1','1'},
};
int init() {
return(top == -1);
}
int isEmpty() {
return(top == -1);
}
int isFull() {
return (top == STACK_SIZE - 1);
}
int Push(StackObject item) {
if (isFull()) {
printf("\n\nStack is full\n");
}
else {
stack[++top] = item;
}
}
StackObject pop() {
if (isEmpty()) {
printf("\n\nStack is empty!\n");
}
else {
return stack[top--];
}
}
void printStack() {
int i;
for (i = MAZE_SIZE-1; i > top; i--) {
printf("| |\n");
}
for (i = top; i >= 0; i--) {
printf("|(%01d,%01d)| \n", stack[i].r,stack[i].c);
}
printf("-----\n");
}
void pushloc(int r, int c) {
if (r < 0 || c < 0) {
return;
}
if (maze[r][c] != '1' && maze[r][c] != '.') {
StackObject temp;
temp.r = r;
temp.c = c;
Push(temp);
}
}
void printMaze(char m[MAZE_SIZE][MAZE_SIZE]) {
int r, c;
printf("\n\n");
for (r = 0; r < MAZE_SIZE; r++) {
for (c = 0; c < MAZE_SIZE; c++) {
if (c == here.c && r == here.r) {
printf("m ");
}
else {
if (m[r][c] == 0) {
printf("0 ");
}
else {
printf("%c ", m[r][c]);
}
}
}
printf("\n");
}
printf("\n\n");
}
void findroot() {
short r, c;
here = entry;
printMaze(maze);
printStack();
while (maze[here.r][here.c] != 'x') {
printMaze(maze);
r = here.r;
c = here.c;
maze[r][c] = '.';
pushloc(r - 1, c);
pushloc(r + 1, c);
pushloc(r, c-1);
pushloc(r, c+1);
printStack();
if (isEmpty()) {
printf("FAILURE\n");
return;
}
else {
here = pop();
}
printMaze(maze);
printStack();
}
printf("SUCCESS!\n");
}
int main() {
findroot();
getchar();
return 0;
}
|
C
|
#ifndef __memory_h_
#define __memory_h_
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strcmp() */
#include "debug.h"
#include "process.h"
typedef struct _MemoryModel
{// Represents memory entites in computer (Real Memory and Disk)
int realMemorySize;
int swapMemorySize;
int **realMemory;
int **swapMemory;
// free lists
int **freeRealMemory; // holds info wheter a cell is free (just 0 or 1)
int **freeSwapMemory; // same but for swap area*/
}MemoryModel;
MemoryModel* Memory_CreateModel(int realMemorySize, int swapMemorySize);
int Memory_GetNumFreeFrames(MemoryModel *mem, char *_memType);
int Memory_AddPage(MemoryModel *mem, char *_memType, int pageContent);
void Memory_RemovePage(MemoryModel *mem, char *_memType, int pageContent);
void Memory_RemoveProcess(MemoryModel *mem, Process *process);
void *Memory_GetModelProperty(MemoryModel *mem, char *memType, char *property);
void Memory_PrintUsedList(MemoryModel *mem, char *_memType, FILE *out);
void Memory_PrintFreeList(MemoryModel *mem, char *_memType, FILE *out);
void Memory_PrintMatrix(MemoryModel *mem, char *_memType, FILE *out);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getNumbers(char *array);
int getNumbers(char *array){
int numbers = 0;
while(array = strpbrk(array, "0123456789")){
numbers = numbers * 10 + *array++ - '0';
}
return numbers;
}
int main()
{
char *array;
array = malloc(sizeof(char));
printf("Insert the alphanumeric array:\n");
scanf("%s", array);
printf("Numbers: %d\n", getNumbers(array));
return 0;
}
|
C
|
#include "../domain.h"
inherit "/std/room";
#define FILE DIR + "/rooms/entrance.c"
void setup(void) {
add_area("newbie");
set_short("Северная часть поля");
set_long("Вы остановились у старого мертвого дерева в центре большого поля. " +
" Чуть дальше на юге вы замечаете дорогу, ведущую к городу. Также " +
"тут привлекает внимание странная нора в холме на востоке.");
set_exits(([
"юг" : STARTING_ROOM,
"восток" : "#enter_hole",
]));
set_objects(
DIR + "/obj/sign",
DIR + "/obj/tree"
);
add_item("нора", "Это довольно таки большая нора. Вы даже сможете " +
"наверно протиснуться в нее.");
add_action("break_branch", "сломать");
add_action("squeeze_hole", "протиснуться");
}
int break_branch(string str) {
object obj;
if ((str == "ветка") || (str == "ветку")) {
if (this_player()->is_completed_quest("NewbieVille")) {
write("На дереве не осталось доступных веток, все обломали.\n");
} else {
if (this_player()->query_gender() == "male") {
this_player()->query_environment()->tell_room(this_player(),
this_player()->query_Name() + " сломал ветку с дерева.\n");
} else if (this_player()->query_gender() == "female") {
this_player()->query_environment()->tell_room(this_player(),
this_player()->query_Name() + " сломала ветку с дерева.\n");
} else {
this_player()->query_environment()->tell_room(this_player(),
this_player()->query_Name() + " сломало ветку с дерева.\n");
}
write("Вы отломили ветку от дерева.\n");
obj = clone_object(DIR + "/obj/stick.c");
obj->move(this_player());
obj->setup();
}
return 1;
} else {
return 0;
}
}
void enter_hole(void) {
object obj;
if (this_player()->is_completed_quest("NewbieVille")) {
write("Вы больше не можете пролезть в нору.");
this_object()->tell_room(this_player(), this_player()->query_Name() +
" пытается пролезть через нору, " +
"но неудачно.");
return;
} else {
obj = find_object(FILE);
if (!obj) {
obj = compile_object(FILE);
if (!obj) {
write("Ошибка в загрузке направления.\n");
return;
}
obj->setup();
obj->setup_mudlib();
}
if (this_player()->move(obj)) {
write("Вы протискиваетесь через нору.");
this_object()->tell_room(this_player(),
this_player()->query_Name() + " протискивается через нору.\n");
this_player()->do_look(this_environment());
}
}
return;
}
int squeeze_hole(string str) {
object obj;
if ((str == "hole") || (str == "") || (str == "нора") || (str == "нору")) {
enter_hole();
return 1;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
bool judgeSquareSum(int c)
{
int n=(int)sqrt(c);//强制转换
int left=0;
int right=n;
while(left<=right)
{
int tmp=left*left+right*right;
if(c==tmp)
{
return true;
}
if(tmp>c)
{
right--;
}
if(tmp<c)
{
left++;
}
}
return false;
}
int main(){
int m;
scanf("%d",&m);
judgeSquareSum(m);
}
//给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c。
|
C
|
#include <stdio.h>
#include <string.h>
#include "radioSort.h"
void getTxtData(char *filename,Wrap *awp);
void visiteWrap(Wrap wap,char *tips);
int main(int argc,char *argv[]){
Wrap awp = {NULL,NULL,0,0};
getTxtData("data.txt", &awp);
visiteWrap(awp,"基数排序\ndefore sort:");
radioSort(&awp);
visiteWrap(awp,"after sort:");
return 0;
}
void getTxtData(char *filename,Wrap *awp){
FILE *fp = fopen(filename, "r");
if( fp ){
char *read = NULL,
seperator[] = " \n";
size_t getlen = 0;
while( getline( &read, &getlen, fp) != -1 ){
getlen = 0;
char *data = strchr(read,':') + 1,
*name = strndup(read, data-read-1);
if( strcmp(name,"radio")==0 ){
int len = atoi(data);
setKeyNode(awp, len);
}else if( strcmp(name,"keynum")==0 ){
awp->keyLayer = atoi(data);
}else if( strcmp(name,"data")==0 ){
setKeyArray(awp, data);
}
}
}
}
void visiteWrap(Wrap wap,char *tips){
printf("%s", tips);
for(int i = 0; i < wap.lenKey; ++i){
printf("%-5s", wap.keyArr[i]);
}
printf("\n");
}
|
C
|
#include<stdio.h>
#include<assert.h>
#include<math.h>
int convert(long int);
void main()
{
long int binary;
printf("Enter the Binary number: ");
scanf("%ld",&binary);
printf("\nDecimal value is : %d\n\n",convert(binary));
assert(convert(1010) == 10);
assert(convert(11) == 2);
}
int convert(long int bin)
{
int i = 0, dec = 0;
long int temp;
while(bin != 0)
{
temp = bin % 10;
bin = bin / 10;
dec = dec + temp * pow(2 , i);
i++;
}
return dec;
}
|
C
|
#include <stdio.h>
#include "./mylib1.h"
int main()
{
int a;
printf("\nEnter ...");
scanf("%d", &a);
int b = lenOfNumber(a);
printf("\n Is %d", b);
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "errors.h"
#include "parser.h"
#include "my.h"
t_parseeye ptr_eye[] =
{
{"position", set_eye_position},
{"rotation", set_eye_rotation},
{NULL, NULL},
};
static void check_arg(t_eye *eye, char **tab)
{
int n;
int check;
n = 0;
check = FAILURE;
while (ptr_eye[n].str)
{
if (tab[0] && !strcmp(tab[0], ptr_eye[n].str))
check = ptr_eye[n].func(eye, tab);
n++;
}
if (tab[0] && check == FAILURE)
{
fprintf(stderr, ERROPT, tab[0]);
exit(EXIT_FAILURE);
}
}
void check_eye(t_eye *eye, char **tab)
{
int i;
char **arg;
i = 1;
while (tab[i])
{
arg = my_worldtab(tab[i], "=,");
check_is_num(arg);
check_arg(eye, arg);
xfree_tab(arg);
i++;
}
}
|
C
|
#include "min.h"
int min(int a, int b){
if(a < b) return a;
else return b;
}
|
C
|
#include<stdio.h>
//int a = 100;
//int main()
//{
// //char ch = 'A';
// //printf("%c\n",ch);
// //int age =20;
// //printf("%d\n",age);
// //printf("%d\n",sizeof(char));
// //printf("%d\n",sizeof(short));
// //printf("%d\n",sizeof(int));
// //printf("%d\n",sizeof(long));
// //printf("%d\n",sizeof(long long));
// //printf("%d\n",sizeof(float));
// //printf("%d\n",sizeof(double));
// //int a = 10;
// printf("%d\n",a);
// return 0;
//}
//int main()
//{
// //ĺ
// int num1 = 0;
// int num2 = 2;
// int sum = 2;
// //-뺯scanf
// scanf("%d%d",&num1,&num2);//ȡַ&
// sum = num1+num2;
// printf("sum = %d\n",sum);
// return 0;
//}
//int main()
//{
// int num = 0;
// printf("num = %d\n", num);
// return 0;
//}
//int global=2021;
//void test()
//{
// printf("test()--%d\n",global);
//}
//
//int main()
//{
// test();
// printf("%d\n",global);
// return 0;
//}
int main()
{
//δñʶ
//externⲿ
extern int g_val;
printf("g_val=%d\n",g_val);
return 0;
}
|
C
|
#include <stdio.h>
main()
{
int i,n;
printf("Bir sayi giriniz: ");
scanf("%d", &n);
if(n>10)
{
printf("%d sayisi 10 veya 10 dan kucuk bir sayi olmali !", n);
}
else
{
for( i=1; i<n; i=i+1 )
{
printf("Sayilan Sayi=%d\n", i);
}
printf("1 ile 10 arasinda %d sayisindan kucuk %d sayi var.", n, i-1);
}
return 0;
}
|
C
|
#include <stdio.h>
#include "bst.h"
#include "assert.h"
#include "structs.h"
/*----------------------------------------------------------------------------
very similar to the compareTo method in java or the strcmp function in c. it
returns an integer to tell you if the left value is greater then, less then, or
equal to the right value. you are comparing the number variable, letter is not
used in the comparison.
if left < right return -1
if left > right return 1
if left = right return 0
*/
/*Define this function type casting the value of void * to the desired type*/
int compare(TYPE left, TYPE right)
{
/*write this*/
/*return 0;*/
struct data* data1;
struct data* data2;
data1=(struct data*)left;
data2=(struct data*)right;
if (data1->number < data2->number)
return -1;
else if (data1->number > data2->number)
return 1;
else
return 0;
}
/*Define this function type casting the value of void * to the desired type*/
void print_type(TYPE curval)
{
/*write this*/
/*return 0;*/
struct data* data1;
data1=(struct data*)curval;
printf(" %d ", data1->number);
}
|
C
|
/*
** main.c for in /home/trambe_m/CPE_2014_corewar/bonus/asmdsm/src
**
** Made by Manuel Trambert
** Login <trambe_m@epitech.net>
**
** Started on Sun Apr 12 17:20:09 2015 Manuel Trambert
** Last update Sun Apr 12 19:57:18 2015 Manuel Trambert
*/
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include "my_select.h"
#include "my.h"
t_glob g_glob;
void gere_key(SDL_Event event)
{
char **av;
av = my_str_to_wordtab("./asm .");
if (event.key.keysym.sym == SDLK_ESCAPE)
exit(0);
else if (event.key.keysym.sym == SDLK_UP)
{
g_glob.flag = 1;
my_sdl("Pictures/Compilateur.jpg");
}
else if (event.key.keysym.sym == SDLK_DOWN)
{
g_glob.flag = 0;
my_sdl("Pictures/lol.jpg");
}
else if (event.key.keysym.sym == SDLK_BACKSPACE)
{
SDL_Quit();
my_select(2, av);
}
}
void pause()
{
int continuer;
SDL_Event event;
continuer = 1;
while (continuer != 0)
{
SDL_PollEvent(&event);
if (event.active.type)
gere_key(event);
}
}
void my_sdl(char *str)
{
SDL_Surface *ecran;
SDL_Surface *imageDeFond;
SDL_Rect positionFond;
ecran = NULL;
imageDeFond = NULL;
positionFond.x = 0;
positionFond.y = 0;
if ((SDL_Init(SDL_INIT_VIDEO)) == -1)
exit(0);
SDL_WM_SetIcon(IMG_Load("sdl_icone.bmp"), NULL);
ecran = SDL_SetVideoMode(2000, 1500, 32, SDL_HWSURFACE);
SDL_WM_SetCaption("Chargement d'images en SDL", NULL);
if ((imageDeFond = IMG_Load(str)) == NULL)
exit(EXIT_FAILURE);
SDL_BlitSurface(imageDeFond, NULL, ecran, &positionFond);
SDL_Flip(ecran);
pause();
SDL_FreeSurface(imageDeFond);
SDL_Quit();
}
int main(__attribute__((unused))int ac, char **av)
{
g_glob.flag = 0;
if (ac == 2)
{
if (my_strcmp(av[1], "--help") != 0)
print_help(av[2]);
}
else
my_sdl("Pictures/Compilateur.jpg");
return (0);
}
|
C
|
# include <stdio.h>
# include <omp.h>
int a[65536],s,test;
int global_size,global_x,n;
void nary_search(int size,int x)
{
if(size<=n)
{
test=0;
#pragma omp parallel num_threads(n)
{
int tid=omp_get_thread_num();
if(a[x+tid]==s)
{
printf("\n FOUND... %d\n",x+tid);
test=1;
}
}
if(test==0)
{
printf("\n NOT FOUND....");
}
}
else
{
test=0;
#pragma omp parallel num_threads(n)
{
int tid=omp_get_thread_num();
if(s>=a[tid*size/n+x] && s<=a[tid*size/n+size/n-1+x])
{
printf("IT MAY BE HERE %d.......%d\n" ,a[tid*size/n+x],a[(tid+1)*size/n-1+x]);
global_size=size/n;
global_x=tid*global_size+x;
test=1;
}
}
if(test==1)
nary_search(global_size,global_x);
else
printf("\n not found");
}
}
int main()
{
int i,size=65536,x=0;
for(i=0;i<=size;i++)
a[i]=i;
printf("\nENTER NUMBER TO BE SEARCH......");
scanf("%d",&s);
printf("\nENTER THE NO.OF THREADS TO BE USE......");
scanf("%d",&n);
nary_search(size,x);
return 0;
}
/*
*************************************************************
OUTPUT:-
comp-sl-12@compsl12-OptiPlex-3020:~/Desktop$ gcc nary_search.c -fopenmp
comp-sl-12@compsl12-OptiPlex-3020:~/Desktop$ ./a.out
ENTER NUMBER TO BE SEARCH......456
ENTER THE NO.OF THREADS TO BE USE......3
IT MAY BE HERE 0.......21844
IT MAY BE HERE 0.......7280
IT MAY BE HERE 0.......2426
IT MAY BE HERE 0.......808
IT MAY BE HERE 269.......538
IT MAY BE HERE 448.......537
IT MAY BE HERE 447.......475
IT MAY BE HERE 456.......465
IT MAY BE HERE 456.......458
FOUND... 456
*/
|
C
|
#include "../include/complex.h"
const char NAME_PLUGIN[] = "Division";
myComplex division(myComplex a, myComplex b) {
myComplex result;
result.Rb = ((a.Rb * b.Rb) + (a.Im * b.Im)) / (pow(b.Rb, 2) + pow(b.Im, 2));
result.Im = ((b.Rb * a.Im) - (a.Rb * b.Im)) / (pow(b.Rb, 2) + pow(b.Im, 2));
return result;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
float num1,num2,toplam,farki,carpim,bolme;
printf("Lutfen 1. sayiyi giriniz: \t " );
scanf("%f",&num1);
printf("Lutfen 2. sayiyi giriniz: \t " );
scanf("%f",&num2);
toplam=num1+num2;
farki= num1-num2;
carpim=num1*num2;
bolme=num1/num2;
printf("Girdiginiz sayilarin toplami : %f \t \nGirdiginiz sayilarin farki : %f \t \nGirdiginiz sayilarin carpimi : %f \t \nGirdiginiz sayilarin bolumu : %f \t \n",toplam ,farki,carpim,bolme);
return 0;
}
|
C
|
#pragma once
#include <glm/glm/glm.hpp>
#include "glm/glm/gtc/matrix_transform.hpp"
#include "glm/glm/gtc/type_ptr.hpp"
//vecת
float vec2radi(glm::vec3 dir) {
float radi;
if (dir.x == 0)
{
if (dir.z > 0) radi = glm::radians(0.0f);
else radi = glm::radians(180.0f);
return radi;
}
else if (dir.z == 0)
{
if (dir.x > 0) radi = glm::radians(90.0f);
else radi = glm::radians(270.0f);
return radi;
}
if (dir.x > 0)
//radi = atan(dir.x / dir.z);
radi = acos(dir.z / (sqrt(dir.x*dir.x + dir.z*dir.z)));
else
radi = acos(-dir.z / (sqrt(dir.x*dir.x + dir.z*dir.z))) + glm::radians(180.0f);
return radi;
}
|
C
|
/* -*- indent-tabs-mode: t; tab-width: 2; c-basic-offset: 2; c-default-style: "stroustrup"; -*- */
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include "./event.h"
int events_minimumSleep(struct linked_list *events){
int result = -1;
struct event *current;
while(events){
current = events->data;
if(current){
if(-1 == result)
result = current->nanoseconds_checkAgain;
if(-1 != current->nanoseconds_checkAgain)
if(current->nanoseconds_checkAgain < result)
result = current->nanoseconds_checkAgain;
}
events = events->next;
}
return result;
}
int events_whichPreconditionMet(struct linked_list *events, struct linked_list* *out){
struct event *candidate;
while(events){
candidate = events->data;
if(candidate){
if(!(candidate->precondition)){
*out = events;
return 0;
}
if((*(candidate->precondition))(candidate, 0)){
*out = events;
return 0;
}
}
events = events->next;
}
return 0;
}
int events_stepOrSleep(struct dequoid *events){
int minimumSleep;
struct linked_list *tempNode;
struct linked_list *node = 0;
struct event *currentEvent = 0;
struct timespec nanotime;
linkedList_popEmptyFreeing(&(events->head));
if(linkedList_removeMiddleEmptiesFreeing(events->head)) return 1;
minimumSleep = events_minimumSleep(events->head);
if(events_whichPreconditionMet(events->head, &node)) return 2;
if(node)
if(node->data)
currentEvent = node->data;
if(currentEvent){
node->data = 0;
node = 0;
if(currentEvent->step)
node = (*(currentEvent->step))(currentEvent, 0);
free(currentEvent);
while(node){
tempNode = node->next;
if(node->data)
dequoid_append(events, node->data, malloc(sizeof(struct linked_list)));
node->next = 0;
node->data = 0;
free(node);
node = tempNode;
}
return 0;
}
if(minimumSleep > 1000){
usleep(minimumSleep / 1000);
return 0;
}
if(!minimumSleep) return 0;
nanotime.tv_sec = 0;
nanotime.tv_nsec = minimumSleep;
nanosleep(&nanotime, 0);
return 0;
}
|
C
|
#include<stdio.h>
// include other libraries if needed
//made to easily print out array
void printArray(int* test, int length){
int i;
for (i = 0; i < length; i++){
printf("%d", test[i]);
if (i != length-1){
printf(",");
}
}
printf("\n");
}
int main() {
int testArray[] = {29, 17, 8, 17, 9, 17, 29,9};
//expected output
// 29,17,8,9
//implement your code here
int i, j, a;
//find the number of elements in the array
int length = sizeof(testArray) / sizeof(testArray[0]);
//iterate through the array to check
for (i = 0; i < length; i++){
//check the rest of the array to check if there are more in the array
for (j = i+1; j < length; j++){
//if the two match the start replacing the j index
if (testArray[i] == testArray[j]){
//iterate down length since a duplicate has been found
for (a = j; a < length; a++){
testArray[a] = testArray[a+1];
}
length = length-1;
}
}
}
printArray(testArray, length);
return 0;
}
|
C
|
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<pthread.h>
#include<semaphore.h>
#define MAX_RESOURCES 7
sem_t mutex;
sem_t mutex1;
int available_Licences=MAX_RESOURCES;
/*decrease available resources by count resources*/
void *decrease_count(void *coun)
{ int *count =coun;
sem_wait(&mutex);
while(available_Licences<*count)
printf("\n>>>>>>> Client is Waiting to get %d Licences Because Available Resource is %d <<<<<<<",*count,available_Licences);
available_Licences-=*count;
printf("\n:::::: Number of Licence Given to new Client is %d now Remaining Licences are %d :::::: \n ",*count,available_Licences);
sem_post(&mutex);
increase_count(*count);
}
/*when a process want to return a number of resources ,it calls the increase count() function:
increase available _resources by count */
int increase_count(int coun)
{ sem_wait(&mutex1);
int count =coun;
available_Licences+=count;
printf("\n:::::: Number of Licence Expired are %d now Availability Of Resources Increased to %d ::::::\n",count,available_Licences);
sem_post(&mutex1);
}
int main()
{
printf(" **************************************************");
printf("\n**************WELCOME TO LICENCE PROVIDER LTD*********************\n");
printf(" **************************************************\n\n");
getch();
sem_init(&mutex,0,1);
sem_init(&mutex1,0,1);
pthread_t client[100];
int count[100];
int clients,i;
printf("\n Enter the no of Clients :");
scanf("%d",&clients);
for(i=0;i<clients;i++)
{
printf("\n Enter no of Licence Client %d wants :",i+1);
scanf("%d",&count[i]);
if(count[i]>available_Licences)
{
printf("\n:::::: Requested Licence Exceed the availability of no of Licences plse Reducde the no of Licence ::::::\n");
i=i-1;
}
}
for(i=0;i<clients;i++)
{
pthread_create(&client[i],NULL,decrease_count,&count[i]);
}
for( i=0;i<clients;i++)
{
pthread_join(client[i],NULL);
}
}
|
C
|
#include <stdio.h>
//declaring a function square above the main function
int square(int num);
int main() {
int result,n;
n=6;
for(int i=1;i<n;i++)
printf("The result is: %d\n",square(i));
return 0;
}
int square(int num)
{
int y;
y=num*num;
return(y);
}
|
C
|
//
// Created by alpharius on 06.08.19.
//
#include "interpolate.h"
//#include
#define TEST//NOT_TEST
// TODO - написать динамически линкуемую версию полинома лагранжа
// не оптимизированные полиномы Лагранжа.
double Lagrange_polinom_interpolation(double x, double* x_set, double* y_set, size_t len){
double result =0;
// промежуточные произведения
double loop_result=1;
for(size_t i=0; i<len; i++){
for(size_t j=0; j<len; j++){
if (i!=j)
loop_result *= (x-x_set[j]) / (x_set[i]-x_set[j]);
}
result += y_set[i] * loop_result;
loop_result = 1.;
}
return result;
}
#ifdef TEST2
#define SIZE 50
int main(void){
double x[SIZE];
double y[SIZE];
for(int i=0; i<SIZE; i++){
x[i] = 0 + 2*M_PI/SIZE * i;
y[i] = sin(x[i]);
}
for (int i=0; i<5; i++){
y[i] = sin(x[i]);
}
double dx = 0.01;
double arg = 0.;
FILE *fp = fopen("interpolation.txt", "w");
FILE *fp2 = fopen("sin.txt", "w");
while (arg < 2*M_PI+1){
fprintf(fp,"%lf %lf\n",arg, Lagrange_polinom_interpolation(arg, x, y, SIZE));
fprintf(fp2, "%lf %lf\n", arg, sin(arg));
arg += dx;
}
fclose(fp);
fclose(fp);
return 0;
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.