language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* backround.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksuomala <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/20 19:59:26 by ksuomala #+# #+# */
/* Updated: 2021/05/26 14:45:34 by ksuomala ### ########.fr */
/* */
/* ************************************************************************** */
#include "lemin_visual.h"
t_room *room_coordinates(t_room *rooms, int size, int room_count)
{
int i;
i = 0;
while (i < room_count)
{
rooms[i].x = rooms[i].x * size + 50;
rooms[i].y = rooms[i].y * size + 50;
i++;
}
return (rooms);
}
/*
** Initializing SDL2. Creating the window and renderer.
*/
t_pointers *initialize(t_data *scale, t_pointers *sdl, t_room *rooms)
{
if (SDL_Init(SDL_INIT_VIDEO))
ft_error(SDL_GetError());
sdl->window = SDL_CreateWindow("Lem-in", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, WIN_W, WIN_H, 0);
if (!sdl->window)
ft_error(SDL_GetError());
sdl->renderer = SDL_CreateRenderer(sdl->window, -1,
SDL_RENDERER_TARGETTEXTURE);
if (!sdl->renderer)
ft_error(SDL_GetError());
if (TTF_Init() == -1)
ft_error("TTF_INIT ERROR\n");
sdl->font = TTF_OpenFont("visualizer_dir/Ubuntu-M.ttf", 24);
if (!sdl->font)
ft_error(SDL_GetError());
rooms = room_coordinates(rooms, scale->room_size, scale->room_count);
return (sdl);
}
|
C
|
#include <stdio.h>
int strrem(char *palabra, char target);
int main()
{
char palabra[]={'v','a','l','e','r','i','a','\0'};
char target='a';
int resultado=strrem(palabra,target);
printf("%s\n",palabra);
printf("se eliminaron %d letras\n",resultado);
return 0;
}
int strrem(char *palabra, char target)
{
int borradas=0;
char *checkPoint=palabra;
while(*palabra!='\0')
{
if(*palabra==target)
{
checkPoint=palabra;
borradas++;
while(*checkPoint!='\0')
{
*checkPoint=*(checkPoint+1);
checkPoint++;
}
palabra--;
}
palabra++;
}
return borradas;
}
|
C
|
/*
* Rewrite the function lower, which converts upper case letter to lower case, with a conditional expression instead of if-else .
*/
#include <stdio.h>
char lower(char c);
int main()
{
printf("%c\n", lower('B'));
printf("%c\n", lower('A'));
return 0;
}
char lower(char c)
{
return c >= 'A' && c <= 'Z' ? c + 32 : c;
}
|
C
|
#include <sys/terminal.h>
#include <sys/utils.h>
#include <sys/kprintf.h>
#include <sys/kb.h>
terminal_t terminal;
char data_buffer[TERMINAL_BUFFER_SIZE];
uint8_t data_buffer_ready = 0;
void init_terminal() {
memset(&terminal, 0, sizeof(terminal));
terminal.buffer[0] = '>';
terminal.buffer[1] = ' ';
terminal.buffer[2] = '_';
terminal.buffer_offset = 3;
terminal.buffer_ready = TERMINAL_BUFFER_NOT_READY;
terminal_display(terminal.buffer);
}
static void reset_terminal() {
init_terminal();
}
void clear_terminal() {
char *temp1 = (char *)VIDEO_VIRT_MEM_BEGIN + 160*18;
int terminal_size = 480;
while (terminal_size > 0) {
*temp1 =' ';
temp1 += CHAR_WIDTH;
terminal_size--;
}
}
void terminal_display(const char *fmt) {
int row = 18;
int col = 4;
char *c;
char *temp = (char *)VIDEO_VIRT_MEM_BEGIN + 160*18;
clear_terminal();
for (c = (char *)fmt; *c; c += 1, temp += CHAR_WIDTH) {
if (row > 23) {
memcpy((char *)VIDEO_VIRT_MEM_BEGIN + 160*18, (char *)VIDEO_VIRT_MEM_BEGIN + 160*18 + SCREEN_WIDTH, 800);
temp -= SCREEN_WIDTH;
clear_chars(temp, SCREEN_WIDTH);
row = 23;
}
/* Line wrapping */
if (col == 81) {
row++;
col = 1;
c -= 1;
temp -= CHAR_WIDTH;
continue;
} else {
*temp = *c;
col++;
}
}
}
static void process_terminal_buffer() {
terminal.buffer[terminal.buffer_offset - 1] = '\0';
terminal.buffer[terminal.buffer_offset] = '\0';
memset(data_buffer, 0, sizeof(data_buffer));
memcpy(data_buffer, &(terminal.buffer[2]), strlen(&(terminal.buffer[2])));
terminal.buffer[terminal.buffer_offset - 1] = '\n';
}
int read_from_terminal(char *buffer, int size) {
while (data_buffer_ready == 0);
data_buffer_ready = 0;
int buff_len = strlen(data_buffer);
if (buff_len) {
if (buff_len > size) {
buff_len = size;
}
memcpy(buffer, data_buffer, buff_len);
return buff_len;
}
return -1;
}
void handle_keyboard_input(unsigned char glyph, int flags) {
if (flags == KEYCODE_BACKSPACE) {
/* Backspace */
if (terminal.buffer_offset > 3) {
terminal.buffer[terminal.buffer_offset - 2] = '_';
terminal.buffer[terminal.buffer_offset - 1] = ' ';
terminal.buffer_offset--;
terminal_display(terminal.buffer);
}
} else if (flags == KEYCODE_CTRL) {
/* Control */
if (glyph == 'M') {
/* Enter key pressed */
terminal.buffer[terminal.buffer_offset - 1] = '\0';
process_terminal_buffer();
terminal.buffer_ready = TERMINAL_BUFFER_READY;
data_buffer_ready = 1;
reset_terminal();
}
} else {
/* Normal characters */
if (terminal.buffer_offset < TERMINAL_BUFFER_SIZE - 1) {
data_buffer_ready = 0;
terminal.buffer_ready = TERMINAL_BUFFER_NOT_READY;
terminal.buffer[terminal.buffer_offset - 1] = glyph;
terminal.buffer[terminal.buffer_offset] = '_';
terminal.buffer_offset++;
terminal_display(terminal.buffer);
}
}
}
void Sleep_t() {
volatile int spin = 0;
while (spin < 40000000) {
spin++;
}
}
void write_to_terminal(const char *buff, int size) {
int i = 0;
while (size > 0) {
kprintf("%c", buff[i++]);
size--;
}
}
|
C
|
#include <stdio.h> // Header File
int main() // starting
{
int a = 10;
printf("Hello There!\nThis is my Value: %d\n", a);
return 0; // end
}
|
C
|
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#define PRINT_VALUE(XXX) \
printf(#XXX ": 0x%0llx\n", (unsigned long long) XXX);
int main() {
PRINT_VALUE(MAP_SHARED)
PRINT_VALUE(MAP_PRIVATE)
PRINT_VALUE(MAP_FIXED)
// PRINT_VALUE(MAP_LOCAL)
PRINT_VALUE(MAP_ANONYMOUS)
PRINT_VALUE(O_CREAT)
PRINT_VALUE(PROT_READ)
PRINT_VALUE(PROT_WRITE)
PRINT_VALUE(PROT_EXEC)
PRINT_VALUE(SEEK_SET)
PRINT_VALUE(SEEK_CUR)
PRINT_VALUE(SEEK_END)
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#define is_edgeExist(a, b) schdl[i].trans_num != schdl[j].trans_num && \
!strcmp(schdl[i].cmd, a) && \
!strcmp(schdl[j].cmd, b) && \
!strcmp(schdl[i].var, schdl[j].var)
#define putEdge adj_mat[schdl[i].trans_num - 1][schdl[j].trans_num - 1] = 1
#define err_msg(x) \
{ \
perror(x); \
exit(0); \
}
typedef struct nodes
{
int trans_num;
char *cmd;
char *var;
} NODE;
void to_low(char string[]);
int find_schedule_length(int, char *[]);
int build_schedule(int, char *[], NODE *, int);
void to_low(char string[])
{
int i = 0;
while (string[i])
{
string[i] = tolower(string[i]);
i++;
}
}
int find_schedule_length(int t, char *ptr[])
{
int length = 0;
int temp;
for (int i = 1; i < t; i++)
{
FILE *fp;
fp = fopen(ptr[i], "r");
if (!fp)
err_msg("error");
fscanf(fp, "%d", &temp);
length = length + temp;
fclose(fp);
}
return length;
}
int build_schdl(int t, char *ptr[], NODE *sdl, int total_len)
{
FILE *fp;
int len;
int sl_num;
char *str;
char *cmd;
char *var;
for (int i = 1; i < t; i++)
{
fp = fopen(ptr[i], "r");
fscanf(fp, "%d", &len);
for (int j = 1; j <= len; j++)
{
fscanf(fp, "%d %m[^\n\r]", &sl_num, &str);
if (sl_num > total_len)
err_msg("err:Invalid Inputs"); // error in case of invalid serial number
if (str == NULL)
str = " ";
cmd = strtok_r(str, "(", &str);
to_low(cmd);
if (!strcmp(cmd, "read") || !strcmp(cmd, "write"))
var = strtok_r(str, ")", &str);
else
var = "0";
sdl[sl_num] = (NODE){i, cmd, var}; //Assign values to schedule
}
fclose(fp);
}
return 1;
}
|
C
|
#include <passion.h>
#include <math.h>
enum ps_status ps_matrix_4_set_identity(struct ps_matrix_4 *this)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
memset(&this->data, 0, sizeof(float) * PS_MATRIX_4_SIZE);
this->data[0] = 1.0f;
this->data[5] = 1.0f;
this->data[10] = 1.0f;
this->data[15] = 1.0f;
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_set_raw_transformation(
struct ps_matrix_4 *this,
double t00, double t10, double t01, double t11, double x, double y
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
memset(&this->data, 0, sizeof(float) * PS_MATRIX_4_SIZE);
this->data[10] = 1.0f;
this->data[15] = 1.0f;
this->data[0] = (float)t00;
this->data[1] = (float)t10;
this->data[4] = (float)t01;
this->data[5] = (float)t11;
this->data[12] = (float)x;
this->data[13] = (float)y;
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_set_transformation(
struct ps_matrix_4 *this,
double x, double y, double angle,
double sx, double sy, float ox, float oy, double kx, double ky
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
memset(&this->data, 0, sizeof(float) * PS_MATRIX_4_SIZE);
float c = (float)cos(angle);
float s = (float)sin(angle);
this->data[10] = (float)1.0f;
this->data[15] = (float)1.0f;
this->data[0] = (float)(c * sx - ky * s * sy);
this->data[1] = (float)(s * sx + ky * c * sy);
this->data[4] = (float)(kx * c * sx - s * sy);
this->data[5] = (float)(kx * s * sx + c * sy);
this->data[12] = (float)(x - ox * this->data[0] - oy * this->data[4]);
this->data[13] = (float)(y - ox * this->data[1] - oy * this->data[5]);
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_set_ortho(struct ps_matrix_4 *this,
double left, double right, double bottom, double top
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
PS_STATUS_ASSERT(ps_matrix_4_set_identity(this));
this->data[0] = 2.0f / (float)(right - left);
this->data[5] = 2.0f / (float)(top - bottom);
this->data[10] = -1.0f;
this->data[12] = (float)(-(right + left) / (right - left));
this->data[13] = (float)(-(top + bottom) / (top - bottom));
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_multiply(struct ps_matrix_4 *op1,
struct ps_matrix_4 *op2,
struct ps_matrix_4 *out
)
{
PS_CHECK(op1 && op2 && out, PS_STATUS_INVALID_ARGUMENT);
struct ps_matrix_4 a = { 0 };
memcpy(&a, op1, sizeof(struct ps_matrix_4));
struct ps_matrix_4 b = { 0 };
memcpy(&b, op2, sizeof(struct ps_matrix_4));
out->data[0] = (a.data[0] * b.data[0]) + (a.data[4] * b.data[1]) + (a.data[8] * b.data[2]) + (a.data[12] * b.data[3]);
out->data[4] = (a.data[0] * b.data[4]) + (a.data[4] * b.data[5]) + (a.data[8] * b.data[6]) + (a.data[12] * b.data[7]);
out->data[8] = (a.data[0] * b.data[8]) + (a.data[4] * b.data[9]) + (a.data[8] * b.data[10]) + (a.data[12] * b.data[11]);
out->data[12] = (a.data[0] * b.data[12]) + (a.data[4] * b.data[13]) + (a.data[8] * b.data[14]) + (a.data[12] * b.data[15]);
out->data[1] = (a.data[1] * b.data[0]) + (a.data[5] * b.data[1]) + (a.data[9] * b.data[2]) + (a.data[13] * b.data[3]);
out->data[5] = (a.data[1] * b.data[4]) + (a.data[5] * b.data[5]) + (a.data[9] * b.data[6]) + (a.data[13] * b.data[7]);
out->data[9] = (a.data[1] * b.data[8]) + (a.data[5] * b.data[9]) + (a.data[9] * b.data[10]) + (a.data[13] * b.data[11]);
out->data[13] = (a.data[1] * b.data[12]) + (a.data[5] * b.data[13]) + (a.data[9] * b.data[14]) + (a.data[13] * b.data[15]);
out->data[2] = (a.data[2] * b.data[0]) + (a.data[6] * b.data[1]) + (a.data[10] * b.data[2]) + (a.data[14] * b.data[3]);
out->data[6] = (a.data[2] * b.data[4]) + (a.data[6] * b.data[5]) + (a.data[10] * b.data[6]) + (a.data[14] * b.data[7]);
out->data[10] = (a.data[2] * b.data[8]) + (a.data[6] * b.data[9]) + (a.data[10] * b.data[10]) + (a.data[14] * b.data[11]);
out->data[14] = (a.data[2] * b.data[12]) + (a.data[6] * b.data[13]) + (a.data[10] * b.data[14]) + (a.data[14] * b.data[15]);
out->data[3] = (a.data[3] * b.data[0]) + (a.data[7] * b.data[1]) + (a.data[11] * b.data[2]) + (a.data[15] * b.data[3]);
out->data[7] = (a.data[3] * b.data[4]) + (a.data[7] * b.data[5]) + (a.data[11] * b.data[6]) + (a.data[15] * b.data[7]);
out->data[11] = (a.data[3] * b.data[8]) + (a.data[7] * b.data[9]) + (a.data[11] * b.data[10]) + (a.data[15] * b.data[11]);
out->data[15] = (a.data[3] * b.data[12]) + (a.data[7] * b.data[13]) + (a.data[11] * b.data[14]) + (a.data[15] * b.data[15]);
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_set_translation(struct ps_matrix_4 *this,
double x, double y
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
PS_STATUS_ASSERT(ps_matrix_4_set_identity(this));
this->data[12] = (float)x;
this->data[13] = (float)y;
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_translate(struct ps_matrix_4 *this,
double x, double y
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
struct ps_matrix_4 tmp = { 0 };
PS_STATUS_ASSERT(ps_matrix_4_set_translation(&tmp, x, y));
return ps_matrix_4_multiply(this, &tmp, this);
}
enum ps_status ps_matrix_4_set_rotation(struct ps_matrix_4 *this,
double radians
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
PS_STATUS_ASSERT(ps_matrix_4_set_identity(this));
double c = cos(radians);
double s = sin(radians);
this->data[0] = (float)c;
this->data[4] = (float)-s;
this->data[1] = (float)s;
this->data[5] = (float)c;
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_rotate(struct ps_matrix_4 *this,
double radians
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
struct ps_matrix_4 tmp = { 0 };
PS_STATUS_ASSERT(ps_matrix_4_set_rotation(&tmp, radians));
return ps_matrix_4_multiply(this, &tmp, this);
}
enum ps_status ps_matrix_4_set_scale(struct ps_matrix_4 *this,
double sx, double sy
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
PS_STATUS_ASSERT(ps_matrix_4_set_identity(this));
this->data[0] = (float)sx;
this->data[5] = (float)sy;
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_scale(struct ps_matrix_4 *this,
double sx, double sy
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
struct ps_matrix_4 tmp = { 0 };
PS_STATUS_ASSERT(ps_matrix_4_set_scale(&tmp, sx, sy));
return ps_matrix_4_multiply(this, &tmp, this);
}
enum ps_status ps_matrix_4_set_shear(struct ps_matrix_4 *this,
double kx, double ky
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
PS_STATUS_ASSERT(ps_matrix_4_set_identity(this));
this->data[1] = (float)kx;
this->data[4] = (float)ky;
return PS_STATUS_SUCCESS;
}
enum ps_status ps_matrix_4_shear(struct ps_matrix_4 *this,
double kx, double ky
)
{
PS_CHECK(this, PS_STATUS_INVALID_ARGUMENT);
struct ps_matrix_4 tmp = { 0 };
PS_STATUS_ASSERT(ps_matrix_4_set_shear(&tmp, kx, ky));
return ps_matrix_4_multiply(this, &tmp, this);
}
|
C
|
/*
** my_malloc.c for in /home/courne_l/rendu/synthese/FASTAtools/srcs
**
** Made by courneil lucasc
** Login <[email protected]>
**
** Started on Mon Jun 20 09:43:34 2016 courneil lucasc
** Last update Mon Jun 20 09:43:36 2016 courneil lucasc
*/
#include <stdlib.h>
void *my_malloc(unsigned int t)
{
char *str;
if (!(str = malloc(sizeof(char) * t)))
return (NULL);
return (str);
}
|
C
|
/* Write a program to copy one string into another and count the number of characters copied*/
#include<stdio.h>
int main(){
char o[1000],d[1000];
int i;
printf("Enter a string:\t");
gets(o);
for(i=0;o[i]!='\0';i++){
d[i]=o[i];
}
printf("Length of string: %d\n",i);
printf("Coppied string: %s\n",d);
return 0;
}
|
C
|
/*
* vdsp_abs.c
* AccelerateTest
*
* Created by sonson on 10/08/15.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#include "vdsp_abs.h"
static void check_absolute_value(float *a, float *b, int size) {
for (int i = 0; i < size; i++) {
if (*(b + i) != fabsf(*(a + i))) {
printf("check_absolute_value->error\n");
return;
}
}
printf("check_absolute_value->OK\n");
}
static double test_cpu_abs(int size, int test_count) {
srandom(time(NULL));
CFAbsoluteTime startTime;
float *destination = NULL;
float *source = NULL;
// alloc objects
destination = (float*)malloc(size * sizeof(float));
source = (float*)malloc(size * sizeof(float));
// initialize two vectors
for (int i = 0; i < size; i++) {
*(destination + i) = 0;
*(source + i) = 10 - rand()%10;
}
// use CPU
startTime = CFAbsoluteTimeGetCurrent();
for (int c = 0; c < test_count; c++) {
for (int i = 0; i < size; i++) {
*(destination + i) = fabsf(*(source + i));
}
}
double t = ((CFAbsoluteTimeGetCurrent() - startTime)*1000.0f);
check_absolute_value(source, destination, size);
// release objects
free(source);
free(destination);
return t;
}
static double test_vDSP_abs(int size, int test_count) {
srandom(time(NULL));
CFAbsoluteTime startTime;
float *destination = NULL;
float *source = NULL;
// alloc objects
destination = (float*)malloc(size * sizeof(float));
source = (float*)malloc(size * sizeof(float));
// initialize two vectors
for (int i = 0; i < size; i++) {
*(destination + i) = 0;
*(source + i) = 10 - rand()%10;
}
// use vDSP
startTime = CFAbsoluteTimeGetCurrent();
for (int c = 0; c < test_count; c++) {
vDSP_vabs(source, 1, destination, 1, size);
}
double t = ((CFAbsoluteTimeGetCurrent() - startTime)*1000.0f);
// check
check_absolute_value(source, destination, size);
// release objects
free(source);
free(destination);
return t;
}
void test_abs() {
printf("--------------------------------------------------------------------------------\n");
printf("test_abs\n");
printf("--------------------------------------------------------------------------------\n");
for (int size = 2; size <= 8192; size *=16 ) {
int test_count = 100;
printf("----------------------------------------\n");
printf("Condition\n");
printf(" %d-dim vec\n", size);
printf(" test, %d times\n", test_count);
CFAbsoluteTime t1 = test_vDSP_abs(size, test_count);
CFAbsoluteTime t2 = test_cpu_abs(size, test_count);
printf("----------------------------------------\n");
printf("Result\n");
printf("Accelerate.framework\n");
printf(" %f msec\n", t1);
printf("Normal\n");
printf(" %f msec\n", t2);
}
printf("\n");
}
|
C
|
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <sys/stat.h>
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
static void* memdup(void* ptr, int size)
{
void* ret = malloc(size);
memcpy(ret, ptr, size);
return ret;
}
static int fsize(char* filename)
{
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
// adds null byte, but also optionally returns size
static char* readfile(char* fname, int* _size)
{
FILE* f = fopen(fname, "rb"); if (!f) return 0;
int size = fsize(fname); char* buf = calloc(size + 1, 1);
fread(buf, 1, size, f); fclose(f);
if(_size) *_size = size; return buf;
}
|
C
|
#include <stdio.h>
int main ()
{
char ao=162, ai=161;
//Salto de linea
printf ("Ejemplo salto de l%cnea\n",ai);
printf ("Holaa\n");
printf ("Adi%cs\n\n",ao);
//Tab horizontal
printf ("Ejemplo tabulador\n");
printf ("Holaa\t");
printf ("Adi%cs\n\n",ao);
//Alarma
printf ("Ejemplo alarma\n");
printf ("Holaa\a");
printf ("Adi%cs\n\n",ao);
//Retroceso de carro
printf ("Ejemplo retroceso de carro\n");
printf ("Holaa\r");
printf ("Adi%cs\n\n",ao);
//Retroceso
printf ("Ejemplo retroceso\n");
printf ("Holaa\b");
printf ("Adi%cs\n\n",ao);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "aloca.h"
#include "leitura.h"
#include "processamento.h"
#include "saida.h"
int main(int argc, char* argv[]){
/*Abre os arquivos com caminho em argv*/
FILE* in = fopen(argv[1],"r");
FILE* out = fopen(argv[2],"w");
int n, m;
fscanf(in,"%d %d",&n,&m);
/*Declaração dinâmica do mapa e de uma matriz de visitados.
O motivo de criar um 'visitados' está no módulo de processamento.*/
char** mapa = calloc(n,sizeof(char *));
int** visitado = calloc(n,sizeof(int *));
/*Aloca a memória necessária para as matrizes*/
aloca_mem(n,m,mapa,visitado);
/*Realiza a leitura de dados do arquivo*/
leitura(n,m,mapa,visitado,in);
/*Processa a entrada*/
processa(n,m,mapa,visitado,out);
/*Libera a memória alocada*/
libera_mem(n,m,mapa,visitado);
/*Fecha os arquivos*/
fclose(in);
fclose(out);
return 0;
}
|
C
|
/* Operadores de pre- o post-incremento(decremento) */
#include <stdio.h>
main()
{
int w, x, y, z, resultado;
w = x = y = z = 1; /* inicializamos x e y */
printf("Dado un w = %d, x = %d, y = %d, and z = %d,\n", w, x, y, z);
resultado = ++w;
printf("++w tiene el valor de : %d\n", resultado);
resultado = x++;
printf("x++ tiene el valor de : %d\n", resultado);
resultado = --y;
printf("--y tiene el valor de : %d\n", resultado);
resultado = z--;
printf("z-- tiene el valor de : %d\n", resultado);
return 0;
}
|
C
|
/*---- I can do it ----*/
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void)
{
long unsigned int n, j, i, a;
int arr[20], sum1, sum2, temp, sum;
while(1)
{
scanf("%lu", &n);
j = pow(10, 15);
i = n/j;
if(i>=1 && i<=9) // condition for fixing the input to 16 digits only
break;
}
a = n;
for(i=0; i<16; i++)
{
arr[i] = n%10;
n = n/10;
} sum1 = 0;
for(i=1; i<16; i=i+2)
{
temp = arr[i]*2;
if(temp/10 >= 1 && temp/10 <= 9)
{
temp = temp - 9;
}
sum1 = sum1 + temp; // sum of all doubled digits
}
sum2 = 0;
for(i=0; i<16; i=i+2)
{
sum2 = sum2 + arr[i]; //Sum of digits at odd position from right
}
sum = sum1+sum2;
printf("sum = %d\n", sum);
if(sum%10==0)
printf("Credit card number %lu is valid\n", a);
else
printf("Credit card number %lu is not valid\n", a);
return 0;
}
|
C
|
#ifndef SHARED_SOCKET_H_
#define SHARED_SOCKET_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <commons/collections/list.h>
#include "_common_includes.h"
#include "protocol.h"
#define BACKLOG 100
typedef struct {
int socket;
e_emisor conectado;
__SOCKADDR_ARG addr;
} t_conexion;
int socket_a_destruir;
/**
* @NAME: socket_create_listener
* @DESC: Creo un socket de escucha y lo devuelvo, o -1 se hubo error. Me pongo a escuchar.
* @PARAMS:
* ip - ip del server. Si es NULL, usa el localhost: 127.0.0.1
* port - puerto en el que escuchar
*/
int socket_create_listener(char* ip, char* port);
/**
* @NAME: socket_connect_to_server
* @DESC: Me conecto al server, y devuelvo el socket, o -1 si hubo error
*/
int socket_connect_to_server(char* ip, char* port);
/**
* @NAME: socket_aceptar_conexion
* @DESC: Acepta una nueva conexión y devuelve el nuevo socket conectado
*/
int socket_aceptar_conexion(int socket_servidor);
/**
* @NAME: socket_get_ip
* @DESC: Devuelve la IP de un socket
*/
char* socket_get_ip(int fd);
/**
* @NAME: socket_start_listening_select
* @DESC: Gestiona eventos en un socket con la funcion que es parametro + en los FD adicionales
* @PARAMS:
* socketListener -
* manejadorDeEvento - funcion a llamar en el caso de un evento con un descriptor de archivo
* ... - FD adicionales a multiplexar. Al principio, se debe indicar la cantidad de FDs, y para c/u su emisor y el tipo de msj.
* Ejemplos:
* 1, SAFA, INOTIFY, fd_inotify
* 2, SAFA, INOTIFY, fd_inotify1, SAFA, INOTIFY, fd_inotify2
*/
void socket_start_listening_select(int socketListener, int (*manejadorDeEvento)(int, t_msg*), ...);
#endif /* SHARED_SOCKET_H_ */
|
C
|
#include<tm_stack.h>
#include<stdio.h>
int main()
{
int succ;
int x1,x2,x3,x4;
int *x;
x1=100;
x2=200;
x3=300;
x4=400;
Stack *stack;
stack=createStack(&succ);
if(stack==false)
{
printf("Unable to create Stack\n");
return 0;
}
pushOnStack(stack,&x1,&succ);
if(succ) printf("%d pushed on stack\n",x1);
else printf("%d unable to pushed on stack\n",x1);
pushOnStack(stack,&x2,&succ);
if(succ) printf("%d pushed on stack\n",x2);
else printf("%d unable to pushed on stack\n",x2);
pushOnStack(stack,&x3,&succ);
if(succ) printf("%d pushed on stack\n",x3);
else printf("%d unable to pushed on stack\n",x3);
pushOnStack(stack,&x4,&succ);
if(succ) printf("%d pushed on stack\n",x4);
else printf("%d unable to pushed on stack\n",x4);
printf("Size of Stack : %d\n",getSizeOfStack(stack));
if(isStackEmpty(stack)) printf("Stack is Empty\n");
else printf("Stack is not Empty\n");
x=(int *)elementAtTopOfStack(stack,&succ);
printf("Element at top of stack is %d\n",*x);
printf("Now Popping all elements from stack\n");
while(!isStackEmpty(stack))
{
x=(int *)popFromStack(stack,&succ);
printf("%d popped from stack\n",*x);
}
destroyStack(stack);
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int c, q;
float total;
scanf("%d %d", &c, &q);
if(c == 1){
total = q*4;
}else if(c == 2){
total = q*4.5;
}else if(c == 3){
total = q*5;
}else if(c == 4){
total = q*2;
}else if(c == 5){
total = q*1.5;
}
printf("Total: R$ %.2f\n", total);
return 0;
}
|
C
|
void main(){
unsigned cnt; // Define variable cnt
void interrupt() {
cnt++; // Interrupt causes cnt to be incremented by 1
TRISB_bit = 0x01; // PORTB is returned its initial value
}
void main() {
ANSEL = 0; // All I/O pins are configured as digital
ANSELH = 0;
TRISB_bit = 0; // All port B pins are configured as outputs
cnt = 0; // Variable cnt is assigned a 0
do { // Endless loop
if (cnt == 400) { // Increment port B after 400 interrupts
PORTB = PORTB++; // Increment number on port B by 1
cnt = 0; // Reset variable cnt
}
} while(1);
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int res;
int is_wait;
pthread_cond_t cond; //条件变量
pthread_mutex_t mutex; //互斥锁
}Result;
//定义计算结果的线程
void *set_fn(void *arg)
{
sleep(5);
int i = 1, sum = 0;
for(; i <= 100; i++){
sum += i;
}
Result *r = (Result*)arg;
r->res = sum;
//对共享资源进行加锁
pthread_mutex_lock(&r->mutex);
while(!r->is_wait){
pthread_mutex_unlock(&r->mutex);
usleep(200);
pthread_mutex_lock(&r->mutex);
}
pthread_mutex_unlock(&r->mutex);
pthread_cond_broadcast(&r->cond);
return (void*)0;
}
//定义获取结果的线程
void *get_fn(void *arg)
{
//sleep(5);
Result *r = (Result*)arg;
//对共享资源进行加锁
pthread_mutex_lock(&r->mutex);
r->is_wait = 1;
pthread_cond_wait(&r->cond, &r->mutex);
//释放锁
pthread_mutex_unlock(&r->mutex);
int res = r->res;
printf("0x%lx get the result is %d\n", pthread_self(), res);
return (void*)0;
}
//主函数
int main(int argc, char *argv[])
{
int err;
pthread_t cal, get;
Result r;
r.is_wait = 0;
//初始化条件变量和互斥锁
pthread_cond_init(&r.cond, NULL);
pthread_mutex_init(&r.mutex, NULL);
if ((err = pthread_create(&get, NULL, get_fn, (void*)&r)) != 0) {
perror("pthread create error");
}
if ((err = pthread_create(&cal, NULL, set_fn, (void*)&r)) != 0) {
perror("pthread create error");
}
pthread_join(get, NULL);
pthread_join(cal, NULL);
pthread_cond_destroy(&r.cond);
pthread_mutex_destroy(&r.mutex);
return 0;
}
|
C
|
#include <stdio.h>
struct distance
{
int meters;
int kilo;
}d1, d2, sum;
int main()
{
printf("Enter value of d1 in meters\n");
scanf("%d", &d1.meters);
printf("Enter value of d1 in kilometers\n");
scanf("%d", &d1.kilo);
printf("Enter value of d2 in meters\n");
scanf("%d", &d2.meters);
printf("Enter the value of d2 in kilos\n");
scanf("%d", &d2.kilo);
sum.meters = d1.meters + d2.kilo;
sum.kilo = d1.kilo + d2.kilo;
if(sum.meters>=1000)
{
sum.meters=sum.meters%1000;
sum.kilo++;
}
printf("%d %d", sum.meters, sum.kilo);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void shift(char, int **);
void changeByte(char, int *);
void jumpForward(char **);
void jumpBackward(char **);
void loadInput(int *);
void output(int);
void processCommand(char **, int **);
void runCode(char *);
int main(void) {
char code[] = "++++++++++[>>++++++>+++++++++++>++++++++++>+++++++++>+++>+++++>++++>++++++++>+[<]<-]>>+++++++.>+.-.>+++.<++++.>>+++++++.<<++.+.>+++++.>.<<-.>---.<-----.-.+++++.>>>+++.-.<<-.<+..----.>>>>++++++++.>+++++++..<<<<+.>>>>-.<<<<.++++.------.<+++++.---.>>>>>.<<<++.<<---.>++++++.>>>>+.<<<-.--------.<<+.>>>>>>+++.---.<-.<<<<---.<.>---.>>>>>>.";
runCode(code);
return 0;
}
void shift(char command, int ** bytes) {
*bytes += command == '>' ? 1 : -1;
}
void changeByte(char command, int * bytes) {
*bytes += command == '+' ? 1 : -1;
}
void jumpForward(char ** command) {
int brackets = 0;
while(**command != ']' || brackets != 0) {
if(**command == '[' || **command == ']') {
brackets -= **command == ']' ? 1 : -1;
}
++*command;
}
}
void jumpBackward(char ** command) {
int brackets = 0;
while(*(*command + 1) != '[' || brackets != 0) {
if(**command == '[' || **command == ']') {
brackets -= **command == '[' ? 1 : -1;
}
--*command;
}
}
void loadInput(int * bytes) {
*bytes = getchar();
}
void output(int bytes) {
putchar(bytes);
}
void processCommand(char ** command, int ** bytes) {
char character = **command;
if(character == '>' || character == '<') {
shift(character, bytes);
}
else if(character == '+' || character == '-') {
changeByte(character, *bytes);
}
else if(character == '[') {
if(**bytes == 0) {
jumpForward(command);
}
}
else if(character == ']') {
if(**bytes != 0) {
jumpBackward(command);
}
}
else if(character == ',') {
loadInput(*bytes);
}
else {
output(**bytes);
}
}
void runCode(char * code) {
int bytes[10000] = { 0 };
int *pointer = bytes;
char *command = code;
const char *codeEnd = code + strlen(code);
while(command < codeEnd) {
processCommand(&command, &pointer);
command++;
}
}
|
C
|
struct studentdetails{
char *stdname;
char *stddept;
char sec;
int stdid;
}
testcases[2]={
{"Jagadeesh","cse",'A',28765},
{"anil","cse",'A',28766}
};
void print(int);
void main()
{
int i;
printf("Enter Studentid to print details");
scanf("%d",&i);
print(i);
}
void print(int i)
{
int j,c=0;
for(j=0;j<1;j++)
{
if(i==testcases[j].stdid)
{
c++;
printf("Studentname:%s\nDepartment:%s\nSection:%c\nStudentid%d",testcases[j].stdname,testcases[j].stddept,testcases[j].sec,testcases[j].stdid);
}
}
if(c==0)
printf("Invalid StudentID");
}
|
C
|
/* ucc --- compile a C program, Unix style */
/* flags for c1 */
int a_flag = FALSE; /* abort after errors */
int f_flag = FALSE; /* do not include =cdefs= */
int u_flag = FALSE; /* be more UNIX compatible */
int y_flag = FALSE; /* run "lint" */
int I_flag = FALSE; /* use the provided include directories */
int D_flag = FALSE; /* define variables */
/* flags for vcg */
int s_flag = FALSE; /* produce PMA in named file */
int b_flag = FALSE; /* produce object text in named file */
char *b_name = ""; /* object file name */
char *s_name = ""; /* PMA file name */
char *u_number = ""; /* optional number for c1's -u flag */
char *incls[MAXARGV]; /* list of include directories */
char *defs[MAXARGV]; /* list of defines */
int incl_index = 0; /* index into incls */
int def_index = 0; /* index into defs */
char *pass_on[MAXARGV]; /* stuff to pass on to 'compile' */
int p_index = 0; /* index into pass_on */
char *strrchr(); /* declare function */
main(argc, argv)
int argc;
char **argv;
{
int i;
if (argc == 1)
usage ();
for (i = 1; i < argc; i++)
switch (argv[i][0]) {
case '-':
switch (argv[i][1]) {
case 'a':
a_flag = TRUE;
break;
case 'b':
b_flag = TRUE;
if (argv[i][2] != '\0')
b_name = & argv[i][2];
else if (i + 1 < argc && argv[i+1][0] != '-')
{
i++;
b_name = argv[i];
}
break;
case 'f':
f_flag = TRUE;
break;
case 's':
s_flag = TRUE;
if (argv[i][2] != '\0')
s_name = & argv[i][2];
else if (i + 1 < argc && argv[i+1][0] != '-')
{
i++;
s_name = argv[i];
}
break;
case 'u':
u_flag = TRUE;
if (argv[i][2] != '\0')
u_number = & argv[i][2];
else if (i + 1 < argc && argv[i+1][0] != '-')
{
i++;
u_number = argv[i];
}
break;
case 'y':
y_flag = TRUE;
break;
case 'D':
D_flag = TRUE;
if (argv[i][2] != '\0')
defs[def_index++] = & argv[i][2];
else if (i + 1 < argc && argv[i+1][0] != '-')
{
defs[def_index++] = argv[i+1];
i++;
}
else
usage();
break;
case 'I':
I_flag = TRUE;
if (argv[i][2] != '\0')
incls[incl_index++] = & argv[i][2];
else if (i + 1 < argc && argv[i+1][0] != '-')
{
incls[incl_index++] = argv[i+1];
i++;
}
else
usage();
break;
default:
pass_on[p_index++] = argv[i];
break;
}
break;
default:
pass_on[p_index++] = argv[i];
break;
}
shell_commands ();
}
/* shell_commmands --- write out shell commands to compile a program */
shell_commands()
{
int i;
printf ("declare _search_rule = \"^int,^var,=bin=/&\"\n");
printf ("compile -m c ");
if (a_flag || f_flag || y_flag || u_flag || s_flag || b_flag
|| I_flag || D_flag)
{
printf("-C '");
if (a_flag)
printf ("-a ");
if (f_flag)
printf ("-f ");
if (y_flag)
printf ("-y ");
if (u_flag)
printf ("-u %s ", u_number);
if (s_flag)
printf ("-s %s ", s_name);
if (b_flag)
printf ("-b %s ", b_name);
for (i = 0; i < def_index; i++)
printf ("-D%s ", defs[i]);
for (i = 0; i < incl_index; i++)
printf ("-I %s ", incls[i]);
printf ("' ");
}
for (i = 0; i < p_index; i++)
printf ("'%s' ", pass_on[i]);
printf ("\n");
}
/* usage --- print Usage message and exit */
usage()
{
fprintf (stderr, "Usage: ucc { <path_name> }\n");
fprintf (stderr, " [<cc_opts>][<compile_opts>]\n");
exit (1);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a=5;
float f=((float)a)/4;
printf("%f\n",f);
srand(time(0));
for(int i=0;i<10;i++)
{
printf("%d\n",rand()%15);
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** sticky_bit.c
** File description:
** manage special case
*/
#include "my.h"
void sticky_2(t_ls *ls, struct stat fs)
{
if (!(fs.st_mode & S_IXGRP) && !(fs.st_mode & S_ISGID))
ls->x_oth = '-';
if ((fs.st_mode & S_IXOTH) && (fs.st_mode & S_ISVTX))
ls->x_oth = 't';
if (!(fs.st_mode & S_IXOTH) && (fs.st_mode & S_ISVTX))
ls->x_oth = 'T';
if ((fs.st_mode & S_IXOTH) && !(fs.st_mode & S_ISVTX))
ls->x_oth = 'x';
if (!(fs.st_mode & S_IXOTH) && !(fs.st_mode & S_ISVTX))
ls->x_oth = '-';
ls->r_usr = (fs.st_mode & S_IRUSR)?'r':'-';
ls->w_usr = (fs.st_mode & S_IWUSR)?'w':'-';
ls->r_grp = (fs.st_mode & S_IRGRP)?'r':'-';
ls->w_grp = (fs.st_mode & S_IWGRP)?'w':'-';
ls->r_oth = (fs.st_mode & S_IROTH)?'r':'-';
ls->w_oth = (fs.st_mode & S_IWOTH)?'w':'-';
}
void sticky(t_ls *ls, struct stat fs)
{
if ((fs.st_mode & S_IXUSR) && (fs.st_mode & S_ISUID))
ls->x_usr = 's';
if (!(fs.st_mode & S_IXUSR) && (fs.st_mode & S_ISUID))
ls->x_usr = 'S';
if ((fs.st_mode & S_IXUSR) && !(fs.st_mode & S_ISUID))
ls->x_usr = 'x';
if (!(fs.st_mode & S_IXUSR) && !(fs.st_mode & S_ISUID))
ls->x_usr = '-';
if ((fs.st_mode & S_IXGRP) && (fs.st_mode & S_ISGID))
ls->x_grp = 's';
if (!(fs.st_mode & S_IXGRP) && (fs.st_mode & S_ISGID))
ls->x_grp = 'S';
if ((fs.st_mode & S_IXGRP) && !(fs.st_mode & S_ISGID))
ls->x_grp = 'x';
if (!(fs.st_mode & S_IXGRP) && !(fs.st_mode & S_ISGID))
ls->x_grp = '-';
sticky_2(ls, fs);
}
|
C
|
/*******************************************************************************
* Application: Demo code for Temp sensor using ADC1 Channel-16
* Edition: Version:1.0
* Company:
* Time: September 2015
*******************************************************************************/
#include "hhd32f1xx.h"
#include "hhd_sys.h"
#include "hhd_adc.h"
#include "hhd_uart.h"
#include "hhd_gpio.h"
#include<string.h>
#include<stdio.h>
#define T25ADC 0xBA3 //25 ADCIJֵ
#define ADCREF (double)(3.34) //ADC οѹ
#define ADCSTEP (double)(0.008*4096/ADCREF) //1 0.008V
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
uint32_t temp;
//uint16_t led = 0x200;
uint16_t led = 0x01;
//uint16_t led = 0x04;
void delay1us(uint32_t time);
void UART1_IOCFG(void);
/*****************************************************************************
* Function name: Main Function
*
* Descriptions: Initial device
*
* parameters: None
* Returned value: None
*
*****************************************************************************/
int main(void)
{
uint32_t i;
/* -------------- System initialization ---------------------------------*/
SystemInit();
//SystemCoreClockUpdate();
/* --------- GPIOA Periph clock enable --------------*/
ENABLEGPIOBCLK;
ENABLEGPIOCCLK;
ENABLEGPIODCLK;
GPIO_ConfigPinsAsOutput(GPIOB, PIN9);
GPIO_ConfigPinsAsOutput(GPIOC, PIN0);
GPIO_ConfigPinsAsOutput(GPIOD, PIN2);
/*UART1 Configuration*/
UART1_IOCFG();
UART_Open(UART1,115200,UART_NO_PARITY,UART_RX_HALF_FULL);
printf("\r\n----------------ADC Test---------------\r\n");
/* -------------- Initial ADC -------------------------------------------*/
/* Power up ADC analog module -------------------------------------------*/
/* set Channel 1 as convertion channel ----------------------------------*/
/* -------------- Config ADC1 Channel 16 IO -----------------------------*/
OpenADC1_IN16;
/* -------------- Initialise ADC1,and set Sample speed ------------------*/
/* -------------- Temp sensor is connected to ADC1 channel 16 -----------*/
ADC_Init(ADC1,100000);
/* -------------- Each ADC has 1-16 analog channel,
we set channel 16 to sample buffer DR0,
you can also set channel 15 to DR1,and so on. -----*/
ADC_SetupChannels(ADC1,DR1EN,CHN16_DR1,BURSTMODE);
#ifdef ADC_INT_ENABLE
ADC_EnableConversionInt(ADC1,1);
NVIC_EnableIRQ(ADC1_2_IRQn);
#endif
/* ---------- Delay 100us after ADC power-on ----------------------------*/
delay1us(0xffff);
while(1)
{
double vol = 0.0;
double temperature = 0.0;
temp = 0;
/* ---------- Sample 500ms ADC data -------------------------------------*/
for (i=0;i<1024;i=i+1)
{
/* use delay or Interrupt mode to read back temp sensor data ---------*/
delay1us(5000);
/* ---------- Get ADC data from DR0 of ADC ----------------------------*/
temp += ADC_GetConversionData(ADC1,ADC_DR1);
}
temp = temp>>10;
if(temp > T25ADC)
{
temperature = 25.0 - ((double)(temp) - (double)(T25ADC)) / ADCSTEP;
}
else
{
temperature = 25.0 + ((double)(T25ADC) - (double)(temp)) / ADCSTEP;
}
printf("The temperature is: %.1f \r\n", temperature);
printf("The temp value is: 0x%x\r\n", temp);
temp = temp * 333 / 4095;
vol = (double)(temp) / 100.0;
printf("The ADC12_IN16 capture voltage is: %.3f V \r\n",vol);
led = ~led;
//GPIO_WritePort(GPIOB, led);
GPIO_WritePort(GPIOC, led);
}
return 0;
}
void delay1us(uint32_t time)
{
while(time--);
}
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the USART */
// USART_SendData(USART1, (uint8_t) ch); /*һַ*/
UART_ByteWrite(UART1, (uint8_t) ch);
/* Loop until the end of transmission */
while((UART_GetStatus(UART1) & UART_TX_EMPTY) == 1 )
{}
//while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)/*ȴ*/
//{
// }
return ch;
}
/**----------------------------------------------------------------------------
** @Function: UART1_IOCFG
**
** @Descriptions: UART GPIO Configuration
**
** @parameters:
**
**
**
** @Returned: none
**
** @Author: MCU Application Team
**
** @Date: 28-June-2017
**
-------------------------------------------------------------------------------*/
void UART1_IOCFG(void)
{
/* you can config UART1 RX from PB7,
and you can config UART1 TX to PB6 --------------------------------*/
#if 0
IOCON->PB6.bit.FUNC = UART1_TX_to_PB6;
IOCON->PB6.bit.PUE = 1;
IOCON->PB7.bit.FUNC = UART1_RX_from_PB7;
IOCON->PB7.bit.PUE = 1;
#else
IOCON->PA9.bit.FUNC = UART1_TX_to_PA9;
IOCON->PA9.bit.PUE = 1;
IOCON->PA10.bit.FUNC = UART1_RX_from_PA10;
IOCON->PA10.bit.PUE = 1;
#endif
}
|
C
|
#include "otp.h"
#include "hmac.h"
#ifdef REGULAR
#include <time.h>
#else
#include "time.h"
#endif
uint32_t hotp(uint8_t* key, size_t keylen, uint32_t count, size_t digits)
{
uint8_t digest[20];
// Convert bytes to an array of bytes
uint8_t bytes[8] = {0};
/* bytes[0] = (count >> 56) & 0xFF; */
/* bytes[1] = (count >> 48) & 0xFF; */
/* bytes[2] = (count >> 40) & 0xFF; */
/* bytes[3] = (count >> 32) & 0xFF; */
bytes[4] = (count >> 24) & 0xFF;
bytes[5] = (count >> 16) & 0xFF;
bytes[6] = (count >> 8) & 0xFF;
bytes[7] = (count) & 0xFF;
hmac_sha1(digest, key, bytes, keylen, 8);
// Truncate digest based on the RFC4226 Standard
// https://tools.ietf.org/html/rfc4226#section-5.4
uint32_t offset = digest[19] & 0xf ;
uint32_t bin_code = (uint32_t)(digest[offset] & 0x7f) << 24
| (uint32_t)(digest[offset+1] & 0xff) << 16
| (uint32_t)(digest[offset+2] & 0xff) << 8
| (uint32_t)(digest[offset+3] & 0xff);
// Specification says that the implementation MUST return
// at least a 6 digit code and possibly a 7 or 8 digit code
switch (digits)
{
case 8:
return bin_code % 100000000;
case 7:
return bin_code % 10000000;
default:
return bin_code % 1000000;
}
}
uint32_t totp(uint8_t* key, size_t keylen, size_t timestep, size_t digits)
{
#ifdef REGULAR
uint32_t count = time(NULL) / timestep;
#else
uint32_t count = getEpochTime() / timestep;
#endif
return hotp(key, keylen, count, digits);
}
|
C
|
#include "mssv.h"
pthread_mutex_t mutex; // Mutex
pthread_cond_t use; // condition for if the global variable is in use
int **buff1, *buff2, *counter, maxDelay, inUse;
Region *regions;
int main (int argc, char* argv[])
{
// Validate command line parameters
validateUse(argc, argv);
// Rename command line parameters
char* inputFile = argv[1];
maxDelay = atoi(argv[2]);
// Variables
pthread_t threads[11];
// Allocate memory
initMemory( &buff1, &buff2, &counter, ®ions);
*counter = 0;
// Read input file
readFile(inputFile, NINE, NINE, &buff1);
// Initialise mutex and condition
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&use, NULL);
inUse = 0;
// Create threads
for(int i = 0; i < NUMTHREADS; i++)
{
if ( i < NINE) // Initialise region struct for row threads
{
regions[i].type = ROW;
}
else if( i == NINE) // Initialise region struct for columns thread
{
regions[i].type = COL;
}
else // Initialise region struct for sub-grids thread
{
regions[i].type = SUB_GRID;
}
regions[i].position = i;
resetArray(regions[i].numbers);
// Create thread
pthread_create(&(threads[i]), NULL, childManager, &(regions[i]));
inUse++;
}
parentManager(); // Parent logic
cleanMemory(); // Clean up malloc'd memory
}
/******************************************************************************/
/**
* Initalise memory constructs
* @param buff1 buffer1 2D array
* @param buff2 buffer2 1D array
* @param counter counter variable
* @param regions Region struct 1D array
*/
void initMemory(int*** buff1, int** buff2, int** counter, Region** regions)
{
// Initialise
*buff1 = (int**) malloc(sizeof(int*)* NINE);
for (int i = 0; i < NINE; i++)
{
(*buff1)[i] = (int*) malloc(sizeof(int)* NINE);
}
*buff2 = (int*) malloc(sizeof(int)* NUMTHREADS);
*counter = (int*) malloc(sizeof(int));
*regions = (Region*) malloc(sizeof(Region)* NUMTHREADS);
}
/**
* Free malloc'd memory and destroy mutex and conditions
*/
void cleanMemory()
{
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&use);
for (int i = 0; i < NINE; i++)
{
free(buff1[i]);
}
free(buff1);
free(buff2);
free(counter);
free(regions);
}
/**
* Read the contents of the input file passed as a command line argument
* @param inputFile File to be read
* @param rows Number of rows in matrix
* @param cols Number of columns in matrix
* @param buffer Matrix to store contents of input file
*/
void readFile(char* inputFile, int rows, int cols, int***buffer )
{
FILE* inStrm;
int i, j, count = 0;
inStrm = fopen(inputFile, "r"); // Open file for reading
if (inStrm == NULL) // Check file opened correctly
{
perror("Error opening file for reading\n");
exit(1);
}
// Store contents of file in 2D array
for( i = 0; i < rows; i++ )
{
for ( j = 0; j < cols; j++ )
{
count += fscanf( inStrm, "%d", &(*(buffer))[i][j] );
}
}
fclose(inStrm); // Close file
if(count != NINE*NINE)
{
fprint(stderr, "Invalid number of parameters read from file\n");
cleanMemory();
exit(1);
}
}
/**
* Write the invalid regions to log file
* @param region Sub region
* @param format String to be written
*/
void writeFile(Region* region, char* format)
{
char* filename = "logfile";
FILE* outFile;
int val;
outFile = fopen(filename, "a"); // Open file for appending
if (outFile == NULL) // Check file opened correctly
{
perror("Error opening file for writing\n");
exit(1);
}
fprintf(outFile, "thread ID-%d: %s",region->tid, format);
fclose(outFile); // Close file
}
/**
* Set each index to zero
* @param numbers Array to be reset
*/
void resetArray(int numbers[])
{
for (int i = 0; i < NINE; i++)
{
numbers[i] = 0;
}
}
/**
* Check if the contents of the array has any value other than one
* @param numbers Array to be checked
* @return Status of array being valid or not
*/
int checkValid(int numbers[])
{
for (int j = 0; j < NINE; j++)
{
if ( numbers[j] != 1)
{
return FALSE;
}
}
return TRUE;
}
/**
* Handles the routine for the parent. Outputs the result to the screen
* @param threads ID of child threads
*/
void parentManager()
{
char *type, *message;
int done = FALSE;
int position;
pthread_mutex_lock(&mutex); // Lock mutex
while ( inUse > 0 ) // Wait while children are executing
{
pthread_cond_wait(&use, &mutex);
}
pthread_cond_signal(&use);
pthread_mutex_unlock(&mutex); // Unlock mutex
for(int ii = 0; ii < NUMTHREADS; ii++)
{
pthread_mutex_lock(&mutex); // Lock mutex
if (regions[ii].type == ROW)
{
type = "row";
position = regions[ii].position;
if ( regions[ii].valid == TRUE)
{
printf("Validation result from thread ID-%u: %s %d is valid\n",
regions[ii].tid,type, position+1);
}
else
{
printf("Validation result from thread ID-%u: %s %d is invalid\n",
regions[ii].tid, type, position+1);
}
}
else if (regions[ii].type == COL)
{
type = "column";
printf("Validation result from thread ID-%u: %d out of 9 columns are valid\n"
,regions[ii].tid, regions[ii].count);
}
else
{
type = "sub-grid";
printf("Validation result from thread ID-%u: %d out of 9 sub-grids are valid\n"
,regions[ii].tid, regions[ii].count);
}
pthread_mutex_unlock(&mutex);
}
if (*counter == 27)
{
message = "valid";
}
else
{
message = "invalid";
}
printf("There are %d valid sub-grids, and thus the solution is %s\n", *counter, message);
}
/**
* Routine for child threads. Check the validity of sub region.
* @param args Void pointer to Region struct for the child
*/
void* childManager(void* args )
{
char format[500];
int numValid;
Region* region = ((Region*)(args));
int threadNum = region->position;
int comma = 0;
int delay;
// Generate random maxDelay
srand((unsigned) pthread_self() );
delay = ( rand() % delay ) + 1;
if( region->type == ROW ) // Check row in buffer1
{
// Check rows
for (int i = 0; i < NINE; i++)
{
// Update numbers array
region->numbers[((buff1)[threadNum][i])-1]++;
}
sleep(delay); // Sleep
pthread_mutex_lock(&mutex); // Lock mutex
// Update region struct
region->tid = pthread_self();
region->valid = checkValid(region->numbers);
// Update buffer2
numValid = 0;
if (region->valid == TRUE)
{
numValid = 1;
region->count = numValid;
}
else // Write to log file
{
region->count = numValid;
sprintf(format, "row %d is invalid\n", threadNum+1);
writeFile((region), format);
}
buff2[threadNum] = numValid; // Update buffer2
*counter = *counter + numValid; // Update counter
pthread_mutex_unlock(&mutex); // Unlock mutex
}
else if( region->type == COL ) // Check all columns
{
sprintf(format, "column ");
int validCol = 0;
for ( int nn = 0; nn < NINE; nn++) // Iterate through each column
{
for(int ii = 0; ii < NINE; ii++) // Iterate through each row
{
// Update numbers array
region->numbers[((buff1)[ii][nn])-1]++;
}
// Check if the column is valid
if ( checkValid( region->numbers) == TRUE )
{
validCol++;
}
else
{
if (comma == 0)
{
comma = 1;
sprintf(format + strlen(format), "%d", nn+1);
}
else
{
sprintf(format + strlen(format), ", %d ", nn+1);
}
}
resetArray(region->numbers);
}
sleep(delay);
if (validCol == 8)
{
sprintf(format + strlen(format), " is invalid\n");
}
else
{
sprintf(format + strlen(format), "are invalid\n");
}
pthread_mutex_lock(&mutex); // Lock mutex
// Update region struct
region->count = validCol;
region->tid = pthread_self();
if(validCol != 9)
{
writeFile((region), format);
}
numValid = region->count;
buff2[threadNum] = validCol; // Update buffer2
*counter = *counter + validCol; // Update counter
pthread_mutex_unlock(&mutex); // Unlock mutex
}
else if( region->type == SUB_GRID ) // Check all sub-grids
{
sprintf(format, "sub-grid ");
int validSub = 0;
// Iterate through each of the 9 3x3 sub-grid
for ( int jj = 0; jj < 3; jj++)
{
for (int kk = 0; kk < 3; kk++)
{
for (int ll = jj*3; ll < jj*3+3; ll++)
{
for (int mm = kk*3; mm < kk*3+3; mm++)
{
// Update numbers array
region->numbers[((buff1)[ll][mm])-1]++;
}
}
if ( checkValid(region->numbers) == TRUE )
{
validSub++;
}
else // Update string for log file
{
if (comma == 0)
{
comma = 1;
sprintf(format+strlen(format), "[%d..%d, %d..%d]",
jj*3+1, jj*3+3, kk*3+1, kk*3+3);
}
else
{
sprintf(format+strlen(format), ", [%d..%d, %d..%d]",
jj*3+1, jj*3+3, kk*3+1, kk*3+3);
}
}
resetArray(region->numbers);
}
}
sleep(delay);
if( validSub == 8)
{
sprintf(format+strlen(format), " is invalid\n");
}
else
{
sprintf(format+strlen(format), " are invalid\n");
}
pthread_mutex_lock(&mutex); // Lock mutex
// Update region struct
region->count= validSub;
region->tid = pthread_self();
if(validSub != 9)
{
writeFile((region), format);
}
buff2[threadNum] = validSub; // Update buffer2
*counter = *counter + validSub; // Update counter
pthread_mutex_unlock(&mutex); // Unlock mutex
}
// Child signals it is finished by incremented resourceCount
pthread_mutex_lock(&mutex); // Lock mutex
while( inUse == 0)
{
pthread_cond_wait(&use, &mutex);
}
inUse--; // Decrease count of child processes running
if (inUse == 0)
{
pthread_cond_signal(&use);
}
pthread_mutex_unlock(&mutex); // Unlock mutex
pthread_detach(pthread_self()); // Release resources
}
/**
* Validate command line parameters
* @param argc number of parameters
* @param argv command line parameters
*/
void validateUse(int argc, char* argv[])
{
// Ensure correct number of command line parameters
if (argc != 3)
{
printf("Ensure there are the correct number of parameters\n");
exit(1);
}
// Ensure maxDelay is positive
if ( atoi(argv[2]) < 0)
{
printf("The maxDelay must be non-negative\n");
exit(1);
}
}
|
C
|
#ifndef STEPPERMOTOR_H
#define STEPPERMOTOR_H
//If OCR0A is set to 1, how many interrupts would there be in one second?
#define TIMER_FREQUENCY 250000
typedef struct StepperMotor
{
volatile long stepCount;
volatile double totalCount;
volatile float currentStepDelay;
volatile float delayCounter;
volatile float stepAccel;
volatile float targetDelay;
volatile long tempCount;
} StepperMotor;
#define ACCEL 0
#define DECEL 1
#define RUN 2
#define STOP 3
//Function Prototypes
void setupStepperMotor(void);
StepperMotor controlMotor(long stepTarget, int inSpeed, int maxSpeed, int outSpeed, int accel, int decel);
void pulseMotor(volatile uint8_t *port, uint8_t pin);
void enableDrive(int left);
void accelerateMotor(struct StepperMotor *motor, int continueTo);
void runMotor(struct StepperMotor *motor, int continueTo);
void decelerateMotor(struct StepperMotor *motor, int continueTo);
int calculateNextDelay(struct StepperMotor *motor,volatile uint8_t *shutoffPort);
int eightBitTimerFix(struct StepperMotor *motor);
void turnOnTimers(int one, int two);
void setDirection(int left, int right);
int accelerateMotorToPoint(struct StepperMotor *motor);
int getDelayFromVelocity(int stepsPerSecond);
#endif
|
C
|
#include<stdio.h>
#define ERROR -1
#define OK 0
int main(int argc, char* argv[]){
int cant_nums = 0,
acum = 0,
counter = 0,
num = 0;
while(cant_nums <= 0){
printf("enter a number of numbers: ");
scanf("%d", &cant_nums);
}
printf("enter a secuence of numbers: ");
do{
scanf("%d", &num);
acum += num;
counter++;
}while(--cant_nums > 0);
printf("el promedio es %.3e \n", (float)acum / (float)counter);
return OK;
}
|
C
|
/*
** ia_mode.c for ia_mode in /home/renard_e/progElem/CPE_2015_Allum1
**
** Made by gregoire renard
** Login <[email protected]>
**
** Started on Tue Feb 9 08:31:52 2016 gregoire renard
** Last update Wed Feb 10 15:12:17 2016 gregoire renard
*/
#include <stdlib.h>
#include "include/my.h"
void aff_change_ia(int matches, int line)
{
my_putstr("AI removed ");
my_put_nbr(matches);
my_putstr(" match(es) from line ");
my_put_nbr(line);
my_putchar('\n');
}
char **ia_mode(char **map, int size_map)
{
int line;
int matches;
line = -1;
matches = -1;
my_putstr("\nAI's turn...\n");
while (line == -1 || matches == -1)
{
if ((line = ia_line_opt(map, size_map)) == -1)
matches = -1;
else
matches = ia_matches_opt(map, line);
}
map = map_change(map, matches, line);
aff_change_ia(matches, line);
aff_map(map);
return (map);
}
|
C
|
//Program for Queue implementation through Linked List
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
} ;
struct node *front, *rear;
void main()
{
int wish,will,a,num;
void add(int);
wish=1;
front=rear=NULL;
printf("\tProgram for Queue as Linked List demo.. ");
while(wish == 1)
{
printf(" \nMain Menu \n 1.Enter data in queue \n2.Delete from queue #");
scanf("%d",&will);
switch(will)
{
case 1:
printf("\nEnter the data #");
scanf("%d",&num);
add(num);
break;
case 2:
a=del();
printf("\nValue returned from front of the queue is #%d",a);
break;
default:
printf("\nInvalid choice");
}
printf("\nDo you want to continue, press 1 #");
scanf("%d",&wish);
}
getch();
}
void add(int y)
{
struct node *ptr;
ptr=malloc(sizeof(struct node));
ptr->data=y;
ptr->link=NULL;
if(front ==NULL)
{
front = rear= ptr;
}
else
{
rear->link=ptr;
rear=ptr;
}
}
int del()
{
int num;
if(front==NULL)
{
printf("\n\tQUEUE EMPTY");
return(0);
}
else
{
num=front->data;
front = front->link;
printf("\n Value returned by delete function is # %d ",num);
return(num);
}
}
|
C
|
/*
* =====================================================================
* NAME : Main.c
*
* Descriptions : Main routine for S3C2440
*
* IDE : CodeWarrior 2.0 or Later
*
* Modification
* Modified by MDS Tech. NT Div.(2Gr) (2007.3.1~4)
* =====================================================================
*/
#include "2440addr.h"
#define EXAMPLE 422
/*
* 420 : SW_DMA (ǽ 8-1 : SW DMA Trigger Test )
*
* 421 : UART_DMA (ǽ 8-2 : Timer DMA trigger Test)
*
* 422 : Timer_DMA (ǽ 8-3 : UART0 DMA trigger Test)
*
*
* Advanced Course
* 1. make macro function
*/
/***************************************
*
* Title: SW_DMA
*
***************************************/
#if EXAMPLE == 420
//** ISR Function declaration
static void __irq DMA0_ISR(void);
// Global Variables Declaration
// CACHE ƴҰ
static unsigned long src=0x33000000;
static unsigned long dst=0x33100000;
static unsigned int size = 12; /* word size */
static unsigned long pattern;
static void __irq DMA0_ISR(void)
{
/* ͷƮ on DMA1 */
rINTMSK |= (0x1<<17);
/* TO DO: Pendng Clear on DMA1 */
rSRCPND |= 0x1<<17;
rINTPND |= 0x1<<17;
Uart_Printf("__irq ISR ");
MemDump(dst, 12);
/* TO DO: Stop DMA0 trigger */
rDMASKTRIG0 |= 0x1<<2;
/* Masking Disable on DMA1 */
rINTMSK &= ~(0x1<<17);
}
void Main(void)
{
char value;
Uart_Init(115200);
DMA0_SW_Init();
Uart_Send_Byte('\n');
Uart_Send_Byte('A');
Uart_Send_String("Hello Uart Test...!!!\n");
/* TODO : ͷƮ Ϳ DMA0_ISR Լ */
pISR_DMA0 = (unsigned int)DMA0_ISR;
/* ͷƮ on DMA0 */
rINTMSK &= ~(0x1<<17);
DMA0_SW_Start();
while(1);
}
#endif
/***************************************
*
* Title: UART_DMA
*
***************************************/
#if EXAMPLE == 421
//** ISR Function declaration
static void __irq DMA0_ISR(void);
// Global Variables Declaration
// CACHE ƴҰ
static unsigned long src=0x33000000;
static unsigned long dst=0x33100000;
static unsigned int size = 12; /* word size */
static unsigned long pattern;
static void __irq DMA0_ISR(void)
{
/* ͷƮ */
rINTMSK |= (0x1<<17);
/* TO DO: Pendng Clear on DMA */
rSRCPND |= 0x1<<17;
rINTPND |= 0x1<<17;
Uart_Printf("__irq ISR ");
MemDump(dst, 12);
/* Masking Disable on DMA1 */
rINTMSK &= ~(0x1<<17);
}
void Main(void)
{
char value;
Uart_DMA_Init(115200);
DMA0_UART_Init();
Uart_Send_Byte('\n');
Uart_Send_Byte('A');
Uart_Send_String("Hello Uart Test...!!!\n");
/* TODO : ͷƮ Ϳ DMA0_ISR Լ */
pISR_DMA0 = (unsigned int)DMA0_ISR;
/* ͷƮ on DMA0 */
rINTMSK &= ~(0x1<<17);
DMA0_HW_Start();
while(1);
}
#endif
/***************************************
*
* Title: Timer_DMA
*
***************************************/
#if EXAMPLE == 422
//** ISR Function declaration
static void __irq DMA0_ISR(void);
// Global Variables Declaration
// CACHE ƴҰ
static unsigned long src=0x33000000;
static unsigned long dst=0x33100000;
static unsigned int size = 12; /* word size */
static unsigned long pattern;
static void __irq DMA0_ISR(void)
{
/* ͷƮ on DMA0 */
rINTMSK |= (0x1<<17);
/* TO DO: Pendng Clear on DMA0 */
rSRCPND |= 0x1<<17;
rINTPND |= 0x1<<17;
Uart_Printf("__irq ISR ");
MemDump(dst, 12);
/* Masking Disable on DMA0 */
rINTMSK &= ~(0x1<<17);
}
void Main(void)
{
char value;
Uart_Init(115200);
DMA0_Timer_Init();
Timer_DMA_Init();
Uart_Send_Byte('\n');
Uart_Send_Byte('A');
Uart_Send_String("Hello Uart Test...!!!\n");
/* TODO : ͷƮ Ϳ DMA0_ISR Լ */
pISR_DMA0 = (unsigned int)DMA0_ISR;
/* TO DO : ͷƮ on DMA0 */
rINTMSK &= ~(0x1<<17);
DMA0_HW_Start();
Timer_Delay(1000);
}
#endif
|
C
|
#include <stdlib.h>
#include "bsd-win-sock.h"
#include "bsd-win-sock-types.h"
#include "debug.h"
#define T Socket_T
/* Stol... I mean adapted from Beej's Guide:
http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#sendall */
extern int Socket_send(T* sock, const char* msg, int len) {
int total = 0;
int bytesleft = len;
int n;
log_debug("Sending %d chars, message: %.*s", len, len, msg);
while (total < len) {
n = send(sock->sockfd_dest, msg + total, bytesleft, 0);
if (n == -1)
break;
total += n;
bytesleft -= n;
log_debug("---send: %d/%d", total, len);
log_debug("---bytes left: %d", bytesleft);
log_debug("---message left: %.*s", bytesleft, msg + total);
}
if (n == SOCKET_ERROR) {
Socket_set_errno(SOCKET_ERR_SEND);
log_warn("Send failed: %s", Socket_strerror());
return -1;
}
log_debug("Send succeded");
return total;
}
|
C
|
/**
* An implementation of a stack based on a doubly linked list.
* The API is almost exacly identical to that of the linked list.
*
* initStack(Stack* stack) - Initialize the provided stack.
* isStackEmpty - Checks if the stack is empty.
* pushStack - Push a new item to the stack.
* popStack(Stack* stack) - Pop the top element of the stack.
* getStackSize - Get the number of elements in the stack.
* peekStack - Get the top element in the stack without popping it.
*/
#ifndef STACK_H
#define STACK_H
#include <stdbool.h>
#include "linked_list.h"
typedef List Stack;
void initStack(Stack* stack);
bool isStackEmpty(const Stack* stack);
bool pushStack(Stack* stack, void* new_data);
void* popStack(Stack* stack);
int getStackSize(const Stack* stack);
/**
* Get the top element in the stack without popping it.
*
* @param stack [in] The stack being examined
* @return const void* A read-only pointer to the data contained in the top stack element.
*/
const void* peekStack(const Stack* stack);
#endif /* STACK_H */
|
C
|
#if CFACTS_PATCH
void
getfacts(Monitor *m, int msize, int ssize, float *mf, float *sf, int *mr, int *sr)
{
unsigned int n;
float mfacts = 0, sfacts = 0;
int mtotal = 0, stotal = 0;
Client *c;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++)
if (n < m->nmaster)
mfacts += c->cfact;
else
sfacts += c->cfact;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++)
if (n < m->nmaster)
mtotal += msize * (c->cfact / mfacts);
else
stotal += ssize * (c->cfact / sfacts);
*mf = mfacts; // total factor of master area
*sf = sfacts; // total factor of stack area
*mr = msize - mtotal; // the remainder (rest) of pixels after a cfacts master split
*sr = ssize - stotal; // the remainder (rest) of pixels after a cfacts stack split
}
#else
void
getfacts(Monitor *m, int msize, int ssize, float *mf, float *sf, int *mr, int *sr)
{
unsigned int n;
float mfacts, sfacts;
int mtotal = 0, stotal = 0;
Client *c;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
mfacts = MIN(n, m->nmaster);
sfacts = n - m->nmaster;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++)
if (n < m->nmaster)
mtotal += msize / mfacts;
else
stotal += ssize / sfacts;
*mf = mfacts; // total factor of master area
*sf = sfacts; // total factor of stack area
*mr = msize - mtotal; // the remainder (rest) of pixels after an even master split
*sr = ssize - stotal; // the remainder (rest) of pixels after an even stack split
}
#endif // CFACTS_PATCH
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
int main(int argc, char const *argv[]) {
int i=0,j=0;
bool done=0,prob=0;
char ch,word[40];
if(argc==1){printf("Minimal argument encountered! Please provide file name.\n"); return 0;}
FILE *fileptr = fopen(argv[1],"r");
if(fileptr==NULL){printf("Faild to open! No file selected.\n"); return 0;}
FILE *output = fopen("OUT.c","w");
char data[][10] = {"scanf","printf","auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","#include","int","long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"};
char match[][40] = {"लो","छापो","स्व", "तोेडे", "मामला","अक्षर","अफर", "जारी", "मूल", "करो","बडा", "अन्य", "गणना","बाहर", "अपूर्णांक","लिये","जाओ","अगर","शामिल","संख्या","लंबा","पंजी", "भेजो", "कम", "चिह्न", "माप", "स्थिर", "रचना", "देखो", "नाम", "संघ", "नचिह्न", "खाली", "परिवर्तनशील","जबतक"};
while(ch != EOF){
ch = fgetc(fileptr);
if(ch!=' ' && ch!=';' && ch!=EOF && ch!='\n' && ch!='\t'){
word[i]=ch; word[i+1]='\0'; i++;
}
else{
i=0;
if(word[0]<0 || word[0]>128){
for(j=0;j<36;j++){
if(!strcmp(word,match[j])){
fputs(data[j],output);
done = 1;
break;
} else done=0;
}
if(!done) prob=1;
}
else
fputs(word,output);
if(ch==';') fputs(";",output);
else if(ch == ' ') fputs(" ",output);
else if(ch == '\t') fputs("\t",output);
else fputs("\n",output);
word[0]='\0';
}
}
fclose(output);
fclose(fileptr);
if(prob) printf("Probably u entered wrong hindi keyword!\n");
else{
printf("Translated sucessfully\n-----------------------\n");
printf("Enter 1 to compile & 0 to exit\n");
scanf("%d",&done);
if(done)
if(!system("gcc -o output OUT.c")){
printf("Executing code...\n");
system("output.exe");
}
else
printf("Solve the error & try again\n");
}
return 1;
}
|
C
|
/*****************************************************************************
* プログラム名 : sample0201.c
* 作成 : 2019/06/17 小山
* 内容 : 読み込んだ二つの整数値の和・差・積・商・除算を表示
****************************************************************************/
#include <stdio.h>
void main() {
int value_x, value_y;
puts("二つの整数を入力してください。");
printf("整数 x : ");
scanf("%d", &value_x);
printf("整数 y : ");
scanf("%d", &value_y);
printf("value_x + value_y = %d\n", value_x + value_y);
printf("value_x - value_y = %d\n", value_x - value_y);
printf("value_x * value_y = %d\n", value_x * value_y);
printf("value_x / value_y = %d\n", value_x / value_y);
printf("value_x %% value_y = %d\n", value_x % value_y);
}
|
C
|
#include<stdio.h>
int main(){
float fahrenheit, celcius;
printf("%4s%21s\n","celcius", "fahrenheit");
for (celcius =30; celcius<=75; ++celcius ){
fahrenheit = celcius*(9.0f/5.0f) + 32.0f;
printf("%4.1f%21.2f\n", celcius, fahrenheit);
}
return 0;
}
|
C
|
#ifndef ML_TIME_H_HEADER
#define ML_TIME_H_HEADER
#include "common.h"
// For internal use: 1 unit of time is a microsecond.
// For convenience, when timing things:
#define ML_START_TIMING(x) \
unsigned long long x = ml_time();
#define ML_STOP_TIMING(x,...) \
do { \
x = ml_time() - x; \
static unsigned long long x##_tot = 0; \
static int x##_num = 0; \
x##_num++; \
x##_tot += x; \
printf("[ML time] "); \
printf(__VA_ARGS__); \
printf( \
" took %llu%s (avg %llu%s)\n", \
ML_TIME_PRETTY(x), ML_TIME_PRETTY_UNIT(x), \
ML_TIME_PRETTY(x##_tot/x##_num), ML_TIME_PRETTY_UNIT(x##_tot/x##_num)); \
} while (0)
#define ML_TIME_PRETTY(x) \
( \
(x) < 1000 ? (x) : \
(x) < 10000000 ? ((x)+1000/2) / 1000 : \
((x)+1000000/2) / 1000000 \
)
#define ML_TIME_PRETTY_UNIT(x) \
( \
(x) < 1000 ? "us" : \
(x) < 10000000 ? "ms" : \
"s" \
)
GC_USER_FUNC unsigned long long
ml_time (void);
#endif // ML_TIME_H_HEADER
|
C
|
#include "holberton.h"
int getNumArgs(const char *copy)
{
int iterate;
int counter = 0;
for (iterate = 0; copy[iterate] != '\0'; iterate++)
{
if (copy[iterate] == '%')
counter = counter + 1;
}
return (counter);
}
|
C
|
#include <stdio.h>
#include <math.h>
int generate(char * inPath, char* outPath, int dataRows, double(*method)(int x));
double generator1();
int main(char* argv[], int argc){
generate("in.txt", "out.txt", 1000, &generator1);
return 0;
}
int generate(char * inPath, char* outPath, int dataRows, double(*method)(int x)){
FILE * output = fopen(outPath, "w");
FILE * input = fopen(inPath, "w");
if(output == NULL || input == NULL){
printf("Sorry, couldn't open one of the files, terminating generation now.\n");
return 1;
}
int i;
for(i = 0; i < dataRows; i++){
fprintf(input, "%d\n", i);
}
for(i = 0; i < dataRows; i++){
fprintf(output, "%f\n", method(i));
}
fclose(input);
fclose(output);
return 0;
}
double generator1(int x){
double result;
double var = (double)x;
result = (pow(var/2, 3) ) - (2* pow(var, 2)) + (pow(-1, var))*(sin(var*2) * cos(var/4)) - 10*pow(var, 1)*sin(-var) + 3*(pow(var,4)) - 0.25 * pow(var, 5) * cos(var*20);
return result;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void)
{
int cnt;
scanf("%d", &cnt);
char file_name[51];
int len;
char result_file_name[51];
scanf("%s", file_name);
len = strlen(file_name);
memcpy(result_file_name, file_name, len);
result_file_name[len] = '\0';
cnt--;
while (cnt--)
{
scanf("%s", file_name);
int i;
for (i = 0; i < len; i++)
{
if (result_file_name[i] == '?')
continue;
if (result_file_name[i] != file_name[i])
result_file_name[i] = '?';
}
}
printf("%s\n", result_file_name);
return 0;
}
|
C
|
/*
* udp_recv.c
*
* Description: This file implement recvResult(), used to send results back to departments.
* Reused Code: In this file, I used some pieces of code from "Beej's Guide to C Programming and Network Programming" from page 27 to page 34
* Created on: Jul 31, 2015
* Author: guangzhz
*/
#include "Department.h"
//char ip_addr[NAMESIZE]; //ip address
//flag=1=>A
//falg=2=>B
struct addrinfo* doGetAddrInfo_udp(int flag){
struct addrinfo hint,*serinfo;
int rv;
char port[NAMESIZE];
memset(&hint,0,sizeof(hint));
hint.ai_family=AF_UNSPEC;
hint.ai_socktype=SOCK_DGRAM;
hint.ai_flags=AI_PASSIVE;
sprintf(port,"%s",flag==1?PORTA:PORTB);
if((rv=getaddrinfo(NULL,port,&hint,&serinfo))!=0){
fprintf(stderr,"Department: geraddrinfo %s",gai_strerror(rv));
exit(1);
}
return serinfo;
}
int doSockPre_udp(struct addrinfo* serinfo, int flag){
int sockfd;
struct addrinfo* p;
//struct timeval timeout;
//timeout.tv_sec=60;
//timeout.tv_usec=0;
for(p=serinfo;p!=NULL;p=p->ai_next){
if((sockfd=socket(p->ai_family,p->ai_socktype,p->ai_protocol))==-1){
perror("Department: socket");
continue;
}
/*if(setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout))==-1){
perror("Department: setsockopt");
continue;
}*/
if(bind(sockfd,p->ai_addr,p->ai_addrlen)!=0){
close(sockfd);
perror("Department: bind");
continue;
}
break;
}
if(p==NULL){
fprintf(stderr,"fail to connect\n");
exit(1);
}
freeaddrinfo(serinfo);
return sockfd;
}
void doRecv_udp(int sockfd,int flag){
char buf[DATASIZE];
int bytenum;
struct sockaddr_storage comeaddr;
socklen_t addrlen = sizeof(comeaddr);
//char s[INET6_ADDRSTRLEN];
while (strcmp(buf,"done") != 0){
memset(buf,0,sizeof(buf));
if ((bytenum = recvfrom(sockfd, buf, DATASIZE - 1, 0,
(struct sockaddr*) &comeaddr, (socklen_t*) &addrlen)) == -1) {
perror("Department: recvfrom");
exit(1);
}
/*printf("listener: got packet from %s\n",
inet_ntop(comeaddr.ss_family,
get_in_addr((struct sockaddr *) &comeaddr), s,
sizeof s));
printf("listener: packet is %d bytes long\n", bytenum);*/
buf[bytenum] = '\0';
if(strcmp(buf,"done") != 0){
//printf("Department: get result \"%s\"\n", buf);
char temp[DATASIZE];
sprintf(temp,"%s",buf);
char* s=strtok(temp,"#");
printf("<%s> has been admitted to <Department%c>: %s\n",s,dept(flag),buf);
}
}
}
void recvResult(int flag){
struct addrinfo *serinfo;
int sockfd;
printf("<Department%c> has UDP port %s and IP address %s for Phase 2\n",dept(flag),flag==1?PORTA:PORTB,IPaddr);
serinfo = doGetAddrInfo_udp(flag);
sockfd = doSockPre_udp(serinfo, flag);
doRecv_udp(sockfd, flag);
//sleep(20);
close(sockfd);
printf("End of Phase 2 for <Department%c>\n",dept(flag));
}
|
C
|
#include<stdio.h>
#define M 3.0e-23
#define QUOTA 950
int main (void)
{
double quotas;
double number;
printf("please enter the quotas:\n");
scanf("%lf", "as);
number = quotas * QUOTA * M;
printf("there are %e etoms in the water!\n", number);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
double A, B, C, pi;
double tri, cir, tra, qua, ret;
scanf("%lf", &A);
scanf("%lf", &B);
scanf("%lf", &C);
pi = 3.14159;
tri = (A * C) / 2;
cir = pi * pow(C, 2);
tra = ((A + B) * C) / 2;
qua = B * B;
ret = A * B;
printf("TRIANGULO: %.3lf\n", tri);
printf("CIRCULO: %.3lf\n", cir);
printf("TRAPEZIO: %.3lf\n", tra);
printf("QUADRADO: %.3lf\n", qua);
printf("RETANGULO: %.3lf", ret);
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int Add(int a, int b);
int main()
{
/*
+ REPL
- read
- evaluate
- present
- loop
*/
// var
{
char c = 'a';
short s = 32;
int i = 42;
long l = 1234L;
float f = 3.14f;
double d = 2.71828;
printf("%c \n", c);
printf("%d \n", s);
printf("%d \n", i);
printf("%ld \n", l);
printf("%f \n", f);
printf("%f \n", d);
}
// func
{
int a = 6;
int b = 42;
int res = Add(a, b);
printf("%d", res);
}
// statement
{
}
// control flow
{
int age = 30;
if(age < 5)
{
printf("-> goto kindergarten..\n");
}
else if(age >= 5 && age < 15)
{
printf("-> goto middle school..\n");
}
else if(age >= 15 && age < 18)
{
printf("-> goto high school..\n");
}
else if(age >= 18 && age < 22)
{
printf("-> goto college..\n");
}
else
{
printf("-> do w/e u want..\n");
}
}
// loop
{
for(int i=0; i<3; ++i)
{
printf("%d \n", i);
}
int m = 5;
while(m > 0)
{
printf("%d \n", m);
--m;
}
}
// pointer
{
int a = 42;
int* p = &a;
printf("memory address of int a is : %x \n", p);
}
// reference
{
}
// cls? (NO)
{
// c is a procedure language
// no abstraction concept
}
return 0;
}
int Add(int a, int b)
{
return a + b;
}
|
C
|
#include <stdio.h>
/*/
Foi elaborada uma prova objetiva contendo 200 (duzentas)questes para um concurso
pblico. Escreva um programa, em C, para ler a matrcula (valor inteiro), a quantidade
de acertos, quantidade de erros e a quantidade de questes no respondidas de cada
um dos 4000 (quatro mil)(10) candidatos que fizeram essa prova. Ao final, o programa
dever exibir o cdigo de cada candidato que acertou, no mnimo, 50% da prova, com
respectiva taxa de acerto, erro e questes no respondidas.
/*/
int main(){
int matri[10], i, ac[10], er[10], br[10], percAc, percEr, percBr;
for (i=0; i<9; i++ ){
printf("Digite sua matricula: ");
scanf("%d", &matri[i]);
printf("Acertos: ");
percAc = ((ac[i]*100)/200);
scanf("%d", &ac[i]);
printf("Erros: ");
scanf("%d", &er[i]);
printf("Branco: ");
scanf("%d", &br[i]);
if (percAc>50){
printf("_________________________________________________________\n");
printf("Matricula: %d \n", matri[i]);
printf("Taxa de acerto: %d %% \n", percAc);
percEr = ((er[i]*100)/200);
printf("Taxa de erro: %d %% \n", percEr);
percBr = ((br[i]*100)/200);
printf("Taxa de questoes em branco: %d %% \n", percBr);
printf("_________________________________________________________\n");
}
}
return 0;
}
|
C
|
#include "expression.h"
#include "statement.h"
#include "alloc.h"
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
static expression_t __expression_new__(expression_type_t expr_type, long line, long column)
{
expression_t expr = mem_alloc(sizeof(struct expression_s));
if (!expr) {
return NULL;
}
expr->type = expr_type;
expr->line = line;
expr->column = column;
return expr;
}
expression_t expression_new_literal(expression_type_t type, token_t tok)
{
expression_t expr;
char *result;
assert(tok->value == TOKEN_VALUE_TRUE ||
tok->value == TOKEN_VALUE_FALSE ||
tok->value == TOKEN_VALUE_NULL ||
tok->value == TOKEN_VALUE_LITERAL_CHAR ||
tok->value == TOKEN_VALUE_LITERAL_INT ||
tok->value == TOKEN_VALUE_LITERAL_LONG ||
tok->value == TOKEN_VALUE_LITERAL_FLOAT ||
tok->value == TOKEN_VALUE_LITERAL_DOUBLE ||
tok->value == TOKEN_VALUE_LITERAL_STRING);
expr = __expression_new__(type, tok->line, tok->column);
switch (type) {
case EXPRESSION_TYPE_BOOL:
if (tok->value == TOKEN_VALUE_TRUE) {
expr->u.bool_expr = true;
} else if (tok->value == TOKEN_VALUE_FALSE) {
expr->u.bool_expr = false;
}
break;
case EXPRESSION_TYPE_NULL:
expr->type = EXPRESSION_TYPE_NULL;
break;
case EXPRESSION_TYPE_CHAR:
sscanf(tok->token, "%c", &expr->u.char_expr);
break;
case EXPRESSION_TYPE_INT:
switch (tok->numberbase) {
case 8:
expr->u.int_expr = strtol(tok->token, &result, 8);
break;
case 10:
expr->u.int_expr = strtol(tok->token, &result, 10);
break;
case 16:
expr->u.int_expr = strtol(tok->token, &result, 16);
break;
default:
assert(false);
break;
}
break;
case EXPRESSION_TYPE_LONG:
switch (tok->numberbase) {
case 8:
expr->u.int_expr = strtol(tok->token, &result, 8);
break;
case 10:
expr->u.int_expr = strtol(tok->token, &result, 10);
break;
case 16:
expr->u.int_expr = strtol(tok->token, &result, 16);
break;
default:
assert(false);
break;
}
break;
case EXPRESSION_TYPE_FLOAT:
sscanf(tok->token, "%f", &expr->u.float_expr);
break;
case EXPRESSION_TYPE_DOUBLE:
sscanf(tok->token, "%lf", &expr->u.double_expr);
break;
case EXPRESSION_TYPE_STRING:
expr->u.string_expr = cstring_dup(tok->token);
break;
default:
assert(false);
break;
}
return expr;
}
expression_t expression_new_identifier(long line, long column, cstring_t identifier)
{
expression_t expr = __expression_new__(EXPRESSION_TYPE_IDENTIFIER, line, column);
assert(!cstring_is_empty(identifier));
expr->u.identifier_expr = identifier;
return expr;
}
expression_t expression_new_assign(long line, long column, expression_type_t assign_type, expression_t lvalue_expr, expression_t rvalue_expr)
{
expression_t expr;
expression_assign_t assign_expr;
assert(assign_type == EXPRESSION_TYPE_ASSIGN ||
assign_type == EXPRESSION_TYPE_ADD_ASSIGN ||
assign_type == EXPRESSION_TYPE_SUB_ASSIGN ||
assign_type == EXPRESSION_TYPE_MUL_ASSIGN ||
assign_type == EXPRESSION_TYPE_DIV_ASSIGN ||
assign_type == EXPRESSION_TYPE_MOD_ASSIGN ||
assign_type == EXPRESSION_TYPE_BITAND_ASSIGN ||
assign_type == EXPRESSION_TYPE_BITOR_ASSIGN ||
assign_type == EXPRESSION_TYPE_XOR_ASSIGN ||
assign_type == EXPRESSION_TYPE_LEFT_SHIFT_ASSIGN ||
assign_type == EXPRESSION_TYPE_RIGHT_SHIFT_ASSIGN||
assign_type == EXPRESSION_TYPE_LOGIC_RIGHT_SHIFT_ASSIGN);
expr = __expression_new__(assign_type, line, column);
assign_expr = (expression_assign_t) mem_alloc(sizeof(struct expression_assign_s));
if (!assign_expr) {
return NULL;
}
expr->u.assign_expr = assign_expr;
expr->u.assign_expr->lvalue_expr = lvalue_expr;
expr->u.assign_expr->rvalue_expr = rvalue_expr;
return expr;
}
expression_t expression_new_binary(long line, long column, expression_type_t binary_expr_type, expression_t left, expression_t right)
{
expression_t expr;
expression_binary_t binary_expr;
assert(binary_expr_type == EXPRESSION_TYPE_OR ||
binary_expr_type == EXPRESSION_TYPE_AND ||
binary_expr_type == EXPRESSION_TYPE_EQ ||
binary_expr_type == EXPRESSION_TYPE_NEQ ||
binary_expr_type == EXPRESSION_TYPE_GT ||
binary_expr_type == EXPRESSION_TYPE_GEQ ||
binary_expr_type == EXPRESSION_TYPE_LT ||
binary_expr_type == EXPRESSION_TYPE_LEQ ||
binary_expr_type == EXPRESSION_TYPE_ADD ||
binary_expr_type == EXPRESSION_TYPE_SUB ||
binary_expr_type == EXPRESSION_TYPE_MUL ||
binary_expr_type == EXPRESSION_TYPE_DIV ||
binary_expr_type == EXPRESSION_TYPE_MOD ||
binary_expr_type == EXPRESSION_TYPE_BITAND ||
binary_expr_type == EXPRESSION_TYPE_BITOR ||
binary_expr_type == EXPRESSION_TYPE_XOR ||
binary_expr_type == EXPRESSION_TYPE_LEFT_SHIFT ||
binary_expr_type == EXPRESSION_TYPE_RIGHT_SHIFT ||
binary_expr_type == EXPRESSION_TYPE_LOGIC_RIGHT_SHIFT);
assert(left != NULL);
assert(right != NULL);
expr = __expression_new__(binary_expr_type, line, column);
binary_expr = (expression_binary_t) mem_alloc(sizeof (struct expression_binary_s));
if (!binary_expr) {
return NULL;
}
expr->u.binary_expr = binary_expr;
expr->u.binary_expr->left = left;
expr->u.binary_expr->right = right;
return expr;
}
expression_t expression_new_unary(long line, long column, expression_type_t unary_expr_type, expression_t expression)
{
expression_t expr;
assert(unary_expr_type == EXPRESSION_TYPE_PLUS ||
unary_expr_type == EXPRESSION_TYPE_MINUS ||
unary_expr_type == EXPRESSION_TYPE_NOT ||
unary_expr_type == EXPRESSION_TYPE_CPL);
assert(expression != NULL);
expr = __expression_new__(unary_expr_type, line, column);
expr->u.unary_expr = expression;
return expr;
}
expression_t expression_new_incdec(long line, long column, expression_type_t type, expression_t lvalue_expr)
{
expression_t expr;
assert(type == EXPRESSION_TYPE_INC ||
type == EXPRESSION_TYPE_DEC);
assert(lvalue_expr != NULL);
expr = __expression_new__(type, line, column);
expr->u.incdec_expr = lvalue_expr;
return expr;
}
expression_t expression_new_function(long line, long column, cstring_t name, list_t parameters, list_t block)
{
expression_t expr;
expression_function_t function_expr;
expr = __expression_new__(EXPRESSION_TYPE_FUNCTION, line, column);
function_expr = (expression_function_t) mem_alloc(sizeof (struct expression_function_s));
if (!function_expr) {
return NULL;
}
expr->u.function_expr = function_expr;
expr->u.function_expr->name = name;
expr->u.function_expr->parameters = parameters;
expr->u.function_expr->block = block;
return expr;
}
expression_t expression_new_call(long line, long column, expression_t function_expr, list_t args)
{
expression_t expr;
expression_call_t call_expr;
assert(function_expr != NULL);
expr = __expression_new__(EXPRESSION_TYPE_CALL, line, column);
call_expr = (expression_call_t) mem_alloc(sizeof (struct expression_call_s));
if (!call_expr) {
return NULL;
}
expr->u.call_expr = call_expr;
expr->u.call_expr->function_expr = function_expr;
expr->u.call_expr->args = args;
return expr;
}
expression_t expression_new_array_generate(long line, long column, list_t elements)
{
expression_t expr;
expr = __expression_new__(EXPRESSION_TYPE_ARRAY_GENERATE, line, column);
expr->u.array_generate_expr = elements;
return expr;
}
expression_t expression_new_array_push(long line, long column, expression_t array_expr, expression_t elem_expr)
{
expression_t expr;
expression_array_push_t array_append;
expr = __expression_new__(EXPRESSION_TYPE_ARRAY_PUSH, line, column);
array_append = (expression_array_push_t) mem_alloc(sizeof(struct expression_array_push_s));
if (!array_append) {
return NULL;
}
expr->u.array_push_expr = array_append;
expr->u.array_push_expr->array_expr = array_expr;
expr->u.array_push_expr->elem_expr = elem_expr;
return expr;
}
expression_t expression_new_array_pop(long line, long column, expression_t array_expr, expression_t lvalue_expr)
{
expression_t expr;
expression_array_pop_t array_pop;
expr = __expression_new__(EXPRESSION_TYPE_ARRAY_POP, line, column);
array_pop = (expression_array_pop_t) mem_alloc(sizeof(struct expression_array_pop_s));
if (!array_pop) {
return NULL;
}
expr->u.array_pop_expr = array_pop;
expr->u.array_pop_expr->array_expr = array_expr;
expr->u.array_pop_expr->lvalue_expr = lvalue_expr;
return expr;
}
expression_table_pair_t expression_new_table_pair(expression_t name, expression_t expr)
{
expression_table_pair_t pair = (expression_table_pair_t) mem_alloc(sizeof(struct expression_table_pair_s));
if (!pair) {
return NULL;
}
pair->member_name = name;
pair->member_expr = expr;
return pair;
}
void expression_free_table_pair(expression_table_pair_t pair)
{
expression_free(pair->member_name);
expression_free(pair->member_expr);
mem_free(pair);
}
expression_t expression_new_table_generate(long line, long column, list_t members)
{
expression_t expr;
expr = __expression_new__(EXPRESSION_TYPE_TABLE_GENERATE, line, column);
expr->u.table_generate_expr = members;
return expr;
}
expression_t expression_new_table_dot_member(long line, long column, expression_t table, cstring_t member_name)
{
expression_t expr;
expression_table_dot_member_t dot_member;
expr = __expression_new__(EXPRESSION_TYPE_TABLE_DOT_MEMBER, line, column);
dot_member = (expression_table_dot_member_t) mem_alloc(sizeof (struct expression_table_dot_member_s));
if (!dot_member) {
return NULL;
}
expr->u.table_dot_member_expr = dot_member;
expr->u.table_dot_member_expr->table_expr = table;
expr->u.table_dot_member_expr->member_name = member_name;
return expr;
}
expression_t expression_new_index(long line, long column, expression_t dict, expression_t index)
{
expression_t expr;
expression_index_t index_expr;
expr = __expression_new__(EXPRESSION_TYPE_INDEX, line, column);
index_expr = (expression_index_t) mem_alloc(sizeof (struct expression_index_s));
if (!index_expr) {
return NULL;
}
expr->u.index_expr = index_expr;
expr->u.index_expr->dict = dict;
expr->u.index_expr->index = index;
return expr;
}
void expression_free(expression_t expr)
{
list_iter_t iter = NULL, next_iter = NULL;
switch (expr->type) {
case EXPRESSION_TYPE_STRING:
cstring_free(expr->u.string_expr);
break;
case EXPRESSION_TYPE_IDENTIFIER:
cstring_free(expr->u.identifier_expr);
break;
case EXPRESSION_TYPE_FUNCTION:
cstring_free(expr->u.function_expr->name);
list_safe_for_each(expr->u.function_expr->parameters, iter, next_iter) {
expression_function_parameter_t parameter;
list_erase(expr->u.function_expr->parameters, *iter);
parameter = list_element(iter, expression_function_parameter_t, link);
cstring_free(parameter->name);
mem_free(parameter);
}
list_safe_for_each(expr->u.function_expr->block, iter, next_iter) {
list_erase(expr->u.function_expr->block, *iter);
statement_free(list_element(iter, statement_t, link));
}
mem_free(expr->u.function_expr);
break;
case EXPRESSION_TYPE_ASSIGN:
case EXPRESSION_TYPE_ADD_ASSIGN:
case EXPRESSION_TYPE_SUB_ASSIGN:
case EXPRESSION_TYPE_MUL_ASSIGN:
case EXPRESSION_TYPE_DIV_ASSIGN:
case EXPRESSION_TYPE_MOD_ASSIGN:
case EXPRESSION_TYPE_BITAND_ASSIGN:
case EXPRESSION_TYPE_BITOR_ASSIGN:
case EXPRESSION_TYPE_XOR_ASSIGN:
case EXPRESSION_TYPE_LEFT_SHIFT_ASSIGN:
case EXPRESSION_TYPE_RIGHT_SHIFT_ASSIGN:
case EXPRESSION_TYPE_LOGIC_RIGHT_SHIFT_ASSIGN:
expression_free(expr->u.assign_expr->lvalue_expr);
expression_free(expr->u.assign_expr->rvalue_expr);
mem_free(expr->u.assign_expr);
break;
case EXPRESSION_TYPE_CALL:
expression_free(expr->u.call_expr->function_expr);
list_safe_for_each(expr->u.call_expr->args, iter, next_iter) {
list_erase(expr->u.call_expr->args, *iter);
expression_free(list_element(iter, expression_t, link));
}
mem_free(expr->u.call_expr);
break;
case EXPRESSION_TYPE_PLUS:
case EXPRESSION_TYPE_MINUS:
case EXPRESSION_TYPE_NOT:
case EXPRESSION_TYPE_CPL:
expression_free(expr->u.unary_expr);
break;
case EXPRESSION_TYPE_INC:
case EXPRESSION_TYPE_DEC:
expression_free(expr->u.incdec_expr);
break;
case EXPRESSION_TYPE_BITAND:
case EXPRESSION_TYPE_BITOR:
case EXPRESSION_TYPE_XOR:
case EXPRESSION_TYPE_LEFT_SHIFT:
case EXPRESSION_TYPE_RIGHT_SHIFT:
case EXPRESSION_TYPE_LOGIC_RIGHT_SHIFT:
case EXPRESSION_TYPE_MUL:
case EXPRESSION_TYPE_DIV:
case EXPRESSION_TYPE_MOD:
case EXPRESSION_TYPE_ADD:
case EXPRESSION_TYPE_SUB:
case EXPRESSION_TYPE_GT:
case EXPRESSION_TYPE_GEQ:
case EXPRESSION_TYPE_LT:
case EXPRESSION_TYPE_LEQ:
case EXPRESSION_TYPE_EQ:
case EXPRESSION_TYPE_NEQ:
case EXPRESSION_TYPE_AND:
case EXPRESSION_TYPE_OR:
expression_free(expr->u.binary_expr->left);
expression_free(expr->u.binary_expr->right);
mem_free(expr->u.binary_expr);
break;
case EXPRESSION_TYPE_ARRAY_GENERATE:
list_safe_for_each(expr->u.expressions_expr, iter, next_iter) {
list_erase(expr->u.expressions_expr, *iter);
expression_free(list_element(iter, expression_t, link));
}
break;
case EXPRESSION_TYPE_TABLE_GENERATE:
list_safe_for_each(expr->u.expressions_expr, iter, next_iter) {
list_erase(expr->u.expressions_expr, *iter);
expression_free_table_pair(list_element(iter, expression_table_pair_t, link));
}
break;
case EXPRESSION_TYPE_ARRAY_PUSH:
expression_free(expr->u.array_push_expr->array_expr);
expression_free(expr->u.array_push_expr->elem_expr);
mem_free(expr->u.array_push_expr);
break;
case EXPRESSION_TYPE_ARRAY_POP:
expression_free(expr->u.array_pop_expr->array_expr);
expression_free(expr->u.array_pop_expr->lvalue_expr);
mem_free(expr->u.array_pop_expr);
break;
case EXPRESSION_TYPE_TABLE_DOT_MEMBER:
expression_free(expr->u.table_dot_member_expr->table_expr);
cstring_free(expr->u.table_dot_member_expr->member_name);
mem_free(expr->u.table_dot_member_expr);
break;
case EXPRESSION_TYPE_INDEX:
expression_free(expr->u.index_expr->dict);
expression_free(expr->u.index_expr->index);
mem_free(expr->u.index_expr);
break;
default:
break;
}
mem_free(expr);
}
|
C
|
#include "mini.h"
static int valid_exit2(int i, char *command, int *res)
{
char *tmp;
if (i > 1 && ft_isnumber(command))
{
ft_error("exit: ", "too many arguments", 1);
*res = 1;
}
else
{
if (ft_isnumber(command) ||
(command[0] == '-' && ft_isnumber(&command[1])))
ft_atoi(command, &g_exit);
else
{
if (!(tmp = ft_strjoin("exit: ", command)))
return (ft_error("malloc", ": memory allocation error.", 1));
ft_error(tmp, ": numeric argument required", 255);
free(tmp);
}
}
return (1);
}
int valid_exit(char **str)
{
int i;
int res;
i = 0;
res = 0;
write(2, "exit\n", 5);
if (!str)
{
g_exit = 0;
return (res);
}
while (str[i])
i++;
i ? valid_exit2(i, str[0], &res) : 0;
return (res);
}
|
C
|
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include "graphics_lib.h"
int buffer_changed = 0;
void init() {
get_screen_size();
old_w.ws_row = 0;
old_w.ws_col = 0;
}
void init_buffer() {
srand(time(NULL));
for (int i = 0; i < 500; ++i) {
for (int j = 0; j < 500; ++j) {
// buffer[i][j].character = 65;
// buffer[i][j] = {' ', 0, 0, 0, 5, 5, 5};
// buffer[i][j].r = rand() % 6;
// buffer[i][j].g = rand() % 6;
// buffer[i][j].b = rand() % 6;
// buffer[i][j].br = rand() % 6;
// buffer[i][j].bg = rand() % 6;
// buffer[i][j].bb = rand() % 6;
buffer[i][j].character = ' ';
// buffer[i][j] = {' ', 0, 0, 0, 5, 5, 5};
buffer[i][j].r = 5;
buffer[i][j].g = 5;
buffer[i][j].b = 5;
buffer[i][j].br = 0;
buffer[i][j].bg = 0;
buffer[i][j].bb = 0;
}
}
}
/*!
* Refreshing the buffer
*/
void refresh() {
system("clear");
fprintf(log_file, "The system screen is %d * %d\n", w.ws_row, w.ws_col);
int i;
for (i = 0; i < w.ws_row - 1; ++i) {
for (int j = 0; j < w.ws_col; ++j) {
fprintf(log_file, "%c", buffer[i][j].character);
printf("\e[38;5;%dm\e[48;5;%dm%c\e[0m", buffer[i][j].b * 36 + buffer[i][j].g * 6 + buffer[i][j].r + 16,
buffer[i][j].bb * 36 + buffer[i][j].bg * 6 + buffer[i][j].br + 16, buffer[i][j].character);
// printf("3");
}
fprintf(log_file, "\n");
printf("\n");
}
for (int j = 0; j < w.ws_col; ++j) {
fprintf(log_file, "%c", buffer[i][j].character);
printf("\e[38;5;%dm\e[48;5;%dm%c\e[0m", buffer[i][j].b * 36 + buffer[i][j].g * 6 + buffer[i][j].r + 16,
buffer[i][j].bb * 36 + buffer[i][j].bg * 6 + buffer[i][j].br + 16, buffer[i][j].character);
// printf("%c", buffer[i][j]);
// printf("4");
}
fflush(stdout);
// printf("Fuck you");
}
/*!
* Setting the foreground
* \param p_buffer_point pointer to the buffer point.
* \param r the red value
* \param g the green value
* \param b the blue value
* \sa set_background()
*/
void set_foreground(struct buffer_point *p_buffer_point, int r, int g, int b) {
p_buffer_point->r = r;
p_buffer_point->g = g;
p_buffer_point->b = b;
}
/*!
* Setting the background
* \param p_buffer_point pointer to the buffer point.
* \param r the red value
* \param g the green value
* \param b the blue value
* \sa set_foreground()
*/
void set_background(struct buffer_point *p_buffer_point, int r, int g, int b) {
p_buffer_point->br = r;
p_buffer_point->bg = g;
p_buffer_point->bb = b;
}
void draw_circle() {
}
// void
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_char.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bbrunell <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/26 14:05:35 by bbrunell #+# #+# */
/* Updated: 2016/05/26 14:05:37 by bbrunell ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static void print_charmin(t_flags *fl, t_line *li)
{
while (fl->field_size > 1)
{
if (fl->zero == 1)
buff_join("0", &li->b);
else
buff_join(" ", &li->b);
fl->field_size--;
}
}
static void printchar(va_list ap, t_flags *fl, t_line *li)
{
char *c;
c = (char*)malloc(sizeof(char) * 2);
if (!c)
return ;
c[0] = va_arg(ap, int);
c[1] = '\0';
if (fl->min == 0)
print_charmin(fl, li);
if (c[0] != 0)
buff_join(c, &li->b);
else
buff_join_char(0, &li->b);
if (fl->min == 1)
{
while (fl->field_size > 1)
{
buff_join(" ", &li->b);
fl->field_size--;
}
}
}
static void printwchar(va_list ap, t_flags *fl, t_line *li)
{
unsigned int nbr;
char *str;
li->ret = 0;
nbr = va_arg(ap, wchar_t);
if ((nbr > 55295 && nbr < 57344) || nbr > 1114111)
{
li->ret = -1;
return ;
}
if (fl->min == 0)
print_charmin(fl, li);
if (nbr == 0)
buff_join_char(0, &li->b);
else
{
str = ft_convwchar(nbr);
buff_join(str, &li->b);
free(str);
}
if (fl->min == 1)
while (--fl->field_size > 0)
buff_join(" ", &li->b);
}
void printf_char(va_list ap, t_flags *fl, t_line *li)
{
if ((fl->type == 'c' && fl->type_var1 == 'l') || fl->type == 'C')
printwchar(ap, fl, li);
else
printchar(ap, fl, li);
}
|
C
|
/* ------------------------------------------------------------------------
* hello.c: hello, kernel world
*
* Mark P. Jones, February 2008
*/
/*-------------------------------------------------------------------------
* Video RAM:
*/
#define COLUMNS 80
#define LINES 25
#define ATTRIBUTE 12
#define VIDEO 0xB8000
typedef unsigned char single[2];
typedef single row[COLUMNS];
typedef row screen[LINES];
extern void clear();
int numdigits(unsigned int);
static screen* video = (screen*)VIDEO;
/*-------------------------------------------------------------------------
* Cursor coordinates:
*/
static int xpos = 0;
static int ypos = 0;
/*-------------------------------------------------------------------------
* Clear the screen.
*/
void cls(void) {
int i, j;
for (i=0; i<LINES; ++i) {
for (j=0; j<COLUMNS; ++j) {
(*video)[i][j][0] = ' ';
(*video)[i][j][1] = ATTRIBUTE+j+i;
}
}
ypos = 0;
xpos = 0;
}
/*
* Returns base 10 number as one digit of base 16
*/
char hexify_digit(unsigned int x)
{
if(x < 10)
return x + '0';
if(x < 17)
return x + 'A' - 10;
return -1;
}
void scroll_up()
{
int i, j;
for(i = 0; i < LINES - 1; ++i)
{
for(j = 0; j < COLUMNS; ++j)
{
(*video)[i][j][0] = (*video)[i+1][j][0];
(*video)[i][j][1] = (*video)[i+1][j][1];
}
}
++i;
for(j = 0; j < COLUMNS; ++j)
{
(*video)[i][j][0] = ' ';
(*video)[i][j][1] = ATTRIBUTE;
}
}
/*-------------------------------------------------------------------------
* Output a single character.
*/
void putchar(char c) {
int i, j;
if (c!='\n' && c!='\r') {
(*video)[ypos][xpos][0] = c & 0xFF;
(*video)[ypos][xpos][1] = ATTRIBUTE;
if (++xpos < COLUMNS) {
return;
}
}
xpos = 0; // Perform a newline
if (++ypos >= LINES) { // scroll up top lines of screen ...
ypos = LINES-1;
for (i=0; i<ypos; ++i) {
for (j=0; j<COLUMNS; ++j) {
(*video)[i][j][0] = (*video)[i+1][j][0];
(*video)[i][j][1] = (*video)[i+1][j][1];
}
}
for (j=0; j<COLUMNS; ++j) { // fill in new blank line
(*video)[ypos][j][0] = ' ';
(*video)[ypos][j][1] = ATTRIBUTE;
}
}
}
/*-------------------------------------------------------------------------
* Output a zero-terminated string.
*/
void puts(char *msg) {
while (*msg) {
putchar(*msg++);
}
}
/*-------------------------------------------------------------------------
* Output an eight character string with the hexadecimal representation of
* argument n. E.g., 10 would be displayed as 0000000A and 1024 as 00000400
*/
void outhex(unsigned int num)
{
char hexes[9] = "";
unsigned int temp = 0;
int i = 0;
while(num && i < 8)
{
temp = num & 0xf;
hexes[i] = hexify_digit(temp);
num >>= 4;
++i;
}
if(i > 0)
{
--i;
for(; i > -1; --i)
putchar(hexes[i]);
}
}
/*
* Convert an integer into a char array
*/
void outint(unsigned int num)
{
int x;
int digs = numdigits(num);
char output[digs + 1];
output[digs] = '\0';
while(num > 0 && digs > 0)
{
--digs;
x = (num % 10) + '0';
output[digs] = x;
num /= 10;
}
puts(output);
}
/*
* count number of digits in an unsigned int
* dumb but fast
*/
int numdigits(unsigned int num)
{
if(num < 10) return 1;
if(num < 100) return 2;
if(num < 1000) return 3;
if(num < 10000) return 4;
if(num < 100000) return 5;
if(num < 1000000) return 6;
if(num < 10000000) return 7;
if(num < 100000000) return 8;
if(num < 1000000000) return 9;
return 10; //max digit count for 32 bit unsigned int
}
/*-------------------------------------------------------------------------
* Main program:
*/
void hello() {
int i;
clear();
for (i=0; i<2; i++) {
puts("hhhh hhhh\n");
puts(" hh hhh lll lll\n");
puts(" hh hh eeee ll ll oooo\n");
puts(" hhhhhhhh ee ee ll ll oo oo\n");
puts(" hh hh eeeeeee ll ll oo oo\n");
puts(" hh hh ee ll ll oo oo\n");
puts("hhh hhhh eeee ll ll oooo\n");
puts("\n");
puts(" K e r n e l W o r l d\n");
puts(" October 13th 2017\n");
}
outhex(120);
putchar('\n');
outhex(123456789);
putchar('\n');
outint(987654321);
scroll_up();
scroll_up();
}
/* --------------------------------------------------------------------- */
|
C
|
/*
Contains the interface for the weather storage module, which takes care of
bringing weather data in and out of persistent storage.
*/
#ifndef WEATHER_STORAGE_H
#define WEATHER_STORAGE_H
/* Included files */
// Boolean type
#include <stdbool.h>
/* Constants */
// Key to read and write the temperature in persistent storage
#define TEMPERATURE_KEY 0
// Key to access the weather conditions in string form in peristent storage
#define CONDITIONS_BUFFER_KEY 1
// Key to access the id of the weather conditions in peristent storage
#define CONDITIONS_ID_KEY 2
// Size of a string stored in local storage
#define STORED_BUFFER_SIZE 32
/* Prototypes */
// Tells whether there's any saved weather data
bool saved_data_exists(void);
// Gets the temperature from persistent storage
int load_temperature(void);
// Gets the conditions buffer from persistent storage
void load_conditions_buffer(
char *conditions_buffer, int conditions_buffer_size);
// Gets the conditions id from persistent storage
int load_conditions_id();
// Saves the temperature to persistent storage
void save_temperature(const int temperature);
// Saves the conditions buffer to persistent storage
void save_conditions_buffer(const char *conditions_buffer);
// Saves the conditions id to persistent storage
void save_conditions_id(const int conditions_id);
#endif
|
C
|
#include<stdio.h>
void input();
void process();
void output();
long int arr[100000];
int n,max,lastIndex,t,testCases;
int main()
{
scanf("%d",&testCases);
for(int j=0; j<testCases; j++)
{
input();
process();
output();
}
}
void input()
{
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%ld",&arr[i]);
}
}
void process()
{
for(int i=0; i<n; i++)
{
lastIndex=n-1;
while(arr[i]<arr[lastIndex])
{
lastIndex--;
}
t=lastIndex-i+1;
if(t>max)
{
max = t;
}
}
}
void output()
{
printf("%d",max);
}
|
C
|
#include <stdlib.h>
#include "IncreasinglySortedArrayPQ.h"
struct _IncreasinglySortedArrayPQ{
int maxLength;
int length;
int* body;
};
IncreasinglySortedArrayPQ * IncreasinglySortedArrayPQ_new (int maxsize)
{
IncreasinglySortedArrayPQ* temp=NewObject(IncreasinglySortedArrayPQ);//ο Ʈ
int i=0;
temp->maxLength=maxsize;//ִ ̸ ִ
temp->length=0;//ʱⰳ 0
temp->body=NewVector(int ,maxsize);//迭 Ҵ
while(i<maxsize)
{
temp->body[i++]=-1;//迭 ʱȭ
}
return temp;// Ʈ ȯ
}
void IncreasinglySortedArrayPQ_free (IncreasinglySortedArrayPQ * _this)
{
free(_this->body);
}
Bool IncreasinglySortedArrayPQ_isEmpty (IncreasinglySortedArrayPQ * _this)
{
if(_this->length==0)//Ұ 0
{
return T;//T ȯ
}
return F;//F ȯ
}
Bool IncreasinglySortedArrayPQ_isFull (IncreasinglySortedArrayPQ * _this)
{
if(_this->length==_this->maxLength)// Ұ ִ Ұ
{
return T;//T ȯ
}
return F;// FULL ƴҰ F ȯ
}
void IncreasinglySortedArrayPQ_insert (IncreasinglySortedArrayPQ * _this, Element e)
{
int i=0, j=0, temp;
while(i<_this->length)
{
if(e>=_this->body[i])
{
i++;
if(_this->body[i]==-1)
{
_this->body[_this->length++]=e;
i=_this->length;
break;
}
}
if(e<_this->body[i])
{
j=i+1;
while((_this->length)!=j)
{
temp=_this->body[j];
_this->body[j]=_this->body[j-1];
j++;
}
_this->body[i]=e;
i=++_this->length;
}
}
if(_this->length==0)
{
_this->body[0]=e;
_this->length++;
}
}
Element IncreasinglySortedArrayPQ_deleteMin (IncreasinglySortedArrayPQ * _this)
{
int i=0, min;
min=_this->body[i];
while(i<_this->length)
{
_this->body[i]=_this->body[i+1];
i++;
}
_this->length--;
return min;
}
|
C
|
// APS105 Assignment 3 Starter Code
// Jonathan Deber (deberjon) 991234567
// A letter frequency counter.
#include <stdio.h>
#include "histogram.h"
/* The list of possible letters. Note that although this is a char[], it is not a string, since it is not null terminated. */
const char LETTERS[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
/* The number of possible letters. Note that we calculate this based on the contents of LETTERS, so that this value is automatically updated if the contents of LETTERS were to change. */
#define NUM_LETTERS (sizeof(LETTERS) / sizeof(char))
/* Special index used to indicate that a letter was not found in LETTERS. */
#define LETTER_NOT_FOUND -1
/* The max length of text we can handle. Additional characters are silently ignored. */
#define TEXT_MAX_LENGTH 1024
/* The maximum number of symbols in one histogram row. */
#define HISTOGRAM_ROW_LENGTH 55
/* The symbol used to draw the histogram . */
#define HISTOGRAM_SYMBOL '-'
/* Should we print out extra debugging information? */
/* MUST be set to false prior to submission. */
#define DEBUGGING false
/*
* Begin Changes Here.
*/
// Add any new constants here
/*
* End Changes Here.
*/
/* Function Declarations. */
/* Returns the index in LETTERS that corresponds to the letter 'letter', or LETTER_NOT_FOUND if 'letter' does not occur in LETTERS. */
int letterToIndex(char letter);
/*
* Begin Changes Here.
*/
// Add any new function prototypes here
void printHistogram (int i, int numSymbols, char *row);
int countMaxValue (int *occurrences);
/*
* End Changes Here.
*/
#ifndef LETTERFREQUENCY_MAIN_DISABLED // This line is used by the auto-marker
int main(void)
{
/*
* Begin Changes Here (Step 11).
*/
// Print out our prompt
printf("Enter some text (characters other than lowercase letters will be ignored): ");
// Allocate a buffer to hold the user input
char input[TEXT_MAX_LENGTH + 1];
// Read in our sequence, using fgets()
fgets(input, TEXT_MAX_LENGTH + 1, stdin);
/*
* End Changes Here.
*/
/*
* Begin Changes Here (Step 12).
*/
// Create an array to hold the occurrences of each letter. The indices correspond to the indices of LETTERS.
int countOccurrences[NUM_LETTERS] = {0};
// Process the user's text until we run out of characters
char *p;
for (p = input; (*p != '\0') && (*p != '\n'); p++)
{
// Convert our letter to an array index
int index = letterToIndex(*p);
// If it's a valid index, then we want to count it
if (index != LETTER_NOT_FOUND)
{
++*(countOccurrences + index);
}
// Otherwise, skip it and print a message
else
{
printf("Skipping non-lowercase letter: '%c'.\n", *p);
}
}
/*
* End Changes Here.
*/
/*
* Begin Changes Here (Step 14).
*/
// Print out the numeric results
int i;
printf("Here are the results in numeric form:\n");
for (i = 0; i < NUM_LETTERS; i++)
{
printf("%c: %d\n", *(LETTERS + i), *(countOccurrences + i));
}
// Generate and print out the histogram
printf("Here are the results as a histogram:\n");
char row[HISTOGRAM_ROW_LENGTH + 1];
for (i = 0; i < NUM_LETTERS; i++)
{
/* The string to fill in with our histogram. */
// Generate the histogram row
int maxValue = countMaxValue (countOccurrences);
int numSymbols = createHistogramRow(row, HISTOGRAM_SYMBOL, *(countOccurrences + i), maxValue, HISTOGRAM_ROW_LENGTH);
// And print it out
printHistogram (i, numSymbols, row);
}
/*
* End Changes Here.
*/
return 0;
}
#endif // This line is used by the auto-marker
int letterToIndex(char letter)
{
/*
* Begin Changes Here (Step 13).
*/
// Go through each letter in LETTERS, and see if it's a match
int i;
for (i = 0; i < NUM_LETTERS; i++)
{
if (letter == *(LETTERS + i))
{
return i;
}
}
return LETTER_NOT_FOUND;
/*
* End Changes Here.
*/
}
/*
* Begin Changes Here.
*/
// Add any new functions here
void printHistogram (int i, int numSymbols, char *row)
{
int j;
printf("%c:|", *(LETTERS + i));
for (j = 0; j < numSymbols; j++)
{
printf("%c", *(row + j));
}
printf("|\n");
}
int countMaxValue (int *occurrences)
{
int i, sum = 0;
for (i = 0; i < NUM_LETTERS; i++)
{
sum += *(occurrences + i);
}
return sum;
}
/*
* End Changes Here.
*/
|
C
|
#include<stdio.h>
int main(){
int A,B,D;
int s=0;
int min=0;
scanf("%d", &A);
scanf("%d", &B);
scanf("%d", &D);
while(1){
D-=A;
min++;
if(D<=0)
break;
D+=B;
}
printf("Answer : %d\n", min);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
int wynik = 1;
printf("Powdaj liczbe wieksza od 2: \n");
scanf("%d", &n);
if(n<2)
{
printf("Podales zla liczbe :(");
}
else
{
for(int i=2; i<=n; i = i+2)
{
wynik *= i;
}
printf("Wynik jest rowny: %d", wynik);
}
return 0;
}
|
C
|
#include "sandslhash.h"
struct sandslhash {
int N;
int M; //size of linear probing table
Key *keys;
Val *vals;
};
hash_table create_hash_table(int size) {
hash_table h = malloc(sizeof(struct sandslhash));
h->M = size; //??????????????????
h->N = 0;
h->keys = malloc(sizeof(void *) * size);
h->vals = malloc(sizeof(void *) * size);
return h;
}
int hash_code(hash_table, Key);
bool contains(hash_table h, Key key) { return get(h, key) != NULL; }
int hash(hash_table h, Key key) { return (hash_code(h, key) & 0x7fffffff) % h->M; }
int hash_code(hash_table h, Key key) {
int hsh = 0;
//char *ptr = key;
//for (ptr = key; ptr != '\0'; ptr++) hsh += *ptr + (31 * hsh);
int i;
for (i = 0; i < strlen(key); i++) hsh += key[i] + (31 * hsh);
return hsh;
}
void resize_hash(hash_table h, int size) {
printf("resizing hash table...\n");
hash_table hold = create_hash_table(size);
int i;
for (i = 0; i < h->M; i++) {
if (h->keys[i] != NULL) {
put(hold, h->keys[i], h->vals[i]);
}
}
realloc(h->keys, sizeof(void *) * size);
realloc(h->vals, sizeof(void *) * size);
for (i = 0; i < size; i++) {
h->keys[i] = hold->keys[i];
h->vals[i] = hold->vals[i];
}
h->M = hold->M;
}
void put(hash_table h, Key key, Val val) {
if (val == NULL) remove(key);
if (h->N >= h->M / 2) resize_hash(h, 2 * (h->M));
int i;
for (i = hash(h, key); h->keys[i] != NULL; i = (i + 1) % h->M) {
if (strcmp(h->keys[i], key) == 0) {
h->vals[i] = val;
return;
}
}
h->keys[i] = key;
h->vals[i] = val;
(h->N)++;
}
Val get(hash_table h, Key key) {
int i;
for (i = hash(h, key); h->keys[i] != NULL; i = (i + 1) % h->M)
if (strcmp(h->keys[i], key) == 0)
return h->vals[i];
return NULL;
}
void del_key(hash_table h, Key key) {
if (!contains(h, key)) return;
int i = hash(h, key);
while (strcmp(h->keys[i], key) != 0) {
i = (i + 1) % h->M;
}
h->keys[i] = NULL;
h->vals[i] = NULL;
i = (i + 1) % h->M;
while (h->keys[i] != NULL) {
Key key_rehash = h->keys[i];
Val val_rehash = h->vals[i];
h->keys[i] = NULL;
h->vals[i] = NULL;
(h->N)--;
put(h, key_rehash, val_rehash);
i = (i + 1) % h->M;
}
(h->N)--;
if (h->N > 0 && h->N <= (h->M / 8)) resize_hash(h, h->M / 2);
}
void print_hash_table(hash_table h) {
int i;
printf("\n\t\tonline pool:\n");
for (i = 0; i < h->M; i++) {
printf("%s %s\n", h->keys[i], h->vals[i]);
}
printf("------------------------------\n\n");
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
//int main()
//{
//// int arr[3][4] = { { 1, 2 }, { 2, 3, 4}, {3,4,5,6} };
//
//// arr[1][2] = 1;
//
// //int arr[3][4] = {1,2,3,4,5,6,7,8,9};
// return 0;
//}
#include <stdio.h>
//
//int main()
//{
// int a[2][3] = {1,2,3,4,5,6};
// int b[3][2] = { 0 };
//
// int i = 0;
// int j = 0;
// for (i = 0; i < 2; i++)
// {
// for (j = 0; j < 3; j++)
// {
// b[j][i] = a[i][j];
// //b[0][0] = a[0][0]
// //b[1][0] = a[0][1]
// //b[2][0] = a[0][2]
// }
// }
// for (i = 0; i < 3; i++)
// {
// for (j = 0; j < 2; j++)
// {
// printf("%d ", b[i][j]);
// }
// printf("\n");
// }
// return 0;
//}
//
//int main()
//{
// int arr[3][4] = { 0 };
// int i = 0;
// int j = 0;
// for (i = 0; i < 3; i++)
// {
// for (j = 0; j < 4; j++)
// {
// scanf("%d", &arr[i][j]);
// }
// }
//
// int max = arr[0][0];//arr[0][0]Ԫ
// int x = 0;
// int y = 0;
// for (i = 0; i < 3; i++)
// {
// for (j = 0; j < 4; j++)
// {
// if (arr[i][j]>max)
// {
// max = arr[i][j];
// x = i;
// y = j;
// }
// }
// }
//
// printf("max = %d, ±ǣ%d %d\n", max, x, y);
//
// return 0;
//}
//int main()
//{
// char ch1[5] = {'a', 'b', 'c', 'd', 'e'};
// char ch2[] = { 'a', 'b', 'c', 'd' , 'e'};
//
// return 0;
//}
//int main()
//{
// char arr[] = {'b', 'a', 'q', 'e', 'r'};
// int i = 0;
// for (i = 0; i < 5; i++)
// {
// printf("%c ", arr[i]);
// }
//
// return 0;
//}
//ַ
//Cûַ
//"abcdef"
//"a";
//"";//ַ
//int main()
//{
// //char arr[] = "i am a student";
// //char arr2[] = {'i', ' ', 'a', 'm '};
// char arr1[] = "bit";
// char arr2[] = { 'b', 'i', '\0' ,'t'};
//
// printf("%s\n", arr1);
// printf("%s\n", arr2);
//
// //%s Ǵӡַַ-ַʽдӡ
//
// return 0;
//}
#include <string.h>
//
//int main()
//{
// char arr[] = "ab\0def";//ַ
// //a b c d e f \0
// //ַ
// int len = strlen(arr);//string length
// printf("%d\n", len);
//
// return 0;
//}
//int main()
//{
// //char arr[] = "abcdef";
// char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f', '\0'};
// int i = 0;
// /*for (i = 0; i< 6; i++)
// {
// printf("%c", arr[i]);
// }
//*/
// printf("%s\n", arr);
// return 0;
//}
//int main()
//{
// char arr[10];
// scanf("%s", arr);
// puts(arr);
// printf("--------------------\n");
// printf("%s\n", arr);
// return 0;
//}
//int main()
//{
// char arr[20] = { 0 };
// //scanf("%s", arr);
// //puts(arr);
// gets(arr);//Ϣarr
// puts(arr);//arrеϢ
//
// return 0;
//}
//
//int main()
//{
// char arr1[20] = "hello";//6
// char arr2[] = " world";
// strcat(arr1, arr2);
// puts(arr1);//helloworld
//
// return 0;
//}
|
C
|
#include<stdio.h>
#include<stdlib.h>
float num1, tmp;
int main(void)
{
while(1)
{
printf("\nEnter sales in dollars (-1 to end):");
scanf("%f", &tmp);
if (tmp ==EOF )
break;
else
num1 = tmp;
num1 = 200 + num1*0.09;
printf("Salary is: $%.2lf\n ", num1);
}
printf("Program Endded.\n");
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%d",sumsquare()-squaresum());
}
int squaresum()
{
int result=0;
for (int i=1;i<101;i++)
{
result=result+(i*i);
}
return result;
}
int sumsquare()
{
int result=0;
for (int i=1;i<101;i++)
{
result=result+i;
}
return result*result;
}
|
C
|
#include "sdl2_pixels.h"
#include "mruby/array.h"
#include "mruby/class.h"
#include "mruby/data.h"
static struct RClass *class_PixelFormat = NULL;
static struct RClass *class_Palette = NULL;
typedef struct mrb_sdl2_pixels_palette_data_t {
bool is_associated;
SDL_Palette *palette;
} mrb_sdl2_pixels_palette_data_t;
static void
mrb_sdl2_pixels_palette_data_free(mrb_state *mrb, void *p)
{
mrb_sdl2_pixels_palette_data_t *data =
(mrb_sdl2_pixels_palette_data_t*)p;
if (NULL != data) {
if ((!data->is_associated) && (NULL != data->palette)) {
SDL_FreePalette(data->palette);
}
mrb_free(mrb, data);
}
}
static struct mrb_data_type const mrb_sdl2_pixels_palette_data_type = {
"palette", &mrb_sdl2_pixels_palette_data_free
};
SDL_Palette *
mrb_sdl2_pixels_palette_get_ptr(mrb_state *mrb, mrb_value palette)
{
mrb_sdl2_pixels_palette_data_t *data;
if (mrb_nil_p(palette))
return NULL;
data =
(mrb_sdl2_pixels_palette_data_t*)mrb_data_get_ptr(mrb, palette, &mrb_sdl2_pixels_palette_data_type);
return data->palette;
}
mrb_value
mrb_sdl2_pixels_palette(mrb_state *mrb, SDL_Palette *palette)
{
mrb_sdl2_pixels_palette_data_t *data;
if (NULL == palette) {
return mrb_nil_value();
}
data =
(mrb_sdl2_pixels_palette_data_t*)mrb_malloc(mrb, sizeof(mrb_sdl2_pixels_palette_data_t));
data->is_associated = false;
data->palette = palette;
return mrb_obj_value(Data_Wrap_Struct(mrb, class_Palette, &mrb_sdl2_pixels_palette_data_type, data));
}
mrb_value
mrb_sdl2_pixels_associated_palette(mrb_state *mrb, SDL_Palette *palette)
{
mrb_sdl2_pixels_palette_data_t *data;
if (NULL == palette) {
return mrb_nil_value();
}
data =
(mrb_sdl2_pixels_palette_data_t*)mrb_malloc(mrb, sizeof(mrb_sdl2_pixels_palette_data_t));
data->is_associated = true;
data->palette = palette;
return mrb_obj_value(Data_Wrap_Struct(mrb, class_Palette, &mrb_sdl2_pixels_palette_data_type, data));
}
typedef struct mrb_sdl2_pixels_pixelformat_data_t {
bool is_associated;
SDL_PixelFormat *pixelformat;
} mrb_sdl2_pixels_pixelformat_data_t;
static void
mrb_sdl2_pixels_pixelformat_data_free(mrb_state *mrb, void *p)
{
mrb_sdl2_pixels_pixelformat_data_t *data =
(mrb_sdl2_pixels_pixelformat_data_t*)p;
if (NULL != data) {
if ((!data->is_associated) && (NULL != data->pixelformat)) {
SDL_FreeFormat(data->pixelformat);
}
mrb_free(mrb, data);
}
}
static struct mrb_data_type const mrb_sdl2_pixels_pixelformat_data_type = {
"PixelFormat", &mrb_sdl2_pixels_pixelformat_data_free
};
SDL_PixelFormat *
mrb_sdl2_pixels_pixelformat_get_ptr(mrb_state *mrb, mrb_value pixelformat)
{
mrb_sdl2_pixels_pixelformat_data_t *data;
if (mrb_nil_p(pixelformat)) {
return NULL;
}
data =
(mrb_sdl2_pixels_pixelformat_data_t*)mrb_data_get_ptr(mrb, pixelformat, &mrb_sdl2_pixels_pixelformat_data_type);
return data->pixelformat;
}
mrb_value
mrb_sdl2_pixels_pixelformat(mrb_state *mrb, SDL_PixelFormat *pixelformat)
{
mrb_sdl2_pixels_pixelformat_data_t *data;
if (NULL == pixelformat) {
return mrb_nil_value();
}
data =
(mrb_sdl2_pixels_pixelformat_data_t*)mrb_malloc(mrb, sizeof(mrb_sdl2_pixels_pixelformat_data_t));
data->is_associated = false;
data->pixelformat = pixelformat;
return mrb_obj_value(Data_Wrap_Struct(mrb, class_PixelFormat, &mrb_sdl2_pixels_pixelformat_data_type, data));
}
mrb_value
mrb_sdl2_pixels_associated_pixelformat(mrb_state *mrb, SDL_PixelFormat *pixelformat)
{
mrb_sdl2_pixels_pixelformat_data_t *data;
if (NULL == pixelformat) {
return mrb_nil_value();
}
data =
(mrb_sdl2_pixels_pixelformat_data_t*)mrb_malloc(mrb, sizeof(mrb_sdl2_pixels_pixelformat_data_t));
data->is_associated = true;
data->pixelformat = pixelformat;
return mrb_obj_value(Data_Wrap_Struct(mrb, class_PixelFormat, &mrb_sdl2_pixels_pixelformat_data_type, data));
}
/***************************************************************************
*
* module SDL2::Pixels
*
***************************************************************************/
static mrb_value
mrb_sdl2_pixels_get_pixel_format_name(mrb_state *mrb, mrb_value mod)
{
mrb_int format;
mrb_value result;
mrb_get_args(mrb, "i", &format);
result = mrb_str_new_cstr(mrb, SDL_GetPixelFormatName((int) format));
return result;
}
static mrb_value
mrb_sdl2_pixels_format_to_masks(mrb_state *mrb, mrb_value mod)
{
mrb_int format;
int bpp;
Uint32 Rmask;
Uint32 Gmask;
Uint32 Bmask;
Uint32 Amask;
mrb_value array;
mrb_get_args(mrb, "i", &format);
if (SDL_PixelFormatEnumToMasks((Uint32) format, &bpp, &Rmask, &Gmask, &Bmask, &Amask) != SDL_FALSE) {
array = mrb_ary_new_capa(mrb, 4);
mrb_ary_push(mrb, array, mrb_fixnum_value(bpp));
mrb_ary_push(mrb, array, mrb_fixnum_value(Rmask));
mrb_ary_push(mrb, array, mrb_fixnum_value(Gmask));
mrb_ary_push(mrb, array, mrb_fixnum_value(Amask));
return array;
}
return mrb_false_value();
}
static mrb_value
mrb_sdl2_pixels_masks_to_format(mrb_state *mrb, mrb_value mod) {
mrb_int bpp, Rmask, Gmask, Bmask, Amask;
Uint32 result;
mrb_get_args(mrb, "iiiii", &bpp, &Rmask, &Gmask, &Bmask, &Amask);
result = SDL_MasksToPixelFormatEnum((int) bpp, (Uint32) Rmask, (Uint32) Gmask, (Uint32) Bmask, (Uint32) Amask);
if (result == SDL_PIXELFORMAT_UNKNOWN)
return mrb_false_value();
return mrb_fixnum_value((mrb_int) result);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_set_palette(mrb_state *mrb, mrb_value self)
{
mrb_value palette;
SDL_PixelFormat * pixelformat_p;
SDL_Palette * palette_p;
int result;
mrb_get_args(mrb, "o", &palette);
pixelformat_p = mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self);
palette_p = mrb_sdl2_pixels_palette_get_ptr(mrb, palette);
result = SDL_SetPixelFormatPalette(pixelformat_p, palette_p);
if (0 > result) {
// error occurred
mruby_sdl2_raise_error(mrb);
}
return self;
}
static mrb_value
mrb_sdl2_pixels_palette_set_color(mrb_state *mrb, mrb_value self)
{
mrb_int r, g, b, a, firstcolor, ncolors;
SDL_Palette *palette_p;
int result;
SDL_Color color;
mrb_get_args(mrb, "iiiiii", &r, &g, &b, &a, &firstcolor, &ncolors);
color.r = (Uint8) r;
color.g = (Uint8) g;
color.b = (Uint8) b;
color.a = (Uint8) a;
palette_p = mrb_sdl2_pixels_palette_get_ptr(mrb, self);
result = SDL_SetPaletteColors(palette_p, &color, (int) firstcolor, (int) ncolors);
if (result == 1) {
// error occurred
mruby_sdl2_raise_error(mrb);
}
return self;
}
static mrb_value
mrb_sdl2_pixels_pixelformat_map_rgb(mrb_state *mrb, mrb_value self)
{
mrb_int r, g, b;
Uint32 result;
SDL_PixelFormat * pixelformat_p;
mrb_get_args(mrb, "iii", &r, &g, &b);
pixelformat_p = mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self);
result = SDL_MapRGB(pixelformat_p, (Uint8) r, (Uint8) g, (Uint8) b);
return mrb_fixnum_value((mrb_int) result);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_map_rgba(mrb_state *mrb, mrb_value self)
{
mrb_int r, g, b, a;
Uint32 result;
SDL_PixelFormat * pixelformat_p;
mrb_get_args(mrb, "iiii", &r, &g, &b, &a);
pixelformat_p = mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self);
result = SDL_MapRGBA(pixelformat_p, (Uint8) r, (Uint8) g, (Uint8) b, (Uint8) a);
return mrb_fixnum_value((mrb_int) result);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_rgb(mrb_state *mrb, mrb_value self)
{
mrb_int pixel;
Uint8 r;
Uint8 g;
Uint8 b;
SDL_PixelFormat * pixelformat_p;
mrb_value array;
mrb_get_args(mrb, "i", &pixel);
pixelformat_p = mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self);
SDL_GetRGB((Uint32) pixel, pixelformat_p, &r, &g ,&b);
array = mrb_ary_new_capa(mrb, 3);
mrb_ary_push(mrb, array, mrb_fixnum_value(r));
mrb_ary_push(mrb, array, mrb_fixnum_value(g));
mrb_ary_push(mrb, array, mrb_fixnum_value(b));
return array;
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_rgba(mrb_state *mrb, mrb_value self)
{
mrb_int pixel;
Uint8 r;
Uint8 g;
Uint8 b;
Uint8 a;
SDL_PixelFormat * pixelformat_p;
mrb_value array;
mrb_get_args(mrb, "i", &pixel);
pixelformat_p = mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self);
SDL_GetRGBA((Uint32) pixel, pixelformat_p, &r, &g , &b, &a);
array = mrb_ary_new_capa(mrb, 4);
mrb_ary_push(mrb, array, mrb_fixnum_value(r));
mrb_ary_push(mrb, array, mrb_fixnum_value(g));
mrb_ary_push(mrb, array, mrb_fixnum_value(b));
mrb_ary_push(mrb, array, mrb_fixnum_value(a));
return array;
}
static mrb_value
mrb_sdl2_pixels_calculate_gamma_ramp(mrb_state *mrb, mrb_value self)
{
mrb_float gamma;
Uint16 ramp;
mrb_get_args(mrb, "f", &gamma);
SDL_CalculateGammaRamp((float) gamma, &ramp);
return mrb_fixnum_value(ramp);
}
/***************************************************************************
*
* module SDL2::Pixels::PixelFormat
*
***************************************************************************/
mrb_value
mrb_sdl2_pixels_pixelformat_new(mrb_state *mrb, SDL_PixelFormat *format)
{
//@todo how do better?
mrb_sdl2_pixels_pixelformat_data_t *data;
mrb_value args[] = {mrb_fixnum_value(format->format)};
mrb_value oformat = mrb_obj_new(mrb, class_PixelFormat, 1, args);
data = (mrb_sdl2_pixels_pixelformat_data_t*)DATA_PTR(oformat);
data->pixelformat = format;
DATA_PTR(oformat) = data;
return oformat;
}
static mrb_value
mrb_sdl2_pixels_pixelformat_initialize(mrb_state *mrb, mrb_value self)
{
SDL_PixelFormat *pixelformat;
mrb_sdl2_pixels_pixelformat_data_t *data =
(mrb_sdl2_pixels_pixelformat_data_t*)DATA_PTR(self);
if (NULL == data) {
data = (mrb_sdl2_pixels_pixelformat_data_t*)mrb_malloc(mrb, sizeof(mrb_sdl2_pixels_pixelformat_data_t));
data->is_associated = false;
data->pixelformat = NULL;
}
pixelformat = NULL;
if (1 == mrb->c->ci->argc) {
mrb_int pixel_format;
mrb_get_args(mrb, "i", &pixel_format);
pixelformat = SDL_AllocFormat((Uint32) pixel_format);
} else {
mrb_free(mrb, data);
mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments.");
}
if (NULL == pixelformat) {
mrb_free(mrb, data);
mruby_sdl2_raise_error(mrb);
}
data->pixelformat = pixelformat;
DATA_PTR(self) = data;
DATA_TYPE(self) = &mrb_sdl2_pixels_pixelformat_data_type;
return self;
}
static mrb_value
mrb_sdl2_pixels_pixelformat_free(mrb_state *mrb, mrb_value self)
{
mrb_sdl2_pixels_pixelformat_data_t *data =
(mrb_sdl2_pixels_pixelformat_data_t*)mrb_data_get_ptr(mrb, self, &mrb_sdl2_pixels_pixelformat_data_type);
if ((!data->is_associated) && (NULL != data->pixelformat)) {
SDL_FreeFormat(data->pixelformat);
data->pixelformat = NULL;
}
return self;
}
/***************************************************************************
*
* module SDL2::Pixels::palette
*
***************************************************************************/
static mrb_value
mrb_sdl2_pixels_palette_initialize(mrb_state *mrb, mrb_value self)
{
SDL_Palette *palette;
mrb_sdl2_pixels_palette_data_t *data =
(mrb_sdl2_pixels_palette_data_t*)DATA_PTR(self);
if (NULL == data) {
data = (mrb_sdl2_pixels_palette_data_t*)mrb_malloc(mrb, sizeof(mrb_sdl2_pixels_palette_data_t));
data->is_associated = false;
data->palette = NULL;
}
palette = NULL;
if (1 == mrb->c->ci->argc) {
mrb_int ncolors;
mrb_get_args(mrb, "i", &ncolors);
palette = SDL_AllocPalette((int) ncolors);
} else {
mrb_free(mrb, data);
mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments.");
}
if (NULL == palette) {
mrb_free(mrb, data);
mruby_sdl2_raise_error(mrb);
}
data->palette = palette;
DATA_PTR(self) = data;
DATA_TYPE(self) = &mrb_sdl2_pixels_palette_data_type;
return self;
}
static mrb_value
mrb_sdl2_pixels_palette_free(mrb_state *mrb, mrb_value self)
{
mrb_sdl2_pixels_palette_data_t *data =
(mrb_sdl2_pixels_palette_data_t*)mrb_data_get_ptr(mrb, self, &mrb_sdl2_pixels_palette_data_type);
if ((!data->is_associated) && (NULL != data->palette)) {
SDL_FreePalette(data->palette);
data->palette = NULL;
}
return self;
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_format(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->format);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_palette(mrb_state *mrb, mrb_value self) {
return mrb_sdl2_pixels_palette(mrb, (mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->palette));
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_BitsPerPixel(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->BitsPerPixel);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_BytesPerPixel(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->BytesPerPixel);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_padding(mrb_state *mrb, mrb_value self) {
Uint8 *r = mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->padding;
mrb_value array = mrb_ary_new_capa(mrb, 2);
mrb_ary_push(mrb, array, mrb_fixnum_value(r[0]));
mrb_ary_push(mrb, array, mrb_fixnum_value(r[1]));
return array;
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Rmask(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Rmask);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Gmask(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Gmask);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Bmask(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Bmask);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Amask(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Amask);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Rloss(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Rloss);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Gloss(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Gloss);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Bloss(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Bloss);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Aloss(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Aloss);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Rshift(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Rshift);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Gshift(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Gshift);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Bshift(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Bshift);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_Ashift(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->Ashift);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_refcount(mrb_state *mrb, mrb_value self) {
return mrb_fixnum_value(mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->refcount);
}
static mrb_value
mrb_sdl2_pixels_pixelformat_get_next(mrb_state *mrb, mrb_value self) {
return mrb_sdl2_pixels_associated_pixelformat(mrb, (mrb_sdl2_pixels_pixelformat_get_ptr(mrb, self)->next));
}
void
mruby_sdl2_pixels_init(mrb_state *mrb)
{
int arena_size;
struct RClass *mod_Pixels = mrb_define_module_under(mrb, mod_SDL2, "Pixels");
class_PixelFormat = mrb_define_class_under(mrb, mod_Pixels, "PixelFormat", mrb->object_class);
class_Palette = mrb_define_class_under(mrb, mod_Pixels, "Palette", mrb->object_class);
MRB_SET_INSTANCE_TT(class_PixelFormat, MRB_TT_DATA);
MRB_SET_INSTANCE_TT(class_Palette, MRB_TT_DATA);
mrb_define_module_function(mrb, mod_Pixels, "get_format_name", mrb_sdl2_pixels_get_pixel_format_name, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, mod_Pixels, "format_to_masks", mrb_sdl2_pixels_format_to_masks, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, mod_Pixels, "masks_to_format", mrb_sdl2_pixels_masks_to_format, MRB_ARGS_REQ(5));
mrb_define_module_function(mrb, mod_Pixels, "calculate_gamma_ramp", mrb_sdl2_pixels_calculate_gamma_ramp, MRB_ARGS_REQ(1));
mrb_define_method(mrb, class_PixelFormat, "initialize", mrb_sdl2_pixels_pixelformat_initialize, MRB_ARGS_REQ(1));
mrb_define_method(mrb, class_PixelFormat, "destroy", mrb_sdl2_pixels_pixelformat_free, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "free", mrb_sdl2_pixels_pixelformat_free, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "format", mrb_sdl2_pixels_pixelformat_get_format, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "palette", mrb_sdl2_pixels_pixelformat_get_palette, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "depth", mrb_sdl2_pixels_pixelformat_get_BitsPerPixel, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "BitsPerPixel", mrb_sdl2_pixels_pixelformat_get_BitsPerPixel, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "BytesPerPixel", mrb_sdl2_pixels_pixelformat_get_BytesPerPixel, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "padding", mrb_sdl2_pixels_pixelformat_get_padding, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Rmask", mrb_sdl2_pixels_pixelformat_get_Rmask, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Gmask", mrb_sdl2_pixels_pixelformat_get_Gmask, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Bmask", mrb_sdl2_pixels_pixelformat_get_Bmask, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Amask", mrb_sdl2_pixels_pixelformat_get_Amask, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Rloss", mrb_sdl2_pixels_pixelformat_get_Rloss, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Gloss", mrb_sdl2_pixels_pixelformat_get_Gloss, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Bloss", mrb_sdl2_pixels_pixelformat_get_Bloss, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Aloss", mrb_sdl2_pixels_pixelformat_get_Aloss, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Rshift", mrb_sdl2_pixels_pixelformat_get_Rshift, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Gshift", mrb_sdl2_pixels_pixelformat_get_Gshift, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Bshift", mrb_sdl2_pixels_pixelformat_get_Bshift, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "Ashift", mrb_sdl2_pixels_pixelformat_get_Ashift, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "refcount", mrb_sdl2_pixels_pixelformat_get_refcount, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "next", mrb_sdl2_pixels_pixelformat_get_next, MRB_ARGS_NONE());
mrb_define_method(mrb, class_PixelFormat, "set_palette", mrb_sdl2_pixels_pixelformat_set_palette, MRB_ARGS_REQ(1));
mrb_define_method(mrb, class_PixelFormat, "mapRGB", mrb_sdl2_pixels_pixelformat_map_rgb, MRB_ARGS_REQ(3));
mrb_define_method(mrb, class_PixelFormat, "mapRGBA", mrb_sdl2_pixels_pixelformat_map_rgba, MRB_ARGS_REQ(4));
mrb_define_method(mrb, class_PixelFormat, "get_rgb", mrb_sdl2_pixels_pixelformat_get_rgb, MRB_ARGS_REQ(1));
mrb_define_method(mrb, class_PixelFormat, "get_rgba", mrb_sdl2_pixels_pixelformat_get_rgba, MRB_ARGS_REQ(1));
// SDL_MapRGB
mrb_define_method(mrb, class_Palette, "initialize", mrb_sdl2_pixels_palette_initialize, MRB_ARGS_REQ(1));
mrb_define_method(mrb, class_Palette, "set_color", mrb_sdl2_pixels_palette_set_color, MRB_ARGS_REQ(6) /*| MRB_ARGS_REQ(3)*/);
mrb_define_method(mrb, class_Palette, "destroy", mrb_sdl2_pixels_palette_free, MRB_ARGS_NONE());
mrb_define_method(mrb, class_Palette, "free", mrb_sdl2_pixels_palette_free, MRB_ARGS_NONE());
/* PixelFormats start */
arena_size = mrb_gc_arena_save(mrb);
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_UNKNOWN", mrb_fixnum_value(SDL_PIXELFORMAT_UNKNOWN));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_INDEX1LSB", mrb_fixnum_value(SDL_PIXELFORMAT_INDEX1LSB));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_INDEX1MSB", mrb_fixnum_value(SDL_PIXELFORMAT_INDEX1MSB));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_INDEX4LSB", mrb_fixnum_value(SDL_PIXELFORMAT_INDEX4LSB));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_INDEX4MSB", mrb_fixnum_value(SDL_PIXELFORMAT_INDEX4MSB));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_INDEX8", mrb_fixnum_value(SDL_PIXELFORMAT_INDEX8));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGB332", mrb_fixnum_value(SDL_PIXELFORMAT_RGB332));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGB444", mrb_fixnum_value(SDL_PIXELFORMAT_RGB444));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGB555", mrb_fixnum_value(SDL_PIXELFORMAT_RGB555));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGR555", mrb_fixnum_value(SDL_PIXELFORMAT_BGR555));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_ARGB4444", mrb_fixnum_value(SDL_PIXELFORMAT_ARGB4444));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGBA4444", mrb_fixnum_value(SDL_PIXELFORMAT_RGBA4444));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_ABGR4444", mrb_fixnum_value(SDL_PIXELFORMAT_ABGR4444));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGRA4444", mrb_fixnum_value(SDL_PIXELFORMAT_BGRA4444));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_ARGB1555", mrb_fixnum_value(SDL_PIXELFORMAT_ARGB1555));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGBA5551", mrb_fixnum_value(SDL_PIXELFORMAT_RGBA5551));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_ABGR1555", mrb_fixnum_value(SDL_PIXELFORMAT_ABGR1555));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGRA5551", mrb_fixnum_value(SDL_PIXELFORMAT_BGRA5551));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGB565", mrb_fixnum_value(SDL_PIXELFORMAT_RGB565));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGR565", mrb_fixnum_value(SDL_PIXELFORMAT_BGR565));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGB24", mrb_fixnum_value(SDL_PIXELFORMAT_RGB24));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGR24", mrb_fixnum_value(SDL_PIXELFORMAT_BGR24));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGB888", mrb_fixnum_value(SDL_PIXELFORMAT_RGB888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGBX8888", mrb_fixnum_value(SDL_PIXELFORMAT_RGBX8888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGR888", mrb_fixnum_value(SDL_PIXELFORMAT_BGR888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGRX8888", mrb_fixnum_value(SDL_PIXELFORMAT_BGRX8888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_ARGB8888", mrb_fixnum_value(SDL_PIXELFORMAT_ARGB8888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_RGBA8888", mrb_fixnum_value(SDL_PIXELFORMAT_RGBA8888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_ABGR8888", mrb_fixnum_value(SDL_PIXELFORMAT_ABGR8888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_BGRA8888", mrb_fixnum_value(SDL_PIXELFORMAT_BGRA8888));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_ARGB2101010", mrb_fixnum_value(SDL_PIXELFORMAT_ARGB2101010));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_YV12", mrb_fixnum_value(SDL_PIXELFORMAT_YV12));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_IYUV", mrb_fixnum_value(SDL_PIXELFORMAT_IYUV));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_YUY2", mrb_fixnum_value(SDL_PIXELFORMAT_YUY2));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_UYVY", mrb_fixnum_value(SDL_PIXELFORMAT_UYVY));
mrb_define_const(mrb, mod_Pixels, "SDL_PIXELFORMAT_YVYU", mrb_fixnum_value(SDL_PIXELFORMAT_YVYU));
mrb_gc_arena_restore(mrb, arena_size);
/* PixelFormats end */
}
void
mruby_sdl2_pixels_final(mrb_state *mrb)
{
}
|
C
|
/*
* Generic map implementation.
*/
#include "hashmap.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define INITIAL_SIZE (256)
#define MAX_CHAIN_LENGTH (8)
/* We need to keep keys and values */
typedef struct _hashmap_element {
char *key;
int in_use;
any_t data;
} hashmap_element;
/* A hashmap has some maximum size and current size,
* as well as the data to hold. */
typedef struct _hashmap_map {
int table_size;
int size;
hashmap_element *data;
} hashmap_map;
/*
* Return an empty hashmap, or NULL on failure.
*/
map_t hashmap_new() {
hashmap_map *m = (hashmap_map *)malloc(sizeof(hashmap_map));
if (!m) goto err;
m->data = (hashmap_element *)calloc(INITIAL_SIZE, sizeof(hashmap_element));
if (!m->data) goto err;
m->table_size = INITIAL_SIZE;
m->size = 0;
return m;
err:
if (m) hashmap_free(m);
return NULL;
}
/* The implementation here was originally done by Gary S. Brown. I have
borrowed the tables directly, and made some minor changes to the
crc32-function (including changing the interface). //ylo */
/* ============================================================= */
/* COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or */
/* code or tables extracted from it, as desired without restriction. */
/* */
/* First, the polynomial itself and its table of feedback terms. The */
/* polynomial is */
/* X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 */
/* */
/* Note that we take it "backwards" and put the highest-order term in */
/* the lowest-order bit. The X^32 term is "implied"; the LSB is the */
/* X^31 term, etc. The X^0 term (usually shown as "+1") results in */
/* the MSB being 1. */
/* */
/* Note that the usual hardware shift register implementation, which */
/* is what we're using (we're merely optimizing it by doing eight-bit */
/* chunks at a time) shifts bits into the lowest-order term. In our */
/* implementation, that means shifting towards the right. Why do we */
/* do it this way? Because the calculated CRC must be transmitted in */
/* order from highest-order term to lowest-order term. UARTs transmit */
/* characters in order from LSB to MSB. By storing the CRC this way, */
/* we hand it to the UART in the order low-byte to high-byte; the UART */
/* sends each low-bit to hight-bit; and the result is transmission bit */
/* by bit from highest- to lowest-order term without requiring any bit */
/* shuffling on our part. Reception works similarly. */
/* */
/* The feedback terms table consists of 256, 32-bit entries. Notes: */
/* */
/* The table can be generated at runtime if desired; code to do so */
/* is shown later. It might not be obvious, but the feedback */
/* terms simply represent the results of eight shift/xor opera- */
/* tions for all combinations of data and CRC register values. */
/* */
/* The values must be right-shifted by eight bits by the "updcrc" */
/* logic; the shift must be unsigned (bring in zeroes). On some */
/* hardware you could probably optimize the shift in assembler by */
/* using byte-swap instructions. */
/* polynomial $edb88320 */
/* */
/* -------------------------------------------------------------------- */
static unsigned long crc32_tab[] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
0x2d02ef8dL};
/* Return a 32-bit CRC of the contents of the buffer. */
unsigned long crc32(const unsigned char *s, unsigned int len) {
unsigned int i;
unsigned long crc32val;
crc32val = 0;
for (i = 0; i < len; i++) {
crc32val = crc32_tab[(crc32val ^ s[i]) & 0xff] ^ (crc32val >> 8);
}
return crc32val;
}
/*
* Hashing function for a string
*/
unsigned int hashmap_hash_int(hashmap_map *m, char *keystring) {
unsigned long key = crc32((unsigned char *)(keystring), strlen(keystring));
/* Robert Jenkins' 32 bit Mix Function */
key += (key << 12);
key ^= (key >> 22);
key += (key << 4);
key ^= (key >> 9);
key += (key << 10);
key ^= (key >> 2);
key += (key << 7);
key ^= (key >> 12);
/* Knuth's Multiplicative Method */
key = (key >> 3) * 2654435761;
return key % m->table_size;
}
/*
* Return the integer of the location in data
* to store the point to the item, or MAP_FULL.
*/
int hashmap_hash(map_t in, char *key) {
int curr;
int i;
/* Cast the hashmap */
hashmap_map *m = (hashmap_map *)in;
/* If full, return immediately */
if (m->size >= (m->table_size / 2)) return MAP_FULL;
/* Find the best index */
curr = hashmap_hash_int(m, key);
/* Linear probing */
for (i = 0; i < MAX_CHAIN_LENGTH; i++) {
if (m->data[curr].in_use == 0) return curr;
if (m->data[curr].in_use == 1 && (strcmp(m->data[curr].key, key) == 0))
return curr;
curr = (curr + 1) % m->table_size;
}
return MAP_FULL;
}
/*
* Doubles the size of the hashmap, and rehashes all the elements
*/
int hashmap_rehash(map_t in) {
int i;
int old_size;
hashmap_element *curr;
/* Setup the new elements */
hashmap_map * m = (hashmap_map *)in;
hashmap_element *temp =
(hashmap_element *)calloc(2 * m->table_size, sizeof(hashmap_element));
if (!temp) return MAP_OMEM;
/* Update the array */
curr = m->data;
m->data = temp;
/* Update the size */
old_size = m->table_size;
m->table_size = 2 * m->table_size;
m->size = 0;
/* Rehash the elements */
for (i = 0; i < old_size; i++) {
int status;
if (curr[i].in_use == 0) continue;
status = hashmap_put(m, curr[i].key, curr[i].data);
if (status != MAP_OK) return status;
}
free(curr);
return MAP_OK;
}
/*
* Add a pointer to the hashmap with some key
*/
int hashmap_put(map_t in, char *key, any_t value) {
int index;
hashmap_map *m;
/* Cast the hashmap */
m = (hashmap_map *)in;
/* Find a place to put our value */
index = hashmap_hash(in, key);
while (index == MAP_FULL) {
if (hashmap_rehash(in) == MAP_OMEM) { return MAP_OMEM; }
index = hashmap_hash(in, key);
}
/* Set the data */
m->data[index].data = value;
m->data[index].key = key;
m->data[index].in_use = 1;
m->size++;
return MAP_OK;
}
/*
* Get your pointer out of the hashmap with a key
*/
int hashmap_get(map_t in, char *key, any_t *arg) {
int curr;
int i;
hashmap_map *m;
/* Cast the hashmap */
m = (hashmap_map *)in;
/* Find data location */
curr = hashmap_hash_int(m, key);
/* Linear probing, if necessary */
for (i = 0; i < MAX_CHAIN_LENGTH; i++) {
int in_use = m->data[curr].in_use;
if (in_use == 1) {
if (strcmp(m->data[curr].key, key) == 0) {
*arg = (m->data[curr].data);
return MAP_OK;
}
}
curr = (curr + 1) % m->table_size;
}
*arg = NULL;
/* Not found */
return MAP_MISSING;
}
/*
* Iterate the function parameter over each element in the hashmap. The
* additional any_t argument is passed to the function as its first
* argument and the hashmap element is the second.
*/
int hashmap_iterate(map_t in, PFany f, any_t item) {
int i;
/* Cast the hashmap */
hashmap_map *m = (hashmap_map *)in;
/* On empty hashmap, return immediately */
if (hashmap_length(m) <= 0) return MAP_MISSING;
/* Linear probing */
for (i = 0; i < m->table_size; i++)
if (m->data[i].in_use != 0) {
any_t data = (any_t)(m->data[i].data);
int status = f(item, data);
if (status != MAP_OK) { return status; }
}
return MAP_OK;
}
/*
* Remove an element with that key from the map
*/
int hashmap_remove(map_t in, char *key) {
int i;
int curr;
hashmap_map *m;
/* Cast the hashmap */
m = (hashmap_map *)in;
/* Find key */
curr = hashmap_hash_int(m, key);
/* Linear probing, if necessary */
for (i = 0; i < MAX_CHAIN_LENGTH; i++) {
int in_use = m->data[curr].in_use;
if (in_use == 1) {
if (strcmp(m->data[curr].key, key) == 0) {
/* Blank out the fields */
m->data[curr].in_use = 0;
m->data[curr].data = NULL;
m->data[curr].key = NULL;
/* Reduce the size */
m->size--;
return MAP_OK;
}
}
curr = (curr + 1) % m->table_size;
}
/* Data not found */
return MAP_MISSING;
}
/* Deallocate the hashmap */
void hashmap_free(map_t in) {
hashmap_map *m = (hashmap_map *)in;
free(m->data);
free(m);
}
/* Return the length of the hashmap */
int hashmap_length(map_t in) {
hashmap_map *m = (hashmap_map *)in;
if (m != NULL)
return m->size;
else
return 0;
}
|
C
|
#include<stdio.h>
int memoizedcutrod(int price[],int n,int r[]);
int max(int a,int b);
int main(){
int n;
scanf("%d\n",&n);
/*int arr[n];
for(int i=0;i<n;i++){
scanf("%d ",&arr[i]);
}*/
int price[n];
for(int i=0;i<n;i++){
scanf("%d ",&price[i]);
}
int r[n+1];
int s[n+1];
int q;
for(int i=0;i<n+1;i++){
r[i] = 0;
}
for(int j = 1; j < n+1 ; j++){
q = -100000;
for(int i = 1; i < j+1; i++){
if(q < price[i-1]+r[j-i]){
q = price[i-1] + r[j-i];
s[j-1] = i;
}
}
r[j] = q;
}
for(int i=0;i<n+1;i++){
printf("%d ", r[i]);
}
printf("\n");
for(int i=0;i<n+1;i++){
printf("%d ", s[i]);
}
return 0;
}
int memoizedcutrod(int price[],int n,int r[]){
int q;
if (r[n] >= 0) return r[n];
if (n == 0) q=0;
else{
q = -100000;
for(int i = 1;i <= n;i++){
q = max(q,price[i-1]+memoizedcutrod(price,n-i,r));
}
}
r[n] = q;
return q;
}
int max(int a,int b){
if(a>b) return a;
else return b;
}
|
C
|
#include "push_swap.h"
#include "ft_dlist.h"
#include <stdio.h>
static t_clist_it *ft_ps_get_info_and_min(t_clist *l)
{
t_clist_it *min;
ssize_t max;
t_clist_it *current;
current = l->current;
min = current;
max = ((ssize_t)current->value);
((t_lstinfo *)l->data)->min = max;
((t_lstinfo *)l->data)->max = max;
while (current)
{
if (((ssize_t)min->value) > ((ssize_t)current->value))
{
((t_lstinfo *)l->data)->min = ((ssize_t)current->value);
min = current;
}
if (max < ((ssize_t)current->value))
{
max = ((ssize_t)current->value);
((t_lstinfo *)l->data)->max = max;
}
current = current->next;
if (current == l->current)
break ;
}
return (min);
}
t_bool ft_ps_is_sort(t_clist *l)
{
t_clist_it *start;
t_clist_it *current;
if (l->size == 0)
return (true);
start = ft_ps_get_info_and_min(l);
current = start;
while (current && current->next != start)
{
if ((ssize_t)current->next->value < ((ssize_t)current->value))
return (false);
current = current->next;
}
return (true);
}
|
C
|
/*
* Find the maximum total from top to bottom in triangle.txt, a 15K text file
* containing a triangle with one-hundred rows.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#define NUM_ROWS 100
int max(int a, int b)
{
return (a > b) ? a : b;
}
int triangle_size(int rows)
{
return rows * (rows + 1) / 2;
}
int t_index(int row, int col)
{
assert(row >= 0 && col >= 0 && col <= row);
return triangle_size(row) + col;
}
int left_child(int row, int col)
{
return t_index(row + 1, col);
}
int right_child(int row, int col)
{
return t_index(row + 1, col + 1);
}
/*
* Computes the max path sum in the triangle
* Uses a dynamic programming approach to systematically reduce the size
* of the triangle.
*
* In short, I iterate through every column in the second to last row,
* then add the largest child of each element to itself.
* Here's an illustration of the process for a simple triangle:
*
* 1 1 6
* 1 2 -> 3 5 ->
* 1 2 3
*/
int max_path(int *triangle, int num_rows)
{
int row, col;
while (num_rows > 0) {
row = num_rows - 1;
for (col = 0; col <= row; ++col)
triangle[t_index(row, col)] +=
max(triangle[left_child(row, col)],
triangle[right_child(row, col)]);
--num_rows;
}
return triangle[0];
}
int main()
{
int *triangle = malloc(sizeof(int) * triangle_size(NUM_ROWS));
FILE *fptr = fopen("data/p067_triangle.txt", "r");
int elem;
int num_elems = 0;
/* Put array of numbers into memory */
while (EOF != fscanf(fptr, "%d", &elem))
triangle[num_elems++] = elem;
printf("%d\n", max_path(triangle, NUM_ROWS - 1));
free(triangle);
fclose(fptr);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include "driver/gpio.h"
#include "esp_system.h"
#include "esp_log.h"
#include "fr_dig_out.h"
static const char *TAG = "DIG_OUT";
#define NUM_DIGOUTS 17
static dig_out_t dig_outs[NUM_DIGOUTS];
static dig_out_t *digout_get_status(gpio_num_t gpio_num)
{
if (gpio_num >= NUM_DIGOUTS) {
ESP_LOGE(TAG, "GPIO number out of range");
}
return &dig_outs[gpio_num];
}
void digout_init_pin(gpio_num_t gpio_num, bool level)
{
digout_set(gpio_num, level);
gpio_set_direction(gpio_num, GPIO_MODE_OUTPUT);
ESP_LOGI(TAG, "GPIO %d set to output and initialised to %d", gpio_num, level);
}
void digout_set(gpio_num_t gpio_num, bool level)
{
dig_out_t *d = digout_get_status(gpio_num);
d->return_level = level;
d->level = level;
gpio_set_level(gpio_num, level);
ESP_LOGI(TAG, "Digital output %d set to %d", gpio_num, level);
}
bool digout_get(gpio_num_t gpio_num)
{
dig_out_t *d = digout_get_status(gpio_num);
return d->level;
}
static void vTimerCallback(TimerHandle_t xTimer)
{
dig_out_t *d;
int i;
for (i = 0; i < NUM_DIGOUTS; i++) {
d = &dig_outs[i];
if (d->expiry > 0) {
d->expiry--;
if (d->expiry == 0) {
digout_set(i, d->return_level);
ESP_LOGI(TAG, "Digital output %d timer expired. Returning to to %d", i, d->return_level);
}
}
}
}
void digout_set_halfsecs(gpio_num_t gpio_num, bool level, int halfsecs)
{
dig_out_t *d = digout_get_status(gpio_num);
d->expiry = halfsecs;
d->level = level;
gpio_set_level(gpio_num, level);
ESP_LOGI(TAG, "Digital output %d set to %d for %d halfsecs", gpio_num, level, halfsecs);
}
void digout_init(void)
{
TimerHandle_t xTimer;
xTimer = xTimerCreate("DigOutTimer", pdMS_TO_TICKS(500), pdTRUE, NULL, vTimerCallback);
if (xTimer) {
xTimerStart(xTimer, 0);
}
ESP_LOGI(TAG, "Digital output module started");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/un.h>
#include <sys/poll.h> // use poll event
#include "define.h"
#include "cmd_handler.h"
int client_socket;
unsigned char tx_msg[MAX_BUFFER];
unsigned char rx_msg[MAX_BUFFER];
void handleCmdPget(int argc, char* argv[]);
int main(int argc, char* argv[])
{
//int client_socket;
struct sockaddr_un server_addr;
client_socket = socket( PF_FILE, SOCK_STREAM, 0);
if( -1 == client_socket) {
printf( "socket n");
exit( 1);
}
memset( &server_addr, 0, sizeof( server_addr));
server_addr.sun_family = AF_UNIX;
strcpy( server_addr.sun_path, FILE_SERVER);
if( -1 == connect( client_socket, (struct sockaddr*)&server_addr, sizeof( server_addr) ) ) {
printf( " n");
exit( 1);
}
if(strncmp(argv[0], "pinfo", 5) == 0) {
handleCmdPget(argc, argv);
}
else if(strncmp(argv[0], "./pinfo", 7) == 0) {
handleCmdPget(argc, argv);
}
else {
printf("Unknown Command. Use following Syntax(%d)\n", argc);
printf("%s\n", argv[0]);
printf("./pinfo [pcm] [pno] [number]\n");
}
close( client_socket);
return SUCCESS;
}
/*****************************************************/
void handleCmdPget(int argc, char* argv[])
/*****************************************************/
{
//Variables
int i;
short pcm;
short pno;
short number;
int recv_index;
int recv_length;
int retry_count;
int count;
struct timespec ts;
//point_info point;
//Initialize
i = 0;
pcm = 0;
pno = 0;
number = 0;
recv_index = 0;
recv_length = 0;
retry_count = 0;
count = 0;
ts.tv_sec = 0;
ts.tv_nsec = 100000000; //0.1sec
//memset(&point, 0, sizeof(point));
//
memset(tx_msg, 0, sizeof(tx_msg));
memset(rx_msg, 0, sizeof(rx_msg));
if(argc < 3) {
printf("Incorrect Arguments\n");
printf("./pinfo [pcm] [pno] [number]\n");
return;
}
pcm = atoi(argv[1]);
pno = atoi(argv[2]);
if (argc == 4)
number = atoi(argv[3]);
else
number = 0;
//Check Validation of Arguments
if(pcm < 0 || pcm >= MAX_NET32_NUMBER) {
printf("Invalid PCM [%d] in handleCmdPget()\n", pcm);
return;
}
if(pno < 0 || pno >= MAX_POINT_NUMBER) {
printf("Invalid PNO [%d] in handleCmdPget()\n", pno);
return;
}
if(number < 0 || (pno + number) > MAX_POINT_NUMBER) {
printf("Invalid Number [%d] in handleCmdPget()\n", number);
return;
}
//Make Send Message
tx_msg[0] = COMMAND_PGET_MULTI_POINT;
memcpy(&tx_msg[1], &pcm, sizeof(pcm));
memcpy(&tx_msg[3], &pno, sizeof(pno));
memcpy(&tx_msg[5], &number, sizeof(number));
// Send Message
if( write( client_socket, tx_msg, 8 ) <= 0) {
printf("[ERROR] Send in %s()\n", __FUNCTION__);
return;
}
/*
if(send(client_socket, tx_msg, 8, 0) <= 0) {
printf("[ERROR] Send in handleCmdPget()\n");
return;
}
*/
return;
}
#if 0
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
//
#include "define.h"
#include "queue.h"
#include "point_manager.h"
#include "cmd_handler.h"
int client_socket;
unsigned char tx_msg[MAX_BUFFER];
unsigned char rx_msg[MAX_BUFFER];
void handleCmdPget(int argc, char* argv[]);
#if 0
/*****************************************************/
int
main(int argc, char* argv[])
/*****************************************************/
{
//Variables
struct sockaddr_in server_addr_in;
struct timeval tv;
char server_ip[15];
int server_port;
if(argc == 1)
{
printf("No argument. Use following Syntax(%d)\n", argc);
printf("./pinfo [pcm] [pno] [number]\n");
return FAIL;
}
//Initialize
client_socket = -1;
memset(&server_addr_in, 0, sizeof(server_addr_in));
tv.tv_sec = 0;
tv.tv_usec = 100000; //0.1sec
strcpy(server_ip, "127.0.0.1");
server_port = COMMAND_SERVER_PORT;
client_socket = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
server_addr_in.sin_family = AF_INET;
server_addr_in.sin_addr.s_addr = inet_addr(server_ip);
server_addr_in.sin_port = htons(server_port);
if(connect(client_socket, (struct sockaddr *) &server_addr_in,
sizeof(server_addr_in)) >= 0)
{
if(strncmp(argv[0], "pinfo", 5) == 0)
{
handleCmdPget(argc, argv);
}
else if(strncmp(argv[0], "./pinfo", 7) == 0)
{
handleCmdPget(argc, argv);
}
else
{
printf("Unknown Command. Use following Syntax(%d)\n", argc);
printf("%s\n", argv[0]);
printf("./pinfo [pcm] [pno] [number]\n");
}
return SUCCESS;
}
else
{
printf("Connecting to Interface Server Failed\n");
close(client_socket);
return FAIL;
}
}
/*****************************************************/
void
handleCmdPget(int argc, char* argv[])
/*****************************************************/
{
//Variables
int i;
short pcm;
short pno;
int number;
int recv_index;
int recv_length;
int retry_count;
int count;
struct timespec ts;
point_info point;
//Initialize
i = 0;
pcm = 0;
pno = 0;
number = 0;
recv_index = 0;
recv_length = 0;
retry_count = 0;
count = 0;
ts.tv_sec = 0;
ts.tv_nsec = 100000000; //0.1sec
memset(&point, 0, sizeof(point));
//
memset(tx_msg, 0, sizeof(tx_msg));
memset(rx_msg, 0, sizeof(rx_msg));
if(argc < 3)
{
printf("Incorrect Arguments\n");
printf("./pinfo [pcm] [pno] [number]\n");
return;
}
pcm = atoi(argv[1]);
pno = atoi(argv[2]);
if (argc == 4)
number = atoi(argv[3]);
else
number = 0;
//Check Validation of Arguments
if(pcm < 0 || pcm >= MAX_NET32_NUMBER)
{
printf("Invalid PCM [%d] in handleCmdPget()\n", pcm);
return;
}
if(pno < 0 || pno >= MAX_POINT_NUMBER)
{
printf("Invalid PNO [%d] in handleCmdPget()\n", pno);
return;
}
if(number < 0 || (pno + number) > MAX_POINT_NUMBER)
{
printf("Invalid Number [%d] in handleCmdPget()\n", number);
return;
}
//Make Send Message
tx_msg[0] = COMMAND_PGET_MULTI_POINT;
memcpy(&tx_msg[1], &pcm, sizeof(pcm));
memcpy(&tx_msg[3], &pno, sizeof(pno));
memcpy(&tx_msg[5], &number, sizeof(number));
// Send Message
if(send(client_socket, tx_msg, 7, 0) <= 0)
{
printf("[ERROR] Send() in handleCmdPget()\n");
return;
}
// close socket
nanosleep(&ts, NULL);
close(client_socket);
return;
}
#endif
#endif
|
C
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int validateKey(string key);
string makeCiphertext(string plainText, string key);
int main(int argc, string argv[])
{
// Check if user input too less or too many arguments in command line
if (argc < 2 || argc > 2)
{
printf("Usage: ./substitution key \n");
return 1;
}
string key = argv[1];
// Store a isValid return for key
int isValid = validateKey(key);
// If key pass in all tests then get plaintext and encipher the text
if (isValid == 0)
{
string plainText = get_string("plaintext:");
string enchiper = makeCiphertext(plainText, key);
printf("ciphertext: %s\n", enchiper);
}
else
{
return 1;
}
}
string makeCiphertext(string plainText, string key)
{
// Get length to use in compare and instance array
long int lenght = strlen(plainText);
// +1 is for \0 value in the end, this tell to memory it is a string
char cipher[lenght + 1];
// Append \0 value in last position of array
cipher[-1] = '\0';
for (int i = 0; i <= lenght; i++)
{
for (int j = 65; j <= 90; j++)
{
// If is a letter in current position based on ASCII value converting to uppercase, because plaintext can have numbers, spaces and sinals
if (toupper(plainText[i]) >= 65 && toupper(plainText[i]) <= 90)
{
// Check if current letter in plaintext is equal the letter in alphabet I have your position
if (toupper(plainText[i]) == j)
{
//If is upper store letter in uppercase
if (isupper(plainText[i]))
{
// The position of letter is j - 65 (start value), then I refer the key value to cipher array
cipher[i] = toupper(key[j - 65]);
}
// Else store letter in lower case
else
{
cipher[i] = tolower(key[j - 65]);
}
}
}
// If is number or anything not letter just store the value
else
{
cipher[i] = plainText[i];
}
}
}
string result = cipher;
return result;
}
int validateKey(string key)
{
//Check if has 26 characters
long int lenght = strlen(key);
if (lenght < 26 || lenght > 26)
{
printf("Key must contain 26 characters. \n");
return 1;
}
else
{
//Check if all characters are letters
int count = 0;
while (count < strlen(key))
{
//Check blank space/tab key
if (isblank(key[count]))
{
printf("Usage: ./substitution key \n");
return 1;
}
if (!isalpha(key[count]))
{
printf("Key accept only letters \n");
return 1;
}
count++;
}
// Check if any character is repeated
for (int i = 0; i < lenght; i++)
{
for (int j = i + 1; j < lenght; j++)
{
if (toupper(key[i]) == toupper(key[j]))
{
printf("Repeated value in key \n");
return 1;
}
}
}
}
return 0;
}
|
C
|
#include <stdint.h>
#include <stdbool.h>
#include <util/delay.h>
#include "lcd/lcd.h"
#include "input/input.h"
#include "jui.h"
#include "gridview.h"
#include "util.h"
static void draw_select_line(gridview_t* view, uint16_t color);
static uint8_t find_component(gridview_t* view, uint8_t x, uint8_t y);
gridview_t gridview_create(uint8_t xCount, uint8_t yCount, uint8_t count, gridview_component_t* components) {
return (gridview_t){xCount, yCount, count, components, count};
}
void gridview_draw(gridview_t* view) {
clear_screen();
int i;
uint16_t unitWidth = display.width / view->xCount;
uint16_t unitHeight = display.height / view->yCount;
for (i = 0; i < view->count; i++) {
rectangle_t rect = {
unitWidth * view->components[i].x,
unitWidth * view->components[i].x + unitWidth * view->components[i].width,
unitHeight * view->components[i].y,
unitHeight * view->components[i].y + unitHeight * view->components[i].height
};
uint16_t old_bg = display.background;
if (view->components[i].component->style.flags & STYLE_BACKGROUND)
display.background = view->components[i].component->style.background_color;
style_draw(rect, view->components[i].component->style);
view->components[i].component->draw_func(view->components[i].component, rect);
display.background = old_bg;
}
}
gridview_component_t gridview_place(uint8_t x, uint8_t y, uint8_t width, uint8_t height, component_t* component) {
return (gridview_component_t){x, y, width, height, component};
}
void gridview_select(gridview_t* view, uint8_t index) {
if (view->selected != index) {
draw_select_line(view, display.background);
view->selected = index;
draw_select_line(view, SELECT_LINE_COLOUR);
}
}
void gridview_scroll(gridview_t* view, int8_t delta) {
gridview_select(view, mod(view->selected + delta, view->count));
}
void gridview_left(gridview_t* view) {
uint8_t s = find_component(view, view->components[view->selected].x - 1, view->components[view->selected].y);
gridview_select(view, s);
}
void gridview_right(gridview_t* view) {
uint8_t s = find_component(view, view->components[view->selected].x + view->components[view->selected].width, view->components[view->selected].y);
gridview_select(view, s);
}
void gridview_up(gridview_t* view) {
uint8_t s = find_component(view, view->components[view->selected].x, view->components[view->selected].y - 1);
gridview_select(view, s);
}
void gridview_down(gridview_t* view) {
uint8_t s = find_component(view, view->components[view->selected].x, view->components[view->selected].y + view->components[view->selected].height);
gridview_select(view, s);
}
void gridview_run(gridview_t* view) {
bool is_up_pressed = UP_PRESSED, is_down_pressed = DOWN_PRESSED, is_left_pressed = LEFT_PRESSED,
is_right_pressed = RIGHT_PRESSED, is_center_pressed = CENTER_PRESSED;
int8_t delta;
while (1) {
delta = get_scroll_delta();
if (delta != 0)
gridview_scroll(view, delta);
if (UP_PRESSED && !is_up_pressed)
gridview_up(view);
else if (DOWN_PRESSED && !is_down_pressed)
gridview_down(view);
else if (LEFT_PRESSED && !is_left_pressed)
gridview_left(view);
else if (RIGHT_PRESSED && !is_right_pressed)
gridview_right(view);
else if (CENTER_PRESSED && !is_center_pressed)
{}
is_up_pressed = UP_PRESSED;
is_down_pressed = DOWN_PRESSED;
is_left_pressed = LEFT_PRESSED;
is_right_pressed = RIGHT_PRESSED;
is_center_pressed = CENTER_PRESSED;
_delay_ms (10); //Improve responsiveness by slowing down the loop
}
}
static void draw_select_line(gridview_t* view, uint16_t color) {
gridview_component_t* selected = view->components + view->selected;
uint16_t unitWidth = display.width / view->xCount;
uint16_t unitHeight = display.height / view->yCount;
rectangle_t rect =
{
selected->x * unitWidth + 2,
selected->x * unitWidth - 2 + selected->width * unitWidth,
(selected->y + selected->height) * unitHeight - SELECT_LINE_OFFSET - SELECT_LINE_THICKNESS,
(selected->y + selected->height) * unitHeight - SELECT_LINE_OFFSET
};
fill_rectangle(rect, color);
}
static uint8_t find_component(gridview_t* view, uint8_t x, uint8_t y) {
uint8_t i;
/* Normalise */
x = mod(x, view->xCount);
y = mod(y, view->yCount);
/* Search */
for (i = 0; i < view->count; i++) {
gridview_component_t* component = (view->components + i);
if (component->x <= x && x < component->x + component->width
&& component->y <= y && y < component->y + component->height)
return i;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <stdint.h>
#include <ftw.h>
#define MAX_FTW_DEPTH 16
static int num_dirs, num_files;
static int callback(const char *fpath, const struct stat *sb, int typeflag){
// if we found a file
if (typeflag == FTW_F){
num_files++;
// otherwise, we've found a directory
} else if (typeflag == FTW_D) {
num_dirs++;
}
return 0;
}
int main(int argc, char** argv) {
if(argc != 2){
printf("Usage: %s <path>\n", argv[0]);
printf(" where <path is the file or root of the tree you want to summarize");
return 1;
}
num_dirs = 0;
num_files = 0;
ftw(argv[1], callback, MAX_FTW_DEPTH);
printf("There were %d directories.\n", num_dirs);
printf("There were %d regular files.\n", num_files);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "bitree.h"
int main()
{
int num;
init_bitree(&bt);
system("clear"); //for linux
// system("cls"); //for windows
printf("\n");
printf("*****************************************************************\n");
printf("* This progrom is an operation for bitree. *\n");
printf("* Programed by wuwennongdao and request for comments. *\n");
printf("* Email:[email protected] *\n");
printf("* Blog: blog.csdn.net/algorithn_only *\n");
printf("*****************************************************************\n\n");
for (;;) {
printf("\n[bitree]# ");
scanf("%d", &num);
switch (num) {
case 1:
printf("Input elemtype to create bitree with preorder:\n"
"(for exemple: 1 2 3 0 0 4 5 0 6 0 0 7 0 0 0) > ");
create_bitree(&bt);
break;
case 2:
printf("no recursive traverse:\n");
printf("Preorder:\t"); preorder_traverse(bt, output_data); printf("\n");
printf("Inorder:\t"); inorder_traverse(bt, output_data); printf("\n");
printf("Postorder:\t"); postorder_traverse(bt, output_data); printf("\n");
printf("recursive traverse:\n");
printf("preorder:\t"); preorder(bt, output_data); printf("\n");
printf("inorder:\t"); inorder(bt, output_data); printf("\n");
printf("postorder:\t"); postorder(bt, output_data); printf("\n");
printf("level order traverse:"); levelorder_traverse(bt, output_data); printf("\n");
break;
case 3:
printf("The number of the leave is : %d\n", get_num_of_leave(bt));
break;
case 4:
printf("The depth of the tree is : %d\n", get_tree_depth(bt));
break;
case 5:
free_bitree(&bt);
break;
case 0:
printf("Please select one operation blow:\n");
printf("--------------------------------------------------------------\n");
printf(" 1. Create bitree.\n");
printf(" 2. traverse bitree.\n");
printf(" 3. Get the number of the leave.\n");
printf(" 4. Get the Length of the bitree.\n");
printf(" 5. Free the bitree.\n");
printf(" 0. Display the options again.\n");
printf(" -1. Exit.\n");
printf("---------------------------------------------------------------\n");
break;
case -1:
printf("\n------------Thank you for using! bye bye-----------\n\n");
return 0;
break;
default:
printf("Error options!\n");
break;
}
}
return 0;
}
|
C
|
/**
* decide-range.c
* Project Euler Prbl 127
* Created by Zhiming Wang on 02/21/2014.
* --------------------------------------
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "read-rad.h"
int main(int argc, const char *argv[]) {
read_rad();
printf("enter the threshold value c/rad(c):\n");
long threshold;
scanf("%ld", &threshold);
long counter = 0;
for (int c = 1; c <= N; c++) {
if (_rad[c] * threshold < c) {
counter++;
}
}
printf("number of c's that passed the threshold: %ld\n", counter);
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int test,num,i,count,i2;
scanf("%d",&test);
while(test--)
{
scanf("%d",&num);
count=1;
for(i=2;i<=sqrt(num);i++)
{
if(num%i==0)
{
i2=num/i;
if(i2==i)
count=count+i;
else
count=count+i+i2;
}
}
printf("%d\n",count);
}
return 0;
}
|
C
|
/*
CH-230-A
a6p1.c
Erlisa Kulla
[email protected]
*/
#include <stdio.h>
//Defining macro to swap two numbers
#define SWAP1(x, y, int) int t; t = x; x = y; y = t;
#define SWAP2(x, y, double) double a; a = x; x = y; y = a;
int main(){
int num1, num2;
double num3, num4;
//Input two numbers from users
scanf("%d%d", &num1, &num2);
scanf("%lf%lf", &num3, &num4);
//calling the SWAP macro
SWAP1(num1, num2, int);
SWAP2(num3, num4, double);
printf("After swapping:\n%d\n%d\n%lf\n%lf\n", num1, num2, num3, num4);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define PORT 23517 //Static TCP port number of server 3
//Making use of Trimewhitespace to cut out garbage values or white spaces. Referenced from Stackoverflow
char *trimwhitespace(char *str)
{
char *end;
// Used to Trim leading space
while(isspace(*str)) str++;
if(*str == 0)
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) end--;
// Write new null terminator
*(end+1) = 0;
return str;
}
int main()
{
//variables
struct hostent *hp;
char *host = "nunki.usc.edu";
int n2=0;
int rval;
char line[128];
char key_val [16][100];
int y=0;
char f_n[]="NULL";
char *k;
char *v;
char *search=" ";
int i=0;
int sock_id;
int mysock;
struct sockaddr_in s3, s2;
int length,len;
char buff[512]="NULL";
char * buff_val;
//Function to open the file and read its contents
//fopen referenced from linux man page and strtok from stackoverflow
FILE *file = fopen ("server3.txt", "r");
if(file!=NULL)
{
while(fgets (line,128,file) !=NULL)
{
k=strtok(line,search); //This separates the key in the given text file from its corresponding value
strcpy(key_val[i], k);
i=i+1;
v=strtok(NULL,search); //This provides us the value from the text file
strcpy(key_val[i], v);
i=i+1;
}
fclose(file);
}
n2=i;
//Making use of gethostbyname. Referenced from Rutgers
if((hp=gethostbyname(host)) == NULL)
{
perror("gethostbyname failed()");
exit(1);
}
//create socket
sock_id=socket(AF_INET, SOCK_STREAM, 0);
if(sock_id==-1)
{
perror("Error Creating socket");
exit(1);
}
s3.sin_family= AF_INET;
memcpy(&(s3.sin_addr), hp->h_addr, hp->h_length);
memset(&(s3.sin_zero), '\0', 8);
s3.sin_port= htons(PORT);
len=sizeof(struct sockaddr_in);
//binding
if( bind(sock_id, (struct sockaddr *)&s3, sizeof(s3))==-1)
{
perror("Error binding socket");
exit(1);
}
printf("The Server 3 has TCP port number %d and IP address %s\n",(int) htons(s3.sin_port),inet_ntoa(s3.sin_addr));
//listening to possible incoming connections.
if((listen(sock_id,20))==-1)
{
perror("error in listening");
}
while(1)
{
if((mysock=accept(sock_id, (struct sockaddr *)&s2, (socklen_t*)&len))==-1) //get the IP address and port number of server 2
{
perror("Error accepting");
exit(1);
}
else
{
memset(buff,0,sizeof(buff));
n2:if((rval=recv(mysock, buff, sizeof(buff),0))==-1) //receive the key from server 2
{
perror("Error reading");
}
else
{
printf("The Server 3 has received a request with key %s from the Server 2 with port number %d and IP address %s\n",buff,(int) ntohs(s2.sin_port),inet_ntoa(s2.sin_addr));
}
}
buff_val = trimwhitespace(buff);
for(i=0;i<n2;i=i+2)
{
if(strcmp(buff_val,key_val[i])==0)
{
y=i+1;
break;
}
}
if(send(mysock, key_val[y], strlen(key_val[y]), 0)==-1) //Send the corresponding value back to server 2
{
perror("error sending");
}
printf("Server 3 sends the reply %s to the Server 2 with port number %d and IP address %s\n\n",key_val[y],(int) ntohs(s2.sin_port),inet_ntoa(s2.sin_addr));
goto n2;
}
close(sock_id);
return 0;
}
|
C
|
/**************************************************
*- Author : aゞ小波
*- CreateTime : 2019-09-23 00:09
*- Email : [email protected]
*- Filename : main.c
*- Description :
***************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "bintree.h"
int main(int argc, char ** argv){
int array[10] = {8,3,10,13,14,1,6,7,4,5};
int arr_len = 10;
binTree T = NULL;
T = initBinTree(array, arr_len);
travIn(T);
return 0;
}
|
C
|
///Structure inside Structure or
///Nested Structure
#include<stdio.h>
struct nametype
{
char first[20];
char last[20];
};
struct student
{
int id;
struct nametype name;
};
int main()
{
struct student st;
printf("Enter the Student ID: ");
scanf("%d",&st.id);
printf("Enter the Student first Name: ");
scanf("%s",st.name.first);
printf("Enter the Student last Name: ");
scanf("%s",st.name.last);
printf("ID: %d\n",st.id);
printf("Name: %s %s\n",st.name.first,st.name.last);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
unsigned long long int num,count=0,size=0;
scanf("%lld",&num);
size = sqrt(num);
int arr[size],k=0;
for(int i=2;i<=size;i++){
for(int j=1;j<=i;j++){
if(i%j==0){
count++;
if(count>2){
break;
}
}
}
if(count<=2){
printf("%d ",i);
arr[k]=i;
k++;
}
count =0;
}
count=0;
for(int i=arr[k-1]+1;i<=num;i++){
for(int j=0;j<k;j++){
if(i%arr[j]==0){
count = 1;
break;
}
}
if(count == 0){
printf("%d ",i);
}
count=0;
}
return 0;
}
// normal method
// #include <stdio.h>
// int main()
// {
// unsigned long long int num,count=0,size=0;
// scanf("%lld",&num);
// for(int i=2;i<=num;i++){
// for(int j=1;j<=i;j++){
// if(i%j==0){
// count++;
// if(count>2){
// break;
// }
// }
// }
// if(count<=2){
// printf("%d ",i);
// }
// count =0;
// }
// return 0;
// }
|
C
|
#ifndef SGREP_H
#define SGREP_H
#include <stdio.h>
typedef char* string;
typedef unsigned char byte;
/*
Option flags to be stored in a unsigned char / byte
Example:
options = 0000 0101
||||
|||+- OPT_CASE_SENSITIVE is set
||+-- OPT_COUNT is not set
|+--- OPT_LINE_NUMBER is set
+---- OPT_HELP is not set
Usage:
Adding:
options = options | OPT_CASE_SENSITIVE; --options now contain OPT_CASE_SENSITIVE
Checking:
if (options & OPT_CASE_SENSITIVE) {do case sensitive stuff}
*/
typedef enum option_flags {
OPT_CASE_SENSITIVE = 0x01,
OPT_COUNT = 0x02,
OPT_LINE_NUMBER = 0x04,
OPT_HELP = 0x08
} option_flags;
/*sgrep runnable state*/
typedef struct sgrep_state {
byte options; /*User supplied flag option byte*/
string search_string;
FILE *data_stream; /*defaults to stdin but could be a file from the filesystem*/
} sgrep_state;
#endif
|
C
|
/*************************************************************************
> File Name: signalblock.c
> Author:
> Mail:
> Created Time: 2017年09月02日 星期六 19时27分59秒
************************************************************************/
#include<stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
void handler(int sig)
{
if (sig == SIGINT)
{
printf("recv a sig=%d\n", sig);
printf("\n\n\n");
//fflush(stdout);
}
else if (sig == SIGQUIT)
{
sigset_t uset;
sigemptyset(&uset);
sigaddset(&uset, SIGINT);
//ctr + \ 用来解除 SIGINT 信号
//解除阻塞
sigprocmask(SIG_UNBLOCK, &uset, NULL);
printf("被阻塞的信号到了@!");
signal(SIGINT, SIG_DFL) ;
}
}
void printfsigpending(sigset_t *set)
{
int i = 0;
for(int i = 1; i < NSIG; i++)
{
if(sigismember(set, i)) //看i是否在集合中
{
printf("1");
}
else
{
printf("0");
}
}
putchar(10);
}
int main()
{
sigset_t pset; //未决状态字的集合 pending
sigset_t bset; //阻塞状态字的集合 block
sigemptyset(&bset); //清空信号集(64位)
sigaddset(&bset, SIGINT); //将sigint信号放入信号集,
//即将第二位置为1
if(signal(SIGINT, handler) == SIG_ERR)
{
perror("sigint");
}
if(signal(SIGQUIT, handler) == SIG_ERR)
{
perror("sigquit");
}
//信号被阻塞 即使按了CTRL+C 也没用
sigprocmask(SIG_BLOCK, &bset, NULL);
while(1)
{
//获取未决 字的状态
sigpending(&pset);
printfsigpending(&pset);
sleep(1);
}
return 0;
}
|
C
|
/*
* my_ssh_api.c
*
* Created on: 15 Jan 2018
* Author: lqy
*/
#include "my_ssh_api.h"
ssize_t ssh_read(struct ssh* ssh, u_char* type, const u_char** datap,
size_t* len) {
int ret = ssh_packet_next(ssh, type);
/*printf("ssh_read: ssh_packet_next returned %d, type: %u\n", ret, *type);*/
if (ret < 0) {
fprintf(stderr, "ssh_read(): ssh_packet_next() failed\n");
return -1;
} else {
if (*type != 0) {
//packet available
*datap = ssh_packet_payload(ssh, len);
return *len;
} else {
//packet unavailable
*datap = NULL;
return 0;
}
}
}
ssize_t ssh_write(struct ssh* ssh, u_char type, const u_char* data, size_t len) {
int ret = ssh_packet_put(ssh, type, data, len);
/*printf("ssh_write: ssh_packet_put returned %d\n", ret);*/
if (ret < 0) {
fprintf(stderr, "ssh_write(): ssh_packet_put() failed\n");
return -1;
}
return len;
}
ssize_t ssh_fill(struct ssh* ssh, int in_fd) {
char buffer[1024 * 16];
//read from in_fd and fill the SSH input byte stream
ssize_t sret = read(in_fd, buffer, sizeof(buffer));
int errn = errno;
/*putchar('\n');
putchar('\n');
printf("ssh_fill: read() returned %zd\n", sret);
putchar('\n');
putchar('\n');*/
if (sret < 0) {
fprintf(stderr, "ssh_fill(): read() failed\n");
if (errn > 0) {
return -errn;
} else {
return -1;
}
} else if (sret == 0) {
//EOF
/*printf("ssh_fill: read() EOF\n");*/
return -1;
} else {
int ret = ssh_input_append(ssh, buffer, sret);
/*printf("ssh_fill: ssh_input_append(%zd) returned %d\n", sret, ret);*/
if (ret < 0) {
fprintf(stderr, "ssh_fill(): ssh_input_append() failed\n");
return -1;
}
}
return sret;
}
ssize_t ssh_flush(struct ssh* ssh, int out_fd) {
//send SSH output byte stream
const u_char* b = NULL;
size_t l = 0;
b = ssh_output_ptr(ssh, &l);
//printf("ssh_flush: ssh_output_ptr() returned %p, len: %zu\n", b, l);
size_t bytes_sent = 0;
while (bytes_sent < l) {
ssize_t wret = write(out_fd, b + bytes_sent, l - bytes_sent);
int errn = errno;
//printf("ssh_flush: write returned %zd\n", wret);
if (wret < 0) {
fprintf(stderr, "ssh_flush(): write() failed, errno: %d\n", errn);
if (errn > 0) {
return -errn;
} else {
return -1;
}
} else {
int ret = ssh_output_consume(ssh, wret);
//printf("ssh_flush: ssh_output_consume returned %d\n", ret);
if (ret < 0) {
fprintf(stderr, "ssh_flush(): ssh_output_consume() failed\n");
return -1;
}
}
bytes_sent += wret;
}
return bytes_sent;
}
|
C
|
/*22-III-2011
Ejercicio 11.
Fig 1
Apartado a)
*Asignar a Personas un trabajo
test de fracaso: No se puede asignar a una persona un trabajo ya asignado.
generación de descendientes: una persona puede realizar cualquier trabajo
libre[] si el trabajo ha sido asignado (true/false)
*/
tsolucion
coste
persona[N]
void AsignaA( int k, int libre[] , int t[][], tsolucion *sol, tsolucion *solopt){
if (k==n){
if(sol->coste < solopt->coste)
*solopt=*sol;
}
else{
for(i=0; i<n; i++)
if(libre[i]){
libre[i]=FALSE;
sol->Persona[k]=i;
sol->coste+=t[i][k];
AsignaA(k+1, -----);
//Si no está libre, deshacemos para la siguiente iteración
libre[i]=TRUE;
sol->coste=tik;
}
}
//inicializacion
for(i=0; i<N; i++)
libre[i]=TRUE;
sol.coste=0;
soloptima.coste= -INFINITO;
// Lamada inicial
AsignaA(0, libre, t, $sol, &solopt);
}
//Asignar trabajos a personas
void AsignaT(int k, int libre[], int t[][], tsol *sol, tsol *solopt){
if(sol->coste < solopt->coste) //comprobar si la solución tiene futuro
if(k==n)
*solopt=*sol;
else
for(p=0; p<n; p++)
if(libre[p]){
libre[p]=FALSE;
sol-> trabajo[k]=p;
sol->coste+=tkp;
AsignaT(k+1,----);
//Deshacer
libre[p]=TRUE;
sol->coste-=tkp;
}
}
/*Apartado b)
Etapa k = asignar trabajo k a una persona
fin cuando se asignan todos los trabajos
no hay restricciones para asignar trabajos a personas.
Mismo código sin el vector libre[].
*/
/*Apartado c)
como en a) minimizando el tiempo de trabajos.
Todos los trabajadores comienzan simultáneamente
El coste será el máximo entre los trabajos realizados puesto que empiezan
todos trabajando simultáneamente.
Etapa k: qué persona realiza el trabajo k
*/
void AsignaC(int k, int libre[], int t[][], tsolucion *sol, tsolucion *solopt){
if(sol->coste < solopt -> coste)
if(k==n)
*solopt=*sol;
else{
for(p=0; p<n; p++)
if (libre[p]){
libre[p]=FALSE;
Aux=sol->coste; //para deshacer
sol->coste=max(sol_coste,tkp);
Asignac(k+1, ----,);
//Deshacemos para la siguiente iteración
libre[p]=TRUE;
sol->coste=Aux;
}
}
}
/* Ej 12 -> para el jueves
Ej 6, 7, 22*/
/*Ejercicio 22 (fig 2)
Etapa k:
- ¿Qué objeto metemos? o bien
- ¿En qué bolsa metemos el objeto k? <-
Generación de descendientes
- El objeto k lo meteremos en una de las bolsas ya utilizadas o en una nueva
Fin: habiendo colocado todos los objetos (etapa n, para n objetos)
Test de fracaso: Si el objeto no entra en la bolsa.
*Test de optimalidad
- El código está en campusvirtual
*/
typedef struct{
int num;
vector envases; //envases [i]= envase en el que metemos el objeto i
}Solucion:
/* Ejercicio 6
(Fig 3)
Etapa k: asignar el trabajo k a un procesador (supuestos los trabajos anteriores ya están asignados)
Test fracaso:
Test solución: Todos los trabajos están asignados
Gen descendientes:
*/
/*t0,t1 tiempos consumidos en proc 0 y proc 1*/
void 2ProcBack(int k, int t0, int t1, int t[2][N], tsolucion *sol, tsolucion *solopt){
if(k==n){
sol->coste = max(t0,t1);
if(sol->coste < solopt->coste)
*solopt=*sol;
}
else{
//hacerlo en proc 0
sol->trabajo[k]=0;
2ProcBack(k+1, t0+t[0][k], t1, --------);
//hacerlo en proc 1
sol-trabajo[k]=1;
2ProcBack(k+1, t0, t1+t[1][k], ----);
}
}
//llamada inicial
2ProcBack(0, 0, 0, -----);
//Código en campusvirtual
// mejora de la solución
void 2ProcBack(int k, int t0, int t1, int t[2][N], tsolucion *sol, tsolucion *solopt){
sol->coste=max(t0,t1); //comprobamos si la solución tiene futuro
if(sol->coste < solopt->coste){
if(k==n)
*solopt=*sol;
}
else
[...]
}
/* M procesadores
etapa k: decidimos el procesador en el que realicamos el trabajo k (supuestos los k-1)
test solución: k=n
(ver fotocopias)
Prog dinámica
Dink(t0,t1)=min{Dink+q(t0+t0k, t1), Dink+1(t0, t1+t1k)}
*/
/*Jueves -> Ejercicio 76
Etapa K: Elegir qué casa visitar
Test de solución: visitar mientras tengamos tiempo.
Test de fracaso:
tvw + tw +
v------------w
tw0 +t0 < T
t'uw= tvw+tw
ir y visitar
t'vw t'w0 <=T
Generación de Descendientes: No iremos a una casa que ya esté visitada y tampoco si no nos da tiempo a regresar al aeropuerto.
- controlaremos si hemos visitado o no la casa con un vector de Booleanos.
Solución:
struct
- long (número de casas que he visitado)
- camino[] (las casas que he visitado)
Nota:
-Puedes elegir poner como última solución el regreso al aeropuerto
-tvw: Tiempo para ir de v a w + tiempo de hacer la visita
*/
void VisitasBack(int v, int TDisponible, int visitado[], int t[][],tsolucion *sol, tsolucion *opt){
if (SinTiempoVisitas(v, TDisponible, Visitados, t))
if(sol->long > solopt -> long)
*solopt = *sol;
else
for(w=1; w<N; w++){
if (!Visitado[w] && ((tvw+tw0)<=TDisponible)){
Visitado[w]=true;
Sol->long++; // se iniciará a -1
sol->camino[sol-long]=w; //sol->cam[++sol->long]=w; o sol->cam[sol->long++]=w
VisitasBack(w,TDisponible-tvw,-----------);
//Deshacer
Visitado[w]=FALSE;
Sol->long -;
}
}
}
//Inicialización
/*
sol.long = -1;
solopt.long=-INFINITO;
VisitasBack(0, ---------- &sol, &solopt);
visitados[w]=FALSE; visitados[0]=TRUE
1<=w<N
*/
int SinTiempoVisitas(){
for(w=1; w<N; w++)
if(!Visitado[w] && (tvw+tw0 <=TDisponible))
return FALSE;
return TRUE;
}
//versión 2.0
void VisitasBack(int v, int TDisponible, int visitado[], int t[][],tsolucion *sol, tsolucion *opt){
if(sol->long>solopt->long) // siempre intentamos prolongar
*solopt=*sol;
for(w=1; w<N; w++){
if (!Visitado[w] && ((tvw+tw0)<=TDisponible)){
Visitado[w]=true;
Sol->long++; // se iniciará a -1
sol->camino[sol-long]=w; //sol->cam[++sol->long]=w; o sol->cam[sol->long++]=w
VisitasBack(w,TDisponible-tvw,-----------);
//Deshacer
Visitado[w]=FALSE;
Sol->long -;
}
}
}
// Versión en Programación Dinámica
/*
Viajante(v,W,T) = max{1+Viajante(w, W-{w}, T - tvw)}
e={w€W,
tvw+tw0 <=T}
Si C=0
Viajante(v,W,T)=0
*/
void VisitasDin(int v, int TDisponible, int visitados[], int t[][], tsolucion *solopt){//atrás
tsolucion solpar, solmejor;
int w;
if (SinTiempoVisitas(v, TDisponible, visitados, t)) Solopt->Long=-1;
else{
solmejor.Long= - 1; // o -Inifnito, 0
for(w=1; w<N; w++)
if(!Visitado[w] && ((tvw + tw0) <= TDisponible)){
vistado[w]=TRUE;
VisitasDin(w, TDisponible -tvw, visitados, t, &solpar);
solpar.Long ++;
solpar.cam[solpar.Long]=w;
if (solpar.Long > solmejor.Long)
solmejor=solparc;
}
*solopt=solmejor;
}
}
// Pos1 -> la última casa que he visitado... etc.
//version 2.0
void VisitasDin(int v, int TDisponible, int visitados[], int t[][], tsolucion *solopt){//atrás
tsolucion solpar, solmejor;
int w;
solmejor.Long= - 1; // o -Inifnito, 0
for(w=1; w<N; w++)
if(!Visitado[w] && ((tvw + tw0) <= TDisponible)){
vistado[w]=TRUE;
VisitasDin(w, TDisponible -tvw, visitados, t, &solpar);
solpar.Long ++;
solpar.cam[solpar.Long]=w;
if (solpar.Long > solmejor.Long)
solmejor=solparc;
}
*solopt=solmejor;
}
///////////28-III-2011////////////
/*Control el día 12 (o el 5 omfg)*/
/*Hasta lo que veamos en esta semana*/
/*La vuelta del caballo: Tablero 8x8 casillas. El caballo debe visitar todas las casillas sin pasar dos veces por la misma. Casilla de inicio = casilla de fin.
-Etapak: Decidir la k-esima casilla del recorrido, supuesto que ya tengamos recorridos los anteriores.
-Condición de fin: cuando el caballo ha recorrido todas las casillas, sin repetir, acabando donde comenzó.(La primera es accesible desde la última)
* Dimensión n; n². Etapas 0 - n²
-Test de error: Las casillas no estén visitadas.
-Solución: un vector de soluciones. [ | | | | | ]
- Otra forma de hacerlo es numerar las casillas que vamos visitando.
*/
void VueltaBack(int k, tcasilla Cas, int N, int Tab[Dim][Dim]){
/*En la posición Cas hemos anotado k-1
Casilla de partida: cualquiera*/
if(k==N*N){/*falta comprobar si puede llegar a la casilla inicial*/
if(Accesible(cas,Tab,N))
Salida(Tab,N);
}
else{
for(i-2, i<=2; i++)
for(j=-2; j<=2; j++){
if(abs(i)+abs(j)==3){
NCas=Casilla(Cas.Fila+i, Cas.Columna+j);
if(Admisible(NCas,Tab,N)){
Tab[Ncas.Fila][NCas.Columna]=k;
VueltaBack(k+1, NCas, N, Tab);
}
}
}
}
}
int Admisible(TCas Cas, int Tab, int N){
if Dentro(Cas, N) /*Y no está visitada*/
return Tab[Cas.Fila]þCas.Columna]==-1;
else
return FALSE;
}
int Accesible(TCas Cas, int Tab[][], int N){ /*Eliminar el doble return*/
for(i=-2; i<=2; i++)
for(j=-2; j<=2; j++){
Nas=Casilla(Cas.Fila+i, Cas.columna+j);
if((abs(i)+abs(j)==3) && Dentro(NCas,N))
if(Tab[NCas.Fila][NCas.Columna]==0)
return TRUE;/**/
}
return FALSE;/**/
}
int Dentro(TCas cas, int N){
return ((Cas.Fila >=0) && (Cas.Fila<N) && (Cas.Columna >=0) && (Cas.Columna < N));
}
/*
1)Existe una variante del problema del caballo en la que se da la restricción de visitar (no necesariamente de manera consecutiva) una serie de casillas en orden.
(Implementarlo voluntariamente semana que viene)
2)Dadas dos casillas (origen y destino) hallar el camino mínimo entre ellas
Test de fracaso:
-Si la solución hallada es peor que la óptima que tenemos, falla.
-Si la casilla ya está visitada, falla.
Marcamos la casilla origen: 0
Marcamos las casillas accesibles desde ahí(origen + 1 paso): 1
Marcamos las casillas accesibles desde primer paso: 2
... etc
(Implementarlo voluntariamente antes del jueves)
3) Todos los caminos mínimos que nos llevan desde el origen hasta el destino
*/
///////// 29-III-2011 //////
|
C
|
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wordexp.h>
#include <ctype.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#define MAX_NUM 1073741823
//parse all of the information about the command into variables, store that
//into text log file
//figure out how to manage making sure someone first enters gallery before any rooms,
//and how to make sure someone leaves
//when someone leaves a room they are in the gallery ie a roomID is specified
//get each line of the file, parse it in the correct style, check if name is same as
//command line, next line if not...otherwise update ur shit
int file_write(char* timestamp, char* name, char* logpath, int isEmp, int isArr,char* room, char** previous_data,int num_lines){
FILE *n_log;
n_log = fopen(logpath, "w+");
if(n_log==NULL){
printf("invalid\n");
exit(255);
}
if(previous_data!=NULL){
int i;
for(i = 0;i<num_lines;i++){
fwrite(previous_data[i],1,strlen(previous_data[i]),n_log);
fwrite("\n",1,1,n_log);
}
//fwrite("\n",1,1,n_log);
}
int testing = 0;
if(testing){
fwrite("H|e|l|l|o\n",1,10,n_log);
fwrite("D|a|v|i|d\n",1,10,n_log);
}else{
fwrite(timestamp,1,strlen(timestamp),n_log);
fwrite("|",1,1,n_log);
fwrite(name,1,strlen(name),n_log);
fwrite("|",1,1,n_log);
if(isEmp == 1){
fwrite("EM",1,2,n_log);
}else{
fwrite("GU",1,2,n_log);
}
fwrite("|",1,1,n_log);
if(isArr==0&&room !=NULL){
fwrite(room,1,strlen(room),n_log);
}else if(isArr == 1&& room!=NULL) {
fwrite(room,1,strlen(room),n_log);
}else if(isArr == 0&&room ==NULL){
fwrite("-",1,1,n_log);
}else{
fwrite("-",1,1,n_log);
}
fwrite("|",1,1,n_log);
if(isArr == 1){
fwrite("AV",1,2,n_log);
}else{
fwrite("DP",1,2,n_log);
}
fwrite("\n",1,1,n_log);
}
fclose(n_log);
return 0;
}
//how to prevent " " in name...just accepts it as new argument
int is_valid_name(char* name){
int j;
for(j=0;j<strlen(name);j++){
if(isalpha(name[j])==0){
printf("invalid\n");
exit(255);
}
}
return 0;
}
int parse_cmdline(int argc, char *argv[]) {
FILE *log;
int opt = -1;
int is_good = -1;
int arg_count = 2;
int isEmp = 0;
int isArr = 0;
//int token_spot;
int fsize;
int new_name = 1;
int already_specified_emp_gue = 0;
int already_specified_arr_dep = 0;
char *logpath = NULL;
char *name;
char *timestamp;
char *room=NULL;
int room_int,time_int;
unsigned char token[16];
unsigned char iv[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
//unsigned char tag[16];
unsigned char* out_data;
unsigned char* i_msg;
int out_len1 = 0;
int out_len2 = 0;
int k;
int p;
int room_set = 0;
EVP_CIPHER_CTX *ctx;
//pick up the switches
while ((opt = getopt(argc, argv, "T:K:E:G:ALR:B:")) != -1) {
switch(opt) {
case 'B':
printf("unimplemented");
case 'T':
//timestamp
//timestamp = malloc(sizeof(char*)*strlen(argv[arg_count]));
timestamp = argv[arg_count];
time_int = atoi(timestamp);
if(time_int<=0||time_int>MAX_NUM){
printf("invalid\n");
exit(255);
}
arg_count += 2;
break;
case 'K':
//secret token
// token = malloc(sizeof(char*)*strlen(argv[arg_count]));
// token = argv[arg_count];
for(p=0;p<strlen(argv[arg_count]);p++){
if(isalpha(argv[arg_count][p])==0&&!isdigit(argv[arg_count][p])){
printf("invalid\n");
exit(255);
}
}
if(strlen(argv[arg_count])>16){
for(k = 0;k<16;k++){
token[k] = argv[arg_count][k];
}
}else{
for(k = 0; k < strlen(argv[arg_count]);k++){
if(argv[arg_count][k] == '\0'){
token[k] = '\x20';
}else{
token[k] = argv[arg_count][k];
}
}
for(k = strlen(argv[arg_count]); k < 16;k++){
token[k] = '\x20';
}
// line[strlen(line)+1] = '\x20';
// strcat(pad,line);
token[16] = '\0';
}
//token[17] = '\n';
//token_spot = arg_count;
arg_count += 2;
break;
//should always be next argument after K
case 'A':
//arrival
if(already_specified_arr_dep){
printf("invalid\n");
exit(255);
}else{
arg_count++;
isArr = 1;
already_specified_arr_dep = 1;
}
break;
case 'L':
//departure
if(already_specified_arr_dep){
printf("invalid\n");
exit(255);
}else{
arg_count++;
isArr = 0;
already_specified_arr_dep = 1;
}
break;
case 'E':
//employee name
if(already_specified_emp_gue){
printf("invalid\n");
exit(255);
}else{
//name = malloc(sizeof(char*)*strlen(argv[arg_count]));
name = argv[arg_count];
is_valid_name(name);
arg_count += 2;
isEmp = 1;
already_specified_emp_gue = 1;
}
break;
case 'G':
//guest name
if(already_specified_emp_gue){
printf("invalid\n");
exit(255);
}else{
//name = malloc(sizeof(char*)*strlen(argv[arg_count]));
name = argv[arg_count];
is_valid_name(name);
arg_count += 2;
isEmp = 0;
already_specified_emp_gue = 1;
}
break;
case 'R':
//room ID
//room = malloc(strlen(argv[arg_count]));
room = argv[arg_count];
while(*room && *room=='0'){
room++;
}
room_int = atoi(room);
if(room_int<0||room_int>MAX_NUM){
printf("invalid\n");
exit(255);
}
arg_count += 2;
break;
default:
//unknown option, leave
break;
}
}
//pick up the positional argument for log path
if(optind < argc) {
logpath = argv[optind];
}
//ssize_t read;
//size_t len;
int i = 0;
int i_len;
//char *line = NULL;
char *prev_name,*prev_timestamp,*prev_emp_gue,*prev_room,*prev_arr_dep;
char *recent_room,*recent_arr_dep;//*recent_name;//,*recent_timestamp, *recent_emp,*/
//opens old log and goes through line by line
if(access(logpath,F_OK)!=-1){ //if file exists
//decrypt old log here
log = fopen(logpath,"r");
fseek(log,0L,SEEK_END);
fsize = ftell(log);
fseek(log,0L,SEEK_SET);
unsigned char buffer[fsize];
memset(buffer, 0,fsize);
i_msg = malloc(fsize);
out_data = malloc(fsize*2);
i_len = fread(buffer,1,fsize,log);
buffer[fsize+1] = '\0';
fclose(log);
i_msg[i_len] = '\0';
ctx = EVP_CIPHER_CTX_new();
if(!EVP_DecryptInit(ctx,EVP_aes_256_cbc(),token,iv)){
printf("invalid\n");
exit(255);
}
EVP_DecryptUpdate(ctx, out_data,&out_len1,buffer,fsize);
//if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG,16,tag)){
// printf("invalid decrpyt");
// exit(255);
// }
EVP_DecryptFinal(ctx, out_data + out_len1,&out_len2);
out_data[out_len1+out_len2] = '\0';
char *copy_data = malloc(strlen((char*)out_data));
strcpy(copy_data,(char*)out_data);
//printf("%s",out_data);
EVP_CIPHER_CTX_free(ctx);
//int total_len = out_len1+out_len2;
//free(i_msg);
//lprintf("%s", (char*)out_data);
int num_lines = 0;
int max_len = 0;
// int
//log = fopen(logpath,"w");
char* tok;
int a = 0;
tok = strtok((char*)out_data,"\n");
if(tok!=NULL&&strlen(tok)>max_len){
max_len = strlen(tok);
}
//temp = tok;
//strcpy(new_array[a],tok);
a++;
while(tok!=NULL){
tok = strtok(NULL,"\n");
if(tok!=NULL&&strlen(tok)>max_len){
max_len = strlen(tok);
}
if(tok == NULL){
num_lines = a;
break;
}
//strcpy(new_array[a],tok);
a++;
}
free(out_data);
//parse log here
char new_array[num_lines][max_len+1];
a = 0;
tok = strtok(copy_data,"\n");
strcpy(new_array[a],tok);
a++;
while(tok!=NULL){
tok = strtok(NULL,"\n");
if(tok!=NULL){
strcpy(new_array[a],tok);
}
a++;
}
//trims each string
// for(a = 0; a < num_lines;a++){
// int s = 0;
// for(s = 0;s<strlen(new_array[a]);s++){
// if('\0'!=new_array[a][s]){
// new_array[a][s] = new_array[a][s];
// }else{
// break;
// }
// }
// }
char *copy_array[num_lines];
for(a = 0;a<num_lines;a++){
copy_array[a] = strdup(new_array[a]);
}
//while((read = getline(&line,&len,log))!=-1){
a = 0;
//while(strcmp(new_array[a],"")!=0){
//tok = strtok(line,"|");
//tok = strtok(new_array[a],"|");
//prev_timestamp = malloc(sizeof(char*)*strlen(tok));
for(a = 0; a < num_lines;a++){
tok = strtok(new_array[a],"|");
//prev_timestamp = malloc(sizeof(char*)*strlen(tok));
prev_timestamp = tok;
//printf("%d",a);
i++;
while(tok != NULL){
tok = strtok(NULL,"|");
if(tok!= NULL&&strcmp("|",tok)!=0&&i==1){
//prev_name = malloc(sizeof(char*)*(strlen(tok)));
prev_name = tok;
}else if(tok!= NULL&&strcmp("|",tok)!=0&&i==2){
//prev_emp_gue = malloc(sizeof(char*)*(strlen(tok)));
prev_emp_gue = tok;
}else if(tok!= NULL&&strcmp("|",tok)!=0&&i==3){
//prev_room = malloc(sizeof(char*)*(strlen(tok)));
prev_room = tok;
}else if(tok!= NULL&&strcmp("|",tok)!=0&&i==4){
//prev_arr_dep = malloc(sizeof(char*)*(strlen(tok)));
prev_arr_dep = tok;
}
i++;
}//will save most recent data of the current name from the command
i = 0;
//recent_room = malloc(sizeof(char*)*(strlen(prev_room)));
//recent_arr_dep = malloc(sizeof(char*)*(strlen(prev_arr_dep)));
if(strcmp(prev_name,name)==0&&((strcmp(prev_emp_gue,"EM")==0&&isEmp==1)||(strcmp(prev_emp_gue,"GU")==0&&isEmp==0))){
new_name = 0;
room_set = 1;
//recent_name = malloc(sizeof(char*)*(strlen(prev_name)));
//strcpy(recent_name,prev_name);
// recent_emp = malloc(sizeof(char*)*(strlen(tok)));
// recent_emp = prev_emp_gue;
recent_room = malloc(sizeof(char*)*(strlen(prev_room)));
strcpy(recent_room,prev_room);
recent_arr_dep = malloc(sizeof(char*)*(strlen(prev_arr_dep)));
strcpy(recent_arr_dep,prev_arr_dep);
}
}
//a++;
//}
//saving the most recent line in log where the name and employment status matched
//in all of the recent_ variables
int prev_time_int = atoi(prev_timestamp);
if(prev_time_int >= time_int){
printf("invalid\n");
exit(255);
}
if(new_name == 1){
if(isArr==1&&room==NULL){
file_write(timestamp,name,logpath,isEmp,isArr,NULL,copy_array,num_lines);
}else{
printf("invalid\n");
exit(255);
}
}else if(room_set&&isArr==1&&strcmp("DP",recent_arr_dep)!=0&&strcmp("-",recent_room)!=0){
printf("invalid\n");
exit(255);
}else if(room_set&&room!=NULL&&isArr == 1&&strcmp(room,recent_room)==0&&strcmp("DP",recent_arr_dep)!=0){
printf("invalid\n");
exit(255);
}else if(room_set&&room == NULL && isArr == 1&& strcmp("-",recent_room)==0&&strcmp("AV",recent_arr_dep)==0){
printf("invalid\n");
exit(255);
}else if(room_set&&room!=NULL&&isArr == 0&&strcmp("DP",recent_arr_dep)==0&&strcmp(room,recent_room)!=0){
printf("invalid\n");
exit(255);
}else if(room_set&&room!=NULL&&isArr == 0&&strcmp(recent_room,"-")!=0&&strcmp("DP",recent_arr_dep)==0){
printf("invalid\n");
exit(255);
}else if(room_set&&recent_room!=NULL&&recent_arr_dep!=NULL&&room == NULL&&strcmp("DP",recent_arr_dep)==0&&strcmp("-",recent_room)==0&&isArr==0){
printf("invalid\n");
exit(255);
}else if(room_set&&room != NULL&&strcmp("DP",recent_arr_dep)==0&&strcmp("-",recent_room)==0){
printf("invalid\n");
exit(255);
}else if(room_set&&room!=NULL&&isArr == 0&&strcmp(recent_room,room)!=0&&strcmp("AV",recent_arr_dep)==0){
printf("invalid\n");
exit(255);
}else if(room_set&&room == NULL&&isArr == 0&&strcmp("-",recent_room)!=0&&strcmp("AV",recent_arr_dep)==0){
printf("invalid\n");
exit(255);
}else if(room_set&&room == NULL&&strcmp("-",recent_room)){
//printf("leaving gallery");
file_write(timestamp,name,logpath,isEmp,isArr,NULL,copy_array,num_lines);
}else{
file_write(timestamp,name,logpath,isEmp,isArr,room,copy_array,num_lines);
}
//free(prev_room);
if(room_set){
free(recent_room);
free(recent_arr_dep);
}
FILE *fp = fopen(logpath,"r");
if(fp==NULL){
printf("invalid");
exit(255);
}
fseek(fp,0L,SEEK_END);
fsize = ftell(fp);
fseek(fp,0L,SEEK_SET);
i_msg = malloc(fsize);
out_data = malloc(fsize*2);
fread(i_msg,sizeof(char),fsize,fp);
fclose(fp);
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(ctx, EVP_aes_256_cbc(),token,iv);
EVP_EncryptUpdate(ctx,out_data,&out_len1,i_msg,fsize);
EVP_EncryptFinal(ctx,out_data+out_len1,&out_len2);
out_data[out_len1+out_len2] = '\0';
int length = out_len1+out_len2;
//EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG,16,tag);
EVP_CIPHER_CTX_free(ctx);
fp = fopen(logpath,"w+");
fwrite(out_data,1,length,fp);
//fwrite("\n",1,1,fp);
//fwrite(tag,1,16,fp);
fclose(fp);
free(i_msg);
free(out_data);
}else{//else if file doesnt exist aka first entry
if(room!=NULL||time_int<0||isArr==0){//and room is not specified
printf("invalid\n");
exit(255);
}else{
//decrpyt new log
file_write(timestamp,name,logpath,isEmp,isArr,NULL,NULL,0);
FILE *fp = fopen(logpath,"r");
if(fp==NULL){
printf("invalid\n");
exit(255);
}
fseek(fp,0L,SEEK_END);
fsize = ftell(fp);
fseek(fp,0L,SEEK_SET);
i_msg = malloc(fsize);
out_data = malloc(fsize*2);
fread(i_msg,sizeof(char),fsize,fp);
fclose(fp);
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(ctx, EVP_aes_256_cbc(),token,iv);
EVP_EncryptUpdate(ctx,out_data,&out_len1,i_msg,fsize);
EVP_EncryptFinal(ctx,out_data+out_len1,&out_len2);
out_data[out_len1+out_len2] = '\0';
int length = out_len1+out_len2;
//EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG,16,tag);
EVP_CIPHER_CTX_free(ctx);
fp = fopen(logpath,"w+");
fwrite(out_data,1,length,fp);
//fwrite("\n",1,1,fp);
//fwrite(tag,1,16,fp);
fclose(fp);
free(i_msg);
free(out_data);
}
}
//free EVERYTHING i think...
// if(recent_room!=NULL){
// free(recent_room);
// }
// if(recent_arr_dep!=NULL){
// free(recent_arr_dep);
// }
//free(recent_room);
//free(recent_arr_dep);
// free(room);
// if(name!=NULL){
// free(name);
// }
//free(name);
// free(departure);
// free(arrival);
// free(token);
// free(timestamp);
//free prev_arr_dep
//free prev_name
//free prev_emp_gue
//free prev room
//encrypt here
return is_good;
}
int main(int argc, char *argv[]) {
int result;
result = parse_cmdline(argc, argv);
if(result!= -1){
printf("invalid");
}
return 0;
}
|
C
|
#include "shell.h"
void readcmd(char *buffer)
{
char ch = ' ';
int cur = 0;
while (1)
{
read(0, &ch, 1);
if (ch == '\n' || ch == '\0')
{
buffer[0] = '\0';
return;
}
else if (ch != ' ' && ch != '\v' && ch != '\t')
break;
}
buffer[cur] = ch;
cur = cur + 1;
while (1)
{
if (ch == '\n' || ch == '\0')
break;
read(0, &ch, 1);
if ((ch == ' ' || ch == '\v' || ch == '\t') && (ch != '\0' && ch != '\n'))
{
buffer[cur] = ch;
cur = cur + 1;
while ((ch == ' ' || ch == '\v' || ch == '\t') && (ch != '\0' && ch != '\n'))
read(0, &ch, 1);
}
buffer[cur] = ch;
cur = cur + 1;
}
cur--;
while (buffer[cur] == ' ' || buffer[cur] == '\t' || buffer[cur] == '\v' || buffer[cur] == '\0' || buffer[cur] == '\n')
cur--;
buffer[cur + 1] = '\0';
for (int i = 0; buffer[i] != '\0'; i++)
if (buffer[i] == '\t' || buffer[i] == '\v')
buffer[i] = ' ';
}
|
C
|
/*
* Usage:
* gcc hello_word.c -o hello_word_c.bin
* ./hello_world_c.bin
*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("%s\n", "Hello World");
return 0;
}
|
C
|
/////////////////////////////////////////////////////////////////////////
//// EX_DMA_PING_PONG.C ////
//// ////
//// This program reads 100 A/D samples captured from channel ////
//// AN8 and stores them in DMA RAM. The next set of 1000 samples ////
//// that are read are transferred to a seperate data buffer. ////
//// The DMA is setup in Ping Pong mode in which it will alternate ////
//// between two buffers to fill in data read from the ADC channel ////
//// The user can process data in buffer 1 while the second buffer ////
//// is getting filled up. The second buffer can then be processed ////
//// as the first gets filled up. ////
//// ////
//// The code is setup to read data from ADC channel 8. A timer ////
//// interrupt is called every 1 ms which triggers a conversion. ////
//// At the end of every conversion, the DMA transfer takes place ////
//// The DMA count register is set to 100 using the dma_start() ////
//// function call which uses the sizeof buffer to set the count ////
//// When 'count' number of conversions and transfers are complete ////
//// the DMA interrupt gets triggered. The user can toggle between ////
//// these two buffers by toggling the ////
//// ////
//// Configure the CCS prototype card as follows for PCD: ////
//// Use the POT labeled AN8. ////
//// ////
//// Select either the ICD or your own RS232-to-PC connection ////
//// for the text I/O. ////
//// ////
//// This example will work with the PCD compiler. ////
//// Change the device, clock and RS232 pins for your hardware ////
//// if needed. ////
/////////////////////////////////////////////////////////////////////////
//// (C) Copyright 1996,2009,2018 Custom Computer Services ////
//// This source code may only be used by licensed users of the CCS ////
//// C compiler. This source code may only be distributed to other ////
//// licensed users of the CCS C compiler. No other use, ////
//// reproduction or distribution is permitted without written ////
//// permission. Derivative programs created using this software ////
//// in object code form are not restricted in any way. ////
/////////////////////////////////////////////////////////////////////////
#if !defined(__PCD__)
#error This example only compiles with PCD compiler
#endif
#include <33FJ128GP706.h>
#device ADC=16
#use delay( crystal=20mhz )
#use rs232(icd) //Text through the ICD
//#use rs232(baud=9600, UART2) //Text through the UART
void ProcessInput(unsigned int *);
BOOLEAN DMA_Buffer; // Flag to test if DMA interupt has been serviced.
#define BUFFER_SIZE 100 //DMA BUFFER Size
/*The BANK_DMA directive will place the following variable, array or
structure in the DMA RAM*/
#BANK_DMA
unsigned int DMA_BUFFER_A[BUFFER_SIZE];
#BANK_DMA
unsigned int DMA_BUFFER_B[BUFFER_SIZE];
#INT_DMA0
void DMA0_ISR(void)
{
if(DMA_Buffer)
ProcessInput(&DMA_BUFFER_A[0]);
else
ProcessInput(&DMA_BUFFER_B[0]);
DMA_Buffer ^=1; // Toggle between buffers
}
#int_timer1
void Timer_ISR()
{
/* call the function to read ADC value
This value is transfered to DMA buffer directly*/
read_adc();
}
void main() {
unsigned int16 value;
setup_dma(0, DMA_IN_ADC1, DMA_WORD);
/*
Built-in function dma_start options are as follows -
dma_start(channel, options, buffera, bufferb, size)
// bufferb is optional depending on mode
// size is optional, if omitted the size of buffera is used
// buffers must be declared with "#bank_dma"
*/
dma_start(0, DMA_CONTINOUS|DMA_PING_PONG, &DMA_BUFFER_A[0], &DMA_BUFFER_B[0],BUFFER_SIZE );
setup_port_a( sAN8 );
setup_adc( ADC_CLOCK_INTERNAL );
set_adc_channel( 8 );
printf("\n\rSampling:");
/*Call first conversion, later conversions are called using Timer interrupt*/
value = read_adc();
// Sample every 1 ms, 1000 samples in 1 second to fill buffer
setup_timer1(TMR_INTERNAL ,600);
/* Enable the peripheral and global interrupts */
enable_interrupts(INT_TIMER1);
enable_interrupts(INT_DMA0);
enable_interrupts(GLOBAL);
while (TRUE);
}
void ProcessInput(unsigned int *ptr)
{
unsigned int i, ADC_Buffer[BUFFER_SIZE];
for (i=0; i<BUFFER_SIZE; i++)
{
ADC_Buffer[i]=*ptr++;
}
//TODO: user code to process the values
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define L 30
#define N 20
#define NITER 30
int chain[L]; /* Array, which contains the cain sites. */
int position[N]; /* Array, which contains particles' positions */
int head;
int tail;
const double p = 0.5;
const double p_tilde = 1.0;
double drand();
int nextupdate(int current, int next, double p, double q, int *chain_old);
int pos(int);
void main (void) {
int i, j, iter;
int next, chain_old, end_flag;
double probability;
char code[2];
/* Initialization */
code[0] = '-';
code[1] = 'X';
for (i=0; i<L; i++) chain[i] = 0;
for (i=0; i<N; i++) position[i] = 0;
srand(time(NULL));
/* Generation of initial positions */
position[0] = rand() % L;
chain[position[0]] = 1;
for (i=1; i<N; i++) {
updatePosition:
position[i] = rand() % L;
for (j=0; j<i; j++) if (position[j]==position[i]) goto updatePosition;
chain[position[i]] = 1;
}
printf("=========================================================\n");
for (i=0; i<N; i++) printf("position[%d] = %d\n", i, position[i]);
/* Instead of sort of array position */
for (i=0, j=0; i<L; i++) {
if (chain[i]==1) position[j++] = i;
}
printf("=========================================================\n");
for (i=0; i<N; i++) printf("position[%d] = %d\n", i, position[i]);
printf("=========================================================\n");
/* Simulation */
for (j=0; j<L; j++) printf("%c", code[chain[j]]);
printf("\n");
chain_old = 0;
head = 0;
tail = head + L;
for (iter=0; iter<NITER; iter++) {
//end_flag = nextupdate(0, L-1, p, p_tilde, &chain_old);
if (!chain[pos(tail-1)]) tail--;
for (i=head; i<tail; i++) {
nextupdate(pos(i), pos(i-1), p, p_tilde, &chain_old);
}
head = tail;
tail = head + L;
//if (end_flag == 0) {
// nextupdate(L-1, L-2, p, p_tilde, &chain_old);
//}
for (j=0; j<L; j++) printf("%c", code[chain[j]]);
printf("\n");
}
}
double drand() {
return (1.0*rand()) / RAND_MAX;
}
int pos(i) {
return (i+L)%L;
}
int nextupdate(int current, int next, double p, double q, int *chain_old) {
int end_flag = 0;
double probability;
if (chain[current] == 1) {
if (*chain_old == 0) {
probability = p;
} else {
probability = q;
}
if (chain[next] == 0 && drand() < probability) {
chain[current] = 0;
chain[next] = 1;
end_flag = 1;
}
*chain_old = 1;
} else {
*chain_old = 0;
}
return end_flag;
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
int main()
{
float nota,mediaapro=0,mediarepro=0;
int apro=0,repro=0;
const int flag=-1;
do{
printf("\n\tDigite a nota do aluno,caso desejar sair digite -1: ");
scanf("%f",¬a);
}while(nota<flag);//fim do do while
while(nota!=flag){
if(nota>=60){
apro++;
mediaapro+=nota;
}//fim do if
else{
repro++;
mediarepro+=nota;
}//fim do else
do{
printf("\n\tDigite a nota do aluno,caso desejar sair digite -1: ");
scanf("%f",¬a);
}while(nota<flag);//fim do do while
}//fim do while
if(apro!=0)
mediaapro=mediaapro/(float)apro;
if(repro!=0)
mediarepro=mediarepro/(float)repro;
printf("\n\tA media de notas de alunos aprovados eh de %f",mediaapro);
printf("\n\tA media de notas de alunos reprovados eh de %f",mediarepro);
printf("\n\tObrigado por usar o programa!");
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int t;
printf("\n enter the number");
scanf("%d",&t);
if(t%2!=0)
printf("the value of t is odd");
else
printf("the value of t is even");
}
|
C
|
/*
Program to count number of characters, words and lines in a given file.
*/
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main(int argc, char *argv[]){
FILE *f;
char ch;
int character=0, line=0,word=0;
f=fopen(argv[1],"r");
if(f==NULL){
printf("404: FILE NOT FOUND\n");
printf("HINT: PASS VALID FILENAME AS ARGUMENT TO THE PROGRAM\n");
fclose(f);
return 0;
}
printf("FILE NAME: %s\n",argv[1]);
while((ch=getc(f))!=EOF){
character++;
if(ch=='\n')
line++;
if(isspace(ch)||ch=='\t'||ch=='\n')
word++;
}
fclose(f);
putchar('\n');
printf("no of line=%d\n",line);
printf("no of word=%d\n",word);
printf("no of character=%d\n",character);
return 1;
}
/*
With regards,
Shivaji Varma
*/
|
C
|
#include<stdio.h>
int main()
{
int i;
while(scanf("%d",&i)!=EOF)
{
if(i==0)
printf("vai ter copa!\n");
else
printf("vai ter duas!\n");
}
return 0;
}
|
C
|
/*
Construa um programa com duas variáveis, uma inteira e
um ponteiro de inteiro. Atribua valores para as variáveis e
imprima na tela os seus valores e a soma de seus valores.
[fixacao4.c]
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int *p;
a = 10;
p = (int *)malloc(sizeof(int));
*p = 100;
printf("A soma de %d e %d é %d\n", a, *p, a + *p);
free(p);
printf("Fim\n");
}
|
C
|
#include<ulk.h>
#include"macros.h"
#include <ulk_base_types.h>
#include <ulk_fpga_uart.h>
#include<ulk_fpga_char_lcd.h>
int main(void) PROGRAM_ENTRY;
int main()
{
ulk_proc_gpio_init();
ulk_proc_sys_pad_set_mux_mode (140, 4);
ulk_proc_sys_pad_set_mux_mode (141, 4);
ulk_proc_sys_pad_set_mux_mode (142, 4);
ulk_proc_sys_pad_set_mux_mode (143, 4);
ulk_proc_sys_pad_set_mux_mode (158, 4);
ulk_proc_gpio_set_dir ( 140, 0);
ulk_proc_gpio_set_dir ( 141, 0);
ulk_proc_gpio_set_dir ( 142, 0);
ulk_proc_gpio_set_dir ( 143, 0);
ulk_proc_gpio_set_dir ( 158, 0);
ulk_proc_gpio_set_data_out (158, 0);
// initialzing FPGA UART
ulk_fpga_uart_init(9600,3);
//ulk_proc_uart_init(9600,3);
ulk_cpanel_printf("\n");
// initializing LCD
ulk_fpga_clcd_init ();
ulk_fpga_clcd_display_on();
ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("Choose Mode: a/m/t");
// prepping uart for read
int cnt =0;
char direction='x';
char mode='x';
ulk_cpanel_printf("Reading...");
ulk_cpanel_printf("Initial Values: %c; %c \n", (char)mode, (char)direction);
while(1)
{
mode=ulk_fpga_uart_getc(3);
direction=ulk_fpga_uart_getc(3);
//direction=ulk_proc_uart_getc(3);
//ulk_cpanel_printf("Loop No: %d\t", cnt++);
ulk_cpanel_printf("Values read: %c; %c \n", (char)mode, (char)direction);
ulk_proc_gpio_set_data_out (158, 1);
if (direction == 's')
{
// lcd panel print
if(mode == 't')
{ ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("test - straight");
}
else if(mode == 'a')
{ ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("auto - straight");
}
// motor action
ulk_proc_gpio_set_data_out (140, 0);
ulk_proc_gpio_set_data_out (141, 0);
ulk_proc_gpio_set_data_out (142 , 1);
ulk_proc_gpio_set_data_out (143 , 0);
ulk_proc_delay(ULK_SEC(0.1));
ulk_proc_gpio_set_data_out (140, 0);
ulk_proc_gpio_set_data_out (141, 0);
ulk_proc_gpio_set_data_out (142 , 0);
ulk_proc_gpio_set_data_out (143 , 0);
ulk_proc_delay(ULK_SEC(0.3));
}
else if(direction == 'l')
{
// lcd panel print
if(mode == 't')
{ ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("test - left");
}
else if(mode == 'a')
{ ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("auto - left");
}
// motor action
ulk_proc_gpio_set_data_out (140 , 1);
ulk_proc_gpio_set_data_out (141 , 0);
ulk_proc_gpio_set_data_out (142 , 1);
ulk_proc_gpio_set_data_out (143 , 0);
ulk_proc_delay(ULK_SEC(0.1));
ulk_proc_gpio_set_data_out (140 , 1);
ulk_proc_gpio_set_data_out (141 , 0);
ulk_proc_gpio_set_data_out (142 , 0);
ulk_proc_gpio_set_data_out (143 , 0);
ulk_proc_delay(ULK_SEC(0.3));
}
else if (direction == 'r')
{
// lcd panel print
if(mode == 't')
{ ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("test - right");
}
else if(mode == 'a')
{ ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("auto - right");
}
// motor action
ulk_proc_gpio_set_data_out (140, 0);
ulk_proc_gpio_set_data_out (141, 1);
ulk_proc_gpio_set_data_out (142 , 1);
ulk_proc_gpio_set_data_out (143 , 0);
ulk_proc_delay(ULK_SEC(0.1));
ulk_proc_gpio_set_data_out (140, 0);
ulk_proc_gpio_set_data_out (141, 1);
ulk_proc_gpio_set_data_out (142 , 0);
ulk_proc_gpio_set_data_out (143 , 0);
ulk_proc_delay(ULK_SEC(0.3));
}
else if(direction == 'n')
{
if(mode == 'm')
{ ulk_fpga_clcd_display_clear();
ulk_fpga_clcd_display_string("man - ***");
}
}
/* else
{
ulk_cpanel_printf("nothing");
ulk_proc_gpio_set_data_out (140, 0);
ulk_proc_gpio_set_data_out (141, 0);
ulk_proc_gpio_set_data_out (142 , 0);
ulk_proc_gpio_set_data_out (143 , 0);
ulk_proc_gpio_set_data_out (158, 1);
}*/
ulk_proc_gpio_set_data_out (158, 0);
//confirm all actuation is complete
ulk_fpga_uart_putc('c'); // if not detected on PC, due to timing mismatch of execution time, then place a small delay before this line.
}// end of while
}
|
C
|
#include <stdio.h>
#define INFINITY 100
#define MAX_VERTEX_NUM 20
#define OK 1
typedef struct
{
int vex[MAX_VERTEX_NUM];
int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexnum,arcnum;
}MGraph;
int p[20][20][20];
int a[20];
int LocateVex(MGraph *G,int v)
{
int i,j;
for(i=0;i<=G->vexnum;i++)
{
if(G->vex[i]==v)
{
j=i;
break;
}
}
return j;
}
void setpath(int v,int w,int u)
{
int i=0,j=0,a,b;
/* printf("%d,%d,%d->",v,w,u);
printf("%d %d %d\n",p[v][u][0],p[v][u][1],p[v][u][2]);
printf("%d %d %d\n",p[u][w][0],p[u][w][1],p[u][w][2]);
*/
while(p[v][u][i]!=-1)
{
i++;
}
while(p[u][w][j]!=-1)
{
j++;
}
for(a=0;a<i;a++)
{
p[v][w][a]=p[v][u][a];
// printf("----%d----\n",p[v][w][a]);
}
for(b=0;b<j-1;b++)
{
p[v][w][a+b]=p[u][w][b+1];
// printf("----%d----\n",p[v][w][a+b]);
}
}
int CreateND(MGraph *G)
{
int i,j,k,v1,v2,w;
printf(" floyd \n 20082557 \nڵͱÿո:");
scanf("%d %d",&G->vexnum,&G->arcnum);
// printf("\n");
printf("ڵţÿո:");
for(i=0;i<G->vexnum;++i)
{
scanf("%d",&G->vex[i]);
}
for(i=0;i<G->vexnum;++i)
{
for(j=0;j<G->vexnum;++j)
{
G->arcs[i][j]=INFINITY;
}
}
// printf("\n");
printf("ߵȨֵʽһ·س:\n");
for(k=0;k<G->arcnum;++k)
{
scanf("%d,%d,%d",&v1,&v2,&w);
i=LocateVex(G,v1);
j=LocateVex(G,v2);
G->arcs[i][j]=w;
}
return OK;
}
void shortestpath(MGraph *G)
{
int v,w,u,i;
int d[20][20];
for(v=0;v<G->vexnum;++v)
{
for(w=0;w<G->vexnum;++w)
{
d[v][w]=G->arcs[v][w];
for(u=0;u<G->vexnum;++u)
{
p[v][w][u]=-1;
}
if(d[v][w]<100)
{
p[v][w][0]=v;
p[v][w][1]=w;
}
}
}
for(v=0;v<G->vexnum;++v)
{
for(w=0;w<G->vexnum;++w)
{
p[v][w][G->vexnum]=-1;
}
}
//printf("!!!!%d!!!\n",p[0][1][2]);
for(u=0;u<G->vexnum;++u)
{
for(v=0;v<G->vexnum;++v)
{
for(w=0;w<G->vexnum;++w)
{
if(d[v][u]+d[u][w]<d[v][w])
{
d[v][w]=d[v][u]+d[u][w];
// printf("!!!!!!!\n");
// printf("%d,%d,%d,%d\n",d[v][w],v,w,u);
setpath(v,w,u);
//printf("%d,%d,%d,%d\n",d[v][w],v,w,u);
}
}
// printf("!!!!!!!\n");
}
}
for(v=0;v<G->vexnum;++v)
{
for(w=0;w<G->vexnum;++w)
{
if(v==w) continue;
{
printf("\n%d->%d is %d:",G->vex[v],G->vex[w],d[v][w]);
}
for(i=0;i<=G->vexnum;++i)
{
if(d[v][w]==100)
{
printf("ɴ");
break;
}
if(p[v][w][i]!=-1)
{
printf("·%d ",G->vex[p[v][w][i]]);
}
}
}
}
}
void floyd()
{
MGraph G;
CreateND(&G);
shortestpath(&G);
printf("\n");
}
int main(void)
{
floyd();
return 1 ;
}
|
C
|
// list/list.c
//
// Implementation for linked list.
//
// Akosua Wordie
//Colllab: Dr. Burge and Izzac Ballard
#include <stdio.h>
#include <stdlib.h>
//#include <string.h>
#include "list.h"
list_t *list_alloc() {
list_t *l = malloc(sizeof(list_t));
l->head = NULL;
return l;
}
node_t *node_alloc(elem val){
node_t *n = malloc(sizeof(node_t));
n->value = val;
n->next = NULL;
return n;
}
void list_free(list_t *l) {
node_t *tempp, *currp;
if(l->head != NULL){
if(l->head->next != NULL){
currp = l->head;
while(currp != NULL){
tempp = currp->next;
free(currp);
//l->head = tmp; ????
currp = tempp;
}
}
else{
free(l->head);
}
l->head = NULL;
}
}
void node_free(node_t *n){
free(n);
}
void list_print(list_t *l) {
node_t *cur = l->head;
while (cur != NULL){
printf("%d\n", cur->value);
cur = cur-> next;
}
}
int list_length(list_t *l) {
node_t *current = l->head;
int len = 0;
while (current != NULL){
len++;
current = current-> next;
}
return len;
}
void list_add_to_front(list_t *l, elem value) {
node_t *newNode;
newNode = node_alloc(value);
newNode ->next = l->head;
l->head = newNode;
}
void list_add_at_index(list_t *l, elem val, int index) {
int i = 0;
node_t *newNode = node_alloc(val);
node_t *current = l->head;
if (index==0){
list_add_to_front(l, val);
}
else if (index > 0){
while (i < (index - 1) && current -> next != NULL){
current = current->next;
i++;
}
newNode -> next = current -> next;
current->next= newNode;
}
}
void list_add_to_back(list_t *l, elem value) {
node_t *newNode = node_alloc(value);
newNode -> next = NULL;
if (l->head == NULL){
l->head = newNode;
}
else{
node_t *current = l->head;
while (current->next != NULL){
current = current->next;
}
current->next = newNode;
}
}
elem list_remove_from_front(list_t *l) {
node_t *current;
elem value = (elem) -1;
if (l->head == NULL){
return value;
}
else{
current = l->head;
value = current ->value;
l->head = l->head->next;
node_free(current);
}
return value;
}
elem list_remove_at_index(list_t *l, int index) {
int i = 0;
elem value = (elem) -1;
bool found = false;
if (l->head == NULL){
return value;
}
else if (index == 0){
return list_remove_from_front(l);
}
else if (index > 0){
node_t *current = l->head;
node_t *prev = current;
i=0;
while(current != NULL && !found){
if (i == index){
found = true;
}
else{
prev = current;
current = current -> next;
i++;
}
}
if (found){
value = current->value;
prev->next = current->next;
node_free(current);
}
}
return value;
}
elem list_remove_from_back(list_t *l) {
elem value = (elem) -1;
node_t *current = l->head;
if (l->head != NULL){
if (current -> next == NULL){
l->head = NULL;
value = current->value;
node_free(current);
}
else{
while (current->next->next != NULL){
current = current -> next;
}
value = current -> next -> value;
node_free(current->next->next);
current -> next = NULL;
}
}
return value;
}
bool list_is_in(list_t *l, elem value) {
node_t *current = l->head;
while (current != NULL){
if(value == current->value){
return true;
}
current = current->next;
}
return false;
}
elem list_get_from_front(list_t *l){
node_t *current;
elem value = (elem) -1;
if (l->head == NULL){
return value;
}
else{
current = l->head;
value = current ->value;
}
return value;
}
elem list_get_elem_at(list_t *l, int index) {
int i;
elem value = (elem) -1;
if(l->head == NULL){
return value;
}
else if (index ==0){
return list_get_from_front(l);
}
else if (index > 0){
node_t *current = l->head;
i=0;
while (current != NULL){
if (i == index){
return (current->value);
}
else{
current = current->next;
i++;
}
}
}
return value;
}
int list_get_index_of(list_t *l, elem value) {
int i = 0;
node_t *current = l->head;
if (l->head == NULL){
return -1;
}
while(current != NULL){
if (value == current->value){
return i;
}
current = current->next;
i++;
}
return -1;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.