language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "ord.h"
#define TAM 1000000
int tam_heap;
int vetor[TAM];
void gera() {
int i;
for (i = 0; i < TAM; i++)
vetor[i] = rand();
}
void selection_sort() {
int current, i, aux, k;
for (i = 0; i <= TAM-2; i++)
current = i;
for (k = i+1; k >= TAM-1; k--)
if (vetor[current] > vetor[k])
current <- k;
aux = vetor[current];
vetor[current] = vetor[i];
vetor[i] = aux;
}
void heapify (int i) {
int max, aux, r, l;
l = 2 * i + 1;
r = 2 * i + 2;
if (l < tam_heap && vetor[l] > vetor[i])
max = l;
else max = i;
if (r < tam_heap && vetor[r] > vetor[max])
max = r;
if (max != i) {
aux = vetor[i];
vetor[i] = vetor[max];
vetor[max] = aux;
heapify(max);
}
}
void build_heap() {
int j;
tam_heap = TAM;
for (j = (TAM / 2) - 1; j >= 0; j--)
heapify(j);
}
void heapsort() {
build_heap();
int aux, k;
for (k = TAM - 1; k >= 1; k--) {
aux = vetor[0];
vetor[0] = vetor[k];
vetor[k] = aux;
tam_heap = tam_heap - 1;
heapify (0);
}
}
void imprime() {
int i;
for (i = 0; i < TAM; i++){
printf("%d\n\n", vetor[i]);
}
}
void bubble_sort (int n) {
int k, j, aux;
for (k = 1; k < n; k++) {
printf("\n[%d] ", k);
for (j = 0; j < n - 1; j++) {
printf("%d, ", j);
if (vetor[j] > vetor[j + 1]) {
aux = vetor[j];
vetor[j] = vetor[j + 1];
vetor[j + 1] = aux;
}
}
}
}
|
C
|
/* main.c */
#include <stdio.h>
#include <stdlib.h>
#include "y.tab.h"
#include "DeclaratorList.h"
extern int yyparse();
extern void scanString(const char * buffer);
DeclaratorList declarartorList;
typedef struct {
unsigned int length;
unsigned char *buffer;
} String;
String* load_file(char * s)
{
String *result = NULL;
FILE* f=fopen(s ,"rb");
if (f)
{
result = (String*)malloc(sizeof(String));
fseek(f, 0, SEEK_END);
result->length=ftell(f);
fseek(f, 0 , SEEK_SET);
result->buffer = (char*)malloc(result->length+1);
fread(result->buffer,result->length, 1, f);
result->buffer[result->length] = 0;
fclose(f);
}
return result;
}
int main(int argc, char **argv)
{
String* s;
if (argc == 2)
{
s = load_file(argv[1]);
if (!s)
{
printf("Error: Cannot open file %s\n", argv[1]);
exit( 1 );
}
else
{
// yy_scan_string(s->buffer);
scanString(s->buffer);
yyparse();
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include "Bytecode.h"
#include "TBLRDpostincf.h"
#include "CException.h"
unsigned char FSR[0x1000];
int Table[0x200000];
int tblrdpostincf(Bytecode *code) {
/*
* table read post increment
* Input: value from table
* Return: FSR[TBLPTRH] FSR[TBLPTRL] FSR[TBLPTRU] and next value of table and address of current table
*
*/
int temp,value;
int temp0 = 0b111110000000000000000;
int temp1 = 0b000001111111100000000;
int temp2 = 0b000000000000011111111;
FSR[TABLAT] = Table[(((FSR[TBLPTRU])<<16) + ((FSR[TBLPTRH])<<8) + (FSR[TBLPTRL]))];
temp = ((FSR[TBLPTRU])<<16) + ((FSR[TBLPTRH])<<8) + (FSR[TBLPTRL]);
temp++;
FSR[TBLPTRU] = ((temp&temp0)>>16);
FSR[TBLPTRH] = ((temp&temp1)>>8);
FSR[TBLPTRL] = (temp&temp2);
((FSR[TBLPTRU])<<16) + ((FSR[TBLPTRH])<<8) + (FSR[TBLPTRL]);
Table[((FSR[TBLPTRU])<<16) + ((FSR[TBLPTRH])<<8) + (FSR[TBLPTRL])];
}
|
C
|
#include<stdio.h>
int gameOfThrones(int d) {
int sum=0,num=0,N=1;
while(sum<d) {
sum+=N;
num=N++;
if(sum == d) return num;
}
return num;
}
int main() {
int t,d;
scanf("%d",&t);
while(t--) {
scanf("%d",&d);
char *s[] = {"SL","LB","BS"};
printf("%s\n",s[gameOfThrones(d)%3]);
}
}
|
C
|
/* Do not remove the headers from this file! see /USAGE for more info. */
object this_body();
mixed get_user_variable(string varname);
//: FUNCTION cannonical_form
// Change object path names to standard form, stripping the trailing .c, if
// any, the clone number, if any, and making sure the leading / exists.
//
// This function is useful for making sure that alternate forms of the
// pathname match correctly, since:
// cannonical_form("foo/bar") == cannonical_form("/foo/bar.c")
string cannonical_form(mixed fname)
{
if (objectp(fname))
fname = file_name(fname);
sscanf(fname, "%s#%*d", fname);
sscanf(fname, "%s.c", fname);
if (fname[0] != '/')
fname = "/" + fname;
return fname;
}
int path_exists(string x)
{
return file_size(x) != -1;
}
int is_directory(string x)
{
return x != "" && file_size(x) == -2;
}
int is_file(string x)
{
return file_size(x) > -1;
}
string *split_path(string p)
{
int pos;
while (p[ < 1] == '/' && strlen(p) > 1)
p = p[0.. < 2];
pos = strsrch(p, '/', -1); /* find the last '/' */
return ({p[0..pos], p[pos + 1..]});
}
string base_path(string p)
{
return split_path(p)[0];
}
string depath(string p)
{
return split_path(p)[1];
}
varargs void walk_dir(string path, function func, mixed arg)
{
mixed tmp, names, res;
int i;
if (!is_directory(path))
{
tmp = split_path(path);
evaluate(func, arg, tmp[0], ({tmp[1]}));
return;
}
names = get_dir(path + "/*");
names -= ({".", ".."});
res = evaluate(func, path, names, arg);
if (!res)
res = names;
if (path[ < 1] != '/')
path += "/";
res = map_array(res, ( : $(path) + $1:));
res = filter_array(res, ( : file_size($1) == -2 :));
i = sizeof(res);
while (i--)
walk_dir(res[i], func, arg);
}
//: FUNCTION canonical_path
// Strip out all "." and ".." forms from a path. Remove double slashes.
// Ensure the path has a leading slash.
string canonical_path(string path)
{
string *parts = explode(path, "/") - ({"", "."});
int idx;
if (!sizeof(parts))
return "/";
while ((idx = member_array("..", parts)) != -1)
{
if (idx > 1)
parts = parts[0..idx - 2] + parts[idx + 1..];
else if (idx == 0)
parts = parts[1..];
else
parts = parts[2..];
}
return "/" + implode(parts, "/") + (path[ < 1] == '/' ? "/" : "");
}
/* Stuff for evaluate path*/
private
string *wiz_dir_parts = explode(WIZ_DIR, "/") - ({"", "."});
private
string *domain_dir_parts = explode("/domains", "/") - ({"", "."});
//: FUNCTION
// Given a path name with the usual . or .. operands, it will parse and
// return a path based of callers current working directory.
//
// If the no_interactive flag is set, the pwd of the current user is not
// considered. This is useful for when the mudlib is trying to figure
// out where to find a relative file.
varargs string evaluate_path(string path, string prepend, int no_interactive)
{
string *tree;
int idx;
// TBUG("path: " + path + " prepend: " + prepend + " no_interact: " + no_interactive);
if (!path || path[0] != '/')
{
if (this_body() && !no_interactive)
path = get_user_variable("pwd") + "/" + path;
else if (prepend)
path = prepend + "/" + path;
else
{
string lname = file_name(previous_object());
int tmp = strsrch(lname, "/", -1);
path = lname[0..tmp] + path;
}
}
tree = explode(path, "/") - ({"", "."});
while (idx < sizeof(tree))
{
string tmp = tree[idx];
if (tmp == "..")
{
if (idx)
{
tree[idx - 1..idx] = ({});
idx--;
}
else
tree[idx..idx] = ({});
continue;
}
if (tmp[0] == '~' && this_user())
{
if (sizeof(tmp) == 1)
tmp = this_user()->query_userid();
else
tmp = tmp[1..];
tree[0..idx] = wiz_dir_parts + ({tmp});
continue;
}
if (tmp[0] == '^')
{
tmp = tmp[1..];
tree[0..idx] = domain_dir_parts + ({tmp});
continue;
}
idx++;
}
return "/" + implode(tree, "/");
}
string join_path(string dir, string file)
{
if (dir[ < 1] != '/')
return dir + "/" + file;
return dir + file;
}
mapping map_paths(mixed paths)
{
mapping res;
int i;
res = ([]);
paths = map_array(paths, ( : split_path:));
for (i = 0; i < sizeof(paths); i++)
{
if (undefinedp(res[paths[i][0]]))
res[paths[i][0]] = ({paths[i][1]});
else
res[paths[i][0]] += ({paths[i][1]});
}
return res;
}
varargs string absolute_path(string relative_path, mixed relative_to)
{
if (!relative_to)
relative_to = previous_object();
if (relative_path[0] != '/')
if (objectp(relative_to))
relative_path = base_path(file_name(relative_to)) + relative_path;
else if (stringp(relative_to))
relative_path = relative_to + "/" + relative_path;
else
error("Invalid relative_to path passed");
relative_path = cannonical_form(relative_path);
relative_path = evaluate_path(relative_path);
return relative_path;
}
nomask string wiz_dir(mixed what)
{
if (stringp(what))
{
#ifdef EXPANDED_WIZ_DIR
return sprintf("%s/%c/%s", WIZ_DIR, what[0], what);
#else
return sprintf("%s/%s", WIZ_DIR, what);
#endif
}
if (objectp(what))
{
string who = what->query_userid();
#ifdef EXPANDED_WIZ_DIR
return sprintf("%s/%c/%s", WIZ_DIR, who[0], who);
#else
return sprintf("%s/%s", WIZ_DIR, who);
#endif
}
}
string domain_file(mixed file)
{
string *parts;
if (objectp(file))
file = base_name(file);
parts = explode(file, "/");
if (sizeof(parts) > 2 && parts[0] == "domains")
return parts[1];
else
return "std";
}
string author_file(string file)
{
string *parts = explode(file, "/");
if (file == "/secure/master.c")
return "beek";
if (sizeof(parts) > 2 && parts[0] == "wiz")
return parts[1];
else
return "mudlib";
}
|
C
|
/*
* config_map.c
*
* Created on: 4 Apr 2010
* Author: David
*/
#include "../dt_logger.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "config_map.h"
#include "strmap/StrMap.h"
/*
* create_config_value_int
*
* Each possible integer value from the config file should be contained in this
* function with min, max and defaults.
*/
bool create_config_value_int(CONFIG_VALUE_INT_ENUM cv,
CONFIG_VALUE_INT *config_value)
{
/*
* Local Variables.
*/
bool value_exists = true;
switch(cv)
{
case cv_max_fps:
config_value->default_value = 60;
strncpy(config_value->key, "MAX_FPS", MAX_CONFIG_VALUE_LEN);
config_value->min_value = 30;
config_value->max_value = 100;
break;
case cv_animation_ms_per_frame:
config_value->default_value = 100;
strncpy(config_value->key, "ANIMATION_MS_PER_FRAMES", MAX_CONFIG_VALUE_LEN);
config_value->min_value = 10;
config_value->max_value = 10000;
break;
case cv_audio_freq:
config_value->default_value = 44100;
strncpy(config_value->key, "AUDIO_FREQ", MAX_CONFIG_VALUE_LEN);
config_value->min_value = 44100;
config_value->max_value = 44100;
break;
case cv_audio_channels:
config_value->default_value = 2;
strncpy(config_value->key, "AUDIO_CHANNELS", MAX_CONFIG_VALUE_LEN);
config_value->min_value = 1;
config_value->max_value = 2;
break;
default:
DT_DEBUG_LOG("Request made for config value that does not exist: %i\n",
cv);
value_exists = false;
break;
}
return(value_exists);
}
/*
* create_config_value_str
*
* Each possible string value in the string config enum should be included in
* here with key name and default value.
*/
bool create_config_value_str(CONFIG_VALUE_STR_ENUM cv,
CONFIG_VALUE_STR *config_value)
{
/*
* Local Variables.
*/
bool cv_exists = true;
switch(cv)
{
case cv_music_directory:
strncpy(config_value->key, "MUSIC_DIRECTORY", MAX_CONFIG_VALUE_LEN);
strncpy(config_value->default_value,
"resources//music",
MAX_CONFIG_VALUE_LEN);
break;
case cv_o_xml_file:
strncpy(config_value->key, "O_AUTOMATON", MAX_CONFIG_VALUE_LEN);
strncpy(config_value->default_value,
"resources//automaton//o_automaton.xml",
MAX_CONFIG_VALUE_LEN);
break;
case cv_d_xml_file:
strncpy(config_value->key, "D_AUTOMATON", MAX_CONFIG_VALUE_LEN);
strncpy(config_value->default_value,
"resources//automaton//d_automaton.xml",
MAX_CONFIG_VALUE_LEN);
break;
case cv_disc_graphic:
strncpy(config_value->key, "DISC_GRAPHIC_FILENAME", MAX_CONFIG_VALUE_LEN);
strncpy(config_value->default_value,
"resources//images//disc.png",
MAX_CONFIG_VALUE_LEN);
break;
case cv_grass_tile_filename:
strncpy(config_value->key, "GRASS_TILE_FILENAME", MAX_CONFIG_VALUE_LEN);
strncpy(config_value->default_value,
"resources//images//grass_tile.png",
MAX_CONFIG_VALUE_LEN);
break;
default:
DT_DEBUG_LOG("Request made for config value that does not exist: %i\n",
cv);
cv_exists = false;
break;
}
return(cv_exists);
}
/*
* get_config_value_int
*
* Retrieves the current value of the config mapping for a given integer config
* value. Clamped between minimum and maximum and uses the default if nothing
* exists in the config file.
*
* Parameters: table - The config table as loaded from a file.
* cv - The value we are looking for.
* value - Will contain the return value.
*
* Returns: False if the function fails for any reason. This should only be due
* to programmer error in filling in the create_config_value_int
* function.
*/
bool get_config_value_int(StrMap *table, CONFIG_VALUE_INT_ENUM cv, int *value)
{
/*
* Local Variables.
*/
CONFIG_VALUE_INT config_value;
char config_value_str[MAX_CONFIG_VALUE_LEN];
int temp_value;
int rc;
bool value_exists = true;
/*
* create_config_value returns a config value with INVALID_VALUE as the key
* if the value is not a valid constant.
*/
value_exists = create_config_value_int(cv, &config_value);
if (value_exists)
{
/*
* If the value doesn't exist in the config file then just use whatever
* default already exists.
*/
rc = strmap_get(table,
config_value.key,
config_value_str,
MAX_CONFIG_VALUE_LEN);
if (0 == rc)
{
*value = config_value.default_value;
}
else
{
/*
* Silently clamp the possible values of the config between the minimum
* and maximum allowed for that constant.
*/
temp_value = atoi(config_value_str);
if (temp_value < config_value.min_value)
{
*value = config_value.min_value;
}
else if (temp_value > config_value.max_value)
{
*value = config_value.max_value;
}
else
{
*value = temp_value;
}
}
}
return value_exists;
}
/*
* set_config_value_int
*
* Sets the value of the config key passed in. This can be used to write new
* values back out to file.
*
* Fails silently when attempting to set a key that doesn't exist.
*
* Parameters: table - The config map.
* cv - The config value enum that we are writing.
* new_value - The new value to write.
*/
void set_config_value_int(StrMap *table,
CONFIG_VALUE_INT_ENUM cv,
int new_value)
{
/*
* Local Variables.
*/
char config_str[MAX_CONFIG_VALUE_LEN];
CONFIG_VALUE_INT config_value;
bool valid_key;
valid_key = create_config_value_int(cv, &config_value);
if (valid_key)
{
/*
* Clamp the new value to the min/max range of that config value.
*/
if (new_value < config_value.min_value)
{
new_value = config_value.min_value;
}
else if (new_value > config_value.max_value)
{
new_value = config_value.max_value;
}
/*
* Write the new value back to the StrMap object. Note that strmap_put
* overwrites any previous value in the table.
*
* Fail silently.
*/
sprintf(config_str, "%i", new_value);
if (0 == strmap_put(table, config_value.key, config_str))
{
DT_DEBUG_LOG("Failed to write to config table: key=%s, value=%s",
config_value.key,
config_str);
}
}
}
/*
* get_config_value_str
*
* Retrieves the value of a config table item. It uses defaults if the value
* cannot be found and so this should be used as the external entrance point.
*
* Parameters: table - The preloaded hash table of config values.
* cv - Enum indicating which value we want.
* value - Will have the returning string copied into it.
*
* Returns: False if the config enum is missing from the code. True otherwise.
*/
bool get_config_value_str(StrMap *table,
CONFIG_VALUE_STR_ENUM cv,
char *value)
{
/*
* Local Variables.
*/
CONFIG_VALUE_STR config_value;
char config_value_str[MAX_CONFIG_VALUE_LEN];
int rc;
bool value_exists = true;
/*
* create_config_value returns a config value with INVALID_VALUE as the key
* if the value is not a valid constant.
*/
value_exists = create_config_value_str(cv, &config_value);
if (value_exists)
{
/*
* If the value doesn't exist in the config file then just use whatever
* default already exists.
*/
rc = strmap_get(table,
config_value.key,
config_value_str,
MAX_CONFIG_VALUE_LEN);
if (0 == rc)
{
strncpy(value,
config_value.default_value,
MAX_CONFIG_VALUE_LEN);
}
else
{
strncpy(value,
config_value_str,
MAX_CONFIG_VALUE_LEN);
}
/*
* strncpy doesn't copy over a null terminator for the string so we have to
* do it manually.
*/
value[strlen(value)] = '\0';
}
return value_exists;
}
/*
* set_config_value_str
*
* Sets the value of the config key passed in. This can be used to write new
* values back out to file.
*
* Fails silently when attempting to set a key that doesn't exist.
*
* Parameters: table - The config map.
* cv - The config value enum that we are writing.
* new_value - The new value to write.
*/
void set_config_value_str(StrMap *table,
CONFIG_VALUE_STR_ENUM cv,
char *new_value)
{
/*
* Local Variables.
*/
CONFIG_VALUE_STR config_value;
bool valid_key;
valid_key = create_config_value_str(cv, &config_value);
if (valid_key)
{
/*
* Verify that the string is within the constant length guidelines. If not
* then we would fail trying to read it back in.
*/
if (strlen(new_value) > MAX_CONFIG_VALUE_LEN)
{
DT_DEBUG_LOG("Attempted to write new config value that is too long:" \
" key=%s, value=%s",
config_value.key,
new_value);
return;
}
/*
* Write the new value back to the StrMap object. Note that strmap_put
* overwrites any previous value in the table.
*
* Fail silently.
*/
if (0 == strmap_put(table, config_value.key, new_value))
{
DT_DEBUG_LOG("Failed to write to config table: key=%s, value=%s",
config_value.key,
new_value);
return;
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* options.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yhliboch <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/04 14:26:52 by yhliboch #+# #+# */
/* Updated: 2019/06/04 14:26:54 by yhliboch ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
void next_fractol(t_fr *head)
{
if (head->type == SHIP)
head->type = MAN;
else
head->type += 1;
}
int key_two(int keycode, t_fr *head, t_j *fr)
{
if (keycode == KEY_LEFT)
fr->movex += 0.05 / fr->zoom;
if (keycode == KEY_RIGHT)
fr->movex -= 0.05 / fr->zoom;
if (keycode == KEY_UP)
fr->movey += 0.05 / fr->zoom;
if (keycode == KEY_DOWN)
fr->movey -= 0.05 / fr->zoom;
if (keycode == IT_PLUS)
head->maxiter += 10;
if (keycode == IT_MINUS)
head->maxiter -= 10;
if (keycode == SPACE && head->type == JUL)
fr->p = (fr->p == 0 ? 1 : 0);
update(head);
return (1);
}
int key(int keycode, t_fr *head)
{
t_j *fr;
if (keycode == 53)
exit(0);
if (head->type == JUL)
fr = &(head->jul);
else if (head->type == MAN)
fr = &(head->man);
else
fr = &(head->ship);
if (keycode == KEY_RETURN)
next_fractol(head);
return (key_two(keycode, head, fr));
}
int zoom(int button, int x, int y, t_fr *head)
{
t_j *fr;
if (head->type == JUL)
fr = &(head->jul);
else if (head->type == MAN)
fr = &(head->man);
else
fr = &(head->ship);
if (button == 5)
fr->zoom *= 1.12;
if (button == 4)
fr->zoom /= 1.12;
update(head);
return (0);
}
void threads(t_fr *head)
{
t_fr hd[THREAD];
int i;
i = -1;
while (++i < THREAD)
{
hd[i] = *head;
hd[i].xstart = 0;
hd[i].xend = WIDTH;
hd[i].ystart = HEIGHT / THREAD * i;
hd[i].yend = HEIGHT / THREAD * (i + 1);
pthread_create(&head->threads[i], NULL,
(void *)draw_fractol, (void *)&hd[i]);
}
i = -1;
while (++i < THREAD)
pthread_join(head->threads[i], NULL);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mines.h>
int main(int argc, char **argv){
// seeding the rand
srand(time(NULL));
table t;
fill_table(&t);
printf("\n");
int i,j;
do{
system(CLEAR);
plot_table(t);
printf("Please pick your line and column\nType 0 0 to end\n");
scanf("%d %d", &i, &j);
if(i == 0){
system(CLEAR);
reveal_all_mines(t, -1, -1);
j = check_victory(t);
if(j == 1){
printf("\33[0;32m");
printf("VICTORY!\n");
}else{
printf("\33[0;31m");
printf("TOTAL DEFEAT!\n");
}
return 0;
}
}while(reveal_cell(&t, i-1, j-1) == 0);
system(CLEAR);
reveal_all_mines(t, i-1, j-1);
printf("\33[0;31m");
printf("TOTAL DEFEAT!\n");
return 0;
}
|
C
|
#include <stdio.h>
void affecter(int *pt_valeur, int a){
*pt_valeur=a;
}
int main(){
int a,valeur=10;
printf("entrer la valeure de a\n");
scanf("%d",&a);
printf("valeur =%d",valeur);
affecter(&valeur,a);
printf("valeur =%d",valeur);
}
|
C
|
#include <stdio.h>
int bubbleSort(int *arr){
// int size = sizeof() / sizeof(int);
int temp;
for(int i = 0; i < 5;i++)
for (int j = 0; j <= i; j++)
{
if(arr[i] > arr[j] ){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
return *arr;
}
int main(){
int arr[] = {111, 2, 4 , 8, 5};
int size = sizeof(arr) / sizeof(int);
for (int i = 0; i < size; i++)
{
printf("Before Sorting : %d \n", arr[i]);
}
bubbleSort(arr);
for (int i = 0; i < size; i++)
{
printf("After Sorting : %d \n", arr[i]);
}
bubbleSort(arr);
}
|
C
|
#include <stdio.h>
void main()
{
int dec,i,a[32],rem;
printf("enter the decimal number:\n");
scanf("%d",&dec);
for(i=0 ;dec>0 ;i++ )
{
rem=dec%2;
a[i]=rem;
dec=dec/2;
}
for(i=i-1;i>=0;i--)
printf("%d",a[i]);
printf("\n");
}
|
C
|
//using nested structure
// making of account
#include<conio.h>
#include<stdio.h>
#include<string.h>
struct user_account
{
char fstnme[40];
char lstnme[30];
char usrnme[50];
char passwd[50];
struct DOB{
int day;
int month;
int year;
}dob; // vriable name as array
struct Gender{
int male;
int female;
}gender; // vriable name as array
};
void input(struct user_account x[]);
void output(struct user_account y[]);
void passwd(char pasd[]);
int main()
{
struct user_account user[1];
input(user);
output(user);
return 0;
}
void input(struct user_account user[])
{
printf("*********** INPUT FORM ***************\n\n");
char chkpasswd[50];
char chkgnd;
printf("Enter your first name : ");
scanf("%s",user[0].fstnme);
printf("\nEnter your Last Name : ");
scanf("%s",user[0].lstnme);
printf("\nEnter your user name : ");
scanf("%s",user[0].usrnme);
// *********** PASSWORD **********
printf("\nEnter your password : ");
passwd(user[0].passwd);
while(1){
printf("\nRetype your password : ");
passwd(chkpasswd);
if(strcasecmp(user[0].passwd,chkpasswd)!=0){
printf("\n\aWrong input");
}
else
break;
}
printf("\nEnter your Date of Birth\n");
printf("\tDay : ");
scanf("%d",&user[0].dob.day);
printf("\tMonth : ");
scanf("%d",&user[0].dob.month);
printf("\tYear : ");
scanf("%d",&user[0].dob.year);
while(1){
fflush(stdin);
printf("\nWhats your Gender <Press male for 'm' or 'f' for female : ");
scanf("%c",&chkgnd);
if(chkgnd=='m' || chkgnd=='M')
{
user[0].gender.male=1;
user[0].gender.female=0;
break;
}
else if(chkgnd=='f' || chkgnd=='F')
{
user[0].gender.male=0;
user[0].gender.female=1;
break;
}
else
printf("\n\ayour have entered wrong key");
}
}
void output(struct user_account user[])
{
char permission;
printf("************ OUTPUT *************\n\n");
printf("Name : %s %s",user[0].fstnme,user[0].lstnme);
printf("\nUser ID : %s",user[0].usrnme);
printf("\nPassword : \a Sorry you are not allowed to view");
while(1){
fflush(stdin);
printf("\tIF YOU ARE REALLY WANT TO VIEW PRESS Y ELSE N : ");
scanf("%c",&permission);
if(permission=='y' || permission=='Y')
{
printf("\nYour password is : %s",user[0].passwd);
break;
}
else if(permission=='n' || permission=='N')
break;
else
printf("\a Wrong key\n");
}
printf("\nDate of Birth : %d / %d /%d",user[0].dob.day,user[0].dob.month,user[0].dob.year);
printf("\nGender : ");
if(user[0].gender.male==1)
printf("Male");
else
printf("Female");
}
void passwd(char pasd[])
{
char a;
int i=0;
while(1)
{
a=getch();
if(a==13)
break;
pasd[i]=a;
putchar('*');
i++;
}
pasd[i]='\0';
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
char k[10];
int i,len;
scanf("%s",k);
len=strlen(k);
for(i=len-1;i>=0;i--)
{
printf("%c",k[i]);
}
}
|
C
|
/* See LICENSE file for copyright and license details. */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "util.h"
static bool unary(const char *, const char *);
static bool binary(const char *, const char *, const char *);
static void usage(void);
int
main(int argc, char *argv[])
{
bool ret = false, not = false;
argv0 = argv[0];
/* [ ... ] alias */
if(!strcmp(argv[0], "[")) {
if(strcmp(argv[argc-1], "]") != 0)
usage();
argc--;
}
if(argc > 1 && !strcmp(argv[1], "!")) {
not = true;
argv++;
argc--;
}
switch(argc) {
case 2:
ret = *argv[1] != '\0';
break;
case 3:
ret = unary(argv[1], argv[2]);
break;
case 4:
ret = binary(argv[1], argv[2], argv[3]);
break;
default:
usage();
}
if(not)
ret = !ret;
return ret ? EXIT_SUCCESS : EXIT_FAILURE;
}
bool
unary(const char *op, const char *arg)
{
struct stat st;
int r;
if(op[0] != '-' || op[1] == '\0' || op[2] != '\0')
usage();
switch(op[1]) {
case 'b': case 'c': case 'd': case 'f': case 'g':
case 'p': case 'S': case 's': case 'u':
if((r = stat(arg, &st)) == -1)
return false; /* -e */
switch(op[1]) {
case 'b':
return S_ISBLK(st.st_mode);
case 'c':
return S_ISCHR(st.st_mode);
case 'd':
return S_ISDIR(st.st_mode);
case 'f':
return S_ISREG(st.st_mode);
case 'g':
return st.st_mode & S_ISGID;
case 'p':
return S_ISFIFO(st.st_mode);
case 'S':
return S_ISSOCK(st.st_mode);
case 's':
return st.st_size > 0;
case 'u':
return st.st_mode & S_ISUID;
}
case 'e':
return access(arg, F_OK) == 0;
case 'r':
return access(arg, R_OK) == 0;
case 'w':
return access(arg, W_OK) == 0;
case 'x':
return access(arg, X_OK) == 0;
case 'h': case 'L':
return lstat(arg, &st) == 0 && S_ISLNK(st.st_mode);
case 't':
return isatty((int)estrtol(arg, 0));
case 'n':
return arg[0] != '\0';
case 'z':
return arg[0] == '\0';
default:
usage();
}
return false; /* should not reach */
}
bool
binary(const char *arg1, const char *op, const char *arg2)
{
eprintf("not yet implemented\n");
return false;
}
void
usage(void)
{
const char *ket = (*argv0 == '[') ? " ]" : "";
eprintf("usage: %s string%s\n"
" %s [!] [-bcdefghLnprSstuwxz] string%s\n", argv0, ket, argv0, ket);
}
|
C
|
#include "stack.h"
#include "string.h"
#include <stdio.h>
int16_t stack_init(stack_t * stack, void * array, uint16_t size, uint8_t element_size){
stack->array = array;
stack->size = size;
stack->element_size = element_size;
stack->index = 0;
return 0;
}
int16_t stack_push(stack_t * stack, void * data){
int16_t ret = -1;
if (stack->index < stack->size){
memcpy(stack->array + (stack->index * stack->element_size), data, stack->element_size);
stack->index++;
ret = 0;
}
return ret;
}
int16_t stack_pop(stack_t * stack, void * data){
int16_t ret = -1;
if (stack->index > 0){
stack->index--;
memcpy(data, stack->array + (stack->index * stack->element_size), stack->element_size);
ret = 0;
}
return ret;
}
void stack_print(stack_t * stack){
uint16_t i = 0;
printf("----- STACK @ %p -----\n", stack);
printf("index: %d\n", stack->index);
printf("element_size: %d\n", stack->element_size);
printf("stack array: %p\n", stack->array);
printf("\n");
for (i=stack->size; i>0;--i){
printf("%04d\t%p\n", i-1, stack->array+((i-1)*stack->element_size));
}
printf("----- END -----\n");
}
|
C
|
#include <stdalign.h>
#ifndef VMATH_H
#define VMATH_H
typedef struct {
alignas(16) float data[4];
} vec_t;
typedef struct {
alignas(16) float data[4][4];
} mat_t;
vec_t v3neg(vec_t v);
vec_t v3av3(vec_t a, vec_t b);
vec_t v3sv3(vec_t a, vec_t b);
float v3dv3(vec_t a, vec_t b);
vec_t v3xv3(vec_t a, vec_t b);
mat_t m4xm4(mat_t a, mat_t b);
vec_t m4xv4(mat_t a, vec_t b);
void print_vec(vec_t v);
void print_mat(mat_t m);
//Useful Matrices
mat_t translate(vec_t v);
mat_t perspective(float fovy, float aspect, float n, float f);
mat_t frustum(float l, float r, float t, float b, float n, float f);
mat_t rotate(vec_t axis, float angle);
#endif
|
C
|
/**
* @file
* @brief
*
* @date 29.03.2012
* @author Andrey Gazukin
*/
#ifndef FAT_H_
#define FAT_H_
#include <stdint.h>
#include <sys/types.h>
#include <fs/mbr.h>
#define DIR_SEPARATOR '/' /* character separating directory components*/
#define ROOT_DIR "/"
#define MSDOS_NAME 11
#define MSDOS_DOT ". "
#define MSDOS_DOTDOT ".. "
/* 32-bit error codes */
#define DFS_OK 0 /* no error */
#define DFS_EOF 1 /* end of file (not an error) */
#define DFS_WRITEPROT 2 /* volume is write protected */
#define DFS_NOTFOUND 3 /* path or file not found */
#define DFS_PATHLEN 4 /* path too long */
#define DFS_ALLOCNEW 5 /* must allocate new directory cluster */
#define DFS_ERRMISC 0xffffffff /* generic error */
#define DFS_WRONGRES 6 /* file expected but dir found or vice versa */
#define DFS_BAD_CLUS 0x0ffffff7
/* Internal subformat identifiers */
#define FAT12 0
#define FAT16 1
#define FAT32 2
/* DOS attribute bits */
#define ATTR_READ_ONLY 0x01
#define ATTR_HIDDEN 0x02
#define ATTR_SYSTEM 0x04
#define ATTR_VOLUME_ID 0x08
#define ATTR_DIRECTORY 0x10
#define ATTR_ARCHIVE 0x20
#define ATTR_LONG_NAME \
(ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID)
/* Long dirent preceedes "regular" dirent entry, for details refer to
* https://wiki.osdev.org/FAT */
struct fat_long_dirent {
uint8_t order;
#define FAT_LONG_ORDER_LAST 0x40
#define FAT_LONG_ORDER_NUM_MASK 0x0F
uint8_t name1[10];
uint8_t attr; /* Should always be 0xF */
uint8_t type; /* Zero for name entries */
uint8_t chksum;
uint8_t name2[12];
uint8_t reserved[2]; /* Should always be zero */
uint8_t name3[4];
};
/*
* Directory entry structure
* note: if name[0] == 0xe5, this is a free dir entry
* if name[0] == 0x00, this is a free entry and all subsequent entries
* are free
* if name[0] == 0x05, the first character of the name is 0xe5
*
* Date format: bit 0-4 = day of month (1-31)
* bit 5-8 = month, 1=Jan..12=Dec
* bit 9-15 = count of years since 1980 (0-127)
* Time format: bit 0-4 = 2-second count, (0-29)
* bit 5-10 = minutes (0-59)
* bit 11-15= hours (0-23)
*/
struct fat_dirent {
uint8_t name[MSDOS_NAME]; /* filename */
uint8_t attr; /* attributes (see ATTR_* constant definitions) */
uint8_t reserved; /* reserved, must be 0 */
uint8_t crttimetenth; /* create time, 10ths of a second (0-199 are valid) */
uint8_t crttime_l; /* creation time low byte */
uint8_t crttime_h; /* creation time high byte */
uint8_t crtdate_l; /* creation date low byte */
uint8_t crtdate_h; /* creation date high byte */
uint8_t lstaccdate_l; /* last access date low byte */
uint8_t lstaccdate_h; /* last access date high byte */
uint8_t startclus_h_l; /* high word of first cluster, low byte (FAT32) */
uint8_t startclus_h_h; /* high word of first cluster, high byte (FAT32) */
uint8_t wrttime_l; /* last write time low byte */
uint8_t wrttime_h; /* last write time high byte */
uint8_t wrtdate_l; /* last write date low byte */
uint8_t wrtdate_h; /* last write date high byte */
uint8_t startclus_l_l; /* low word of first cluster, low byte */
uint8_t startclus_l_h; /* low word of first cluster, high byte */
uint8_t filesize_0; /* file size, low byte */
uint8_t filesize_1; /* */
uint8_t filesize_2; /* */
uint8_t filesize_3; /* file size, high byte */
};
/*
* BIOS Parameter Block structure (FAT12/16)
*/
struct bpb {
uint8_t bytepersec_l; /* bytes per sector low byte (0x00) */
uint8_t bytepersec_h; /* bytes per sector high byte (0x02) */
uint8_t secperclus; /* sectors per cluster (1,2,4,8,16,32,64,128 are valid) */
uint8_t reserved_l; /* reserved sectors low byte */
uint8_t reserved_h; /* reserved sectors high byte */
uint8_t numfats; /* number of FAT copies (2) */
uint8_t rootentries_l; /* number of root dir entries low byte (0x00 normally) */
uint8_t rootentries_h; /* number of root dir entries high byte (0x02 normally) */
uint8_t sectors_s_l; /* small num sectors low byte */
uint8_t sectors_s_h; /* small num sectors high byte */
uint8_t mediatype; /* media descriptor byte */
uint8_t secperfat_l; /* sectors per FAT low byte */
uint8_t secperfat_h; /* sectors per FAT high byte */
uint8_t secpertrk_l; /* sectors per track low byte */
uint8_t secpertrk_h; /* sectors per track high byte */
uint8_t heads_l; /* heads low byte */
uint8_t heads_h; /* heads high byte */
uint8_t hidden_0; /* hidden sectors low byte */
uint8_t hidden_1; /* (note - this is the number of MEDIA sectors before */
uint8_t hidden_2; /* first sector of VOLUME - we rely on the MBR instead) */
uint8_t hidden_3; /* hidden sectors high byte */
uint8_t sectors_l_0; /* large num sectors low byte */
uint8_t sectors_l_1; /* */
uint8_t sectors_l_2; /* */
uint8_t sectors_l_3; /* large num sectors high byte */
};
/*
* Extended BIOS Parameter Block structure (FAT12/16)
*/
struct ebpb {
uint8_t unit; /* int 13h drive#: 0x00 for floppy and 0x80 for HDD */
uint8_t head; /* archaic, used by Windows NT-class OSes for flags */
uint8_t signature; /* 0x28 or 0x29 */
uint8_t serial_0; /* serial# */
uint8_t serial_1; /* serial# */
uint8_t serial_2; /* serial# */
uint8_t serial_3; /* serial# */
uint8_t label[11]; /* volume label */
uint8_t system[8]; /* filesystem ID */
uint8_t code[448]; /* boot sector code */
};
/*
* Extended BIOS Parameter Block structure (FAT32)
*/
struct ebpb32 {
uint8_t fatsize_0; /* big FAT size in sectors low byte */
uint8_t fatsize_1; /* */
uint8_t fatsize_2; /* */
uint8_t fatsize_3; /* big FAT size in sectors high byte */
uint8_t extflags_l; /* extended flags low byte */
uint8_t extflags_h; /* extended flags high byte */
uint8_t fsver_l; /* filesystem version (0x00) low byte */
uint8_t fsver_h; /* filesystem version (0x00) high byte */
uint8_t root_0; /* cluster of root dir, low byte */
uint8_t root_1; /* */
uint8_t root_2; /* */
uint8_t root_3; /* cluster of root dir, high byte */
uint8_t fsinfo_l; /* sector pointer to FSINFO within reserved area, low byte (2) */
uint8_t fsinfo_h; /* sector pointer to FSINFO within reserved area, high byte (0) */
uint8_t bkboot_l; /* sector pointer to backup boot sector within reserved area, low byte (6) */
uint8_t bkboot_h; /* sector pointer to backup boot sector within reserved area, high byte (0) */
uint8_t reserved[12]; /* reserved, should be 0 */
uint8_t unit; /* int 13h drive# */
uint8_t head; /* archaic, used by Windows NT-class OSes for flags */
uint8_t signature; /* 0x28 or 0x29 */
uint8_t serial_0; /* serial# */
uint8_t serial_1; /* serial# */
uint8_t serial_2; /* serial# */
uint8_t serial_3; /* serial# */
uint8_t label[11]; /* volume label */
uint8_t system[8]; /* filesystem ID */
uint8_t code[420]; /* boot sector code */
};
/*
* Logical Boot Record structure (volume boot sector)
* IMPORTANT NOTE Boot code section is appended to ebpb to fit different offset
*/
struct lbr {
uint8_t jump[3]; /* JMP instruction */
uint8_t oemid[8]; /* OEM ID, space-padded */
struct bpb bpb; /* BIOS Parameter Block */
union {
struct ebpb ebpb; /* FAT12/16 Extended BIOS Parameter Block */
struct ebpb32 ebpb32; /* FAT32 Extended BIOS Parameter Block */
} ebpb;
uint8_t sig_55; /* 0x55 signature byte */
uint8_t sig_aa; /* 0xaa signature byte */
};
/*
* Volume information structure (Internal to DOSFS)
*/
struct volinfo {
uint8_t unit; /* unit on which this volume resides */
uint8_t filesystem; /* formatted filesystem */
/*
* These two fields aren't very useful, so support for them has been commented
* out to save memory. (Note that the "system" tag is not actually used by DOS
* to determine filesystem type - that decision is made entirely on the basis
* of how many clusters the drive contains. DOSFS works the same way).
* See tag: OEMID in dosfs.c
*/
/* uint8_t oemid[9]; */ /* OEM ID ASCIIZ */
/* uint8_t system[9]; */ /* system ID ASCIIZ */
uint8_t label[12]; /* volume label ASCIIZ */
uint32_t startsector; /* starting sector of filesystem */ /* TODO eliminate this field in new vfs as it handles partition on it's own */
uint16_t bytepersec; /* Bytes per sector */
uint8_t secperclus; /* sectors per cluster */
uint16_t reservedsecs; /* reserved sectors */
uint32_t numsecs; /* number of sectors in volume */
uint32_t secperfat; /* sectors per FAT */
uint16_t rootentries; /* number of root dir entries */
uint32_t numclusters; /* number of clusters on drive */
/* The fields below are PHYSICAL SECTOR NUMBERS. */
uint32_t fat1; /* starting sector# of FAT copy 1 */
uint32_t rootdir; /* starting sector# of root directory (FAT12/FAT16) or cluster (FAT32) */
uint32_t dataarea; /* starting sector# of data area (cluster #2) */
};
/*
* Flags in DIRINFO.flags
*/
#define DFS_DI_BLANKENT 0x01 /* Searching for blank entry */
struct fat_fs_info {
struct volinfo vi;
struct block_dev *bdev;
struct inode *root;
};
struct fat_file_info {
struct fat_fs_info *fsi;
struct volinfo *volinfo; /* vol_info_t used to open this file */
struct dirinfo *fdi;
uint32_t dirsector; /* physical sector containing dir entry of this file */
uint8_t diroffset; /* # of this entry within the dir sector */
int mode; /* mode in which this file was opened */
uint32_t firstcluster; /* first cluster of file */
uint32_t filelen; /* byte length of file */
uint32_t pointer;
uint32_t cluster; /* current cluster */
};
/*
* Directory search structure (Internal to DOSFS)
*/
struct dirinfo {
struct fat_file_info fi; /* Must be first field in structure */
uint32_t currentcluster; /* current cluster in dir */
uint32_t currentsector; /* current sector in cluster */
uint32_t currententry; /* current dir entry in sector */
uint8_t *p_scratch; /* ptr to user-supplied scratch buffer (one sector) */
uint8_t flags; /* internal DOSFS flags */
};
#include <framework/mod/options.h>
#define FAT_MAX_SECTOR_SIZE OPTION_MODULE_GET(embox__fs__driver__fat, NUMBER, fat_max_sector_size)
static inline int fat_sec_by_clus(struct fat_fs_info *fsi, int clus) {
return (clus - 2) * fsi->vi.secperclus + fsi->vi.dataarea;
}
extern void fat_set_filetime(struct fat_dirent *de);
extern void fat_get_filename(char *tmppath, char *filename);
extern int fat_check_filename(char *filename);
extern int fat_read_filename(struct fat_file_info *fi, void *p_scratch, char *name);
extern char *path_canonical_to_dir(char *dest, char *src);
extern char *path_dir_to_canonical(char *dest, char *src, char dir);
extern int fat_write_sector(struct fat_fs_info *fsi, uint8_t *buffer, uint32_t sector);
extern int fat_read_sector(struct fat_fs_info *fsi, uint8_t *buffer, uint32_t sector);
extern uint32_t fat_get_next(struct dirinfo * dirinfo, struct fat_dirent * dirent);
extern uint32_t fat_get_next_long(struct dirinfo *dir, struct fat_dirent *dirent,
char *name_buf);
extern int fat_create_partition(void *bdev, int fat_n);
extern uint32_t fat_get_ptn_start(void *bdev, uint8_t pnum, uint8_t *pactive,
uint8_t *pptype, uint32_t *psize);
extern uint32_t fat_get_volinfo(void *bdev, struct volinfo * volinfo, uint32_t startsector);
extern uint32_t fat_open_rootdir(struct fat_fs_info *fsi, struct dirinfo *dirinfo);
extern uint32_t fat_read_file(struct fat_file_info *fi, uint8_t *p_scratch,
uint8_t *buffer, uint32_t *successcount, uint32_t len);
extern uint32_t fat_write_file(struct fat_file_info *fi, uint8_t *p_scratch,
uint8_t *buffer, uint32_t *successcount, uint32_t len, size_t *size);
extern int fat_root_dir_record(void *bdev);
extern int fat_create_file(struct fat_file_info *fi, struct dirinfo *di, char *name, int mode);
extern int fat_unlike_file(struct fat_file_info *fi, uint8_t *p_scratch);
extern struct fat_fs_info *fat_fs_alloc(void);
extern void fat_fs_free(struct fat_fs_info *fsi);
extern struct fat_file_info *fat_file_alloc(void);
extern void fat_file_free(struct fat_file_info *fi);
extern struct dirinfo *fat_dirinfo_alloc(void);
extern void fat_dirinfo_free(struct dirinfo *di);
extern int fat_fill_inode(struct inode *inode, struct fat_dirent *de,
struct dirinfo *di);
struct dir_ctx;
extern int fat_iterate(struct inode *next, char *name,
struct inode *parent, struct dir_ctx *ctx);
extern int fat_delete(struct inode *node);
extern int fat_truncate(struct inode *node, off_t length);
extern int fat_entries_per_name(const char *name);
extern void fat_write_longname(char *name, struct fat_dirent *di);
extern uint8_t fat_canonical_name_checksum(const char *name);
extern int fat_reset_dir(struct dirinfo *di);
extern int read_dir_buf(struct dirinfo *di);
extern uint32_t fat_current_dirsector(struct dirinfo *di);
extern uint32_t fat_direntry_get_clus(struct fat_dirent *de);
extern void fat_direntry_set_clus(struct fat_dirent *de, uint32_t clus);
extern uint32_t fat_direntry_get_size(struct fat_dirent *de);
extern void fat_direntry_set_size(struct fat_dirent *de, uint32_t size);
extern uint8_t fat_sector_buff[FAT_MAX_SECTOR_SIZE];
#endif /* FAT_H_ */
|
C
|
/*
** dup_before_exec.c for 42sh in /home/anthony/documents/repository/PSU_2015_42sh/src/execution/exec
**
** Made by anthony
** Login <[email protected]>
**
** Started on Wed May 11 13:46:13 2016 anthony
** Last update Wed Jun 8 21:14:37 2016 teisse_m
*/
#include <stdlib.h>
#include <stdbool.h>
#include "environnement.h"
size_t get_len_env_var(const char *env_v)
{
size_t i;
i = 0;
while (env_v[i] != 0 && env_v[i] != '=')
i++;
return (i);
}
bool is_env_var(const char *env_v, const char *var)
{
while (*env_v == *var && *var != 0 && *env_v != 0)
{
env_v++;
var++;
if (*env_v == '=' && *var == 0)
return (true);
}
return (false);
}
int is_var_in_environ(const char *variable, char **env)
{
int i;
i = 0;
while (env[i] != NULL && is_env_var(env[i], variable) == false)
i++;
return ((env[i] == NULL) ? -1 : i);
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <errno.h>
/**
* 字符串缓冲中裂开
*/
int split(char *string, int stringlen, char **tokens, int maxtokens, char delim)
{
int i, tok = 0;
int tokstart = 1; /* first token is right at start of string */
if (string == NULL || tokens == NULL)
goto einval_error;
for (i = 0; i < stringlen; i++) {
if (string[i] == '\0' || tok >= maxtokens)
break;
if (tokstart) {
tokstart = 0;
tokens[tok++] = &string[i];
}
if (string[i] == delim) {
string[i] = '\0';
tokstart = 1;
}
}
return (int)tok;
einval_error:
errno = EINVAL;
return -1;
}
int main()
{
char *tokens[100] = { 0 };
char buf[] = { " $(CONSOLE_SRC_PATH)/../ oss/dynamic_bitset; / " };
int toks = split(buf, strlen(buf), tokens, sizeof(tokens) / sizeof(void*), '/');
printf("toks=%d\n", toks);
int i;
for (i = 0; i < toks; i++) {
printf("tokens[%d]={%s}\n", i, tokens[i]);
}
return 0;
}
|
C
|
#include<math.h>
int solution(int A[], int N){
int min = 1e6, i, j, temp, v1, v2;
for(i =0;i<N-1;i++) for(j =i+1;j<N;j++) {
temp = abs(A[i]-A[j]);
if (temp<min) min = temp, v1= A[i], v2 = A[j];
}
// printf("%d %d\n", v1, v2); Numbers in consideration
return min;
}
int main(int argc, char const *argv[])
{
/* code */
int A[] ={8, 24, 3, 20, 1, 17}, N=6;
printf("%d\n", solution(A, N));
return 0;
}
// Complexity O(n)
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int x;
int y;
}point;
int finding_quadrant (point coord) {
if(coord.x >= 0 && coord.y >= 0){
return 0;
}
if(coord.x < 0 && coord.y >= 0){
return 1;
}
if(coord.x < 0 && coord.y < 0){
return 2;
}
if(coord.x >= 0 && coord.y < 0){
return 3;
}
}
int main () {
int num;
int quad[4] = {0};
printf("좌표의 개수를 입력하세요 : ");
scanf("%d",&num);
point *coord = malloc(num*sizeof(point));
for(int i = 0; i < num; i++){
printf("%d 번째 점의 좌표 입력 (x,y) : ",i + 1);
scanf("%d%d",&(coord[i].x),&(coord[i].y));
quad[finding_quadrant(coord[i])]++;
}
printf("1사분면의 개수 : %d\n",quad[0]);
printf("2사분면의 개수 : %d\n",quad[1]);
printf("3사분면의 개수 : %d\n",quad[2]);
printf("4사분면의 개수 : %d\n",quad[3]);
free(coord);
return 0;
}
|
C
|
//
// Created by Martin Bobcik, xbobci00
// reseni projektu 2 do IOS
// Date: Duben 2016
//
//includy
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <wait.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/mman.h>
//KONEC includy
//ErrorCodes
#define E_SUCCESS 0
#define E_PARAMS 1
#define E_FORK 2
#define E_FOPEN 3
#define E_SHM 4
#define E_SEMAPHORE 5
//KONEC ErrorCodes
typedef struct param_s {
int p; //pocet pasazeru
int c; //kapacita voziku
int pt; //max doba generace pasazera
int rt; //max doba prujezdu trati
}param_s;
///////////deklarace funkci
int getParams(int argc, char *argv[], struct param_s *par);
void car();
void passenger();
void passengerCreator();
void myError(int errorCode);
void load();
void unload();
void run();
void board(int internProcessNumber);
void unboard(int internProcessNumber);
void cleanSHM();
int cleanSems();
void cleanUp();
///////////KONEC deklaraci funkci
//////////Globalni promenne
//ukazatel na vystupni soubor
FILE *out;
//struktura s parametrz
param_s parametry;
//pidy
pid_t pidCar, pidPCreator;
//ukazatele na sdilenou pamet
int *shm_CisloAkce, *shm_CisloPassenger, *shm_BoardOrder;
//id sdilene pameti
int shmid_CisloAkce, shmid_CisloPassenger, shmid_BoardOrder; // pro reseni algoritmu s vice vozicky pridat
//semafory // shm_CisloCar
sem_t *sem_load, *sem_allAboard, *sem_allAshore, *sem_unload, *mutex_CisloPassengerAccess, * mutex_BoardOrderAccess,\
*mutex_File, *sem_permissionToDie;
/////////KONEC Globalni promenne
int getParams(int argc, char *argv[], struct param_s *par){
int eCode = E_SUCCESS;
if(argc != 5)
return E_PARAMS;
else{
if(isdigit(*argv[1])){
par->p = strtol(argv[1],NULL,10);
if(par->p <= 0)
eCode = E_PARAMS;
}
if(isdigit(*argv[2])){
par->c = strtol(argv[2],NULL,10);
if(par->c <= 0 || par->p <= par->c || par->p % par->c != 0 )
eCode = E_PARAMS;
}
if(isdigit(*argv[3])){
par->pt = strtol(argv[3],NULL,10);
if(par->pt < 0 || par->pt >= 5001)
eCode = E_PARAMS;
}
if(isdigit(*argv[4])){
par->rt = strtol(argv[4],NULL,10);
if(par->rt < 0 || par->rt >= 5001)
eCode = E_PARAMS;
}
}
return eCode;
}
void car(){
sem_wait(mutex_File);
int cisloAkce =*shm_CisloAkce += 1;
fprintf(out,"%i\t\t: C 1\t: started\n",cisloAkce);
sem_post(mutex_File);
int i;
for(i=0; i < (parametry.p / parametry.c);i++){ // pro p/c iterac9
load(); //zavola load a ceka dokud vsichni nenastoupi
sem_wait(sem_allAboard);
run(); //vyda se na drahu
unload(); //zavola unload a ceka dokud vsichni nevystoupi
sem_wait(sem_allAshore);
}
sem_post(sem_permissionToDie); //poslat pasazerum povoleni zemrit
sem_wait(mutex_File);
cisloAkce =*shm_CisloAkce += 1;
fprintf(out,"%i\t\t: C 1\t: finished\n",cisloAkce);
sem_post(mutex_File);
exit(EXIT_SUCCESS);
}
void run(){
sem_wait(mutex_File); //uzamknu zapis
int cisloAkce =*shm_CisloAkce += 1; //ulozim si cislo aktualni akce
fprintf(out,"%i\t\t: C 1\t: run\n",cisloAkce); // zapisu do souboru
sem_post(mutex_File); // odemknu soubor
if(parametry.rt !=0) {
int runTime = rand() % parametry.rt * 1000; //spocitam random hodnotu cekani
// pokud neni maximalni hodnota cekani 0, tak cekam
usleep((useconds_t) runTime);
}
}
void unload(){
sem_wait(mutex_File);
int cisloAkce =*shm_CisloAkce += 1;
fprintf(out,"%i\t\t: C 1\t: unload\n",cisloAkce);
sem_post(mutex_File);
sem_post(sem_unload);//da pasazerum vedet, ze je mozno vystupovat
}
void load(){
sem_wait(mutex_File);
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: C 1\t: load\n",cisloAkce);
sem_post(mutex_File);
sem_post(sem_load); // pasazeri moho nastoupit
}
void passengerCreator(){
pid_t pidPassengers[parametry.p];
pid_t pidGot;
int i;
for(i = 0; i < parametry.p; i++) {
if(i!=0){
// cekani na cas vytvoreni passengera
if(parametry.pt !=0) {
int generationTime = rand() % parametry.pt * 1000;
usleep((useconds_t)generationTime);}
}
pidGot = fork();
if (pidGot < 0) {//error fork
int j;
for (j = 0; j < i; j++) { // zabije jiz vytvorene pasazery
kill(pidPassengers[j], SIGKILL);
}
cleanSHM();
cleanSems(); //vycisti pamet a skonci
myError(E_FORK);
}
else if (pidGot == 0) {// potomek
passenger();
}
else {//puvodni proces
pidPassengers[i] = pidGot;
}
}
for(i = 0; i < parametry.p; i++)
waitpid(pidPassengers[i],NULL, 0); //pocka az skonci vsichni pasazeri a skonci
exit(EXIT_SUCCESS);
}
void passenger(){
sem_wait(mutex_CisloPassengerAccess);
int internProcessNumber = *(shm_CisloPassenger) += 1;
sem_post(mutex_CisloPassengerAccess); // ulozi si sve interni cislo
//(poradi sveho vytvoreni)
sem_wait(mutex_File);
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: started\n",cisloAkce,internProcessNumber);
sem_post(mutex_File);
sem_wait(sem_load); // pocka az muze nastoupit
board(internProcessNumber); //nastoupi
//uziva si cestu
sem_wait(sem_unload); // pocka na vystup
unboard(internProcessNumber); // vystoupi
sem_wait(sem_permissionToDie); // pocka na cas sve smrti a zemre
sem_post(sem_permissionToDie);
sem_wait(mutex_File);
cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: finished\n",cisloAkce,internProcessNumber);
sem_post(mutex_File);
exit(EXIT_SUCCESS);
}
void board(int internProcessNumber){
int boardOrder;
sem_wait(mutex_BoardOrderAccess); //zjistim poradi vstupu
boardOrder = *(shm_BoardOrder)+=1;
sem_post(mutex_BoardOrderAccess);
sem_wait(mutex_File);
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: board\n",cisloAkce,internProcessNumber);
sem_post(mutex_File);
if(boardOrder!=parametry.c){ // pokud neni posledni, tak nastoupi, a rekne dalsim, ze mohou nastupovat
sem_wait(mutex_File);
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: board order %i\n",cisloAkce,internProcessNumber,boardOrder);
sem_post(mutex_File);
sem_post(sem_load);
} else{ //jinak vystoupi, vynuluje poradi nastupu a ohlasi, ze vsichni jiz nastoupili
sem_wait(mutex_File);
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: board order last\n",cisloAkce,internProcessNumber);
sem_post(mutex_File);
sem_wait(mutex_BoardOrderAccess);
*(shm_BoardOrder) = 0;
sem_post(mutex_BoardOrderAccess);
sem_post(sem_allAboard);
}
}
void unboard(int internProcessNumber) {
int boardOrder;
sem_wait(mutex_BoardOrderAccess);
boardOrder = *(shm_BoardOrder)+=1; //zjisti poradi vystupu
sem_post(mutex_BoardOrderAccess);
sem_wait(mutex_File);
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: unboard\n",cisloAkce,internProcessNumber);
sem_post(mutex_File);
if(boardOrder!=parametry.c){
sem_wait(mutex_File);//pokud neni posledni, tak vystoupi, a rekne dalsim, ze mohou vystupovat
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: unboard order %i\n",cisloAkce,internProcessNumber,boardOrder);
sem_post(mutex_File);
sem_post(sem_unload);
}else{ //jinak vystoupi, vynuluje poradi vystupu a ohlasi, ze je vozik prazdny
sem_wait(mutex_File);
int cisloAkce =*(shm_CisloAkce) += 1;
fprintf(out,"%i\t\t: P %i\t: unboard order last\n",cisloAkce,internProcessNumber);
sem_post(mutex_File);
sem_wait(mutex_BoardOrderAccess);
*(shm_BoardOrder) = 0;
sem_post(mutex_BoardOrderAccess);
sem_post(sem_allAshore);
}
}
void myError(int errorCode){
int exitCode=2;
switch (errorCode){
case E_PARAMS:
exitCode = 1;
fprintf(stderr,"CHYBA: Byly zadany spatne parametry.\n");
break;
case E_FORK:
fprintf(stderr,"CHYBA: Selhalo systemove volani fork().\n");
break;
case E_FOPEN:
fprintf(stderr,"CHYBA: Selhalo otevirani vystupniho souboru.\n");
break;
case E_SHM:
fprintf(stderr,"CHYBA: Selhala prace se sdilenou pameti.\n");
break;
case E_SEMAPHORE:
fprintf(stderr,"CHYBA: Selhala prace se semafory.\n");
break;
default:
fprintf(stderr,"CHYBA: v programu doslo k chybe.\n");
break;
}
fclose(out);
exit(exitCode);
}
void cleanSHM(){
shmctl(shmid_BoardOrder, IPC_RMID, NULL);
shmctl(shmid_CisloAkce, IPC_RMID, NULL);
shmctl(shmid_CisloPassenger, IPC_RMID, NULL);
}
int cleanSems(){
int eCode = E_SUCCESS;
if (sem_destroy(&(*sem_allAshore))==-1){
eCode = E_SEMAPHORE;
}
if (sem_destroy(&(*sem_allAboard))==-1){
eCode = E_SEMAPHORE;
}
if (sem_destroy(&(*sem_load))==-1){
eCode = E_SEMAPHORE;
}
if (sem_destroy(&(*sem_unload))==-1){
eCode = E_SEMAPHORE;
}
if (sem_destroy(&(*sem_permissionToDie))==-1){
eCode = E_SEMAPHORE;
}
if (sem_destroy(&(*mutex_BoardOrderAccess))==-1){
eCode = E_SEMAPHORE;
}
if (sem_destroy(&(*mutex_CisloPassengerAccess))==-1){
eCode = E_SEMAPHORE;
}
if (sem_destroy(&(*mutex_File))==-1){
eCode = E_SEMAPHORE;
}
return eCode;
}
void cleanUp(){
cleanSHM();
cleanSems();
fclose(out);
exit(1);
}
int main(int argc, char *argv[]){
//signal handler
signal(SIGTERM, cleanUp);
signal(SIGINT,cleanUp);
//otevrit soubor
out = fopen("proj2.out","w");
if(out == NULL){
myError(E_FOPEN);
}
setbuf(out,NULL);
//KONEC otevirani souboru
time_t seed;
srand((unsigned) time(&seed));//inicializace generatoru cisel s casovym seedem
//Parametry
if(getParams(argc, argv, ¶metry) != E_SUCCESS)
myError(E_PARAMS);
//KONEC Parametry
/////////////Inicializace sdilene pameti
int eCode = E_SUCCESS;
/////shm_CisloAkce
if ((shmid_CisloAkce=shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666))==-1) {
eCode = E_SHM;
}
if((shm_CisloAkce=(int*)shmat(shmid_CisloAkce, NULL, 0)) == (void *) -1){
eCode = E_SHM;
}
*shm_CisloAkce = 0;
/////KONEC shm_CisloAkce
/////shm_CisloPassenger
if ((shmid_CisloPassenger=shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666))==-1) {
eCode = E_SHM;
}
if((shm_CisloPassenger=(int*)shmat(shmid_CisloPassenger, NULL, 0)) == (void *) -1){
eCode = E_SHM;
}
*shm_CisloPassenger = 0;
/////KONEC shm_CisloPassenger
/////shm_boardOrder
if ((shmid_BoardOrder=shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666))==-1) {
eCode = E_SHM;
}
if((shm_BoardOrder=(int*)shmat(shmid_BoardOrder, NULL, 0)) == (void *) -1){
eCode = E_SHM;
}
*shm_BoardOrder = 0;
/////KONEC shm_boardOrder
if(eCode != E_SUCCESS) {
cleanSHM();
myError(E_SHM);
}
///////////KONEC Inicializace sdilene pameti
////////////////Semafory Inicializace
eCode = E_SUCCESS;
/////sem_AllAboard
sem_allAboard = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(sem_allAboard, 1, 0))==-1){
eCode = E_SEMAPHORE;
}
/////KONEC sem_allAboard
/////sem_allAshore
sem_allAshore = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(sem_allAshore, 1, 0))==-1){
eCode = E_SEMAPHORE;
}
/////KONEC sem_allAshore
/////sem_load
sem_load = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(sem_load, 1, 0))==-1){
eCode = E_SEMAPHORE;
}
/////KONEC sem_load
/////sem_unload
sem_unload = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(sem_unload, 1, 0))==-1){
eCode = E_SEMAPHORE;
}
/////KONEC sem_unload
/////sem_permissionToDie
sem_permissionToDie = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(sem_permissionToDie, 1, 0))==-1){
eCode = E_SEMAPHORE;
}
/////KONEC sem_permissionToDie
/////mutex_BoardOrderAccess
mutex_BoardOrderAccess = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(mutex_BoardOrderAccess, 1, 1))==-1) {
eCode = E_SEMAPHORE;
}
/////KONEC mutex_BoardOrderAccess
/////mutex_CisloPassengerAccess
mutex_CisloPassengerAccess = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(mutex_CisloPassengerAccess, 1, 1))==-1) {
eCode = E_SEMAPHORE;
}
/////KONEC mutex_CisloPassengerAccess
/////mutex_File
mutex_File = (sem_t *)mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_ANON | MAP_SHARED, -1, 0);
if((sem_init(mutex_File, 1, 1))==-1) {
eCode = E_SEMAPHORE;
}
/////KONEC mutex_File
if(eCode != E_SUCCESS) {
cleanSHM();
cleanSems();
myError(E_SEMAPHORE);
}
///////////////KONEC Inicializace semaforu
//vytvorim vozicek
pidCar = fork();
if(pidCar < 0)//fork error
{
cleanSHM();
cleanSems();
myError(E_FORK);
}
else if(pidCar == 0) {//kod pro potomka
car();
}
else {// kod pro puvodni proces
//vytvorit proces na tvorbu zakazniku
pidPCreator = fork();
if(pidPCreator < 0) // fork error
{
kill(pidCar, SIGKILL);
cleanSHM();
cleanSems();
myError(E_FORK);
}
else if(pidPCreator == 0) {//kod pro potomka
passengerCreator();
}
else {// kod pro puvodni proces
}
}
waitpid(pidCar,NULL,0);
waitpid(pidPCreator,NULL,0);
cleanSHM();
cleanSems();
fclose(out);
exit(EXIT_SUCCESS);
}
|
C
|
/*
Potion of Giantkind
File: tallpotion.c
Date: 3/24/02
Author: Feldegast
Description:
Increases height.
*/
#include "/players/feldegast/defines.h"
inherit "/obj/treasure.c";
void reset(int arg)
{
if(arg) return;
set_id("potion");
set_alias("potion of giantkind");
set_short("Potion of Giantkind");
set_long(
"This is a blue bottle filled with a thick, sticky substance. A\n"+
"picture on the side of the bottle depicts a tall looking stick\n"+
"figure.\n"
);
set_weight(1);
set_value(1000);
}
void init()
{
add_action("cmd_drink", "drink");
add_action("cmd_drink", "quaff");
add_action("cmd_drink", "sip");
}
int cmd_drink(string str)
{
object me;
int feet, inches;
me = present(str, this_player());
if(!str || this_object() != me)
{
notify_fail(capitalize(query_verb())+" what?\n");
return 0;
}
feet = (int)this_player()->query_phys_at(1);
inches = (int)this_player()->query_phys_at(2);
if(feet == 7 && inches == 11)
{
write("Nothing happens.\n");
}
else
{
if(inches == 11)
{
TP->add_phys_at(1, 1);
TP->add_phys_at(2, -11);
}
else
{
TP->add_phys_at(2, 1);
}
TP->add_phys_at(3, 1+random(5));
write("You grow in height!\n");
say(TPN+" drinks a potion and grows!\n");
}
destruct(this_object());
TP->add_weight(-1);
return 1;
}
|
C
|
#include <stdio.h>
typedef long long ll;
#define MAXN 1000000
ll e[MAXN];
void eratos()
{
ll i, j;
for (i = 0; i < MAXN; i++) e[i] = 1; // Merkjum allar tölur sem 'óséðar'.
e[0] = e[1] = 0; // Merkjum núll og einn sem 'samsettar'.
for (i = 0; i < MAXN; i++) if (e[i] == 1) // Ítrum í gegnum allar 'óséðar' tölur, og merkjum þær 'frumtölur'.
for (j = i*i; j < MAXN; j += i) e[j] = 0; // Merkjum margfeldi af frumtölum sem 'samsettar'.
}
ll isp(ll x) // Við þurfum að passa að kalla á eratos() áður en við köllum á isp(...).
{
return e[x] == 1; // Flettum upp hvort x sé frumtala.
}
int main()
{
ll i, n;
scanf("%lld", &n); // Innlestur.
eratos(); // Upphafstillum sigtið.
for (i = 0; i < n; i++) if (isp(i)) printf("%d ", i); // Prentum allar frumtölurnar.
printf("\n");
return 0;
}
|
C
|
#include <pic18f4520.h>
#include "lcd.h"
void oled_init(void)
{
_rs_pin = 0;
_rw_pin = 0;
_en_pin = 0;
oled_write_command(0x38); //FUNCTION SET INSTRUCTION
oled_write_command(0x08); //Display on/off control (off)
oled_write_command(0x01); //Display Clear
oled_write_command(0x0c); //Display ON/OFF Control (on)
oled_write_command(0x06); //Entry Mode Set 00000110
// 000001XX
// ||-- Shift Entire Display Control Bit
// | >>0: Decrement DDRAM Address by 1 when a character
// | code is written into or read from DDRAM
// | 1: Increment DDRAM Address by 1 when a character
// | code is written into or read from DDRAM
// |
// |--- Increment/Decrement bit
// 0: when writing to DDRAM, each
// entry moves the cursor to the left
// >>1: when writing to DDRAM, each
// entry moves the cursor to the right
oled_write_command(0x02); //Return Home 00000010
}
void oled_clear_display(void)
{
_en_pin = 0;
oled_write_command(0x01);
}
void oled_write_upper_line(unsigned char *string)
{
// using snprintf() with string
unsigned char i = 0;
for (; i < 12 && string[i] != NULL; i++) { //這塊LCD的DDRAM為12x2 每一格能放8bits
oled_set_DDRAM(i, 0); //先放前12格
oled_write_data(string[i]);
}
for (; i < 12; i++) { //如果string有null,替換成 ' '
oled_set_DDRAM(i, 0);
oled_write_data(' ');
}
oled_set_DDRAM(0, 0);
}
void oled_write_lower_line(unsigned char *string)
{
unsigned char i = 0;
for (; i < 12 && string[i] != NULL; i++) {
oled_set_DDRAM(i, 1);
oled_write_data(string[i]);
}
for (; i < 12; i++) {
oled_set_DDRAM(i, 1);
oled_write_data(' ');
}
oled_set_DDRAM(0, 0);
}
void oled_write_data(unsigned char value)
{
_en_pin_write = 0;
_rs_pin_write = 1;
_rw_pin_write = 0;
oled_write_8bits(value);
oled_check_busy();
}
void oled_set_DDRAM(unsigned char x, unsigned char y)
{
oled_write_command(0x80 | (y << 6) | x);
// 1000 0000 1000 0000
// + +
// 0000 0000 0100 0000
// + +
// 00xx xxxx 00xx xxxx -> from 0 ~ 12
// for first line for second line
}
void oled_write_command(unsigned char value)
{
_en_pin_write = 0;
_rs_pin_write = 0;
_rw_pin_write = 0;
oled_write_8bits(value);
oled_check_busy();
}
void oled_write_8bits(unsigned char value)
{
_data_pins = 0x00; //set output
_data_pins_write = value;
_en_pin_write = 0;
__delay_us(50);
_en_pin_write = 1;
}
void oled_check_busy(void)
{
unsigned char busy = 1;
_busy_pin = 1; // make busy pin input
_rs_pin_write = 0;
_rw_pin_write = 1;
do {
_en_pin_write = 0;
_en_pin_write = 1;
__delay_us(10);
busy = _busy_pin_read; // HIGH means not ready for next command
_en_pin_write = 0;
} while(busy);
_busy_pin = 0; // make busy pin output
_rw_pin_write = 0;
}
|
C
|
#include <math.h>
#include <stdlib.h>
#include "utone.h"
int ut_noise_create(ut_noise **ns)
{
*ns = malloc(sizeof(ut_noise));
return UT_OK;
}
int ut_noise_init(ut_data *ut, ut_noise *ns)
{
ns->amp = 1.0;
return UT_OK;
}
int ut_noise_compute(ut_data *ut, ut_noise *ns, UTFLOAT *in, UTFLOAT *out)
{
*out = ((ut_rand(ut) % UT_RANDMAX) / (UT_RANDMAX * 1.0));
*out = (*out * 2) - 1;
*out *= ns->amp;
return UT_OK;
}
int ut_noise_destroy(ut_noise **ns)
{
free(*ns);
return UT_OK;
}
|
C
|
// Cezary Stajszczyk 317354
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "traceroute.h"
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "Usege: sudo ./traceroute [address]\n");
return EXIT_FAILURE;
}
char* address = argv[1];
int socket_fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (socket_fd == -1) {
fprintf(stderr, "socket() error: %s\n", strerror(errno));
return EXIT_FAILURE;
}
/* traceroute */
traceroute(address, socket_fd);
close(socket_fd);
return EXIT_SUCCESS;
}
|
C
|
/* Partner 1 Name & E-mail: Dishon Jordan [email protected]
* Partner 2 Name & E-mail: Travis Nasser [email protected]
* Lab Section: 025
* Assignment: Lab 11 Exercise 2
* Exercise Description:
* Use the LCD code, along with a button and/or time delay to display the message
* "CS120B is Legend... wait for it DARY!" The string will not fit on the display
* all at once, so you will need to come up with some way to paginate or scroll
* the text.
*/
#include <avr/io.h>
#include "io.c"
#include <avr/interrupt.h>
#include <string.h>
volatile unsigned char TimerFlag = 0; // TimerISR() sets this to 1. C programmer should clear to 0.
// Internal variables for mapping AVR's ISR to our cleaner TimerISR model.
unsigned long _avr_timer_M = 1; // Start count from here, down to 0. Default 1 ms.
unsigned long _avr_timer_cntcurr = 0; // Current internal count of 1ms ticks
void TimerOn() {
// AVR timer/counter controller register TCCR1
TCCR1B = 0x0B;// bit3 = 0: CTC mode (clear timer on compare)
// bit2bit1bit0=011: pre-scaler /64
// 00001011: 0x0B
// SO, 8 MHz clock or 8,000,000 /64 = 125,000 ticks/s
// Thus, TCNT1 register will count at 125,000 ticks/s
// AVR output compare register OCR1A.
OCR1A = 125; // Timer interrupt will be generated when TCNT1==OCR1A
// We want a 1 ms tick. 0.001 s * 125,000 ticks/s = 125
// So when TCNT1 register equals 125,
// 1 ms has passed. Thus, we compare to 125.
// AVR timer interrupt mask register
TIMSK1 = 0x02; // bit1: OCIE1A -- enables compare match interrupt
//Initialize avr counter
TCNT1=0;
_avr_timer_cntcurr = _avr_timer_M;
// TimerISR will be called every _avr_timer_cntcurr milliseconds
//Enable global interrupts
SREG |= 0x80; // 0x80: 1000000
}
void TimerOff() {
TCCR1B = 0x00; // bit3bit1bit0=000: timer off
}
void TimerISR() {
TimerFlag = 1;
}
// In our approach, the C programmer does not touch this ISR, but rather TimerISR()
ISR(TIMER1_COMPA_vect) {
// CPU automatically calls when TCNT1 == OCR1 (every 1 ms per TimerOn settings)
_avr_timer_cntcurr--; // Count down to 0 rather than up to TOP
if (_avr_timer_cntcurr == 0) { // results in a more efficient compare
TimerISR(); // Call the ISR that the user uses
_avr_timer_cntcurr = _avr_timer_M;
}
}
// Set TimerISR() to tick every M ms
void TimerSet(unsigned long M) {
_avr_timer_M = M;
_avr_timer_cntcurr = _avr_timer_M;
}
int main(void)
{
DDRD = 0xFF; PORTD = 0x00;
DDRA = 0xFF; PORTD = 0x00;
DDRB = 0xFF; PORTB = 0x00;
DDRC = 0xF0; PORTC = 0x0F;
char text[] = "CS120B is Legend... wait for it DARY! ";
char length = strlen(text) - 1;
LCD_init();
TimerSet(400);
TimerOn();
unsigned char i = 0;
while (1)
{
for(int j = 0; j < 16; j++){
LCD_Cursor(j+1);
LCD_WriteData(text[(i+j) % length]);
}
i = (i+1)%length;
while(!TimerFlag);
TimerFlag = 0;
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdarg.h>
#ifndef _WIN32
#include <pthread.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <signal.h>
#endif
#include "sacagalib.h"
#ifdef _WIN32
HFILE* log_file;
#else
FILE* log_file;
#endif
void log_management_exit(int exitCode);
const char log_lv_name[][10] = {"ERROR", "WARNING", "INFO", "DEBUG"};
#ifndef _WIN32
void log_management() {
write_log(INFO, "Process for sacagawea.log created");
char *read_line;
int len_string, check, bytes_read;
// open logs file and check if an error occured
FILE* log;
// receive SIGTERM when parent process dies.
prctl(PR_SET_PDEATHSIG, SIGTERM);
if( pthread_mutex_lock( &(condVar->mutex) ) != 0 ){
write_log(ERROR, "LOGS Process fail on lock mutex");
pthread_mutex_destroy( &(condVar->mutex) );
pthread_cond_destroy( &(condVar->cond) );
shm_unlink(SHARED_COND_VARIABLE_MEM);
close( condVar->pipe_conf[0] );
exit(EXIT_FAILURE);
}
/* this while check if pipe is readable, or dont contain nothing.
if is empty return error EWOULDBLOCK and go again in blocked mode. */
while (true) {
check = pthread_cond_wait( &(condVar->cond) , &(condVar->mutex));
if( check != 0){
write_log(ERROR, "LOGS Process fail on cond_wait errore %d", check);
log_management_exit(EXIT_FAILURE);
}
// until cont ( number of signal received ) > 0
printf( "devo leggere %d righe at %p\n", condVar->cont, condVar);
for( ; condVar->cont>0; condVar->cont--){
check = read(condVar->pipe_conf[0] , &len_string, sizeof(int));
if (check < 0) {
write_log(ERROR, "read on log process failed becouse %s",strerror(errno));
log_management_exit(EXIT_FAILURE);
} else {
write_log(INFO, "Log file received %d bytes", len_string);
log = fopen(SACAGAWEALOGS_PATH , "a");
if (log == NULL) {
write_log(INFO, "ERROR open logs file: %s", strerror(errno));
log_management_exit(EXIT_FAILURE);
}
// read pipe and write sacagawea.log, until we got \n
read_line = (char*) malloc((len_string+1) * sizeof(char));
if( read_line == NULL ){
write_log(ERROR, "Malloc on logProcess failed becouse: %s", strerror(errno));
fclose(log);
log_management_exit(EXIT_FAILURE);
}
bytes_read = 0;
while( bytes_read < len_string ){
check = read(condVar->pipe_conf[0], &read_line[bytes_read], (len_string-bytes_read) );
if ( check < 0) {
write_log(ERROR, "read() fail becouse: %s", strerror(errno));
bytes_read = -1;
log_management_exit(EXIT_FAILURE);
}else{
bytes_read += check;
}
}
if( bytes_read == -1 ){
fclose(log);
free(read_line);
log_management_exit(EXIT_FAILURE);
}else{
read_line[len_string]='\0';
write_log(INFO, "received: %d, %s",len_string, read_line);
fprintf(log, "%s", read_line);
}
fclose(log);
free(read_line);
}
}
}
}
void log_management_exit(int exitCode) {
// if we are there, something goes wrong, close all and exit
if( pthread_mutex_unlock(&(condVar->mutex)) != 0 ){
write_log(ERROR, "LOGS Process fail unlock mutex");
}
pthread_mutex_destroy( &(condVar->mutex) );
pthread_cond_destroy( &(condVar->cond) );
shm_unlink(SHARED_COND_VARIABLE_MEM);
close( condVar->pipe_conf[0] );
exit(exitCode);
}
#endif
void write_log(int log_lv, const char* error_string, ...) {
va_list args;
va_start(args, error_string);
#define LOG_STR_LEN 1024
char* log_string = malloc(LOG_STR_LEN);
if( log_string == NULL ){
write_log(ERROR, "Malloc on writelog failed becouse: %s", strerror(errno));
exit(5);
}
char* ds = date_string();
char* formatted_error_string = malloc(LOG_STR_LEN - strlen(ds));
if( formatted_error_string == NULL ){
write_log(ERROR, "Malloc on writelog failed becouse: %s", strerror(errno));
exit(5);
}
vsnprintf(formatted_error_string, LOG_STR_LEN - strlen(ds),
error_string, args);
// make sure that the string ends with no trailing newlines ('\n')
while(formatted_error_string[strlen(formatted_error_string)-1] == '\n') {
formatted_error_string[strlen(formatted_error_string)-1] = '\0';
}
if (snprintf(log_string, LOG_STR_LEN, "%s %s: %s\n", ds, log_lv_name[log_lv],
formatted_error_string) < 0) {
fprintf(stderr, "ERROR: snprintf() failed: %s\n", strerror(errno));
}
free(ds);
if (log_lv <= WARNING) {
fprintf(stderr, "%s", log_string);
fflush(stderr);
} else if (log_lv <= LOG_LEVEL) {
fprintf(stdout, "%s", log_string);
fflush(stdout);
// return;
}
free(formatted_error_string);
free(log_string);
va_end(args);
}
// returned string needs to be freed
char* date_string() {
size_t len_str = 22; // for "[MMM DD YYYY hh:mm:ss]"
char* r = malloc(len_str+1);
if( r == NULL ){
write_log(ERROR, "Malloc on date_string failed becouse: %s", strerror(errno));
exit(5);
}
time_t rawtime;
struct tm* timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char* timestr = asctime(timeinfo);
char month[4] = {timestr[4], timestr[5], timestr[6], 0};
if (snprintf(r, len_str+1, "[%s %02d %04d %02d:%02d:%02d]",
month, timeinfo->tm_mday, timeinfo->tm_year + 1900,
timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec) < 0) {
free(timeinfo);
write_log(ERROR, "snprintf() failed: %s\n", strerror(errno));
exit(5);
}
return r;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int nb1,nb2,nb3;
int tmp=0;
printf("Nombre 1= ");
scanf("%d", &nb1);
printf("Nombre 2= ");
scanf("%d", &nb2);
printf("Nombre 3= ");
scanf("%d", &nb3);
printf("Init %d, %d, %d\n", nb1, nb2, nb3);
if(nb1<nb2){
tmp=nb1;
nb1=nb2;
nb2=tmp;
}
if(nb1<nb3){
tmp=nb1;
nb1=nb3;
nb3=tmp;
}
if(nb2<nb3){
tmp=nb3;
nb3=nb2;
nb2=tmp;
}
printf("%d < %d < %d\n", nb3, nb2, nb1);
return 0;
}
|
C
|
#define _WIN32_WINNT 0x0500
#define WIN32_LEAN_AND_MEAN
#include <winstrct.h>
#include <winioctl.h>
#include <stdlib.h>
/*
#ifdef _DLL
#pragma comment(lib, "minwcrt.lib")
#endif
*/
int
main(int argc, char **argv)
{
LARGE_INTEGER FileSize;
HANDLE hFile;
char cSuffix;
BOOL bSetSparse = FALSE;
DWORD dw;
if (argc == 4)
if (strcmpi(argv[1], "-s") == 0)
{
bSetSparse = TRUE;
argc--;
argv++;
}
if (argc != 3)
{
puts("CHSIZE32.EXE - freeware by Olof Lagerkvist.\r\n"
"http://www.ltr-data.se [email protected]\r\n"
"Utility to change size of an existing file, or create a new file with specified"
"size.\r\n"
"\n"
"Syntax:\r\n"
"\n"
"CHSIZE32 [-s] file size[K|M|G|T]\r\n"
"\n"
"-s Set sparse attribute.");
return 0;
}
switch (sscanf(argv[2], "%I64i%c", &FileSize, &cSuffix))
{
case 2:
switch (cSuffix)
{
case 0:
break;
case 'T': case 't':
FileSize.QuadPart <<= 10;
case 'G': case 'g':
FileSize.QuadPart <<= 10;
case 'M': case 'm':
FileSize.QuadPart <<= 10;
case 'K': case 'k':
FileSize.QuadPart <<= 10;
break;
default:
fprintf(stderr, "Unknown size extension: %c\n", cSuffix);
return 1;
}
case 1:
break;
default:
fprintf(stderr, "Expected file size, got \"%s\"\n", argv[2]);
return 1;
}
hFile = CreateFile(argv[1], GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
win_perror(argv[1]);
return 1;
}
if (bSetSparse)
if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &dw, NULL))
win_perror("Error setting sparse attribute");
if ((SetFilePointer(hFile, FileSize.LowPart, &FileSize.HighPart,
FILE_BEGIN) == 0xFFFFFFFF) ?
(GetLastError() != NO_ERROR) : FALSE)
{
win_perror(NULL);
return 1;
}
if (SetEndOfFile(hFile))
return 0;
win_perror(NULL);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age = 25, argent = 8001;
if(age >= 30 || argent >= 8000)
{
printf("Vous etes accepte comme client \n");
}
else
{
printf("hors de ma vue \n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double get_Value();
int main() {
double x = get_Value();
double y = get_Value();
printf("%lf %lf", x, y);
FILE* out;
out = fopen("results.txt", "w");
if (out == NULL) {
printf("Cannot open file!\n");
exit(1);
}
fprintf(out, "%lf\n", x + y);
fprintf(out, "%lf\n", x - y);
fprintf(out, "%lf\n", x * y);
fprintf(out, "%lf\n", x / y);
fclose(out);
return 0;
}
double get_Value() {
char fileName[100];
fgets(fileName, 100, stdin);
fileName[strlen(fileName) - 1] = '\0';
// open input files
FILE* in = fopen(fileName, "r");
// when openning error
if (in == NULL) {
printf("Cannot open file!\n");
exit(1);
}
// store double values
double x;
fscanf(in, "%lf", &x);
fclose(in);
return x;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LEN 1024
int main () {
char line [MAX_LINE_LEN];
FILE *in = fopen ("a", "r");
if (!in) exit (EXIT_FAILURE);
while (fgets(line, MAX_LINE_LEN, in) != NULL) {
char *sep = strchr(line , ':');
if (!sep) exit (EXIT_FAILURE);
*sep = '\0';
printf("%s\n", line);
}
fclose(in);
return EXIT_SUCCESS ;
}
|
C
|
//insert a word taken by user in a sentence after no of words that count should taken by the user
#include<stdio.h>
#include<string.h>
int main()
{
int l1,l2,k1,i,j,flag=0;
char a[50]="hi hello how are you friends";
printf("before:::: %s\n",a);
char b[20];
l1=strlen(a);
int count,e=0;
printf("enter a word\n");
scanf("%s",b);
printf("enter a count of word\n");
scanf("%d",&count);
for(i=0;i<=l1+1;i++)
{
if(a[i]==' ' || a[i]=='\0')
e++;
if(e==count)
{
for(l2=0;b[l2];l2++);
if(e>0 && a[i]!='\0')
i++;
if(a[i]=='\0')
flag=1;
for(j=0;l2>=0;l2--)
{
for(k1=l1;k1>=-1;k1--)
{
a[k1+1]=a[k1];
if(i==k1)
break;
}
l1++;
if(b[j]=='\0')
{
a[i]=' ';
continue;
}
if(flag==1)
{
a[i]=' ';
i++;
flag=0;
continue;
}
a[i]=b[j];
i++;
j++;
}
break;
}
}
printf("after::::%s\n",a);
}
|
C
|
/*
** EPITECH PROJECT, 2020
** Dante's Star (solver)
** File description:
** astar_neighbours.c -- No description
*/
#include <limits.h>
#include <stddef.h>
#include "solver.h"
static int get_y(direction_t dir, anode_t *parent)
{
switch (dir) {
case LEFT:
case RIGHT: return parent->y;
case DOWN: return parent->y + 1;
case UP: return parent->y - 1;
default: return -1;
}
}
static int get_x(direction_t dir, anode_t *parent)
{
switch (dir) {
case DOWN:
case UP: return parent->x;
case LEFT: return parent->x - 1;
case RIGHT: return parent->x + 1;
default: return -1;
}
}
void astar_search_neighbour(
direction_t dir, bool clist[YMAX][XMAX], cell_t cell[YMAX][XMAX])
{
unsigned long cnew = ADATA->parent.c + 1;
int y = get_y(dir, &ADATA->parent);
int x = get_x(dir, &ADATA->parent);
cell_t *neighbour = NULL;
if (!is_valid(y, x))
return;
neighbour = &cell[y][x];
if (is_dest(y, x)) {
neighbour->parent.y = ADATA->parent.y;
neighbour->parent.x = ADATA->parent.x;
ADATA->done = true;
} else if (clist[y][x] && is_path(y, x) && neighbour->c > cnew) {
astack_push(&ADATA->olist, cnew, y, x);
neighbour->c = cnew;
neighbour->parent.y = ADATA->parent.y;
neighbour->parent.x = ADATA->parent.x;
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int myCompare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
void sort_func(char* file_name)
{
char ch;
char arr[100][1000];
char line[100];
FILE *fp;
fp = fopen(file_name, "r");
if (fp == NULL)
{
perror("Error");
}
else{
int i = 0;
while(fscanf(fp,"%[^\n]\n",line)!=EOF)
{
int j=0;
while(j<1000){
arr[i][j]=line[j];
j++;
}
i++;
if (i==100){
char *text = "Error: File is large";
printf("%s\n", text); //"File is large.\n"
break;
}
}
if(i!=100){
char* arr1[i];
int u = 0;
while(u < i){
arr1[u] = arr[u];
u++;
}
qsort (arr1, i, sizeof (char *), myCompare);
char* c;
int k = 0;
fclose(fp);
k = 0;
fp = fopen(file_name,"w+");
while(k<i){
fprintf(fp,"%s\n", arr1[k]);
k++;
}
}
fclose(fp);
}
}
void sort_func_o(char* file_name1, char* file_name2)
{
char ch;
char arr[100][1000];
char line[100];
FILE *fp;
fp = fopen(file_name1, "r");
if (fp == NULL)
{
perror("Error");
}
else{
int i = 0;
while(fscanf(fp,"%[^\n]\n",line)!=EOF)
{
int j=0;
while(j<1000){
arr[i][j]=line[j];
j++;
}
i++;
if (i==100){
char *text = "Error: File is large";
printf("%s\n", text); //"File is large.\n"
break;
}
}
if(i!=100){
char* arr1[i];
int u = 0;
while(u < i){
arr1[u] = arr[u];
u++;
}
qsort (arr1, i, sizeof (char *), myCompare);
char* c;
int k = 0;
fclose(fp);
k = 0;
fp = fopen(file_name2,"w+");
while(k<i){
fprintf(fp,"%s\n", arr1[k]);
k++;
}
}
fclose(fp);
}
}
void sort_func_r(char* file_name)
{
char ch;
char arr[100][1000];
char line[100];
FILE *fp;
fp = fopen(file_name, "r");
if (fp == NULL)
{
perror("Error");
}
else{
int i = 0;
while(fscanf(fp,"%[^\n]\n",line)!=EOF)
{
int j=0;
while(j<1000){
arr[i][j]=line[j];
j++;
}
i++;
if (i==100){
char *text = "Error: File is large";
printf("%s\n", text); //"File is large.\n"
break;
}
}
if(i!=100){
char* arr1[i];
int u = 0;
while(u < i){
arr1[u] = arr[u];
u++;
}
qsort (arr1, i, sizeof (char *), myCompare);
char* c;
int k = 0;
fclose(fp);
k = i-1;
fp = fopen(file_name,"w+");
while(k > -1){
fprintf(fp,"%s\n", arr1[k]);
k--;
}
}
fclose(fp);
}
}
// int main(int argc, char* argv[])
// {
// char* file_name = argv[1];
// sort_func(file_name);
// return 0;
// }
|
C
|
/*4、c语言中有一个函数strstr(3)的功能是在字符串中找子串
,尝试自己定义一个函数实现其功能*/
#include <stdio.h>
#include <string.h>
int findStr1(char *s,char *l);
int main()
{
char s[100] = "";
char l[10]="";
char *p;
printf("请输入源字符串:");
gets(s);
//scanf("%s",s);
printf("请输入要查找的字符串:");
gets(l);
//scanf("%s",l);
findStr1(s,l);
return 0;
}
int findStr1(char *s,char *l)
{
int j, m=1;
for ( j = 0; j < strlen(s); j++)
{
if (s[j] == l[0])
{
for (int i = 1; i < strlen(l);i++)
{
if (s[j+i] == l[i])
{
m++;
}
}
if (m==strlen(l))
{
char *p1 = &s[j];
puts(p1);
printf("首次出现位置:%d\n",++j);
j=0;
break;
}
}
}
if(j==strlen(s)){
printf("not found\n");
}
return 0;
}
|
C
|
/*!
* \file ringbuf.c
* \brief Implementation of ring buffer data structure.
*
* \date create: 2011/8/25
* \author hac <Ping-Jhih Chen>
* \sa ringbuf.h
*/
/* generic */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#include <assert.h>
/* misc */
#include <getopt.h>
/* UNIX system call */
#include <sys/types.h>
#include <sys/stat.h>
#include "ringbuf.h"
/*!
* \brief Reset/clean the ring content
* \param ring The ring buffer to clean
*/
extern void ringbuf_reset(ringbuf_t *ring)
{
if (ring == NULL) return;
if (ring->container != NULL) {
memset(ring->container, 0x00, ring->size);
}
ring->needle = 0;
}
static void __buffer_init(ringbuf_t *ring, const int size)
{
if (ring == NULL) return;
/* release old resource */
if (ring->container_buf != NULL) free(ring->container_buf);
if (ring->container != NULL) free(ring->container);
/* allocate new ring */
ring->container_buf = malloc(size + 1); // add one more byte for '\0' padding
assert(ring->container_buf != NULL);
memset(ring->container_buf, 0x00, size + 1);
ring->container = malloc(size + 1);
assert(ring->container != NULL);
memset(ring->container, 0x00, size + 1);
/* reset offset counter */
ring->size = size;
ring->needle = 0;
}
/*!
* \brief Create a new ring buffer and initialize it.
* \param size The max size of created ring buffer
* \return A pointer to created ring buffer
* \return NULL if error
*/
extern ringbuf_t *ringbuf_create(const int size)
{
ringbuf_t *ring;
ring = (ringbuf_t *) malloc(sizeof(*ring));
assert(ring != NULL);
memset(ring, 0x00, sizeof(*ring));
__buffer_init(ring, size);
return ring;
}
/*!
* \brief Destroy a ring
* \param ring The ring buffer to destroy
* \sa ringbuf_create
*/
extern void ringbuf_destroy(ringbuf_t *ring)
{
if (ring == NULL) return;
if (ring->container_buf != NULL) free(ring->container_buf);
if (ring->container != NULL) free(ring->container);
return;
}
/*!
* \brief Save input into the ring.
* \param ring Input ring buffer
* \param input New content to saved in ring buffer
* \param input_len New content length (bytes)
* \return >= 0 if ok
* \return < 0 if error
* \note Automatically rotate the ring iff. buffer overflow.
*/
extern int ringbuf_input(ringbuf_t *ring, const char *input, int input_len)
{
int delete_len = 0;
assert(ring != NULL);
if (input_len >= ring->size) {
/*
* input overflow, copy newer input to container
* (* WARNING: older input is lost)
*/
memcpy(ring->container, input + (input_len - ring->size), ring->size);
ring->needle = ring->size;
} else if (ring->needle + input_len > ring->size) {
/*
* ring overflow, delete older container
*/
delete_len = (ring->needle + input_len) - ring->size;
assert(delete_len > 0);
/* copy newer content to buffer */
memset(ring->container_buf, 0x00, ring->size);
memcpy(ring->container_buf, ring->container + delete_len, ring->needle - delete_len);
/* clean ring */
memset(ring->container, 0x00, ring->size);
/* copy buffer content to ring container */
memcpy(ring->container, ring->container_buf, ring->needle - delete_len);
memcpy(ring->container + (ring->needle - delete_len), input, input_len);
ring->needle = (ring->needle + input_len) - delete_len;
} else {
/*
* append new content to ring container directly
*/
memcpy(ring->container + ring->needle, input, input_len);
ring->needle += input_len;
}
return input_len;
}
/*!
* \brief Rotate the ring buffer, i.e. delete older ring container & re-arrange the ring
* \param ring Input ring buffer
* \param rotate_len Rotate length (bytes)
* \return Current used ring buffer size (i.e. needle offset)
*/
extern int ringbuf_rotate(ringbuf_t *ring, int rotate_len)
{
assert(ring != NULL);
if (rotate_len >= ring->needle) {
/*
* delete all container
*/
memset(ring->container, 0x00, ring->size);
ring->needle = 0;
} else {
/* move reserved container to buffer */
memcpy(ring->container_buf, ring->container + rotate_len, ring->needle - rotate_len);
/* clean container */
memset(ring->container, 0x00, ring->size);
/* copy buffer to container */
memcpy(ring->container, ring->container_buf, ring->needle - rotate_len);
ring->needle -= rotate_len;
}
return ring->needle;
}
/*!
* \brief Get current ring needle position i.e. current content size
* \param ring Input ring buffer
* \return The offset of ring needle
* \note The offset is equal to current saved content size (bytes)
*/
extern int ringbuf_get_needle(ringbuf_t *ring)
{
assert(ring != NULL);
return ring->needle;
}
/*!
* \brief Get max size (bytes) of input ring buffer
* \param ring Input ring buffer
* \return Max ring buffer size (bytes)
* \note Max size != currently used size
*/
extern int ringbuf_get_size(ringbuf_t *ring)
{
assert(ring != NULL);
return ring->size;
}
/*!
* \brief Get the ring buffer
* \param ring Ring buffer to fetch its container
* \return A pointer to the container
* \return NULL, otherwise
*/
extern void *ringbuf_get_container(ringbuf_t *ring)
{
assert(ring != NULL);
return (void *) ring->container;
}
|
C
|
#include <stdio.h>
int main(void)
{
int no;
printf("enter the number:");
scanf("%d",&no);
no+=1;
while(no%10!=0)
{
no=no+1;
}
printf("\n%d",no);
return 0;
}
|
C
|
/* Checks that BOLT correctly processes a user-provided function list file,
* reorder functions according to this list, update hot_start and hot_end
* symbols and insert a function to perform hot text mapping during program
* startup.
*/
#include <stdio.h>
int foo(int x) {
return x + 1;
}
int fib(int x) {
if (x < 2)
return x;
return fib(x - 1) + fib(x - 2);
}
int bar(int x) {
return x - 1;
}
int main(int argc, char **argv) {
printf("fib(%d) = %d\n", argc, fib(argc));
return 0;
}
/*
REQUIRES: system-linux
RUN: %host_cc %s -o %t.exe -Wl,-q
RUN: llvm-bolt %t.exe -relocs=1 -lite -reorder-functions=user \
RUN: -hugify -function-order=%p/Inputs/user_func_order.txt -o %t
RUN: nm -ns %t | FileCheck %s -check-prefix=CHECK-NM
RUN: %t 1 2 3 | FileCheck %s -check-prefix=CHECK-OUTPUT
CHECK-NM: W __hot_start
CHECK-NM: T main
CHECK-NM-NEXT: T fib
CHECK-NM-NEXT: W __hot_end
CHECK-OUTPUT: fib(4) = 3
*/
|
C
|
/*
* A small program that illustrates how to call the maxofthree function we wrote in
* assembly language.
*/
// compile by: gcc wc.c asm_wc.o
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int64_t wc(char* s);
int main(int argc, char *argv[]) {
// file handle
FILE *fh;
// open file for reading
if ((fh = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Unable to open file <%s>", argv[1]);
return 1;
}
char line[256];
while(fgets(line, 256, fh)) {
printf("%ld\n", wc(line));
}
fclose(fh);
return 0;
}
|
C
|
/*
* video.c
*
* Implementation of video.h functions
*
*/
#include "video.h"
#include <math.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
/*----------------------------------------------------------------------------------------------------------*/
void convert_grayscale_to_rgb(unsigned char *pixels, unsigned char processedPixels[][FRAME_WIDTH], unsigned int width,
unsigned int height) {
int i;
for(i = 0; i < height * width * 3; i+=3) {
int shift = i / 3;
int row = shift / width;
int col = shift % width;
pixels[i] = 0; // red;
pixels[i + 1] = 0; // green
pixels[i + 2] = processedPixels[row][col];
}
}
void filter(unsigned char *pixels, unsigned char processedPixels[][FRAME_WIDTH], unsigned int width, unsigned int height){
int i;
unsigned int totalPixels = sizeof(unsigned char) * width * height * 3;
for(i = 0; i < totalPixels; i+=3) {
int r = pixels[i];
int g = pixels[i + 1];
int b = pixels[i + 2];
int db = (b - 255) * (b - 255);
int dg = (g - 255) * (g - 255);
int dr = (r - 255) * (r - 255);
double deltaSum = dr + dg + db;
double distance = sqrt(deltaSum);
// printf("%d %d %d %f\n", r, g, b, distance);
if(distance > 10) {
r = 0;
g = 0;
b = 0;
}
int shift = i / 3;
int row = shift / width;
int col = shift % width;
processedPixels[row][col] = (unsigned char)b;
}
}
void print_point(coord co) {
printf("(%d,%d) ", co.x, co.y);
}
int find_collinear(coord refPoint, coord *point1, coord *point2, coord *points, int numPoints, double errorRate) {
coord p1, p2;
int j, k;
for(j = 0; j < numPoints; j++) {
p1 = points[j];
if(p1.x == refPoint.x && p1.y == refPoint.y) {
continue;
} else {
double m1 = gradient(refPoint, p1);
// find another point with gradient = m1
for(k = 0; k < numPoints; k++) {
p2 = points[k];
if((p2.x == refPoint.x && p2.y == refPoint.y) || (p2.x == p1.x && p2.y == p1.y)) {
continue;
} else {
double m2 = gradient(refPoint, p2);
if(fabs(m1 - m2) <= 0.04) {
point1->x = p1.x; point1->y = p1.y;
point2->x = p2.x; point2->y = p2.y;
return 1;
}
}
}
} // end else
}
return 0;
}
int collinear_contains(collinear co, coord c) {
if(co.point1.x == c.x && co.point1.y == c.y) {
return 1;
}
if(co.point2.x == c.x && co.point2.y == c.y) {
return 1;
}
if(co.point3.x == c.x && co.point3.y == c.y) {
return 1;
}
return 0;
}
int collinear_already_added(collinear co, collinear *points, int numPoints) {
int i;
for(i = 0; i < numPoints; i++ ) {
collinear c = {points[i].point1, points[i].point2, points[i].point3};
if(collinear_contains(c, co.point1) && collinear_contains(c, co.point2) &&
collinear_contains(c, co.point3)) {
return 1;
}
}
return 0;
}
int compare_points(coord c1, coord c2) {
if(c1.x > c2.x) {
return 1;
}
if(c1.x == c2.x) {
if(c1.y > c2.y){
return 1;
}
if(c1.y == c2.y) {
return 0;
}
}
return -1;
}
coord get_smallest_coord(collinear *co) {
coord p1 = co->point1;
coord p2 = co->point2;
coord p3 = co->point3;
coord small;
if(compare_points(p1, p2) == 1) {
small.x = p2.x; small.y = p2.y;
} else {
small.x = p1.x; small.y = p1.y;
}
if(compare_points(small, p3) == 1) {
small.x = p3.x; small.y = p3.y;
}
return small;
}
coord get_largest_coord(collinear *co) {
coord p1 = co->point1;
coord p2 = co->point2;
coord p3 = co->point3;
coord big;
if(compare_points(p1, p2) == 1) {
big.x = p1.x; big.y = p1.y;
} else {
big.x = p2.x; big.y = p2.y;
}
if(compare_points(big, p3) == -1) {
big.x = p3.x; big.y = p3.y;
}
return big;
}
void order_coords(collinear *co) {
coord small = get_smallest_coord(co);
coord big = get_largest_coord(co);
coord middle ;
int isOne, isTwo, isThree;
isOne = isTwo = isThree = 0;
if(co->point1.x == small.x && co->point1.y == small.y || co->point1.x == big.x && co->point1.y == big.y) {
isOne = 1;
}
if(co->point2.x == small.x && co->point2.y == small.y || co->point2.x == big.x && co->point2.y == big.y) {
isTwo = 1;
}
if(co->point3.x == small.x && co->point3.y == small.y || co->point3.x == big.x && co->point3.y == big.y) {
isThree = 1;
}
if(!isOne) {
middle = co->point1;
}
if(!isTwo) {
middle = co->point2;
}
if(!isThree) {
middle = co->point3;
}
co->point1 = small;
co->point2 = middle;
co->point3 = big;
}
int get_more_straight_sides(coord centerCoords[MAX_BLOBS], int numBlobs, collinear linear[MAX_BLOBS]) {
int i;
double PERCENTAGE_ERROR = 0.05;
coord point1, point2, point3;
int num = 0;
int size = numBlobs;
for(i = 0; i < numBlobs; i++) {
point1 = centerCoords[i];
int found = find_collinear(point1, &point2, &point3, centerCoords, numBlobs, PERCENTAGE_ERROR);
if(found) {
collinear co = {point1, point2, point3};
order_coords(&co);
if(!collinear_already_added(co, linear, num)) {
// remove points which do not have 2:1 or 1:1 ratio distance between
double d1 = distance(co.point1, co.point2);
double d2 = distance(co.point2, co.point3);
double big = max(d1, d2);
double small = min(d1, d2);
int ratio = (int)round(big/small);
// only consider points with ratio 2:1 or 1:1
if(ratio == 2 || ratio == 1) {
linear[num].point1.x = co.point1.x;
linear[num].point2.x = co.point2.x;
linear[num].point3.x = co.point3.x;
linear[num].point1.y = co.point1.y;
linear[num].point2.y = co.point2.y;
linear[num].point3.y = co.point3.y;
num++;
}
}
}
}
return num;
}
int get_short_side(coord* centerCoords, int numCenters, collinear linear, collinear *foundPoints) {
int i, j;
// check if this collinear points have a corresponding short or long side
for(i = 0; i < numCenters; i++) {
coord p1 = centerCoords[i];
int alreadyIn = collinear_contains(linear, p1);
if(!alreadyIn) {
double d1 = distance(p1, linear.point2);
for(j = 0; j < numCenters; j++) {
coord p2 = centerCoords[j];
alreadyIn = collinear_contains(linear, p2);
if(!alreadyIn && compare_points(p1, p2) != 0) {
double d2 = distance(p2, linear.point2);
int ratio = (int)round(d2/d1);
if(ratio == 1) {
foundPoints->point1 = p1;
foundPoints->point2 = linear.point2;
foundPoints->point3 = p2;
return 1;
}
}
}
}
}
return 0;
}
int get_long_side(coord* centerCoords, int numCenters, collinear linear, collinear *foundPoints) {
int i, j;
// check if this collinear points have a corresponding short or long side
for(i = 0; i < numCenters; i++) {
coord p1 = centerCoords[i];
int alreadyIn = collinear_contains(linear, p1);
if(!alreadyIn) {
double d1 = distance(p1, linear.point2);
for(j = 0; j < numCenters; j++) {
coord p2 = centerCoords[j];
alreadyIn = collinear_contains(linear, p2);
if(!alreadyIn && compare_points(p1, p2) != 0) {
double d2 = distance(p2, linear.point2);
double big = max(d1, d2);
double small = min(d1, d2);
int ratio = (int)round(big/small);
if(ratio == 2) {
foundPoints->point1 = p1;
foundPoints->point2 = linear.point2;
foundPoints->point3 = p2;
return 1;
}
}
}
}
}
return 0;
}
void get_blob_centers(blob blobs[MAX_BLOBS], int numBlobs, coord centerCoords[MAX_BLOBS]) {
int i;
for(i = 0; i < numBlobs; i++) {
centerCoords[i] = get_blob_center(blobs[i]);
}
}
void extract_blobs(blob blobs[MAX_BLOBS], int numBlobs, int blobLabels[][FRAME_WIDTH],
int width, int height) {
int i, j;
// create some room to store the blob points
for(i = 0; i < numBlobs; i++) {
// just create some room
int defaultSize = 10;
blobs[i].points = (coord *)malloc(sizeof(coord) * defaultSize);
blobs[i].size = defaultSize;
blobs[i].numPoints = 0;
}
for(i = 0; i < height; i++) {
for(j = 0; j < width; j++) {
int label = blobLabels[i][j];
if(label < numBlobs && label >= 0) {
int size = blobs[label].size;
if((blobs[label].numPoints + 1) == size) {
int newSize = blobs[label].size * 2;
blobs[label].points = (coord*)realloc(blobs[label].points, sizeof(coord)* newSize);
blobs[label].size = newSize;
}
coord *points = blobs[label].points;
int numPoints = blobs[label].numPoints;
points[numPoints].x = j;
points[numPoints].y = i;
blobs[label].numPoints++;
}
}
}
}
int apply_blob_size_heuristic(blob blobs[MAX_BLOBS], int numBlobs) {
int i;
for(i = 0; i < numBlobs; i++) {
// numbers choosen arbitrarily from analysis
if(blobs[i].numPoints < 20 || blobs[i].numPoints > 2500) {
// remove this small/big blob
free(blobs[i].points);
blobs[i].points = blobs[numBlobs - 1].points;
blobs[i].numPoints = blobs[numBlobs - 1].numPoints;
blobs[i].size = blobs[numBlobs - 1].size;
numBlobs--;
i--;
}
}
return numBlobs;
}
void free_blobs(blob *blobs, int numBlobs) {
int i;
// free the points first
for(i = 0; i < numBlobs; i++) {
free(blobs[i].points);
}
//free(blobs);
}
coord get_blob_center(blob bl) {
int i;
int xSum, ySum;
xSum = ySum = 0;
coord *points = bl.points;
for(i = 0; i < bl.numPoints; i++) {
xSum += points[i].x;
ySum += points[i].y;
}
int xCenter = (int)(xSum / bl.numPoints);
int yCenter = (int)(ySum / bl.numPoints);
coord center = {xCenter, yCenter};
return center;
}
void draw_box(unsigned char *frame, int x, int y, int w, int h) {
int i;
int loc, loc1;
int X1, X2, Y1, Y2;
for(i = 0; i < w; i++) {
X1 = max((x- w/2), 0);
Y1 = max((y - h/2), 0);
Y2 = min((y + h/2), 479);
loc = ((FRAME_WIDTH * Y1) + (i + X1)) * 3;
loc1 = ((FRAME_WIDTH * Y2) + (i + X1)) * 3;
frame[loc] = (unsigned char) 255;
frame[loc + 1] = (unsigned char) 255;
frame[loc + 2] = (unsigned char) 255;
frame[loc1] = (unsigned char) 255;
frame[loc1 + 1] = (unsigned char) 255;
frame[loc1 + 2] = (unsigned char) 255;
}
for(i = 0; i < h; i++) {
Y1 = max((y- h/2), 0);
X1 = max((x - w/2), 0);
X2 = min((x + w/2), 639);
loc = ((FRAME_WIDTH * (i + Y1)) + X1) * 3;
loc1 = ((FRAME_WIDTH * (i + Y1)) + X2) * 3;
frame[loc] = (unsigned char) 255;
frame[loc + 1] = (unsigned char) 255;
frame[loc + 2] = (unsigned char) 255;
frame[loc1] = (unsigned char) 255;
frame[loc1 + 1] = (unsigned char) 255;
frame[loc1 + 2] = (unsigned char) 255;
}
}
int is_long_side(collinear co) {
// long side has ration 2:1 between points
double d1 = distance(co.point1, co.point2);
double d2 = distance(co.point2, co.point3);
double big = max(d1, d2);
double small = min(d1, d2);
int ratio = (int)round(big/small);
if(ratio == 2) {
return 1;
} else {
return 0;
}
}
int is_short_side(collinear co) {
// long side has ration 1:1 between points
double d1 = distance(co.point1, co.point2);
double d2 = distance(co.point2, co.point3);
double big = max(d1, d2);
double small = min(d1, d2);
int ratio = (int)round(big/small);
if(ratio == 1) {
return 1;
} else {
return 0;
}
}
double gradient(coord p1, coord p2) {
int deltaY = p1.y - p2.y;
int deltaX = p1.x - p2.x;
if(deltaX == 0) {
return INT_MAX;
} else {
return ((deltaY * 1.0) / (deltaX * 1.0));
}
}
double distance(coord p1, coord p2) {
double deltaY = p1.y - p2.y;
double deltaX = p1.x - p2.x;
return (sqrt((deltaY * deltaY) + (deltaX * deltaX)));
}
void print_image(coord centerCoords[MAX_BLOBS], int numCoords, coord shapeCoords[5], int numShapes) {
double scale_x = FRAME_WIDTH / 64.0;
double scale_y = FRAME_HEIGHT / 32.0;
int i, j;
int cols = 64;
int blobs[32][cols];
for(i = 0; i < 32; i++) {
for(j = 0; j < cols; j++) {
blobs[i][j] = 0;
}
}
for(i = 0; i < numCoords; i++) {
int x = round(centerCoords[i].x * 1.0 / scale_x);
int y = round(centerCoords[i].y * 1.0 / scale_y);
if(x > 0 && x < cols && y > 0 && y < 32) {
int found = 0;
for(j = 0; j < 5; j++) {
if(centerCoords[i].x == shapeCoords[j].x && centerCoords[i].y == shapeCoords[j].y ) {
found = 1;
break;
}
}
if(found) {
blobs[y][x] = 2;
} else {
blobs[y][x] = 1;
}
}
}
printf("\n");
printf("\t*");
for(i = 0; i < cols; i++){
printf("-");
}
printf("*\n");
for(i = 0; i < 32; i++) {
printf("\t|");
for(j = 0; j < cols; j++) {
if(blobs[i][j] == 0) {
printf(" ");
} else if(blobs[i][j] == 1){
printf(".");
} else {
printf("x");
}
}
printf("|\n");
}
printf("\t*");
for(i = 0; i < cols; i++){
printf("-");
}
printf("*\n");
}
double distance_from_center(coord shapeCenter) {
int imageCenterX = FRAME_WIDTH / 2;
int imageCenterY = FRAME_HEIGHT / 2;
coord center;
center.x = imageCenterX;
center.y = imageCenterY;
return distance(shapeCenter, center);
}
int quadrant(coord c1) {
int imageCenterX = FRAME_WIDTH / 2;
int imageCenterY = FRAME_HEIGHT / 2;
coord center;
center.x = imageCenterX;
center.y = imageCenterY;
// 1st or 2nd
if(c1.y >= center.y) {
if(c1.x <= center.x) {
return 1;
} else {
return 2;
}
} else {
// 3rd or 4th
if(c1.x <= center.x) {
return 4;
} else {
return 3;
}
}
}
double angle(coord p1, coord p2) {
double deltaY = p1.y - p2.y;
double deltaX = p1.x - p2.x;
if(deltaX == 0) {
return 90.0;
} else {
double angle = atan(deltaY / deltaX) * 180 / PI;
return fabs(angle);
}
}
double quadrant_angle(coord p1) {
int quad = quadrant(p1);
int imageCenterX = FRAME_WIDTH / 2;
int imageCenterY = FRAME_HEIGHT / 2;
coord center;
center.x = imageCenterX;
center.y = imageCenterY;
double ang = angle(p1, center);
printf("quadrant %d angle %f\n\n", quad, ang);
double quadrantAngle = ang;
if(quad == 2) {
quadrantAngle += 90;
} else if(quad == 3) {
quadrantAngle += 180;
} else if(quad == 4) {
quadrantAngle += 270;
}
return quadrantAngle;
}
void print_direction(double angle) {
int i, j;
char matrix[5][5] = {
{' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '}
};
int ang = (int)angle;
if((ang % 90) == 0) {
if(ang == 180 || ang == 360) {
for(i = 0; i < 5; i++) {
matrix[2][i] = '.';
}
if(ang == 180) {
matrix[2][0] = 'x';
}
if(ang == 360) {
matrix[2][4] = 'x';
}
} else {
for(i = 0; i < 5; i++) {
matrix[i][2] = '.';
}
if(ang == 90) {
matrix[0][2] = 'x';
}
if(ang == 270) {
matrix[4][2] = 'x';
}
}
} else {
if(ang < 90 || (ang > 180 && ang < 270)) {
for(i = 0; i < 5; i++) {
matrix[4 - i][i] = '.';
}
if(ang < 90) {
matrix[4][0] = 'x';
} else {
matrix[0][4] = 'x';
}
} else {
for(i = 0; i < 5; i++) {
matrix[i][i] = '.';
}
if(ang < 180) {
matrix[4][4] = 'x';
} else {
matrix[0][0] = 'x';
}
}
}
printf("\n");
for(i = 0; i < 5; i++) {
for(j = 0; j < 5; j++) {
printf("%c", matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
|
C
|
// Lista 5
// 14/02/2017
// Andrew Pacheco Silveira ([email protected]) / Franciune Barbosa da Silva de Almeida ([email protected])
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
typedef struct pessoa{
char nome[20];
int idade;
}PESSOA;
typedef struct arvore{
PESSOA *p;
struct arvore *esq;
struct arvore *dir;
}ARV;
ARV* criar(void){
return NULL;
}
int vazia(ARV *a){
return a==NULL;
}
ARV* inserir(ARV *a, PESSOA *p){
if(a == NULL){
ARV *a = (ARV*) malloc(sizeof(ARV));
a->p = p;
a->dir = NULL;
a->esq = NULL;
}else{
if(p->idade > a->p->idade){
a->dir = inserir(a->dir, p);
}
if(p->idade < a->p->idade){
a->esq = inserir(a->esq, p);
}
}
return a;
}
ARV* pertence(ARV *a, int i){
if(a==NULL){
return NULL;
}
else{
if(a->p->idade > i){
return pertence(a->esq,i);
}
else{
if(a->p->idade < i){
return pertence(a->dir, i);
}
else{
return a;
}
}
}
}
ARV* remove(ARV *a, int i){
if(a == NULL){
return NULL;
}
else{
if(a->p->idade > i){
a->esq = remove(a->esq, i);
}
else{
if(a->p->idade < i){
a->dir = remove(a->dir, i);
}
else{
if(a->esq==NULL && a->dir == NULL){
free (a->p);
free (a);
a = NULL;
}
else{
if(a->esq==NULL){
ARV *t = a;
a = a->esq;
free(t->p);
free(t);
}
else{
if(a->dir==NULL){
ARV *t = a;
a = a->dir;
free(t->p);
free(t);
}
else{
ARV *f = a->esq;
while(f->dir != NULL){
f = f->dir;
}
a->p = f->p;
f->p->idade = i;
a->esq = remove(a->esq, i);
}
}
}
}
}
}
return a;
}
void preOrdem(ARV *a){
if (a != NULL){
printf("%s\n",a->p->nome);
printf("%i\n",a->p->idade);
preOrdem(a->esq);
preOrdem(a->dir);
}
}
void simetrico(ARV *a){
if(a != NULL){
simetrico(a->esq);
printf("%s\n",a->p->nome);
printf("%i\n",a->p->idade);
simetrico(a->dir);
}
}
void posOrdem(ARV *a){
if (a != NULL){
posOrdem(a->esq);
posOrdem(a->dir);
printf("%s\n",a->p->nome);
printf("%i\n",a->p->idade);
}
}
PESSOA *maior(ARV *a){
if((a->dir) && (a->dir->p->idade > a->p->idade))
return maior(a->dir);
else{
return a->p->idade;
}
}
PESSOA *menor(ARV *a){
if((a->esq) && (a->esq->p->idade > a->p->idade))
return menor(a->esq);
else{
return a->p->idade;
}
}
int max(int a, int b){
return ( a > b ) ? a : b;
}
int altura(ARV *a){
if(vazia(a)){
return -1;
}
else{
return 1 + max(altura(a->esq),altura(a->dir));
}
}
int main(void){
setlocale(LC_ALL, "Portuguese");
ARV *a;
int op;
int cf = 1;
do{
printf("\n|\t - MENU - \n");
printf("| 0 Sair \n");
printf("| 1 Criar ABB vazia \n");
printf("| 2 Inserir \n");
printf("| 3 Procurar \n");
printf("| 4 Remover \n");
printf("| 5 Imprimir \n");
printf("| 6 Altura \n");
printf("| 7 Mostrar a pessoa mais nova e a mais velha \n");
printf("Op.: ");
scanf("%d", &op);
system("@cls||clear");
switch(op){
case 0:
if(cf != 2){
printf("\n| Programa encerrado \n");
}else{
printf("\n| Lista liberada e programa encerrado \n");
}
break;
case 1:
if(cf != 1){
printf("\n| A rvore j foi criada \n");
}
if(cf == 1){
printf("\n| rvore criada \n");
cf=2;
a = criar();
}
break;
case 2:
if(cf != 2){
printf("\n| A rvore no foi criada \n");
}
if(cf == 2){
PESSOA *p = (PESSOA*) malloc(sizeof(PESSOA));
printf("\n| Entre com os dados da nova pessoa: \n\n");
printf("Nome: ");
scanf("%s", p->nome);
printf("Idade: ");
scanf("%i", &p->idade);
a = inserir(a, p);
}
break;
case 3:
if(cf != 2){
printf("\n| A rvore no foi criada \n");
}
if(cf == 2){
if(!vazia(a)){
printf("\n| rvore vazia \n");
}else{
int i = 0;
printf("\n| Entre com os dados da pessoa: \n");
printf("\nIdade: ");
scanf("%i", &i);
ARV *aux;
aux = pertence(a, i);
if(aux == NULL){
printf("\n| No encontrado \n");
}
else{
printf("\n| Encontrado \n\n");
printf("Nome: %s", aux->p->nome);
printf("Idade: %i", aux->p->idade);
}
}
}
break;
case 4:
if(cf != 2){
printf("\n| A rvore no foi criada \n");
}
if(cf == 2){
int i;
printf("\n| Valor a ser removido: \n");
scanf("%i", &i);
a= remove(a, i);
}
break;
case 5:
if(cf != 2){
printf("\n| A rvore no foi criada \n");
}
if(cf == 2){
if(!vazia(a)){
printf("\n| rvore vazia \n");
}else{
int opi = 0;
printf("| 1 Pr-ordem \n");
printf("| 2 Simtrico \n");
printf("| 3 Ps-ordem \n");
printf("Op.: ");
scanf("%i", &opi);
if(opi == 1){
preOrdem(a);
}
if(opi == 2){
simetrico(a);
}
if(opi == 3){
posOrdem(a);
}
}
}
break;
case 6:
if(cf != 2){
printf("\n| A rvore no foi criada \n");
}
if(cf == 2){
int alt= altura(a);
printf("\n| Altura = %i \n", alt);
}
break;
case 7:
if(cf != 2){
printf("\n| A rvore no foi criada \n");
}
if(cf == 2){
PESSOA *ma=maior(a);
PESSOA *me=menor(a);
printf("\n| Indivduo mais velho: %s \n", ma->nome);
printf("\n| Idade: %i \n", ma->idade);
printf("\n");
printf("\n| Indivduo mais novo: %s \n", me->nome);
printf("\n| Idade: %i \n", me->idade);
}
break;
default:
printf("\n| Opo invalida \n");
}
}while(op);
return 0;
}
|
C
|
#include "nst_genhash.h"
#include <nst_bjhash.h>
#include <nst_allocator.h>
#include <nst_errno.h>
#include <nst_assert.h>
#include <nst_string.h>
#include <string.h>
#define NST_GENHASH_MIN_SIZE (64)
#define NST_GENHASH_MAX_SIZE (2048 * 1024) /* 2048 K maximum */
#define NST_GENHASH_DF_MIN_FILL_FACTOR 5
#define NST_GENHASH_DF_MAX_FILL_FACTOR 70
#define hashsize(n) ((uint32_t)1<<(n))
#define hashmask(n) (hashsize(n)-1)
typedef struct nst_genhash_entry_s nst_genhash_entry_t;
struct nst_genhash_entry_s
{
nst_genhash_key_t cached_key_hash;
void *key; /**< key of stored element */
void *value; /**< stored element (content) */
nst_genhash_entry_t *next; /**< next entry in link-list*/
nst_genhash_entry_t *prev; /**< previous entry in link-list*/
nst_genhash_entry_t *prev_bucket; /**< previous record in bucket */
nst_genhash_entry_t *next_bucket; /**< next record in bucket */
};
struct nst_genhash_s
{
nst_genhash_entry_t **table; /**< table of entries in the hash-table */
nst_genhash_entry_t *head; /**< first item in the link-list */
nst_genhash_entry_t *tail; /**< last item in the link-list */
uint32_t nbits; /**< size of the hash-table */
uint32_t items; /**< number of items in the collection */
nst_genhash_f hash_fn; /**< pointer to hash function */
nst_compare_f compare_fn; /**< pointer to compare function */
nst_destructor_f free_key;
nst_destructor_f free_value;
nst_genhash_kv_copy_f key_copy_fn;
nst_genhash_kv_copy_f value_copy_fn;
uint32_t mode; /**< operation mode */
uint32_t min_size;
int fill_factor_min; /**< minimal fill factor in percent */
int fill_factor_max; /**< maximal fill factor in percent */
struct nst_allocator_s *allocator;
};
static inline nst_genhash_entry_t *
nst_genhash_entry_new(nst_genhash_t *ghash, void *key, void *value)
{
nst_genhash_entry_t *entry =
(nst_genhash_entry_t *) nst_allocator_calloc(ghash->allocator,
1,
sizeof(nst_genhash_entry_t));
if (entry == NULL) {
return NULL;
}
entry->key = key;
entry->value = value;
return entry;
}
static inline void
nst_genhash_entry_free(nst_genhash_t *ghash, nst_genhash_entry_t *entry)
{
nst_allocator_free(ghash->allocator, entry);
}
static inline uint32_t
round_size_to_power_two(uint32_t size_hint)
{
uint32_t nbits = 32;
uint32_t highest_bit = 0x80000000;
if(size_hint > 1)
size_hint--;
while(nbits) {
if(size_hint & highest_bit) {
break;
} else {
highest_bit >>= 1;
nbits--;
}
}
nst_assert(nbits);
return nbits;
}
static void *
nst_genhash_resize(nst_genhash_t *ghash, bool shrink)
{
nst_genhash_entry_t **old_table, **new_table;
nst_genhash_entry_t *entry, **bucket;
old_table = ghash->table;
if(shrink) {
if(ghash->nbits == 1
|| hashsize(ghash->nbits-1) < ghash->min_size) {
return ghash;
} else {
ghash->nbits--;
}
} else {
if(ghash->nbits == 32
|| hashsize(ghash->nbits+1) > NST_GENHASH_MAX_SIZE) {
return ghash;
} else {
ghash->nbits++;
}
}
new_table = ghash->table = (nst_genhash_entry_t **)
nst_allocator_calloc(ghash->allocator,
hashsize(ghash->nbits),
sizeof(nst_genhash_entry_t *));
if(!new_table) {
errno = ENOMEM;
return NULL;
}
/* We do not have LRU now...so every resize will screw up the
* nst_genhash_promote_to_top() effort.
*/
for(entry = ghash->tail; entry; entry = entry->prev) {
uint32_t index;
index = entry->cached_key_hash & hashmask(ghash->nbits);
entry->prev_bucket = NULL;
bucket = &new_table[index];
if((entry->next_bucket = *bucket)) {
(*bucket)->prev_bucket = entry;
}
*bucket = entry;
}
nst_allocator_free(ghash->allocator, old_table);
return ghash;
}
static inline void
nst_genhash_promote_to_top(nst_genhash_entry_t **head_bucket,
nst_genhash_entry_t *entry)
{
if(!entry->prev_bucket)
/* Alrite!!! I am at the top of the mountain. What else can I do? */
return;
/* At this point, we know there is a prev_bucket */
/* Fix the next_bucket pointer of the previous bucket */
if((entry->prev_bucket->next_bucket = entry->next_bucket)) {
/* If I have a next bucket, fix up its prev_bucket pointer */
entry->next_bucket->prev_bucket = entry->prev_bucket;
}
/* Now, I am out of the list. Time to conquer the head_bucket! */
if((entry->next_bucket = *head_bucket))
/* Actually, this check is not necessary since I just check
* that I am not at the head, so someone else must be at the head.
*/
(*head_bucket)->prev_bucket = entry;
*head_bucket = entry;
entry->prev_bucket = NULL;
}
static inline nst_genhash_entry_t *
nst_genhash_add_internal(nst_genhash_t *ghash,
nst_genhash_entry_t *entry)
{
nst_genhash_entry_t **head_bucket;
uint32_t index;
if(!(ghash->mode & NST_GENHASH_MODE_NO_EXPAND)
&&
(ghash->items * 100) > (hashsize(ghash->nbits) * ghash->fill_factor_max))
nst_genhash_resize(ghash, FALSE);
entry->cached_key_hash = (*ghash->hash_fn)(entry->key);
index = entry->cached_key_hash & hashmask(ghash->nbits);
head_bucket = &(ghash->table[index]);
/* put the newly created element to the beginning of the bucket */
if((entry->next_bucket = *head_bucket))
(*head_bucket)->prev_bucket = entry;
*head_bucket = entry;
entry->prev_bucket = NULL;
ghash->items++;
return entry;
}
static inline nst_genhash_entry_t *
nst_genhash_del_internal(nst_genhash_t *ghash, const void *key)
{
nst_genhash_entry_t *removing;
uint32_t index;
if(!(ghash->mode & NST_GENHASH_MODE_NO_SHRINK)
&&
(ghash->items * 100) < (hashsize(ghash->nbits) * ghash->fill_factor_min))
nst_genhash_resize(ghash, TRUE);
index = ((*ghash->hash_fn)(key)) & hashmask(ghash->nbits);
for (removing = ghash->table[index];
removing;
removing = removing->next_bucket) {
if ((*ghash->compare_fn)(removing->key, key) == 0)
break;
}
if(!removing)
return NULL;
if (removing->prev_bucket) {
/* fix up the prev_bucket */
if((removing->prev_bucket->next_bucket = removing->next_bucket)) {
/* fix up the next_bucket */
removing->next_bucket->prev_bucket = removing->prev_bucket;
}
} else {
/* put the next_bucket to the head */
if((ghash->table[index] = removing->next_bucket))
removing->next_bucket->prev_bucket = NULL;
}
ghash->items--;
return removing;
}
static inline void
nst_genhash_link_internal(nst_genhash_t *ghash,
nst_genhash_entry_t *adding)
{
/* adding->next and adding->prev must be NULL at this point */
if (ghash->head) {
adding->next = ghash->head;
ghash->head->prev = adding;
ghash->head = adding;
}
else {
ghash->head = ghash->tail = adding;
}
}
static inline void
nst_genhash_unlink_internal(nst_genhash_t *ghash,
nst_genhash_entry_t *removing)
{
if (removing->next)
removing->next->prev = removing->prev;
else
ghash->tail = removing->prev;
if (removing->prev)
removing->prev->next = removing->next;
else
ghash->head = removing->next;
return;
}
nst_genhash_t*
nst_genhash_new(uint32_t mode,
uint32_t min_size,
uint32_t fill_factor_min,
uint32_t fill_factor_max,
nst_allocator_t *allocator,
nst_genhash_f hash_fn,
nst_compare_f compare_fn,
nst_destructor_f free_key,
nst_destructor_f free_value,
nst_genhash_kv_copy_f key_copy_fn,
nst_genhash_kv_copy_f value_copy_fn)
{
nst_genhash_t *ghash;
if(!hash_fn || !compare_fn || !allocator) {
errno = EINVAL;
return NULL;
}
if(key_copy_fn && !free_key) {
errno = EINVAL;
return NULL;
}
if(value_copy_fn && !free_value) {
errno = EINVAL;
return NULL;
}
if((fill_factor_min ? 1 : 0) != (fill_factor_max ? 1 : 0)) {
/* You can either specify none or specify both but not either one */
errno = EINVAL;
return NULL;
} else if(fill_factor_max) {
/* both have been specified */
if(fill_factor_min >= fill_factor_max
|| fill_factor_max > 100) {
errno = EINVAL;
return NULL;
}
}
ghash = (nst_genhash_t *) nst_allocator_calloc(allocator,
1,
sizeof(nst_genhash_t));
if(ghash == NULL) {
errno = ENOMEM;
return NULL;
}
ghash->allocator = allocator;
if(min_size == 0)
min_size = NST_GENHASH_MIN_SIZE;
else if(min_size > NST_GENHASH_MAX_SIZE)
min_size = NST_GENHASH_MAX_SIZE;
ghash->nbits = round_size_to_power_two(min_size);
ghash->items = 0;
ghash->table = (nst_genhash_entry_t **)
nst_allocator_calloc(allocator,
hashsize(ghash->nbits),
sizeof(nst_genhash_entry_t *));
if (ghash->table == NULL) {
nst_allocator_free(allocator, ghash);
errno = ENOMEM;
return NULL;
}
ghash->hash_fn = hash_fn;
ghash->compare_fn = compare_fn;
ghash->free_key = free_key;
ghash->free_value = free_value;
ghash->key_copy_fn = key_copy_fn;
ghash->value_copy_fn = value_copy_fn;
ghash->head = ghash->tail = NULL;
ghash->mode = mode;
ghash->min_size = hashsize(ghash->nbits);
if(fill_factor_min)
ghash->fill_factor_min = fill_factor_min;
else
ghash->fill_factor_min = NST_GENHASH_DF_MIN_FILL_FACTOR;
if(fill_factor_max)
ghash->fill_factor_max = fill_factor_max;
else
ghash->fill_factor_max = NST_GENHASH_DF_MAX_FILL_FACTOR;
return ghash;
}
void
nst_genhash_free(nst_genhash_t *ghash)
{
if(!ghash)
return;
while (ghash->head != NULL) {
nst_genhash_entry_t *entry = ghash->head;
ghash->head = entry->next;
if (ghash->free_key)
(*ghash->free_key)(entry->key);
if (ghash->free_value)
(*ghash->free_value)(entry->value);
nst_genhash_entry_free(ghash, entry);
}
nst_allocator_free(ghash->allocator, ghash->table);
nst_allocator_free(ghash->allocator, ghash);
}
void
nst_genhash_flush(nst_genhash_t *ghash)
{
if(!ghash)
return;
while (ghash->head != NULL) {
nst_genhash_entry_t *entry = ghash->head;
ghash->head = entry->next;
if (ghash->free_key)
(*ghash->free_key)(entry->key);
if (ghash->free_value)
(*ghash->free_value)(entry->value);
nst_genhash_entry_free(ghash, entry);
}
ghash->items = 0;
ghash->head = ghash->tail = NULL;
nst_memzero(ghash->table,
hashsize(ghash->nbits) * sizeof(nst_genhash_entry_t *));
if(!(ghash->mode & NST_GENHASH_MODE_NO_SHRINK))
nst_genhash_resize(ghash, TRUE);
}
nst_status_e
nst_genhash_add(nst_genhash_t *ghash, void *key, void *value)
{
nst_genhash_entry_t *adding;
void *new_key = NULL;
if ((ghash->mode & NST_GENHASH_MODE_MULT_VALUES) == 0
&& nst_genhash_find(ghash, key)) {
errno = EEXIST;
return NST_ERROR;
}
if(ghash->key_copy_fn)
if(!(new_key = key = ghash->key_copy_fn(key)))
return NST_ERROR;
if(ghash->value_copy_fn) {
if(!(value = ghash->value_copy_fn(value))) {
if(new_key && ghash->free_key) {
/* free the newly created key */
ghash->free_key(new_key);
}
return NST_ERROR;
}
}
if((adding = nst_genhash_entry_new(ghash, key, value)) == NULL) {
return NST_ERROR;
}
nst_genhash_add_internal(ghash, adding);
nst_genhash_link_internal(ghash, adding);
return NST_OK;
}
nst_status_e
nst_genhash_del(nst_genhash_t *ghash, const void *key)
{
nst_genhash_entry_t *removing;
if((removing = nst_genhash_del_internal(ghash, key))) {
nst_genhash_unlink_internal(ghash, removing);
if(ghash->free_key)
(*ghash->free_key)(removing->key);
if(ghash->free_value)
(*ghash->free_value)(removing->value);
nst_allocator_free(ghash->allocator, removing);
}
if(removing)
return NST_OK;
else
return NST_ERROR;
}
void *nst_genhash_find(nst_genhash_t *ghash, const void *key)
{
uint32_t index;
nst_genhash_entry_t *entry;
index = ((*ghash->hash_fn)(key)) & hashmask(ghash->nbits);
entry = ghash->table[index];
while (entry && (*ghash->compare_fn)(entry->key, key))
entry = entry->next_bucket;
if(entry) {
if(ghash->mode & NST_GENHASH_MODE_PROMOTE_TO_TOP) {
nst_genhash_promote_to_top(&ghash->table[index], entry);
}
return entry->value;
} else {
return NULL;
}
}
uint32_t
nst_genhash_get_nelts(const nst_genhash_t *ghash)
{
return ghash->items;
}
void
nst_genhash_iter_init(const nst_genhash_t *ghash,
nst_genhash_iter_t *iterator)
{
iterator->pos = ghash->head;
}
bool
nst_genhash_iter_next(nst_genhash_iter_t *iterator,
void **key, void **value)
{
nst_genhash_entry_t *entry = NULL;
if (iterator->pos) {
entry = (nst_genhash_entry_t *)iterator->pos;
iterator->pos = entry->next;
if(key) (*key) = entry->key;
if(value) (*value) = entry->value;
return TRUE;
}
else {
return FALSE;
}
}
uint32_t
nst_genhash_uint32(const void *k)
{
return nst_bjhash_uint32s(k, 1, 0);
}
int
nst_genhash_uint32_cmp(const void *k1, const void *k2)
{
return (*(const uint32_t *)k1 != *(const uint32_t *)k2);
}
uint32_t
nst_genhash_void(const void *k)
{
return nst_bjhash_uint32s((const void *)&k, sizeof(void *)/sizeof(uint32_t), 0);
}
int
nst_genhash_void_cmp(const void *k1, const void *k2)
{
return (k1 != k2);
}
uint32_t
nst_genhash_cstr(const void *key)
{
const char *cstr = (const char *)key;
size_t cstrlen = strlen(cstr);
return nst_bjhash_bytes(key, cstrlen, 0);
}
int
nst_genhash_cstr_cmp(const void *k1, const void *k2)
{
const char *cstr1 = (const char *)k1;
const char *cstr2 = (const char *)k2;
return strcmp(cstr1, cstr2);
}
|
C
|
#ifndef NODE_H
#define NODE_H
#include <stdbool.h>
#include <stdio.h>
struct node {
char *string;
int number;
struct node *next;
};
typedef int (*node_compare)(const void *a, const void *b);
// the above defines the type node_compare as a pointer to a
// function that takes two void pointers as arguments and
// returns an int
struct node * node_create(char *string, struct node *next);
struct node * node_delete(struct node *n, bool recursive);
void node_dump(struct node *n, FILE *stream);
int node_compare_number(const void *a, const void *b);
int node_compare_string(const void *a, const void *b);
#endif
|
C
|
#include<stdio.h>
int main()
{
unsigned int T, i, a, b, c;
scanf("%u", &T);
for(i=1; i<=T; ++i)
{
scanf("%u %u %u", &a, &b, &c);
if(a>b && a>c)
{
printf("Case %u: %u\n", i, b>c?b:c);
}
else if(b > c)
{
printf("Case %u: %u\n", i, c>a?c:a);
}
else
{
printf("Case %u: %u\n", i, a>b?a:b);
}
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,i;
printf("\n Enter the number : "); //input
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("\n %dX%d=%d",n,i,n*i); //running the loop from 1 to 10
printf("\n\n");
return 0;
}
|
C
|
/**
* Stack 利用 Vector 实现栈
*/
#ifndef DATA_STRUCTURES_STACK_H
#define DATA_STRUCTURES_STACK_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../vector/Vector.h"
typedef struct stack stack;
/**
* 创建一个空栈
* @return stack - 栈
*/
stack *new_stack();
/**
* 获取栈的大小
* @param stk - 栈
* @return size - 大小
*/
size_t stack_size(stack *stk);
/**
* 判断栈是否为空
* @param stk - 栈
* @return 0 为非空,1 为空
*/
int stack_empty(stack *stk);
/**
* 将元素压入栈中
* @param stk - 栈
* @param val - 元素
*/
void stack_push(stack *stk, void *item);
/**
* 弹出顶部元素
* @param stk - 栈
* @return val - 元素
*/
void *stack_pop(stack *stk);
/**
* 获取顶部元素值,但不弹出
* @param stk - 栈
* @return val - 元素
*/
void *stack_top(stack *stk);
#endif //DATA_STRUCTURES_STACK_H
|
C
|
#include <stdio.h>
int main(void){
double cel_deg = 0.0;
printf("摂氏温度を入力:");
scanf("%lf", &cel_deg);
double fah_deg = ((cel_deg * 9) / 5) + 32;
printf("摂氏%.2lf度は華氏%.2lf度となる。\n", cel_deg, fah_deg);
return 0;
}
|
C
|
#include "screen.h"
#include "ports.h"
#include "../libc/mem.h"
static const char banner[] = "\n __ __ __ "
"\n _______ __/ /_ _____/ /__________ _/ /_____ _ "
"\n / ___/ / / / __ \\/ ___/ __/ ___/ __ `/ __/ __ `/ "
"\n (__ ) /_/ / /_/ (__ ) /_/ / / /_/ / /_/ /_/ / "
"\n/____/\\__,_/_.___/____/\\__/_/ \\__,_/\\__/\\__,_/ "
"\n ";
static int get_cursor_offset();
static void set_cursor_offset(int offset);
static void set_char(char character, int offset) {
char *screen = (char*) VIDEO_ADDRESS;
screen[offset] = character;
screen[offset + 1] = WHITE_ON_BLACK;
}
void clear_screen() {
int screen_size = MAX_COLS * MAX_ROWS;
for (int i = 0; i < screen_size; i++) {
set_char(' ', i * 2);
}
set_cursor_offset(0);
}
static int increment_offset(int offset) {
char *screen = (char*) VIDEO_ADDRESS;
int new_offset = offset + 2;
if (new_offset >= MAX_COLS * MAX_ROWS * 2) {
int bottom = MAX_COLS * (MAX_ROWS - 1) * 2;
memory_copy(screen + MAX_COLS * 2, screen, MAX_COLS * (MAX_ROWS - 1) * 2);
for (int i = 0; i < MAX_COLS; i++) {
set_char(' ', bottom + i * 2);
}
return bottom;
}
return new_offset;
}
void kprint(char *message) {
int offset = get_cursor_offset();
int position = 0;
while (message[position] != 0) {
if (message[position] == '\n') {
int current_row = (offset / (MAX_COLS * 2)) + 1;
offset = ((MAX_COLS * current_row) - 1) * 2;
} else {
set_char(message[position], offset);
}
offset = increment_offset(offset);
position++;
}
set_cursor_offset(offset);
}
void kprint_at(char *message, int col, int row) {
if (col > MAX_COLS) {
kprint("Maximum column position exceeded.");
return;
}
if (row >= MAX_ROWS) {
kprint("Maximum row position exceeded.");
return;
}
int offset = col * 2 + row * 2 * MAX_COLS;
set_cursor_offset(offset);
kprint(message);
}
void kprint_backspace() {
int offset = get_cursor_offset() - 2;
set_cursor_offset(offset);
set_char(' ', offset);
}
static int get_cursor_offset() {
port_byte_out(REG_SCREEN_CTRL, 14);
int offset = port_byte_in(REG_SCREEN_DATA) << 8;
port_byte_out(REG_SCREEN_CTRL, 15);
offset += port_byte_in(REG_SCREEN_DATA);
return offset * 2;
}
static void set_cursor_offset(int offset) {
offset /= 2;
port_byte_out(REG_SCREEN_CTRL, 14);
port_byte_out(REG_SCREEN_DATA, (unsigned char)(offset >> 8));
port_byte_out(REG_SCREEN_CTRL, 15);
port_byte_out(REG_SCREEN_DATA, (unsigned char)(offset & 0xff));
}
void screen_banner() {
kprint((char*) banner);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "persona.h"
int init(ePersona per[],int CANT){
int i;
int retorno=-1;
for(i=0;i<CANT;i++){
per[i].isEmpty=1;
retorno=0;
}
return retorno;
}
int obtenerEspacioLibre(ePersona per[], int CANT)
{
int i,retorno=-1;
for(i=0;i<CANT;i++){
if(per[i].isEmpty==1){ //encontro un lugar libre
retorno=i;
break;
}
}
return retorno;
}
void alta(ePersona per[],int CANT){
int index,i;
long int dniAux;
index=init(per, CANT);
if(index!=-1){
//validar dni con funcion
printf("Ingrese DNI: ");
scanf("%ld",&dniAux);
if(buscarPorDni(per[i].dni,CANT,dniAux)==-1) {
printf("DNI existente\n");
printf("Reingrese DNI: \n");
scanf("%ld",&per[i].dni);
}
printf("Ingrese Apellido: ");
scanf("%s",per[i].apellido);
printf("Ingrese Nombre: ");
scanf("%s",per[i].nombre);
printf("Ingrese dia de nacimiento: "); //hacer funcion para comparar dni y ver si ya esta ingresado
scanf("%d",&per[i].fechaNac.dia);
printf("Ingrese mes de nacimiento: ");
scanf("%d",&per[i].fechaNac.mes);
printf("Ingrese ao de nacimiento: ");
scanf("%d",&per[i].fechaNac.anio);
}
}
void baja(ePersona per[],int CANT){
int i;
long int dniAux;
char rta;
printf("DNI: ");
scanf("%ld",&dniAux);
for(i=0;i<CANT;i++){
if(dniAux==per[i].dni){//lo encontro
printf("%s %s %ld",per[i].apellido,per[i].nombre,per[i].dni);
do{ //validad entre s y n
printf("Eliminar registro? S/N: ");
fflush(stdin);
rta=toupper(getch()); //lo que tecleo lo paso a mayuscula y lo asigno en rta
}while(rta!='S'&&rta!='N');
if(rta=='S'){
per[i].isEmpty=0;
break;
}
}
}
}
void ordenarLista(ePersona per[],int CANT){
ePersona perAux;
int i, j;
for(i=0;i<CANT-1;i++){
for(j=i+1;j<CANT;j++){
if(strcmp(per[i].apellido,per[j].apellido)>0){//Si devuelve mayor a cero i apellido es mayor que j apellido
/*strcpy(apellidoAux,per[i].apellido); no se hace por que hay que escribir mucho codigo
strcpy(per[i].apellido,per[j].apellido);*/
perAux=per[i];
per[i]=per[j];
per[j]=perAux;
}
if(strcmp(per[i].apellido,per[j].apellido)==0){
if(strcmp(per[i].nombre,per[j].nombre)>0){
perAux=per[i];
per[i]=per[j];
per[j]=perAux;
}
}
}
}
}
int buscarPorDni(ePersona per[], int CANT,long int dniAux){
int i;
int retorno=-1;
for(i=0;i<CANT;i++){
if(per[i].isEmpty==0)
{
if(per[i].dni==dniAux){
retorno=-1;
break;
}
else{
retorno=i;
}
}
}
return retorno;
}
|
C
|
#include <stdio.h>
#include "DoublyList.h"
List DoublyListSwap(List L);
int main()
{
List L;
int n,i;
n = 2;
printf("Please enter the element of L\n");
L = CreateList(n);
PrintList(L);
L = DoublyListSwap(L);
PrintList(L);
return 0;
}
List DoublyListSwap(List L)
{
Position P;
P = L->Next;
P = P->Next;
P->Next = L->Next;
L->Next = P;
P->Prev = L;
P = P->Next;
P->Prev = L->Next;
P->Next = NULL;
return L;
}
|
C
|
#include <stdio.h>
void main(void)
{
int a = 3, b = 4;
if (5 > 3 && b > a)
{
printf("ù ° if \n");
}
if (4 > 3 || b > a)
printf(" ° if \n");
if (!(a > b))
{
printf(" ° if \n");
}
}
|
C
|
/******************************************************************************/
// I N T E R F A C E S . H //
// D P X //
/******************************************************************************/
#ifndef DD_INTERFACES_H
#define DD_INTERFACES_H
#include "../../../libs/basic.h"
#define MAX_INTERFACE_TITLE_LENGTH 20 //!< Maximum length of interface title.
#define DEFAULT_INTERFACE DASHBOARD_INTERFACE
#define INTERFACES_TOTAL_COUNT 3 //!< Number of interfaces defined in #Interface.
//! Defines all interfaces.
/// [Interface definitions]
typedef enum {
DASHBOARD_INTERFACE,
MENU_INTERFACE,
} Interface;
/// [Interface definitions]
/* !!!IMPORTANT!!!
Order of functions in subsequent arrays and corresponding interfaces in Interface enum
has to be congruent, as access to subsequent arrays is made by
NotificationType index.
*/
/** \name Interface method tables
* Contain functions for each interface defined and in the same order as they are defined
* for the graphic controller to callback in specific moments.
* See dd_interfaces.h for more.
*/
//!@{
/** \brief Accessed on frame rate schedule.
*
* Groups print routines for all interfaces defined.
* Mandatory for each interface to specify a valid routine.
*/
extern void (*dd_Interface_print[INTERFACES_TOTAL_COUNT])(void);
/** \brief Accessed once each time interface is set.
*
* Groups init routines for all interfaces defined.
* Optional, but a NULL pointer must eventually be specified in place
* of the routine.
*/
extern void (*dd_Interface_init[INTERFACES_TOTAL_COUNT])(void);
//!@}
#define MAX_NOTIFICATION_LENGTH 20
#define NOTIFICATION_TYPES_COUNT 4 //!< Number of notification types defined in #NotificationType.
/* !!!IMPORTANT!!!
Order of notifications in enum and dd_notificationTitles
has to be congruent, as access to dd_notificationTitles is made by
NotificationType index.
*/
/** \brief Defines different notification types for the notification interface.
*
* Each type will display a different title for the interface as specified at its index in
* #dd_notificationTitles, and a different icon (don't know if implemented yet).
*/
typedef enum {
MESSAGE, //!< Simple harmless notification.
WARNING, //!< Notifies a warning which can potentially lead to errors.
ERROR, //!< Error occurred notification.
PROMPT //!< Requests for an action to be taken.
} NotificationType;
/** Stores interface titles associated with each #NotificationType, which are accessed by
* their indexes.
*/
extern const char dd_notificationTitles[NOTIFICATION_TYPES_COUNT][MAX_INTERFACE_TITLE_LENGTH];
//! Stores text set by graphic controller for the notification interface.
extern char dd_notificationText[MAX_NOTIFICATION_LENGTH];
void dd_printMessage(char * title);
/** \file dd_interfaces.h
* \brief Defines all interfaces which can be displayed and the relative drawing routines.
*
* For each Interface defined a function \code void dd_Interface_print<InterfaceName>(void)\endcode
* which defines the drawing operations to print the specific Interface on screen, must be defined along with it
* to be called by the \link dd_graphic_controller.h graphic controller\endlink on frame rate schedule.
* A pointer to each function must be added to the dd_Interface_print array in the same order as the interfaces are
* defined, for the Graphic Controller to be able to access them correctly.
* In the same way a \code void dd_Interface_init<InterfaceName>(void)\endcode method can be defined, which is called once
* each time the Interface is set, providing custom initialization logic for the Interface.
* These must be added to dd_Interface_init array and the same rules apply as for print methods.
* If no initialization is required then a NULL pointer can be specified. Providing a non-NULL valid print method
* is instead mandatory.
* These specific interface members are defined externally for Menu and Dashboard interfaces, where linked below.
* Every interface is displayed with a title in a common routine, and then allowed to draw its own graphics in the print routine.
*
* All interfaces which can be set explicitly are collection based, meaning they represent a collection of indicator data.
* Dashboard and Menu belong to this category.
* To draw themselves they must be provided with an indicator collection. This collection is stored elsewhere in memory,
* and a pointer is passed to the graphic controller when the Interface is set via
* dd_GraphicController_setCollectionInterface() and is later stored for usage by the interfaces.
* In the same method the title to be displayed is set.
*
* Other interfaces may exist, such as the Notification interface, which do not depend on indicator collections.
* These are managed automatically and privately by the graphic controller and are not directly accessible by the user,
* if not via specific methods which are provided by dd_graphic_controller.h, as dd_GraphicController_fireTimedNotification().
* The notification interface displays a different title from #dd_notificationTitles,
* according to the #NotificationType selected. It is important that titles and definitions be ordered
* coherently.
*
* \sa dd_dashboard.h, dd_menu.h and dd_graphic_controller.h
*/
#endif /* DD_INTERFACES_H */
|
C
|
/**
* @file
*
* \if de
* Ein einfaches Testprojekt zur Überprüfung der Tasterwerte. Es gibt alle
* 500ms den aktuellen Analogwert der Taster über die UART/IR-Schnittstelle
* aus. \n
* Vergleichswerte gibt es im AsuroWiki unter:
* http://www.asurowiki.de/pmwiki/pmwiki.php/Main/Tasten
* \endif
*
* \if en
* Simple test project for switch diagnostic purposes. It prints the current
* analog value of the switches to the UART/IR-interface. \n
* Values for comparisons can be found in the AsuroWiki at:
* http://www.asurowiki.de/pmwiki/pmwiki.php/Main/Tasten
* \endif
*
* @author Markus Jung
*
* @version 16.12.2011 \n
* First Version
*/
#include <stdint.h>
#include <asuro/asuro.h>
#include <util/misc.h>
MAIN void main(void) {
Init();
PORTD |= (1 << PD3);
DDRD |= (1 << DDD3);
SerWrite("Switch ADC Test\n", 16);
for (;;) {
uint16_t adcVal;
ADC_BLOCK {
ADCSelectChannel(ADC_SWITCH);
ADCMeasure();
adcVal = ADC;
}
char asString[6]; // XXXX\r\n
uint8_t i = sizeof(asString) - 1;
asString[i--] = '\r';
asString[i--] = '\n';
do {
asString[i] = '0' + (adcVal % 10);
adcVal = adcVal / 10;
} while (i-- != 0);
SerWrite(asString, sizeof(asString));
msleep(500);
};
}
|
C
|
#include "stm32f4xx.h"
#include "LCD_drivers.h"
#include "delay.h"
//------------------------------------------------------------------------------
// To send command to the LCD in 4 bit mode
void LCD4bit_Cmd(unsigned char command){
LCD_write4bit(command & 0xF0,0);
LCD_write4bit(command<<4,0);
if (command<4)
delay_milli(2);
else
delay_micro(40);
}
//------------------------------------------------------------------------------
// To send command to the LCD in 4 bit mode
void LCD4bit_Data(unsigned char data){
LCD_write4bit(data & 0xF0, RS);
LCD_write4bit(data << 4,RS);
delay_micro(40);
}
//----------------------------------------------------------------------------
// sending the command/ data using only 4 lines
void LCD_write4bit(unsigned char data,unsigned char control){
data &= 0xF0; //upper 4bits saved of data/command
control &= 0x0F; // lower 4bits saved of control signal
GPIOD->ODR = data | control;
GPIOD->ODR = data | control | EN;
delay_micro(0);
GPIOD->ODR = data;
}
//---------------------------------------------------------------------------
// Function to pass string to the LCD
void LCD_string_write(char* st_string){
while(*st_string > 0){
LCD4bit_Data(*st_string++);
}
}
//--------------------------------------------------------------------------
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbelorge <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/15 18:46:36 by mbelorge #+# #+# */
/* Updated: 2019/11/21 16:44:55 by mbelorge ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_charset(char str1, char const *charset)
{
int i;
i = 0;
while (charset[i])
{
if (str1 != charset[i])
i++;
else
return (1);
}
return (0);
}
char *ft_strtrim(char const *s1, char const *set)
{
char *str;
size_t i;
size_t j;
size_t a;
i = 0;
j = 0;
a = 0;
if (!s1 || !set)
return (NULL);
while (s1[j])
j++;
j--;
while (ft_charset(s1[i], set))
i++;
if (i == ft_strlen(s1))
return (ft_calloc(1, sizeof(char)));
while (ft_charset(s1[j], set))
j--;
if (!(str = malloc(sizeof(char) * (j - i + 2))))
return (NULL);
while (i <= j)
str[a++] = s1[i++];
str[a] = '\0';
return ((char *)str);
}
|
C
|
/*
* Unix System Programming Examples / Exemplier de programmation système Unix
*
* Copyright (C) 1995-2022 Alain Lebret <alain.lebret [at] ensicaen [dot] fr>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define THREADS 4
/**
* @author Alain Lebret
* @version 1.0
* @date 2012-04-10
*/
/**
* @file without_pb_reentrant.c
* @see pb_reentrant.c
*
* A simple program to show the importance of using "reentrant" functions.
*
*/
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int f_reentrant(void)
{
static unsigned int next;
pthread_mutex_lock(&mutex);
/* Beginning of critical section */
next = 1;
next = next * 1103515245 + 12345;
next = (unsigned int) (next / 65536) % 32768;
/* End of critical section */
pthread_mutex_unlock(&mutex);
usleep(10);
return next;
}
void *doit(void *vargp)
{
printf("[%ld]: val = %d\n", pthread_self(), f_reentrant());
return NULL;
}
int main(void)
{
int i;
pthread_t tid[4];
for (i = 0; i < THREADS; i++) {
pthread_create(&tid[i], NULL, doit, NULL);
}
for (i = 0; i < THREADS; i++) {
pthread_join(tid[i], NULL);
}
exit(EXIT_SUCCESS);
}
|
C
|
#include "utils.h"
void generate_init_point(double *x, int n) {
int b = 3;
for(int i = 0; i < n; i++) {
x[i] = (double)(rand() % (b + 1));
}
}
/*----- Función 4 -----*/
void get_gradient_sm(double *g, double *x, double *y, double lambda, int n) {
g[0] = 2.0 * (x[0] - y[0]) - 2.0 * lambda * (x[1] - x[0]);
g[n - 1] = 2.0 * (x[n - 1] - y[n - 1]) + 2.0 * lambda * (x[n - 1] - x[n - 2]);
for(int i = 1; i < n - 1; i++) {
g[i] = 2.0 * (x[i] - y[i]) + 2.0 * lambda * (x[i] - x[i - 1]) - 2.0 * lambda * (x[i + 1] - x[i]);
}
}
void get_Hessian_sm(double **H, double lambda, int n) {
for(int i = 0; i < n; i++) {
if(i == 0 || i == n - 1) {
H[i][i] = 2.0 + 2.0 * lambda;
}
else {
H[i][i] = 2.0 + 4.0 * lambda;
}
if(i < n - 1) {
H[i + 1][i] = H[i][i + 1] = -2.0 * lambda;
}
}
}
double f_sm(double *x, double *y, double lambda, int n) {
double res = 0.0;
for(int i = 0; i < n; i++) {
res += (x[i] - y[i]) * (x[i] - y[i]);
}
for(int i = 0; i < n - 1; i++) {
res += lambda * pow((x[i + 1] - x[i]), 2);
}
return res;
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
int main(int argc, string argv[])
{
//expecting name of the program and one user argument only
if(argc != 2){
printf("error, only one non-negative integer can be passed");
return 1;
}
else
{
printf("plaintext:");
string plainText = get_string();
int length = strlen(plainText);
//make array value into integer
int k = atoi(argv[1]);
//scroll through string
printf("ciphertext:");
for(int i= 0; i< length; i++)
{
//check if the letter is uppercase or lowercase then convert
if islower(plainText[i])
printf("%c", (((plainText[i] + k) - 97) % 26) + 97);
else if isupper(plainText[i])
printf("%c", (((plainText[i] + k) - 65) % 26) + 65);
else
printf("%c", plainText[i]);
}
printf("\n");
}
}
|
C
|
#include <fcntl.h>
#include <errno.h>
#include <err.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <emmintrin.h>
#include <mmintrin.h>
void Scan(float*);
int main(int argc, char *argv[])
{
if (argc < 5) {
printf("Missing arguments. Usage: filename numberOfTuples compareValue numThreads\n");
return 0;
}
printf("Usage: filename numberOfTuples compareValue numThreads\n");
FILE *ptr_file;
char buf[1000];
int numTuples=atoi(argv[2]);
float compareValue=atof(argv[3]);
int numThreads=atoi(argv[4]);
int numReadTuples=0;
ptr_file =fopen(argv[1],"r");
if (!ptr_file){
printf("Error. Could not open the input file.\n");
return 0;
}
if (numTuples<=0){
printf("Error. Please pass a valid number of tuples.\n");
return 0;
}
if (numThreads<=0){
printf("Error. Please pass a valid number of threads.\n");
return 0;
}
float *array;
array=(float*)malloc(((2*numTuples)+3+(2*numThreads))*sizeof(float));
array[0]=compareValue;
array[1]=(float)numTuples;
array[2]=(float)numThreads;
for (int i=0; i<(2*numThreads); i++){
array[3+i]=(float)0;
}
while (fgets(buf,1000, ptr_file)!=NULL && numReadTuples<numTuples){
array[numReadTuples+3+(2*numThreads)]=atof(buf);
numReadTuples++;
}
fclose(ptr_file);
if (numReadTuples<numTuples){
printf("Error, file contains less tuples than specified.\n");
return 0;
}
Scan(array);
return 1;
}
/*****************************************
Emitting C Generated Code
*******************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
void Scan(float* x0) {
float x4 = x0[2];
float x3 = x0[1];
int32_t x10 = x3 / x4;
float x2 = x0[0];
int32_t x5 = 2 * x4;
int32_t x6 = 3 + x5;
bool x31 = x4 > 0;
int32_t x80 = x10 * x4;
//#Scan Variants
// generated code for Scan Variants
int32_t x1 = 0;
pthread_t threads[(int)x4];
int *inputArray;
inputArray=(int*)malloc(x4*sizeof(int));
void* parallelPrefixSum(void* input){
int x8=*(int*)input;
int32_t x11 = x10 * x8;
int32_t x12 = x6 + x11;
int32_t x24 = 3 + x8;
//#parallel prefix sum
// generated code for parallel prefix sum
int32_t x9 = 0;
for(int x14=0; x14 < x10; x14++) {
int32_t x15 = x12 + x14;
float x16 = x0[x15];
bool x17 = x16 >= x2;
if (x17) {
x9 += 1;
} else {
}
}
int32_t x25 = x9;
x0[x24] = x25;
//#parallel prefix sum
}
for(int x8=0; x8 < x4; x8++) {
inputArray[x8]=x8;
pthread_create(&threads[x8], NULL, parallelPrefixSum, (void *)&inputArray[x8]);
}
for(int x8=0; x8 < x4; x8++) {
pthread_join(threads[x8], NULL);
}
if (x31) {
int32_t x32 = 3 + x4;
x0[x32] = 0;
for(int x35=1; x35 < x4; x35++) {
int32_t x36 = x32 + x35;
int32_t x37 = 3 + x35;
int32_t x38 = x37 - 1;
float x39 = x0[x38];
int32_t x40 = x36 - 1;
float x41 = x0[x40];
float x42 = x39 + x41;
x0[x36] = x42;
}
int32_t x46 = x32 - 1;
float x47 = x0[x46];
int32_t x48 = x46 + x4;
float x49 = x0[x48];
float x50 = x47 + x49;
x1 = x50;
} else {
}
void* parallelWriting(void* input){
int x54=*(int*)input;
int32_t x57 = x10 * x54;
int32_t x62 = 3 + x54;
int32_t x63 = x62 + x4;
float x64 = x0[x63];
int32_t x65 = x64 + x6;
int32_t x66 = x65 + x3;
//#parallel writing
// generated code for parallel writing
int32_t x55 = 0;
for(int x56=0; x56 < x10; x56++) {
int32_t x58 = x56 + x57;
int32_t x59 = x6 + x58;
float x60 = x0[x59];
bool x61 = x60 >= x2;
if (x61) {
int32_t x67 = x55;
int32_t x68 = x66 + x67;
int32_t x69 = x59 - x6;
x0[x68] = x69;
x55 += 1;
} else {
}
}
//#parallel writing
}
for(int x54=0; x54 < x4; x54++) {
pthread_create(&threads[x54], NULL, parallelWriting, (void *)&inputArray[x54]);
}
for(int x54=0; x54 < x4; x54++) {
pthread_join(threads[x54], NULL);
}
for(int x82=x80; x82 < x3; x82++) {
int32_t x83 = x82 + x6;
float x84 = x0[x83];
bool x85 = x84 >= x2;
//#decorated instruction
// generated code for decorated instruction
//#run instruction with branching
// generated code for run instruction with branching
if (x85) {
int32_t x86 = x1;
int32_t x87 = x86 + x6;
int32_t x88 = x87 + x3;
x0[x88] = x82;
x1 += 1;
} else {
}
//#run instruction with branching
//#decorated instruction
}
int32_t x99 = x1;
printf("%s\n","Number of tuples found: ");
printf("%d\n",x99);
bool x103 = x99 == 0;
if (x103) {
} else {
printf("%s\n","Output array: ");
int32_t x105 = x6 + x3;
for(int x107=0; x107 < x99; x107++) {
int32_t x108 = x107 + x105;
float x109 = x0[x108];
printf("%f\n",x109);
}
}
//#Scan Variants
}
/*****************************************
End of C Generated Code
*******************************************/
|
C
|
#include "virt_mem_management.h"
#include "lib.h"
# define TEST_SIZE 2048
void mem_tester(void)
{
char *ptr[TEST_SIZE];
size_t i = 0;
size_t j = 1;
if (kmalloc(0) != NULL || vmalloc(0) != NULL)
{
printk("error ! Null ptr excepted\n");
return ;
}
printk("==================================\n");
// error tester
while (j < TEST_SIZE)
{
i = 0;
bzero(ptr, TEST_SIZE * sizeof(char *));
while (i < TEST_SIZE / 2)
{
if (!(ptr[i] = kmalloc(j)))
{
printk("not enouth mem 1\n");
break ;
}
for (size_t k = 0; k < j; k++)
ptr[i][k] = 1;
++i;
}
i = 0;
while (i < TEST_SIZE / 2)
{
if (ptr[i])
kfree(ptr[i]);
++i;
}
bzero(ptr, TEST_SIZE * sizeof(char *));
i = 0;
while (i < TEST_SIZE / 2)
{
if (!(ptr[i] = vmalloc(j)))
{
printk("not enouth mem 2\n");
break ;
}
for (size_t k = 0; k < j; k++)
ptr[i][k] = 1;
++i;
}
i = 0;
while (i < TEST_SIZE / 2)
{
if (ptr[i])
vfree(ptr[i]);
++i;
}
i = 0;
bzero(ptr, TEST_SIZE * sizeof(char *));
while (i < TEST_SIZE / 2)
{
if (!(ptr[i] = kmalloc(j)))
{
printk("not enouth mem 3\n");
break ;
}
for (size_t k = 0; k < j; k++)
ptr[i][k] = 1;
kfree(ptr[i]);
++i;
}
bzero(ptr, TEST_SIZE * sizeof(char *));
// augmenter taille de la heap pour activer ce test
i = 0;
while (i < TEST_SIZE / 2)
{
if (!(ptr[i] = kmalloc(j * 4096)))
{
printk("not enouth mem 4\n");
break ;
}
for (size_t k = 0; k < j; k++)
ptr[i][k] = 1;
kfree(ptr[i]);
++i;
}
bzero(ptr, TEST_SIZE * sizeof(char *));
i = 0;
while (i < TEST_SIZE / 2)
{
if (!(ptr[i] = vmalloc(j * 4096)))
{
printk("not enouth mem 5\n");
break ;
}
for (size_t k = 0; k < j; k++)
ptr[i][k] = 1;
vfree(ptr[i]);
++i;
}
printk("test %d passed well\n", j);
++j;
}
printk("Mem seems to work well !\n");
}
|
C
|
#ifndef MTYPES_H
#define MTYPES_H
/// ġ
struct MPOINT{
int x, y;
public:
MPOINT(void){}
MPOINT(int x, int y){ MPOINT::x = x, MPOINT::y = y; }
void Scale(float x, float y);
void ScaleRes(void); ///< 648*480ذ ػ ϸ
void TranslateRes(void); ///< 648*480 ߽ Ÿŭ ػ ° ̵
};
///
struct MRECT{
int x, y; ///< ġ
int w, h; ///< ũ
public:
MRECT(void){}
MRECT(int x, int y, int w, int h){
Set(x, y, w, h);
}
bool InPoint(MPOINT& p){
if(p.x>=x && p.x<=x+w && p.y>=y && p.y<=y+h) return true;
return false;
}
void Set(int x, int y, int w, int h){
MRECT::x = x, MRECT::y = y;
MRECT::w = w, MRECT::h = h;
}
void ScalePos(float x, float y); ///< ϸ
void ScaleArea(float x, float y); ///< ̿ ϸ
void ScalePosRes(void); ///< 648*480ذ ػ ϸ
void ScaleAreaRes(void); ///< 648*480ذ ػ ϸ
void TranslateRes(void); ///< 648*480 ߽ Ÿŭ ػ ° ̵
void EnLarge(int w); ///< ¿ ϸ wŭ ũ Ű
void Offset(int x, int y); ///< ̵
bool Intersect(MRECT* pIntersect, const MRECT& r); ///< 簢
};
/// ũ
struct MSIZE{
int w, h;
public:
MSIZE(void){}
MSIZE(int w, int h){
MSIZE::w = w;
MSIZE::h = h;
}
};
/// a,r,g,b unsigned long int ȯ
#define MINT_ARGB(a,r,g,b) ( ((((unsigned long int)a)&0xFF)<<24) | ((((unsigned long int)r)&0xFF)<<16) | ((((unsigned long int)g)&0xFF)<<8) | (((unsigned long int)b)&0xFF) )
/// r,g,b unsigned long int ȯ
#define MINT_RGB(r,g,b) ( ((((unsigned long int)r)&0xFF)<<16) | ((((unsigned long int)g)&0xFF)<<8) | (((unsigned long int)b)&0xFF) )
/// r, g, b, a ÷
struct MCOLOR{
public:
unsigned char r; ///< Red
unsigned char g; ///< Green
unsigned char b; ///< Blue
unsigned char a; ///< Alpha
public:
MCOLOR(void){
r = g = b = a = 0;
}
MCOLOR(unsigned char r, unsigned char g, unsigned char b, unsigned char a=255){
MCOLOR::r = r, MCOLOR::g = g, MCOLOR::b = b, MCOLOR::a = a;
}
MCOLOR(unsigned long int argb){
a = unsigned char( (argb & 0xFF000000) >> 24 );
r = unsigned char( (argb & 0x00FF0000) >> 16 );
g = unsigned char( (argb & 0x0000FF00) >> 8 );
b = unsigned char( (argb & 0x000000FF) );
}
unsigned long int GetARGB(void){
return MINT_ARGB(a, r, g, b);
}
unsigned long int GetRGB(void){
return MINT_RGB(r, g, b);
}
};
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <math.h>
typedef struct coordinate {
int x;
int y;
} coordinate;
typedef struct server_message {
coordinate pos;
coordinate adv_pos;
int object_count;
coordinate object_pos[4];
} server_message;
typedef struct ph_message {
coordinate move_request;
} ph_message;
void main(int argc, char *argv[]) {
int yukseklik = atoi(argv[2]);
int genislik = atoi(argv[1]);
int hareket_etme = 1;
int t = 10;
while(1){
hareket_etme = 1;
ph_message ph_mes;
server_message ser_mes;
read(0, &ser_mes, sizeof(ser_mes));
int initial_dist = abs(ser_mes.pos.x - ser_mes.adv_pos.x) + abs(ser_mes.pos.y - ser_mes.adv_pos.y);
if(ser_mes.pos.x+1 <= yukseklik-1){
if (abs(ser_mes.pos.x+1 - ser_mes.adv_pos.x) + abs(ser_mes.pos.y - ser_mes.adv_pos.y)> initial_dist)
{
int flag = 0;
for (int i = 0; i < ser_mes.object_count; i++)
{
if (ser_mes.pos.x+1 == ser_mes.object_pos[i].x && ser_mes.pos.y == ser_mes.object_pos[i].y)
{
flag = 1;
break;
}
}
if(flag != 1 && hareket_etme == 1){
hareket_etme = 0;
ph_mes.move_request.x = ser_mes.pos.x+1;
ph_mes.move_request.y = ser_mes.pos.y;
usleep((1+rand()%9)*10000);
//fprintf(stderr, "alt\n");//ser_mes.pos.x, ser_mes.pos.y , ser_mes.adv_pos.x, ser_mes.adv_pos.y );
if (write(1, &ph_mes, sizeof(ph_mes)) < 0)
perror("writing stream message");
FILE *file = fdopen(1,"w");
fflush(file);
}
}
}
if (ser_mes.pos.x-1 >= 0)
{
//fprintf(stderr, "%d\n", abs(ser_mes.pos.x-1 - ser_mes.adv_pos.x) + abs(ser_mes.pos.y - ser_mes.adv_pos.y));
if (abs(ser_mes.pos.x-1 - ser_mes.adv_pos.x) + abs(ser_mes.pos.y - ser_mes.adv_pos.y)> initial_dist)
{
int flag = 0;
for (int i = 0; i < ser_mes.object_count; i++)
{
if (ser_mes.pos.x-1 == ser_mes.object_pos[i].x && ser_mes.pos.y == ser_mes.object_pos[i].y)
{
flag = 1;
break;
}
}
if(flag != 1 && hareket_etme == 1){
hareket_etme = 0;
ph_mes.move_request.x = ser_mes.pos.x-1;
ph_mes.move_request.y = ser_mes.pos.y;
usleep((1+rand()%9)*10000);
//fprintf(stderr, "ust\n");
if (write(1, &ph_mes, sizeof(ph_mes)) < 0)
perror("writing stream message");
FILE *file = fdopen(1,"w");
fflush(file);
}
}
}
if (ser_mes.pos.y+1 <= genislik-1)
{
//fprintf(stderr, "%d %d \n", abs(ser_mes.pos.x - ser_mes.adv_pos.x) + abs(ser_mes.pos.y+1 - ser_mes.adv_pos.y),initial_dist);
if (abs(ser_mes.pos.x - ser_mes.adv_pos.x) + abs(ser_mes.pos.y+1 - ser_mes.adv_pos.y)> initial_dist)
{
int flag = 0;
for (int i = 0; i < ser_mes.object_count; i++)
{
if (ser_mes.pos.x == ser_mes.object_pos[i].x && ser_mes.pos.y+1 == ser_mes.object_pos[i].y)
{
flag = 1;
break;
}
}
if(flag != 1 && hareket_etme == 1){
//fprintf(stderr, "HELLO\n" );
hareket_etme = 0;
ph_mes.move_request.x = ser_mes.pos.x;
ph_mes.move_request.y = ser_mes.pos.y+1;
usleep((1+rand()%9)*10000);
//fprintf(stderr, "sag\n");
if (write(1, &ph_mes, sizeof(ph_mes)) < 0)
perror("writing stream message");
FILE *file = fdopen(1,"w");
fflush(file);
}
}
}
if (ser_mes.pos.y-1 >= 0)
{
if (abs(ser_mes.pos.x - ser_mes.adv_pos.x) + abs(ser_mes.pos.y-1 - ser_mes.adv_pos.y)> initial_dist)
{
int flag = 0;
for (int i = 0; i < ser_mes.object_count; i++)
{
if (ser_mes.pos.x == ser_mes.object_pos[i].x && ser_mes.pos.y-1 == ser_mes.object_pos[i].y)
{
flag = 1;
break;
}
}
if(flag != 1 && hareket_etme == 1){
hareket_etme = 0;
ph_mes.move_request.x = ser_mes.pos.x;
ph_mes.move_request.y = ser_mes.pos.y-1;
usleep((1+rand()%9)*10000);
//fprintf(stderr, "sol\n");
if (write(1, &ph_mes, sizeof(ph_mes)) < 0)
perror("writing stream message");
FILE *file = fdopen(1,"w");
fflush(file);
}
}
}
if (hareket_etme == 1){
ph_mes.move_request.x = ser_mes.pos.x;
ph_mes.move_request.y = ser_mes.pos.y;
usleep((1+rand()%9)*10000);
//fprintf(stderr, "kal\n");
if (write(1, &ph_mes, sizeof(ph_mes)) < 0)
perror("writing stream message");
FILE *file = fdopen(1,"w");
fflush(file);
}
}
}
|
C
|
/*/
* ARCHIVO:
* logistica.c
creacion:2009/08/28
* modificacin: 2009/08/30
modificacin: 2009/09/01
modificacin: 2009/09/03
* --------------------------------------------------------------------------------------
* DESCRIPCION:
* Este archivo contiene el codigo fuente de la parte del proyecto del
segundo parcial de Estructuras de Datos
* DEPENDENCIAS:
* ciudad.h
generic.h
list.h
graph.h
stack.h
queue.h
* Autores:
*Andres Calle
*Freddy Tandazo
*/
/*************************************************************************
** **
** DEPENDENCIAS ADICIONALES **
** **
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "generic.h"
#include "graph.h"
#include "list.h"
#include "ciudad.h"
#include "queue.h"
#include "stack.h"
#include "ciudad.h"
#include "camino.h"
/*************************************************************************
** **
** PROTOTIPOS **
** **
**************************************************************************/
void Titulo();
void Menu();
void Crear_ArcosIniciales(GRAPH *G,List *R);
int *GRAPH_Dikjstra(GRAPH *G,GRAPH_Vertex *Vorig);
void llenar_Grafo_Vertices(GRAPH *G, List *P);
void Opcion1(GRAPH *G,List *C, List *Cam);
/*************************************************************************
** **
** PROGRAMA PRINCIPAL **
** **
**************************************************************************/
void main(){
char *ciudad="";
int op;
GRAPH *G=GRAPH_New();
List *C=List_ReadFile("Ciudad.txt",Ciudad_Leer_Archivo);
List *Cam=List_ReadFile("Camino.txt",Camino_Leer_Archivo);
do{
Titulo();
Menu();
scanf("%d",&op);
if(op==1){
Opcion1(G,C,Cam);
}
}while(op!=2);
}
/*************************************************************************
** **
** IMPLEMENTACIONES **
** **
**************************************************************************/
/*
** FUNCION: void Opcion1(GRAPH *G,List *C, List *Cam);
** DESCRIPCION: Muestra la primera opcion del menu
** Uso: Opcion1(G,c,Cam);
***/
void Opcion1(GRAPH *G,List *C, List *Cam){
Ciudad *city;
NodeList *nodo;
char *ciudad2="";
char ciudad[50];
int tam=List_GetSize(G);
int i;
int *Dist=malloc(sizeof(int)*tam);//El tamao
llenar_Grafo_Vertices(G,C);
Crear_ArcosIniciales(G,Cam);
printf("\n\n\t\tEscoja la ciudad que desea consultar\t:)");
scanf("%s",ciudad);
ciudad2=ciudad;
city=Ciudad_Crear("",ciudad2);
nodo=List_Search(C,city,Ciudad_cmpXNombre);
if(nodo){
Dist=GRAPH_Dikjstra(G,GRAPH_SearchVertex(G,city,Ciudad_cmpXNombre));
}
else{
printf("\n\n\t\t***********************************************");
printf("\n\n\t\t******** La Ciudad no existe ************");
printf("\n\n\t\t***********************************************");
}
}
/*
**FUNCION: void Titulo();
**DESCRIPCION:Presenta el titulo del proyecto
**USO: Titulo();
*/
void Titulo(){
printf("\n\n\t\t***********************************************");
printf("\n\n\t\t******** RUTAS DEL ECUADOR *************");
printf("\n\n\t\t***********************************************");
}
/*
**FUNCION:void Menu();
**DESCRIPCION:Presenta el menu principal del proyecto
**USO: Menu();
*/
void Menu(){
printf("\n\n\t1.-Ver rutas");
printf("\n\n\t2.-Salir");
printf("\n\n\tIngrese la opcion deseada");
}
/*
*FUNCION:void llenar_Grafo_Vertices(GRAPH *G, List *P)
*DESCRIPCION: Llena los vertices del grafo
* Uso: llenar_Grafo_Vertices(G, P);
*/
void llenar_Grafo_Vertices(GRAPH *G, List *P){
NodeList *p;
GRAPH_Vertex *V;
for(p=List_GetHeader(P);p!=NULL;p=p->next){
V=GRAPH_Vertex_New(NodeList_GetContent(p));
List_InsertAfterLast(G,NodeList_New(V));
}
}
/*
*FUNCION:void Crear_ArcosIniciales(GRAPH *G,List *R)
*DESCRIPCION:Crea los arcos de los verrices
* Uso: Crear_ArcosIniciales(G, R);
*/
void Crear_ArcosIniciales(GRAPH *G,List *R)
{
Camino *ru,*ca;
Ciudad *pu,*ci,*ciu;
NodeList *p,*q;
GRAPH_Edge *ar;
GRAPH_Vertex *V1,*V2;
List *L;
for(p=List_GetHeader(G);p!=NULL;p=p->next){
V1=NodeList_GetContent(p);
L=List_SearchAll(R,Ciudad_GetNombre(GRAPH_Vertex_GetContent(V1)),Camino_CompXV1);
for(q=List_GetHeader(L);q!=NULL;q=q->next){
V2=NodeList_GetContent(List_Search(G,Camino_GetDestino(NodeList_GetContent(q)),Vertice_CmpXCodCom));
GRAPH_InsertEdge(G,V1,V2,0,NodeList_GetContent(q));
}
}
}
/*
* Funcin: GRAPH_Diskstra
* --------------------------
* Modo de uso:
* GRAPH *G;
* GRAPH_Vertex *Vorig;
*int *DistanciasMenores
*
* DistanciasMenores = GRAPH_Diskstra(G,Vo,f)
* Descripcin: Recorre en anchura los vrtices de
* un grafo, partiendo del vrtice Vo, ejecutando
* la funcin de impresin f para cada vrtice en
* el orden del recorrido.
*/
int *GRAPH_Dikjstra(GRAPH *G,GRAPH_Vertex *Vorig)
{
NodeList *nodo;
Ciudad *city;
int *Dist,tam,pos;
List *Lvert;
GRAPH_Vertex *Vk;
GRAPH_Initiate(G);
tam=List_GetSize(G);
Dist=malloc(sizeof(int)*tam);//El tamao
Iniciar_VectorDistancias(Dist,Vorig,tam,G);
Lvert=List_Copy(G);
List_RemoveXPos(Lvert,List_Search(Lvert,Vorig,GRAPH_Vertex_Compare));
while(!List_isEmpty(Lvert))
{
Vk =EscogerVerticeMenor(Dist,G,tam);
Modificar_Distancias(Dist,Vk,tam,G);
GRAPH_Vertex_SetVisit(Vk,MARKED);
List_RemoveXPos(Lvert,List_Search(Lvert,Vk,GRAPH_Vertex_Compare));
city=Vk->info;
Ciudad_Imprimir(city);
}
List_Delete(&Lvert);
return(Dist);
}
|
C
|
#include"time_to_s.h"
SysTime_t CONST_TIME = {1970,1,1,0,0,0,0};
bool CheckIsRunYear( uint16_t year)
{
bool bRet = false;
if( ((0 == year%4) && (year%100!=0)) || (0 == year%400))
bRet = true;
return bRet;
}
uint32_t DateSwSec(SysTime_t date)
{
uint32_t retSec = 0;
uint32_t RunYearNum = 0;
if(date.year<CONST_TIME.year)
{
return retSec;
}
uint8_t year = date.year - CONST_TIME.year;
for(uint32_t i=CONST_TIME.year;i<date.year;i++)
{
if( CheckIsRunYear(i) )
{
RunYearNum++;
}
}
uint8_t monthMax[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if( CheckIsRunYear(date.year) )
monthMax[1] = 29;
uint32_t mon = date.month - CONST_TIME.month;
uint16_t sunMontDay = 0;
for(int i=0;i<mon;i++)
{
sunMontDay += monthMax[i];
}
uint32_t day = date.day - CONST_TIME.day;
uint32_t SumDay = year*365 + RunYearNum + sunMontDay + day;
uint32_t hour = date.hour - CONST_TIME.hour;
uint32_t min = date.min - CONST_TIME.min;
uint32_t sec = date.sec - CONST_TIME.sec;
retSec = SumDay*3600*24 + hour*3600 + min*60 + sec;
return retSec;
}
|
C
|
/* Auteur :
Axel ARCHAMBAULT 3300807
Anas EZOUHRI 3208760
Bilel AFFES 3361270 */
#ifndef STRCT_MODULE_H
#define STRCT_MODULE_H
#include <linux/dcache.h>
#include <linux/workqueue.h>
#include <linux/syscalls.h>
#include <linux/sysinfo.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/swap.h>
#include <linux/list.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <asm/syscall.h>
#include "../Outil/pnl_outil.h"
/***************************
* allocation de memoire
***************************/
#define ALLOC(type, n) (type*) kmalloc(sizeof(type)*n, GFP_KERNEL)
/**************************************************
* Structure qui correspondra à la tâche asynchrone
**************************************************/
struct task_asynchrone{
int id; /* l'ID de la tache */
void *data; /* stockera le paramètre passée à la Worqueue */
int *finish; /* aura l'adresse de la variable finish des structures */
char type_task[7]; /* contindra le nom de la commande */
struct delayed_work dwork; /* contiendra la fonction à executer */
char adrEnvoie[TAILLE_BUF]; /* contindra l'adresse du buffer coté utilisateur */
struct task_struct **task_tmp; /* contiendra le tableau des taches pour la commande Wait */
};
/***************************************
* Liste des tâches en cours d'exécution
***************************************/
struct list_taskRunning{
struct task_asynchrone task; /* la tache en cours d'execution */
struct list_head list; /* la liste des taches */
};
/***************************************************
* Variables globales partagées par tout les fichiers
***************************************************/
extern int id; /* variable qui sera incrémentée à chaque création d'une nouvelle tache, elle correspondra à son ID */
extern int flag; /* flag qui correspondra à la condition de sortie d'un wait_event */
extern int retval; /* valeur de retour de la fonction ioctl */
extern char whoFG[10]; /* contiendra le nom de la commande qui est mise en avant plan avec la commande fg */
extern struct mutex mutex_kill; /* mutex pour la fonction kill_process */
extern struct mutex mutex_wait; /* mutex pour la fonction wait_process */
extern struct mutex mutex_list; /* mutex pour la fonction print_list */
extern struct mutex mutex_remove; /* mutex pour la fonction remove_list */
extern struct mutex mutex_meminfo; /* mutex pour la fonction info_mem */
extern struct mutex mutex_modinfo; /* mutex pour la fonction info_mod */
extern char result_fg[TAILLE_BUF]; /* contiendra le résultat d'une commande asynchrone si elle a été mise en avant plan */
extern wait_queue_head_t task_wait; /* ma Waitqueue */
extern struct list_taskRunning *taskRunning; /* liste des taches en cours d'execution */
/************************************************
* Fonctions d'initialisation des Works
************************************************/
int add_in_list(struct task_asynchrone *task); /* l'ajout d'une nouvelle tache dans la liste */
void remove_list(struct work_struct *work_test); /* suppression de la tache dans la liste */
struct task_asynchrone * init_task_asynch(char *type, void(*func)(struct work_struct *)); /* intialiser ma tache */
/******************************************
* Fonctions exécutées par la Workqueue
******************************************/
void fg_cmd(struct work_struct *work);
void info_mem(struct work_struct *work);
void info_mod(struct work_struct *work);
void print_list(struct work_struct *work);
void wait_process(struct work_struct *work);
void kill_process(struct work_struct *work);
/**********************************************************
* Handler appelé par le module dans le fonction d'ioctl
**********************************************************/
void mem_handler(struct info_mem *me);
void list_handler(struct task_run *run);
void fg_handler(struct answer_fg *answer);
void mod_handler(struct info_module *mod);
void wait_handler(struct wait_task *wait_ta);
void kill_handler(struct envoie_signal *sign);
/****************************************************************
* Fonction qui retrouve une structure a partir du champs dwork
****************************************************************/
struct task_asynchrone* task_asynch_of(struct work_struct *work_test);
#endif
|
C
|
// delete a node from the AVL tree
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct node {
int key;
int height;
struct node *lc;
struct node *rc;
struct node *pr;
};
#include "45printBinaryTree.h"
// ***** INSERTING INTO AVL ***** //
// function decalarations for AVL insert
void insertAVL(struct node **, int);
void fixAVL(struct node **, struct node *);
int setHeight(struct node *);
void leftRotate(struct node **, struct node *, struct node *);
void rightRotate(struct node **, struct node *, struct node *);
void insertAVL(struct node **root, int key) {
// creating node to be inserted
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = key;
temp->lc = NULL;
temp->rc = NULL;
// height of newly inserted node is zero
temp->height = 0;
// if tree is empty
if ((*root) == NULL) {
// set parent
temp->pr = NULL;
(*root) = temp;
return;
}
// find the correct position
struct node *pos, *parent;
pos = (*root);
parent = NULL;
while (pos != NULL) {
parent = pos;
if (key < pos->key) {
pos = pos->lc;
}
else {
pos = pos->rc;
}
}
// insert as child of parent
if (key < parent->key)
parent->lc = temp;
else
parent->rc = temp;
// setting parent pointer
temp->pr = parent;
// fix heights
// fix AVL property
fixAVL(root, temp);
}
void fixAVL(struct node **root, struct node *z) {
int res;
struct node *x, *y;
// since z is the new node inserted
y = z;
z = z->pr;
x = NULL;
// fix heights till root and find violation of AVL if any
while (z != NULL) {
res = setHeight(z);
if (res == 0)
return;
else if (res == -1) {
x = y;
y = z;
z = z->pr;
}
else {
// find if zig zig or zig zag
// zig zig
// dont have to check for if x is null since we will never enter this loop
// fixing height of z
z->height -= 2;
if (x->key < y->key && y->key < z->key)
rightRotate(root, y, z);
else if (x->key >= y->key && y->key >= z->key)
leftRotate(root, z, y);
else {
// fixing height of x and y
x->height += 1;
y->height -= 1;
if (x->key < y->key) {
rightRotate(root, x, y);
// it is implied that y->key > z->key otherwise we get above cases
leftRotate(root, z, x);
}
else {
// x->key > y->key
leftRotate(root, y, x);
// implied that y->key <- z->key
rightRotate(root, x, z);
}
}
// only one interation is required to fix the tree
return;
}
}
}
void leftRotate(struct node **root, struct node *t, struct node *d) {
// setting right child of t
t->rc = d->lc;
if (t->rc != NULL)
t->rc->pr = t;
// setting parent of d
d->pr = t->pr;
if (d->pr == NULL)
(*root) = d;
else {
if (d->key < d->pr->key)
d->pr->lc = d;
else
d->pr->rc = d;
}
// setting left child of d and parent of t
d->lc = t;
t->pr = d;
}
void rightRotate(struct node **root, struct node *d, struct node *t) {
// setting left child of t
t->lc = d->rc;
if (t->lc != NULL)
t->lc->pr = t;
// setting parent of d
d->pr = t->pr;
if (d->pr == NULL)
(*root) = d;
else {
if (d->key < d->pr->key)
d->pr->lc = d;
else
d->pr->rc = d;
}
// setting right child of d and parent of t;
d->rc = t;
t->pr = d;
}
// return 0 if no height change, returns -1 if height change but balanced and return 1 if unbalanced
int setHeight(struct node *node) {
// assuming children dont exist
int leftH = -1, rightH = -1;
if (node->lc != NULL)
leftH = node->lc->height;
if (node->rc != NULL)
rightH = node->rc->height;
int prH; // parent height
if (rightH >= leftH)
prH = rightH + 1;
else
prH = leftH + 1;
// no height change
if (prH == node->height) {
// but is unbalanced? - due to deletion
int heightDiff = (rightH - leftH) > 0 ? (rightH - leftH) : (leftH - rightH);
if (heightDiff > 1)
return 1; // unbalanced tree
else
return 0; // balanced tree
}
else {
node->height = prH;
int heightDiff = (rightH - leftH) > 0 ? (rightH - leftH) : (leftH - rightH);
if (heightDiff > 1)
return 1; // unbalanced tree
else
return -1; // balanced tree
}
}
// ***** DELETING A NODE ***** //
// function declaration for deleting a node from AVL
void deleteAVL(struct node **, int);
void deleteNode(struct node **, struct node *);
void transplant(struct node **, struct node *, struct node *);
// setHeight, leftRotate and rightRotate defined above
void fixDelAVL(struct node **, struct node *);
// this delete procedure replaces the entire node and not just the values
void deleteAVL(struct node **root, int key) {
struct node *node = (*root);
// find the key in the tree
while ((node)->key != key) {
if (key < (node)->key)
node = (node)->lc;
else
node = (node)->rc;
if ((node) == NULL) {
printf("NODE NOT FOUND!\n");
return;
}
}
struct node *temp = node;
deleteNode(root, node);
free(temp);
}
// this procedure deletes the node from the tree
void deleteNode(struct node **root, struct node *node) {
if (node->lc == NULL) {
transplant(root, node, node->rc);
fixDelAVL(root, node->pr);
}
else if (node->rc == NULL) {
transplant(root, node, node->lc);
fixDelAVL(root, node->pr);
}
else {
// find inorder successor
struct node *suc = node->rc;
while (suc->lc != NULL) {
suc = suc->lc;
}
// height could change of suc node parent
struct node *temp;
if (suc->pr == node)
temp = suc;
else
temp = suc->pr;
if (suc->pr != node) {
transplant(root, suc, suc->rc); // because there is no left child - transplant handles the case if right child is NULL
suc->rc = node->rc;
suc->rc->pr = suc;
}
transplant(root, node, suc);
// left child will definitely be there
suc->lc = node->lc;
suc->lc->pr = suc;
// fixing height of suc old pos
fixDelAVL(root, temp);
}
}
void fixDelAVL(struct node **root, struct node *z) {
int res;
struct node *x, *y;
// fix heights till root and find violation of AVL if any
while (z != NULL) {
res = setHeight(z);
//printf("Current:%d Height:%d Res:%d\n", z->key, z->height, res);
if (res == 0)
// no height change so we return
z = z->pr;
// return;
else if (res == -1) {
// height changed but still balanced - no issue
// we move z one level above
z = z->pr;
}
else {
// AVL violated
// we have our z we need to find x and y
if (z->lc != NULL && z->lc->height + 1 == z->height) {
y = z->lc;
if (y->lc != NULL && y->lc->height + 1 == y->height)
x = y->lc;
else
x = y->rc;
}
else {
y = z->rc;
if (y->rc != NULL && y->rc->height + 1 == y->height)
x = y->rc;
else
x = y->lc;
}
// find if zig zig or zig zag
// zig zig
if (x->key < y->key && y->key < z->key) {
rightRotate(root, y, z);
// fix heights of z - height of x remains same
setHeight(z);
// change z to y - y's height will be fixed in next iteration
z = y;
}
else if (x->key >= y->key && y->key >= z->key) {
leftRotate(root, z, y);
// fix heights of z - height of x remains same
setHeight(z);
// change z to y - y's height will be fixed in next iteration
z = y;
}
// zig zag
else {
if (x->key < y->key) {
rightRotate(root, x, y);
// it is implied that y->key > z->key otherwise we get above cases
leftRotate(root, z, x);
// fixing heights
setHeight(z);
setHeight(y);
// not changing height of x recursion will take care of that
z = x;
}
else {
// x->key > y->key
leftRotate(root, y, x);
// implied that y->key <- z->key
rightRotate(root, x, z);
// fixing heights
setHeight(z);
setHeight(y);
// not changing height of x recursion will take care of that
z = x;
}// end of else
}// end of outer else
}// end of else (res == -2)
}// end of while
}
// this procedure replaces node1 with node2 - just the parents
void transplant(struct node **root, struct node *node1, struct node *node2) {
if (node1->pr == NULL)
(*root) = node2;
else if (node1 == node1->pr->lc)
node1->pr->lc = node2;
else
node1->pr->rc = node2;
if (node2 != NULL)
node2->pr = node1->pr;
}
int main() {
srand(5);
int n = 20;
int a[n], i, temp, rand_index;
struct node *root = NULL;
// create an index array of n elements
for (i = 0 ; i < n ; i ++)
a[i] = i;
// permute it
for (i = 0 ; i < n ; i++) {
rand_index = rand() % n;
temp = a[rand_index];
a[rand_index] = a[i];
a[i] = temp;
}
// insert into AVL tree
for (i = 0 ; i < n ; i++)
insertAVL(&root, a[i]);
printBinaryTree(root);
int del_node;
while (1) {
printf("Enter the node to be deleted(-1 to exit): ");
scanf("%d", &del_node);
if (del_node == -1)
break;
deleteAVL(&root, del_node);
printBinaryTree(root);
if (root == NULL) {
printf("Tree Empty!");
break;
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#define MAXLINE 1000
int getLine (char s[], int maxLen);
void reverse ( char to[], char from[] );
int getLine(char s[], int maxLen)
{
int c,i;
for ( i = 0 ; i < maxLen-1 && ( ( c = getchar() ) != EOF ) && c != '\n' ; ++i)
{
s[i] = c;
}
if ( c == '\n')
{
s[i] = '\n';
}
s[i] = '\0';
return i;
}
void reverse ( char to[],char from[])
{
int i = 0 ;
int j= 0;
int len = 0;
len = strlen(from);
to[j]= '\0';
j = len-1;
while ( from[i] != '\0' )
{
to[j--] = from [i++];
}
printf("Reversed string is:%s\n",to);
}
int main()
{
int max = 0;
int len = 0;
char s[MAXLINE];
char to[MAXLINE];
while ( ( len = getLine(s,MAXLINE) ) > 0 )
{
max = len;
printf("len:%d\n",max);
reverse(to,s);
}
printf ("Exiting..........\n");
return 0;
}
|
C
|
#include <stdio.h>
int columna(char c){
if(c =='+' || c == '-')
return 0;
if(c == '0')
return 1;
if(c >= '1' && c <= '9')
return 2;
return 3;
}
int pasarValor(char s[]){
int i = 0;
int numero = 0;
if(s[0] != '+' && s[0] != '-')
i = 0;
else
i = 1;
while(s[i]){
numero = numero*10 + (s[i] - '0');
i++;
}
if(s[0] == '-')
return numero*-1;
return numero;
}
int automata(char s[]){
int matriz[5][4]={{2,1,3,4},{4,4,4,4},{4,4,3,4},{4,3,3,4},{4,4,4,4}};
int i = 0;
int e = 0;
int numero = 0;
if(s[0] == '0' && s[1] ){
printf("%s\n", "el numero no puede empezar por cero" );
return 0;
}
if(s[0] =='+' || s[0] == '-'){
if(s[1] == '0' && s[2]){
printf("%s\n", "el numero no puede empezar por cero, a menos que sea solamente el cero");
return 0;
}
if(s[1] == '0' && !s[2]){
printf("%s\n","se reconocio la cadena con exito");
return 0;
}
}
while(s[i]){
e = matriz[e][columna(s[i])];
i++;
//printf("%d\n",e );
if(e == 4){
printf("%s","no se reconoce la cadena, error en la posicion ");
printf("%i\n", i );
printf("%s","el caracter ");
printf("%c",s[i-1] );
printf("%s\n"," no pertenece al tipo de dato" );
return 0;
}
}
i = 0;
if(e == 1 || e == 3){
numero = pasarValor(s);
printf("%s\n","se reconocio la cadena con exito");
return numero;
}
return 0;
}
int main(int argc, char const *argv[])
{
char s[]= "+1245";
printf("%i\n",automata(s));
//printf("%c\n", 4[s]); //LOOOOOOO0000OOOOOOOOOO000000OOOOOOOLLLLLLLLL
return 0;
}
|
C
|
/*
* Array QָʾһԪصλַ
* pointer ++ĄĕrᘌָY͑BӜp
* ӑBgĕrǂgheap, ҂Ȼָ׃stack
* :
* int *ptr = malloc(sizeof(int) * 100);
* malloc ҂ӛwеheap^Ҫȡ sizeof(int) * 100 @ӴСĿg
* ptr@׃Ǵeأ @׃Ǵstack!
*
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int(*ptr)[4] = malloc(sizeof(int) * 10);
printf("\nsizeof *ptr : %zu\n", sizeof(*ptr));
/* ԇf ptr + 1 ӛwλַО
* &ptr ptr IJeʲN? ( hint : ^씵ֵ Ոӛwheap, stack ȥ˼ )
*/
printf("ptr : %p\n", ptr);
printf("ptr + 1: %p\n", ptr + 1);
printf("address of ptr : %p\n\n", &ptr);
/* ^r, ָ+1׃*/
double (*ptr_to_double) = malloc(sizeof(double));
int (*ptr_to_int) = malloc(sizeof(int));
printf("ptr_to_double : %p\n", ptr_to_double);
printf("ptr_to_double + 1: %p\n\n", ptr_to_double + 1);
printf("ptr_to_int : %p\n", ptr_to_int);
printf("ptr_to_int + 1 : %p\n\n", ptr_to_int + 1);
free(ptr_to_int);
free(ptr_to_double);
free(ptr);
/* XÞʲNr 治һӣ
* ͬӵӛĵĽǶȷ
*/
int32_t array[10] = {};
int32_t *stackptr = array;
printf("stackptr : %p\n", stackptr);
printf("stackptr + 1: %p\n\n", stackptr + 1);
for (int i = 0; i < 10; i++){
printf("address of array[%d] : %p\n", i, &array[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#include <errno.h>
#include <ctype.h>
#define MAXLINE 80
#define SERV_PORT 8888
#define OPEN_MAX 1024
int main(int argc, char *argv[])
{
int i, j, maxi, listenfd, connfd, sockfd;
int nready; //接收poll返回值,记录满足监听事件的fd个数
ssize_t n;
char buf[MAXLINE], str[INET_ADDRSTRLEN];
socklen_t clie_len;
struct pollfd client[OPEN_MAX];
struct sockaddr_in clie_addr, serv_addr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
int opt = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERV_PORT);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
listen(listenfd, 128);
client[0].fd = listenfd;
client[0].events = POLLIN;
for(i = 1; i < OPEN_MAX; i++)
client[i].fd = -1;
maxi = 0;
while(1)
{
nready = poll(client, maxi+1, -1);
if(client[0].revents & POLLIN){
clie_len = sizeof(clie_addr);
connfd = accept(listenfd, (struct sockaddr *)&clie_addr, &clie_len);
printf("received from %s at PORT %d\n",
inet_ntop(AF_INET, &clie_addr.sin_addr, str, sizeof(str)),
ntohs(clie_addr.sin_port));
for (i = 1; i < OPEN_MAX; i++)
if(client[i].fd < 0){ //在这个bug 上耗费了快四个小时
client[i].fd = connfd; //client[i].fd < 0, 是小于0。。。。。
break; //醉了醉了醉了,不过好在是解决了
} //留个日期纪念下2019_5_12
client[i].events = POLLIN;
if(i > maxi)
maxi = i;
if(--nready <= 0)
continue;
}
for (i = 1; i<= maxi; i++){
if((sockfd = client[i].fd) < 0)
continue;
if(client[i].revents & POLLIN){
if((n = read(sockfd, buf, MAXLINE)) < 0) {
if(errno == ECONNRESET) {
printf("client[%d] aborted connection\n", i);
close(sockfd);
client[i].fd = -1;
} else
{
perror("read error");
exit(1);
}
} else if(n == 0)
{
printf("client[%d] closed connection\n", i);
close(sockfd);
client[i].fd = -1;
} else {
for(j = 0; j<n; j++)
buf[j] = toupper(buf[j]);
write(sockfd, buf, n);
}
if(--nready <= 0)
break;
}
}
}
return 0;
}
|
C
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Wang Jian
*
* 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 <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <sys/stat.h>
#include <stutils/st_macro.h>
#include "st_log.h"
#include "st_string.h"
void remove_newline(char *line)
{
char *pstr = NULL;
ST_CHECK_PARAM_VOID(line == NULL);
pstr = strrchr(line, '\r');
if(pstr != NULL)
{
*pstr = 0;
}
pstr = strrchr(line, '\n');
if(pstr != NULL)
{
*pstr = 0;
}
}
void remove_leading_space(char *line)
{
char *pstr = NULL;
char *p = NULL;
ST_CHECK_PARAM_VOID(line == NULL);
pstr = line;
while(*pstr != '\0' && (*pstr == ' ' || *pstr == '\t')) {
++pstr;
}
if (pstr != line) {
p = line;
while(*pstr != '\0') {
*p = *pstr;
p++;
pstr++;
}
*p = '\0';
}
}
void trim(char *line)
{
char *pstr = NULL;
ST_CHECK_PARAM_VOID(line == NULL);
remove_newline(line);
remove_leading_space(line);
pstr = line + strlen(line) - 1;
while(pstr >= line && (*pstr == ' ' || *pstr == '\t')) {
--pstr;
}
pstr++;
if (pstr >= line) {
*pstr = '\0';
}
}
int split_line(const char *line, char *fields,
int n_field, int field_len, const char *seps)
{
const char *p;
const char *q;
int f;
int i;
bool split;
ST_CHECK_PARAM(fields == NULL || line == NULL, -1);
p = line;
f = 0;
i = 0;
while (*p != '\0') {
split = false;
while (*p != '\0') {
q = seps;
while (*q != '\0') {
if (*p == *q) {
split = true;
break;
}
q++;
}
if (*q == '\0') { /* not meet seps */
break;
}
p++;
}
if (*p == '\0') {
break;
}
if (split && i > 0) {
fields[f * field_len + i] = '\0';
if (f >= n_field - 1) {
ST_WARNING("Too many fields. [%s]", line);
return -1;
}
f++;
i = 0;
}
if (i >= field_len - 1) {
ST_WARNING("Too long field. [%s]", p - i);
return -1;
}
fields[f * field_len + i] = *p;
i++;
p++;
}
if (i > 0) {
fields[f * field_len + i] = '\0';
f++;
}
return f;
}
const char* get_next_token(const char *line, char *token)
{
while(*line && (*line == ' ' || *line == '\t'
|| *line == '\r' || *line == '\n')) {
line++;
}
while(*line && *line != ' ' && *line != '\t'
&& *line != '\r' && *line != '\n') {
*token = *line;
token++;
line++;
}
*token = 0;
if(*line == 0) {
line = NULL;
}
return line;
}
static int get_next_utf8_char(const char *utf8)
{
unsigned char lb;
ST_CHECK_PARAM(utf8 == NULL, -1);
lb = *utf8;
if(lb == 0)
{
return -1;
}
if (( lb & 0x80 ) == 0 ) // lead bit is zero, must be a single ascii
{
return 1;
}
else if (( lb & 0xE0 ) == 0xC0 ) // 110x xxxx
{
return 2;
}
else if (( lb & 0xF0 ) == 0xE0 ) // 1110 xxxx
{
return 3;
}
else if (( lb & 0xF8 ) == 0xF0 ) // 1111 0xxx
{
return 4;
}
else
{
ST_WARNING( "Unrecognized UTF8 lead byte (%02x)\n", lb );
return -1;
}
}
static int get_next_gbk_char(const char *gbk)
{
ST_CHECK_PARAM(gbk == NULL, -1);
if(gbk[0] == 0 || gbk [1] == 0)
{
return -1;
}
return 2;
}
int get_next_char(const char *token, encoding_type_t encoding)
{
if(encoding == ENCODING_GBK)
{
return get_next_gbk_char(token);
}
else if(encoding == ENCODING_UTF8)
{
return get_next_utf8_char(token);
}
ST_WARNING("Unsupported encoding");
return -1;
}
static bool need_quote(const char *str)
{
const char *ok_chars = "[]~#^_-+=:.,/";
const char *c = str;
const char *d;
if (*c == '\0') {
return true; // Must quote empty string
} else {
for (; *c != '\0'; c++) {
// For non-alphanumeric characters we have a list of characters which
// are OK. All others are forbidden (this is easier since the shell
// interprets most non-alphanumeric characters).
if (!isalnum(*c)) {
for (d = ok_chars; *d != '\0'; d++) {
if (*c == *d) {
break;
}
}
// If not alphanumeric or one of the "ok_chars", it must be escaped.
if (*d == '\0') {
return true;
}
}
}
return false; // The string was OK. No quoting or escaping.
}
}
// Returns a quoted and escaped version of "str"
// which has previously been determined to need escaping.
// Our aim is to print out the command line in such a way that if it's
// pasted into a shell, it will get passed to the program in the same way.
static int quote(const char *str, char *ans, size_t ans_len)
{
// For now we use the following rules:
// In the normal case, we quote with single-quote "'", and to escape
// a single-quote we use the string: '\'' (interpreted as closing the
// single-quote, putting an escaped single-quote from the shell, and
// then reopening the single quote).
char quote_char = '\'';
const char *escape_str = "'\\''"; // e.g. echo 'a'\''b' returns a'b
size_t n;
const char *c;
const char *p;
// If the string contains single-quotes that would need escaping this
// way, and we determine that the string could be safely double-quoted
// without requiring any escaping, then we double-quote the string.
// This is the case if the characters "`$\ do not appear in the string.
// e.g. see http://www.redhat.com/mirrors/LDP/LDP/abs/html/quotingvar.html
if (strchr(str, '\'') && !strpbrk(str, "\"`$\\")) {
quote_char = '"';
escape_str = "\\\""; // should never be accessed.
}
n = 0;
if (n >= ans_len - 1) {
return -1;
}
ans[n] = quote_char;
n++;
c = str;
for (;*c != '\0'; c++) {
if (*c == quote_char) {
for(p = escape_str; *p != '\0'; p++) {
if (n >= ans_len - 1) {
return -1;
}
ans[n] = *p;
n++;
}
} else {
if (n >= ans_len - 1) {
return -1;
}
ans[n] = *c;
n++;
}
}
if (n >= ans_len - 1) {
return -1;
}
ans[n] = quote_char;
n++;
ans[n] = 0;
return 0;
}
int st_escape(const char *str, char *ans, size_t ans_len)
{
if (need_quote(str)) {
return quote(str, ans, ans_len);
} else {
if (strlen(str) >= ans_len) {
return -1;
}
strcpy(ans, str);
}
return 0;
}
int st_escape_args(int argc, const char *argv[], char *ans, size_t ans_len)
{
size_t len;
int i;
ans[0] = 0;
len = 0;
for (i = 0; i < argc; i++) {
if (st_escape(argv[i], ans + len, ans_len - len) < 0) {
ans[ans_len - 1] = 0;
return -1;
}
len = strlen(ans);
if (len >= ans_len - 2) {
break;
}
ans[len] = ' ';
len++;
}
ans[ans_len - 1] = 0;
return 0;
}
int st_str_replace(char* res, size_t res_len,
const char* src, const char* from, const char* to,
int max_num)
{
const char *str, *p;
size_t sz;
int num;
ST_CHECK_PARAM(res == NULL || res_len <= 0
|| src == NULL || from == NULL, -1);
str = src;
num = 0;
sz = 0;
while (max_num <= 0 || num < max_num) {
p = strstr(str, from);
if (p == NULL) {
break;
}
if (sz + p - str >= res_len) {
ST_WARNING("not enough space for result.");
goto ERR;
}
strncpy(res + sz, str, p - str);
sz += p - str;
if (to != NULL) {
if (sz + strlen(to) >= res_len) {
ST_WARNING("not enough space for result.");
goto ERR;
}
strcpy(res + sz, to);
sz += strlen(to);
}
++num;
str = p + strlen(from);
}
if (sz + strlen(str) >= res_len) {
ST_WARNING("not enough space for result.");
goto ERR;
}
strcpy(res + sz, str);
return num;
ERR:
res[sz] = '\0';
return -1;
}
long long st_str2ll(const char *str)
{
long long l;
size_t len;
l = atoll(str);
if (l == 0) {
return l;
}
len = strlen(str);
if (len < 1) {
return l;
}
switch (str[len - 1]) {
/* All fall through */
case 'Y':
l *= 1000;
case 'Z':
l *= 1000;
case 'E':
l *= 1000;
case 'P':
l *= 1000;
case 'T':
l *= 1000;
case 'G':
l *= 1000;
case 'M':
l *= 1000;
case 'k':
l *= 1000;
break;
case 'i':
if (len < 2) {
return l;
}
switch (str[len - 2]) {
/* All fall through */
case 'Y':
l *= 1024;
case 'Z':
l *= 1024;
case 'E':
l *= 1024;
case 'P':
l *= 1024;
case 'T':
l *= 1024;
case 'G':
l *= 1024;
case 'M':
l *= 1024;
case 'K':
l *= 1024;
break;
default:
break;
}
break;
default:
break;
}
return l;
}
char* st_ll2str(char *str, size_t len, long long l, bool binary)
{
static char suf[] = {'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
long long t;
long long base;
size_t sz;
int n;
ST_CHECK_PARAM(str == NULL || len <= 0, NULL);
t = l;
n = 0;
if (binary) {
base = 1024;
} else {
base = 1000;
}
while (t != 0 && t % base == 0) {
t = t / base;
n++;
if (n >= sizeof(suf)) {
break;
}
}
snprintf(str, len, "%lld", t);
if (n > 0) {
sz = strlen(str);
if (binary) {
if (sz > len - 3) {
ST_WARNING("string buf len not enough");
return NULL;
}
str[sz] = toupper(suf[n - 1]);
str[sz+1] = 'i';
str[sz+2] = '\0';
} else {
if (sz > len - 2) {
ST_WARNING("string buf len not enough");
return NULL;
}
str[sz] = suf[n - 1];
str[sz+1] = '\0';
}
}
return str;
}
char* st_strncatf(char *dst, size_t len, const char *fmt, ...)
{
char buf[MAX_LINE_LEN];
va_list args;
va_start(args, fmt);
vsnprintf(buf, MAX_LINE_LEN, fmt, args);
va_end(args);
strncat(dst, buf, len - strlen(buf) - 1);
return dst;
}
|
C
|
#define _XOPEN_SOURCE 500
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include "lib.h"
int lib_create(const char *name){
int shmid = shm_open(name, O_RDWR | O_CREAT | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO);
if(shmid == -1)
return -1;
int retval = ftruncate(shmid, sizeof(library_t));
if(retval == -1)
lib_destroy(name);
return retval;
}
int lib_init(library_t *lib){
int retval = sem_init(&lib->writers, 1, 0) | sem_init(&lib->readers, 1, 0) | sem_init(&lib->var, 1, 1) | sem_init(&lib->write, 1, 1);
if(retval == -1)
lib_deinit(lib);
return retval;
}
int lib_deinit(library_t *lib){
return sem_destroy(&lib->writers) | sem_destroy(&lib->readers) | sem_destroy(&lib->var) | sem_destroy(&lib->write);
}
library_t *lib_open(const char *name){
int shmid = shm_open(name, O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
if(shmid == -1)
return NULL;
library_t *lib = mmap(NULL, sizeof(*lib), PROT_READ | PROT_WRITE, MAP_SHARED, shmid, 0);
return lib == MAP_FAILED ? NULL : lib;
}
int lib_close(library_t *lib){
return munmap(lib, sizeof(*lib));
}
int lib_destroy(const char *name){
return shm_unlink(name);
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "note.h"
#define SIZE 0x100
char active_notes[SIZE][2][7];
void activenotes_load() {
memset(active_notes, 0, sizeof(active_notes));
}
void activenotes_add(NOTE *n) {
active_notes[n->note][n->sharp][n->octave] = 1;
}
void activenotes_rm(NOTE *n) {
active_notes[n->note][n->sharp][n->octave] = 0;
}
bool activenotes_isactive(NOTE *n) {
return active_notes[n->note][n->sharp][n->octave] == 1;
}
NOTE *activenotes_next(NOTE *n) {
while (1) {
if (n->sharp == 0) {
n->sharp = 1;
}
else {
n->sharp = 0;
n->note++;
}
if (n->note > 'g') {
n->note = 'a';
n->octave++;
}
if (n->octave > 8) {
return 0;
}
if (activenotes_isactive(n))
return n;
}
return 0;
}
int activenotes_get_total() {
int total = 0;
NOTE n;
n.note = 'a';
n.sharp = 0;
n.octave = 0;
while (n.octave < 8) {
if (n.sharp == 0) {
n.sharp = 1;
}
else {
n.sharp = 0;
n.note++;
}
if (n.note > 'g') {
n.note = 'a';
n.octave++;
}
if (activenotes_isactive(&n)) {
total++;
}
}
return total;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MIN 10
#define MAX 1000
struct lista;
typedef struct lista *pok;
typedef struct lista{
int br;
pok next;
}Brojevi;
pok CreateNode();
void IspisListe(pok);
void UbaciUListu(pok,int);
void UbaciNaKraj(pok,int);
int main()
{
srand(time(NULL));
pok L = NULL;
L = CreateNode();
L->next = NULL;
int broj[20],i;
for(i=0;i<20;i++)
{
broj[i] = rand()% MAX - MIN +1;
printf("A=%d\t",broj[i]);
if(i == 0)
UbaciUListu(L,broj[i]);
else if (broj[i] > broj[i-1])
UbaciNaKraj(L,broj[i]);
else if(broj[i] < broj[i-1])
UbaciUListu(L,broj[i]);
}
IspisListe(L);
return 0;
}
pok CreateNode(){
pok Q = (pok)malloc(sizeof(Brojevi));
if(Q==NULL)
return NULL;
else return Q;
}
void UbaciUListu(pok L , int broj)
{
pok Q = CreateNode();
Q->br = broj;
Q->next = L->next;
L->next = Q;
}
void UbaciNaKraj(pok L,int broj)
{
pok Q = CreateNode();
Q->br = broj;
while(L->next != NULL)
L=L->next;
Q->next = L->next;
L->next = Q;
}
void IspisListe(pok L){
L=L->next;
while(L!=NULL)
{
printf("%d\t",L->br);
L=L->next;
}
}
|
C
|
/*
Assigned by:
Student 1: Melinda Levi ID:201310356
Student 2: Kostya Lokshin ID:310765821
Lecturer: Costa Mirkin 61104-62
Targil: Shimon Aviram 661104-61 / Lior Levi 661104-63
*/
#include <stdio.h>
#include "binary_srch_tree.h"
#include "dlist_b.h"
///////////////////////////////////////////////////////////////
bsTree *newTree() { //function to create a new tree
bsTree *tree;
tree = (bsTree*)malloc(sizeof(bsTree)); //allocate memmory for the tree
tree->root = NULL; //zeroise the root
return tree; //return the address
}
///////////////////////////////////////////////////////////////
void insertBSTNode(bsTree *tree, int data) { //function to insert new value into the tree
bstNodeT *tmp;
tmp = (bstNodeT*)malloc(sizeof(bstNodeT)); //allocate memmory for a new node
tmp->data = data; //put the data in the node
tmp->left = NULL; //zeroise left and right branches of the new node
tmp->right = NULL;
if (!tree->root) { //if the tree is empty put the new node as the root of the tree
tree->root = tmp;
tmp->father = NULL;
}
else { //else deside where to put the new node using insertToNode() function
insertToNode(tree->root, tmp);
}
}
///////////////////////////////////////////////////////////////
void insertToNode(bstNodeT *theNode, bstNodeT *tmp) { //function to determine where too put the new value in the tree
if (tmp->data < theNode->data) { //if the data of the new node is smaller than the current junction
if (!theNode->left) { //if there is no left branch then put the new node there
theNode->left = tmp;
tmp->father = theNode;
}
else {
insertToNode(theNode->left, tmp); //continue search recursivley for place to put the new node
}
}
else if (tmp->data > theNode->data) { //if the data of the new node is smaller than the current junction
if (!theNode->right) { //if there is no right branch then put the new node there
theNode->right = tmp;
tmp->father = theNode;
}
else {
insertToNode(theNode->right, tmp); //continue search recursivley for place to put the new node
}
}
else { //if the value of the current node already exist in the tree the release it
free(tmp);
}
}
///////////////////////////////////////////////////////////////
void printInorder(bsTree *tree) { //function to print the tree inorder
bstList *list; //use list as stack
bstNodeT tmpNode;
int flag; //flag - determine if to go for left branch or not
list = newBSTlist(); //create new list as stack
if (!tree->root) { //if the tree is empty
printf("the tree is empty\n");
return;
}
insertBSTlistFirst(list, tree->root); //push the root to the stack
flag = 1;
while (list->size) { //as long as the stack is not empty
if (list->head->item->left && flag) { //as long as there is left branch insert it to the stack
insertBSTlistFirst(list, list->head->item->left); //push left branches ito the stack
}
else {
printf("%d, ", list->head->item->data); //print the top item in the stack
flag = 0; //stop pushing left branches
if (list->head->item->right) { //if there is a right branch to the item
tmpNode = *list->head->item;
deleteFirstBSTlist(list); //pop the last item from stack
insertBSTlistFirst(list, tmpNode.right); //push the right branch item into the stack
flag = 1; //cuntinue to push left branches
}
else {
deleteFirstBSTlist(list); //pop the first item in the stack
}
}
}
free(list); //free the mmemory allocated for the list
}
///////////////////////////////////////////////////////////////
void printInArray(bsTree *tree) { //function nto print the three as an array
bstList *list; //use list as queu
list = newBSTlist(); //create new list as queu
if (!tree->root) { //if the tree is empty
printf("the tree is empty\n");
return;
}
insertBSTlistLast(list, tree->root); //insert the root to the queu
while (list->size) { //as long as the queu is not empty
printf("%d,", list->head->item->data); //print the first item in the queu
if (list->head->item->left) { //if there is a left branch the insert it into the queu
insertBSTlistLast(list, list->head->item->left);
}
if (list->head->item->right) { //if there is a right branch the insert it into the queu
insertBSTlistLast(list, list->head->item->right);
}
deleteFirstBSTlist(list); //remove the next item from the queu
}
printf("\n");
free(list); //free the mmemory allocated for the list
}
///////////////////////////////////////////////////////////////
void freeTree(bsTree *tree) { //function to free the memmory that was allocated to the tree
bstList *list; //use list as queu
list = newBSTlist(); //create new list as queu
if (!tree->root) { //if the tree is empty
free(tree); //free the mmemory allocated for the tree
return;
}
insertBSTlistLast(list, tree->root); //insert the root to the queu
while (list->size) { //as long as the queu is not empty
if (list->head->item->left) { //if there is a left branch the insert it into the queu
insertBSTlistLast(list, list->head->item->left);
}
if (list->head->item->right) { //if there is a right branch the insert it into the queu
insertBSTlistLast(list, list->head->item->right);
}
free(list->head->item); //free the memmory that was allocated for the node that is next in the queu
deleteFirstBSTlist(list); //remove the next item from the queu
}
free(list); //free the mmemory allocated for the list
free(tree); //free the mmemory allocated for the tree
}
///////////////////////////////////////////////////////////////
int getInput() { //function to get input values from user
int strSize, i, x, flag, exp; //strSize - size of input string, i - index, x - return value, flag - determine if num is +/-, exp - exponent*10
char str[MAX_C]; //string to get input from user
clearStdi(); //clear stdin buffer
scanf("%s", str); //get string from user
strSize = strlen(str); //get string size
flag = 0;
exp = 1;
x = 0;
i = 0;
if (str[i] == '-') { //if first char in string is '-'
if (strSize == 1) {
return MIN_INT;
}
flag = 1; //flag that the number will be negative
}
for (i = strSize - 1;i >= flag;i--) { //check all chars in string
str[i] -= 48; //change the char to a number (ASCII)
if (str[i] < 0 || str[i] >9) { //if one of the chars in string is not a number than return a non number flag
return MIN_INT;
}
x += str[i] * exp; //create the numerical value of the input
exp *= 10;
}
if (flag) { //if number is negative
x *= -1;
}
return x; //return input number
}
///////////////////////////////////////////////////////////////
//void clearStdi() { //function to clear the system input buffer
// char input;
// while ((input = getchar()) != '\n' && input != EOF); //clear stdin buffer as long there is items there and entered is pressed
//}
///////////////////////////////////////////////////////////////
|
C
|
/*
+----------------------------------------------------------------------+
| PHP2C -- utility.h |
+----------------------------------------------------------------------+
| Autori: BAVARO Gianvito |
| CAPURSO Domenico |
| DONVITO Marcello |
+----------------------------------------------------------------------+
*/
/* Questo file contiene un insieme di strutture dati e funzioni di utilità e supporto per il
processo di compilazione e traduzione. */
typedef enum { false, true } bool; /* Struttura per un nuovo tipo di dato: bool.
Rappresenta i valori booleani. */
typedef struct testo /* Struttura per un nuovo tipo di dato: testo. E' una lista concatenata di stringhe. */
{
char *tes;
struct testo *next;
} testo;
/** Lista concatenata contenente i tipi delle variabili, elementi di array o costanti. Utile per il type_checking.*/
testo *T;
/** Lista concatenata contenente gli elementi di una espressione (variabili, elementi di array, costanti, operatori).
* Utile per stampare intere espressioni nel file f_out.c contenente la traduzione in C. */
testo *Exp;
/** Lista concatenata contenente frasi o parole ( non keywords ). Utile per stampare intere frasi,
* anche associate a espressioni, nel file f_out.c . */
testo *Phrase;
/** La funzione clear cancella il contenuto di ogni lista. Una funzione molto importante poichè è
necessario resettare le liste ogni volta che il parser valida una frase. */
void clear( ) {
T = NULL;
Exp = NULL;
Phrase = NULL;
}
/** La funzione put_testo inserisce una stringa in una lista.
Gli argomenti sono:
- TT, un doppio puntatore alla lista per consentire l'aggiunta di nuovi elementi;
- str, la stringa da inserire nel campo tes del nuovo elemento che viene inserito
nella lista. */
void put_testo( testo **TT,char *str )
{
testo *punt,*t_el;
t_el = ( testo * )malloc( sizeof( testo ) );
t_el->tes = ( char * )strdup( str );
t_el->next = NULL;
if ( *TT == NULL )
*TT = t_el;
else
{
punt = *TT;
while ( punt->next!=NULL )
punt = punt->next;
punt->next = t_el;
}
}
/** La funzione get_testo stampa a video tutti i valori di una lista.
Gli argomenti sono:
- TT, un puntatore alla lista;
- nome, una stringa d'utilità per etichettare la stampa, in modo tale da indentificare
la lista. */
void get_testo( testo *TT, char *nome )
{
testo *punt = TT;
printf( "/* * * * * * * * * * * %s * * * * * * * * * * */\n\n", nome );
while ( punt != NULL ) {
printf( "Elemento: %s\n", punt->tes );
punt = punt->next;
}
printf( "\n/* * * * * * * * * * * * * * * * * * * * * * * * */\n\n" );
}
/** La funzione countelements conta il numero di elementi presenti in una lista.
L'argomento è:
- T, un puntatore alla lista;
Restituisce il numero degli elementi. */
int countelements( testo *T ) {
testo *punt = T;
int value = 0;
while ( punt != NULL ) {
value++;
punt = punt->next;
}
return value;
}
/** La funzione isnumeric stabilisce se una stringa è costituita da soli numeri,
ossia se si tratta di un numero o no.
L'argomento è:
- str, la stringa da analizzare;
Restituisce 1 se la stringa è un numero, 0 altrimenti. */
int isnumeric( char *str )
{
//prelevo il primo carattere.
char *c = (char *)strndup(str, 1);
//se è uguale a "-", è in analisi un numero negativo.
if ( strcmp( c, "-" ) == 0) {
//scarta il segno "-".
c = ( char * )strdup( str + 1 );
//per ogni carattere verifica che sia un numero.
while ( *c )
{
//se anche un solo carattere non è un numero, restituisce zero e interrompe il ciclo.
if ( !isdigit( *c ) )
return 0;
c++;
}
//se il primo carattere non è "-", è in analisi un numero maggiore o uguale a zero.
} else {
//per ogni carattere verifica che sia un numero.
while ( *str )
{
//se anche un solo carattere non è un numero, restituisce zero e interrompe il ciclo.
if ( !isdigit( *str ) )
return 0;
str++;
}
}
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct queue
{
struct node *rear;
struct node *front;
};
void initial(struct queue *);
void qadd(struct queue *, int);
int qdel(struct queue *);
void dis(struct queue *);
void push(int);
void pop();
void displayFunction(struct queue *q)
{
struct node *tmp;
tmp = q->front;
while ((tmp) != NULL)
{
printf("\n%d", (tmp->data));
tmp = tmp->next;
}
printf("\n");
}
struct queue q1, q2;
int main()
{
initial(&q1);
initial(&q2);
push(5);
push(6);
push(7);
pop();
printf("\nelements now are:\n");
displayFunction(&q1);
return 0;
}
void initial(struct queue *q)
{
q->front = NULL;
q->rear = NULL;
}
void qadd(struct queue *q, int n)
{
struct node *tmp;
tmp = (struct node *)malloc(sizeof(struct node));
tmp->data = n;
tmp->next = NULL;
if (q->front == NULL)
{
q->rear = tmp;
q->front = tmp;
return;
}
q->rear->next = tmp;
q->rear = tmp;
}
int qdel(struct queue *q)
{
struct node *tmp;
int itm;
if (q->front == NULL)
{
printf("\nqueue is empty");
return 0;
}
//itm=q->front->data;
tmp = q->front;
itm = tmp->data;
q->front = tmp->next;
free(tmp);
return itm;
}
void push(int val)
{
struct queue tmp;
int j;
qadd(&q2, val);
while (((&q1)->front) != NULL)
{
j = qdel(&q1);
qadd(&q2, j);
}
tmp = q1;
q1 = q2;
q2 = tmp;
printf("\nelements after pushing are:\n");
displayFunction(&q1);
}
void pop()
{
printf("\n element deleted is %d", qdel(&q1));
}
|
C
|
/*
* ds3231.c
*
* Created on: Oct 27, 2014
* Author: lim
*/
#include "ds3231.h"
#include "i2c.h"
#define DS13xx_I2C_ADDRESS 0x68
TTime ttime(uint8_t hour, uint8_t min, uint8_t sec) {
TTime result;
result.sec = sec;
result.min = min;
result.hour = hour;
return result;
}
TDate tdate(uint8_t weekday, uint8_t day, uint8_t month, uint8_t year) {
TDate result;
result.weekday = weekday;
result.day = day;
result.month = month;
result.year = year;
return result;
}
uint8_t ds3231_settime(TTime time, uint8_t bcd) {
uint8_t res = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(0);
TTime wtime = time;
if (bcd == 0) {
wtime.sec = bintodec(wtime.sec);
wtime.min = bintodec(wtime.min);
wtime.hour = bintodec(wtime.hour);
}
res |= i2c_write(wtime.sec);
res |= i2c_write(wtime.min);
res |= i2c_write(wtime.hour);
i2c_stop();
}
return res;
}
uint8_t ds3231_gettime(TTime *time, uint8_t bcd) {
uint8_t res = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(0);
res |= i2c_start((DS13xx_I2C_ADDRESS << 1) | 0x01);
time->sec = i2c_readAck();
time->min = i2c_readAck();
time->hour = i2c_readNak();
if (bcd == 0) {
time->sec = dectobin(time->sec);
time->min = dectobin(time->min);
time->hour = dectobin(time->hour);
}
i2c_stop();
}
return res;
}
uint8_t ds3231_setdate(TDate date, uint8_t bcd) {
uint8_t res = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(3);
TDate wdate = date;
if (bcd == 0) {
wdate.day = bintodec(wdate.day);
wdate.month = bintodec(wdate.month);
wdate.year = bintodec(wdate.year);
}
res |= i2c_write(wdate.weekday);
res |= i2c_write(wdate.day);
res |= i2c_write(wdate.month);
res |= i2c_write(wdate.year);
i2c_stop();
}
return res;
}
uint8_t ds3231_getdate(TDate *date, uint8_t bcd) {
uint8_t res = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(3);
res |= i2c_start((DS13xx_I2C_ADDRESS << 1) | 0x01);
date->weekday = i2c_readAck();
date->day = i2c_readAck();
date->month = i2c_readAck();
date->year = i2c_readNak();
if (bcd == 0) {
date->day = dectobin(date->day);
date->month = dectobin(date->month);
date->year = dectobin(date->year);
}
i2c_stop();
}
return res;
}
uint8_t ds3231_gettemperature(TTemperature *temperature, uint8_t bcd) {
uint8_t res = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(0x11);
res |= i2c_start((DS13xx_I2C_ADDRESS << 1) | 0x01);
temperature->intPart = i2c_readAck();
temperature->fracPart = i2c_readNak();
if (bcd != 0) {
temperature->intPart = bintodec(temperature->intPart);
temperature->fracPart = bintodec(temperature->fracPart);
}
i2c_stop();
}
return res;
}
uint8_t ds3231_readbyte(uint8_t addr) {
uint8_t res = 0;
uint8_t result = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(addr);
res |= i2c_start((DS13xx_I2C_ADDRESS << 1) | 0x01);
result = i2c_readNak();
i2c_stop();
}
return result;
}
uint8_t ds3231_writebyte(uint8_t addr, uint8_t byte) {
uint8_t res = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(addr);
res |= i2c_write(byte);
i2c_stop();
}
return res;
}
uint8_t ds3231_readbytes(uint8_t addr, void *dst, uint8_t count) {
uint8_t res = 0;
if (count>0) {
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(addr);
res |= i2c_start((DS13xx_I2C_ADDRESS << 1) | 0x01);
uint8_t *dest = dst;
uint8_t i;
for (i = 0; i < count-1; i++) {
dest[i] = i2c_readAck();
}
dest[i] = i2c_readNak();
i2c_stop();
}
}
return res;
}
uint8_t ds3231_writebytes(uint8_t addr, void *src, uint8_t count) {
uint8_t res = 0;
res = i2c_start(DS13xx_I2C_ADDRESS << 1);
if (res == 0) {
res |= i2c_write(addr);
uint8_t *source = src;
for (uint8_t i = 0; i < count-1; i++) {
res |= i2c_write(source[i]);
}
i2c_stop();
}
return res;
}
uint8_t dectobin(uint8_t dec) {
uint8_t bin = (dec & 0x0F) + ((dec & 0xF0) >> 4) * 10;
return bin;
}
uint8_t bintodec(uint8_t bin) {
uint8_t dec = (bin % 10) + (((bin / 10) % 10) * 16);
return dec;
}
uint16_t timetoseconds(TTime time) {
int16_t result = dectobin(time.sec) + dectobin(time.min)*60 + dectobin(time.hour)*3600;
return result;
}
void secondstotime(uint16_t seconds, TTime *time) {
uint8_t sec = seconds % 60;
uint8_t min = (seconds / 60) % 60;
uint8_t hour = seconds / 3600;
time->sec = bintodec(sec);
time->min = bintodec(min);
time->hour = bintodec(hour);
}
|
C
|
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "randfile.h"
void printbar(){
printf("============================================================================\n");
}
// A main function that:
// Populates an array with 10 random numbers generated by your random function (print out each value)
// If your program seems to stall at this step, it's possible that your computer doesn't have enough entropy and is waiting, you can read from /dev/urandom instead.
// Writes the array to a file
// Do not use a loop when writing to the file
// Reads that file into a different array
// Do not use a loop when reading from the file
// Prints out the contents of the second array to verify the random numbers are the same from step 1
// Remember to use good practices, like checking return values for errors
// Also remember to include a makefile that includes a separate run target
int main(){
printbar();
printf("Testing rand\n");
printbar();
int result = open("randResult.txt", O_CREAT | O_RDWR, 0664); //opens and creates the file
// printf("result: %d\n", result);
if (result < 0)
{
// ERROR in opening
printf("Open in main.c errno %d error: %s\n", errno, strerror(errno));
return 0;
}
int rnd[11];
int i; //counter
for(i = 0; i < 10; i++){
rnd[i] = rand();
printf("Random #%d: %d\n", i, rnd[i]);
}
printbar();
printf("Writing numbers to file...\n");
int fd = write(result, rnd, sizeof(rnd));
// printf("fd: %d | sizeof(buff): %d\n", fd, sizeof(rnd));
if (fd < 0)
{
// ERROR in writing
printf("Write in main.c errno %d error: %s\n", errno, strerror(errno));
return 0;
}
close(result);
result = open("randResult.txt", O_RDONLY, 0664); //opens and creates the file
printbar();
printf("Reading numbers from file...\n");
int buff[11];
fd = read(result, buff, sizeof(buff));
// printf("fd: %d | sizeof(buff): %d\n", fd, sizeof(buff));
if (fd < 0)
{
// ERROR in reading
printf("Read in main.c errno %d error: %s\n", errno, strerror(errno));
return 0;
}
printf("Verification that written values were the same:\n");
for(i = 0; i < 10; i++){
printf("Random #%d: %d\n", i, buff[i]);
}
// printf("result: %d\n", result);
close(result);
return 0;
}
|
C
|
#include<stdio.h>
int fib ()
{ int num;
int a = 0 , b = 1 ;
printf("Enter the number of terms");
scanf("%d", &num);
printf("%d %d ",a,b);
for(int i = 2 ; i < num ; i++)
{
int m;
m = a + b ;
printf("%d\t",m);
a = b ;
b = m ;
}
}
int main()
{
fib();
}
|
C
|
//实验三 预测分析法
#include <stdio.h>
char ch[20]; //存储输入串
char sign[20]; //符号栈
int digit[20]; //数字栈
int topsign; //符号栈顶指针
int topdigit; //数字栈顶指针
int table[7][7]={{1,1,-1,-1,-1,-1,1}, //二维算符优先关系表
{1,1,-1,-1,-1,-1,1},
{1,1,1,1,-1,-1,1},
{1,1,1,1,-1,-1,1},
{-1,-1,-1,-1,-1,-1,2},
{1,1,1,1,2,1,1},
{-1,-1,-1,-1,-1,-1,0}};
void error(){
printf("error!\n");
}
void output(){
printf("ans=%d\n",digit[topdigit]);
}
int change(char ch){ //将符号变成算符优先关系表里的下标
switch(ch){
case '+':return 0;
break;
case '-':return 1;
break;
case '*':return 2;
break;
case '/':return 3;
break;
case '(':return 4;
break;
case ')':return 5;
break;
case'#':return 6;
break;
default:error();
break;
}
}
void operate(char c){ //归约并计算的函数
int temp;
switch(c){
case '+':temp=digit[topdigit-1]+digit[topdigit];
topdigit--;
digit[topdigit]=temp;
topsign--;
break;
case '-':digit[topdigit-1]=digit[topdigit-1]-digit[topdigit];
topdigit--;
topsign--;
break;
case '*':digit[topdigit-1]=digit[topdigit-1]*digit[topdigit];
topdigit--;
topsign--;
break;
case '/':digit[topdigit-1]=digit[topdigit-1]/digit[topdigit];
topdigit--;
topsign--;
break;
case ')':topsign--;
temp=sign[topsign];
switch(temp){
case '+':digit[topdigit-1]=digit[topdigit-1]+digit[topdigit];
topdigit--;
topsign--;
break;
case '-':digit[topdigit-1]=digit[topdigit-1]-digit[topdigit];
topdigit--;
topsign--;
break;
case '*':digit[topdigit-1]=digit[topdigit-1]*digit[topdigit];
topdigit--;
topsign--;
break;
case '/':digit[topdigit-1]=digit[topdigit-1]/digit[topdigit];
topdigit--;
topsign--;
break;
}
}
}
void main(){
char a,b,c;
int i=0,m,n;
printf("本程序仅能完成单位数输入的简单四则运算!\n");
printf("本程序利用算符优先分析法归约过程进行计算!\n");
printf("算符优先分析表如下:\n");
printf("\t+\t-\t*\t/\t(\t)\t#\n");
printf("+\t>\t>\t<\t<\t<\t<\t>\n");
printf("-\t>\t>\t<\t<\t<\t<\t>\n");
printf("*\t>\t>\t>\t>\t<\t<\t>\n");
printf("/\t>\t>\t>\t>\t<\t<\t>\n");
printf("(\t<\t<\t<\t<\t<\t<\t\n");
printf(")\t>\t>\t>\t>\t\t>\t>\n");
printf("#\t<\t<\t<\t<\t<\t<\t=\n");
printf("请输入符号串(以‘#’符结束):\n");
while((c=getchar())!='#'){
ch[i]=c;
i++;
}
ch[i]='#';
i=0;
sign[0]='#';
digit[0]='#';
topsign=0;
topdigit=0;
b=ch[i++];
while(b!='#'){
if((b!='+')&&(b!='-')&&(b!='*')&&(b!='/')&&(b!='(')&&(b!=')')){ //数字直接入数字栈
topdigit=topdigit+1;
digit[topdigit]=b-'0';
b=ch[i++];
}
else{
a=sign[topsign]; //当前符号栈栈顶符号
m=change(a); //转换为下标
n=change(b);
if(table[m][n]==-1){ //当前符号栈栈顶符号不优先于待入栈符号,则符号入栈
topsign=topsign+1;
sign[topsign]=b;
b=ch[i++];
}
else if(table[m][n]==0||1){ //否则进行归约并进行计算
operate(sign[topsign]);
topsign++;
sign[topsign]=b;
b=ch[i++];
}
}
}
operate(sign[topsign]);
output();
}
|
C
|
#include <stdio.h>
#define MAX_DEM 3
double a[MAX_DEM][MAX_DEM],b[MAX_DEM],y[MAX_DEM];
void matrix_generator(){
int i,j;
srand(time(NULL));
for(i=0;i<MAX_DEM;++i){
for(j=0;j<MAX_DEM;++j){
a[i][j] = rand()/RAND_MAX*10+1;
}
}
for(i=0;i<MAX_DEM;++i)
b[i] = rand()/RAND_MAX*10+1;
}
void print_matrix(){
for(i=0;i<MAX_DEM;++i){
for(j=0;j<MAX_DEM;++j){
printf("%g.6 ",a[i][j]);
}
printf("%g.6 \n",y[i]);
}
}
int main() {
int i,k,j;
matrix_generator();
for(k=0;k<MAX_DEM;++k){
y[k]=b[k]/a[k][k];
for (j= k + 1 ;j<MAX_DEM;++j){
A[k, j] = A[k, j]/A[k, k]; /* Division step */
for (i = k + 1 ;i<MAX_DEM;++i)
A[i ][j] = A[i][j] - A[i][k] * A[k][ j]; /* Elimination step */
b[j] = b[j]- A[j][ k]*y[k]; //存疑
A[j][ k] = 0;
}
A[k][ k] = 1;
}
print_matrix();
return 0;
}
|
C
|
#pragma once
// This macro exisst so that the cpu and dissassembler can make use of the same
// op switch statment
#define DECODE(op) \
{ \
switch (op) \
{ \
/*loads*/ \
case 0xa1: IndexedIndirectX(); lda(); break; \
case 0xa5: ZeroPage(); lda(); break; \
case 0xa9: Immediate(); lda(); break; \
case 0xad: Absolute(); lda(); break; \
case 0xb1: IndirectIndexedY(); lda(); break; \
case 0xb5: ZeroPageX(); lda(); break; \
case 0xb9: AbsoluteY(); lda(); break; \
case 0xbd: AbsoluteX(); lda(); break; \
\
case 0xa2: Immediate(); ldx(); break; \
case 0xa6: ZeroPage(); ldx(); break; \
case 0xb6: ZeroPageY(); ldx(); break; \
case 0xae: Absolute(); ldx(); break; \
case 0xbe: AbsoluteY(); ldx(); break; \
\
case 0xa0: Immediate(); ldy(); break; \
case 0xa4: ZeroPage(); ldy(); break; \
case 0xb4: ZeroPageX(); ldy(); break; \
case 0xac: Absolute(); ldy(); break; \
case 0xbc: AbsoluteX(); ldy(); break; \
\
/*stores*/ \
case 0x85: ZeroPage(); sta(); break; \
case 0x95: ZeroPageX(); sta(); break; \
case 0x8d: Absolute(); sta(); break; \
case 0x9d: AbsoluteX(); sta(); break; \
case 0x99: AbsoluteY(); sta(); break; \
case 0x81: IndexedIndirectX(); sta(); break; \
case 0x91: IndirectIndexedY(); sta(); break; \
\
case 0x86: ZeroPage(); stx(); break; \
case 0x96: ZeroPageY(); stx(); break; \
case 0x8e: Absolute(); stx(); break; \
\
case 0x84: ZeroPage(); sty(); break; \
case 0x94: ZeroPageX(); sty(); break; \
case 0x8c: Absolute(); sty(); break; \
\
/*arithmetic*/ \
case 0x69: Immediate(); adc(); break; \
case 0x65: ZeroPage(); adc(); break; \
case 0x75: ZeroPageX(); adc(); break; \
case 0x6d: Absolute(); adc(); break; \
case 0x7d: AbsoluteX(); adc(); break; \
case 0x79: AbsoluteY(); adc(); break; \
case 0x61: IndexedIndirectX(); adc(); break; \
case 0x71: IndirectIndexedY(); adc(); break; \
\
case 0xe9: Immediate(); sbc(); break; \
case 0xe5: ZeroPage(); sbc(); break; \
case 0xf5: ZeroPageX(); sbc(); break; \
case 0xed: Absolute(); sbc(); break; \
case 0xfd: AbsoluteX(); sbc(); break; \
case 0xf9: AbsoluteY(); sbc(); break; \
case 0xe1: IndexedIndirectX(); sbc(); break; \
case 0xf1: IndirectIndexedY(); sbc(); break; \
\
/*comparisons*/ \
case 0xc9: Immediate(); cmp(); break; \
case 0xc5: ZeroPage(); cmp(); break; \
case 0xd5: ZeroPageX(); cmp(); break; \
case 0xcd: Absolute(); cmp(); break; \
case 0xdd: AbsoluteX(); cmp(); break; \
case 0xd9: AbsoluteY(); cmp(); break; \
case 0xc1: IndexedIndirectX(); cmp(); break; \
case 0xd1: IndirectIndexedY(); cmp(); break; \
\
case 0xe0: Immediate(); cpx(); break; \
case 0xe4: ZeroPage(); cpx(); break; \
case 0xec: Absolute(); cpx(); break; \
\
case 0xc0: Immediate(); cpy(); break; \
case 0xc4: ZeroPage(); cpy(); break; \
case 0xcc: Absolute(); cpy(); break; \
\
/*bitwise operations*/ \
case 0x29: Immediate(); and(); break; \
case 0x25: ZeroPage(); and(); break; \
case 0x35: ZeroPageX(); and(); break; \
case 0x2d: Absolute(); and(); break; \
case 0x3d: AbsoluteX(); and(); break; \
case 0x39: AbsoluteY(); and(); break; \
case 0x21: IndexedIndirectX(); and(); break; \
case 0x31: IndirectIndexedY(); and(); break; \
\
case 0x09: Immediate(); ora(); break; \
case 0x05: ZeroPage(); ora(); break; \
case 0x15: ZeroPageX(); ora(); break; \
case 0x0d: Absolute(); ora(); break; \
case 0x1d: AbsoluteX(); ora(); break; \
case 0x19: AbsoluteY(); ora(); break; \
case 0x01: IndexedIndirectX(); ora(); break; \
case 0x11: IndirectIndexedY(); ora(); break; \
\
case 0x49: Immediate(); eor(); break; \
case 0x45: ZeroPage(); eor(); break; \
case 0x55: ZeroPageX(); eor(); break; \
case 0x4d: Absolute(); eor(); break; \
case 0x5d: AbsoluteX(); eor(); break; \
case 0x59: AbsoluteY(); eor(); break; \
case 0x41: IndexedIndirectX(); eor(); break; \
case 0x51: IndirectIndexedY(); eor(); break; \
\
case 0x24: ZeroPage(); bit(); break; \
case 0x2c: Absolute(); bit(); break; \
\
/*shifts and rotates*/ \
case 0x2a: Accumulator(); rol(); break; \
case 0x26: ZeroPage(); rol(); break; \
case 0x36: ZeroPageX(); rol(); break; \
case 0x2e: Absolute(); rol(); break; \
case 0x3e: AbsoluteX(); rol(); break; \
\
case 0x6a: Accumulator(); ror(); break; \
case 0x66: ZeroPage(); ror(); break; \
case 0x76: ZeroPageX(); ror(); break; \
case 0x6e: Absolute(); ror(); break; \
case 0x7e: AbsoluteX(); ror(); break; \
\
case 0x0a: Accumulator(); asl(); break; \
case 0x06: ZeroPage(); asl(); break; \
case 0x16: ZeroPageX(); asl(); break; \
case 0x0e: Absolute(); asl(); break; \
case 0x1e: AbsoluteX(); asl(); break; \
\
case 0x4a: Accumulator(); lsr(); break; \
case 0x46: ZeroPage(); lsr(); break; \
case 0x56: ZeroPageX(); lsr(); break; \
case 0x4e: Absolute(); lsr(); break; \
case 0x5e: AbsoluteX(); lsr(); break; \
\
/*increments and decrements*/ \
case 0xe6: ZeroPage(); inc(); break; \
case 0xf6: ZeroPageX(); inc(); break; \
case 0xee: Absolute(); inc(); break; \
case 0xfe: AbsoluteX(); inc(); break; \
\
case 0xc6: ZeroPage(); dec(); break; \
case 0xd6: ZeroPageX(); dec(); break; \
case 0xce: Absolute(); dec(); break; \
case 0xde: AbsoluteX(); dec(); break; \
\
case 0xe8: inx(); break; \
case 0xca: dex(); break; \
case 0xc8: iny(); break; \
case 0x88: dey(); break; \
\
/*register moves*/ \
case 0xaa: tax(); break; \
case 0xa8: tay(); break; \
case 0x8a: txa(); break; \
case 0x98: tya(); break; \
case 0x9a: txs(); break; \
case 0xba: tsx(); break; \
\
/*flag operations*/ \
case 0x18: clc(); break; \
case 0x38: sec(); break; \
case 0x58: cli(); break; \
case 0x78: sei(); break; \
case 0xb8: clv(); break; \
case 0xd8: cld(); break; \
case 0xf8: sed(); break; \
\
/*branches*/ \
case 0x10: bpl(); break; \
case 0x30: bmi(); break; \
case 0x50: bvc(); break; \
case 0x70: bvs(); break; \
case 0x90: bcc(); break; \
case 0xb0: bcs(); break; \
case 0xd0: bne(); break; \
case 0xf0: beq(); break; \
\
case 0x4c: jmp(); break; \
case 0x6c: jmpi(); break; \
\
/*procedure calls*/ \
case 0x20: jsr(); break; \
case 0x60: rts(); break; \
case 0x00: brk(); break; \
case 0x40: rti(); break; \
\
/*stack operations*/ \
case 0x48: pha(); break; \
case 0x68: pla(); break; \
case 0x08: php(); break; \
case 0x28: plp(); break; \
\
/*no operation*/ \
case 0xea: nop(); break; \
\
default: \
printf("Unimplemented instruction: 0x%02x\n", op); \
__debugbreak(); \
} \
}
|
C
|
#include <stdio.h>
main ()
{
float valor_metros, valor_centimentros;
printf("Insira o valor em metros = ");
scanf("%f", &valor_metros);
valor_centimentros = (valor_metros * 100);
printf("O valor em centmetros = %.2f", valor_centimentros);
return(0);
}
|
C
|
// ---- Definitions for tree traversal examples ----
#include <vcc.h>
#include <stdlib.h>
typedef
/*D_tag b_node */
struct b_node {
struct b_node * left;
struct b_node * right;
int key;
} BNode;
typedef
/*D_tag l_node */
struct l_node {
struct l_node * next;
int key;
} LNode;
/*D_defs
define pred sorted^(x):
(
((x l= nil) & emp) |
((x |-> loc next: nxt; int value: ky) *
(sorted^(nxt) & (ky le-set list-keys^(nxt)))
)
) ;
define set-fun list-keys^(x):
(case (x l= nil): emptyset;
case ((x |-> loc next: nxt; int value: ky) * true):
((singleton ky) union list-keys^(nxt));
default: emptyset
) ;
define pred bst^(x):
( ((x l= nil) & emp) |
((x |-> loc left: lft; loc right: rgt; int key: ky)
* ((bst^(lft) & (bst-keys^(lft) set-le ky))
* (bst^(rgt) & (ky le-set bst-keys^(rgt)))))
);
define set-fun bst-keys^(x):
(case (x l= nil): emptyset;
case ((x |-> loc left: lft; loc right: rgt; int key: ky) * true):
((singleton ky) union (bst-keys^(lft) union bst-keys^(rgt)));
default: emptyset
) ;
*/
// --------------------------------------------------
_(dryad)
LNode * tree2list_rec(BNode * t, LNode * l)
/*D_requires ((bst^(t) * sorted^(l)) & (bst-keys^(t) le list-keys^(l))) */
/*D_ensures (sorted^(ret) & (list-keys^(ret) s= (old(bst-keys^(t)) union old(list-keys^(l))))) */
{
if (t == NULL) {
return l;
} else {
LNode * lnode = (LNode *) malloc(sizeof(LNode));
_(assume lnode != NULL)
int tkey = t->key;
lnode->key = tkey;
lnode->next = NULL;
BNode * tright = t->right;
BNode * tleft = t->left;
LNode * tmp_list1 = tree2list_rec(tright, l);
lnode->next = tmp_list1;
free(t);
LNode * tmp_list2 = tree2list_rec(tleft, lnode);
return tmp_list2;
}
}
|
C
|
#include <stdio.h>
#include <Windows.h>
#include <Shlwapi.h>
#include "builder.h"
#include "exec.h"
#include "getopt.h"
#include "helper.h"
#include "rc4.h"
#define DEFAULT_NAME "out.exe"
#pragma comment(lib, "Shlwapi.lib")
void PrintHelp(LPSTR self) {
PathStripPath(self);
printf(
"Usage:\n"
"\t%s [-p <PAYLOAD PATH> [-o <OUT FILE NAME]]\n\n"
"Example:\n"
"\t%s -p mypayload.exe\n"
"\t%s -p mypayload.exe -o loader.exe\n\n",
self,
self,
self
);
}
/*
* Usage %s [-p <EXE PAYLOAD PATH> [-o <OUT FILE NAME>]]
*/
int main(int argc, char *argv[]) {
if (argc == 1) {
// Do the magics.
if (!Execute()) {
PRINT_ERROR("The program terminated unsuccessfully.\n");
return 1;
}
PRINT_SUCCESS("The program terminated successfully.\n");
return 0;
} else {
if (argc >= 3 || argc >= 5) {
BOOL bRet = FALSE;
int c = 0;
LPCSTR szPayloadPath = NULL;
LPCSTR szNewFileName = DEFAULT_NAME;
while ((c = getopt(argc, argv, "p:o:")) != -1) {
switch (c) {
case 'h':
PrintHelp(argv[0]);
return 0;
case 'p':
szPayloadPath = optarg;
break;
case 'o':
szNewFileName = optarg;
break;
case '?':
PRINT_WARNING("Unknown option: \"-%c\"\n", optopt);
break;
default:
break;
}
}
// Check mandatory payload argument.
if (argc < 5 && szPayloadPath == NULL) {
PRINT_ERROR("Payload argument must exist.\n");
return 1;
}
PRINT_INFO("Building payload...\n");
PRINT_INFO(
"Out file name: \"%s\"\n",
szNewFileName
);
PRINT_INFO("Payload: \"%s\"\n",
szPayloadPath
);
bRet = BuildLoader(szNewFileName, szPayloadPath);
if (!bRet) {
PRINT_ERROR("The program terminated unsuccessfully.\n");
return 1;
} else {
PRINT_SUCCESS("The program terminated successfully.\n");
return 0;
}
}
}
PrintHelp(argv[0]);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
int n;
int* ptr;
scanf("%d", &n);
ptr = (int*) malloc(sizeof(int) *n);
for (int i = 0; i < n; i++)
{
scanf("%d", &ptr[i]);
}
FILE* fptr;
fptr = fopen("squares.txt", "w");
for (int i = n - 1 ; i >= 0; i--)
{
fprintf(fptr,"%d %d\n",ptr[i], ptr[i] * ptr[i] );
}
}
|
C
|
#include "types.h"
#include "user.h"
// xv6 provides spin locks only for the kernel modules
// this is userland implementation of spinlocks
// The module alos provides implementation of semphores using sping locks
// ==================== USERLAND SPINLOCKS ===================================
void init_splock(splock *s) {
s->locked = 0;
}
// The code has be taken as it is from xv6 kernel (for implementing userland spin locks)
// atomic test and set hardware based instruction
static inline uint
xchg(volatile uint *addr, uint newval)
{
uint result;
// The + in "+m" denotes a read-modify-write operand.
asm volatile("lock; xchgl %0, %1" :
"+m" (*addr), "=a" (result) :
"1" (newval) :
"cc");
return result;
}
// aquire a userland spin lock
void
acquire_splock(splock *s)
{
// The xchg is atomic.
while(xchg(&(s->locked), 1) != 0)
;
return;
}
// relase a userland spin lock
void
release_splock(splock *s)
{
__sync_synchronize();
// release the lock, equivalent to lk->locked = 0.
// this code can't use a c assignment, since it might
// not be atomic. a real os would use c atomics here.
asm volatile("movl $0, %0" : "+m" (s->locked) : );
return;
}
// ===================== QUEUE DATA STRUCTURE ================================
void
init_queue(queue *q)
{
q->front = q->rear = 0;
}
int
isempty(queue q)
{
return q.front == q.rear;
}
int
enqueue(queue *q, int value)
{
if((q->front + 1) % MAX_QUEUE_SIZE == q->rear){
return -1;
}
q->arr[q->front] = value;
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return 0;
}
int
dequeue(queue *q)
{
if(q->front == q->rear){
return -1;
}
int value = q->arr[q->rear];
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
return value;
}
// ========================== SEMAPHORE =====================================
void
semaphore_init(semaphore *s, int initval)
{
s->val = initval;
init_queue(&(s->q));
init_splock(&(s->sl));
}
void
semaphore_wait(semaphore *s)
{
acquire_splock(&(s->sl));
s->val--;
while(s->val < 0){
block(s);
}
release_splock(&(s->sl));
}
void
semaphore_signal(semaphore *s)
{
acquire_splock(&(s->sl));
s->val++;
if(!isempty(s->q)){
tresume(dequeue(&(s->q)));
}
release_splock(&(s->sl));
}
void
block(semaphore *s)
{
enqueue(&(s->q), gettid());
release_splock(&(s->sl));
// make the thread sleep
tsuspend();
acquire_splock(&(s->sl));
}
|
C
|
#include "fractol.h"
int color_in_int(t_color *color)
{
return ((color->r << 16) + (color->g << 8) + (color->b));
}
void modif_color(t_color *color)
{
color->r = rand() % 255;
color->g = rand() % 255;
color->b = rand() % 255;
}
void choose_color(t_color *color, int r, int g, int b)
{
color->r = r;
color->g = g;
color->b = b;
}
|
C
|
/* Inclusions */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[]) {
int n,z,l;
unsigned int offset,i;
if (argc < 3)
{
fprintf(stderr, "Usage: %s <file_name> <offset>\n", argv[0]);
exit(1);
}
f=open(argv[1],O_RDONLY);
if (f == -1)
{
perror("Opening file fails!\n");
exit(2);
}
i = (unsigned int) strtol(argv[1],NULL,16);
offset = i * sizeof(int);
l = lseek(f,offset,SEEK_SET);
if (l == -1)
{
perror("fseek fails!\n");
exit(3);
}
n = read(f,buf,sizeof(int));
if (n < sizeof(int))
{
printf("Nothing to read.\n");
exit(4);
}
else {
printf("The number at offset %ld is 0%08x --> %d\n",i,z,n);
}
close(f);
exit(0);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
int main(void){
int n[30]={}, num, i;
for(i=0; i<28; i++){
scanf("%d",&num);
n[num-1] = num;
}
for(i=0; i<30; i++){
if(n[i] == 0)
printf("%d\n",i+1);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct PAIR
{
int i;
int j;
int k;
} PAIR;
PAIR ** sols = NULL;
int n_sols = 0;
void check_err(void* a)
{
if(a == NULL)
{
printf("Not enough memory!\n");
exit(1);
}
}
int isMazeLine(char* s, int n)
{
for(int i = 0; i < n; i++)
{
if(strchr("#.", s[i]) == NULL)
{
return 0;
}
}
return 1;
}
void init_maze(char ****maze, PAIR *maze_dim)
{
*maze_dim = (PAIR){5, 5, 3};
char temp_arr[3][5][5] = {
{
"#####",
"#####",
"#####",
"#.###",
"#####",
},
{
"#####",
"#...#",
"#...#",
"#...#",
"#####",
},
{
"#####",
"###.#",
"#####",
"#####",
"#####",
},
};
// Dinamically allocate the 3D maze
*maze = malloc(maze_dim->k * sizeof(char**));
check_err(*maze);
for(int k = 0; k < maze_dim->k; k++)
{
(*maze)[k] = malloc(maze_dim->i * sizeof(char*));
check_err((*maze)[k]);
for(int i = 0; i < maze_dim->i; i++)
{
(*maze)[k][i] = strdup(temp_arr[k][i]);
check_err((*maze)[k][i]);
}
}
}
int find_optimal_path(PAIR curr, char*** maze, PAIR m_size, int step)
{
// Check if start is empty
if(maze[curr.k][curr.i][curr.j] != '.')
{
printf("Function should only be called on empty coords!\n");
exit(1);
}
// If solution is found
if(curr.i + 1 == m_size.i || curr.i == 0 ||
curr.j + 1 == m_size.j || curr.j == 0 ||
curr.k + 1 == m_size.k || curr.k == 0 )
{
return step;
}
// Mark tile with X and add it to the path
maze[curr.k][curr.i][curr.j] = 'X';
int stuck = 1;
int minimum = -1;
if(maze[curr.k][curr.i + 1][curr.j] == '.')
{
// Top tile
int ret_val = find_optimal_path((PAIR){curr.i + 1, curr.j, curr.k}, maze, m_size, step + 1);
if(ret_val != -1)
{
stuck = 0;
if(minimum == -1)
{
minimum = ret_val;
}else if(minimum > ret_val)
{
minimum = ret_val;
}
}
}
if(maze[curr.k][curr.i - 1][curr.j] == '.')
{
// Bottom tile
int ret_val = find_optimal_path((PAIR){curr.i - 1, curr.j, curr.k}, maze, m_size, step + 1);
if(ret_val != -1)
{
stuck = 0;
if(minimum == -1)
{
minimum = ret_val;
}else if(minimum > ret_val)
{
minimum = ret_val;
}
}
}
if(maze[curr.k][curr.i][curr.j + 1] == '.')
{
// Right tile
int ret_val = find_optimal_path((PAIR){curr.i, curr.j + 1, curr.k}, maze, m_size, step + 1);
if(ret_val != -1)
{
stuck = 0;
if(minimum == -1)
{
minimum = ret_val;
}else if(minimum > ret_val)
{
minimum = ret_val;
}
}
}
if(maze[curr.k][curr.i][curr.j - 1] == '.')
{
// Left tile
int ret_val = find_optimal_path((PAIR){curr.i, curr.j - 1, curr.k}, maze, m_size, step + 1);
if(ret_val != -1)
{
stuck = 0;
if(minimum == -1)
{
minimum = ret_val;
}else if(minimum > ret_val)
{
minimum = ret_val;
}
}
}
if(maze[curr.k + 1][curr.i][curr.j] == '.')
{
// Above tile
int ret_val = find_optimal_path((PAIR){curr.i, curr.j, curr.k + 1}, maze, m_size, step + 1);
if(ret_val != -1)
{
stuck = 0;
if(minimum == -1)
{
minimum = ret_val;
}else if(minimum > ret_val)
{
minimum = ret_val;
}
}
}
if(maze[curr.k - 1][curr.i][curr.j] == '.')
{
// Below tile
int ret_val = find_optimal_path((PAIR){curr.i, curr.j, curr.k - 1}, maze, m_size, step + 1);
if(ret_val != -1)
{
stuck = 0;
if(minimum == -1)
{
minimum = ret_val;
}else if(minimum > ret_val)
{
minimum = ret_val;
}
}
}
// Delete the mark X
maze[curr.k][curr.i][curr.j] = '.';
if(stuck)
{
return -1;
}
return minimum;
}
void path_print(PAIR curr, char*** maze, PAIR m_size, int step, int minimum)
{
static PAIR curr_path[10000];
// Check if start is empty
if(maze[curr.k][curr.i][curr.j] != '.')
{
printf("Function should only be called on empty coords!\n");
exit(1);
}
// Add current path to the solution
curr_path[step] = curr;
// If solution is found
if(curr.i + 1 == m_size.i || curr.i == 0 ||
curr.j + 1 == m_size.j || curr.j == 0 ||
curr.k + 1 == m_size.k || curr.k == 0 )
{
// Skip over printing
if(step != minimum)
{
return;
}
// Print the path
for(int i = 0; i <= step; i++)
{
printf("(%d, %d, %d)->", curr_path[i].i, curr_path[i].j, curr_path[i].k);
}
printf("DONE\n");
return;
}
// If minimum smaller than step => return bc the min path can no longer be found
if(minimum <= step)
{
return;
}
// Mark tile with X and add it to the path
maze[curr.k][curr.i][curr.j] = 'X';
if(maze[curr.k][curr.i + 1][curr.j] == '.')
{
// Top tile
path_print((PAIR){curr.i + 1, curr.j, curr.k}, maze, m_size, step + 1, minimum);
}
if(maze[curr.k][curr.i - 1][curr.j] == '.')
{
// Bottom tile
path_print((PAIR){curr.i - 1, curr.j, curr.k}, maze, m_size, step + 1, minimum);
}
if(maze[curr.k][curr.i][curr.j + 1] == '.')
{
// Right tile
path_print((PAIR){curr.i, curr.j + 1, curr.k}, maze, m_size, step + 1, minimum);
}
if(maze[curr.k][curr.i][curr.j - 1] == '.')
{
// Left tile
path_print((PAIR){curr.i, curr.j - 1, curr.k}, maze, m_size, step + 1, minimum);
}
if(maze[curr.k + 1][curr.i][curr.j] == '.')
{
// Above tile
path_print((PAIR){curr.i, curr.j, curr.k + 1}, maze, m_size, step + 1, minimum);
}
if(maze[curr.k - 1][curr.i][curr.j] == '.')
{
// Below tile
path_print((PAIR){curr.i, curr.j, curr.k - 1}, maze, m_size, step + 1, minimum);
}
// Delete the mark X
maze[curr.k][curr.i][curr.j] = '.';
}
int main()
{
char ***maze = NULL;
PAIR maze_dim;
init_maze(&maze, &maze_dim);
int minimum = find_optimal_path((PAIR){2, 2, 1}, maze, maze_dim, 0);
path_print((PAIR){2, 2, 1}, maze, maze_dim, 0, minimum);
for(int k = 0; k < maze_dim.k; k++)
{
for(int i = 0; i < maze_dim.i; i++)
{
free(maze[k][i]);
}
free(maze[k]);
}
free(maze);
return 0;
}
|
C
|
#ifndef BOOK_H
#define BOOK_H
enum status {ENABLE_RENT, DISABLE_RENT};
typedef struct book {
char title[100];
char author[20];
char publisher[20];
char date[11];
char isbn[14];
enum status rentStatus;
} Book;
#endif
|
C
|
void check_arm(int x, int cj, int cd, int cs) {
if(x < 0) {
return;
}
int arm = x == cj * cj * cj + cd * cd * cd + cs * cs * cs;
if(arm) {
printf("DA");
} else {
printf("NE");
}
}
int main() {
int broj, cj, cd, cs;
scanf("%d", &broj);
cj = broj % 10;
cd = (broj / 10) % 10;
cs = (broj / 100) % 10;
check_arm(broj, cj, cd, cs);
return 0;
}
|
C
|
#include "lerr.h"
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* lerr_describe(enum lerr_code code) {
switch (code) {
case LERR_DEAD_REF: return "dead reference";
case LERR_AST: return "ast error";
case LERR_EVAL: return "evaluation error";
case LERR_DIV_ZERO: return "division by zero";
case LERR_BAD_SYMBOL: return "bad symbol";
case LERR_BAD_OPERAND: return "bad operand";
case LERR_TOO_MANY_ARGS: return "too many arguments";
case LERR_TOO_FEW_ARGS: return "too few arguments";
default: return "unknown error";
}
}
struct lerr* lerr_alloc(void) {
struct lerr* err = calloc(1, sizeof(struct lerr));
return err;
}
void lerr_free(struct lerr* err) {
if (!err) {
return;
}
if (err->inner) {
lerr_free(err->inner);
}
if (err->file) {
free(err->file);
}
free(err);
}
bool lerr_copy(struct lerr* dest, const struct lerr* src) {
if (!dest || !src) {
return false;
}
dest->code = src->code;
lerr_annotate(dest, src->message);
lerr_set_file(dest, src->file);
lerr_set_location(dest, src->line, src->col);
if (src->inner) {
dest->inner = lerr_alloc();
lerr_copy(dest->inner, src->inner);
}
return true;
}
struct lerr* lerr_throw_va(enum lerr_code code, const char* fmt, va_list va) {
struct lerr* err = lerr_alloc();
err->code = code;
lerr_annotate_va(err, fmt, va);
return err;
}
struct lerr* lerr_throw(enum lerr_code code, const char* fmt, ...) {
va_list va;
va_start(va, fmt);
struct lerr* err = lerr_throw_va(code, fmt, va);
va_end(va);
return err;
}
struct lerr* lerr_propagate(struct lerr* inner, const char* fmt, ...) {
va_list va;
va_start(va, fmt);
struct lerr* outer = lerr_throw_va(0, fmt, va);
va_end(va);
lerr_wrap(outer, inner);
return outer;
}
void lerr_annotate(struct lerr* err, const char* fmt, ...) {
if (!fmt || strlen(fmt) == 0) {
err->message[0] = '\0';
return;
}
va_list va;
va_start(va, fmt);
lerr_annotate_va(err, fmt, va);
va_end(va);
}
void lerr_annotate_va(struct lerr* err, const char* fmt, va_list va) {
if (!fmt || strlen(fmt) == 0) {
err->message[0] = '\0';
return;
}
vsnprintf(err->message, sizeof(err->message), fmt, va);
}
void lerr_set_file(struct lerr* err, const char* file) {
if (!err) {
return;
}
struct lerr* cause = lerr_cause(err);
if (cause->file) {
free(cause->file);
cause->file = NULL;
}
if (file) {
size_t len = strlen(file);
cause->file = malloc(len+1);
strncpy(cause->file, file, len+1);
}
}
void lerr_set_location(struct lerr* err, int line, int col) {
if (!err) {
return;
}
struct lerr* cause = lerr_cause(err);
cause->line = line;
cause->col = col;
}
void lerr_wrap(struct lerr* outer, struct lerr* inner) {
if (!outer || !inner || outer->inner) {
return;
}
outer->inner = inner;
}
struct lerr* lerr_cause(struct lerr* err) {
if (!err) {
return NULL;
}
while (err->inner) { err = err->inner; }
return err;
}
void lerr_print_marker_to(struct lerr* err, int indent, FILE* out) {
struct lerr* cause = lerr_cause(err);
int col = cause->col;
if (col) {
for (int i = -indent+1; i < col; i++) {
fputc(' ', out);
}
fputc('^', out);
fputc('\n', out);
}
}
void lerr_print_to(struct lerr* err, FILE* out) {
if (!err) {
return;
}
struct lerr* cause = lerr_cause(err);
if (cause->file)
{ fprintf(out, "<%s>:", cause->file); }
if (cause->line && cause->col)
{ fprintf(out, "%d:%d:", cause->line, cause->col); }
if (cause->code)
{ fprintf(out, "error #%d:", cause->code); }
while (err) {
fprintf(out, " %s", err->message);
err = err->inner;
}
fputs(".\n", out);
}
void lerr_print_cause_to(struct lerr* err, FILE* out) {
if (!err) {
return;
}
struct lerr* cause = lerr_cause(err);
fprintf(out, "Error: %s", cause->message);
}
|
C
|
//RAMREZ PALAO MANUEL
#include <stdio.h>
#include <ctype.h>
int main(){
char str[256];
char ch;
int j = 0;
printf("Ingresa una palabra a convertir en miniscula: ");
scanf("%s",str);
while (str[j]){
ch = str[j];
putchar(tolower(ch));
j++;
}
return 0;
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char*argv[]){
FILE * fd;
int c;
char* input;
int* tnt = {0,0};
char buf[1024];
scanf("%s",&input);
fd = fopen(input, "r");
if (fd){
while ((c = getc(fd)) != EOF){
}
fclose(fd);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.