language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mini_sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: asipes <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/20 17:17:10 by asipes #+# #+# */
/* Updated: 2019/07/20 17:18:51 by asipes ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void mini_sort(t_push *ds)
{
if (ds->size_a == 2)
duo_sort(ds);
else if (ds->size_a == 3)
trio_sort(ds);
else if (ds->size_a == 4)
quadro_sort(ds);
else
penta_sort(ds);
}
void duo_sort(t_push *ds)
{
if (ds->a_beg->ord != 1)
SA;
}
void trio_sort(t_push *ds)
{
if (FIRST < SECOND)
{
if (FIRST < THIRD && SECOND > THIRD)
{
SA;
RA;
}
else if (FIRST > THIRD)
{
RRA;
}
}
else if (FIRST > SECOND)
{
if (FIRST < THIRD)
SA;
else if (FIRST > THIRD && SECOND < THIRD)
RA;
else if (FIRST > THIRD && SECOND > THIRD)
{
SA;
RRA;
}
}
}
void quadro_sort(t_push *ds)
{
search_max(ds);
if (ds->i > 1)
{
while (ds->a_beg->ord != 1)
RA;
}
else
{
while (ds->a_beg->ord != 1)
{
RRA;
}
}
PB;
trio_sort(ds);
PA;
}
void penta_sort(t_push *ds)
{
ds->i = 2;
while (ds->i > 0)
{
if (ds->a_beg->ord < 3)
{
PB;
ds->i--;
}
else
RA;
}
trio_sort(ds);
if (ds->b_beg->ord == 1)
SB;
PA;
PA;
}
|
C
|
/* 뒤에서 k번째 노드는 무엇일까요?
[지시문]
연결리스트의 응용 문제
연결리스트가 하나 주어졋을 때 해당 연결 리스트의 뒤에서 k번째 노드의 값을 출력
연결리스트는 이미 만들어져 있다고 가정 */
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* next;
} Node;
void append(Node* head, int data)
{
Node* node = (Node*)malloc(sizeof(node));
node->data = data;
node->next = NULL;
while (head->next != NULL)
{
head = head->next;
}
head->next = node;
}
int getLastNode(Node* head, int k)
{
int size = 0;
int result = 0;
Node* pt = head;
while (pt->next != NULL)
{
size += sizeof(head);
pt = pt->next;
}
int count = size/sizeof(head);
while (head->next != NULL)
{
head = head->next;
if (k == count)
{
result = head->data;
break;
}
count--;
}
return result;
}
void printList(Node* head)
{
while (head->next != NULL)
{
head = head->next;
printf("%d ", head->data);
}
printf("\n");
}
int main(void)
{
Node* head = (Node*)malloc(sizeof(Node));
append(head, 9);
append(head, 8);
append(head, 4);
append(head, 14);
append(head, 5);
printList(head);
printf("%dth last node is %d\n", 2, getLastNode(head, 2));
}
|
C
|
#include "stdlib.h"
struct ListNode {
int val;
struct ListNode *next;
};
// a' + c + b' == b' + c + a'
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode* p1 = pHead1;
struct ListNode* p2 = pHead2;
while (p1 != p2) {
if (p1 == NULL)
p1 = pHead2;
else
p1 = p1->next;
if (p2 == NULL)
p2 = pHead1;
else
p2 = p2->next;
}
return p1;
}
|
C
|
#include <stdio.h>
int argumentLength(int arg) {
int argLength = 1;
while (arg / 10 > 0) {
argLength++;
arg /= 10;
}
return argLength;
}
void outputFraction(int numerator, int denomerator) {
printf("%i\n--\n", numerator);
printf("%i\n", denomerator);
}
void outputReciprocalFraction(int numerator, int denomerator) {
printf("%i\n--\n", denomerator);
printf("%i\n", numerator);
}
int selectAction(int numerator, int denomerator) {
int choice = 0;
printf("Select your action (1 - output fraction, 2 - output decimal fraction, 3 - output num in sciencific, 4 - output reciprocal fraction, 5 - output reciprocal decimal fractionr, 6 - reciprocal scientific notation\n, 7 - information about developer and version\n");
scanf_s("%d", &choice);
if (choice < 0 || choice > 7) {
printf("You tryed to enter wrong value");
exit();
}
switch (choice) {
case 1:
outputFraction(numerator, denomerator);
break;
case 2:
printf("%f\n", (float)numerator / (float)denomerator);
break;
case 3:
printf("%e\n", (float)numerator / (float)denomerator);
break;
case 4:
outputReciprocalFraction(numerator, denomerator);
break;
case 5:
printf("%f\n", (float)denomerator / (float)numerator);
break;
case 6:
printf("%e\n", (float)denomerator / (float)numerator);
break;
case 7:
printf("Developed by Freasy\nVersion 1.54\n");
break;
default:
printf(" ");
break;
return 0;
}
return 1;
}
int main() {
int numerator = 0, denomerator = 0, choice = 0, action = 0;
printf("Please enter numerator for rational fraction\n");
scanf_s("%i", &numerator);
printf("Please enter denomerator for rational fraction\n");
scanf_s("%i", &denomerator);
printf("Numerator = %i\n", numerator);
printf("denomerator = %i\n", denomerator);
action = selectAction(numerator, denomerator);
while (action) {
action = selectAction(numerator, denomerator);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
float freq;
int leaf;
char ch;
struct node *left,*right;
}Node;
Node** sort(Node** nodes,int n)
{
int i,j;
for (i = 0; i < n; ++i)
for(j=0;j<n-1-i;j++)
if(nodes[j]->freq>nodes[j+1]->freq)
{
Node* n =nodes[j];
nodes[j] = nodes[j+1];
nodes[j+1] = n;
}
return nodes;
}
Node* HuffmanCodes(Node** nodes,int n)
{
int i;
for(i=0;i<n-1;i+=2)
{
Node* new = (Node*)malloc(sizeof(Node));
new->left = nodes[i];
new->right = nodes[i+1];
new->leaf = 0;
new->freq = nodes[i]->freq+nodes[i+1]->freq;
nodes[n] = new;
n++;
nodes = sort(nodes,n);
}
return nodes[n-1];
}
int printCodes(Node* tree,int arr[],int i)
{
if(tree->leaf == 1)
{
printf("%c-->",tree->ch);
int k;
for(k=0;k<i;k++)
printf("%d",arr[k]);
printf("\n");
}
else
{
arr[i]=0;
printCodes(tree->left,arr,i+1);
arr[i]=1;
printCodes(tree->right,arr,i+1);
}
}
int main()
{
int n,i,j;
printf("Input size of alphabet: ");scanf("%d",&n);
Node** nodes = (Node**) calloc(n*n,sizeof(Node*));
printf("Input alphabet\n");
for(i=0;i<n;i++)
{
nodes[i]=(Node*)malloc(sizeof(Node));
scanf(" %c",&(nodes[i]->ch));
}
printf("Input frequencies\n");
for(i=0;i<n;i++)
{
scanf("%f",&(nodes[i]->freq));
nodes[i]->leaf = 1;
}
//sort
nodes = sort(nodes,n);
Node* tree = HuffmanCodes(nodes,n);
int* arr = (int*)calloc(n*n,sizeof(int));
printCodes(tree,arr,0);
return 0;
}
|
C
|
#include <stdio.h>
int gcd2nums(int p, int q) {
if (0 == p) {
return q;
}
return gcd2nums(q % p, p);
}
int gcdnnums(int *arr, int n) {
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = gcd2nums(arr[i], gcd);
}
return gcd;
}
int lcm2nums(int p, int q) {
return (p * q) / gcd2nums(p, q);
}
int lcmnnums(int *arr, int n) {
int lcm = arr[0];
for (int i = 1; i < n; i++) {
lcm = lcm2nums(arr[i], lcm);
}
return lcm;
}
int main() {
int n;
int m;
scanf("%d %d", &n, &m);
int a[n];
for(int a_i = 0; a_i < n; a_i++){
scanf("%d", &a[a_i]);
}
int b[m];
for(int b_i = 0; b_i < m; b_i++){
scanf("%d", &b[b_i]);
}
int x = lcmnnums(a, n);
int y = gcdnnums(b, m);
int count = 0;
for (int i = x, j = 2; i <= y; i = x * j, j++) {
if (0 == (y % i)) {
count++;
}
}
printf("%d", count);
return 0;
}
|
C
|
#include <stdio.h>
void removeString(char string[], int start, int count)
{
int i;
for (i = 0; string[i] != '\0'; ++i)
{
if (i >= start)
string[i] = string[i + count];
}
string[i + 1] = '\0';
}
int main(void)
{
char txt[10] = "what ever";
removeString(txt, 3, 3);
printf("%s\n", txt);
}
|
C
|
#include<stdio.h>
void main()
{
int n1,n2;
printf("Enter First Number : ");
scanf("%d",&n1);
while(n1<0)
{
printf("Please Enter Positive Value : ");
scanf("%d",&n1);
}
printf("Enter Second Number : ");
scanf("%d",&n2);
while(n2<0)
{
printf("Please Enter Positive Value : ");
scanf("%d",&n2);
}
printf("%d + %d = %d",n1,n2,(n1+n2));
}
|
C
|
#include<stdio.h>
void bubble(int arr[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
void main()
{
int arr[100],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter the elements:");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
bubble(arr,n);
for(i=0;i<n;i++)
printf("%d ",arr[i]);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS –
#pragma once
#include "pa-1.h"
#include <stdio.h>
// "pa-1.c"
int main()
{
//Declaring an array
int list[3];
//Declaring variables
int n = 0;
int x = 0;
int r = 0;
int y = 0;
int z = 0;
int rotateNum = 0;
int searchRecur = 0;
int collatzNum = 0;
int average = 0;
bool results;
char brackets[1000];
char lookFor[1000];
char paragraph[1000];
char fString[1000];
char sString[1000];
char *e[1000];
char *pattern[1000];
char *text[1000];
char *s1[1000];
char *s2[1000];
char *s3[1000];
//Function 1
//Will see if input is an armstrong number
printf("Enter a number to check if it's an armstrong number: ");
scanf("%d", &n);
results = f_armstrong(n);
if (results == true)
{
printf("%d is an armstrong number", n);
}
else
{
printf("%d is not an armstrong number", n);
}
//Function 2
//Will see if brackets are balanced
printf("\n\nEnter brackets and the program will check to see if they are in order: ");
scanf("%s", &brackets);
results = f_brackets(brackets);
if (results == true)
{
printf("Your brackets are in order");
}
else
{
printf("Your brackets are not in order");
}
//Function 3
//Will see if input is a perfect number
printf("\n\nEnter a number and the program will check to see if it's a perfect number: ");
scanf("%d", &x);
results = f_perfect(x);
if (results == true)
{
printf("%d is a perfect number", x);
}
else
{
printf("%d is not a perfect number", x);
}
//Function 4
//Will rotate input by a number that is also given
printf("\n\nEnter a number that you want to rotate its digits: ");
scanf("%d", &n);
printf("Enter a number that you want to rotate by: ");
scanf("%d", &r);
rotateNum = f_rotate(n, r);
printf("\nThe new number is: %d", rotateNum);
//Funtction 5
//Will search for a pattern in a text
printf("\n\nEnter a pattern you want to search for: ");
scanf("%s", &lookFor);
printf("Enter a text you want to search through: ");
scanf("%s", ¶graph);
searchRecur = f_str_search(lookFor, paragraph);
printf("%s can be found in your text %d times", lookFor, searchRecur);
//Funtction 6
//Will perform the Collatz conjucture on input
printf("\n\nEnter a number for the program to perform the Collatz conjucture to: ");
scanf("%d", &n);
collatzNum = f_collatz_count(n);
printf("It took %d iterations", collatzNum);
//Funtction 7
//This function will take a number and create an array with the amount and perform other operation
printf("\n\nEnter a number to determine how many random numbers are generated: ");
scanf("%d", &n);
average = f_array(n);
printf("The numbers were randomly generated between 1-99 and multiplied by 2. The following number is the average of the (up to 5) numbers divisible by 3: %d", average);
//Funtction 8
//This function will take two strings and put them into one, in shorter/larger/shorter order
printf("\n\nEnter the first text you want to forge with: ");
scanf("%s", &fString);
printf("\nEnter the second text you want to forge with: ");
scanf("%s", &sString);
f_strings(fString, sString, s3);
printf("Your new string is: %s", s3);
//Function 9
//This will take three numbers and sort them in order
printf("\n\nThe program will now take three numbers and sort them in assending order. Enter the first number: ");
scanf("%d", &x);
printf("Enter the second number: ");
scanf("%d", &y);
printf("Enter the third number: ");
scanf("%d", &z);
f_sort(x, y, z, list);
printf("The numbers in order are: %d %d %d", list[0], list[1], list[2]);
//Funtction 10
//This will look for a set of numbers that equate to the input, when cubed
printf("\n\nEnter a number and the program will see if a set of numbers cubed will equate to it: ");
scanf("%d", &n);
int *twoValues = f_cubed_sum(n);
if (twoValues)
{
printf("The two values are: %d and %d", twoValues[0], twoValues[1]);
}
else
{
printf("There is no pair of integers that satasfy the formula");
}
free(twoValues);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{int x, y;
float price;
printf("[1] crisps\n");
printf("[2] popcorn\n");
printf("[3] chocolate\n");
printf("[4] cola\n");
printf("[0] exit\n");
for(x=1;x<=5;x++) {
scanf("%d",&y);
if(y==0) break;
switch(y){
case 1:price = 3.0;break;
case 2:price = 2.5;break;
case 3:price = 4.0;break;
case 4:price = 3.5;break;
default:price = 0.0;break;
}
printf("price = %.1f\n",price);
}
printf("Thanks\n");
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
int r;
double area;
scanf("%d",&r);
area=3.1416*pow(r,2);
printf("Area is %lf\n",area);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** settings_move_vol_cursor.c
** File description:
** settings_move_vol_cursor
*/
#include "my_world.h"
void set_volume_up(global_game_t *global_game)
{
int size_scrollbar = global_game->settings->scroll_bar->size.x - 30;
if (global_game->settings->cursor->pos.x < \
global_game->settings->scroll_bar->pos.x + size_scrollbar) {
global_game->settings->cursor->pos.x += 10;
sfRectangleShape_setPosition(global_game->settings->cursor->rect, \
global_game->settings->cursor->pos);
global_game->set->volume += 2;
sfMusic_setVolume(global_game->set->music, global_game->set->volume);
}
}
void set_volume_down(global_game_t *global_game)
{
if (global_game->settings->cursor->pos.x > \
global_game->settings->scroll_bar->pos.x) {
global_game->settings->cursor->pos.x -= 10;
sfRectangleShape_setPosition(global_game->settings->cursor->rect, \
global_game->settings->cursor->pos);
global_game->set->volume -= 2;
sfMusic_setVolume(global_game->set->music, global_game->set->volume);
}
}
void up_cursor(global_game_t *global_game)
{
int pos_x = global_game->settings->plus->pos.x;
int pos_y = global_game->settings->plus->pos.y;
int size_x = pos_x + global_game->settings->plus->size.x;
int size_y = pos_y + global_game->settings->plus->size.y;
if (global_game->set->event.mouseButton.x > pos_x && \
global_game->set->event.mouseButton.x < size_x) {
if (global_game->set->event.mouseButton.y > pos_y && \
global_game->set->event.mouseButton.y < size_y) {
set_volume_up(global_game);
play_sound_effect(global_game->set);
}
if (global_game->set->error == 1)
return;
}
}
void down_cursor(global_game_t *global_game)
{
int pos_x = global_game->settings->sub->pos.x;
int pos_y = global_game->settings->sub->pos.y;
int size_x = pos_x + global_game->settings->sub->size.x;
int size_y = pos_y + global_game->settings->sub->size.y;
if (global_game->set->event.mouseButton.x > pos_x && \
global_game->set->event.mouseButton.x < size_x) {
if (global_game->set->event.mouseButton.y > pos_y && \
global_game->set->event.mouseButton.y < size_y) {
set_volume_down(global_game);
play_sound_effect(global_game->set);
}
if (global_game->set->error == 1)
return;
}
}
void settings_move_vol_cursor(global_game_t *global_game)
{
up_cursor(global_game);
if (global_game->set->error == 1)
return;
down_cursor(global_game);
if (global_game->set->error == 1)
return;
is_button_hover(global_game, global_game->settings->plus, \
global_game->set->mouse_pos, sfRed);
is_button_hover(global_game, global_game->settings->sub, \
global_game->set->mouse_pos, sfRed);
is_button_hover(global_game, global_game->settings->framerate_30_button, \
global_game->set->mouse_pos, sfRed);
is_button_hover(global_game, global_game->settings->framerate_45_button, \
global_game->set->mouse_pos, sfRed);
is_button_hover(global_game, global_game->settings->framerate_60_button, \
global_game->set->mouse_pos, sfRed);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
typedef int wchar_t ;
typedef int uint8_t ;
typedef int /*<<< orphan*/ mbstate_t ;
struct TYPE_2__ {scalar_t__ want; } ;
typedef TYPE_1__ _EucState ;
/* Variables and functions */
int /*<<< orphan*/ EILSEQ ;
int /*<<< orphan*/ EINVAL ;
int MB_CUR_MAX ;
int /*<<< orphan*/ errno ;
__attribute__((used)) static size_t
_EUC_wcrtomb_impl(char * __restrict s, wchar_t wc,
mbstate_t * __restrict ps,
uint8_t cs2, uint8_t cs2width, uint8_t cs3, uint8_t cs3width)
{
_EucState *es;
int i, len;
wchar_t nm;
es = (_EucState *)ps;
if (es->want != 0) {
errno = EINVAL;
return ((size_t)-1);
}
if (s == NULL)
/* Reset to initial shift state (no-op) */
return (1);
if ((wc & ~0x7f) == 0) {
/* Fast path for plain ASCII (CS0) */
*s = (char)wc;
return (1);
}
/* Determine the "length" */
if ((unsigned)wc > 0xffffff) {
len = 4;
} else if ((unsigned)wc > 0xffff) {
len = 3;
} else if ((unsigned)wc > 0xff) {
len = 2;
} else {
len = 1;
}
if (len > MB_CUR_MAX) {
errno = EILSEQ;
return ((size_t)-1);
}
/* This first check excludes CS1, which is implicitly valid. */
if ((wc < 0xa100) || (wc > 0xffff)) {
/* Check for valid CS2 or CS3 */
nm = (wc >> ((len - 1) * 8));
if (nm == cs2) {
if (len != cs2width) {
errno = EILSEQ;
return ((size_t)-1);
}
} else if (nm == cs3) {
if (len != cs3width) {
errno = EILSEQ;
return ((size_t)-1);
}
} else {
errno = EILSEQ;
return ((size_t)-1);
}
}
/* Stash the bytes, least significant last */
for (i = len - 1; i >= 0; i--) {
s[i] = (wc & 0xff);
wc >>= 8;
}
return (len);
}
|
C
|
#ifndef __LIST_H__
#define __LIST_H__
struct list {
struct list *prev, *next;
};
static inline int list_empty(struct list *l)
{
return l->next == l;
}
static inline void list_init(struct list *n)
{
n->next = n;
n->prev = n;
}
static inline void list_del(struct list *n)
{
n->next->prev = n->prev;
n->prev->next = n->next;
}
static inline void list_add(struct list *l, struct list *n)
{
n->next = l->next;
n->next->prev = n;
l->next = n;
n->prev = l;
}
#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define list_foreach_safe(type, e, list_head, member) do {\
struct list *__l; \
struct list *__next; \
for (__l = ((list_head)->next); __l != (list_head); __l = __next) { \
__next = __l->next; \
type *e = container_of(__l, type, member);
#define list_foreach(type, e, list_head, member) do {\
struct list *__l; \
for (__l = ((list_head)->next); __l != (list_head); __l = __l->next) { \
type *e = container_of(__l, type, member);
#define end_list_foreach } } while (0);
#endif /* __LIST_H__ */
|
C
|
int ch2int(char ch){
switch(ch){
case 'I':return 1;
case 'V':return 5;
case 'X':return 10;
case 'L':return 50;
case 'C':return 100;
case 'D':return 500;
case 'M':return 1000;
}
return 0;
}
int romanToInt(char* s) {
int length = strlen(s);
if (length == 0){
return 0;
}
int index = 0;
char ch = s[index];
int result = ch2int(ch);
if (length == 1){
return result;
}
for(index = 1; index < length; index++){
ch = s[index];
result += ch2int(ch);
if (ch2int(s[index]) > ch2int(s[index-1])){
result -= ch2int(s[index-1])*2;
}
}
return result;
}
|
C
|
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define BUF_SIZE 40
int main(void) {
struct passwd *pw;
struct group *prim_grp, *secondary_grp;
pw = getpwnam("syspro");
prim_grp = getgrgid(pw->pw_gid);
printf("Primary Group\n%s\n", prim_grp->gr_name);
printf("\n");
printf("Secondary Groups\n");
while ((secondary_grp = getgrent()) != NULL) {
int m_idx = 0;
while (secondary_grp->gr_mem[m_idx] != NULL) {
if (strcmp(secondary_grp->gr_mem[m_idx], pw->pw_name) == 0) {
printf("%s ", secondary_grp->gr_name);
printf("\n");
}
m_idx++;
}
}
return 0;
}
|
C
|
/* Project Name: Ana Process Explorer
* Written By : Ahmad Siavashi -> Email: [email protected],
* Ali Kianinejad -> Email: [email protected],
* Farid Amiri,
* Mohammad Javad Moein.
* Course Title: Principles of Programming.
* Instructor : Dr. Ali Hamze.
* T.A : Mr. Hojat Doulabi.
* Shiraz University, Shiraz, Iran.
* Spring 1391, 2012.
*/
#include <Windows.h>
#include <stdio.h>
#include "AnaMainHeader.h"
#include "DrawTools.h"
/////////////////////////////////////////////////////////////////////////////////////
#define COLUMN_WIDTH 7
#define DISTANCE_BETWEEN_GRAPH_COLUMNS 0
#define MAX_NUMBER_OF_COLUMN 25
#define PERECENTAGE_LEN 5
/////////////////////////////////////////////////////////////////////////////////////
// Graph Dimensions info.
static INT GraphInfo[MAX_NUMBER_OF_COLUMN][2]={{-1,0},{-1,1},{-1,0},{-1,1},{-1,0},{-1,1},{-1,0},{-1,1},{-1,0},{-1,1},{-1,0},{-1,1},
{-1,0},{-1,1},{-1,0},{-1,1},{-1,0},{-1,1},{-1,1},{-1,0},{-1,1},{-1,0},{-1,1},{-1,0},{-1,1}};
static INT StatusHistory=0;
INT Color[6]={BACKGROUND_GREEN|BACKGROUND_BLUE|BACKGROUND_INTENSITY , BACKGROUND_GREEN | BACKGROUND_BLUE ,
BACKGROUND_GREEN |BACKGROUND_INTENSITY, BACKGROUND_GREEN,
BACKGROUND_RED |BACKGROUND_INTENSITY,BACKGROUND_RED};
INT MaxPossibleGraphColumns;
INT Ratio;
/////////////////////////////////////////////////////////////////////////////////////
VOID PaintRegion(INT Top,INT Bottom,INT Left,INT Right,INT color){
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
SMALL_RECT srctScrollRect, srctClipRect;
CHAR_INFO chiFill;
COORD coordDest;
// Get the screen buffer size.
GetConsoleScreenBufferInfo(hConsole, &csbiInfo);
// The scrolling rectangle is the bottom 15 rows of the
// screen buffer.
srctScrollRect.Top = Top;
srctScrollRect.Bottom = Bottom;
srctScrollRect.Left = Left;
srctScrollRect.Right = Right;
// The destination for the scroll rectangle is one row up.
coordDest.X = 0;
coordDest.Y = csbiInfo.dwSize.Y + 100;
// The clipping rectangle is the same as the scrolling rectangle.
// The destination row is left unchanged.
srctClipRect = srctScrollRect;
// Fill the bottom row with green blanks.
chiFill.Attributes = color;
chiFill.Char.UnicodeChar = (WCHAR)' ';
// Scroll up one line.
WaitForSingleObject(hScreenMutex,INFINITE);
ScrollConsoleScreenBuffer(hConsole, &srctScrollRect,&srctClipRect,coordDest,&chiFill);
ReleaseMutex(hScreenMutex);
}
INT EvaluatePosition(INT Right,INT n){
//position =end of box - ((size of colm + distance between col)*(n+1)
return Right -((COLUMN_WIDTH + DISTANCE_BETWEEN_GRAPH_COLUMNS)*(n+1));
}
VOID HorizontalBlankXYCount(INT x,INT y,INT Num,INT CurrentColm){
INT i;
WaitForSingleObject(hScreenMutex,INFINITE);
for(i=0;i<Num;i++)
PrintXY(BLANK,x+i,y);
ReleaseMutex(hScreenMutex);
}
VOID DrawOneColumn(INT Top,INT x,INT y,INT num,INT CurrentColm){
INT i;
for(i=0;i<num;i++)
if((y-i)>=Top)
HorizontalBlankXYCount(x,y-i,COLUMN_WIDTH,CurrentColm);
}
VOID DrawAllColumns(INT Top,INT Right,INT Bottom,INT MaxPossibleGraphColumns,INT Status){
INT i;
for(i=0;i<MaxPossibleGraphColumns;i++){
if (GraphInfo[i][0]!=-1){
switch (Status){
case 0:
if (GraphInfo[i][1])
SetConsoleTextAttribute(hConsole,Color[0]);
else
SetConsoleTextAttribute(hConsole,Color[1]);
break;
case 1:
if (GraphInfo[i][1])
SetConsoleTextAttribute(hConsole,Color[2]);
else
SetConsoleTextAttribute(hConsole,Color[3]);
break;
case 2:
if (GraphInfo[i][1])
SetConsoleTextAttribute(hConsole,Color[4]);
else
SetConsoleTextAttribute(hConsole,Color[5]);
break;
}
if (GraphInfo[i][0]/Ratio==0)
DrawOneColumn(Top,EvaluatePosition(Right,i),Bottom,1,i);
else
DrawOneColumn(Top,EvaluatePosition(Right,i),Bottom,GraphInfo[i][0]/Ratio,i);
}
SetConsoleTextAttribute(hConsole,REGULAR_COLOR);
}
}
VOID SetInfo(INT Top,INT Bottom,INT Right,INT Left,SIZE_T Percentage){
INT i,j;
MaxPossibleGraphColumns=(Right - Left - DISTANCE_BETWEEN_GRAPH_COLUMNS)/(COLUMN_WIDTH + DISTANCE_BETWEEN_GRAPH_COLUMNS);
for(i=MaxPossibleGraphColumns;i>0;i--)
for(j=0;j<2;j++)
GraphInfo[i][j]=GraphInfo[i-1][j];
GraphInfo[0][0]=Percentage;
if (GraphInfo[1][1]==0)
GraphInfo[0][1]=1;
else
GraphInfo[0][1]=0;
Ratio = 100/(Bottom - Top - 1);
}
VOID ClsGraphColumns(INT Top,INT Right,INT Bottom,INT MaxPossibleGraphColumns){
INT i;
WaitForSingleObject(hScreenMutex,INFINITE);
for(i=0;i<MaxPossibleGraphColumns;i++){
if (GraphInfo[i][0]!=-1){
SetConsoleTextAttribute(hConsole,REGULAR_COLOR);
if (GraphInfo[i][0]/Ratio==0)
DrawOneColumn(Top,EvaluatePosition(Right,i),Bottom,1,i);
else
DrawOneColumn(Top,EvaluatePosition(Right,i),Bottom,GraphInfo[i][0]/Ratio,i);
}
SetConsoleTextAttribute(hConsole,REGULAR_COLOR);
}
ReleaseMutex(hScreenMutex);
}
VOID EvacuateGraphHistory(VOID){
INT i;
for(i=0;i<MAX_NUMBER_OF_COLUMN;i++){
GraphInfo[i][0]=-1;
GraphInfo[i][1]=0;
}
}
VOID GraphStaticPart(INT Top,INT Bottom,INT Left){
WaitForSingleObject(hScreenMutex,INFINITE);
PrintXY(TEXT("100%%"),Left,Top);
PrintXY(TEXT("0 %%"),Left,Bottom);
PrintXY(TEXT("50 %%"),Left,(Bottom+Top)/2);
if ((((Bottom+Top)/2)+Bottom)/2-(Bottom+Top)/2>6){
PrintXY(TEXT("75 %%"),Left,(((Bottom+Top)/2)+Top)/2);
PrintXY(TEXT("25 %%"),Left,(((Bottom+Top)/2)+Bottom)/2);
}
ReleaseMutex(hScreenMutex);
}
VOID DrawGraph(INT Top,INT Bottom,INT Left,INT Right,SIZE_T Percentage,INT Status){
GraphStaticPart(Top,Bottom,Left);
PaintRegion(Top,Bottom,Left + PERECENTAGE_LEN,Right,REGULAR_COLOR);
SetInfo(Top,Bottom,Right,Left + PERECENTAGE_LEN,Percentage);
if (Ratio>0) DrawAllColumns(Top,Right,Bottom,MaxPossibleGraphColumns,Status);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int is_number(char s[])
{
int i = 0;
for (; s[i] != '\0'; i++)
{
if (isdigit(s[i]) == 0)
{
return 0;
}
}
return 1;
}
int main(int argc, char *argv[])
{
// If there is no argument, or multiple keys were given, or the key was not a number, print usage and exit
if (argc != 2 || is_number(argv[1]) == 0)
{
printf("Usage: ./caesar key\n");
return 1;
}
// If the key is negative, print usage and exit
int key = atoi(argv[1]) % 26;
if (key < 0)
{
printf("Usage: ./caesar key\n");
return 1;
}
// Get plaintext from user
printf("plaintext: ");
char plain[1024];
scanf("%[^\n]%*c", plain);
int txtlen = strlen(plain);
// Print ciphertext encrypted using key
printf("ciphertext: ");
for (int i = 0; i < txtlen; i++)
{
if (isalpha(plain[i]))
{
if (isupper(plain[i]))
{
printf("%c", ((plain[i] - 'A' + key) % 26) + 'A');
}
else
{
printf("%c", ((plain[i] - 'a' + key) % 26) + 'a');
}
}
else
{
printf("%c", plain[i]);
}
}
printf("\n");
}
|
C
|
/*
If the lengths of the sides of a triangle are denoted by a, b, and c, then area
of triangle is given by
area=sqrt(S(s-a)(s-b)(s-c))
where, S = ( a + b + c ) / 2
*/
#include<stdio.h>
#include<math.h>
int areat(int a, int b, int c)
{
int s,area;
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
return(area);
}
int main()
{
int areat(int, int, int);
int x,y,z,t;
printf("\n Enter the three sides of the triangle");
scanf("%d%d%d",&x,&y,&z);
t=areat(x,y,z);
printf("The area of the triangle is %d\n",t);
}
|
C
|
#include"iostream.h"
int main()
{
int a,s,l,b;
cout"enter length and breath"
cin>>l;
cin>>b;
a=l*b;
s=2*(l+b);
cout<<a<<s<<endl;
}
|
C
|
/*
* UART.c
*
* Description: Source file for the UART AVR driver
* Created on: Jan 29, 2020
* Author: Mostafa Alaa
*/
#include "UART.h"
#include "Config/UART_Config.h"
#define BAUD_PRESCALE (((F_CPU / (UART_BAUDRATE * 8UL))) - 1)
/*****************************************************
* Functions Definitions *
*****************************************************/
void UART_init(const UartCommType type)
{
/* U2X = 1 for double transmission speed */
UCSRA = (1<<U2X);
/************************** UCSRB Description **************************
* RXCIE = 0 Disable USART RX Complete Interrupt Enable
* TXCIE = 0 Disable USART Tx Complete Interrupt Enable
* UDRIE = 0 Disable USART Data Register Empty Interrupt Enable
* RXEN = 1 Receiver Enable
* RXEN = 1 Transmitter Enable
* UCSZ2 = 0 For 8-bit data mode
* RXB8 & TXB8 not used for 8-bit data mode
***********************************************************************/
if(type == Full_Duplex)
{
UCSRB = (1<<RXEN) | (1<<TXEN);
}
else if(type == Transmitter)
{
SET_BIT(UCSRB, TXEN);
}
else
{
SET_BIT(UCSRB, RXEN);
}
/************************** UCSRC Description **************************
* URSEL = 1 The URSEL must be one when writing the UCSRC
* UMSEL = 0 Asynchronous Operation
* UPM1:0 = 00 Disable parity bit
* USBS = 0 One stop bit
* UCSZ1:0 = 11 For 8-bit data mode
* UCPOL = 0 Used with the Synchronous operation only
***********************************************************************/
UCSRC = (1<<URSEL) | (1<<UCSZ0) | (1<<UCSZ1);
/*
* First 8 bits from the BAUD_PRESCALE inside UBRRL
* last 4 bits in UBRRH
*/
CLEAR_BIT(UBRRH, URSEL);
UBRRH = BAUD_PRESCALE>>8;
UBRRL = BAUD_PRESCALE;
}
void UART_sendByte(const uint8 data)
{
/*
* Polling till Tx buffer (UDR) is empty and ready
* for transmitting a new byte
*/
while(BIT_IS_CLEAR(UCSRA,UDRE)){}
/* Put the required data in the UDR register */
UDR = data;
}
uint8 UART_recieveByte(void)
{
/* Polling till UART receive data */
while(BIT_IS_CLEAR(UCSRA,RXC)){}
/* Return the received data from the Rx buffer (UDR) */
return UDR;
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, char **argv) {
srand(time(NULL));
int n = rand() - RAND_MAX / 2;
printf("n = %d\n", n);
if (n > 0) {
int i;
i = 0;
printf("Inside \"if\", i = %d\n", i);
}
else {
int i;
i = 127;
printf("Inside \"else\", i = %d\n", i);
}
int i;
i = -128;
printf("Outside \"if...else\", i = %d\n", i);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_uitoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cado-car <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/12 17:59:03 by cado-car #+# #+# */
/* Updated: 2021/08/12 21:45:48 by cado-car ### ########lyon.fr */
/* */
/* ************************************************************************** */
/*
* DESCRIPTION
* The uitoa_base() converts an unsigned integer into a string, passing it to
* the base given as an argument.
* PARAMETERS
* #1. The unsigned long to convert.
* #2. The base in which to convert the number to.
* RETURN VALUES
* The string representing the converted number.
*/
#include "libft.h"
static size_t ft_countsize(unsigned long n, size_t len_base);
static void ft_convbase(unsigned long nbr, char *num, char *base, size_t i);
char *ft_uitoa_base(unsigned long nbr, char *base)
{
size_t len_nbr;
size_t len_base;
char *number;
len_base = ft_strlen(base);
len_nbr = ft_countsize(nbr, len_base);
number = malloc((len_nbr + 1) * sizeof(char));
if (!number)
return (NULL);
number[len_nbr--] = '\0';
ft_convbase(nbr, number, base, len_nbr);
return (number);
}
// recursively count long size
static size_t ft_countsize(unsigned long n, size_t len_base)
{
if ((n / len_base) == 0)
return (1);
else
return (1 + ft_countsize(n / len_base, len_base));
}
// recursively convert long to string
static void ft_convbase(unsigned long nbr, char *num, char *base, size_t i)
{
size_t len_base;
len_base = ft_strlen(base);
if (nbr >= (unsigned long int)len_base)
ft_convbase((nbr / len_base), num, base, (i - 1));
num[i] = base[nbr % len_base];
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int *soma (int *v1, int *v2, int x){ //Função para a soma dos vetores
int i;
int *v3 = malloc(x * sizeof(int));
for(i=0; i<x; i++){
v3[i] = v1[i] + v2[i];
}
free(v2);
free(v1);
return v3;
}
int vcont (int t1, int t2){ //Função para a contagem dos elementos dos vetores
int i;
int x;
if(t1 > t2){
x = t1;
} else{
x = t2;
}
int *v1 = malloc(x * sizeof(int));
int *v2 = malloc(x * sizeof(int));
for(i=0; i<x; i++){
v1[i] = 0;
v2[i] = 0;
}
for(i=0; i<t1; i++){
printf("Informe o elemento %d do vetor 1: ", i + 1);
scanf("%d", &v1[i]);
}
for(i=0; i<t2; i++){
printf("Informe o elemento %d do vetor 2: ", i + 1);
scanf("\n %d", &v2[i]);
}
return soma(v1, v2, x);
}
int main (){ //Função principal
int t1, t2;
int i;
printf("Informe o tamanho do vetor 1: ");
scanf("%d", &t1);
printf("\n");
printf("Informe o tamanho do vetor 2: ");
scanf("%d", &t2);
printf("\n");
int *v3 = vcont(t1, t2);
for(i=0; v3[i]; i++){
printf9("%d", v3[i]);
}
free(v3);
return 0;
}
|
C
|
// 소리 파일 저장용량 계산하기
#include <stdio.h>
int main() {
long long int h, b, c, s; // 가장 큰 정수형
double mb;
scanf ("%lld %lld %lld %lld", &h, &b, &c, &s);
mb = h * b * c * s;
mb = mb / 8 / 1024 / 1024; // MB 값으로 변환
printf ("%.1lf MB", mb);
return 0;
}
|
C
|
/*
* Advanced Calculator
*
* This is a quick and dirty ncurses based calculator written
* as practice to brush up on C. This will also be used as
* a program for to port to as many languages as cared.
*
* Author: Cameron Roy
* Date Begun: 2020/12/31
* Date Completed:
*
*/
//Libraries included
#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
//Global variables
//Genuinely simple addition functions, move down later
long addition(long a,long b) {
return a + b;
}
double Daddition(double a, double b) {
return a + b;
}
//Prototyping functions area
//Binary
long DtoB(long x);
int BtoD(int x);
//Hexadecimal
int HtoD(char x[]);
char DtoH(int x);
//Octal Numbering
int main(void){
//For testing, just runs the BtoD loop with the value in brackets.
printf("Binary to Decimal: %d\n", BtoD(1010));
char Array[8] = {"0","0","0","0","0","0","0","0"};
//printf("Hexadecimal to Decmial: %d\n", HtoD(char *Array));
HtoD(*Array);
//Setting up various ncurses stuff for the window
/*
initscr();
clear();
curs_set(TRUE);
cbreak();
noecho();
timeout(1);
//Screen space related variables
int xMax, yMax;
getmaxyx(stdscr, yMax, xMax);
mvprintw(2,2, "weed");
refresh();
usleep(50000);
*/
return 0;
}
/*
* This is a loop that converts a base 2 number into a base 10 number.
* Currently 16bit, but will be expanded to up to 64 bit, as
* anymore than 64bit doesnt really make sense as current
* processors are only 64bit anyways.
*/
int BtoD(int x) {
//Variable declaration area
int bArray[16];
int dArray[16];
int binaryNum = x;
int buffer, power;
//This section basically reverses the binary number
for(int i=0;i>=0 && i<16;i++){
bArray[i] = binaryNum % 10;
binaryNum /= 10;
//Only here for testing
//printf("%d",bArray[i]);
//printf("|");
}
//This is where the actual conversion between binary to decimal
//occurs. basically, it goes from 0 to 15 in the array, at each
//stage it multiplies the value in that array location by
//2 to the power of the index. That should give us a pattern
//of (2^0, 2^1, 2^2...) similar to how you would solve a
//conversion as a human. It then stores those values in an
//array, and finally adds up all the values in the array for
//the final result
for(int i=0;i>=0 && i<16;i++){
power = pow(2,i);
dArray[i]=bArray[i] * power;
//printf("\n%d",dArray[i]);
buffer += dArray[i];
//printf("\nBUFFER=%d",buffer);
}
return buffer;
}
int HtoD(char x[]){
//Variable declaration area
char hArray[8];
int dArray[8];
int buffer, power;
//This section just reverses the order of the array
for (int i=15,j=0;i>=0;i--,j++){
hArray[j] = x[i];
printf("HArray %d\n",hArray[j]);
printf("X %d\n",x[i]);
}
}
long DtoB(long x) {
int bin[64];
for (int i=0; i<64; i++){
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
#include<stdlib.h>
#include<limits.h>
/*#include<algorithm>*/
/*using namespace std;*/
typedef long int LD;
typedef long long int LLD;
typedef float F;
typedef double LF;
typedef unsigned int U;
typedef unsigned long int LU;
typedef unsigned long long int LLU;
typedef char C;
#define sf scanf
#define pf printf
#define PI acos(-1.0)
#define sq(x) (x)*(x)
#define MAX(x,y) (x>y)?x:y
#define MIN(x,y) (x<y)?x:y
#define MAX3(x,y,z) (x>y)?((x>z)?x:z):((y>z)?((y>x)?y:x):z)
#define MIN3(x,y,z) (x<y)?((x<z)?x:z):((y<z)?((y<x)?y:x):z)
#define FOR(i,x,cases) for(i=x;i<cases;i++)
#define FOR1(i,cases,x) for(i=cases;i>=x;i--)
#define nn printf("\n")
#define chk printf("chek\n")
#define chk1 printf("chek1\n")
#define sz 100004
int arr[sz];
int main()
{
LLU S,sum;
int low,high,N,i,len,key;
while(sf("%d%llu",&N,&S)!=EOF)
{
key=1;
for(i=0;i<N;i++)
sf("%d",&arr[i]);
high=low=sum=0;
len=N;
while(high<N)
{
if(sum>=S)
{
if(len>(high-low))
len=high-low;
key=2;
}
if(sum>=S && low<high)
{
sum-=arr[low];
low++;
}
else
{
sum+=arr[high];
high++;
}
}
if(key==2)
pf("%d\n",len);
else
pf("%0\n");
}
return 0;
}
|
C
|
/** @file mat4f.c
* @author Cy Baca
*/
#include <math.h>
#include <assert.h>
#include <stdlib.h>
#define MAT4ARRAY_LEN 16
#define MAT4VEC_LEN 4
enum {
MAT4ARRAY_U_ERROR
, MAT4ARRAY_IDENTITY
, MAT4ARRAY_ZERO
, MAT4ARRAY_DEBUG
/* , MAT4ARRAY_MODEL
, MAT4ARRAY_VIEW
, MAT4ARRAY_CLIP */
, MAT4ARRAY_O_ERROR
};
enum {
MAT4ARRAY_EULER_U_ERROR = 0x0
, MAT4ARRAY_ROLL = 0x1
, MAT4ARRAY_PITCH = 0x2
, MAT4ARRAY_YAW = 0x4
, MAT4ARRAY_EULER_O_ERROR = 0x8
};
void _about_roll(float *, double);
void _about_pitch(float *, double);
void _about_yaw(float *, double);
/** utility ------------------------------------------------------------------*/
void
mat4array_copy(float *restrict out, const float *restrict in)
{
out[ 0] = in[ 0]; out[ 1] = in[ 1]; out[ 2] = in[ 2]; out[ 3] = in[ 3];
out[ 4] = in[ 4]; out[ 5] = in[ 5]; out[ 6] = in[ 6]; out[ 7] = in[ 7];
out[ 8] = in[ 8]; out[ 9] = in[ 9]; out[10] = in[10]; out[11] = in[11];
out[12] = in[12]; out[13] = in[13]; out[14] = in[14]; out[15] = in[15];
}
void
mat4array_set(float *restrict out, int style)
{
assert(out != NULL);
switch (style) {
case MAT4ARRAY_IDENTITY:
out[ 0] = 1.0f; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f;
out[ 4] = 0.0f; out[ 5] = 1.0f; out[ 6] = 0.0f; out[ 7] = 0.0f;
out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = 1.0f; out[11] = 0.0f;
out[12] = 0.0f; out[13] = 0.0f; out[14] = 0.0f; out[15] = 1.0f;
break;
case MAT4ARRAY_ZERO:
out[ 0] = 0.0f; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f;
out[ 4] = 0.0f; out[ 5] = 0.0f; out[ 6] = 0.0f; out[ 7] = 0.0f;
out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = 0.0f; out[11] = 0.0f;
out[12] = 0.0f; out[13] = 0.0f; out[14] = 0.0f; out[15] = 0.0f;
break;
case MAT4ARRAY_DEBUG:
out[ 0] = 0.0f; out[ 1] = 1.0f; out[ 2] = 2.0f; out[ 3] = 3.0f;
out[ 4] = 4.0f; out[ 5] = 5.0f; out[ 6] = 6.0f; out[ 7] = 7.0f;
out[ 8] = 8.0f; out[ 9] = 9.0f; out[10] = 10.0f; out[11] = 11.0f;
out[12] = 12.0f; out[13] = 13.0f; out[14] = 14.0f; out[15] = 15.0f;
break;
default:
assert(style < MAT4ARRAY_O_ERROR && style > MAT4ARRAY_U_ERROR);
}
}
/** translation --------------------------------------------------------------*/
/* これが典型的なモデル・マトリクスです。
* 1, 0, 0, T_x [0][0], [0][1], [0][2], [0][3] @ ────> i0, i1, i2, i3 >──╮
* -------------- ╭───<────────────────<──╯
* , 0, 1, 0, T_y [1][0], [1][1], [1][2], [1][3] @ ╰──> i4, i5, i6, i7 ─>──╮
* --------------
* , 0, 0, 1, T_z
* --------------
* , 0, 0, 0, 1
*
*
*
* 1, | 0, | 0, | 0 [0][0], [1][0], [2][0], [3][0] @ ───> i0, i1, i2, i3 >──╮
* | | | ╭───<────────────────<──╯
* , 0, | 1, | 0, | 0 [0][1], [1][1], [2][1], [3][1] @ ╰──> i4, i5, i6, i7 ─>──╮
* | | |
* , 0, | 0, | 1, | 0
* | | |
* ,T_x,|T_y,|T_z,| 1
*/
#define X 0
#define Y 1
#define Z 2
#define W 3
void
mat4array_get_translationv3(float *restrict out, float *restrict in)
{
out[ 0] = 1.0f; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f;
out[ 4] = 0.0f; out[ 5] = 1.0f; out[ 6] = 0.0f; out[ 7] = 0.0f;
out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = 1.0f; out[11] = 0.0f;
out[12] = in[X]; out[13] = in[Y]; out[14] = in[Z]; out[15] = 1.0f;
}
void
mat4array_get_translation(float *restrict out, float x, float y, float z)
{
out[ 0] = 1.0f; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f;
out[ 4] = 0.0f; out[ 5] = 1.0f; out[ 6] = 0.0f; out[ 7] = 0.0f;
out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = 1.0f; out[11] = 0.0f;
out[12] = x; out[13] = y; out[14] = z; out[15] = 1.0f;
}
void
mat4array_translate(float *restrict out, float x, float y, float z)
{
vecMat4_t mat = vecMat4_row_get(out);
mat.w[X] += mat.x[X] * x + mat.y[X] * y + mat.z[X] * z;
mat.w[Y] += mat.x[Y] * x + mat.y[Y] * y + mat.z[Y] * z;
mat.w[Z] += mat.x[Z] * x + mat.y[Z] * y + mat.z[Z] * z;
mat.w[W] += mat.x[W] * x + mat.y[W] * y + mat.z[W] * z;
}
void
mat4array_translatev3(float *restrict out, float *restrict in)
{
vecMat4_t mat = vecMat4_row_get(out);
mat.w[X] += mat.x[X] * in[X] + mat.y[X] * in[Y] + mat.z[X] * in[Z];
mat.w[Y] += mat.x[Y] * in[X] + mat.y[Y] * in[Y] + mat.z[Y] * in[Z];
mat.w[Z] += mat.x[Z] * in[X] + mat.y[Z] * in[Y] + mat.z[Z] * in[Z];
mat.w[W] += mat.x[W] * in[X] + mat.y[W] * in[Y] + mat.z[W] * in[Z];
}
#undef X
#undef Y
#undef Z
#undef W
/** multiply -----------------------------------------------------------------*/
void
mat4array_get_product(float *restrict out, const float *restrict inp)
{
float A[16];
A[ 0] = out[ 0]; A[ 1] = out[ 1]; A[ 2] = out[ 2]; A[ 3] = out[ 3];
A[ 4] = out[ 4]; A[ 5] = out[ 5]; A[ 6] = out[ 6]; A[ 7] = out[ 7];
A[ 8] = out[ 8]; A[ 9] = out[ 9]; A[10] = out[10]; A[11] = out[11];
A[12] = out[12]; A[13] = out[13]; A[14] = out[14]; A[15] = out[15];
vecMat4_t ot = vecMat4_row_get(out);
cvecMat4_t in = cvecMat4_row_get(inp);
int i = 0;
for (; i < 4; ++i) {
ot.x[i] = A[ 0] * in.x[i]
+ A[ 1] * in.y[i]
+ A[ 2] * in.z[i]
+ A[ 3] * in.w[i];
ot.y[i] = A[ 4] * in.x[i]
+ A[ 5] * in.y[i]
+ A[ 6] * in.z[i]
+ A[ 7] * in.w[i];
ot.z[i] = A[ 8] * in.x[i]
+ A[ 9] * in.y[i]
+ A[10] * in.z[i]
+ A[11] * in.w[i];
ot.w[i] = A[12] * in.x[i]
+ A[13] * in.y[i]
+ A[14] * in.z[i]
+ A[15] * in.w[i];
}
}
/** rotation -----------------------------------------------------------------*/
void
mat4array_rotatev3(float *restrict out, double rad, float *restrict in)
{
float cop[16];
float rot[16];
vecMat4_t ot;
vecMat4_t cp;
ot = vecMat4_row_get(out);
cp = vecMat4_row_get(cop);
float c = (float)cos(rad);
float s = (float)sin(rad);
/* copy input matrix */
cop[ 0] = out[ 0]; cop[ 1] = out[ 1]; cop[ 2] = out[ 2]; cop[ 3] = out[ 3];
cop[ 4] = out[ 4]; cop[ 5] = out[ 5]; cop[ 6] = out[ 6]; cop[ 7] = out[ 7];
cop[ 8] = out[ 8]; cop[ 9] = out[ 9]; cop[10] = out[10]; cop[11] = out[11];
cop[12] = out[12]; cop[13] = out[13]; cop[14] = out[14]; cop[15] = out[15];
# define x 0
# define y 1
# define z 2
/* normalize */
float len = (float)sqrt(
in[x] * in[x]
+ in[y] * in[y]
+ in[z] * in[z]);
float norm[3] = { in[x] / len, in[y] / len, in[z] / len };
float frac[3] = {
(1.0f - c) * norm[x]
, (1.0f - c) * norm[y]
, (1.0f - c) * norm[z] };
/* make rotation matrix, thank you glm header lib */
rot[ 0] = c + frac[x] * norm[x];
rot[ 1] = frac[x] * norm[y] + s * norm[z];
rot[ 2] = frac[x] * norm[z] - s * norm[y];
rot[ 4] = frac[y] * norm[x] - s * norm[z];
rot[ 5] = c + frac[y] * norm[y];
rot[ 6] = frac[y] * norm[z] + s * norm[x];
rot[ 8] = frac[z] * norm[x] + s * norm[y];
rot[ 9] = frac[z] * norm[y] - s * norm[x];
rot[10] = c + frac[z] * norm[z];
# undef x
# undef y
# undef z
ot.x[0] = cp.x[0] * rot[0] + cp.y[0] * rot[1] + cp.z[0] * rot[ 2];
ot.x[1] = cp.x[1] * rot[0] + cp.y[1] * rot[1] + cp.z[1] * rot[ 2];
ot.x[2] = cp.x[2] * rot[0] + cp.y[2] * rot[1] + cp.z[2] * rot[ 2];
ot.x[3] = cp.x[3] * rot[0] + cp.y[3] * rot[1] + cp.z[3] * rot[ 2];
ot.y[0] = cp.x[0] * rot[4] + cp.y[0] * rot[5] + cp.z[0] * rot[ 6];
ot.y[1] = cp.x[1] * rot[4] + cp.y[1] * rot[5] + cp.z[1] * rot[ 6];
ot.y[2] = cp.x[2] * rot[4] + cp.y[2] * rot[5] + cp.z[2] * rot[ 6];
ot.y[3] = cp.x[3] * rot[4] + cp.y[3] * rot[5] + cp.z[3] * rot[ 6];
ot.z[0] = cp.x[0] * rot[8] + cp.y[0] * rot[9] + cp.z[0] * rot[10];
ot.z[1] = cp.x[1] * rot[8] + cp.y[1] * rot[9] + cp.z[1] * rot[10];
ot.z[2] = cp.x[2] * rot[8] + cp.y[2] * rot[9] + cp.z[2] * rot[10];
ot.z[3] = cp.x[3] * rot[8] + cp.y[3] * rot[9] + cp.z[3] * rot[10];
}
void
mat4array_rotate(float *restrict out, double rad, float x, float y, float z)
{
float cop[16];
float rot[16];
vecMat4_t ret;
vecMat4_t mat;
/* copy input matrix */
cop[ 0] = out[ 0]; cop[ 1] = out[ 1]; cop[ 2] = out[ 2]; cop[ 3] = out[ 3];
cop[ 4] = out[ 4]; cop[ 5] = out[ 5]; cop[ 6] = out[ 6]; cop[ 7] = out[ 7];
cop[ 8] = out[ 8]; cop[ 9] = out[ 9]; cop[10] = out[10]; cop[11] = out[11];
cop[12] = out[12]; cop[13] = out[13]; cop[14] = out[14]; cop[15] = out[15];
float c = (float)cos(rad);
float s = (float)sin(rad);
/* normalize http://www.fundza.com/vectors/normalize/ */
float len = (float)sqrt((x * x) + (y * y) + (z * z));
float nx = x / len;
float ny = y / len;
float nz = z / len;
/* make rotation matrix, thank you glm header lib */
float tx = (1.0f - c) * nx;
float ty = (1.0f - c) * ny;
float tz = (1.0f - c) * nz;
rot[ 0] = c + tx * nx;
rot[ 1] = tx * ny + s * nz;
rot[ 2] = tx * nz - s * ny;
rot[ 4] = ty * nx - s * nz;
rot[ 5] = c + ty * ny;
rot[ 6] = ty * nz + s * nx;
rot[ 8] = tz * nx + s * ny;
rot[ 9] = tz * ny - s * nx;
rot[10] = c + tz * nz;
/* multiply by original */
ret = vecMat4_row_get(out);
mat = vecMat4_row_get(cop);
ret.x[0] = mat.x[0] * rot[0] + mat.y[0] * rot[1] + mat.z[0] * rot[ 2];
ret.x[1] = mat.x[1] * rot[0] + mat.y[1] * rot[1] + mat.z[1] * rot[ 2];
ret.x[2] = mat.x[2] * rot[0] + mat.y[2] * rot[1] + mat.z[2] * rot[ 2];
ret.x[3] = mat.x[3] * rot[0] + mat.y[3] * rot[1] + mat.z[3] * rot[ 2];
ret.y[0] = mat.x[0] * rot[4] + mat.y[0] * rot[5] + mat.z[0] * rot[ 6];
ret.y[1] = mat.x[1] * rot[4] + mat.y[1] * rot[5] + mat.z[1] * rot[ 6];
ret.y[2] = mat.x[2] * rot[4] + mat.y[2] * rot[5] + mat.z[2] * rot[ 6];
ret.y[3] = mat.x[3] * rot[4] + mat.y[3] * rot[5] + mat.z[3] * rot[ 6];
ret.z[0] = mat.x[0] * rot[8] + mat.y[0] * rot[9] + mat.z[0] * rot[10];
ret.z[1] = mat.x[1] * rot[8] + mat.y[1] * rot[9] + mat.z[1] * rot[10];
ret.z[2] = mat.x[2] * rot[8] + mat.y[2] * rot[9] + mat.z[2] * rot[10];
ret.z[3] = mat.x[3] * rot[8] + mat.y[3] * rot[9] + mat.z[3] * rot[10];
}
void
mat4array_get_rotation(float *restrict out, double rad, int axis)
{
switch (axis) {
case MAT4ARRAY_ROLL | MAT4ARRAY_PITCH | MAT4ARRAY_YAW:
_about_roll( out, rad);
_about_pitch(out, rad);
_about_yaw( out, rad);
break;
case MAT4ARRAY_ROLL | MAT4ARRAY_PITCH:
_about_roll( out, rad);
_about_pitch(out, rad);
break;
case MAT4ARRAY_ROLL | MAT4ARRAY_YAW:
_about_roll(out, rad);
_about_yaw( out, rad);
break;
case MAT4ARRAY_PITCH | MAT4ARRAY_YAW:
_about_pitch(out, rad);
_about_yaw( out, rad);
break;
case MAT4ARRAY_ROLL: _about_roll( out, rad); break;
case MAT4ARRAY_PITCH: _about_pitch(out, rad); break;
case MAT4ARRAY_YAW: _about_yaw( out, rad); break;
default:
assert(axis > MAT4ARRAY_EULER_U_ERROR
&& axis < MAT4ARRAY_EULER_O_ERROR);
}
}
void _about_roll(float *out, double rad)
{
float c = (float)cos(rad);
float s = (float)sin(rad);
out[ 0] = c; out[ 1] = s; out[ 2] = 0.0f; out[ 3] = 0.0f;
out[ 4] = -s; out[ 5] = c; out[ 6] = 0.0f; out[ 7] = 0.0f;
out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = 1.0f; out[11] = 0.0f;
out[12] = 0.0f; out[13] = 0.0f; out[14] = 0.0f; out[15] = 1.0f;
}
void _about_pitch(float *out, double rad)
{
float c = (float)cos(rad);
float s = (float)sin(rad);
out[ 0] = 1.0f; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f;
out[ 4] = 0.0f; out[ 5] = c; out[ 6] = -s; out[ 7] = 0.0f;
out[ 8] = 0.0f; out[ 9] = -s; out[10] = c; out[11] = 0.0f;
out[12] = 0.0f; out[13] = 0.0f; out[14] = 0.0f; out[15] = 1.0f;
}
void _about_yaw(float *out, double rad)
{
float c = (float)cos(rad);
float s = (float)sin(rad);
out[ 0] = c; out[ 1] = 0.0f; out[ 2] = -s; out[ 3] = 0.0f;
out[ 4] = 0.0f; out[ 5] = 1.0f; out[ 6] = 0.0f; out[ 7] = 0.0f;
out[ 8] = s; out[ 9] = 0.0f; out[10] = c; out[11] = 0.0f;
out[12] = 0.0f; out[13] = 0.0f; out[14] = 0.0f; out[15] = 1.0f;
}
/** scale --------------------------------------------------------------------*/
/** mat4array_scale.c */
/* S_x 0 0 0
* 0 S_y 0 0
* 0 0 S_z 0
* 0 0 0 1
*/
void
mat4array_get_scaled(float *restrict out, float x, float y, float z)
{
out[ 0] = x; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f;
out[ 4] = 0.0f; out[ 5] = y; out[ 6] = 0.0f; out[ 7] = 0.0f;
out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = z; out[11] = 0.0f;
out[12] = 0.0f; out[13] = 0.0f; out[14] = 0.0f; out[15] = 1.0f;
}
void
mat4array_scale(float *restrict out, float x, float y, float z)
{
vecMat4_t ot = vecMat4_row_get(out);
/*
float cop[16];
out[ 0] = cop[ 0]; out[ 1] = cop[ 1]; out[ 2] = cop[ 2]; out[ 3] = cop[ 3];
out[ 4] = cop[ 4]; out[ 5] = cop[ 5]; out[ 6] = cop[ 6]; out[ 7] = cop[ 7];
out[ 8] = cop[ 8]; out[ 9] = cop[ 9]; out[10] = cop[10]; out[11] = cop[11];
out[12] = cop[12]; out[13] = cop[13]; out[14] = cop[14]; out[15] = cop[15];
vecMat_t cp = vecMat4_row_get(cop);
float scl[16];
scl[ 0] = x; scl[ 1] = 0.0f; scl[ 2] = 0.0f; scl[ 3] = 0.0f;
scl[ 4] = 0.0f; scl[ 5] = y; scl[ 6] = 0.0f; scl[ 7] = 0.0f;
scl[ 8] = 0.0f; scl[ 9] = 0.0f; scl[10] = z; scl[11] = 0.0f;
scl[12] = 0.0f; scl[13] = 0.0f; scl[14] = 0.0f; scl[15] = 1.0f;
vecMat_t sc = vecMat4_row_get(scl);
int i = 0;
for (; i < 4; ++i){
ot.a[i] = cp.a[i] * x;
ot.b[i] = cp.b[i] * y;
ot.c[i] = cp.c[i] * z;
}
*/
int i = 0;
for (; i < 4; ++i) {
ot.x[i] *= x;
ot.y[i] *= y;
ot.z[i] *= z;
}
}
void
mat4array_scalev3(float *restrict out, float *restrict in)
{
vecMat4_t ot = vecMat4_row_get(out);
int i = 0;
for (; i < 4; ++i) {
ot.x[i] *= in[0];
ot.y[i] *= in[1];
ot.z[i] *= in[2];
}
}
/** transpose ----------------------------------------------------------------*/
void
mat4array_transpose(float *restrict out)
{
assert(out != (void *)0);
float tmp[16];
tmp[ 0] = out[ 0]; tmp[ 1] = out[ 1]; tmp[ 2] = out[ 2]; tmp[ 3] = out[ 3];
tmp[ 4] = out[ 4]; tmp[ 5] = out[ 5]; tmp[ 6] = out[ 6]; tmp[ 7] = out[ 7];
tmp[ 8] = out[ 8]; tmp[ 9] = out[ 9]; tmp[10] = out[10]; tmp[11] = out[11];
tmp[12] = out[12]; tmp[13] = out[13]; tmp[14] = out[14]; tmp[15] = out[15];
int i = 0;
for (; i < 4; out += 4, ++i) {
float *restrict itr = tmp;
int j = 0;
for (; j < 4; itr += 4, ++j)
out[j] = itr[i];
}
}
/** compound -----------------------------------------------------------------*/
void
mat4array_get_look_at(
float *restrict out
, float *restrict eye
, float *restrict mid
, float *restrict up)
{
# define x 0
# define y 1
# define z 2
float roll[3] = { mid[x] - eye[x], mid[y] - eye[y], mid[z] - eye[z] };
float len_recip = 1.0f / (float)sqrt(
roll[x] * roll[x]
+ roll[y] * roll[y]
+ roll[z] * roll[z]);
roll[x] *= len_recip;
roll[y] *= len_recip;
roll[z] *= len_recip;
float pitch[3] = {
roll[y] * up[z] - roll[z] * up[y]
, roll[z] * up[x] - roll[x] * up[z]
, roll[x] * up[y] - roll[y] * up[x] };
len_recip = 1.0f / (float)sqrt(
pitch[x] * pitch[x]
+ pitch[y] * pitch[y]
+ pitch[z] * pitch[z]);
pitch[x] *= len_recip;
pitch[y] *= len_recip;
pitch[z] *= len_recip;
float yaw[3] = {
pitch[y] * roll[z] - pitch[z] * roll[y]
, pitch[z] * roll[x] - pitch[x] * roll[z]
, pitch[x] * roll[y] - pitch[y] * roll[x]
};
out[ 0] = pitch[x];
out[ 4] = pitch[y];
out[ 8] = pitch[z];
out[ 1] = yaw[x];
out[ 5] = yaw[y];
out[ 9] = yaw[z];
out[ 2] = -roll[x];
out[ 6] = -roll[y];
out[10] = -roll[z];
out[12] = -(pitch[x] * eye[x] + pitch[y] * eye[y] + pitch[z] * eye[z]);
out[13] = -(yaw[x] * eye[x] + yaw[y] * eye[y] + yaw[z] * eye[z]);
out[14] = roll[x] * eye[x] + roll[y] * eye[y] + roll[z] * eye[z];
# undef x
# undef y
# undef z
}
void
mat4array_get_frustrum(
float *restrict out
, float left
, float right
, float top
, float bottom
, float near
, float far)
{
float dz = right - left;
float dy = top - bottom;
float dx = far - near;
out[ 0] = 2.0f * near / dz;
out[ 5] = 2.0f * near / dy;
out[ 8] = (right + left) / dz;
out[ 9] = (top + bottom) / dy;
out[10] = -(far + near) / dx;
out[11] = -1;
out[14] = -(2 * far * near) / dx;
}
void
mat4array_get_perspective( /* glm/gtc/matrix_transform.inl */
float *restrict out
, const float field_of_view
, const float aspect_ratio
, const float near_plane
, const float far_plane)
{
assert(aspect_ratio > 0.0f);
float loc = (float)tan(field_of_view / 2);
out[ 0] = 1.0f / (aspect_ratio * loc);
out[ 5] = 1.0f / loc;
out[10] = -(far_plane + near_plane) / far_plane - near_plane;
out[11] = -1.0f;
out[14] = -(2.0f * far_plane * near_plane) / far_plane - near_plane;
}
/** eof */
|
C
|
// INITIALIZATION OF AN ARRAY
#include <stdio.h>
int main()
{
int a[] = {34, 232, 23};
float b[] = {3.4, 23.2, 2.3};
printf("The value of a[0] is %d\n", a[0]);
printf("The value of a[1] is %d\n", a[1]);
printf("The value of a[2] is %d\n", a[2]);
printf("The value of b[0] is %.2f\n", b[0]);
printf("The value of b[1] is %.2f\n", b[1]);
printf("The value of b[2] is %.2f\n", b[2]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include "clam.h"
int main(int argc, char **argv)
{
for (int a = 0; a < argc; a++) {
const char *arg = argv[a];
clam_match_result_t i = 0;
if ((i = clam_match_posix_option(arg, "h")) || (i = clam_match_posix_long_option(arg, "-help"))) {
printf("Usage: example [option]\n");
printf(" -h | --help This help information\n");
printf(" -lname | -l name | --link name | --link=name | -link name | --link=name\n");
printf(" /f [value]\n");
return 0;
}
bool longopt;
if (
(longopt = true, i = clam_match_posix_long_option(arg, "link")) ||
(longopt = true, i = clam_match_posix_long_option(arg, "-link")) ||
(longopt = false, i = clam_match_posix_option(arg, "l"))) {
clam_match_result_t eq = 0;
if (longopt && !clam_match_end(arg + i) && !clam_match_char(arg + i, '=')) {
printf("invalid trailer %s at %d in %s\n", arg + i, i, arg);
return 1;
}
if (longopt) {
i += eq = clam_match_char(arg + i, '=');
}
arg += i;
if (!eq && clam_match_end(arg)) {
arg = argv[++a];
if (a == argc) {
printf("link requires an argument\n");
return 1;
}
}
printf("linking with %s\n", arg);
continue;
}
if (i = clam_match_windows_switch(arg, "Ff")) {
arg = argv[++a];
if (a < argc) {
printf("doing something with with %s\n", arg);
} else {
printf("using a default with /f");
}
continue;
}
}
}
|
C
|
/* ******************************************************************
Arquivos de exemplo para o desenvolvimento de um algoritmo de
branch-and-cut usando o XPRESS. Este branch-and-cut resolve o
problema da mochila 0-1 e usa como cortes as desigualdades de
cobertura simples (cover inequalities) da forma x(c) < |C| -1 onde
C um conjunto de itens formando uma cobertura minimal.
Autor: Cid Carvalho de Souza
Instituto de Computao - UNICAMP - Brazil
Data: segundo semestre de 2003
Arquivo: princ.c
Descrio: arquivo com programas em C
* *************************************************************** */
/* includes dos arquivos .h */
#ifndef HGLOBAIS
#include "globais.h"
#endif
/* variaveis globais */
/* dados da mochila */
int n; /* nmero de itens */
double *c; /* custos */
int *w; /* pesos */
int W; /* capacidade */
/* - variaveis para inclusao de cortes: qrtype, mstart e dmatval
* usadas para carga inicial do LP tambem. */
int *mcols, *mtype, *mstart;
char *qrtype;
double *drhs, *dmatval;
/* estrutura do XPRESS contendo o problema */
XPRSprob prob;
/* armazena as solucoes do LP e do ILP */
double *x;
/* contador do total de cortes por n da arvore B&B */
int totcuts=0;
/* contador do total de ns explorados B&B */
int totnodes=0;
/* contador do total de lacos de separacao de cortes por n da arvore B&B */
int itersep=0;
/* valor de retorno das rotinas do XPRESS */
int xpress_ret;
/* status retornado por algumas rotinas do XPRESS */
int xpress_status;
/* armazena a melhor solucao inteira encontrada */
double *xstar;
/* armazena o valor da solucao otima */
double zstar;
/* - profundidade maxima de um no da arvore de B&B aonde sera feita separacao */
int MAX_NODE_DEPTH_FOR_SEP=1000000;
/* - valor otimo da primeira relaxacao */
double objval_relax;
/* - valor da relaxacao linear no final do 1o n */
double objval_node1;
/* - diz se usara ou nao a heuristica primal */
Boolean HEURISTICA_PRIMAL;
/* - diz se usara ou nao cortes */
Boolean BRANCH_AND_CUT;
/* - n onde encontrou a melhor solucao inteira */
int NODE_BEST_INTEGER_SOL=-1;
/* declaracoes das callbacks */
int XPRS_CC Cortes(XPRSprob prob, void* data);
void XPRS_CC SalvaMelhorSol(XPRSprob prob, void *my_object);
/* rotinas auxiliares */
void errormsg(const char *sSubName,int nLineNo,int nErrCode);
void ImprimeSol(double *x);
void HeuristicaPrimal(int node);
void Mochila(double *c,int *w,int b,int n,int *x,double *val);
/* mensagem de uso do programa */
void showUsage() {
printf ("Uso: knap <estrategia> <prof_max_para_corte> < <instancia> \n");
printf ("- estrategia: string de \"0\"\'s e \"1\"\'s de tamanho 2.\n");
printf (" - 1a. posio \"1\" se a heurstica primal usada. \n");
printf (" - 2a. posio \"1\" se as minhas \"cover inequalities\" forem separadas.\n");
printf (" Nota: estrategia=\"00\" equivale a um Branch-and-Bound puro\n");
printf ("- prof_max_para_corte: maior altura de um n para aplicar cortes\n");
printf (" (default=1000000) \n");
printf ("- instancia: nome do arquivo contendo a instncia \n");
}
/* ============================ */
/* Inicio do programa principal */
/* ============================ */
int main(int argc, char * argv[]){
/* variaveis auxiliares */
int i,j;
char opcoes[2]="";
/* variaveis para montar o LP no solver */
int *mrwind, *mgcols;
char *qgtype;
double *rhs, *obj, *dlb, *dub, melhor_limitante_dual;
char probname[] = "mochila";
/* Verifica estratgia a adotar de acordo com a linha de comando */
if ( (argc<2) || (argc>3) ) {
showUsage();
exit(-1);
}
if ( (strlen(argv[1]) != 2) ){
printf("Primeiro parmetro tem tamanho menor que 2. \n");
showUsage();
exit(-1);
}
else{
sprintf(opcoes,"%c",argv[1][0]);
if ( (strcmp(opcoes,"0")) && (strcmp(opcoes,"1")) ){
printf("Primeiro parmetro dever ter apenas \"0\"s e \"1\"s !\n");
showUsage();
exit(-1);
}
else HEURISTICA_PRIMAL=(strcmp(opcoes,"0"));
sprintf(opcoes,"%c",argv[1][1]);
if ( (strcmp(opcoes,"0")) && (strcmp(opcoes,"1")) ){
printf("Primeiro parmetro dever ter apenas \"0\"s e \"1\"s !\n");
showUsage();
exit(-1);
}
else BRANCH_AND_CUT=(strcmp(opcoes,"0"));
}
if (argc>=3) MAX_NODE_DEPTH_FOR_SEP=atoi(argv[2]);
/* inicializa valores de variaveis globais */
totcuts=0; itersep=0; zstar=XPRS_MINUSINFINITY;
/* le dados de entrada do problema da Mochila 0-1.*/
scanf("%d %d",&n,&W);
c=(double *)malloc(n*sizeof(double));
w=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++) scanf("%lf",&c[i]);
for(i=0;i<n;i++) scanf("%d",&w[i]);
/* aloca espaco para os arrays que sero usados pelo XPRESS na carga do problema.
* Ler no manual do XPRESS a documentao sobre a rotina XPRSloadglobal. */
/* arrays com informaes sobre as variveis */
qgtype = malloc(n*sizeof(char));
obj=(double *)malloc(n*sizeof(double));
dlb=(double *)malloc(n*sizeof(double));
dub=(double *)malloc(n*sizeof(double));
mgcols=(int *)malloc(n*sizeof(int));
/* arrays com informaes sobre as restries (s tem uma !)*/
qrtype = malloc(sizeof(char));
rhs=(double *)malloc(sizeof(double));
mstart=(int *)malloc((n+1)*sizeof(int));
mrwind=(int *)malloc(n*sizeof(int));
dmatval=(double *)malloc(n*sizeof(double));
/* carga dos vetores */
for(i=0;i<n;i++){
obj[i]=c[i]; /* custos das variveis */
dlb[i]=0.0; /* limite inferior das variveis */
dub[i]=1.0; /* limite superior das variveis */
mgcols[i]=i; /* todas variveis so globais (veja manual para explicao) */
qgtype[i]='B'; /* todas variveis so binrias */
mrwind[i]=0; /* todas variveis ocorrem na primeira restrio */
mstart[i]=i; /* (veja manual para explicao) */
dmatval[i]=w[i]; /* coeficiente da varivel na restrio 1 */
}
rhs[0]=(double) W;
qrtype[0]='L';
mstart[n]=n;
/* incializaco do XPRESS */
xpress_ret=XPRSinit("");
if (xpress_ret) errormsg("Main: Erro de inicializacao do XPRESS.\n",__LINE__,xpress_ret);
/* "cria" o problema */
xpress_ret=XPRScreateprob(&prob);
if (xpress_ret) errormsg("Main: Erro na initializacao do problema",__LINE__,xpress_ret);
/* ======================================================================== */
/* Atribui valores a vrios parametros de controle do XPRESS */
/* ======================================================================== */
/* limita o tempo de execucao */
xpress_ret=XPRSsetintcontrol(prob,XPRS_MAXTIME,MAX_CPU_TIME);
if (xpress_ret) errormsg("Main: Erro ao tentar setar o XPRS_MAXTIME.\n",__LINE__,xpress_ret);
/* aloca espao extra de linhas para insero de cortes. CUIDADO:
Isto tem que ser feito ANTES (!) de carregar o problema ! */
xpress_ret=XPRSsetintcontrol(prob,XPRS_EXTRAROWS,MAX_NUM_CORTES+1);
if (xpress_ret)
errormsg("Main: Erro ao tentar setar o XPRS_EXTRAROWS.\n",__LINE__,xpress_ret);
/* aloca espao extra de elementos no nulos para insero de
cortes. CUIDADO: Isto tem que ser feito ANTES (!) de carregar o
problema ! */
xpress_ret=XPRSsetintcontrol(prob,XPRS_EXTRAELEMS,n*n);
if (xpress_ret)
errormsg("Main: Erro ao tentar setar o XPRS_EXTRAELEMS.",__LINE__,xpress_ret);
/*=====================================================================================*/
/* RELEASE NOTE: The controls CPKEEPALLCUTS, CPMAXCUTS and CPMAXELEMS have been removed*/
/* limita o nmero mximo de cortes que podero ser inseridos
xpress_ret=XPRSsetintcontrol(prob,XPRS_CPMAXCUTS,MAX_NUM_CORTES);
if (xpress_ret)
errormsg("Main: Erro ao tentar setar o XPRS_CPMAXCUTS.\n",__LINE__,xpress_ret);*/
/* limita o nmero mximo de elementos no-nulos nos cortes que podero ser inseridos
xpress_ret=XPRSsetintcontrol(prob,XPRS_CPMAXELEMS,MAX_NUM_CORTES*n);
if (xpress_ret)
errormsg("Main: Erro ao tentar setar o XPRS_CPMAXELEMS.",__LINE__,xpress_ret);*/
/*=====================================================================================*/
/* carga do modelo*/
xpress_ret=XPRSloadglobal(prob, probname, n, 1, qrtype, rhs, NULL, obj, mstart, NULL,
mrwind, dmatval, dlb, dub, n, 0, qgtype, mgcols, NULL, NULL, NULL, NULL, NULL);
if (xpress_ret) errormsg("Main: Erro na carga do modelo.",__LINE__,xpress_ret);
/* libera memoria dos vetores usado na carga do LP */
free(qrtype); free(rhs); free(obj); free(mstart); free(mrwind); free(dmatval);
free(dlb); free(dub); free(qgtype); free(mgcols);
/* salva um arquivo ".lp" com o LP original */
xpress_ret=XPRSwriteprob(prob,"LP","l");
if (xpress_ret)
errormsg("Main: Erro na chamada da rotina XPRSwriteprob.\n",__LINE__,xpress_ret);
/* Desabilita o PRESOLVE: o problema da mochila muito fcil para o XPRESS */
xpress_ret=XPRSsetintcontrol(prob,XPRS_PRESOLVE,0);
if (xpress_ret) errormsg("Main: Erro ao desabilitar o presolve.",__LINE__,xpress_ret);
/* impresso para conferncia */
if (HEURISTICA_PRIMAL) printf("*** Heurstica Primal ser usada\n");
if (BRANCH_AND_CUT) {
printf("*** Algoritmo de branch-and-cut.\n");
/* aloca espaco para as estruturas que serao usadas para
* armazenar os cortes encontrados na separacao. Para evitar
* perda de tempo, estas estruturas sao alocadas uma unica vez.
* Para isso, o tamanho das mesmas deve ser o maior possivel
* para comportar os dados obtidos por *qualquer* uma das
* rotinas de separacao. No caso a rotina de separao poder
* gerar at um "cover ineuqality" por vez. Ler no manual a
* descrio da rotina XPRSaddcuts */
qrtype=(char *)malloc(sizeof(char));
mtype=(int *) malloc(sizeof(int));
drhs=(double *)malloc(sizeof(double));
mstart=(int *)malloc((n+1)*sizeof(int));
mcols=(int *)malloc(n*sizeof(int)); /* cada corte tera no maximo n nao-zeros */
dmatval=(double *)malloc(n*sizeof(double));
/* callback indicando que sera feita separacao de cortes em cada
n da arvore de B&B */
xpress_ret=XPRSsetcbcutmgr(prob,Cortes,NULL);
if (xpress_ret)
errormsg("Main: Erro na chamada da rotina XPRSsetcbcutmgr.\n",__LINE__,xpress_ret);
/*=====================================================================================*/
/* RELEASE NOTE: The controls CPKEEPALLCUTS, CPMAXCUTS and CPMAXELEMS have been removed*/
/* Diz ao XPRESS que quer manter cortes no pool
xpress_ret=XPRSsetintcontrol(prob,XPRS_CPKEEPALLCUTS,0);
if (xpress_ret)
errormsg("Main: Erro ao tentar setar o XPRS_CPKEEPALLCUTS.\n",__LINE__,xpress_ret); */
/*=====================================================================================*/
}
else {
printf("*** Algoritmo de branch-and-bound puro.\n");
qrtype=NULL; mtype=NULL; drhs=NULL; mstart=NULL;
mcols=NULL; dmatval=NULL;
if (HEURISTICA_PRIMAL) {
/* callback indicando que sera feita separacao de cortes em
cada n da arvore de B&B. Mas, neste caso, a rotina
nao faz corte, limitando-se apenas a executar a
heuristica primal. */
xpress_ret=XPRSsetcbcutmgr(prob,Cortes,NULL);
if (xpress_ret)
errormsg("Main: rotina XPRSsetcbcutmgr.\n",__LINE__,xpress_ret);
}
}
/* Desabilita a separacao de cortes do XPRESS. Mochila muito fcil para o XPRESS */
xpress_ret=XPRSsetintcontrol(prob,XPRS_CUTSTRATEGY,0);
if (xpress_ret)
errormsg("Main: Erro ao tentar setar o XPRS_CUTSTRATEGY.\n",__LINE__,xpress_ret);
/* callback para salvar a melhor solucao inteira encontrada */
xpress_ret=XPRSsetcbintsol(prob,SalvaMelhorSol,NULL);
if (xpress_ret)
errormsg("Main: Erro na chamada da rotina XPRSsetcbintsol.\n",__LINE__,xpress_ret);
/* aloca espaco para o vetor "x" que contera as solucoes das
* relaxacoes e de "xstar" que armazenara a melhor solucao inteira
* encontrada. */
x=(double *)malloc(n*sizeof(double));
xstar=(double *)malloc(n*sizeof(double));
/* resolve o problema */
xpress_ret=XPRSmaxim(prob,"g");
if (xpress_ret) errormsg("Main: Erro na chamada da rotina XPRSmaxim.\n",__LINE__,xpress_ret);
/* imprime a solucao otima ou a melhor solucao encontrada (se achou) e o seu valor */
xpress_ret=XPRSgetintattrib(prob,XPRS_MIPSTATUS,&xpress_status);
if (xpress_ret)
errormsg("Main: Erro na chamada da rotina XPRSgetintatrib.\n",__LINE__,xpress_ret);
if ( (xpress_status==XPRS_MIP_OPTIMAL) ||
(xpress_status==XPRS_MIP_SOLUTION) ||
(zstar > XPRS_MINUSINFINITY ) ){
XPRSgetintattrib(prob,XPRS_MIPSOLNODE,&NODE_BEST_INTEGER_SOL);
printf("\n");
printf("- Valor da solucao otima =%12.6f \n",(double)(zstar));
printf("- Variaveis otimas: (n=%d)\n",NODE_BEST_INTEGER_SOL);
if ( zstar == XPRS_MINUSINFINITY ) {
xpress_ret=XPRSgetsol(prob,xstar,NULL,NULL,NULL);
if (xpress_ret)
errormsg("Main: Erro na chamada da rotina XPRSgetsol\n",__LINE__,xpress_ret);
}
ImprimeSol(xstar);
}
else printf("Main: programa terminou sem achar solucao inteira !\n");
/* impressao de estatisticas */
printf("********************\n");
printf("Estatisticas finais:\n");
printf("********************\n");
printf(".total de cortes inseridos ........ = %d\n",totcuts);
printf(".valor da FO da primeira relaxao. = %.6f\n",objval_relax);
printf(".valor da FO no n raiz ........... = %.6f\n",objval_node1);
xpress_ret=XPRSgetintattrib(prob,XPRS_NODES,&totnodes);
if (xpress_ret)
errormsg("Main: Erro na chamada da rotina XPRSgetintatrib.\n",__LINE__,xpress_ret);
printf(".total de ns explorados .......... = %d\n",totnodes);
printf(".n da melhor solucao inteira ..... = %d\n",NODE_BEST_INTEGER_SOL);
printf(".valor da melhor solucao inteira .. = %d\n",(int)(zstar+0.5));
/* somar 0.5 evita erros de arredondamento */
/* verifica o valor do melhor_limitante_dual */
xpress_ret=XPRSgetdblattrib(prob,XPRS_BESTBOUND,&melhor_limitante_dual);
if (xpress_ret)
errormsg("Main: Erro na chamada de XPRSgetdblattrib.\n",__LINE__,xpress_ret);
if (melhor_limitante_dual < zstar+EPSILON) melhor_limitante_dual=zstar;
printf(".melhor limitante dual ............ = %.6f\n",melhor_limitante_dual);
/* libera a memoria usada pelo problema */
/*
xpress_ret=XPRSdestroyprob(prob);
if (xpress_ret)
errormsg("Main: Erro na liberacao da memoria usada pelo problema.\n",__LINE__,xpress_ret);
*/
/* libera toda memoria usada no programa */
if (qrtype) free(qrtype);
if (mtype) free(mtype);
if (drhs) free(drhs);
if (mstart) free(mstart);
if (mcols) free(mcols);
if (dmatval) free(dmatval);
if (x) free(x);
if (xstar) free(xstar);
xpress_ret=XPRSfree();
if (xpress_ret)
errormsg("Main: Erro na liberacao de memoria final.\n",__LINE__,xpress_ret);
printf("========================================\n");
return 0;
}
/* =====================================================================
* Rotina (callback) para salvar a melhor solucao. Roda para todo n
* onde acha solucao inteira.
* =====================================================================
*/
void XPRS_CC SalvaMelhorSol(XPRSprob prob, void *my_object)
{
int i, cols, peso_aux=0, node;
double objval;
Boolean viavel;
/* pega o numero do n corrente */
xpress_ret=XPRSgetintattrib(prob,XPRS_NODES,&node);
if (xpress_ret)
errormsg("SalvaMelhorSol: rotina XPRSgetintattrib.\n",__LINE__,xpress_ret);
xpress_ret=XPRSgetintattrib(prob,XPRS_COLS,&cols);
if (xpress_ret)
errormsg("SalvaMelhorSol: rotina XPRSgetintattrib\n",__LINE__,xpress_ret);
xpress_ret=XPRSgetdblattrib(prob,XPRS_LPOBJVAL,&objval);
if (xpress_ret)
errormsg("SalvaMelhorSol: rotina XPRSgetdblattrib\n",__LINE__,xpress_ret);
xpress_ret=XPRSgetsol(prob,x,NULL,NULL,NULL);
if (xpress_ret)
errormsg("SalvaMelhorSol: Erro na chamada da rotina XPRSgetsol\n",__LINE__,xpress_ret);
/* testa se a soluo vivel */
for(i=0;i<cols;i++) peso_aux += x[i]*w[i];
viavel=(peso_aux <= W + EPSILON);
/*
printf("\n..Encontrada uma soluo inteira (n=%d): valor=%f, peso=%d,",
node,objval,peso_aux);
if (viavel) printf(" viavel\n"); else printf(" inviavel\n");
for(i=0;i<cols;i++)
if (x[i]>EPSILON) printf(" x[%3d] = %12.6f (w=%6d, c=%12.6f)\n",i,x[i],w[i],c[i]);
*/
/* se a solucao tiver custo melhor que a melhor solucao disponivel entao salva */
if ((objval > zstar-EPSILON) && viavel) {
printf(".. atualizando melhor soluo ...\n");
for(i=0;i<cols;i++) xstar[i]=x[i];
zstar=objval;
/* informa xpress sobre novo incumbent */
xpress_ret=XPRSsetdblcontrol(prob,XPRS_MIPABSCUTOFF,zstar+1.0-EPSILON);
if (xpress_ret)
errormsg("SalvaMelhorSol: XPRSsetdblcontrol.\n",__LINE__,xpress_ret);
NODE_BEST_INTEGER_SOL=node;
/* Impresso para sada */
printf("..Melhor soluo inteira encontrada no n %d, peso %d e custo %12.6f\n",
NODE_BEST_INTEGER_SOL,peso_aux,zstar);
printf("..Soluo encontrada: \n");
ImprimeSol(x);
}
return;
}
/**********************************************************************************\
* Rotina para separacao de Cover inequalities. Roda em todo n.
* Autor: Cid Carvalho de Souza
* Data: segundo semestre de 2003
\**********************************************************************************/
int XPRS_CC Cortes(XPRSprob prob, void* data)
{
int encontrou, i, irhs, k, node, node_depth, solfile, ret;
int nLPStatus, nIntInf;
/* variaveis para a separacao das cover inequalities */
int *peso, capacidade, nitem, *sol;
double *custo, val, lpobjval, ajuste_val;
/* se for B&B puro e no usar Heurstica Primal, no faz nada */
if ( (!BRANCH_AND_CUT) && (!HEURISTICA_PRIMAL)) return 0;
/* Recupera a status do LP e o nmero de inviabilidades inteiras
* Procura cortes e executa heurstica primal (quando tiver sido
* solicitado) apenas se o LP for timo e a soluo no for
* inteira. */
XPRSgetintattrib(prob,XPRS_LPSTATUS,&nLPStatus);
XPRSgetintattrib(prob,XPRS_MIPINFEAS,&nIntInf);
if (!(nLPStatus == 1 && nIntInf>0)) return 0;
/* Muda o parmetro SOLUTIONFILE para pegar a soluo do LP da
memria. LEIA O MANUAL PARA ENTENDER este trecho */
XPRSgetintcontrol(prob,XPRS_SOLUTIONFILE,&solfile);
XPRSsetintcontrol(prob,XPRS_SOLUTIONFILE,0);
/* Pega a soluo do LP. */
XPRSgetsol(prob,x,NULL,NULL,NULL);
/* Restaura de volta o valor do SOLUTIONFILE */
XPRSsetintcontrol(prob,XPRS_SOLUTIONFILE,solfile);
/* verifica o nmero do n em que se encontra */
XPRSgetintattrib(prob,XPRS_NODES,&node);
/* Imprime cabealho do n */
printf("\n=========\n");
printf("N %d\n",node);
printf("\n=========\n");
printf("Lao de separao: %d\n",itersep);
/* executa a heurstica primal se for o caso */
if (HEURISTICA_PRIMAL) HeuristicaPrimal(node);
/* pega o valor otimo do LP ... */
XPRSgetdblattrib(prob, XPRS_LPOBJVAL,&lpobjval);
/* Imprime dados sobre o n */
printf(".Valor timo do LP: %12.6f\n",lpobjval);
printf(".Soluo tima do LP:\n");
ImprimeSol(x);
printf(".Rotina de separao\n");
/* guarda o valor da funo objetivo no primeiro n */
if (node==1) objval_node1=lpobjval;
/* guarda o valor da funo objetivo da primeira relaxao */
if ((node==1) && (!itersep)) objval_relax=lpobjval;
/* sai fora se for branch and bound puro */
if (!BRANCH_AND_CUT) return 0;
/* sai fora se a profundidade do n corrente for maior que
* MAX_NODE_DEPTH_FOR_SEP. */
xpress_ret=XPRSgetintattrib(prob,XPRS_NODEDEPTH,&node_depth);
if (xpress_ret)
errormsg("Cortes: erro na chamada da rotina XPRSgetintattrib.\n",__LINE__,xpress_ret);
if (node_depth > MAX_NODE_DEPTH_FOR_SEP) return 0;
/* varivel indicando se achou desigualdade violada ou no */
encontrou=0;
/* carga dos parametros para a rotina de separacao da Cover Ineq */
/* ATENCAO: A rotina Mochila nao usa a posicao zero dos vetores
custo, peso e sol, portanto para carregar o problema e para
pegar a solucao eh preciso acertar os indices */
peso=(int *)malloc(sizeof(int)*(n+1)); /* +1 !! */
assert(peso);
capacidade=0;
for(i=0;i<n;i++){
peso[i+1]=w[i]; /* +1 !!! */
capacidade=capacidade+peso[i+1]; /* +1 !! */
}
capacidade=capacidade-1-W;
/* calcula custos para o problema de separao (mochila) */
ajuste_val=0.0; /* ajuste para o custo do pbm da separao */
custo=(double *)malloc(sizeof(double)*(n+1)); /* +1 !!! */
assert(custo);
for(i=0;i<n;i++) {
custo[i+1]=1.0-x[i];
ajuste_val += custo[i+1];
}
/* aloca espaco para o vetor solucao da rotina Mochila */
sol=(int *)malloc(sizeof(int)*(n+1)); /* +1 !!! */
assert(sol);
/* resolve a mochila usando Programao Dinmica */
Mochila(custo,peso,capacidade,n,sol,&val);
/* calculo do RHS da desigualdade de cobertura */
irhs=0;
for(i=1;i<=n;i++)
if (sol[i]==0) irhs++;
/* verifica se a desigualdade estah violada */
if (ajuste_val - val < 1.0-EPSILON) {
encontrou=1;
/* prepara a insercao do corte */
mtype[0]=1;
qrtype[0]='L';
drhs[0]=(double)irhs - 1.0;
mstart[0]=0; mstart[1]=irhs;
k=0;
for(i=1;i<=n;i++)
if (!sol[i]) {
mcols[k]=i-1; dmatval[k]=1.0; k++;
}
assert(k==irhs);
/* Impresso do corte */
printf("..corte encontrado: (viol=%12.6f)\n\n ",1.0-ajuste_val+val);
for(i=0;i<irhs;i++){
printf("x[%d] ",mcols[i]);
if (i==irhs-1) printf("<= %d\n\n",irhs-1);
else printf("+ ");
}
/* adiciona o corte usando rotina XPRSaddcuts */
xpress_ret=XPRSaddcuts(prob, 1, mtype, qrtype, drhs, mstart, mcols, dmatval);
totcuts++;
if (xpress_ret)
errormsg("Cortes: erro na chamada da rotina XPRSgetintattrib.\n",__LINE__,xpress_ret);
}
else printf("..corte no encontrado\n");
assert(peso && sol && custo);
free(peso); free(sol); free(custo);
printf("..Fim da rotina de cortes\n");
/* salva um arquivo MPS com o LP original */
xpress_ret=XPRSwriteprob(prob,"LPcuts","l");
if (xpress_ret)
errormsg("Cortes: rotina XPRSwriteprob.\n",__LINE__,xpress_ret);
if ((encontrou) && (itersep < MAX_ITER_SEP))
{ itersep++; ret=1; /* continua buscando cortes neste n */ }
else
{ itersep=0; ret=0; /* vai parar de buscar cortes neste n */}
return ret;
}
/**********************************************************************************\
* Rotina que resolve uma mochila binaria por Programao Dinmica.
* Autor: Cid Carvalho de Souza
* Data: 10/2002
*
* Objetivo: resolver uma mochila binaria maximizando o custo cx
* e com uma restricao do tipo wx <= b.
*
* Entrada: vetores $c$ (custos), $w$ (pesos), $b$ (capacidade)
* e $n$ numero de itens.
*
* Saidas: vetor $x$ (solucoes) e $z$ (valor otimo).
*
* Observacao: todos os vetores sao inteiros, exceto os custos
* que sao "double", assim como o valor otimo $z$.
*
* IMPORTANTE: todos os vetores comecam na posicao zero mas os itens
* so supostamente numerados de 1 a n. Assim, c[1] o custo do item 1.
*
\**********************************************************************************/
void Mochila(double *c,int *w,int b,int n,int *x,double *val) {
int k, d;
double aux, limite=0.0; /* variaveis auxiliares para calculos de custo */
double **z; /* matriz de resultados intermediarios da Prog. Din */
/* aloca espaco para $z$ */
z=(double **)malloc((n+1)*sizeof(double *));
for(k=0;k<=n;k++) z[k]=(double *)malloc((b+1)*sizeof(double));
/* inicializa o $z$ */
for(k=0;k<=n;k++)
for(d=0;d<=b;d++) z[k][d]=0.0;
/* calculo do "limite" (numero negativo cujo valor absoluto eh
maior que o valor otimo com certeza): foi inicializado com ZERO. */
for(k=1;k<=n;k++) limite=limite-c[k];
/* prog. din.: completando a matriz z */
for(k=1;k<=n;k++)
for(d=1;d<=b;d++){
/* aux sera igual ao valor de z[k-1][d-w[k]] quando esta celula
existir ou sera igual ao "limite" caso contrario. */
aux = (d-w[k]) < 0 ? limite : z[k-1][d-w[k]] ;
z[k][d] = (z[k-1][d] > aux+c[k]) ? z[k-1][d] : aux+c[k];
}
/* carrega o vetor solucao */
for(k=0;k<=n;k++) x[k]=0;
d=b; k=n;
while ((d!=0) && (k!=0)) {
if (z[k-1][d] != z[k][d]) {
d=d-w[k]; x[k]=1;
}
k--;
}
*val=z[n][b];
/* desaloca espaco de $z$ */
for(k=0;k<=n;k++) free(z[k]);
free(z);
return;
}
/**********************************************************************************\
* Rotina que encontra uma soluo heurstica para mochila binaria
* dada a soluo e uma relaxao linear.
*
* Autor: Cid Carvalho de Souza
* Data: 10/2003
*
* Entrada: a soluo fracionria corrente $x$ e o n corrente sendo
* explorado o n "node".
*
* Idia da heurstica: ordenar itens em ordem decrescente dos valores
* de $x$. Em seguida ir construindo a soluo heurstica $xh$ fixando
* as variveis em 1 ao varrer o vetor na ordem decrescente enquanto a
* capacidade da mochila permitir.
*
\**********************************************************************************/
typedef struct{
double valor;
int indice;
} RegAux;
/* rotina auxiliar de comparacao para o "qsort". CUIDADO: Feito para
* ordenar em ordem *DECRESCENTE* ! */
int ComparaRegAux(const void *a, const void *b) {
int ret;
if (((RegAux *)a)->valor > ((RegAux *)b)->valor) ret=-1;
else {
if (((RegAux *)a)->valor < ((RegAux *)b)->valor) ret=1;
else ret=0;
}
return ret;
}
void HeuristicaPrimal(int node){
/* variveis locais */
RegAux *xh;
double custo;
int i, j, Wresidual;
xh=(RegAux *)malloc(n*sizeof(RegAux));
for(i=0;i<n;i++){
xh[i].valor=x[i];
xh[i].indice=i;
}
qsort(xh,n,sizeof(RegAux),&ComparaRegAux);
/* calcula custo e compara com a melhor solucao corrente. Se for
* melhor, informa o XPRESS sobre o novo incumbent e salva a
* solucao. */
custo=0.0;
Wresidual=W;
for(i=0;(i<n) && (Wresidual > w[xh[i].indice]);i++){
Wresidual -= w[xh[i].indice];
custo += c[xh[i].indice];
}
/* Nota: ao final deste lao "i-1" ser o maior ndice (em xh !) de
um item que cabe na mochila. */
/* Impresso da soluo heurstica encontrada */
printf("..Soluo Primal encontrada:\n");
for(j=0;j<i;j++)
printf("item %3d, peso %6d, custo %12.6f\n",
xh[j].indice,w[xh[j].indice],c[xh[j].indice]);
printf(" %6d %12.6f\n",
W-Wresidual,custo);
/* verifica se atualizar o incumbent */
if (custo > zstar) {
printf("..Heurstica Primal melhorou a soluo\n");
for(j=0;j<i;j++) xstar[xh[i].indice]=1.0;
for(j=i;j<n;j++) xstar[xh[i].indice]=0.0;
zstar=custo;
/* atualiza numero do n onde encontrou a melhor solucao */
NODE_BEST_INTEGER_SOL=node;
/* informa xpress sobre novo incumbent */
xpress_ret=XPRSsetdblcontrol(prob,XPRS_MIPABSCUTOFF,custo+1.0-EPSILON);
if (xpress_ret)
errormsg("Heuristica Primal: Erro \n",__LINE__,xpress_ret);
}
else printf("..Heurstica Primal no melhorou a soluo\n");
free(xh);
return;
}
/**********************************************************************************\
* Rotina que imprime uma soluo heurstica para mochila binaria
* dada a soluo e uma relaxao linear.
*
* Autor: Cid Carvalho de Souza
* Data: 10/2003
/*********************************************************************************/
void ImprimeSol(double *a){
int i;
for(i=0;i<n;i++) if (a[i] > EPSILON)
printf("x[%3d]=%12.6f (w[%3d]=%6d, c[%3d]=%12.6f)\n",i,a[i],i,w[i],i,c[i]);
}
/**********************************************************************************\
* Rotina copiada de programas exemplo do XPRES ... :(
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*
* Name: errormsg
* Purpose: Display error information about failed subroutines.
* Arguments: const char *sSubName Subroutine name
* int nLineNo Line number
* int nErrCode Error code
* Return Value: None
\**********************************************************************************/
void errormsg(const char *sSubName,int nLineNo,int nErrCode)
{
int nErrNo; /* Optimizer error number */
/* Print error message */
printf("The subroutine %s has failed on line %d\n",sSubName,nLineNo);
/* Append the error code, if it exists */
if (nErrCode!=-1) printf("with error code %d\n",nErrCode);
/* Append Optimizer error number, if available */
if (nErrCode==32) {
XPRSgetintattrib(prob,XPRS_ERRORCODE,&nErrNo);
printf("The Optimizer error number is: %d\n",nErrNo);
}
/* Free memory, close files and exit */
XPRSdestroyprob(prob);
XPRSfree();
exit(nErrCode);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* Faca um programa que leia dois numeros e mostre qual deles eh o maior. */
int main() {
float num1, num2;
printf("Digite o primeiro numero: ");
scanf("%f", &num1);
printf("Digite o segundo numero: ");
scanf("%f", &num2);
if(num1 > num2) {
printf("O numero %f eh maior que %f.\n", num1, num2);
} else if(num2 > num1){
printf("O numero %f eh maior que %f.\n", num2, num1);
} else {
printf("Numeros iguais\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
void removeString (char source[], int start, int count)
{
int i = 0;
while ( source[i] != '\0' ) {
if ( i >= start )
source[i] = source[i + count];
++i;
printf("i: %i, %s\n", i, source);
}
}
int main(void)
{
void removeString(char source[], int start, int count);
char source[] = "the wrong son";
removeString(source, 4, 6);
printf("The result is: \"%s\"\n", source);
return 0;
}
|
C
|
/**************************************************************
Program prebere vhodno sliko in na podlagi danih n
korakov zgenerira novo sliko, kjer se slikovne pike
spreminjajo glede na sosedne pike, ki jih obdajajo.
Avtor: Žiga Kljun
**************************************************************/
#include "qdbmp.h"
#include <stdio.h>
#include "qdbmp.c"
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
int main( int argc, char* argv[] ) {
BMP* bmp;
BMP* nova;
UCHAR r, g, b;
int width, height;
int x, y;
/* Preverimo, če je število vnešenih argumentov pravilno */
if ( argc != 3 )
{
fprintf( stderr, "Uporaba: %s <vhodna slika> <izhodna slika>",
argv[ 0 ] );
return 0;
}
bmp = BMP_ReadFile( argv[ 1 ] );
nova=BMP_ReadFile( "random.bmp");
BMP_CHECK_ERROR( stderr, -1 );
width = BMP_GetWidth( bmp );
height = BMP_GetHeight( bmp );
srand ( time(NULL) );
/* Definiramo tabelo sosedov, ki jo bomo kasneje uporabljali
za shranjevanje barv sosednjih pik */
UCHAR tabela_sosedov[ 4 ][3];
int stBarv=0;
int random_number=0;
int koraki=0;
printf("Vneste stevilo korakov, ki jih zelite izvesti \n");
int stKorakov;
scanf ("%d", &stKorakov);
/* Z zanko se zapeljemo cez vse korake in v vsakem od njih
izvedemo spreminjanje barv */
while(koraki<stKorakov){
for ( y = 0 ; y < height ; y++ )
{
for ( x = 0 ; x < width ; x++ )
{
stBarv=-1;
if((x-1)>=0){
/* Preberemo RGB vrednosti x-1, y pike */
BMP_GetPixelRGB( bmp, x-1, y, &r, &g, &b );
stBarv++;
tabela_sosedov[stBarv][0]=r;
tabela_sosedov[stBarv][1]=g;
tabela_sosedov[stBarv][2]=b;
}
if((y-1)>=0){
BMP_GetPixelRGB( bmp, x, y-1, &r, &g, &b );
stBarv++;
tabela_sosedov[stBarv][0]=r;
tabela_sosedov[stBarv][1]=g;
tabela_sosedov[stBarv][2]=b;
}
if((x+1)<width){
BMP_GetPixelRGB( bmp, x+1, y, &r, &g, &b );
stBarv++;
tabela_sosedov[stBarv][0]=r;
tabela_sosedov[stBarv][1]=g;
tabela_sosedov[stBarv][2]=b;
}
if((y+1)<height){
BMP_GetPixelRGB( bmp, x, y+1, &r, &g, &b );
stBarv++;
tabela_sosedov[stBarv][0]=r;
tabela_sosedov[stBarv][1]=g;
tabela_sosedov[stBarv][2]=b;
}
/* Zgeneriramo nakljucno stevilo po modulu, ki je
enak stevilu sosedov */
random_number = rand()%stBarv;
/* Nastavimo RGB vrednost novi sliki */
BMP_SetPixelRGB( nova, x, y, tabela_sosedov[random_number][0],
tabela_sosedov[random_number][1],
tabela_sosedov[random_number][2]);
}
}
bmp=nova;
koraki++;
}
/* Shranimo novo sliko */
BMP_WriteFile( nova, argv[ 2 ] );
BMP_CHECK_ERROR( stdout, -2 );
/* Sprostimo spomin */
BMP_Free( bmp );
return 0;
}
|
C
|
/*
* CNRSIM
* translate_notation.h
* Library that parses a tab-separated file
* provided by the user containing the
* notation dictionary.
*
* @author Riccardo Massidda
*/
#ifndef TRANSLATE_NOTATION
#define TRANSLATE_NOTATION
#include <uthash.h>
#include <stdbool.h>
typedef struct region_index_t region_index_t;
struct region_index_t {
char * reg; // region label
char * alt; // alternate notation
UT_hash_handle hh;
};
/*
* Initialize a structure containing
* the dictionary.
*
* @param filename path to the file to be parsed
* @returns pointer to the initialized dictionary, NULL otherwise
*/
region_index_t * tr_init ( char * filename );
/*
* Translates the notation
*
* @param index pointer to the index
* @param label string that contains the notation to translate
* @returns string containing alternate notation, NULL if there isn't any
*/
char * tr_translate ( region_index_t * index, char * label );
/*
* Free allocated memory
*
* @param index pointer to the index
*/
void tr_destroy ( region_index_t * index );
#endif
|
C
|
/*
** EPITECH PROJECT, 2021
** Live-Astek-Linked-List
** File description:
** game
*/
#include "game.h"
#include <SFML/Graphics.h>
#include <stdlib.h>
void game_init(game_t *game)
{
*game = (game_t){
.window = sfRenderWindow_create(
(sfVideoMode){1280, 720, 32},
"TchouTchou",
sfDefaultStyle,
NULL),
.texture_wagon = sfTexture_createFromFile("assets/tileset.png", NULL),
.train = NULL};
}
void game_update(game_t *game) { train_update(game->train); }
#include <stdio.h>
void game_event(game_t *game)
{
sfEvent event;
while (sfRenderWindow_pollEvent(game->window, &event)) {
if (event.type == sfEvtClosed) {
sfRenderWindow_close(game->window);
}
if (event.type == sfEvtKeyPressed) {
if (event.key.code == sfKeySpace) {
train_add_wagon(&game->train, game->texture_wagon);
}
if (event.key.code == sfKeyA) {
train_fiouufff(game->train);
}
if (event.key.code == sfKeyF) {
train_crash_wagon(&game->train);
}
}
}
}
void game_draw(game_t *game)
{
sfRenderWindow_clear(game->window, sfBlack);
train_draw(game->train, game->window);
sfRenderWindow_display(game->window);
}
void game_end(game_t *game)
{
sfRenderWindow_destroy(game->window);
while (game->train) {
linked_list_t *node = list_pop(&game->train);
wagon_destroy(node->data);
free(node);
}
sfTexture_destroy(game->texture_wagon);
}
|
C
|
/***************************************************
3. (int *) fun();
main() { int *p; p=fun(); printf(“\n %u”,p);}
int *fun() { int ivar=20; return &ivar; }
***************************************************/
#include<stdio.h>
(int*) fun();
//int *fun();
main()
{
int *p;
p=fun();
printf("%u \n",p);
}
int *fun()
{
int ivar=20;
return &ivar;
}
|
C
|
// gcc generate_matrix.c -o generate_matrix
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int i, j, n = 3, m = 3, max_val = 50, min_val = -max_val;
if (argc < 3) {
fprintf(stderr, "Too few arguments\n");
return 1;
}
n = atoi(argv[1]);
m = atoi(argv[2]);
if (argc == 4) {
max_val = atoi(argv[3]);
min_val = -max_val;
} else if (argc > 4) {
min_val = atoi(argv[3]);
max_val = atoi(argv[4]);
}
if (min_val >= max_val) {
fprintf(stderr, "The minumum value must be less than maximum value\n");
return 1;
}
srand(time(NULL));
fprintf(stdout, "%d %d\n", n, m);
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j) {
int r = (rand() % (max_val-min_val+1)) + min_val;
fprintf(stdout, "%d ", r);
}
fprintf(stdout, "\n");
}
fprintf(stdout, "\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n;
int a=2;
int i = 0;
int arr[1000];
scanf("%d", &n);
int m = n;
if (n == 0)
printf("0");
while (n != 0)
{
if (n == 1)
{
arr[i] = 1;
i++;
break;
}
else if (n % 2 == 0)
{
arr[i] = 0;
n /= -2;
}
else
{
arr[i] = 1;
n = -(n - 1) / 2;
}
i++;
}
i--;
for (int j = i; j >=0 ; j--)
{
printf("%d", arr[j]);
}
}
|
C
|
#include "posicion.h"
Posicion crear_posicion(char* string_posicion)
{
Posicion posicion;
posicion.posX = string_posicion[0]-'0';
posicion.posY = string_posicion[2]-'0';
return posicion;
}
int distancia_entre(Posicion posicion1, Posicion posicion2) { return abs(posicion2.posX-posicion1.posX)+abs(posicion2.posY-posicion1.posY); }
int distancia_menor(Posicion posicion, t_list* posiciones, int* indice)
{
if(list_is_empty(posiciones)) return -1;
int distancia = distancia_entre(posicion, *((Posicion*) list_get(posiciones, 0)));
*indice = 0;
for(int i=1; i<posiciones->elements_count;i++)
{
int nueva_distancia = distancia_entre(posicion, *((Posicion*) list_get(posiciones, i)));
if(nueva_distancia<distancia)
{
distancia = nueva_distancia;
*indice = i;
}
}
return distancia;
}
bool es_misma_posicion(Posicion posicion_1, Posicion posicion_2) { return posicion_1.posX==posicion_2.posX && posicion_1.posY == posicion_2.posY; }
|
C
|
/*
File Name : doubly.h
Description : Function Definitions to implement a doubly linked list
Programmer : Sparsh Jain
Roll No : 111601026
Date : October 17, 2017
*/
void createDoubly(struct doubly *list)
{
list->head = NULL;
list->tail = NULL;
list->length = 0;
}
void addHead(struct doubly *list, data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = data;
ptr->prev = NULL;
ptr->next = NULL;
if(list->length == 0)
list->head = list->tail = ptr;
else
{
ptr->next = list->head;
list->head->prev = ptr;
list->head = ptr;
}
list->length++;
}
void addTail(struct doubly *list, data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = data;
ptr->prev = NULL;
ptr->next = NULL;
if(list->length == 0)
list->head = list->tail = ptr;
else
{
ptr->prev = list->tail;
list->tail->next = ptr;
list->tail = ptr;
}
list->length++;
}
void addAfter(struct doubly *list, data, find)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node)), *p;
ptr->data = data;
ptr->prev = NULL;
ptr->next = NULL;
p = list->head;
while(p != NULL)
{
if(p->data == find)
{
ptr->prev = p;
ptr->next = p->next;
if(p->next != NULL)
p->next->prev = ptr;
else
list->tail = ptr;
p->next = ptr;
list->length++;
return;
}
p = p->next;
}
printf("\n %d not found!\n %d not added!", find, data);
}
void addBefore(struct doubly *list, data, find)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node)), *p;
ptr->data = data;
ptr->prev = NULL;
ptr->next = NULL;
p = list->head;
while(p != NULL)
{
if(p->data == find)
{
ptr->next = p;
ptr->prev = p->prev;
if(p->prev != NULL)
p->prev->next = ptr;
else
list->head = ptr;
p->prev = ptr;
list->length++;
return;
}
p = p->next;
}
printf("\n %d not found!\n %d not added!", find, data);
}
int delHead(struct doubly *list)
{
struct node *ptr = list->head;
int data;
if(list->length == 0)
{
printf("\n Nothing to delete! Returning -1!");
return -1;
}
if(list->length == 1)
{
list->head = list->tail = NULL;
list->length--;
data = ptr->data;
free(ptr);
return data;
}
list->head = list->head->next;
list->head->prev = NULL;
list->length--;
data = ptr->data;
free(ptr);
return data;
}
int delTail(struct doubly *list)
{
struct node *ptr = list->tail;
int data;
if(list->length == 0)
{
printf("\n Nothing to delete! Returning -1!");
return -1;
}
if(list->length == 1)
{
list->head = list->tail = NULL;
list->length--;
data = ptr->data;
free(ptr);
return data;
}
list->tail = list->tail->prev;
list->tail->next = NULL;
list->length--;
data = ptr->data;
free(ptr);
return data;
}
int delNode(struct doubly *list, data)
{
struct node *ptr = list->head;
if(list->length == 0)
{
printf("\n Nothing to delete! Returning -1!");
return -1;
}
while(ptr != NULL)
{
if(ptr->data == data)
{
if(list->head == ptr)
list->head = ptr->next;
if(list->tail == ptr)
list->tail = ptr->prev;
if(ptr->next != NULL)
ptr->next->prev = ptr->prev;
if(ptr->prev != NULL)
ptr->prev->next = ptr->next;
list->length--;
free(ptr);
return data;
}
else ptr = ptr->next;
}
printf("\n %d not found!\n Nothing deleted!\n Returning -1", data);
return -1;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main(void){
// get card_number from user
printf("Number: ");
long long entered_card_number = get_long_long();
long long card_number = entered_card_number;
// initialize checksum variable and card number length variable
int checksum = 0;
int card_number_length = 0;
// calculate the checksum for the card number using Luhn's algorithm and
// count card number length
while(card_number > 0){
// add last digit in card_number to checksum
checksum += card_number % 10;
// remove last digit from card_number and increment card_number_length
card_number /= 10;
card_number_length += 1;
// if last digit in card_number times 2 >= 10, add the two digits of that number
// to checksum, otherwise add that single digit to the checksum
if(((card_number % 10) * 2) >= 10){
checksum += 1 + (((card_number % 10) * 2) % 10);
} else {
checksum += ((card_number % 10) * 2);
}
// remove last digit from card_number and increment card_number_length as long as
// card_number is not now zero
if(card_number != 0){card_number_length += 1;}
card_number = card_number / 10;
}
//shorten entered card number to only the first two digits
long long first_digits = entered_card_number;
for(int i = card_number_length; i > 2; i--){
first_digits /= 10;
}
// determine card number validity
if(checksum % 10 == 0){
switch(card_number_length){
case 15:
if(first_digits == 34 || first_digits == 37){
printf("AMEX\n");
}
break;
case 16:
if(first_digits == 51 || first_digits == 52 || first_digits == 53 || first_digits == 54 || first_digits == 55){
printf("MASTERCARD\n");
}
case 13:
if(first_digits / 10 == 4){
printf("VISA\n");
}
break;
default:
printf("INVALID\n");
break;
}
} else {
printf("INVALID\n");
}
}
|
C
|
#include "card_array.h"
#include <assert.h>
#include <err.h>
#include <stdio.h>
card_array*
card_array_new(size_t num_cards)
{
card_array* new_card_array = malloc(sizeof(card_array));
if (new_card_array == NULL) {
err(1, "new_card_array malloc failed");
}
new_card_array->cards = malloc(num_cards*sizeof(card_id));
if (new_card_array->cards == NULL) {
err(1, "new_card_array->cards malloc failed");
}
new_card_array->num_cards = num_cards;
return new_card_array;
}
card_array*
flatten_card_location(card_location* card_loc)
{
size_t total_card_amt = get_total_cards(card_loc);
card_array* card_arr = card_array_new(total_card_amt);
size_t i = 0;
for (card_id card = DIAMONDS; card < TOTAL_UNIQUE_CARDS; ++card) {
size_t card_amt = get_card_amount(card_loc, card);
if (card_amt == 0) {
continue;
}
for (size_t card_number = 0; card_number < card_amt; ++card_number) {
assert(i < total_card_amt);
card_arr->cards[i] = card;
i++;
}
}
return card_arr;
}
void
shuffle_card_array(card_array* card_arr)
{
if (card_arr->num_cards > 1) {
for (size_t i = 0; i < card_arr->num_cards - 1; ++i) {
size_t rnd = (size_t) rand();
size_t j = i + rnd/(RAND_MAX/(card_arr->num_cards - i) + 1);
card_id tmp = card_arr->cards[j];
card_arr->cards[j] = card_arr->cards[i];
card_arr->cards[i] = tmp;
}
}
}
card_location**
deal_cards(size_t num_players, card_array* ordered_deck)
{
card_location** player_hands = calloc(num_players, sizeof(card_location*));
if (player_hands == NULL) {
err(1, "*player_hands malloc failed");
}
for (size_t i = 0; i < num_players; ++i) {
player_hands[i] = card_location_new();
}
/* Deal cards out */
for (size_t i = 0; i < ordered_deck->num_cards; ++i) {
/* Get the current player */
size_t iplayer = i % num_players;
#ifdef DBUG
printf("Player %zu, card %zu\n", iplayer, i);
#endif /* DBUG */
/* Give a card from the deck to the current player */
add_card_to_location(player_hands[iplayer], ordered_deck->cards[i]);
}
return player_hands;
}
void
free_card_array(card_array* card_arr)
{
free(card_arr->cards);
free(card_arr);
}
|
C
|
#include <assert.h>
#include <stdlib.h>
#include <salis.h>
#define MBST_MASK 0x80
#define USED_MASK 0x40
#define INST_MASK 0x3f
static sbool g_isInit;
static suint g_order;
static suint g_size;
static suint g_mbsc;
static suint g_used;
static suint g_cap;
static sbyte * g_data;
void
sm_init ( suint ordr )
{
suint bs = sizeof ( *g_data );
assert ( !g_isInit );
assert ( !s_isInit ());
assert ( INST_MASK == SINST_COUNT - 1 );
g_isInit = STRUE;
g_order = ordr;
g_size = 1 << ordr;
g_cap = g_size / 2;
g_data = calloc ( g_size, bs );
assert ( g_data );
}
void
sm_quit ( void )
{
assert ( g_isInit );
assert ( s_isInit ());
free ( g_data );
g_isInit = SFALSE;
g_order = 0;
g_size = 0;
g_mbsc = 0;
g_used = 0;
g_cap = 0;
g_data = NULL;
}
void
sm_save ( FILE * file )
{
assert ( g_isInit );
assert ( file );
fwrite ( &g_isInit, sizeof ( sbool ), 1, file );
fwrite ( &g_order, sizeof ( suint ), 1, file );
fwrite ( &g_size, sizeof ( suint ), 1, file );
fwrite ( &g_mbsc, sizeof ( suint ), 1, file );
fwrite ( &g_used, sizeof ( suint ), 1, file );
fwrite ( &g_cap, sizeof ( suint ), 1, file );
fwrite ( g_data, sizeof ( sbyte ), g_size, file );
}
void
sm_load ( FILE * file )
{
assert ( !g_isInit );
assert ( file );
fread ( &g_isInit, sizeof ( sbool ), 1, file );
fread ( &g_order, sizeof ( suint ), 1, file );
fread ( &g_size, sizeof ( suint ), 1, file );
fread ( &g_mbsc, sizeof ( suint ), 1, file );
fread ( &g_used, sizeof ( suint ), 1, file );
fread ( &g_cap, sizeof ( suint ), 1, file );
g_data = calloc ( g_size, sizeof ( *g_data ));
assert ( g_data );
fread ( g_data, sizeof ( sbyte ), g_size, file );
}
sbool
sm_isInit ( void )
{
return g_isInit;
}
suint
sm_getOrder ( void )
{
return g_order;
}
suint
sm_getSize ( void )
{
return g_size;
}
suint
sm_getMBSCount ( void )
{
return g_mbsc;
}
suint
sm_getUsed ( void )
{
return g_used;
}
suint
sm_getCap ( void )
{
return g_cap;
}
sbool
sm_overCap ( void )
{
assert ( g_isInit );
return g_used > g_cap;
}
sbool
sm_isValid ( suint addr )
{
assert ( g_isInit );
return addr < g_size;
}
sbool
sm_isMBStart ( suint addr )
{
assert ( g_isInit );
assert ( sm_isValid ( addr ));
return !!( g_data [ addr ] & MBST_MASK );
}
sbool
sm_isUsed ( suint addr )
{
assert ( g_isInit );
assert ( sm_isValid ( addr ));
return !!( g_data [ addr ] & USED_MASK );
}
void
sm_setMBStart ( suint addr )
{
assert ( g_isInit );
assert ( sm_isValid ( addr ));
assert ( !sm_isMBStart ( addr ));
g_data [ addr ] ^= MBST_MASK;
g_mbsc ++;
assert ( sm_isMBStart ( addr ));
assert ( g_mbsc );
assert ( g_mbsc <= g_size );
}
void
sm_unsetMBStart ( suint addr )
{
assert ( g_isInit );
assert ( g_mbsc );
assert ( sm_isValid ( addr ));
assert ( sm_isMBStart ( addr ));
g_data [ addr ] ^= MBST_MASK;
g_mbsc --;
assert ( !sm_isMBStart ( addr ));
assert ( g_mbsc <= g_size );
}
void
sm_alloc ( suint addr )
{
assert ( g_isInit );
assert ( sm_isValid ( addr ));
assert ( !sm_isUsed ( addr ));
g_data [ addr ] ^= USED_MASK;
g_used ++;
assert ( sm_isUsed ( addr ));
assert ( g_used );
assert ( g_used <= g_size );
}
void
sm_dealloc ( suint addr )
{
assert ( g_isInit );
assert ( g_used );
assert ( sm_isValid ( addr ));
assert ( sm_isUsed ( addr ));
g_data [ addr ] ^= USED_MASK;
g_used --;
assert ( !sm_isUsed ( addr ));
assert ( g_used <= g_size );
}
sbyte
sm_getInst ( suint addr )
{
assert ( g_isInit );
assert ( sm_isValid ( addr ));
return g_data [ addr ] & INST_MASK;
}
void
sm_setInst ( suint addr, sbyte inst )
{
assert ( g_isInit );
assert ( sm_isValid ( addr ));
assert ( si_isInst ( inst ));
g_data [ addr ] &= ( MBST_MASK | USED_MASK );
g_data [ addr ] |= inst;
}
|
C
|
#include <stdio.h>
/*
CS50x: Week 4 Shorts - Collatz challenge
Write a recursive function that utilizes the Collatz Conjecture.
https://en.wikipedia.org/wiki/Collatz_conjecture
Author: Adrian Arumugam
Date: 2016-01-08
*/
int collatz(int n)
{
// Base case.
if (n == 1)
return 0;
// Even numbers.
else if ((n % 2) == 0)
return 1 + collatz(n / 2);
// Odd numbers.
else
return 1 + collatz((3 * n) + 1);
}
int main(void)
{
int numbers[11] = {1,2,3,4,5,6,7,8,15,27,50};
for(int i = 0; i < 11; i++)
{
int steps = collatz(numbers[i]);
printf("Steps to reach 1 from %i: %i\n", numbers[i], steps);
}
}
|
C
|
/**
* @brief It implements the command interpreter
*
* @file command.c
* @author Paloma Ruiz Matesanz
* @version 2.0
* @date 22-02-2021
* @copyright GNU Public License
*/
#include <stdio.h>
#include <strings.h>
#include "command.h"
#define CMD_LENGHT 30
char *cmd_to_str[N_CMD]
[N_CMDT] = {{"","No command"}, {"","Unknown"}, {"e","Exit"}, {"n","Next"}, {"b","Back"}, {"t", "Take"}, {"d", "Drop"}, {"j", "Jump"}};
T_Command get_user_input(){
T_Command cmd = NO_CMD;char
input[CMD_LENGHT] = "";
int i = UNKNOWN - NO_CMD + 1;
if (scanf("%s", input) > 0) {cmd = UNKNOWN;
while(cmd == UNKNOWN && i < N_CMD)
{
if (!strcasecmp(input, cmd_to_str[i] [CMDS])|| !strcasecmp(input, cmd_to_str[i][CMDL]))
{
cmd = i + NO_CMD;
} else{
i++;
}
}
}
return cmd;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define key(a) (a.votos)
#define keyCode(a) (a.code)
#define less(a, b) (key(a) < key(b))
#define lessCode(a, b) (keyCode(a) < keyCode(b))
#define exch(a, b) { Item t = a; a = b; b = t; }
#define cmpexch(a, b) { if (less(b, a)) exch(a, b); }
typedef struct item {
int code;
int votos;
} Item;
Item presidente[100];
Item senador[1000];
Item depFed[10000];
Item depEst[100000];
int votos, votospresidente, votosInvalidos;
int separa(Item *vetor, int l, int r) {
Item c = vetor[r];
int j = l;
for (int k = l; k < r; k++) {
if (vetor[k].votos == c.votos) {
if (lessCode(vetor[k], c)) {
exch(vetor[k], vetor[j]);
j++;
}
}
else {
if (less(vetor[k], c)) {
exch(vetor[k], vetor[j]);
j++;
}
}
}
exch(vetor[j], vetor[r]);
return j;
}
void quicksort(Item *vetor, int l, int r) {
int j;
if (r <= l)
return;
j = separa(vetor, l, r);
quicksort(vetor, l, j - 1);
quicksort(vetor, j + 1, r);
}
void quickselect(Item *v, int l, int r, int k) {
int i;
if (r <= l)
return;
i = separa(v, l, r);
if (i > k)
quickselect(v, l, i - 1, k);
if (i < k)
quickselect(v, i + 1, r, k);
}
void init() {
int i;
for (i = 0; i < 100; i++) {
presidente[i].code = i;
presidente[i].votos = 0;
}
for (i = 0; i < 1000; i++) {
senador[i].code = i;
senador[i].votos = 0;
}
for (i = 0; i < 10000; i++) {
depFed[i].code = i;
depFed[i].votos = 0;
}
for (i = 0; i < 100000; i++) {
depEst[i].code = i;
depEst[i].votos = 0;
}
}
int main() {
int S, F, E, codigo, auxCod, pot;
double presidenteInd, presidenteValid;
init();
scanf(" %d %d %d", &S, &F, &E);
while (scanf("%d", &codigo) != EOF) {
if (codigo <= 0)
votosInvalidos++;
else {
pot = 0;
auxCod = codigo;
while (codigo) {
codigo /= 10;
pot++;
}
switch (pot) {
case 2:
presidente[auxCod].votos++;
votos++;
votospresidente++;
break;
case 3:
senador[auxCod].votos++;
votos++;
break;
case 4:
depFed[auxCod].votos++;
votos++;
break;
case 5:
depEst[auxCod].votos++;
votos++;
}
}
}
quickselect(presidente, 0, 99, 99);
presidenteValid = votospresidente * 0.51;
printf("%d %d\n", votos, votosInvalidos);
if (presidente[99].votos < presidenteValid)
printf("Segundo turno\n");
else
printf("%d\n", presidente[99].code);
quickselect(senador, 0, 999, 999 - S);
quicksort(senador, 999 - S, 999);
for (int i = 0; i < S; i++)
printf("%d ", senador[999 - i].code);
printf("\n");
quickselect(depFed, 0, 9999, 9999 - F);
quicksort(depFed, 9999 - F, 9999);
for (int i = 0; i < F; i++)
printf("%d ", depFed[9999 - i].code);
printf("\n");
quickselect(depEst, 0, 99999, 99999 - E);
quicksort(depEst, 99999 - E, 99999);
for (int i = 0; i < E; i++)
printf("%d ", depEst[99999 - i].code);
printf("\n");
return 0;
}
|
C
|
/*
Project teammates-
Shantanu Purandare, ASU ID- 1217160516
Girish Kumar Ethirajan, ASU ID- 1216305688
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "sem.h"
#include <unistd.h>
semaphore_t mutex,w_sem,r_sem;
int done = 0,arr[3];
void childwork(int *n)
{
// This is the child thread function
while(1) {
P(&mutex);
if (done != *n) {
V(&mutex);
P(&w_sem);
}
if (done == 0) {
arr[*n]++;
done = 1;
V(&w_sem);
} else if(done == 1) {
arr[*n]++;
done = 2;
V(&w_sem);
} else if(done == 2) {
arr[*n]++;
done = 3;
V(&r_sem);
}
V(&mutex);
sleep(2);
}
}
int main()
{
// This is the parent(main) thread
init_sem(&mutex, 1);
init_sem(&w_sem, 0);
init_sem(&r_sem, 0);
arr[0]=0; arr[1]=0;arr[2]=0;
int n1 = 0, n2 = 1, n3 = 2;
start_thread(childwork, &n1);
start_thread(childwork, &n2);
start_thread(childwork, &n3);
while(1){
P(&mutex);
if(done!=3){
V(&mutex);
P(&r_sem);
}
done=0;
printf("Values %d %d %d\n",arr[0],arr[1],arr[2]);
V(&w_sem);
V(&mutex);
sleep(1);
}
return 0;
}
|
C
|
/*
Fernando Garrote de la Macorra A01027503
Alejandra Nissan Leizorek A01024682
Actividad 3 Ejercicio 2
*/
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
typedef struct{
int min;
int max;
int numArchivos;
}urna;
int numeroUrnas = 0;
//Funciones
void recorrerArchivos(char *, urna *);
void imprimir(urna *);
int main(int argc, const char* argv[]){
char * currentDir;
int tamanoUrnas = 0, i=0;
currentDir = (char*)malloc(100*sizeof(char));
printf("Favor de ingresar el número de urnas: ");
scanf("%d", &numeroUrnas);
printf("Favor de ingresar el rango de las urnas en bytes: ");
scanf("%d", &tamanoUrnas);
urna * urnas = (urna*)malloc(numeroUrnas*sizeof(urna));
//Asignación de rangos a las urnas
urna * aux = urnas;
urna * final = urnas + numeroUrnas;
for(;aux<final; ++aux){
//A la ultima urna le asignamos al valor max -1 para identificar que es mayor que el min
if(aux==final-1){
aux->min= i*tamanoUrnas;
aux->max= -1;
}
else{
aux->min= i*tamanoUrnas;
aux->max= (i*tamanoUrnas) + tamanoUrnas -1;
}
i++;
printf("Min: %d Max: %d\n", aux->min, aux->max);
}
printf("Favor de ingresar el directorio para comenzar: \n");
scanf(" %[^\n]", currentDir);
recorrerArchivos(currentDir, urnas);
imprimir(urnas);
free(currentDir);
free(urnas);
}
void recorrerArchivos(char * dir, urna * urnas){
DIR * pointer = NULL;
urna * aux = urnas;
urna * final = urnas + numeroUrnas;
struct dirent *sd;
struct stat stats;
char * subDir;
subDir = (char*)malloc(600*sizeof(char));
pointer = opendir(dir);
if(pointer == NULL){
printf("No se pudo abrir el directorio\n");
printf("No esta bien el path o encontro un directorio al que no puede acceder por permisos\n");
imprimir(urnas);
exit(1);
}
while((sd = readdir(pointer))!=NULL){
sprintf(subDir, "%s/%s", dir, sd->d_name);
stat(subDir, &stats);
//printf("Estamos en la carpeta: %s\n", subDir);
if(S_ISDIR(stats.st_mode) && strcmp(sd->d_name, "..")!= 0 && strcmp(sd->d_name, ".")!= 0){
recorrerArchivos(subDir, urnas);
}
else{
if(strcmp(sd->d_name, "..")!= 0 && strcmp(sd->d_name, ".")!= 0){
aux = urnas;
final = urnas + numeroUrnas;
for(;aux<final; ++aux){
//printf("Estamos analizando: %s tiene un tamaño de %ld\n", sd->d_name, stats.st_size);
if((stats.st_size< aux->max && stats.st_size>= aux->min) || (stats.st_size> aux->min && aux->max==-1)){
aux->numArchivos= aux->numArchivos +1;
}
}
}
}
}
closedir(pointer);
free(subDir);
}
void imprimir(urna * urnas){
urna * aux1 = urnas;
urna * final1 = urnas + numeroUrnas;
int cont=0;
printf("Urna NumArchivo Histograma\n");
for(;aux1<final1; ++aux1){
printf("%d-%d %d ", aux1->min, aux1->max, aux1->numArchivos);
//Aqui se controla el número de puntos, 100 es el máximo que va a pintar
if(aux1->numArchivos>100){
cont = 100;
}
else{
cont = aux1->numArchivos;
}
for(int i=0; i<cont; i++){
printf("*");
}
printf("\n");
}
}
|
C
|
/*
randomstring.c
Matthew Meyn
My random tester finds the error message by having inputChar() generate random characters and having
inputString() generate a string of random characters within a relatively small range: each of the 5
non-null characters will be within a range of 5 characters of the corresponding "error" value. This
decreases the amount of time required to get the string "reset". Generating completely random letters
takes a very long time before the string "reset" is produced. But when the chances of finding the "bad"
character (for example, 'r' for the first one) are increased to 1 out of 10 characters rather than 1
out of 26, the "bad" string is very likely to be generated within the first few hundred thousand tries,
often within around 100,000.
*/
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rotate.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tzenz <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/30 17:09:22 by tzenz #+# #+# */
/* Updated: 2020/02/01 15:40:52 by tzenz ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void isometric(int *x, int *y, int z)
{
int pre_x;
int pre_y;
pre_x = *x;
pre_y = *y;
*x = pre_x - pre_y * cos(0.523599);
*y = -z + (pre_x + pre_y) * sin(0.523599);
}
void rotate_x(int *y, int *z, double alpha)
{
int pre_y;
pre_y = *y;
*y = pre_y * cos(alpha) + *z * sin(alpha);
*z = -pre_y * sin(alpha) + *z * cos(alpha);
}
void rotate_y(int *x, int *z, double beta)
{
int pre_x;
pre_x = *x;
*x = pre_x * cos(beta) + *z * sin(beta);
*z = -pre_x * sin(beta) + *z * cos(beta);
}
void rotate_z(int *x, int *y, double gamma)
{
int pre_x;
int pre_y;
pre_x = *x;
pre_y = *y;
*x = pre_x * cos(gamma) - pre_y * sin(gamma);
*y = pre_x * sin(gamma) + pre_y * cos(gamma);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "dog.h"
/**
* new_dog - copies a struc
* @name: dog name
* @age: dog age
* @owner: owner name
* Return: the copied struct
*/
dog_t *new_dog(char *name, float age, char *owner)
{
struct dog *new_dog_reg;
int i = 0, j = 0, k;
char *aka, *master;
if (name == NULL || owner == NULL || age < 0)
return (NULL);
new_dog_reg = malloc(sizeof(struct dog));
if (new_dog_reg == NULL)
{
return (NULL);
}
while (name[i])
i++;
while (owner[j])
j++;
aka = malloc(i * sizeof(char) + 1);
if (aka == NULL)
{
free(new_dog_reg);
return (NULL);
}
master = malloc(j * sizeof(char) + 1);
if (master == NULL)
{
free(aka);
free(new_dog_reg);
return (NULL);
}
for (k = 0; k <= i; k++)
aka[k] = name[k];
for (k = 0; k <= j; k++)
master[k] = owner[k];
new_dog_reg->name = aka;
new_dog_reg->owner = master;
new_dog_reg->age = age;
return (new_dog_reg);
}
|
C
|
#include <assert.h>
int main()
{
char a[] = "a\0b\0";
assert(sizeof a == 5);
assert(a[0] == 'a');
assert(a[1] == '\0');
assert(a[2] == 'b');
assert(a[3] == '\0');
assert(a[4] == '\0');
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "levenshtein.h"
// CLI.
int
main(int argc, char **argv) {
char *a = argv[1];
char *b = argv[2];
if (argc == 2) {
if (!strcmp(a, "-v") || !strcmp(a, "--version")) {
printf("%s", "0.1.1\n");
return 0;
}
if (!strcmp(a, "-h") || !strcmp(a, "--help")) {
printf("%s", "\n");
printf("%s", " Usage: levenshtein <words...>\n");
printf("%s", "\n");
printf("%s", " Levenshtein algorithm CLI\n");
printf("%s", "\n");
printf("%s", " Options:\n");
printf("%s", "\n");
printf("%s", " -h, --help output usage information\n");
printf("%s", " -v, --version output version number\n");
printf("%s", "\n");
printf("%s", " Usage:\n");
printf("%s", "\n");
printf("%s", " # output distance\n");
printf("%s", " $ levenshtein sitting kitten\n");
printf("%s", " # 3\n");
printf("%s", "\n");
return 0;
}
}
if (argc != 3) {
fprintf(stderr, "\033[31mLevenshtein expects two arguments\033[0m\n");
return 1;
}
printf("%zu\n", levenshtein(a, b));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAXBITS 32
void main()
{
int bits[MAXBITS]; // declare array bits, to hold the bits.
int index;
int number;
int num;
number = 16; // choose a number to test the code
printf(" Binary of Decimal %5d = ", number);
index = 0;
while (number > 0)
{
bits[index] = number%2;
number = number / 2;
index = index + 1;
}
for (int i = index - 1; i >= 0; i--)
{
printf(" %1d", bits[i]);
}
printf("\n ");
for (num=100;num<=128;num++)
{
number = num;
index = 0;
while (number > 0)
{
bits[index] = number%2;
number = number / 2;
index = index + 1;
}
for (int i = index - 1; i >= 0; i--)
{
printf(" %1d", bits[i]);
}
printf("\n ");
}
getch();
}
|
C
|
/**
* 希尔排序:C 语言
*
* @author skywang
* @date 2014/03/11
*/
#include <stdio.h>
// 数组长度
#define LENGTH(array) ( (sizeof(array)) / (sizeof(array[0])) )
/*
* 希尔排序
*
* 参数说明:
* a -- 待排序的数组
* n -- 数组的长度
*/
void shell_sort1(int a[], int n)
{
int i,j,gap;
// gap为步长,每次减为原来的一半。
for (gap = n / 2; gap > 0; gap /= 2)
{
// 共gap个组,对每一组都执行直接插入排序
for (i = 0 ;i < gap; i++)
{
for (j = i + gap; j < n; j += gap)
{
// 如果a[j] < a[j-gap],则寻找a[j]位置,并将后面数据的位置都后移。
if (a[j] < a[j - gap])
{
int tmp = a[j];
int k = j - gap;
while (k >= 0 && a[k] > tmp)
{
a[k + gap] = a[k];
k -= gap;
}
a[k + gap] = tmp;
}
}
}
}
}
/*
* 对希尔排序中的单个组进行排序
*
* 参数说明:
* a -- 待排序的数组
* n -- 数组总的长度
* i -- 组的起始位置
* gap -- 组的步长
*
* 组是"从i开始,将相隔gap长度的数都取出"所组成的!
*/
void group_sort(int a[], int n, int i,int gap)
{
int j;
for (j = i + gap; j < n; j += gap)
{
// 如果a[j] < a[j-gap],则寻找a[j]位置,并将后面数据的位置都后移。
if (a[j] < a[j - gap])
{
int tmp = a[j];
int k = j - gap;
while (k >= 0 && a[k] > tmp)
{
a[k + gap] = a[k];
k -= gap;
}
a[k + gap] = tmp;
}
}
}
/*
* 希尔排序
*
* 参数说明:
* a -- 待排序的数组
* n -- 数组的长度
*/
void shell_sort2(int a[], int n)
{
int i,gap;
// gap为步长,每次减为原来的一半。
for (gap = n / 2; gap > 0; gap /= 2)
{
// 共gap个组,对每一组都执行直接插入排序
for (i = 0 ;i < gap; i++)
group_sort(a, n, i, gap);
}
}
void main()
{
int i;
int a[] = {80,30,60,40,20,10,50,70};
int ilen = LENGTH(a);
printf("before sort:");
for (i=0; i<ilen; i++)
printf("%d ", a[i]);
printf("\n");
shell_sort1(a, ilen);
//shell_sort2(a, ilen);
printf("after sort:");
for (i=0; i<ilen; i++)
printf("%d ", a[i]);
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 26
struct node {
char data;
struct node *next;
};
struct node * get_node(){
struct node *p = (struct node *)malloc(sizeof(struct node));
return p;
}
void hash_insert(char c, struct node *hash_table[SIZE]){
int hash_value = c - 'a';
struct node *t = get_node();
t -> data = c;
t -> next = NULL;
//printf("\nhash_value = %d\n", hash_value);
if (hash_table[hash_value] == NULL){
hash_table[hash_value] = t;
}
else{
struct node *k = hash_table[hash_value];
while (k -> next != NULL){
//printf("\n%d\n", k->data);
k = k -> next;
}
k -> next = t;
}
}
void print_table(struct node *table[SIZE]){
for (int i = 0; i < SIZE; i++){
struct node *t = table[i];
int i = 0;
while (t != NULL && i == 0){
printf("%c\t", t -> data);
t = t -> next;
i++;
}
}
printf("\n");
}
void main(){
int n;
scanf("%d", &n);
struct node *hash_table[SIZE];
while (n){
for (int i = 0; i < SIZE; i++){
hash_table[i] = NULL;
}
char c[100];
scanf("%s", c);
int l = strlen(c);
for (int i = 0; i < l ; i++){
hash_insert(c[i], hash_table);
}
print_table(hash_table);
n--;
}
}
|
C
|
#include "SDL2/SDL.h"
#include "constants.h"
void render(SDL_Renderer *renderer, Bird bird, Pipe pipes[])
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
/* SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); */
SDL_Rect bird_rect = {bird.x, bird.y, BIRD_WIDTH, BIRD_HEIGHT};
/* SDL_RenderFillRect(renderer, &bird_rect); */
SDL_RenderCopy(renderer, bird.texture, NULL, &bird_rect);
for (int i = 0; i < 5; i++)
{
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_Rect pipe_top_rect = {pipes[i].x, 0, PIPE_WIDTH, pipes[i].y};
SDL_RenderFillRect(renderer, &pipe_top_rect);
SDL_Rect pipe_bottom_rect = {pipes[i].x, pipes[i].y + GAP, PIPE_WIDTH, HEIGHT};
SDL_RenderFillRect(renderer, &pipe_bottom_rect);
}
SDL_RenderPresent(renderer);
}
|
C
|
#include "sys.h"
#include "stdio.h"
uint32_t sys_call_table[SYSCALL_MAX_SIZE];
static void set_sys_call(int num, uint32_t sys_call);
void init_sys_call()
{
//1.查看内存中进程数量的系统调用
set_sys_call(SYS_PROC_NUM, (uint32_t) sys_get_proc_num);
//2.清屏
set_sys_call(SYS_WRITE_CLEAR, (uint32_t) sys_write_clear);
//3.进程退出
set_sys_call(SYS_EXIT, (uint32_t) sys_exit);
//51.内核打印函数
set_sys_call(SYS_WRITE, (uint32_t) sys_write);
//52.获取进程ID
set_sys_call(SYS_PROC_PID, (uint32_t) sys_get_proc_pid);
//53杀死进程
set_sys_call(SYS_KILL, (uint32_t) sys_kill);
//102.发送中断
set_sys_call(SYS_SEND_INT, (uint32_t) sys_send_interrupt);
//103.接收中断
set_sys_call(SYS_RECV_INT, (uint32_t) sys_recv_interrupt);
//151.内核打印函数
set_sys_call(SYS_WRITE_COLOR, (uint32_t) sys_write_color);
//152
set_sys_call(SYS_SEND_MESSAGE, (uint32_t) sys_send_message);
//153
set_sys_call(SYS_RECV_MESSAGE, (uint32_t) sys_recv_message);
}
static void set_sys_call(int num, uint32_t sys_call)
{
sys_call_table[num] = sys_call;
}
|
C
|
#include "stdio.h";
#include "stdlib.h";
#include "io.h";
#include "math.h";
#include "time.h";
#define OK 1;
#define ERROR 0;
#define TRUE 1;
#define FALSE 0;
#define MAXSIZE 1000;
typedef int QElementType;
typedef struct QNode
{
QElementType data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct
{
QueuePtr front, rear;
} LinkQueue;
// 插入元素
Status EnQueue(LinkQueue *Q, QElementType e)
{
QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
if (!s)
{
exit(OVERFLOW)
}
s->data = e;
s->next = NULL;
Q->rear->next = s;
Q->rear = s;
return OK;
}
// 队头删除元素
Status DeQueue(LinkQueue *Q, QElementType *e)
{
QueuePtr p;
if (Q->front == Q->rear)
{
return ERROR
}
p = Q->front->next;
*e = p->data;
Q->front->next = p->next;
if (Q->rear == p)
{
Q->rear = Q->front;
}
free(p);
return OK;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
#include"server.h"
#include <sys/stat.h>
#include<fcntl.h>
#include<sys/sendfile.h>
#include<sys/wait.h>
typedef struct sockaddr sockaddr;
typedef struct sockaddr_in sockaddr_in;
//一次从socket中读取一行数据
//把数据放到buf缓冲区中
//如果读取失败,返回-1
//\n \r \r\n
int ReadLine(int sock,char buf[],ssize_t size){
//从socket中一次读取一个字符
char c='\0';
ssize_t i=0;//当前读了多少字符
//结束条件:
//a) 读的长度太长,达到了缓冲区长度的上限
//b) 读到了\n(此处我们要兼容\r \r\n的情况,如果遇到\r\n或者\r 想办法换成\n
while(i<size-1&&c!='\n'){
ssize_t read_size=recv(sock,&c,1,0);
if(read_size<=0){
//预期是读到\n这样的换行符,结果还没读到呢,
//就先读到了EOF,这种情况我们也暂时认为是失败
return -1;
}
if(c=='\r'){
//当前遇到了\r,但是还需要确定下一个字符是不是\n
//MSG_PEEK 选项从内核的缓冲区中读数据
//但是读到的数据不会从缓冲区中删除掉
recv(sock,&c,1,MSG_PEEK);
if(c=='\n'){
recv(sock,&c,1,0);
}else{
c='\n';
}
}
buf[i++]=c;
}
buf[i]='\0';
return i;//实际读到的字符个数
//如果读到\n就返回
}
int split(char input[],char*split_char,char *output[],int output_size){
// strtok不是一个线程安全的函数。因为根据其定义,它必须使用
// 内部静态变量来记录字符串中下一个需要解析的标记的当前位置。
// 但是,由于指示这个位置的变量只有一个,那么,在同一个程序中出
// 现多个解析不同字符串的strtok调用时,各自的字符串的解析就会互相干扰。所以使用strtok_r
//strtok_r会破坏待分解字符串的完整性,但是将剩余字符串保存在手动传入的缓冲区中。保证了安全性。
int i=0;
char *pch;
char*tmp=NULL;//strtok_r需要手动传入缓冲区
pch=strtok_r(input,split_char,&tmp);
while(pch!=NULL){
if(i>=output_size){
return i;
}
output[i++]=pch;
pch=strtok_r(NULL,split_char,&tmp);
}
return i;
}
int ParseFirstLine(char first_line[],char**p_url,char**p_method){
//把首行按照空格进行字符串切分
char *tok[10];
//切分得到的每一个部分,就放到tok数组之中
//返回值就是tok数组中包含几个元素
//最后一个参数10表示tok数组中最多能放几个元素
int tok_size=split(first_line," ",tok,10);
if(tok_size!=3){//切分出来的是 方法 url 版本号
printf("Split failed! tok_size=%d\n",tok_size);
return -1;
}
*p_method=tok[0];
*p_url=tok[1];
return 0;
}
int ParseQueryString(char*url,char**p_url_path,char**p_query_string){
*p_url_path=url;
char*p=url;
for(;*p!='\0';++p){
if(*p=='?'){
*p='\0';
*p_query_string=p+1;
return 0;
}
}
//循环结束都没找到?,说明这个请求不带query_string
*p_query_string=NULL;
return 0;
}
int ParseHeader(int sock,int *content_length){
char buf[SIZE]={0};
while(1){
//1循环从socket中读取一行
size_t read_size=ReadLine(sock,buf,sizeof(buf));
//处理读失败的情况
if(read_size<=0){
return -1;
}
//处理读完的情况,读到空行
if(strcmp(buf,"\n")==0){
return 0;
}
//2 判定当前行是不是Content-Length
//如果是,就直接把value读出来
//如果不是就丢弃
//strncmp比较字符串前n个字符是否相等
const char*content_length_str="Content-Length: ";
if(content_length!=NULL&&strncmp(buf,content_length_str,strlen(content_length_str))==0){
*content_length=atoi(buf+strlen(content_length_str));//只把value的值赋给content_length
}
}
return 0;
}
void Handler404(int sock){
//构造一个完整的HTTP响应
//状态码就是404
//body部分应该也是一个404页面
const char * first_line="HTTP/1.1 404 NOT Found\n";
const char* blank_line="\n";
const char* type_line="\" Content-Type:\"\" text/html;charset=utf-8\"\n";//在headler部分也加上,增强代码的健壮性,保证
//任何浏览器都不乱码
const char* html="<head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"> </head>"
"<h1>404 Nou Found 您的页面不小心走丢了了!!!!</h1>";
send(sock,first_line,strlen(first_line),0);
send(sock,type_line,strlen(type_line),0);
send(sock,blank_line,strlen(blank_line),0);
send(sock,html,strlen(html),0);
return;
}
int IsDir(const char* file_path){//判断是文件还是目录
struct stat st;
int ret=stat(file_path,&st);//stat可以获取到file_path的详细信息,存放在结构体st中
if(ret<0){//文件不存在,表示不是目录
return 0;
}
if(S_ISDIR(st.st_mode)){//通过S_ISDIR这个宏来判定file_path是否是一个目录,st.mode保存的是文件类型
return 1;
}
return 0;
}
void HandlerFilePath(const char*url_path,char file_path[]){
//HTTP服务器的根目录:用户指定的任意一个存在的目录
//url_path =>/index.html
//file_path=>./wwwroot/index.html
//a)给 url_path 加上前缀
sprintf(file_path,"./wwwroot%s",url_path);//字符串拼接
//b)例如:url_path => / 请求的是一个目录,想办法给目录中追加上一个 index.html文件(取一个默认文件)
if(file_path[strlen(file_path)-1]=='/'){//判断file_path最后一个字符是否是‘\’
strcat(file_path,"index.html");
}
//c) 例如 url_path => /image无法确定是文件还是目录,需要判定
if(IsDir(file_path)){
strcat(file_path,"/index.html");
}
return;
}
ssize_t GetFileSize(const char*file_path){
struct stat st;
int ret=stat(file_path,&st);
if(ret<0){
//打开文件失败,很可能文件不存在
//此时返回的文件长度为0
return 0;
}
return st.st_size;
}
int WriteStaticFile(int sock,const char*file_path){
//1 打开文件
//什么情况下会打开文件失败 a) 文件描述符不够用 b) 文件不存在
int fd=open(file_path,O_RDONLY);
if(fd<0){
perror("open");
return 404;
}
//2 把构造出的HTTP响应写入到socket之中
//a)写入首行
const char* first_line="HTTP/1.1 200 OK\n";
send(sock,first_line,strlen(first_line),0);
//b)写入header
//可根据扩展名来显示类型,但现在绝大多数浏览器都能自动匹配类型,根据扩展名自动匹配类型
const char* type_line=" Content-Type: text/html;charset=utf-8\n";//文本类型
//const char* type_line="\" Content-Type:\"\" image/jpg;charset=utf-8\"\n";//图片类型
send(sock,type_line,strlen(type_line),0);
//c)写入空行
const char* blank_line="\n";
send(sock,blank_line,strlen(blank_line),0);
//d)写入body(文件内容)
/*不够高效
//把文件中所有的文件一个字节一个字节的读取出来再一个字节一个字节写入sock
ssize_t file_size=GetFileSize(file_path);//获取到文件的总字节数
ssize_t i=0;
for(;i<file_size;i++){
char c;
read(fd,&c,1);//系统调用不够高效,设计从内核向用户缓存拷贝数据
send(sock,&c,1,0);//涉及从用户缓存向网卡中拷贝数据
}
*/
sendfile(sock,fd,NULL,GetFileSize(file_path));//直接从内核到内核的拷贝
//避免了内核和用户之间得来回拷贝,从fd拷贝到网卡上,NULL表示从起始
//位置开始拷贝
//3 关闭文件
close(fd);
return 200;
}
int HandlerStaticFile(int sock,Request*req){//静态生成页面
//1 根据 url_path 获取到文件在服务器上的真实路径
char file_path[SIZE]={0};//用来保存文件的真实路径
HandlerFilePath(req->url_path,file_path);//利用url来找到文件的真实路径
//2 读取文件,把文件的内容直接写回到socket之中
int err_code=WriteStaticFile(sock,file_path);
return err_code;
}
int HandlerCGIFather(int new_sock,int father_read,int father_write,int child_pid,Request*req){
//如果是post请求,就把body写入到管道
if(strcasecmp(req->method,"POST")==0){
int i=0;
char c='\0';
for(;i<req->content_length;i++){
read(new_sock,&c,1);
write(father_write,&c,1);
}
}
//2 构造HTTP响应
const char*first_line="HTTP/1.1 200 OK\n";
send(new_sock,first_line,strlen(first_line),0);
const char* type_line="\" Content-Type:\"\" text/html;charset=utf-8\"\n";
send(new_sock,type_line,strlen(type_line),0);
const char* blank_line="\n";
send(new_sock,blank_line,strlen(blank_line),0);
//循环从管道中读取数据,并写入到socket
char c='\0';
while(read(father_read,&c,1)>0){//读管道,读到EOF返回0,什么
//时候读到EOF,写端全部关闭,再尝试继续读,会读到EOF,管道读端
//关闭,再尝试写,会产生SIDPIPE信号,导致进程异常终止
send(new_sock,&c,1,0);
}
//4.回收子进程的资源
waitpid(child_pid,NULL,0);//回收对应的子进程
return 200;
}
int HandlerCGIChild(int child_read,int child_write,Request*req){
//1.设置环境变量
char method_env[SIZE]={0};
sprintf(method_env,"REQUEST_METHOD=%s",req->method);
putenv(method_env);
//还需要设置 QUERY_STRING 或者 CONTENT_LENGTH
if(strcasecmp(req->method,"GET")==0){
char query_string_env[SIZE]={0};
sprintf(query_string_env,"QUERY_STRING=%s",req->query_string);
putenv(query_string_env);
}else{
char content_length_env[SIZE]={0};
sprintf(content_length_env,"CONTENT_LENGTH=%d",req->content_length);
putenv(content_length_env);
}
//2.把标准输入,标准输出重定向到管道中
dup2(child_read,0);
dup2(child_write,1);
//3.对子进程进行程序替换
// url_path: /cgi-bin/test
// file_path: ./wwwroot/cgi-bin/test
char file_path[SIZE]={0};
HandlerFilePath(req->url_path,file_path);
//l
//lp
//le
//v
//vp
//ve
execl(file_path,file_path,NULL);
return 200;
}
int HandlerCGI(int new_sock,Request*req){//动态生成页面
//1.创建一对匿名管道
int fd1[2],fd2[2];
int ret=pipe(fd1);
if(ret<0){
return 404;
}
ret=pipe(fd2);
if(ret<0){
//第二个管道创建失败,记得要关闭第一个管道
//的读端和写端
close(fd1[0]);
close(fd2[1]);
return 404;
}
// fd1 fd2 这样的变量名描述性太差,后边直接使用的话
// 是非常容易弄混淆的,所以直接在此处定义几个更加明确
// 的变量来描述该文件描述符的用途。
int father_read=fd1[0];
int child_write=fd1[1];
int father_write=fd2[1];
int child_read=fd2[0];
//2.创建子进程
ret=fork();
//3.父子进程各自执行不同的逻辑
if(ret>0){
//farther
//注意关掉父进程不用的文件描述符
//此处父进程优先关闭这俩个管道的文件描述符
//是为了后续父进程从子进程这里读数据的时候
//能够读到EOF,对于管道来说,所有的写端关闭
//,继续读,才有EOF,而此处所有的写端,一方面
//是父进程需要关闭,另一方面子进程也需要关闭
//所以此处父进程先关闭不必要的写端置之后,后
//续子进程用完了,直接关闭,父进程也就直接读到了
//EOF
close(child_read);
close(child_write);
int err_code=HandlerCGIFather(new_sock,father_read,father_write,ret,req);
}else if(ret==0){
//child
//注意关掉子进程不用的文件描述符
close(father_read);
close(father_write);
int err_code=HandlerCGIChild(child_read,child_write,req);
}else{
perror("fork");
close(fd1[0]);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
return 404;
}
//4.收尾工作和错误处理
}
void HandlerRequest(int new_sock){
int err_code=200;
//1.读取并解析请求
Request req;
memset(&req,0,sizeof(req));
//a)从socket中读取首行
if(ReadLine(new_sock,req.first_line,sizeof(req.first_line))<=0){
//todo失败处理
err_code=404;
goto END;
}
//b)从首行中解析出url和method
if(ParseFirstLine(req.first_line,&req.url,&req.method)<0){
//todo失败处理
err_code=404;
goto END;
}
//c)解析url,从url中解析出url_path,query_string
if(ParseQueryString(req.url,&req.url_path,&req.query_string)<0){
//todo失败处理
err_code=404;
goto END;
}
//处理header,丢弃了大部分header,只处理content-length
if(ParseHeader(new_sock,&req.content_length)<0){
//todo失败处理
err_code=404;
goto END;
}
printf("method: %s\n",req.method);
printf("url_path: %s\n",req.url_path);
printf("query_string: %s\n",req.query_string);
printf("content_length: %d\n",req.content_length);
//2.静态、动态生成页面,把生成页面写回客户端
//假如浏览器发送的请求方法叫“get”/"GET",不区分大小写的比较
//如果请求是get请求并且没有query_string,那么就返回静态页面
if(strcasecmp(req.method,"GET")==0
&&req.query_string==NULL){
err_code=HandlerStaticFile(new_sock,&req);
}
//如果是get请求,有query_string,那么就返回动态页面
else if(strcasecmp(req.method,"GET")==0
&&req.query_string!=NULL){
err_code=HandlerCGI(new_sock,&req);
}
//如果是post请求(一定是带参数的,参数是通过body来传给服务器的),那么也返回动态页面
else if(strcasecmp(req.method,"POST")==0){
err_code=HandlerCGI(new_sock,&req);
}else{//收到其他方法
//todo错误处理
err_code=404;
goto END;
}
//错误处理:直接返回一个404的HTTP响应
END:
if(err_code!=200){
Handler404(new_sock);
}
close(new_sock);
return;
}
void * ThreadEntry(void * arg){
int64_t new_sock=(int64_t)arg;
//此处HandlerRequest作用是为了解耦合,一旦需要把服务器改成多进程或者IO多路复用
//整体代码的改动都是比较小的
HandlerRequest(new_sock);
return NULL;
}
//服务器启动
void HttpServerStart(const char*ip,short port){
int listen_sock=socket(AF_INET,SOCK_STREAM,0);
if(listen_sock<0){
perror("socket");
return;
}
//设置,使得可重用Time-wait状态
int opt=1;
setsockopt(listen_sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr(ip);//将点分十进制的ip地址转换成32位的
addr.sin_port=htons(port);//主机序的字节序转换为网络序的字节序
int ret=bind(listen_sock,(sockaddr*)&addr,sizeof(addr));
if(ret<0){
perror("bind");
return;
}
ret=listen(listen_sock,5);
if(ret<0){
perror("listern");
return;
}
printf("Server Init Ok\n");
while(1){
sockaddr_in peer;//对端ip,端口号
socklen_t len=sizeof(peer);
int64_t new_sock=accept(listen_sock,(sockaddr*)&peer,&len);
if(new_sock<0){
perror("accept");
continue;
}
//使用多线程来实现Tcp服务器
pthread_t tid;
pthread_create(&tid,NULL,ThreadEntry,(void *)new_sock);
pthread_detach(tid);
}
}
//./server [ip] [port]
int main(int argc,char*argv[]){
if(argc!=3){
printf("Usage ./server [ip] [port]\n");
return 1;
}
HttpServerStart(argv[1],atoi(argv[2]));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Circular_Dupla.h"
struct tipo_lista
{
int valor;
struct tipo_lista *pred;
struct tipo_lista *prox;
};
CircularDupla *criar()
{
return NULL;
}
CircularDupla *alocar(int valor)
{
CircularDupla *novo = (CircularDupla *) malloc (sizeof(CircularDupla));
if(novo == NULL)
{
printf("Erro na reserva de memoria");
}
else
{
novo->valor = valor;
novo->pred = NULL;
novo->prox = NULL;
}
return novo;
}
CircularDupla *inserirFim(CircularDupla* L, int valor)
{
CircularDupla *novo=alocar(valor);
if(L==NULL)
{
L=novo;
L->prox=L;
L->pred=L;
}
else
{
novo->prox=L;
novo->pred=L->pred;
L->pred->prox=novo;
L->pred=novo;
}
return L;
}
CircularDupla *inserirInicio(CircularDupla* L, int valor)
{
CircularDupla *novo = alocar(valor);
if(L==NULL)
{
L=novo;
L->prox=L;
L->pred=L;
}
else
{
novo->prox=L;
novo->pred=L->pred;
L->pred->prox=novo;
L->pred = novo;
L=novo;
}
return L;
}
CircularDupla *inserirOrdem(CircularDupla *L, int valor)
{
CircularDupla *aux=L, *novo=alocar(valor);
if(L==NULL)
{
L=novo;
L->prox=L;
L->pred=L;
}
else
{
do
{
if(aux->valor>aux->prox->valor)
{
//if(aux->pred->valor<aux->valor){
aux->pred->prox=novo->pred;
aux->prox->pred=novo->prox;
}
//}
else
{
aux=aux->prox;
}
}
while(aux!=L);
}
return L;
}
CircularDupla *buscar(CircularDupla *L, int dado)
{
CircularDupla *aux, *achou=NULL;
aux = L;
do
{
if(aux->valor==dado)
{
achou=aux;
break;
}
else
{
aux=aux->prox;
}
}
while(aux!=L);
return achou;
}
void mostrar(CircularDupla *L)
{
CircularDupla *aux;
aux = L;
if (aux == NULL)
{
printf("Lista vazia!");
}
else
{
do
{
printf("\n__________________________");
printf("\n%i", aux->valor);
printf("\n__________________________");
aux = aux->prox;
}
while(aux!=L);
}
}
CircularDupla *excluir (CircularDupla *L, int dado)
{
CircularDupla *aux = buscar(L, dado);
printf("%d", aux->valor);
if (aux != NULL)
{
if (aux == L)
{
if(aux->prox == L)
{
free(aux);
L = NULL;
return L;
}
L = aux->prox;
}
if (aux == L->pred)
{
L->pred = aux->pred;
}
aux->prox->pred = aux->pred;
aux->pred->prox = aux->prox;
free(aux);
return L;
}
else
{
printf("\nElemento nao encontrado");
}
return L;
}
void liberar(CircularDupla *L)
{
CircularDupla *excluir;
while(L!=NULL)
{
excluir=L;
L=L->prox;
free(excluir);
}
free(L);
}
|
C
|
/*
** main.c for sources in /home/dabbec_j/projets/sysunix/allum1/sources
**
** Made by jalil dabbech
** Login <[email protected]>
**
** Started on Tue Jul 02 12:18:27 2013 jalil dabbech
** Last update Sat Jul 13 05:42:33 2013 jalil dabbech
*/
#include <stdlib.h>
#include <unistd.h>
#include "my_printf.h"
#include "my_allum1.h"
#include "my.h"
t_opt g_opt[] =
{
{"-r", "--rows", &set_nbrows},
{"-p", "--player", &set_nbplayer},
{"-h", "--help", &show_help}
};
void check_option(char *str, int j)
{
if (str[0] == '-' && j == 3)
{
write(2, "./allum1: Unknow option ", 24);
write(2, str, my_strlen(str));
write(2, "\n", 1);
exit(EXIT_FAILURE);
}
}
void check_args(int *nbr, char **av)
{
int j;
int i;
i = 1;
while (av[i])
{
j = 0;
while (j < 3)
{
if (my_strcmp(av[i], g_opt[j].short_str) == 0 ||
my_strcmp(av[i], g_opt[j].long_str) == 0)
{
g_opt[j].fct(nbr, my_getnbr(av[i + 1]));
j = 4;
}
j++;
}
check_option(av[i], j);
i++;
}
}
int main(int ac, char **av)
{
int *nbr;
if (!(nbr = malloc(2 * sizeof(int))))
return (-1);
nbr[ROWS] = 20;
nbr[PLAYERS] = 1;
if (ac > 1)
check_args(nbr, av);
my_allum(nbr);
free(nbr);
return (0);
}
|
C
|
#include "declerations.h"
// a function that gets a command and a list of apartments and adds the apartmets to the list's tail
void addAnApt(char** command, List* list,int* code) {
char* copy = NULL;
char* address = NULL;
char* temp;
int price;
short int rooms;
Date date;
//cTime avaluation
time_t currentTime;
struct tm* tm;
Date sDate;
time(¤tTime);
sDate.hours = currentTime / 3600;
tm = localtime(¤tTime);
sDate.day = tm->tm_mon + 1;
sDate.month = tm->tm_mday;
sDate.year = tm->tm_year + 1900;
sDate.year = (tm->tm_year + 1900) % 100;
// apartmet fieds avaluation
copyString(©, *command);
temp = strtok(copy, "\"");
temp = strtok(NULL, "\"");
copyString(&address, temp);
price = atoi(strtok(NULL, " "));
rooms = atoi(strtok(NULL, " "));
date.day = atoi(strtok(NULL, " "));
date.month = atoi(strtok(NULL, " "));
date.year = atoi(strtok(NULL, " "));
insertDataToEndList(list, *code, address, rooms, price, sDate, date, NULL);
(*code)++;
free(copy);
}
// a function that creates an empty list
List makeEmptyList() {
List res;
res.head = calloc(1, sizeof(Apartment));
res.head->next = NULL;
res.tail = res.head;
return res;
}
// a function that gets an apartment's data and ads a new apartment to the list's tail
void insertDataToEndList(List* lst, int code, char* adress, short int rooms, int price, Date sDate, Date date, Apartment* next) {
Apartment* newApt;
newApt = createApartment(code, adress, rooms, price, sDate, date, next);
insertNodeToTail(lst, newApt);
}
// a function that creats a node of an a partment
Apartment* createApartment(int code, char* adress, short int rooms, int price, Date sDate, Date date, Apartment* next) {
Apartment* res;
res = calloc(1, sizeof(Apartment));
res->adress = adress;
res->code = code;
res->date = date;
res->next = next;
res->price = price;
res->rooms = rooms;
res->dbDate = sDate;
return res;
}
// a function that inserts a node to the tail of the list of the apartments
void insertNodeToTail(List* lst, Apartment* node) {
if (isEmpty(*lst)) {
lst->head->next = node;
}
else {
lst->tail->next = node;
}
lst->tail = node;
}
// a function that checks if a list is empty
bool isEmpty(List lst) {
return lst.head->next == NULL;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int t,length,count,i,k;
long long int a;
char *b,*c;
char d;
b = malloc( 200*sizeof(char) );
c = malloc( 200*sizeof(char) );
scanf("%d",&t);
while(t--)
{
count=0;
scanf("%s",b);
length= strlen(b);
for(i=0;i<length;i++)
{
if(b[i]>='0' && b[i]<='9')
{
c[count++] = b[i];
}
else
{
c[count]='\0';
a = atoi(c);
count=0;
d=b[i];
k=i;
break;
}
}
for(;i<length;i++)
{
if(b[i]>='0' && b[i]<='9')
{
c[count++] = b[i];
printf("%c\n",c[count-1]);
}
else
{
c[count]='\0';
if(d=='+')
{
a=a+ atoi(c);
printf("%d\n",atoi(c));
}
if(d=='*')
{
a*= atoi(c);
}
if(d=='-')
{
a-= atoi(c);
}
if(d=='/')
{
a/= atoi(c);
}
count=0;
d=b[i];
}
}
printf("%lld\n",a);
}
return 0;
}
|
C
|
#include "substances.h"
static double min(double a, double b){
return (a < b ? a : b);
}
inline double substances_calculate_alcohol_dose(Person * p_person){
return 0.0;
}
double substances_calculate_MDMA_dose(Person * p_person){
// A "linear dose" in milligrams; 1.5 mg/kg * body_mass
double linear_dose = 1.5 * p_person->body_mass;
// A "safer dose" that heavier people with a "normal" or
// "fast" metabolism should opt for if the linear dose
// exceeds this one. Given in milligrams.
double threshold_dose = 50 + p_person->body_mass;
// The "safest dose" (except for no dose), that should
// always be the upper limit for people with a "slow"
// metabolism, regardless of body mass.
// Given in milligrams.
double safest_dose = 120;
double mdma_dose;
if(p_person->metabolism == METABOLISM_SLOW){
mdma_dose = min(linear_dose, safest_dose);
}
else{
mdma_dose = min(linear_dose, threshold_dose);
}
return mdma_dose;
}
|
C
|
/*Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
*/
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
if (matrixRowSize == 0 || matrixColSize == 0)
{
return false;
}
if (matrix[0][0] > target)
{
return false;
}
if (matrix[matrixRowSize - 1][matrixColSize - 1] < target)
{
return false;
}
int x = matrixRowSize - 1;
int y = 0;
while (x >= 0 && y < matrixColSize)
{
if (matrix[x][y] == target)
return true;
else if (matrix[x][y] > target)
x--;
else
y++;
}
return false;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
double myPower(double num, int order);
double myRoot(double num, int order, double precision);
int main(void)
{
double num1, num2;
int order1, order2;
double preci;
printf("제곱할 값(실수)과 차수(정수)를 입력하세요 ");
scanf("%lf %d", &num1, &order1);
printf("%f의 %d제곱: %f\n", num1, order1, myPower(num1, order1));
printf("제곱근을 구할 값과 차수, 정밀도를 입력하세요 ");
scanf("%lf %d %lf", &num2, &order2, &preci);
printf("%f의 %d제곱근: %.12f\n", num2, order2, myRoot(num2, order2, preci));
return 0;
}
double myPower(double num, int order)
{
int i;
double result = 1;
if (order == 0)
return 1;
else if (order > 0) {
for (i = 0; i < order; i++)
result *= num;
return result;
}
else {
for (i = 0; i < -order; i++)
result *= num;
return 1 / result;
}
}
double myRoot(double num, int order, double precision)
{
double rnum, lnum, mnum, pnum;
if (num > 0)
{
rnum = num;
lnum = 0;
while (1) {
mnum = (rnum + lnum) / 2;
pnum = myPower(mnum, order);
if (pnum < num)
lnum = mnum;
else if (pnum > num)
rnum = mnum;
if (pnum < num + precision && pnum > num - precision)
return mnum;
}
}
return -1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
typedef int element;
typedef struct DQNode {
element data;
struct DQNode *llink;
struct DQNode *rlink;
}DQNode;
typedef struct {
DQNode *front, *rear;
}DQueType;
DQueType* createDQue() {
DQueType *DQ;
DQ = (DQueType*)malloc(sizeof(DQueType));
DQ->front = NULL;
DQ->rear = NULL;
return DQ;
}
bool isEmpty(DQueType *DQ) {
if (DQ->front == NULL) {
printf("\n Linked Queue is empty!\n");
return true;
}
else return false;
}
void insertFront(DQueType *DQ, element item) {
DQNode *newNode = (DQNode*)malloc(sizeof(DQNode));
newNode->data = item;
if (DQ->front == NULL) {
DQ->front = newNode;
DQ->rear = newNode;
newNode->rlink = NULL;
newNode->llink = NULL;
}
else {
DQ->front->llink = newNode;
newNode->rlink = DQ->front;
newNode->llink = NULL;
DQ->front = newNode;
}
}
void insertRear(DQueType *DQ, element item) {
DQNode *newNode = (DQNode*)malloc(sizeof(DQNode));
newNode->data = item;
if (DQ->rear == NULL) {
DQ->front = newNode;
DQ->rear = newNode;
newNode->rlink = NULL;
newNode->llink == NULL;
}
else {
DQ->rear->rlink = newNode;
newNode->rlink = NULL;
newNode->llink = DQ->rear;
DQ->rear = newNode;
}
}
element deleteFront(DQueType *DQ) {
DQNode *old = DQ->front;
element item;
if (isEmpty(DQ)) return 0;
else {
item = old->data;
if (DQ->front->rlink == NULL) {
DQ->front == NULL;
DQ->rear = NULL;
}
else {
DQ->front = DQ->front->rlink;
DQ->front->llink = NULL;
}
free(old);
return item;
}
}
element deleteRear(DQueType *DQ) {
DQNode *old = DQ->rear;
element item;
if (isEmpty(DQ)) return 0;
else {
item = old->data;
if (DQ->rear->llink == NULL) {
DQ->front = NULL;
DQ->rear = NULL;
}
else {
DQ->rear = DQ->rear->llink;
DQ->rear->rlink = NULL;
}
free(old);
return item;
}
}
element peekFront(DQueType *DQ) {
element item;
if (isEmpty(DQ)) return 0;
else {
item = DQ->front->data;
return item;
}
}
element peekFront(DQueType *DQ) {
element item;
if (isEmpty(DQ)) return 0;
else {
item = DQ->rear->data;
return item;
}
}
void printDQ(DQueType *DQ) {
DQNode *temp = DQ->front;
printf("DeQue: ");
while (temp) {
printf("%3d", temp->data);
temp = temp->llink;
}
printf("\n");
}
int main() {
return 0;
}
|
C
|
/* queue.h -- Queue的接口 */
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include <stdbool.h>
// 在这里插入Item类型的定义,例如
typedef struct item {
long arrive; //一位顾客加入队列的时间
int processtime; //该顾客咨询时花费的时间
} Item;
// 或者 typedef struct item {int gumption; int charisma;} Item;
#define MAXQUEUE 10
typedef struct node{
Item item;
struct node * next;
} Node;
typedef struct queue {
Node * front; /* 指向队列首项的指针 */
Node * rear; /* 指向队列尾项的指针 */
int items; /* 队列中的项数 */
} Queue;
/* 操作: 初始化队列 */
/* 前提条件: pq 指向一个队列 */
/* 后置条件: 队列被初始化为空 */
void InitializeQueue(Queue * pq);
/* 操作: 检查队列是否已满 */
/* 前提条件: pq 指向之前被初始化的队列 */
/* 后置条件: 如果队列已满则返回true,否则返回false */
bool QueueIsFull(const Queue * pq);
/* 操作: 检查队列是否为空 */
/* 前提条件: pq 指向之前被初始化的队列 */
/* 后置条件: 如果队列为空则返回true,否则返回false */
bool QueueIsEmpty(const Queue *pq);
/* 操作: 确定队列中的项数 */
/* 前提条件: pq 指向之前被初始化的队列 */
/* 后置条件: 返回队列中的项数 */
int QueueItemCount(const Queue * pq);
/* 操作: 在队列末尾添加项 */
/* 前提条件: pq 指向之前被初始化的队列 */
/* item是要被添加在队列末尾的项 */
/* 后置条件: 如果队列不为空,item将被添加在队列的末尾, */
/* 该函数返回true;否则,队列不改变,该函数返回false*/
bool EnQueue(Item item, Queue * pq);
/* 操作: 从队列的开头删除项 */
/* 前提条件: pq 指向之前被初始化的队列 */
/* 后置条件: 如果队列不为空,队列首端的item将被拷贝到*pitem中 */
/* 并被删除,且函数返回true; */
/* 如果该操作使得队列为空,则重置队列为空 */
/* 如果队列在操作前为空,该函数返回false */
bool DeQueue(Item *pitem, Queue * pq);
/* 操作: 清空队列 */
/* 前提条件: pq 指向之前被初始化的队列 */
/* 后置条件: 队列被清空 */
void EmptyTheQueue(Queue * pq);
#endif
|
C
|
/*
* 120b_lab5_ex2.c
*
* Created: 10/18/2019 11:52:48 AM
* Author : Matthew L
*/
#include <avr/io.h>
enum States{init, inc, dec, zero, wait, wait2} state;
unsigned char button0;
unsigned char button1;
unsigned char tempC;
void button_Press(){
button0 = ~PINA & 0x01;
button1 = ~PINA & 0x02;
switch(state){ // Transitions
case init:
if(!button0 && !button1){
state = init;
}
else if(button0 && !button1){
state = inc;
}
else if(!button0 && button1){
state = dec;
}
else if(button0 && button1){
state = zero;
}
break;
case inc:
if(button0 && button1){
state = zero;
}
else{
state = wait2;
}
break;
case dec:
if(button0 && button1){
state = zero;
}
else{
state = wait2;
}
break;
case zero:
if(!button0 && !button1){
state = init;
}
else if (button0 && !button1){
state = inc;
}
else if(!button0 && button1){
state = dec;
}
else if(button0 && button1){
state = zero;
}
break;
case wait:
if(button0 && button1){
state = zero;
}
else if(button0 && !button1){
state = inc;
}
else if(!button0 && button1){
state = dec;
}
else{
state = wait;
}
break;
case wait2:
if(!button0 && !button1){
state = wait;
}
else if(button0 && button1){
state = zero;
}
else{
state = wait2;
}
break;
}
switch(state){
case init:
break;
case inc:
if(tempC < 9){
tempC = tempC + 1;
}
break;
case dec:
if(tempC > 0){
tempC = tempC - 1;
}
break;
case zero:
tempC = 0;
break;
case wait:
break;
case wait2:
break;
}
}
int main(void)
{
DDRA = 0x00; PORTA = 0xFF;
DDRC = 0xFF; PORTC = 0x00;
// initialize to 0s
state = init;
tempC = 0x07;
/* Replace with your application code */
while (1)
{
button_Press();
PORTC = tempC;
}
}
|
C
|
/******************************************************************************
* The Linux Programming Interface practices.
* File: t_system.c
*
* Author: garyparrot
* Created: 2019/07/31
* Description: Demonstrate system()
******************************************************************************/
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include "print_wait_status.h"
#include "tlpi_hdr.h"
#define MAX_CMD_LED 200
int main(int argc, const char *argv[]){
char str[MAX_CMD_LED];
int status;
for(;;){
printf("Command: ");
fflush(stdout);
if(fgets(str, MAX_CMD_LED, stdin) == NULL)
break;
status = system(str);
printf("system() returned: status=0x%04x (%d,%d)\n", (unsigned int) status, status >> 8, status & 0xff);
if(status == -1)
errExit("system");
else{
if(WIFEXITED(status) && WEXITSTATUS(status) == 127)
printf("(Probably) could not invoke shell\n");
else
printWaitStatus(NULL, status);
}
}
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
int main()
{
char ch;
printf("input");
scanf("%c",&ch);
if ( (ch>='a' &&ch<='z')||(ch>='A'&& ch<='Z'))
printf("%c is a alphabet", ch);
else
printf("%c is a not a alphabet", ch);
return 0;
}
|
C
|
#include "process.h"
childArgs processWork(int tNum, pthread_mutex_t *mutex) {
childArgs child;
childArgs *c = &child;
c->pid = getpid();
message mrcv;
key_t key;
int msgid;
long ranges[2];
//ftok to generate unique key
if ((key = ftok("msgq.txt", 70)) == -1) {
perror("ftok");
exit(1);
}
//msgget creates a message queue and returns identifier
if ((msgid = msgget(key, 0666 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
if (msgrcv(msgid, &mrcv, sizeof(mrcv.mesg_text), 1, 0) == -1){
perror("msgrcv");
exit(1);
}
//tknMsg call sends the ranges to the msgqueue
tknMsg(mrcv.mesg_text, ranges);
c->R1 = ranges[0];
c->R2 = ranges[1];
printf("c->minrang: %ld c->maxrang: %ld\n", c->R1, c->R2);
//double the amount of threads since range is between two numbers
int TRSIZE = tNum*2;
long tRanges[TRSIZE];
//partition the range of the process for each thread
prtnRange(c->R1, c->R2, tNum, tRanges, TRSIZE);
pthread_t threads[tNum];
threadArgs args[tNum];
//variable int y accumulater to traverse through ranges for each thread
int y = 0;
//for loop that will assign and initialize all the member variables within
//threadArgs structures for each thread
for (int i = 0; i<tNum; i++) {
threadArgs *ptr = &args[i];
ptr->tid = i+1;
ptr->rNum1 = tRanges[y];
ptr->rNum2 = tRanges[y+1];
ptr->mutex = mutex; //set mutex to address of key (pass mutex by reference)
Array arr;
ptr->t_array = &arr;
initArray(ptr->t_array, ISIZE);
if ( pthread_create(&threads[i], NULL, thread_PrimeCalculate, (void*)ptr) != 0) {
perror("Error: Unable to create thread using pthread_create()");
exit(errno);
}
y += 2;
}
//wait for threads to complete
for(int j=0; j<tNum; j++) {
pthread_join( threads[j], NULL );
}
//print process info from threads
//printf("Process %ld\n", (long)c->pid);
Array tPrimes;
Array *tptr = &tPrimes;
initArray(tptr, ISIZE);
for(int k = 0; k < tNum; k++) {
threadArgs *p = &args[k];
for(unsigned m = 0; m < p->t_array->used; m++)
insertArray(tptr, p->t_array->arr[m]);
//deallocating memory
clearArray(p->t_array);
}
//calculate and store the sum of the threads prime calculations
c->Psum = procSumPrimes(tptr);
//deallocating memory
clearArray(tptr);
printf("sum: %ld\nend of process %ld\n", c->Psum, (long)c->pid);
return child;
}
//method to tokenize message of ranges from parent process and store them into
//an array of type long
void tknMsg(char *msg, long *arr)
{
char *token, //char pointer to array of char to store string after using strtok function
*space = " \t\n\f\r\v"; //char pointer to array to function as delimiter
token = strtok(msg, space);
int i = 0;
while (token != NULL) {
char *p = token;
if(isdigit(*p))
arr[i] = strtol(p, &p, 10);
i++;
token = strtok(NULL, space);
}
}
//function to partition the range among either processes or threads
void prtnRange(long r1 , long r2, int count, long* Ranges, int SIZE) {
long rAmount = (r2 - r1)/count;//range num 2 minus range num 1 (difference between ranges)
int flag; //flag for switch statement to handle uneven partitioning of ranges
for(int i = 0; i < SIZE; i+=2) {
if (r1 < r2)
{
Ranges[i] = r1;
Ranges[i+1] = r1 + rAmount;
flag = (Ranges[i+1] > r2)? 1:0;
switch(flag)
{
case 0:
r1 = Ranges[i+1] + 1;
break;
case 1:
Ranges[i+1] = r2;
break;
}
}
}
}
//function to process the sum of the array passed to it.
long procSumPrimes(Array *ptr) {
long sum = 0;
for(unsigned n = 0; n < ptr->used; n++) {
sum += ptr->arr[n];
}
return sum;
}
|
C
|
/*
* 返回值演示
* */
#include <stdio.h>
int read(void) {
int val = 0;
printf("请输入一个数字:");
scanf("%d", &val);
return val;
}
int main() {
int val = read();
printf("val是%d\n", val);
return 0;
}
|
C
|
#include <stdio.h>
#include "atomic.h"
#define PRINT_VALUE(msg) \
printf(#msg": a = %d\n", atomic_read(&a));
int main()
{
atomic_t a = ATOMIC_INIT(9);
int c;
PRINT_VALUE("initial");
atomic_add(4, &a);
PRINT_VALUE("add 4");
atomic_sub(5, &a);
PRINT_VALUE("sub 5");
atomic_inc(&a);
PRINT_VALUE("inc");
atomic_dec(&a);
PRINT_VALUE("dec");
c = atomic_sub_and_test(8, &a);
printf("sub and test 10: %d, %d\n", atomic_read(&a), c);
c = atomic_inc_and_test(&a);
printf("inc and test: %d, %d\n", atomic_read(&a), c);
c = atomic_dec_and_test(&a);
printf("dec and test: %d, %d\n", atomic_read(&a), c);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
#include "float_vec.h"
#include "barrier.h"
#include "utils.h"
void swap_float(float * a, float * b)
{
float t = *a;
*a = *b;
*b = t;
}
int qsort_partition(float * data, int left, int right)
{
float pivot = data[right];
int i = left - 1;
for (int j = left; j <= right - 1; j++)
{
if (data[j] < pivot)
{
i++;
swap_float(&data[i], &data[j]);
}
}
swap_float(&data[i + 1], &data[right]);
return i + 1;
}
void qsort_f(float * data, int left, int right)
{
if (left < right)
{
int partition = qsort_partition(data, left, right);
qsort_f(data, left, partition - 1);
qsort_f(data, partition + 1, right);
}
}
void
qsort_floats(floats* xs)
{
// TODO: man 3 qsort ?
qsort_f(xs->data, 0, xs->size - 1);
}
floats*
sample(float* data, long size, int P)
{
// TODO: Randomly sample 3*(P-1) items from the input data.
int rss = 3 * (P - 1);
floats * result = make_floats(rss);
for (int i = 0; i < rss; ++i)
{
result->data[i] = data[rand() % size];
}
return result;
}
void
sort_worker(int pnum, float* data, long size, int P, floats* samps, long* sizes, barrier* bb)
{
floats* xs = make_floats(0);
for (int i = 0; i < size; ++i)
{
if (samps->data[pnum] <= data[i] && data[i] < samps->data[pnum + 1])
{
floats_push(xs, data[i]);
}
}
sizes[pnum] = xs->size;
printf("%d: start %.04f, count %ld\n", pnum, samps->data[pnum], xs->size);
qsort_floats(xs);
barrier_wait(bb);
long sum = 0, start = 0, end = 0;
for (int i = 0; i < pnum; ++i)
{
sum += sizes[i];
}
start = sum;
end = sum + sizes[pnum];
for (int i = start; i < end; ++i)
{
data[i] = xs->data[i - start];
}
free_floats(xs);
}
void
run_sort_workers(float* data, long size, int P, floats* samps, long* sizes, barrier* bb)
{
pid_t cur_pid, pids[P];
for (int i = 0; i < P; ++i)
{
cur_pid = fork();
if (cur_pid == 0)
{
sort_worker(i, data, size, P, samps, sizes, bb);
exit(0);
}
else
{
pids[i] = cur_pid;
}
}
for (int i = 0; i < P; ++i)
{
waitpid(pids[i], NULL, 0);
}
}
void
sample_sort(float* data, long size, int P, long* sizes, barrier* bb)
{
floats * randomSample = sample(data, size, P);
qsort_floats(randomSample);
floats * samps = make_floats(P + 1);
samps->data[0] = 0;
samps->data[samps->size - 1] = __FLT_MAX__;
for (int i = 0; i < P - 1; ++i)
{
samps->data[i + 1] = randomSample->data[i * 3 + 1];
}
run_sort_workers(data, size, P, samps, sizes, bb);
free_floats(randomSample);
free_floats(samps);
}
int
main(int argc, char* argv[])
{
if (argc != 3) {
printf("Usage:\n");
printf("\t%s P data.dat\n", argv[0]);
return 1;
}
const int P = atoi(argv[1]);
const char* fname = argv[2];
seed_rng();
int fd = open(fname, O_RDWR);
check_rv(fd);
void* file = 0; // TODO: Use mmap for I/O
struct stat st;
fstat(fd, &st);
long file_size = st.st_size;
file = mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
long count = 0; // TODO: this is in the file
float* data = 0; // TODO: this is in the file
count = ((long * ) (file))[0];
data = (float *)(file + sizeof(long));
long sizes_bytes = P * sizeof(long);
// long* sizes = malloc(sizes_bytes); // TODO: This should be shared memory.
long * sizes = mmap(NULL, sizes_bytes, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
barrier* bb = make_barrier(P);
sample_sort(data, count, P, sizes, bb);
free_barrier(bb);
// TODO: Clean up resources.
(void) file;
munmap(file, file_size);
munmap(sizes, sizes_bytes);
return 0;
}
|
C
|
#include "file.h"
#include "freemap.h"
#include "inode.h"
#include "utils.h"
static ssize_t mfs_file_write(struct file * filp, const char __user * buf, size_t len, loff_t * ppos)
{
int err = 0;
struct super_block *sb = NULL;
struct inode *inode = NULL;
struct mfs_inode *minode = NULL;
size_t newlen = 0, offset = 0;
inode = file_inode(filp);
minode = MFS_INODE(inode);
sb = inode->i_sb;
offset = ( ppos ? *ppos : 0 );
newlen = len + offset;
pr_err("Writing to file %s (%zu bytes, offset: %llu)\n",minode->name,len,(ppos ? *ppos : 0));
if(unlikely(minode->file.size < newlen)) {
//pr_err("realloc %zu bytes at data block %lu\n",newlen,minode->file.data_block);
err = mfs_alloc_freemap(sb,minode->file.size,newlen,&minode->file.data_block);
if(unlikely(err)) {
goto release; }
//pr_err("realloced %zu bytes at data block %lu\n",newlen,minode->file.data_block);
err = mfs_write_blockdev(sb,minode->inode_block,0,sizeof(struct mfs_inode),minode);
if(unlikely(err)) {
goto release; }
}
err = mfs_write_blockdev(sb,minode->file.data_block,offset,newlen,buf);
if(unlikely(err)) {
goto release; }
inode->i_size = minode->file.size = newlen;
err = mfs_write_blockdev(sb,minode->inode_block,0,sizeof(struct mfs_inode),minode);
if(unlikely(err)) {
goto release; }
if(ppos) {
*ppos = *ppos + len;
}
release:
if(err) {
return -err;
} else {
return len;
}
}
static ssize_t mfs_file_read(struct file * filp, char __user * buf, size_t len, loff_t * ppos)
{
int err = 0;
struct super_block *sb = NULL;
struct inode *inode = NULL;
struct mfs_inode *minode = NULL;
size_t offset = 0,read_len = 0;
inode = file_inode(filp);
minode = MFS_INODE(inode);
sb = inode->i_sb;
offset = ( ppos ? *ppos : 0 );
read_len = min(minode->file.size-offset,len);
if(offset >= minode->file.size) {
return 0; }
pr_err("Reading from file %s (size: %zu bytes, read: %zu bytes, offset: %llu, block: %lu)\n",minode->name,minode->file.size,read_len,(ppos ? *ppos : 0),minode->file.data_block);
err = mfs_read_blockdev(sb,minode->file.data_block,offset,read_len,buf);
if( unlikely(err) ) {
return -err;
} else {
*ppos += read_len;
return read_len;
}
}
const struct file_operations mfs_file_operations = {
.read = mfs_file_read,
.write = mfs_file_write,
};
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int n,i,j,count=0;
scanf("%d",&n);
char s[n];
scanf("%s",s);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i]==s[j])
{
count++;
s[i]='0';
}
}
}
printf("%d",(strlen(s)-count));
return 0;
}
|
C
|
#include<stdio.h>
int sumofsquares(int n)
{
return (n * (n + 1) * (2 * n + 1)) / 6;
}
int main()
{
int n;
printf("Please enter the number of terms : ");
scanf("%d",&n);
printf("The sum of squares of the first n natural numbers is : %d\n",sumofsquares(n));
}
|
C
|
#include<stdio.h>
int main(){
printf("please input a chain of chracters(no more than 50)\n");
char a[50];
int i = 0;
int amount = 0;
int k = 0;
while((a[i]= getchar()) != '\n'){
i++;
}
for(k = 0;k<i;){
if((a[k]>='A'&&a[k]<='Z')||(a[k]>='a'&&a[k]<='z')){
k++;
}else{
amount++;
k++;
}
}
printf("The number of wordis: %d\n",amount);
return 0;
}
|
C
|
#include <stdio.h>
void main() {
int a, b;
a = 5;
b = 3;
while (a > b) {
a = a - b;
}
printf("%d \n", a);
}
|
C
|
/*
** EPITECH PROJECT, 2017
** copy_buff.c
** File description:
** Function that delete the number at the top of the map
*/
#include "bsq.h"
#include <stdlib.h>
void copy_buff(char *buffer)
{
char *buff = malloc(sizeof(char) * my_strlen(buffer) + 1);
int i = 0;
int j = 0;
while (buffer[i] != '\n') {
i = i + 1;
}
i = i + 1;
while (buffer[i] != '\0') {
buff[j] = buffer[i];
i = i + 1;
j = j + 1;
}
buff[j] = '\0';
i = 0;
while (buff[i] != '\0') {
buffer[i] = buff[i];
i = i + 1;
}
buffer[i] = '\0';
free(buff);
}
|
C
|
//sourcecode
#include<stdio.h>
#include<stdlib.h>
main()
{
int n,a[1000],i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
a[n]=1;
a[n+1]=1;
for(i=0;i<n;i+=3)
printf("%d ",a[i]*a[i+1]*a[i+2]);
}
//product of three
/*
Sample IP:
1 2 3
Sample OP:
6
*/
|
C
|
#include <stdio.h>
int main () {
int input;
int count = 0;
while( count < 1 ){
/* この部分に必要なプログラムを補う */
printf("偶数は0回入力されています.正の整数を入力して下さい.");
scanf("%d",&input);
if (input %2 == 0)
{
count = count+1;
}
}
while( count < 2){
printf("偶数は1回入力されています.正の整数を入力して下さい.");
scanf("%d",&input);
if (input %2 == 0)
{
count = count+1;
}
}
printf("2回偶数が入力されました.プログラムを終了します.\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "sway/commands.h"
static struct cmd_results *parse_border_color(struct border_colors *border_colors, const char *cmd_name, int argc, char **argv) {
struct cmd_results *error = NULL;
if (argc != 5) {
return cmd_results_new(CMD_INVALID, cmd_name, "Requires exactly five color values");
}
uint32_t colors[5];
int i;
for (i = 0; i < 5; i++) {
char buffer[10];
error = add_color(cmd_name, buffer, argv[i]);
if (error) {
return error;
}
colors[i] = strtoul(buffer+1, NULL, 16);
}
border_colors->border = colors[0];
border_colors->background = colors[1];
border_colors->text = colors[2];
border_colors->indicator = colors[3];
border_colors->child_border = colors[4];
return cmd_results_new(CMD_SUCCESS, NULL, NULL);
}
struct cmd_results *cmd_client_focused(int argc, char **argv) {
return parse_border_color(&config->border_colors.focused, "client.focused", argc, argv);
}
struct cmd_results *cmd_client_focused_inactive(int argc, char **argv) {
return parse_border_color(&config->border_colors.focused_inactive, "client.focused_inactive", argc, argv);
}
struct cmd_results *cmd_client_unfocused(int argc, char **argv) {
return parse_border_color(&config->border_colors.unfocused, "client.unfocused", argc, argv);
}
struct cmd_results *cmd_client_urgent(int argc, char **argv) {
return parse_border_color(&config->border_colors.urgent, "client.urgent", argc, argv);
}
struct cmd_results *cmd_client_placeholder(int argc, char **argv) {
return parse_border_color(&config->border_colors.placeholder, "client.placeholder", argc, argv);
}
struct cmd_results *cmd_client_background(int argc, char **argv) {
char buffer[10];
struct cmd_results *error = NULL;
uint32_t background;
if (argc != 1) {
return cmd_results_new(CMD_INVALID, "client.background", "Requires exactly one color value");
}
error = add_color("client.background", buffer, argv[0]);
if (error) {
return error;
}
background = strtoul(buffer+1, NULL, 16);
config->border_colors.background = background;
return cmd_results_new(CMD_SUCCESS, NULL, NULL);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <getopt.h>
#include <cblas.h>
#include <lapacke.h>
typedef double* matrix;
matrix create(size_t m, size_t n)
{
matrix mat;
mat = malloc(m * n * sizeof(double));
for(size_t i = 0; i < m*n; ++i)
{
mat[i] = 0;
}
return mat;
}
matrix copy_matrix(const matrix A, size_t m, size_t n)
{
matrix mat;
mat = malloc(m * n * sizeof(double));
for(size_t i = 0; i < m*n; ++i)
{
mat[i] = A[i];
}
return mat;
}
matrix create_rand_matrix(size_t m, size_t n)
{
matrix mat;
srand(time(0));
mat = malloc(m * n * sizeof(double));
for(size_t i = 0; i < m*n; ++i)
{
mat[i] = (double) rand() / RAND_MAX;
}
return mat;
}
void print_matrix(const matrix mat, size_t m, size_t n)
{
for(size_t i = 0; i < m; ++i)
{
for(size_t j = 0; j < n; ++j)
printf("%lf ", mat[i*n + j]);
printf("\n");
}
}
matrix create_I(size_t m, size_t n)
{
matrix matrix2;
matrix2 = malloc(m * n * sizeof(double));
for(size_t i = 0; i < m; ++i)
{
for(size_t j = 0; j < n; ++j)
if (i == j)
matrix2[i*n + j] = 1;
else
matrix2[i*n + j] = 0;
}
return matrix2;
}
matrix create_O(size_t m, size_t n)
{
matrix mat;
mat = malloc(m * n * sizeof(double));
for(size_t i = 0; i < m*n; ++i)
{
mat[i] = 0;
}
return mat;
}
double error_of_qr(const matrix A, const matrix newA, size_t n)
{
double er = 0;
double norm = 0;
for(size_t i = 0; i < n*n; ++i)
{
er = er + (A[i] - newA[i]) * (A[i] - newA[i]);
norm = norm + A[i] * A[i];
}
norm = sqrt(norm);
er = sqrt(er) / norm;
return er;
}
matrix* QRdecomposition(const matrix A, size_t N)
{
matrix* QR = malloc( 2 * sizeof(matrix));
double *vT, *vrT, *vq;
vT = malloc(N * sizeof(double));
vrT = malloc(N * sizeof(double));
vq = malloc(N * sizeof(double));
matrix Q, R, P;
Q = create_I(N, N);
R = copy_matrix(A, N, N);
P = create_O(N, N);
// A = Q*R
// P = I - (2/vT*v) * v*vT - householder matrix, v - householder
// Pn*Pn-1*...*P1*A = R
// P1*P2*...*Pn = Q
for(size_t k = 0; k < N; ++k)
{
size_t size;
size = N - k;
for(size_t i = 0; i < size; ++i)
vT[i] = R[(k + i) * N + k];
double w1;
w1 = cblas_dnrm2(size, vT, 1);
if (R[k * N + k] > 0)
vT[0] = vT[0] + w1;
else
vT[0] = vT[0] - w1;
cblas_dgemv(CblasRowMajor, CblasTrans, size, size, 1, R + k*N + k, N, vT, 1, 0, vrT, 1);
double w2;
w2 = cblas_ddot(size, vT, 1, vT, 1);
cblas_dgemv(CblasRowMajor, CblasNoTrans, N, size, 1, Q + k, N, vT, 1, 0, vq, 1);
w2 = 2.0 / w2;
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, size, size, 1, -w2, vT, N, vrT, N, 1, R + k*N + k, N);
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, N, size, 1, -w2, vq, N, vT, N, 1, Q + k, N);
}
QR[0] = Q;
QR[1] = R;
free(vT);
free(vrT);
free(vq);
free(P);
return QR;
}
int main(int argc, char *argv[])
{
// Set size of matrix
size_t size;
size = 2048;
matrix A;
A = create_rand_matrix(size, size);
// QR - decomposition
matrix* QR;
clock_t start = clock();
QR = QRdecomposition(A, size);
clock_t end = clock();
printf("Time: %lf\n",(double) (end - start) / CLOCKS_PER_SEC );
// Compute Error of QR decomposition
matrix newA;
newA = create(size, size);
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, size, size, size, 1, QR[0], size, QR[1], size, 0, newA, size);
printf("Error: %.16lf\n", error_of_qr(A, newA, size));
free(A);
free(newA);
free(QR[0]);
free(QR[1]);
free(QR);
return 0;
}
|
C
|
///////////////////////////////////////////////////////////////////////////////
//
/// \file fastpos.h
/// \brief Kind of two-bit version of bit scan reverse
///
// Authors: Igor Pavlov
// Lasse Collin
//
// This file has been put into the public domain.
// You can do whatever you want with this file.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef LZMA_FASTPOS_H
#define LZMA_FASTPOS_H
// LZMA encodes match distances by storing the highest two bits using
// a six-bit value [0, 63], and then the missing lower bits.
// Dictionary size is also stored using this encoding in the .xz
// file format header.
//
// fastpos.h provides a way to quickly find out the correct six-bit
// values. The following table gives some examples of this encoding:
//
// dist return
// 0 0
// 1 1
// 2 2
// 3 3
// 4 4
// 5 4
// 6 5
// 7 5
// 8 6
// 11 6
// 12 7
// ... ...
// 15 7
// 16 8
// 17 8
// ... ...
// 23 8
// 24 9
// 25 9
// ... ...
//
//
// Provided functions or macros
// ----------------------------
//
// get_dist_slot(dist) is the basic version. get_dist_slot_2(dist)
// assumes that dist >= FULL_DISTANCES, thus the result is at least
// FULL_DISTANCES_BITS * 2. Using get_dist_slot(dist) instead of
// get_dist_slot_2(dist) would give the same result, but get_dist_slot_2(dist)
// should be tiny bit faster due to the assumption being made.
//
//
// Size vs. speed
// --------------
//
// With some CPUs that have fast BSR (bit scan reverse) instruction, the
// size optimized version is slightly faster than the bigger table based
// approach. Such CPUs include Intel Pentium Pro, Pentium II, Pentium III
// and Core 2 (possibly others). AMD K7 seems to have slower BSR, but that
// would still have speed roughly comparable to the table version. Older
// x86 CPUs like the original Pentium have very slow BSR; on those systems
// the table version is a lot faster.
//
// On some CPUs, the table version is a lot faster when using position
// dependent code, but with position independent code the size optimized
// version is slightly faster. This occurs at least on 32-bit SPARC (no
// ASM optimizations).
//
// I'm making the table version the default, because that has good speed
// on all systems I have tried. The size optimized version is sometimes
// slightly faster, but sometimes it is a lot slower.
#ifdef HAVE_SMALL
# define get_dist_slot(dist) \
((dist) <= 4 ? (dist) : get_dist_slot_2(dist))
static inline uint32_t
get_dist_slot_2(uint32_t dist)
{
const uint32_t i = bsr32(dist);
return (i + i) + ((dist >> (i - 1)) & 1);
}
#else
#define FASTPOS_BITS 13
extern const uint8_t lzma_fastpos[1 << FASTPOS_BITS];
#define fastpos_shift(extra, n) \
((extra) + (n) * (FASTPOS_BITS - 1))
#define fastpos_limit(extra, n) \
(UINT32_C(1) << (FASTPOS_BITS + fastpos_shift(extra, n)))
#define fastpos_result(dist, extra, n) \
(uint32_t)(lzma_fastpos[(dist) >> fastpos_shift(extra, n)]) \
+ 2 * fastpos_shift(extra, n)
static inline uint32_t
get_dist_slot(uint32_t dist)
{
// If it is small enough, we can pick the result directly from
// the precalculated table.
if (dist < fastpos_limit(0, 0))
return lzma_fastpos[dist];
if (dist < fastpos_limit(0, 1))
return fastpos_result(dist, 0, 1);
return fastpos_result(dist, 0, 2);
}
#ifdef FULL_DISTANCES_BITS
static inline uint32_t
get_dist_slot_2(uint32_t dist)
{
assert(dist >= FULL_DISTANCES);
if (dist < fastpos_limit(FULL_DISTANCES_BITS - 1, 0))
return fastpos_result(dist, FULL_DISTANCES_BITS - 1, 0);
if (dist < fastpos_limit(FULL_DISTANCES_BITS - 1, 1))
return fastpos_result(dist, FULL_DISTANCES_BITS - 1, 1);
return fastpos_result(dist, FULL_DISTANCES_BITS - 1, 2);
}
#endif
#endif
#endif
|
C
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkHalf_DEFINED
#define SkHalf_DEFINED
#include "include/core/SkTypes.h"
#include "include/private/SkNx.h"
// 16-bit floating point value
// format is 1 bit sign, 5 bits exponent, 10 bits mantissa
// only used for storage
typedef uint16_t SkHalf;
static constexpr uint16_t SK_HalfMin = 0x0400; // 2^-14 (minimum positive normal value)
static constexpr uint16_t SK_HalfMax = 0x7bff; // 65504
static constexpr uint16_t SK_HalfEpsilon = 0x1400; // 2^-10
static constexpr uint16_t SK_Half1 = 0x3C00; // 1
// convert between half and single precision floating point
float SkHalfToFloat(SkHalf h);
SkHalf SkFloatToHalf(float f);
// Convert between half and single precision floating point,
// assuming inputs and outputs are both finite, and may
// flush values which would be denormal half floats to zero.
static inline Sk4f SkHalfToFloat_finite_ftz(uint64_t);
static inline Sk4h SkFloatToHalf_finite_ftz(const Sk4f&);
// ~~~~~~~~~~~ impl ~~~~~~~~~~~~~~ //
// Like the serial versions in SkHalf.cpp, these are based on
// https://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/
// GCC 4.9 lacks the intrinsics to use ARMv8 f16<->f32 instructions, so we use inline assembly.
static inline Sk4f SkHalfToFloat_finite_ftz(uint64_t rgba) {
Sk4h hs = Sk4h::Load(&rgba);
#if !defined(SKNX_NO_SIMD) && defined(SK_CPU_ARM64)
float32x4_t fs;
asm ("fcvtl %[fs].4s, %[hs].4h \n" // vcvt_f32_f16(...)
: [fs] "=w" (fs) // =w: write-only NEON register
: [hs] "w" (hs.fVec)); // w: read-only NEON register
return fs;
#else
Sk4i bits = SkNx_cast<int>(hs), // Expand to 32 bit.
sign = bits & 0x00008000, // Save the sign bit for later...
positive = bits ^ sign, // ...but strip it off for now.
is_norm = 0x03ff < positive; // Exponent > 0?
// For normal half floats, extend the mantissa by 13 zero bits,
// then adjust the exponent from 15 bias to 127 bias.
Sk4i norm = (positive << 13) + ((127 - 15) << 23);
Sk4i merged = (sign << 16) | (norm & is_norm);
return Sk4f::Load(&merged);
#endif
}
static inline Sk4h SkFloatToHalf_finite_ftz(const Sk4f& fs) {
#if !defined(SKNX_NO_SIMD) && defined(SK_CPU_ARM64)
float32x4_t vec = fs.fVec;
asm ("fcvtn %[vec].4h, %[vec].4s \n" // vcvt_f16_f32(vec)
: [vec] "+w" (vec)); // +w: read-write NEON register
return vreinterpret_u16_f32(vget_low_f32(vec));
#else
Sk4i bits = Sk4i::Load(&fs),
sign = bits & 0x80000000, // Save the sign bit for later...
positive = bits ^ sign, // ...but strip it off for now.
will_be_norm = 0x387fdfff < positive; // greater than largest denorm half?
// For normal half floats, adjust the exponent from 127 bias to 15 bias,
// then drop the bottom 13 mantissa bits.
Sk4i norm = (positive - ((127 - 15) << 23)) >> 13;
Sk4i merged = (sign >> 16) | (will_be_norm & norm);
return SkNx_cast<uint16_t>(merged);
#endif
}
#endif
|
C
|
#include "libasm.h"
void test_strdup(void)
{
printf("\n\n@@@@@@@@@@@@@@@@@- Tests strdup -@@@@@@@@@@@@@@@@@\n\n");
printf("--------------------------------------\n");
printf("|test|\n");
printf("|%s|\n", strdup("test"));
printf("|%s|\n", ft_strdup("test"));
printf("--------------------------------------\n");
printf("||\n");
printf("|%s|\n", strdup(""));
printf("|%s|\n", ft_strdup(""));
printf("--------------------------------------\n");
printf("|123 456 789|\n");
printf("|%s|\n", strdup("123 456 789"));
printf("|%s|\n", ft_strdup("123 456 789"));
printf("--------------------------------------\n");
printf("\\0\n");
printf("|%s|\n", strdup("\0"));
printf("|%s|\n", ft_strdup("\0"));
printf("--------------------------------------\n");
}
void test_read(void)
{
int fd;
char *buff;
char *buff2;
int ret;
char *file = "./srcs/ft_strlen.s";
buff = malloc(sizeof(char) * 1000);
buff2 = malloc(sizeof(char) * 1000);
printf("\n@@@@@@@@@@@@@@@@@- Tests read -@@@@@@@@@@@@@@@@@\n\n");
printf("--------------------------------------\n");
printf("file name : %s\n", file);
printf("--------------------------------------\n");
fd = open(file, O_RDONLY);
ret = read(fd, buff, 500);
if (ret == -1)
printf("%s", strerror(errno));
printf("%s\n", buff);
close(fd);
fd = 0;
ret = 0;
printf("--------------------------------------\n");
fd = open(file, O_RDONLY);
ret = ft_read(fd, buff2, 500);
if (ret == -1)
printf("%s", strerror(errno));
printf("%s\n", buff2);
close(fd);
free(buff);
free(buff2);
printf("--------------------------------------\n");
}
void test_write(void)
{
ft_write(0, "@@@@@@@@@@@@@@@@@- Tests write -@@@@@@@@@@@@@@@@@\n\n", 52);
printf("--------------------------------------\n");
write(1, "|test|\n", 7);
ft_write(1, "|test|\n", 7);
ft_write(1, "---------------------------\n", 28);
write(0, "|test 0 fd|\n", 12);
ft_write(0, "|test 0 fd|\n", 12);
ft_write(0, "---------------------------\n", 28);
printf("--------------------------------------\n");
}
void test_strcmp(void)
{
printf("\n@@@@@@@@@@@@@@@@@- Tests strcmp -@@@@@@@@@@@@@@@@@\n\n");
printf("--------------------------------------\n");
printf("|test|testa|\n");
printf("|%d|\n", strcmp("test", "testa"));
printf("|%d|\n", ft_strcmp("test", "testa"));
printf("--------------------------------------\n");
printf("|testa|test|\n");
printf("|%d|\n", strcmp("testa", "test"));
printf("|%d|\n", ft_strcmp("testa", "test"));
printf("--------------------------------------\n");
printf("|test|test|\n");
printf("|%d|\n", strcmp("test", "test"));
printf("|%d|\n", ft_strcmp("test", "test"));
printf("--------------------------------------\n");
printf("| | |\n");
printf("|%d|\n", strcmp("", ""));
printf("|%d|\n", ft_strcmp("", ""));
printf("--------------------------------------\n");
printf("|\\xff|\\xff|\n");
printf("|%d|\n", strcmp("\xff", "\xff"));
printf("|%d|\n", ft_strcmp("\xff", "\xff"));
printf("--------------------------------------\n");
}
void test_strcpy(void)
{
char dst[100];
printf("\n@@@@@@@@@@@@@@@@@- Tests strcpy -@@@@@@@@@@@@@@@@@\n\n");
printf("|test|\n");
printf("|%s|\n", strcpy(dst, "test"));
printf("|%s|\n", ft_strcpy(dst, "test"));
printf("--------------------------------------\n");
printf("|abc123|\n");
printf("|%s|\n", strcpy(dst, "abc123"));
printf("|%s|\n", ft_strcpy(dst, "abc123"));
printf("--------------------------------------\n");
printf("\\n\n");
printf("|%s|\n", strcpy(dst, "\n"));
printf("|%s|\n", ft_strcpy(dst, "\n"));
printf("--------------------------------------\n");
}
void test_strlen(void)
{
printf("\n\n@@@@@@@@@@@@@@@@@- Tests strlen -@@@@@@@@@@@@@@@@@\n\n");
printf("--------------------------------------\n");
printf("|test|\n");
printf("|%d|\n", (int)strlen("test"));
printf("|%d|\n", (int)ft_strlen("test"));
printf("--------------------------------------\n");
printf("|12345abc|\n");
printf("|%d|\n", (int)strlen("12345abc"));
printf("|%d|\n", (int)ft_strlen("12345abc"));
printf("--------------------------------------\n");
printf("|\\0|\n");
printf("|%d|\n", (int)strlen("\0"));
printf("|%d|\n", (int)ft_strlen("\0"));
printf("--------------------------------------\n");
}
int main(void)
{
test_strlen();
test_strcpy();
test_strcmp();
test_write();
test_read();
test_strdup();
}
|
C
|
/**
* Agents are the core elements of the Robotic Framework
* which correspond to state machines executing the program
* and transmitting information between each other
*/
#ifndef ROBOTIC_FRAMEWORK_AGENTS_H
#define ROBOTIC_FRAMEWORK_AGENTS_H
#include <RF_events.h>
#include <RF_queue.h>
typedef enum
{
RF_HANDLED = 0,
RF_UNHANDLED = 1,
} RFHandle;
struct RFBaseAgent
{
struct RF_BaseQueue FIFOQueue;
RFHandle (*currentHandler)(struct RFBaseAgent* const self, RFEvent *const evt);
};
typedef struct RFBaseAgent RFAgent;
void RFBaseAgentConstructor(RFAgent* const self, RFHandle (*initialTransition)(RFAgent* const self, RFEvent *const evt));
/**
* Posts event directly to the agent's queue
*
* Note: This should only be used to post an event to itself
*/
void postEventToAgent(RFAgent* self, RFEvent const * const evt);
#define INITIAL_TRANSITION(me, state) \
((RFAgent*)me)->currentHandler = state; \
(void)((RFAgent*)me)->currentHandler(me, &RFEvent_InitialSignal);
#define ENTRY_TRANSITION(me, state) \
((RFAgent*)me)->currentHandler = state; \
(void)((RFAgent*)me)->currentHandler(me, &RFEvent_EntrySignal);
#define EXIT_TRANSITION(me) \
(void)((RFAgent*)me)->currentHandler(me, &RFEvent_ExitSignal);
/**
* TODO: Execute transition does not work
* To be unit tested!
*/
#define EXECUTE_TRANSITION(me, state) \
EXIT_TRANSITION(me) \
ENTRY_TRANSITION(me, state) \
return RF_HANDLED;
#endif
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* img_bmp_gen.c :+: :+: */
/* +:+ */
/* By: nmartins <[email protected]> +#+ */
/* +#+ */
/* Created: 2019/08/13 16:24:16 by nmartins #+# #+# */
/* Updated: 2019/08/13 18:12:10 by nmartins ######## odam.nl */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <unistd.h>
#include "image.h"
static const char g_bitmap_header[2] = "BM";
void write_null(int fd, size_t len)
{
const static char null_buff[1024] = {};
if (len > 1024)
perror("Cannot write more than 1024 null bytes");
write(fd, null_buff, len);
}
static void write_bytes(t_image *img, int fd)
{
uint32_t color;
int x;
int y;
int i;
y = img->height;
i = 0;
while (y >= 0)
{
x = 0;
while (x < img->width)
{
color = *img_get_pixel(img, x, y);
write(fd, &color, img->bpp / 8);
i++;
x++;
}
y--;
write_null(fd, img->width * img->bpp / 8 % 4);
}
}
void write_size_bitmap(t_image *img, int fd)
{
const int size_row = img->width * img->bpp / 8 + img->width * img->bpp / 8 % 4;
const int size_bitmap = size_row * img->height;
write(fd, &size_bitmap, 4);
}
int calculate_size(t_image *img)
{
const int size_row = img->width * img->bpp / 8 + img->width * img->bpp / 8 % 4;
int size;
size = 54;
size += size_row * img->height;
return (size);
}
void img_bmp_gen_fd(t_image *img, int fd)
{
const int reading_offset = 54;
const int num_bytes = 40;
const short plane = 1;
const int size = calculate_size(img);
write(fd, g_bitmap_header, 2);
write(fd, &size, 4);
write_null(fd, 4);
write(fd, &reading_offset, 4);
write(fd, &num_bytes, 4);
write(fd, &img->width, 4);
write(fd, &img->height, 4);
write(fd, &plane, 2);
write(fd, &img->bpp, 2);
write_null(fd, 4);
write_size_bitmap(img, fd);
write_null(fd, 16);
write_bytes(img, fd);
}
|
C
|
/* ring.c */
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <utmp.h>
#define LONG_TIME 300000 /* half second worth of usec's */
#define SHORT_TIME 100000 /* quarter second worth of usec's */
#ifndef UTMP_FILE
# define UTMP_FILE "/var/adm/utmp"
#endif
#define TRUE 1
#define FALSE 0
#define nonuser(ut) (ut.ut_type == 8)
#define BELL '\x7'
void ring(FILE *);
void main(argc, argv)
int argc;
char *argv[];
{
FILE *terminal;
char term_str[20] = "/dev/";
int utmp_fileid;
struct utmp utmp_entry;
if (argc != 2)
{
printf("Usage: ring username\n\n");
exit(0);
}
if ((utmp_fileid = open(UTMP_FILE, O_RDONLY)) == -1)
{
fprintf(stderr,"Can not open %s.\n", UTMP_FILE);
exit(1);
}
while (read(utmp_fileid, &utmp_entry, sizeof(utmp_entry)) > 0)
{
if (nonuser(utmp_entry) == FALSE)
if (strncmp(argv[1],utmp_entry.ut_name,sizeof(argv[1])) == 0)
break;
}
close(utmp_fileid);
if (strncmp(argv[1],utmp_entry.ut_name,sizeof(argv[1])) != 0)
{
printf("%s is not logged in.\n", argv[1]);
exit(1);
}
strcat(term_str, utmp_entry.ut_line);
if ((terminal = fopen(term_str, "w")) == NULL)
{
printf("%s is not accepting messages on %s\n", argv[1], utmp_entry.ut_line);
exit(1);
}
printf("Ringing %s on %s.\n", argv[1], utmp_entry.ut_line);
ring(terminal);
fclose(terminal);
return;
}
/* ---------- ring() ---------- */
void ring(filevar)
FILE *filevar;
{
putc(BELL,filevar);
fflush(filevar);
usleep(SHORT_TIME);
putc(BELL,filevar);
fflush(filevar);
usleep(LONG_TIME);
putc(BELL,filevar);
fflush(filevar);
return;
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void)
{
int fd[2],nbytes;
int childpid;
char string[] = "Helloi world!\n";
char readbuffer[80];
pipe(fd);
childpid = fork();
if(childpid == 0)
{
close(fd[0]);
write(fd[1],string,(strlen(string)+1));
exit(0);
}
else
{
close(fd[1]);
nbytes = read(fd[0],readbuffer,sizeof(readbuffer));
printf("Recieve string : %s",readbuffer);
}
return (0);
}
|
C
|
#include<stdio.h>
int count=0;
int a[5001][5001]={0};
int path(int i,int j)
{
if(i<0||j<0||a[i][j]==1)
return;
else if((i==0)&&(j==0))
++count;
else
{
path(i-1,j);
path(i,j-1);
}
}
int main()
{
int m,n,k,i,a1,a2;
scanf("%d %d %d",&m,&n,&k);
for(i=0;i<k;++i)
{
scanf("%d %d",&a1,&a2);
a[a1-1][a2-1]=1;
}
path(m-1,n-1);
printf("%d\n",count);
return 0;
}
|
C
|
#include<stdio.h>
/* program for celsius - fahrenheit table*/
main()
{
int lower=0,upper=100,step=10;
float fah,celsius;
celsius=lower;
printf("CELSIUS-FAHRENHEIT TABLE\n");
while(celsius<=upper)
{
fah=(celsius*5)/9+32;
printf("%.0f\t%.1f\n",celsius,fah);
celsius=celsius+step;
}
}
|
C
|
//incorrect swap
//by Kevin Schwaar
#include <stdio.h>
void swap (int *x, int *y);
int main(void){
int x=1;
int y=123;
printf("Before the swap, x=%d and y=%d\n",x,y);
swap(&x,&y);
printf("After the swap, x=%d and y=%d.\n",x,y);
}
void swap (int *x, int *y){
int tmp = *x;
*x = *y;
*y = tmp;
}
|
C
|
#include <stdio.h>
#define MAX_LEN 1000 + 1
int dp[MAX_LEN][MAX_LEN];
char str[2][MAX_LEN];
int len[2];
#define min(a, b) (((a) > (b)) ? (b) : (a))
#define max(a, b) (((a) > (b)) ? (a) : (b))
int main() {
scanf("%s %s", str[0], str[1]);
for (len[0] = 0; str[0][len[0]]; ++len[0]);
for (len[1] = 0; str[1][len[1]]; ++len[1]);
for (int i = 1; i <= len[0]; ++i) {
for (int j = 1; j <= len[1]; ++j) {
if (str[0][i - 1] == str[1][j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else {
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
int r = dp[len[0]][len[1]];
printf("%d\n", r);
str[0][r] = '\0';
for (int a = len[0], b = len[1]; r > 0;) {
if (dp[a - 1][b] == dp[a][b]) {
--a;
}
else if (dp[a][b - 1] == dp[a][b]) {
--b;
}
else if (dp[a - 1][b - 1] + 1 == dp[a][b]) {
str[0][--r] = str[1][b - 1];
--a, --b;
}
}
printf("%s", str[0]);
return 0;
}
|
C
|
/* LAB-4 library source file -Challenge1
SUBIR KUMAR PADHEE
ECEN5613
*/
#include "main.h"
/* Function definitions */
/* computes time elapsed between start and stop of timer 2 */
void compute_time()
{
long long time_computed = 0;
long UB = 0;
UB = 0x00FF & TH2;
//printf("\r\n UB:%l ov_cnt:%d", UB, ov_cnt);
time_computed = (((UB << 8) + TL2) * 1085);
time_computed = (time_computed/1000) + ((71105 * ov_cnt));
printf("\r\n\r\n\t\t\t\t\t\t\tTime taken for the operation is %ld usec", time_computed);
printf("\r\n\t\t\t\t\t\t\t [ TH2:%02X TL2:%02X Overflow count: %d ]", TH2, TL2, ov_cnt);
}
/* Search a string from the text written on the LCD */
unsigned char search2()
{
volatile unsigned char i = 0, j = 0, no_match = 0, len = 0 ;//loop vars, flags, length var
unsigned char str[64] = {'\0'};//stores the string to be searched-max 64 chars
unsigned char ch = '\0';//stores each char extracted from the DDRAM
unsigned char pos = '\0';//stores the position of the extracted character on the DDRAM
volatile unsigned char posBEG = '\0';//stores the position of the first matched character on the DDRAM
volatile unsigned char posFIRST = 0x5F;//used to prevent repetition searches
unsigned char revert = 0;//used to restore the position of the curson in case entire string does not match
volatile unsigned char first_time = 1; //flag
putstring("\r\n\r\n\t\t\t\t\t\t\t*****************************************");
putstring("\r\n\t\t\t\t\t\t\t* *");
putstring("\r\n\t\t\t\t\t\t\t* Word Search *");
putstring("\r\n\t\t\t\t\t\t\t* Enter THE STRING TO SEARCH *");
putstring("\r\n\t\t\t\t\t\t\t* *");
putstring("\r\n\t\t\t\t\t\t\t*****************************************\r\n");
getstring_search(str);
len = strlen(str);
lcdgotoxy(0,0);
TR2 = 1;//to compute time
if(len == 1)
{
for(i = 0; i < 64 ; i++)
{
ch = ddram_pos(&posBEG);
if(posBEG == posFIRST)
{
return 1;
}
if(ch == str[0])
{
if(first_time)
{
posFIRST = posBEG;
first_time = 0;
}
printf("\r\n\t\t\t\t\t\t\t Found a match for %s at 0x%02X", str, posBEG);
}
}
}
for(i = 0; i < 128 ; i++)
{
ch = ddram_pos(&posBEG);
if(posBEG == posFIRST)
{
return 1;
}
if(ch == str[j])
{
revert = i+1;
if((i >=64) && (j == 0))
break;
j++;
for(; ((j < len) && (no_match == 0));i++)
{
ch = ddram_pos(&pos);
if(ch != str[j++])
{
no_match = 1;
j = 0;//for next match search
i = i-j;
}
}
if(no_match == 0)
{
printf("\r\n\t\t\t\t\t\t\t Found a match for %s at 0x%02X", str, posBEG);
no_match = 1;
j = 0;//for next match search
}
if(no_match)
{
i--;//to negate the one extra i++
lcdgotoxy(revert/16 ,revert%16);
NOP;
}
}
else
{
//get next char from lcd
}
no_match = 0;
}
putstring("\r\n\t\t\t\t\t\t\t\t Search over!");
}
/* extracts charaters and their position from the LCD(DDRAM) in the order they are displayed */
unsigned char ddram_pos(unsigned char *pos)
{
unsigned char ch = '\0';
RS = 0;
RWbar = 1;
NOP;
RD_DATA;
*pos = (*(xdata unsigned char *)RD_ADDR) & 0x7F; //Read the DDRAM address of the current cursor position
/* The cursor is incremented linearly and not in the order characters are displayed on the LCD.
The following lines make sure the cursor position is set in the order of display */
if(*pos == 0x0F)
{
lcdgotoxy(1,0);
}
else if(*pos == 0x4F)
{
lcdgotoxy(2,0);
}
else if(*pos == 0x1F)
{
lcdgotoxy(3,0);
}
else if(*pos == 0x5F)
{
lcdgotoxy(0,0);
}
RS = 1;
RWbar = 1;
NOP;
ch = *(xdata unsigned char *)RD_ADDR; //Read the character pointed to by the current cursor position on the LCD
NOP;
return ch;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.