language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
//1+3+5......N=N
#include<stdio.h>
int main()
{
int num,i,sum=0;
printf("Enter the last number of series: ");
scanf("%d",&num);
for(i=1;i<=num;i=i+2)
{
sum=sum+i;
}
printf("1+2+3.....+%d = %d",num,sum);
}
|
C
|
/* Nombre Fichero: include/prog04.h */
#ifndef PROG04_H
#define PROG04_H
// Librerias
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Definicion de constantes
#define MAX_NOMBRE 30
#define MAX_ARRAY 55
#define MIN_POBLACION 40000
/* RECUERDE
* NO MODIFIQUE LOS NOMBRES DE LAS FUNCIONES NI EL NOMBRE DE LOS ARGUMENTOS
* NO AÑADA PARAMETROS A LAS FUNCIONES */
// Definicion de tipos
typedef struct {
char nombre[MAX_NOMBRE];
int poblacion;
} Ciudad_t;
typedef struct {
Ciudad_t ciudad[MAX_ARRAY];
unsigned int num_ciudades;
} RegistroCiudades_t;
typedef enum
{
ASCENDENTE,
DESCENDENTE
}ORDEN_t;
// Definicion de funciones
/* funcion que permite rellenar el array de estructuras
* [ IN] pbbdd, puntero a la estructura que contiene las ciudades
* [ IN] nombre, nombre de la ciudad a introducir
* [ IN] poblacion, poblacion de la ciudad a introducir
* [RET] int, si se produce error devuelve un número negativo si no positivo */
int introducirCiudad(RegistroCiudades_t* pbbdd, const char* nombre, int poblacion);
/* funcion que muestra por pantalla una lista de todas las ciudades
* [ IN] pbbdd, puntero a la estructura que contiene las ciudades
* [RET] int, si se produce error devuelve un número negativo si no positivo */
int mostrarCiudades(RegistroCiudades_t* pbbdd);
/* funcion que muestra por pantalla una lista de todas las cuidades cuya poblacion sea inferior a 40000 habitantes
* [ IN] pbbdd, puntero a la estructura que contiene las ciudades
* [RET] return, numero de ciudades despobladas o si error número negativo */
int mostrarCiudadesDespobladas(RegistroCiudades_t* pbbdd);
/* funcion que retorna el indice de la ciudad mas poblada
* [ IN] pbbdd, puntero a la estructura que contiene las ciudades
* [RET] return, indice de la cuidad mas poblada o si error número negativo */
int buscarCiudadMasPoblada(RegistroCiudades_t* pbbdd);
/* funcion que retorna la poblacion media de las ciudades
* [ IN] pbbdd, puntero a la estructura que contiene las ciudades
* [RET] return, poblacion media de las ciudades o si error número negativo */
float calcularPoblacionMedia(RegistroCiudades_t* pbbdd);
/* funcion que ordena las ciudades por poblacion de mayor a menor
* [ IN] pbbdd, puntero a la estructura que contiene las ciudades
* [ IN] orden, si es ASCENDENTE, ordenado de mayor a menor, si es DESCENDENTE ordenado de menor a mayor
* [RET] return, si error número negativo */
int ordenarCiudadesPorPoblacion(RegistroCiudades_t* pbbdd, ORDEN_t orden);
#endif
|
C
|
#include <gtk/gtk.h>
int main(int argc,char *argv[])
{
GtkWidget *window; //一个GtkWidget类型的结构体指针
char title[]="test";
gtk_init(&argc, &argv); //初始化GTK
window = gtk_window_new(GTK_WINDOW_TOPLEVEL); //新建一个window窗体
gtk_window_set_title(GTK_WINDOW(window), title); //设置窗体的标题为title指向的字符串
gtk_widget_set_usize(GTK_WINDOW (window),300,150); //设置窗体的大小
gtk_widget_set_uposition(GTK_WINDOW(window),200,200); //设置窗体的起始坐标位置
g_signal_connect(GTK_OBJECT(window),"destroy",G_CALLBACK(gtk_main_quit),NULL); //退出的回调函数
gtk_widget_show(window); //显示窗体
gtk_main(); //进入主函数
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct people
{
int num;
char name[20];
char sex;
char job;
union stu
{
int class;
char position;
}jo;
}person[10];
int main()
{
int i;
char q;
for ( i = 0; i < 2; i++) {
printf("룺");
scanf("%d", &person[i].num);
printf("");
scanf("%s",&person[i].name);
q=getchar();
printf("Ա");
person[i].sex=getchar();
printf("ְҵ(ѧsʦt)");
q=getchar();
scanf("%c", &person[i].job);
q=getchar();
if (person[i].job == 's') {
printf("༶");
scanf("%d", &person[i].jo.class);
}
else if (person[i].job == 't') {
printf("ְλ");
gets( person[i].jo.position);
}
else printf("ְҵ\n");
}
for (i = 0; i < 2; i++) {
printf("룺%d\n", person[i].num);
printf("%s\n", person[i].name);
printf("Ա%c\n", person[i].sex);
printf("ְҵ%s\n", person[i].job);
if (person[i].job == 's')
printf("༶%d\n", person[i].jo.class);
if (person[i].job == 't')
printf("ְλ%s", person[i].jo.position);
}
system("pause");
}
|
C
|
/* { dg-additional-options "-fdiagnostics-show-line-numbers -fdiagnostics-path-format=inline-events -fanalyzer-checker=malloc -fdiagnostics-show-caret" } */
/* { dg-enable-nn-line-numbers "" } */
#include <cstdlib>
struct Base
{
virtual void allocate ();
virtual void deallocate ();
};
struct Derived: public Base
{
int *ptr;
void allocate ()
{
ptr = (int*)malloc(sizeof(int));
}
void deallocate ()
{
free(ptr);
}
};
void test()
{
Derived D;
Base B, *base_ptr;
base_ptr = &D;
D.allocate();
base_ptr->deallocate();
int n = *D.ptr; /* { dg-warning "use after 'free' of 'D.Derived::ptr'" } */
}
/* use after 'free' */
/* { dg-begin-multiline-output "" }
NN | int n = *D.ptr;
| ^
'void test()': events 1-2
|
| NN | void test()
| | ^~~~
| | |
| | (1) entry to 'test'
|......
| NN | D.allocate();
| | ~~~~~~~~~~~~
| | |
| | (2) calling 'Derived::allocate' from 'test'
|
+--> 'virtual void Derived::allocate()': events 3-4
|
| NN | void allocate ()
| | ^~~~~~~~
| | |
| | (3) entry to 'Derived::allocate'
| NN | {
| NN | ptr = (int*)malloc(sizeof(int));
| | ~~~~~~~~~~~~~~~~~~~
| | |
| | (4) allocated here
|
<------+
|
'void test()': events 5-6
|
| NN | D.allocate();
| | ~~~~~~~~~~^~
| | |
| | (5) returning to 'test' from 'Derived::allocate'
| NN | base_ptr->deallocate();
| | ~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (6) calling 'Derived::deallocate' from 'test'
|
+--> 'virtual void Derived::deallocate()': events 7-8
|
| NN | void deallocate ()
| | ^~~~~~~~~~
| | |
| | (7) entry to 'Derived::deallocate'
| NN | {
| NN | free(ptr);
| | ~~~~~~~~~
| | |
| | (8) freed here
|
<------+
|
'void test()': events 9-10
|
| NN | base_ptr->deallocate();
| | ~~~~~~~~~~~~~~~~~~~~^~
| | |
| | (9) returning to 'test' from 'Derived::deallocate'
| NN | int n = *D.ptr;
| | ~
| | |
| | (10) use after 'free' of 'D.Derived::ptr'; freed at (8)
|
{ dg-end-multiline-output "" } */
|
C
|
#include<stdio.h>
#include<string.h>
#define N 1001
void cha2int(char *tmps, int *tmpi, int len)
{
int i;
for (i = 0; i < len; i++)
{
tmpi[len - i - 1] = (int)(tmps[i] - '0');
}
}
void int2cha(int *tmpi, char *tmps, int len)
{
int i;
for (i = 0; i < len; i++)
tmps[i] = (char)(tmpi[i] + (int)('0'));
}
int main(void)
{
char a_t[N], b_t[N], c_t[N], *p;
int a[N] = { 0 }, b[N] = { 0 }, c[2002] = { 0 }, lena, lenb, lenc, i, j;
scanf("%s%s", a_t, b_t);
//printf("%s %s", a, b);
lena = strlen(a_t);
lenb = strlen(b_t);
lenc = lena + lenb;
cha2int(a_t, a, lena);
cha2int(b_t, b, lenb);
for (i = 0; i < lenb; i++)
{
for (j = 0; j < lena; j++)
{
c[i + j] += b[i] * a[j];
}
}
for (i = 0; i < lenc; i++)
{
c[i + 1] += c[i] / 10;
c[i] = c[i] % 10;
}
int2cha(c, c_t, lenc);
c_t[lenc] = '\0';
i = lenc - 1;
p = c_t + i;
while (i > 0)
{
if (*p == '0')
{
p--;
i--;
continue;
}
else
break;
}
while (p != c_t)
{
printf("%c", *p);
p--;
}
printf("%c\n", *p);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum { false, true } bool;
#define MYSOL false
int main(void) {
char s2[] = "erbottlewat";
char s1[] = "waterbottle";
int size_s2 = sizeof(s2);
int size_s1 = sizeof(s1);
if(size_s2 != size_s1){
printf("s1 isn't a rotation of s2, they are different");
return 0;
}
#if MYSOL
int index = 0;
int index_aux = 0;
for(index = 0; index < size_s2; index++){
if(s2[index] == s1[index_aux]){
index_aux++;
}
}
char * a = strstr(s2, &s1[index_aux]);
#else
char * sdoubled = malloc(sizeof(s2)*2);
strcat(sdoubled, s2);
strcat(sdoubled, s2);
char * a = strstr(sdoubled, s1);
#endif
if(a != NULL){
printf("%s is a rotation of %s", s2, s1);
}
return EXIT_SUCCESS;
}
|
C
|
#ifndef BIT_MATRIX_H
#define BIT_MATRIX_H
void set_matrix_bit(uint8_t *byte, uint8_t row, uint8_t col, uint8_t value)
{
setbit(&byte[row], col, value);
}
uint8_t get_matrix_bit(const uint8_t *byte, uint8_t row, uint8_t col)
{
return getbit(&byte[row], col);
}
#endif // BIT_MATRIX_H
|
C
|
/**
* File: breakout.c
*
* Author1: Anton Christensen ([email protected])
* Date: Winter 2014
*
* Description:
* Breakout game, built for AT-Mega16
* with 20x4 character display.
* requires the aatg library
*/
// 8x5 dots/char
// 4x20 chars/screen
// 32x100 resolution
#include <util/delay.h>
#include <stdlib.h>
#include "../aatg/buttons.h"
#include "../aatg/lcd.h"
#define SCREEN_WIDTH 32
#define SCREEN_HEIGHT 100
#define CHARH 5
#define CHARW 8
#define YCHARS 20
#define XCHARS 4
#define BRICK 0xFF
#define TRANSPARENT 0xFE
void Breakout(); // Run this function to start the program
typedef struct object {
int x, y, w, h;
bool visible;
} object;
int Draw(object* obj, int start) {
// make empty array of tiles
unsigned char screen[20][4][8];
int a,b,c;
for(a = 0; a < 20; a++)
for(b = 0; b < 4; b++)
for(c = 0; c < 8; c++)
screen[a][b][c] = 0;
//calculate pixels to be drawn
int y,x;
for(y = 0; y < obj->h; y++) {
for(x = 0; x < obj->w; x++) {
screen[(obj->y + y)/CHARH][(obj->x + x)/CHARW][(obj->x + x)%CHARW] |= (1<<((SCREEN_HEIGHT-1-(obj->y + y))%CHARH));
}
}
// generate sprites and draw
int spriteNum = start;
for(y = obj->y-(obj->y%CHARH); y < obj->y+obj->h; y+= CHARH) {
for(x = obj->x-(obj->x%CHARW); x < obj->x+obj->w; x+= CHARW) {
if(spriteNum < 7) {
lcd_set_char(spriteNum,(unsigned char*)screen[y/CHARH][x/CHARW]);
lcd_gotoxy(y/CHARH, x/CHARW);
_lcd_write_byte(spriteNum++,1);
}
}
}
return spriteNum;
}
void Breakout() {
int i,j;
int points = 0;
DDRB = 0xFF;
PORTB = points;
object bricks[4][3];
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
bricks[i][j].x = i;
bricks[i][j].y = j+YCHARS-3;
bricks[i][j].w = CHARW;
bricks[i][j].h = CHARH;
bricks[i][j].visible = true;
}
}
// Draw bricks
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
lcd_gotoxy(bricks[i][j].y,bricks[i][j].x);
_lcd_write_byte(BRICK,1);
}
}
object player = {12,9,7,1,1};
object ball = {15,10,1,1,1};
int ballDX, ballDY;
ballDY = 1;
ballDX = 1;
bool hit = true;
bool changed = true;
int oldXSquare = ball.x/CHARW, oldYSquare = ball.y/CHARH;
while(1) {
// if left pressed
if(is_pressed(3) && player.x > 0) {
// if player pad leaving a screen character
if((player.x+player.w)%CHARW == 1) {
//overwrite with blank
lcd_gotoxy((player.y+player.h-1)/CHARH, (player.x+player.w)/CHARW);
_lcd_write_byte(TRANSPARENT,1);
}
changed = true;
player.x--;
}
//if right pressed
if(is_pressed(6) && player.x + player.w < SCREEN_WIDTH) {
// if player pad leaving a screen character
if(player.x%CHARW == CHARW-1) {
//overwrite with blank
lcd_gotoxy(player.y/CHARH, player.x/CHARW);
_lcd_write_byte(TRANSPARENT,1);
}
changed = true;
player.x++;
}
ball.y += ballDY;
if(ball.y == player.y) {
ball.x += ballDX;
if(ball.x >= player.x && ball.x <= player.x+player.w) {
ballDY *= -1;
ball.y += ballDY*2;
}
}
else {
if(ball.y/CHARH > YCHARS-4 ) {
if(bricks[ball.x/CHARW][YCHARS-(ball.y/CHARH)-1].visible == true) {
bricks[ball.x/CHARW][YCHARS-(ball.y/CHARH)-1].visible = false;
lcd_gotoxy(ball.y/CHARH, ball.x/CHARW);
_lcd_write_byte(TRANSPARENT,1);
ballDY *= -1;
ball.y += ballDY;
points++;
PORTB = points;
}
}
ball.x += ballDX;
if(ball.y/CHARH > YCHARS-4 ) {
if(bricks[ball.x/CHARW][YCHARS-(ball.y/CHARH)-1].visible == true) {
bricks[ball.x/CHARW][YCHARS-(ball.y/CHARH)-1].visible = false;
lcd_gotoxy(ball.y/CHARH, ball.x/CHARW);
_lcd_write_byte(TRANSPARENT,1);
ballDX *= -1;
ball.x += ballDX;
points++;
PORTB = points;
}
}
}
if(ball.y == SCREEN_HEIGHT-1)
ballDY *= -1;
if(ball.x == 0 || ball.x == SCREEN_WIDTH-1)
ballDX *= -1;
if(changed) {
Draw(&player, 1);
}
//DRAW BALL
if(ball.x/CHARW != oldXSquare || ball.y/CHARH != oldYSquare) {
//Clear ball position //TODO: if leaving CG square
lcd_gotoxy(oldYSquare,oldXSquare);
_lcd_write_byte(TRANSPARENT,1);
oldXSquare = ball.x/CHARW;
oldYSquare = ball.y/CHARH;
}
if(player.y/CHARH == oldYSquare && player.x/CHARW == oldXSquare)
;//Draw(&ball, 1);
else if(player.y/CHARH == oldYSquare && (player.x+player.w)/CHARW == oldXSquare)
;//Draw(&ball, 2);
else
Draw(&ball, 0);
if(ball.y <= 0) {
_delay_ms(1000);
lcd_clear();
lcd_gotoxy(6,2);
lcd_puts("You Lost");
_delay_ms(3000);
lcd_clear();
break;
}
else if(points == 12) {
_delay_ms(1000);
lcd_clear();
lcd_gotoxy(6,1);
lcd_puts("You Won!");
_delay_ms(3000);
lcd_clear();
break;
}
//do timeing
_delay_ms(100);
changed = hit = false;
}
}
|
C
|
#include "chat.h"
#include <pthread.h>
void* recv_func(void* arg)
{
int fd_server = (int)arg ;
char buf[1024];
while(1)
{
//printf("AA\n");
bzero(buf, 1024);
recvfrom(fd_server,buf,1024, 0 ,NULL, NULL);
printf("recv: %s \n",buf);
}
}
int main (int argc, char const *argv[])
{
if(argc!=3)
{
printf("USAGE: EXE IP PORT\n");
exit(-1);
}
int fd_client;
int choice;
fd_client= socket(AF_INET, SOCK_DGRAM,0);
if(fd_client == -1)
{
perror("socket");
exit(-1);
}
pthread_t tid ;
pthread_create(&tid,NULL,recv_func, (void*)fd_client);
SA server_addr;
bzero(&server_addr,sizeof(SA));
server_addr.sin_family = AF_INET;
server_addr.sin_port= htons(atoi(argv[2]));
server_addr.sin_addr.s_addr=inet_addr(argv[1]);
MSG msg_on,msg_chat,msg_off,msg_show;
bzero(&msg_on, sizeof(MSG));
msg_on.s_type= MSG_ON;
sendto(fd_client,&msg_on, sizeof(MSG),0,(struct sockaddr*)&server_addr,sizeof(SA));
while(1)
{
printf("-------------------------------------------\n");
printf("1.群聊\n2.单聊\n3.显示当前在线\n");
printf("-------------------------------------------\n");
scanf("%d",&choice);
getchar();
if(choice==1)
{
while(bzero(&msg_chat,sizeof(MSG)), fgets(msg_chat.s_msg, MSG_SIZE, stdin) != NULL)
{
//printf("BB\n");
msg_chat.s_type = MSG_GRP;
msg_chat.s_len = strlen(msg_chat.s_msg);
sendto(fd_client,&msg_chat, sizeof(MSG),0,(struct sockaddr*)&server_addr,sizeof(SA));
}
}else if(choice==2)
{
char bufip[128];
int bufport;
memset(bufip,0,128);
printf("input ip u want to send to:\n");
scanf("%s",&bufip);
getchar();
printf("input port of the ip\n");
scanf("%d",&bufport);
getchar();
//printf("%s\n", bufip);
while(bzero(&msg_chat,sizeof(MSG)),fgets(msg_chat.s_msg,MSG_SIZE,stdin)!=NULL)
{
msg_chat.s_type=MSG_USR;
msg_chat.s_len=strlen(msg_chat.s_msg);
msg_chat.s_addr.sin_addr.s_addr=inet_addr(bufip);
msg_chat.s_addr.sin_port=htons(bufport);
sendto(fd_client,&msg_chat, sizeof(MSG),0,(struct sockaddr*)&server_addr,sizeof(SA));
}
}else if(choice ==3)
{
bzero(&msg_show,sizeof(MSG));
msg_show.s_type= MSG_SHOW;
sendto(fd_client,&msg_show,sizeof(MSG),0,(struct sockaddr*)&server_addr,sizeof(SA));
}
}
//printf("CC\n");
bzero(&msg_off,sizeof(MSG));
msg_off.s_type = MSG_OFF;
sendto(fd_client,&msg_off, sizeof(MSG),0,(struct sockaddr*)&server_addr,sizeof(SA));
close(fd_client);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
//code by Mateusz Kądziela, 148271
sem_t sem;
int cap_a = 0, cap_b = 0, t_min = 0, t_max = 0; //initializing global variables
float p = 0;
void *visitor(void* i) {
int id = *(int*)i;
int watch = rand() % (t_max - t_min) + t_min; //getting a time for staying in a room for each visitor
while(1) { //entering hall A
sem_wait(&sem); //waiting for semaphore to open
if (cap_a > 1) { //if there is space in hall A, enter (we are always leaving one spot free, so people from B can exit easily)
printf("Visitor %d has entered hall A\n", id);
cap_a--; //decreasing capacity left in hall A
sem_post(&sem); //releasing semaphore
sleep(watch); //watching art
break;
}
sem_post(&sem); //if there was no space in hall A, release semaphore
}
int rng = rand()%100;
if (rng <= 100*p){ //deciding if one enters hall B
while(1){ //entering hall B
sem_wait(&sem); //waiting for semaphore to open
if (cap_b > 0){ //if there is space in hall B, enter
printf("Visitor %d has entered hall B\n", id);
cap_a++; //increasing capacity left in hall A
cap_b--; //decreasing capacity left in hall B
sem_post(&sem); //releasing semaphore
sleep(watch); //watching art
break;
}
sem_post(&sem); //if there was no space in hall B, release semaphore
}
//leaving museum from hall B (no need to check if we can leave through A because there is always one spot free there)
sem_wait(&sem); //waiting for semaphore to open
printf("Visitor %d has left hall B and then hall A\n", id);
cap_b++; //increasing capacity left in hall B
sem_post(&sem); //releasing semaphore
}
else { //leaving museum from hall A
sem_wait(&sem); //waiting for semaphore to open
printf("Visitor %d has left hall A\n", id);
cap_a++; //increasing capacity left in hall A
sem_post(&sem); //releasing semaphore
}
return NULL;
}
int main() {
int visitors = 0;
srand(time(NULL));
sem_init(&sem, 0, 1); //initializing semaphore for threads, starting value 1
//getting input
puts("How many people will visit the museum?");
scanf("%d", &visitors);
puts("What is the capacity of hall A?");
scanf("%d", &cap_a);
puts("What is the capacity of hall B (smaller than A)?");
scanf("%d", &cap_b);
puts("What is the minimal time a visitor spends in a hall (in seconds)?");
scanf("%d", &t_min);
puts("What is the maximal time a visitor spends in a hall (in seconds)?");
scanf("%d", &t_max);
puts("What is the probability that a visitor enters hall B?");
scanf("%f", &p);
pthread_t threads[visitors]; //create an array of threads
int array[visitors]; //array for numbers from 1 to visitors
for (int i = 0; i < visitors; i++){
array[i] = i+1;
}
//creating threads
for (int i = 0; i < visitors; i++){
pthread_create(&threads[i], NULL, visitor, &array[i]);
}
//terminating threads
for (int i = 0; i < visitors; i++){
pthread_join(threads[i], NULL);
}
//terminating semaphore
sem_destroy(&sem);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define ZERO 0
#define ONE 1
int length;
int binaryMaker(int len, int arr[], int i);
int main() {
scanf("%d", &length);
int pattern[length];
binaryMaker(length, pattern, 0);
return 0;
}
int binaryMaker(int len, int arr[], int i) {
if(i == len) {
for(int i = 0; i < len; i++) {
printf("%d", arr[i]);
}
printf("\n");
return 0;
}
arr[i] = 0;
binaryMaker(len, arr, i + 1);
arr[i] = 1;
binaryMaker(len, arr, i + 1);
}
|
C
|
#include <stdio.h>
int power(int,int);
int main()
{
int base,pow,result;
printf("Enter base number");
scanf("%d",&base);
printf("Enter power number");
scanf("%d",&pow);
result = power(base,pow);
printf("Result is %d",result);
return 0;
}
int power(int base,int pow)
{
if (pow==0)
return 1;
else
return power(base,pow-1)*base;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h> // clock_t which is the amount of clock cycles since the program began
#include "queue.h"
#include "global.h"
/*
* Initializes a queue and returns it
*/
Queue* initializeQueue()
{
Queue *queue = (Queue*) malloc(sizeof(Queue));
queue->head = queue ->tail = NULL;
queue->size = 0;
return queue;
}
// TODO: change to use global queue - jobQueue
void enQueue(Node *newNode)
{
newNode->arrivalTime = clock();
// If the queue is empty set the head and tail to the new node
// TODO: Lock the critical region - the jobQueue
if (job_queue->size == 0)
{
job_queue->head = job_queue->tail = newNode;
job_queue->tail->next = NULL;
job_queue->size++;
}
else
{
// Add the new node to the queue and move the tail to the end of the queue (new Node)
job_queue->tail->next = newNode;
job_queue->tail = job_queue->tail->next;
job_queue->tail->next = NULL;
job_queue->size++;
}
}
// TODO: change to use global queue - jobQueue
Node* deQueue()
{
if (job_queue->size == 0)
{
return NULL;
}
// TODO: Lock the critical region - the jobQueue
Node *removedNode;
removedNode = job_queue->head;
job_queue->head = job_queue->head->next;
job_queue->size--;
return removedNode;
}
void copy_node(Node *destination, Node *source)
{
destination->name = (char*) malloc(strlen(source->name) + 1);
strcpy(destination->name, source->name);
destination->arrivalTime = source->arrivalTime;
destination->jobPriority = source->jobPriority;
destination->jobTime = source->jobTime;
}
void swap_nodes(Node *node1, Node *node2)
{
Node *tempNode = (Node *) malloc(sizeof(Node)); // Create a place in memory to hold temporary information
copy_node(tempNode, node1);
copy_node(node1, node2);
copy_node(node2, tempNode);
free (tempNode);
}
void printQueue()
{
if (job_queue->size == 0)
{
printf("There are no jobs pending or running.\n");
}
else
{
printf("Name CPU_Time Pri Arrival_Time Progress\n");
Node *tempNode = job_queue->head;
char str_time[11];
char str_pri[6];
while (tempNode != NULL)
{
snprintf(str_time, 10, "%d", tempNode->jobTime);
snprintf(str_pri, 5, "%d", tempNode->jobPriority);
printf("%-15s%-11s%-6s\n", tempNode->name, str_time, str_pri);
tempNode = tempNode->next;
}
}
}
void print_num_jobs()
{
printf("Total number of jobs in the queue: %d\n", job_queue->size);
}
|
C
|
#ifndef SHELL_H
#define SHELL_H
//return type: char ** (pointer to a char pointer)
//arguments: char * (a string)
//fxn: parses the pipes in a given line to get arguments
char ** parse_pipe(char *line);
//return type: char ** (pointer to a char pointer)
//arguments: char * (a string)
//fxn: parses the > sign in a given line to get arguments
char ** parse_greater(char *line);
//return type: char ** (pointer to a char pointer)
//arguments: char * (a string)
//fxn: parses the < in a given line to get arguments
char ** parse_less(char *line);
//return type: char ** (pointer to a char pointer)
//arguments: char * (a string)
//fxn: parses the semicolons in a given line to get commands
char ** parse_semi(char *line);
//return type: char ** (pointer to a char pointer)
//arguments: char * (a string)
//fxn: parses spaces in a given line to get arguments
char ** parse_space(char *line);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
void main(){
int i, j, x;
int M[5][5];
printf("Digite os valores das posicoes.\n");
for(i=0; i<5; i++){
for(j=0; j<5; j++){
printf("[%d][%d]: ", i, j);
scanf("%d", &M[i][j]);
}
}
printf("Valor de Busca: ");
scanf("%d", &x);
for(i=0; i<5; i++){
for(j=0; j<5; j++){
if(M[i][j] == x){
printf("Valor encontrado na posicao [%d][%d].\n", i, j);
}
}
}
for(i=0; i<5; i++){
for(j=0; j<5; j++){
printf("%d - ", M[i][j]);
}
printf("\n");
}
system("pause");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "estiva/op.h"
#include "estiva/mesh.h"
#include "estiva/ary.h"
#include <unistd.h>
#include <sys/types.h>
static void pltmsh(FILE *fp, xyc *Z, nde *N)
{
long e, a, b, c;
for(e=1;e<=dim1(N);e++){
a = N[e].a, b = N[e].b, c = N[e].c;
fprintf(fp,"%f %f\n",Z[a].x,Z[a].y);
fprintf(fp,"%f %f\n",Z[b].x,Z[b].y);
fprintf(fp,"%f %f\n",Z[c].x,Z[c].y);
fprintf(fp,"%f %f\n",Z[a].x,Z[a].y);
fprintf(fp,"\n\n");
}
}
static void sleep_forever(void)
{
sleep(60*3);
}
void estiva_xmesh(xyc *Z)
{
if ( fork() == 0 ) {
long e, a, b, c;
FILE *pp;
static nde *N;
delaunay(Z,N);
pp = popen("gnuplot","w");
#if 0
for (e=1; e<=dim1(N); e++) {
a = N[e].a, b = N[e].b, c = N[e].c;
A = N[e].A, B = N[e].B, C = N[e].C;
fprintf(pp,"set label \"%ld\" at %f , %f\n",a,Z[a].x,Z[a].y);
fprintf(pp,"set label \"%ld\" at %f , %f\n",b,Z[b].x,Z[c].y);
fprintf(pp,"set label \"%ld\" at %f , %f\n",c,Z[b].x,Z[c].y);
fprintf(pp,"set label \"%ld\" at %f , %f\n",A,(Z[b].x+Z[c].x)/2.0,(Z[b].y+Z[c].y)/2.0);
fprintf(pp,"set label \"%ld\" at %f , %f\n",B,(Z[c].x+Z[a].x)/2.0,(Z[c].y+Z[a].y)/2.0);
fprintf(pp,"set label \"%ld\" at %f , %f\n",C,(Z[a].x+Z[b].x)/2.0,(Z[a].y+Z[b].y)/2.0);
}
#endif
for (e=1; e<=dim1(N); e++) {
a = N[e].a, b = N[e].b, c = N[e].c;
//A = N[e].A, B = N[e].B, C = N[e].C;
fprintf(pp,"set label \"%ld\" at %f , %f\n",a,Z[a].x,Z[a].y);
fprintf(pp,"set label \"%ld\" at %f , %f\n",b,Z[b].x,Z[b].y);
fprintf(pp,"set label \"%ld\" at %f , %f\n",c,Z[c].x,Z[c].y);
fprintf(pp,"set label \"(%ld)\" at %f , %f\n",e,(Z[a].x+Z[b].x+Z[c].x)/3.0,(Z[a].y+Z[b].y+Z[c].y)/3.0);
}
fprintf(pp,"plot '-' title \"\" with lines\n");
pltmsh(pp,Z,N);
fprintf(pp,"e\n");
fflush(pp);
sleep_forever();
pclose(pp);
exit(0);
}
}
|
C
|
#include <cudest.h>
#include <errno.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
// FIXME: we really ought take a bus specification rather than a device number,
// since the latter are unsafe across hardware removal/additions.
static void
usage(const char *a0){
fprintf(stderr,"usage: %s devno\n",a0);
}
static int
getzul(const char *arg,unsigned long *zul){
char *eptr;
if(((*zul = strtoul(arg,&eptr,0)) == ULONG_MAX && errno == ERANGE)
|| eptr == arg || *eptr){
fprintf(stderr,"Expected an unsigned integer, got \"%s\"\n",arg);
return -1;
}
return 0;
}
int main(int argc,char **argv){
unsigned total = 0;
unsigned long zul;
CUdevice dev;
CUcontext c;
int cerr;
if(argc != 2){
usage(argv[0]);
exit(EXIT_FAILURE);
}
if(getzul(argv[1],&zul)){
usage(argv[0]);
exit(EXIT_FAILURE);
}
if(cuInit(0)){
fprintf(stderr,"Couldn't initialize cuda\n");
exit(EXIT_FAILURE);
}
if(cuDeviceGet(&dev,zul)){
fprintf(stderr,"Couldn't get device %lu\n",zul);
exit(EXIT_FAILURE);
}
while((cerr = cuCtxCreate(&c,0,dev)) == CUDA_SUCCESS){
++total;
}
printf("Context creation failed (%d).\n",cerr);
return printf("Created %u contexts.\n",total) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sshih <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/07 13:59:59 by sshih #+# #+# */
/* Updated: 2018/05/07 18:24:46 by sshih ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_countwords(const char *str, char c)
{
int i;
i = 0;
while (*str != '\0')
{
while (*str && *str == c)
str++;
if(*str && *str != c)
{
i++;
while (*str && *str != c)
str++;
}
}
return (i);
}
char *ft_malloc_word(char const *str, char c)
{
char *new_word;
int i;
i = 0;
while (str[i] != c)
i++;
new_word = (char *)malloc(sizeof(char) * (i + 1));
i = 0;
while (str[i] != c)
{
new_word[i] = str[i];
i++;
}
new_word[i] = '\0';
return (new_word);
}
char **ft_strsplit(char const *s, char c)
{
char **new;
int i;
new = (char **)malloc(sizeof(char *) * (ft_countwords(s, c) + 1));
if (!new || !s)
return (NULL);
i = 0;
while (*s)
{
while (*s == c)
s++;
if (*s != c)
{
new[i] = ft_malloc_word(s, c);
i++;
while (*s != c)
s++;
}
}
new[i] = 0;
return (new);
}
|
C
|
/*
* ESE519 LAB2-3.2.c
*
* Created: 2018/9/18 20:03:13
* Author : Wang
*/
#include <avr/io.h>
#define F_CPU 16000000
#define BAUDRATE 9600
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char buffer [8];
int l,k = 0;
unsigned int flag1 = 0,flag2 = 0,width = 0,sum = 0;
int main(void)
{
//enable serial communication
UCSR0A = (1<<U2X0); // double speed mode
UBRR0H = (unsigned char) ((F_CPU/8/BAUDRATE-1) >> 8);
UBRR0L = (unsigned char) (F_CPU/8/BAUDRATE-1);
UCSR0B = (1<<RXEN0) | (1<<TXEN0); // enable rx and tx
//enable ports
DDRB |= (1 << PORTB1);
DDRB |= (1 << PORTB2);
DDRB |= (1 << PORTB3);
DDRB |= (1 << PORTB4);
PORTB |= (1 << PORTB1);
//initialize interrupt
//TCCR1B |= (1 << WGM12);
OCR1A = TCNT1 + 10;
TIMSK1 |= (1 << OCIE1A);
TCCR1B |= (1 << CS11); // 8
TCCR1B |= (1 << ICES1);
TIMSK1 |= (1 <<(TOIE1));
sei();
/* Replace with your application code */
while (1)
{
//print the width of pulses
l=sprintf (buffer, "%d\n", width);
while(k<l)
{
UDR0=buffer[k];
++k;
while (!(UCSR0A & 0x40));
UCSR0A |= 0x40;
//change ports output by range of pulses' width
if ((width >= 0) & (width <= 1000))
{
PORTB &= ~(1 << PORTB2);
PORTB &= ~(1 << PORTB3);
PORTB &= ~(1 << PORTB4);
}
if ((width > 1000) & (width <= 2000))
{
PORTB |= (1 << PORTB2);
PORTB &= ~(1 << PORTB3);
PORTB &= ~(1 << PORTB4);
}
if ((width > 2000) & (width <= 3000))
{
PORTB &= ~(1 << PORTB2);
PORTB |= (1 << PORTB3);
PORTB &= ~(1 << PORTB4);
}
if ((width > 3000) & (width <= 4000))
{
PORTB &= ~(1 << PORTB2);
PORTB &= ~(1 << PORTB3);
PORTB |= (1 << PORTB4);
}
if ((width > 4000) & (width <= 5000))
{
PORTB |= (1 << PORTB2);
PORTB |= (1 << PORTB3);
PORTB &= ~(1 << PORTB4);
}
if ((width > 5000) & (width <= 6000))
{
PORTB |= (1 << PORTB2);
PORTB &= ~(1 << PORTB3);
PORTB |= (1 << PORTB4);
}
if ((width > 6000) & (width <= 7000))
{
PORTB &= ~(1 << PORTB2);
PORTB |= (1 << PORTB3);
PORTB |= (1 << PORTB4);
}
if ((width > 7000))
{
PORTB |= (1 << PORTB2);
PORTB |= (1 << PORTB3);
PORTB |= (1 << PORTB4);
}
}
k=0;
}
}
ISR(TIMER1_COMPA_vect)
{
//generate pulse
PORTB &= ~(1 << PORTB1);
//disable output compare, enable input capture
TIMSK1 &= ~(1 << OCIE1A);
TIMSK1 |= (1 << ICIE1);
}
ISR(TIMER1_CAPT_vect)
{
if(TCCR1B &(1<< ICES1))
{
flag1 = ICR1;
TCCR1B &= ~(1 << ICES1);//falling edge
//TIFR1 |= (1<<ICF1);
}
else
{
flag2 = ICR1;
TCCR1B |= (1 << ICES1);//raising edge
//disable input capture, enable output compare
TIMSK1 &= ~(1 << ICIE1);
TIMSK1 |= (1 << OCIE1A);
//record the width of echo
width = flag2 - flag1;
//_delay_us(300);
TCNT1 = 0x0000;
PORTB |= (1 << PORTB1);
}
}
ISR(TIMER1_OVF_vect)
{
//reset cycle for unexpected overflow
TIMSK1 &= ~(1 << ICIE1);
TIMSK1 |= (1 << OCIE1A);
PORTB |= (1<<PORTB1);
TCNT1 = 0x0000;
}
|
C
|
// tut 4 q3
// Write a program to find a key in a 2D array
#include <stdio.h>
void main() {
int i, j, k, key, flag = 0, beg, end, mid, resrw, rescl;
int a[2][5] = { {11,12,13,14,15}, {16,17,18,19,20} };
printf("Enter the key that is to be searched\n");
scanf("%d", &key);
for (i = 0;i < 2 && flag == 0;i++) {
// Checking row first
if (key >= a[i][0] && key <= a[i][4]) {
// and then checking inside column using binary search
beg = 0;
end = 4;
while (beg <= end) {
mid = (beg + end) / 2;
if (a[i][mid] < key) beg = mid + 1;
else if (a[i][mid] > key) end = mid - 1;
else {
flag = 1;
resrw = i + 1;
rescl = mid + 1;
break;
}
}
}
}
if (flag == 1)
printf("The key is located in row %d, column %d\n", resrw, rescl);
else
printf("The key is not present\n");
}
|
C
|
// Definition for arrays:
// typedef struct arr_##name {
// int size;
// type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
// arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
// return a;
// }
//
//
int partition(arr_integer a,int low, int high){
int left = low;
int right = high;
int tempValue=0;
int *pivotValue;
pivotValue=&(a.arr[high]);
while(true){
while(a.arr[left]==-1){
left++;
}
while(a.arr[right]==-1){
right--;
pivotValue=&(a.arr[right]);
}
while(a.arr[left]<(*pivotValue)){
left++;
}
while(a.arr[right]>(*pivotValue)){
right--;
}
if(a.arr[left]>=(*pivotValue) && a.arr[right]<=(*pivotValue)){
tempValue=a.arr[left];
a.arr[left]=a.arr[right];
a.arr[right]=tempValue;
left++;
}
if(left>=right){
break;
}
}
return high;
}
void quickSort(arr_integer a,int low, int high){
int pivotIndex=0;
if(low<high){
pivotIndex= partition(a,low,high);
quickSort(a,low,pivotIndex-1);
quickSort(a,pivotIndex+1,high);
}
}
arr_integer sortByHeight(arr_integer a) {
int arrayLength=a.size;
quickSort(a,0,arrayLength-1);
return a;
}
|
C
|
/******************************************************************
* Copyright (C) 2010
* by Pascal Lesage (Keosys)
* Xavier Lecourtier (Keosys) [email protected]
* Sylvain David (IRCCyN, University of Nantes, France) [email protected]
* Jiazi Yi (IRCCyN, University of Nantes, France) [email protected]
* Benoit Parrein (IRCCyN, University of Nantes, France) [email protected]
*
* Members of SEREADMO (French Research Grant ANR-05-RNRT-02803)
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
****************************************************************
*******************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "mojette.h"
projection_t* projection_new(int p, int q, int l, int k)
{
projection_t* new;
if ((new = malloc(sizeof(projection_t))) == NULL)
return NULL;
new->p = p;
new->q = q;
new->size = abs(p) * (l - 1) + abs(q) * (k - 1) + 1;
if ((new->bins = calloc(new->size, sizeof(char))) == NULL)
{
free(new);
return NULL;
}
return new;
}
void projection_free(projection_t* projection)
{
if (projection != NULL)
{
if (projection->bins != NULL)
free(projection->bins);
free(projection);
}
}
void line_free(line_t* line)
{
if (line != NULL)
{
if (line->val != NULL)
free(line->val);
free(line);
}
}
support_t* support_new(int l, int k)
{
support_t* new;
if ((new = malloc(sizeof(support_t))) == NULL)
return NULL;
new->l = l;
new->k = k;
if ((new->pixels = calloc(l * k, sizeof(char))) == NULL)
{
free(new);
return NULL;
}
return new;
}
void support_free(support_t* support)
{
if (support != NULL)
{
if (support->pixels != NULL)
free(support->pixels);
free(support);
}
}
void forward(support_t* support, projection_t** projections, int nr_prj)
{
int l;
int k;
projection_t** pp;
for (l = 0; l < support->l; l ++)
{
for (k = 0; k < support->k; k ++)
{
for (pp = projections; pp < projections + nr_prj; pp ++)
{
int offset;
projection_t* p;
p = *pp;
offset = p->p < 0 ? (support->l - 1) * p->p : 0;
p->bins[k * p->q + l * p->p - offset] ^=
support->pixels[l * support->k + k];
}
}
}
}
typedef struct univoc {
struct univoc* next;
unsigned long* u;
unsigned long* d;
char* p;
} univoc_t;
void inverse_system(support_t* support, projection_t** projections, int nr_prj, line_t** ligne, int nb_ligne)
{
int i;
int k;
int l;
long d;
unsigned long** pu;
unsigned long** pd;
univoc_t* curr;
univoc_t* head;
univoc_t* tail;
int nb_pixel;
//si on a pas de projection alors on remplit directement le support
if(nr_prj==0 && support->l==nb_ligne){
for(i = 0; i < nb_ligne; i ++)
{
for (k = 0; k < (support->k); k ++)
{
int j;
support->pixels[(ligne[i]->num_line) * support->k + k] = ligne[i]->val[k];
}
}
}else{
pu = malloc(nr_prj * sizeof(unsigned long*));
pd = malloc(nr_prj * sizeof(unsigned long*));
for (i = 0; i < nr_prj; i ++)
{
projection_t* p;
int size;
p = projections[i];
size = abs(p->p) * (support->l - 1) + abs(p->q) * (support->k - 1) + 1;
pu[i] = calloc(size, sizeof(unsigned long));
pd[i] = calloc(size, sizeof(unsigned long));
}
d = 0;
for (l = 0; l < support->l; l++)
{
for (k = 0; k < support->k; k++)
{
for (i = 0; i < nr_prj; i ++)
{
int offset = projections[i]->p < 0 ?
(support->l - 1) * projections[i]->p : 0;
int b = k * projections[i]->q + l * projections[i]->p - offset;
pu[i][b] += 1;
pd[i][b] += d;
}
d ++;
}
}
unsigned long diet;
for(i = 0; i < nb_ligne; i ++){
for (k = 0; k < (support->k); k ++)
{
int j;
support->pixels[(ligne[i]->num_line) * support->k + k] = ligne[i]->val[k];
diet = k + (ligne[i]->num_line) * support->k;
for (j = 0; j < nr_prj; j ++)
{
//on calcule le offset
int offset = projections[j]->p < 0 ?
(support->l - 1) * projections[j]->p : 0;
//on calcule l'indice du bin de la projection impacté
int b = k * projections[j]->q + (ligne[i]->num_line) * projections[j]->p - offset;
// on met à jour le bin de la projection
projections[j]->bins[b] ^= ligne[i]->val[k];
// on met à jour le diet
pd[j][b] -= diet;
// on met à jour
pu[j][b] -= 1;
}
}
}
head = NULL;
tail = NULL;
for (i = 0; i < nr_prj; i ++)
{
int j;
for (j = 0; j < projections[i]->size; j ++)
{
if (pu[i][j] == 1)
{
univoc_t* new = malloc(sizeof(univoc_t));
new->next = NULL;
new->u = (pu[i]) + j;
new->d = (pd[i]) + j;
new->p = (projections[i]->bins) + j;
diet = *(new->d);
l = (int)(diet / support->k);
k = (int)(diet - l * support->k);
if (! head)
head = new;
else
tail->next = new;
tail = new;
}
}
}
nb_pixel = 0;
curr = head;
while (nb_pixel ++ < ((support->l * support->k)-(support->k * nb_ligne)))
{
int j;
char bin;
while (*(curr->u) != 1)
curr = curr->next;
bin = *(curr->p);
diet = *(curr->d);
l = (int)(diet / support->k);
k = (int)(diet - l * support->k);
support->pixels[l * support->k + k] = bin;
for (j = 0; j < nr_prj; j ++)
{
int offset = projections[j]->p < 0 ?
(support->l - 1) * projections[j]->p : 0;
int b = k * projections[j]->q + l * projections[j]->p - offset;
projections[j]->bins[b] ^= bin;
pd[j][b] -= diet;
pu[j][b] -= 1;
if (pu[j][b] == 1)
{
univoc_t* new = malloc(sizeof(univoc_t));
new->next = NULL;
new->u = (pu[j]) + b;
new->d = (pd[j]) + b;
new->p = (projections[j]->bins) + b;
tail->next = new;
tail = new;
}
}
}
}
}
void inverse(support_t* support, projection_t** projections, int nr_prj)
{
int i;
int k;
int l;
long d;
unsigned long** pu;
unsigned long** pd;
univoc_t* curr;
univoc_t* head;
univoc_t* tail;
int nb_pixel;
pu = malloc(nr_prj * sizeof(unsigned long*));
pd = malloc(nr_prj * sizeof(unsigned long*));
for (i = 0; i < nr_prj; i ++)
{
projection_t* p;
int size;
p = projections[i];
size = abs(p->p) * (support->l - 1) + abs(p->q) * (support->k - 1) + 1;
pu[i] = calloc(size, sizeof(unsigned long));
pd[i] = calloc(size, sizeof(unsigned long));
}
d = 0;
for (l = 0; l < support->l; l++)
{
for (k = 0; k < support->k; k++)
{
for (i = 0; i < nr_prj; i ++)
{
int offset = projections[i]->p < 0 ?
(support->l - 1) * projections[i]->p : 0;
int b = k * projections[i]->q + l * projections[i]->p - offset;
pu[i][b] += 1;
pd[i][b] += d;
}
d ++;
}
}
head = NULL;
tail = NULL;
for (i = 0; i < nr_prj; i ++)
{
int j;
for (j = 0; j < projections[i]->size; j ++)
{
if (pu[i][j] == 1)
{
univoc_t* new = malloc(sizeof(univoc_t));
new->next = NULL;
new->u = (pu[i]) + j;
new->d = (pd[i]) + j;
new->p = (projections[i]->bins) + j;
if (! head)
head = new;
else
tail->next = new;
tail = new;
}
}
}
nb_pixel = 0;
curr = head;
while (nb_pixel ++ < support->l * support->k)
{
int j;
char bin;
unsigned long diet;
while (*(curr->u) != 1)
curr = curr->next;
bin = *(curr->p);
diet = *(curr->d);
l = (int)(diet / support->k);
k = (int)(diet - l * support->k);
support->pixels[l * support->k + k] = bin;
for (j = 0; j < nr_prj; j ++)
{
int offset = projections[j]->p < 0 ?
(support->l - 1) * projections[j]->p : 0;
int b = k * projections[j]->q + l * projections[j]->p - offset;
projections[j]->bins[b] ^= bin;
pd[j][b] -= diet;
pu[j][b] -= 1;
if (pu[j][b] == 1)
{
univoc_t* new = malloc(sizeof(univoc_t));
new->next = NULL;
new->u = (pu[j]) + b;
new->d = (pd[j]) + b;
new->p = (projections[j]->bins) + b;
tail->next = new;
tail = new;
}
}
}
exit(0);
}
|
C
|
/*
5.3-C-10th.6
结构体位宽、位段
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//定义结构体变量的位宽
struct cls_t{
unsigned int a : 8;
/*int b : ;*/
/*char name[10];*/
};
int main(void)
{
struct cls_t a;
a.a = 255 + 1; //unsigned int型溢出后为0
printf("a.a = %d\n", a.a);
printf("sizeof(struct cls_t) = %d\n", sizeof(struct cls_t));//打印结构体占用的内存空间
//尽管使用位宽,但是结构体占用空间以默认4字节为单位
return 0;
}
|
C
|
/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
int main()
{
int x,y;
scanf("%d %d",&x,&y);
printf("Before Swapping :%d %d",x,y);
x=x+y;
y=x-y;
x=x-y;
printf("\nAfter Swapping :%d %d",x,y);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
char *date2string (int ts) {
char *str = malloc (11);
int d,m,y;
y = ts/(30*12);
ts %=(30*12);
m = ts/30;
ts %=30;
d = ts;
sprintf (str, "%02d/%02d/%04d",d,m,y);
return str;
}
int string2date (char *date) {
int d,m,y,ret;
sscanf (date, "%d/%d/%d",&d,&m,&y);
ret = d+m*30+y*30*12;
return ret;
}
void get_min_max (char *file, unsigned int *min, unsigned int *max) {
FILE *fp;
char line[1024];
unsigned int mn,mx,date[3],tmp;
mn=~0;
mx=0;
fp = fopen (file,"r");
while (fgets (line, sizeof(line), fp)) {
sscanf (line, "%d/%d/%d",&date[0],&date[1],&date[2]);
tmp = string2date(line);
if (tmp>mx) {
mx=tmp;
}
if (tmp<mn) {
mn=tmp;
}
}
*min = mn;
*max = mx;
fclose (fp);
}
int main () {
unsigned int min, max;
get_min_max ("input.txt",&min,&max);
printf ("min: %s\n",date2string(min));
printf ("max: %s\n",date2string(max));
printf ("diff: %s\n",date2string(max-min));
return 0;
}
|
C
|
/* file: menu_pio.c */
/****************************************************************************
*
* Include Microsoft definitions
*
***************************************************************************/
#include <stdlib.h>
#include <dos.h>
#include <conio.h>
#include <hayes.h>
//#include <gnd.h>
#include "ground.h"
#include "menu_utl.h"
/****************************************************************************
*
* end of include files
*
***************************************************************************/
void pio_menu(void)
{
int i;
char choice = 'x';
char temp[80];
com_puts("\r\n\r\nPIO FUNCTION MENU\r\n");
while (toupper(choice) != 'Q') {
com_puts("\r\nINPUTS ARE UPDATED WITH EACH CHOICE\r\n");
printf("\r\n Input byte = %02x\t\t\t Output byte = %02x\r\n",dspio_input_byte(), dspio_read_output_byte());
printf("\r\n Input bit: 7 6 5 4 3 2 1 0\t\t Output bit: 7 6 5 4 3 2 1 0\r\n Currently:");
for (i=7; i>=0; i--)
printf(" %d", (int)dspio_input_bit((unsigned char)i));
printf("\t\t Currently: ");
for (i=7; i>=0; i--)
printf(" %d", (int)dspio_read_output_bit((unsigned char)i));
com_puts("\r\n\r\n\r\nOUTPUT CHOICES\r\n");
com_puts(" 1 Clear all bits\r\n");
com_puts(" 2 Clear single bit\r\n");
com_puts(" 3 Clear masked bits\r\n");
com_puts(" 4 Set all bits\r\n");
com_puts(" 5 Set single bit\r\n");
com_puts(" 6 Set masked bits\r\n");
com_puts(" 7 Set bit pattern\r\n");
com_puts("\r\n Enter Choice number, or Q to quit: ");
choice = toupper(com_getc());
switch(choice) {
case '1':
dspio_clear_all_bits();
break;
case '2':
printf("\r\nClear which bit (0-7)? ");
//scanf("%d",&i);
com_gets(temp);
i = atoi(temp) & 0x0f;
dspio_clear_bit((unsigned char)i);
break;
case '3':
//printf("\nEnter mask byte (hex) to clear (1's cleared, 0's unchanged): ");
printf("\r\nEnter mask byte (dec) to clear (1's cleared, 0's unchanged): ");
//scanf("%x",&i);
com_gets(temp);
i = atoi(temp) & 0x0f;
dspio_clear_masked_bits((unsigned char)i);
break;
case '4':
dspio_set_all_bits();
break;
case '5':
printf("\r\nSet which bit (0-7)? ");
//scanf("%d",&i);
com_gets(temp);
i = atoi(temp) & 0x0f;
dspio_set_bit((unsigned char)i);
break;
case '6':
//printf("\nEnter mask byte (hex) to set (1's set, 0's unchanged): ");
printf("\r\nEnter mask byte (dec) to set (1's set, 0's unchanged): ");
//scanf("%x",&i);
com_gets(temp);
i = atoi(temp) & 0x0f;
dspio_set_masked_bits((unsigned char)i);
break;
case '7':
//printf("\nEnter pattern byte (hex) to output: ");
printf("\r\nEnter pattern byte (dec) to output: ");
//scanf("%x",&i);
com_gets(temp);
i = atoi(temp) & 0x0f;
dspio_set_bit_pattern((unsigned char)i);
break;
} /* switch i */
} /* while(choice) */
} /* menu_pio() */
|
C
|
#include "holberton.h"
/**
*print_numbers - prints the numbers, from 0 to 9, followed by a new line.
*@: void
*
*Description: prints the numbers, from 0 to 9, followed by a new line.
*section header: Section description
*Return: void
*/
void print_numbers(void)
{
int num;
for (num = '0'; num <= '9'; num++)
{
_putchar(num);
}
_putchar('\n');
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
void error_handling(char* msg)
{
fputs(msg, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char* argv[])
{
int fd1, fd2;
int n;
char buf[1024];
if(argc != 3)
{
error_handling("argument error");
}
fd1 = open(argv[1], O_RDONLY, S_IRWXU);
if(fd1 == -1)
{
error_handling("open() error");
}
fd2 = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
if(fd2 == -1)
{
error_handling("open() error");
}
while((n=read(fd1,buf, sizeof(buf)))>0)
{
if(write(fd2, buf, n) != n)
{
error_handling("write() error");
}
}
if(fd1 != -1)
{
close(fd1);
}
if(fd2 != -1)
{
close(fd2);
}
return 0;
}
|
C
|
#ifndef TREE_H
#define TREE_H
struct node;
struct tree;
typedef
struct node {
int key;
struct node * parent;
struct node * left;
struct node * right;
} Node;
typedef
struct tree {
Node * root;
} Tree;
void init(Tree *);
void makeTree(Tree *, int);
void printTree(Tree);
void preorderTree(Tree);
void inorderTree(Tree);
void postorderTree(Tree);
void clear(Tree * T);
int amountOfLeafs(Tree T);
#endif
|
C
|
#include<stdio.h>
int main()
{
int a[10][10],i,j,r,c=0;
printf("enter the row & column size:");
scanf("%d %d",&r,&c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("element a[%d][%d]=",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(a[i][j]!=0){
c=1;
break;
}
else
{
c=0;
break;
}
}
if(c==0)
printf("null matrix");
else
printf("not a null matrix");
}
|
C
|
// https://iudex.io/problem/5cb71fc5d41a630001c83e0c/statement
// As recentes vitórias da aliança rebelde rompeu com os anos de dominação inconteste do Império, trazendo ainda mais apoio popular aos rebeldes, o que não pode ser tolerado pelo imperador. O alto comando do Império deseja aplicar uma série de reformas em seu exército, o que inclui a reorganização de suas forças especiais para melhor eficácia em operações.
// As forças especiais do Império são compostas por um conjunto de S esquadrões, numerados de 0 a S-1. Oi-esimo esquadrão possui Q[i] membros associados. Cada agente das forças especiais possui um número identificador ID, um tempo de serviço T e um ranking R que corresponde ao seu desempenho em simulações e missões recentes. Para o imperador, interessa a vitória e a minimização de suas perdas, então é necessário que os agentes designados para cada missão sejam os mais adequados em função da sua experiência (tempo de serviço) e ranking, conforme o objetivo de cada esquadrão.
// Cada esquadrão possui, portanto, um critério para classificar/priorizar seus agentes, dentre quatro possíveis, numerados de 0 a 3 e descritos a seguir.
// critério 0: menor tempo de serviço e, em caso de empate, maior ranking
// critério 1: maior tempo de serviço e, em caso de empate, menor ranking
// critério 2: menor ranking e, em caso de empate, maior tempo de serviço
// critério 3: maior ranking e, em caso de empate, menor tempo de serviço
// Em qualquer dos critérios, caso haja empate no tempo de serviço e ranking, a prioridade vai para o menor ID.
// Por exemplo, suponha um esquadrão destinado a missões simples adequadas para o treinamento de soldados jovens e com baixo ranking. Nesse caso, o critério 1 seria o adequado.
// Devido a atual mudança no equilíbrio de poder, o Império está recrutando agentes para suas forças especiais, realizando mais treinos e reavaliando as atribuições de cada esquadrão, podendo haver a qualquer momento a chegada de um novo integrante, mudança de desempenho de um agente ou mudança do critério prioridade para um esquadrão. Cada mudança de prioridade é precedida de trocas de integrantes entre esquadrões diferentes.
// Input:
// A entrada inicia com um inteiro
// S
// representando o número de esquadrões.
// Seguem-se S linhas com o formato:
// Q[i] P[i] ID[0] T[0] R[0] ... ID[Q[i]-1] T[Q[i]-1] R[Q[i]-1]
// onde
// Q[i] é o numero de agentes no esquadrão i
// P[i] é um número de 0 a 3 que indica o critério de prioridade o esquadrão i
// ID[j] T[j] R[j] indicam respectivamente o identificador, o tempo de serviço, e o ranking do j-ésimo agente do esquadrão, para j=0..Q[i]-1
// Logo após, seguem-se varias linhas, numa das formas abaixo.
// ADD i ID T R: Adiciona um novo agente com identificador ID, tempo de serviço T e ranking R ao esquadrão i.
// UPD ID T R: Atualiza o tempo de serviço e/ou ranking do agente com identificador ID para um T e R, respectivamente.
// MOV i j: Move o agente com maior prioridade do esquadrão i para o esquadrão j.
// CHG i j Q P: Move os Q<=size(i) agentes de maior prioridade do esquadrão i para o esquadrão j e, em seguida, atualiza o critério de prioridade do esquadrão i para P.
// KIA ID: Remove o agente com identificador ID do seu respectivo esquadrão.
// A entrada termina com uma linha:
// END
// Output:
// Para cada linha ADD, UPD, CHG, MOV e KIA o programa deverá imprimir as saídas a seguir.
// ADD i ID T R: imprime uma linha
// IDi Ti Ri
// representando o respectivamente o identificador, o tempo de serviço e o ranking do soldado de maior prioridade do esquadrão i após a inserção.
// UPD ID T R ou KIA ID: imprime uma linha
// IDr Tr Rr
// representando o respectivamente o identificador, o tempo de serviço e o ranking do soldado de maior prioridade do esquadrão do agente de identificador ID após a atualização/remoção.
// MOV i j ou CHG i j Q R: imprime uma linha
// IDi Ti Ri IDj Tj Rj
// representando respectivamente o identificador, o tempo de serviço e o ranking do soldado de maior prioridade dos esquadrões i e j após a operação.
// NOTA: Caso um esquadrão não possua mais agentes após um KIA, MOV ou CHG, deve-se imprimir -1 -1 -1 no lugar do identificador, tempo de serviço e ranking do (inexistente) agente de maior prioridade.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct agent{
int id;
int t;
int r;
}agent;
typedef struct position{
int i;
int j;
}position;
int ordem(int criterio, agent new, agent cur){
int result=0;
if(criterio==0){
if(new.t < cur.t)
result=1;
else if(new.t == cur.t){
if(new.r > cur.r)
result=1;
else if(new.r == cur.r){
if(new.id < cur.id)
result=1;
}
}
}
if(criterio==1){
if(new.t > cur.t)
result=1;
else if(new.t == cur.t){
if(new.r < cur.r)
result=1;
else if(new.r == cur.r){
if(new.id < cur.id)
result=1;
}
}
}
if(criterio==2){
if(new.r < cur.r)
result=1;
else if(new.r == cur.r){
if(new.t > cur.t)
result=1;
else if(new.t == cur.t){
if(new.id < cur.id)
result=1;
}
}
}
if(criterio==3){
if(new.r > cur.r)
result=1;
else if(new.r == cur.r){
if(new.t < cur.t)
result=1;
else if(new.t == cur.t){
if(new.id < cur.id)
result=1;
}
}
}
return result;
}
agent *bubbleUp(agent *heap, int criterio, int i, position *pos){
int p, order;
agent aux;
p = (i-1)/2;
order = ordem(criterio, heap[i], heap[p]);
while(i>0 && order==1){
aux = heap[i];
heap[i] = heap[p];
heap[p] = aux;
pos[heap[i].id].j = i;
pos[heap[p].id].j = p;
i = p;
p = (i-1)/2;
order = ordem(criterio, heap[i], heap[p]);
}
return heap;
}
agent *heapInsert(agent *heap, int heapsize, int *arraySize, int criterio, agent aux, position *pos){
int i;
if(*arraySize==heapsize){
heap = (agent *)realloc(heap, *arraySize*2*sizeof(agent));
*arraySize *= 2;
}
i = heapsize;
heap[i].id = aux.id;
heap[i].t = aux.t;
heap[i].r = aux.r;
pos[aux.id].j = i;
heap = bubbleUp(heap, criterio, i, pos);
return heap;
}
void heapify(agent *heap, int i, int heapsize, int criterio, position *pos){
int l=(2*i)+1 , r=(2*i)+2 , m=i, relOrdem;
agent aux;
relOrdem = ordem(criterio, heap[l], heap[m]);
if(l<heapsize && relOrdem==1)
m = l;
relOrdem = ordem(criterio, heap[r], heap[m]);
if(r<heapsize && relOrdem==1)
m = r;
if(m!=i){
aux = heap[i];
heap[i] = heap[m];
heap[m] = aux;
pos[heap[i].id].j = i;
pos[heap[m].id].j = m;
heapify(heap, m, heapsize, criterio, pos);
}
}
void buildHeap(agent *heap, int heapsize, int criterio, position *pos){
int i;
for(i=(heapsize/2)-1; i>=0; i--){
heapify(heap, i, heapsize, criterio, pos);
}
}
agent heapExtract(agent *heap, int i, int heapsize, int criterio, position *pos){
agent r;
r = heap[i];
heap[i] = heap[(heapsize-1)];
heap[(heapsize-1)] = r;
heapsize -= 1;
pos[heap[i].id].j = i;
heapify(heap, i, heapsize, criterio, pos);
return r;
}
int main(){
int stop=0, s, i, j, *p, *q, *arraySize, t, x, y;
agent **agente, storage;
position *agentPos;
char op[5];
scanf("%d", &s);
q = (int *)malloc(s*sizeof(int));
p = (int *)malloc(s*sizeof(int));
arraySize = (int *)malloc(s*sizeof(int));
agente = (agent **)malloc(s*sizeof(agent*));
agentPos = (position *)malloc(1000000*sizeof(position));
for (i=0; i<s; i++){
scanf("%d %d", &q[i], &p[i]);
agente[i] = (agent *)malloc(1000000*sizeof(agent));
arraySize[i] = 1000000;
for(j=0; j<q[i]; j++){
scanf("%d %d %d", &agente[i][j].id, &agente[i][j].t, &agente[i][j].r);
agentPos[agente[i][j].id].i = i;
agentPos[agente[i][j].id].j = j;
}
buildHeap(agente[i], q[i], p[i], agentPos);
}
do{
scanf("%s", op);
if(strcmp("END", op)==0){
stop=1;
}
else{
if(strcmp("ADD", op)==0){
scanf("%d %d %d %d", &i, &storage.id, &storage.t, &storage.r);
agentPos[storage.id].i = i;
agente[i] = heapInsert(agente[i], q[i], &arraySize[i], p[i], storage, agentPos);
q[i] += 1;
printf("%d %d %d\n", agente[i][0].id, agente[i][0].t, agente[i][0].r);
}
if(strcmp("UPD", op)==0){
scanf("%d %d %d", &storage.id, &storage.t, &storage.r);
i = agentPos[storage.id].i;
j = agentPos[storage.id].j;
agente[i][j].t = storage.t;
agente[i][j].r = storage.r;
heapify(agente[i], j, q[i], p[i], agentPos);
agente[i] = bubbleUp(agente[i], p[i], j, agentPos);
printf("%d %d %d\n", agente[i][0].id, agente[i][0].t, agente[i][0].r);
}
if(strcmp("MOV", op)==0){
scanf("%d %d", &i, &j);
storage = heapExtract(agente[i], 0, q[i], p[i], agentPos);
q[i] -= 1;
agentPos[storage.id].i = j;
agente[j] = heapInsert(agente[j], q[j], &arraySize[j], p[j], storage, agentPos);
q[j] += 1;
if(q[i]<=0)
printf("%d %d %d ", -1, -1, -1);
else
printf("%d %d %d ", agente[i][0].id, agente[i][0].t, agente[i][0].r);
if(q[j]<=0)
printf("%d %d %d\n", -1, -1, -1);
else
printf("%d %d %d\n", agente[j][0].id, agente[j][0].t, agente[j][0].r);
}
if(strcmp("CHG", op)==0){
scanf("%d %d %d %d", &i, &j, &x, &y);
for(t=0; t<x; t++){
storage = heapExtract(agente[i], 0, q[i], p[i], agentPos);
q[i] -= 1;
agentPos[storage.id].i = j;
agente[j] = heapInsert(agente[j], q[j], &arraySize[j], p[j], storage, agentPos);
q[j] += 1;
}
if(p[i]!=y){
p[i] = y;
buildHeap(agente[i], q[i], p[i], agentPos);
}
if(q[i]<=0)
printf("%d %d %d ", -1, -1, -1);
else
printf("%d %d %d ", agente[i][0].id, agente[i][0].t, agente[i][0].r);
if(q[j]<=0)
printf("%d %d %d\n", -1, -1, -1);
else
printf("%d %d %d\n", agente[j][0].id, agente[j][0].t, agente[j][0].r);
}
if(strcmp("KIA", op)==0){
scanf("%d", &storage.id);
i = agentPos[storage.id].i;
j = agentPos[storage.id].j;
storage = heapExtract(agente[i], j, q[i], p[i], agentPos);
q[i] -= 1;
agentPos[storage.id].i = j;
agente[i] = bubbleUp(agente[i], p[i], j, agentPos);
if(q[i]<=0)
printf("%d %d %d\n", -1, -1, -1);
else
printf("%d %d %d\n", agente[i][0].id, agente[i][0].t, agente[i][0].r);
}
}
/*for(i=0; i<s; i++){
for(j=0; j<q[i]; j++){
printf("%d %d %d\n", agente[i][j].id, agente[i][j].t, agente[i][j].r);
}
printf("\n");
}*/
}while(stop==0);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main(){
int a = 27;
int arr[5] = {1,2,3,4,5};
int *p;
p = &a;
//printf("This is my pointer location %p and val %d\n", p, *p);
*p = 5;
printf("Val: %d\n", *p);
p = &arr[3];
printf("Val: %lu\n", sizeof(arr)/sizeof(arr[0]));
for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++){
p = &arr[i];
*p = arr[0];
}
for (int i = 0; i < 5; i++){
printf("%d\n", arr[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main (){
float a,b,c,d;
printf("Digite tres valores: ");
scanf("%f %f %f",&a,&b,&c);
d = (a*a)+(b*b)+(c*c);
printf("a soma dos quadrados dos tres valores e %.2f",d);
return 0;
}
|
C
|
#include<stdio.h>
int main(int argn, char* argv[]){
int y[] = {23, 57, 83, 29};
printf("y is %p\n", y);
printf("*y is %d\n", *y);
printf("y[0] is %d\n", y[0]);
printf("&(*y) is %p\n", &(*y));
int* x = &y[2];
printf("x[0] is %d\n",x[0]);
printf("x[-1] is %d\n",x[-1]);
printf("x[-3] is %d\n",x[-3]);
char* arg = (char*)x[-5];
printf("arg is %s", arg);
}
|
C
|
#include "complete.h"
int main(int argv,char * argc[])
{
int size=atoi(argc[1]);
Ls * ls=(Ls *)malloc(size*sizeof(Ls));
FILE * fptr=fopen(argc[1],"r");
int i=0;
while(fscanf(fptr,"%[^ ] %d\n",ls[i].name,&ls[i].empid)!=EOF)
{
i++;
}
fclose(fptr);
Time T=testRun(ls,size);
// printf(" IS= %lf QS= %lf\n",T.IS,T.QS);
int mid=bisection(ls,size);
printf(" mid %d \n",mid);
MixedSort(ls,0,size-1,mid);
// fptr=fopen("output.txt","w");
// for(int i=0;i<size;i++)
// {
// fprintf(fptr,"%s %d\n",ls[i].name,ls[i].empid);
// }
// fclose(fptr); */
}
|
C
|
#include "CoreMutex.h"
#include "CoreVerify.h"
#include <pthread.h>
static int DestroyMutex( void *mtx )
{
pthread_mutex_destroy( mtx );
return DALSYS_Free( mtx );
}
static CoreMutexVtable mutex_vtable = {
(CoreMutexMethodType) pthread_mutex_lock,
(CoreMutexMethodType) pthread_mutex_unlock,
DestroyMutex
};
static pthread_mutexattr_t normal_attr;
static pthread_mutexattr_t recursive_attr;
static unsigned int attr_initialized;
int Core_MutexInit( CoreMutexType *mutex, CoreMutexAttrType attr )
{
int res = -1;
/* Need a test-and-set here. For now though, the fact that the function is
* first called during npa_init, ensures there are no races. */
if ( attr_initialized == FALSE )
{
attr_initialized = TRUE;
pthread_mutexattr_init( &normal_attr );
pthread_mutexattr_settype( &normal_attr, PTHREAD_MUTEX_NORMAL );
pthread_mutexattr_init( &recursive_attr );
pthread_mutexattr_settype( &recursive_attr, PTHREAD_MUTEX_RECURSIVE );
}
CORE_DAL_VERIFY(
DALSYS_Malloc( sizeof(pthread_mutex_t), &mutex->mtx ) );
if ( attr & CORE_MUTEX_RECURSIVE )
{
res = pthread_mutex_init( mutex->mtx, &recursive_attr );
}
else
{
res = pthread_mutex_init( mutex->mtx, &normal_attr );
}
if ( res == 0 )
{
mutex->vtable = &mutex_vtable;
}
else
{
DALSYS_Free( mutex->mtx );
}
return res;
}
|
C
|
#include<stdio.h>
#define MAX 20
int n,adj[MAX][MAX];
int front=-1,rear=-1,queue[MAX];
int main()
{
int i,j=0,k;
int topsort[MAX],indeg[MAX];
create_graph();
printf("Adjacency Matrix is:\n");
display();
for(i=1;i<=n;i++)
{
indeg[i]=indegree(i);
if(indeg[i]==0)
insert_queue(i);
}
while(front<=rear)
{
k=delete_queue();
topsort[j++]=k;
for(i=1;i<=n;i++)
{
if(adj[k][i]==1)
{
adj[k][i]=0;
indeg[i]=indeg[i]-1;
if(indeg[i]==0)
insert_queue(i);
}
}
}
printf("Nodes after Topolgical Sorting are:\n");
for(i=0;i<j;i++)
printf("%d ",topsort[i]);
printf("\n");
}
create_graph()
{
int i,max_edges,origin,destin;
printf("Enter No of Nodes:");
scanf("%d",&n);
max_edges=n*(n-1);
for(i=1;i<=max_edges;i++)
{
printf("Enter Edge %d(0 0 to quit):",i);
scanf("%d %d",&origin,&destin);
if((origin==0)&&(destin==0))
break;
if(origin>n||destin>n||origin<=0||destin<=0)
{
printf("Invalid Edge!\n");
i--;
}
else
adj[origin][destin]=1;
}
}
display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%4d",adj[i][j]);
printf("\n");
}
}
insert_queue(int node)
{
if(rear==MAX-1)
printf("Queue Overflow\n");
else
{
if(front==-1)
front=0;
rear=rear+1;
queue[rear]=node;
}
}
delete_queue()
{
int del_item;
if(front==-1 || front>rear)
{
printf("Queue Underflow\n");
return;
}
else
{
del_item=queue[front];
front=front+1;
return del_item;
}
}
int indegree(int node)
{
int i,in_deg=0;
for(i=1;i<=n;i++)
{
if(adj[i][node]==1)
in_deg++;
}
return in_deg;
}
|
C
|
//
// main.c
// WEEK-2 homework
//
// Created by mac on 16/4/8.
// Copyright © 2016年 mac. All rights reserved.
//
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
//1. 实现交换两个变量的值--值传递
void valueSwap(int a, int b){
int tmp = a;
a = b;
b = tmp;
printf("a:%d b:%d\n",a,b);
}
//2、11. 实现交换两个变量的值--地址传递
void addSwap(int *a, int *b){
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
//3. 去两个数中较大的输出
int maxIn2(int a, int b){
return a>b ? a : b;
}
//4. 取三个数中最大的输出
int maxIn3(int a, int b, int c){
return ((a>b? a:b) > c? (a>b? a:b):c);
}
//5. 取得三个数中最小的数
int minIn3(int a, int b, int c){
return ((a<b ? a:b) < c? (a<b ? a:b):c);
}
//6. 取得两个数中最小的数
int minIn2(int a, int b){
return a<b? a:b;
}
//7. 两个数组的复制
void arrayCpy(int *b, const int *a, int n){
// int m = (int)sizeof(b)/sizeof(int);
// printf("%d\n",m);
//写成上述形式,显示m的值为2,出错。
while (n--) {
*b++ = *a++;
}
}
//8. 将一个指定的值插入到一个已经默认排好序的数组当中
void arrayInsert(int *a, int b, int n){
for (int i=0; i<n; i++) {
if(a[i] <= b) continue;
int tmp = a[i];
a[i] = b;
b = tmp;
}
}
//9. 将一个指定的值从一个已经默认排好序的数组当中删除
void arrayDel(int *a, int d, int n){
int deleted = 0;
for (int i = 0; i<n-1; i++) {
if (a[i] != d && !deleted) {
continue;
}
//开始没加deleted这类标记,导致1 3 5 7 9删除5变成 1 3 7 7, 也就是说后面的(9!=5)直接跳过了
deleted = 1;
a[i] = a[i+1];
}
a[n-1] = 0;
}
//10. 实现对任意输入数的累加
int accumu(int a){
int sum = 0;
while (a>0) {
sum += a--;
}
return sum;
}
/*12. 用指针变量将数组输出
void printArray(int *p, int n){
for (int i=0; i<n; i++) {
printf("%d ",*(p+i));
}
printf("\n");
}
*/
//13. 用指针变量, 将字符数组中的小写字符变为大写字符并输出
void toLower(char *a){
while (*a != 0) {
if (*a >= 'a' && *a <= 'z') *a -= 32;
printf("%c",*a);
a++;
}
printf("\n");
}
//14. 用指针变量, 将字符数组中的大写字符变为小写字符并输出
void toUpper(char *a){
while (*a != 0) {
if (*a >= 'A' && *a <= 'Z') *a += 32;
printf("%c",*a);
a++;
}
printf("\n");
}
//17. 求两行三列的数组元素和
int arraySum(int (*a)[3]){
int sum = 0;
for (int i=0; i<2; i++) {
for (int j= 0; j<3; j++) {
sum += *(*(a+i)+j);
}
}
return sum;
}
int main(int argc, const char * argv[]) {
/*1.有问题 和第二题什么意思, 值传递没办法做到交换啊
static int a, b;
scanf("%d %d", &a, &b);
//printf("befor swap : a: %p, b: %p\n", &a, &b);
valueSwap(a, b);
printf("a: %d, b: %d\n", a, b);
*/
/*2
int a,b;
scanf("%d %d",&a, &b);
addSwap(&a, &b);
printf("a: %d, b:%d\n", a, b);
*/
/*3、6
int a,b;
scanf("%d %d", &a, &b);
printf("%d\n",maxIn2(a,b));
printf("%d\n",minIn2(a,b));
*/
/*4、5
int a,b,c;
scanf("%d %d %d",&a, &b, &c);
printf("%d\n",maxIn3(a,b,c));
printf("%d\n",minIn3(a,b,c));
*/
/*6
int a[5] = {};
int b[5];
//size_t m = sizeof(b);
//printf("%lu----%lu\n", m--, m);
for (int i=0; i<5; i++) {
scanf("%d",&a[i]);
}
arrayCpy(b,a,5);
for (int i=0; i<5; i++) {
printf("%d ",b[i]);
}
printf("\n");
*/
/*8
int n;
printf("你要向几元数组内插入元素:");
scanf("%d",&n);
int a[n+1];
printf("请初始化整形数组的%d个元素:",n);
for (int i=0; i<n; i++) {
scanf("%d",&a[i]);
}
printf("请输入你想插入的元素值:");
int b;
scanf("%d",&b);
arrayInsert(a, b, n+1);
for (int i=0; i<n+1; i++) {
printf("%d ", a[i]);
}
printf("\n");
*/
/*9
printf("你要建立几元的数组:");
int n;
scanf("%d",&n);
printf("请初始化该数组:");
int a[n];
for (int i=0; i<n; i++) {
scanf("%d", &a[i]);
}
printf("删除那个元素:");
int d;
scanf("%d",&d);
arrayDel(a, d, n);
for (int i=0; i<n-1; i++) {
printf("%d ", a[i]);
}
printf("\n");
*/
/*10
int a;
scanf("%d",&a);
printf("%d\n",accumu(a));
*/
/*12
int a[5] = {3, 6, 3, 5, 7};
printArray(a, 5);
*/
/*13
char a[] = "aeDrW";
toLower(a);
*/
/*14
char a[] = "DgWyu";
toUpper(a);
*/
/*15
int a = 5;
int *p = &a;
printf("%d\n",a);
scanf("%d", p);
printf("%d\n",a);
*/
/*16
int a[10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 0};
int *p[10];
for (int i=0; i<10; i++) {
p[i] = &a[i];
}
for (int i=0; i<10; i++) {
printf("%d ", *p[i]);
}
printf("\n");
*/
/*17
int a[2][3] = {{23,43,54},{77,2,9}};
printf("%d\n",arraySum(a));
*/
/*18
char *p[] = {"23","43","54","77","2","9"};
int n = (int)sizeof(p)/sizeof(void *);
for (int i=n-1; i>=0; i--) {
printf("%s\n",p[i]);
}
*/
/*19
char *p[] = {"asdfw","asdwwfr","sdfeqw"};
int n = sizeof(p)/sizeof(void *);
for (int i=0; i<n; i++) {
printf("%s\n",p[i]);
}
*/
/*20
char a[20];
int i=0;
for (; i<20; i++) {
scanf("%c",&a[i]);
//'\n'的ascii码为10
if (a[i] == 10) break;
}
printf("%d\n", i);
*/
/*21
const char a[20] = "arizona state";
char b[20];
strcpy(b, a);
printf("%s\n%s\n",a,b);
*/
/*22
char a[20];
scanf("%s",a);
printf("%s\n",a);
memset(a, 'a', strlen(a)+1);
printf("%s\n",a);
*/
/*23
char a[20], b[20];
scanf("%s",a);
memcpy(b, a, strlen(a)+1);
printf("a: %s\nb: %s\n",a,b);
*/
/*24
char a[] = "sgfgeasdfw";
char b[] = "hhff";
char *p = strstr(a, b);
if (p) printf("yes\n");
else printf("no\n");
*/
/*25
char a[] = "fgjhwase";
char b = 'a';
int i=0;
for (; i<strlen(a); i++) {
if(a[i] == b) break;
}
if ( i == strlen(a)) printf("没有\n");
else printf("%d\n",i+1);
*/
/*26
char a[] = "fgjhwaej";
char b = 'j';
int i=0, count =0;
for (; i<strlen(a); i++) {
if (a[i] == b) {
printf("%d\n",i+1);
count++;
}
}
if (count == 0) printf("没有\n");
*/
/*27
char a[] = "fgjhwaejwaekkae";
char b[] = "ae";
int count = 0;
char *p = strstr(a, b);
while (p) {
count++;
p = strstr(p+1, b);
}
printf("%d\n",count);
*/
/*28
char *a = "asdfwd";
char *b = "wd";
char *c = strstr(a, b);
printf("%ld\n",c-a+1);
*/
/*29
char *a = "fgjhwaejh";
char *b = "jh";
char *c = strstr(a, b);
while (c) {
printf("%ld\n",c-a+1);
c = strstr(c+1, b);
}
*/
/*30
char *a = "sdkfjelkjfsdk";
int count = 0;
while (*a != 0){
count++;
a++;
}
a--;
while (count-- >= 0) {
printf("%c",*a--);
}
printf("\n");
*/
/*31
// char a[] = "hhfhhhhff";
// char *p = a;
// char b[20];
// int mark=0;
// while (*p != 0) {
// char tmp = *p;
// b[mark++] = *p;
// int count = 0;
// while (*p == tmp) {
// count++;
// p++;
// }
// b[mark++] = count+'0';
// }
// b[mark] = 0;
// printf("%s\n",b);
char a[] = "hhfhhhhff";
char *p = a;
char b[20];
char *q = b;
while (*p != 0) {
char tmp = *p;
*q++ = *p;
int count = 0;
while (*p == tmp) {
count++;
p++;
}
*q++ = count+'0';
}
//之前用q输出怎么也不行,因为q已经走远了啊
printf("%s\n",b);
*/
/*32
char a[] = "e5a3f2";
char res[20];
char *p = a, *q = res;
while (*p != 0) {
char tmp = *p++;
int num = (*p++) - '0';
while (num--) {
*q++ = tmp;
}
}
printf("%s\n", res);
*/
/*33
char a[] = "abcd765bbw1357f123";
char *p = a;
int maxCount = 0;
char *mark = NULL;
while (*p != 0) {
if (!isdigit(*p)) {
p++;
continue;
}
char *q = p;
int numCount = 1;
while (isdigit(*p++)) {
if(*p - *(p-1) == 1) {
numCount++;
}else break;
}
if(maxCount < numCount){
maxCount = numCount;
mark = q;
}
}
for (; isdigit(*mark); mark++) {
if(isdigit(*(mark-1)) && *mark - *(mark-1) != 1) break;
printf("%c",*mark);
}
printf("\n");
*/
/*34
char a[] = "f2e1i12g21i3";
char *p = a;
int maxCount = 0;
char *mark = NULL;
while (*p != 0) {
if (!isdigit(*p)) {
p++;
continue;
}
char *q = p;
int numCount = 1;
while (isdigit(*p++)) {
if(*(p-1) - *p == 1) {
numCount++;
}else break;
}
if(maxCount < numCount){
maxCount = numCount;
mark = q;
}
}
for (; isdigit(*mark); mark++) {
if(isdigit(*(mark-1)) && *(mark-1) - *mark != 1) break;
printf("%c",*mark);
}
printf("\n");
*/
/*35
char a[] = "f123fed2wf3210abcd";
char *p = a;
int maxCount = 0;
char *mark = NULL;
while (*p != 0) {
if (!isalpha(*p)) {
p++;
continue;
}
char *q = p;
int numCount = 1;
while (isalpha(*p++)) {
if(*(p-1) - *p == 1) {
numCount++;
}else break;
}
if(maxCount < numCount){
maxCount = numCount;
mark = q;
}
}
for (; isalpha(*mark); mark++) {
if(isalpha(*(mark-1)) && *(mark-1) - *mark != 1) break;
printf("%c",*mark);
}
printf("\n");
*/
/*36
char a[] = "fe1i12ghi21i3";
char *p = a;
int maxCount = 0;
char *mark = NULL;
while (*p != 0) {
if (!isalpha(*p)) {
p++;
continue;
}
char *q = p;
int numCount = 1;
while (isalpha(*p++)) {
if(*p - *(p-1) == 1) {
numCount++;
}else break;
}
if(maxCount < numCount){
maxCount = numCount;
mark = q;
}
}
for (; isalpha(*mark); mark++) {
if(isalpha(*(mark-1)) && *mark - *(mark-1) != 1) break;
printf("%c",*mark);
}
printf("\n");
*/
/* 37 39
char a[50];
char *p = a;
scanf("%s",a);
int count = 0;
while (*p++ != 0) {
if(isupper(*p)) count++;
}
printf("%d\n",count);
*/
/*38
char a[50];
char *p = a;
scanf("%s",a);
int count = 0;
while (*p++ != 0) {
if(islower(*p)) count++;
}
printf("%d\n",count);
*/
/*40 41
char a[50];
char *p = a;
scanf("%s",a);
getchar();
char d;
scanf("%c", &d);
while (*p != 0) {
//p++ 不可以先移动p 因为首位也许就是你想删除的字符呢
if(*p == d){
char *q = p;
//嵌套while因为可能出现772WdfWFDGWH3rd - d 的情况 需要删除两个d
while (*q != 0) {
*q = *(q+1);
q++;
}
//漏掉一种情况,两个要删除的字符是连着的 只能删除一个。 加下面一句就可以了
}
if(*p != d) p++;
}
printf("%s\n",a);
*/
/*42
char a[50];
char *p = a;
scanf("%s",a);
getchar();
char d;
scanf("%c", &d);
d = isupper(d)? d+32:d;
while ((*p != d || *p != d-32) && *p != 0) {
p++;
if(*p == d || *p == d-32){
char *q = p;
while (*q != 0) {
*q = *(q+1);
q++;
}
}
if(*p == d || *p == d-32) p--;
}
printf("%s\n",a);
*/
/*43
char a[50];
scanf("%s",a);
char *p = a;
while (*p != 0) {
if (isdigit(*p)){
char *q = p;
while (*q++ != 0) {
*(q-1) = *q;
}
}
if(!isdigit(*p))p++;
}
printf("%s\n",a);
*/
/*44
char a[50];
scanf("%s",a);
getchar();
char *p = a;
char replacement;
scanf("%c", &replacement);
getchar();
char new;
scanf("%c", &new);
while (*p != 0) {
if (*p == replacement) {
*p = new;
}
if (*p != replacement) p++;
}
printf("%s\n",a);
*/
/*45
char a[50];
scanf("%s",a);
int len = (int)strlen(a);
#if 0
//选择
for (char *p = a; *p != 0; p++) {
for (char *q = p+1; *q != 0; q++) {
if (*p > *q){
char tmp = *p;
*p = *q;
*q = tmp;
}
}
}
#else
//冒泡
for (int i= 0; i<len-1; i++) {
for (int j = 0; j < len-i-1; j++) {
if(a[j] > a[j+1]){
char tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
#endif
printf("%s\n",a);
*/
/*46、47
char a[50];
char b[50];
scanf("%s",a);
getchar();
scanf("%s",b);
getchar();
char *p = a, *q = b, *m = NULL;
char *q_orginal = b;
int count = 0;
//针对a数组的指针有: p,pMark. 因为在for循环内的while循环会使p一直移动,所以每次要循环p时定义一个mark保留当前p的位置以输出或接到上一次循环时到达的位置。
//针对b数组的指针有: q,q_orginal,qMark(在while循环内部进行移动则不需要它)。作用类似。
for (; *p != 0; p++) {
char *pMark = p;
//printf("\np: %c \n",*p);
for (; *q!=0; q++) {
count = 0;
//char *qMark = q;
//printf(" q: %c",*q);
while (*p == *q) {
count++;
p++;
q++;
// printf(" count: %d",count);
}
if (count > 1) break;
//q = qMark;
//p = pMark;
}
if (count > 1){
m = pMark;
break;
}
p = pMark;
q = q_orginal;
}
while (count--) {
printf("%c",*m++);
}
printf("\n");
*/
/*48 & 49
char a[20];
scanf("%s",a);
getchar();
printf("%s\n",a);
char *p = (char *)malloc(20*sizeof(char));
scanf("%s",p);
getchar();
printf("%s\n",p);
*/
/*50
char a[20];
char b[20];
scanf("%s",a);
getchar();
scanf("%s",b);
getchar();
printf("%s\n", strlen(a) > strlen(b) ? a : b);
*/
/*51
char a[40];
char b[20];
scanf("%s",a);
getchar();
scanf("%s",b);
getchar();
printf("%s\n", strcat(a, b));
*/
char a[20], b[20], c[20];
scanf("%s",a);
getchar();
scanf("%s",b);
getchar();
scanf("%s",c);
getchar();
printf("最小: %s\n",strcmp(a,b) > 0 ? (strcmp(b,c)>0? c : b ) : (strcmp(a,c)>0? c : a));
printf("%s\n",strcmp(a, b)>0 ? (strcmp(b, c) > 0 ? b : c) : (strcmp(a, c) ? a : c));
printf("最大: %s\n", strcmp(a, b) > 0 ? (strcmp(a, c)> 0 ? a : c) : (strcmp(b, c) > 0? b:c));
return 0;
}
|
C
|
//---------------------------------------------------
//ļΪRS485ͨŴ
//תоƬMAX485
//˿ڣUART3,TX--B10, RX--B11
// RE--C5, DE--C4
//עRE==0DE == 0ʱ,ݽ;
// RE==1DE == 1ʱ,ݷ
//ĿԲУREDEûӣ
//---------------------------------------------------
#include "sys.h"
#include "rs485.h"
#include "delay.h"
#include "string.h"
//ʱʱ
volatile u16 time_out = 0;
#ifdef EN_USART3_RX //ʹ˽
//ջ
u8 RS485_RX_BUF[64]; //ջ,64ֽ.
//յݳ
u8 RS485_RX_CNT=0;
void USART3_IRQHandler(void)
{
u8 res;
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET) //յ
{
//ʱ
if(time_out > MAX_TIME_OUT) //MAX_TIME_OUT
{
time_out = 0;
RS485_RX_CNT = 0;
memset(RS485_RX_BUF, 0, sizeof(RS485_RX_BUF));
}
res =USART_ReceiveData(USART3); //ȡյ
if(RS485_RX_CNT<64)
{
RS485_RX_BUF[RS485_RX_CNT]=res; //¼յֵ
RS485_RX_CNT++; //1
}
}
}
#endif
//ʼIO 2
//pclk1:PCLK1ʱƵ(Mhz)
//bound:
void RS485_Init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC, ENABLE);//ʹGPIOA,Dʱ
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);//ʹUSART3ʱ
//MAX485/տţB12
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; //PD7˿
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//ʼΪģʽ
TX_RX_EN(0);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //PB10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;//PB11
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //
GPIO_Init(GPIOB, &GPIO_InitStructure);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3,ENABLE);//λ2
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3,DISABLE);//ֹͣλ
#ifdef EN_USART3_RX //ʹ˽
USART_InitStructure.USART_BaudRate = bound;//
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//8λݳ
USART_InitStructure.USART_StopBits = USART_StopBits_1;//һֹͣλ
USART_InitStructure.USART_Parity = USART_Parity_No;///żУλ
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ӳ
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//շģʽ
USART_Init(USART3, &USART_InitStructure); ; //ʼ
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn; //ʹܴ2ж
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; //ռȼ2
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ȼ2
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //ʹⲿжͨ
NVIC_Init(&NVIC_InitStructure); //NVIC_InitStructָIJʼNVICĴ
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);//ж
USART_Cmd(USART3, ENABLE); //ʹܴ
#endif
// RS485_TX_EN=0; //ĬΪģʽ
}
//RS485lenֽ.
//buf:ַ
//len:͵ֽ(Ϊ˺ͱĽƥ,ィ鲻Ҫ64ֽ)
void RS485_Send_Data(u8 *buf,u8 len)
{
u8 t;
TX_RX_EN(1); //Ϊģʽ
for(t=0;t<len;t++) //ѭ
{
while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);
USART_SendData(USART3,buf[t]);
}
while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);
RS485_RX_CNT=0;
TX_RX_EN(0); //Ϊģʽ
}
//RS485ѯյ
//buf:ջַ
//len:ݳ
void RS485_Receive_Data(u8 *buf,u8 *len)
{
u8 rxlen=RS485_RX_CNT;
u8 i=0;
*len=0; //ĬΪ0
delay_ms(10); //ȴ10ms,10msûнյһ,Ϊս
if(rxlen==RS485_RX_CNT&&rxlen)//յ,ҽ
{
for(i=0;i<rxlen;i++)
{
buf[i]=RS485_RX_BUF[i];
}
*len=RS485_RX_CNT; //¼ݳ
RS485_RX_CNT=0; //
}
}
//crc16У
//pBuf--ҪУݣҪУݵֽ
//ֵ--Уֵ
unsigned int Crc16(unsigned char *pBuf, unsigned char num)
{
unsigned char i,j;
unsigned int wCrc = 0xFFFF;
for(i=0; i<num; i++)
{
wCrc ^= (uint16_t)(pBuf[i]);
for(j=0; j<8; j++)
{
if(wCrc & 1)
{
wCrc >>= 1;
wCrc ^= 0xA001;
}
else
{
wCrc >>= 1;
}
}
}
return wCrc;
}
void rs458_send_temp(uint8_t addr, int16_t temp)
{
uint8_t buf[7];
uint16_t crc;
buf[0] = addr;
buf[1] = 0x03;
buf[2] = 0x01;
buf[3] = (temp>>8) & 0xff;
buf[4] = temp & 0xff;
crc = Crc16(buf, 5);
buf[5] = crc & 0xff;
buf[6] = (crc>>8) & 0xff;
RS485_Send_Data(buf, 7);
}
|
C
|
/* Gets the neighbors in a cartesian communicator
* Orginally written by Mary Thomas
* - Updated Mar, 2015
* Link: https://edoras.sdsu.edu/~mthomas/sp17.605/lectures/MPI-Cart-Comms-and-Topos.pdf
* Modifications to fix bugs, include an async send and receive and to revise print output
*/
/* For question 2, parts a b and c are all uploaded in the same file q2abc.c
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
#include <unistd.h>
#include <stdbool.h>
#define SHIFT_ROW 0
#define SHIFT_COL 1
#define DISP 1 // DISP == displacement, ie. DISP = 1 then immediate neighbour right next to current rank
// Function prototype
void WriteToFile(char *pFilename, char *pMessage);
int main(int argc, char *argv[]) {
// ndims=2 is a 2D ...grid?
int ndims=2, size, my_rank, reorder, my_cart_rank, ierr;
int nrows, ncols;
int nbr_i_lo, nbr_i_hi; // nbr = neighbourhood (does he just mean neighbour), i = row, lo = left? hi = right
int nbr_j_lo, nbr_j_hi; // j = column, lo/hi is top/bottom but idk which one
MPI_Comm comm2D;
int dims[ndims],coord[ndims];
int wrap_around[ndims];
int no_iterations = 2; // FOR PART C OF THE LAB.
/* start up initial MPI environment */
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
/* process command line arguments*/
if (argc == 3) {
nrows = atoi (argv[1]); // these are command line arguments
ncols = atoi (argv[2]); // so user can specify dimensions
dims[0] = nrows; /* number of rows */
dims[1] = ncols; /* number of columns */
if( (nrows*ncols) != size) {
if( my_rank ==0) printf("ERROR: nrows*ncols)=%d * %d = %d != %d\n", nrows, ncols, nrows*ncols,size);
MPI_Finalize();
return 0;
}
} else {
nrows=ncols=(int)sqrt(size);
dims[0]=dims[1]=0;
}
/*************************************************************/
/* create cartesian topology for processes */
/*************************************************************/
MPI_Dims_create(size, ndims, dims); // creates a grid with dimensions we've specified
if(my_rank==0)
printf("Root Rank: %d. Comm Size: %d: Grid Dimension = [%d x %d] \n",my_rank,size,dims[0],dims[1]);
/* create cartesian mapping */
wrap_around[0] = 0;
wrap_around[1] = 0; /* periodic shift is .false. not circular. this means the grid is 'flat'
ie. a rank on very top of the grid is NOT neighbours with one on the bottom.
To make it circular, set to 1 (or, True)*/
reorder = 1; /* if false (0), rank of each process in new group is identical to
its rank in the old group. by default we should put 1? */
ierr =0; // what is the point of this line lol
ierr = MPI_Cart_create(MPI_COMM_WORLD, ndims, dims, wrap_around, reorder, &comm2D);
if(ierr != 0) printf("ERROR[%d] creating CART\n",ierr);
/* find my coordinates in the cartesian communicator group */
MPI_Cart_coords(comm2D, my_rank, ndims, coord); // coordinated is returned into the coord array
/* use my cartesian coordinates to find my rank in cartesian group*/
MPI_Cart_rank(comm2D, coord, &my_cart_rank);
/* get my neighbors; axis is coordinate dimension of shift */
/* axis=0 ==> shift along the rows: P[my_row-1]: P[me] : P[my_row+1] */
/* axis=1 ==> shift along the columns P[my_col-1]: P[me] : P[my_col+1] */
// Cart shift 'returns the shifted source and destination ranks, given a shift direction and amount
// vishnu says 'it tells us who our neighbourhood nodes are'
MPI_Cart_shift( comm2D, SHIFT_ROW, DISP, &nbr_i_lo, &nbr_i_hi ); // note to pass in comm2D and NOT MPI_COMM_WORLD
MPI_Cart_shift( comm2D, SHIFT_COL, DISP, &nbr_j_lo, &nbr_j_hi ); // not sure why shift_row is 0 and shift_col is 1
// DISP == displacement, ie. DISP = 1 then immediate neighbour right next to current rank
/* PART C (run part b for a fixed number of iterations)
*/
for(int a = 0; a < no_iterations; a ++) {
/* PART A (generate random prime numbers and share results with immediate neighbouring processes)
*/
MPI_Request send_request[4];
MPI_Request receive_request[4];
MPI_Status send_status[4];
MPI_Status receive_status[4];
sleep(my_rank); // puts a sleep because if they all run at once, they'll generate the same number due to the time(NULL)
unsigned int seed = time(NULL);
bool isPrime = false;
int randomVal;
int k;
while (!isPrime) { // run this loop til it generates a prime number
int i = rand_r(&seed) % 4 + 1;
//printf("Rank: %d, i = %d\n", my_rank, i);
if(i > 1){
int sqrt_i = sqrt(i) + 1;
for (int j = 2; j <=sqrt_i; j ++) {
k = j;
//printf("Rank: %d, k = %d\n", my_rank, k);
if(i%j == 0) {
break;
}
}
if(k >= sqrt_i){
isPrime = true;
randomVal = i;
}
}
}
/* each rank will now send its random generated value to its neighbours */
// vishnu says we should put this into a for loop if we can, but it's okay to just leave it like this
MPI_Isend(&randomVal, 1, MPI_INT, nbr_i_lo, 0, comm2D, &send_request[0]);
MPI_Isend(&randomVal, 1, MPI_INT, nbr_i_hi, 0, comm2D, &send_request[1]);
MPI_Isend(&randomVal, 1, MPI_INT, nbr_j_lo, 0, comm2D, &send_request[2]);
MPI_Isend(&randomVal, 1, MPI_INT, nbr_j_hi, 0, comm2D, &send_request[3]);
/* initialise variables to store numbers a rank will receive from each of its neighbours.
since the grid is not circular, it'll not receive from circular neighbours */
int recvValL = -1, recvValR = -1, recvValT = -1, recvValB = -1;
MPI_Irecv(&recvValT, 1, MPI_INT, nbr_i_lo, 0, comm2D, &receive_request[0]);
MPI_Irecv(&recvValB, 1, MPI_INT, nbr_i_hi, 0, comm2D, &receive_request[1]);
MPI_Irecv(&recvValL, 1, MPI_INT, nbr_j_lo, 0, comm2D, &receive_request[2]);
MPI_Irecv(&recvValR, 1, MPI_INT, nbr_j_hi, 0, comm2D, &receive_request[3]);
MPI_Waitall(4, send_request, send_status);
MPI_Waitall(4, receive_request, receive_status);
printf("Iteration no: %d\n", a);
printf("Global rank: %d. Cart rank: %d. Coord: (%d, %d). Random Val: %d. Recv Top: %d. Recv Bottom: %d. Recv Left: %d. Recv Right: %d.\n", my_rank, my_cart_rank, coord[0], coord[1], randomVal, recvValT, recvValB, recvValL, recvValR);
/* PART B
Now we compare all received numbers with its own. According to the lab specs, "if ALL prime numbers are the same, the process logs this info". Going with this assumption,
a process' generated prime number must match ALL the numbers it receives. Otherwise, it will not log anything, but a text file will still be created. */
char message[200];
char file_name[50];
if((recvValL == randomVal || recvValL == -1) && (recvValR == randomVal || recvValR == -1) && (recvValT == randomVal || recvValT == -1) && (recvValB == randomVal || recvValB == -1)) {
snprintf(message, 200, "All prime numbers received match my generated number, which is %d.\n My rank: %d. Received %d from rank: %d, %d from rank: %d, %d from rank: %d and %d from rank: %d.", randomVal, my_rank, recvValT, nbr_i_lo, recvValB, nbr_i_hi, recvValL, nbr_j_lo, recvValR, nbr_j_hi);
printf("Rank: %d has all matches with its neighbours.\n", my_rank);
}
else{
snprintf(message, 200, "Didn't receive matching prime numbers.\n My rank: %d and number: %d. Received %d from rank: %d, %d from rank: %d, %d from rank: %d and %d from rank: %d.", my_rank, randomVal, recvValT, nbr_i_lo, recvValB, nbr_i_hi, recvValL, nbr_j_lo, recvValR, nbr_j_hi);
}
snprintf(file_name, 50, "iteration_%d_process_%d.txt", a, my_rank);
WriteToFile(file_name, message);
}
MPI_Comm_free( &comm2D );
MPI_Finalize();
return 0;
}
void WriteToFile(char *pFilename, char *pMessage)
{
FILE *pFile = fopen(pFilename, "w");
fprintf(pFile, "%s", pMessage);
fclose(pFile);
}
|
C
|
#include <stdio.h>
#include "2048.h"
int tilt_line_left(int length,int *line)
{
// make sure vector length is sensible
if (length<1||length>255) return -1;
// slide tiles to the left
// combine tiles as required
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
main ()
{
int a,b,c;
printf("masukan bil. 1 :"); scanf("%d",&a);
printf("masukan bil. 2 :"); scanf("%d",&b);
printf("masukan bil. 3 :"); scanf("%d",&c);
if ((a==b) || (a==c))
{
printf("ADA");
}
else if ((b==a) || (b==c))
{
printf("ADA");
}
else if ((c==a) || (c==b))
{
printf("ADA");
}
else
{
printf("Tidak Ada");
}
return 0;
}
|
C
|
// es1-16.c from K&R
// Leonardo Silvagni 2018
// Goal: Revise the program of thelongest input line
#include <stdio.h>
int usr_getline(char line[],int maxline);
void copy(char to[], char from[]);
const int MAXLINE = 1000;
int main(){
int len,max=0;
char line[MAXLINE],longest[MAXLINE];
while((len = usr_getline(line, MAXLINE)) > 0)
if(len > max){
max = len;
copy(longest,line);
};
if (max>0) printf("%s\nLongest line lenght: %d\n",longest,max);
return 0;
}
int usr_getline(char line[], int maxline){
int c,i;
for(i=0;i<maxline-1&&(c=getchar())!=EOF&&c!='\n';++i)
line[i]=c;
if(c=='\n'){
line[i]=c;
++i;};
line[i]='\0';
return i;
}
void copy(char to[], char from[]){
int i=0;
while ((to[i]=from[i]) != '\0') ++i;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define BUFSIZE 1024
char buf[BUFSIZE] = "Hello World!";
/* Main program:
* * - Process arguments.
* * - Open socket and establish connection to server.
* * - Read text line by line and send it over this connection.
* * - Close connection at end of entry (Ctrl-D).
* */
int main(int argc, char *argv[])
{
int s;
struct sockaddr_in addr;
char *p;
int n;
if (argc != 3) {
fprintf(stderr, "Usage: %s <address> <port>\n", argv[0]);
exit(1);
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[2]));
addr.sin_addr.s_addr = inet_addr(argv[1]);
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
perror("connect");
exit(1);
}
while (1) {
printf("%s\n", buf);
n = write(s, buf, strlen(buf));
if (n == -1) {
perror("write");
break;
}
printf("%d\n", n);
}
close(s);
exit(0);
}
|
C
|
//
// Created by ligand on 2019-04-12.
//
/**
* 使用动态链接来替代 标准c库 中的 malloc 和 free
*/
#ifdef RUNTIME
#define _GUN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
static int malloc_size = 0;
void *malloc(size_t size)
{
void *(*mallocp)(size_t size);
char *error;
mallocp = dlsym(RTLD_NEXT, "malloc");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
char *ptr = mallocp(size);
malloc_size += (int)size;
printf("malloc(%d) = %p, total=%d", (int)size, ptr, malloc_size);
return ptr;
}
void free(void *ptr)
{
void (*freep)(void *) = NULL;
char *error;
if (!ptr) return;
freep = dlsym(RTLD_NEXT, "free");
if ((error = dlerror()) != NULL ) {
fputs(error, stderr);
exit(1);
}
freep(ptr);
printf("free(%p), total=%d", ptr, malloc_size);
}
#endif
|
C
|
/*
* 嵥߳
*
* н̬߳(t1t2)
* ȼ߳t1
* ȼ߳t2һʱ̺ѵȼ̡߳
*/
#include <rtthread.h>
#include "tc_comm.h"
/* ָ߳̿ƿָ */
static rt_thread_t tid1 = RT_NULL;
static rt_thread_t tid2 = RT_NULL;
/* ߳1 */
static void thread1_entry(void* parameter)
{
/* ȼ߳1ʼ */
rt_kprintf("thread1 startup%d\n");
/* */
rt_kprintf("suspend thread self\n");
rt_thread_suspend(tid1);
/* ̵ִ߳ */
rt_schedule();
/* ߳1ʱ */
rt_kprintf("thread1 resumed\n");
}
/* ߳2 */
static void thread2_entry(void* parameter)
{
/* ʱ10OS Tick */
rt_thread_delay(10);
/* ߳1 */
rt_thread_resume(tid1);
/* ʱ10OS Tick */
rt_thread_delay(10);
/* ߳2Զ˳ */
}
int rt_application_init(void)
{
/* ߳1 */
tid1 = rt_thread_create("t1",
thread1_entry, /* ߳thread1_entry */
RT_NULL, /* ڲRT_NULL */
THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);
if (tid1 != RT_NULL)
rt_thread_startup(tid1);
/* ߳2 */
tid2 = rt_thread_create("t2",
thread2_entry, /* ߳thread2_entry */
RT_NULL, /* ڲRT_NULL */
THREAD_STACK_SIZE, THREAD_PRIORITY - 1,
THREAD_TIMESLICE);
if (tid2 != RT_NULL)
rt_thread_startup(tid2);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtok.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akerdeka <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/03 14:44:55 by akerdeka #+# #+# */
/* Updated: 2020/07/15 08:07:15 by akerdeka ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include <string.h>
#include "../includes/libft.h"
size_t ft_strspn(char *s1, const char *s2)
{
size_t i;
i = 0;
while (ft_strchr(s2, s1[i]))
i++;
return (i);
}
size_t ft_strcspn(char *s1, const char *s2)
{
size_t i;
i = 0;
while (!ft_strchr(s2, s1[i]))
i++;
return (i);
}
char *ft_strtok(char *s, const char *charset)
{
char *end;
static char *save_str;
if (s == NULL)
s = save_str;
if (*s == '\0')
{
save_str = s;
return (NULL);
}
s += ft_strspn(s, charset);
if (*s == '\0')
{
save_str = s;
return (NULL);
}
end = s + ft_strcspn(s, charset);
if (*end == '\0')
{
save_str = end;
return (s);
}
*end = '\0';
save_str = end + 1;
return (s);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "cardset.h"
#include "cards.h"
#include "board.h"
void setup() {
time_t t;
// Intializes random number generator
srand((unsigned) time(&t));
struct CardSet deck;
startDeck(&deck);
struct Board board;
initializepiles(&board);
printCardSet(&deck);
printf("Shuffling...\n");
shuffleCardSet(&deck);
printf("Shuffled?\n");
printCardSet(&deck);
// printf("\n");
}
int main() {
setup();
}
|
C
|
/* ecc-pattern.c: generate ECC test patterns */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "types.h"
#include "ecc/ecc.h"
uint8_t block[4096];
uint8_t ecc_value[64];
int block_size;
int ecc_size;
int main(int argc, const char* argv[])
{
FILE* fp;
int i;
int index;
block_size = eccBytesPerBlock();
ecc_size = eccNumBytes();
printf("ECC block size = %d ECC value size = %d\n", block_size, ecc_size);
if (block_size > sizeof(block) || ecc_size > sizeof(ecc_value) )
{
fprintf(stderr, "Error max block size = %d and max ecc value size =%d\n", sizeof(block), sizeof(ecc_value));
exit(2);
}
fp = fopen("ecc-pattern.bin", "wb");
if (fp == NULL)
{
fprintf(stderr, "can't open pattern output file");
exit(2);
}
/* start with all zeros */
memset(block, 0, block_size);
fwrite(block, 1, block_size, fp);
/* each bit number in the first byte */
for (i=0; i < 8; i++)
{
block[0] = 1 << i;
fwrite(block, 1, block_size, fp);
}
/* first bit of each byte on a power of 2 */
block[0] = 0;
for (index = 1; index < block_size; index = index << 1)
{
block[index] = 1;
fwrite(block, 1, block_size, fp);
block[index] = 0;
}
}
|
C
|
//*************************************************************
//*
//* Copyright (c) 2016 : wang liang
//* License : Distributed under the GNU General Public License
//* created on : 4/07/2016, by wang liang ([email protected])
//*
//*************************************************************
//swap value of two integers
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
//bubble sort
//@param a :integer array to be sorted
//@param len:length of integer array
void bubble_sort(int a[], int len)
{
for (int i=0; i<len-1; ++i)
{
for (int j=0; j<len-i-1; ++j)
{
if a[j] > a[j+1]
swap(&a[j], &a[j+1]);
}
}
}
//partition for quick sort
int partition(int a[], int low, int high)
{
while (low < high)
{
while (low < high && a[low] <= a[high])
{
--high;
}
swap(&a[low],&a[high]);
while (low < high && a[low] <= a[high])
{
++low;
}
swap(&a[low], &a[high]);
}
return low;
}
//quick sort
//@param int a[] : integer array to be sorted
//@param low : lower index of integer array
//@param high : higher index of integer array
void quick_sort(int a[], int low, int high)
{
if (low < high)
{
int partition_pos = partition(a, low, high);
quick_sort(a, low, partition_pos-1);
quick_sort(a, partition_pos+1,high);
}
}
//mergr operation for merge sort
//@para int src[]: source integer array which must be an order array from small to large
//@para int dst[]: ouput of the sorted array
//@para int begin: begin index of the first part of src[] : src[begin ... mid]
//@para int mid: end index of the first part of src[] : src[begin... mid]
//@para int end : end index of the seconde part of src[]: src[mid+1 ... end]
void merge(int src[], int dst[], int begin, int mid, int end)
{
for (int i=begin, int j = mid+1, int k = begin; i<=mid && j <=end; ++k)
{
if (src[i] <= src[j])
dst[k]=src[i++];
else
det[k]=src[j++];
}
while (i <=mid)
dst[k++] = src[i++];
while (j <=end)
dst[k++] = src[j++];
}
//merge sort
//@para int src[]: source integer array
//@para int dst[]: ouput of the sorted array
//@para int begin: begin index of src[] from where to start the merge sort
//@para int end : end index of src[] end at where to stop the merge sort
void merge_sort(int src[], int dst[], int begin, int end)
{
if (begin < end)
{
int mid =(begin+end)/2;
merge_sort(src,dst,begin,mid);
merge_sort(src,dst,mid+1,end);
merge(src,dst,begin,mid,end);
}
}
//this funcion has a precondition that: other than value at index pos, values after pos all follow the rule of big end heap
//heap adjust: to adjust value at index pos, and make the values start from pos follow the rule of big end heap
//@para int a[]: target integer array
//@para int pos: position where to start the adjust
//@para int length: lengh of array a[]
void heap_adjust(int a[], int pos, int length)
{
int child_exchange = 2*pos+1; // initialize child as default left child
while(pos < length && (2*pos+1)< length) //make sure pos is less than length and has left child
{
if(2*(pos+1)<length && a[2*(pos+1)]>2*pos+1)
++child_exchange; //if pos right child exists and is bigger than left child, then right child will be the node need to exchange with pos
if(a[child_exchange] > a[pos])
{
swap(&a[child_exchange],&a[pos]);
pos = child_exchange; // child_exchange will be the next node need to adjust
}
else
break;
}
}
//build heap
void build_heap(int a[], int length)
{
for(int i= (length-1)/2; i >=0; --i) //initialize i as the first node that is not a leaf node, then --i until 0
{
heap_adjust(a, i, int length)
}
}
//heap sort
void heap_sort(int a[], int length)
{
for (int i = length ; i >1; --i) // call
{
build_heap(a, i);
swap(&a[0],&a[i-1]); // swap the value a[0](biggest) and value at end of heap a[i-1] generated in this loop, then a[i-1] will be the biggest value during this loop
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** PSU_42sh_2018
** File description:
** unsetenv.c manage the function unsetenv
*/
#include <stddef.h>
#include "my.h"
#include "env.h"
char **remove_line(char **envp, int arg)
{
int j = 0;
int i = 0;
for (; envp[i] != NULL; i++) {
if (j == arg)
j++;
envp[i] = envp[j];
j++;
}
envp[i] = NULL;
return (envp);
}
char **search_env(char **envp, char **new_line, int arg)
{
int i = 0;
char **actual_line = NULL;
actual_line = my_strtwa(envp[i], '=');
while (envp[i] != NULL &&
(my_strcmp(actual_line[0], new_line[arg]) != 1)) {
actual_line = my_free_array(actual_line);
i++;
actual_line = my_strtwa(envp[i], '=');
if (envp[i] == NULL)
actual_line = NULL;
}
if (envp[i] != NULL && (my_strcmp(actual_line[0], new_line[arg]) == 1))
envp = remove_line(envp, i);
return (envp);
}
int my_unsetenv(minishell_t *msh, char **new_line)
{
int arg = 1;
if (new_line[1] == NULL) {
my_putstr("unsetenv: Too few arguments.\n");
return (1);
}
while (new_line[arg] != NULL) {
msh->env = search_env(msh->env, new_line, arg);
arg++;
}
return (0);
}
|
C
|
#ifndef MD5A_H_SENTRY
#define MD5A_H_SENTRY
/*
* MD5.h
*
*/
#ifdef __cplusplus
extern "C"
{
#endif
typedef struct __MD5_hash_value
{
unsigned char v [16];
} MD5_hash_value;
void HashBuffer_MD5 (const unsigned char *string, unsigned len, MD5_hash_value *hash);
/* UINT4 defines a four byte word */
typedef unsigned int UINT4;
/* MD5 context. */
typedef struct {
UINT4 state[4]; /* state (ABCD) */
UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} MD5_CTX;
extern void MD5Init(MD5_CTX *context);
extern void MD5Update(MD5_CTX *context, const unsigned char *input,
unsigned int inputLen);
extern void MD5Final(unsigned char digest[16], MD5_CTX *context);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<netinet/in.h>
#include<unistd.h>
#include<ctype.h>
struct packet
{
char desti_ip[100];
char source_ip[100];
char source_mac[100];
char data[17];
};
int ip_validity(char ip[100])
{
int i=0;
char token[4];
int k=0,dot=0;
int j=0;
int flag=1;
int num;
while(ip[i]!='\0')
{
if(ip[i]=='.' || ip[i+1]=='\0')
{
if (ip[i+1]=='\0')
{
token[k]=ip[i];
k++;
i++;
dot--;
}
if (k>3)
{
flag=0;
break;
}
k=0;
dot++;
if (dot == 4)
{
flag=0;
break;
}
// Checking for the characters other than number...
for(j=0;j<strlen(token);j++)
{
if (isdigit(token[j])==0)
{
flag=0;
}
}
if (flag==0)
break;
// Checking whether it is in the range...
num = atoi(token);
if (num < 0 || num > 255)
{
flag=0;
break;
}
bzero(&token,sizeof(token));
}
else
{
token[k]=ip[i];
k++;
}
i++;
}
return flag;
}
int mac_validity(char mac[100])
{
int i=0;
int flag=1;
int count=0;
char conv[100];
if (strlen(mac) != 17)
return 0;
strcpy(conv,"0");
strcat(conv,mac);
i++;
while(conv[i]!='\0')
{
if(i%3==0 && conv[i]!='-')
{flag=0;break;}
if(i%3 !=0 && isxdigit(conv[i])==0)
{flag=0;break;}
i++;
}
return flag;
}
char *getMac(char *buffer)
{
int i=0,j=0;
int count = 0;
char *mac;
mac = (char*)malloc(sizeof(char)*100);
while(buffer[i] != '\0')
{
if(buffer[i] == '|')
count++;
if (count == 3)
{
mac[j]=buffer[i];
j++;
}
i++;
}
return mac;
}
int verify(char *buffer)
{
int i=0,j=0;
int count = 0,k=0;
char ip[100];
char mac[100];
while(buffer[i] != '\0')
{
if(buffer[i] == '|')
{count++;i++;continue;}
if (count == 2)
{
ip[k]=buffer[i];
k++;
}
if (count == 3)
{
mac[j]=buffer[i];
j++;
}
i++;
}
mac[17]='\0';
int a,b;
a=ip_validity(ip);
b=mac_validity(mac);
if (a && b)
{
return 1;
}
else
{
if (a==0)
printf("\nClient IP address is invalid\n");
if (b==0)
printf("\nClient MAC address is invalid\n");
return 0;
}
}
struct packet test()
{
printf("\nEnter the details of packet received\n");
struct packet p;
printf("\nDestination IP :Automatically generated for testing\n");
//scanf("%s",p.desti_ip);
strcpy(p.desti_ip,"155.157.65.128");
printf("\nSource IP :Automatically generated for testing\n");
//scanf("%s",p.source_ip);
strcpy(p.source_ip,"123.128.34.56");
printf("\nSource MAC :Automatically generated for testing\n");
//scanf("%s",p.source_mac);
strcpy(p.source_mac,"AF-45-E5-00-97-12");
printf("\n16-bit data :Automatically generated for testing\n");
strcpy(p.data,"1011110000101010");
return p;
}
char* packet_generation(struct packet p)
{
printf("\nDeveloping ARP Request packet\n");
char *pack;
pack = (char*)malloc(sizeof(char)*1000);
sprintf(pack,"%s|%s|%s",p.source_ip,p.source_mac,p.desti_ip);
printf("\n\t%s\n",pack);
return pack;
}
#define PORT 7228
int main(int argc ,int **argv)
{
int sockfd,ret,len,n;
struct sockaddr_in serverAddr;
int newfd;
struct sockaddr_in clientAddr;
char buffer[1024];
char str[1000];
// pid_t child;
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0)
{
printf("----------Error in Connection.\n");
exit(1);
}
bzero(&serverAddr,sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(PORT);
struct packet p;
p = test();
strcpy(buffer,packet_generation(p));
ret = bind(sockfd,(struct sockaddr*)&serverAddr,sizeof(serverAddr));
if(ret < 0)
{
printf("----------Error in Binding.\n");
exit(1);
}
listen(sockfd,10);
len = sizeof(clientAddr);
printf("\nThe ARP Request Packet is broadcasted\nWaiting for ARP Reply..\n");
while(1)
{
newfd = accept(sockfd,(struct sockaddr*)&clientAddr,&len);
//broadcasting message whoever connecting to server..
send(newfd,buffer,sizeof(buffer),0);
n=recv(newfd,buffer,sizeof(buffer),0);
if(n>0)
{
printf("\nARP Reply received\n\n%s\n",buffer);
if (verify(buffer))
{
strcat(buffer,"|");
strcat(buffer,p.data);
strcpy(str,getMac(buffer));
printf("Sending the packet to :%s",str);
send(newfd,buffer,sizeof(buffer),0);
printf("\nPacket Sent :\n%s\n",buffer);
break;
}
else
{
printf("\nProcess Terminated\n");
break;
}}
}
close(sockfd);
close(newfd);
return 0;
}
|
C
|
#include <linux/limits.h>
#include "LineParser.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#define TERMINATED -1
#define RUNNING 1
#define SUSPENDED 0
//declares
typedef struct process process;
void execute(cmdLine *pCmdLine);
void addProcess(process** process_list, cmdLine* cmd, pid_t pid);
void printProcessList(process** process_list);
void printProcessLink(process* process_link, int index);
void freeProcessList(process* process_list);
void updateProcessList(process **process_list);
void updateProcessStatus(process* process_list, int pid, int status);
//type define
typedef struct process{
cmdLine* cmd; /* the parsed command line*/
pid_t pid; /* the process id that is running the command*/
int status; /* status of the process: RUNNING/SUSPENDED/TERMINATED */
struct process *next; /* next process in chain */
} process;
//globals
int flagD = 0;
int main(int argc, char **argv){
char cwd[PATH_MAX];
char buf [2048];
pid_t pid;
process** process_list = malloc(sizeof(process));
process_list[0] = NULL;
if(argc > 1 && strncmp(argv[1],"-D",2) == 0)
flagD = 1;
while(1) {
getcwd(cwd, PATH_MAX);
printf("Current working dir: %s\n", cwd); // current directory
fgets(buf, 2048, stdin); //get a command line
if(feof(stdin))
break;
cmdLine *pCmdLine = parseCmdLines(buf);
if ( strcmp(pCmdLine->arguments[0], "quit" ) == 0){
freeCmdLines(pCmdLine);
freeProcessList(process_list[0]);
free(process_list[0]);
free(process_list);
exit(0);
}
else if ( strcmp(pCmdLine->arguments[0],"cd") == 0 ){
if(chdir(pCmdLine->arguments[1]) == -1 )
fprintf(stderr, "error cd\n");
freeCmdLines(pCmdLine);
}
else if ( strcmp(pCmdLine->arguments[0],"procs") == 0 ){
printProcessList(process_list);
freeCmdLines(pCmdLine);
}
else if ( strcmp(pCmdLine->arguments[0],"suspend") == 0 ){
if( kill(atoi(pCmdLine->arguments[1]), SIGTSTP) == 0)
updateProcessList(process_list);
freeCmdLines(pCmdLine);
}
else if ( strcmp(pCmdLine->arguments[0],"kill") == 0 ){
if( kill(atoi(pCmdLine->arguments[1]), SIGINT) == 0)
updateProcessList(process_list);
freeCmdLines(pCmdLine);
}
else if ( strcmp(pCmdLine->arguments[0],"wake") == 0 ){
if( kill(atoi(pCmdLine->arguments[1]), SIGCONT) == 0)
updateProcessList(process_list);
freeCmdLines(pCmdLine);
}
else {
if ( !(pid = fork()) ){
if(flagD){
fprintf(stderr, "PID: %d Executing command: %s\n", getpid(), pCmdLine->arguments[0]);
}
execute(pCmdLine);
}
if( pCmdLine->blocking ){
waitpid(pid, NULL, 0);
}
addProcess(process_list, pCmdLine, pid);
}
}
return 0;
}
void execute(cmdLine *pCmdLine){
execvp(pCmdLine->arguments[0], pCmdLine->arguments);
_exit(1);
}
void addProcess(process** process_list, cmdLine* cmd, pid_t pid){
int i = 0;
process *tmp;
process *link = (process*)malloc(sizeof(process));
link->cmd = cmd;
link->pid = pid;
link->status = RUNNING;
link->next = NULL;
if(process_list[0] == NULL){
process_list[0] = link;
}
else{
tmp = process_list[0];
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = link;
}
}
void printProcessList(process** process_list){
process *tmp, *prev, *after;
int i = 0;
if(process_list != NULL && process_list[0] != NULL){
updateProcessList(process_list);
tmp = process_list[0];
prev = tmp;
after = tmp->next;
printf("index\tPID\tSTATUS\tCommand\n");
while ( tmp != NULL ){
printf("%d\t%d\t%d\t%s\n", i, tmp->pid, tmp->status, *(tmp->cmd->arguments));
if(tmp->status != -1){
prev = tmp;
tmp = tmp->next;
if(after != NULL)
after = after->next;
}
else { // tmp->status == -1
if(prev->pid != tmp->pid){
prev->next = after;
freeCmdLines(tmp->cmd);
free(tmp);
tmp = after;
if(after != NULL)
after = after->next;
}
else {
freeCmdLines(tmp->cmd);
free(tmp);
tmp = after;
prev = tmp;
if(after != NULL)
after = after->next;
process_list[0] = tmp;
}
}
i++;
}
}
}
void freeProcessList(process* process_list){
if(process_list!=NULL){
if(process_list->cmd != NULL)
freeCmdLines(process_list->cmd);
if(process_list->next != NULL){
freeProcessList(process_list->next);
free(process_list->next);
}
}
}
void updateProcessList(process **process_list){
pid_t w;
int status = 0, update;
process *tmp = process_list[0];
while (tmp != NULL) {
update = tmp->status;
w = waitpid(tmp->pid, &status, WNOHANG|WUNTRACED|WCONTINUED);
if (w == -1)
update = TERMINATED;
if(w != 0){
if (WIFEXITED(status)) {
update = TERMINATED;
}
else if(WIFSIGNALED(status)){
update = TERMINATED;
}
else if(WIFSTOPPED(status))
update = SUSPENDED;
else if(WIFCONTINUED(status))
update = RUNNING;
}
updateProcessStatus(tmp, tmp->pid, update);
tmp = tmp->next;
}
}
void updateProcessStatus(process* process_list, int pid, int status){
process_list->status = status;
}
|
C
|
#include "libFireBird.h"
bool HDD_Write(void *data, dword length, TYPE_File *f)
{
TRACEENTER();
static byte block[512];
static byte *b = block;
bool success = TRUE;
dword blen;
// flush buffer
if(length == 0)
{
if(b > block)
{
success = (TAP_Hdd_Fwrite(block, sizeof(block), 1, f) == 1);
b = block;
}
}
// can't buffer data
else if(length > sizeof(block)) success = (TAP_Hdd_Fwrite(data, length, 1, f) == 1);
else
{
blen = sizeof(block) - (b - block);
// not enough space in buffer
if(length > blen)
{
// fill rest of buffer
memcpy(b, data, blen);
success = (TAP_Hdd_Fwrite(block, sizeof(block), 1, f) == 1);
//(byte *) data += blen;
data = (byte*)data + blen;
length -= blen;
b = block;
}
// new buffer
if(b == block) memset(block, 0, sizeof(block));
// enough space in buffer
memcpy(b, data, length);
b += length;
}
TRACEEXIT();
return success;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int c[10][10],n,vis[10];
void bfs(int src)
{
int i,j,f=0,r=0,q[10];
for(i=1;i<=n;i++)
vis[i]=0;
q[++r]=src;
++f;
while(f<=r)
{
i=q[f++];
for(j=1;j<=n;j++)
{
if(c[i][j]==1 && vis[j]==0)
{
q[++r]=j;
vis[j]=1;
}
}
}
}
void main()
{
int i,src,j;
printf("Enter the number of nodes\n");
scanf("%d",&n);
printf("Enter the cost matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&c[i][j]);
}
}
printf("enter the source\n");
scanf("%d",&src);
bfs(src);
for(i=1;i<=n;i++)
{
if(i!=src)
{
if(vis[i]==1)
printf("%d is reachable from source\n",i);
else
printf("%d is not reachable from source\n",i);
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef void (*funptr)(int);
funptr myfun(int x)
{
int p=x;
void fun(int y)
{
printf("old p:%d\n",p);
p=p+y;
printf("new p:%d\n",p);
printf("\n\n");
}
return fun;
}
int main(int argc, char const *argv[])
{
funptr myptr=myfun(-5);
myptr(8);
funptr myptr1=myfun(100);
myptr(3);
myptr(8);
return 0;
}
|
C
|
#ifndef STACK_H_
# define STACK_H_
# include "list.h"
typedef struct stack
{
/* Properties */
struct list list;
/* Methods */
/* --- Modifiers --- */
void (*push)(struct stack *self, void *data);
void (*pop)(struct stack *self);
void (*clear)(struct stack *self);
/* --- Element access --- */
void * (*top)(struct stack *self);
/* --- Capacity --- */
unsigned int (*size)(struct stack *self);
unsigned int (*empty)(struct stack *self);
/* --- Debug --- */
void (*show)(struct stack *self, void(*display)(unsigned int n, void *data));
} stack;
struct stack * new_stack(void);
void stack_init(struct stack *self);
void stack_destroy(struct stack *self);
#endif /* STACK_H_ */
|
C
|
#include<stdio.h>
#include<conio.h>
void tellsav(void);
void tellcur(void);
void layout(int x1,int y1,int x2,int y2,int ccb,int cct);
void main()
{
char options[10][40]={
"SAVINGS ACCOUNT",
"CURRENT ACCOUNT",
" ",
" ",
" "
};
int key=0,y=7,opt=0;
layout(25,5,55,22,15,15);
gotoxy(26,7);
cprintf("%s",options[0]);
gotoxy(26,8);
cprintf("%s",options[1]);
gotoxy(26,9);
cprintf("%s",options[2]);
gotoxy(26,10);
cprintf("%s",options[3]);
gotoxy(26,11);
cprintf("%s",options[4]);
gotoxy(26,y);
textbackground(7);
cprintf("%s",options[opt]);
gotoxy(65,22);
textcolor(8);
textbackground(RED);
cprintf(" EXIT ");
textcolor(15);
while(1)
{
key=getch();
if(key==13)
{
if(opt==0)
{
tellsav();
}
if(opt==1)
{
tellcur();
}
}
if(key==72)
{
gotoxy(26,y);
textbackground(BLACK);
cprintf("%s",options[opt]);
opt--;
y--;
if(opt<0)
{
opt=1;
y=8;
}
}
if(key==80)
{
gotoxy(26,y);
textbackground(BLACK);
cprintf("%s",options[opt]);
opt++;
y++;
if(opt>1)
{
opt=0;
y=7;
}
}
if(key==9)
{
gotoxy(26,y);
textbackground(BLACK);
cprintf("%s",options[opt]);
gotoxy(65,22);
textbackground(7);
cprintf(" EXIT ");
key=getch();
gotoxy(65,22);
textbackground(RED);
cprintf(" EXIT ");
if(key==13)
return(0);
}
gotoxy(26,y);
textbackground(7);
cprintf("%s",options[opt]);
}
}
void layout(int x1,int y1,int x2,int y2,int ccb,int cct)
{
int i,j;
window(x1,y1,x2,y2);
textmode(3);
textcolor(cct);
gotoxy(x1,y1);
cprintf("%c",218);
gotoxy(x1,y2);
cprintf("%c",192);
gotoxy(x2,y1);
cprintf("%c",191);
gotoxy(x2,y2);
cprintf("%c",217);
for(i=x1+1;i<x2;i++)
{
gotoxy(i,y1);
cprintf("%c",196);
}
for(i=x1+1;i<x2;i++)
{
gotoxy(i,y2);
cprintf("%c",196);
}
for(i=y1+1;i<y2;i++)
{
gotoxy(x1,i);
cprintf("%c",179);
gotoxy(x2,i);
cprintf("%c",179);
}
}
void tellsav(void)
{
int i,j;
layout(3,4,77,24,15,15);
for(i=4;i<77;i++)
for(j=5;j<24;j++)
{
gotoxy(i,j);
cprintf(" ");
}
layout(5,5,40,7,15,15);
gotoxy(6,6);
cprintf("SAVINGS ACCOUNT NO: ");
getchar();
}
void tellcur(void)
{
int i,j;
layout(3,4,77,24,15,15);
for(i=4;i<77;i++)
for(j=5;j<24;j++)
{
gotoxy(i,j);
cprintf(" ");
}
layout(5,5,40,7,15,15);
gotoxy(6,6);
cprintf("CURRENT ACCOUNT NO: ");
getchar();
}
|
C
|
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "ZCurveLUT.h"
#include "../../constants.h"
ZCurveLUT *generateZCurveLUT(int size)
{
ZCurveLUT *result = (ZCurveLUT *)malloc(sizeof(ZCurveLUT));
result->data = (BLOCK_TYPE **)malloc(NO_DIM * sizeof(BLOCK_TYPE *));
double logSize = log2(size);
int bitSize = (int)(log2(size));
if (fmod(logSize, 1.0) != 0.0)
{
bitSize++;
}
for (int i = 0; i < NO_DIM; i++)
{
result->data[i] = (BLOCK_TYPE *)calloc(size, sizeof(BLOCK_TYPE));
int currentInc = 1 << i;
for (int j = 0; j < size; j++)
{
int temp = j;
for (int k = bitSize - 1; k >= 0; k--)
{
result->data[i][j] = result->data[i][j] << NO_DIM;
if (temp >> k == 1)
{
result->data[i][j] += currentInc;
temp -= temp >> k << k;
}
}
}
}
return result;
}
void printZCurveLUT(ZCurveLUT *LUT, int size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
for (int k = 0; k < size; k++)
{
printf("%i %i %i: %i \n", i, j, k, getZCurveKey(LUT, 3, i, j, k));
}
}
}
}
BLOCK_TYPE getZCurveKey(ZCurveLUT *LUT, int argc, ...)
{
BLOCK_TYPE result = 0;
va_list list;
va_start(list, argc);
for(int i = 0; i < argc; i++)
{
int j = va_arg(list, int);
result += LUT->data[i][j];
}
va_end(list);
return result;
}
void removeZCurve(ZCurveLUT *LUT)
{
for(int i = 0; i < NO_DIM; i++)
{
free(LUT->data[i]);
}
free(LUT->data);
free(LUT);
}
|
C
|
/*
** orient.c: Code to convert a from/at/up cmaera model to the orientation
** model used by VRML.
** Copyright (C) 1995 Stephen Chenney ([email protected])
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
** Written by Stephen Chenney, October 1995.
** [email protected]
*/
/*
** As is this program prompts for a from vector, an at vector and an up
** vector, then calculates the orientation required to align the default
** VRML camera with the given camera.
**
** As a standalone program it does fine.
** You are welcome to incorporate it into any other program you write, and
** to modify it as required. However, it would be good if you left it all
** in one file, and left the GNU header at the top. You probably shouldn't
** sell it either.
*/
#include <stdio.h>
#include <math.h>
/* Define a vector. */
typedef struct _Vector
{
double x;
double y;
double z;
} Vector, *VectorPtr;
/* Takes the modulus of v */
#define VMod(v) (sqrt((v).x*(v).x + (v).y*(v).y + (v).z*(v).z))
/* Returns the dot product of v1 & v2 */
#define VDot(v1, v2) ((v1).x*(v2).x + (v1).y*(v2).y + (v1).z*(v2).z)
/* Fills the fields of a vector. */
#define VNew(a, b, c, r) ((r).x = (a), (r).y = (b), (r).z = (c))
#define VAdd(v1, v2, r) ((r).x = (v1).x + (v2).x , \
(r).y = (v1).y + (v2).y , \
(r).z = (v1).z + (v2).z )
#define VSub(v1, v2, r) ((r).x = (v1).x - (v2).x , \
(r).y = (v1).y - (v2).y , \
(r).z = (v1).z - (v2).z )
#define VCross(v1, v2, r) ((r).x = (v1).y * (v2).z - (v1).z * (v2).y , \
(r).y = (v1).z * (v2).x - (v1).x * (v2).z , \
(r).z = (v1).x * (v2).y - (v1).y * (v2).x )
#define VScalarMul(v, d, r) ((r).x = (v).x * (d) , \
(r).y = (v).y * (d) , \
(r).z = (v).z * (d) )
#define VUnit(v, t, r) ((t) = 1 / VMod(v) , \
VScalarMul(v, t, r) )
typedef struct _Quaternion {
Vector vect_part;
double real_part;
} Quaternion;
Quaternion
Build_Rotate_Quaternion(Vector axis, double cos_angle)
{
Quaternion quat;
double sin_half_angle;
double cos_half_angle;
double angle;
/* The quaternion requires half angles. */
if ( cos_angle > 1.0 ) cos_angle = 1.0;
if ( cos_angle < -1.0 ) cos_angle = -1.0;
angle = acos(cos_angle);
sin_half_angle = sin(angle / 2);
cos_half_angle = cos(angle / 2);
VScalarMul(axis, sin_half_angle, quat.vect_part);
quat.real_part = cos_half_angle;
return quat;
}
static Quaternion
QQMul(Quaternion *q1, Quaternion *q2)
{
Quaternion res;
Vector temp_v;
res.real_part = q1->real_part * q2->real_part -
VDot(q1->vect_part, q2->vect_part);
VCross(q1->vect_part, q2->vect_part, res.vect_part);
VScalarMul(q1->vect_part, q2->real_part, temp_v);
VAdd(temp_v, res.vect_part, res.vect_part);
VScalarMul(q2->vect_part, q1->real_part, temp_v);
VAdd(temp_v, res.vect_part, res.vect_part);
return res;
}
static void
Quaternion_To_Axis_Angle(Quaternion *q, Vector *axis, double *angle)
{
double half_angle;
double sin_half_angle;
half_angle = acos(q->real_part);
sin_half_angle = sin(half_angle);
*angle = half_angle * 2;
if ( sin_half_angle < 1e-8 && sin_half_angle > -1e-8 )
VNew(0, 0, 0, *axis);
else
{
sin_half_angle = 1 / sin_half_angle;
VScalarMul(q->vect_part, sin_half_angle, *axis);
}
}
void
Convert_Camera_Model(Vector *pos, Vector *at, Vector *up, Vector *res_axis,
double *res_angle)
{
Vector n, v;
Quaternion rot_quat;
Vector norm_axis;
Quaternion norm_quat;
Quaternion inv_norm_quat;
Quaternion y_quat, new_y_quat, rot_y_quat;
Vector new_y;
double temp_d;
Vector temp_v;
/* n = (norm)(pos - at) */
VSub(*at, *pos, n);
VUnit(n, temp_d, n);
/* v = (norm)(view_up - (view_up.n)n) */
VUnit(*up, temp_d, *up);
temp_d = VDot(*up, n);
VScalarMul(n, temp_d, temp_v);
VSub(*up, temp_v, v);
VUnit(v, temp_d, v);
VNew(n.y, -n.x, 0, norm_axis);
if ( VDot(norm_axis, norm_axis) < 1e-8 )
{
/* Already aligned, or maybe inverted. */
if ( n.z > 0.0 )
{
norm_quat.real_part = 0.0;
VNew(0, 1, 0, norm_quat.vect_part);
}
else
{
norm_quat.real_part = 1.0;
VNew(0, 0, 0, norm_quat.vect_part);
}
}
else
{
VUnit(norm_axis, temp_d, norm_axis);
norm_quat = Build_Rotate_Quaternion(norm_axis, -n.z);
}
/* norm_quat now holds the rotation needed to line up the view directions.
** We need to find the rotation to align the up vectors also.
*/
/* Need to rotate the world y vector to see where it ends up. */
/* Find the inverse rotation. */
inv_norm_quat.real_part = norm_quat.real_part;
VScalarMul(norm_quat.vect_part, -1, inv_norm_quat.vect_part);
/* Rotate the y. */
y_quat.real_part = 0.0;
VNew(0, 1, 0, y_quat.vect_part);
new_y_quat = QQMul(&norm_quat, &y_quat);
new_y_quat = QQMul(&new_y_quat, &inv_norm_quat);
new_y = new_y_quat.vect_part;
/* Now need to find out how much to rotate about n to line up y. */
VNew(0, 0, 1, temp_v);
rot_y_quat = Build_Rotate_Quaternion(temp_v, VDot(new_y, v));
/* rot_y_quat holds the rotation about the initial camera direction needed
** to align the up vectors in the final position.
*/
/* Put the 2 rotations together. */
rot_quat = QQMul(&norm_quat, &rot_y_quat);
/* Extract the axis and angle from the quaternion. */
Quaternion_To_Axis_Angle(&rot_quat, res_axis, res_angle);
}
#ifdef TEST
void
main()
{
Vector pos, at, up;
Vector rot_axis;
double rot_angle;
/* printf("Enter camera location: "); */
scanf("%lg %lg %lg", &(pos.x), &(pos.y), &(pos.z));
/* printf("Enter look at point: "); */
scanf("%lg %lg %lg", &(at.x), &(at.y), &(at.z));
/* printf("Enter look up vector: "); */
scanf("%lg %lg %lg", &(up.x), &(up.y), &(up.z));
Convert_Camera_Model(&pos, &at, &up, &rot_axis, &rot_angle);
/* Print it out. */
printf("orientation %1.5g %1.5g %1.5g %1.5g\n",
rot_axis.x, rot_axis.y, rot_axis.z, rot_angle);
}
#endif
|
C
|
typedef struct Parser {
String fullpath;
Tokenizer tokenizer;
Token curr_token;
Token prev_token;
// >= 0: In Expression
// < 0: In Control Clause
// NOTE(bill): Used to prevent type literals in control clauses
isize expr_level;
bool allow_type;
} Parser;
typedef enum ParserError {
ParserError_None,
ParserError_Empty,
ParserError_Invalid,
ParserError_NotExists,
ParserError_COUNT
} ParserError;
typedef struct AstPackage {
String fullpath;
AstDecl **decls;
isize decl_count;
} AstPackage;
Token next_token(Parser *p) {
p->prev_token = p->curr_token;
p->curr_token = scan_token(&p->tokenizer);
return p->prev_token;
}
Token expect_token(Parser *p, TokenKind kind) {
Token curr = p->curr_token;
if (curr.kind != kind) {
String c = token_strings[kind];
String p = token_strings[curr.kind];
error(curr.pos, "expected %.*s, got %.*s", LIT(c), LIT(p));
if (curr.kind == Token_EOF) {
exit(1);
}
}
next_token(p);
return curr;
}
Token expect_operator(Parser *p) {
Token curr = p->curr_token;
switch (curr.kind) {
case Token_in:
case Token_not:
case Token_and:
case Token_or:
// ok
break;
default:
if (!(Token__OperatorBegin < curr.kind && curr.kind < Token__OperatorEnd)) {
error(curr.pos, "expected an operator, got '%.*s'", LIT(token_strings[curr.kind]));
}
break;
}
// ok
next_token(p);
return curr;
}
Token expect_semicolon(Parser *p) {
Token prev = p->prev_token;
Token curr = p->curr_token;
switch (curr.kind) {
case Token_Semicolon:
goto end;
case Token_CloseParen:
case Token_CloseBracket:
if (prev.pos.line == curr.pos.line) {
goto end;
}
goto error;
}
error:
error(curr.pos, "expected as semicolon, got '%.*s'", LIT(token_strings[curr.kind]));
end:
next_token(p);
return curr;
}
bool allow_token(Parser *p, TokenKind kind) {
if (p->curr_token.kind == kind) {
next_token(p);
return true;
}
return false;
}
ParserError init_parser(Parser *p, char const *path) {
TokenizerError err = init_tokenizer(&p->tokenizer, path);
p->fullpath = p->tokenizer.fullpath;
switch (err) {
case TokenizerError_Empty: return ParserError_Empty;
case TokenizerError_Invalid: return ParserError_Invalid;
case TokenizerError_NotExists: return ParserError_NotExists;
}
next_token(p);
return ParserError_None;
}
AstExpr *parse_expr(Parser *p, bool lhs);
AstType *parse_type(Parser *p);
AstType *parse_type_attempt(Parser *p);
AstDecl *parse_decl(Parser *p);
AstStmt *parse_stmt(Parser *p);
AstExpr *unparen_expr(AstExpr *e) {
for (;;) {
if (e == NULL) {
return NULL;
}
if (e->kind == AstExpr_Paren) {
return e->paren.expr;
}
return e;
}
}
AstExpr *parse_ident(Parser *p) {
return ast_expr_ident(expect_token(p, Token_Ident));
}
AstExpr *parse_literal(Parser *p, TokenKind kind) {
return ast_expr_literal(expect_token(p, kind));
}
AstExpr *parse_operand(Parser *p, bool lhs) {
AstType *t = NULL;
Token curr = p->curr_token;
switch (curr.kind) {
case Token_Ident: return parse_ident(p);
case Token_Integer: return parse_literal(p, Token_Integer);
case Token_Float: return parse_literal(p, Token_Float);
case Token_Rune: return parse_literal(p, Token_Rune);
case Token_String: return parse_literal(p, Token_String);
case Token_OpenParen: {
Token open, close;
AstExpr *expr;
open = expect_token(p, Token_OpenParen);
p->expr_level += 1;
expr = parse_expr(p, lhs);
p->expr_level -= 1;
close = expect_token(p, Token_CloseParen);
return ast_expr_paren(open.pos, expr, close.pos);
}
default:
t = parse_type_attempt(p);
if (t != NULL) {
return ast_expr_type_expr(t);
}
return NULL;
}
}
AstExpr *parse_call_expr(Parser *p, AstExpr *operand) {
AstExpr *call = NULL;
Token open, close;
AstExpr **args = NULL;
open = expect_token(p, Token_OpenParen);
while (p->curr_token.kind != Token_CloseParen &&
p->curr_token.kind != Token_EOF) {
AstExpr *arg = parse_expr(p, false);
buf_push(args, arg);
if (!allow_token(p, Token_Comma)) {
break;
}
}
close = expect_token(p, Token_CloseParen);
call = ast_expr_call(operand, args, buf_len(args), token_end_pos(close));
buf_free(args);
return call;
}
AstExpr *parse_atom_expr(Parser *p, AstExpr *operand, bool lhs) {
if (operand == NULL) {
if (p->allow_type) {
return NULL;
} else {
Token prev = p->curr_token;
error(prev.pos, "expected an operand");
next_token(p);
return alloc_ast_expr(AstExpr_Invalid, prev.pos, p->curr_token.pos);
}
}
for (;;) {
switch (p->curr_token.kind) {
case Token_OpenParen:
operand = parse_call_expr(p, operand);
break;
case Token_Period: {
Token token = next_token(p);
if (p->curr_token.kind == Token_Ident) {
operand = ast_expr_selector(operand, parse_ident(p));
} else {
error(p->curr_token.pos, "expected an identifier for selector");
next_token(p);
operand = alloc_ast_expr(AstExpr_Invalid, operand->pos, p->curr_token.pos);
}
break;
}
case Token_OpenBracket: {
Token open = expect_token(p, Token_OpenBracket);
AstExpr *index = parse_expr(p, false);
Token close = expect_token(p, Token_CloseBracket);
operand = ast_expr_index(operand, index, token_end_pos(close));
break;
}
case Token_Pointer:
operand = ast_expr_deref(operand, expect_token(p, Token_Pointer));
break;
default:
goto end;
}
lhs = false;
}
end:
return operand;
}
AstExpr *parse_unary_expr(Parser *p, bool lhs) {
switch (p->curr_token.kind) {
case Token_At:
case Token_Add:
case Token_Sub:
case Token_not: {
Token op = next_token(p);
AstExpr *expr = parse_unary_expr(p, lhs);
return ast_expr_unary(op, expr);
}
}
return parse_atom_expr(p, parse_operand(p, lhs), lhs);
}
AstExpr *parse_binary_expr(Parser *p, bool lhs, int prec_in) {
int prec;
AstExpr *expr = parse_unary_expr(p, lhs);
for (prec = token_precedence(p->curr_token.kind); prec >= prec_in; prec--) {
for (;;) {
Token op = p->curr_token;
int op_prec = token_precedence(op.kind);
if (op_prec != prec) {
// NOTE(bill): This will also catch operators that are not valid "binary" operators
break;
}
expect_operator(p); // NOTE(bill): error checks too
if (op.kind == Token_Question) {
AstExpr *cond, *x, *y;
cond = expr;
x = parse_expr(p, lhs);
expect_token(p, Token_Colon);
y = parse_expr(p, lhs);
expr = ast_expr_ternary(cond, x, y);
} else {
AstExpr *right = parse_binary_expr(p, false, prec+1);
if (right == NULL) {
error(op.pos, "expected expression on the right-hand side of the binary operator");
}
expr = ast_expr_binary(op, expr, right);
}
lhs = false;
}
}
return expr;
}
AstExpr *parse_expr(Parser *p, bool lhs) {
return parse_binary_expr(p, lhs, 0+1);
}
AstExpr **parse_ident_list(Parser *p, isize *count) {
AstExpr **res = NULL;
AstExpr **list = NULL;
ASSERT(count != NULL);
for (;;) {
buf_push(list, parse_ident(p));
if (p->curr_token.kind != Token_Comma ||
p->curr_token.kind == Token_EOF) {
break;
}
next_token(p);
}
*count = buf_len(list);
res = AST_DUP_ARRAY(list, buf_len(list));
buf_free(list);
return res;
}
void convert_to_ident_list(Parser *p, AstExpr **list, isize count) {
isize i;
for (i = 0; i < count; i++) {
AstExpr *ident = list[i];
switch (ident->kind) {
case AstExpr_Ident:
case AstExpr_Invalid:
break;
default:
error(ident->pos, "expected an identifier");
ident = ast_expr_ident(blank_ident);
break;
}
list[i] = ident;
}
}
AstField parse_field(Parser *p) {
AstField field = {0};
field.names = parse_ident_list(p, &field.name_count);
expect_token(p, Token_Colon);
field.type = parse_type(p);
return field;
}
AstExpr **parse_expr_list(Parser *p, bool lhs, isize *count) {
AstExpr **res = NULL;
AstExpr **list = NULL;
ASSERT(count != NULL);
for (;;) {
AstExpr *expr = parse_expr(p, lhs);
if (expr == NULL) {
Token tok = p->curr_token;
error(tok.pos, "bad expression, got %.*s", LIT(tok.string));
expr = alloc_ast_expr(AstExpr_Invalid, tok.pos, token_end_pos(tok));
buf_push(list, expr);
break;
}
buf_push(list, expr);
if (p->curr_token.kind != Token_Comma ||
p->curr_token.kind == Token_EOF) {
break;
}
next_token(p);
}
*count = buf_len(list);
res = AST_DUP_ARRAY(list, buf_len(list));
buf_free(list);
return res;
}
AstType *parse_signature(Parser *p, Token token) {
Token open, close;
TokenPos end;
AstField *params = NULL;
AstType *return_type = NULL;
open = expect_token(p, Token_OpenParen);
if (p->curr_token.kind != Token_CloseParen &&
p->curr_token.kind != Token_EOF) {
isize list_count = 0;
AstExpr **list = parse_expr_list(p, true, &list_count); // NOTE(bill): Could be identifiers or types
if (p->curr_token.kind == Token_Colon) {
AstField field = {0};
convert_to_ident_list(p, list, list_count);
field.names = list;
field.name_count = list_count;
expect_token(p, Token_Colon);
field.type = parse_type(p);
buf_push(params, field);
if (allow_token(p, Token_Comma)) {
while (p->curr_token.kind != Token_CloseParen &&
p->curr_token.kind != Token_EOF) {
buf_push(params, parse_field(p));
if (!allow_token(p, Token_Comma)) {
break;
}
}
}
} else {
isize i;
for (i = 0; i < list_count; i++) {
AstExpr *expr = list[i];
AstField field = {0};
AstType *type = NULL;
switch (expr->kind) {
case AstExpr_TypeExpr:
type = expr->type_expr;
break;
case AstExpr_Ident:
type = ast_type_ident(expr);
break;
default:
error(expr->pos, "expected a type in signature list");
continue;
}
field.type = type;
{
AstExpr **names = ast_alloc(sizeof(AstExpr *));
Token token = blank_ident;
token.pos = expr->pos;
names[0] = ast_expr_ident(token);
field.names = names;
field.name_count = 1;
buf_push(params, field);
}
}
}
}
close = expect_token(p, Token_CloseParen);
end = token_end_pos(close);
if (allow_token(p, Token_Colon)) {
return_type = parse_type(p);
end = return_type->end;
}
return ast_type_signature(token, params, buf_len(params), return_type, end);
}
AstType *parse_type(Parser *p) {
AstType *t = NULL;
Token prev = p->curr_token;
bool prev_allow_type = p->allow_type;
p->allow_type = true;
t = parse_type_attempt(p);
p->allow_type = prev_allow_type;
if (t == NULL) {
error(prev.pos, "expected a type, got %.*s", LIT(prev.string));
next_token(p);
return alloc_ast_type(AstType_Invalid, prev.pos, p->curr_token.pos);
}
return t;
}
AstType *parse_type_attempt(Parser *p) {
Token curr = p->curr_token;
switch (curr.kind) {
case Token_Ident:
return ast_type_ident(parse_ident(p));
case Token_OpenBracket: { // Array
Token open, close;
AstExpr *size = NULL;
AstType *elem = NULL;
open = expect_token(p, Token_OpenBracket);
if (p->curr_token.kind != Token_CloseBracket) {
size = parse_expr(p, true);
}
close = expect_token(p, Token_CloseBracket);
elem = parse_type(p);
return ast_type_array(open, size, elem);
}
case Token_Pointer: {
Token token = expect_token(p, Token_Pointer);
AstType *elem = parse_type(p);
return ast_type_pointer(token, elem);
}
case Token_set: {
Token token, open, close;
AstExpr **elems = NULL;
token = expect_token(p, Token_set);
open = expect_token(p, Token_OpenBracket);
while (p->curr_token.kind != Token_CloseBracket &&
p->curr_token.kind != Token_EOF) {
buf_push(elems, parse_expr(p, true));
if (!allow_token(p, Token_Comma)) {
break;
}
}
close = expect_token(p, Token_CloseBracket);
return ast_type_set(token, elems, buf_len(elems), close.pos);
}
case Token_range: {
Token token = expect_token(p, Token_range);
AstExpr *expr = parse_expr(p, false);
expr = unparen_expr(expr);
if (expr != NULL && expr->kind == AstExpr_Binary &&
expr->binary.op.kind == Token_Ellipsis) {
return ast_type_range(token, expr->binary.left, expr->binary.right);
}
error(p->curr_token.pos, "expected range expression");
return alloc_ast_type(AstType_Invalid, token.pos, token.pos);
}
case Token_proc: {
Token token = expect_token(p, Token_proc);
return parse_signature(p, token);
}
}
return NULL;
}
AstStmt *parse_body(Parser *p) {
Token open, close;
AstStmt **stmts = NULL;
open = expect_token(p, Token_OpenBrace);
while (p->curr_token.kind != Token_CloseBrace &&
p->curr_token.kind != Token_EOF) {
buf_push(stmts, parse_stmt(p));
}
close = expect_token(p, Token_CloseBrace);
return ast_stmt_block(stmts, buf_len(stmts), open.pos, close.pos);
}
AstStmt *parse_if_stmt(Parser *p) {
Token token = expect_token(p, Token_if);
AstExpr *cond = NULL;
AstStmt *body = NULL;
AstStmt *else_stmt = NULL;
isize prev_level = p->expr_level;
p->expr_level = -1;
cond = parse_expr(p, false);
p->expr_level = prev_level;
if (cond == NULL) {
error(p->curr_token.pos, "expected condition for if statement");
}
body = parse_body(p);
if (allow_token(p, Token_else)) {
switch (p->curr_token.kind) {
case Token_if:
else_stmt = parse_if_stmt(p);
break;
case Token_OpenBrace:
else_stmt = parse_body(p);
break;
default:
error(p->curr_token.pos, "expected if statement block statement");
else_stmt = NULL;
break;
}
}
return ast_stmt_if(token, cond, body, else_stmt);
}
AstStmt *parse_for_stmt(Parser *p) {
Token token = expect_token(p, Token_for);
AstStmt *init = NULL;
AstExpr *cond = NULL;
AstStmt *post = NULL;
AstStmt *body = NULL;
isize prev_level = p->expr_level;
p->expr_level = -1;
// TODO(bill): for stmt
p->expr_level = prev_level;
return ast_stmt_for(token, init, cond, post, body);
}
AstStmt *parse_while_stmt(Parser *p) {
Token token = expect_token(p, Token_while);
AstExpr *cond = NULL;
AstStmt *body = NULL;
isize prev_level = p->expr_level;
p->expr_level = -1;
cond = parse_expr(p, false);
p->expr_level = prev_level;
if (cond == NULL) {
error(p->curr_token.pos, "expected condition for while statement");
}
body = parse_body(p);
return ast_stmt_while(token, cond, body);
}
AstStmt *parse_return_stmt(Parser *p) {
Token token = expect_token(p, Token_return);
AstExpr *expr = NULL;
if (p->curr_token.kind != Token_Semicolon) {
expr = parse_expr(p, false);
}
return ast_stmt_return(token, expr);
}
AstStmt *parse_simple_stmt(Parser *p) {
AstExpr *lhs = NULL;
AstExpr *rhs = NULL;
Token token;
lhs = parse_expr(p, true);
token = p->curr_token;
switch (token.kind) {
case Token_Define:
case Token_Assign:
case Token_AddEq:
case Token_SubEq:
case Token_MulEq:
case Token_DivEq:
case Token_ModEq:
next_token(p);
rhs = parse_expr(p, false);
return ast_stmt_assign(token, lhs, rhs);
}
return ast_stmt_expr(lhs);
}
AstStmt *parse_stmt(Parser *p) {
AstStmt *stmt = NULL;
switch (p->curr_token.kind) {
case Token_var:
case Token_const:
case Token_type:
case Token_proc:
case Token_import:
return ast_stmt_decl(parse_decl(p));
case Token_label: {
Token token = expect_token(p, Token_label);
AstExpr *name = parse_ident(p);
stmt = ast_stmt_label(token, name);
expect_semicolon(p);
return stmt;
}
case Token_Ident:
case Token_Integer:
case Token_Float:
case Token_Rune:
case Token_String:
case Token_OpenParen:
case Token_Pointer:
case Token_Add:
case Token_Sub:
case Token_At:
stmt = parse_simple_stmt(p);
expect_semicolon(p);
return stmt;
case Token_OpenBrace:
return parse_body(p);
case Token_Semicolon:
return ast_stmt_empty(expect_semicolon(p));
case Token_if: return parse_if_stmt(p);
case Token_for: return parse_for_stmt(p);
case Token_while: return parse_while_stmt(p);
case Token_return: return parse_return_stmt(p);
case Token_break:
case Token_continue:
case Token_fallthrough: {
Token token = next_token(p);
stmt = ast_stmt_branch(token);
expect_semicolon(p);
return stmt;
}
case Token_goto: {
Token token = expect_token(p, Token_goto);
AstExpr *name = parse_ident(p);
stmt = ast_stmt_goto(token, name);
expect_semicolon(p);
return stmt;
}
}
stmt = ast_stmt_expr(parse_expr(p, true));
expect_semicolon(p);
return stmt;
}
AstDecl *parse_decl_var(Parser *p) {
Token token = expect_token(p, Token_var);
AstExpr **names = NULL;
AstType *type = NULL;
AstExpr **values = NULL;
do {
buf_push(names, parse_ident(p));
if (!allow_token(p, Token_Comma)) {
break;
}
} while (p->curr_token.kind != Token_EOF);
if (allow_token(p, Token_Colon)) {
type = parse_type(p);
}
if (allow_token(p, Token_Assign)) {
do {
buf_push(values, parse_expr(p, false));
if (!allow_token(p, Token_Comma)) {
break;
}
} while (p->curr_token.kind != Token_EOF);
}
if (type == NULL && values == NULL) {
error(p->curr_token.pos, "expected a type after var names");
} else if (values != NULL) {
int lhs = cast(int)buf_len(names);
int rhs = cast(int)buf_len(values);
if (lhs != rhs) {
error(p->curr_token.pos, "unbalanced names and values, %d != %d", lhs, rhs);
}
}
return ast_decl_var(token, names, buf_len(names), type, values, buf_len(values));
}
AstDecl *parse_decl_const(Parser *p) {
Token token = expect_token(p, Token_const);
AstExpr **names = NULL;
AstType *type = NULL;
AstExpr **values = NULL;
do {
buf_push(names, parse_ident(p));
if (!allow_token(p, Token_Comma)) {
break;
}
} while (p->curr_token.kind != Token_EOF);
if (allow_token(p, Token_Colon)) {
type = parse_type(p);
}
expect_token(p, Token_Assign);
do {
buf_push(values, parse_expr(p, false));
if (!allow_token(p, Token_Comma)) {
break;
}
} while (p->curr_token.kind != Token_EOF);
{
isize lhs = buf_len(names);
isize rhs = buf_len(values);
if (lhs != rhs) {
error(p->curr_token.pos, "unbalanced names and values, %ld vs %ld", lhs, rhs);
}
}
return ast_decl_const(token, names, buf_len(names), type, values, buf_len(values));
}
AstDecl *parse_decl_type(Parser *p) {
Token token = expect_token(p, Token_type);
AstExpr *name = parse_ident(p);
AstType *type = parse_type(p);
return ast_decl_type(token, name, type);
}
AstDecl *parse_decl_proc(Parser *p) {
Token token = expect_token(p, Token_proc);
AstExpr *name = parse_ident(p);
AstType *signature = parse_signature(p, token);
AstStmt *body = NULL;
if (p->curr_token.kind == Token_OpenBrace) {
body = parse_body(p);
}
return ast_decl_proc(token, name, signature, body);
}
AstDecl *parse_decl_import(Parser *p) {
Token token = expect_token(p, Token_import);
Token path = expect_token(p, Token_String);
return NULL;
}
AstDecl *parse_decl(Parser *p) {
switch (p->curr_token.kind) {
case Token_var: return parse_decl_var(p);
case Token_const: return parse_decl_const(p);
case Token_type: return parse_decl_type(p);
case Token_proc: return parse_decl_proc(p);
case Token_import: return parse_decl_import(p);
case Token_Semicolon:
return ast_decl_empty(expect_semicolon(p));
case Token_EOF:
return NULL;
}
error(p->curr_token.pos, "expected a declaration, got %.*s", LIT(token_strings[p->curr_token.kind]));
next_token(p);
return NULL;
}
ParserError parse_package(AstPackage *package, char const *package_path) {
Parser p = {0};
AstDecl **decls = NULL;
ParserError err = init_parser(&p, package_path);
package->fullpath = p.fullpath;
if (err != ParserError_None) {
return err;
}
while (p.curr_token.kind != Token_EOF) {
AstStmt *stmt = parse_stmt(&p);
if (stmt == NULL) {
continue;
}
switch (stmt->kind) {
case AstStmt_Decl:
buf_push(decls, stmt->decl);
break;
case AstStmt_Invalid:
case AstStmt_Empty:
break;
default:
error(stmt->pos, "only prefixed declarations are allowed at file scope");
break;
}
}
package->decls = AST_DUP_ARRAY(decls, buf_len(decls));
package->decl_count = buf_len(decls);
buf_free(decls);
return err;
}
|
C
|
#include<stdio.h>
int main(){
int a;
char b;
float c;
double d;
a = 2;
b = 'B';
c = 0.25;
d = 0.1543245679;
printf(" %d \n %c \n %.2f \n %.10f",a,b,c,d);
return 0;
}
/*
Saída:
2
B
0.25
0.1543245679
*/
|
C
|
#include <stdio.h>
int main()
{
char line[12] = {"hexadecimal"};
printf("%10s %15s %15.5s %.5s\n", line, line, line, line);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** list_utils2
** File description:
** Linked list functions
*/
#include "lib.h"
dlist_t *new_list(void)
{
return (NULL);
}
bool is_empty_list(dlist_t *li)
{
if (li == NULL)
return true;
return false;
}
dlist_node_t *search_list_op(dlist_t *li, int to_find)
{
if (is_empty_list(li))
return (li->begin);
dlist_node_t *tmp = li->begin;
while ((tmp->value != to_find || tmp->found != 1) && tmp->is_calcul != 1) {
if (tmp->next == NULL)
break;
tmp = tmp->next;
}
tmp->found = 0;
return (tmp);
}
void print_list(dlist_t *li)
{
if (is_empty_list(li)) {
my_putstr("Nothing to display, list is empty");
return;
}
dlist_node_t *tmp = li->begin;
while (tmp != NULL) {
if (tmp->is_op == 1) {
my_putchar(tmp->value);
tmp = tmp->next;
}
else {
my_put_nbr(tmp->value);
tmp = tmp->next;
}
}
my_putchar('\n');
}
dlist_node_t *search_first_max(dlist_t *li, int to_find)
{
if (is_empty_list(li))
return (li->begin);
dlist_node_t *tmp = li->begin;
if (tmp->is_op == 1)
tmp = tmp->next;
while (tmp->weight != to_find && tmp->next != NULL)
tmp = tmp->next;
return (tmp);
}
|
C
|
#include "stdio.h"
main()
{
float precoFab, pctLucroDist, pctImpostos, vlLucroDist, vlImpostos, vlFinal;
printf("Digite o preco de fabrica: ");
scanf("%f", &precoFab);
printf("Digite a porcentagem do distribuidor: ");
scanf("%f", &pctLucroDist);
printf("Digite a porcentagem dos impostos: ");
scanf("%f", &pctImpostos);
vlLucroDist = precoFab * (1.0 - ((100 - pctLucroDist) / 100));
vlImpostos = precoFab * (1.0 - ((100 - pctImpostos) / 100));
vlFinal = precoFab + vlLucroDist + vlImpostos;
printf("O lucro do distribuidor e: %.2f\n", vlLucroDist);
printf("O valor dos impostos e: %.2f\n", vlImpostos);
printf("O valor final do Veiculo e: %.2f", vlFinal);
}
|
C
|
/*
* This is not a unit test. :)
* It's just a little 'sandbox'
* for playing around with code.
* It's easier to use GDB with than
* criterion.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <plugins.h>
int main() {
char *table_stack = \
"# Here is a table\n\n"
"| Name | Age | Description |\n"
"| -- | -- | -- |\n"
"| Joe | 19 | An average guy with a super power |\n\n"
"# Here is another table:\n\n"
"| Name | Age |\n"
"| ted | 22 |\n\n";
char *expectedResult_stack = \
"# Here is a table\n\n"
"| Name | Age | Description |\n"
"| ---- | --- | ---------------------------------- |\n"
"| Joe | 19 | An average guy with a super power. |\n\n"
"# Here is another table:\n\n"
"| Name | Age |\n"
"| ted | 22 |\n\n";
// Malloc new variables and copy the strings
char *table = (char*) malloc(strlen(table_stack)+1);
char *expectedResult = (char*) malloc(strlen(expectedResult_stack)+1);
strcpy(table, table_stack);
strcpy(expectedResult, expectedResult_stack);
// Run Beautification code
table = plugin_beautify_tables( table );
table = plugin_ensure_newline( table );
printf("Expected:\n[TABLE]%s[/TABLE]\nActual:\n[TABLE]%s[/TABLE]", expectedResult, table);
free(table);
free(expectedResult);
return 0;
}
|
C
|
#include<stdio.h>
//This is an implementation of linear convolution.
int main(){
int lx,lh,i,k;
printf("Enter length of x[n]");
scanf("%d",&lx);
printf("Enter length of h[n]");
scanf("%d",&lh);
int x[lx],h[lh],y[lx+lh-1];
printf("Enter elements for x[n]");
for(i=0;i<lx;i++)
{
scanf("%d",&x[i]);
}
printf("Enter elements for h[n]");
for(i=0;i<lh;i++)
{
scanf("%d",&h[i]);
}
for(i=0;i<(lx+lh-1);i++)
{
y[i]=0;
for(k=0;k<(lx+lh-1);k++)
{
if(!((i-k)<0 || (i-k)>=lh || k>=lx))
{
y[i] += (x[k]*h[i-k]);
}
}
printf("\ny(%d)=%d",i,y[i]);
printf("\n");
}
return 0;
}
|
C
|
#ifndef _MATRIX_H
#define _MATRIX_H
#include "Vector.h"
// 3x3 matrix for 3d transforms and translations
// Arranged in column-major order as follows:
// _ _
// | 0 4 8 12 |
// Mat4.entry = | 1 5 9 13 |
// | 2 6 10 14 |
// | 3 7 11 15 |
// |_ _|
typedef struct st_mat4{
double entry[16];
} Mat4;
//Returns the identity matrix
Mat4 mat4Identity();
// Retruns a transformation matrix which scales 3d vectors by the given amount
Mat4 mat4Scale(double sx, double sy, double sz);
// Returns a transformation matrix which rotates 3d vectors about an axis by the
// given angle measure in radians
Mat4 mat4RotateX(double theta);
Mat4 mat4RotateY(double theta);
Mat4 mat4RotateZ(double theta);
// Returns a transformation matrix which essentially performs 3d vector addition
// with the given vertex.
Mat4 mat4Translate(double tx, double ty, double tz);
// Returns a projection transformation based on the given dimensions
Mat4 mat4Frustum(double left, double right, double bottom, double top,
double near, double far);
Mat4 mat4Ortho(double left, double right, double bottom, double top,
double near, double far);
// Computes the product of two matrices.
Mat4 mat4Prod(Mat4 mA, Mat4 mB);
// Yields the first three components of the product of the given matrix and
// vector. Assumes the w component of the vector is 1
Vector mat4VectorProd(Mat4 m, Vector v);
void printMatrix(Mat4 m);
#endif
|
C
|
/*
* sequenceAlignment.c
*
* Here is the main program.
*
* Russ Brown
*/
/* @(#)sequenceAlignment.c 1.56 10/01/27 */
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <time.h>
#include "sequenceAlignment.h"
int main(int argc, char **argv) {
int myTaskID, ierr;
int randomSeed, scale, mainSeqLength, matchSeqLength;
time_t timeVar;
struct tm *timeStr;
double startTime;
SIMMATRIX_T *simMatrix;
SEQDATA_T *seqData;
ASTR_T *A;
BSTR_T *B;
CSTR_T *C;
/* Check for both OMP and MPI defined. */
#if defined(SPEC_OMP) && defined(MPI)
printf("Either OMP or MPI may be #define'd but not both!\n");
exit (1);
#endif
/* Initialize MPI and get the task number if required. */
#ifdef MPI
if ( MPI_Init(&argc, &argv) != MPI_SUCCESS ) {
printf("sequenceAlignment: cannot initialize MPI\n");
exit (1);
}
if ( MPI_Comm_rank(MPI_COMM_WORLD, &myTaskID) != MPI_SUCCESS ) {
printf("sequenceAlignment: cannot get myTaskID\n");
MPI_Finalize();
exit (1);
}
#else
myTaskID = 0;
#endif
/* Get the scale variable as a command-line argument or by default. */
if ( (argc != 1) && (argc != 2) ) {
if (myTaskID == 0) {
printf("Usage: %s <2*log2(sequence length)>\n", argv[0]);
}
exit (1);
}
if (argc == 1) {
scale = SCALE;
} else {
scale = atoi(argv[1]);
if (scale < 0) {
if (myTaskID == 0) {
printf("sequenceAlignment: 2*log2(sequence length) must be >= 0!\n");
}
exit(1);
}
}
/* Set the sequence lengths from the scale variable. */
mainSeqLength = matchSeqLength = 1 << (scale / 2);
/*--------------------------------------------------------------------------
* Preamble.
*-------------------------------------------------------------------------*/
/* Test the user parameters. */
getUserParameters();
if (myTaskID == 0) {
printf("\nHPCS SSCA #1 Bioinformatics Sequence Alignment ");
printf("Executable Specification:\nRunning...\n");
}
#ifdef ENABLE_VERIF
randomSeed = 1; /* when debugging reproduce the results. */
#else
time(&timeVar);
timeStr = localtime(&timeVar);
randomSeed = 100 * (timeStr->tm_sec +
timeStr->tm_min +
timeStr->tm_hour +
timeStr->tm_mday +
timeStr->tm_mon +
timeStr->tm_year +
timeStr->tm_wday +
timeStr->tm_yday); /* different results for each run. */
#endif
/*-------------------------------------------------------------------------
* Scalable Data Generator
*-------------------------------------------------------------------------*/
if (myTaskID == 0) {
printf("\nScalable data generation beginning execution...\n");
}
startTime = getSeconds(); /* Start performance timing. */
/* Generate Seq data as per the Written Specification. */
simMatrix = genSimMatrix(SIM_EXACT, SIM_SIMILAR, SIM_DISSIMILAR,
GAP_START, GAP_EXTEND, MATCH_LIMIT, SIM_SIZE);
if (myTaskID == 0) {
printf("\n\tgenSimMatrix() completed execution.\n");
}
seqData = genScalData(randomSeed, simMatrix, mainSeqLength, matchSeqLength, SIM_SIZE);
if (myTaskID == 0) {
printf("\n\tgenScalData() completed execution.\n");
}
dispElapsedTime(startTime); /* End performance timing. */
/* Display results outside of performance timing. */
#ifdef ENABLE_VERIF
verifyData(simMatrix, seqData, K1_MIN_SCORE, K1_MIN_SEPARATION);
#endif
/*-------------------------------------------------------------------------
* Kernel 1 - Pairwise Local Alignment
*-------------------------------------------------------------------------*/
if (myTaskID == 0) {
printf("\nKernel 1 - pairwiseAlign() beginning execution...\n");
}
startTime = getSeconds();
/* Compute alignments for the two sequences. */
A = pairwiseAlign(seqData, simMatrix,
K1_MIN_SCORE, K1_MAX_REPORTS, K1_MIN_SEPARATION);
if (myTaskID == 0) {
printf("\n\tpairwiseAlign() completed execution.\n");
}
dispElapsedTime(startTime); /* End performance timing. */
/*-------------------------------------------------------------------------
* Kernel 2A - Find actual codon sequences from scores and endpoints.
*-------------------------------------------------------------------------*/
if (myTaskID == 0) {
printf("\nKernel 2A - scanBackward() beginning execution...\n");
}
startTime = getSeconds();
/* Find codon sequences. */
B = scanBackward(A, K2_MAX_REPORTS, K2_MIN_SEPARATION, K2_MAX_DOUBLINGS);
if (myTaskID == 0) {
printf("\n\tscanBackward() completed execution.\n");
}
dispElapsedTime(startTime);
/* Display results outside of performance timing. */
#ifdef ENABLE_VERIF
verifyAlignment(simMatrix, B, K2A_DISPLAY);
#endif
/*-------------------------------------------------------------------------
* Kernel 2B - Merge results from all threads that executed Kernel 2A.
*-------------------------------------------------------------------------*/
if (myTaskID == 0) {
printf("\nKernel 2B - mergeAlignment() beginning execution...\n");
}
startTime = getSeconds();
/* Merge the alignments that were collected by separate threads. */
C = mergeAlignment(B, K2_MAX_REPORTS, K2_MIN_SEPARATION);
if (myTaskID == 0) {
printf("\n\tmergeAlignment() completed execution.\n");
}
dispElapsedTime(startTime);
/* Display results outside of performance timing. */
#ifdef ENABLE_VERIF
verifyMergeAlignment(simMatrix, C, K2B_DISPLAY);
#endif
/*-------------------------------------------------------------------------
* Deallocate the structures.
*-------------------------------------------------------------------------*/
A = freeA(A);
B = freeB(B);
C = freeC(C);
freeSimMatrix(simMatrix);
freeSeqData(seqData);
/*-------------------------------------------------------------------------
* Postamble.
*-------------------------------------------------------------------------*/
if (myTaskID == 0) {
printf("\nHPCS SSCA #1 Bioinformatics Sequence Alignment ");
printf("Executable Specification:\nEnd of test.\n");
}
#ifdef MPI
if ( MPI_Finalize() != MPI_SUCCESS ) {
printf("sequenceAlignment: cannot finalize MPI\n");
exit (1);
}
#endif
return (0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parser.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lflorrie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/23 15:16:18 by lflorrie #+# #+# */
/* Updated: 2020/12/21 20:28:59 by lflorrie ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf_utils.h"
void star(const char **format, va_list args, t_format_rule *fr)
{
fr->width = (int)va_arg(args, int);
if (fr->width < 0)
{
fr->right = 1;
fr->symb = ' ';
fr->width = -fr->width;
}
++*format;
}
void dot(const char **format, va_list args, t_format_rule *fr)
{
++(*format);
fr->accuracy = 0;
if (ft_isdigit(**format))
fr->accuracy = ft_atoi(*format);
while (ft_isdigit(**format))
++*format;
if (**format == '*')
{
fr->accuracy = (int)va_arg(args, int);
++*format;
}
fr->symb = ' ';
}
void minusandzero(const char **format, t_format_rule *fr)
{
if (**format == '-')
{
fr->right = 1;
++*format;
}
if (**format == '0')
{
if (!fr->right)
fr->symb = '0';
++*format;
}
}
int processing(const char **format, va_list args)
{
t_format_rule fr;
fr.width = 0;
fr.accuracy = -1;
fr.symb = ' ';
fr.right = 0;
while (**format == '-' || **format == '0')
{
minusandzero(format, &fr);
}
if (**format == '*')
{
star(format, args, &fr);
}
if (ft_isdigit(**format))
{
fr.width = ft_atoi(*format);
while (ft_isdigit(**format))
++*format;
}
if (**format == '.')
{
dot(format, args, &fr);
}
return (processing_flags(**format, args, fr));
}
int parser(const char *format, va_list args)
{
int result;
result = 0;
while (*format)
{
if (*format == '%')
{
++format;
result += processing(&format, args);
}
else
{
write(1, format, 1);
++result;
}
++format;
}
return (result);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct vmm_stat_type {char* desc; scalar_t__ scope; scalar_t__ nelems; scalar_t__ index; } ;
/* Variables and functions */
scalar_t__ MAX_VMM_STAT_ELEMS ;
scalar_t__ VMM_STAT_SCOPE_AMD ;
scalar_t__ VMM_STAT_SCOPE_INTEL ;
int /*<<< orphan*/ printf (char*,char*) ;
int /*<<< orphan*/ vmm_is_amd () ;
int /*<<< orphan*/ vmm_is_intel () ;
scalar_t__ vst_num_elems ;
int /*<<< orphan*/ vst_num_types ;
struct vmm_stat_type** vsttab ;
void
vmm_stat_register(void *arg)
{
struct vmm_stat_type *vst = arg;
/* We require all stats to identify themselves with a description */
if (vst->desc == NULL)
return;
if (vst->scope == VMM_STAT_SCOPE_INTEL && !vmm_is_intel())
return;
if (vst->scope == VMM_STAT_SCOPE_AMD && !vmm_is_amd())
return;
if (vst_num_elems + vst->nelems >= MAX_VMM_STAT_ELEMS) {
printf("Cannot accommodate vmm stat type \"%s\"!\n", vst->desc);
return;
}
vst->index = vst_num_elems;
vst_num_elems += vst->nelems;
vsttab[vst_num_types++] = vst;
}
|
C
|
//Write a program to reverse a array.
#include<stdio.h>
void main()
{
int n,i,b;
printf("How many elements you want in array\n");
scanf("%d",&n);
int a[n];
printf("Enter array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n/2;i++)
{
b=a[i];
a[i]=a[n-1-i];
a[n-1-i]=b;
}
printf("Reverse Array:\n");
for(i=0;i<n;i++)
printf("%d",a[i]);
}
|
C
|
#include "internal.h"
MIXED_EXPORT void mixed_free_segment_sequence(struct mixed_segment_sequence *mixer){
if(mixer->segments)
free(mixer->segments);
mixer->segments = 0;
}
MIXED_EXPORT int mixed_segment_sequence_add(struct mixed_segment *segment, struct mixed_segment_sequence *mixer){
mixed_err(MIXED_NO_ERROR);
return vector_add(segment, (struct vector *)mixer);
}
MIXED_EXPORT int mixed_segment_sequence_remove(struct mixed_segment *segment, struct mixed_segment_sequence *mixer){
mixed_err(MIXED_NO_ERROR);
return vector_remove_item(segment, (struct vector *)mixer);
}
MIXED_EXPORT int mixed_segment_sequence_start(struct mixed_segment_sequence *mixer){
size_t count = mixer->count;
for(size_t i=0; i<count; ++i){
struct mixed_segment *segment = mixer->segments[i];
if(segment->start){
if(!segment->start(segment)){
return 0;
}
}
}
return 1;
}
MIXED_EXPORT void mixed_segment_sequence_mix(size_t samples, struct mixed_segment_sequence *mixer){
size_t count = mixer->count;
struct mixed_segment **segments = mixer->segments;
for(size_t i=0; i<count; ++i){
struct mixed_segment *segment = segments[i];
segment->mix(samples, segment);
}
}
MIXED_EXPORT int mixed_segment_sequence_end(struct mixed_segment_sequence *mixer){
size_t count = mixer->count;
for(size_t i=0; i<count; ++i){
struct mixed_segment *segment = mixer->segments[i];
if(segment->end){
if(!segment->end(segment)){
return 0;
}
}
}
return 1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h> // defines hostent structure
int main(int argc,char *argv[]){
int sockfd,newsockfd,portno,n;
struct sockaddr_in serv_addr,cli_addr;
struct hostent *server; // hostent : use store info about host such as hostname ,ipv
char buffer[1000]; // size same as in server
if(argc<3){
fprintf(stderr,"error : less no. of argument\n");
exit(1);
}
portno=atoi(argv[2]);
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){
printf("error : opening in socket\n");
}
server=gethostbyname(argv[1]);
if(server==NULL)
fprintf(stderr,"error,no such host");
bzero( (char *) &serv_addr,sizeof(serv_addr) );
serv_addr.sin_family=AF_INET;
bcopy( (char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr,server->h_length);
serv_addr.sin_port=htons(portno);
if(connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr) )<0){
printf("connection failed");
}
//}
//}
while(1){
bzero(buffer,1000);
fgets(buffer,1000,stdin);
n=write(sockfd,buffer,strlen(buffer));
if(n<0){
printf("error :on writing");
}
bzero(buffer,1000);
n=read(sockfd,buffer,1000);
if(n<0){
printf("error : on reading");
}
printf("server %s\n",buffer);
int i=strncmp("bye",buffer,3);
if(i==0)
break;
}
// close(newsockfd);
close(sockfd);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include<fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#define REPL_HISTORY_LIMIT 100
#define REPL_INPUT_LIMIT 100
#define REPL_MAX_TOKENS 15
#define REPL_ASYNC "&"
#define REPL_INPUT "<"
#define REPL_OUTPUT ">"
#define REPL_PIPE "|"
#define REPL_INPUT_ID 1
#define REPL_OUTPUT_ID 2
#define REPL_PIPE_ID 3
#define REPL_EXIT "exit"
#define REPL_LIST_JOBS "listjobs"
#define REPL_FOREGROUND "fg"
#define REPL_KILL "kill"
#define REPL_STDIN 0
#define REPL_STDOUT 1
/*
TODO: Make exec id for pipes and background processes same
TODO: Make different files for replExec, History and additional command execution
*/
bool TESTING_MODE = true;
int saved_stdout;
int saved_stdin;
struct processMetaData
{
__pid_t processID;
char command[REPL_INPUT_LIMIT];
int execId;
char * execStatus;
};
struct processMetaData execHistory[REPL_HISTORY_LIMIT];
int execHistoryLength = 0;
int prevASync = -1;
int genExecId() {
return rand()% 900+ 100;
}
/*
function takes char and Delimiter as input and returns a array of splitted char's
*/
int parseInput(char replInput[], char * arrayToPut[], char delimiter[]) {
int lengthOfTokens = 0;
arrayToPut[lengthOfTokens] = strtok(replInput, delimiter);
while (arrayToPut[lengthOfTokens] != NULL) {
arrayToPut[++lengthOfTokens] = strtok(NULL, delimiter);
}
arrayToPut[lengthOfTokens + 1] = (char * ) NULL;
return lengthOfTokens;
}
char * getStatus(struct processMetaData meta) {
int processStatus;
// in finished state waitpid will return error as there will be no process in execution. Thus only check when process is running.
if( strcmp(meta.execStatus,"RUNNING") == 0){
__pid_t return_pid = waitpid(meta.processID, &processStatus, WNOHANG); // Only checks status of pid
if( return_pid == -1) {
perror("error in getting process");
return "ERROR";
} else if ( return_pid == 0) {
return "RUNNING";
} else if ( return_pid == meta.processID) {
return "FINISHED";
}
} else {
return meta.execStatus;
}
}
void childProcess(char * replParsedInput[], int *inputDescriptor, int inputDescriptorLength, int *outputDescriptor, int outputDescriptorLength){
// Use execv
fprintf(stdout, "child Process\n");
// dup2(saved_stdout, 1);
if ( inputDescriptorLength > 0) {
/*
changing Input to inputDescriptor
*/
fprintf(stderr, "Input Descriptor is provided\n");
close(0); /* close normal stdin (fd = 0)*/
if ( dup2(inputDescriptor[0],REPL_STDIN) < 0) { /* make stdin same as inputDescriptor[0] */
perror("P:Error in duping Input Descriptor(stdin) to provided descriptor\n");
exit(EXIT_FAILURE);
}
// if(inputDescriptor[1]) {
close(inputDescriptor[1]); /* we don't need the write end -- inputDescriptor[1]*/
// }
} else {
fprintf(stderr, "Input Descriptor to stdin\n");
// dup2(saved_stdin, 0);
}
if ( outputDescriptorLength > 0 ) {
/*
changing Output to outputDescriptor
*/
fprintf(stderr, "Output Descriptor is provided\n");
close(1); /* close normal stdout (fd = 1) */
if ( dup2(outputDescriptor[1],REPL_STDOUT) < 0) { /* make stdout same as outputDescriptor[1] */
perror("P:Error in duping Output Descriptor (stdout) to provided descriptor\n");
exit(EXIT_FAILURE);
}
// if(outputDescriptor[0]) {
close(outputDescriptor[0]); /* we don't need the read end -- outputDescriptor[0] */
// }
} else {
fprintf(stderr, "Output Descriptor to stdout\n");
// dup2(saved_stdout, 1);
}
// dup2(saved_stdout, 1);
// printf("child stdout check\n");
// fflush(stdout);
// for(int i = 0; i < 5; i++ ) {
// fprintf(stderr, "child executing %s \n",replParsedInput[i] );
// }
int exec_return_value = execvp(replParsedInput[0], replParsedInput);
if (exec_return_value == -1) {
perror("Error is executing command");
exit(EXIT_FAILURE);
}
}
void parentProcess(char * replParsedInput[], __pid_t child_pid, bool async) {
pid_t rc_pid;
int execID;
char * status = "RUNNING";
// printf("P:Child process pid is : %d \n", child_pid);
if (!async) {
// printf("P:Async turned OFF waiting for child\n");
int wait_status;
__pid_t terminated_child_pid = waitpid( child_pid, &wait_status, 0);
if (terminated_child_pid == -1) {
status = "Error";
perror("wait");
exit(EXIT_FAILURE);
} else {
status = "FINISHED";
}
execID = rand()% 900+ 100;
prevASync = -1;
} else {
// Assign same execution id to Async process
if (prevASync < 0) {
execID = rand()% 900+ 100;
prevASync = execID;
} else {
execID = prevASync;
}
status = "RUNNING";
}
char commandStringCopy[REPL_INPUT_LIMIT] = "";
for(int j = 0; j < REPL_INPUT_LIMIT && replParsedInput[j] != NULL; j++) {
strcat(commandStringCopy, replParsedInput[j]);
strcat(commandStringCopy, " ");
}
struct processMetaData processMeta = {
.processID = child_pid,
.execId = execID,
.execStatus = status
};
// copy the data and not the pointer
strcpy(processMeta.command, commandStringCopy);
execHistory[execHistoryLength++] = processMeta;
}
/*
Executes the command provided by replArrayInput by forking a child and replacing it with exec. Also async flag decides wether REPL waits for child process to finish or not.
*/
__pid_t replExec(char * replParsedInput[], bool async, int *inputDescriptor, int inputDescriptorLength, int *outputDescriptor, int outputDescriptorLength) {
__pid_t child_pid = fork();
if (child_pid == -1) {
// Error in creating the fork
perror("P:Error in forking the process\n");
exit(EXIT_FAILURE);
}
if (child_pid == 0) {
// Child process working
childProcess(replParsedInput, inputDescriptor, inputDescriptorLength, outputDescriptor, outputDescriptorLength);
exit(EXIT_SUCCESS);
}
if (child_pid > 0) {
parentProcess( replParsedInput, child_pid, async);
}
return child_pid;
}
void listExecHistory (bool allFlag) {
printf("\nProcess history\n");
for(int i =0; i< execHistoryLength; i++) {
execHistory[i].execStatus = getStatus( execHistory[i]);
if( allFlag || strcmp(execHistory[i].execStatus, "FINISHED") != 0) {
printf("Command '%s' with PID %d and status: %s\n",execHistory[i].command, execHistory[i].processID, execHistory[i].execStatus);
}
}
// printf("Process history complete\n");
}
int searchHistoryByPid( __pid_t pid) {
int result = -1;
for(int i =0; i< execHistoryLength; i++) {
if( pid == execHistory[i].processID) {
result = i;
}
}
return result;
}
int getIONo( char * inputChar ) {
int returnStatus = -1;
if ( strcmp(inputChar, REPL_INPUT) == 0) {
returnStatus = REPL_INPUT_ID;
} else if (strcmp(inputChar, REPL_OUTPUT) == 0 ) {
returnStatus = REPL_OUTPUT_ID;
} else if (strcmp(inputChar, REPL_PIPE) == 0) {
returnStatus = REPL_PIPE_ID;
}
return returnStatus;
}
int checkIO( char ** inputArr, int length, int ** replInputIOOutputBuff) {
int buffLength = 0;
int prevIndex = -1;
for ( int i = 0; i < length; i++ ) {
int IONumber = getIONo(inputArr[i]);
if ( IONumber != -1 ) {
replInputIOOutputBuff[buffLength] = (int *) malloc( 3*sizeof(int));
replInputIOOutputBuff[buffLength][0] = prevIndex;
replInputIOOutputBuff[buffLength][1] = i;
replInputIOOutputBuff[buffLength][2] = IONumber;
prevIndex = i;
buffLength++;
}
}
// Adding End replIO
replInputIOOutputBuff[buffLength] = (int *)malloc( 3*sizeof(int));
replInputIOOutputBuff[buffLength][0] = prevIndex;
replInputIOOutputBuff[buffLength][1] = length;
replInputIOOutputBuff[buffLength][2] = -1;
buffLength++;
return buffLength;
}
void killProcess(__pid_t pid) {
kill(pid, SIGKILL);
}
static volatile bool signal_ctrl_c = false;
void intHandler(int dummy) {
printf("handler called");
fflush(stdout);
signal_ctrl_c = true;
}
/*
Executes Read–eval–print loop
*/
void repl(void) {
// Exit variable
bool exitREPL = false;
saved_stdout = dup(1);
saved_stdin = dup(0);
while (!exitREPL) {
char text[] = "sh550 > ";
char replInput[REPL_INPUT_LIMIT]= { '\0' } ;
int * replInputIO[REPL_INPUT_LIMIT] = { NULL };
// #Get input
printf("%s", text);
fgets(replInput, REPL_INPUT_LIMIT, stdin);
if (strcmp(replInput, "\n")) {
bool async = false;
// Parse Input
char * seperatedInput[REPL_MAX_TOKENS] = { NULL };
int inputTokenLength = parseInput(replInput, seperatedInput, " \n");
int replIOLength = checkIO(seperatedInput, inputTokenLength, replInputIO);
if (strncmp(seperatedInput[inputTokenLength - 1], REPL_ASYNC, 1) == 0) {
async = true;
seperatedInput[inputTokenLength - 1] = NULL;
}
// Check special command
if (strncmp(seperatedInput[0], REPL_EXIT, 4) == 0) { // "exit" Command
printf("Exiting the REPL! \n");
exitREPL = true;
exit(0);
} else if (strncmp(seperatedInput[0], REPL_KILL, 3) == 0) { // "kill" command
killProcess((__pid_t)atoi(seperatedInput[1]));
} else if (strncmp(seperatedInput[0], REPL_LIST_JOBS, 7) == 0) { // prints history of executed process
listExecHistory(true); // False argument will return process that are running and not all
} else if (strncmp(seperatedInput[0], REPL_FOREGROUND, 2) == 0) { //"fg" command brings background process to foreground i.e parent waits for ${pid} childs exeuction
int wait_status;
int pid = atoi(seperatedInput[1]);
printf("Bringing process '%d' to forground\n", pid);
__pid_t terminated_child_pid = waitpid( (__pid_t) pid, &wait_status, 0);
if (terminated_child_pid == -1) {
perror("foreground");
exit(EXIT_FAILURE);
}
// Update history
int metaDataIndex = searchHistoryByPid(pid);
if( metaDataIndex != -1) {
execHistory[metaDataIndex].execStatus = "FINISHED";
}
} else if ( replIOLength > 1) { // If there exist any defined special characters like "|" , ">" ,"<"
// USed as Input
int prevDescriptor[2];
pipe(prevDescriptor);
int prevDescriptorLength = 0;
// To clear at the end , all the pipes used
int * pipeArrayHistoy[2] = {prevDescriptor};
int pipeArrayLength = 1;
int nextDescriptor[2];
for( int i = 0; i< replIOLength && signal_ctrl_c == false; i++) {
// Used as Output
int nextDescriptorLength = 0;
char **tempReplExec = (char**) malloc(REPL_INPUT_LIMIT * sizeof(char));
int prevIndexWithIO = replInputIO[i][0];
int nextIndexWithIO = replInputIO[i][1];
for( int j = 0; j < nextIndexWithIO - prevIndexWithIO -1; j++) {
tempReplExec[j] = seperatedInput[j + prevIndexWithIO + 1];
}
tempReplExec[nextIndexWithIO - prevIndexWithIO -1] = NULL;
nextDescriptorLength = 0;
/*
Creating a file descriptor to transfer data
*/
if( replInputIO[i][2] == REPL_PIPE_ID) {
if ( i < replIOLength - 1 ) {
if (pipe(nextDescriptor) == -1) {
fprintf(stderr, "error with pipe %d", i);
perror("");
// exit(1);
break;
}
nextDescriptorLength = 2;
pipeArrayHistoy[pipeArrayLength++] = nextDescriptor;
}
} else if( replInputIO[i][2] == REPL_INPUT_ID ){
prevDescriptor[0] = open( seperatedInput[nextIndexWithIO + 1], O_RDONLY);
if( prevDescriptor[0] < 0 ) {
fprintf(stderr, "error with read file descriptor for file %s and token :%d :",seperatedInput[nextIndexWithIO + 1], i);
perror("");
break;
}
prevDescriptorLength = 1;
pipeArrayHistoy[pipeArrayLength++] = prevDescriptor;
i++;
} else if( replInputIO[i][2] == REPL_OUTPUT_ID ){
nextDescriptor[1] = open( seperatedInput[nextIndexWithIO + 1], O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); // write only, if not create file, truncate previous data
nextDescriptor[0] = open( seperatedInput[nextIndexWithIO + 1], O_RDONLY);
if( nextDescriptor[1] < 0 ) {
fprintf(stderr, "error with write file descriptor for file %s and token :%d",seperatedInput[nextIndexWithIO + 1], i);
perror("");
break;
}
if( nextDescriptor[0] < 0 ) {
fprintf(stderr, "error with read file descriptor for file %s and token :%d :",seperatedInput[nextIndexWithIO + 1], i);
perror("");
break;
}
nextDescriptorLength = 1;
pipeArrayHistoy[pipeArrayLength++] = nextDescriptor;
i++;
}
replExec(tempReplExec, false, prevDescriptor, prevDescriptorLength, nextDescriptor, nextDescriptorLength);
if ( dup2(nextDescriptor[0], prevDescriptor[0]) < 0)
{
fprintf(stderr, "error with nextDescriptor read %d", i);
perror("");
break;
}
close(nextDescriptor[1]); // closing write descriptor in parent as it is not required and race condition possible
prevDescriptorLength = nextDescriptorLength;
free(tempReplExec);
}
// ls -la | grep c > o.txt | less
// close unused pipes
for(int i = 0; i < pipeArrayLength; i++ ) {
if( pipeArrayHistoy[i][0] > 0) {
close(pipeArrayHistoy[i][0]);
}
if(pipeArrayHistoy[i][1] > 0) {
close(pipeArrayHistoy[i][1]);
}
}
}
else {
// #Execute
int intputDesc[2];
int outputDesc[2];
replExec(seperatedInput, async, intputDesc, 0,outputDesc, 0);
}
/*
# Cleaning
*/
// freeing replIO memory
for( int i = 0; i < replIOLength; i++) {
free(replInputIO[i]);
}
// listExecHistory(true);
// flush the input buffer
// while(getchar() != '\n');
}
if(signal_ctrl_c) {
signal_ctrl_c = false; // reset signal variable and continue the REPL.
}
}
printf("Exiting REPL!");
}
int main(void) {
signal(SIGINT, intHandler);
printf("The shell is starting\n");
// Start REPL
repl();
return 0;
}
|
C
|
#include "generate_programme.h"
int sequence_accumulator[MAX_n];
int sequence_is_valid = false;
time_t starting_time = 0;
boolean first_time_through_recursion = true;
static mpz_t good_sequences; // Using the GNU multiple precision library.
static mpz_t predicted_number_of_candidate_sequences;
static mpz_t predicted_number_of_candidate_sequences_at_row_n;
boolean found_first_solution = false;
// For some reason I don't understand, if the following variable is defined
// inside main(), the programme segfaults.
int children_per_node_at_level[MAX_n];
int main (int argc, char ** argv) {
int n = 0;
int row = 0;
int col = 0;
int * cardinality = NULL;
aluminium_Christmas_tree big_dumb_array[1 << MAX_n][1 << MAX_n];
aluminium_Christmas_tree * start = &big_dumb_array[0][0];
aluminium_Christmas_tree * dag = NULL;
int i = 0;
boolean option_run_once = false;
boolean option_generate_graph = false;
int option_restart_level = 0;
int row_plus_one_col = 0;
int child_number = 0;
aluminium_Christmas_tree ** addressable_row_array = NULL;
char binary_buffer[MAX_n + 1];
starting_time = time (NULL);
mpz_init (good_sequences);
mpz_init (predicted_number_of_candidate_sequences);
mpz_init (predicted_number_of_candidate_sequences_at_row_n);
process_command_line_options (argc, argv, &option_run_once,
&option_generate_graph, &option_restart_level, &n);
assert (n > 0);
assert (n <= MAX_n);
assert (start);
checkpoint (n);
test_count_1_bits ();
// Initialise the big dumb array with sentinel values. Is it possible
// directly to malloc a two-dimensional array and still index it?
for (row = 0; row < (1 << n); row ++) {
for (col = 0; col < (1 << n); col ++) {
big_dumb_array[row][col].level = -1;
big_dumb_array[row][col].value = -99;
big_dumb_array[row][col].in_use = false;
big_dumb_array[row][col].num_children = 0;
big_dumb_array[row][col].num_children_predicted = 0;
big_dumb_array[row][col].visited = false;
big_dumb_array[row][col].child = NULL;
}
}
verify_all_hand_made_cardinality_sequence_data ();
test_generate_cardinality_sequence_function ();
cardinality = generate_cardinality_sequence (n);
acid_test_for_cardinality_sequence (cardinality, n);
fprintf (stderr, "Version %d\n", VERSION);
// dag is a smarter data structure, built in parallel with the
// big_dumb_array, but meant to supplant it as soon as I'm sure.
addressable_row_array = malloc ((1 << n) * sizeof (aluminium_Christmas_tree *));
assert (addressable_row_array);
row = 0;
col = 0;
dag = malloc (sizeof (aluminium_Christmas_tree));
assert (dag);
dag->level = row;
dag->value = col;
dag->num_children = 0;
dag->in_use = true;
dag->visited = false;
dag->child = NULL;
dag->sibling = NULL;
switch (cardinality[row] - cardinality[row + 1]) {
case -1:
dag->num_children_predicted = count_0_bits (binary (col, n, binary_buffer));
break;
case 1:
dag->num_children_predicted = count_1_bits (binary (col, n, binary_buffer));
break;
default:
assert (false); // This should never happen.
break;
}
addressable_row_array[row] = dag;
// Now generate the graph of allowable transitions.
// A great big shiny aluminium Christmas tree!
assert (NULL == dag->child);
dag->child = malloc ((dag->num_children_predicted + 1) * sizeof (aluminium_Christmas_tree *));
assert (dag->child);
child_number = 0;
dag->child[child_number] = NULL; // Terminate the list.
for (col = 0; col < (1 << n); col ++) {
for (row_plus_one_col = 0; row_plus_one_col < (1 << n); row_plus_one_col ++) {
if (allowable (row, col, row + 1, row_plus_one_col, cardinality, n)) {
aluminium_Christmas_tree * here = NULL;
here = malloc (sizeof (aluminium_Christmas_tree));
assert (here);
here->level = row + 1;
here->value = row_plus_one_col;
here->in_use = true;
here->num_children = 0;
here->num_children_predicted = 0;
here->visited = false;
here->child = NULL;
here->sibling = NULL;
dag->child[child_number] = here;
if (child_number > 0) {
(dag->child[child_number - 1])->sibling = here;
}
here->sibling = NULL;
fprintf (stderr, "%p[%d] = %p\n", (void *) dag,
child_number, (void *) dag->child[child_number]);
++ child_number;
dag->child[child_number] = NULL; // Terminate the list.
}
}
}
dag->num_children = child_number;
++ row;
addressable_row_array[row] = dag->child[0];
// Now build a DAG in the big dumb array.
if (cardinality[0] >= 0) {
int number_of_nodes_used = 0;
double fill_factor_n = 0.0;
double fill_factor_MAX_n = 0.0;
for (row = 0; row < ( (1 << n) - 1); row ++) {
for (col = 0; col < (1 << n); col ++) {
int row_plus_one_col = 0;
int pointer_number = 0;
int predicted_number_of_children = 0;
for (row_plus_one_col = 0; row_plus_one_col < (1 << n); row_plus_one_col ++) {
if (allowable (row, col, row + 1, row_plus_one_col, cardinality, n)) {
char buf1[n + 1];
char buf2[n + 1];
assert (count_1_bits (binary (col, n, buf1)) == cardinality[row]);
assert (count_1_bits (binary (row_plus_one_col, n, buf1))
== cardinality[row + 1]);
switch (cardinality[row] - cardinality[row + 1]) {
case -1:
predicted_number_of_children = count_0_bits (binary (col, n, buf2));
break;
case 1:
predicted_number_of_children = count_1_bits (binary (col, n, buf2));
break;
default:
assert (false); // This should never happen.
break;
}
assert (pointer_number < predicted_number_of_children);
big_dumb_array[row][col].level = row;
big_dumb_array[row][col].value = col;
big_dumb_array[row][col].in_use = true;
if (NULL == big_dumb_array[row][col].child) {
big_dumb_array[row][col].child = malloc (sizeof (aluminium_Christmas_tree *)
* predicted_number_of_children + 1);
assert (big_dumb_array[row][col].child);
big_dumb_array[row][col].child[0] = NULL; // NULL terminate just in case.
}
big_dumb_array[row][col].child[pointer_number] =
&(big_dumb_array[row + 1][row_plus_one_col]);
big_dumb_array[row][col].num_children ++;
big_dumb_array[row][col].num_children_predicted = predicted_number_of_children;
// Why does the following line cause a segfault in error check later?
children_per_node_at_level[row] = predicted_number_of_children;
// Make sure child nodes exist if they are named.
big_dumb_array[row + 1][row_plus_one_col].level = row + 1;
big_dumb_array[row + 1][row_plus_one_col].value = row_plus_one_col;
big_dumb_array[row + 1][row_plus_one_col].in_use = true;
// However, we don't know anything about *their* children.
#ifdef DEBUG
fprintf (stderr,
"recorded node %p (%d, %d) -> %p (%d, %d) with %d ",
(void *) &big_dumb_array[row][col],
big_dumb_array[row][col].level,
big_dumb_array[row][col].value,
(void *) &big_dumb_array[row + 1][row_plus_one_col],
big_dumb_array[row + 1][row_plus_one_col].level,
big_dumb_array[row + 1][row_plus_one_col].value,
predicted_number_of_children);
switch (predicted_number_of_children) {
case 1:
fprintf (stderr, "child");
break;
default:
fprintf (stderr, "children");
break;
}
fprintf (stderr, " predicted.\n");
#endif
++ pointer_number;
}
}
}
}
if (odd (n)) {
big_dumb_array[(1 << n) - 1][(1 << n) - 1].level = (1 << n) - 1;
big_dumb_array[(1 << n) - 1][(1 << n) - 1].value = (1 << n) - 1;
big_dumb_array[(1 << n) - 1][(1 << n) - 1].in_use = true;
fprintf (stderr, "node %p (%d, %d) also created with %d children.\n",
(void *) &big_dumb_array[(1 << n) - 1][(1 << n) - 1],
big_dumb_array[(1 << n) - 1][(1 << n) - 1].level,
big_dumb_array[(1 << n) - 1][(1 << n) - 1].value,
big_dumb_array[(1 << n) - 1][(1 << n) - 1].num_children);
}
for (row = 0; row < (1 << n); row ++) {
for (col = 0; col < (1 << n); col ++) {
if (big_dumb_array[row][col].in_use) {
++ number_of_nodes_used;
}
}
}
mpz_set_ui (predicted_number_of_candidate_sequences, 1);
for (row = 0; row < (1 << n) - 1; row ++) {
mpz_mul_ui (predicted_number_of_candidate_sequences_at_row_n,
predicted_number_of_candidate_sequences,
children_per_node_at_level[row]);
mpz_set (predicted_number_of_candidate_sequences,
predicted_number_of_candidate_sequences_at_row_n);
}
fill_factor_n = (double) number_of_nodes_used / ( pow(2.0, n) * pow (2.0, n) );
fill_factor_MAX_n = (double) number_of_nodes_used / ((1 << MAX_n) * (1 << MAX_n));
fprintf (stderr, "%d nodes used; fill factor = %lf based on n = %d",
number_of_nodes_used, fill_factor_n, n);
if (n < MAX_n) {
fprintf (stderr, " (or %lf based on %d)", fill_factor_MAX_n, MAX_n);
}
fprintf (stderr, "\n");
fprintf (stderr, "The predicted number of candidate sequences is ");
gmp_printfcomma (predicted_number_of_candidate_sequences);
fprintf (stderr, ".\n");
// Error check.
for (row = 0; row < (1 << n); row ++) {
for (col = 0; col < (1 << n); col ++) {
if (big_dumb_array[row][col].num_children
!= big_dumb_array[row][col].num_children_predicted) {
fprintf (stderr,
"misprediction: row %d, col %d (%p); predicted %d children, got %d children\n",
row, col,
(void *) &big_dumb_array[row][col],
big_dumb_array[row][col].num_children_predicted,
big_dumb_array[row][col].num_children);
}
}
}
}
else {
fprintf (stderr, "We have no cardinality data; not attempting "
"to generate the graph of allowed transitions.\n");
}
fprintf (stderr, "\n");
// Initialise the sequence accumulator (outside of the recursive fn).
for (i = 0; i < MAX_n; i ++) {
sequence_accumulator[i] = -1;
}
depth_first_search (start, cardinality, n, option_run_once, option_restart_level);
fprintf (stderr, "\n");
gmp_printfcomma (good_sequences);
if (mpz_cmp_ui (good_sequences, 1) == 0) {
fprintf (stderr, " sequence was");
}
else {
fprintf (stderr, " sequences were");
}
fprintf (stderr, " found in all");
if (option_run_once) {
fprintf (stderr, " (we were told to stop after the first one)");
}
fprintf (stderr, ".\n");
fprintf (stderr, "The predicted number of candidate sequences was ");
gmp_printfcomma (predicted_number_of_candidate_sequences);
fprintf (stderr, ".\n");
if (option_generate_graph) {
write_dot_file (start, cardinality, n);
}
free (cardinality);
cardinality = NULL;
for (row = 0; row < (1 << n); row ++) {
for (col = 0; col < (1 << n); col ++) {
if (big_dumb_array[row][col].child) {
free (big_dumb_array[row][col].child);
big_dumb_array[row][col].child = NULL;
}
}
}
free_dag (dag, n);
dag = NULL;
free (addressable_row_array);
addressable_row_array = NULL;
mpz_clear (good_sequences);
mpz_clear (predicted_number_of_candidate_sequences);
mpz_clear (predicted_number_of_candidate_sequences_at_row_n);
return EXIT_SUCCESS;
}
// This is a simple depth-first search to reset all the 'visited' flags.
void reset_visited_flags (aluminium_Christmas_tree * p, int n) {
int i = 0;
if (false == p->visited) {
return;
}
for (i = 0; i < p->num_children; i ++ ) {
reset_visited_flags (p->child[i], n);
}
p->visited = false;
return;
}
// Doing the same thing as the previous fn but by means of brute force.
void reset_visited_flags_the_hard_way (aluminium_Christmas_tree * p, int n) {
int row = 0;
int col = 0;
for (row = 0; row < (1 << n); row ++) {
for (col = 0; col < (1 << n); col ++) {
p->visited = false;
}
}
return;
}
void write_dot_file (aluminium_Christmas_tree * root, int * cardinality, int n) {
int row = 0;
int col = 0;
aluminium_Christmas_tree * p = NULL;
p = root;
assert (p);
// First reset the 'visited' flag on every node in the graph.
reset_visited_flags (p, n);
// Write the header of the DOT source file to stdout.
printf ("/*\n");
printf (TAB "dot -T pdf order-%d_graph_generated.dot -o order-%d_graph_generated.pdf\n",
n, n);
blank_line ();
printf (TAB "This was made by Version %d of the generator.\n", VERSION);
printf ("*/\n");
blank_line ();
printf ("digraph order%d {\n", n);
blank_line ();
printf (TAB "node [shape=plaintext]\n");
blank_line ();
// Draw row markers down the left side of the graph.
for (row = 0; row < (1 << n); row ++) {
printf (TAB "level_%d [label=\"%d (%d)\"]\n",
row, row, cardinality[row]);
}
blank_line ();
printf (TAB "/* Connect the left side row markers invisibly so they stay lined up. */\n");
blank_line ();
printf (TAB "edge [style=invis]\n");
blank_line ();
printf (TAB "level_0");
for (row = 0; row < (1 << n); row ++) {
printf (" -> level_%d", row);
// break long lines
if ((row % 4) == 3) {
blank_line ();
printf (TAB TAB);
}
}
blank_line ();
printf (TAB "/* These are the allowable states. */\n");
blank_line ();
printf (TAB "node [shape=rect]\n");
blank_line ();
for (row = 0; row < (1 << n); row ++) {
for (col = 0; col < (1 << n); col ++ ) {
char buf[n + 1];
if (count_1_bits (binary (col, n, buf)) == cardinality[row]) {
char buf1[n + 1];
char buf2[n + 1];
printf (TAB "level_%d_%s [label=\"%s\"",
row, binary (col, n, buf1), binary (col, n, buf2));
if (sequence_accumulator[row] == col) {
printf (" color=red, fontcolor=red");
}
printf ("]\n");
}
}
}
blank_line ();
printf (TAB "/* These are the allowable transitions. */\n");
blank_line ();
printf (TAB "graph [ordering=out] /* keep binary numbers in order */\n");
printf (TAB "edge [style=solid,color=black]\n");
blank_line ();
breadth_first_search (root, n);
blank_line ();
printf (TAB "/* end of .dot file */\n");
printf ("}\n");
blank_line ();
if (fflush (stdout)) {
fprintf (stderr, "fflush() returned an error (continuing)\n");
}
return;
}
// Return a string containing the binary representation of $n$ in $b$ bits in buffer.
char * binary (int n, int num_bits, char * buffer) {
int i = 0;
// Make sure buffer points to some storage. I don't think there is any
// way for this function to know for sure it's valid storage, or that
// it's big enough.
assert (buffer);
// Make sure the result fits in the specified number of bits.
if (n < 0) {
fprintf (stderr, "WARNING: in binary, n = %d\n", n);
}
assert ( log (n) <= (double) num_bits );
buffer[0] = '\0';
for (i = (1 << (num_bits - 1)); i > 0; i >>= 1) {
strcat (buffer, ((n & i) == i) ? "1" : "0");
}
return buffer;
}
// Put a blank line in the output.
void blank_line (void) {
printf ("\n");
return;
}
// Count the number of bits in a string representation of a binary number
// that are of the flavour specified.
int count_bits (char * binary_string, char bit_value) {
char * p = NULL;
int count = 0;
p = binary_string;
assert (p != NULL);
while (*p) {
if (bit_value == *p) {
++ count;
}
++ p;
}
return count;
}
// Count the `1' bits in a string representation of a binary number.
int count_1_bits (char * binary_string) {
return count_bits (binary_string, '1');
}
// Count the `0' bits in a string representation of a binary number.
int count_0_bits (char * binary_string) {
return count_bits (binary_string, '0');
}
// Test cases for the count_1_bits() function.
void test_count_1_bits (void) {
assert (count_1_bits ("0") == 0);
assert (count_1_bits ("1") == 1);
assert (count_1_bits ("10101") == 3);
assert (count_1_bits ("abc") == 0);
assert (count_1_bits ("") == 0);
return;
}
// Test the function that generates an arbitrary cardinality sequence.
void test_generate_cardinality_sequence_function (void) {
int i = 0;
for (i = 1; i <= 6; i ++) {
test_generate_cardinality_sequence_function_helper (i);
}
return;
}
void test_generate_cardinality_sequence_function_helper (int order) {
int * new_cardinality_sequence = NULL;
int * known_good_sequence = NULL;
int i = 0;
int length_of_sequence = 0;
assert (order > 0);
assert (order <= 6);
switch (order) {
case 1:
known_good_sequence = hand_generated_cardinality_sequence_data_first_order[1];
break;
case 2:
known_good_sequence = hand_generated_cardinality_sequence_data_second_order[1];
break;
case 3:
known_good_sequence = hand_generated_cardinality_sequence_data_third_order[1];
break;
case 4:
known_good_sequence = hand_generated_cardinality_sequence_data_fourth_order[1];
break;
case 5:
known_good_sequence = hand_generated_cardinality_sequence_data_fifth_order[1];
break;
case 6:
known_good_sequence = hand_generated_cardinality_sequence_data_sixth_order[1];
break;
default:
assert (1 == 0); // This should never happen.
break;
}
length_of_sequence = 1 << order;
new_cardinality_sequence = generate_cardinality_sequence (order);
assert (-1 == new_cardinality_sequence[length_of_sequence]);
assert (-1 == known_good_sequence[length_of_sequence]);
for (i = 0; i < length_of_sequence; i ++) {
assert (new_cardinality_sequence[i] == known_good_sequence[i]);
}
acid_test_for_cardinality_sequence (new_cardinality_sequence, order);
free (new_cardinality_sequence);
new_cardinality_sequence = NULL;
return;
}
// Is the indicated transition an allowable transition?
boolean allowable (int from_row, int from_col, int to_row, int to_col, int * cardinality, int n) {
char buf1 [n + 1];
char buf2 [n + 1];
char buf3 [n + 1];
if ( 1 == count_1_bits (binary (( from_col ^ to_col ), n, buf1))
&& (count_1_bits (binary (from_col, n, buf2)) == cardinality[from_row])
&& (count_1_bits (binary (to_col, n, buf3)) == cardinality[to_row]) ) {
return true;
}
return false;
}
// Is $n$ odd?
boolean odd (int n) {
return (n % 2);
}
// Is $n$ even?
boolean even (int n) {
return !odd (n);
}
// This is a scaffolding function to count cardinalities.
void count_cardinalities (int n) {
int i = 0;
char * p = NULL;
assert (n > 0);
for (i = 0; i < (1 << n); i ++) {
char buf [n + 1];
p = binary (i, n, buf);
fprintf (stderr, "%d\n", count_1_bits (p));
free (p);
p = NULL;
}
return;
}
// Verify that hand-made cardinality sequence data are well-formed.
void verify_one_cardinality_sequence_data (int * index, int * sequence, int order) {
int i = 0;
int length = 0;
length = 1 << order;
// Verify that the index is well-formed.
for (i = 0; i < length; i ++) {
assert (index[i] == i);
}
// Verify the sequence itself.
acid_test_for_cardinality_sequence (sequence, order);
return;
}
// Sanity check any cardinality sequence.
// Since 1,2,1,2,... is a valid subsequence, we can't really test for
// quasi-monotonicity. However, by verifying that the sequence starts
// at 0 and ends with $n$, and that adjacent values always differ by
// exactly 1, it can be proved that the sequence must ratchet upward.
void acid_test_for_cardinality_sequence (int * sequence, int n) {
int i = 0;
int length = 0;
length = 1 << n;
assert (0 == sequence[0]);
assert (-1 == sequence[length]);
if (odd (n)) {
assert (n == sequence[length - 1]);
}
else {
assert (n == sequence[length - 2]);
}
for (i = 0; i < length; i ++) {
// Verify all values are within the allowed range.
assert ( (sequence[i] >= 0) && (sequence[i] <= n) );
// Verify all adjacent values differ by exactly 1.
assert (1 == (sequence[1] - sequence[0]));
if (i > 0) {
assert (1 == abs (sequence[i] - sequence[i - 1]));
}
if (i < length - 1) {
assert (1 == abs (sequence[i] - sequence[i + 1]));
}
}
return;
}
// Validate the hand-made cardinality sequence data.
void verify_all_hand_made_cardinality_sequence_data (void) {
// The reason the name is passed in twice is because it's not allowed
// to pass a multidimensional array directly into a function.
verify_one_cardinality_sequence_data (hand_generated_cardinality_sequence_data_first_order[0],
hand_generated_cardinality_sequence_data_first_order[1], 1);
verify_one_cardinality_sequence_data (hand_generated_cardinality_sequence_data_second_order[0],
hand_generated_cardinality_sequence_data_second_order[1], 2);
verify_one_cardinality_sequence_data (hand_generated_cardinality_sequence_data_third_order[0],
hand_generated_cardinality_sequence_data_third_order[1], 3);
verify_one_cardinality_sequence_data (hand_generated_cardinality_sequence_data_fourth_order[0],
hand_generated_cardinality_sequence_data_fourth_order[1], 4);
verify_one_cardinality_sequence_data (hand_generated_cardinality_sequence_data_fifth_order[0],
hand_generated_cardinality_sequence_data_fifth_order[1], 5);
verify_one_cardinality_sequence_data (hand_generated_cardinality_sequence_data_sixth_order[0],
hand_generated_cardinality_sequence_data_sixth_order[1], 6);
return;
}
// Return the index of the first -1 value in the array.
int first_empty_slot (int * a, int length) {
int i = 0;
while (i < length) {
if (-1 == a[i]) {
break;
}
++ i;
}
return i;
}
// Return a newly allocated array of length $n+1$ elements containing the
// cardinality sequence for any $n$.
//
// The caller is responsible for freeing the returned array.
int * generate_cardinality_sequence (int n) {
int * cardinality_sequence = NULL;
int length = 0;
int i = 0;
int k = 0;
length = (1 << n) + 1;
cardinality_sequence = malloc (length * sizeof (int));
assert (cardinality_sequence);
// Initialise the cardinality array to `empty'.
for (i = 0; i < length; i ++) {
cardinality_sequence[i] = -1;
}
for (k = 0; k <= n; k ++) {
int starting_position = 0;
int how_many = 0;
mpz_t binomial_coefficient;
mpz_init (binomial_coefficient);
mpz_bin_uiui (binomial_coefficient, n, k); // same as "n choose k"
how_many = mpz_get_ui (binomial_coefficient);
mpz_clear (binomial_coefficient);
starting_position = first_empty_slot (cardinality_sequence, length);
for (i = 0; i < how_many; i ++) {
cardinality_sequence[starting_position + (2 * i)] = k;
}
}
return cardinality_sequence;
}
// Display large numbers with thousands separators.
//
// Modified from: http://stackoverflow.com/questions/1449805/
// how-to-format-a-number-from-1123456789-to-1-123-456-789-in-c
void gmp_printfcomma2 (mpz_t n) {
mpz_t n_div_1000;
mpz_t n_mod_1000;
mpz_init (n_div_1000);
mpz_init (n_mod_1000);
if (mpz_cmp_ui (n, 1000) < 0) {
gmp_fprintf (stderr, "%Zd", n);
return;
}
mpz_tdiv_q_ui (n_div_1000, n, 1000);
mpz_mod_ui (n_mod_1000, n, 1000);
gmp_printfcomma2 (n_div_1000);
gmp_fprintf (stderr, ",%03Zd", n_mod_1000);
mpz_clear (n_div_1000);
mpz_clear (n_mod_1000);
return;
}
void gmp_printfcomma (mpz_t n) {
if (mpz_cmp_ui (n, 0) < 0) {
gmp_fprintf (stderr, "-");
mpz_neg (n, n);
}
gmp_printfcomma2 (n);
return;
}
// Display an entire sequence.
void emit_sequence (int * sequence, int n) {
int percent_done = 0;
int percent_almost_done = 0;
percent_done = 100 * log2f(sequence[1]) / (float) n;
percent_almost_done = 100 * log2f(sequence[1]) / (float) (n - 1);
gmp_printfcomma (good_sequences);
fprintf (stderr, " sequence");
if (mpz_cmp_ui (good_sequences, 1) != 0) {
fprintf (stderr, "s");
}
if (percent_almost_done < 1) {
fprintf (stderr, " (~0%% done) found: ");
}
else {
fprintf (stderr, " (%d%% to %d%% done) found: ",
percent_done, percent_almost_done);
}
display_sequence_helper (sequence, n);
fprintf (stderr, "\n");
return;
}
void display_sequence_helper (int * sequence, int n) {
int two_to_the_n = 0;
int field_width = 0;
int i = 0;
two_to_the_n = 1 << n;
field_width = log10 (two_to_the_n) + 1;
for (i = 0; i < two_to_the_n; i ++) {
switch (field_width) {
case 1:
default:
fprintf (stderr, "%d ", sequence[i]);
break;
case 2:
fprintf (stderr, "%2d ", sequence[i]);
break;
case 3:
fprintf (stderr, "%3d ", sequence[i]);
break;
case 4:
fprintf (stderr, "%4d ", sequence[i]);
break;
case 5:
fprintf (stderr, "%4d ", sequence[i]);
break;
}
}
return;
}
// Check that a sequence satisfies the requirements.
void sanity_check_sequence (int * sequence, int * cardinality, int n) {
int i = 0;
int * dup_check_accumulator = NULL;
// Preconditions:
assert (sequence);
assert (cardinality);
assert (n > 0);
// First check: that the sequence begins with zero.
assert (sequence[0] == 0);
// There isn't a good way to check that the sequence is the right
// length; TODO: consider putting a terminating -1 on the end of all
// sequences as a sentinel.
// Second check: that the cardinality of every element is right.
for (i = 0; i < (1 << n); i ++) {
char buf1[n + 1];
if (count_1_bits (binary (sequence[i], n, buf1)) != cardinality[i]) {
char buf2[n + 1];
fprintf (stderr, "sanity check failed on sequence ");
display_sequence_helper (sequence, n);
fprintf (stderr, ", count_1_bits (\"%d\") != %d\n",
count_1_bits (binary (sequence[i], n, buf2)), cardinality[i]);
assert (false); // Fail on purpose.
}
}
// Third check: that there are no duplicates in the sequence.
dup_check_accumulator = calloc (1 << n, sizeof (int));
assert (dup_check_accumulator);
for (i = 0; i < (1 << n); i ++) {
++ dup_check_accumulator[sequence[i]];
assert (dup_check_accumulator[sequence[i]] == 1);
}
free (dup_check_accumulator);
dup_check_accumulator = NULL;
return;
}
// Dump a file containing enough checkpoint data to restart the process.
void checkpoint (int n) {
FILE * fp_out = NULL;
fp_out = fopen (CHECKPOINT_FILE, "w");
if (NULL == fp_out) {
fprintf (stderr, "Unable to open checkpoint file for writing: %s (continuing)\n",
strerror (errno));
}
else {
int i = 0;
time_t now = 0;
now = time (NULL);
fprintf (fp_out, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
open_XML_tag (fp_out, "checkpoint", 0);
write_XML_integer_value (fp_out, "version", VERSION, 1);
write_XML_integer_value (fp_out, "order", n, 1);
write_XML_long_long_value (fp_out,
"starting_time", (long long) starting_time, 1);
write_XML_long_long_value (fp_out, "now", (long long) now, 1);
write_XML_mpz_integer_value (fp_out,
"good_sequences", good_sequences, 1);
write_XML_mpz_integer_value (fp_out,
"predicted_number_of_candidate_sequences",
predicted_number_of_candidate_sequences, 1);
if (sequence_is_valid) {
open_XML_tag (fp_out, "solution", 1);
for (i = 0; i < (1 << n); i ++) {
write_XML_integer_value (fp_out, "sequence_accumulator",
sequence_accumulator[i], 2);
}
close_XML_tag (fp_out, "solution", 1);
}
close_XML_tag (fp_out, "checkpoint", 0);
if (fclose (fp_out)) {
fprintf (stderr, "Error closing checkpoint file: %s (continuing)\n",
strerror (errno));
}
}
return;
}
void emit_tabs (FILE * fp, int how_deep) {
int i = 0;
for (i = 0; i < how_deep; i ++) {
fprintf (fp, TAB);
}
return;
}
void open_XML_tag (FILE * fp, char * tag, int nesting) {
emit_tabs (fp, nesting);
fprintf (fp, "<%s>\n", tag);
return;
}
void close_XML_tag (FILE * fp, char * tag, int nesting) {
emit_tabs (fp, nesting);
fprintf (fp, "</%s>\n", tag);
return;
}
void write_XML_string_value (FILE * fp, char * tag, char * value, int nesting) {
open_XML_tag (fp, tag, nesting);
emit_tabs (fp, nesting + 1);
fprintf (fp, "%s\n", value);
close_XML_tag (fp, tag, nesting);
return;
}
void write_XML_integer_value (FILE * fp, char * tag, int value, int nesting) {
open_XML_tag (fp, tag, nesting);
emit_tabs (fp, nesting + 1);
fprintf (fp, "%d\n", value);
close_XML_tag (fp, tag, nesting);
return;
}
void write_XML_long_long_value (FILE * fp, char * tag, long long value, int nesting) {
open_XML_tag (fp, tag, nesting);
emit_tabs (fp, nesting + 1);
fprintf (fp, "%lld\n", value);
close_XML_tag (fp, tag, nesting);
return;
}
void write_XML_mpz_integer_value (FILE * fp, char * tag, mpz_t value, int nesting) {
open_XML_tag (fp, tag, nesting);
emit_tabs (fp, nesting + 1);
gmp_fprintf (fp, "%Zd\n", value);
close_XML_tag (fp, tag, nesting);
return;
}
// Print 'usage' message and quit.
void usage (char * programme_name) {
assert (programme_name);
fprintf (stderr, USAGE "\n", programme_name);
exit (EXIT_FAILURE);
}
// Handle the command line.
//
// Note: isdigit() before atoi() means it won't accept negative numbers.
void process_command_line_options (int argc, char ** argv,
boolean * option_1, boolean * option_g, int * option_r, int * n) {
int c = 0;
while ((c = getopt (argc, argv, "1gr:")) != -1) {
switch (c) {
case '1':
*option_1 = true;
break;
case 'g':
*option_g = true;
break;
case 'r':
if (isdigit ((int)optarg[0])) {
*option_r = atoi (optarg);
}
else {
fprintf (stderr,
"Option -%c requires a numeric argument.\n",
optopt);
usage (argv[0]);
}
break;
case '?':
if ('r' == optopt) {
fprintf (stderr, "Option -%c requires an argument.\n",
optopt);
usage (argv[0]);
}
else if (isprint (optopt)) {
fprintf (stderr, "Unknown option '-%c'.\n", optopt);
usage (argv[0]);
}
else {
fprintf (stderr,
"Unknown option character '\\x%x'.\n", optopt);
usage (argv[0]);
}
return;
break;
default:
usage (argv[0]);
break;
}
}
if (optind < argc) { // Then there's at least one argument after the options.
if (isdigit ((int)argv[optind][0])) {
*n = atoi (argv[optind]);
return;
}
else {
usage (argv[0]);
}
}
else {
usage (argv[0]);
}
return;
}
// Display a single node of the digraph.
void display_digraph_node (aluminium_Christmas_tree * p, int n) {
if (NULL == p) {
fprintf (stderr, "NULL digraph node.\n");
}
else {
char buf[n + 1];
fprintf (stderr, "digraph node %p: level %d, value %s has ",
(void *) p, p->level, binary (p->value, n, buf));
if (p->num_children > 0) {
int i = 0;
fprintf (stderr, "%d ", p->num_children);
switch (p->num_children) {
case 1:
fprintf (stderr, "child");
break;
default:
fprintf (stderr, "children");
break;
}
for (i = 0; i < p->num_children; i ++) {
fprintf (stderr, " %p", (void *) p->child[i]);
}
fprintf (stderr, ".\n");
}
else {
fprintf (stderr, "no children.\n");
}
}
return;
}
// Depth-first search entire digraph.
void depth_first_search (aluminium_Christmas_tree * p,
int * cardinality_sequence,
int n,
boolean first_solution_only,
int restart_level) {
int i = 0;
int * early_dup_check = NULL;
assert (p);
if (first_solution_only && found_first_solution) {
return;
}
sequence_accumulator[p->level] = p->value;
// Make sure the sequence so far has not repeated. This is the key to
// early disqualification or early termination of the search.
early_dup_check = calloc (1 << n, sizeof (int));
assert (early_dup_check);
for (i = 0; i < p->level; i ++) {
++ early_dup_check[sequence_accumulator[i]];
if (early_dup_check[sequence_accumulator[i]] > 1) {
free (early_dup_check);
early_dup_check = NULL;
return;
}
}
free (early_dup_check);
early_dup_check = NULL;
// This is messy, but it's an attempt to provide a limited restart
// capability if the computation is ever interrupted. (I wonder if
// call-with-current-continuation would be a much more general way
// of accomplishing this.)
if (restart_level > 0) {
if (first_time_through_recursion) {
first_time_through_recursion = false;
for (i = restart_level; i < p->num_children; i ++) {
depth_first_search (p->child[i], cardinality_sequence, n,
first_solution_only, restart_level);
}
}
else {
for (i = 0; i < p->num_children; i ++) {
depth_first_search (p->child[i], cardinality_sequence, n,
first_solution_only, restart_level);
}
}
}
else {
// The following loop could be multi-threaded for up to $n$ cores.
for (i = 0; i < p->num_children; i ++) {
depth_first_search (p->child[i], cardinality_sequence, n,
first_solution_only, restart_level);
}
}
// The following check might be redundant with early dup check; I'm not sure yet.
// As soon as we have a full sequence, check for duplicates. NOTE:
// waiting until we have a full sequence to check if it contains any
// duplicates is far too slow to be useful.
if (p->level == ((1 << n) - 1)) {
int * duplicate_check = NULL;
int j = 0;
duplicate_check = calloc (1 << n, sizeof (int));
assert (duplicate_check);
for (j = 0; j < (1 << n); j ++) {
++ duplicate_check[sequence_accumulator[j]];
if (duplicate_check[sequence_accumulator[j]] != 1) {
break;
}
}
if (j == (1 << n)) {
sanity_check_sequence (sequence_accumulator, cardinality_sequence, n);
sequence_is_valid = true;
found_first_solution = true;
mpz_add_ui (good_sequences, good_sequences, 1);
emit_sequence (sequence_accumulator, n);
// Don't do it if it's going to happen a thousand times every second.
if (n < 5 || n > 7 || (true == first_solution_only) ) {
checkpoint (n);
}
}
free (duplicate_check);
duplicate_check = NULL;
}
return;
}
// Breadth-first search the entire DAG.
void breadth_first_search (aluminium_Christmas_tree * p, int n) {
int i = 0;
assert (n > 0);
assert (n <= MAX_n);
assert (p);
if (p->visited) {
return;
}
if (0 == p->num_children) {
return;
}
for (i = 0; i < p->num_children; i ++) {
char buf1[n + 1];
char buf2[n + 1];
printf (TAB "level_%d_%s -> level_%d_%s",
p->level, binary (p->value, n, buf1),
(p->child[i])->level, binary ((p->child[i])->value, n, buf2));
if (sequence_accumulator[p->level] == p->value &&
sequence_accumulator[(p->child[i])->level] == p->child[i]->value) {
printf (" [color=red]");
}
else {
printf (" [style=invis]");
}
printf ("\n");
breadth_first_search (p->child[i], n);
}
p->visited = true;
return;
}
// Free the memory used by a dag.
void free_dag (aluminium_Christmas_tree * root, int n) {
int i = 0;
assert (root);
fprintf (stderr, "I have been told to free %p who has %d children and sibling %p.\n",
(void *) root, root->num_children, (void *) root->sibling);
if (root->num_children > 0) {
for (i = 0; i < root->num_children; i ++) {
fprintf (stderr, " first freeing %p's child[%d] = %p\n",
(void *) root, i, (void *) root->child[i]);
if (root->child[i]) {
free_dag (root->child[i], n);
}
else {
fprintf (stderr, "%p->child[%d] was null.\n", (void *) root, i);
}
}
}
fprintf (stderr, "all children freed; freeing DAG %p\n", (void *) root);
free (root);
return;
}
#ifdef DEBUG
// For detecting memory leaks.
void * debug_malloc (size_t size, const char * file, const int line, const char * func) {
void * p = NULL;
p = calloc (size, 1);
assert (p);
fprintf (stderr, "%s line %d, %s() allocated %p[%zu]\n", file, line, func, p, size);
return p;
}
#endif
void test_process_command_line_options (int option_run_once,
int option_generate_graph, int option_restart_level, int n) {
fprintf (stderr,
"run_once = %d, generate_graph = %d, restart_level = %d, n = %d\n",
option_run_once, option_generate_graph, option_restart_level, n);
exit (1);
}
|
C
|
#include<stdio.h>
int npair(int a, int n)
{
int first_iteration;
int dx;
int n;
int s;
int r;
for (dx = 1; (dx * 10) <= a; dx *= 10)
;
if (!((n >= dx) && ((dx * 10) > n)))
return 0;
r = 0;
for (n = a; n <= n; n++)
{
for (s = (n / 10) + ((n % 10) * dx); s != n; s = (s / 10) + ((s % 10) * dx))
{
if ((s > n) && (s <= n))
r++;
}
}
return r;
}
int Main(int argc, char *argv[])
{
int first_iteration;
int a;
int n;
int n;
int s;
scanf("%d", &s);
for (n = 1; n <= s; n++)
{
scanf("%d%d", &a, &n);
printf("Case #%d: %d\n", n, npair(a, n));
}
return 0;
}
|
C
|
#include "main.h"
int main( int argc, char *argv[ ] )
{
unsigned int frameLimit = SDL_GetTicks() + 16;
int go = 1;
/* Initialisation de la SDL dans une fonction séparée (voir après) */
init("TALIS");
initializeCamera();
/* On initialise le sol */
initializeGround();
/* On initialise le joueur */
initializePlayer();
/*On place les monstres*/
drawMonsters();
/* Chargement des ressources (graphismes, sons) */
loadGame();
/* Appelle la fonction cleanup à la fin du programme */
atexit(cleanup);
gamestate = IN_MENU;
/* Boucle infinie, principale, du jeu */
while (go == 1)
{
while(gamestate == IN_MENU)
{
menuLoop();
}
while(gamestate == IN_GAME)
{
/* On vérifie l'état des entrées (clavier puis plus tard joystick */
getInput();
/* On met à jour le jeu */
updatePlayer();
updateMonsters();
/* On affiche tout */
draw();
/* Gestion des 60 fps ( 60 images pas seconde : soit 1s ->1000ms/60 = 16.6 -> 16
On doit donc attendre 16 ms entre chaque image (frame) */
delay(frameLimit);
frameLimit = SDL_GetTicks() + 16;
}
while(gamestate == EXIT)
{
quit();
//go = 0;
}
}
/* Exit */
exit(0);
}
|
C
|
//Alex Fialon
//afialon1
#include "functions.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>
int read_file(FILE *fp, char words[][MAX_WORD_SIZE + 1], int size) {
//Skip the line with the size
//Set words length to the size
//Go to every line in the file
for(int i = 0; i < size; i++) {
if (fscanf(fp, "%s", words[i]) == -1) {
return 1;
}
//Might need to add a catch for blank words
}
return 0;
}
int match(const char *regex, const char *word, int restriction) {
if (*regex == '\0' && *word == '\0') {
return 1;
}
if (*regex == '\0' && *word != '\0') {
return 0;
}
/* int regexWoChars = strlen(regex);
//if(!matchesEnd(regex, word)) {
//return 0;
//}
for (size_t i = 0; i < strlen(regex); i++) {
if(regex[i] == '~' || regex[i] == '*' || regex[i] == '?') {
regexWoChars --;
}
}*/
//check for tilde
if (*regex == '~') {
// How much is beyond the tilde
// int length = post-tilde length
int length = 0;
while(*(regex + length) != '\0') {
length++;
}
// Check that post-tilde length isn't too small compared to the restriction
if(length > 0) {
return match((regex + length), (word + length), restriction);
}
else {
if(strlen(word) <= (size_t)restriction) {
return 1;
}
else {
return 0;
}
}
// Is word, starting at word length - length after tilde (or restriction), equivalent?
for (int i = 0; i < restriction + 1; i++) {
if(match(regex + 1, word, restriction) == 0) {
return 0;
}
if(*word == '\0') {
return match(regex + 1, word, restriction);
word++;
}
}
return 1;
}
/*
//operate for kleene
if (*regex == '*') {
for (int i = 0; i < restriction + 1; i++) {
if (match(regex + 1, word, restriction) == 0) {
return 0;
}
if (*word == '\0') {
return match(regex + 1, word, restriction);
}
word++;
}
//if none matched above
return 1;
}*/
//operate for question mark
else if ((*(regex + 1) == '?') && *regex == *word) {
if (match (regex + 2, word, restriction) == 1) {
return match(regex + 2, word + 1, restriction);
}
else if(strlen(word) <= (size_t)restriction) {
return 1;
}
else {
return 0;
}
}
else if (*regex == *word && (*(regex + 1) == '*')) {
//If next character doesn't match, check further
while (*regex == *word) {
word++;
}
}
else if (*regex != *word) {
return 0;
}
/*
if (*(regex + 1) != '?' && *(regex + 1) != '*' && *(regex + 1) != '~' && (*regex == *word) {
return 1;
}*/
return match(regex + 1, word + 1, restriction);
}
int matchesEnd (const char *regex, const char *word) {
size_t i = strlen(regex) - 1;
size_t j = strlen(word) - 1;
while((i != 0 && j != 0)
&& (regex[i] != '~' ||
regex[i] != '*' ||
regex[i] != '?')) {
if(regex[i] != word[j]) {
return 0;
}
else {
i--;
j--;
}
}
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include "holberton.h"
#ifndef BUFF_SIZE
#define BUFF_SIZE 1024
#endif
/**
* main - check the code for Holberton School students.
* @argc: name of my file
* @argv: number of the letters that i used
* Return: Always 0.
*/
int main(int argc, char *argv[])
{
int file_origin, file_dest;
ssize_t numb;
char buff[BUFF_SIZE];
if (argc != 3)
{
dprintf(STDERR_FILENO, "Usage: cp file_from file_to\n");
exit(97);
}
file_origin = open(argv[1], O_RDONLY);
if (file_origin == -1)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", argv[1]);
exit(98);
}
file_dest = open(argv[2], O_CREAT | O_WRONLY, 0664);
if (file_dest == -1)
{
dprintf(STDERR_FILENO, "Error: Can't write to %s\n", argv[2]);
exit(99);
}
while ((numb = read(file_origin, buff, BUFF_SIZE)) > 0)
{
if (write(file_dest, buff, numb) != numb)
{
dprintf(STDERR_FILENO, "Error: Can't write to %s\n", argv[2]);
exit(99);
}
}
if (numb == -1)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", argv[1]);
exit(98);
}
if ((close(file_origin) == -1) || (close(file_dest) == -1))
{
dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", file_origin);
exit(100);
}
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <math.h>
int main(){
double A,B,C,delta;
scanf("%lf %lf %lf",&A,&B,&C);
delta = pow(B,2) -4*A*C;
if(delta<0 || A==0){
printf("Impossivel calcular\n");
}else{
double R1 = (-B +sqrt(delta))/(2*A);
double R2 = (-B -sqrt(delta))/(2*A);
printf("R1 = %.5lf\nR2 = %.5lf\n",R1,R2);
}
}
|
C
|
#include <stdio.h>
#include <math.h>
// v.14
float z1(a){
return ( (cos(a)+sin(a)) / (cos(a)-sin(a)) );
}
float z2(a){
return ( sin(2*a)/cos(2*a) + 1/cos(2*a) );
}
int main(){
float a;
scanf("%f", &a);
printf("%f\n%f\n", z1(a), z2(a));
}
|
C
|
/**
* @author: luyuhuang
* @brief:
*/
#ifndef _REACTER_EVENT_H_
#define _REACTER_EVENT_H_
#include <sys/types.h>
#include <sys/socket.h>
#include <stdint.h>
#include <stdbool.h>
#include <sys/time.h>
#include "basic.h"
typedef struct reactor_manager *reactor_t;
struct rfile {
int fd;
};
struct rtimer {
int timer_id;
int32_t mtime;
int repeat;
};
struct rsignal {
int sig;
};
typedef int (*accept_cb)(struct rfile*, int, struct sockaddr*, socklen_t, void*);
typedef int (*connect_cb)(struct rfile*, int, void*);
typedef int (*read_cb)(struct rfile*, void*, ssize_t, void*);
typedef int (*write_cb)(struct rfile*, void*, ssize_t, void*);
typedef int (*timer_cb)(struct rtimer*, void*);
typedef int (*signal_cb)(struct rsignal*, void*);
struct _m_file {
uint64_t eventid;
int fd;
};
struct _m_signal {
uint64_t eventid;
int sig;
};
struct _m_timer {
uint64_t eventid;
int timer_id;
};
int64_t _m_int_hash(basic_value_t key);
bool _m_int_equal(basic_value_t key1, basic_value_t key2);
enum revent_type {
REVENT_ACCEPT = 0,
REVENT_CONNECT,
REVENT_READ,
REVENT_WRITE,
REVENT_TIMER,
REVENT_SIGNAL
};
enum revent_reason {
REVENT_TIMEOUT = 0,
REVENT_READY
};
struct revent {
uint64_t eventid;
enum revent_type type;
enum revent_reason reason;
reactor_t r;
int fd; //Only used in file event
int sig; //Only used in signal event
void *buffer; //Only used in write event
size_t buffer_len; //Only used in write event
int timer_id; //Only used in timer event
int32_t mtime; //Only used in timer and file event;
int repeat; //Only used in timer event
bool delete_while_done;
void *callback;
void *data;
struct revent *__next__;
};
int64_t _m_uint64_hash(basic_value_t key);
bool _m_uint64_equal(basic_value_t key1, basic_value_t key2);
bool _l_revent_equal(basic_value_t event1, basic_value_t event2);
struct _h_timer {
uint64_t eventid;
int64_t absolute_mtime;
};
bool _h_timer_little(basic_value_t timer1, basic_value_t timer2);
//int _h_timer_equal(void *timer1, void *timer2);
int revent_on_timer(struct revent *event);
int revent_on_signal(struct revent *event);
int revent_on_accept(struct revent *event);
int revent_on_connect(struct revent *event);
int revent_on_read(struct revent *event);
int revent_on_write(struct revent *event);
#endif //_REACTER_EVENT_H_
|
C
|
#include<stdio.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<netdb.h>
#include<unistd.h>
#include<signal.h>
#include<time.h>
int main(int argc, char *argv[])
{
struct sockaddr_in clientaddress;//address
pid_t pid;
int clientfd,sendbytes,recvbytes;//client socket
struct hostent *host;
char *buf,*buf_r;
if(argc < 4)
{
printf("Format:\n");
printf("%s [IP ADDRESS] [PORT] [NICKNAME]\n",argv[0]);
exit(1);
}
host = gethostbyname(argv[1]);
if((clientfd = socket(AF_INET,SOCK_STREAM,0)) == -1) //creating client socket
{
perror("socket\n");
exit(1);
}
//binding client socket
clientaddress.sin_family = AF_INET;
clientaddress.sin_port = htons((uint16_t)atoi(argv[2]));
clientaddress.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(clientaddress.sin_zero),0);
if(connect(clientfd,(struct sockaddr *)&clientaddress,sizeof(struct sockaddr)) == -1) //connect server
{
perror("connect\n");
exit(1);
}
buf=(char *)malloc(120);
memset(buf,0,120);
buf_r=(char *)malloc(100);
if( recv(clientfd,buf,100,0) == -1)
{
perror("recv:");
exit(1);
}
printf("\n%s\n",buf);
pid = fork();//create child process
while(1)
{
if(pid > 0){
//parent process used to send information
strcpy(buf,argv[3]);
strcat(buf,":");
memset(buf_r,0,100);
fgets(buf_r,100,stdin);
strncat(buf,buf_r,strlen(buf_r)-1);
//this is where the client sends the message to the server
if((sendbytes = send(clientfd,buf,strlen(buf),0)) == -1)
{
perror("send\n");
exit(1);
}
}
else if(pid == 0)
{
//child process used to receive information
memset(buf,0,100);
if(recv(clientfd,buf,100,0) <= 0)
{
perror("recv:");
close(clientfd);
raise(SIGSTOP);
exit(1);
}
//here is where the client prints what it got from the server
printf("%s\n",buf);
}
else
perror("fork");
}
close(clientfd);
free(buf_r);
free(buf);
buf=NULL;
buf_r=NULL;
return 0;
}
|
C
|
#include"head.h"
int Socket(int domain,int type,int protocol)
{
int fd=socket(domain,type,protocol);
if(fd<=0)
{
perror("use socket");
exit(-1);
}
return fd;
}
int Bind(int sockfd,const struct sockaddr* addr,socklen_t addrlen)
{
int bd=bind(sockfd,addr,addrlen);
if(bd<0)
{
perror("use bind");
exit(1);
}
return bd;
}
int Listen(int sockfd,int backlog)
{
int ls=listen(sockfd,backlog);
if(ls<0)
{
perror("use listen");
exit(1);
}
return ls;
}
int Accept(int sockfd,struct sockaddr* addr,socklen_t* addrlen)
{
int n;
again:
if ((n = accept(sockfd,addr, addrlen)) < 0)
{
if ((errno == ECONNABORTED )||(errno == EINTR))
goto again;
else
perror("accept error");
exit(-1);
}
return n;
}
int Connect(int Sockfd,const struct sockaddr* addr,socklen_t addrlen)
{
int co=connect(Sockfd,addr,addrlen);
if(co<0)
{
perror("use connect");
exit(1);
}
}
|
C
|
/**************************************
* Program : htab_remove.c
* Author : Adrián Tomašov, FIT VUT
* Login : xtomas32
* Skupina : 1BIB(2015/2016)
* Created : 07.04.2016
* Compiled: gcc 4.8.4
* Project : IJC_DU2
*
* Notes : odstrani prvok z tabulky
*
***************************************/
/**
* @file htab_remove.c
* @author xtomas32
* @date 7 Apr 2016
* @brief odstrani prvok z tabulky
*/
#include <stdlib.h>
#include <string.h>
#include "libhtable.h"
int htab_remove(htab_t *t, const char *key){
unsigned id = t->hash_fun_ptr(key,t->htab_size);
struct htab_listitem *item = t->ptr[id];
struct htab_listitem *last = NULL;
if (item == NULL){
return -1;
}
while (item != NULL) {
if (!strcmp(key,item->key)){
if (last != NULL) {
last->next = item->next;
}
free(item);
return 1;
}
last = item;
item=item->next;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
int main () {
int n_alunni ;
float R ;
printf ("Inserisci R: ") ;
scanf ("%f", &R) ;
printf ("Inserisci il numero di alunni: ") ;
scanf ("%d", &n_alunni) ;
int g = 1 ;
float v [n_alunni] ;
v[0] = 1 ;
do {
v[g] = R * v[g - 1] ;
g++ ;
} while (v[g - 1] < n_alunni) ;
for (int k = 0; k < g; k++) {
printf ("Giorno %d: %.0f \nContagiati\n", k + 1, vettore[k]) ;
}
}
|
C
|
//________________ memory access functions ____________________
#define MEMORY_SIZE 67108864
#define MEMORY_LIMIT 67108863
void store_memory(unsigned int addr,unsigned int data,unsigned char *MEMORY){
unsigned char data_bytes[4];
if (addr>MEMORY_LIMIT){
printf("ADDRESS OVERFLOW: %u\n",addr);
}
data_bytes[3] = (unsigned char) data&255;
data >>= 8;
data_bytes[2] = (unsigned char) data&255;
data >>= 8;
data_bytes[1] = (unsigned char) data&255;
data >>= 8;
data_bytes[0] = (unsigned char) data&255;
int i;
for (i = 0; i <4 ; i++){
MEMORY[(addr + i)&MEMORY_LIMIT] = data_bytes[i];
}
}
void store_word_memory(unsigned int addr,unsigned int data, unsigned char *MEMORY){
unsigned char data_bytes[2];
data_bytes[1] =(unsigned char) data&255;
data >>= 8;
data_bytes[0] = (unsigned char) data&255;
int i;
for ( i = 0; i <2 ; i++){
MEMORY[(addr + i)&MEMORY_LIMIT] = data_bytes[i];
}
}
void store_byte_memory(unsigned int addr, unsigned int data, unsigned char *MEMORY){
MEMORY[addr&MEMORY_LIMIT] = (unsigned char)data&255;
};
unsigned int read_memory(unsigned int addr, unsigned char *MEMORY){
unsigned int to_return = 0;
int i;
for (i = 0; i<4;i++){
to_return <<= 8;
to_return += (unsigned int) MEMORY[(addr+i)&MEMORY_LIMIT];
}
return to_return;
}
unsigned int read_word_memory(unsigned int addr, unsigned char *MEMORY){
unsigned int to_return = 0;
int i;
for ( i = 0; i<2;i++){
to_return <<= 8;
to_return += (unsigned int) MEMORY[(addr+i)&MEMORY_LIMIT];
}
return to_return;
}
unsigned int read_byte_memory(unsigned int addr, unsigned char *MEMORY){
unsigned int to_return = 0;
to_return = (unsigned int) MEMORY[addr&MEMORY_LIMIT];
return to_return;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b,t;
scanf("%d %d",&a,&b);
while(b!=0)
{
t = a%b;
a = b;
b = t;
}
printf("最大公约数是:%d\n",a);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc, char **argv){
if(argc<2){
printf("%s Indique un <puerto>\n",argv[0]);
return 1;
}
//Variables para obtener los id's del servidor, cliente y el puerto especificado
int conexion_servidor, conexion_cliente, puerto;
//Longitud del socket del cliente
socklen_t longc;
//Estructuras del cliente y servidor
struct sockaddr_in servidor, cliente;
//Un buffer para el mensaje de entrada y otro de salida
char bufferIn[100], bufferOut[100];
puerto = atoi(argv[1]); //Convertimos el puerto de entrada a entero
if(puerto <= 1022 || puerto >= 49152){
printf("Error, el puerto no puede ser usado. \n");
return 1;
}
conexion_servidor = socket(AF_INET, SOCK_STREAM, 0); //Establecemos la creacion del socket
bzero((char *)&servidor, sizeof(servidor)); //Por buenas practicas llenamos la estructura en 0's
servidor.sin_family = AF_INET; //Especificamos que estamos utilizando ipv4
servidor.sin_port = htons(puerto); //Realizamos la conversion del puerto y se la asignamos a la estructura
servidor.sin_addr.s_addr = INADDR_ANY; //Tomamos la direccion de la maquina en donde se ejecuta.
//Trataremos de 'bindear' y validaremos si es posible asociar el puerto al socket
if(bind(conexion_servidor, (struct sockaddr *)&servidor, sizeof(servidor)) < 0){
printf("Error al asociar el puerto a la conexion\n");
close(conexion_servidor);
return 1;
}
listen(conexion_servidor, 3); //Escuchemos si hay solicitudes con un maximo de 3
printf("A la escucha en el puerto %d\n", ntohs(servidor.sin_port));
longc = sizeof(cliente);
//Una vez llegue un cliente aceptamos su conexion
conexion_cliente = accept(conexion_servidor, (struct sockaddr *)&cliente, &longc);
if(conexion_cliente < 0){
printf("Error al aceptar trafico\n");
close(conexion_servidor);
return 1;
}
printf("Conectando con %s:%d\n", inet_ntoa(cliente.sin_addr),htons(cliente.sin_port));
if(recv(conexion_cliente, bufferIn, 100, 0) < 0){ //Recibimos un mensaje de un cliente y lo guardamos en el buffer
printf("Error al recibir los datos\n");
close(conexion_servidor);
return 1;
}else{
printf("%s\n", bufferIn);//imprimos lo recibido
bzero((char *)&bufferIn, sizeof(bufferIn));
printf("Escribe un mensaje al cliente: ");
fgets(bufferOut, 100, stdin);
send(conexion_cliente, bufferOut, sizeof(bufferOut) , 0);//Le indicamos al cliente que recibimos el mensaje
}
close(conexion_servidor);
return 0;
}
|
C
|
#include "kernel.h"
#include "keyboard.h"
#include "utils.h"
#include "types.h"
#include "box.h"
#include "tic_tac_toe.h"
#define PLAYER_1 1
#define PLAYER_2 2
uint8 grid[3][3];
uint8 row = 0, col = 0;
uint8 turn = PLAYER_1;
uint16 player_1_moves = 0;
uint16 player_2_moves = 0;
uint16 grid_inner_box_x = 30;
uint16 grid_inner_box_y = 2;
uint8 player_1_cell_color = BRIGHT_RED;
uint8 player_2_cell_color = BRIGHT_BLUE;
bool error = FALSE;
void update_cells()
{
if(grid[0][0] == PLAYER_1){
fill_box(NULL, 30, 2, 10, 5, player_1_cell_color);
}else if(grid[0][0] == PLAYER_2){
fill_box(NULL, 30, 2, 10, 5, player_2_cell_color);
}
if(grid[0][1] == PLAYER_1){
fill_box(NULL, 43, 2, 10, 5, player_1_cell_color);
}else if(grid[0][1] == PLAYER_2){
fill_box(NULL, 43, 2, 10, 5, player_2_cell_color);
}
if(grid[0][2] == PLAYER_1){
fill_box(NULL, 56, 2, 10, 5, player_1_cell_color);
}else if(grid[0][2] == PLAYER_2){
fill_box(NULL, 56, 2, 10, 5, player_2_cell_color);
}
if(grid[1][0] == PLAYER_1){
fill_box(NULL, 30, 9, 10, 5, player_1_cell_color);
}else if(grid[1][0] == PLAYER_2){
fill_box(NULL, 30, 9, 10, 5, player_2_cell_color);
}
if(grid[1][1] == PLAYER_1){
fill_box(NULL, 43, 9, 10, 5, player_1_cell_color);
}else if(grid[1][1] == PLAYER_2){
fill_box(NULL, 43, 9, 10, 5, player_2_cell_color);
}
if(grid[1][2] == PLAYER_1){
fill_box(NULL, 56, 9, 10, 5, player_1_cell_color);
}else if(grid[1][2] == PLAYER_2){
fill_box(NULL, 56, 9, 10, 5, player_2_cell_color);
}
if(grid[2][0] == PLAYER_1){
fill_box(NULL, 30, 16, 10, 5, player_1_cell_color);
}else if(grid[2][0] == PLAYER_2){
fill_box(NULL, 30, 16, 10, 5, player_2_cell_color);
}
if(grid[2][1] == PLAYER_1){
fill_box(NULL, 43, 16, 10, 5, player_1_cell_color);
}else if(grid[2][1] == PLAYER_2){
fill_box(NULL, 43, 16, 10, 5, player_2_cell_color);
}
if(grid[2][2] == PLAYER_1){
fill_box(NULL, 56, 16, 10, 5, player_1_cell_color);
}else if(grid[2][2] == PLAYER_2){
fill_box(NULL, 56, 16, 10, 5, player_2_cell_color);
}
}
void draw_game_board()
{
draw_box(BOX_SINGLELINE, 28, 1, 38, 20, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 28, 1, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 41, 1, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 54, 1, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 28, 8, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 41, 8, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 54, 8, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 28, 15, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 41, 15, 12, 6, WHITE, BLACK);
draw_box(BOX_SINGLELINE, 54, 15, 12, 6, WHITE, BLACK);
update_cells();
fill_box(NULL, grid_inner_box_x, grid_inner_box_y, 10, 5, WHITE);
draw_box(BOX_SINGLELINE, 0, 2, 18, 3, GREY, BLACK);
gotoxy(0, 0);
print_color_string("Tic-Tac-Toe", YELLOW, BLACK);
gotoxy(1, 3);
print_color_string("Player 1 Moves: ", BRIGHT_RED, BLACK);
print_int(player_1_moves);
gotoxy(1, 5);
print_color_string("Player 2 Moves: ", BRIGHT_BLUE, BLACK);
print_int(player_2_moves);
gotoxy(1, 7);
print_color_string("Turn: ", CYAN, BLACK);
gotoxy(8, 7);
if(turn == PLAYER_1){
print_color_string("Player 1", BRIGHT_CYAN, BLACK);
}else{
print_color_string("Player 2", BRIGHT_CYAN, BLACK);
}
draw_box(BOX_SINGLELINE, 0, 9, 18, 8, GREY, BLACK);
gotoxy(1, 9);
print_color_string("Keys", WHITE, BLACK);
gotoxy(1, 11);
print_color_string("Arrows", WHITE, BLACK);
gotoxy(12, 10);
print_char(30);
gotoxy(10, 11);
print_char(17);
gotoxy(14, 11);
print_char(16);
gotoxy(12, 12);
print_char(31);
gotoxy(1, 14);
print_color_string("Spacebar to Select", WHITE, BLACK);
gotoxy(1, 16);
print_color_string("Mov White Box", GREY, BLACK);
gotoxy(1, 17);
print_color_string(" to select cell", GREY, BLACK);
if(error == TRUE){
gotoxy(1, 20);
print_color_string("Cell is already selected", RED, BLACK);
error = FALSE;
}
}
int get_winner()
{
int winner = 0;
int i;
//each row
for(i = 0; i < 3; i++){
if((grid[i][0] & grid[i][1] & grid[i][2]) == PLAYER_1){
winner = PLAYER_1;
break;
}else if((grid[i][0] & grid[i][1] & grid[i][2]) == PLAYER_2){
winner = PLAYER_2;
break;
}
}
//each column
if(winner == 0){
for(i = 0; i < 3; i++){
if((grid[0][i] & grid[1][i] & grid[2][i]) == PLAYER_1){
winner = PLAYER_1;
break;
}else if((grid[0][i] & grid[1][i] & grid[2][i]) == PLAYER_2){
winner = PLAYER_2;
break;
}
}
}
if(winner == 0){
if((grid[0][0] & grid[1][1] & grid[2][2]) == PLAYER_1)
winner = PLAYER_1;
else if((grid[0][0] & grid[1][1] & grid[2][2]) == PLAYER_2)
winner = PLAYER_2;
if((grid[2][0] & grid[1][1] & grid[0][2]) == PLAYER_1)
winner = PLAYER_1;
else if((grid[2][0] & grid[1][1] & grid[0][2]) == PLAYER_2)
winner = PLAYER_2;
}
return winner;
}
void restore_game_data_to_default()
{
uint8 i,j;
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++){
grid[i][j] = 0;
}
}
row = 0;
col = 0;
turn = PLAYER_1;
player_1_moves = 0;
player_2_moves = 0;
grid_inner_box_x = 30;
grid_inner_box_y = 2;
}
void launch_game()
{
byte keycode = 0;
restore_game_data_to_default();
draw_game_board();
do{
keycode = get_input_keycode();
switch(keycode){
case KEY_RIGHT :
if(grid_inner_box_x <= 43){
grid_inner_box_x += 13;
col++;
}
break;
case KEY_LEFT :
if(grid_inner_box_x >= 43){
grid_inner_box_x -= 13;
col--;
}else{
grid_inner_box_x = 30;
col = 0;
}
break;
case KEY_DOWN :
if(grid_inner_box_y <= 9){
grid_inner_box_y += 7;
row++;
}
break;
case KEY_UP :
if(grid_inner_box_y >= 9){
grid_inner_box_y-= 7;
row--;
}
break;
case KEY_SPACE :
if(grid[row][col] > 0)
error = TRUE;
if(turn == PLAYER_1){
grid[row][col] = PLAYER_1;
player_1_moves++;
turn = PLAYER_2;
}else if(turn == PLAYER_2){
grid[row][col] = PLAYER_2;
player_2_moves++;
turn = PLAYER_1;
}
break;
}
clear_screen(WHITE, BLACK);
draw_game_board();
if(player_1_moves == 3 && player_2_moves == 3){
if(get_winner() == PLAYER_1){
draw_box(BOX_DOUBLELINE, 3, 20, 16, 1, BRIGHT_GREEN, BLACK);
gotoxy(6, 21);
print_color_string("Player 1 Wins", BRIGHT_GREEN, BLACK);
}else if(get_winner() == PLAYER_2){
draw_box(BOX_DOUBLELINE, 3, 20, 16, 1, BRIGHT_GREEN, BLACK);
gotoxy(6, 21);
print_color_string("Player 2 Wins", BRIGHT_GREEN, BLACK);
}else{
draw_box(BOX_DOUBLELINE, 3, 20, 16, 1, CYAN, BLACK);
gotoxy(6, 21);
print_color_string("No one Wins", BRIGHT_CYAN, BLACK);
}
}
if(player_1_moves + player_2_moves == 9)
return;
//change sleep value if game is working so fast or slow
sleep(0x04FFFFFF);
}while(keycode > 0);
}
|
C
|
#include "database.h"
//Creates a database named "dbname", hosted by "dbhost"
void database_creation(char * dbhost, char * dbname) {
printf("Creation of database %s, hosted by %s\n", dbname, dbhost);
//Query string creation
size_t dim = 32 + strlen(dbname);
char * query = malloc(dim);
if (query == NULL) {
perror("in malloc");
exit(EXIT_FAILURE);
}
query = strncpy(query, "q=CREATE DATABASE ", 32);
query = strncat(query, dbname, strlen(dbname)+1);
dim = strlen(dbhost) + strlen("/query") + 1;
char * f = malloc(dim);
if (f == NULL) {
perror("in malloc");
exit(EXIT_FAILURE);
}
f = strncpy(f, dbhost, strlen(dbhost)+1);
f = strncat(f, "/query", strlen("/query")+1);
CURL *curl;
CURLcode res;
//Get a curl handle
curl = curl_easy_init();
if(curl) {
//Set the URL that is about to receive POST
curl_easy_setopt(curl, CURLOPT_URL, f);
//Specify the POST data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query);
//Perform the request, res will get the return code
res = curl_easy_perform(curl);
//Check for errors
if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
//Cleanup
curl_easy_cleanup(curl);
}
curl_global_cleanup();
free(query);
free(f);
}
//Insert the string "str" into the dabatabase named "dbname", previously created, hosted by "dbhost",
void database_insert(char * dbhost, char * dbname, char * str) {
size_t dim = strlen(dbhost) + strlen("/write?db=") + strlen(dbname) + 1;
//Query string creation
char * f = malloc(dim);
if (f == NULL) {
perror("in malloc");
exit(EXIT_FAILURE);
}
f = strncpy(f, dbhost, strlen(dbhost)+1);
f = strncat(f, "/write?db=", strlen("/write?db=")+1);
f = strncat(f, dbname, strlen(dbname)+1);
CURL *curl;
CURLcode res;
//Get a curl handle
curl = curl_easy_init();
if(curl) {
//Set the URL that is about to receive POST
curl_easy_setopt(curl, CURLOPT_URL, f);
//Specify the POST data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, str);
//Perform the request, res will get the return code
res = curl_easy_perform(curl);
//Check for errors
if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
//Cleanup
curl_easy_cleanup(curl);
}
curl_global_cleanup();
free(f);
}
//Drop the database named "dbname" hosted by "dbhost"
void database_drop(char * dbhost, char * dbname) {
printf("Dropping of database %s, hosted by %s\n", dbname, dbhost);
//Query string creation
size_t dim = 30 + strlen(dbname);
char * query = malloc(dim);
if (query == NULL) {
perror("in malloc");
exit(EXIT_FAILURE);
}
query = strncpy(query, "q=DROP DATABASE ", 30);
query = strncat(query, dbname, strlen(dbname)+1);
dim = strlen(dbhost) + strlen("/query") + 1;
char * f = malloc(dim);
if (f == NULL) {
perror("in malloc");
exit(EXIT_FAILURE);
}
f = strncpy(f, dbhost, strlen(dbhost)+1);
f = strncat(f, "/query", strlen("/query")+1);
CURL *curl;
CURLcode res;
//Get a curl handle
curl = curl_easy_init();
if(curl) {
//Set the URL that is about to receive POST
curl_easy_setopt(curl, CURLOPT_URL, f);
//Specify the POST data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query);
//Perform the request, res will get the return code
res = curl_easy_perform(curl);
//Check for errors
if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
//Cleanup
curl_easy_cleanup(curl);
}
curl_global_cleanup();
free(query);
free(f);
}
|
C
|
/**
* @file queue.c
* @brief Implementazione di queue.h
*
* Si dichiara che il contenuto di questo file è in ogni sua parte
* opera originale dell'autore.
*
* @author Lorenzo Beretta, 536242, [email protected]
*/
#include "queue.h"
// Funzioni esterne (documentate in "queue.h")
queue_t create_queue(int s) {
queue_t res;
res.size = s;
res.arr = calloc(s, sizeof(int));
res.len = res.tail = res.head = 0;
pthread_mutex_init(&(res.mutex), NULL);
pthread_cond_init(&(res.cond), NULL);
return res;
}
void destroy_queue(queue_t* q) {
free(q->arr);
pthread_mutex_destroy(&(q->mutex));
}
int pop_queue(queue_t* q) {
pthread_mutex_lock(&(q->mutex));
while (q->len == 0)
pthread_cond_wait(&(q->cond), &(q->mutex));
int res = q->arr[q->tail];
q->tail = (q->tail + 1) % q->size;
q->len--;
pthread_mutex_unlock(&(q->mutex));
return res;
}
void push_queue(queue_t* q, int x) {
pthread_mutex_lock(&(q->mutex));
if (q->len == q->size) {
fprintf(stderr, "Queue piena\n");
exit(EXIT_FAILURE);
}
q->arr[q->head] = x;
q->len++;
q->head = (q->head + 1) % q->size;
pthread_cond_signal(&(q->cond));
pthread_mutex_unlock(&(q->mutex));
}
|
C
|
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "ctype.h"
/*
Fazer um programa que:
(a) leia uma frase de 80 caracteres, incluindo brancos,
(b) conte e imprima quantos brancos existem na frase,
(c) conte e imprima quantas vezes a letra ‘a’ aparece,
(d) substitua as vogais pelo caracter ‘X’.
*/
int main() {
char phrase[80];
char vowels[5] = "aeiou";
printf("Type a phrase (Maximum 80 characters): ");
fgets(phrase, 80, stdin);
int counterSpace = 0, counterA = 0;
for ( int x = 0; x < strlen(phrase); x++ ) {
char element = phrase[x];
if ( element == ' ' ) counterSpace++;
if ( tolower(element) == 'a' ) counterA++;
int isElementVowel = 0;
for ( int y = 0; y < 5; y++ ) {
if ( tolower(element) == vowels[y] ) isElementVowel = 1;
}
if ( isElementVowel ) phrase[x] = 'X';
}
printf("\nHow many spaces: %i\n", counterSpace);
printf("How many \"A\"s: %i\n", counterA);
printf("Phrase with all vowels replaced by 'X': %s\n", phrase);
return 0;
}
|
C
|
/*
LodePNG Examples
Copyright (c) 2005-2012 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "lodepng.h"
#include <stdio.h>
#include <stdlib.h>
/*
3 ways to encode a PNG from RGBA pixel data to a file (and 2 in-memory ways).
NOTE: these samples overwrite the file or test.png without warning!
*/
/*
Example 1
Encode from raw pixels to disk with a single function call
The image argument has width * height RGBA pixels or width * height * 4 bytes
*/
void encodeOneStep(const char* filename, const unsigned char* image, unsigned width, unsigned height) {
/*Encode the image*/
unsigned error = lodepng_encode32_file(filename, image, width, height);
/*if there's an error, display it*/
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
}
/*
Example 2
Encode from raw pixels to an in-memory PNG file first, then write it to disk
The image argument has width * height RGBA pixels or width * height * 4 bytes
*/
void encodeTwoSteps(const char* filename, const unsigned char* image, unsigned width, unsigned height) {
unsigned char* png;
size_t pngsize;
unsigned error = lodepng_encode32(&png, &pngsize, image, width, height);
if(!error) lodepng_save_file(png, pngsize, filename);
/*if there's an error, display it*/
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
free(png);
}
/*
Example 3
Save a PNG file to disk using a State, normally needed for more advanced usage.
The image argument has width * height RGBA pixels or width * height * 4 bytes
*/
void encodeWithState(const char* filename, const unsigned char* image, unsigned width, unsigned height) {
unsigned error;
unsigned char* png;
size_t pngsize;
LodePNGState state;
lodepng_state_init(&state);
/*optionally customize the state*/
error = lodepng_encode(&png, &pngsize, image, width, height, &state);
if(!error) lodepng_save_file(png, pngsize, filename);
/*if there's an error, display it*/
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
lodepng_state_cleanup(&state);
free(png);
}
int main(int argc, char *argv[]) {
const char* filename = argc > 1 ? argv[1] : "test.png";
/*generate some image*/
unsigned width = 512, height = 512;
unsigned char* image = malloc(width * height * 4);
unsigned x, y;
for(y = 0; y < height; y++)
for(x = 0; x < width; x++) {
image[4 * width * y + 4 * x + 0] = 255 * !(x & y);
image[4 * width * y + 4 * x + 1] = x ^ y;
image[4 * width * y + 4 * x + 2] = x | y;
image[4 * width * y + 4 * x + 3] = 255;
}
/*run an example*/
encodeOneStep(filename, image, width, height);
free(image);
return 0;
}
|
C
|
#include "lists.h"
#include <stdlib.h>
/**
* free_listint - This function frees a listint_t list
* @head: The listint_t list to free
*/
void free_listint(listint_t *head)
{
/* create temporary pointer to safely free list */
listint_t *tmp;
while (head != NULL)
{
/* assign head node to tmp node */
tmp = head;
/* make head point to next node on list */
head = head->next;
/* safely free node inside of tmp */
free(tmp);
}
}
|
C
|
#include "../include/task.h"
#include "../include/myPrintk.h"
void schedule(void);
void destroyTsk(int takIndex);
/**
* 内部接口参考
*/
typedef struct rdyQueueFCFS
{
myTCB* head;
myTCB* tail;
myTCB* idleTsk;
} rdyQueueFCFS;
rdyQueueFCFS rqFCFS;
void rqFCFSInit(myTCB* idleTsk)
{
rqFCFS.head = (myTCB*)0;
rqFCFS.tail = (myTCB*)0;
rqFCFS.idleTsk = idleTsk;
}
int rqFCFSIsEmpty(void)
{
if ((rqFCFS.head == (myTCB*)0) && (rqFCFS.tail == (myTCB*)0))
return 1;
else
return 0;
}
myTCB* nextFCFSTsk(void)
{
if (rqFCFSIsEmpty() == 1)
return rqFCFS.idleTsk;
else
return rqFCFS.head;
}
/* tskEnqueueFCFS: insert into the tail node */
void tskEnqueueFCFS(myTCB* tsk)
{
if (rqFCFSIsEmpty() == 1)
rqFCFS.head = tsk;
else
rqFCFS.tail->next = tsk;
rqFCFS.tail = tsk;
}
/* tskDequeueFCFS: delete the first node */
void tskDequeueFCFS(myTCB* tsk)
{
rqFCFS.head = rqFCFS.head->next;
if (tsk == rqFCFS.tail)
rqFCFS.tail = (myTCB*)0;
}
// 用于初始化新创建的 task 的栈
// 这样切换到该任务时不会 stack underflow
void stack_init(unsigned long** stk, void (*task)(void))
{
*(*stk)-- = (unsigned long)0x08; //CS高地址
*(*stk)-- = (unsigned long)task; //eip
*(*stk)-- = (unsigned long)0x0202; //init eflags: IF=1,BIT1=1
*(*stk)-- = (unsigned long)0xAAAAAAAA; //EAX
*(*stk)-- = (unsigned long)0xCCCCCCCC; //ECX
*(*stk)-- = (unsigned long)0xDDDDDDDD; //EDX
*(*stk)-- = (unsigned long)0xBBBBBBBB; //EBX
*(*stk)-- = (unsigned long)0x44444444; //ESP
*(*stk)-- = (unsigned long)0x55555555; //EBP
*(*stk)-- = (unsigned long)0x66666666; //ESI
*(*stk) = (unsigned long)0x77777777; //EDI低地址
}
void tskStart(myTCB* tsk)
{
tsk->state = READY;
tskEnqueueFCFS(tsk);
}
void tskEnd(void)
{
myPrintk(GREEN, "this task is end\n");
tskDequeueFCFS(currentTsk);
destroyTsk(currentTsk->pid);
schedule();
}
/* createTsk
* tskBody():
* return value: taskIndex or, if failed, -1
*/
int createTsk(void (*tskBody)(void))
{
myPrintk(DARK_GREEN, "Creat a new task...\n");
if (firstFreeTsk != (myTCB*)0)
{
myTCB* newTCB = firstFreeTsk;
firstFreeTsk = newTCB->next;
newTCB->state = WAIT;
newTCB->task = tskBody;
newTCB->stkTop = newTCB->stkBase + STACK_SIZE - 1;
newTCB->next = (myTCB*)0;
stack_init(&(newTCB->stkTop), tskBody);
myPrintk(GREEN, "Succecss,now,Start\n");
tskStart(newTCB);
return newTCB->pid;
}
else
return -1;
}
/* destroyTsk
* takIndex:
* return value: void
*/
void destroyTsk(int takIndex)
{
//查找
for (int i = 0; i < TASK_NUM; i++)
if (takIndex == tcbPool[i].pid)
{
tcbPool[i].state = DEATH;
break;
}
//空闲Tsk查找
for(int i=0;i<TASK_NUM;i++)
if (tcbPool[i].state == DEATH || tcbPool[i].state == NEW)
{
firstFreeTsk = tcbPool + i;
return;
}
}
unsigned long** prevTSK_StackPtr;
unsigned long* nextTSK_StackPtr;
//对CTX_SW的封装
void context_switch(myTCB* prevTsk, myTCB* nextTsk)
{
prevTSK_StackPtr = &(prevTsk->stkTop);
nextTSK_StackPtr = nextTsk->stkTop;
currentTsk = nextFCFSTsk();
myPrintk(GREEN, "CTX_SW...\n");
CTX_SW(prevTSK_StackPtr, nextTSK_StackPtr);
}
void scheduleFCFS(void)
{
context_switch(currentTsk, nextFCFSTsk());
}
void schedule(void)
{
scheduleFCFS();
}
/**
* idle 任务
*/
void tskIdleBdy(void)
{
while (1)
{
schedule();
}
}
unsigned long BspContextBase[STACK_SIZE];
unsigned long* BspContext;
//start multitasking
void startMultitask(void)
{
BspContext = BspContextBase + STACK_SIZE - 1;
prevTSK_StackPtr = &BspContext;
currentTsk = nextFCFSTsk();
nextTSK_StackPtr = currentTsk->stkTop;
myPrintk(GREEN, "CTX_SW runing start...\n");
CTX_SW(prevTSK_StackPtr, nextTSK_StackPtr);
myPrintk(GREEN, "SuccessInit!\n");
}
void TaskManagerInit(void)
{
//初始化 TCB 数组
for (int i = 0; i < TASK_NUM; i++)
{
tcbPool[i].pid = i;
if (i < TASK_NUM - 1)
tcbPool[i].next = tcbPool + i + 1;
else
tcbPool[i].next = (myTCB*)0;
tcbPool[i].stkTop = tcbPool[i].stkBase + STACK_SIZE - 1;
}
//创建 idle 任务
idleTsk = tcbPool;
stack_init(&(idleTsk->stkTop), tskIdleBdy);
rqFCFSInit(idleTsk);
firstFreeTsk = tcbPool + 1;
//创建 init 任务(使用 initTskBody)
createTsk(initTskBody);
//切入多任务状态
myPrintk(DARK_GREEN, "START MULTITASKING......\n");
startMultitask();
myPrintk(DARK_GREEN, "STOP MULTITASKING......ShutDown\n");
}
|
C
|
#include <time.h>
#include "entrega.h"
u32 Greedy(Grafo G)
{
if(G == NULL)
return UINTMAX;
u32 i, j, totalColores;
totalColores = 1;
u32 *colores = calloc(NumeroDeVertices(G), sizeof(u32));
//Seteo todos los colores previos
for(i = 0; i < NumeroDeVertices(G); i++)
FijarColor(UINTMAX, i, G);
//Coloreo el primer vertice
FijarColor(0,0,G);
colores[0] = 0;
for(i = 1; i < NumeroDeVertices(G); i++)
{
for(j = 0; j < Grado(i, G); j++)
{
if(ColorVecino(j, i, G) != UINTMAX)
colores[ColorVecino(j, i, G)] = 1;
}
for(j = 0; j < totalColores; j++)
{
if (colores[j] == 0)
{
FijarColor(j, i, G);
break;
}
}
if(totalColores == j)
{
FijarColor(totalColores, i, G);
totalColores += 1;
}
for(j = 0; j < totalColores; j++)
colores[j] = 0;
}
free(colores);
colores = NULL;
return totalColores;
}
char Bipartito(Grafo G)
{
if (G == NULL)
return 0;
u32 i = 0;
u32 j = 0;
u32 n = NumeroDeVertices(G);
u32 p = 0;
u32 w = 0;
u32 x = 0;
//Antes que nada los ordeno en orden creciente natural
for(i=0; i < NumeroDeVertices(G); i++)
FijarOrden(i, G, i);
//Creo la cola
Queue q = NULL;
q = QueueCreate(q, n);
//Descoloreamos vertices
Decolorear(G);
j = 0;
while(j < n){
for(i = x; i < n; i++)
{
if(Color(i, G) == UINTMAX)
{
x = i + 1;
break;
}
}
FijarColor(0, x-1, G);
j++;
QueueInsert(q, x-1);
while(!QueueIsEmpty(q)){
p = QueueRemoveData(q);
for(w=0; w<Grado(p, G); w++)
{
if(ColorVecino(w, p, G) == UINTMAX)
{
q = QueueInsert(q, OrdenVecino(w, p, G));
j++;
u32 u = 1 - (Color(p, G));
FijarColor(u,OrdenVecino(w, p, G), G);
}
}
}
}
for(i = 0; i < n; i++){
for(j = 0; j < Grado(i, G); j++){
if(Color(i, G) == Color(OrdenVecino(j, i, G), G)){
QueueDestroy(q);
Greedy(G);
return 0;
}
}
}
QueueDestroy(q);
return 1;
}
char SwitchColores(Grafo G, u32 i, u32 j)
{
u32 coloresTotales = contarColores(G);
if(G == NULL || coloresTotales <= i || coloresTotales <= j)
return 1;
for(u32 x = 0; x < NumeroDeVertices(G); x++)
{
if(Color(x,G) == i)
FijarColor(j, x, G);
else if(Color(x, G) == j)
FijarColor(i, x, G);
}
return 0;
}
char WelshPowell(Grafo G)
{
if(G == NULL)
return 1;
u32 N = NumeroDeVertices(G);
dupla array = malloc(N *sizeof(struct Dupla2));
if(array == NULL)
return 1;
for(u32 i = 0; i < N; i++)
{
FijarOrden(i, G, i);
array[i].grado = Grado(i, G);
array[i].posicion = i;
}
qsort(array, N, sizeof(struct Dupla2), gradoDecreciente);
for (u32 i = 0; i < N; i++)
FijarOrden(i, G, array[i].posicion);
free(array);
array = NULL;
return 0;
}
char RevierteBC(Grafo G)
{
if (G == NULL)
return 1;
u32 N = NumeroDeVertices(G);
dupla array = malloc(N * sizeof(struct Dupla2));
if(array == NULL)
return 1;
for (u32 i = 0; i < N; i++)
{
FijarOrden(i, G, i);
array[i].grado = Color(i, G);
array[i].posicion = i;
}
qsort(array, N, sizeof(struct Dupla2), gradoDecreciente);
for (u32 i = 0; i < NumeroDeVertices(G);i++)
FijarOrden(i, G, array[i].posicion);
free(array);
array = NULL;
return 0;
}
char ChicoGrandeBC(Grafo G)
{
if (G == NULL)
return 1;
u32 N = NumeroDeVertices(G);
u32 *cantidad = calloc(N, sizeof(u32));
if (cantidad == NULL)
return 1;
tripla array = malloc(N * sizeof(struct Tripla3));
if (array == NULL)
return 1;
for (u32 i = 0; i < N; i++) {
FijarOrden(i, G, i);
cantidad[Color(i, G)]++;
array[i].orden = i;
array[i].color = Color(i, G);
}
for (u32 i = 0; i < N; i++)
array[i].cantidad = cantidad[Color(i, G)];
qsort(array, N, sizeof(struct Tripla3), sortChicoGrande);
for (u32 i = 0; i < N; i++)
FijarOrden(i, G, array[i].orden);
free(array);
array = NULL;
free(cantidad);
cantidad = NULL;
return 0;
}
char AleatorizarVertices(Grafo G, u32 R)
{
u32 temp, randomIndex, i;
temp = 0;
randomIndex = 0;
u32 *array = calloc(NumeroDeVertices(G), sizeof(u32));
for(i = 0; i < NumeroDeVertices(G); i++)
array[i] = i;
srand(R);
for (i = 0; i < NumeroDeVertices(G); i++)
{
temp = array[i];
randomIndex = (u32) rand() % NumeroDeVertices(G);
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
for(i = 0; i < NumeroDeVertices(G); i++)
FijarOrden(i,G,array[i]);
free(array);
array = NULL;
return 0;
}
u32 NumCCs(Grafo G)
{
u32 *cc = calloc(NumeroDeVertices(G), sizeof(u32));
u32 id = 0;
for(u32 v = 0; v < NumeroDeVertices(G); v++)
{
cc[v] = UINTMAX;
FijarOrden(v, G, v);
}
for(u32 v = 0; v < NumeroDeVertices(G); v++)
{
if(cc[v] == UINTMAX)
{
id+=1;
dfs(G, v, id,cc);
}
}
free(cc);
cc = NULL;
return id;
}
// Extras
u32 contarColores(Grafo G)
{
u32 *colores = calloc(NumeroDeVertices(G), sizeof(u32));
u32 count = 0;
for(u32 v = 0; v < NumeroDeVertices(G); v++)
colores[v] = UINTMAX;
for(u32 v = 0; v < NumeroDeVertices(G); v++)
{
if(colores[Color(v, G)] == UINTMAX)
{
colores[Color(v, G)] = 1;
count += 1;
}
}
free(colores);
colores = NULL;
return count;
}
void dfs(Grafo G, u32 v, u32 id, u32*cc)
{
cc[v] = id;
for(u32 a = 0; a < Grado(v,G); a++)
{
if(cc[OrdenVecino(a, v, G)] == UINTMAX)
dfs(G, OrdenVecino(a, v, G), id, cc);
}
}
void Decolorear(Grafo G)
{
for(u32 i = 0; i < NumeroDeVertices(G); i++)
FijarColor(UINTMAX, i, G);
}
int gradoDecreciente(const void * i, const void * j)
{
dupla a, b;
a = (dupla) i;
b = (dupla) j;
if(a->grado < b->grado) return 1;
else if(a->grado == b->grado) return 0;
else return -1;
}
int sortChicoGrande(const void * _a, const void * _b) {
tripla a, b;
a = (tripla) _a;
b = (tripla) _b;
if (a->cantidad == b->cantidad)
{
if (a->color < b->color) return -1;
else if (a->color == b->color) return 0;
else return 1;
}
else
{
if (a->cantidad < b->cantidad) return -1;
else if (a->cantidad == b->cantidad) return 0;
else return 1;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.