language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * Tamir Moshiashvili * 316131259 * 89-231-03 * EX3 */ #include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <memory.h> #define SHM_SIZE 4096 // strings #define FIFO "fifo_clientTOserver" #define GAME_OVER_MSG "GAME OVER\n" #define BLACK_WINNER "Winning player: Black\n" #define WHITE_WINNER "Winning player: White\n" #define TIE "No winning player\n" static void createSharedMemory(int *shmid, char **shmaddr); static int createFifo(int *fd); static int handlePlayers(int fd, pid_t *pid1, pid_t *pid2, char *shmaddr); static void deleteSharedMemory(char *shmaddr, int shmid); /** * write message by perror and exit the program. * @param errMsg error message. */ static void exitError(char *errMsg) { perror(errMsg); exit(EXIT_FAILURE); } /** * delete shared memory and exit the program. * @param shmaddr address of shared memory. * @param shmid shared memory id. */ static void exitAndDeleteMemory(char *shmaddr, int shmid) { deleteSharedMemory(shmaddr, shmid); exit(EXIT_FAILURE); } int main(int argc, char **argv) { int fd; int shmid; char *shmaddr = NULL; char *msg = NULL; pid_t pid1, pid2; unsigned int timeToSleep = 1; // start of game createSharedMemory(&shmid, &shmaddr); if (createFifo(&fd) < 0) { exitAndDeleteMemory(shmaddr, shmid); } if (handlePlayers(fd, &pid1, &pid2, shmaddr) < 0) { exitAndDeleteMemory(shmaddr, shmid); } // wait for end of game while (*shmaddr != 'e') { sleep(timeToSleep); timeToSleep = (timeToSleep + 1) % 5; } // analyze who is the winner if (write(1, GAME_OVER_MSG, strlen(GAME_OVER_MSG)) < 0) { perror("write failed"); } switch (*(shmaddr + 1)) { case 'b': msg = BLACK_WINNER; break; case 'w': msg = WHITE_WINNER; break; default: msg = TIE; } if (write(1, msg, strlen(msg)) < 0) { perror("write failed"); } // delete shared memory deleteSharedMemory(shmaddr, shmid); exit(EXIT_SUCCESS); } /** * create the shared memory. * @param shmid address of int. * @param shmaddr address of shared-memory-address. */ static void createSharedMemory(int *shmid, char **shmaddr) { key_t key; // create key if ((key = ftok("ex31.c", 'k')) == (key_t) -1) { exitError("ftok failed"); } // create memory if ((*shmid = shmget(key, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666)) == -1) { exitError("shmget failed"); } // attach if ((*shmaddr = shmat(*shmid, NULL, SHM_RDONLY)) == (char *) -1) { // delete shared memory if (shmctl(*shmid, IPC_RMID, NULL) == -1) { exitError("shmctl failed"); } exitError("shmat failed"); } } /** * write by perror and return value. * @param errMsg error message. * @return -1. */ static int perror_return(char *errMsg) { perror(errMsg); return -1; } /** * create and open fifo. * @param fd address of fd. * @return 0 on success, -1 otherwise. */ static int createFifo(int *fd) { // create fifo if (mkfifo(FIFO, 0666) == -1) { return perror_return("mkfifo failed"); } // open fifo if ((*fd = open(FIFO, O_RDONLY)) < 0) { return perror_return("open-fifo failed"); } return 0; } /** * read line from fd to buffer. * @param buffer buffer to contain the string. * @param fd file descriptor. * @return 0 on success, -1 otherwise. */ static int readLine(char buffer[], int fd) { char c[2]; c[1] = '\0'; do { if (read(fd, c, 1) == -1) { return perror_return("read failed"); } strcat(buffer, c); } while (c[0] != '\0'); return 0; } /** * read string from fifo which will be pid. * @param fd file descriptor of fifo. * @param pid address of pid. * @return 0 on success, -1 otherwise. */ static int handleSinglePlayer(int fd, pid_t *pid) { char pidBuffer[16]; memset(pidBuffer, 0, 16); // read till there is a valid pid do { if (readLine(pidBuffer, fd) < 0) { return -1; } *pid = atoi(pidBuffer); } while (*pid == 0); return 0; } /** * close the fifo and delete it. * @param fd file descriptor of fifo. * @return 0 on success, -1 otherwise. */ static int deleteFifo(int fd) { if (close(fd) == -1) { perror("closing fifo failed"); } if (unlink(FIFO) == -1) { return perror_return("unlink to fifo failed"); } return 0; } /** * connect to players and signal them. * @param fd file descriptor of fifo. * @param pid1 for first player. * @param pid2 for second player. * @param shmaddr shared memory. * @return 0 on success, -1 otherwise. */ static int handlePlayers(int fd, pid_t *pid1, pid_t *pid2, char *shmaddr) { // handle first player if (handleSinglePlayer(fd, pid1) < 0) { deleteFifo(fd); return -1; } // handle second player if (handleSinglePlayer(fd, pid2) < 0) { deleteFifo(fd); return -1; } // delete fifo if (deleteFifo(fd) == -1) { return -1; } // send signals if (kill(*pid1, SIGUSR1) == -1) { return perror_return("sending signal to process1 failed"); } while (*shmaddr == '\0') { // wait for first player to enter his move sleep(1); } if (kill(*pid2, SIGUSR1) == -1) { return perror_return("sending signal to process2 failed"); } return 0; } /** * delete shared memory. * @param shmaddr shared memory. * @param shmid shared memory id. */ static void deleteSharedMemory(char *shmaddr, int shmid) { if (shmdt(shmaddr) < 0) { exitError("shmdt failed"); } if (shmctl(shmid, IPC_RMID, NULL) == -1) { exitError("shmctl failed"); } }
C
#include "mystery.h" int num[200]; int add (int a, int b){ return a + b; } int dothething(int n){ if (n == 1 || n == 2){ return 1; }else{ return add(dothething(n-1), dothething(n-2)); } } int main(int argc,char** argv){ int tmp = atoi(argv[1]); int result; if(tmp==0){ result=0; }else if(tmp<0){ printf("Invalid input\n"); return 0; }else{ result = dothething(tmp); } printf("value = %d\n",result); return 0; }
C
/* ** EPITECH PROJECT, 2017 ** test ** File description: ** test */ #include <criterion/criterion.h> #include <criterion/redirect.h> #include "header_tetris.h" Test(print_shape, test1) { char *shape[] = {"**", "*", "**", NULL}; tetrimino_t tetri = {"flo", 2, 3, 4, shape, true}; char str[] = "Tetriminos : Name flo : Size 2*3 : Color 4 :\n\ **\n*\n**\n\0"; cr_redirect_stdout(); print_shape(&tetri); cr_assert_stdout_eq_str(str); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ struct TYPE_2__ {scalar_t__ a_seek; scalar_t__ f_seek; int /*<<< orphan*/ type; } ; struct whyle {scalar_t__ w_fename; struct whyle* w_next; TYPE_1__ w_end; int /*<<< orphan*/ w_start; } ; struct command {int dummy; } ; typedef int /*<<< orphan*/ Char ; /* Variables and functions */ int ERR_EXPRESSION ; int ERR_NAME ; scalar_t__ SEEKEQ (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ; int /*<<< orphan*/ TCSH_F_SEEK ; int /*<<< orphan*/ TC_WHILE ; int /*<<< orphan*/ USE (struct command*) ; int /*<<< orphan*/ doagain () ; int /*<<< orphan*/ exp0 (int /*<<< orphan*/ ***,int) ; int /*<<< orphan*/ expr (int /*<<< orphan*/ ***) ; scalar_t__ intty ; int /*<<< orphan*/ lineloc ; scalar_t__ noexec ; int /*<<< orphan*/ preread () ; int /*<<< orphan*/ stderror (int) ; int /*<<< orphan*/ toend () ; struct whyle* whyles ; struct whyle* xcalloc (int,int) ; int /*<<< orphan*/ zlast ; void dowhile(Char **v, struct command *c) { int status; int again = whyles != 0 && SEEKEQ(&whyles->w_start, &lineloc) && whyles->w_fename == 0; USE(c); v++; /* * Implement prereading here also, taking care not to evaluate the * expression before the loop has been read up from a terminal. */ if (noexec) status = 0; else if (intty && !again) status = !exp0(&v, 1); else status = !expr(&v); if (*v && !noexec) stderror(ERR_NAME | ERR_EXPRESSION); if (!again) { struct whyle *nwp = xcalloc(1, sizeof(*nwp)); nwp->w_start = lineloc; nwp->w_end.type = TCSH_F_SEEK; nwp->w_end.f_seek = 0; nwp->w_end.a_seek = 0; nwp->w_next = whyles; whyles = nwp; zlast = TC_WHILE; if (intty) { /* * The tty preread */ preread(); doagain(); return; } } if (status) /* We ain't gonna loop no more, no more! */ toend(); }
C
#include "header.h" int main() { int menuOption = mainMenu(); int x, y, currentGen = 1; cel **table; switch(menuOption) { case 0: printf("\n\n--Novo Jogo--\n\n"); printf("Tamanho do mundo (x y): "); scanf("%d %d", &x, &y); table = defineTable(x, y); displayTable(x, y, table, 0); insertCel(x, y, table); break; case 1: table = loadTable(&x, &y, &currentGen); displayTable(x, y, table, 0); break; default: printf("\n\nFechando o Jogo...\n\n"); return 0; } gameMenu(x, y, currentGen, table); printf("\n\nFechando o Jogo...\n\n"); return 0; }
C
// program to test forever loop #include<stdio.h> int main (void) { int counter = 0; while(0==0) { printf("%i",counter); counter++; } }
C
/****************************************************************************** * MSP-EXP430G2-LaunchPad Software UART Transmission * * Original Code: From MSP-EXP430G2-LaunchPad User Experience Application * Original Author: Texas Instruments * * Description: This code shows the minimum neeed to send data over a software * UART pin (P1.1). This is a highly condenced and modified version * of the User Experience Application which comes programmed with * the LaunchPad. * * Modified by Nicholas J. Conn - http://msp430launchpad.blogspot.com * Date Modified: 07-25-10 ******************************************************************************/ #include "msp430g2231.h" #define TXD BIT1 // TXD on P1.1 #define Bitime 104 //9600 Baud, SMCLK=1MHz (1MHz/9600)=104 unsigned char BitCnt; // Bit count, used when transmitting byte unsigned int TXByte; // Value sent over UART when Transmit() is called // Function Definitions void Transmit(void); void main(void) { WDTCTL = WDTPW + WDTHOLD; // Stop WDT unsigned int uartUpdateTimer = 10; // Loops until byte is sent unsigned int i = 0; // Transmit value counter BCSCTL1 = CALBC1_1MHZ; // Set range DCOCTL = CALDCO_1MHZ; // SMCLK = DCO = 1MHz P1SEL |= TXD; // P1DIR |= TXD; // __bis_SR_register(GIE); // interrupts enabled\ /* Main Application Loop */ while(1) { if ((--uartUpdateTimer == 0)) { TXByte = i; Transmit(); i++; uartUpdateTimer = 10; } } } // Function Transmits Character from TXByte void Transmit() { CCTL0 = OUT; // TXD Idle as Mark TACTL = TASSEL_2 + MC_2; // SMCLK, continuous mode BitCnt = 0xA; // Load Bit counter, 8 bits + ST/SP CCR0 = TAR; CCR0 += Bitime; // Set time till first bit TXByte |= 0x100; // Add stop bit to TXByte (which is logical 1) TXByte = TXByte << 1; // Add start bit (which is logical 0) CCTL0 = CCIS0 + OUTMOD0 + CCIE; // Set signal, intial value, enable interrupts while ( CCTL0 & CCIE ); // Wait for TX completion TACTL = TASSEL_2; // SMCLK, timer off (for power consumption) } // Timer A0 interrupt service routine #pragma vector=TIMERA0_VECTOR __interrupt void Timer_A (void) { CCR0 += Bitime; // Add Offset to CCR0 if ( BitCnt == 0) // If all bits TXed, disable interrupt CCTL0 &= ~ CCIE ; else { CCTL0 |= OUTMOD2; // TX Space if (TXByte & 0x01) CCTL0 &= ~ OUTMOD2; // TX Mark TXByte = TXByte >> 1; BitCnt --; } }
C
/** * @file include/mcube/list.h * * @author Hiroyuki Chishiro */ #ifndef __MCUBE_MCUBE_LIST_H__ #define __MCUBE_MCUBE_LIST_H__ /* * Type-generic doubly-linked lists * * Copyright (C) 2010 Ahmed S. Darwish <[email protected]> * * This API is very close to the Linux-2.6 one, which I've used back in * the days and found it to be very flexible. The code itself was * "cleanroomed" from Bovet & Cesati's `Understanding the Linux Kernel' * book to avoid copyrights mismatch. * * A good feature of this API is letting us allocate and deallocate both * the structure _and_ its linked-list pointers in one-shot. This avoids * unnecessary fragmentation in kmalloc() buffers, lessens the chance of * memory leaks, and improves locality of reference. * * Such lists typically look like this: * * * .--------------------------------------------------------. * | | * | struct A struct B struct C | * | .......... .......... .......... | * | . . . . . . | * v . . . . . . | * --- . --- . . --- . . --- . | * |@| ---------> |@| ---------> |@| ---------> |@| ------. * | | . | | . . | | . . | | . * |*| <--------- |*| <--------- |*| <--------- |*| <----. * --- . --- . . --- . . --- . | * `H' . `n' . . `n' . . `n' . | * | .......... .......... .......... | * | | * .--------------------------------------------------------. * * * where 'H' and 'n' are list_node structures, and 'H' is the list's * head. '@' is a node's next pointer, while '*' is the same node's * prev pointer. All of the next and prev pointers point to _other_ * list_node objects, not to the super-objects A, B, or C. * * Check the test-cases for usage examples. */ #ifndef __ASSEMBLY__ /* * Doubly-linked list node */ struct list_node { struct list_node *next; struct list_node *prev; }; /* * Static init, for inside-structure nodes */ #define LIST_INIT(n) \ { \ .next = &(n), \ .prev = &(n), \ } /* * Global declaration with a static init */ #define LIST_NODE(n) \ struct list_node n = LIST_INIT(n) /* * Dynamic init, for run-time */ static inline void list_init(struct list_node *node) { node->next = node; node->prev = node; } /* * Is this node connected with any neighbours? */ static inline bool list_empty(const struct list_node *node) { if (node->next == node) { assert(node->prev == node); return true; } assert(node->prev != node); return false; } /* * Insert @new right after @node */ static inline void list_add(struct list_node *node, struct list_node *new) { new->next = node->next; new->next->prev = new; node->next = new; new->prev = node; } /* * Insert @new right before @node */ static inline void list_add_tail(struct list_node *node, struct list_node *new) { new->prev = node->prev; new->prev->next = new; node->prev = new; new->next = node; } /* * Return the address of the data structure of type @type * that includes given @node. @node_name is the node's * name inside that structure declaration. * * The "useless" pointer assignment is for type-checking. * `Make it hard to misuse' -- a golden APIs advice. */ #define list_entry(node, type, node_name) \ ({ \ size_t offset; \ __unused struct list_node *m; \ \ m = (node); \ \ offset = offsetof(type, node_name); \ (type *)((uint8_t *)(node) - offset); \ }) /* * Scan the list, beginning from @node, using the iterator * @struc. @struc is of type pointer to the structure * containing @node. @name is the node's name inside that * structure (the one containing @node) declaration. * * NOTE! Don't delete the the iterator's list node inside * loop: we use it in the initialization of next iteration. */ #define list_for_each(node, struc, name) \ for (struc = list_entry((node)->next, typeof(*struc), name); \ &(struc->name) != (node); \ struc = list_entry(struc->name.next, typeof(*struc), name)) /* * Same as list_for_each(), but with making it safe to * delete the iterator's list node inside the loop. This * is useful for popping-up list elements as you go. * * You'll need to give us a spare iterator for this. */ #define list_for_each_safe(node, struc, spare_struc, name) \ for (struc = list_entry((node)->next, typeof(*struc), name), \ spare_struc = list_entry(struc->name.next, typeof(*struc), name); \ &(struc->name) != (node); \ struc = spare_struc, \ spare_struc = list_entry(struc->name.next, typeof(*struc), name)) /* * Pop @node out of its connected neighbours. */ static inline void list_del(struct list_node *node) { struct list_node *prevn; struct list_node *nextn; prevn = node->prev; nextn = node->next; assert(prevn); assert(nextn); assert(prevn->next == node); assert(nextn->prev == node); prevn->next = node->next; nextn->prev = node->prev; node->next = node; node->prev = node; } #endif /* !__ASSEMBLY__ */ #endif /* __MCUBE_MCUBE_LIST_H__ */
C
#include "utility.h" #include "../../core/util/log.h" #include "types.h" void extract_signture(bytes_t i_raw_sig, uint8_t* o_sig) { //ECDSA signature encoded as TLV: 30 L 02 Lr r 02 Ls s int lr = i_raw_sig.data[3]; int ls = i_raw_sig.data[lr + 5]; int offset = 0; in3_log_debug("lr %d, ls %d \n", lr, ls); if (lr > 0x20) { memcpy(o_sig + offset, i_raw_sig.data + 5, lr - 1); offset = lr - 1; } else { memcpy(o_sig, i_raw_sig.data + 4, lr); offset = lr; } if (ls > 0x20) { memcpy(o_sig + offset, i_raw_sig.data + lr + 7, ls - 1); } else { memcpy(o_sig + offset, i_raw_sig.data + lr + 6, ls); } } int get_recid_from_pub_key(const ecdsa_curve* curve, uint8_t* pub_key, const uint8_t* sig, const uint8_t* digest) { int i = 0; uint8_t p_key[65]; int ret = 0; int recid = -1; for (i = 0; i < 4; i++) { ret = ecdsa_recover_pub_from_sig(curve, p_key, sig, digest, i); if (ret == 0) { if (memcmp(pub_key, p_key, 65) == 0) { recid = i; break; } } } return recid; } uint32_t reverse_bytes(uint32_t bytes) { uint32_t aux = 0; uint8_t byte; int i; for (i = 0; i < 32; i += 8) { byte = (bytes >> i) & 0xff; aux |= byte << (32 - 8 - i); } return aux; }
C
/* * 分配、设置、注册一个 platfrom_driver 结构体 * 这边的程序不用改变 */ #include <linux/module.h> #include <linux/version.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/sched.h> #include <linux/pm.h> #include <linux/slab.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/gpio_keys.h> #include <linux/workqueue.h> #include <linux/gpio.h> #include <asm/io.h> #include <asm/uaccess.h> static int major; static struct class *led_class; volatile unsigned long *gpkcon0 = NULL; volatile unsigned long *gpkdat = NULL; static int pin; static int led_open(struct inode *inode ,struct file *file) { //配置gpkcon0为输出状态 *gpkcon0 &= ~(0xf<<(pin*4));//先清零 *gpkcon0 |= (0x1<<(pin*4));//在配置为输出状态 return 0; } static ssize_t led_write(struct file *filp,const char __user *buf,size_t count,loff_t *f_pos) { int val = 0; int tmp; tmp = copy_from_user(&val,buf,count); if(tmp) printk("copy_from_user failed!\n"); printk("val = %d\n",val); if (val == 1) { *gpkdat &= ~(1<<pin);//点灯 } else { *gpkdat |= (1<<pin);//灭灯 } return 0; } static struct file_operations led_fops= { .owner = THIS_MODULE, .open = led_open, .write = led_write, }; static int led_probe(struct platform_device *pdev) { //根据platform_device的资源来获取资源 struct resource *res; struct device *cd; res = platform_get_resource(pdev,IORESOURCE_MEM,0); //获取内存资源 gpkcon0 = ioremap(res->start,res->end - res->start + 1); gpkdat = gpkcon0+2; res = platform_get_resource(pdev,IORESOURCE_IRQ,0); //获取中断资源 pin = res->start; printk("pin = %d\n",pin); printk("led_probe, found led\n"); //注册字符设备驱动 major = register_chrdev(0, "led", &led_fops); led_class =class_create(THIS_MODULE, "led"); if (IS_ERR(led_class)) return PTR_ERR(led_class); cd = device_create(led_class, NULL, MKDEV(major, 0), NULL, "led"); if (IS_ERR(cd)) return PTR_ERR(cd); return 0; } static int led_remove(struct platform_device *pdev) { device_destroy(led_class,MKDEV(major,0)); class_destroy(led_class); unregister_chrdev(major,"led"); iounmap(gpkcon0); printk("led_remove!\n"); return 0; } static struct platform_driver led_drv = { .probe = led_probe, .remove = led_remove, .driver = { .name = "myled", }, }; static int led_drv_init(void) { int ret; ret = platform_driver_register(&led_drv); if (ret != 0) pr_err("Failed to register ab8500 regulator: %d\n", ret); printk("led init sucess\n"); return 0; } static void led_drv_exit(void) { platform_driver_unregister(&led_drv); } module_init(led_drv_init); module_exit(led_drv_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("CXD"); MODULE_VERSION("1.0"); MODULE_DESCRIPTION("S3C6410 LED Driver");
C
#include <stdio.h> #include"servolib.h" //This is the Modular Servo Library we are using to control Servo Movement void drive_to_botguy(){}; void drive_to_scoring_area(){}; int main() { servo arm = build_servo(1, 0, 2048); //Build a 'servo' named 'arm' //It is in Port #1, Its Minimum Position is 0, Its Maximum Position is 2048 servo claw = build_servo(3, 300, 1500); //Build a 'servo' named 'claw' //It is in Port #3, Its Minimum Position is 300, Its Maximum Position is 1500 servo_movement up = build_servo_movement(100, 15, 6); //Build a 'servo_movement' named 'up' //Its desired position is 100 Ticks, It moves 15 ticks each movement with a Latency of 6 ms servo_movement down = build_servo_movement(2000, 8, 10); //Build a 'servo_movement' named 'down' //Its desired position is 2000 Ticks, It moves 8 ticks each movement with a Latency of 10 ms servo_movement open = build_servo_movement(400, 20, 5); //Build a 'servo_movement' named 'open' //Its desired position is 400 Ticks, It moves 20 ticks each movement with a Latency of 5 ms servo_movement close = build_servo_movement(1400, 12, 6); //Build a 'servo_movement' named 'close' //Its desired position is 1400 Ticks, It moves 12 ticks each movement with a Latency of 6 ms move_servo(arm, up); //Move the 'arm' servo to the 'up' position move_servo(claw, open); //Move the 'claw' servo to the open position //NOTE: The 'claw' and 'arm' servos do not wait to finish //NOTE: This code would immediately execute the 'drive_to_botguy()' function //NOTE: The 'claw' and 'arm'would move while the robot is still moving drive_to_botguy(); //Drive the robot to botguy wait_servo(claw, close); //Wait until the 'claw' servo is at the 'close' position //NOTE: This function waits until the the servo is done moving to execute the next function //NOTE: This is the same as calling 'move_servo(claw, close);' and then 'bsd(claw);' drive_to_scoring_area(); //Drive to the scoring area wait_servo(arm, down); //Wait until the 'arm' servo is at the 'down' position wait_servo(claw, open); //Wait until the 'claw' servo is at the 'open' position return 0; //Returns '0' to the system }
C
/* Meno: Datum: Simulujte nasledujucu situaciu. V malom kralovstve korunovali noveho krala a chodia sa mu neustale klanat styria slachtici a desiati poddani. Prejavovanie ucty kralovi trva nejaky cas (v simulacii 1s) a nejaky cas si slahctic ci poddany dava prestavku (v simulacii 4s). Cela simulacia nech trva 30s. 1. Doplnte do programu pocitadlo pocitajuce, kolko krat sa kralovi poklonili slachtici; a pocitadlo pocitajuce, kolko krat sa kralovi poklonili poddani. [2b] 2. Zabezpecte, aby sa kralovi sucasne klanali maximalne dvaja slachtici a tiez aby sa kralovi neklanal slachtic spolu s poddanym (cize alebo max. 2 slachtici, alebo lubovolne vela poddanych). Ak je pred kralom rad, slachtici maju samozrejme prednost. [5b] 3. Osetrite v programe spravne ukoncenie simulacie po uplynuti stanoveneho casu. [3b] Poznamky: - na synchronizaciu pouzite iba mutexy, podmienene premenne alebo semafory - nespoliehajte sa na uvedene casy, simulacia by mala fungovat aj s inymi casmi - build (console): gcc poslovia_a_pisari -o poslovia_a_pisari -lpthread */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #define TRUE 1 #define FALSE 0 // signal na zastavenie simulacie int stoj = 0, slachticiCount = 0, poddaniCount = 0; int cakajuciSlachtici = 0, slachticiVnutri = 0, poddaniVnutri = 0; // Synchornizacne konstrukcie pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condPoddani = PTHREAD_COND_INITIALIZER; pthread_cond_t condSlachtici = PTHREAD_COND_INITIALIZER; // klananie sa void klananie(void) { sleep(1); } // prestavka medzi klananiami void prestavka(void) { sleep(4); } // slachtic void *slachtic( void *ptr ) { // pokial nie je zastaveny while(!stoj) { // Zaznamenaj cakajucich slachticov pthread_mutex_lock(&mutex); cakajuciSlachtici++; printf("SLA: cakam na klananie | cakajuci slachtici: %d\n", cakajuciSlachtici); // Pusti ku kralovi ak nie su dnu iny dvaja slachtici alebo poddani while(slachticiVnutri == 2 || poddaniVnutri > 1){ // Ukonci ak skoncila simulacia if(stoj){ pthread_mutex_unlock(&mutex); return NULL; } pthread_cond_wait(&condSlachtici, &mutex); } // Idu sa klanat ku kralovi cakajuciSlachtici--; slachticiVnutri++; printf("SLA: Idem sa klanat | vnutri slachticov: %d\n", slachticiVnutri); pthread_mutex_unlock(&mutex); // poklona u krala klananie(); // Zaznamenaj cakajucich slachticov pthread_mutex_lock(&mutex); // Zaznamenaj odchod slachtica slachticiVnutri--; slachticiCount++; printf("SLA: Odchadzam | poklony celkovo: %d\n", slachticiCount); // Odchadzajuci slachtic sinalizuje cakajucim slachticom alebo poddanym if(cakajuciSlachtici > 0){ pthread_cond_broadcast(&condSlachtici); } else if(cakajuciSlachtici == 0){ pthread_cond_broadcast(&condPoddani); } pthread_mutex_unlock(&mutex); prestavka(); } return NULL; } // poddany void *poddany( void *ptr ) { // pokial nie je zastaveny while(!stoj) { // Vzajomne vylucuj pthread_mutex_lock(&mutex); while(cakajuciSlachtici > 0 || slachticiVnutri > 0){ // Ukonci ak skoncila simulacia if(stoj){ pthread_mutex_unlock(&mutex); return NULL; } pthread_cond_wait(&condPoddani, &mutex); } // Eviduj poddanych vnutri poddaniVnutri++; printf("POD: Idem sa klanat | vnutri poddanych: %d\n", poddaniVnutri); pthread_mutex_unlock(&mutex); // Klananie poddaneho klananie(); // Vzajomne vylucuj pthread_mutex_lock(&mutex); poddaniVnutri--; poddaniCount++; printf("POD: Odchadzam | poklony celkovo: %d\n", poddaniCount); // Posledny poddany vnutri signalizuje slachticom ze mozu ist dnu if(poddaniVnutri == 0 && cakajuciSlachtici == 0){ pthread_cond_broadcast(&condPoddani); } pthread_mutex_unlock(&mutex); prestavka(); } return NULL; } int main(void) { int i; pthread_t slachtici[4]; pthread_t poddani[10]; for (i=0;i<4;i++) pthread_create( &slachtici[i], NULL, &slachtic, NULL); for (i=0;i<10;i++) pthread_create( &poddani[i], NULL, &poddany, NULL); sleep(30); // Zastav simulaciu pthread_mutex_lock(&mutex); printf("Koniec simulacie !!! \n"); stoj = 1; pthread_cond_broadcast(&condSlachtici); pthread_cond_broadcast(&condPoddani); pthread_mutex_unlock(&mutex); for (i=0;i<4;i++) pthread_join( slachtici[i], NULL); for (i=0;i<10;i++) pthread_join( poddani[i], NULL); printf("Poddani: %d klanani\n", poddaniCount); printf("Slachtici: %d klanani\n", slachticiCount); exit(EXIT_SUCCESS); }
C
/* Pedro Diógenes Alefe Lucas Bernardo Morais Foi alterado a entrada para N = 90000 para ter um tempo mais amplo e poder medir melhor o speedup. Tempo sequencial: real 0m21,744s user 0m21,740s sys 0m0,004s Tempo paralelo com politica default: real 0m12,236s user 0m22,645s sys 0m0,000s Tempo paralelo com política dynamic com chunks de tamanho 300 (raiz quadrada de N): real 0m11,271s user 0m22,534s sys 0m0,004s Speedup: 21,744 / 11,271 = 1.92 */ #include <stdio.h> #include <stdlib.h> int main() { int i, j, n = 90000; // Allocate input, output and position arrays int *in = (int*) calloc(n, sizeof(int)); int *pos = (int*) calloc(n, sizeof(int)); int *out = (int*) calloc(n, sizeof(int)); // Initialize input array in the reverse order for(i=0; i < n; i++) in[i] = n-i; // Print input array // for(i=0; i < n; i++) // printf("%d ",in[i]); // Silly sort (you have to make this code parallel) #pragma omp parallel for private(i, j) schedule(dynamic, 300) num_threads(2) for(i=0; i < n; i++) for(j=0; j < n; j++) if(in[i] > in[j]) pos[i]++; // Move elements to final position for(i=0; i < n; i++) out[pos[i]] = in[i]; // print output array // for(i=0; i < n; i++) // printf("%d ",out[i]); // Check if answer is correct for(i=0; i < n; i++) if(i+1 != out[i]) { printf("test failed\n"); exit(0); } printf("test passed\n"); }
C
/**************************************************************************** * hexdump - a program to display a file in hexadecimal and ascii * Such as: * 000020: 19 00 00 00 48 00 00 00 5F 5F 50 41 47 45 5A 45 | ....H...__PAGEZE * * Author: Robert Bierman * Date: March 28, 2020 * Source: hexdump.c * * Primary Purpose: * Written as a utility for CSC-415 Operating Systems, File System project * to allow the dumping of the "drive" file for verification of proper * structure and content. * * copyright 2020 Robert Bierman ****************************************************************************/ // Compilation: gcc hexdump.c -o hexdump #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #ifndef uint64_t typedef u_int64_t uint64_t; #endif #ifndef uint32_t typedef u_int32_t uint32_t; #endif #define BUFSIZE 4096 //amount read at one time #define BLOCKSIZE 256 // number of bytes printed before a blank line #define LBABLOCKSIZE 512 // display blocks from command line are based on 512 bytes #define VERSION "1.0" // Version // This procedure takes a file name, a starting block and a number of blocks and dumps the // file to stdout. // Output (including the number of blocks) is limited by the length of the file and // partial blocks are counted as a whole block for the header showing how many blocks are // being displayed. // // Checks are done to ensure that blanks are displayed on the last line of the output // if the file only partially uses the last 16 bytes. int processFile (char * filename, uint64_t startBlock, uint64_t numBlocks) { int readbytes; int position = 0; int loops = BUFSIZE / BLOCKSIZE; //number of loops of blocks within one buffer read int offset; int k; uint32_t lbaBlockSize = LBABLOCKSIZE; uint64_t numBytesToStartBlock; uint64_t numBytesToProcess; uint64_t endOfFile; numBytesToProcess = numBlocks * lbaBlockSize; numBytesToStartBlock = startBlock * lbaBlockSize; int fd = open (filename, O_RDONLY); //open the file // Error opening file (common if they don't enter a valid file name) if (fd == -1) { printf ("ERROR: failed to open file '%s'\n", filename); return -2; } endOfFile = lseek(fd, 0, SEEK_END); //will reset seek below if (numBytesToProcess == 0) { numBytesToProcess = endOfFile; //reset numBlocks for the header here numBlocks = ((numBytesToProcess + lbaBlockSize) - 1) / lbaBlockSize; numBlocks = numBlocks - startBlock; } unsigned char * buf = malloc (BUFSIZE); //Allocate the read buffer // Very rare error - something bad if I can not allocate a small buffer if (buf == NULL) { close (fd); printf ("Failed to allocate buffer\n"); return -3; } //Position to the startBlock lseek (fd, numBytesToStartBlock, SEEK_SET); position = numBytesToStartBlock; if (position > endOfFile) //can not start past the end of the filename { printf ("Can not dump file %s, starting at block %llu, past the end of the file.\n\n", filename, (unsigned long long)startBlock); return (-5); } // calculate max blocks we can display from the given start point uint64_t maxBlocks = (((endOfFile - position) + lbaBlockSize) - 1) / lbaBlockSize; if (numBlocks > maxBlocks) numBlocks = maxBlocks; //Proces the file - the do loop goes until we read less bytes than the BUFSIZE printf ("Dumping file %s, starting at block %llu for %llu block%c:\n\n", filename, (unsigned long long)startBlock, (unsigned long long)numBlocks, numBlocks != 1?'s':'\0'); do { if (position >= (numBytesToStartBlock + numBytesToProcess)) goto cleanup; readbytes = read (fd, buf, BUFSIZE); //Read one block offset = 0; //set our offset within the block for (int i = 0; i < loops; i++) //Loop for each "Block" within one buffer read { for (int j = 0; j < BLOCKSIZE/16; j++) //loop j lines for each block { if (position+offset >= (numBytesToStartBlock + numBytesToProcess)) goto cleanup; // Handle if we are at the end of the file and the line will have less // than 16 bytes associated with it. if (offset + 16 > readbytes) { printf ("%06X: ", offset+position); for (k = 0; k < readbytes - offset; k++) { printf ("%02X ", buf[offset + k]); } for (;k < 16; k++) { printf (" "); //Print remaining of the hex output as blanks to fill out the line } printf (" | "); for (k = 0; k < readbytes - offset; k++) { printf ("%c", buf[offset + k] < 32?'.':buf[offset+k]); } printf("\n"); } else { //If a full line, do one print for the full line printf ("%06X: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X | %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", offset+position, buf[offset + 0],buf[offset + 1],buf[offset + 2],buf[offset + 3], buf[offset + 4],buf[offset + 5],buf[offset + 6],buf[offset + 7], buf[offset + 8],buf[offset + 9],buf[offset + 10],buf[offset + 11], buf[offset + 12],buf[offset + 13],buf[offset + 14],buf[offset + 15], buf[offset + 0] < 32?'.':buf[offset + 0], buf[offset + 1] < 32?'.':buf[offset + 1], buf[offset + 2] < 32?'.':buf[offset + 2], buf[offset + 3] < 32?'.':buf[offset + 3], buf[offset + 4] < 32?'.':buf[offset + 4], buf[offset + 5] < 32?'.':buf[offset + 5], buf[offset + 6] < 32?'.':buf[offset + 6], buf[offset + 7] < 32?'.':buf[offset + 7], buf[offset + 8] < 32?'.':buf[offset + 8], buf[offset + 9] < 32?'.':buf[offset + 9], buf[offset + 10] < 32?'.':buf[offset + 10], buf[offset + 11] < 32?'.':buf[offset + 11], buf[offset + 12] < 32?'.':buf[offset + 12], buf[offset + 13] < 32?'.':buf[offset + 13], buf[offset + 14] < 32?'.':buf[offset + 14], buf[offset + 15] < 32?'.':buf[offset + 15]); } //up the offset by 16 for the next line offset = offset + 16; //if greater than the readbytes we have exhausted this buffer if (offset >= readbytes) break; } //print a blank line between each BLOCK printf("\n"); //if greater than the readbytes we have exhausted this buffer if (offset >= readbytes) break; } //Next buffer, increment the overall position within the file. position = position + readbytes; // If we read the number of bytes requested (BUFSIZE), then we have not hit // the end of file yet, and should try to read more. } while (readbytes == BUFSIZE); cleanup: // clean up free (buf); close (fd); return 0; } // processArguments handles the command line using getopt_long to parse the argv array // // It then sets variable and or dispatches the action necessary based on the parameters. // it handles the multiple calls to processFile by iterating on uncontained parameters int processArguments (int argc, char * argv[]) { int c; int digit_optind = 0; uint64_t count, start; count = 0; start = 0; int retval; char * filename = NULL; while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {"count", required_argument, 0, 'c'}, //forces to c {"start", required_argument, 0, 's'}, //forces to s {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"file", required_argument, 0, 'f'}, {0, 0, 0, 0 } }; c = getopt_long(argc, argv, "c:s:f:vh", long_options, &option_index); if (c == -1) break; switch (c) { case 0: //It is a long option (all converted so should be none) printf("Unknown option %s", long_options[option_index].name); if (optarg) printf(" with arg %s", optarg); printf("\n"); exit (-1); case 'c': count = atol(optarg); break; case 's': start = atol(optarg); break; case 'f': filename = optarg; break; case 'h': printf ("USAGE: hexdump --file <filename> [--count num512ByteBlocks] [--start start512ByteBlock] [--help] [--version]\n"); exit (0); case 'v': printf("hexdump - Version %s; copyright 2020 Robert Bierman\n\n", VERSION); exit (0); case '?': break; default: printf("Unknown option returned character code 0%o ??\n", c); exit (-1); } } //if a file name is already specified - process it if (filename != NULL) { retval = processFile (filename, start, count); if (retval != 0) return (retval); } //additional files (same arguments) if (optind < argc) { while (optind < argc) { retval = processFile (argv[optind++], start, count); if (retval != 0) return (retval); } } return 0; } //Main calls process arguments which in turn calls process file. int main (int argc, char * argv[]) { return (processArguments (argc, argv)); }
C
#include <R.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> void cartgini(int *fn, int *fp, int *groups,double *fvals,int *group, int *ngroup,double *val); void cartentropy(int *fn, int *fp, int *groups,double *fvals,int *group, int *ngroup,double *val); void zero_int(int *mem, int size); void sort_group(double *vals,int *group,int *fp,int *fn,int left, int right) ; void zero(double *mem, int size); void sort_data(double *x, int *index,int left, int right); void cartgini(int *fn, int *fp, int *groups,double *fvals,int *group, int *ngroup,double *val) { int i, k,n,p,g,left,right,l,*xindex,j; double dev, prob,index,minindex, *vals; double *x; int *nright; n=*fn; p=*fp; g=*groups; vals = Calloc(p*n,double); for(i=0; i<p; i++) { for(j=0; j<n; j++) vals[i*n+j] = fvals[i*n+j]; } right = n-1; left = 0; xindex = Calloc(n,int);zero_int(xindex,n); for (i=0; i<n; i++) xindex[i] = group[i]; sort_group(vals,xindex,fp,fn,left,right); /* data relocation and make index */ x = Calloc(n,double); zero(x,n); minindex=0; nright = Calloc(g,int); for(l=0; l<p; l++) { for (i=0; i<n; i++) x[i] = vals[l*n+i]; left=0; right=n-1; sort_data(x, xindex,left,right) ; /* Calculate gini index */ zero_int(nright,g); index=1; for (i=0; i<g; i++) { prob = ((double)ngroup[i])/((double)n); if (prob>0) index -= prob*prob; } for (i=0; i<n-1; i++) { (nright[(xindex[i]-1)])++; dev=1; for (k=0; k<g; k++) { prob = ((double) nright[k])/((double)(i+1)); dev -= ((double)(i+1))*(prob*prob)/((double)n); prob = ((double) (ngroup[k]-nright[k]))/((double)(n-i-1)); dev -= ((double)(n-i-1))*(prob*prob)/((double)n); } if (dev<index) index = dev; } if(l==0 ) minindex= index; else if(minindex < index) minindex = index; } *val = 1-minindex; Free(vals); Free(x); Free(xindex); Free(nright); } /*********************** Entropy *********************************************************************/ void cartentropy(int *fn, int *fp, int *groups,double *fvals,int *group, int *ngroup,double *val) { int i, k,n,p,g,left,right,l,*xindex,j; double dev, prob,index,minindex, *vals; double *x; int *nright; n=*fn; p=*fp; g=*groups; vals = Calloc(p*n,double); for(i=0; i<p; i++) { for(j=0; j<n; j++) vals[i*n+j] = fvals[i*n+j]; } right = n-1; left = 0; xindex = Calloc(n,int);zero_int(xindex,n); for (i=0; i<n; i++) xindex[i] = group[i]; sort_group(vals,xindex,fp,fn,left,right); /* data relocation and make index */ x = Calloc(n,double); zero(x,n); minindex=0; nright = Calloc(g,int); for(l=0; l<p; l++) { for (i=0; i<n; i++) x[i] = vals[l*n+i]; left=0; right=n-1; sort_data(x, xindex,left,right) ; zero_int(nright,g); index = 0; for (i=0; i<g; i++) { prob = ((double)ngroup[i])/((double)n); if (prob>0) index -= prob*log(prob); } for (i=0; i<n-1; i++) { (nright[(xindex[i]-1)])++; dev=0; for (k=0; k<g; k++) { prob = ((double) nright[k])/((double)(i+1)); if(prob>0) dev -= ((double)(i+1))*prob*log(prob)/((double)(n)); prob = ((double) (ngroup[k]-nright[k]))/((double)(n-i-1)); if(prob>0) dev -=((double)(n-i-1))* prob*log(prob)/((double)(n)); } if (dev<index) index = dev; } if(l==0 ) minindex= index; else if(minindex < index) minindex = index; } *val = 1-minindex/log(g); Free(x); Free(xindex); Free(nright); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include "commands.h" #define SHELL_RL_SIZE 1024 #define SHELL_TOK_SIZE 64 #define SHELL_TOK_DELIM "\t\r\n\a" char *shell_read_line(void); char **shell_split_line(char *line); int shell_launch(char **args); int shell_execute(char **args); void shell_loop(void) { char *line; char **args; int status; do{ printf("> "); line = shell_read_line(); args = shell_split_line(line); status = shell_execute(args); free(line); free(args); }while(status); } char *shell_read_line(void) { char *line = NULL; ssize_t bufsize = 0; if(getline(&line, &bufsize, stdin)==-1){ if(feof(stdin)) exit(EXIT_SUCCESS); }else { perror("readline"); exit(EXIT_FAILURE); } return line; /* int bufsize = SHELL_RL_SIZE; int position = 0, c; char *buffer = malloc(sizeof(char)*bufsize); if(!buffer){ fprintf(stderr, "shell: allocation error\n"); exit(EXIT_FAILURE); } while(1){ c = gerchar(); if(c==EOF||c=='\n'){ buffer[position] = '\0'; return buffer; }else{ buffer[position] = c; } position++; if(position >= bufsize){ bufsize += SHELL_RL_SIZE; buffer = realloc(buffer, bufsize); if(!buffer){ fprintf(stderr, "shell: allocation error\n"); exit(EXIT_FAILURE); } } } */ } char **shell_split_line(char *line) { int bufsize = SHELL_TOK_SIZE, position = 0; char **tokens = malloc(bufsize*sizeof(char*)); char *token; if(!tokens){ fprintf(stderr, "shell: allocation error\n"); exit(EXIT_FAILURE); } token = strtok(line, SHELL_TOK_DELIM); while(token!=NULL){ tokens[position] = token; position++; if(position >=bufsize){ bufsize += SHELL_TOK_SIZE; tokens = realloc(tokens, bufsize*sizeof(char*)); if(!tokens){ fprintf(stderr, "shell: allocation error\n"); exit(EXIT_FAILURE); } } token = strtok(NULL, SHELL_TOK_DELIM); } tokens[position] = NULL; return tokens; } int shell_launch(char **args) { pid_t pid, wpid; int status; pid = fork(); if(pid == 0){ if(execvp(args[0], args) ==-1){ perror("shell"); } exit(EXIT_FAILURE); }else if(pid<0){ perror("shell"); }else{ do{ wpid = waitpid(pid, &status, WUNTRACED); }while(!WIFEXITED(status)&&!WIFSIGNALED(status)); } return 1; } int shell_execute(char **args) { int i; if(args[0] == NULL){ return 1; } for(i=0;i<shell_num_builtins();i++){ if(strcmp(args[0], builtin_str[i])==0){ return (*builtin_func[i])(args); } } return shell_launch(args); }
C
#include <myLinux.h> void *thr_fn(void *arg) { int n = 3; while (n--) { printf("thread count %d\n", n); sleep(1); } return (void *) 1; } int main(int argc, char *argv[]) { pthread_t tid; void *tret; int err; pthread_create(&tid, NULL, thr_fn, NULL); // pthread_detach(tid); while (1) { err = pthread_join(tid, &tret); if (err != 0) fprintf(stderr, "thread %s\n", strerror(err)); else fprintf(stderr, "thread exit code %d\n", (int) tret); sleep(1); } return 0; }
C
#include <stdio.h> void display(); int main() { int iRange = 0; printf("Enter any Number to print pattern on the console :""\n"); scanf("%d",&iRange); display(iRange); return 0; } void display(int iCount) { int iRow=0; int iLimit=1; printf("\n"); continu: for(iRow=1; iRow <= iCount;iRow++) { printf("*""\t"); } printf("\n"); iLimit++; if(iLimit<=5) { goto continu; } }
C
// // Created by tangwan on 2019-09-16. // /** * @desc: 7-8 哈利·波特的考试 * @author tangwan * @date 2019-09-16 */ #include <string.h> #include <stdio.h> #include <stdlib.h> #define MaxVertexNum 100 /* 最大顶点数设为100 */ #define INFINITY 65535 /* ∞设为双字节无符号整数的最大值65535*/ typedef int Vertex; /* 用顶点下标表示顶点,为整型 */ typedef int WeightType; /* 边的权值设为整型 */ typedef struct GNode *PtrToGNode; struct GNode { int Nv; /*顶点数*/ int Ne; /*边数*/ WeightType G[MaxVertexNum][MaxVertexNum]; }; typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型,矩阵(matrix)*/ typedef struct ENode *PtrToENode; struct ENode { Vertex V1, V2; /* 有向边<V1, V2> */ WeightType Weight; /* 权重 */ }; typedef PtrToENode Edge; /** * 构建图 */ MGraph BuildGraph(); MGraph CreateGraph(int VertexNum); void InsertEdge(MGraph Graph, Edge E); /** * 弗洛伊德算法,多源最短路径 */ void Floyd(MGraph Graph, WeightType D[][MaxVertexNum]); /** * 获取最合适的小动物 */ void FindAnimal(MGraph Graph); /** * 获取最大的路径 */ WeightType FindMaxDist(WeightType D[][MaxVertexNum], Vertex i, int N); /** 输入样例: 6 11 3 4 70 1 2 1 5 4 50 2 6 50 5 6 60 1 3 70 4 6 60 3 6 80 5 1 100 2 4 60 5 2 80 输出样例: 4 70 */ int main() { MGraph G = BuildGraph(); FindAnimal(G); return 0; } MGraph CreateGraph(int VertexNum) { Vertex V, W;/* 用顶点下标表示顶点,为整型*/ MGraph Graph; Graph = malloc(sizeof(struct GNode)); Graph->Nv = VertexNum; Graph->Ne = 0; /* 注意: 这里默认顶点编号从0开始,到(Graph->Nv -1)*/ for (V = 0; V < Graph->Nv; V++) for (W = 0; W < Graph->Nv; W++) Graph->G[V][W] = INFINITY;/*或INFINITY*/ return Graph; } void InsertEdge(MGraph Graph, Edge E) { /* 插入边 <V1, V2> */ Graph->G[E->V1][E->V2] = E->Weight; /* 若是无向图,还要插入边<V2, V1> */ Graph->G[E->V2][E->V1] = E->Weight; } MGraph BuildGraph() { MGraph Graph; Edge E; int Nv, i; scanf("%d", &Nv); /* 读入顶点个数 */ Graph = CreateGraph(Nv); /* 初始化有Nv个顶点但没有边的图 */ scanf("%d", &(Graph->Ne));/* 读入边数 */ if (Graph->Ne != 0) {/* 如果有边 */ E = (Edge) malloc(sizeof(struct ENode));/* 建立边结点 */ /*读入边,格式为"起点 终点 权重",插入邻接矩阵*/ for (i = 0; i < Graph->Ne; i++) { scanf("%d %d %d", &E->V1, &E->V2, &E->Weight); E->V1--; E->V2--; /* 起始编号从0开始 */ InsertEdge(Graph, E); } } return Graph; } void Floyd(MGraph Graph, WeightType D[][MaxVertexNum]) { Vertex i, j, k; /* 初始化 */ for (i = 0; i < Graph->Nv; i++) for (j = 0; j < Graph->Nv; j++) { D[i][j] = Graph->G[i][j]; } for (k = 0; k < Graph->Nv; k++) for (i = 0; i < Graph->Nv; i++) for (j = 0; j < Graph->Nv; j++) if (D[i][k] + D[k][j] < D[i][j]) { D[i][j] = D[i][k] + D[k][j]; } } void FindAnimal(MGraph Graph) { WeightType D[MaxVertexNum][MaxVertexNum], MaxDist, MinDist; Vertex Animal, i; Floyd(Graph, D); MinDist = INFINITY; for (i = 0; i < Graph->Nv; i++) { MaxDist = FindMaxDist(D, i, Graph->Nv); if (MaxDist == INFINITY) { /* 说明有从i无法变出的动物 */ printf("0\n"); return; } if (MinDist > MaxDist) { /* 找到最长距离更小的动物 */ MinDist = MaxDist; Animal = i + 1; /* 更新距离,记录编号 */ } } printf("%d %d\n", Animal, MinDist); } WeightType FindMaxDist(WeightType D[][MaxVertexNum], Vertex i, int N) { WeightType MaxDist; Vertex j; MaxDist = 0; for (j = 0; j < N; j++) /* 找出i到其他动物j的最长距离 */ if (i != j && D[i][j] > MaxDist) MaxDist = D[i][j]; return MaxDist; }
C
#include <stdio.h> #include <stdlib.h> #include <stdio.h> #include "ilist.h" #include "hashtable_ed.h" int main(int argc, char** argv){ int n, m, i, chave; int seed = 0; n = argc > 1 ? atoi(argv[1]) : 10; m = argc > 2 ? atoi(argv[2]) : n >> 1; srand(seed); THED* ht; ILIST *chaves = NULL; ht = THED_Criar(m, 10); // teste 1 // THED_Inserir(ht, 10, 5); // THED_Imprimir(ht); // THED_Inserir(ht, 11, 7); // THED_Imprimir(ht); // THED_Inserir(ht, 13, 0); // THED_Imprimir(ht); // ILIST *chaves = THED_Chaves(ht); // ILIST_Imprimir(chaves, 0); // ILIST_Destruir(chaves); // teste 2 // for(i = 0; i < n; i++){ // chave = (rand() % (n*10)); // THED_Inserir(ht, chave, chave + (rand() % 10)); // } // THED_Imprimir(ht); // chaves = THED_Chaves(ht); // ILIST_Imprimir(chaves, 0); // ILIST_Destruir(chaves); THED_Destruir(ht); return EXIT_SUCCESS; }
C
/** * @file buf.h * * Defines structures and functions for working with byte arrays of arbitrary * length. These are mostly used in the serialisation and deserialisation of * messages between the client and Diffusion, but are useful in a range of * other situations. * * Copyright © 2014, 2015 Push Technology Ltd., All Rights Reserved. * * Use is subject to license terms. * * NOTICE: All information contained herein is, and remains the * property of Push Technology. The intellectual and technical * concepts contained herein are proprietary to Push Technology and * may be covered by U.S. and Foreign Patents, patents in process, and * are protected by trade secret or copyright law. */ #ifndef _diffusion_buf_h_ #define _diffusion_buf_h_ 1 #include <limits.h> #include <inttypes.h> #include <apr.h> #include "list.h" #include "types/common_types.h" /** * A buffer for holding arbitrarily terminated byte arrays. Functions are * available (see (@ref buf.h)) to manipulate the byte array. */ typedef struct buf_s { /// Bytes contained in this buffer. char *data; /// Length in bytes contained in this buffer. apr_size_t len; } BUF_T; /** * Allocate memory for a new buffer. * * @retval "BUF_T *" A pointer to a new buffer. * @retval NULL If the buffer cannot be created. */ BUF_T *buf_create(void); /** * Free memory in the buffer, and the buffer itself. * * @param buf The buffer to be freed. */ void buf_free(BUF_T *buf); /** * A utility function for displaying the contents of a buffer to stdout, in * hexadecimal format. * * @param buf The buffer to display. */ void hexdump_buf(BUF_T *buf); /** * Creates a deep copy of an existing buffer. `buf_free` should be called * on the pointer when no longer needed. * * @param src The buffer to copy. * @retval "BUF_t *" A newly allocated buffer. * @retval NULL If the new buffer cannot be created. */ BUF_T *buf_dup(const BUF_T *src); /** * Appends an unsigned 64-bit integer to the buffer in Diffusion's packeder * integer format. * * @param buf The buffer to write to. * @param val A 64-bit unsigned integer. */ void buf_write_uint64_enc(BUF_T *buf, const uint64_t val); /** * Appends an unsigned 32-bit integer to the buffer in Diffusion's packed * integer format. * * @param buf The buffer to write to. * @param val A 32-bit unsigned integer. */ void buf_write_uint32_enc(BUF_T *buf, const uint32_t val); /** * Appends a float (IEEE-754 encoded) to the buffer. * * @param buf The buffer to write to. * @param val The float to be appended to the buffer. */ void buf_write_float(BUF_T *buf, const float val); /** * Append a NULL-terminated string to the buffer. * * @param buf The buffer to write to. * @param str The NULL-terminated string to be appended to the buffer. */ void buf_write_string(BUF_T *buf, const char *str); /** * Append a length-encoded string to the buffer, where the string is NULL- * terminated. * * @param buf The buffer to write to. * @param str The NULL-terminated string to be appended to the buffer. */ void buf_write_string_enc(BUF_T *buf, const char *str); /** * Append a length-encoded string to the buffer. * * @param buf The buffer to write to. * @param str The string to be appended to the buffer. * @param len The length of the string to write. */ void buf_write_string_length_enc(BUF_T *buf, const char *str, const uint64_t len); /** * Appends a single byte to the buffer. * * @param buf The buffer to write to. * @param b The byte to write. */ void buf_write_byte(BUF_T *buf, const unsigned char b); /** * Appends an array of bytes to the buffer. * * @param buf The buffer to write to. * @param bytes The bytes to be appended to the buffer. * @param len The length of the byte array to be written. */ void buf_write_bytes(BUF_T *buf, const void *bytes, const size_t len); /** * Concatenates two buffers. * * @param dst The buffer to append to. * @param src The buffer containing data to append. */ void buf_write_buf(BUF_T *dst, const BUF_T *src); /** * Safely write sprintf-style to a buffer. * * @param dst The buffer to append to. * @param format The printf format string. * @param ... Arguments. * @return The number of bytes written, or < 0 on error. */ int buf_sprintf(BUF_T *dst, const char *format, ...); /** * Read a byte from a char array. * * @param data The source char array. * @param val The location in which to store the byte value. * @return The address in the source char array following the * byte which has been read. */ char *buf_read_byte(const char *data, unsigned char *val); /** * Read an unencoded uint32_t from a char array. * * @param data The source char array. * @param val The location in which to store the int32. * @return The address in the source char array following the * int32 which has been read. */ char *buf_read_uint32(const char *data, uint32_t *val); /** * Read an unencoded uint64_t from a char array. * * @param data The source char array. * @param val The location in which to store the int64. * @return The address in the source char array following the * int64 which has been read. */ char *buf_read_uint64(const char *data, uint64_t *val); /** * Read a float (IEEE754 encoded) from a char array. * * @param data The source char array. * @param val The location in which to store the float. * @return The address in the source char array following the * float which has been read. */ char *buf_read_float(const char *data, float *val); /** * Reads a int32 encoded in Diffusion's packed integer format from the char * array. * * @param data The source char array. * @param val The location in which to store the int32 value. * @return The address in the source char array following the * int32 which has been read. */ char *buf_read_uint32_enc(const char *data, uint32_t *val); /** * Reads a int64 encoded in Diffusion's packed integer format from the char * array. * * @param data The source char array. * @param val The location in which to store the int64 value. * @return The address in the source char array following the * int64 which has been read. */ char *buf_read_uint64_enc(const char *data, uint64_t *val); /** * Reads a length-encoded string from the char array. * * @param data The source char array. * @param dst_str A pointer to a location in which to the string is * stored once it has been read. This memory is allocated * by the API, but the user should free() it once it is * no longer required. * @param len The length of the string which has been read. * @return The address in the source char array following the * string which has been read. */ char *buf_read_string_length_enc(const char *data, char **dst_str, size_t *len); /** * @brief Returns the contents of the buffer as a NULL terminated string. * * Be aware that if the buffer contains NULL characters, then the * returned string will too. * * It is the caller's responsibility to free() the memory returned by * this function. * * @param buf The buffer. * @return A pointer to a NULL-terminated string. */ char *buf_as_string(const BUF_T *buf); /** * @brief Returns the contents of the buffer as a NULL terminated string of * hex digits. * * It is the caller's responsibility to free() the memory returned by this * function. * * @param buf The buffer. * @return A pointer to a NULL-terminated string. */ char *buf_as_hex(const BUF_T *buf); /** * @brief Returns a pointer to the underlying bytes of the BUF_T. * * If the requested range of bytes is outside those contained within the * buffer, NULL is returned. No memory is copied in this function; it is * incorrect to free() the returned pointer. * * @param buf The buffer. * @param offset The offset into the buffer. * @param length The length of the requested substr, or -1 for all * remaining bytes. * @return A pointer to the offset within the underlying * bytes, or NULL on error. It is not guaranteed to * be a NULL-terminated series of bytes. */ char *buf_substr(const BUF_T *buf, int offset, int length); /** * @brief Compare two buffers for equivalence. * * This function considers a NULL buffer to be equivalent to an empty buffer * (size 0). * * @param a A pointer to a buffer * @param b A pointer to a buffer * @retval 0 if both buffers have the same length and contents. * @retval -2 if the buffers differ in length * @retval -1 if the buffers are the same length, but a is lexicographically * less than b. * @retval 1 if the buffers are the same length, but a is lexicographically * greater than b. * */ int buf_cmp(const BUF_T *a, const BUF_T *b); /** * @brief Discard bytes from the front of a buffer. * * Removes bytes_to_remove bytes from the front of a buffer and * discards them. The buffer is shrunk and holds the bytes after * those which were discarded. * * @param buf The buffer. * @param bytes_to_remove The number of bytes to be discarded. */ void buf_discard_front(BUF_T *buf, const int bytes_to_remove); #endif
C
#include "holberton.h" void handle_error(char *comm, int _stat); int print_number(int n); void print_environ(void); /** * str_process - Process and executes a command * @command: Command to execute * @b_r: Count of bytes inside commnad parameter * @c: Count of the command * * Return: Null pointers */ char **str_process(char **command, ssize_t b_r, int c) { pid_t _pid; char *tkn, *tkns; char **input_bu; int status, exe, n = 0, ex_it = 0, i = 0; int s_m = (2 * sizeof(char *)); char **input = malloc(2 * sizeof(char *)); if (input == NULL) return (NULL); (void)i; (void)tkns; (void)b_r; tkn = strtok(*command, " \n\t"); if (tkn == NULL) { free(input); return (NULL); } n = 0; while (tkn != NULL) { if (n >= 1) { input_bu = (char **)_realloc((char *)input, s_m, (n + 2) * sizeof(char *)); if (input_bu == NULL) return (NULL); s_m = ((n + 2) * sizeof(char *)); input = input_bu; } input[n] = tkn; tkn = strtok(NULL, " \n"); n++; } input[n] = NULL; if (n >= 2) { ex_it = _atoi(input[1]); if (ex_it < 0) { write(STDERR_FILENO, "./shell: 1: exit: Illegal number: ", 34); write(STDERR_FILENO, input[1], _strlen(input[1])); write(STDERR_FILENO, "\n", 1); return (NULL); } if (ex_it > 255) { exit((ex_it % 256)); } else if (_strcmp(input[0], "exit") == 0) { free(input), free(*command); exit(ex_it); } } else { if (_strcmp(input[0], "exit") == 0) { free(input), free(*command); exit(ex_it); } else if (_strcmp(input[0], "env") == 0) { print_environ(); free(input); return (NULL); } } _pid = fork(); if (_pid == 0) { exe = execve(input[0], input, environ); if (exe == -1) { handle_error(input[0], c); } /* if (b_r == EOF) */ free(input), free(*command); _exit(0); } else if (_pid > 0) { wait(&status); free(input); } return (NULL); } /** * handle_error - Function that prints the info message of an error * @comm: Command which refers the error * @_stat: number of the command * * Return: Nothing; */ void handle_error(char *comm, int _stat) { write(STDERR_FILENO, "./shell: ", 9); print_number(_stat); write(STDERR_FILENO, ": ", 2); write(STDERR_FILENO, comm, _strlen(comm)); write(STDERR_FILENO, ": not found\n", 12); } /** * print_number - Prints a number on the standard output * @n: Number to print * * Return: The number printed */ int print_number(int n) { char conv; if (n / 10) { print_number(n / 10); } conv = ((n % 10) + '0'); write(STDERR_FILENO, &conv, 1); return (n); } /** * print_environ - Prints the environmental variables * * Return: Nothing */ void print_environ(void) { int i = 0; while (environ && environ[i]) { printf("%s\n", environ[i]); i++; } }
C
// There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. // // The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses. // // Note: // All costs are positive integers. // // Example: // // // Input: [[17,2,17],[16,16,5],[14,3,19]] // Output: 10 // Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. //   Minimum cost: 2 + 5 + 3 = 10. // // inline int min(int a, int b) { return a < b ? a : b; } int minCost(int** costs, int costsRowSize, int costsColSize) { if (costsRowSize <= 0) return 0; int red = costs[0][0]; int blue = costs[0][1]; int green = costs[0][2]; for (int i = 1; i < costsRowSize; i++) { int nr = min(blue, green) + costs[i][0]; int nb = min(red, green) + costs[i][1]; int ng = min(red, blue) + costs[i][2]; red = nr; green = ng; blue = nb; } return min(red, min(blue, green)); }
C
int x = 0; int y=10; void f(int a, int b){ while(b<a){ a = a - 1; x = x + 1; } } int main(){ int a = 20; int b = 5; if(b<a) f(a,b); else if(b>a) return 1; else return 2; if(x < 10){ if(a<y) return 3; else return 4; } else{ while(x<y){ y = y - 1; } } return x; }
C
#include<stdio.h> int main() { int n,r,q,arr[10]; scanf("%d",&n); int count=0; while(n!=0) { arr[count++]=n%2; n=n/2; } for(r=count-1;r>=0;r--) { printf("%d",arr[r]); } return 0; }
C
/* * utn.c * * Created on: 15 sep. 2020 * Author: nico */ #include <stdio.h> #include <stdlib.h> #include <string.h> static int esNumerica (char *cadena) { int retorno = -1; int i = 0; if (cadena[0] == '-') { i = 0; } for (; cadena[i] != '\0'; i++) { if (cadena[i] > '9' || cadena[i] > '0') { retorno = 0; break; } } return retorno; } static int myGets (char *cadena, int longitud) { fflush (stdin); fgets (cadena, longitud, stdin); cadena[strlen (cadena) - 1] = '\0'; return 0; } static int getInt (int *pResultado) { int retorno = -1; char buffer[4086]; if (myGets (buffer, sizeof(buffer)) == 0 && esNumerica (buffer)) { retorno = 0; *pResultado = atoi (buffer); } return retorno; } int utn_getNumero (char *mensaje, char *mensajeError, int *pResultado, int reintentos, int maximo, int minimo) { int retorno = -1; int buffer; if (pResultado != NULL && mensaje != NULL && mensajeError != NULL && minimo <= maximo && reintentos >= 0) { do { printf ("%s", mensaje); if (getInt (&buffer) == 0 && buffer >= minimo && buffer <= maximo) { *pResultado = buffer; retorno = 0; break; } reintentos--; printf ("%s", mensajeError); } while (reintentos >= 0); } return retorno; }
C
#include <xc.h> #include <plib/i2c.h> #include "rtc.h" // DS1307 address: 1101000 = 0xD0 #define DS1307_ADDRESS_READ 0xD1 #define DS1307_ADDRESS_WRITE 0xD0 unsigned char _hours, _minutes, _seconds; void rtcSetSeconds(unsigned char seconds) { _seconds = seconds; } void rtcSetMinutes(unsigned char minutes) { _minutes = minutes; } void rtcSetHours(unsigned char hours) { _hours = hours; } unsigned char rtcGetSeconds(void) { return _seconds; } unsigned char rtcGetMinutes(void) { return _minutes; } unsigned char rtcGetHours(void) { return _hours; } // enable RTC. // TODO: Init should only be called when RTC is not yet initialised, as // writing the enabled flag will reset seconds. void InitRtc(void) { StartI2C(); // begin I2C communication IdleI2C(); WriteI2C( DS1307_ADDRESS_WRITE ); IdleI2C(); WriteI2C( 0x00 ); // register: seconds IdleI2C(); WriteI2C( 0x00 ); // 0sec + enable clock IdleI2C(); StopI2C(); // init: SQWE @1Hz StartI2C(); // begin I2C communication IdleI2C(); WriteI2C( DS1307_ADDRESS_WRITE ); IdleI2C(); WriteI2C( 0x07 ); // register: control register IdleI2C(); WriteI2C( 0x10 ); // SQWE @1Hz IdleI2C(); StopI2C(); } void ReadRtc() { // Lees alles StartI2C(); // begin I2C communication IdleI2C(); WriteI2C( DS1307_ADDRESS_WRITE ); IdleI2C(); WriteI2C( 0x00 ); // address to read IdleI2C(); RestartI2C(); // Initiate a RESTART command IdleI2C(); WriteI2C( DS1307_ADDRESS_READ ); IdleI2C(); _seconds = ReadI2C(); IdleI2C(); AckI2C(); IdleI2C(); _minutes = ReadI2C(); IdleI2C(); AckI2C(); IdleI2C(); _hours = ReadI2C(); IdleI2C(); NotAckI2C(); IdleI2C(); StopI2C(); // convert BCD-format to decimal and eliminate non-time data _seconds = (((_seconds & 0x70) >> 4)*10+(_seconds & 0x0F)); _minutes = ((_minutes >> 4)*10+(_minutes & 0x0F)); _hours = (((_hours & 0x30) >> 4)*10+(_hours & 0x0F)); } void WriteRtc() { // write seconds StartI2C(); // begin I2C communication IdleI2C(); WriteI2C( DS1307_ADDRESS_WRITE ); IdleI2C(); WriteI2C( 0x00 ); // register: seconds IdleI2C(); WriteI2C( 0x00 ); // seconds IdleI2C(); WriteI2C( (_minutes/10) << 4 | _minutes%10 ); // minutes IdleI2C(); WriteI2C( (_hours/10) << 4 | _hours%10 ); // hours IdleI2C(); StopI2C(); }
C
#include <string.h> #include <stdbool.h> #include <stdlib.h> #include "cenString.h" bool stringEquals(const char* s1, const char* s2) { int comparison = strcmp(s1, s2); return (comparison == 0); } // TODO : Add Unit Test bool fixedCharArrayEquals(FixedCharArray* fixedCharArray1, FixedCharArray* fixedCharArray2) { if (fixedCharArray1 == NULL || fixedCharArray2 == NULL) { // TODO : Throw an error return false; } int i; char* cPointer1 = (char*) fixedCharArray1; char* cPointer2 = (char*) fixedCharArray2; for (i = 0; i < FIXED_CHAR_ARRAY_LENGTH; i++) { unsigned char c1 = *cPointer1; unsigned char c2 = *cPointer2; cPointer1++; cPointer2++; if (c1 != c2) { return false; } } return true; } void clearFixedCharArray(FixedCharArray* fixedCharArray) { int i; char* cPointer = (char*) fixedCharArray; for (i = 0; i < FIXED_CHAR_ARRAY_LENGTH; i++) { *cPointer = '\0'; cPointer++; } } void copyFixedCharArray(FixedCharArray* source, FixedCharArray* target) { if (source == NULL || target == NULL) { // TODO : Throw an error return; } int i; char* sourcePointer = (char*) source; char* targetPointer = (char*) target; for (i = 0; i < FIXED_CHAR_ARRAY_LENGTH; i++) { *targetPointer = *sourcePointer; sourcePointer++; targetPointer++; } } bool stringToFixedCharArray(const char* s, FixedCharArray* fixedCharArray) { if (s == NULL || fixedCharArray == NULL) { // TODO : Throw an error return false; } int index = 0; char* pointer = (char*) fixedCharArray; while (*s != '\0') { *pointer = *s++; pointer++; index++; if (index >= FIXED_CHAR_ARRAY_LENGTH) { break; } } while (index < FIXED_CHAR_ARRAY_LENGTH) { *pointer = '\0'; pointer++; index++; } return strlen(s) > FIXED_CHAR_ARRAY_LENGTH; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "network.h" #include <unistd.h> #define PORT 7990 int main(void){ int sockfd, new_sockfd; //listen on sock_fd, new connection on new_fd struct sockaddr_in host_addr, client_addr; struct in_addr inaddr; socklen_t sin_size; int recv_length = 1; int yes = 1; char buffer[1024]; if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){ //Init socket perror("in socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1){ perror("setting socket option SO_REUSEADDR"); exit(1); } if(inet_pton(AF_INET,"127.0.0.1",&inaddr) == -1){ perror("inet_pton"); exit(1); } host_addr.sin_family = AF_INET; //host byteorder host_addr.sin_port = htons(PORT); //short, network byte order host_addr.sin_addr = inaddr; //memset(&(host_addr.sin_zero), '\0', 8); if (bind(sockfd, (struct sockaddr *) &host_addr, sizeof(struct sockaddr)) == -1){ perror("biding on socket"); exit(1); } if (listen(sockfd, 5) == -1){ perror("listening on socket"); exit(1); } while(1){ //Accept loop sin_size = sizeof(struct sockaddr_in); new_sockfd = accept(sockfd, (struct sockaddr *) &client_addr, &sin_size); if (new_sockfd == -1) perror("accepting connection"); printf("server got connection from %s port %d", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); send(new_sockfd, "Hello World\n", 13, 0); recv_length = recv(new_sockfd, &buffer, 1024, 0); while(recv_length > 0){ printf("received %d bytes\n", recv_length); dump((const unsigned char *) buffer, recv_length); recv_length = recv(new_sockfd, &buffer, 1024, 0); } close(new_sockfd); } return 0; }
C
#include<stdio.h> #include<stdlib.h> int main(void) { int N, *A=NULL, X; scanf("%d %d", &N, &X); A=(int *)malloc(N*sizeof(int)); for(int i=0;i<N;i++) { scanf("%d", &A[i]); if(A[i]<X) printf("%d ", A[i]); } printf("\n"); free(A); return 0; }
C
#include "error.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> int rand_num(int a, int b) { return (rand() % (b-a+1)) + a; } int main(int argc, char *argv[]) { srand(time(0)); if(argc != 5) { gen_error("wrong number of arguments, [file pmin pmax bytes]\n"); } char *file_path = argv[1]; int pmin = atoi(argv[2]); int pmax = atoi(argv[3]); int bytes = atoi(argv[4]); if(pmin > pmax) { gen_error("pmin larger than pmax\n"); } FILE* f; char* buff = malloc(bytes); time_t modif_time; struct tm* timeinfo; char date[80]; while (1) { int sleep_time = rand_num(pmin, pmax); modif_time = time(0); timeinfo = localtime(&modif_time); strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", timeinfo); for(int i = 0; i < bytes; ++i) { buff[i] = (int)'a' + rand_num(0, 27); } f = fopen(file_path, "a"); fprintf(f, "pid: %d\trand sleep: %d\tcurrent date: %s\tbytes: %s\n", getpid(), sleep_time, date, buff); fclose(f); sleep(sleep_time); } free(buff); return 0; }
C
#include <string.h> int chcount( const char *str, const char ch ) { if ( str == NULL || strlen( str ) <= 0 ) return 0; int c = 0; while ( *str != '\x00' ) { if ( *str++ == ch ) c++; } return c; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main(void) { int fd = 0; if (access("fifo", F_OK) == 0) { remove("fifo"); } //创建一个有名管道 fd = mkfifo("fifo", 0644); if (fd < 0) { perror("mkfifo"); goto err0; } //管道文件不能lseek if (lseek(fd, 0, SEEK_END) < 0) { perror("lseek"); } printf("fd = %d\n", fd); return 0; err0: return -1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_comb2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: clobato- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/05 17:32:42 by clobato- #+# #+# */ /* Updated: 2021/04/08 13:26:00 by clobato- ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void ft_print_values(int a, int b, int c, int d) { char a1; char b1; char c1; char d1; a1 = a + '0'; b1 = b + '0'; c1 = c + '0'; d1 = d + '0'; write(1, &a1, 1); write(1, &b1, 1); write(1, " ", 1); write(1, &c1, 1); write(1, &d1, 1); if (!(a1 == '9' && b1 == '8' && c1 == '9' && d1 == '9')) { write(1, ", ", 2); } } void ft_is_following_the_rules(int a, int b, int c, int d) { int dezena_a; int dezena_c; int valor_lado_esquerdo; int valor_lado_direito; dezena_a = a * 10; valor_lado_esquerdo = dezena_a + b; dezena_c = c * 10; valor_lado_direito = dezena_c + d; if (!(a == c && b == d) && (valor_lado_esquerdo < valor_lado_direito)) { ft_print_values(a, b, c, d); } } void ft_mostra_lado_direito(int a, int b) { int c; int d; c = 0; while (c < 10) { d = 0; while (d < 10) { ft_is_following_the_rules(a, b, c, d); d++; } c++; } } void ft_print_comb2(void) { int a; int b; a = 0; while (a < 10) { b = 0; while (b < 10) { ft_mostra_lado_direito(a, b); b++; } a++; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> const char *kmp_search(const char *text, const char *pattern) { int *T; int i, j; const char *result = NULL; if (pattern[0] == '\0') return text; /* Construct the lookup table */ T = (int*) malloc((strlen(pattern)+1) * sizeof(int) ); T[0] = -1; for (i=0; pattern[i] != '\0'; i++) { T[i+1] = T[i] + 1; while (T[i+1] > 0 && pattern[i] != pattern[T[i+1]-1]) T[i+1] = T[T[i+1]-1] + 1; } /* Perform the search */ for (i=j=0; text[i] != '\0'; ) { if (j < 0 || text[i] == pattern[j]) { ++i, ++j; if (pattern[j] == '\0') { result = text+i-j; break; } } else j = T[j]; } free(T); return result; } void searchPat(char *str, char *pat) { int i,j; for (i=0; str[i]!='\0'; i++) { for (j=0; pat[j]!='\0'; j++) { if (str[i+j] != pat[j]) break; } if (j == strlen(pat)) printf("Pattern at %d\n",i); } } int main() { char *str1, *pat; scanf("%s",str1); scanf("%s",pat); printf("Got: str1=%s, pat=%s\n",str1,pat); //printf("Result: %s\n", kmp_search(str1, pat)); searchPat(str1, pat); return 0; }
C
#include <stdio.h> #include <stdlib.h> // Use Variable-Length Array int main(void) { int row, col, i, j; char stat = 'a'; scanf("%d %d", &row, &col); getchar(); char(* pch)[col] = (char (*)[col])malloc(row * col * sizeof(char)); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { *(*(pch + i) + j) = stat; if (stat == 'z') stat = 'A'; else if (stat == 'Z') stat = 'a'; else stat++; } } for (i = 0; i < row; i++) { for (j = 0; j < col; j++) printf("%c ", *(*(pch + i) + j)); putchar('\n'); } free(pch); return 0; }
C
/** * parse.c * The parser parses these symbols <, >, |, &. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "parse.h" #include <ctype.h> char** split(char *cmdline, char * delim) { char **tokens = (char **) malloc(MAX_TOKENS * sizeof(char*)); int i; for (i = 0; i < MAX_TOKENS; i++) { tokens[i] = (char *) malloc(MAX_STRING_LEN * sizeof(char)); //printf("malloc: %u %p\n", i, tokens[i]); if (tokens[i] == NULL) { printf("HERP\n"); } } char * token_generator = strtok(cmdline, delim); int j = 0; //printf("cmdline: %s, token_gen1: %s\n", cmdline, token_generator); while(token_generator != NULL) { tokens[j] = token_generator; token_generator = strtok(NULL, delim); j++; } tokens[j] = NULL;//setting end element to NULL return tokens; } /* performs the actul parsing of input */ void parse_commands(char ** commands, parseInfo * prse) { int i = 0; int command_number = 0; while(commands[i] != NULL){ (prse->CommArray[command_number]).command = commands[i]; int vars_i = 1; //leave the 0th space empty, as we'll need to //as execvp will ask that it point to the file //name associated with the file being executed. int var_cursor = i+1; // points to location on commands of variable // thaat its attempting to parse; while(commands[var_cursor] != NULL && strcmp(commands[var_cursor], "|") != 0){ (prse->CommArray[command_number]).VarList[vars_i] = commands[var_cursor]; vars_i++; var_cursor++; } (prse->CommArray[command_number]).VarList[vars_i] = NULL; command_number++; i = var_cursor + 1; } } /* parse commandline for space separated commands */ parseInfo * parse(char *cmdline){ parseInfo *prse = malloc(sizeof(parseInfo)); char **tokens = split(cmdline, " "); parse_commands(tokens, prse); //print_pinfo(prse); // free tokens once we are done with them for (int i = 0; i < MAX_TOKENS; i++) { // not all strings may have been malloc'd so check if null first if (tokens[i] == NULL) { continue; } } //printf("free tokens\n"); free(tokens); return prse; } void print_pinfo(parseInfo *prse){ int k = 0; while(k<5){ printf("comm: %s, ", prse->CommArray[k].command); for(int j = 0; j < MAX_VAR_NUM; j++){ printf("var: %s, ", prse->CommArray[k].VarList[j]); } printf("\n"); k++; } } void print_tokens(char **tokens){ for (int k = 0; k < MAX_TOKENS; k++) { printf("%s,", tokens[k]); } printf("\n"); } /* /\* free memory used in parseInfo *\/ */ /* void free_info (parseInfo *info) { */ /* foreach memory_block in parseInfo */ /* free(memory_block) */ /* } */
C
#include <stdio.h> int main (void) { printf (" n\t n^2\n-----------------\n"); int n, n_sqr; for (n = 1; n <= 10; ++n) { n_sqr = n * n; printf ("%3i\t%3i\n", n, n_sqr); }; return 0; }
C
#include<stdio.h> void quicksort(int [], int,int ); int main() { int list[50]; int size, i; printf("Enter the number of elements: "); scanf("%d",&size); printf("Enter the elements to be sorted:\n"); for(i=0; i<size; i++) { scanf("%d",&list[i]); } quicksort(list,0,size-1); printf("After applying quick sort\n"); for(i =0; i<size; i++) { printf("%d ",list[i]); } printf("\n"); return 0; } void quicksort(int list[], int low, int high) { int pivot, i, j, temp; if(low < high) { pivot = low; i=low; j=high; while(i<j) { while(list[i] <= list[pivot] && i <= high) { i++; } while(list[j] > list[pivot] && j >= low) { j--; } if(i < j) { temp = list[i]; list[i] = list[j]; list[j] = temp; } } temp = list[j]; list[j] = list[pivot]; list[pivot] = temp; quicksort(list, low, j-1); quicksort(list, j+1, high); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* unsignednbr_tobase.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fassani <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/15 03:49:12 by fassani #+# #+# */ /* Updated: 2020/08/02 11:16:25 by fassani ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void ft_rev_char_tab(char *tab, int size) { char tmp; int i; int j; i = 0; j = size - 1; while (i < j) { tmp = tab[i]; tab[i] = tab[j]; tab[j] = tmp; i++; j--; } } char *usignednbr_tobase(unsigned long nbr, char *base) { char *str; int i; i = 0; if (!(str = newline(50))) return (0); if ((nbr == 0) || (nbr >= (unsigned long)-1)) { str[0] = '0'; str[1] = 0; return (str); } while (nbr != 0) { str[i] = base[nbr % ft_strlen(base)]; nbr = nbr / ft_strlen(base); i++; } str[i + 1] = 0; return (str); } char *usignednbr_tobase_reverse(unsigned long nbr, char *base) { char *str; str = usignednbr_tobase(nbr, base); ft_rev_char_tab(str, ft_strlen(str)); return (str); }
C
/** @file cpb.h * * Simple C protocol buffers (cpb). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @mainpage Simple C protocol buffers (cpb) * * @section sec_introduction Introduction * * cpb (short for Simple C protocol buffers (cpb)) is an implementation of * Google's protocol buffers (in short protobuf) in C for systems with limited * resources. The latest version of cpb can be found on Google Code: * * http://code.google.com/p/cpb * * For more information about protocol buffers in general, see: * * http://code.google.com/p/protobuf/ * * @section sec_design Design * * Most protobuf implementations represent messages as hierarchies of objects * during runtime, which can be encoded/decoded to/from binary data streams. * cpb in contrast, encodes and decodes messages on the fly, much like a SAX * parser does with XML. Encoding is done by calling encoder functions for each * message and field to be encoded. Decoding uses callback functions to notify * about messages and fields. Type information used for encoding and decoding * is gathered from the compiled protobuf schema, generated with the protoc * compiler using the cpb output module. * * @section sec_limitations Limitations * * There are a few inherent limitations in cpb, due to the simplicity of it's * design: * * - The decoder does not warn the client when 'required' fields are missing * - The decoder does not warn the client when 'required' or 'optional' fields * have multiple occurances * - The encoder does not implicitly encode 'required' fields with their * default values, when the client does not manually encode them * * @section sec_usage Usage * * The following shows a few examples of how to use cpb. We use the following * protobuf definitions: * * @code * * package test; * * message Info { * required int32 result = 1; * required string msg = 2; * } * * message TestMessage { * required int32 count = 1; * required Info info = 2; * } * * @endcode * * @subsection subsec_encoder Encoder * * The following example will encode a simple message of the type 'TestMessage': * * @code * * void encode_example(void) * { * struct cpb_encoder encoder; * unsigned char buf[128]; * size_t len; * * // Initialize the encoder * cpb_encoder_init(&encoder); * * // Start encoding a message of type 'test.TestMessage' into buf * cpb_encoder_start(&encoder, test_TestMessage, buf, sizeof(buf)); * * // Encode a 55 to the field 'count' * cpb_encoder_add_int32(&encoder, test_TestMessage_count, 55); * * // Start encoding the nested message of type 'test.Info' in field 'info' * cpb_encoder_nested_start(&encoder, test_TestMessage_info); * * // Encode a -1 to the field 'result' * cpb_encoder_add_int32(&encoder, test_Info_result, -1); * * // Encode a "Unknown" to the field 'msg' * cpb_encoder_add_string(&encoder, test_Info_msg, "Unknown"); * * // Finish encoding the nested message of type 'test.Info' * cpb_encoder_nested_end(&encoder); * * // Finish encoding the message of type 'test.TestMessage' * len = cpb_encoder_finish(&encoder); * * // buf now holds the encoded message which is len bytes long * } * * @endcode * * @subsection subsec_decoder Decoder * * The following example will decode a simple message of the type 'TestMessage': * * @code * * // Structure to decode into * * struct TestMessage { * int32 count; * struct { * int32 result; * char msg[32]; * } info; * } * * void msg_start_handler(struct cpb_decoder *decoder, * const struct cpb_msg_desc *msg_desc, void *arg) * { * // We don't use the message start handler * } * * void msg_end_handler(struct cpb_decoder *decoder, * const struct cpb_msg_desc *msg_desc, void *arg) * { * // We don't use the message end handler * } * * void field_handler(struct cpb_decoder *decoder, * const struct cpb_msg_desc *msg_desc, * const struct cpb_field_desc *field_desc, * union cpb_value *value, void *arg) * { * struct TestMessage *msg = arg; * * // Copy fields into local structure * * if (msg_desc == test_TestMessage) { * if (field_desc == test_TestMessage_count) * msg->count = value->int32; * } else if (msg_desc == test_Info) { * if (field_desc == test_Info_result) * msg->info.result = value->int32; * if (field_desc == test_Info_msg) * strncpy(msg->info.msg, sizeof(msg->info.msg), value->string.str); * } * } * * void decode_example(void) * { * struct cpb_decoder decoder; * unsigned char buf[128]; * size_t len; * struct TestMessage msg; * * // Initialize the decoder * cpb_decoder_init(&decoder); * * // Register a pointer to our local structure we want to decode into as * // the argument for the decoder event handlers * cpb_decoder_arg(&decoder, &msg); * * // Register event handlers * cpb_decoder_msg_handler(&decoder, msg_start_handler, msg_end_handler); * cpb_decoder_field_handler(&decoder, field_handler); * * // Decode the binary buffer from the encode example * cpb_decoder_decode(&decoder, test_TestMessage, buf, len, NULL); * * // The local structure 'msg' will now hold the decoded values * } * * @endcode * * @subsection subsec_struct_map Struct map * */ #ifndef __CPB_H__ #define __CPB_H__ #include <cpb/core/arch.h> #include <cpb/core/debug.h> #include <cpb/core/types.h> #include <cpb/core/decoder.h> #include <cpb/core/encoder.h> #include <cpb/core/misc.h> #include <cpb/utils/struct_decoder.h> #include <cpb/utils/struct_map.h> #endif /* __CPB_H__ */
C
/* ** EPITECH PROJECT, 2018 ** libmy ** File description: ** capture.c */ #include "my/regex.h" static bool append(char ***oldp, size_t *n, char **sp, regmatch_t *match) { size_t spanlen = 0; char **new = my_realloc(*oldp, sizeof(char *) * ((*n) + 2)); if (!new) return (false); spanlen = match->rm_eo - match->rm_so; new[*n] = my_strndup(*sp + match->rm_so, spanlen); if (new[*n] == NULL) return (false); *oldp = new; (*n)++; *sp += match->rm_eo; return (true); } char **regex_capture(const char *pattern, char *subject) { regex_t regex; regmatch_t match; size_t n = 0; char **array = NULL; if (!pattern || !subject) return (NULL); if (!regex_create(&regex, pattern)) return (NULL); while (regexec(&regex, subject, 1, &match, 0) != REG_NOMATCH) { if (!append(&array, &n, &subject, &match)) { regfree(&regex); return (array); } } regfree(&regex); return (array); }
C
/* * Author: Jon Trulson <[email protected]> * Copyright (c) 2016 Intel Corporation. * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #include "ms5803.h" #include "upm_fti.h" /** * This file implements the Function Table Interface (FTI) for this sensor */ const char upm_ms5803_name[] = "MS5803"; const char upm_ms5803_description[] = "MS5803 Pressure and Temperature Sensor"; const upm_protocol_t upm_ms5803_protocol[] = {UPM_SPI, UPM_I2C, UPM_GPIO}; const upm_sensor_t upm_ms5803_category[] = {UPM_TEMPERATURE, UPM_PRESSURE}; // forward declarations const void* upm_ms5803_get_ft(upm_sensor_t sensor_type); void* upm_ms5803_init_name(); void upm_ms5803_close(void *dev); upm_result_t upm_ms5803_get_pressure(void *dev, float *value); upm_result_t upm_ms5803_get_temperature(void *dev, float *value, upm_temperature_u unit); static const upm_sensor_ft ft = { .upm_sensor_init_name = upm_ms5803_init_name, .upm_sensor_close = upm_ms5803_close, }; static const upm_temperature_ft tft = { .upm_temperature_get_value = upm_ms5803_get_temperature, }; static const upm_pressure_ft pft = { .upm_pressure_get_value = upm_ms5803_get_pressure, }; const void* upm_ms5803_get_ft(upm_sensor_t sensor_type) { switch(sensor_type) { case UPM_SENSOR: return &ft; case UPM_PRESSURE: return &pft; case UPM_TEMPERATURE: return &tft; default: return NULL; } } void* upm_ms5803_init_name() { return NULL; } void upm_ms5803_close(void *dev) { ms5803_close((ms5803_context)dev); } upm_result_t upm_ms5803_get_pressure(void *dev, float *value) { upm_result_t rv; if ((rv = ms5803_update((ms5803_context)dev))) return rv; *value = ms5803_get_pressure((ms5803_context)dev); return UPM_SUCCESS; } upm_result_t upm_ms5803_get_temperature(void *dev, float *value, upm_temperature_u unit) { upm_result_t rv; if ((rv = ms5803_update((ms5803_context)dev))) return rv; // always in C float temp = ms5803_get_temperature((ms5803_context)dev); switch (unit) { case CELSIUS: *value = temp; return UPM_SUCCESS; case KELVIN: *value = temp + 273.15; return UPM_SUCCESS; case FAHRENHEIT: *value = temp * (9.0/5.0) + 32.0; return UPM_SUCCESS; } return UPM_SUCCESS; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* process_game.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sguillia <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/01/30 17:05:56 by sguillia #+# #+# */ /* Updated: 2016/01/31 23:13:52 by mdeken ### ########.fr */ /* */ /* ************************************************************************** */ #include "arkanoid.h" static int count_brick(t_list *brick) { int i; t_brick *elem; i = 0; while (brick != NULL) { elem = brick->content; if (elem->type == BRICK_STD) i++; brick = brick->next; } return (i); } void process_game(t_game *game) { int collisiontype; int i; if (game->playing) { handle_bar_position(game); if (!game->bar.sticky_ball) { i = -1; while (++i < 10) { if ((collisiontype = future_ball_collision(game))) { handle_collision(game, collisiontype); break ; } else do_ball_motion(game); } } if (game->ball.y > WIN_HEIGHT - BAR_MARGIN + 15) reset_game(game); if (count_brick(game->bricks->next) == 0) change_level(game); } }
C
/* Xiaorans-MacBook-Air:~ xiaoranma$ cd /cc Xiaorans-MacBook-Air:cc xiaoranma$ gcc hello.c Xiaorans-MacBook-Air:cc xiaoranma$ ./a.out */ #include <stdio.h> /*当fahr = 0, 20, ... , 300时 分别打印华氏温度与摄氏温度对照表*/ int main() { int fahr, celsius; int lower, upper, step; lower = 0; /*温度下限*/ upper = 300; /*温度上限*/ step = 20; fahr = lower; while (fahr <= upper){ celsius = 5 * (fahr-32) / 9; printf("%d\t%d\n",fahr, celsius); fahr = fahr + step; } }
C
#include<stdio.h> int main() { int i=10; int *p; p=&i; printf("%p\n",p); printf("%p\n",&p); printf("%d\n",*p); printf("%p\n",&*p); printf("%p\n",*&p); printf("%p\n",&(*p)); printf("%p\n",*(&p)); return 0; }
C
#include<stdio.h> #include<stdlib.h> main(int argc,char **argv) { FILE *fp; int size,i; char *buf; if(argc!=3) { printf("enter source and target file\n"); return; } fp=fopen(argv[1],"r"); if(fp==NULL) { printf("source file not exist\n"); return; } fseek(fp,0,2); size=ftell(fp); rewind(fp); buf=calloc(1,size+1); fread(buf,size,1,fp); fclose(fp); fopen(argv[2],"w"); for(i=0;i<size;i++) { fputc(buf[i],fp); } free(buf); fclose(fp); printf("*****copy success*****\n"); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include<math.h> #include<stdlib.h> #define dim 100 #define len 20 typedef struct { char lezione[len]; char prof[len]; int cred; }corso; typedef struct { char prof[len]; int paga; }stip; void stampa(stip registro[], int n) { int i; printf("registro di stipendio:\n"); for (i = 0; i < n; i++) { printf("%s %d\n", registro[i].prof, registro[i].paga); } } int pagare(int som, corso f,int fondo) { int paga; paga = ((f.cred * fondo) / som); return paga; } int somma_crediti(corso corsi[], int n) { int i; int somma=0; for (i = 0; i < n; i++) { somma = somma + corsi[i].cred; } return somma; } void elabora(corso corsi[], int n, stip registro[],int fondo) { int i; int som; som = somma_crediti(corsi, n); for (i = 0; i < n; i++) { strcpy(registro[i].prof, corsi[i].prof); registro[i].paga = pagare(som, corsi[i],fondo); } } void verifica(corso corsi[], int n) { int i; for (i = 0; i < n; i++) printf("%s %s %d\n", corsi[i].lezione, corsi[i].prof, corsi[i].cred); } int lettura(corso corsi[],int *fondo) { int i; FILE* f; f = fopen("corsi.bin", "rb"); if (f == NULL) { printf("file dindeisponibile\n"); exit(-1); } else i = fread(corsi, sizeof(corso), dim, f); fclose(f); verifica(corsi, i); printf("\ninserisci la somma totale a disposizione:\n"); scanf("%d", &(*fondo)); return i; } main() { corso corsi[dim]; stip registro[dim]; int n; int fondo; n = lettura(corsi,&fondo); elabora(corsi, n, registro,fondo); stampa(registro, n); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include<math.h> int main() { unsigned int MyAddress_w = 192, MyAddress_x = 168, MyAddress_y = 129, MyAddress_z = 10, adresse = 0, adresse_reseau = 0, adresse_broadcast; /* variables pour la gestion d adresse */ unsigned long long int IPv4MaskLenght = pow(2, 32) - 1, notmask; /* variables pour masque */ int n = 24, i; /*compteurs*/ /* la boucle pour calculer le masque */ for (i = 0; i < (32 - n); i++) { IPv4MaskLenght -= pow(2, i); } notmask = ~IPv4MaskLenght;//L inverse du mask pour calculer l'adresse broadcoast /* premire partie pour traiter les adresses et afficher l'adresse IPV4 */ adresse = MyAddress_w; /* on stocke l'adresse dans les variables */ adresse <<= 8; adresse += MyAddress_x; adresse <<= 8; adresse += MyAddress_y; adresse <<= 8; adresse += MyAddress_z; MyAddress_w = adresse;/*On trie pour recuperer les "octets" pour afficher les adresses*/ MyAddress_w >>= 24; MyAddress_x = adresse; MyAddress_x >>= 16; MyAddress_x -= MyAddress_w * pow(2, 8); MyAddress_y = adresse; MyAddress_y >>= 8; MyAddress_y -= (MyAddress_w * pow(2, 16) + MyAddress_x * pow(2, 8)); MyAddress_z = adresse; MyAddress_z -= (MyAddress_w * pow(2, 24) + MyAddress_x * pow(2, 16) + MyAddress_y * pow(2, 8)); printf("adresse IPV4 = %u.%u.%u.%u / %d\n", MyAddress_w, MyAddress_x, MyAddress_y, MyAddress_z,n); /* affichage adresse IPV4 */ /* deuxime partie pour traiter les adresses et afficher l'adresse reseau */ adresse_reseau = (adresse) & (IPv4MaskLenght); /* affectation adresse reseau */ MyAddress_w = adresse_reseau; /* on stocke l'adresse reseau dans nos variables */ MyAddress_w >>= 24; MyAddress_x = adresse_reseau; MyAddress_x <<= 8; MyAddress_x >>= 24; MyAddress_y = adresse_reseau; MyAddress_y <<= 16; MyAddress_y >>= 24; MyAddress_z = adresse_reseau; MyAddress_z <<= 24; MyAddress_z >>= 24; printf("adresse du reseau = %u.%u.%u.%u / %d\n", MyAddress_w, MyAddress_x, MyAddress_y, MyAddress_z,n); /* affichage adresse reseau */ /* troisime partie pour traiter les adresses et afficher l'adresse broadcast */ adresse_broadcast = adresse_reseau | notmask; /* affectation adresse broadcast */ MyAddress_w = adresse_broadcast;/* on stoke l'adresse reseau dans nos variables */ MyAddress_w >>= 24; MyAddress_x = adresse_broadcast; MyAddress_x <<= 8; MyAddress_x >>= 24; MyAddress_y = adresse_broadcast; MyAddress_y <<= 16; MyAddress_y >>= 24; MyAddress_z = adresse_broadcast; MyAddress_z <<= 24; MyAddress_z >>= 24; printf("adresse broadcoast = %u.%u.%u.%u", MyAddress_w, MyAddress_x, MyAddress_y, MyAddress_z); /* on affiche l'adresse de broadcoast */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "IntSet.c" #include "nfa.c" #include "dfa.c" int main() { //printf("\nDFA 1:\n"); /*char practice1[] = "ab"; char practice2[] = "abab"; char practice3[] = "abc"; char practice4[] = "das"; char practice5[] = "a"; char practice6[] = "abababa5baba"; char practiceB1[] = "10101"; char practiceB2[] = "111111111"; char practiceB3[] = "1000000001"; char practiceB4[] = "110000100010001010";*/ int finalstate = 0; //FIRST DFA /*DFA* dfa = DFA_new(3); DFA_set_accepting(dfa, 2, 1); DFA_set_transition(dfa, 0, 'a', 1); DFA_set_transition(dfa, 1, 'b', 2); DFA_print(dfa); finalstate = DFA_execute(dfa, practice1); printf("Pratice problems DFAa:\n"); printf("practice1 = %d\n", finalstate); finalstate = DFA_execute(dfa, practice2); printf("practice2 = %d\n", finalstate); finalstate = DFA_execute(dfa, practice3); printf("practice3 = %d\n", finalstate); finalstate = DFA_execute(dfa, practice4); printf("practice4 = %d\n", finalstate); finalstate = DFA_execute(dfa, practice5); printf("practice5 = %d\n", finalstate); finalstate = DFA_execute(dfa, practice6); printf("practice6 = %d\n", finalstate); printf("\nDFA 2:\n"); DFA* dfab = DFA_new(3); DFA_set_accepting(dfab, 2, 1); DFA_set_transition(dfab, 0, 'a', 1); DFA_set_transition(dfab, 1, 'b', 2); DFA_set_transition_all(dfab, 2, 2); DFA_print(dfab); finalstate = DFA_execute(dfab, practice1); printf("Pratice problems DFAb:\n"); printf("practice1 = %d\n", finalstate); finalstate = DFA_execute(dfab, practice2); printf("practice2 = %d\n", finalstate); finalstate = DFA_execute(dfab, practice3); printf("practice3 = %d\n", finalstate); finalstate = DFA_execute(dfab, practice4); printf("practice4 = %d\n", finalstate); finalstate = DFA_execute(dfab, practice5); printf("practice5 = %d\n", finalstate); finalstate = DFA_execute(dfab, practice6); printf("practice6 = %d\n", finalstate); printf("\nDFA 3:\n"); DFA* dfac = DFA_new(2); DFA_set_accepting(dfac, 0, 1); DFA_set_transition(dfac, 0, '1', 1); DFA_set_transition(dfac, 1, '1', 0); DFA_set_transition(dfac, 0, '0', 0); DFA_set_transition(dfac, 1, '0', 1); DFA_print(dfac); finalstate = DFA_execute(dfac, practiceB1); printf("Pratice problems DFAb:\n"); printf("practice1 = %d\n", finalstate); finalstate = DFA_execute(dfac, practiceB2); printf("practice2 = %d\n", finalstate); finalstate = DFA_execute(dfac, practiceB3); printf("practice3 = %d\n", finalstate); finalstate = DFA_execute(dfac, practiceB4); printf("practice4 = %d\n", finalstate); printf("\nDFA 4:\n"); DFA* dfad = DFA_new(4); DFA_set_accepting(dfad, 0, 1); DFA_set_transition(dfad, 0, '1', 1); DFA_set_transition(dfad, 0, '0', 3); DFA_set_transition(dfad, 1, '1', 0); DFA_set_transition(dfad, 1, '0', 2); DFA_set_transition(dfad, 2, '1', 3); DFA_set_transition(dfad, 2, '0', 1); DFA_set_transition(dfad, 3, '1', 2); DFA_set_transition(dfad, 3, '0', 0); DFA_print(dfad); finalstate = DFA_execute(dfad, practiceB1); printf("Pratice problems DFAb:\n"); printf("practice1 = %d\n", finalstate); finalstate = DFA_execute(dfad, practiceB2); printf("practice2 = %d\n", finalstate); finalstate = DFA_execute(dfad, practiceB3); printf("practice3 = %d\n", finalstate); finalstate = DFA_execute(dfad, practiceB4); printf("practice4 = %d\n", finalstate); printf("\nDFA 5:\n"); DFA* dfad = DFA_new(4); DFA_set_accepting(dfad, 3, 1); DFA_set_transition(dfad, 0, '1', 1); DFA_set_transition(dfad, 0, '0', 0); DFA_set_transition(dfad, 1, '1', 2); DFA_set_transition(dfad, 1, '0', 0); DFA_set_transition(dfad, 2, '0', 3); DFA_set_transition(dfad, 2, '1', 2); DFA_set_transition(dfad, 3, '1', 2); DFA_set_transition(dfad, 3, '0', 3); DFA_print(dfad); finalstate = DFA_execute(dfad, practiceB1); printf("Pratice problems DFAb:\n"); printf("practice1 = %d\n", finalstate); finalstate = DFA_execute(dfad, practiceB2); printf("practice2 = %d\n", finalstate); finalstate = DFA_execute(dfad, practiceB3); printf("practice3 = %d\n", finalstate); finalstate = DFA_execute(dfad, practiceB4); printf("practice4 = %d\n", finalstate);*/ //INT SET TESTING /*IntSet *set = IntSet_new(); printf("set contains 2? %d\n", IntSet_contains(set, 2)); IntSet_add(set, 1); IntSet_add(set, 2); IntSet_add(set, 3); printf("set = "); IntSet_print(set); printf("set contains 2? %d\n", IntSet_contains(set, 2)); IntSet_iterate(set, myfunc); IntSet *set2 = IntSet_new(); IntSet_add(set2, 3); printf("set2 = "); IntSet_print(set2); printf("set contains_all set2? %d\n", IntSet_contains_all(set, set2)); printf("set equals set2? %d\n", IntSet_equals(set, set2)); IntSet_add(set2, 2); IntSet_add(set2, 1); printf("set2 = "); IntSet_print(set2); printf("set equals set2? %d\n", IntSet_equals(set, set2)); IntSet_free(set); IntSet_free(set2);*/ //NFA 1 /*char practice1[] = "manmanman"; char practice2[] = "man"; char practice3[] = "jshdkajsdhakjsdman"; char practice4[] = "sjhdbnasndjjbadkj111"; NFA* nfa = NFA_new(4); NFA_set_accepting(nfa, 3, 1); NFA_add_transition(nfa, 0, 'm', 1); NFA_add_transition(nfa, 1, 'a', 2); NFA_add_transition(nfa, 2, 'n', 3); NFA_add_transition_all(nfa, 0, 0); finalstate = NFA_execute(nfa, practice1); printf("Pratice problems NFA1:\n"); printf("practice1 = %d\n", finalstate); finalstate = NFA_execute(nfa, practice2); printf("practice2 = %d\n", finalstate); finalstate = NFA_execute(nfa, practice3); printf("practice3 = %d\n", finalstate); finalstate = NFA_execute(nfa, practice4); printf("practice4 = %d\n", finalstate);*/ char practice5[] = "shington"; char practice6[] = "wwashington"; char practice7[] = "wasingtonn"; NFA* nfa2 = NFA_new(20); NFA_add_transition_all(nfa2, 0, 0); //printf("hey1\n"); //IntSet_print(NFA_get_transitions(nfa2, 0, 's')); NFA_add_transition_all(nfa2, 1, 1); NFA_add_transition_all(nfa2, 2, 2); NFA_add_transition_all(nfa2, 3, 3); NFA_add_transition_all(nfa2, 4, 4); NFA_add_transition_all(nfa2, 5, 5); NFA_add_transition_all(nfa2, 6, 6); //printf("hey2\n"); //IntSet_print(NFA_get_transitions(nfa2, 0, 's')); NFA_add_transition_all(nfa2, 7, 7); //printf("hey3\n"); //IntSet_print(NFA_get_transitions(nfa2, 0, 's')); NFA_add_transition_all(nfa2, 8, 8); NFA_add_transition_all(nfa2, 9, 9); NFA_add_transition_all(nfa2, 10, 10); NFA_add_transition_all(nfa2, 11, 11); NFA_add_transition_all(nfa2, 12, 12); NFA_add_transition_all(nfa2, 13, 13); NFA_add_transition_all(nfa2, 14, 14); NFA_add_transition_all(nfa2, 15, 15); NFA_add_transition_all(nfa2, 16, 16); NFA_add_transition_all(nfa2, 17, 17); NFA_add_transition_all(nfa2, 18, 18); NFA_add_transition_all(nfa2, 19, 19); NFA_set_accepting(nfa2, 2, 1); NFA_set_accepting(nfa2, 12, 1); NFA_set_accepting(nfa2, 4, 1); NFA_set_accepting(nfa2, 10, 1); NFA_set_accepting(nfa2, 8, 1); NFA_set_accepting(nfa2, 14, 1); NFA_set_accepting(nfa2, 16, 1); NFA_set_accepting(nfa2, 19, 1); NFA_add_transition(nfa2, 0, 'a', 1); NFA_add_transition(nfa2, 1, 'a', 2); NFA_add_transition(nfa2, 0, 's', 11); NFA_add_transition(nfa2, 11, 's', 12); NFA_add_transition(nfa2, 0, 'g', 3); NFA_add_transition(nfa2, 3, 'g', 4); NFA_add_transition(nfa2, 0, 'o', 9); NFA_add_transition(nfa2, 9, 'o', 10); NFA_add_transition(nfa2, 0, 'h', 5); NFA_add_transition(nfa2, 5, 'h', 6); NFA_add_transition(nfa2, 0, 'i', 7); NFA_add_transition(nfa2, 7, 'i', 8); NFA_add_transition(nfa2, 0, 't', 13); NFA_add_transition(nfa2, 13, 't', 14); NFA_add_transition(nfa2, 0, 'w', 15); NFA_add_transition(nfa2, 15, 'w', 16); NFA_add_transition(nfa2, 0, 'n', 17); NFA_add_transition(nfa2, 17, 'n', 18); NFA_add_transition(nfa2, 18, 'n', 19); finalstate = NFA_execute(nfa2, practice5); printf("Pratice problems NFA1:\n"); printf("practice5 = %d\n", finalstate); finalstate = NFA_execute(nfa2, practice6); printf("practice6 = %d\n", finalstate); finalstate = NFA_execute(nfa2, practice7); printf("practice7 = %d\n", finalstate); DFA* dfa = DFA_construct(nfa2); DFA_execute(dfa, "wwashington"); /* NFA* nfa = NFA_new(4); NFA_add_transition_all(nfa, 0, 0); NFA_add_transition(nfa, 0, 'm', 1); NFA_add_transition(nfa, 1, 'a', 2); NFA_add_transition(nfa, 2, 'n', 3); NFA_set_accepting(nfa, 3, true); DFA* dfa = DFA_construct(nfa); //DFA_print(dfa); printf("\n%d\n", DFA_execute(dfa, "man")); */ return 0; }
C
// Projet 6 - Arnold LI - Enze WU - Shadé ALAO AFOLABI #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> #define bound 50 #define w 0.8 /* ********* Structures ********* */ typedef struct { int i; //position i de l'élément int j; //position j de l'élément double p; //valeur élément }Element; typedef struct { int m; //nbr d'éléments non nuls de la matrice Element * T; //tableau d'elements stockage de la matrice creuse int n; //taille de la matrice carre }Matrice; /* ********* Initialisations ********* */ void init_element(Element *e, int i, int j, double p) { e->i = i; e->j = j; e->p = p; } //allocation de la mémoire pour la matrice //initialisation des valeurs à 0 void init_matrice( Matrice * M, int m, int n) { //int i = 0; //Matrice *M ;//= new Matrice; M->m = m; M->n = n; M->T = (Element *)malloc(sizeof(Element )*m); /*M.T[m];// = malloc(m * sizeof(Element)); //M->T = (Element*)malloc(m * sizeof(Element)); for (i = 0; i < m; i++) { M.T[i].i = M.T[i].j = M.T[i].p = 0; } */ //return M; } void free_matrice(Matrice *M) { free(M->T); delete M; } //rempli la matrice à partir d'un fichier void remplir_Matrice(Matrice * M, FILE *f){ int i,j; //indices de la matrice int d; // nbr d'éléments non nuls sur la ligne i int m; //nbr d'éléments non nuls de la matrice int n; //taille de la matrice carre double p; // valeur dans la matrice fscanf (f,"%d %d",&n, &m); //Matrice M; init_matrice(M, m,n); int k = 0; /* for(j=0;j<n;j++){ int rowNum; if(fscanf(f,"%d %d",&rowNum, &d) != EOF) { for(i=0;i<d-1 ;i++){ if(fscanf(f,"%d %lf",&M->T[k].j, &p)!= '\n') { M->T[k].i = rowNum - 1; M->T[k].j -= 1; M->T[k].p = p; k++; } } } } */ int rowNum; //printf("\nje lis : \n "); for(j=0;j<n;j++){ fscanf(f,"%d %d",&rowNum, &d); //printf("%d et %d ",rowNum,d); for(i=0;i<d ;i++){ fscanf(f,"%d %lf",&M->T[k].j, &p); M->T[k].i = rowNum - 1; M->T[k].j -= 1; M->T[k].p = p; printf("K = %d \t M[%d][%d] = '%f' \n",k, M->T[k].i, M->T[k].j,p); k++; } } //printf("\nFIN DE je lis \n "); //return &M; } // Methode des puissances double * puissance(Matrice* M, double *x){ int i; double *y = (double*)malloc(M->n* sizeof(double)); for(i=0;i<M->m;i++) y[M->T[i].j] += x[M->T[i].i] * M->T[i].p; return y; } //itération sur la métode des puissances double * multpuissance(Matrice* M,double *y,int num){ int i = 0; double *tmp = y; for(i=0;i<num;i++) tmp=puissance(M,tmp); return tmp; } void init_vecteur(double * V, int taille){ int i; for(i = 0; i<taille ; i++) V[i] = (1.0 / taille * 1.0); } void convergence(double *z1,double *z2,int taille){ int i = 0; for(i = 0; i<taille; i++) { if(abs(z2[i]-z1[i]) < 0.00001) printf("\nFonction convergence : %d f\n",i); } } //gauss double * Gauss_Seidel ( Matrice* a, double x[], double TOL, int MAXN,double y[],double *z ) { //Turning "ax=b" into "x=Bx+f" Matrice B ; init_matrice(&B, a->m, a->n); int i,j; int k; //itération sur la matrice a int tmp1, tmp2; int l = 0; // itération sur B //transfer le forme matrice de B for(i = 0; i< a->m; i++) { for(j = 0;j < a->m; j++) { tmp1 = tmp2 = 0; if(j!=i) { for(k = 0 ; k < a->m ; k++) { if((a->T[k].i == i) && (a->T[k].j == j)) tmp1 = -a->T[k].p; if((a->T[k].i == i) && (a->T[k].j == i)) tmp2 = a->T[k].p; if((tmp1 != 0) && (tmp2 != 0)){ B.T[l].i = i; B.T[l].j = j; B.T[l].p = tmp1/tmp2; l++; } } } } } //Iteration par rapport la valeur de puissance //pour la condidition xk+1 for(i=0;i<a->m;i++) { if(a->T[i].j<i) { for(k = 0 ; k < i-1 ; k++) z[a->T[k].j] += y[a->T[k].i] * a->T[k].p; } //pour la condition de xk else if(a->T[i].j>i) { for(k = i+1 ; k <a->m ; k++) z[a->T[k].j] += x[a->T[k].i] * a->T[k].p; } } //free_matrice(&B); return z; } // SOR combine y et z dans x void resultat (Matrice* M, double *y, double *z, double *x) { int i; for (i = 0; i < M->n; i++) x[i] = (w * y[i]) + ((1 - w) * z[i]); } /* ******** fonctions annexes de débuguage ********* */ void affiche_matrice(Matrice *M){ int i; printf("\n J'affiche la matrice : \n"); for(i = 0; i < M->m ; i++){ if(i%3 == 0)printf("\n"); printf("M[%d][%d] = %f \t", M->T[i].i, M->T[i].j, M->T[i].p); } } void affiche_vecteur(double * V, int taille){ int i; printf("\nVecteur : \n"); for(i = 0; i<taille ; i++) printf("%f \t",V[i]); printf("\n"); } void somme(double *v, int taille){ float s = 0; int i; for(i = 0; i < taille; i++) s += v[i]; printf("\nSomme ligne vecteur = %f\n",s); } /* Main */ int main(){ FILE *f1 = fopen("Stanford.txt","r"); Matrice M; remplir_Matrice(&M, f1); //affiche_matrice(&M); //variables int n; int MAXN = 100; //Nbre d'itération max double TOL = 10.0; n = 112; //Allocation mémoire des vecteurs double* x = (double*)malloc(M.n * sizeof(double)); double* Y = (double*)malloc(M.n * sizeof(double)); double* y1 = (double*)malloc(M.n * sizeof(double)); double* y2 = (double*)malloc(M.n * sizeof(double)); double* y3 = (double*)malloc(M.n * sizeof(double)); double *z1 = (double*)malloc((M.n) * sizeof(double)); double *z2 = (double*)malloc((M.n) * sizeof(double)); double* res1 = (double*)malloc(M.n * sizeof(double)); double* res2 = (double*)malloc(M.n * sizeof(double)); init_vecteur(x, M.n); //méthode des puissances Y = puissance(&M,x); y1=multpuissance(&M,Y,n); y2=multpuissance(&M,Y,n+1); y3=multpuissance(&M,Y,n+2); //affiche_vecteur(Y, M.n); affiche_vecteur(y2, M.n); //Gauss z1 = Gauss_Seidel(&M, y1, TOL, MAXN ,y2,z2); z2 = Gauss_Seidel(&M, y2, TOL, MAXN ,y3,z2); //SOR resultat(&M,y1,z1,res1); resultat(&M,y2,z2,res2); affiche_vecteur(z1, M.n); affiche_vecteur(z2, M.n); convergence(res1,res2,M.n); //Libération espace mémoire /*free(res1); free(res2); free_matrice(&M); free(x); free(Y); */ return 0; }
C
long n;main(m){scanf("%ld%d",&n,&m);n=(n-2)*(m-2);printf("%ld",n>0?n:-n);} ./Main.c:1:8: warning: return type defaults to int [-Wimplicit-int] long n;main(m){scanf("%ld%d",&n,&m);n=(n-2)*(m-2);printf("%ld",n>0?n:-n);} ^ ./Main.c: In function main: ./Main.c:1:8: warning: type of m defaults to int [-Wimplicit-int] ./Main.c:1:16: warning: implicit declaration of function scanf [-Wimplicit-function-declaration] long n;main(m){scanf("%ld%d",&n,&m);n=(n-2)*(m-2);printf("%ld",n>0?n:-n);} ^ ./Main.c:1:16: warning: incompatible implicit declaration of built-in function scanf ./Main.c:1:16: note: include <stdio.h> or provide a declaration of scanf ./Main.c:1:51: warning: implicit declaration of function printf [-Wimplicit-function-declaration] long n;main(m){scanf("%ld%d",&n,&m);n=(n-2)*(m-2);printf("%ld",n>0?n:-n);} ^ ./Main.c:1:51: warning: incompatible implicit declaration of built-in function printf ./Main.c:1:51: note: include <stdio.h> or provide a declaration of printf
C
/* * Copyright 2020 Scott Vokes * * See LICENCE for the full copyright terms. */ #include <assert.h> #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <stdio.h> #include <inttypes.h> #include <fsm/fsm.h> #include <adt/alloc.h> #include <adt/hash.h> #include <adt/stateset.h> #include "adt/common.h" #include <adt/internedstateset.h> #define LOG_ISS 0 #define NO_ID ((uint32_t)-1) #define DEF_SETS 8 #define DEF_BUF 64 #define DEF_BUCKETS 256 /* Interner for `struct state_set *`s. */ struct interned_state_set_pool { const struct fsm_alloc *alloc; /* Buffer for storing lists of state IDs. */ struct issp_state_set_buf { size_t ceil; size_t used; fsm_state_t *buf; } buf; /* Unique state sets. */ struct issp_state_set_descriptors { size_t ceil; size_t used; struct issp_set { size_t buf_offset; size_t length; struct state_set *ss; /* can be NULL */ } *sets; } sets; /* Hash table, for quickly finding and reusing * state sets with the same states. */ struct issp_htab { size_t bucket_count; /* power of 2 */ size_t used; uint32_t *buckets; /* or NO_ID */ } htab; }; /* It's very common to have state sets with only a single state, * particularly when determinising an FSM that is already mostly * deterministic. Rather than interning them, just return a specially * formatted interned_state_set_id boxing the single state. */ #define SINGLETON_BIT ((uint64_t)1 << 63) #define IS_SINGLETON(X) (X & SINGLETON_BIT) #define MASK_SINGLETON(X) (X & ~SINGLETON_BIT) /* Allocate an interned state set pool. */ struct interned_state_set_pool * interned_state_set_pool_alloc(const struct fsm_alloc *a) { struct interned_state_set_pool *res = NULL; struct issp_set *sets = NULL; fsm_state_t *buf = NULL; uint32_t *buckets = NULL; res = f_calloc(a, 1, sizeof(*res)); if (res == NULL) { goto cleanup; } sets = f_malloc(a, DEF_SETS * sizeof(sets[0])); if (sets == NULL) { goto cleanup; } buf = f_malloc(a, DEF_BUF * sizeof(buf[0])); if (sets == NULL) { goto cleanup; } buckets = f_malloc(a, DEF_BUCKETS * sizeof(buckets[0])); if (buckets == NULL) { goto cleanup; } for (size_t i = 0; i < DEF_BUCKETS; i++) { buckets[i] = NO_ID; } struct interned_state_set_pool p = { .alloc = a, .sets = { .ceil = DEF_SETS, .sets = sets, }, .buf = { .ceil = DEF_BUF, .buf = buf, }, .htab = { .bucket_count = DEF_BUCKETS, .buckets = buckets, }, }; memcpy(res, &p, sizeof(p)); return res; cleanup: f_free(a, sets); f_free(a, buf); f_free(a, buckets); f_free(a, res); return NULL; } /* Free the pool. * Any state_sets on the interned state sets within the pool * will also be freed. */ void interned_state_set_pool_free(struct interned_state_set_pool *pool) { if (pool == NULL) { return; } #if LOG_ISS fprintf(stderr, "%s: sets: %zu/%zu, buf: %zu/%zu state_ids, htab: %zu/%zu buckets used\n", __func__, pool->sets.used, pool->sets.ceil, pool->buf.used, pool->buf.ceil, pool->htab.used, pool->htab.bucket_count); #endif for (size_t i = 0; i < pool->sets.used; i++) { if (pool->sets.sets[i].ss != NULL) { state_set_free(pool->sets.sets[i].ss); } } f_free(pool->alloc, pool->sets.sets); f_free(pool->alloc, pool->buf.buf); f_free(pool->alloc, pool->htab.buckets); f_free(pool->alloc, pool); } static void dump_tables(FILE *f, const struct interned_state_set_pool *pool) { #if LOG_ISS > 1 fprintf(f, "%s: sets:\n", __func__); for (size_t i = 0; i < pool->sets.used; i++) { struct issp_set *s = &pool->sets.sets[i]; fprintf(f, "-- sets[%zu]: length %zd, offset %zd =>", i, s->length, s->buf_offset); for (size_t i = 0; i < s->length; i++) { fprintf(f, " %u", pool->buf.buf[s->buf_offset + i]); } fprintf(f, "\n"); } fprintf(f, "%s: buf: %zu/%zu used\n", __func__, pool->buf.used, pool->buf.ceil); fprintf(f, "%s: htab: %zu/%zu used\n", __func__, pool->htab.used, pool->htab.bucket_count); #endif #if LOG_ISS > 1 for (size_t i = 0; i < pool->htab.bucket_count; i++) { const uint32_t b = pool->htab.buckets[i]; if (b != NO_ID) { fprintf(f, "%s: htab[%zu]: %u\n", __func__, i, b); } } #else uint8_t count = 0; size_t row_count = 0; for (size_t i = 0; i < pool->htab.bucket_count; i++) { const uint32_t b = pool->htab.buckets[i]; if (b != NO_ID) { count++; } if ((i & 7) == 7) { const char c = (count == 0 ? '.' : '0' + count); fprintf(f, "%c", c); row_count += count; count = 0; if ((i & 511) == 511) { /* 64 chars wide */ fprintf(f, " -- %zu\n", row_count); row_count = 0; } } } fprintf(f, "\n"); #endif } SUPPRESS_EXPECTED_UNSIGNED_INTEGER_OVERFLOW() static uint64_t hash_state_ids(size_t count, const fsm_state_t *ids) { uint64_t h = 0; for (size_t i = 0; i < count; i++) { h = hash_id(ids[i]) + (FSM_PHI_64 * h); } return h; } static bool grow_htab(struct interned_state_set_pool *pool) { const uint64_t ocount = pool->htab.bucket_count; const uint64_t ncount = 2 * ocount; const uint64_t nmask = ncount - 1; uint32_t *obuckets = pool->htab.buckets; uint32_t *nbuckets = f_malloc(pool->alloc, ncount * sizeof(nbuckets[0])); if (nbuckets == NULL) { return false; } for (size_t i = 0; i < ncount; i++) { nbuckets[i] = NO_ID; } size_t max_collisions = 0; for (size_t i = 0; i < ocount; i++) { size_t collisions = 0; const uint32_t id = obuckets[i]; if (id == NO_ID) { continue; } struct issp_set *s = &pool->sets.sets[id]; assert(s->buf_offset + s->length <= pool->buf.used); const fsm_state_t *buf = &pool->buf.buf[s->buf_offset]; const uint64_t h = hash_state_ids(s->length, buf); for (uint64_t b_i = 0; b_i < ncount; b_i++) { uint32_t *nb = &nbuckets[(h + b_i) & nmask]; if (*nb == NO_ID) { *nb = id; break; } else { collisions++; } } if (collisions > max_collisions) { max_collisions = collisions; } } f_free(pool->alloc, obuckets); pool->htab.buckets = nbuckets; pool->htab.bucket_count = ncount; if (LOG_ISS) { fprintf(stderr, "%s: %" PRIu64 " -> %" PRIu64 ", max_collisions %zu\n", __func__, ocount, ncount, max_collisions); dump_tables(stderr, pool); } return true; } /* Save a state set and get a unique identifier that can refer * to it later. If there is more than one instance of the same * set of states, reuse the existing identifier. */ bool interned_state_set_intern_set(struct interned_state_set_pool *pool, size_t state_count, const fsm_state_t *states, interned_state_set_id *result) { #if LOG_ISS > 2 fprintf(stderr, "%s: state_count %zu\n", __func__, state_count); #endif #if EXPENSIVE_CHECKS /* input must be ordered */ for (size_t i = 1; i < state_count; i++) { assert(states[i - 1] <= states[i]); } #endif assert(state_count > 0); /* If there's only one state, return a singleton. */ if (state_count == 1) { *result = states[0] | SINGLETON_BIT; return true; } /* otherwise, check the hash table */ if (pool->htab.used > pool->htab.bucket_count/2) { if (!grow_htab(pool)) { return false; } } const uint64_t mask = pool->htab.bucket_count - 1; const uint64_t h = hash_state_ids(state_count, states); /* * TODO: When state_count is > 1 these sets tend to partially * overlap, so if reducing memory usage becomes more important * than time, they could be compressed by interning state IDs * pairwise: for example, [121 261 264 268 273 276 279] might * become ,4 279 where: * * - ,0 -> 121 261 * - ,1 -> 264 268 * - ,2 -> 273 276 * - ,3 -> ,0 ,1 * - ,4 -> ,3 ,2 * * and each pair is stored as uint32_t[2] and interned, * where pair IDs have the msb set. fsm_state_t is expected * to fit in 31 bits. * * As long as the pairwise chunking is done bottom-up (group * all pairs of IDs, then all pairs of pairs, ...) it should * also converge on the same top level ID, for constant * comparison, and creating a new pair ID means the set has * not been seen before. */ uint32_t *dst_bucket = NULL; size_t probes = 0; for (uint64_t b_i = 0; b_i < pool->htab.bucket_count; b_i++) { uint32_t *b = &pool->htab.buckets[(h + b_i) & mask]; #if LOG_ISS > 1 fprintf(stderr, "%s: htab[(0x%lx + %lu) & 0x%lx => %d\n", __func__, h, b_i, mask, *b); #endif if (*b == NO_ID) { #if LOG_ISS > 3 fprintf(stderr, "%s: empty bucket (%zd probes)\n", __func__, probes); #endif dst_bucket = b; break; } const uint32_t id = *b; assert(id < pool->sets.used); struct issp_set *s = &pool->sets.sets[id]; if (s->length != state_count) { probes++; continue; } assert(s->buf_offset + s->length <= pool->buf.used); const fsm_state_t *buf = &pool->buf.buf[s->buf_offset]; if (0 == memcmp(states, buf, s->length * sizeof(buf[0]))) { *result = id; #if LOG_ISS > 3 fprintf(stderr, "%s: reused %u (%zd probes)\n", __func__, id, probes); #endif return true; } else { probes++; continue; } } assert(dst_bucket != NULL); #if LOG_ISS > 3 fprintf(stderr, "%s: miss after %zd probes\n", __func__, probes); #endif #define VERIFY_HTAB_WITH_LINEAR_SERACH 0 #if VERIFY_HTAB_WITH_LINEAR_SERACH for (interned_state_set_id i = 0; i < pool->sets.used; i++) { struct issp_set *s = &pool->sets.sets[i]; if (s->length == state_count && 0 == memcmp(states, &pool->buf.buf[s->buf_offset], s->length * sizeof(states[0]))) { dump_tables(stderr, pool); fprintf(stderr, "%s: expected to find set %zu in htab but did not\n", __func__, i); assert(!"missed in htab but hit in linear search"); } } #endif const interned_state_set_id dst = pool->sets.used; /* if not found, add to set list and buffer, growing as necessary */ if (pool->sets.used == pool->sets.ceil) { const size_t nceil = 2*pool->sets.ceil; struct issp_set *nsets = f_realloc(pool->alloc, pool->sets.sets, nceil * sizeof(nsets[0])); if (nsets == NULL) { return false; } pool->sets.ceil = nceil; pool->sets.sets = nsets; } if (pool->buf.used + state_count > pool->buf.ceil) { size_t nceil = 2*pool->buf.ceil; while (nceil < pool->buf.used + state_count) { nceil *= 2; } fsm_state_t *nbuf = f_realloc(pool->alloc, pool->buf.buf, nceil * sizeof(nbuf[0])); if (nbuf == NULL) { return false; } pool->buf.ceil = nceil; pool->buf.buf = nbuf; } struct issp_set *s = &pool->sets.sets[dst]; s->ss = NULL; s->buf_offset = pool->buf.used; s->length = state_count; memcpy(&pool->buf.buf[s->buf_offset], states, s->length * sizeof(states[0])); pool->buf.used += state_count; *result = dst; *dst_bucket = dst; pool->htab.used++; pool->sets.used++; #if LOG_ISS fprintf(stderr, "%s: interned new %ld with %zd states, htab now using %zu/%zu\n", __func__, *result, state_count, pool->htab.used, pool->htab.bucket_count); #endif return true; } typedef void iter_iss_cb(fsm_state_t s, void *opaque); static void iter_interned_state_set(const struct interned_state_set_pool *pool, interned_state_set_id iss_id, iter_iss_cb *cb, void *opaque) { assert(pool != NULL); if (IS_SINGLETON(iss_id)) { cb(MASK_SINGLETON(iss_id), opaque); return; } assert(iss_id < pool->sets.used); const struct issp_set *s = &pool->sets.sets[iss_id]; #if LOG_ISS fprintf(stderr, "%s: iss_id %ld => s->buf_offset %zu, length %zu\n", __func__, iss_id, s->buf_offset, s->length); #endif assert(s->buf_offset + s->length <= pool->buf.used); const fsm_state_t *buf = &pool->buf.buf[s->buf_offset]; for (size_t i = 0; i < s->length; i++) { cb(buf[i], opaque); } } struct mk_state_set_env { bool ok; const struct fsm_alloc *alloc; struct state_set *dst; }; static void mk_state_set_cb(fsm_state_t s, void *opaque) { struct mk_state_set_env *env = opaque; if (!state_set_add(&env->dst, env->alloc, s)) { env->ok = false; } } /* Get the state_set associated with an interned ID. * If the state_set has already been built, return the saved instance. */ struct state_set * interned_state_set_get_state_set(struct interned_state_set_pool *pool, interned_state_set_id iss_id) { if (IS_SINGLETON(iss_id)) { struct state_set *dst = NULL; const fsm_state_t s = MASK_SINGLETON(iss_id); if (!state_set_add(&dst, pool->alloc, s)) { return false; } return dst; /* also a singleton */ } assert(iss_id < pool->sets.used); struct issp_set *s = &pool->sets.sets[iss_id]; if (s->ss == NULL) { struct mk_state_set_env env = { .alloc = pool->alloc, .ok = true, .dst = NULL, }; iter_interned_state_set(pool, iss_id, mk_state_set_cb, &env); if (!env.ok) { state_set_free(env.dst); env.dst = NULL; } s->ss = env.dst; } return s->ss; } static void dump_state_set_cb(fsm_state_t s, void *opaque) { FILE *f = opaque; fprintf(f, " %d", s); } /* Dump the list of states associated with a set ID. For debugging. */ void interned_state_set_dump(FILE *f, const struct interned_state_set_pool *pool, interned_state_set_id set_id) { iter_interned_state_set(pool, set_id, dump_state_set_cb, f); }
C
#include <stdlib.h> #include "KnxInterface.h" DATA_TYPE pdu_alloc() { DEBUG("pdu_alloc begin\n"); DATA_TYPE pdu = (DATA_TYPE)malloc(120); // FIXME: buffer alloc return pdu; } void HexDump(void *v,int len,int addr) { int i,j,k; char binstr[80]; char *buf = (char *)v; for (i=0;i<len;i++) { if (0==(i%16)) { sprintf(binstr,"%08x -",i+addr); sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]); } else if (15==(i%16)) { sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]); sprintf(binstr,"%s ",binstr); for (j=i-15;j<=i;j++) { sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.'); } printf("%s\n",binstr); } else { sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]); } } if (0!=(i%16)) { k=16-(i%16); for (j=0;j<k;j++) { sprintf(binstr,"%s ",binstr); } sprintf(binstr,"%s ",binstr); k=16-k; for (j=i-k;j<i;j++) { sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.'); } printf("%s\n",binstr); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int somadigit(char *x) { int b=0, soma=0, i; for(i=0;i<strlen(x);i++){ b = x[i]-'0'; soma+=b; } return soma; } int somadigit2(int k) { int resto,somatorio; somatorio=0; while (k>0) { resto=k%10; k=(k-resto)/10; somatorio=somatorio+resto; } return somatorio; } int main(void) { char vet1[1001]; for(;;) { int n=0, b=0; scanf("%s", vet1); if(vet1[0]=='0')return 0; if(somadigit(vet1)%9==0) { b = somadigit(vet1); for(;;) { if(somadigit2(b)==b){printf("%s is a multiple of 9 and has 9-degree %d.\n", vet1, n+1);break;} else{b=(somadigit2(b));n++;} } } else { printf("%s is not a multiple of 9.\n", vet1); } } return 0; }
C
/** @file * Implementacja operacji na liście wskaźników na struktury @c PhoneForward * stworzonych w pliku @ref phone_forward_struct.h z interfejscem w pliku * @ref phone_forward_list.h * * @author Witalis Domitrz <[email protected]> * @date 13.05.2018 */ #include <stdlib.h> #include <stdbool.h> #include "phone_forward_list.h" #include "phone_forward_struct.h" /** * @brief Tworzy element listy * Tworzy element listy będący poprzednikiem @p next i z wartością @p val * @param[in, out] next – wskaźnik na następnik nowotworzonego elementu; * @param[in, out] val – wskaźnik na wartość nowotworzonego elementu. * @return Zwraca wskaźnik na nowoutworzony element, lub @c NULL gdy nie * udało się zaalokować pamięci. */ struct PhoneForwardList *phoneForwardListElemCreate( struct PhoneForwardList *next, struct PhoneForward *val) { struct PhoneForwardList *newPhoneForwardList; // Alokacja nowej struktury newPhoneForwardList = malloc(sizeof(struct PhoneForwardList)); if (newPhoneForwardList == NULL) return NULL; // Ustawienie wartości newPhoneForwardList->val = val; newPhoneForwardList->next = next; // Zwrócenie nowej struktury return newPhoneForwardList; } struct PhoneForwardList *phoneForwardListCreate(void) { // Lista pusta to wskaźnik na pierwszy element, który jest NULL-em return phoneForwardListElemCreate(NULL, NULL); } void phoneForwardListDestroy(struct PhoneForwardList *phoneForwardList) { // Sprawdzenie, czy nie jesteśmy już na końcu if (phoneForwardList == NULL) return; // Zwolnienie kolejnego elementu phoneForwardListDestroy(phoneForwardList->next); // Zwolnienie aktualnego elemntu free(phoneForwardList); } bool phoneForwardListAdd(struct PhoneForwardList *phoneForwardList, struct PhoneForward *phoneForward) { struct PhoneForwardList *currentElem; // Sprawdzenie poprawności wejścia if (phoneForward == NULL || phoneForwardList == NULL) return false; // Utworzenie nowego elementu currentElem = phoneForwardListElemCreate(phoneForwardList->next, phoneForward); if (currentElem == NULL) return false; // Dodanie nowego elementu do listy phoneForwardList->next = currentElem; return true; } void phoneForwardListRemove(struct PhoneForwardList *phoneForwardList, struct PhoneForward const *phoneForward) { struct PhoneForwardList *currentElem, *helper; // Sprawdzenie poprawności wejścia if (phoneForward == NULL || phoneForwardList == NULL) return; // Przeiterowanie się po liście w celu znalezienie elementu o danej wartości currentElem = phoneForwardList; while (currentElem->next != NULL) { if (currentElem->next->val == phoneForward) { // Usunięcie znalezionego elementu helper = currentElem->next; currentElem->next = helper->next; helper->next = NULL; phoneForwardListDestroy(helper); return; } currentElem = currentElem->next; } } bool phoneForwardListIsEmpty(struct PhoneForwardList *phoneForwardList) { return phoneForwardList->next == NULL; }
C
#include <stdlib.h> #include "input_buffer.h" typedef enum { META_COMMAND_SUCCESS, META_COMMAND_UNRECOGNISED_COMMAND } MetaCommandResult; MetaCommandResult do_meta_command(InputBuffer* input_buffer) { if (strcmp(input_buffer->buffer, ".exit") == 0) { exit(EXIT_SUCCESS); } else { return META_COMMAND_UNRECOGNISED_COMMAND; } }
C
/* Write a program to sort 10 numbers using quick sort. */ #include<stdio.h> #define n 5 void quicksort(int x[n],int first,int last) { int i, j, pivot, temp; if(first<last) { pivot=first; i=first; j=last; while(i<j) { while(x[i]<=x[pivot]&&i<last) { i++; } while(x[j]>x[pivot]) { j--; } if(i<j) { temp=x[i]; x[i]=x[j]; x[j]=temp; } } temp=x[pivot]; x[pivot]=x[j]; x[j]=temp; quicksort(x,first,j-1); quicksort(x,j+1,last); } } int main() { int i, x[25]; printf("Enter the elements:\n"); for(i=0;i<n;i++) { scanf("%d",&x[i]); } quicksort(x,0,n-1); printf("Sorted List:\n"); for(i=0;i<n;i++) { printf("%d, ",x[i]); } return 0; } /* OUTPUT: Enter the elements: 5 2 1 7 8 Sorted List: 1, 2, 5, 7, 8, */
C
#include "libft.h" #include <sys/stat.h> #include <stdlib.h> extern char **g_env; void free_array(char **array) { int i; i = 0; while (array && *(array + i)) { free(*(array + i)); i++; } free(array); } int file_is_exist(char *pathname) { struct stat buf; if (!pathname) return (0); if (stat(pathname, &buf) == -1) return (0); return (1); } char **find_path_var(void) { int i; i = 0; while (g_env[i]) { if (!ft_strncmp("PATH=", g_env[i], 5)) break; i++; } if (!g_env[i]) return (NULL); return (ft_split(g_env[i] + 5, ':')); } char *find_path(char **array, char *name) { int i; char *tmp; char *pathname; i = 0; while (array[i]) { if (!(tmp = ft_strjoin(array[i], "/"))) exit(1); if (!(pathname = ft_strjoin(tmp, name))) exit(1); free(tmp); if (file_is_exist(pathname)) break; free(pathname); pathname = NULL; i++; } return (pathname); }
C
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> void sigroutine(int signo) { fprintf(stdout, "got signal %d.\n", signo); exit(1); } int main(void) { signal(SIGTERM, sigroutine); while (1) sleep(10); return 0; }
C
#include <stdio.h> #include <string.h> #include <cs50.h> #include <ctype.h> char caesar(char coin, int pre); int main(int argc, string argv[]) { bool code = false; string input = ""; int inputlength; int a = 0; string key = ""; int keylength = 0; do { if(argc != 2) { printf("give at least 2 command line arguments\n"); return 1; } else { if(argv[1]) { int length = strlen(argv[1]); for(int i = 0; i < length; i++) { if(!isalpha(argv[1][i])) { // We accept only letters as input. printf("Your input contains illegal characters.\n"); return 1; } else { // All good, input can be accepted as key. code = true; key = argv[1]; } } } } } while(!code); keylength = strlen(key); int keycodes[keylength]; for(int i = 0; i < keylength;i++) { keycodes[i] = toupper(key[i]) - 65; } input = GetString(); inputlength = strlen(input); for (int i = 0; i < inputlength; i++) { if(!isalpha(input[i])) { printf("%c", input[i]); } else { printf("%c", caesar(input[i], keycodes[a])); if(a < keylength - 1) { a++; } else { a = 0; } } } printf("\n"); return 0; } char caesar(char coin, int pre) { if(islower(coin)) { return ((((coin - 97)+pre)%26)+97); } else { return ((((coin - 65) +pre)%26)+65); } }
C
/* * usart.h * * Created on: 27-jan-2009 * Author: Jan */ #ifndef USART_H_ #define USART_H_ void USART_Init(unsigned int baudrate) { /* Set baud rate */ UBRR0H = (unsigned char)(baudrate>>8); UBRR0L = (unsigned char)baudrate; /* Enable receiver and interrupt*/ UCSR0B = (1<<RXEN0)|(1<<RXCIE0)|(1<<TXEN0); /* Set frame format: 9data UCSZ0 = 7, 8data UCSZ0 = 3, 1stop bit */ UCSR0C = (1<<UCSZ00)|(1<<UCSZ01)|(0<<UCSZ02)|(1<<USBS0); } void USART_Transmit( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSR0A & (1<<UDRE0)) ); /* Put data into buffer, sends the data */ UDR0 = data; } unsigned char USART_Receive( void ) { unsigned char status, resl; /* Wait for data to be received */ while ( !(UCSR0A & (1<<RXC0)) ) ; /* Get status and 9th bit, then data */ /* from buffer */ status = UCSR0A; resl = UDR0; /* If error, return -1 */ if ( status & (1<<FE0)) return -1; /* Filter the 9th bit, then return */ return (resl); } #endif /* USART_H_ */
C
#include <stdio.h> int main() { float somaDeDigitos(float num1, float num2); float a, b, soma; printf("Digite 2 numeros: "); scanf("%d%d", &a, &b); soma = somaDeDigitos(a, b); printf("A soma e %d\n", soma); return 0; } float somaDeDigitos(float num1, float num2) { float valorAbsoluto (float x); // Declarando a função de baixo if(num1 < 0) { num1 = valorAbsoluto(num1); } if (num2 < 0) { num2 = valorAbsoluto(num2); } return num1 + num2; } float valorAbsoluto (float x) { return x * -1; }
C
/* 冒泡排序 * 与C语言库函数 qsort 使用方法相同 */ #ifndef __CLIB_DATA_STRUCTURE_BUBBLESORT_C__ #define __CLIB_DATA_STRUCTURE_BUBBLESORT_C__ #include "swp.h" int compare_int(const void *a,const void *b) { return *(int *)a - *(int *)b; } void bubbleSort(void *base,size_t n,size_t size, int (*compare)(const void *,const void *)) { int i,j; for(i=0;i<n-1;i++){ for(j=0;j<n-1-i;j++){ if(compare(base+j*size,base+(j+1)*size)>0) { swp(base+j*size,base+(j+1)*size,size); } } } } #endif
C
#include "message_queue.h" int mq_init(key_t key) { int msqid; //Try to initialize the Message Queue if ((msqid = msgget(key, IPC_CREAT | 0666 )) < 0) { perror("msgget"); exit(1); } printf("Created and Attached to Message Queue with MQID: %d\n", msqid); return msqid; } int mq_attach(key_t key) { int msqid; //Atempt to get the Message Queue ID using the common key if ((msqid = msgget(key, 0666)) < 0) { perror("msgget"); exit(1); } printf("Attached to Message Queue with MQID: %d\n", msqid); return msqid; } void mq_send_message(int msqid, message_buf *sbuf) { size_t buf_length = strlen(sbuf->mtext) + 1 ; /* * Send a message. */ if (msgsnd(msqid, sbuf, buf_length, IPC_NOWAIT) < 0) { printf ("%d, %ld, %s, %ld\n", msqid, sbuf->mtype, sbuf->mtext, buf_length); perror("msgsnd"); exit(1); } else printf("Message: \"%s\" Sent\n", sbuf->mtext); } int mq_receive_message(int msqid, int message_type, message_buf *rbuf) { /* * Receive an answer of desired message type. */ if (msgrcv(msqid, rbuf, MSGSZ, message_type, IPC_NOWAIT) < 0) { if(errno != ENOMSG) { //The message was not received properly, exit with errors perror("msgrcv"); exit(1); } printf("No messages of type %d received\n", message_type); return 0; } else printf("%s received\n", rbuf->mtext); return 1; }
C
/* printint, printx macro */ #include "stdio.h" #include <ctype.h> #define printint(var) x##var #define printx(n) printint((x##n)) int main(int argc, char const *argv[]) { printf("%i\n", isdigit('9') ); return 0; }
C
/** Copyright 2020 Bishop Bettini Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "usage.c" #include "version.c" int main(int argc, char *argv[]) { DocoptArgs args = docopt(argc, argv, 1, VERSION); /* process arguments # bad/vacuous arg check if the width is negative, exit failure if the width is zero, exit success # default setting if the width isn't set, calculate from term if the start char isn't set, default to a '' if the repeat char isn't set if the locale is utf-8, use a UTF-8 box drawing dash otherwise use the ANSI - if the finish char isn't set, default to a '' if the new line char isn't set if the environment is known, default to the environment's else default to \n # meat output the start char for (i = 0; i < width; i++) { output the repeat character } output the finish char output the newline char */ return EXIT_SUCCESS; }
C
/* homework.c * * insertion sorting * * * * * * Created by Sergiy Ninoshvili on 15/06/2016 * * * * Copyright 2016 Sergiy Ninoshvili. All rights reserved. * * */ #include <stdio.h> #include "List.h" #include "node.h" list *Homework(list *thelist) { node *head = thelist->head; node *tail = thelist->tail; node *insertionItem = head->next; node *compareItem = head; node *beforeCompare = (compareItem->previous == NULL) ? head : compareItem->previous; node *saveAdress = insertionItem->next; node *EndSorted = insertionItem->previous; while (compareItem != tail) { saveAdress = insertionItem->next; while (compareItem != NULL) { if (compareItem->data > insertionItem->data && beforeCompare->data < insertionItem->data) { if (insertionItem == tail) { thelist->tail = compareItem; compareItem->next = NULL; compareItem->previous = insertionItem; insertionItem->next = compareItem; insertionItem->previous = beforeCompare; beforeCompare->next = insertionItem; return thelist; } if (beforeCompare != NULL) beforeCompare->next = insertionItem; else thelist->head = insertionItem; node *afterInsertionItem = insertionItem->next; //put insertionItem between compare and before compare item insertionItem->previous = beforeCompare; insertionItem->next = compareItem; compareItem->previous = insertionItem; if (compareItem != EndSorted) { EndSorted->next = afterInsertionItem; afterInsertionItem->previous = EndSorted; } else { compareItem->next = afterInsertionItem; afterInsertionItem->previous = compareItem; } break; } compareItem = beforeCompare; beforeCompare = (compareItem == NULL)? head : compareItem->previous; } insertionItem = saveAdress; EndSorted = (insertionItem == NULL)? tail : insertionItem->previous; compareItem = (insertionItem == NULL)? tail: insertionItem->previous; beforeCompare = (compareItem == NULL) ? head : compareItem->previous; } return thelist; }
C
#include "../include/team.h" #include <stdlib.h> void make_empty_team(team *t, int size) { t->ages = (int *) calloc(size, sizeof(int)); t->adjacency = (list *) malloc(size * sizeof(list)); for (int i = 0; i < size; i++) make_empty_list(&t->adjacency[i]); t->size = size; } void set_age(team *t, int position, int age) { t->ages[position] = age; } void insert_edge(team *t, int source, int dest) { add_item_end(&t->adjacency[source - OFFSET], dest - OFFSET); } void free_team(team *t) { free(t->ages); free_list(t->adjacency); }
C
//#include<bits/stdc++.h> #include<bits/stdc++.h> using namespace std; int main(){ freopen("in.txt","r",stdin); int tc; //scanf("%d",&tc); cin>>tc; while(tc--) { char s[10]; scanf("%s",s); if(s.length>3) cout<<3<<endl; else{ int count = 0; if( s[0]=='o' ) count++; if( s[1]=='n' ) count++; if( s[2]=='e' ) count++; if( count>=2 ) cout <<1<<endl; else cout<<2<<endl; } } return 0; }
C
#include "helpers.h" #include <math.h> #include <stdio.h> // Convert image to grayscale void grayscale(int height, int width, RGBTRIPLE image[height][width]) { int newcolor; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { newcolor = round(((image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen) / 3.0)); image[i][j].rgbtBlue = newcolor; image[i][j].rgbtRed = newcolor; image[i][j].rgbtGreen = newcolor; newcolor = 0; } } return; } // Convert image to sepia void sepia(int height, int width, RGBTRIPLE image[height][width]) { double Red; double Green; double Blue; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Red = .393 * image[i][j].rgbtRed + .769 * image[i][j].rgbtGreen + .189 * image[i][j].rgbtBlue; Green = .349 * image[i][j].rgbtRed + .686 * image[i][j].rgbtGreen + .168 * image[i][j].rgbtBlue; Blue = .272 * image[i][j].rgbtRed + .534 * image[i][j].rgbtGreen + .131 * image[i][j].rgbtBlue; if (Red > 255) { image[i][j].rgbtRed = 255; } else { image[i][j].rgbtRed = round(Red); } if (Green > 255) { image[i][j].rgbtGreen = 255; } else { image[i][j].rgbtGreen = round(Green); } if (Blue > 255) { image[i][j].rgbtBlue = 255; } else { image[i][j].rgbtBlue = round(Blue); } } } } // Reflect image horizontally void reflect(int height, int width, RGBTRIPLE image[height][width]) { for (int h = 0; h < height; h++) { for (int i = 0, n = width / 2; i < n; i++) { RGBTRIPLE pixel = image[h][i]; image[h][i] = image[h][width - i - 1]; image[h][width - i - 1] = pixel; } } } // Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE duplic[height][width]; for (int x = 0; x < height; x++) { for (int y = 0; y < width; y++) { duplic[x][y] = image[x][y]; } } double newred = 0; double newblue = 0; double newgreen = 0; double count = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { for (int l = i - 1; l <= i + 1; l++) { for (int s = j - 1; s <= j + 1; s++) { if (l >= 0 && l < height && s >= 0 && s < width) { newred += duplic[l][s].rgbtRed; newgreen += duplic[l][s].rgbtGreen; newblue += duplic[l][s].rgbtBlue; count++; } } } image[i][j].rgbtRed = round(newred / count); image[i][j].rgbtGreen = round(newgreen / count); image[i][j].rgbtBlue = round(newblue / count); newred = 0; newgreen = 0; newblue = 0; count = 0; } } }
C
// hollow inverted right triangle. #include<stdio.h> int main() { int i,j,n; printf("Enter any rows:"); scanf("%d",&n); for(i=1;i<=n;i++){ for(j=i;j<=n;j++){ if(j==i ||i==1 || j==n){ printf("*");// printing star depend on the value of j and i. } else{ printf(" ");// If condition not successful. } } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char weekday[10]; char name[101]; struct { int hour; int min; } Start; struct { int hour; int min; } End; } TVshow; typedef struct { int numShows; char name[11]; TVshow *shows; } Channel; typedef struct { int numChannels; Channel *channels; } Guide; Guide *readTV(char *filename) { FILE *fp = fopen(filename, "rb"); int i, j; Guide *g = malloc(sizeof(Guide)); if (fp == NULL) { g = NULL; } else { fscanf(fp, "%d", &g->numChannels); g->channels = malloc(g->numChannels * sizeof(Channel)); for (i = 0; i < g->numChannels; i++) { fscanf(fp, " %s %d", g->channels[i].name, &g->channels[i].numShows); g->channels[i].shows = malloc(g->channels[i].numShows * sizeof(TVshow)); } fscanf(fp, "\n"); for (i = 0; i < g->numChannels; i++) { for (j = 0; j < g->channels[i].numShows; j++) { fscanf(fp, " %d:%d", &g->channels[i].shows[j].Start.hour, &g->channels[i].shows[j].Start.min); fscanf(fp, " %d:%d", &g->channels[i].shows[j].End.hour, &g->channels[i].shows[j].End.min); fscanf(fp, " %s", g->channels[i].shows[j].weekday); fscanf(fp, " %[^\t\n]\n", g->channels[i].shows[j].name); } } fclose(fp); } return g; } void whatsOn(Guide *g, char weekday[4], char time[6]) { int i, j; char startTime[6], endTime[6]; for (i = 0; i < g->numChannels; i++) { for (j = 0; j < g->channels[i].numShows; j++) { if ((strcmp(weekday, g->channels[i].shows[j].weekday)) == 0) { sprintf(startTime, "%d:%d", g->channels[i].shows[j].Start.hour, g->channels[i].shows[j].Start.min); sprintf(endTime, "%d:%d", g->channels[i].shows[j].End.hour, g->channels[i].shows[j].End.min); if ((strcmp(time, startTime)) <= 0 || (strcmp(time, endTime)) >= 0) { printf("Channel: %s\n", g->channels[i].name); printf("Show: %s\n", g->channels[i].shows[j].name); printf("\n"); } } } } } int main(int argc, char *argv[]) { int i; Guide *g; if (argc != 4) { fprintf(stderr, "Wrong number of arguments."); } else { if ((g = readTV(argv[1])) == NULL) { fprintf(stderr, "Input file could not be read."); } else { whatsOn(g, argv[2], argv[3]); for (i = 0; i < g->numChannels; i++) { free(g->channels[i].shows); } free(g->channels); } free(g); } return 0; }
C
#include<stdio.h> int main() { float h,m,ans; while(scanf("%f:%2f",&h,&m)==2) { if(h==0&&m==0)break; ans=h*30+(m/2)-(m*6); if(ans<0)ans=ans*(-1); if(ans>(360-ans))ans=360-ans; printf("%.3f\n",ans); } return 0; }
C
/* * ===================================================================================== * * Filename: hightlightAndSummary.c * * Description: * * Version: 1.0 * Created: 07/03/2011 06:16:47 PM * Revision: none * Compiler: gcc * * Author: kangle.wang (mn), [email protected] * Company: APE-TECH * * ====================================================================================== */ #include <string.h> #include <math.h> #include "findPositionStruct.h" #include "stringsReplace.h" #include "hightlightAndSummary.h" #include "log4c.h" #include "findStringsWithoutCase.h" static char* get_keywords ( char** pKeywords, size16_t* pkeySz, int num) { char* back = (char*)malloc(pkeySz[num] + 1); strncpy(back, pKeywords[num], pkeySz[num]); back[pkeySz[num]] = '\0'; return back; } /* ----- end of function get_keywords ----- */ static char* get_dest ( char* p_keywords, int isBigSize ) { char* css_strings_head = NULL; if(isBigSize == 0) { css_strings_head = "<span class='news_title2'>"; } else { css_strings_head = "<span class='news_title1'>"; } int css_strings_head_lens = strlen(css_strings_head); char* css_strings_end= "</span>"; int css_strings_end_lens = strlen(css_strings_end); int lens = strlen(p_keywords); char* back = (char*)malloc(css_strings_head_lens + css_strings_end_lens + lens + 1); memcpy(back, css_strings_head, css_strings_head_lens); memcpy(&back[css_strings_head_lens], p_keywords, lens); memcpy(&back[css_strings_head_lens + lens], css_strings_end, css_strings_end_lens); back[css_strings_head_lens + css_strings_end_lens + lens] = '\0'; return back; } /* ----- end of function get_dest ----- */ PositionList* creat_new_node ( char* point, int lens ) { PositionList* new = (PositionList*)malloc(sizeof(PositionList)); new->position = point; new->lens = lens; new->next = NULL; return new; } /* ----- end of function creat_new_node ----- */ static void insert_position_exact ( PositionListPoint* pointInfo, char* point, PositionList* needsToInsert) { PositionList* cursor = pointInfo->head_point; if((cursor->position) > point) { needsToInsert->next = cursor; pointInfo->head_point = needsToInsert; return ; } if(cursor->next != NULL) { while(1) { if(cursor->next == NULL) { cursor->next = needsToInsert; pointInfo->last_point = needsToInsert; break; } if( point < (cursor->next->position)) { needsToInsert->next = cursor->next; cursor->next = needsToInsert; break; } cursor = cursor->next; } } else { if(cursor->position < point) { cursor->next = needsToInsert; pointInfo->last_point = needsToInsert; } else { needsToInsert->next = cursor; } } return ; } /* ----- end of function insert_position_exact ----- */ static void insert_position ( PositionListPoint* pointInfo, char* point, int lens, int isByOrder) { if( pointInfo->head_point == NULL) { PositionList* new = creat_new_node(point, lens); pointInfo->head_point = new; pointInfo->last_point = new; } else { PositionList* last_point = creat_new_node(point, lens); if(isByOrder == 0) { pointInfo->last_point->next = last_point; pointInfo->last_point = last_point; } else { insert_position_exact(pointInfo, point, last_point); } } return ; } /* ----- end of function insert_position ----- */ static void find_position_and_insert ( PositionListPoint* pointInfo, char* content, char* keywords, int lens, int isByOrder ) { char* point = NULL; char* point_head = content; int keywords_lens = strlen(keywords); // while( (point = strstr(point_head, keywords)) != NULL) char *exact = find_without_case(point_head, keywords); char *switch_point = NULL; if(exact == NULL) { switch_point = keywords; } else { switch_point = exact; } while( (point = strstr(point_head, switch_point)) != NULL) { insert_position(pointInfo, point, lens, isByOrder); point_head = point + keywords_lens; } free(exact); return ; } /* ----- end of function find_position_and_insert ----- */ void delete_position_list(PositionList* head ) { PositionList* point = head->next; while(head != NULL) { free(head); head = point; if(head != NULL) { point = head->next; } } return ; } /* ----- end of function delete_postion_list ----- */ static void get_position_list (PositionListPoint* pointInfo, char* content, char** pKeywords, size16_t* pkeySz, count_t num ) { int i = 0; char* p_keywords = NULL; for(i = 0; i < num ; i++) { p_keywords = get_keywords(pKeywords, pkeySz, i); if(i == 0) { find_position_and_insert(pointInfo , content, p_keywords, pkeySz[i], 0); } else { find_position_and_insert(pointInfo , content, p_keywords, pkeySz[i], 1); } free(p_keywords); } return ; } /* ----- end of function get_instead ----- */ static int is_english ( const char *pkeywords ) { int back = 0; int lens = strlen(pkeywords); int i = 0; for(i = 0; i < lens ; i++) { if((unsigned char)pkeywords[i] > 0xe0 && (unsigned char)pkeywords[i] < 0xef) { i = i + 2; } if((unsigned char)pkeywords[i] > 0x40 && (unsigned char)pkeywords[i] < 0x5b) { back = 1; } if((unsigned char)pkeywords[i] > 0x60 && (unsigned char)pkeywords[i] < 0x7b) { back = 1; } } return back; } /* ----- end of function is_chinese ----- */ static char is_anti ( const char key ) { char back = key; if((unsigned char)key > 0x40 && (unsigned char)key < 0x5b ) { back = (unsigned char)key + 0x20; } if((unsigned char)key > 0x60 && (unsigned char)key < 0x7b ) { back = (unsigned char)key - 0x20; } return back; } /* ----- end of function is_anti ----- */ static char* get_strings_by_bit (const char *pkeywords, const long long int num ) //根据比特位对相应字符取反 { char *back = NULL; int lens = strlen(pkeywords); // printf("%d ", lens); back = (char*)malloc(lens + 1); memset(back, '\0', lens + 1); int i = 0; for(i = 0; i < lens ; i++) { long long int is_bit_true = pow(2, i); if((is_bit_true&num) != 0) { back[i] = is_anti(pkeywords[i]); } else { back[i] = pkeywords[i]; } } back[lens] = '\0'; return back; } /* ----- end of function get_strings_by_bit ----- */ static char* get_exact_whatis ( const char *content, const char *pkeywords ) //根据原文中出现的英文单词 确定大小写 { char *back = NULL; int lens = strlen(pkeywords); int counts = pow(2, lens); long long int i = 0; for(i = 0; i < counts ; i++) { char *strings = get_strings_by_bit(pkeywords, i); char *point = NULL; /* Explicitly call the log4c cleanup routine */ point = strstr(content, strings); if( point != NULL) { back = (char*)malloc(lens + 1); strncpy(back, strings, lens); back[lens] = '\0'; free(strings); return back; } free(strings); strings = NULL; } back = (char*)malloc(lens + 1); strncpy(back, pkeywords, lens); back[lens] = '\0'; return back ; } /* ----- end of function get_exact_whatis ----- */ static char* get_change_by_case (const char *content, const char *pkeywords) //如果是中文,原样输出 英文 则查找其在原文中到底具体字符的大小写 { char *back = NULL; int lens = strlen(pkeywords); if((is_english(pkeywords))) { back = get_exact_whatis(content, pkeywords); } else { back = (char*)malloc(lens + 1); strncpy(back, pkeywords, lens); back[lens] = '\0'; } return back; } /* ----- end of function get_change_by_case ----- */ static char* get_instead ( char *pKeywords, int couts) { int keywords_len = strlen(pKeywords); char *back = (char*)malloc(keywords_len + couts +1); memset(back, '\n', couts); strncpy(back + couts, pKeywords, keywords_len); back[keywords_len + couts] = '\0'; return back; } /* ----- end of function get_position_list ----- */ char* hightlight_title(char* title, char** pKeywords, size16_t* pkeySz, count_t num, int isBigSize) { int i = 0; for(i = 0; i < num ; i++) { // char *p_keywords = get_keywords(pKeywords, pkeySz, i); char *p_change_by_case = get_keywords(pKeywords, pkeySz, i); char *p_keywords = get_change_by_case(title, p_change_by_case); /* char *p_instead = get_instead(p_change_by_case, i + 1); title = strings_replace_with_free(title, p_change_by_case, p_instead); */ char *p_instead = get_instead(p_keywords, i + 1); title = strings_replace_with_free(title, p_keywords, p_instead); free(p_change_by_case); free(p_keywords); free(p_instead); } for(i = num - 1; i >= 0 ; i--) { char *p_change_by_case = get_keywords(pKeywords, pkeySz, i); char *p_keywords = get_change_by_case(title, p_change_by_case); // char *p_keywords = get_keywords(pKeywords, pkeySz, i); char *p_instead = get_instead(p_keywords, i + 1); char *p_dest = NULL; if(isBigSize == 0) { p_dest = get_dest(p_keywords, 0); } else { p_dest = get_dest(p_keywords, 1); } title = strings_replace_with_free(title, p_instead, p_dest); free(p_change_by_case); free(p_keywords); free(p_instead); free(p_dest); } return title; } /* ----- end of function hightlight_title ----- */ char* get_summary (char* content, char** pKeywords, size16_t* pkeySz, count_t num) { PositionListPoint* pointInfo = (PositionListPoint*)malloc(sizeof(PositionListPoint)); pointInfo->head_point = NULL; pointInfo->last_point = NULL; get_position_list(pointInfo, content, pKeywords, pkeySz, num); PositionStruct* position = get_position_struct(pointInfo->head_point, content); char* back = (char*)malloc(position->lens + 4); strncpy(back, position->position, position->lens); strncpy(back + position->lens, "...", 3); back[position->lens + 3] = '\0'; if(pointInfo->head_point != NULL) { delete_position_list(pointInfo->head_point); } free(pointInfo); free(position); return back; } /* ----- end of function get_summary ----- */
C
#include <stdint.h> #include "pico/stdlib.h" #include "pico/binary_info.h" #include "hardware/spi.h" const int LOW = 0; const int HIGH = 1; const int OUTPUT = 1; #ifdef PICO_DEFAULT_SPI_CSN_PIN void binkLED(int times) { for (int i = 0; i < times; i++) { gpio_put(PICO_DEFAULT_LED_PIN, 0); sleep_ms(1000); gpio_put(PICO_DEFAULT_LED_PIN, 1); sleep_ms(1000); } } static inline void cs_select() { asm volatile("nop \n nop \n nop"); gpio_put(PICO_DEFAULT_SPI_CSN_PIN, 0); asm volatile("nop \n nop \n nop"); } static inline void cs_deselect() { asm volatile("nop \n nop \n nop"); gpio_put(PICO_DEFAULT_SPI_CSN_PIN, 1); asm volatile("nop \n nop \n nop"); } #endif void delay(unsigned int milliseconds) { sleep_ms(milliseconds); }; void pinMode(int pin, int mode) { gpio_init(pin); gpio_set_dir(pin, GPIO_OUT); }; void digitalWrite(int pin, int value) { gpio_put(pin, value); }; int spiSetup(int channel, int speed) { spi_init(spi_default, speed); gpio_set_function(PICO_DEFAULT_SPI_RX_PIN, GPIO_FUNC_SPI); gpio_set_function(PICO_DEFAULT_SPI_SCK_PIN, GPIO_FUNC_SPI); gpio_set_function(PICO_DEFAULT_SPI_TX_PIN, GPIO_FUNC_SPI); // Make the SPI pins available to picotool bi_decl(bi_3pins_with_func(PICO_DEFAULT_SPI_RX_PIN, PICO_DEFAULT_SPI_TX_PIN, PICO_DEFAULT_SPI_SCK_PIN, GPIO_FUNC_SPI)); // Chip select is active-low, so we'll initialise it to a driven-high state gpio_init(PICO_DEFAULT_SPI_CSN_PIN); gpio_set_dir(PICO_DEFAULT_SPI_CSN_PIN, GPIO_OUT); gpio_put(PICO_DEFAULT_SPI_CSN_PIN, 1); // Make the CS pin available to picotool bi_decl(bi_1pin_with_name(PICO_DEFAULT_SPI_CSN_PIN, "SPI CS")); return 0; }; int spiDataRW(int channel, uint8 *data, int length) { cs_select(); spi_write_blocking(spi_default, data, length); cs_deselect(); return 0; };
C
#include "print_tools.h" void print_by_byte(void *p_obj, char *src, int size){ int i = 0; printf("%s's size is %d\n", src, size); while(i < size){ printf("%02X,",*(((unsigned char *)p_obj)+i)); i++; if(i == size){ printf("$\n"); } } }
C
#ifndef DEFINES_H #define DEFINES_H // Program states #define STATE_INTRO 0 #define STATE_MENU 1 #define STATE_PREGAME 2 #define STATE_INGAME 3 #define STATE_GAMEOVER 4 #define STATE_HIGHSCORES 5 #define STATE_NEWHIGHSCORE 6 // Menu defines #define MENU_ITEM_COUNT 2 #define MENU_ITEM_PLAY 0 #define MENU_ITEM_SCORES 1 #define GAMEOVER_ITEM_COUNT 3 #define GAMEOVER_ITEM_SCORE 0 #define GAMEOVER_ITEM_PLAY 1 #define GAMEOVER_ITEM_QUIT 2 // Custom characters printed to the LCD // These numbers are used as references; the actual layout of the characters // is defined elsewhere #define AIR_CHAR 0b00100000 #define BLOCK_CHAR 0b11111111 #define GROUND_CHAR 0 #define STICKMAN_CHAR_A 1 #define STICKMAN_CHAR_B 2 #define STICKMAN_GROUND_CHAR_A 3 #define STICKMAN_GROUND_CHAR_B 4 #define ENEMY_CHAR_A 5 #define ENEMY_CHAR_B 6 #define DEAD_CHAR 7 // The minimum distance that ground and blocks must go for before switching // to a different tile type #define LANDSCAPE_MIN 5 // The probability that the current tile will be repeated when the landscape is // next updated, as a percentage // Can be anywhere between 1 and 98, though really high values aren't recommended #define LANDSCAPE_REPEAT_CHANCE 50 // How many tiles the stickman will jump over when the centre button is pressed #define JUMP_DISTANCE 2 // Delays (in milliseconds) // Specifies how long to wait between executing various parts of the game loop #define DELAY_INPUTS 30 #define DELAY_LCD 170 // Number of high scores to store; probably best not to set this above 9 #define HIGHSCORES_COUNT 3 #endif
C
#include <stdio.h> #include <libgen.h> typedef struct node{ char name[64]; // node's name string char type; struct node *child, *sibling, *parent; }NODE; NODE *root, *cwd, *start; char line[128]; // for gettting user input line char command[64], pathname[64]; // for command and pathname strings char dname[64], bname[64]; // for dirname and basename char *name[100]; // token string pointers int n; // number of token strings in pathname FILE *fp; char *cmd[] = {"mkdir", "rmdir", "ls", "cd", "pwd", "creat", "rm", "reload", "save", “menu”, "quit", NULL}; /**********************************************************************/ int tokenize(char *pathname) { int i = 0; name[i] = strtok(path, "/"); // first call to strtok() i++; n+; while(s) { printf(“%s “, s); name[i] = strtok(0, "/"); // call strtok() until it returns NULL i++; n++; } return n = number of token strings } int findCmd(char *command) { int i = 0; while(cmd[i]){ if (!strcmp(command, cmd[i])) return i; // found command: return index i i++; } return -1; // not found: return -1 } int dbname(char *pathname) { char temp[128]; // dirname(), basename() destroy original pathname strcpy(temp, pathname); strcpy(dname, dirname(temp)); strcpy(temp, pathname); strcpy(bname, basename(temp)); } NODE *search_child(NODE *parent, char *name) { NODE* temp = null; temp = parent->child; while(temp != NULL) { if(temp->name == name) return temp; temp = temp->sibling; } return 0; } NODE *path2node(char *pathname) { return the node pointer of a pathname, or 0 if the node does not exist. if pathname[0] = '/' start = root; else start = cwd; n = tokenize(pathname); // NOTE: pass a copy of pathname NODE *p = start; for (int i=0; i < n; i++){ p = search_child(p, name[i]); if (p==0) return 0; // if name[i] does not exist } return p; } bool mkdir(char *pathname) { if(cwd = null) *cwd = new NODE(); } bool rmdir(char* pathname) { } bool ls(char* pathname) { } bool rm(char* pathname) { } bool cd(char* pathname) { } bool pwd(void) { //walk up the tree, concat dirnames into string and print that string out to the screen } bool creat(char* pathname) { } bool rm(char* pathname) { } void save(FILE *filename) { } void reload(FILE* filename) { } bool menu(void) { } bool quit(void) { //calls save to file then exits the program } //tree list of lists, each node is either a file or a directory int main() { int index; char line[128], command[16], pathname[64]; initialize(); //initialize root node of the file system tree while(1){ printf("input a commad line : "); fgets(line,128,stdin); line[strlen(line)-1] = 0; sscanf(line, “%s %s”, command, pathname); int find = findCmd(command); index = find; switch(index){ case 0 : mkdir(pathname); break; case 1 : rmdir(pathname); break; case 2 : ls(pathname); break; case 3 : cd(pathname); break; case 4 : pwd(); break; case 5 : creat(pathname); break; case 6 : rm(pathname); break; case 7 : reload(fp); break; case 8 : save(fp); break; case 9 : menu(); break; case 10 : quit(); break; default: printf(“invalid command %s\n”, command); } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aanzieu <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/08 16:14:42 by aanzieu #+# #+# */ /* Updated: 2019/03/19 09:15:20 by aanzieu ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../../include/ft_nm.h" static void print_ext(t_seg_list seg) { if (seg.n_type & N_EXT) { if (seg.n_desc == REFERENCED_DYNAMICALLY) ft_putstr_fd("[referenced dynamically] ", 1); ft_putstr_fd("external ", 1); } else if (seg.n_type & N_PEXT) ft_putstr("non-external (was a private external) "); else ft_putstr("non-external "); } int help_nm(void) { ft_putstr_fd("\nUSAGE: /bin/ft_nm -[jUurpA] <input files>\n", 1); return (1); } void print_name_section(t_seg_list seg) { if (seg.sectname[0] && seg.segname[0]) { ft_putstr_fd("(", 1); ft_putstr_fd(seg.segname, 1); ft_putchar_fd(',', 1); ft_putstr_fd(seg.sectname, 1); ft_putstr_fd(") ", 1); } else ft_putstr("(?,?) "); } void print_option_m(t_seg_list seg, t_obj *obj) { char c; c = ft_toupper(get_char_type_64(seg, obj)); if ((seg.n_type & N_TYPE) == N_UNDF && seg.n_value) ft_putstr("(common) "); else if (c == 'U') ft_putstr("(undefined) "); else if (c == 'C') ft_putstr("(common) "); else if (c == 'A') ft_putstr("(absolute) "); else if (c == 'I') ft_putstr("(indirect) "); else if ((seg.n_type & N_TYPE) == N_SECT) print_name_section(seg); else ft_putstr("(?) "); print_ext(seg); } void print_cpu_type(t_obj *obj) { const char *name; name = get_arch_type(obj->cputype, obj->cpusubtype).name; if (!name) { ft_putchar_fd('\n', 1); ft_putstr_fd(obj->path, 1); ft_putstr_fd(" (for architecture ):", 1); ft_putchar_fd('\n', 1); } else { ft_putchar_fd('\n', 1); ft_putstr_fd(obj->path, 1); ft_putstr_fd(" (for architecture ", 1); ft_putstr_fd(name, 1); ft_putstr_fd("):", 1); ft_putchar_fd('\n', 1); } }
C
#include "Assignment1SDD.h" /* #1 implement a method that creates a new package with the given values @return a package with the given values; by default the package is not delivered @input data for package fields */ package createPackage(const char* street, int streetNo, float weight, const char* contact) { package newPack; newPack.isDelivered = false; newPack.adr.no = streetNo; strcpy(newPack.adr.street, street); newPack.weight = weight; if (contact != NULL) { newPack.contact = (char*)malloc(strlen(contact) + 1); strcpy(newPack.contact, contact); } return newPack; }; /* #2 implement a method that prints a package at the console @input the package to print */ void printPackage(package myPackage) { printf("\nThe weight is: %.2f", myPackage.weight); printf("\nThe address is: %d, %s street", myPackage.adr.no, myPackage.adr.street); printf("\nThe contact is: %s", myPackage.contact); if (myPackage.isDelivered == true) printf("\nThe package is delivered"); else printf("\nThe package is not delivered"); printf("\n............"); }; /* #3 implement a method that converts the package structure to the serialized_version @return returns a serialized_package article based on the received package @input an existing package */ serialized_package serializePackage(package p) { serialized_package newPack; newPack.weight = p.weight; newPack.adr.no = p.adr.no; strcpy(newPack.adr.street, p.adr.street); if (p.contact != NULL) strcpy(newPack.contact, p.contact); newPack.isDelivered = p.isDelivered; return newPack; }; void printSerializedPackage(serialized_package myPackage) //this is my function in order to check myself { printf("\nThe weight is: %.2f", myPackage.weight); printf("\nThe address is: %d, %s street", myPackage.adr.no, myPackage.adr.street); printf("\nThe contact is: %s", myPackage.contact); if (myPackage.isDelivered == true) printf("\nThe package is delivered"); else printf("\nThe package is not delivered"); } /* #4 implement a method that convert the serialized_package structure to a package one @return returns a package article based on the received serialized_package @input an existing serialized_package Important ! watch out for the dynamic field in the package structure */ package deserializePackage(serialized_package s_p) { package newPack; newPack.weight = s_p.weight; strcpy(newPack.adr.street, s_p.adr.street); newPack.adr.no = s_p.adr.no; newPack.contact = (char*)malloc(strlen(s_p.contact) + 1); strcpy(newPack.contact, s_p.contact); newPack.isDelivered = s_p.isDelivered; return newPack; } /* #5 method for inserting a serialized_package element in the database @return number of inserted packages @input the database and the serialized package */ int insert(db myDb, serialized_package pack) { fwrite((char*)&pack.weight, sizeof(float), 1, myDb.pf); fwrite(pack.adr.street, sizeof(pack.adr.street), 1, myDb.pf); fwrite((char*)&pack.adr.no, sizeof(int), 1, myDb.pf); fwrite(pack.contact, sizeof(pack.contact), 1, myDb.pf); fwrite((char*)&pack.isDelivered, sizeof(bool), 1, myDb.pf); return 1; }; /* #6 method for inserting an array of serialized_package elements in the database @return number of inserted packages @input the database, the array and its number of elements; the array can have from 1 to N packages */ int insert(db myDb, serialized_package* pack, int noPacks) { int insertedPacks = 0; int ok = 0; for (int i = 0; i < noPacks; i++) { ok = insert(myDb, pack[i]); if (ok == 1) insertedPacks++; ok = 0; } return insertedPacks; }; /* #7 method for selecting the first package for a given contact name @return the first package with the given contact; if there is no package for the contact then the functions return a package with a "non existing" contact @input the database, the array and its number of elements */ package selectFirstOrDefault(db myDb, const char* contact) { package pack; int ok = 0; float weight = 0; char street[50]; int no; char contacts[1000]; bool isDelivered; unsigned int x = getFileSize(myDb.pf); unsigned int i; for (i = 0; i < x && ok == 0; i = i + sizeof(serialized_package)) { fread(&weight, sizeof(float), 1, myDb.pf); fread(&street, sizeof(street), 1, myDb.pf); fread(&no, sizeof(int), 1, myDb.pf); fread(&contacts, sizeof(contacts), 1, myDb.pf); fread(&isDelivered, sizeof(bool), 1, myDb.pf); if (strcmp(contact, contacts) == 0) { ok = 1; pack = createPackage(street, no, weight, contacts); pack.isDelivered = isDelivered; } } if (ok == 0) { pack = createPackage("Non existing", 0, 0, "Non existing"); pack.isDelivered = false; } return pack; }; /* #8 method for selecting all @input the database and the given weight @return the packageList of the packages with a weight greater than the given one */ packageList selectHeavyPackages(db myDb, float weight) //there are too many people in the database { packageList List; float weights; char street[50]; int no; char contacts[1000]; bool isDelivered; unsigned int x = getFileSize(myDb.pf); for (unsigned int i = 0; i < x; i = i + sizeof(serialized_package)) { fread(&weights, sizeof(float), 1, myDb.pf); fread(&street, sizeof(street), 1, myDb.pf); fread(&no, sizeof(int), 1, myDb.pf); fread(&contacts, sizeof(contacts), 1, myDb.pf); fread(&isDelivered, sizeof(bool), 1, myDb.pf); if (weights > weight) { package pack = createPackage(street, no, weights, contacts); pack.isDelivered = isDelivered; if (List.noPackages == 0) { List.packages = (package*)malloc(sizeof(package)); List.packages[0] = pack; List.noPackages++; } else { package* packs = (package*)malloc(sizeof(package)*List.noPackages); for (int i = 0; i < List.noPackages; i++) packs[i] = List.packages[i]; List.noPackages++; free(List.packages); List.packages = (package*)malloc(sizeof(package)*List.noPackages); for (int i = 0; i < List.noPackages - 1; i++) List.packages[i] = packs[i]; List.packages[List.noPackages - 1] = pack; free(packs); } } } return List; }; /* #9 method for printing to the console all packages from a package list @input the given packageList */ void printAll(packageList list) { for (int i = 0; i < list.noPackages; i++) { printf("\n-----------------------\n"); printSerializedPackage(serializePackage(list.packages[i])); } }; /* #10 method for printing to the console all packages from the database @input the database */ void printAll(db myDb) { printf("\n-----------------------\n"); float weights; char street[50]; int no; char contacts[1000]; bool isDelivered; unsigned int x = getFileSize(myDb.pf); for (unsigned int i = 0; i < x; i = i + sizeof(serialized_package)) { fread(&weights, sizeof(float), 1, myDb.pf); fread(&street, sizeof(street), 1, myDb.pf); fread(&no, sizeof(int), 1, myDb.pf); fread(&contacts, sizeof(contacts), 1, myDb.pf); fread(&isDelivered, sizeof(bool), 1, myDb.pf); package pack = createPackage(street, no, weights, contacts); pack.isDelivered = isDelivered; printPackage(pack); } printf("\n-----------------------\n"); }; bool connect2(db* myDB, const char* user, const char* pass) { if (strcmp(user, myDB->userName) == 0 && strcmp(pass, myDB->pass) == 0) { myDB->pf = fopen(myDB->fileName, "ab+"); if (myDB->pf == NULL) return false; return true; } else return false; } int main() { const char* streets[] = { "Calea Dorobanti", "Calea Victoriei", "Eminescu" }; int numbers[] = { 10, 5, 87 }; const char* contacts[] = { "John", "Anna", "Bob" }; //the weights were declared as int! float weights[] = { 10.6, 3.5, 80 }; //generate data package testData[3]; for (int i = 0; i < 3; i++) { testData[i] = createPackage(streets[i], numbers[i], weights[i], contacts[i]); } //PART 1 //print test data printf("*Test Data* The packages are: \n"); for (int i = 0; i < 3; i++) { printPackage(testData[i]); } serialized_package myPackage = serializePackage(testData[0]); package p = deserializePackage(myPackage); printf("\nThe package, which I serialized and then deserialized is: \n"); printPackage(p); //printSerializedPackage(myPackage); here I made my own function to print the serialized packages db packageDB = createDB("admin", "1234", "TestPack"); if (connect(&packageDB, "admin", "1234")) { printf("\n *Info* You are connected\n"); for (int i = 0; i < 3; i++) { //insert the serialized version insert(packageDB, serializePackage(testData[i])); } reset(packageDB); printf("\nSize of the serialized article is %d bytes", sizeof(serialized_package)); printf("\nFile size is %d bytes", getFileSize(packageDB.pf)); reset(packageDB); package p5 = selectFirstOrDefault(packageDB, "John"); printf("\nThe package with the contact given is: \n"); printPackage(p5); reset(packageDB); packageList l = selectHeavyPackages(packageDB, 5); printf("\nThe heavy packages are: "); printAll(l); //print the file content printf("\n *File Data*\n"); printAll(packageDB); close(&packageDB); } else printf("\n *Error* No connection to the DB"); //PART 2 db inputDb = createDB("admin", "1234", "InputPack"); if (connect2(&inputDb, "admin", "1234")) { printf("\n *Info* You are connected"); printf("\n *File Data*\n"); serialized_package testData2[3]; for (int i = 0; i < 3; i++) testData2[i] = serializePackage(testData[i]); insert(inputDb, testData2, 3); //checking the second insert function printAll(inputDb); reset(inputDb); printf("\nSize of the serialized article is %d bytes", sizeof(serialized_package)); printf("\nFile size is %d bytes", getFileSize(inputDb.pf)); package item = selectFirstOrDefault(inputDb, "Anna"); printf("\nThe searched package is for %s and its weight is %f\n", item.contact, item.weight); reset(inputDb); packageList list = selectHeavyPackages(inputDb, 3.5); printf("\nThe heavy packages are: "); printAll(list); //here you wrote close(&packageDB); close(&inputDb); } else printf("\n *Error* No connection to the DB"); printf("\n"); }
C
#include<stdio.h> struct list { struct list *node; int data; }; struct list *start; void insert(int x,int pos) { int i; struct list *newnode=(struct list *)malloc(sizeof(struct list)); struct list *l=start; for(i=2;i<=pos;i++) l=l->node; newnode->data=x; newnode->node=l->node; if(pos==1) start=newnode; else l->node=newnode; } void print() { struct list *l=start; if(l==NULL) { printf("empty list\n"); return; } while(l!=NULL) { printf("%d\t",l->data); l=l->node; } printf("\n"); } void delete(int pos) { if(start==NULL) { printf("list is empty.no element available for deletion\n"); return; } if(pos==1) { printf("deleted element is %d\n",start->data); start=start->node; return; } struct list *l=start; int i; for(i=3;i<=pos;i++) l=l->node; printf("deleted element is %d\n",(l->node)->data); l->node=(l->node)->node; } int main() { start=(struct list *)malloc(sizeof(struct list)); int menu=1; char choice; while(menu==1) { printf("ENTER YOR CHOICE:\n1->insert an element\n2->delete an element\n3->show the current list\n4->exit menu\n"); scanf("%c"&choice); switch(choice) { case '1': { int x; printf("enter the element to be inserted: "); scanf("%d",&x); printf("enter your choice:\n1->insert at the beginning\n2->insert in the middle\n
C
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct node { int data; struct node* link; }Node; //typedef struct //{ // listNode* head; //}linkedList_h; // //linkedList_h* createLinkedList_h(void) //{ // linkedList_h* L; // L = (linkedList_h*)malloc(sizeof(linkedList_h)); // L->head = NULL; // return L; //} // //void freeLinkedList_h(linkedList_h* L) //{ // listNode* p; // while (L->head != NULL) // { // p = L->head; // L->head = L->head->link; // free(p); // p = NULL; // } //} int main() { Node* head = (Node*)malloc(sizeof(Node)); Node* node1 = (Node*)malloc(sizeof(Node));// Node* node2 = (Node*)malloc(sizeof(Node)); Node* node3 = (Node*)malloc(sizeof(Node)); Node* node4 = (Node*)malloc(sizeof(Node)); Node* node5 = (Node*)malloc(sizeof(Node)); if (node1 == NULL) return; head->link = node1; node1->data = 10; node1->link = node2; node2->data = 20; node2->link = node3; node3->data = 30; node3->link = node4; node4->data = 40; node4->link = node5; node5->data = 50; node5->link = NULL; int i = 1; Node* curr = head->link; while (curr != NULL) { printf("%d° : %d\n", i++, curr->data); curr = curr->link; } free(head); free(node1); free(node2); free(node3); free(node4); free(node5); return 0; }
C
/* * frequency.h * * Counter structure for counting token frequencies. */ #ifndef FREQUENCY_H #define FREQUENCY_H /* * Structure used to count token frequencies. * * Example usage: * * FrequencyMap *fm = FM_create(3); * FM_add(fm, "apple"); * FM_add(fm, "orange"); * FM_add(fm, "banana"); * FM_add(fm, "apple"); * * int apples = FM_frequency(fm, "apple"); // 2 * int oranges = FM_frequency(fm, "orange"); // 1 * int bananas = FM_frequency(fm, "banana"); // 1 * FM_destroy(fm); * */ typedef struct frequency_map FrequencyMap; /* * Create a new FrequencyMap instance. * Capacity determines the number of distinct tokens the instance can track. */ FrequencyMap *FM_create(size_t capacity); /* * Deallocate the instance. * This does not affect any of the tokens referenced by the map. */ void FM_destroy(FrequencyMap *fm); /* * Increase the frequency of a token by 1 (inserts the token if it is not * already present in the map). */ void FM_add(FrequencyMap *fm, char *token); /* * Get the frequency of a token. Returns 0 if the token is not in the map. */ int FM_frequency(FrequencyMap *fm, char *token); #endif
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX 1000 void add(char s1[],char s2[]) { int len1 = strlen(s1); int len2 = strlen(s2); int lens= (len1>len2)?(len1+1):(len2+1); //char sum[lens] = {0}; int i,j,k,l; int c = 0; char *sum = (char *)malloc(sizeof(char)*lens); //i = len1-1,j = len2-1,k=lens-1 i = len1-1;j = len2-1;k=lens-1; for(;i>=0&&j>=0;) { int res = s1[i]-'0'+s2[j]-'0'+c; // printf("%d",s1[i]-'0'+s2[j]-'0'+c); if(res>9) { sum[k] = (res)%10+'0'; c=1; } else { sum[k] = res+'0'; c=0; } // printf("%d:%c\n",k,sum[k]); i--;j--;k--; } //printf("i:%d\nj:%d\nk:%d\n",i,j,k); if(i>=0) { //j = i,l =k j = i;l =k; for(;j>=0;j--,l--) { int res = s1[j]-'0'+c; if(res>9) { sum[l] = (res)%10+'0'; c=1; } else { sum[l] = res+'0'; c=0; } //printf("%d:%c\n",l,sum[l]); } } if(j>=0) { //i = j, l=k i = j; l=k; for(;i>=0;i--,l--) { int res = s2[i]-'0'+c; if(res>9) { sum[l] = (res)%10+'0'; c=1; } else { sum[l] = res+'0'; c=0; } //printf("%d:%c\n",l,sum[l]); } } // if(c==0) // { // for(i = lens-1;i>0;i--) // printf("%d:%c\n",i,sum[i]); // printf("\n"); // } // else // { // for(i = lens-1;i>0;i--) // printf("%d:%c\n",i,sum[i]); // printf("1\n"); // } if(c==0) { for(i = 1;i<lens;i++) printf("%c",sum[i]); printf("\n"); } else { printf("1"); for(i = 1;i<lens;i++) printf("%c",sum[i]); printf("\n"); } free(sum); } int main() { int ncase; scanf("%d",&ncase); while(ncase--) { char s1[MAX] = {0}; char s2[MAX] = {0}; scanf("%s%s",s1,s2); add(s1,s2); } }
C
/* storage class: (auto, register, static, extern) * defines the scope (visibility) and life-time of var, func. */ // auto: default storage class for all local var // register: define local var to be stored in a register instead of RAM // static: instructs the compiler to keep a local var in existence // extern: give reference of a globle var that is visible to ALL program files. #include <stdio.h> void func(void); static int count = 5; int main() { while (count--) { func(); } return 0; } void func(void) { static int i = 5; i++; printf("i is %d and count is %d\n", i, count); }
C
#include<stdio.h> #include<math.h> int arearectangle(int l,int b) { return l*b; } int perimeterrectangle(int l,int b) { return 2*(l+b); } int areasquare(int s) { return s*s; } int perimetersquare(int s) { return 4*s; } int arearhombus(int d1,int d2) { return 0.5*d1*d2; } int perimeterrhombus(int s) { return 4*s; }
C
#include<stdio.h> #include<string.h> int main() { char n[250]; long long int t,p,q; gets(n); scanf("%lld", &t); while(t--) { scanf("%lld %lld", &p,&q); if(q%p==0) printf("YES\n"); else printf("NO\n"); } return 0; }
C
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> #include<error.h> #include<stdbool.h> #include<sys/types.h> #include<dirent.h> extern int errorno; int main(int args,char**argv) { char*source=argv[1]; char*destination=argv[2]; int sourcelength=strlen(source); int destilength=strlen(destination); _Bool flag,is_exit; char*p1=source+sourcelength-1; char*p2=destination+destilength-1; while(*p1--==*p2--&&*p1!='.'); if(*p1=='.'&&*p2=='.')//判断文件扩展名是否相同,相同即为从文件到文件 { flag=true; while(*p1==*p2&&*p1!='/')p1--,p2--; if(*p1==*p2&&*p1=='/'&&*p2=='/') is_exit=true; else is_exit=false; } else//从文件到目录 { flag=false; p1=source+sourcelength-1; } if(flag==true)//从文件复制到文件 { int rfd=open(source,O_RDONLY); int fd; if(is_exit==false) fd=open(destination,O_WRONLY|O_CREAT|O_TRUNC); else { char option; printf("覆盖for y;合并 for n\n"); scanf("%c",&option); if(option=='y') fd=open(destination,O_WRONLY|O_CREAT|O_TRUNC,0xff); else fd=open(destination,O_APPEND|O_WRONLY); } char ch; while(read(rfd,&ch,1)!=0) { if(write(fd,&ch,1)==-1) { fprintf(stderr,"写入文件错误"); break; } } if(close(rfd)==0&&close(fd)==0); else { fprintf(stderr,"关闭文件出错"); } } else//从文件复制到目录 { DIR*di=opendir(destination);p1=source+sourcelength-1; if(di==NULL) { perror(destination);//异常处理 return 1; } char*filename; while(*p1!='/') p1--; filename=p1; struct dirent* dirp; is_exit=false; while((dirp=readdir(di))!=NULL) { if(strcmp(dirp->d_name,filename+1)==0) { is_exit=true; break; } } char option='y'; if(is_exit==true) { printf("覆盖for y;合并 for n"); scanf("%c",&option); } char path[80]={'\0'}; strcpy(path,destination); strcat(path,filename); int rfd=open(source,O_RDONLY); int fd; if(option=='y') { fd=open(path,O_WRONLY|O_CREAT|O_TRUNC,0xffff); char ch; if(closedir(di)==-1) perror("destination"); while(read(rfd,&ch,1)!=0) { if(write(fd,&ch,1)==-1) { fprintf(stderr,"写入文件错误"); break; } } } else { fd=open(path,O_APPEND|O_WRONLY,0xffff); char ch; if(closedir(di)==-1) perror("destination"); while(read(rfd,&ch,1)!=0) { if(write(fd,&ch,1)==-1) { fprintf(stderr,"写入文件错误"); break; } } if(close(rfd)==0&&close(fd)==0); else { fprintf(stderr,"关闭文件出错"); } } return 0; } } #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> #include<error.h> #include<stdbool.h> #include<sys/types.h> #include<dirent.h> extern int errorno; int main(int args,char**argv) { char*source=argv[1]; char*destination=argv[2]; int sourcelength=strlen(source); int destilength=strlen(destination); _Bool flag,is_exit; char*p1=source+sourcelength-1; char*p2=destination+destilength-1; while(*p1--==*p2--&&*p1!='.'); if(*p1=='.'&&*p2=='.')//判断文件扩展名是否相同,相同即为从文件到文件 { flag=true; while(*p1==*p2&&*p1!='/')p1--,p2--; if(*p1==*p2&&*p1=='/'&&*p2=='/') is_exit=true; else is_exit=false; } else//从文件到目录 { flag=false; p1=source+sourcelength-1; } if(flag==true)//从文件复制到文件 { int rfd=open(source,O_RDONLY); int fd; if(is_exit==false) fd=open(destination,O_WRONLY|O_CREAT|O_TRUNC); else { char option; printf("覆盖for y;合并 for n\n"); scanf("%c",&option); if(option=='y') fd=open(destination,O_WRONLY|O_CREAT|O_TRUNC,0xff); else fd=open(destination,O_APPEND|O_WRONLY); } char ch; while(read(rfd,&ch,1)!=0) { if(write(fd,&ch,1)==-1) { fprintf(stderr,"写入文件错误"); break; } } if(close(rfd)==0&&close(fd)==0); else { fprintf(stderr,"关闭文件出错"); } } else//从文件复制到目录 { DIR*di=opendir(destination);p1=source+sourcelength-1; if(di==NULL) { perror(destination);//异常处理 return 1; } char*filename; while(*p1!='/') p1--; filename=p1; struct dirent* dirp; is_exit=false; while((dirp=readdir(di))!=NULL) { if(strcmp(dirp->d_name,filename+1)==0) { is_exit=true; break; } } char option='y'; if(is_exit==true) { printf("覆盖for y;合并 for n"); scanf("%c",&option); } char path[80]={'\0'}; strcpy(path,destination); strcat(path,filename); int rfd=open(source,O_RDONLY); int fd; if(option=='y') { fd=open(path,O_WRONLY|O_CREAT|O_TRUNC,0xffff); char ch; if(closedir(di)==-1) perror("destination"); while(read(rfd,&ch,1)!=0) { if(write(fd,&ch,1)==-1) { fprintf(stderr,"写入文件错误"); break; } } } else { fd=open(path,O_APPEND|O_WRONLY,0xffff); char ch; if(closedir(di)==-1) perror("destination"); while(read(rfd,&ch,1)!=0) { if(write(fd,&ch,1)==-1) { fprintf(stderr,"写入文件错误"); break; } } if(close(rfd)==0&&close(fd)==0); else { fprintf(stderr,"关闭文件出错"); } } return 0; } }
C
// // Created by Oleg Berdyshev on 3/10/20. // #include "parser.h" /** * @param mode - current mode (unquote, quote, double quote). Mutable parameter * @param exp - expression * @param pos - current position in the expression which will effect mode. */ void mx_change_mode(e_mode *mode, char *exp, int pos) { switch (*mode) { case unquote: if (exp[pos] == '"') if (mx_count_esc(exp, pos) % 2 == 0) *mode = dquote; if (exp[pos] == '\'') if (mx_count_esc(exp, pos) % 2 == 0) *mode = quote; break; case dquote: if (exp[pos] == '"') if (mx_count_esc(exp, pos) % 2 == 0) *mode = unquote; break; case quote: if (exp[pos] == '\'') *mode = unquote; break; } }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> // a helper linked list data type typedef struct Node { int key; int val; struct Node* head; struct Node* next; } ListNode; // helper QueueNode linked list (implementation) class struct QueueNode { struct QueueNode *QueueTop; struct QueueNode *QueueEnd; int length; int item; struct QueueNode *next; } QueueNode; int n; // number of key-value pairs ListNode* head; // the linked list of key-value pairs ListNode* createNode(int key, int val, ListNode* next) { ListNode* temp = (struct Node*)malloc(sizeof(struct Node)); temp->key = key; temp->val = val; temp->next = next; return temp; } /* * Returns the number of key-value pairs in this symbol table. * * @return the number of key-value pairs in this symbol table */ int size() { return n; } /** * Returns true if this symbol table is empty. * * @return {@code true} if this symbol table is empty; * {@code false} otherwise */ bool isEmpty(struct QueueNode* st) { return size() == 0; } /** * Returns the value associated with the given key in this symbol table. * * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ int get(ListNode* temp, int cKey) { ListNode* runner; if (cKey == '\0') { printf("argument to get() is null"); return 0; } for (ListNode* runner = temp->head; runner != NULL; runner = runner->next) { if (cKey == runner->key) { return runner->val; } } return 0; } /** * Returns true if this symbol table contains the specified key. * * @param key the key * @return {@code true} if this symbol table contains {@code key}; * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ bool contains(ListNode* temp, int key) { if (key == '\0') { printf("argument to contains() is null"); return false; } return get(temp, key) != '\0'; } // delete key in linked list beginning at Node x // warning: function call stack too large if table is large ListNode* deleteKey(ListNode* x, int key) { if (x == NULL) { return NULL; } if (key == x->key) { n--; return x->next; } x->next = deleteKey(x->next, key); return x; } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ void delete(ListNode* x, int key) { if (key == '\0') { printf("argument to delete() is null"); return; } x->head = deleteKey(x->head, key); } /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ void put(ListNode* temp, int key, int val) { ListNode* runner; if (key == '\0') { printf("first argument to put() is null"); return; } if (val < 0) { delete(temp, key); return; } for (ListNode* runner = temp->head; runner != NULL; runner = runner->next) { if (key == (runner->key)) { runner->val = val; return; } } temp->head = createNode(key, val, temp->head); n++; } /** * Adds the item to this queue. * * @param item the item to add */ void enqueue(struct QueueNode* st, int correctNum) { // creating a new oldLast which points to the previous last node struct QueueNode* oldLast = (struct QueueNode*)malloc(sizeof(QueueNode)); oldLast = st->QueueEnd; // create the new last node st->QueueEnd = (struct QueueNode*)malloc(sizeof(QueueNode)); // update the properties of the last node; its next pointer should point to NULL st->QueueEnd->item = correctNum; st->QueueEnd->next = NULL; // checking if st is empty; set the QueueTop value to the QueueEnd value if(isEmpty(st)) { st->QueueEnd = st->QueueTop; } // update the next pointer of the oldLast to point to the the newly allocated st0>QueueEnd else { oldLast->next = st->QueueEnd; } // update the length properties! st->length++; } /** * Returns all keys in the symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * * @return all keys in the symbol table */ struct QueueNode* keys(ListNode* temp) { struct QueueNode* queueMain = (struct QueueNode*)malloc(sizeof(QueueNode)); // Queue<int> queue = new Queue<int>(); for (ListNode* x = temp->head; x != NULL; x = x->next) { enqueue(queueMain, x->key); } return queueMain; } /** * Unit tests the {@code SequentialSearchST} data type. * * @param args the command-line arguments */ int main() { int p, count, range; ListNode* searchMain = (struct Node*)malloc(sizeof(struct Node)); printf("Please enter a valid range of integers you want to include!"); printf("\n"); scanf("%d", &count); printf("Now enter these integers each seperated by a space!"); printf("\n"); for (int i = 0; i < count; i++) { p = i; scanf("%d", &searchMain->key); put(searchMain, searchMain->key, p); } for (ListNode* s = searchMain->head; s != NULL; s = s->next) { printf("%d %d\n", s->key, s->val); } return 0; }
C
#include <stdio.h> int main(int argc, char** argv) { if (argc <= 1) { printf("usage: %s <password>\n", argv[0]); return(-1); } char* pass = argv[1]; if ( (pass[0] == 'P') && (pass[1] == 'A') && (pass[2] == 'S') && (pass[3] == 'S') && (pass[4] == 'W') && (pass[5] == 'O') && (pass[6] == 'R') && (pass[7] == 'D') ) { puts("WIN"); } else { puts("FAIL"); } }
C
//--------------------------------------------------------------------------------------------- // S C O R E S . C // // Tudo sobre a tabela de scores - exibir, alterar, gravar... //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // Constantes //--------------------------------------------------------------------------------------------- #define BOX_COLOR 241 // Cor da caixa que rodeia as letras no quadro "PARABNS" //--------------------------------------------------------------------------------------------- // Variveis globais da fonte SCORES.C //--------------------------------------------------------------------------------------------- // Player um array de 10 estruturas. Isto , so 10 posies (pois "OS MELHORES SOB-GELO" // um top 10), em que cada uma possui um campo name para o nome do jogador, e um campo score // para a respectiva pontuao static struct { char *name; // Apontador para o nome do jogador int score; // Varivel inteira para a pontuao } Player[ 10 ]; // Mximo = 10 jogadores no top //--------------------------------------------------------------------------------------------- // Funes locais da fonte SCORES.C //--------------------------------------------------------------------------------------------- // ͻ // Nome: insert_your_name Autor: Jorge Alexandre Cabrita Morgado (Fev/Mar/Abr 1994) // Ķ // Objectivo: Rotina utilizada para inserir o nome do jogador caso tenha sido alcanado // um novo high-score. A funo exibe o quadro das letras no ecran e executa // o processamento de teclado. Ser exibida uma caixa magenta (cor 241) em // volta da letra actualmente seleccionada. O utilizador poder ento mover // essa mesma caixa (isto , seleccionar outra letra) utilizando as quatro // arrow-keys. Pode ainda, abandonar a introduo teclando <ESCAPE> ou // seleccionado a palavra "FIM" - no primeiro caso a funo retornar o // ltimo nome introduzido pelo jogador; no segundo caso a funo no retorna // nome nenhum (retorna um string vazia - "" ou '\0'). // Tome especial ateno s teclas <RETURN>, <ENTER>) ou <SPACE>: elas so // utilizada para seleccionar o actual contedo da caixa, e tem algumas // particulariedades, especialmente quando esse contedo " " (SPACE), // "<-" (BACKSPACE), "FIM", ou ainda a tentativa de introduzir uma letra que // j no cabe na range (cujo mximo de 12 caracteres). // // Parmetros: ptrName o endereo de incio do nome introduzido (e que ser retornado). // // Retorna: A funo retorna um apontador para o incio nome introduzido pelo jogador. // ͼ static char *insert_your_name( char *ptrName ) { BOOLEAN bExitInsert = FALSE; // Controla o final (saida) da introduo do nome static char oldName[ 13 ] = ""; // Buffer para o ltimo nome introduzido char bufName[ 13 ] = ""; // Buffer para o nome a introduzir int n = 0; // Contador para o apontador bufName int nX = 0, nY = 0; // Posio (nX,nY) nas matrizes de coordenadas da caixa int nLeft[ 5 ][ 6 ] = { { 113, 129, 145, 161, 177, 193 }, // Coordenadas { 113, 129, 145, 161, 177, 193 }, // X do canto { 113, 129, 145, 161, 177, 193 }, // esquerdo da { 113, 129, 145, 161, 177, 193 }, // caixa. { 113, 129, 145, 161, 177, 177 } }; int nRight[ 5 ][ 6 ] = { { 125, 141, 157, 173, 189, 205 }, // Coordenadas { 125, 141, 157, 173, 189, 205 }, // X do canto { 125, 141, 157, 173, 189, 205 }, // direito da { 125, 141, 157, 173, 189, 205 }, // caixa. { 125, 141, 157, 173, 205, 205 } }; int nTop[ 5 ] = { 50, 66, 82, 98, 114 }; // Coordenadas Y do topo da caixa int nBottom[ 5 ] = { 62, 78, 94, 110, 126 }; // Coordenadas Y do fundo da caixa v_putimage( 97, 35, 126, 122, ptrNewScore ); // Exibe a imagem do quadro "PARABNS" write_str( 112, 139, "????????????" ); // Exibe a range para o nome a introduzir v_box( nLeft[ nY ][ nX ], nTop[ nY ], nRight[ nY ][ nX ], nBottom[ nY ], BOX_COLOR ); // Cx while( KEYPRESSED ); // Aguarda que todas as teclas estejam soltas do { if( KEYPRESSED ) // Se alguma tecla foi pressionada { v_box( nLeft[ nY ][ nX ], nTop[ nY ], nRight[ nY ][ nX ], nBottom[ nY ], 0 ); // Caixa if( KEY_ESCAPE ) // Tecla <ESCAPE> { bExitInsert = TRUE; // Abandona no prximo ciclo strcpy( bufName, oldName); // Assume o ltimo nome introduzido } else if( KEY_ENTER || KEY_SPACE ) // Se pressionou a tecla <ENTER> sobre... { if( nY == 4 && nX >= 4 && nX <= 5 ) // Se <ENTER> sobre "FIM" bExitInsert = TRUE; else if( n > 0 && nX == 3 && nY == 4 ) // Se <ENTER> sobre "<-" write_str( 112 + 8 * --n, 139, "?" ); // Apaga a letra e recua valor n else if( n > 11 || ( n == 0 && nX==3 && nY==4 ) ) // Se exedeu range para + ou - s_out_of_range(); // Som - tentou agir fora a range else if( nX == 2 && nY == 4 ) // Se <ENTER> sobre " " *(bufName + n++) = '^'; // Insere um espao no nome else // Se <ENTER> sobre uma letra *(bufName + n++) = 'A' + nX + nY * 6; // Insere a letra escolhida *(bufName + n) = '\0'; // Insere final de string write_str( 112, 139, bufName ); // Exibe o nome j introduzido } else if( KEY_RIGHT && ( ( nX == 4 && nY == 4 ) || ++nX > 5 ) ) // Arrow-key right nX = 0; else if( KEY_LEFT && nX == 5 && nY == 4 ) // Arrow-key left sobre "FIM" nX -= 2; else if( KEY_LEFT && --nX < 0 ) // Arrow-key left sobre uma letra nX = 5; else if( KEY_DOWN && ++nY > 4 ) // Arrow-key down nY = 0; else if( KEY_UP && --nY < 0 ) // Arrow-key up nY = 4; v_box( nLeft[ nY ][ nX ], nTop[ nY ], nRight[ nY ][ nX ], nBottom[ nY ], BOX_COLOR ); while( KEYPRESSED ); // Aguarda que a tecla seja libertada } } while( !bExitInsert ); // Ciclo - enquanto a "saida" for FALSE if( ( ptrName = ( char * )realloc( ptrName, strlen( bufName ) + 1 ) ) == NULL ) // Re-aloca exit_with_error( "Re-alocao de memria" ); // Informa o erro e regressa ao DOS strcpy( ptrName, bufName ); // Copia o contedo do buffer para o apontador strcpy( oldName, bufName ); // Actualiza o ltimo nome introduzido cls_game_area(); // Limpa o ecran de jogo (tabuleiro) return( ptrName ); // Retorna o endereo de incio do nome introduzido } // ͻ // Nome: scores_quicksort Autor: Jorge Alexandre Cabrita Morgado (Fev/Mar/Abr 1994) // Ķ // Objectivo: Ordena as pontues decrescentemente, bem como, os respectivos nomes. // Para efectuar esta ordenao eu recorri ao mtodo QUICKSORT, da que no // vale a pena perder tempo com explicaes, pois parto do princpio que voc // conhece este algoritmo. // No entanto, s uma nota: a ordenao decrescente uma vez que quem tem // maior pontuao deve surgir em primeiro lugar na tabela. // // Parmetros: left e right so os limites do segmento a ordenar. // ͼ static void scores_quicksort( int left, int right ) { int media, ndx1, ndx2, i; int troca; // Varivel temporria para a troca dos scores char *temp; // Varivel temporria para a troca dos names media = Player[ ( left + right ) / 2 ].score; ndx1 = left; ndx2 = right; do { while( Player[ ndx1 ].score > media ) ndx1++; // Aproxima-se da mdia por baixo while( media > Player[ ndx2 ].score ) ndx2--; // Aproxima-se da mdia por cima if( ndx1 <= ndx2 ) // Neste caso vai haver troca { temp = Player[ ndx1 ].name; // Troca Player[ ndx1 ].name = Player[ ndx2 ].name; // os Player[ ndx2 ].name = temp; // names troca = Player[ ndx1 ].score; // Troca Player[ ndx1++ ].score = Player[ ndx2 ].score; // os Player[ ndx2-- ].score = troca; // scores } } while( ndx1 <= ndx2 ); if( left < ndx2 ) scores_quicksort( left, ndx2 ); // Recursividade com if( ndx1 < right ) scores_quicksort( ndx1, right ); // um novo segmento } // ͻ // Nome: save_scores Autor: Jorge Alexandre Cabrita Morgado (Fev/Mar/Abr 1994) // Ķ // Objectivo: Grava a tabela d' "OS MELHORES SOB-GELO" no ficheiro SCORES.SG. // Veja no manual do programador como est organizada a informao da tabela // dentro do ficheiro SCORES.SG. // // Parmetros: Nenhum // ͼ static void save_scores( void ) { char tmpScore[ 5 ]; // Apontador temporrio para a pontuao int nTotal; // Total de nomes existentes na tabela dos scores (max.10) int nHandle; // Handle do ficheiro "SCORES.TXT" if( (nHandle = open("SCORES.SG", O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE) ) == -1 ) // Se ocorreu um erro na abertura do ficheiro "SCORES.SG" exit_with_error( "Erro na abertura de SCORES.SG:" ); // Exibe a mensagem e volta ao DOS for( nTotal = 0; nTotal < 10 && Player[ nTotal ].score; nTotal++ ) // Ciclo - corre a tabela if( write( nHandle, Player[ nTotal ].name, strlen( Player[ nTotal ].name ) + 1 ) == -1 ) // Se ocorreu um erro na escrita dos nomes no ficheiro "SCORES.SG" exit_with_error( "Erro escrevendo em SCORES.SG:" ); // Exibe a mensagem e volta ao DOS if( write( nHandle, "\n", 1 ) == -1 ) // Se ocorreu um erro escrevendo o caracter nova-linha no ficheiro "SCORES.SG" exit_with_error( "Erro escrevendo em SCORES.SG:" ); // Exibe a mensagem e volta ao DOS for( nTotal = 0; nTotal < 10 && Player[ nTotal ].score; nTotal++ ) // Ciclo - corre a tabela { itoa( Player[ nTotal ].score, tmpScore, 10 ); // Converte os scores para string if( write( nHandle, tmpScore, strlen( tmpScore ) + 1 ) == -1 ) // Se ocorreu um erro naescrita dos scores no ficheiro "SCORES.SG" exit_with_error( "Erro escrevendo em SCORES.SG:" ); // Exibe a mensagem e volta ao DOS } } //--------------------------------------------------------------------------------------------- // Funes externas da fonte SCORES.C //--------------------------------------------------------------------------------------------- // ͻ // Nome: load_scores Autor: Jorge Alexandre Cabrita Morgado (Fev/Mar/Abr 1994) // Ķ // Objectivo: Inicializa ptrScores (apontador para a imagem da tabela dos scores). // A funo est ainda encarregue de inicializar as 10 estruturas de Player. // Isso feito abrindo o ficheiro SCORES.SG que contm a tabela desde a // a ltima vez que o jogo foi carregado e algum record foi alcanado. // Se por exemplo s existirem 5 nomes e respectivas pontuaes no ficheiro // SCORES.SG, somente as 5 primeiras estruturas de Player[ 10 ] sero // inicializadas. // Veja no manual do programador com est organizada a informao da tabela // dentro do ficheiro SCORES.SG. // // Parmetros: Nenhum // ͼ void load_scores( void ) { char *ptrFile; // Apontador para o ficheiro "SCORES.SG" int nTotal; // Total de nomes existentes na tabela dos scores (max.10) int i; // Contador para ciclo for ptrScores = getfile( "SCORES.BIN", O_BINARY ); // Carrega imagem da tabela na memria ptrNewScore = getfile( "NEWSCORE.BIN", O_BINARY ); // Carrega a imagem do quadro "PARABNS" ptrFile = getfile( "SCORES.SG", O_TEXT ); // Carrega os scores da tabela na memria for( nTotal = 0; nTotal < 10 && *ptrFile != '\n'; nTotal++ ) { Player[ nTotal ].name = ( char * )calloc( strlen( ptrFile ) + 1, sizeof( char ) ); strcpy( Player[ nTotal ].name, ptrFile ); // Apontadores para cada nome ptrFile += strlen( Player[ nTotal ].name ) + 1; // Avana para o prximo nome } ptrFile++; // Salta o caracter '\n' que indica o final dos nomes - agora vm as pontuaes for( i = 0; i < nTotal; i++ ) { Player[ i ].score = atoi( ptrFile ); // Apontador para cada pontuao ptrFile += strlen( ptrFile ) + 1; // Avana para a prxima pontuao } for( ; nTotal < 10; nTotal++ ) // Se a tabela dos scores ainda no tem 10 nomes { Player[ nTotal ].name = NULL; // Coloca o resto dos pointers a apontar para nada Player[ nTotal ].score = 0; // Coloca o resto das pontuaes a zero } scores_quicksort( 0, 9 ); // Ordena a tabela pois o ficheiro pode estar corrompido } // ͻ // Nome: scores_display Autor: Jorge Alexandre Cabrita Morgado (Fev/Mar/Abr 1994) // Ķ // Objectivo: Exibe a tabela dos high-scores no ecran. // // Parmetros: Nenhum // ͼ void scores_display( void ) { char tmpScore[ 5 ]; // Apontador temporrio para a pontuao int i; // Contador para ciclo for v_putimage( 70, 76, 180, 114, ptrScores ); // Exibe a imagem da tabela for( i = 0; i < 10 && Player[ i ].score; i++ ) // Enquanto houver scores (maiores que zero) { write_str( 93, 99 + i * 8, Player[ i ].name ); // Exibe nome do jogador itoa( Player[ i ].score, tmpScore, 10 ); // Converte score para string write_str( 237 - strlen( tmpScore ) * 8, 99 + i * 8, tmpScore ); // Escreve o score } while( KEY_ENTER ) // Espera enquanto no libertar a tecla <ENTER> (ou <RETURN>) back_letters(); // Enquanto isso vai correndo o rodap while( !KEYPRESSED ) // Espera enquanto no for pressionada uma tecla qualquer back_letters(); // Enquanto isso vai correndo o rodap v_clswin( 70, 76, 250, 190, 0 ); // Limpa a zona da tabela } // ͻ // Nome: get_a_highscore Autor: Jorge Alexandre Cabrita Morgado (Fev/Mar/Abr 1994) // Ķ // Objectivo: Verifica se o jogador merece entrar na tabela "OS MELHORES SOB-GELO". // Se sim, substitui o ltimo da tabela pelo actual jogador, bem como, a sua // pontuao. No final re-ordena todos os elementos da tabela. // // Parmetros: nHighScore a pontuao alcanada pelo jogador candidato a um lugar na // tabela. // ͼ void get_a_highscore( int nHighScore ) { if( nHighScore > Player[ 9 ].score ) // Se o score alcanado superior ao ltimo da tabela { Player[ 9 ].name = insert_your_name( Player[ 9 ].name ); // Introduo do nome do jogador Player[ 9 ].score = nHighScore; // Coloca o novo score na tabela scores_quicksort( 0, 9 ); // Re-ordena os scores e os respectivos nomes save_scores(); // Salva a tabela d' "OS MELHORES SOB-GELO" } }
C
/** @defgroup unicode Unicode @section unicode_character_encodings Character Encodings Currently supported character encodings - _sym_utf_8; // utf-8, no bom - _sym_utf_16; // utf-16, big-endian - _sym_utf_16be; // utf-16, big-endian - _sym_utf_16le; // utf-16, little-endian - _sym_iso_8859_1; // iso-8859-1 (latin-1) - _sym_us_ascii; // us-ascii 7-bit - _sym_ms_ansi; // ms-ansi (microsoft code page 1252) - _sym_macroman; // mac roman - - _sym_charset_converter; - _sym_convert; @subsection unicode_character_encodings_example Example Usage @code t_charset_converter *conv = object_new(CLASS_NOBOX, gensym("charset_converter"), ps_macroman, ps_ms_ansi); char *cstr = "Text to convert"; char *cvtbuffer = NULL; // to-be-allocated data buffer long cvtbuflen = 0; // length of buffer on output if (conv) { // note that it isn't necessary to send in a 0-terminated string, although we do so here if (object_method(conv, gensym("convert"), cstr, strlen(cstr) + 1, &cvtbuffer, &cvtbuflen) == ERR_NONE) { // do something with the converted buffer sysmem_freeptr(cvtbuffer); // free newly allocated data buffer } object_free(conv); // free converter } @endcode */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "board.h" int validMove(disk played, disk board[SIZE][SIZE]) //checks if the move is valid. 1st checks your disk is next to opposite colour, { //then calls endsWithYourColour. Returns 0 if valid 1 if not. int x = played.pos.row; int y = played.pos.col; int Oppositecolour; if(played.type == WHITE) Oppositecolour = BLACK; else if (played.type == BLACK) Oppositecolour = WHITE; for(int i = 0; i < 9; i++) //to check all directions surrounding played piece { if( ((x >= 0) && (y >= 0)) && ((x<= 7) && (y <= 7)) ) //if the piece is within the board { switch(i) //checking what piece is next to the played piece { case 0: if((board[x][y-1].type == Oppositecolour) && ((x>=0)&&(y >0)&&(x<=7)&&(y<=7))) //checking north of played piece if(endsWithYourColour(played,i,board) == 0) return 0; break; case 1: if((board[x+1][y-1].type == Oppositecolour) &&((x>=0)&&(y>0)&&(x<7)&&(y<=7))) //checking north east if(endsWithYourColour(played,i,board) == 0) return 0; break; case 2: if((board[x+1][y].type == Oppositecolour) && ((x>=0)&&(y>=0)&&(x<7)&&(y<=7))) //east if(endsWithYourColour(played,i,board) == 0) return 0; break; case 3: if((board[x+1][y+1].type == Oppositecolour) && ((x>=0)&&(y>=0)&&(x<7)&&(y<7))) //south east if(endsWithYourColour(played,i,board) == 0) return 0; break; case 4: if((board[x][y+1].type == Oppositecolour) && ((x>=0)&&(y>=0)&&(x<=7)&&(y<7))) //south if(endsWithYourColour(played,i,board) == 0) return 0; break; case 5: if((board[x-1][y+1].type == Oppositecolour) &&((x>0)&&(y>=0)&&(x<=7)&&(y<7))) // south west if(endsWithYourColour(played,i,board) == 0) return 0; break; case 6: if((board[x-1][y].type == Oppositecolour) &&((x>0)&&(y>=0)&&(x<=7)&&(y<=7)))// west if(endsWithYourColour(played,i,board) == 0) return 0; break; case 7: if((board[x-1][y-1].type == Oppositecolour) && ((x>0)&&(y>0)&&(x<=7)&&(y<=7))) // north west if(endsWithYourColour(played,i,board) == 0) return 0; break; default : return 1; } } } } int endsWithYourColour(disk played, int i, disk board[SIZE][SIZE]) //checks that a line of opposite coloured disks ends with your disk colour { // returns 0 if true and 1 if false int currentSpace = NONE; int x = played.pos.row; int y = played.pos.col; switch(i) //checking what piece is next to the played piece { case 0: while(currentSpace != played.type && ((x>= 0) && (y > 0) && (x<=7) && (y <= 7))) //as long as piece is an oppoiste colour and itsn't the edge of the board { currentSpace = board[x][y-1].type; //checking straight ahead if(currentSpace == played.type) //if straight line is ended with same colour token return 0; y--; //moving in the straight line } break; case 1: while(currentSpace != played.type && ((x>=0) && (y > 0) && (x<7) && (y <= 7))) //keeping going until hits opposite colour and it isn't the edge of th board { currentSpace = board[x+1][y-1].type; //checking north east if(currentSpace == played.type) //if straight line is ended with the same colour token return 0; y--; //moving in straight line x++; // moving in straight line } break; case 2: while(currentSpace != played.type && ((x>= 0) && (y >= 0) && (x<7) && (y <= 7))) { currentSpace = board[x+1][y].type; //checking east if(currentSpace == played.type) return 0; x++; } break; case 3: while(currentSpace != played.type && ((x>= 0) && (y >= 0) && (x<7) && (y <7))) { currentSpace = board[x+1][y+1].type; //south east if(currentSpace == played.type) return 0; y++; x++; } break; case 4: while(currentSpace != played.type && ((x>= 0) && (y >= 0) && (x<=7) && (y < 7))) { currentSpace = board[x][y+1].type; //south if(currentSpace == played.type) return 0; y++; } break; case 5: while(currentSpace != played.type && ((x> 0) && (y >= 0) && (x<=7) && (y < 7))) { currentSpace = board[x-1][y+1].type; //south west if(currentSpace == played.type) return 0; y++; x--; } break; case 6: while(currentSpace != played.type && ((x> 0) && (y >= 0) && (x<=7) && (y <= 7))) { currentSpace = board[x-1][y].type; //west if(currentSpace == played.type) return 0; x--; } break; case 7: while(currentSpace != played.type &&((x> 0) && (y > 0) && (x<=7) && (y <= 7))) { currentSpace = board[x-1][y-1].type; //north west if(currentSpace == played.type) return 0; y--; x--; } break; default : return 1; } } bool movePlayer(int playerGo, player *player1, player *player2, disk board[SIZE][SIZE]) // Searches board for valid move { // Game Theory, APS (Like Nim) if(playerGo%2 == 0) { printf("\n %s's go.", player1->name); int valid = findValidMove(*player1, board); if(valid == 0) return false; // Returns false if no valid move, ends game printBoard(player1, player2, board); // Make move disk moveMade; moveMade.type = player1->type; disk boardsquare; int check = 1; while(check == 1) { printf("\n\n\t Insert move (x y): "); scanf("%d%*c%d", &moveMade.pos.col, &moveMade.pos.row); //the %*c is a way to stop scanf reading in characters. e.g if someone typed 3,4 the , would be discouted moveMade.pos.row -= 1; moveMade.pos.col -= 1; check = validMove(moveMade, board); if(check == 1) { printf("\n\n ERROR: Invalid move"); } } // Remove Valid Move Disks for(int r=0; r<8; r++) { for(int c=0; c<8; c++) { if(board[r][c].type == VALID) board[r][c].type = NONE; } } player1->points++; flipCounter(moveMade, player1, player2, board); } else { printf("\n %s's go.", player2->name); int valid = findValidMove(*player2, board); if(valid == 0) return false; // Returns false if no valid move, ends game printBoard(player1, player2, board); // Make move disk moveMade; moveMade.type = player2->type; disk boardsquare; int check = 1; while(check == 1) { printf("\n\n\t Insert move (x y): "); scanf("%d%*c%d", &moveMade.pos.col, &moveMade.pos.row); //the %*c is a way to stop scanf reading in characters. e.g if someone typed 3,4 the , would be discouted moveMade.pos.row -= 1; moveMade.pos.col -= 1; check = validMove(moveMade, board); if(check == 1) { printf("\n\n ERROR: Invalid move"); } } // Remove Valid Move Disks for(int r=0; r<8; r++) { for(int c=0; c<8; c++) { if(board[r][c].type == VALID) board[r][c].type = NONE; } } player2->points++; flipCounter(moveMade, player1, player2, board); } } int findValidMove(player player1, disk board[SIZE][SIZE]) { int val=0; // Changes to 1 if valid move found disk boardsquare; disk currentsquare; currentsquare.type = player1.type; for(int row=0; row<SIZE; row++) // Scans through rows { for(int col=0; col<SIZE; col++) // Scans through columns { currentsquare.pos.row = row; currentsquare.pos.col = col; boardsquare.type = board[row][col].type; if((validMove(currentsquare, board) == 0) && (boardsquare.type == NONE)) // Valid Move Found { board[row][col].type = VALID; val = 1; } } } return val; } void flipCounter(disk moveMade, player *player1, player *player2, disk board[SIZE][SIZE]) { scanCounters(moveMade, player1, player2, board, 1, 0); //south scanCounters(moveMade, player1, player2, board, 1, 1); //south east scanCounters(moveMade, player1, player2, board, 0, 1); //east scanCounters(moveMade, player1, player2, board, -1, 1); //north east scanCounters(moveMade, player1, player2, board, -1, 0); //north scanCounters(moveMade, player1, player2, board, -1, -1); //north west scanCounters(moveMade, player1, player2, board, 0, -1); //west scanCounters(moveMade, player1, player2, board, 1, -1); //south west } void scanCounters(disk moveMade, player *player1, player *player2, disk board[SIZE][SIZE], int xChange, int yChange) { int y = moveMade.pos.col + yChange; int x = moveMade.pos.row + xChange; int end = 0; int points = 0; while((y>=0 && x>=0) && (y<=7 && x<=7) && end == 0) { if(moveMade.type == WHITE) { if(board[x][y].type == WHITE) { points = returnAndFlip(moveMade, board, xChange, (x - xChange), yChange, (y - yChange)); player2->points += points; player1->points -= points; end = 1; } else if(board[x][y].type == NONE) end = 0; } else if(moveMade.type == BLACK) { if(board[x][y].type == BLACK) { points = returnAndFlip(moveMade, board, xChange, (x - xChange), yChange, (y - yChange)); player1->points += points; player2->points -= points; end = 1; } else if(board[x][y].type == NONE) end = 0; } x += xChange; y += yChange; } } int returnAndFlip(disk moveMade, disk board[SIZE][SIZE], int xChange, int x, int yChange, int y) { int point = 0; int end = 0; int colSelected = moveMade.pos.col; int rowSelected = moveMade.pos.row; while(end == 0) { if(board[x][y].type == WHITE && moveMade.type == BLACK) { board[rowSelected][colSelected].type = BLACK; board[x][y].type = BLACK; point++; } else if(board[x][y].type == BLACK && moveMade.type == WHITE) { board[rowSelected][colSelected].type = WHITE; board[x][y].type = WHITE; point++; } else end = 1; x -= xChange; y -= yChange; } return point; }
C
/************************************************************************* > File Name: 183.c > Author: wangshuai > Mail: [email protected] > Created Time: 2019年12月13日 星期五 18时26分59秒 ************************************************************************/ #include<stdio.h> int func(int n) { if (n <= 0) return 0; if (n == 1) return 1; else if (n % 2 == 0) return 3 * func(n / 2) - 1; else return 3 * func((n + 1) / 2) - 1; } int main() { int n; scanf("%d", &n); printf("%d\n", func(n)); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int boleta; int empleado; int importe; float importeVendedor1 = 0; float importeVendedor2 = 0; float importeVendedor3 = 0; float importeFinal1; float importeFinal2; float importeFinal3; int respuesta = 1; do { printf("\nIngrese el importe de la boleta: "); scanf("%d", &importe); do { printf("\nIngrese el numero del vendedor: "); scanf("%d", &empleado); } while (empleado < 1 || empleado > 3); switch(empleado) { case 1 : importeVendedor1 += importe; break; case 2 : importeVendedor2 += importe; break; case 3 : importeVendedor3 += importe; break; } printf("\n\nDesea ingresar otra boleta? 1 para continuar/0 para parar? "); scanf("%d", &respuesta); } while (respuesta != 0); importeFinal1 = (float)importeVendedor1 * 1.05; importeFinal2 = (float)importeVendedor2 * 1.05; importeFinal3 = (float)importeVendedor3 * 1.05; printf("\nEl vendedor 1 gano: %.2f", importeFinal1); printf("\nEl vendedor 2 gano: %.2f", importeFinal2); printf("\nEl vendedor 3 gano: %.2f", importeFinal3); return 0; }
C
/*File name: shmem.c *Type: C source file *Date: 2017/04/21 */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <sys/shm.h> #include <string.h> #include "shmdata.h" #include "signal.h" int shmid; void *shmem_addr= NULL; //This is the start address of the shared memory struct shared_memory_struct *shared_memory; //Creat the shared_memory /* *void permission_handler(int signal_fd):Handle the RW_flag in struct. */ void permission_handler(int signal_fd) { printf("\nPID:%d, I got a signal %d, and I will change the permission to WRITE only\n", getpid(), signal_fd); shared_memory -> RW_flag = !shared_memory->RW_flag; } /* *void shmread(int shared_memory_fd):Read the shared_memory_fd. */ void shmread(int shared_memory_fd) { //Creat the shared_memory if it doesn't exits. all the process is R/W/X permission: 0666 if((shmid = shmget((key_t)shared_memory_fd, sizeof(struct shared_memory_struct), 0666|IPC_CREAT)) == -1) { printf("PID:%d, Creat the shared memory failed in process.\n", getpid()); exit(EXIT_FAILURE); } //Link the shared_memory to the current process shmem_addr = shmat(shmid, 0 ,0); if(shmem_addr == (void*)-1) { printf("PID:%d, There is an error when Link the shared_memory into current process.\n", getpid()); exit(EXIT_FAILURE); } else printf("PID:%d, The shared_memory attached at %ld in process.\n",getpid(), (unsigned long int)shmem_addr); //Config the shared_memory shared_memory = (struct shared_memory_struct*)shmem_addr; signal(SIGALRM, permission_handler); while(1) //Read the data from the shared_memory { if(shared_memory->RW_flag != 0) //No process Write data into shared_memory, then we can Read out { printf("PID:%d, Read from the shared_memory: %s\n",getpid(),shared_memory->text); //After read out the data sleep(rand() % 3); //Send the signal to set the shared_memory can be only write. if(kill(getpid(), SIGALRM) == -1) { printf("PID:%d, Send out the signal to change the permission to write only Failure\n", getpid()); exit(EXIT_FAILURE); } else printf("PID:%d, Send out the signal to change the permission to write only Successful\n", getpid()); } else//There is another process is writing the shared_memory. sleep(1); printf("PID:%d, Waiting the data wrting into shared_memory\n",getpid()); } //Separate the shared_memory from the current process if(shmdt(shmem_addr) == -1) { printf("PID:%d, Separate the shared memory %d \"(%d)\" failed in process.\n",getpid(), shmid, shared_memory_fd); exit(EXIT_FAILURE); } //Delete the shared_memory if(shmctl(shmid, IPC_RMID, 0) == -1) { printf("PID:%d, Delete the shared memory %d \"(%d)\" failed in process.\n",getpid(), shmid, shared_memory_fd); exit(EXIT_FAILURE); } } /* *void shmwrite(int shared_memory_fd):Write the shared_memory_fd. */ void shmwrite(int shared_memory_fd) { static char Data_WR[SHMEM_SZ] = {"This is test for shared_memory"}; //Creat the shared_memory if it doesn't exits. all the process is R/W/X permission: 0666 if((shmid = shmget((key_t)shared_memory_fd, sizeof(struct shared_memory_struct), 0666|IPC_CREAT)) == -1) { printf("PID:%d, Creat the shared memory failed in process.\n", getpid()); exit(EXIT_FAILURE); } //Link the shared_memory to the current process shmem_addr = shmat(shmid, 0 ,0); if(shmem_addr == (void*)-1) { printf("PID:%d, There is an error when Link the shared_memory into current process.\n", getpid()); exit(EXIT_FAILURE); } else printf("PID:%d, The shared_memory attached at %ld in process.\n",getpid(), (unsigned long int)shmem_addr); //Config the shared_memory shared_memory = (struct shared_memory_struct*)shmem_addr; signal(SIGALRM, permission_handler); while(1) { while(shared_memory->RW_flag != 0)//Waiting the data to be read { sleep(1); printf("PID:%d, Waiting for the data to be read\n", getpid()); } printf("PID:%d, Write the date:\n", getpid()); strncpy(shared_memory -> text, Data_WR, SHMEM_SZ); printf("PID:%d, Writing the data into shared_memory.text:%s\n", getpid(), shared_memory->text); if(kill(getpid(), SIGALRM) == -1) { printf("PID:%d, Send out the signal to change the permission to Read only Failure\n", getpid()); exit(EXIT_FAILURE); } else { printf("PID:%d, Send out the signal to change the permission to Read only\n", getpid()); } } //Separate the shared_memory from the current process if(shmdt(shmem_addr) == -1) { printf("PID:%d, Separate the shared memory %d \"(%d)\" failed in process.\n",getpid(), shmid, shared_memory_fd); exit(EXIT_FAILURE); } //Delete the shared_memory if(shmctl(shmid, IPC_RMID, 0) == -1) { printf("PID:%d, Delete the shared memory %d \"(%d)\" failed in process.\n",getpid(), shmid, shared_memory_fd); exit(EXIT_FAILURE); } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_CITIES 101 #define INF 100000 struct Node { int dest; int len; int toll; struct Node *next; }; struct Node roads[MAX_CITIES]; struct Node backup[MAX_CITIES*MAX_CITIES]; int visited[MAX_CITIES]; int k, n, r; int min_len; void dfs(int c, int cur_len, int cur_toll) { int i; struct Node *node; if(cur_len>=min_len || cur_toll>k) return; if(c == n) { min_len = cur_len; return; } for(node=roads[c].next; node!=NULL; node=node->next) { if(!visited[node->dest]) { visited[node->dest] = 1; dfs(node->dest, cur_len+node->len, cur_toll+node->toll); visited[node->dest] = 0; } } } int main(int argc, char **argv) { int i, s, d, l, t, cnt=0; memset(visited, 0, sizeof(visited)); scanf("%d", &k); scanf("%d", &n); scanf("%d", &r); for(i=1; i<=n; i++) roads[i].next = NULL; for(i=0; i<r; i++) { scanf("%d %d %d %d", &s, &d, &l, &t); backup[cnt].dest = d; backup[cnt].len = l; backup[cnt].toll = t; backup[cnt].next = roads[s].next; roads[s].next = backup+cnt; ++cnt; } min_len = INF; visited[1] = 1; dfs(1, 0, 0); if(min_len == INF) printf("-1\n"); else printf("%d\n", min_len); }
C
#include "bel-ast.h" #ifndef _BEL_NODE_STACK_H #define _BEL_NODE_STACK_H typedef struct { int top; int max; bel_ast_node* contents[]; } bel_node_stack; bel_node_stack* stack_init(int max); void stack_destroy(bel_node_stack* stack); bel_ast_node* stack_peek(bel_node_stack* stack); void stack_push(bel_node_stack* stack, bel_ast_node* node); bel_ast_node* stack_pop(bel_node_stack* stack); int stack_is_empty(bel_node_stack* stack); int stack_is_full(bel_node_stack* stack); #endif /* not defined _BEL_NODE_STACK_H */