language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, i, sum = 0, count = 0;
for(i = 0;; i++)
{
if(n==sum)
break;
}
cout<<count<<endl;
}
|
C
|
// sorter.h
// Module to spawn a separate thread to sort random arrays
// (permutations) on a background thread. It provides access to
// contents of the current (potentially partially sorted) array,
// and to the count of the total number of arrays sorted.
#ifndef _SORTER_H_
#define _SORTER_H_
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Globally defined variables
pthread_mutex_t mutex;
int numSortedArr;
int arrLength;
int* globArray;
/******************************************************************/
//Array sorting-related functions
// Create array
void createArray(int length);
// Utilizes swap and randomizer functions to create permutation of array
void permutation(int *arr, int arrSize);
// For each element in array, choose a random number and then swap
int randomizer(int arrSize);
// Simple swap helper function
void swap(int* arr, int i, int j);
// Sorts array
void bubbleSort(int* arr, int arrSize);
// Begin/end the background thread which sorts random permutations.
void* sorter_startSorting(void* arg);
// Prints array 10 elements per line
void printArr(int *arr, int arrLength, int space);
#endif
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int isPerfectSquare(int num)
{
int i;
int res=0;
for (i = 1; i <= 100; i++)
{
if (i * i == num)
{
res = i;
return res;
}
}
return res;
}
int main(void)
{
int i, sum = 0, min = 10001;
int n, m;
scanf("%d %d", &n, &m);
for (i = n; i <= m; i++)
{
if (isPerfectSquare(i))
{
sum += i;
if (i < min)
{
min = i;
}
}
}
printf("%d\n", sum);
printf("%d", min);
return 0;
}
|
C
|
#include <stdio.h> // perror のために必要
#include <unistd.h> // execve のために必要
char *args[] = { "date", NULL };
char *envs[] = { "LC_TIME=ja_JP.UTF-8", "TZ=Cuba", NULL};
char *execpath="/bin/date";
int main(int argc, char *argv[], char *envp[]) {
execve(execpath, args, envs); // /bin/dateを上記の環境変数で実行
perror(execpath); // execveが戻ってきたらエラー!
return 1;
}
/* 実行例(日本語表示、キューバ時間で表示される)
% ./exectest2
2023年 4月 1日 土曜日 20時25分52秒 CDT
*/
|
C
|
#include<stdio.h>
#include<math.h>
void main()
{
float xA,xB,yA,yB,a;
printf("Nhap cac canh toa do A B:");
scanf("%f%f%f%f",&xA,&yA,&xB,&yB);
a=(sqrt((xB-xA)*(xB-xA)+(yB-yA)*(yB-yA)));
printf("Do dai AB:%0.2f",a);
}
|
C
|
#include<stdio.h>
#include<unistd.h>
void print_msg(char *);
int main()
{
print_msg("hello ");
print_msg("world\n");
return 0;
}
void print_msg(char *m)
{
int i;
for ( i = 0 ; i < 5; i++ )
{
printf("%s", m);
fflush(stdout);
sleep(1);
}
}
|
C
|
#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <GLFW/glfw3.h> // GLFW helper library
#include <stdio.h>
int main() {
// start GL context and O/S window using the GLFW helper library
if (!glfwInit()) {
fprintf(stderr, "ERROR: could not start GLFW3\n");
return 1;
}
GLFWwindow* window = glfwCreateWindow(640, 480, "Simple Shader", NULL, NULL);
if (!window) {
fprintf(stderr, "ERROR: could not open window with GLFW3\n");
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
// start GLEW extension handler
glewExperimental = GL_TRUE;
glewInit();
// get version info
const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string
const GLubyte* version = glGetString(GL_VERSION); // version as a string
printf("Renderer: %s\n", renderer);
printf("OpenGL version supported %s\n", version);
// tell GL to only draw onto a pixel if the shape is closer to the viewer
glEnable(GL_DEPTH_TEST); // enable depth-testing
glDepthFunc(GL_LESS); // depth-testing interprets a smaller value as "closer"
/* OTHER STUFF GOES HERE NEXT */
float points[] = {
0.0f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f
};
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), points, GL_STATIC_DRAW);
GLuint vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
const char* vertex_shader =
"#version 140\n"
"in vec3 vp;"
"void main() {"
" gl_Position = vec4(vp, 1.0);"
"}";
const char* fragment_shader =
"#version 140\n"
"out vec4 frag_colour;"
"void main() {"
" frag_colour = vec4(0.5, 0.0, 0.5, 1.0);"
"}";
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &vertex_shader, NULL);
glCompileShader(vs);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &fragment_shader, NULL);
glCompileShader(fs);
GLuint shader_program = glCreateProgram();
glAttachShader(shader_program, fs);
glAttachShader(shader_program, vs);
glLinkProgram(shader_program);
while(!glfwWindowShouldClose(window)) {
// wipe the drawing surface clear
//
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//
glUseProgram(shader_program);
//
glBindVertexArray(vao);
//
// // draw points 0-3 from the currently bound VAO with current in-use shader
//
glDrawArrays(GL_TRIANGLES, 0, 3);
//
// // update other events like input handling
//
glfwPollEvents();
//
// // put the stuff we've been drawing onto the display
//
glfwSwapBuffers(window);
//
}
// close GL context and any other GLFW resources
glfwTerminate();
return 0;
}
|
C
|
/*
Задача 10. Направете два триъгълника с отместване.
*/
#include <stdio.h>
struct point{
int m_x;
int m_y;
};
int main(){
struct point a={3,4};
struct point b={7,10};
char rect[15][15];
int k = 0;
for(int i=0;i<15;i++){
printf("\n");
for(int j=0;j<15;j++){
if ((i>= a.m_x && i<=b.m_x) && (j> a.m_y+(i-a.m_x) && j<b.m_y)) {
printf("@");
}
else if ((i>= a.m_x&& i<=b.m_x) && (j> (7+a.m_y)+(i-a.m_x) && j<(7+b.m_y))) {
printf("@");
}
else {
printf("-");
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include "lab2.h"
int main() {
// Array of 10 doubles
const unsigned int size = 10;
double array[size];
// Array for copying original array for reciprocals
double arrayCopy[size];
printf("Creating an array of %i doubles.\n", size);
arrayInput(array, size);
printf("\nPrinting our array using pointer arithmetic.\n");
printArrayPtrArithmetic(array, size);
printf("\nCopying our array into a new array.\n");
for (int i = 0; i < size; i++) {
arrayCopy[i] = array[i];
}
printf("\nTaking the reciprocal of our copied array.\n");
reciprocal(arrayCopy, size);
printf("\nPrinting our original array.\n");
printArrayPtrArithmetic(array, size);
printf("\nPrinting our reciprocal array.\n");
printArrayPtrArithmeticReciprocal(arrayCopy, size);
}
|
C
|
/*
* view.c
* The view module use OpenGL to show the present status of a game.
* It uses the VBO indexing to powering the render. Only one mesh is generated
* during the module initialisation and used to draw all circles in the display
* function.
*
* created by Lana Abi Rached and Vianney Rousset.
*
* version: 2.1
* last modification: 2014-04-11
* responsable: R. Boulic
*/
#include <stdio.h>
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#include "view.h"
#include "players.h" ///
#include "config.h"
#include "mesh.h"
#include "V2D.h"
// main_window: the windows where the game is drawn.
static int main_window;
// mainGame: this link the module to the present game state. /// "state" ?
static game_t* mainGame = NULL;
// circle: this mesh is generated once with the mesh module and will be used to
// draw all circles.
static mesh_t* circle = NULL;
// display is the glut display function that draw the game in the main window.
static void display(void);
// reshape is the glut reshape function that correct the aspect ratio.
static void reshape(int w, int h);
// refresh will be used as the glut idle function to any for any animations.
static void refresh(void);
void view_Init(int* argc, char** argv)
{
// init glut
glutInit(argc, argv);
// get screen size (width and height)
int screenW = glutGet(GLUT_SCREEN_WIDTH),
screenH = glutGet(GLUT_SCREEN_HEIGHT);
// open main window
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition((screenW - WINDOW_WIDTH) / 2,
(screenH - WINDOW_HEIGHT) / 2);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
main_window = glutCreateWindow(WINDOW_TITLE);
// set glut functions
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutIdleFunc(NULL);
// enable anti-aliasing (+set blending, +set anti-aliasing quality)
glEnable(GL_MULTISAMPLE);
glEnable(GL_BLEND);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// create the circle mesh
circle = mesh_createCircle(DISK_RESOLUTION);
}
void view_redraw(void)
{
printf("INFO: redraw game.\n");
refresh();
}
/// setters ///
void view_setGame(game_t* game)
{
mainGame = game;
}
/// getters ///
game_t* view_getGame(void)
{
return mainGame;
}
int view_getMainWindow()
{
return main_window;
}
void refresh(void)
{
glutPostRedisplay();
}
void display(void)
{
// iterator variables
unsigned char i = 0;
unsigned short j = 0;
// reset modelview and clear
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.95, 0.95, 0.9, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// draw disks
if (mainGame != NULL)
for (i = 0; i < MAX_PLAYER; i++)
{
player_t* player = game_getPlayer(mainGame, i);
const unsigned short ndisks = player_getNDisks(player);
for (j = 0; j < ndisks; j++) {
disk_t* disk = player_getDisk(player, j);
v2d_t position = disk_getPos(disk);
float radius = disk_getValue(disk) * MIN_RADIUS * 0.9;
// transform origin
glLoadIdentity();
glTranslatef(position.x, position.y, 0);
glScaled(radius, radius, radius);
// draw circle
if (circle != NULL)
{
glColor3f(0.2*i, 0.5/(i+1), 0.2);
mesh_draw(circle, MESH_FILLED);
glColor3f(0.5*i, 0.8/(i+1), 0.5);
mesh_draw(circle, MESH_BORDERED);
} else
error("The circle mesh isn't created.");
}
}
// unbind buffers
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// swap buffers
glutSwapBuffers();
}
void reshape(int w, int h) ////
{
float xy_aspect;
xy_aspect = (float)w / (float)h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (xy_aspect > 1)
glViewport(0, 0, h, h);
else
glViewport(0, 0, w, w);
glOrtho(0, MAX_MODELE, 0, MAX_MODELE, 0, 100);
glutPostRedisplay();
}
|
C
|
#include "bytecode_program.h"
bool instructions_equal(Instruction a, Instruction b, void* constants){
if(a.type!=b.type){
return false;
}
switch(a.type){
case b_end:
case b_discard:
case b_enter_scope:
case b_leave_scope:
case b_null:
case b_return:
case b_binary:
case b_prefix:
case b_new_scope:
case b_table_set:
case b_table_set_keep:
case b_get:
case b_table_get:
return true;// these instructions doesn't use the argument
case b_set:
return a.bool_argument==b.bool_argument;
case b_load_float:
return a.float_argument==b.float_argument;
case b_load_int:
return a.int_argument==b.int_argument;
case b_load_string:
return a.uint_argument==b.uint_argument||strcmp((char*)constants+a.uint_argument, (char*)constants+b.uint_argument)==0;
case b_function_1:
return a.function_argument.is_variadic==b.function_argument.is_variadic
&& a.function_argument.arguments_count==b.function_argument.arguments_count;
case b_swap:
return a.swap_argument.left==b.swap_argument.left
&& a.swap_argument.right==b.swap_argument.right;
default:
return a.uint_argument==b.uint_argument;
}
}
char* stringify_constants(const BytecodeProgram* program){
char* result=malloc(program->constants_size);
for(int i=0; i<program->constants_size-1; i++){
if(program->constants[i]=='\0'){
result[i]='\n';
} else {
result[i]=program->constants[i];
}
}
result[program->constants_size]='\0';
return result;
}
void print_instruction(Instruction instruction, void* constants){
#define STRINGIFY_BOOL(b) ((b) ? "true" : "false")
switch(instruction.type){
case b_end:
case b_discard:
case b_enter_scope:
case b_leave_scope:
case b_null:
case b_return:
case b_binary:
case b_prefix:
case b_new_scope:
case b_table_set:
case b_table_set_keep:
case b_get:
case b_table_get:
printf("%s", INSTRUCTION_NAMES[instruction.type]);// these instructions doesn't use the argument
break;
case b_set:
printf("%s %s", INSTRUCTION_NAMES[instruction.type], STRINGIFY_BOOL(instruction.bool_argument));
break;
case b_load_float:
printf("%s %f", INSTRUCTION_NAMES[instruction.type], instruction.float_argument);
break;
case b_load_int:
printf("%s %i", INSTRUCTION_NAMES[instruction.type], instruction.int_argument);
break;
case b_load_string:
printf("%s %u \"%s\"", INSTRUCTION_NAMES[instruction.type], instruction.uint_argument, ((char*)constants)+instruction.uint_argument);
break;
case b_function_1:
printf("%s %s %u", INSTRUCTION_NAMES[instruction.type], STRINGIFY_BOOL(instruction.function_argument.is_variadic), instruction.function_argument.arguments_count);
break;
case b_swap:
printf("%s %u %u", INSTRUCTION_NAMES[instruction.type], instruction.swap_argument.left, instruction.swap_argument.right);
break;
default:
printf("%s %u", INSTRUCTION_NAMES[instruction.type], instruction.uint_argument);
}
#undef STRINGIFY_BOOL
}
void print_bytecode_program(const BytecodeProgram* program){
int pointer=0;
while(program->code[pointer].type!=b_end){
printf("%i: ", pointer);
print_instruction(program->code[pointer], program->constants);
/*int comment=program->information[pointer].comment;
if(comment>=0 && comment<program->constants_size){
printf(" # %s\n", &program->constants[comment]);
} else {*/
printf("\n");
//}
pointer++;
}
printf("CONSTANTS:");
for(int i=0; i<program->constants_size-1;){
printf("\n%i: ", i);
i+=printf("%s", program->constants+i)+1;// printf returns number of characters printed, we also skip the '\0' character
}
printf("\n");
if(program->sub_programs_count>0){
for(int i=0; i<program->sub_programs_count; i++){
printf("SUBPROGRAM[%i]\n", i);
print_bytecode_program(program->sub_programs[i]);
}
}
}
Assumption assumption_copy(Executor* E, Assumption source){
Assumption copied={source.type};
if(source.assumption_type==a_constant){
copied.constant=copy(E, source.constant);
} else {
copied.type=source.type;
}
return copied;
}
BytecodeProgram* bytecode_program_copy(Executor* E, const BytecodeProgram* source, bool copy_assumptions) {
BytecodeProgram* copy=malloc(sizeof(BytecodeProgram));
int c=0;
for(; source->code[c].type!=b_end; c++);
c++;
copy->code=copy_memory(source->code, c*sizeof(Instruction));
copy->information=copy_memory(source->information, c*sizeof(InstructionInformation));
copy->constants=copy_memory(source->constants, source->constants_size);
copy->constants_size=source->constants_size;
copy->upvalues=copy_memory(source->upvalues, source->upvalues_count*sizeof(unsigned));
copy->upvalues_count=source->upvalues_count;
copy->expected_arguments=source->expected_arguments;
copy->calls_count=0;
copy->statistics.initialized=false;
if(copy_assumptions && source->assumptions!=NULL){
uint assumptions_count=copy->upvalues_count+copy->expected_arguments;
copy->assumptions=malloc(sizeof(Assumption)*assumptions_count);
for(int i=0; i<assumptions_count; i++){
copy->assumptions[i]=assumption_copy(E, source->assumptions[i]);
}
} else {
copy->assumptions=NULL;
}
copy->sub_programs_count=source->sub_programs_count;
copy->sub_programs=malloc(sizeof(BytecodeProgram)*copy->sub_programs_count);
for(int i=0; i<source->sub_programs_count; i++){
copy->sub_programs[i]=bytecode_program_copy(E, source->sub_programs[i], true);
}
bytecode_program_init(E, copy);
return copy;
}
BytecodeProgram* bytecode_program_copy_override(Executor* E, const BytecodeProgram* source){
return bytecode_program_copy(E, source, true);
}
#define INITIAL_LABELS_COUNT 4
void bytecode_program_list_labels(BytecodeProgram* program){
uint* labels=malloc(INITIAL_LABELS_COUNT*sizeof(uint));
int labels_count=INITIAL_LABELS_COUNT;
int pointer=0;
while(program->code[pointer].type!=b_end){
if(program->code[pointer].type==b_label){
while(program->code[pointer].uint_argument>=labels_count){
labels_count*=2;
labels=realloc(labels, labels_count*sizeof(uint));
}
labels[program->code[pointer].uint_argument]=pointer;
}
pointer++;
}
program->labels=labels;
program->labels_count=labels_count;
}
#undef INITIAL_LABELS_COUNT
void bytecode_program_count_stack_depth(BytecodeProgram* program){
int max_stack_depth=0;
int current_stack_depth=0;
for(Instruction* i=program->code; i->type!=b_end; i++){
current_stack_depth+=pushes_to_stack(*i);
if(current_stack_depth>max_stack_depth){
max_stack_depth=current_stack_depth;
}
current_stack_depth-=gets_from_stack(*i);
}
program->stack_depth=max_stack_depth;
}
void bytecode_program_foreach_children(Executor* E, BytecodeProgram* program,
ForeachChildrenCallback callback, void* data) {
for(int i=0; i<program->sub_programs_count; i++){
Object wrapped=wrap_heap_object((HeapObject*)program->sub_programs[i]);
callback(E, &wrapped, data);
}
for(int i=0; i<vector_count(&program->variants); i++){
Object wrapped=wrap_heap_object((HeapObject*)pointers_vector_get(&program->variants, i));
callback(E, &wrapped, data);
}
}
void bytecode_program_free(BytecodeProgram* program) {
free(program->source_file_name);
free(program->labels);
free(program->code);
free(program->information);
free(program->constants);
free(program->upvalues);
vector_deinit(&program->variants);
free(program);
}
void bytecode_program_init(Executor* E, BytecodeProgram* program){
bytecode_program_list_labels(program);
bytecode_program_count_stack_depth(program);
program->calls_count=0;
program->statistics.initialized=false;
program->assumptions=NULL;
vector_init(&program->variants, sizeof(BytecodeProgram), 4);
managed_pointer_init(E, (ManagedPointer*)&program->mp, (ManagedPointerFreeFunction)bytecode_program_free);
program->mp.foreach_children=(ManagedPointerForeachChildrenFunction)bytecode_program_foreach_children;
program->mp.copy=(ManagedPointerCopyFunction)bytecode_program_copy_override;
for(int i=0; i<program->sub_programs_count; i++){
program->sub_programs[i]->source_file_name=strdup(program->source_file_name);
bytecode_program_init(E, program->sub_programs[i]);
heap_object_reference((HeapObject*)program->sub_programs[i]);
}
program->compiled=NULL;
}
|
C
|
#include "Instructions.h"
#include "Functions.h"
void check_instructions(char **char_array_A, char **char_array_B, char **char_array_C, char **char_array_D, int line, char *key[])
{
char ch = 'a';
int arr_size = 0, plus_size, i, j;
int reg[17];
int *arr = malloc(arr_size * sizeof(int));
int** pointer = &arr;
COORD coord;
coord.X = 0;
coord.Y = 0;
for (i = 0; i < 17; i++) reg[i] = 0;
reg[15] = *char_array_A;
for (i = 0; i < line; i++)
{
if (ch != 'f') ch = 'a';
while (ch != '\r' && ch != 'f' && ch != 'q') ch = _getch();
if (ch == 'q') break;
if (ch != 'f' || i == line) print_char_arrays(char_array_A, char_array_B, char_array_C, char_array_D, line, i + 1, coord);
for (j = 0; j < 20; j++)
if (strcmp(key[j], char_array_B[i]) == 0)
switch (j)
{
case 0:
arr = DS(char_array_A, char_array_C, char_array_D, arr, i, &arr_size, &plus_size);
reg[14] = *pointer;
j = 20; break;
case 1:
arr = DC(char_array_A, char_array_C, char_array_D, arr, i, &arr_size, &plus_size);
reg[14] = *pointer;
j = 20; break;
case 2:
L(reg, char_array_A, char_array_C, char_array_D, i, *pointer);
j = 22; break;
case 3:
LA(reg, char_array_A, char_array_C, char_array_D, i, *pointer);
j = 22; break;
case 4:
LR(reg, char_array_C, char_array_D, i);
j = 21; break;
case 5:
dzialanie_arytmetyczne(char_array_A, char_array_C, char_array_D, i, j = 1, reg, arr, *pointer); //A
j = 22; break;
case 6:
dzialanie_arytmetyczne_R(char_array_C, char_array_D, i, j = 1, reg, arr); //AR
j = 21; break;
case 7:
dzialanie_arytmetyczne(char_array_A, char_array_C, char_array_D, i, j = 2, reg, arr, *pointer); //S
j = 22; break;
case 8:
dzialanie_arytmetyczne_R(char_array_C, char_array_D, i, j = 2, reg, arr); //SR
j = 21; break;
case 9:
dzialanie_arytmetyczne(char_array_A, char_array_C, char_array_D, i, j = 3, reg, arr, *pointer); //M
j = 22; break;
case 10:
dzialanie_arytmetyczne_R(char_array_C, char_array_D, i, j = 3, reg, arr); //MR
j = 21; break;
case 11:
dzialanie_arytmetyczne(char_array_A, char_array_C, char_array_D, i, j = 4, reg, arr, *pointer); //D
j = 22; break;
case 12:
dzialanie_arytmetyczne_R(char_array_C, char_array_D, i, j = 4, reg, arr); //DR
j = 21; break;
case 13:
C(reg, char_array_A, char_array_C, char_array_D, i, arr, *pointer);
j = 22; break;
case 14:
CR(reg, char_array_C, char_array_D, i);
j = 21; break;
case 15:
i = J( char_array_A, char_array_C, i);
j = 30; break;
case 16:
i = JP(reg, char_array_A, char_array_C, i);
j = 30; break;
case 17:
i = JZ(reg, char_array_A, char_array_C, i);
j = 30; break;
case 18:
i = JN(reg, char_array_A, char_array_C, i);
j = 30; break;
case 19:
ST(reg, char_array_A, char_array_C, char_array_D, i, *pointer);
j = 22; break;
}
if (ch != 'f' || i == line)
{
print_registers_array(char_array_C, char_array_D, coord, reg, i, j);
print_values_array(char_array_A, char_array_D, coord, arr_size, arr, i, j, *pointer, reg);
}
if (i == line - 1)
{
print_values_array(char_array_A, char_array_D, coord, arr_size, arr, i, j, *pointer, reg);
print_registers_array(char_array_C, char_array_D, coord, reg, i, j);
}
}
coord.X = 1;
coord.Y = 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
_getch();
*pointer = NULL;
free(arr);
}
|
C
|
/**
* @file test_longto.c
* @author Egorov N.V. <egorov@rti-mints.ru>
* @date Tue Aug 24 16:00:00 2010
*
* @brief Тестирование функций преоброзования строк
*
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <config.h>
#ifndef USE_VSPRINTF
#define asstring(x) #x
static inline char* longtoHEX(long obj, char* out, size_t bl);
static inline char* longtohex(long obj, char* out, size_t bl);
char* longtooct(long obj, char* out, size_t bl);
char* longtodec(long obj, char *out, size_t bl);
int main(int argc, char** argv)
{
char buff[200];
if (strcmp(longtoHEX(0xFFE, buff, 200), asstring(FFE)))
{
puts(buff);
return -1;
}
if (strcmp(longtohex(0xad14e, buff, 200), "ad14e"))
{
puts("longtohex failure");
puts(buff);
return -1;
}
if(strcmp(longtooct(0674, buff, 200), "674"))
{
puts("longtooct failure");
puts(buff);
return -1;
}
if(!longtodec(1256789, buff, 200))
{
puts("Failure longtodec");
return -1;
}
if(strcmp(longtodec(1256789, buff, 200), "1256789"))
{
puts("longtodec failure");
puts(buff);
return -1;
}
return 0;
}
#else
int main (int argc, char** argv)
{
return 0;
}
#endif
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct vmm_stat_type {int index; int nelems; char* desc; } ;
/* Variables and functions */
int EINVAL ;
int /*<<< orphan*/ snprintf (char*,int,char*,char*,int) ;
int /*<<< orphan*/ strlcpy (char*,char*,int) ;
int vst_num_types ;
struct vmm_stat_type** vsttab ;
int
vmm_stat_desc_copy(int index, char *buf, int bufsize)
{
int i;
struct vmm_stat_type *vst;
for (i = 0; i < vst_num_types; i++) {
vst = vsttab[i];
if (index >= vst->index && index < vst->index + vst->nelems) {
if (vst->nelems > 1) {
snprintf(buf, bufsize, "%s[%d]",
vst->desc, index - vst->index);
} else {
strlcpy(buf, vst->desc, bufsize);
}
return (0); /* found it */
}
}
return (EINVAL);
}
|
C
|
#include <stdio.h>
int sprintf(char * str, const char * fmt, ...)
{
int ret;
va_list ap;
va_start (ap, fmt);
ret = vsprintf(str, fmt, ap);
va_end (ap);
*(unsigned char*)(str + ret) = '\0'; /* terminate the string */
return ret;
}
|
C
|
/*
*
* Producer-Consumer Lab
*
* Copyright (c) 2019 Peter A. Dinda
*
*/
#ifndef _RING_H
#define _RING_H
#include <stdint.h>
// For performance, this should be a multiple of the cache line size
#define CACHE_ALIGN_SIZE 64
#define CACHE_ALIGN __attribute__((aligned(CACHE_ALIGN_SIZE)))
// structure definition is here to make it possible to optimize via inlining
// push/pull, etc
typedef volatile int lock_t;
typedef struct _ring {
uint64_t size; // number of elements on queue
uint64_t head; // where next push goes
uint64_t tail; // where last pull came from
int can_interrupt;
//
// WRITE ME!
//
// synchronization variables (e.g. locks) would go here
// note that you should think carefully about their alignment
int oldstate;
// the ring consists of size elements
// each element is a void pointer and thus we
// can enqueue anything by reference
// the "[0]" here is a C idiom that allows us to
// have trailing data
void* elements[0] CACHE_ALIGN;
} CACHE_ALIGN ring_t;
ring_t* ring_create(uint32_t size, // how many things can be in the ring at once
uint32_t producer_limit, // limit, if any, on number of producers (0=none)
int producer_interrupts, // true if producers can run in interrupt handlers
uint32_t consumer_limit, // limit, if any, on the number of consumers (0=none)
int consumer_interrupts); // true if consumers can run in interrupt handlers
void ring_destroy(ring_t* ring);
// Producer Side
// push data into the ring, blocking until possible
// returns 0 on success, negative on error
int ring_push(ring_t* ring, void* data);
// push data into the ring, if possible
// returns 0 on success, negative on error, 1 if the ring is full
int ring_try_push(ring_t* ring, void* data);
void lock(volatile lock_t *lock);
void unlock(volatile lock_t *lock);
// Consumer Side
// pull data from the ring
// returns 0 on success, negative on error
// data is returned via reference (2nd parameter)
int ring_pull(ring_t* ring, void** data);
// pull data from the ring, if possible
// returns 0 on success, negative on error, 1 if the ring is empty
// data is returned via reference (2nd parameter)
int ring_try_pull(ring_t* ring, void** data);
#endif
|
C
|
#include "vmem_parser.h"
#include <string.h>
void free_mem_rgn(struct mem_rgn* mr){
free(mr->p_name);
if(mr->n_remaining > 0)free(mr->remaining_addr);
}
/*
* if which_rgn's int* res param is not NULL, it is set
* to one of three possible values:
* STACK, HEAP, or other
* if (res > HEAP) or (res >= 2), the value of res refers to
* additional region[res-2]
*/
const char* which_rgn(struct mem_rgn rgn, void* addr, int* res){
if(addr >= rgn.stack.start && addr <= rgn.stack.end){
if(res)*res = STACK;
return "stack";
}
if(addr >= rgn.heap.start && addr <= rgn.heap.end){
if(res)*res = HEAP;
return "heap";
}
for(int i = 0; i < rgn.n_remaining; ++i){
if(addr >= rgn.remaining_addr[i].start && addr <= rgn.remaining_addr[i].end){
if(res)*res = 2 + i;
return "unmarked";
}
}
if(res)*res = -1;
return NULL;
}
char* get_proc_name(pid_t pid){
char path[30];
sprintf(path, "/proc/%i/cmdline", pid);
char* line = NULL;
FILE* fp = fopen(path, "r");
if(!fp)return line;
size_t sz = 0;
getline(&line, &sz, fp);
fclose(fp);
return line;
}
struct mem_rgn get_vmem_locations(pid_t pid, bool unmarked_additional){
char* tmp = NULL;
char map_path[30];
sprintf(map_path, "/proc/%i/maps", pid);
struct mem_rgn vmem;
vmem.pid = pid;
vmem.p_name = get_proc_name(pid);
vmem.heap.end = vmem.heap.start = vmem.stack.end = vmem.stack.start = NULL;
vmem.n_remaining = 0;
FILE* fp = fopen(map_path, "r");
if(!fp)return vmem;
int rem_alloc_sz = 0;
void* p_end = NULL;
size_t sz = 0;
while(getline(&tmp, &sz, fp) != EOF){
char* start_add = tmp;
char* end_add = strchr(tmp, '-');
char* space = strchr(end_add, ' ');
*(space++) = '\0';
*(end_add++) = '\0';
void* l_start_add = (void*)strtoul(start_add, NULL, 16);
void* l_end_add = (void*)strtoul(end_add, NULL, 16);
char* sl;
// TODO: make the criteria for unmarked_additional more strict/correct, too many regions are being returned
// TODO: look into the p_end != l_start_add precaution, it is only correct to use as a criterion in some circumstances
// in others, it will ignore important values, for example, variables in the python interpreter
// the commented line below is much less strict for unmarked_additional
/*if(unmarked_additional || (p_end != l_start_add && ((sl = strchr(space, '/')) && strstr(sl, vmem.p_name)))){*/
if(p_end != l_start_add && (unmarked_additional || (((sl = strchr(space, '/')) && strstr(sl, vmem.p_name))))){
if(vmem.n_remaining == rem_alloc_sz){
++rem_alloc_sz;
if(vmem.n_remaining == 0)vmem.remaining_addr = malloc(sizeof(struct m_addr_pair)*rem_alloc_sz);
else{
struct m_addr_pair* tmp_realloc = malloc(sizeof(struct m_addr_pair)*rem_alloc_sz);
memcpy(tmp_realloc, vmem.remaining_addr, sizeof(struct m_addr_pair)*(rem_alloc_sz-1));
free(vmem.remaining_addr);
vmem.remaining_addr = tmp_realloc;
}
}
vmem.remaining_addr[vmem.n_remaining].start = l_start_add;
vmem.remaining_addr[vmem.n_remaining++].end = l_end_add;
}
char* desc = strchr(space, '[');
if(desc){
*strchr(desc, ']') = '\0';
++desc;
if(strcmp(desc, "heap") == 0){
vmem.heap.start = l_start_add;
vmem.heap.end = l_end_add;
}
if(strcmp(desc, "stack") == 0){
vmem.stack.start = l_start_add;
vmem.stack.end = l_end_add;
}
}
p_end = l_end_add;
}
// free memory allocated by getline
free(tmp);
fclose(fp);
return vmem;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int list[7]={38,27,43,3,9,82,10};
int partition(int list[], int left, int right) {
int pivot, temp;
int low, high;
low=left;
high=right+1;
pivot=list[left];
do {
do{
low++;
}while(low<=right && list[low]<pivot);
do{
high--;
}while(high>=left && list[high]>pivot);
if(low<high) {
temp=list[low];
list[low]=list[high];
list[high]=temp;
}
}while(low<high);
temp=list[left];
list[left]=list[high];
list[high]=temp;
return high;
}
void quickSort(int list[], int left, int right) {
if(left<right) {
int q=partition(list,left,right);
quickSort(list,left,q-1);
quickSort(list,q+1,right);
}
}
int main() {
int i=0;
quickSort(list,0,6);
for(i=0;i<7;i++) {
printf("%d\t",list[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Datos.h"
#include "ArrayList.h"
int main()
{
ArrayList* lista = al_newArrayList();
ArrayList* auxList = al_newArrayList();
eProducto* producto;
eProducto* auxProducto;
FILE* datos = generarBinario("datos.dat");
FILE* temporal = generarBinario("temporal.dat");
int opcion;
int indice;
int indiceReal;
char rta = 's';
while (rta == 's')
{
opcion = menu ("\n1 - Alta\n2 - Baja\n3 -Baja Fisica\n4 - Modificar \n5 - Listar\n6 - Salir\n\nOpcion: ","\nNo ha ingresado un valor permitido. Reingrese\n\nOpcion: ",1,6);
system ("cls");
switch(opcion)
{
case 1:
producto = alta_producto();
al_add(lista,producto);
guardarEnBinario(lista,"datos.dat");
system ("Pause");
break;
case 2:
system ("Pause");
break;
case 3:
system ("Pause");
break;
case 4:
indice = buscarIndice(lista);
auxProducto=al_get(lista,indice);
printf("El producto seleccionado es: \n");
mostrarProducto(auxProducto);
printf("Desea modificarlo? <s-n>");
if (rta == 's')
{
modificarProducto (auxProducto);
}
al_add(lista->pElements+indice,auxProducto);
system ("Pause");
break;
case 5:
auxList = leerDesdeArchivo ("datos.dat");
listar(auxList);
system ("Pause");
break;
case 6:
rta = 'n';
break;
}
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bkonjuha <bkonjuha@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/23 19:54:18 by bkonjuha #+# #+# */
/* Updated: 2020/09/02 16:22:29 by bkonjuha ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/lemin.h"
t_option *init_option(void)
{
t_option *op;
if (!(op = (t_option *)malloc(sizeof(t_option))))
ft_errno("Failed to allocate memory", NULL);
op->info = 0;
op->paths = 0;
op->error = 0;
op->help = 0;
return (op);
}
t_room **init_all_rooms(int count)
{
t_room **rooms;
int i;
i = -1;
if (!(rooms = (t_room **)malloc(sizeof(t_room*) * count)))
ft_errno("Failed to allocate memory", NULL);
while (++i < count)
rooms[i] = NULL;
return (rooms);
}
t_room *init_room(int edges)
{
t_room *room;
int i;
i = -1;
if (!(room = (t_room *)malloc(sizeof(t_room))))
ft_errno("Failed to allocate memory", NULL);
if (!(room->edge = (t_edge *)malloc(sizeof(t_edge) * edges)))
ft_errno("Failed to allocate memory", NULL);
room->name = NULL;
room->path = 0;
room->visited = 0;
while (++i < edges)
{
room->edge[i].next = NULL;
room->edge[i].pair = NULL;
room->edge[i].current = 1;
}
return (room);
}
t_combinations *init_comb(void)
{
t_combinations *comb;
if (!(comb = (t_combinations *)malloc(sizeof(t_combinations))))
ft_errno("Failed to allocate memory", NULL);
comb->next = NULL;
comb->print = 0;
comb->set = NULL;
return (comb);
}
|
C
|
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h>
const int long_size = sizeof(long);
void getdata(pid_t child, long addr,
char *str, int len)
{ char *laddr;
int i, j;
union u {
long val;
char chars[long_size];
}data;
i = 0;
j = len / long_size;
laddr = str;
while(i < j) {
data.val = ptrace(PTRACE_PEEKDATA, child,
addr + i * 4, NULL);
memcpy(laddr, data.chars, long_size);
++i;
laddr += long_size;
}
j = len % long_size;
if(j != 0) {
data.val = ptrace(PTRACE_PEEKDATA, child,
addr + i * 4, NULL);
memcpy(laddr, data.chars, j);
}
str[len] = '\0';
}
void putdata(pid_t child, long addr,
char *str, int len)
{ char *laddr;
int i, j;
union u {
long val;
char chars[long_size];
}data;
i = 0;
j = len / long_size;
laddr = str;
while(i < j) {
memcpy(data.chars, laddr, long_size);
ptrace(PTRACE_POKEDATA, child,
addr + i * 4, data.val);
++i;
laddr += long_size;
}
j = len % long_size;
if(j != 0) {
memcpy(data.chars, laddr, j);
ptrace(PTRACE_POKEDATA, child,
addr + i * 4, data.val);
}
}
int main(int argc, char *argv[])
{ pid_t traced_process;
struct user_regs_struct regs, newregs;
long ins;
/* int 0x80, int3 */
char code[] = {0xcd,0x80,0xcc,0};
char backup[4];
if(argc != 2) {
printf("Usage: %s <pid to be traced>\n",
argv[0], argv[1]);
exit(1);
}
traced_process = atoi(argv[1]);
ptrace(PTRACE_ATTACH, traced_process,
NULL, NULL);
wait(NULL);
ptrace(PTRACE_GETREGS, traced_process,
NULL, ®s);
/* Copy instructions into a backup variable */
getdata(traced_process, regs.eip, backup, 3);
/* Put the breakpoint */
putdata(traced_process, regs.eip, code, 3);
/* Let the process continue and execute
the int 3 instruction */
ptrace(PTRACE_CONT, traced_process, NULL, NULL);
wait(NULL);
printf("The process stopped, putting back "
"the original instructions\n");
printf("Press <enter> to continue\n");
getchar();
putdata(traced_process, regs.eip, backup, 3);
/* Setting the eip back to the original
instruction to let the process continue */
ptrace(PTRACE_SETREGS, traced_process,
NULL, ®s);
ptrace(PTRACE_DETACH, traced_process,
NULL, NULL);
return 0;
}
|
C
|
#include "gpio.h"
#include "types.h"
#include <stdarg.h>
enum gpio_cmd {
GPIO_INPUT,
GPIO_SET,
GPIO_CLEAR,
GPIO_TOGGLE,
};
u64 SUNXI_PIO_BASE_MAPPED;
u64 SUNXI_R_PIO_BASE_MAPPED;
/**
* @deprecated Please use driver model instead
* Request a GPIO. This should be called before any of the other functions
* are used on this GPIO.
*
* Note: With driver model, the label is allocated so there is no need for
* the caller to preserve it.
*
* @param gpio GPIO number
* @param label User label for this GPIO
* @return 0 if ok, -1 on error
*/
extern int gpio_request(unsigned gpio, const char *label);
/**
* @deprecated Please use driver model instead
* Stop using the GPIO. This function should not alter pin configuration.
*
* @param gpio GPIO number
* @return 0 if ok, -1 on error
*/
extern int gpio_free(unsigned gpio);
/**
* @deprecated Please use driver model instead
* Make a GPIO an input.
*
* @param gpio GPIO number
* @return 0 if ok, -1 on error
*/
extern int gpio_direction_input(unsigned gpio);
/**
* @deprecated Please use driver model instead
* Make a GPIO an output, and set its value.
*
* @param gpio GPIO number
* @param value GPIO value (0 for low or 1 for high)
* @return 0 if ok, -1 on error
*/
extern int gpio_direction_output(unsigned gpio, int value);
/**
* @deprecated Please use driver model instead
* Get a GPIO's value. This will work whether the GPIO is an input
* or an output.
*
* @param gpio GPIO number
* @return 0 if low, 1 if high, -1 on error
*/
extern int gpio_get_value(unsigned gpio);
/**
* @deprecated Please use driver model instead
* Set an output GPIO's value. The GPIO must already be an output or
* this function may have no effect.
*
* @param gpio GPIO number
* @param value GPIO value (0 for low or 1 for high)
* @return 0 if ok, -1 on error
*/
extern int gpio_set_value(unsigned gpio, int value);
#define unlikely(x) __builtin_expect(!!(x), 0)
#define IS_ERR_VALUE(x) unlikely((x) >= (unsigned long)-4095)
extern int fast_sprintf(char *dst_buf, char *format, ...);
void (* printd_ptr)(const char* s, ...);
void print_console(char* fmt, ...){
va_list args;
char tmp[100];
va_start(args, fmt);
fast_sprintf(tmp, fmt, args);
va_end(args);
(*printd_ptr)("%s", tmp);
}
int do_gpio(enum gpio_cmd cmd, int gpio){
int value;
if ( cmd == GPIO_INPUT) {
gpio_direction_input(gpio);
value = gpio_get_value(gpio);
} else {
switch (cmd) {
case GPIO_SET:
value = 1;
break;
case GPIO_CLEAR:
value = 0;
break;
case GPIO_TOGGLE:
value = gpio_get_value(gpio);
if (!IS_ERR_VALUE(value))
value = !value;
break;
default:
break;
}
gpio_direction_output(gpio, value);
}
print_console("gpio: (gpio %i) value is ", gpio);
if (IS_ERR_VALUE(value))
print_console("unknown (ret=%d)\n", value);
else
print_console("%d\n", value);
}
|
C
|
/*************************************************************************
* *
* Copyright c 1984 The board of trustees of the Leland Stanford *
* Junior University. All rights reserved. *
* This subroutine may not be used outside of the SUPREM4 computer *
* program without the prior written consent of Stanford University. *
* *
*************************************************************************/
/* misc.c Version 5.1 */
/* Last Modification : 7/3/91 08:34:05 */
#include <math.h>
#include "global.h"
#include "constant.h"
#include "geom.h"
/************************************************************************
* *
* dist( a , b ) - this function returns the distance *
* between two points. if b is null, just return magnitude. *
* *
************************************************************************/
double dist ( a, b)
float a[MAXDIM], b[MAXDIM];
{
float tx, ty;
tx = a[0];
ty = a[1];
if (b) {
tx -= b[0];
ty -= b[1];
}
switch( mode ) {
case ONED :
return( fabs(tx) );
case TWOD :
return ( sqrt( tx*tx + ty*ty ) );
}
return(0.0);
}
/************************************************************************
* *
* vol_ele(t) - this routine returns the volume of the element *
* *
************************************************************************/
float vol_ele(t)
int t;
{
switch(mode) {
case ONED :
return( fabs( cordinate(pt_nd(vert_tri(t,0)),0) -
cordinate(pt_nd(vert_tri(t,1)),0) ) );
break;
case TWOD :
return( area_tri(
cordinate(pt_nd(vert_tri(t,0)),0),
cordinate(pt_nd(vert_tri(t,0)),1),
cordinate(pt_nd(vert_tri(t,1)),0),
cordinate(pt_nd(vert_tri(t,1)),1),
cordinate(pt_nd(vert_tri(t,2)),0),
cordinate(pt_nd(vert_tri(t,2)),1) ) );
break;
}
return(0.0);
}
/************************************************************************
* *
* area_tri(a1,a2,b1,b2,c1,c2) - this routine returns the area of *
* the triangle formed by the coordintes passed. *
* *
************************************************************************/
float area_tri(a1,a2,b1,b2,c1,c2)
float a1,a2,b1,b2,c1,c2;
{
return( (b1*(c2-a2) + c1*(a2-b2) + a1*(b2-c2) ) * 0.5 );
}
/************************************************************************
* *
* pt_in_tri(x,y,tr) - this routine determins if the pt x,y is in *
* element number tr. *
* *
************************************************************************/
pt_in_tri(c,tr)
float c[3];
int tr;
{
float tx1, tx2, tx3, ty1, ty2, ty3;
float abtol, artol, tsign;
float x = c[0];
float y = c[1];
switch( mode ) {
case ONED :
if ( (c[0] < cordinate(pt_nd(vert_tri(tr,0)),0)) !=
(c[0] <= cordinate(pt_nd(vert_tri(tr,1)),0)) )
return(TRUE);
else
return(FALSE);
break;
case TWOD :
/*get triangle coordinates*/
tx1 = cordinate( pt_nd( vert_tri(tr,0) ), 0);
ty1 = cordinate( pt_nd( vert_tri(tr,0) ), 1);
tx2 = cordinate( pt_nd( vert_tri(tr,1) ), 0);
ty2 = cordinate( pt_nd( vert_tri(tr,1) ), 1);
tx3 = cordinate( pt_nd( vert_tri(tr,2) ), 0);
ty3 = cordinate( pt_nd( vert_tri(tr,2) ), 1);
/*calculate tolerances*/
abtol = 1e-04;
artol = area_tri(tx1,ty1, tx2,ty2, tx3,ty3);
tsign = artol/fabs(artol);
artol = fabs(artol);
artol = artol * abtol;
/*begin the testing*/
if ( (tsign * area_tri( tx1,ty1, tx2,ty2, x,y )) <= -artol)
return( FALSE );
if ( (tsign * area_tri( tx2,ty2, tx3,ty3, x,y )) <= -artol)
return( FALSE );
if ( (tsign * area_tri( tx3,ty3, tx1,ty1, x,y )) <= -artol)
return( FALSE );
/*if all that failed, retun true*/
return( TRUE );
}
return(-1);
}
|
C
|
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
/*stack structure definition*/
struct stack
{
int stackPointer;
float items[];
};
/*An alias for the stack struct*/
typedef struct stack Stack; //"Stack" is an alias for the struct
/* operation: declares a pointer to a stack and allocates */
/* enough memory so that the array 'items' in the */
/* stack will have 'max_size' usable elements. */
/* preconditions: maximum amount of items that the stack will */
/* be able to fit is passed to the function. */
/* postconditions: the pointer to the stack is returned. */
Stack *newStack(int max_size);
/* operation: pushes the float passed in onto the specified */
/* stack. The stack pointer is incremented. */
/* preconditions: a pointer to a predeclared stack and a float*/
/* are passed to the function. */
/* postconditions: stack will contain the float 'item' and the*/
/* stackPointer within the stack holds the new*/
/* float item's index in the 'items' array. */
void push(Stack *theStack, const float item);
/* operation: pops and returns a float from the specified */
/* stack. The stack pointer is decremented. */
/* preconditions: a pointer to a predeclared stack from which */
/* a float will be obtained is passed in. */
/* postconditions: float obtained is returned and stack */
/* pointer will point to next item, if any. */
/* If stack was empty when 'pop' is called, */
/* a null character '\0' is returned instead. */
float pop(Stack *theStack);
/* operation: similar to the operation of the pop function */
/* but does not decrement the stack pointer. */
/* preconditions: a pointer to a predeclared stack whose top */
/* item will be returned is passed in. */
/* postconditions: float at the top of the stack (the last */
/* item pushed) is returned. If stack is */
/* empty, a null character '\0' is returned. */
float top(Stack *theStack);
/* operation: checks the specified stack's stack pointer to */
/* see if the stack is empty and returns a value */
/* indicating the state of the stack. */
/* preconditions: a pointer to a predeclared stack that needs */
/* to be checked is passed in. */
/* postconditions: 1 is returned if the stack is empty. */
/* 0 is returned if the stack is not empty. */
bool is_empty(Stack *theStack);
#endif // STACK_H_INCLUDED
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstnew.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mxiong <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/13 10:07:43 by mxiong #+# #+# */
/* Updated: 2018/03/13 12:52:56 by mxiong ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lstnew(void const *content, size_t content_size)
{
t_list *new_link;
new_link = (t_list *)malloc(sizeof(t_list));
if (new_link == NULL)
return (NULL);
if (content == NULL)
{
new_link->content = NULL;
new_link->content_size = 0;
}
else
{
new_link->content =
(t_list *)malloc(sizeof(*content) * content_size + 1);
if (new_link->content == NULL)
return (NULL);
ft_memcpy(new_link->content, content, content_size);
new_link->content_size = content_size;
new_link->next = NULL;
}
return (new_link);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000
#define TRUE 1
#define FALSE 0
void init_array(int *pinakas, int n, int a, int b);
void copy_array(int *dest, int *src, int n);
void print_array(int *pinakas, int n);
void swap(int *a, int *b);
int bubble_sort(int *pinakas, int n);
int selection_sort(int *pinakas, int n);
int insertion_sort(int *pinakas, int n);
void mergesort(int *pinakas, int start, int finish, int *cnt);
void merge(int *pinakas, int start, int finish, int *cnt);
void quicksort(int *pinakas, int start, int finish, int *cnt);
int partition(int *pinakas, int start, int finish, int *cnt);
int main()
{
int pinakas[SIZE];
int source[SIZE];
int i,j,N=20;
int cnt;
int choice;
init_array(source,N,0,1000); //arxikopoihsh enos tyxaiou pinaka 1000 stoixeiwn
do{
printf("\n\nMENU");
printf("\n------------");
printf("\n1-Bubble_sort");
printf("\n2-Selection_sort");
printf("\n3-Insertion_sort");
printf("\n4-Merge_sort");
printf("\n5-Quick_sort");
printf("\n6-End");
printf("\nEpilogi?");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("BubbleSort: ");
copy_array(pinakas, source, N);
cnt=bubble_sort(pinakas, N);
print_array(pinakas,N);
printf("\nBubbleSort: %d",cnt);
break;
case 2:
printf("SelectionSort: ");
copy_array(pinakas, source, N);
cnt=selection_sort(pinakas, N);
print_array(pinakas,N);
printf("\nSelectionSort: %d", cnt);
break;
case 3:
printf("insertion_sort:");
copy_array(pinakas,source,N);
cnt=insertion_sort(pinakas,N);
print_array(pinakas,N);
break;
case 4:
copy_array(pinakas, source, N);
cnt=0;
mergesort(pinakas, 0, N-1, &cnt);
print_array(pinakas,N);
printf("\nMergeSort: %d", cnt);
break;
case 5:
copy_array(pinakas, source, N);
cnt=0;
quicksort(pinakas, 0, N-1, &cnt);
print_array(pinakas,N);
printf("\nQuickSort: %d", cnt);
break;
case 6:
printf("End\n");
exit(0);
default:
puts("Wrong input");
}
}while((choice>1 || choice<5));
return 0;
}
void init_array(int *pinakas, int n, int a, int b)
{
int i;
srand(time(NULL));
for (i=0; i<n; i++)
pinakas[i]=a+rand()%(b-a+1);
}
void copy_array(int *dest, int *src, int n)
{
int i;
for (i=0; i<n; i++)
dest[i]=src[i];
}
void print_array(int *pinakas, int n)
{
int i;
printf("[");
for (i=0; i<n-1; i++)
printf("%2d, ",pinakas[i]);
printf("%2d]",pinakas[n-1]);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int bubble_sort(int *pinakas, int n)
{
int i,j;
int cnt=0;
for (i=0; i<n; i++)
{
for (j=n-1; j>=i+1; j--)
{
cnt++;
if (pinakas[j]<pinakas[j-1])
swap(&pinakas[j], &pinakas[j-1]);
}
}
return cnt;
}
int selection_sort(int *pinakas, int n)
{
int i,j,pos;
int cnt=0;
for (i=0; i<n; i++)
{
pos=i;
for (j=i+1; j<n; j++)
{
cnt++;
if (pinakas[j]<pinakas[pos])
pos=j;
}
swap(&pinakas[i], &pinakas[pos]);
}
return cnt;
}
int insertion_sort(int *pinakas, int n)
{
int i,j;
int cnt=0;
for (i=1; i<n; i++)
{
for (j=i; j>=1; j--)
{
cnt++;
if (pinakas[j]<pinakas[j-1])
swap(&pinakas[j], &pinakas[j-1]);
else
break;
}
}
return cnt;
}
void mergesort(int *pinakas, int start, int finish, int *cnt)
{
int middle;
if (start==finish) /* 1 stoixeio */
return;
else if (start==finish-1) /* 2 stoixeia */
{
(*cnt)++;
if (pinakas[start]>pinakas[finish])
swap(&pinakas[start], &pinakas[finish]);
}
else
{
middle=(start+finish)/2;
mergesort(pinakas,start,middle, cnt);
mergesort(pinakas,middle+1,finish, cnt);
merge(pinakas,start,finish, cnt);
}
}
void merge(int *pinakas, int start, int finish, int *cnt)
{
int C[SIZE];
int i,j,k;
int middle, n, m;
middle=(start+finish)/2;
/* 1os pinakas PIN[start..middle]=PIN[i..n] */
i=start;
n=middle;
/* 2os pinakas PIN[middle+1..finish]=PIN[j...m] */
j=middle+1;
m=finish;
/* C: sigxwneumenos pinakas */
k=0;
/* 1. Sigxwneusi twn dio pinakwn */
while (i<=n && j<=m)
{
(*cnt)++;
if (pinakas[i]<pinakas[j])
{
C[k]=pinakas[i];
k++;
i++;
}
else
{
C[k]=pinakas[j];
k++;
j++;
}
}
/* 2. Antigrafi tou pinaka pou perissevei sto telos tou sigxwneumenou pinaka */
if (i==n+1) /* Eksantlithike o 1os pinakas */
{
while (j<=m)
{
C[k]=pinakas[j];
k++;
j++;
}
}
else /* Eksantlithike o 2os pinakas */
{
while (i<=n)
{
C[k]=pinakas[i];
k++;
i++;
}
}
/* 3. Antigrafi tou C ston pinaka */
k=0;
i=start;
while (i<=finish)
{
pinakas[i]=C[k];
i++;
k++;
}
}
void quicksort(int *pinakas, int start, int finish, int *cnt)
{
int i,pos;
if (start<finish)
{
pos=partition(pinakas,start,finish, cnt);
quicksort(pinakas,start,pos-1, cnt);
quicksort(pinakas,pos+1,finish, cnt);
}
}
int partition(int *pinakas, int start, int finish, int *cnt)
{
int pivot, i, j;
pivot=pinakas[start];
i=start+1;
j=finish;
while(1)
{
(*cnt)++;
while(pinakas[i]<=pivot && i<=finish)
{
i++;
(*cnt)++;
}
while(pinakas[j]>pivot && j>=start)
{
j--;
(*cnt)++;
}
if (i<j)
swap(&pinakas[i],&pinakas[j]);
else
{
swap(&pinakas[start],&pinakas[j]);
return j;
}
}
}
|
C
|
/*该程序测试SOCKET网络通信其中的服务器
*
*
*/
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <string.h>
int main(int argc, char *argv[])
{
if(argc != 3){
printf("%s IP PORT. \n", argv[0]);
exit(-1) ;
}
// 创建客户端
int fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd < 0){
perror("socket failed");
exit(-1) ;
}
// 连接服务器
struct sockaddr_in si;
si.sin_family = AF_INET;
if(inet_aton(argv[1], &(si.sin_addr)) == 0){
printf("Invalid IP address \n");
exit(-1) ;
}
si.sin_port = htons(atoi(argv[2])); // 必须使用htons
if( connect(fd, (struct sockaddr *)(&si), sizeof(si)) < 0 ){
perror("connect failed");
exit(-1) ;
}else{
printf("服务器连接成功... \n");
}
// 不断收发数据
char msg[1024];
while(1){
printf("输入:");
fflush(stdout);
scanf(" %[^\n]", msg);
if(msg[0] == 'q')
break;
write(fd, msg, strlen(msg));
int n = read(fd, msg, sizeof(msg) - 1 );
if(n<= 0){
break;
}
msg[n] = '\0';
printf("服务器的回应为: %s \n", msg);
}
puts("关闭客户端...");
close(fd);
return 0;
}
|
C
|
/*
** password.c for in /home/levuoj/rendu/pamela/src/password
**
** Made by Jouvel Anthony
** Login <anthony.jouvel@epitech.eu>
**
** Started on Tue Nov 21 18:42:37 2017 Jouvel Anthony
** Last update Sun Nov 26 17:30:29 2017 Jouvel Anthony
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#include "password.h"
#include "utils.h"
#include "unused.h"
int create_passphrase(const char *login)
{
char *command = NULL;
char *path = NULL;
struct passwd *pass = NULL;
if (asprintf(&path, "/home/%s/.pass", login) == -1)
return (-1);
if (asprintf(&command, "head -c 4000 < /dev/urandom > %s", path) == -1)
return (-1);
if (execute_command(command) == -1)
return (-1);
free(command);
pass = getpwnam(login);
if (asprintf(&command, "chown %s:%d %s", login, pass->pw_gid, path) == -1)
return (PAM_SESSION_ERR);
if (execute_command(command) == -1)
return (PAM_SESSION_ERR);
free(command);
return (0);
}
int encrypt_passphrase(const char *password, const char *login)
{
char *command = NULL;
char *path = NULL;
struct passwd *pass = NULL;
if (asprintf(&path, "/home/%s", login) == -1)
return (-1);
if (asprintf(&command,
"echo %s |openssl aes-256-cbc -a -salt -in %s/.pass -out %s/.pass.enc -pass stdin",
password, path, path) == -1)
return (-1);
if (execute_command(command) == -1)
return (-1);
free(command);
pass = getpwnam(login);
if (asprintf(&command, "chown %s:%d %s/.pass.enc", login, pass->pw_gid, path) == -1)
return (PAM_SESSION_ERR);
if (execute_command(command) == -1)
return (PAM_SESSION_ERR);
free(command);
if (asprintf(&path, "/home/%s/.pass", login) == -1)
return (-1);
remove(path);
free(path);
return (0);
}
int decrypt_passphrase(const char *password, const char *login)
{
char *command = NULL;
char *path = NULL;
struct passwd *pass = NULL;
if (asprintf(&path, "/home/%s", login) == -1)
return (-1);
if (asprintf(&command,
"echo %s |openssl aes-256-cbc -d -a -in %s/.pass.enc -out %s/.pass -pass stdin",
password, path, path) == -1)
return (-1);
if (execute_command(command) == -1)
return (-1);
free(command);
pass = getpwnam(login);
if (asprintf(&command, "chown %s:%d %s/.pass", login, pass->pw_gid, path) == -1)
return (PAM_SESSION_ERR);
if (execute_command(command) == -1)
return (PAM_SESSION_ERR);
free(command);
free(path);
return (0);
}
PAM_EXTERN int pam_sm_chauthtok(pam_handle_t *pamh,
int flags,
int argc,
const char **argv)
{
UNUSED(flags);
UNUSED(argc);
UNUSED(argv);
const void *old_password = NULL;
const void *new_password = NULL;
const void *login = NULL;
char *path = NULL;
int ret_value;
if ((ret_value = pam_get_item(pamh, PAM_AUTHTOK, &new_password)) != PAM_SUCCESS ||
new_password == NULL)
return (ret_value);
if ((ret_value = pam_get_item(pamh, PAM_OLDAUTHTOK, &old_password)) != PAM_SUCCESS ||
old_password == NULL)
return (ret_value);
if ((ret_value = pam_get_item(pamh, PAM_USER, &login)) != PAM_SUCCESS)
return (ret_value);
printf("login = %s\n", (char*)login);
if (asprintf(&path, "/home/%s/.pass", (char *)login) == -1)
return (PAM_SESSION_ERR);
if (access(path, F_OK) == -1)
{
if (create_passphrase((char *)login) == -1)
return (PAM_AUTHTOK_ERR);
if (decrypt_passphrase(old_password, (char *)login) == -1)
return (PAM_AUTHTOK_ERR);
if (encrypt_passphrase(new_password, (char *)login) == -1)
return (PAM_AUTHTOK_ERR);
}
free(path);
return (PAM_SUCCESS);
}
|
C
|
#include <stdio.h>
#include "ww.h"
//step 1 declare sprites
#include "player_one.h"
#include "player_two.h"
#include "ball.h"
//adding this to allow location of player 2 and ball location
int screen_width = 1024;
int screen_height = 576;
int y_dir = -5;
int x_dir = -5;
int main( int argc, char * argv[] ) {
if(ww_window_create(argc, argv, "Pixarray", 1024, 576)) {
printf("Closing..\n");
return 1;
}
//step 2 declare sprites
init_player_one();
init_player_two();
init_ball();
//mathing the paddle location
player_two->pad_x = (screen_width - player_two->width);
//offset to get location of ball
ball->pad_y = (screen_height / 2) - (ball->height / 2);
ball->pad_x = (screen_width / 2) - (ball->width / 2);
while(!ww_window_received_quit_event()) {
//adding movement to paddles
if (keystate.w == 1 && player_one->pad_y > 0) {
player_one->pad_y = player_one->pad_y - 4;
}
if (keystate.s == 1 && player_one->pad_y < screen_height - player_one->height) {
player_one->pad_y = player_one->pad_y + 4;
}
if (keystate.up == 1 && player_two->pad_y > 0){
player_two->pad_y = player_two->pad_y - 4;
}
if (keystate.dn == 1 && player_two->pad_y < screen_height - player_two->height) {
player_two->pad_y = player_two->pad_y + 4;
}
//ball movement
ball->pad_y = ball->pad_y + y_dir;
ball->pad_x = ball->pad_x + x_dir;
//keep ball on screen
if (ball->pad_y > (screen_height - ball->height) || ball->pad_y <= 0) {
y_dir = y_dir * -1;
}
//**paddle bounce**
// ball breaks player1's right plane
// top of ball is higher than bottom of paddle and top of ball is lower than p1 top
if (ball->pad_x <= player_one->pad_x + player_one->width) {
if (ball->pad_y <= player_one->pad_y + player_one->height && !(ball->pad_y < player_one->pad_y)) {
x_dir = x_dir * -1;
}
}
// ^^ also interesting
if (ball->pad_x >= player_two->pad_x - player_two->width) {
if (ball->pad_y <= player_two->pad_y + player_two->height && !(ball->pad_y < player_two->pad_y)) {
x_dir = x_dir * -1;
}
}
//respawn ball
if (ball->pad_x < 0 || ball->pad_x > screen_width) {
ball->pad_x = (screen_width/2) - (ball->width/2);
ball->pad_y = (screen_height/2) - (ball->height/2);
x_dir = x_dir * -1;
}
//portal pong
//if (player_one->pad_y > screen_height) {
//player_one = 0;
//step 3 add sprites to game
ww_draw_sprite (player_one);
ww_draw_sprite (player_two);
ww_draw_sprite (ball);
ww_window_update_events();
ww_window_update_buffer();
}
ww_window_destroy();
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int n,i,j,a[100],mini,max;
scanf("%d",&n);
for(j=0;j<n;j++)
{
for(i=0;i<5;i++)
{
scanf("%d ",&a[i]);
}
mini=a[0];
for(i=0;i<5;i++)
{
if(mini>a[i])
mini=a[i];
}
max=a[0];
for(i=0;i<5;i++)
{
if(max<a[i])
max=a[i];
}
printf("%d %d\n",max,mini);
}
return 0;
}
|
C
|
/* $Id$ */
#ifndef HOOK_H
#define HOOK_H
#ifndef COMMON_CORE_H
# error You should include "common_core.h" first.
#endif
//#include <stdlib.h>
extern SB_DECLARE_DATA const char *current_hooking_module;
extern SB_DECLARE_DATA int debug_module_hooks;
// meta module exportϴ api hook 屸.
// member HOOK_LINK(...) .
#define HOOK_STRUCT(members) \
static struct { members } _hooks;
// api hook
#define HOOK_LINK(name) \
hook_link_array_t *link_##name;
typedef struct {
/** The amount of memory allocated for each element of the array */
int elt_size;
/** The number of active elements in the array */
int nelts;
/** The number of elements allocated in the array */
int nalloc;
/** The elements in the array */
void *elts;
} hook_link_array_t;
// name space SB Ư DECLARE_HOOK
#define SB_DECLARE_HOOK(ret,name,args) \
DECLARE_HOOK(sb,SB,ret,name,args)
/**
* Declare a hook function
* @param ns namespace
* @param link macro namespace
* @param ret The return type of the hook
* @param name The hook's name (as a literal)
* @param args The arguments the hook function takes, in brackets.
*/
#define DECLARE_HOOK(ns,link,ret,name,args) \
typedef ret ns##_HOOK_##name##_t args; \
link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf, \
const char * const *aszPre, \
const char * const *aszSucc, int nOrder); \
link##_DECLARE(ret) ns##_run_##name args; \
typedef struct ns##_LINK_##name##_t \
{ \
ns##_HOOK_##name##_t *pFunc; \
const char *szName; \
const char * const *aszPredecessors; \
const char * const *aszSuccessors; \
int nOrder; \
} ns##_LINK_##name##_t;
/* 1. api function type typedef Ѵ.
* 2. ns_hook_*() Ѵ. (module metamodule api Ͻ )
* 3. ns_run_*() Ѵ. (meta module api )
* 4. hook_link_array_t array element type typedefѴ.
**/
// name space SB Ư IMPLEMENT_HOOK_RUN_FIRST
#define SB_IMPLEMENT_HOOK_RUN_FIRST(ret,name,args_decl,args_use,decline) \
IMPLEMENT_HOOK_RUN_FIRST(sb,SB,ret,name,args_decl,args_use,decline)
#define SB_IMPLEMENT_HOOK_RUN_ALL(ret,name,args_decl,args_use,ok,decline) \
IMPLEMENT_HOOK_RUN_ALL(sb,SB,ret,name,args_decl,args_use,ok,decline)
#define SB_IMPLEMENT_HOOK_RUN_VOID_ALL(name,args_decl,args_use) \
IMPLEMENT_HOOK_RUN_VOID_ALL(sb,SB,name,args_decl,args_use)
// run function returns return value of hooked function
/*#define SB_IMPLEMENT_HOOK_RUN_ONCE(ret,name,args_decl,args_use) \
IMPLEMENT_HOOK_RUN_ONCE(sb,SB,ret,name,args_decl,args_use)*/
/**
* Implement a hook that runs until the first function that returns
* something other than decline. If all functions return decline, the
* hook runner returns decline. The implementation is called
* ns_run_<i>name</i>.
*
* @param ns the namespace
* @param link the namespace of macro
* @param ret The return type of the hook (and the hook runner)
* @param name The name of the hook
* @param args_decl The declaration of the arguments for the hook, for example
* "(int x,void *y)"
* @param args_use The arguments for the hook as used in a call, for example
* "(x,y)"
* @param decline The "decline" return value
* @return decline or an error.
*/
#define IMPLEMENT_HOOK_RUN_FIRST(ns,link,ret,name,args_decl,args_use,decline) \
IMPLEMENT_HOOK_BASE(ns,link,name) \
link##_DECLARE(ret) ns##_run_##name args_decl \
{ \
ns##_LINK_##name##_t *pHook; \
int n; \
ret rv; \
\
if(!_hooks.link_##name){ \
warn("No function hooked"); \
return decline; \
} \
\
pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \
for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \
{ \
rv=pHook[n].pFunc args_use; \
\
if(rv != decline) \
return rv; \
} \
warn("No function run(all function hooked returned decline)"); \
return decline; \
}
#define IMPLEMENT_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \
IMPLEMENT_HOOK_BASE(ns,link,name) \
link##_DECLARE(ret) ns##_run_##name args_decl \
{ \
ns##_LINK_##name##_t *pHook; \
int n; \
ret rv; \
\
if(!_hooks.link_##name) {\
warn("No function hooked"); \
return ok; \
} \
\
pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \
for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \
{ \
rv=pHook[n].pFunc args_use; \
\
if(rv != ok && rv != decline) \
return rv; \
} \
return ok; \
}
#define IMPLEMENT_HOOK_RUN_VOID_ALL(ns,link,name,args_decl,args_use) \
IMPLEMENT_HOOK_BASE(ns,link,name) \
link##_DECLARE(void) ns##_run_##name args_decl \
{ \
ns##_LINK_##name##_t *pHook; \
int n; \
\
if(!_hooks.link_##name) {\
warn("No function hooked"); \
return ; \
} \
\
pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \
for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \
{ \
pHook[n].pFunc args_use; \
\
} \
return ; \
}
#if 0
#define IMPLEMENT_HOOK_RUN_ONCE(sb,SB,ret,name,args_decl,args_use) \
IMPLEMENT_HOOK_BASE_ONCE(ns,link,name) \
link##_DECLARE(ret) ns##_run_##name args_decl \
{ \
ns##_LINK_##name##_t *pHook; \
int n; \
ret rv; \
\
if(!_hooks.link_##name) \
return ; \
\
pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \
for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \
{ \
rv=pHook[n].pFunc args_use; \
\
} \
return rv; \
}
#endif
// TODO: gotta implement hook_sort_register() and sort_hooks().
// see srclib/apr-util/include/apr_hooks.h and
// srclib/apr-util/hooks/apr_hooks.c of apache 2.0.xx.
#define IMPLEMENT_HOOK_BASE(ns,link,name) \
link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf,const char * const *aszPre, \
const char * const *aszSucc,int nOrder) \
{ \
ns##_LINK_##name##_t *pHook; \
if(!_hooks.link_##name) \
{ \
_hooks.link_##name=make_hook_link_array(sizeof(ns##_LINK_##name##_t)); \
hook_sort_register(#name,&_hooks.link_##name); \
} \
pHook=get_last_arrayptr(_hooks.link_##name); \
pHook->pFunc=pf; \
pHook->aszPredecessors=aszPre; \
pHook->aszSuccessors=aszSucc; \
pHook->nOrder=nOrder; \
pHook->szName=current_hooking_module; \
if(debug_module_hooks) \
show_hook(#name,aszPre,aszSucc); \
}
#define HOOK_REALLY_FIRST 0
#define HOOK_FIRST 10
#define HOOK_MIDDLE 20
#define HOOK_LAST 30
#define HOOK_REALLY_LAST 40
SB_DECLARE(hook_link_array_t*) make_hook_link_array(size_t size);
SB_DECLARE(void*) get_last_arrayptr(hook_link_array_t* hook_link_array);
SB_DECLARE(void) show_hook(const char *name, const char * const *aszPre, const char * const *aszSucc);
SB_DECLARE(void) sb_sort_hook();
SB_DECLARE(void) hook_sort_register(const char *szHookName,
hook_link_array_t **aHooks);
#endif // _HOOK_H_
|
C
|
/*
This is a very simple c compiler written by Prof. Jenq Kuen Lee,
Department of Computer Science, National Tsing-Hua Univ., Taiwan,
Fall 1995.
This is used in compiler class.
This file contains Symbol Table Handling.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "symbol_table.h"
extern FILE *f_asm;
int cur_counter = 0;
int cur_scope = 1;
int cur_offset = 0;
char *copys(char *s) {
char *ret = malloc(sizeof(char) * strlen(s));
strcpy(ret, s);
return ret;
}
void init_symbol_table() {
memset(&table[0], 0, sizeof(struct symbol_entry)*MAX_TABLE_SIZE);
}
char *install_symbol(char *s)
{
if (cur_counter >= MAX_TABLE_SIZE) {
fprintf(stderr, "Symbol Table Full");
}
else {
fprintf(f_asm, "# ---- Installing symbol: %s on $fp+(%d)\n", s, cur_offset);
table[cur_counter].scope = cur_scope;
table[cur_counter].name = copys(s);
table[cur_counter].offset = cur_offset;
cur_offset -= 4;
fprintf(f_asm, "addi\t$sp,\t$sp,\t-4\n");
cur_counter++;
}
return(s);
}
// To return an integer as an index of the symbol table
int look_up_symbol(char *s) {
int i;
// for (i=0; i<cur_counter; i++) {
// fprintf(f_asm, "# ---[$fp+(%d)] is %s\n", table[i].offset, table[i].name);
// }
if (cur_counter == 0) return (-1);
for (i = cur_counter - 1; i >= 0; i--) {
if (!strcmp(s,table[i].name)) return i;
}
return (-1);
}
// Pop up symbols of the given scope from the symbol table upon the
// exit of a given scope.
void pop_up_symbol(int scope) {
int i;
if (cur_counter == 0) return;
for (i = cur_counter-1; i >= 0; i--) {
if (table[i].scope != scope) break;
}
if (i < 0) cur_counter = 0;
cur_counter = i + 1;
}
void push_symbol_to_stack(char *s) {
fprintf(f_asm, "lwi\t$r0,\t[$fp+(%d)]\n", get_offset(s));
fprintf(f_asm, "swi\t$r0,\t[$sp]\n");
cur_offset -= 4;
fprintf(f_asm, "addi $sp, $sp, -4\n");
}
void push_int_to_stack(int i) {
fprintf(f_asm, "movi\t$r0,\t%d\n", i);
fprintf(f_asm, "swi\t$r0,\t[$sp]\n");
cur_offset -= 4;
fprintf(f_asm, "addi\t$sp,\t$sp,\t-4\n");
}
void stack_pop_word() {
fprintf(f_asm, "# ---- stack poping\n");
cur_offset += 4;
fprintf(f_asm, "addi\t$sp,\t$sp,\t4\n");
}
void assign_symbol_to_top(char *s) {
fprintf(f_asm, "# ---- Assigning symbol: \"%s\" to the content of stack top\n", s);
fprintf(f_asm, "lwi\t$r0,\t[$sp+4]\n");
fprintf(f_asm, "swi\t$r0,\t[$fp+(%d)]\n", get_offset(s));
}
int get_offset(char *s) {
return table[look_up_symbol(s)].offset;
}
void set_if_not_zero(char *reg) {
fprintf(f_asm, "# ---- Set %s if not zero\n", reg);
fprintf(f_asm, "slti\t%s,\t%s,\t1\n", reg, reg);
fprintf(f_asm, "zeb\t%s,\t%s\n", reg, reg);
fprintf(f_asm, "slti\t%s,\t%s,\t1\n", reg, reg);
}
void set_if_zero(char *reg) {
fprintf(f_asm, "# ---- Set %s if zero (negation)\n", reg);
fprintf(f_asm, "slti\t%s,\t%s,\t1\n", reg, reg);
fprintf(f_asm, "zeb\t%s,\t%s\n", reg, reg);
}
// // Set up parameter scope and offset
// void set_scope_and_offset_of_param(char *s)
// {
// int i,j,index;
// int total_args;
// index = look_up_symbol(s);
// if (index<0) err("Error in function header");
// else {
// table[index].type = T_FUNCTION;
// total_args = cur_counter -index -1;
// table[index].total_args=total_args;
// for (j=total_args, i=cur_counter-1;i>index; i--,j--)
// {
// table[i].scope= cur_scope;
// table[i].offset= j;
// table[i].mode = ARGUMENT_MODE;
// }
// }
// }
// // Set up local var offset
// void set_local_vars(char *functor) {
// int i,j,index,index1;
// int total_locals;
// index = look_up_symbol(functor);
// index1 = index + table[index].total_args;
// total_locals= cur_counter -index1 -1;
// if (total_locals < 0) {
// err("Error in number of local variables");
// }
// table[index].total_locals=total_locals;
// for (j = total_locals, i = cur_counter-1; j>0; i--, j--)
// {
// table[i].scope= cur_scope;
// table[i].offset= j;
// table[i].mode = LOCAL_MODE;
// }
// }
// // Set GLOBAL_MODE to global variables
// void set_global_vars(char *s)
// {
// int index;
// index = look_up_symbol(s);
// table[index].mode = GLOBAL_MODE;
// table[index].scope = 1;
// }
// /*
// To generate house-keeping work at the beginning of the function
// */
// code_gen_func_header(functor)
// char *functor;
// {
// fprintf(f_asm," ; %s\n",functor);
// fprintf(f_asm," assume cs:_TEXT\n");
// fprintf(f_asm,"_%s proc near\n",functor);
// fprintf(f_asm," push bp\n");
// fprintf(f_asm," mov bp,sp\n");
// fprintf(f_asm," ; \n");
// }
// /*
// To generate global symbol vars
// */
// code_gen_global_vars()
// {
// int i;
// fprintf(f_asm,"_BSS segment word public 'BSS'\n");
// for (i=0; i<cur_counter; i++)
// {
// if (table[i].mode == GLOBAL_MODE)
// {
// fprintf(f_asm,"_%s label word\n",table[i].name);
// fprintf(f_asm," db 2 dup (?)\n");
// }
// }
// fprintf(f_asm,"_BSS ends\n");
// }
// /*
// To geenrate house-keeping work at the end of a function
// */
// code_gen_at_end_of_function_body(functor)
// char *functor;
// {
// int i;
// fprintf(f_asm," ; \n");
// fprintf(f_asm," mov sp, bp\n");
// fprintf(f_asm," pop bp\n");
// fprintf(f_asm," ret\n");
// fprintf(f_asm,"_%s endp\n",functor);
// }
|
C
|
#include <stdio.h>
int main( ) {
typedef char Letter;
Letter ch;
ch = 'a';
printf("%c\n",ch);
Letter ch1;
ch1 = 'i';
printf("%c\n",ch1);
return 0;
}
|
C
|
/* ==========================================================================
* mem.c - Tiny heap.
* --------------------------------------------------------------------------
* Copyright (c) 2009 William Ahern
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#include <limits.h> /* CHAR_BIT */
#include <string.h> /* strlen(3) */
#include <errno.h> /* ENOMEM errno */
#include <sys/param.h> /* howmany setbit clrbit isset */
#define PAGESIZE 4096U
#define SLOTSIZE 16U
#define SLOTCOUNT (PAGESIZE/SLOTSIZE)
#define BESTFIT (1U<<0U)
struct page {
unsigned char index[howmany(SLOTCOUNT, CHAR_BIT)];
unsigned char ptr[howmany(SLOTCOUNT, CHAR_BIT)];
unsigned long flags;
unsigned char data[PAGESIZE];
}; /* struct page */
struct slot {
unsigned base, count;
}; /* struct slot */
static struct slot toslot(struct page *page, void *p) {
struct slot slot;
unsigned end;
slot.base = ((unsigned char *)p - &page->data[0]) / SLOTSIZE;
for (end = slot.base; end < SLOTCOUNT && isset(page->index, end); end++)
;;
slot.count = end - slot.base;
return slot;
} /* toslot() */
static void scan(struct page *page, struct slot *slot, unsigned *next) {
unsigned base, end;
for (base = *next; base < SLOTCOUNT && isset(page->index, base); base++)
;;
for (end = base; end < SLOTCOUNT && isclr(page->index, end); end++)
;;
*next = end;
slot->base = base;
slot->count = end - base;
} /* scan() */
void *get(struct page *page, size_t size) {
unsigned count = howmany(size, SLOTSIZE);
unsigned next = 0;
struct slot slot;
void *p;
do {
scan(page, &slot, &next);
} while (slot.count && slot.count < count);
if (!slot.count)
{ errno = ENOMEM; return 0; }
if ((page->flags & BESTFIT) && slot.count != count) {
struct slot tmp;
do {
do {
scan(page, &tmp, &next);
} while (tmp.count && tmp.count < count);
if (tmp.count >= count && tmp.count < slot.count)
slot = tmp;
} while (tmp.count);
}
p = &page->data[slot.base * SLOTSIZE];
setbit(page->ptr, slot.base);
while (count--) {
setbit(page->index, slot.base);
slot.base++;
}
return p;
} /* get() */
void put(struct page *page, void *p) {
struct slot slot = toslot(page, p);
clrbit(page->ptr, slot.base);
while (slot.count--) {
clrbit(page->index, slot.base);
slot.base++;
}
} /* put() */
void *mdup(struct page *page, const void *src, size_t len) {
char *dst = get(page, len);
return (dst)? memcpy(dst, src, len): 0;
} /* mdup() */
char *sdup(struct page *page, const char *src) {
return mdup(page, src, strlen(src) + 1);
} /* sdup() */
#if 1
#include <stddef.h> /* offsetof */
#include <stdlib.h> /* EXIT_FAILURE */
#include <stdio.h> /* fputc(3) fputs(3) fprintf(3) */
#include <string.h> /* perror(3) */
#include <ctype.h> /* isprint(3) */
#include <locale.h> /* LC_ALL setlocale(3) */
#include <sys/param.h> /* setbit clrbit */
#include <unistd.h> /* getopt(3) */
static void frepc(int ch, int count, FILE *fp)
{ while (count--) fputc(ch, fp); }
void printslot(struct page *page, struct slot *slot, FILE *fp) {
static const char hex[] = "01234567890abcdef";
unsigned p, pe, i;
p = slot->base * SLOTSIZE;
pe = p + (slot->count * SLOTSIZE);
do {
fputs(" ", fp);
for (i = 0; p + i < pe && i < 16; i++) {
fputc(hex[0x0f & (page->data[p + i] >> 4)], fp);
fputc(hex[0x0f & (page->data[p + i] >> 0)], fp);
fputc(' ', fp);
}
frepc(' ', 18 - i, fp);
for (i = 0; p + i < pe && i < 16; i++)
fputc((isprint(page->data[p + i]))? page->data[p + i] : '.', fp);
fputc('\n', fp);
p += 16;
} while (p < pe);
} /* printslot() */
void printpage(struct page *page, FILE *fp) {
struct slot slot = { 0 };
unsigned end;
while (slot.base < SLOTCOUNT) {
while (isclr(page->ptr, slot.base)) {
if (++slot.base >= SLOTCOUNT)
return;
}
for (end = slot.base + 1; end < SLOTCOUNT && isset(page->index, end) && isclr(page->ptr, end); end++)
;;
slot.count = end - slot.base;
fprintf(fp, "(%u:%u)\n", slot.base, slot.count);
printslot(page, &slot, fp);
slot.base += slot.count;
}
} /* printpage() */
int main(int argc, char *argv[]) {
static const unsigned primes[] =
{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 };
struct page page;
char word[256], *str;
int opt, fflag = 0;
unsigned i;
setlocale(LC_ALL, "C");
memset(&page, 0, sizeof page);
while (-1 != (opt = getopt(argc, argv, "bfzh"))) {
switch (opt) {
case 'b':
page.flags |= BESTFIT;
break;
case 'f':
fflag = 1;
for (i = 0; i < sizeof primes / sizeof primes[0] && i < SLOTCOUNT; i++)
setbit(page.index, primes[i]);
break;
case 'z':
printf("(struct page) : %zu\n", sizeof page);
printf("offsetof(data) : %zu\n", offsetof(struct page, data));
return 0;
default:
fprintf(stderr,
"%s [-bfzh]\n"
" -b Best fit\n"
" -f Fragment memory\n"
" -z Print data structure sizes\n"
" -h Print usage\n\n"
"Report bugs to <william@25thandClement.com>\n", argv[0]);
return (opt == 'h')? 0 : EXIT_FAILURE;
} /* switch() */
}
while (EOF != scanf("%256s", word)) {
if (!(str = sdup(&page, word)))
perror("sdup");
}
if (fflag) {
for (i = 0; i < sizeof primes / sizeof primes[0] && i < SLOTCOUNT; i++)
clrbit(page.index, primes[i]);
}
printpage(&page, stdout);
return 0;
} /* main() */
#endif /* MAIN */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "libreria.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int i,num,numMax,numMin,bandera=0,total=0;
for(i=0;i<20;i++){
do{
printf("Ingrese un numero,va el numero%d\n>",(i+1));
scanf("%d",&num);
fflush(stdin);
if(comprobar(num)==0){
printf("Error,ingrese otro numero\n");
}
}while(comprobar(num)==0);
total+=num;
if(bandera==0){
numMin=num;
numMax=num;
bandera=1;
}if(num>numMax){
numMax=num;
}if(num<numMin){
numMin=num;
}
}
printf("El numero Maximo es %d\n",numMax);
printf("El numero Minimo es %d\n",numMin);
printf("El Promedio es %d",(total/20));
return 0;
}
|
C
|
/*
When I was a kid, and wanted to count the dollar bills in my life savings, I would count out loud:
one, two, three, four, five, six, seven, eight, nine, ten;
eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty;
twenty-one, twenty-two, twenty-three, twenty-four, twenty-five...
Eventually I got tired of pronouncing each of these multi-syllable numbers. Being mathematically minded, I created a much more efficient method of counting:
one, two, three, four, five, six, seven, eight, nine, ten;
one, two, three, four, five, six, seven, eight, nine, twenty;
one, two, three, four, five, six, seven, eight, nine, thirty...
As you can see, I would only pronounce the digit(s) that have changed from the previous number. This has the added advantage that it's considerably more repetitive than the English names for numbers, and therefore requires less brainpower to compute.
Challenge
Write a program/function which takes in a positive integer and outputs/returns how I would count it: that is, the right-most non-zero digit and all trailing zeroes.
Examples
1 1
2 2
10 10
11 1
29 9
30 30
99 9
100 100
119 9
120 20
200 200
409 9
1020 20
A full list of test-cases shouldn't be necessary. This is A274206 on OEIS.
Rules
Your entry must theoretically work for all positive integers, ignoring precision and memory issues.
Input and output must be in decimal.
You may choose to take input and/or output as a number, a string, or an array of digits.
Input is guaranteed to be a positive integer. Your entry can do anything for invalid input.
This is code-golf, so the shortest code in bytes wins.
*/
#include <assert.h>
#include <stdio.h>
#define nelem(x) (sizeof(x) / sizeof(x[0]))
typedef unsigned long long uvlong;
// http://oeis.org/A274206
uvlong
efficient(uvlong n)
{
uvlong p, v;
p = 1;
for (v = 0; n > 0; n /= 10) {
v = n % 10;
if (v)
break;
p *= 10;
}
return v * p;
}
int
main(void)
{
static const uvlong tab[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 1, 2, 3, 4, 5, 6, 7, 8, 9, 60, 1, 2, 3, 4, 5, 6, 7, 8, 9, 70, 1, 2, 3, 4, 5, 6, 7, 8, 9, 80};
uvlong i;
assert(efficient(0) == 0);
assert(efficient(1) == 1);
assert(efficient(2) == 2);
assert(efficient(10) == 10);
assert(efficient(11) == 1);
assert(efficient(29) == 9);
assert(efficient(30) == 30);
assert(efficient(99) == 9);
assert(efficient(100) == 100);
assert(efficient(119) == 9);
assert(efficient(120) == 20);
assert(efficient(200) == 200);
assert(efficient(409) == 9);
assert(efficient(1020) == 20);
for (i = 0; i < nelem(tab); i++)
assert(efficient(i + 1) == tab[i]);
return 0;
}
|
C
|
#include <sys/queue.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct mydata__
{
int data;
LIST_ENTRY(mydata__) list;
} mydata;
LIST_HEAD(listhead, mydata__) head;
static mydata all_data[100];
int main(int argc, char *argv[])
{
LIST_INIT(&head);
int i;
for (i = 0; i < 10; i++) {
all_data[i].data = i;
LIST_INSERT_HEAD(&head, &all_data[i], list);
}
for (; i < 20; i++) {
all_data[i].data = i;
LIST_INSERT_AFTER(&all_data[2], &all_data[i], list);
}
mydata *p;
for (p = head.lh_first; p != NULL; p = p->list.le_next) {
printf("data = %d\n", p->data);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int num1,num2, count=0;
scanf("%d",&num2);
for(num1=2; num1<num2; num1++)
{
if(num2%num1==0)
{
count=1;
//break;
}
}
if(count==1)
{
printf("%d is not a prime number\n",num2);
}
else
{
printf("%d is a prime number\n",num2);
}
}
|
C
|
#include<stdio.h>
int main()
{
int var=1;
printf("Using postfix (var++) var = %d\n",var++);
printf("Value after increment is:%d\n\n\n",var);
var=1;
printf("Using prefix (++var) var = %d\n",++var);
printf("Value after increment is:%d\n",var);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
void *xcalloc(int, int);
void print_usage(void);
void print_version(void);
#define STR_EQ 0
#define LONG_OPT 0
#define TRUE 1
#define FALSE 0
int main(int argc, char *argv[]){
int ret, i;
int len, wb;
int name_flag = FALSE, append_flag = FALSE;
int open_flag;
int fd;
off_t off;
char *f_name;
struct option opts[] = {
{"help", no_argument, 0, 0},
{"version", no_argument, 0, 0},
{"name", required_argument, 0, 'n'},
{"append", no_argument, 0, 'a'},
{0,0,0,0}
};
if(argc == 1){
print_usage();
exit(EXIT_FAILURE);
}
while ((ret == getopt_long(argc, argv, "hvn:a", opts, &i)) != -1){
switch (ret){
case 'h':
print_usage();
exit(EXIT_SUCCESS);
case 'v':
print_version();
exit (EXIT_SUCCESS);
case 'n':
name_flag = TRUE;
f_name = optarg;
break;
case 'a':
append_flag = TRUE;
break;
default:
print_usage();
exit (EXIT_FAILURE);
}
}
if(name_flag == FALSE){
print_usage();
exit(EXIT_FAILURE);
}
if(append_flag == TRUE){
open_flag = O_RDWR | O_APPEND;
}
fd = open(f_name, open_flag);
if(fd<0){
printf("open:%s:%s\n", f_name, strerror(errno));
exit(EXIT_FAILURE);
}
printf("going to write at offset = %d\n", (int)off);
sleep (10);
len = strlen ("hello, world!");
wb = write(fd, "hello, world!", len);
if(wb != len){
printf("write:%s:%s\n", f_name, strerror(errno));
exit(EXIT_FAILURE);
}
if(close(fd) == -1){
printf("close:%s:%s\n", f_name, strerror(errno));
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
void print_usage(){
printf(" [options]\n--help:prints help\n--version:prints version\n");
}
void print_version(){
printf("0.1\n");
}
void *xalloc(int nr_elements, int size_per_element){
void *ptr = NULL;
ptr = calloc(nr_elements, size_per_element);
if(ptr == NULL){
fprintf(stderr, "xcalloc:fatal:out of memory\n");
exit(EXIT_FAILURE);
}
return (ptr);
}
|
C
|
#include "heap.h"
int findMin(Heap *h){
return h->contents[0];
}
Heap* buildHeap(int *arr){
Heap *h=(Heap*)malloc(sizeof(Heap));
h->contents=(int*)malloc(sizeof(int)*(sizeof(arr)/sizeof(arr[0])));
for(int j=sizeof(arr)/(sizeof(arr[0])*2); j>=0; j--){
minHeapify(h,h->last,j);
}
}
void HeapSort(int *arr){
Heap *h=buildHeap(arr);
int size=h->last;
for(int j=h->last; j>=0; j--){
swapArr(h->contents, 0, j);
size=size-1;
minHeapify(h, size-1 , 0);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUMBER_CHAR 1000
int main (int argc, char *argv[])
{
FILE *fp = NULL;
char get_string[MAX_NUMBER_CHAR] = "";
int c =0;
int count =0;
fp = fopen("file_text/file_source.txt", "r+"); // "r+"" : it mean read and write into file. If "r" it is only read
// printf("getc: %d\n", getc(fp));
// for (c = getc(fp); c != EOF; c = getc(fp)){
// if (c != '\n' && c != ' '){ // Increment count if this character is newline
// printf("getc %d in for: %d\n", count, getc(fp));
// count ++;
// }
// }
if (fp != NULL){
while(fgets(get_string, MAX_NUMBER_CHAR, fp) != NULL){
printf("%s", get_string);
}
fclose(fp);
}
return 0;
}
/* Sẽ viết từng module về file luôn
+ Đếm số ký tự
+ Đếm số từ
+ Đếm số dòng
+ Hàm random chọn dòng
+ Tìm một ký tự
*/
|
C
|
/* Written By: Nikesh Srivatava & Chris Anderson
* ---- Version Table ----
* |==============================================================|
* | Ver | Dates | Author | Comments |
* |=======|============|==========|==============================|
* | v0.1 | 2012.10.03 | Nikesh | Original Code |
* |==============================================================|
*/
// REGULAR EXPRESSIONS:
// Identifiers: identsym = letter (letter | digit)*
// Numbers: numbersym = (digit)+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_MAX_FILE_SIZE 1 << 10 // 1024
#define MAX_ID_LENGTH 11
#define MAX_NUMBER_DIGITS 5
#define NUMBER_RESERVED_WORDS 13
typedef enum {
nulsym = 1, identsym, numbersym, plussym, minussym,
multsym, slashsym, oddsym, eqsym, neqsym, lessym, leqsym,
gtrsym, geqsym, lparentsym, rparentsym, commasym, semicolonsym,
periodsym, becomessym, beginsym, endsym, ifsym, thensym,
whilesym, dosym, callsym, constsym, intsym, procsym, outsym,
insym , elsesym
} token_type;
char *word[] = {"const", "int", "procedure", "call", "begin", "end", "if", "then", "else", "while", "do", "in", "out"};
int wordSymbol[] = {constsym, intsym, procsym, callsym, beginsym, endsym, ifsym, thensym, elsesym, whilesym, dosym, insym, outsym};
int ssym[256];
int CURRENT_MAX_FILE_SIZE;
char *buffer;
char *errors[] = {"Variable does not start with a letter", "Number too long", "Name too long", "Invalid symbols"};
// Signifies whether debug statements are on or off.
int debugFlag = 0;
void initializeGlobals();
void debug(char* text);
void runScanner(FILE *fin, FILE *fout);
int main(int argc, char * argv[])
{
// Initialize
initializeGlobals();
// Temporary String
char *foobar;
FILE* fin; // Input
FILE* fout; // Output
// No input file. Use default.
if(argc < 2) {
fin = fopen("Scanner.in","rb");
fout = fopen("Scanner.out","wb");
}
// Just an input file. Use declared string
else if(argc == 2) {
argc--; argv++;
foobar = *argv;
fin = fopen(foobar, "rb");
argc--; argv++;
foobar = *argv;
fout = fopen(foobar,"wb");
}
// TBD: Flag indicating something special in the run.
else {
debug("Error: Parameter Format. Please try again!\n");
return 1;
}
// Check for Input File Error
if(fin == NULL) {
debug("Error: Input file did not open correctly!\n");
return 1;
}
runScanner(fin, fout);
fclose(fin);
fclose(fout);
return 0;
}
// Initialize globals
void initializeGlobals() {
// Initialize ssym with values
ssym[(int)'+'] = plussym;
ssym[(int)'-']= minussym;
ssym[(int)'*'] = multsym;
ssym[(int)'/'] = slashsym;
ssym[(int)'('] = lparentsym;
ssym[(int)')'] = rparentsym;
ssym[(int)'='] = eqsym;
ssym[(int)','] = commasym;
ssym[(int)'.'] = periodsym;
ssym[(int)'#'] = neqsym;
ssym[(int)'<'] = lessym;
ssym[(int)'>'] = gtrsym;
ssym[(int)'$'] = leqsym;
ssym[(int)'%'] = geqsym;
ssym[(int)';'] = semicolonsym;
// Initialize buffer for inputFile
CURRENT_MAX_FILE_SIZE = INITIAL_MAX_FILE_SIZE;
buffer = (char *)malloc(INITIAL_MAX_FILE_SIZE);
}
// Prints the string passed in to screen.
void debug(char* text) {
if(debugFlag) printf("%s",text);
}
// Starts the execution of the Lexical Analyzer
void runScanner(FILE *fin, FILE *fout) {
long numChars = 0, numLexemes = 0;
char c, prev;
int inComment = 0, i, stringBuilderIndex;
int *tokens;
char *lexemes[512]; // Assume we will have 512 lexemes originally
// Read in the file character by character
printf("Source Program:\n");
while ((c = fgetc(fin)) != EOF) {
printf("%c", c);
if (numChars == CURRENT_MAX_FILE_SIZE) {
buffer = (char *)realloc(buffer, 2 * CURRENT_MAX_FILE_SIZE);
CURRENT_MAX_FILE_SIZE *= 2;
if (buffer == NULL) {
printf("Error. Not enough memory to reallocate\n");
exit(1);
}
}
// If c is a whitespace character, and the previous character was a white space, don't do anything. If the previous character was not a whitespace, add a space to distinguish it from other symbols in the file.
if ( inComment && prev == '*' && c == '/') { // Turn off comment section
inComment = 0;
}
else if (inComment) { // If comments are on, ignore characters
prev = c;
continue;
}
else if ( prev == '/' && c == '*' ) { // Turn on comment section
inComment = 1;
buffer[numChars - 1] = ' ';
numChars--; // This line is so we only have one space after comments and not two
}
else if (c == ' ' || c == '\t' || c == '\n') { // Clean whitespace
if (numChars > 0 && buffer[numChars - 1] == ' ') {
;
}
else {
buffer[numChars] = ' ';
numChars++;
}
}
else { // Otherwise, just put the character in the buffer
buffer[numChars] = c;
numChars++;
}
prev = c;
}
// Put a null character that the end of the string in order to make it easy to print out
if (numChars == CURRENT_MAX_FILE_SIZE) {
buffer = (char *)realloc(buffer, 2 * CURRENT_MAX_FILE_SIZE);
CURRENT_MAX_FILE_SIZE *= 2;
if (buffer == NULL) {
printf("Error. Not enough memory to reallocate\n");
exit(1);
}
}
// Note, after this line numChars doesn't index the null-terminating character. It indexes the character prior to that, aka the last character in the string.
buffer[numChars] = '\0';
printf("\n");
//printf("\n\n%s\n\n", buffer);
//exit(0);
// Now tokenize the file and produce the lexemes
i = 0;
while (i < numChars) {
c = buffer[i];
// In this condition, you don't know whether the string is a keyword or an identifier, you'll have to figure this out
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { // If c is a letter
// Create storage for an identifier or keyword with potentially length of 11 + 1 (for \0)
lexemes[numLexemes] = (char *)malloc(MAX_ID_LENGTH + 1);
// Create the string
stringBuilderIndex = 0;
lexemes[numLexemes][stringBuilderIndex++] = c;
i++;
while (i < numChars) {
c = buffer[i];
if (c == ' ') {
break;
}
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
lexemes[numLexemes][stringBuilderIndex++] = c;
}
else {
lexemes[numLexemes][stringBuilderIndex] = '\0';
break; // This break should stop the i++ from getting executed and in the outer for-loop you'll have the current c be the symbol (potentially a special symbol) so the outer loop can deal with it.
}
if (stringBuilderIndex > MAX_ID_LENGTH) {
printf("Error: Identifier Name too long.\n");
exit(1);
}
i++;
}
// End the string with a null-terminating character
lexemes[numLexemes][stringBuilderIndex] = '\0';
numLexemes++;
}
else if (c >= '0' && c <= '9') { // If c is the start of a digit
// Create storage for an identifier or keyword with potentially length of 5 + 1 (for \0)
lexemes[numLexemes] = (char *)malloc(MAX_NUMBER_DIGITS + 1);
// Create the string
stringBuilderIndex = 0;
lexemes[numLexemes][stringBuilderIndex++] = c;
i++;
while (i < numChars) {
c = buffer[i];
if (c == ' ') {
break;
}
if (c >= '0' && c <= '9') {
lexemes[numLexemes][stringBuilderIndex++] = c;
}
else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
printf("Error: Invalid Symbols.\n");
exit(1);
}
else {
lexemes[numLexemes][stringBuilderIndex] = '\0';
break; // This break should stop the i++ from getting executed and in the outer for-loop you'll have the current c be the symbol (potentially a special symbol) so the outer loop can deal with it.
}
if (stringBuilderIndex > MAX_NUMBER_DIGITS) {
printf("Error: Number too long.\n");
exit(1);
}
i++;
}
// End the string with a null-terminating character
lexemes[numLexemes][stringBuilderIndex] = '\0';
numLexemes++;
}
else if ( c == ' ') { // If c is a space, start next token
i++;
}
else { // Otherwise, check if it a special symbol
// Special Symbols: ‘+’, ‘-‘, ‘*’, ‘/’, ‘(‘, ‘)’, ‘=’, ’,’ , ‘.’, ‘ <’, ‘>’, ‘;’ , ’:’
switch (c) {
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case ',':
case '.':
case ';':
lexemes[numLexemes] = (char *)malloc(2);
lexemes[numLexemes][0] = c;
lexemes[numLexemes][1] = '\0';
numLexemes++;
break;
case '<':
// Need to check '=' in here for the optional <= symbol and '>' for the <> symbol
lexemes[numLexemes] = (char *)malloc(3);
lexemes[numLexemes][0] = c;
i++;
if (i < numChars && ((c = buffer[i]) == '=' || c == '>')) {
lexemes[numLexemes][1] = c;
lexemes[numLexemes][2] = '\0';
}
else {
lexemes[numLexemes][1] = '\0';
numLexemes++;
continue; // Don't want to increment i again
}
numLexemes++;
break;
case '>':
case ':':
// Need to check '=' in here for the >= or := symbols
lexemes[numLexemes] = (char *)malloc(3);
lexemes[numLexemes][0] = c;
i++;
if (i < numChars && (c = buffer[i]) == '=') {
lexemes[numLexemes][1] = c;
lexemes[numLexemes][2] = '\0';
}
else {
lexemes[numLexemes][1] = '\0';
numLexemes++;
continue; // Don't want to increment i again
}
numLexemes++;
break;
default:
printf("Error: Invalid Symbols.\n");
exit(1);
break;
}
i++;
}
}
// Convert into tokens
tokens = (int *)malloc(numLexemes);
for (i = 0; i < numLexemes; i++) {
// Check to see whether it is a symbol, number or special symbol
c = lexemes[i][0];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
// Need to check whether it is a keyword or an identifier
if (!strcmp(lexemes[i], "const")) {
tokens[i] = constsym;
}
else if (!strcmp(lexemes[i], "int")) {
tokens[i] = intsym;
}
else if (!strcmp(lexemes[i], "procedure")) {
tokens[i] = procsym;
}
else if (!strcmp(lexemes[i], "call")) {
tokens[i] = callsym;
}
else if (!strcmp(lexemes[i], "begin")) {
tokens[i] = beginsym;
}
else if (!strcmp(lexemes[i], "end")) {
tokens[i] = endsym;
}
else if (!strcmp(lexemes[i], "if")) {
tokens[i] = ifsym;
}
else if (!strcmp(lexemes[i], "then")) {
tokens[i] = thensym;
}
else if (!strcmp(lexemes[i], "else")) {
tokens[i] = elsesym;
}
else if (!strcmp(lexemes[i], "while")) {
tokens[i] = whilesym;
}
else if (!strcmp(lexemes[i], "do")) {
tokens[i] = dosym;
}
else if (!strcmp(lexemes[i], "in")) {
tokens[i] = insym;
}
else if (!strcmp(lexemes[i], "out")) {
tokens[i] = outsym;
}
else {
// Otherwise it must be an identifier
tokens[i] = identsym;
}
}
else if (c >= '0' && c <= '9') {
// Need to convert into an int.
tokens[i] = numbersym;
}
else {
// Need to convert into the correct symbol code
if (c != '<' && c != ':' && c != '>') {
tokens[i] = ssym[c];
}
else {
if (lexemes[i][1] == '=') {
switch (c) {
case '<':
tokens[i] = leqsym;
break;
case '>':
tokens[i] = geqsym;
break;
case ':':
tokens[i] = becomessym;
break;
}
}
else if (c == '<' && lexemes[i][1] == '>') {
tokens[i] = neqsym;
}
}
}
}
// Print lexeme list
// printf("Number of Lexemes: %ld\n", numLexemes);
printf("\nLexeme Table:\nlexeme\ttoken type\n");
for (i = 0; i<numLexemes; i++) {
printf("%s\t\t%d\n", lexemes[i], tokens[i]);
}
// Now print out the final lexeme list
printf("\nLexeme List:\n");
for (i = 0; i < numLexemes; i++) {
printf("%d ", tokens[i]);
if (tokens[i] == identsym || tokens[i] == numbersym)
printf("%s ", lexemes[i]);
}
}
|
C
|
/*
* Tutorial 4 Jeopardy Project for SOFE 3950U / CSCI 3020U: Operating Systems
*
* Copyright (C) 2015, <GROUP MEMBERS>
* All rights reserved.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "questions.h"
question quest[NUM_QUESTIONS] = {
{
"BEATLES",
"This one was married to Yoko Ono",
"JOHN",
100,
false
},
{
"BEATLES",
"This one played bass",
"PAUL",
200,
false
},
{
"BEATLES",
"This one died in 1966",
"PAUL",
300,
false
},
{
"BEATLES",
"This one lifts 850 times its body mass",
"HERCULES",
400,
false
},
{
"INSECTS",
"This one spins a web",
"SPIDER",
100,
false
},
{
"INSECTS",
"This one is named after its mode of transportation",
"FLY",
200,
false
},
{
"INSECTS",
"This one crawls on the ground",
"WORM",
300,
false
},
{
"INSECTS",
"This one is not margerine and doesn't walk",
"BUTTERFLY",
400,
false
},
{
"BUGS",
"Number when page not found",
"404",
100,
false
},
{
"BUGS",
"I couldn't think of another one",
"404",
200,
false
},
{
"BUGS",
"I couldn't think of one more'",
"404",
300,
false
},
{
"BUGS",
"Name in Hyrule",
"ERROR",
400,
false
}
};
// Initializes the array of questions for the game
void initialize_game(void)
{
// initialize each question struct and assign it to the questions array
}
// Displays each of the remaining categories and question dollar values that have not been answered
void display_categories(void)
{
// print categories and dollar values for each unanswered question in questions array
printf("On the menu tonight:\n");
for (int i = 0; i < NUM_CATEGORIES; i++)
{
if (!quest[0+i].answered || !quest[1+i].answered || !quest[2+i].answered || !quest[3+i].answered)
{
printf ("%-5s %-5s\t", categories[i], " ");
for (int j = 0; j < 4; j++)
{
if (quest[i*4 + j].answered == false)
{
printf("%-2d \t", quest[i*4 +j].value);
}
else printf("%-2s\t", " ");
}
}
printf("\n"); //this spacing is necessary, it was getting on my nerves
}
printf("Pick your poison: ");
}
// Displays the question for the category and dollar value
void display_question(char *category, int value)
{
//printf("%s %d\n", category, value);
for (int i=0; i<NUM_QUESTIONS; i++)
{
if ( ( strcmp(quest[i].category, category) == 0 ) && (quest[i].value == value) )
{
printf("\033[1;34m\t\t%s\033[0m\n", quest[i].question);
quest[i].answered = true; //we might as well mark it here
break; //this might fix something
}
}
}
// Returns true if the answer is correct for the question for that category and dollar value
bool valid_answer(char *category, int value, char *answer)
{
int test = 0;
if (answer[strlen(answer)-1] == '\n') { answer[strlen(answer)-1] = '\0'; } //remove newline
for (int i=0; i<strlen(answer); i++)
{
if (answer[i] == ' ')
{
test++;
}
}
if (! (test == 2) ) return false;
char *p = strtok(answer, " ");
if ( !(strcmp(&p, "WHO") || strcmp(&p, "WHAT") ) ) return false;
if (p != NULL) p = strtok(NULL, " ");
if ( !strcmp(&p, "IS") ) return false;
if (p != NULL) p = strtok(NULL, " ");
strcpy(answer, p);
for (int i=0; i<NUM_QUESTIONS; i++)
{
if ( ( strcmp(quest[i].category, category) == 0 ) && (quest[i].value == value) )
{
if ( strcmp(quest[i].answer, answer) == 0 )
{
return true;
}
else { return false; }
}
}
}
// Returns true if the question has already been answered
bool already_answered(char *category, int value)
{
for (int i=0; i<NUM_QUESTIONS; i++)
{
if ( ( strcmp(quest[i].category, category) == 0 ) && (quest[i].value == value) )
{
if ( quest[i].answered == false )
{
return false;
}
else { return true; }
}
}
}
|
C
|
//
// main.c
// SIMP Assembler
//
// Created by Dan Malka on 28/12/2020.
//
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 256
#define MAXLABELSIZE 50
#define MAXSIZE 500
typedef struct LABEL
{
char LABELNAME[MAXLABELSIZE];
int labeladdress;
struct LABEL* next;
}LABEL;
LABEL* create_label(char label_name[MAXLABELSIZE], int label_address) { //creat new label
LABEL *new_label;
char word[5] = "word";
if (strcmp(word, label_name) == 0)
return NULL;
new_label = (LABEL*)malloc(sizeof(LABEL)); //allocate memmory for new label
if (new_label == NULL) {
printf("Fail to allocate memmory");
return NULL;
}
strcpy(new_label->LABELNAME, label_name); //give label name
new_label->labeladdress = label_address; //number of row
new_label->next = NULL;
return(new_label);
}
LABEL* first_read(FILE* rfile) {
char LINE[MAXSIZE]; // a place to put the line and labels
char strs[6][MAXLABELSIZE]; // a list for the registers name
int i, l, pc_counter, elements;
LABEL* label_list = NULL;
LABEL *current = NULL, *next_label;
char *ptr, *token;
const char clean[10] = " :,.-\t\n\r";
pc_counter = 0;
while (feof(rfile) == 0) { //read next line untill the end of the file
fgets(LINE, MAXSIZE, rfile);
ptr = strchr(LINE, '#'); //clear all string after '#'
if (ptr != NULL) {
*ptr = '\0';
}
token = strtok(LINE, clean); //break the string into tokens
elements = 0;
for (i = 0; i < 6; i++) { // insert the tokens into the list, if there is nothing left insert NULL
if (token == NULL) {
strs[i][0] = NULL;
token = strtok(NULL, clean);
}
else {
strcpy(strs[i], token);
token = strtok(NULL, clean);
elements++;
}
}
if (elements == 1) {//there is only label in this row
if (label_list == NULL) { //insert the first label
label_list = create_label(strs[0], pc_counter);
current = label_list;
}
else {
next_label = create_label(strs[0], pc_counter);//insert new label
current->next = next_label;
current = current->next;
}
}
else if (elements == 6) { //this is a row with label and command
if (label_list == NULL) { //insert the first label
label_list = create_label(strs[0], pc_counter);
current = label_list;
}
else {
next_label = create_label(strs[0], pc_counter);//insert new label
current->next = next_label;
current = current->next;
}
pc_counter += 2; //progress the pc counter by 2
}
else if (elements == 0)
continue;
else {
l = 0;
for (i = 0; i < 6; i++) {
if (strcmp("$imm", strs[i]) == 0) {
pc_counter += 2;
l = 1;
break;
}
else if (strcmp("word", strs[i]) == 0){ // handles .word - not counting pc
l=-1;
break;
}
}
if (l == 0)
pc_counter += 1;
}
}
return (label_list);
}
int searchforlabel(LABEL *label_list, char *label_name) // searches for label_name in label_list
{
int result = 0, found;
LABEL *current;
current = label_list;
found = 0;
while (current != NULL) // iterates until the end of the list
{
if (strcmp(current->LABELNAME, label_name) == 0) { // compares the string to the labelname in current label
found = 1;
result = current->labeladdress; // takes the label address
break;
}
else {
current = current->next; // next label
}
}
if (found == 0) // not found
return (-1);
else
return(result);
}
/* an auxilary struct to be used as a dictionary */
typedef struct { char* str; char* hexa; }dict;
dict register_to_hexa_dict [] =
{
{ "$zero", "0"},
{ "$imm", "1"},
{ "$v0", "2"},
{ "$a0", "3"},
{ "$a1", "4" },
{ "$t0", "5" },
{ "$t1", "6" },
{ "$t2", "7" },
{ "$t3", "8" },
{ "$s0", "9" },
{ "$s1", "A" },
{ "$s2", "B" },
{ "$gp", "C" },
{ "$sp", "D" },
{ "$fp", "E"},
{ "$ra", "F" },
};
/* creating a 'dictionary' for a commands to its hexa lower case only! */
dict command_to_hexa_dict [] =
{
{ "add", "00"},
{ "sub", "01"},
{ "and", "02"},
{ "or", "03"},
{ "xor", "04" },
{ "mul", "05" },
{ "sll", "06" },
{ "sra", "07" },
{ "srl", "08" },
{ "beq", "09" },
{ "bne", "0A" },
{ "blt", "0B" },
{ "bgt", "0C" },
{ "ble", "0D" },
{ "bge", "0E"},
{ "jal", "0F" },
{ "lw", "10" },
{ "sw", "11" },
{ "reti", "12" },
{ "in", "13" },
{ "out", "14" },
{ "halt", "15" },
};
char* getValue(char * str, int mode)
{
dict* pSearch;
char * selected = NULL; //
if (str != NULL)
{
switch (mode)
{
case 1: // command search
/* runing on the dictionary to get the command selected */
for(pSearch = command_to_hexa_dict; pSearch != command_to_hexa_dict + sizeof(command_to_hexa_dict) / sizeof(command_to_hexa_dict[0]); pSearch++ )
{
if(!strcmp( pSearch->str, str))
selected = (pSearch->hexa);
}
if (selected == NULL)
printf("%s is not a valid command name\n", str);
break;
case 2: // register search
/* runing on the dictionary to get the register selected */
for(pSearch = register_to_hexa_dict; pSearch != register_to_hexa_dict + sizeof(register_to_hexa_dict) / sizeof(register_to_hexa_dict[0]); pSearch++ )
{
if(!strcmp( pSearch->str, str))
selected = (pSearch->hexa);
}
if (selected == NULL)
printf("%s is not a valid register name\n", str);
break;
}
}
else
printf("expected command/register name, got NULL\n");
return selected;
}
int main(void)
{
int datamemmory[4096] = { 0 };
FILE *fp, *fw_imemin, *dmemin; // check if needed as "a" mode or "w" mode
fp = fopen("/Users/danmalka/Documents/לימודים/שנה\ ג/סמסטר\ א/מבנה\ המחשב/פרויקט/SIMP\ Assembler/fib.asm", "r");
if (fp == NULL) {
perror("Failed: ");
return 1;
}
LABEL *label_list = first_read(fp);
rewind(fp);
char buffer[MAXSIZE];
// -1 to allow room for NULL terminator for really long string
fw_imemin = fopen("/Users/danmalka/Documents/לימודים/שנה\ ג/סמסטר\ א/מבנה\ המחשב/פרויקט/SIMP\ Assembler/imemin.txt", "w");
while (fgets(buffer, MAXSIZE - 1, fp))
{
int is_imm=0, is_word=0, add_hexa=0, val_hexa=0;
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = 0; // sets the buffer to 0 after the index for end of line
char * pch;
int k = 0;
char* parameters[5]; // init the 5 commands array in the line
pch = strtok (buffer," ,\t:");
if (pch == NULL)
continue;
while (pch != NULL)
{
if (*pch == '#') // reached comments
{
pch = NULL; // to get out of loop
continue;
}
parameters[k++] = pch;//assigns the command in the 5 commands 1-line array
if (strcmp("$imm", pch) == 0)
is_imm = 1;
if (strcmp(".word", pch) == 0)
is_word = 1;
pch = strtok (NULL, " ,\t"); // gets next token
if (is_word){ // handles hexa values for .word command
if (k == 2)
if (parameters[1][1] == 'x' || parameters[1][1] == 'X')
add_hexa = 1; // address hexa flag
if (k == 3)
if (parameters[2][1] == 'x' || parameters[2][1] == 'X')
val_hexa = 1; // value hexa flag
}
}
int imm,label_line,address=0,value=0;
unsigned int imm_5;
label_line = searchforlabel(label_list, parameters[0]);
if (label_line!=-1) // check if it is a label line
continue;
imm = searchforlabel(label_list, parameters[4]); // check if there is a label in the last token
if (imm ==-1) // not label
{
if (parameters[4][1] == 'x' || parameters[4][1] == 'X') // handles immediate hexa values
imm = strtol(parameters[4], NULL, 16);
else
imm = strtol(parameters[4], NULL, 10); // decimal values
imm_5 = (unsigned int)(imm & 0xFFFFF);
}
else // gets label line from imm
{
imm_5 = (unsigned int)(imm & 0xFFFFF);
}
if (is_word){ // a word command
if (add_hexa && val_hexa){ // both value and address are hexa
address = strtol(parameters[1], NULL, 16);
value = strtol(parameters[2], NULL, 16);
}
else if (add_hexa){ // only address is hexa
address = strtol(parameters[1], NULL, 16);
value = strtol(parameters[2], NULL, 10);
}
else if (val_hexa){ // only value is hexa
value = strtol(parameters[2], NULL, 16);
address = strtol(parameters[1], NULL, 10);
}
else{ // none is hexa
address = strtol(parameters[1], NULL, 10);
value = strtol(parameters[2], NULL, 10);
}
}
char* opcode;
char *rd,*rs,*rt;
if (!is_word) { // not a .word command
opcode = getValue(parameters[0], 1); //gets opcode
rd = getValue(parameters[1], 2); // gets current rd register hexa
rs = getValue(parameters[2], 2);// gets current rs register hexa
rt = getValue(parameters[3], 2);// gets current rt register hexa
fprintf(fw_imemin,"%s%s%s%s\n",opcode,rd,rs,rt); // prints current line to file
if (is_imm) // print one more line if uses immediate
fprintf(fw_imemin,"%05X\n",imm_5);
}
else
datamemmory[address] = value;
}
dmemin = fopen("/Users/danmalka/Documents/לימודים/שנה\ ג/סמסטר\ א/מבנה\ המחשב/פרויקט/SIMP\ Assembler/dmemin.txt", "w");
for (int i = 0; i<4096; ++i) // iterates over datamemmory and prints to file its values
fprintf(dmemin,"%08X\n",datamemmory[i]);
fclose(fp);
fclose(dmemin);
fclose(fw_imemin);
return 0;
}
|
C
|
/*
* strdup.c
*/
#include <string.h>
#include <stdlib.h>
/*@
requires \exists integer i; Length_of_str_is(s,i);
assigns \nothing;
ensures \result != \null ==> \forall integer i; 0 <= i <= Length(s) ==> s[i] == \result[i];
@*/
char *strdup(const char *s)
{
int l = strlen(s) + 1;
char *d = malloc(l);
//@ assert \separated(s+(0..Length(s)), d+(0..Length(s)));
if (d)
memcpy(d, s, l);
return d;
}
|
C
|
#include <stdio.h>
/*
Binary Search
The binary search algorithm is used for searching for a value in a sorted array (either in
ascending or descending order). To see how this algorithm works, assume that we are
searching for a value in an array sorted in ascending order:
Step 1: We use two variables, that is, start and end, which indicate the start and
the end of the part of the array, in which we are searching for the value. We use
the variable middle to calculate the middle position of that part: middle =
(start+end)/2. For example, if we have a sorted array of 100 integers, start
should be initialized to 0, end to 99, so middle becomes 49.
Step 2: We compare the value we are searching for against the middle element:
(a) If they are equal, then the searched value is found and the algorithm
terminates.
(b) If it is greater, the algorithm is repeated at the part of the array starting from
the middle position and up to the end. Therefore, start becomes start =
middle+1 and the algorithm goes back to Step 1.
(c) If it is less, the algorithm is repeated at the part of the array starting from
the start position and up to the middle. Therefore, end becomes end =
middle−1 and the algorithm goes back to Step 1.
In short, the binary search algorithm divides the array into two parts. Then, the searched
value is compared with the middle element and the same process is repeated in the respective part.
*/
/*
* Write a function that searches for a number in an array of integers. If the number
is stored, the function should return the position of its first occurrence, otherwise
−1. Write a program that declares an array of integers sorted in ascending order.
The program should read an integer and use the function to display its array
position.
*/
int binary_search(int arr[], int size, int num);
int main()
{
int num, pos, arr[] = {10, 20, 30, 40, 50, 60, 70};
printf("Enter number to search: ");
scanf("%d", &num);
pos = binary_search(arr, sizeof(arr)/sizeof(int), num);
if(pos == -1)
printf("%d isn’t found\n", num);
else
printf("%d is found in position %d\n", num, pos);
return 0;
}
int binary_search(int arr[], int size, int num)
{
int start, end, middle;
start = 0;
end = size - 1;
while(start <= end)
{
middle = (start + end)/2;
if(num < arr[middle])
end = middle - 1;
else if(num > arr[middle])
start = middle + 1;
else
return middle;
}
return -1; /* If the execution reaches this point means that the number was not found. */
}
|
C
|
/*
** buffer.c for buffer in /home/yan/Documents/psu/PSU_2016_zappy
**
** Made by yan
** Login <yan.poinssot@epitech.eu>
**
** Started on Fri Jun 23 13:58:04 2017 yan
** Last update Tue Jun 27 13:55:57 2017 yan
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "zappy_buffer.h"
#include "zappy_server.h"
t_buffer *init_buffer()
{
t_buffer *back;
back = x_malloc(sizeof(t_buffer));
bzero(back->letter, BUFFER_SIZE);
back->start = 0;
back->end = 0;
return (back);
}
int execute_buffer(t_server *server, t_player *player)
{
char line[BUFFER_SIZE];
char *command;
int a;
a = 0;
while (player->buffer->start != player->buffer->end)
{
line[a] = player->buffer->letter[player->buffer->start];
a++;
player->buffer->start = (player->buffer->start == BUFFER_SIZE - 1) ?
0 : player->buffer->start + 1;
}
line[a] = '\0';
(void)server;
command = epur_str(strdup(line));
printf("Command -> [%s]\n", line);
gest_command(player, server, command);
return (0);
}
int read_buffer(t_server *server, t_player *player)
{
char buf[BUFFER_SIZE];
ssize_t size;
int pos;
if ((size = recv(player->fd, buf, BUFFER_SIZE - 1, 0)) <= 0)
return (1);
buf[size] = '\0';
pos = 0;
while (buf[pos] != '\0')
{
if (buf[pos] == '\n' || buf[pos] == '\r')
{
execute_buffer(server, player);
player->buffer->start = player->buffer->end;
}
else
{
player->buffer->letter[player->buffer->end] = buf[pos];
player->buffer->end = (player->buffer->end == BUFFER_SIZE - 1) ?
0 : player->buffer->end + 1;
}
pos++;
}
return (0);
}
|
C
|
#include<stdio.h>
int main()
{
int num1,num2,mul,i,flag=0;
printf("Enter the numbers");
scanf("%d %d",&num1,&num2);
mul=num1*num2;
for(i=1;i<mul;i++)
{
if(mul==i*i)
{
flag=1;
printf("\nYES");
break;
}
}
if(flag==0)
printf("\nNO");
return 0;
}
|
C
|
/*
* 编写一段程序。它不读取任何命令行参数或者读取一个命令行参数。
* 如果有一个参数,程序将它作为一个输入文件名。
* 如果没有参数,使用标准输入最为输入。假设输入完全由浮点数组成。
* 让程序计算并且报告输入数字的算数平均值。
*
* 将每次读入的数直接加到 sum 中,而不将其再存入一个数组中。
* */
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main (int argc, char *argv[])
{
FILE *in;
double n;
int cnt = 0;
double sum = 0.0;
// 定 in
if (argc == 1)
in = stdin;
else if (argc == 2) // 如果有一个参数,则将其作为文件名
{
if ((in = fopen (argv[1], "r")) == NULL)
{
fprintf (stderr, "Can't open file %s.\n", argv[1]);
exit (1);
}
}
else
{
fprintf (stderr, "Usage: %s [filename]\n", argv[0]);
exit (2);
}
while (fscanf (in, "%lf", &n) == 1)
{
cnt++;
sum += n;
}
if (cnt > 0)
fprintf(stdout, "The average of those numbers is %lf\n", sum / cnt);
else
fprintf (stdout, "No valid data.\n");
return 0;
}
|
C
|
#include<stdio.h>
int main(void)
{
int toes = 10;
int toes_twice;
int toes_square;
int temp ;
temp = toes;
toes_twice = toes*2;
toes_square = temp*temp;
printf("toes_twice is %d, toes_square is %d", toes_twice, toes_square);
getchar();
return 0;
}
|
C
|
double distance(int i, int j){//recibe numeros de equipos, no indices (hay que restar)
/*cout<<"locacion actual:"<<i<<endl;
cout<<"me muevo a:"<<j<<endl;
cout<<"recorro una distancia de:"<< D[i-1][j-1]<<endl;*/
return D[i-1][j-1];
}
double teamScheduleDistance(vector<vector<int>> S, int j){
double dist=0;
int actual=j;
int next=j;
for(int i=0;i<2*(n-1);i++){
int t=S[i][j-1];
//cout<<endl<<"siguiente rival: "<<t<<endl;
if(t<0){//juego de visita
next=abs(t);
}
else{//juego como local
next=j;
}
dist+=distance(actual,next);
//cout<<"distancia actual recorrida por el equipo "<<j<<": "<<dist<<endl;
actual=next;
}
next=j;
dist+=distance(actual,j);
//cout<<"distancia final recorrida por el equipo "<<j<<": "<<dist<<endl;
return dist;
}
double scheduleDistance(vector<vector<int>> S){
double dist=0;
for(int j=1;j<=n;j++){
dist+=teamScheduleDistance(S,j);
//cout<<"distancia recorrida por equipos actualmente: "<<dist<<endl;
}
return dist;
}
void atMostConflicts(vector<vector<int>> S, vector<int> & conflictedRounds, vector<int> & conlfictedTeams){
int cost=0;
for(int j=0;j<n;j++){
int consecutive=0;
int sign;
if (S[0][j]>0) sign=1;
else sign=-1;
int teamconflict=0;
vector<int> currentRows;//filas en que hay visitas/locales seguidas, en el equipo
for(int i=0;i<2*(n-1);i++){
if(S[i][j]*sign<0){
if(currentRows.size()>3){
addValues(conflictedRounds,currentRows);
teamconflict=1;
}
resetVector(currentRows);
sign=-sign;
}
currentRows.push_back(i);
//cout<<"S["<<i<<"]["<<j<<"]: "<<S[i][j]<<", c.rows: ";printVector(currentRows);
}
if(currentRows.size()>3){
addValues(conflictedRounds,currentRows);
teamconflict=1;
}
if(teamconflict==1) add(conlfictedTeams,j);
}
return;
}
void noRepeatConflicts(vector<vector<int>> S, vector<int> & conflictedRounds, vector<int> & conlfictedTeams){
for(int j=0;j<n;j++){
int actual=0;
int next=0;
int teamconflict=0;
for(int i=0;i<2*(n-1);i++){
next=S[i][j];
if(abs(actual)==abs(next)){
add(conflictedRounds,i);
add(conflictedRounds,i-1);
teamconflict=1;
}
actual=next;
}
if(teamconflict==1) add(conlfictedTeams,j);
}
return;
}
int totalConflicts(vector<vector<int>> S){
vector<int> conflictedTeams;
vector<int> conflictedRounds;
noRepeatConflicts(S,conflictedRounds,conflictedTeams);
atMostConflicts(S,conflictedRounds,conflictedTeams);
int CT=conflictedTeams.size();
int CR=conflictedRounds.size();
return CT+CR;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
void main (){
int fub[16] = {0, 1}, i, suma=0;
for(i=0; i<16; i++){
fub[i+2]=fub[i]+fub[i+1];
printf("%d, ", fub[i]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include<sys/types.h>
#include <unistd.h>
#include<sys/wait.h>
int main(){
pid_t pid,ppid, special_pid;
int status;
for( int i=0; i<2; i++){
pid=fork();
if (pid<0){
printf("error\n");
exit(-1);
}
if (pid==0){
printf("child %d with parent %d starts sleeping\n", i+1, getppid());
sleep(5);
printf("child %d with parent %d finished sleeping\n", getpid(), getppid());
exit(1);
}/*else{
if(i==2){
special_pid=pid;
}
}
}
waitpid(special_pid, &status, 0);
printf("parent %d with child %d finished sleeping\n", getpid(), pid);
return 0;
}*/
}
if(pid=waitpid(pid, &status, 0)){
printf("parent %d with child %d finished sleeping\n", getpid(), pid);
}
pid=wait(&status);
printf("parent %d with child %d finished sleeping\n", getpid(), pid);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node* insert(struct node* head, int ele, int pos)
{
struct node* newnode = (struct node*) malloc(sizeof(struct node));
newnode->data = ele;
newnode->next = NULL;
if(head==NULL)
return newnode;
else if(pos==1)
{
newnode->next = head;
return newnode;
}
struct node* temp = head;
int c=1;
while(c<pos-1 && temp->next)
{
c++;
temp = temp->next;
}
newnode->next = temp->next;
temp->next = newnode;
return head;
}
struct node* delete_node(struct node* head, int pos)
{
int num=1;
struct node* temp=head;
if(pos<1)
{
printf("Enter valid pos\n");
return head;
}
else if(pos==1)
{
head = head->next;
temp->next = NULL;
free(temp);
return head;
}
while(num<pos-1 && temp->next)
{
temp=temp->next;
num+=1;
}
if(num<pos-1)
{
printf("Enter valid pos\n");
return head;
}
struct node* temp2 = temp->next;
temp->next = temp2->next;
temp2->next = NULL;
free(temp2);
return head;
}
void display_ll(struct node* head)
{
while(head->next)
{
printf("%d->",head->data);
head= head->next;
}
printf("%d",head->data);
}
int main()
{
struct node* head = NULL;
int ch,ele,pos;
while(1)
{
printf("Enter option : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter number : ");
scanf("%d",&ele);
printf("Enter position : ");
scanf("%d",&pos);
head = insert(head,ele,pos);
break;
case 2:
printf("Enter position : ");
scanf("%d",&pos);
head = delete_node(head,pos);
break;
case 3:
display_ll(head);
break;
default:
exit(0);
}
}
return 0;
}
////
//
//cin - > scanf
//cout - > printf
//new - > malloc()
//delete - > free
//class - > struct
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int valorA, valorB;
int soma, subtrair, multiplicar, dividir, resto;
printf("Digite o primeiro valor: ");
scanf("%d", &valorA);
printf("Digite o segundo valor: ");
scanf("%d", &valorB);
soma = valorA + valorA;
subtrair = valorA - valorB;
multiplicar = valorA * valorB;
dividir = valorA / valorB;
resto = valorA % valorB;
printf("A soma foi ..... %d \n", soma);
printf("A sobtração foi ..... %d \n", subtrair);
printf("A multiplicação foi ..... %d \n", multiplicar);
printf("A divisão foi ..... %d \n", dividir);
printf("O resto foi ..... %d \n", resto);
return 0;
}
|
C
|
/*
Desarrollar una función que reciba como parámetro un caracter.
La función debe mostrar un mensaje si es una vocal o no es una vocal.
Debe funcionar tanto con mayúsculas y minúsculas.
*/
#include<stdio.h>
int getVowels(char input);
int stopExecution();
//////////////////////////////////////////////////////////////////////////////////////////
// //
// MAIN LIMPIO //
// //
//////////////////////////////////////////////////////////////////////////////////////////
int main() {
do{
system("CLS");
printf("Vocal o consonante?\n\n");
printf("Presione una letra.\n\n");
getVowels(getch());
}while(!stopExecution());
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////
// //
// FUNCIONES SECUNDARIAS //
// //
//////////////////////////////////////////////////////////////////////////////////////////
int stopExecution() {
unsigned char input;
printf("Presione C para continuar/repetir o E para terminar.\n\n");
do {
input = getch();
if(input == 'C' || input == 'c') return 0;
if(input == 'E' || input == 'e') return 1;
}while(1);
}
int getVowels(char input) {
switch(input) {
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u': printf("\tEs una vocal!\n\n"); return;
default: break;
}
if(input >= 'A' && input <= 'Z' || input >= 'a' && input <= 'z') printf("\tEs una consonante.\n\n");
else printf("\tNo es una letra!\n\n");
}
|
C
|
#include <stdio.h>
#define NUM_ELEMENTS 10
int main(void)
{
//variable declarations
int akArray[NUM_ELEMENTS]; //int iarray changed to int akArray
int i, num, sum = 0;
//code
printf("\n\n");
printf("Enter Integer Elememts For Array : \n\n");
for (i = 0; i < NUM_ELEMENTS; i++)
{
scanf("%d", &num);
akArray[i] = num;
}
for (i = 0; i < NUM_ELEMENTS; i++)
{
sum = sum + akArray[i];
}
printf("\n\n");
printf("Sum Of ALL Elements Of Array = %d\n\n", sum);
getch();
return(0);
}
|
C
|
#include<stdio.h>
typedef struct product {
char name[20];
int price;
int stock;
}PRODUCT;
int main(void) {
PRODUCT product1 = {"ﰢ",1000,10};
PRODUCT product2 = { "",4000,10 };
PRODUCT product3 = { "",3000,10 };
/*ü 迭 ü ּҰ ؾѴ.*/
PRODUCT* prd[] = { &product1,&product2,&product3 };
for (int i = 0;i < sizeof(prd) / sizeof(prd[0]);i++) {
printf("%d", sizeof(prd) / sizeof(prd[0]));
printf("%s %d %d\n", prd[i]->name,prd[i]->price,prd[i]->stock);
}
return 0;
}
|
C
|
/* File: stock2.c
By: Tep Dobry
login: tep
Date:
Mod :
*/
/* Program to compute the value of one stock in a portfolio reading
the data at run time */
main()
{ /* Variable Declarations */
int shares; /* number of shares owned */
int sell_whole; /* selling price information */
int sell_numer, sell_denomin;
float portfolio_value; /* the value of the portfolio */
/* Get the number of shares values */
printf("Enter number of shares: ");
scanf("%d", &shares);
/* Get the selling price */
printf("Enter stock selling price as whole numerator denominator: ");
scanf("%d %d %d", &sell_whole, &sell_numer, &sell_denomin);
/* Print data values */
printf("You have %d shares of stock\n",shares);
printf("selling at $%d %d/%d\n",
sell_whole,sell_numer,sell_denomin);
/* Calculate portfolio value */
portfolio_value = shares * (sell_whole +
(float) sell_numer / (float) sell_denomin);
/* Print result */
printf("\nThe value of your portfolio is $%f\n",portfolio_value);
}
|
C
|
#include<stdio.h>
void main()
{
int cost[10][10],visited[10]={0},ne=1;
int i,j,a,b,u,v,n,s,min,mincost=0;
printf("\nEnter number of vertices : ");
scanf("%d",&n);
printf("\nEnter adjacency matrix : ");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j] == 0)
cost[i][j] = 999;
}
}
printf("\nEnter source : ");
scanf("%d",&s);
visited[s] = 1;
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min && visited[i]!=0)
{
min = cost[i][j];
a=u=i;
b=v=j;
}
}
}
if(visited[u]==0 || visited[v]==0)
{
printf("\nEdge %d(%d,%d) cost is %d",ne++,a,b,min);
mincost += min;
visited[b] = 1; //b
}
cost[a][b]=cost[b][a]=999; //after adding it should not be considered again so make it 999
}
printf("\nTotal minimum cost is %d",mincost);
}
/*
0 3 1 6 0 0
3 0 5 0 3 0
1 5 0 5 6 4
6 0 5 0 0 2
0 3 6 0 0 6
0 0 4 2 6 0
cost = 13
*/
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include "Alert.h"
#include "AlertManager.h"
#include "AlertScheduler.h"
enum {ALERT_SCHEDULER_UNACTIVE=0, ALERT_SCHEDULER_ACTIVE};
void alert_func(int sData, void *data)
{
AlertScheduler *scheduler = NULL;
AlertManager *manager = NULL;
Alert *alert = NULL;
char *token = NULL;
scheduler = (AlertScheduler *)data;
manager = alertscheduler_get_alertmanager(scheduler);
alert = alertscheduler_get_alert(scheduler);
token = alert_get_token(alert);
alertscheduler_set_active(scheduler,ALERT_SCHEDULER_ACTIVE);
alertmanager_start_alert(manager, token);
}
AlertScheduler *alertscheduler_new(Alert *alert, AlertManager *handler)
{
int ret ;
unsigned long second;
AlertScheduler *alertScheduler = NULL;
alertScheduler = calloc(sizeof(AlertScheduler), 1);
if(NULL == alertScheduler) {
error("malloc AlertScheduler failed");
return NULL;
}
ret = pthread_mutex_init(&alertScheduler->aMutex,NULL);
if(ret) {
error("pthread_mutex_init failed");
goto failed;
}
alertScheduler->alert = alert ;
alertScheduler->active = ALERT_SCHEDULER_UNACTIVE;
alertScheduler->handler = handler;
#if 0
second = alert_get_time_diff(alert);
DEBUG_INFO("***************second:%ld\n",second);
alertScheduler->timer = newTimer(alert_func, 1,(void *)alertScheduler, second);
if( NULL == alertScheduler->timer) {
DEBUG_ERR("newTimer failed");
goto failed1;
}
TimerAdd(alertScheduler->timer);
#endif
return alertScheduler;
failed1:
pthread_mutex_destroy(&alertScheduler->aMutex);
failed:
if(NULL!= alert) {
alert_free(alert);
}
free(alertScheduler);
alertScheduler = NULL;
return NULL;
}
int alertscheduler_is_active(AlertScheduler * alertScheduler)
{
int ret;
ret = (alertScheduler->active == ALERT_SCHEDULER_ACTIVE);
return ret;
}
void alertscheduler_set_active(AlertScheduler * alertScheduler, int active)
{
alertScheduler->active = active;
}
Alert * alertscheduler_get_alert(AlertScheduler * alertScheduler)
{
return alertScheduler->alert;
}
AlertManager* alertscheduler_get_alertmanager(AlertScheduler * alertScheduler)
{
return alertScheduler->handler;
}
void alertscheduler_cancel(AlertScheduler * alertScheduler, AlertManager *handler)
{
Alert *alert = NULL;
char *token = NULL;
alert = alertscheduler_get_alert(alertScheduler);
token = alert_get_token(alert);
info("cancel token:%s",token);
//if(alertscheduler_is_active(alertScheduler)) {
alertscheduler_set_active(alertScheduler,ALERT_SCHEDULER_UNACTIVE);
alertmanager_stop_alert(handler,token);
//}
}
void alertscheduler_free(AlertScheduler * alertScheduler)
{
if(NULL != alertScheduler) {
#if 0
if(NULL!= alertScheduler->timer) {
//freeTimer(alertScheduler->timer);
TimerDel(alertScheduler->timer);
}
#else
Alert *alert = alertScheduler->alert;
char *token = alert_get_token(alert);
crontab_delete_alert(token);
#endif
if(NULL != alertScheduler->alert) {
alert_free(alertScheduler->alert);
}
pthread_mutex_destroy(&alertScheduler->aMutex);
free(alertScheduler);
alertScheduler = NULL;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
#if 1
//difference between scanf and sscanf
char s1[3], s2[3] = "San";
printf("Enter string: ");
scanf("%s", &s1);
printf("s1: %s\n", s1);
printf("s1 address %d\n", &s1);
sscanf(s1,"%s",s2); // s1 will get copied to s2
printf("s2: %s\n", s2);
printf("s1 address %d\n", &s1);
printf("s2 address %d\n", &s2);
#endif
#if 1
//difference between printf and fprintf
//fprintf it used to perform write operation in the file pointed to by FILE handle
//fprintf(filename, "control string ", argument);
#endif
#if 0
int arr_1[] = {1,3,4,5,6}; // integer array
char arr_c[3] = { 'A', 'B', 'C' };// 3 bytes //chracter array
char arr_2[] = "hello"; // 6 bytes -one null charcter \0
char arr_3[] = { 'A', 'B', 'C', '\0' }; // 6 bytes -one null charcter \0
printf("%s\n", arr_c);
printf("%s\n", arr_2);
printf("%s\n", arr_3);
#endif
#if 0
int b = 100;
int* ptr; //unintialzed pointer -garbage value - 'Wild pointer'
ptr = &b; // referencing a pointer // intialization of pointer
printf("%d\n", *ptr); // de-referencing
//int* ptr2 = NULL; // null pointers
//printf("%d\n", *ptr2); // de-referencing
#endif
#if 0
char c = 'x';
char* ptr3 = &c; // size of char* int* folat* is the same 32bit/64bit
printf("%c\n", *ptr3);
// upcasting
int b = 100;
char* ptr4 = &b; // No problem because it will fetch 1-byte(LSB) from given 4 bytes
printf("%d\n", *ptr4);
// downcasting
int *ptr5 = &c;
printf("%d\n", *ptr5); // gives garbage value (compiler gives segmentation fault)
#endif
#if 0
char c = 'x';
void* ptr = &c; // generic pointer (it can holds adress of any data type address)
//printf("%c\n", *ptr); // error (compiler dont know how many bytes it needs to fetch)
printf("%c\n", *(char*)ptr); // must to type cast
#endif
#if 0
char* ptr = (char*)malloc(4); // dynamical allocates memory on heap section// ptr is on stack , ptr holds heap address
free(ptr); // if dont free at the end of main ptr will get destoyed and dynamically memory will be get leaked
//after free ptr is called as dangling pointer
//*ptr = 100; // undefined behaviour
//immediately after making pointer free, we need to assign to NULL as per roll books
*ptr = NULL;
#endif
#if 0
int arr[] = {1,2,3,4,5};
int i = 10;
int j = 20;
int* ptr1 = &i;//pointer pointing to i
int* ptr2 = arr;
*ptr1 = 100;// i = 100
(*ptr1)++; // i = 101
ptr1++; // becarefull where are we advancing pointer
*ptr1 = &j; //pointer pointing to j
*ptr1 = 200; // j =200
*ptr2 = 10; // first element of array , arr[0]
*ptr2++; // pointer pointing to next element
*ptr2 = 20; //arr[1] = 20
int k = *ptr2; // k = 20
k = *ptr2++; /// k = 20 // ptr2 is dereferenced first the ptr2 increments, ptr2 = arr[2]
k = *ptr2; ///k = 3; arr[2]
k = ++*ptr2; //k = 4; ptr2 = arr[3]
k = ++(*ptr2) // k = 5 ;ptr2 = arr[3]
#endif
#if 0
//const int ci; // rule: always intialize the constant at the time of declaration, we cannot modify it later since it is read only memory
//ci = 10;
const int ci = 10; // this is correct way
int i = 10;
int j = 20;
int* ptr = &i;
*ptr = 100;
ptr = &j;
const int* ptr1; // ptr1 is pointer to an read only integer constant location
ptr1 = &i;
*ptr1 = 100; // ERROR- we cant modify value
ptr1 = &j; //valid - can change adress of the value
int const* ptr2; //ptr2 is pointer to an read only integer constant location
*ptr2 = 100;// Error
ptr2 = &i; // valid
int *const ptr3; // ptr3 is constant pointer points to integer
*ptr3 = 100; ///valid
ptr3 = &i; //not valid
int const *const ptr4 = &i; //ptr4 is constant pointer pointing to constant integer
*ptr4 = 100// ERROR
ptr4 = &j; // ERROR
#endif
while (1);
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
long long int w, h;
scanf("%lld %lld", &w, &h);
printf("%lld", ((w*w)/4 * (h*h)/4));
return 0;
}
|
C
|
# include <stdio.h>
#define MAX 40
void ler_vetor(int vetor[], int tam){
int i;
for(i=0;i<tam;i++)
scanf(" %d", &vetor[i]); /*atribui elemento pra cada posição*/
}
int compara(int element, int vetor2[], int tam){
int j;
for(j=0;j<tam;j++){
if(element==vetor2[j]) /*confere se há repetição entre os dois vetores*/
return -1;
}
return 0;
}
void imprime(int vetor[], int tam){
int i;
for(i=0;i<tam;i++)
if(vetor[i]!= -2)
printf("%d ", vetor[i]);
printf("\n");
}
int main(){
int m, n, i, A[MAX], B[MAX], num, diferenca[80];/*80 é a soma máxima dos dois vetores*/
int rest = 0;
scanf("%d %d", &m, &n);
ler_vetor(A, m);
ler_vetor(B, n);
num = m+n;
for(i=0;i<num;i++)/*preenche o vetor resposta*/
diferenca[i] = -2;
for(i=0;i<m;i++){
if(compara(A[i],B,n)==0){
diferenca[rest] = 0 + A[i];
rest +=1;
}
}
for(i=0;i<n;i++)
if(compara(B[i],A,m)==0){
diferenca[rest] = 0 + B[i];
rest +=1;
}
imprime(diferenca, num);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define FIFO1 "./fifo.1"
#define FIFO2 "./fifo.2" //Может быть доделаю с этим
void work(int gold_mine, int col_get_mine, pid_t pid_mine)
{
if(pid_mine == 0)
{
printf("Шахта найдена, в шахте золота: %d\n", gold_mine);
int col_gold;
ssize_t n;
while(gold_mine>0)
{
int readfd = open(FIFO1, O_RDONLY, 0);
printf("В шахте нет работников\n");
read(readfd, &col_gold, sizeof(col_gold));
gold_mine-=col_gold;
printf("В шахте осталось золота: %d\n", gold_mine);
close(readfd);
}
printf("Шахта рухнула\n");
exit(getpid());
}
else
{
printf("Шахтер %d готов к работе\n", getpid());
while(1)
{
int writefd = open(FIFO1, O_WRONLY, 0);
write(writefd, &col_get_mine, sizeof(int));
int time = rand()%20;
printf("Шахтер %d отнёс золото, вернётся через %d\n", getpid(), time);
sleep(time);
close(writefd);
}
}
}
int main()
{
int stat;
int col_work;
int get_col_gold;
int gold_mine;
int status_pid;
printf("Введите количество балбесов собирающее количество золота\n");
scanf("%d", &col_work);
printf("Введите количество собираемого золота\n");
scanf("%d", &get_col_gold);
printf("Введите количество золота в шахте\n");
scanf("%d", &gold_mine);
pid_t pid_work[col_work];
pid_t pid_mine;
pid_t pid_parent = getpid();
pid_mine = fork();
if(pid_mine == -1)
{
perror("Fork is down, process mine is not work\n");
exit(1);
}
for(int i = 0; i < col_work && pid_parent == getpid(); i++)
{
pid_work[i] = fork();
srand(getpid());
if(pid_work[i]==-1)
{
perror("Fork is down, process is ot work\n");
printf("Process %d is not work", i);
for(int j = 0; j<i; j++)
{
kill(pid_work[j], SIGKILL);
}
kill(pid_mine, SIGKILL);
exit(1);
}
}
mkfifo(FIFO1, 0666);
if(getpid()!=pid_parent)
{
work(gold_mine, get_col_gold, pid_mine);
}
else
{
status_pid = waitpid(pid_mine, &stat, 0);
if(pid_mine == status_pid)
{
printf("Процесс потомое %d вышел, result = %d\n", pid_mine, WEXITSTATUS(stat));
}
for(int i = 0; i < col_work; i++)
{
kill(pid_work[i], SIGKILL);
printf("Process: %d вышел\n", pid_work[i]);
}
}
system("rm fifo.1");
printf("End\n");
return 0;
}
|
C
|
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#define BUFLEN 1500
int main(int argc, char *argv[]) {
struct addrinfo hints, *ai, *ai0;
char ip_address[BUFLEN];
int i;
if (argc < 2) {
printf("Usage: %s <hostname>\n", argv[0]);
return 1;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((i = getaddrinfo(argv[1], NULL, &hints, &ai0)) != 0) {
printf("Unable to look up IP address: %s", gai_strerror(i));
}
for (ai = ai0; ai != NULL; ai = ai->ai_next) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *) ai->ai_addr;
void *addr = &(ipv4->sin_addr);
if(ai->ai_family != AF_INET) {
continue;
}
inet_ntop(AF_INET, addr, ip_address, BUFLEN);
printf("%s\n", ip_address);
}
freeaddrinfo(ai0);
return 0;
}
|
C
|
/*
Class: CPSC 346-01
Team Member 1: Matt Carter
Team Member 2: n/a
GU Username of project lead: mcarter6
Pgm Name: proj8.c
Pgm Desc: Constructing a virtual memory simulator
Usage: ./a.out BACKING_STORE.bin addresses.txt
*/
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define TLB_SIZE 16
#define PAGES 256
#define PAGE_MASK 255
#define PAGE_SIZE 256
#define OFFSET_BITS 8
#define OFFSET_MASK 255
#define MEMORY_SIZE PAGES * PAGE_SIZE
struct tlbentry
{
unsigned char page_number;
unsigned char frame_number;
int tlb_ref;
};
typedef struct tlbentry tlbentry;
int main(int argc, char *argv[]) {
int x = 0;
int pagetable[PAGES];
tlbentry tlb[TLB_SIZE];
signed char main_memory[MEMORY_SIZE];
signed char *backing;
char tempAddress[1000];
int logical_address;
int offset;
int logical_page;
int physical_page;
int physical_address;
int numPageFaults = 0;
int numPageRefs = 1;
int numTLBRefs = 1;
int numTLBHits = 0;
FILE *ifp = fopen(argv[2], "r");
while (fgets (tempAddress, 1000, ifp) != NULL) {
fscanf(ifp, "%[^\n]", tempAddress);
const char *backing_filename = argv[1];
int backing_fd = open(backing_filename, O_RDONLY);
if (backing = mmap(0, MEMORY_SIZE, PROT_READ, MAP_PRIVATE, backing_fd, 0)) {
x++;
}
//open simulation of address bus and read the first line
logical_address = atoi(tempAddress);
//extract low order 8 bits from the logical_address.
offset = logical_address & OFFSET_MASK;
//extract bits 8 through 15. This is the page number gotten by shifting right 8 bits
logical_page = (logical_address >> OFFSET_BITS) & PAGE_MASK;
//When you write the program, the physical page will increment by 1 for each copy
//from simulated backing store to main memory
physical_page = x%256;
//copy from secondary storage to simulated RAM. The address on secondary storage
//is an offset into backing, computed by multiplying the logical
//page number by 256 and adding the offset
memcpy(main_memory + physical_page * PAGE_SIZE,
backing + logical_page * PAGE_SIZE, PAGE_SIZE);
//Shift the physical page left 8 bits and or with the offset
//This has the effect of adding the offset to the physical_page
physical_address = (physical_page << OFFSET_BITS) | offset;
//extract the value stored at offset bytes within the page
signed char value = main_memory[physical_page * PAGE_SIZE + offset];
printf("Virtual address: %d Physical address: %d Value: %d\n", logical_address, physical_address, value);
}
printf("Number of Translated Addresses: %i\n", x);
printf("Page Faults: %i\n", numPageFaults);
printf("Page Fault Rate: %d\n", numPageFaults/numPageRefs);
printf("TLB Hits: %i\n", numTLBHits);
printf("TLB Hit Rate: %d\n", numTLBHits/numTLBRefs);
fclose(ifp);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "handle_ferr.h"
#include "ggets.h"
#include "ll3.h"
static void *print(int tag, void *lp)
{
char *ln = lp;
printf("%d: %s\n", tag, ln);
return lp;
}
static void dofile(char *pname, char *fname, FILE * inf)
{
ll *beg = NULL;
char *ln;
while (fggets(&ln, inf) != EOF) {
if (!(beg = new_node((int) strlen(ln), ln, beg))) {
free_all_nodes(free_all_data(beg));
fprintf(stderr, "%s: new_node() failed on %s\n", pname, fname);
exit(EXIT_FAILURE);
}
}
puts(fname);
free_all_nodes(free_all_data(map(reverse(beg), print)));
}
int main(int argc, char *argv[])
{
FILE *inf;
int i;
if (argc == 1) {
dofile(argv[0], "stdin", stdin);
if (ferror(stdin)) {
handle_ferr("stdin", argv[0]);
}
return 0;
}
for (i = 1; i < argc; i++) {
if (!(inf = fopen(argv[i], "r"))) {
handle_ferr(argv[i], argv[0]);
continue;
}
dofile(argv[0], argv[i], inf);
if (ferror(inf)) {
handle_ferr(argv[i], argv[0]);
}
if (fclose(inf)) {
handle_ferr(argv[i], argv[0]);
}
}
return 0;
}
|
C
|
#include "testLibrary.h"
int sizeOfPoint(){
return sizeof(POINT);
}
POINT newPoint(int x, int y){
POINT p;
p.x = x;
p.y = y;
return p;
}
int assertCorrectPoint(POINT aPoint, int x, int y){
return aPoint.x == x && aPoint.y == y;
}
int sizeOfLongStruct(){
return sizeof(LONG_STRUCT);
}
int passingLongStruct(LONG_STRUCT st, float b, double c, long d){
return st.b == b && st.c == c && st.d == d;
}
int passingLongStructByRef(LONG_STRUCT* st, float b, double c, long d){
return st && st->b == b && st->c == c && st->d == d;
}
int sizeOfNestedStruct(){
return sizeof(NESTED_STRUCTS);
}
int passingNestedStruct(NESTED_STRUCTS st, char a, double y){
return st.inner.a == a && st.y == y;
}
|
C
|
#ifndef NODE_H
#define NODE_H
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define NODE_I(V) { .type = INTEGER, .int_value = V, .matcher = EQUAL }
#define NODE_IM(V, M) { .type = INTEGER, .int_value = V, .matcher = M }
#define NODE_S(V) { .type = STRING, .str_value = V, .matcher = EQUAL }
#define NODE_SM(V, M) { .type = STRING, .str_value = V, .matcher = M }
enum node_type { INTEGER, STRING };
enum node_matcher { EQUAL, LESSER, LESSER_OR_EQUAL, GREATER, GREATER_OR_EQUAL, ANY };
struct node {
enum node_type type;
enum node_matcher matcher;
char *str_value;
unsigned int_value;
};
struct node make_string_node(const char *string, unsigned size);
struct node make_int_node(unsigned integer);
void destroy_node(struct node *node);
void print_node(struct node node);
bool match_node(
const struct node *pattern,
const struct node *value
);
bool match_pattern(const char *pattern, const char *value);
bool match_integer(
enum node_matcher matcher,
unsigned pattern,
unsigned value
);
bool match_string(
enum node_matcher matcher,
const char *pattern,
const char *value
);
size_t node_length(const struct node n);
#endif /* end of include guard: NODE_H */
|
C
|
#include "frame_io.h"
void save_frame(AVPicture *pFrame, int width, int height, char *name) {
FILE *pFile;
int y;
// Open file
pFile = fopen(name, "wb");
if (pFile == NULL)
return;
// Write header
fprintf(pFile, "P6\n%d %d\n255\n", width, height);
// Write pixel data
for (y = 0; y < height; y++)
fwrite((pFrame->data[0] + y * pFrame->linesize[0]), 1, (size_t) (width * 3), pFile);
// Close file
fclose(pFile);
}
void save_frame_data(AVPicture *pFrame, uint16_t width, uint16_t height, char *name) {
int y;
// Open file
FILE *pFile = fopen(name, "wb");
if (pFile == NULL)
return;
fwrite(&width, sizeof(uint16_t), 1, pFile);
fwrite(&height, sizeof(uint16_t), 1, pFile);
//fprintf(pFile, "%d%d", width, height);
for (y = 0; y < height; y++)
fwrite(pFrame->data[0] + y * pFrame->linesize[0], 1, (size_t) (width * 3), pFile);
// Close file
fclose(pFile);
}
AVFrame *read_frame_data(char *file) {
FILE *pFile;
long lSize;
uint8_t *buffer;
AVFrame *frame = av_frame_alloc();
// Open file
pFile = fopen(file, "r+");
if (pFile == NULL)
return NULL;
uint16_t width, height;
fread(&width, sizeof(uint16_t), 1, pFile);
fread(&height, sizeof(uint16_t), 1, pFile);
lSize = width * height * 3;
buffer = calloc(1, (size_t) (lSize + 1));
if (!buffer) fclose(pFile), fputs("memory alloc fails", stderr), exit(1);
if (1 != fread(buffer, (size_t) lSize, 1, pFile))
fclose(pFile), free(buffer), fputs("entire read fails", stderr), exit(1);
// Close file
fclose(pFile);
frame->width = width;
frame->height = height;
avpicture_fill((AVPicture *) frame, buffer, AV_PIX_FMT_RGB24, width, height);
return frame;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> //Funciones sleep
#include <pthread.h> //Threads
#include "hidapi.h" //USB-HID
typedef int boolean;
#define TRUE 1
#define FALSE 0
boolean en_ejecucion;
void *captura_finalizacion(void *arg){
getchar(); //Este extrae del buffer del teclado el ENTER que quedo de la seleccion del usuario
getchar(); //Este captura realmente el nuevo ENTER que el usuario presiona para terminar la ejecucion
en_ejecucion=FALSE;
return NULL;
}
//Muestra el contenido del buffer de manera "raw" (cruda). Muestra los valores leidos del dispositivo, byte por byte, en sistema decimal
void despliega_salida_cruda(unsigned char buffer[], int LONGITUD_BUFFER){
int i;
for(i = 0; i < LONGITUD_BUFFER; i++){
//Relleno para que todos los numeros muestren 3 cifras
if(buffer[i] < 100)
printf("0");
if(buffer[i] < 10)
printf("0");
//Mostramos el valor leido
printf("%d ", buffer[i]);
}
printf("\n");
}
int min_x=0, min_y=0, max_x=100, max_y=100,posX=50,posY=50;
//Muestra el contenido del buffer de manera procesada, agregando semantica a cada grupo de bytes/bits
void despliega_salida_mouse_usb(unsigned char buffer[]){
//Esto está pensado para un mouse gamer Dragunov (Fabricante: Dragon War)
printf("Botón izquierdo: %s\n", buffer[0]==1||buffer[0]==3||buffer[0]==5||buffer[0]==7||buffer[0]==9||buffer[0]==11||buffer[0]==13||buffer[0]==15||buffer[0]==17||buffer[0]==21||buffer[0]==23||buffer[0]==25||buffer[0]==27||buffer[0]==29||buffer[0]==31?"PRESIONADO":"LIBRE");
printf("Botón derecho: %s\n", buffer[0]==2||buffer[0]==3||buffer[0]==6||buffer[0]==7||buffer[0]==10||buffer[0]==11||buffer[0]==14||buffer[0]==15||buffer[0]==19||buffer[0]==22||buffer[0]==23||buffer[0]==26||buffer[0]==30||buffer[0]==31?"PRESIONADO":"LIBRE");
printf("Botón de pulgar adelante: %s\n",buffer[0]==16||buffer[0]==17||buffer[0]==18||buffer[0]==19||buffer[0]==20||buffer[0]==21||buffer[0]==22||buffer[0]==23||buffer[0]==24||buffer[0]==25||buffer[0]==26||buffer[0]==27||buffer[0]==28||buffer[0]==29||buffer[0]==30||buffer[0]==31?"PRESIONADO":"LIBRE");
printf("Botón de pulgar atrás: %s\n",buffer[0]==8||buffer[0]==9||buffer[0]==10||buffer[0]==11||buffer[0]==12||buffer[0]==13||buffer[0]==14||buffer[0]==15||buffer[0]==24||buffer[0]==25||buffer[0]==26||buffer[0]==27||buffer[0]==28||buffer[0]==29||buffer[0]==30||buffer[0]==31?"PRESIONADO":"LIBRE");
printf("Botón scroll (rueda): %s\n", buffer[0] == 4 ||buffer[0]==5||buffer[0]==6||buffer[0]==7||buffer[0]==12||buffer[0]==13||buffer[0]==14||buffer[0]==15||buffer[0]==20||buffer[0]==21||buffer[0]==22||buffer[0]==23||buffer[0]==28||buffer[0]==29||buffer[0]==30||buffer[0]==31?"PRESIONADO":"LIBRE");
printf("Scroll arriba/abajo: %s\n", buffer[4] == 1?"ARRIBA": buffer[4] ==255?"ABAJO":"LIBRE");
printf("Posicion X: %d\n", buffer[1]>220 && buffer[2]==15 && posX>min_x? posX=posX-1:((1<buffer[1])&&(buffer[1]<25)) && buffer[2]==0 && posX<max_x? posX=posX+1: posX);
printf("Posicion Y: %d\n", buffer[2]>1 && buffer[3]==0 && posY>min_y? posY=posY-1:buffer[2]>1 && buffer[3]==255 && posY<max_y? posY=posY+1: posY);
}
int main(){
struct hid_device_info *dispositivos_disponibles, *dispositivo_actual;
//Listamos los dispositivos USB-HID conectados (los argumentos en 0 indican que se listen todos, sin filtro por vendor_id o product_id)
dispositivos_disponibles = hid_enumerate(0x0, 0x0);
dispositivo_actual = dispositivos_disponibles;
printf("\nDispositivos encontrados:\n========================\n");
int i=1;
while(dispositivo_actual) {
printf("%d. Vendor Id : %04hx\n", i, dispositivo_actual->vendor_id);
printf(" Product Id : %04hx\n", dispositivo_actual->product_id);
printf(" Path : %s\n", dispositivo_actual->path);
printf(" No. de serie: %ls\n", dispositivo_actual->serial_number);
printf(" Fabricante : %ls\n", dispositivo_actual->manufacturer_string);
printf(" Producto : %ls\n", dispositivo_actual->product_string);
printf(" Release : %hx\n", dispositivo_actual->release_number);
printf(" Interfaz : %d\n", dispositivo_actual->interface_number);
printf("\n");
dispositivo_actual = dispositivo_actual->next;
i++;
}
//Permitimos al usuario seleccionar el dispositivo a muestrear
int cantidad_dispositivos = i-1;
int opcion;
printf("Elija el dispositivo a monitorear (0 = SALIR): ");
scanf("%d", &opcion);
while(opcion < 0 || opcion > cantidad_dispositivos){
printf("Opción invalida! Elija una opción entre 0 y %d", cantidad_dispositivos);
scanf("%d", &opcion);
}
if(opcion != 0){
//Buscamos el dispositivo elegido por el usuario
dispositivo_actual = dispositivos_disponibles;
for(i = 1; i < opcion; i++){
if(dispositivo_actual->next)
dispositivo_actual = dispositivo_actual->next;
}
//Abrimos el dispositivo
hid_device *dispositivo;
dispositivo = hid_open(dispositivo_actual->vendor_id, dispositivo_actual->product_id, NULL);
//Lanzamos un thread para capturar la senal de finalizacion (cuando el usuario presiona ENTER)
pthread_t tid;
pthread_create(&tid, NULL, captura_finalizacion, NULL);
//Creamos el buffer
const int LONGITUD_BUFFER = 5;
unsigned char buffer[LONGITUD_BUFFER];
//Leemos la entrada cada 100 ms
en_ejecucion = TRUE;
while(en_ejecucion == TRUE){
//Limpiamos la pantalla (esto no es estandar, depende de cada SO)
printf("\033[2J");
//Esperamos 100 ms
usleep(10000);
//Leemos del dispositivo
memset(buffer, 0, sizeof(buffer)); //limpiamos el buffer
hid_read(dispositivo, buffer, sizeof(buffer));
//Mostramos por pantalla
despliega_salida_cruda(buffer, LONGITUD_BUFFER);
despliega_salida_mouse_usb(buffer);
}
pthread_join(tid, NULL);
//Al salir, cerramos el dispositivo
hid_close(dispositivo);
}
//Liberamos la memoria utilizada por la lista de dispositivos disponibles
hid_free_enumeration(dispositivos_disponibles);
//Liberamos otras estructuras de datos internas de la biblioteca hidapi
hid_exit();
printf("\n\nEjecución finalizada\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char rand_char(){
return (char)( (rand() % 26) + 97);
}
int main()
{
setvbuf(stdin, NULL, _IOFBF, 32768);
setvbuf(stdout, NULL, _IOFBF, 32768);
srand(rand()+time(NULL));
int T,N,H,i,j,score=0,new_score=-1;
scanf("%d%d%d",&T,&N,&H);
char passwords[200][13];
int honey_server[200] = {0};
for(i=0;i<N;i++){
int len = rand()%5 + 8;
for(j = 0; j < len; j++){
passwords[i][j] = rand_char();
}
passwords[i][j] = '\0';
}
int change,change2,change3;
char old_pass[13];
char old_pass2[13];
char old_pass3[13];
int server_no = 0;
while(T--){
if(honey_server[server_no%(N)] == 1){
change = (++server_no)%(N);
}
else{
change = server_no%(N);
}
strcpy(old_pass,passwords[change]);
if(honey_server[(1+change)%(N)] == 1){
change2 = (2+change)%(N);
}
else{
change2 = (change+1)%(N);
}
strcpy(old_pass2,passwords[change2]);
change3 = (int)(rand()%N);
if( (honey_server[(change3)%(N)] == 1 )){
change3 = (++change3)%(N);
}
strcpy(old_pass3,passwords[change3]);
int len = rand()%5 + 8;
for(j = 0; j < len; j++){
passwords[change][j] = rand_char();
}
passwords[change][j] = '\0';
len = rand()%5 + 8;
for(j = 0; j < len; j++){
passwords[change2][j] = rand_char();
}
passwords[change2][j] = '\0';
len = rand()%5 + 8;
for(j = 0; j < len; j++){
passwords[change3][j] = rand_char();
}
passwords[change3][j] = '\0';
for(i=0;i<N;i++){
printf("%s\n",passwords[i]);
fflush(stdout);
}
scanf("%d",&new_score);
if(new_score < score){
strcpy(passwords[change],old_pass);
strcpy(passwords[change2],old_pass2);
strcpy(passwords[change3],old_pass3);
}
else if(new_score >= score){
score = new_score;
honey_server[change] = 1;
honey_server[change2] = 1;
honey_server[change3] = 1;
}
server_no++;
}
return 0;
}
|
C
|
# 圆形体体积计算器(20 分)
# 本题要求实现一个常用圆形体体积的计算器。计算公式如下:
# 球体体积 V=3/4πr^3,其中r是球体半径。
# 圆柱体体积 V=πr^2h,其中r是底圆半径,h是高。
# 圆锥体体积 V=1/3πr^2h,其中r是底圆半径,h是高。
# 输入格式:
# 在每次计算之前,要求输出如下界面:
# 1-Ball
# 2-Cylinder
# 3-Cone
# other-Exit
# Please enter your command:
# 输出格式:
# 如果读入的指令是1或2或3,则执行相应的体积计算;如果是其他整数,则程序结束运行。
# 当输入为1时,在计算球体体积之前,打印Please enter the radius:,然后读入球体半径,完成计算;
# 当输入为2时,在计算圆柱体体积之前,打印Please enter the radius and the height:,然后读入底圆半径和高,完成计算;
# 当输入为3时,在计算圆锥体体积之前,打印Please enter the radius and the height:,然后读入底圆半径和高,完成计算。
# 计算结果在一行内输出,保留小数点后两位。
# 输入样例:
# 1
# 2
# 3
# 2.4 3
# 0
# 输出样例:
# 1-Ball
# 2-Cylinder
# 3-Cone
# other-Exit
# Please enter your command:
# Please enter the radius:
# 33.51
# 1-Ball
# 2-Cylinder
# 3-Cone
# other-Exit
# Please enter your command:
# Please enter the radius and the height:
# 18.10
# 1-Ball
# 2-Cylinder
# 3-Cone
# other-Exit
# Please enter your command:
#include <stdio.h>
int main()
{
int a;
double k, h, r;
k = 0.0;
while(1)
{
printf("1-Ball\n");
printf("2-Cylinder\n");
printf("3-Cone\n");
printf("other-Exit\n");
printf("Please enter your command:\n");
scanf("%d", &a);
if(a==3||a==1||a==2)
{
if(a==1)
{
printf("Please enter the radius:");
scanf("%lf", &r);
k = 4.0/3*3.1415926*r*r*r;
printf("%.2lf\n", k);
}
else
{
h = 0;
printf("Please enter the radius and the height:");
if(a==2)
{
scanf("%lf %lf", &r, &h);
k = 3.1415926*r*r*h;
printf("%.2lf\n", k);
}
else{
scanf("%lf %lf", &r, &h);
k = 1.0/3*3.1415926*r*r*h;
printf("%.2lf\n", k);
}
}
}
else{
Return 0;
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
/**
* @author beanmoon
*/
/* typedef int stack_elem_t; */
//define stack_elem_t to (void *) to fit in p024binary_tree.c
typedef void * stack_elem_t;
typedef struct{
int size;
int capacity;
stack_elem_t *elems;
} stack_type;
stack_type * stack_create(int capacity){
stack_type *s = (stack_type *)malloc(sizeof(stack_type));
s->size = 0;
s->capacity = capacity;
s->elems = (stack_elem_t*)malloc(capacity * sizeof(stack_elem_t));
return s;
}
void stack_destroy(stack_type *s){
free(s->elems);
free(s);
}
int stack_empty(const stack_type *s){
return s->size == 0;
}
int stack_size(const stack_type *s){
return s->size;
}
void stack_push(stack_type *s, stack_elem_t new){
if(s->size == s->capacity){
stack_elem_t *tmp = (stack_elem_t *)\
realloc(s->elems, s->capacity * 2 * sizeof(stack_elem_t));
s->elems = tmp;
s->capacity = s->capacity * 2;
}
s->elems[s->size++] = new;
}
stack_elem_t stack_pop(stack_type *s){
/* return s->elems[s->size--]; */
return s->elems[--s->size];
}
/* int main(){ */
/* return 0; */
/* } */
|
C
|
/*Checks numbers for repeated digits*/
#include <stdio.h>
#include <stdbool.h>
int
main (int argc, char *argv[])
{
bool digit_seen[10] = {false};
int digit;
long n, i = 0;
/* 首先将数读入一个数组,但是这里如何声明数组是个问题?*/
printf("Enter numbers(<=0 to terminate): ");
do
{
scanf("%ld", &n[i]);
i++;
} while (n[i-1] > 0);
/* 采用for循环,对数组中得每个数字进行判断是否有重复的数字 */
for (i = 0; n[i] > 0; i += 1)
{
while (n[i] > 0)
{
digit = n[i] % 10;
if (digit_seen[digit])
{
break;
}
digit_seen[digit] = true;
n[i] /= 10;
}
if (n[i] > 0)
{
printf("%ld has repeated digit(s)\n.", n[i]);
}
else
{
printf("No repeated digit\n");
}
}
return 0;
}
|
C
|
/**************************
* 函数功能:为进程设置文件模式创建屏蔽字,并返回以前的值;
* 函数原型:
*
* mode_t umask (mode_t cmask);
* 参数说明
* cmask是前面介绍的文件权限的9个值的若干个按位“或”构成,9个权限如下所示:
**/
/*****************************
* 文件访问权限
* st_mode屏蔽 意义
* S_IRUSR 用户-读
* S_IWUSR 用户-写
* S_IXUSR 用户-执行
*****************************
* S_IRGRP 组-读
* S_IWGRP 组-写
* S_IXGRP 组-执行
*****************************
* S_IROTH 其他-读
* S_IWOTH 其他-写
* S_IXOTH 其他-执行
*****************************
*/
/* umask的主要作用是在创建文件时设置或者屏蔽文件的某些权限;
* 下面举例子,在创建文件时指定文件的权限属性:mode &(~cmask);
* 其中mode 是open或者creat函数的属性参数
*/
#include "apue.h"
#include <fcntl.h>
#define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
int main(void)
{
umask(0);//set the first umask
//此时cmask值为000
if(creat("umask",RWRWRW) < 0)//creat参数的mode权限值为666
err_sys("creat error for umask.");
//最后创建成功的文件umask权限属性为mode &(~cmask),即为666
umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);//set the second umask
//此时cmask权限值为066
if(creat("bar",RWRWRW) < 0)//creat参数mode权限值依然为666
err_sys("creat error for bar.");
//成功创建的文件bar权限属性为mode &(~cmask),即为600
exit(0);
}
|
C
|
#include <stdio.h>
int main()
{
int n = 0;
printf("Enter the size of an array: ");
scanf("%d", &n);
int a[n];
printf("Enter the elements of an array:\n");
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
int maximum = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > maximum)
{
maximum = a[i];
}
}
printf("Maximum number in an array is %d\n", maximum);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int c[] = {2,8,3,4,4,6,7,5};
int j,*p = c, *q = c;
for(j = 0; j < 5; j++)
{
printf("%d\r\n",*c);
++q;
}
for(j = 0;j<5;j++)
{
printf("%d\r\n",*p);
++p;
}
}
|
C
|
/* icanna.c
* VERSION: 0.9.0
* AUTHER: knak@ceres.dti.ne.jp
* DATE: 2003.9.29
* LICENCE: GPL
*/
/*
* communicate unix domain cannaserver
* stdin -> cannaserver -> stdout
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define BFSZ (4096) /* buffer size */
#define CANNA_PATH ("/tmp/.iroha_unix/IROHA") /* unix domain socket path */
/*
* connect unix domain cannaserver
*/
int
connect_canna_server()
{
int canna;
struct sockaddr_un sun;
/* create unix domain socket */
if ((canna = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
/* connect cannaserver */
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path, CANNA_PATH);
if (connect(canna, (struct sockaddr*)&sun, SUN_LEN(&sun)) < 0) {
perror("connect");
exit(1);
}
return canna;
}
/*
* data transport
* stdin -> canna
* canna -> stdout
*/
int
transport(in, out)
int in, out;
{
char* buf = NULL; /* data buffer */
int len = BFSZ; /* data length */
int count = -1; /* read count */
/* read input */
while (len == BFSZ) {
count++;
/* allocate data buffer */
if ((buf = (char*)realloc(buf, (count + 1) * BFSZ)) == NULL) {
perror("realloc");
exit(1);
}
/* read input to data buffer */
if ((len = read(in, buf + count * BFSZ, BFSZ)) < 0) {
perror("read");
exit(1);
}
}
len += count * BFSZ;
/* write output */
if (len > 0 && write(out, buf, len) < 0) {
perror("write");
exit(1);
}
/* destroy data buffer */
free(buf);
return len;
}
/*
* communicate unix domain cannaserver
*/
int
main()
{
int canna;
canna = connect_canna_server(); /* connect unix domain cannaserver */
/* transport request & response, until stdin or cannaserver is eof */
while (1)
/* transport request from stdin to cannaserver,
* transport response from cannaserver to stdout */
if (transport(0, canna) == 0 || transport(canna, 1) == 0)
/* when stdin or cannaserver is eof, break loop */
break;
close(canna); /* close unix domain cannaserver */
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int n,k;
for(k=31;k<100;k++)
{
n=k*k;
if((n%10==n/10%10) && (n/100%10==n/1000) && (n%10!=n/1000))
printf("%d\n",n);
}
return 0;
}
|
C
|
//#include <stdio.h>
//
//int main()
//{
// int n;
// scanf("%d", &n);
//
// int min = 1000000, max = -1000000;
// int input;
// for (int i = 0; i < n; ++i)
// {
// scanf("%d", &input);
// if (input > max) max = input;
// if (input < min) min = input;
// }
//
// printf("%d %d\n", min, max);
// return 0;
//}
|
C
|
/*
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int myAtoi(char* str) {
long ret = 0;
int length = strlen(str);
int sign = 1;
int findfirst = 0;
for(int i = 0;i<length;i++){
char ch = str[i];
if(ch >= '0' && ch <= '9'){
int num = ch - '0';
ret *= 10;
ret += num;
if(findfirst == 0)
findfirst = 1;
if(ret * sign > 2147483647)
return 2147483647;
if(ret * sign < -2147483648)
return -2147483648;
continue;
}
else if(ch == 32 && findfirst == 0){
continue;
}
else if(findfirst == 0){
if(ch == '+'){
findfirst = 1;
continue;
}
else if(ch == '-'){
sign = -1;
findfirst = 1;
continue;
}
}
//error
//return 0;
break;
}
return ret * sign;
}
int main(){
char *testcase[5] = {" 123 45 67",
" a134",
"-124 6",
" +0 123456",
"-00123a00"};
for(int i = 0;i<5;i++){
printf("%s -> %d \n",testcase[i],myAtoi(testcase[i]));
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int num1;
int num2;
int num3;
printf("Input three integer: ");
scanf("%d %d %d", &num1, &num2, &num3);
printf("%d\n", num1);
printf("%d\n", num2);
printf("%d\n", num3);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_LIST_SIZE 8
typedef struct {
unsigned int maxSize;
unsigned int size;
void** entries;
} List;
List* InitList();
void DeleteList(List* ls);
int AppendToList(List* ls, void* entry);
void* GetListItem(List* ls, unsigned int index);
List* IntersectList(List* lsa, List* lsb);
|
C
|
/**
* Copyright © 2018 Andrey Nevolin, https://github.com/AndreyNevolin
* Twitter: @Andrey_Nevolin
* LinkedIn: https://www.linkedin.com/in/andrey-nevolin-76387328
*
* Example code demonstrating use of Wall-clock Time Measurement library (wtmlib)
*/
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include "src/wtmlib.h"
#define USECS_TO_LOOP_FOR 2547291ul
int calcDeltaInNsecs( const struct timespec *start_time,
const struct timespec *end_time,
uint64_t *delta)
{
if ( start_time->tv_sec > end_time->tv_sec )
{
fprintf( stdout, "\tSystem error. Start system time has %lu seconds while end "
"system time has smaller amount of seconds (%lu)\n", start_time->tv_sec,
end_time->tv_sec);
return -1;
}
uint64_t num_nsecs = 0;
uint64_t num_secs = end_time->tv_sec - start_time->tv_sec;
if ( !num_secs && start_time->tv_nsec > end_time->tv_nsec )
{
fprintf( stdout, "\tSystem error. Start and end system times have equal amounts "
"of seconds but the start time has more nanoseconds (%lu > %lu)\n",
start_time->tv_nsec, end_time->tv_nsec);
return -1;
}
if ( start_time->tv_nsec > end_time->tv_nsec )
{
num_secs--;
num_nsecs = 1000000000 - start_time->tv_nsec + end_time->tv_nsec;
} else
{
num_nsecs = end_time->tv_nsec - start_time->tv_nsec;
}
if ( delta ) *delta = (num_secs * 1000000000) + num_nsecs;
return 0;
}
int main()
{
char err_msg[WTMLIB_MAX_ERR_MSG_SIZE] = "";
int64_t tsc_range_length = INT64_MAX;
bool is_monotonic = false;
wtmlib_TSCConversionParams_t conv_params = {.mult = 0, .shift = -1,
.nsecs_per_tsc_modulus = 0,
.tsc_remainder_length = 0,
.tsc_remainder_bitmask = 0};
uint64_t secs_before_wrap = 0;
struct timespec start_time = {.tv_sec = 0, .tv_nsec = 0};
struct timespec end_time = {.tv_sec = 0, .tv_nsec = 0};
uint64_t elapsed_nsecs = 0;
uint64_t start_tsc_val = 0, end_tsc_val = 0;
int ret = 0;
fprintf( stdout, "Evaluating TSC reliability (all needed data is collected using a "
"single thread \"jumping\" from one CPU to another)...\n");
ret = wtmlib_EvalTSCReliabilityCPUSW( &tsc_range_length, &is_monotonic, err_msg,
sizeof( err_msg));
if ( ret )
{
fprintf( stdout, "\tEvaluation failed. ");
switch ( ret )
{
case WTMLIB_RET_TSC_INCONSISTENCY:
fprintf( stdout, "Major TSC inconsistency detected: %s\n\n", err_msg);
break;
case WTMLIB_RET_GENERIC_ERR:
fprintf( stdout, "%s\n\n", err_msg);
break;
default:
fprintf( stdout, "Unexpected error type. Error message: %s\n\n", err_msg);
}
} else
{
fprintf( stdout, "\tEstimated maximum shift between TSC counters running on "
"different CPUs: %ld\n", tsc_range_length);
fprintf( stdout, "\tTSC values measured successively on same or different CPUs "
"%s monotonically increase\n\n", is_monotonic ? "DO" : "DO NOT");
}
fprintf( stdout, "Evaluating TSC reliability (all needed data is collected by "
"concurrently running threads; one thread per each available CPU. "
"Measurements taken by the threads are sequentially ordered using CAS)"
"...\n");
ret = wtmlib_EvalTSCReliabilityCOP( &tsc_range_length, &is_monotonic, err_msg,
sizeof( err_msg));
if ( ret )
{
fprintf( stdout, "\tEvaluation failed. ");
switch ( ret )
{
case WTMLIB_RET_TSC_INCONSISTENCY:
fprintf( stdout, "Major TSC inconsistency detected: %s\n\n", err_msg);
break;
case WTMLIB_RET_POOR_STAT:
fprintf( stdout, "Statistical significance criteria are not met: %s\n\n",
err_msg);
break;
case WTMLIB_RET_GENERIC_ERR:
fprintf( stdout, "%s\n\n", err_msg);
break;
default:
fprintf( stdout, "Unexpected error type. Error message: %s\n\n", err_msg);
}
} else
{
fprintf( stdout, "\tEstimated maximum shift between TSC counters running on "
"different CPUs: %ld\n", tsc_range_length);
fprintf( stdout, "\tTSC values measured successively on same or different CPUs "
"%s monotonically increase\n\n", is_monotonic ? "DO" : "DO NOT");
}
fprintf( stdout, "Getting TSC-to-nanoseconds conversion parameters...\n");
ret = wtmlib_GetTSCToNsecConversionParams( &conv_params, &secs_before_wrap, err_msg,
sizeof( err_msg));
if ( ret )
{
fprintf( stdout, "\tFailed. ");
switch ( ret )
{
case WTMLIB_RET_TSC_INCONSISTENCY:
fprintf( stdout, "Major TSC inconsistency detected: %s\n\n", err_msg);
break;
case WTMLIB_RET_GENERIC_ERR:
fprintf( stdout, "%s\n\n", err_msg);
break;
default:
fprintf( stdout, "Unexpected error type. Error message: %s\n\n", err_msg);
}
} else
{
fprintf( stdout, "\tNanoseconds per TSC modulus: %lu\n",
conv_params.nsecs_per_tsc_modulus);
fprintf( stdout, "\tLength of TSC remainder in bits: %d\n",
conv_params.tsc_remainder_length);
fprintf( stdout, "\tBitmask used to extract TSC remainder: %016lx\n",
conv_params.tsc_remainder_bitmask);
fprintf( stdout, "\tMultiplicator: %lu\n", conv_params.mult);
fprintf( stdout, "\tShift: %d\n", conv_params.shift);
fprintf( stdout, "\tTSC ticks per second: %lu\n", conv_params.tsc_ticks_per_sec);
fprintf( stdout, "\tSeconds before the earliest TSC wrap: %lu\n\n",
secs_before_wrap);
}
fprintf( stdout, "Now looping for approximately %lu microseconds and measuring "
"the elapsed time using both system and WTMLIB means...\n",
USECS_TO_LOOP_FOR);
ret = clock_gettime( CLOCK_MONOTONIC_RAW, &start_time);
start_tsc_val = WTMLIB_GET_TSC();
if ( ret )
{
fprintf( stdout, "\tclock_gettime() failed");
/* This is a test program. It must always succeed */
return 0;
}
do
{
ret = clock_gettime( CLOCK_MONOTONIC_RAW, &end_time);
end_tsc_val = WTMLIB_GET_TSC();
if ( ret )
{
fprintf( stdout, "\tclock_gettime() failed");
/* This is a test program. It must always succeed */
return 0;
}
if ( calcDeltaInNsecs( &start_time, &end_time, &elapsed_nsecs) ) return 0;
} while ( elapsed_nsecs < USECS_TO_LOOP_FOR * 1000 );
if ( end_tsc_val < start_tsc_val )
{
fprintf( stdout, "\tError. End TSC value is smaller than start TSC value\n");
/* This is a test program. It must always succeed */
return 0;
}
fprintf( stdout, "\t%lu nanoseconds passed according to \"clock_gettime()\"\n",
elapsed_nsecs);
fprintf( stdout, "\t%lu nanoseconds passed according to WTMLIB\n",
WTMLIB_TSC_TO_NSEC( end_tsc_val - start_tsc_val, &conv_params));
return 0;
}
|
C
|
#include "mylib.h"
#include <limits.h>
struct pollfd client[OPEN_MAX];
char* name[OPEN_MAX];
uint8_t client_status[OPEN_MAX];
int main()
{
int listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(8080);
servaddr.sin_addr.s_addr = INADDR_ANY;
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
listen(listenfd, 10);
client[0].fd = listenfd;
client[0].events = POLLRDNORM;
for(int i = 1; i < OPEN_MAX; i++)
{
client[i].fd = -1;
}
int maxi = 0;
while(1)
{
int nready = poll(client, maxi + 1, -1);
if(client[0].revents & POLLRDNORM)
{
struct sockaddr_in cliaddr;
socklen_t len = sizeof(cliaddr);
int connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &len);
int i;
for(i = 1; i < OPEN_MAX; i++)
{
if (client[i].fd < 0)
{
client[i].fd = connfd;
break;
}
}
if(i == OPEN_MAX)
{
char* errorConnect = "Khong the ket noi toi server!!!\n";
writen(connfd, errorConnect, strlen(errorConnect));
continue;
}
client[i].events = POLLRDNORM;
char* welcome = "Gui lenh theo cu phap \"client_id: <ten>\"\n";
writen(connfd, welcome, strlen(welcome));
if(i > maxi) maxi = i;
if(--nready <= 0)
continue;
}
for(int i = 1; i <= maxi; i++)
{
if(client[i].fd < 0)
continue;
if(client[i].revents & POLLRDNORM)
{
char buffer[1024];
if(readline(client[i].fd, buffer, sizeof(buffer)) == 0)
{
close(client[i].fd);
client[i].fd = -1;
client_status[i] = 0;
free(name[i]);
printf("1 client da thoat!!!\n");
continue;
}
if(client_status[i] == 0)
{
if(strncmp(buffer, "client_id: ", 11) == 0)
{
char* valid = "CHUC MUNG BAN DA VAO ROOM\n";
writen(client[i].fd, valid, strlen(valid));
client_status[i] = 1; //da vao room
name[i] = (char*)calloc(MAXLINE, 1);
strcpy(name[i], buffer + 11);
name[i][strlen(name[i]) - 1] = 0;
}
else
{
char* invalid = "SAI CU PHAP\n";
writen(client[i].fd, invalid, strlen(invalid));
}
}
else
{
char message[1024];
sprintf(message, "%s: %s", name[i], buffer);
for(int k = 1; k <= maxi; k++)
{
if(client_status[k] == 1 && k != i)
{
writen(client[k].fd, message, strlen(message));
}
}
}
if(--nready <= 0)
break;
}
}
}
}
|
C
|
/**
* Defines für den Laser-Ranger
*
* Hokuyo URG-04LX: fov 240°, 681 samples
*/
#ifndef LASER_H
#define LASER_H
#include <math.h>
/**
* Field-Of-View in Grad
*/
#define LASER_FOV_DEG (240.0)
/**
* Samples in FOV
*/
#define LASER_SAMPLES (681)
/**
* Maximale Messung in Metern
*/
#define LASER_RANGE_MIN (0.35)
/**
* Minimale Messung in Metern
*/
#define LASER_RANGE_MAX (4.0)
/**
* Epsilonwert für Distanzvergleiche
*/
#define LASER_RANGE_EPSILON (0.001)
/**
* Umwandlung von Winkel in Sample
*/
#define LASER_RANGEINDEX_FROM_ANGLE_DEG(degree) \
((int)((degree/(LASER_FOV_DEG/2)) * LASER_SAMPLES/2 + LASER_SAMPLES/2))
/**
* Umwandlung von Sample in Winkel
*/
#define LASER_DEGREE_FROM_RANGEINDEX(index) \
((double)(index*LASER_ANGULAR_RESOLUTION_DEG+LASER_MIN_ANGLE_DEG))
/**
* Field-Of-View in Radians
*/
#define LASER_FOV_RAD (LASER_FOV_DEG * M_PI / 180.0)
/**
* Winkelauflösung in Grad
*/
#define LASER_ANGULAR_RESOLUTION_DEG (LASER_FOV_DEG / LASER_SAMPLES)
/**
* Winkelauflösung in Radians
*/
#define LASER_ANGULAR_RESOLUTION_RAD (LASER_FOV_RAD / LASER_SAMPLES)
/**
* Maximaler Öffnungswinkel in Radians
*/
#define LASER_MAX_ANGLE_RAD (LASER_FOV_RAD/2.0)
/**
* Minimaler Öffnungswinkel in Radians
*/
#define LASER_MIN_ANGLE_RAD (-LASER_MAX_ANGLE_RAD)
/**
* Maximaler Öffnungswinkel in Degree
*/
#define LASER_MAX_ANGLE_DEG (LASER_FOV_DEG/2.0)
/**
* Minimaler Öffnungswinkel in Degree
*/
#define LASER_MIN_ANGLE_DEG (-LASER_MAX_ANGLE_DEG)
#endif
|
C
|
/**************************************************************************
PROGRAM NAME : dssd (source dssd.c)
**************************************************************************/
#include <string.h>
#include <stdio.h>
#include <time.h>
FILE *inp; /* input file */
FILE *out; /* output file */
char *p1;
char *p2;
char *input;
char *output;
char buf[2000]; /* buffer area to read input file */
char buf2[10000]; /* buffer area to hold joined file */
char comment[10000];
char ruref[12];
char name[36];
char sic[6];
char period[7];
int reply;
int cnt1, cnt2, i, j, l, x, len, newflag,namelen;
time_t tim;
main(argc,argv)
int argc;
char *argv[];
{
if(argc < 3)
{
fprintf(stderr,"Error, usage is %s <inputfilename> <outputfilename>\n",argv[0]);
exit(1);
}
tim = time(NULL);
fprintf(stderr,"\nProgram Begins %s\n",ctime(&tim));
cnt1=0;
cnt2=0;
input = argv[1]; /* input file assigned to pointer */
output = argv[2]; /* output file assigned to pointer */
if ((inp = fopen(input,"r")) == NULL)
{
fprintf(stderr,"Error opening %s does it exist?\n",input);
exit(1);
}
if ((out = fopen(output,"w")) == NULL)
{
fprintf(stderr,"Error opening %s permissions?, disk full?\n",output);
exit(1);
}
newflag=0;
read1();
p1 = buf;
strncpy(ruref,buf,11);
p1 += 20;
strncpy(sic,p1,5);
p1 = buf;
p1 +=26;
len = strcspn(p1,"|");
namelen = len;
strncpy(name,p1,len);
/* findname();*/
while (feof(inp) == 0)
{
if(strncmp(ruref,buf,11) != 0) /* checks for new ruref */
{
newflag=0;
strncpy(buf2,ruref,11);
strcat(buf2,"|");
strncat(buf2,name,namelen);
strcat(buf2,"|");
strcat(buf2,sic);
strcat(buf2,"|\n");
strcat(buf2,comment);
strcat(buf2,"###\n");
fputs(buf2,out);
cnt2++;
for(j=0;j<10000;j++)
{
buf2[j]='\0';
comment[j]='\0';
}
p1 = buf;
strncpy(ruref,buf,11);
p1 += 20;
strncpy(sic,p1,5);
p1 = buf;
p1 +=26;
len = strcspn(p1,"|");
namelen = len;
strncpy(name,p1,len);
}
findname();
read1();
}
fclose(inp);
fprintf(stderr,"Records read from input file = %d\n",cnt1);
fprintf(stderr,"Records written to output file = %d\n",cnt2);
tim = time(NULL);
fprintf(stderr,"Program Ends OK %s\n",ctime(&tim));
return 0;
}
/*************************** findname ******************************/
/* old layout is
ruref : name : sic : period : comment
new layout is
ruref | period : sic92 | name | comment | author */
findname()
{
j=0;
x=0;
p1 = buf; /* point at buffer */
p1 +=12; /* point past ruref */
p2 = p1;
p2 = buf;
p2 +=26; /* position at name */
len = strcspn(p2,"|"); /* find length of name */
p2 += len; /* point at comment */
p2++;
len = strcspn(p2,"|"); /* find length of comment */
if (len > 2) /* ignore empty comments */
{
strncpy(period,p1,6); /* copy in current period */
strncat(comment,period,6);
strcat(comment," "); /* comment with 2 spaces */
p1 = buf;
p1 +=26; /* position at name */
len = strcspn(p1,"|"); /* find length of name */
p1 += len; /* point at comment */
p1++;
len = strcspn(p1,"|"); /* find length of comment */
strncat(comment,p1,len); /* append comment */
p1 += len; /* point at author */
p1++;
strcat(comment," ");
strcat(comment,p1); /* append author */
}
return 0;
}
/*************************** read1 ******************************/
read1()
{
for(j=0;j<2000;j++)
{
buf[j]='\0';
}
fgets(buf,2000,inp);
if (feof(inp) != 0)
{
fprintf(stderr,"End of file %s\n",input);
return 0;
}
cnt1++;
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
int pedirIntRango;
int main()
{
int x = pedirIntRango();
printf("%d",x);
return 0;
}
int pedirIntRango(int min,int sup){
int num;
printf("Ingrese un numero entre %d y %d",min,sup);
scanf("%d",&num);
while(num < 0 || num > 500){
printf("Error. Ingrese un numero entre %d y %d",min,sup);
scanf("%d",&num);
}
return num;
}
int main(){
int x;
int flagX;
flagX = getInt(&x);
if(flagX == 1){
printf("x vale: %d"x);
}
else{
printf("No se puede cargar");
}
}
void getInt(int* puntero){
int num;
int todoOk;
printf("ingrese numero: ");
scanf("%d"&num);
if(num >=0){
*puntero = num;
todoOk = 1;
}
else{
todoOk = 0;
}
}
*/
int main(){
int x;
int flagX;
flagX = getInt(&x);
if(flagX == 1){
printf("x vale: %d"x);
}
else{
printf("No se puede cargar");
}
}
void getInt(int* puntero){
int num;
int todoOk;
int contador = 0;
printf("ingrese numero positivo: ");
scanf("%d"&num);
while(num <= 0){
printf("Error.Reingrese numero")
scanf("%d"&num);
contador++;
if(contador=3){
todoOk
}
}
if(num >=0){
*puntero = num;
todoOk = 1;
}
else{
todoOk = 0;
}
}
*/
|
C
|
#include "headers.h"
#include "linkedList.h"
#include "PriorityQueue.h"
#include "Queue.h"
#include "PCB.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include <signal.h>
#include <time.h>
#include <math.h>
void userHandler(int signum);
void startProcess(PCB* processPCB, FILE* outLogFile);
void resumeProcess(PCB* processPCB, FILE* outLogFile, bool silent);
void stopProcess(PCB* processPCB, FILE* outLogFile, bool silent);
void finishProcess(PCB* processPCB, FILE* outLogFile,FILE* outMemFile);
void SRTN(FILE* outLogFile, FILE* outMemFile);
void HPF(FILE* outLogFile, FILE* outMemFile);
void RR(FILE* outLogFile, FILE* outMemFile, int Quantum);
int succesful_exit_handler = 0; // global variable to store that the child exited successfully
int finish_scheduler = 0; // global variable to store if the scheduler should stop (No other processes)
// global variables initialized for calculations
double total_waiting_time = 0;
double total_proceesing_time = 0;
double total_WTA = 0;
double processCount = 0;
Queue WTAQueue;
void StandardDeviation(FILE* outCalcFile);
// array of memory chunks linked lists
LinkedList freeChunks[8];
// allocates memory for the given process
void allocate_mem(PCB* processPCB, FILE* outMemFile);
// gets the first available chunk in the memory list with number list_num
int getFirstFreeChunk(int list_num);
// Adds the required chunk number to the free chuncks
int freeChunck(int list_num, int chunk_num);
// Merge free memory chunks
int mergeFreeChuncks(int list_num, int freed_chunk_num);
//printing free chuncks lists
void DisplayChunkLists();
int main(int argc, char * argv[])
{
// Establish communication with the clock module
initClk();
// Handler for SIGUSR1 signal sent by children to the scheduler upon successful termination
signal(SIGUSR1, userHandler);
// Open an output file for the scheduler log (in the write mode)
FILE* outLogFile = (FILE *) malloc(sizeof(FILE));
outLogFile = fopen("SchedulerLog.txt", "w");
if (outLogFile == NULL) {
printf("Could not open output file for scheduler log.\n");
}
// Open an output file for the scheduler calculations (in the write mode)
FILE* outCalcFile = (FILE *) malloc(sizeof(FILE));
outCalcFile = fopen("SchedulerCalc.txt", "w");
if (outCalcFile == NULL) {
printf("Could not open output file for scheduler calculations.\n");
}
// Open an output file for the memory log (in the write mode)
FILE* outMemFile = (FILE *) malloc(sizeof(FILE));
outMemFile = fopen("MemoryLog.txt", "w");
if (outMemFile == NULL) {
printf("Could not open output file for memory log.\n");
}
// Read the passed arguments
int quantum;
char *schedalg = NULL;
if (argc == 2) {
// Get the chosen algorithm
schedalg = argv[0];
///////printf("Algorithm chosen: %s.\n", schedalg);
// Get the quantum needed for round robin algorithm
quantum = atoi(argv[1]);
///////printf("Quantum chosen: %d.\n", quantum);
}
// Initialize message queue
initMsgQueue();
// Initialize linked lists of free memory chunks
for (int i = 0; i < 8; i++) {
LLInit(&(freeChunks[i]), sizeof(int));
}
SortedInsert(&(freeChunks[7]), 1);
// Initialize queue of weighted turnaround times
queueInit(&WTAQueue, sizeof(double));
// Get initial value of CPU clocks used by scheduler
clock_t befClocks = clock();
///////printf("Initial value of scheduler CPU clocks %ld\n", befClocks);
// Run the chosen algorithm (HPF, RR or SRTN)
if(strcmp(schedalg,"HPF") == 0)
{
printf("Chosen algorithm is HPF.\n");
HPF(outLogFile,outMemFile);
}
else if (strcmp(schedalg,"RR") == 0) {
printf("Chosen algorithm is RR with a quantum of %d seconds.\n", quantum);
RR(outLogFile,outMemFile,quantum);
}
else if (strcmp(schedalg,"SRTN") == 0) {
printf("Chosen algorithm is SRTN.\n");
SRTN(outLogFile,outMemFile);
}
// Get final value of CPU clocks used by scheduler
clock_t aftClocks = clock();
///////printf("Final value of scheduler CPU clocks %ld\n", aftClocks);
// Total CPU clocks used by scheduler
clock_t totalClks = aftClocks - befClocks;
// Calculate total time taken by scheduler in seconds
double totalSched = ((double) totalClks) + (((double) total_proceesing_time) * ((double) CLOCKS_PER_SEC));
totalSched = (double) (totalSched/CLOCKS_PER_SEC);
// Calculate CPU utilization and print it in output file
double cpu_utilization= (double) ((total_proceesing_time/totalSched)*100);
fprintf(outCalcFile, "CPU utilization: %.0f %% \n", cpu_utilization);
// Calculate average weighted turnaround time and print it in output file
double AWTA = (double) (total_WTA/processCount);
fprintf(outCalcFile,"Avg WTA = %.2f\n", AWTA);
// Calculate average waiting time and print it in output file
double Avg_waiting= (double) (total_waiting_time/processCount);
fprintf(outCalcFile,"Avg Waiting = %.2f \n",Avg_waiting);
// Calculate standard deviation and print it in output file
StandardDeviation(outCalcFile);
// Close the output log and calculations file
fclose(outLogFile);
fclose(outCalcFile);
fclose(outMemFile);
// Upon termination, release resources of communication with the clock module
//destroyClk(false);
return 0;
}
// Allocates memory for the given process
void allocate_mem(PCB* processPCB,FILE* outMemFile) {
// get the number of the list corresponding to the required memory size
int list_num = ceil(log2(processPCB->mem_size)) - 3;
int chunk_size = pow(2, (list_num + 3));
int chunk_num = getFirstFreeChunk(list_num);
// update process PCB to store number of allocated memory chunk
processPCB->alloc_mem_chunk = chunk_num;
//print for testing
//printf("\n\nThe process with ID %d is allocated at %d, and its chunck number is %d\n\n", processPCB->id, getClk(), processPCB->alloc_mem_chunk);
//DisplayChunkLists();
int currTime1 = getClk();
int startingbyte = chunk_size*(chunk_num-1);
int endbyte = startingbyte + chunk_size -1;
fprintf(outMemFile, "At time %d allocated %d bytes for process %d from %d to %d\n", currTime1, processPCB->mem_size, processPCB->id, startingbyte, endbyte) ;
}
// Gets the first available chunk in the memory list with number list_num
int getFirstFreeChunk(int list_num) {
if ((list_num < 0) || (list_num > 7)) {
printf("Required chunk size is invalid; out of boundaries.\n");
return -1;
}
if (freeChunks[list_num].sizeOfLL != 0) {
return (delete_begin((&freeChunks[list_num])));
}
else {
if ((list_num + 1) > 7) {
printf("No free memory available for allocation.\n");
return -1;
}
int chunk_num = getFirstFreeChunk(list_num + 1);
if (chunk_num != -1)
{
SortedInsert((&freeChunks[list_num]), chunk_num*2);
return ((chunk_num*2) - 1);
}
else {
return -1;
}
}
}
// Adds the required chunk number to the free chuncks
int freeChunck(int list_num, int chunk_num)
{
//this function checks if the required chunk number is not free, then add it to the free chuncks
if (chunk_num == 0)
{
printf("Invalid chunck num");
return 0;
}
if ((list_num < 0) || (list_num > 7)) {
printf("Invalid chunk size, No memory is allocated with this chunk.\n");
return 0;
}
else
{
//check if this chunck is free
int found = findPos(&freeChunks[list_num], chunk_num);
//if it is already free, we cannot deallocate it
if(found == 1)
{
printf("There is no memory allocated in this chunck number");
return 0;
}
//if it is not free, we add it to the free chuncks
else
{
SortedInsert(&freeChunks[list_num],chunk_num);
return chunk_num;
}
}
}
// Merge free memory chunks
int mergeFreeChuncks(int list_num, int freed_chunk_num)
{
if (freed_chunk_num == 0)
{
printf("\nInvalid chunck num\n");
return 0;
}
if ((list_num < 0) || (list_num > 7)) {
printf("\nInvalid chunk size, No memory is allocated with this chunk.\n");
return 0;
}
//check if the preceeding or proceeding elements are found (even or odd)
int oddChunck = 1; //0 if even, 1 if odd
int found;
if (freed_chunk_num % 2 == 0)
{
found = findPos(&freeChunks[list_num],freed_chunk_num-1);
oddChunck = 0;
}
else
{
found = findPos(&freeChunks[list_num], freed_chunk_num+1);
oddChunck = 1;
}
//if element is not found, return as there is no merge
if (found == 0)
{
printf("\nFound no element suitable for merging\n");
return 0;
}
else
{
if (oddChunck == 0) //even chunck
{
int del = delete_element(&freeChunks[list_num], freed_chunk_num);
int del_prev = delete_element(&freeChunks[list_num], freed_chunk_num-1);
if (del == 1 && del_prev == 1) //successful deletion
{
SortedInsert(&freeChunks[list_num+1], freed_chunk_num/2);
return (1+mergeFreeChuncks(list_num+1, freed_chunk_num/2));
}
else
{
printf("\nUnable to merge\n");
return 0;
}
}
else //odd chunck
{
int del_next = delete_element(&freeChunks[list_num], freed_chunk_num+1);
//printf("\nDeleted Element: %d", del_next);
int del = delete_element(&freeChunks[list_num], freed_chunk_num);
//printf("\nDeleted Element: %d", del);
if (del == 1 && del_next == 1) //successful deletion
{
SortedInsert(&freeChunks[list_num+1], (freed_chunk_num+1)/2);
return (1+ mergeFreeChuncks(list_num+1, (freed_chunk_num+1)/2));
}
else
{
printf("\nUnable to merge\n");
return 0;
}
}
}
}
// Resumes a currently running process
void resumeProcess(PCB* processPCB, FILE* outLogFile, bool silent) {
// Send a continue signal to the process
kill(processPCB->pid, SIGCONT);
// Calculate and update the process waiting time and state
int currTime = getClk();
processPCB->waitingTime = (currTime - processPCB->arrivalTime) - (processPCB->runTime - processPCB->remainingTime);
processPCB->state = RUNNING;
// Print the "resumed" line in the output log file
if (!silent) {
fprintf(outLogFile, "At time %d process %d resumed arr %d total %d remain %d wait %d\n", currTime, processPCB->id, processPCB->arrivalTime, processPCB->runTime, processPCB->remainingTime, processPCB->waitingTime);
}
}
// Starts a process for the first time
void startProcess(PCB* processPCB, FILE* outLogFile) {
// Create the process
int pid = fork();
if (pid == -1)
perror("Error in fork. Could not start process.\n");
else if (pid == 0)
{
char str[100];
sprintf(str, "%d", processPCB->runTime);
char * param[] = {str, NULL};
execv("./process.out", param); // param contains the running time of the process
}
else {
int currTime = getClk();
// Update the process PCB fields as appropriate
processPCB->pid = pid;
processPCB->startTime = currTime;
processPCB->remainingTime = processPCB->runTime;
processPCB->waitingTime = currTime - processPCB->arrivalTime;
processPCB->state = RUNNING;
///////printf("Process created successfully.\n");
// Print the "started" line in the output log file
fprintf(outLogFile, "At time %d process %d started arr %d total %d remain %d wait %d\n", currTime, processPCB->id, processPCB->arrivalTime, processPCB->runTime, processPCB->remainingTime, processPCB->waitingTime);
}
}
// Stops a currently running process
void stopProcess(PCB* processPCB, FILE* outLogFile, bool silent) {
// Send a stop signal to the process
kill(processPCB->pid, SIGSTOP);
// Calculate and update the process remaining time and state
int currTime = getClk();
processPCB->remainingTime = (processPCB->runTime) - (currTime - processPCB->arrivalTime - processPCB->waitingTime);
processPCB->state = WAITING;
// Print the "stopped" line in the output log file
if(!silent) {
fprintf(outLogFile, "At time %d process %d stopped arr %d total %d remain %d wait %d\n", currTime, processPCB->id, processPCB->arrivalTime, processPCB->runTime, processPCB->remainingTime, processPCB->waitingTime);
}
}
// Updates the process data as appropriate upon termination
void finishProcess(PCB* processPCB, FILE* outLogFile,FILE* outMemFile)
{
int currTime = getClk();
//free memory chunck and merge
int list_num = ceil(log2(processPCB->mem_size)) - 3;
int chunk_size = pow(2, (list_num + 3));
int merge = mergeFreeChuncks(list_num,freeChunck(list_num,processPCB->alloc_mem_chunk));
// Calculate and update the process remaining time, finish time and state
processPCB->remainingTime = 0;
processPCB->finishTime = processPCB->arrivalTime + processPCB->waitingTime + processPCB->runTime;
processPCB->state = FINISHED;
//print for testing
//printf("\n\nThe process with ID %d is deallocated at %d, and its chunck number is %d\n\n",processPCB->id, processPCB->finishTime, processPCB->alloc_mem_chunk);
//DisplayChunkLists();
// Calculate turnaround time and the weighted turnaround time
double turn_around_time = currTime - processPCB->arrivalTime;
double w_turn_around_time = turn_around_time/((double)(processPCB->runTime));
// Calcualate contribution to the global variables
total_waiting_time = total_waiting_time + processPCB->waitingTime;
total_WTA = total_WTA + w_turn_around_time;
total_proceesing_time = total_proceesing_time + processPCB->runTime;
processCount++;
double* WTApointer = (double *) malloc(sizeof(double));
*WTApointer = w_turn_around_time;
enqueue(&WTAQueue, WTApointer);
// Print the "finished" line in the output log file
fprintf(outLogFile, "At time %d process %d finished arr %d total %d remain %d wait %d TA %.0f WTA %.2f\n", currTime, processPCB->id, processPCB->arrivalTime, processPCB->runTime, processPCB->remainingTime, processPCB->waitingTime, turn_around_time, w_turn_around_time);
//////////////
int startingbyte = chunk_size*(processPCB->alloc_mem_chunk-1);
int endbyte = startingbyte + chunk_size -1;
fprintf(outMemFile, "At time %d freed %d bytes from process %d from %d to %d\n", currTime, processPCB->mem_size, processPCB->id, startingbyte, endbyte) ;
/////////////////////
free(processPCB);
processPCB = NULL;
succesful_exit_handler = 0;
}
// Handler for the SIGUSR1 signal sent to scheduler upon successful termination of a process
void userHandler(int signum) {
printf("Process successfully terminated.\n");
succesful_exit_handler = 1;
}
// Calculates the standard deviation of the weighted turnaround times of all processes
void StandardDeviation(FILE* outCalcFile)
{
// Average weighted turnaround time
double AWTA = (double) (total_WTA/processCount);
// Dequeuing from WTAQueue to calculate standard deviation
double currDouble;
double SD_numerator = 0;
while (getQueueSize(&WTAQueue) != 0) {
dequeue(&WTAQueue,&currDouble);
double powerResult = pow((currDouble-AWTA), 2);
SD_numerator += powerResult;
}
// Final result of the standard deviation of the weighted turnaround times
double SD = sqrt(((double) (SD_numerator/processCount)));
// Print the result in the output file
fprintf(outCalcFile, "Std WTA = %.2f\n", SD);
}
// Shortest Remaining Time Next Algorithm
void SRTN(FILE* outLogFile,FILE* outMemFile) {
printf("Running SRTN.\n");
// Initialize a priority queue
PNode* PQueueHead = NULL;
struct msgbuff tempBuffer;
PCB* tempPCB = NULL;
int status;
while(1) {
///////printf("Inside While\n");
// In case of an empty priority queue
if (isEmpty(&PQueueHead)) {
// If the termination flag is 1; i.e. no more processes are coming
if(finish_scheduler) {
printf("Empty priority queue (%d) and finish flag is true\n", isEmpty(&PQueueHead));
break;
}
// Wait till you receive a message
status = 0;
while(!status) {
printf("Will wait for message\n");
tempBuffer = receiveMsg(1, &status);
}
if(status) {
// Received message
printf("Received process with id %d and pid %d\n", tempBuffer.data.id, tempBuffer.data.pid);
// Check if incoming process is a flag
if (tempBuffer.data.pid == -10)
{
// Break
printf("Empty priority queue (%d) and received flag\n", isEmpty(&PQueueHead));
break;
}
else {
// If process is not flag
tempPCB = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, tempPCB);
// Allocate memory to the new process
allocate_mem(tempPCB,outMemFile);
// Push process to the queue
push(&PQueueHead, tempPCB, tempPCB->remainingTime);
printf("Pushed process with id %d and pid %d\n", tempPCB->id, tempPCB->pid);
}
}
else {
printf("Empty priority queue and could not receive messsage\n");
}
}
status = 0;
tempBuffer = receiveMsg(0, &status);
while(status == 1) {
printf("Received process with id %d and pid %d\n", tempBuffer.data.id, tempBuffer.data.pid);
// Check for flag process
if (tempBuffer.data.pid == -10)
{
finish_scheduler = 1;
status = 0;
}
else {
// Not flag process
tempPCB = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, tempPCB);
// Allocate memory to the new process
allocate_mem(tempPCB,outMemFile);
// Push process to the queue
push(&PQueueHead, tempPCB, tempPCB->remainingTime);
printf("Pushed process with id %d and pid %d\n", tempPCB->id, tempPCB->pid);
status = 0;
tempBuffer = receiveMsg(0, &status);
}
}
PCB* currProcessPCB = (PCB *) malloc(sizeof(PCB));
int afterPop = pop(&PQueueHead, currProcessPCB);
printf("Successful popping (%d). Popped process with id %d and pid %d\n", afterPop, currProcessPCB->id, currProcessPCB->pid);
// Chech whether process was forked before
if (currProcessPCB->pid == -5) {
// Start process
startProcess(currProcessPCB, outLogFile);
printf("Started process with id %d and pid %d\n", currProcessPCB->id, currProcessPCB->pid);
}
else {
// Resume process
resumeProcess(currProcessPCB, outLogFile, 0);
}
succesful_exit_handler = 0;
// If termination flag is not set yet; i.e. more processes are still coming
if(!finish_scheduler) {
printf("Will wait for message\n");
status = 0;
tempBuffer = receiveMsg(1, &status);
}
else {
// No more processes are coming
// Wait for current process to terminate
int stat;
pid_t isCurrProccess = waitpid(currProcessPCB->pid, &stat, 0);
if ((isCurrProccess != currProcessPCB->pid) || !(WIFEXITED(stat))) {
printf("Exit code received from process: %d.\n", WEXITSTATUS(stat));
if (WIFSIGNALED(stat)) {
psignal(WTERMSIG(stat), "Exit signal:");
}
}
///////printf("Exit status from process %d.\n", WIFEXITED(stat));
///////printf("After sleep\n");
}
// If running process exits successfully
if (succesful_exit_handler) {
printf("Will finish process with id %d\n", currProcessPCB->id);
finishProcess(currProcessPCB, outLogFile,outMemFile);
}
if (status == 1) {
// A message was received
// Check for flag process
if (tempBuffer.data.pid != -10) {
// Stop running process
stopProcess(currProcessPCB, outLogFile, 0);
succesful_exit_handler = 0;
tempPCB = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, tempPCB);
// Allocate memory to the new process
allocate_mem(tempPCB,outMemFile);
// Push both processes into the priority queue
push(&PQueueHead, currProcessPCB, currProcessPCB->remainingTime);
push(&PQueueHead, tempPCB, tempPCB->remainingTime);
printf("Pushed process with id %d and pid %d\n", tempPCB->id, tempPCB->pid);
}
else {
// Stop and resume running process just to correctly calculate all its attributes
stopProcess(currProcessPCB, outLogFile, 0);
succesful_exit_handler = 0;
resumeProcess(currProcessPCB, outLogFile, 0);
printf("Will wait for process with pid %d to finish\n", currProcessPCB->pid);
// Wait for process to finish
int stat;
pid_t isCurrProccess = waitpid(currProcessPCB->pid, &stat, 0);
if ((isCurrProccess != currProcessPCB->pid) || !(WIFEXITED(stat))) {
printf("Exit code received from process: %d.\n", WEXITSTATUS(stat));
if (WIFSIGNALED(stat)) {
psignal(WTERMSIG(stat), "Exit signal:");
}
}
///////printf("Exit status from process %d.\n", WIFEXITED(stat));
///////printf("After sleep\n");
finishProcess(currProcessPCB, outLogFile,outMemFile);
printf("Finished process with id %d\n", currProcessPCB->id);
// Set termination flag
finish_scheduler = 1;
}
}
}
return;
}
void RR(FILE* outLogFile,FILE* outMemFile, int Quantum) {
printf("Running RR\n");
// Initializing ready queue
Queue readyQueue;
queueInit(&readyQueue, sizeof(PCB));
struct msgbuff tempBuffer;
PCB* tempPCB = NULL;
int status;
finish_scheduler = 0;
while(1) {
///////printf("Inside While\n");
// If queue is empty
if (getQueueSize(&readyQueue) == 0) {
// If the termination flag is 1; i.e. no more processes are coming
if(finish_scheduler) {
printf("Empty queue (%d) and finish flag is true\n", getQueueSize(&readyQueue));
break;
}
// Wait till you receive a message
status = 0;
while(!status) {
printf("Will wait for message\n");
tempBuffer = receiveMsg(1, &status);
}
if(status) {
// Received message
printf("Received process with id %d and pid %d\n", tempBuffer.data.id, tempBuffer.data.pid);
// Check if incoming process is a flag
if (tempBuffer.data.pid == -10) {
printf("Empty queue (%d) and received flag\n", getQueueSize(&readyQueue));
break;
}
else {
// If process is not flag
tempPCB = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, tempPCB);
// Allocate memory to the new process
allocate_mem(tempPCB,outMemFile);
// Push process to the queue
enqueue(&readyQueue, tempPCB);
printf("Enqueued process with id %d and pid %d\n", tempPCB->id, tempPCB->pid);
}
}
else {
printf("Empty queue and could not receive messsage\n");
}
}
status = 0;
tempBuffer = receiveMsg(0, &status);
while(status == 1) {
printf("Received process with pid %d\n", tempBuffer.data.pid);
// Check for flag process
if (tempBuffer.data.pid == -10)
{
finish_scheduler = 1;
status = 0;
}
else {
// Not flag process
tempPCB = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, tempPCB);
// Allocate memory to the new process
allocate_mem(tempPCB,outMemFile);
// Push process to the queue
enqueue(&readyQueue, tempPCB);
printf("Enqueued process with id %d\n", tempPCB->id);
status = 0;
tempBuffer = receiveMsg(0, &status);
}
}
PCB* currProcessPCB = (PCB *) malloc(sizeof(PCB));
int afterDeq = dequeue(&readyQueue, currProcessPCB);
printf("Successful dequeuing (%d) Dequeued process with id %d and pid %d\n", afterDeq, currProcessPCB->id, currProcessPCB->pid);
// Chech whether process was forked before
if (currProcessPCB->pid == -5) {
// Start process
startProcess(currProcessPCB, outLogFile);
printf("Started process with id and %d pid %d\n", currProcessPCB->id, currProcessPCB->pid);
}
else {
// Resume process
resumeProcess(currProcessPCB, outLogFile, 0);
}
// Check if remaining time of process fits wihtin a quantum
if (currProcessPCB->remainingTime <= Quantum) {
// Wait for current process to terminate
int stat;
pid_t isCurrProccess = waitpid(currProcessPCB->pid, &stat, 0);
if ((isCurrProccess != currProcessPCB->pid) || !(WIFEXITED(stat))) {
printf("Exit code received from process: %d.\n", WEXITSTATUS(stat));
if (WIFSIGNALED(stat)) {
psignal(WTERMSIG(stat), "Exit signal:");
}
}
///////printf("Exit status from process %d.\n", WIFEXITED(stat));
///////printf("After sleep\n");
// Extra check that process exited successfully
while (!succesful_exit_handler)
{
stopProcess(currProcessPCB, outLogFile, 1);
resumeProcess(currProcessPCB, outLogFile, 1);
int stat;
pid_t isCurrProccess = waitpid(currProcessPCB->pid, &stat, 0);
if ((isCurrProccess != currProcessPCB->pid) || !(WIFEXITED(stat))) {
printf("Exit code received from process: %d.\n", WEXITSTATUS(stat));
if (WIFSIGNALED(stat)) {
psignal(WTERMSIG(stat), "Exit signal:");
}
}
///////printf("Exit status from process %d.\n", WIFEXITED(stat));
///////printf("After sleep\n");
}
finishProcess(currProcessPCB, outLogFile,outMemFile);
}
else {
// If process remaining time does not fit in a quantum
sleep(Quantum);
// After quantum
printf("Stopping process with id %d\n", currProcessPCB->id);
stopProcess(currProcessPCB, outLogFile, 0);
// Receive any process in the message queue
status = 0;
tempBuffer = receiveMsg(0, &status);
while(status == 1) {
printf("Received process with pid %d\n", tempBuffer.data.pid);
// Check for flag process
if (tempBuffer.data.pid == -10)
{
finish_scheduler = 1;
status = 0;
}
else {
tempPCB = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, tempPCB);
// Allocate memory to the new process
allocate_mem(tempPCB,outMemFile);
enqueue(&readyQueue, tempPCB);
printf("Enqueued process with id %d", tempPCB->id);
status = 0;
tempBuffer = receiveMsg(0, &status);
}
}
enqueue(&readyQueue, currProcessPCB);
}
}
return;
}
void HPF(FILE* outLogFile, FILE* outMemFile) {
printf("Running HPF\n");
// Initializing ready queue
PNode* ReadyQueue = NULL;
struct msgbuff tempBuffer;
PCB* temp_process_pcb = (PCB *) malloc(sizeof(PCB));
int status;
finish_scheduler = 0;
while(1) {
///////printf("Inside While\n");
if (isEmpty(&ReadyQueue)) {
// If the termination flag is 1; i.e. no more processes are coming
if(finish_scheduler) {
printf("Empty priority queue (%d) and finish flag is true\n", isEmpty(&ReadyQueue));
break;
}
// Wait till you receive a message
status = 0;
while(!status) {
printf("Will wait for message\n");
tempBuffer = receiveMsg(1, &status);
}
if(status) {
// Received message
printf("Received process with id %d and pid %d\n", tempBuffer.data.id, tempBuffer.data.pid);
// Check if incoming process is a flag
if (tempBuffer.data.pid == -10)
{
printf("Empty priority queue (%d) and received flag\n", isEmpty(&ReadyQueue));
break;
}
else {
// If process is not flag
temp_process_pcb = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, temp_process_pcb);
// Allocate memory to the new process
allocate_mem(temp_process_pcb,outMemFile);
push(&ReadyQueue, temp_process_pcb, temp_process_pcb->priority);
// Push process to the priority queue
printf("Pushed process with id %d and pid %d\n", temp_process_pcb->id, temp_process_pcb->pid);
}
}
else {
printf("Empty priority queue and could not receive messsage\n");
}
}
status = 0;
tempBuffer = receiveMsg(0, &status);
while(status == 1) {
printf("Received process with pid %d\n", tempBuffer.data.pid);
// Check for flag process
if (tempBuffer.data.pid == -10)
{
finish_scheduler = 1;
status = 0;
}
else {
// Not flag process
temp_process_pcb = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, temp_process_pcb);
// Allocate memory to the new process
allocate_mem(temp_process_pcb,outMemFile);
// Push process to the priority queue
push(&ReadyQueue, temp_process_pcb, temp_process_pcb->priority);
printf("Pushed process with id %d and pid %d\n", temp_process_pcb->id, temp_process_pcb->pid);
status = 0;
tempBuffer = receiveMsg(0, &status);
}
}
PCB* currProcessPCB = (PCB *) malloc(sizeof(PCB));
int afterPop = pop(&ReadyQueue, currProcessPCB);
printf("Successful popping (%d). Popped process with id %d and pid %d\n", afterPop, currProcessPCB->id, currProcessPCB->pid);
if (currProcessPCB->pid == -5) {
startProcess(currProcessPCB, outLogFile);
printf("Started id %d pid %d\n", currProcessPCB->id, currProcessPCB->pid);
}
// Wait for current process to terminate
int stat;
pid_t isCurrProccess = waitpid(currProcessPCB->pid, &stat, 0);
if ((isCurrProccess != currProcessPCB->pid) || !(WIFEXITED(stat))) {
printf("Exit code received from process: %d.\n", WEXITSTATUS(stat));
if (WIFSIGNALED(stat)) {
psignal(WTERMSIG(stat), "Exit signal:");
}
}
///////printf("Exit status from process %d.\n", WIFEXITED(stat));
///////printf("After sleep\n");
// Extra check on successful termination of the process
while (!succesful_exit_handler)
{
stopProcess(currProcessPCB, outLogFile, 1);
resumeProcess(currProcessPCB, outLogFile, 1);
int stat;
pid_t isCurrProccess = waitpid(currProcessPCB->pid, &stat, 0);
if ((isCurrProccess != currProcessPCB->pid) || !(WIFEXITED(stat))) {
printf("Exit code received from process: %d.\n", WEXITSTATUS(stat));
if (WIFSIGNALED(stat)) {
psignal(WTERMSIG(stat), "Exit signal:");
}
}
///////printf("Exit status from process %d.\n", WIFEXITED(stat));
///////printf("After sleep\n");
}
finishProcess(currProcessPCB, outLogFile,outMemFile);
status = 0;
tempBuffer = receiveMsg(0, &status);
while(status == 1) {
printf("Received process with pid %d\n", tempBuffer.data.pid);
// Check for flag process
if (tempBuffer.data.pid == -10)
{
finish_scheduler = 1;
status = 0;
}
else {
// Not flag
temp_process_pcb = (PCB *) malloc(sizeof(PCB));
equate(&tempBuffer.data, temp_process_pcb);
// Allocate memory to the new process
allocate_mem(temp_process_pcb,outMemFile);
push(&ReadyQueue, temp_process_pcb, temp_process_pcb->priority);
// Push process to the priority queue
printf("Pushed process with id %d and pid %d\n", temp_process_pcb->id, temp_process_pcb->pid);
status = 0;
tempBuffer = receiveMsg(0, &status);
}
}
}
return;
}
//printing free chuncks lists
void DisplayChunkLists() {
int chunck = 8;
for (int i = 0; i < 8; i++) {
printf("List Number %d: and it's chunck is: %d \n", i, chunck);
chunck = chunck*2;
display(&freeChunks[i]);
printf("\n");
}
}
|
C
|
//
// Created by Bori on 2/25/2020.
//
#include <stdlib.h>
#include <stdio.h>
#include "list.h"
dlList createDLList() {
dlList newdlList;
newdlList.sentinel = createNodeWithSelfReference(0);
return newdlList;
}
void addFirst(dlList *mydlList, int value) {
node *newNode = createNode(value, mydlList->sentinel, mydlList->sentinel->next);
mydlList->sentinel->next->prev = newNode;
mydlList->sentinel->next = newNode;
if (mydlList->sentinel->prev == mydlList->sentinel) {
mydlList->sentinel->prev = newNode; //if list was empty
}
}
void addLast(dlList *mydlList, int value) {
node *newNode = createNode(value, mydlList->sentinel->prev, mydlList->sentinel);
mydlList->sentinel->prev->next = newNode;
mydlList->sentinel->prev = newNode;
if (mydlList->sentinel->next == mydlList->sentinel) {
mydlList->sentinel->next = newNode; //if list was empty
}
}
void deleteFirst(dlList *mydlList) {
mydlList->sentinel->next = mydlList->sentinel->next->next;
if (mydlList->sentinel->next == mydlList->sentinel) {
mydlList->sentinel->prev = mydlList->sentinel;
}
}
void deleteLast(dlList *mydlList) {
mydlList->sentinel->prev = mydlList->sentinel->prev->prev;
if (mydlList->sentinel->prev == mydlList->sentinel) {
mydlList->sentinel->next = mydlList->sentinel;
}
}
void deleteAll(dlList *mydlList) {
node *curFirst;
while (mydlList->sentinel->next != mydlList->sentinel) {
curFirst = mydlList->sentinel->next;
mydlList->sentinel->next = mydlList->sentinel->next->next;
free(curFirst);
}
mydlList->sentinel->prev = mydlList->sentinel;
}
void deleteValue(dlList *mydlList, int value) {
node *curNode = mydlList->sentinel->next;
node *prevNode = mydlList->sentinel;
while (curNode != mydlList->sentinel) {
if (curNode->data ==
value) //remark that in all of the 3 cases prevNode is constant/it's value doesn't matter anymore
{
prevNode->next = curNode->next;
curNode->next->prev = prevNode;
free(curNode);
curNode = prevNode->next;
} else {
prevNode = curNode;
curNode = curNode->next;
}
}
}
void printAll(dlList *mydlList, FILE *outFile) {
if (mydlList->sentinel->next == mydlList->sentinel) fprintf(outFile, "List is empty\n");
else {
node *curNode = mydlList->sentinel->next;
while (curNode != mydlList->sentinel) {
fprintf(outFile, "%d ", curNode->data);
curNode = curNode->next;
}
fprintf(outFile, "\n");
}
}
void printFirstX(dlList *mydlList, int x, FILE *outFile) {
if (mydlList->sentinel->next == mydlList->sentinel) fprintf(outFile, "List is empty\n");
else {
int countPrintedElem = 0;
node *curNode = mydlList->sentinel->next;
while (countPrintedElem < x && curNode != mydlList->sentinel) {
fprintf(outFile, "%d ", curNode->data);
curNode = curNode->next;
countPrintedElem++;
}
fprintf(outFile, "\n");
}
}
static void printLastX_recusive(node *curNode, node *sentinel, int x, FILE *outfile) {
if (curNode != sentinel) {
if (x == 1) {
fprintf(outfile, "%d ", curNode->data);
} else {
printLastX_recusive(curNode->prev, sentinel, x - 1, outfile);
fprintf(outfile, "%d ", curNode->data);
}
}
}
void printLastX(dlList *mydlList, int x, FILE *outFile) {
if (mydlList->sentinel->prev == mydlList->sentinel) {
fprintf(outFile, "List is empty\n");
} else {
printLastX_recusive(mydlList->sentinel->prev, mydlList->sentinel, x, outFile);
fprintf(outFile, "\n");
}
}
|
C
|
#include "find.h"
#include <stdio.h>
#include <stdlib.h>
char **blocks_array = NULL;
unsigned int num_blocks = 0;
unsigned int initialized = 0;
char *search_dir = NULL;
char *file_search = NULL;
char *tmp_name = NULL;
int create_table(unsigned int size) {
if(initialized == 1) {
fprintf(stderr, "library already initialized\n");
return -1;
}
num_blocks = size;
blocks_array = calloc(num_blocks, sizeof(char*));
initialized = 1;
return 0;
}
int set_search_directory(char *dir, char *file, char *tmp_file_name) {
search_dir = dir;
file_search = file;
tmp_name = tmp_file_name;
return 0;
}
int search_directory() {
char buf[256];
snprintf(buf, sizeof buf, "find %s -name %s > %s", search_dir, file_search, tmp_name);
int find_status = system(buf);
if(find_status != 0)
return find_status;
return 0;
}
long get_file_size(FILE *f) {
fseek(f, 0L, SEEK_END);
long file_size = ftell(f);
rewind(f);
return file_size;
}
int load_file(char ** buffer, char *file_path) {
FILE * f = fopen (file_path, "rb");
if(!f) {
fprintf(stderr, "problem with reading file\n");
return -1;
}
long file_size = get_file_size(f);
*buffer = calloc(file_size, sizeof(char));
fread(*buffer, sizeof(char), file_size, f);
fclose(f);
return 0;
}
int last_search_to_array() {
return file_to_array(tmp_name);
}
int file_to_array(char *file_name) {
for(int i = 0; i < num_blocks; ++i) {
if(blocks_array[i] == NULL) {
int load_status = load_file(&blocks_array[i], file_name);
if(load_status < 0) {
fprintf(stderr, "cant load into array, error\n");
return load_status;
}
return i;
}
}
fprintf(stderr, "cant load into array, array is full\n");
return -1;
}
char *get_block(int idx) {
return blocks_array[idx];
}
int delete_block(int idx) {
free(blocks_array[idx]);
blocks_array[idx] = NULL;
return 0;
}
void delete_array() {
for(int i = 0; i < num_blocks; ++i) {
delete_block(i);
}
free(blocks_array);
}
|
C
|
#include "gpio.h"
struct Morse { char letter; const char* symbol; } code[] = {
{ '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', "--.." },
{ ' ', " " },
{ '0', "-----" },
{ '1', ".----" },
{ '2', "..---" },
{ '3', "...--" },
{ '4', "....-" },
{ '5', "....." },
{ '6', "-...." },
{ '7', "--..." },
{ '8', "---.." },
{ '9', "----." }
};
static int nchars = sizeof(code) / sizeof (struct Morse);
// how fast do you want to go?
// a value of 300000 takes about a minute to say "raspberry alpha omega"
// smaller numbers make it faster
#define dot_pause 300000
#define dash_pause (dot_pause * 3)
#define gap_pause dot_pause
#define letter_pause (dot_pause * 3)
#define word_pause (gap_pause * 7)
void switch_off(int duration) {
raspi_okled_set(0);
raspi_timer_wait(duration);
}
void switch_on(int duration) {
raspi_okled_set(1);
raspi_timer_wait(duration);
}
void morse_glyph(char c) {
switch(c) {
case '.':
switch_on(dot_pause);
break;
case '-':
switch_on(dash_pause);
break;
default:
raspi_timer_wait(word_pause);
break;
}
switch_off(gap_pause);
}
void morse_symbol(const char* symbol) {
struct Crate* crate;
for (char c = *symbol; c != 0; c = *++symbol) {
morse_glyph(c);
}
raspi_timer_wait(letter_pause);
}
void morse_char(char c) {
for (int i = 0; i < nchars; ++i) {
if (c == code[i].letter) {
morse_symbol(code[i].symbol);
return;
}
}
}
void morse_string(const char* message) {
for (char c = *message; c != 0; c = *++message) {
morse_char(c);
}
}
void flash_dots(int ndots) {
for (int i = 0; i < ndots; ++i) {
morse_glyph('.');
}
raspi_timer_wait(letter_pause);
}
void halt(const char* message) {
for (;;) {
morse_string(message);
}
}
|
C
|
#include <stdio.h>
union uniao{
int x;
float y;
}uniao;
int main(void) {
int e=0, n=0;
float n1=0;
printf("Voce deseja entrar com um numero inteiro(1) ou flutuante(2)?\n");
scanf("%d", &e);
if(e==1){
printf("\nDigite seu numero: ");
scanf("%d", &n);
uniao.x = n;
printf("\nSeu numero em ponto flutuante e: %f", uniao.y);
}
if(e==2){
printf("\nDigite seu numero: ");
scanf("%f", &n1);
uniao.y=n1;
printf("\nSeu numero em inteiro e: %d", uniao.x);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "graph.h"
static int *pre, *low;
static int *stack;
static int cnt;
static int k, n;
TG *cria(void) {
TG *g = (TG *) malloc(sizeof(TG));
g->prim = NULL;
return g;
}
TNO *busca_no(TG *g, int n) {
TNO *p = g->prim;
while ((p) && (p->id_no != n)) {
p = p->prox_no;
}
return p;
}
void insere_no(TG *g, int no) {
TNO *p = busca_no(g, no);
if (p)return;
p = (TNO *) malloc((sizeof(TNO)));
p->id_no = no;
p->prim_viz = NULL;
p->prox_no = g->prim;
g->prim = p;
}
TViz *busca_aresta(TG *g, int no1, int no2) {
TNO *viz1 = busca_no(g, no1);
if (!viz1)return NULL;
TNO *viz2 = busca_no(g, no2);
if (!viz2)return NULL;
TViz *p = viz1->prim_viz;
while ((p) && (p->id_viz != no2)) {
p = p->prox_viz;
}
return p;
}
void insere_aresta(TG *g, int id1, int id2, int custo) {
TNO *p1 = busca_no(g, id1);
if (!p1)return;
TNO *p2 = busca_no(g, id2);
if (!p2)return;
TViz *v = busca_aresta(g, id1, id2);
if (v) {
v->custo = custo;
return;
}
v = (TViz *) malloc(sizeof(TViz));
v->id_viz = id2;
v->custo = custo;
v->prox_viz = p1->prim_viz;
p1->prim_viz = v;
}
void imprime(TG *g) {
TNO *p = g->prim;
while (p) {
printf("%d:\n", p->id_no);
TViz *v = p->prim_viz;
while (v) {
printf("viz: %d \t custo:%d\n", v->id_viz, v->custo);
v = v->prox_viz;
}
p = p->prox_no;
}
}
void retira_aresta(TG *g, int id1, int id2) {
TNO *p1 = busca_no(g, id1);
if (!p1)return;
TNO *p2 = busca_no(g, id2);
if (!p2)return;
TViz *v = p1->prim_viz, *ant = NULL;
while ((v) && (v->id_viz != id2)) {
ant = v;
v = v->prox_viz;
}
if (!v)return;;
if (!ant)
p1->prim_viz = v->prox_viz;
else
ant->prox_viz = v->prox_viz;
free(v);
}
void retira_no(TG *g, int id) {
TNO *p = g->prim, *ant = NULL;
while ((p) && p->id_no != id) {
ant = p;
p = p->prox_no;
}
if (!p) return;
TViz *v = p->prim_viz;
while (v) {
retira_aresta(g, id, v->id_viz);
v = p->prim_viz;
}
if (!ant) {
g->prim = p->prox_no;
} else {
ant->prox_no = p->prox_no;
}
free(p);
}
void libera(TG *g) {
TNO *p = g->prim;
while (p) {
TViz *v = p->prim_viz;
while (v) {
TViz *t = v;
v = v->prox_viz;
free(t);
}
TNO *q = p;
p = p->prox_no;
free(q);
}
free(g);
}
static int visit[1000] = {0};
// gamb
int checkOrientation(int *values, int total_nodes) {
int oriented = 0;
int j;
for (j = 0; j < total_nodes; j++) {
if (values[j]) {
oriented = 1;
break;
}
}
if (oriented) {
printf("orientado\n");
} else {
printf("nao orientado\n");
}
return oriented;
}
static void reachR(TG *G, int check) {
visit[check] = 1;
TNO *p = G->prim;
while (p->id_no != check) {
p = p->prox_no;
}
TViz *viz = p->prim_viz;
while (viz) {
if (visit[viz->id_viz] == 0) {
reachR(G, viz->id_viz);
}
viz = viz->prox_viz;
}
}
int graphBFS(TG *G, int from, int searched) {
int i;
for (i = 0; i < 1000; ++i) {
visit[i] = 0;
}
reachR(G, from);
if (visit[searched] == 0) {
return 0;
} else {
return 1;
}
}
int graphStillConnected(TG *g, int total) {
int i, j;
for (i = 0; i < 1000; ++i) {
visit[i] = 0;
}
reachR(g, 0);
for (j = 0; j < total; ++j) {
if (visit[j] == 0) {
return 0;
}
}
return 1;
}
int checkValidBridge(TG *g, int from, int to, int total) {
if (from > to) {
return 0;
}
retira_aresta(g, from, to);
retira_aresta(g, to, from);
int ans = !graphStillConnected(g, total);
insere_aresta(g, from, to, 1);
insere_aresta(g, to, from, 1);
return ans;
}
// gamb
TViz *copyViz(TViz *viz) {
if (!viz) {
return;
}
TViz *novo = NULL;
TViz *p = viz;
while (p) {
TViz *aux = malloc(sizeof(TViz));
aux->id_viz = p->id_viz;
aux->custo = 1;
aux->prox_viz = novo;
novo = aux;
p = p->prox_viz;
}
return novo;
}
void freeViz(TViz *viz) {
if (!viz) {
return;
}
while (viz) {
TViz *prox = viz->prox_viz;
free(viz);
viz = prox;
}
}
void printBridges(TG *g, int total) {
TNO *p = g->prim;
int i = 1;
while (p) {
TViz *viz = copyViz(p->prim_viz);
TViz *t = viz;
while (t) {
int id_no = p->id_no;
int id_viz = t->id_viz;
if (checkValidBridge(g, id_no, id_viz, total)) {
printf("bridge %d: %d -> %d\n", i, id_no + 1, id_viz + 1);
i++;
}
t = t->prox_viz;
}
liberaVizinho(viz);
p = p->prox_no;
}
}
void liberaVizinho(TViz *viz) {
while(viz){
TViz *p = viz;
viz = viz->prox_viz;
free(p);
}
}
// gamb
static void reachArticulation(TG *G, int check, int tested) {
if (check == tested) {
return;
}
visit[check] = 1;
TNO *p = G->prim;
while (p->id_no != check) {
p = p->prox_no;
}
TViz *viz = p->prim_viz;
while (viz) {
if (visit[viz->id_viz] == 0) {
reachArticulation(G, viz->id_viz, tested);
}
viz = viz->prox_viz;
}
}
int graphStillConnectedForArticulation(TG *g, int total, int tested) {
int i;
for (i = 0; i < 1000; ++i) {
visit[i] = 0;
}
if (tested == 0) {
reachArticulation(g, 1, tested);
} else {
reachArticulation(g, 0, tested);
}
for (int j = 0; j < total; j++) {
if (visit[j] == 0 && j != tested) {
return 0;
}
}
return 1;
}
void printArticulations(TG *g, int total) {
int i;
for (i = 0; i < total; i++) {
if (!graphStillConnectedForArticulation(g, total, i)) {
printf("articulation point: %d\n", i + 1);
}
}
}
// gamb
static void reachClusters(TG *G, int check) {
printf(" %d", check + 1);
visit[check] = 1;
TNO *p = G->prim;
while ((p) && p->id_no != check) {
p = p->prox_no;
}
TViz *viz = p->prim_viz;
while (viz) {
if (visit[viz->id_viz] == 0) {
reachClusters(G, viz->id_viz);
}
viz = viz->prox_viz;
}
}
void printClusters(TG *g, int total) {
int i, j;
for (i = 0; i < 1000; ++i) {
visit[i] = 0;
}
int count = 1;
for (j = 0; j < total; ++j) {
if (!visit[j]) {
printf("cluster %d:", count++);
reachClusters(g, j);
printf("\n");
}
}
}
int Graphsct(TG *grafo, int sc[], int totalVertices) {
int v;
pre = malloc(totalVertices * sizeof(int));
low = malloc(totalVertices * sizeof(int));
stack = malloc(totalVertices * sizeof(int));
for (v = 0; v < totalVertices; v++) {
pre[v] = sc[v] = -1;
}
cnt = k = n = 0;
for (v = 0; v < totalVertices; v++) {
if (pre[v] == -1) {
pre[v] = v;
strongR(grafo, v, sc);
}
}
free(pre);
free(low);
free(stack);
return k;
}
void strongR(TG *grafo, int v, int sc[]) {
int w, u, min;
TViz *a;
pre[v] = cnt++;
min = pre[v];
stack[n++] = v;
TNO *no = busca_no(grafo, v);
for (a = no->prim_viz; a; a = a->prox_viz) {
w = a->id_viz;
if (pre[w] == -1) {
strongR(grafo, w, sc);
if (low[w] < min) min = low[w];
} else if (pre[w] < pre[v - 1] && sc[w] == -1) {
if (pre[w] < min)min = pre[w];
}
}
low[v] = min;
if (low[v] == pre[v]) {
do {
u = stack[--n];
sc[u] = k;
} while (u != v);
k++;
}
}
void show_strong_components(TG *grafo, int sc[], int totaldeVertices) {
int iterator, gambiarra, dh;
gambiarra = Graphsct(grafo, sc, totaldeVertices);
for (iterator = 0; iterator < gambiarra; iterator++) {
for (dh = 1; dh <= totaldeVertices; dh++) {
if (sc[dh - 1] == iterator) printf("%d ", dh);
}
printf("\n");
}
}
|
C
|
/****************************************************************************
Jamie Zhang
cs12xre
Christopher Cabreros
cs12xjm
CSE 12, W15
March 12
Assignment 9
File Name: Tree.c
Description: Contains all the constructors and functions for Tree and
TNode. The functions allow the insertion, removal, and
lookup of a TNode into the tree by reading and writing to
a disk file, as well as to write out the whole tree or a
TNode.
****************************************************************************/
#include <stdlib.h>
#include <string.h>
#include "Tree.h"
// debug messages
static const char ALLOCATE[] = " - Allocating]\n";
static const char COST_READ[] = "[Cost Increment (Disk Access): Reading ";
static const char COST_WRITE[] = "[Cost Increment (Disk Access): Writing ";
static const char DEALLOCATE[] = " - Deallocating]\n";
static const char TREE[] = "[Tree ";
template <class Whatever>
int Tree<Whatever>::debug_on = 0;
template <class Whatever>
long Tree<Whatever>::cost = 0;
template <class Whatever>
long Tree<Whatever>::operation = 0;
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define THRESHOLD 2
template <class Whatever>
ostream & operator << (ostream &, const TNode<Whatever> &);
/*-----------------------------------------------------------------------
Name: TNode
Description: Nodes holding the data that will be inserted into
the Tree.
Data Fields: data - data/object going into the tree
height - height of the node
balance - balance of the node
left - location in the datafile of the left child
right - location in the datafile of the right child
this_position - location in the datafile of the
current node
-----------------------------------------------------------------------*/
template <class Whatever>
struct TNode {
// friends:
// data fields:
Whatever data;
long height;
long balance;
offset left;
offset right;
offset this_position; // current position
// function fields:
TNode () : height (0), balance (0), left (0), right (0),
this_position (0) {}
// to declare the working TNode in Tree's Remove
TNode (Whatever & element) : data (element), height (0), balance (0),
left (0), right (0), this_position (0) {}
TNode (Whatever &, fstream *, long &); // to add new node to disk
TNode (const offset &, fstream *); // to read node from disk
unsigned long Insert (Whatever &, fstream *, long &, offset &);
unsigned long Lookup (Whatever &, fstream *);
void Read (const offset &, fstream *); // read node from disk
unsigned long Remove (TNode<Whatever> &, fstream *, long &, offset &,
long fromSHB = FALSE);
void ReplaceAndRemoveMax (TNode<Whatever> &, fstream *, offset &);
void SetHeightAndBalance (fstream *, offset &);
void Write (fstream *) const; // update node to disk
ostream & Write_AllTNodes (ostream &, fstream *) const;
};
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: Set_Debug_On
Purpose: Turns debug messages on.
Description: Sets value of the debug variable to true.
Input: void - no input
Result: void - no output
-----------------------------------------------------------------------*/
template <class Whatever>
void Tree<Whatever> :: Set_Debug_On(){
debug_on = 1;
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: Set_Debug_Off
Purpose: Turns debug messages off.
Description: Sets value of the debug variable to false.
Input: void - no input
Result: void - no output
-----------------------------------------------------------------------*/
template <class Whatever>
void Tree<Whatever> :: Set_Debug_Off(){
debug_on = 0;
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: Insert
Purpose: Inserts a TNode into the tree.
Description: If the tree is empty, we insert the root node and
write it to the tree. Otherwise, we read in the root
node and delegate the inserting to its Insert.
Input: element - the data we want to insert into the tree
Result: long - 1 if the insert succeeded, 0 if the insert
failed
-----------------------------------------------------------------------*/
template <class Whatever>
unsigned long Tree<Whatever> :: Insert (Whatever & element) {
long inserted = 0; //flag for if the item was successfully inserted or not
//check if tree is empty
if(occupancy == 0) {
//insert root node
TNode<Whatever> root (element, fio, occupancy);
inserted = 1;
}
else {
//gets the root node
TNode<Whatever> readRootNode (root, fio);
//delegate to the root node's insert
inserted = readRootNode.Insert(element, fio, occupancy, root);
}
//increments operation because a tree operation occurred
IncrementOperation();
return inserted;
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: ReplaceAndRemoveMax
Purpose: Removes a node and replaces it with its predecessor
node.
Description: Keep recursively calling ReplaceAndRemoveMax on the
right child of the current node until we find a node
without a right child. Replace the data in the node
we want to remove with the data in the node we just
found (the predecessor node). Remove the predecessor
node from the tree.
Input: targetTNode - the a reference to the TNode we want to
remove from the tree
fio - the filestream corresponding to the datafile
where the Tree is stored on disk
PositionInParent - a reference to the TNode position
in the parent TNode used to get to the
current TNode's offset in the datafile
Result: void - no output
-----------------------------------------------------------------------*/
template <class Whatever>
void TNode<Whatever> :: ReplaceAndRemoveMax (TNode<Whatever> & targetTNode,
fstream * fio, offset & PositionInParent) {
//keep going right until you find a leaf
if (right){
TNode<Whatever> rightChild (right, fio);
rightChild.ReplaceAndRemoveMax(targetTNode, fio, right);
//set the height and balance after the change in positions
SetHeightAndBalance(fio, PositionInParent);
}
//otherwise set the data of the targetTNode to current data,
//set pointer to null, and delete the node
else{
//replace the data into the target TNode
targetTNode.data = data;
//assign children correctly, if possible
PositionInParent = left;
}
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: Remove
Purpose: Removes a node from the tree.
Description: If the node we want to remove is the current node,
remove it and replace it with its child if it has 1
child, set it to null if it has 0 children, or call
RARM if it has 2 children. Otherwise, if the node
we want to remove is greater or less than the
current node, go left or right depending and call
Remove recursively on the current node's child if
it exists. If the child doesn't exist, the item isn't
in the tree and we can't remove it.
Input: elementTNode - the a reference to the TNode we want to
remove from the tree
fio - the filestream corresponding to the datafile
where the Tree is stored on disk
occupancy - the occupancy of the tree
PositionInParent - a reference to the TNode position
in the parent TNode used to get to the
current TNode's offset in the datafile
Result: long - 1 if the remove succeeded, 0 if the remove
failed
-----------------------------------------------------------------------*/
template <class Whatever>
unsigned long TNode<Whatever> :: Remove (TNode<Whatever> & elementTNode,
fstream * fio, long & occupancy, offset & PositionInParent,
long fromSHB) {
unsigned long result = 0; //result of the many function calls
//case left
if (data > elementTNode.data){
//check if left is null
if (!left){
result = 0;
}
else {
//make a left child and recursively call remove
TNode<Whatever> leftChild (left, fio);
result = leftChild.Remove(elementTNode, fio, occupancy, left,
fromSHB);
//update the tree, if not from setHeightAndBalance
if (!fromSHB){
SetHeightAndBalance(fio, PositionInParent);
}
}
}
//case center
else if (data == elementTNode.data){
//assign data to element TNode
elementTNode.data = data;
//update occupancy
occupancy--;
//tell driver of successful operation
result = 1;
//case 1 left child
if (left && !right){
//set positionInParent to the left
PositionInParent = left;
}
//case 1 right child
else if (!left && right){
//set positionInParent to the right
PositionInParent = right;
}
//case 2 children
else if (left && right){
//read the left TNode
TNode<Whatever> leftChild(left, fio);
//call replaceAndRemoveMax on the left node
leftChild.ReplaceAndRemoveMax(*this, fio, left);
Write(fio);
}
//case no children
else{
//set positionInParent
PositionInParent = 0;
}
}
//case right
else{
//check if right is null
if (!right){
result = 0;
}
else{
//make a right child and recursively call remove
TNode<Whatever> rightChild (right, fio);
result = rightChild.Remove(elementTNode, fio, occupancy, right,
fromSHB);
//update the tree, if not from setHeightAndBalance
if (!fromSHB){
SetHeightAndBalance(fio, PositionInParent);
}
}
}
//tell driver result of the remove
return result;
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: Remove
Purpose: Removes a node from the tree.
Description: If the tree is empty, do nothing. Otherwise, delegate
to the root node's remove method.
Input: element - the item we want to remove from the tree.
Result: long - 1 if the remove was successful, 0 if the
remove failed
-----------------------------------------------------------------------*/
template <class Whatever>
unsigned long Tree<Whatever> :: Remove (Whatever & element) {
long removed = 0; //flag for if the item was successfully removed or not
//check if tree is empty
if (occupancy == 0){
//do nothing
}
//otherwise delegate to remove of the tree
else{
TNode<Whatever> tempNode(element);
//get the root node
TNode<Whatever> readRootNode(root, fio);
//delegate to the root node's remove
removed = readRootNode.Remove(tempNode, fio, occupancy, root, 0);
//change the element input parameter
element = tempNode.data;
//increment operations because a tree operation occured
IncrementOperation();
//check if the last node was removed
if (occupancy == 0){
ResetRoot();
}
}
return removed;
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: SetHeightAndBalance
Purpose: Updates the height and balance of the current node.
Description: Gets the height and balances of the current node's
children if they exist. Finds the height by finding
1 plus the tallest child's height. Finds the balance
by subtracting left child's height - right child's
height. If the balance is over 2 or less than -2,
remove and then reinsert the current node into the
tree.
Input: fio - the filestream corresponding to the datafile
where the Tree is stored on disk
PositionInParent - a reference to the TNode position
in the parent TNode used to get to the
current TNode's offset in the datafile
Result: void - no output
-----------------------------------------------------------------------*/
template <class Whatever>
void TNode<Whatever> :: SetHeightAndBalance (fstream * fio,
offset & PositionInParent) {
long leftHeight = -1; //variable holding the height of the left child
long rightHeight = -1; //variable holding the height of the right child
//checks if we have a left child
if(left){
//reads in the left child and grabs its height
TNode<Whatever> leftChild (left, fio);
leftHeight = leftChild.height;
}
//checks if we have a right child
if(right){
//reads in the right child and grabs its height
TNode<Whatever> rightChild (right, fio);
rightHeight = rightChild.height;
}
//sets the node's height to the height of the tallest child + 1
if(leftHeight >= rightHeight){
height = leftHeight + 1;
}
else{
height = rightHeight + 1;
}
//sets the balance to height of the left child - height of the right child
balance = leftHeight - rightHeight;
//if balance is over threshold
if (abs(balance) > THRESHOLD){
//declare a local variable for occupancy. because these operations
//should not affect tree occupancy
long occupancy = 0; //temp variable
TNode<Whatever> tempNode(data);
//remove this current node from the tree
Remove(*this, fio, occupancy, PositionInParent, 1);
TNode<Whatever> tempNode2(PositionInParent, fio);
//reinsert this back into the tree
tempNode2.Insert(tempNode.data, fio, occupancy, PositionInParent);
}
else{
//updates the file with the new heights and balances
Write(fio);
}
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: GetCost
Purpose: Returns cost.
Description: Returns the number of reads and writes we've done.
Input: None.
Result: long - value of cost
-----------------------------------------------------------------------*/
template <class Whatever>
long Tree <Whatever> :: GetCost () {
return cost;
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: GetOperation
Purpose: Returns operation.
Description: Returns the number of operations we've done.
Input: None.
Result: long - value of operation
-----------------------------------------------------------------------*/
template <class Whatever>
long Tree <Whatever> :: GetOperation () {
return operation;
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: IncrementCost
Purpose: Increments cost.
Description: Increments cost. Should be called whenever a read
or write occurs.
Input: None.
Result: void - no return
-----------------------------------------------------------------------*/
template <class Whatever>
void Tree <Whatever> :: IncrementCost () {
cost++;
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: IncrementOperation
Purpose: Increments operation.
Description: Increments operation. Should be called whenever Tree's
Insert, Remove, or Lookup is called.
Input: None.
Result: void - no return
-----------------------------------------------------------------------*/
template <class Whatever>
void Tree <Whatever> :: IncrementOperation () {
operation++;
}
/*-----------------------------------------------------------------------
Function Name: Tree<Whatever> :: ResetRoot
Purpose: Resets root to point to the end of the file.
Description: Moves the pointer to the end of the file and sets
root to be the position at the end of the file.
Input: None.
Result: void - no return
-----------------------------------------------------------------------*/
template <class Whatever>
void Tree <Whatever> :: ResetRoot () {
//sets root to be the end of the file
fio->seekg(0, ios::end);
root = fio->tellg();
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: Insert
Purpose: Inserts a node into the tree.
Description: If the data is the same as the data in the current
node, it's a duplicate insert and we want to replace
the old data with the new data. Otherwise, if the
data is greater or less than the current node's data,
we check the current node's right or left child
respectively and insert the data if the child is null.
Otherwise, we call Insert recursively.
Input: element - the data we want to insert into the tree
fio - the filestream corresponding to the datafile
where the Tree is stored on disk
occupancy - the occupancy of the tree
PositionInParent - a reference to the TNode position
in the parent TNode used to get to the
current TNode's offset in the datafile
Result: long - 1 if the insert succeeded, 0 if it failed
-----------------------------------------------------------------------*/
template <class Whatever>
unsigned long TNode<Whatever> :: Insert (Whatever & element, fstream * fio,
long & occupancy, offset & PositionInParent) {
long inserted = 0; //flag for if insert succeeded or not
//checks for duplicate insertion
if(data == element) {
//replaces old data with new data
data = element;
Write(fio);
inserted = 1;
}
//element is alphabetically less than current data, go left
else if(data > element) {
//insert a new node if the current node doesn't have a left child
if(!left){
//write a new node holding element
TNode<Whatever> newNode (element, fio, occupancy);
//updates left offset to point to the new node's position
left = newNode.this_position;
//updates height and balance since we inserted a new node
SetHeightAndBalance(fio, PositionInParent);
inserted = 1;
}
//recursively call Insert if we have a left child
else {
TNode<Whatever> leftChild (left, fio);
inserted = leftChild.Insert(element, fio, occupancy, left);
//updates height and balance since we inserted a new node
SetHeightAndBalance(fio, PositionInParent);
}
}
//element is alphabetically greater than current data, go right
else {
//insert a new node if the current node doesn't have a right child
if(!right)
{
//write a new node holding element
TNode<Whatever> newNode (element, fio, occupancy);
//updates right offset to point to the new node's position
right = newNode.this_position;
//updates height and balance since we inserted a new node
SetHeightAndBalance(fio, PositionInParent);
inserted = 1;
}
//recursively call Insert if we have a right child
else {
TNode<Whatever> rightChild (right, fio);
inserted = rightChild.Insert(element, fio, occupancy, right);
//updates height and balance since we inserted a new node
SetHeightAndBalance(fio, PositionInParent);
}
}
return inserted;
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: Lookup
Purpose: Looks to see if an item is in the tree.
Description: If the data is the same as the data in the current
node, we found what we're looking for! Otherwise,
check if the data is greater or less than the data
in the current node, check the right or left child
respectively. If there is no child, the item isn't
in the tree. Otherwise, recursively call Lookup
with the child.
Input: element - the data we want to look for in the tree
fio - the filestream corresponding to the datafile
where the Tree is stored on disk
Result: long - 1 if the lookup succeeded, 0 if it failed
-----------------------------------------------------------------------*/
template <class Whatever>
unsigned long TNode<Whatever> :: Lookup (Whatever & element, fstream * fio) {
long found = 0; //flag for if the lookup succeeded or not
//end the recursion if we found what we're looking for
if(data == element){
element = data; //return the data to the user
found = 1;
}
//element is alphabetically less than current data, go left
else if (data > element) {
//if there's no left child, the element isn't there
if(!left) {
return found;
}
//recursively call Lookup to check the left child & its children
else {
TNode<Whatever> leftChild (left, fio);
found = leftChild.Lookup(element, fio);
}
}
//element is alphabetically greater than current data, go right
else {
//if there's no right child, the element isn't there
if(!right) {
return found;
}
//recursively call Lookup to check the right child & its children
else {
TNode<Whatever> rightChild (right, fio);
found = rightChild.Lookup(element, fio);
}
}
return found;
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: Lookup
Purpose: Looks to see if an item is in the tree.
Description: If the tree is empty, do nothing. Otherwise, delegate
to the root node's Lookup.
Input: element - the data we want to look for in the tree
Result: long - 1 if the lookup succeeded, 0 if it failed
-----------------------------------------------------------------------*/
template <class Whatever>
unsigned long Tree<Whatever> :: Lookup (Whatever & element) const {
long found = 0; //flag for if lookup succeeded or not
//element isn't there if there are no nodes in the tree
if(occupancy == 0) {
//do nothing
}
else {
//reads in the root node
TNode<Whatever> readRootNode (root, fio);
found = readRootNode.Lookup(element, fio);
}
//increments operation because a tree operation occurred
IncrementOperation();
return found;
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: Read
Purpose: Reads in a TNode from a specified position in a file.
Description: Sets the read pointer to the position we want to
start reading from and reads in the data from the
file. Increments cost because a read occured.
Input: position - where in the file we want to start reading
fio - the filestream corresponding to the datafile
where the Tree is stored on disk
Result: void - no return
-----------------------------------------------------------------------*/
template <class Whatever>
void TNode<Whatever> :: Read (const offset & position, fstream * fio) {
//reads the TNode at the specified position
fio->seekg(position, ios::beg);
fio->read((char *)(this), sizeof(TNode<Whatever>));
//increments cost because a read occured
Tree<Whatever>::IncrementCost();
//debug
if(Tree<Whatever>::debug_on){
cerr << COST_READ << (const char*)this->data << "]\n";
}
}
/*-----------------------------------------------------------------------
Function Name: TNode's Read Constructor
Purpose: Creates a new TNode by reading it in from a specified
position in a file.
Description: Delegates all work to the Read() function.
Input: position - where in the file we want to start reading
fio - the filestream corresponding to the datafile
where the Tree is stored on disk
-----------------------------------------------------------------------*/
template <class Whatever>
TNode<Whatever> :: TNode (const offset & position, fstream * fio) {
//delegates work to Read() to read the TNode from the file
Read(position, fio);
}
/*-----------------------------------------------------------------------
Function Name: TNode's Write Constructor
Purpose: Creates a new TNode, initializes its values and writes
it to the file.
Description: Initializes all data fields and delegates all work to
the Write() function to actually write to the file.
Input: element - the data going into the node
fio - the filestream corresponding to the datafile
where the Tree is stored on disk
occupancy - the occupancy of the tree
-----------------------------------------------------------------------*/
template <class Whatever>
TNode<Whatever> :: TNode (Whatever & element, fstream * fio, long & occupancy):
data (element), height (0), balance (0), left (0), right (0) {
//increments the Tree's occupancy field
occupancy++;
//sets this_position to be the current end of the file
fio->seekp(0, ios::end);
this_position = fio->tellp();
//delegates work to Write() to write the TNode to the file
Write(fio);
}
/*-----------------------------------------------------------------------
Function Name: TNode<Whatever> :: Write
Purpose: Writes a TNode to its position in a file.
Description: Sets the write pointer to be where we want to write
the TNode to and then write the data to the file.
Increment cost because a write occurred.
Input: fio - the filestream corresponding to the datafile
where the Tree is stored on disk
Result: void - no return
-----------------------------------------------------------------------*/
template <class Whatever>
void TNode<Whatever> :: Write (fstream * fio) const {
//writes the TNode to the end of the file
fio->seekp(this_position, ios::beg);
fio->write((const char *)(this), sizeof(TNode<Whatever>));
//increments cost because a write occured
Tree<Whatever>::IncrementCost();
//debug
if(Tree<Whatever>::debug_on)
{
cerr <<COST_WRITE << (const char*)data << "]\n";
}
}
/*-----------------------------------------------------------------------
Function Name: Tree's Constructor
Purpose: Creates a new Tree and a new fstream object.
Description: Allocates memory for a new fstream object and
initializes all the data fields that need to be
initialized in the tree. If the file we're reading
from is empty, we want to reserve space to write out
root and occupancy. Otherwise, read in root and
occupancy from the file.
Input: datafile - the data file where all the info will be
stored
-----------------------------------------------------------------------*/
template <class Whatever>
Tree<Whatever> :: Tree (const char * datafile) :
fio (new fstream (datafile, ios :: out | ios :: in)){
static long counter; //static variable to track number of trees
tree_count = ++counter; //initialize tree_count
occupancy = 0; //initialize occupancy
root = 0; //initialize root
//debug
if(debug_on)
{
cerr << TREE << tree_count << ALLOCATE;
}
//gets the position of the beginning of the file
fio->seekg(0, ios::beg);
offset beginning = fio->tellg();
//gets the position of the end of the file
fio->seekg(0, ios::end);
offset ending = fio->tellg();
//file is empty, reserve space for root and occupancy
if(beginning == ending){
//move the write pointer to the beginning and write out
//root and occupancy
fio->seekp(0, ios::beg);
fio->write((const char *)(&root), sizeof(root));
fio->write((const char *)(&occupancy), sizeof(occupancy));
root = fio->tellp();
}
//file not empty, read in values
else{
//move the read pointer to the beginning and read in values of
//root and occupancy
fio->seekg(0, ios::beg);
fio->read((char *)(&root), sizeof(root));
fio->read((char *)(&occupancy), sizeof(occupancy));
}
}
template <class Whatever>
Tree<Whatever> :: ~Tree (void)
/***************************************************************************
% Routine Name : Tree :: ~Tree (public)
% File : Tree.c
%
% Description : deallocates memory associated with the Tree. It
% will also delete all the memory of the elements within
% the table.
***************************************************************************/
{
if(debug_on)
{
cerr << TREE << tree_count << DEALLOCATE;
}
//writes to the file the values of root and occupancy of the tree right
//before deallocating
fio->seekp(0, ios::beg);
fio->write((const char *)(&root), sizeof(root));
fio->write((const char *)(&occupancy), sizeof(occupancy));
delete fio;
} /* end: ~Tree */
template <class Whatever>
ostream & operator << (ostream & stream, const TNode<Whatever> & nnn) {
stream << "at height: :" << nnn.height << " with balance: "
<< nnn.balance << " ";
return stream << nnn.data << "\n";
}
template <class Whatever>
ostream & Tree<Whatever> :: Write (ostream & stream) const
/***************************************************************************
% Routine Name : Tree :: Write (public)
% File : Tree.c
%
% Description : This funtion will output the contents of the Tree table
% to the stream specificed by the caller. The stream could be
% cerr, cout, or any other valid stream.
%
% Parameters descriptions :
%
% name description
% ------------------ ------------------------------------------------------
% stream A reference to the output stream.
% <return> A reference to the output stream.
***************************************************************************/
{
long old_cost = cost;
stream << "Tree " << tree_count << ":\n"
<< "occupancy is " << occupancy << " elements.\n";
fio->seekg (0, ios :: end);
offset end = fio->tellg ();
// check for new file
if (root != end) {
TNode<Whatever> readRootNode (root, fio);
readRootNode.Write_AllTNodes (stream, fio);
}
// ignore cost when displaying nodes to users
cost = old_cost;
return stream;
}
template <class Whatever>
ostream & TNode<Whatever> ::
Write_AllTNodes (ostream & stream, fstream * fio) const {
if (left) {
TNode<Whatever> readLeftNode (left, fio);
readLeftNode.Write_AllTNodes (stream, fio);
}
stream << *this;
if (right) {
TNode<Whatever> readRightNode (right, fio);
readRightNode.Write_AllTNodes (stream, fio);
}
return stream;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void playerinfo();
void gamelayout();
int dice();
void game();
int control(int *,int *,int, int);
void snake();
void display();
void snakedecrement(int *, int *);
void ladderincrement(int *, int *);
void ladder();
char p1[30];
int i1 = 9;
int j1 = 0;
int i2 = 9;
int j2 = 0;
int ladder_ini[2];
int ladder_fin[2];
int snake_ini[2];
int snake_fin[2];
int main() {
printf("start\n");
playerinfo();
game();
return 0;
}
void playerinfo() {
printf("enter player1 name");
gets(p1);
printf("player symbol is 0\n");
}
void gamelayout() {
int layout[10][10] = {
{100,99,98,97,96,95,94,93,92,91},
{81,82,83,84,85,86,87,88,89,90},
{80,79,78,77,76,75,74,73,72,71},
{61,62,63,64,65,66,67,68,69,70},
{60,59,58,57,56,55,54,53,52,51},
{41,42,43,44,45,46,47,48,49,50},
{40,39,38,37,36,35,34,33,32,31},
{21,22,23,24,25,26,27,28,29,30},
{20,19,18,17,16,15,14,13,12,11},
{1,2,3,4,5,6,7,8,9,10}
};
}
void display(int *layout[10], int a, int b, int symbol) {
}
int dice() {
int rno;
srand(time(NULL));
rno = rand() % 6 + 1;
printf("Hi %d\n", rno);
return rno;
}
void game() {
char move;
int symbol = 0;
int score1 = 0;
int score2 = 0;
int die;
int count;
int *p1_row_pos;
int *p1_col_pos;
int *p2_row_pos;
int *p2_col_pos;
p1_row_pos = &i1;
p1_col_pos = &j1;
p2_row_pos = &i2;
p2_col_pos = &j2;
while (score1 < 100 && score2 < 100) {
if (symbol == 0) {
count = 0;
printf("players turn,press enter key to throw the dice");
scanf("%c",&move);
do {
count++;
die = dice();
printf("Player Value: %d\n",die);
score1 += control(p1_row_pos, p1_col_pos, 0, die);
snakedecrement(p1_row_pos, p1_col_pos);
ladderincrement(p1_row_pos, p1_col_pos);
display(*p1_row_pos,*p1_col_pos, symbol);
} while (die == 6 && count < 3);
symbol = 999;
}
else {
count = 0;
printf("computers turn \n");
char ch;
scanf("%c", &ch);
do {
count++;
die = dice();
printf("Computer Value: %d\n",die);
score2 += control(p2_row_pos, p2_col_pos, 0, die);
snakedecrement(p2_row_pos, p2_col_pos);
ladderincrement(p2_row_pos, p2_col_pos);
display(*p2_row_pos, *p2_col_pos, symbol);
} while (die == 6 && count < 3);
symbol = 0;
}
}
if (symbol == 0)
printf("computer is the winner");
else
printf("%s is the winner",p1);
}
int control( int *i, int *j, int k,int die) {
int score = 1;
if(*i == 9 && *j == 0)
k = 1;
while (k < die) {
if ((*i) % 2 != 0) {
while ((*j) <= 9) {
if (k < die)
k++;
else
break;
(*j)++;
score++;
}
if ((*j) > 9) {
(*j)--;
(*i)--;
}
}
else {
while ((*j) >= 0) {
if (k < die)
k++;
else
break;
(*j)--;
score++;
}
if((*j) < 0) {
(*j)++;
(*i)--;
}
}
}
return score;
}
void snake() {
int temp;
srand(time(NULL));
while (1) {
int r = rand() % 10;
if ( r % 2 == 0) {
snake_ini[0] = r;
break;
}
}
while(1) {
int r = rand() % 10;
if ( r % 2 == 0) {
snake_ini[1] = r;
break;
}
}
while(1) {
int r = rand() % 10;
if ( r % 2 == 0) {
snake_fin[1] = r;
break;
}
}
while(1) {
int r = rand() % 10;
if (snake_ini[0] == r && r % 2 != 0)
continue;
else {
snake_fin[0] = r;
break;
}
}
if (snake_fin[0] > snake_ini[0]) {
temp = snake_fin[0];
snake_fin[0] = snake_ini[0];
snake_ini[0] = temp;
}
}
void ladder() {
int temp;
srand(time(NULL));
while(1) {
int r = rand() % 10;
if ( r % 2 != 0) {
ladder_ini[0] = r;
break;
}
}
while(1) {
int r = rand() % 10;
if ( r % 2 != 0 ) {
ladder_ini[1] = r;
break;
}
}
while(1) {
int r = rand() % 10;
if ( r % 2 != 0) {
ladder_fin[1] = r;
break;
}
}
while(1) {
int r = rand() % 10;
if ( ladder_ini[0] == r && r % 2 == 0 )
continue;
else {
ladder_fin[0] = r;
break;
}
}
if ( ladder_fin[0] < ladder_ini[0]) {
temp = ladder_ini[0];
ladder_ini[0] = ladder_fin[0];
ladder_fin[0] = temp;
}
}
void snakedecrement(int *p_row, int *p_col) {
if(snake_ini[0] == *p_row && snake_ini[1] == *p_col) {
printf("you got bit by a snake\n");
*p_row = snake_fin[0];
*p_col = snake_fin[1];
}
}
void ladderincrement(int *p_row, int *p_col) {
if(ladder_ini[0] == *p_row && ladder_ini[1] == *p_col) {
printf("you got a ladder\n");
*p_row = ladder_fin[0];
*p_col = ladder_fin[1];
}
}
|
C
|
//
// searchTfIdf.c
// Assignment 2 COMP1927
// 3 June 2016
// Created by Winnie Zheng && Vivian Bakiris
//
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "searchTfIdf.h"
#include "prlist.h"
#include "searchPagerank.h"
#include "pagerank.h"
#include <math.h>
#include <sys/stat.h>
#include <errno.h>
//calculates tfIDF - needs to be called by main - taking in argc and argv arguments.
void calculateTfIdf(int argc, char *argv[]){
if(argc == 1) {
printf("nothing in command line \n");
return;
}
FILE *f = fopen("invertedIndex.txt", "r");
DLList urlFormat = tFData(argv, argc, 1);
if(DLListLength(urlFormat) == 0) { //empty list case.
printf("m8 none of these words share the same url ay\n");
return;
}
else {
//REMOVE .txt from LIST string urls.
DLList urlList = pageRankL(argv, argc);
DLListNode *temp = newDLListNode(urlFormat->first->data);
temp = urlFormat->first;
DLListNode *temp2 = newDLListNode(urlList->first->data);
temp2 = urlList->first;
while(temp != NULL && temp2 != NULL) {
temp->data = temp2->data;
temp = temp->next;
temp2 = temp2->next;
}
fclose(f);
}
//calculate Tf: iterate through every URl and calculate their tf - frequency of word occuring in current doc= curr->wordFreq for each curr
DLList tfD = tFData(argv, argc, 1);
double * tfIdf = malloc(100000000* sizeof(double *)); //used to store tfidf values
DLListNode *curr = newDLListNode(urlFormat->first->data);
DLListNode *curr2 = newDLListNode(tfD->first->data);
curr = urlFormat->first;
curr2 = tfD->first;
double N = (double)numUrls(); //get our TOTAL num Documents/urls in our colleciton
int i = 0;
double tf = 0;
double idf = 0;
int x = 1;
double totalF = 0;
//urls first -> break it down to EACH word by calling tfData function (incrementing x) -> for each word, store TF value
while(curr != NULL) { // we want to traverse through ALL urls that contain our query term
x = 1;
while(x < argc) { //where x++ will iterate through to the next word - must start at 1 because of argv
tfD = tFData(argv, argc, x);
tf = (double)curr2->wordFreq; //store tF value of current URL.
if(totalFreqWord(argv[x],1) == 0) {
break;
}
totalF = totalFreqWord(argv[x],1);
idf =log10(N/totalF);
tfIdf[i] += idf *tf; //each ith URL
// printf("ifIdf is %lf %lf %lf %lf %lf\n", tf, totalF, N, idf, tfIdf[i]); print all data out
x++; //iterate through to the next word.
}
//print out our TFIDF RANK for each url to stdout
printf("%s %lf\n", curr->data, tfIdf[i]);
curr = curr->next; //iterate through to the next URL
i++;
}
}
//this function takes in argv and argc files - which will find its values when called in totalFreq
DLList findUrlsForfreq (char *argv[], int argc) {
if(argc == 0) {
printf("nothing in command line ...\n");
return 0;
}
if(argc != 1) {
argc = argc-1;
}
DLList matchedUrls = newDLList();
FILE* f=fopen("invertedIndex.txt", "r");
//counter variables
int count = 0;
int j = 1;
int k = 0;
int x = 1;
char * urls = malloc(fsize("invertedIndex.txt")); //array used to scan through file
int test[argc];
//checks for existence of words entered in command line//
while(count < argc) {
k = 0;
while (fscanf(f,"%s", &urls[k]) != EOF) { //read through the file till the END of file
removegrammar(*argv);
normalize(*argv);
if((strcmp(*argv, &urls[k]) == 0)) { //if we've found our search word
test[j] = 0;
break;
}
else {
test[j] = 1;
}
k++;
}
count++;
j++;
fclose(f);
}
j = 0;
while(j < argc) {
if(test[j] == 1) {
printf("no urls matching all search words\n");
return 0;
}
j++;
}
//if all our words entered on command line exist... proceed:
count = 0;
x = 1;
fclose(f); //after test scan is done! close file..
int c = 0;
int done = 0;
while(count < argc) { //loop to go through each search word in the search
f = fopen("invertedIndex.txt", "r");
//rest counters
k = 0;
c = 0;
//delete all elements from old tempUrl list to replace by new word url list
DLList tempUrls = newDLList();
done = 0;
while (fscanf(f,"%s", &urls[k]) != EOF && done == 0) { //read through the file till the END of file
normalize(*argv);
removegrammar(*argv);
if((strcmp(*argv, &urls[k]) == 0)) { //if we've found our search word
while(fgets(&urls[k], 100, f) != NULL && done == 0) {//keep scaning through the urls to add in the list UNTIL we
char * cpy = strchr(&urls[k], ' '); //take the line of urls corresponding our word
char *ptr = cpy;
char *splitS;
while(ptr != NULL && done == 0) { //split our string to store all urls associated with our word
splitS= strsep(&ptr, " ");
if(splitS[strlen(splitS)-1] == '\n') {
splitS[strlen(splitS)-1] = '\0';
}
if(count == 0 && c != 0) { //for single query word cases
DLListAfter(matchedUrls, splitS);
}
else if(count > 0 && c!= 0) { //more than one query word entered
DLListAfter(tempUrls, splitS);
}
c++;
if(ptr == NULL ) {
done = 1;
break;
}
}
}
}
k++;
}
//compare and match for more than one query term
if(count > 0) {
matchedUrls = compareMatch(matchedUrls, tempUrls); //call matchedUrls -> a function which compares and matches common urls shared by all query terms
}
x++;
count++;
fclose(f);
free(urls);
}
//empty list case
if(DLListLength(matchedUrls) == 0) {
printf("no matching urls for ya search words m8\n");
return NULL;
}
return matchedUrls; //return our matching url list
}
//iterates through ALL files assocaited with EACH query word and returns the total frequency of this
int totalFreqWord (char *word, int numQueryTerms) {
if(numQueryTerms == 0) {
printf("nothing in command line lel\n");
return 0;
}
DLList tfD = newDLList();
char *txt = ".txt"; //to append at the end of matchingUrl list
//counter variables;
int j = 0;
int k = 0;
int i = 1;
int y = 0;
int count = 0;
int open = 0;
int totalCounter = 0;
int empty = 0; //once we've found our total freq, set empty to 1
while(j < 1 && empty == 0) { //we need to go through EVERY query term
//for each query term, we need to find the urls which contain this query term. - we will reset this this for every word
if(findUrlsForfreq(&word, numQueryTerms) == NULL){ //find all URLS that contain our current query word
empty = 1;
break;
}
tfD = findUrlsForfreq(&word, numQueryTerms);// matchingUrlPages(inv, argv[i]);
DLListNode * curr = tfD->first;
curr->numDocs = DLListLength(tfD); //store the total number of URLS found
DLListNode *tempUrl = newDLListNode(tfD->first->data);
y = 0;
while(DLListLength(tfD) > y) { //open ALL existing urls.
tempUrl->data = curr->data;
strcat(tempUrl->data, txt);
FILE *f = fopen(tempUrl->data, "r"); //open each txt file
open = 1;
char * urls = malloc(fsize("invertedIndex.txt"));
k = 0;
// printf("tempUrl %s\n", tempUrl->data);
totalCounter = 0;
while(fscanf(f,"%s", &urls[k]) != EOF && open == 1) { //loop through each text file to look and count the frequency for each query term
normalize(&urls[k]);
removegrammar(&urls[k]);
if(strcmp(word, &urls[k]) == 0) { //once we've found our word... increase our totalCounter :)
totalCounter = 1;
}
k++;
}
fclose(f);
y++;
i++;
curr = curr->next;
open = 0;
if(totalCounter == 1) {
tfD->first->totalFreq = count+1;
count++;
}
}
j++;
}
if(empty == 1) {
return 0;
}
return tfD->first->totalFreq;
}
//this function takes in all the urls associated with all query terms(urls in common) and counts the individual frequency of each query term per file - all
DLList tFData (char *argv[], int numQueryTerms, int p) { //p is used as a counter for iterating through single words and finding their frequency in a particular file
if(numQueryTerms == 0) {
printf("nothing in command line lel\n");
return 0;
}
numQueryTerms = numQueryTerms-1; //argc values - 1
DLList tfD = newDLList();
char *txt = ".txt";
//counter variables;
int j = 0;
int k = 0;
int i = 1;
int y = 0;
int count = 0;
int open = 0;
int x = 1;
int empty = 0;
while(j < p && empty == 0) { //we need to go through EVERY query term
//for each query term, we need to find the urls which contain this query term. - we will reset this this for every word
if(pageRankL(argv, numQueryTerms+1) == NULL){ //find all URLS that contain our current query word
empty = 1;
break;
}
tfD = pageRankL(argv,numQueryTerms+1);
DLListNode * curr = tfD->first;
curr->numDocs = DLListLength(tfD); //store the total number of URLS found
DLListNode *tempUrl = newDLListNode(tfD->first->data);
y = 0;
while(DLListLength(tfD) > y) { //open ALL existing urls.
tempUrl->data = curr->data;
strcat(tempUrl->data, txt);
printf("temp %s\n", tempUrl->data);
FILE * f = fopen(tempUrl->data, "r"); //open each txt file
open = 1;
char * urls = malloc(fsize("invertedIndex.txt"));
k = 0;
while(fscanf(f,"%s", &urls[k]) != EOF && open == 1) { //loop through each text file to look and count the frequency for each query term
normalize(&urls[k]);
removegrammar(&urls[k]);
if(strcmp(argv[x], &urls[k]) == 0) { //if we've found our matching word..
curr->wordFreq = curr->wordFreq+1; //increase the word freq counter
count++;
}
k++;
}
fclose(f);
y++;
i++;
curr = curr->next; //iterate to the next FILE
open = 0;
}
j++;
x++;
}
return tfD;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.