language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bdeomin <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/08 20:41:54 by bdeomin #+# #+# */ /* Updated: 2019/02/08 20:41:56 by bdeomin ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" void part_on_string(char *result, t_figure *figure, unsigned short *mask) { unsigned char b; unsigned char i; i = figure->body.index_start; b = 0; while (i <= figure->body.index_end) { if (*mask & figure->body.figure.part[b]) result[i] = figure->character; i++; b++; } *mask = *mask << 1; } void print_field(t_param *param, t_figure *figure) { char result[param->currsize][(param->currsize) + 1]; unsigned char a; unsigned short mask; ft_memset(result, '.', param->currsize * ((param->currsize) + 1)); a = 0; while (a < (param->currsize)) result[a++][param->currsize] = '\n'; while (figure) { a = 0; mask = 1; while ((mask < figure->body.byte.position[0]) && ++a) mask = mask << 1; while (mask <= figure->body.byte.position[1]) part_on_string(&result[a++][0], figure, &mask); figure = figure->next; } a = 0; while (a < (param->currsize)) write(1, result[a++], param->currsize + 1); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef scalar_t__ u_int ; typedef char u_char ; /* Variables and functions */ int /*<<< orphan*/ isascii (char) ; scalar_t__ islower (char) ; scalar_t__ isxdigit (char) ; char toupper (char) ; char xtob (char) ; u_int inet_nsap_addr(const char *ascii, u_char *binary, int maxlen) { u_char c, nib; u_int len = 0; if (ascii[0] != '0' || (ascii[1] != 'x' && ascii[1] != 'X')) return (0); ascii += 2; while ((c = *ascii++) != '\0' && len < (u_int)maxlen) { if (c == '.' || c == '+' || c == '/') continue; if (!isascii(c)) return (0); if (islower(c)) c = toupper(c); if (isxdigit(c)) { nib = xtob(c); c = *ascii++; if (c != '\0') { c = toupper(c); if (isxdigit(c)) { *binary++ = (nib << 4) | xtob(c); len++; } else return (0); } else return (0); } else return (0); } return (len); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> static char *studentName = "Bowen Johnson"; // report whether machine is big or small endian void bigOrSmallEndian() { int x = 1; if (*(char *)&x == 1) { printf("byte order: little-endian\n"); } else { printf("byte order: big-endian\n"); } } // get next float using scanf() // returns true (success) or false (failure) // if call succeeded, return float value via fPtr bool getNextFloat(float *fPtr) { // replace this code with the call to scanf() *fPtr = 0.0; scanf("%f", fPtr); if (!fPtr) { return false; } else { return true; } } // print requested data for the given number void printNumberData(float f) { int f2i = f; //int to hex printf("%10i", f2i); printf(" "); printf("0x%08X\n", f2i); //float to hex printf("%10.02f", f); printf(" "); printf("0x%08X\n", *(int*)&f); } int main(int argc, char **argv) { float f; // number currently being analyzed bool validInput; // was user input valid? printf("CS201 - A01 - %s\n\n", studentName); bigOrSmallEndian(); for (;;) { if (argc == 1) // allow grading script to control ... printf("> "); // ... whether prompt character is printed validInput = getNextFloat(&f); if (! validInput) { // encountered bad input printf("bad input\n"); while (getchar() != '\n') ; // flush bad line from input buffer continue; } printNumberData(f); if (f == 0.0) { printf("bye...\n"); break; } } printf("\n"); return 0; }
C
#include <stdio.h> int main(){ int i,low,high,mid,n,key,array[100]; printf("enter number of element : "); scanf("%d",&n); printf("enter %d integer\n",n); for(i=0;i<n;i++){ printf("enter #%d value",i+1); scanf("%d",&array[i]); } printf("enter value to find"); scanf("%d",&key); low=0; high=n-1; mid=(low+high)/2; while(low<=high){ if(array[mid]<key){ low=mid+1; } else if(array[mid]==key){ printf("%d found at location %d\n",key,mid+1); break; } else{ high=mid-1; mid=(low+high)/2; } } if(low>high){ printf("not found! %d isn't present in the list\n",key); } return 0; }
C
//------------------notes-------------------- const float As3 = 233.08*2; const float A3 = 220.00*2; const float B3 = 246.94*2; const float Cs3 = 138.59*2; const float Cs4 = 277.18*2; const float C3 = 130.81*2; const float C4 = 261.63*2; const float Ds3 = 155.56*2; const float D3 = 146.83*2; const float D4 = 293.67*2; const float E3 = 164.81*2; const float E4 = 329.63*2; const float Fs3 = 185.00*2; const float Fs4 = 369.99*2; const float F3 = 174.61*2; const float F4 = 349.23*2; const float G3 = 196.00*2; const float G4 = 392.00*2; //-------------------time--------------------- const int QUARTER = 36; const int QUARTER_DOT = 54; const int WHOLE = 144; const int HALF = 72; const int HALF_DOT = 108; const int EIGHTH = 18; //------------------functions----------------- void playNote(float freq, int length) { PlayTone(freq, length); while(bSoundActive){}; } void first() { playNote(B3, QUARTER); playNote(G3, EIGHTH); playNote(C4, QUARTER); playNote(G3, EIGHTH); playNote(Cs4, QUARTER); playNote(G3, EIGHTH); playNote(D4, WHOLE); playNote(E4, EIGHTH); playNote(B3, QUARTER); playNote(D4, EIGHTH); wait10Msec(EIGHTH); playNote(D4, EIGHTH); playNote(E4, QUARTER); playNote(B3, QUARTER); playNote(D4, HALF); playNote(C4, QUARTER); playNote(F3, EIGHTH); wait10Msec(EIGHTH); playNote(D4, QUARTER); playNote(Cs4, EIGHTH); playNote(C4, QUARTER); } void second() { playNote(B3, EIGHTH); playNote(A3, WHOLE); wait10Msec(EIGHTH); playNote(B3, EIGHTH); playNote(Fs3, QUARTER); playNote(A3, EIGHTH); wait10Msec(EIGHTH); playNote(A3, QUARTER); playNote(B3, EIGHTH); playNote(Fs3, QUARTER); playNote(A3, HALF); playNote(G3, EIGHTH); playNote(C3, QUARTER); wait10Msec(EIGHTH); playNote(C3, QUARTER); playNote(Cs3, QUARTER); playNote(D3, QUARTER); playNote(Ds3, EIGHTH); playNote(E3, HALF_DOT); playNote(E4, QUARTER_DOT); playNote(D4, QUARTER); playNote(C4, EIGHTH); wait10Msec(EIGHTH); playNote(B3, EIGHTH); playNote(A3, QUARTER); } void third() { playNote(G3, EIGHTH); playNote(Fs3, QUARTER_DOT); playNote(B3, HALF); playNote(Fs3, EIGHTH); playNote(A3, QUARTER); playNote(G3, WHOLE); wait10Msec(18); playNote(E3, QUARTER); playNote(G3, QUARTER); playNote(B3, QUARTER); playNote(E4, QUARTER); playNote(Fs4, EIGHTH); playNote(G4, HALF_DOT); wait10Msec(18); playNote(E4, QUARTER); playNote(G4, EIGHTH); playNote(Fs4, QUARTER); playNote(E4, EIGHTH); playNote(F4, QUARTER); playNote(B3, QUARTER); playNote(Fs4, QUARTER_DOT); playNote(F4, EIGHTH); playNote(E4, QUARTER); playNote(F4, EIGHTH); playNote(C4, EIGHTH); playNote(E4, QUARTER); playNote(As3, QUARTER); playNote(E4, QUARTER_DOT); playNote(E4, EIGHTH); playNote(D4, QUARTER); playNote(Cs4, EIGHTH); playNote(D4, QUARTER); } //----------------------main--------------------- task main() { bool flamingo = true; bool blownUp = true; while(flamingo == blownUp) { first(); second(); third(); } }
C
/* * os.h */ // // some useful types // typedef void (* pfv_t)(); typedef int (* pfi_t)(); typedef unsigned int (* pfu_t)(); typedef union namenum { char name[4]; short half[2]; long num; void *ptr; float fnum; } namenum_t; #define TRUE 1 #define FALSE 0 #define NULL 0 #define DEAD 0xdeadbeef // // time // typedef unsigned long long uint64_t; extern uint64_t get_time ( void ); extern unsigned long now_usec ( void ); extern unsigned long now_hrs ( void ); extern void wait( unsigned long usecs ); extern void set_timer(); extern void init_time(); #define ONE_USEC 0x1 #define ONE_MSEC (ONE_USEC * 1000) #define ONE_SEC (ONE_MSEC * 1000) // // TIME values - caveats: // a. this assumes you are using the 900MHz-driven clock-timer as "now" // b. it is ridiculously inaccurate (only approximately == 1 usec, 1 msec, 1 sec) // c. but, hey, it works for now - one can always trim it up to be more accurate later // (e.g., set these values to *precisely* the number of clock-timer cycles that // bring you to the desired time ... I just didn't have the *time* (haha get it?) // to do all that work) // #define USEC(u) (u * ONE_USEC) #define MSEC(m) (m * ONE_MSEC) #define SECS(s) (s * ONE_SEC) // note we can only go up to 2000 seconds #define MAX_BLOCK_TIME USEC(500) // // some system parameters // #define NUM_CORES 4 #define NUM_THREADS 16 #define MAX_SLEEP_INTERVAL ONE_MSEC // // callout // #include "llist.h" struct event { LL_PTRS; int timeout; int repeat_interval; int max_repeats; int arg; pfv_t go; namenum_t data; }; extern void init_timeoutq( void ); extern int bring_timeoutq_current( void ); extern void insert_event(struct event *); extern void create_timeoutq_event( int, int, int, pfv_t, namenum_t ); extern int handle_timeoutq_event( void ); #define MIN_TIMEOUT ONE_MSEC // // dev // #include "dev.h" enum dev_types { DEV_INVALID, DEV_WORD, DEV_CBUF, DEV_BLOCK, }; // // I/O // struct dev { char devname[8]; int devtype; pfv_t init; pfi_t read; pfi_t write; pfi_t rcheck; pfi_t wcheck; }; extern void init_io(); enum readwrite { IO_READ, IO_WRITE, MAX_TYPES, }; struct io { LL_PTRS; int rw; int type; int device; int threadid; namenum_t data; }; extern struct io * get_io_entry(int type); extern void free_io_entry(struct io *iop); extern void do_dev_word(struct event *ep); extern void do_dev_cbuffer(struct event *ep); // // kversion // extern char kversion[]; // // led // extern void init_led(); extern void led_on(); extern void led_off(); extern void blink_led_stall(unsigned int reps); // // log/errno // enum debug_levels { DEBUG_LOW, DEBUG_MED, DEBUG_HI, DEBUG_NONE }; #define DEBUG_LEVEL DEBUG_NONE extern void * GETPC(); #if 0 #define debug(x,y,z); #else #define debug(x,y,z); if (x >= DEBUG_LEVEL) { dont_call_directly(GETPC(),y,z); } #endif extern void dont_call_directly( void *, char *, unsigned long); extern void log( char *, long); extern void panic( int, char *); extern void init_log( void ); extern void die( long pc ); extern void idump( int * ); enum err_numbers { ERRNO_NONE, ERRNO_ASSERT, ERRNO_SPACE, ERRNO_INTERRUPT, ERRNO_SYSCALL, ERRNO_DEVHANDLER, /* add new ones above this line */ ERRNO_MAX }; #define NOVAL 0xbadf000d #define LOG_LR(); \ { long lr; \ asm volatile ("mov %[lr], lr\n" \ : [lr] "=r" (lr) \ : \ : ); \ log("lr = ", lr); \ } #define LOG_SP(); \ { long sp; \ asm volatile ("mov %[sp], sp\n" \ : [sp] "=r" (sp) \ : \ : ); \ log("sp = ", sp); \ } // // test utils // int is_printing(char c); long atol_dec(char *s); long atol_hex(char *s); void strcpy4(char *to, char *from); int strcpyN(char *to, char *from, int bufsiz); int strlen(char *s); // // thread // extern void scheduler(int); extern void wake_thread(long, long); extern void init_threads(); extern void create_thread(char *name, char *filename); extern void dump_tcb(long); extern void dump_processes(); extern long thread_activeid(); enum states { THREAD_INIT, THREAD_SLEEP, THREAD_RUN, MAX_THREAD_STATES, }; enum tcb_regs { REG_r0, REG_r1, REG_r2, REG_r3, REG_r4, REG_r5, REG_r6, REG_r7, REG_r8, REG_r9, REG_r10, REG_r11, REG_r12, REG_sp, REG_lr, REG_pc, REG_spsr, REG_ttbr, REG_asid, // insert new ones here TCB_NUMREGS, }; // // UART // extern unsigned int uart_lcr ( void ); extern unsigned int uart_recv ( void ); extern int uart_recvcheck ( void ); extern int uart_sendcheck ( void ); extern void uart_send ( unsigned int ); extern void uart_flush ( void ); extern void uart_put2d ( unsigned long ); extern void uart_put3d ( unsigned long ); extern void uart_put8x ( unsigned int ); extern void uart_put12x ( unsigned int ); extern void uart_put32x ( unsigned int ); extern void uart_put64x ( unsigned long long ); extern void uart_puts ( char * ); extern void uart_putns ( char * , int ); extern void init_uart ( void ); // // utils // extern void PUT32 ( unsigned long, unsigned long ); extern unsigned long GET32 ( unsigned long ); extern void * GETPC ( void ); extern void idle ( void ); extern void sync ( void ); extern void hang ( void ); extern void dummy ( void ); extern long cpu_id ( void ); extern void enable_irq ( void ); extern void enable_fiq ( void ); extern void disable_irq ( void ); extern void disable_fiq ( void ); // // VM routines // extern void init_vm ( void ); long vm_allocate(); void vm_deallocate( long address ); void map( unsigned int ASID, unsigned int vaddr, unsigned int paddr, int io, int g ); void initialize_table( long asid ); unsigned long *vm_pagetable( long asid ); unsigned long vm_translate( long thread, long addr ); extern void invalidate_tlb(); extern void sync(); extern unsigned int readTTBCR(); extern void writeTTBCR(unsigned int); extern unsigned int readTTBR0(); extern void writeTTBR0(unsigned int); extern unsigned int readTTBR1(); extern void writeTTBR1(unsigned int); extern unsigned int readCONTEXTIDR(); extern void writeCONTEXTIDR(unsigned int); extern unsigned int readDACR(); extern void writeDACR(unsigned int); extern unsigned int readSCTLR(); extern void writeSCTLR(unsigned int); extern void setSMP();
C
#include "pit.h" #include "paging.h" #define ASM 1 /*init_pit * DESCRIPTION : Initialize PIT * INPUT : None * OUTPUT : None * RETURN VALUE: None */ int32_t terminal_index; void init_pit() { /*initialize the terminal_index as 0*/ terminal_index = 0; /*pit_call initialized as flag use for first three iteration*/ pit_call = 0; /* 0x36 == 0b 0011 0110 * Select channel | Access mode | Operating mode | BCD/Binary mode * Channel 0 lobyte/highbyte Mode 3 Binary mode */ outb(0x36, MODE_REGISTER); /* send lowest 8 bits */ outb(PIT_HZ & 0xFF, CHANNEL_0_DATA); /* send highest 8 bits */ outb(PIT_HZ >> _8, CHANNEL_0_DATA); /* enable IRQ */ enable_irq(PIT_IRQ); } /*pit_handler * DESCRIPTION: function that is triggered when the interrupt occurs * INPUT: None * OUTPUT: None * RETURN VALUE: None */ void pit_handler() { /* variable declaration */ pcb_t* prev_pcb, *cur_pcb; int prev; /* send EOI to acknowledge interrupt */ cli(); send_eoi( PIT_IRQ ); sti(); /* save current terminal_index */ prev = terminal_index; /* update terminal_index to next terminal's index */ terminal_index = (terminal_index + 1) % NUM_OF_TERMINALS; /* save current terminal's status */ asm ( "movl %%esp, %0;" "movl %%ebp, %1;" :"=r"(terminals[prev].term_esp), "=r"(terminals[prev].term_ebp) : :"cc" ); /* next terminal has no running shell, we need to boot shell program first */ if(-1 == terminals[terminal_index].cur_process_index) { /* raise pit_call flag for execute() */ pit_call = 1; /* boot shell */ execute((uint8_t*) "shell"); } /* * context switching section * * Due to the effect of Round Robin, we have booted shell for each terminal, * and we only need to remap paging, move esp, ebp, tss.esp0, and set RTC frequency * to perform context switching */ /* lower pit_call flag since we are doing context switching */ pit_call = 0; /* allocate paging */ map_page(_8 * MB + terminals[terminal_index].cur_process_index * _4 * MB); /* allocate video memory, 12 bit to align the address */ map_video_page((uint32_t)(VIDEO_MEM << 12), terminal_index); /* restore esp0 for next terminal */ tss.esp0 = _8 * MB - _8 * KB *terminals[terminal_index].cur_process_index - _4; /* get current terminal's pcb */ cur_pcb = (pcb_t *)get_pcb_addr(terminals[terminal_index].cur_process_index ); /* get previous terminal's pcb */ prev_pcb = (pcb_t *)get_pcb_addr(terminals[prev].cur_process_index ); /* * if we see the difference RTC frequency between current pcb and previous pcb, * we need to modify RTC frequency, otherwise we can skip this procedure */ rtc_set_freq(cur_pcb->rtc_freq); /* * modify esp and ebp to shift to next terminal's stack * * since we store the terminal's esp and ebp in pit_handler() [line 56], * when we modify esp and ebp, the function call we are in should be * next terminal's interrupt call of pit_handler(). When we leave and ret, * we will return from this function call and get back to pit_linkage() from * interrupt_linkage.S. With the help of pre-pushed iret context by MMU, when * we iret, we will return to next terminal's process's user space, which is * the goal of context switching */ asm ( "movl %0, %%esp;" "movl %1, %%ebp;" "leave;" "ret;" : /* no output */ : "r"(terminals[terminal_index].term_esp), "r"(terminals[terminal_index].term_ebp) : "cc", "%esp", "%ebp" ); }
C
#include <stdio.h> #include <stdlib.h> int main() { int a = 22, b = 11; int sum = a + b; printf("Sum = %d\n",sum); return 0; }
C
/* * File: Main.c * Author: Armstrong Subero * PIC: 18F4553 w/Ext OSC @ 16MHz ; PLL to 48MHz, 5v * Program: 08_ADC * Compiler: XC8 (v1.38, MPLAX X v5.05) * Program Version: 1.0 * * * Program Description: This Program Allows PIC18F4553 to use the ADC module * and results are sent via TX pin to a serial LCD * Hardware Description: A 2x16 Parallax LCD RX pin is connected to RC6 and * a potentiometer is connected to PIN RA0 (AN0). * * Created September 7th, 2018, 9:09 PM */ /******************************************************************************* * Includes and Defines ******************************************************************************/ #include "18F4553_STD.h" #include "USART.h" #include "ADC.h" /******************************************************************************* * Function: Main * * Returns: Nothing * * Description: Program entry point ******************************************************************************/ void main(void) { int result; // initialize 12 bit ADC ADC_Init(); delay_ms(1000); USART_Init(19200); delay_ms(1000); while(1) { // read channel 0 result = ADC_Read(0); // Write Result USART_Write_Integer(result); delay_ms(3000); USART_Write(12); } return; }
C
#pragma once #include "mathLib.h" struct Vertex { Vec3 position; Vec3 normal; Vec3 color; // alpha of color is always 1 Vertex(const Vec3& pos, const Vec3& nor, const Vec3& col): position{ pos }, normal{ nor }, color{ col } { } Vertex(const Vertex& v): position{ v.position }, normal{ v.normal }, color{ v.color } { } };
C
#include "inicio.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lista.h" #include "plantillaDiscos.h" #include "plantillaParticion.h" #include "plantillaReporte.h" int ope1,ope2,p,err,h; //p=1 si esta activo char comando[8],tk[100],unit[3],path[100],type[6],fit[3],name[15],delete[5],add[8],id[5],content[100],dest[100],iddest[5],file[100],size[8]; void leerArchivo(char path[]){ } void iniVars(){ h=0; ope1=-1; ope2=-1; p=-1; err=0; strcpy(tk,""); strcpy(unit,""); strcpy(path,""); strcpy(type,""); strcpy(fit,""); strcpy(name,""); strcpy(delete,""); strcpy(add,""); strcpy(id,""); strcpy(content,""); strcpy(dest,""); strcpy(iddest,""); strcpy(file,""); strcpy(size,""); strcpy(comando,""); } void separarComando(char entrada[]){ char *token; char contenido[100]; Lista *l; l=malloc(sizeof(Lista)); token=strtok(entrada," "); while(token!=NULL){ h++; strcpy(contenido,""); strcat(contenido,token); addLista(l, contenido); token=strtok(NULL," "); } verificarComando(l); free(l); } void waitInst(){ char entrada[200]; int i; printf("\n"); getchar(); fflush(stdin); scanf("%[^\n]",entrada); i=strlen(entrada); if(i>0){ if(strcmp(entrada,"0")==0){ exit(0); } iniVars(); //printf("capturado: %s\n",entrada); separarComando(entrada); } } void menu(char comando[]){ int num = atoi(size); int tam = atoi(add); //printf("comando: %i, %s \n",ope1,comando); if(err==0){ if(ope1==1 && strcmp(comando,"AC")==0){ //para crear discos crearDisco(num,"m",path); }else if(ope1==1 && strcmp(comando,"ABC")==0){ crearDisco(num,unit,path); }else if(ope1==2 && strcmp(comando,"C")==0){ //eliminar disco; eliminarDisco(path); }else if(ope1==3 && ope2==-1){ if(strcmp(comando,"ACF")==0){ crearParticion(num,"k",path,"p","wf",name); }else if(strcmp(comando,"ACEF")==0){ crearParticion(num,"k",path,"p",fit,name); }else if(strcmp(comando,"ACDF")==0){ crearParticion(num,"k",path,type,"wf",name); }else if(strcmp(comando,"ACDEF")==0){ crearParticion(num,"k",path,type,fit,name); }else if(strcmp(comando,"ABCF")==0){ crearParticion(num,unit,path,"p","wf",name); }else if(strcmp(comando,"ABCEF")==0){ crearParticion(num,unit,path,"p",fit,name); }else if(strcmp(comando,"ABCDF")==0){ crearParticion(num,unit,path,type,"wf",name); }else if(strcmp(comando,"ABCDEF")==0){ crearParticion(num,unit,path,type,fit,name); }else{ printf("error comando no reconocido!!\n"); } }else if(ope1==3 && ope2==4){ eliminarParticion(delete,name,path); }else if(ope1==3 && ope2==5){ modificarParticion(tam,unit,path,name); }else if(ope1==6 && strcmp(comando,"CF")==0){ formatearParticion(path,"full",name); }else if(ope1==6 && strcmp(comando,"CDF")==0){ formatearParticion(path,type,name); }else if(ope1==7 && strcmp(comando,"CF")==0){ montarParticion(path,name); }else if(ope1==8 && strcmp(comando,"I")==0){ desmontarParticion(id); }else if(ope1==18 && strcmp(comando,"FCI")==0 && strcmp(name,"mbr")==0){ reporteMBR(path,id); }else if(ope1==18 && strcmp(comando,"FCI")==0 && strcmp(name,"disk")==0){ reporteMBRPART(path,id); }else if(ope1==18 && strcmp(comando,"FCI")==0 && strcmp(name,"sb")==0){ reporteSB(path,id); }else if(ope1==18 && strcmp(comando,"FCI")==0 && strcmp(name,"bm_inode")==0){ reporteBitmapInodos(path,id); }else if(ope1==18 && strcmp(comando,"FCI")==0 && strcmp(name,"bm_block")==0){ reporteBitmapBloques(path,id); }else if(ope1==19 && strcmp(comando,"C")==0){ leerArchivo(path); }else{ printf("error comando no reconocido!!\n"); } }else{ printf("error comando no reconocido!!\n"); } } void verificarComando(Lista *l){ int k=0; char token[100]; nodol *nodo; while(k<h){ nodo=getLista(l); strcpy(token,""); strcat(token,nodo->contenido); if(strcmp(token,"mkdisk")==0 || strcmp(token,"Mkdisk")==0 ){ ope1=1; }else if(strcmp(token,"rmdisk")==0){ ope1=2; }else if(strcmp(token,"fdisk")==0){ ope1=3; }else if(strcmp(token,"-delete")==0){ ope2=4; }else if(strcmp(token,"-add")==0){ ope2=5; }else if(strcmp(token,"mkfs")==0){ ope1=6; }else if(strcmp(token,"mount")==0){ ope1=7; }else if(strcmp(token,"unmount")==0){ ope1=8; }else if(strcmp(token,"mkfile")==0){ ope1=9; }else if(strcmp(token,"cat")==0){ ope1=10; }else if(strcmp(token,"rmfile")==0){ ope1=11; }else if(strcmp(token,"edit")==0){ ope1=12; }else if(strcmp(token,"rename")==0){ ope1=13; }else if(strcmp(token,"mkdir")==0){ ope1=14; }else if(strcmp(token,"cp")==0){ ope1=15; }else if(strcmp(token,"mv")==0){ ope1=16; }else if(strcmp(token,"find")==0){ ope1=17; }else if(strcmp(token,"rep")==0){ ope1=18; }else if(strcmp(token,"exec")==0){ ope1=19; }else if(strcmp(token,"-p")==0){ p=1; }else{ char *tok; tok=strtok(token,"="); if(strcmp(tok,"-size")==0){ strcat(comando,"A"); tok=strtok(NULL,"="); strcpy(size,tok); }else if(strcmp(tok,"-unit")==0){ strcat(comando,"B"); tok=strtok(NULL,"="); strcpy(unit,tok); }else if(strcmp(tok,"-path")==0 || strcmp(tok,"-Path")==0 || strcmp(tok,"-PAth")==0){ strcat(comando,"C"); tok=strtok(NULL,"="); strcpy(path,tok); }else if(strcmp(tok,"-type")==0){ strcat(comando,"D"); tok=strtok(NULL,"="); strcpy(type,tok); }else if(strcmp(tok,"-fit")==0){ strcat(comando,"E"); tok=strtok(NULL,"="); strcpy(fit,tok); }else if(strcmp(tok,"-name")==0){ strcat(comando,"F"); tok=strtok(NULL,"="); strcpy(name,tok); }else if(strcmp(tok,"-delete")==0){ strcat(comando,"G"); tok=strtok(NULL,"="); strcpy(delete,tok); }else if(strcmp(tok,"-add")==0){ strcat(comando,"H"); tok=strtok(NULL,"="); strcpy(add,tok); }else if(strcmp(tok,"-id")==0){ strcat(comando,"I"); tok=strtok(NULL,"="); strcpy(id,tok); }else if(strcmp(tok,"-content")==0){ strcat(comando,"K"); tok=strtok(NULL,"="); strcpy(content,tok); }else if(strcmp(tok,"-dest")==0){ strcat(comando,"L"); tok=strtok(NULL,"="); strcpy(dest,tok); }else if(strcmp(tok,"-iddest")==0){ strcat(comando,"M"); tok=strtok(NULL,"="); strcpy(iddest,tok); }else if(strcmp(tok,"-file")==0){ strcat(comando,"N"); tok=strtok(NULL,"="); strcpy(file,tok); }else{ err=err+1; printf("#errores: %i\n",err); } } k++; } menu(comando); }
C
/************************************************************** * * userprog/ksyscall.h * * Kernel interface for systemcalls * * by Marcus Voelp (c) Universitaet Karlsruhe * **************************************************************/ #ifndef __USERPROG_KSYSCALL_H__ #define __USERPROG_KSYSCALL_H__ #include "kernel.h" #include "synchconsole.h" void SysHalt() { kernel->interrupt->Halt(); } int SysAdd(int op1, int op2) { return op1 + op2; } bool cmp(char A[], char B[]) { int i=0; bool bigger=false; bool hasAns=false; while(true) { if(A[i]=='\0') { if(B[i]!='\0') return false; return hasAns && bigger; } else if(B[i]=='\0') { return true; } else if(A[i]!=B[i]) { if(A[i]>B[i] && !hasAns) { bigger=true; hasAns=true; } else if(A[i]<B[i] && !hasAns) { bigger=false; hasAns=true; } } i++; } return false; } void SysPrintNumRecursion(int n, bool isNegative) { if(n==0) { if(isNegative) { kernel->synchConsoleOut->PutChar('-'); } return; } SysPrintNumRecursion(n/10, isNegative); int i=n%10; char t=(char)(i+'0'); kernel->synchConsoleOut->PutChar(t); } void SysPrintNum(int n) { bool isNegative=false; if(n==0) { kernel->synchConsoleOut->PutChar('0'); return; } if(n<0) { isNegative=true; n=-n; } SysPrintNumRecursion(n, isNegative); } int inflate(char A[]) { int ans=0; int i=0; while(true) { if(A[i]=='\0') return ans; ans=ans*10+(A[i]-'0'); i++; } return 0; } char* SysReadString(char* buffer, int length) { int i=0; char oneChar; while(i<length) { oneChar=kernel->synchConsoleIn->GetChar(); if(oneChar!='\n') { buffer[i]=oneChar; i++; } else { break; } } buffer[i]='\0'; return buffer; } bool SysReadNum(int &ans) { char IntMax[12]="2147483647\0"; char IntMin[12]="2147483648\0"; char buffer[1000]; char oneChar; int i=0; int isNegative=0; while(i<1000) { oneChar=kernel->synchConsoleIn->GetChar(); if(oneChar=='-' && i==0) { isNegative=1; } else if(oneChar>='0' && oneChar<='9') { buffer[i-isNegative]=oneChar; } else if(oneChar=='\n' || oneChar==' ') { break; } else { return false; } i++; } buffer[i-isNegative]='\0'; if((isNegative==1 && cmp(buffer, IntMin)) || (isNegative==0 && cmp(buffer, IntMax))) { return false; } ans=inflate(buffer); if(isNegative==1) { ans=-ans; } return true; } void SysPrintString(char* buffer) { int i=0; while(*(buffer+i)!='\0') { kernel->synchConsoleOut->PutChar(*(buffer+i)); i++; } kernel->synchConsoleOut->PutChar('\n'); } #endif /* ! __USERPROG_KSYSCALL_H__ */
C
#include <stdio.h> #include <stdint.h> #include <inttypes.h> /* * PRIME_T - Liczby Pierwsze * http://pl.spoj.com/problems/PRIME_T/ * http://ideone.com/4eSs3u */ int main(void) { int32_t nTest, i; int16_t number, tmp, wynik; int8_t j; scanf("%" SCNd32, &nTest); for (i = 0; i < nTest; i++) { scanf("%" SCNd16, &number); tmp = number; j = 0; while (--tmp > 1) { wynik = number % tmp; if (wynik == 0) { j = 1; break; } } if (number == 1) j = 1; printf( j == 0 ? "TAK\n" : "NIE\n"); } return 0; }
C
#include<stdio.h> void main() { float notas[4]={}, aluno[10]={}; int contador=0; while (contador<10) { printf("Digite a primeira nota do %dº aluno: ",contador+1); scanf("%f",&notas[0]); printf("Digite a segunda nota do %dº aluno: ",contador+1); scanf("%f",&notas[1]); printf("Digite a terceira nota do %dº aluno: ",contador+1); scanf("%f",&notas[2]); printf("Digite a quarta nota do %dº aluno: ",contador+1); scanf("%f",&notas[3]); //atribuição das notas para os alunos aluno[contador] = ((aluno[contador]+notas[0]+notas[1]+notas[2]+notas[3])/4); contador++; } contador=0; while (contador<10) { if (aluno[contador] >=6) { printf("A nota do %dº aluno foi %.1f. Aluno aprovado.\n",contador+1,aluno[contador]);} else printf("A nota do %dº aluno foi %.1f. Aluno reprovado.\n",contador+1,aluno[contador]); contador++; } }
C
#include<stdio.h> void main() { int a,b,c,d,e,f; printf("enter any number whose once digit is less than five "); scanf("%d",&a); b = a/10; c = a%10; printf("\n the last digit of the number is %d",c); e = 2*c; f = b*10 + e; printf("\n the new number obtained after doubling its once digit is %d",f); }
C
#include "rlutils_command_args.h" #include "redismodule.h" #include "memory/rlutils_memory.h" #include "utils/arr_rm_alloc.h" #include <string.h> #include <assert.h> #define ArgsMask uint64_t void RLUTILS_PRFX_ArgIteratorInit(RLUTILS_PRFX_ArgIterator* iter, RedisModuleString** argv, size_t argc){ *iter = (RLUTILS_PRFX_ArgIterator){ .argv = argv, .argc = argc, .location = 0, }; } RedisModuleString* RLUTILS_PRFX_ArgIteratorCurr(RLUTILS_PRFX_ArgIterator* iter){ if(iter->location >= iter->argc){ return NULL; } return iter->argv[iter->location]; } RedisModuleString* RLUTILS_PRFX_ArgIteratorNext(RLUTILS_PRFX_ArgIterator* iter){ RedisModuleString* curr = RLUTILS_PRFX_ArgIteratorCurr(iter); if(curr){ ++iter->location; } return curr; } int RLUTILS_PRFX_ArgIteratorNextLong(RLUTILS_PRFX_ArgIterator* iter, long long* val){ RedisModuleString* temp = RLUTILS_PRFX_ArgIteratorNext(iter); if(!temp){ return REDISMODULE_ERR; } return RedisModule_StringToLongLong(temp, val); } int RLUTILS_PRFX_ArgIteratorNextDouble(RLUTILS_PRFX_ArgIterator* iter, double* val){ RedisModuleString* temp = RLUTILS_PRFX_ArgIteratorNext(iter); if(!temp){ return REDISMODULE_ERR; } return RedisModule_StringToDouble(temp, val); } const char* RLUTILS_PRFX_ArgIteratorNextCStr(RLUTILS_PRFX_ArgIterator* iter){ RedisModuleString* temp = RLUTILS_PRFX_ArgIteratorNext(iter); if(!temp){ return NULL; } return RedisModule_StringPtrLen(temp, NULL); } RLUTILS_PRFX_CommandNamedArgsDef* RLUTILS_PRFX_CommandArgsFindDef(const char* name, RLUTILS_PRFX_CommandNamedArgsDef* defs, size_t* index){ if(index) *index = 0; for(RLUTILS_PRFX_CommandNamedArgsDef* curr = defs ; curr->name ; curr++){ if(strcmp(curr->name, name) == 0){ return curr; } if(index) ++(*index); } return NULL; } #define SET_ERR(buff, e, ...) \ RLUTILS_PRFX_asprintf(buff, e, ##__VA_ARGS__); \ int RLUTILS_PRFX_ParseArg(RLUTILS_PRFX_CommandArgsDef* arg, RLUTILS_PRFX_ArgIterator* iter, RLUTILS_PRFX_MemoryGuard* mg, char** err){ long long lval; double dval; char* sval; RedisModuleString* rsval; switch(arg->val.type){ case BOOL: *(arg->val.bval) = true; return REDISMODULE_OK; case LONG: if(RLUTILS_PRFX_ArgIteratorNextLong(iter, &lval) != REDISMODULE_OK){ SET_ERR(err, "failing to parse long value for argument"); return REDISMODULE_ERR; } if(lval < arg->val.lvalMin || lval > arg->val.lvalMax){ SET_ERR(err, "given value is out of range, value : %ld, range: %ld - %ld", lval, arg->val.lvalMin, arg->val.lvalMax); return REDISMODULE_ERR; } *arg->val.lval = lval; return REDISMODULE_OK; case DOUBLE: if(RLUTILS_PRFX_ArgIteratorNextDouble(iter, &dval) != REDISMODULE_OK){ SET_ERR(err, "failing to parse double value for argument"); return REDISMODULE_ERR; } if(dval < arg->val.dvalMin || dval > arg->val.dvalMax){ SET_ERR(err, "given value is out of range, value : %lf, range: %lf - %lf", dval, arg->val.dvalMin, arg->val.dvalMax); return REDISMODULE_ERR; } *arg->val.dval = dval; return REDISMODULE_OK; case STR: sval = (char*)RLUTILS_PRFX_ArgIteratorNextCStr(iter); if(!sval){ SET_ERR(err, "no value given to argument"); return REDISMODULE_ERR; } if (arg->flags & FreeOldValue){ RLUTILS_PRFX_free(*(arg->val.sval)); } *(arg->val.sval) = sval; if (arg->flags & CommandArgCopy){ *(arg->val.sval) = RLUTILS_PRFX_strdup(*(arg->val.sval)); RLUTILS_PRFX_MemoryGuardAddPtr(mg, *(arg->val.sval)); } return REDISMODULE_OK; case REDISSTR: rsval = RLUTILS_PRFX_ArgIteratorNext(iter); if(!rsval){ SET_ERR(err, "no value given to argument"); return REDISMODULE_ERR; } if (arg->flags & FreeOldValue){ RedisModule_FreeString(NULL, *(arg->val.rsval)); } *(arg->val.rsval) = rsval; if (arg->flags & CommandArgCopy){ RedisModule_RetainString(NULL, *(arg->val.rsval)); RLUTILS_PRFX_MemoryGuardAddRedisString(mg, *(arg->val.rsval)); } return REDISMODULE_OK; case CALLBACK: return arg->val.setCallback(arg->val.ctx, iter); default: assert(false); } return REDISMODULE_ERR; } static ArgsMask GetMendatoryArgsMask(RLUTILS_PRFX_CommandNamedArgsDef* defs){ ArgsMask mask = 0; size_t index = 0; for(RLUTILS_PRFX_CommandNamedArgsDef* curr = defs ; curr->name ; curr++){ if(curr->arg.flags & CommandArgMendatory){ mask |= 1 << index; } } return mask; } static size_t FindMissingArgIndex(ArgsMask mendatoryArgsMask){ size_t index = 0; while(!(mendatoryArgsMask & 1)){ ++index; assert(index < 64); mendatoryArgsMask = mendatoryArgsMask >> 1; } return index; } static int ParseArgs(RLUTILS_PRFX_CommandArgsDef* args, RLUTILS_PRFX_MemoryGuard* mg, RLUTILS_PRFX_ArgIterator* iter, char** err){ if(!args){ return REDISMODULE_OK; } while(args->val.lval){ char* parsingErr = NULL; assert(args->val.type != BOOL && "bool val only supported with named args"); if(RLUTILS_PRFX_ParseArg(args, iter, mg, &parsingErr) != REDISMODULE_OK){ SET_ERR(err, "Failed setting argument value, %s", parsingErr); RLUTILS_PRFX_free(parsingErr); return REDISMODULE_ERR; } ++args; } return REDISMODULE_OK; } static int ParseArrayArgs(RLUTILS_PRFX_CommandArrVarPtr* arrArgs, RLUTILS_PRFX_MemoryGuard* mg, RLUTILS_PRFX_ArgIterator* iter, char** err){ if(!arrArgs){ return REDISMODULE_OK; } if(arrArgs->type == CALLBACK){ return arrArgs->setCallback(arrArgs->ctx, iter); }else{ while(RLUTILS_PRFX_ArgIteratorCurr(iter)){ union{ long long lval; double dval; bool bval; char* sval; RedisModuleString* rsval; } val; RLUTILS_PRFX_CommandArgsDef ptr = { .val.lval = &val.lval, .val.type = arrArgs->type, .flags = arrArgs->flags, }; char* parsingErr = NULL; if(RLUTILS_PRFX_ParseArg(&ptr, iter, mg, &parsingErr) != REDISMODULE_OK){ SET_ERR(err, "Failed setting argument value, %s", parsingErr); RLUTILS_PRFX_free(parsingErr); return REDISMODULE_ERR; } switch(arrArgs->type){ case BOOL: *(arrArgs->bval) = array_append(*(arrArgs->bval), val.bval); break; case LONG: *(arrArgs->lval) = array_append(*(arrArgs->lval), val.lval); break; case DOUBLE: *(arrArgs->dval) = array_append(*(arrArgs->dval), val.dval); break; case STR: *(arrArgs->sval) = array_append(*(arrArgs->sval), val.sval); break; case REDISSTR: *(arrArgs->rsval) = array_append(*(arrArgs->rsval), val.rsval); break; default: assert(0); } } } return REDISMODULE_OK; } static int ParseNamedArgs(RLUTILS_PRFX_CommandNamedArgsDef* namedArgs, RLUTILS_PRFX_MemoryGuard* mg, RLUTILS_PRFX_ArgIterator* iter, char** err, RLUTILS_PRFX_ArgsParsingFlag flags){ if(!namedArgs){ return REDISMODULE_OK; } RedisModuleString* curr = NULL; ArgsMask mendatoryArgsMask = GetMendatoryArgsMask(namedArgs); // parse named args while((curr = RLUTILS_PRFX_ArgIteratorCurr(iter))){ const char* argName = RedisModule_StringPtrLen(curr, NULL); size_t index; RLUTILS_PRFX_CommandNamedArgsDef* def = RLUTILS_PRFX_CommandArgsFindDef(argName, namedArgs, &index); if (!def){ if(flags & RaiseErrorOnUnknownArg){ SET_ERR(err, "Unknown argument given %s", argName); return REDISMODULE_ERR; }else{ // found an unknown named argument move to the last parsing stage break; } } // advance the iterator before continue parsing RLUTILS_PRFX_ArgIteratorNext(iter); char* parsingErr = NULL; if(RLUTILS_PRFX_ParseArg(&def->arg, iter, mg, &parsingErr) != REDISMODULE_OK){ SET_ERR(err, "Failed setting argument '%s' value, %s", argName, parsingErr); RLUTILS_PRFX_free(parsingErr); return REDISMODULE_ERR; } mendatoryArgsMask &= ~(1 << index); } if(mendatoryArgsMask){ size_t missingIndex = FindMissingArgIndex(mendatoryArgsMask); SET_ERR(err, "Mandatory arguments was not set : %s", namedArgs[missingIndex].name); return REDISMODULE_ERR; } return REDISMODULE_OK; } int RLUTILS_PRFX_CommandArgsParseInternal(RedisModuleString** argv, size_t argc, RLUTILS_PRFX_CommandArgsDef* args, RLUTILS_PRFX_CommandNamedArgsDef* namedArgs, RLUTILS_PRFX_CommandArrVarPtr* arrPtr, RLUTILS_PRFX_ArgsParsingFlag flags, char** err){ #define GOTO_ERROR() \ retVal = REDISMODULE_ERR; \ goto error; RLUTILS_PRFX_ArgIterator iter; RLUTILS_PRFX_MemoryGuard mg; int retVal = REDISMODULE_OK; RLUTILS_PRFX_ArgIteratorInit(&iter, argv, argc); RLUTILS_PRFX_MemoryGuardrInit(&mg); // parsing args if(ParseArgs(args, &mg, &iter, err) != REDISMODULE_OK){ GOTO_ERROR(); } if(ParseNamedArgs(namedArgs, &mg, &iter, err, flags) != REDISMODULE_OK){ GOTO_ERROR(); } if(ParseArrayArgs(arrPtr, &mg, &iter, err) != REDISMODULE_OK){ GOTO_ERROR(); } if(RLUTILS_PRFX_ArgIteratorNext(&iter) && (flags & RaiseErrorOnExtraArgsLeft)){ SET_ERR(err, "Argument without parsing def is given"); GOTO_ERROR(); } error: if (*err){ RLUTILS_PRFX_MemoryGuardFreeUnits(&mg); } RLUTILS_PRFX_MemoryGuardFreeStructure(&mg); return retVal; } int RLUTILS_PRFX_CommandArgsParse(RedisModuleCtx* ctx, RedisModuleString** argv, size_t argc, RLUTILS_PRFX_CommandArgsDef* args, RLUTILS_PRFX_CommandNamedArgsDef* namedArgs, RLUTILS_PRFX_CommandArrVarPtr* arrPtr, RLUTILS_PRFX_ArgsParsingFlag flags){ char* err; if(RLUTILS_PRFX_CommandArgsParseInternal(argv, argc, args, namedArgs, arrPtr, flags, &err) != REDISMODULE_OK){ RedisModule_ReplyWithError(ctx, err); RLUTILS_PRFX_free(err); return REDISMODULE_ERR; } return REDISMODULE_OK; }
C
/* Prompts user for last name, first name, and middle name individually ** Display in this format B. L. Jones */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main (void){ char lname[60], fname[60], mname[60], dest[160]; puts("Last Name:"); fgets(lname,60,stdin); puts("First Name:"); fgets(fname,60,stdin); puts("Middle Name:"); fgets(mname,60,stdin); strncpy(dest, fname,1); strcat(dest, ". "); strncat(dest, mname,1); strcat(dest, ". "); strcat(dest, lname); puts(dest); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* st.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahouel <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/16 11:23:36 by ahouel #+# #+# */ /* Updated: 2018/01/17 19:04:38 by ahouel ### ########.fr */ /* */ /* ************************************************************************** */ #include "vm.h" /* ** Montre l'operation ld avec -v 4 */ static void show_st(t_pcb *proc) { ft_printf("r%d %d\n", proc->op->param[0], proc->op->param[1]); } /* ** Transfert direct Registre > RAM / Registre. Charge le contenu du ** registre passé en premier parametre dans le second parametre. Si la ** valeur du premier parametre est egale a zero, alors le carry passe a ** l'etat un, sinon a l'etat zero. */ void st(t_vm *vm, t_pcb *proc) { int addr; if (proc->op->param_type[1] == IND_CODE) { addr = get_address(proc, proc->op->param[1]); store_ind_value(vm, addr, proc->reg[proc->op->param[0] - 1], proc->uid); } else proc->reg[proc->op->param[1] - 1] = proc->reg[proc->op->param[0] - 1]; if (vm->verbosity & V_OP) show_st(proc); }
C
#include <stdio.h> #include <string.h> typedef char* string; //TODO fix string getString(void) { string name; printf("Give me a name: "); scanf("%s", name); return name; } void main(void) { string name = getString(); int i; //switch to C99 in order to declare i inside for loop for(i=0; i < strlen(name); i++) { printf("%c\n", name[i]); } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #define M_PI 3.14159265358979323846 double f(double x); int main() { double a = 0; double b = M_PI; double iterations = 1000; double dx = (b - a) / (iterations + 1); double hL = 0; double xL = 0; double i = 0; for (i = a + dx; i < b - dx; i+=dx) { xL = ((a + dx) + (i - dx)); hL += (f(xL) * ((b - dx) - (a + dx))); } double linearAverage = hL/iterations; printf("Linear Average: %.5f", linearAverage); return 0; } double f(double x) { return x*x; }
C
#ifndef CHESSGAME_H_ #define CHESSGAME_H_ #include <stdio.h> #include "ChessGameCommon.h" #include "ArrayList.h" #define WHITE_KING_SYMBOL 'k' #define BLACK_KING_SYMBOL 'K' /** * ChessGame Summary: * * A container that represents a classic chess game, a two players or one player. * The container supports the following functions. * * chessGameCreate - Creates a new game board * chessGameCopy - Copies a game board * chessGameDestroy - Frees all memory resources associated with a game * chessGameSetMove - Sets a move on a game board * chessGameGetMoves - Gets all valid moves by a specified piece. * chessGameIsValidMove - Checks if a move is valid * chessGameUndoMove - Undoes previous move made by the last player * chessGamePrintBoard - Prints the current board * chessGameGetCurrentPlayer - Returns the current player * */ typedef struct chess_game_t { ChessBoard gameBoard; int currentPlayer; int historySize; unsigned int maxDepth; ArrayList* history; ChessPiecePosition whiteKingPosition; ChessPiecePosition blackKingPosition; bool isCheck; } ChessGame; /** * Type used for returning error codes from game functions */ typedef enum chess_game_message_t { CHESS_GAME_NONE, CHESS_GAME_ERROR, CHESS_GAME_INVALID_POSITION, CHESS_GAME_NO_PIECE_FOUND, CHESS_GAME_NO_PLAYER_PIECE_FOUND, CHESS_GAME_INVALID_MOVE, CHESS_GAME_MOVE_THREATEN_KING, CHESS_GAME_UNRESOLVED_THREATENED_KING, CHESS_GAME_EMPTY_HISTORY, CHESS_GAME_DRAW, CHESS_GAME_CHECK, CHESS_GAME_CHECKMATE, CHESS_GAME_SUCCESS, CHESS_GAME_UNDO_SUCCESS, CHESS_GAME_RESTART, CHESS_GAME_QUIT_SUCCESS, CHESS_GAME_INVALID_COMMAND, } CHESS_GAME_MESSAGE; /** * Creates a new game. * * @return * NULL if a memory allocation failure occurs. * Otherwise, a new game instance is returned. */ ChessGame* chessGameCreate(); /** * Creates a copy of a given game. * The new copy has the same status as the src game. * * @param src - the source game which will be copied * @return * NULL if either src is NULL or a memory allocation failure occurred. * Otherwise, an new copy of the source game is returned. * */ ChessGame* chessGameCopy(ChessGame* src); /** * Creates a copy of a given game. The new copy has the same status as the src game, * only with an empty history of flexible size. * * @param src - the source game which will be copied * @return * NULL if either src is NULL or a memory allocation failure occurred. * Otherwise, an new copy of the source game is returned. * */ ChessGame* chessGameCopyEmptyHistory(ChessGame* src, int historySize); /** * Frees all memory allocation associated with a given game. If src==NULL * the function does nothing. * * @param src - the source game */ void chessGameDestroy(ChessGame* src); /** * Sets the next move in a given game by specifying ChessPiecePosition. * * @param game - The source game. Assumes not NULL. * @param cur_pos - The piece's position on board. Assumes not NULL. * @param next_pos - The specified position. Assumes not NULL. * * @return * CHESS_GAME_INVALID_POSITION - if cur_pos or next_pos are out-of-range. * CHESS_GAME_INVALID_MOVE - if the given next_pos is illegal for this piece. * CHESS_GAME_MOVE_THREATEN_KING - if the move will cause your king to be threatened. * CHESS_GAME_UNRESOLVED_THREATENED_KING - if the move doesn't resolve the threatened king. * CHESS_GAME_SUCCESS - otherwise */ CHESS_GAME_MESSAGE chessGameSetMove(ChessGame* game, ChessPiecePosition cur_pos, ChessPiecePosition next_pos); /** * Gets all valid moves for the specified position. * * @param game - The game. Assumes not NULL. * @param pos - The piece's position on board. Assumes not NULL. * * @return * ArrayList with all possible moves */ ArrayList* chessGameGetMoves(ChessGame* game, ChessPiecePosition pos); /** * Undo the last move on the board and changes the current player's turn. * If the user invoked this command more than historySize times in a row, an error occurs. * * @param src - The source game, assumes not NULL. * @return * CHESS_GAME_EMPTY_HISTORY - if the user invoked this function more then * historySize in a row. * CHESS_GAME_SUCCESS - On success. The last move on the board is removed, * and the current player is changed. */ CHESS_GAME_MESSAGE chessGameUndoMove(ChessGame* game); /** * On success, the function prints the board game to the file given. * Uses the defined representation of each piece. * * @param game - Assumes not NULL. * @param file - Assumes not NULL. */ void chessGamePrintBoard(ChessGame* game, FILE* file); /** * Returns the current player of the specified game. * @param game - Assume not null * @return * game->currentPlayer */ int chessGameGetCurrentPlayer(ChessGame* src); /* * returns the opponent of the current player. * @param player - the current player. * @return * CHESS_WHITE_PLAYER if player == CHESS_BLACK_PLAYER. * CHESS_BLACK_PLAYER if player == CHESS_WHITE_PLAYER. */ int chessGameGetOpponentByPlayer(int player); /** * Checks if the current state is checkmate, draw or none of them. * @param game - the source game * @return * CHESS_GAME_DRAW - if the game is draw. * CHESS_GAME_CHECKMATE - if their's a checkmate. * CHESS_GAME_NONE - if none of the above is true. */ CHESS_GAME_MESSAGE chessGameGetCurrentState(ChessGame* game); /** * Update game->isCheck of the given game. * @param game - the source game */ void chessGameUpdateIsCheck(ChessGame* game); /** * Converts from char to ChessPiece instance. * @param piece - the char representing the piece. * @return * ChessPiece - the chessPiece the char represents. */ ChessPiece chessGameCharToChessPieceConverter(char piece); #endif
C
#include "stdio.h" #include "../lib/CSLink.h" #include "stdlib.h" int main() { CSLink *L; ElemType arr[5] = { 1, 2, 3, 4, 5 }; /* InitList(&L); for (int i = 1; i <= 5; ++i) { Insert(&L, i, i); } printf("len=%d\n", GetLength(L)); Display(L); Delete(&L, 3); Display(L); DestroyList(&L); */ CreateLinkR(&L, arr, 5); Display(L); Insert(&L, 100, 7); Display(L); return 0; }
C
#include<stdio.h> int main() { int i=0,a=0; while(i<20) { for(;;) { if((i%10)==0) break; else i--; } i+= 11; a += i; } printf("%d\n",a); // 32 return 0; } #if 0 //-189 ת void rotate(int* nums, int numsSize, int k) { k = k%numsSize; reverse(nums, 0, numsSize - 1); reverse(nums, 0, k - 1); reverse(nums, k, numsSize - 1); } void reverse(int* nums, int left, int right) { int mid = (left + right) / 2; for (int i = right; i>mid; i--) { int temp = nums[i]; nums[i] = nums[left + right - i]; nums[left + right - i] = temp; } } //-35 λ //1 int searchInsert(int* nums, int numsSize, int target) { if (target < nums[0]) return 0; if (target > nums[numsSize - 1]) return numsSize; int i; for (i = 0; i < numsSize; i++) { if (nums[i] == target) return i; if (nums[i] < target && target < nums[i + 1]) return i + 1; } return i; } //2 int searchInsert(int* nums, int numsSize, int target){ for (int i = 0; i<numsSize; i++) { if (target <= nums[i]) return i; } return numsSize; #endif
C
#include <stdio.h> int main() { int i=0, j=0; printf ("i=%d, j=%d\n", i, j); printf ("i++=%d, ++j=%d\n", i++, ++j); printf ("i=%d, j=%d\n", i, j); }
C
/* Max Henrique Barbosa - 16/0047013 Érico Maximiano - 16/0070287 */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <math.h> //-------------------- DECLARACAO DE FUNCOES --------------------- int gerarNumeroAleatorio (); int menorValor(int *,int ,int); int transformaBinDecimal(int *); double energia(int **); double contraste(int **); double homogeneidade(int **); void selecionaImagem (int *,int *,char *,FILE *,int **,int *,int *,int); void ilbp(int **,int ,int ,double **, int); void ilbpQuadrante(int **,int ,int ,double **,int); void alocaMatriz(int **); void rotacionaVetor(int *); void normalizaVetor(double *,int); void mediaPontos(double **,double *,double *); void glcm(int **, int, int , double **, int); void euclidiana(double **, double *, double *, int *, int *, int *); void imagensParaTreino(int *,int *,char *, FILE *, int **, int *, int *, int); void salvaVetNormalizados(double **aspectos); //------------------------------ MAIN ----------------------------- int main(int argc, char const *argv[]) { FILE *arq; int **vetorImagens; int linha, coluna, i, j, cont, pixel; int acerto = 0, falsaRejeicao = 0, falsaAceitacao = 0; double *mediaGrama, *mediaAsfalto; double **aspectos; char nomeArquivo[20] = "", aux; static int asfalto[50], grama[50]; if(mediaGrama = (double*)calloc(536,sizeof(double)),mediaGrama == NULL){ printf("alocação falhou!\n"); exit(1); } if(mediaAsfalto = (double*)calloc(536,sizeof(double)),mediaAsfalto == NULL){ printf("alocação falhou!\n"); exit(1); } if( aspectos = (double**)calloc(50,sizeof(double*)),aspectos == NULL){ printf("alocação falhou!\n"); exit(1); } for(i = 0; i < 50; i++){ if(*(aspectos+i) = (double*)calloc(536,sizeof(double)),*(aspectos+i) == NULL){ printf("alocação falhou!\n"); exit(1); } } for (cont = 0; cont < 50; cont++) { linha=0; coluna=0; selecionaImagem(asfalto,grama,nomeArquivo,arq,vetorImagens,&linha,&coluna,cont%2); if(vetorImagens = (int**)malloc(linha*sizeof(int*)),vetorImagens == NULL){ printf("alocação falhou!\n"); } for(i = 0; i<linha; i++){ if(*(vetorImagens+i) = (int*)malloc(coluna*sizeof(int)),*(vetorImagens+i) == NULL){ printf("alocação falhou!\n"); } } if(arq = fopen(nomeArquivo,"r"),arq == NULL){ printf("erro ao abrir o arquivo!\n"); exit(1); } for(i = 0; i<linha; i++) for(j = 0; j<coluna; j++){ fscanf(arq,"%d%c",&pixel,&aux); *(*(vetorImagens+i)+j) = pixel; } ilbp(vetorImagens,linha,coluna,aspectos,cont); glcm(vetorImagens,linha,coluna,aspectos,cont); fclose(arq); for(i = 0; i<linha; i++){ free(*(vetorImagens+i)); } free(vetorImagens); strcpy(nomeArquivo, "" ); } for (i = 0; i < 50; i++) { normalizaVetor(*(aspectos+i),536); } mediaPontos(aspectos,mediaGrama,mediaAsfalto); salvaVetNormalizados(aspectos); for(i = 0; i<50; i++){ free(*(aspectos+i)); } free(aspectos); if(aspectos = (double**)calloc(50,sizeof(double*)),aspectos == NULL){ printf("alocação falhou!\n"); exit(1); } for(i = 0; i<50; i++){ if(*(aspectos+i) = (double*)calloc(536,sizeof(double)),*(aspectos+i) == NULL){ printf("alocação falhou!\n"); exit(1); } } for (cont = 0; cont < 50; cont++) { linha=0; coluna=0; imagensParaTreino(asfalto,grama,nomeArquivo,arq,vetorImagens,&linha,&coluna,cont%2); if(vetorImagens = (int**)malloc(linha*sizeof(int*)),vetorImagens == NULL){ printf("alocação falhou!\n"); } for(i = 0; i<linha; i++){ if(*(vetorImagens+i) = (int*)malloc(coluna*sizeof(int)),*(vetorImagens+i) == NULL){ printf("alocação falhou!\n"); } } if(arq = fopen(nomeArquivo,"r"),arq == NULL){ printf("erro ao abrir o arquivo!\n"); exit(1); } for(i = 0; i<linha; i++) for(j = 0; j<coluna; j++){ fscanf(arq,"%d%c",&pixel,&aux); *(*(vetorImagens+i)+j) = pixel; } ilbp(vetorImagens,linha,coluna,aspectos,cont); glcm(vetorImagens,linha,coluna,aspectos,cont); fclose(arq); for(i = 0; i<linha; i++){ free(*(vetorImagens+i)); } free(vetorImagens); strcpy(nomeArquivo, "" ); } for (i = 0; i < 50; i++) { normalizaVetor(*(aspectos+i),536); } euclidiana(aspectos,mediaAsfalto,mediaGrama,&acerto,&falsaAceitacao,&falsaRejeicao); printf("Taxa de Acerto: %d%%\n",acerto*100/50); printf("Taxa de Falsa Aceitação: %d%%\n",falsaAceitacao*100/50); printf("Taxa de Falsa Rejeição: %d%%\n",falsaRejeicao*100/50); salvaVetNormalizados(aspectos); for(i = 0; i<50; i++){ free(*(aspectos+i)); } free(aspectos); free(mediaGrama); free(mediaAsfalto); return 0; } //-------------------------------FUNÇÕES----------------------------------- int gerarNumeroAleatorio (){ //Gerar numeros aleatórios para selicionar arquivos srand(time(NULL)); return (rand() % 50) + 1; } //------------------------------------------------------------------------- void ilbp(int **vetorImagens,int linha,int colunas,double **aspectos,int cont){ int i,j; for(i = 1; i < linha-1; i++) { for (j = 1; j < colunas-1; j++) { ilbpQuadrante(vetorImagens,i,j,aspectos,cont); } } } //----------------------------------------------------------------------------- int transformaBinDecimal(int *bin){//Transforma Binário para Decimal int decimal=0; for (int i = 0; i < 9; i++) { decimal += pow(2,(8-i)) * bin[i]; } return decimal; } //----------------------------------------------------------------------------- int menorValor(int *vetor,int menor,int cont){//Encontra o menor valor do vetor de decimal int n; if (cont == 9) { return menor; } else { n = transformaBinDecimal(vetor); if (n < menor) { menor = n; } rotacionaVetor(vetor); return menorValor(vetor,menor,cont+1); } } //------------------------------------------------------------------------- void ilbpQuadrante(int **vetorImagens,int linha,int coluna,double **aspectos,int aux){ double total=0.0; int cont=0,minValue; int vetor[9]; for (int i = linha-1; i <= linha+1; i++) { for (int j = coluna-1; j <= coluna+1; j++) { total += *(*(vetorImagens+i)+j); vetor[cont] = vetorImagens[i][j]; cont++; } } for (int i = 0; i < 9; i++) { if (total/9 >= vetor[i]) { vetor[i] = 1; } else { vetor[i] = 0; } } minValue = menorValor(vetor,256,0); if (aux%2) { aspectos[(aux-1)/2][minValue]+=1; } else { aspectos[50/2+aux/2][minValue]+=1; } } //------------------------------------------------------------------------- void rotacionaVetor(int *vetor){ int aux = vetor[0]; int aux1; vetor[0] = vetor[8]; for (int i = 1; i < 9; i++) { aux1 = vetor[i]; vetor[i] = aux; aux = aux1; } } //------------------------------------------------------------------------- void normalizaVetor(double *vetor,int tamVetor){ int maior=0,menor=10000,i; for (i = 0; i < tamVetor; i++) { if (vetor[i] < menor) { menor = vetor[i]; }else if(vetor[i] > maior){ maior = vetor[i]; } } if (maior == menor) { return; } for (i = 0; i < tamVetor; i++) { vetor[i] = (vetor[i] - menor)/(maior - menor); } } //------------------------------------------------------------------------- void mediaPontos(double **aspectos,double *mediaGrama,double *mediaAsfalto){ int i,j; double total=0.0; for (j = 0; j < 536; j++) { for (i = 0; i < 50/2; i++) { total+= aspectos[i][j]; } mediaGrama[j] = total/(50/2); total = 0.0; for (i = 50/2; i < 50; i++) { total+= aspectos[i][j]; } mediaAsfalto[j] = total/(50/2); total = 0.0; } } //------------------------------------------------------------------------- void euclidiana(double **aspectos, double *mediaAsfalto,double *mediaGrama,int *acerto,int *falsaAceitacao,int *falsaRejeicao){ double total = 0.0,distEuclidGrama,distEuclidAsfalto; int i,j; for (i = 0; i < 50; i++) { for (j = 0; j < 536; j++) { total+= pow(aspectos[i][j] - mediaGrama[j],2); } distEuclidGrama = sqrt(total); total = 0.0; for (j = 0; j < 536; j++) { total+= pow(aspectos[i][j] - mediaAsfalto[j],2); } distEuclidAsfalto = sqrt(total); total = 0.0; if (i < 50/2) { if (distEuclidGrama < distEuclidAsfalto) { *acerto += 1; } else { *falsaRejeicao += 1; } } else{ if (distEuclidGrama > distEuclidAsfalto) { *acerto += 1; } else { *falsaAceitacao += 1; } } } } //------------------------------------------------------------------------- double contraste(int **vetorImagens){ int i,j; double total=0.0; for (i = 0; i < 256; i++) { for (j = 0; j < 256; j++) { total += vetorImagens[i][j]*pow(i-j,2); } } return total; } //------------------------------------------------------------------------- double homogeneidade(int **vetorImagens){ int i,j; double total=0.0; for (i = 0; i < 256; i++) { for (j = 0; j < 256; j++) { total += vetorImagens[i][j]/(1+abs(i-j)); } } return total; } //------------------------------------------------------------------------- double energia(int **vetorImagens){ int i,j; double total=0.0; for (i = 0; i < 256; i++) { for (j = 0; j < 256; j++) { total += pow(vetorImagens[i][j],2); } } return total; } //------------------------------------------------------------------------- void glcm(int **vetorImagens,int linha,int coluna,double **aspectos,int cont){ int ***matrizesGlcm; int i,j,t; if(matrizesGlcm = (int***)calloc(8,sizeof(int**)),matrizesGlcm == NULL){ printf("alocação falhou!\n"); } for (i = 0; i < 8; i++) { if(matrizesGlcm[i] = (int**)calloc(256,sizeof(int*)),matrizesGlcm[i] == NULL){ printf("alocação falhou!\n"); } for (j = 0; j < 256; j++) { if(matrizesGlcm[i][j] = (int*)calloc(256,sizeof(int)),matrizesGlcm[i][j] == NULL){ printf("alocação falhou!\n"); } } } for (t = 0; t < 8; t++) { for (i = 1; i < linha-1; i++) { for (j = 1; j < coluna-1; j++) { switch (t) { case 0: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i-1][j-1]]++; break; case 1: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i-1][j]]++; break; case 2: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i-1][j+1]]++; break; case 3: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i][j-1]]++; break; case 4: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i][j+1]]++; break; case 5: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i+1][j-1]]++; break; case 6: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i+1][j]]++; break; case 7: matrizesGlcm[t][vetorImagens[i][j]][vetorImagens[i+1][j+1]]++; } } } if (cont%2) { aspectos[(cont-1)/2][512+3*t] = energia(matrizesGlcm[t]); aspectos[(cont-1)/2][512+3*t+1] = homogeneidade(matrizesGlcm[t]); aspectos[(cont-1)/2][512+3*t+2] = contraste(matrizesGlcm[t]); } else { aspectos[50/2+cont/2][512+3*t] = energia(matrizesGlcm[t]); aspectos[50/2+cont/2][512+3*t+1] = homogeneidade(matrizesGlcm[t]); aspectos[50/2+cont/2][512+3*t+2] = contraste(matrizesGlcm[t]); } } for (i = 0; i < 8; i++) { for (j = 0; j < 256; j++) { free(matrizesGlcm[i][j]); } free(matrizesGlcm[i]); } free(matrizesGlcm); } //------------------------------------------------------------------------- void imagensParaTreino(int *asfalto,int *grama,char *nomeArquivo,FILE *arq,int **vetorImagens,int *linha,int *coluna,int seletor){ int cont=0,numeroAleatorio; char stringNumeroAleatorio[4]; int pixel; char aux; if (seletor) { strcat(nomeArquivo,"DataSet/grass/grass_"); while(grama[cont]) { cont++; } numeroAleatorio = cont+1; grama[cont] = 1; } else { strcat(nomeArquivo,"DataSet/asphalt/asphalt_"); while(asfalto[cont]) { cont++; } numeroAleatorio = cont+1; asfalto[cont] = 1; } sprintf(stringNumeroAleatorio,"%02d",numeroAleatorio); strcat(nomeArquivo,stringNumeroAleatorio); strcat(nomeArquivo,".txt"); if(arq = fopen(nomeArquivo,"r"),arq == NULL){ printf("erro ao abrir o arquivo!\n"); exit(1); } while(!feof(arq)){ fscanf(arq, "%d%c",&pixel,&aux); if(aux == ';'){ *coluna += 1; } else if(aux == '\n'){ *linha += 1; } } *linha -= 1; *coluna = *coluna/(*linha)+1; fclose(arq); } //------------------------------------------------------------------------- void selecionaImagem(int *asfalto,int *grama,char *nomeArquivo,FILE *arq,int **vetorImagens,int *linha,int *coluna,int seletor){ int numeroAleatorio; char stringNumeroAleatorio[4]; int pixel; char aux; if (seletor) { strcat(nomeArquivo,"DataSet/grass/grass_"); numeroAleatorio = gerarNumeroAleatorio(); while(grama[numeroAleatorio-1]) { numeroAleatorio = gerarNumeroAleatorio(); } grama[numeroAleatorio-1] = 1; } else { strcat(nomeArquivo,"DataSet/asphalt/asphalt_"); numeroAleatorio = gerarNumeroAleatorio(); while(asfalto[numeroAleatorio-1]) { numeroAleatorio = gerarNumeroAleatorio(); } asfalto[numeroAleatorio-1] = 1; } sprintf(stringNumeroAleatorio,"%02d",numeroAleatorio); strcat(nomeArquivo,stringNumeroAleatorio); strcat(nomeArquivo,".txt"); if(arq = fopen(nomeArquivo,"r"),arq == NULL){ printf("erro ao abrir o arquivo!\n"); exit(1); } while(!feof(arq)){ fscanf(arq, "%d%c",&pixel,&aux); if(aux == ';'){ *coluna += 1; } else if(aux == '\n'){ *linha += 1; } } *linha -= 1; *coluna = *coluna/(*linha)+1; fclose(arq); } void salvaVetNormalizados(double **aspectos){ FILE *arquivo; if (arquivo = fopen("vetoresNormalizados.txt", "a+"), arquivo == NULL){ printf("erro ao abrir o arquivo!\n"); exit(1); } for( int i = 0; i < 50; i++){ for( int j = 0; j < 536; j++){ fprintf(arquivo, "%lf ", aspectos[i][j]); } fprintf(arquivo, "\n"); } fclose(arquivo); }
C
/* cx22-ap5.c */ #include <stdio.h> #include "lw_oopc.h" INTERFACE(IA) { void (*init)(void*); void (*deposit)(void*, double); void (*withdraw)(void*, double); }; CLASS(Account) { IMPLEMENTS(IA); double amount; char state; void (*state_action)(void*); void (*message_O)(void*); }; static void init(void* t) { Account* cthis = (Account*)t; cthis->amount = 0; cthis->state='N'; } static void deposit(void*t, double a) { Account* cthis = (Account*)t; cthis->amount += a; } static void withdraw(void* t, double a) { Account* cthis = (Account*)t; if( (cthis->amount - a) < 0 ) { cthis->state='O'; cthis->state_action(cthis); cthis->state = 'N'; } else { cthis->amount -= a; cthis->state_action(cthis); } } static void message_O(void*t) { Account* cthis = (Account*)t; printf("Over(%6.2f)\n", cthis->amount); } static void message_N() { printf("Welcome\n"); } static void state_action(void*t) { Account* cthis = (Account*)t; switch( cthis->state ) { case 'O': cthis->message_O(cthis); break; case 'N': message_N(); break; }; } CTOR(Account) FUNCTION_SETTING(IA.init, init); FUNCTION_SETTING(IA.deposit, deposit); FUNCTION_SETTING(IA.withdraw, withdraw); FUNCTION_SETTING(state_action, state_action); FUNCTION_SETTING(message_O, message_O); END_CTOR void main() { Account* acc = (Account*)AccountNew(); acc->init(acc); acc->deposit(acc, 100.5); acc->withdraw(acc, 50.5); acc->withdraw(acc, 50.6); getchar(); return 0; } 
C
#include "headers/evts.h" /** * Mousemove event callback function handler. * * @param eventType Flag defining event type * @param e Event object * @param userData Callback parameter * @return Status code */ EM_BOOL mouse_callback(int eventType, const EmscriptenMouseEvent *e, void *userData) { if (eventType == EMSCRIPTEN_EVENT_MOUSEMOVE) { mouseX = e->targetX; mouseY = e->targetY; } if (eventType == EMSCRIPTEN_EVENT_MOUSELEAVE) { mouseX = -1; } return 0; } /** * Setup event handlers by calling emscripten * callback functions. This syntax is correct, * since it is from official documentation. */ void evts_setup() { EMSCRIPTEN_RESULT ret = emscripten_set_mousemove_callback("screen", 0, 1, mouse_callback); ret = emscripten_set_mouseleave_callback("screen", 0, 1, mouse_callback); }
C
#include "stdio.h" #include "unistd.h" #include "stdlib.h" #include "sys/types.h" //#include "types" int main(void){ char** argv = (char**) malloc(3*sizeof(char*)); argv[0] = "/bin/ls"; argv[1] = "."; argv[2] = NULL; for(int i = 0; i< 10; i++){ printf("%d\n", i); if(i == 3){ pid_t pi = fork(); if(pi == 0){ execv("/bin/ls", argv); } } } return 0; }
C
#include <stdio.h> #include <math.h> #include <string.h> /* E3: More functions and scoping trials E4: Using static for variable persistence between calls */ void p(int); void fun(int); int x = 4; int main() { //E4-3 //printf("%d\n", x); //p(x); //E4-4: run fun() 5 times for(int c = 1;c<=5;c++) { fun(5); } } void p(int z) { int x = 8; printf("%d was sent to printer 'p'.\n", x); } void fun(int y) { static int x = 5; x = x + y; printf("Loop %d\n", x); }
C
#include <stdio.h> #define message_for(a,b) printf(#a " and " #b ",we love you!\n"); #define tokenpaster(n) printf("token" #n "=%d",token##n) int main(void) { message_for(xie,zhi); int token34=34; tokenpaster(34); return 0; }
C
/* ************************************ *ͨWindows API * ʾ * virtual.c * 5.4.2 ͷſɶдڴҳ **************************************/ /* ͷļ*/ #include <windows.h> #include <stdio.h> #include "../env_dll/env.h" /************************************* * int main(void) * ʾڴʹ * * δʹ **************************************/ int main(void) { EnumEnvironmentVariables(); ChangeEnviromentVariables("PATH","C:\\",VARIABLES_APPEND); EnumEnvironmentVariables(); ChangeEnviromentVariables("PATH","C:\\",VARIABLES_NULL); EnumEnvironmentVariables(); ChangeEnviromentVariables("XX","C:\\",VARIABLES_RESET); EnumEnvironmentVariables(); }
C
typedef int SDataType; typedef struct Stack { SDataType *arr; int top; int capacity; }Stack; void StackInit(Stack *ps ); void StackPush (Stack *ps,SDataType data); void StackPop(Stack *ps); SDataType StackTop(Stack *ps); int StackEmpty(Stack *ps); void StackDestroy(Stack *ps); int StackSize(Stack *ps); void StackInit(Stack *ps ){ assert(ps); ps->arr = (SDataType*)malloc (sizeof(SDataType)*5); if(ps->arr ==NULL){ assert(0); return; } ps->capacity = 5; ps->top = 0; } void StackPush (Stack *ps,SDataType data){ assert(ps); if(ps->top == ps->capacity){ int Newcapacity = 2*ps->capacity; int i; SDataType *NewStack; NewStack = (SDataType *)malloc(sizeof(SDataType)*Newcapacity); for(i = 0;i<ps->top;i++){ NewStack[i] = ps->arr[i]; } free(ps->arr); ps->arr = NewStack; ps->capacity = Newcapacity; } ps->arr[ps->top] = data; ps->top++; } void StackPop(Stack *ps){ assert(ps); if(StackEmpty (ps)){ return ; } ps->top--; } SDataType StackTop(Stack *ps) { assert(ps); return ps->arr[ps->top-1]; } int StackEmpty(Stack *ps){ assert(ps); return 0 == ps->top; } int StackSize(Stack *ps){ assert(ps); return ps->top; } void StackDestroy(Stack *ps) { assert(ps); if(ps->arr){ free(ps->arr); ps->top = 0; ps->capacity = 0; } } //ջDzܱ,ûбIJ //push o(1) //pop o(1) //top o(1) //getmin o(1) //һοԴջԪ //һԪشСֵ //ڶԪش //ջԪ ȡtop //ջһγ //ջ , s1 ,s2 Сֵ /* ջ : s1 ÿζҪһԪ s2 data<=Сֵ s2 ҲҪԪ ջ: s1 ÿζҪһԪ s2 ȵ ʱs1 һԪ */ typedef struct { Stack ds; Stack ms; } MinStack; /** initialize your data structure here. */ MinStack* minStackCreate() { //MinStack obj ʱںڵջ, ͷ //һʱ,н, //ͨmallocŵȥ MinStack* obj = (MinStack*)malloc(sizeof(MinStack)); if(obj == NULL) { assert(obj); return NULL; } StackInit(&obj->ds); StackInit(&obj->ms); return obj; } void minStackPush(MinStack* obj, int x) { //ջ StackPush(&obj->ds,x); //СջûлСֵmsTopС if(StackEmpty(&obj->ms) || x <= StackTop(&obj->ms)){ StackPush(&obj->ms,x); } } void minStackPop(MinStack* obj) { //ȵĻ,ô,,һds if(StackTop(&obj->ms) == StackTop(&obj->ds)) { StackPop(&obj->ms); } StackPop(&obj->ds); } int minStackTop(MinStack* obj) { return StackTop(&obj->ds); } int minStackGetMin(MinStack* obj) { return StackTop(&obj->ms); } void minStackFree(MinStack* obj) { StackDestroy(&obj->ds); StackDestroy(&obj->ms); free(obj); }
C
// // main.c // Bubblesort // // Created by Simon Schöpke on 06.01.21. // #include <stdio.h> #define MAX_LENGTH 100 void bubblesort_v2(int **a, int length) { int i; int j; for (i = 0; i < length - 1; i++) { for (j = 0; j < length - i - 1; j++) { if (*a[j] > *a[j + 1]) { int *tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } void init_ptrs_v2(int **ptrs, int *ints, int count) { int i; for (i = 0; i < count; i++) { ptrs[i] = &ints[i]; } } int main(int argc, const char * argv[]) { int ints[] = {1,9,2,8,4,5,6,3,7,0}; int count = 10; int i; int *ptrs[MAX_LENGTH] = {NULL}; init_ptrs_v2(ptrs, ints, count); bubblesort_v2(ptrs, count); for (i = 0; i < count; i++) { printf("%d ", *ptrs[i]); } printf("\n"); return 0; }
C
#include<stdio.h> #include<String.h> void main() { char s[100],s1[100],ch,s2[100],h=0,c; int i,v=1; clrscr(); printf("Enter the String ::"); gets(s); s1[0]=s[0]; for(i=0;s[i]!='\0';i++) { ch=s[i]; c=s[i+1]; if(ch==' '&&c!=' ') s1[v++]=c; } for(i=0;i<v-1;i++) printf("%c%c ",s1[i],'.'); for(i=strlen(s);s[i]!=' ';i--) { s2[h++]=s[i]; } printf("%c",' '); for(i=h-1;i>=0;i--) { printf("%c",s2[i]); } getch(); }
C
#include<stdio.h> #include<stdlib.h> #include"FindRank.c" int subsetRank(struct Node* root, int l,int u,int x) { return findRank(root,x) - findRank(root, u) + 1; } int main() { int n; printf("enter no of elements\n"); scanf("%d",&n); printf("enter array\n"); struct Node* root = (struct Node*)malloc(sizeof(struct Node)); root = 0; for(int i=0;i<n;i++) { int num; scanf("%d",&num); root = insert(root, num); } inorder(root); printf("enter lwr and upr bounds\n"); int l,u; scanf("%d %d",&l,&u); printf("enter number between %d and %d\n",l,u); int x; scanf("%d",&x); printf("the rank of %d in subset between %d and %d = %d\n",x,l,u,subsetRank(root,l,u,x)); return 0; }
C
#include <stdio.h> #include <cs50.h> // int main(void){ int numbers[16] = get_long("What's your card number?\n"); printf("%i\n", numbers); /*if(numbers > 5599999999999999 || numbers < 4000000000000){ printf("INVALID\n"); } char number = numbers; int first = 0; int second = 0; for (int i = 0; i<17; i++){ if(i==0 || i%2==0){ char num = number[i]*2; for(i in num){ first = first + i; } } else{ second = second + number[i]; } } if (first+second%10==0){ switch (number) { //figure first two cases! case number[0]==3 && number[1]==4||7 : printf("AMEX\n"); break; case number[0]==5 && number[1] >0 && <6 : printf("MASTERCARD\n"); break; case number[0]==4 : printf("VISA\n"); break; } } else{ printf("INVALID\n"); }*/ }
C
#if !defined(COMMON_H) #define COMMON_H /** * Boolean type. */ enum Boolean { FALSE, /**< False is zero. */ TRUE /**< True is not zero. */ }; /** * Gets the minimum value. * * @param x A value. * @param y Another value. * @return Return the smaller of x and y. If x equals y, return y. */ #define min(x, y) ((x) < (y) ? (x) : (y)) #endif
C
#include <avr/io.h> #include <util/delay.h> #include "i2c.h" #define CLOCK_ADDRESS 0x54 #define CLOCK_ADDRESS_W (CLOCK_ADDRESS << 1) #define CLOCK_ADDRESS_R (CLOCK_ADDRESS_W | 0x01) struct Time { uint8_t hours , minutes , seconds; }; void tick(void); volatile struct Time curr_time; void tick(void) { curr_time.seconds++; if (curr_time.seconds >= 60) { curr_time.minutes++; curr_time.seconds = 0; } if (curr_time.minutes >= 60) { curr_time.hours++; curr_time.minutes = 0; } if (curr_time.hours >= 24) curr_time.hours = 0; } int main(void) { initI2C(); curr_time.hours = 16; curr_time.minutes = 36; curr_time.seconds = 6; while (1) { i2cStart(); /* START */ i2cSend(CLOCK_ADDRESS_W); /* MT_SLA */ i2cSend(curr_time.hours); /* DATA */ i2cSend(curr_time.minutes); i2cSend(curr_time.seconds); i2cStop(); /* STOP */ tick(); _delay_ms(5000); } return 0; }
C
/*-----------------------------------------------------------------------* * filename - puts.c * * function(s) * puts - puts a string on a stream *-----------------------------------------------------------------------*/ /* * C/C++ Run Time Library - Version 10.0 * * Copyright (c) 1987, 2000 by Inprise Corporation * All Rights Reserved. * */ /* $Revision: 9.0 $ */ #include <stdio.h> #include <string.h> #include <_stdio.h> #include <_io.h> #include <_tchar.h> /*---------------------------------------------------------------------* Name _putts used as puts and _putws puts - outputs a string to stdout _putws - outputs a wide string to stdout Usage int puts(const char *string); int _putws(const wchar_t *string); Prototype in stdio.h Description _putts copies the null-terminated string string to the standard output stream stdout and appends a newline character. Return value On successful completion, _putts returns the last character written. Otherwise, a value of EOF is returned. *---------------------------------------------------------------------*/ int _RTLENTRY _EXPFUNC _putts (const _TCHAR *s) { int len, rc; #ifdef _UNICODE int i; #endif _lock_stream(stdout); if (s == NULL) rc = 0; else { len = _tcslen(s); #ifndef _UNICODE if ((int)__fputn(s,len,stdout) == len && _lputc('\n',stdout) == '\n') rc = '\n'; else rc = EOF; #else for (i=0; i<len; i++) { if (s[i] != _lputwc(s[i], stdout)) RETURN(EOF); } if (L'\n' != _lputwc(L'\n', stdout)) rc = EOF; else rc = L'\n'; #endif } #ifdef _UNICODE exit: #endif _unlock_stream(stdout); return (rc); }
C
#include<stdio.h> int main() { int n, q; scanf("%d %d", &n, &q); int i, j; int l, r, t; int a[102] = {}; for (i = 0; i < q; i++) { scanf("%d %d %d", &l, &r, &t); l--; for (j = l; j < r; j++) a[j] = t; } for (i = 0; i < n; i++) printf("%d\n", a[i]); return 0; } ./Main.c: In function main: ./Main.c:5:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d %d", &n, &q); ^ ./Main.c:11:9: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d %d %d", &l, &r, &t); ^
C
/* @author Praveen Reddy * @date : 2021-09-03 * @desc Creating Soft Link using symlink system call */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> int main(){ const char* src="/home/praveen/IIITB/Term 1/Software Systems/Lab Exercises/Hands_on_List1/test"; const char* link_path="/home/praveen/IIITB/Term 1/Software Systems/Lab Exercises/Hands_on_List1/test_soft_link"; int val=symlink(src,link_path); //Returns 0 on successful creation, else -1 if(val==-1){ perror("symlink"); exit(EXIT_FAILURE); } printf("Soft link created successfully\n"); return 0; }
C
// Lab4-2 #include <stdio.h> #include <stdbool.h> double* sort(double num[]) { double num_check; int n = 0; while (true) { int nub = 0; for(int i=0 ; i<2 ; i++) { if(num[i] <= num[i+1]) // check all number sort nub += 1; else break; } if(nub == 2) break; else { for(int i=0 ; i<2 ; i++) { if(num[i] > num[i+1]) // compare { num_check = num[i]; num[i] = num[i+1]; num[i+1] = num_check; } } } } return num; } int main() { double num[3]; scanf("%lf %lf %lf", &num[0], &num[1], &num[2]); sort(num); printf("%.2f\n",num[1]); return 0; }
C
#ifndef __HASH_MAP_H #define __HASH_MAP_H struct hash_map_node { char* key; char* value; struct hash_map_node* next; }; struct hash_map { struct hash_map_node* _node; char* _buffer; struct hash_map* (*put) (struct hash_map* this, char* key, char* value); char* (*get) (struct hash_map* this, char* key); char* (*toString)(struct hash_map* this); void (*delete) (struct hash_map* this); }; struct hash_map* hash_map_new(); void hash_map_delete (struct hash_map* this); struct hash_map* hash_map_put (struct hash_map* this, char* key, char* value); char* hash_map_get (struct hash_map* this, char* data); char* hash_map_toString(struct hash_map* this); #endif
C
// Trie that automatically adds to array create new indexes - Jared Johansson // Created March 2017 // Last updated May 2018: added ability to print and destroy tree #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Trie-SM.h" #define DEBUG 0 // Allocates memory for a trieNode, O(1) Trie *createNode(char *master, int size) { if (DEBUG) printf("Entered: createNode\n"); Trie *new; if ((new = malloc(sizeof(Trie))) == NULL) return NULL; if ((new->nodes = calloc(size, sizeof(Trie *))) == NULL) { free(new); return NULL; } if ((new->indexes = malloc(sizeof(char) * size)) == NULL) { free(new->nodes); free(new); return NULL; } new->word = 0; new->size = size; strcpy(new->indexes, master); if (DEBUG) printf("->Exit: createNode\n"); return new; } // Initalizes struct with root trie, O(1) Tree *createTree(void) { if (DEBUG) printf("Entered: createTree\n"); Tree *new; // Allocating all space if ((new = malloc(sizeof(Tree))) == NULL) return NULL; if ((new->indexes = malloc(sizeof(char) * 27)) == NULL) return NULL; // Inializing new->capacity = 26; strcpy(new->indexes, "abcdefghijklmnopqrstuvwxyz"); new->root = createNode(new->indexes, new->capacity); if (DEBUG) printf("->Exit: createTree\n"); return new; } // Adds new index to string of known indexes, O(1) void addIndex(Tree *tree, int ch) { if (DEBUG) printf("Entered: addIndex\n"); int i = 0, j = 0; char *new; // Space for current string plus null char and new char if ((new = malloc(sizeof(char) * (tree->capacity + 2))) == NULL) return; // Get location of where index needs to be added while (ch > tree->indexes[i]) i++; // Add all letters before insertion while (j < i) new[j] = tree->indexes[j++]; // Insert and add remaining new[i] = ch; while(i < tree->capacity) new[i + 1] = tree->indexes[i++]; free(tree->indexes); tree->indexes = new; tree->capacity++; tree->indexes[tree->capacity] = '\0'; if (DEBUG) printf("->Exit: addIndex\n"); } // Checks if new char and adds to indexes if so, O() void ifnew(Tree *tree, int ch) { if (DEBUG) printf("Entered: ifnew\n"); int i, in = 0; for (i = 0; i < tree->capacity; i++) { // skip a - z, because they will not match if (tree->indexes[i] == 'a') i += 25; if (tree->indexes[i] == ch) in = 1; } if (!in) addIndex(tree, ch); if (DEBUG) printf("->Exit: ifnew\n"); } // Checks string to see if new index needs to be added, O() void checkStr(Tree *tree, char *str, int len) { if (DEBUG) printf("Entered: checkStr\n"); int i; for (i = 0; i < len; i++) { // Only check if char has already been added if not a - z if ((str[i] >= ' ' && str[i] < 'a') || (str[i] > 'z' && str[i] <= '~')) ifnew(tree, str[i]); } if (DEBUG) printf("->Exit: checkStr\n"); } // Checks if trie node has updated indexes, O() void checkIndexes(Tree *tree, Trie *root) { if (DEBUG) printf("Entered: checkIndexes\n"); int i = 0, j = 0; char *newIndexes; Trie **newNodes; if (tree->capacity != root->size) { if ((newNodes = calloc(tree->capacity, sizeof(Trie *))) == NULL) return; if ((newIndexes = malloc(sizeof(char) * (tree->capacity + 1))) == NULL) { free(newNodes); return; } // Copy addresses to new trie node pointer array while(j < tree->capacity) { if (tree->indexes[j] == root->indexes[i]) { newNodes[j] = root->nodes[i]; i++; j++; } else { newNodes[j] = NULL; j++; } } free(root->nodes); root->nodes = newNodes; strcpy(newIndexes, tree->indexes); free(root->indexes); root->indexes = newIndexes; } if (DEBUG) printf("->Exit: checkIndexes\n"); } // Retrieves proper index of trie node array int getIndex(Tree *tree, int ch) { if (DEBUG) printf("Entered: getIndex\n"); int i = 0; while (ch != tree->indexes[i]) i++; if (DEBUG) printf("->Exit: getIndex\n"); return i; } // Add word into trie, O() void insert(Tree *tree, char *str, int len) { if (DEBUG) printf("Entered: insert\n"); int i, index; Trie *aux = tree->root; for (i = 0; i < len; i++) { // Updating old indices and getting correct index checkIndexes(tree, aux); index = getIndex(tree, str[i]); // Create path while moving forward if (aux->nodes[index] == NULL) aux->nodes[index] = createNode(tree->indexes, tree->capacity); aux = aux->nodes[index]; } aux->word = 1; if (DEBUG) printf("->Exit: insert\n"); } // Main function handle adding word into trie, O(k) Tree *addWord(Tree *tree, char *str) { if (DEBUG) printf("Entered: addWord\n"); int len; if (str == NULL) return tree; if ((len = strlen(str)) > MAX_WORD_LENGTH) { fprintf(stderr, "Error: String too large.\n"); return tree; } if (tree == NULL) tree = createTree(); checkStr(tree, str, len); // Master indexes updated insert(tree, str, len); if (DEBUG) printf("->Exit: addWord\n\n"); return tree; } // Recursive print function to print words, O(n) void printLoop(Trie *root, char *str, int k) { int i; if (root == NULL) return; str[k + 1] = '\0'; if (root->word == 1) printf("->%s\n", str); for (i = 0; i < root->size; i++) if (root->nodes[i] != NULL) { str[k] = root->indexes[i]; printLoop(root->nodes[i], str, k + 1); } str[k] = '\0'; } // Print words from trie struct, O(n) void printTree(Tree *tree) { int i; char str[MAX_WORD_LENGTH + 1]; if (tree->root == NULL) return; str[1] = '\0'; for (i = 0; i < tree->capacity; i++) if (tree->root->nodes[i] != NULL) { str[0] = tree->root->indexes[i]; printLoop(tree->root->nodes[i], str, 1); } } // Frees all trie data void burnTrie(Trie *root) { int i; if (root == NULL) return; for (i = 0; i < root->size; i++) burnTrie(root->nodes[i]); free(root->indexes); free(root->nodes); free(root); } // Destroys tree by freeing all space held by structure void destroyTree(Tree *tree) { int i; if (tree == NULL) return; burnTrie(tree->root); free(tree->indexes); free(tree); } int main(void) { Tree *tree = NULL; tree = addWord(tree, "add space"); printf("%s\n", tree->indexes); addWord(tree, "add 1 2 3"); printf("%s\n", tree->indexes); addWord(tree, "add 0 9 5"); printf("%s\n", tree->indexes); addWord(tree, "test symb@ls"); printf("%s\n", tree->indexes); addWord(tree, "more #(!*$"); printf("%s\n", tree->indexes); addWord(tree, "existing"); printf("%s\n", tree->indexes); addWord(tree, "EXISTING"); printf("%s\n", tree->indexes); printTree(tree); destroyTree(tree); return 0; }
C
/* * eval.c * Facility: m4 macro processor * by: oz */ #include "mdef.h" #include "extr.h" extern ndptr lookup(); extern char *strsave(); extern char *mktemp(); /* * eval - evaluate built-in macros. * argc - number of elements in argv. * argv - element vector : * argv[0] = definition of a user * macro or nil if built-in. * argv[1] = name of the macro or * built-in. * argv[2] = parameters to user-defined * . macro or built-in. * . * * Note that the minimum value for argc is 3. A call in the form * of macro-or-builtin() will result in: * argv[0] = nullstr * argv[1] = macro-or-builtin * argv[2] = nullstr * */ eval (argv, argc, td) register char *argv[]; register int argc; register int td; { register int c, n; static int sysval; #ifdef DEBUG printf("argc = %d\n", argc); for (n = 0; n < argc; n++) printf("argv[%d] = %s\n", n, argv[n]); #endif /* * if argc == 3 and argv[2] is null, * then we have macro-or-builtin() type call. * We adjust argc to avoid further checking.. * */ if (argc == 3 && !*(argv[2])) argc--; switch (td & ~STATIC) { case DEFITYPE: if (argc > 2) dodefine(argv[2], (argc > 3) ? argv[3] : null); break; case PUSDTYPE: if (argc > 2) dopushdef(argv[2], (argc > 3) ? argv[3] : null); break; case DUMPTYPE: dodump(argv, argc); break; case EXPRTYPE: /* * doexpr - evaluate arithmetic expression * */ if (argc > 2) pbnum(expr(argv[2])); break; case IFELTYPE: if (argc > 4) doifelse(argv, argc); break; case IFDFTYPE: /* * doifdef - select one of two alternatives based * on the existence of another definition */ if (argc > 3) { if (lookup(argv[2]) != nil) pbstr(argv[3]); else if (argc > 4) pbstr(argv[4]); } break; case LENGTYPE: /* * dolen - find the length of the argument * */ if (argc > 2) pbnum((argc > 2) ? strlen(argv[2]) : 0); break; case INCRTYPE: /* * doincr - increment the value of the argument * */ if (argc > 2) pbnum(atoi(argv[2]) + 1); break; case DECRTYPE: /* * dodecr - decrement the value of the argument * */ if (argc > 2) pbnum(atoi(argv[2]) - 1); break; #if unix || vms case SYSCTYPE: /* * dosys - execute system command * */ if (argc > 2) sysval = system(argv[2]); break; case SYSVTYPE: /* * dosysval - return value of the last system call. * */ pbnum(sysval); break; #endif case INCLTYPE: if (argc > 2) if (!doincl(argv[2])) { fprintf(stderr,"m4: %s: ",argv[2]); error("cannot open for read."); } break; case SINCTYPE: if (argc > 2) (void) doincl(argv[2]); break; #ifdef EXTENDED case PASTTYPE: if (argc > 2) if (!dopaste(argv[2])) { fprintf(stderr,"m4: %s: ",argv[2]); error("cannot open for read."); } break; case SPASTYPE: if (argc > 2) (void) dopaste(argv[2]); break; #endif case CHNQTYPE: dochq(argv, argc); break; case CHNCTYPE: dochc(argv, argc); break; case SUBSTYPE: /* * dosub - select substring * */ if (argc > 3) dosub(argv,argc); break; case SHIFTYPE: /* * doshift - push back all arguments except the * first one (i.e. skip argv[2]) */ if (argc > 3) { for (n = argc-1; n > 3; n--) { putback(rquote); pbstr(argv[n]); putback(lquote); putback(','); } putback(rquote); pbstr(argv[3]); putback(lquote); } break; case DIVRTYPE: if (argc > 2 && (n = atoi(argv[2])) != 0) dodiv(n); else { active = stdout; oindex = 0; } break; case UNDVTYPE: doundiv(argv, argc); break; case DIVNTYPE: /* * dodivnum - return the number of current * output diversion * */ pbnum(oindex); break; case UNDFTYPE: /* * doundefine - undefine a previously defined * macro(s) or m4 keyword(s). */ if (argc > 2) for (n = 2; n < argc; n++) remhash(argv[n], ALL); break; case POPDTYPE: /* * dopopdef - remove the topmost definitions of * macro(s) or m4 keyword(s). */ if (argc > 2) for (n = 2; n < argc; n++) remhash(argv[n], TOP); break; case MKTMTYPE: /* * dotemp - create a temporary file * */ if (argc > 2) pbstr(mktemp(argv[2])); break; case TRNLTYPE: /* * dotranslit - replace all characters in the * source string that appears in * the "from" string with the corresponding * characters in the "to" string. * */ if (argc > 3) { char temp[MAXTOK]; if (argc > 4) map(temp, argv[2], argv[3], argv[4]); else map(temp, argv[2], argv[3], null); pbstr(temp); } else if (argc > 2) pbstr(argv[2]); break; case INDXTYPE: /* * doindex - find the index of the second argument * string in the first argument string. * -1 if not present. */ pbnum((argc > 3) ? indx(argv[2], argv[3]) : -1); break; case ERRPTYPE: /* * doerrp - print the arguments to stderr file * */ if (argc > 2) { for (n = 2; n < argc; n++) fprintf(stderr,"%s ", argv[n]); fprintf(stderr, "\n"); } break; case DNLNTYPE: /* * dodnl - eat-up-to and including newline * */ while ((c = gpbc()) != '\n' && c != EOF) ; break; case M4WRTYPE: /* * dom4wrap - set up for wrap-up/wind-down activity * */ m4wraps = (argc > 2) ? strsave(argv[2]) : null; break; case EXITTYPE: /* * doexit - immediate exit from m4. * */ exit((argc > 2) ? atoi(argv[2]) : 0); break; case DEFNTYPE: if (argc > 2) for (n = 2; n < argc; n++) dodefn(argv[n]); break; default: error("m4: major botch in eval."); break; } }
C
#include <stdio.h> #define byte char void print_bin(unsigned a); int main() { print_bin(-93); return 0; } void print_bin(unsigned a) { int b = (int) sizeof a; unsigned mask = 1; printf("mask=%d\n", mask); if ((int)a<0) printf("-"); a =~a; for (mask =0x10000000; mask >=1; mask>>=1) if (>=0) printf((!(a&mask))? "0":"1"); else printf((a&mask)? "0":"1"); printf("\n"); }
C
#include<stdio.h> int main() { int a = 5, b = 6, c = 2, d = 4; int x,y; x = a * b; y = c * d; printf("%d\n", x); printf("%d\n", y); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <sys/wait.h> int main(){ pid_t pid; int ret = 1; int status; pid = fork(); if (pid == -1){ // pid == -1 means error occured printf("can't fork, error occured\n"); exit(EXIT_FAILURE); } else if (pid == 0){ // pid == 0 means child process created // getpid() returns process id of calling process printf("child process, pid = %u\n",getpid()); // the argv list first argument should point to // filename associated with file being executed // the array pointer must be terminated by NULL // pointer char * argv_list[] = {"ls","-lart","/home",NULL}; // the execv() only return if error occured. // The return value is -1 execv("ls",argv_list); exit(0); } else{ // a positive number is returned for the pid of // parent process // getppid() returns process id of parent of // calling process printf("parent process, pid = %u\n",getppid()); // the parent process calls waitpid() on the child // waitpid() system call suspends execution of // calling process until a child specified by pid // argument has changed state // see wait() man page for all the flags or options // used here if (waitpid(pid, &status, 0) > 0) { if (WIFEXITED(status) && !WEXITSTATUS(status)) printf("program execution successful\n"); else if (WIFEXITED(status) && WEXITSTATUS(status)) { if (WEXITSTATUS(status) == 127) { // execv failed printf("execv failed\n"); } else printf("program terminated normally," " but returned a non-zero status\n"); } else printf("program didn't terminate normally\n"); } else { // waitpid() failed printf("waitpid() failed\n"); } exit(0); } return 0; }
C
/*====================================================================== t <- ISATOMF(F) Is Atomic Formula? \Input \parm{F} is a quantifier--free formula. \Output \parm{t} is 1 if \v{F} is an atomic formula, 0 otherwise. ======================================================================*/ #include "qepcad.h" Word ISATOMF(Word F) { Word T,t; /* hide t; */ Step1: /* Check. */ T = FIRST(F); if (T == LTOP || T == EQOP || T == GTOP || T == GEOP || T == NEOP || T == LEOP || T == IROOT) t = 1; else t = 0; goto Return; Return: /* Prepare for return. */ return(t); }
C
#include"SeqList.h" #include<assert.h> void SeqListInit(SeqList* seqlist, int capacity){ //жָǷΪ //if (seqlist == nullptr){} assert(seqlist); //ڶϿٿռ seqlist->array = (SDateType*)malloc(sizeof(SDateType) * capacity); //жǷΪ assert(seqlist->array); seqlist->size = 0; seqlist->capacity = capacity; } void SeqListDestroy(SeqList* seqlist){ assert(seqlist); assert(seqlist->array); free(seqlist->array); seqlist->size = 0; seqlist->capacity = 0; printf("ռͷ\n"); } void PushBack(SeqList* seqlist, SDateType val){ assert(seqlist); assert(seqlist->array); seqlist->array[seqlist->size] = val; seqlist->size++; } void PopBack(SeqList* seqlist){ assert(seqlist); assert(seqlist->array); assert(seqlist->size > 0); seqlist->size--; } void PushHand(SeqList* seqlist, SDateType val){ assert(seqlist); assert(seqlist->array); seqlist->size++; for (int i = seqlist->size; i > 0; i--){ seqlist->array[i] = seqlist->array[i - 1]; } seqlist->array[0] = val; } void PopHand(SeqList* seqlist){ assert(seqlist); assert(seqlist->array); assert(seqlist->size > 0); //for (int i = 0; i < seqlist->size - 1; i++){ //seqlist->array[i] = seqlist->array[i + 1]; //} for (int i = 1; i < seqlist->size; i++){ seqlist->array[i - 1] = seqlist->array[i]; } seqlist->size--; } void SeqListChange(SeqList* seqlist, SDateType n, SDateType val){ assert(seqlist); assert(seqlist->array); assert(seqlist->size > 0); seqlist->array[n] = val; } int SeqListFind(SeqList* seqlist, SDateType val){ assert(seqlist); assert(seqlist->array); assert(seqlist->size > 0); for (int i = 0; i < seqlist->size; i++){ if (seqlist->array[i] == val){ printf("%d\n", i); } } return -1; } void Print(SeqList* seqlist){ for (int i = 0; i <seqlist->size; i++){ printf("%d ", seqlist->array[i]); } printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> // The includes listed in the lstat man page. #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main(int argc, char **argv) { // In order for this demo to work, create a file named example.txt in the // same directory as this code. char *path = "example.txt"; // On teach.cs, run: man lstat // Read about the lstat system call, which has two parameters: // a file path and a pointer to a struct stat. // Note: lstat is available on teach.cs and it may not be installed on // your personal computer. Run this demo on teach.cs. // We need to allocate space for a struct stat. We'll pass // a pointer to this struct as an argument to lstat, and // the call on lstat will populate it with information about path. struct stat stat_buf; // Call lstat to populate stat_buf with information about path. // Also, error check the system call and if it fails, return with exit code 1. // See the RETURN section of the man page to learn about what lstat returns. if (lstat(path, &stat_buf) == -1) { perror("lstat"); return 1; } // Let's use the information in stat_buf to check whether path is a // regular file. Read the lstat man page to find out about the various // macros that you can use. // We'll use macro S_ISREG: if (S_ISREG(stat_buf.st_mode)) { printf("%s is a regular file\n", path); } // Next, we'll use use the logical "and" operator to extract the permissions: int permissions = stat_buf.st_mode & 0777; printf("the file permissions are %o\n", permissions); return 0; }
C
#include<stdio.h> int main(){ long long B[64][64],n; int i,j,k; for(i=0;i<64;i++) B[1][i]=i; for(i=2;i<64;i++){ B[i][0]=0; for(j=1;j<64;j++) B[i][j]=B[i][j-1]+B[i-1][j-1]+1; } while(scanf("%d%lld",&k,&n),k!=0&&n!=0){ if(k>63) k=63; if(n>B[k][63]) puts("More than 63 trials needed."); else{ for(i=1;i<64&&B[k][i]<n;i++); printf("%d\n",i); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> int static compare (const void* first, const void* second); int minimumCost(int price[], int n); int main(){ int n; printf("Enter the size of array : "); scanf("%d", &n); int price[n]; for(int i=0; i<n; i++){ printf("Enter the component : "); scanf("%d", &price[i]); } printf("Total cost is %i to cross the bridge.\n",minimumCost(price, n)); return 0; } //Compare function int static compare (const void* first, const void* second){ if (*(int*)first > *(int*)second) return 1; else if (*(int*)first < *(int*)second) return -1; else return 0; } //Calculate the minimum cost int minimumCost(int price[], int n){ // Sort the price array qsort(price, n, sizeof(int),compare); int totalCost = 0; printf("Procedure\n"); for(int i=n-1; i>1; i-=2){ if((n%2 == 1) && i==2){ printf("%i and %i\n",price[0],price[i]); // move to right totalCost += price[i]; printf("%i\n",price[0]); // move to left totalCost += price[0]; printf("%i and %i\n",price[0],price[i-1]); // move to right totalCost += price[i-1]; return totalCost; } if(price[1]*2 <= price[0] + price[i-1]){ printf("%i and %i\n",price[0],price[1]); // move to right totalCost += price[1]; printf("%i\n",price[0]); // move to left totalCost += price[0]; printf("%i and %i\n",price[i-1],price[i]); // move to right totalCost += price[i]; printf("%i\n",price[1]); // move to left totalCost += price[1]; } else{ printf("%i and %i\n",price[0],price[i]); // move to right totalCost += price[i]; printf("%i\n",price[0]); // move to left totalCost += price[0]; printf("%i and %i\n",price[0],price[i-1]); // move to right totalCost += price[i-1]; printf("%i\n",price[0]); // move to left totalCost += price[0]; } } printf("%i and %i\n",price[0],price[1]); totalCost += price[1]; return totalCost; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../include/Interface.h" void printRecord(patientRecord record) { printf("%s | %s | %s | %s | %s | %d | %d-%d-%d | %d-%d-%d\n", record.recordID, record.patientFirstName, record.patientLastName, record.diseaseID, record.country, record.age, record.entryDate.day, record.entryDate.month, record.entryDate.year, record.exitDate.day, record.exitDate.month, record.exitDate.year); } void printList(listNode *head) { listNode *current = head; while (current != NULL) { printRecord(*(current->record)); current = current->next; } } listNode *sortDateInsert(listNode **head, patientRecord **record) { int sortFlag; if (*head == NULL) { // if list is empty *head = (listNode *)malloc(sizeof(listNode)); if (*head == NULL) { exit(-1); } (*head)->record = *record; (*head)->next = NULL; return *head; } listNode *current; sortFlag = compareDates(*head, *record); if (sortFlag == 0 || sortFlag == 1) { // if new record's date is older than head's (or same) current = (listNode *)malloc(sizeof(listNode)); if (current == NULL) { exit(-1); } current->record = *record; current->next = *head; *head = current; return *head; } current = *head; listNode *previous = NULL; listNode *newNode = (listNode *)malloc(sizeof(listNode)); if (newNode == NULL) { exit(-1); } newNode->record = *record; while (current->next != NULL && compareDates(current, *record) == 2) { previous = current; current = current->next; } if (current->next == NULL) { if (compareDates(current, *record) == 2) { current->next = newNode; newNode->next = NULL; } else { newNode->next = current; previous->next = newNode; } } else { newNode->next = current; previous->next = newNode; } return newNode; } listNode *patientsEntryRecord(listNode *head, char *recordID) { listNode *current = head; while(current != NULL) { if(!strcmp(current->record->recordID, recordID)) return current; current = current->next; } return NULL; } listNode *storeData(char *patientRecordsFile, listNode **head, char *date, char *country, StatsDateNode **currDateNode) { listNode *activeCase = NULL; char tmpDateInfo[11]; char tmpEntryInfo[32]; FILE *fp = fopen(patientRecordsFile, "r"); if (fp == NULL) { printf("Could not open file %s\n", patientRecordsFile); exit(-1); } patientRecord *tmpRecordPtr; for (int i = 0; !feof(fp); i++) { switch(i % 6) { case 0: // start of a record tmpRecordPtr = malloc(sizeof(patientRecord)); if (tmpRecordPtr == NULL) { exit(-1); } fscanf(fp, "%s", tmpEntryInfo); tmpRecordPtr->recordID = malloc(sizeof(char) * (strlen(tmpEntryInfo) + 1)); strcpy(tmpRecordPtr->recordID, tmpEntryInfo); break; case 1: fscanf(fp, "%s", tmpEntryInfo); if(!strcmp(tmpEntryInfo, "ENTRY")) { // create a new record and set the entry date tmpRecordPtr->country = malloc(sizeof(char) * (strlen(country) + 1)); strcpy(tmpRecordPtr->country, country); sscanf(date, "%d-%d-%d.txt", &(tmpRecordPtr->entryDate.day), &(tmpRecordPtr->entryDate.month), &(tmpRecordPtr->entryDate.year)); tmpRecordPtr->exitDate.day = 0; tmpRecordPtr->exitDate.month = 0; tmpRecordPtr->exitDate.year = 0; } else if (!strcmp(tmpEntryInfo, "EXIT")) { // check if there is already a patient and update that record. Else ERROR. activeCase = patientsEntryRecord(*head, tmpRecordPtr->recordID); if(activeCase != NULL) { // there is an active case with this patient sscanf(date, "%d-%d-%d.txt", &(activeCase->record->exitDate.day), &(activeCase->record->exitDate.month), &(activeCase->record->exitDate.year)); } else { printf("ERROR: Invalid record with ID = %s\n", tmpRecordPtr->recordID); } // tmpRecord must be destroyed now because it's invalid, and we continue to the next record free(tmpRecordPtr->recordID); free(tmpRecordPtr); int n = 4; i += 4; while(n--) // cycle through the invalid record fscanf(fp, "%s", tmpEntryInfo); continue; } break; case 2: fscanf(fp, "%s", tmpEntryInfo); tmpRecordPtr->patientFirstName = malloc(sizeof(char) * (strlen(tmpEntryInfo) + 1)); strcpy(tmpRecordPtr->patientFirstName, tmpEntryInfo); break; case 3: fscanf(fp, "%s", tmpEntryInfo); tmpRecordPtr->patientLastName = malloc(sizeof(char) * (strlen(tmpEntryInfo) + 1)); strcpy(tmpRecordPtr->patientLastName, tmpEntryInfo); break; case 4: fscanf(fp, "%s", tmpEntryInfo); tmpRecordPtr->diseaseID = malloc(sizeof(char) * (strlen(tmpEntryInfo) + 1)); strcpy(tmpRecordPtr->diseaseID, tmpEntryInfo); break; case 5: fscanf(fp, "%s", tmpEntryInfo); tmpRecordPtr->age = atoi(tmpEntryInfo); addStatsToDisease(&((*currDateNode)->diseaseListPtr), tmpRecordPtr->diseaseID, tmpRecordPtr->age); sortDateInsert(head, &tmpRecordPtr); break; } } fclose(fp); return *head; } bool isUniqueID(listNode *head, char *newID) { listNode *current = head; while (current->next != NULL && strcmp(current->record->recordID, newID)) { current = current->next; } if (current->next == NULL) { if (strcmp(current->record->recordID, newID)) { return true; } } return false; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define CHECK_ALLOC(x) if(!(x)) { puts("Memory allocation error!"); exit(1); } char **allocate(int m, int n) { char **table; table = (char **) malloc(m * sizeof(char*)); CHECK_ALLOC(table); for (int i = 0; i < m; i++) { table[i] = (char *) malloc(n * sizeof(char)); CHECK_ALLOC(table[i]); memset(table[i], 'O', n * sizeof(char)); } return table; } void load(char **table, int m, int n) { int k, x, y; char type; printf("\nHow many figures you want to load? "); scanf("%d", &k); for (int i = 0; i < k; i++) { do { printf("Figure position and type? [King=K, Queen=Q, Rook=R, Bishop=B, Knight=N, Pawn=P\n"); scanf("%d%d %c", &x, &y, &type); fflush(stdin); if (x < 0 || x >= m) continue; if (y < 0 || y >= n) continue; if (type == 'K' || type == 'Q' || type == 'R' || type == 'B' || type == 'N' || type == 'P') break; } while (1); table[x][y] = type; } } int check(int x, int y, int m, int n) { if (x < 0 || x >= m) return 0; if (y < 0 || y >= n) return 0; return 1; } void proccess(char **attacker, char **defender, int m, int n) { static const int displacement[][2] = { { 1, -2 }, { -1, -2 }, { 1, 2 }, { -1, 2 }, { -2, 1 }, { -2, -1 }, { 2, 1 }, { 2, -1 } }; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (attacker[i][j] == 'N') for (int k = 0; k < 8; k++) { int x = i + displacement[k][0]; int y = j + displacement[k][1]; if (check(x, y, m, n) && defender[x][y] != 'O') { printf("\nMoves:\n"); printf("N(%d,%d) -> %c(%d,%d)\n", i, j, defender[x][y], x, y); } } } void deallocate(char **table, int m) { for (int i = 0; i < m; i++) free(table[i]); free(table); } int main() { char **white, **black, color; int m, n; printf("m, n? "); scanf("%d%d", &m, &n); white = allocate(m, n); black = allocate(m, n); printf("\nLoading white figures positions..."); load(white, m, n); printf("\nLoading black figures positions..."); load(black, m, n); fflush(stdin); printf("\nColor of the knight which is going to be checked? [w/W for white or b/B for black]\n"); scanf("%c", &color); if (color == 'W' || color == 'w') proccess(white, black, m, n); else proccess(black, white, m, n); deallocate(white, m); deallocate(black, m); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "listaEncadeada.h" Lista* create(){ Lista* novaLista = (Lista*) malloc (sizeof (Lista)); // 1 Complexidade Espacial, 1 Complexidade Temporal if (novaLista != NULL){ // 1 Complexidade Temporal novaLista->inicio = novaLista->fim = NULL; // 2 Complexidade Temporal novaLista->tamanho = 0; // 1 Complexidade Temporal } return novaLista; // 1 Complexidade Temporal } // Complexidade Espacial = O(1), Complexidade Temporal = O(c), c constante int add (Lista* lista, int elemento){ // 2 Complexidade Espacial No* novo = (No*) malloc(sizeof(No)); // 1 Complexidade Espacial, 1 Complexidade Temporal if (novo != NULL){ // 1 Complexidade Temporal novo->info = elemento; // 1 Complexidade Temporal novo->prox = NULL; // 1 Complexidade Temporal if (lista->inicio == NULL){ // 1 Complexidade Temporal lista->inicio = novo; // 1 Complexidade Temporal } else { lista->fim->prox = novo; // 1 Complexidade Temporal } lista->fim = novo; // 1 Complexidade Temporal lista->tamanho++; // 1 Complexidade Temporal return 1; // 1 Complexidade Temporal } return 0; // 1 Complexidade Temporal } // Complexidade Espacial = O(3) = O(c), c constante // Complexidade Temporal = O(11) = O(c), c constante int pop(Lista* lista, int elemento){ // 2 Complexidade Espacial if (!isEmpty(lista)){ // 1 Complexidade Temporal No* aux = lista->inicio; // 1 Complexidade Espacial,1 Complexidade Temporal No* ant; // 1 Complexidade Espacial, 1 Complexidade Temporal while (aux != NULL && aux->info != elemento){ // N Complexidade Temporal ant = aux; // 1 Complexidade Temporal aux = aux->prox; // 1 Complexidade Temporal } if (aux != NULL){ // 1 Complexidade Temporal if (aux == lista->inicio){ // 1 Complexidade Temporal lista->inicio = aux->prox; // 1 Complexidade Temporal } else { ant->prox = aux->prox; // 1 Complexidade Temporal } if (aux == lista->fim){ // 1 Complexidade Temporal lista->fim = ant; // 1 Complexidade Temporal } lista->tamanho--; // 1 Complexidade Temporal freeNo(aux); // 1 Complexidade Temporal return 1; // 1 Complexidade Temporal } return 0; // 1 Complexidade Temporal } return 0; // 1 Complexidade Temporal } // Complexidade Espacial = O(4) // Complexidade Temporal = O(14 + 2*N) = O(14+N) = O(N) int size(Lista* lista){ // 1 Complexidade Espacial return lista->tamanho; // 1 Complexidade Temporal } // Complexidade Espacial = Complexidade Temporal = O(c), c constante int find (Lista* lista, int elemento){ // 2 Complexidade Espacial if (!isEmpty(lista)){ // 1 Complexidade Temporal No* aux; // 1 Complexidade Espacial, 1 Complexidade Temporal int pos = 0; // 1 Complexidade Espacial, 1 Complexidade Temporal for (aux = lista->inicio; aux != NULL; aux = aux->prox){ // N Complexidade Temporal if (aux->info == elemento){ // 1 Complexidade Temporal return pos; // 1 Complexidade Temporal } pos++; // 1 Complexidade Temporal } return -1; // 1 Complexidade Temporal } return -1; // 1 Complexidade Temporal } // Complexidade Espacial = O(4), Complexidade Temporal = O(N) void clear(Lista* lista){ // 1 Complexidade Espacial if (!isEmpty(lista)){ // 1 Complexidade Temporal No* aux = lista->inicio; // 1 Complexidade Espacial, 1 Complexidade Temporal while (aux != NULL){ // N Complexidade Temporal No* aux2 = aux->prox; // 1 Complexidade Temporal, 1 Complexidade Espacial freeNo(aux); // 1 Complexidade Temporal aux = aux2; // 1 Complexidade Temporal } lista->tamanho = 0; // 1 Complexidade Temporal lista->inicio = lista->fim = NULL; // 2 Complexidade Temporal } } // Complexidade Espacial = O(2 + N) = O(N) // Complexidade Temporal = O(5 + 3*N) = O(5 + N) = O(N) int isEmpty(Lista* lista){ // 1 Complexidade Espacial return lista->tamanho == 0; // 1 Complexidade Temporal } // Complexidade Temporal = Complexidade Espacial = O(c), c constante void imprimirLista (Lista* lista){ // 1 Complexidade Espacial if (isEmpty(lista)){ // 1 Complexidade Temporal printf ("Lista vazia!\n\n"); // 1 Complexidade Temporal } else { No* aux = lista->inicio; // 1 Complexidade Espacial, 1 Complexidade Temporal while (aux != NULL){ // N Complexidade Temporal imprimirNo (aux); // 1 Complexidade Temporal aux = aux->prox; // 1 Complexidade Temporal } printf("NULL\nTamanho: %d\n\n", size(lista)); // 1 Complexidade Temporal } } // Complexidade Espacial = O(c), c constante // Complexidade Temporal = O(N)
C
#include<stdio.h> long kaijo(int); int main(void){ int a=0; printf("Type Integer"); scanf("%d",&a); printf("%2d!=%10ld\n",a,kaijo(a)); return 0; } long kaijo(int n){ if(n==0) return 1L; else return n*kaijo(n-1); }
C
/* * SNAPSPECKS: tabulate a snapshot in specks format * * 7-nov-00 PJT Created, Q&D * 11-mar-01 PJT time floating * 19-may-01 integer again? */ #include <nemo.h> #include <snapshot/snapshot.h> #include <snapshot/body.h> #include <snapshot/get_snap.c> string defv[] = { /* DEFAULT INPUT PARAMETERS */ "in=???\n Input file (snapshot)", "options=x,y,z,m\n Output variables", "format=%g\n Format for output", "times=all\n Times to select snapshot", "VERSION=1.0a\n 19-may-01 PJT", NULL, }; string usage="tabulate a snapshot in specks format"; extern string *burststring(string,string); #define MAXOPT 50 void nemo_main() { stream instr, tabstr; real tsnap, dr, aux; string times; Body *btab = NULL, *bp, *bq; bool Qsepar, Qhead; int i, n, nbody, bits, nsep, isep, nopt, ParticlesBit, datatime = 0; char fmt[20],*pfmt; string *opt; rproc btrtrans(), fopt[MAXOPT]; ParticlesBit = (MassBit | PhaseSpaceBit | PotentialBit | AccelerationBit | AuxBit | KeyBit); instr = stropen(getparam("in"), "r"); /* open input file */ opt = burststring(getparam("options"),", "); nopt = 0; /* count options */ while (opt[nopt]) { /* scan through options */ fopt[nopt] = btrtrans(opt[nopt]); nopt++; if (nopt==MAXOPT) { warning("Maximum number of options = %d exhausted\n",MAXOPT); break; } } printf("## file created by snapspecks\n"); for (i=0; i<nopt; i++) printf("# %s ",opt[i]); printf("\n"); times = getparam("times"); pfmt = getparam("format"); strcpy (fmt,pfmt); if (strchr(fmt,' ')==NULL && strchr(fmt,',')==NULL) strcat (fmt," "); /* append blank if user did not specify sep */ printf("datavar 0 lum\n"); get_history(instr); /* read history */ for(;;) { /* repeating until first or all times are read */ get_history(instr); if (!get_tag_ok(instr, SnapShotTag)) break; get_snap(instr, &btab, &nbody, &tsnap, &bits); if (!streq(times,"all") && !within(tsnap,times,0.0001)) continue; /* skip work on this snapshot */ if ( (bits & ParticlesBit) == 0) continue; /* skip work, no data here */ printf("# time=%g\n",tsnap); printf("datatime %d\n",datatime++); for (bp = btab, i=0; bp < btab+nbody; bp++, i++) { for (n=0; n<nopt; n++) { aux = fopt[n](bp,tsnap,i); printf(fmt,aux); } printf("\n"); } } strclose(instr); }
C
// // qweue.c // Scientific_work_v2.0 // // Created by Artem on 18/08/2018. // Copyright © 2018 Artem. All rights reserved. // #include "Header.h" int* creatr_qweue(int n){ int *result = calloc(n+2, sizeof(unsigned int)); result[0] = n+2; result[1] = 2; return result; } void push_qweue(int *qweue, int inf){ int last_point = qweue[1]; qweue[1] += 1; qweue[last_point] = inf; } int pop_qweue(int *qweue){ if (qweue == NULL || qweue[1] == 2) return -1; //unsigned int last_point = qweue[1]; int result = qweue[2]; for(int i = 2; i<qweue[1]; ++i) qweue[i] = qweue[i+1]; qweue[qweue[1]] = 0; if(qweue[1] > 1) --qweue[1]; return result; };
C
#include <stdio.h> main(){ int a, b; a = 10; b = 11; a >= b? printf("a e maior ou igual a b") : printf("a nao e maior ou igual a b"); // nao precisa usar o if - condicional ternario }
C
#include<stdio.h> #include<math.h> typedef long long ll; int nxt=0; long primes[78500]; ll fac[78500][2]; void init(){ ll n=int(1e6)+1; int *arr=new int[n]; int i,j; for(i=2;i<n;i++){ if(arr[i]) continue; primes[nxt++]=i; for(j=2*i;j<n;j+=i) arr[j]=1; } } int main(){ init(); int t; scanf("%d",&t); while(t--){ scanf("%lld%lld",&n,&k); memset(fac,0,sizeof (fac)); ll max=0; for(j=0;j<nxt;j++){ if(k==1) break; if(k%primes[j]==0){ fac[max][0]=primes[j]; int lcnt=0; while(k%primes[j]==0){ k/=primes[j]; lcnt++; } fac[max++][1]=lcnt; } } if(k!=1){ fac[max][0]=k; fac[max++][1]=1; } ll x; ll res=n; ll comp,win=INF; for(j=0;j<max;j++){ n=res; x=fac[j][0]; ll pw=0; while(n){ n/=x; pw+=n; } comp=fac[j][1]-pw; if(comp<win) win=comp; } if(win>0) printf("%lld\n",win); else puts("0"); } return 0; }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> /** * infinite_while - Sleeps infinitely * * Return: 0 */ int infinite_while(void) { while (1) { sleep(1); } return (0); } /** * main - Creates 5 zombie processes * * Return: EXIT_SUCCESS if function properly, otherwise EXIT_FAILURE */ int main(void) { int i; pid_t pid; for (i = 0; i < 5; ++i) { pid = fork(); if (pid < 0) return (EXIT_FAILURE); else if (!pid) { printf("Zombie process created, PID: %d\n", getpid()); return (EXIT_SUCCESS); } } infinite_while(); return (EXIT_SUCCESS); }
C
#include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/unistd.h> #include <linux/syscalls.h> static unsigned long **find_sys_call_table(void) { unsigned long offset; unsigned long **sct; // PAGE_OFFSETから探索 for(offset = PAGE_OFFSET; offset < ULLONG_MAX; offset += sizeof(void *)) { // 仮にoffsetがsys_call_tableの先頭だとする sct = (unsigned long**)offset; // __NR_close番目のポインタがsys_closeであれば一致 if(sct[__NR_close] == (unsigned long*) sys_close) { printk(KERN_INFO "gettable: Found sys_call_table at 0x%lx", (unsigned long)sct); return sct; } } printk(KERN_INFO "gettable: Found nothing"); return NULL; } /* * モジュール初期化 */ int init_module(void) { unsigned long x; printk(KERN_INFO "gettable: init\n"); // sys_call_tableを探索 x = (unsigned long)find_sys_call_table(); // 物理アドレスも表示 x = __phys_addr_nodebug(x); printk(KERN_INFO "gettable: Physical address is 0x%lx", x); return 0; } /* * モジュール解放 */ void cleanup_module(void) { printk(KERN_INFO "gettable: exit\n"); }
C
#include <stdio.h> #include <stdlib.h> #include "E2funciones.h" //argv[1] = orden(Ascendente = 1, Descendente = 2) //argv[2] = datos.bin int main(int argc, char const *argv[]) { system("clear"); if (argc<3) { printf("Error faltan datos para ejecutar el programa. Por favor llame al programa de esta forma:\n\n"); printf("./E2.exe (Si desea ordenarlos de forma ascedente ponga aquí 1, si desea ordenarlos de forma descendente) nombre_del_fichero_de_alumnos\n\n"); printf("Pulse enter para salir...\n"); getchar(); system("clear"); return (-1); } int existen = existeFichero(argv[2]); switch(existen) { case 0: printf("Error no existen los archivos pasados como argumento.\n"); printf("Pulse enter para continuar..."); getchar(); return 0; break; case 1: ; alumno *clase; clase = reservaMemoriaClase(numeroDeAlumnos(argv[2])); rellenaClase(argv[2], clase, numeroDeAlumnos(argv[2])); int orden = atoi(argv[1]); int (*funcion) (alumno, alumno); switch(orden) { case 1: funcion = &ascendente; ordenaClase(clase, numeroDeAlumnos(argv[2]), funcion); break; case 2: funcion = &descendente; ordenaClase(clase, numeroDeAlumnos(argv[2]), funcion); break; default: printf("Error el numero introducido no se corresponde con ninún orden.\n"); printf("Introduzca 1 para ordenarlos de forma ascedente\n"); printf("Introduzca 2 para ordenarlos de forma descendente\n"); } free(clase); break; } return 0; }
C
//@@ TESTS: TEST_NULL TEST_STRCPY TEST_STRCPY2 TEST_STRCAT TEST_STRCHR TEST_STRDUP TEST_STRPBRK TEST_MEMCPY TEST_MEMCPY2 TEST_MEMMOVE TEST_MEMSET TEST_MEMCHR //@@ TESTS: TAINT NO_TAINT #include <string.h> #include <stdio.h> int main() { char danger[100]; char safe[100]; char other[100]; #if defined(TAINT) gets(danger); "EXPECT_TAINT_WARNINGS"; #else "EXPECT_NO_WARNINGS"; #endif #if defined TEST_NULL *safe = *danger; #elif defined TEST_STRCPY strcpy(safe, danger); #elif defined TEST_STRCPY2 *safe = *strcpy(other, danger); #elif defined TEST_STRCAT strcat(safe, danger); #elif defined TEST_STRCHR *safe = *strchr(danger, 'x'); #elif defined TEST_STRDUP *safe = *strdup(danger); #elif defined TEST_STRPBRK *safe = *strpbrk(danger, "x"); #elif defined TEST_MEMCPY memcpy(safe, danger, 100); #elif defined TEST_MEMCPY2 *safe = *( (char*) memcpy(other, danger, 100) ); #elif defined TEST_MEMMOVE memmove(safe, danger, 100); #elif defined TEST_MEMSET memset(safe, danger[0], 100); #elif defined TEST_MEMCHR *safe = *( (char*) memchr(danger, 'x', 100) ); #else # error "didn't select test" ERROR ERROR ERROR; #endif printf(safe); }
C
/* esse foi o primeiro código que eu testei mas deu errado #include <stdio.h> int main () { int XE, YE, XD, YD; int XP, YP; scanf ("%d %d %d %d",&XE, &YE, &XD, &YD); scanf ("%d %d", &XP, &YP); // esse primeiro if representa o caso baso descrito no enunciado da questão if (XE < XD && YE > YD) { if (XP >= XE && XP <= XD && YP >= YD && YP <= YE) { printf ("Dentro!"); } else { printf ("Fora!");} return 0;} } */ #include <stdio.h> int main () { int XE, YE, XD, YD; int XP, YP; scanf ("%d %d %d %d",&XE, &YE, &XD, &YD); scanf ("%d %d", &XP, &YP); if (XE < XD && YE > YD) { if (XP >= XE && XP <= XD && YP >= YD && YP <= YE) { printf ("Dentro!"); } else { printf ("Fora!");} } else if (XE < XD && YE < YD) { if (XP >= XE && XP <= XD && YP <= YD && YP >= YE) { printf ("Dentro!"); } else {printf ("Fora!");} } else if (XE > XD && YE > YD) { if (XP <= XE && XP >= XD && YP >= YD && YP <= YE) {printf ("Dentro!"); } else {printf ("Fora!");} } else if (XE > XD && YE < YD) { if (XP <= XE && XP >= XD && YP <= YD && YP >= YE) { printf ("Dentro!"); } else {printf ("Fora!");} } else {printf (" error");} return 0; }
C
#include "Bibliotecas.h" int minusculas(char palavra[]) { int i; int aux = strlen(palavra); if (aux == 0 || palavra == NULL || strcmp(palavra, " ")==0) { return 1; } for (i = 0; i < aux; i++) { palavra[i] = tolower(palavra[i]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> int *getConjuntoFatorial(int, int); int main() { int n0, size, *vetor, i; scanf("%d",&n0); scanf("%d",&size); vetor = getConjuntoFatorial(n0, size); for(i=0;i<size;i++){ printf("%d ",vetor[i]); } return 0; } int *getConjuntoFatorial(int n0, int size){ int fat=1,*vetor,i,aux=n0; vetor= (int*) malloc(size * sizeof(int)); assert(vetor); while(n0>1){ fat= fat*n0; n0--; } vetor[0]=fat; for (i=1;i<size;i++){ vetor[i]=vetor[i-1]*(aux+1); aux++; } return vetor; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include"SeqList.h" void SeqListInit(SeqList* ps)//ʼ { assert(ps); ps->_array = NULL; ps->_capacity = 0; ps->_size = 0; } void SeqListDestory(SeqList* ps)// { assert(ps); if (ps->_array) { free(ps->_array); ps->_array = NULL; ps->_capacity = 0; ps->_size = 0; } } SeqListCheckCapacity(SeqList* ps)//ǷҪݣִ { assert(ps); if (ps->_size == ps->_capacity) { size_t newcapacity =( ps->_capacity == 0) ? 4 : ps->_capacity*2; ps->_array = (DataType*)realloc(ps->_array, sizeof(DataType)*newcapacity); ps->_capacity = newcapacity; } } void SeqListPushBack(SeqList* ps, DataType x)//β { assert(ps); SeqListCheckCapacity(ps); ps->_array[ps->_size] = x; ps->_size++; //SeqListInsert(ps, ps->_size, x); } void SeqListPushFront(SeqList* ps, DataType x)//ͷ { assert(ps); SeqListCheckCapacity(ps); size_t i = 0; for (i = ps->_size; i > 0; i--) { ps->_array[i] = ps->_array[i-1]; } ps->_array[0] = x; ps->_size++; //SeqListInsert(ps, 0, x); } void SeqListPopBack(SeqList* ps)//βɾ { assert(ps && ps->_size > 0); ps->_size--; //SeqListErase(ps, ps->_size-1); } void SeqListPopFront(SeqList* ps)//ͷɾ { assert(ps); size_t i = 0; for (i = 0; i < ps->_size-1; i++) { ps->_array[i] = ps->_array[i + 1]; } ps->_array[ps->_size - 1] = 0; ps->_size--; //SeqListErase(ps, 0); } void SeqListInsert(SeqList* ps, size_t pos, DataType x)//ijλòһԪ { assert(ps && pos <= ps->_size); SeqListCheckCapacity(ps); size_t i = 0; for (i = ps->_size; i > pos; i--) { ps->_array[i] = ps->_array[i-1]; } ps->_array[pos] = x; ps->_size++; } void SeqListErase(SeqList* ps, size_t pos)//ɾijλõԪ { assert(ps && pos < ps->_size); size_t i = 0; for (i = pos; i < ps->_size-1; i++) { ps->_array[i] = ps->_array[i+1]; } ps->_size--; } size_t SeqListSize(SeqList* ps)//˳ʵԪصĸ { assert(ps); return ps->_size; } size_t SeqListFind(SeqList* ps, DataType x)//ijһԪ,± { assert(ps); size_t i = 0; for (i = 0; i < ps->_size; i++) { if (ps->_array[i] == x) return i; } return -1; } DataType SeqListAt(SeqList* ps, size_t pos)//λposֵ { assert(ps); return ps->_array[pos]; } void SeqListBubbleSort(SeqList* ps)//˳ð() {//ʱ临ӶȣON^2 assert(ps); DataType temp; size_t i = 0,j = 0; for (size_t i = 0; i < ps->_size; i++) { for (size_t j = 0; j < ps->_size - i - 1; j++) { if (ps->_array[j] > ps->_array[j + 1]) { temp = ps->_array[j]; ps->_array[j] = ps->_array[j + 1]; ps->_array[j + 1] = temp; } } } } size_t SeqListBinaryFind(SeqList* ps, DataType x)//ֲ //Ҫʱ临ӶȣO(N) ռ临ӶȣO(1) { assert(ps); size_t start = 0; size_t end = ps->_size - 1;//ұ //size_t end = ps->_size;//ҿ size_t mid = start + (end - start) / 2; while (start <= end)//Ҫ俪һ { if (x > ps->_array[mid]) { start = mid + 1;// mid = start + (end - start) / 2; } else if (x < ps->_array[mid]) { end = mid - 1;//ұ mid = start + (end - start) / 2; } else { return mid; } } return -1; } void SeqListRemoveAll(SeqList* ps, DataType x)//ȥظԪ { assert(ps); size_t index = 0; for (size_t i = 0; i < ps->_size;i++) { if (ps->_array[i] != x) { ps->_array[index++] = ps->_array[i]; } } ps->_size = index; }
C
// Programa que imprime los argumentos de la linea de // comandos y sale #include <stdio.h> int main(int argc, char **argv) { while (*argv != NULL) printf("%s\n", *argv++); return 0; }
C
#include <stdio.h> /*The problem: Given a Matrix of 0's and 1's, Find the size of the biggest square submatrix that conatins no 1's Sample input 1 0 0 0 0 0 0 0 0 0 output: 3 Sample input 2 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 output: 2 */ #define ROW 5 #define COLUMN 7 void input(int rows, int columns, int matrix[][columns]); void output(int rows, int columns, int matrix[][columns]); int biggestSquare(int rows, int columns,int matrix[][columns]); int helper(int rows,int columns, int startRow, int startCol, int matrix[][columns]); /* biggestSquare function will figure out the larget squre of 0's helper function will help the biggestSquare function to determiine the largest square of zeros */ int main(int argc,char**argv) { int matrix[ROW][COLUMN]; input(ROW,COLUMN,matrix); output(ROW,COLUMN,matrix); printf("Largest square of 0's is: %i\n",biggestSquare(ROW,COLUMN,matrix)); return 0; } void input(int rows, int columns, int matrix[][columns]) { int i,j; //Scanning forinput below //This does not check if the user input is a valid integer or 1/0 for(i=0;i<ROW; i++) { for(j=0;j<COLUMN;j++) { printf("Please input [%i][%i]: ",i,j); scanf("%i",&matrix[i][j]); } } printf("\n"); } void output(int rows, int columns, int matrix[][columns]) { int i,j; for(i=0;i<ROW; i++) { for(j=0;j<COLUMN;j++) { printf("%i ",matrix[i][j]); } printf("\n"); } } int biggestSquare(int rows, int columns,int matrix[][columns]) { int i,j, potMax; int max = 0; //assuming max dimension of square is 0 for(i = 0; i<rows; i++) { for(j = 0; j<columns; j++) { if(matrix[i][j] == 0) { potMax = helper(rows,columns, i,j, matrix); if(max < potMax ) max = potMax; } } } return max; } int helper(int rows,int columns, int startRow, int startCol, int matrix[][columns]) { int count = 1; //will keep track of dimention of largest square //we will initialize to 1 since if we enter this function, you have detected // a 1 int i,j; // below for loop counts the dimension of the potential square for(i = startRow + 1, j=startCol+1; i<rows && j<columns; i++, j++) { //checks to see if both symetrical horizontal and vertical are 0 //keeps track of dimension of square in counter variable if(matrix[startRow][j]==0 && matrix[i][startCol]==0) count++; else break; } //below for loop checks the inner potential square for(i = startRow + 1; i<count + startRow; i++) { for(j = startCol + 1; j<count + startCol; j++) { //this is when you encounter a 1 in your matrix if(matrix[i][j] != 0) { count = j -1; } } } return count; }
C
#include "jit/ir/passes/pass_stat.h" #include "core/assert.h" #include "core/math.h" #include "core/string.h" static struct list s_stats; void pass_stat_register(struct pass_stat *stat) { list_add(&s_stats, &stat->it); } void pass_stat_unregister(struct pass_stat *stat) { list_remove(&s_stats, &stat->it); } void pass_stat_print_all() { LOG_INFO("===-----------------------------------------------------==="); LOG_INFO("Pass stats"); LOG_INFO("===-----------------------------------------------------==="); int w = 0; list_for_each_entry(stat, &s_stats, struct pass_stat, it) { int l = (int)strlen(stat->desc); w = MAX(l, w); } list_for_each_entry(stat, &s_stats, struct pass_stat, it) { LOG_INFO("%-*s %d", w, stat->desc, stat->n); } }
C
#include <stdio.h> #include <stdlib.h> #include "listDin.h" int main() { ListDin l1,l2,l3; IdxType val; ElType min, max,idx; CreateListDin(&l1,5); CreateListDin(&l2,5); displayList(l1); printf("\n"); printf("bikin list 1:\n"); printf("\n"); readList(&l1); displayList(l1); printf("\n"); printf("bikin list 1:\n"); readList(&l2); displayList(l2); printf("\n"); printf("panjangnya %d\n", length(l1)); if (isEmpty(l1)) { printf("list kosong\n"); } else if (!isEmpty(l1)) { printf("list gak kosong\n"); } if (isFull(l1)) { printf("list penuh\n"); } else if (!isFull(l1)) { printf("list gak penuh\n"); } idx= getLastIdx(l1); printf("last element l1:\n"); printf("%d",ELMT(l1,idx)); if(isIdxValid(l1, 7)){ printf("l1 index 7 valid\n"); } if(isIdxValid(l1, 4)){ printf("l1 index 4 valid\n"); } if(isIdxValid(l1, 7)){ printf("l1 index 7 efektif\n"); } if(isIdxValid(l1, 4)){ printf("l1 index 4 efektif\n"); } displayList(plusMinusList(l1,l2,true)); printf("\n"); displayList(plusMinusList(l1,l2,false)); printf("\n"); if(isListEqual(l1,l2)){ printf("kedua list sama\n"); } if(!isListEqual(l1,l2)){ printf("kedua list tidak sama\n"); } printf("cari elemen apa?\n"); scanf("%d",&val); printf("%d ada di index %d",val, indexOf(l1,val)); extremes(l1,&max,&min); printf("max: %d\nmin:%d",max,min); copyList(l1,&l3); displayList(l3); printf("\n"); printf("ditotalin jadi: %d\n", sumList(l1)); printf("nilai apa yang mau dicari muncul berapa kali?\n"); scanf("%d",&val); printf("%d muncul %d kali\n", val,countVal(l1,val)); if (isAllEven(l1)) { printf("l1 genap semua\n"); } if (!isAllEven(l1)) { printf("l1 gak genap semua\n"); } printf("l1 abis disort ascending jadi:\n"); sort(&l1,true); displayList(l1); printf("\n"); printf("l1 abis disort descending jadi:\n"); sort(&l1,false); displayList(l1); printf("\n"); printf("mau berapa yang ditambahin?\n"); scanf("%d",&val); growList(&l1,1); insertLast(&l1, val); displayList(l1); printf("\n"); deleteLast(&l1,&val); displayList(l1); printf("\n"); shrinkList(&l1,1); growList(&l1, 10); printf("kapasitas %d",CAPACITY(l1)); shrinkList(&l1, 5); printf("kapasitas %d",CAPACITY(l1)); compactList(&l1); printf("kapasitas %d",CAPACITY(l1)); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <math.h> #define TASCII_SIZE 128 enum { PROG_NAME, K_PARAM, OBS_NUM, TEST_NAME, DATA_NAME, ARG_NUM }; long double euclid_dis(unsigned int obs_num, long double *argsA, long double *argsB){ long double dis = 0; #ifdef DEBUG for(int i = 0; i < obs_num; printf("%LF/%LF\n", *(argsA + i), *(argsB + i)), ++i); #endif while(0 < obs_num--) dis += pow(*(argsA + obs_num) - *(argsB + obs_num), 2); dis = pow(dis, 0.5); return dis; }; static void rec_qck(long double *vector, long double **vaux, char *vecaux, int start, int end){ int i = start, j = end; long double pivot = *(vector + (i + j)/2), aux; long double *aux2; char aux3; while(j >= i){ while(i <= end && *(vector + i) < pivot) ++i; while(j >= start && *(vector + j) > pivot) --j; if (j >= i){ aux = *(vector + i); *(vector + i) = *(vector + j); *(vector + j) = aux; aux2 = *(vaux + i); *(vaux + i) = *(vaux + j); *(vaux + j) = aux2; aux3 = *(vecaux + i); *(vecaux + i) = *(vecaux + j); *(vecaux + j) = aux3; ++i; --j; } } if (i < end) rec_qck(vector, vaux, vecaux, i, end); if (j > start) rec_qck(vector, vaux, vecaux, start, j); }; void qckSort(void *vector, long double **vaux, char *aux, size_t size){ rec_qck((long double *) vector, vaux, aux, 0, size - 1); }; long double **get_data(FILE *fdata, char **labels, size_t *dt_size, unsigned int obs_num){ long double **dt_matrix = NULL; while(!feof(fdata)){ dt_matrix = realloc(dt_matrix, sizeof(long double *) * (1 + *dt_size)); *labels = realloc(*labels, sizeof(char *) * (1 + *dt_size)); *(*dt_size + dt_matrix) = malloc(sizeof(long double) * obs_num); for(unsigned int i = obs_num; i > 0; --i) fscanf(fdata, "%LF", (*(*dt_size + dt_matrix) + i - 1)); fscanf(fdata, "%*c%c", (*labels + *dt_size)); #ifdef DEBUG printf("TEST; %c\n", *(*labels + *dt_size)); #endif ++(*dt_size); }; return dt_matrix; }; #ifdef DEBUG void print_data(long double **data, unsigned int rows, unsigned int obs_num){ for(unsigned int k = 0; k < rows; printf("\n"), ++k) for(unsigned int l = 0; l < obs_num; printf("%LF ", *(*(data + k) + l)), ++l); } #endif void destroy_data(long double **data, unsigned int rows){ while(0 < rows--) free(*(data + rows)); free(data); }; void knn (unsigned int K, FILE *finput, FILE *fdata, unsigned int obs_num){ size_t dt_size = 0; char *labels = NULL, res_label = 0; long double **dt_matrix = get_data(fdata, &labels, &dt_size, obs_num), *distances = malloc(sizeof(long double) * dt_size), *obs = malloc(sizeof(long double) * obs_num); unsigned int *freqs = malloc(sizeof(unsigned int) * TASCII_SIZE), i, freq_major = 0; while(!feof(finput)){ for(i = 0; i < TASCII_SIZE; *(freqs + i++) = 0); //Load all data from fdata in a matrix k //begin repeat until feof(finput)k //Get one single case from finput k //calculate all euclid_dis from this case to the data from fdata and store in a vector //Sort the vector //Get the K first results and do a mean //Print mean and repeat. //print_data(dt_matrix, dt_size, obs_num); for(i = obs_num; i > 0; --i) fscanf(finput, "%LF", (obs + i - 1)); for(i = dt_size; i > 0; *(distances + i - 1) = euclid_dis(obs_num, obs, *(dt_matrix + i - 1)), --i); qckSort(distances, dt_matrix, labels, dt_size); for(i = 0; i < K; ++(*(freqs + *(labels + i++)))); for(i = 0; i < TASCII_SIZE; ++i){ if (*(freqs + i) > freq_major){ res_label = (char) i; freq_major = *(freqs + i); } } printf("class: %c\n", res_label); freq_major = 0; res_label = 0; }; free(obs); free(freqs); free(labels); free(distances); destroy_data(dt_matrix, dt_size); }; int main(int argc, char const *argv[]){ extern int errno; if (argc == ARG_NUM && OBS_NUM > 0 && K_PARAM > 0){ FILE *finput = fopen(*(TEST_NAME + argv), "r"); if (finput != NULL){ FILE *fdata = fopen(*(DATA_NAME + argv), "r"); if (fdata != NULL){ knn(atol(*(K_PARAM + argv)),finput, fdata, atol(argv[OBS_NUM])); fclose(finput); fclose(fdata); return 0; } fclose(finput); printf("E#%hd with \"%s\": %s\n", errno, *(DATA_NAME + argv), strerror(errno)); return errno; } printf("E#%hd with \"%s\": %s\n", errno, *(TEST_NAME + argv), strerror(errno)); return errno; }; printf("usage: %s <K> <obs num> <test path> <data path>\n", *(PROG_NAME + argv)); return 1; };
C
#include "urg_ctrl.h" #include "math_utils.h" #include <stdio.h> #include <stdlib.h> static void urg_exit(urg_t *urg, const char *message) { printf("%s: %s\n", message, urg_error(urg)); urg_disconnect(urg); #ifdef MSC getchar(); #endif exit(1); } int main(int argc, char *argv[]) { //const char device[] = "COM3"; /* Example for Windows */ const char device[] = "/dev/ttyACM0"; /* Example for Linux */ int ret = 0; int n; int i; /* Connection */ urg_t urg; ret = urg_connect(&urg, device, 115200); if (ret < 0) { urg_exit(&urg, "urg_connect()"); } /* Outputs the angle of each index */ n = urg_dataMax(&urg); for (i = 0; i < n; i += 8) { double radian = urg_index2rad(&urg, i); int degree = urg_index2deg(&urg, i); printf("%03d, %d [deg], %.1f [rad], %d, %d\n", i, degree, radian, urg_deg2index(&urg, degree), urg_rad2index(&urg, radian)); } return 0; }
C
#include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<string.h> #define BUFSIZE 1024 int cout(int line, char buf[]) { int n=0; int cout = 0; for(int i =0; i<strlen(buf); i++) { cout ++; if(n == line) break; if(buf[i] == '\n') n ++; } return cout; } int main(int argc, char** argv) { char buf[BUFSIZE]; int fd1 = 0; int fd2 = 0; int n = 0; int line = 0; int cout1 = 0; int cout2 = 0; int offset1 = 0; int offset2 = 0; fd1 = open(argv[1], O_RDONLY); fd2 = open(argv[1], O_RDWR); // 获取整个文件 while(1) { n = read(fd1, buf, BUFSIZE); if(n <= 0) break; } cout1 = cout(3, buf); cout2 = cout(2, buf); // 定位到fd1的第3行 offset1 = lseek(fd1, cout1, SEEK_SET); // 定位到fd2的第2行 offset2 = lseek(fd2, cout2, SEEK_SET); char buf1[BUFSIZE]; int pos,ret; // 读取fd1写入到fd2 while(1) { n = read(fd1, buf1, BUFSIZE); if(n<=0) break; pos = 0; while(n > 0) { ret = write(fd2, buf1+pos, n); if(ret < 0) { perror("write()"); exit(1); } n-=ret; pos+=ret; } } close(fd2); close(fd1); exit(0); }
C
#include<stdio.h> int main (void) { int value=0; float factorial=1 ; int i , x, multi_x; float sum=1 ; printf("Please Enter a Value:") ; scanf("%d" , &value ) ; printf("Please Enter a 'X' Value:") ; scanf("%d" , &x ) ; multi_x=x; if(value!=0) { for (i=1; i<=value ;i++ ) { factorial*= i; sum+= multi_x/factorial; multi_x*=x; } printf("e^x is %f\n" , sum) ; } else { factorial=1; sum+= 1/factorial; printf(" e is %f\n" , sum) ; } return 0 ; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <string.h> #define FALSE 0 #define TRUE 1 typedef struct { char name[10]; int age; float salary; } humanBeing; int humansEqual(humanBeing, humanBeing); int main() { humanBeing persona1, persona2; struct { char name[10]; int age; float salary; } person; strcpy(person.name, "piero"); person.age = 25; person.salary = 500.20; strcpy(persona1.name, "jhonatan"); persona1.age = 26; persona1.salary = 500; strcpy(persona2.name, "jhonatan"); persona2.age = 26; persona2.salary = 50; printf(" nombre: %s \n edad: %d \n",person.name, person.age); printf("\n"); printf(" nombre: %s \n edad: %d \n",persona1.name, persona1.age); printf("\n"); if(strcmp(persona1.name, persona2.name)) printf("las dos personas tienen el nombre diferente \n"); else printf("las dos personas tienen el mismo nombre \n"); if(humansEqual(persona1, persona2)) printf("las dos personas son la misma \n"); else printf("las dos personas son diferentes \n"); return 0; } int humansEqual(humanBeing person1, humanBeing person2) { if(strcmp(person1.name, person2.name)) return FALSE; if(person1.age != person2.age) return FALSE; if(person1.salary != person2.salary) return FALSE; return TRUE; }
C
#include <stdio.h> #include "Task3.h" void printPascalTriangle(int depth) { int n; int k; int i; long long term; for (n = 0; n<depth; n++) { printf("|L%2d|", n); for (i = n; i <= depth; i++) { printf("%3c", ' '); } for (k = 0; k <= n; k++) { term = pascalTriangle(n, k); printf("%6lld", term); } printf("\n"); } } long long pascalTriangle(int n, int k) { if ((n == 0) || (k == 0) || (k == n)) { return 1; } return pascalTriangle(n - 1, k - 1) + pascalTriangle(n - 1, k); }
C
/* Disciplina: Computacao Concorrente */ /* Prof.: Silvana Rossetto */ /* Codigo: Projetar e implementar um algoritmo concorrente para o problema de multiplicação de matrizes e coletar informações sobre o seu tempo de execucão*/ #include<stdio.h> #include<stdlib.h> #include"timer.h" #include<pthread.h> float *matrizPrincipal; //primeira matriz float *matrizAuxiliar; //segunda matriz float *saida; //matriz de saida float *checar; //checar se a multiplicação ta certa int nthreads; //numero de threads typedef struct{ //definir struct int id; // identificador do elemento que a thread vai processar int dim; // dimensao das estruturas de entrada }tArgs; /*Funcao que as threads irao executar */ void* tarefa(void *arg){ tArgs *args = (tArgs*) arg; for(int i=args->id;i<args->dim;i+=nthreads){ for(int j=0; j<args->dim;j++){ for(int k=0;k<args->dim;k++){ saida[i*args->dim+j]+=matrizPrincipal[i*args->dim+k]*matrizAuxiliar[k*args->dim+j]; } } } pthread_exit(NULL); } /*Fluxo principal*/ int main(int argc, char*argv[]){ int dim; //dimensao da matriz de entrada pthread_t *tid; //identificadores das threads no sistema tArgs *args; //identificadores locais das threads e dimensao int i; int j; double begin; double end; double duration; GET_TIME(begin); /*Etapa de leitura e avaliacao dos parametros de entrada*/ if(argc<3){ //<3 pq um será a o arg passado na hora de pedir pra compilar no ./ outro da dim e outro do numero de thread. printf("Quantidade de parâmetros insuficiente. Digite: %s <dimensao da matriz> \n ", argv[0]); return 1; } dim=atoi(argv[1]); //funcao atoi transforma string pra inteiro nthreads = atoi(argv[2]); if(nthreads>dim) nthreads=dim; /*Etapa de alocacao de memoria para as estruturas de dados*/ matrizPrincipal=(float*) malloc(sizeof(float)*dim*dim); /* - malloc armazena uma quantidade de bytes no primeiro espaço de memória que dê para esses bytes estarem alocados de forma contínua na memória - malloc retorna ponteiro pra void, por isso faz um typecast para float [(float*)] - sizeof é o tipo que será usado */ if(matrizPrincipal==NULL){ //caso o malloc não ache o espaço ele retorna NULL printf("Erro --malloc\n"); return 2; } matrizAuxiliar= (float*) malloc(sizeof(float)*dim*dim); if(matrizAuxiliar==NULL){ printf("Erro --malloc\n"); return 2; } saida= (float*) malloc(sizeof(float)*dim*dim); if(saida==NULL){ printf("Erro --malloc\n"); return 2; } for(i=0;i<dim;i++){ for(j=0;j<dim;j++){ //na primeira vez que passar aqui vai estar atuando somente na primeira linha da matriz matrizPrincipal[i*dim+j]=i+j; matrizAuxiliar[i*dim+j]=j; saida[i*dim+j]=0; } } GET_TIME(end); duration = end-begin; printf("Duracao de inicializacao: %lf\n", duration); /*Etapa de multiplicacao da matriz pelo vetor */ GET_TIME(begin); /*Etapa de alocacao das estruturas*/ tid=(pthread_t*)malloc(sizeof(pthread_t)*nthreads); if(tid==NULL) { puts("Erro"); return 2; } args = (tArgs*) malloc(sizeof(tArgs)*nthreads); if(args==NULL) { puts("Erro"); return 2; } /*Etapa de criacao das threads*/ for(int i =0; i<nthreads;i++){ (args+i)->id=i; (args+i)->dim=dim; if(pthread_create(tid+i,NULL,tarefa,(void*)(args+i))){ puts("Erro--pthread_create"); return 3; } } /*Etapa de espera pelo termino das threads*/ for(int i=0;i<nthreads;i++){ pthread_join(*(tid+i),NULL); } GET_TIME(end); //finaliza a contagem do tempo duration = end-begin; //calcula a duracao printf("Duracao da multiplicacao: %lf\n", duration); checar= (float*) malloc(sizeof(float)*dim*dim); //alocando e inicializando a matriz de verificacao, para nao haver interferencia if(checar==NULL){ puts("Erro"); return 2; } for(i=0;i<dim;i++){ for(j=0;j<dim;j++){ checar[i*dim+j]=0; } } for( i=0;i<dim;i++){ for( j=0;j<dim;j++){ for(int k=0;k<dim;k++){ checar[i*dim+j]+=matrizPrincipal[i*dim+k]*matrizAuxiliar[k*dim+j]; } } } /*Etapa de Verificacao de erros */ int aux=0; for( i=0;i<dim;i++){ for( j=0;j<dim;j++){ if(checar[i*dim+j]!=saida[i*dim+j]) aux+=1; } } if(aux==0){ puts("Sem erros"); } else{ puts("Erro durante a execucao"); } /*Etapa de liberacao de memoria */ free(matrizPrincipal); free(matrizAuxiliar); free(saida); free(args); free(tid); free(checar); GET_TIME(begin); GET_TIME(end); duration=end-begin; printf("Duracao da finalizacao: %lf\n", duration); return 0; } /*ANEXO*/ /*Etapa de exibicao dos resultados.*/ /*ESTA ETAPA FICARÁ COMENTADO POIS TRABALHAREMOS COM MATRIZES GRANDES */ /*for(i=0;i<dim;i++){ for(j=0;j<dim;j++){ printf("%.1f",matrizPrincipal[i*dim+j]); } printf("\n"); } printf("\n"); for(i=0;i<dim;i++){ for(j=0;j<dim;j++){ printf("%.1f",matrizAuxiliar[i*dim+j]); } printf("\n"); } printf("\n"); for( i=0;i<dim;i++){ for( j=0;j<dim;j++){ printf("%.1f",saida[i*dim+j]); } printf("\n"); } printf("\n"); for(i=0;i<dim;i++){ for(j=0;j<dim;j++){ printf("%.1f",checar[i*dim+j]); } printf("\n"); } printf("\n"); */
C
#include<stdio.h> #include<string.h> int *s; int *e; int *c; int ans[49]; int inline scan() { int N = 0; char C; C=getchar_unlocked(); while (C < '0' || C>'9') C=getchar_unlocked(); while (C >= '0' && C <= '9') { N = (N<<3) + (N<<1) + C - '0'; C=getchar(); } return N; } int main() { int t,i,n,j,k; t=scan(); for(i=0;i<t;i++) { memset(ans,0,sizeof(ans)); n=scan(); s=calloc(n,sizeof(int)); e=calloc(n,sizeof(int)); c=calloc(n,sizeof(int)); for(j=0;j<n;j++) { s[j]=scan(); e[j]=scan(); c[j]=scan(); } for(j=1;j<49;j++) { for(k=0;k<n;k++) { if(e[k]<=j && ans[j]<(ans[s[k]]+c[k])) ans[j]=ans[s[k]]+c[k]; } } printf("%d\n",ans[48]); } return 0; }
C
/* * Project name: PWM (PWM library Demonstration) * Copyright: (c) Mikroelektronika, 2008. * Revision History: 20081218: - initial release; * Description: This is a simple demonstration of PWM library, which is being used for control of the MCU's PWM module. The module is initialized and started, after which the PWM1 ans PWM2 Duty Ratios can be adjusted by means of 4 buttons connected to pins RA0, RA1, RA2 and RA3. The changes can be monitored on the PWM output pins. * Test configuration: MCU: PIC18F87J60 http://ww1.microchip.com/downloads/en/DeviceDoc/39762d.pdf Dev.Board: EasyPIC PRO v7 http://www.mikroe.com/easypic-pro/ Oscillator: HS, 25.0000 MHz Ext. Modules: - SW: mikroC PRO for PIC http://www.mikroe.com/mikroc/pic/ * NOTES: - Connect button jumper (J12) to Vcc and pull-down PORTA (place jumper J1 in lower position). (board specific) - Turn on LEDs on PORTC switch SW10.3. (board specific) */ unsigned short current_duty1, old_duty1, current_duty2, old_duty2; void InitMain() { ADCON1 |= 0x0F; // Configure AN pins as digital CMCON |= 7; // Disable comparators PORTA = 0; TRISA = 255; // configure PORTA pins as input PWM1_Init(5000); // Initialize PWM1 module at 5KHz PWM2_Init(5000); // Initialize PWM2 module at 5KHz } void main() { InitMain(); current_duty1 = 127; // initial value for current_duty1 current_duty2 = 127; // initial value for current_duty2 PWM1_Start(); // start PWM1 PWM2_Start(); // start PWM2 PWM1_Set_Duty(current_duty1); // Set current duty for PWM1 PWM2_Set_Duty(current_duty2); // Set current duty for PWM2 while (1) { // endless loop if (RA0_bit) { // button on RA0 pressed current_duty1--; // decrement current_duty1 PWM1_Set_Duty(current_duty1); } if (RA1_bit) { // button on RA1 pressed current_duty1++; // increment current_duty1 PWM1_Set_Duty(current_duty1); } if (RA2_bit) { // button on RA2 pressed current_duty2--; // decrement current_duty2 PWM2_Set_Duty(current_duty2); } if (RA3_bit) { // button on RA3 pressed current_duty2++; // increment current_duty2 PWM2_Set_Duty(current_duty2); } Delay_ms(5); // slow down change pace a little } }
C
#define _GNU_SOURCE #include <errno.h> #include <net/if.h> #include <stdio.h> #include <string.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <unistd.h> unsigned if_nametoindex(const char* name) { struct ifreq ifr; int fd, r; if ((fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0) { return 0; } strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); r = ioctl(fd, SIOCGIFINDEX, &ifr); int saved_errno = errno; if (close(fd) == -1) { fprintf(stderr, "if_nametoindex failed to close fd: %s\n", strerror(errno)); } errno = saved_errno; return r < 0 ? 0 : ifr.ifr_ifindex; }
C
#include <stdio.h> #include <string.h> int addr_space = 24; int block_size; int num_sets; int assoc; char write_policy; int cache_size; int num_blocks; int tag; int offset; int index; /* Will process and output all flags */ void GetFlags(int argc, char *argv[]) { if (argc == 1) { block_size = 32; num_sets = 64; assoc = 1; write_policy = 't'; } while ((argc > 1) && (argv[1][0] == '-')) { switch (argv[1][1]) { case 'b': block_size = atoi(&argv[1][3]); break; case 's': num_sets = atoi(&argv[1][3]); break; case 'a': assoc = atoi(&argv[1][3]); break; case 'W': write_policy = argv[1][3]; break; default: printf("Wrong Argument: %s\n", argv[1]); } argv += 2; argc -= 2; } } /* Prints header information for cache */ void PrintHeader() { int offset = block_size; int index = num_sets; int counter = 0; /* Log base 2 of block_size to find offset */ while (offset >>= 1) { counter++; } offset = counter; counter = 0; /* Log base 2 of num_sets to find index */ while (index >>= 1) { counter++; } index = counter; int tag = addr_space - offset - index; cache_size = (num_sets * block_size * assoc) / 1024; num_blocks = num_sets * assoc; int extra_space = (num_blocks * tag) / 8; double percentage = ((double)extra_space / (cache_size * 1024)) * 100; printf("%dKB %d-way associative cache:\n", cache_size, assoc); printf("%2s Block size = %d bytes\n", "", block_size); printf("%2s Number of [sets,blocks] = [%d,%d]\n", "", num_sets, num_blocks); printf("%2s Extra space for tag storage = %d bytes (%1.4g%)\n", "", extra_space, percentage); printf("%2s Bits for [tag,index,offset] = [%d, %d, %d] = %d\n", "", tag, index, offset, tag+index+offset); if (write_policy == 'b') printf("%2s Write policy = %s\n", "", "Write-back"); else printf("%2s Write policy = %s\n", "", "Write-through"); printf("\n"); printf("%-7s %-36s %-5s %s %19s\n", "Hex", "Binary Address", "Set", "Blk", "Memory"); printf("%-7s %-31s %s %s %4s %4s %-4s %-4s %-4s\n", "Address", "(tag/index/offset)", "Tag", "Index", "off", "Way", "UWay", "Read", "Writ"); printf("%-7s %s %s %s %4s %4s %-4s %-4s %-4s\n", "=======", "==========================", "========", "=====", "===", "====", "====", "====", "===="); } void HexToBin(char hex[], int hexc, char *bin[]) { int i = 0; while (i != hexc) { switch (hex[i]) { case '0': bin[i] = "0000"; break; case '1': bin[i] = "0001"; break; case '2': bin[i] = "0010"; break; case '3': bin[i] = "0011"; break; case '4': bin[i] = "0100"; break; case '5': bin[i] = "0101"; break; case '6': bin[i] = "0110"; break; case '7': bin[i] = "0111"; break; case '8': bin[i] = "1000"; break; case '9': bin[i] = "1001"; break; case 'a': bin[i] = "1010"; break; case 'b': bin[i] = "1011"; break; case 'c': bin[i] = "1100"; break; case 'd': bin[i] = "1101"; break; case 'e': bin[i] = "1110"; break; case 'f': bin[i] = "1111"; break; default: break; } //printf("%s\n", bin[i]); i++; } bin[5] = "\0"; } int main(int argc, char *argv[]) { GetFlags(argc, argv); PrintHeader(); char hex[6]; char *bin[6]; hex[0] = '0'; hex[1] = 'c'; hex[2] = '0'; hex[3] = 'e'; hex[4] = '7'; hex[5] = '\0'; int hexc = sizeof(hex); printf("%s", hex); HexToBin(hex, hexc, bin); char *str = bin[0]; char *newstr; newstr = malloc(strlen(str)+1+4); strcpy(newstr, str); int i = 1; printf("%7s", bin[0]); //for (i; i < hexc; i++) // printf("%s", bin[i]); //printf("\n"); char *str = bin[0]; char *newstr; newstr = malloc(strlen(str)+1+4); strcpy(newstr, str); for (i=1; i < hexc; i++) strcat(newstr, bin[i]); for (i = 0; i < addr_space; i++) { printf("%c", newstr[i]); //printf("i=%d\n", i); if (i == 8 || i == 14 ) printf(" "); } printf("\n"); return 0; }
C
/* * File: LAB8.c * Author: Jos Santizo * * Creado el 4 de octubre de 2021 * * Descripcin: Contadores que aumentan por medio de una entrada analgica (pots) */ //---------------------Bits de configuracin------------------------------- // CONFIG1 #pragma config FOSC = INTRC_NOCLKOUT// Oscillator Selection bits (INTOSCIO oscillator: I/O function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN) #pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled and can be enabled by SWDTEN bit of the WDTCON register) #pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled) #pragma config MCLRE = OFF // RE3/MCLR pin function select bit (RE3/MCLR pin function is digital input, MCLR internally tied to VDD) #pragma config CP = OFF // Code Protection bit (Program memory code protection is disabled) #pragma config CPD = OFF // Data Code Protection bit (Data memory code protection is disabled) #pragma config BOREN = OFF // Brown Out Reset Selection bits (BOR disabled) #pragma config IESO = OFF // Internal External Switchover bit (Internal/External Switchover mode is disabled) #pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is disabled) #pragma config LVP = OFF // Low Voltage Programming Enable bit (RB3 pin has digital I/O, HV on MCLR must be used for programming) // CONFIG2 #pragma config BOR4V = BOR40V // Brown-out Reset Selection bit (Brown-out Reset set to 4.0V) #pragma config WRT = OFF // Flash Program Memory Self Write Enable bits (Write protection off) // #pragma config statements should precede project file includes. // Use project enums instead of #define for ON and OFF. //-----------------Libreras utilizadas en cdigo-------------------- #include <xc.h> #include <stdint.h> #include <stdio.h> //-----------------Definicin de frecuencia de cristal--------------- #define _XTAL_FREQ 4000000 //-----------------------Constantes---------------------------------- #define valor_tmr0 237 // valor_tmr0 = 237 //-----------------------Variables------------------------------------ int cont2 = 0; int cont_vol = 0; uint8_t digi = 0; uint8_t disp_selector = 0b001; int dig[3]; //------------Funciones sin retorno de variables---------------------- void setup(void); // Funcin de setup void divisor(void); // Funcin para dividir nmeros en dgitos void tmr0(void); // Funcin para reiniciar TMR0 void displays(void); // Funcin para alternar valores mostrados en displays //-------------Funciones que retornan variables----------------------- int tabla(int a); // Tabla para traducir valores a displays de 7 segmentos int tabla_p(int a); // Tabla que traduce valores a displays de 7 segmentos pero con punto decimal incluido //----------------------Interrupciones-------------------------------- void __interrupt() isr(void){ if(PIR1bits.ADIF){ if(ADCON0bits.CHS == 1){ // Si el channel es 1 (puerto AN1) cont_vol = 2*ADRESH; // Valor analgico traducido = cont_vol divisor(); // Llamar subrutina de divisor } else{ PORTC = ADRESH; // Si channel select = 0 } // entonces asignar PORTC = ADRESH PIR1bits.ADIF = 0; // Limpiar bander de interrupcin ADC } if(T0IF){ tmr0(); // Mostrar displays en interrupcin de Timer 0 displays(); } } //----------------------Main Loop-------------------------------- void main(void) { setup(); // Subrutina de setup ADCON0bits.GO = 1; // Comenzar conversin ADC while(1){ if(ADCON0bits.GO == 0){ // Si bit GO = 0 if(ADCON0bits.CHS == 1){ // Si Input Channel = AN1 ADCON0bits.CHS = 0; // Asignar input Channel = AN0 __delay_us(50); // Delay de 50 ms } else{ // Si Input Channel = AN0 ADCON0bits.CHS = 1; // Asignar Input Channel = AN1 __delay_us(50); } __delay_us(50); ADCON0bits.GO = 1; // Asignar bit GO = 1 } } } //----------------------Subrutinas-------------------------------- void setup(void){ //Configuracin de entradas y salidas ANSEL = 0b00000011; // Pines 0 y 1 de PORTA como analgicos ANSELH = 0; TRISA = 0b00000011; // PORTA, bit 0 y 1 como entrada analgica TRISC = 0; // PORTC como salida TRISD = 0; // PORTD como salida TRISE = 0; // PORTE como salida PORTA = 0; // Limpiar PORTA PORTD = 0; // Limpiar PORTD PORTC = 0; // Limpiar PORTC PORTE = 0; // Limpiar PORTE //Configuracin de oscilador OSCCONbits.IRCF = 0b0110; // Oscilador a 4 MHz = 110 OSCCONbits.SCS = 1; //Configuracin de TMR0 OPTION_REGbits.T0CS = 0; // bit 5 TMR0 Clock Source Select bit...0 = Internal Clock (CLKO) 1 = Transition on T0CKI pin OPTION_REGbits.T0SE = 0; // bit 4 TMR0 Source Edge Select bit 0 = low/high 1 = high/low OPTION_REGbits.PSA = 0; // bit 3 Prescaler Assignment bit...0 = Prescaler is assigned to the Timer0 OPTION_REGbits.PS2 = 1; // bits 2-0 PS2:PS0: Prescaler Rate Select bits OPTION_REGbits.PS1 = 1; OPTION_REGbits.PS0 = 1; TMR0 = valor_tmr0; // preset for timer register //Configuracin del ADC ADCON1bits.ADFM = 0; // Resultado justificado a la izquierda ADCON1bits.VCFG0 = 0; // Voltaje 0 de referencia = VSS ADCON1bits.VCFG1 = 0; // Voltaje 1 de referencia = VDD ADCON0bits.ADCS = 0b01; // Conversin ADC generada a 2us ADCON0bits.CHS = 0; // Input Channel = AN0 ADCON0bits.ADON = 1; // ADC = enabled __delay_us(50); //Configuracin de interrupciones INTCONbits.T0IF = 0; // Habilitada la bandera de TIMER 0 INTCONbits.T0IE = 1; // Habilitar las interrupciones de TIMER 0 INTCONbits.GIE = 1; // Habilitar interrupciones globales PIR1bits.ADIF = 0; // Limpiar bandera de interrupcin del ADC PIE1bits.ADIE = 1; // Interrupcin ADC = enabled INTCONbits.PEIE = 1; // Interrupciones perifricas activadas return; } void tmr0(void){ INTCONbits.T0IF = 0; // Limpiar bandera de TIMER 0 TMR0 = valor_tmr0; // TMR0 = 237 return; } void divisor(void){ for(int i = 0; i<3 ; i++){ // De i = 0 hasta i = 2 dig[i] = cont_vol % 10; // array[i] = cont_vol mod 10(retornar residuo). Devuelve digito por dgito de un nmero. cont_vol = (cont_vol - dig[i])/10; // cont_vol = valor sin ltimo digito. } } void displays(void){ PORTE = disp_selector; // PORTE = 0b001 if(disp_selector == 0b001){ // Si disp_selector = 0b001 PORTD = tabla(dig[0]); // PORTD = valor traducido de posicin 0 de array dig[] disp_selector = 0b010; // disp_selector = 0b010 } else if(disp_selector == 0b010){ // Si disp_selector = 0b010 PORTD = tabla(dig[1]); // PORTD = valor traducido de posicin 1 de array dig[] disp_selector = 0b100; // disp_selector = 0b100 } else if(disp_selector == 0b100){ // Si disp_selector = 0b100 PORTD = tabla_p(dig[2]); // PORTD = valor traducido de posicin 2 de array dig[] disp_selector = 0b001; // disp_selector = 0b001 } } int tabla(int a){ switch (a){ // Ingresar valor de "a" a switch case case 0: // Si a = 0 return 0b00111111; // devolver valor 0b00111111 break; case 1: // Si a = 1 return 0b00000110; // devolver valor 0b00000110 break; case 2: // Si a = 2 return 0b01011011; // devolver valor 0b01011011 break; case 3: // Si a = 3 return 0b01001111; // devolver valor 0b01001111 break; case 4: // Si a = 4 return 0b01100110; // devolver valor 0b01100110 break; case 5: // Si a = 5 return 0b01101101; // devolver valor 0b01101101 break; case 6: // Si a = 6 return 0b01111101; // devolver valor 0b01111101 break; case 7: // Si a = 7 return 0b00000111; // devolver valor 0b01111101 break; case 8: // Si a = 8 return 0b01111111; // devolver valor 0b01111111 break; case 9: // Si a = 9 return 0b01101111; // devolver valor 0b01101111 break; default: break; } } int tabla_p(int a){ switch (a){ // Ingresar valor de "a" a switch case case 0: // Si a = 0 return 0b10111111; // devolver valor 0b10111111 break; case 1: // Si a = 1 return 0b10000110; // devolver valor 0b10000110 break; case 2: // Si a = 2 return 0b11011011; // devolver valor 0b11011011 break; case 3: // Si a = 3 return 0b11001111; // devolver valor 0b11001111 break; case 4: // Si a = 4 return 0b11100110; // devolver valor 0b11100110 break; case 5: // Si a = 5 return 0b11101101; // devolver valor 0b11101101 break; case 6: // Si a = 6 return 0b11111101; // devolver valor 0b11111101 break; case 7: // Si a = 7 return 0b10000111; // devolver valor 0b11111101 break; case 8: // Si a = 8 return 0b11111111; // devolver valor 0b11111111 break; case 9: // Si a = 9 return 0b11101111; // devolver valor 0b11101111 break; default: break; } }
C
#include <stdlib.h> #include <stdio.h> #include <time.h> #include "transaction.h" #include "apriori.h" int main(int argc, char *argv[]) { clock_t begin = clock(); if (argc != 3) { printf("Usage: ./apriori <threshold> <num transactions>\n"); return EXIT_FAILURE; } int support_threshold = atoi(argv[1]); int num_transactions = atoi(argv[2]); printf("using support threshold %d\n", support_threshold); struct trans_list t_list = generate_trans_list(num_transactions); print_trans_list(t_list); struct occurr_table *o_table = malloc(sizeof(struct occurr_table)); // first run through will have 9 items (1,2,3,...,9) o_table->occurr = malloc(sizeof(struct occurrence) * 10); o_table->threshold = support_threshold; o_table->length = 10; for (int i = 0; i < 10; ++i) { o_table->occurr[i].item = malloc(sizeof(struct item)); // item sets will be size one at the start o_table->occurr[i].item->i = malloc(sizeof(int) * 1); o_table->occurr[i].item->i[0] = i; o_table->occurr[i].item->length = 1; } fill_occurrence_table(o_table, t_list); print_occurr_table(*o_table); while(1) { struct occurr_table *new_occurr_table = malloc(sizeof(struct occurr_table)); printf("next round\n"); int res = next_round(o_table, new_occurr_table); printf("fill table\n"); fill_occurrence_table(new_occurr_table, t_list); printf("print table\n"); print_occurr_table(*new_occurr_table); if (res == 0) { break; } o_table = new_occurr_table; } clock_t end = clock(); double runtime = (double)(end - begin) / CLOCKS_PER_SEC; printf("Runtime: %lfs\n", runtime / 1000); return EXIT_SUCCESS; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> struct node { int cof,exp; struct node *link; }; struct node *r=NULL,*r1=NULL,*r2=NULL; void display(struct node *,struct node *); struct node * insert1(int,int); void insertdisplay(struct node *); void mulpoly(struct node *,struct node *); struct node * insertion(int ,int ); void sort(struct node *); struct node * insert(int ,int ); struct node * addition(struct node *,struct node *); void insertadd(struct node *); void complete_mul(struct node *,struct node *,int,int); void main() { struct node *temp=NULL,*root=NULL,*p=NULL,*temp1=NULL,*root1=NULL,*p1=NULL; int n,m,i; printf("\n\nenter the size of first polynomial: "); scanf("%d",&n); printf("\n\n"); for(i=1;i<=n;i++) { temp=(struct node*)malloc(sizeof(struct node )); printf("enter the %d coefficient into first linked list: ",i); scanf("%d",&temp->cof); printf("enter the %d exponent into first linked list: ",i); scanf("%d",&temp->exp); printf("\n"); temp->link=NULL; if(root==NULL) { root=temp; } else{ p=root; while(p->link!=NULL) { p=p->link; } p->link=temp; } } printf("\n\nenter the size of second polynomial: "); scanf("%d",&m); printf("\n\n"); for(i=1;i<=m;i++) { temp1=(struct node*)malloc(sizeof(struct node )); printf("enter the %d coefficient into first linked list: ",i); scanf("%d",&temp1->cof); printf("enter the %d exponent into first linked list: ",i); scanf("%d",&temp1->exp); printf("\n"); temp1->link=NULL; if(root1==NULL) { root1=temp1; } else{ p1=root1; while(p1->link!=NULL) { p1=p1->link; } p1->link=temp1; } } display(root,root1); mulpoly(root,root1); complete_mul(root,root1,n,m); } void display(struct node *root,struct node *root1) { struct node *temp=NULL,*temp1=NULL; temp=root; temp1=root1; printf("\n\nfirst polynomial:\n\n"); while (temp->link!=NULL) { printf("%dx^%d ",temp->cof,temp->exp); temp=temp->link; } printf("%dx^%d",temp->cof,temp->exp); printf("\n\nsecond polynomial:\n\n"); while (temp1->link!=NULL) { printf("%dx^%d ",temp1->cof,temp1->exp); temp1=temp1->link; } printf("%dx^%d",temp1->cof,temp1->exp); } struct node * insert1(int a,int b) { struct node *temp=NULL,*p=NULL; temp=(struct node*)malloc(sizeof(struct node )); temp->cof=a; temp->exp=b; temp->link=NULL; if(r2==NULL) { r2=temp; } else{ p=r2; while(p->link!=NULL) { p=p->link; } p->link=temp; } return r2; } void mulpoly(struct node *root,struct node *root1) { struct node *temp=NULL,*temp1=NULL,*p=NULL; int a,b; temp=root; temp1=root1; while(temp1!=NULL) { while(temp!=NULL) { a=temp1->cof*temp->cof; b=temp1->exp+temp->exp; p=insert1(a,b); temp=temp->link; } temp=root; temp1=temp1->link; } insertdisplay(p); } void insertdisplay(struct node *root) { printf("\n\nAfter multiplying two polynomial:\n\n"); while (root!=NULL) { printf("%dx^%d ",root->cof,root->exp); root=root->link; } } struct node * insertion(int a,int b) { struct node *temp=NULL,*p=NULL; temp=(struct node*)malloc(sizeof(struct node )); temp->cof=a; temp->exp=b; temp->link=NULL; if(r1==NULL) { r1=temp; } else{ p=r1; while(p->link!=NULL) { p=p->link; } p->link=temp; } return r1; } void sort(struct node *root) { struct node *temp=NULL,*p=NULL,*q=NULL; int i,j,temp1,temp11,temp2,temp22; p=root; q=root; while(p!=NULL) { temp=p; while(temp!=NULL) { temp1=p->exp; temp2=temp->exp; if(temp1<temp2) { temp11=p->cof; p->cof=temp->cof; temp->cof=temp11; temp->exp=temp1; p->exp=temp2; } temp=temp->link; } p=p->link; } } struct node * insert(int a,int b) { struct node *temp=NULL,*p=NULL; temp=(struct node*)malloc(sizeof(struct node )); temp->cof=a; temp->exp=b; temp->link=NULL; if(r==NULL) { r=temp; } else{ p=r; while(p->link!=NULL) { p=p->link; } p->link=temp; } return r; } struct node* addition(struct node *root,struct node *root1) { struct node *s=NULL; while((root!=NULL)&&(root1!=NULL)) { if(root->exp>root1->exp) { s=insert(root->cof,root->exp); root=root->link; } else if(root1->exp>root->exp) { s=insert(root1->cof,root1->exp); root1=root1->link; } else { s=insert(root->cof+root1->cof,root->exp); root=root->link; root1=root1->link; } } while(root!=NULL){ s=insert(root->cof,root->exp); root=root->link; } while(root1!=NULL){ s= insert(root1->cof,root1->exp); root1=root1->link; } return s; } void complete_mul(struct node *root,struct node *root1,int n,int m) { struct node *temp=NULL,*temp1=NULL,*p=NULL,*sop=NULL; int a,b; if(m<=n) { temp=root; temp1=root1; while(temp1!=NULL) { while(temp!=NULL) { a=temp1->cof*temp->cof; b=temp1->exp+temp->exp; p=insertion(a,b); temp=temp->link; } sort(p); sop=addition(sop,p); r1=NULL; r=NULL; temp=root; temp1=temp1->link; } insertadd(sop); } else{ temp=root1; temp1=root; while(temp1!=NULL) { while(temp!=NULL) { a=temp1->cof*temp->cof; b=temp1->exp+temp->exp; p=insertion(a,b); temp=temp->link; } sort(p); sop=addition(sop,p); r1=NULL; r=NULL; temp=root1; temp1=temp1->link; } insertadd(sop); } } void insertadd(struct node *root) { printf("\n\nTHE COMPLETE RESULT: after multiply and addition of two polynomial:\n\n"); while (root!=NULL) { printf("%dx^%d ",root->cof,root->exp); root=root->link; } printf("\n\n"); }
C
#ifndef TERM_H_INCLUDED #define TERM_H_INCLUDED #include <termios.h> /* * Get the original terminal mode, set TCSANOW for the new one and * register reset_terminal_mode() for program exit. */ void nonblock(); /* * Use the original terminal mode to reset the terminal on program * exit. */ void reset_terminal_mode(); /* * Figure out whether we hit a key. */ int kbhit(); /* * Reset the input status after we have received input, so kbhit() * return false again. */ int reset_input(); #endif
C
/* Christopher Bachelor ** cbachelor@ucla.edu ** UCLA ID: 004608570 ** FOR LAB 2B */ #include <stdio.h> #include <getopt.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include "SortedList.h" #include <time.h> #include <pthread.h> #include <string.h> #include <signal.h> /*Globals used in the program*/ #define KEY_SIZE 10 int numThreads = 1; /*Number of threads, default 1*/ int numIter = 1; /*Number of iterations, default 1*/ int numLists = 1; /*Number of lists with --lists, default 1*/ int* testSet; /*Array of integers for test-and-set operation for each list*/ char syncopts = ' '; int opt_yield = 0; SortedList_t* list; /*List we use*/ SortedListElement_t* elements; int* elementsListIndex; /*Array whose index corresponds to elements, holds value of which list to insert*/ pthread_mutex_t* mutex; unsigned long long* threadTime; /*Array used to store lock acquisition time per thread*/ /*Signal handler to catch SEGFAULTS*/ void signal_handler(int signum) { fprintf(stderr, "Error: Segfault caught\n"); exit(2); } /*Calculates the time it took for the threads to finish computations*/ unsigned long long calculateTime(struct timespec start_time, struct timespec end_time) { unsigned long long ns; ns = end_time.tv_sec - start_time.tv_sec; ns *= 1000000000; ns += end_time.tv_nsec; ns -= start_time.tv_nsec; return ns; } /*Prints out the desired output after parsing through the given options*/ void printOutput(unsigned long long timeVal ) { int i; unsigned long long lockTime = 0; /*Calculation for total number of mutex operations: number of elements * (insert + lookup/delete) + each thread * lock sublist mutex */ int numMutex = numThreads * numIter * 2 + numThreads * numLists; int numOps = numThreads * numIter * 3; int printNone = 0; /*Calculate total lock acquisition time*/ if(syncopts == 'm' || syncopts == 's') { for(i = 0; i < numThreads; i++) { lockTime += threadTime[i]; } lockTime = lockTime / numMutex; } unsigned long long avgOps = timeVal/((unsigned long long) numOps); fprintf(stdout, "list-"); if(opt_yield & INSERT_YIELD) { fprintf(stdout, "i"); printNone = 1; } if( opt_yield & DELETE_YIELD) { fprintf(stdout, "d"); printNone = 1; } if (opt_yield & LOOKUP_YIELD) { fprintf(stdout, "l"); printNone = 1; } if(!printNone) { fprintf(stdout, "none"); } fprintf(stdout, "-"); if (syncopts != 's' && syncopts != 'm') { fprintf(stdout, "none"); } else { fprintf(stdout, "%c", syncopts); } fprintf(stdout, ",%d,%d,%d,%d,%lld,%lld,%llu\n", numThreads, numIter, numLists, numOps, timeVal, avgOps, lockTime); } /*Initializes the opt_yield bits based on the options given in --yield*/ void yieldSet(char* yieldParam) { int i = 0; while(yieldParam[i] != '\0') { if(yieldParam[i]== 'i' ) { opt_yield |= INSERT_YIELD; } else if (yieldParam[i] == 'd') { opt_yield |= DELETE_YIELD; } else if (yieldParam[i] == 'l') { opt_yield |= LOOKUP_YIELD; } else { fprintf(stderr, "Please specify a correct parameter to --yield\n"); fprintf(stderr, "Usage: lab2a_list [-t TOTAL_THREADS] [-i TOTAL_ITERATIONS]\n"); exit(1); } i++; } } /*Initializes the sync parameters given by --sync*/ void syncSet (char syncTemp){ if (syncTemp == 'm' || syncTemp == 's') { syncopts = syncTemp; } else { fprintf(stderr, "Please specify a correct parameter to --sync\n"); fprintf(stderr, "Usage: lab2a_add [-t TOTAL_THREADS] [-i TOTAL_ITERATIONS]\n"); exit(1); } } /*Initializes all the list elements with a random key Additionally hashes each key with the sub-list it belongs to in a separate array, but with the same index*/ void keyGen(int numElements) { int i, t, randomLetter; int sum = 0; srand(time(NULL)); /*The key is based on KEY_SIZE random alphabet characters (initially 10)*/ for (i = 0; i < numElements; i++) { char* tempKey = malloc((KEY_SIZE+1) * sizeof(char)); if(tempKey == NULL) { fprintf(stderr, "Error: Failed to allocate key elements\n"); exit(1); } for(t = 0; t < KEY_SIZE; t++) { randomLetter = rand() % 26; sum += randomLetter; tempKey[t] = randomLetter + 'a'; } tempKey[KEY_SIZE] = '\0'; /*Detached elements have a random key and its pointers are NULL*/ elements[i].key = tempKey; elements[i].next = NULL; elements[i].prev = NULL; elementsListIndex[i] = sum % numLists; sum = 0; } } /*Initialize numLists length of lists, each pointing to itself*/ void initializeList() { int i, rc; list = malloc(sizeof(SortedList_t) * numLists); if (list == NULL) { fprintf(stderr, "Error: failed to allocate list\n"); exit(1); } for (i = 0; i < numLists; i++) { list[i].key = NULL; list[i].next = &list[i]; list[i].prev = &list[i]; } /*Initialize an array of mutexes used per list*/ if(syncopts== 'm') { mutex = malloc(sizeof(pthread_mutex_t) * numLists); if (mutex == NULL) { fprintf(stderr, "Error: failed to allocate list\n"); exit(1); } for (i = 0; i < numLists; i++) { rc = pthread_mutex_init(&mutex[i], NULL); if(rc != 0) { fprintf(stderr, "Error: return code from pthread_mutex_init() is %d\n", rc); } } } /*Initialize an array of test-and-set variables used for spin lock */ else if (syncopts == 's') { testSet = malloc(sizeof(int) * numLists); if (testSet == NULL) { fprintf(stderr, "Error: failed to allocate list\n"); exit(1); } for(i = 0; i < numLists; i++) { testSet[i] = 0; } } } /*Main function that each thread calls*/ void* thread_func(void* tidPtr) { int tid = *((int *) tidPtr); int i, t, ret, sumTemp; int sum = 0; SortedListElement_t* elementPtr; /*Variables used to calculate lock acquisition time*/ struct timespec start_time, end_time; /*Each thread gets its own chunk of elements based on their thread ID*/ for(i = tid * numIter; i < tid * numIter + numIter; i++) { /*First insert all elements into the list*/ switch(syncopts) { /*Different options for synchronization depending on input parameters*/ case 'm': /*Calculate the time it takes to get a hold of the mutex*/ clock_gettime(CLOCK_MONOTONIC, &start_time); pthread_mutex_lock(&mutex[elementsListIndex[i]]); clock_gettime(CLOCK_MONOTONIC, &end_time); threadTime[tid] += calculateTime(start_time, end_time); SortedList_insert(&list[elementsListIndex[i]], &elements[i]); pthread_mutex_unlock(&mutex[elementsListIndex[i]]); break; case 's': /*Calculate the time it takes to get a hold of the spin lock*/ clock_gettime(CLOCK_MONOTONIC, &start_time); while(__sync_lock_test_and_set(&testSet[elementsListIndex[i]], 1) == 1) { ; } clock_gettime(CLOCK_MONOTONIC, &end_time); threadTime[tid] += calculateTime(start_time, end_time); SortedList_insert(&list[elementsListIndex[i]], &elements[i]); __sync_lock_release(&testSet[elementsListIndex[i]]); break; default: SortedList_insert(&list[elementsListIndex[i]], &elements[i]); } } /*Each thread performs SortedList_length calculation*/ switch(syncopts) { case 'm': for(t = 0; t < numLists; t++) { clock_gettime(CLOCK_MONOTONIC, &start_time); pthread_mutex_lock(&mutex[elementsListIndex[t]]); clock_gettime(CLOCK_MONOTONIC, &end_time); threadTime[tid] += calculateTime(start_time, end_time); sumTemp = SortedList_length(&list[elementsListIndex[t]]); if(sumTemp == -1) { fprintf(stderr, "Error: Corrupted list in SortedList_length()"); exit(2); } pthread_mutex_unlock(&mutex[elementsListIndex[t]]); sum += sumTemp; } break; case 's': for(t = 0; t < numLists; t++) { clock_gettime(CLOCK_MONOTONIC, &start_time); while(__sync_lock_test_and_set(&testSet[elementsListIndex[t]], 1) == 1) { ; } clock_gettime(CLOCK_MONOTONIC, &end_time); threadTime[tid] += calculateTime(start_time, end_time); sumTemp += SortedList_length(&list[elementsListIndex[t]]); if(sumTemp == -1) { fprintf(stderr, "Error: Corrupted list in SortedList_length()"); exit(2); } __sync_lock_release(&testSet[elementsListIndex[t]]); sum += sumTemp; } break; default: for (t = 0; t < numLists; t++) { sumTemp += SortedList_length(&list[elementsListIndex[i]]); if(sumTemp == -1) { fprintf(stderr, "Error: Corrupted list in SortedList_length()"); exit(2); } sum += sumTemp; } } /*Each thread looks up the elements they inserted and deletes them, with given synchronization options*/ for(i = tid * numIter; i < tid * numIter + numIter; i++) { switch (syncopts) { case 'm': clock_gettime(CLOCK_MONOTONIC, &start_time); pthread_mutex_lock(&mutex[elementsListIndex[i]]); clock_gettime(CLOCK_MONOTONIC, &end_time); threadTime[tid] += calculateTime(start_time, end_time); elementPtr = SortedList_lookup(&list[elementsListIndex[i]], elements[i].key); if(elementPtr == NULL) { fprintf(stderr, "Error: Couldn't find element\n"); exit(2); } ret = SortedList_delete(elementPtr); if (ret == 1) { fprintf(stderr, "Error: Corrupted prev/next pointers in SortedList_delete()\n"); exit(2); } pthread_mutex_unlock(&mutex[elementsListIndex[i]]); break; case 's': clock_gettime(CLOCK_MONOTONIC, &start_time); while(__sync_lock_test_and_set(&testSet[elementsListIndex[i]], 1) == 1) { ; } clock_gettime(CLOCK_MONOTONIC, &end_time); threadTime[tid] += calculateTime(start_time, end_time); elementPtr = SortedList_lookup(&list[elementsListIndex[i]], elements[i].key); if(elementPtr == NULL) { fprintf(stderr, "Error: Couldn't find element\n"); exit(2); } ret = SortedList_delete(elementPtr); if (ret == 1) { fprintf(stderr, "Error: Corrupted prev/next pointers in SortedList_delete()\n"); exit(2); } __sync_lock_release(&testSet[elementsListIndex[i]]); break; default: elementPtr = SortedList_lookup(&list[elementsListIndex[i]], elements[i].key); if(elementPtr == NULL) { fprintf(stderr, "Error: Couldn't find element\n"); exit(2); } // fprintf(stderr, "Deleting %s\n", elements[i].key); ret = SortedList_delete(elementPtr); if (ret == 1) { fprintf(stderr, "Error: Corrupted prev/next pointers in SortedList_delete()\n"); exit(2); } } } } int main(int argc, char* argv[]) { int option_index = 0; int ret = 0; int yieldOn = 0; int syncOn = 0; char* yieldTemp; int rc, i, t; char* syncTemp; /*Properly interpret command line arguments*/ static struct option command_arg[] = { {"threads", optional_argument, 0, 't'}, {"iterations", optional_argument, 0, 'i'}, {"yield", required_argument, 0, 'y'}, {"sync", required_argument, 0, 's'}, {"lists", optional_argument, 0, 'l'}, {0, 0, 0, 0} }; while(ret != -1) { ret = getopt_long(argc, argv, "tiy:s:l", command_arg, &option_index); switch (ret) { case 't': numThreads = atoi(optarg); break; case 'i': numIter = atoi(optarg); break; case 'y': yieldTemp = optarg; yieldOn = 1; break; case 's': syncTemp = optarg; if(optarg != NULL) syncOn = 1; break; case 'l': numLists = atoi(optarg); case -1: break; default: fprintf(stderr, "Usage: lab2a_list [-t TOTAL_THREADS] [-i TOTAL_ITERATIONS] [-y i|d|l] [-s m|s]\n"); exit(1); } } /*Interpret yield options and sync options given*/ if(yieldOn) { yieldSet(yieldTemp); } if(syncOn) { syncSet(syncTemp[0]); } /*Start signal handling in case of SEGFAULT*/ signal(SIGSEGV, signal_handler); int numElements = numThreads * numIter; initializeList(); /*Allocate memory for the elements, and create additional array that holds value of the list it belongs to*/ elements = malloc(numElements * (sizeof(SortedListElement_t))); elementsListIndex = malloc(numElements * (sizeof(int))); if(elements == NULL || elementsListIndex == NULL) { fprintf(stderr, "Error: Failed to allocate elements\n"); exit(1); } keyGen(numElements); /*Allocate space to store lock acquisition time per thread*/ threadTime = malloc(sizeof(unsigned long long) * numThreads); for (i = 0; i < numThreads; i++) { threadTime[i] = 0; } /*Initialize time recording variables, and start recording*/ struct timespec start_time, end_time; unsigned long long ns; clock_gettime(CLOCK_MONOTONIC, &start_time); /*Initialize pthread attributes*/ pthread_t* thread = malloc(numThreads * sizeof(pthread_t)); int* tid = malloc(numThreads * sizeof(int)); pthread_attr_t attr; rc = pthread_attr_init(&attr); if (rc != 0) { fprintf(stderr, "Error: return code from pthread_attr_init() is %d\n", rc); exit(1); } rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); if (rc != 0) { fprintf(stderr, "Error: return code from pthread_attr_setdetachstate() is %d\n", rc); exit(1); } /*Initialize all threads and make them run the thread functions*/ for (i = 0; i < numThreads; i++) { tid[i] = i; rc = pthread_create(&thread[i], &attr, thread_func, (void *) &tid[i]); if (rc != 0) { fprintf(stderr, "Error: return code from pthread_create() is %d\n", rc); exit(1); } } /*Wait for all the threads to terminate*/ void* status; for (t = 0; t < numThreads; t++) { rc = pthread_join(thread[t], &status); if (rc != 0) { fprintf(stderr, "Error: return code from pthread_join() is %d\n", rc); exit(1); } } /*Capture time of end of calculations and calculate duration in milliseconds*/ clock_gettime(CLOCK_MONOTONIC, &end_time); ns = calculateTime(start_time, end_time); /*Final list calculation: If not 0, then synchronization error*/ int sum = 0; int sumTemp; for (i = 0; i < numLists; i++) { sumTemp = SortedList_length(&list[i]); if(sumTemp == -1) { fprintf(stderr, "Error: List length is not 0 after threads have terminated\n"); exit(2); } sum += sumTemp; } printOutput(ns); /*Free all memory that was allocated*/ for(i = 0; i < numIter*numThreads; i++) { free((void *) elements[i].key); } free(elements); free(tid); free(thread); free(threadTime); if(syncopts == 'm') { for(i = 0; i < numLists; i++) { pthread_mutex_destroy(&mutex[i]); } free(mutex); } free(elementsListIndex); free(list); if(syncopts == 's') { free((void *)testSet); } }
C
/* Copyright (C) 2015 copyright holder This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //Project Name: DefaultProject //Owner: gmello //UID : 1000 // Faça um programa que receba o raio, calcule e mostre // o comprimento da esfera // a area da esfera // o volume da esfera #include<stdio.h> #include<math.h> #define PI 3.14 int main(void){ float raio; printf("Raio da esfera: "); scanf("%f", &raio); printf("Comprimento da esfera %.2f\n", 2*PI*raio ); printf("Area da esfera: %.2f\n", PI*pow(raio,2)); printf("Volume da esfera: %.2f\n", (PI*pow(raio,3))/4.0f); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { /*Escribe un programa que calcule la factorial de n, donde n es un numero entero ma- yor o igual a 0 dado por el usuario.*/ int ft, num=0, h=1; printf("ingrese un numero: "); scanf("%d",&ft); while(ft>0) { num=num+1; h=h*num; ft--; } printf("El factorial es: %d", h); return 0; }
C
/** 206 Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head){ typedef struct ListNode Node; Node *pre ,*cur ,*preced ; if (!head) return NULL; pre = NULL , cur =head , preced = cur->next; while (preced) { cur->next = pre; pre = cur ; cur = preced ; preced = preced->next; } cur->next = pre; return cur; }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/uio.h> #include <time.h> #include <errno.h> #include <semaphore.h> #include "buffer.h" /* This method takes in a buffer and initializes its variable values */ void createBuffer(Buffer* buff) { buff -> in = 0; // set the in value to 0 buff -> out = 0; // set the out value to 0 sem_init(&buff->emptySem, 1, 200); // set the semaphore for the empty semaphore to 1 sem_init(&buff->fullSem,1, 0); // set the full semaphore to the value of 0 } /* This method takes in a character and a buffer and puts the character at the buff->in location */ void deposit(Buffer* buff, char c) { sem_wait(&buff->emptySem); // This makes the empty semaphore go down by 1 since we are depositing a character buff->stream[buff->in] = c; // place the character in the in location of the buff buff->in = (buff->in +1) % 200; // increase the in location by one and mod by 20 to make it circular sem_post(&buff->fullSem); // This increases the full semaphore by 1 since it has a new character } /* This method takes in a buffer and removes the character returing that character from the method */ char remoove(Buffer* buff) { sem_wait(&buff->fullSem); // This increases the full semaphore by 1 with the removal of a character char temp = buff->stream[buff->out]; // This keeps the value in the out location of the buffer buff->out = (buff->out+1)%200; // this increases the value of the out and mod 20 to keep the count going around the buffer sem_post(&buff->emptySem); // this increases the empty semaphore by 1 since a value was removed and another character can be added to the buffer return temp; // This returns the character taken from the buffer } /* This method takes in a buffer and prints all of its values. Used for debugging */ void print(Buffer* buff) { int count = 0; for(count = 0; count < 201; count++) { printf("%c", buff->stream[count]); // This goes through each value in the buffer and prints each one } printf("\n"); }
C
#include<stdio.h> int main() { int x,c=0; printf("enter the number\n"); scanf("%d",&x); /* while(x) { if(x & 0x01) c++; x=x>>1; } printf("number of 1's:%d\n",c); if(c==1) printf("number is power of 2\n"); else printf("number is not power of 2\n"); } */ /* in above programm loop is continuing upto x==0 ,so itteration process takes place for long term*/ /* so reduce itteration process we hwve to write*/ /* while(x) { x= x & (x-1); c++; printf("count=%d\n",c); } if(c==1) printf("number is power of 2\n"); else printf("number is not power of 2\n"); } */ /* if x=0 it is not multiplied by 2*/ if(x && !(x&(x-1))) printf("power of 2\n"); else printf("not power of 2\n"); }
C
#include<stdio.h> void main() { int n,i,sum=0; { printf("Enter a number: "); scanf("%d",&n); } { for(i=1;i<=n;i++) { sum +=i;// sum = sum+i; } { printf("Sum = %d",sum); } return 0; }
C
#include "system_queue.h" static SystemQueue s_queue; void SystemQueueInit() { s_queue.n = 0; } size_t SizeSystemQueue() { return s_queue.n; } int EnqueueSystemQueue(const PEvent event) { int ret = 0; if(s_queue.n <= MAX_EVENTS) { Event_clone(OBJECT(event), OBJECT(&s_queue.system_events[s_queue.n++])); //s_queue.system_events[++s_queue.n] = *event; ++ret; } return ret; } int DequeueSystemQueue(PEvent event) { int i; int ret = 0; if(s_queue.n > 0) { Event_clone(OBJECT(&s_queue.system_events[0]), OBJECT(event)); --s_queue.n; //*event = s_queue.system_events[0]; ++ret; } for(i = 0; i < (s_queue.n); ++i) { s_queue.system_events[i] = s_queue.system_events[i+1]; } return ret; }
C
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */ #include <fcntl.h> #include <stdio.h> /* for printf() and fprintf() */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <sys/ioctl.h> #include <sys/socket.h> /* for socket(), bind(), and connect() */ #include <sys/time.h> #include <sys/types.h> #include <unistd.h> /* for close() */ #define MAXPENDING 5 /* Maximum outstanding connection requests */ void DieWithError(char *errorMessage); /* Error handling function */ void HandleTCPClient(int clntSocket); /* TCP client handling function */ void reverseStr(char *str) { int length; char *p1; char *p2; length = strlen(str); //获取字符串长度 p1 = str; //p1指向字符串首地址 p2 = str + length - 1; //p2指向字符串尾地址 if (str == NULL) { printf("空指针错误!"); return ; } while (p1 < p2) //当p1地址小于p2地址时执行循环 { char c = *p1; *p1 = *p2; //完成指针指向地址的值的交换 *p2 = c; p1++; //交换完毕后p1指针指向下一个字符地址 p2--; //交换完毕后p2指针指向上一个字符地址 } } int main(int argc, char *argv[]) { int servSock; /* Socket descriptor for server */ int clntSock; /* Socket descriptor for client */ struct sockaddr_in echoServAddr; /* Local address */ struct sockaddr_in echoClntAddr; /* Client address */ unsigned short echoServPort; /* Server port */ unsigned int clntLen; /* Length of client address data structure */ char *msg; int yes = 1; if (argc != 2) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]); exit(1); } echoServPort = atoi(argv[1]); /* First arg: local port */ /* Create socket for incoming connections */ if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); if (setsockopt(servSock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(int)) == -1) DieWithError("setsockopt() failed"); /* Construct local address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(echoServPort); /* Local port */ /* Bind to the local address */ if (bind(servSock, (struct sockaddr *)&echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("bind() failed"); /* Mark the socket so it will listen for incoming connections */ if (listen(servSock, MAXPENDING) < 0) DieWithError("listen() failed"); char buffer[128]; fd_set rfds; int retval, nread; FD_ZERO(&rfds); FD_SET(0, &rfds); FD_SET(servSock, &rfds); printf("input 'quit' to quit the server.\n"); for (;;) /* Run forever */ { /* Set the size of the in-out parameter */ // clntLen = sizeof(echoClntAddr); // /* Wait for a client to connect */ // if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) // DieWithError("accept() failed"); // int sendnum=0; // //if(sendnum=!=strlen(msg)) // recv(clntSock, msg, strlen(msg)-1, 0); // msg = reverseStr(msg); // send(clntSock, msg, sizeof(msg)-1, 0); // HandleTCPClient(clntSock); // } FD_ZERO(&rfds); // select. FD_SET(0, &rfds); FD_SET(servSock, &rfds); retval = select(FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0); //&tv); if (retval == -1) DieWithError("select()"); else if (retval) { if (FD_ISSET(0, &rfds)) { ioctl(0, FIONREAD, &nread); if (nread == 0) { printf("There is no input\n"); continue; } nread = read(0, buffer, nread); nread--; buffer[nread] = '\0'; if (strcmp(buffer, "quit") == 0) { printf("The server will be shut down in 1 second...\n"); sleep(1); exit(1); } else if (strcmp(buffer, "RETURN") == 0) { FD_CLR(0, &rfds); printf("The information will be ended\n"); close(1); } printf("read %d letter from keyboard: %s\n", nread, buffer); } if (FD_ISSET(servSock, &rfds)) { /* Set the size of the in-out parameter */ clntLen = sizeof(echoClntAddr); /* Wait for a client to connect */ if ((clntSock = accept(servSock, (struct sockaddr *)&echoClntAddr, &clntLen)) < 0) DieWithError("accept() failed"); printf("\nHandling client %s:%d\n", inet_ntoa(echoClntAddr.sin_addr), ntohs(echoClntAddr.sin_port)); HandleTCPClient(clntSock); } } else { printf("Out of time\n"); break; } } }
C
// tcpcli01.c #include "unp.h" int main(int argc, char *argv[]){ if(argc!=2){ fprintf(stderr, "Usage: %s <IP>\n", argv[0]); exit(1); } int sockfd = Socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in servsock; char buf[MAXLINE]; bzero(&servsock, sizeof(servsock)); servsock.sin_family = AF_INET; servsock.sin_port = htons(SERV_PORT); inet_pton(AF_INET, argv[1], &servsock.sin_addr); Connect(sockfd, (SA*)&servsock, sizeof(servsock)); written(sockfd, "hello!\n", 7); Readline(sockfd, buf, sizeof(buf)); printf("%s: GET %s", getcurtime(), buf); sleep(10); // 等待服务器被关闭 printf("%s: write data\n", getcurtime()); written(sockfd, "abc\n", 4); printf("%s: after written\n", getcurtime()); sleep(10); printf("%s: read data\n", getcurtime()); Readline(sockfd, buf, sizeof(buf)); printf("%s: after readline\n", getcurtime()); }
C
/****************************************************************************** * Copyright 2020 The Firmament Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "led.h" uint8_t led_status[2]; void led_on(LED_Type led) { if(led == LED_RED) { GPIO_ResetBits(LED_PORT, LED_RED_PIN); led_status[LED_RED] = 1; } else { GPIO_ResetBits(LED_PORT, LED_BLUE_PIN); led_status[LED_BLUE] = 1; } } void led_off(LED_Type led) { if(led == LED_RED) { GPIO_SetBits(LED_PORT, LED_RED_PIN); led_status[LED_RED] = 0; } else { GPIO_SetBits(LED_PORT, LED_BLUE_PIN); led_status[LED_BLUE] = 0; } } void led_toggle(LED_Type led) { if(led_status[led]) led_off(led); else led_on(led); } void led_init(void) { GPIO_InitTypeDef GPIO_InitStructure; /* GPIOD Periph clock enable */ RCC_APB2PeriphClockCmd(LED_RCC, ENABLE); /* Configure PD0 and PD2 in output pushpull mode */ GPIO_InitStructure.GPIO_Pin = LED_RED_PIN | LED_BLUE_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(LED_PORT, &GPIO_InitStructure); led_off(LED_RED); led_off(LED_BLUE); }
C
#include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> void *thread_function(void *data) { //pid_t pid; //pthread_t tid; //pid = getpid(); //tid = pthread_self(); //char* thread_name = (char*)data; int i = 0; while (i < 5) { printf("%s, count %d\n", (char*)data, i); i++; sleep(1); } } int main() { pthread_t p_thread; char p1[] = "thread1"; char p2[] = "main"; int status; pthread_create(&p_thread, NULL, thread_function, (void *)p1); if (p_thread < 0) { perror("nono~\n"); exit(0); } thread_function((void*)p2); pthread_join(p_thread, (void**)&status); printf("bye~\n"); return 0; }