language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
int main()
{
int n,t;
scanf("%d",&n);
{
t=n/100;
if(t>0)
printf("%d\n",t);
else
printf("0\n");
n=n-100*t;
t=n/50;
if(t>0)
printf("%d\n",t);
else
printf("0\n");
n=n-50*t;
t=n/20;
if(t>0)
printf("%d\n",t);
else
printf("0\n");
n=n-20*t;
t=n/10;
if(t>0)
printf("%d\n",t);
else
printf("0\n");
n=n-10*t;
t=n/5;
if(t>0)
printf("%d\n",t);
else
printf("0\n");
n=n-5*t;
if(n>0)
printf("%d\n",n);
else
printf("0\n");
return 0;
}
}
|
C
|
//*******************************************
// Trading functions
//res::http://docs.mql4.com/trading
//*******************************************
#ifndef TRADING_H__
#define TRADING_H__
#include"Framework/standardCPPLibrary.h"
#include"DataType.h"
#include"DataStructures.h"
#define MODE_TRADES 0
#define MODE_HISTORY 1
#define SELECT_BY_POS 1
#define SELECT_BY_TICKET 2
//Returns true if successful, otherwise false. To get additional error information, one has to call the GetLastError() function.
bool OrderClose(int ticket, double lots, double price, int slippage, color Color=CLR_NONE);
bool OrderCloseBy(int ticket, int opposite, color Color=CLR_NONE);
double OrderClosePrice();
datetime OrderCloseTime();
string OrderComment();
double OrderCommission();
//If the function succeeds, it returns true, otherwise false. To get the detailed error information, call the GetLastError() function.
bool OrderDelete(int ticket, color arrow_color );
datetime OrderExpiration();
double OrderLots();
int OrderMagicNumber();
/*
Parms:
double price: use in pending order, if the order is Opened, please set to 0
Return:
If the function succeeds, it returns true, otherwise false.To get the detailed error information, call the GetLastError() function.
*/
bool OrderModify(int ticket, double price, double stoploss, double takeprofit, datetime expiration,
color arrow_color=CLR_NONE);
double OrderOpenPrice();
datetime OrderOpenTime();
void OrderPrint();
double OrderProfit();
//It returns true if the function succeeds, otherwise falses. To get the error information, one has to call the GetLastError() function.
bool OrderSelect(int index, int select, int pool=MODE_TRADES);
//Returns number of the ticket assigned to the order by the trade server or - 1 if it fails.To get additional error information, one has to call the GetLastError() function.
int OrderSend(string symbol, int cmd, double volume, double price, int slippage, double stoploss,
double takeprofit, string comment=NULL, int magic=0, datetime expiration=0,
color arrow_color=CLR_NONE);
//The number of closed orders in the account history loaded into the terminal.The history list size depends on the current settings of the "Account history" tab of the terminal.
int OrdersHistoryTotal();
//Total amount of market and pending orders.
int OrdersTotal();
double OrderStopLoss();
double OrderSwap();
string OrderSymbol();
double OrderTakeProfit();
int OrderTicket();
int OrderType();
/*
The function calculates the margin required for the specified order type, on the current account,
in the current market environment not taking into account current pending orders and open positions.
It allows the evaluation of margin for the trade operation planned. The value is returned in the account
currency.
*/
bool OrderCalcMargin(
ENUM_ORDER_TYPE action, // type of order
string symbol, // symbol name
double volume, // volume
double price, // open price
double& margin // value for obtaining the margin value
);
/*
The function calculates the profit for the current account, in the current market conditions, based
on the parameters passed.The function is used for pre - evaluation of the result of a trade operation.
The value is returned in the account currency.
*/
bool OrderCalcProfit(
ENUM_ORDER_TYPE action, // type of the order (ORDER_TYPE_BUY or ORDER_TYPE_SELL)
string symbol, // symbol name
double volume, // volume
double price_open, // open price
double price_close, // close price
double& profit // variable for obtaining the profit value
);
/*
The OrderCheck() function checks if there are enough money to execute a required trade operation.
The check results are placed to the fields of the MqlTradeCheckResult structure.
*/
bool OrderCheck(
MqlTradeRequest& request, // request structure
MqlTradeCheckResult& result // result structure
);
//The OrderSend() function is used for executing trade operations by sending requests to a trade server.
bool OrderSend(
MqlTradeRequest& request, // query structure
MqlTradeResult& result // structure of the answer
);
/*
The OrderSendAsync() function is used for conducting asynchronous trade operations without waiting for
the trade server's response to a sent request. The function is designed for high-frequency trading,
when under the terms of the trading algorithm it is unacceptable to waste time waiting for a response
from the server.
*/
bool OrderSendAsync(
MqlTradeRequest& request, // Request structure
MqlTradeResult& result // Response structure
);
//Returns the number of open positions.
int PositionsTotal();
/*
Returns the symbol corresponding to the open position and automatically selects the position for further
working with it using functions PositionGetDouble, PositionGetInteger, PositionGetString.
*/
string PositionGetSymbol(
int index // Number in the list of positions
);
/*
Chooses an open position for further working with it.Returns true if the function is successfully
completed.Returns false in case of failure.To obtain information about the error, call GetLastError().
*/
bool PositionSelect(
string symbol // Symbol name
);
/*
The function returns the requested property of an open position, pre - selected using PositionGetSymbol
or PositionSelect.The position property must be of the double type.There are 2 variants of the function.
1. Immediately returns the property value..
*/
double PositionGetDouble(ENUM_POSITION_PROPERTY_DOUBLE property_id );
/*
2. Returns true or false, depending on the success of the function execution.If successful, the value
of the property is placed in a receiving variable passed by reference by the last parameter.
*/
bool PositionGetDouble(
ENUM_POSITION_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
/*
The function returns the requested property of an open position, pre - selected using PositionGetSymbol
or PositionSelect.The position property should be of datetime, int type.There are 2 variants of the function.
1. Immediately returns the property value.
*/
long PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER property_id );
/*
2. Returns true or false, depending on the success of the function execution.If successful, the value of
the property is placed in a receiving variables passed by reference by the last parameter.
*/
bool PositionGetInteger(
ENUM_POSITION_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
/*
The function returns the requested property of an open position, pre - selected using PositionGetSymbol or
PositionSelect.The position property should be of the string type.There are 2 variants of the function.
1. Immediately returns the property value.
*/
string PositionGetString(ENUM_POSITION_PROPERTY_STRING property_id );
/*
2. Returns true or false, depending on the success of the function execution.If successful, the value of the
property is placed in a receiving variables passed by reference by the last parameter.
*/
bool PositionGetString(
ENUM_POSITION_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
//Returns ticket of a corresponding order automatically selects the order for further working with it using functions.
ulong OrderGetTicket(
int index // Number in the list of orders
);
/*
Selects an order to work with.Returns true if the function has been successfully completed.Returns false if the
function completion has failed.For more information about an error call GetLastError().
*/
bool OrderSelect(ulong ticket);
/*
Returns the requested property of an order, pre - selected using OrderGetTicket or OrderSelect.The order property
must be of the double type.There are 2 variants of the function.
1. Immediately returns the property value.
*/
double OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE property_id );
/*
2. Returns true or false, depending on the success of a function.If successful, the value of the property is placed
in a target variable passed by reference by the last parameter.
*/
bool OrderGetDouble(
ENUM_ORDER_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
/*
Returns the requested order property, pre - selected using OrderGetTicket or OrderSelect.Order property must be
of the datetime, int type.There are 2 variants of the function.
1. Immediately returns the property value.
*/
long OrderGetInteger(ENUM_ORDER_PROPERTY_INTEGER property_id );
/*
2. Returns true or false depending on the success of the function.If successful, the value of the property
is placed into a target variable passed by reference by the last parameter.
*/
bool OrderGetInteger(
ENUM_ORDER_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
/*
Returns the requested order property, pre - selected using OrderGetTicket or OrderSelect.The order property
must be of the string type.There are 2 variants of the function.
1. Immediately returns the property value.
*/
string OrderGetString(ENUM_ORDER_PROPERTY_STRING property_id );
/*
2. Returns true or false, depending on the success of the function.If successful, the value of the property
is placed into a target variable passed by reference by the last parameter.
*/
bool OrderGetString(
ENUM_ORDER_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
//Retrieves the history of deals and orders for the specified period of server time.
bool HistorySelect(
datetime from_date, // From date
datetime to_date // To date
);
//Retrieves the history of deals and orders having the specified position identifier.
bool HistorySelectByPosition(
long position_id // position identifier - POSITION_IDENTIFIER
);
/*
Selects an order from the history for further calling it through appropriate functions.It returns true
if the function has been successfully completed.Returns false if the function has failed.For more details on
error call GetLastError().
*/
bool HistoryOrderSelect(
ulong ticket // Order ticket
);
/*
Returns the number of orders in the history.Prior to calling HistoryOrdersTotal(), first it is necessary
to receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition() function.
*/
int HistoryOrdersTotal();
/*
Return the ticket of a corresponding order in the history.Prior to calling HistoryOrderGetTicket(),
first it is necessary to receive the history of deals and orders using the HistorySelect() or
HistorySelectByPosition() function.
*/
ulong HistoryOrderGetTicket(
int index // Number in the list of orders
);
/*
Returns the requested order property.The order property must be of the double type.There are 2 variants of the function.
1. Immediately returns the property value.
*/
double HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_DOUBLE property_id // Property identifier
);
/*
2. Returns true or false, depending on the success of the function.If successful, the value of the property
is placed into a target variable passed by reference by the last parameter.
*/
bool HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
/*
Returns the requested property of an order.The order property must be of datetime, int type.There are 2 variants
of the function.
1. Immediately returns the property value.
*/
long HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_INTEGER property_id // Property identifier
);
/*
2. Returns true or false, depending on the success of the function.If successful, the value of the property is
placed into a target variable passed by reference by the last parameter.
*/
bool HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
/*
Returns the requested property of an order.The order property must be of the string type.There are 2 variants
of the function.
1. Immediately returns the property value.
*/
string HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_STRING property_id // Property identifier
);
/*
2. Returns true or false, depending on the success of the function.If successful, the value of the property
is placed into a target variable passed by reference by the last parameter.
*/
bool HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
/*
Selects a deal in the history for further calling it through appropriate functions.It returns true if the
function has been successfully completed.Returns false if the function has failed.For more details on error
call GetLastError().
*/
bool HistoryDealSelect(ulong ticket);
/*
Returns the number of deal in history.Prior to calling HistoryDealsTotal(), first it is necessary to
receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition() function.
*/
int HistoryDealsTotal();
/*
The function selects a deal for further processing and returns the deal ticket in history.Prior to
calling HistoryDealGetTicket(), first it is necessary to receive the history of deals and orders using
the HistorySelect() or HistorySelectByPosition() function.
*/
ulong HistoryDealGetTicket(int index);
/*
Returns the requested property of a deal.The deal property must be of the double type.There are 2
variants of the function.
1. Immediately returns the property value.
*/
double HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_DOUBLE property_id // Property identifier
);
/*
2. Returns true or false, depending on the success of the function.If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
*/
bool HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
/*
Returns the requested property of a deal.The deal property must be of the datetime, int type.There are 2
variants of the function.
1. Immediately returns the property value.
*/
long HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_INTEGER property_id // Property identifier
);
/*
2. Returns true or false, depending on the success of the function.If successful, the value of the property
is placed into a target variable passed by reference by the last parameter.
*/
bool HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
/*
Returns the requested property of a deal.The deal property must be of the string type.There are 2 variants
of the function.
1. Immediately returns the property value.
*/
string HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_STRING property_id // Property identifier
);
/*
2. Returns true or false, depending on the success of the function.If successful, the value of the property
is placed into a target variable passed by reference by the last parameter.
*/
bool HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
#endif
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 1;
char *states[] = {"California", "Oregon", "Washington", "Texas"};
while(i < argc) {
states[i+3] = argv[i];
i++;
}
// I am getting a *** stack smashing detected *** message on running the program and then it says core dumped. Valrgind doesn't give me errors but i have managed to use the while loop to add the argv into the states array - my idea for a solution is the above line but unfortunately that doesn't appear to be working - i thought it might be that the array wasn't terminating properly
i = 0;
int num_states = 3 + argc;
while(i<num_states) {
printf("state %d: %s\n", i, states[i]);
i++;
}
return 0;
}
|
C
|
/* Test file for semantic errors. Contains exactly one error. */
int n;
int main(void) {
n = 42;
n[2]; // Index an integer
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("enter the a value");
scanf("d",&a);
if(a%2==0)
printf("%d is even",a);
else if(a%2!=0)
printf("%d is odd",a);
else
printf("%d is zero",a);
}
|
C
|
#include<stdio.h>
int main()
{
int number,newNumber;
printf("Enter a number:\n");
scanf("%d",&number);
while(number)
{
newNumber=(newNumber*10)+number%10;
number=number/10;
}
printf("%d is your Reverse number\n",newNumber);
return 0;
}
|
C
|
//
// T16-11-diving-board-lcci.c
// algorithm
//
// Created by Ankui on 7/8/20.
// Copyright © 2020 Ankui. All rights reserved.
//
// https://leetcode-cn.com/problems/diving-board-lcci/
#include "T16-11-diving-board-lcci.h"
#include "algorithm-common.h"
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* divingBoard(int shorter, int longer, int k, int* returnSize) {
if (k == 0) {
*returnSize = 0;
return NULL;
}
if (shorter == longer) {
int *p = malloc(sizeof(int));
*p = shorter * k;
*returnSize = 1;
return p;
}
*returnSize = k + 1;
int *lengths = malloc(sizeof(int) * (k + 1));
for (int i = 0; i <= k; i++) {
lengths[i] = shorter * (k - i) + longer * i;
}
return lengths;
}
|
C
|
/*************************************************************************
Copyright (C), 2015, TP-LINK TECHNOLOGIES CO., LTD.
File Name: client.c
Description: a client gives instructions and get response
Author: HeXiong
Email: hexiong@tp-link.net
History:
-----------------------------------------------
v0.1,2015-11-06,hexiong create the file and complete the function
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "client.h"
#define MAXLINE 4096
#define SERV_PORT 3000
#define UNIX_DOMAIN "/tmp/UNIX.domain"
#define UNIX_SEND "/tmp/UNIX.send"
int manager_start(int choice)
{
/* socket discriptor */
int sockfd;
/* the read and write buffer */
char sendline[MAXLINE];
char recvline[MAXLINE];
/* judge bind successfully or not */
int ret;
/* create the socket */
sockfd = socket(PF_UNIX, SOCK_DGRAM, 0);
if (sockfd < 0)
{
printf("Problem in creating the socket\n");
return 0;
}
/* we send content to this file */
struct sockaddr_un servaddr;
servaddr.sun_family = AF_UNIX;
strncpy(servaddr.sun_path, UNIX_DOMAIN, sizeof(servaddr.sun_path) - 1);
/* we receive content from this file */
struct sockaddr_un servaddr1;
servaddr1.sun_family = AF_UNIX;
strncpy(servaddr1.sun_path, UNIX_SEND, sizeof(servaddr1.sun_path) - 1);
unlink(UNIX_SEND);
/* memset buffer */
memset(sendline, 0, MAXLINE);
ret = bind(sockfd, (struct sockaddr *)&servaddr1, sizeof(servaddr1));
if (ret == -1)
{
perror("Cannot bind socket\n");
close(sockfd);
unlink(UNIX_SEND);
return 0;
}
/* according to user's input to fill buffer */
if (1 == choice)
{
sendline[0] = '1';
sendline[1] = '\0';
}
else if (2 == choice)
{
sendline[0] = '2';
sendline[1] = '\0';
}
else
{
return 0;
}
/* send buffer to server */
printf("The sendline is %s\n", sendline);
if (sendto(sockfd, sendline, strlen(sendline), 0,
(struct sockaddr *)&servaddr, sizeof(servaddr)) == -1)
{
printf("sendto error\n");
return 0;
}
while (1)
{
/* store the result return from server */
char result[MAXLINE];
memset(result, 0, MAXLINE);
if (recvfrom(sockfd, recvline, MAXLINE, 0, NULL, 0) < 0)
{
printf("read error\n");
return 0;
}
else
{
if (recvline[0] == '1')
{
close(sockfd);
unlink(UNIX_SEND);
return 1;
}
else
{
close(sockfd);
unlink(UNIX_SEND);
return 0;
}
}
}
}
|
C
|
#include "gap_buffer.h"
#include <string.h>
gap_buffer *gap_buffer_new(size_t len) {
gap_buffer *new_gb = calloc(1, sizeof(gap_buffer));
if(new_gb && len > 0) {
new_gb->buf = malloc(len);
if(new_gb->buf) {
new_gb->maxlen = len;
new_gb->len = 0;
new_gb->gap_end = len;
} else {
free(new_gb);
new_gb = NULL;
}
}
return new_gb;
}
void gap_buffer_delete(gap_buffer *gb) {
if(gb) {
if(gb->buf) {
free(gb->buf);
}
free(gb);
}
}
bool gap_buffer_empty(gap_buffer *gb) {
return gb->len == 0;
}
size_t gap_buffer_length(gap_buffer *gb) {
return gb->len;
}
// makes sure the gap beginning is at the cursor position
int _gap_buffer_sync(gap_buffer *gb) {
if(gb->gap_begin == gb->cursor) {
return gb->gap_begin;
}
if(gb->cursor < gb->gap_begin) { // cursor is in front of the gap, need to move data back
int count = gb->gap_begin - gb->cursor;
memmove(gb->buf + gb->gap_end - count, gb->buf + gb->cursor, count);
gb->gap_begin -= count;
gb->gap_end -= count;
} else { // cursor is in/past the gap, need to move data to front of buffer
int count = gb->cursor - gb->gap_end;
memmove(gb->buf + gb->gap_begin, gb->buf + gb->gap_end, count);
gb->gap_begin += count;
gb->gap_end += count;
//gb->cursor = gb->gap_begin;
}
return gb->cursor;
}
int _gap_buffer_chkexpand(gap_buffer *gb) {
const int multiplier = 2;
if(gb->gap_begin == gb->gap_end) {
size_t newsize = gb->len ? gb->len * multiplier : 1;
if(newsize < gb->len) { // check for overflow
return -1;
}
void *newptr = realloc(gb->buf, newsize);
if(!newptr) {
return -1;
}
size_t move_ct = gb->len - gb->gap_end;
memmove(newptr + newsize - move_ct, newptr + gb->gap_end, move_ct);
gb->buf = newptr;
gb->gap_end = newsize - move_ct;
gb->maxlen = newsize;
}
return 0;
}
// shrink the storage allocated for the gap buffer if it's below a low watermark
int _gap_buffer_chkshrink(gap_buffer *gb) {
const int divisor = 2;
size_t low_watermark = gb->maxlen / (2 * divisor);
size_t newlen = gb->maxlen / divisor;
// avoid shrinking to zero to avoid realloc() acting as a free() call
if(newlen && gb->len <= low_watermark) {
int old_cursor = gb->cursor;
// move the buffer gap to the end of the contents
if(gap_buffer_setcursor(gb, gb->len) != gb->len) {
return -1;
}
_gap_buffer_sync(gb);
char *newptr = realloc(gb->buf, newlen);
if(!newptr) {
gap_buffer_setcursor(gb, old_cursor);
return -1;
}
gb->buf = newptr;
gb->maxlen = newlen;
gb->gap_end = newlen;
gap_buffer_setcursor(gb, old_cursor);
}
return 0;
}
int gap_buffer_getcursor(gap_buffer *gb) {
return gb->cursor;
}
int gap_buffer_movecursor(gap_buffer *gb, int count) {
gb->cursor += count;
if(gb->cursor < 0) {
gb->cursor = 0;
} else if(gb->cursor > gb->len) {
gb->cursor = gb->len; }
return gb->cursor;
}
int gap_buffer_setcursor(gap_buffer *gb, int pos) {
gb->cursor = pos;
if(gb->cursor < 0) {
gb->cursor = 0;
} else if(gb->cursor > gb->len) {
gb->cursor = gb->len;
}
return gb->cursor;
}
// return the number of characters added to the buffer
int gap_buffer_addch(gap_buffer *gb, char c) {
_gap_buffer_sync(gb); // sync gap buffer with cursor
if(_gap_buffer_chkexpand(gb) < 0) {
return 0;
}
if(gb->len >= gb->maxlen) {
return 0;
}
gb->buf[gb->cursor] = c;
++gb->cursor;
++gb->gap_begin;
++gb->len;
return 1;
}
int gap_buffer_delch(gap_buffer *gb) {
_gap_buffer_sync(gb); // sync gap buffer with cursor
if(gb->len == 0 || gb->cursor == 0) {
return 0;
}
--gb->cursor;
--gb->gap_begin;
--gb->len;
_gap_buffer_chkshrink(gb);
return 1;
}
int gap_buffer_copy(gap_buffer *gb, char *dst, size_t len) {
size_t n_copied = 0;
size_t n_to_copy = gb->gap_begin;
n_to_copy = n_to_copy < len ? n_to_copy : len;
memcpy(dst, gb->buf, n_to_copy);
dst += n_to_copy;
len -= n_to_copy;
n_copied += n_to_copy;
n_to_copy = gb->len - n_to_copy;
n_to_copy = n_to_copy < len ? n_to_copy : len;
memcpy(dst, gb->buf + gb->gap_end, n_to_copy);
n_copied += n_to_copy;
return n_copied;
}
char gap_buffer_getbyte(gap_buffer *gb, size_t pos) {
if(pos >= gb->gap_begin) {
pos = (pos - gb->gap_begin) + gb->gap_end;
}
return gb->buf[pos];
}
char *gap_buffer_getpos(gap_buffer *gb, size_t pos) {
if(pos >= gb->gap_begin) {
pos = (pos - gb->gap_begin) + gb->gap_end;
}
return &gb->buf[pos];
}
|
C
|
#include "sort.h"
/**
* swap_arr - swap two numbers in the array
* @a: number 1
* @b: number 2
* @array: array to print in case of swap
* @size: array size
* Return: Nothing
*/
void swap_arr(int *a, int *b, int *array, size_t size)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
if (temp != *a)
print_array(array, size);
}
/**
* partition - function to parse the array in 2 arrays
* @array: array
* @low: position of first element of the array
* @last: position of the last element
* @size: array size
* Return: final position of pivot
*/
int partition(int *array, int low, int last, size_t size)
{
int pivot = array[last], j;
int i = low - 1;
for (j = low; j < last; j++)
{
if (array[j] <= pivot)
{
i++;
swap_arr(&array[j], &array[i], array, size);
}
}
i = i + 1;
swap_arr(&array[i], &array[last], array, size);
return (i);
}
/**
* new_quick - Recursive function to sort the array
* @array: array
* @low: position of first element of the array
* @last: position of the last element
* @size: array size
* Return: Nothing
*/
void new_quick(int *array, int low, int last, size_t size)
{
int div;
if (low < last)
{
div = partition(array, low, last, size);
new_quick(array, 0, div - 1, size);
new_quick(array, div + 1, last, size);
}
}
/**
* quick_sort - sorts an array in ascending order
* @array: array to be sroted
* @size: array size
* Return: Nothing
*/
void quick_sort(int *array, size_t size)
{
int last, low;
last = size - 1;
low = 0;
if (array == NULL || size < 2)
return;
new_quick(array, low, last, size);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "misc.h"
#ifndef MAX_NUM
#define MAX_NUM 10000
#endif
int results[MAX_NUM][N]={0};
int seq[MAX_NUM];
int sort_seq[MAX_NUM];
int sort_results[MAX_NUM][N]={0};
int cnt = 0;
/*
make -e t=62 n=20 m=10000
*/
void insert_num(int n)
{
int i,j;
if(cnt == 0)
{
memcpy(sort_results[0], results[n], N*sizeof(int));
cnt++;
sort_seq[0] = seq[n];
}
else
{ if(compare_long_nums(sort_results[cnt-1], results[n])>0)
{
for(i=cnt-1;i>=0;i--)
{
if(compare_long_nums(sort_results[i], results[n])<0)
{
for(j=cnt-1;j>i;j--)
{
memcpy(sort_results[j+1], sort_results[j], N*sizeof(int));
sort_seq[j+1] = sort_seq[j];
}
memcpy(sort_results[i+1], results[n], N*sizeof(int));
sort_seq[i+1] = seq[n];
break;
}
}
}
else
{
memcpy(sort_results[cnt], results[n], N*sizeof(int));
sort_seq[cnt] = seq[n];
}
cnt++;
}
}
int main()
{
long long i,n,k;
long long result;
for(i=0;i<MAX_NUM;i++)
{
result = i*i*i;
format_long_long_num(result, &results[i][0]);
sort_list(&results[i][1],results[i][0]);
printf("%lld:",i);
output_long_num(results[i]);
seq[i] = i;
insert_num(i);
}
for(i=0;i<MAX_NUM;i++)
{
#if 0
printf("%2d: %d",i, sort_seq[i]);
output_long_num(sort_results[i]);
#endif
if(memcmp(sort_results[i],sort_results[i+1],N*sizeof(int))==0 &&
memcmp(sort_results[i],sort_results[i+2],N*sizeof(int)) ==0 &&
memcmp(sort_results[i],sort_results[i+3],N*sizeof(int)) ==0 &&
memcmp(sort_results[i],sort_results[i+4],N*sizeof(int)) ==0)
{
printf("%d %d %d %d %d\n", sort_seq[i],sort_seq[i+1],sort_seq[i+2],
sort_seq[i+3],sort_seq[i+4]);
/*break;*/
}
}
return 0;
}
|
C
|
//#define _CRT_SECURE_NO_WARNINGS 1
//#include<stdio.h>
//int main()
//{
// int x, y;
// scanf("%d", &x);
// if (x > 0)
// y = 1;
// else if (x == 0)
// y = 0;
// else y = -1;
// printf("%d", y);
// system("pause");
// return 0;
//}
//
//#include<stdio.h> //1-100֮
//int main()
//{
// int i = 0;
// for (i = 0; i <= 100; i++)
// {
// if (i%2!=0)
// printf("%d\n",i);
// }
//
//
// system("pause");
// return 0;
//}
#include<stdio.h>
int main()
{
int arr1[] = { 1, 2, 3, 4 };
int arr2[] = { 5, 6, 3, 9, 0 };
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 5; j++)
{
if (arr1[i] == arr2[j]) //һֱûУô@һ䲻ִУ
{
printf("\n");
return 0; //һ ô@return 0ǽ@ѭ
}
}
}
printf("û\n");
return 0;
}
|
C
|
/*
Ex.1: Create function to copy all digits from input string to output string
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
uint8_t extractDigits(char* inputStr, char* outputStr, uint16_t maxLength);
int main()
{
uint16_t length = 200;
char inputStr[length];
char outputStr[length];
uint8_t isNoDigits = 1;
memset(inputStr, '\0', sizeof(char)*length);
memset(outputStr, '\0', sizeof(char)*length);
printf("Enter your data (up to %d characters):", length);
scanf("%s", &inputStr);
isNoDigits = extractDigits(&inputStr, &outputStr, length);
if (isNoDigits == 0)
{
printf("Extarcted digits from your string:\n %s", outputStr);
}
else
{
printf("Your string contains no digits. Sorry.");
}
return 0;
}
uint8_t extractDigits(char* inputStr, char* outputStr, uint16_t maxLength)
{
uint8_t isNoDigits = 1;
int i,j;
for (i = 0, j = 0; i< maxLength; i++)
{
if (*(inputStr+i) >= '0' && *(inputStr+i)<='9')
{
*(outputStr+j) = *(inputStr+i);
j++;
}
}
if (j==0)
{
isNoDigits =1;
}
else
{
isNoDigits =0;
}
return isNoDigits;
}
|
C
|
#include <stdio.h>
#include "holberton.h"
/**
*main - entry point
*
*Return: Returns 0 upon successful run.
*/
int main(void)
{
long int c = 1, ch = 2, sum = 0, r = 2;
while (sum < 4000000)
{
sum = c + ch;
c = ch;
ch = sum;
if (sum % 2 == 0)
{
r += sum;
}
}
printf("%li\n", r);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void printIntArray(int *a, int n) {
int i;
for(i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int countPositive(int *v, int n) {
int counter, i;
for(i = 0, counter = 0; i < n; i++) {
if (v[i] >= 0)
counter++;
}
return counter;
}
void readArrayElements(int *a, int n) {
int i;
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
}
int *allocIntArray(int n) {
int *a;
a = malloc(n * sizeof(int));
if (a == NULL) {
printf("There are not enough memory!");
exit(1);
}
return a;
}
int *selectOnlyPositive(int *v, int n, int *nPositive) {
int *positiveArray;
int i, j;
*nPositive = countPositive(v, n);
positiveArray = allocIntArray(*nPositive);
j = 0;
for(i = 0; i < n || j < *nPositive; i++) {
if(v[i] >= 0)
positiveArray[j++] = v[i];
}
return positiveArray;
}
void freeMemory(int *a) {
free(a);
}
int main() {
int n, nPositiveArray;
int *array, *positiveArray;
printf("Insert the length of dynamic int array: ");
scanf("%d", &n);
array = allocIntArray(n);
printf("Insert array elements: ");
readArrayElements(array, n);
positiveArray = selectOnlyPositive(array, n, &nPositiveArray);
printIntArray(positiveArray, nPositiveArray);
freeMemory(array);
freeMemory(positiveArray);
return 0;
}
|
C
|
/**
* initials.c
*
* Lisa Carson
*
* User types in name and gets initials
*
*/
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// Gets name
string name = GetString();
// Gives initials
for(int i = 0, n = strlen(name); i < n; i++)
{
if (i == 0)
{
printf("%c", toupper(name[i]));
}
if (isspace(name[i]))
{
printf("%c", toupper(name[i + 1]));
}
}
printf("\n");
}
|
C
|
//
// main.c
// Exe7.25
//
// Created by Francesco Parrucci on 12/05/19.
// Copyright © 2019 Francesco Parrucci. All rights reserved.
//
/*
/*
(Attraversamento di un Labirinto) La griglia seguente è la rappresentazione di un labirinto all'interno di una matrice.
111111111111
100010000001
001010111101
111010000101
100001110100
111101010101
100101010101
110101010101
100000000101
111111011101
100000010001
111111111111
I numeri uno e zero rappresentano rispettivamente le pareti e i corridoi del labirinto.
Esiste un semplice algoritmo di attraversamento di un labirinto che garantisce il ritrovamento dell'uscista (sempre che
c'è ne sia una). Nel caso ceh l'uscita non ci fosse vi ritrovereste di nuovo al punto di partenza. Poggiate la mano a
destra sulla parete alla vostra destra e cominciate a camminare in avanti.
Non rimuovete mai la vostra mano dalla parete. Se il labirinto svolta a destra, seguite il muro a destra. Alla fine ar
riverete sicuramente all'uscita del labirinto, se nel frattempo non avete rimosso la vostra mano dalla parete. E' proba
bile che esista un percorso piu' breve di quello che avete intrapreso, ma in questo modo avrete la certezza di uscire
dal labirinto.
Scrivete la funzoine ricorsiva mazeTraverse per attraversare il labirinto. La funzione dovrà ricevere come argomenti
una matrice di caratteri 12 per 12, per rappresentare il labirinto, e la posizione di partenza all'interno dello stesso.
Man mano che mazeTraverse tenterà di individuare l'uscita dal labirinto, dovrà inserire il carattere x in ogni casella
del percorso. La funione dovrà visualizzare il labirinto dopo ogni mossa così che l'utente possa seguire la risuluzione
del labirinto.
(Generazione casuale di labirinti) Scrivete una funzione mazeGenerator che riceva come argomento una matrice di caratteri
12 per 12 e produca un labirinto a caso. La funzione dovrà anche restituire i punti di ingresso e di uscita del labirinto.
Provate la vostra funzione mazeTraverse dell'Esercizio 7.25 utilizzando vari labirinti generati a caso
(Lavirinti di qualsisi dimensione) Generalizzate le funzioni mazeTraverse dell'Esercizio 7.25 e 7.26, in modo da elaborare
labirinti di qualsiasi larghezza e altezza.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#define SIZE 12
int size;
void mazePrint(int maze [][12]);
void mazeTraverse(int maze[][12], int x, int y);
void mazeCreation(int maze[][12]);
void mazeGenerator(int maze[][12],int *,int *,int *,int *);
int main(){
srand(time(NULL));
printf("\nInserire la dimensione del labirinto: ");
scanf("%d",&size);
int maze[size][size], x, y, outX,outY;
mazeGenerator(maze,&y,&x,&outY,&outX);
//mazeCreation(maze);
mazePrint(maze);
getchar();
printf("\nValori d'ingresso: (y,x) (%d,%d)\n",x,y);
//printf("\n\t\tInserire un valore per le x :");
//scanf("%d",&x);
//printf("\n\t\tInserire un valore per le y :");
//scanf("%d",&y);
mazeTraverse(maze,y,x);
mazePrint(maze);
return 0;
}
void mazeGenerator(int maze[][12],int *Yi,int *Xi, int *Yo, int *Xo){
int countY, countX, mov, i=0, lato = 1 + rand() % 4, Xin, Xout,Yin,Yout;
for(countY = 0; countY <= size - 1; countY++)
for(countX = 0; countX <= size - 1; countX++)
maze[countY][countX] = 1;
for(countY = 1; countY <= size - 2; countY += 2){
Xin = rand() % 2;
for(countX = 1; countX <= size - 2; countX++){
if(Xin == 0)
maze[countY][countX] = 0;
}
}
for(countY = 1; countY <= size - 2; countY +=2){
Xin = rand() % 2;
for(countX = 1; countX <= size - 2; countX++){
if(Xin == 0)
maze[countX][countY] = 0;
}
}
lato = 1 + rand() % 4;
printf("\nValore del lato %d\n",lato);
if(lato == 1){ // simistro
Xin = 0;
Yin = 1 + rand() % (size - 2); // valore casuale di partenza per y
Xout = size - 1;
Yout = 1 + rand() % (size - 2); // valore casuale di partenza per y
}else if(lato == 2){ // superiore
Yin = 0;
Xin = 1 + rand() % (size - 2); // valore casuale di partenza per x
Yout = size - 1;
Xout = 1 + rand() % (size - 2); // valore casuale di partenza per x
}else if(lato == 3){ // destro
Xin = size - 1;
Yin = 1 + rand() % (size - 2); // valore casuale di partenza per y
Xout = 0;
Yout = 1 + rand() % (size - 2); // valore casuale di partenza per y
}else if(lato == 4){ // inferiore
Yin = size - 1;
Xin = 1 + rand() % (size - 2); // valore casuale di partenza per x
Yout = 0;
Xout = 1 + rand() % (size - 2); // valore casuale di partenza per x
}
*Xo = Xout;
*Xi = Xin;
*Yo = Yout;
*Yi = Yin;
maze[Yin][Xin] = 0; // imposti la partenza a 0
mov = 2 + rand() % 7;
i = 0;
printf("\nvalore casuale : %d\n",mov);
printf("\nValori di partenza Yin = %d , Xin = %d",Yin, Xin);
while(i < mov){
if(lato == 1 && Xin < size - 1)
maze[Yin][++Xin] = 0;
else if(lato == 2 && Yin < size - 1)
maze[++Yin][Xin] = 0;
else if(lato == 3 && Xin > 0)
maze[Yin][--Xin] = 0;
else if(lato == 4 && Yin > 0)
maze[--Yin][Xin] = 0;
i++;
}
if(lato == 1)
lato = 3;
else if(lato == 2)
lato = 4;
else if(lato == 3)
lato = 1;
else
lato = 2;
maze[Yout][Xout] = 0; // imposti l'uscita a 0
mov = 2 + rand() % 4;
i = 0;
printf("\nvalore casuale : %d\n",mov);
printf("\nValori di uscita Yout = %d , Xout = %d",Yout, Xout);
printf("\nvalore di lato: %d",lato);
while(i < mov){
if(lato == 1 && Xout < size - 1)
maze[Yout][++Xout] = 0;
else if(lato == 2 && Yout < size - 1)
maze[++Yout][Xout] = 0;
else if(lato == 3 && Xout > 0)
maze[Yout][--Xout] = 0;
else if(lato == 4 && Yout > 0)
maze[--Yout][Xout] = 0;
i++;
}
}
void mazePrint(int maze [][12]){
int x, y;
for(x = 0; x <= 10; x++)
printf("\n");
printf("\t\t ");
for(x = 1; x <= size; x++)
printf(" %2d",x);
printf("\n\t\t ");
for(x = 1; x <= size; x++)
printf(" |");
printf("\n\t\t");
for(x = 0; x <= size - 1;x++ ){
printf("%2d - ",x+1);
for(y = 0; y <= size - 1; y++)
printf(" %2d",maze[x][y]);
printf("\n\t\t");
}
//for(x = 0; x <= 10; x++)
// printf("\n");
}
void mazeTraverse(int maze[][12], int ys, int xs){
int x = xs , y = ys;
if(x == 0 && (y >= 0 && y <= 11)){ // 1 ° caso inizio a bordo sinistro
printf("\nPartito da lato sinistro ");
if(y == 0){
printf("angolo superiore ");
if(maze[y][x+1] == 2){
maze[x][y] = 2;
}else if(maze[y+1][x] == 2){
maze[x][y] = 2;
}else if(maze[y+1][x] == 0 ){ // libero sotto
maze[x][y] = 2;
y++;
}else if(maze[y][x+1] == 0 ){ // libero davanti
maze[x][y] = 2;
x++;
}else // bloccato
maze[y][x] = 2;
}else if(y == 11){
printf("angolo inferiore ");
if(maze[y][x+1] == 2){
maze[y][x] = 2;
}else if(maze[y-1][x] == 2){
maze[x][y] = 2;
}else if(maze[y-1][x] == 0){ // libero davanti
maze[y][x] = 2;
y--;
}else if(maze[y][x+1] == 0){ // libero sopra
maze[y][x] = 2;
x++;
}else // bloccato
maze[y][x] = 2;
}else{ // 10 >= y >= 1
printf("posizione di y : %d",y+1);
if(maze[y][x+1] == 2){
maze[y][x] = 2;
}else if(maze[y+1][x] == 2){
maze[y][x] = 2;
}else if(maze[y-1][x] == 2){
maze[x][y] = 2;
}else if(maze[y+1][x] == 0){ // libero in basso
maze[y][x] = 2;
y++;
}else if(maze[y-1][x] == 0){ // libero sopra
maze[y][x] = 2;
y--;
}else if(maze[y][x+1] == 0){ // libero avanti
maze[y][x] = 2;
x++;
}else // bloccato
maze[y][x] = 2;
}
}else if(y == 11 && (x >= 0 && x <= 11)){ // 2 * caso inizio bordo inferiore
printf("\nPartito da lato inferiore ");
if(x == 0){
printf("angolo sinistro ");
if(maze[y-1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x+1] == 2){
maze[y][x] = 2;
}else if(maze[y+1][x] == 0 ){ // libero avanti
maze[y][x] = 2;
y++;
}else if(maze[y][x+1] == 0 ){ // libero sopra
maze[y][x] = 2;
x++;
}else // bloccato
maze[y][x] = 2;
}else if(x == 11){
printf("angolo destro ");
if(maze[y-1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 2){
maze[y][x] = 2;
}else if(maze[y-1][x] == 0){ // libero sopra
maze[y][x] = 2;
y--;
}else if(maze[y][x-1] == 0){ // libero dietro
maze[y][x] = 2;
x--;
}else // bloccato
maze[y][x] = 2;
}else{ // 10 >= x >= 1
printf("posizione di x : %d",x+1);
if(maze[y-1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x+1] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 2){
maze[y][x] = 2;
}else if(maze[y-1][x] == 0){ // libero avanti
maze[y][x] = 2;
y--;
}else if(maze[y][x+1] == 0){ // libero sopra
maze[y][x] = 2;
x++;
}else if(maze[y][x-1] == 0){ // libero dietro
maze[y][x] = 2;
x--;
}else // bloccato
maze[y][x] = 2;
}
}else if(x == 11 && (y >= 0 && y <= 11)){ // 3 * caso inizio bordo destro
printf("\nPartito da lato destro ");
if(y == 0){
printf("angolo superiore ");
if(maze[y][x-1] == 2){
maze[y][x] = 2;
}else if(maze[y+1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 0){ // libero dietro
maze[y][x] = 2;
x--;
}else if(maze[y-1][x] == 0){ // libero sotto
maze[y][x] = 2;
y--;
}else // bloccato
maze[y][x] = 2;
}else if(y == 11){
printf("angolo inferiore ");
if(maze[y-1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 0 ){ // libero sopra
maze[y][x] = 2;
x--;
}else if(maze[y-1][x] == 0 ){ // libero dietro
maze[y][x] = 2;
y--;
}else // bloccato
maze[y][x] = 2;
}else{ // 10 >= x >= 1
printf("posizione di y : %d",y+1);
if(maze[y-1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 2){
maze[y][x] = 2;
}else if(maze[y][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 0){ // libero dietro
maze[y][x] = 2;
x--;
}else if(maze[y-1][x] == 0){ // libero sopra
maze[y][x] = 2;
y--;
}else if(maze[y+1][x] == 0){ // libero dietro
maze[y][x] = 2;
y++;
}else // bloccato
maze[y][x] = 2;
}
}else if(y == 0 && (x >= 0 && x <= 11)){ // 4 ° caso inizio a bordo superiore
printf("\nPartito da lato superiore ");
if(x == 0){
printf("angolo sinistro ");
if(maze[y+1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x+1] == 2){
maze[y][x] = 2;
}else if(maze[y+1][x] == 0 ){ // libero sotto
maze[y][x] = 2;
y++;
}else if(maze[y][x+1] == 0 ){ // libero davanti
maze[y][x] = 2;
x++;
}else // bloccato
maze[y][x] = 2;
}else if(x == 11){
printf("angolo destro ");
if(maze[y][x-1] == 2){
maze[y][x] = 2;
}else if(maze[y+1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 0 ){ // libero dietro
maze[y][x] = 2;
x--;
}else if(maze[y+1][x] == 0 ){ // libero sotto
maze[y][x] = 2;
y++;
}else // bloccato
maze[y][x] = 2;
}else{ // 10 >= x >= 1
printf("posizione di x : %d",x+1);
if(maze[y+1][x] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 2){
maze[y][x] = 2;
}else if(maze[y][x+1] == 2){
maze[y][x] = 2;
}else if(maze[y][x-1] == 0){ // libero dietro
maze[y][x] = 2;
x--;
}else if(maze[y+1][x] == 0){ // libero sotto
maze[y][x] = 2;
y++;
}else if(maze[y][x+1] == 0){ // libero avanti
maze[y][x] = 2;
x++;
}else // bloccato
maze[y][x] = 2;
}
}else{// if(x > 0 && x < size -1 && y >0 && y < size - 1){ // interno quadrato
if(maze[y][x-1] != 0){ // provenienza da sinistra
// casi in cui giro a destra
printf("\nProvengo da sinistra ");
if(maze[y+1][x] == 0){ // giro a dx all'incrocio
printf("giro a destra");
maze[y][x] = 2;
y++;
}else if(maze[y][x+1] == 0){ // proseguo se dx è bloccato
printf("tiro dritto!");
maze[y][x] = 2;
x++;
}else if(maze[y-1][x] == 0){ // giro a sx se unica
printf("giro a sinistra");
maze[y][x] = 2;
y--;
}else{
printf("sono in trappola");
maze[y][x] = 2;
}
}else if (maze [y][x+1] != 0){ // provenienza da destra
printf("\nProvengo da destra ");
if(maze[y-1][x] == 0){ // giro a dx all'incrocio
printf("giro a destra");
maze[y][x] = 2;
y--;
}else if(maze[y][x-1] == 0){ // proseguo se dx è bloccato
printf("tiro dritto!");
maze[y][x] = 2;
x--;
}else if(maze[y+1][x] == 0){ // giro a sx se unica
printf("giro a sinistra");
maze[y][x] = 2;
y++;
}else{
printf("sono in trappola");
maze[y][x] = 2;
}
}else if (maze [y-1][x] != 0){ // provenienza da sopra
// casi in cui giro a dx
printf("\nProvengo da su ");
if(maze[y][x-1] == 0) { // giro a dx se tutto libero
printf("giro a destra");
maze[y][x] = 2;
x--;
// casi in cui vado dritto
}else if(maze[y+1][x] == 0){ // proseguo se dx è bloccato
printf("tiro dritto!");
maze[y][x] = 2;
y++;
// casi in cui giro a sx
}else if(maze[y][x+1] == 0){ // giro a sx se unica
printf("giro a sinistra");
maze[y][x] = 2;
x++;
}else{
printf("sono in trappola");
maze[y][x] = 2;
}
}else if(maze[y+1][x] != 0){ // provengo dal basso
printf("\nProvengo da giu ");
// tutto libero giro a dx
if(maze[y][x+1] == 0 ) {
printf("giro a destra");
maze[y][x] = 2;
x++;
}else if(maze[y-1][x] == 0 ){
printf("tiro dritto!");
maze[y][x] = 2;
y--;
}else if(maze[y][x-1] == 0){
printf("giro a sinistra");
maze[y][x] = 2;
x--;
}else{
printf("sono in trappola");
maze[y][x] = 2;
}
}
}
mazePrint(maze);
getchar();
if(x != xs || y != ys){
mazeTraverse(maze,y,x);
}else
return;
}
void mazeCreation(int maze[][12]){
int x, y;
for(x = 0; x <= size - 1; x++)
for(y = 0; y <= size - 1; y++)
maze[x][y] = rand() % 2;
}
|
C
|
#include <stdio.h>
#include <math.h>
char arr[2188][2188];
void Sirepinski(int length, int row_left, int col_left){
if (length == 1)
return;
for (int i = row_left + length / 3; i < (row_left + (length / 3) * 2); i++){
for (int j = col_left + length / 3; j < (col_left + (length / 3) * 2); j++)
arr[i][j] = '#';
}
Sirepinski(length / 3, row_left, col_left);
Sirepinski(length / 3, row_left, col_left + (length / 3));
Sirepinski(length / 3, row_left, col_left + (length / 3) * 2);
Sirepinski(length / 3, row_left + (length / 3), col_left);
Sirepinski(length / 3, row_left + (length / 3), col_left + (length / 3) * 2);
Sirepinski(length / 3, row_left + (length / 3) * 2, col_left);
Sirepinski(length / 3, row_left + (length / 3) * 2, col_left + (length / 3));
Sirepinski(length / 3, row_left + (length / 3) * 2, col_left + (length / 3) * 2);
}
int main(){
int n; scanf("%d", &n);
int power = pow(3, n);
for (int i = 1; i <= power; i++){
for (int j = 1; j <= power; j++)
arr[i][j] = '.';
}
Sirepinski(power, 1, 1);
for (int i = 1; i <= power; i++){
for (int j = 1; j <= power; j++)
printf("%c", arr[i][j]);
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<cs50.h>
int main(void)
{
string name;
int age;
name=get_string("Enter your name:");
age=get_int("Enter age");
for(int i=0;i<=age;i++){
printf(",");
for(int j=0;j=i+1;j++)
printf("|");
}
}
|
C
|
// - ------------------------------------------------------------------------------------------ - //
// Directory - File Name tree cataloging library //
// - ------------------------------------------------------------------------------------------ - //
#ifndef __Library_GELCore_GelDirectory_File_H__
#define __Library_GELCore_GelDirectory_File_H__
// - ------------------------------------------------------------------------------------------ - //
#include <Lib/GelFile/GelFile.h>
#include <Lib/GelVFile/GelVFile.h>
#include "GelDirectory_Core.h"
// - ------------------------------------------------------------------------------------------ - //
// Directories are lists of file names. They can be populated manually, or be polled from disk
// and other sources. The next step up from a Directory is an Archive, which contains data too.
//
// TODO: When indexing a string, consider attaching the name (BaseName/) to the front.
// TODO: Searching for a file (given a pattern to match)
// TODO: Saving and loading Directories to and from disk/streams. (Need FILE* library)
// - ------------------------------------------------------------------------------------------ - //
// - ------------------------------------------------------------------------------------------ - //
// Use this alternative "new" function when you don't know how big a file is //
// - ------------------------------------------------------------------------------------------ - //
inline GelDirectory* new_GelDirectory( GelFile* fp ) {
GelDirectory* p = new GelDirectory;
p->BaseName = new_String( fp );
p->FileName = new_GelHeap( fp );
// Return data //
return p;
}
// - ------------------------------------------------------------------------------------------ - //
inline GelDirectory* new_GelDirectory( GelVFile* fp ) {
GelDirectory* p = new GelDirectory;
p->BaseName = new_String( fp );
p->FileName = new_GelHeap( fp );
// Return data //
return p;
}
// - ------------------------------------------------------------------------------------------ - //
inline GelDirectory* read_GelDirectory( GelFile* fp ) {
return new_GelDirectory( fp );
}
// - ------------------------------------------------------------------------------------------ - //
inline GelDirectory* read_GelDirectory( GelVFile* fp ) {
return new_GelDirectory( fp );
}
// - ------------------------------------------------------------------------------------------ - //
// - ------------------------------------------------------------------------------------------ - //
// This is our "new_GelDirectory" that takes a file. We can't use new, because it's taken up by //
// UnixDir's "new_GelDirectory" call. It takes a string and poll's that from disk. //
// - ------------------------------------------------------------------------------------------ - //
inline GelDirectory* read_GelDirectory( const char* _FileName ) {
// Open File //
GelFile* fp = open_readonly_GelFile( _FileName );
if ( fp == 0 ) {
return 0;
}
// GelDirectory is too complicated a type to rely on the file size alone, so we need to read //
// and write a stored GelHeap in much the same way as we would to a FILE*. //
GelDirectory* p = new GelDirectory;
p->BaseName = new_String( fp );
p->FileName = new_GelHeap( fp );
// Close file //
close_GelFile( fp );
// Return data //
return p;
}
// - ------------------------------------------------------------------------------------------ - //
// - ------------------------------------------------------------------------------------------ - //
// This function is only so useful, as it relys on the arrays being correctly allocated //
inline const size_t read_GelDirectory( GelDirectory* p, const char* _FileName ) {
// Open File //
GelFile* fp = open_readonly_GelFile( _FileName );
if ( fp == 0 ) {
return 0;
}
size_t BytesRead = read_String( p->BaseName, fp );
BytesRead += read_GelHeap( p->FileName, fp );
// Close file //
close_GelFile( fp );
// Return the number of bytes read //
return BytesRead;
}
// - ------------------------------------------------------------------------------------------ - //
inline const size_t write_GelDirectory( const GelDirectory* p, const char* _FileName ) {
// Open File //
GelFile* fp = open_writeonly_GelFile( _FileName );
if ( fp == 0 ) {
return 0;
}
size_t BytesWritten = write_String( p->BaseName, fp );
BytesWritten += write_GelHeap( p->FileName, fp );
// TODO: Assert on fire write error //
// Close file //
close_GelFile( fp );
// Return the number of bytes read //
return BytesWritten;
}
// - ------------------------------------------------------------------------------------------ - //
// For syntactical compatability, read_GelHeap which functions the same as new_GelHeap. //
// Note: This is bad, as it's unclear allocation is done. new_GelHeap() is preferred. //
// - ------------------------------------------------------------------------------------------ - //
//inline GelHeap* read_GelHeap( const char* _FileName ) {
// return new_GelHeap( _FileName );
//}
// - ------------------------------------------------------------------------------------------ - //
// - ------------------------------------------------------------------------------------------ - //
// This function is only so useful, as it rely's on the arrays being correctly allocated //
inline const size_t read_GelDirectory( GelDirectory* p, GelFile* fp ) {
size_t BytesRead = read_String( p->BaseName, fp );
BytesRead += read_GelHeap( p->FileName, fp );
// TODO: If I happen to only read some of the file, less than Size, that would be bad. //
// Return the number of bytes read //
return BytesRead;
}
// - ------------------------------------------------------------------------------------------ - //
inline const size_t write_GelDirectory( const GelDirectory* p, GelFile* fp ) {
size_t BytesWritten = write_String( p->BaseName, fp );
BytesWritten += write_GelHeap( p->FileName, fp );
// TODO: Assert on fire write error //
// Return the number of bytes read //
return BytesWritten;
}
// - ------------------------------------------------------------------------------------------ - //
// - ------------------------------------------------------------------------------------------ - //
// This function is only so useful, as it rely's on the arrays being correctly allocated //
inline const size_t read_GelDirectory( GelDirectory* p, GelVFile* fp ) {
size_t BytesRead = read_String( p->BaseName, fp );
BytesRead += read_GelHeap( p->FileName, fp );
// TODO: If I happen to only read some of the file, less than Size, that would be bad. //
// Return the number of bytes read //
return BytesRead;
}
// - ------------------------------------------------------------------------------------------ - //
inline const size_t write_GelDirectory( const GelDirectory* p, GelVFile* fp ) {
size_t BytesWritten = write_String( p->BaseName, fp );
BytesWritten += write_GelHeap( p->FileName, fp );
// TODO: Assert on fire write error //
// Return the number of bytes read //
return BytesWritten;
}
// - ------------------------------------------------------------------------------------------ - //
// - ------------------------------------------------------------------------------------------ - //
#endif // __Library_Data_GelDirectory_File_H__ //
// - ------------------------------------------------------------------------------------------ - //
|
C
|
// Linked List (Insert element at beginning of the word)!
// head is global variable
#include <stdio.h>
#include "stdlib.h"
struct Node{
int data;
struct Node* next;
};
struct Node* head; // Global Variable
void Insert(int x);
void Print();
int main() {
head = NULL;
printf("Linked List (Insert element at beginning of the word)!\n");
printf("struct size=%d\n", sizeof(head));
printf("How many Numbers? \n");
int i, n, x;
scanf("%d", &n);
for ( i = 0; i < n; ++i) {
printf("Enter the numbers \n");
scanf("%d", &x);
Insert(x);
Print();
}
return 0;
}
void Insert(int x)
{
// Look at the fig 6-LinkedListAlgorithm(InsertingAtBeginning).png to Understand the concept behind
struct Node *temp;
temp = (struct Node*) malloc(sizeof(struct Node)); // Address get from Heap
temp->data = x; // or *temp.data = 2
temp->next = head; // Old address
head = temp ; // New address from heap
}
void Print()
{
struct Node * temp;
temp = head; // we do not lose head info so we create temp
printf("List is: ");
while (temp != NULL) // Traversal temp = 200
{
if(temp->next != NULL)
printf(" %d|%d --->", temp->data, temp->next); // 1 | 300
else
printf(" %d|%d", temp->data, temp->next); // 1 | 300
temp = temp->next; // 300
}
printf("\n");
}
/**
// head is Local variable
#include <stdio.h>
#include "stdlib.h"
struct Node{
int data;
struct Node* next;
};
struct Node* Insert(int x, struct Node* head);
void Print();
int main() {
struct Node* head; // Local Variable
head = NULL;
printf("Linked List (Insert element at beginning of the word)!\n");
printf("struct size=%d\n", sizeof(head));
printf("How many Numbers? \n");
int i, n, x;
scanf("%d", &n);
for ( i = 0; i < n; ++i) {
printf("Enter the numbers \n");
scanf("%d", &x);
head = Insert(x, head);
Print(head);
}
return 0;
}
struct Node* Insert(int x, struct Node* head)
{
// Look at the fig 6-LinkedListAlgorithm(InsertingAtBeginning).png to Understand the concept behind
struct Node *temp;
temp = (struct Node*) malloc(sizeof(struct Node)); // Address get from Heap
temp->data = x; // or *temp.data = 2
temp->next = head; // Old head
head = temp ; // New address from heap
return head;
}
void Print(struct Node* head)
{
// struct Node * temp; Not using temp variable here because head is passed as Arg
// temp = head; // we do nor lose head info so we create temp
printf("List is: ");
while (head != NULL) // Traversal head = 200
{
printf(" %d|%d --->", head->data, head->next); // 1 | 300
head = head->next; // 300
}
printf("\n");
}
*/
|
C
|
#include <stdio.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
printf("After Swapping (within function) %d %d\n", *x, *y);
}
int main()
{
int x = 10, y = 20;
printf("Before Swapping (Main) %d %d\n", x, y);
swap(&x, &y);
printf("After Swapping (Main) %d %d\n", x, y);
return 0;
}
|
C
|
/*************************************************************************
> File Name: B.c
> Author: Li Meng
> Mail: ldx19980108@gmail.com
> Created Time: 2018年08月06日 星期一 10时05分54秒
************************************************************************/
#include<stdio.h>
#include<string.h>
int main(void){
int n;
int dp[32768];
memset(&dp, 0, sizeof(dp));
dp[0] = 1;
for(int i = 1;i <= 3;i++)
for(int j = i;j < 32768; j++)
dp[j] += dp[j - i];
while(scanf("%d",&n) != EOF)
printf("%d\n",dp[n]);
return 0;
}
|
C
|
/*
* SnakeMain.c
*
* Created: 2/2/2018 4:07:53 PM
* Author: Kumar Kartikeya
*/
#include <util/delay.h>
#include <avr/io.h>
#include <stdlib.h>
#include "LCD_4bit.h"
#include <string.h>`
#include <avr/interrupt.h>
#define rButton PIND3 //Right turn button at pin 3
#define lButton PIND2 //Left turn button at 2
int foodx , foody; // Food coordinates
int headx, heady; // Head coordinates
int length = 3;
unsigned int size; // Length of snake
uint8_t arr[8] = { //Snake state matrix
0b11111000,
0b11111111,
0b11111111,
0b11111111,
0b11111111,
0b11111111,
0b11111111,
0b11111111
};
uint8_t foodArr[8] ={ //Food state matrix
0b11111111,
0b11111111,
0b11111111,
0b11111111,
0b11111111,
0b11111111,
0b11111111,
0b11111111
} ;
typedef enum { //Creating direction as an enum
right, // 0 for right
down, // 1 for down
left, // 2 for left
up // 3 for up
}direction;
typedef enum{ //Creating boolean datatype
false,
true
}bool;
bool buttonFlag = true;
typedef struct{ //Creating a struct for a single segment of snake
int x;
int y; //Coordinates
struct segment *c; //Pointer
}segment;
direction facing = up;
segment snake[64] ={ // Initializing array of snake segments with initially 3 segments
0,0, &(snake[1]),
0,1, &(snake[2]),
0,2, NULL
};
headx = 0;
heady = 2;
void gameOver(){ //Turn ON all LEDs when game over
int j = 0;
for(j = 0 ; j < 8; j++){
arr[j] = 0b00000000;
foodArr[j] = 0b00000000;
LCD_Disp("Game Over.");
}
}
void moveSnake(void){
int newx = headx;
int newy = heady;
buttonFlag = 1;
switch(facing){ // setting coordinates of next head position
case 0:
newx += 1;
break;
case 1:
newy -= 1;
break;
case 2:
newx -= 1;
break;
case 3:
newy += 1;
break;
}
segment newHeadPosition = {newx, newy, NULL}; // making the new head
arr[newx] &= ~(1<<newy);
segment oldHead = {.x = headx, .y = heady, &(newHeadPosition)}; // Putting old head as new second segment
arr[snake[0].x] |= (1 << snake[0].y);
snake[length-1] = oldHead;
for(int i = 0;i < length-1; i++){
snake[i] = snake[i+1];
}
snake[length-1] = newHeadPosition;
headx = newx;
heady = newy;
if(headx > 7 || headx < 0 || heady > 7 || heady < 0){
gameOver();
}
int k = 0;
for(k = 0; k < length-1; k++){
if((headx == snake[k].x) && (heady == snake[k].y)){
gameOver();
}
}
}
void displayFood(){
PORTB |= (1 << foodx);
PORTA = (foodArr[foodx]);
_delay_us(60);
PORTA = 0xff;
PORTB &= ~(1 << foodx);
}
void generateFood(){
foodArr[foodx] |= (1 << foody);
int temp1, temp2;
temp1 = (rand())%8;
foodx = temp1;
temp2 = (rand()%8);
foody = temp2;
foodArr[foodx] &= ~( 1<<foody );
}
void addSegment(){
int newx = headx;
int newy = heady;
buttonFlag = 1;
switch(facing){ // setting coordinates of next head position
case 0:
newx += 1;
break;
case 1:
newy -= 1;
break;
case 2:
newx -= 1;
break;
case 3:
newy += 1;
break;
}
segment newHead = {newx, newy, NULL};
segment oldHead = {.x = headx, .y = heady, &(newHead)};
snake[length-1] = oldHead;
snake[length] = newHead;
headx = newx;
heady = newy;
arr[newx] &= ~(1<<newy);
arr[snake[0].x] |= (1 << snake[0].y);
length++;
LCD_setCursor(9,1);
LCD_printScore((length-3));
}
LCD_setup(){
LCD_Init();
LCD_setCursor(0, 0);
LCD_Disp("Snake hsss~");
LCD_setCursor(1,1);
LCD_Disp("Score: ");
LCD_setCursor(11,1);
LCD_Disp(" ");
}
ISR(INT0_vect){
if(facing == up){
facing = right;
}else{
facing++; // Change direction clockwise
}
_delay_ms(50);
}
ISR(INT1_vect){
if(facing == right){
facing = up;
}else{
facing--; // Change direction anticlockwise
}
_delay_ms(50);
}
int main(void)
{
DDRA = 0b11111111; //Ground pins set to OUTPUT
DDRB = 0b11111111; //Red pins set to OUTPUT
DDRC = 0b11111111; //Green pins set to OUTPUT
DDRD = 0b11001111; //Set first 6 pins for LCD and last two for buttons
PORTD |= (1 << rButton);
PORTD |= (1 << lButton);
PORTA = 0b11111111;
PORTB = 0b00000000;
GICR |= 1<<INT0;
GICR |= 1<<INT1;
LCD_setup();
LCD_setCursor(9,1);
LCD_printScore((length-3));
generateFood();
int count = 0;
sei();
while(1)
{
if(count >= 600){
moveSnake();
if(foodx == headx && foody == heady){
addSegment();
generateFood();
}
count = 0;
}
count++;
for(int i = 0; i < 8; i++){ //Printing Matrix on 8*8 LED Display
PORTC |= (1 << i);
PORTA = (arr[i]);
_delay_us(60);
PORTA = 0xff;
PORTC &= ~(1 << i);
}
displayFood();
}
}
|
C
|
/**************************************************\
* Display ANSI Color Schemes with Space Invaders *
* Inspired by a bash script by pfh and lolilolicon *
* Sam Stuewe (C) 2014 Licensed under the terms of *
* the GNU Public License version 2 *
\**************************************************/
// Includes //
#include <stdio.h> // printf()
#include <stdlib.h> // EXIT_SUCCESS
#include "ansicolor.h" // ANSI escapes
// Main Function //
signed
main (void) {
/* Top Row Invaders */
printf(ANSI_FG_BLACK " ▀▄ ▄▀ "
ANSI_FG_RED " ▄▄▄████▄▄▄ "
ANSI_FG_GREEN " ▄██▄ "
ANSI_FG_YELLOW " ▀▄ ▄▀ "
ANSI_FG_BLUE " ▄▄▄████▄▄▄ "
ANSI_FG_MAGENTA " ▄██▄ "
ANSI_FG_CYAN " ▀▄ ▄▀ \n"
ANSI_FG_BLACK " ▄█▀███▀█▄ "
ANSI_FG_RED " ███▀▀██▀▀███ "
ANSI_FG_GREEN " ▄█▀██▀█▄ "
ANSI_FG_YELLOW " ▄█▀███▀█▄ "
ANSI_FG_BLUE " ███▀▀██▀▀███ "
ANSI_FG_MAGENTA " ▄█▀██▀█▄ "
ANSI_FG_CYAN " ▄█▀███▀█▄ \n"
ANSI_FG_BLACK "█▀███████▀█ "
ANSI_FG_RED " ▀▀███▀▀███▀▀ "
ANSI_FG_GREEN " ▀█▀██▀█▀ "
ANSI_FG_YELLOW " █▀███████▀█ "
ANSI_FG_BLUE " ▀▀███▀▀███▀▀ "
ANSI_FG_MAGENTA " ▀█▀██▀█▀ "
ANSI_FG_CYAN " █▀███████▀█ \n"
ANSI_FG_BLACK "▀ ▀▄▄ ▄▄▀ ▀ "
ANSI_FG_RED " ▀█▄ ▀▀ ▄█▀ "
ANSI_FG_GREEN " ▀▄ ▄▀ "
ANSI_FG_YELLOW " ▀ ▀▄▄ ▄▄▀ ▀ "
ANSI_FG_BLUE " ▀█▄ ▀▀ ▄█▀ "
ANSI_FG_MAGENTA " ▀▄ ▄▀ "
ANSI_FG_CYAN " ▀ ▀▄▄ ▄▄▀ ▀ \n"
ANSI_BOLD_ON "\n"
/* Bottom Row Invaders */
ANSI_FG_BLACK "▄ ▀▄ ▄▀ ▄ "
ANSI_FG_RED " ▄▄▄████▄▄▄ "
ANSI_FG_GREEN " ▄██▄ "
ANSI_FG_YELLOW " ▄ ▀▄ ▄▀ ▄ "
ANSI_FG_BLUE " ▄▄▄████▄▄▄ "
ANSI_FG_MAGENTA " ▄██▄ "
ANSI_FG_CYAN " ▄ ▀▄ ▄▀ ▄ \n"
ANSI_FG_BLACK "█▄█▀███▀█▄█ "
ANSI_FG_RED " ███▀▀██▀▀███ "
ANSI_FG_GREEN " ▄█▀██▀█▄ "
ANSI_FG_YELLOW " █▄█▀███▀█▄█ "
ANSI_FG_BLUE " ███▀▀██▀▀███ "
ANSI_FG_MAGENTA " ▄█▀██▀█▄ "
ANSI_FG_CYAN " █▄█▀███▀█▄█ \n"
ANSI_FG_BLACK "▀█████████▀ "
ANSI_FG_RED " ▀▀▀██▀▀██▀▀▀ "
ANSI_FG_GREEN " ▀▀█▀▀█▀▀ "
ANSI_FG_YELLOW " ▀█████████▀ "
ANSI_FG_BLUE " ▀▀▀██▀▀██▀▀▀ "
ANSI_FG_MAGENTA " ▀▀█▀▀█▀▀ "
ANSI_FG_CYAN " ▀█████████▀ \n"
ANSI_FG_BLACK " ▄▀ ▀▄ "
ANSI_FG_RED " ▄▄▀▀ ▀▀ ▀▀▄▄ "
ANSI_FG_GREEN " ▄▀▄▀▀▄▀▄ "
ANSI_FG_YELLOW " ▄▀ ▀▄ "
ANSI_FG_BLUE " ▄▄▀▀ ▀▀ ▀▀▄▄ "
ANSI_FG_MAGENTA " ▄▀▄▀▀▄▀▄ "
ANSI_FG_CYAN " ▄▀ ▀▄ \n"
ANSI_RESET "\n"
/* Defender's Tank */
"\t\t\t\t\t ▌\n\n"
"\t\t\t\t\t▌\n\n"
"\t\t\t\t ▄█▄\n"
"\t\t\t\t ▄█████████▄\n"
"\t\t\t\t ▀▀▀▀▀▀▀▀▀▀▀\n");
return EXIT_SUCCESS;
}
// vim: set ts=4 sw=4 et:
|
C
|
#define _ISOC99_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <ctype.h>
#include <errno.h>
#include "bzseek.h"
void usage(const char* progname){
const char msg[] = {
"\n"
"Usage: \n"
"%s <file.bz2> [-i indexfile] -g\n"
" -- generate an index for the bzip2 <file.bz2>\n"
"%s <file.bz2> [-i indexfile] <start> <len>\n"
" -- read <len> bytes starting at <start> from an indexed file\n"
" <start> and <len> may be decimal, 0xhex or 0oct\n"
};
fprintf(stderr, msg, progname, progname);
exit(1);
}
void describe(const char* prog, const char* msg, bzseek_err err){
if (err == BZSEEK_IO_ERR){
fprintf(stderr, "%s: ", prog);
perror(msg);
}else if (err != BZSEEK_OK){
fprintf(stderr, "%s: %s: %s\n", prog, msg, bzseek_errmsg(err));
}
}
int do_build(const char* prog, const char* filename, const char* index){
bzseek_err err = bzseek_build_index(filename, index);
if (err){
describe(prog, "building index", err);
return 1;
}else{
return 0;
}
}
#define BUFFER_SIZE 1024
int do_read(const char* prog, const char* filename, const char* index, uint64_t start, unsigned int len){
char buf[BUFFER_SIZE];
bzseek_err err;
bzseek_file f;
err = bzseek_open(&f, filename, index);
if (err){describe(prog, "opening file", err); return 1;}
while (len > 0){
int l = len > BUFFER_SIZE ? BUFFER_SIZE : len;
err = bzseek_read(&f, start, l, buf);
if (err){
if (err == BZSEEK_EOF){
fprintf(stderr, "%s: Warning: End-of-file reached during read.\n", prog);
l = len = (int)(bzseek_len(&f) - start);
}else{
describe(prog, "reading", err);
return 1;
}
}
fwrite(buf, 1, l, stdout);
len -= l;
start += l;
}
return 0;
}
int main(int argc, char* argv[]){
char* indexfile = NULL;
struct option longopts[] = {
{"index", 1, NULL, 'i'},
{"generate", 0, NULL, 'g'},
{0,0,0,0}
};
int c;
int mode = 0;
char* opts[3];
int nopts = 0;
while ((c = getopt_long(argc, argv, "-gi:", longopts, NULL)) != -1){
switch (c){
case 1:
if (nopts < 3) opts[nopts++] = optarg;
break;
case 'i':
indexfile = optarg;
break;
case 'g':
mode = 1;
break;
case '?':
if (optopt == 'i')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
usage(argv[0]);
break;
default:
fprintf(stderr, "Error parsing options\n");
usage(argv[0]);
}
}
if (mode == 0){
if (nopts != 3){
fprintf(stderr, "Missing arguments\n");
usage(argv[0]);
}
char* filename = opts[0];
uint64_t start;
unsigned int len;
char* endptr;
start = strtoull(opts[1], &endptr, 0);
if (*endptr != '\0'){
fprintf(stderr, "Can't parse %s as a starting position\n", opts[1]);
usage(argv[0]);
}
len = strtoul(opts[2], &endptr, 0);
if (*endptr != '\0'){
fprintf(stderr, "Can't parse %s as a length\n", opts[2]);
usage(argv[0]);
}
return do_read(argv[0], filename, indexfile, start, len);
}else{
if (nopts < 1){
fprintf(stderr, "Missing filename\n");
usage(argv[0]);
}else if (nopts > 1){
fprintf(stderr, "Unexpected options\n");
usage(argv[0]);
}
const char* filename = opts[0];
return do_build(argv[0], filename, indexfile);
}
}
|
C
|
/*
* knn.c
*
* Created on: Dec 7, 2020
* Author: Samuel
*/
#include "knn.h"
uint16_t knn(float* test_d, float* train_d, uint16_t* train_l){
float distance[40];
float innersum = 0.0f;
// Calculate the distance to each point
for (uint16_t i = 0; i < train_size; i++)
{
innersum = 0.0f;
for (uint16_t j = 0; j < mel_len; j++)
{
innersum += (test_d[j] - train_d[i*mel_len + j]) * (test_d[j] - train_d[i*mel_len + j]);
}
distance[i] = sqrtf(innersum);
}
Led6 = 0;
// Sort distance smallest to largest value
uint16_t already_sorted = 0;
float temp = 0.0f;
uint16_t templ = 0;
for (uint16_t i = 0; i < train_size; i++)
{
already_sorted = 1;
for (uint16_t j = 0; j < (train_size - i - 1); j++)
{
if (distance[j] > distance[j+1])
{
temp = distance[j];
distance[j] = distance[j+1];
distance[j+1] = temp;
templ = train_l[j];
train_l[j] = train_l[j+1];
train_l[j+1] = templ;
}
}
if (already_sorted)
break;
}
Led7 = 0;
int16_t vote = 0;
if (train_l[0]){
vote++;
}
else{
vote--;
}
if (train_l[1]){
vote++;
}
else{
vote--;
}
if (train_l[2]){
vote++;
}
else{
vote--;
}
if (vote > 0){
return 1;
}
else{
return 0;
}
}
|
C
|
#include <stdio.h>
#define LENGTH 3
int data[LENGTH]; // some integers
int main(int argc, char **argv) {
int *pi = NULL; // a simple pointer to an integer
int **ppi = NULL; // a pointer to a pointer to an integer
int i = 0;
printf("Multiple Indirection example\n");
// initialize our integer array
for (i = 0; i < LENGTH; i++) {
data[i] = i;
}
// print the array
for (i = 0; i < LENGTH; i++) {
printf("data[%d] = %d\n", i, data[i]);
}
// A: Simple pointer to a pointer to an integer
pi = data; // set the pointer to start of integer array
ppi = π // and set the pointer to pointer to address of pi
for (i = 0; i < LENGTH; i++) {
printf("\naddress of data[%d] is %p\n", i, &data[i]);
printf("item pointed to by pi is %d\n", *pi);
printf("item pointed to by ppi is %p (address of pi %p)\n", *ppi, &pi);
printf("item pointed to by double indrection of ppi is %d\n", **ppi);
printf("value of pi is %p and value pointed by pi is %d\n", pi, *pi);
printf("The address of pi is %p and the value of ppi (what it points to) is %p \n\n", &pi, ppi);
pi += 1; // advance the pointer to point to next element of the data array
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
// FUNCTION PRINT
void print(char *c)
{
while(*c)
{
printf("%c",*c);
c++;
}
printf("\n");
}
// FUNCTION
// FUNCTION THING
void thing(FILE *fp)
{
int i=0,j;
int loc=0;
char buffer[200],c;
c = getc(fp);
int sp=0;
int cm=0;
char fn[100];
while(c!= EOF)
{
if(c=='/')
{
cm=cm+1;
}
while(c!='\n')
{
buffer[i]=c;
i++;
c = getc(fp);
}
if(getc(fp)=='\n')
sp=sp+1;
buffer[i] = '\0';
for (j=0;j<i;j++)
{
}
i=0;
loc++;
c = getc(fp);
}
loc=loc-sp-cm;
printf("no. of lines of code is %d ",++loc);
}
// FUNCTION
// FUNCTION MAIN
int main()
{
FILE *fp;
char fileName[30];
printf("File name: ");
scanf("%s",fileName);
fp = fopen(fileName,"r");
thing(fp);
printf("\n");
}
// FUNCTION
|
C
|
/* This example was presented at the CNC'2 summer school on MPFR and MPC at
* LORIA, Nancy, France. It shows how one can use different rounding modes.
* This example implements the OddRoundedAdd algorithm, which returns the
* sum z = x + y rounded-to-odd:
* * RO(z) = z if z is exactly representable;
* * otherwise RO(z) is the value among RD(z) and RU(z) whose
* least significant bit is a one.
*/
/*
Copyright 2009-2019 Free Software Foundation, Inc.
Contributed by the AriC and Caramba projects, INRIA.
This file is part of the GNU MPFR Library.
The GNU MPFR Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
The GNU MPFR 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 Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see
https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <mpfr.h>
#define LIST x, y, d, u, e, z
int main (int argc, char **argv)
{
mpfr_t LIST;
mpfr_prec_t prec;
int pprec; /* will be prec - 1 for mpfr_printf */
if (argc != 4)
{
fprintf (stderr, "Usage: rndo-add <prec> <x> <y>\n");
exit (1);
}
prec = atoi (argv[1]);
if (prec < 2)
{
fprintf (stderr, "rndo-add: bad precision\n");
exit (1);
}
pprec = prec - 1;
mpfr_inits2 (prec, LIST, (mpfr_ptr) 0);
if (mpfr_set_str (x, argv[2], 0, MPFR_RNDN))
{
fprintf (stderr, "rndo-add: bad x value\n");
exit (1);
}
mpfr_printf ("x = %.*Rb\n", pprec, x);
if (mpfr_set_str (y, argv[3], 0, MPFR_RNDN))
{
fprintf (stderr, "rndo-add: bad y value\n");
exit (1);
}
mpfr_printf ("y = %.*Rb\n", pprec, y);
mpfr_add (d, x, y, MPFR_RNDD);
mpfr_printf ("d = %.*Rb\n", pprec, d);
mpfr_add (u, x, y, MPFR_RNDU);
mpfr_printf ("u = %.*Rb\n", pprec, u);
mpfr_add (e, d, u, MPFR_RNDN);
mpfr_div_2ui (e, e, 1, MPFR_RNDN);
mpfr_printf ("e = %.*Rb\n", pprec, e);
mpfr_sub (z, u, e, MPFR_RNDN);
mpfr_add (z, z, d, MPFR_RNDN);
mpfr_printf ("z = %.*Rb\n", pprec, z);
mpfr_clears (LIST, (mpfr_ptr) 0);
mpfr_free_cache ();
return 0;
}
|
C
|
/*
#include <stdio.h>
void modify(int *ptr)
{
*ptr = 99;
}
int main(void) {
int number = 1;
modify(&number);
printf("number = %d \n", number);
return 0;
}
*/
|
C
|
/*
* ENCE260 GAME: BATTLESHIPS
* @authors: Logan Beard
* & Jen Lowe
* @date: 17/10/17
* @brief: Graphics module for battleships game
* */
#include "tinygl.h"
#include "font.h"
#include "../fonts/font3x5_1.h"
#include "pacer.h"
#define NUM_FLASHES 3
#define NUM_FLASHES_WIN 5
#define FLASH_TOTAL_DURATION 60
#define FLASH_ON_DURATION (FLASH_TOTAL_DURATION / 2)
#define HIT_MESSAGE_TICK_LENGTH 1030
#define MISS_MESSAGE_TICK_LENGH 1250
#define MAX_X_COORD 4
#define MAX_Y_COORD 6
#define NUM_ROWS 5
#define NUM_COLS 7
#define HIT_MISS_TEXT_SPEED 30
#define WIN_LOSE_TEXT_SPEED 20
typedef struct ship_struct
//struct for ship which containts the start and end x/y coordinates
{
int length;
int xstart;
int ystart;
int xend;
int yend;
} Ship;
/*display known hits/misses from other persons board based on values
* in 'visible' board matrix. 'on_or_off' parameter dictates whether
* flashing light is on (1) or off (0) */
void draw_visible(int visible[][NUM_COLS], int on_or_off);
/*display ships that have already been placed */
void display_placed(Ship ship2, Ship ship3, Ship ship4, int ship);
/*display either hit or miss message based on 'hit' parameter
* where a hit is represented by hit=1, miss is hit=0 */
void display_hit_miss(int hit, int x, int y);
/*display either win or lose message based on 'win' parameter
* which is set to 1 for a win and 0 for a loss */
void display_win_lose(int win);
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* queue.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: slyazid <slyazid@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/21 15:24:47 by slyazid #+# #+# */
/* Updated: 2019/12/02 06:35:29 by slyazid ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
t_queue *new_node(t_room *room)
{
t_queue *new;
new = (t_queue*)malloc(sizeof(t_queue));
new->rooms = room;
new->next = NULL;
new->prec = NULL;
return (new);
}
/*
** add to queue and set the new head;
*/
void enqueue(t_htqueue **queue, t_room *room)
{
t_queue *new;
new = new_node(room);
if (!(*queue)->head)
{
(*queue)->head = new;
(*queue)->tail = new;
return ;
}
new->prec = (*queue)->tail;
(*queue)->tail->next = new;
(*queue)->tail = new;
}
/*
** dequeue from tail; and free the dequeued :3 + update the queue;
*/
void dequeue(t_htqueue **queue)
{
t_queue *head;
head = NULL;
if (!(*queue)->head)
return ;
head = (*queue)->head;
(*queue)->head = ((*queue)->head->next) ? (*queue)->head->next : NULL;
head ? free(head) : 0;
}
void unvisit(t_htqueue **queue)
{
t_queue *tmp;
tmp = (*queue)->head;
while (tmp)
{
tmp->rooms->visited = 0;
tmp->rooms->visit_group = 0;
dequeue(queue);
tmp = (*queue)->head;
}
free(tmp);
}
|
C
|
#include <stdio.h>
int main () {
int i,j;
int Matrix[3][3];
printf("Enter The Values Of A 3X3 Matrix:");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
scanf("%d",&Matrix[i][j]);
}
}
printf("\nThe Matrix Is:");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++){
printf("\t%d",Matrix[i][j]);
}
}
return 0;
}
|
C
|
/* atexit example */
#include "tests.h"
#include <stdio.h>
#include <stdlib.h> /* atexit */
int r_value = 3;
void fnExit1(void)
{
r_value += 2;
}
void fnExit2(void)
{
r_value *= 5;
}
void done(void)
{
printf("%d\n", r_value);
}
int main()
{
plan(0);
atexit(done);
atexit(fnExit1);
atexit(fnExit2);
done_testing();
}
|
C
|
#include "quad_math.h"
/**
* @brief fast rsqrt
* @param number
* @retval y
*/
float Q_rsqrt(float number)
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) );
return y;
}
/**
* @brief fast abs
* @param None
* @retval None
*/
float FL_ABS(float x)
{
if(x < 0) return -x;
else return x;
}
void Limit(int16_t *data,int16_t limit)
{
if(*data<-limit)
{
*data=-limit;
return;
}
if(*data>limit)
{
*data=limit;
return;
}
}
void Limitf(float *data,float limit)
{
if(*data<-limit)
{
*data=-limit;
return;
}
if(*data>limit)
{
*data=limit;
return;
}
}
void Limit_t2(int16_t *data,int16_t limit_low,int16_t limit_up)
{
if(*data<limit_low)
{
*data=limit_low;
return;
}
if(*data>limit_up)
{
*data=limit_up;
return;
}
}
/**
* @brief Constraint float data
* @param a lower upper
* @retval a result
*/
float Constraint_f(float a , float lower , float upper)
{
if (a >= upper)
a = upper;
else if (a <= lower)
a = lower;
return (a);
}
/**
* @brief Constraint int data
* @param a lower upper
* @retval a result
*/
int32_t Constraint_int(int32_t a , int32_t lower , int32_t upper)
{
if (a >= upper)
return upper;
else if (a <= lower)
return lower;
else
return a;
}
/**
* @brief Low pass filter cutoff frequency 'a' (rad/s)
* @param new_data old_data a dt
* @retval result
*/
float DLPF(float new_data, float old_data, float a, float dt)
{
float aT = a * dt;
aT = Constraint_f(aT, 0.0f, 0.999f);
return ((1.0f - aT) * old_data + aT * new_data);
}
/**
* @brief Constraint a (-2PI,2PI)
* @param a
* @retval a
*/
float Warp_ToPI(float a)
{
while (a > PI)
a -= 2.0f * PI;
while (a < -PI)
a += 2.0f * PI;
return a;
}
float max(float a, float b)
{
if (a > b)
return a;
else
return b;
}
float min(float a, float b)
{
if (a < b)
return a;
else
return b;
}
|
C
|
/*
* srf02.c
*
* Created on: Jan 6, 2015
* Author: Iulian Gheorghiu <morgoth.creator@gmail.com>
*/
#include "stdbool.h"
#include "srf02.h"
#include "board_init.h"
#include "api/twi_api.h"
#include "api/timer_api.h"
#include "api/uart_api.h"
bool srf02_start(SRF02_t *structure, SRF02_COMMANDS command) {
if(structure->busy)
return true;
timer_interval(&structure->Timeout_Timer, 80);
structure->busy = true;
Twi_t* TwiStruct = structure->TWI;
unsigned char dev_addr = 0x70;
if(structure->addr)
dev_addr = structure->addr;
unsigned char tmp[2];
switch(command)
{
case SRF02_START_RANGING:
case SRF02_FAKE_RANGING:
tmp[0] = 0;
tmp[1] = command + structure->measure_unit;
if(twi.tx(TwiStruct, dev_addr, tmp, 2))
structure->reg_inst = command;
break;
default:
return false;
}
return true;
}
bool srf02_read(SRF02_t *structure) {
if(timer_tick(&structure->Timeout_Timer)) {
structure->busy = false;
return false;
}
if(!structure->busy)
return false;
Twi_t* TwiStruct = structure->TWI;
unsigned char dev_addr = 0x70;
if(structure->addr)
dev_addr = structure->addr;
unsigned char reg = 2;
unsigned char result[2];
switch(structure->reg_inst)
{
case SRF02_START_RANGING:
case SRF02_FAKE_RANGING:
if(!twi.trx(TwiStruct, dev_addr, ®, 1, result, 2))
return false;
else {
structure->range_value = result[0] << 8;
structure->range_value |= result[1];
return true;
}
break;
default:
return false;
}
return true;
}
void srf02_display_data(SRF02_t *structure) {
switch(structure->measure_unit)
{
case SRF02_INCH:
uart.printf(DebugCom, "SRF02: Range = %u inch\n\r", (unsigned long)structure->range_value);
break;
case SRF02_CENTIMETER:
uart.printf(DebugCom, "SRF02: Range = %u centimeters\n\r", (unsigned long)structure->range_value);
break;
case SRF02_MICROSECONDS:
uart.printf(DebugCom, "SRF02: Range = %u microseconds\n\r", (unsigned long)structure->range_value);
break;
}
}
|
C
|
#include "fs.h"
#include "debug.h"
#include "httpd.h"
#include <mem.h>
#include <spi_flash.h>
#define NODE_ADDR(i) \
((FS_SECTOR_START * FS_SECTOR_SIZE) + ((i) * FS_NODE_SIZE))
ICACHE_FLASH_ATTR
fs_err_t fs_format() {
fs_err_t err = FS_OK;
uint16_t s;
uint32_t *tmp = os_zalloc(FS_SECTOR_SIZE);
/* Erase sectors */
for (s = FS_SECTOR_START; s <= FS_FAT_SECTOR_LAST; s++) {
INFO("Erasing sector: 0X%03X", s);
err = spi_flash_erase_sector(s);
if (err != SPI_FLASH_RESULT_OK) {
ERROR("Canot erase sector: %d, err: %d\r\n", s, err);
err = FS_ERR_FAT_ERASE;
break;
}
err = spi_flash_write(s * FS_SECTOR_SIZE, tmp, FS_SECTOR_SIZE);
if (err != SPI_FLASH_RESULT_OK) {
ERROR("Canot write sector: %d, err: %d\r\n", s, err);
err = FS_ERR_FAT_ERASE;
break;
}
}
os_free(tmp);
return err;
}
static ICACHE_FLASH_ATTR
fs_err_t _node_iter(uint8_t filter, fs_node_cb_t cb, void *arg) {
fs_err_t err;
fs_err_t retval = FS_ERR_ITER_END;
uint16_t i;
uint32_t s;
struct fs_node *t = (struct fs_node *)os_zalloc(FS_SECTOR_SIZE);
struct fs_node *n;
for (s = FS_SECTOR_START; s <= FS_FAT_SECTOR_LAST; s++) {
/* Read sector: 0x%03X */
err = spi_flash_read(s * FS_SECTOR_SIZE, (uint32_t*)t, FS_SECTOR_SIZE);
if (err != SPI_FLASH_RESULT_OK) {
ERROR("Canot read sector: 0x%03X, err: %d", s, err);
retval = FS_ERR_FAT_ERASE;
break;
}
/* Loop over nodes */
for (i = 0; i < FS_NODES_PER_SECTOR; i++) {
n = t + i;
/* Filter: %d %d */
if ( !((n->flags & filter) || (n->flags == filter)) ) {
continue;
}
/* Calculate Id */
n->id = (FS_NODES_PER_SECTOR * (s - FS_SECTOR_START)) + i;
DEBUG("Sector: 0x%03X id: %3u flags: %u size :%u p: %p",
s, n->id, n->flags, n->size, n);
/* Callback: %d */
err = cb(n, arg);
/* Requested Next node */
if (err == FS_ERR_ITER_NEXT) {
continue;
}
if (err == FS_SAVE) {
CHK("Requested to save then break: id: %d flags: %d", n->id,
n->flags);
err = spi_flash_erase_sector(s);
if (err != SPI_FLASH_RESULT_OK) {
ERROR("Canot erase sector: %d, err: %d\r\n", s, err);
retval = FS_ERR_SECTOR_ERASE;
break;
}
if (spi_flash_write(s * FS_SECTOR_SIZE, (uint32_t*)t,
FS_SECTOR_SIZE)) {
retval = FS_ERR_WRITE_NODE;
break;
}
retval = FS_OK;
break;
}
retval = err;
break;
}
}
os_free(t);
return retval;
}
static ICACHE_FLASH_ATTR
fs_err_t _namematch_cb( struct fs_node *n, void *arg) {
struct fs_file *f = (struct fs_file*) arg;
if (os_strncmp(f->node.name, n->name, FS_FILENAME_MAX) == 0) {
/* found */
return FS_OK;
}
return FS_ERR_ITER_NEXT;
}
static ICACHE_FLASH_ATTR
fs_err_t _allocate_cb(struct fs_node *n, void *arg) {
struct fs_file *f = (struct fs_file*) arg;
os_memcpy(n->name, f->node.name, FS_FILENAME_MAX);
n->flags = FS_NODE_ALLOCATED;
n->size = 0;
n->nextid = n->id;
os_memcpy(&f->node, n, FS_NODE_SIZE);
/* Just return Save on the first occurance */
return FS_SAVE;
}
ICACHE_FLASH_ATTR
fs_err_t fs_new(struct fs_file *f) {
fs_err_t err;
err = _node_iter(FS_NODE_ALLOCATED, _namematch_cb, f);
CHK("iter err: %d", err);
if (err == FS_OK) {
return FS_ERR_FILE_EXISTS;
}
if (err != FS_ERR_ITER_END) {
return err;
}
/* loop over fat nodes to find a free node to store file. */
err = _node_iter(FS_NODE_FREE, _allocate_cb, f);
if (err) {
return FS_ERR_NOSPACE;
}
CHK("Free node found: id: %d", f->node.id);
return FS_OK;
}
ICACHE_FLASH_ATTR
fs_err_t fs_close(struct fs_file *f) {
return FS_OK;
}
static ICACHE_FLASH_ATTR
fs_err_t _node_replace_with_next(struct fs_node *n) {
uint16_t addr = FS_NODE_ADDR(n->nextid);
return spi_flash_read(addr, (uint32_t*)n, sizeof(struct fs_node));
}
static ICACHE_FLASH_ATTR
fs_err_t _node_replace_with_last(struct fs_node *n) {
fs_err_t err;
if (FS_NODE_IS_LAST(n)) {
return FS_OK;
}
err = _node_replace_with_next(n);
if (err) {
return err;
}
return _node_replace_with_last(n);
}
static ICACHE_FLASH_ATTR
fs_err_t _node_save(struct fs_node *n) {
fs_err_t err;
uint32_t sectaddr;
err = spi_flash_read(sectaddr, (uint32_t*)buff, FS_SECTOR_SIZE);
if (err) {
break;
}
f->node.size += rb_read(b, buff + (FS_SECTOR_SIZE - sectavail),
MIN(avail, sectavail));
err = spi_flash_erase_sector(sectaddr / FS_SECTOR_SIZE);
if (err) {
break;
}
err = spi_flash_write(sectaddr, (uint32_t*)buff, FS_SECTOR_SIZE);
if (err) {
break;
}
}
ICACHE_FLASH_ATTR
fs_err_t fs_rbwrite(struct fs_file *f, struct ringbuffer *b) {
fs_err_t err = FS_OK;
uint16_t avail;
uint16_t sectavail;
uint32_t sectaddr;
char *buff;
struct fs_node n;
buff = os_zalloc(FS_SECTOR_SIZE);
while (true) {
avail = RB_USED(b);
if (!avail) {
break;
}
os_memcpy(&n, &f->node, sizeof(struct fs_node));
err = _node_replace_with_last(&n);
if (err) {
break;
}
sectavail = FS_SECTOR_SIZE - (f->node.size % FS_SECTOR_SIZE);
sectaddr = FS_NODE_TARGET_ADDR(n.id);
CHK("Writing: %d bytes, lastnode: %d lastsect: 0x%06X "
"sectavail: %d filename: %s",
avail, n.id, sectaddr, sectavail, f->node.name);
if (sectavail) {
err = spi_flash_read(sectaddr, (uint32_t*)buff, FS_SECTOR_SIZE);
if (err) {
break;
}
f->node.size += rb_read(b, buff + (FS_SECTOR_SIZE - sectavail),
MIN(avail, sectavail));
err = spi_flash_erase_sector(sectaddr / FS_SECTOR_SIZE);
if (err) {
break;
}
err = spi_flash_write(sectaddr, (uint32_t*)buff, FS_SECTOR_SIZE);
if (err) {
break;
}
err = _node_save(&f->node);
if (err) {
break;
}
}
}
os_free(buff);
return err;
}
//static
//void _write_sector(uint16_t len) {
// SpiFlashOpResult err;
//
// system_soft_wdt_feed();
// system_upgrade_erase_flash(FOTA_SECTORSIZE);
// //os_delay_us(100);
// //os_printf("E: 0x%05X\r\n", fs.sector * FOTA_SECTORSIZE);
//
// system_soft_wdt_feed();
// char sector[FOTA_SECTORSIZE];
// memset(sector, 0, FOTA_SECTORSIZE);
//
// rb_safepop(&rb, sector, len);
// system_upgrade(sector, len);
// //os_delay_us(100);
// total += len;
// INFO("W: 0x%05X, len: %d, total: %d\r\n",
// fs.sector * FOTA_SECTORSIZE, len, total);
// fs.sector++;
// //err = spi_flash_write(fs.sector * FOTA_SECTORSIZE,
// // sector,
// // FOTA_SECTORSIZE);
// //if (err != SPI_FLASH_RESULT_OK) {
// // os_printf("Canot write flash: %d\r\n", err);
// // return;
// //}
//
//}
//
//
//int fota_feed(char * data, Size datalen, bool last) {
// RingBuffer *b = &rb;
// int err = rb_safepush(b, data, datalen);
// if (err != RB_OK) {
// return err;
// }
//
// while (rb_used(b) >= FOTA_SECTORSIZE) {
// _write_sector(FOTA_SECTORSIZE);
// }
//
// if (last) {
// _write_sector(rb_used(b));
// }
//
// return RB_OK;
//}
//
//
//void fota_init() {
// // Buffer
// rb.blob = (char*) os_malloc(FOTA_BUFFERSIZE + 1);
// rb_reset((RingBuffer*)&rb);
// fs.sector = system_upgrade_userbin_check() == UPGRADE_FW_BIN1 ?
// SYSTEM_PARTITION_OTA2_ADDR / FOTA_SECTORSIZE: 1;
//
// total = 0;
// //system_soft_wdt_stop();
// //wifi_fpm_close();
// //bool fp = spi_flash_erase_protect_disable();
// //if (!fp) {
// // os_printf("Cannot disable the flash protection\r\n");
// // return;
// //}
//
// system_upgrade_init();
// system_upgrade_flag_set(UPGRADE_FLAG_START);
// os_printf("FOTA: Init Sector: %X\r\n", fs.sector);
//}
//
//
//void fota_finalize() {
// os_free(rb.blob);
// os_printf("REBOOTING\r\n");
// system_soft_wdt_feed();
// system_upgrade_deinit();
// system_upgrade_flag_set(UPGRADE_FLAG_FINISH);
// system_upgrade_reboot();
//}
|
C
|
#include <stdio.h>
void main()
{
char a;
a = getch();
printf("%c is %d in ASCII\n",a,a);
}
|
C
|
#include <X11/Xlib.h>
#include <X11/X.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
typedef struct RGB_struct {
uint8_t b;
uint8_t g;
uint8_t r;
} RGB;
int main()
{
Display *display = XOpenDisplay(NULL);
Window root = DefaultRootWindow(display);
XWindowAttributes gwa;
XGetWindowAttributes(display, root, &gwa);
uint32_t width = gwa.width;
uint32_t height = gwa.height;
// The first image, to measure the screen and allocate the buffer
XImage *image = XGetImage(display, root, 0, 0, width, height, AllPlanes, ZPixmap);
uint8_t array[width * height * 3];
const uint32_t red_mask = image->red_mask;
const uint32_t green_mask = image->green_mask;
const uint32_t blue_mask = image->blue_mask;
printf("mask: %p %p %p\nbyte_order: %d\nunit: %d\nbit_order: %d\npad: %d\ndepth: %d\nBPL: %d\nbPPx: %d\n",
red_mask, green_mask, blue_mask, image->byte_order, image->bitmap_unit,
image->bitmap_bit_order, image->bitmap_pad, image->depth, image->bytes_per_line, image->bits_per_pixel);
union Color {
uint32_t hex;
RGB rgb;
struct {
uint8_t b;
uint8_t g;
uint8_t r;
};
};
// sampling steps
const uint32_t xnum = 32;
const uint32_t ynum = 24;
const uint32_t xstep = width/xnum;
const uint32_t ystep = height/ynum;
// ideally we should downscale it using nearest-neighbour
union Color *C;
while (XGetSubImage(display, root, 0, 0, width, height, AllPlanes, ZPixmap, image, 0, 0)) {
#define P_GOTO(x,y) C = ((union Color*)image->data + y*width + x);
printf("\033[2J\033[H");
for (int i = 0; i < ynum; i++) {
printf("\n");
for (int j = 0; j < xnum; j++) {
P_GOTO(j*xstep, i*ystep);
printf("\x1b[48;2;%d;%d;%dm \x1b[m", C->r, C->g, C->b);
}
}
usleep(100000);
}
return 0;
}
#if 0
typedef struct _XImage {
int width, height; /* size of image */
int xoffset; /* number of pixels offset in X direction */
int format; /* XYBitmap, XYPixmap, ZPixmap */
char *data; /* pointer to image data */
int byte_order; /* data byte order, LSBFirst, MSBFirst */
int bitmap_unit; /* quant. of scanline 8, 16, 32 */
int bitmap_bit_order; /* LSBFirst, MSBFirst */
int bitmap_pad; /* 8, 16, 32 either XY or ZPixmap */
int depth; /* depth of image */
int bytes_per_line; /* accelerator to next scanline */
int bits_per_pixel; /* bits per pixel (ZPixmap) */
unsigned long red_mask; /* bits in z arrangement */
unsigned long green_mask;
unsigned long blue_mask;
XPointer obdata; /* hook for the object routines to hang on */
struct funcs { /* image manipulation routines */
struct _XImage *(*create_image)();
int (*destroy_image)();
unsigned long (*get_pixel)();
int (*put_pixel)();
struct _XImage *(*sub_image)();
int (*add_pixel)();
} f;
} XImage;
#endif
|
C
|
/**
* Input: [2,2,1]
* Output: 1
*/
int singleNumber(int* nums, int numsSize){
int i, val=0;
for (i=0;i<numsSize; i++) {
val = val ^ nums[i];
}
return val;
}
|
C
|
#include <stdio.h>
#include "optimized_functions.h"
#include <string.h>
int main()
{
char test_string[] = "qwertyuioasdfghjkzxcvbnmytrewertyuiuytjgfghjhgygyg";
unsigned long strlen_time = 0;
unsigned long strchr_time = 0;
unsigned long start = curr_tick_num();
strlen(test_string);
strlen_time = curr_tick_num() - start;
start = curr_tick_num();
strchr(test_string, '\0');
strchr_time = curr_tick_num() - start;
start = curr_tick_num();
strlen(test_string);
strlen_time = curr_tick_num() - start;
printf("strlen - %lu\nstrchr - %lu\n", strlen_time, strchr_time);
return 0;
}
|
C
|
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <regex.h>
# include <dirent.h>
# include <time.h>
#define BUFFER_SIZE 2048
void die(char *path){
perror(path);
exit(0);
}
int main(void){
char command[100];
while(1){
fprintf(stdout, "shell original$\t");
fgets(command, sizeof(command), stdin);
pid_t pid;
pid=fork();
if (pid<0){
fprintf(stderr, "Proc Error\n");
}
if (pid==0){
execl(command, command, NULL);
die(command);
}
else{
int status;
waitpid(pid, &status, 0);
break;
}
}
}
|
C
|
/******************************************************************************
File name : xhw1.c
Author : Raghavendra Suvvari
Description : This is an user defined file from where we call the
concat system call by passing the appropriate flags,
output file, input files, flags.
Date : 1/29/2014
Version : 1.0
******************************************************************************/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include "header.h"
#define __NR_xconcat 349 /* our private syscall number */
#define __user
/*****************************************************************
* @main - Entry point of the program
* @argc: Number of arguments entered in the command line
* @argv: Pointer array which contains the command line arguments
******************************************************************/
int main(int argc, char *argv[])
{
int rc = 0;
int c = 0;
int i = 0, j = 0;
int oflag = O_RDWR;
mode_t mode = 0777;
int flag = 0;
char *string = malloc(sizeof(char *));
char *isMode = NULL;
struct myargs args;
/* getopt reads each flag from the given string*/
while ((c = getopt(argc, argv, "acteANPm:h")) != -1)
switch (c) {
case 'a':
oflag = oflag | O_APPEND;
break;
case 'c':
oflag = oflag | O_CREAT;
break;
case 't':
oflag = oflag | O_TRUNC;
break;
case 'e':
oflag = oflag | O_EXCL;
break;
case 'A':
flag = flag | 0x04;
break;
case 'N':
flag = flag | 0x01;
break;
case 'P':
flag = flag + 0x02;
break;
case 'm':
mode = strtol(optarg, NULL, 8);
isMode = optarg;
break;
case 'h':
fprintf(stderr, "Usage: %s [- actemh] [-ANP] name\n", argv[0]);
exit(EXIT_FAILURE);
case '?':
fprintf(stderr, "Usage: %s [- actemh] [-ANP] name\n", argv[0]);
exit(EXIT_FAILURE);
}
if (oflag == O_RDWR)
oflag = O_RDWR | O_APPEND;
args.oflags = oflag;
args.mode = mode;
args.flags = flag;
args.outfile = malloc(sizeof(char));
args.outfile = argv[optind];
args.infile_count = argc - optind - 1;
args.infiles = malloc((argc-optind-1) * sizeof(char *));
for (i = optind+1, j = 0; i < argc ; i++, j++) {
args.infiles[j] = malloc(sizeof(argv[i]) * sizeof(char));
args.infiles[j] = argv[i];
}
if (isMode != NULL) {
sprintf(string, "%o", mode);
if (strcmp(string, isMode) != 0) {
printf("\n Error: Entered mode is invalid\n");
free(string);
exit(0);
}
}
free(string);
void *dummy = (void *)&args;
rc = syscall(__NR_xconcat, dummy, sizeof(struct myargs));
if (rc >= 0)
printf("%d\n", rc);
/* Print the appropriate error */
else
printf("\nErrorno: %d\t %s\n", errno, strerror(errno));
exit(rc);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct date // definition of struct
{
int day;
int month;
int year;
}yesterday; // declaring of variable called yesterday: optional
int main()
{
// declaration of variables from struct
struct date today;
struct date tomorrow;
// assign values to variables
today.day = 13;
today.month = 1;
today.year = 2020;
tomorrow.day = 14;
tomorrow.month = 1;
tomorrow.year = 2020;
printf("Today's date is %i/%i/%i.\n", today.day, today.month, today.year);
printf("Tomorrow's date is %i/%i/%i.\n", tomorrow.day, tomorrow.month, tomorrow.year);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define NTAB 32
#define NDIV (1 + (IM-1)/NTAB)
#define EPS 1.2E-7
#define RNMX (1.0 - EPS)
/* Random number generator from Numerical Recipes*/
float ran1(long *idum)
{
int j;
long k;
static long iy = 0;
static long iv[NTAB];
float temp;
if (*idum <= 0 || !iy)
{
if (-(*idum) < 1) *idum = 1;
else *idum = -(*idum);
for (j = NTAB+7; j>=0; j--)
{
k = (*idum)/IQ;
*idum = IA*(*idum - k*IQ) - IR*k;
if (*idum < 0) *idum += IM;
if (j < NTAB) iv[j] = *idum;
}
iy = iv[0];
}
k = (*idum)/IQ;
*idum = IA*(*idum - k*IQ) - IR*k;
if ( *idum < 0) *idum += IM;
j = iy/NDIV;
iy = iv[j];
iv[j] = *idum;
if ( (temp = AM*iy) > RNMX) return RNMX;
else return temp;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main (){
int n;
double r,b;
scanf ("%d",&n);
r= log2(n);
b = r-(int)r;
if (b==0) {
printf ("true");
}
else
{
printf ("false");
}
return 0;
}
|
C
|
/* Andres Landeta alandeta 631427 */
/* Header File for game*/
#define NUM_CHOOSEN 4 /* Size of the pattern used for the code */
#define MAX_GUESSES 10 /* Maximun number of guesses per game */
#define NUM_LETTERS 6 /* Number of letters in the alphabet */
#define ALPHABET "ABCDEF" /* Letters used in the code */
#define LETTER_PLACEHOLDER '@' /* Permit the discard of used letters */
#define MSG_LEN 50
/* Guess output format */
typedef struct
{
int num_guesses;
char* log_msg;
char* send_msg;
int send_len;
}guess_out_t;
char* generate_code(char* choosen);
guess_out_t* next_guess(char* choosen, char* input, int num_guesses);
int is_valid(char letter);
int incorrect_position(char* input, char* compare);
guess_out_t* feedback(int num_guesses, int b, int m, char* choosen);
char* game_instructions();
|
C
|
#include <stdio.h>
#include <pthread.h>
void * update_val(void *arg);
int main() {
int i, *retval, val[10];
pthread_t tid[10];
for (i = 0; i < 10; i++)
{
val[i] = i;
pthread_create(&tid[i], NULL, update_val, val + i);
}
for (i = 0; i < 10; i++)
{
pthread_join(tid[i], (void **) &retval);
printf("Thread %d: %d %d\n", i, val[i], *retval);
}
return 0;
}
void * update_val(void *arg)
{
int i, *count;
count = (int *) arg;
for (i = 0; i < 10; i++)
*count += 1;
pthread_exit(count);
}
|
C
|
/*
* aliens.h
*
* Created on: Sep 27, 2016
* Author: superman
*/
#ifndef ALIENS_H_
#define ALIENS_H_
#include "screen.h"
#include "globals.h"
#include <stdint.h>
// draws the aliens in their initial positions on the board.
void aliens_draw_initial();
// moves all the aliens, as a block.
// initially moves them all to the right;
// when the reach the right edge, moves them down;
// then moves them left;
// then down, then right, etc.
void aliens_update_position();
// kill and blank the given alien
void aliens_kill_alien(uint8_t alien);
#endif /* ALIENS_H_ */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_put_convertion.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbelalou <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/16 05:10:51 by mbelalou #+# #+# */
/* Updated: 2018/05/03 16:35:43 by mbelalou ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../../inc/printf.h"
void ft_put_convertion(t_convert *convertion)
{
if (convertion)
{
ft_putstr("-5- print convertion value :\n\t- h ->\t");
ft_putnbr((convertion->h) ? 1 : 0);
ft_putstr("\t- value h ->\t");
ft_putnbr(convertion->nbr_h % 2);
ft_putstr("\n\t- l ->\t");
ft_putnbr((convertion->l) ? 1 : 0);
ft_putstr("\t- value l ->\t");
ft_putnbr(convertion->nbr_l % 2);
ft_putstr("\n\t- j ->\t");
ft_putnbr((convertion->j) ? 1 : 0);
ft_putstr("\n\t- z ->\t");
ft_putnbr((convertion->z) ? 1 : 0);
ft_putstr("\n");
}
else
ft_putstr("flags is NULL\n");
}
|
C
|
#include <stdio.h>
void funcao(int n){
printf("%d\n", n);
return funcao(++n);
}
int main(){
funcao(0);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
int global = 1;
int main(int argc , char * argv[]) {
int local = 2 , input;
int * dynamic = malloc(sizeof(int));
*dynamic = 3;
if(argc != 2) {
printf("You must run this program with exactly 1 argument!\n");
return 1;
}
if((input = open(argv[1] , O_RDONLY)) == -1) {
printf("Can't open %s\n" , argv[1]);
return 2;
}
printf("Pre-fork : I am %d\n" , getpid());
printf("Pre-fork : global = %d; address = %p\n" , global , &global);
printf("Pre-fork : local = %d; address = %p\n" , local , &local);
printf("Pre-fork : *dynamic = %d; dynamic = %p; &dynamic = %p\n" , *dynamic , dynamic , &dynamic);
printf("Pre-fork : input = %d\n", input);
char s[6];
strcpy(s , "xxxxx");
int i = read(input , s , 5);
if(i != 5) {
printf("Can't read %s\n" , argv[1]);
return 3;
}
printf("Pre-fork : Reading 5 bytes %s\n", s);
pid_t pid = fork();
switch(pid) {
case -1 :
printf("There was an error while forking\n");
return 4;
break;
case 0 :
printf("Child : I am %d, spawned by %d\n" , getpid() , getppid());
printf("Child : global = %d; address = %p\n" , global , &global);
printf("Child : local = %d; address = %p\n" , local , &local);
printf("Child : *dynamic = %d; dynamic = %p; &dynamic = %p\n" , *dynamic , dynamic , &dynamic);
printf("Child : input = %d\n", input);
char s[3];
strcpy(s , "xx");
int i = read(input , s , 2);
if(i != 2) {
printf("Can't read %s\n" , argv[1]);
return 5;
}
printf("Child : Reading 2 bytes %s\n", s);
global += 10; local += 10; *dynamic += 10;
printf("Child then : I am %d, spawned by %d\n" , getpid() , getppid());
printf("Child then : global = %d; address = %p\n" , global , &global);
printf("Child then : local = %d; address = %p\n" , local , &local);
printf("Child then : *dynamic = %d; dynamic = %p; &dynamic = %p\n" , *dynamic , dynamic , &dynamic);
printf("Child then : input = %d\n", input);
sleep(6);
break;
default :
global += 100; local += 100; *dynamic += 100;
printf("Parent then : I am %d, spawned by %d\n" , getpid() , getppid());
printf("Parent then : global = %d; address = %p\n" , global , &global);
printf("Parent then : local = %d; address = %p\n" , local , &local);
printf("Parent then : *dynamic = %d; dynamic = %p; &dynamic = %p\n" , *dynamic , dynamic , &dynamic);
printf("Parent then : input = %d\n", input);
close(input);
break;
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,a=1, sum=0;
printf("Enter the last number: ");
scanf("%d",&n);
printf("1+2+3+.....+%d",n);
while(a<=n){
sum=sum+a;
a++;
}
printf("= %d",sum);
getch();
}
|
C
|
/*
MT2020013 Apoorv Panse
Write a program to create a file and print the file descriptor value. Use creat ( ) system call
*/
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(){
const char * file = "test3.txt";
int fileDescriptor = creat(file, 0777);
if(fileDescriptor == -1){
printf("%s\n",strerror(errno));
}
else{
printf("File descriptor: %d \n", fileDescriptor);
}
return 0;
}
|
C
|
#ifndef UTIL_H
#define UTIL_H
#define DEBUG_ON
#define INFO_ON
#ifdef DEBUG_ON
#include <stdio.h>
#define DEBUG(fmt, var) printf(__FILE__ "@l:%d in %s\t" #var":" fmt "\n", __LINE__, __func__, var);
#define DEBUGH(t) printf(__FILE__ "@l:%d in %s\t%s\n", __LINE__, __func__, t);
#else
#define DEBUG(x) ;
#endif
#ifdef INFO_ON
#include <stdio.h>
#define INFOV(fmt, var) printf(#var":" fmt "\n", var);
#else
#define INFOV(x) ;
#endif
#endif //UTIL_H
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct tokenNode{
struct tokenNode *prev;
struct tokenNode *next;
void *data;
};
typedef struct tokenNode TokenNode;
struct tokenList{
TokenNode * firstNode;
TokenNode * lastNode;
int len;
};
typedef struct tokenList TokenList;
//ͷڵ
void push(TokenList * list, void * data){
TokenNode * node = (TokenNode *)malloc(sizeof(TokenNode));
node->data = data;
node->prev = list->lastNode;
if (list->lastNode != NULL){
list->lastNode->next = node;
}
list->lastNode = node;
if (list->len == 0){
list->firstNode = node;
}
list->len++;
}
//ȡָλϵĽڵֵ
/*void *getVal(TokenList * list, int pos){
if (pos < 0)
return NULL;
int i;
TokenNode * curNode = list->firstNode;
for(i = 0; i < pos; i++){
if (curNode->next != NULL){
curNode = curNode->next;
}
else{
curNode = NULL;
break;
}
}
if (curNode == NULL){
return NULL;
}
return curNode->data;
}
*/
static void print_r(TokenList * list){
printf("len = %d\n", list->len);
int i = 0;
TokenNode * node = list->firstNode;
while(i != list->len){
if (node == NULL)
break;
printf("list[%d]: %s\n", i, node->data);
node = node->next;
i++;
}
}
int main(){
TokenList * list = (TokenList*)malloc(sizeof(TokenList));
list->firstNode = NULL;
list->lastNode = NULL;
list->len =0;
push(list, "node 0");
push(list, "node 1");
push(list, "node 2");
print_r(list);
return 0;
}
|
C
|
//WAP to check whether a number is positive,negative or zero using switch case
#include<stdio.h>
int main()
{
int n;
printf("\n\n\tEnter any number : ");
scanf("%d",&n);
switch(n>0)
{
case 0:
switch(n<0)
{
case 0:
printf("\n\tThe given number is zero");
break;
case 1:
printf("\n\tThe given number is negative");
break;
default:
printf("\n\tError");
}
break;
case 1:
printf("\n\tThe given number is positive");
break;
default:
printf("\n\tError");
break;
}
printf("\n\n\nSuccessfully Executed...");
return 0;
}
|
C
|
/*
============================================================================
Author :
Jose Luis Soncco-Alvarez and Mauricio Ayala-Rincon
Group of Theory of Computation
Universidade de Brasilia (UnB) - Brazil
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include "ordenar_pob.h"
#include "structs_ga.h"
# include "mpi.h" //processamento paralelo
/*void swap2(poblacion *pob,int i, int j) {
cromosoma cromosomaT;
cromosomaT = pob->cromosomas[i];
pob->cromosomas[i] = pob->cromosomas[j];
pob->cromosomas[j] = cromosomaT;
}
int partition(poblacion *pob, int left, int right) {
int i, j;
i = left;
for (j = left + 1; j <= right; ++j) {
if (pob->cromosomas[j].fitness < pob->cromosomas[left].fitness) {
++i;
swap2(pob,i,j);
}
}
swap2(pob,left,i);
return i;
}
void quickSort(poblacion *pob, int left, int right) {
int r;
if (right > left) {
r = partition(pob, left, right);
quickSort(pob, left, r - 1);
quickSort(pob, r + 1, right);
}
}*/
void countingSort(poblacion *pob, int k){
int i,j;
int c[k];
cromosoma *a;
/*alocar memoria para poblacion temporal "a" */
a = malloc(pob->tamanhoPoblacion*sizeof(cromosoma));
if (a == NULL) printf("a NULL en countingSort() de ordenar_pob.c \n");
for(i=0;i<pob->tamanhoPoblacion;i++){
a[i].genes = malloc(pob->cromosomas[0].tamanho * sizeof(int));//alocar memoria para cada cromosoma
if (a[i].genes == NULL)
printf("a[i].genes NULL en countingSort() de ordenar_pob.c \n");
}
/*hacer una copia poblacion*/
for(i=0; i<pob->tamanhoPoblacion; i++){
a[i].fitness = pob->cromosomas[i].fitness;
for(j=0; j<pob->cromosomas[0].tamanho; j++)
a[i].genes[j] = pob->cromosomas[i].genes[j];
}
/*counting sort*/
for(i=0; i<k; i++){
c[i] = 0;
}
for(i=0; i<pob->tamanhoPoblacion; i++){
c[a[i].fitness] = c[a[i].fitness] + 1;
}
for(i=1; i<k; i++){
c[i] = c[i] + c[i-1];
}
for(i=pob->tamanhoPoblacion-1; i>=0; i--){
//copiar en poblacion
pob->cromosomas[c[a[i].fitness]-1].fitness = a[i].fitness;
for(j=0; j<pob->cromosomas[0].tamanho; j++)
pob->cromosomas[c[a[i].fitness]-1].genes[j] = a[i].genes[j];
c[a[i].fitness] = c[a[i].fitness] - 1;
}
/*Liberar memoria*/
for(i=0;i<pob->tamanhoPoblacion;i++){
free(a[i].genes);
}
free(a);
}
|
C
|
#include <stdio.h>
int main()
{
int arr[40],n,j,i,a;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(i=1;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
a=arr[i];
arr[i]=arr[j];
arr[j]=a;
}
}
}
for(i=0;i<n;i++)
{
printf(" %d",arr[i]);
}
return 0;
}
|
C
|
/*
gsim config_file catalog image
Generate a simulated image with parameters specified in the config file.
read object info from the catalog file (one per line), place them in an
image with noise and write to the image file.
config file
-----------
The config file should have at least these entries. Others
can exist also and will be ignored.
nrow = integer
Number of rows in the image
ncol = integer
Number of columns in the image
noise_type = "string"
Type of noise in the image. Currently
"gauss" for gaussian noise or "poisson"
For poisson noise, a deviate is drawn based on
the value sky+flux in each pixel.
For gaussian, sqrt(sky) is used for the width of gaussian noise.
sky = double
Value for the sky. Specify zero for no noise.
nsub = integer
the number of points in each dimension to use for sub-pixel
integration over the pixels.
ellip_type = "e" or "g"
if "e" then the ellipticities in the file are given as
(a^2-b^2)/(a^2+b^2). If ellip_type is "g" they are (a-b)/(a+b)
seed = integer
Seed for the random number generator
catalog file
------------
The catalog file should be a space-delimited text file with the following
columns
model row col e1 e2 sigma counts psfmodel psfe1 psfe2 psf_sigma
Note that for psfs, the centroid and counts are not given
column description
- model should currently be
"gauss" - a single gaussian
"exp" - an exponential represented using gaussians
"dev" - an devaucouleur represented using gaussians
"turb" - turbulent psf represented using gaussians
"psf" - the object ellip/size info is ignored and a psf is placed
at the given location
If you want a bulge+disk, just put two entries in the file. You can
add any number of components to an object this way.
- row,col
zero-offset row and column in the image
- e1,e2
The ellipticity of the object or the psf. This is the version defined
by the <x^2>
T=<x^2> + <y^2>
e1=(<x^2> - <y^2>)/T
e2=2*<xy>/T
We could just as easily use the reduced shear definition.
- sigma is the "sigma" of the object or psf, defined as
sqrt( (<x^2> + <y^2>)/2 ) === sqrt(T/2)
for a gaussian this is the average of the sigmas in each dimension
output image
------------
The output image is written to the indicated file. The format
is FITS.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "gconfig.h"
#include "object_simple.h"
#include "catalog.h"
#include "image.h"
#include "gmix.h"
#include "gmix_image.h"
#include "image_rand.h"
#include "image_fits.h"
// we will only draw the objects out do a radius of GMIX_PADDING*sigma
//
// sigma is the average over the gaussians in the mixture
//
// T = <x^2> + <y^2>
// <T> = sum(p_i * T_i)/sum(p_i)
// sigma = sqrt(T/2)
//
// draw_radius = GMIX_PADDING*sigma
#define GMIX_PADDING 5.0
/*
make sure this is the same random number generator used by image_rand.c
*/
void set_seed(long seed) {
srand48(seed);
}
struct image *make_image(const struct gconfig *conf)
{
fprintf(stderr,"making image\n");
struct image *im=image_new(conf->nrow, conf->ncol);
return im;
}
void add_noise(const struct gconfig *conf, struct image *image)
{
if (conf->sky <= 0) {
fprintf(stderr,"sky is zero, not adding sky or noise\n");
return;
}
fprintf(stderr,"adding noise\n");
fprintf(stderr," adding sky background\n");
image_add_scalar(image,conf->sky);
// strcasecmp is gnu extension
if (0==strcasecmp(conf->noise_type,"none")) {
fprintf(stderr," not adding noise\n");
return;
}
if (0==strcasecmp(conf->noise_type,"poisson")) {
fprintf(stderr," adding poisson noise\n");
image_add_poisson(image);
} else if (0==strcasecmp(conf->noise_type,"gauss")) {
fprintf(stderr," adding gaussian noise\n");
double skysig=sqrt(conf->sky);
image_add_randn(image, skysig);
} else {
// we check the config, so should not get here
fprintf(stderr,"unexpected noise_type: '%s'\n", conf->noise_type);
exit(EXIT_FAILURE);
}
}
/* add a ! to front of name so cfitsio will clobber any existing file */
void write_image(const struct image *self,
const char *filename)
{
int clobber=1;
fprintf(stderr,"writing %s\n", filename);
image_write_fits(self, filename, clobber);
}
struct gmix *make_gmix0(struct object_simple *object)
{
double pars[6] = {0};
long flags=0;
pars[0] = object->row;
pars[1] = object->col;
pars[2] = object->shape.e1;
pars[3] = object->shape.e2;
pars[4] = object->T;
pars[5] = object->counts;
struct gmix_pars *gpars=NULL;
struct gmix *gmix=NULL;
if ( 0==strcasecmp(object->model, "exp") ) {
gpars=gmix_pars_new(GMIX_EXP, pars, 6, SHAPE_SYSTEM_E, &flags);
} else if ( 0==strcasecmp(object->model, "dev") ) {
gpars=gmix_pars_new(GMIX_DEV, pars, 6, SHAPE_SYSTEM_E, &flags);
} else if ( 0==strcasecmp(object->model, "gauss") ) {
gpars=gmix_pars_new(GMIX_COELLIP, pars, 6, SHAPE_SYSTEM_E, &flags);
} else {
fprintf(stderr,"bad object model: '%s'\n", object->model);
exit(EXIT_FAILURE);
}
if (flags != 0) {
fprintf(stderr,"problem making pars: %s: %d\n",
__FILE__,__LINE__);
exit(1);
}
gmix = gmix_new_model(gpars, &flags);
if (flags != 0) {
fprintf(stderr,"problem making model: %s: %d\n",
__FILE__,__LINE__);
exit(1);
}
gpars=gmix_pars_free(gpars);
return gmix;
}
struct gmix *make_psf_gmix(struct object_simple *object,
double row, double col,
double flux)
{
double pars[6] = {0};
long flags=0;
pars[0] = row;
pars[1] = col;
pars[2] = object->psf_shape.e1;
pars[3] = object->psf_shape.e2;
pars[4] = object->psf_T;
pars[5] = flux;
struct gmix_pars *gpars=NULL;
struct gmix *gmix=NULL;
if ( 0==strcasecmp(object->psf_model, "turb") ) {
gpars=gmix_pars_new(GMIX_TURB, pars, 6, SHAPE_SYSTEM_E, &flags);
} else if ( 0==strcasecmp(object->psf_model, "gauss") ) {
gpars=gmix_pars_new(GMIX_COELLIP, pars, 6, SHAPE_SYSTEM_E, &flags);
} else {
fprintf(stderr,"bad psf model: '%s'\n", object->psf_model);
exit(EXIT_FAILURE);
}
if (flags != 0) {
fprintf(stderr,"problem making psf pars: %s: %d\n",
__FILE__,__LINE__);
exit(1);
}
gmix = gmix_new_model(gpars, &flags);
if (flags != 0) {
fprintf(stderr,"problem making psf model: %s: %d\n",
__FILE__,__LINE__);
exit(1);
}
gpars=gmix_pars_free(gpars);
return gmix;
}
struct gmix *make_star_gmix(struct object_simple *object)
{
struct gmix *gmix=make_psf_gmix(object,
object->row,
object->col,
object->counts);
return gmix;
}
struct gmix *make_galaxy_gmix(struct object_simple *object)
{
long flags=0;
struct gmix *gmix0 = make_gmix0(object);
struct gmix *gmix_psf = make_psf_gmix(object,1,1,1);
struct gmix *gmix = gmix_convolve(gmix0, gmix_psf,&flags);
gmix0 = gmix_free(gmix0);
gmix_psf = gmix_free(gmix_psf);
return gmix;
}
struct gmix *make_gmix(struct object_simple *object)
{
struct gmix *gmix = NULL;
if (0==strcasecmp(object->model, "star")) {
gmix = make_star_gmix(object);
} else {
if (0==strcasecmp(object->psf_model,"none")) {
gmix = make_gmix0(object);
} else {
gmix = make_galaxy_gmix(object);
}
}
return gmix;
}
void get_radius_and_cen(const struct gmix *gmix,
double *rad, double *row, double *col)
{
double irr=0,irc=0,icc=0,counts=0;
gmix_get_totals(gmix, row, col, &irr, &irc, &icc, &counts);
if (irr > icc) {
(*rad) = sqrt(irr);
} else {
(*rad) = sqrt(icc);
}
(*rad) *= GMIX_PADDING;
}
void set_mask(struct image_mask *self, const struct gmix *gmix)
{
double row=0, col=0, rad=0;
get_radius_and_cen(gmix, &row, &col, &rad);
get_radius_and_cen(gmix, &rad, &row, &col);
self->rowmin = row-rad;
self->rowmax = row+rad;
self->colmin = col-rad;
self->colmax = col+rad;
}
void put_gmix(const struct gconfig *conf, struct image *image, const struct gmix *gmix)
{
struct image_mask mask={0};
set_mask(&mask, gmix);
gmix_image_put_masked(image, gmix, conf->nsub, &mask);
}
void put_object(const struct gconfig *conf, struct image *image, struct object_simple *object)
{
struct gmix *gmix=make_gmix(object);
put_gmix(conf, image, gmix);
gmix=gmix_free(gmix);
}
void put_objects(const struct gconfig *conf, struct image *image, struct catalog *cat)
{
fprintf(stderr,"putting objects\n");
struct object_simple *object = cat->data;
for (ssize_t i=0; i<cat->size; i++) {
if ( ((i+1) % 500) ==0 || i==0 ) {
fprintf(stderr,"%ld/%ld\n", i+1, cat->size);
}
put_object(conf, image, object);
object++;
}
}
int main(int argc, char **argv)
{
if (argc < 4) {
fprintf(stderr,"gsim config_file catalog image\n");
exit(EXIT_FAILURE);
}
const char *config_file=argv[1];
const char *cat_file=argv[2];
const char *image_file=argv[3];
struct gconfig *conf=gconfig_read(config_file);
gconfig_write(conf, stderr);
set_seed(conf->seed);
struct catalog *cat=catalog_read(cat_file);
struct image *image=make_image(conf);
put_objects(conf, image, cat);
add_noise(conf, image);
write_image(image, image_file);
gconfg_write2fits(conf, image_file);
free(conf);
image=image_free(image);
cat=catalog_free(cat);
}
|
C
|
//
// Created by zhangyangshuo on 2020/11/9.
//
#include <stdio.h>
#include <stdlib.h>
struct object {
int val;
int index;
};
int compare(const void *a, const void *b){
return ((struct object*)a)->val - ((struct object*)b)->val;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i,j;
struct object *objs = malloc(numsSize* sizeof(*objs));
for(i =0;i<numsSize;i++){
objs[i].val = nums[i];
objs[i].index = i;
}
qsort(objs,numsSize,sizeof(*objs),compare);
int *results = malloc(2*sizeof(int));
i = 0;
j = numsSize-1;
while(i<j){
int sum = objs[i].val+objs[j].val;
if(sum<target){
i++;
}else if(sum>target){
j--;
}else{
results[0] = objs[i].index;
results[1] = objs[j].index;
*returnSize = 2;
free(objs);
return results;
}
}
free(objs);
return NULL;
}
int main(void){
int nums[] ={3,2,3};
int size = sizeof(nums) / sizeof(*nums);
int target = 6;
int count = 0;
int *indexes = twoSum(nums,size ,target,&count);
if(indexes!=NULL){
printf("%d %d\n",indexes[0],indexes[1]);
}else{
printf("Not found\n");
}
return 0;
}
|
C
|
#include "physicalLayer.h"
#include "linkLayer.h"
#include "transportLayer.h"
#include <arpa/inet.h>
void ethType(uint16_t type){
char *etherType = NULL;
if(ntohs(type) == ARP){
etherType = "ARP";
}
else if(ntohs(type) == IPV4){
etherType = "IP";
}
else {
etherType = "Unknown";
}
printf("%s\n", etherType);//formatting
}
int parseEthernetHeader(const u_char *pkt_data){
int subStructureReturn = 0;
struct enet_header *ethHeader = (struct enet_header *)pkt_data;
printEthernetHeader(ethHeader);
//now pass on to correct sub-structure
if(ntohs(ethHeader->type) == ARP){
subStructureReturn = parseARPHeader(&pkt_data[sizeof(uint8_t) * 14]);
}
else if(ntohs(ethHeader->type) == IPV4){
subStructureReturn = parseIPHeader(&pkt_data[sizeof(uint8_t) * 14]);
}
else {
fprintf(stderr, "Unable to parse substructure of Ethernet Header... Returning 1\n");
subStructureReturn = 1;
}
return subStructureReturn;
}
void printEthernetHeader(struct enet_header *ethHeader){
printf("\tEthernet Header\n");
printf("\t\tDest MAC: ");
strMAC(ethHeader->dest);
printf("\n\t\tSource MAC: ");
strMAC(ethHeader->source);
printf("\n\t\tType: ");
ethType(ethHeader->type);
}
|
C
|
/*
Que : 9. Write a C program to count count of number of vowels and number of consonants in the given string. (Using Dynamic Memory Allocation)
Owner: Rushikesh Sanjay Pokharkar
Batch: PPA9
*/
// ********* Solution *********
#include<stdio.h> // Include necessary header files
//#include<stdlib.h>
void main() {
int n, i = 0, no_of_char = 1; // Declaration of variables.
char ch;
char* p = NULL; // Initializing pointer to null value.
char vowels[] = { 'a','e','i','o','u','A','E','I','O','U' };
char consonants[] = { 'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z','B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z' };
int vowels_count = 0, consonants_count = 0;
// Syntax for Dynamic memory allociation of array.
p = (char*)malloc(sizeof(char)); // Given 1 byte memory dynamically..
*(p + i) = '\0'; // String terminating character is added at position 0 of array..
printf("Enter the string : ");
// Logic to take input in array using DMA.
do
{
scanf_s("%c", &ch);
if (ch != '\n') {
no_of_char++;
p = (char*)realloc(p, no_of_char * sizeof(char)); // reallocate memory to new character.
*(p + i) = ch;
*(p + i + 1) = '\0';
i++;
}
} while (ch != '\n');
printf("User Entered String is: ");
int j = 0;
while (*(p + j) != '\0') // While loop to print array..
{
printf("%c", *(p + j));
j++;
}
int size_vowels = sizeof(vowels);
int size_consonants = sizeof(consonants);
int size_datatype = sizeof(vowels[0]);
int vowels_len = size_vowels / size_datatype; // Calculating size of array vowels
int consonants_len = size_consonants / size_datatype; // Calculating size of array consonants
// Logic to count the number of vowels and consonants in given string.
i = 0;
while (*(p + i) != '\0') {
if (*(p + i) == ' ') {
i++;
continue;
}
for (int j = 0; j < vowels_len; j++)
{
if (*(p + i) == vowels[j]) // If vowels fount in string increase count of vowels
{
vowels_count++;
break;
}
}
for (int k = 0; k < consonants_len; k++)
{
if (*(p + i) == consonants[k]) // If consonants fount in string increase count of consonants
{
consonants_count++;
break;
}
}
i++;
}
printf("\nThe vowels count in given string is: %d\n", vowels_count);
printf("The consonants count in given string is: %d\n", consonants_count);
free(p); // Free the memory which is given to pointer p Dynamically...
}
|
C
|
/*
* Copyright (c) 2018-2019 Snowflake Computing, Inc. All rights reserved.
*/
#include "arraylist.h"
#include "memory.h"
ARRAY_LIST* STDCALL sf_array_list_init() {
ARRAY_LIST *al = (ARRAY_LIST *) calloc(1, sizeof(ARRAY_LIST));
// No spots are used yet
al->used = 0;
// Always initialize to 8
al->size = 8;
// Initialize array to NULL
al->data = (void **) SF_CALLOC(al->size, sizeof(void *));
return al;
}
void STDCALL sf_array_list_deallocate(ARRAY_LIST *al) {
if (al != NULL) {
SF_FREE(al->data);
}
SF_FREE(al);
}
void STDCALL sf_array_list_grow(ARRAY_LIST *al, size_t min_size) {
if (!al) {
return;
}
size_t i;
size_t new_size = al->size;
while (new_size < min_size) {
new_size *= 2;
}
al->data = (void **) SF_REALLOC(al->data, sizeof(void *) * new_size);
// Initialize new memory to NULL
for (i = al->size; i < new_size; i++) {
al->data[i] = NULL;
}
al->size = new_size;
}
void STDCALL sf_array_list_set(ARRAY_LIST *al, void *item, size_t index) {
if (!al) {
return;
}
if (al->size <= index) {
sf_array_list_grow(al, index+1);
}
// If element we are writing to is NULL and item is not NULL, we want to increment 'used'.
// Otherwise we are writing to a spot that already contains an element
if (!al->data[index] && item) {
al->used++;
} else if (al->data[index] && !item) {
// If this element exists and item is NULL, then we are deleting from the arraylist
// and so we decrement used
al->used--;
}
al->data[index] = item;
}
void* STDCALL sf_array_list_get(ARRAY_LIST *al, size_t index) {
if (!al) {
return NULL;
}
if (al->size <= index) {
sf_array_list_grow(al, index+1);
}
return al->data[index];
}
|
C
|
#include "lists.h"
/**
* get_nodeint_at_index - return the data of the nth node
*
* @head: head of the list
* @index: index of the find
* Return: the node that have the index
*/
listint_t *get_nodeint_at_index(listint_t *head, unsigned int index)
{
/*declare an auxiliar pointer*/
listint_t *aux;
unsigned int count_index;
/*pointer to the head*/
aux = head;
count_index = 0;
/*iterate on the list*/
while (count_index < index && aux->next != NULL)
{
aux = aux->next;
count_index++;
}
/*validate if the counter is equal to teh index*/
if (count_index == index)
return (aux);
return (NULL);
}
|
C
|
#include <stdio.h>
#include <math.h>
int main() {
float x, value, term;
int loop;
x = 0.57735; // tan (PI/6)
value = 0.0;
term = x;
for (loop=0; term >=0.00001 || term <= -0.00001; ++loop) {
term = pow(-1,loop)*pow(x, 2*(loop+1)-1)/(2*(loop+1)-1);
value = value + term;
}
printf("Value of PI: %f\nNo of iterations: %d\n", value*6, loop);
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int tam;
scanf("%d",&tam);
int vet[tam];
int i, j, aux;
int chave;
for(i = 0; i < tam; i++){
scanf("%d",&vet[i]);
}
int intervalo = tam / 2;
while(intervalo > 0){
for(i = intervalo; i < tam;i++){
j = i;
while(vet[j] < vet[j-intervalo] && (j > 0)){
aux = vet[j-intervalo];
vet[j-intervalo] = vet[j];
vet[j] = aux;
j = j - intervalo;
}
}
intervalo = intervalo / 2;
}
for(i = 0; i < tam; i++){
printf(" %d",vet[i]);
}
}
|
C
|
#include <stdio.h>
#include "swap_l_r_node.h"
#include <stdlib.h>
#include<math.h>
#include <time.h>
#define bool char
#define true 1
#define false 0
void swap_l_r_node(p_p_tree pptree)
{
if(is_nul(pptree))printf("header cannot be null");
size_t size = (*pptree)->size;
size_t new_size = (size_t)my_log(2, size);
int begin = 1;
int end = 0;
// printf("new_size===%d\n", new_size);
for(int i=1;i<=new_size;i++)
{
if(begin > size)break;
int range = pow(2,i);
end = begin + range - 1;
if(end > size)end=size-1;
des_sort( pptree, begin, end);
begin = end + 1;
}
}
void swap_1(int* x, int* y)
{
*x = *x^*y;
*y = *x^*y;//(*x^*y)^*y=*x(ԭֵ)
*x = *x^*y;//(*x^*y)^((*x^*y)^*y)=*yԭֵ
}
void init_node(p_p_tree pptree, int* header, size_t size)
{
if(!header||!size||!pptree)printf("tree cannot be null");
*pptree = (p_tree)calloc(1, sizeof(int*)+sizeof(size_t));
(*pptree)->data = header;
(*pptree)->size = size;
}
int main(void)
{
srand(time(NULL));
size_t size = 700000;
size_t a[size];
for(int i=0;i<size;i++)
{
a[i] = rand()%size;
// printf("%d,",a[i]);
}
printf("\n");
// int a[] = {4,5,2,6,7,8,2,1};
p_p_tree pptree = (p_p_tree)calloc(1,sizeof(p_tree));
p_tree ptree = *pptree;
const int size_1 = sizeof(a)/sizeof(a[0]);
// printf("size1===%d,",size_1);
time_t t; //time_tһͣtime_t͵t
time(&t); //ȡõǰʱ
printf("%s\n",ctime(&t));// ctime(&t)תΪַӡ
init_node(pptree, a, size_1);
// printf("size2===%d,",size_1);
// printf("header===%d\n",*((*pptree)->data));
swap_l_r_node(pptree);
// printf("size3===%d,",sizeof(a)/sizeof(a[0]));
//sizeֵΪɶı?
// printf("size4===%d\n",size_1);
// printf("%d,",a[2]);
time(&t); //ȡõǰʱ
printf("%s\n",ctime(&t));// ctime(&t)תΪַӡ
// for(int i=0;i<size_1;i++)printf("%d,",a[i]);
return 0;
}
void des_sort(p_p_tree pptree, size_t index_b, size_t index_e)
{
// printf("index_b===%d,", index_b);
// printf("index_e===%d\n", index_e);
if(is_nul(pptree))printf("tree cannot be null");
if(index_b < 0 || index_e > (*pptree)->size)
{
printf("begin and end index must be in the fair range");
return;
}
int index = index_b + (index_e-index_b+1)/2;
// printf("index===%d\n", index);
while(index_b<index_e)
{
// printf("---before---\n");
// printf("index_b_value===%d,", *((*pptree)->data+index_b));
// printf("index_e_value===%d\n", *((*pptree)->data+index_e));
swap_1((*pptree)->data+index_b, (*pptree)->data+index_e);
// printf("---after---\n");
// printf("index_b_value===%d,", *((*pptree)->data+index_b));
// printf("index_e_value===%d\n", *((*pptree)->data+index_e));
index_b++;
index_e--;
}
}
bool is_nul(p_p_tree pptree)
{
return !pptree||!(*pptree)||!(*pptree)->data||!(*pptree)->size;
}
float my_log(int a, int b)
{
return log(b)/log(a);
}
|
C
|
#pragma once
#include "kernel32_undoc.h"
bool create_new_process1(PROCESS_INFORMATION &pi, LPWSTR cmdLine, LPWSTR startDir = NULL)
{
STARTUPINFO si;
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
memset(&pi, 0, sizeof(PROCESS_INFORMATION));
if (!CreateProcess(
NULL,
cmdLine,
NULL, //lpProcessAttributes
NULL, //lpThreadAttributes
FALSE, //bInheritHandles
DETACHED_PROCESS|CREATE_SUSPENDED|CREATE_NO_WINDOW, //dwCreationFlags
NULL, //lpEnvironment
startDir, //lpCurrentDirectory
&si, //lpStartupInfo
&pi //lpProcessInformation
))
{
printf("[ERROR] CreateProcess failed, Error = %x\n", GetLastError());
return false;
}
return true;
}
bool create_new_process2(PROCESS_INFORMATION &pi, LPWSTR cmdLine, LPWSTR startDir = NULL)
{
STARTUPINFO si;
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
memset(&pi, 0, sizeof(PROCESS_INFORMATION));
HANDLE hToken = NULL;
HANDLE hNewToken = NULL;
if (!CreateProcessInternalW (hToken,
NULL, //lpApplicationName
(LPWSTR) cmdLine, //lpCommandLine
NULL, //lpProcessAttributes
NULL, //lpThreadAttributes
FALSE, //bInheritHandles
CREATE_SUSPENDED|DETACHED_PROCESS|CREATE_NO_WINDOW, //dwCreationFlags
NULL, //lpEnvironment
startDir, //lpCurrentDirectory
&si, //lpStartupInfo
&pi, //lpProcessInformation
&hNewToken
))
{
printf("[ERROR] CreateProcessInternalW failed, Error = %x\n", GetLastError());
return false;
}
return true;
}
|
C
|
// function that counts how many C networks there are
int countC(int set[][4], int size){
int dynamic = size;
// start with 0 networks
int classC = 0;
for (int i = 0; i < dynamic; i++){
// checks if the number counts towards C networks
if(set[i][0] >= 192) {
// increment networks
classC += 1;
}
}
return classC;
}
|
C
|
#include<stdio.h>
void daxpy_(int* n, double* DA,
double* DX, int *incx,
double* DY, int *incy);
int main(){
int N=5;
double DX[5]={2,3,4,6,1};
double DY[5]={1,1,1,1,1};
int i;
int INCX;
int INCY;
double DA;
DA = 5;
INCX = 1;
INCY = 1;
daxpy_(&N, &DA, DX, &INCX, DY, &INCY);
for (i = 0;i < 10;i++){
printf ("%f ",DY[i]);
}
}
|
C
|
/*
Copyright Luke A.C.A. Rieff 2020 - All Rights Reserved
*/
#include "buzzer.h"
void buzzer_init(const buzzer_t *buzzer) {
buzzer->gpio->MODER &= ~(0x3 << (2 * buzzer->pin));
buzzer->gpio->MODER |= (0x1 << (2 * buzzer->pin));
buzzer->gpio->ODR &= ~(0x1 << buzzer->pin);
}
void buzzer_buzz(const buzzer_t *buzzer, uint16_t pulses,
uint16_t delay) {
for (uint16_t i = 0; i < pulses; ++i) {
buzzer->gpio->ODR |= (0x1 << buzzer->pin);
delay_us(delay);
buzzer->gpio->ODR &= ~(0x1 << buzzer->pin);
delay_us(delay);
}
}
|
C
|
#include "linkedlist.h"
int dllist_isempty(struct DLList* list)
{
return list->head == 0;
}
int sllist_isempty(struct SLList* list)
{
return list->head == 0;
}
int csllist_isempty(struct CSLList* list)
{
return list->head == 0;
}
void slqueue_init(struct SLQueue* slqueue)
{
slqueue->head = NULL;
slqueue->tail = NULL;
}
// returns 1 if the queue was empty
int slqueue_push(struct SLQueue* slqueue, struct SLListNode* node)
{
node->next = NULL;
if (slqueue->tail == NULL) {
// First item
slqueue->head = node;
slqueue->tail = node;
return 1;
} else {
slqueue->tail->next = node;
slqueue->tail = node;
return 0;
}
}
struct SLListNode* slqueue_pop(struct SLQueue* slqueue)
{
struct SLListNode* result = slqueue->head;
if (result == NULL) return NULL;
slqueue->head = result->next;
if (result->next == NULL) {
slqueue->tail = NULL;
}
#if LLIST_CLEARDANGLE == 1
result->next = NULL;
#endif
return result;
}
void dllist_init(struct DLList* list)
{
list->head = NULL;
list->tail = NULL;
}
void dllist_insertafter(struct DLList* list, struct DLListNode* node, struct DLListNode* newnode)
{
newnode->prev = node;
newnode->next = node->next;
if (node->next == NULL) {
list->tail = newnode;
} else {
node->next->prev = newnode;
}
node->next = newnode;
}
void dllist_insertbefore(struct DLList* list,struct DLListNode* node, struct DLListNode* newnode)
{
newnode->prev = node->prev;
newnode->next = node;
if(node->prev == NULL) {
list->head = newnode;
} else {
node->prev->next = newnode;
}
node->prev = newnode;
}
void dllist_insertfirst(struct DLList* list, struct DLListNode* newnode)
{
if (list->head == NULL) {
list->head = newnode;
list->tail = newnode;
newnode->prev = NULL;
newnode->next = NULL;
} else {
dllist_insertbefore(list, list->head, newnode);
}
}
void dllist_insertlast(struct DLList* list, struct DLListNode* newnode)
{
if (list->tail == NULL) {
dllist_insertfirst(list, newnode);
} else {
dllist_insertafter(list, list->tail, newnode);
}
}
void dllist_bringtofront(struct DLList* list, struct DLListNode* node)
{
dllist_remove(list,node);
dllist_insertfirst(list,node);
}
void dllist_sendtoback(struct DLList* list, struct DLListNode* node)
{
dllist_remove(list,node);
dllist_insertlast(list,node);
}
struct DLListNode* dllist_rotate(struct DLList* list)
{
struct DLListNode* item = list->head;
if (item){
if (list->head == list->tail) return item;
list->head = item->next;
list->head->prev = NULL;
item->prev = list->tail;
item->next = NULL;
list->tail->next = item;
list->tail = item;
}
return item;
}
void dllist_remove(struct DLList* list, struct DLListNode* node)
{
if (node->prev == NULL) {
list->head = node->next;
} else {
node->prev->next = node->next;
}
if (node->next == NULL) {
list->tail = node->prev;
} else {
node->next->prev = node->prev;
}
}
struct DLListNode* dllist_popfirst(struct DLList* list)
{
struct DLListNode* result = list->head;
if (result) {
dllist_remove(list, result);
}
return result;
}
int dllist_count(struct DLList* list)
{
int count = 0;
struct DLListNode* cursor = list->head;
while(cursor) {
count++;
cursor = cursor->next;
}
return count;
}
void sllist_init(struct SLList* list)
{
list->head = NULL;
}
void sllist_insertafter(struct SLList* list, struct SLListNode* node, struct SLListNode* newnode)
{
newnode->next = node->next;
node->next = newnode;
}
void sllist_insertfirst(struct SLList* list, struct SLListNode* newnode)
{
newnode->next = list->head;
list->head = newnode;
}
struct SLListNode* sllist_popfirst(struct SLList* list)
{
struct SLListNode* result = list->head;
if (result) {
list->head = result->next;
// clear dangling pointer
result->next = NULL;
}
return result;
}
// [NOTE] O(n)
int sllist_remove(struct SLList* list, struct SLListNode* node)
{
ASSERT(list->head,"Cannot remove the node from an empty list.")
// first find the node linking to 'node'
struct SLListNode* cursor = list->head;
if (node == cursor) {
list->head = node->next;
node->next = 0;
return RESULT_SUCCESS;
}
struct SLListNode* prev = cursor;
for(cursor = cursor->next;cursor != NULL;cursor = cursor->next) {
if (cursor == node) {
prev->next = node->next;
node->next = 0;
return RESULT_SUCCESS;
}
prev = cursor;
};
return RESULT_FAILURE;
// Node does not belong to the list
}
int sllist_count(struct SLList* list)
{
int count = 0;
struct SLListNode* cursor = list->head;
while(cursor) {
count++;
cursor = cursor->next;
}
return count;
}
void sllist_bringtofront(struct SLList* list, struct SLListNode* node)
{
// don't do anything if node is already at top
if (list->head == node) return;
struct SLListNode* cursor = list->head;
struct SLListNode* prev = NULL;
while(cursor != node) {
prev = cursor;
cursor = cursor->next;
}
if (prev) {
prev->next = cursor->next;
} else {
// first item
list->head = cursor->next;
}
// find the top of the list
cursor = list->head;
while(cursor->next) {
cursor = cursor->next;
}
// if not already top of the list, put it there
if (cursor != node) {
cursor->next = node;
node->next = NULL;
}
}
void csllist_init(struct CSLList* list)
{
list->head = NULL;
}
void csllist_insertafter(struct CSLList* list,
struct SLListNode* node,
struct SLListNode* newnode)
{
newnode->next = node->next;
node->next = newnode;
}
void csllist_insertfirst(struct CSLList* list, struct SLListNode* newnode)
{
if (list->head) {
newnode->next = list->head->next;
list->head->next = newnode;
list->head = newnode;
} else {
newnode->next = newnode;
}
list->head = newnode;
}
void csllist_rotate(struct CSLList* list)
{
if (list->head){list->head = list->head->next;}
}
// Remark: this function has O(n) execution time
// so only use for small lists
void csllist_remove(struct CSLList* list, struct SLListNode* node)
{
ASSERT(list->head,"Cannot remove the node from an empty list.")
// first find the node linking to 'node'
struct SLListNode* cursor = list->head;
do {
if (cursor->next == node) break;
cursor = cursor->next;
}while(cursor);
if (cursor == node) {
// this was the last node in the list
list->head = NULL;
} else{
cursor->next = node->next;
}
// clear dangling pointer
node->next = NULL;
}
int csllist_count(struct CSLList* list)
{
int count = 0;
struct SLListNode* cursor = list->head;
if (cursor) {
do {
count++;
cursor = cursor->next;
} while(cursor!=list->head);
}
return count;
}
struct SLListNode* slqueue_poptail(struct SLQueue* slqueue)
{
struct SLListNode* result = NULL;
if (slqueue->tail) {
result = slqueue->tail;
if (slqueue->head == slqueue->tail) {
slqueue->head = NULL;
slqueue->tail = NULL;
} else {
// find previous
struct SLListNode* c = slqueue->head;
while(c->next != result){c = c->next;}
// readjust tail
slqueue->tail = c;
c->next = NULL;
}
result->next = NULL;
}
return result;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "element/Tower.h"
#include "element/Monster.h"
#include "geometry/Intersection.h"
#include "ihm/Interface.h"
/************* Création d'une nouvelle liste de tours *************/
/* Initialisation de la liste de tours et allocation de mémoire pour la liste de tours *
* Retourne la liste de tours */
LTower* new_LTower(void) {
//Alloue de la mémoire
LTower *p_ltower = malloc(sizeof(LTower));
if (p_ltower != NULL) {
p_ltower->length = 0;
p_ltower->p_head = NULL;
p_ltower->p_tail = NULL;
}
else {
fprintf(stderr, "Erreur lors de l'allocation memoire de la liste de tours\n");
return NULL;
}
return p_ltower;
}
/************* Ajouter une tour en fin de liste *************/
/* Ajoute une tour à la liste. Alloue la place mémoire pour la tour et attribue les valeurs *
* Prend en paramètre la liste de tours, la puissance d'attaque, la vitesse d'attaque, le type *
* le périmétre d'action, le cout et la position. Retourne 0 en cas d'erreur et 1 sinon */
int addTower(LTower* p_ltower, int power, int rate, char* type_tower, int range, int cost, float x, float y) {
// On vérifie si notre liste a été allouée
if (p_ltower != NULL) {
//Création d'une nouvelle tour
Tower* new_tower = malloc(sizeof(Tower));
// On vérifie si le malloc n'a pas échoué
if (new_tower != NULL) {
new_tower->rate = rate;
new_tower->compteur = 0;
new_tower->range = range;
new_tower->type_tower = type_tower;
new_tower->cost = cost;
new_tower->power = power;
new_tower->lvl = 1;
new_tower->x = x;
new_tower->y = y;
//Pointer vers la tour suivant à NULL car on rajoute à la fin de la liste
new_tower->p_next = NULL;
// Cas où notre liste est vide (pointeur vers fin de liste à NULL)
if (p_ltower->p_tail == NULL) {
// Pointe la tête de la liste sur la nouvelle tour
p_ltower->p_head = new_tower;
//Pointe p_prev de la nouvelle tour à NULL
new_tower->p_prev = NULL;
}
// Cas où des éléments sont déjà présents dans la liste
else {
// Pointe p_prev de la nouvelle tour sur la dernière tour de la liste
new_tower->p_prev = p_ltower->p_tail;
// Relie la dernière tour de la liste à la nouvelle tour
p_ltower->p_tail->p_next = new_tower;
}
// Pointe la fin de la liste sur la nouvelle tour
p_ltower->p_tail = new_tower;
// On augmente de 1 la taille de la liste
p_ltower->length++;
}
else {
fprintf(stderr, "Problème dans la creation de la nouvelle tour\n");
return 0;
}
}
else {
fprintf(stderr, "Cette liste de tours n'existe pas\n");
return 0;
}
return 1;
}
/**************************** Augmenter le niveau d'une tour ********************************/
/* Augmente le niveau, l'attage, la vitesse de tire et le périmètre d'action d'une tour. *
* Prend en paramètre un pointeur vers la tour que l'on souhaite modifier. *
* Retourne 0 en cas d'erreur et 1 sinon. */
int upgrateTower(Tower* p_courant, Interface* interface) {
if(p_courant != NULL) {
if(interface != NULL) {
//Si c'est une tour hybride
if(strcmp("H", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 50)) {
interface->money -= (p_courant->lvl * 50);
p_courant->power += 5;
if(p_courant->rate - 1 > 0)
p_courant->rate -= 1;
p_courant->range += 3;
}
}
//Si c'est une tour mitrailette
else if(strcmp("M", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 100)) {
interface->money -= (p_courant->lvl * 100);
p_courant->power += 2;
if(p_courant->rate - 1 > 0)
p_courant->rate -= 1;
p_courant->range += 3;
}
}
//Si c'est une tour laser
else if(strcmp("L", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 200)) {
interface->money -= (p_courant->lvl * 200);
p_courant->power += 4;
if(p_courant->rate - 1 > 0)
p_courant->rate -= 1;
p_courant->range += 2;
}
}
//Si c'est une tour rocket
else if(strcmp("R", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 150)) {
interface->money -= (p_courant->lvl * 150);
p_courant->power += 5;
if(p_courant->rate - 2 > 0)
p_courant->rate -= 1;
p_courant->range += 2;
}
}
p_courant->lvl ++;
}
else {
fprintf(stderr, "Erreur : cette interface n'existe pas\n");
return 0;
}
}
else {
fprintf(stderr, "Erreur : cette tour n'existe pas\n");
return 0;
}
return 1;
}
/**************************** Augmenter l'attaque d'une tour ********************************/
/* Augmente l'attaque d'une tour. Prend en paramètre un pointeur vers la tour que l'on *
* souhaite modifier. Retourne 0 en cas d'erreur et 1 sinon. */
int upgradePowerT(Tower* p_courant, Interface* interface) {
if(p_courant != NULL) {
if(interface != NULL) {
p_courant->power += 5;
//Si c'est une tour hybride
if(strcmp("H", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 20))
interface->money -= (p_courant->lvl * 20);
}
//Si c'est une tour mitrailette
else if(strcmp("M", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 30))
interface->money -= (p_courant->lvl * 30);
}
//Si c'est une tour rocket
else if(strcmp("R", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 50))
interface->money -= (p_courant->lvl * 50);
}
//Si c'est une tour laser
else if(strcmp("L", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 70))
interface->money -= (p_courant->lvl * 70);
}
}
else {
fprintf(stderr, "Erreur : cette interface n'existe pas\n");
return 0;
}
}
else {
fprintf(stderr, "Erreur cette tour n'existe pas\n");
return 0;
}
return 1;
}
/**************************** Augmenter la vitesse de tir d'une tour ********************************/
/* Augmente la vitesse de tir d'une tour. Prend en paramètre un pointeur vers la tour que l'on *
* souhaite modifier. Retourne 0 en cas d'erreur et 1 sinon. */
int upgradeRateT(Tower* p_courant, Interface* interface) {
if(p_courant != NULL) {
if(interface != NULL) {
if(p_courant->rate - 1 > 0) {
p_courant->rate -= 1;
//Si c'est une tour hybride
if(strcmp("H", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 20))
interface->money -= (p_courant->lvl * 20);
}
//Si c'est une tour mitrailette
else if(strcmp("M", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 50))
interface->money -= (p_courant->lvl * 50);
}
//Si c'est une tour rocket
else if(strcmp("R", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 60))
interface->money -= (p_courant->lvl * 60);
}
//Si c'est une tour laser
else if(strcmp("L", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 70))
interface->money -= (p_courant->lvl * 70);
}
}
}
else {
fprintf(stderr, "Erreur : cette interface n'existe pas\n");
return 0;
}
}
else {
fprintf(stderr, "Erreur cette tour n'existe pas\n");
return 0;
}
return 1;
}
/**************************** Augmenter le périmètre d'action d'une tour ********************************/
/* Augmente le périmètre d'action d'une tour. Prend en paramètre un pointeur vers la tour que l'on *
* souhaite modifier. Retourne 0 en cas d'erreur et 1 sinon. */
int upgradeRangeT(Tower* p_courant, Interface* interface) {
if(p_courant != NULL) {
if(interface != NULL) {
p_courant->range += 3;
//Si c'est une tour hybride
if(strcmp("H", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 20))
interface->money -= (p_courant->lvl * 20);
}
//Si c'est une tour mitrailette
else if(strcmp("M", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 50))
interface->money -= (p_courant->lvl * 50);
}
//Si c'est une tour rocket
else if(strcmp("R", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 50))
interface->money -= (p_courant->lvl * 50);
}
//Si c'est une tour laser
else if(strcmp("L", p_courant->type_tower) == 0) {
if(interface->money >= (p_courant->lvl * 60))
interface->money -= (p_courant->lvl * 60);
}
}
else {
fprintf(stderr, "Erreur : cette interface n'existe pas\n");
return 0;
}
}
else {
fprintf(stderr, "Erreur cette tour n'existe pas\n");
return 0;
}
return 1;
}
/****************** Vérifier si la tour est sur un zone constructible ***********************/
/* Vérifie si la tour est sur une zone constructible : Vérifie si les coordonnées de chaque *
* extremité fait partie de la liste de point. Prend en paramètre la liste de pixel et les deux *
* extremités (deux points). Retourne 1 si c'est valide, sinon 0. */
int verificationConstruct(LNode* l_node, Point2D point1, Point2D point2) {
if(l_node != NULL) {
int i, test = 0;
Point2D point;
for(i = 0; i < 4; i++) {
//Vérifie avec les quatres points du quad
switch(i) {
case 0 :
point.x = point1.x; point.y = point1.y;
break;
case 1 :
point.x = point1.x; point.y = point2.y;
break;
case 2 :
point.x = point2.x; point.y = point2.y;
break;
case 3 :
point.x = point2.x; point.y = point1.y;
break;
}
//Créer un pointeur temporaire node pour parcourir la liste de noeud
Node* p_tmp = l_node->p_head;
while(p_tmp != NULL){
if(point.x == p_tmp->x && point.y == p_tmp->y)
test++;
p_tmp = p_tmp->p_next;
}
}
//Si les 4 extremité sont dans la zone constructible
if(test < 4)
return 0;
}
else {
fprintf(stderr, "Il y a un probleme avec la liste de points constructible\n");
return 0;
}
return 1;
}
/****************** Faire bouger la tour ***********************/
/* Fait bouger la tour en fonction des positions passé en paramètre. Passe en paramètre la liste de tours, *
* la tour que l'on souhaite bouger, la nouvelle position : x et y. Retourne 0 en cas d'erreur et & sinon */
int moveTower(LTower* p_ltower, Tower* p_courant, LNode* l_node, float x, float y) {
if(p_ltower != NULL) {
if(p_courant != NULL) {
p_courant->x = x;
p_courant->y = y;
Point2D point1, point2;
point1.x = x + 15; point1.y = y + 15;
point2.x = x - 15; point2.y = y - 15;
if(verificationConstruct(l_node, point1, point2) == 1) {
point1.x = x + 20; point1.y = y + 20;
point2.x = x - 20; point2.y = y - 20;
//Si ce n'est pas le premier de la liste
if(p_courant->p_prev != NULL){
Point2D point3, point4;
//Créer un pointeur tour temporaire pour parcourir la liste
Tower* p_tmp = p_ltower->p_head;
//Parcour de la liste
while(p_tmp->p_next != NULL) {
point3.x = (p_tmp->x) + 20; point3.y = (p_tmp->y) + 20;
point4.x = (p_tmp->x) - 20; point4.y = (p_tmp->y) - 20;
//Vérifie qu'il ne se trouve pas sur une autre tour (pas d'intersection)
if(intersectionCarres (point1, point2, point3, point4) == 0)
p_tmp = p_tmp->p_next;
else
return 0;
}
return 1;
}
//Sinon pas besoin de faire la vérification pour les collisions de quads
else
return 1;
}
}
else {
fprintf(stderr, "Cette tour n'existe pas\n");
return 0;
}
}
else {
fprintf(stderr, "Erreur : il y a un problème avec la liste de tours\n");
return 0;
}
return 0;
}
/************* Supprimer une tour selon sa position *************/
/* Supprime une tour selon sa position, vérifie si c'est le premier, le dernier ou une tour dans la liste puis la supprime *
* Prend en paramètre la liste de tours et la tour à supprimer et retourne la liste de tours. */
LTower* removeTower(LTower* p_ltower, Tower* p_courant) {
// On vérifie si notre liste a été allouée
if (p_ltower != NULL) {
if(p_courant != NULL) {
//Si c'est la dernière tour de la liste
if (p_courant->p_next == NULL) {
//Pointe la fin de la liste sur la tour précédente
p_ltower->p_tail = p_courant->p_prev;
if(p_ltower->p_tail != NULL) {
//Lien de la dernière tour vers la tour suivante est NULL
p_ltower->p_tail->p_next = NULL;
}
else
p_ltower->p_head = NULL;
}
//Si c'est la première de la liste
else if (p_courant->p_prev == NULL) {
//Pointe la tête de la liste vers la tour suivante
p_ltower->p_head = p_courant->p_next;
if(p_ltower->p_head != NULL) {
//Le lien vers de la deuxième tour vers la tour précédente est NULL
p_ltower->p_head->p_prev = NULL;
}
else
p_ltower->p_tail = NULL;
}
else {
//Relie la tour suivante à la tour précédente de la tour que l'on veut supprmer
p_courant->p_next->p_prev = p_courant->p_prev;
//Relie la tour précédente à la tour suivante de la tour que l'on veut supprmer
p_courant->p_prev->p_next = p_courant->p_next;
}
//Libère espace mémoire : supprime la tour
free(p_courant);
//Décrémente de un la taille de la liste
p_ltower->length--;
}
else
fprintf(stderr, "Cette tour n'existe pas");
}
else
fprintf(stderr, "Cette liste de tours n'existe pas");
// on retourne notre nouvelle liste
return p_ltower;
}
/************* Supprimer toutes les tours de la liste *************/
/* Supprime la liste de tours. Prend en paramètre un pointeur vers la liste de tours */
void removeAllTower (LTower* p_ltower) {
//Si la liste n'est pas vide
if (p_ltower->length != 0) {
//Tant que la liste n'est pas vide
while (p_ltower->p_head != NULL) {
p_ltower = removeTower(p_ltower, p_ltower->p_head);
}
}
}
/************* Supprimer la liste de tours *************/
/* Supprime la liste de tours. Prend en paramètre un pointeur vers la liste de tours */
void freeAllTower (LTower* p_ltower) {
//Si la liste n'est pas vide
if (p_ltower->length != 0) {
//Tant que la liste n'est pas vide
while (p_ltower->p_head != NULL) {
p_ltower = removeTower(p_ltower, p_ltower->p_head);
}
}
free(p_ltower);
}
|
C
|
/*
* File: timer.c
* Author: dhung
*
*/
#include <xc.h>
#include "timer.h"
void initTimers() {
//initTimer1();
initTimer2();
initTimer32bit();
}
void initTimer1() {
TMR1 = 0; //Clear timer
T1CONbits.TCKPS = 3; //Prescalar 256
T1CONbits.TCS = 0; //Set oscillator
PR1 = 389; //PR for ~10 ms, rounded from 389.625
IEC0bits.T1IE = 1; //Enable
IFS0bits.T1IF = 0; //Flag down
IPC1bits.T1IP = 7; //Default priority
T1CONbits.TON = 0; //Timer off -- manually turn on when needed
}
void initTimer2() {
TMR2 = 0;
T2CONbits.TCKPS = 0; //Prescalar 1
T2CONbits.TCS = 0;
IFS0bits.T2IF = 0; //Flag down
}
void initTimer32bit() {
//Use timers 4 and 5
TMR4 = 0;
TMR5 = 0;
T4CONbits.TCS = 0;
//T5CONbits.TCS = 0;
T4CONbits.T32 = 1;
T4CONbits.TCKPS = 7;
IFS0bits.T5IF = 0;
IEC0bits.T5IE = 1;
IPC5bits.T5IP = 7;
PR4 = 0b0011000100101100;
PR5 = 0x01;
T4CONbits.ON = 0;
}
void delayMs(unsigned int delay) {
int i = 0;
for (i = 0; i != delay; ++i) {
delayUs(1000); //delay 1 ms
}
}
void delayUs(unsigned int delay){
TMR2 = 0;
PR2 = 14*delay;
IFS0bits.T2IF = 0;
T2CONbits.ON = 1;
while (IFS0bits.T2IF == 0);
T2CONbits.ON = 0;
}
|
C
|
#include "driver/gpio.h"
#include "esp32renard_gpio_timeout.h"
typedef struct {
gpio_num_t gpio;
gpio_int_type_t type;
} timeout_source_t;
static timeout_source_t timeout_sources[5];
static size_t timeout_source_count = 0;
void esp32renard_gpio_timeout_add(gpio_num_t gpio, gpio_int_type_t type)
{
if (type == GPIO_INTR_HIGH_LEVEL || type == GPIO_INTR_LOW_LEVEL) {
timeout_sources[timeout_source_count].gpio = gpio;
timeout_sources[timeout_source_count].type = type;
++timeout_source_count;
}
}
bool esp32renard_gpio_timeout_continue(void)
{
for (size_t i = 0; i < timeout_source_count; ++i)
gpio_wakeup_enable(timeout_sources[i].gpio, timeout_sources[i].type);
return timeout_source_count > 0;
}
bool esp32renard_gpio_timeout_occurred(void)
{
for (size_t i = 0; i < timeout_source_count; ++i) {
if (gpio_get_level(timeout_sources[i].gpio) == (timeout_sources[i].type == GPIO_INTR_HIGH_LEVEL))
return true;
}
return false;
}
|
C
|
/* See LICENSE for license details. */
/*
Module: feed_list.h
Description:
Generic linked list to be used for all lists in feed project.
Comments:
The list is a circular doubly linked list. A fake element is used
to point to first and last elements. The same structure is used for
each element including the fake element. However, the fake element
does not have the same derived type as the other elements.
The caller is reponsible of casting the element to the derived type.
Before casting, it is important to make sure that the element is
not the fake element. If the list is not the first member of the
derived type, then it may be useful to use the offsetof() macro to
get a pointer to the start of the derived type.
The circular feature ensures that each element is part of a list.
Operations may be done on a single element or on groups of elements.
The same method is used to insert elements or to remove elements.
See the examples section for more details.
Examples:
- create an empty list
feed_list_init(&o_list);
- insert a first list before a second
feed_list_join(&o_first, &o_second);
- insert a first list after a second
feed_list_join(&o_second, &o_first);
- remove a single element from a list
feed_list_join(&o_element, &o_element);
- remove a group of elements from a list
feed_list_join(&o_last, &o_first);
Notes:
To insert all elements of a list into another, you first need to
detach the elements from the fake or else the final list may end up
with two fake elements.
p_first = o_fake.p_next;
feed_list_join(&o_fake, &o_fake);
feed_list_join(p_first, &o_other);
*/
/* Header file dependencies */
#if !defined(INC_FEED_OS_H)
#error include feed_os.h first
#endif /* #if !defined(INC_FEED_OS_H) */
/* Reverse include guard */
#if defined(INC_FEED_LIST_H)
#error include feed_list.h once
#endif /* #if defined(INC_FEED_LIST_H) */
#define INC_FEED_LIST_H
/*
Structure: feed_list
Description:
*/
struct feed_list
{
struct feed_list *
p_next;
struct feed_list *
p_prev;
}; /* struct feed_list */
/* Public functions ... */
void
feed_list_init(
struct feed_list * const
p_node);
void
feed_list_join(
struct feed_list * const
p_before,
struct feed_list * const
p_after);
/* end-of-file: feed_list.h */
|
C
|
/*
** sort_client_list.c for zappy in /home/candan_c/rendu/c/zappy
**
** Made by caner candan
** Login <candan_c@epitech.net>
**
** Started on Mon Jun 9 21:03:18 2008 caner candan
** Last update Mon Jun 9 21:09:35 2008 caner candan
*/
#include <stdio.h>
#include "observator_2d.h"
void sort_client_list(t_list **begin)
{
t_list *p;
t_list *swap;
p = *begin;
while ((*begin)->next)
{
if (CLIENT((*begin)->data)->y
> CLIENT((*begin)->next->data)->y)
{
printf("petit swap\n");
swap = (*begin)->next->data;
(*begin)->next->data = (*begin)->data;
(*begin)->data = swap;
*begin = p;
}
else
*begin = (*begin)->next;
}
*begin = p;
}
|
C
|
/*********************************************************************/
/* */
/* This Program Written by Paul Edwards. */
/* Released to the public domain */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* zap - modify a file by changing a byte at an offset */
/* e.g. zap temp.txt 3 13 (put a 13 at offset 3 [0-based]). */
/* */
/* You can use hex digits instead of decimal by prefixing the */
/* number with "0x" or "0X". */
/* */
/* You can use octal digits instead of decimal by prefixing the */
/* number with "0". */
/* */
/*********************************************************************/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *fu;
if (argc < 4)
{
printf("usage: zap <fnm> <offs> <dec>\n");
return (EXIT_FAILURE);
}
fu = fopen(*(argv+1), "r+b");
if (fu == NULL)
{
printf("unable to open file %s\n", *(argv+1));
return (EXIT_FAILURE);
}
fseek(fu, strtol(*(argv+2), NULL, 0), SEEK_SET);
fputc((int)strtol(*(argv+3), NULL, 0), fu);
fclose(fu);
return (EXIT_SUCCESS);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "huffmannode.h"
#define swap(x, y) \
{ \
struct node *swap = (x); \
(x) = (y); \
(y) = swap; \
}
/**
* Compares the weight of two nodes.
*
* Returns the difference of their weight:
* return < 0 if this < that
* return = 0 if this == that
* return > 0 if this > that
*/
int compare(struct node *this, struct node *that);
struct node {
int weight;
int is_leaf;
union {
struct {
struct node *left;
struct node *right;
} parent;
struct {
int key;
int depth;
} leaf;
} type;
};
struct node *new_leaf_node(int key, int weight)
{
struct node *this = malloc(sizeof *this);
this->weight = weight;
this->type.leaf.key = key;
this->type.leaf.depth = 0;
this->is_leaf = 1;
return this;
}
struct node *new_parent_node(struct node *left, struct node *right)
{
struct node *this = malloc(sizeof *this);
this->weight = left->weight + right->weight;
this->type.parent.left = left;
this->type.parent.right = right;
this->is_leaf = 0;
return this;
}
void free_node(struct node *this)
{
free(this);
}
int is_leaf(struct node *this)
{
return this->is_leaf;
}
int get_weight(struct node *this)
{
return this->weight;
}
void set_depth(struct node *this, int depth)
{
assert(this->is_leaf);
this->type.leaf.depth = depth;
}
int get_depth(struct node *this)
{
assert(this->is_leaf);
return this->type.leaf.depth;
}
int get_key(struct node *this)
{
assert(is_leaf(this));
return this->type.leaf.key;
}
struct node *left_child(struct node *this)
{
assert(!is_leaf(this));
return this->type.parent.left;
}
struct node *right_child(struct node *this)
{
assert(!is_leaf(this));
return this->type.parent.right;
}
int compare(struct node *this, struct node *that)
{
return this->weight - that->weight;
}
/**
* In-place quicksort of an array of nodes.
*/
void sort_nodes(struct node **nodes, int length)
{
if (length < 2) {
return;
}
if (length == 2) {
/* swap if the only two nodes are in the wrong order */
if (compare(nodes[0], nodes[1]) > 0) {
swap(nodes[0], nodes[1]);
}
return;
}
/* use middle node as pivot */
swap(nodes[length / 2], nodes[length - 1]);
struct node *pivot = nodes[length - 1];
/* find left and right nodes in wrong order */
int left = 0;
int right = length - 2;
while (left <= right) {
/* find rightmost node in wrong order to pivot */
while(left <= right && compare(pivot, nodes[right]) <= 0) {
right--;
}
/* find leftmost node in wrong order to pivot*/
while (left <= right && compare(nodes[left], pivot) <= 0) {
left++;
}
/* swap left and right if were found out of order */
if (left <= right) {
if (left != right) {
swap(nodes[left], nodes[right]);
}
left++;
right--;
}
}
/* swap pivot and node at which left and right crossed */
int swap_pos = right + 1;
if (swap_pos != length - 1) {
swap(nodes[swap_pos], nodes[length - 1])
}
/* call sort on left and right subarrays */
sort_nodes(nodes, swap_pos);
sort_nodes(nodes + (swap_pos + 1), length - (swap_pos + 1));
}
int binary_search_nodes(huff_node *nodes, int length, huff_node node)
{
int value = get_weight(node);
int lower = 0;
int upper = length - 1;
while (lower <= upper) {
int mid = lower + (upper - lower) / 2;
int mid_weight = get_weight(nodes[mid]);
if (value == mid_weight) {
return mid;
}
else if (value < mid_weight) {
upper = mid - 1;
}
else if (value > mid_weight) {
lower = mid + 1;
}
}
return lower;
}
|
C
|
#include "holberton.h"
/**
* print_alphabet_x10 - main function
*
*Description: prints the alphabet in lowercase 10 times
*
*Return: Returns void
*
*/
void print_alphabet_x10(void)
{
int i;
int j;
for (i = 1; i <= 10 ; i++)
{
j = 'a';
while (j <= 'z')
{
_putchar(j);
j++;
}
_putchar('\n');
}
return;
}
|
C
|
#include <stdio.h>
#define MAX_PESSOAS 11
typedef struct data_nascimento {
int dia;
int mes;
int ano;
} Data;
typedef struct pessoa {
char nome[50];
float altura;
struct data_nascimento data;
} Pessoa;
Pessoa pessoas[MAX_PESSOAS];
int main() {
scanf("%s", &pessoas[0].nome);
pessoas[0].altura = 1.7;
pessoas[0].data.dia = 2;
pessoas[0].data.mes = 12;
pessoas[0].data.ano = 2000;
scanf("%s", &pessoas[1].nome);
pessoas[1].altura = 1.4;
pessoas[1].data.dia = 18;
pessoas[1].data.mes = 4;
pessoas[1].data.ano = 2008;
int i;
for (i = 0; i < MAX_PESSOAS; i++) {
if (pessoas[i].altura != 0) {
printf("Nome: %s\n", pessoas[i].nome);
printf("Altura: %.1f\n", pessoas[i].altura);
printf("dia: %d\n", pessoas[i].data.dia);
printf("mes: %d\n", pessoas[i].data.mes);
printf("ano: %d\n", pessoas[i].data.ano);
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int val=2;
printf("val=%i \n",val);
printf("val=%i \n",val++);
printf("val=%i \n",val--);
printf("val=%i \n",--val);
}
|
C
|
#include <stdio.h>
#include <pthread.h>
void *printInt(void *x) {
printf("%d\n", x);
pthread_exit(NULL);
}
int main( ) {
pthread_t threads[2];
long t1 = 15;
long t2 = 17;
pthread_create(&threads[0], NULL, printInt, (void*)t1);
pthread_create(&threads[1], NULL, printInt, (void*)t2);
pthread_exit(NULL);
return 0;
}
|
C
|
//URI Online Judge | 1134
#include <stdio.h>
int main(){
int tipo=0, gasolina=0, alcool=0, diesel=0;
while(tipo != 4){
scanf("%d", &tipo);
switch (tipo)
{
case 1:
alcool++;
break;
case 2:
gasolina++;
break;
case 3:
diesel++;
break;
case 4:
printf("MUITO OBRIGADO\n");
printf("Alcool: %d\n", alcool);
printf("Gasolina: %d\n", gasolina);
printf("Diesel: %d\n", diesel);
break;
default:
break;
}
}
return 0;
}
|
C
|
#include <avr/interrupt.h>
#include <stdlib.h>
#include <string.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/atomic.h>
#include <util/delay.h>
void initADC(){
ADMUX = (1<<REFS0); // set mux
ADCSRA = (1<<ADEN)|(1<<ADPS1)|(1<<ADPS0); // divided by prescale of 8
}
unsigned int read_adc(int axis){
/*if(axis==0){ // z axis is PA0
ADMUX = 0b10100000;
}
else if(axis==1){ // y axis is PA1
ADMUX = 0b10100001;
}
else if(axis==2){ // x axis is PA2
ADMUX = 0b10100010;
}
else{
return 0;
}*/
axis=axis&0b00000111;
ADMUX|=axis;
ADCSRA|= (1<<ADSC); // clear ADSC by writing one to it
while(!(ADCSRA&(1<<ADSC))) // wait for conversion to complete
;
return(ADC); // retuens 10 bit unsigned number
}
// Method triggered by overflow
ISR(TIMER1_OVF_vect)
{
PORTB ^= 0xFF; //toggle PORTB values
}
// Data from Bluetooth TX given to USART RX
unsigned char USART_Receive( void )
{
/* Wait for data to be received */
while ( !(UCSRA & (1<<RXC)) ) { }
/* Get and return received data from buffer */
return UDR;
}
// Data from USART TX given to Bluetooth RX
void USART_Transmit( unsigned char data )
{
/* Wait for empty transmit buffer */
while ( !( UCSRA & (1<<UDRE)) ) { }
/* Put data into buffer, sends the data */
UDR = data;
}
void USART_SendString(char *str) /* Send string of USART data function */
{
int i=0;
while (str[i]!=0)
{
USART_Transmit( str[i] ); /* Send each char of string till the NULL */
i++;
}
}
// Flush USART
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSRA & (1<<RXC) ) dummy = UDR;
}
// Initialize USART
void USART_Init( unsigned int baud )
{
/* Set baud rate */
UBRRH = (unsigned char)(baud>>8);
UBRRL = (unsigned char)baud;
UCSRA |= (1<<U2X);
/* Enable receiver and transmitter */
UCSRB = (1<<RXEN)|(1<<TXEN);
/* Set frame format: 8data, 2stop bit */
UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);
}
//
void Bluetooth_Init(){
//USART_Init(9600);
USART_Init(12); // UBRR value for 9600
char *cmd = "AT+UART=9600,2,0\r\n";
while (*cmd != '\0'){
USART_Transmit( *cmd );
++cmd;
}
}
void USART_Start_Timer()
{
TCCR1B |= (1 << CS11); // Timer1 prescaler = 8
TCNT1 = 0; // Clear the timer counter
TIMSK = (1 << TOIE1); // Enable timer1 overflow interrupt(TOIE1)
sei(); // Enable global interrupts
}
// Main Method
int main(void){
Bluetooth_Init();
initADC();
// LED Light is Port B
DDRB = 0xFF; // Set PORTB as output
PORTB = 0; // Clear PORTB bits (turn the LEDs off)
// Bluetooth is Port D
DDRD = 0x01; // PD0 is RX so processor reads it, PD1 is TX so processor writes it
while(1){
char DATA_IN = USART_Receive();
if(DATA_IN == '0') {
PORTB = read_adc(0);
_delay_ms(100);
USART_SendString( "Read Z Axis Acceleration.\n" );
USART_SendString( read_adc(0) );
USART_SendString( "\n" );
}
else if(DATA_IN == '1') {
PORTB = read_adc(1);
_delay_ms(100);
USART_SendString( "Read Y Axis Acceleration.\n" );
USART_SendString( read_adc(1) );
USART_SendString( "\n" );
}
else if(DATA_IN == '2') {
PORTB = read_adc(2);
_delay_ms(100);
USART_SendString( "Read X Axis Acceleration.\n" );
USART_SendString( read_adc(2) );
USART_SendString( "\n" );
}
else if(DATA_IN == '\n' || DATA_IN == '\r');
else USART_SendString( "Please select a proper option.\n" );
/*
char DATA_IN = USART_Receive();
if(DATA_IN == '1') {
PORTB |= 0xFF; // all the LEDs
USART_SendString( "LED is on.\n" );
}
else if(DATA_IN == '0') {
PORTB &= ~0xFF; // all the LEDs
USART_SendString( "LED is off.\n" );
}
else if(DATA_IN == '\n' || DATA_IN == '\r');
else USART_SendString( "Please select a proper option.\n" );
*/
}
}
|
C
|
#include <apop.h>
/* This sample produces a dummy times table, gets a summary, and prunes the summary table.
If you are not a test script, uncomment the last line to display the pruned table. */
int main(){
int i, j;
apop_data *d = apop_data_alloc(0, 10, 4);
for (i=0; i< 10; i++)
for (j=0; j< 4; j++)
apop_data_set(d, i, j, i*j);
apop_data *summary = apop_data_summarize(d);
apop_data_prune_columns(summary, "mean", "median");
assert(apop_name_find(summary->names, "mean", 'c')!=-2);
assert(apop_name_find(summary->names, "median", 'c')!=-2);
assert(apop_name_find(summary->names, "max", 'c')==-2); //not found
assert(apop_name_find(summary->names, "variance", 'c')==-2); //not found
assert(apop_data_get(summary, .row=0, .colname="mean")==0);
assert(apop_data_get(summary, .row=1, .colname="median")==4);
assert(apop_data_get(summary, .row=2, .colname="median")==8);
//apop_data_show(summary);
}
|
C
|
#include <stdio.h>
int main(){
float x, y;
char resposta;
printf("Digite o primeiro numero\n");
scanf("%f", &x);
printf("Digite o segundo numero\n");
scanf("%f", &y);
float z = (x*y)+5;
if(z<=0){
resposta = "A";
}else if(z<=100){
resposta = "B";
}else{
resposta = "C";
}
printf("\n");
printf("z: %.f", z);
printf("\n");
printf("Resposta: %c", resposta);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/**
* main - multiplies two numbers
* @argc: argument count
* @argv: argument vector
*
* Return: 0
*/
int main(int argc, char *argv[])
{
int count, sum = 1;
for (count = 1; count < argc; count++)
{
sum *= atoi(argv[count]);
}
if (argc != 3)
{
puts("Error");
return (1);
}
printf("%d\n", sum);
return (0);
}
|
C
|
#ifndef TIME_DEFS_H
#define TIME_DEFS_H
#include <time.h> // gives time_t
//typedef uint32_t time_t; // time in number of microseconds
#include "iqmath.h"
//-------------------------------------------------------------------
// note: float is for TI TMS compiler
//#define TIME_SEC(s) (time_t)((float)(s)*1000000.0)
//#define TIME_MSEC(ms) (time_t)((float)(ms)*1000.0)
#define TIME_SEC(s) (time_t)((s)*1000000.0)
#define TIME_MSEC(ms) (time_t)((ms)*1000.0)
#define TIME_USEC(us) (time_t)(us)
#if IQMATH_FLOAT32
#define time2IQ(T) ((float)(T)*(float)1e-6)
#define IQ2time(T) (time_t)((float)(T)*(float)1e6)
#define time2IQms(T) ((float)(T)*(float)1e-3)
#define IQms2time(T) (time_t)((float)(T)*(float)1e3)
#endif
#if IQMATH_INT32
#define time2IQ(T) IQ20mpy((iq20_t)(T), IQ(1.048576))
#define IQ2time(T) IQmpy((iq_t)(T), IQ20(0.953674316))
#define time2IQms(T) IQ10mpy((iq10_t)(T), IQ(1.024))
#define IQms2time(T) IQmpy(IQdiv1024((iq_t)(T))+1, IQ20(0.9765625))
#endif
#define time2FLOAT(T) ((float)(T)*1e-6)
#endif // TIME_DEFS_H
|
C
|
/*
* gcc prime_factor_decomposition.c -lm
*
*/
#include <stdio.h>
#include <math.h>
main()
{
long int b, n, d, i;
scanf("%ld", &n);
d = 2;
while (n > 1)
{
b = n % d;
//printf("%ld %ld %ld\n", n, d, b);
if (b == 0)
{
printf("%ld\n", d);
n /= d;
}
else
{
int next_div_not_found = 1;
while (next_div_not_found)
{
d++;
int is_prime = 1;
for (i = 2; i < (long int)sqrt(d); i++)
{
if (d % i == 0)
{
is_prime = 0;
break;
}
}
if (is_prime)
break;
}
}
}
}
|
C
|
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *tree;
void create_tree(struct node *tree)
{
tree = NULL;
}
struct node *insertElement(struct node *tree, int val)
{
struct node *ptr, *nodeptr, *parentptr;
ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = val;
ptr->left = NULL;
ptr->right = NULL;
if (tree == NULL)
{
tree = ptr;
tree->left = NULL;
tree->right = NULL;
}
else
{
parentptr = NULL;
nodeptr = tree;
while (nodeptr != NULL)
{
parentptr = nodeptr;
if (val < nodeptr->data)
nodeptr = nodeptr->left;
else
nodeptr = nodeptr->right;
}
if (val < parentptr->data)
parentptr->left = ptr;
else
parentptr->right = ptr;
}
return tree;
}
void preorderTraversal(struct node *tree)
{
if (tree != NULL)
{
printf("%d\n", tree->data);
preorderTraversal(tree->left);
preorderTraversal(tree->right);
}
}
void inorderTraversal(struct node *tree)
{
if (tree != NULL)
{
inorderTraversal(tree->left);
printf("%d\n", tree->data);
inorderTraversal(tree->right);
}
}
void postorderTraversal(struct node *tree)
{
if (tree != NULL)
{
postorderTraversal(tree->left);
postorderTraversal(tree->right);
printf("%d\n", tree->data);
}
}
struct node *deleteElement(struct node *tree, int val)
{
struct node *cur, *parent, *suc, *psuc, *ptr;
if (tree->left == NULL)
{
printf("\nThe tree is empty ");
return (tree);
}
parent = tree;
cur = tree->left;
while (cur != NULL && val != cur->data)
{
parent = cur;
cur = (val < cur->data) ? cur->left : cur->right;
}
if (cur == NULL)
{
printf("\nThe value is not present in the tree");
return (tree);
}
if (cur->left == NULL)
ptr = cur->right;
else if (cur->right == NULL)
ptr = cur->left;
else
{
psuc = cur;
cur = cur->left;
while (suc->left != NULL)
{
psuc = suc;
suc = suc->left;
}
if (cur == psuc)
{
suc->left = cur->right;
}
else
{
suc->left = cur->left;
psuc->left = suc->right;
suc->right = cur->right;
}
ptr = suc;
}
if (parent->left == cur)
parent->left = ptr;
else
parent->right = ptr;
free(cur);
return tree;
}
struct node *deleteTree(struct node *tree)
{
if (tree != NULL)
{
deleteTree(tree->left);
deleteTree(tree->right);
free(tree);
}
}
int main()
{
int option, val;
struct node *ptr;
create_tree(tree);
do
{
printf("\n--------MAIN MENU--------");
printf("\n1. Insert Element");
printf("\n2. Preorder Traversal");
printf("\n3. Inorder Traversal");
printf("\n4. Postorder Traversal");
printf("\n5. Delete an element");
printf("\n6. Delete tree");
printf("\n7. Exit");
printf("\nEnter your choice : ");
scanf("%d", &option);
switch (option)
{
case 1:
printf("Enter the value of the new node : ");
scanf("%d", &val);
tree = insertElement(tree, val);
break;
case 2:
printf("\nThe elements of the tree are : \n");
preorderTraversal(tree);
break;
case 3:
printf("\nThe elements of the tree are : \n");
inorderTraversal(tree);
break;
case 4:
printf("\nThe elements of the tree are : \n");
postorderTraversal(tree);
break;
case 5:
printf("\nEnter the element to be deleted : ");
scanf("%d", &val);
tree = deleteElement(tree, val);
break;
case 6:
tree = deleteTree(tree);
printf("\nThe tree has been deleted");
break;
}
} while (option != 7);
printf("\nThe program has ended");
return 0;
}
|
C
|
/* Dato un vettore ordinato di interi V ed un numero n, si scriva la
porzione di codice per implementare un algoritmo di ricerca e
stampare l’indice del primo elemento di V uguale ad n. (Esempio 1)
Si modifichi il programma per trovare più occorrenze dello stesso
numero (stampandone tutti gli indici).
Si modifichi il programma per creare un secondo array V2 in cui
inserire gli indici delle occorrenze (quelli stampati al punto
precedente). Si presti attenzione a non lasciare buchi in V2 . Al
termine si stampi V2 .
*/
#include <stdio.h>
#define MAX_N 10
typedef int array[MAX_N];
int main(){
array V, V2;
int n, i, j;
/* Leggo il vettore */
for (i=0; i<MAX_N; i++){
printf("Inserisci l'elemento nella posizione con indice %d: ", i);
scanf("%d", &V[i]);
}
/* Leggo l'elemento da cercare */
printf("Inserisci l'elemento da cercare: ");
scanf("%d", &n);
/* Cerco l'elemento ed utilizzo un secondo indice per salvarne la posizione in V2 senza lasciare buchi */
for (i=0, j=0; i < MAX_N; i++){
if (V[i] == n){
V2[j] = i;
j++;
}
}
/* Stampo. Abbiamo visto come j possa essere usato per terminare la scansione di V2 al punto esatto */
for (i = 0; i < j; i++){
printf("%d ", V2[i]);
}
printf("\n");
}
|
C
|
#ifndef __MEMEORY_INFO_STRUCT_H_H__
#define __MEMEORY_INFO_STRUCT_H_H__
#include <stdio.h>
#include <stdlib.h>
#include "__hash.h"
enum MEM_OP_TYPE
{
OP_NEW = 0,
OP_NEW_ARRAY,
OP_DELETE,
OP_DELETE_ARRAY,
OP_MALLOC,
OP_FREE,
OP_NONE
};
enum MEM_STATE
{
MEM_STATE_ALLOCATED = 0, //已分配
MEM_STATE_REPEAT_ALLOCATED, //同一地址重复分配
MEM_STATE_RELEASED, //已经正确释放
MEM_STATE_REPEATED_RELEASED, //重复释放
MEM_STATE_UNKNOW_ADDR, //未知地址释放
MEM_STATE_DELETE_MISMATCH //delete/delete[]与new[]/new不匹配
};
typedef struct _meminfo
{
NextElemT _next; //注意:这里必须放在结构体中的第一个位置
unsigned int _size;
const char * _file;
const char * _func;
unsigned int _line;
MEM_OP_TYPE _type;
unsigned int _state;
MEM_OP_TYPE _expect_type;
//默认构造
_meminfo() :_next(0, NULL)
, _size(0)
, _file(NULL)
, _func(NULL)
, _line(0)
, _type(OP_NONE)
, _state(0)
{}
//带参构造
_meminfo(unsigned long ptr, unsigned int size, const char * file, const char * func, unsigned int line, MEM_OP_TYPE type,
MEM_OP_TYPE expect_type = OP_NONE, unsigned int state = 0, NextElemT * next = NULL)
: _next(ptr, next)
, _size(size)
, _file(file)
, _func(func)
, _line(line)
, _type(type)
, _expect_type(expect_type)
, _state(state)
{}
} MemInfoT;
#endif //__MEMEORY_INFO_STRUCT_H_H__
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "../../libuEliece/src/uEliece.h"
int main(int argc, char *argv[]) {
if (argc!=2) {
printf("Specify size in MB\n");
return -1;
}
uEl_PubKey public_key;
uEl_PrivKey private_key;
//preparing testing file
printf("Creating file of given size ...\n");
int i = 0;
int FILESIZE = (argv[1][1] - '0') * 1<<20;
printf("FILESIZE :%d\n", FILESIZE);
uint8_t *msg = malloc(FILESIZE);
memset(msg,'a', FILESIZE);
printf("Preparing for encryption ...\n");
FILE* pubkey_file = fopen("uEl_pub.key", "rb");
if (pubkey_file == NULL)
return -1;
if (fread( public_key, sizeof(uint8_t), (UEL_MDPC_M/8)+1, pubkey_file) != (UEL_MDPC_M/8)+1)
return -1;
fclose(pubkey_file);
uEl_msglen_t length;
uEl_msglen_t len = FILESIZE * 8;
printf("Encrypting\n"); fflush(stdout);
uEliece_encrypt( &msg, len, &length, public_key, uEl_default_rng() );
FILE* outfile = fopen("myfile.encrypted","wb");
fwrite(msg, length, 1, outfile);
fclose(outfile);
printf("Encryption finished\n");
printf("Preparing for decryption ...\n");
FILE* privkey_file = fopen("uEl_priv.key", "rb");
if (fread( private_key[0], sizeof(uint16_t), UEL_MDPC_W/2, privkey_file) != UEL_MDPC_W/2)
return -1;
if (fread( private_key[1], sizeof(uint16_t), UEL_MDPC_W/2, privkey_file) != UEL_MDPC_W/2)
return -1;
fclose(privkey_file);
if (uEliece_decrypt(&msg,length*8,&length,private_key ) & UEL_BAD_INTEGRITY) {
printf("Bad integrity");
}
printf("Decryption finished\n");
printf("Validation starting ...\n");
for(i = 0; i < FILESIZE; i++) {
if(msg[i] != 'a') {
printf("Validation failed!\n");
return -1;
}
}
printf("Validation succeeded. Everything works\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct question {
char content[200];
char answers[4][50];
int correct;
} Question;
Question * questions;
void skipNlines(FILE * f,int n){
while(n){
char t = fgetc(f);
if(t == '\n')
n--;
}
}
int load_questions(){
FILE * fp;
int qNum;
fp = fopen("round1.txt","r");
fscanf(fp,"%d",&qNum);
questions = (Question*)malloc(sizeof(Question) * qNum);
skipNlines(fp,2);
for(int i=0;i<qNum;i++){
do{
fgets(questions[i].content,100,fp);
}while(strlen(questions[i].content) <= 10);
fgets(questions[i].answers[0],50,fp);
fgets(questions[i].answers[1],50,fp);
fgets(questions[i].answers[2],50,fp);
fgets(questions[i].answers[3],50,fp);
fscanf(fp,"%d",&questions[i].correct);
printf("%s",questions[i].content);
printf("%s",questions[i].answers[0]);
printf("%s",questions[i].answers[1]);
printf("%s",questions[i].answers[2]);
printf("%s",questions[i].answers[3]);
printf("%d\n",questions[i].correct);
}
return qNum;
}
int main(){
int numOfQuestions=0;
system("clear");
printf("\t\t\tDAMPLURI TAMASHEBI\n");
printf("\n\t\t***************************************");
printf("\n\t\t\t HERZLICH WILLKOMMEN ");
printf("\n\t\t\t TO THE QUIZ ");
printf("\n\t\t\t DAMPLURI TAMASHEBI ");
printf("\n\t\t***************************************");
printf("\n\t\t Click S to begin the quiz");
printf("\n\t\t Click T to access the top score");
printf("\n\t\t Click R to reset your points");
printf("\n\t\t Click Q to quit");
printf("\n\t\t***************************************\n\n");
numOfQuestions = load_questions();
// for(int i=0;i<numOfQuestions;i++)
// puts(questions[i].content);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ins5.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: juspende <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/25 14:25:41 by juspende #+# #+# */
/* Updated: 2018/08/21 14:54:53 by juspende ### ########.fr */
/* */
/* ************************************************************************** */
#include "corewar.h"
static void ft_ext_two(t_asm *strukt, char *s, int line, t_ins *t)
{
if (s[t->i] == LABEL_CHAR)
{
t->tp = ft_find_label(strukt, s + t->i + 1, line);
ft_write_us(t->tp, strukt);
strukt->size += 2;
}
else
{
t->tmp = (unsigned short)ft_atoi(s + t->i);
ft_write_us(t->tmp, strukt);
strukt->size += 2;
}
}
static void ft_ext_one(t_asm *strukt, char *s, int line, t_ins *t)
{
if (s[t->i] == DIRECT_CHAR)
{
if (s[t->i + 1] == LABEL_CHAR)
t->tp = ft_find_label(strukt, s + t->i + 2, line);
else
t->tp = ft_atoi(s + t->i + 1);
strukt->size += 4;
ft_write_ui(t->tp, strukt);
}
else if (s[t->i] == 'r')
{
t->tmp = (char)ft_atoi(s + t->i + 1);
ft_write(strukt, &t->tmp, 1);
strukt->size += 1;
}
else
ft_ext_two(strukt, s, line, t);
while (s[t->i] != SEPARATOR_CHAR)
t->i++;
t->i++;
while (s[t->i] == ' ' || s[t->i] == '\t')
t->i++;
}
void ft_and_xor_or(t_asm *strukt, char *s, char opcode, int line)
{
t_ins t;
t.i = ft_find_instruction(s);
ft_check_instruction_line(s + t.i, 3, "277");
t.inst = opcode;
strukt->size += 2;
ft_write(strukt, &t.inst, 1);
t.inst = ft_write_codage(s + t.i);
ft_write(strukt, &t.inst, 1);
ft_ext_one(strukt, s, line, &t);
ft_ext_one(strukt, s, line, &t);
t.tmp = (char)ft_atoi(s + t.i + 1);
ft_write(strukt, &t.tmp, 1);
strukt->size += 1;
}
|
C
|
#include <stdio.h>
int main()
{
int s[10];
int t[42]={0, };
for(int i=0;i<10;i++)
{
scanf("%d", &s[i]);
}
int cnt=0;
for(int i=0;i<10;i++)
{
t[(s[i]%42)]++;
}
for(int i=0;i<42;i++)
{
if(t[i]>0) cnt++;
}
printf("%d", cnt);
}
|
C
|
#include "my.h"
int my_strlen(char *s)
{
if (s != NULL)
{
int counter = 0;
while (1)
{
if (s[counter] == '\0')
{
return counter;
}
else
{
counter++;
}
}
}
else
{
return -1;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.