language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | //// 10 - Է¹ Ǵϴ α Ͻÿ.
//// ( - 4 ̰, 100 ƴ or 400 )
//#include <stdio.h>
//int main( )
//{
// int year; // Է¹
//
// printf(" Է: ");
// scanf("%d", &year);
//
// if(((year%4==0)&&(year%100!=0))||(year%400==0))
// printf("\n");
// else
// printf("\n");
//} |
C | #include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int enqueue(int queue[], int *back, int *p, int a){
(*p)++;
queue = (int *)realloc(queue, (*p) * sizeof(int));
queue[*back] = a;
(*back)++;
}
int pop(int *front){
(*front)++;
}
int main(){
int n, i, j;
scanf("%d",&n);
int a[n];
int *massage, front = 0, back = 1, p = 1;
massage = (int *)malloc(p * sizeof(int));
bool dk = false;
for(i = 0; i < n; i++){
scanf("%d", &a[i]);
}
int k;
scanf("%d",&k);
massage[0] = a[0];
for(i = 1;i < n;i++){
if(p < k){
dk = false;
for(j = 0;j < i;j++){
if(a[i] == a[j]) dk = true;
}
if(dk == false){
enqueue(massage, &back, &p, a[i]);
}
}
else if(p >= k){
dk = false;
for(j = p - k;j < p;j++){
if(a[i] == massage[j]) dk = true;
}
if(dk == false){
enqueue(massage, &back, &p, a[i]);
pop(&front);
}
}
}
for(i = front;i < back;i++){
printf("%d ",massage[i]);
}
free(massage);
return 0;
}
|
C | #pragma once
#include <inttypes.h>
#include <math.h>
struct MidiNote
{
uint8_t channel;
uint8_t note;
uint8_t velocity;
static double getFrequency(int midiNote)
{
return 440.0 * powf(2.0, (midiNote - 69) * 0.08333333333333333);
}
}; |
C | //100~999ˮɻ
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main(void)
{
int i = 100;
do
{
//λ
int a = i % 10;
//ʮλ
int b = i / 10 % 10;
//λ
int c = i / 100;
if (pow(a, 3) + pow(b, 3) + pow(c, 3) == i)
{
printf("%d\n", i);
}
i++;
} while (i < 1000);
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* read_filepart_3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jsprigga <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/27 14:37:48 by jsprigga #+# #+# */
/* Updated: 2018/12/27 15:22:23 by jsprigga ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int check_coord(t_point *curr_p, int i, t_list *tmp)
{
int res;
int j;
t_point *changing_p;
res = 0;
j = -1;
while (++j < 4)
{
changing_p = ((t_elem *)tmp->content)->point[j];
if (i == j)
continue;
if ((curr_p->x + 1) == changing_p->x && curr_p->y == changing_p->y)
res++;
if ((curr_p->x - 1) == changing_p->x && curr_p->y == changing_p->y)
res++;
if ((curr_p->y + 1) == changing_p->y && curr_p->x == changing_p->x)
res++;
if ((curr_p->y - 1) == changing_p->y && curr_p->x == changing_p->x)
res++;
}
return (res);
}
void check_figures_validity(t_list **tetr_list)
{
t_list *tmp;
int i;
int sum_figure;
t_point *curr_p;
tmp = *tetr_list;
while (tmp)
{
i = -1;
sum_figure = 0;
while (++i < 4)
{
curr_p = ((t_elem *)tmp->content)->point[i];
sum_figure += check_coord(curr_p, i, tmp);
}
tmp = tmp->next;
if (sum_figure < 6)
f_error(tetr_list);
}
}
|
C | /*
Problem Statement :
Accept N numbers from user check whether that numbers contains 11 in
it or not.
Input : N : 6
Elements : 85 66 11 80 93 88
Output : 11 is present
Input : N : 6
Elements : 85 66 3 80 93 88
Output : 11 is absent
*/
#include "Header.h"
int main()
{
int iValue = 0;
int *ptr = NULL;
int iCnt = 0;
BOOL bRet = FALSE;
printf("Enter the number of values :\n");
scanf("%d", &iValue);
if (iValue <= 0)
{
printf("ERROR : INVALID NUMBER OF VALUES\n");
return -1;
}
ptr = (int *)malloc(sizeof(int) * iValue);
if (ptr == NULL)
{
printf("ERROR : unbale to Allocate Memory\n");
return -1;
}
printf("Enter %d Numbers \n", iValue);
for (iCnt = 0; iCnt < iValue; iCnt++)
{
scanf("%d", &ptr[iCnt]);
}
bRet = Check(ptr, iValue);
if (bRet == ERRARRAY)
{
printf("ERROR : Invalid memory address\n");
}
else if (bRet == ERRSIZE)
{
printf("ERROR : Invalid size\n");
}
else if (bRet == TRUE)
{
printf("11 is Present\n");
}
else
{
printf("11 is Absent\n");
}
return 0;
} |
C | #include<stdio.h>
#include<locale.h>
int main() {
setlocale(LC_ALL, "Russian");
int n,s,k=0,r=0;
printf(" ");
scanf_s("%d", &n);
s = n; //
// -
while (5 < 6) { //
if (s % 10 == 0) {
break;
}
else {
s /= 10;
k++;
}
}
if (k == 1) {
printf(" , \n");
}
else {
for (int i = 0; i < k; i++) {
s = n / 10;
for (int j = 0; j < k; j++) {
if (n % 10 == s % 10) { //
// ..
r++;
}
else {
s /= 10;
}
}
n /= 10; // 10
s = 0;
}
if (r == 0) {
printf(" \n");
}
else {
printf(" \n");
}
}
return 0;
} |
C | #pragma once
#include "Nest/Api/NodeArray.h"
#ifdef __cplusplus
extern "C" {
#endif
/// Structure describing a symbol table, with multiple entries
/// Note that the entries will be allocated after this structure.
struct Nest_SymTab {
struct Nest_SymTab* parent; ///< The parent symbol table
Nest_Node* node; ///< The node that introduced this symbol table
};
typedef struct Nest_SymTab Nest_SymTab;
/// Creates a SymTab object, for the given parent and given node
Nest_SymTab* Nest_mkSymTab(Nest_SymTab* parent, Nest_Node* node);
/// Create and enter a new entry into the symbol table
void Nest_symTabEnter(Nest_SymTab* symTab, const char* name, Nest_Node* node);
/// Add a node to the symtab to be checked whenever we want to search symbols in
/// this symbol table. At the point of adding the node, we don't know yet what
/// symbols the node would generate to the symbol table
void Nest_symTabAddToCheckNode(Nest_SymTab* symTab, Nest_Node* node);
/// Copies the entries from the given tab to the current tab
/// If this symbol table already contains the given symbols, this will not add them anymore.
/// However, if this table contains some copied entries, this will add new entries with the same
/// name
void Nest_symTabCopyEntries(Nest_SymTab* symTab, Nest_SymTab* otherSymTab);
/// Returns a list of symbol table entries
Nest_NodeArray Nest_symTabAllEntries(Nest_SymTab* symTab);
/// Look up an existing symbol table entry, by the name of the symbol
/// Note that more than one symbols can be registered in the table with the same name
Nest_NodeArray Nest_symTabLookupCurrent(Nest_SymTab* symTab, const char* name);
/// Look up an existing symbol table entry and parent entries, by the name of the symbol
/// If no matching symbol is found in the current symbol table, this will recursively try in the
/// parent tables. Note that more than one symbols can be registered in the table with the same name
Nest_NodeArray Nest_symTabLookup(Nest_SymTab* symTab, const char* name);
/// Writes to console the content of the current symbol table and of all the
/// parent symbol tables
void Nest_dumpSymTabs(Nest_SymTab* symTab);
/// Writes to console the names in the current symtab (one a single line)
void Nest_dumpSymTabNames(Nest_SymTab* symTab);
/// Writes to console the hierarchy of the given symbol table
void Nest_dumpSymTabHierarchy(Nest_SymTab* symTab);
#ifdef __cplusplus
}
#endif
|
C | //Maximum intervals overlap
#include <stdio.h>
void insertionSort(int a[],int n){
for(int i=1;i<n;i++){
int j=i-1;
int key=a[i];
while(j>=0 && a[j]>key){
a[j+1]=a[j];
j=j-1;
}
a[j+1]=key;
}
}
void maxGuests(int a[],int e[],int n){
insertionSort(a,n);
insertionSort(e,n);
int guests=1;
int max=0;
int i=1,j=0;
int time=a[0];
while(i<n && j<n){
if(a[i]<=e[j]){
guests++;
if(guests>max){
max=guests;
time=a[i];
}
i++;
}else{
guests--;
j++;
}
}
printf("Maximum guests in the party is: %d at time %d",max,time);
}
int main(){
int a[]={1, 2, 9, 5, 5};//ariival time
int e[]={4, 5, 12, 9, 12};//exit time
int n=sizeof(a)/sizeof(a[0]);
maxGuests(a,e,n);
return 0;
}
|
C | #include <ctype.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <getopt.h>
#include "find_min_max.h"
#include "utils.h"
pid_t currentPID;
int ShowZombies(){
FILE *ls_proc;
ls_proc = popen("ps axo pid=,stat=", "r");
char buffer[12800];
while (fgets(buffer, sizeof(buffer)-1, ls_proc) != NULL){
printf("%s", buffer);
}
fclose(ls_proc);
return 0;
}
int MyKill(){
int result = kill(currentPID, SIGKILL);
if(result == 0)
printf("killed child process\n");
else
printf("error killing child process\n");
return result;
}
int MyKillTERM(){
int result = kill(currentPID, SIGTERM);
if(result == 0)
printf("killed child process (WITH TERM)\n");
else
printf("error killing child process (WITH TERM)\n");
return result;
}
int main(int argc, char **argv) {
int seed = -1;
int array_size = -1;
int pnum = -1;
bool with_files = false;
int timeout = -1;
//printf(argc);
while (true) {
int current_optind = optind ? optind : 1;
static struct option options[] = {{"seed", required_argument, 0, 0},
{"array_size", required_argument, 0, 0},
{"pnum", required_argument, 0, 0},
{"by_files", no_argument, 0, 'f'},
{"timeout", required_argument, 0, 't'},
{0, 0, 0, 0}};
int option_index = 0;
int c = getopt_long(argc, argv, "ft", options, &option_index);
if (c == -1) break;
switch (c) {
case 0:
switch (option_index) {
case 0:
seed = atoi(optarg);
if (seed <= 0) {
printf("seed must be a positive number\n");
return 1;
}
break;
case 1:
array_size = atoi(optarg);
if (array_size <= 0) {
printf("array_size must be a positive number\n");
return 1;
}
break;
case 2:
pnum = atoi(optarg);
if (pnum <= 0) {
printf("pnum must be a positive number\n");
return 1;
}
break;
case 3:
with_files = true;
break;
defalut:
printf("Index %d is out of options\n", option_index);
}
break;
case 'f':
with_files = true;
break;
case 't':
timeout = atoi(optarg);
if (pnum <= 0) {
printf("timeout must be a positive number\n");
return 1;
}
break;
case '?':
break;
default:
printf("getopt returned character code 0%o?\n", c);
}
}
if (optind < argc) {
printf("Has at least one no option argument\n");
return 1;
}
if (seed == -1 || array_size == -1 || pnum == -1) {
printf("Usage: %s --seed \"num\" --array_size \"num\" --pnum \"num\" \n",
argv[0]);
return 1;
}
int *array = malloc(sizeof(int) * array_size);
GenerateArray(array, array_size, seed);
printf("\nTIMEOUT = %d\n",timeout);
//print array
printf("\n\nARRAY:\n");
for(int i = 0; i < array_size; i++)
printf("%i ", array[i]);
printf("\n\n");
int active_child_processes = 0;
struct timeval start_time;
gettimeofday(&start_time, NULL);
//pipe
int pipefd[2];
pipe(pipefd);
int array_piece = array_size / pnum > 0 ? array_size / pnum : 1;
for (int i = 0; i < pnum; i++) {
pid_t child_pid = fork();
printf("%d", child_pid);
currentPID = child_pid;
if (child_pid >= 0) {
// successful fork
active_child_processes += 1;
if (child_pid == 0) {
// child process
;
struct MinMax min_max;
int begin = i * array_piece < array_size ? i * array_piece : array_size;
int end = (i + 1) * array_piece < array_size ? (i + 1) * array_piece : array_size;
if (begin == array_size) {
min_max = GetMinMax(array, 0, 1);
} else {
min_max = GetMinMax(array, begin, end);
}// parallel somehow
printf("\nPARENT PID: %d, THIS PID: %d, CHILD PID: %d # min: %i, max: %i\n---------------------------------\n", getppid(), getpid(), currentPID, min_max.min, min_max.max);
if (with_files) {
// use files here
FILE* fp = fopen("Out.txt", "a");
fwrite(&min_max, sizeof(struct MinMax), 1, fp);
fclose(fp);
} else {
// use pipe here
write(pipefd[1],&min_max,sizeof(struct MinMax));
}
return 0;
}
} else {
printf("Fork failed!\n");
return 1;
}
}
ShowZombies();
while (active_child_processes > 0) {
if(timeout != -1){
if (active_child_processes % 2 == 0)
signal(SIGALRM, MyKill);
else
signal(SIGALRM, MyKillTERM);
alarm(timeout);
sleep(5);
}
// your code here
close(pipefd[1]);
wait(NULL);
active_child_processes--;
}
struct MinMax min_max;
min_max.min = INT_MAX;
min_max.max = INT_MIN;
printf("//FROM ");
printf(with_files ? "FILE" : "PIPE");
for (int i = 0; i < pnum; i++) {
struct MinMax buff;
if (with_files) {
// read from files
FILE* fp = fopen("Out.txt", "rb");
// printf("\nBYTE FILE POS: %i, FILE POINTER: %p" COLOR _NC, i*sizeof(struct MinMax),*fp);
fseek(fp, i*sizeof(struct MinMax), SEEK_SET);
fread(&buff, sizeof(struct MinMax), 1, fp);
printf("\nPNUM #%i : min: %i max: %i",i+1,buff.min, buff.max);
fclose(fp);
} else {
// read from pipes
read(pipefd[0], &buff, sizeof(struct MinMax));
printf("\nPNUM #%i :min:%i max: %i",i+1,buff.min, buff.max);
}
if (buff.min < min_max.min) min_max.min = buff.min;
if (buff.max > min_max.max) min_max.max = buff.max;
}
struct timeval finish_time;
gettimeofday(&finish_time, NULL);
double elapsed_time = (finish_time.tv_sec - start_time.tv_sec) * 1000.0;
elapsed_time += (finish_time.tv_usec - start_time.tv_usec) / 1000.0;
free(array);
printf("\n\n\nRESULT");
printf("\nMin: %i\n", min_max.min);
printf("Max: %i\n", min_max.max);
printf("Elapsed time: %fms\n", elapsed_time);
fflush(NULL);
return 0;
}
|
C | /*
* An implementation of the ARC4 algorithm
*
* Copyright (C) 2001-2003 Christophe Devine
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "rc4.h"
void rc4_setup( struct rc4_state *s, unsigned char *key, int length )
{
int i, j, k, *m, a;
s->x = 0;
s->y = 0;
m = s->m;
for( i = 0; i < 256; i++ )
{
m[i] = i;
}
j = k = 0;
for( i = 0; i < 256; i++ )
{
a = m[i];
j = (unsigned char) ( j + a + key[k] );
m[i] = m[j]; m[j] = a;
if( ++k >= length ) k = 0;
}
}
void rc4_crypt( struct rc4_state *s, unsigned char *data, int length )
{
int i, x, y, *m, a, b;
x = s->x;
y = s->y;
m = s->m;
for( i = 0; i < length; i++ )
{
x = (unsigned char) ( x + 1 ); a = m[x];
y = (unsigned char) ( y + a );
m[x] = b = m[y];
m[y] = a;
data[i] ^= m[(unsigned char) ( a + b )];
}
s->x = x;
s->y = y;
}
#include <string.h>
#include <stdio.h>
/*
* ARC4 tests vectors from OpenSSL (crypto/rc4/rc4test.c)
*/
static unsigned char keys[7][30]={
{8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
{8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
{8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{4,0xef,0x01,0x23,0x45},
{8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef},
{4,0xef,0x01,0x23,0x45},
};
static unsigned char data_len[7]={8,8,8,20,28,10};
static unsigned char data[7][30]={
{0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff},
{0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0,
0x12,0x34,0x56,0x78,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff},
{0},
};
static unsigned char output[7][30]={
{0x75,0xb7,0x87,0x80,0x99,0xe0,0xc5,0x96,0x00},
{0x74,0x94,0xc2,0xe7,0x10,0x4b,0x08,0x79,0x00},
{0xde,0x18,0x89,0x41,0xa3,0x37,0x5d,0x3a,0x00},
{0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,
0xbd,0x61,0x5a,0x11,0x62,0xe1,0xc7,0xba,
0x36,0xb6,0x78,0x58,0x00},
{0x66,0xa0,0x94,0x9f,0x8a,0xf7,0xd6,0x89,
0x1f,0x7f,0x83,0x2b,0xa8,0x33,0xc0,0x0c,
0x89,0x2e,0xbe,0x30,0x14,0x3c,0xe2,0x87,
0x40,0x01,0x1e,0xcf,0x00},
{0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,0xbd,0x61,0x00},
{0},
};
int main( int argc, const char **argv )
{
int i, j;
struct rc4_state s;
unsigned char buffer[30];
int count = 200000;
if (argc == 2) count = atoi(argv[1]);
printf( "\n RC4 Validation Tests:\n\n" );
for( i = 0; i < 6; i++ )
{
printf( " Test %d ", i + 1 );
for( j = 0; j < count; j++ )
{
memcpy( buffer, data[i], data_len[i] );
rc4_setup( &s, &keys[i][1], keys[i][0] );
rc4_crypt( &s, buffer, data_len[i] );
}
if( memcmp( buffer, output[i], data_len[i] ) )
{
printf( "failed!\n" );
return( 1 );
}
printf( "passed.\n" );
}
printf( "\n" );
return( 0 );
}
|
C | /*
* channel.h
*
* Created on: May 30, 2021
* Author: jpaca
*/
#ifndef CHANNEL_H
#define CHANNEL_H
#include "main.h"
#include <stdint.h>
#include "board_defines.h"
typedef struct channel_t
{
GPIO_TypeDef * port;
uint16_t pin;
}channel_t;
// Function to convert loc to channel_t
// check loc and compare against pin defines in board_defines.h
// Assign appropriate port and pin
// Only need to do this for digital input and output pins
channel_t convert_loc_to_channel(uint32_t loc);
#endif /* CHANNEL_H */
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
char opr1[50],opr2[50];
struct stack
{
char data[1000];
struct listItem *next;
};
typedef struct stack STACK;
//create a new node
STACK *createStack()
{
STACK *create;
create = (STACK*)malloc(sizeof(STACK));
create->next=NULL;
return create;
}
//insertion at beginning
STACK *insert_at_beg(STACK *top,char str[])
{
STACK *makenode;
makenode = createStack();
strcpy(makenode->data,str);
if(top == NULL)
{
top=makenode;
}
else
{
makenode->next = top;
top = makenode;
}
return top;
}
STACK *push(STACK *top,char str[])
{
top = insert_at_beg(top,str);
return top;
}
STACK *pop(STACK *top,char res[])
{
if(top==NULL)
return;
else
{
STACK *temp = top;
top = top->next;
strcpy(res,temp->data);
free(temp);
return top;
}
}
void printStack(STACK *top)
{
STACK *temp=top;
while(temp!=NULL)
{
fputs(temp->data,stdout);
temp=temp->next;
}
}
int char_type(char c)
{
if(c == '+' || c == '' || c == '*' || c == '/')
return 1;
else
return 0;
}
void prefix_to_infix(char s1[])
{
STACK *top = NULL;
int i,len = strlen(s1);
for(i=len-1;i>=0;i--)
{
char temp2[6],temp1[2];
temp1[0]=s1[i];
switch(char_type(s1[i]))
{
case 0:
top = push(top,temp1);
break;
case 1:
top = pop(top,opr1);
top = pop(top,opr2);
temp2[0]='(';
strcat(temp2,opr1);
strcat(temp2,temp1);
strcat(temp2,opr2);
temp1[0]=')';
strcat(temp2,temp1);
top = push(top,temp2);
break;
}
}
printStack(top);
}
int main()
{
char prefix[100];
gets(prefix);
prefix_to_infix(prefix);
}
|
C | #include "BinTree.h"
#include <malloc.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "Queue.h"
BTNode* BinaryTreeFind(BTNode* pRoot, BTDataType x) {
if (pRoot == NULL)
return NULL;
if (pRoot->_data == x)
return pRoot;
BTNode* pTemp = NULL;
if (pTemp = BinaryTreeFind(pRoot->_pLeft, x))
return pTemp;
return BinaryTreeFind(pRoot->_pRight, x);
}
|
C | /*
* MyShell Project for SOFE 3950U / CSCI 3020U: Operating Systems
*
* Copyright (C) 2015, Albert Fung 100520898, Jason Runzer 100520992, Nicholas Gregorio 100514374
* All rights reserved.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include "utility.h"
#include "myshell.h"
#include <pwd.h>
#include <errno.h>
#include <dirent.h>
#include <termios.h>
#include <unistd.h>
// Put macros or constants here using #define
#define BUFFER_LEN 256
// Put global environment variables here
int userID;
char *userName;
char currentpath[BUFFER_LEN];
char oldPath[BUFFER_LEN];
char buffer[];
char command[BUFFER_LEN] = { 0 };
char arg[BUFFER_LEN] = { 0 };
int totalArguments = 0;
char **allArguments = NULL;
int n_spaces = 0;
// Define functions declared in myshell.h here
//tokenizes the arguments that the user inputs or a line from the file
void tokenize() {
//Reinitialize arg
totalArguments = 0;
// Perform string tokenization to get the command and argument
char* token = strtok(buffer, " \n");
while(token){
//allocate more room for the next command in the buffer
allArguments = realloc(allArguments,sizeof(char*) * ++totalArguments);
allArguments[totalArguments-1] = token; //add the argument to the array of arguments
token = strtok(NULL, " \n"); //get the next token
}
}
int main(int argc, char *argv[]) {
// Input buffer and and commands
//get the username of the current user
userName = getlogin();
//if executed in the terminal, the userName pointer will not be null
if (userName == NULL)
userName = "user";
//executed if there is a file name as a command line argument
if (argc > 1) {
//open the command file
FILE *fp;
FILE *output;
if ((fp = fopen(argv[1], "r")) == NULL) {
printf("Error, file not found");
exit(1);
}
//keep executing a command from the file until there are no commands left.
while (fgets(buffer,BUFFER_LEN,fp) != NULL) {
//tokenize the commands from the single line
tokenize();
execute_command(allArguments, totalArguments);
}
//Close files.
fclose(fp);
fclose(stdout);
exit(0);
}
//prints the username and path of the user
normal_display();
// Parse the commands provided using argc and argv
// Perform an infinite loop getting command input from users
while (fgets(buffer, BUFFER_LEN, stdin) != NULL) {
setenv("SHELL",
"/Desktop/git_project/OperatingSystem/OperatingSystems/myshell ",
1); //initalize SHELL environment variable
tokenize(); //tokenize the input from the user
execute_command(allArguments, totalArguments);
//display the username and the path
normal_display();
}
return EXIT_SUCCESS;
}
|
C | #include <stdio.h>
#include <math.h>
#include <conio.h>
#define true 1
#define false 0
#define err -2000123000
#define max 2147483646
typedef struct
{
double inet, vlc, oth, sms, mms, abr;
} user;
double stod1(char s[1000])
{
int i = 0, o = false;
double sm = 0;
if (s[0] == '-')
{
o = true;
i++;
}
if (s[0] == '\0' || s[0] == '\n')
return 0;
while (s[i] != '\0' && s[i] != '\n')
{
if (s[i] >= '0' && s[i] <= '9')
sm = sm * 10 + (s[i] - '0');
else
return err;
if (sm >= max / 100)
return err;
i++;
}
if (o == true)
return -1 * sm;
else
return sm;
}
void problem1()
{
FILE *fp = fopen("tarif.txt", "r");
int n, m, i, j,o,f;
char s[1000];
user u;
double a[20][12], b[20];
char name[20][1000];
if (fp != NULL)
printf("Succesfully loaded tariffs\n");
else
{
printf("error while loading tariffs\n");
return;
}
fscanf(fp, "%d%d", &n, &m);
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
fscanf(fp, "%lf", &a[i][j]);
fscanf(fp, "%s", name[i]);
}
fclose(fp);
f = false;
while (true)
{
printf("1. Enter data about user\n");
printf("2. Calculate optimal tariff for this user\n");
printf("3. Information about tariffs\n");
printf("4. Contact information of velcom company\n");
printf("5. Exit from the program\n");
o = getch();
if (o == '1')
{
printf("Enter please average amount per month of:\n");
printf("1. Internet using(MB): ");
scanf("%s", s);
u.inet = stod1(s);
if (u.inet < 0)
{
printf("error\n");
continue;
}
printf("2. Call time in VELCOM(Minutes): ");
scanf("%s", s);
u.vlc = stod1(s);
if (u.vlc < 0)
{
printf("error\n");
continue;
}
printf("3. Call time in other networks(Minutes): ");
scanf("%s", s);
u.oth = stod1(s);
if (u.oth < 0)
{
printf("error\n");
continue;
}
printf("4. Amount of SMS: ");
scanf("%s", s);
u.sms = stod1(s);
if (u.sms < 0)
{
printf("error\n");
continue;
}
printf("5. MMS count: ");
scanf("%s", s);
u.mms = stod1(s);
if (u.mms < 0)
{
printf("error\n");
continue;
}
printf("6.Call time to other countries(Minutes): ");
scanf("%s", s);
u.abr = stod1(s);
if (u.abr < 0)
{
printf("error\n");
continue;
}
f = true;
printf("User profile has been succesfully changed \n");
}
else if (o == '2')
{
if (f == false)
printf("There is no data about user\n");
else
{
int pz[20];
for (i = 0; i < n; i++)
{
b[i] = a[i][6];
if (a[i][0] != -1 && u.inet > a[i][0])
b[i] += (u.inet - a[i][0]) * a[i][1];
if (a[i][4] != -1 && u.sms > a[i][4])
b[i] += (u.sms - a[i][4]) * a[i][9];
if (a[i][5] != -1 && u.mms > a[i][5])
b[i] += (u.mms - a[i][5]) * a[i][10];
if (a[i][2] != -1 && u.vlc > a[i][2])
b[i] += (u.vlc - a[i][2]) * a[i][7];
if (a[i][3] != -1 && u.oth > a[i][3])
b[i] += (u.oth - a[i][3]) * a[i][8];
b[i] += u.abr * a[i][11];
}
for (i = 0; i < n; i++)
pz[i] = i;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (b[pz[i]] < b[pz[j]])
{
int x = pz[i];
pz[i] = pz[j];
pz[j] = x;
}
for (i = 0; i < n; i++)
printf("tariff %s will cost %lf rubles\n\n", name[pz[i]], b[pz[i]]);
}
}
else if (o == '3')
{
for (i = 0; i < n; i++)
{
printf("************\n%d. Tariff name: %s\n", i, name[i]);
if (a[i][0] == -1)
printf("Unlimited internet\n");
else
printf("Internet(MB): %lf\n", a[i][0]);
printf("Cost of 1 over used MB: %lf\n", a[i][1]);
if (a[i][2] == -1)
printf("Unlimited minutes within Velcome\n");
else
printf("Minutes within velcome: %lf\n", a[i][2]);
if (a[i][3] == -1)
printf("Unlimited minutes to other networks\n");
else
printf("Minutes to other networks: %lf\n", a[i][3]);
if (a[i][4] == -1)
printf("Unlimited SMS\n");
else
printf("SMS count: %lf\n", a[i][4]);
if (a[i][5] == -1)
printf("Unlimited MMS\n");
else
printf("MMS count: %lf\n", a[i][5]);
printf("Subscription fee: %lf\n", a[i][6]);
printf("Cost of 1 minute overused within Velcome: %lf\n", a[i][7]);
printf("Cost of 1 minute overused to other networks: %lf\n", a[i][8]);
printf("Cost of 1 SMS over limit : %lf\n", a[i][9]);
printf("Cost of 1 MMS over limit : %lf\n", a[i][10]);
printf("Cost of 1 call minute to other country: %lf\n", a[i][11]);
}
printf("\n^ ^ ^ ^ ^\n");
printf("| | | | |\n");
printf("Information about all Velcome tariffs\n");
}
else if (o == '4')
{
printf("tariffs: https://www.a1.by/ru/plans/c/b2ctariffs\n");
printf("150 - number of contact center(for free in Belarus)\n");
printf("71000 (0.03 ruble)\n");
printf("+375 29 6 000 150 (cost depends on roaming)\n");
printf("email address [email protected]\n");
printf("more contact information: https://www.a1.by/ru/company/mobile-services-contacts\n");
printf("web site: http://www.velcom.by/\n");
}
else if (o == '5')
break;
else
printf("Wrong operation\n");
printf("\n------------------\n");
}
printf("Do novyh vstrech");
}
|
C | #include "holberton.h"
/**
* cant_read - prints error message upon failure to read
* @str: filename
* Return: void
*/
void cant_read(char *str)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", str);
exit(98);
}
/**
* cant_write - prints error message when n fails to create or to write to file
* @str: name of file
* Return: void
*/
void cant_write(char *str)
{
dprintf(STDERR_FILENO, "Error: Can't write to %s\n", str);
exit(99);
}
/**
* cant_close_fd - prints error message upon failure to close descriptor
* @fdv: file descriptor value
* Return: void
*/
void cant_close_fd(int fdv)
{
dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", fdv);
exit(100);
}
/**
* main - copies the content of a file to another file
* @argc: number of arguments
* @argv: arguments
* Return: 0 upon success
*/
int main(int argc, char **argv)
{
int fdfrom, fdto, bytes_read, bytes_written;
char buf[1024];
if (argc != 3)
{
dprintf(STDERR_FILENO, "Usage: cp file_from file_to\n");
exit(97);
}
fdfrom = open(argv[1], O_RDONLY);
if (fdfrom == -1)
cant_read(argv[1]);
fdto = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fdto == -1)
{
cant_write(argv[2]);
}
bytes_read = 1024;
while (bytes_read == 1024)
{
bytes_read = read(fdfrom, buf, 1024);
if (bytes_read == -1)
cant_read(argv[1]);
bytes_written = write(fdto, buf, bytes_read);
if (bytes_written != bytes_read)
cant_write(argv[2]);
}
if (close(fdto) == -1)
cant_close_fd(fdto);
if (close(fdfrom) == -1)
cant_close_fd(fdfrom);
return (0);
}
|
C | /* ========================================
*
* Nicholas Jannuzzi
* CMPE121 Spring 2016
*
*
* Lab Exercise 1, part 1B: PWM control of LED
*
*
* ========================================
*/
#include "project.h"
#define Pot_Min 1
#define Pot_Max 65535
int32 reading;
int main(void)
{
//initialize modules
PWM_1_Start();
//start ADC and start conversions
ADC_DelSig_1_Start();
ADC_DelSig_1_StartConvert();
//main program loop
for(;;)
{
//get reading via read function, using a 32 bit integer so we don't lose half our values
reading = ADC_DelSig_1_GetResult32();
//saturation for values above and below the min and max values
if(reading <= Pot_Min)
{
reading = Pot_Min;
}
if(reading >= Pot_Max)
{
reading = Pot_Max;
}
//reading = reading * PWM_MAX/Pot_Max;
//write using pwm module
PWM_1_WriteCompare(reading);
}
}
/* [] END OF FILE */
|
C | /*
** main.c for lo in /home/munoz_d/CPE_2015_BSQ/src
**
** Made by Munoz David
** Login <[email protected]>
**
** Started on Sun Dec 20 21:38:17 2015 Munoz David
** Last update Sun Dec 20 22:38:28 2015 Munoz David
*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include "../include/my_bsq.h"
#include "../include/my.h"
int main(int ac, char **av)
{
char **deriv_tab;
int **primitive_tab;
int file;
char *str;
int nblev;
if (arg_check(ac) == -1)
return (0);
file = open(av[1], O_RDONLY);
str = line(file);
if (gnl_check(str) == -1)
return (0);
nblev = gnl_check(str);
deriv_tab = init_deriv_tab(file, nblev);
primitive_tab = init_primi_tab(deriv_tab);
parse_int_tab(deriv_tab, primitive_tab);
free(str);
free_primi_tab(deriv_tab, primitive_tab);
free_deriv_tab(deriv_tab);
close(file);
return (0);
}
char **init_deriv_tab(int file, int nbl)
{
char **tab;
int i;
char *str;
i = 0;
if (nbl == 0)
return (0);
tab = malloc(sizeof(char *) * (nbl + 1));
if (tab == NULL)
return (0);
while (str = line(file))
tab[i++] = str;
tab[i] = NULL;
free(str);
return (tab);
}
void print_deriv_tab(char **tab)
{
int i;
i = 0;
while (tab[i] != '\0')
{
my_putstr(tab[i]);
my_putchar('\n');
i++;
}
}
|
C | #include<stdio.h>
int main()
{
char s[20];
gets(s);
int i=0,l=0;
while(s[i]!='\0')
{
l++;
i++;
}
printf("%d",l);
return 0;
}
|
C | // Benchmark latency of various methods to learn the CPU ID.
//
// CPUID gives the initial APIC ID
// RDTSCP gives the "processor ID"
// RDPID is the same as RDTSCP but doesn't give the clock
//
// RDPID not available in Haswell
#include <stddef.h>
#include <stdio.h>
#include <inttypes.h>
#include <stdbool.h>
#include <assert.h>
#include <sys/mman.h>
#define always_inline \
__attribute__((always_inline))
typedef unsigned long ul;
static always_inline
uint64_t rdtscp(void)
{
uint64_t rax = 0, rdx = 0;
__asm__ __volatile__ ("rdtscp"
: "=a" (rax), "=d" (rdx)
: : "memory");
return ((rdx << 32) | rax);
}
// extract just the ID; not used for timing
static always_inline
uint64_t rdtscp_id(void)
{
uint64_t rax = 0, rcx = 0, rdx = 0;
__asm__ __volatile__ ("rdtscp"
: "=a" (rax), "=d" (rdx), "=c"(rcx)
: : "memory");
return rcx; // processor ID
}
static always_inline
uint64_t cpuid(void)
{
unsigned int leaf = 0;
unsigned int subleaf = 0;
unsigned int eax=1, ebx=0, ecx=0, edx=0;
__asm__ __volatile__ ("cpuid"
: "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
: "a"(leaf), "b"(0), "c"(subleaf), "d"(0)
:
"memory");
return (ebx >> 24) & 0xff; // inital APIC ID
}
void bench() {
const int iters = 1<<22;
ul now = rdtscp();
for (int i = 0; i < iters; i++)
__asm__ __volatile__ ("nop":::"memory");
ul end = rdtscp();
ul loop_cycles = (end-now);
now = rdtscp();
for (int i = 0; i < iters; i++)
(void)cpuid();
end = rdtscp();
ul cpuid_cycles = (end-now);
now = rdtscp();
for (int i = 0; i < iters; i++)
rdtscp_id();
end = rdtscp();
ul rdtscp_cycles = (end-now);
asm volatile ("sfence");
printf(" cpuid: %.2f\n",
(float)(cpuid_cycles-loop_cycles) / (float)iters);
printf(" rdtscp: %.2f\n",
(float)(rdtscp_cycles-loop_cycles) / (float)iters);
}
int main() {
bench();
}
|
C | void print_buffer(CSV_BUFFER *buffer)
{
int i, j;
printf("\n");
for (i = 0; i < buffer->rows; i++) {
for (j = 0; j < buffer->width[i]; j++) {
printf("%c%s%c%c", buffer->text_delim, buffer->field[i][j]->text, buffer->text_delim, buffer->field_delim);
}
printf("\n");
}
printf("\n\n");
}
|
C | #include<stdio.h>
#include<string.h>
int main()
{
char s[1000] ;
int i ;
gets(s) ;
if(strlen(s)>80){
printf("lenth is gretter then 80\n") ;
}
for(i=0 ;i<strlen(s);i++){
if(i%10==0){
printf("\n") ;
}
printf("%c",s[i]) ;
}
return 0 ;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "instructions.h"
// обход дерева,
// включение, исключение и поиск узлов,
void instruction_bst()
{
blue();
printf("\n\t\t\t\t\t\t\t\t\t\tМеню:\n\
\t\t\t\t\t\t\t▍▹ 1. %-30s\n\
\t\t\t\t\t\t\t▍▸ 2. %-30s\n\
\t\t\t\t\t\t\t▍▹ 3. %-30s\n\
\t\t\t\t\t\t\t▍▸ 4. %-30s\n\
\t\t\t\t\t\t\t▍▹ 5. %-30s\n\
\t\t\t\t\t\t\t▍▸ 0. %-30s\n",
"Вывести дерево",
"Добавить эелемент",
"Удалить элемент",
"Найти элемент",
"Заполнить (Из файла)",
"Выход");
green();
printf("\t\t\t\t\t\t\t\t\tВыберите действие: ");
white();
}
void instruction_hash()
{
blue();
printf("\n\t\t\t\t\t\t\t\t\t\tМеню:\n\
\t\t\t\t\t\t\t▍▹ 1. %-30s\n\
\t\t\t\t\t\t\t▍▸ 2. %-30s\n\
\t\t\t\t\t\t\t▍▹ 3. %-30s\n\
\t\t\t\t\t\t\t▍▸ 4. %-30s\n\
\t\t\t\t\t\t\t▍▹ 5. %-30s\n\
\t\t\t\t\t\t\t▍▸ 0. %-30s\n",
"Вывод",
"Добавить эелемент",
"Удалить элемент",
"Найти элемент",
"Заполнить (Из файла)",
"Выход");
green();
printf("\t\t\t\t\t\t\t\t\tВыберите действие: ");
white();
}
int instruction()
{
blue();
printf("\n\t\t\t\t\t\t\t\t\t\tМеню:\n\
\t\t\t\t\t\t\t▍▸ 1. %-30s\n\
\t\t\t\t\t\t\t▍▹ 2. %-30s\n\
\t\t\t\t\t\t\t▍▸ 3. %-30s\n\
\t\t\t\t\t\t\t▍▹ 4. %-30s\n\
\t\t\t\t\t\t\t▍▸ 5. %-30s\n\
\t\t\t\t\t\t\t▍▹ 6. %-30s\n\
\t\t\t\t\t\t\t▍▸ 7. %-30s\n\
\t\t\t\t\t\t\t▍▹ 0. %-30s\n",
"Вывод хеш-таблицы",
"Вывод дерева",
"Добавить элемент",
"Найти элемент",
"Заполнить (Из файла)",
"Сбалансировать дерево",
"Вывод АВЛ - дерева",
"Выход");
green();
printf("\t\t\t\t\t\t\t\t\tВыберите действие: ");
white();
}
int scanf_answer()
{
char answer_char[MAX_LEN_ANSWER];
scanf("%s", answer_char);
int answer = atoi(answer_char);
while (!answer)
{
if (strcmp(answer_char, "0") == 0)
break;
red();
printf("\n\t\t\t\t\t\t\t\t\tВаш ответ мне не понятен.");
green();
printf("\n\t\t\t\t\t\t\t\t\tВыберите действие:");
white();
scanf("%s", answer_char);
answer = atoi(answer_char);
}
white();
return answer;
} |
C | #include "geometry.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/* Construit le point x y z */
Point3D pointXYZ(float x, float y, float z) {
Point3D tmp;
tmp.x = x;
tmp.y = y;
tmp.z = z;
return tmp;
}
/* Construit le vecteur x y z */
Vector3D vectorXYZ(float x, float y, float z) {
Vector3D tmp;
tmp.x = x;
tmp.y = y;
tmp.z = z;
return tmp;
}
/* Construit le vecteur AB = B-A */
Vector3D vector(Point3D A, Point3D B) {
float x, y, z;
x = A.x - B.x;
y = A.y - B.y;
z = A.z - B.z;
return vectorXYZ(x, y, z);
}
/* Construit le point P + V */
Point3D pointPlusVector(Point3D P, Vector3D V) {
float x, y, z;
x = P.x + V.x;
y = P.y + V.y;
z = P.z + V.z;
return pointXYZ(x, y, z);
}
/* Addition de vecteurs */
Vector3D addVectors(Vector3D A, Vector3D B) {
float x, y, z;
x = A.x + B.x;
y = A.y + B.y;
z = A.z + B.z;
return vectorXYZ(x, y, z);
}
/* Soustraction de vecteurs */
Vector3D subVectors(Vector3D A, Vector3D B) {
float x, y, z;
x = A.x - B.x;
y = A.y - B.y;
z = A.z - B.z;
return vectorXYZ(x, y, z);
}
/* Multiplication de vecteurs */
Vector3D multVectors(Vector3D V, float a) {
float x, y, z;
x = V.x * a;
y = V.y * a;
z = V.z * a;
return vectorXYZ(x, y, z);
}
/* Multiplication de vecteurs */
Vector3D divVectors(Vector3D V, float a) {
if ( a == 0.0 ) {
printf("Division par 0 ...\n");
return vectorXYZ(0.0, 0.0, 0.0);
}
float x, y, z;
x = V.x / a;
y = V.y / a;
z = V.z / a;
return vectorXYZ(x, y, z);
}
/* Produit scalaire de deux vecteurs */
float dot(Vector3D A, Vector3D B) {
float x,y,z;
x = A.x*B.x;
y = A.y*B.y;
z = A.z*B.z;
/*printf("x:%f, y:%f, z:%f", x, y, z);*/
return x+y+z;
}
/* Norme d'un vecteur */
float norm(Vector3D V) {
float x,y,z;
x = V.x*V.x;
y = V.y*V.y;
z = V.z*V.z;
return sqrt(x+y+z);
}
/* Retourne le vecteur normalisé passé en parametre */
Vector3D normalize(Vector3D V) {
float n = norm(V);
if ( n == 0.0 ) {
printf("Vecteur nul\n");
return V;
}
V.x /= n;
V.y /= n;
V.z /= n;
return V;
} |
C | #include "gen_queue.h"
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
//appends an item to the end of the Queue.
//Queue does not take ownership of the item, must be allocated/deallocated elsewhere
int gen_append(struct gen_queue * Q, void * item) {
//lock critical area
pthread_mutex_lock(&Q->lock);
struct gen_queue_node* node = (struct gen_queue_node*) malloc(sizeof(struct gen_queue_node));
node->data = item;
node->next = NULL;
Q->number_of_nodes++;
//if this was the first node we added
if(Q->number_of_nodes == 1){
Q->head = node;
Q->tail = node;
} else {
Q->tail->next = node;
Q->tail = node;
}
pthread_cond_signal(&Q->pop_ready);
pthread_mutex_unlock(&Q->lock);
//no errors
return 0;
}
void* gen_pop(struct gen_queue * Q, int* waiterCount, bool* kill) {
pthread_mutex_lock(&Q->lock);
//only uses numw
while(gen_is_empty(Q)){
(*waiterCount)++;
pthread_cond_wait(&Q->pop_ready, &Q->lock);
//the kill command was send, we exit
if(*kill) {
//printf("kill command recieved\n");
//need to unlock before exit
pthread_mutex_unlock(&Q->lock);
return NULL;
}
(*waiterCount)--;
}
assert(Q->number_of_nodes != 0);
struct gen_queue_node* node = Q->head;
Q->number_of_nodes--;
//if that was the last node
if(Q->number_of_nodes == 0){
Q->head = NULL;
Q->tail = NULL;
} else {
Q->head = Q->head->next;
}
void * item = node->data;
free(node);
pthread_mutex_unlock(&Q->lock);
return item;
}
//creates a new gen_queue
struct gen_queue* gen_queue_init(){
struct gen_queue* Q = (struct gen_queue*)malloc(sizeof(struct gen_queue));
Q->head = NULL;
Q->tail = NULL;
Q->number_of_nodes = 0;
//TODO: do something with this
int ret = pthread_mutex_init(&Q->lock, NULL);
ret = ret || pthread_cond_init(&Q->pop_ready, NULL);
if(ret != 0) {
//something horrible has happened
printf("SOMETHING MUTEX FAILED TO INIT");
abort();
}
return Q;
}
//should be EMPTY by now
int gen_queue_destroy(struct gen_queue* Q){
assert(Q->number_of_nodes == 0);
//TODO: do this
//if these fail i really dont give a shit
pthread_mutex_destroy(&Q->lock);
pthread_cond_destroy(&Q->pop_ready);
free(Q);
return 0;
}
bool gen_is_empty(struct gen_queue* Q){
if(Q->number_of_nodes == 0) {
return true;
} else {
return false;
}
} |
C | #include <stdio.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
int
prepare_key(char *key)
{
char buffer[];
char Table = {A, B, C, D, E, F, G, H, I, J, K, L,
M, N, O, P, Q, R, S, T, U, V, W, X,
Y,Z};
toupper(*key);
for(i=0; i<strlen(key); i++) {
for(j=0; j<strlen(key);j++) {
if(strcmp(key[i],key[j]) == 0) {
key[j] = key[j+1];
}
}
}
for(i = 0; key[i] !=NULL; i++) {
for(int j=0; j < 26; j++) {
if( key[i] = Table[j]) {
Table[j] = Table[j+1];
}
}
}
strcat(key[i], Table[j])
return key[i];
}
/*
*
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define TRUE 1
#define FALSE 0
int
prepare_key(char *key)
{
register char *keyp;
register char *dup;
register int character;
if( *key == '\0')
return FALSE;
for(keyp = key; (character = *keyp) != '\0'; keyp++) {
if( !islower(character)) {
if(!isupper(character))
return FASLE;
*keyp = toupper(character);
}
for(keyp = key; (character = *keyp) != '\0'; ) {
dup == ++keyp;
while( (dup= strchr(dup, character)) != NULL)
strcpy(dup,dup+1);
}
for(character = 'a'; character <= 'z'; character ++) {
if(strchr(key, character) == NULL) {
*keyp++ = character;
*keyp = '\0';
}
}
return TRUE;
}
|
C | #include<stdio.h>
#include<stdlib.h>
void moveZeroes(int* nums,int size);
int main()
{
int nums[] = {3,0,0,84,12,0,1,0};
moveZeroes(nums,8);
for(int i=0;i < 8;i++)
printf("%d\t",nums[i]);
}
void moveZeroes(int* nums,int size) //[3,12,0,1,0]
{
int* temp = (int*)malloc(size*sizeof(int));
temp = calloc(size,sizeof(int));
for(int i = 0;i < size;i++)
temp[i] = nums[i];
int i = 0;
int j = size-1;
for(int k = 0;k < size;k++)
{
if(temp[k] == 0)
{
nums[j] = temp[k];
j--;
}
else
{
nums[i] = temp[k];
i++;
}
}
free(temp);
} |
C | #include<stdio.h>
#include<conio.h>
void main()
{
int year;
printf("Enter the year:");
scanf("%d",&year);
if(year%4==0&&year%100!=0||year%400==0)
printf("The year is leap year.\n");
else
printf("The year is not a leap year.\n");
getch();
}
|
C | //
// Created by sebastian on 10/11/2019.
//
#include <stdio.h>
#include <stdlib.h>.//me gusto mucho la interaccion
int main()
{
int n,m, max = -1,min=1000000;
printf("--------------------------\n");
printf("Valor M%cximo de la Matriz!\n",160);
printf("--------------------------\n");
printf("Ingrese las dimensiones de la matriz:\n");
scanf("%d %d",&n,&m);
int matriz[n][m];
printf("Vale! pues la matriz sera de %d FILAS y %d COLUMNAS\n",n,m);
printf("Ingrese los valores: \n");
for (int i=0; i < n; i++) {
for (int j=0; j< m; j++){
scanf("%d",&matriz[i][j]);
}
}
printf("Asi se ve tu matriz %d x %d: \n",n,m);
for (int i=0; i < n; i++) {
for (int j=0; j< m; j++){
printf("%d ",matriz[i][j]);
if (matriz[i][j] > max){ //recorre el elemento mayor
max = matriz[i][j];
}
if (matriz[i][j] < min){ //recorre el elemento menor
min = matriz[i][j];
}
}
printf("\n");
}
system("PAUSE");
printf("--------------------------------------------------------------------------\n");
printf("El valor minimo de esta matriz es %d y el mayor valor %d \n",min,max);
printf("---------------------------------------------------------------------------\n");
return 0;
}
|
C | /// Author: Terry Hsu
/// Test case for creating memdom domains
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <smv_lib.h>
#include <memdom_lib.h>
#include <pthread.h>
#define NUM_THREADS 10
#define NUM_MEMDOMS_PER_THREAD 100
// Thread stack for creating memdoms
void *fn(void *args){
int i = 0;
int memdom_id[NUM_MEMDOMS_PER_THREAD];
for (i = 0; i < NUM_MEMDOMS_PER_THREAD; i++) {
memdom_id[i] = memdom_create();
}
for (i = 0; i < NUM_MEMDOMS_PER_THREAD; i++) {
if (memdom_id[i] != -1) {
memdom_kill(memdom_id[i]);
}
}
return NULL;
}
int main(){
int i = 0;
int memdom_id[NUM_MEMDOMS_PER_THREAD];
pthread_t tid[NUM_THREADS];
smv_main_init(1);
for (i = 0; i < NUM_THREADS; i++) {
pthread_create(&tid[i], NULL, fn, NULL);
}
// main thread create memdoms
for (i = 0; i < NUM_MEMDOMS_PER_THREAD; i++) {
memdom_id[i] = memdom_create();
}
for (i = 0; i < NUM_MEMDOMS_PER_THREAD; i++) {
if (memdom_id[i] != -1) {
// memdom_kill(memdom_id[i]);
}
}
// wait for child threads
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(tid[i], NULL);
}
// Try delete a non-existing memdom
memdom_kill(12345);
return 0;
}
|
C | /*------------------------------------------------------------------------------
* 4190.308 Computer Architecture Spring 2020
*
* Bomb Lab
*
* Handout: May 6, 2020
* Due: May 20, 2020 11:00
*
* The binary bomb notifies the bomblab server automatically when you solve a
* phase. You can look at the current scoreboard at
* https://csap.snu.ac.kr/comparch/bomblab/scoreboard
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "support.h"
#include "phases.h"
FILE *infile;
int main(int argc, char *argv[])
{
char *input;
// When run with no arguments, the bomb reads its input lines from standard
// input.
if (argc == 1) infile = stdin;
// When run with one argument <file>, the bomb reads from <file> until EOF,
// and then switches to standard input. Thus, as you defuse each phase, you
// can add its defusing string to <file> and avoid having to retype it.
else if (argc == 2) {
if (!(infile = fopen(argv[1], "r"))) {
printf("%s: Error: Couldn't open %s\n", argv[0], argv[1]);
exit(8);
}
}
// You can't run the bomb with more than one command line argument.
else {
printf("Usage: %s [<input_file>]\n", argv[0]);
exit(8);
}
// Do all sorts of secret stuff that makes the bomb harder to defuse.
initialize_bomb();
printf("Welcome to my fiendish little bomb. You have 6 phases with\n");
printf("which to blow yourself up. Have a nice day!\n");
// first phase
input = read_line(); // get input
phase_1(input); // run the phase
phase_defused(); // phase_1 only comes back when defused
printf("Phase 1 defused. How about the next one?\n");
// second phase
input = read_line();
phase_2(input);
phase_defused();
printf("That's number 2. Keep going!\n");
// third phase
input = read_line();
phase_3(input);
phase_defused();
printf("Halfway there!\n");
// fourth phase
input = read_line();
phase_4(input);
phase_defused();
printf("So you got that one. Try this one.\n");
// fifth phase
input = read_line();
phase_5(input);
phase_defused();
printf("Good work! On to the next...\n");
// sixth phase
input = read_line();
phase_6(input);
phase_defused();
// is that really all?
return 0;
}
|
C | /*
* Copyright 2017, Crank Software Inc. All Rights Reserved.
*
* For more information email [email protected].
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h> // for usleep
#endif
#include <gre/greio.h>
#include "ClusterIO_events.h"
/**
* cross-platform sleep
*/
void
sleep_ms(int milliseconds) {
#ifdef WIN32
Sleep(milliseconds);
#else
usleep(milliseconds * 1000);
#endif
}
int
main(int argc, char **argv) {
gre_io_t *send_handle;
gre_io_serialized_data_t *nbuffer = NULL;
cluster_update_event_t event_data;
int ret;
// Connect to a channel to send messages (write)
send_handle = gre_io_open("cluster", GRE_IO_TYPE_WRONLY);
if (send_handle == NULL) {
fprintf(stderr, "Can't open send channel\n");
return 0;
}
memset(&event_data, 0, sizeof(event_data));
while(1) {
// Simulate data acquisition ...
sleep_ms(80);
event_data.speed = (event_data.speed + 1) % 200;
event_data.rpm = (event_data.rpm + 50) % 10000;
// Serialize the data to a buffer
nbuffer = gre_io_serialize(nbuffer, NULL, CLUSTER_UPDATE_EVENT, CLUSTER_UPDATE_FMT, &event_data, sizeof(event_data));
if (!nbuffer) {
fprintf(stderr, "Can't serialized data to buffer, exiting\n");
break;
}
// Send the serialized event buffer
ret = gre_io_send(send_handle, nbuffer);
if (ret < 0) {
fprintf(stderr, "Send failed, exiting\n");
break;
}
}
//Release the buffer memory, close the send handle
gre_io_free_buffer(nbuffer);
gre_io_close(send_handle);
return 0;
}
|
C | /*Joao Guilherme Araujo - 9725165 */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*-----------------Trie and its functions--------------------*/
//Trie data structure definition
struct Trie{
char ending; //1 if a terminating character of a word
struct Trie *node[26];
};
typedef struct Trie trie;
//Trie constructor
trie *create(){
trie *ret = calloc(1, sizeof(trie));
return ret;
}
//Trie destructor
void destroy(trie *t){
for(int i = 0; i < 26; ++i)
if((t->node)[i] != NULL)
destroy((t->node)[i]);
free(t);
}
//Insert word in Trie
void insert(trie *dict, char *word){
int pos = (word[0] <= 'Z')?(word[0] - 'A'):(word[0] - 'a');
if((dict->node)[pos] == NULL) (dict->node)[pos] = create();
if(word[1] == '\0') (dict->node)[pos]->ending = 1;
else insert((dict->node)[pos], word + 1);
}
//Searches word in Trie
//Returns 1 if found, 0 otherwise
int search(trie *dict, char *word){
int pos = (word[0] <= 'Z')?(word[0] - 'A'):(word[0] - 'a');
if((dict->node)[pos] == NULL) return 0;
if(word[1] == '\0') return (dict->node)[pos]->ending;
return search((dict->node)[pos], word + 1);
}
/*-----------------Auxiliar function--------------------*/
//Removes non alphabetic characters from word
void clean_word(char **word){
for(int i = 0; (*word)[i] != '\0'; ++i){
if(!isalpha((*word)[i])){
(*word)[i] = '\0';
break;
}
}
}
/*------------Dictionary and Json processing------------*/
//Loads Dictionary to trie
void load_dict(trie *dict, FILE *in){
char *word, *token;
word = calloc(128, sizeof(char));
char delimeters[64] = " _(),!#\'-\".@?&“0123456789"; //delimeters for strtok
while(fscanf(in, "%s", word) != EOF){ //reads each word of dictionary
token = strtok(word, delimeters); //breaks compoud words
while (token != NULL){
clean_word(&token);
if(isalpha(token[0]))
insert(dict, token);
token = strtok(NULL, delimeters);
}
}
free(word);
}
void correct_tweets(trie *dict, FILE *in){
size_t size = 0;
int has_tweets = 0;
char *line, *pos, *word;
char needle[16] = "text\":"; //tag to search
char delimeters[64] = " _(),!#\'-\".@?&“0123456789"; //delimeters for strtok
while(getline(&line, &size, in) != -1){ //reads all the json's lines
pos = strstr(line, needle);
if(pos != NULL){ //if the text tag was found
has_tweets = 1;
pos += 8; //jumps to beggining of tweet
word = strtok(pos, delimeters); //breaks line in constituent words
while(word != NULL){
clean_word(&word);
if(isalpha(word[0]) && search(dict, word) == 0) //if it's a word and it's not in the dictionary
printf("%s ", word); //print it
word = strtok(NULL, delimeters);
}
printf("\n");
}
}
if(!has_tweets) printf("No tweets to check\n");
if(line != NULL) free(line);
}
int main(){
trie *dict;
char aux[32];
scanf("%s", aux);
FILE *in;
dict = create();
in = fopen(aux, "r");
load_dict(dict, in);
fclose(in);
scanf("%s", aux);
in = fopen(aux, "r");
correct_tweets(dict, in);
fclose(in);
destroy(dict);
return 0;
}
|
C | #include <stdio.h>
struct node
{
int burst_time;
int wait_time;
int turn_around_time;
int exec_time_left;
};
int main(int argc, char const *argv[])
{
int n, i, j, slice, update;
struct node process_list[10];
printf("Enter number of processes[max 10]: ");
scanf("%d", &n);
printf("Enter time slice: ");
scanf("%d", &slice);
// Collect burst time
printf("Enter burst time: ");
for(i=0; i<n; i++)
{
printf("Process %d: ", i+1);
scanf("%d", &process_list[i].burst_time);
process_list[i].exec_time_left = process_list[i].burst_time;
process_list[i].wait_time = 0;
}
// Burst time
int total_burst_time = 0, counter_burst_time = 0;
for( i = 0; i < n; i++)
total_burst_time += process_list[i].burst_time;
i=-1;
int counter = 0;
while(total_burst_time > counter_burst_time)
{
i = (i+1) % n;
if(process_list[i].exec_time_left < 1)
continue;
else if(process_list[i].exec_time_left <= slice)
{
// Process ends here
for(j = 0; j < n; j++)
{
// Add current execution time to waiting time of other processes that has not completed execution
if(process_list[j].exec_time_left < 1 || i==j)
continue;
else
{
process_list[j].wait_time += process_list[i].exec_time_left;
}
}
// Set the turn around time, increase counter
process_list[i].turn_around_time = process_list[i].wait_time + process_list[i].burst_time;
counter_burst_time += process_list[i].exec_time_left;
process_list[i].exec_time_left = 0;
}
else
{
// Process executes for time slice and then continues
for(j = 0; j < n; j++)
{
// Add current execution time to waiting time of other processes that has not completed execution
if(process_list[j].exec_time_left < 1 || i==j)
continue;
else
process_list[j].wait_time += slice;
}
// Reduce execution time left, increase counter
process_list[i].exec_time_left -= slice;
counter_burst_time += slice;
}
}
printf("\nProcess\t\tBurst time\tWaiting time\t\tTurnaround Time");
for(i=0;i<n;i++)
{
printf("\n%d \t\t%d \t\t%d \t\t\t%d", i + 1, process_list[i].burst_time, process_list[i].wait_time, process_list[i].turn_around_time);
}
return 0;
} |
C | //Newton-Raphson Root Finding Method
//Algorithm:
//xi+1 = xi - f(xi)/f'(xi)
//Example: find the roots of f(x) = 2x2 -x -21
//% cat newt3.cpp
// Newton-Raphson method for finding the
// roots of f(x) = 0 for a polynomial function
#include <iostream>
using namespace std;
#include <cmath>
double newton(double a, double b, double c, double x0, double crit);
int main()
{
double a, b, c, root, guess, conv_crit;
cout << "Enter values for a, b, and c :";
cin >> a >> b >> c;
cout << "Enter a guess for the root :";
cin >> guess;
cout << "Enter the convergence criterion: ";
cin >> conv_crit;
// call function newton
root = newton(a, b, c, guess, conv_crit);
// display result
cout.setf(ios::fixed | ios::showpoint);
cout.precision(4);
cout << "One root is " << root << endl;
return 0;
}
double newton(double a, double b, double c, double x0, double crit)
{
double x1, delta;
int iters = 0;
// use a do-while loop
do
{
x1 = x0 - (a*x0*x0 + b*x0 + c) / ( 2*a*x0 + b);
delta = fabs ( x1 - x0 );
x0 = x1; // new approximation becomes the old
// approximation for the next iteration
iters++; // count the number of iterations
} while (delta > crit && iters <= 30);
cout << iters << " iterations" << endl;
return x1;
}
//% a.out
//Enter values for a, b, and c :2 -1 -21
//Enter a guess for the root :10
//Enter the convergence criterion: .0001
//5 iterations
//One root is 3.5000
//% a.out
//Enter values for a, b, and c :2 -1 -21
//Enter a guess for the root :-9
//Enter the convergence criterion: .0001
//5 iterations
//One root is -3.0000
|
C | #include<stdio.h>
int main()
{
int n=10,arr[n];
int max=0,s,i,j,z;
for (i=0;i<10;i++)
scanf("%d",&arr[i]);
i=0;
for (j=0;j<10;j++)
{
z=arr[i];
if (z<0)
max=i;
i++;
}
i=0;
for (j=0;j<10;j++)
{
z=arr[i];
if (z<0&&z>arr[max])
max=i;
i++;
}
if (max!=0||arr[max]<0){
s=arr[9];
arr[9]=arr[max];
arr[max]=s;
}
for (i=0;i<10;i++)
printf("%d ",arr[i]);
return 0;
}
|
C | #include <stdlib.h>
#include<stdio.h>
struct node{
int data;
struct node* next;
};
struct node* top=NULL;
void push(int key){
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=key;
newnode->next=NULL;
if (newnode==NULL){
printf("stack overflow");
}else{
if(top!=NULL){
newnode->next=top;
}top=newnode;
}
}
int pop(){
struct node* temp;
int x=-1;
if(top==NULL){
printf("stack underflow");
}else{
x=top->data;
temp=top;
top=top->next;
free(temp);
temp=NULL;
}return x;
}
void display(){
struct node* temp=top;
while (temp!=NULL)
{
printf("%d", temp->data);
printf("\n");
temp=temp->next;
}
}
int isFull(){
struct node* newnode=(struct node*)malloc(sizeof(struct node));
if (newnode==NULL){
return 1;
}return 0;
}
int isEmpty(){
if (top==NULL){
return 1;
}return 0;
}
int stackTop(){
if (top==NULL){
return -1;
}return top->data;
}
int peek(int pos){
struct node* temp=top;
for(int i=0;i<pos-1 && temp;i++){
temp=temp->next;
}return temp->data;
}
void main(){
push(4);
push(3);
push(6);
push(8);
push(5);
display();
// pop();
// pop();
// pop();
// pop();
printf("\n");
printf("%d", peek(4));
// display();
} |
C |
/**
Code file for hash tables.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "storer.h"
#include "eprintf.h"
static State *linked_lookup(char *prefix[], int create, PrefixStorer* ps);
static void linked_add(char *prefix[], char *word, PrefixStorer* ps);
static void print(PrefixStorer* ps);
static void cleanup(PrefixStorer* ps);
/**
Called to create a new linked list.
*/
PrefixStorer* makeLinkedPrefixStorer(){
/*
Malloc a new PrefixStorer
*/
PrefixStorer* p = emalloc(sizeof(PrefixStorer));
/*
Set which functions it will contain
*/
p->lookup = &linked_lookup;
p->add = &linked_add;
p->print = &print;
p->cleanup = &cleanup;
/*
Initialize p to NULL because the linked list initially contains nothing.
*/
p->tableBase = NULL;
return p;
}
/**
Called to delete the contents of this PrefixStorer.
*/
static void cleanup(PrefixStorer* ps){
State *statehead = (State*) (ps->tableBase);
while(statehead != NULL){
State* current = statehead;
statehead = statehead->next;
cleanupState(current);
free(current);
}
}
/**
Prints the contents of the PrefixStorer out to standard out.
*/
static void print(PrefixStorer* ps){
State* sp;
int i;
State *statehead = (State*) (ps->tableBase);
assert(statehead != NULL);
for (sp = statehead; sp != NULL; sp = sp->next) {
printf("Tuple: ");
for (i = 0; i < NPREF; i++){
printf("<%s>", sp->pref[i]);
}
printf("\n");
}
}
/* lookup: search for prefix; create if requested. */
/* returns pointer if present or created; NULL if not. */
/* creation doesn't strdup so strings mustn't change later. */
static State* linked_lookup(char *prefix[NPREF], int create, PrefixStorer* ps)
{
int i;
State *sp;
State *statehead = (State*) (ps->tableBase);
for (sp = statehead; sp != NULL; sp = sp->next) {
for (i = 0; i < NPREF; i++)
if (strcmp(prefix[i], sp->pref[i]) != 0)
break;
if (i == NPREF) /* found it */
return sp;
}
if (create) {
sp = (State *) emalloc(sizeof(State));
for (i = 0; i < NPREF; i++)
sp->pref[i] = prefix[i];
sp->suf = NULL;
sp->next = statehead;
ps->tableBase = sp;
}
return sp;
}
/* add: add word to suffix list, update prefix */
static void linked_add(char *prefix[NPREF], char *suffix, PrefixStorer* ps)
{
State *sp;
sp = (ps->lookup)(prefix, 1, ps); /* create if not found */
addsuffix(sp, suffix);
/* move the words down the prefix */
memmove(prefix, prefix+1, (NPREF-1)*sizeof(prefix[0]));
prefix[NPREF-1] = suffix;
}
|
C | /*
* I2C ͨѶЭʵ飨2016-5-13 5 17:35 PM)
I2C 鷳ĵطʱ⣬ǰǽӴ Uart ЭͲе 1602 ҺI2C ǰЭ鶼ҪЩֱʾĻͼ£
SCL ----__--__--__--__--__--__--__--__--__--__----
SDA --_S_/7 \/6 \/5 \/4 \/3 \/2 \/1 \/0 \/a \_T_--
ܽһ I2C ͨѶ
1. SCL Ϊʱźţʱӵزͷͣ SCL Ϊߵƽʱȶ
2. ʼλֹͣλͼе S Tͼ S T λöӦΪ ͵ƽʼλ SCL SDA Ϊ ߵƽʱ SDA һʱʾݴĿʼ֮෴ SCL SDA Ϊ͵ƽʱ SCL һʱ SDA ʾݽ
3. ֡ Uart ͬǣI2C ϵÿһ֡ݲ һʼλ + 8 λλ + ack λ + λI2C λҲ˵һ֡ݿ һʼλ + 8 λ + ack λ + 8 λ + ack + ... + 8 λ + ack + λ
4. SDA ΪλΪ ack λĴڣSDA ݽӿӦΪ˫ IO
5. ack Ӧλܵ I2C ͵ݺ ack λһݣڱе AT24C02 ӦλΪ 0
I2C ͨѶʱƵʣ
I2C һֵٵͨѶЭ飬Ϊͨٺ٣ƵʷֱΪ 100K400K3.4M24C02 ֲ˵ 2.52.75V ĵѹ£Ϊ 400K Ƶûбд
ҰϵĵƬΪ STC89C52RCΪ 11.0592 MHzԼƵΪ
11.0592 * 10^6/12 = 921600 1000000 = 1000 KHz
ɴ˿ɼƬ I2C ҪٶȿһЩҪֶʱ1000/400 = 2.5, 1000/100 = 10, Ϊ˼ѡģʽ
Ƭļʱ
intrins.h ļṩһ _nop_() ûתһڣѡģʽһʱʱҪ 3 _nop()Ҫ 2 _nop_() Ϊʹ 4 _nop_() ʱ SCL ʱڡ
ȻʱͼҪõʱΪ˼ſлIJͼ(S T ӦΪ ͵ƽ
SCL ----__--__--__--__--__--__--__--__--__--__----
SDA --SS<7-><6-><5-><4-><3-><2-><1-><0-><ac>TTTT--
--------1---2---3---4---5---6---7---8---9---A-----
õ˲ I2C źẉ̂
1. ʼλ SDA SClʱ SDK ʱͼ 1 λ
2. λȸ SDA ֵȻ SCLʱ SCLʱ 2 λ
3. ظڶ 9 λ
4. ACK λ SDA(ڽź)ʱ SCLȡ ackʱ SCLͼ A λ
5. λ SCL SDAʱ SCLʱ SDAʱ
I2C ͨѶʱڲ ƽ˳Ҫһ SCL δ֪Ϊߵƽʱ仯 SDA ֵܻͷûǣĵʱڵƬָٶȱȽûмλñ仯Ͳǿеģʹõ CPLD FPGA ߸ٵ CPU ǵİʵʱмʱ̱仯Ͳ
ʵĿģ
ͨ I2C Э EEPROMͺΪ AT24C02)I2C һַַڶӦô ack Ӧ 0͵ LedͲ Led Сơ
ֲᣬAT24C02 ĵַΪ 8'b1010_(A2)(A1)(A0)(R/W)дԷ͵Ϊ 8'b1010_0000 Ƿ͵Ϊ 0xA0
ʵ
Ƿ 0xA0 ʱӦһ ACK(0)ǵ LED0
ʵлҪһڵĵַ 0xB0Ӧ ACK Ϊ 1Ϩ LED1
**/
#include <reg52.h>
#include <intrins.h>
#define delay() { _nop_(); _nop_(); _nop_(); _nop_(); }
sbit I2C_SCL = P3^7;
sbit I2C_SDA = P3^6;
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
sbit Led0 = P0^0;
sbit Led1 = P0^1;
unsigned char ack = 1;
void led_init(void);
void i2c_start(void);
void i2c_data(unsigned char sent_data);
void i2c_stop(void);
void main()
{
led_init();
i2c_start();
i2c_data(0xA0);
if(ack==0)
Led0 = 0;
else
Led0 = 1;
i2c_stop();
i2c_start();
i2c_data(0xB0);
if(ack==0)
Led1 = 0;
else
Led1 = 1;
i2c_stop();
while (1);
}
void led_init(void){
ADDR0 = 0;
ADDR1 = 1;
ADDR2 = 1;
ADDR3 = 1;
ENLED = 0;
}
void i2c_start(void){
I2C_SDA = 1;
I2C_SCL = 1;
delay();
I2C_SDA = 0;
delay();
I2C_SCL = 0;
}
void i2c_data(unsigned char sent_data) {
unsigned char mask;
for(mask = 0x80; mask != 0; mask = mask >> 1){
{
if((mask & sent_data) == 0x00)
I2C_SDA = 0;
else
I2C_SDA = 1;
}
delay();
I2C_SCL = 1;
delay();
I2C_SCL = 0;
}
I2C_SDA = 1;
delay();
I2C_SCL = 1;
ack = I2C_SDA;
delay();
I2C_SCL = 0;
}
void i2c_stop(void){
I2C_SCL = 0;
I2C_SDA = 0;
delay();
I2C_SCL = 1;
delay();
I2C_SDA = 1;
delay();
}
|
C | #include <stdio.h>
#include <math.h>
#include <complex.h>
int main() {
double a,b,c;
scanf("%lf", &a);
scanf("%lf", &b);
scanf("%lf", &c);
double D = pow(b, 2) - 4 * a * c;
if (D > 0) {
D = sqrt(D);
printf("%f\n%f\n", (-b + D) / (2 * a), (-b - D) / (2 * a));
} else if (D == 0) {
printf("%f\n", -b / (2 * a));
} else {
D = sqrt(-D);
double _Complex z1 = (-b + D * I) / (2 * a);
double _Complex z2 = (-b - D * I) / (2 * a);
printf("%f+%f*I\n%f%f*I\n", creal(z1), cimag(z1), creal(z2), cimag(z2));
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<gmp.h>
#include<math.h>
#include"arithZn.h"
void mpzExpo_mod(mpz_t result, mpz_t m, mpz_t e, mpz_t n){
/*int i = 0;
size_t fin = 0;
mpz_t t;
mpz_t m;
mpz_t tmp;
mpz_init (t);
mpz_init (tmp);
mpz_set(t,m);
mpz_set(result,b);
fin = mpz_sizeinbase(e,2);
for(i = 0;i < fin;i++){//Comparaison entre i et e
if(
}
mpz_clear(t);
mpz_clear(tmp);*/
}
void mpz_max(mpz_t result, mpz_t a,mpz_t b){
if(mpz_cmp(a,b)>=0)
mpz_set(result,a);
else
mpz_set(result,b);
}
void mpz_min(mpz_t result, mpz_t a,mpz_t b){
if(mpz_cmp(a,b)<=0)
mpz_set(result,a);
else
mpz_set(result,b);
}
void mpzMy_pgcd(mpz_t result,mpz_t a, mpz_t b){
mpz_t min;
mpz_t max;
mpz_t tmp;
mpz_init (min);
mpz_init (max);
mpz_init (tmp);
mpzMy_pgcdMemSave(result,a,b,min,max,tmp);
mpz_clear(min);
mpz_clear(max);
mpz_clear(tmp);
}
void mpzMy_pgcdMemSave(mpz_t result,mpz_t a, mpz_t b,mpz_t min,mpz_t max,mpz_t tmp){
if(mpz_cmp(a,b)==0)
mpz_set(result,a);
else{
mpz_max(max,a,b);
mpz_min(min,a,b);
mpz_sub(tmp,max,min);
mpzMy_pgcdMemSave(result,tmp,min,min,max,tmp);
}
}
void mpzFastExp(mpz_t result, mpz_t m, mpz_t e){
/*U ← 1 T ← m,
Pour i = 0 ` Nb − 1 Faire
a
Si ei = 1 alors U ← T · U mod N
T ← T · T mod N
Retourner U*/
/*mpz_t u,t;
mpz_set_str(u,"1",10);
mpz_set(t,m);
mpz_clear(u);
mpz_clear(t);*/
}
void mpzMy_inverse(mpz_t result, mpz_t a, mpz_t n)
{
mpz_t t, nt, r, nr, q, tmp,tmpa, tmpn;
mpz_init (t);
mpz_init (nt);
mpz_init (r);
mpz_init (nr);
mpz_init (q);
mpz_init (tmp);
mpz_init (tmpa);
mpz_init (tmpn);
if (mpz_sgn(n) == -1)
mpz_neg(tmpn,n);
if (mpz_sgn(a) == -1) {
mpz_neg(tmpa,a);
mpz_mod(tmpa,tmpa,n);
mpz_sub(tmpa, n,tmpa);
}
mpz_set(tmpn,n);
mpz_set(tmpa,a);
mpz_set_str(nt,"1",10);
mpz_set(r,tmpn);
mpz_mod(nr,a,tmpn);
while (mpz_sgn(nr) != 0) {
mpz_tdiv_q(q,r,nr);
mpz_set(tmp,nt);
mpz_mul(nt,q,nt);
mpz_sub(nt,t,nt);
mpz_set(t,tmp);
mpz_set(tmp,nr);
mpz_mul(nr,q,nr);
mpz_sub(nr,r,nr);
mpz_set(r,tmp);
}
if (mpz_sgn(t) == -1){
mpz_add(t,t,tmpn);
mpz_set(result,t);
}
mpz_set(result,t);
if (mpz_cmp_d(r,1.0) < 0){ /*plus grand que 1*/
mpz_set_str(result,"-1",10); /* No inverse */
}
mpz_clear(t);
mpz_clear(nt);
mpz_clear(r);
mpz_clear(nr);
mpz_clear(q);
mpz_clear(tmp);
mpz_clear(tmpa);
mpz_clear(tmpn);
}
int iMod_exp(int m, int e, int n){
int t = m;
int i = 0;
for(i = 1;i < e;i++){
t = (t*m)%n;
}
return t;
}
int iMy_pgcd(int a, int b){
int result = 0;
if(a == b)
result = a;
else
result = iMy_pgcd(fmax(a,b)-fmin(a,b),fmin(a,b));
return result;
}
int iMy_inverse(int a, int b)
{
int t, nt, r, nr, q, tmp;
if (b < 0)
b = -b;
if (a < 0)
a = b - (-a % b);
t = 0;
nt = 1;
r = b;
nr = a % b;
while (nr != 0) {
q = r/nr;
tmp = nt;
nt = t - q*nt;
t = tmp;
tmp = nr;
nr = r - q*nr;
r = tmp;
}
if (r > 1)
return -1; // No inverse
if (t < 0)
t += b;
return t;
}
|
C | #include <stdio.h>
int A[100][100], B[100][100];
int main()
{
int n, m, i, j;
scanf("%d %d", &n, &m);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
scanf("%d", &A[i][j]);
for (j=0; j<m; j++)
for (i=0; i<n; i++)
B[j][i] = A[i][j];
for (j=0; j<m; j++)
{
for (i=0; i<n; i++)
printf("%d ", B[j][i]);
printf("\n");
}
return 0;
} |
C | # include <stdio.h>
int strindex(char[], char[]);
int main(void)
{
printf("%d\n", strindex("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo",
"buffalo")); // answer - 56
}
int strindex(char s[], char t[])
{
int pos = -1;
int i, j;
for (i = 0; s[i] != '\0'; i++) {
for (j=i; s[j] != '\0'; j++) {
if (s[j] != t[j-i])
break;
else if (t[j-i+1] == '\0')
pos = i;
}
}
return pos;
}
|
C | #include <netinet/in.h>
#include "unpheader.h"
void print_fdset(fd_set s)
{
printf("{");
int fisrt = 1;
for(int i=0;i<FD_SETSIZE;++i) {
if(FD_ISSET(i,&s)) {
if(!fisrt)
printf(",%d",i);
else
printf("%d",i);
fisrt = 0;
}
}
printf("}\n");
}
int main()
{
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(12200);
int listenfd = Socket(AF_INET, SOCK_STREAM, 0);
int opt = 1;
if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt))<0) Perror("setsockopt error");
Bind(listenfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
Listen(listenfd, 20);
int connfds[FD_SETSIZE];
int end_connfds = 0;
int maxfd = listenfd;
fd_set fdset_conn;
for(int i=0;i<FD_SETSIZE;++i) connfds[i] = -1;
FD_ZERO(&fdset_conn);
FD_SET(listenfd, &fdset_conn);
while(1) {
fd_set rset = fdset_conn;
int ns = Select(maxfd+1, &rset, NULL, NULL, NULL);
//fprintf(stderr,"ns:%d ",ns);print_fdset(rset); kill(getpid(),SIGTSTP);
if(FD_ISSET(listenfd, &rset)) {
// fprintf(stderr,"accept "); kill(getpid(),SIGTSTP);
int newconnfd = Accept(listenfd, NULL, NULL);
int index;
for(index=0;index<FD_SETSIZE;++index) {
if(connfds[index]==-1) {
connfds[index] = newconnfd;
end_connfds = myMax(index+1,end_connfds);
break;
}
}
if(index==FD_SETSIZE)
Perror("too many connections");
FD_SET(newconnfd, &fdset_conn);
maxfd = myMax(newconnfd, maxfd);
--ns;
}
for(int i=0;i<end_connfds && ns>0;++i) {
if(connfds[i]!=-1 && FD_ISSET(connfds[i],&rset)) {
int n;
int buf[MAXLINE];
if((n=Read(connfds[i],buf,MAXLINE))>=0) {
if(n==0) { //client send EOF
close(connfds[i]);
FD_CLR(connfds[i],&fdset_conn);
connfds[i] = -1;
} else {
Writen(connfds[i],buf,n);
}
}
--ns;
}
}
}
return 0;
}
|
C | /*
* Exercise 2-8
*
* Write a function rightrot(x, n) that returns the value of the integer x
* rotated to the right n bit positions.
*/
#include <stdio.h>
unsigned rightrot(unsigned x, int n);
int main()
{
unsigned x = 9713; // 0010 0101 1111 0001
printf("%u\n", rightrot(x, 4));
return 0;
}
unsigned rightrot(unsigned x, int n)
{
int dec, max;
unsigned int i, q;
dec = x ; i = 0;
max = 1;
/* calculate number of bits */
while (dec > 0) {
dec = dec / 2;
++i;
}
q = (i + 4 - 1) / 4; // round up
q = (4 * q);
/* calculate max bit */
for(int j = 1; j <= q-1; ++j) {
max *= 2;
}
//printf("%d\n", i);
//printf("%d\n", max);
/* rotate to the right by n bits position */
for (int j = 0; j < n; ++j) {
if (x & 0b0001 == 1) {
x = (x >> 1) | max;
}
else
x >>= 1;
}
return x;
// ~(~0U >> x) - rotate to the right in the end
}
|
C | #include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(int argc, string argv[])
{
// Check for proper input
if( argc == 1 || argc > 2 )
{
printf("%i",1);
return 1;
}
string keyword = argv[1];
int key_len = strlen(keyword);
int key[key_len];
// Check for valid keyword and define change key
for( int i = 0; i < key_len; i++)
{
// If alpha character, convert to key value
if( keyword[i] >= 'a' && keyword[i] <= 'z')
{
key[i] = keyword[i] - 'a';
}
else if( keyword[i] >= 'A' && keyword[i] <= 'Z')
{
key[i] = keyword[i] - 'A';
}
// If non alpha character, quit
else
{
printf("%i",1); return 1;
}
}
string phrase = GetString();
int phrase_len = strlen(phrase);
int letter;
int new_letter;
int i = 0; int count = 0;
// Encryption sequence
while( i < phrase_len )
{
letter = phrase[i];
// Encrypts non alpha characters
if( ( letter >= 'A' && letter <= 'Z' ) || ( letter >= 'a' && letter <= 'z' ) )
{
new_letter = letter + key[count % key_len];
// Wraps character if necessary
if( new_letter > 'z' || (new_letter > 'Z' && letter < 'a') )
{
new_letter -= 26;
}
// Displays encrypted character
printf("%c", new_letter);
count++;
}
// Does not encrypt non alpha characters
else
{
printf("%c", letter);
}
i++;
}
printf("\n");
return 0;
} |
C | #include <stdio.h>
#include "read_input.h"
int main(void)
{
int first, second;
read_int("Syötä ensimmäinen kokonaisluku: ", &first);
read_int("Syötä toinen kokonaisluku: ", &second);
if (first % second == 0)
printf("%i on %i:n %i. monikerta.\n", first, second, first/second);
else
printf("%i ei ole %i:n monikerta.\n", first, second);
return 0;
}
|
C | #include <stdio.h>
int main()
{
int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
} |
C | /*
A year is leap year if the following conditions are satisfied:
1.Year is multiple of 400.
2.Year is multiple of 4 and not multiple of 100.
pseudo-code:
if year is divisible by 400 then is_leap_year
else if year is divisible by 100 then not_leap_year
else if year is divisible by 4 then is_leap_year
else not_leap_year
*/
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
// leap year if perfectly divisible by 400
if (year % 400 == 0) {
printf("%d is a leap year.", year);
}
// not a leap year if divisible by 100
// but not divisible by 400
else if (year % 100 == 0) {
printf("%d is not a leap year.", year);
}
// leap year if not divisible by 100
// but divisible by 4
else if (year % 4 == 0) {
printf("%d is a leap year.", year);
}
// all other years are not leap year
else {
printf("%d is not a leap year.", year);
}
return 0;
}
|
C | #include <stdio.h>
#include <cs50.h>
#include <math.h>
#define K25 25
#define K10 10
#define K5 5
int main(void)
{
float balance;
do
{
printf("Gimme a float: ");
balance = get_float();
}
while(balance <= 0);
// convert balance to kobo
int kobo = (int)round(balance * 100);
// count coins
int count = 0;
// store the remainders
int remains = 0;
// for 25 kobo
count += kobo / K25;
remains = kobo % K25;
// for 10 kobo
count += remains / K10;
remains = remains % K10;
// for 5 kobo
count += remains / K5;
remains = remains % K5;
// for 1 kobo
count += remains;
printf("%d\n", count);
} |
C | #include <Polynomail.h>
void
AddPolynomial(const Polynomial Poly1, const Polynomial Poly2, Polynomial PolySum)
{
int i;
ZeroPolynomial(PolySum);
PolySum->HighPower = Max(Poly1->HighPower, Poly2->HighPower);
for(i = PolySum->HighPower; i >= 0; i--)
{
PolySum->CoeffArray[i] = Poly1->CoeffArray[i] + Poly2->CoeffArray[i];
}
}
|
C | #include "../include/options.h"
#include <getopt.h>
static struct option long_opts[] =
{
{"execute", required_argument, NULL, 'e'},
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'}
};
int main(int argc, char *argv[])
{
int opt;
int retcode = 0;
extern char *optarg;
while ((opt = getopt_long(argc, argv, "e:vh", long_opts, NULL)) != -1)
{
switch (opt)
{
case 'e':
retcode = opt_execute(optarg);
break;
case 'v':
retcode = opt_version();
break;
case 'h':
retcode = opt_help();
break;
}
}
if (optind == 1 && argc == 2)
retcode = opt_execute(argv[1]);
if (optind == 1)
printf("pvm: no options specified\n");
return retcode;
}
|
C | // Written by Cezary Migazewski - Last Edit 1/1/16
my_float kepler_equation (my_float e, my_float M)
{
my_float E, E0, f0, f1, f2, f3, d1, d2, d3, delta, nu;
int i;
E = M;
delta=1;
i=0;
while ((delta>1e-8) && (i<100)) {
++i;
E0=E;
f0=E-e*sin(E)-M;
f1=1-e*cos(E);
f2=e*sin(E);
f3=e*cos(E);
d1=-f0/f1;
d2=-f0/(f1+d1*f2/2);
d3=-f0/(f1+d2*f2/2+d2*d2*f3/6);
E=E+d3;
delta=fabs(E0-E);
}
nu = 2*atan2(sqrt(1 + e)*sin(E/2.), sqrt(1 - e)*cos(E/2.));
return nu;
}
|
C | #include<cs50.h>
#include<stdio.h>
#include<math.h>
int sum_of_digits(long long number, long long odd_or_even);
int even_addition(int digit);
int get_digits(long long number, long long loop, int decision);
int main(void)
{
printf("Please enter a credit card number \n");
long long number = get_long_long();
int sum_even = sum_of_digits(number, 10);
int sum_odd = sum_of_digits(number,1);
int total = sum_even + sum_odd ;
if((total % 10) == 0)
{
if((int)(number/1000000000000000) == 5)
{
printf("MASTERCARD\n");
}
else if( ( (int)(number/1000000000000000) == 4) || ( (int)(number/1000000000000) == 4) )
{
printf("VISA\n");
}
else if((int)(number/100000000000000) == 3)
{
printf("AMEX\n");
}
}
else
printf("INVALID\n") ;
}
int sum_of_digits(long long number , long long odd_or_even)
{
int calc = 0;
int temp = 0;
int decision = odd_or_even;
for(int i=1;i<9;i++)
{
//printf("value of x is %lld \n" , odd_or_even);
temp = ((get_digits(number, odd_or_even, decision)));
if(decision==10)
{
temp = even_addition(temp);
}
else if(decision==1)
{
temp = temp + 0;
}
else
{
printf("I am a stupid programmer, I messed up, sorry");
}
calc = calc + temp;
odd_or_even = odd_or_even*100;
}
return calc;
}
int get_digits(long long number, long long loop, int decision)
{
if((number/loop) > 0)
{
int digit = ((long long)(number / loop) % 10) ;
// printf("The value of digit = %i\n", digit);
if(decision==10)
{
digit = digit *2;
}
else if(decision==1)
{
digit = digit + 0;
}
else
{
printf("I am a stupid programmer, I messed up, sorry");
digit = 0;
}
return digit;
}
else
return 0;
}
int even_addition(int digit)
{
if(digit > 9)
{
digit = ((digit % 10) + (int)(digit/10));
return digit;
}
else
return digit ;
} |
C |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readLine(char* buffer) {
char c;
int i = 0;
while((c = getchar()) != '\n') {
buffer[i++] = c;
}
buffer[i] = '\0';
return buffer;
}
int main(void) {
char buffer[100];
while(1) {
printf("$ ");
readLine(buffer);
printf("%s:%d\n", buffer, strlen(buffer));
}
return 0;
}
|
C | /*
* File: scheduler.h
* Description: The main scheduler
* *****************************************************************************
* Copyright 2021 Scott Maday
* Check the LICENSE file that came with this program for licensing terms
*/
#pragma once
#include "x86_64/isr.h"
#define SCHEDULER_QUEUES_NUM _SCHEDULER_QUEUES_NUM
struct Thread {
uint64_t tid;
struct Process* process;
struct Thread* next;
} __attribute__((packed));
struct SchedulerContextFrame {
struct SchedulerContextFrameRegisters {
uint64_t rax, rbx, rcx, rdx, rsi, rdi, rbp, r8, r9, r10, r11, r12, r13, r14, r15;
} general;
uint64_t rip, cs, rflags, rsp, ss;
uint64_t self;
} __attribute__((packed));
struct SchedulerContext {
struct SchedulerContextFrame context_frame;
uint64_t flags;
uint64_t error_code;
struct Thread task;
} __attribute__((packed));
struct SchedulerNode {
struct SchedulerContext context;
size_t queue_num;
struct SchedulerNode* previous;
struct SchedulerNode* next;
} __attribute__((packed));
struct SchedulerTaskInitialState {
struct SchedulerContextFrameRegisters general; // general purpose registers
void* entry; // start point
void* stack; // initial stack pointer
uint8_t rpl; // requested privilege level
};
enum SchedulerQueueNumber {
SCHEDULER_QUEUE_PRIORITY,
SCHEDULER_QUEUE_REGULAR,
SCHEDULER_QUEUE_BATCH,
_SCHEDULER_QUEUES_NUM
};
enum SchedulerQueueFlagBits {
SCHEDULER_QUEUE_FLAG_LOCKED = 0,
};
enum SchedulerContextFlagBits {
SCHEDULER_CONTEXT_FLAG_LOCKED = 0,
SCHEDULER_CONTEXT_FLAG_FINISHED = 1,
};
// Initializes scheduler
void scheduler_init();
// Gets the next task and advances the task ring
struct SchedulerNode* scheduler_next_task(struct SchedulerNode* current);
// Adds the task with [initial_state] to the queue of [queue_num]
struct SchedulerNode* scheduler_add_task(struct SchedulerTaskInitialState* initial_state, enum SchedulerQueueNumber queue_num);
// Frees the resources of task [node] and dequeues it from its queue. Assumes [node] has already acquired a lock.
void scheduler_free_task(struct SchedulerNode* node);
// *** From scheduler.asm *** //
// Begins scheduling tasks once unlocked for the processor calling this
// There is no going back once the scheduler has been entered
// [should_unlock] will unlock a spin loop
void scheduler_entry(bool should_unlock);
// Causes the processor to halt until it's interrupted
void scheduler_idle(); |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lltoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gguichar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/16 09:28:56 by gguichar #+# #+# */
/* Updated: 2018/11/16 14:12:26 by gguichar ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
static char ft_base_char(int n)
{
if (n < 10)
return (n + '0');
return (n - 10 + 'A');
}
char *ft_lltoa_base(long long n, int base)
{
unsigned long long value;
int count;
char *str;
if (base < 2 || base > 36)
return (NULL);
value = (n < 0) ? -n : n;
count = (n == 0 || (n < 0 && base == 10));
while (value != 0)
{
value /= base;
count++;
}
if (!(str = (char *)malloc(sizeof(*str) * (count + 1))))
return (NULL);
str[count] = '\0';
value = (n < 0) ? -n : n;
while (--count > 0)
{
str[count] = ft_base_char(value % base);
value /= base;
}
*str = (n < 0 && base == 10 ? '-' : ft_base_char(value));
return (str);
}
|
C | #include "holberton.h"
/**
*_pow_recursion - return value f x raised to power y
*@x: x value
*@y: value being raise to
*Return: returns int
**/
int _pow_recursion(int x, int y)
{
if (y < 0)
return (-1);
if (y == 0)
{
return (1);
}
return (x * _pow_recursion(x, y - 1));
}
|
C | #ifndef IMM_LIST_H
#define IMM_LIST_H
#include "api.h"
#include "container.h"
#include <stdbool.h>
struct imm_list
{
struct imm_list *next;
struct imm_list *prev;
};
IMM_API void imm_list_init(struct imm_list *list);
IMM_API void imm_list_add(struct imm_list *neu, struct imm_list *head);
IMM_API void imm_list_del(struct imm_list *entry);
IMM_API bool imm_list_is_head(struct imm_list const *list,
struct imm_list const *head);
IMM_API bool imm_list_empty(struct imm_list const *head);
#define imm_list_for_each(pos, head) \
for (pos = (head)->next; !imm_list_is_head(pos, (head)); pos = pos->next)
#define imm_list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; !imm_list_is_head(pos, (head)); \
pos = n, n = pos->next)
#define imm_list_entry(ptr, type, member) imm_container(ptr, type, member)
#define imm_list_first_entry(ptr, type, member) \
imm_list_entry((ptr)->next, type, member)
#define imm_list_entry_is_head(pos, head, member) (&pos->member == (head))
#define imm_list_next_entry(pos, member) \
imm_list_entry((pos)->member.next, __typeof__(*(pos)), member)
#define imm_list_for_each_entry(pos, head, member) \
for (pos = imm_list_first_entry(head, __typeof__(*pos), member); \
!imm_list_entry_is_head(pos, head, member); \
pos = imm_list_next_entry(pos, member))
#endif
|
C | #include "ind_lt_neg.h"
int ind_lt_neg(int a, int arr[100])
{
int x = 0;
for (int i = 0; i > a; i++)
{
if (arr[i] < 0)
{
x = i;
}
}
return x;
}
|
C | /*
** EPITECH PROJECT, 2019
** minishell1
** File description:
** my_getenv.c
*/
#include <unistd.h>
#include <stdlib.h>
#include "../include/structures.h"
#include "../include/my.h"
char *my_getenv(name_t *value, name_t *name, char *elem, char **command)
{
char *path;
int count = 0;
char **pathes;
char *ret;
name = name->head;
value = value->head;
for (; my_strcmp(name->name, elem) != 0;) {
if (name->next == NULL)
return (NULL);
name = name->next;
value = value->next;
}
for (; value->name[count] != '\0'; count++);
path = malloc(sizeof(char) * (count + 1));
path[count] = '\0';
for (int mem = 0; value->name[mem] != '\0'; mem++)
path[mem] = value->name[mem];
return (path);
} |
C | #include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int wordcount(char s[],int x)
{
int n=0;
if(s[0]!='\0')
{
for(int i=0;i<x && s[i+1]!='\0';i++)
if(s[i]==' '&& s[i+1]!=' ')
n++;
n=s[0]==' '?n:n+1;
}
return n;
}
int main()
{
char s[100];
printf("Enter the string : ");
gets(s);
printf("The total number of words is %d",wordcount(s,100));
return 0;
} |
C | /**
* Header file for config file management.
* @author John Bellardo
*/
#ifndef CONFIG_H
#define CONFIG_H
#include <stdlib.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void *(*CFG_parseCB_t)(const char *key, const char *value, void *data,
void *p1, void *p2);
struct CFG_ParseCB
{
CFG_parseCB_t cb;
void *p1, *p2;
};
struct CFG_ParseValue
{
const char *name;
struct CFG_ParseObj *subObj, **subObjArr;
struct CFG_ParseCB cb;
};
struct CFG_ParseObj
{
const char *subtype;
struct CFG_ParseCB initCb, finiCb;
struct CFG_ParseValue *keys;
};
struct CFG_Array {
int len, capacity;
void **data;
};
void *CFG_MallocCB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_StrdupCB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_InetAtonCB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_uint32_CB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_uint16_CB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_int32_CB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_int16_CB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_float_CB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_PtrCpyCB(const char *key, const char *value, void *data, void *p1,
void *p2);
void *CFG_PtrArrayAppendCB(const char *key, const char *value, void *data,
void *p1, void *p2);
#define CFG_MALLOC(x) { &CFG_MallocCB, (void*)(sizeof(x)), NULL }
#define CFG_NULL { NULL, NULL, NULL }
#define CFG_NULLK { NULL, NULL, NULL, CFG_NULL }
#define CFG_OBJ(n, obj, str, field) { n, obj, NULL, { &CFG_PtrCpyCB, (void*)offsetof(str,field), NULL } }
#define CFG_OBJLIST(n, objlist, str, field) { n, NULL, objlist, { &CFG_PtrCpyCB, (void*)offsetof(str,field), NULL } }
#define CFG_OBJARR(n, obj, str, field) { n, obj, NULL, { &CFG_PtrArrayAppendCB, (void*)offsetof(str,field), NULL } }
#define CFG_OBJLISTARR(n, objlist, str, field) { n, NULL, objlist, { &CFG_PtrArrayAppendCB, (void*)offsetof(str,field), NULL } }
#define CFG_OBJCB(n, obj, cb) { n, obj, NULL, { &cb, NULL, NULL } }
#define CFG_STRDUP(n, str, field) { n, NULL, NULL, { &CFG_StrdupCB, (void*)offsetof(str,field), NULL } }
#define CFG_UINT32(n, str, field) { n, NULL, NULL, { &CFG_uint32_CB, (void*)offsetof(str,field), NULL } }
#define CFG_UINT16(n, str, field) { n, NULL, NULL, { &CFG_uint16_CB, (void*)offsetof(str,field), NULL } }
#define CFG_INT32(n, str, field) { n, NULL, NULL, { &CFG_int32_CB, (void*)offsetof(str,field), NULL } }
#define CFG_INT16(n, str, field) { n, NULL, NULL, { &CFG_int16_CB, (void*)offsetof(str,field), NULL } }
#define CFG_FLOAT(n, str, field) { n, NULL, NULL, { &CFG_float_CB, (void*)offsetof(str,field), NULL } }
#define CFG_INET_ATON(n, str, field) { n, NULL, NULL, { &CFG_InetAtonCB, (void*)offsetof(str,field), NULL } }
#define CFG_OBJNAME(x) CFG__##x##__obj
#define CFG_VALNAME(x) CFG__##x##__keys
#define CFG_SUBNAME(x) CFG__##x##__subtypes
#define CFG_NEWOBJ_GBL(x, ini, fin, ...) static struct CFG_ParseValue CFG_VALNAME(x)[] = { __VA_ARGS__, CFG_NULLK }; \
struct CFG_ParseObj CFG_OBJNAME(x) = { "", ini, fin, CFG_VALNAME(x) };
#define CFG_NEWOBJ(x, ini, fin, ...) static struct CFG_ParseValue CFG_VALNAME(x)[] = { __VA_ARGS__, CFG_NULLK }; \
static struct CFG_ParseObj CFG_OBJNAME(x) = { "", ini, fin, CFG_VALNAME(x) };
#define CFG_NEWSUBOBJ(x, name, ini, fin, ...) static struct CFG_ParseValue CFG_VALNAME(x)[] = { __VA_ARGS__, CFG_NULLK }; \
struct CFG_ParseObj CFG_OBJNAME(x) = { name, ini, fin, CFG_VALNAME(x) };
#define CFG_EMPTYOBJ(x, ini, fin) static struct CFG_ParseValue CFG_VALNAME(x)[] = { CFG_NULLK }; \
static struct CFG_ParseObj CFG_OBJNAME(x) = { "", ini, fin, CFG_VALNAME(x) };
/**
* \brief Get the path of the configuration file.
* \returns The full POSIX path of the current configuration file. If there is
* no file the string is empty and the pointer is non-NULL.
**/
const char *CFG_getPath();
/**
* \brief Locates the configuration file with the given name. It searches in
* the current working directory, in $HOME/.<filename>, and in /etc/<filename>
* in that order.
* \returns True if a configuration file is located and false otherwise.
**/
int CFG_locateConfigFile(const char *name);
/**
* \brief This function parses the configuration file
**/
void *CFG_parseFile(struct CFG_ParseObj *);
/**
* \brief This function parses the configuration file located at the
* given path. This bypassed the normal directory search order.
**/
void *CFG_parseFileAtPath(struct CFG_ParseObj *, const char *path);
/// Prototype for a function that knows how to clean up memory for a struct
typedef void (*CFG_objFreeCb_t)(void*);
/**
* \brief Free any heap memory associated with an array structure
**/
void CFG_freeArray(struct CFG_Array *arr, CFG_objFreeCb_t freeCb);
#ifdef __cplusplus
}
#endif
#endif
|
C | #include <stdio.h>
// 共用体类型的定义
struct mystruct
{
int a;
char b;
};
// a和b其实指向同一块内存空间,只是对这块内存空间的2种不同的解析方式。
// 如果我们使用u1.a那么就按照int类型来解析这个内存空间;如果我们使用u1.b那么就按照char类型
// 来解析这块内存空间。
union myunion
{
int a;
char b;
};
typedef union xx
{
int a;
char b;
double c;
}XXX;
union test
{
int a;
float b;
};
int main(void)
{
union test t1;
t1.a = 1123477881;
printf("value = %f.\n", t1.b);
int a = 1123477881;
printf("指针方式:%f.\n", *((float *)&a));
/*
// test1
struct mystruct s1;
s1.a = 23;
printf("s1.b = %d.\n", s1.b); // s1.b = 0. 结论是s1.a和s1.b是独立无关的
printf("&s1.a = %p.\n", &s1.a);
printf("&s1.b = %p.\n", &s1.b);
union myunion u1; // 共用体变量的定义
u1.a = 23; // 共用体元素的使用
printf("u1.b = %d.\n", u1.b); // u1.b = 23.结论是u1.a和u1.b是相关的
// a和b的地址一样,充分说明a和b指向同一块内存,只是对这块内存的不同解析规则
printf("&u1.a = %p.\n", &u1.a);
printf("&u1.b = %p.\n", &u1.b);
printf("sizeof(XXX) = %d.\n", sizeof(XXX));
printf("sizeof(union xx) = %d.\n", sizeof(union xx));
*/
return 0;
}
|
C | # include <stdlib.h>
# include <stdio.h>
# include <math.h>
# include <time.h>
# include <string.h>
int main ( int argc, char *argv[] );
char ch_cap ( char ch );
int ch_eqi ( char ch1, char ch2 );
int ch_to_digit ( char ch );
int file_column_count ( char *input_filename );
int file_row_count ( char *input_filename );
int i4_power ( int i, int j );
void power_rule_set ( int point_num_1d, double x_1d[], double w_1d[],
double r_1d[], int dim_num, int point_num, double x[],
double w[], double r[] );
int power_rule_size ( int point_num_1d, int dim_num );
double r8_epsilon ( );
double *r8mat_data_read ( char *input_filename, int m, int n );
void r8mat_header_read ( char *input_filename, int *m, int *n );
void r8mat_write ( char *output_filename, int m, int n, double table[] );
int s_len_trim ( char *s );
int s_to_i4 ( char *s, int *last, int *error );
double s_to_r8 ( char *s, int *lchar, int *error );
int s_to_r8vec ( char *s, int n, double rvec[] );
int s_word_count ( char *s );
void timestamp ( );
void tuple_next ( int m1, int m2, int n, int *rank, int x[] );
/******************************************************************************/
int main ( int argc, char *argv[] )
/******************************************************************************/
/*
Purpose:
MAIN is the main program for POWER_RULE.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
05 February 2014
Author:
John Burkardt
*/
{
int dim;
int dim_num;
int dim_num_1d;
int error;
int last;
int more;
int point_num;
int point_num_1d;
int point_num_1d2;
char quad_1d_filename[80];
char quad_r_1d_filename[80];
char quad_r_filename[] = "power_r.txt";
char quad_w_1d_filename[80];
char quad_w_filename[] = "power_w.txt";
char quad_x_1d_filename[80];
char quad_x_filename[] = "power_x.txt";
double *r;
double *r_1d;
double *w;
double *w_1d;
double *x;
double *x_1d;
timestamp ( );
printf ( "\n" );
printf ( "POWER_RULE\n" );
printf ( " C version\n" );
printf ( "\n" );
printf ( " Compiled on %s at %s\n", __DATE__ , __TIME__ );
printf ( "\n" );
printf ( " Create a multidimensional power rule\n" );
printf ( " as a product of identical 1D integration rules.\n" );
/*
Get the quadrature file root name:
*/
if ( 1 < argc )
{
strcpy ( quad_1d_filename, argv[1] );
}
else
{
printf ( "\n" );
printf ( "POWER_RULE:\n" );
printf ( " Enter the \"root\" name of the 1D quadrature files.\n" );
scanf ( "%s", quad_1d_filename );
}
/*
Create the names of:
the quadrature X file;
the quadrature W file;
the quadrature R file;
*/
strcpy ( quad_r_1d_filename, quad_1d_filename );
strcat ( quad_r_1d_filename, "_r.txt" );
strcpy ( quad_w_1d_filename, quad_1d_filename );
strcat ( quad_w_1d_filename, "_w.txt" );
strcpy ( quad_x_1d_filename, quad_1d_filename );
strcat ( quad_x_1d_filename, "_x.txt" );
/*
The second command line argument is the spatial dimension.
*/
if ( 2 < argc )
{
dim_num = s_to_i4 ( argv[2], &last, &error );
}
else
{
printf ( "\n" );
printf ( "POWER_RULE:\n" );
printf ( " Please enter the desired spatial dimension of the rule.\n" );
scanf ( "%d", &dim_num );
}
/*
Summarize the input.
*/
printf ( "\n" );
printf ( "POWER_RULE: User input:\n" );
printf ( " Quadrature rule X file = \"%s\"\n", quad_x_1d_filename );
printf ( " Quadrature rule W file = \"%s\"\n", quad_w_1d_filename );
printf ( " Quadrature rule R file = \"%s\"\n", quad_r_1d_filename );
printf ( " Spatial dimension = %d\n", dim_num );
/*
Read the X file.
*/
r8mat_header_read ( quad_x_1d_filename, &dim_num_1d, &point_num_1d );
if ( dim_num_1d != 1 )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "POWER_RULE - Fatal error!\n" );
fprintf ( stderr, " The 1D quadrature abscissa file should have exactly\n" );
fprintf ( stderr, " one value on each line.\n" );
exit ( 1 );
}
printf ( "\n" );
printf ( " Number of points in 1D rule = %d\n", point_num_1d );
x_1d = r8mat_data_read ( quad_x_1d_filename, dim_num_1d, point_num_1d );
/*
Read the W file.
*/
r8mat_header_read ( quad_w_1d_filename, &dim_num_1d, &point_num_1d2 );
if ( dim_num_1d != 1 )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "POWER_RULE - Fatal error!\n" );
fprintf ( stderr, " The 1D quadrature weight file should have exactly\n" );
fprintf ( stderr, " one value on each line.\n" );
exit ( 1 );
}
if ( point_num_1d2 != point_num_1d )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "POWER_RULE - Fatal error!\n" );
fprintf ( stderr, " The 1D quadrature weight file should have exactly\n" );
fprintf ( stderr, " the same number of lines as the abscissa file.\n" );
exit ( 1 );
}
w_1d = r8mat_data_read ( quad_w_1d_filename, dim_num_1d, point_num_1d );
/*
Read the R file.
*/
r8mat_header_read ( quad_r_1d_filename, &dim_num_1d, &point_num_1d2 );
if ( dim_num_1d != 1 )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "POWER_RULE - Fatal error!\n" );
fprintf ( stderr, " The 1D quadrature region file should have exactly\n" );
fprintf ( stderr, " one value on each line.\n" );
exit ( 1 );
}
if ( point_num_1d2 != 2 )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "POWER_RULE - Fatal error!\n" );
fprintf ( stderr, " The 1D quadrature region file should have two lines.\n" );
exit ( 1 );
}
r_1d = r8mat_data_read ( quad_r_1d_filename, 1, 2 );
/*
Determine size of the rule.
*/
point_num = power_rule_size ( point_num_1d, dim_num );
printf ( "\n" );
printf ( " Number of points in rule = %d\n", point_num );
/*
Compute the rule.
*/
w = ( double * ) malloc ( point_num * sizeof ( double ) );
x = ( double * ) malloc ( dim_num * point_num * sizeof ( double ) );
r = ( double * ) malloc ( dim_num * 2 * sizeof ( double ) );
power_rule_set ( point_num_1d, x_1d, w_1d, r_1d, dim_num, point_num,
x, w, r );
/*
Write rule to files.
*/
printf ( "\n" );
printf ( " Creating quadrature rule X file = \"%s\"\n", quad_x_filename );
r8mat_write ( quad_x_filename, dim_num, point_num, x );
printf ( " Creating quadrature rule W file = \"%s\"\n", quad_w_filename );
r8mat_write ( quad_w_filename, 1, point_num, w );
printf ( " Creating quadrature rule R file = \"%s\"\n", quad_r_filename );
r8mat_write ( quad_r_filename, dim_num, 2, r );
/*
Free memory.
*/
free ( w );
free ( w_1d );
free ( x );
free ( x_1d );
free ( r );
free ( r_1d );
/*
Terminate.
*/
printf ( "\n" );
printf ( "POWER_RULE:\n" );
printf ( " Normal end of execution.\n" );
printf ( "\n" );
timestamp ( );
return 0;
}
/******************************************************************************/
char ch_cap ( char ch )
/******************************************************************************/
/*
Purpose:
CH_CAP capitalizes a single character.
Discussion:
This routine should be equivalent to the library "toupper" function.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
19 July 1998
Author:
John Burkardt
Parameters:
Input, char CH, the character to capitalize.
Output, char CH_CAP, the capitalized character.
*/
{
if ( 97 <= ch && ch <= 122 )
{
ch = ch - 32;
}
return ch;
}
/******************************************************************************/
int ch_eqi ( char ch1, char ch2 )
/******************************************************************************/
/*
Purpose:
CH_EQI is TRUE (1) if two characters are equal, disregarding case.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
13 June 2003
Author:
John Burkardt
Parameters:
Input, char CH1, CH2, the characters to compare.
Output, int CH_EQI, is TRUE (1) if the two characters are equal,
disregarding case and FALSE (0) otherwise.
*/
{
int value;
if ( 97 <= ch1 && ch1 <= 122 )
{
ch1 = ch1 - 32;
}
if ( 97 <= ch2 && ch2 <= 122 )
{
ch2 = ch2 - 32;
}
if ( ch1 == ch2 )
{
value = 1;
}
else
{
value = 0;
}
return value;
}
/******************************************************************************/
int ch_to_digit ( char ch )
/******************************************************************************/
/*
Purpose:
CH_TO_DIGIT returns the integer value of a base 10 digit.
Example:
CH DIGIT
--- -----
'0' 0
'1' 1
... ...
'9' 9
' ' 0
'X' -1
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
13 June 2003
Author:
John Burkardt
Parameters:
Input, char CH, the decimal digit, '0' through '9' or blank are legal.
Output, int CH_TO_DIGIT, the corresponding integer value. If the
character was 'illegal', then DIGIT is -1.
*/
{
int digit;
if ( '0' <= ch && ch <= '9' )
{
digit = ch - '0';
}
else if ( ch == ' ' )
{
digit = 0;
}
else
{
digit = -1;
}
return digit;
}
/******************************************************************************/
int file_column_count ( char *input_filename )
/******************************************************************************/
/*
Purpose:
FILE_COLUMN_COUNT counts the number of columns in the first line of a file.
Discussion:
The file is assumed to be a simple text file.
Most lines of the file is presumed to consist of COLUMN_NUM words, separated
by spaces. There may also be some blank lines, and some comment lines,
which have a "#" in column 1.
The routine tries to find the first non-comment non-blank line and
counts the number of words in that line.
If all lines are blanks or comments, it goes back and tries to analyze
a comment line.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
13 June 2003
Author:
John Burkardt
Parameters:
Input, char *INPUT_FILENAME, the name of the file.
Output, int FILE_COLUMN_COUNT, the number of columns assumed
to be in the file.
*/
{
# define LINE_MAX 255
int column_num;
char *error;
FILE *input;
int got_one;
char line[LINE_MAX];
/*
Open the file.
*/
input = fopen ( input_filename, "r" );
if ( !input )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "FILE_COLUMN_COUNT - Fatal error!\n" );
fprintf ( stderr, " Could not open the input file: \"%s\"\n",
input_filename );
exit ( 1 );
}
/*
Read one line, but skip blank lines and comment lines.
*/
got_one = 0;
for ( ; ; )
{
error = fgets ( line, LINE_MAX, input );
if ( !error )
{
break;
}
if ( s_len_trim ( line ) == 0 )
{
continue;
}
if ( line[0] == '#' )
{
continue;
}
got_one = 1;
break;
}
if ( got_one == 0 )
{
fclose ( input );
input = fopen ( input_filename, "r" );
for ( ; ; )
{
error = fgets ( line, LINE_MAX, input );
if ( !error )
{
break;
}
if ( s_len_trim ( line ) == 0 )
{
continue;
}
got_one = 1;
break;
}
}
fclose ( input );
if ( got_one == 0 )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "FILE_COLUMN_COUNT - Warning!\n" );
fprintf ( stderr, " The file does not seem to contain any data.\n" );
exit ( 1 );
}
column_num = s_word_count ( line );
return column_num;
# undef LINE_MAX
}
/******************************************************************************/
int file_row_count ( char *input_filename )
/******************************************************************************/
/*
Purpose:
FILE_ROW_COUNT counts the number of row records in a file.
Discussion:
It does not count lines that are blank, or that begin with a
comment symbol '#'.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
13 June 2003
Author:
John Burkardt
Parameters:
Input, char *INPUT_FILENAME, the name of the input file.
Output, int FILE_ROW_COUNT, the number of rows found.
*/
{
# define LINE_MAX 255
int bad_num;
int comment_num;
char *error;
FILE *input;
int i;
char line[LINE_MAX];
int record_num;
int row_num;
row_num = 0;
comment_num = 0;
record_num = 0;
bad_num = 0;
input = fopen ( input_filename, "r" );
if ( !input )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "FILE_ROW_COUNT - Fatal error!\n" );
fprintf ( stderr, " Could not open the input file: \"%s\"\n",
input_filename );
exit ( 1 );
}
for ( ; ; )
{
error = fgets ( line, LINE_MAX, input );
if ( !error )
{
break;
}
record_num = record_num + 1;
if ( line[0] == '#' )
{
comment_num = comment_num + 1;
continue;
}
if ( s_len_trim ( line ) == 0 )
{
comment_num = comment_num + 1;
continue;
}
row_num = row_num + 1;
}
fclose ( input );
return row_num;
# undef LINE_MAX
}
/******************************************************************************/
int i4_power ( int i, int j )
/******************************************************************************/
/*
Purpose:
I4_POWER returns the value of I^J.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
23 October 2007
Author:
John Burkardt
Parameters:
Input, int I, J, the base and the power. J should be nonnegative.
Output, int I4_POWER, the value of I^J.
*/
{
int k;
int value;
if ( j < 0 )
{
if ( i == 1 )
{
value = 1;
}
else if ( i == 0 )
{
printf ( "\n" );
printf ( "I4_POWER - Fatal error!\n" );
printf ( " I^J requested, with I = 0 and J negative.\n" );
exit ( 1 );
}
else
{
value = 0;
}
}
else if ( j == 0 )
{
if ( i == 0 )
{
printf ( "\n" );
printf ( "I4_POWER - Fatal error!\n" );
printf ( " I^J requested, with I = 0 and J = 0.\n" );
exit ( 1 );
}
else
{
value = 1;
}
}
else if ( j == 1 )
{
value = i;
}
else
{
value = 1;
for ( k = 1; k <= j; k++ )
{
value = value * i;
}
}
return value;
}
/******************************************************************************/
void power_rule_set ( int point_num_1d, double x_1d[], double w_1d[],
double r_1d[], int dim_num, int point_num, double x[],
double w[], double r[] )
/******************************************************************************/
/*
Purpose:
POWER_RULE_SET sets up a power rule.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
05 February 2014
Author:
John Burkardt
Parameters:
Input, int POINT_NUM_1D, the order of the 1D rule.
Input, double X_1D[POINT_NUM_1D], the points of the 1D rule.
Input, double W_1D[POINT_NUM_1D], the weights of the
1D rule.
Input, double R_1D[2], the extreme points that define
the range of the 1D region.
Input, int DIM_NUM, the spatial dimension.
Input, int POINT_NUM, the number of points in the rule.
Output, double X[DIM_NUM*POINT_NUM], the points of the rule.
Output, double W[POINT_NUM], the weights of the rule.
Output, double R[DIM_NUM*2], the extreme points
that define the range of the product rule region.
*/
{
int dim;
int *indx;
int k;
indx = ( int * ) malloc ( dim_num * sizeof ( int ) );
k = 0;
for ( ; ; )
{
tuple_next ( 0, point_num_1d-1, dim_num, &k, indx );
if ( k == 0 )
{
break;
}
w[k-1] = 1.0;
for ( dim = 0; dim < dim_num; dim++ )
{
w[k-1] = w[k-1] * w_1d[indx[dim]];
}
for ( dim = 0; dim < dim_num; dim++ )
{
x[dim+(k-1)*dim_num] = x_1d[indx[dim]];
}
}
free ( indx );
for ( dim = 0; dim < dim_num; dim++ )
{
r[dim+0*dim_num] = r_1d[0];
r[dim+1*dim_num] = r_1d[1];
}
return;
}
/******************************************************************************/
int power_rule_size ( int point_num_1d, int dim_num )
/******************************************************************************/
/*
Purpose:
POWER_RULE_SIZE returns the size of a power rule.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
05 Febraury 2014
Author:
John Burkardt
Parameters:
Input, int POINT_NUM_1D, the number of points in the 1D rule.
Input, int DIM_NUM, the spatial dimension.
Output, int POWER_RULE_SIZE, the number of points in the rule.
*/
{
int point_num;
point_num = i4_power ( point_num_1d, dim_num );
return point_num;
}
/******************************************************************************/
double r8_epsilon ( )
/******************************************************************************/
/*
Purpose:
R8_EPSILON returns the R8 round off unit.
Discussion:
R8_EPSILON is a number R which is a power of 2 with the property that,
to the precision of the computer's arithmetic,
1 < 1 + R
but
1 = ( 1 + R / 2 )
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
01 September 2012
Author:
John Burkardt
Parameters:
Output, double R8_EPSILON, the R8 round-off unit.
*/
{
const double value = 2.220446049250313E-016;
return value;
}
/******************************************************************************/
double *r8mat_data_read ( char *input_filename, int m, int n )
/******************************************************************************/
/*
Purpose:
R8MAT_DATA_READ reads the data from an R8MAT file.
Discussion:
An R8MAT is an array of R8's.
The file is assumed to contain one record per line.
Records beginning with the '#' character are comments, and are ignored.
Blank lines are also ignored.
Each line that is not ignored is assumed to contain exactly (or at least)
M real numbers, representing the coordinates of a point.
There are assumed to be exactly (or at least) N such records.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
27 January 2005
Author:
John Burkardt
Parameters:
Input, char *INPUT_FILENAME, the name of the input file.
Input, int M, the number of spatial dimensions.
Input, int N, the number of points. The program
will stop reading data once N values have been read.
Output, double R8MAT_DATA_READ[M*N], the data.
*/
{
# define LINE_MAX 255
int error;
char *got_string;
FILE *input;
int i;
int j;
char line[255];
double *table;
double *x;
input = fopen ( input_filename, "r" );
if ( !input )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "R8MAT_DATA_READ - Fatal error!\n" );
fprintf ( stderr, " Could not open the input file: \"%s\"\n", input_filename );
exit ( 1 );
}
table = ( double * ) malloc ( m * n * sizeof ( double ) );
x = ( double * ) malloc ( m * sizeof ( double ) );
j = 0;
while ( j < n )
{
got_string = fgets ( line, LINE_MAX, input );
if ( !got_string )
{
break;
}
if ( line[0] == '#' || s_len_trim ( line ) == 0 )
{
continue;
}
error = s_to_r8vec ( line, m, x );
if ( error == 1 )
{
continue;
}
for ( i = 0; i < m; i++ )
{
table[i+j*m] = x[i];
}
j = j + 1;
}
fclose ( input );
free ( x );
return table;
# undef LINE_MAX
}
/******************************************************************************/
void r8mat_header_read ( char *input_filename, int *m, int *n )
/******************************************************************************/
/*
Purpose:
R8MAT_HEADER_READ reads the header from an R8MAT file.
Discussion:
An R8MAT is an array of R8's.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
04 June 2004
Author:
John Burkardt
Parameters:
Input, char *INPUT_FILENAME, the name of the input file.
Output, int *M, the number of spatial dimensions.
Output, int *N, the number of points.
*/
{
*m = file_column_count ( input_filename );
if ( *m <= 0 )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "R8MAT_HEADER_READ - Fatal error!\n" );
fprintf ( stderr, " FILE_COLUMN_COUNT failed.\n" );
exit ( 1 );
}
*n = file_row_count ( input_filename );
if ( *n <= 0 )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "R8MAT_HEADER_READ - Fatal error!\n" );
fprintf ( stderr, " FILE_ROW_COUNT failed.\n" );
exit ( 1 );
}
return;
}
/******************************************************************************/
void r8mat_write ( char *output_filename, int m, int n, double table[] )
/******************************************************************************/
/*
Purpose:
R8MAT_WRITE writes an R8MAT file.
Discussion:
An R8MAT is an array of R8's.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
01 June 2009
Author:
John Burkardt
Parameters:
Input, char *OUTPUT_FILENAME, the output filename.
Input, int M, the spatial dimension.
Input, int N, the number of points.
Input, double TABLE[M*N], the data.
*/
{
int i;
int j;
FILE *output;
/*
Open the file.
*/
output = fopen ( output_filename, "wt" );
if ( !output )
{
fprintf ( stderr, "\n" );
fprintf ( stderr, "R8MAT_WRITE - Fatal error!\n" );
fprintf ( stderr, " Could not open the output file.\n" );
exit ( 1 );
}
/*
Write the data.
*/
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
fprintf ( output, " %24.16g", table[i+j*m] );
}
fprintf ( output, "\n" );
}
/*
Close the file.
*/
fclose ( output );
return;
}
/******************************************************************************/
int s_len_trim ( char *s )
/******************************************************************************/
/*
Purpose:
S_LEN_TRIM returns the length of a string to the last nonblank.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
26 April 2003
Author:
John Burkardt
Parameters:
Input, char *S, a pointer to a string.
Output, int S_LEN_TRIM, the length of the string to the last nonblank.
If S_LEN_TRIM is 0, then the string is entirely blank.
*/
{
int n;
char *t;
n = strlen ( s );
t = s + strlen ( s ) - 1;
while ( 0 < n )
{
if ( *t != ' ' )
{
return n;
}
t--;
n--;
}
return n;
}
/******************************************************************************/
int s_to_i4 ( char *s, int *last, int *error )
/******************************************************************************/
/*
Purpose:
S_TO_I4 reads an I4 from a string.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
13 June 2003
Author:
John Burkardt
Parameters:
Input, char *S, a string to be examined.
Output, int *LAST, the last character of S used to make IVAL.
Output, int *ERROR is TRUE (1) if an error occurred and FALSE (0) otherwise.
Output, int *S_TO_I4, the integer value read from the string.
If the string is blank, then IVAL will be returned 0.
*/
{
char c;
int i;
int isgn;
int istate;
int ival;
*error = 0;
istate = 0;
isgn = 1;
i = 0;
ival = 0;
while ( *s )
{
c = s[i];
i = i + 1;
/*
Haven't read anything.
*/
if ( istate == 0 )
{
if ( c == ' ' )
{
}
else if ( c == '-' )
{
istate = 1;
isgn = -1;
}
else if ( c == '+' )
{
istate = 1;
isgn = + 1;
}
else if ( '0' <= c && c <= '9' )
{
istate = 2;
ival = c - '0';
}
else
{
*error = 1;
return ival;
}
}
/*
Have read the sign, expecting digits.
*/
else if ( istate == 1 )
{
if ( c == ' ' )
{
}
else if ( '0' <= c && c <= '9' )
{
istate = 2;
ival = c - '0';
}
else
{
*error = 1;
return ival;
}
}
/*
Have read at least one digit, expecting more.
*/
else if ( istate == 2 )
{
if ( '0' <= c && c <= '9' )
{
ival = 10 * (ival) + c - '0';
}
else
{
ival = isgn * ival;
*last = i - 1;
return ival;
}
}
}
/*
If we read all the characters in the string, see if we're OK.
*/
if ( istate == 2 )
{
ival = isgn * ival;
*last = s_len_trim ( s );
}
else
{
*error = 1;
*last = 0;
}
return ival;
}
/******************************************************************************/
double s_to_r8 ( char *s, int *lchar, int *error )
/******************************************************************************/
/*
Purpose:
S_TO_R8 reads an R8 value from a string.
Discussion:
We have had some trouble with input of the form 1.0E-312.
For now, let's assume anything less than 1.0E-20 is zero.
This routine will read as many characters as possible until it reaches
the end of the string, or encounters a character which cannot be
part of the real number.
Legal input is:
1 blanks,
2 '+' or '-' sign,
2.5 spaces
3 integer part,
4 decimal point,
5 fraction part,
6 'E' or 'e' or 'D' or 'd', exponent marker,
7 exponent sign,
8 exponent integer part,
9 exponent decimal point,
10 exponent fraction part,
11 blanks,
12 final comma or semicolon.
with most quantities optional.
Example:
S R
'1' 1.0
' 1 ' 1.0
'1A' 1.0
'12,34,56' 12.0
' 34 7' 34.0
'-1E2ABCD' -100.0
'-1X2ABCD' -1.0
' 2E-1' 0.2
'23.45' 23.45
'-4.2E+2' -420.0
'17d2' 1700.0
'-14e-2' -0.14
'e2' 100.0
'-12.73e-9.23' -12.73 * 10.0^(-9.23)
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
24 June 2005
Author:
John Burkardt
Parameters:
Input, char *S, the string containing the
data to be read. Reading will begin at position 1 and
terminate at the end of the string, or when no more
characters can be read to form a legal real. Blanks,
commas, or other nonnumeric data will, in particular,
cause the conversion to halt.
Output, int *LCHAR, the number of characters read from
the string to form the number, including any terminating
characters such as a trailing comma or blanks.
Output, int *ERROR, is TRUE (1) if an error occurred and FALSE (0)
otherwise.
Output, double S_TO_R8, the value that was read from the string.
*/
{
char c;
int ihave;
int isgn;
int iterm;
int jbot;
int jsgn;
int jtop;
int nchar;
int ndig;
double r;
double rbot;
double rexp;
double rtop;
char TAB = 9;
nchar = s_len_trim ( s );
*error = 0;
r = 0.0;
*lchar = -1;
isgn = 1;
rtop = 0.0;
rbot = 1.0;
jsgn = 1;
jtop = 0;
jbot = 1;
ihave = 1;
iterm = 0;
for ( ; ; )
{
c = s[*lchar+1];
*lchar = *lchar + 1;
/*
Blank or TAB character.
*/
if ( c == ' ' || c == TAB )
{
if ( ihave == 2 )
{
}
else if ( ihave == 6 || ihave == 7 )
{
iterm = 1;
}
else if ( 1 < ihave )
{
ihave = 11;
}
}
/*
Comma.
*/
else if ( c == ',' || c == ';' )
{
if ( ihave != 1 )
{
iterm = 1;
ihave = 12;
*lchar = *lchar + 1;
}
}
/*
Minus sign.
*/
else if ( c == '-' )
{
if ( ihave == 1 )
{
ihave = 2;
isgn = -1;
}
else if ( ihave == 6 )
{
ihave = 7;
jsgn = -1;
}
else
{
iterm = 1;
}
}
/*
Plus sign.
*/
else if ( c == '+' )
{
if ( ihave == 1 )
{
ihave = 2;
}
else if ( ihave == 6 )
{
ihave = 7;
}
else
{
iterm = 1;
}
}
/*
Decimal point.
*/
else if ( c == '.' )
{
if ( ihave < 4 )
{
ihave = 4;
}
else if ( 6 <= ihave && ihave <= 8 )
{
ihave = 9;
}
else
{
iterm = 1;
}
}
/*
Exponent marker.
*/
else if ( ch_eqi ( c, 'E' ) || ch_eqi ( c, 'D' ) )
{
if ( ihave < 6 )
{
ihave = 6;
}
else
{
iterm = 1;
}
}
/*
Digit.
*/
else if ( ihave < 11 && '0' <= c && c <= '9' )
{
if ( ihave <= 2 )
{
ihave = 3;
}
else if ( ihave == 4 )
{
ihave = 5;
}
else if ( ihave == 6 || ihave == 7 )
{
ihave = 8;
}
else if ( ihave == 9 )
{
ihave = 10;
}
ndig = ch_to_digit ( c );
if ( ihave == 3 )
{
rtop = 10.0 * rtop + ( double ) ndig;
}
else if ( ihave == 5 )
{
rtop = 10.0 * rtop + ( double ) ndig;
rbot = 10.0 * rbot;
}
else if ( ihave == 8 )
{
jtop = 10 * jtop + ndig;
}
else if ( ihave == 10 )
{
jtop = 10 * jtop + ndig;
jbot = 10 * jbot;
}
}
/*
Anything else is regarded as a terminator.
*/
else
{
iterm = 1;
}
/*
If we haven't seen a terminator, and we haven't examined the
entire string, go get the next character.
*/
if ( iterm == 1 || nchar <= *lchar + 1 )
{
break;
}
}
/*
If we haven't seen a terminator, and we have examined the
entire string, then we're done, and LCHAR is equal to NCHAR.
*/
if ( iterm != 1 && (*lchar) + 1 == nchar )
{
*lchar = nchar;
}
/*
Number seems to have terminated. Have we got a legal number?
Not if we terminated in states 1, 2, 6 or 7!
*/
if ( ihave == 1 || ihave == 2 || ihave == 6 || ihave == 7 )
{
*error = 1;
return r;
}
/*
Number seems OK. Form it.
We have had some trouble with input of the form 1.0E-312.
For now, let's assume anything less than 1.0E-20 is zero.
*/
if ( jtop == 0 )
{
rexp = 1.0;
}
else
{
if ( jbot == 1 )
{
if ( jsgn * jtop < -20 )
{
rexp = 0.0;
}
else
{
rexp = pow ( ( double ) 10.0, ( double ) ( jsgn * jtop ) );
}
}
else
{
if ( jsgn * jtop < -20 * jbot )
{
rexp = 0.0;
}
else
{
rexp = jsgn * jtop;
rexp = rexp / jbot;
rexp = pow ( ( double ) 10.0, ( double ) rexp );
}
}
}
r = isgn * rexp * rtop / rbot;
return r;
}
/******************************************************************************/
int s_to_r8vec ( char *s, int n, double rvec[] )
/******************************************************************************/
/*
Purpose:
S_TO_R8VEC reads an R8VEC from a string.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
19 February 2001
Author:
John Burkardt
Parameters:
Input, char *S, the string to be read.
Input, int N, the number of values expected.
Output, double RVEC[N], the values read from the string.
Output, int S_TO_R8VEC, is TRUE (1) if an error occurred and FALSE (0)
otherwise.
*/
{
int error;
int i;
int lchar;
error = 0;
for ( i = 0; i < n; i++ )
{
rvec[i] = s_to_r8 ( s, &lchar, &error );
if ( error )
{
return error;
}
s = s + lchar;
}
return error;
}
/******************************************************************************/
int s_word_count ( char *s )
/******************************************************************************/
/*
Purpose:
S_WORD_COUNT counts the number of "words" in a string.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
30 January 2006
Author:
John Burkardt
Parameters:
Input, char *S, the string to be examined.
Output, int S_WORD_COUNT, the number of "words" in the string.
Words are presumed to be separated by one or more blanks.
*/
{
int blank;
int i;
int word_num;
word_num = 0;
blank = 1;
while ( *s )
{
if ( *s == ' ' || *s == '\n' )
{
blank = 1;
}
else if ( blank )
{
word_num = word_num + 1;
blank = 0;
}
*s++;
}
return word_num;
}
/******************************************************************************/
void timestamp ( )
/******************************************************************************/
/*
Purpose:
TIMESTAMP prints the current YMDHMS date as a time stamp.
Example:
31 May 2001 09:45:54 AM
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
24 September 2003
Author:
John Burkardt
Parameters:
None
*/
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct tm *tm;
size_t len;
time_t now;
now = time ( NULL );
tm = localtime ( &now );
len = strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm );
printf ( "%s\n", time_buffer );
return;
# undef TIME_SIZE
}
/******************************************************************************/
void tuple_next ( int m1, int m2, int n, int *rank, int x[] )
/******************************************************************************/
/*
Purpose:
TUPLE_NEXT computes the next element of a tuple space.
Discussion:
The elements are N vectors. Each entry is constrained to lie
between M1 and M2. The elements are produced one at a time.
The first element is
(M1,M1,...,M1),
the second element is
(M1,M1,...,M1+1),
and the last element is
(M2,M2,...,M2)
Intermediate elements are produced in lexicographic order.
Example:
N = 2, M1 = 1, M2 = 3
INPUT OUTPUT
------- -------
Rank X Rank X
---- --- ----- ---
0 * * 1 1 1
1 1 1 2 1 2
2 1 2 3 1 3
3 1 3 4 2 1
4 2 1 5 2 2
5 2 2 6 2 3
6 2 3 7 3 1
7 3 1 8 3 2
8 3 2 9 3 3
9 3 3 0 0 0
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
29 April 2003
Author:
John Burkardt
Parameters:
Input, int M1, M2, the minimum and maximum entries.
Input, int N, the number of components.
Input/output, int *RANK, counts the elements.
On first call, set RANK to 0. Thereafter, the output value of RANK
will indicate the order of the element returned. When there are no
more elements, RANK will be returned as 0.
Input/output, int X[N], on input the previous tuple.
On output, the next tuple.
*/
{
int i;
int j;
if ( m2 < m1 )
{
*rank = 0;
return;
}
if ( *rank <= 0 )
{
for ( i = 0; i < n; i++ )
{
x[i] = m1;
}
*rank = 1;
}
else
{
*rank = *rank + 1;
i = n - 1;
for ( ; ; )
{
if ( x[i] < m2 )
{
x[i] = x[i] + 1;
break;
}
x[i] = m1;
if ( i == 0 )
{
*rank = 0;
for ( j = 0; j < n; j++ )
{
x[j] = m1;
}
break;
}
i = i - 1;
}
}
return;
}
|
C | /* LzmaRamDecode.h */
#ifndef __LzmaRamDecode_h
#define __LzmaRamDecode_h
#include <stdlib.h>
/*
LzmaRamGetUncompressedSize:
In:
inBuffer - input data
inSize - input data size
Out:
outSize - uncompressed size
Return code:
0 - OK
1 - Error in headers
*/
int LzmaRamGetUncompressedSize(
const unsigned char *inBuffer,
size_t inSize,
size_t *outSize);
/*
LzmaRamDecompress:
In:
inBuffer - input data
inSize - input data size
outBuffer - output data
outSize - output size
allocFunc - alloc function (can be malloc)
freeFunc - free function (can be free)
Out:
outSizeProcessed - processed size
Return code:
0 - OK
1 - Error in headers / data stream
2 - Memory allocating error
Memory requirements depend from properties of LZMA stream.
With default lzma settings it's about 16 KB.
*/
int LzmaRamDecompress(
const unsigned char *inBuffer,
size_t inSize,
unsigned char *outBuffer,
size_t outSize,
size_t* outSizeProcessed,
void * (*allocFunc)(size_t size),
void (*freeFunc)(void *));
#endif
|
C |
#include<stdio.h>
#define Max 10
int Q[20];
int front=-1,rear=-1,data;
void exit();
void insert_Q()
{
if(front==0 && rear==Max-1)
{
printf("\n\t\t\t!......Q_Overflow......!\n");
}
else if(front!=0 && rear==Max-1)
{
rear=0;
printf("\n\t\t\tEnter data:");
scanf("%d",&Q[rear]);
rear=rear+1;
if(rear==front-1)
{
printf("\n\t\t\t!......Q_Underflow......!\n");
}
}
else //if(rear!=Max-1)
{
if(front==-1 && rear==-1)
{
front=0;
rear=0;
}
else
{
rear=rear+1;
}
printf("\n\t\t\tEnter data:");
scanf("%d",&data);
Q[rear]=data;
}
}
void delete_Q()
{
if(front==-1 && rear==-1)
{
printf("\n\t\t\t!......Q_Underflow......!\n");
}
else if(front==rear)
{
data=Q[front];
front=-1;
rear=-1;
printf("\n\t\t\t\t%d is deleted successfully\n",data);
}
else
{
if(front==Max-1)
{
data=Q[front];
printf("\n\t\t\t\t%d is deleted successfully\n",data);
front=0;
}
else
{
data=Q[front];
front=front+1;
printf("\n\t\t\t\t%d is deleted successfully\n",data);
}
}
}
void Q_Display()
{
int temp;
if(front==-1 && rear==-1)
{
printf("\n\t\t\t\t\t\t!!......Q_Underflow......!!\n");
}
else
{
temp=front;
printf("\n\t\t\t\t\t\t>>>>>..Data Display..<<<<<<\n");
printf("\n");
while(temp!=rear)
{
printf("\n\t\t\t");
printf("%d",Q[temp]);
temp=temp+1;
}
printf("\n\t\t\t");
printf("%d",Q[temp]);
}
}
void main()
{
int ch;
do
{
printf("\n\t\t\t\t\t______Circular Queue Array Menu Driven Programme______\n");
printf("\n\n\t\t\t\t\t\tH\tO\tM\tE\n");
printf("\t\t1.EN_Q\n\t\t2.DE_Q\n\t\t3.Display_Q\n\t\t4.Exit\n");
printf("\n\t\t\tEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: insert_Q();
break;
case 2: delete_Q();
break;
case 3: Q_Display();
break;
case 4: exit(0);
default: printf("\n\t\t\t!!!!.......Wrong choice.....!!!!....\n");
printf("\n\t\t******* _____Programme_____*******\n");
}
}while(ch!=4);
}
|
C | /*
* FM hello world
* based on Programming the AdLib/Sound Blaster FM Music Chips
* http://www.shipbrook.net/jeff/sb.html
*
* Tested with djgpp and DOSBox
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define ADDR_PORT 0x388
#define DATA_PORT 0x389
typedef char* string;
void outb(const int port, const char data) {
__asm __volatile("outb %0,%w1" : : "a" (data), "d" (port));
}
int inb(const int port) {
char data;
__asm __volatile("inb %w1,%0" : "=a" (data) : "d" (port));
return data;
}
void msleep(const int microsecs) {
const int wait = 1000000 / microsecs;
const uclock_t start = uclock();
while (uclock() < start + UCLOCKS_PER_SEC / wait);
}
void write(const int reg, const int value) {
printf("write %x to %x\n", value, reg);
outb(ADDR_PORT, reg);
msleep(4);
outb(DATA_PORT, value);
msleep(24);
}
void reset_sound() {
int i, j;
write(1, 0);
write(2, 0);
write(3, 0);
write(4, 0);
write(8, 0);
for (i = 0; i < 4; ++i) {
for (j = 0; j <= 0x15; ++j) {
write(0x20 + (0x20 * i) + j, 0);
}
}
for (i = 0; i < 3; ++i) {
for (j = 0; j <= 8; ++j) {
write(0xa0 + (0x10 * i) + j, 0);
}
}
write(0xbd, 0);
for (i = 0; i <= 5; ++i) {
write(0xe0 + i, 0);
}
}
void make_a_sound() {
write(0x20, 0x01); // Set the modulator's multiple to 1
write(0x40, 0x10); // Set the modulator's level to about 40 dB
write(0x60, 0xf0); // Modulator attack: quick; decay: long
write(0x80, 0x77); // Modulator sustain: medium; release: medium
write(0xa0, 0x98); // Set voice frequency's LSB (it'll be a D#)
write(0x23, 0x01); // Set the carrier's multiple to 1
write(0x43, 0x00); // Set the carrier to maximum volume (about 47 dB)
write(0x63, 0xf0); // Carrier attack: quick; decay: long
write(0x83, 0x77); // Carrier sustain: medium; release: medium
write(0xb0, 0x31); // Turn the voice on; set the octave and freq MSB
sleep(1);
write(0xb0, 0x11);
}
int main(int argc, char** argv) {
printf("start\n");
reset_sound();
make_a_sound();
reset_sound();
printf("end\n");
return EXIT_SUCCESS;
}
|
C | //
// Created by hlhd on 2021/5/7.
//
#include "../all.h"
void stdInCallbackEP(evutil_socket_t fd, short what, void* arg)
{
char buf[1024];
printf("stdin_callback start %s\n", (char*)arg);
int ret = read(fd, buf, sizeof(buf));
buf[ret] = '\0';
printf("buf is %s\n", buf);
printf("stdin_callback end %s\n", (char*)arg);
}
int mainep()
{
struct event_base* base = event_base_new();
event_base_priority_init(base, 4);
struct event* ev0 = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST, stdInCallbackEP, "ev0");
event_priority_set(ev0, 3);
event_add(ev0, NULL);
// two event -- same fd
struct event* ev1 = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST, stdInCallbackEP, "ev1");
event_priority_set(ev1, 2);
event_add(ev1, NULL);
/* event loop */
event_base_dispatch(base);
event_base_free(base);
event_free(ev0); // "event_base" first free, "event" then free. But why??
event_free(ev1);
return 0;
}
|
C | /**
* Ŀʹõĺ궨塣
*/
#include <NkUtils/types.h>
#include <NkUtils/log.h>
#include <string.h>
#ifndef NK_ASSERT_H_
#define NK_ASSERT_H_
NK_CPP_EXTERN_BEGIN
/**
* ʱ㡣
*/
#define NK_CHECK_POINT() \
do {\
NK_PChar file = strrchr(__FILE__, '/');\
printf("\r\n-- @ %s:%d \r\n\r\n", !file ? __FILE__ : file + 1, __LINE__);\
} while(0)
/**
* ʱԡ
*/
#define NK_ASSERT(__exp) \
do{\
if(!(__exp)){\
NK_Log()->alert("\"%s()\" Assertion Condition ( \"%s\" ) @ %d.", __PRETTY_FUNCTION__, #__exp, __LINE__);\
exit(1);\
}\
}while(0)
#define NK_ASSERT_TRUE(__condition) \
NK_ASSERT(__condition)
#define NK_ASSERT_FALSE(__condition) \
NK_ASSERT(!(__condition))
#define NK_TEST_(__condition, __verbose) \
((__condition) ? NK_True : \
(((__verbose) ? NK_Log()->warn("\"%s() @ %d\" Expect Condition ( \"%s\" ).", __PRETTY_FUNCTION__, __LINE__, #__condition) : 0), NK_False))
#define NK_TEST(__condition) \
NK_TEST_(__condition, NK_True)
#define NK_EXPECT(__condition) \
do{\
if (!NK_TEST_(__condition, NK_False)){\
return;\
}\
}while(0)
#define NK_EXPECT_RETURN(__condition, __ret) \
do{\
if (!NK_TEST_(__condition, NK_False)){\
return(__ret);\
}\
}while(0)
#define NK_EXPECT_JUMP(__condition, __location) \
do{\
if (!NK_TEST_(__condition, NK_False)){\
goto __location;\
}\
}while(0)
#define NK_EXPECT_VERBOSE(__condition) \
do{\
if (!NK_TEST_(__condition, NK_True)){\
return;\
}\
}while(0)
#define NK_EXPECT_VERBOSE_RETURN(__condition, __ret) \
do{\
if (!NK_TEST_(__condition, NK_True)){\
return(__ret);\
}\
}while(0)
#define NK_EXPECT_VERBOSE_JUMP(__condition, __location) \
do{\
if (!NK_TEST_(__condition, NK_True)){\
goto __location;\
}\
}while(0)
NK_CPP_EXTERN_END
#endif /* NK_ASSERT_H_ */
|
C | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <cs50.h>
string ari(string s) {
string grade;
float chara = 0, word = 0, sentence = 0;
for(int i = 0; i<strlen(s); i++) {
if(isalnum(s[i])) {
chara = chara + 1;
}
if(s[i]==' ') {
word = word +1;
}
if(s[i]=='.' || s[i]=='?' || s[i]=='!') {
sentence = sentence + 1;
}
}
float num1 = 4.71 * (chara/word);
float num2 = 0.5 * (word/sentence);
float num = num1 + num2 - 21.43;
// printf("%f\n", num);//
int b = 0;
if(num==(int)num) {
b = (int)num;
}
else if(num>(int)num) {
b = (int)num + 1;
}
//printf("%d\n", b);//
if(b==1) {
grade = "Kindergarten";
}
if(b==2) {
grade="First/Second Grade";
}
if(b==3) {
grade="Third Grade";
}
if(b==4) {
grade="Fourth Grade";
}
if(b==5) {
grade="Fifth Grade";
}
if(b==6) {
grade="Sixth Grade";
}
if(b==7) {
grade="Seventh Grade";
}
if(b==8) {
grade="Eighth Grade";
}
if(b==9) {
grade="Ninth Grade";
}
if(b==10) {
grade="Tenth Grade";
}
if(b==11) {
grade="Eleventh Grade";
}
if(b==12) {
grade="Twelfth Grade";
}
if(b==13) {
grade="College Student";
}
if(b==14) {
grade="Professor";
}
//printf("%s\n", grade);//
return grade;
}
|
C | #include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define cuenta 472395814
//FUNCION DEPOSITO
float depo(float capital,float d){
float saldo;
capital+=(capital*0.0125)+d;
return(capital);
}
//FUNCION RETIRO
float ret(float capital,float retiro){
float saldo;
capital=capital-retiro;
return(capital);
}
//FUNCION TRANSFERENCIA
float transfer(float capital,float trans){
float saldo;
capital=capital-trans;
return(capital);
}
//PROGRAMA PRINCIPAL
int main(){
int menu[99],i;
float monto[99];
float capital,deposito,transferencia,opc,cont,saldo,retiro,contret,conttran,acum,contdep;
int contrase;
cont=0;
contdep=0;
contret=0;
conttran=0;
acum=0;
i=0;
char nombre[50];
printf("\t**BIENVENIDO AL BANCO ABC**\n");
printf("Por favor ingrese su nombre \n");
gets(nombre);
printf("Ingrese su numero de cuenta\n");
scanf("%d",&contrase);
system("CLS");
if(contrase!=cuenta){
do{
system("CLS");
printf("Numero de cuenta invalido\n");
printf("Ingrese su numero de cuenta\n");
scanf("%d"",&contrase);
system("CLS");
}while(contrase!=cuenta);}
if(contrase==cuenta){
printf("\t SEA BIENVENIDO A SU CUENTA\n");
printf("Ingrese su capital\n");
scanf("%f",&capital);
if(capital>=100){
do{
printf("\nESCOJA LA OPCION QUE DESEA REALIZAR\n");
printf("1.Deposito \n2.Retiro \n3.Transferencia \n4.Salir \OPCION:");
scanf("%f",opc);
system("CLS");
if(opc>4 ||opc<1){
printf("Opcion no valida\n");
printf("Por favor ingrese una opcion valida\n");
}
//DEPOSITO
if(opc==1){
if(cont<=99){
i++;
printf("Ingrese el monto que desea depositar\n");
scanf("%f";&deposito);
saldo=depo(capital,deposito);
capital+=(capital*0.0125)+deposito;
printf("Su saldo actual es de:%f,saldo");
contdep++;
monto[i]=deposito;
menu[i]=1;}
else{
printf("Usted ha alcanzado el numero maximo de transacciones");
printf("Su saldo actual es de:%f",saldo);
}
}
//RETIRO
if(opc==2){
if(contret>=4 || cont>=100){
printf("Lo sentimos, usted ha alcanzado el maximo de retiros o transacciones por dia\n");}
if(contret<=3 && cont<=99 && acum<1500){
i++;
printf("Ingrese el monto que desea retirar\n");
scanf("%f",&retiro);
saldo=ret(capital-retiro);
contret++;
// cont++;
acum=acum+retiro;
monto[i]=retiro;
menu[i]=2;
}
if(retiro>1500){
i--;
printf("Usted no puede retirar esta cantidad ya que su capital quedara bpor debajo de los 100 dolares\n");
capital=capital+retiro;
saldo=saldo+retiro;
//cont--;
contret--;
acum=acum-retiro;
}
if(acum>=1500){
i--;
printf("Usted ha alcanzado el monto maximo que puede retirar\n");
}
printf("Su saldo actual es de:%f,saldo");
}
//TRANSFERENCIA
if(opc==3){
if(conttran>2 || cont>=100){
i--;
printf("Lo sentimos,usted ha alcanzado el numero maximo de transferencias o transacciones posibles\n");
}
if(conttran<=2 && cont<=99){
i++;
printf("Ingrese el monto que desea transferir\n");
scanf("%f,&transferencia");
saldo=transfer(capital,transferencia);
capital=capital-transferencia;
//cont++;
conttran++;
menu[i]=3;
monto[i]=transferencia;}
if(saldo<100){
i--;
printf("Usted no puede retirar esta cantidad quedara por debajo de los 100 dolares\n");
capital=capital+retiro;
saldo=saldo+transferencia;
//cont++;
conttran--;
}
printf("Su saldo actual es de:%f", saldo);
}
cont=contdep+conttran;
if(opc==4){
printf("\t BANCO ABC-ESTADO DE CUENTA\n");
printf("Cliente:%s,nombre");
printf("\nN de Cuenta:%d,contrase");
printf("nN\t Tipo de transaccion \t Monto\n");
for(i=4;i<=cont;i++){
printf("%i",i);
if(menu[i]==1){
printf("\t DEPOSITO");
printf("\t\t%.2f\n",monto[i]);}
else if(menu[i]==2){
printf("\t RETIRO\t\t\t %2.f\n";monto[i]);}
else if(menu[i]==3){
printf("\t TRANSFERENCIA\t\t %2.f\n",monto[i]);}
}
printf("\n Su saldo es:%f",capital);
}
}while(opc==1|| opc==2|| opc==3 || opc>4 || opc<1);
}
else{
printf("Usted no puede tener un capital menor a 100");
}
}
}
|
C | // made by Ankit Das
// on 15 July 2020
// tested on gcc 8
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
int MAX = 0;
void display(int *array)
{
int i = 0;
printf("\n");
for(i = 0; i < MAX; i++)
printf("%d ",*(array + i));
printf("\n");
}
void insert(int *array, int n, int data)
{
int i = 0;
if( n > MAX + 1 || n < 1)
printf("\nINVALID OPERATION!");
else{
for(i = MAX; i >= n - 1; i--)
*(array + (i+1)) = *(array + i);
*(array + (n - 1)) = data;
MAX++;
display(array);
}
}
void delete(int *array, int n)
{
int i = 0;
if( n > MAX || n < 0)
printf("\nINVALID OPERATION");
else{
for(i = n; i < MAX; i++)
*(array + (i - 1)) = *(array + i);
*(array + MAX) = 0;
MAX--;
display(array);
}
}
void Edelete(int *array, int element) // wrapper function for delete, just finds the location
{
int i = 0;
bool found = false;
for(i = 0; i < MAX; i++)
if(*(array + i) == element)
{
delete(array,i+1);
found = true;
break;
}
if(!found)
printf("\nELEMENT NOT FOUND!");
}
void search(int *array, int n)
{
if( n > MAX + 1 || n < 0)
printf("\nINVALID OPERATION");
else
printf("\nELEMENT AT %d is %d",n,*(array + (n - 1)));
display(array);
}
void Esearch(int *array, int n)
{
bool found = false;
int i = 0;
for(i = 0; i <= MAX; i++)
if(*(array + i) == n)
{
printf("\nELEMENT %d FOUND AT %d",n,i+1);
found = true;
}
if(!found)
printf("\nELEMENT NOT FOUND!");
display(array);
}
void reverse(int *array)
{
int i = 0;
int j = MAX - 1;
int save = 0;
while(i < j){
array[i] = array[i] + array [j];
array[j] = array[i] - array [j];
array[i] = array[i] - array[j];
i++;
j--;
}
display(array);
}
void main()
{
printf("ENTER INITIAL SIZE OF ARRAY: ");
scanf("%d",&MAX);
int i = 0;
int *array = calloc(MAX,sizeof(int)); // dynamically allocate memory to a pointer
for(i = 0; i <= MAX; i++) // array initialization is required in case of dev-c. can be omitted if using gcc
*(array + i) = 0;
bool run = true;
int choice = 0, count = 0;
int n = 0, data = 0;
while(run){ // while run is true, the program runs
printf("\n\n-- MENU --"); // MAIN MENU
printf("\n1.INSERT AT POSITION");
printf("\n2.INSERT AT BEGINNING");
printf("\n3.INSERT AT END");
printf("\n4.DELETE AT POSITION");
printf("\n5.DELETE BY ELEMENT");
printf("\n6.SEARCH BY POSITION");
printf("\n7.SEARCH BY ELEMENT");
printf("\n8.REVERSE ARRAY");
printf("\n9.EXIT");
printf("\n\nENTER YOUR CHOICE:");
scanf("%d", &choice);
if(choice < 8)
scanf("%d",&n);
switch (choice)
{
case 1:
scanf("%d",&data);
insert(array,n,data);
break;
case 2:
insert(array,1,n);
break;
case 3:
insert(array,MAX+1,n);
break;
case 4:
delete(array,n);
break;
case 5:
Edelete(array,n);
break;
case 6:
search(array,n);
break;
case 7:
Esearch(array,n);
break;
case 8:
reverse(array);
break;
case 9:
run = false;
break;
default:
printf("\nERROR! ENTER A VALID CHOICE");
break;
}
}
free(array); // free allocated memory
}
|
C | /* bgrep - A binary grep tool. */
#include "blib.h"
#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x20
int flip_pe_la_flag(char* name) {
map_file(name, WRITE_FILE);
if( CH_BUF(0) != 'M' || CH_BUF(1) != 'Z' )
goto invalid_ret; // MZ header missing.
uint32_t pe_loc = U32_BUF(0x3C);
if ( U32_BUF(pe_loc) != 0x4550 )
goto invalid_ret; // No PE header here.
pe_loc += 0x12;
U16_BUF(pe_loc) ^= IMAGE_FILE_LARGE_ADDRESS_AWARE; // Toggle it.
// Succeeded
unmap_file();
return 0;
invalid_ret:
unmap_file();
return 1;
}
int check_pe_la_flag(char* name) {
map_file(name, READ_FILE);
if( CH_BUF(0) != 'M' || CH_BUF(1) != 'Z' )
goto invalid_ret; // MZ header missing.
uint32_t pe_loc = U32_BUF(0x3C);
if ( U32_BUF(pe_loc) != 0x4550 )
goto invalid_ret; // No PE header here.
pe_loc += 0x12;
if( !(U16_BUF(pe_loc) & IMAGE_FILE_LARGE_ADDRESS_AWARE) )
goto no_ret; // Not LA aware, is PE
// LA aware PE image.
unmap_file();
return 0;
no_ret:
unmap_file();
return 1;
invalid_ret:
unmap_file();
return 2;
}
int check_pe(char* name) {
map_file(name, READ_FILE);
if( CH_BUF(0) != 'M' || CH_BUF(1) != 'Z' )
goto invalid_ret; // MZ header missing.
uint32_t pe_loc = U32_BUF(0x3C);
if ( U32_BUF(pe_loc) != 0x4550 )
goto invalid_ret; // No PE header here.
unmap_file();
return 0; // Is PE
invalid_ret:
unmap_file();
return 1; // Not PE
}
void help(char* name) {
printf("%s bflag\n", PACKAGE_STRING);
printf("(C) 2015 Jon Feldman (@chaoskagami) <%s>\n", PACKAGE_BUGREPORT);
printf("Usage:\n");
printf(" %s [args] file ...\n", name);
printf("Options (PE Images):\n");
printf(" -v Show information on file\n");
printf(" -L Flip the large address aware bit\n");
printf("Report bugs to <%s>\n", PACKAGE_URL);
printf("This software is licensed under the MIT license.\n");
}
int main(int argc, char** argv) {
int opt;
int do_op = 0;
while ( (opt = getopt(argc, argv, "hvL")) != -1) {
switch(opt) {
case 'h':
help(argv[0]);
return 0;
break;
case 'v':
do_op = 1; // View
break;
case 'L':
do_op = 2; // Flip LA flag
break;
case '?':
fprintf(stderr, "error: unknown option. Run with -h for more info\n");
return 1;
default:
fprintf(stderr, "error: unknown option. Run with -h for more info\n");
return 1;
}
}
if (optind == argc) {
fprintf(stderr, "error: requires a file argument. Run with -h for more info\n");
return 1;
}
int ret = 0;
switch(do_op) {
case 0:
fprintf(stderr, "error: no operation specified\n");
return 1;
case 1: // View flags
printf("Is PE Image: ");
ret = check_pe(argv[optind]);
if (ret == 0) {
printf("Yes\n");
printf("Large Address Aware: ");
ret = check_pe_la_flag(argv[optind]);
if (ret == 0) {
printf("Yes\n");
} else {
printf("No\n");
}
} else {
printf("No\n");
}
break;
case 2:
ret = flip_pe_la_flag(argv[optind]);
if (ret == 0)
printf("Flipped the LA bit.\n");
else
printf("Failed to flip LA bit.\n");
break;
}
}
|
C | #include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
int n,i;
int x;
scanf("%d", &n);
int pre[n];
for(i=0; i<n; i++){
scanf("%d", &x);
pre[x-1]=i+1;
}
for(i=0; i<n; i++){
printf("%d", pre[i]);
}
return 0;
}
|
C | #include <stdio.h>
int main(){
int a[10];
a = {1,2,3,4,5,6,7,8,9,10};
int i;
printf("the size of an integer in my version of C is %d\n",sizeof(int));
printf("a is %d\n",a);
for (i=0;i<10;i++){
printf("the ADDRESS of a[%d] is %d\n",i, &(a[i]));
}
return 0;
}
|
C | #include "stdlib.h"
#include "stdio.h"
#include "string.h"
void inverseArr(char *myArr){
char *p1 = NULL;
p1 = myArr;
if(*p1 == '\0' || p1 == NULL) return;
inverseArr(p1+1); //˴ȲִУջȳ
printf("%c",*p1);
}
int main(){
char *p1 = "avsbfgsfg";
int len1 = strlen(p1);
inverseArr(p1);
return 0;
}
|
C | /**
* @file pthread_ex.h
* @brief function definitions for threading example in hw3
* @author Andrew Kuklinski
* @date 02/18/2018
**/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
extern pthread_mutex_t locking;
//struct to be used to pass information between threads
typedef struct{
int member1;
int member2;
//FILE *hw3log;
char * inputfile;
}input_var; //struct is shared by all threads
//function to report CPU utilization metrics to a log file
void *metrics_fxn(void *param);
//function to search a file and produce a linked list of the contents
void* llsearch_fxn(void *param);
//signal handler to exit metric thread
void metric_exit(int signum);
//signal handler to exit search thread
void search_exit(int signum);
/*create, initialize, and start a posix counter that sends
*a signal to run a function. arguments: how many nanoseconds between
*timer roll over*/
void metric_counter_init(unsigned long long int firedelay) ;
|
C | #include <stdio.h>
#define MAX(x, y) ( ((x) > (y)) ? (x) : (y))
#define MIN(x, y) ( ((x) < (y)) ? (x) : (y))
#define N 7
int policzWode(int *histogram);
int main(){
int histogram[N] = {3, 5, 4, 2, 1, 7, 2};
printf("Maksymalny stan zgromadzonej wody wynosi %d.\n", policzWode(histogram));
return 0;
}
int policzWode(int *histogram){
int h_lewy[N];
int h_prawy[N];
int woda = 0;
h_lewy[0] = histogram[0];
for (int l = 0; l < N; ++l){
h_lewy[l] = MAX(h_lewy[l - 1], histogram[l]);
}
h_prawy[N - 1] = histogram[N - 1];
for (int p = N - 2; p >= 0; --p){
h_prawy[p] = MAX(histogram[p], h_prawy[p+1]);
}
for (int k = 0; k < N; ++k){
woda += MIN(h_lewy[k], h_prawy[k]) - histogram[k];
}
return woda;
}
|
C | // ------------------------------------------------------------------------
// NAME: Victor Gorchilov
// CLASS: 11a
// NUMBER: 8
// PROBLEM: #1
// FILE NAME: strlen.c (unix file name)
// FILE PURPOSE: creating strlen without use of library
// ------------------------------------------------------------------------
#include <stdio.h>
size_t strlen(const char *string) {
//------------------------------------------------------------------------
// FUNCTION: strlen
// finding length of a string
// PARAMETERS:
// a string to get length of
//------------------------------------------------------------------------
size_t size = 0;
while (string[size]) {
size++;
}
return size;
}
int main() {
char str[100];
fgets(str, 100, stdin);
printf("Lenght of string: %lu\n", strlen(str));
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include"answer10.h"
#include<strings.h>
#include<inttypes.h>
char** explode(const char* str, const char* delims,int* arrLen)
{
int num_delim = 0; // No. of delimiters in the string 'delims'
int str_index = 0; // String Index
// This Below loop is used find out how many delimiters are in the string 'delims'
while(str[str_index] != '\0')
{
if(strchr(delims,str[str_index]) != NULL)
{
num_delim += 1;
}
str_index++;
}
char** strArr = malloc((num_delim + 1) * sizeof(char*)); // This Allocates spaces to create (num_delim + 1) strings.
int strArr_count = 0; // Flag for the no.of strings that can be accomodated in strArr
int last_ind = 0; // Used to get the position where a character is last found.
int i = 0; // Index to check the strlen of str
while(i <= strlen(str))
{
if(strchr(delims,str[i]) == NULL)
{
i++;
}
else
{
//if(i > last_ind)
{
strArr[strArr_count] = malloc(sizeof(char)*(i - last_ind + 1));
memcpy(strArr[strArr_count],&str[last_ind],(i - last_ind));
strArr[strArr_count][i - last_ind] = '\0';
strArr_count += 1; // Flag to exit the loop if all the memory is utilised
}
i++;
last_ind = i;
}
}
*arrLen = num_delim + 1; // No.of Strings that are Returned.
return(strArr);
}
typedef struct review
{
int no_reviews;
long int offset; // For the reviews.tsv
}ReviewNode;
typedef struct location
{
struct location* next;
long int offset; // For the businesses.tsv
int bus_id; // Id of a Business's different Location
ReviewNode reviews;
}LocationNode;
typedef struct business
{
//BusinessNode* Root = NULL;
struct business* Left;
struct business* Right;
LocationNode* location;
char* BusinessName;
}BusinessNode;
typedef struct YelpDataBST
{
char* BusFile;
char* RevFile;
BusinessNode* BNode;
}YelpData;
BusinessNode* create_business(char* businessname)
{
BusinessNode* busNode = malloc(sizeof(BusinessNode)); // Have to allocate memory for the Business Node
busNode -> BusinessName = strdup(businessname); // strdup is done in another function
busNode -> Left = NULL; // Left Branch of the Binary Tree.
busNode -> Right = NULL; // Right Branch of the Binary Tree.
busNode -> location = NULL; // Used for storing the Address of different locations of a single business.
return(busNode);
}
LocationNode* create_Location(long int bus_offset, long int rev_offset, int count,int business_id)
{
LocationNode* locNode = malloc(sizeof(LocationNode));
locNode -> offset = bus_offset;
locNode -> next = NULL;
locNode -> bus_id = business_id;
(locNode -> reviews).offset = rev_offset;
(locNode -> reviews).no_reviews = count;
return locNode;
}
/* The Below Function is Used to insert the entering node at the End. */
LocationNode* Location_list(LocationNode* head,long int bus_offset,long int rev_offset,int count,int business_id)
{
if(head == NULL)
{
return(create_Location(bus_offset,rev_offset,count,business_id));
}
head -> next = Location_list(head -> next, bus_offset,rev_offset,count,business_id);
return(head);
}
uint32_t Loclist_length(LocationNode* loclist)
{
uint32_t length = 0;
LocationNode* list = loclist;
while(list != NULL)
{
length += 1;
list = list -> next;
}
return(length);
}
// This is to print the Reviews of the Each Independent Business location.
/*void print_Locations(LocationNode* head, const char* filename_bus,const char* filename_rev)
{
FILE* fp_bus = fopen(filename_bus,"r"); // for Businesses.tsv
FILE* fp_rev = fopen(filename_rev,"r"); // For Reviews.tsv
char* str_bus = malloc(sizeof(char)* 6000); // Used to read and Print the address of the business Location.
char* str_rev = malloc(sizeof(char)* 6000); // Used to read and print the review of the business Location.
int count_rev = 0; // For printing all the reviews.
//long int offset_rev =
while(head != NULL)
{
fseek(fp_bus,head -> offset,SEEK_SET); // makes the File Pointer Read at the offset from the beginning of the file.
if(fgets(str_bus,6000,fp_bus) != NULL)
{
printf(" %.80s\n",str_bus); // Prints the Business Name and Address
count_rev = (head -> reviews).no_reviews; // Gets the no.of reviews.
fseek(fp_rev,(head -> reviews).offset,SEEK_SET);
if(fgets(str_rev,6000,fp_rev) != NULL)
{
// This Below loop is used to print the reviews of a business Location.
while(count_rev > 0)
{
printf(" %.70s\n",str_rev); // Prints review from a specific Customer.
fseek(fp_rev,1 + (int)(floor(log10(head -> bus_id)) + 1),SEEK_CUR);
fgets(str_rev,6000,fp_rev);
count_rev -= 1;
}
}
// printf("Offset is %ld",head -> offset);
}
head = head -> next;
}
free(str_bus); // Have to free this
free(str_rev); // Have to free this...
fclose(fp_bus);
fclose(fp_rev);
} */
// CREATING THE BUSINESS BINARY TREE
BusinessNode* create_BST(char* business, BusinessNode* root,long int bus_offset,long int rev_offset, int count,int business_id)
{
if(root == NULL)
{
BusinessNode* bus_node = create_business(business); // This Business Node has to created first.
bus_node -> location = create_Location(bus_offset,rev_offset,count,business_id); // Location is created pointing from that Business Location.
return bus_node; // Creates and Inserts the Node at the NULL.
}
// Here We add the Address of the Business Location(Offset in businesses.tsv File) to the location linked list (Because We do not need to add the same business name)
if(strcasecmp(business , root -> BusinessName) == 0)
{
root -> location = Location_list(root -> location,bus_offset,rev_offset,count,business_id);
}
if(strcasecmp(business , root -> BusinessName) < 0)
{
root -> Left = create_BST(business,root -> Left,bus_offset,rev_offset,count,business_id); // Inserts the Node in the Left Side of the Binary Tree.
}
if(strcasecmp(business , root -> BusinessName) > 0)
{
root -> Right = create_BST(business, root -> Right,bus_offset,rev_offset,count,business_id); // Inserts the Node in the Right Side of the Binary Tree.
}
return(root);
}
/*void print_tree(BusinessNode* Root,const char* filename1,const char* filename2)
{
if(Root == NULL)
{
return;
}
print_tree(Root -> Left,filename1,filename2); // Prints the Left Side of the Tree
printf("\n\nThe Business Name is %s at ",Root -> BusinessName);
print_Locations(Root -> location,filename1,filename2);
print_tree(Root -> Right,filename1,filename2); // Print the Right Side of the Tree
//fclose(fp);
} */
// Destroying the Location List
void destroy_Loclist(LocationNode* location)
{
while(location != NULL)
{
LocationNode* locpointer = location -> next;
free(location);
location = locpointer;
}
}
void destroy_BST(BusinessNode* Root)
{
if(Root == NULL)
{
return;
}
// Destroys the Left Part of the Tree
destroy_BST(Root -> Left);
// Destroys the Right part of the Tree
destroy_BST(Root -> Right);
destroy_Loclist(Root -> location);
free(Root -> BusinessName);
free(Root);
return;
}
YelpData* readfile(const char* busfilename, const char* revfilename)
{
FILE* fp1 = fopen(busfilename,"r");
FILE* fp2 = fopen(revfilename,"r");
if(fp1 == NULL || fp2 == NULL) {
fprintf(stderr, "Failed to open %s, or %s, or both\n", busfilename, revfilename);
return NULL;
}
YelpData* BusinessData = malloc(sizeof(YelpData));
BusinessData -> BusFile = strdup(busfilename);
BusinessData -> RevFile = strdup(revfilename);
//fclose(fp2); // Shift it to the Bottom Once Done Constructing the Whole BST and Location Nodes Pointing.
char* str1 = malloc(sizeof(char)*6000);
char* str2 = malloc(sizeof(char)*6000); // For Reviews.tsv
BusinessNode* BST = NULL; // Initialize it to NULL.
int len1 = 0;
int len2 = 0;
long int posbus = ftell(fp1); // File Pointer Position for the Businesses.tsv
long int posrev = ftell(fp2); // File Pointer Position for the Reviews.tsv
int ind1 = 0; // For Business
int ind2 = 0; // For Reviews
int count = 0; // No.of Reviews
while(!feof(fp1))
{
if(feof(fp1))
{
break;
}
fgets(str1,6000,fp1);
char** strArr1 = explode(str1,"\t",&len1);
//char* business = strArr[1]; // This gives the Business Name and Need not malloc the 'business' because malloc is done in explode.
int business_id = atoi(strArr1[0]); // To get the business ID
long int bus_offset = posbus + strlen(strArr1[0]) + strlen(strArr1[1]) + 2; // Used to get the Offset of the Address Location in the File.
long int rev_offset = 0;
// This Below Loop is used to get the offset the review and the no.of reviews.
while(fgets(str2,6000,fp2)!= NULL)
{
char** strArr2 = explode(str2,"\t",&len2);
rev_offset = posrev + strlen(strArr2[0]) + 1;
if(strcmp(strArr2[0],strArr1[0]) == 0)
{
count += 1;
for(ind2 = 0; ind2 < len2; ind2++)
{
free(strArr2[ind2]);
}
free(strArr2);
}
// This is used to break if the Business ID is greater than the Required BusinessID
else
{
//if(strlen(str2) > 0)
//{
fseek(fp2,-strlen(str2),SEEK_CUR); // This Brings the File Pointer to the beginning of the Reviews of a Business Location.
//}
/*else
{
break;
}*/
posrev = ftell(fp2);
for(ind2 = 0; ind2 < len2; ind2++)
{
free(strArr2[ind2]);
}
free(strArr2);
break;
}
}
BST = create_BST(strArr1[1],BST,bus_offset,rev_offset,count,business_id);
count = 0;
for(ind1 = 0; ind1 < len1; ind1++)
{
free(strArr1[ind1]);
}
// Updating the Position of the File Pointer
posbus = ftell(fp1);
free(strArr1);
}
free(str1);
free(str2);
fclose(fp1);
fclose(fp2);
BusinessData -> BNode = BST;
return BusinessData;
}
// CREATING YELP DATA BUSINESS TREE
struct YelpDataBST* create_business_bst(const char* businesses_path,const char* reviews_path)
{
return(readfile(businesses_path,reviews_path));
}
int comparfunc_rev(const void* arg1,const void* arg2)
{
const struct Review* ptr1 = (const struct Review *)arg1;
const struct Review* ptr2 = (const struct Review *)arg2;
uint8_t val1 = (*ptr1).stars;
uint8_t val2 = (*ptr2).stars;
if(val1 < val2) { return 1; }
if(val1 == val2)
{
if(strlen((*ptr1).text) > strlen((*ptr2).text))
{
return(-1);
}
if(strlen((*ptr1).text) < strlen((*ptr2).text))
{
return(1);
}
return 0;
}
return(-1);
}
int comparfunc_loc(const void* arg1,const void* arg2)
{
const struct Location* ptr1 = (const struct Location *)arg1;
const struct Location* ptr2 = (const struct Location *)arg2;
// Comparing the States
if(strcasecmp((*ptr1).state,(*ptr2).state) < 0)
{
return(-1);
}
if(strcasecmp((*ptr1).state,(*ptr2).state) > 0)
{
return(1);
}
// Same State
else
{
if(strcasecmp((*ptr1).city,(*ptr2).city) < 0)
{
return(-1);
}
if(strcasecmp((*ptr1).city,(*ptr2).city) > 0)
{
return(1);
}
// Same City
else
{
// Comparing the Addresses
if(strcasecmp((*ptr1).address,(*ptr2).address) < 0)
{
return(-1);
}
if(strcasecmp((*ptr1).address,(*ptr2).address) > 0)
{
return(1);
}
else
{
return(0);
}
}
}
}
// A DUPLICATE FUNCTION TO GET THE REVIEWS OF A BUSINESS FUNCTION.
struct Business* Get_Reviews(FILE* bus_file, FILE* rev_file, BusinessNode* bst,char* name,char* state,char* zip_code)
{
//This is the Case where we haven't found any BusinessName
if(bst == NULL)
{
//printf("\n\nCannot find the Business Name U asked for...??? Please try an another Business Name\n\n");
return(NULL);
}
if(strcasecmp(name,bst -> BusinessName) < 0)
{
return(Get_Reviews(bus_file,rev_file,bst -> Left,name,state,zip_code));
}
if(strcasecmp(name,bst -> BusinessName) > 0)
{
return(Get_Reviews(bus_file,rev_file,bst -> Right,name,state,zip_code));
}
//Here I need to create the business Reviews and return the Business
else
{
struct Business* bus_loc = malloc(sizeof(struct Business)); // Have to Allocate Memory. ( DO NOT DO IT Outside this 'if' Statement )
char* str_bus = malloc(sizeof(char)*6000); // For the Business Address and related Data
char* str_rev = malloc(sizeof(char)*6000); // For the Reviews of a specific Location.
bus_loc -> name = strdup(bst -> BusinessName);
// Checking with Location Nodes for the required state and zip_code
LocationNode* new_loc = bst -> location;
int len = 0; // For the "explode" Function on str_bus.
uint32_t length_list = Loclist_length(new_loc); // Used for allocating the Memory for storing all the details of the Locations of a Business.
bus_loc -> num_locations = length_list;
// HERE WE CREATE ENOUGH MEMORY for an Array of type "Location" to STORE ALL THE LOCATIONS of a Business.
bus_loc -> locations = malloc(sizeof(struct Location)*length_list);
int ind_null = 0;
for(ind_null = 0;ind_null<length_list;ind_null++)
{
bus_loc -> locations[ind_null].address = NULL;
}
int count = 0; // For 'Location' array index
while(new_loc != NULL) // || length_list != 0)
{
fseek(bus_file,new_loc -> offset,SEEK_SET); // Takes the File Pointer to the offset of a Specified Address Location of a Business in the file.
fgets(str_bus,6000,bus_file); // Getting all the details of a Business (Business Location).
char** Arr_Bus = explode(str_bus,"\t",&len);
//printf("\n\n State: %s\n Zip_Code: %s \n %d \nZip_Code_File: %s\n",state,zip_code,(state == NULL && strcasecmp(Arr_Bus[3],zip_code) == 0),Arr_Bus[3]);
if(((state == NULL) && (zip_code == NULL)) || (state == NULL && strcasecmp(Arr_Bus[3],zip_code) == 0) || (zip_code == NULL && strcasecmp(Arr_Bus[2],state) == 0) || (state != NULL && zip_code != NULL && ((strcasecmp(Arr_Bus[2],state) == 0) && (strcasecmp(Arr_Bus[3],zip_code) == 0))))
{
bus_loc -> locations[count].address = strdup(Arr_Bus[0]); // Address Location.
bus_loc -> locations[count].city = strdup(Arr_Bus[1]); // City
bus_loc -> locations[count].state = strdup(Arr_Bus[2]); // State
bus_loc -> locations[count].zip_code = strdup(Arr_Bus[3]); // Zip_Code
bus_loc -> locations[count].num_reviews = (new_loc -> reviews).no_reviews;
bus_loc -> locations[count].reviews = malloc(sizeof(struct Review)*(bus_loc -> locations[count].num_reviews));
// Now input all the reviews into the Reviews list.
int reviews_count = 0; // Have to Create a Duplicate Variable.
fseek(rev_file,(new_loc -> reviews).offset,SEEK_SET); // To Move Reviews File Pointer into specified business Reviews Location.
while(reviews_count < (bus_loc -> locations[count].num_reviews))
{
fgets(str_rev,6000,rev_file);
int len_rev = 0; // for 'explode' on rev string
char** Arr_Rev = explode(str_rev,"\t",&len_rev);
if(len_rev == 5)
{
((bus_loc -> locations[count].reviews)[reviews_count]).stars = atoi(Arr_Rev[0]); // Input the Star Rating.
((bus_loc -> locations[count].reviews)[reviews_count]).text = strdup(Arr_Rev[4]); // Input the Review text.
}
else
{
((bus_loc -> locations[count].reviews)[reviews_count]).stars = atoi(Arr_Rev[1]); // Input the Star Rating.
((bus_loc -> locations[count].reviews)[reviews_count]).text = strdup(Arr_Rev[5]); // Input the Review text.
}
//fseek(rev_file,1 + (int)(floor(log10(new_loc -> bus_id)) + 1),SEEK_CUR); // Put the File Pointer pointing from the Star Rating in the line.
int ind_rev = 0; // Index to free Arr_rev
// Freeing the Arr_Rev
for(ind_rev = 0; ind_rev < len_rev;ind_rev++)
{
free(Arr_Rev[ind_rev]);
}
free(Arr_Rev);
reviews_count += 1;
}
// SORT THE REVIEWS ARRAY ACCORDING TO THE STAR RATING IN DESCENDING ORDER.
qsort(&(bus_loc -> locations[count]).reviews[0],bus_loc -> locations[count].num_reviews,sizeof(struct Review),comparfunc_rev);
count += 1;
}
int ind_bus = 0;
for(ind_bus = 0; ind_bus < len;ind_bus++)
{
free(Arr_Bus[ind_bus]);
}
free(Arr_Bus);
new_loc = new_loc -> next;
}
//printf("\nNo_Locations: %d\n",bus_loc -> num_locations);
bus_loc -> num_locations = count;
//printf("\nCount: %d\n",count);
qsort(&(bus_loc -> locations[0]),bus_loc -> num_locations,sizeof(struct Location),comparfunc_loc);
free(str_bus);
free(str_rev);
return(bus_loc);
}
}
// GET THE REVIEWS OF A GIVEN BUSINESS LOCATION (By Giving a Business Name, State and ZipCode)
struct Business* get_business_reviews(struct YelpDataBST* bst,char* name, char* state, char* zip_code)
{
FILE* bus_file = fopen(bst -> BusFile,"r");
FILE* rev_file = fopen(bst -> RevFile,"r");
struct Business* bus_struct = Get_Reviews(bus_file,rev_file,bst -> BNode,name,state,zip_code);
fclose(bus_file);
fclose(rev_file);
return(bus_struct);
}
void destroy_business_result(struct Business* b)
{
free(b -> name); // Freeing the Business Name
int ind_loc = 0;
// This Loop is used to free the locations Array
for(ind_loc = 0;ind_loc < (b -> num_locations);ind_loc++)
{
if(b -> locations[ind_loc].address == NULL)
{
break;
}
free((b -> locations[ind_loc]).address);
free((b -> locations[ind_loc]).city);
free((b -> locations[ind_loc]).state);
free((b -> locations[ind_loc]).zip_code);
// Now Free the Reviews Array
int ind_rev = 0;
for(ind_rev = 0; ind_rev < (b -> locations[ind_loc]).num_reviews; ind_rev++)
{
free(((b -> locations[ind_loc]).reviews[ind_rev]).text);
}
free((b -> locations[ind_loc]).reviews);
//free(b -> locations[ind_loc]);
}
//Finally Free the Memory of the Location struct
free(b -> locations);
//Free Business
free(b);
}
void destroy_business_bst(struct YelpDataBST* bst)
{
destroy_BST(bst -> BNode);
free(bst -> BusFile); // Freeing the Businesses File Name
free(bst -> RevFile); // Freeing the Reviews File Name
free(bst); // Freeing the YelpData
return;
}
/*int main(int argc, char** argv)
{
YelpData* Root = create_business_bst("samplebus.tsv","samplerev.tsv");
//print_tree(Root -> BNode,"bus.tsv","rev.tsv");
struct Business* business_rev = get_business_reviews(Root,"Starbucks",NULL,"12345");
destroy_business_result(business_rev);
destroy_business_bst(Root);
return(EXIT_SUCCESS);
}*/
|
C | /*
* Definition for singly-linked list:
* struct ListNode {
* int val;
* struct ListNode* next;
* };
*/
#include <math.h>
int countNodes(struct ListNode* head)
{
int count = 0;
struct ListNode* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int getDecimalValue(struct ListNode* head)
{
struct ListNode* current = head;
int decimalValue = 0;
int i;
int numberNodes;
int powerOfTwo;
numberNodes = countNodes(head);
for (i = numberNodes - 1; i >= 0; i--) {
powerOfTwo = (int) pow(2.0, (double) i);
decimalValue += powerOfTwo * current->val;
current = current->next;
}
return decimalValue;
}
|
C | #include "holberton.h"
/**
*_strpbrk - searches a string for bytes
*
*@s: string
*@accept: string
*
*Return: a pointer to s or NULL
*/
char *_strpbrk(char *s, char *accept)
{
int i, j, pos, flag = 0;
for (i = 0; s[i] != '\0'; i++)
;
pos = i;
for (i = 0; accept[i] != '\0'; i++)
{
for (j = 0; s[j] != '\0'; j++)
{
if (accept[i] == s[j])
{
if (j <= pos)
{
pos = j;
flag = 1;
}
}
}
}
if (flag == 1)
{
return (&s[pos]);
}
else
{
return ('\0');
}
}
|
C | #include "invArray.h"
typedef struct tabinv{
inv_t* vettInv;
int nInv;
}tabInv_t;
tabInvP invTinit()//inizializza il wrapper per l'inventario
{
tabInvP tabInv;
tabInv=(tabInv_t*)malloc(sizeof(tabInv_t));
tabInv->nInv=0;
return tabInv;
}
inv_t* sObjL1(tabInvP tabInv,int f)
{
return &(tabInv->vettInv[f]);
}
int sObjL2(tabInvP tabInv)
{
int i,n;
char nomeoggetto[maxl];
printf("scrivere il nome dell'oggetto\n");
fgets(nomeoggetto,maxl,stdin);
sscanf(nomeoggetto,"%s ",nomeoggetto);
n=tabInv->nInv;
for(i=0;i<n;i++)
if(KeyisEq(nomeoggetto,&(tabInv->vettInv[i])))
{
printf("oggetto trovato\n");
return i;
}
printf("oggetto non trovato\n");
return -1;
}
void pObjL1(tabInvP tabInv,int f)
{
int index;
inv_t Obj;
if(f==-1)
{
index=sObjL2(tabInv);
if(index!=-1)
Obj=tabInv->vettInv[index];
else
return;
}
else Obj=tabInv->vettInv[f];
pObjL0(&Obj);
return;
}
int aggiungiTabeq(tabInvP tabInv)
{
int n,i;
FILE* fp=NULL;
n=0;
char temp[200];
printf("come si chiama il file?\n");
fgets(temp,200,stdin);
sscanf(temp,"%s ",temp);
fp=fopen(temp,"r");
if(fp==NULL)
{
printf("file non trovato!\n");
return 0;
}
fscanf(fp,"%d ",&n);
if((tabInv->nInv)==0)
{
tabInv->vettInv=(inv_t*)malloc(n*sizeof(inv_t));
tabInv->nInv+=n;
}
else
{
tabInv->nInv+=n;
tabInv->vettInv=(inv_t*)realloc(tabInv->vettInv,(tabInv->nInv)*sizeof(inv_t));
}
for(i=(tabInv->nInv)-n;(i<tabInv->nInv)&&(readstrEq(fp,&(tabInv->vettInv[i])));i++);
fclose(fp);
return (i==tabInv->nInv);
}
void liberaI(tabInvP tabInv)
{
free(tabInv->vettInv);
return;
}
|
C | #include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *link;
};
struct node *create(struct node *,int);
void traverse(struct node *);
void exit();
int main(){
struct node *start=NULL;
int choice,n;
printf("\t\t\t\t\t\t\t\t\t\t\t CREATION AND DISPLAY OF LINKED LIST");
printf("\n\n\n\n\n");
while(1){
printf("\n1.create\n2.traverse\n3.exit\n");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice){
case 1 : printf("enter no. of items:");
scanf("%d",&n);
start=create(start,n);
break;
case 2 : traverse(start);
break;
case 3 : exit(0);
break;
default : printf("ivalid input");
}
}
return 0;
}
struct node *create(struct node *start,int n){
struct node *temp,*newnode;
int i;
for(i=1;i<=n;i++){
newnode=(struct node *)malloc(sizeof(struct node));
printf("enter %d item:",i);
scanf("%d",&newnode->data);
newnode->link=NULL;
if(start==NULL){
start=temp=newnode;
}
else{
temp->link=newnode;
temp=newnode;
}
}
return start;
}
void traverse(struct node *temp){
if(temp==NULL)
printf("list is empty");
else{
while(temp!=NULL){
printf(" %d ",temp->data);
temp=temp->link;
}
}
}
|
C | #include<stdio.h>
int main()
{
char a[100];
int b1=0,c1=0,d1=0,e1=0,f1=0,g1=0,i;
scanf("%s",&a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='{')
b1++;
else if(a[i]=='[')
c1++;
else if(a[i]=='(')
d1++;
else if(a[i]=='}')
e1++;
else if(a[i]==']')
f1++;
else
g1++;
}
if(b1==e1&&c1==f1&&d1==g1)
printf("yes");
else
printf("no");
}
|
C | #include<stdlib.h>
#include<locale.h>
int main(){
setlocale(LC_ALL,NULL);
printf("File is %s\nDate %s\nTime %s\nLine %d\n",__FILE__,__DATE__,__TIME__,__LINE__);
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<pwd.h>
#include<string.h>
#include <dirent.h>
#include <errno.h>
int checkdir(char *directory)
{
DIR* dir = opendir(directory);
if (dir)
{
/* Directory exists. */
closedir(dir);
return 1;
}
else if (ENOENT == errno)
{
/* Directory does not exist. */
return 0;
}
else
{
/* opendir() failed for some other reason. */
return -1;
}
}
int main (int argc, char **argv)
{
char argument[1000];
int i,j;
for(i=0;i<=strlen(argv[2]);i++)
{
argument[i]=*(*(argv+2)+i);
}
argument[i]='\0';
char dirlist[100][100],dirpath[100][100];
for(i=0;i<100;i++)for(j=0;j<100;j++){dirlist[i][j]='\0';dirpath[i][j]='\0';}
int index=0,n=0;i=0;
while(1)
{
if(argument[i]=='\0')
{
strncpy(dirlist[n],argument+index,i-index);
n++;
break;
}
if(argument[i]==' ')
{
strncpy(dirlist[n],argument+index,i-index);
n++;
index=i+1;
}
if(argument[i]=='/')
{
char temp[100];for(j=0;j<100;j++)temp[j]='\0';
strncpy(temp,argument+index,i-index);
strcat(dirpath[n],temp);
strcat(dirpath[n],"/");
index=i+1;
}
i++;
}
for(i=0;i<n;i++)
{
if(dirpath[i][0]=='\0')
{
char temp[100];for(j=0;j<100;j++)temp[j]='\0';
strcat(temp,argv[1]);
strcat(temp,dirpath[i]);
strcat(temp,"//");
strcat(temp,dirlist[i]);
mkdir(temp, 0777);
}
else
{
for(j=0;j<strlen(dirpath[i]);j++)
{
if(dirpath[i][j]=='/')
{
char temp[100],temp1[100];temp1[0]='\0';temp[0]='\0';
strcat(temp,argv[1]);
strncpy(temp1,dirpath[i],j);
strcat(temp,"/");
strcat(temp,temp1);
printf("%s\n",temp);
mkdir(temp, 0777);
}
}
char tempe[100];for(j=0;j<100;j++)tempe[j]='\0';
strcat(tempe,argv[1]);
strcat(tempe,"/");
strcat(tempe,dirpath[i]);
strcat(tempe,dirlist[i]);
printf("%s\n",tempe);
mkdir(tempe, 0777);
}
}
return 0;
}
|
C | #include "lib/pen.h"
enum opcao{vai = 1, volta = -1};
void dragao(Pen &p, float tam, int n, opcao op, float desl){
if(n == 0){
p.walk(tam);
return;
}
dragao(p, tam, n - 1, vai, desl - 10);
p.right(90 * op);
dragao(p, tam, n - 1, volta, desl + 10);
}
void frac_dragao(){
Pen pen(800, 800);
pen.setSpeed(20);
pen.setThickness(3);
pen.setColor(255, 255, 255);
pen.setXY(300, 250);
pen.setHeading(0);
dragao(pen, 10, 10, vai, 125);
pen.wait();
}
|
C | #include <stdio.h>
#define TAMANIO 20
void imprimir(int* elemento);
void ordenar(int* elemento);
void main (void) {
int elemento[] = {16, 20, 9, 7, 10, 6, 11, 2, 12, 8, 14, 1, 15, 5, 17, 3, 18, 13, 19, 4};
imprimir(elemento);
ordenar(elemento);
}
void imprimir(int* elemento) {
int i;
for (i = 0; i < TAMANIO; i++) {
printf("%3d", elemento[i]);
}
printf("\n");
}
void ordenar(int* elemento) {
int contador, indice;
int auxiliar;
for (contador = 1; contador < TAMANIO; contador++) {
auxiliar = elemento[contador];
indice = contador - 1;
while (auxiliar < elemento[indice] && indice >= 0) {
elemento[indice + 1] = elemento[indice];
indice--;
}
elemento[indice + 1] = auxiliar;
imprimir(elemento);
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
FILE *fp,*fp1;
int d;
char c[20],s[20],t;
fp = fopen("fileA", "a+");
printf("Enter the country\n");
scanf("%s", s);
while (fscanf(fp, "%20s", c)==1)
{
if (strcmp(strupr(s), strupr(c)) == 0)
{
fseek(fp, ftell(fp) + 1, SEEK_SET);
do{
t = fgetc(fp);
printf("%c", t);
} while (t != 10&&t!=EOF);
break;
}
}
} |
C | #include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
double compute_average_word_length(const char *sentence);
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s \"Enter a sentence in quotes.\"\n", argv[0]);
return 1;
}
printf("%.2f\n", compute_average_word_length(argv[1]));
return 0;
}
double compute_average_word_length(const char *sentence)
{
register bool in_word = false;
double chars, words, apostrophes;
int open_quotes, other_single_quotes;
open_quotes = other_single_quotes = 0;
chars = words = apostrophes = 0.0;
for (const char *c = sentence; *c; c++) {
if (*c == '\'') {
if (in_word)
/* could be an apostrophe or a close-quote right after a word */
other_single_quotes++;
else {
if (open_quotes % 2 > 0)
/*
Count of open-quotes is odd, so we're looking for a close quote.
This one is placed after punctuation or an extra space after a word.
*/
other_single_quotes++;
else
open_quotes++;
}
} else if (isalnum(*c) || *c == '-' || *c == '_') {
in_word = true;
chars++;
} else if (in_word) {
/* we just left the word: we won't be here in the case of initial or multiple spaces */
in_word = false;
words++;
}
}
/* did we terminate on a word character? */
if (in_word)
words++;
/* adjust char count for apostrophes, but only if the single quotes balance out */
if (other_single_quotes >= open_quotes)
apostrophes = (double) (other_single_quotes - open_quotes);
chars += apostrophes;
return chars / words;
}
|
C | /*===========================================================================
gary.c
This team forms a loose pattern once the ball is aquired.
The robot that finds the ball is the captain. The others
flank him diagonally, hoping to catch the kicks of the
opposing team.
Gary Boone [email protected]
===========================================================================*/
#include "players.h"
#define POS_X 4 /* flanking position horizontal */
#define POS_Y 4 /* flanking position vertical */
/* forward ref */
UN(goToNE)(int gx, int gy, int x, int y, int x_dist, int y_dist);
static int UN(got_it) = -1; /* who is the captain? */
static int UN(capt_loc_x) = -1;
static int UN(capt_loc_y) = -1;
/* nearBall (by Steve Rowe)
Given a local area, return the direction to the ball, or 9 if the ball
is not in the local area.
*/
int UN(nearBall)(int local_area[9])
{
int i;
for (i = 0; i < 9; ++i) {
if (local_area[i] == BALL) {
return 1;
}
}
return 0;
}
/*-----------------------------------------------------
player1()
If the ball is nearby, either get to
the east side of it, or if already on the
east, kick it.
-----------------------------------------------------*/
int UN(player1)(int local_area[9], int ball_direction, int x, int y)
{
if (!UN(nearBall)(local_area)) /* if not near ball */
if (UN(got_it) == 1) /* but was capt */
UN(got_it) = -1; /* release capt */
else;
else /* if near ball */
if (UN(got_it) == -1) { /* but there is no captain */
UN(capt_loc_x) = x; /* become captain */
UN(capt_loc_y) = y;
UN(got_it) = 1;
}
/*
* If right next to the ball, on the west, get to east side.
*/
if (local_area[N] == BALL) return(NE);
if (local_area[NE] == BALL) return(E);
if (local_area[E] == BALL) return(SE);
if (local_area[SE] == BALL) return(E);
if (local_area[S] == BALL) return(SE);
/*
* If already on the west, kick!
*/
if (local_area[SW] == BALL) return(KICK);
if (local_area[W] == BALL) return(KICK);
if (local_area[NW] == BALL) return(KICK);
/*
* If not near the ball, just go to it.
*/
if (UN(got_it) == -1) /* if no capt, go for ball */
return(ball_direction);
else /* else go to position */
return UN(goToNE)(UN(capt_loc_x), UN(capt_loc_y), x, y, POS_X, POS_Y);
}
int
UN(goToNE)(int gx, int gy, int x, int y, int x_dist, int y_dist)
{
int dx, dy;
dx = gx - x + x_dist;
dy = gy - y + y_dist;
if ((dx < 0) && (dy < 0)) return NW;
if ((dx < 0) && (dy == 0)) return W;
if ((dx < 0) && (dy > 0)) return SW;
if ((dx == 0) && (dy > 0)) return S;
if ((dx == 0) && (dy == 0)) return S;
if ((dx == 0) && (dy < 0)) return N;
if ((dx > 0) && (dy < 0)) return NE;
if ((dx > 0) && (dy == 0)) return E;
if ((dx > 0) && (dy > 0)) return SE;
}
/*-----------------------------------------------------
player2()
-----------------------------------------------------*/
int UN(player2)(int local_area[9], int ball_direction, int x, int y)
{
if (!UN(nearBall)(local_area)) /* if not near ball */
if (UN(got_it) == 2) /* but was capt */
UN(got_it) = -1; /* release capt */
else;
else /* if near ball */
if (UN(got_it) == -1) { /* but there is no captain */
/* become captain */
UN(capt_loc_x) = x;
UN(capt_loc_y) = y;
UN(got_it) = 2;
}
/* If right next to the ball, on the west, get to east side. */
if (local_area[N] == BALL) return(NE);
if (local_area[NE] == BALL) return(E);
if (local_area[E] == BALL) return(SE);
if (local_area[SE] == BALL) return(E);
if (local_area[S] == BALL) return(SE);
/* if already on the west, kick! */
if (local_area[SW] == BALL) return(KICK);
if (local_area[W] == BALL) return(KICK);
if (local_area[NW] == BALL) return(KICK);
/* If not near the ball, just go to NE of player 1 */
if (UN(got_it) == -1) /* if no capt, go for ball */
return(ball_direction);
else /* else go to position */
return UN(goToNE)(UN(capt_loc_x), UN(capt_loc_y), x, y, POS_X, -POS_Y);
}
/*-----------------------------------------------------
player3()
-----------------------------------------------------*/
int UN(player3)(int local_area[9], int ball_direction, int x, int y)
{
if (!UN(nearBall)(local_area)) /* if not near ball */
if (UN(got_it) == 3) /* but was capt */
UN(got_it) = -1; /* release capt */
else;
else /* if near ball */
if (UN(got_it) == -1) { /* but there is no captain */
/* become captain */
UN(capt_loc_x) = x;
UN(capt_loc_y) = y;
UN(got_it) = 3;
}
/* If right next to the ball, on the west, get to east side. */
if (local_area[N] == BALL) return(NE);
if (local_area[NE] == BALL) return(E);
if (local_area[E] == BALL) return(SE);
if (local_area[SE] == BALL) return(E);
if (local_area[S] == BALL) return(SE);
/* If already on the west, kick! */
if (local_area[SW] == BALL) return(KICK);
if (local_area[W] == BALL) return(KICK);
if (local_area[NW] == BALL) return(KICK);
/* If not near the ball, just go to NE of player 1 */
if (UN(got_it) == -1) /* if no capt, go for ball */
return(ball_direction);
else /* else go to position */
return UN(goToNE)(UN(capt_loc_x), UN(capt_loc_y), x, y, POS_X, POS_Y/2);
}
/*-----------------------------------------------------
player4()
-----------------------------------------------------*/
int UN(player4)(int local_area[9], int ball_direction, int x, int y)
{
if (!UN(nearBall)(local_area)) /* if not near ball */
if (UN(got_it) == 4) /* but was capt */
UN(got_it) = -1; /* release capt */
else;
else /* if near ball */
if (UN(got_it) == -1) { /* but there is no captain */
/* become captain */
UN(capt_loc_x) = x;
UN(capt_loc_y) = y;
UN(got_it) = 4;
}
/* If right next to the ball, on the west, get to east side. */
if (local_area[N] == BALL) return(NE);
if (local_area[NE] == BALL) return(E);
if (local_area[E] == BALL) return(SE);
if (local_area[SE] == BALL) return(E);
if (local_area[S] == BALL) return(SE);
/* If already on the west, kick! */
if (local_area[SW] == BALL) return(KICK);
if (local_area[W] == BALL) return(KICK);
if (local_area[NW] == BALL) return(KICK);
/* If not near the ball, just go to NE of player 1 */
if (UN(got_it) == -1) /* if no capt, go for ball */
return(ball_direction);
else /* else go to position */
return UN(goToNE)(UN(capt_loc_x), UN(capt_loc_y), x, y, POS_X, -POS_Y/2);
}
/*-----------------------------------------------------
team_name()
Every team must have a name. Make sure it
is exactly 20 characters. Pad with spaces.
-----------------------------------------------------*/
char *UN(team_name)()
{
char *s;
/* "####################\0" <--- 20 characters */
s = "Feeble Forcers \0";
return(s);
}
/*-----------------------------------------------------
initialize_game()
This function is called only once per
game, before play begins. You can leave it
empty, or put code here to initialize your
variables, etc.
-----------------------------------------------------*/
void UN(initialize_game)()
{
}
/*-----------------------------------------------------
initialize_point()
This function is called once per point, just
before play begins for that point.
You can leave it empty, or put code here to initialize
your variables, etc.
-----------------------------------------------------*/
void UN(initialize_point)()
{
}
/*-----------------------------------------------------
lost_point()
If your team loses a point, this function is
called, otherwise, if you win the point, won_point()
is called. You can leave it empty, or put code here
for negative re-inforcement, etc.
-----------------------------------------------------*/
void UN(lost_point)()
{
}
/*-----------------------------------------------------
won_point()
If your team wins a point, this function is
called, otherwise, if you lose the point, lost_point()
is called. You can leave it empty, or put code here
for positive re-inforcement, etc.
-----------------------------------------------------*/
void UN(won_point)()
{
}
/*-----------------------------------------------------
game_over()
This function is called once at the end of
the game. You can leave it empty, or put code
here to save things to a file, etc.
-----------------------------------------------------*/
void UN(game_over)()
{
}
|
C | # include <stdio.h>
# include <stdlib.h>
# define MAX 100
//The Binary Counter function takes an Array and size n as its
//parameters. It traverses the Array from right to left and
//increments the value by 1.
void binCounter(int A[], int n){
int i;
for (i=n-1; i>=0; i--){
if (A[i]==0){
A[i]=1;
break;
}
else if (A[i]==1) A[i]=0;
}
}
void printPath (int A[], int n, int pos){
void binCounter(int[], int);
void printArray(int[], int);
int i;
for (i=0; i<pos; i++)
binCounter(A, n);
printArray(A, n);
}
void printArray(int A[], int n){
int i;
for (i=0; i<n; i++){
if (A[i]==0) printf("L");
else printf("R");
}
}
//Function calculates the largest sum of a path by using a Binary Counter.
//After, determine the n-bit counter, it increments through this
//using a brute force method of testing all values to determine the largest
//values.
int bruteForceBinCounter(int A[][MAX], int binArray[], int numRows){
void binCounter(int[], int);
int poss = numRows*numRows, n=0, p;
int largest = -9999, row, col, j;
while (n<poss){
int Sum=A[0][0];
row=0;
col=0;
for (j=0; j<numRows; j++){
if (binArray[j]==0){
Sum+= A[row+1][col];
row++;
}
else
if (binArray[j]==1){
Sum+= A[row+1][col+1];
row++; col++;
}
}
binCounter(binArray, numRows);
if (Sum>=largest){
largest=Sum;
p=n;
}
n++;
}
return largest;
}
int bestSumSimpleRecursion(int A[][MAX], int i, int j, int n){
int left, right;
if (i==n) return A[i][j];
left = bestSumSimpleRecursion(A, i+1, j, n);
right = bestSumSimpleRecursion(A, i+1, j+1, n);
if (left>right) return left + A[i][j];
else return right + A[i][j];
}
int bestSumMemoization(int A[][MAX], int B[][MAX], int i, int j, int n){
int left, right;
if (i==n) return B[i][j];
left = bestSumMemoization(A, B, i+1, j, n);
right = bestSumMemoization(A, B, i+1, j+1, n);
if (left>right) return B[i][j] = left + A[i][j];
else return B[i][j] = right + A[i][j];
}
int bottomUpDynamic(int A[][MAX], int n){
int i, j, sum=0;
for (i=n-1; i>=0; i--){
for (j=0; j<=i; j++){
if (A[i+1][j] > A[i+1][j+1]) A[i][j]+=A[i+1][j];
else A[i][j]+=A[i+1][j+1];
}
}
return A[0][0];
}
int main (){
int Arr[MAX][MAX], Arr2[MAX][MAX], binArray[MAX], numRows, row, col, i, j, val;
int bruteForceBinCounter(int[][], int[], int);
int bestSumSimpleRecursion(int[][], int, int, int);
int bestSumMemoiztion(int[][], int[][], int, int, int);
int bottomUpDynamic(int[][], int);
void binCounter(int[], int);
void printArray(int[], int);
void printPath (int[], int, int);
FILE * in = fopen("input.txt", "r");
FILE * out = fopen("output.txt", "w");
fscanf(in, "%d", &numRows);
if (numRows==0){
printf ("No rows read, exiting... \n");
exit(0);
}
if (numRows==1){
fscanf(in, "%d", &val);
printf ("One row read, the largest sum is %d\n", val);
}
for (i=0; i<numRows; i++){
binArray[i]=0;
for (j=0; j<=i; j++){
fscanf(in, "%d", &val);
Arr[i][j]=val;
Arr2[i][j]=val;
}
}
int bfSum = bruteForceBinCounter(Arr, binArray, numRows);//working but I know there is an error
int simpleSum = bestSumSimpleRecursion(Arr, 0,0,numRows);
int memoSum = bestSumMemoization(Arr, Arr2, 0, 0, numRows);
int dynamicSum = bottomUpDynamic(Arr, numRows); //working
printf("Brute Force Binary Counter: Sum = %d\n", bfSum);
printf("Simple Recursion: Sum = %d\n", simpleSum);
printf("Best Sum Memoization Recursion: Sum = %d\n", memoSum);
printf("Dynamic Program, Button Up Approach: Sum = %d\n", dynamicSum);
fprintf(out, "Brute Force Binary Counter: Sum = %d\n", bfSum);
fprintf(out, "Simple Recursion: Sum = %d\n", simpleSum);
fprintf(out, "Best Sum Memoization Recursion: Sum = %d\n", memoSum);
fprintf(out, "Dynamic Program, Button Up Approach: Sum = %d\n", dynamicSum);
return 0;
}
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct ref_array_item {char* refname; scalar_t__ kind; } ;
struct ref_array {int nr; struct ref_array_item** items; } ;
/* Variables and functions */
scalar_t__ FILTER_REFS_DETACHED_HEAD ;
scalar_t__ FILTER_REFS_REMOTES ;
int /*<<< orphan*/ free (char*) ;
char* get_head_description () ;
int /*<<< orphan*/ skip_prefix (char*,char*,char const**) ;
int utf8_strwidth (char const*) ;
__attribute__((used)) static int calc_maxwidth(struct ref_array *refs, int remote_bonus)
{
int i, max = 0;
for (i = 0; i < refs->nr; i++) {
struct ref_array_item *it = refs->items[i];
const char *desc = it->refname;
int w;
skip_prefix(it->refname, "refs/heads/", &desc);
skip_prefix(it->refname, "refs/remotes/", &desc);
if (it->kind == FILTER_REFS_DETACHED_HEAD) {
char *head_desc = get_head_description();
w = utf8_strwidth(head_desc);
free(head_desc);
} else
w = utf8_strwidth(desc);
if (it->kind == FILTER_REFS_REMOTES)
w += remote_bonus;
if (w > max)
max = w;
}
return max;
} |
C | #include<stdio.h>
int main()
{
typedef struct{
int i;
int j;
} posT;
posT pos1;
pos1.i=1;
pos1.j=2;
printf("The i is %d\n",pos1.i);
//Pointers should first be initialized here or segment fault
posT pos2;
posT *ppos=&pos2;
ppos->i=3;
printf("The i is %d\n",ppos->i);
printf("The j is %d\n",ppos->j);//No fault
}
|
C | #include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include <ncurses.h>
#include <unistd.h>
int initall(void)
{
initscr();
return 0;
};
int enditall(void)
{
endwin();
return 0;
}
// Init a cell matrix with zeros
CellMatrix* Init_matrix(int n_rows, int n_cols) {
struct CellMatrix* matrix = malloc(sizeof(CellMatrix));
matrix->rows = n_rows;
matrix->cols = n_cols;
int x = 0;
int** data = malloc(sizeof(int*) * n_rows);
for(x = 0; x < n_rows; x++){
data[x] = calloc(n_cols, sizeof(int));
}
matrix->data = data;
return matrix;
}
void Initialize(struct CellMatrix **matrix_local, int n_rows, int n_cols) {
struct CellMatrix* matrix = malloc(sizeof(CellMatrix));
matrix = malloc(sizeof(CellMatrix));
matrix->rows = n_rows;
matrix->cols = n_cols;
int x = 0;
int** data = malloc(sizeof(int*) * n_rows);
for(x = 0; x < n_rows; x++){
data[x] = calloc(n_cols, sizeof(int));
}
matrix->data = data;
*matrix_local = matrix;
}
void increment_space(CellMatrix **matrix0) {
int new_rows = (*matrix0)->rows + 2;
int new_cols = (*matrix0)->cols + 2;
int x = 0, y = 0;
struct CellMatrix *matrix = Init_matrix(new_rows, new_cols);
for(x = 1; x < new_rows-1; x++) {
for(y = 1; y < new_cols-1; y++) {
matrix->data[x][y] = (*matrix0)->data[x-1][y-1];
}
}
free(*matrix0);
*matrix0 = matrix;
}
void transfer_data(CellMatrix **matrix_to, CellMatrix *matrix_from) {
int new_rows = (matrix_from)->rows;
int new_cols = (matrix_from)->cols;
int x = 0, y = 0;
struct CellMatrix *matrix = Init_matrix(new_rows, new_cols);
for(x = 0; x < new_rows; x++) {
for(y = 0; y < new_cols; y++) {
matrix->data[x][y] = (matrix_from)->data[x][y];
}
}
*matrix_to = matrix;
}
void print_matrix(CellMatrix* m) {
int x = 0, y = 0;
int row, col;
int r_mid = (int)((m->rows)/2.0) + 1;
int c_mid = (int)((m->cols)/2.0) + 1;
getmaxyx(stdscr, row, col);
row = row/2; col = col/2;
for(x = 0; x < m->rows; x++) {
for(y = 0; y < m->cols; y++) {\
if (m->data[x][y] == 1)
{
mvprintw(x+row-r_mid,y+col-c_mid,"X");
}
}
}
}
int neighbours(int x, int y, struct CellMatrix *space)
{
int count = 0, life = 0;
int i = 0, j = 0;
for (i = -1; i <= 1; i++)
for (j = -1; j <= 1; j++)
if((space->data[x+i][y+j] == 1) && (i!=0 || j!=0))
count++;
if(space->data[x][y] == 1)
{
if (count<2)
life = 0;
else if (count == 2 || count == 3)
life = 1;
else
life = 0;
}
else
{
if (count==3 && (space->data[x][y] == 0))
{
life = 1;
}
}
return life;
}
void life(struct CellMatrix **current, struct CellMatrix **future)
{
struct CellMatrix *temp = Init_matrix((*current)->rows, (*current)->cols);
int r = (*current)->rows, c = (*current)->cols;
int i = 0, j = 0;
for (i = 1; i < r-1; i++)
{
for (j = 1; j < c-1; j++)
{
temp->data[i][j] = neighbours(i,j,(*current));
}
}
*future = temp;
}
int increment_space_check(struct CellMatrix *current)
{
int check = 0, count = 0;
int r = current->rows, c = current->cols;
int i = 0, j = 0;
for (i = 0; i < 2; i++)
{
for (j = 0; j < c; j++)
{
count = count + current->data[i][j] + current->data[i + r-2][j];
if(count>0)
{
check = 1;
return check;
}
}
}
i = 0; j = 0;
if(count==0)
for (j = 0; j < 2; j++)
{
for (i = 0; i < r; i++)
{
count = count + current->data[i][j] + current->data[i][j+c-2];
if(count>0)
{
check = 1;
return check;
}
}
}
if(count>0)
check = 1;
return check;
}
void init_display(void)
{
printf("\nWelcome! to the Conway's Game of Life");
printf("\nA program that plays Game of Life on terminal irrespective of its size and shape\n");
printf("\nBelow are the available three patterns to start with");
printf("\n\n");
int data[5][26]={{0}};
// pattern 1
data[2][2] = 1; data[2][1] = 1;
data[1][2] = 1; data[1][3] = 1;
data[3][2] = 1;
//pattern 2
data[2][7] = 1; data[2][8] = 1;
data[3][8] = 1; data[1][13] = 1;
data[3][13] = 1; data[3][12] = 1;
data[3][14] = 1;
//pattern 3
data[1][19] = 1; data[3][18] = 1;
data[3][19] = 1; data[2][21] = 1;
data[3][22] = 1; data[3][23] = 1;
data[3][24] = 1;
int i = 0, j = 0;
for (i = 0; i < 5; i++)
{
printf("\n");
for (j = 0; j < 24; j++)
{
if (data[i][j]==1)
{
printf("X ");
}
else
{
if ((j==5)|(j==16))
printf("| ");
else
printf(" ");
}
}
}
printf("\n Pattern 1 \t\t Pattern 2 \t\t\t Pattern 3");
printf("\n \n \n");
}
void patterns_initialize(struct CellMatrix **matrix_local, int pattern){
switch(pattern){
case 1: {
(*matrix_local)->data[2][2] = 1; (*matrix_local)->data[2][1] = 1;
(*matrix_local)->data[1][2] = 1; (*matrix_local)->data[1][3] = 1;
(*matrix_local)->data[3][2] = 1;
break;
}
case 2:{
(*matrix_local)->data[2][1] = 1; (*matrix_local)->data[2][2] = 1;
(*matrix_local)->data[3][2] = 1; (*matrix_local)->data[1][7] = 1;
(*matrix_local)->data[3][7] = 1; (*matrix_local)->data[3][6] = 1;
(*matrix_local)->data[3][8] = 1;
break;
}
case 3:{
(*matrix_local)->data[1][2] = 1; (*matrix_local)->data[3][1] = 1;
(*matrix_local)->data[3][2] = 1; (*matrix_local)->data[2][4] = 1;
(*matrix_local)->data[3][5] = 1; (*matrix_local)->data[3][6] = 1;
(*matrix_local)->data[3][7] = 1;
break;
}
}
}
|
C | /*
* Sean Keough
* GitHub: SKeough117
*
* set.c - CS50 'set' module
*
* see set.h for more information.
*
* Sean Keough, January 2020
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "set.h"
#include "memory.h"
/******************* file-local global variables ****************/
/* none */
/********* local types ************/
typedef struct setnode {
void *item; // pointer to value stored with key
char *key; // pointer to string key for value
struct setnode *next;
} setnode_t;
/***************** global types *******************/
typedef struct set {
struct setnode *head; // head of the list of nodes in the set
} set_t;
/*************** global functions *****************/
/* functions that are visible outside this file */
/* see set.h for comments */
/************** local functions ***************/
/* not visible outside this file */
set_t *set_new(void);
bool set_insert(set_t *set, const char *key, void *item);
setnode_t *setnode_new(const char *key, void *item);
void set_delete(set_t *set, void(*itemdelete)(void *item));
void set_iterate(set_t *set, void *arg, void(*itemfunc)(void *arg, const char *key, void *item));
void set_print(set_t *set, FILE *fp, void(*itemprint)(FILE *fp, const char *key, void *item));
/*************** set_new() *****************/
set_t *set_new(void)
{
// Allocate memory for set and set pointer
set_t *set = malloc(sizeof(set_t));
// If the pointer is null (no items), then print an error
if (set == NULL) {
printf("Error: Set equal to Null\n");
return NULL;
} else {
set->head = NULL;
return set;
}
}
/******************** set_insert() ********************/
bool set_insert(set_t *set, const char *key, void *item)
{
// Check for set and item validity
if (set != NULL && item != NULL)
{
if(key != NULL) {
// Loop through the list, checking for identical keys
// allocate a new node for the linked list
setnode_t *new = setnode_new(key, item);
if (new != NULL) {
// add the node to the head of the set list
new->next = set->head;
set->head = new;
return true;
}
}
}
fprintf(stdout, "Set_Insert Error: parameter passed not valid\n");
return false;
}
void set_set(set_t *set, const char *key, char *newkey){
if(set_find(set,key)){
setnode_t *current_node = set->head;
while(current_node != NULL) {
// Find identical key for resetting
if(strcmp(current_node->key, key) == 0) {
current_node->key = newkey;
}
current_node = current_node->next;
}
}
}
/***************** setnode_new **********************/
/* Allocate and initialize a setnode */
setnode_t *setnode_new(const char *key, void *item)
{
setnode_t *node = malloc(sizeof(setnode_t));
if (node == NULL) {
// error allocating memory for node; returns data
return NULL;
} else {
node->key = malloc(sizeof(char)*(strlen(key)+1));
node->item = malloc(sizeof(char)*(strlen(item)+1));
strcpy(node->key, key);
strcpy(node->item,item);
node->next = NULL;
return node;
}
}
/************************ set_find() **************************/
void *set_find(set_t *set, const char *key) {
if(set == NULL || key == NULL) {
return NULL; // bad set or key
} else {
setnode_t *curr_node = set->head;
while(curr_node != NULL) {
if(strcmp(key, curr_node->key) == 0) {
return curr_node->item;
}
curr_node = curr_node->next;
}
return NULL;
}
}
void *set_find2(set_t *set, const char *key1, const char *key2) {
if(set == NULL || key1 == NULL || key2 == NULL) {
return NULL; // bad set or key
} else {
setnode_t *curr_node = set->head;
while(curr_node != NULL) {
if((strcmp(key1, curr_node->key) == 0) && (strcmp(key2, curr_node->item) == 0)) {
return curr_node->item;
}
if((strcmp(key2, curr_node->key) == 0) && (strcmp(key1, curr_node->item) == 0)) {
return curr_node->item;
}
curr_node = curr_node->next;
}
return NULL;
}
}
/*************************** set_print() **********************************/
void set_print(set_t *set, FILE *fp, void (*itemprint)(FILE *fp, const char *key, void *item) )
{
// Check file path validity
if (fp != NULL) {
// Check set validity
if (set != NULL && itemprint != NULL) {
// fprintf(fp, "{ KEY : VALUE }\n");
// fprintf(fp, "----------------\n");
// Loop through all the nodes
for(setnode_t *node = set->head; node != NULL; node = node->next) {
// Check validity of function passed
if(itemprint != NULL) {
// print the node's key and item
(*itemprint)(fp, node->key, node->item);
}
}
}
} else {
fputs("Error: null set or function pointers\n", fp);
}
}
/*************************** set_iterate() *****************************/
void set_iterate(set_t *set, void *arg, void(*itemfunc)(void *arg, const char *key, void *item))
{
if(set != NULL && arg != NULL) {
if(itemfunc != NULL) {
// call the (*itemfunc) with arg on each key and item
for(setnode_t *node = set->head; node != NULL; node = node->next) {
(*itemfunc)(arg, node->key, node->item);
}
}
}
}
/************************** set_delete() *******************/
void set_delete(set_t *set, void(*itemdelete)(void *item))
{
if (set != NULL) {
for (setnode_t *pair = set->head; pair != NULL;) {
if (itemdelete != NULL) {
(*itemdelete)(pair->item);
}
setnode_t *next = pair->next; // Store next pair
count_free(pair->key);
count_free(pair);
pair = next; // Iterate
}
count_free(set);
}
}
|
C | #include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "rngs.h"
int main(){
int i;
int k[10] = {adventurer, council_room, feast, gardens, mine,
remodel, smithy, village, baron, great_hall};
int tempCount;
int actualCount;
struct gameState G;
initializeGame(2, k, 1, &G);//Initialize game with 2 players
printf("TESTING supplyCount():\n");
printf("Initial Count of Adventurer is %d\n", supplyCount(adventurer, &G));
for (i = 0; i < 12; i++)
{
tempCount = supplyCount(adventurer, &G);
gainCard(7, &G, 0, 0);
actualCount = supplyCount(adventurer, &G);
if(tempCount > 0){
tempCount = tempCount - 1;
}
//int gainCard(int supplyPos, struct gameState *state, int toFlag, int player)
assert(tempCount == actualCount);
printf("Actual count = %d, expected count = %d\n", actualCount, tempCount);
}
printf("\nInitial Count of Province is %d\n", supplyCount(province, &G));
for (i = 0; i < 10; i++)
{
tempCount = supplyCount(province, &G);
gainCard(3, &G, 0, 0);
actualCount = supplyCount(province, &G);
if(tempCount > 0){
tempCount = tempCount - 1;
}
assert(tempCount == actualCount);
printf("Actual count = %d, expected count = %d\n", actualCount, tempCount);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.