language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strchr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jwalsh <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/04 12:35:54 by jwalsh #+# #+# */
/* Updated: 2016/11/10 18:45:44 by jwalsh ### ########.fr */
/* */
/* ************************************************************************** */
/*
** Locates the first occurrence of c (converted to char) in the string pointed
** to by s. The terminating null character is considered to be part of the
** string; therefore if c is \0, the function locates the \0.
** Returns a pointer to the located character or NULL if the character
** does not appear in the string.
*/
#include "libft.h"
char *ft_strchr(const char *s, int c)
{
size_t i;
i = 0;
while (s[i])
{
if (s[i] == (char)c)
return ((char *)s + i);
i++;
}
if (!c && !s[i])
return ((char *)s + i);
return (NULL);
}
|
C
|
/* Author: Nathan Smith, CST235
* Date: , '17
*/
#include <stdio.h>
#include <stdlib.h>
#include "funcs.h"
void iterateNumbers (int iArray[], int iSize, FNPTR_TYPE fn)
{
for (int i = 0; i < iSize; ++i)
{
printf("The value after the function pointer is applied is: %d\n", fn(iArray[i]));
}
}
|
C
|
#include"List.h"
void ListInit(pList lt)
{
assert(lt);
lt->head = (pListNode)malloc(sizeof(ListNode));
lt->head->prev = lt->head;
lt->head->next = lt->head;
}
void ListDestory(pList lt)
{
pListNode cur, del;
assert(lt);
cur = lt->head->next;
while (cur->next!= lt->head)
{
del = cur;
cur = cur->next;
free(del);
del = NULL;
}
free(lt->head);
lt->head = NULL;
}
pListNode BuyListNode(DataType x)
{
pListNode New = (pListNode)malloc(sizeof(ListNode));
New->data = x;
New->next = NULL;
New->prev = NULL;
return New;
}
void ListPushBack(pList lt, DataType x)
{
assert(lt);
ListInsert(lt->head, x);
}
void ListPushFront(pList lt, DataType x)
{
assert(lt);
ListInsert(lt->head->next, x);
}
void ListPopBack(pList lt)
{
assert(lt);
ListErase(lt->head->prev);
}
void ListPopFront(pList lt)
{
assert(lt);
ListErase(lt->head->next);
}
pListNode ListFind(pList lt, DataType x)
{
pListNode cur;
assert(lt);
cur = lt->head->next;
while (cur != lt->head)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
void ListInsert(pListNode pos, DataType x)
{
pListNode NewNode;
assert(pos);
NewNode = BuyListNode(x);
NewNode->data = x;
NewNode->prev = pos->prev;
pos->prev->next = NewNode;
NewNode->next = pos;
pos->prev = NewNode;
}
void ListErase(pListNode pos)
{
pListNode cur;
assert(pos);
cur = pos;
if (pos->next == pos)
{
printf("Ϊգɾ\n");
return;
}
pos->next->prev = pos->prev;
pos->prev->next = pos->next;
free(cur);
cur = NULL;
}
int ListSize(pList lt)
{
int count = 0;
pListNode cur;
assert(lt);
if (lt->head->next == lt->head)
return 0;
else
{
cur = lt->head->next;
while (cur != lt->head)
{
count += 1;
cur = cur->next;
}
return count;
}
}
int ListEmpty(pList lt)
{
assert(lt);
if (lt->head->next == lt->head)
return 0;
else
return 1;
}
void ListPrint(pList lt)
{
pListNode cur;
assert(lt);
cur = lt->head->next;
while (cur!= lt->head)
{
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void set_base_down(unsigned long long base[], unsigned long long down[], unsigned long long pre_sum[], unsigned long long n) {
for (int i = 0; i < (n+1)/2 + 1; i++) {
base[i] = (n-i)*4*i+1;
}
for (int i = 0; i < (n+1)/2; i++) {
down[i] = base[i+1]+base[i]+n-2*i-1;
}
pre_sum[0] = 0;
for (int i = 0; i < (n+1)/2 - 1; i++) {
pre_sum[i+1] = pre_sum[i] + down[i];
}
}
unsigned long long plus(int i, int n, unsigned long long base[], unsigned long long down[], unsigned long long pre_sum[]) {
unsigned long long sum = 0;
int j = 0;
int r_i = i < (n+1)/2?i:n-i-1;
sum = pre_sum[r_i];
if (i < (n+1)/2) {
sum += (base[i]*2 + n - 1 - 2*i) * (n-2*i)/2;
}
else {
sum += down[r_i] * (n-2*r_i)/ 2;
}
return sum;
}
int main(){
int n;
scanf("%d", &n);
unsigned long long *base = (unsigned long long *)malloc(sizeof(unsigned long long)*((n+1)/2+1));
unsigned long long *down = (unsigned long long *)malloc(sizeof(unsigned long long)*(n+1)/2);
unsigned long long *pre_sum = (unsigned long long *)malloc(sizeof(unsigned long long)*(n+1)/2);
set_base_down(base, down, pre_sum, n);
for (int i = 0; i < n; i++) {
fprintf(stdout, "%llu\n", plus(i, n, base, down, pre_sum));
}
return 0;
}
// int main(int argc, char *argv[]){
// int n,i;
// sscanf(argv[1], "%d", &n);
// sscanf(argv[2], "%d", &i);
// unsigned long long *base = (unsigned long long *)malloc(sizeof(unsigned long long)*((n+1)/2+1));
// unsigned long long *down = (unsigned long long *)malloc(sizeof(unsigned long long)*(n+1)/2);
// unsigned long long *pre_sum = (unsigned long long *)malloc(sizeof(unsigned long long)*(n+1)/2);
// set_base_down(base, down, pre_sum, n);
//
// fprintf(stdout, "%llu\n", plus(i, n, base, down, pre_sum));
//
// return 0;
// }
|
C
|
#include <stdio.h>
#define MAX 10
int queue[MAX];
int front = -1, rear = -1;
void insert(void);
int delete(void);
int peek(void);
void display(void);
int main()
{
int option, num;
do
{
printf("\n ***** MAIN MENU *****");
printf("\n 1. Insert an element: ");
printf("\n 2. Delete an element: ");
printf("\n 3. Peek an element");
printf("\n 4. Display all elements");
printf("\n 5. EXIT");
printf("\n Enter an option: ");
scanf("%d", &option);
switch(option)
{
case 1:
insert();
break;
case 2:
num = delete();
if (num != -1)
printf("\n The number deleted is %d \n", num);
break;
case 3:
num = peek();
if (num != -1)
printf("\n The FIFO value in queue is: %d \n", num);
break;
case 4:
display();
break;
}
}while(option != 5);
return 0;
}
void insert()
{
int num;
printf("\n Enter the number to be inserted: ");
scanf("%d", &num);
if (rear == MAX - 1)
printf("\n OVERFLOW");
else if(front == - 1 && rear == -1)
front = rear = 0;
else
++rear;
queue[rear] = num;
}
int delete()
{
int val;
if (front == -1 || front > rear)
{
printf("\n UNDERFLOW\n");
return -1;
}
else
{
val = queue[front++];
if(front > rear)
front = rear = -1;
return val;
}
}
int peek()
{
if(front == -1 || front > rear)
printf("\n THE QUEUE IS EMPTY \n");
else
return queue[front];
return -1;
}
void display()
{
int i;
printf("\n");
if(front == -1 || front > rear)
printf("\n THE QUEUE IS EMPTY");
else
for ( i = front; i <= rear; ++i )
printf("\t %d", queue[i]);
printf("\n");
}
|
C
|
#include <stdio.h>
#include "arq.h"
FILE *open_arq(char *n){
FILE *novo = fopen(n, "r");
return novo;
}
void pega_linha(FILE *n, int *l, int *co, float *v){
float val;
int cont = 0, pos = 0, flag = 0, lin, col;
char temp[10], c;
do{
c = fgetc(n);
if(feof(n) && flag == 0){
*l = -1;
*co = -1;
return;
}
flag = 1;
if(c == ';'){
switch(cont){
case 0:
temp[pos] = 0;
sscanf(temp, "%d", &lin);
pos = 0;
cont++;
break;
case 1:
temp[pos] = 0;
sscanf(temp, "%d", &col);
pos = 0;
cont++;
break;
}
}else if(c == '\n'){
temp[pos] = 0;
sscanf(temp, "%f", &val);
*l = lin;
*co = col;
*v = val;
return;
}else{
temp[pos] = c;
pos++;
}
}while(!feof(n));
temp[pos] = 0;
sscanf(temp, "%f", &val);
*l = lin;
*co = col;
*v = val;
return;
}
int pega_topo(FILE *n){
char temp[20], c;
int val, cont =0;
while(c != '\n'){
c = fgetc(n);
temp[cont] = c;
cont++;
}
temp[cont] = 0;
sscanf(temp, "%d", &val);
return val;
}
void fecha_arq(FILE *f){
fclose(f);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void ary_copy(int a[], const int b[], int n) {
int i;
for (i = 0; i < n; i++) {
a[i] = b[i];
}
for ( i = 0; i < n; i++)
{
printf("%d", a[i]);
}
}
int main(void) {
int number;
int *a;
int *b;
int i;
printf("迭 Էϼ");
scanf_s("%d", &number);
a = calloc(number, sizeof(int));
b = calloc(number, sizeof(int));
if (a == NULL)
printf(" Ȯ ߽ϴ:)");
else {
printf("Ҹ Էּ");
for ( i = 0; i < number; i++)
{
scanf_s("%d", &b[i]);
}
ary_copy(a, b, number);
free(a);
free(b);
}
system("pause");
return 0;
}
|
C
|
// register address
#define PERI_BASE 0x20000000
#define GPIO_BASE (PERI_BASE + 0x200000)
#define BLOCK_SIZE 4096
// gpio pinmode
#define INPUT 0x0
#define OUTPUT 0x1
#define ALT0 0x4
#define ALT1 0x5
#define ALT2 0x6
#define ALT3 0x7
#define ALT4 0x3
#define ALT5 0x2
static volatile unsigned int *Gpio = NULL;
void gpio_init ()
{
if (Gpio) return;
int fd;
void *gpio_map;
fd = open("/dev/mem", O_RDWR | O_SYNC);
if (fd == -1) {
printf("error: cannot open /dev/mem (gpio_setup)\n");
exit(-1);
}
gpio_map = mmap(NULL, BLOCK_SIZE,
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, GPIO_BASE );
if ((int) gpio_map == -1) {
printf("error: cannot map /dev/mem on the memory (gpio_setup)\n");
exit(-1);
}
close(fd);
Gpio = (unsigned int *) gpio_map;
}
void gpio_configure (int pin, int mode)
{
int index = pin / 10;
unsigned int mask = ~(0x7 << ((pin % 10) * 3));
Gpio[index] = (Gpio[index] & mask) | ((mode & 0x7) << ((pin % 10) * 3));
}
void gpio_set (int pin)
{
Gpio[7] = 0x1 << pin;
}
void gpio_clear (int pin)
{
Gpio[10] = 0x1 << pin;
}
|
C
|
/*
** toolbox.c for navy in /home/boissi_p/rendu/PSU_2016_navy/src
**
** Made by Pierre-Malick Boissiere
** Login <boissi_p@epitech.net>
**
** Started on Mon Jan 30 15:06:31 2017 Pierre-Malick Boissiere
** Last update Sun Feb 19 16:28:54 2017 Pierre-Malick Boissiere
*/
#include "my.h"
int my_strlen(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
i++;
return (i);
}
void my_putstr(char *str)
{
write(1, str, my_strlen(str));
}
int my_getnbr(char *str)
{
int i;
int nbr;
i = 0;
nbr = 0;
if (str[i] < '0' && str[i] > '9')
i = i + 1;
else
{
while (str[i] >= '0' && str[i] <= '9')
{
nbr = ((nbr * 10) + (str[i] - 48));
i = i + 1;
}
}
return (nbr);
}
char *my_strcat(char *dest, char *src)
{
int count;
int i;
count = 0;
i = 0;
if (dest != NULL && src != NULL)
{
while (dest[count] != '\0')
count += 1;
while (src[i] != '\0')
dest[count++] = src[i++];
dest[count] = '\0';
return (dest);
}
return (dest);
}
void my_put_nbr(int n)
{
int c;
c = 0;
if (n < 0)
{
write(1, "-", 1);
n = -n;
}
if (n >= 10)
my_put_nbr(n / 10);
c = ((n % 10) + '0');
write(1, &c, 1);
}
|
C
|
#include "uart.h"
#include "string.h"
#include "bootloader.h"
#define INPUT_BUFFER_SIZE 64
void system_start()
{
uart_puts("---------------------------\n");
uart_puts("Raspberry Pi 3B+ Bootloader\n");
uart_puts("---------------------------\n");
}
int main()
{
// set uart
uart_init();
system_start();
char cmd[INPUT_BUFFER_SIZE];
while (1)
{
uart_puts("\r# ");
memset(cmd, 0, INPUT_BUFFER_SIZE);
uart_gets(cmd, INPUT_BUFFER_SIZE);
uart_send('\r');
uart_send('\n');
if (strcmp(cmd, "") == 0)
continue;
else if(strcmp(cmd, "hello") == 0)
uart_puts("Hello World!\n");
else if(strcmp(cmd, "load_images") == 0){
loadimg();
}
else{
uart_puts("Not find\n");
}
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_piece.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: plaurent <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/22 18:25:16 by plaurent #+# #+# */
/* Updated: 2019/05/29 18:09:49 by plaurent ### ########.fr */
/* */
/* ************************************************************************** */
#include "filler.h"
static int test_line(char **tab)
{
int i;
i = 0;
while (tab[i])
i++;
if (i != 3)
return (0);
if (ft_strcmp(tab[0], "Piece") != 0)
return (0);
return (1);
}
int piece_info(t_asset *asset)
{
char **tab;
char *line;
tab = NULL;
if (get_next_line(0, &line, 0) != 1)
return (1);
if (!(tab = ft_strsplit(line, ' ')))
{
ft_strdel(&line);
return (1);
}
ft_strdel(&line);
if (test_line(tab) != 1)
{
free_tab(&tab);
return (1);
}
asset->y_pmax = ft_atoi(tab[1]);
asset->x_pmax = ft_atoi(tab[2]);
free_tab(&tab);
if (asset->y_pmax <= 0 || asset->x_pmax <= 0)
return (1);
return (0);
}
static int test_line2(char *line, int x_pmax)
{
int i;
i = -1;
while (line[++i])
if ((line[i] != '.' && line[i] != '*') || i > x_pmax)
return (0);
if (i != x_pmax)
return (0);
return (1);
}
int get_piece(t_asset *asset)
{
char *line;
int i;
i = 0;
if (!(asset->piece = (char **)malloc(sizeof(char *) * (asset->y_pmax + 1))))
return (1);
while (i <= asset->y_pmax - 1)
{
if ((get_next_line(0, &line, 0)) != 1)
return (1);
if (test_line2(line, asset->x_pmax) != 1)
{
asset->piece[i] = NULL;
ft_strdel(&line);
return (1);
}
if (!(asset->piece[i++] = ft_strsub(line, 0, asset->x_pmax)))
{
ft_strdel(&line);
return (1);
}
ft_strdel(&line);
}
asset->piece[i] = NULL;
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int key;
} element;
void buildFlag(void);
void mergeSort(element initList[], int n);
void mergePass(element initList[], element mergedList[], int n, int s);
void merge(element initList[], element mergeList[], int i, int m, int n);
void printList(void);
element initList[30], mergedList[30];
int accu[10] = {0}, part[10] = {0};
int num = 1, n = 1;
int main(void)
{
FILE *fptr;
fptr = fopen("set.txt", "r");
while(1){/*ŪɡAlistsiinitList array */
fscanf(fptr, "%d%*c", &initList[num++]);
if(feof(fptr)) break;
}
fclose(fptr);
num--; /*num is # of records*/
buildFlag();
mergeSort(initList, n);
printList();
getchar();
return 0;
}
void buildFlag(void)
{
int i;
for(i = 1; i < num; i++){/*prevailing order within the input list*/
if(initList[i].key > initList[i+1].key){
accu[n++] = i;
}
}/*n is # of ordered sublists*/
accu[n] = num; /*accu array sublists̫@index */
for(i = 1; i <= n ; i++){/*part array ثeCsublistrecordӼ*/
part[i] = accu[i] - accu[i-1];
}
}
void mergeSort(element initList[], int n)
{
int s = 1;
int i, j;
while(s < n){
mergePass(initList, mergedList, n, s);
s *= 2;
j = 1;
/* update part array */
for(i = 1; i <= (n/s)+1 ; i++){
part[i] = part[j] + part[j+1];
j+=2;
}
/* update initList */
for(i = 0; i < num; i++)
initList[i] = mergedList[i];
}
}
void mergePass(element initList[], element mergedList[], int n, int s)
{
int i, j, k;
for(i = 1; i <= n-2*s+1; i +=2*s){/*@*/
merge(initList, mergedList, accu[i], accu[i]+part[i]-1, accu[i+2*s-1]);
}
if(i+s-1 < n)/*̫@*/
merge(initList, mergedList, accu[i], accu[i]+part[i]-1, accu[n]);
else/*Sժ*/
for(j = i; j <= n; j++)
mergedList[accu[j]] = initList[accu[j]];
}
void merge(element initList[], element mergeList[], int i, int m, int n)
{
int j, k, t;
j = m+1;
k = i;
while(i <= m && j <= n){
if(initList[i].key <= initList[j].key)
mergedList[k++] = initList[i++];
else
mergedList[k++] = initList[j++];
}
if(i > m)
for(t = j; t <= n; t++)
mergedList[k++] = initList[t];
else
for(t = i; t <= m; t++)
mergedList[k++] = initList[t];
}
void printList(void)
{/*LXmergedList*/
int i;
for(i = 1; i < num; i++){
printf("%d,", mergedList[i]);
}
printf("%d", mergedList[i]);
}
|
C
|
#include "libft.h"
char *ft_strrev(char *str)
{
char swap;
int j;
int c;
j = 0;
c = 0;
while (str[c] != '\0')
{
c++;
}
c--;
while (c > j)
{
swap = str[c];
str[c] = str[j];
str[j] = swap;
c--;
j++;
}
return (str);
}
|
C
|
#include<stdio.h>
char c[1000];
int main ()
{
int i;
char s[100];
gets(s);
for(i=0;i<strlen(s);i++){
s[i]=s[i];
}
if(strcmp(s,strrev(s))){
printf("Not Palindrome\n");
}
else{
printf("Palindrome\n");
}
return 0;
}
|
C
|
//
// test3.c
//
//
// Created by Michael Geiger on 4/13/17.
// Simple program to be run in OS Project 1
//
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = getpid();
printf("Running program test3 in process %d\n", (int)pid);
if ((int)pid % 2)
printf("T3: PID %d is odd\n", (int)pid);
else
printf("T3: PID %d is even\n", (int)pid);
return 0;
}
|
C
|
/*****************************************************************************
* Copyright Statement:
* --------------------
* MobileTech(Shanghai) Co., Ltd.
*
*****************************************************************************/
/*****************************************************************************
*
* Filename:
* ---------
* oa_llist.h
*
* Project:
* --------
* OPEN AT project
*
* Description:
* ------------
* This Module defines llist function.
*
* Author:
* -------
* .
*
****************************************************************************/
#ifndef _LLIST_H
#define _LLIST_H
/**
* container_of - cast a member of a structure out to the containing structure
*
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
/*
* These are non-NULL pointers that will result in page faults
* under normal circumstances, used to verify that nobody uses
* non-initialized llist entries.
*/
#define LLIST_POISON1 (0)
#define LLIST_POISON2 (0)
/*
* Simple doubly linked llist implementation.
*
* Some of the internal functions ("__xxx") are useful when
* manipulating whole llists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/
typedef struct llist_head_t{
struct llist_head_t *next, *prev;
}llist_head;
#define LLIST_HEAD_INIT(name) { &(name), &(name) }
#define LLIST_HEAD(name) \
llist_head name = LLIST_HEAD_INIT(name)
#define INIT_LLIST_HEAD(ptr) do { \
(ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal llist manipulation where we know
* the prev/next entries already!
*/
static void __llist_add(llist_head *p,
llist_head *prev,
llist_head *next)
{
next->prev = p;
p->next = next;
p->prev = prev;
prev->next = p;
}
/**
* llist_add - add a new entry
* @new: new entry to be added
* @head: llist head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static void llist_add(llist_head *p, llist_head *head)
{
__llist_add(p, head, head->next);
}
/**
* llist_add_tail - add a new entry
* @new: new entry to be added
* @head: llist head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static void llist_add_tail(llist_head *p, llist_head *head)
{
__llist_add(p, head->prev, head);
}
/*
* Delete a llist entry by making the prev/next entries
* point to each other.
*
* This is only for internal llist manipulation where we know
* the prev/next entries already!
*/
static void __llist_del(llist_head * prev, llist_head * next)
{
next->prev = prev;
prev->next = next;
}
/**
* llist_del - deletes entry from llist.
* @entry: the element to delete from the llist.
* Note: llist_empty on entry does not return true after this, the entry is
* in an undefined state.
*/
static void llist_del(llist_head *entry)
{
__llist_del(entry->prev, entry->next);
entry->next = LLIST_POISON1;
entry->prev = LLIST_POISON2;
}
/**
* llist_del_init - deletes entry from llist and reinitialize it.
* @entry: the element to delete from the llist.
*/
static void llist_del_init(llist_head *entry)
{
__llist_del(entry->prev, entry->next);
INIT_LLIST_HEAD(entry);
}
/**
* llist_move - delete from one llist and add as another's head
* @llist: the entry to move
* @head: the head that will precede our entry
*/
static void llist_move(llist_head *llist, llist_head *head)
{
__llist_del(llist->prev, llist->next);
llist_add(llist, head);
}
/**
* llist_move_tail - delete from one llist and add as another's tail
* @llist: the entry to move
* @head: the head that will follow our entry
*/
static void llist_move_tail(llist_head *llist,
llist_head *head)
{
__llist_del(llist->prev, llist->next);
llist_add_tail(llist, head);
}
/**
* llist_empty - tests whether a llist is empty
* @head: the llist to test.
*/
static int llist_empty(const llist_head *head)
{
return head->next == head;
}
/**
* llist_entry - get the struct for this entry
* @ptr: the &llist_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the llist_struct within the struct.
*/
#define llist_entry(ptr, type, member) \
container_of(ptr, type, member)
#endif
|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: ConvierteAMayusculas.c
* Author: virgiliopadronbatun
*
* Created on 24 de julio de 2018, 17:43
*/
#include <stdio.h>
#include <stdlib.h>
// Figura 7.10: fig07_10.c
#include <ctype.h>
void convierteAMayusculas( char *ptrS );
int main() {
char cadena[] = "caracteres y $32.98"; /* inicializa char arreglo */
printf( "La cadena antes de la conversion es : %s", cadena );
convierteAMayusculas( cadena );
printf( "\nLa cadena despues de la conversion es: %s\n", cadena );
return 0; /* indica terminacion exitosa */
}
//mediante un apuntador no constante a un dato no constante */
/* convierte una cadena a letras mayusculas */
void convierteAmayusculas( char *ptrS ) {
while ( *ptrS != '\0' ) { /* el carácter actual no es el caracter nulo */
if ( islower( *ptrS ) ) { /* si el caracter es minuscula, */
*ptrS = toupper( *ptrS ); /* Lo convierte a mayuscula */
}
++ptrS; /* mueve ptrS al siguiente caracter */
}
}
//Impresion de una cadena caracter por caracter mediante
//un apuntador no constante a un dato constante */
//Puedo modificar la direccion de memoria a la cual apunta el apuntador.
//Siempre y cuando sea una variable const char, pero no puedo modificar los valores ya que es const
void imprimeCaracteres( const char *ptrS ) {
for( ; *ptrS != '\0'; ptrS++){
printf( "%c", *ptrS );
}
}
//Un apuntador constante a una variable no constante, osea podemos modificar el valor de la variable pero no del apuntador
//El apuntador debe inicializarse cuando se declara.
/* ptr es un apuntador constante a un entero que se puede modificar a traves de ptr,
* pero ptr siempre apunta a la misma ubicacion de memoria */
// int *const ptr = &x;
// *ptr = 7; /* permitido: *ptr no es const */
// ptr = &y; /* error: ptr es const; no se puede asignar una nueva direccion */
/* ptr es un apuntador constante a un entero constante. ptr siempre apunta a la misma ubicacion;
* el entero en esa ubicacion no se puede modificar */
// const int *const ptr = &x;
// *ptr = 7; /* error: *ptr es const; no se puede asignar un nuevo valor */
// ptr = &y; /* error: ptr es const; no se puede asignar una nueva direccion */
|
C
|
//
// Created by Yassin Alsahlani on 9/6/18.
//
#include <stdio.h>
#include <stdlib.h>
/*
Baseline
ECE 2035 Homework 1-2
This is the only file that should be modified for the C implementation
of Homework 1.
This program computes the index (ClassID) at which the maximum value occurs
in a set of 10 confidence values.
If there are two or more indices that have equal maximum values, the LARGER
index is chosen.
FOR FULL CREDIT, BE SURE TO TRY MULTIPLE TEST CASES and DOCUMENT YOUR CODE.
*/
//DO NOT change the following declaration (you may change the initial value).
unsigned ConfidenceValues[] = {1, 70, 0, 0, 21, 2, 3, 0, 3, 0}; // 1
unsigned ClassID;
/*
For the grading scripts to run correctly, the above declarations
must be the first lines of code in this file (for this homework
assignment only). Under penalty of grade point loss, do not change
these lines, except to replace the initial values while you are testing
your code.
Also, do not include any additional libraries.
*/
int main() {
ClassID = 0;
/*
* Code Starts Here
*/
int len = sizeof(ConfidenceValues)/ sizeof(ConfidenceValues[0]); //storing the length of the array in a local variable
for (int i = 0; i < len; ++i) { //looping through the array to find the largest value and compare it with the value we aleardy have
if (ConfidenceValues[i] >= ConfidenceValues[ClassID]){
ClassID = i;
}
}
// Your program should use this print statement.
// Do not change the format!
printf("%d is the class with highest confidence value.\n", ClassID);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char const *argv[]) {
int x1,y1,x2,y2;
printf("Entre com o primeiro ponto\n" );
scanf("%d %d",&x1,&y1 );
printf("Entre com o segundo ponto\n" );
scanf("%d %d",&x2,&y2 );
printf("%0.2f\n",sqrt(pow(x2-x1,2)+pow(y2-y1,2)));
return 0;
}
|
C
|
#include<stdio.h>
main(){
int i,j,array [3] [2];
for (i=0; i<3; i++){
for (j=0; j<2;j++)
scanf ("%d",&array [i] [j]);
}
for (i=0; i<3; i++){
for ( j=0; j<2; j++){
printf("\t%d\t", array [i] [j]);
}
printf("\n");
}
for ( j=0; j<3; j++)
{
array[j][1]=array[j][0]+array[j][1];
printf("%d\n",array[j][1]);
}
}
|
C
|
/**
* @file journal.c
*
* Function implementations for journaling.
*/
#include "journal.h"
#include "server-part1.h"
int callocs = 0;
int frees = 0;
int log_transaction(transaction *tx) {
pthread_mutex_lock(&journal_mutex);
FILE *file = fopen("tx_log", "a");
struct stat st;
size_t data_len = 0;
long bytes_written = 0;
long remaining_bytes = 0;
char *rbb = NULL;
if (file == NULL) {
perror("Could not open tx_log: ");
return -1;
}
tx->txb.txid = rand();
if (!fwrite(&(tx->txb.txid), 1, sizeof(int), file)) { // issue begin (txid)
perror("Could not write txid: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int)); // delete txid
perror("Could not flush txid: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
bytes_written += sizeof(int);
data_len = tx->db.data_len; // length prefix for easy unmarshalling
if (!fwrite(&(tx->db.data_len), 1, sizeof(size_t), file)) { // issue data length
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int)); // delete txid
perror("Could not write db.data_len: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t)); // delete txid/data_len
perror("Could not flush db.data_len: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
bytes_written += sizeof(size_t);
if (!fwrite(tx->db.data, 1, data_len, file)) { // issue data
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t)); // delete txid/data_len
perror("Could not write db.data: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len); // delete txid/data_len/data
perror("Could not flush db.data: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
bytes_written += data_len;
if (!fwrite("\0", 1, 1, file)) { // issue null byte
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len); // delete txid/data_len/data
perror("Could not write nullbyte: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1); // delete txid/data_len/data/nullbyte
perror("Could not flush nullbyte: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
bytes_written += 1;
tx->valid = 1; // mark transaction as valid
if (!fwrite(&( tx->valid ), 1, sizeof(int), file)) { // issue valid entry indicator
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1); // delete txid/data_len/data/nullbyte
perror("Could not write valid flag: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1 - sizeof(int)); // delete txid/data_len/data/nullbyte/valid
perror("Could not flush valid flag: "); fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
bytes_written += sizeof(int);
tx->txe.committed = 1; // other writes good, mark committed flag
if (!fwrite(&( tx->txe.committed ), 1, sizeof(int), file)) { // issue commit flag
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1 - sizeof(int)); // delete txid/data_len/data/nullbyte/valid
perror("Could not write committed flag: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1 - sizeof(int) - sizeof(int)); // delete txid/data_len/data/nullbyte/valid/committed
perror("Could not flush committed flag: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
bytes_written += sizeof(int);
if (!fwrite("\n", 1, 1, file)) { // issue entry delimiter
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1 - sizeof(int) - sizeof(int)); // delete txid/data_len/data/nullbyte/valid/committed
perror("Could not flush newline: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1 - sizeof(int) - sizeof(int) - 1); // delete txid/data_len/data/nullbyte/valid/committed/newline
perror("Could not flush newline: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
bytes_written += 1;
remaining_bytes = MAX_JOURNAL_ENTRY_SIZE - bytes_written;
rbb = (char *) calloc(remaining_bytes, sizeof(char));
if (!fwrite(rbb, 1, remaining_bytes, file)) { // fill entry to MAX_J--, dont need newline then but leave for now
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1 - sizeof(int) - sizeof(int) - 1); // delete txid/data_len/data/nullbyte/valid/committed/newline
perror("Could not flush remaining_bytes: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (fflush(file) != 0) {
stat("tx_log", &st);
ftruncate(fileno(file), st.st_size - sizeof(int) - sizeof(size_t) - data_len - 1 - sizeof(int) - sizeof(int) - 1 - remaining_bytes); // delete txid/data_len/data/nullbyte/valid/committed/newline
perror("Could not flush remaining_bytes: ");
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
free(rbb);
// bytes_written += remaining_bytes; // dont care
// log entry successfully written
fclose(file);
pthread_mutex_unlock(&journal_mutex);
// return tx->txb.txid;
return 0; // OK
}
int unmarshall_journal_entry(transaction *tmp_transaction, char *tmp_entry) {
// need to change to make sure we account for a botched journal entry (i.e. the last one in the case of a sudden server crash)
// this may try to read out of bounds of tmp_entry if tmp_entry is messed up
char *entry_pos = tmp_entry;
memcpy(&(tmp_transaction->txb.txid), entry_pos, sizeof(int)); // txid
entry_pos += sizeof(int);
memcpy(&(tmp_transaction->db.data_len), entry_pos, sizeof(size_t)); // length prefix
entry_pos += sizeof(size_t);
tmp_transaction->db.data = (char *) calloc(tmp_transaction->db.data_len + 1, sizeof(char));
callocs++;
printf("callocs: %d\n", callocs);
// printf("db.data: %s, db.data_len: %d\n", tmp_transaction->db.data, tmp_transaction->db.data_len);
printf("asking for %d bytes: %s\n", (tmp_transaction->db.data_len + 1), strerror(errno));
memcpy(tmp_transaction->db.data, entry_pos, tmp_transaction->db.data_len + 1); // data and null byte
entry_pos += tmp_transaction->db.data_len + 1;
memcpy(&(tmp_transaction->valid), entry_pos, sizeof(int)); // valid
entry_pos += sizeof(int);
memcpy(&(tmp_transaction->txe.committed), entry_pos, sizeof(int)); // committed
entry_pos += sizeof(int);
// dont need newline char
return 0;
}
int remove_transaction(int txid) {
pthread_mutex_lock(&journal_mutex);
char *tmp_entry = (char *) calloc(MAX_JOURNAL_ENTRY_SIZE, sizeof(char));
transaction *tmp_transaction = (transaction *) calloc(sizeof(transaction), sizeof(char));
int temp_txid = 0;
long offset = 0;
int z = 0;
FILE *file = fopen("tx_log", "r+");
if (file == NULL) {
perror("Could not open tx_log: ");
pthread_mutex_unlock(&journal_mutex);
return -1;
}
while (1) {
if (fgets(tmp_entry, MAX_JOURNAL_ENTRY_SIZE, file) != NULL) { // read to newline (including newline char, and advances file position to next entry)
if (unmarshall_journal_entry(tmp_transaction, tmp_entry) != 0) {
perror("Could not unmarshall journal entry: ");
free(tmp_transaction);
free(tmp_entry);
tmp_entry = NULL;
tmp_transaction = NULL;
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
temp_txid = tmp_transaction->txb.txid;
if (temp_txid == txid) { // found transaction in log
if (!tmp_transaction->valid) { // if already marked as invalid, ignore
free(tmp_entry);
tmp_entry = NULL;
tmp_transaction = NULL;
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return 0;
}
// otherwise, seek back and mark invalid
offset = (sizeof(int) + sizeof(int) + 1) * -1;
fseek(file, offset, SEEK_CUR);
fwrite(&z, 1, sizeof(int), file); // mark transaction as invalid (subsequent recovers/removes should ignore it)
if (fflush(file) != 0) {
perror("Could not remove transaction: ");
free(tmp_entry);
tmp_entry = NULL;
tmp_transaction = NULL;
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1;
}
free(tmp_entry);
tmp_entry = NULL;
tmp_transaction = NULL;
// rewind(file); // dont need
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return 0;
}
} else { // end of file
break;
}
}
if (tmp_transaction->db.data) {
free(tmp_transaction->db.data);
}
free(tmp_transaction);
free(tmp_entry);
tmp_entry = NULL;
tmp_transaction = NULL;
fclose(file);
pthread_mutex_unlock(&journal_mutex);
return -1; // tx not found
}
int flush_log() {
int rc;
// pthread_mutex_lock(&journal_mutex);
rc = remove("tx_log");
// pthread_mutex_unlock(&journal_mutex);
return rc;
}
int recover() {
pthread_mutex_lock(&journal_mutex);
char *tmp_entry = (char *) calloc(MAX_JOURNAL_ENTRY_SIZE, sizeof(char));
transaction *tmp_transaction = (transaction *) calloc(sizeof(transaction), sizeof(char));
callocs+=2;
char *key = NULL;
char *value = NULL;
char *request_type;
char *response = NULL;
char *save_ptr;
int response_size;
int read_bytes = 0;
FILE *file = fopen("tx_log", "r");
if (file == NULL) {
perror("Could not open tx_log: ");
pthread_mutex_unlock(&journal_mutex);
return -1;
}
while (1) { // should we be re-journaling while replaying journal? cant read/write to tx_log at the same time though
// if (fgets(tmp_entry, MAX_JOURNAL_ENTRY_SIZE, file) != NULL) { // if system crash at any point, only the last line in journal should be messed up
if ((read_bytes = fread(tmp_entry, sizeof(char), MAX_JOURNAL_ENTRY_SIZE, file)) == MAX_JOURNAL_ENTRY_SIZE) {
printf("readbytes: %d\n", read_bytes);
if (unmarshall_journal_entry(tmp_transaction, tmp_entry) != 0) {
perror("Could not unmarshall journal entry: ");
free(tmp_transaction);
free(tmp_entry);
tmp_entry = NULL;
tmp_transaction = NULL;
printf("closing file-1: %d\n", fileno(file));
fclose(file);
printf("closed file-1\n");
pthread_mutex_unlock(&journal_mutex);
return -1;
}
if (!tmp_transaction->valid) {
continue; // ignore
}
request_type = strtok_r(tmp_transaction->db.data, " ", &save_ptr);
key = strtok_r(NULL, " ", &save_ptr);
value = strtok_r(NULL, " ", &save_ptr);
if (request_type == NULL || key == NULL) {
printf("Invalid key/command received\n");
} else if (strncmp(request_type, "GET", 3) == 0) {
printf("serving get...\n");
server_1_get_request(key, &response, &response_size);
printf("done serving request\n");
} else if (strncmp(request_type, "PUT", 3) == 0) {
printf("serving put...\n");
server_1_put_request(key, value, &response, &response_size);
printf("done serving request\n");
} else if (strncmp(request_type, "INSERT", 6) == 0) {
printf("serving insert...\n");
server_1_insert_request(key, value, &response, &response_size);
printf("done serving request\n");
} else if (strncmp(request_type, "DELETE", 6) == 0) {
printf("serving delete...\n");
server_1_delete_request(key, &response, &response_size);
printf("done serving request\n");
} else { // incorrectly formatted journal entry, ignore
continue;
}
if (tmp_transaction->db.data) {
free(tmp_transaction->db.data);
tmp_transaction->db.data = NULL;
frees++;
printf("frees: %d\n", frees);
}
if (response != NULL) {
free(response);
}
response = NULL;
} else { // short read or zero read -> EOF or malformed entry? either way exit
printf("readbytes: %d\n", read_bytes);
printf("errno: %s\n", strerror(errno));
printf("===========\n");
printf("closing file-2: %d\n", fileno(file));
fclose(file);
printf("closed file-2\n");
break;
}
}
if (tmp_transaction->db.data) {
free(tmp_transaction->db.data);
tmp_transaction->db.data = NULL;
}
free(tmp_transaction);
free(tmp_entry);
frees += 2;
printf("frees: %d\n", frees);
// printf("closing file-2: %d\n", fileno(file));
// if (fclose(file) != 0) {
// perror("Error closing file: ");
// }
// printf("closed file-2\n");
remove("tx_log"); // flush_log but already have lock
pthread_mutex_unlock(&journal_mutex);
return 0;
}
|
C
|
/*********************************************************************************
Copyright 2006-2009 MakingThings
Licensed under the Apache License,
Version 2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for
the specific language governing permissions and limitations under the License.
*********************************************************************************/
#include "digitalin.h"
#include "core.h"
// This number is 4 because the a/d converter is sitting on the IO's 4 - 7
// this means that we'll need to use the A/d converter to get the digital value.
// Crazy, eh? And slow. Whew.
#define DIGITALIN_COUNT 8
#ifndef DIGITALIN_THRESHOLD
#define DIGITALIN_THRESHOLD 200
#endif
// only need symbols for the first 4 since the others are ains
#define DIGITALIN_0 PIN_PB27
#define DIGITALIN_1 PIN_PB28
#define DIGITALIN_2 PIN_PB29
#define DIGITALIN_3 PIN_PB30
static void digitalinAutoSendInit(void);
/**
\defgroup digitalin Digital Input
Read the 8 inputs on the Application Board as digital values - on or off.
\section Usage
Use digitalinValue() to read digital in values.
\section Notes
Internally, the 8 inputs on the Application Board consist of 4 dedicated analog inputs,
and 4 lines which can be configured either as digitial ins or outs. Because digital
ins 4-7 are always \ref analogin lines, there's no performance gain to reading those as DigitalIns
as opposed to AnalogIns.
\ingroup io
@{
*/
void digitalinInit()
{
#ifdef OSC
digitalinAutoSendInit();
#endif
}
static int digitalinGetPin(int index)
{
switch (index) {
case 0: return DIGITALIN_0;
case 1: return DIGITALIN_1;
case 2: return DIGITALIN_2;
case 3: return DIGITALIN_3;
default: return 0;
}
}
/**
Read the value of a Digital Input on the MAKE Application Board.
If the voltage on the input is greater than ~0.6V, the Digital In will read high.
@param channel The digital in channel to read - valid options are 0-7.
@return True when high, false when low.
\b Example
\code
if (digitalinValue(5) == ON) {
// DigitalIn 5 is high
}
else {
// DigitalIn 5 is low
}
\endcode
*/
bool digitalinValue(int channel)
{
if (channel > 3)
return analoginValue(channel) > DIGITALIN_THRESHOLD;
else
return pinValue(digitalinGetPin(channel));
}
/** @}
*/
#ifdef OSC
/** \defgroup DigitalInOSC Digital In - OSC
Read the Application Board's Digital Inputs via OSC.
\ingroup OSC
\section devices Devices
There are 8 Digital Inputs on the Make Application Board, numbered <b>0 - 7</b>.
The Digital Ins are physically the same as the Analog Ins - they're on the same
signal lines and the same connectors - but reading them as Digital Ins is
slightly more efficient/quicker.
If the voltage on the input is greater than <b>~0.6V</b>, the Digital In will read high.
\section properties Properties
The Digital Ins have the following properties
- value
\par Value
The \b value property corresponds to the on/off value of a Digital In.
Because you can only ever \b read the value of an input, you'll never
want to include an argument at the end of your OSC message to read the value.
To read the third Digital In, send the message
\verbatim /digitalin/2/value \endverbatim
*/
static void digitalinOscHandler(OscChannel ch, char* address, int idx, OscData d[], int datalen)
{
UNUSED(d);
if (datalen == 0) {
OscData d = { .type = INT, .value.i = digitalinValue(idx) };
oscCreateMessage(ch, address, &d, 1);
}
}
// sort of a checksum to verify whether a previous save was legit
#define DIN_AUTOSEND_SAVED 0xDF
static uint8_t digitalinAutosendVals[DIGITALIN_COUNT];
static uint16_t digitalinAutosendChannels;
void digitalinAutoSendInit()
{
digitalinAutosendChannels = eepromRead(EEPROM_DIGITALIN_AUTOSEND);
if (((digitalinAutosendChannels >> 8) & 0xFF) != DIN_AUTOSEND_SAVED)
digitalinAutosendChannels = DIN_AUTOSEND_SAVED << 8;
}
static void digitalinOscAutosender(OscChannel ch)
{
uint8_t i;
OscData d = { .type = INT };
char addr[20];
for (i = 0; i < ANALOGIN_CHANNELS; i++) {
if (digitalinAutosendChannels & (1 << i)) {
d.value.i = digitalinValue(i);
if (digitalinAutosendVals[i] != d.value.i) {
digitalinAutosendVals[i] = d.value.i;
sniprintf(addr, sizeof(addr), "/digitalin/%d/value", i);
oscCreateMessage(ch, addr, &d, 1);
}
}
}
}
static void digitalinAutosendHandler(OscChannel ch, char* address, int idx, OscData d[], int datalen)
{
UNUSED(d);
UNUSED(address);
if (datalen == 0) {
OscData d;
d.type = INT;
d.value.i = (digitalinAutosendChannels & (1 << idx)) ? 1 : 0;
oscCreateMessage(ch, address, &d, 1);
}
else if (datalen == 1) {
if (d[0].value.i)
digitalinAutosendChannels |= (1 << idx);
else
digitalinAutosendChannels &= ~(1 << idx);
eepromWrite(EEPROM_DIGITALIN_AUTOSEND, digitalinAutosendChannels);
}
}
static const OscNode digitalinAutosendNode = { .name = "autosend", .handler = digitalinAutosendHandler };
static const OscNode digitalinValueNode = { .name = "value", .handler = digitalinOscHandler };
const OscNode digitalinOsc = {
.name = "digitalin",
.range = DIGITALIN_COUNT,
.autosender = digitalinOscAutosender,
.children = {
&digitalinValueNode,
&digitalinAutosendNode, 0
}
};
#endif // OSC
|
C
|
/* Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. */
/* For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. */
/* Note: */
/* You must do this in-place without making a copy of the array. */
/* Minimize the total number of operations. */
#include <stdio.h>
#include <string.h>
void moveZeroes(int *nums, int numsSize) {
int count = 0;
int i, j;
for(i=0; i<numsSize-count-1; i++){
if(nums[i]==0){
for(j=i; j<numsSize-count-1; j++){
nums[j] = nums[j+1];
}
count++;
i--;
}
}
memset(nums+numsSize-count, 0, count*sizeof(int));
}
int main(void){
// int a[] = {0,1,0,3,5};
//int a[]={4,2,4,0,0,3,0,5,1,0};
int a[] = {0,1,0,3,12};
moveZeroes(a, 5);
for(int i=0; i<5; i++){printf("%d\n", a[i]);}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** libmy-tek2
** File description:
** dsa / circular_buffer / circular_buffer.c
*/
#include "my/dsa/circular_buffer.h"
circular_buffer_t *cb_create(size_t size)
{
circular_buffer_t *this = calloc(1, sizeof(circular_buffer_t));
if (!this)
return (NULL);
this->size = (size == 0) ? CBUFFER_DEFAULT_SIZE : size;
this->buffer = calloc(this->size, sizeof(char));
if (!this->buffer) {
free(this);
return (NULL);
}
this->full = false;
this->empty = true;
return (this);
}
void cb_destroy(circular_buffer_t *this)
{
free(this->buffer);
free(this);
}
|
C
|
//exit restricted
#include<stdlib.h>
struct emp
{
int id,sal;
struct emp *ptr;
};
struct emp* start, *front, *rear;
void insert_at_end()
{
//problem
struct emp *k;
k=(struct emp *)malloc(sizeof(struct emp));
printf("Enter id and sal \n");
scanf("%d %d",&k->id,&k->sal);
k->ptr=NULL;
if(rear== NULL)
front=rear=k;
else
{
rear->ptr=k;
rear=k;
}
}
void insert_at_beg()
{
struct emp *k;
k= (struct emp *)malloc(sizeof(struct emp));
printf("Enter id and sal \n");
scanf("%d %d",&k->id,&k->sal);
k->ptr =NULL;
if(front ==NULL)
{
front =rear=k;
}
else
{
k->ptr=front;
front=k;
}
}
void del()
{
//del at begning
struct emp *k;
if(front==NULL)
printf("QUEUE EMPTY \n");
else
{
k=front;
front=front->ptr;
free(k);
}
if(front==NULL)
rear=NULL;
}
void disp()
{
struct emp *k;
if(front==NULL)
printf(" QUEUE EMPTY \n");
else
{
k=front;
printf("THE QUEUE IS \n");
while(k)
{
printf("%d \n",k->id);
printf("%d \n",k->sal);
k=k->ptr;
}
}
}
int main()
{
start=NULL;
front=NULL;
rear=NULL;
int ch=0;
while(ch<5)
{
printf("Choose from the following! \n1.Insert at beg \n2.Insert at end \n3.Delete \n4.Display \n");
scanf("%d",&ch);
switch(ch)
{
case 1:insert_at_beg();break;
case 2:insert_at_end();break;
case 3:del();break;
case 4:disp();break;
}
}
}
|
C
|
//买鸡问题:公鸡每只5元,母鸡每只3元,小鸡每元3只,现用100元买100只鸡,问各买多少只鸡
#include <stdio.h>
int main()
{
int i,j,k;
for(i=0;i*5<=100;i++)
{
for(j=0;j*3<=100;j++)
{
for(k=0;k/3<=100;k+=3)
if(i+j+k==100&&i*5+j*3+k/3==100)
printf("Cock--%d\tHen--%d\tChicken--%d\n",i,j,k);
}
}
return 0;
}
|
C
|
/*
* LineCounting.c
*
* Created on: 20 Jan 2021
* Author: Al
*/
#include <stdio.h>
/* count lines in input */
int main()
{
int c;
int nl;
nl = 0;
for ( c = getchar(); c != EOF; c = getchar() ) {
if (c == '\n') {
++nl;
}
}
(void)printf("%d\n", nl);
return 0;
}
|
C
|
//在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int i;
set<char> s;
if(str.empty())return -1;
for(i=0;i<str.size()-1;++i)
{
if(str.find(str[i],i+1)==string::npos&&s.find(str[i])==s.end())break;
s.insert(str[i]);
}
return i;
}
};
|
C
|
#pragma once
enum CardinalPointFlags
{
EAST = 1 << 0,
NORTH = 1 << 1,
SOUTH = 1 << 2,
WEST = 1 << 3
};
// Allows for a CardinalPointFlag to hold multiple flags of the same type
// Example:
// CardinalPointFlag northEast = CardinalPointFlag.NORTH | CardinalPointFlag.EAST;
inline CardinalPointFlags operator|(CardinalPointFlags& a, CardinalPointFlags& b)
{
return static_cast<CardinalPointFlags>(static_cast<int>(a) | static_cast<int>(b));
}
// Allows for a CardinalPointFlag to hold multiple flags of the same type
// Example:
// CardinalPointFlag northEast = CardinalPointFlag.NORTH;
// northEast |= CardinalPointFlag.EAST;
inline CardinalPointFlags& operator|=(CardinalPointFlags& originalFlag, CardinalPointFlags flagToAdd)
{
originalFlag = originalFlag | flagToAdd;
return originalFlag;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int stat[21][21] = {0, };
int flag[21] = {0, };
int team = 0;
int min = 10000;
void startlink(int n, int index, int combi)
{
int start = 0;
int link = 0;
if (team == index / 2)
{
for (int i = 1; i <= index; i++)
{
for (int j = 1; j <= index; j++)
{
if (flag[i] == 0 && flag[j] == 0)
start += stat[i][j];
else if (flag[i] == 1 && flag[j] == 1)
link += stat[i][j];
}
}
if (abs(start - link) < min)
min = abs(start - link);
return ;
}
for (int i = 1; i <= index; i++)
{
if (i > combi && flag[i] == 0)
{
flag[i] = 1;
team++;
startlink(n + 1, index, i);
if (min == 0)
break ;
flag[i] = 0;
team--;
}
}
}
int main(void)
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &stat[i][j]);
startlink(1, n, 0);
printf("%d\n", min);
}
|
C
|
#include <stdio.h>
/*
0 1 2 3 4 5 6 7 8 9
a s d d d f g h d \0
i
j
d
*/
int main(void)
{
char str[20] = {0};
char ch = 0;
int i, j;
printf("ַҪɾַ");
scanf("%s %c", str, &ch);
printf("ǰ");
puts(str);
for(i = 0; str[i]!='\0'; i++)
{
if(str[i] == ch)
{
for(j = i; str[j]!='\0'; j++)
{
str[j] = str[j+1];
}
i--;
}
}
puts("ɾ:");
puts(str);
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int t,n,k,i,a[1003],count=0,min,j,num;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
min=2000000000;
if(n==2)
{
printf("%d 1\n",abs(a[0]+a[1]-k));
}
else
{
for(i=0;i<n-1;i++)
{
for(j=(i+1);j<n;j++)
{
if(i!=j)
{
num=abs(a[i]+a[j]-k);
if(num==min)
{
count++;
}
else if(num<min)
{
count=1;
min=num;
}
}
}
}
printf("%d %d\n",min,count);
}
}
return 0;
}
|
C
|
//template for testing code
//download with: wget troll.cs.ua.edu/ACP-C/tester.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int steps;
double miles;
printf("Input the number of steps you have taken today: ");
scanf("%d", &steps);
miles = (double) steps * 26 / 12 / 5280;
printf("You have walked %lf miles today.", miles);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int buscaBin(int*, int, int, int);
int main() {
int N, M;
scanf("%d", &N);
int *v1 = (int*)malloc(sizeof(int*) * N);
for (int i = 0; i < N; i++) {
scanf("%d", &v1[i]);
}
scanf("%d", &M);
int *v2 = (int*)malloc(sizeof(int*) * M);
for (int i = 0; i < M; i++) {
scanf("%d", &v2[i]);
}
for (int i = 0; i < M; i++) {
int posicao;
posicao = buscaBin(v1, 0, N, v2[i]);
printf("%d\n", posicao);
}
free(v1);
free(v2);
return 0;
}
int buscaBin(int* v, int esq, int dir, int x) {
int meio;
if(esq <= dir) {
meio = (esq + dir) / 2;
if (v[meio] == x) {
return meio;
} else if (v[meio] > x) {
return buscaBin(v, esq, meio - 1, x);
} else {
return buscaBin(v, meio + 1, dir, x);
}
}
return -1;
}
|
C
|
#include<stdio.h>
void main()
{
int a,b,c,ans;
scanf("%d%d%d",&a,&b,&c);
ans=a*b%c;
printf("%d",ans);
}
|
C
|
/*
* metering.c
*
* Created on: 20.04.2011
* Author: G�nter Hildebrandt
*/
#include "metering.h"
#include <avr/io.h>
#include <util/delay.h>
#include "sys/clock.h"
#include "contiki.h"
#include "dev/leds.h"
#include <avr/eeprom.h>
#include "eeprom_variables.h"
#include "dev/leds.h"
#include "relay.h"
/** \brief This is a file internal variable that contains the 16 MSB of the
* metering pulse period.
*
* The metering pulse period (32-bit) is in METERING_TIMER_RESOLUTION. For the
* AVR microcontroller implementation this is solved by using a 16-bit
* timer (Timer1) with a clock frequency of 8 MHz and a prescaler of 1/1024.
* The metering_pulse_period is incremented when the 16-bit timer
* overflows, representing the 16 MSB. The timer value it self (TCNT1)
* is then the 16 LSB.
*
*/
//local variables
static clock_time_t metering_pulse_period = 0;
static clock_time_t clock_old;
static uint16_t metering_calibration_power;
static uint16_t metering_reference_value;
static uint8_t metering_calibration_state = 0;
static uint16_t metering_power;
static bool metering_calibration = false;
/*calculates the consumed energy on the basis of the counted pulses (num_pulses) in i given period (integration_time)
* P = 247.4W/Hz * f_CF */
uint16_t
calc_power(uint16_t pulse_period)
{
uint16_t P;
P = metering_reference_value / pulse_period;
return P;
}
void
metering_init(void)
{
/* Load reference values from EEPROM */
metering_reference_value = eeprom_read_word((void*) EE_METERING_REF );
metering_calibration_power = eeprom_read_word((void*)EE_METERING_CAL_LOAD);
SET_METERING_INT();
metering_start();
}
void
metering_start(void)
{
/*Reset variables used in file.*/
metering_pulse_period = 0;
metering_power = 0;
clock_old = clock_time();
ENABLE_METERING_INTERRUPT(); /* Enable external interrupt. */
}
void
metering_stop(void)
{
DISABLE_METERING_INTERRUPT(); /* Disable external capture interrupt. */
metering_reset();
}
void
metering_reset(void)
{
metering_power = 0;
}
uint16_t
metering_get_power(void)
{
return metering_power;
}
bool
metering_calibrate(void)
{
unsigned char cal_flag = eeprom_read_byte((void*)EE_METERING_CAL_FLAG);
if (cal_flag == 0xFF) {
metering_calibration = true;
leds_on(LEDS_ALL);
return true;
}
else
return false;
}
//interrupt service routine for the metering interrupt
ISR(METERING_VECT)
{
//calibration
if (metering_calibration == true) {
//do 10 measurements
if (metering_calibration_state < 10)
{
if (metering_calibration_state == 0)
{
//reset Timer
metering_pulse_period = clock_time();
}
metering_calibration_state++;
}
else {
//get mean pulse period over 10 cycles
if (clock_time() > metering_pulse_period)
metering_pulse_period = clock_time() - metering_pulse_period;
else //overflow of clock_time()
metering_pulse_period = 0xFFFF - metering_pulse_period + clock_time() + 1;
metering_pulse_period /= 10;
metering_reference_value = metering_pulse_period * metering_calibration_power;
//store calibration in EEPROM
eeprom_write_word((void*) EE_METERING_REF, metering_reference_value);
//lock calibration by setting flag in eeprom
eeprom_write_byte((void*) EE_METERING_CAL_FLAG, 0x00);
metering_calibration_state = 0;
metering_calibration = false;
relay_leds();
}
}
//measurement
else
{
//get pulse period
if (clock_time() > clock_old)
metering_pulse_period = clock_time() - clock_old;
else //overflow of clock_time()
metering_pulse_period = 0xFFFF - clock_old + clock_time() + 1;
clock_old = clock_time();
//calculate and set electrical power
metering_power = calc_power(metering_pulse_period);
}
}
|
C
|
/*************************************************************************
> File Name : processMemory.c
> Author : lirongwei
> Mail : a2413044193@gmail.com
> Created Time : 2020/07/08 09:47:54
************************************************************************/
#include<stdio.h>
/**
* 源程序 源代码
* 程序(可执行性文件)
*
* 进程 时间概念 可执行性文件被拉起,到结束的这一段过程,成为进程
*
* 进程空间:可执行性文件被拉起后,在内存中的分布情况
**/
int main(int argc, char** argv) {
printf("hello, world");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
void swap(int *, int *);
int i, j, a[10];
printf("Please enter 10 numbers:\n");
for(i=0; i<10; i++)
scanf("%d", &a[i]);
printf("The original order is:\n");
for(i=0; i<10; i++)
printf("%d\t", a[i]);
printf("\n");
for(i=0; i<+(9-1)/2; i++)
swap((a+i), (a+9-i));
printf("The current order is:\n");
for(i=0; i<10; i++)
printf("%d\t", a[i]);
printf("\n");
return 0;
}
void swap(int *p1, int *p2)
{
int tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
|
C
|
/*
2015-06-16
bluepp
May the force be with me!
Note: This is an extension of House Robber.
After robbing those houses on that street,
the thief has found himself a new place for his thievery
so that he will not get too much attention.
This time, all houses at this place are arranged in a circle.
That means the first house is the neighbor of the last one.
Meanwhile, the security system for these houses remain the same as
for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house,
determine the maximum amount of money you can rob tonight without alerting the police.
https://leetcode.com/problems/house-robber-ii/
*/
int rob(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
if (n == 2) return max(nums[0], nums[1]);
int dp[n];
memset(dp, 0, sizeof(dp));
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < n-1; i++)
{
dp[i] = max(nums[i]+dp[i-2], dp[i-1]);
}
int ret1 = dp[n-2];
memset(dp, 0, sizeof(dp));
dp[1] = nums[1];
dp[2] = max(nums[1], nums[2]);
for (int i = 3; i < n; i++)
{
dp[i] = max(nums[i]+dp[i-2], dp[i-1]);
}
int ret2 = dp[n-1];
int ret = max(ret1, ret2);
return ret;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* other.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: plurlene <plurlene@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/12 19:49:34 by plurlene #+# #+# */
/* Updated: 2021/03/15 17:14:59 by plurlene ### ########.fr */
/* */
/* ************************************************************************** */
#include "cube3d.h"
int scip_whitespaces(char *str, int s)
{
int i;
i = 0;
while (str[i] == ' ')
i++;
return (i + s);
}
int scip_digits(char *str, int flag, int bias)
{
int i;
i = 0;
if (flag)
{
while (ft_isdigit(str[i]))
i++;
}
else
{
while (!ft_isdigit(str[i]))
i++;
}
return (i + bias);
}
void clear_str_arr(char **arr)
{
int i;
i = 0;
while (arr[i])
{
free(arr[i]);
i++;
}
free(arr[i]);
free(arr);
}
int ft_isnum(char *str)
{
int i;
i = 0;
while (str[i])
{
if (ft_isdigit(str[i]))
i++;
else
return (0);
}
return (i);
}
int ft_char_num(char *str, int c)
{
int i;
int num;
i = -1;
num = 0;
while (str[++i])
if (str[i] == c)
num++;
return (num);
}
|
C
|
/*
* op.c
* Copyright (C) 2013 National University of Singapore
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"
#include "misc.h"
#include "op.h"
/*
* Operator specification.
*/
struct opspec_s
{
char *name; // Operator's name.
/* BINOP */
bool is_binop; // Is binop?
assoc_t binop_assoc; // Operator's assocativity.
unsigned binop_priority; // Operator's priority.
bool binop_ac; // Operator is AC?
bool binop_space; // Operator printed with a space?
/* UNOP */
bool is_unop; // Is unop?
unsigned unop_priority; // Operator's priority.
bool unop_space; // Operator printed with a space?
};
typedef struct opspec_s *opspec_t;
/*
* Op-table.
*/
static const struct opspec_s binoptable[] =
{
{"!=", true, XFX, 700, false, true, false, 0, false},
{"*", true, XFY, 400, true, false, false, 0, false},
{"+", true, YFX, 500, true, true, false, 0, false},
{"-", true, YFX, 500, false, true, false, 0, false},
{"->", true, XFY, 900, false, true, false, 0, false},
{"/", true, YFX, 400, false, false, false, 0, false},
{"/\\", true, XFY, 1000, true, true, false, 0, false},
{"<", true, XFX, 700, false, true, false, 0, false},
{"<->", true, XFY, 900, true, true, false, 0, false},
{"<=", true, XFX, 700, false, true, false, 0, false},
{"=", true, XFX, 700, false, true, false, 0, false},
{">", true, XFX, 700, false, true, false, 0, false},
{">=", true, XFX, 700, false, true, false, 0, false},
{"\\/", true, XFY, 1100, true, true, false, 0, false},
{"^", true, XFY, 200, false, false, false, 0, false},
{"xor", true, YFX, 500, true, true, false, 0, false},
};
/*
* Operator comparison.
*/
static int binop_compare(const void *a, const void *b)
{
const opspec_t a1 = (const opspec_t)a;
const opspec_t b1 = (const opspec_t)b;
return strcmp(a1->name, b1->name);
}
/*
* Register a new binary operator.
*/
extern opinfo_t binop_register(opinfo_t opinfo, char *binop, assoc_t assoc,
unsigned priority, bool ac, bool space)
{
opspec_t opspec;
if (!opinfo_search(opinfo, binop, &opspec))
{
opspec = (opspec_t)gc_malloc(sizeof(struct opspec_s));
memset(opspec, 0, sizeof(struct opspec_s));
if (!gc_isptr(binop))
{
size_t len = strlen(binop);
char *binop_1 = (char *)gc_malloc(len + 1);
strcpy(binop_1, binop);
binop = binop_1;
opspec->name = binop;
}
opinfo = opinfo_insert(opinfo, binop, opspec);
}
opspec->is_binop = true;
opspec->binop_assoc = assoc;
opspec->binop_priority = priority;
opspec->binop_ac = ac;
opspec->binop_space = space;
return opinfo;
}
/*
* Register a new unary operator.
*/
extern opinfo_t unop_register(opinfo_t opinfo, char *unop, unsigned priority,
bool space)
{
opspec_t opspec;
if (!opinfo_search(opinfo, unop, &opspec))
{
opspec = (opspec_t)gc_malloc(sizeof(struct opspec_s));
memset(opspec, 0, sizeof(struct opspec_s));
if (!gc_isptr(unop))
{
size_t len = strlen(unop);
char *unop_1 = (char *)gc_malloc(len + 1);
strcpy(unop_1, unop);
unop = unop_1;
opspec->name = unop;
}
opinfo = opinfo_insert(opinfo, unop, opspec);
}
opspec->is_unop = true;
opspec->unop_priority = priority;
opspec->unop_space = space;
return opinfo;
}
/*
* Operator lookup.
*/
extern bool binop_lookup(opinfo_t opinfo, const char *binop, assoc_t *assoc,
unsigned *priority, bool *ac, bool *space)
{
struct opspec_s key = {(char *)binop, false, 0, 0, false, false, 0, false};
opspec_t val = bsearch(&key, binoptable,
sizeof(binoptable)/sizeof(struct opspec_s), sizeof(struct opspec_s),
binop_compare);
if (val == NULL)
{
if (!opinfo_search(opinfo, (char *)binop, &val))
return false;
}
if (!val->is_binop)
return false;
if (assoc != NULL)
*assoc = val->binop_assoc;
if (priority != NULL)
*priority = val->binop_priority;
if (ac != NULL)
*ac = val->binop_ac;
if (space != NULL)
*space = val->binop_space;
return true;
}
/*
* Operator lookup.
*/
extern bool unop_lookup(opinfo_t opinfo, const char *unop, unsigned *priority,
bool *space)
{
opspec_t opspec;
if (strcmp(unop, "-") == 0)
{
if (priority != NULL)
*priority = 200;
if (space != NULL)
*space = false;
}
else if (strcmp(unop, "not") == 0)
{
if (priority != NULL)
*priority = 850; // XXX: 900 -> 850
if (space != NULL)
*space = true;
}
else if (opinfo_search(opinfo, (char *)unop, &opspec))
{
if (!opspec->is_unop)
return false;
if (priority != NULL)
*priority = opspec->unop_priority;
if (space != NULL)
*space = opspec->unop_space;
}
else
return false;
return true;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* header.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thvanher <thvanher@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/11 10:50:01 by thvanher #+# #+# */
/* Updated: 2020/09/14 10:13:31 by thvanher ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i])
i++;
return (i);
}
char *ft_strchr(const char *s, int c)
{
char *str;
unsigned char b;
int i;
int len;
str = (char *)s;
b = (unsigned char)c;
i = -1;
len = ft_strlen(str);
while (++i < len + 1)
{
if (str[i] == b)
return (str + i);
}
return (0);
}
char *ft_strdup(char *src)
{
char *dest;
int len;
int i;
len = ft_strlen(src);
i = 0;
if (!(dest = (char *)malloc((len + 1) * sizeof(char))))
return (0);
ft_memcpy(dest, src, len);
dest[len] = '\0';
return (dest);
}
void *ft_memcpy(void *dst, const void *src, size_t n)
{
const unsigned char *csrc;
unsigned char *cdst;
size_t i;
csrc = (const unsigned char *)src;
cdst = (unsigned char *)dst;
i = 0;
if (!dst && !src)
return (0);
while (i < n)
{
cdst[i] = csrc[i];
i++;
}
return (cdst);
}
char *ft_strjoin(char const *s1, char const *s2)
{
char *new;
size_t len1;
size_t len2;
new = 0;
if (!s1 && !s2)
return (new);
if (!s1 || !s2)
return (!s1 ? ft_strdup((char *)s2) : ft_strdup((char *)s1));
len1 = ft_strlen((char *)s1);
len2 = ft_strlen((char *)s2);
if (!(new = (char *)malloc((len1 + len2 + 1) * sizeof(char))))
return (0);
ft_memcpy(new, s1, len1);
ft_memcpy(new + len1, s2, len2);
new[len1 + len2] = '\0';
return (new);
}
|
C
|
/* ------------------------------------------------
* Vorspann
* ------------------------------------------------
*/
// CPP-Definition für Maximale Anzahl der Eingabeversuche
#define MAXVERSUCH 3
// Header-Dateien der C-Standardbibliothek einlesen
#include <stdio.h> // enthält Deklarationen für
// printf(), scanf()
#include <stdlib.h> // enthält CPP-Definitionen für
// EXIT_SUCCESS und EXIT_FAILURE
#include <stdbool.h> // enthält CPP-Definitionen für
// Typ bool und seine Werte true, false
/* ------------------------------------------------
* Vorwärts-Deklaration der Hilfsfunktionen
* ------------------------------------------------
*/
// Vorwärts-Deklaration durch Angabe der Funktionsköpfe
extern int ggT(int a, int b, int* addr_result);
extern int readInteger(char* prompt, int* n);
// Alternative: Vorwärts-Deklaration durch Angabe von Prototypen
extern int ggT(int, int, int*);
extern int readInteger(char*, int*);
/* ------------------------------------------------
* Hauptfunktion main()
* ------------------------------------------------
*/
int main (void) {
int i1;
int i2;
int theGGT;
// Lies zwei ganze Zahlen in i1 und i2 ein
printf("Bitte geben Sie zwei ganze Zahlen ein\n");
if(readInteger("Bitte die erste Zahl i1= ", &i1) != EXIT_SUCCESS ) {
printf("Fehler bei der Eingabe der Zahl i1\n");
// Code für fehlerhafte Ausführung des gesamten Programms melden
return EXIT_FAILURE;
}
if(readInteger("Bitte die zweite Zahl i2= ", &i2) != EXIT_SUCCESS ) {
printf("Fehler bei der Eingabe der Zahl i2\n");
// Code für fehlerhafte Ausführung des gesamten Programms melden
return EXIT_FAILURE;
}
// Berechne GGT
if(ggT(i1, i2, &theGGT) != EXIT_SUCCESS){
printf("\nFehler bei der Berechnung des GGT\n"
"Grund: i1 oder i2 war 0!\n");
return EXIT_FAILURE;
}
// Ausgabe des Resultats
printf ("\nDer größte gemeinsame Teiler von %d und %d ist: %d\n",
i1, i2, theGGT);
// Code für korrekte Ausführung des gesamten Programms melden.
// Per Konvention:
// 0 --> alles OK
// 1-255 --> Fehler-Codes
//
return EXIT_SUCCESS;
}
/* ------------------------------------------------
* Hilfsfunktionen
* ------------------------------------------------
*/
// Berechne den größten gemeinsamen Teiler (GGT)
// nach dem Euklid'schen Algorithmus.
//
// Achtung:
// Bei dieser Variante wird das Resultat per
// Referenzparameter addr_result zurückgegeben.
// Der Funktionswert ist ein FehlerCode.
//
int ggT(int a, int b, int* addr_result) {
// Vermeide Endlosschleife; prüfe auf 0
if (a == 0 || b == 0){
// Code für fehlerhafte Ausführung melden
return EXIT_FAILURE;
}
// Fix fuer negative Zahlen
if (a < 0) { a = -a; }
if (b < 0) { b = -b; }
while (a != b) {
if (a < b)
b = b - a;
else
a = a - b;
}
// Zuweisung des GGT an Referenzparameter addr_result
*addr_result = a;
// Code für korrekte Ausführung melden
return EXIT_SUCCESS;
}
// Lese eine ganze Zahl ein.
// Es sind MAXVERSUCH fehlerhafte Eingaben erlaubt.
//
int readInteger(char* prompt, int* n) {
bool erfolg = false;
int versuch = 1; // Anzahl der Versuche
while (!erfolg && versuch <= MAXVERSUCH ) {
printf("%s",prompt);
fflush(stdout);
if(scanf("%d", n) != 1) {
versuch++;
printf("Sie müssen hier eine ganze Zahl eingeben!!!\n");
while(getchar() != '\n');
continue;
} else {
erfolg = true;
while(getchar() != '\n');
}
}
// Stelle fest, wieso wir die Schleife verlassen haben
// und gibt entsprechenden Fehler-Code an den Aufrufer
// der Funktion (hier main()) zurück.
if (!erfolg) {
return EXIT_FAILURE;
} else {
return EXIT_SUCCESS;
}
}
|
C
|
#include<stdio.h>
main()
{
int i,j,n[100];
printf("Enter 5 nos\n");
for(i=0;i<5;i++)
{
scanf("%d",&n[i]);
/*if(n[i]==5)
{*/
break;
/*}
*/ }
for(j=i+1;j<5;j++)
{
n[j]=0;
}
printf("The nos are\n");
for(i=0;i<5;i++)
{
printf("%d\n",n[i]);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: clbouche <clbouche@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/09 15:02:02 by clbouche #+# #+# */
/* Updated: 2021/08/23 10:59:29 by clbouche ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef PHILO_H
# define PHILO_H
/*
** DEFINE
*/
# define DEAD 1
# define ALIVE 0
# define FULL_BELLY 2
# define ERR_NUM "The arguments must be numerical and positive numbers"
# define ERR_NB_ARGS "The execution of the program requires 5 or 6 parameters"
# define ERR_NB_PHILO "No philosopher wants to eat"
# define ERR_INIT "Something went wrong with initialization"
# define ERR_MALLOC "Malloc returned NULL value"
# define ERR_THREAD "The creation of thread doesn't work"
# define ERR_ARG "Invalid arguments"
/*
** LIBRAIRIES
*/
# include <unistd.h>
# include <sys/time.h>
# include <pthread.h>
# include <string.h>
# include <stdio.h>
# include <stdlib.h>
/*
** STRUCTURES
*/
typedef struct s_thread_data
{
int nb_of_philo;
int time_to_die;
int time_to_eat;
int time_to_sleep;
int nb_meals_per_philo;
int dead_signal;
int full_belly;
long long start_time;
pthread_mutex_t message;
pthread_mutex_t end;
pthread_mutex_t finish;
pthread_mutex_t mutex_eat;
} t_thread_data;
struct s_params;
typedef struct s_philo
{
pthread_t thread;
pthread_t thread_death;
pthread_mutex_t *right_fork;
pthread_mutex_t left_fork;
t_thread_data *data;
int id;
unsigned int nb_meal;
long long timer_death;
} t_philo;
typedef struct s_params
{
t_philo *philo;
t_thread_data data;
} t_params;
/*
** FUNCTIONS
*/
void ft_msleep(long long time_to_go);
void parsing(int argc, char **argv, t_params *params);
int create_threads(t_params *params);
int ft_atoi(const char *str);
void ft_error(char *error);
void philo_message(t_philo *philo, char *msg);
long long get_time(void);
int check_death(t_philo *philo, int i);
void *is_dead(void *data);
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>
void error(const char* msg)
{
perror(msg);
exit(1);
}
int main()
{
int c_sock;
//call socket() function with necessary parameters for UDP
c_sock = socket(AF_INET, SOCK_DGRAM, 0);
if (c_sock < 0)
error("Error opening socket");
struct sockaddr_in client;
socklen_t client_len;
memset(&client, 0, sizeof(client));
client_len = sizeof(client);
client.sin_family = AF_INET;
client.sin_port = htons(9009);
client.sin_addr.s_addr = INADDR_ANY;
printf("Yo! This is Client.\n\n");
char fname[100], extension[100], ext[10], buffer[20000], buf[1];
printf("Enter File name without extension: ");
scanf("%s", fname);
printf("Enter extension: ");
scanf("%s", ext);
//concat the extension to the filname with a dot in between
strcpy(extension, fname);
strcat(extension, ".");
strcat(extension, ext);
printf("\nFile Name: %s.\n\n", extension);
//open the file in read mode
FILE *fp;
fp = fopen(extension, "rb");
printf("Opened %s.\n", extension);
char eof[1] = "0";
//send the name of the file and its extension to the server
sendto(c_sock, fname, sizeof(fname), 0, (struct sockaddr*)&client, sizeof(client));
sendto(c_sock, ext, sizeof(ext), 0, (struct sockaddr*)&client, sizeof(client));
while(!feof(fp))
{
//scan the file and send its contents to the server
fscanf(fp, "%c", &buf[0]);
sendto(c_sock, eof, sizeof(eof), 0, (struct sockaddr*)&client, sizeof(client));
sendto(c_sock, buf, sizeof(buf), 0, (struct sockaddr*)&client, sizeof(client));
}
printf("\n\nFile Ended \n\n");
//send a signal to the server indicating that the file has been sent
eof[0] = '1';
sendto(c_sock, eof, sizeof(eof), 0, (struct sockaddr*)&client, sizeof(client));
printf("File sent.\n");
//close client
close(c_sock);
return 0;
}
|
C
|
#include "heap.h"
#include <stdio.h>
int main()
{
struct Heap h;
struct Heap * p = &h;
int v[] = {7, 16, 49, 82, 5, 31, 6, 2, 44};
int i;
heap_init(p);
for( i = 0; i < sizeof(v) / sizeof(v[0]); i++ )
{
heap_push(p, v[i]);
}
while( h.size )
{
int value;
if( heap_pop(p, &value) )
{
printf("[%2d] ", value);
heap_print(p);
}
else
{
printf("*** error ***\n");
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
#include <math.h>
int** matrixInit(int rows, int cols, int value){
//creating the array
int** myMatrix = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++){
myMatrix[i] = (int*)malloc(cols * sizeof(int*));
for (int j = 0; j < cols; j++){
myMatrix[i][j] = value; //setting the value
}
}
return myMatrix;
}
int matrixMin(int** arr, int rows, int cols){
int min = arr[0][0];
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
if (arr[i][j] < min){
min = arr[i][j];
}
}
}
return min;
}
int matrixMax(int** arr, int rows, int cols){
int max = arr[0][0];
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
if (arr[i][j] > max){
max = arr[i][j];
}
}
}
return max;
}
int digitCalc(int num){
int digits;
if (abs(num) == 1){
digits = 1;
}
else{
digits = (ceil(log10(abs (num))));
}
if (num < 0){
digits += 1;
}
return digits;
}
void matrixPrint(int **arr, int rows, int cols){
int max = matrixMax(arr, rows, cols);
int min = matrixMin(arr, rows, cols);
int digits_of_max = digitCalc(max);
int digits_of_min = digitCalc(min);
int max_digits;
if (digits_of_max >= digits_of_min){
max_digits = digits_of_max;
}
else{
max_digits = digits_of_min;
}
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
int num = arr[i][j];
int digits_of_num = digitCalc(num);
int spaces = max_digits - digits_of_num + 1;
printf("%d", num);
for (int s = 0; s < spaces; s++){
printf(" ");
}
}
printf("\n");
}
}
void matrixDestroy(int **arr, int length1){
for (int i = 0; i < length1; i++){
free(arr[i]);
}
free (arr);
return;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/errno.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include<time.h>
static int create_sem( int klucz,int liczba_elementow,int wartosc_semafora);
static void semafor_p(int semid,int numer_semafora);
static void semafor_v(int semid, int numer_semafora);
int w = 0;
int sp = 1;
int main(int argc , char * argv[])
{
srand(time(NULL));
//generowanie klucza, taki sam jak w glownym i czytelniku
key_t klucz=ftok(".",'F');
//zbior 2 semaforow o wartosci 1
int semID=create_sem(klucz,2,1);
//pseudokod
while(1)
{
//czekaj az bedzie mozna pisac
semafor_p(semID,sp);
//sekcja krytyczna
FILE *input;
if((input=fopen("czytelnia", "w")))
{
char l = 0;
l = ('A' + (rand() % 26));
printf("[Pisarz %d]\tZapisuje do czytelni znak %c\n",getpid(),l);
fputc(l, input);
fclose(input);
}
sleep(1);
//koniec sekcji krytycznej
semafor_v(semID,sp);//zakoncz pisac
}
}
//tworzenie i ustawienie semaforow o ile jeszcze nie sa ustawione
static int create_sem( int klucz,int liczba_elementow,int wartosc_semafora)
{
int semid=semget(klucz,liczba_elementow,IPC_CREAT|IPC_EXCL|0666);
if (errno==EEXIST)
{
semid=semget(klucz,liczba_elementow,IPC_CREAT|0666);
return semid;
}
else
{
for(int i=0;i<liczba_elementow;i++)
{
int ustaw_sem;
ustaw_sem=semctl(semid,i,SETVAL,wartosc_semafora);
if (ustaw_sem==-1)
{
perror("[reader] semctl SETVAL erorr");
exit(EXIT_FAILURE);
}
}
return semid;
}
perror("[reader]semget IPC_CREAT|IPC_EXECL error");
exit(EXIT_FAILURE);
}
static void semafor_p(int semid,int numer_semafora)
{
int zmien_sem;
struct sembuf bufor_sem;
bufor_sem.sem_num=numer_semafora;
bufor_sem.sem_op=-1;
bufor_sem.sem_flg=0;
zmien_sem=semop(semid,&bufor_sem,1);
if (zmien_sem==-1)
{
if(errno==EINTR)
{
semafor_p(semid,numer_semafora);
}
else if(errno==EIDRM)
{
printf("Zestaw semaforow zostal juz usuniety\n");
}
else
{
printf("Nie moglem zamknac semafora.\n");
exit(EXIT_FAILURE);
}
}
}
static void semafor_v(int semid, int numer_semafora)
{
int zmien_sem;
struct sembuf bufor_sem;
bufor_sem.sem_num=numer_semafora;
bufor_sem.sem_op=1;
bufor_sem.sem_flg=0;
zmien_sem=semop(semid,&bufor_sem,1);
if (zmien_sem==-1)
{
if(errno==EIDRM)
{
printf("Zestaw semaforow zostal juz usuniety\n");
}
else
{
printf("Nie moglem otworzyc semafora.\n");
exit(EXIT_FAILURE);
}
}
}
|
C
|
/*Basic program to print address of a variable*/
/*C in Depth P9.1 example*/
#include<stdio.h>
int main()
{
int age = 30;
float salary = 1500.50;
printf("Address of age = %p\n", &age);
printf("Address of salary = %p\n", &salary);
return 0;
}
|
C
|
#include <inttypes.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include "avrlaunch/avrlaunch.h"
#include "avrlaunch/log.h"
#include "avrlaunch/shell.h"
#include "avrlaunch/pgmspace/pgm_strings.h"
#include "avrlaunch/hal/atmega328p/hal_adc.h"
#define NO_DUMMY -1
static int8_t dummy_channel = NO_DUMMY;
static void error_not_adc_channel(const uint8_t channel);
static shell_result adc_shell_handler(shell_command* command);
void adc_init(void) {
ADMUX &= 0x00;
ADCSRA &= 0x00;
// Set ADC prescale factor to 128
set_bit(&ADCSRA, ADPS2);
set_bit(&ADCSRA, ADPS1);
set_bit(&ADCSRA, ADPS0);
// Disable power reduction
clear_bit(&PRR, PRADC);
// Enable the ADC
set_bit(&ADCSRA, ADEN);
// Set reference voltage to AVcc
set_bit(&ADMUX, REFS0);
// Set to full 10 bit operation
clear_bit(&ADMUX, ADLAR);
PGM_STR(ADC_SHELL_ADC, shell_adc)
shell_register_handler(shell_adc, adc_shell_handler);
}
void adc_enable_dummy(uint8_t channel) {
if (channel > 5) {
error_not_adc_channel(channel);
return;
}
dummy_channel = channel;
}
uint16_t adc_read(uint8_t channel) {
if (channel > 5) {
error_not_adc_channel(channel);
return 0;
}
if (dummy_channel != NO_DUMMY) {
// Take a reading from the dummy channel to try and clear the S&H circuitry
ADMUX = (ADMUX & 0xf0) | dummy_channel;
set_bit(&ADCSRA, ADSC);
while (bit_is_set(ADCSRA, ADSC));
}
// Set ADC input channel
ADMUX = (ADMUX & 0xf0) | channel;
// Start the conversion
set_bit(&ADCSRA, ADSC);
while (bit_is_set(ADCSRA, ADSC));
// Read the low byte first!
uint8_t low = ADCL;
uint8_t high = ADCH;
return (high << 8) | low;
}
static void error_not_adc_channel(const uint8_t channel) {
set_system_error();
if (LOG_LEVEL >= LOG_LEVEL_ERROR) {
PGM_STR(ADC_NO_CHANNEL, failed_msg)
LOG_ERROR(failed_msg, channel);
}
}
static shell_result adc_shell_handler(shell_command* command) {
if (!string_eq(command->command, "adc")) return SHELL_RESULT_FAIL;
if (command->args_count == 0) return SHELL_RESULT_FAIL;
if (string_eq(command->args[0], "read")) {
shell_printf("Channel\tReading\r\n");
if (command->args_count == 2) {
uint8_t channel = atoi(command->args[1]);
shell_printf("%u\t%u\r\n", channel, adc_read(channel));
} else {
for (int i = 0; i < 6; i++) {
shell_printf("%u\t%u\r\n", i, adc_read(i));
}
}
return SHELL_RESULT_SUCCESS;
}
return SHELL_RESULT_FAIL;
}
|
C
|
#include <tcpip/h/network.h>
/*------------------------------------------------------------------------
* tfinsert - add a new TCP segment fragment to a TCB sequence queue
*
* 将数据插入到ptcb->tcb_rsegq中去
*------------------------------------------------------------------------
*/
int
tfinsert(struct tcb *ptcb, tcpseq seq, unsigned int datalen) {
struct tcpfrag *tf;
if (datalen == 0) {
return OK;
}
tf= (struct tcpfrag*)kmalloc(sizeof(struct tcpfrag));
tf->tf_seq = seq;
tf->tf_len = datalen;
if(ptcb->tcb_rsegq == NULL) {
ptcb->tcb_rsegq = create_queue(NTCPFRAG);
}
if(enq(ptcb->tcb_rsegq, tf) < 0) {
freebuf(tf);
}
return OK;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct queue {
int capacity;
int size;
int front;
int rear;
pthread_t *elements;
} queue;
queue *create_queue(int maxElements) {
queue *q = (queue *)malloc(sizeof(queue));
q -> elements = (int *)malloc(sizeof(pthread_t) * maxElements);
q -> size = 0;
q -> capacity = 0;
q -> front = 0;
q -> rear = -1;
return q;
}
void dequeue(queue *q) {
if (q -> size != 0) {
q -> size--;
q -> front++;
if (q -> front == q -> capacity)
q -> front = 0;
}
}
pthread_t front(queue *q) {
if (q -> size != 0)
return q -> elements[q -> front];
}
void enqueue(queue *q, pthread_t element) {
if (q -> size == q -> capacity)
q -> capacity++;
else {
q -> size++;
q -> rear = q -> rear + 1;
if (q -> rear == q -> capacity)
q -> rear = 0;
q -> elements[q -> rear] = element;
}
}
|
C
|
/*
* Project1.c
*
* Created: 1/18/2019 7:50:43 PM
* Author : Kian Farsany
*/
#include <avr/io.h>
#include "avr.c"
void wait_half() {
volatile int i,n = 17000;
for (i = 0; i < n; ++i) {
//blah
}
}
int main(void)
{
DDRB = 1;
while (1)
{
if (GET_BIT(PINB, 1) == 0) {
PORTB = 1;
//wait_half();
wait_avr(500);
PORTB = 0;
//wait_half();
wait_avr(500);
}
else {
PORTB = 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 */
typedef scalar_t__ uint8_t ;
typedef int uint32_t ;
/* Variables and functions */
__attribute__((used)) static uint32_t
witness_hash_djb2(const uint8_t *key, uint32_t size)
{
unsigned int hash = 5381;
int i;
/* hash = hash * 33 + key[i] */
if (size)
for (i = 0; i < size; i++)
hash = ((hash << 5) + hash) + (unsigned int)key[i];
else
for (i = 0; key[i] != 0; i++)
hash = ((hash << 5) + hash) + (unsigned int)key[i];
return (hash);
}
|
C
|
#include "sort.h"
/**
*bubble_sort - Sorts an array of integers in ascending order.
*@array: Array of integers.
*@size: Size of the array.
*Return: Nothing.
*/
void bubble_sort(int *array, size_t size)
{
size_t a, b;
if (size < 2)
return;
for (a = 0; a < size - 1; a++)
for (b = 0; b < size - 1; b++)
if (array[b] > array[b + 1])
{
array[b] += array[b + 1];
array[b + 1] = array[b] - array[b + 1];
array[b] -= array[b + 1];
print_array(array, size);
}
}
|
C
|
//first device
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include "gpio_ioctl.h"
#include <stdint.h>
#include <poll.h>
#define SIZE_OF_BUF 5 /*Ring buffer size*/
#define GPIO_TRIGGER_1 38 /*Trigger pin device 0*/
#define GPIO_ECHO_1 10 /*Echo pin device 0*/
#define GPIO_TRIGGER_2 40 /*Trigger pin device 1*/
#define GPIO_ECHO_2 0 /*Echo pin device 1*/
#define GPIO_MUX_1 74 /*Mux pin for echo pin of device 0*/
#define GPIO_MUX_2 66 /*Mux pin for echo pin of device 1*/
int set_retval;
typedef struct {
uint64_t TSC;
}data, *Pdata;
void IOSetup_init(void)
{
int PinExport,pin_test;
PinExport = open("/sys/class/gpio/export", O_WRONLY);
if (PinExport < 0)
printf("\n gpio export open failed");
if(0< write(PinExport,"74",2)) /*Pin number "74" can be changed to other pins*/
printf("error PinExport 74");
if (PinExport < 0)
printf("\n gpio export open failed");
if(0< write(PinExport,"66",2)) /*Pin number "66" can be changed to other pins*/
printf("error PinExport 66");
close(PinExport);
//Set the value for the pins
pin_test = open("/sys/class/gpio/gpio74/value", O_WRONLY); /*Pin number "74" can be changed to other pins*/
if (pin_test < 0)
printf("\n gpio%d value open failed",GPIO_MUX_1);
if(0< write(pin_test ,"0",1))
printf("error gpio%d value",GPIO_MUX_1 );
pin_test = open("/sys/class/gpio/gpio66/value", O_WRONLY); /*Pin number "66" can be changed to other pins*/
if (pin_test < 0)
printf("\n gpio%d value open failed", GPIO_MUX_2);
if(0< write(pin_test,"0",1))
printf("error gpio%d value", GPIO_MUX_2);
close(pin_test);
}
void IOSetup_exit(void)
{ int PinUnexport;
PinUnexport = open("/sys/class/gpio/unexport", O_WRONLY);
if (PinUnexport < 0)
printf("\n gpio unexport open failed");
if(write(PinUnexport,"74",2)< 0) /*Pin number "74" can be changed to other pins*/
printf("error PinUnexport 74");
if (PinUnexport < 0)
printf("\n gpio unexport open failed");
if( write(PinUnexport,"66",2)< 0) /*Pin number "66" can be changed to other pins*/
printf("error PinUnexport 66");
close(PinUnexport);
}
/* Setting the trigger and echo pins
@fd: file descriptor
@trigger: gpio pin to be set as trigger pin
@echo: gpio pin to be set as echo pin
*/
int hcsr_set_pins(int fd, int trigger, int echo) /*call to give input key to the read function*/
{
SIOCTL_SETPIN Sioctl_setpin;
Sioctl_setpin.in.in_trigger = trigger;
Sioctl_setpin.in.in_echo = echo;
if((set_retval = ioctl(fd,HCSR_IOCTL_SETPIN,(unsigned long)&Sioctl_setpin))!=0){
printf("ioctl error %d\n", set_retval);}
if(set_retval)
printf("hcsr_dev_error: unable to perform hcsr_set_pins \n");
return 0;
}
/* Setting the mode(one shot or periodic)
@fd: file descriptor
@mode: one shot=0 and periodic=1
@freq: frequency should be <16hz
*/
int hcsr_set_mode(int fd, int mode, int freq) /*call to give input key to the read function*/
{
SIOCTL_SETMODE Sioctl_setmode;
Sioctl_setmode.in.in_mode = mode;
Sioctl_setmode.in.in_time = freq;
if((set_retval = ioctl(fd,HCSR_IOCTL_SETMODE,(unsigned long)&Sioctl_setmode))!=0){
printf("ioctl error %d\n", set_retval);}
if(set_retval)
printf("hcsr_dev_error: unable to perform hcsr_set_mode \n");
return 0;
}
int main(int argc, char **argv)
{
int fd1, fd2, res;
int new_buff1, new_buff2 ,i;
int buf;
IOSetup_init();
/*Opening device 1*/
fd1 = open("/dev/HCSR_1", O_RDWR);
if (fd1 < 0 ){
printf("Can not open device hcsr1 file\n");
return 0;
}
else {
printf("hcsr1 device is opened\n");
}
/*Opening device 2*/
fd2 = open("/dev/HCSR_2", O_RDWR);
if (fd2 < 0 ){
printf("Can not open device hcsr2 file\n");
return 0;
}
else {
printf("hcsr2 device is opened\n");
}
/*Setting trigger and echo pins for device 1*/
res = hcsr_set_pins(fd1,GPIO_TRIGGER_1,GPIO_ECHO_1) ;
if(res<0)
printf("hcsr_set_pins for hcsr1 failed\n");
/*Setting trigger and echo pins for device 2*/
res = hcsr_set_pins(fd2,GPIO_TRIGGER_2,GPIO_ECHO_2) ;
if(res<0)
printf("hcsr_set_pins for hcsr2 failed\n");
/*Setting one-shot mode for device 1*/
res = hcsr_set_mode(fd1,0,12) ; //one shot mode
if(res<0)
printf("hcsr_set_mode for hcsr1 failed\n");
/*Setting one-shot mode for device 2*/
res = hcsr_set_mode(fd2,0,11) ; //one shot mode
if(res<0)
printf("hcsr_set_mode for hcsr2 failed\n");
/*Block the read function in device 1 when the buffer is empty*/
if ((res =read( fd1, &buf , sizeof(int)))==-1)
printf("no data is read\n");
else
printf("distance read for hcsr1 = %d\n ", buf);
/*Performing one-shot without clearing the buffer */
new_buff1 = 0;
res = write(fd1, &new_buff1, sizeof(int));
if(res<0)
printf("write operation for hcsr1 failed");
new_buff2 = 0;
res = write(fd2, &new_buff2, sizeof(int));
if(res<0)
printf("write operation for hcsr2 failed");
/*Setting sampling mode for the devices*/
res = hcsr_set_mode(fd1,1,10) ;
if(res<0)
printf("hcsr_set_mode for hcsr1 failed\n");
res = hcsr_set_mode(fd2,1,5) ;
if(res<0)
printf("hcsr_set_mode for hcsr2 failed\n");
/*Thread to start the sampling and write process*/
new_buff1 = 1;
res = write(fd1, &new_buff1, sizeof(int));
if(res<0)
printf("write operation for hcsr1 failed");
new_buff2 = 1;
res = write(fd2, &new_buff2, sizeof(int));//sampling
if(res<0)
printf("write operation for hcsr2 failed");
sleep(3);
/*Stopping of thread to write in device 2*/
new_buff2 = 0;
res = write(fd2, &new_buff2, sizeof(int));
if(res<0)
printf("write operation for hcsr2 failed");
/*Reading measurment from ring buffer of device 1*/
if ((res =read( fd1, &buf , sizeof(int)))==-1)
printf("no data is read form hcsr1 \n");
else
printf("distance read for hcsr1 = %d\n ", buf);
sleep(2);
/*Stopping sampling mode of device 1*/
new_buff1 = 0;
res = write(fd1, &new_buff1, sizeof(int));
if(res<0)
printf("write operation failed for hcsr1 ");
/*Reading measurment from ring buffer of device 2*/
if ((res =read( fd2, &buf , sizeof(int)))==-1)
printf("no data is read form hcsr2 \n");
else
printf("distance read for hcsr2 = %d\n ", buf);
/*Setting one shot mode*/
res = hcsr_set_mode(fd1,0,6) ;
if(res<0)
printf("hcsr_set_mode for hcsr1 failed\n");
/*One shot mode with on-going measurement*/
new_buff1 = 1 ;
res = write(fd1, &new_buff1, sizeof(int));
if(res<0)
printf("write operation failed for hcsr1 ");
/*Burst shot mode*/
res = hcsr_set_mode(fd1,1,5) ;
if(res<0)
printf("hcsr_set_mode failed for hcsr1 \n");
/*Thread to start the sampling and write process*/
new_buff1 = 1;
res = write(fd1, &new_buff1, sizeof(int));
if(res<0)
printf("write operation for hcsr1 failed");
sleep(5);
/*Stopping sampling mode of device 1*/
new_buff1 = 0;
res = write(fd1, &new_buff1, sizeof(int));
if(res<0)
printf("write operation failed for hcsr1 ");
/*Reading the values of buffers of device 1 and 2*/
for(i=0 ; i< 5; i++)
{
if ((res =read( fd1, &buf , sizeof(int)))==-1)
printf("no data is read form hcsr1 \n");
else
printf("distance read form hcsr1 = %d\n ", buf);
}
for(i=0 ; i< 5; i++)
{
if ((res =read( fd2, &buf , sizeof(int)))==-1)
printf("no data is read form hcsr2 \n");
else
printf("distance read form hcsr2 = %d\n ", buf);
}
sleep(4);
IOSetup_exit();
close(fd1);
close(fd2);
return 0;
}
|
C
|
//------------------------------------------
// D.c
//
//------------------------------------------
#include <stdio.h>
#include <stdlib.h>
// Macro for Debugging
#define DEBUG
#define TMP
int main (void){
int N;
int i,j;
int t[110],v[110]; /*tの値とvの値を格納*/
double gragh[500];
int sumt;
double tmp;
printf("Program D.c Start! \n\n");
printf("INPUT N: ==> ");
scanf("%d",&N); /*Nの入力*/
printf("N = %d\n\n", N);
t[0] = 0;
/* tの入力*/
for(i = 0; i < N; i++){
printf("INPUT t[%d]: ==> ", i+1);
scanf("%d",&t[i+1]);
printf("t[%d] == %d\n\n", i+1, t[i+1]);
}
/* tの配列を累積時間にする*/
for (i = 2; i < N+1; i++){
t[i] += t[i-1];
}
/*累積最終時間が終了時間*/
sumt = t[N];
/*vの入力*/
for(i = 0 ; i < N; i++){
printf("INPUT v[%d]: ==> ", i);
scanf("%d",&v[i]);
printf("v[%d] == %d\n\n", i, v[i]);
}
#ifdef DEBUG
/* 配列tと配列vの要素をチェックする */
printf("\n-----t------\n");
for (j = 0; j < N + 1; j++){
printf("t[%d] = %d\n", j, t[j]);
}
/* ここでsegmentation fault */
printf("\n-----v------\n");
for (j = 0; j < N; j++){
printf("v[%d] = %d\n", j, v[j]);
}
#endif
{ int p = 0;
printf("get p ==>");
scanf("%d", &p);
printf("\n");
}
printf("i: %d, sumt: %d, N: %d\n", i, sumt, N);
/* graghの最初の状態をつくる */
for (i = 1;i < sumt * 2 + 1; i++){
if (i < sumt+1){
gragh[i] = (double)i/2;
}else{
gragh[i] = gragh[i-1] - 0.5;
}
}
#ifdef DEBUG /*デバッグここから*/
for (i = 0;i < sumt * 2 + 1; i++){
printf("graph[%d] = %lf\n", i, gragh[i]);
}
printf("\n-----t------\n");
for (j = 0; j < N + 1; j++){
printf("t[%d] = %d\n", j, t[j]);
}
printf("\n-----v------\n");
for (j = 0; j < N; j++){
printf("v[%d] = %d\n", j, v[j]);
}
printf("\n");
#endif /*デバッグここまで*/
/* グラフを作成する */
printf("-----a---\n");
for(j = 0; j < N; j++){
for(i = 1; i< sumt * 2 + 1; i++){
printf("i = %d\n",i);
if (t[j]*2 > i){
tmp = ((double) t[j]+(double) v[j] - (double)i / 2);
if (gragh[i] > tmp){
gragh[i] = tmp;
}
} else{
if ((t[j] * 2 <= i) && (i <= (t[j + 1] * 2))){
if (gragh[i] > (double)v[j]){
gragh[i] = (double)v[j];
}
} else {
tmp = ((double)v[j] + 0.5*(double)(i - t[j+1] * 2));
if (gragh[i] > tmp){
gragh[i] = tmp;
}
}
}
}
}
#ifdef DEBUG /*デバッグここから*/
for (i = 0; i < sumt *2 + 1; i++){
printf("graph[%d] = %lf\n", i, gragh[i]);
}
#endif /*デバッグここまで*/
/*面積の計算*/
double val = 0.0;
for(i = 0; i < sumt * 2; i++){
if (gragh[i] != gragh[i+1]){
val += ((gragh[i] + gragh[i+1]) * 0.25);
} else{
val += ((gragh[i]) * 0.5);
}
}
/* 答えの出力 */
printf("val = %lf\n", val);
printf("program terminated.\n\n");
return 0;
}
//-----------------------------------------------------
// copyright (C) 2017 Koshizuka, All Rights Reserved.
//-----------------------------------------------------
|
C
|
#include "holberton.h"
/**
* get_bit - that returns the value of a bit at a given index.
* @n: number
* @index: index
* Return: the converted number
*/
int get_bit(unsigned long int n, unsigned int index)
{
if (index < 64)
{
n >>= index;
return (n & 1);
}
return (-1);
}
|
C
|
/*
* f_ops.h
*
* Created on: 2017年5月22日
* Author: YJ-User17
*/
#ifndef __F_OPS_H__
#define __F_OPS_H__
/* ips */
#include "fs.h"
/* fs write */
static int fs_write(struct file * filp,const char * buffer , unsigned int buflen)
{
/* judge */
if( filp != 0 && filp->f_inode->ops.write != 0 )
{
return filp->f_inode->ops.write(filp,buffer,buflen);
}
else
{
return FS_ERR;
}
}
/* fs read */
static int fs_read(struct file * filp,char *buffer , unsigned int buflen)
{
/* judge */
if( filp != 0 && filp->f_inode->ops.read != 0 )
{
return filp->f_inode->ops.read(filp,buffer,buflen);
}
else
{
return 0;
}
}
/* fs sync */
static int fs_sync(struct file * filp)
{
/* judge */
if( filp != 0 && filp->f_inode->ops.sync != 0 )
{
return filp->f_inode->ops.sync(filp);
}
else
{
return FS_ERR;
}
}
/* fs close */
static int fs_close(struct file * filp)
{
/* judge */
if( filp != 0 && filp->f_inode->ops.close != 0 )
{
return filp->f_inode->ops.close(filp);
}
else
{
return FS_ERR;
}
}
/* fs opendir */
static int fs_opendir( struct file * filp , const char *path )
{
/* judge */
if( filp != 0 && filp->f_inode->ops.opendir != 0 )
{
return filp->f_inode->ops.opendir(path);
}
else
{
return FS_ERR;
}
}
/* fs seek */
static int fs_seek(struct file *filp, unsigned int offset, unsigned int whence)
{
/* judge */
if( filp != 0 && filp->f_inode->ops.lseek != 0 )
{
return filp->f_inode->ops.lseek(filp,offset,whence);
}
else
{
return FS_ERR;
}
}
/*fs ioctrl */
static int fs_ioctl(struct file *filp, int cmd, unsigned long arg,void *pri_data)
{
/* judge */
if( filp != 0 && filp->f_inode->ops.ioctl != 0 )
{
return filp->f_inode->ops.ioctl(filp,cmd,arg,pri_data);
}
else
{
return FS_ERR;
}
}
/* fs readdir */
static int fs_readdir( FAR struct file *filp, const char *path,readdir_entrance_def * buffer )
{
/* judge */
if( filp != 0 && filp->f_inode->ops.readir != 0 )
{
return filp->f_inode->ops.readir(filp,path,buffer);
}
else
{
return FS_ERR;
}
}
#endif /* __F_OPS_H__ */
|
C
|
#define MaxVertexNum 100
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
typedef struct ENode* PtrToENode;
struct ENode
{
Vertex V1,V2;
WeightType Weight;
};
typedef PtrToENode Edge;
typedef struct AdjVNode* PtrToAdjVNode;
struct AdjVNode
{
Vertex AdjV;
WeightType Weight;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FisrtEdge;
DataType Data;
}AdjList[MaxVertexNum];
typedef struct GNode* PtrToGNode;
struct GNode
{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
LGraph CreateGraph(int VertexNum)
{
Vertex V;
LGraph Graph;
Graph = (LGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for(V=0;V<Graph->Nv;V++)
Graph->G[V].FisrtEdge = NULL;
return Graph;
}
void InsertEdge(LGraph Graph, Edge E)
{
PtrToAdjVNode NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->V2;
NewNode->Weight = E->Weight;
NewNode->Next = Graph->G[E->V1].FisrtEdge;
Graph->G[E->V1].FisrtEdge = NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->V1;
NewNode->Weight = E->Weight;
NewNode->Next = Graph->G[E->V2].FisrtEdge;
Graph->G[E->V2].FisrtEdge = NewNode;
}
LGraph BuildGraph()
{
LGraph Graph;
Edge E;
Vertex V;
int Nv,i;
scanf("%d",&Nv);
Graph = CreateGraph(Nv);
scanf("%d",&(Graph->Ne));
if(Graph->Ne != 0){
E = (Edge)malloc(sizeof(struct ENode));
for(i=0;i<Graph->Ne;i++){
scanf("%d %d %d",&E->V1,&E->V2,&E->Weight);
InsertEdge(Graph,E);
}
}
for(V=0;V<Graph->Nv;V++)
scanf("%c",&(Graph->G[V].Data));
return Graph;
}
|
C
|
/*该头文件主要定义了文件系统的数据结构,全局变量定义*/
#include"block.h"
#ifndef FILESYSTEM_H_INCLUDED
#define FILESYSTEM_H_INCLUDED
//定义当前环境 1为开发环境 0为生产环境
#define ENV 0
struct fatitem {
//存放文件下一个磁盘的指针
int item;
//磁盘块是否空闲的标志位 0为空闲
char em_disk;
};
struct openFile {
//当前打开的文件表
struct openFileItem {
//文件名
char name[9];
//起始盘块号
int firstdisk;
//文件的大小
int size;
}opeitem[MOFN];
//当前打开的文件数目
int cur_size;
};
struct dirOrFile {
//文件控制块信息
struct FCB {
//文件名
char name[9];
//0为普通文件 1为目录
char property;
//文件的大小
int size;
//起始盘块号
int firstdisk;
//子目录起始盘号
int next;
//1表示根目录
int sign;
}dirOrFileitem[MSD + 2];
};
struct fatitem *fat;
struct dirOrFile *root;
struct dirOrFile *nowDir;
struct openFile openFile;
//当前打开文件的下标
int fd = -1;
char *dirPath;
char *fdisk;
void initfile();
void format();
void initRoot();
void exitSystem();
void console(char info[]);
int touch(char *name);
int open(char *name);
int close(char *name);
int write(int fd, char *buf, int len);
int read(int fd, char *buf);
int del(char *name);
int mkdir(char *name);
int rmdir(char *name);
void dir();
int cd(char *name);
void print();
void show();
void doMain();
int main();
#endif
|
C
|
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
void find(char *fn,char *dir);
int main(int argc, char *argv[])
{
char *fn = NULL;
char *dir = NULL;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "f:d:")) != -1) {
switch (c) {
case 'f':
fn = optarg;
break;
case 'd':
dir = optarg;
break;
default:
return 1;
}
}
find(fn, dir);
return 0;
}
// Parametre olarak bir dosya ismi ve içinde arama yapılacak klasör ismi alıyor.
// Klasörü recursive olarak tarıyor.
void find(char *fn, char *dire)
{
int found = 0;
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(dire)))
return;
if (!(entry = readdir(dir)))
return;
do {
// Klasörün içinde başka bir klasör varsa, o klasörü de tarıyoruz.
if (entry->d_type == DT_DIR) {
char p[1024];
strcpy(p, dire);
strcat(p, "/");
strcat(p, entry->d_name);
// Şimdiki ve bir üst klasörü temsil eden . ve .. yı es geçiyoruz.
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
find(fn, p);
}
else {
if((strcmp(fn, entry->d_name)) == 0) {
found = 1;
struct stat file_stats;
char file[1024];
strcpy(file, dire);
strcat(file, "/");
strcat(file, entry->d_name);
// Dosyanın bilgilerini alıyoruz
if((stat(file, &file_stats)) == -1) {
return;
}
printf("%s/%s,\t%ld,\t%ld,\t%s\n",
dire,
entry->d_name,
file_stats.st_ino,
file_stats.st_size,
ctime(&file_stats.st_mtime)
);
}
}
} while (entry = readdir(dir));
if(!found) {
printf("File %s could not be found in %s\n", fn, dire);
}
closedir(dir);
}
|
C
|
#include "strutil.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
char *substr(const char *str, size_t n)
{
if (n > strlen(str))
{
char *cadena = malloc(sizeof(char) * (strlen(str) + 1));
if (!cadena)
return NULL;
strcpy(cadena, str);
return cadena;
}
char *nueva_cadena = malloc(sizeof(char) * (size_t)(n + 1));
if (!nueva_cadena)
return NULL;
int i = 0;
while (i < n)
{
nueva_cadena[i] = str[i];
i++;
}
nueva_cadena[i] = '\0';
return nueva_cadena;
}
int _count_splits(const char *str, char sep)
{
int total_splits = 0;
for (int i = 0; i < strlen(str); i++)
if (str[i] == sep)
total_splits++;
total_splits++;
return total_splits;
}
int _array_total_splits(char **strv, size_t *cantidad_chars)
{
int total_splits = 0;
while (strv[total_splits])
{
(*cantidad_chars) += strlen(strv[total_splits]);
total_splits++;
}
return total_splits;
}
char **split(const char *str, char sep)
{
int total_splits = _count_splits(str, sep);
char **nueva_cadena = malloc(sizeof(char *) * (total_splits + 1));
int split_start = 0;
int nueva_cadena_i = 0;
for (int i = 0; i <= strlen(str); i++)
if (str[i] == sep || str[i] == '\0') // previene caso borde
{
// substr("ej,emplo" + 3, 5) == "emplo"
nueva_cadena[nueva_cadena_i] = substr(str + split_start, i - split_start);
split_start = i + 1; // salta separador
nueva_cadena_i++;
}
nueva_cadena[total_splits] = NULL;
return nueva_cadena;
}
char *join(char **strv, char sep)
{
if (!strv[0])
{
char *empty_string = malloc(sizeof(char));
empty_string[0] = '\0';
return empty_string;
}
size_t cantidad_chars = 0;
size_t total_splits = _array_total_splits(strv, &cantidad_chars);
size_t new_string_len = cantidad_chars + total_splits;
char *joined_string = malloc(sizeof(char) * new_string_len);
if (!joined_string)
return NULL;
joined_string[0] = '\0';
char _sep[1];
_sep[0] = sep;
size_t i_actual = 0;
for (size_t i = 0; i < new_string_len; i++)
{
strcat(joined_string + i_actual, strv[i]);
if (!strv[i + 1])
{
strcat(joined_string, "\0");
return joined_string;
}
i_actual += strlen(strv[i]);
strcat(joined_string, _sep);
}
return joined_string;
}
void free_strv(char *strv[])
{
int i = 0;
while (strv[i])
{
free(strv[i]);
i++;
}
free(strv);
}
|
C
|
#include <stdio.h>
#include <conio.h>
main()
{
void wczytywanie(int [],int );
void drukowanie(int [],int );
int a[10],b[10],k,m,n;
do
{
printf("\n Podaj ilosc elementow ciagu a:\n m = ");
k=scanf("%d",&m);
fflush(stdin);
}
while(k==0||m<1||m>10);
printf("\n Wczytaj tablice a:\n");
wczytywanie(a,m);
do
{
printf("\n Podaj ilosc elementow ciagu b:\n n = ");
k=scanf("%d",&n);
fflush(stdin);
}
while(k==0||n<1||n>10);
printf("\n Wczytaj tablice b:\n");
wczytywanie(b,n);
printf("\n\n Tablica a:\n");
drukowanie(a,m);
printf("\n\n Tablica b:\n");
drukowanie(b,n);
getch();
return 0;
}
void wczytywanie(int a[],int n)
{
int i,k;
for(i=0;i<n;i++)
do
{
printf("\n element %d = ",i);
k=scanf("%d",&a[i]);
fflush(stdin);
}
while(k==0);
}
void drukowanie(int a[],int n)
{
int i;
for(i=0;i<n;i++)
printf("\n element %d = %d",i,a[i]);
}
//:)
|
C
|
/*
Que 10 : Write a C program to count number of digits in a number.
owner:Aditya Wagh
Batch:PPA9
*/
//Solution
#include<stdio.h>
void main()
{
int n;
int count=0;
//initialization
printf("enter the number : \n");
scanf("%d",&n);
while(n!=0)
{
n=n/10;
count+=1;
}
//end of while
printf("total digits are %d ",count);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "xmalloc.h"
#include "linkedlist.h"
conscell *ll_push(conscell *list, void *data)
{
conscell *new = xmalloc(sizeof *new);
new->data = data;
new->next = list;
return new;
}
conscell *ll_pop(conscell *list)
{
if(list == NULL) return NULL;
conscell *p = list->next;
free(list);
return p;
}
void ll_free(conscell *list)
{
while(list != NULL)
{
list = ll_pop(list);
}
}
// not implemented
conscell *ll_reverse(conscell *list)
{
return NULL;
}
conscell *ll_sort(conscell *list,
int (*cmp)(const void *a, const void *b, void *params),
void *params)
{
conscell *list1 = NULL;
conscell *list2 = NULL;
conscell *p, *q, *head;
if(list == NULL)
return list;
head = list;
p = list->next;
while(p != NULL) {
q = p->next;
if(cmp(p->data, head->data, params) < 0) {
p->next = list1;
list1 = p;
} else {
p->next = list2;
list2 = p;
}
p = q;
}
list1 = ll_sort(list1, cmp, params);
list2 = ll_sort(list2, cmp, params);
head->next = list2;
if(list1 == NULL)
return head;
for(p = list1; p->next != NULL; p = p->next)
;
p->next = head;
return list1;
}
conscell *ll_filter(conscell *list,
int (*filter)(const void *a),
conscell **removed)
{
if(list == NULL)
return list;
else if(filter(list->data)) {
conscell *p = list->next;
list->next = *removed;
*removed = list;
return ll_filter(p, filter, removed);
}else {
list->next = ll_filter(list->next, filter, removed);
return list;
}
}
int ll_length(conscell *list)
{
if(list == NULL) return 0;
int count = 1;
conscell *p = list;
for(p = list; p->next != NULL; p=p->next, count++)
;
return count;
}
|
C
|
#include "DataStruct.h"
#include "AVL_Tree.h"
//int main(int argc, const char * argv[]) {
//// BinTree t1,t2,t3,t4,t5;
//// t1=(BinTree)malloc(sizeof(BinTree));
//// t2=(BinTree)malloc(sizeof(BinTree));
//// t3=(BinTree)malloc(sizeof(BinTree));
//// t4=(BinTree)malloc(sizeof(BinTree));
//// t5=(BinTree)malloc(sizeof(BinTree));
//// t1->Data=1;t1->Left=t2;t1->Right=t3;
//// t2->Data=2;t2->Left=NULL;t2->Right=t4;
////// t3->Data=3;t3->Left=t5;t3->Right=NULL;
//// t3->Data=3;t3->Left=NULL;t3->Right=t5;
//// t4->Data=4;t4->Left=NULL;t4->Right=NULL;
//// t5->Data=5;t5->Left=NULL;t5->Right=NULL;
//
// AVLTree t1,t2,t3,t4,t5;
// t1=(AVLTree)malloc(sizeof(AVLTree));
// t2=(AVLTree)malloc(sizeof(AVLTree));
// t3=(AVLTree)malloc(sizeof(AVLTree));
// t4=(AVLTree)malloc(sizeof(AVLTree));
// t5=(AVLTree)malloc(sizeof(AVLTree));
// t1->Data=3;t1->Left=t2;t1->Right=t3;t1->Height=3;
// t2->Data=2;t2->Left=t3;t2->Right=NULL;t2->Height=2;
// // t3->Data=3;t3->Left=t5;t3->Right=NULL;
// t3->Data=4;t3->Left=NULL;t3->Right=t5;t3->Height=2;
// t4->Data=1;t4->Left=NULL;t4->Right=NULL;t4->Height=1;
// t5->Data=5;t5->Left=NULL;t5->Right=NULL;t5->Height=1;
// printf("%d\n",GetHeight(t1));
// t1=AVL_Insert(t1, 4);
// printf("%d\n",t1->Right->Right->Data);
// return 0;
//}
|
C
|
#include "solver.h"
#include "mouse.h"
// This function redirects function calls from mouse.c to the desired maze solving algorithm
Action solver(Mouse *mouse)
{
// This can be changed to call other maze solving algorithms
return leftWallFollower(mouse);
}
// Simple algorithm; mouse goes straight until encountering a wall, then preferentially turns left
Action obstacleAvoider(Mouse *mouse)
{
if(getFrontReading(mouse) == 0) return FORWARD;
else if(getLeftReading(mouse) == 0) return LEFT;
else if(getRightReading(mouse) == 0) return RIGHT;
else return LEFT;
}
// Left wall following algorithm
int turnedLeft = 0;
Action leftWallFollower(Mouse *mouse)
{
if(turnedLeft)
{
turnedLeft = 0;
return FORWARD;
}
else if(getLeftReading(mouse) == 0)
{
turnedLeft = 1;
return LEFT;
}
else if(getFrontReading(mouse) == 0) return FORWARD;
else return RIGHT;
}
Action floodFill(Mouse *mouse)
{
// TODO: Implement this function!
return IDLE;
}
|
C
|
// A C program to implement flood fill algorithm
#include<stdio.h>
// Dimentions of paint screen
#define M 8
#define N 8
// A recursive function to replace previous color 'prevC' at '(x, y)'
// and all surrounding pixels of (x, y) with new color 'newC' and
void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC)
{
// Base cases
if (x < 0 || x >= M || y < 0 || y >= N)
return;
if (screen[x][y] != prevC)
return;
// Replace the color at (x, y)
screen[x][y] = newC;
// Recur for north, east, south and west
floodFillUtil(screen, x+1, y, prevC, newC);
floodFillUtil(screen, x-1, y, prevC, newC);
floodFillUtil(screen, x, y+1, prevC, newC);
floodFillUtil(screen, x, y-1, prevC, newC);
}
// It mainly finds the previous color on (x, y) and
// calls floodFillUtil()
void floodFill(int screen[][N], int x, int y, int newC)
{
int prevC = screen[x][y];
floodFillUtil(screen, x, y, prevC, newC);
}
// Driver program to test above function
int main()
{
int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1},
};
int x = 4, y = 4, newC = 3;
floodFill(screen, x, y, newC);
printf("Updated screen after call to floodFill: n");
for (int i=0; i<M; i++)
{
for (int j=0; j<N; j++)
printf("%d ", screen[i][j]);
printf("\n");
}
}
|
C
|
#include "holberton.h"
/**
* get_bit - This function returns the value of a bit at
* a given index
* @n: The bit passed to the function
* @index: The index to find
* Return: The value of a bit at that given index
*/
int get_bit(unsigned long int n, unsigned int index)
{
/* shift to the index */
unsigned int val = n >> index;
/* error check: if index greater than bit */
if (index >= (sizeof(n) * 8))
return (-1);
/* mask off low-order bits and return last bit */
return (val & 1);
}
|
C
|
//
// algorithm_ practice.h
// Algorithm-C
//
// Created by 掌上汇通Mac on 2018/10/24.
// Copyright © 2018 掌上汇通Mac. All rights reserved.
//
#ifndef algorithm__practice_h
#define algorithm__practice_h
#include <stdio.h>
#endif /* algorithm__practice_h */
/*题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?*/
void square_number(void);
/*题目:输出9*9口诀。*/
void multiplication_tables(void);
/*题目:古典问题(兔子生崽):有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?(输出前40个月即可)*/
void rabbit(void);
/*题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。*/
void prime_factor(int n);
/*题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。*/
void perfect_number(void);
/*题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
n: n个人围成一圈 m: 报数m的人退出圈子
*/
void number_off(int n, int m);
/*创建链表*/
void creat_linked_list(void);
/*全排列*/
void theWholeArrangement(int arr[],int k, int n);
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void addqatend(struct node **f , struct node **r, int num )
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = num;
if(*f == NULL )
{
temp->next = NULL;
*f = *r = temp;
}
else
{
(*r)->next = temp;
*r = temp;
}
}
void addqatbeg(struct node **f, struct node **r , int num)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node ));
temp->data = num;
if(*f == NULL)
{
temp->next = NULL;
*f = *r = temp;
}
else
{
temp->next = *f;
*f = temp;
}
}
int delqatbeg(struct node **f, struct node **r)
{
struct node *temp;
int item;
if(*f == NULL)
{
printf("Dequeue Already Empty .");
}
else
{
temp = *f;
if(temp->next == NULL )
{
*f = NULL;
*r = NULL;
item = temp->data;
free(temp);
return (item);
}
else
{
*f = temp->next;
item = temp->data;
free(temp);
return item;
}
}
return 0;
}
int delqatend(struct node **f, struct node **r )
{
struct node *temp;
int item;
if(*f == NULL)
{
printf("Dequeue Already Empty .");
}
else
{
temp = *f;
if(temp->next == NULL )
{
*f = NULL;
*r = NULL;
item = temp->data;
free(temp);
return (item);
}
while(temp->next != *r )
{
temp = temp->next;
}
item = temp->next->data;
temp->next = NULL;
free(*r);
*r = temp;
return (item);
}
return 0;
}
int deqcount(struct node *q )
{
int c = 0;
while(q != NULL)
{
c++;
q = q->next;
}
return c;
}
void deqdisplay(struct node *q )
{
while(q != NULL)
{
printf("%d->", q->data);
if(q->next == NULL)
{
printf("NULL");
}
q = q->next;
}
}
int main()
{
struct node *front , *rear;
front = rear = NULL;
addqatend(&front, &rear, 1);
addqatend(&front, &rear, 2);
addqatend(&front, &rear, 3);
addqatend(&front, &rear, 11);
addqatend(&front, &rear, 12);
addqatend(&front, &rear, 13);
deqdisplay(front);
printf("\nNumber of Elements are : %d\n", deqcount(front));
addqatbeg(&front, &rear, 22);
addqatbeg(&front, &rear, 33);
addqatbeg(&front, &rear, 44);
addqatbeg(&front, &rear, 55);
addqatbeg(&front, &rear, 66);
addqatbeg(&front, &rear, 77);
deqdisplay(front);
printf("\nNumber of Elements are : %d\n", deqcount(front));
delqatbeg(&front, &rear);
delqatbeg(&front, &rear);
deqdisplay(front);
printf("\nNumber of Elements are : %d", deqcount(front));
printf("\n");
delqatend(&front, &rear);
delqatend(&front, &rear);
deqdisplay(front);
printf("\nNumber of Elements are : %d\n", deqcount(front));
return 0;
}
|
C
|
/**
*/
#include <stdio.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/err.h>
// 3072, 7680, 15360
#define PRIVATE_KEY_FILE "RSAPriKey_3072.pem"
#define PUBLIC_KEY_FILE "RSAPubKey_3072.pub"
typedef unsigned char byte;
uint64_t rdtsc(){
unsigned int lo,hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return ((uint64_t)hi << 32) | lo;
}
// fill byte stram with random content. not cryptographic strong random
void fill_with_random(unsigned char *stream, int n)
{
size_t i;
for (i = 0; i < n; i++)
{
stream[i] = (unsigned char) (rand() % 255 + 1);
}
stream[n] = 0;
}
// note that the only 0 can show up at the end of the stream
char* gen_random_bytestream(int num_bytes)
{
unsigned char* stream=malloc(num_bytes + 1);
if (stream == NULL)
{
printf("ERROR : Could not allocate memory for random buffer !");
}
fill_with_random(stream, num_bytes);
return stream;
}
static void
printHex(const char *title, const unsigned char *s, int len)
{
int n;
printf("%s:", title);
for (n = 0; n < len; ++n) {
if ((n % 16) == 0) {
printf("\n%04x", n);
}
printf(" %02x", s[n]);
}
printf("\n");
}
void handleErrors(void)
{
ERR_print_errors_fp(stderr);
abort();
}
void generate_pri_keys()
{
// 3072, 7680, 15360
FILE *priKeyFile;
RSA *prikey=NULL;
prikey = RSA_generate_key(15360, RSA_F4, NULL, NULL);
if (prikey == NULL) {
printf("RSA_generate_key: error\n");
return;
}
priKeyFile = fopen("RSAPriKey_15360.pem", "w");
if (priKeyFile == NULL) {
perror("failed to fopen");
return;
}
PEM_write_RSAPrivateKey(priKeyFile, prikey, NULL, NULL, 0, NULL, NULL);
}
int main(int argc, char *argv[]) {
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
// load private and public keys
RSA *prikey=NULL, *pubkey=NULL;
FILE *f_pri;
if(NULL != (f_pri= fopen(PRIVATE_KEY_FILE, "r")) ) {
prikey = PEM_read_RSAPrivateKey(f_pri, NULL, NULL, NULL);
printf("Loaded Private key ... \n");
}
FILE * f_pub;
if(NULL != (f_pub= fopen(PUBLIC_KEY_FILE, "r")) ) {
pubkey = PEM_read_RSA_PUBKEY(f_pub, NULL, NULL, NULL);
printf("Loaded Public key ... \n");
}
// becnhamrk
uint64_t start_cycles, end_cycles, total_cycles, cycles_avg;
uint64_t start_cycles_ve, end_cycles_ve, total_cycles_ve, cycles_avg_ve;
int repetitions = 3;
for(int data_size_kb=512; data_size_kb<=64 * 1024; data_size_kb+=512) {
int data_size = 1024 * data_size_kb;
byte *msg = gen_random_bytestream(data_size);
int msg_len = strlen ((byte *)msg);
unsigned char hash[SHA512_DIGEST_LENGTH];
int ret;
SHA512(msg, msg_len, hash);
total_cycles = 0;
total_cycles_ve = 0;
for(int r=0; r<repetitions; r++) {
unsigned char sign[512];
unsigned int signLen;
start_cycles = rdtsc();
RSA_sign(NID_sha512, hash, SHA512_DIGEST_LENGTH, sign,
&signLen, prikey);
end_cycles = rdtsc();
total_cycles += (end_cycles - start_cycles);
start_cycles_ve = rdtsc();
RSA_verify(NID_sha512, hash, SHA512_DIGEST_LENGTH, sign,
signLen, pubkey);
end_cycles_ve = rdtsc();
total_cycles_ve += (end_cycles_ve - start_cycles_ve);
}
double avg_cycles = (double)total_cycles/repetitions;
double avg_cycles_ve = (double)total_cycles_ve/repetitions;
printf("%8f\n", avg_cycles_ve);
}
RSA_free(prikey);
RSA_free(pubkey);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
float varA, varB, varC, result, PI;
int opcao;
PI = 3.1415;
printf("--------------------------\n");
printf("Bem vindo a calculadora:\n");
printf("--------------------------\n");
printf("Escolha uma opção:\n");
printf("1) para volume da caixa:\n");
printf("2) para volume da esfera:\n");
printf("3) para volume do cilindro:\n");
printf("4) para divisão do cone:\n");
printf("--------------------------\n");
scanf("%d", &opcao);
if(opcao==1){
printf("Digite tres números:\n");
scanf("%f", &varA);
scanf("%f", &varB);
scanf("%f", &varC);
printf("--------------------------\n");
result = varA * varB * varC;
printf("O valor da area é %f", result);
}else if(opcao==2){
printf("Digite o raio:\n");
scanf("%f", &varA);
printf("--------------------------\n");
result = (varA*varA)*4/3*PI;
printf("O valor do volume do raio é %f", result);
}else if(opcao==3){
printf("Digite H (primeiro valor) e R (Segundo valor):\n");
scanf("%f", &varA);
scanf("%f", &varB);
printf("--------------------------\n");
result = PI*(varA*varA)*varB;
printf("O valor do volume do cilindro é %f:", result);
}else if(opcao==4){
printf("Digite H (primeiro valor) e R (Segundo valor):\n");
scanf("%f", &varA);
scanf("%f", &varB);
printf("--------------------------\n");
result = (PI*(varA*varA)*varB)*1/3;
printf("O valor do volume do cone é %f:", result);
}else{
printf("Opção inválida. Tente novamente!");
}
}
|
C
|
/*
* Simple debugging memory allocator.
*
* Each memory block is laid out as follows:
*
* +--------+-----------------+------+------------------+-------------------+
* | header | redzone | data | unused remainder | redzone |
* +--------+-----------------+------+------------------+-------------------+
*
* Remainders arise when a memory request for a given size is satisfied with
* a larger block. ``remainder + tail fence post'' can be derived using
* block_sz - data_sz - sizeof(header) - FENCE_SZ;
*
* Simplistic assumptions --- these make sense to change, just not in today's
* lab:
* - all blocks are 8-byte aligned and a multiple of 8 bytes.
* - zero filled on allocation.
* - redzones are the same size.
* - redzones and remainders are filled with a fixed byte (can extend to hash
* using the address).
* - the header stores block size and allocation/free site (file, function, lineno).
* - when users call free() we mark the block as free but do not reuse it
* (to minimize chance reuse can cause us to miss errors). this also
* simplifies the implementation.
*
* - all memory is laid out in a single contiguous region.
* +----+----+----+--------------------+
* | b1 | b2 | b3 | ...... free .... |
* +----+----+----+--------------------+
* cannot be resized. to allocate take a piece from the front. when you
* run out, you panic.
*
* easy to enumerate all blocks using the header information.
*/
typedef enum { ALLOCED = 11, FREED } state_t;
typedef struct {
const char *file;
const char *func;
unsigned lineno;
} src_loc_t;
// pull the remainder into the second redzone.
typedef struct header {
uint32_t nbytes_alloc; // how much the user requested to allocate.
uint32_t nbytes_rem; // the unused remainder (since we roundup).
uint32_t state; // state of the block: { ALLOCED, FREED }
// checksum of this header struct: use fast_hash from our libpi/libc
// uint32_t fast_hash(&header, sizeof(header));
uint32_t cksum;
src_loc_t alloc_loc, // location they called ckalloc() at.
free_loc; // location they called ckfree() at.
// used for error reporting.
// used for gc
uint32_t refs_start; // number of pointers to the start of the block.
uint32_t refs_middle; // number of pointers to the middle of the block.
// if you do a coalescing free you need something like this.
struct header *prev; // pointer to previous block, if any. needed if
// we do a coalescing free.
uint32_t padding; // 8 byte align.
} hdr_t;
// shouldn't be in the header: emit error, don't panic
#define ck_error(_h, args...) do { \
trace("ERROR:");\
printk(args); \
hdr_print(_h); \
} while(0)
// emit error, then panic.
#define ck_panic(_h, args...) do { \
trace("ERROR:");\
printk(args); \
hdr_print(_h); \
panic(args); \
} while(0)
// shouldn't be in the header.
static void inline hdr_print(hdr_t *h) {
trace("\tnbytes=%d\n", h->nbytes_alloc);
src_loc_t *l = &h->alloc_loc;
if(l->file)
trace("\tBlock allocated at: %s:%s:%d\n", l->file, l->func, l->lineno);
l = &h->free_loc;
if(h->state == FREED && l->file)
trace("\tBlock freed at: %s:%s:%d\n", l->file, l->func, l->lineno);
}
// shouldn't be in the header.
enum {
SENTINAL = 0xfe, // the sentinal we mark with --- should be less naive.
REDZONE = 128, // sizeof redzone
// offset of user allocation.
ALLOC_OFFSET = sizeof(hdr_t) + REDZONE,
OVERHEAD_NBYTES = ALLOC_OFFSET + REDZONE
};
// to make things easy in lab; trivial to fix.
_Static_assert((sizeof(hdr_t) + REDZONE) % 8 == 0, "REDZONE + header must be 8 byte aligned!");
#define ckalloc(_n) (ckalloc)(_n, __FILE__, __FUNCTION__, __LINE__)
#define ckfree(_ptr) (ckfree)(_ptr, __FILE__, __FUNCTION__, __LINE__)
void *(ckalloc)(uint32_t nbytes, const char *file, const char *func, unsigned lineno);
void (ckfree)(void *addr, const char *file, const char *func, unsigned lineno);
void ck_init(void *heap_start, unsigned n);
// integrity check the allocated / freed blocks in the heap
//
// returns number of errors in the heap. stops checking
// if heap is in an unrecoverable state.
int ck_heap_errors(void);
|
C
|
/*
* See what happens whan mapping a non-truncated file and what happens
* when doing private mapping on a file.
*
* 2011, Razvan Deaconescu, razvan.deaconescu@cs.pub.ro
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
/* Turn to MAP_PRIVATE for private mapping. */
#define MAPPING_TYPE MAP_SHARED
/* Uncomment to enable file truncation (ftruncate(2)). */
/*#define TRUNCATE_FILE 1*/
#define FILENAME "test.map"
#define MAPPING_SIZE (getpagesize())
int main(void)
{
int fd;
char *addr;
/* For testing purpose, remove file from filesystem. */
unlink(FILENAME);
fd = open(FILENAME, O_RDWR | O_CREAT, 0644);
if (fd < 0) {
perror("open");
exit(EXIT_FAILURE);
}
#if TRUNCATE_FILE == 1
if (ftruncate(fd, MAPPING_SIZE) < 0) {
perror("ftruncate");
exit(EXIT_FAILURE);
}
#endif
addr = mmap(NULL, MAPPING_SIZE, PROT_READ | PROT_WRITE, MAPPING_TYPE, fd, 0);
if (addr == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
/*
* Do access.
* In case of shared-mapping on non-truncated file, this results
* in the delivery of SIGBUS.
*/
*addr = 'a';
munmap(addr, MAPPING_SIZE);
close(fd);
return 0;
}
|
C
|
#include "VMsimulator.h"
/*
* Justin Barish
* Jack Kraszewski
*
* We pledge our honor that we have abided by the Stevens Honor System
*/
struct node{
frame p;
struct node* next;
struct node* prev;
};
typedef struct node* Node;
Node head = NULL;
Node tail = NULL;
/*
* [tail] [head]
* | |
* |frame | |frame | |frame |
* |prev=null|<--|=prev |<--|=prev |
* |next = --|-->|next=--|-->|next=null|
*
* Add to tail, remove from head with dequeueFirst
*/
/*num of elements currently in queue*/
int numElements = 0;
/*remove item at head
*returns NULL if nothing in list
*/
frame dequeueFirst(){
if(head!=NULL){
frame pTemp = head->p;
Node temp = head;
if(head->prev!=NULL){
temp->prev->next=NULL;
}
head=temp->prev;
free(temp);
numElements--;
if(numElements==0){
tail ==NULL;
}
return pTemp;
}
return NULL;
}
/*add to tail*/
void enqueue(frame prod){
if(head!=NULL){
Node new = (Node)malloc(sizeof(struct node));
new->p = prod;
tail->prev = new;
new->next = tail;
tail = new;
new->prev = NULL;
}else{
/*first thing in list*/
Node new = (Node)malloc(sizeof(struct node));
new->p = prod;
new->prev = NULL;
new->next=NULL;
head = new;
tail = new;
}
numElements++;
}
int getNumElements(){
return numElements;
}
|
C
|
#include <stdio.h>
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, b;
scanf("%d%d", &a, &b);
int c = a;
a = b;
b = c;
printf("%d %d", a, b);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* format.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lde-moul <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/13 14:46:56 by lde-moul #+# #+# */
/* Updated: 2017/03/13 15:25:18 by lde-moul ### ########.fr */
/* */
/* ************************************************************************** */
#include "format.h"
#include "flags.h"
#include "width.h"
#include "precision.h"
#include "conversion.h"
#include "conflict.h"
#include "print_decimal.h"
#include "print_hexadecimal.h"
#include "print_octal.h"
#include "print_signed.h"
#include "print_string.h"
#include "print_wstring.h"
#include "print_char.h"
#include "print_wchar.h"
#include "print_pointer.h"
static void print_formatted_unsigned(va_list args, t_format *info)
{
uintmax_t n;
if (info->conversion_length == CONV_HH)
n = (unsigned char)va_arg(args, int);
else if (info->conversion_length == CONV_H)
n = (unsigned short)va_arg(args, int);
else if (info->conversion_length == CONV_L)
n = va_arg(args, unsigned long);
else if (info->conversion_length == CONV_LL)
n = va_arg(args, unsigned long long);
else if (info->conversion_length == CONV_J)
n = va_arg(args, uintmax_t);
else if (info->conversion_length == CONV_Z)
n = va_arg(args, size_t);
else
n = va_arg(args, unsigned int);
if (info->conversion_format == CONV_NONE)
print_decimal(n, info);
else if (info->conversion_format == CONV_OCTAL)
print_octal(n, info);
else
print_hexadecimal(n, info);
}
static void print_formatted_signed(va_list args, t_format *info)
{
if (info->conversion_length == CONV_HH)
print_signed((signed char)va_arg(args, int), info);
else if (info->conversion_length == CONV_H)
print_signed((short)va_arg(args, int), info);
else if (info->conversion_length == CONV_L)
print_signed(va_arg(args, long), info);
else if (info->conversion_length == CONV_LL)
print_signed(va_arg(args, long long), info);
else if (info->conversion_length == CONV_J)
print_signed(va_arg(args, intmax_t), info);
else if (info->conversion_length == CONV_Z)
print_signed(va_arg(args, size_t), info);
else
print_signed(va_arg(args, int), info);
}
int print_formatted(const char *fmt, va_list args, size_t *i)
{
t_format info;
(*i)++;
check_flags(fmt, i, &info.flags);
check_width(fmt, args, i, &info);
check_precision(fmt, args, i, &info.precision);
check_conversion(fmt, i, &info);
check_conflicts(&info);
if (info.conversion_type == CONV_UNSIGNED)
print_formatted_unsigned(args, &info);
else if (info.conversion_type == CONV_SIGNED)
print_formatted_signed(args, &info);
else if (info.conversion_type == CONV_STRING)
print_string(va_arg(args, char*), &info);
else if (info.conversion_type == CONV_WSTRING)
print_wstring(va_arg(args, wchar_t*), &info);
else if (info.conversion_type == CONV_CHAR)
print_char((unsigned char)va_arg(args, int), &info);
else if (info.conversion_type == CONV_WCHAR)
print_wchar(va_arg(args, wchar_t), &info);
else if (info.conversion_type == CONV_POINTER)
print_pointer((size_t)va_arg(args, void*), &info);
else if (info.conversion_type == CONV_PERCENT)
print_char(fmt[*i], &info);
return (info.written);
}
|
C
|
#include <stdio.h>
int main() {
printf("The character\n \0 is used to terminate a string.");
char my_string[10]; // indicates that there is only only 9 spaces for characters because the last char has to be a null terminator '\0'
char word[] = {'H', 'e','l','l','o','!'};
char word_2[] = {"hello"};
char compiler_assigned[] = "This is assigned by the compiler";
//my_string = "err"; // will generate an error because you can't assign strings since it's an array
printf("word[] is %s\n", word);
printf("compiler_assigned[] is %s\n", compiler_assigned);
printf("word_2[] is %s\n", word_2);
printf("my_string is %s\n", my_string);
// strings are arrays so you cannot use equality operators on them
// you would need to compare each character by character. instead use strcmp
// 'x' is not the same as "x". "x" has both a x char and a '\0'
int count = 0;
while (compiler_assigned[count] != '\0')
++count;
printf("\nThe length of the string %s is %d.\n", compiler_assigned, count);
return 0;
}
|
C
|
/*--------------------------------------------------------------------------------
* Libraries
*--------------------------------------------------------------------------------*/
#include "Task.h"
#include "Timer.h"
/* software components includes */
#include "Sensor.h"
#include "Lighting.h"
#include "Display.h"
#include "ComManager.h"
/*--------------------------------------------------------------------------------
* Const and Macro
*--------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------
* Global variables
*--------------------------------------------------------------------------------*/
TaskConfiguration_Type taskList[] =
{
/* task init function , task cyclic function , task period [ms] */
{ &Lighting_InitRunnable , &Lighting_MainRunnable , SWC_LIGHTING_PERIOD },
{ &ComManager_InitRunnable , &ComManager_MainRunnable , SWC_COMMANAGER_PERIOD},
{ &Display_InitRunnable , &Display_MainRunnable , SWC_DISPLAY_PERIOD },
{ &Sensor_InitRunnable , &Sensor_MainRunnable , SWC_SENSOR_PERIOD }
};
const U8 TASKS_NUMBER = sizeof(taskList)/sizeof(taskList[0]);
U32 lastRun[TASKS_NUMBER] = {0};
/*--------------------------------------------------------------------------------
* Functions prototypes
*--------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------
@name Task_Init
@brief Initialize module
@paramIn void
@paramOut OK - all task have been schedueled
NOK - task init errors
*--------------------------------------------------------------------------------*/
U8 Task_Init(void)
{
return RETURN_OK;
}
/*--------------------------------------------------------------------------------
@name Task_Deinit
@brief Deinitialize module
@paramIn void
@paramOut OK - all task have been schedueled
NOK - task init errors
*--------------------------------------------------------------------------------*/
U8 Task_Deinit(void)
{
return RETURN_OK;
}
/*--------------------------------------------------------------------------------
@name Task_InitRunnable
@brief Call the initialization functions for all tasks
@paramIn void
@paramOut
*--------------------------------------------------------------------------------*/
void Task_InitRunnable(void)
{
U8 index = 0;
for(index=0; index<TASKS_NUMBER; index++)
{
taskList[index].taskInitRunnable();
}
}
/*--------------------------------------------------------------------------------
@name Task_MainRunnable
@brief This task run forever. This will launch all the task in this system
@paramIn void
@paramOut void
*--------------------------------------------------------------------------------*/
void Task_MainRunnable()
{
U64 currentTime = 0;
while(1)
{
/*************************************************
* ROUND ROBIN method
*************************************************/
currentTime = Timer_GetCurrentTime();
for(U8 index=0; index<TASKS_NUMBER; index++)
{
if(currentTime >= (lastRun[index] + taskList[index].taskPeriod))
{
if(taskList[index].taskMainRunnable != nullptr)
{
taskList[index].taskMainRunnable();
lastRun[index] = currentTime;
}
}
}
}
}
|
C
|
/*file ptask.c
details This module contains the functions to create and manage the tasks
author Davide Rasla
todo
*/
#include "main.h"
//----------------------------------------
// PTASK LIBRARY
//----------------------------------------
/*
This function creates a periodic task
setting the scheduler algorithm to SCHED_FIFO
*/
int task_create(int i, void*(*task)(void *), int period, int drel, int prio){
pthread_attr_t myatt;
struct sched_param mypar;
int tret;
printf("Created task: %d\n",i );
tp[i].arg = i;
tp[i].period = period;
tp[i].deadline = drel;
tp[i].priority = prio;
tp[i].dmiss = 0;
pthread_attr_init(&myatt);
pthread_attr_setinheritsched(&myatt,PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&myatt, SCHED_FIFO);
mypar.sched_priority = tp[i].priority;
pthread_attr_setschedparam(&myatt, &mypar);
tret = pthread_create(&tid[i], &myatt, task, (void*)(&tp[i]));
if (tret != 0) {
perror("task_create");
return -1;
}
return tret;
}
/*
Retrieves the task index stored in tp->arg.
*/
int get_task_index(void* arg){
struct task_par *tp;
tp = (struct task_par *)arg;
return tp->arg;
}
/*
Retrieves the task period stored in tp[i].period.
*/
int task_period(int i){
return tp[i].period;
}
/*
Reads the current time and computes the next activation
time and the absolute deadline of the task.
*/
void set_activation(int i){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
time_copy(&(tp[i].at), t);
time_copy(&(tp[i].dl), t);
time_add_ms(&(tp[i].at), tp[i].period);
time_add_ms(&(tp[i].dl), tp[i].deadline);
}
/*
If the thread is still in execution when re‐activated, it
increments the value of dmiss and returns 1, otherwise
returns 0.
*/
int deadline_miss(int i){
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
if (time_cmp(&now, tp[i].dl) > 0) {
tp[i].dmiss++;
return 1;
}
return 0;
}
/*
Suspends the calling thread until the next activation and,
when awaken, updates activation time and deadline.
NOTE: Even though the thread calls time_add_ms() after
the wake‐up time, the computation is correct.
*/
void wait_for_activation(int i){
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &(tp[i].at), NULL);
time_add_ms(&(tp[i].at), tp[i].period);
time_add_ms(&(tp[i].dl), tp[i].period);
}
/*
The main thread blocks until the other created threads finish
*/
void wait_for_task_end(int i){
pthread_join(tid[i], NULL);
}
/*
Sets the piority of the main thread higher than the others and
the policy to use to schedule the threads
*/
void ptask_init(int policy){
struct sched_param my_par;
my_par.sched_priority = PRI + 7;
pthread_setschedparam(pthread_self(), policy, &my_par);
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
/*
* 9. Palindrome Number
* Determine whether an integer is a palindrome.
* Do this without extra space.
*
* Runtime: 48ms
*/
int palindrome(int num) {
if(num < 0) { return 0; }
if(num < 10) { return 1; }
int n = log10(num);
int l = n + 1;
int c = n;
while(c >= l / 2) {
int d = l - c - 1;
int p1 = pow(10, c);
int p2 = pow(10, d);
int y = ((num - (num % p1)) / p1) % 10;
int z = ((num - (num % p2)) / p2) % 10;
if(y != z) {
return 0;
}
c = c - 1;
}
return 1;
}
int main(int argc, char** argv) {
if(argc == 1) {
printf("Usage: ./palindrome <number>\n");
return 0;
}
int number = atoi(argv[1]);
if(palindrome(number)) {
printf("%d is a palindrome.\n", number);
}
else {
printf("%d is not a palindrome.\n", number);
}
return 0;
}
|
C
|
#include "holberton.h"
/**
*_strcat - concatenates two strings
*@src: source
*@dest: destination
*Return: return a pointeur to tthe resulting string
*/
char *_strcat(char *dest, char *src)
{
int char_end_src;/*array nuber with value '\0' in src*/
int i;
/*loocking for '\0' in dst*/
{
for (i = 0 ; dest[i] != '\0' ; i++)
{
}
for (char_end_src = 0 ; src[char_end_src] != '\0' ; char_end_src++)
/*add add src to dest*/
{
dest[i + char_end_src] = src[char_end_src];
}
}
return (dest);
}
|
C
|
/*12279 - Emoogle Balance*/
#include <stdio.h>
int main(){
int casos, cont=1, i;
while(scanf("%d", &casos) != EOF){
if( casos==0){
break;
}
int num;
int tot=0;
for(i=0; i<casos; i++){
scanf("%d", &num);
if(num==0){
tot--;
}
else{
tot++;
}
}
printf("Case %d: %d\n", cont, tot);
cont++;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main(){
double n,m;
printf("Enter a number : \n");
scanf("%lf",&n);
m=log10(n);
printf("Number of digits = %lf",m+1);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define N 101
int ord (const void * a, const void * b) {
return ( *(float*)b - *(float*)a );
}
float l1(float wcl[], float cap_veicolo, float ncl){
float tot_pesi=0., l1;
for(int i=0; i<ncl; i++){
tot_pesi+=wcl[i];
}
l1 = tot_pesi/cap_veicolo;
return ceil(l1);
}
float max(float a, float b){ return a>b?a:b; }
int main(int argc, char *argv[]) {
FILE *fd;
int i=1, tmp;
float capac, l2;
char c[100];
fd=fopen(argv[1], "r");
if( fd==NULL ) {
perror("Errore in apertura del file");
exit(1);
}
for(int x=0; x<8; x++){
if(x==4){
fscanf(fd, "%d", &tmp);
fscanf(fd, "%f", &capac);
}else{
fscanf(fd, "%s", c);
}
}
fgets(c, 100, fd);
float pesi[N+2];
while(i<=N){
for(int j=0; j<7; j++){
if(j==3){
fscanf(fd, "%f", &pesi[i]);
}else{
fscanf(fd, "%d", &tmp);
}
}
i++;
}
fclose(fd);
qsort(pesi+1, N, sizeof(float), ord);
int jst;
for(i=1; i<=N; i++){
if(pesi[i]<=(capac/2)){
jst=i;
break;
}
}
int cj12, jp, js, cj2;
if(jst==1){
l2 = l1(pesi+1, capac, N);
}else{
float sjst=0.;
cj12 = jst-1; //|j1|+|j2|
for(i=jst; i<=N-1; i++){
sjst+=pesi[i];
}
jp=jst;
for(i=1; i<=N; i++){
if(i<jst && pesi[i]<=(capac-pesi[jst])){
jp=i;
break;
}
}
cj2=jst-jp;//|j2|
float sj2=0.;
if(jp<jst){
for(i=jp; i<=jst-1; i++){
sj2+=pesi[i];
}
}
js=jst;
float sj3=pesi[js];
pesi[N+1]=0;
while (pesi[js+1]==pesi[js]) {
js++;
sj3+=pesi[js];
}
l2=cj12;
do {
l2 = max(l2, cj12+ceil(((sj3+sj2)/capac)-cj2));
js++;
if(js<=N){
sj3+=pesi[js];
while (pesi[js+1]==pesi[js]) {
js++;
sj3+=pesi[js];
}
while (jp>1 && pesi[jp-1]<=(capac-pesi[js])) {
jp--;
cj2++;
sj2+=pesi[jp];
}
}
} while(js<=N && (cj12+ceil(((sjst+sj2)/capac)-cj2))>l2 );
}
printf("%s --> %d\n", argv[1], (int)l2);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: letuffle <letuffle@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/27 23:45:35 by letuffle #+# #+# */
/* Updated: 2020/07/27 23:45:37 by letuffle ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include "libft.h"
void *ft_memccpy_m(void *dest, void *src, int c, size_t n)
{
size_t i;
i = 0;
while (i < n)
{
((unsigned char*)dest)[i] = ((unsigned char*)src)[i];
if (((unsigned char*)src)[i] == (unsigned char)c)
{
((unsigned char*)dest)[i] = '\0';
break ;
}
i++;
}
if (i < n)
return (src + i + 1);
return (NULL);
}
char *set_nullstr(va_list args, t_formats *formats)
{
char *str;
int accuracy;
str = va_arg(args, char*);
if (!str)
{
str = ft_strdup("(null)");
if (formats->accuracy[0] == '.')
{
accuracy = ft_atoi(formats->accuracy + 1);
if (accuracy >= 0 && accuracy <= 6)
str[accuracy] = '\0';
}
return (str);
}
return (ft_strdup(str));
}
char *ft_full(char c, size_t size)
{
size_t i;
char *str;
i = 0;
str = malloc(size + 1);
if (str)
{
while (i < size)
{
str[i] = c;
i++;
}
str[size] = '\0';
}
return (str);
}
int ft_max(int a, int b)
{
return ((a > b) ? a : b);
}
int isnumbertype(char c)
{
if (c == 'd' || c == 'u' || c == 'i' || c == 'x' || c == 'X')
return (1);
return (0);
}
|
C
|
#include<stdio.h>
int main()
{
int a,kvadrat,kub;
printf("\n Vasheto chislo e:");
scanf("%d",&a);
kvadrat=a*a;
printf("\n%d",kvadrat);
kub=kvadrat*a;
printf("\n%d",kub);
}
|
C
|
/*
* @Description: -
* @Version: -
* @Author: Fox_benjiaming
* @Date: 2020-10-21 01:06:55
* @LastEditors: Fox_benjiaming
* @LastEditTime: 2020-10-22 01:25:00
*/
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/time.h>
#include <stdlib.h>
#include <unistd.h>
#define SEND_BUFF_SIZE 11
#define READ_BUFF_SIZE 32
void calculate_crc(unsigned char *data, int x_len, int y_len)
{
int i, j;
unsigned char crc = 0;
unsigned char *ptr;
for (i = 0; i < x_len; i++)
{
ptr = data + i*y_len;
for (j = 0; j < y_len-1; j++)
crc += *(ptr + j);
*(ptr + j) = crc;
}
}
unsigned char send_buff[][SEND_BUFF_SIZE] = {
//发送学习模块存储器1里数据的指令
{0x7e, 0x07, 0x00, 0x59, 0x39, 0x59, 0x39, 0x14, 0x00, 0},
//发送学习模块存储器2里数据的指令
{0x7e, 0x07, 0x00, 0x59, 0x39, 0x59, 0x39, 0x14, 0x01, 0},
//发送学习模块存储器3里数据的指令
{0x7e, 0x07, 0x00, 0x59, 0x39, 0x59, 0x39, 0x14, 0x02, 0},
//发送学习模块存储器4里数据的指令
{0x7e, 0x07, 0x00, 0x59, 0x39, 0x59, 0x39, 0x14, 0x03, 0},
//发送学习模块存储器5里数据的指令
{0x7e, 0x07, 0x00, 0x59, 0x39, 0x59, 0x39, 0x14, 0x04, 0},
//发送学习模块存储器6里数据的指令
{0x7e, 0x07, 0x00, 0x59, 0x39, 0x59, 0x39, 0x14, 0x05, 0},
//发送学习模块存储器7里数据的指令
{0x7e, 0x07, 0x00, 0x59, 0x39, 0x59, 0x39, 0x14, 0x06, 0}
};
// 串口2文件句柄
int fd;
// 单次串口数据缓冲区
unsigned char uart_read_buffer[READ_BUFF_SIZE];
unsigned int uart_read_count;
// 单次串口数据读取完成标志位,需要手动复位
bool read_finish_flag = false;
void read_thread(void)
{
read(fd, NULL, 0);
printf("haha\n");
}
int main(int argc, char *argv[])
{
int i;
pthread_t read_thread_id;
char *str = "aaa\n";
fd = open("/dev/tv_control", O_RDWR);
// printf("I am main:%d\n", pthread_self());
// pthread_create(&read_thread_id, NULL, (void *)read_thread, NULL);
// write(fd, str, 7);
// pthread_join(read_thread_id, NULL);
// while (1)
// {
calculate_crc((char *)send_buff, 7, SEND_BUFF_SIZE);
// for (i = 0; i < 1; i++)
// {
write(fd, send_buff[0], SEND_BUFF_SIZE);
// write(fd, str, 4);
sleep(2);
// }
// write(fd, str, 3);
// }
close(fd);
return 0;
}
|
C
|
#ifndef UTILS_H_
#define UTILS_H_
#include "common/lamp_config.h"
static Notification* SelectNotification(lamp_config_t* config, jenkins_status_t status) {
Notification* n = NULL;
for (int i = 0; i < JENKINS_STATUS_NR_ITEMS; i++){
if (config->notification_list[i].jenkins_status == status) {
n = &config->notification_list[i];
break;
}
}
return n;
}
static Color HTMLToColor(String html) {
Color output;
sscanf(html.substring(1,3).c_str(), "%2x", &output.red);
sscanf(html.substring(3,5).c_str(), "%2x", &output.green);
sscanf(html.substring(5,7).c_str(), "%2x", &output.blue);
return output;
}
static String ColorToHTML(Color c) { //TODO(Ortinson): Improve
String r = String(c.red, HEX);
if (c.red <= 15)
r = String("0" + r);
String g = String(c.green, HEX);
if (c.green <= 15)
g = String("0" + g);
String b = String(c.blue, HEX);
if (c.blue <= 15)
b = String("0" + b);
return String("#" + r + g + b);
}
#endif
|
C
|
#ifndef _LINKED_LIST_SET_
#define _LINKED_LIST_SET_
#include "LinkedList.h"
typedef struct LinkedListSet LinkedListSet;
struct LinkedListSet {
LinkedList *ll;
};
LinkedListSet* create_linked_list_set() {
LinkedListSet *lls = NULL;
lls = (LinkedListSet*)malloc(sizeof(LinkedListSet));
lls->ll = create_linked_list();
return lls;
}
int LinkedListSet_getSize(LinkedListSet *lls) {
return linkedList_getSize(lls->ll);
}
bool LinkedListSet_isEmpty(LinkedListSet *lls) {
return linkedList_isEmpty(lls->ll);
}
bool LinkedListSet_contains(LinkedListSet *lls, B e) {
return linkedList_contains(lls->ll, e);
}
void LinkedListSet_add(LinkedListSet *lls, B e) {
if (!LinkedListSet_contains(lls, e))
linkedList_addFirst(lls->ll,e);
}
void LinkedListSet_remove(LinkedListSet *lls, B e) {
linkedList_remove(lls->ll, e);
}
void release_linked_list_set(LinkedListSet *lls) {
release_linked_list(lls->ll);
free(lls);
lls = NULL;
}
#endif
|
C
|
/**********************SY-1ʵ鿪************************
* ƽ̨SY-1+STC89C52
* ƣSY-1 ʵλʾ05
* ˾˼ԴӿƼ˾
* д˼Դ
* ڣ2012-12-25
* QQ : 936559219
* :11.0592MHZ
******************************************************************/
#include <reg51.h>
sbit dula=P2^6; //ѡźŵ
sbit wela=P2^7; //λѡźŵ
unsigned char code wei[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf};
//ܸλ
unsigned char code duan[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d};
//0-5
void delay(unsigned int i)
{
unsigned int m,n;
for(m=i;m>0;m--)
for(n=90;n>0;n--);
}
void main()
{
unsigned char num;
while(1)
{
for(num=0;num<6;num++)
{
P0=wei[num];
wela=1;
wela=0;
P0=duan[num];
dula=1;
dula=0;
delay(1000);
}
}
}
|
C
|
#include <stdio.h>
int main(){
int quantidade_minima, quantidade_maxima;
float estoque_medio;
printf ("Informe a quantidade minima: ");
scanf("%d", &quantidade_minima);
printf("Informe a quantidade maxima: ");
scanf("%d", &quantidade_maxima);
estoque_medio = (quantidade_minima + quantidade_maxima) / 2;
printf("A quantidade media é de %.2f", estoque_medio);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "binaria.h"
int bin_vazia(no_bin *arvore)
{
return arvore == NULL;
}
no_bin *bin_buscar(no_bin *arvore, int valor)
{
if (!bin_vazia(arvore)) {
if (valor == arvore->info)
return arvore;
else if (valor < arvore->info)
return bin_buscar(arvore->esq, valor);
else if (valor > arvore->info)
return bin_buscar(arvore->dir, valor);
}
return NULL;
}
no_bin *bin_inserir(no_bin *arvore, int valor)
{
if (bin_vazia(arvore)) {
arvore = (no_bin *) malloc(sizeof(no_bin));
arvore->dir = arvore->esq = NULL;
arvore->info = valor;
} else if (valor < arvore->info) {
arvore->esq = bin_inserir(arvore->esq, valor);
} else if (valor > arvore->info) {
arvore->dir = bin_inserir(arvore->dir, valor);
}
return arvore;
}
void bin_imprimir(no_bin *arvore)
{
if (!bin_vazia(arvore)) {
bin_imprimir(arvore->esq);
printf("%d\n", arvore->info);
bin_imprimir(arvore->dir);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} node;
typedef node *nodePtr;
int size (), empty (),exist ( int, int *), pop ( int *), stackLen = 0;
void printStack (), push ( nodePtr);
nodePtr head = NULL, tail = NULL;
int main(){
setvbuf( stdout, NULL, _IONBF, 0);
int type = 0, input = 0, reward = 0;
while( type != 7){
printf("%s","\nEnter type\n\t1.push\n\t2.pop\n\t3.printStack\n\t4.empty\n\t5.size\n\t6.exist\n\t7.exit --> ");
scanf("%d", &type);
switch( type){
default :{
puts("\ntype ERROR ,reTry plz.\n");
break;
}case 5:{
printf("\nsize = %d", size());
break;
}case 4:{
if( !empty()) printf("not empty, size is %d !\n", size());
else puts("nothing there !");
break;
}case 6:{
printf("\n%s","input the number u wanna find --> ");
scanf("%d",&input);
if( exist( input, &reward)) printf("it's exist, on pos %d !\n", reward);
else puts("not in there !");
break;
}case 3:{
printStack();
break;
}case 1:{
printf("%s","input yor data --> ");
nodePtr ptr = malloc(sizeof(*ptr));
scanf("%d",&( ptr -> data));
push( ptr);
break;
}case 2:{
if(pop( &reward)) printf("%d is deleted !\n", reward);
else puts("nothing there !");
break;
}case 7:{
puts("bye !");
break;
}
}
}
}
int size(){ return stackLen;}
int empty(){ return head == NULL ? 1 : 0;}
int exist( int target, int * pos){
nodePtr current = head;
*pos = 1;
while( current != NULL){
if( current -> data == target) return 1;
current = current -> next;
*pos += 1;
}return 0;
}
void printStack(){
nodePtr current = head;
if(empty()) puts("List is empty!");
else
while(current != NULL){
printf("\t%d", current -> data);
current = current -> next;
}
}
void push( nodePtr ptr){
if( head == NULL) head = ptr;
else tail -> next = ptr;
tail = ptr;
ptr -> next = NULL;
stackLen ++;
}
int pop( int * value){
nodePtr current = head, previous = NULL;
if(empty()) return 0;
*value = tail->data;
while( current != tail){
previous = current;
current = current -> next;
}
if( previous == NULL) head = NULL;
else previous -> next = NULL;
tail = previous;
free( current);
stackLen --;
return 1;
}
|
C
|
#pragma warning( disable : 4996)
#include<stdio.h>
#include<stdlib.h>
#include"Database.h"
#define SHOW_HOTEL_STATUS 1
#define ADD_CUSTOMER 2
#define CHECKIN 3
#define CHECKOUT 4
#define SHOW_ROOM_DETAILS 5
#define UPPER_FIRST_LETTERS 6
#define SUB_STRING_NAME 7
#define EXIT -1
void main()
{
int choice = 0;
database_t database = { 0,0 };
setNewHotel(&database.CaliforniaHotel);
while (choice != EXIT)
{
printf("\nPress 1 to show hotel status\n");
printf("Press 2 to add customer\n");
printf("Press 3 to checkIn\n");
printf("Press 4 to checkOut\n");
printf("Press 5 to print room details\n");
printf("Press 6 to set customer's name's first letter\n");
printf("Press 7 to enter a name and print customers\n");
printf("To exit press 0 or any other number..\n");
scanf("%d", &choice);
switch (choice)
{
case SHOW_HOTEL_STATUS:
showHotelStatus(&database.CaliforniaHotel);
break;
case ADD_CUSTOMER:
addCustomer(&database);
break;
case CHECKIN:
checkIn(&database);
break;
case CHECKOUT:
checkOut(&database);
break;
case SHOW_ROOM_DETAILS:
showRoomDetails(&database.CaliforniaHotel);
break;
case UPPER_FIRST_LETTERS:
upperCustomersFirstLetters(database.customers, database.cusSize);
break;
case SUB_STRING_NAME:
subSringCustomersName(database.customers, database.cusSize);
break;
default:
freeArchive(&database);
choice = EXIT;
printf("\nBye-Bye\n");
break;
}
}
system("pause");
}
|
C
|
/* Here will go the prototype functions for the HashTable ADT */
#include "ListBook.h"
#include <stdio.h>
/*Declaration of the HashTableHndl empty pointer. Set it to null
*when you first use it! */
typedef struct HashTableStruct * HashTableHndl;
/* makes the new hash table and puts an array of BookListHndls
* of size size in the actual table */
HashTableHndl NewHashTable (int size);
/* frees the hash table and all structures within it*/
/* Pre: H is not NULL*/
void freeHashTable (HashTableHndl H);
/* Hashes based on the string and inserts it into the slot in the table*/
/* Pre: H is not NULL*/
void insertIntoHashTable (HashTableHndl H, char * title, int id);
/* uses the hash function to look up the right element, then prints it if
* it is found*/
/* Pre: H is not NULL*/
void printTableElement (HashTableHndl H, char * title);
|
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 */
typedef int track_t ;
typedef scalar_t__ lsn_t ;
typedef int /*<<< orphan*/ CdIo_t ;
/* Variables and functions */
int CDIO_CDROM_LEADOUT_TRACK ;
int CDIO_INVALID_TRACK ;
int cdio_get_first_track_num (int /*<<< orphan*/ const*) ;
int cdio_get_last_track_num (int /*<<< orphan*/ const*) ;
scalar_t__ cdio_get_track_lsn (int /*<<< orphan*/ const*,int const) ;
track_t
cdio_get_track(const CdIo_t *p_cdio, lsn_t lsn)
{
if (!p_cdio) return CDIO_INVALID_TRACK;
{
track_t i_low_track = cdio_get_first_track_num(p_cdio);
track_t i_high_track = cdio_get_last_track_num(p_cdio)+1;
track_t i_lead_track = i_high_track;
if (CDIO_INVALID_TRACK == i_low_track
|| CDIO_INVALID_TRACK == i_high_track ) return CDIO_INVALID_TRACK;
if (lsn < cdio_get_track_lsn(p_cdio, i_low_track))
return 0; /* We're in the pre-gap of first track */
if (lsn > cdio_get_track_lsn(p_cdio, CDIO_CDROM_LEADOUT_TRACK))
return CDIO_INVALID_TRACK; /* We're beyond the end. */
do {
const track_t i_mid = (i_low_track + i_high_track) / 2;
const lsn_t i_mid_lsn = cdio_get_track_lsn(p_cdio, i_mid);
if (lsn <= i_mid_lsn) i_high_track = i_mid - 1;
if (lsn >= i_mid_lsn) i_low_track = i_mid + 1;
} while ( i_low_track <= i_high_track );
if (i_low_track > i_high_track + 1) {
i_high_track++;
}
if (i_high_track == i_lead_track ) {
return CDIO_CDROM_LEADOUT_TRACK;
} else {
return i_high_track;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.