language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
int main() {
int input = 0, x = 0;
int sum = 0;
printf("Input a positive number less than 500: ");
scanf("%i", &x);
input = x;
while ( x != 0 ) {
sum += x % 10;
x /= 10;
}
printf("Sum of the digit %i is: %i\n", input, sum);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/time.h>
#include "cycle.h"
int main(void){
struct timeval t1,t2;
double elapsedTime;
unsigned int N=10;
//while(N<10000){
LinkedList *l=createList(N);
printf("Total heap space=%u\n", spaceAllocated);
l=createCycle(l);
//gettimeofday(&t1, NULL);
printf("%s\n",testCyclic(l));
/*gettimeofday(&t2, NULL);
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;
printf("Total time is %f ms.\n for %u", elapsedTime,N);*/
l=makeCircularList(l);
printf("%s\n",testCyclic(l));
myfree(l);
N*=10;
//}
}
|
C
|
#define F_CPU 16000000UL //freq 16 MHz
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "SPI_routines.h"
#include "SD_routines.h"
#include "UART_routines.h"
#include "i2c_routines.h"
#include "ADC_routines.h"
#include "FAT32.h"
#define INTERVAL 1000 //interval in milliseconds, between two measurements
//interval defined here is approximate only, as the overhead delays
//are not added, error is more for smaller values (i.e. <100ms)
//minimum: 10; maximum: 600000 (600 seconds)
#define KEY_PRESSED (!(PINC & 0x80))
#define GREEN_LED_ON PORTC |= 0x20
#define RED_LED_ON PORTC |= 0x40
#define RED_LED_OFF PORTC &= ~0x40
void port_init(void)
{
PORTB = 0x00; //pull-up on for pushbutton
DDRB = 0xef; //MISO line i/p, rest o/p
PORTC = 0x80; //pull-up for push-button
DDRC = 0x60; //PC7- i/p (pushbutton), PC6, PC5 - o/p (two LEDs)
}
//call this routine to initialize all peripherals
void init_devices(void)
{
cli(); //all interrupts disabled
port_init();
spi_init();
uart0_init();
//all peripherals are now initialized
}
//function to blink LED in case of any error
void blinkRedLED(void)
{
while(1) //blink red LED continuously, if error
{
RED_LED_ON;
_delay_ms(400);
RED_LED_OFF;
_delay_ms(400);
}
}
//*************************** MAIN *******************************//
int main(void)
{
unsigned char option, error, i, j, data, channel;
unsigned char fileName[] = "test.txt";
unsigned int delay, k;
_delay_ms(100); //delay for VCC stabilization
init_devices();
GREEN_LED_ON; //turn on green LED to indicate power on
RED_LED_OFF; //keep red LED off for now
transmitString_F (PSTR("\n\r\n\r****************************************************"));
transmitString_F (PSTR("\n\r microSD ATMEGA328P "));
transmitString_F (PSTR("\n\r****************************************************\n\r"));
cardType = 0;
for (i=0; i<10; i++)
{
error = SD_init();
if(!error) break;
}
if(error)
{
if(error == 1) transmitString_F(PSTR("SD card not detected.."));
if(error == 2) transmitString_F(PSTR("Card Initialization failed.."));
blinkRedLED();
}
switch (cardType)
{
case 1:transmitString_F(PSTR("Standard Capacity Card (Ver 1.x) Detected!"));
break;
case 2:transmitString_F(PSTR("High Capacity Card Detected!"));
break;
case 3:transmitString_F(PSTR("Standard Capacity Card (Ver 2.x) Detected!"));
break;
default:transmitString_F(PSTR("Unknown SD Card Detected!"));
break;
}
error = getBootSectorData (); //read boot sector and keep necessary data in global variables
if(error)
{
transmitString_F (PSTR("\n\rFAT32 not found!")); //FAT32 incompatible drive
blinkRedLED();
}
SPI_HIGH_SPEED; //SCK - 4 MHz
_delay_ms(1); //some delay for settling new spi speed
//For displaying menu on hyper terminal, the key (psh-button) must be kept pressed while
//powering ON or while reset. If key is not kept pressed, the program will not display menu and it will
//simply wait for start recording command (i.e. pressing of key afterwards)
while(1)
{
transmitString_F(PSTR("\n\r\n\r> 0 : Exit the Menu"));
transmitString_F(PSTR("\n\r> 1 : Get file list"));
transmitString_F(PSTR("\n\r> 2 : Write Test File"));
transmitString_F(PSTR("\n\r> 3 : Read File"));
transmitString_F(PSTR("\n\r> 4 : Delete File"));
transmitString_F(PSTR("\n\r> 5 : Display Memory"));
transmitString_F(PSTR("\n\r\n\r> Enter the option:"));
option = receiveByte();
transmitByte(option);
switch (option)
{
case '0':transmitString_F(PSTR("\n\Operation Stopped.."));
goto STOP;
case '1':TX_NEWLINE;
findFiles(GET_LIST,0);
break;
case '2':TX_NEWLINE;
//From here onwards, gather data by appending strings in dataString
//dataString is declared in FAT32.h
//make sure dataString doesn't exceed its MAX_STRING_SIZE, defined in FAT32.h
for(i=0; i<10; i++) dataString[i] = 'A';
dataString[i++] = ',';
for(j=0;j<8; j++) dataString[i++] = i+'0';
dataString[i++] = ',';
transmitString_F(PSTR("Writing ..."));
error = writeFile("testing.txt");
if(error) blinkRedLED();
transmitString_F(PSTR("Done"));
break;
case '3':
case '4':transmitString_F(PSTR("\n\rEnter file name: "));
for(i=0; i<13; i++)
fileName[i] = 0x00; //clearing any previously stored file name
i=0;
while(1)
{
data = receiveByte();
if(data == 0x0d) break; //'ENTER' key pressed
if(data == 0x08) //'Back Space' key pressed
{
if(i != 0)
{
transmitByte(data);
transmitByte(' ');
transmitByte(data);
i--;
}
continue;
}
if(data <0x20 || data > 0x7e) continue; //check for valid English text character
transmitByte(data);
fileName[i++] = data;
if(i==13){transmitString_F(PSTR(" file name too long..")); break;}
}
if(i>12) break;
TX_NEWLINE;
if(option == '3')
{
error = readFile( READ, fileName);
if(error == 1) transmitString_F(PSTR("File does not exist.."));
}
if(option == '4') deleteFile(fileName);
break;
case '5':
displayMemory(HIGH,getSetFreeCluster(TOTAL_FREE,GET,0));
break;
default:transmitString_F(PSTR("\n\r\n\r Invalid option!\n\r"));
}
}
while(1)
{
while(1)
{
}//end of while(1)
STOP:
RED_LED_OFF; //recording stopped
}//end of while(1)
return 0;
}//end of main
//********** END *********** www.dharmanitech.com *************
|
C
|
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle INSERT statements in SQLite.
**
** $Id$
*/
#include "sqliteInt.h"
/*
** This routine is call to handle SQL of the following forms:
**
** insert into TABLE (IDLIST) values(EXPRLIST)
** insert into TABLE (IDLIST) select
**
** The IDLIST following the table name is always optional. If omitted,
** then a list of all columns for the table is substituted. The IDLIST
** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
**
** The pList parameter holds EXPRLIST in the first form of the INSERT
** statement above, and pSelect is NULL. For the second form, pList is
** NULL and pSelect is a pointer to the select statement used to generate
** data for the insert.
**
** The code generated follows one of three templates. For a simple
** select with data coming from a VALUES clause, the code executes
** once straight down through. The template looks like this:
**
** open write cursor to <table> and its indices
** puts VALUES clause expressions onto the stack
** write the resulting record into <table>
** cleanup
**
** If the statement is of the form
**
** INSERT INTO <table> SELECT ...
**
** And the SELECT clause does not read from <table> at any time, then
** the generated code follows this template:
**
** goto B
** A: setup for the SELECT
** loop over the tables in the SELECT
** gosub C
** end loop
** cleanup after the SELECT
** goto D
** B: open write cursor to <table> and its indices
** goto A
** C: insert the select result into <table>
** return
** D: cleanup
**
** The third template is used if the insert statement takes its
** values from a SELECT but the data is being inserted into a table
** that is also read as part of the SELECT. In the third form,
** we have to use a intermediate table to store the results of
** the select. The template is like this:
**
** goto B
** A: setup for the SELECT
** loop over the tables in the SELECT
** gosub C
** end loop
** cleanup after the SELECT
** goto D
** C: insert the select result into the intermediate table
** return
** B: open a cursor to an intermediate table
** goto A
** D: open write cursor to <table> and its indices
** loop over the intermediate table
** transfer values form intermediate table into <table>
** end the loop
** cleanup
*/
void sqliteInsert(
Parse *pParse, /* Parser context */
SrcList *pTabList, /* Name of table into which we are inserting */
ExprList *pList, /* List of values to be inserted */
Select *pSelect, /* A SELECT statement to use as the data source */
IdList *pColumn, /* Column names corresponding to IDLIST. */
int onError /* How to handle constraint errors */
){
Table *pTab; /* The table to insert into */
char *zTab; /* Name of the table into which we are inserting */
const char *zDb; /* Name of the database holding this table */
int i, j, idx; /* Loop counters */
Vdbe *v; /* Generate code into this virtual machine */
Index *pIdx; /* For looping over indices of the table */
int nColumn; /* Number of columns in the data */
int base; /* VDBE Cursor number for pTab */
int iCont, iBreak; /* Beginning and end of the loop over srcTab */
sqlite *db; /* The main database structure */
int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
int endOfLoop; /* Label for the end of the insertion loop */
int useTempTable; /* Store SELECT results in intermediate table */
int srcTab; /* Data comes from this temporary cursor if >=0 */
int iSelectLoop; /* Address of code that implements the SELECT */
int iCleanup; /* Address of the cleanup code */
int iInsertBlock; /* Address of the subroutine used to insert data */
int iCntMem; /* Memory cell used for the row counter */
int isView; /* True if attempting to insert into a view */
int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
int before_triggers; /* True if there are BEFORE triggers */
int after_triggers; /* True if there are AFTER triggers */
int newIdx = -1; /* Cursor for the NEW table */
if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
db = pParse->db;
/* Locate the table into which we will be inserting new information.
*/
assert( pTabList->nSrc==1 );
zTab = pTabList->a[0].zName;
if( zTab==0 ) goto insert_cleanup;
pTab = sqliteSrcListLookup(pParse, pTabList);
if( pTab==0 ){
goto insert_cleanup;
}
assert( pTab->iDb<db->nDb );
zDb = db->aDb[pTab->iDb].zName;
if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
goto insert_cleanup;
}
/* Ensure that:
* (a) the table is not read-only,
* (b) that if it is a view then ON INSERT triggers exist
*/
before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
TK_BEFORE, TK_ROW, 0);
after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
TK_AFTER, TK_ROW, 0);
row_triggers_exist = before_triggers || after_triggers;
isView = pTab->pSelect!=0;
if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
goto insert_cleanup;
}
if( pTab==0 ) goto insert_cleanup;
/* If pTab is really a view, make sure it has been initialized.
*/
if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
goto insert_cleanup;
}
/* Allocate a VDBE
*/
v = sqliteGetVdbe(pParse);
if( v==0 ) goto insert_cleanup;
sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist, pTab->iDb);
/* if there are row triggers, allocate a temp table for new.* references. */
if( row_triggers_exist ){
newIdx = pParse->nTab++;
}
/* Figure out how many columns of data are supplied. If the data
** is coming from a SELECT statement, then this step also generates
** all the code to implement the SELECT statement and invoke a subroutine
** to process each row of the result. (Template 2.) If the SELECT
** statement uses the the table that is being inserted into, then the
** subroutine is also coded here. That subroutine stores the SELECT
** results in a temporary table. (Template 3.)
*/
if( pSelect ){
/* Data is coming from a SELECT. Generate code to implement that SELECT
*/
int rc, iInitCode;
iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
iSelectLoop = sqliteVdbeCurrentAddr(v);
iInsertBlock = sqliteVdbeMakeLabel(v);
rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
iCleanup = sqliteVdbeMakeLabel(v);
sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
assert( pSelect->pEList );
nColumn = pSelect->pEList->nExpr;
/* Set useTempTable to TRUE if the result of the SELECT statement
** should be written into a temporary table. Set to FALSE if each
** row of the SELECT can be written directly into the result table.
**
** A temp table must be used if the table being updated is also one
** of the tables being read by the SELECT statement. Also use a
** temp table in the case of row triggers.
*/
if( row_triggers_exist ){
useTempTable = 1;
}else{
int addr = sqliteVdbeFindOp(v, OP_OpenRead, pTab->tnum);
useTempTable = 0;
if( addr>0 ){
VdbeOp *pOp = sqliteVdbeGetOp(v, addr-2);
if( pOp->opcode==OP_Integer && pOp->p1==pTab->iDb ){
useTempTable = 1;
}
}
}
if( useTempTable ){
/* Generate the subroutine that SELECT calls to process each row of
** the result. Store the result in a temporary table
*/
srcTab = pParse->nTab++;
sqliteVdbeResolveLabel(v, iInsertBlock);
sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
sqliteVdbeAddOp(v, OP_Pull, 1, 0);
sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
sqliteVdbeAddOp(v, OP_Return, 0, 0);
/* The following code runs first because the GOTO at the very top
** of the program jumps to it. Create the temporary table, then jump
** back up and execute the SELECT code above.
*/
sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
sqliteVdbeResolveLabel(v, iCleanup);
}else{
sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
}
}else{
/* This is the case if the data for the INSERT is coming from a VALUES
** clause
*/
SrcList dummy;
assert( pList!=0 );
srcTab = -1;
useTempTable = 0;
assert( pList );
nColumn = pList->nExpr;
dummy.nSrc = 0;
for(i=0; i<nColumn; i++){
if( sqliteExprResolveIds(pParse, &dummy, 0, pList->a[i].pExpr) ){
goto insert_cleanup;
}
if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
goto insert_cleanup;
}
}
}
/* Make sure the number of columns in the source data matches the number
** of columns to be inserted into the table.
*/
if( pColumn==0 && nColumn!=pTab->nCol ){
sqliteErrorMsg(pParse,
"table %S has %d columns but %d values were supplied",
pTabList, 0, pTab->nCol, nColumn);
goto insert_cleanup;
}
if( pColumn!=0 && nColumn!=pColumn->nId ){
sqliteErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
goto insert_cleanup;
}
/* If the INSERT statement included an IDLIST term, then make sure
** all elements of the IDLIST really are columns of the table and
** remember the column indices.
**
** If the table has an INTEGER PRIMARY KEY column and that column
** is named in the IDLIST, then record in the keyColumn variable
** the index into IDLIST of the primary key column. keyColumn is
** the index of the primary key as it appears in IDLIST, not as
** is appears in the original table. (The index of the primary
** key in the original table is pTab->iPKey.)
*/
if( pColumn ){
for(i=0; i<pColumn->nId; i++){
pColumn->a[i].idx = -1;
}
for(i=0; i<pColumn->nId; i++){
for(j=0; j<pTab->nCol; j++){
if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
pColumn->a[i].idx = j;
if( j==pTab->iPKey ){
keyColumn = i;
}
break;
}
}
if( j>=pTab->nCol ){
if( sqliteIsRowid(pColumn->a[i].zName) ){
keyColumn = i;
}else{
sqliteErrorMsg(pParse, "table %S has no column named %s",
pTabList, 0, pColumn->a[i].zName);
pParse->nErr++;
goto insert_cleanup;
}
}
}
}
/* If there is no IDLIST term but the table has an integer primary
** key, the set the keyColumn variable to the primary key column index
** in the original table definition.
*/
if( pColumn==0 ){
keyColumn = pTab->iPKey;
}
/* Open the temp table for FOR EACH ROW triggers
*/
if( row_triggers_exist ){
sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
}
/* Initialize the count of rows to be inserted
*/
if( db->flags & SQLITE_CountRows ){
iCntMem = pParse->nMem++;
sqliteVdbeAddOp(v, OP_Integer, 0, 0);
sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
}
/* Open tables and indices if there are no row triggers */
if( !row_triggers_exist ){
base = pParse->nTab;
idx = sqliteOpenTableAndIndices(pParse, pTab, base);
pParse->nTab += idx;
}
/* If the data source is a temporary table, then we have to create
** a loop because there might be multiple rows of data. If the data
** source is a subroutine call from the SELECT statement, then we need
** to launch the SELECT statement processing.
*/
if( useTempTable ){
iBreak = sqliteVdbeMakeLabel(v);
sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
iCont = sqliteVdbeCurrentAddr(v);
}else if( pSelect ){
sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
sqliteVdbeResolveLabel(v, iInsertBlock);
}
/* Run the BEFORE and INSTEAD OF triggers, if there are any
*/
endOfLoop = sqliteVdbeMakeLabel(v);
if( before_triggers ){
/* build the NEW.* reference row. Note that if there is an INTEGER
** PRIMARY KEY into which a NULL is being inserted, that NULL will be
** translated into a unique ID for the row. But on a BEFORE trigger,
** we do not know what the unique ID will be (because the insert has
** not happened yet) so we substitute a rowid of -1
*/
if( keyColumn<0 ){
sqliteVdbeAddOp(v, OP_Integer, -1, 0);
}else if( useTempTable ){
sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
}else if( pSelect ){
sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
}else{
sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
sqliteVdbeAddOp(v, OP_Pop, 1, 0);
sqliteVdbeAddOp(v, OP_Integer, -1, 0);
sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
}
/* Create the new column data
*/
for(i=0; i<pTab->nCol; i++){
if( pColumn==0 ){
j = i;
}else{
for(j=0; j<pColumn->nId; j++){
if( pColumn->a[j].idx==i ) break;
}
}
if( pColumn && j>=pColumn->nId ){
sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
}else if( useTempTable ){
sqliteVdbeAddOp(v, OP_Column, srcTab, j);
}else if( pSelect ){
sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
}else{
sqliteExprCode(pParse, pList->a[j].pExpr);
}
}
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
/* Fire BEFORE or INSTEAD OF triggers */
if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab,
newIdx, -1, onError, endOfLoop) ){
goto insert_cleanup;
}
}
/* If any triggers exists, the opening of tables and indices is deferred
** until now.
*/
if( row_triggers_exist && !isView ){
base = pParse->nTab;
idx = sqliteOpenTableAndIndices(pParse, pTab, base);
pParse->nTab += idx;
}
/* Push the record number for the new entry onto the stack. The
** record number is a randomly generate integer created by NewRecno
** except when the table has an INTEGER PRIMARY KEY column, in which
** case the record number is the same as that column.
*/
if( !isView ){
if( keyColumn>=0 ){
if( useTempTable ){
sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
}else if( pSelect ){
sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
}else{
sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
}
/* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
** to generate a unique primary key value.
*/
sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
sqliteVdbeAddOp(v, OP_Pop, 1, 0);
sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
}else{
sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
}
/* Push onto the stack, data for all columns of the new entry, beginning
** with the first column.
*/
for(i=0; i<pTab->nCol; i++){
if( i==pTab->iPKey ){
/* The value of the INTEGER PRIMARY KEY column is always a NULL.
** Whenever this column is read, the record number will be substituted
** in its place. So will fill this column with a NULL to avoid
** taking up data space with information that will never be used. */
sqliteVdbeAddOp(v, OP_String, 0, 0);
continue;
}
if( pColumn==0 ){
j = i;
}else{
for(j=0; j<pColumn->nId; j++){
if( pColumn->a[j].idx==i ) break;
}
}
if( pColumn && j>=pColumn->nId ){
sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
}else if( useTempTable ){
sqliteVdbeAddOp(v, OP_Column, srcTab, j);
}else if( pSelect ){
sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
}else{
sqliteExprCode(pParse, pList->a[j].pExpr);
}
}
/* Generate code to check constraints and generate index keys and
** do the insertion.
*/
sqliteGenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
0, onError, endOfLoop);
sqliteCompleteInsertion(pParse, pTab, base, 0,0,0,
after_triggers ? newIdx : -1);
}
/* Update the count of rows that are inserted
*/
if( (db->flags & SQLITE_CountRows)!=0 ){
sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
}
if( row_triggers_exist ){
/* Close all tables opened */
if( !isView ){
sqliteVdbeAddOp(v, OP_Close, base, 0);
for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
}
}
/* Code AFTER triggers */
if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
onError, endOfLoop) ){
goto insert_cleanup;
}
}
/* The bottom of the loop, if the data source is a SELECT statement
*/
sqliteVdbeResolveLabel(v, endOfLoop);
if( useTempTable ){
sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
sqliteVdbeResolveLabel(v, iBreak);
sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
}else if( pSelect ){
sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
sqliteVdbeAddOp(v, OP_Return, 0, 0);
sqliteVdbeResolveLabel(v, iCleanup);
}
if( !row_triggers_exist ){
/* Close all tables opened */
sqliteVdbeAddOp(v, OP_Close, base, 0);
for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
}
}
sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
sqliteEndWriteOperation(pParse);
/*
** Return the number of rows inserted.
*/
if( db->flags & SQLITE_CountRows ){
sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows inserted", P3_STATIC);
sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
sqliteVdbeAddOp(v, OP_Callback, 1, 0);
}
insert_cleanup:
sqliteSrcListDelete(pTabList);
if( pList ) sqliteExprListDelete(pList);
if( pSelect ) sqliteSelectDelete(pSelect);
sqliteIdListDelete(pColumn);
}
/*
** Generate code to do a constraint check prior to an INSERT or an UPDATE.
**
** When this routine is called, the stack contains (from bottom to top)
** the following values:
**
** 1. The recno of the row to be updated before the update. This
** value is omitted unless we are doing an UPDATE that involves a
** change to the record number.
**
** 2. The recno of the row after the update.
**
** 3. The data in the first column of the entry after the update.
**
** i. Data from middle columns...
**
** N. The data in the last column of the entry after the update.
**
** The old recno shown as entry (1) above is omitted unless both isUpdate
** and recnoChng are 1. isUpdate is true for UPDATEs and false for
** INSERTs and recnoChng is true if the record number is being changed.
**
** The code generated by this routine pushes additional entries onto
** the stack which are the keys for new index entries for the new record.
** The order of index keys is the same as the order of the indices on
** the pTable->pIndex list. A key is only created for index i if
** aIdxUsed!=0 and aIdxUsed[i]!=0.
**
** This routine also generates code to check constraints. NOT NULL,
** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
** then the appropriate action is performed. There are five possible
** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
**
** Constraint type Action What Happens
** --------------- ---------- ----------------------------------------
** any ROLLBACK The current transaction is rolled back and
** sqlite_exec() returns immediately with a
** return code of SQLITE_CONSTRAINT.
**
** any ABORT Back out changes from the current command
** only (do not do a complete rollback) then
** cause sqlite_exec() to return immediately
** with SQLITE_CONSTRAINT.
**
** any FAIL Sqlite_exec() returns immediately with a
** return code of SQLITE_CONSTRAINT. The
** transaction is not rolled back and any
** prior changes are retained.
**
** any IGNORE The record number and data is popped from
** the stack and there is an immediate jump
** to label ignoreDest.
**
** NOT NULL REPLACE The NULL value is replace by the default
** value for that column. If the default value
** is NULL, the action is the same as ABORT.
**
** UNIQUE REPLACE The other row that conflicts with the row
** being inserted is removed.
**
** CHECK REPLACE Illegal. The results in an exception.
**
** Which action to take is determined by the overrideError parameter.
** Or if overrideError==OE_Default, then the pParse->onError parameter
** is used. Or if pParse->onError==OE_Default then the onError value
** for the constraint is used.
**
** The calling routine must open a read/write cursor for pTab with
** cursor number "base". All indices of pTab must also have open
** read/write cursors with cursor number base+i for the i-th cursor.
** Except, if there is no possibility of a REPLACE action then
** cursors do not need to be open for indices where aIdxUsed[i]==0.
**
** If the isUpdate flag is true, it means that the "base" cursor is
** initially pointing to an entry that is being updated. The isUpdate
** flag causes extra code to be generated so that the "base" cursor
** is still pointing at the same entry after the routine returns.
** Without the isUpdate flag, the "base" cursor might be moved.
*/
void sqliteGenerateConstraintChecks(
Parse *pParse, /* The parser context */
Table *pTab, /* the table into which we are inserting */
int base, /* Index of a read/write cursor pointing at pTab */
char *aIdxUsed, /* Which indices are used. NULL means all are used */
int recnoChng, /* True if the record number will change */
int isUpdate, /* True for UPDATE, False for INSERT */
int overrideError, /* Override onError to this if not OE_Default */
int ignoreDest /* Jump to this label on an OE_Ignore resolution */
){
int i;
Vdbe *v;
int nCol;
int onError;
int addr;
int extra;
int iCur;
Index *pIdx;
int seenReplace = 0;
int jumpInst1, jumpInst2;
int contAddr;
int hasTwoRecnos = (isUpdate && recnoChng);
v = sqliteGetVdbe(pParse);
assert( v!=0 );
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
nCol = pTab->nCol;
/* Test all NOT NULL constraints.
*/
for(i=0; i<nCol; i++){
if( i==pTab->iPKey ){
continue;
}
onError = pTab->aCol[i].notNull;
if( onError==OE_None ) continue;
if( overrideError!=OE_Default ){
onError = overrideError;
}else if( pParse->db->onError!=OE_Default ){
onError = pParse->db->onError;
}else if( onError==OE_Default ){
onError = OE_Abort;
}
if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
onError = OE_Abort;
}
sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
switch( onError ){
case OE_Rollback:
case OE_Abort:
case OE_Fail: {
char *zMsg = 0;
sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
" may not be NULL", (char*)0);
sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
break;
}
case OE_Ignore: {
sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
break;
}
case OE_Replace: {
sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
break;
}
default: assert(0);
}
sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
}
/* Test all CHECK constraints
*/
/**** TBD ****/
/* If we have an INTEGER PRIMARY KEY, make sure the primary key
** of the new record does not previously exist. Except, if this
** is an UPDATE and the primary key is not changing, that is OK.
*/
if( recnoChng ){
onError = pTab->keyConf;
if( overrideError!=OE_Default ){
onError = overrideError;
}else if( pParse->db->onError!=OE_Default ){
onError = pParse->db->onError;
}else if( onError==OE_Default ){
onError = OE_Abort;
}
if( isUpdate ){
sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
}
sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
switch( onError ){
default: {
onError = OE_Abort;
/* Fall thru into the next case */
}
case OE_Rollback:
case OE_Abort:
case OE_Fail: {
sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
"PRIMARY KEY must be unique", P3_STATIC);
break;
}
case OE_Replace: {
sqliteGenerateRowIndexDelete(pParse->db, v, pTab, base, 0);
if( isUpdate ){
sqliteVdbeAddOp(v, OP_Dup, nCol+hasTwoRecnos, 1);
sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
}
seenReplace = 1;
break;
}
case OE_Ignore: {
assert( seenReplace==0 );
sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
break;
}
}
contAddr = sqliteVdbeCurrentAddr(v);
sqliteVdbeChangeP2(v, jumpInst2, contAddr);
if( isUpdate ){
sqliteVdbeChangeP2(v, jumpInst1, contAddr);
sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
}
}
/* Test all UNIQUE constraints by creating entries for each UNIQUE
** index and making sure that duplicate entries do not already exist.
** Add the new records to the indices as we go.
*/
extra = -1;
for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
extra++;
/* Create a key for accessing the index entry */
sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
for(i=0; i<pIdx->nColumn; i++){
int idx = pIdx->aiColumn[i];
if( idx==pTab->iPKey ){
sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
}else{
sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
}
}
jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
/* Find out what action to take in case there is an indexing conflict */
onError = pIdx->onError;
if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
if( overrideError!=OE_Default ){
onError = overrideError;
}else if( pParse->db->onError!=OE_Default ){
onError = pParse->db->onError;
}else if( onError==OE_Default ){
onError = OE_Abort;
}
if( seenReplace ){
if( onError==OE_Ignore ) onError = OE_Replace;
else if( onError==OE_Fail ) onError = OE_Abort;
}
/* Check to see if the new index entry will be unique */
sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
/* Generate code that executes if the new index entry is not unique */
switch( onError ){
case OE_Rollback:
case OE_Abort:
case OE_Fail: {
int j, n1, n2;
char zErrMsg[200];
strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
n1 = strlen(zErrMsg);
for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
n2 = strlen(zCol);
if( j>0 ){
strcpy(&zErrMsg[n1], ", ");
n1 += 2;
}
if( n1+n2>sizeof(zErrMsg)-30 ){
strcpy(&zErrMsg[n1], "...");
n1 += 3;
break;
}else{
strcpy(&zErrMsg[n1], zCol);
n1 += n2;
}
}
strcpy(&zErrMsg[n1],
pIdx->nColumn>1 ? " are not unique" : " is not unique");
sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
break;
}
case OE_Ignore: {
assert( seenReplace==0 );
sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
break;
}
case OE_Replace: {
sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
if( isUpdate ){
sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
}
seenReplace = 1;
break;
}
default: assert(0);
}
contAddr = sqliteVdbeCurrentAddr(v);
#if NULL_DISTINCT_FOR_UNIQUE
sqliteVdbeChangeP2(v, jumpInst1, contAddr);
#endif
sqliteVdbeChangeP2(v, jumpInst2, contAddr);
}
}
/*
** This routine generates code to finish the INSERT or UPDATE operation
** that was started by a prior call to sqliteGenerateConstraintChecks.
** The stack must contain keys for all active indices followed by data
** and the recno for the new entry. This routine creates the new
** entries in all indices and in the main table.
**
** The arguments to this routine should be the same as the first six
** arguments to sqliteGenerateConstraintChecks.
*/
void sqliteCompleteInsertion(
Parse *pParse, /* The parser context */
Table *pTab, /* the table into which we are inserting */
int base, /* Index of a read/write cursor pointing at pTab */
char *aIdxUsed, /* Which indices are used. NULL means all are used */
int recnoChng, /* True if the record number will change */
int isUpdate, /* True for UPDATE, False for INSERT */
int newIdx /* Index of NEW table for triggers. -1 if none */
){
int i;
Vdbe *v;
int nIdx;
Index *pIdx;
v = sqliteGetVdbe(pParse);
assert( v!=0 );
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
for(i=nIdx-1; i>=0; i--){
if( aIdxUsed && aIdxUsed[i]==0 ) continue;
sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
}
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
if( newIdx>=0 ){
sqliteVdbeAddOp(v, OP_Dup, 1, 0);
sqliteVdbeAddOp(v, OP_Dup, 1, 0);
sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
}
sqliteVdbeAddOp(v, OP_PutIntKey, base,
(pParse->trigStack?0:OPFLAG_NCHANGE) |
(isUpdate?0:OPFLAG_LASTROWID) | OPFLAG_CSCHANGE);
if( isUpdate && recnoChng ){
sqliteVdbeAddOp(v, OP_Pop, 1, 0);
}
}
/*
** Generate code that will open write cursors for a table and for all
** indices of that table. The "base" parameter is the cursor number used
** for the table. Indices are opened on subsequent cursors.
**
** Return the total number of cursors opened. This is always at least
** 1 (for the main table) plus more for each cursor.
*/
int sqliteOpenTableAndIndices(Parse *pParse, Table *pTab, int base){
int i;
Index *pIdx;
Vdbe *v = sqliteGetVdbe(pParse);
assert( v!=0 );
sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
sqliteVdbeOp3(v, OP_OpenWrite, base, pTab->tnum, pTab->zName, P3_STATIC);
for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
sqliteVdbeOp3(v, OP_OpenWrite, i+base, pIdx->tnum, pIdx->zName, P3_STATIC);
}
return i;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_ls.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vgrankul <vgrankul@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/22 11:28:19 by vgrankul #+# #+# */
/* Updated: 2020/08/14 16:04:15 by vgrankul ### ########.fr */
/* */
/* ************************************************************************** */
#include "./libft/libft.h"
#include "ft_ls.h"
void print_error(int errnum)
{
ft_printf("%s\n", strerror(errnum));
exit(EXIT_FAILURE);
}
void recursive_list(char *basepath, int *flags)
{
t_list *head;
t_list *sort;
char *tmp;
char *tmp1;
head = NULL;
tmp = NULL;
tmp1 = NULL;
create_arr(basepath, flags);
if (*flags & RE_FLAG)
{
get_path_list(&head, basepath, flags, tmp1);
sort = sort_path_list(head);
if (*flags & T_FLAG)
sort = sort_path_time_list(head, tmp);
if (*flags & R_FLAG)
sort = sort_rev_path_list(head);
while (sort != NULL)
{
ft_printf("\n%s:\n", sort->path);
recursive_list(sort->path, flags);
sort = sort->next;
}
destroy_list(head);
}
}
int main(int argc, char **argv)
{
int flags;
flags = 0;
if (argc > 1)
check_argv(argv, &flags);
else
recursive_list("./", &flags);
return (0);
}
|
C
|
/*
NAME:
Pi_mc: PI Monte Carlo
Purpose:
This program uses a Monte Carlo algorithm to compute PI as an
example of how random number generators are used to solve problems.
Note that if your goal is to find digits of pi, there are much
better algorithms you could use.
Usage:
To keep the program as simple as possible, you must edit the file
and change the value of num_trials to change the number of samples
used. Then compile and run the program.
Algorithm:
The basic idea behind the algorithm is easy to visualize. Draw a
square on a wall. Inside the square, draw a circle. Now randomly throw
darts at the wall. some darts will land inside the square. Of those,
some will fall inside the circle. The probability of landing inside
the circle or the square is proportional to their areas.
We can use a random number generator to "throw the darts" and count
how many "darts" fall inside the square and how many inside the
cicle. Dividing these two numbers gives us the ratio of their areas
and from that we can compute pi.
Algorithm details:
To turn this into code, I need a bit more detail. Assume the circle
is centered inside the square. the circle will have a radius of r and
each side of the square will be of area 2*r (i.e. the diameter of the
circle).
A(circle) = pi * r^2
A(square) = (2*r)*(2*r) = 4*r^2
ratio = A(circle)/A(square) = pi/4
Since the probability (P) of a dart falling inside a figure (i.e. the square
or the circle) is proportional to the area, we have
ratio = P(circle)/P(square) = pi/4
If I throw N darts as computed by random numbers evenly distributed
over the area of the square
P(sqaure) = N/N .... i.e. every dart lands in the square
P(circle) = N(circle)/N
ratio = (N(circle)/N)/(N/N) = N(circle)/N
Hence, to find the area, I compute N random "darts" and count how many fall
inside the circle. The equation for a circle is
x^2 + y^2 = r^2
So I randomly compute "x" and "y" evenly distributed from -r to r and
count the "dart" as falling inside the cicle if
x^2 + y^2 < or = r
Results:
Remember, our goal is to demonstrate a simple monte carlo algorithm,
not compute pi. But just for the record, here are some results (Intel
compiler version 10.0, Windows XP, core duo laptop)
100 3.160000
1000 3.148000
10000 3.154000
100000 3.139920
1000000 3.141456
10000000 3.141590
100000000 3.141581
As a point of reference, the first 7 digits of the true value of pi
is 3.141592
History:
Written by Tim Mattson, 9/2007.
*/
#include <stdio.h>
#include <omp.h>
#include "random.h"
//
// The monte carlo pi program
//
static long num_trials = 100000000;
int main ()
{
long i; long Ncirc = 0;
double pi, x, y, test;
double r = 1.0; // radius of circle. Side of squrare is 2*r
range(-r, r); // The circle and square are centered at the origin
double time = omp_get_wtime();
for(i=0;i<num_trials; i++)
{
x = drandom();
y = drandom();
test = x*x + y*y;
if (test <= r*r) Ncirc++;
}
pi = 4.0 * ((double)Ncirc/(double)num_trials);
printf("\n %ld trials, pi is %lf ",num_trials, pi);
printf(" in %lf seconds\n",omp_get_wtime()-time);
return 0;
}
|
C
|
/**********************************************************************
* parcoursEnLargeur.c
*
* (Djebien Tarik) <tarik.djebien@etudiant.univ-lille1.fr>
*
* PROCEDURE en_largeur(G,s)
* Parcours en largeur d'abord de la composante connexe s,
* sans tenir compte des orientations.
* DEBUT
* colorier en bleu tous les sommets sauf s.
* vider la file.
* colorier s en vert et l'enfiler.
* TANT QUE la file n'est pas vide FAIRE
* defiler x
* POUR TOUT voisin y de x FAIRE
* SI y est bleu ALORS
* colorier y en vert et l'enfiler
* FINSI
* FINPOUR
* colorier x en rouge
* FINTQ
* FINPROCEDURE
***********************************************************************/
/* Ce programme prend un nom de graphe en entrée et un départ,le charge,
et creer la visualisation du parcours en largeur du graphe.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "sys/wait.h" /* necessaire pour la macro WEXITSTATUS */
#include "graphe.h"
/* Couleurs */
typedef enum {ROUGE=0, BLEU=1, VERT=2} tCouleur;
typedef tCouleur tTabCouleurs[MAX_SOMMETS];
void graphe2visuCouleurs(tGraphe g,char *outfile,tTabCouleurs t){
FILE *fic;
int res;
char couleur[20];
char commande[80];
char dotfile[80]; /* le fichier .dot pour créer le .ps */
char psfile[80]; /* le fichier .ps pour lancer evince nomFichier.ps */
tNomSommet origine,destination,nom;
tNumeroSommet i;
tArc arc;
/* On va creer un fichier pour graphviz, dans le fichier "outfile".dot */
strcpy(dotfile,outfile);
strcpy(psfile,outfile);
strcat(dotfile,".dot"); /* extension .dot */
strcat(psfile,".ps"); /* extension .ps */
fic = fopen(dotfile,"w"); /* Ouverture du fichier en droit en ecriture */
if (fic == NULL)
halt("Ouverture du fichier %s en ecriture impossible\n.",dotfile);
if (grapheEstOriente(g))
fprintf(fic,"digraph{\n");
else
fprintf(fic,"graph{\n");
for(i=0;i<grapheNbSommets(g);i++){
grapheRecupNomSommet(g,i,nom);
switch (t[i]){
case ROUGE : strcpy(couleur,"red");break;
case BLEU : strcpy(couleur,"blue");break;
case VERT : strcpy(couleur,"green");break;
default : strcpy(couleur,"black");break;
}
fprintf(fic,"%s [color=%s]\n",nom,couleur);
}
for(i=0; i < grapheNbArcs(g); i++) {
arc = grapheRecupArcNumero(g,i);
grapheRecupNomSommet(g,arc.orig,origine);
grapheRecupNomSommet(g,arc.dest,destination);
if (grapheEstOriente(g))
fprintf(fic,"%s -> %s\n",origine,destination);
else
fprintf(fic,"%s -- %s\n",origine,destination);
}
fprintf(fic,"}");
fclose(fic); /* Fermeture du fichier */
sprintf(commande, "dot -Tps %s -o %s", dotfile,psfile);
res = system(commande);
if (WEXITSTATUS(res))
halt("La commande suivante a echoue :\n %s \n",commande);
}
void
en_largeur
(tGraphe G,tNomSommet s,char* outfile){
tNumeroSommet i,x,y;
tNomSommet nom;
tTabCouleurs tab;
tFileSommets F;
printf("PARCOURS EN LARGEUR : \n");
// colorier en bleu tous les sommets sauf s.
for(i=0;i<grapheNbSommets(G);i++){
grapheRecupNomSommet(G,i,nom);
if(strcmp(nom,s)!=0)
tab[i]=BLEU;
}
graphe2visuCouleurs(G,outfile,tab);
getchar();
// vider la file
F = fileSommetsAlloue();
//colorier s en vert et l'enfiler.
i=grapheChercheSommetParNom(G,s);
tab[i]=VERT;
graphe2visuCouleurs(G,outfile,tab);
getchar();
fileSommetsEnfile(F,i);
if (grapheEstOriente(G)){
// TANT QUE la file n'est pas vide FAIRE
while (!(fileSommetsEstVide(F))) {
// defiler x
x = fileSommetsDefile(F);
// POUR TOUT voisin y de x FAIRE
for(i=0;i<grapheNbSuccesseursSommet(G,x);i++){
y = grapheSuccesseurSommetNumero(G,x,i);
// SI y est bleu ALORS
if (tab[y]==BLEU) {
// colorier y en vert et l'enfiler
tab[y]=VERT;
graphe2visuCouleurs(G,outfile,tab);
getchar();
fileSommetsEnfile(F,y);
}
// FINSI
}
// FINPOUR
// colorier x en rouge
tab[x]= ROUGE;
graphe2visuCouleurs(G,outfile,tab);
getchar();
grapheRecupNomSommet(G,x,nom);
printf(" %s ",nom);
}
// FINTQ
}
else
{
// TANT QUE la file n'est pas vide FAIRE
while (!(fileSommetsEstVide(F))) {
// defiler x
x = fileSommetsDefile(F);
// POUR TOUT voisin y de x FAIRE
for(i=0;i<grapheNbVoisinsSommet(G,x);i++){
y = grapheVoisinSommetNumero(G,x,i);
// SI y est bleu ALORS
if (tab[y]==BLEU) {
// colorier y en vert et l'enfiler
tab[y]=VERT;
graphe2visuCouleurs(G,outfile,tab);
getchar();
fileSommetsEnfile(F,y);
}
// FINSI
}
// FINPOUR
// colorier x en rouge
tab[x]= ROUGE;
graphe2visuCouleurs(G,outfile,tab);
getchar();
grapheRecupNomSommet(G,x,nom);
printf(" %s ",nom);
}
// FINTQ
}
printf("\n");
}
int main(int argc, char *argv[]) {
tGraphe graphe;
tNomSommet depart;
char* visu;
char nomGraphe[80];
if (argc != 3) {
halt("Usage : %s <FichierGraphe>.grp <SommetDepart> \n", argv[0]);
}
/* On récupere <nomDuGraphe>.grp en parametre */
strcpy(nomGraphe,argv[1]);
visu = strtok (nomGraphe,".");
/* On cree les fichier <nomDuGraphe>.dot et <nomDuGraphe>.ps */
graphe = grapheAlloue();
grapheChargeFichier(graphe, argv[1]);
strcpy(depart,argv[2]);
en_largeur(graphe,depart,visu);
grapheLibere(graphe);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
int minWire(int, int, int*);
int main()
{
int t, n, c, i, j, Arr[100000], dummy[100000], wire = 0, check = 0;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
c = getchar();
i = 0;
while((c = getchar()) != '\n')
{
if(c == '0')
;
else
{
dummy[check] = i;
check++;
}
i++;
}
for(i = 0; i < n; i++)
scanf("%d", &Arr[i]);
wire += Arr[dummy[0]] - Arr[0] + Arr[n - 1] - Arr[dummy[check - 1]];
for(j = 0; j < check - 1; j++)
wire += minWire(dummy[j], dummy[j + 1], Arr);
printf("%d\n", wire);
wire = check = 0;
}
}
int minWire(int a, int b, int *A)
{
int min = 1000000000, j = 0, Sum[100000], Sum2[100000], sum = 0, i;
j = 0;
for(i = a; i < b; i++)
{
Sum[j] = A[i] - A[a];
j++;
}
j = 0;
for(i = a + 1; i <= b; i++)
{
Sum2[j] = A[b] - A[i];
j++;
}
for(i = 0; i < b - a; i++)
{
if( min > Sum[i] + Sum2[i])
min = Sum[i] + Sum2[i];
}
return min;
}
|
C
|
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc == 1) {
system("echo $HOME");
//if (fork() == 0)
system("./Terminar 100 &");
//if (fork() == 0)
system("./Terminar 5 &");
}
sleep(argc > 1 ? atoi(argv[1]) : 200);
kill(0, SIGKILL);
return 0;
}
|
C
|
/*******************************************************************************
* File : 1947.c
* Author : tainzhi
* Mail : qfq61@qq.com
* Created : 2017-04-17 13:23:51
* Modified : 2017-04-17 13:26:54
*******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 200
int father[MAX_SIZE], son[MAX_SIZE], brother[MAX_SIZE];
int dp[MAX_SIZE][MAX_SIZE];
int n, p;
int max_int = 1000000;
int Min(int a, int b) {
return a < b ? a : b;
}
void DFS(int root) {
dp[root][1] = 0;
int child, tmp;
child = son[root];
while (child != 0) {
DFS(child);
for (int i = p; i >= 1; --i) {
tmp = dp[root][i] + 1;
for (int j = 1; j < i; ++j) {
tmp = Min(tmp, dp[child][j] + dp[root][i-j]);
}
dp[root][i] = tmp;
}
child = brother[child];
}
}
int main() {
while (scanf("%d %d", &n, &p) != EOF) {
memset(father, 0, sizeof(father));
memset(son, 0, sizeof(son));
int u, v;
for (int i = 0; i < n - 1; ++i) {
scanf("%d %d", &u, &v);
father[v] = 1;
brother[v] = son[u];
son[u] = v;
}
for (int i = 1; i <= n; ++i)
for (int j = 0; j <= p; ++j)
dp[i][j] = max_int;
int root = -1;
for (int i = 1; i <= n; ++i)
if (!father[i]) {
root = i;
break;
}
DFS(root);
int ans = dp[root][p];
for (int i = 1; i <= n; ++i)
ans = Min(ans, dp[i][p] + 1);
printf("%d\n", ans);
}
return 0;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* main - Entry point
*
* Return: Always 0 (Success)
*/
int main(void)
{
long num = 612852475143;
int i = 2;
int max = 0;
while (num != 1)
{
while (num % i == 0)
{
if (i > max)
max = i;
num = num / i;
}
i++;
}
printf("%d\n", max);
return (0);
}
|
C
|
#include <stdio.h>
#include <string.h>
void main (void)
{
char *(*puntero[10])(char&,char (*)(char),char,char *);
char info[]="Esto es una prueba";
printf ("%d",sizeof(char)*(strlen(info)-2));
}
|
C
|
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include "util.h"
int main(int argc, char const *argv[]) {
if (argc != 3) {
printf("usage: [exec] [point num] [thread num]\n");
return -1;
}
int pnt_nums, thread_nums;
sscanf(argv[1], "%d", &pnt_nums);
sscanf(argv[2], "%d", &thread_nums);
srand (time(NULL));
// Use reduce to protect pnt_in_cc
int pnt_in_cc = 0;
// int* pnt_in_cc = (int*)malloc(sizeof(int)*thread_nums);
clock_t begin = clock();
int i;
#pragma omp parallel for num_threads(thread_nums) reduction(+:pnt_in_cc)
for (i=0; i<pnt_nums; i++) {
double x = RandDouble(0, 1);
double y = RandDouble(0, 1);
if (InCircle(x, y)) {
pnt_in_cc += 1;
}
}
clock_t end = clock();
clock_t time_spent = end - begin;
double pi = pnt_in_cc*1.0/pnt_nums;
pi *= 4.0;
printf("%d points get %lf take %ld ms\n", pnt_nums, pi, time_spent);
return 0;
}
|
C
|
#include<stdio.h>
void f();
void b();
int qunju = 5;
int main()
{
f();
f();
b();
return 0;
}
void f()
{ static int a = 1;//static声明后a为全局变量 但是针对函数内是初始化 1 次,再次调用时结束值
//其他函数 不可以调用此值
//概括就是 全局变量是 全局的生存期 本地的作用域
//全局变量呢 地址都是放在一起的 一次排列 而 对于局部变量他存放的地址 和 全局变量的地址有很大的差别
printf("%d\n",a);
printf("地址 = %p\n%p\n",&a,&quanju);
a+=1;
printf("%d\n",a);
}
void b()
{
//cishi
}
void view()
{ int a = 1;
{
static int a = 2;
printf("%d",a);
printf("%s",__func__);//打印当前函数的名字view
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
printf("Vvedite n\n");
int n;
scanf("%d", &n);
int k = 1;
for(int i = n - 1; i >= 0; i--){
for(int j = 0; j < i; j++)
printf(" ");
for(int j = 0; j < k; j++)
printf("*");
for(int j = 0; j < i; j++)
printf(" ");
printf("\n");
k = k + 2;
}
printf("%d", n);
return 0;
}
|
C
|
#include <stdio.h>
#define MAXN 40
int n;
int a[MAXN][MAXN];
int main()
{
int i, j;
scanf("%d", &n);
a[0][0] = 1;
for (i = 0; i < n; ++i)
{
a[i][0] = a[i][i] = 1;
for (j = 1; j < i; ++j)
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
for (i = 0; i < n; ++i)
{
for (j = 0; j <= i; ++j)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
clrscr();
int n;
printf("\nEnter a no");
scanf(%d,&n);
if(n==0)
{
printf("no is zero:);
}
else if(n%2==0)
{
printf("even no");
}
else
{
printf("odd no");
}
}
|
C
|
/***************************************************************************
server.c
Version: 2.25
Wed Aug 31 10:33:22 2011
Copyright 2011 Karolina, Patricia, Pedro
Email: {karol.milano, lvlayumi, ptersnow}@gmail.com
****************************************************************************/
#include "httpd.h"
char *
get_mime_type(char *name)
{
char *ext = strrchr(name, '.');
if(!ext) {
free(ext);
return "application/octet-stream";
}
if(strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) {
free(ext);
return "text/html";
}
if(strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) {
free(ext);
return "image/jpeg";
}
if(strcmp(ext, ".css") == 0) {
free(ext);
return "text/css";
}
if(strcmp(ext, ".pdf") == 0) {
free(ext);
return "application/pdf";
}
free(ext);
return "application/octet-stream";
}
void
send_headers(int sock, int status, char *title, char *mime, int length)
{
char *aux;
char header[4096];
sprintf(header, "%s %d %s\r\nServer: %s\r\n \
Content-Type: %s\r\n", PROTOCOL, status, title, SERVER,
(mime != NULL) ? mime : "text/plain");
if(length >= 0) {
asprintf(&aux, "Content-Length: %d\r\n", length);
strcat(header, aux);
free(aux);
}
strcat(header, "\r\n");
send(sock, header, strlen(header), 0);
}
void
send_error(int sock, int status, char *title, char *text)
{
char *error;
send_headers(sock, status, title, "text/html", -1);
asprintf(&error, "<html>\n<head><title>%d %s</title></head>\n \
<body><h4>%d %s</h4>%s</body>\n</html>\n", status, title,
status, title, text);
send(sock, error, strlen(error), 0);
free(error);
}
void
send_file(int sock, char *method, char *path, struct stat *statbuf)
{
FILE *fp = fopen(path, "r");
int n, length;
char data[4096];
printf("OPEN\n");
if (!fp)
send_error(sock, 403, "Forbidden", "Access denied.");
else
{
length = S_ISREG(statbuf->st_mode) ? statbuf->st_size : -1;
send_headers(sock, 200, "OK", get_mime_type(path), length);
if(!memcmp(method, "GET", 3))
while((n = fread(data, 1, sizeof(data), fp)) > 0)
send(sock, data, sizeof(char) * n, 0);
fclose(fp);
}
}
void
perror_exit(const char *msg)
{
perror(msg);
_exit(1);
}
void
usage(char *exec)
{
printf("\nUsage: %s <options> \
\nwhere possible options include:\n \
\r -f <port> \t\t Specify the port where the server will run.\n \
\r -t <N> <port> \t\t Generate <N> threads to run.\n\n", exec);
_exit(1);
}
|
C
|
/*
Copyright (c) 2019-2020, Adrien BLASSIAU and Corentin JUVIGNY
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "include.h"
#include "sort.h"
#define CAPACITY 100
#define N 10
int main(int argc,char* argv[])
{
int i,n;
int tab[CAPACITY] = {[0 ... CAPACITY-1] = 0};
int sorted_tab[CAPACITY] = {[0 ... CAPACITY-1] = 0};
size_t cutpoints[CAPACITY];
size_t cutlength;
if ((argc = argc > N ? N : argc-1) < 3) {
srand(time(NULL));
for (i = 0, n = N; i < N; i++)
tab[i] = rand()%20;
} else {
for (i = 0, argv=argv+1, n = argc; i < argc; i++)
tab[i] = strtol(argv[i],NULL,0);
}
//Include your code here
cutlength = monotonic(tab,n,cutpoints);
for (i = 0; i < n; i++) printf("%d ",tab[i]);
printf("\n");
reverse(tab,n,cutpoints,cutlength);
for (i = 0; i < n; i++) printf("%d ",tab[i]);
printf("\n");
merge(tab,n,sorted_tab,cutpoints,cutlength);
for (i = 0; i < n; i++) printf("%d ",tab[i]);
printf("\n");
return 0;
}
|
C
|
#define N 6
extern char gameboard[N][N];
extern int ROWS, COLS;
extern int turn;
extern int fW, fE, fN, fS, fNW, fNE, fSW, fSE;
void flip_condition() {
int i, k, l; //for
if(turn==0) { //
if(ROWS<N-2&&gameboard[ROWS+1][COLS]=='X'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS+k][COLS]=='X'&&gameboard[ROWS+k+1][COLS]=='O')//θ ִ Ȯ
for(i=1;i<N-1;i++){
if(ROWS+k<N-1) { //ROWS+k>=N-1̸ ̻ ʿ ִ θ
if(gameboard[ROWS+i][COLS]=='X') {
gameboard[ROWS+i][COLS]='O'; //ǿ ´ ٲٱ
fS++; //ٲ
gameboard[ROWS][COLS]='O';
continue; //شǴ ٲٱ
}
else if(gameboard[ROWS+i][COLS]=='O')
break; // ٲ
}
}
}
}
if(ROWS>1&&gameboard[ROWS-1][COLS]=='X'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS-k][COLS]=='X'&&gameboard[ROWS-k-1][COLS]=='O')
for(i=1;i<N-1;i++){
if(ROWS-k>0) {
if(gameboard[ROWS-i][COLS]=='X'){
gameboard[ROWS-i][COLS]='O';
fN++;
gameboard[ROWS][COLS]='O';
continue;
}
else if(gameboard[ROWS-i][COLS]=='O')
break;
}
}
}
}
if(COLS>1&&gameboard[ROWS][COLS-1]=='X'){ //
for(k=1;k<N-1;k++){
if(gameboard[ROWS][COLS-k]=='X'&&gameboard[ROWS][COLS-k-1]=='O')
for(i=1;i<N-1;i++){
if(COLS-k>0) {
if(gameboard[ROWS][COLS-i]=='X'){
gameboard[ROWS][COLS-i]='O';
fW++;
gameboard[ROWS][COLS]='O';
continue;
}
else if(gameboard[ROWS][COLS-i]=='O')
break;
}
}
}
}
if(COLS<N-2&&gameboard[ROWS][COLS+1]=='X'){ //
for(k=1;k<N-1;k++){
if(gameboard[ROWS][COLS+k]=='X'&&gameboard[ROWS][COLS+k+1]=='O')
for(i=1;i<N-1;i++){
if(COLS+k<N-1) {
if(gameboard[ROWS][COLS+i]=='X'){
gameboard[ROWS][COLS+i]='O';
fE++;
gameboard[ROWS][COLS]='O';
continue;
}
else if(gameboard[ROWS][COLS+i]=='O')
break;
}
}
}
}
if(ROWS>1&&COLS>1&&gameboard[ROWS-1][COLS-1]=='X'){ //ϼ
for(k=1;k<N-1;k++) {
if(gameboard[ROWS-k][COLS-k]=='X'&&gameboard[ROWS-k-1][COLS-k-1]=='O')
for(i=1;i<N-1;i++) {
if(ROWS-k>0&&COLS-k>0) {
if(gameboard[ROWS-i][COLS-i]=='X'){
gameboard[ROWS-i][COLS-i]='O';
fNW++;
gameboard[ROWS][COLS]='O';
continue;
}
else if(gameboard[ROWS-i][COLS-i]=='O')
break;
}
}
}
}
if(ROWS>1&&COLS<N-2&&gameboard[ROWS-1][COLS+1]=='X'){ //ϵ
for(k=1;k<N-1;k++) {
if(gameboard[ROWS-k][COLS+k]=='X'&&gameboard[ROWS-k-1][COLS+k+1]=='O')
for(i=1;i<N-1;i++) {
if(ROWS-k>0&&COLS+k<N-1) {
if(gameboard[ROWS-i][COLS+i]=='X'){
gameboard[ROWS-i][COLS+i]='O';
fNE++;
gameboard[ROWS][COLS]='O';
continue;
}
else if(gameboard[ROWS-i][COLS+i]=='O')
break;
}
}
}
}
if(ROWS<N-2&&COLS>1&&gameboard[ROWS+1][COLS-1]=='X'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS+k][COLS-k]=='X'&&gameboard[ROWS+k+1][COLS-k-1]=='O')
for(i=1;i<N-1;i++) {
if(ROWS+k<N-1&&COLS-k>0) {
if(gameboard[ROWS+i][COLS-i]=='X'){
gameboard[ROWS+i][COLS-i]='O';
fSW++;
gameboard[ROWS][COLS]='O';
continue;
}
else if(gameboard[ROWS+i][COLS-i]=='O')
break;
}
}
}
}
if(ROWS<N-2&&COLS<N-2&&gameboard[ROWS+1][COLS+1]=='X'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS+k][COLS+k]=='X'&&gameboard[ROWS+k+1][COLS+k+1]=='O')
for(i=1;i<N-1;i++) {
if(ROWS+k<N-1&&COLS+k<N-1) {
if(gameboard[ROWS+i][COLS+i]=='X'){
gameboard[ROWS+i][COLS+i]='O';
fSE++;
gameboard[ROWS][COLS]='O';
continue;
}
else if(gameboard[ROWS+i][COLS+i]=='O')
break;
}
}
}
}
}
else if(turn==1) { //
if(ROWS<N-2&&gameboard[ROWS+1][COLS]=='O'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS+k][COLS]=='O'&&gameboard[ROWS+k+1][COLS]=='X')
for(i=1;i<N-1;i++){
if(ROWS+k<N-1) {
if(gameboard[ROWS+i][COLS]=='O') {
gameboard[ROWS+i][COLS]='X';
fS++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS+i][COLS]=='X')
break;
}
}
}
}
if(ROWS>1&&gameboard[ROWS-1][COLS]=='O'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS-k][COLS]=='O'&&gameboard[ROWS-k-1][COLS]=='X')
for(i=1;i<N-1;i++){
if(ROWS-k>0) {
if(gameboard[ROWS-i][COLS]=='O'){
gameboard[ROWS-i][COLS]='X';
fN++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS-i][COLS]=='X')
break;
}
}
}
}
if(COLS>1&&gameboard[ROWS][COLS-1]=='O'){ //
for(k=1;k<N-1;k++){
if(gameboard[ROWS][COLS-k]=='O'&&gameboard[ROWS][COLS-k-1]=='X')
for(i=1;i<N-1;i++){
if(COLS-k>0) {
if(gameboard[ROWS][COLS-i]=='O'){
gameboard[ROWS][COLS-i]='X';
fW++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS][COLS-i]=='X')
break;
}
}
}
}
if(COLS<N-2&&gameboard[ROWS][COLS+1]=='O'){ //
for(k=1;k<N-1;k++){
if(gameboard[ROWS][COLS+k]=='O'&&gameboard[ROWS][COLS+k+1]=='X')
for(i=1;i<N-1;i++){
if(COLS+k<N-1) {
if(gameboard[ROWS][COLS+i]=='O'){
gameboard[ROWS][COLS+i]='X';
fE++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS][COLS+i]=='X')
break;
}
}
}
}
if(ROWS>1&&COLS>1&&gameboard[ROWS-1][COLS-1]=='O'){ //ϼ
for(k=1;k<N-1;k++) {
if(gameboard[ROWS-k][COLS-k]=='O'&&gameboard[ROWS-k-1][COLS-k-1]=='X')
for(i=1;i<N-1;i++) {
if(ROWS-k>0&&COLS-k>0) {
if(gameboard[ROWS-i][COLS-i]=='O'){
gameboard[ROWS-i][COLS-i]='X';
fNW++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS-i][COLS-i]=='X')
break;
}
}
}
}
if(ROWS>1&&COLS<N-2&&gameboard[ROWS-1][COLS+1]=='O'){ //ϵ
for(k=1;k<N-1;k++) {
if(gameboard[ROWS-k][COLS+k]=='O'&&gameboard[ROWS-k-1][COLS+k+1]=='X')
for(i=1;i<N-1;i++) {
if(ROWS-k>0&&COLS+k<N-1) {
if(gameboard[ROWS-i][COLS+i]=='O'){
gameboard[ROWS-i][COLS+i]='X';
fNE++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS-i][COLS+i]=='X')
break;
}
}
}
}
if(ROWS<N-2&&COLS>1&&gameboard[ROWS+1][COLS-1]=='O'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS+k][COLS-k]=='O'&&gameboard[ROWS+k+1][COLS-k-1]=='X')
for(i=1;i<N-1;i++) {
if(ROWS+k<N-1&&COLS-k>0) {
if(gameboard[ROWS+i][COLS-i]=='O'){
gameboard[ROWS+i][COLS-i]='X';
fSW++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS+i][COLS-i]=='X')
break;
}
}
}
}
if(ROWS<N-2&&COLS<N-2&&gameboard[ROWS+1][COLS+1]=='O'){ //
for(k=1;k<N-1;k++) {
if(gameboard[ROWS+k][COLS+k]=='O'&&gameboard[ROWS+k+1][COLS+k+1]=='X')
for(i=1;i<N-1;i++) {
if(ROWS+k<N-1&&COLS+k<N-1) {
if(gameboard[ROWS+i][COLS+i]=='O'){
gameboard[ROWS+i][COLS+i]='X';
fSE++;
gameboard[ROWS][COLS]='X';
continue;
}
else if(gameboard[ROWS+i][COLS+i]=='X')
break;
}
}
}
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netdb.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<fcntl.h>
#include<unistd.h>
//#define PORT_NUM 8887
#define MESSAGE_MAX_LEN 99999
#define PAYLOAD_MAX_LEN 9999
#define PATH_MAX_LEN 9999
char PORT_NUM[4] = "8887";
char _400Error[26] = "HTTP/1.0 400 Bad Request\n";
char _404Error[27] = "HTTP/1.0 404 Not Found\r\n\r\n";
char _405Error[33] = "HTTP/1.0 405 Method Not Allowed\n";
char _200OK[20] = "HTTP/1.0 200 OK\r\n\r\n";
char _404Message[60] = "<!DOCTYPE html>\n<html>\n<body>404 Not Found</body>\n</html>";
void setServer(char *port, int* socknum)
{
int sockOpt = 1;
struct addrinfo hints, *res, *ips;
memset(&hints, 0, sizeof(hints)); //hints를 0으로 초기화.
hints.ai_family = AF_INET; //IPv4 주소체계
hints.ai_socktype = SOCK_STREAM; //http는 TCP를 사용하므로.
hints.ai_flags = AI_PASSIVE;
if(getaddrinfo(NULL, port, &hints, &res)){
perror("Error : getaddrinfo function error. \n");
return;
}
//이건 공부용으로 해놓은 코드.
//addrinfo 구조체에 ai_next가 있는 이유 : 하나의 호스트가, 여러 ip주소를 가질 수 있기 때문이다.
//아래의 코드는 여러 ip주소에 서버 소켓을 생성하는 작업.
for(ips = res; ips != NULL; ips = ips->ai_next){
*socknum = socket(ips->ai_family,ips->ai_socktype, 0);
setsockopt(*socknum, SOL_SOCKET, SO_REUSEADDR, &sockOpt, sizeof(sockOpt)); //bind Error 해결
if(*socknum == -1){ //소켓 생성 실패 했을 때,
continue;
}
if(bind(*socknum, ips->ai_addr, ips->ai_addrlen) == 0 ){ //소켓이 생성되었고, bind까지 성공했을때,
break;
}
}
freeaddrinfo(res); //res 구조체를free.
if(listen(*socknum, 100000) != 0){
perror("listen() error\n");
exit(1);
}
}
void response(int clientSockfd, char *root)
{
char msg[MESSAGE_MAX_LEN];
char *header[3];
char payload[PAYLOAD_MAX_LEN];
int rcvbyte;
int fd;
int readbytes;
memset( (void*)msg, (int)'\0', MESSAGE_MAX_LEN); //메시지를 받을 버퍼 초기화.
rcvbyte = recv(clientSockfd, msg, MESSAGE_MAX_LEN, 0); //메시지 수신
if(rcvbyte == -1){
fprintf(stderr, "Error : recv function Error.\n");
}
else if(rcvbyte == 0 ){
fprintf(stderr, "Error : 0 byte received. \n");
}
else{
printf("--------[REQUEST MESSAGE]-------------\n");
printf("%s\n", msg); //수신한 메시지를 출력
printf("%d\n", strlen(msg));
printf("--------------------------------------\n");
header[0] = strtok(msg, " \n\t"); //Request 메시지의 메소드가 들어감. ex) GET
if(strncmp(header[0], "GET", 3) == 0){
header[1] = strtok(NULL, " \t\n");
header[2] = strtok(NULL, " \t\n");
if(strcmp(header[1], "/") == 0){
header[1] = "./index.html";
}
if( header[2] == NULL || header[1] == NULL){
printf("%s\n", _400Error);
write(clientSockfd, _400Error, strlen(_400Error));
}
else if(strncmp(header[2], "HTTP/1.0", 8) != 0 && strncmp(header[2], "HTTP/1.1", 8) != 0){
printf("%s\n", _400Error);
write(clientSockfd, _400Error, strlen(_400Error));
}
else{
printf("file open:%s\n", header[1]); // 파일을 열것임을 출력.
if((fd = open(header[1], O_RDONLY)) != -1){
printf("%s\n",_200OK); //200OK 출력
send(clientSockfd, _200OK, strlen(_200OK), 0);
while( (readbytes = read(fd,payload, PAYLOAD_MAX_LEN)) > 0 ){
write(clientSockfd, payload, readbytes);
}
}
else{
printf("%s\n",_404Error);
send(clientSockfd, _404Error, strlen(_404Error), 0);
strcpy(payload, _404Message);
write(clientSockfd, payload, strlen(_404Message));
}
}
}
else{
printf("%s\n", _400Error);
write(clientSockfd, _400Error, strlen(_400Error));
}
}
shutdown(clientSockfd, SHUT_RDWR);
close(clientSockfd);
clientSockfd = -1;
}
int main(int argc, char argv[])
{
int socknum; //소켓 식별자
struct sockaddr_in clientaddr;
char port[6]; //strcpy를 사용해야되나?
char root[PATH_MAX_LEN];
int clientSockfd;
socklen_t addrlen;
int i;
strcpy(root, getenv("PWD"));//현재 디렉토리를 root에 받아옴
strcpy(port, PORT_NUM); //port번호 설정
(char*)malloc(strlen(root)*sizeof(char)); //root 설정
printf("--------------[CURRENT DIRECTORY PATH]------------\n");
printf("%s\n", root);
printf("--------------------------------------------------\n");
printf("서버 설정을 시작합니다.\n");
setServer(port, &socknum); //서버를 설정한다.
printf("서버 설정이 완료됐습니다.\n");
while(1){
addrlen = sizeof(clientaddr);
clientSockfd = accept(socknum, (struct sockaddr *)&clientaddr, &addrlen);
if(clientSockfd == -1){
printf("Error : accept 에러\n");
}
response(clientSockfd, root); //respond
}
printf("서버가 종료되었습니다\n");
return 0;
}
|
C
|
#include "cbase.h"
void buffer_assign_data_fast(Buffer *buffer, const char *bytes, size_t len) {
array_assign_fast(&buffer->array, bytes, len);
}
bool buffer_assign_data(Buffer *buffer, const char *bytes, size_t len,
Status *status) {
return array_assign(&buffer->array, bytes, len, status);
}
void buffer_assign_buffer_fast(Buffer *dst, Buffer *src) {
array_assign_array_same_fast(&dst->array, &src->array);
}
bool buffer_assign_buffer(Buffer *dst, Buffer *src, Status *status) {
return array_assign_array_same(&dst->array, &src->array, status);
}
void buffer_assign_slice_fast(Buffer *buffer, Slice *slice) {
array_assign_fast(&buffer->array, slice->data, slice->len);
}
bool buffer_assign_slice(Buffer *buffer, Slice *slice, Status *status) {
return array_assign(&buffer->array, slice->data, slice->len, status);
}
bool buffer_ensure_capacity(Buffer *buffer, size_t len, Status *status) {
return array_ensure_capacity(&buffer->array, len, status);
}
bool buffer_set_size(Buffer *buffer, size_t len, Status *status) {
return array_set_size(&buffer->array, len, status);
}
void buffer_init(Buffer *buffer) {
array_init(&buffer->array, sizeof(char));
}
bool buffer_init_alloc(Buffer *buffer, size_t alloc, Status *status) {
return array_init_alloc(&buffer->array, alloc, sizeof(char), status);
}
bool buffer_init_from_data(Buffer *buffer, const char *data, size_t len,
Status *status) {
return (
buffer_init_alloc(buffer, len, status) &&
buffer_assign_data(buffer, data, len, status)
);
}
bool buffer_new(Buffer **buffer, Status *status) {
if (!cbmalloc(1, sizeof(Buffer), buffer, status)) {
return status_propagate(status);
}
buffer_init(*buffer);
return status_ok(status);
}
bool buffer_new_alloc(Buffer **buffer, size_t alloc, Status *status) {
return (
buffer_new(buffer, status) &&
buffer_ensure_capacity(*buffer, alloc, status)
);
}
bool buffer_new_from_data(Buffer **buffer, const char *data, size_t len,
Status *status) {
return (
buffer_new_alloc(buffer, len, status) &&
buffer_assign_data(*buffer, data, len, status)
);
}
bool buffer_compact(Buffer *buffer, Status *status) {
return array_compact(&buffer->array, status);
}
bool buffer_equals_data_at_fast(Buffer *buffer, size_t index,
const void *data,
size_t len) {
return memcmp(array_index_fast(&buffer->array, index), data, len) == 0;
}
bool buffer_equals_data_at(Buffer *buffer, size_t index, const void *data,
size_t len,
bool *equal,
Status *status) {
if ((index + len) > buffer->array.len) {
return index_out_of_bounds(status);
}
*equal = buffer_equals_data_at_fast(buffer, index, data, len);
return true;
}
bool buffer_equals_data(Buffer *buffer, const char *data, size_t len) {
return buffer_equals_data_at_fast(buffer, 0, data, len);
}
bool buffer_equals_buffer(Buffer *b1, Buffer *b2) {
return (
(b1->array.len == b2->array.len) &&
buffer_equals_data(b1, b2->array.elements, b1->array.len)
);
}
bool buffer_starts_with_data_fast(Buffer *buffer, const void *data,
size_t len) {
return buffer_equals_data_at_fast(buffer, 0, data, len);
}
bool buffer_starts_with_data(Buffer *buffer, const void *data,
size_t len,
bool *equal,
Status *status) {
return buffer_equals_data_at(buffer, 0, data, len, equal, status);
}
bool buffer_ends_with_data_fast(Buffer *buffer, const void *data, size_t len) {
return buffer_equals_data_at_fast(buffer, buffer->array.len - len, data,
len);
}
bool buffer_ends_with_data(Buffer *buffer, const void *data, size_t len,
bool *equal,
Status *status) {
if (len > buffer->array.len) {
return index_out_of_bounds(status);
}
*equal = buffer_ends_with_data_fast(buffer, data, len);
return status_ok(status);
}
void buffer_read_fast(Buffer *buffer, size_t index, size_t len, void *out) {
array_copy_elements_fast(&buffer->array, index, len, out);
}
bool buffer_read(Buffer *buffer, size_t index, size_t len, void *out,
Status *status) {
return array_copy_elements(&buffer->array, index, len, out, status);
}
void buffer_slice_fast(Buffer *buffer, size_t index, size_t len,
Slice *slice) {
slice->data = array_index_fast(&buffer->array, index);
slice->len = len;
}
bool buffer_slice(Buffer *buffer, size_t index, size_t len,
Slice *slice,
Status *status) {
if ((index + len) > buffer->array.len) {
return index_out_of_bounds(status);
}
buffer_slice_fast(buffer, index, len, slice);
return status_ok(status);
}
void buffer_slice_full(Buffer *buffer, Slice *slice) {
slice->data = buffer->array.elements;
slice->len = buffer->array.len;
}
void buffer_delete_fast(Buffer *buffer, size_t index, size_t len) {
array_delete_many_fast(&buffer->array, index, len);
}
bool buffer_delete(Buffer *buffer, size_t index, size_t len,
Status *status) {
return array_delete_many(&buffer->array, index, len, status);
}
void buffer_clear_no_zero(Buffer *buffer) {
array_clear_no_zero(&buffer->array);
}
void buffer_clear(Buffer *buffer) {
array_clear(&buffer->array);
}
void buffer_free(Buffer *buffer) {
array_free(&buffer->array);
}
void buffer_insert_data_fast(Buffer *buffer, size_t index, const char *bytes,
size_t count) {
array_insert_many_fast(&buffer->array, index, bytes, count);
}
bool buffer_insert_data(Buffer *buffer, size_t index, const char *bytes,
size_t count,
Status *status) {
return array_insert_many(&buffer->array, index, bytes, count, status);
}
void buffer_insert_blank_data_fast_no_zero(Buffer *buffer, size_t index,
size_t count) {
array_shift_elements_down_fast_no_zero(&buffer->array, index, count);
}
void buffer_insert_blank_data_fast(Buffer *buffer, size_t index,
size_t count) {
array_shift_elements_down_fast(&buffer->array, index, count);
}
bool buffer_insert_blank_data_no_zero(Buffer *buffer, size_t index,
size_t count,
Status *status) {
return array_shift_elements_down_no_zero(&buffer->array, index, count,
status);
}
bool buffer_insert_blank_data(Buffer *buffer, size_t index, size_t count,
Status *status) {
return array_shift_elements_down(&buffer->array, index, count, status);
}
void buffer_insert_slice_fast(Buffer *buffer, size_t index, Slice *slice) {
array_insert_many_fast(&buffer->array, index, slice->data, slice->len);
}
bool buffer_insert_slice(Buffer *buffer, size_t index, Slice *slice,
Status *status) {
return array_insert_many(&buffer->array, index, slice->data, slice->len,
status);
}
void buffer_prepend_data_fast(Buffer *buffer, const char *bytes, size_t count) {
array_prepend_many_fast(&buffer->array, bytes, count);
}
bool buffer_prepend_data(Buffer *buffer, const char *bytes, size_t count,
Status *status) {
return array_prepend_many(&buffer->array, bytes, count, status);
}
void buffer_prepend_slice_fast(Buffer *buffer, Slice *slice) {
array_prepend_many_fast(&buffer->array, slice->data, slice->len);
}
bool buffer_prepend_slice(Buffer *buffer, Slice *slice, Status *status) {
return array_prepend_many(&buffer->array, slice->data, slice->len,
status);
}
void buffer_append_data_fast(Buffer *buffer, const char *bytes, size_t count) {
array_append_many_fast(&buffer->array, bytes, count);
}
bool buffer_append_data(Buffer *buffer, const char *bytes, size_t count,
Status *status) {
return array_append_many(&buffer->array, bytes, count, status);
}
void buffer_append_slice_fast(Buffer *buffer, Slice *slice) {
array_append_many_fast(&buffer->array, slice->data, slice->len);
}
bool buffer_append_slice(Buffer *buffer, Slice *slice, Status *status) {
return array_append_many(&buffer->array, slice->data, slice->len, status);
}
void buffer_overwrite_data_fast(Buffer *buffer, size_t index, const char *bytes,
size_t count) {
array_overwrite_many_fast(&buffer->array, index, bytes, count);
}
bool buffer_overwrite_data(Buffer *buffer, size_t index, const char *bytes,
size_t count,
Status *status) {
return array_overwrite_many(&buffer->array, index, bytes, count, status);
}
void buffer_overwrite_slice_fast(Buffer *buffer, size_t index, Slice *slice) {
array_overwrite_many_fast(&buffer->array, index, slice->data, slice->len);
}
bool buffer_overwrite_slice(Buffer *buffer, size_t index, Slice *slice,
Status *status) {
return array_overwrite_many(&buffer->array, index, slice->data, slice->len,
status);
}
void buffer_zero_section_fast(Buffer *buffer, size_t index, size_t len) {
array_zero_elements_fast(&buffer->array, index, len);
}
bool buffer_zero_section(Buffer *buffer, size_t index, size_t len,
Status *status) {
return array_zero_elements(&buffer->array, index, len, status);
}
void buffer_zero_fast(Buffer *buffer) {
array_zero_elements_fast(&buffer->array, 0, buffer->array.len);
}
bool buffer_zero(Buffer *buffer, Status *status) {
return array_zero_elements(&buffer->array, 0, buffer->array.len, status);
}
bool buffer_encode(Buffer *src, const char *src_encoding,
const char *dst_encoding,
Buffer *dst,
Status *status) {
while (true) {
size_t len = dst->array.alloc;
if (charset_convert_data(src->array.elements, src->array.len,
src_encoding,
dst_encoding,
dst->array.elements,
&len,
status)) {
dst->array.len = len;
break;
}
if (!status_match(status, "charset",
CHARSET_OUTPUT_BUFFER_TOO_SMALL)) {
return status_propagate(status);
}
if (!buffer_ensure_capacity(dst, dst->array.alloc * 2, status)) {
return status_propagate(status);
}
}
return status_ok(status);
}
/* vi: set et ts=4 sw=4: */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/sem.h>
int main(){
int *soma, x=3, y=3;
int idMem; /* identificador da memória comum */
int sem;
struct sembuf P, V;
P.sem_num=0;P.sem_op= -1;
P.sem_flg=0;
V.sem_num=0;
V.sem_op=1;
V.sem_flg=0;
if ((sem = semget(IPC_PRIVATE, 1, IPC_CREAT|0666)) == -1){
perror("Erro do semget"); exit(0);
}
//Inicia semáforo com 1 (Último parâmetro)
if (semctl(sem, 0, SETVAL, 1) == -1) {
perror("Erro ao inicializar semáforo");
exit(0);
}
//Cria uma área de memória compartilhada
idMem = shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666);
if (idMem == -1) {
perror("Erro no shmget") ;
exit(0) ;
}
// acoplamento do processo a zona de memória
soma = shmat(idMem, 0, 0);
*soma = 10;
if (fork()==0){
semop(sem, &P, 1);
*soma = *soma + x + y;
printf("\n\nNo filho1: soma = %d", *soma); puts(" ");
semop(sem, &V, 1);
exit(0);
}
if (fork()==0){
semop(sem, &P, 1);
x = x + 5;
*soma = *soma + 10;
printf("\n\nNo filho2: soma = %d", *soma); puts(" ");
semop(sem, &V, 1);
exit(0);
}
wait(0); wait(0);
*soma = *soma + 10;
printf("\nValor do pai: Soma = %d", *soma); puts(" ");
}
|
C
|
#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
FILE* file = fopen("phonebook.csv", "a");
char* name = get_string("Name: ");
char* number = get_string("Number: ");
fprintf(file, "%s,%s\n", name, number);
fclose(file);
}
|
C
|
#include "client.h"
char *client_name,*connect_type,*socket_path,*port_no;
int serv;
int main(int argc, char** argv){
if(argc!=4){perror("Error: wrong ammount of args");exit(-1);}
if (strlen(argv[1]) != M_NAME_LENGTH) {perror("Error: wrong client name");exit(EXIT_FAILURE);}
if (!streq(argv[2], "network") && !streq(argv[2], "local")) {
perror("Error: connection type must be on of the following 'network' or 'local");exit(EXIT_FAILURE);}
client_name=argv[1];
connect_type=argv[2];
socket_path=argv[3];
port_no=NULL;
char *msg = client_name;
signal(SIGINT, sigint_handler);
if (streq(connect_type, "network")) {
int i = 0;
while (socket_path[i]) {
if (socket_path[i] == ':') {
socket_path[i] = '\0';
port_no = socket_path + i + 1;
break;
}
i++;
}
if (port_no == NULL) {perror("Error: wrong server address, must be 'IPv4:port'\n"); exit(EXIT_FAILURE);}
}
if ((serv = est_connection(connect_type, socket_path, port_no)) < 0) {perror("Error: est_connection");exit(EXIT_FAILURE);}
send(serv, msg, 1024, 0);
char received[1024];
recv(serv, received, 1024, 0);
if(!streq("OK",received))
{shutdown(serv, SHUT_RDWR);close(serv);printf("%s: %s\n",client_name,received);exit(0);}
printf("%s connected\n",client_name);
while (1) {
char act_req[M_MSG_SIZE];
recv(serv, act_req, M_MSG_SIZE, 0);
handle_action(act_req);
}
}
int est_connection(char *type, char *socket_path, char *port_no){
int serv_socket;
if (streq(type, "network")) {
struct addrinfo addr, *res;
memset(&addr, 0, sizeof(addr));
addr.ai_family = AF_UNSPEC;
addr.ai_socktype = SOCK_STREAM;
getaddrinfo(socket_path, port_no, &addr, &res);
if ((serv_socket = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0) {perror("Error: socket");return -1;}
if (connect(serv_socket, res->ai_addr, res->ai_addrlen) < 0) {close(serv_socket);perror("Error: connect");return -1;}
}
else if (streq(type, "local")) {
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path,socket_path);
if ((serv_socket = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {perror("Error: socket");return -1;}
if (connect(serv_socket, (const struct sockaddr *) &addr, sizeof(addr)) < 0) {close(serv_socket);perror("Error: connect");return -1;}
}
else serv_socket = -1;
return serv_socket;
}
void handle_action(char *req) {
if (streq(req, "ping")) {send_msg(serv, "pong");return;}
char orig_req[M_MSG_SIZE];
strcpy(orig_req, req);
char **argv = malloc(4 * sizeof(char *));
argv[0] = req;
int ord = 1;
int i = 0;
while (req[i] && ord < 4) {
if (req[i] == ' ') {
argv[ord] = req + i + 1;
req[i] = '\0';
ord++;
}
i++;
}
if (ord != 4) {
printf("Wrong action request received: %s\n", orig_req);
char resp[M_MSG_SIZE];
sprintf(resp, "Wrong request: %s", orig_req);
send_msg(serv, resp);
free(argv);
return;
}
int idx = atoi(argv[0]);
double arg1 = atof(argv[2]);
double arg2 = atof(argv[3]);
printf("%s: Requested action: %s %lf %lf\n",client_name,argv[1], arg1, arg2);
if (streq(argv[1], "+")) {
double res = arg1 + arg2;
char result[M_MSG_SIZE];
sprintf(result, "%d %f", idx, res);
send_msg(serv, result);
}
else if (streq(argv[1], "-")) {
double res = arg1 - arg2;
char result[M_MSG_SIZE];
sprintf(result, "%d %f", idx, res);
send_msg(serv, result);
}
else if (streq(argv[1], "*")) {
double res = arg1 * arg2;
char result[M_MSG_SIZE];
sprintf(result, "%d %f", idx, res);
send_msg(serv, result);
}
else if (streq(argv[1], "/")) {
if (arg2 != 0.0) {
double res = arg1 / arg2;
char result[M_MSG_SIZE];
sprintf(result, "%d %f", idx, res);
send_msg(serv, result);
}
else{
char result[M_MSG_SIZE];
sprintf(result, "I'm sorry, you cannot divide by 0");
send_msg(serv, result);
}
}
else {
puts("Unsupported operation");
send_msg(serv, "Unsupported operation");
free(argv);
return;
}
free(argv);
}
void send_msg(int client, char *msg) {
char message[M_MSG_SIZE];
sprintf(message, "%s", msg);
send(client, message, M_MSG_SIZE, 0);
}
void sigint_handler(int sig){
printf("Client: shutting down\n");
send_msg(serv, "close");
if (shutdown(serv, SHUT_RDWR) < 0) {perror("Error: shutdown");}
if (close(serv) < 0) {perror("Error: close");}
exit(0);
}
int streq(char *string1, char *string2) {
return strcmp(string1, string2) == 0;
}
int validateInteger(char* s){
int i;
for(i=0;s[i]!='\0' && s[i]!=' ' && s[i]!='\n';i++){
if(s[i]<'0' || s[i]>'9')return 0;
}
return 1;
}
|
C
|
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "lsmcolors.h"
#include "ansicodes.h"
#include "lsmount.h"
void initcolors(void) {
colors[0] = ANSI_ESC_RED;
colors[1] = ANSI_ESC_GREEN;
colors[2] = ANSI_ESC_BLUE;
colors[3] = ANSI_ESC_YELLOW;
colors[4] = ANSI_ESC_WHITE;
colors[5] = ANSI_ESC_WHITE;
}
char* colortoesc(char* cstr) {
if(!strcmp(cstr, "black")) {
return ANSI_ESC_BLACK;
}else if(!strcmp(cstr, "red")) {
return ANSI_ESC_RED;
}else if(!strcmp(cstr, "green")) {
return ANSI_ESC_GREEN;
}else if(!strcmp(cstr, "yellow")) {
return ANSI_ESC_YELLOW;
}else if(!strcmp(cstr, "blue")) {
return ANSI_ESC_BLUE;
}else if(!strcmp(cstr, "magenta")) {
return ANSI_ESC_MAGENTA;
}else if(!strcmp(cstr, "cyan")) {
return ANSI_ESC_CYAN;
}else if(!strcmp(cstr, "white")) {
return ANSI_ESC_WHITE;
}else{
printf(_("unknown color\n"));
exit(1);
}
}
|
C
|
#include <stdlib.h>
#include "index_vec.h"
struct index_vec {
size_t *arr;
size_t cap;
size_t len;
};
struct index_vec *index_vec_new(void) {
size_t cap = 1;
size_t *arr = malloc(cap * sizeof *arr);
struct index_vec *vec = malloc(sizeof *vec);
vec->arr = arr;
vec->cap = cap;
vec->len = 0;
return vec;
}
void index_vec_del(struct index_vec *vec) {
free(vec->arr);
free(vec);
}
void index_vec_app(struct index_vec *vec, size_t index) {
if (vec->len == vec->cap) {
size_t new_cap = 2 * vec->cap;
size_t *new_arr = malloc(new_cap * sizeof *new_arr);
for (size_t i = 0; i < vec->len; ++i)
new_arr[i] = vec->arr[i];
free(vec->arr);
vec->arr = new_arr;
vec->cap = new_cap;
}
vec->arr[vec->len++] = index;
}
size_t index_vec_len(const struct index_vec *vec) {
return vec->len;
}
size_t index_vec_get(const struct index_vec *vec, size_t index) {
return vec->arr[index];
}
|
C
|
#include <stdio.h>
#include <omp.h>
#include <stdint.h>
#include <math.h>
#include "io-util.h"
#include "rand.h"
#define PI 3.14159265358979323846
int main(){
//prompt for input
uint64_t tosses;
{
StreamIterator iter = allocStreamIter(stdin);
printf("Enter Tosses: \n");
tosses = readUInt64(iter);
freeStreamIter(iter);
if(tosses == 0){
printf("Invalid number of tosses.");
return 1;
}
}
const uint64_t seedVal = 0;
uint64_t hits = 0;
#pragma omp parallel reduction(+:hits)
{
//setup the random
Random rand = seed((uint64_t)omp_get_thread_num() ^ seedVal);
//perform the
#pragma omp for schedule(static)
for(uint64_t toss = 0; toss < tosses; toss++){
double x = randFloat64(&rand, -1, 1);
double y = randFloat64(&rand, -1, 1);
if(x * x + y * y <= 1)
hits++;
}
}
//print results
double pi = 4.0 * hits / tosses;
double error = fabs(PI - pi) / PI;
printf("PI: %lf\n", pi);
printf("Error: %.6lf%%\n", error * 100);
}
|
C
|
#include "sparse_matrices.h"
/**
* HELPER FUNCTIONS
*/
void fill_nnz_int(struct Matrix *, struct sparse_csr *);
void fill_nnz_double(struct Matrix *, struct sparse_csr *);
void fill_IA_JA(struct Matrix *matrix, struct sparse_csr *matrix_csr);
// CONVERT MATRIX INTO SPARSE CSR FROMAT
void matrix_to_csr(struct Matrix *matrix, struct sparse_csr *matrix_csr)
{
// MAKE NNZ ARRAY
if (strcmp(matrix->data_type, INT) == 0)
fill_nnz_int(matrix, matrix_csr);
else
fill_nnz_double(matrix, matrix_csr);
fill_IA_JA(matrix, matrix_csr);
}
// FILL IN matrix -> nnz_int
void fill_nnz_int(struct Matrix *matrix, struct sparse_csr *matrix_csr)
{
// MANAGE DATA TYPE PARAM IN CSC_MATRIX
matrix_csr->data_type = (char *)safe_malloc(strlen(FLOAT) * sizeof(char));
strcpy(matrix_csr->data_type, INT);
const char s[2] = " ";
char *token;
int index = 0;
matrix_csr->NNZ_int_size = 0;
matrix_csr->NNZ_int = (int *)safe_malloc(sizeof(int));
/* get the first token */
char *payload_cpy = (char *)safe_malloc(matrix->payload_length * sizeof(char));
strcpy(payload_cpy, matrix->payload);
token = strtok(payload_cpy, s);
/* walk through other tokens */
while (token != NULL)
{
int tmp = atoi(token);
if (tmp != 0)
{
matrix_csr->NNZ_int[index] = tmp;
index++; // increment before realloc so correct amount of memory is reallocated -- think about it !
matrix_csr->NNZ_int = (int *)safe_realloc(matrix_csr->NNZ_int, (index + 1) * sizeof(matrix_csr->NNZ_int[0]));
matrix_csr->NNZ_int_size++; // increment length of NNZ_int variable
}
token = strtok(NULL, s);
}
}
// FILL IN matrix -> nnz_double
void fill_nnz_double(struct Matrix *matrix, struct sparse_csr *matrix_csr)
{
// MANAGE DATA TYPE PARAM IN CSC_MATRIX
matrix_csr->data_type = (char *)safe_malloc(strlen(FLOAT) * sizeof(char));
strcpy(matrix_csr->data_type, FLOAT);
const char s[2] = " ";
char *token;
int index = 0;
matrix_csr->NNZ_double_size = 0;
matrix_csr->NNZ_double = (double *)safe_malloc(sizeof(double));
/* get the first token */
char *payload_cpy = (char *)safe_malloc(matrix->payload_length * sizeof(char));
strcpy(payload_cpy, matrix->payload);
token = strtok(payload_cpy, s);
/* walk through other tokens */
while (token != NULL)
{
double tmp = atof(token);
if (tmp != 0)
{
matrix_csr->NNZ_double[index] = tmp;
index++; // increment before realloc so correct amount of memory is reallocated -- think about it !
matrix_csr->NNZ_double = (double *)safe_realloc(matrix_csr->NNZ_double, (index + 1) * sizeof(matrix_csr->NNZ_double[0]));
matrix_csr->NNZ_double_size++; // increment length of NNZ_double variable
}
token = strtok(NULL, s);
}
}
// FILL IN matrix -> nnz_double
void fill_IA_JA(struct Matrix *matrix, struct sparse_csr *matrix_csr)
{
int row_cnt = 0;
int row = 0;
int col = 0;
int nrow = matrix->nrow;
int ncol = matrix->ncol;
// IAs STUFF
int IA[nrow + 1];
memset(IA, 0, sizeof(IA)); // set to zero
matrix_csr->JA = (int *)safe_malloc(sizeof(int));
matrix_csr->JA_size = 0;
// UPDATE NROW, NCOL IN SPARSE MATRIX
matrix_csr->nrow = nrow;
matrix_csr->ncol = ncol;
int nvals = 0;
const char s[2] = " ";
char *token;
/* get the first token */
char *payload_cpy = (char *)safe_malloc(matrix->payload_length * sizeof(char));
strcpy(payload_cpy, matrix->payload);
token = strtok(payload_cpy, s);
/* walk through other tokens */
while (token != NULL)
{
// YOU ARE IN THE row ROW
if (row_cnt % ncol == 0)
row++;
//printf("%d\t", row);
int tmp = atoi(token);
if (tmp != 0)
{
// ADD COLUMN INDEX OF ELEMENT ADDED TO NNZ
matrix_csr->JA = (int *)safe_realloc(matrix_csr->JA, (nvals + 1) * sizeof(matrix_csr->JA[0]));
matrix_csr->JA[nvals] = col;
matrix_csr->JA_size++;
// INCREMENT NUMBER OF NON-ZEROS IN ROW
IA[row]++;
nvals++;
}
token = strtok(NULL, s);
row_cnt++;
// YOU ARE IN THE col COLUMN
//printf("%d\t", col);
col = (col + 1) % ncol;
}
// BUILD CSR MATRIX (IAs)
matrix_csr->IA_size = nrow + 1;
matrix_csr->IA = (int *)safe_malloc(matrix_csr->IA_size * sizeof(int));
matrix_csr->IA[0] = 0;
for (int k = 1; k < nrow + 1; k++)
matrix_csr->IA[k] = matrix_csr->IA[k - 1] + IA[k];
}
|
C
|
/*
* File: main.c
* Author: carlostovar
*
* Created on 30 de noviembre de 2016, 7:19
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
*
*/
int main(int argc, char** argv) {
int patron[2][2];
int matriz[10][10];
int i,j;
int ok;
ok=0;
printf("\n\nLa matriz aleatoria es:\n\n");
//llenar aleatoriamente
for(i=0;i<10;i++){
for(j=0;j<10;j++){
matriz[i][j]=rand()%10;//Agrega numero aleatorio a la posicion ij de la matriz
printf("%d\t",matriz[i][j]);//imprime elemento de la matriz en pantalla
}
printf("\n\n");//para dejar espacios entre filas.
}
srand(time(0));//numeros Aleatorios en funcion del tiempo
//Llenar valores de la matriz
for(i=0;i<2;i++){
for(j=0;j<2;j++){
printf("\n Ingresa valor para la posicion [%d][%d]: ",i,j);
scanf("%d",&patron[i][j]);
}
}
for(i=0;i<10;i++){
for(j=0;j<10;j++){
if(matriz[i][j]==patron[0][0]&&matriz[i][j+1]==patron[0][1]&&matriz[i+1][j]==patron[1][0]&&matriz[i+1][j+1]==patron[1][1])
ok++;
}
}
if(ok!=0)
printf("La encontre!");
else
printf("no la encontre");
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
/* unformatted char input | unformatted char output
int gfetc(FILE *fp) / getc(FILE *fp) | int fputc(int c, FILE *fp) / putc(int c, FILE*fp)
returns the input char from stream | returns EOF on error else positive number
returns EOF for end of file or error |
*/
/************************* Example Code ****************************************
int c;
while((c=fgetc(stdin))!=EOF){
fputc(c,stdout);
}
printf("EOF Encountered...\n");
********************************************************************************/
/* Unformatted string input | Unformatted string output
char *fgets(char *s, int max, FILE *fp) | int fputs(const char *s, FILE *fp)
reads from stream fp to string s, | writes from string s to stream fp.
max-1 characters, stopping on new line, |
returns s. | returns EOF in case of any error,
It returns NULL in case of | and non negative for no error.
EOF or error encounters. |
char *gets(char *s) only for stdin | int puts(const char *s) only for stdout
* /
/********************************Example Code **************************************
char input[1000];
while(fgets(input,sizeof(input),stdin)!= NULL){
fputs(input,stdout);
}
printf("EOF Encountered...\n");
******************************************************************************/
/* Formatted imput | Formatted output
int scanf(char *format, ...) for stdin only | int printf("%s",s) for stdout only
int fscanf(FILE *stream,char *format,...) reads | int fprintf(FILE *stresam, char *format,...)
from srtream to string or other variable | converts & writes output to stream under the
as specified by the format. The last argument | control of format.
maust be pointer to the variable to store. |
int sscanf(cont char *s, const char *format,...)| int sprintf(char *s, const char *format,...)
here the input characters are taken from | here the output is written to string s.
string s. |
Reads upto first white space, not include the |
white space. |
returns EOF on error else returns number of | returns number of char written else negative
input items converted. | if error occurs.
/**********************Example code **************************************************/
char name[100];
char buffer[100];
int a = 12345;
int b = 0;
printf("Enter your name: ");
fscanf(stdin,"%s",name);
fprintf(stdout,"%s\n",name);
sprintf(buffer,"%d",a);
fprintf(stdout,"%s\n",buffer);
sscanf(buffer,"%d",&b);
fprintf(stdout,"%d\n",b);
return 0;
}
|
C
|
#include <stdio.h>
int platform1D(int ar[], int size);
int main()
{
int i,b[50],size;
printf("Enter array size: \n");
scanf("%d", &size);
printf("Enter %d data: \n", size);
for (i=0; i<size; i++)
scanf("%d",&b[i]);
printf("platform1D(): %d\n", platform1D(b,size));
return 0;
}
int platform1D(int ar[], int size)
{
/* Write your code here */
int i, count=1, index=0, max;
int arb[size];
for (i=0;i<size;i++)
{
if (ar[i]==ar[i+1])
{
count += 1;
}
else if (ar[i]!=ar[i+1] || i == size-1)
{
arb[index] = count;
count = 1;
index++;
arb[index] = 0;
}
}
i = 0;
if (index==0)
{
max = 1;
}
else
{
max = arb[0];
while (index>=0)
{
if (arb[index]>max)
{
max = arb[index];
}
index--;
}
}
return max;
}
|
C
|
/*
en un archivo contiene las notas de los alumnos en cada materia.
el archivo esta ordenado por legajo.
estructura del archivo:
typedef struct Notas
{
int legajo;
char materia[20];
int nota;
} Notas ;
se pide:
1- crear programa para cargar archivo.
2- crear programa para leer archivo de notas y:
2.1- calcular promedio por alumno.
2.2- mostrar nota mas alta de cada alumno.
- el nombre del archivo debe ser pasado por parametro al programa
*/
|
C
|
// Implements a dictionary's functionality
#include <stdbool.h>
#include "dictionary.h"
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 1024 * 10;
// Hash table
node *table[N];
int total_size = 0;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int h = hash(word);
node *head = table[h];
while (head) {
if (!strcasecmp(head->word, word)) {
return true;
}
head = head->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
int sum = 0;
for(; *word; word++) {
sum += tolower(*word);
}
return sum % N;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
char buffer[LENGTH + 1];
while (fscanf(file, "%s", buffer) != EOF) { // fscanf遇到空格和换行时结束,注意空格时也结束。这与fgets有区别,fgets遇到空格不结束
// while (!feof(file)) {
// if (fgets(buffer,LENGTH + 1,file) != NULL)
{
node *n = calloc(1, sizeof(node));
strcpy(n->word, buffer);
total_size++;
int h = hash(buffer);
n->next = table[h];
table[h] = n;
}
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return total_size;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for (int i = 0; i < N; i++) {
node *head = table[i];
if (head != NULL) {
node *next = NULL;
do {
next = head->next;
free(head);
head = next;
} while (head != NULL);
}
}
return true;
}
|
C
|
#include <stdio.h>
#include <omp.h>
main()
{
int i,j ,k,n;
FILE *fp;
i =2;
k = 2;
j = 0;
n = 0;
double t_start,t_end,t_sp0,t_sp1,t_sp2,t_sp3,t_sp4,t_sp5,t_sp6,t_sp7,t_sp8;
double speedup1,speedup2,speedup3,speedup4,speedup5,speedup6,speedup7,speedup8;
fp = fopen("data0.txt","w");
t_start = omp_get_wtime();
for ( i = 2;i<=100000;i++)
{
for ( k = 1;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp0 = t_end - t_start;
j = 0;
n = 0;
t_start = omp_get_wtime();
fp = fopen("data1.txt","w");
#pragma omp parallel num_threads(1)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 1;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp1 = t_end - t_start;
speedup1 = t_sp0/t_sp1;
n = 0;
j = 0;
t_start = omp_get_wtime();
fp = fopen("data2.txt","w");
#pragma omp parallel num_threads(2)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 1;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp2 = t_end - t_start;
speedup2 = t_sp0/t_sp2;
n = 0;
j = 0;
t_start = omp_get_wtime();
fp = fopen("data3.txt","w");
#pragma omp parallel num_threads(3)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 1;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp3 = t_end - t_start;
speedup3 = t_sp0/t_sp3;
n = 0;
j = 0;
t_start = omp_get_wtime();
fp = fopen("data4.txt","w");
#pragma omp parallel num_threads(4)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 1;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp4 = t_end - t_start;
speedup4 = t_sp0/t_sp4;
n = 0;
j = 0;
t_start = omp_get_wtime();
fp = fopen("data5.txt","w");
#pragma omp parallel num_threads(5)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 2;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp5 = t_end - t_start;
speedup5 = t_sp0/t_sp5;
n = 0;
j = 0;
t_start = omp_get_wtime();
fp = fopen("data6.txt","w");
#pragma omp parallel num_threads(6)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 2;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp6 = t_end - t_start;
speedup6 = t_sp0/t_sp6;
n = 0;
j = 0;
t_start = omp_get_wtime();
fp = fopen("data7.txt","w");
#pragma omp parallel num_threads(7)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 2;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp7 = t_end - t_start;
speedup7 = t_sp0/t_sp7;
n = 0;
j = 0;
t_start = omp_get_wtime();
fp = fopen("data8.txt","w");
#pragma omp parallel num_threads(8)
#pragma omp parallel private(n)
for ( i = 2;i<=100000;i++)
{
#pragma omp parallel for reduction(+:n)
for ( k = 2;k<i;k++)
{
if(i%k == 0)
n += 1;
}
if (n <= 2)
{
fprintf(fp,"%d ",i);
j++;
}
}
fclose(fp);
printf("the number of prime number is : %d\n",j);
t_end = omp_get_wtime();
t_sp8 = t_end - t_start;
speedup8 = t_sp0/t_sp8;
printf("sigle threads time is :%f\n",t_sp0);
printf("one threads time is :%f,speedup is :%f\n ",t_sp1,speedup1);
printf("two threads time is :%f,speedup is :%f\n ",t_sp2,speedup2);
printf("three threads time is :%f,speedup is :%f\n ",t_sp3,speedup3);
printf("four threads time is :%f,speedup is :%f\n ",t_sp4,speedup4);
printf("five threads time is :%f,speedup is :%f\n ",t_sp5,speedup5);
printf("six threads time is :%f,speedup is :%f\n ",t_sp6,speedup6);
printf("seven threads time is :%f,speedup is :%f\n ",t_sp7,speedup7);
printf("eight threads time is :%f,speedup is :%f\n ",t_sp8,speedup8);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** test_my_put_nbr.c
** File description:
** test nbr
*/
int my_put_nbr(int nb);
int main()
{
my_put_nbr(1000);
my_put_nbr(0);
my_put_nbr(-0);
my_put_nbr(-2147483647);
my_put_nbr(2147483647);
my_put_nbr(-42);
my_put_nbr(-2147483648);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"
#include "dict.h"
//* function name: ReadDictionary
//* Description: This function reads a dictionary line by line from the standard input
//* Parameters: None
//* return value: a Pointer to the dictionery
pHash ReadDictionary() {
pHash dictionary;
char entryLine[100] = "";
char* word, * translation;
dictionary = CreateDictionary();
while (scanf("%s", entryLine) == 1) { // Not EOF
word = strtok(entryLine, "=");
translation = strtok(NULL, "=");
AddTranslation(dictionary, word, translation);
}
return dictionary;
}
int main() {
pHash Dictionary;
Dictionary = ReadDictionary();
PrintDictionary(Dictionary);
DeleteTranslation(Dictionary, "dog");
DeleteTranslation(Dictionary, "cat");
DeleteTranslation(Dictionary, "astronaut");
PrintDictionary(Dictionary);
AddTranslation(Dictionary, "goat", "ez");
AddTranslation(Dictionary, "cow", "para");
AddTranslation(Dictionary, "school", "beitsefer");
AddTranslation(Dictionary, "boy", "yeled");
PrintDictionary(Dictionary);
Translate(Dictionary, "flag");
Translate(Dictionary, "goat");
Translate(Dictionary, "school");
Translate(Dictionary, "apple");
HashDestroy(Dictionary);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
typedef struct ListNode ListNode;
typedef struct TreeNode TreeNode;
TreeNode *findCommon(TreeNode *node, TreeNode *p, TreeNode *q, int *flag) {
if (node == NULL) {return NULL;}
// int current_flag = *flag;
int l_flag = 0;
int r_flag = 0;
int current_flag = 0;
TreeNode *l_rt = findCommon(node->left, p, q, &l_flag);
TreeNode *r_rt = findCommon(node->right, p, q, &r_flag);
if (node == p || node == q) {current_flag = 1;}
if (current_flag + l_flag + r_flag == 2) {
*flag = 2;
if (l_flag == 2) {
return l_rt;
}
if (r_flag == 2) {
return r_rt;
}
return node;
}
if (current_flag + l_flag + r_flag == 1) {
*flag = 1;
}
return node;
}
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
int flag = 0;
return findCommon(root, p, q, &flag);
}
int main() {
ListNode *node = (ListNode *) malloc(sizeof(ListNode));
ListNode *node1 = (ListNode *) malloc(sizeof(ListNode));
ListNode *node2 = (ListNode *) malloc(sizeof(ListNode));
ListNode *node3 = (ListNode *) malloc(sizeof(ListNode));
ListNode *node4 = (ListNode *) malloc(sizeof(ListNode));
ListNode *node5 = (ListNode *) malloc(sizeof(ListNode));
ListNode *node6 = (ListNode *) malloc(sizeof(ListNode));
// node - 1 - 2
node->val = 0;
node->next = node1;
node1->next = node2;
node2->next = NULL;
node1->val = 7;
node2->val = 2;
node3->val = 3;
// another list
// node3 - 4 - 5 - 6
node3->next = node4;
node4->next = node5;
node5->next = node6;
node6->next = NULL;
node4->val = 4;
node5->val = 5;
node6->val = 6;
// empty list
ListNode *nodeEmpty = (ListNode *) malloc(sizeof(ListNode));
nodeEmpty->val = 0;
nodeEmpty->next = NULL;
/***********************/
// Binary tree init
struct TreeNode *tree;
tree = (struct TreeNode *) malloc (sizeof(struct TreeNode));
(*tree).val = 1;
// left
struct TreeNode *leftTree = (struct TreeNode *)malloc(sizeof(struct TreeNode));
(*leftTree).val = 2;
(*leftTree).left = NULL;
(*leftTree).right = NULL;
(*tree).left = leftTree;
(*tree).right = NULL;
// left right
struct TreeNode *tmpTree = (struct TreeNode *) malloc(sizeof(struct TreeNode));
(*tmpTree).val = 3;
(*tmpTree).left = NULL;
(*tmpTree).right = NULL;
(*leftTree).right = tmpTree;
TreeNode *ret = lowestCommonAncestor(tree, leftTree, tmpTree);
printf("ret %d\n", ret->val);
return 0;
}
|
C
|
#include "xc.h"
#include "tempSensor_Library.h"
void i2c_init(void)
{
TRISBbits.TRISB0 = 1; // Digital Output (make it input only when reading data)
TRISBbits.TRISB1 = 1; // Digital Output
TRISBbits.TRISB4=0; //Testing LED output
I2C1CON=0x0000; //clear control bits
I2C1STAT=0x0000; //clear status bits
I2C1CONbits.DISSLW=1; //Disable slew rate control
I2C1CONbits.SMEN=0; //disable SMBUS
I2C1BRG=0x9D; //Baud Rate 100 kHz
IFS1bits.MI2C1IF = 0; //reset IF
I2C1CONbits.I2CEN=1;
I2C1CONbits.SEN = 0; //Force Idle
}
void i2c_start(void)
{
IFS1bits.MI2C1IF = 0; //clear flag
while ( I2C1STATbits.RBF ) ; // wait for idle condition
I2C1CONbits.SEN = 1; //Initiate START condition
while (!IFS1bits.MI2C1IF) ; // wait for a flag to be set
IFS1bits.MI2C1IF = 0; //clear flag
}
void i2c_stop(void)
{
IFS1bits.MI2C1IF = 0; //clear flag
while ( I2C1STATbits.RBF ) ; // wait for idle condition
I2C1CONbits.PEN = 1; //Initiate STOP condition
while (!IFS1bits.MI2C1IF) ; // wait for a flag to be set
IFS1bits.MI2C1IF = 0; //clear flag
}
unsigned char i2c_write(unsigned char i2cWriteData)
{
IFS1bits.MI2C1IF = 0; //clear flag
while (I2C1STATbits.RBF) ; // wait for idle condition
I2C1TRN = i2cWriteData;
while (!IFS1bits.MI2C1IF) ; // wait for a flag to be set
IFS1bits.MI2C1IF = 0; //clear flag
return ( !I2C1STATbits.ACKSTAT ); // function returns '1' if transmission is acknowledged
}
unsigned char i2c_read( unsigned char ack )
{
unsigned char i2cReadData;
IFS1bits.MI2C1IF = 0; //reset IF
while (I2C1STATbits.RBF); // wait for idle condition
I2C1CONbits.RCEN = 1; // enable receive mode
while (!IFS1bits.MI2C1IF); // wait for a flag to be set
IFS1bits.MI2C1IF = 0; //reset IF
i2cReadData = I2C1RCV; // Read SSPBUF and put it in i2cReadData
if (ack) // if ack=1
{
I2C1CONbits.ACKDT = 0; // then transmit an Acknowledge
}
else
{
I2C1CONbits.ACKDT = 1; // otherwise transmit a Not Acknowledge
}
I2C1CONbits.ACKEN = 1; // send acknowledge sequence
while (!IFS1bits.MI2C1IF) ; // wait for a flag to be set
IFS1bits.MI2C1IF = 0; //reset IF
return(i2cReadData); // return the value read from SSPBUF
}
void i2c_config(void)
{
i2c_start(); // send START command
i2c_write(0b00110000); //WRITE Command (see Section 4.1.4 ?Address Byte?)
i2c_write(0x01); // Write CONFIG Register
i2c_write(0x00); // Write data
i2c_write(0x08); // Write data
i2c_stop(); // send STOP command
i2c_start(); // send START command
i2c_write(0b00110000); //WRITE Command (see Section 4.1.4 ?Address Byte?)
i2c_write(0x05); // Write TA Register Address
i2c_start(); //Repeat START
i2c_write(0b00110001); // READ Command (see Section 4.1.4 ?Address Byte?)
}
void initPushButton(void)
{
LATB=0x0000;
TRISBbits.TRISB15=1; //Button input
CNPU1bits.CN11PUE=1; //Pullup resistor for RB15 Button
T2CON = 0x0020; //Stop Timer, Tcy clk source, PRE 1:256
TMR2 = 0; // Initialize to zero (also best practice)
PR2 = 62499; // Set period to be larger than max external sig duration
T2CONbits.TON = 1; // Restart 16-bit Timer2
IFS0bits.T2IF = 0;
IEC0bits.T2IE = 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* helpers2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akalmyko <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/11 18:13:03 by akalmyko #+# #+# */
/* Updated: 2017/02/13 17:57:16 by hcherchi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libunit.h"
int ft_strlen(const char *str)
{
int count;
char *copy;
count = 0;
copy = (char*)str;
if (!copy)
return (0);
while (*copy != '\0')
{
count++;
copy++;
}
return (count);
}
int ft_strcmp(char *s1, char *s2)
{
unsigned char *p1;
unsigned char *p2;
p1 = (unsigned char *)s1;
p2 = (unsigned char *)s2;
while (*p1 || *p2)
{
if (*p1 != *p2)
return (*p1 - *p2);
p1++;
p2++;
}
return (0);
}
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putnbr(int n)
{
unsigned int nb;
if (n < 0)
{
ft_putchar('-');
n = -n;
}
nb = (unsigned int)n;
if (nb >= 10)
{
ft_putnbr(nb / 10);
ft_putnbr(nb % 10);
}
else
ft_putchar(nb + '0');
}
void ft_printname(char *str)
{
ft_putchar('\n');
ft_putstr("-------------------------------------\n ");
ft_putstr(str);
ft_putchar('\n');
ft_putstr("-------------------------------------\n");
}
|
C
|
#include<stdio.h>
#define MAX 6
int main(void){
for (int i = 0; i < MAX; i ++){
for (int y = 0; y < MAX; y++){
if (y < i){
printf(" ");
}else{
printf("*");
}
}
printf("\n");
}
}
|
C
|
/*һṹ,ڱǵڼ,ע*/
#include <stdio.h>
int main()
{
struct time
{
int year;
int month;
int day;
};
int i,day=0;
int month[12]={31,28,31,30,31,30,31,31,30,31,30,31};
struct time Time;
printf("Ҫ(ʽ--,,)\n");
scanf("%d,%d,%d",&Time.year,&Time.month,&Time.day);
if(Time.year%4==0)
{
month[1]=29;
}
for(i=1;i<Time.month;i++)
{
day=day+month[i-1];
}
day=day+Time.day;
printf("Ϊеĵ%d",day);
}
|
C
|
#include "Rummikub.h"
carta * criabaralho(){
carta *Baralho = (carta *) calloc(106, sizeof(carta));
int v;
printf("Voce deseja jogar com:\n");
printf("1 - Baralho aleatorio\n");
printf("2 - Baralho pre-definido(Arquivo)\n");
scanf("%d",&v);
if(v==1){
srand(time(NULL));
char valores[14] = {'1','2','3','4','5','6','7','8','9','A','B','C','D','*'};
char naipes[5] = {'#','!','@','$','*'};
int i=0, j, k, r, c;
while(i<106){
j = rand() % 14;
if(j!=13){
k = rand() % 4;
}else{
k = 4;
}
c = 0;
for(r=0;r<106;r++){
if(Baralho[r].valor==valores[j] && Baralho[r].naipe==naipes[k]){
c++;
}
}
if(c>=2){continue;}
Baralho[i].valor = valores[j];
Baralho[i].naipe = naipes[k];
i++;
}
return Baralho;
}else{
if(v==2){
int i;
char carta[3];
char nome[20];
FILE * Arq;
printf("Insira o nome do arquivo a ser lido: ");
scanf("%s",nome);
Arq = fopen(nome,"rt");
if(Arq==NULL){
printf("Arquivo nao encontrado\n");
return NULL;
}
for(i=0;i<106;i++){
fscanf(Arq,"%s",carta);
Baralho[i].valor = carta[0];
Baralho[i].naipe = carta[1];
}
fclose(Arq);
return Baralho;
}else{
printf("Valor invalido\n");
return NULL;
}
}
}
|
C
|
// Copyright (c) 2003-2013, LogMeIn, Inc. All rights reserved.
// This is part of Xively C library, it is under the BSD 3-Clause license.
/**
* \file xi_helpers.h
* \author Olgierd Humenczuk
* \brief General helpers used by the library
*/
#ifndef __XI_HELPERS_H__
#define __XI_HELPERS_H__
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* \note Needed to avoid using `strdup()` which can cause some problems with `free()`,
* because of buggy `realloc()` implementations.
*
* \return Duplicated string or null in case of memory allocation problem.
*/
char* xi_str_dup( const char* s );
/**
* \brief Copies `src` string into `dst`, but stops whenever `delim` is reached or the `dst_size` is exceeded
*
* \return Number of copied characters or -1 if an error occurred.
*/
int xi_str_copy_untiln( char* dst, size_t dst_size, const char* src, char delim );
/**
* \brief Converts from `tm` to `time_t`
*
* \note This code assumes that unsigned long can be converted to `time_t`.
* A `time_t` should not be wider than `unsigned long`, since this
* would mean that the check for overflow at the end could fail.
*
* \note This implementation had been copied from MINIX C library.
* Which is 100% compatible with our license.
*
* \note This function does not take into account the timezone or the `dst`,
* it just converts `tm` structure using date and time fields (i.e. UTC).
*/
time_t xi_mktime( struct tm* t );
/**
* \brief This just wraps system's `gmtime()`, it a facade for future use
*/
struct tm* xi_gmtime( time_t* t );
/**
* \brief Replaces `p` with `r` for every `p` in `buffer`
*
* \return Pointer to converted buffer.
* \note This function assumes that the buffer is terminated with `\0`.
*/
char* xi_replace_with(
char p, char r
, char* buffer
, size_t max_chars );
#ifdef __cplusplus
}
#endif
#endif // __XI_HELPERS_H__
|
C
|
#include <stdio.h>
#include <stdlib.h>
void main() {
int N = 0, J = 0;
int sum = 0;
scanf("%d %d", &J, &N);
//사탕의 개수 J, 상자의 개수 N개(모두 크기 다름)
int* r = malloc(N * sizeof(int));
int* c = malloc(N * sizeof(int));
int* box = malloc(N * sizeof(int));
for (int i = 0; i < N; i++) {
scanf("%d %d", &r[i], &c[i]);
box[i] = r[i] * c[i];
}
//가로세로 입력하고 박스는 가로랑 세로 곱한 거.
int temp;
for (int i = 0; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
if (box[i] < box[j]) {
temp = box[j];
box[j] = box[i];
box[i] = temp;
}
}
}
//box를 내림차순으로 정렬
for (int i = N - 1; i >= 0; i--) {
if (J - box[i] > 0) {
J -= box[i];
sum++;
}
}
//박스 총 몇개 필요한지 count
printf("%d", sum);
}
|
C
|
/* Psi-, weight- and psi-prime functions for M-estimators
Copyright (C) 2020-21 Tobias Schoch (e-mail: tobias.schoch@gmail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, a copy is available at
https://www.gnu.org/licenses/
Notes:
Currently, the following psi-functions (and their respective weight-
and psi-prime functions) are implemented:
- psi = 0: Huber psi-function (see Huber, 1981)
- psi = 1: asymmetric Huber psi-function (see Hulliger, 1995)
- psi = 2: Tukey biweight psi-function (see Huber, 1981)
If you want to add other psi-functions, you must include them in the
switch case statements of the functions 'get_wgt_function',
'get_psi_function', and 'get_psi_prime_function'; see below.
References:
- Huber, P.J. (1981). Robust Statistics, New York: John Wiley & Sons.
- Hulliger, B. (1995). Outlier Robust Horvitz-Thompson Estimator, Survey
Methodology 21, pp. 79-87.
*/
#include "psifunctions.h"
#define _POWER2(_x) ((_x) * (_x))
double huber_wgt(double, const double);
double huber_psi(double, double);
double huber_psi_prime(double, const double);
double huber_wgt_asym(double, const double);
double huber_psi_asym(double, const double);
double huber_psi_prime_asym(double, const double);
double tukey_wgt(double, const double);
double tukey_psi(double, const double);
double tukey_psi_prime(double, const double);
/******************************************************************************\
|* Obtain the weight (wgt), psi- or psi-prime function associated with a *|
|* psi-function; this wrapper function has its own return type 'f_ptr' *|
\******************************************************************************/
f_ptr get_wgt_function(int psi)
{
switch (psi) {
case 0: // weight of Huber psi-function
return huber_wgt;
case 1: // weight of Huber asymmetric psi-function
return huber_wgt_asym;
case 2: // weight of Tukey biweight psi-function
return tukey_wgt;
default:
return huber_wgt;
}
}
f_ptr get_psi_function(int psi)
{
switch (psi) {
case 0: // Huber psi-function
return huber_psi;
case 1: // Huber asymmetric psi-function
return huber_psi_asym;
case 2: // Tukey biweight psi-function
return tukey_psi;
default:
return huber_psi;
}
}
f_ptr get_psi_prime_function(int psi)
{
switch (psi) {
case 0: // Huber psi-function
return huber_psi_prime;
case 1: // Huber asymmetric psi-function
return huber_psi_prime_asym;
case 2: // Tukey biweight psi-function
return tukey_psi_prime;
default:
return huber_psi_prime;
}
}
/******************************************************************************\
|* psi-function callable from R *|
|* *|
|* x vector, array[n] *|
|* k tuning constant *|
|* n dimension *|
|* psi 0 = Huber, 1 = asymmetric Huber, 2 = Tukey biweight *|
|* res on return: psi(x), array[n] *|
\******************************************************************************/
void psi_function(double *x, double *k, int *n, int *psi, double *res)
{
double (*f_psi)(double, const double);
f_psi = get_psi_function(*psi);
for (int i = 0; i < *n; i++)
res[i] = (*f_psi)(x[i], *k);
}
/******************************************************************************\
|* Huber psi-, psi-prime- and wgt-functions *|
\******************************************************************************/
double huber_psi(double x, const double k)
{
return (x <= -k) ? -k : ((x < k) ? x : k);
}
double huber_psi_prime(double x, const double k)
{
return (fabs(x) <= k) ? 1.0 : 0.0;
}
double huber_wgt(double x, const double k)
{
double z = fabs(x);
if (z > DBL_EPSILON)
return (z >= k) ? k / z : 1.0;
else
return 0.0;
}
/******************************************************************************\
|* Huber asymmetric psi-, psi-prime- and wgt-functions *|
\******************************************************************************/
double huber_psi_asym(double x, const double k)
{
return (x <= k) ? x : k;
}
double huber_psi_prime_asym(double x, const double k)
{
return (x <= k) ? 1.0 : 0.0;
}
double huber_wgt_asym(double x, const double k)
{
double z = fabs(x);
if (z > DBL_EPSILON)
return (x <= k) ? 1.0 : k / x;
else
return 0.0;
}
/******************************************************************************\
|* Tukey biweigt psi-, psi-prime- and wgt-functions *|
\******************************************************************************/
double tukey_psi(double x, const double k)
{
if (fabs(x) > k) {
return 0.0;
} else {
double z = x / k;
double u = 1.0 - _POWER2(z);
return x * _POWER2(u);
}
}
double tukey_psi_prime(double x, const double k)
{
if (fabs(x) > k) {
return 0.0;
} else {
x /= k;
double z = _POWER2(x);
return (1.0 - z) * (1.0 - 5.0 * z);
}
}
double tukey_wgt(double x, const double k)
{
if (fabs(x) > k) {
return 0.0;
} else {
double z = x / k;
z = (1.0 - z) * (1.0 + z);
return _POWER2(z);
}
}
#undef _POWER2
|
C
|
/****************************************************************************
* Returns the total cpu time used in seconds.
* Emulates the Cray fortran library function of the same name.
****************************************************************************/
#ifdef LINUX /* LINUX */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
double second( arg )
double *arg;
{
struct rusage buf;
double t1, t2;
double t11, t12;
double temp;
getrusage( RUSAGE_SELF, &buf );
/* Get system time and user time in SECONDS.*/
#ifdef DEBUG
temp = (double)buf.ru_utime.tv_sec + (double)buf.ru_utime.tv_usec*1.0e-6 +
(double)buf.ru_stime.tv_sec + (double)buf.ru_stime.tv_usec*1.0e-6;
t11 = (double)buf.ru_utime.tv_sec;
t12 = (double)(buf.ru_utime.tv_usec);
printf("SECOND: t11 = %e t12 = %e\n", t11, t12 );
t12 = (double)(buf.ru_utime.tv_usec)*1.0e-6;
printf("SECOND: t11 = %e t12 = %e\n", t11, t12 );
#endif
t1 = (double)buf.ru_utime.tv_sec + (double)(buf.ru_utime.tv_usec)*1.0e-6;
t2 = (double)buf.ru_stime.tv_sec + (double)(buf.ru_stime.tv_usec)*1.0e-6;
temp = t1 + t2;
/* Return the sum of system and user time in SECONDS.*/
return( temp );
}
double dsecnd( arg )
double *arg;
{
return( second( arg ) ) ;
}
#elif AIX
#include <unistd.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/resource.h>
/* Returns the current value of the wall clock timer.
* C entry point.
*/
double
wc_second()
{
struct timeval s_val;
gettimeofday(&s_val,0);
return ((double) s_val.tv_sec + 0.000001 * (double) (s_val.tv_usec));
}
/* Returns the current value of the user+system timer. C entry point.
*/
double
us_second()
{
struct rusage ru;
double tu, ts;
getrusage(RUSAGE_SELF,&ru);
tu = (double) (ru.ru_utime.tv_sec) +
1.0e-6 * (double) (ru.ru_utime.tv_usec);
ts = (double) ru.ru_stime.tv_sec +
1.0e-6 * (double) (ru.ru_stime.tv_usec);
return (tu + ts);
}
/* Returns the current value of the user+system timer. C entry point.
*/
double
dsecnd( arg )
double *arg;
{
return( us_second() );
}
double
second( arg )
double *arg;
{
return( us_second() );
}
#elif _BGL
/*----------------------------------------------------------*/
/* elapsed-time timing functions */
/*----------------------------------------------------------*/
extern unsigned long long rts_get_timebase(void);
static double seconds_per_cycle = 1.4285714285714285714e-9; /* 700 MHz default */
#define WTIME(TB) TB = rts_get_timebase()
#define TCONV(TB1,TB2) seconds_per_cycle*((double) (TB1 - TB2))
double dsecnd(
double *arg)
{
static int first = 1;
static unsigned long long tb0;
unsigned long long tb;
if (first) {
first = 0;
WTIME(tb0);
}
return (TCONV(WTIME(tb), tb0));
}
double second(
double *arg)
{
static int first = 1;
static unsigned long long tb0;
unsigned long long tb;
if (first) {
first = 0;
WTIME(tb0);
}
return (TCONV(WTIME(tb), tb0));
}
#endif
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char s[10000];
scanf("%s",s);
printf("%.2lf\n",strlen(s)*.01);
}
return 0;
}
|
C
|
/*
* TASK 7
* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
* What is the 10 001st prime number?
*
* Result: 104743
*/
#include "euler.h"
long task7() {
/*
* We'll use the sieve of Eratosthenes
* A modified version will be used; here, we only mark the given location with either 1 or 0 and use the
* position indicator for the prime
*
* However, this will NOT work under a 32bit-OS!
* Should be fixed. Could be fixed using a the Segmented Sieve.
*/
if(OS == 32) {
printf("INFO: This is a 32bit OS. Problem 7 can only be calculated under 64bit. =( \n");
return 104743;
}
return sieveOfEratosthenes(10001,false);
}
/**
* This is also used by problem 10
* I know that re-using parameter is horrible, but C doesn't support optional parameter or overloading
* @param limit Either the limit of numbers (if !sum; Problem 7) or the limit of added numbers
* @param sum Sum up the primes? (Problem 10)
* @return Either the limit-st prime (if !sum) or the sum of all primes until limit (if sum)
*/
long sieveOfEratosthenes(int limit, bool sum) {
limit--;
const int UNMARKED = 1;
const int MARKED = 0;
long i = 0, j = 0, counter = 0;
long size = limit*100; // Not exactly accurate. Might need some refining
int* primes = malloc(size * sizeof(int));
int lastPrime = 2;
long long int _sum = lastPrime;
// start at 2. Set all as prime
for (i = lastPrime; i < size; i++) {
// this kills 32bit-OS, since j*i will exceed 2^(32)-1 pretty quickly
*(primes+i) = UNMARKED;
}
*(primes+2) = MARKED;
i = lastPrime;
// Starting from p^(2), enumerate its multiples by counting to n in increments of p, and mark them in the list
do {
for (j = i; (i * j) < size; j++) {
*(primes+j*i) = MARKED;
}
// Find the first number greater than p in the list that is not marked
for (j = lastPrime; j < size; j++) {
if (j > lastPrime && *(primes+j) == UNMARKED) {
// Let p now equal this new number
i = lastPrime = j;
// Increment prime-count
counter++;
if(sum && lastPrime < limit) _sum += i;
if(sum && lastPrime >= limit) return _sum;
//printf("%i, ",lastPrime);
//printf("Found %ith prime (of %i): %i \n",counter,limit,lastPrime);
break;
}
}
} while (counter < limit);
free(primes);
printf("\n");
if(sum) return _sum;
return lastPrime;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <cwctype>
#include <wchar.h>
#include <locale.h>
#include <string.h>
#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <dirent.h>
#define SEPARATOR "/"
int stackSize = 10;
char** stack;
int top = -1;
bool isempty() {
return top == -1;
}
char* pop() {
if(!isempty()) {
return stack[top--];
}
}
void push(char* data) {
top++;
if (top >= stackSize) {
int oldSize = stackSize * sizeof(char*);
stackSize *= 2;
int newSize = stackSize * sizeof(char*);
char** newStack = (char**)malloc(newSize);
memcpy(newStack, stack, oldSize);
stack = newStack;
}
stack[top] = data;
}
void printPermissions(mode_t fileMode) {
printf( (S_ISDIR(fileMode)) ? "d" : "-");
printf( (fileMode & S_IRUSR) ? "r" : "-");
printf( (fileMode & S_IWUSR) ? "w" : "-");
printf( (fileMode & S_IXUSR) ? "x" : "-");
printf( (fileMode & S_IRGRP) ? "r" : "-");
printf( (fileMode & S_IWGRP) ? "w" : "-");
printf( (fileMode & S_IXGRP) ? "x" : "-");
printf( (fileMode & S_IROTH) ? "r" : "-");
printf( (fileMode & S_IWOTH) ? "w" : "-");
printf( (fileMode & S_IXOTH) ? "x" : "-");
}
char* getUserName(uid_t uid) {
struct passwd* passwdEntry = getpwuid(uid);
if (passwdEntry == NULL) {
return "";
}
return passwdEntry->pw_name;
}
char* getGroupName(gid_t gid) {
struct group* groupEntry = getgrgid(gid);
if (groupEntry == NULL) {
return "";
}
return groupEntry->gr_name;
}
void ls(char *path) {
DIR *directory = opendir(path);
if (directory != NULL) {
struct dirent* entry;
while ((entry = readdir(directory)) != NULL) {
if (entry->d_name == NULL) {
continue;
}
// skip .. and .
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char* pathBuffer = (char*)malloc(strlen(path) + strlen(entry->d_name) + 2);
strcat(strcat(strcpy(pathBuffer, path), SEPARATOR), entry->d_name);
struct stat statBuffer;
if (stat(pathBuffer, &statBuffer) == 0) {
char timeBuffer[26];
struct tm* tm_info;
const time_t* mtime = &statBuffer.st_mtime;
tm_info = localtime(mtime);
strftime(timeBuffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
printPermissions(statBuffer.st_mode);
printf(" %s %s %d %s %s\n",
getUserName(statBuffer.st_uid),
getGroupName(statBuffer.st_gid),
statBuffer.st_size,
timeBuffer,
pathBuffer);
if (S_ISDIR(statBuffer.st_mode)) {
push(pathBuffer);
}
}
}
closedir(directory);
}
}
int main(int argc, char** argv) {
stack = (char**)malloc(sizeof(char*) * stackSize);
char* directory = (char*)malloc(26 * sizeof(char));
if (argc == 2) {
strcpy(directory, argv[1]);
} else {
strcpy(directory, ".");
}
push(directory);
while (!isempty()) {
char* dir = pop();
if (argc > 1) {
printf("\n%s:\n", dir);
}
ls(dir);
free(dir);
}
return 0;
}
|
C
|
#include <assert.h>
#include "int_stack.h"
int intstack_new(IntStack *this_, size_t alloc_size)
{
assert(this_);
assert(alloc_size > 0);
int *data = (int *)calloc(alloc_size, sizeof(*data));
if (!data)
{
return ZCPU_ERR_MEM_ALLOC;
}
this_->index = 0;
this_->alloc_size = alloc_size;
this_->data = data;
return ZCPU_OK;
}
void intstack_del(IntStack *this_)
{
if (!this_)
return;
free(this_->data);
this_->data = NULL;
this_->index = 0;
this_->alloc_size = 0;
}
int intstack_push(IntStack *this_, int item)
{
assert(this_);
if (this_->index == this_->alloc_size)
{
return ZCPU_ERR_STACK_OVERFLOW;
}
this_->data[this_->index++] = item;
return ZCPU_OK;
}
int intstack_pop(IntStack *this_, int *item)
{
assert(this_);
if (this_->index == 0)
{
return ZCPU_ERR_STACK_UNDERFLOW;
}
this_->index--;
if (item)
{
*item = this_->data[this_->index];
}
return ZCPU_OK;
}
|
C
|
#include "libmx.h"
void mx_pop_back(t_list **head) {
if (head == NULL || *head == NULL) return NULL;
t_list *delL = NULL;
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
}
else {
while (delL->next->next) {
delL = delL->next;
}
free(delL->next);
delL->next = NULL;
}
|
C
|
// Вывести строчку написаную после двоеточия или то что написано между двумя двоеточиями
#include "Header.h"
#include "Functionlist6.2.c"
int main()
{
char x; // Для повтора
char *RawLine; // Строчка ввода
char *Line; // Форматированая строчка
int Length = 0; // Длинна строк
do
{
Length = StringLength(Length); // Ввод длинны строки
RawLine = MemoryAllocation(Length); // Выделение памяти под первую строку
Line = MemoryAllocation(Length); // Выделение памяти под вторую строку
Input(RawLine, Length); // Ввод сиволов в строку
Calculations(RawLine, Line, Length); // Вычисления
Output(Line); // Вывод линии
printf("Do you want to repeat program? y/n\n"); // Повтор программы y/n
rewind(stdin); // Чистка буфера
scanf_s("%c", &x);
} while (x == 'y');
return 0;
}
|
C
|
#include <stdio.h>
#define N 8 // power of 2
int a[N];
void mark(int x, int y)
{
int i;
for(i = 0; i < y; i++)
a[x]++;
}
rule(int l, int r, int h)
{
int i, j, t;
for (t = 1, j = 1; t <= h; j += j, t++)
for (i = 0; l+j+i <= r; i+= j+j)
mark(l+j+i, t);
}
int main(void)
{
int l = 0, r = N, h = (l+r) /2, i, j;
for (i = 0; i < N; i++)
a[i] = 0;
rule(l, r, h);
for (i = 0; i < N; i++)
{
for (j = 0; j < a[i]; j++)
printf("-");
printf("\n");
printf("\n");
}
printf("-\n");
return 0;
}
|
C
|
#include "system.h"
void fifo32_init(FIFO32_STRUCT *fifo, t_U32 size, t_S32 *buf)
{
fifo->size = size;
fifo->buf = buf;
fifo->free = size;
fifo->flags = 0;
fifo->write_entry = 0;
fifo->read_entry = 0;
}
t_S8 fifo32_put(FIFO32_STRUCT *fifo, t_S32 data)
{
if(fifo->free == 0)
{
fifo->flags = 1;
return -1;
}
fifo->buf[fifo->write_entry] = data;
fifo->write_entry++;
if(fifo->write_entry == fifo->size)
{
fifo->write_entry = 0;
}
fifo->free--;
return 0;
}
t_S32 fifo32_get(FIFO32_STRUCT *fifo)
{
t_S32 data;
if(fifo->free == fifo->size)
{
return -1;
}
data = fifo->buf[fifo->read_entry];
fifo->read_entry++;
if(fifo->read_entry == fifo->size)
{
fifo->read_entry = 0;
}
fifo->free++;
return data;
}
t_U32 fifo32_status(FIFO32_STRUCT *fifo)
{
return fifo->size - fifo->free;
}
|
C
|
#include "math.h"
#include "stdlib.h"
#include "string.h"
#include "array.h"
int** array_chunk(int *array, int arraySize, int chunkSize) { //function to chunk the array with the given chunk size fegew
/*
*array - pointer to array to be chunked
arraySize - number of elements in the array
chunkSize - number of elements to be in each array chunk
return a pointer to the two dimensional array which contains the chunked arrays
*/
int i,j;
float arrSize = (float)arraySize;
int row = (int)ceil(arrSize/chunkSize);
int **data = calloc(row,sizeof(int*));
for(i=0;i<row;i++) {
data[i] = calloc(chunkSize,sizeof(int));
for(j=0;j<chunkSize;j++) {
data[i][j] = array[(i*chunkSize)+j];
}
}
return data;
}
struct new_array array_diff(int *array1, int *array2, int array1_Size, int array2_Size) { //function to check the difference between two arrays
/*
*array1 - pointer to array to be comapared
*array2 - pointer to array to compared with
return a struct which contains difference array and its size*/
int i,j,flag=0,count=0;
struct new_array diff;
int *data = malloc(array1_Size*sizeof(int));
for(i=0;i<array1_Size;i++) {
for(j=0;j<array2_Size;j++) {
if(array1[i]==array2[j]) {
flag=1;
break;
}
}
if(flag==0) {
*(data+count) = array1[i];
count++;
}
flag=0;
}
diff.data = data;
diff.arraySize = count;
return diff;
}
int in_array(int *array,int arraySize,int val) { //function to check whether value exists in an array or not
/*
*array - pointer to array
arraySize - size of the array
val - value to be checked
return 1 if exists otherwise 0
*/
int i;
for(i=0;i<arraySize;i++) {
if(array[i]==val) {
return 1;
}
return 0;
}
}
int* unset(int *array,int arraySize,int val, int key) { //function to remove the element in an array based on key or value
/* *array - pointer to array
arraySize - size of the array
val - value or key to be removed
key - boolean value which tells whether the value that is contained in
val variable is a key or actual value itself.
key = (can take 0 or 1) 0 means value in the val variable is actual value itself
1 means value in val variable is the key in the array to be removed
returns the pointer to the new array with element removed
*/
int i,count=0;
int *data = calloc(arraySize-1,sizeof(int));
for(i=0;i<arraySize;i++) {
if(key==0) {
if(array[i]!=val) {
data[count] = array[i];
count++;
}
} else {
if(i!=val) {
data[count] = array[i];
count++;
}
}
}
return data;
}
struct new_array remove_duplicates_by_value(int *array, int arraySize, int val) { //function to remove the duplicates of passed value
/*
*array - pointer to array
arraySize - size of the array
val - value to be found for duplicates
return a struct which contains mentioned duplicate elements removed array and its size
*/
int i,count=0,val_count=0;
struct new_array duplicate_removed;
int *data = calloc(arraySize,sizeof(int));
for(i=0;i<arraySize;i++) {
if(array[i]==val) {
val_count++;
if(val_count>1) {
continue;
}
}
data[count] = array[i];
count++;
}
duplicate_removed.arraySize = count;
duplicate_removed.data = data;
return duplicate_removed;
}
struct new_array array_pop(int *array,int arraySize) { //function to remove the last element from the array and return it
/*
*array - pointer to array
arraySize - size of the array
return a struct which contains the last element and the pointer to new array.*/
struct new_array arraypop;
int *data = calloc(arraySize-1,sizeof(int));
memcpy(data,array,((arraySize-1)*sizeof(int)));
arraypop.arraySize = array[arraySize-1];
arraypop.data = data;
return arraypop;
}
struct new_array array_push(int *array, int arraySize, int val) { //function to push an element to an array
/*
*array - pointer to array
arraySize - size of the array
return a struct which contains the pointer to the new array and count of the array*/
struct new_array arraypush;
int *data = calloc(arraySize+1,sizeof(int));
memcpy(data,array,((arraySize)*sizeof(int)));
data[arraySize] = val;
arraypush.arraySize = arraySize+1;
arraypush.data = data;
return arraypush;
}
struct new_array array_slice(int *array,int arraySize, int startIndex, int length) { //array to return an slice of an array
/*
*array - pointer to the array
arraySize - size of the array
startIndex - starting point for slicing
Length - Length of the slice
return a struct which contains new sliced array and its count*/
int i,count=0;
struct new_array arraySlice;
int *data = calloc((startIndex+length-1),sizeof(int));
for(i=startIndex;i<length-1;i++) {
data[count]= array[i];
count++;
}
arraySlice.arraySize = count;
arraySlice.data = data;
return arraySlice;
}
int array_sum(int *array,int arraySize) { //function to add all elements of an array
/*
*array - pointer to an array
arraySize - size of an array
return the sum of all elements of an array*/
int i,sum=0;
for(i=0;i<arraySize;i++) {
sum+=array[i];
}
return sum;
}
int array_product(int *array,int arraySize) { //function to multiply all elements of an array
/*
*array - pointer to an array
arraySize - size of an array
return the product of all elements of an array*/
int i,product=0;
for(i=0;i<arraySize;i++) {
if(array[i]==0) {
return 0;
}
product*=array[i];
}
return product;
}
int* array_reverse(int *array, int arraySize) { //function to return elements in reverse order
/*
*array - pointer to the array
arraySize - size of the array
return the pointer to the new array which contains the elements in reverse order*/
int i,count=0;
int *data = calloc(arraySize,sizeof(int));
for(i=arraySize-1;i>=0;i--) {
data[count] = array[i];
count++;
}
return *data;
}
int array_search(int *array, int arraySize,int val) { //returns the key for the given value in the array
/*
*array - pointer to the array
val - value for which the key should be found
arraySize - size of the array
return the key corresponding to the given value*/
int i,key;
for(i=0;i<=arraySize;i++) {
if(array[i]==val) {
key = i;
break;
}
}
return key;
}
}
|
C
|
//DIÞARDAN GÝREN SAYININ RAKAMLARINI TOPLAYAN PROGRAM
#include<stdio.h>
#include<conio.h>
int main()
{
int sayi,toplam=0,k,ilksayi;
printf("sayi gir :");
scanf("%d",&sayi);
ilksayi = sayi;
while (sayi>0)
{
k = sayi % 10;
sayi = sayi / 10;
toplam = toplam + k;
}
printf("%d",toplam);
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "FunCpIOLA.h"
/****************************************************************************************
*********************** SOLICITAR INT, FLOAT, CHAR Y VALIDAMOS *************************
***************************************************************************************/
float getFloat(char mensaje[])
{
float auxiliar;
printf("%s", mensaje);
scanf("%f", &auxiliar);
return auxiliar;
}
int getInt(char mensaje[])
{
int auxiliar;
printf("%s", mensaje);
scanf("%d", &auxiliar);
return auxiliar;
}
char getChar(char mensaje[])
{
char auxiliar;
printf("%s", mensaje);
fflush(stdin); //LIMPIA LA BASURA
scanf("%c", &auxiliar);
return auxiliar;
}
char getNumeroAleatorio(int desde, int hasta, int iniciar)
{
if(iniciar)
srand(time(NULL));
return desde + (rand() % (hasta + 1 - desde));
}
int esNumerico(char str[])
{
int i = 0;
while(str[i] != '\0')
{
if(str[i] < '0' || str[i] > '9')
return 0;
i++;
}
return 1;
}
int esSoloLetras(char str[])
{
int i = 0;
while(str[i] != '\0')
{
if((str[i] != ' ') && (str[i] < 'a' || str[i] > 'z') && (str[i] < 'A' || str[i] > 'Z'))
return 0;
i++;
}
return 1;
}
int esAlfaNumerico(char str[])
{
int i = 0;
while(str[i] != '\0')
{
if((str[i] != ' ') && (str[i] < 'a' || str[i] > 'z') && (str[i] < 'A' || str[i] > 'Z') && (str[i] < '0' || str[i] > '9'))
return 0;
i++;
}
return 1;
}
int esTelefono(char str[])
{
int i = 0;
int contadorGuiones = 0;
while(str[i] != '\0')
{
if((str[i] != ' ') && (str[i] != '-') && (str[i] < '0' || str[i] > '9'))
return 0;
if(str[i] == '-')
contadorGuiones++;
i++;
}
if(contadorGuiones == 1) //DEBE TENER UN GUION
return 1;
return 0;
}
void getString(char mensaje[], char input[])
{
printf(mensaje);
scanf("%s", input);
}
int getStringLetras(char mensaje[], char input[])
{
char aux[256];
getString(mensaje,aux);
if(esSoloLetras(aux))
{
strcpy(input,aux);
return 1;
}
return 0;
}
int getStringNumeros(char mensaje[], char input[])
{
char aux[256];
getString(mensaje,aux);
if(esNumerico(aux))
{
strcpy(input,aux);
return 1;
}
return 0;
}
int getStringNumerosFlotantes(char mensaje[],char input[])
{
char aux[256];
getString(mensaje,aux);
if(esNumericoFlotante(aux))
{
strcpy(input,aux);
return 1;
}
return 0;
}
int getValidInt(char requestMessage[],char errorMessage[], int* input,int lowLimit, int hiLimit,int attemps)
{
char auxStr[256];
int auxInt, i, retorno = -1;
for(i=0;i<attemps;i++)
{
if (!getStringNumeros(requestMessage,auxStr))
{
printf ("%s",errorMessage);
break;
continue;
}
auxInt = atoi(auxStr);
if(auxInt < lowLimit || auxInt > hiLimit)
{
printf ("%s",errorMessage);
continue;
}
*input = auxInt;
retorno = 0;
break;
}
return retorno;
}
int getValidString(char requestMessage[],char errorMessage[], char errorMessageLenght[],char input[], int maxLenght,int attemps)
{
int i;
int retorno=-1;
char buffer[1024];
for(i=0;i<attemps;i++)
{
if (!getStringLetras(requestMessage,buffer))
{
printf ("%s",errorMessage);
continue;
}
if(strlen(buffer) >= maxLenght)
{
printf ("%s",errorMessageLenght);
continue;
}
retorno=0;
strcpy(input,buffer);
break;
}
return retorno;
}
int getValidFloat(char requestMessage[],char errorMessage[], float* input,float lowLimit, float hiLimit,int attemps)
{
char auxStr[256];
int i, retorno = -1;
float auxInt;
for(i=0;i<attemps;i++)
{
if (!getStringNumerosFlotantes(requestMessage,auxStr))
{
printf ("%s",errorMessage);
break;
continue;
}
auxInt = atof(auxStr);
if(auxInt < lowLimit || auxInt > hiLimit)
{
printf ("%s",errorMessage);
continue;
}
*input = auxInt;
retorno = 0;
break;
}
return retorno;
}
/**
* \brief Limpia el stdin, similar a fflush
* \param -
* \return -
*
*/
void clearStdin(void)
{
setbuf(stdin,NULL);
}
/**
* \brief Hace una pausa, similar al system("pause")
* \param -
* \return -
*
*/
void pause(void)
{
getChar("");
}
/**
* \brief Hace un clear, similar al system("clear")
* \param -
* \return -
*
*/
void clearScreen(void)
{
system("clear"); //system("cls");
}
/****************************************************************************************
*************************** FIN DE FUNCIONES ********************************************
****************************************************************************************/
|
C
|
#include <ipconf.h>
#include "net_sas.h"
void errno_task(TOOL_VP_INT exinf);
/* MODULE_HDR +----------------------------------------------------------+
**
** <W[> SAS_ERRNO_01
**
** <> SAS_ERRNO_01( void )
**
** Ȃ
**
** <^[l> sXe[^X (BOOL) TEST_PASS I
** TEST_FAIL ُI
**
** <@\> DUAL04_errno ɑ G[B
**
** <l> ( 0 )o͂,OK
+-----------------------------------------------------------------------+
** <ύX>
** Date Reason Ver. Name
** ( 040721 )(Original )(1.0 )(s.i )
-----------------------------------------------------------------------+*/
int SAS_ERRNO_01(void)
{
int ret;
TOOL_T_RTSK rtsk;
TOOL_T_CTSK ctsk;
TOOL_ID tid;
TOOL_ER ercd;
/* ^XNԂ̊mF */
if(TOOL_ref_tsk (TOOL_TSK_SELF, &rtsk) != 0){
NET_printf("Can't fork, error=%d\n", ercd);
return TEST_FAIL;
}
/* ^XNID̎擾 */
TOOL_get_tid (&tid);
/* q^XNNݒ */
ctsk.tskatr = TA_HLNG | TA_ACT;
ctsk.task = (TOOL_FP)errno_task;
ctsk.exinf = (TOOL_VP_INT) &tid;
ctsk.itskpri = rtsk.tskpri - 1;
ctsk.stksz = 16384;
ctsk.stk = NULL;
/* q^XNN */
#ifndef TEST_TOOL_CSS
if( (ercd = acre_tsk(&ctsk)) < 0 ) {
NET_printf("Can't fork, error=%d\n", ercd);
return TEST_FAIL;
}
#else
if (send_tstart_msg(QID_TEST_TASK1, &ctsk) < 0) {
NET_printf("Can't fork\n");
return TEST_FAIL;
}
#endif /* TEST_TOOL_CSS */
/* 3b̑҂ */
(void)TOOL_tslp_tsk(3000);
/* NCAgNʒm */
saSendReply(saCntlSock, REP_READY);
return TEST_PASS;
}
void errno_task(TOOL_VP_INT exinf)
{
int ret;
int err;
char sname[20];
TOOL_ID* ptid = (TOOL_ID *)exinf;
/* ^XNN */
if (NET_open (-(*ptid)) != 0)
{
TOOL_exd_tsk ();
return;
}
/* create ap_proc structure */
ap_proc_create();
/* */
memset(sname, 0x00, sizeof(sname));
/* ViIݒ */
sprintf(sname, "%s", "SAS_ERRNO_01()");
/* ݒ肳ĂȂł낤errNO̎擾s0i[Ă邱ƂmF */
ret = errno();
/* ʔ */
if(ret < 0){
err = NET_errno();
sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err);
sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does occur.)\n", sname);
NET_close();
TOOL_exd_tsk ();
return;
} else {
err = NET_errno();
sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err);
if ( err != 0 ){
sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname);
NET_close();
TOOL_exd_tsk ();
return;
}
}
sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname);
NET_close();
TOOL_exd_tsk ();
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void quickSort(int *vetor, int inicio, int fim){
int i, j, meio, aux;
i = inicio;
j = fim;
meio = vetor[(inicio + fim) / 2];
do{
while(vetor[i] < meio)
i++;
while(vetor[j] > meio)
j--;
if(i <= j){
aux = vetor[i];
vetor[i] = vetor[j];
vetor[j] = aux;
i++;
j--;
}
}while(i <= j);
if(inicio < j)
quickSort(vetor, inicio, j);
if(i < fim)
quickSort(vetor, i, fim);
}
int main(){
int v[10], i;
printf("Entre os %d elementos do vetor:\n", 10);
for(i = 0; i < 10; i++){
scanf("%d", &v[i]);
}
quickSort(v, 0, 9); //vetor, incio, fim
printf("\n\nVetor ordenado:\n");
for(i = 0; i < 10; i++){
printf("%d\t", v[i]);
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
//1 Passo: Declaracao das Variaveis
float codigo, unidades, preco, desconto, precof;
//2 Passo:Entrada de Dados
printf("Digite o Codigo do produto comprado: ");
scanf("%f", &codigo);
printf("Digite a quantidade de produtos: ");
scanf("%f", &unidades);
//3 e 4 Passo:Processamento/Saida de Dados
if(codigo >= 1 && codigo <= 10){
preco = 10 * unidades;
printf("O preço por unidade do produto comprado e = 10 \n");
printf("O preço total da nota e = %.2f\n", preco);
}else if(codigo >= 11 && codigo <= 20){
preco = 15 * unidades;
printf("O preco por unidade do produto comprado e = 15 \n");
printf("O preco total da nota e = %.2f\n", preco);
}else if(codigo >= 21 && codigo <= 30){
preco = 20 * unidades;
printf("O preco por unidade do produto comprado e = 20 \n");
printf("O preco total da nota e = %.2f\n", preco);
}else if(codigo >= 31 && codigo <= 40){
preco = 30 * unidades;
printf("O preco por unidade do produto comprado e = 30 \n");
printf(") preco total da nota e = %.2f\n", preco);
}else {
printf("ERRO: (NAO EXITE ESSE CODIGO)");
}
if(preco <= 250){
desconto = preco * 0.05;
precof = preco - desconto;
printf("O valor do desconto e = %.2f\n", desconto);
printf("O preco final apos o desconto e = %.2f\n", precof);
}else if(preco >= 250 && preco <= 500){
desconto = preco * 0.10;
precof = preco - desconto;
printf("O valor do desconto e = %.2f\n", desconto);
printf("O preco final apos o desconto e = %.2f\n", precof);
}else if(preco > 500){
desconto = preco *0.15;
precof = preco - desconto;
printf("O valor do desconto e = %.2f\n", desconto);
printf("O preco final apos o desconto e = %.2f\n", precof);
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** zappy
** File description:
** broadcast command
*/
#include "server.h"
/*!
* @brief prints the message on file descriptor of receiver
* @param receive_fd file descriptor of receiver
* @param sender_fd file descriptor of sender
* @param name name of team of sender
* @param mess message to be sent
*/
void print_message(int receive_fd, int sender_fd, char *mess, server_t *server)
{
players_t *receiver = get_current_player(receive_fd, server);
players_t *sender = get_current_player(sender_fd, server);
int broad_nb = get_broadcast_nb(receiver, sender);
if (receive_fd != sender_fd) {
if (dprintf(receive_fd, REPL_BROAD, broad_nb, mess) < 0)
exit(ERROR);
}
}
/*!
* @brief browses teams and players to propagate message
* @param player current player
* @param team team of current player
* @param server struct containing server infos
* @param mess tje message to be sent
*/
void propagate_message(players_t *player, server_t * server, \
char *mess)
{
teams_t *tmp = server->teams;
players_t *tmp_p;
for (; tmp != NULL; tmp = tmp->next) {
tmp_p = tmp->players;
for (; tmp_p != NULL; tmp_p = tmp_p->next)
print_message(tmp_p->fd, player->fd, mess, server);
}
}
/*!
* @brief broadcasts a message to all clients actually connected to server
* @param server struct containing server infos
* @param action action element of current action
* @param fd file descriptor of current client
*/
void broadcast_command(server_t *server, actions_t *action, int fd)
{
players_t *player = get_current_player(fd, server);
teams_t *team = get_team_by_player(player, server);
if (player != NULL && team != NULL) {
propagate_message(player, server, action->tab[1]);
pbc(server, player, action->tab[1]);
if (dprintf(fd, REPL_OK) < 0)
exit(ERROR);
}
}
|
C
|
//\===========================================================================================
//\ File: gba_input.h
//\ Author: Morgan James
//\ Date Created: 13/11/2017
//\ Brief: Outlines the registers for GBA Key Input and provides functionality for handling key presses.
//\===========================================================================================
#include "gba_registry.h"
#include "gba_types.h"
#ifndef __GBA_INPUT_H__
#define __GBA_INPUT_H__
//\===========================================================================================
//\ Key Registry Defines
//\===========================================================================================
#define REGISTRY_KEY_INPUT *(vu16*)(REGISTRY_BASE + 0x130)//Define for Hardware Key Input Register.
#define REGISTRY_KEY_CONTROL *(vu16*)(REGISTRY_BASE + 0x132)//Define for Hardware Key Interrupt Control Register.
//\===========================================================================================
//\ Key Enumerations
//\===========================================================================================
typedef enum KEYS//An enumeration for all GBA keys and inputs.
{
A = (1 << 0), //Button A.
B = (1 << 1), //Button B.
SELECT = (1 << 2), //Select button.
START = (1 << 3), //Start button.
RIGHT = (1 << 4), //Right D-pad.
LEFT = (1 << 5), //Left D-pad.
UP = (1 << 6), //Up D-pad.
DOWN = (1 << 7), //Down D-pad.
R = (1 << 8), //Shoulder R.
L = (1 << 9), //Shoulder L.
SHOULDER = (1 << 10), //L or R.
ANY = 0x03FF, //any key.
ANYDPAD = 0x00F0, //any D-pad.
ACCEPT = 0x0009, //A or start.
CANCEL = 0x0002, //B (well, it usually is).
RESET = 0x000F, //St+Se+A+B.
KEYIRQ_ENABLE = (1 << 14), //Enable keypad interrupt.
KEYIRQ_OR = (0 << 15), //interrupt logical OR mode.
KEYIRQ_AND = (1 << 15), //interrupt logical AND mode.
}KEYS;
//\===========================================================================================
//\ Functions For Keys
//\===========================================================================================
#define KEY_MASK 0x03FF//Define for the key mask.
extern u16 u16CurrentKeys, u16PreviousKeys;//Variables to hold the current and previous state of the hardware keys.
extern void PollKeys();//Function to test for Hardware Key Depress.
extern u16 CurrentKeyState(); //Get current key state.
extern u16 PreviousKeyState(); //Get previous key state.
extern u32 KeyDown(u32 a_u32Key); //Gives the keys of \a key that are currently down.
extern u32 KeyUp(u32 a_u32Key); //Gives the keys of \a key that are currently up.
extern u32 KeyHeld(u32 a_u32Key); //Gives the keys of \a key that are pressed.
extern u32 KeyReleased(u32 a_u32Key); //Gives the keys of \a key that are released.
extern u32 KeyHit(u32 a_u32Key); //Gives the keys of \a key that are hit.
extern u32 KeyStateChange(u32 a_u32Key); //Gives the keys of \a key that are changed.
typedef enum AXIS//An enumeration for the axis'.
{
HORIZONTAL = 0,//The horizontal axis.
VERTICAL,//The vertical axis.
}AXIS;
extern s32 GetAxis(AXIS a_u32Val);//A function to get the axis.
#endif//__GBA_INPUT_H__
|
C
|
#include <string.h>
#include "./List.h"
#define NAME_LENGTH 20
#define TWITTER_TEXT_LENGTH 140
typedef struct s_userInfo {
int tweetCount;
int mentionCount;
int retweetCount;
int likeCount;
} UserInfo;
UserInfo UserInfo_New(int tweetCount, int mentionCount, int retweetCount, int likeCount);
typedef struct s_User {
char name[NAME_LENGTH];
UserInfo info;
} User;
User User_New(char name[NAME_LENGTH], UserInfo info);
typedef struct s_HashTag {
char name[20];
List* tweetList;
int tweetCount;
} Hashtag;
Hashtag Hashtag_New(char name[NAME_LENGTH]);
typedef struct s_Tweet {
User *creator;
int reTweetCount;
int likeCount;
char text[TWITTER_TEXT_LENGTH];
List* mentionList;
List* hashtagList;
} Tweet;
Tweet Tweet_New(User* creator, int reTweetCount, int likeCount, char text[TWITTER_TEXT_LENGTH]);
void opA(int qttHash, int qttCit); // Listar as hastags mais citadas em toda rede.
void opB(int userQtt); // Listar os usurios que mais postam tweets.
void opC(int tweetsQtt); // Listar os tweets com maior nmero de retweets.
void opD(int userQtt); // Listar os usurios mais mencionados nos tweets.
void opE(int userQtt); // Listar os usurios mais influentes (aquele que possui o maior nmero de retweets.)
void opF(int userQtt); // Listar os usurios mais engajados da rede. Engajamento a interao do pblico com as postagens do usurio e determina o alcance das postagens. O engajamento contabilizado pela somatrio da quantidade de interaes dos tweets de um usurio, que inclui: gostar do tweet (like), quantidade de retweets e quantidade de menes ao usurio.
|
C
|
#include "monty.h"
/**
* pop - release memory
*
* @stack: stack
* @line_number: number of line
*
* Return: nothing
*/
void pop(stack_t **stack, unsigned int line_number)
{
stack_t *vector;
vector = *stack;
if (vector == NULL)
{
free(release.temp);
free(release.containerFile);
free_h(stack);
fclose(release.openFile);
fprintf(stderr, "L%u: can't pop an empty stack\n", line_number);
exit(EXIT_FAILURE);
}
(*(stack)) = (*(stack))->next;
free(vector);
}
|
C
|
#include "../../includes/ft_lib_push_swap.h"
void ft_checking_pos(t_env *vn, int pos)
{
int rank;
rank = val_to_rank(vn, vn->a->tab[in(vn->a->bot + pos)]);
ft_checking(vn, rank);
}
int ft_calc_head(t_env *vn, int rank)
{
int pos;
int bot;
int count;
int tmp;
count = 1;
bot = vn->a->bot;
tmp = rank_to_pos_a(vn, rank);
pos = tmp - 1;
while (pos >= 0)
{
if (vn->a->tab[in(bot + pos)] > vn->a->tab[in(bot + tmp)])
{
count++;
tmp = pos;
}
pos--;
}
return (count);
}
void ft_select_to_b(t_env *vn, t_ps *ps)
{
int i;
int tmp;
int pos;
int bot;
i = 0;
bot = vn->a->bot;
ps->head = i;
ps->moves = ft_calc_head(vn, ps->head);
i++;
while (i < vn->len)
{
tmp = ft_calc_head(vn, i);
if (ps->moves < tmp || (ps->moves == tmp && i < ps->head))
{
ps->moves = tmp;
ps->head = i;
}
i++;
}
pos = rank_to_pos_a(vn, ps->head);
ft_checking_pos(vn, pos);
tmp = pos;
pos--;
while (pos >= 0)
{
if (vn->a->tab[in(bot + pos)] > vn->a->tab[in(bot + tmp)])
{
ft_checking_pos(vn, pos);
tmp = pos;
}
pos--;
}
}
int ft_is_true(t_env *vn, int val)
{
int i;
i = 0;
while (i <= vn->len - 1)
{
if (vn->org[i] == val)
{
return (vn->cb[i]);
}
i++;
}
return (-1);
}
int ft_is_f_in_a(t_env *vn)
{
int i;
int len;
i = 0;
len = st_nb_elem(vn->a);
while (i < len)
{
if (!ft_is_true(vn, vn->a->tab[in(vn->a->bot + i)]))
return (1);
i++;
}
return (0);
}
void ft_a_to_b(t_env *vn, t_ps *ps)
{
(void)ps;
while (ft_is_f_in_a(vn))
{
if (!ft_is_true(vn, vn->a->tab[in(vn->a->top)]))
{
ft_putstr("pb\n");
pb(vn->b, vn->a);
}
else
{
ft_putstr("ra\n");
ra(vn->a);
}
}
}
void printf_ps(t_st *st) //
{
int i;
if (st_is_empty(st) == 0)
{
i = st->top;
while (i >= st->bot)
{
printf("(%d)\n", st->tab[in(i)]);
i--;
}
}
printf("\n=--=\n");
}
int maxi(int a, int b)
{
return ((a >= b)? a : b);
}
int ft_calc_longest_inc_subarr(t_env *vn, int index)
{
int result = 1;
int *f;
f = (int*)malloc(sizeof(int) * (index + 1));
/*for (int i=1; i <= index; i++)
{
f[i] = 0;
for (int j=0; j<i; j++)
{
if (vn->org[j] < vn->org[i])
f[i] = maxi(f[i], f[j] + 1);
}
result = maxi(result, f[i]);
}*/
for (int i=0; i<=index; i++)
{
f[i] = 0;
for (int j=i-1; j>=0; j--)
{
if (vn->org[i] > vn->org[j])
f[i] = maxi(f[i], f[j]);
}
f[i] += 1;
result = maxi(result, f[i]);
}
free(f);
return (result);
}
int lis(t_env *vn, int* a, int len ) {
int *best, i, j, max = 0;
int *p;
best = (int*) malloc ( sizeof( int ) * len );
p = (int*) malloc ( sizeof( int ) * len );
for ( i = 0; i < len; i++ )
{
best[i] = 1;
p[i] = -1;
}
for ( i = 1; i < len; i++ )
{ for ( j = 0; j < i; j++ )
{
if ( a[i] < a[j] && best[i] < best[j] + 1 )
{
best[i] = best[j] + 1;
p[i] = j;
if(best[max] < best[i])
max = i;
}
}
}
i = max;
while (1)
{
vn->cb[i] = 1;
i = p[i];
if (i == -1)
break ;
}
free(best);
free(p);
return max;
}
void ft_select_to_b_new(t_env *vn)
{
lis(vn, vn->org, vn->len);
}
void push_swap(t_env *vn, t_ps *ps)
{
ft_select_to_b_new(vn);
ft_a_to_b(vn, ps);
ft_select_to_a(vn, ps);
ft_align_a(vn, ps);
}
|
C
|
#include <pebble.h>
static Window *s_window;
static TextLayer *s_text_layer;
static PreferredContentSize s_content_size;
static void prv_window_load(Window *window) {
Layer *window_layer = window_get_root_layer(s_window);
GRect bounds = layer_get_bounds(window_layer);
s_text_layer = text_layer_create((GRect) { .origin = { 0, 50 }, .size = { bounds.size.w, 80 } });
text_layer_set_text_alignment(s_text_layer, GTextAlignmentCenter);
// Change font size based on ContentSize
switch(s_content_size) {
case PreferredContentSizeSmall:
text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD));
text_layer_set_text(s_text_layer, "Content Size\nSmall");
break;
case PreferredContentSizeMedium:
text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD));
text_layer_set_text(s_text_layer, "Content Size\nMedium");
break;
case PreferredContentSizeLarge:
text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD));
text_layer_set_text(s_text_layer, "Content Size\nLarge");
break;
case PreferredContentSizeExtraLarge:
text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD));
text_layer_set_text(s_text_layer, "Content Size\nExtra Large");
break;
default:
break;
}
layer_add_child(window_layer, text_layer_get_layer(s_text_layer));
}
static void prv_window_unload(Window *window) {
text_layer_destroy(s_text_layer);
}
static void prv_init(void) {
s_window = window_create();
window_set_window_handlers(s_window, (WindowHandlers) {
.load = prv_window_load,
.unload = prv_window_unload,
});
// Detect ContentSize setting
s_content_size = preferred_content_size();
window_stack_push(s_window, true);
}
static void prv_deinit(void) {
window_destroy(s_window);
}
int main(void) {
prv_init();
app_event_loop();
prv_deinit();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ps_step_3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gsinged <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/16 11:56:58 by gsinged #+# #+# */
/* Updated: 2020/11/16 11:57:02 by gsinged ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int ft_three(t_ps *ps)
{
while (!ft_dllst_q_sort(ps->a))
ft_move(ps, 11);
if (ft_dllst_q_sort(ps->a) == 1)
return (1);
else
{
if (ft_dllst_position_min(ps->a, NULL) == 2)
ft_move(ps, 31);
else
ft_move(ps, 41);
}
if (ft_dllst_q_sort(ps->a) == 1)
return (1);
return (0);
}
void ps_step3_sort(t_ps *ps)
{
int i;
t_dllist *min;
i = ft_dllst_position_min(ps->a, &min);
if (i <= (ps->na / 2) + 1)
{
while (ps->a != min)
ft_move(ps, 31);
}
else
{
while (ps->a != min)
ft_move(ps, 41);
}
}
void ps_step3_two(t_ps *ps)
{
int i;
i = ft_dllst_position_max(ps->a, NULL);
i = ps->na - i;
while (i-- > 0)
ft_move(ps, 41);
if (ps->a->n > ps->a->next->n)
ft_move(ps, 11);
}
void ps_step_3(t_ps *ps)
{
int m;
int ch;
int len;
ch = ft_dllst_max_chunk(ps->a);
m = ft_dllst_medium_n_chunk(ps->a, ch);
len = ft_dllst_lenght_chunk(ps->a, ch);
while (len > 2)
{
ps_step1_chunk(ps, m);
ch = ft_dllst_max_chunk(ps->a);
m = ft_dllst_medium_n_chunk(ps->a, ch);
len = ft_dllst_lenght_chunk(ps->a, ch);
}
ps_step3_two(ps);
}
|
C
|
#include <stdlib.h>
#include <mpi.h>
int IncOrder(const void *e1, const void *e2)
{
return (*((int *) e1) - *((int *) e2));
}
/* This is the CompareSplit function */
void CompareSplit(int nlocal, int *elements, int *relements, int *wspace, int keepsmall)
{
int i, j, k;
for (i = 0; i < nlocal; i++)
{
wspace[i] = elements[i]; // Copy the elements array into the wspace array
}
if (keepsmall)
{
// Keep the nlocal smaller elements
for (i = j = k = 0; k < nlocal; k++)
{
if (j == nlocal || (i < nlocal && wspace[i] < relements[j]))
{
elements[k] = wspace[i++];
}
else
{
elements[k] = relements[j++];
}
}
}
else
{
// Keep the nlocal larger elements
for (i = k = nlocal - 1, j = nlocal - 1; k >= 0; k--)
{
if (j == 0 || (i >= 0 && wspace[i] < relements[j]))
{
elements[k] = wspace[i--];
}
else
{
elements[k] = relements[j--];
}
}
}
}
void main(int argc, char *argv[])
{
int n;
int npes; // N processors
int myrank;
int nlocal;
int *elements; // Array that stores local elements
int *relements; // Araray that stores received elements
int oddrank;
int evenrank;
int *wspace;
int i;
MPI_Status status;
// Initialize MPI and get system information
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &npes);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
n = atoi(argv[1]);
nlocal = n/npes;
// Allocate memory
elements = (int *)malloc(nlocal*sizeof(int));
relements = (int *)malloc(nlocal*sizeof(int));
wspace = (int *)malloc(nlocal*sizeof(int));
// Fill in the elements array with random elements
srandom(myrank);
for (i = 0; i < nlocal; i++)
{
elements[i] = random();
}
// sort the local elements using built-in quicksort
qsort(elements, nlocal, sizeof(int), IncOrder);
// Determine the rank fo the processors that myrank needs to communicate during
// the odd and even phases of the algorithm
if (myrank % 2 == 0)
{
oddrank = myrank - 1;
evenrank = myrank + 1;
}
else
{
oddrank = myrank + 1;
evenrank = myrank - 1;
}
// Set the ranks of the processors at the end of the linear
if (oddrank == -1 || oddrank == npes)
oddrank = MPI_PROC_NULL;
if (evenrank == -1 || evenrank == npes)
evenrank = MPI_PROC_NULL;
// Get into the main loop of the odd-even sorting algorithm
for (i = 0; i < npes - 1; i++)
{
if (i % 2 == 1)
{
// Odd phase
MPI_Sendrecv(elements, nlocal, MPI_INT, oddrank, 1, relements, nlocal, MPI_INT, oddrank, 1, MPI_COMM_WORLD, &status);
}
else
{
// Even phase
MPI_Sendrecv(elements, nlocal, MPI_INT, evenrank, 1, relements, nlocal, MPI_INT, evenrank, 1, MPI_COMM_WORLD, &status);
}
CompareSplit(nlocal, elements, relements, wspace, myrank < status.MPI_SOURCE);
}
free(elements); free(relements); free(wspace);
MPI_Finalize();
}
|
C
|
/* $Id$ */
#include <ptable-utils.h>
PTBL_Production PTBL_LookUpProduction(PTBL_ParseTable pt, int label) {
PTBL_Labels labels = PTBL_getParseTableLabels(pt);
ATermInt num = ATmakeInt(label);
PTBL_Label head;
for (; !PTBL_isLabelsEmpty(labels); labels = PTBL_getLabelsTail(labels)) {
head = PTBL_getLabelsHead(labels);
if (ATisEqual(PTBL_getLabelNumber(head), num)) {
return PTBL_getLabelProduction(head);
}
}
ATwarning("PTBL_LookUpProduction: production %d not found\n", label);
return NULL;
}
|
C
|
/*************************************************
文件名:zuoye2.c
功 能:统计文件中英文字母个数并输出出现最多的字母
版本号:0.0.1
*************************************************/
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int i,j,fd1=0,rd_data=0,letter[26]={0},max;
char ch;
/*打开文件*/
fd1=open("file.txt",O_RDONLY);
if(fd1<0)
{
perror("file.txt open error");
return -1;
}
while(1)
{
/*统计字母(不区分大小写)*/
rd_data=read(fd1,&ch,1);
if(rd_data<=0) break;
for(i=65;i<91;i++)
{
if(ch==i||ch==i+32)
letter[i-65]++;
}
}
/*查找出现最多的字母*/
max=letter[0];j=0;
for(i=65;i<91;i++)
{
if(letter[i-65]>max)
{
max=letter[i-65];
j=i;
}
}
printf("出现最多的字母为%c,出现了%d次\n",j,max);
close(fd1);
}
|
C
|
#include <string.h>
char* strrchr(const char source[static 1], int character)
{
unsigned char c = character;
if (!c)
return (char*)(source + strlen(source));
char* found = 0;
char* candidate;
while ((candidate = strchr(source, character))) {
found = candidate;
source = candidate + 1;
}
return found;
}
|
C
|
/**************************************************************
5079번
jongtae0509
C
정확한 풀이코드 길이:289 byte(s)
수행 시간:0 ms
메모리 :1120 kb
****************************************************************/
#include<stdio.h>
int main(){
int v,i,a=0,b=0;
char s[20]={};
scanf("%d",&v);
scanf("%s",s);
for(i=0;i<v;i++){
if(s[i]=='A'){
a++;
}
else if(s[i]=='B'){
b++;
}
}
if(a>b){
puts("A");
}
else if(a==b){
puts("Tie");
}
else{
puts("B");
}
}
|
C
|
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
FILE *log_file;
double
dwalltime()
{
double sec;
struct timeval tv;
gettimeofday(&tv, NULL);
sec = tv.tv_sec + tv.tv_usec / 1000000.0;
return sec;
}
void
print_log(const char *s, ...)
{
va_list args;
va_start(args, s);
vfprintf(log_file, s, args);
fflush(log_file);
va_end(args);
}
void
init_log(const char *filename, const char *mode)
{
log_file = fopen(filename, mode);
print_log("Log file path: %s\n", filename);
}
|
C
|
#ifndef PRODUCT
#define PRODUCT
struct Product{
int item; // which kind of product, not the id;
int category; // optional now;
double weight; //
int max_number[3]; // the maximum item number for small,
public:
Product(){
item = -1;
category = -1;
double weight = 0;
max_number[0] = 0;
max_number[1] = 0;
max_number[2] = 0;
}
Product(int i, int c, double w, int number1, int number2, int number3){
item = i;
category = c;
weight = w;
max_number[0] = number1;
max_number[1] = number2;
max_number[2] = number3;
}
int getItem() {return item;}
int getCategory() {return category;}
double getWeight() {return weight;}
int getNumber1() {return max_number[0];}
int getNumber2() {return max_number[1];}
int getNumber3() {return max_number[2];}
void setItem(int i) { item = i; }
void setCategory(int c) { category = c; }
void setWeight(double w) { weight = w; }
void setNumber1(int number1) { max_number[0] = number1; }
void setNumber2(int number2) { max_number[1] = number2; }
void setNumber3(int number3) { max_number[2] = number3; }
};
#endif // PRODUCT
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void insert(char*, int);
void delete();
void list();
void save_data (char*);
void read_data (char*);
typedef struct node {
char table_name[20];
int table_size;
struct node *next;
} INFO_NODE;
INFO_NODE *heads[4];
INFO_NODE *tails[4];
int main (int argc, char *argv[]) {
int input;
char name[20];
int size;
if (argc == 1) {
printf("The file name is missing.\n");
}
else {
read_data(argv[1]);
}
while (1) {
printf("What do you want to do?\n");
printf(" [1] Add a name to the list.\n");
printf(" [2] Remove a name from the list.\n");
printf(" [3] Show the list of names.\n");
printf(" [4] Quit the program.\n\n");
scanf("%d", &input);
switch (input) {
case 1:
printf("What is the guest's name? ");
scanf("%s", name);
printf("\nHow many people are in the party? ");
scanf("%d", &size);
insert(name, size);
break;
case 2:
delete();
break;
case 3:
list();
break;
default:
save_data(argv[1]);
return 0;
}
}
}
void insert (char *name, int size) {
INFO_NODE *temp;
INFO_NODE *p;
int i;
int j;
for (i = 0; i < 4; i++) {
temp = heads[i];
while (temp != NULL) {
if (strcmp(name, temp->table_name) == 0) {
printf("The name is already on the waiting list!\n\n");
return;
}
tails[i] = temp;
temp = temp->next;
}
}
p = (INFO_NODE *)malloc(sizeof(INFO_NODE));
if (p == NULL) {
printf("Could not allocate memory.\n");
return;
}
p->table_size = size;
strcpy(p->table_name, name);
p->next = NULL;
switch (size) {
case 1:
case 2:
j = 0;
break;
case 3:
case 4:
j = 1;
break;
case 5:
case 6:
j = 2;
break;
default:
j = 3;
break;
}
if (heads[j] == NULL) {
heads[j] = p;
tails[j] = p;
printf("\n%s has been added to the waiting list.\n\n", p->table_name);
return;
}
else {
tails[j]->next = p;
}
tails[i] = p;
return;
}
void delete() {
INFO_NODE *p;
INFO_NODE *q;
int open_table = 0;
int i;
printf("What is the size of the next available table? ");
scanf("%d", &open_table);
switch (open_table) {
case 1:
case 2:
i = 0;
break;
case 3:
case 4:
i = 1;
break;
case 5:
case 6:
i = 2;
break;
default:
i = 3;
break;
}
for (i = i; i >= 0; i--) {
if (heads[i] == NULL) {
printf("\nThere are no reservations to cancel.\n");
}
else {
q = heads[i];
p = q->next;
if (q -> table_size <= open_table) {
printf("\n%s's table has been cleared.\n", q->table_name);
heads[i] = heads[i]->next;
free(q);
return;
}
while (p != NULL) {
if (p->table_size <= open_table) {
printf("\n%s's table has been cleared.\n", p->table_name);
q->next = p->next;
free(p);
return;
}
p = p->next;
q = q->next;
}
}
}
printf("\nThere are no tables to accomodate that size right now.\n");
}
void list() {
INFO_NODE *p;
int i;
for (i = 0; i < 4; i++) {
p = heads[i];
while (p != NULL) {
printf("\n%s\t%d\n", p->table_name, p->table_size);
p = p->next;
}
}
return;
}
void read_data (char *file_name) {
FILE *fp;
char name[20];
int size;
fp = fopen(file_name, "r");
if (fp == NULL) {
printf("Can't open file %s", name);
return;
}
fseek(fp, 50, SEEK_SET);
while (fscanf(fp, "%s %d", name, &size) == 2) {
printf("Reading file.\n");
insert(name, size);
}
fclose(fp);
return;
}
void save_data (char *file_name) {
FILE *fp;
INFO_NODE *p;
INFO_NODE *q;
int i;
fp = fopen(file_name, "w");
if (fp == NULL) {
printf("Can't open file.\n");
return;
}
fprintf(fp, "Name:\t\tGroup Size:\t\n------------------------------\n");
for (i = 0; i < 4; i++) {
p = heads[i];
q = p;
while (p != NULL) {
fprintf(fp, "%s %d\n", p->table_name, p->table_size);
p = p->next;
free(q);
}
}
fclose(fp);
return;
}
|
C
|
int32_t
intcmp(const void *a, const void *b,size_t x UNUSED)
{
if ((*(const int *) a) < (*(const int *) b)) {
return -1;
} else if ((*(const int *) a) > (*(const int *) b)) {
return 1;
} else {
return 0;
}
}
void
print_int(const void *a)
{
printf("%d ", (*(const int *) a));
}
void *
ckalloc(size_t size)
{
void *ptr;
do {
ptr = malloc(size);
}
while (!ptr);
return ptr;
}
void
ckfree(void *ptr)
{
free(ptr);
}
|
C
|
//
// main.c
// SumReductionOpenCL
//
// Created by Ruben Vasconcelos on 4/5/17.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/cl.h>
#endif
const char *ProgramSource =
"kernel void add(global int* input,\n"\
" const int group_size,\n"\
" const int data_size,\n"\
" global int* result) {\n"\
"\n"\
" int index = get_global_id(0) * group_size;\n"\
" int sum = 0;\n"\
" int limit = (get_global_id(0) + 1) * group_size;\n"\
" if(get_global_id(0) == get_num_groups(0)-1){\n"\
" limit = data_size;\n"\
" }\n"\
"\n"\
" while (index < limit) {\n"\
" sum += input[index];\n"\
" index++;\n"\
" }\n"\
" result[get_group_id(0)] = sum;\n"\
"}\n";
int
main(void) {
cl_context context;
cl_context_properties properties[3];
cl_kernel kernel;
cl_command_queue command_queue;
cl_program program;
cl_int err;
cl_uint num_of_platforms=0;
cl_platform_id platform_id;
cl_device_id device_id;
cl_device_id all_device_id[2];
cl_uint num_of_devices=0;
cl_mem input, output;
size_t numItems = 2000000;
size_t itemsPerBlock = 250;
int inputData[numItems];
int result[numItems/itemsPerBlock];
struct timeval start, end;
FILE *myFile;
myFile = fopen("input_nums", "r");
//read file into array
int i;
if (myFile == NULL) {
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < numItems; i++) {
fscanf(myFile, "%d,", &inputData[i] );
}
fclose(myFile);
gettimeofday(&start , NULL);
/*retreive a list of platforms available*/
if(clGetPlatformIDs(1, &platform_id, &num_of_platforms) != CL_SUCCESS) {
printf("Unable to get platform id\n");
return 1;
}
/*try to get a supported GPU device*/
if(clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 2, all_device_id, &num_of_devices) != CL_SUCCESS) {
printf("Unable to get device id\n");
return 1;
}
device_id = all_device_id[1];
/*context properties list − must be terminated with 0*/
properties[0] = CL_CONTEXT_PLATFORM;
properties[1] = (cl_context_properties) platform_id;
properties[2] = 0;
/*create a context with the GPU device*/
context = clCreateContext(properties, 1, &device_id, NULL, NULL, &err);
/*create command queue using the context and device*/
command_queue = clCreateCommandQueue(context, device_id, 0, &err);
/*create a program from the kernel source code*/
program=clCreateProgramWithSource(context, 1, (const char**) &ProgramSource, NULL, &err);
/*compile the program*/
if(clBuildProgram(program, 0, NULL, NULL, NULL, NULL) != CL_SUCCESS) {
printf("Error building program\n");
return 1;
}
/*specify which kernel from the program to execute*/
kernel=clCreateKernel(program, "add", &err);
/*create buffers for the input and ouput*/
input = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(int) * numItems, NULL, NULL);
output = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(int) * numItems, NULL, NULL);
/*load data into the input buffer*/
clEnqueueWriteBuffer(command_queue, input, CL_TRUE, 0, sizeof(int) * numItems, inputData, 0, NULL, NULL);
/*set the argument list for the kernel command*/
clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&input);
clSetKernelArg(kernel, 1, sizeof(int),&itemsPerBlock);
clSetKernelArg(kernel, 2, sizeof(int),&numItems);
clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *)&output);
/*enqueue the kernel command for execution*/
gettimeofday(&end , NULL);
printf("prep work - %lu seconds and %d microseconds \n",(end.tv_sec - start.tv_sec),(end.tv_usec - start.tv_usec));
gettimeofday(&start , NULL);
size_t commands = (numItems/itemsPerBlock);
size_t oneWorkItem = 1;
clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &commands, &oneWorkItem, 0, NULL, NULL);
clFinish(command_queue);
/*copy the results from the output buffer*/
clEnqueueReadBuffer(command_queue, output, CL_TRUE, 0, sizeof(int)* (numItems/itemsPerBlock), result, 0, NULL, NULL);
int sum = result[0];
for (i = 1; i < (numItems/itemsPerBlock); i++) {
sum += result[i];
}
gettimeofday(&end , NULL);
printf("sum reduction - %lu seconds and %d microseconds \n",(end.tv_sec - start.tv_sec),(end.tv_usec - start.tv_usec));
printf("output: %d\n", sum);
/*cleanup − release OpenCL resources*/
clReleaseMemObject(input);
clReleaseMemObject(output);
clReleaseProgram(program);
clReleaseKernel(kernel);
clReleaseCommandQueue(command_queue);
clReleaseContext(context);
return(0);
}
|
C
|
#include "param.h"
#include "coeur.h"
#include <arduino.h>
void lancement(){
if (analogRead(0) >= SENSIBILITE) { /* SENSIBILITE CONSEILLEE >950 afin de supprimer les interférences de la carte
et obtenir une meilleure temporisation (elle démarre à 480 lors du lancement)*/
switch (MODE) { //Selection du mode d'affichage défini dans param.h
case 1 : /*Cas allumage en flash de toutes les LEDs, configurer une SENSIBILITE à une valeur supérieure à 950
pour pouvoir afficher les battements d'un coeur plus rapide*/
FullOn(); //Allumage complet
delay(1); //Delay afin de pouvoir laisser les LEDs s'allumer
FullOff(); //Extinction complète
break; //-----------------------------------------------------------------------------------------------------------
case 2 : //Cas d'allumage des LEDs en mode chenille
if (analogRead(0) >= SENSIBILITE + 25) {
chenille(&compteur);
delay(1000);
compteur++;
}
break; //-----------------------------------------------------------------------------------------------------------
case 3 : //Cas d'allumage des LEDs en mode chenille, allumage d'une LED sur deux
if (analogRead(0) >= SENSIBILITE + 25) {
chenille1sur2(&compteur);
delay(1000); //Attente afin de faire redescendre la valeur du PIN d'entrée
compteur++; //Incrémentation du compteur servant à passer à l'étape d'après pour le prochain appel de la fonction
}
break; //-----------------------------------------------------------------------------------------------------------
case 4 : //Cas d'affichage en LEDmètre (affichage en mode pile informatique)
if (analogRead(0) >= SENSIBILITE + 25) {
LEDmetre(&compteur);
delay(1000); //Attente afin de faire redescendre la valeur du PIN d'entrée
compteur++; //Incrémentation du compteur servant à passer à l'étape d'après pour le prochain appel de la fonction
}
break; //-----------------------------------------------------------------------------------------------------------
case 5 : //Cas d'allumage d'une seule LED, au choix
choixLED();
break; //-----------------------------------------------------------------------------------------------------------
case 6 : //Cas d'allumage d'une LED en sautant un nombre déterminé d'autres LEDs
On1SurNb(); //Allumage de 1 LED sur un nombre déterminé
delay(1); //Attente afin de laisser les LEDs s'allumer
Off1SurNb(); //Extinction de 1 LED sur un nombre déterminé
break;
default :
break;
} //Fin du switch
} //Fin du if de vérification d'un poul
}
void FullOn(){ //Fonction allumant toutes les LEDs
int j;
for(j=LED1;j<=LED10;j++){
digitalWrite(j,HIGH);
}
}
void FullOff(){ //Fonction éteignant toutes les LEDs
int j;
for(j=LED1;j<=LED10;j++){
digitalWrite(j,LOW);
}
}
void On1SurNb(){ //Fonction allumant 1 LED sur UNSURNB (définie dans param.h)
int j;
for(j=LED1;j<=LED10;j+=UNSURNB){
digitalWrite(j,HIGH);
}
}
void Off1SurNb(){ //Fonction éteignant 1 LED sur UNSURNB (définie dans param.h)
int j;
for(j=LED1;j<=LED10;j+=UNSURNB){
digitalWrite(j,LOW);
}
}
void chenille(int *compteur){ //Fonction faisant une chenille d'allumage de LEDs
switch(*compteur){
case 1 :
digitalWrite(LED1, HIGH); //Allumage LED1
break;
case 2 :
digitalWrite(LED2, HIGH); //Allumage LED2
break;
case 3 :
digitalWrite(LED3, HIGH); //Allumage LED3
break;
case 4 :
digitalWrite(LED4, HIGH); //Allumage LED4
break;
case 5 :
digitalWrite(LED5, HIGH); //Allumage LED5
break;
case 6 :
digitalWrite(LED6, HIGH); //Allumage LED6
break;
case 7 :
digitalWrite(LED7, HIGH); //Allumage LED7
break;
case 8 :
digitalWrite(LED8, HIGH); //Allumage LED8
break;
case 9 :
digitalWrite(LED9, HIGH); //Allumage LED9
break;
case 10 :
digitalWrite(LED10, HIGH); //Allumage LED10
break;
case 11 :
digitalWrite(LED1, LOW); //Extinction LED1
break;
case 12 :
digitalWrite(LED2, LOW); //Extinction LED2
break;
case 13 :
digitalWrite(LED3, LOW); //Extinction LED3
break;
case 14 :
digitalWrite(LED4, LOW); //Extinction LED4
break;
case 15 :
digitalWrite(LED5, LOW); //Extinction LED5
break;
case 16 :
digitalWrite(LED6, LOW); //Extinction LED6
break;
case 17 :
digitalWrite(LED7, LOW); //Extinction LED7
break;
case 18 :
digitalWrite(LED8, LOW); //Extinction LED8
break;
case 19 :
digitalWrite(LED9, LOW); //Extinction LED9
break;
case 20 :
digitalWrite(LED10, LOW); //Extinction LED10
*compteur = 0;
break;
default :
break;
}
} //Fin de la fonction chenille
void chenille1sur2(int *compteur){ //Fonction faisant une chenille de LEDs en allumant 1 LED/2
switch(*compteur){
case 1 : //Début de l'allumage des LEDs
digitalWrite(LED1, HIGH); //Allumage LED1
break;
case 2 :
digitalWrite(LED3, HIGH); //Allumage LED3
break;
case 3 :
digitalWrite(LED5, HIGH); //Allumage LED5
break;
case 4 :
digitalWrite(LED7, HIGH); //Allumage LED7
break;
case 5 :
digitalWrite(LED9, HIGH); //Allumage LED9
break;
case 6 :
digitalWrite(LED2, HIGH); //Allumage LED2
break;
case 7 :
digitalWrite(LED4, HIGH); //Allumage LED4
break;
case 8 :
digitalWrite(LED6, HIGH); //Allumage LED6
break;
case 9 :
digitalWrite(LED8, HIGH); //Allumage LED8
break;
case 10 :
digitalWrite(LED10, HIGH); //Alumage LED10
break; //Fin d'allumage des LEDs
case 11 : //Début de l'extinction des LEDs
digitalWrite(LED1, LOW); //Extinction LED1
break;
case 12 :
digitalWrite(LED3, LOW); //Extinction LED3
break;
case 13 :
digitalWrite(LED5, LOW); //Extinction LED5
break;
case 14 :
digitalWrite(LED7, LOW); //Extinction LED7
break;
case 15 :
digitalWrite(LED9, LOW); //Extinction LED9
break;
case 16 :
digitalWrite(LED2, LOW); //Extinction LED2
break;
case 17 :
digitalWrite(LED4, LOW); //Extinction LED4
break;
case 18 :
digitalWrite(LED6, LOW); //Extinction LED6
break;
case 19 :
digitalWrite(LED8, LOW); //Extinction LED8
break;
case 20 :
digitalWrite(LED10, LOW); //Extinction LED10
*compteur = 0; //Remise à zéro du compteur allumant les LEDs
break; //Fin d'extinction des LEDs
default :
break;
}
} //Fin fonction chenille de LED 1/2
void LEDmetre(int *compteur){ //Fonction allumant les LEDs sur un modèle de pile informatique
switch(*compteur){
case 1 : //Début de l'allumage des LEDs
digitalWrite(LED1, HIGH); //Allumage LED1
break;
case 2 :
digitalWrite(LED2, HIGH); //Allumage LED2
break;
case 3 :
digitalWrite(LED3, HIGH); //Allumage LED3
break;
case 4 :
digitalWrite(LED4, HIGH); //Allumage LED4
break;
case 5 :
digitalWrite(LED5, HIGH); //Allumage LED5
break;
case 6 :
digitalWrite(LED6, HIGH); //Allumage LED6
break;
case 7 :
digitalWrite(LED7, HIGH); //Allumage LED7
break;
case 8 :
digitalWrite(LED8, HIGH); //Allumage LED8
break;
case 9 :
digitalWrite(LED9, HIGH); //Allumage LED9
break;
case 10 :
digitalWrite(LED10, HIGH); //LED10
break; //Fin d'allumage des LEDs
case 11 : //Début de l'extinction des LEDs
digitalWrite(LED10, LOW); //Extinction LED10
break;
case 12 :
digitalWrite(LED9, LOW); //Extinction LED9
break;
case 13 :
digitalWrite(LED8, LOW); //Extinction LED8
break;
case 14 :
digitalWrite(LED7, LOW); //Extinction LED7
break;
case 15 :
digitalWrite(LED6, LOW); //Extinction LED6
break;
case 16 :
digitalWrite(LED5, LOW); //Extinction LED5
break;
case 17 :
digitalWrite(LED4, LOW); //Extinction LED4
break;
case 18 :
digitalWrite(LED3, LOW); //Extinction LED3
break;
case 19 :
digitalWrite(LED2, LOW); //Extinction LED2
break;
case 20 :
digitalWrite(LED1, LOW); //Extinction LED1
*compteur = 0; //Remise à zéro du compteur allumant les LEDs
break; //Fin extinction des LEDs
case 21:
break;
default :
break;
}
} //Fin fonction LEDmètre
void choixLED(){ //Fonction permettant de choisir une LED à allumer
switch(LED){
case 1 : //Allumage LED1
digitalWrite(LED1, HIGH);
delay(1);
digitalWrite(LED1, LOW); //Extinction LED1
break;
case 2 :
digitalWrite(LED2, HIGH);
delay(1); //LED2
digitalWrite(LED2, LOW);
break;
case 3 :
digitalWrite(LED3, HIGH);
delay(1); //LED3
digitalWrite(LED3, LOW);
break;
case 4 :
digitalWrite(LED4, HIGH);
delay(1); //LED4
digitalWrite(LED4, LOW);
break;
case 5 :
digitalWrite(LED5, HIGH);
delay(1); //LED5
digitalWrite(LED5, LOW);
break;
case 6 :
digitalWrite(LED6, HIGH);
delay(1); //LED6
digitalWrite(LED6, LOW);
break;
case 7 :
digitalWrite(LED7, HIGH);
delay(1); //LED7
digitalWrite(LED7, LOW);
break;
case 8 :
digitalWrite(LED8, HIGH);
delay(1); //LED8
digitalWrite(LED8, LOW);
break;
case 9 :
digitalWrite(LED9, HIGH);
delay(1); //LED9
digitalWrite(LED9, LOW);
break;
case 10 :
digitalWrite(LED10, HIGH);
delay(1); //LED10
digitalWrite(LED10, LOW);
break;
default :
FullOn();
delay(1); //Clignotement x1 de toutes les LEDs montrant une erreur
FullOff();
break;
}
} //Fin fonction choix de la LED
|
C
|
/*memcpy将字符串2中的n个字符拷贝到字符串1中,并返回字符串2*/
void *memcpy(void *dest, const void *src, int count)
{
assert((dest != NULL) && (src != NULL));
void *address = dest;
while(count--) {
*(char *)dest = *(char *)src;
dest = (char *)dest + 1;
src = (char *)src + 1;
}
return address;
}
/* 由src所指内存区域复制不多于count个字节到dest所指内存区域,如果遇到字符c则停止复制,
* 返回值:如果c没有被复制,则返回NULL,否则,返回字符c 后面紧挨一个字符位置的指针。
*/
void *memccpy(void *dest, const void *src, int c, unsigned int count)
{
assert((dest != NULL) && (src != NULL));
while(count--) {
*(char *)dest = *(char *)src;
if(*(char *)src == (char)c)
return ((char *)dest + 1);
dest = (char *)dest + 1;
src = (char *)src + 1;
}
return NULL;
}
|
C
|
#include "queue.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void push(char data[MSG_SIZE], Block **head, Block **tail)
{
/* push a block into the top of queue
* data: the messange of the block, max size depends on MSG_SIZE
* head: pointer, points to the head of queue
* tail: pointer, points to the tail of queue */
Block *nblock = malloc(sizeof(Block)); /* allocate new block */
strncpy(nblock->msg, data, MSG_SIZE); /* copy data to new block */
nblock->ptr = NULL; /* the last block of queue, points to "nothing". */
/* test boundary condition */
if( (*tail) == NULL )
{
/* empty queue */
(*head) = nblock;
(*tail) = nblock;
}
else
{
/* normal condition */
(*tail)->ptr = nblock; /* let the previous block points to the new block */
(*tail) = (*tail)->ptr; /* update tail */
}
}
void pop(Block **head, Block **tail)
{
/* pop out a block from the tail of queue
* head: pointer, points to the head of queue
* tail: pointer, points to the tail of queue */
/* test boudary condition, whether the queue is empty */
if( (*head) == NULL )
{
/* empty queue, raise error */
printf("ERROR: empty queue\n");
}
else
{
/* normal condition */
Block *temp = (*head);
(*head) = (*head)->ptr;
printf("The poped block messange is: %s\n", temp->msg);
free(temp);
}
}
void print_queue(Block **head)
{
/* print the whole queue */
if((*head) == NULL)
{
/* queue empty, exit. */
printf("The queue is empty.\n");
return ;
}
else
{
/* not empty, iteratively print it */
printf("The queue: \n");
for(Block *i=(*head); i!=NULL; i = i->ptr)
{
printf("%s", i->msg);
if(i->ptr != NULL)
{
printf(" -> ");
}
else
{
printf("\n");
}
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// CONSTANTS DECLARATIONS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#define TRUE 1
#define FALSE 0
#define SHOWLOG 1
#define DEFAULT_OFFSET 1078
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// STRUCTS DECLARATIONS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typedef struct {
unsigned char r;
unsigned char g;
unsigned char b;
} pixel;
typedef struct {
unsigned short padding;
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BITMAPFILEHEADER;
typedef struct {
unsigned int biSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
unsigned int biXPelsPerMeter;
unsigned int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
} BITMAPINFOHEADER;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTION OPERATIONS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
Reads in the Bmpmap image and gathers information from the header
Gets the width and height of the image which is used to calculate
all of the bits that will be passed into the array of images
*/
int readFile (char fileName[], int *rows, int *cols, pixel **image);
int readHeader(int fd, int *rows, int *cols, unsigned int *start);
int readBits (int fd, pixel *image, int rows, int cols, unsigned int start);
/*
Outputs the Bmpmap image and writes all the necessary information to the
file first by creating the header and then using the rows and cols to
generate the binary that should be put into the file
*/
int writeFile (char fileName[], int rows, int cols, pixel *image);
int writeHeader(int fd, unsigned int rows, unsigned int cols, unsigned int start);
int writeBits(int fd, int rows, int cols, pixel *image, unsigned int start);
/*
Operates on the file
*/
int flipImage (pixel *original, pixel **newImage, int rows, int cols);
int rotate (pixel *original, pixel **newImage, int rotation, int rows, int cols);
int enlarge(pixel *original, int rows, int cols, int scale, pixel **newImage, int *newRows, int *newcols);
// Determines which operations to run
void determineFunctions(int scale, int degree, int flip,char *outputFile,char *inputFile);
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* wall.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmartins <lmartins@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/07 04:39:43 by lmartins #+# #+# */
/* Updated: 2021/08/07 07:19:13 by lmartins ### ########.fr */
/* */
/* ************************************************************************** */
#include "cub3d.h"
int get_color(t_img *img, int x, int y)
{
char *color;
color = img->addr + (y * img->line_length + x * (img->bits_per_pixel / 8));
return (*(unsigned int *)(color));
}
void wall_limits(t_parameters *info, double wall_height, int column_id)
{
int pixel[2];
int i;
pixel[TOP] = (info->height / 2) - (wall_height / 2);
pixel[BOTTOM] = (info->height / 2) + (wall_height / 2);
i = 0;
while (i <= pixel[TOP] && i >= 0 && i <= info->height)
{
ft_pixel_put(info->img, column_id, i, info->ceil_color);
i++;
}
while (i <= pixel[BOTTOM] && i >= 0 && i <= info->height)
{
ft_pixel_put(info->img, column_id, i,
get_texture(info, i, info->ray[column_id], pixel));
i++;
}
while (i <= info->height)
{
ft_pixel_put(info->img, column_id, i, info->floor_color);
i++;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void main() {
int v[5],i;
for(i=0;i<5;i++){
printf("introduzca valor\n");
scanf("%d",&v[i]);
};
printf("La cadena es:");
for(i=0;i<5;i++){
printf("%d ",v[i]);
};
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
int pangkat(int a, int b){
if(b == 1)
{
return a;
}
else
{
return a*pangkat(a,(b-1));
}
}
int main()
{
int a,b;
int i=0;
int hasil=1;
printf("===...Hallo...=== \n\n");
printf("\n");
Sleep(2000);
printf("\n");
printf("Loading");
Sleep(1000);
printf(".");
Sleep(1000);
printf(".");
Sleep(1000);
printf(".");
Sleep(1000);
printf(".");
printf("\n");
printf("========================== \n");
printf("Masukkan Angka : ");
scanf("%d",&a);
printf("========================== \n");
printf("Dipangkatkan : ");
scanf("%d",&b);
printf("========================== \n");
printf("\n");
printf("Loading");
Sleep(1000);
printf(". \n");
printf("\n");
printf("Hasil Rekursifnya Adalah %d\n\n",pangkat(a,b));
for(i=0;i<b;i++)
{
hasil=hasil*a;
}
printf("Hasil dari iterasi biasa adalah %d\n",hasil);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int occ[26];
void clear_occ() {
for(int i = 0; i < 26; i++) {
occ[i] = 0;
}
}
int main() {
size_t size=32;
char* line = (char*)malloc(size*sizeof(char));
int t = 0;
while(!feof(stdin)) {
int len = getline(&line,&size,stdin);
/* printf("%d\n",len); */
for(int i = 0; i < len-1; i++) {
t+=(occ[line[i]-'a']++==0);
}
if(len == 1) {
/* t=0; */
clear_occ();
}
}
printf("%d\n",t);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define PRECHECK 0xAEAEAEAEAEAEAEAEL
#define POSTCHECK 0xEAEAEAEAEAEAEAEAL
// +------------------------------------------+
// + Pointer to next memory block +
// +------------------------------------------+
// + Size of User Data, in bytes +
// +------------------------------------------+
// + PRECHECK sentinel +
// +------------------------------------------+
// + +
// + +
// + User Data +
// + +
// + +
// +------------------------------------------+
// + POSTCHECK sentinel +
// +------------------------------------------+
unsigned long *firstMemoryBlock = NULL;
typedef struct node{
long data;
struct *next;
}node_t;
// Grab some memory
void *getMem(int numBytes) {
// TODO: Implement
node_t node=NULL;
void* pVoid = malloc(3*node+numBytes);
node->next = pVoid;
long* pdata = pVoid+sizeof(node);
*pData= numBytes;
printf("%d\n", *pData);
}
// Check one memory block for integrity
void checkMem(unsigned long *longPtr) {
// TODO: Implement
}
// Free memory allocated by getMem
void freeMem(void *userPtr) {
// TODO: Implement
}
// Check all the un-freed memory
void finalMemoryCheck() {
// TODO: Implement
}
int main(int argc, char *argv[]) {
char *userPtr;
printf("===== Test 1\n");
userPtr = getMem(1);
userPtr[0] = 'x';
userPtr[1] = 'y';
printf("===== Test 2\n");
userPtr = getMem(100);
userPtr[-30] = 'a';
userPtr[230] = 'b';
printf("===== Test 3\n");
userPtr = getMem(10);
userPtr[0] = 'x';
userPtr[9] = 'y';
freeMem(userPtr);
printf("===== Test 4\n");
userPtr = getMem(1000);
userPtr[-1] = 'a';
userPtr[1000] = 'b';
finalMemoryCheck();
return 0;
}
|
C
|
#ifndef __lc_util_h__
#define __lc_util_h__
#include <glib.h>
#include <lc/lc.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* lc_singleton_get:
*
* Retrieves a singleton instance of lc_t. The instance will already be
* initialized to defaults and attached to the glib event loop. If the
* instance could not be created or initialized, then NULL is returned.
*/
lc_t * lcu_singleton_get ();
/**
* lc_singleton_release:
*
* Releases the singleton LC and decrements its reference count. If there are
* no more references to the singleton LC (lc_singleton_get increments the
* reference count), then it is destroyed.
*/
void lcu_singleton_release (lc_t *lc);
/**
* lcu_mainloop_attach_lc (lc_t *lc)
* attaches/detaches LC to/from the glib mainloop
* When attached, lc_handle() is invoked "automatically" when a message is
* received over LC.
*
* only one instance of lc_t can be attached per process
*
* returns 0 on success, -1 on failure
*/
int lcu_glib_mainloop_attach_lc (lc_t *lc);
int lcu_glib_mainloop_detach_lc (lc_t *lc);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
/*
Ryan Lebeau
22/01/2018
AssignOnePartTwo.c
COMP 3300
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/wait.h>
int* bubbleSort(int[],int);
int persistance(int, int);
int* largest(int[]);
int* smallest(int[]);
int main(int argc, char* argv[]){
//time of program launch
double time_spent = 0;
clock_t begin = clock();
//if no parameter given
if(argc==1){
printf("You need to enter in a text file name");
return 0;
}
//scanning in all numbers from text file
int n=125;
int nums[n];
FILE *txtPtr = fopen(argv[1], "r");
for(int i=0;i<n;i++){
fscanf(txtPtr, "%d", &nums[i]);
}
//sorted array
int *sortNums = bubbleSort(nums, n);
//seperating array into 5 parts
int one[25],two[25],three[25],four[25],five[25];
memcpy(one, sortNums, 25*sizeof(int));
memcpy(two, &sortNums[25], 25*sizeof(int));
memcpy(three, &sortNums[50], 25*sizeof(int));
memcpy(four, &sortNums[75], 25*sizeof(int));
memcpy(five, &sortNums[100], 25*sizeof(int));
int status;
int pids[5];
//make 5 children
for(int i=0;i<5;i++){
if((pids[i]=fork()) == 0){
//inside child process
printf("I am kid#:%d and my id is %d\n", i+1, getpid());
//using the correct fifth of the sorted array per child
int persis[25];
switch(i){
case 0:
//finding persistance of each number
for(int i=0;i<25;i++){
persis[i]=persistance(one[i],0);
printf("%d persistance %d\n", one[i], persis[i]);
}
//storing position and value of smallest/largest persistance
int* smallStuff = smallest(persis), *largeStuff = largest(persis);
//printing out each number based off of position and its persistance
printf("\n%d has the smallest persistance %d\n%d has the largest persistance %d\n", one[smallStuff[1]], smallStuff[0], one[largeStuff[1]], largeStuff[0]);
break;
case 1:
for(int i=0;i<25;i++){
persis[i]=persistance(two[i],0);
printf("%d persistance %d\n", two[i], persis[i]);
}
int* smallStuff2 = smallest(persis), *largeStuff2 = largest(persis);
printf("\n%d has the smallest persistance %d\n%d has the largest persistance %d\n", two[smallStuff2[1]], smallStuff2[0], two[largeStuff2[1]], largeStuff2[0]);
break;
case 2:
for(int i=0;i<25;i++){
persis[i]=persistance(three[i],0);
printf("%d persistance %d\n", three[i], persis[i]);
}
int* smallStuff3 = smallest(persis), *largeStuff3 = largest(persis);
printf("\n%d has the smallest persistance %d\n%d has the largest persistance %d\n", three[smallStuff3[1]], smallStuff3[0], three[largeStuff3[1]], largeStuff3[0]);
break;
case 3:
for(int i=0;i<25;i++){
persis[i]=persistance(four[i],0);
printf("%d persistance %d\n", four[i], persis[i]);
}
int* smallStuff4 = smallest(persis), *largeStuff4 = largest(persis);
printf("\n%d has the smallest persistance %d\n%d has the largest persistance %d\n", four[smallStuff4[1]], smallStuff4[0], four[largeStuff4[1]], largeStuff4[0]);
break;
case 4:
for(int i=0;i<25;i++){
persis[i]=persistance(five[i],0);
printf("%d persistance %d\n", five[i], persis[i]);
}
int* smallStuff5 = smallest(persis), *largeStuff5 = largest(persis);
printf("\n%d has the smallest persistance %d\n%d has the largest persistance %d\n", five[smallStuff5[1]], smallStuff5[0], five[largeStuff5[1]], largeStuff5[0]);
break;
}
exit(1);
}
//inside parent
if (wait(&status) >= 0){
if (WIFEXITED(status)){
//which child exited with what code, they force exit with code 0
printf("From the main: child, id %d ended with status %d\n-----\n", pids[i], WEXITSTATUS(status));
}
}
}
//calculating final CPU usage time
clock_t end = clock();
time_spent += (double)(end - begin)/CLOCKS_PER_SEC;
printf("Time elpased is %f seconds\n", time_spent);
printf("Goodbye!");
return 0;
}
//sorting from smallest to largest
int* bubbleSort(int nums[], int n){
int temp;
//simple bubblesort loops
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i-1;j++){
if(nums[j]>nums[j+1]){
temp=nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
}
}
}
return nums;
}
//recursive function which finally returns persistance once number reaches one digit
int persistance(int num, int count){
int newNum=1, digit=0, len;
char numS[9], digitC;
//convert number to string
sprintf(numS, "%d", num);
len=strlen(numS);
//if length of string is one (down to one digit)
if(len==1)
return count;
//access each char of string(digit) and mutliply to newNum
for(int i=0;i<len;i++){
digit=numS[i] - '0';
newNum*=digit;
}
//recursion until newNum is only one digit, then return persistance
return persistance(newNum, count+1);
}
//takes in the array of persistances and returns the largest one and its position
int* largest(int persist[]){
int position, large=persist[0];
//setting memory for array so it can be returned
int *stuff = malloc(2 * sizeof(int));
//find largest persistance
for(int i=0;i<25;i++){
if(persist[i]>large){
large=persist[i];
position=i;
}
}
//add both position and persistance to stuff array
stuff[0]=large;stuff[1]=position;
return stuff;
}
//takes in the array of persistances and returns the smallest one and its position
int* smallest(int persist[]){
int position, small=persist[0];
//setting memory for array so it can be returned
int *stuff = malloc(2 * sizeof(int));
//find smallest persistance
for(int i=0;i<25;i++){
if(persist[i]<small){
small=persist[i];
position=i;
}
}
//add both position and persistance to stuff array
stuff[0]=small;stuff[1]=position;
return stuff;
}
|
C
|
/*
* 中断头文件
*
* 中断相关,类型定义,函数声明
*
* author:// 绝大部分代码来自 《操作系统真相还原》
*/
#ifndef __INTERRUPT_H
#define __INTERRUPT_H
#include "std_type_define.h"
#define PIC_M_CTRL 0x20 //这里用的可编程中断控制器是8259A,主片的控制端口是0x20
#define PIC_M_DATA 0x21 //主片的数据端口是0x21
#define PIC_S_CTRL 0xa0 //从片的控制端口是0xa0
#define PIC_S_DATA 0xa1 //从片的数据端口是0xa1
#define IDT_DESC_CNT 0x21 //目前总共支持的中断数
#define EFLAGS_IF 0x00000200 // eflags寄存器中的if位为1
#define GET_EFLAGS(EFLAG_VAR) asm volatile("pushfl; popl %0" : "=g" (EFLAG_VAR)) //flag读取寄存器
/*中断门描述符结构体*/
struct gate_desc {
uint16_t func_offset_low_word;
uint16_t selector;
uint8_t dcount; //此项为双字计数字段,是门描述符中的第4字节。此项固定值,不用考虑
uint8_t attribute;
uint16_t func_offset_high_word;
};
/* 定义中断的两种状态:
* INTR_OFF值为0,表示关中断,
* INTR_ON值为1,表示开中断 */
enum intr_status { // 中断状态
INTR_OFF, // 中断关闭
INTR_ON // 中断打开
};
//w函数指针,中断处理函数
typedef void* intr_handler;
void idt_init(void); //中断初始化
// 注册中断处理函数
void register_handler(uint8_t vector_no, intr_handler function);
enum intr_status intr_set_status(enum intr_status status);
enum intr_status intr_get_status();
enum intr_status intr_enable();
enum intr_status intr_disable();
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct context {
char *namelist[10];
int val;
};
int
main(void) {
struct context *ctx = calloc(1, sizeof(*ctx));
int i;
for (i = 0; i < 10; i++) {
printf("%d: %p\n", i, ctx->namelist[i]);
}
printf("val %d\n", ctx->val);
return 0;
}
|
C
|
#include "libtexproma_private.h"
void tpm_repeat(tpm_mono_buf dst, tpm_mono_buf src, unsigned nx, unsigned ny) {
for (int y = 0; y < TP_HEIGHT; y++)
for (int x = 0; x < TP_WIDTH; x++)
tpm_put_pixel(dst, x, y, tpm_get_pixel(src, x * nx, y * ny));
}
void tpm_flip(tpm_mono_buf dst, tpm_mono_buf src) {
for (int y = 0; y < TP_HEIGHT; y++)
for (int x = 0; x < TP_WIDTH; x++)
tpm_put_pixel(dst, (TP_WIDTH - 1) - x, y, tpm_get_pixel(src, x, y));
}
void tpm_rotate(tpm_mono_buf dst, tpm_mono_buf src) {
for (int y = 0; y < TP_HEIGHT; y++)
for (int x = 0; x < TP_WIDTH; x++)
tpm_put_pixel(dst, y, x, tpm_get_pixel(src, x, y));
}
void tpm_twist(tpm_mono_buf dst, tpm_mono_buf src, float strength) {
float s = constrain(strength, -1.0f, 1.0f) * 2.0f * M_PI / TP_WIDTH;
for (int y = 0; y < TP_HEIGHT; y++) {
for (int x = 0; x < TP_WIDTH; x++) {
float xp = (float)(x - 128);
float yp = (float)(y - 128);
float r = sqrtf(xp * xp + yp * yp);
int c;
if (r <= 128.0f) {
float ang = atan2(xp, yp) + (s * (128.0f - r));
xp = sinf(ang) * r + 128.0f;
yp = cosf(ang) * r + 128.0f;
c = tpm_get_filtered_pixel(src, xp, yp);
} else {
c = tpm_get_pixel(src, x, y);
}
tpm_put_pixel(dst, x, y, c);
}
}
}
void tpm_move(tpm_mono_buf dst, tpm_mono_buf src, float move_x, float move_y) {
int xo = constrain(move_x, -1.0f, 1.0f) * TP_WIDTH;
int yo = constrain(move_y, -1.0f, 1.0f) * TP_HEIGHT;
for (int y = 0; y < TP_HEIGHT; y++)
for (int x = 0; x < TP_WIDTH; x++)
tpm_put_pixel(dst, x, y, tpm_get_pixel(src, x + xo, y + yo));
}
void tpm_distort(tpm_mono_buf dst, tpm_mono_buf src,
tpm_mono_buf umap, tpm_mono_buf vmap,
float ustrength, float vstrength)
{
for (int y = 0; y < TP_HEIGHT; y++) {
for (int x = 0; x < TP_WIDTH; x++) {
float fu = (float)tpm_get_pixel(umap, x, y) * ustrength + (float)x;
float fv = (float)tpm_get_pixel(vmap, x, y) * vstrength + (float)y;
tpm_put_pixel(dst, x, y, tpm_get_filtered_pixel(src, fu, fv));
}
}
}
|
C
|
#include "cutting.h"
void print_token(char *token, int ptr_debut, int ptr_fin)
{
//printf("\n<ptrs = %d, ptrf = %d>\n", ptr_debut, ptr_fin);
while(ptr_debut <= ptr_fin) printf("%c", token[ptr_debut++]);
}
void fileToTempon()
{
pascalTabS = NULL;
char *m = (char*)malloc(MAX_LINE*sizeof(char));
int row = 1; // c'est le nombre de ligne
FILE *F = fopen(nameFile, "r");
while(fgets(m,MAX_LINE,F) != NULL)
{
decoupage(m, row);
row++;
}
}
int isSpeacial(char s)
{
if (s == '+' ||
s == '-' ||
s == '*' ||
s == '/' ||
s == ':' ||
s == '=' ||
s == ';' ||
s == ',' ||
s == '.' ||
s == '<' ||
s == '>' ||
s == '(' ||
s == ')' ||
s == ' ' ||
s == '\n'||
s == '\t'||
s == '{') return 1 ;
return 0 ;
}
void decoupage(char *temp, int line)
{
int ptr_debut = 0, ptr_fin = 0 ;
int longueur_line = strlen(temp);
int isComdeb = 0;
int isComfin = 0;
//printf("\nDECOPAGE ::: %s\n", temp);
for(ptr_fin = 0; ptr_fin < longueur_line; ptr_fin++)
{
///Trait the commentaire
if(temp[ptr_fin] == '{' && temp[ptr_fin+1] == '*') isComdeb = 1;
if(temp[ptr_fin] == '*' && temp[ptr_fin+1] == '}') {isComfin = 1; ptr_fin += 2;}
if(isComdeb && !isComfin) continue;
if(!isSpeacial(temp[ptr_fin]))
{
//if(ptr_fin == longueur_line - 1) Filter_identifer_number(temp, ptr_debut, ptr_fin);
continue;
}
else
{
///Trait the token temp[ptr_debut-->ptrfin-1]
if(!isSpeacial(temp[ptr_debut])) Filter_identifer_number(temp, ptr_debut, ptr_fin-1);
///Trait the space and tab
if(temp[ptr_fin] == ' ' || temp[ptr_fin] == '\t')
{
ptr_debut = ptr_fin + 1;
}
else if(temp[ptr_fin] == '\n')
{
continue;
}
///for the special symbol :=, <>, <=, >=
else if(( temp[ptr_fin] == ':' && temp[ptr_fin+1] == '=') ||
( temp[ptr_fin] == '<' && temp[ptr_fin+1] == '>') ||
((temp[ptr_fin] == '<' || temp[ptr_fin] == '>') && temp[ptr_fin+1] == '='))
{
//Traite de symbole
getSpecialSymbol(temp, ptr_fin, ptr_fin+1);
ptr_debut = ptr_fin + 2 ;
ptr_fin++;
}
else
{
//Traite
getSpecialSymbol(temp, ptr_fin, ptr_fin);
ptr_debut = ptr_fin+1;
}
}
}
}
symbolTable_t *addLexem(symbolTable_t *pascalTabS, char *temp, int ptr_debut, int ptr_fin, char *unlex)
{
symbolTable_t *lex = (symbolTable_t*) malloc(sizeof(symbolTable_t));
if(pascalTabS == NULL) pascalTabS = lex;
else
{
symbolTable_t *next = pascalTabS;
while(next->nextLexem != NULL) next = next->nextLexem;
lex->lexem = toString(temp, ptr_debut, ptr_fin);
lex->lexUnity = (char*) malloc(strlen(unlex)*sizeof(char));
strcpy(lex->lexUnity, unlex);
lex->nextLexem = NULL;
next->nextLexem = lex;
}
return pascalTabS;
}
void Filter_identifer_number(char* temp, int ptr_debut, int ptr_fin)
{
print_token(temp, ptr_debut, ptr_fin);
if(isdigit(temp[ptr_debut]))
{
if(IsNumber(temp, ptr_debut, ptr_fin))
{
printf("\t\t\tNUMBER\n");
//pascalTabS = addLexem(pascalTabS, temp, ptr_debut, ptr_fin, "NUMBER");
}
else
{
printf("\t\t\tERROR\n");
//pascalTabS = addLexem(pascalTabS, temp, ptr_debut, ptr_fin, "ERROR");
}
}
else if(isalpha(temp[ptr_debut]))
{
char *unlex = IsKeyWord(temp, ptr_debut, ptr_fin);
if(unlex != NULL)
{
printf("\t\t\t%s\n", unlex);
//pascalTabS = addLexem(pascalTabS, temp, ptr_debut, ptr_fin, unlex);
}
else if(IsIdentifier(temp, ptr_debut, ptr_fin))
{
printf("\t\t\tIDENTIFIER\n");
//pascalTabS = addLexem(pascalTabS, temp, ptr_debut, ptr_fin, "IDENTIFIER");
}
else
{
printf("\t\t\tERROR\n");
//pascalTabS = addLexem(pascalTabS, temp, ptr_debut, ptr_fin, "ERROR");
}
}
else
{
printf("\t\t\tERROR\n");
//pascalTabS = addLexem(pascalTabS, temp, ptr_debut, ptr_fin, "ERROR");
}
}
void getSpecialSymbol(char* str, int ptrs, int ptrf)
{
print_token(str, ptrs, ptrf);
char *k = isSpeacialSymbol(str, ptrs, ptrf);
if(k != NULL) /*addLexem(pascalTabS, str, ptrs, ptrf, k);*/ printf("\t\t\t%s\n", k);
else /*addLexem(pascalTabS, str, ptrs, ptrf, "ERROR");*/ printf("\t\t\tERROR\n");
}
void printLexTab()
{
symbolTable_t *next = pascalTabS;
while(next != NULL)
{
printf("%s\t\t\t\t%s\n", next->lexem, next->lexUnity);
next = next->nextLexem;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jmartyn- <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/14 15:39:19 by jmartyn- #+# #+# */
/* Updated: 2019/09/14 15:39:54 by jmartyn- ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void flag_hash_and_zero_print_continue(int j, int i, char *hexadecimal)
{
char tmp;
while (j >= 0)
{
if (is_upper(hexadecimal[j]) == 1)
{
tmp = hexadecimal[j];
tmp = tmp + 32;
write(1, &tmp, 1);
j--;
}
if (is_upper(hexadecimal[j]) == 0)
{
tmp = hexadecimal[j];
write(1, &tmp, 1);
j--;
}
if (is_digit(hexadecimal[j] == 1))
{
write(1, &hexadecimal[j], 1);
j--;
}
}
}
void flag_hash_and_zero_print(const char *format, va_list list, struct p parsed_x)
{
char hexadecimal[100];
long decimal;
long quotient;
long remainder;
int i;
i = 0;
decimal = va_arg(list, int);
quotient = decimal;
if (decimal < 0)
quotient = handle_negative_x(decimal);
if (quotient == 0)
write(1, "0", 1);
while (quotient != 0)
{
remainder = quotient % 16;
if (remainder < 10)
hexadecimal[i] = 48 + remainder;
else
hexadecimal[i] = 55 + remainder;
i++;
quotient = quotient / 16;
}
if (decimal != 0)
write(1, "0x", 2);
flag_hash_and_zero_print_continue((i - 1), i, hexadecimal);
}
int flag_hash_and_zero(const char *format, va_list list, int res, struct p parsed)
{
res = res - parsed.size;
flag_hash_and_zero_print(format, list, parsed);
return (res);
}
|
C
|
#include <stdio.h>
#include "dllist.h"
void dl_init_node(LPDL_NODE node)
{
node->dl_next = NULL;
node->dl_pre = NULL;
}
void dl_insert_node(LPDL_NODE node, LPDL_NODE insert, LPDL_ROOT root)
{
if (insert) { //update head
node->dl_next = insert->dl_next;
insert->dl_next = node;
node->dl_pre = insert;
if (node->dl_next) {
node->dl_next->dl_pre = node;
} else { //update last
root->dl_last = node;
}
} else {
if (root->dl_head) {
root->dl_head->dl_pre = node;
node->dl_next = root->dl_head;
root->dl_head = node;
root->dl_head->dl_pre = NULL;
} else {
root->dl_head = node;
node->dl_pre = NULL;
root->dl_last = node;
node->dl_next = NULL;
}
}
}
void dl_remove_node(LPDL_NODE node, LPDL_ROOT root)
{
if (node->dl_pre) {
node->dl_pre->dl_next = node->dl_next;
} else {
root->dl_head = node->dl_next;
}
if (node->dl_next) {
node->dl_next->dl_pre = node->dl_pre;
} else {
root->dl_last = node->dl_pre;
}
}
void dl_replace_node(LPDL_NODE node, LPDL_NODE replace, LPDL_ROOT root)
{
if (node->dl_pre) {
node->dl_pre->dl_next = replace;
replace->dl_pre = node->dl_pre;
} else {
root->dl_head = replace;
}
if (node->dl_next) {
node->dl_next->dl_pre = replace;
replace->dl_next = node->dl_next;
} else {
root->dl_last = replace;
}
}
LPDL_NODE dl_next(LPDL_NODE node)
{
return node->dl_next;
}
LPDL_NODE dl_prev(LPDL_NODE node)
{
return node->dl_pre;
}
LPDL_NODE dl_first(const LPDL_ROOT root)
{
return root->dl_head;
}
LPDL_NODE dl_last(const LPDL_ROOT root)
{
return root->dl_last;
}
|
C
|
// Your Name
// CS136, Winter 2015
// Assignment 8, Problem 2
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <stdbool.h>
int main(void) {
struct dyn_array {
int *data;
int len ;
int max ;
};
struct dyn_array da = {NULL, 0, 0};
int ch;
while (1){
int returns = scanf("%d", &ch);
if (da.len == da.max) {
if (da.max == 0) {
da.max = 1;
da.data = malloc(sizeof(int));
} else {
da.max *= 2;
da.data = realloc(da.data, sizeof(int) * da.max); }
}
if (returns == 0 || returns == EOF){
for (int i = 0; i < (da.len); ++i){ // pay attention to here
// (int i = 0; i <= (da.len); ++i) is not good!!
if(da.data[i] < da.data[da.len - 1])
printf ("%d\n", da.data[i]);
}
free(da.data);
return(0);
}
da.data[da.len] = ch;
da.len++;
}
}
|
C
|
//File: ServerC.c
// prj02 : This file contains the 'main' function. Program execution begins and ends there.
// Author: CHIKE OKONTA
// CLASS: CSCI 312
// PROJECT 03: Implementation file (ServerC.c)
// Date: 10/19/2020
/*
* PURPOSE
* Play rock Paper and Scissors using client server connections
*/
/*
* INSTRUCTIONS
* 1. Ensure ServerC.c, ServerG.c, sharedCode.h are all in the same directory
* 2. run the following line in terminal: make
* 4. run pwd to ensure makefile was successfully generated
* 5. run the following command
* ./ServerC
* 6. follow instructions on the screen
*/
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include "sharedCode.h"
//Fuction: HandleTCP Client
void HandleTCPClient(int clntSocket) {
//Launch ServerG
int err = execl("./ServerG", "ServerG", clntSocket, (char *)NULL);
if (err == -1)
{
printf("Failed to launch ServerG");
exit(1);
}
}
int main(int argc, char* argv[])
{
if (argc != 2) // Test for correct number of arguments
DieWithUserMessage("Parameter(s)", "<Server Port/Service>");
char* service = argv[1]; // First arg: local port/service
int servSock = SetupTCPServerSocket(service);
if (servSock < 0)
DieWithUserMessage("SetupTCPServerSocket() failed", "unable to establish");
unsigned int childProcCount = 0; // Number of child processes
//SERVER C
for (;;)
{ // Run forever
// New connection creates a client socket
int clntSock = AcceptTCPConnection(servSock);
// Fork child process and report any errors
pid_t processID = fork();
if (processID < 0)
DieWithSystemMessage("fork() failed");
else if (processID == 0)
{ // If this is the child process
//Start ServerG
close(servSock); // Child closes parent socketSet
HandleTCPClient(clntSock);
exit(0); // Child process terminates
}
printf("with child process: %d\n", processID);
close(clntSock); // Parent closes child socket descriptor
childProcCount++; // Increment number of child processes
while (childProcCount)
{ // Clean up all zombies
processID = waitpid((pid_t)-1, NULL, WNOHANG); // Non-blocking wait
if (processID < 0) // waitpid() error?
DieWithSystemMessage("waitpid() failed");
else if (processID == 0) // No zombie to wait on
break;
else
childProcCount--; // Cleaned up after a child
}
}
// NOT REACHED
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
//char buffer[BUFSIZE]; // Buffer for echo string
//// Receive message from client
//ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
//if (numBytesRcvd < 0)
// DieWithSystemMessage("recv() failed");
//// Send received string and receive again until end of stream
//while (numBytesRcvd > 0)
//{ // 0 indicates end of stream
// // Echo message back to client
// ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
// if (numBytesSent < 0)
// DieWithSystemMessage("send() failed");
// else if (numBytesSent != numBytesRcvd)
// DieWithUserMessage("send()", "sent unexpected number of bytes");
// // See if there is more data to receive
// numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
// if (numBytesRcvd < 0)
// DieWithSystemMessage("recv() failed");
|
C
|
/*
* bunker.h
*
* Created on: Sep 22, 2016
* Author: superman
*/
#ifndef BUNKER_H_
#define BUNKER_H_
#include <stdint.h>
#define BUNKER_NUM_BUNKERS 4 //Number of bunkers
#define BUNKER_NUM_TILES 10 //Number of bunker tiles
#define BUNKER_EROSION_STATE_0 0 //Erosion state 0 whole
#define BUNKER_EROSION_STATE_1 1 //Erosion state 1 eroded
#define BUNKER_EROSION_STATE_2 2 //Erosion state 2 more eroded
#define BUNKER_EROSION_STATE_3 3 //Erosion state 3 even more eroded
#define BUNKER_EROSION_STATE_4 4 //Erosion state 4 gone
#define BUNKER_Y 170 //BUNKER vertical position
typedef struct
{
int16_t x; //Position of Bunker
uint16_t bunker_tiles[BUNKER_NUM_TILES]; //Status of which aliens are alive
} bunker_graphics;
//initialze the 4 bunkers
void bunker_init();
//erode bunker of given bunker and tile
void bunker_erode(uint16_t bunkerNumber, uint16_t tileNumber);
//get x coordinate of given bunker
int16_t bunker_getX(uint16_t bunkerNumber);
//Get the erosion state of given bunker and tile
uint16_t bunker_getErosionState(uint16_t bunkerNumber, uint16_t tileNumber);
#endif /* BUNKER_H_ */
|
C
|
#include<stdio.h>
#include<limits.h>
int main()
{
int n, m;
int arr[100001] = { 0, };
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
int l = 0, r = 0;
int num = 0;
int sum = 0;
int ans = INT_MAX;
while (l <= r&&r<=n)
{
if (sum >= m)
{
//printf("len: %d\n", r - l);
if(ans>r-l)
ans = r - l;
sum -= arr[l];
l++;
}
else
{
sum += arr[r];
r++;
}
}
if (ans == INT_MAX)
ans = 0;
printf("%d\n", ans);
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "graph.h"
#include "list.h"
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
struct _graph{
node **list;
int vertices;
};
graph *graph_create(int vertices) {
graph *g = calloc(1, sizeof(graph));
g->list = calloc(vertices, sizeof(node *));
g->vertices = vertices;
return g;
}
graph *graph_from_sequence(int *seq, int len) {
int vertices = -1;
for (int i = 0; i < len; i++) {
vertices = MAX(vertices, seq[i]);
}
graph *g = graph_create(vertices + 1);
for (int i = 1; i < len; i++) {
graph_edge *ge = graph_edge_get(g, seq[i - 1], seq[i]);
if (ge) {
ge->w++;
} else {
graph_edge_add(g, seq[i - 1], seq[i], 1);
}
}
graph_edge_add(g, seq[len - 1], -1, 1);
return g;
}
void graph_destroy(graph *g) {
for(int i = 0; i < g->vertices; i++) {
for (node *x = g->list[i]; x; x = list_next(x)) {
free(list_val(x).pointer);
}
list_destroy(g->list[i]);
}
free(g->list);
free(g);
}
double graph_vertex_similarity(graph *g1, graph *g2) {
int max_vertices = MAX(g1->vertices, g2->vertices);
int common_vertices = 0;
int total_vertices = 0;
for (int i = 0; i < max_vertices; i++) {
if (i < g1->vertices && i < g2->vertices && g1->list[i] && g2->list[i]) {
common_vertices++;
}
if ((i < g1->vertices && g1->list[i]) || (i < g2->vertices && g2->list[i])) {
total_vertices++;
}
}
return common_vertices / (double) total_vertices;
}
double graph_edge_similarity(graph *g1, graph *g2) {
int max_vertices = MAX(g1->vertices, g2->vertices);
int common_weight = 0;
int total_weight = 0;
int *g1_weights = malloc(max_vertices * sizeof(int));
int *g2_weights = malloc(max_vertices * sizeof(int));
for (int i = 0; i < max_vertices; i++) {
memset(g1_weights, 0, max_vertices * sizeof(int));
memset(g2_weights, 0, max_vertices * sizeof(int));
if (i < g1->vertices) {
for (node *x = g1->list[i]; x; x = list_next(x)) {
graph_edge *ge = list_val(x).pointer;
if (0 <= ge->v && ge->v < max_vertices) {
g1_weights[ge->v] += ge->w;
}
}
}
if (i < g2->vertices) {
for (node *x = g2->list[i]; x; x = list_next(x)) {
graph_edge *ge = list_val(x).pointer;
if (0 <= ge->v && ge->v < max_vertices) {
g2_weights[ge->v] += ge->w;
}
}
}
for (int j = 0; j < max_vertices; j++) {
common_weight += MIN(g1_weights[j], g2_weights[j]);
total_weight += MAX(g1_weights[j], g2_weights[j]);
}
}
free(g1_weights);
free(g2_weights);
return common_weight / (double) total_weight;
}
void graph_edge_add(graph *g, int u, int v, int w) {
graph_edge *ge = malloc(sizeof(graph_edge));
*ge = (graph_edge) {u, v, w};
g->list[u] = list_insert(g->list[u], (node_val) {.pointer = (void*) ge});
}
graph_edge *graph_edge_get(graph *g, int u, int v) {
node *x = g->list[u];
for (node *x = g->list[u]; x; x = list_next(x)) {
graph_edge *ge = list_val(x).pointer;
if (ge->v == v) {
return ge;
}
}
return NULL;
}
void graph_edge_remove(graph *g, int u, int v) {
for (node *x = g->list[u]; x; x = list_next(x)) {
graph_edge *ge = list_val(x).pointer;
if(ge->v == v){
g->list[u] = list_delete(g->list[u], list_val(x));
break;
}
}
}
node *graph_edge_list(graph *g, int u) {
return g->list[u];
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.