language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*128. Descubra (e imprima) o valor da maior varivel do exerccio anterior, atravs da funo maior,
cujos parmetros devem ser as variveis ponteiros para m e n.*/
#include<stdio.h>
int maior(int *ptrm, int *ptrn){
if(*ptrm>*ptrn){
printf("\nM e o maior valor: ");
printf("%d", *ptrm);
}
if(*ptrn>*ptrm){
printf("\nN e o maior valor: ");
printf("%d", *ptrn);
}
if(*ptrn==*ptrm){
printf("\nOs valores sao iguais: %d e %d", *ptrm, *ptrn);
}
return 0;
}
int main(){
int m, n;
int *ptrm, *ptrn;
printf("Informe o valor de m:\n");
scanf("%d", &m);
ptrm=&m;
printf("Informe o valor de n:\n");
scanf("%d", &n);
ptrn=&n;
maior(ptrm, ptrn);
printf("\n%d %d", *ptrm, *ptrn);
return 0;
}
|
C
|
/**
˼·
ڡѵҪ¼вַͬĸ
룺ַͬ = ڵĿ C ͬ細ΪABCCA,BCĿֱΪ112,ͬĸΪ 4 C 2
Windows¼ǰиַӦĸ
MaxSame¼ǰͬĸ
MaxSameIndex¼ͬĸ±ꡣ
*/
#define MAX 256
#define GET_MAX(x, y) ((x) > y) ? (x) : (y)
int characterReplacement(char * s, int k)
{
int windows[MAX] = {0};
int diffNum = 0;
int left = 0;
int right;
int max = -1;
int maxSame = -1;
int maxSameIndex;
int len;
if (s == NULL) {
return 0;
}
len = strlen(s);
if (len == 0) {
return 0;
}
for (right = 0; right < len; right++) {
windows[s[right]]++;
// maxSame maxSameIndex
if (windows[s[right]] >= maxSame) {
maxSame = windows[s[right]];
maxSameIndex = right;
}
// ǰвͬĸĸ = ڳ - ظ
diffNum = (right - left + 1) - maxSame;
while (diffNum > k) {
// ɾȥIJԪأֱɾ
if (left != maxSameIndex) {
windows[s[left]]--;
left++;
diffNum = (right - left + 1) - maxSame;
} else {// ԪأmaxSame
maxSame--;
windows[s[left]]--;
left++;
diffNum = (right - left + 1) - maxSame;
}
}
//ǰĽΪͬ+ͬ
max = GET_MAX(max, maxSame + k);
}
// Ϊ˹ĸȫͬ
return max > len ? len : max;
}
|
C
|
#ifndef COZY_INTERPRETER_VARIABLE_REGISTER_H
#define COZY_INTERPRETER_VARIABLE_REGISTER_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "constants.h"
#include "string_operations.h"
#include "instruction.h"
typedef enum {
INT,
NOT_A_TYPE
} variable_type_t;
typedef struct nod {
int value;
bool defined;
struct nod * next_node[NUMBER_OF_LETTERS];
} node_t;
typedef node_t * variable_register_t;
int get_letter_code(char letter);
node_t * create_variable_register();
bool is_letter_code_proper_for_variable_name(int letter_code);
variable_register_t define_variable(variable_register_t variable_register, char *name, int line_number, instruction_tree_t instruction_tree);
variable_register_t set_val(variable_register_t variable_register, char *name, int val, int line_number, instruction_tree_t instruction_tree);
bool is_variable_name_forbidden(char *name);
bool is_variable_defined(variable_register_t variable_register, char *name, int line_number, instruction_tree_t instruction_tree);
int get_variable_val(variable_register_t variable_register, char *name, int line_number, instruction_tree_t instruction_tree);
variable_type_t detect_variable_type(char *name);
variable_register_t remove_variable_register(variable_register_t variable_register);
#endif //COZY_INTERPRETER_VARIABLE_REGISTER_H
|
C
|
#ifndef JAM_H
#define JAM_H
#include "boolean.h"
/* *** Definisi TYPE JAM <HH:MM:SS> *** */
typedef struct {
int HH; /* integer [0..23] */
int MM; /* integer [0..59] */
int SS; /* integer [0..59] */
} JAM;
/* *** Notasi Akses: selektor JAM *** */
#define Hour(J) (J).HH
#define Minute(J) (J).MM
#define Second(J) (J).SS
void TulisJAM (JAM J);
/* I.S. : J sembarang */
/* F.S. : Nilai J ditulis dg format HH:MM:SS */
/* Proses : menulis nilai setiap komponen J ke layar dalam format HH:MM:SS
tanpa karakter apa pun di depan atau belakangnya, termasuk spasi, enter, dll.*/
/* ***************************************************************** */
/* KELOMPOK KONVERSI TERHADAP TYPE */
/* ***************************************************************** */
long JAMToDetik (JAM J);
/* Diberikan sebuah JAM, mengkonversi menjadi jumlah detik dari pukul 0:0:0 */
/* Rumus : detik = 3600*HH + 60*MM + SS */
/* Nilai maksimum = 3600*23+59*60+59 */
JAM DetikToJAM (long N);
/* Mengirim konversi detik ke JAM */
/* Catatan: Jika N >= 86400, maka harus dikonversi dulu menjadi jumlah detik yang
mewakili jumlah detik yang mungkin dalam 1 hari, yaitu dengan rumus:
N1 = N mod 86400, baru N1 dikonversi menjadi JAM */
void IncrementJAM (JAM *J);
/* Jam akan diincrement dari setiap step yang dijalankan */
#endif
|
C
|
/* Copyright 2015 Codethink Ltd.
*
* 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 "ofc/sema.h"
#include <math.h>
const ofc_sema_typeval_t* ofc_sema_expr_constant(
const ofc_sema_expr_t* expr)
{
return (expr ? expr->constant : NULL);
}
bool ofc_sema_expr_is_constant(
const ofc_sema_expr_t* expr)
{
return (ofc_sema_expr_constant(expr) != NULL);
}
static const ofc_sema_type_t* OFC_SEMA_EXPR__LOGICAL_RETURN(
const ofc_sema_type_t* a,
const ofc_sema_type_t* b)
{
(void)a;
(void)b;
return ofc_sema_type_logical_default();
}
typedef enum
{
OFC_SEMA_EXPR__OP_TYPE_INVALID = 0,
OFC_SEMA_EXPR__OP_TYPE_ALLOW = 1,
OFC_SEMA_EXPR__OP_TYPE_WARN = 2,
} ofc_sema_expr__op_type_e;
typedef struct
{
/* We need to use a function pointer since we can't
statically define a type, it's also more flexible. */
const ofc_sema_type_t* (*rtype)(
const ofc_sema_type_t*,
const ofc_sema_type_t*);
ofc_sema_expr__op_type_e allow_logical;
ofc_sema_expr__op_type_e allow_integer;
ofc_sema_expr__op_type_e allow_real;
ofc_sema_expr__op_type_e allow_complex;
ofc_sema_expr__op_type_e allow_character;
bool promote;
} ofc_sema_expr__rule_t;
static ofc_sema_expr__rule_t ofc_sema_expr__rule[] =
{
{ NULL, 0, 0, 0, 0, 0, 0 }, /* CONSTANT */
{ NULL, 0, 0, 0, 0, 0, 0 }, /* LHS */
{ NULL, 0, 0, 0, 0, 0, 0 }, /* CAST */
{ NULL, 0, 0, 0, 0, 0, 0 }, /* INTRINSIC */
{ NULL, 0, 0, 0, 0, 0, 0 }, /* FUNCTION */
{ NULL, 0, 0, 0, 0, 0, 0 }, /* IMPLICIT_DO */
{ NULL, 0, 0, 0, 0, 0, 0 }, /* ARRAY */
{ NULL, 0, 0, 0, 0, 0, 0 }, /* RESHAPE */
{ NULL, 0, 1, 1, 1, 0, 0 }, /* POWER */
{ NULL, 0, 1, 1, 1, 0, 1 }, /* MULTIPLY */
{ NULL, 0, 0, 0, 0, 1, 0 }, /* CONCAT */
{ NULL, 0, 1, 1, 1, 0, 1 }, /* DIVIDE */
{ NULL, 0, 1, 1, 1, 0, 1 }, /* ADD */
{ NULL, 0, 1, 1, 1, 0, 1 }, /* SUBTRACT */
{ NULL, 0, 1, 1, 1, 0, 1 }, /* NEGATE */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 2, 1, 1, 1, 1, 1 }, /* EQ */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 2, 1, 1, 1, 1, 1 }, /* NE */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 2, 1, 1, 0, 2, 1 }, /* LT */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 2, 1, 1, 0, 2, 1 }, /* LE */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 2, 1, 1, 0, 2, 1 }, /* GT */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 2, 1, 1, 0, 2, 1 }, /* GE */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 1, 1, 0, 0, 0, 1 }, /* NOT */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 1, 1, 0, 0, 0, 1 }, /* AND */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 1, 1, 0, 0, 0, 1 }, /* OR */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 1, 1, 0, 0, 0, 1 }, /* XOR */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 1, 0, 0, 0, 0, 1 }, /* EQV */
{ OFC_SEMA_EXPR__LOGICAL_RETURN, 1, 0, 0, 0, 0, 1 }, /* NEQV */
};
static ofc_sema_expr__op_type_e ofc_sema_expr_type_allowed(
ofc_sema_expr_e etype,
const ofc_sema_type_t* type)
{
if (!type)
return OFC_SEMA_EXPR__OP_TYPE_INVALID;
if (etype >= OFC_SEMA_EXPR_COUNT)
return OFC_SEMA_EXPR__OP_TYPE_INVALID;
ofc_sema_expr__rule_t rule
= ofc_sema_expr__rule[etype];
if (rule.allow_logical
&& ofc_sema_type_is_logical(type))
return rule.allow_logical;
if (rule.allow_integer
&& ofc_sema_type_is_integer(type))
return rule.allow_integer;
if (rule.allow_real
&& (type->type == OFC_SEMA_TYPE_REAL))
return rule.allow_real;
if (rule.allow_complex
&& (type->type == OFC_SEMA_TYPE_COMPLEX))
return rule.allow_complex;
if (rule.allow_character
&& (type->type == OFC_SEMA_TYPE_CHARACTER))
return rule.allow_character;
return OFC_SEMA_EXPR__OP_TYPE_INVALID;
}
static ofc_sema_typeval_t* ofc_sema_typeval_negate__faux_binary(
const ofc_sema_typeval_t* a,
const ofc_sema_typeval_t* b)
{
(void)b;
return ofc_sema_typeval_negate(a);
}
static ofc_sema_typeval_t* ofc_sema_typeval_not__faux_binary(
const ofc_sema_typeval_t* a,
const ofc_sema_typeval_t* b)
{
(void)b;
return ofc_sema_typeval_not(a);
}
static ofc_sema_typeval_t* (*ofc_sema_expr__resolve[])(
const ofc_sema_typeval_t*,
const ofc_sema_typeval_t*) =
{
NULL, /* CONSTANT */
NULL, /* LHS */
NULL, /* CAST */
NULL, /* INTRINSIC */
NULL, /* FUNCTION */
NULL, /* IMPLICIT_DO */
NULL, /* ARRAY */
NULL, /* RESHAPE */
ofc_sema_typeval_power,
ofc_sema_typeval_multiply,
ofc_sema_typeval_concat,
ofc_sema_typeval_divide,
ofc_sema_typeval_add,
ofc_sema_typeval_subtract,
ofc_sema_typeval_negate__faux_binary,
ofc_sema_typeval_eq,
ofc_sema_typeval_ne,
ofc_sema_typeval_lt,
ofc_sema_typeval_le,
ofc_sema_typeval_gt,
ofc_sema_typeval_ge,
ofc_sema_typeval_not__faux_binary,
ofc_sema_typeval_and,
ofc_sema_typeval_or,
ofc_sema_typeval_xor,
ofc_sema_typeval_eqv,
ofc_sema_typeval_neqv,
};
static ofc_sema_expr_t* ofc_sema_expr__create(
ofc_sema_expr_e type)
{
if (type >= OFC_SEMA_EXPR_COUNT)
return NULL;
ofc_sema_expr_t* expr
= (ofc_sema_expr_t*)malloc(
sizeof(ofc_sema_expr_t));
if (!expr) return NULL;
expr->type = type;
expr->src = OFC_SPARSE_REF_EMPTY;
expr->constant = NULL;
expr->label = NULL;
expr->brackets = false;
expr->repeat = 1;
expr->is_alt_return = false;
expr->is_label = false;
expr->is_format = false;
switch (type)
{
case OFC_SEMA_EXPR_CONSTANT:
break;
case OFC_SEMA_EXPR_LHS:
expr->lhs = NULL;
break;
case OFC_SEMA_EXPR_CAST:
expr->cast.type = NULL;
expr->cast.expr = NULL;
break;
case OFC_SEMA_EXPR_INTRINSIC:
expr->intrinsic = NULL;
expr->args = NULL;
break;
case OFC_SEMA_EXPR_FUNCTION:
expr->function = NULL;
expr->args = NULL;
break;
case OFC_SEMA_EXPR_IMPLICIT_DO:
expr->implicit_do.expr = NULL;
expr->implicit_do.iter = NULL;
expr->implicit_do.init = NULL;
expr->implicit_do.last = NULL;
expr->implicit_do.step = NULL;
break;
case OFC_SEMA_EXPR_ARRAY:
expr->array = NULL;
break;
case OFC_SEMA_EXPR_RESHAPE:
expr->reshape.source = NULL;
expr->reshape.shape = NULL;
break;
default:
expr->a = NULL;
expr->b = NULL;
break;
}
return expr;
}
ofc_sema_expr_t* ofc_sema_expr_copy_replace(
const ofc_sema_expr_t* expr,
const ofc_sema_decl_t* replace,
const ofc_sema_expr_t* with)
{
if (!expr) return NULL;
ofc_sema_expr_t* copy
= ofc_sema_expr__create(expr->type);
if (!copy) return NULL;
copy->src = expr->src;
copy->brackets = expr->brackets;
copy->repeat = expr->repeat;
if (expr->constant)
{
copy->constant = ofc_sema_typeval_copy(expr->constant);
if (!copy->constant)
{
ofc_sema_expr_delete(copy);
return NULL;
}
}
bool success = true;
switch (copy->type)
{
case OFC_SEMA_EXPR_CONSTANT:
break;
case OFC_SEMA_EXPR_LHS:
if (with && expr->lhs
&& (expr->lhs->type == OFC_SEMA_LHS_DECL)
&& (expr->lhs->decl == replace))
{
ofc_sema_expr_delete(copy);
return ofc_sema_expr_copy(with);
}
else if (with)
{
copy->lhs = ofc_sema_lhs_copy_replace(
expr->lhs, replace, with);
if (!copy->lhs)
{
ofc_sema_expr_delete(copy);
return NULL;
}
}
else
{
if (!ofc_sema_lhs_reference(expr->lhs))
{
ofc_sema_expr_delete(copy);
return NULL;
}
copy->lhs = expr->lhs;
}
break;
case OFC_SEMA_EXPR_CAST:
copy->cast.type = expr->cast.type;
copy->cast.expr = ofc_sema_expr_copy_replace(
expr->cast.expr, replace, with);
success = (copy->cast.expr != NULL);
break;
case OFC_SEMA_EXPR_INTRINSIC:
copy->intrinsic = expr->intrinsic;
if (expr->args)
{
copy->args = ofc_sema_dummy_arg_list_copy_replace(
expr->args, replace, with);
success = (copy->args != NULL);
}
break;
case OFC_SEMA_EXPR_FUNCTION:
copy->function = expr->function;
if (expr->args)
{
copy->args = ofc_sema_dummy_arg_list_copy_replace(
expr->args, replace, with);
success = (copy->args != NULL);
}
break;
case OFC_SEMA_EXPR_IMPLICIT_DO:
copy->implicit_do.expr
= ofc_sema_expr_list_copy_replace(
expr->implicit_do.expr, replace, with);
copy->implicit_do.iter
= (ofc_sema_decl_reference(expr->implicit_do.iter)
? expr->implicit_do.iter : NULL);
copy->implicit_do.init
= ofc_sema_expr_copy_replace(
expr->implicit_do.init, replace, with);
copy->implicit_do.last
= ofc_sema_expr_copy_replace(
expr->implicit_do.last, replace, with);
copy->implicit_do.step
= ofc_sema_expr_copy_replace(
expr->implicit_do.step, replace, with);
if (!copy->implicit_do.expr
|| !copy->implicit_do.iter
|| !copy->implicit_do.init
|| !copy->implicit_do.last)
success = false;
if (expr->implicit_do.step
&& !copy->implicit_do.step)
success = false;
break;
case OFC_SEMA_EXPR_ARRAY:
copy->array = ofc_sema_expr_list_copy(expr->array);
if (expr->array && !copy->array)
success = false;
break;
case OFC_SEMA_EXPR_RESHAPE:
copy->reshape.source = ofc_sema_expr_list_copy(
expr->reshape.source);
copy->reshape.shape = ofc_sema_array_copy(
expr->reshape.shape);
if (!copy->reshape.source
|| !copy->reshape.shape)
success = false;
break;
default:
copy->a = ofc_sema_expr_copy_replace(
expr->a, replace, with);
copy->b = ofc_sema_expr_copy_replace(
expr->b, replace, with);
/* We need to re-resolve the constant incase a subexpression
has been replaced. */
if (ofc_sema_expr_is_constant(copy->a)
&& ofc_sema_expr__resolve[expr->type])
{
if (!copy->b)
{
ofc_sema_typeval_delete(copy->constant);
copy->constant = ofc_sema_expr__resolve[expr->type](
copy->a->constant, NULL);
}
else if (ofc_sema_expr_is_constant(copy->b))
{
ofc_sema_typeval_delete(copy->constant);
copy->constant = ofc_sema_expr__resolve[expr->type](
copy->a->constant, copy->b->constant);
}
}
success = (copy->a && (!expr->b || (copy->b != NULL)));
break;
}
if (!success)
{
ofc_sema_expr_delete(copy);
return NULL;
}
return copy;
}
ofc_sema_expr_t* ofc_sema_expr_copy(
const ofc_sema_expr_t* expr)
{
return ofc_sema_expr_copy_replace(
expr, NULL, NULL);
}
/* Map parse operators to sema expr type. */
static ofc_sema_expr_e ofc_sema_expr__binary_map[] =
{
OFC_SEMA_EXPR_POWER,
OFC_SEMA_EXPR_MULTIPLY,
OFC_SEMA_EXPR_CONCAT,
OFC_SEMA_EXPR_DIVIDE,
OFC_SEMA_EXPR_ADD,
OFC_SEMA_EXPR_SUBTRACT,
OFC_SEMA_EXPR_EQ,
OFC_SEMA_EXPR_NE,
OFC_SEMA_EXPR_LT,
OFC_SEMA_EXPR_LE,
OFC_SEMA_EXPR_GT,
OFC_SEMA_EXPR_GE,
OFC_SEMA_EXPR_NOT,
OFC_SEMA_EXPR_AND,
OFC_SEMA_EXPR_OR,
OFC_SEMA_EXPR_XOR,
OFC_SEMA_EXPR_EQV,
OFC_SEMA_EXPR_NEQV,
};
ofc_sema_expr_t* ofc_sema_expr_cast(
ofc_sema_expr_t* expr,
const ofc_sema_type_t* type)
{
if (!type || !expr)
return NULL;
if (!ofc_sema_type_cast_valid(
ofc_sema_expr_type(expr), type))
return NULL;
ofc_sema_expr_t* cast
= ofc_sema_expr__create(
OFC_SEMA_EXPR_CAST);
if (!cast) return NULL;
if (ofc_sema_expr_is_constant(expr))
{
cast->constant = ofc_sema_typeval_cast(
expr->constant, type);
if (!cast->constant)
{
ofc_sema_expr_delete(cast);
return NULL;
}
}
else if (!ofc_sema_type_cast_is_lossless(
ofc_sema_expr_type(expr), type))
{
ofc_sparse_ref_warning(expr->src,
"Implicit cast may be lossy.");
}
cast->src = expr->src;
cast->cast.type = type;
cast->cast.expr = expr;
return cast;
}
ofc_sema_expr_t* ofc_sema_expr_cast_intrinsic(
ofc_sema_expr_t* expr, const ofc_sema_type_t* type)
{
if (!expr)
return NULL;
const ofc_sema_intrinsic_t* intrinsic
= ofc_sema_intrinsic_cast_func(type);
if (!intrinsic) return NULL;
ofc_sema_expr_t* cast
= ofc_sema_expr__create(
OFC_SEMA_EXPR_INTRINSIC);
if (!cast) return NULL;
ofc_sema_dummy_arg_t* dummy_arg
= ofc_sema_dummy_arg_wrap_expr(expr);
ofc_sema_dummy_arg_list_t* args
= ofc_sema_dummy_arg_list_create();
if (!ofc_sema_dummy_arg_list_add(args, dummy_arg))
{
ofc_sema_dummy_arg_list_delete(args);
ofc_sema_expr_delete(cast);
return NULL;
}
cast->args = ofc_sema_intrinsic_cast(
expr->src, intrinsic, args);
ofc_sema_dummy_arg_list_delete(args);
if (!cast->args)
{
ofc_sema_expr_delete(cast);
return NULL;
}
cast->intrinsic = intrinsic;
cast->constant = ofc_sema_intrinsic_constant(
cast->intrinsic, cast->args);
return cast;
}
ofc_sema_expr_t* ofc_sema_expr_typeval(
ofc_sema_typeval_t* typeval)
{
if (!typeval)
return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(OFC_SEMA_EXPR_CONSTANT);
if (!expr) return NULL;
expr->constant = typeval;
expr->src = typeval->src;
return expr;
}
ofc_sema_expr_t* ofc_sema_expr_integer(
int value, ofc_sema_kind_e kind)
{
ofc_sema_expr_t* expr
= ofc_sema_expr__create(OFC_SEMA_EXPR_CONSTANT);
if (!expr) return NULL;
expr->constant = ofc_sema_typeval_create_integer(
value, kind, OFC_SPARSE_REF_EMPTY);
if (!expr->constant)
{
ofc_sema_expr_delete(expr);
return NULL;
}
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__binary(
ofc_sema_scope_t* scope,
ofc_parse_operator_e op,
const ofc_parse_expr_t* a,
const ofc_parse_expr_t* b)
{
if (op >= OFC_PARSE_OPERATOR_COUNT)
return 0;
ofc_sema_expr_e type
= ofc_sema_expr__binary_map[op];
ofc_sema_expr_t* as = ofc_sema_expr(
scope, a);
if (!as) return NULL;
const ofc_sema_type_t* at
= ofc_sema_expr_type(as);
if (!at)
{
ofc_sema_expr_delete(as);
return NULL;
}
ofc_sema_expr__op_type_e err
= ofc_sema_expr_type_allowed(type, at);
if (err == OFC_SEMA_EXPR__OP_TYPE_INVALID)
{
ofc_sparse_ref_error(a->src,
"Can't use type %s in operator '%s'",
ofc_sema_type_str_rep(at),
ofc_parse_operator_str_rep(op));
ofc_sema_expr_delete(as);
return NULL;
}
else if (err == OFC_SEMA_EXPR__OP_TYPE_WARN)
{
ofc_sparse_ref_warning(a->src,
"Using type %s in operator '%s'",
ofc_sema_type_str_rep(at),
ofc_parse_operator_str_rep(op));
}
ofc_sema_expr_t* bs = ofc_sema_expr(
scope, b);
if (!bs)
{
ofc_sema_expr_delete(as);
return NULL;
}
const ofc_sema_type_t* bt
= ofc_sema_expr_type(bs);
if (!bt)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
err = ofc_sema_expr_type_allowed(type, bt);
if (err == OFC_SEMA_EXPR__OP_TYPE_INVALID)
{
ofc_sparse_ref_error(a->src,
"Can't use type %s in operator '%s'",
ofc_sema_type_str_rep(bt),
ofc_parse_operator_str_rep(op));
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
else if (err == OFC_SEMA_EXPR__OP_TYPE_WARN)
{
ofc_sparse_ref_warning(a->src,
"Using type %s in operator '%s'",
ofc_sema_type_str_rep(bt),
ofc_parse_operator_str_rep(op));
}
if (ofc_sema_expr__rule[type].promote)
{
if ((at->type == OFC_SEMA_TYPE_CHARACTER)
&& (bt->type == OFC_SEMA_TYPE_CHARACTER))
{
unsigned asize, bsize;
if (!ofc_sema_type_base_size(at, &asize)
|| !ofc_sema_type_base_size(bt, &bsize))
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
if (asize < bsize)
{
at = ofc_sema_type_create_character(
bt->kind, at->len, at->len_var);
if (!at)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(as, at);
if (!cast)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
as = cast;
}
else
{
bt = ofc_sema_type_create_character(
at->kind, bt->len, bt->len_var);
if (!bt)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(bs, bt);
if (!cast)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
bs = cast;
}
}
else if (!ofc_sema_type_compatible(at, bt))
{
if (type == OFC_SEMA_EXPR_AND
|| type == OFC_SEMA_EXPR_OR
|| type == OFC_SEMA_EXPR_XOR
|| type == OFC_SEMA_EXPR_EQV
|| type == OFC_SEMA_EXPR_NEQV)
{
const ofc_sema_type_t* logtype
= ofc_sema_type_logical_default();
if (!ofc_sema_type_compatible(at, logtype))
{
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(as, logtype);
if (!cast)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
as = cast;
}
if (!ofc_sema_type_compatible(bt, logtype))
{
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(bs, logtype);
if (!cast)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
bs = cast;
}
}
else
{
const ofc_sema_type_t* ptype
= ofc_sema_type_promote(at, bt);
if (!ptype)
{
ofc_sparse_ref_error(a->src,
"Incompatible types (%s, %s) in operator %s",
ofc_sema_type_str_rep(at),
ofc_sema_type_str_rep(bt),
ofc_parse_operator_str_rep(op));
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
if (!ofc_sema_type_compatible(at, ptype))
{
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(as, ptype);
if (!cast)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
as = cast;
}
if (!ofc_sema_type_compatible(bt, ptype))
{
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(bs, ptype);
if (!cast)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
bs = cast;
}
}
}
}
ofc_sema_expr_t* expr
= ofc_sema_expr__create(type);
if (!expr)
{
ofc_sema_expr_delete(bs);
ofc_sema_expr_delete(as);
return NULL;
}
if (ofc_sema_expr_is_constant(as)
&& ofc_sema_expr_is_constant(bs)
&& ofc_sema_expr__resolve[type])
{
expr->constant = ofc_sema_expr__resolve[type](
as->constant, bs->constant);
}
expr->a = as;
expr->b = bs;
expr->src = OFC_SPARSE_REF_EMPTY;
ofc_sparse_ref_bridge(
as->src, bs->src, &expr->src);
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__unary(
ofc_sema_scope_t* scope,
ofc_parse_operator_e op,
const ofc_parse_expr_t* a)
{
bool needs_bool = false;
ofc_sema_expr_e type;
switch (op)
{
case OFC_PARSE_OPERATOR_ADD:
return ofc_sema_expr(scope, a);
case OFC_PARSE_OPERATOR_SUBTRACT:
type = OFC_SEMA_EXPR_NEGATE;
break;
case OFC_PARSE_OPERATOR_NOT:
type = OFC_SEMA_EXPR_NOT;
needs_bool = true;
break;
default:
return NULL;
}
ofc_sema_expr_t* as = ofc_sema_expr(scope, a);
if (!as) return NULL;
const ofc_sema_type_t* at
= ofc_sema_expr_type(as);
ofc_sema_expr__op_type_e err
= ofc_sema_expr_type_allowed(type, at);
if (err == OFC_SEMA_EXPR__OP_TYPE_INVALID)
{
ofc_sparse_ref_error(a->src,
"Can't use type %s in operator '%s'",
ofc_sema_type_str_rep(at),
ofc_parse_operator_str_rep(op));
ofc_sema_expr_delete(as);
return NULL;
}
else if (err == OFC_SEMA_EXPR__OP_TYPE_WARN)
{
ofc_sparse_ref_warning(a->src,
"Using type %s in operator '%s'",
ofc_sema_type_str_rep(at),
ofc_parse_operator_str_rep(op));
}
if (needs_bool && !ofc_sema_type_is_logical(at))
{
const ofc_sema_type_t* logtype
= ofc_sema_type_logical_default();
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(as, logtype);
if (!cast)
{
ofc_sema_expr_delete(as);
return NULL;
}
as = cast;
}
ofc_sema_expr_t* expr
= ofc_sema_expr__create(type);
if (!expr)
{
ofc_sema_expr_delete(as);
return NULL;
}
if (ofc_sema_expr_is_constant(as)
&& ofc_sema_expr__resolve[type])
{
expr->constant = ofc_sema_expr__resolve[type](
as->constant, NULL);
}
expr->a = as;
expr->src = a->src;
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__literal(
const ofc_parse_literal_t* literal)
{
ofc_sema_typeval_t* tv
= ofc_sema_typeval_literal(
literal, NULL);
if (!tv) return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(
OFC_SEMA_EXPR_CONSTANT);
if (!expr)
{
ofc_sema_typeval_delete(tv);
return NULL;
}
expr->constant = tv;
expr->src = literal->src;
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__array(
ofc_sema_scope_t* scope,
const ofc_parse_expr_list_t* array)
{
ofc_sema_expr_list_t* list
= ofc_sema_expr_list(scope, array);
if (array && !list) return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(
OFC_SEMA_EXPR_ARRAY);
if (!expr)
{
ofc_sema_expr_list_delete(list);
return NULL;
}
expr->array = list;
expr->src = array->src;
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__reshape(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* pexpr)
{
if (!pexpr
|| (pexpr->type != OFC_PARSE_EXPR_RESHAPE)
|| !pexpr->reshape.source
|| !pexpr->reshape.shape)
return NULL;
if (pexpr->reshape.pad)
{
/* TODO - Support PAD in RESHAPE */
ofc_sparse_ref_error(pexpr->reshape.pad->src,
"PAD parameter not supported in RESHAPE");
return NULL;
}
if (pexpr->reshape.order)
{
/* TODO - Support ORDER in RESHAPE */
ofc_sparse_ref_error(pexpr->reshape.order->src,
"ORDER parameter not supported in RESHAPE");
return NULL;
}
if (pexpr->reshape.source->type != OFC_PARSE_EXPR_ARRAY)
{
ofc_sparse_ref_error(pexpr->reshape.source->src,
"RESHAPE SOURCE parameter must be an array");
return NULL;
}
if (pexpr->reshape.shape->type != OFC_PARSE_EXPR_ARRAY)
{
ofc_sparse_ref_error(pexpr->reshape.shape->src,
"RESHAPE SHAPE parameter must be an array");
return NULL;
}
ofc_sema_expr_list_t* source
= ofc_sema_expr_list(scope,
pexpr->reshape.source->array);
if (!source) return NULL;
ofc_sema_array_t* shape
= ofc_sema_array_array(scope,
pexpr->reshape.shape->array);
if (!shape)
{
ofc_sema_expr_list_delete(source);
return NULL;
}
ofc_sema_expr_t* expr
= ofc_sema_expr__create(
OFC_SEMA_EXPR_RESHAPE);
if (!expr)
{
ofc_sema_array_delete(shape);
ofc_sema_expr_list_delete(source);
return NULL;
}
expr->reshape.source = source;
expr->reshape.shape = shape;
expr->src = pexpr->src;
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__intrinsic(
ofc_sema_scope_t* scope,
const ofc_parse_lhs_t* name,
const ofc_sema_intrinsic_t* intrinsic)
{
if (!name)
return NULL;
if (!intrinsic
|| (name->type != OFC_PARSE_LHS_ARRAY)
|| !name->array.index
|| !name->parent
|| (name->parent->type != OFC_PARSE_LHS_VARIABLE))
{
ofc_sparse_ref_error(name->src,
"Invalid invocation of INTRINSIC function.");
return NULL;
}
ofc_sema_dummy_arg_list_t* args = NULL;
if (name->array.index->count > 0)
{
if (!name->array.index->range)
return NULL;
ofc_sema_dummy_arg_list_t* rargs
= ofc_sema_dummy_arg_list_create();
if (!rargs) return NULL;
unsigned i;
for (i = 0; i < name->array.index->count; i++)
{
const ofc_parse_array_range_t* range
= name->array.index->range[i];
if (!range || range->is_slice
|| range->last || range->stride)
{
ofc_sema_dummy_arg_list_delete(rargs);
return NULL;
}
ofc_sema_expr_t* expr
= ofc_sema_expr_dummy_arg(scope, range->first);
if (!expr)
{
ofc_sema_dummy_arg_list_delete(rargs);
return NULL;
}
ofc_sema_dummy_arg_t* dummy_arg
= ofc_sema_dummy_arg_wrap_expr(expr);
if (!dummy_arg)
{
ofc_sema_expr_delete(expr);
ofc_sema_dummy_arg_list_delete(rargs);
return NULL;
}
if (!ofc_sema_dummy_arg_list_add(rargs, dummy_arg))
{
ofc_sema_dummy_arg_delete(dummy_arg);
ofc_sema_dummy_arg_list_delete(rargs);
return NULL;
}
}
args = ofc_sema_intrinsic_cast(
name->src, intrinsic, rargs);
ofc_sema_dummy_arg_list_delete(rargs);
if (!args) return NULL;
}
ofc_sema_expr_t* expr
= ofc_sema_expr__create(
OFC_SEMA_EXPR_INTRINSIC);
if (!expr)
{
ofc_sema_dummy_arg_list_delete(args);
return NULL;
}
expr->intrinsic = intrinsic;
expr->args = args;
expr->constant = ofc_sema_intrinsic_constant(
intrinsic, args);
expr->src = OFC_SPARSE_REF_EMPTY;
ofc_sparse_ref_bridge(
name->parent->src, name->src,
&expr->src);
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__function(
ofc_sema_scope_t* scope,
const ofc_parse_lhs_t* name,
const ofc_sema_decl_t* decl)
{
if (!name)
return NULL;
if (!decl || !ofc_sema_decl_is_function(decl)
|| (name->type != OFC_PARSE_LHS_ARRAY)
|| !name->parent
|| (name->parent->type != OFC_PARSE_LHS_VARIABLE))
return NULL;
/* TODO - Defer checking of arguments for a later pass? */
const ofc_sema_scope_t* fscope = decl->func;
if (fscope)
{
unsigned acount = 0;
if (name->array.index)
acount = name->array.index->count;
if (fscope->args
? (acount != fscope->args->count)
: (acount != 0))
{
ofc_sparse_ref_error(name->src,
"Incorrect number of arguments in function call.");
return NULL;
}
}
ofc_sema_dummy_arg_list_t* args = NULL;
if (name->array.index
&& (name->array.index->count > 0))
{
if (!name->array.index->range)
return NULL;
args = ofc_sema_dummy_arg_list_create();
if (!args) return NULL;
unsigned i;
for (i = 0; i < name->array.index->count; i++)
{
const ofc_parse_array_range_t* range
= name->array.index->range[i];
if (!range || range->is_slice
|| range->last || range->stride)
{
ofc_sema_dummy_arg_list_delete(args);
return NULL;
}
ofc_sema_dummy_arg_t* dummy_arg
= ofc_sema_dummy_arg(scope, range->first);
if (!dummy_arg)
{
ofc_sema_dummy_arg_list_delete(args);
return NULL;
}
if (!ofc_sema_dummy_arg_list_add(args, dummy_arg))
{
ofc_sema_dummy_arg_delete(dummy_arg);
ofc_sema_dummy_arg_list_delete(args);
return NULL;
}
}
/* TODO - Validate and cast arguments. */
}
ofc_sema_expr_t* expr
= ofc_sema_expr__create(
OFC_SEMA_EXPR_FUNCTION);
if (!expr)
{
ofc_sema_dummy_arg_list_delete(args);
return NULL;
}
expr->function = decl;
expr->args = args;
expr->src = OFC_SPARSE_REF_EMPTY;
ofc_sparse_ref_bridge(
name->parent->src, name->src, &expr->src);
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__lhs(
ofc_sema_scope_t* scope,
const ofc_parse_lhs_t* name,
bool is_dummy_arg)
{
if (!name)
return NULL;
ofc_sema_lhs_t* lhs = (is_dummy_arg
? ofc_sema_lhs_in_dummy_arg(scope, name)
: ofc_sema_lhs_in_expr(scope, name));
if (!lhs) return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(
OFC_SEMA_EXPR_LHS);
if (!expr)
{
ofc_sema_lhs_delete(lhs);
return NULL;
}
expr->lhs = lhs;
expr->src = name->src;
if (ofc_sema_lhs_is_parameter(lhs))
{
expr->constant
= ofc_sema_lhs_parameter(lhs);
if (!expr->constant)
{
ofc_sema_expr_delete(expr);
return NULL;
}
}
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__variable(
ofc_sema_scope_t* scope,
const ofc_parse_lhs_t* name,
bool is_dummy_arg)
{
if (!name)
return NULL;
ofc_sparse_ref_t base_name;
if (!ofc_parse_lhs_base_name(
*name, &base_name))
return NULL;
const ofc_sema_decl_t* decl
= ofc_sema_scope_decl_find(
scope, base_name.string, false);
const ofc_sema_intrinsic_t* intrinsic = NULL;
if (decl && decl->is_intrinsic)
{
intrinsic = decl->intrinsic;
}
else if (!decl)
{
intrinsic = ofc_sema_intrinsic(
base_name.string, global_opts.case_sensitive);
}
ofc_sema_expr_t* expr;
if (intrinsic
&& (name->type == OFC_PARSE_LHS_ARRAY))
{
expr = ofc_sema_expr__intrinsic(
scope, name, intrinsic);
}
else if (ofc_sema_decl_is_function(decl))
{
expr = ofc_sema_expr__function(
scope, name, decl);
if (!expr)
{
/* FUNCTION types are only valid as arguments. */
expr = ofc_sema_expr__lhs(
scope, name, is_dummy_arg);
}
}
else
{
bool is_array = false;
bool is_function = false;
if (decl)
{
is_array = ofc_sema_decl_is_array(decl);
is_function = ofc_sema_decl_is_function(decl);
}
if ((is_function || !is_array)
&& ofc_parse_lhs_possible_function_call(*name))
{
if ((name->type != OFC_PARSE_LHS_ARRAY)
|| !name->parent
|| (name->parent->type != OFC_PARSE_LHS_VARIABLE))
{
/* TODO - Handle complicated functions
returning arrays or structures. */
return NULL;
}
ofc_sema_decl_t* fdecl
= ofc_sema_scope_decl_find_create(
scope, base_name, false);
if (!fdecl)
{
ofc_sparse_ref_error(name->parent->src,
"No complete IMPLICIT rule or specifier for function");
return NULL;
}
if (!ofc_sema_decl_function(fdecl))
{
ofc_sparse_ref_error(name->src,
"Declaration cannot be used as a function");
return NULL;
}
expr = ofc_sema_expr__function(
scope, name, fdecl);
if (!expr)
{
ofc_sparse_ref_error(name->src,
"Invalid invocation of function");
}
else if (!decl)
{
ofc_sparse_ref_warning(name->src,
"Implicit function declaration");
}
}
else
{
expr = ofc_sema_expr__lhs(
scope, name, is_dummy_arg);
}
}
return expr;
}
static ofc_sema_expr_t* ofc_sema_expr__brackets(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* expr)
{
if (!scope || !expr)
return NULL;
ofc_sema_expr_t* expr_bracket
= ofc_sema_expr(scope, expr);
if (!expr_bracket)
return NULL;
expr_bracket->brackets = true;
return expr_bracket;
}
ofc_sema_expr_t* ofc_sema_expr(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* expr)
{
if (!expr)
return NULL;
switch (expr->type)
{
case OFC_PARSE_EXPR_CONSTANT:
return ofc_sema_expr__literal(
&expr->literal);
case OFC_PARSE_EXPR_VARIABLE:
return ofc_sema_expr__variable(
scope, expr->variable, false);
case OFC_PARSE_EXPR_BRACKETS:
return ofc_sema_expr__brackets(
scope, expr->brackets.expr);
case OFC_PARSE_EXPR_UNARY:
return ofc_sema_expr__unary(
scope, expr->unary.operator,
expr->unary.a);
case OFC_PARSE_EXPR_BINARY:
return ofc_sema_expr__binary(
scope, expr->binary.operator,
expr->binary.a, expr->binary.b);
case OFC_PARSE_EXPR_ARRAY:
return ofc_sema_expr__array(
scope, expr->array);
case OFC_PARSE_EXPR_RESHAPE:
return ofc_sema_expr__reshape(
scope, expr);
default:
break;
}
return NULL;
}
static ofc_sema_expr_t* ofc_sema_expr__repeat(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* expr)
{
if ((expr->type != OFC_PARSE_EXPR_BINARY)
|| (expr->binary.operator != OFC_PARSE_OPERATOR_MULTIPLY))
return NULL;
ofc_sema_expr_t* rexpr
= ofc_sema_expr(scope, expr->binary.a);
unsigned repeat;
bool success = ofc_sema_expr_resolve_uint(rexpr, &repeat);
ofc_sema_expr_delete(rexpr);
if (!success) return NULL;
ofc_sema_expr_t* e
= ofc_sema_expr(scope, expr->binary.b);
if (!e) return NULL;
e->repeat = repeat;
return e;
}
ofc_sema_expr_t* ofc_sema_expr_repeat(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* expr)
{
if (!expr) return NULL;
ofc_sema_expr_t* e
= ofc_sema_expr__repeat(scope, expr);
if (!e) e = ofc_sema_expr(scope, expr);
return e;
}
ofc_sema_expr_t* ofc_sema_expr_dummy_arg(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* expr)
{
if (!expr) return NULL;
if (expr->type == OFC_PARSE_EXPR_VARIABLE)
{
ofc_sema_expr_t* e
= ofc_sema_expr__variable(
scope, expr->variable, true);
if (e)
{
if ((e->type == OFC_SEMA_EXPR_LHS)
&& !ofc_sema_lhs_is_array(e->lhs)
&& !ofc_sema_lhs_is_structure(e->lhs))
{
ofc_sparse_ref_t base_name;
if (!ofc_parse_lhs_base_name(
*expr->variable, &base_name))
{
ofc_sema_expr_delete(e);
return NULL;
}
const ofc_sema_decl_t* decl
= ofc_sema_scope_decl_find(
scope, base_name.string, false);
if (decl && decl->is_intrinsic)
{
if (!ofc_sema_intrinsic_is_specific(decl->intrinsic))
{
ofc_sparse_ref_error(e->src,
"Generic intrinsic function '%.*s' can't be passed as an argument",
e->src.string.size, e->src.string.base);
ofc_sema_expr_delete(e);
return NULL;
}
}
}
return e;
}
}
return ofc_sema_expr(scope, expr);
}
ofc_sema_expr_t* ofc_sema_expr_label(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* expr)
{
ofc_sema_expr_t* label
= ofc_sema_expr(scope, expr);
if (!label) return NULL;
const ofc_sema_type_t* type
= ofc_sema_expr_type(label);
if (!ofc_sema_type_is_integer(type))
{
ofc_sparse_ref_warning(label->src,
"Label must be an INTEGER expression");
ofc_sema_expr_delete(label);
return NULL;
}
const ofc_sema_typeval_t* tv
= ofc_sema_expr_constant(label);
if (tv)
{
int64_t v;
bool has_val = ofc_sema_typeval_get_integer(tv, &v);
if (has_val && (v <= 0))
{
ofc_sparse_ref_warning(label->src,
"Label expression must be greater than zero");
ofc_sema_expr_delete(label);
return NULL;
}
}
label->is_label = true;
return label;
}
ofc_sema_expr_t* ofc_sema_expr_alt_return(
ofc_sema_scope_t* scope,
const ofc_parse_expr_t* expr)
{
ofc_sema_expr_t* alt_return
= ofc_sema_expr_label(scope, expr);
if (!alt_return) return NULL;
alt_return->is_alt_return = true;
return alt_return;
}
static ofc_sema_expr_t* ofc_sema_expr__implicit_do(
ofc_sema_scope_t* scope,
ofc_sparse_ref_t src,
const ofc_parse_expr_implicit_do_t* id)
{
if (!id || !id->init)
return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(
OFC_SEMA_EXPR_IMPLICIT_DO);
if (!expr) return NULL;
expr->src = src;
ofc_sema_lhs_t* iter_lhs
= ofc_sema_lhs_from_expr(
scope, id->iter);
if (!iter_lhs)
{
ofc_sema_expr_delete(expr);
return NULL;
}
if (!ofc_sema_lhs_mark_used(
iter_lhs, true, true))
{
ofc_sema_lhs_delete(iter_lhs);
ofc_sema_expr_delete(expr);
return NULL;
}
if (iter_lhs->type != OFC_SEMA_LHS_DECL)
{
ofc_sparse_ref_error(id->iter->src,
"Implicit do loop iterator must be a variable");
ofc_sema_lhs_delete(iter_lhs);
ofc_sema_expr_delete(expr);
return NULL;
}
if (!ofc_sema_decl_reference(iter_lhs->decl))
{
ofc_sema_lhs_delete(iter_lhs);
ofc_sema_expr_delete(expr);
return NULL;
}
expr->implicit_do.iter = iter_lhs->decl;
ofc_sema_lhs_delete(iter_lhs);
const ofc_sema_type_t* iter_type
= ofc_sema_decl_type(expr->implicit_do.iter);
if (!iter_type)
{
ofc_sema_expr_delete(expr);
return NULL;
}
if (!ofc_sema_type_is_scalar(iter_type))
{
ofc_sparse_ref_error(id->iter->src,
"Implicit do loop iterator must be a scalar type");
ofc_sema_expr_delete(expr);
return NULL;
}
if (!ofc_sema_type_is_integer(iter_type))
{
ofc_sparse_ref_warning(id->iter->src,
"Using REAL in implicit do loop iterator");
}
expr->implicit_do.init = ofc_sema_expr(
scope, id->init);
if (!expr->implicit_do.init)
{
ofc_sema_expr_delete(expr);
return NULL;
}
const ofc_sema_type_t* init_type
= ofc_sema_expr_type(expr->implicit_do.init);
if (!init_type)
{
ofc_sema_expr_delete(expr);
return NULL;
}
else if (!ofc_sema_type_compatible(
iter_type, init_type))
{
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(
expr->implicit_do.init, iter_type);
if (!cast)
{
ofc_sema_expr_delete(expr);
return NULL;
}
expr->implicit_do.init = cast;
}
expr->implicit_do.last = ofc_sema_expr(
scope, id->limit);
if (!expr->implicit_do.last)
{
ofc_sema_expr_delete(expr);
return NULL;
}
const ofc_sema_type_t* last_type
= ofc_sema_expr_type(expr->implicit_do.last);
if (!last_type)
{
ofc_sema_expr_delete(expr);
return NULL;
}
else if (!ofc_sema_type_compatible(
iter_type, last_type))
{
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(
expr->implicit_do.last, iter_type);
if (!cast)
{
ofc_sparse_ref_error(id->limit->src,
"Expression type '%s' doesn't match iterator type '%s'",
ofc_sema_type_str_rep(last_type),
ofc_sema_type_str_rep(iter_type));
ofc_sema_expr_delete(expr);
return NULL;
}
expr->implicit_do.last = cast;
}
if (id->step)
{
expr->implicit_do.step
= ofc_sema_expr(scope, id->step);
if (!expr->implicit_do.step)
{
ofc_sema_expr_delete(expr);
return NULL;
}
const ofc_sema_type_t* step_type
= ofc_sema_expr_type(expr->implicit_do.step);
if (!step_type)
{
ofc_sema_expr_delete(expr);
return NULL;
}
else if (!ofc_sema_type_compatible(
iter_type, step_type))
{
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(
expr->implicit_do.step, iter_type);
if (!cast)
{
ofc_sparse_ref_error(id->step->src,
"Expression type '%s' doesn't match iterator type '%s'",
ofc_sema_type_str_rep(step_type),
ofc_sema_type_str_rep(iter_type));
ofc_sema_expr_delete(expr);
return NULL;
}
expr->implicit_do.step = cast;
}
}
if (id->dlist && (id->dlist->count > 0))
{
expr->implicit_do.expr
= ofc_sema_expr_list_io(scope, id->dlist);
if (!expr->implicit_do.expr)
{
ofc_sema_expr_delete(expr);
return NULL;
}
}
else
{
ofc_sema_expr_delete(expr);
return NULL;
}
const ofc_sema_typeval_t* ctv[3];
ctv[0] = ofc_sema_expr_constant(
expr->implicit_do.init);
ctv[1] = ofc_sema_expr_constant(
expr->implicit_do.last);
ctv[2] = ofc_sema_expr_constant(
expr->implicit_do.step);
long double first, last, step = 1.0;
if (ofc_sema_typeval_get_real(ctv[0], &first)
&& ofc_sema_typeval_get_real(ctv[1], &last)
&& (!ctv[2] || ofc_sema_typeval_get_real(ctv[2], &step)))
{
long double dcount = floor((last - first) / step);
if (dcount < 0.0)
{
ofc_sparse_ref_error(src,
"Loop iterates away from limit");
ofc_sema_expr_delete(expr);
return NULL;
}
dcount += 1.0;
expr->implicit_do.count = (unsigned)dcount;
if ((long double)expr->implicit_do.count != dcount)
{
ofc_sema_expr_delete(expr);
return NULL;
}
expr->implicit_do.count_var = false;
}
else
{
expr->implicit_do.count_var = true;
expr->implicit_do.count = 0;
}
return expr;
}
ofc_sema_expr_t* ofc_sema_expr_wrap_lhs(
ofc_sema_lhs_t* lhs)
{
if (!lhs) return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(OFC_SEMA_EXPR_LHS);
if (!expr) return NULL;
if (!ofc_sema_lhs_reference(lhs))
{
ofc_sema_expr_delete(expr);
return NULL;
}
expr->lhs = lhs;
expr->src = expr->lhs->src;
return expr;
}
void ofc_sema_expr_delete(
ofc_sema_expr_t* expr)
{
if (!expr)
return;
ofc_sema_typeval_delete(
expr->constant);
switch (expr->type)
{
case OFC_SEMA_EXPR_CONSTANT:
break;
case OFC_SEMA_EXPR_LHS:
ofc_sema_lhs_delete(expr->lhs);
break;
case OFC_SEMA_EXPR_CAST:
ofc_sema_expr_delete(expr->cast.expr);
break;
case OFC_SEMA_EXPR_INTRINSIC:
case OFC_SEMA_EXPR_FUNCTION:
ofc_sema_dummy_arg_list_delete(expr->args);
break;
case OFC_SEMA_EXPR_IMPLICIT_DO:
ofc_sema_expr_list_delete(expr->implicit_do.expr);
ofc_sema_decl_delete(expr->implicit_do.iter);
ofc_sema_expr_delete(expr->implicit_do.init);
ofc_sema_expr_delete(expr->implicit_do.last);
ofc_sema_expr_delete(expr->implicit_do.step);
break;
case OFC_SEMA_EXPR_ARRAY:
ofc_sema_expr_list_delete(expr->array);
break;
case OFC_SEMA_EXPR_RESHAPE:
ofc_sema_expr_list_delete(expr->reshape.source);
ofc_sema_array_delete(expr->reshape.shape);
break;
default:
ofc_sema_expr_delete(expr->b);
ofc_sema_expr_delete(expr->a);
break;
}
free(expr);
}
const ofc_sema_array_t* ofc_sema_expr_array(
const ofc_sema_expr_t* expr)
{
if (!expr) return NULL;
/* TODO - Support for all expressions. */
switch (expr->type)
{
case OFC_SEMA_EXPR_LHS:
return ofc_sema_lhs_array(expr->lhs);
case OFC_SEMA_EXPR_CAST:
return ofc_sema_expr_array(expr->cast.expr);
default:
break;
}
return NULL;
}
ofc_sema_structure_t* ofc_sema_expr_structure(
const ofc_sema_expr_t* expr)
{
if (!expr) return NULL;
/* TODO - Support for all expressions. */
switch (expr->type)
{
case OFC_SEMA_EXPR_LHS:
return ofc_sema_lhs_structure(expr->lhs);
case OFC_SEMA_EXPR_CAST:
return ofc_sema_expr_structure(expr->cast.expr);
default:
break;
}
return NULL;
}
bool ofc_sema_expr_elem_count(
const ofc_sema_expr_t* expr,
unsigned* count)
{
if (!expr)
return false;
unsigned ecount = 1;
if (expr->type == OFC_SEMA_EXPR_IMPLICIT_DO)
{
if (expr->implicit_do.count_var)
return false;
unsigned idecount;
if (!ofc_sema_expr_list_elem_count(
expr->implicit_do.expr, &idecount))
return false;
ecount *= idecount;
ecount *= expr->implicit_do.count;
}
else if (expr->type == OFC_SEMA_EXPR_ARRAY)
{
if (!expr->array)
{
if (count) *count = 0;
return true;
}
return ofc_sema_expr_list_elem_count(
expr->array, count);
}
else if (expr->type == OFC_SEMA_EXPR_RESHAPE)
{
if (!expr->reshape.source)
{
if (count) *count = 0;
return true;
}
return ofc_sema_expr_list_elem_count(
expr->reshape.source, count);
}
const ofc_sema_array_t* array
= ofc_sema_expr_array(expr);
if (array)
{
unsigned acount;
if (!ofc_sema_array_total(
array, &acount))
return false;
ecount *= acount;
}
const ofc_sema_structure_t* structure
= ofc_sema_expr_structure(expr);
if (structure)
{
unsigned scount;
if (!ofc_sema_structure_elem_count(
structure, &scount))
return false;
ecount *= scount;
}
if (count) *count = ecount;
return true;
}
ofc_sema_expr_t* ofc_sema_expr_elem_get(
const ofc_sema_expr_t* expr, unsigned offset)
{
if (!expr)
return NULL;
switch (expr->type)
{
case OFC_SEMA_EXPR_LHS:
{
if (!ofc_sema_lhs_is_array(expr->lhs))
break;
ofc_sema_expr_t* sub_elem
= ofc_sema_expr__create(OFC_SEMA_EXPR_LHS);
if (!sub_elem) return NULL;
sub_elem->lhs = ofc_sema_lhs_elem_get(
expr->lhs, offset);
if (!sub_elem->lhs)
{
ofc_sema_expr_delete(sub_elem);
return NULL;
}
return sub_elem;
}
case OFC_SEMA_EXPR_CAST:
{
ofc_sema_expr_t* sexpr
= ofc_sema_expr_elem_get(
expr->cast.expr, offset);
if (!sexpr) return NULL;
ofc_sema_expr_t* cast
= ofc_sema_expr_cast(
sexpr, expr->cast.type);
if (!cast)
{
ofc_sema_expr_delete(sexpr);
return NULL;
}
return cast;
}
case OFC_SEMA_EXPR_IMPLICIT_DO:
{
if (!expr->implicit_do.iter)
return NULL;
unsigned sub_elem_count;
if (!ofc_sema_expr_list_elem_count(
expr->implicit_do.expr, &sub_elem_count))
return NULL;
if (sub_elem_count == 0)
return NULL;
unsigned sub_offset
= (offset % sub_elem_count);
offset /= sub_elem_count;
const ofc_sema_typeval_t* ctv[2];
ctv[0] = ofc_sema_expr_constant(
expr->implicit_do.init);
ctv[1] = ofc_sema_expr_constant(
expr->implicit_do.step);
long double first, step = 1.0;
if (!ofc_sema_typeval_get_real(ctv[0], &first))
return NULL;
if (ctv[1] && !ofc_sema_typeval_get_real(ctv[1], &step))
return NULL;
long double doffset
= first + ((long double)offset * step);
ofc_sema_typeval_t* dinit
= ofc_sema_typeval_create_real(
doffset, OFC_SEMA_KIND_NONE,
OFC_SPARSE_REF_EMPTY);
if (!dinit) return NULL;
ofc_sema_typeval_t* init
= ofc_sema_typeval_cast(
dinit, expr->implicit_do.iter->type);
ofc_sema_typeval_delete(dinit);
if (!init) return NULL;
ofc_sema_expr_t* iter_expr
= ofc_sema_expr_typeval(init);
if (!iter_expr)
{
ofc_sema_typeval_delete(init);
return NULL;
}
ofc_sema_expr_t* rval = NULL;
unsigned e = sub_offset;
unsigned i;
for (i = 0; i < expr->implicit_do.expr->count; i++)
{
ofc_sema_expr_t* expr_dummy
= expr->implicit_do.expr->expr[i];
unsigned elem_count;
if (!ofc_sema_expr_elem_count(
expr_dummy, &elem_count))
return NULL;
unsigned elem_total = elem_count;
if (expr_dummy->repeat > 1)
elem_total *= expr_dummy->repeat;
if (e < elem_total)
{
ofc_sema_expr_t* body
= ofc_sema_expr_copy_replace(
expr_dummy, expr->implicit_do.iter, iter_expr);
if (!body) return NULL;
rval = ofc_sema_expr_elem_get(
body, sub_offset);
ofc_sema_expr_delete(body);
}
else
{
e -= elem_total;
}
}
ofc_sema_expr_delete(iter_expr);
return rval;
}
case OFC_SEMA_EXPR_ARRAY:
return ofc_sema_expr_list_elem_get(
expr->array, offset);
case OFC_SEMA_EXPR_RESHAPE:
return ofc_sema_expr_list_elem_get(
expr->reshape.source, offset);
default:
break;
}
if (offset != 0)
return NULL;
return ofc_sema_expr_copy(expr);
}
bool ofc_sema_expr_compare(
const ofc_sema_expr_t* a,
const ofc_sema_expr_t* b)
{
if (!a || !b)
return false;
if (a == b)
return true;
if ((a->type != b->type)
|| (a->is_label != b->is_label)
|| (a->is_alt_return != b->is_alt_return))
return false;
if (ofc_sema_expr_is_constant(a)
&& ofc_sema_expr_is_constant(b))
return ofc_sema_typeval_compare(
a->constant, b->constant);
switch (a->type)
{
case OFC_SEMA_EXPR_CONSTANT:
return false;
case OFC_SEMA_EXPR_LHS:
return ofc_sema_lhs_compare(a->lhs, b->lhs);
case OFC_SEMA_EXPR_CAST:
if (!ofc_sema_type_compatible(
a->cast.type, b->cast.type))
return false;
return ofc_sema_expr_compare(
a->cast.expr, b->cast.expr);
case OFC_SEMA_EXPR_INTRINSIC:
return ((a->intrinsic == b->intrinsic)
&& ofc_sema_dummy_arg_list_compare(a->args, b->args));
case OFC_SEMA_EXPR_FUNCTION:
return ((a->function == b->function)
&& ofc_sema_dummy_arg_list_compare(a->args, b->args));
case OFC_SEMA_EXPR_IMPLICIT_DO:
return (ofc_sema_expr_list_compare(
a->implicit_do.expr, b->implicit_do.expr)
&& (a->implicit_do.iter == b->implicit_do.iter)
&& ofc_sema_expr_compare(
a->implicit_do.init, b->implicit_do.init)
&& ofc_sema_expr_compare(
a->implicit_do.last, b->implicit_do.last)
&& ofc_sema_expr_compare_def_one(
a->implicit_do.step, b->implicit_do.step));
case OFC_SEMA_EXPR_ARRAY:
if (!a->array && !b->array)
return true;
return ofc_sema_expr_list_compare(
a->array, b->array);
case OFC_SEMA_EXPR_RESHAPE:
return (ofc_sema_expr_list_compare(
a->reshape.source, b->reshape.source)
&& ofc_sema_array_compare(
a->reshape.shape, b->reshape.shape));
default:
break;
}
if ((a->a != b->a)
&& !ofc_sema_expr_compare(a->a, b->a))
return false;
return ((a->b == b->b)
|| ofc_sema_expr_compare(a->b, b->b));
}
bool ofc_sema_expr_compare_def_one(
const ofc_sema_expr_t* a,
const ofc_sema_expr_t* b)
{
if (a && b)
return ofc_sema_expr_compare(a, b);
if (!a && !b)
return true;
const ofc_sema_expr_t* c = (a ? a : b);
const ofc_sema_typeval_t* ctv
= ofc_sema_expr_constant(c);
if (!ctv) return false;
return ofc_sema_typeval_is_one(ctv);
}
ofc_sema_expr_t* ofc_sema_expr_add(
const ofc_sema_expr_t* a,
const ofc_sema_expr_t* b)
{
if (!a || !b) return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(OFC_SEMA_EXPR_ADD);
if (!expr) return NULL;
expr->a = ofc_sema_expr_copy(a);
expr->b = ofc_sema_expr_copy(b);
return expr;
}
ofc_sema_expr_t* ofc_sema_expr_sub(
const ofc_sema_expr_t* a,
const ofc_sema_expr_t* b)
{
if (!a || !b) return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(OFC_SEMA_EXPR_SUBTRACT);
if (!expr) return NULL;
expr->a = ofc_sema_expr_copy(a);
expr->b = ofc_sema_expr_copy(b);
return expr;
}
ofc_sema_expr_t* ofc_sema_expr_div(
const ofc_sema_expr_t* a,
const ofc_sema_expr_t* b)
{
if (!a || !b) return NULL;
ofc_sema_expr_t* expr
= ofc_sema_expr__create(OFC_SEMA_EXPR_DIVIDE);
if (!expr) return NULL;
expr->a = ofc_sema_expr_copy(a);
expr->b = ofc_sema_expr_copy(b);
return expr;
}
const ofc_sema_type_t* ofc_sema_expr_type(
const ofc_sema_expr_t* expr)
{
if (!expr)
return NULL;
switch (expr->type)
{
case OFC_SEMA_EXPR_CONSTANT:
return expr->constant->type;
case OFC_SEMA_EXPR_LHS:
return ofc_sema_lhs_type(
expr->lhs);
case OFC_SEMA_EXPR_CAST:
return expr->cast.type;
case OFC_SEMA_EXPR_INTRINSIC:
return ofc_sema_intrinsic_type(
expr->intrinsic, expr->args);
case OFC_SEMA_EXPR_FUNCTION:
return ofc_sema_decl_base_type(
expr->function);
case OFC_SEMA_EXPR_IMPLICIT_DO:
case OFC_SEMA_EXPR_ARRAY:
case OFC_SEMA_EXPR_RESHAPE:
return NULL;
default:
break;
}
if (expr->type >= OFC_SEMA_EXPR_COUNT)
return NULL;
ofc_sema_expr__rule_t rule
= ofc_sema_expr__rule[expr->type];
if (rule.rtype)
return rule.rtype(
ofc_sema_expr_type(expr->a),
ofc_sema_expr_type(expr->b));
return ofc_sema_expr_type(expr->a);
}
bool ofc_sema_expr_type_is_character(
const ofc_sema_expr_t* expr)
{
if (!expr) return false;
return ofc_sema_type_is_character(
ofc_sema_expr_type(expr));
}
bool ofc_sema_expr_type_is_integer(
const ofc_sema_expr_t* expr)
{
if (!expr) return false;
return ofc_sema_type_is_integer(
ofc_sema_expr_type(expr));
}
bool ofc_sema_expr_validate_uint(
const ofc_sema_expr_t* expr)
{
if (!expr)
return false;
const ofc_sema_type_t* type
= ofc_sema_expr_type(expr);
if (!ofc_sema_type_is_integer(type))
return false;
const ofc_sema_typeval_t* tv
= ofc_sema_expr_constant(expr);
if (tv)
{
int64_t v;
bool has_val = ofc_sema_typeval_get_integer(tv, &v);
if (has_val && (v < 0)) return false;
}
return true;
}
bool ofc_sema_expr_resolve_uint(
const ofc_sema_expr_t* expr,
unsigned* value)
{
const ofc_sema_typeval_t* tv
= ofc_sema_expr_constant(expr);
if (!tv) return false;
int64_t i;
if (!ofc_sema_typeval_get_integer(tv, &i))
return false;
if (i < 0) return false;
unsigned u = i;
if (i != u)
return false;
if (value) *value = u;
return true;
}
bool ofc_sema_expr_resolve_int(
const ofc_sema_expr_t* expr,
int* value)
{
const ofc_sema_typeval_t* tv
= ofc_sema_expr_constant(expr);
if (!tv) return false;
int64_t i;
if (!ofc_sema_typeval_get_integer(tv, &i))
return false;
int d = i;
if (i != d)
return false;
if (value) *value = d;
return true;
}
static ofc_sema_expr_list_t* ofc_sema_expr__list(
ofc_sema_scope_t* scope,
const ofc_parse_expr_list_t* list,
bool allow_repeat,
bool allow_implicit_do,
bool is_label)
{
if (!list)
return NULL;
/* Label lists can never have repeats. */
if (allow_repeat && is_label)
return NULL;
ofc_sema_expr_list_t* slist
= ofc_sema_expr_list_create();
if (!slist) return NULL;
unsigned i;
for (i = 0; i < list->count; i++)
{
ofc_sema_expr_t* expr;
if (list->expr[i]->type == OFC_PARSE_EXPR_IMPLICIT_DO)
{
if (!allow_implicit_do)
{
ofc_sema_expr_list_delete(slist);
return NULL;
}
expr = ofc_sema_expr__implicit_do(scope,
list->expr[i]->src,
list->expr[i]->implicit_do);
}
else
{
if (is_label)
expr = ofc_sema_expr_label(scope, list->expr[i]);
else if (allow_repeat)
expr = ofc_sema_expr_repeat(scope, list->expr[i]);
else
expr = ofc_sema_expr(scope, list->expr[i]);
if (!expr)
{
ofc_sema_expr_list_delete(slist);
return NULL;
}
}
if (!ofc_sema_expr_list_add(slist, expr))
{
ofc_sema_expr_delete(expr);
ofc_sema_expr_list_delete(slist);
return NULL;
}
}
return slist;
}
ofc_sema_expr_list_t* ofc_sema_expr_list(
ofc_sema_scope_t* scope,
const ofc_parse_expr_list_t* list)
{
return ofc_sema_expr__list(
scope, list, false, false, false);
}
ofc_sema_expr_list_t* ofc_sema_expr_list_label(
ofc_sema_scope_t* scope,
const ofc_parse_expr_list_t* list)
{
return ofc_sema_expr__list(
scope, list, false, false, true);
}
ofc_sema_expr_list_t* ofc_sema_expr_list_clist(
ofc_sema_scope_t* scope,
const ofc_parse_expr_list_t* clist)
{
return ofc_sema_expr__list(
scope, clist, true, false, false);
}
ofc_sema_expr_list_t* ofc_sema_expr_list_io(
ofc_sema_scope_t* scope,
const ofc_parse_expr_list_t* iolist)
{
return ofc_sema_expr__list(
scope, iolist, false, true, false);
}
ofc_sema_expr_list_t* ofc_sema_expr_list_create(void)
{
ofc_sema_expr_list_t* list
= (ofc_sema_expr_list_t*)malloc(
sizeof(ofc_sema_expr_list_t));
if (!list) return NULL;
list->count = 0;
list->expr = NULL;
return list;
}
void ofc_sema_expr_list_delete(
ofc_sema_expr_list_t* list)
{
if (!list)
return;
unsigned i;
for (i = 0; i < list->count; i++)
ofc_sema_expr_delete(list->expr[i]);
free(list->expr);
free(list);
}
ofc_sema_expr_list_t* ofc_sema_expr_list_copy_replace(
const ofc_sema_expr_list_t* list,
const ofc_sema_decl_t* replace,
const ofc_sema_expr_t* with)
{
if (!list) return NULL;
ofc_sema_expr_list_t* copy
= (ofc_sema_expr_list_t*)malloc(
sizeof(ofc_sema_expr_list_t));
if (!copy) return NULL;
copy->expr = (ofc_sema_expr_t**)malloc(
(sizeof(ofc_sema_expr_t*) * list->count));
if (!copy->expr)
{
free(copy);
return NULL;
}
copy->count = list->count;
bool fail = false;
unsigned i;
for (i = 0; i < copy->count; i++)
{
const ofc_sema_expr_t* expr = list->expr[i];
copy->expr[i] = ofc_sema_expr_copy_replace(
expr, replace, with);
if (copy->expr[i] == NULL)
fail = true;
}
if (fail)
{
ofc_sema_expr_list_delete(copy);
return NULL;
}
return copy;
}
ofc_sema_expr_list_t* ofc_sema_expr_list_copy(
const ofc_sema_expr_list_t* list)
{
return ofc_sema_expr_list_copy_replace(
list, NULL, NULL);
}
bool ofc_sema_expr_list_add(
ofc_sema_expr_list_t* list,
ofc_sema_expr_t* expr)
{
if (!list || !expr)
return false;
ofc_sema_expr_t** nexpr
= (ofc_sema_expr_t**)realloc(list->expr,
(sizeof(ofc_sema_expr_t*) * (list->count + 1)));
if (!nexpr) return NULL;
list->expr = nexpr;
list->expr[list->count++] = expr;
return true;
}
unsigned ofc_sema_expr_list_count(
const ofc_sema_expr_list_t* list)
{
return (list ? list->count : 0);
}
bool ofc_sema_expr_list_elem_count(
const ofc_sema_expr_list_t* list, unsigned* count)
{
if (!list) return false;
unsigned len = 0;
unsigned i;
for (i = 0; i < list->count; i++)
{
ofc_sema_expr_t* expr
= list->expr[i];
unsigned elem_count;
if (!ofc_sema_expr_elem_count(
expr, &elem_count))
return false;
if (expr->repeat > 1)
elem_count *= expr->repeat;
len += elem_count;
}
if (count) *count = len;
return true;
}
ofc_sema_expr_t* ofc_sema_expr_list_elem_get(
const ofc_sema_expr_list_t* list, unsigned offset)
{
if (!list)
return NULL;
unsigned e = offset;
unsigned i;
for (i = 0; i < list->count; i++)
{
ofc_sema_expr_t* expr
= list->expr[i];
unsigned elem_count;
if (!ofc_sema_expr_elem_count(
expr, &elem_count))
return NULL;
unsigned elem_total = elem_count;
if (expr->repeat > 1)
elem_total *= expr->repeat;
if (e < elem_total)
{
if (elem_count == 1)
return ofc_sema_expr_copy(expr);
return ofc_sema_expr_elem_get(
expr, (e % elem_count));
}
else
{
e -= elem_total;
}
}
return NULL;
}
bool ofc_sema_expr_list_compare(
const ofc_sema_expr_list_t* a,
const ofc_sema_expr_list_t* b)
{
if (!a || !b)
return false;
if (a == b)
return true;
if (a->count != b->count)
return false;
unsigned i;
for (i = 0; i < a->count; i++)
{
if (!ofc_sema_expr_compare(
a->expr[i], b->expr[i]))
return false;
}
return true;
}
bool ofc_sema_expr_foreach(
ofc_sema_expr_t* expr, void* param,
bool (*func)(ofc_sema_expr_t* expr, void* param))
{
if (!expr || !func)
return false;
switch (expr->type)
{
case OFC_SEMA_EXPR_CONSTANT:
case OFC_SEMA_EXPR_LHS:
break;
case OFC_SEMA_EXPR_CAST:
if (expr->cast.expr
&& !func(expr->cast.expr, param))
return false;
break;
case OFC_SEMA_EXPR_INTRINSIC:
case OFC_SEMA_EXPR_FUNCTION:
if (expr->args
&& !ofc_sema_dummy_arg_list_foreach_expr(
expr->args, param, func))
return false;
break;
case OFC_SEMA_EXPR_IMPLICIT_DO:
if (expr->implicit_do.expr
&& !ofc_sema_expr_list_foreach(
expr->implicit_do.expr, param, func))
return false;
if (expr->implicit_do.init
&& !func(expr->implicit_do.init, param))
return false;
if (expr->implicit_do.last
&& !func(expr->implicit_do.last, param))
return false;
if (expr->implicit_do.step
&& !func(expr->implicit_do.step, param))
return false;
break;
case OFC_SEMA_EXPR_ARRAY:
if (!expr->array)
return true;
return ofc_sema_expr_list_foreach(
expr->array, param, func);
case OFC_SEMA_EXPR_RESHAPE:
if (!expr->reshape.source)
return true;
return ofc_sema_expr_list_foreach(
expr->reshape.source, param, func);
default:
if ((expr->a && !func(expr->a, param))
|| (expr->b && !func(expr->b, param)))
return false;
break;
}
return func(expr, param);
}
bool ofc_sema_expr_list_foreach(
ofc_sema_expr_list_t* list, void* param,
bool (*func)(ofc_sema_expr_t* expr, void* param))
{
if (!list || !func)
return false;
unsigned i;
for (i = 0; i < list->count; i++)
{
if (!ofc_sema_expr_foreach(
list->expr[i], param, func))
return false;
}
return true;
}
static const char* ofc_sema_expr__operator[] =
{
NULL, /* CONSTANT */
NULL, /* LHS */
NULL, /* CAST */
NULL, /* INTRINSIC */
NULL, /* FUNCTION */
NULL, /* IMPLICIT_DO */
NULL, /* ARRAY */
NULL, /* RESHAPE */
"**",
"*",
"//",
"/",
"+",
"-",
"-",
".EQ.",
".NE.",
".LT.",
".LE.",
".GT.",
".GE.",
".NOT.",
".AND.",
".OR.",
".XOR.",
".EQV.",
".NEQV.",
};
static bool ofc_sema_expr__root_is_constant(
const ofc_sema_expr_t* expr)
{
if (!expr) return false;
switch (expr->type)
{
case OFC_SEMA_EXPR_CONSTANT:
return true;
case OFC_SEMA_EXPR_CAST:
return ofc_sema_expr__root_is_constant(
expr->cast.expr);
default:
break;
}
return false;
}
bool ofc_sema_expr_print(
ofc_colstr_t* cs,
const ofc_sema_expr_t* expr)
{
if (!cs || !expr) return false;
if (expr->is_alt_return
&& !ofc_colstr_atomic_writef(cs, "*"))
return false;
if (expr->brackets
&& !ofc_colstr_atomic_writef(cs, "("))
return false;
switch (expr->type)
{
case OFC_SEMA_EXPR_CONSTANT:
if (!ofc_sema_typeval_print(cs, expr->constant))
return false;
break;
case OFC_SEMA_EXPR_LHS:
if (!ofc_sema_lhs_print(cs, expr->lhs))
return false;
break;
case OFC_SEMA_EXPR_CAST:
{
bool print_const = (expr->constant
&& ofc_sema_typeval_can_print(expr->constant)
&& ofc_sema_expr__root_is_constant(expr->cast.expr));
if (print_const
&& ofc_sema_expr_type_is_character(expr->cast.expr)
&& !ofc_sema_expr_type_is_character(expr))
print_const = false;
if (print_const
? !ofc_sema_typeval_print(cs, expr->constant)
: !ofc_sema_expr_print(cs, expr->cast.expr))
return false;
break;
}
case OFC_SEMA_EXPR_INTRINSIC:
if(!ofc_sema_intrinsic_print(cs, expr->intrinsic)
|| !ofc_colstr_atomic_writef(cs, "(")
|| !ofc_sema_dummy_arg_list_print(cs, expr->args)
|| !ofc_colstr_atomic_writef(cs, ")"))
return false;
break;
case OFC_SEMA_EXPR_FUNCTION:
if (!ofc_sema_decl_print_name(cs, expr->function)
|| !ofc_colstr_atomic_writef(cs, "(")
|| (expr->args && !ofc_sema_dummy_arg_list_print(cs, expr->args))
|| !ofc_colstr_atomic_writef(cs, ")"))
return false;
break;
case OFC_SEMA_EXPR_IMPLICIT_DO:
if (!ofc_colstr_atomic_writef(cs, "(")
|| !ofc_sema_expr_list_print(cs, expr->implicit_do.expr)
|| !ofc_colstr_atomic_writef(cs, ",")
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_sema_decl_print_name(cs, expr->implicit_do.iter)
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_colstr_atomic_writef(cs, "=")
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_sema_expr_print(cs, expr->implicit_do.init)
|| !ofc_colstr_atomic_writef(cs, ",")
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_sema_expr_print(cs, expr->implicit_do.last))
return false;
if (expr->implicit_do.step)
{
if (!ofc_colstr_atomic_writef(cs, ",")
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_sema_expr_print(cs, expr->implicit_do.step))
return false;
}
if (!ofc_colstr_atomic_writef(cs, ")"))
return false;
break;
case OFC_SEMA_EXPR_ARRAY:
if (!ofc_colstr_atomic_writef(cs, "(/")
|| !ofc_colstr_atomic_writef(cs, " "))
return false;
if (expr->array && !ofc_sema_expr_list_print(cs, expr->array))
return false;
if (!ofc_colstr_atomic_writef(cs, " ")
|| !ofc_colstr_atomic_writef(cs, "/)"))
return false;
break;
case OFC_SEMA_EXPR_RESHAPE:
return ofc_colstr_keyword_atomic_writez(cs, "RESHAPE")
&& ofc_colstr_atomic_writef(cs, "(")
&& ofc_colstr_atomic_writef(cs, "(/")
&& ofc_colstr_atomic_writef(cs, " ")
&& ofc_sema_expr_list_print(cs, expr->reshape.source)
&& ofc_colstr_atomic_writef(cs, ",")
&& ofc_colstr_atomic_writef(cs, " ")
&& ofc_colstr_atomic_writef(cs, "(/")
&& ofc_colstr_atomic_writef(cs, " ")
&& ofc_sema_array_print(cs, expr->reshape.shape)
&& ofc_colstr_atomic_writef(cs, " ")
&& ofc_colstr_atomic_writef(cs, "/)")
&& ofc_colstr_atomic_writef(cs, ")");
default:
if (expr->type >= OFC_SEMA_EXPR_COUNT)
return false;
if (expr->b)
{
/* Print binary expression */
if (!ofc_sema_expr_print(cs, expr->a)
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_colstr_keyword_atomic_writez(cs,
ofc_sema_expr__operator[expr->type])
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_sema_expr_print(cs, expr->b))
return false;
}
else
{
/* Print unary expression */
if (!ofc_colstr_keyword_atomic_writez(cs,
ofc_sema_expr__operator[expr->type])
|| !ofc_colstr_atomic_writef(cs, " ")
|| !ofc_sema_expr_print(cs, expr->a))
return false;
}
break;
}
if (expr->brackets
&& !ofc_colstr_atomic_writef(cs, ")"))
return false;
return true;
}
bool ofc_sema_expr_list_print(
ofc_colstr_t* cs,
const ofc_sema_expr_list_t* expr_list)
{
if (!cs || !expr_list) return false;
unsigned i;
for (i = 0; i < expr_list->count; i++)
{
if (!ofc_sema_expr_print(cs, expr_list->expr[i]))
return false;
if ((expr_list->count > 1)
&& (i < expr_list->count - 1))
{
if (!ofc_colstr_atomic_writef(cs, ", "))
return false;
}
}
return true;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 105
int map_in[MAX][MAX] = {{0}};
int map_out[MAX][MAX] = {{0}};
void printout(int term,int n, int m);
int main(void)
{
//freopen("testout.txt","w+",stdout);
int i, j;
int m,n;
int term;
scanf("%d",&term);
while(term--)
{
memset(map_out,0x00,sizeof(int)*MAX*MAX);
memset(map_in,-1,sizeof(int)*MAX*MAX);
scanf("%d %d",&n,&m);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
scanf("%d",&map_in[i+1][j+1]);
}
printout(term,n,m);
}
return 0;
}
void printout(int term, int n, int m)
{
int ok;
int i, j;
for(i=1;i<n+1;i++)
{
for(j=1;j<m+1;j++)
{
if(map_in[i][j]==1)
{
ok = 0;
if(map_in[i+1][j]==0)
ok = 1;
else if(map_in[i-1][j]==0)
ok = 1;
else if(map_in[i][j+1]==0)
ok = 1;
else if(map_in[i][j-1]==0)
ok = 1;
else
ok = 0;
if(ok == 1)
map_out[i-1][j-1] = 1;
}
}
}
#if 0
for(i=0;i<n;i++) /*For debugging*/
{
for(j=0;j<m;j++)
printf("%d",map_out[i][j]);
printf("\n");
}
#endif
for(i=0;i<n;i++)
{
if(i>0)
printf("\n");
for(j=0;j<m;j++)
{
if(j>0)
printf(" ");
if(map_out[i][j]==1)
printf("0");
else
printf("_");
}
}
if(term>0)
printf("\n\n");
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char logged_in_name[20];
char logged_in_id[20];
int login_status;
int reg_status;
void user_login();
int teacher_select();
void logout();
void ratting_check(int n)
{
FILE *ratt_fp;
char ratt_name[20], temp;
int ratt_num, ratt_sum = 0, len, count = 0;
double avg_ratt = 0.00;
if(n == 1)
{
printf("\nShowing ratting for (Mahabub Alom sir): \n");
printf("--------------------------------------\n\n");
ratt_fp = fopen("Data_File\\rattingT1.txt", "r");
}
else if(n == 2)
{
printf("\nShowing review for (Milon Biswas sir): \n");
printf("--------------------------------------\n\n");
ratt_fp = fopen("Data_File\\rattingT2.txt", "r");
}
else
{
printf("\nShowing review for (Shamim Reza sir): \n");
printf("-------------------------------------\n\n");
ratt_fp = fopen("Data_File\\rattingT3.txt", "r");
}
if(!ratt_fp)
{
perror("\n\nFile opening failed!");
exit(1);
}
printf("\nGiven Name\t\tRatting(out of 10)");
printf("\n----------- ------------------");
while(1)
{
fgets(ratt_name, 20, ratt_fp);
fscanf(ratt_fp, "%d", &ratt_num);
if(fscanf(ratt_fp, "%c", &temp) == EOF)
break;
ratt_name[strlen(ratt_name) - 1] = '\0';
printf("\n%s", ratt_name);
len = 20 - strlen(ratt_name);
while(len--)
{
printf(" ");
}
printf("\t\t%d", ratt_num);
ratt_sum += ratt_num;
count++;
}
if(ratt_sum > 0)
avg_ratt = (double)ratt_sum / (double)count;
printf("\n\n>>> Average ratting(Out of 10): ");
printf("%0.2lf <<<", avg_ratt);
fclose(ratt_fp);
}
int check_ratted(int n)
{
FILE *ratted_fp;
char file_id[12], local_logged_id[20];
int i = 0;
while(logged_in_id[i] != '\n' && logged_in_id[i] != '\0')
{
local_logged_id[i] = logged_in_id[i];
i++;
}
if(n == 1)
{
ratted_fp = fopen("Data_File\\ratted_idT1.txt", "r");
}
if(n == 2)
{
ratted_fp = fopen("Data_File\\ratted_idT2.txt", "r");
}
if(n == 3)
{
ratted_fp = fopen("Data_File\\ratted_idT3.txt", "r");
}
if(!ratted_fp)
{
perror("File opening_failed");
exit(1);
}
while(fscanf(ratted_fp, "%s", file_id) != EOF)
{
//printf("\nLogged in id: %s\tFile id: %s\n", logged_in_id, file_id);
if(!strcmp(local_logged_id, file_id))
{
printf("\n\nSorry!This ID already used for this teacher ratting");
printf("\n---------------------------------------------------");
fclose(ratted_fp);
return 1;
}
}
fclose(ratted_fp);
return 0;
}
void input_ratting(int n)
{
FILE *ratt_fp, *ratted_id_fp;
int ratt_num;
double temp_ratt_no;
if(n == 1)
{
printf("\nInput ratting for (Mahabub Alom sir): \n");
printf("--------------------------------------\n");
ratt_fp = fopen("Data_File\\rattingT1.txt", "a+");
ratted_id_fp = fopen("Data_File\\ratted_idT1.txt", "a+");
}
else if(n == 2)
{
printf("\nInput ratting for (Milon Biswas sir): \n");
printf("--------------------------------------\n");
ratt_fp = fopen("Data_File\\rattingT2.txt", "a+");
ratted_id_fp = fopen("Data_File\\ratted_idT2.txt", "a+");
}
else
{
printf("\nInput ratting for (Shamim Reza sir): \n");
printf("-------------------------------------");
ratt_fp = fopen("Data_File\\rattingT3.txt", "a+");
ratted_id_fp = fopen("Data_File\\ratted_idT3.txt", "a+");
}
if(!ratt_fp)
{
perror("\n\nFile opening failed!");
exit(1);
}
if(!ratted_id_fp)
{
perror("\n\nFile opening failed!");
exit(1);
}
if(check_ratted(n))
{
fclose(ratted_id_fp);
fclose(ratt_fp);
return ;
}
while(1)
{
printf("\n\nRatting(Only int 0 to 10): ");
scanf("%lf", &temp_ratt_no);
if(temp_ratt_no >= 0.00 && temp_ratt_no <= 10.00)
break;
}
ratt_num = (int)temp_ratt_no;
fprintf(ratt_fp, "%s", logged_in_name);
fprintf(ratt_fp, "%d\n", ratt_num);
fprintf(ratted_id_fp, "%s\n", logged_in_id);
printf("\n\nRatting added Successfully");
printf("\n---------------------------");
fclose(ratt_fp);
fclose(ratted_id_fp);
}
void ratting()
{
int menu_input, tech_select;
printf("\nRatting: ");
printf("\n-------");
while(1)
{
printf("\n\n1.Check ratting\n2.Input ratting\n0.Main menu\n\n>_");
scanf("%d", &menu_input);
if(menu_input == 0)
{
return ;
}
if(menu_input == 1)
{
printf("\n\nCheck ratting");
printf("\n-------------");
tech_select = teacher_select();
if(tech_select)
{
ratting_check(tech_select);
}
else
{
return ;
}
}
else if(menu_input == 2)
{
printf("\n\nInput ratting");
printf("\n-------------");
if(login_status == 0)
user_login();
else
{
printf("\n\nContinue as: %s", logged_in_name);
logout();
}
if(login_status == 0 && reg_status == 0)
return ;
if(strlen(logged_in_name))
{
tech_select = teacher_select();
if(tech_select)
{
input_ratting(tech_select);
}
else
{
return ;
}
}
}
else if(menu_input != 1 && menu_input != 2)
{
printf("\n\nWrong input!");
}
}
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* _strchr - Locates a character in a string.
* @s: Variable with the string input.
* @c: Variable that contain the char to locate.
* Return: c, pointer to initial value.
*/
char *_strchr(char *s, char c)
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (*(s + i) == c)
return (&s[i]);
}
if (c == '\0')
{
return (&s[i]);
}
return (NULL);
}
|
C
|
//
// cube.c
//
//
// Created by Simon Boigelot & Edward Nicol on 29/04/2015.
//
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct {
int *elem;
double *X;
double *Y;
double *Z;
int nElem;
int nNode;
int nLocalNode;
} femMesh;
femMesh *femMeshRead(const char *filename)
{
femMesh *theMesh = malloc(sizeof(femMesh));
int i,trash,*elem;
FILE* file = fopen(filename,"r");
if (file == NULL) printf ("No mesh file !");
if (!fscanf(file, "Number of nodes %d \n", &theMesh->nNode)) printf("Cannot read the number of nodes\n");
theMesh->X = malloc(sizeof(double)*theMesh->nNode);
theMesh->Y = malloc(sizeof(double)*theMesh->nNode);
theMesh->Z = malloc(sizeof(double)*theMesh->nNode);
for (i = 0; i < theMesh->nNode; ++i) {
if (!fscanf(file,"%d : %le %le %le \n",&trash,&theMesh->X[i],&theMesh->Y[i], &theMesh->Z[i])) printf("Cannot read node %d\n", i); }
char str[256]; if (!fgets(str, sizeof(str), file)) printf("Error while reading the mesh file !\n");
if (!strncmp(str,"Number of triangles",19)) {
if (!sscanf(str,"Number of triangles %d \n", &theMesh->nElem)) printf("Cannot read the number of elements\n");
theMesh->elem = malloc(sizeof(int)*3*theMesh->nElem);
theMesh->nLocalNode = 3;
for (i = 0; i < theMesh->nElem; ++i) {
elem = &(theMesh->elem[i*3]);
if(!fscanf(file,"%d : %d %d %d\n", &trash,&elem[0],&elem[1],&elem[2])) printf("Cannot read element %d\n", i); }}
else if (!strncmp(str,"Number of quads",15)) {
if (!sscanf(str,"Number of quads %d \n", &theMesh->nElem))printf("Cannot read the number of elements\n");
theMesh->elem = malloc(sizeof(int)*4*theMesh->nElem);
theMesh->nLocalNode = 4;
for (i = 0; i < theMesh->nElem; ++i) {
elem = &(theMesh->elem[i*4]);
if (!fscanf(file,"%d : %d %d %d %d\n", &trash,&elem[0],&elem[1],&elem[2],&elem[3])) printf("Cannot read element %d\n", i); }}
else if (!strncmp(str,"Number of tetrahedra",20)) {
if (!sscanf(str,"Number of tetrahedra %d \n", &theMesh->nElem)) printf("Cannot read the number of elements\n");
theMesh->elem = malloc(sizeof(int)*4*theMesh->nElem);
theMesh->nLocalNode = 4;
for (i = 0; i < theMesh->nElem; ++i) {
elem = &(theMesh->elem[i*4]);
if (!fscanf(file,"%d : %d %d %d %d\n", &trash,&elem[0],&elem[1],&elem[2],&elem[3])) printf("Cannot read element %d\n", i); }}
fclose(file);
return theMesh;
}
void femMeshFree(femMesh *theMesh)
{
free(theMesh->X);
free(theMesh->Y);
free(theMesh->Z);
free(theMesh->elem);
free(theMesh);
}
typedef struct
{
double *R;
double *R0;
double *D;
double *D0;
double *AD;
double *AD0;
double error;
int size;
int iter;
} femIterativeSolver;
void femIterativeSolverInit(femIterativeSolver *mySolver)
{
int i;
mySolver->iter = 0;
mySolver->error = 10.0e+12;
for (i=0 ; i < mySolver->size*6 ; i++)
mySolver->R[i] = 0;
}
femIterativeSolver *femIterativeSolverCreate(int size)
{
femIterativeSolver *mySolver = malloc(sizeof(femIterativeSolver));
mySolver->R = malloc(sizeof(double)*size*6);
mySolver->R0 = mySolver->R + size;
mySolver->D = mySolver->R + size*2;
mySolver->D0 = mySolver->R + size*3;
mySolver->AD = mySolver->R + size*4;
mySolver->AD0 = mySolver->R + size*5;
mySolver->size = size;
femIterativeSolverInit(mySolver);
return(mySolver);
}
void femIterativeSolverFree(femIterativeSolver *mySolver)
{
free(mySolver->R);
free(mySolver);
}
int femIterativeSolverConverged(femIterativeSolver *mySolver)
{
int testConvergence = 0;
if (mySolver->iter > 3000) testConvergence = -1;
if (mySolver->error < 10.0e-6) testConvergence = 1;
return(testConvergence);
}
typedef struct
{
int elem[2];
int node[3];
}femEdge;
typedef struct
{
femMesh *theMesh;
femEdge *edges;
int nEdge;
int nBoundary;
}femEdges;
int fmid (int n1, int n2, int n3)
{
int diff1 = n1 - n2;
int diff2 = n1 - n3;
if ((diff1>0 || diff2>0) && diff1*diff2 <0)
{
return n1;
}
else if (diff1 < 0 && diff2 < 0)
{
return fmin(n2, n3);
}
else
{
return fmax(n2, n3);
}
}
int femEdgesCompare(const void *edgeOne, const void *edgeTwo)
{
int *nodeOne = ((femEdge*) edgeOne)->node;
int *nodeTwo = ((femEdge*) edgeTwo)->node;
int diffMin = fmin(fmin(nodeOne[0],nodeOne[1]),nodeOne[2]) - fmin(fmin(nodeTwo[0],nodeTwo[1]),nodeTwo[2]);
int diffMax = fmax(fmax(nodeOne[0],nodeOne[1]),nodeOne[2]) - fmax(fmax(nodeTwo[0],nodeTwo[1]),nodeTwo[2]);
int diffMid = fmid(nodeOne[0], nodeOne[1], nodeOne[2]) - fmid(nodeTwo[0], nodeTwo[1], nodeTwo[2]);
if (diffMin < 0) return 1;
if (diffMin > 0) return -1;
if (diffMid < 0) return 1;
if (diffMid > 0) return -1;
if (diffMax < 0) return 1;
if (diffMax > 0) return -1;
return 0;
}
femEdges* femEdgesCreate(femMesh *theMesh)
{
femEdges *theEdges = malloc(sizeof(femEdges));
int nLoc = theMesh->nLocalNode;
int i,j,n = theMesh->nElem * nLoc;
femEdge* edges = malloc(n * sizeof(femEdge));
theEdges->theMesh = theMesh;
theEdges->edges = edges;
theEdges->nEdge = n;
theEdges->nBoundary = n;
for (i = 0; i < theMesh->nElem; i++)
{
int *elem = &(theMesh->elem[i*nLoc]);
for (j = 0; j < nLoc; j++)
{
int id = i * nLoc + j;
edges[id].elem[0] = i;
edges[id].elem[1] = -1;
edges[id].node[0] = elem[j];
edges[id].node[1] = elem[(j + 1) % nLoc];
edges[id].node[2] = elem[(j + 2) % nLoc];
}
}
qsort(theEdges->edges, theEdges->nEdge, sizeof(femEdge), femEdgesCompare);
int index = 0;
int nBoundary = 0;
for (i=0; i < theEdges->nEdge; i++)
{
if (i == theEdges->nEdge - 1 || femEdgesCompare(&edges[i],&edges[i+1]) != 0)
{
edges[index] = edges[i];
nBoundary++;
}
else
{
edges[index] = edges[i];
edges[index].elem[1] = edges[i+1].elem[0];
i ++;
}
index++;
}
theEdges->edges = realloc(edges, index * sizeof(femEdge));
theEdges->nEdge = index;
theEdges->nBoundary = nBoundary;
return theEdges;
}
void femEdgesFree(femEdges* theEdges)
{
free(theEdges->edges);
free(theEdges);
}
typedef struct
{
femIterativeSolver* theSolver;
femMesh* theMesh;
int size;
double* soluce;
femEdges* theEdges;
} femProblem;
femProblem* femProblemCreate(const char *meshFileName)
{
femProblem *theProblem = malloc(sizeof(femProblem));
theProblem->theMesh = femMeshRead(meshFileName);
theProblem->size = theProblem->theMesh->nNode*3;
theProblem->theSolver = femIterativeSolverCreate(theProblem->size);
theProblem->theEdges = femEdgesCreate(theProblem->theMesh);
theProblem->soluce = malloc(sizeof(double)*theProblem->size);
int i;
for (i = 0; i < theProblem->size; i++)
{
theProblem->soluce[i] = 0;
}
return theProblem;
}
void femProblemFree(femProblem* theProblem)
{
femMeshFree(theProblem->theMesh);
femIterativeSolverFree(theProblem->theSolver);
femEdgesFree(theProblem->theEdges);
free(theProblem->soluce);
free(theProblem);
}
void tetrahedraXsi(double Xsi[4], double Eta[4], double Zet[4])
{
Xsi[0] = 0.0; Eta[0] = 0.0, Zet[0] = 0.0;
Xsi[1] = 1.0; Eta[1] = 0.0, Zet[1] = 0.0;
Xsi[2] = 0.0; Eta[2] = 1.0, Zet[2] = 0.0;
Xsi[3] = 0.0; Eta[3] = 0.0, Zet[3] = 1.0;
}
void tetrahedraPhi(double xsi, double eta, double zet, double phi[4])
{
phi[0] = 1.0 - xsi - eta - zet;
phi[1] = xsi;
phi[2] = eta;
phi[3] = zet;
}
void tetrahedraDphi(double xsi, double eta, double zet, double dphidxsi[4],double dphideta[4],double dphidzet[4])
{
dphidxsi[0] = -1.0; dphideta[0] = -1.0; dphidzet[0] = -1.0;
dphidxsi[1] = 1.0; dphideta[1] = 0.0; dphidzet[1] = 0.0;
dphidxsi[2] = 0.0; dphideta[2] = 1.0; dphidzet[2] = 0.0;
dphidxsi[3] = 0.0; dphideta[3] = 0.0; dphidzet[3] = 1.0;
}
/*
* direction:
* 0 = u
* 1 = v
* 2 = w
* 3 = contrainte de colonne
*/
void cubeConstrain (femProblem* theProblem, int myNode, int myValue, int direction)
{
femIterativeSolver* theSolver = theProblem->theSolver;
if (direction == 3)
{
theSolver->R0[myNode] = 0;
theSolver->D0[myNode] = 0;
theSolver->AD0[myNode] = 0;
theSolver->R0[myNode+theProblem->theMesh->nNode] = 0;
theSolver->D0[myNode+theProblem->theMesh->nNode] = 0;
theSolver->AD0[myNode+theProblem->theMesh->nNode] = 0;
theSolver->R0[myNode+2*theProblem->theMesh->nNode] = myValue;
theSolver->D0[myNode+2*theProblem->theMesh->nNode] = myValue;
theSolver->AD0[myNode+2*theProblem->theMesh->nNode] = myValue;
}
else
{
theSolver->R0[myNode+direction*theProblem->theMesh->nNode] = myValue;
theSolver->D0[myNode+direction*theProblem->theMesh->nNode] = myValue;
theSolver->AD0[myNode+direction*theProblem->theMesh->nNode] = myValue;
}
}
double MaxError(double *tab, int size)
{
int i;
double max = tab[0];
for(i=1;i<size;i++)
{
if(tab[i] >= max) max = tab[i];
}
return max;
}
/*
* Elimination suivant la methode des gradients conjugues
* Copier-Coller de la soluce du devoir 5 :-)
*/
double *femIterativeSolverEliminate(femIterativeSolver *mySolver)
{
mySolver->iter++;
//double error = 0.0;
double residus = 0.0;
double error[mySolver->size];
int i;
double denAlpha = 0.0;
for (i=0; i < mySolver->size; i++)
{
//error += (mySolver->R0[i])*(mySolver->R0[i]);
residus += (mySolver->R0[i])*(mySolver->R0[i]);
error[i] = (mySolver->R0[i])-(mySolver->R0[i]);
denAlpha += mySolver->D0[i] * mySolver->AD0[i];
}
//double alpha = error/denAlpha;
double alpha = residus/denAlpha;
if (mySolver->iter == 1)
{
for (i=0; i < mySolver->size; i++)
{
mySolver->R[i] = 0.0;
}
}
else
{
double numBeta = 0.0;
for (i=0; i < mySolver->size; i++)
{
mySolver->R[i] = alpha * mySolver->D0[i];
mySolver->R0[i] = mySolver->R0[i] - alpha * mySolver->AD0[i];
numBeta += mySolver->R0[i] * mySolver->R0[i];
mySolver->AD[i] = 0.0;
}
//double beta = numBeta/error;
double beta = numBeta/residus;
for (i=0; i < mySolver->size; i++)
{
mySolver->AD0[i] = 0.0;
mySolver->D0[i] = mySolver->R0[i] + beta * mySolver->D0[i];
}
}
//mySolver->error = sqrt(error);
mySolver->error = MaxError(error,mySolver->size);
return(mySolver->R);
}
void cubeEliminate (femProblem* theProblem, double alpha, double E, double nu, double *U, double *V, double *W)
{
femMesh* theMesh = theProblem->theMesh;
femIterativeSolver* theSolver = theProblem->theSolver;
int size = theProblem->size;
int iElem,i,iEdge, nLocalNode = theMesh->nLocalNode, index;
double X[nLocalNode], Y[nLocalNode], Z[nLocalNode], Uloc[nLocalNode], Vloc[nLocalNode], Wloc[nLocalNode];
int map[nLocalNode];
double xsi, eta, zet, weight;
double dxdxsi, dxdeta, dxdzet, dydxsi, dydeta, dydzet, dzdxsi, dzdeta, dzdzet;
double ajac;
double dphidxsi[nLocalNode], dphideta[nLocalNode], dphidzet[nLocalNode];
double dphidx[nLocalNode], dphidy[nLocalNode], dphidz[nLocalNode];
const double a = E/(2*(1+nu));
const double b = 2*a;
const double c = E*nu/((1+nu)*(1-2*nu));
double dudx, dudy, dudz, dvdx, dvdy, dvdz, dwdx, dwdy, dwdz;
double dD1dx, dD1dy, dD1dz, dD2dx, dD2dy, dD2dz, dD3dx, dD3dy, dD3dz;
double *D0 = theSolver->D0;
double *AD0 = theSolver->AD0;
double *R0 = theSolver->R0;
for (iElem=0; iElem<size; iElem++)
{
for (i=0; i<nLocalNode; i++)
{
map[i] = theMesh->elem[iElem*nLocalNode+i];
X[i] = theMesh->X[map[i]];
Y[i] = theMesh->Y[map[i]];
Z[i] = theMesh->Z[map[i]];
Uloc[i] = U[map[i]];
Vloc[i] = V[map[i]];
Wloc[i] = W[map[i]];
}
xsi = 1.0/4.0;
eta = 1.0/4.0;
zet = 1.0/4.0;
weight = 1.0/6.0;
tetrahedraDphi(xsi,eta,zet,dphidxsi,dphideta,dphidzet);
dxdxsi = 0.0;
dxdeta = 0.0;
dxdzet = 0.0;
dydxsi = 0.0;
dydeta = 0.0;
dydzet = 0.0;
dzdxsi = 0.0;
dzdeta = 0.0;
dzdzet = 0.0;
for(i=0; i<nLocalNode; i++)
{
dxdxsi += X[i] * dphidxsi[i];
dydxsi += Y[i] * dphidxsi[i];
dzdxsi += Z[i] * dphidxsi[i];
dxdeta += X[i] * dphideta[i];
dydeta += Y[i] * dphideta[i];
dzdeta += Z[i] * dphideta[i];
dxdzet += X[i] * dphidzet[i];
dydzet += Y[i] * dphidzet[i];
dzdzet += Z[i] * dphidzet[i];
}
ajac = dxdxsi * dydeta * dzdzet + dxdeta * dydzet * dzdxsi + dxdzet * dydxsi * dzdeta - dzdxsi * dydeta * dxdzet - dxdxsi * dzdeta * dydzet - dydxsi * dxdeta * dzdzet;
ajac = fabs(ajac);
for (i=0; i<nLocalNode; i++)
{
dphidx[i] = (dphidxsi[i]*(dydeta*dzdzet-dydzet*dzdeta)+dphideta[i]*(dydzet*dzdxsi-dydxsi*dzdzet)+dphidzet[i]*(dydxsi*dzdeta-dydeta*dzdxsi))/ajac;
dphidy[i] = (dphidxsi[i]*(dxdzet*dzdeta-dxdeta*dzdzet)+dphideta[i]*(dxdxsi*dzdzet-dxdzet*dzdxsi)+dphidzet[i]*(dxdeta*dzdxsi-dxdxsi*dzdeta))/ajac;
dphidz[i] = (dphidxsi[i]*(dxdeta*dydzet-dxdzet*dydeta)+dphideta[i]*(dxdzet*dydxsi-dxdxsi*dydzet)+dphidzet[i]*(dxdxsi*dydeta-dxdeta*dydxsi))/ajac;
}
if (theSolver->iter==0)
{
dudx=0, dudy=0, dudz=0, dvdx=0, dvdy=0, dvdz=0, dwdx=0, dwdy=0, dwdz=0;
for (i=0; i<nLocalNode; i++)
{
dudx += Uloc[i]*dphidx[i];
dudy += Uloc[i]*dphidy[i];
dudz += Uloc[i]*dphidz[i];
dvdx += Vloc[i]*dphidx[i];
dvdy += Vloc[i]*dphidy[i];
dvdz += Vloc[i]*dphidz[i];
dwdx += Wloc[i]*dphidx[i];
dwdy += Wloc[i]*dphidy[i];
dwdz += Wloc[i]*dphidz[i];
}
for (i=0; i<nLocalNode; i++)
{
index = map[i];
D0[index] -= (b*dphidx[i]*dudx + c*(dphidx[i]*(dudx+dvdy+dwdz))+a*(dphidy[i]*(dudy+dvdx))+a*(dphidz[i]*(dudz+dwdx)))*ajac*weight;
D0[index+size/3] -= (a*(dphidx[i]*(dudy+dvdx))+b*dphidy[i]*dvdy+c*(dphidy[i]*(dudx+dvdy+dwdz))+a*(dphidz[i]*(dvdz+dwdx)))*ajac*weight;
D0[index+size*2/3] -= (a*(dphidx[i]*(dudz+dwdx))+a*(dphidy[i]*(dvdz+dwdy))+b*dphidz[i]*dwdz+c*(dphidz[i]*(dudx+dvdy+dwdz)))*ajac*weight;
}
for (i=0; i<nLocalNode; i++)
{
index = map[i];
R0[index] = D0[index];
R0[index+size/3] = D0[index+size/3];
R0[index+size*2/3] = D0[index+size*2/3];
}
}
else
{
dD1dx=0, dD1dy=0, dD1dz=0, dD2dx=0, dD2dy=0, dD2dz=0, dD3dx=0, dD3dy=0, dD3dz=0;
for (i=0; i<nLocalNode; i++)
{
index = map[i];
dD1dx += D0[index]*dphidx[i]; //partie "en U"
dD1dy += D0[index]*dphidy[i];
dD1dz += D0[index]*dphidz[i];
dD2dx += D0[index+size/3]*dphidx[i]; //partie "en V"
dD2dy += D0[index+size/3]*dphidy[i];
dD2dz += D0[index+size/3]*dphidz[i];
dD3dx += D0[index+size*2/3]*dphidx[i]; //partie "en W"
dD3dy += D0[index+size*2/3]*dphidy[i];
dD3dz += D0[index+size*2/3]*dphidz[i];
}
for (i=0; i<nLocalNode; i++)
{
index = map[i];
AD0[index] += (b*dphidx[i]*dD1dx + c*(dphidx[i]*(dD1dx+dD2dy+dD3dz))+a*(dphidy[i]*(dD1dy+dD2dx))+a*(dphidz[i]*(dD1dz+dD3dx)))*ajac*weight;
AD0[index+size/3] += (a*(dphidx[i]*(dD1dy+dD2dx))+b*dphidy[i]*dD2dy+c*(dphidy[i]*(dD1dx+dD2dy+dD3dz))+a*(dphidz[i]*(dD2dz+dD3dx)))*ajac*weight;
AD0[index+size*2/3] += (a*(dphidx[i]*(dD1dz+dD3dx))+a*(dphidy[i]*(dD2dz+dD3dy))+b*dphidz[i]*dD3dz+c*(dphidz[i]*(dD1dx+dD2dy+dD3dz)))*ajac*weight;
}
}
} // Fin assemblage -> fin boucle iElem
/*
*
* Appliquer les contraintes sur D0 R0 AD0 :-)
*
*
*/
/*
for (i=0; i<size; i++)
{
printf("R0[%d] = %f\n",i, R0[i]);
}*/
/*
for (i=0; i<size; i++)
{
printf("R0[%d] = %f\n",i, R0[i]);
}*/
/*
* Elimination suivant la methode des gradients conjugues
* Copier-Coller de la soluce du devoir 5 :-)
*/
}
void cubeCompute(double alpha, double E, double nu, const char *meshFileName, double *U, double *V, double *W)
{
femProblem* theProblem = femProblemCreate(meshFileName);
femMesh* theMesh = femMeshRead(meshFileName);
femIterativeSolver *theSolver = theProblem->theSolver;
int testConvergence, i, iEdge, nNode = theMesh->nNode, iter=0;
do
{
/*
* Application des contraintes
*/
for (iEdge=0; iEdge<theProblem->theEdges->nEdge; iEdge++)
{
femEdge edge = theProblem->theEdges->edges[iEdge];
if (edge.elem[1]==-1)
{
for (i=0; i<3; i++)
{
if (theMesh->X[edge.node[i] == 0])
{
cubeConstrain(theProblem, edge.node[i], 0, 0);
}
if (theMesh->Y[edge.node[i] == 0])
{
cubeConstrain(theProblem, edge.node[i], 0, 1);
}
if (theMesh->Z[edge.node[i] == 0])
{
cubeConstrain(theProblem, edge.node[i], 0, 2);
}
if (theMesh->Z[edge.node[i]] == 1 && theMesh->X[edge.node[i]]<=4/10 && theMesh->Y[edge.node[i]]<=4/10)
{
cubeConstrain(theProblem, edge.node[i], alpha, 3);
}
}
}
double *soluce = femIterativeSolverEliminate(theSolver);
for (i = 0; i < theProblem->theMesh->nNode; i++)
{
// vecteur a redecomposer en U, V, W a la fin
theProblem->soluce[i] += soluce[i];
}
}
cubeEliminate(theProblem, alpha, E, nu, U, V, W);
testConvergence = femIterativeSolverConverged(theProblem->theSolver);
iter++;
}
while (testConvergence==0);
if(testConvergence==1) printf("Cool :-)\n");
if(testConvergence == -1) printf("No convergence in %d steps",3000);
/*
for (i=0; i<nNode; i++)
{
printf("U[%d] = %f\n",i, U[i]);
}*/
for (i=0; i<nNode; i++)
{
U[i] = theProblem->soluce[i];
V[i] = theProblem->soluce[i+nNode];
W[i] = theProblem->soluce[i+2*nNode];
}
printf("Number of iterations %d\n", iter);
for (i=0; i<nNode; i++)
{
printf("U[%d] = %f\n",i, U[i]);
}
free(theMesh);
femProblemFree(theProblem);
}
|
C
|
bool isAnagram(char* s, char* t) {
int bitMaps[26] = {0}, bitMapt[26] = {0}, lens = strlen(s), lent = strlen(t), i = 0, j = 0;
bool res = false;
if (lens != lent)
goto ret;
while (1) {
if (i != lens)
bitMaps[s[i++]-'a']++;
if (j != lent)
bitMapt[t[j++]-'a']++;
if (i == lens && j == lens)
break;
}
res = memcmp(bitMaps, bitMapt, sizeof(bitMaps)) == 0 ? true : false;
ret:
return res;
}
|
C
|
// Compile this assignment with: gcc main.c -o main
//
// Include parts of the C Standard Library
// These have been written by some other really
// smart engineers.
#include <stdio.h> // For IO operations
#include <stdlib.h> // for malloc/free
// Our library that we have written.
// Also, by a really smart engineer!
#include "my_graph.h"
// Note that we are locating this file
// within the same directory, so we use quotations
// and provide the path to this file which is within
// our current directory.
int main(int argc, const char * argv[]) {
graph_t * graph = create_graph();
graph_add_node(graph, 1);
printf("here %d\n", print_path(graph, 1, 53));
printf("here %d\n", has_cycle(graph));
printf("here %d \n", is_reachable(graph, 1, 53));
//printf("cycle is %d\n", print_path(graph, 5, 7));
graph_add_node(graph, 1);
graph_add_node(graph, 2);
graph_add_node(graph, 3);
graph_add_node(graph, 4);
graph_add_node(graph, 5);
graph_add_node(graph,6);
graph_add_node(graph,7);
//graph_add_edge(graph,1,7);
graph_add_edge(graph,1,2);
graph_add_edge(graph,2,4);
graph_add_edge(graph,2,3);
graph_add_edge(graph,3,5);
graph_add_edge(graph,3,6);
graph_add_edge(graph,6,7);
graph_add_node(graph, 9);
graph_add_edge(graph,7,1);
//graph_add_edge(graph, 9, 9);
print_graph(graph);
//printf("%d \n", is_reachable(graph, 4, 3));
printf("Path is %d\n", print_path(graph, 5,7));
free_graph(graph);
return 0;
}
|
C
|
/*******************************************************************
*
* @FileName Data_Process.c
* @Date 2017.03.03
* @Author DS.Chin
*
*********************************************************************/
#include "Data_Process.h"
/* @Gloable Variables --------------------------------------*/
_Flag NetChgFlag;
/* @File Variables -----------------------------------------*/
_Flag TamperCloseFlag;
_Flag ConnectFlag;
_Flag SensorFlag;
_Flag PowerOnFlag;
enum
{
TAMPER_IDLE,
TAMPER_CLOSE,
TAMPER_OPEN
}TamperStatus;
enum
{
NET_IDLE,
NET_CONNECT,
NET_DISCONNECT
}NetStatus,NetPreStatus;
/***********************************************************************
*
* @FunctionName Power_On_Init
*
***/
void Power_On_Init(void)
{
/* To Check the device have or not connect to the net */
if (PORT_DEV_ADD == SET) NetStatus = NET_DISCONNECT;
else NetStatus = NET_CONNECT;
/* Tamper status check */
if (PORT_TAMPER == RESET) TamperStatus = TAMPER_CLOSE;
else TamperStatus = TAMPER_OPEN;
/* Check Sensor status */
if (PORT_SENSOR == RESET) SensorStatus = SENSOR_OPEN;
else SensorStatus = SENSOR_CLOSE;
NetPreStatus = NetStatus;
PowerOnFlag = TRUE;
}
/***********************************************************************
*
* @FunctionName Data_Process
*
***/
void Data_Process(void)
{
static _Uint8 ShakeTime;
static _Flag ShakeFlag;
/* to check the net status, change mode to G-FAST when connected, & to */
/* RGB-SLOWLY when disconnected */
if (NetStatus != NET_IDLE)
{
ShakeTime++;
if (ShakeTime > 2)
{
ShakeTime = 0;
if (NetStatus == NET_CONNECT && PORT_DEV_ADD == RESET && NetPreStatus != NET_CONNECT)
{
ShakeFlag = TRUE;
ConnectFlag = TRUE;
LedData.ModeBuf = LED_G_FAST;
if (PowerOnFlag != TRUE)
{
NetChgFlag = TRUE;
}
NetPreStatus = NetStatus;
}
else if (NetStatus == NET_DISCONNECT && PORT_DEV_ADD == SET && NetPreStatus != NET_DISCONNECT)
{
ShakeFlag = TRUE;
ConnectFlag = FALSE;
LedData.ModeBuf = LED_RGB_SLOW;
NetPreStatus = NetStatus;
}
if (ShakeFlag == TRUE)
{
ShakeFlag = FALSE;
// get mode & set init Flag
LedData.Mode = LedData.ModeBuf;
LedData.InitFlag = TRUE;
}
// clear status
PowerOnFlag = FALSE;
NetStatus = NET_IDLE;
}
}
else
{
ShakeTime = 0;
ShakeFlag = FALSE;
}
/* have not connect to the net , keep the mode as RGB flash slowly when */
/* Tamper tirg. Keep Off mode when sensor trig */
if (ConnectFlag == FALSE)
{
/* check the tamper status */
if (TamperStatus != TAMPER_IDLE)
{
if (TamperStatus == TAMPER_CLOSE)
{
TamperCloseFlag = TRUE;
LedData.ModeBuf = LED_RGB_OFF;
}
else
{
TamperCloseFlag = FALSE;
LedData.ModeBuf = LED_RGB_SLOW;
}
// get mode & set init flag
LedData.Mode = LedData.ModeBuf;
LedData.InitFlag = TRUE;
WakeUpMode = 1;
WakeUpInit = TRUE;
// clear status
TamperStatus = TAMPER_IDLE;
}
}
/* when device connected to the net, change mode to B-SLOW when tamper trig */
/* and to R-SLOW when tamper closed and sensor trig */
else if (NetChgFlag == FALSE)
{
/* check the tamper status */
if (TamperStatus != TAMPER_IDLE)
{
if (TamperStatus == TAMPER_CLOSE)
{
TamperCloseFlag = TRUE;
LedData.ModeBuf = LED_RGB_OFF;
}
else
{
TamperCloseFlag = FALSE;
LedData.ModeBuf = LED_B_SLOW;
}
// get the mode and set init flag
LedData.Mode = LedData.ModeBuf;
LedData.InitFlag = TRUE;
WakeUpMode = 1;
WakeUpInit = TRUE;
// clear status
TamperStatus = TAMPER_IDLE;
}
/* check the sensor status when tamper closed */
if (TamperCloseFlag == TRUE)
{
if (SensorStatus != SENSOR_IDLE)
{
if (SensorStatus == SENSOR_CLOSE)
{
SensorFlag = TRUE;
LedData.Mode = LED_R_SLOW;
TriggerMode = 1;
}
else
{
SensorFlag = FALSE;
LedData.Mode = LED_RGB_OFF;
TriggerMode = 0;
}
//get the mode and set init flag
LedData.InitFlag = TRUE;
WakeUpMode = 1;
WakeUpInit = TRUE;
//clear status
SensorStatus = SENSOR_IDLE;
}
else if (SensorFlag == TRUE)
{
if (LedData.Mode != LED_R_SLOW)
{
LedData.Mode = LED_R_SLOW;
LedData.InitFlag = TRUE;
}
}
}
}
}
/***********************************************************************
*
* @FunctionName Interrupt_Process
*
***/
void Interrupt_Process(void) interrupt 7
{
/* To Check the device have or not connect to the net */
if (PORT_DEV_ADD == SET) NetStatus = NET_DISCONNECT;
else NetStatus = NET_CONNECT;
//Tamper
if ((PIF & 0x80) == 0x80)
{
if (PORT_TAMPER == RESET) TamperStatus = TAMPER_CLOSE;
else TamperStatus = TAMPER_OPEN;
}
//Sensor
if ((PIF & 0x10) == 0x10)
{
// if (PORT_SENSOR == RESET) SensorStatus = SENSOR_OPEN;
// else SensorStatus = SENSOR_CLOSE;
}
//Clear
PIF = 0x0;
}
/***********************************************************************
*
* @FunctionName WKT_Interrupt
*
***/
void WKT_Interrupt(void) interrupt 17
{
WKCON &= ~(BIT3 | BIT4);
TrigForbidFlag = FALSE;
}
|
C
|
#include <stdio.h>
int main()
{
int array[100], n, i, j, position, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i< n; i++)
scanf("%d", &array[i]);
for (i = 0; i < (n - 1); i++) // finding minimum element (n-1) times
{
position = i;
for (j = i + 1; j < n; j++)
{
if (array[position] > array[j])
position = j;
}
if (position != i)
{
t = array[i];
array[i] = array[position];
array[position] = t;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
printf("%d ", array[i]);
return 0;
}
|
C
|
//ʵֱַstrcmpַȽϺӼֵַȽϴСǰߴں1ǰСں-10
#include<stdio.h>
#include<string.h>
int strcmp_(char *st1,char *st2);
int main()
{
char A[100],B[100];
while(scanf("%s %s",A,B)!=EOF)
{
int Num=strcmp_(A,B);
if(Num>0)
printf("1\n");
else
if(Num<0)
printf("-1\n");
else
printf("0\n");
}
return 0;
}
/*****************************************/
int strcmp_(char *st1,char *st2)
{
for(int i=0;i<strlen(st1)&&i<strlen(st2);i++)
if(st1[i]!=st2[i])
return st1[i]-st2[i];
return strlen(st1)-strlen(st2);
}
|
C
|
void InsertionSortCLang(int* a, int size)
{
int i,j,temp;
for(i=1;i<size;i++)
{
temp=a[i];
j=i-1;
while(j>=0 &&a[j]>temp)
{
a[j+1]=a[j];
j-=1;
}
a[j+1]=temp;
}
}
|
C
|
#include "../include/read_line.h"
#include "../include/tlpi_hdr.h"
#include <fcntl.h>
#include <netdb.h>
#include <pthread.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/stat.h>
#define PORT_NUM "50004"
#define BACKLOG 50
#define BUF_SIZE 1000
#define MAX_FILE_SIZE 100000
void
errPage(int cfd, char* cause, char* errnum, char* shortmsg, char* longmsg)
{
char buf[BUF_SIZE];
/* Print the HTTP response headers */
sprintf(buf, "HTTP/1.0 %s %s\r\n", errnum, shortmsg);
write(cfd, buf, strlen(buf));
sprintf(buf, "Content-type: text/html\r\n\r\n");
write(cfd, buf, strlen(buf));
/* Print the HTTP response body */
sprintf(buf, "<html><title>Tiny Error</title>");
write(cfd, buf, strlen(buf));
sprintf(buf,
"<body bgcolor="
"ffffff"
">\r\n");
write(cfd, buf, strlen(buf));
sprintf(buf, "%s: %s\r\n", errnum, shortmsg);
write(cfd, buf, strlen(buf));
sprintf(buf, "<p>%s: %s\r\n", longmsg, cause);
write(cfd, buf, strlen(buf));
sprintf(buf, "<hr><em>The Fun Web server</em>\r\n");
write(cfd, buf, strlen(buf));
}
void
readothhrd(int cfd)
{
int numread;
char buf[BUF_SIZE];
readLine(cfd, buf, BUF_SIZE);
while (strcmp(buf, "\r\n")) {
readLine(cfd, buf, BUF_SIZE);
printf("%s", buf);
}
return;
}
void
getFiletype(char* filename, char* filetype)
{
if (strstr(filename, ".html")) {
strcpy(filetype, "text/html");
} else if (strstr(filename, ".gif")) {
strcpy(filetype, "text/gif");
} else if (strstr(filename, ".png")) {
strcpy(filetype, "text/png");
} else if (strstr(filename, ".jpg")) {
strcpy(filetype, "text/jpeg");
} else if (strstr(filename, ".css")) {
strcpy(filetype, "text/css");
} else if (strstr(filename, ".js")) {
strcpy(filetype, "text/js");
} else {
strcpy(filetype, "text/plain");
}
}
int
parseUrl(char* url, char* filename, char* cgiargs)
{
char* ptr;
if (!strstr(url, "cgi-bin")) {
strcpy(cgiargs, "");
strcpy(filename, ".");
strcat(filename, url);
if (url[strlen(url) - 1] == '/') {
strcat(filename, "index.html");
}
return 1;
} else {
ptr = index(url, '?');
if (ptr) {
strcpy(cgiargs, ptr + 1);
*ptr = '\0';
} else {
strcpy(cgiargs, "");
}
strcpy(filename, ".");
strcat(filename, url);
return 0;
}
}
int
staticRequest(int cfd, char* filename, int filesize)
{
int n, fd;
char buf[BUF_SIZE], filetype[BUF_SIZE];
getFiletype(filename, filetype);
sprintf(buf, "HTTP/1.0 200 OK\r\n");
write(cfd, buf, strlen(buf));
sprintf(buf, "Server: Fun Web Server\r\n");
write(cfd, buf, strlen(buf));
sprintf(buf, "Connection close\r\n");
write(cfd, buf, strlen(buf));
sprintf(buf, "Content-length: %d\r\n", filesize);
write(cfd, buf, strlen(buf));
sprintf(buf, "Content-type: %s\r\n\r\n", filetype);
write(cfd, buf, strlen(buf));
if ((fd = open(filename, O_RDONLY)) == -1) {
return -1;
}
while ((n = sendfile(cfd, fd, NULL, filesize)) > 0)
;
if (n == -1) {
close(fd);
return -1;
}
close(fd);
// fdp = mmap(NULL, filesize, PROT_READ, MAP_PRIVATE, fd, 0);
// close(fd);
// n = write(cfd, fdp, filesize);
// if (n != filesize) {
// printf("error");
// return -1;
// }
// munmap(fdp, filesize);
printf("sent file\n");
return 0;
}
int
dynamicRequest(int cfd, char* filename, char* cgiargs)
{
dup2(cfd, STDOUT_FILENO);
execve(filename, NULL, NULL);
return 0;
}
int
serveWeb(int cfd)
{
int numread, isStatic;
struct stat sbuf;
char buf[BUF_SIZE], method[BUF_SIZE], url[BUF_SIZE], version[BUF_SIZE], filename[BUF_SIZE],
cgiargs[BUF_SIZE];
if ((numread = readLine(cfd, buf, BUF_SIZE)) == -1) {
return -1;
}
sscanf(buf, "%s %s %s", method, url, version);
readothhrd(cfd);
if (strcmp(method, "GET")) {
errPage(cfd, method, "501", "Not Implemented", "funserver does not implement this method");
return -1;
}
isStatic = parseUrl(url, filename, cgiargs);
printf("url: %s\n", filename);
if (stat(filename, &sbuf) == -1) {
errPage(cfd, filename, "404", "Not found", "funserver couldn't find this file");
return -1;
}
if (isStatic) {
staticRequest(cfd, filename, sbuf.st_size);
} else {
dynamicRequest(cfd, filename, cgiargs);
}
printf("received GET req\n");
return 0;
}
int
main(int argc, char* argv[])
{
int lfd, cfd, optval, s;
struct sockaddr_storage claddr;
socklen_t addrlen;
struct addrinfo hints;
struct addrinfo *result, *rp;
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = SIG_IGN;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
errExit("sigaction");
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_canonname = NULL;
hints.ai_next = NULL;
hints.ai_addr = NULL;
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
if (getaddrinfo(NULL, PORT_NUM, &hints, &result) == -1) {
errExit("getaddrinfo");
}
optval = 1;
for (rp = result; rp != NULL; rp = rp->ai_next) {
lfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (lfd == -1) {
continue;
}
if (setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) {
errExit("setsockopt");
}
if (bind(lfd, rp->ai_addr, rp->ai_addrlen) == 0) {
break;
}
close(lfd);
}
if (rp == NULL) {
fatal("could not bind");
}
if (listen(lfd, BACKLOG) == -1) {
errExit("listen");
}
freeaddrinfo(result);
for (;;) {
cfd = accept(lfd, (struct sockaddr*)&claddr, &addrlen);
if (cfd == -1) {
continue;
}
printf("connected\n");
switch (fork()) {
case -1:
printf("error fork");
close(cfd);
break;
case 0:
close(lfd);
serveWeb(cfd);
_exit(EXIT_SUCCESS);
default: close(cfd); break;
}
}
}
|
C
|
/*#include <stdio.h>
int main() {
int a;
printf("Inserire Int: ");
scanf("%d", &a);
printf("%d",a);
return 0;
}
#include <stdio.h>
int main()
{
int a;
float b;
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
}
#include <stdio.h>
int somma(int x, int y)
{
int f = x + y;
if(x == y) {
printf("Numeri uguali\n");
return 100;
}
return f;
}
int main()
{
int a;
int b;
printf("Inserire primo Int: ");
scanf("%d", &a);
printf("Inserire secondo Int: ");
scanf("%d", &b);
int c = somma(a,b);
printf("Somma: %d\n",c);
return 0;
}
#include <stdio.h>
int main() {
const int maxInput = 100;
int i;
double number, average, sum = 0.0;
for (i = 1; i <= maxInput; ++i) {
printf("%d. Enter a number: ", i);
scanf("%lf", &number);
// go to jump if the user enters a negative number
if (number < 0.0) {
goto jump;
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
#include <stdio.h>
int somma(int x, int y);
int main()
{
int a;
int b;
printf("Inserire primo Int: ");
scanf("%d", &a);
printf("Inserire secondo Int: ");
scanf("%d", &b);
int c = somma(a,b);
printf("Somma: %d\n",c);
return 0;
}
int somma(int x, int y)
{
int f = x + y;
if(x == y) {
printf("Numeri uguali\n");
return 100;
}
return f;
}#include <stdio.h>
int main()
{
float a[5][5], b[5][5], result[5][5];
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
// Taking input using nested for loop
printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
// adding corresponding elements of two arrays
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}
// Displaying the sum
printf("\nSum Of Matrix:\n");
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
{
printf("%.1f\t", result[i][j]);
if (j == 1)
printf("\n");
}
return 0;
}#include <stdio.h>
int main()
{
int a = 5;
int b = 10;
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("address of a: %p\n", &a);
printf("address of b: %p\n", &b);
int *f = &a;
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("address of a: %p\n", &a);
printf("address of b: %p\n", &b);
return 0;
}#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
#include <stdio.h>
int main() {
int x[4];
int i;
for(i = 0; i < 4; ++i) {
printf("&x[%d] = %p\n", i, &x[i]);
}
printf("Address of array x: %p", x);
return 0;
}#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
#include <stdio.h>
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
#include <stdio.h>
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;
int main()
{
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);
// adding feet
sum.feet = dist1.feet + dist2.feet;
// adding inches
sum.inch = dist1.inch + dist2.inch;
}
#include <stdio.h>
#include <string.h>
#define MAX 20
typedef struct
{
char cognome[30];
char nome[20];
int voto;
} alunno;
int main()
{
alunno a[MAX];
int n, i, j, trovato;
char cognome_alunno[20];
do
{
printf("Inserisci il numero di alunni:");
scanf("%d", &n);
} while (n < 1 || n > MAX);
for (i = 0; i < n; i++)
{
printf("Inserisci il cognome dell'alunno:");
scanf("%s", a[i].cognome);
printf("Inserisci il nome dell'alunno:");
scanf("%s", a[i].nome);
printf("Inserisci il voto:");
scanf("%d", &a[i].voto);
}
printf("\nInserisci il cognome dell'alunno da cercare: ");
scanf("%s", cognome_alunno);
trovato = 0;
for (j = 0; j < n; j++)
{
if (strcmp(a[j].cognome, cognome_alunno) == 0)
{
printf("\nAlunno trovato in posizione %d\nnome:%s\nvoto:%d", j + 1, a[j].nome, a[j].voto);
trovato = 1;
}
}
if (!trovato)
printf("\nAlunno non trovato.\n");
return 0;
}
if(st[i].name == " " || st[i].name == ""){
printf("Vuoto");
#include <stdio.h>
#include <string.h>
struct student
{
int age;
int voti;
char CorsodiStudi[30];
char name[30];
char surname[30];
};
int main()
{
int i;
struct student st[i];
printf("Enter 2 students\n");
for (i = 0; i < 2; i++)
{
printf("\nEnter Name: ");
scanf("\n%29s", st[i].name);
printf("\nEnter Surname: ");
scanf("\n%29s", st[i].surname);
printf("\nEnter Age: ");
scanf("\n%d", &st[i].age);
printf("\nEnter Corso di studi: ");
scanf("\n%29s", st[i].CorsodiStudi);
printf("\nEnter Media dei voti: ");
scanf("\n%d", &st[i].voti);
printf("\n###################################################################################\n");
}
int x;
printf("\nStudent Information List:\n");
for (x = 0; x < 2; x++)
{
printf("\nName: %s", st[x].name);
printf("\nSurname: %s", st[x].surname);
printf("\nAge: %d", st[x].age);
printf("\nCorso di studi: %s", st[x].CorsodiStudi);
printf("\nMedia dei Voti: %d", st[x].voti);
printf("\n###################################################################################\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(){
int x,y,d;
printf("\nEnter first number: ");
scanf("\n%d", &x);
printf("\nEnter second number: ");
scanf("\n%d", &y);
if(x == y)
{
printf("Numeri uguali\n");
} else if(x > y){
d = x - y;
printf("%d valore più alto di %d\n",x, d);
} else {
d = y - x;
printf("%d valore più alto di %d\n",y, d);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include "test-import.c"
int main(int argc, char const *argv[])
{
int x;
printf("Inserisci numero: ");
scanf("%d",&x);
testprint(x);
int *f = poin(x);
printf("\nPuntatore: %p", f);
printf("\nPuntatore: %p", &x);
printf("\nMoltiplicato: %d", x);
printf("\nMoltiplicato: %d", multy(x));
return 0;
}
#include <stdio.h>
#include <string.h>
#include "testi.c"
int main(int argc, char const *argv[])
{
int c[5][5];
int f = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
c[i][j] = f++;
if(find(c[i][j],10) == 0){
printf("VT ");
}else
{
printf("%d ",c[i][j]);
}
}
printf("\n\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include "testi.c"
int main(int argc, char const *argv[])
{
char s[] = "Andrea";
int i;
size_t f = sizeof(s) / sizeof(char);
for (i = 0; i < f; i++)
{
if(s[i] =='\0'){
printf("Valore Finale\n");
}else{
printf("%c\n",s[i]);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int id = fork();
int n;
if (id == 0){
n = 1;
printf("Processo ID: %d\n", id);
} else{
n = 6;
}
if(id != 0){
wait();
}
int i;
for (i = n; i < n + 5; i++)
{
printf("%d ",i);
fflush(stdout);
}
if(id != 0){
printf("\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
int id1 = fork();
int id2 = fork();
if (id1 == 0)
{
if (id2 == 0)
{
printf("We are process y\n");
}
else
{
printf("We are process x\n");
}
}
else
{
if (id2 == 0)
{
printf("We are process z\n");
}
else
{
printf("We are parent process!!! \n");
}
}
while (wait(NULL) != -1 || errno != ECHILD){
printf("Waited for a child\n");
}
return 0;
}
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
int id = fork();
if( id == 0){
sleep(1);
}
printf("Curret ID: %d, Parrent ID: %d\n",
getpid(),
getppid()
);
int res = wait(NULL);
if( res == -1){
printf("No childer wait\n");
}else{
printf("%d finisced \n",res);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char **argv)
{
char *vector = (char *) malloc(4);
memset(vector, 'a', 6);
printf("%d\n", strlen(vector));
//prezapiswa
vector = (char *) realloc(vector, 6);
free(vector);
vector = NULL;
free(vector);
return 0;
}
|
C
|
/**
* Requiments:
* 1. Given a linked list, remove the nth node from the end of list
* and return its head.
* 2. Think about the time complexity and space complexity
* of you function and write it in your report.
*
* For example:
* Given linked list: 1->2->3->4->5, and n = 2.
* After removing the second node from the end,
* the linked list becomes 1->2->3->5.
*
* Note:
* You may assume that the given n will always be valid.
**/
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
/* Your code should start from here. */
/* End of your code. */
}
/* Warning: Testbench. PLEASE leave it INTACT. */
/* Warning: Testbench. PLEASE leave it INTACT. */
/* Warning: Testbench. PLEASE leave it INTACT. */
void printLst(struct ListNode *);
void deleteLst(struct ListNode *);
int main(int argc, char** argv){
struct ListNode *head, *probe;
int lstSize[5] = {1,2,4,8,16};
int Loc[5];
int i;
srand(time(NULL));
for (i = 0; i < 5; i++)
Loc[i] = rand() % lstSize[i] + 1;
for (i = 0; i < 5; i++){
int j;
/* Initialize the linked list. */
head = NULL;
if (lstSize[i]){
head = (struct ListNode *)malloc(sizeof(struct ListNode));
head->val = rand() % 100;
head->next = NULL;
}
for (probe = head, j = 1; j < lstSize[i]; j++){
probe->next = (struct ListNode *)malloc(sizeof(struct ListNode));
probe = probe->next;
probe->val = rand() % 100;
probe->next = NULL;
}
printf("Case%2d: remove #%d element from the end of \n",i+1,Loc[i]);
printLst(head);
/* Test */
printf("The new linked list is:\n");
printLst(removeNthFromEnd(head, Loc[i]));
printf("\n");
deleteLst(head);
}
return 0;
}
/* Print the linked list. */
void printLst(struct ListNode * probe){
for (; probe != NULL; probe = probe->next){
printf("%d->",probe->val);
}
printf("\b\b \n");
}
/* Delete the linked list. */
void deleteLst(struct ListNode *head){
if (head == NULL)
return;
deleteLst(head->next);
free(head);
return;
}
/** Zhang Chen, Dept. EE, Fudan University, 2016 **/
|
C
|
#include "BRMixFile.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char byte;
struct BRMixFile
{
char *_filename;
BRMappedFileRef _mappedFile;
uint16_t _entryCount;
uint32_t _size;
struct _BRMixFileEntry *_entries;
};
struct _BRMixFileEntry
{
uint32_t id;
uint32_t offset;
uint32_t length;
};
BRMixFileRef BRMixFileOpen(const char *aFilename)
{
BRMixFileRef mixFile = calloc(1, sizeof(struct BRMixFile));
if (!mixFile)
return 0;
mixFile->_filename = strdup(aFilename);
mixFile->_entries = 0;
mixFile->_mappedFile = BRMappedFileMapFile(aFilename);
if (!mixFile->_mappedFile)
goto cleanup;
byte *p = BRMappedFileGetData(mixFile->_mappedFile);
byte *end = p + BRMappedFileGetSize(mixFile->_mappedFile);
BRPtrRangeRef r = BRPtrRangeCreate(p, end);
mixFile->_entryCount = BRPtrRangeReadLE16AndAdvance(r);
mixFile->_size = BRPtrRangeReadLE32AndAdvance(r);
//printf("entryCount: %u\n", mixFile->_entryCount);
//printf("size: %u\n", mixFile->_size);
// TODO: Verify size against map size
if (mixFile->_size > BRMappedFileGetSize(mixFile->_mappedFile))
goto cleanup;
mixFile->_entries = calloc(mixFile->_entryCount, sizeof(struct _BRMixFileEntry));
if (!mixFile->_entries)
goto cleanup;
size_t i;
for (i = 0; i != mixFile->_entryCount; ++i)
{
mixFile->_entries[i].id = BRPtrRangeReadLE32AndAdvance(r);
mixFile->_entries[i].offset = BRPtrRangeReadLE32AndAdvance(r);
mixFile->_entries[i].length = BRPtrRangeReadLE32AndAdvance(r);
/*
printf("Entry %3zu: %08x %08x %08x\n", i,
mixFile->_entries[i].id,
mixFile->_entries[i].offset,
mixFile->_entries[i].length
);
*/
}
return mixFile;
cleanup:
BRMixFileClose(mixFile);
return 0;
}
void BRMixFileClose(BRMixFileRef aMixFile)
{
if (!aMixFile)
return;
BRMappedFileUnmapFile(aMixFile->_mappedFile);
free(aMixFile->_entries);
free(aMixFile);
}
const char *BRMixFileGetName(BRMixFileRef aMixFile)
{
return aMixFile->_filename;
}
uint16_t BRMixFileGetResourceCount(BRMixFileRef aMixFile)
{
if (!aMixFile)
return 0;
return aMixFile->_entryCount;
}
void *_BRMixFileGetResourceDataByIndex(BRMixFileRef aMixFile, uint16_t aIndex)
{
if (!aMixFile || aIndex >= aMixFile->_entryCount)
return 0;
return (uint8_t*)BRMappedFileGetData(aMixFile->_mappedFile) +
aMixFile->_entries[aIndex].offset +
6 + 12 * aMixFile->_entryCount;
}
size_t _BRMixFileGetResourceSizeByIndex(BRMixFileRef aMixFile, uint16_t aIndex)
{
if (!aMixFile || aIndex >= aMixFile->_entryCount)
return 0;
return aMixFile->_entries[aIndex].length;
}
BRPtrRangeRef BRMixFileGetResourceRangeByIndex(BRMixFileRef aMixFile, uint16_t aIndex)
{
if (!aMixFile || aIndex >= aMixFile->_entryCount)
return 0;
//printf("ID: 0x%08x\n", aMixFile->_entries[aIndex].id);
uint8_t *p = _BRMixFileGetResourceDataByIndex(aMixFile, aIndex);
size_t size = _BRMixFileGetResourceSizeByIndex(aMixFile, aIndex);
return BRPtrRangeCreate(p, p + size);
}
#define ROL(n) ((n << 1) | ((n >> 31) & 1))
uint32_t _BRMixFileGetIdForName(const char *aResourceName)
{
char buffer[12] = { 0 };
int i;
for (i = 0; aResourceName[i] && i < 12; ++i)
buffer[i] = toupper(aResourceName[i]);
uint32_t id = 0;
for (i = 0; i < 12 && buffer[i]; i += 4)
{
uint32_t t = buffer[i + 3] << 24
| buffer[i + 2] << 16
| buffer[i + 1] << 8
| buffer[i + 0];
id = ROL(id) + t;
}
//printf("_BRMixFileGetIdForName(\"%s\") = %08x\n", aResourceName, id);
return id;
}
#undef ROL
int32_t _BRMixFileGetIndexForId(BRMixFileRef aMixFile, uint32_t aId)
{
static BRMixFileRef cachedMixFile;
static uint32_t cachedId;
static int32_t cachedIndex;
if (aMixFile == cachedMixFile && cachedId == aId)
return cachedIndex;
int32_t i;
for (i = 0; i != aMixFile->_entryCount; ++i)
if (aMixFile->_entries[i].id == aId)
{
cachedMixFile = aMixFile;
cachedId = aId;
cachedIndex = i;
return i;
}
return -1;
}
BRPtrRangeRef BRMixFileGetResourceRangeByName(BRMixFileRef aMixFile, const char *aResourceName)
{
uint32_t id = _BRMixFileGetIdForName(aResourceName);
int32_t index = _BRMixFileGetIndexForId(aMixFile, id);
if (index == -1)
return 0;
return BRMixFileGetResourceRangeByIndex(aMixFile, index);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#define BUFFER_SIZE 256
int cree_socket_tcp_ip()
{
int sock;
struct sockaddr_in adresse;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "Erreur socket\n");
return -1;
}
memset(&adresse, 0, sizeof(struct sockaddr_in));
adresse.sin_family = AF_INET;
// donner un numéro de port disponible quelconque
// adresse.sin_port = htons(0);
// aucun controle sur l'adresse IP :
//adresse.sin_addr.s_addr = htons(INADDR_ANY);
// Autre exemple :
// connexion sur le port 33016 fix�
adresse.sin_port = htons(33016);
// depuis localhost seulement :
inet_aton("127.0.1.1", &adresse.sin_addr);
if (bind(sock, (struct sockaddr *)&adresse,
sizeof(struct sockaddr_in)) < 0)
{
close(sock);
fprintf(stderr, "Erreur bind\n");
return -1;
}
return sock;
}
int affiche_adresse_socket(int sock)
{
struct sockaddr_in adresse;
socklen_t longueur;
longueur = sizeof(struct sockaddr_in);
if (getsockname(sock, (struct sockaddr *)&adresse, &longueur) < 0)
{
fprintf(stderr, "Erreur getsockname\n");
return -1;
}
printf("IP = %s, Port = %u\n", inet_ntoa(adresse.sin_addr),
ntohs(adresse.sin_port));
return 0;
}
int main(void)
{
int sock_contact;
int sock_connectee;
struct sockaddr_in adresse;
socklen_t longueur;
pid_t pid_fils;
char bufferR[BUFFER_SIZE];
char bufferW[BUFFER_SIZE];
char tmp[50];
int nb;
sock_contact = cree_socket_tcp_ip();
if (sock_contact < 0)
return -1;
listen(sock_contact, 5);
printf("Mon adresse (sock contact) -> ");
affiche_adresse_socket(sock_contact);
while (1)
{
longueur = sizeof(struct sockaddr_in);
sock_connectee = accept(sock_contact,
(struct sockaddr *)&adresse,
&longueur);
if (sock_connectee < 0)
{
fprintf(stderr, "Erreur accept\n");
return -1;
}
pid_fils = fork();
if (pid_fils == -1)
{
fprintf(stderr, "Erreur fork\n");
return -1;
}
if (pid_fils == 0)
{ /* fils */
close(sock_contact);
sprintf(bufferW, "IP = %s, Port = %u\n", inet_ntoa(adresse.sin_addr), ntohs(adresse.sin_port));
printf("Connexion");
affiche_adresse_socket(sock_connectee);
printf(" %s", bufferW);
strcat(bufferW, "Veuillez entrez votre message : ");
write(sock_connectee, bufferW, BUFFER_SIZE);
nb = read(sock_connectee, bufferR, BUFFER_SIZE);
sprintf(bufferW, "Message: %s\n", bufferR);
write(sock_connectee, bufferW, BUFFER_SIZE);
exit(0);
}
else
{
close(sock_connectee);
}
}
return 0;
}
|
C
|
#include "Stack.h"
int secondStack [1000];
void enqueue (int entity)
{
push(entity);
}
int dequeue()
{
if (top <= 0)
{
printf("Queue is empty\n");
return 0;
}
else
{
int result;
int count = 0;
while (top > 0)
{
secondStack[count++] = pop();
}
result = secondStack[--count];
count--;
for (int i = count; i >= 0; i--)
{
push(secondStack[i]);
}
return result;
}
}
|
C
|
//https://www.tldp.org/LDP/lpg/node81.html
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <ctype.h>
#include <string.h>
#define SEGSIZE 100
void usage();
void writeshm(int shmid, char *segptr, char *text);
void changemode(int shmid, char *mode);
void removeshm(int shmid);
void readshm(int shmid, char *segptr);
main(int argc, char *argv[])
{
key_t key;
int shmid, cntr;
char *segptr;
if(argc == 1)
usage();
/* Create unique key via call to ftok() */
key = ftok(".", 'S');
/* Open the shared memory segment - create if necessary */
if((shmid = shmget(key, SEGSIZE, IPC_CREAT|IPC_EXCL|0666)) == -1)
{
printf("Shared memory segment exists - opening as client\n");
/* Segment probably already exists - try as a client */
if((shmid = shmget(key, SEGSIZE, 0)) == -1)
{
perror("shmget");
exit(1);
}
}
else
{
printf("Creating new shared memory segment\n");
}
/* Attach (map) the shared memory segment into the current process */
if((segptr = (char *)shmat(shmid, 0, 0)) == (char *)-1)
{
perror("shmat");
exit(1);
}
switch(tolower(argv[1][0]))
{
case 'w': writeshm(shmid, segptr, argv[2]);
break;
case 'r': readshm(shmid, segptr);
break;
case 'd': removeshm(shmid);
break;
case 'm': changemode(shmid, argv[2]);
break;
default: usage();
}
}
writeshm(int shmid, char *segptr, char *text)
{
strcpy(segptr, text);
printf("Done...\n");
}
readshm(int shmid, char *segptr)
{
printf("segptr: %s\n", segptr);
}
removeshm(int shmid)
{
shmctl(shmid, IPC_RMID, 0);
printf("Shared memory segment marked for deletion\n");
}
changemode(int shmid, char *mode)
{
struct shmid_ds myshmds;
/* Get current values for internal data structure */
shmctl(shmid, IPC_STAT, &myshmds);
/* Display old permissions */
printf("Old permissions were: %o\n", myshmds.shm_perm.mode);
/* Convert and load the mode */
sscanf(mode, "%o", &myshmds.shm_perm.mode);
/* Update the mode */
shmctl(shmid, IPC_SET, &myshmds);
printf("New permissions are : %o\n", myshmds.shm_perm.mode);
}
usage()
{
fprintf(stderr, "shmtool - A utility for tinkering with shared memory\n");
fprintf(stderr, "\nUSAGE: shmtool (w)rite <text>\n");
fprintf(stderr, " (r)ead\n");
fprintf(stderr, " (d)elete\n");
fprintf(stderr, " (m)ode change <octal mode>\n");
exit(1);
}
|
C
|
/*
* Author: Meet Udeshi
*/
#include <stdint.h>
#include <stdbool.h>
#include "inc/tm4c123gh6pm.h"
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_gpio.h"
#include "driverlib/sysctl.h"
#include "driverlib/interrupt.h"
#include "driverlib/timer.h"
#include "driverlib/gpio.h"
#define RED GPIO_PIN_1
#define BLUE GPIO_PIN_2
#define GREEN GPIO_PIN_3
#define SW1 GPIO_PIN_4
#define SW2 GPIO_PIN_0
#define SW_STATE_IDLE 1
#define SW_STATE_PRESS 2
#define SW_STATE_RELEASE 3
#define SW_PRESSED 1
#define SW_RELEASED 2
uint8_t currLEDColor = RED;
uint8_t sw1State = SW_STATE_IDLE;
uint8_t sw2State = SW_STATE_IDLE;
uint32_t sw2Count = 0;
/*
* Maps next LED color to current color
*
* currState: Current LED color
*/
uint8_t nextLEDState(uint8_t currState) {
switch(currState) {
case RED: return GREEN;
case BLUE: return RED;
case GREEN: return BLUE;
default: return RED;
}
}
/*
* Detect key pressed or released using state machine
*
* currState: pointer to current state variable
* swVal: Value of switch which was read
*
* Return: SW_PRESSED if switch pressed, SW_RELEASED if released else 0
*/
uint8_t detectKeyPress(uint8_t* currState, uint8_t swVal) {
uint8_t nextState = SW_STATE_IDLE;
uint8_t ret = 0;
if(swVal) { // released
nextState = SW_STATE_IDLE;
if(*currState == SW_STATE_RELEASE) {
ret = SW_RELEASED;
}
} else { // pressed
switch(*currState) {
case SW_STATE_IDLE:
nextState = SW_STATE_PRESS;
break;
case SW_STATE_PRESS:
nextState = SW_STATE_RELEASE;
ret = SW_PRESSED;
break;
case SW_STATE_RELEASE:
nextState = SW_STATE_RELEASE;
break;
}
}
*currState = nextState;
return ret;
}
void Timer0IntHandler() {
TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
uint8_t switchValue = GPIOPinRead(GPIO_PORTF_BASE, SW1 | SW2);
uint8_t sw1Trans = detectKeyPress(&sw1State, switchValue & SW1);
uint8_t sw2Trans = detectKeyPress(&sw2State, switchValue & SW2);
if(sw1Trans == SW_PRESSED) {
GPIOPinWrite(GPIO_PORTF_BASE, RED|BLUE|GREEN, currLEDColor);
currLEDColor = nextLEDState(currLEDColor);
} else if(sw1Trans == SW_RELEASED) {
GPIOPinWrite(GPIO_PORTF_BASE, RED|BLUE|GREEN, 0);
}
if(sw2Trans == SW_PRESSED) {
sw2Count ++;
}
}
/*
* Configure all required peripherals
*/
void configPeripherals() {
SysCtlClockSet(SYSCTL_SYSDIV_5|SYSCTL_USE_PLL|SYSCTL_OSC_MAIN|SYSCTL_XTAL_16MHZ);
// Enable PORTF clock
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
HWREG(GPIO_PORTF_BASE+GPIO_O_LOCK) = GPIO_LOCK_KEY;
HWREG(GPIO_PORTF_BASE+GPIO_O_CR) |= SW2;
// LED output, switches input
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, RED|BLUE|GREEN);
GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, SW1|SW2);
GPIOPadConfigSet(GPIO_PORTF_BASE, SW1 | SW2,
GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
// Enable timer clock
SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC);
// Set-up timer interrupt
IntEnable(INT_TIMER0A);
TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
IntMasterEnable();
}
/*
* Sets timer load to trigger interrupt at given frequency
*
* freq: Frequency in Hz
*/
void setTimerFreq(uint32_t freq) {
uint32_t period = SysCtlClockGet() / freq;
TimerLoadSet(TIMER0_BASE, TIMER_A, period - 1);
}
int main(void) {
configPeripherals();
setTimerFreq(100); // Hz
TimerEnable(TIMER0_BASE, TIMER_A);
while(1) {
// chill out
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define white 1
#define gray 2
#define black 3
typedef struct edge{
int i;
struct edge *next;
}edge;
typedef struct node{
int i,d,f,color;
edge *next;
}node;
typedef struct gve{
int v,e;
node *g;
}gve;
typedef struct link_element{
int i;
struct link_element *next;
}link_element;
int insert(node *pnode,int i)
{
edge *new;
new=(edge *)malloc(sizeof(edge));
new->i=i;
new->next=pnode->next;
pnode->next=new;
return 0;
}
int link_insert(link_element **link,int i)
{
link_element *new;
new=(link_element *)malloc(sizeof(link_element));
new->i=i;
new->next=*link;
*link=new;
return 0;
}
int dfsvisit(gve G,node *pnode,int *time,link_element **link)
{
edge *tmp=pnode->next;
(*time)++;
pnode->d=*time;
pnode->color=gray;
while (tmp!=NULL)
{
if (G.g[tmp->i].color==white)
dfsvisit(G,&G.g[tmp->i],time,link);
tmp=tmp->next;
}
pnode->color=black;
(*time)++;
pnode->f=*time;
link_insert(link,pnode->i);
return 0;
}
int dfs(gve G,link_element **link)
{
int time=0,i;
for (i=1;i<=G.v;i++)
if (G.g[i].color==white)
dfsvisit(G,&G.g[i],&time,link);
return 0;
}
int dfsvisit2(gve G,node *pnode,int *time)
{
edge *tmp=pnode->next;
(*time)++;
pnode->d=*time;
pnode->color=gray;
printf("%d ",pnode->i);
while (tmp!=NULL)
{
if (G.g[tmp->i].color==white)
dfsvisit2(G,&G.g[tmp->i],time);
tmp=tmp->next;
}
pnode->color=black;
(*time)++;
pnode->f=*time;
return 0;
}
int dfs2(gve G,link_element **link)
{
int time=0;
link_element *tmp=*link;
while (tmp!=NULL)
{
if (G.g[tmp->i].color==white)
{
dfsvisit2(G,&G.g[tmp->i],&time);
printf("\n");
}
tmp=tmp->next;
}
return 0;
}
gve trans(gve G)
{
gve Gt;
Gt.v=G.v;
Gt.e=G.e;
Gt.g=(node *)malloc(sizeof(node)*(Gt.v+1));
int i;
for (i=1;i<=Gt.v;i++)
{
Gt.g[i].next=NULL;
Gt.g[i].color=white;
Gt.g[i].i=i;
}
edge *tmp;
for (i=1;i<=Gt.v;i++)
{
tmp=G.g[i].next;
while (tmp!=NULL)
{
insert(&Gt.g[tmp->i],i);
tmp=tmp->next;
}
}
return Gt;
}
int css(gve G)
{
link_element **link;
link=(link_element **)malloc(sizeof(link_element *));
*link=NULL;
gve Gt;
dfs(G,link);
Gt=trans(G);
dfs2(Gt,link);
return 0;
}
int main(void)
{
int i;
gve G;
scanf("%d%d",&G.v,&G.e);
G.g=(node *)malloc(sizeof(node)*(G.v+1));
for (i=1;i<=G.v;i++)
{
G.g[i].next=NULL;
G.g[i].color=white;
G.g[i].i=i;
}
int s,d;
for (i=1;i<=G.e;i++)
{
scanf("%d%d",&s,&d);
insert(&G.g[s],d);
}
css(G);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include "sqlite3.h"
#include "cgic.h"
int cgiMain()
{
cgiHeaderContentType("text/html");
fprintf(cgiOut, "<HTML>\n");
fprintf(cgiOut, "<meta charset='UTF-8'>");
fprintf(cgiOut, "<HTML><HEAD>\n");
fprintf(cgiOut, "<TITLE>net_check</TITLE></HEAD>\n");
fprintf(cgiOut, "<BODY>");
char st_date[100] = {0};
char st_time[100] = {0};
cgiFormString("st_date",st_date,20);
cgiFormString("st_time",st_time,20);
strcat(st_date,"-");
strcat(st_date,st_time);
char end_date[100] = {0};
char end_time[100] = {0};
cgiFormString("end_date",end_date,20);
cgiFormString("end_time",end_time,20);
fprintf(cgiOut,"end_date = %s\n",end_date);
if(strlen(end_date) < 10){//没有输入终止日期
time_t t;
struct tm* mydate;
time (&t); //获取现在的时间
mydate = localtime (&t);
sprintf(end_date,"%04d/%02d/%02d-%02d:%02d:%02d",mydate->tm_year+1900,mydate->tm_mon + 1,mydate->tm_mday,mydate->tm_hour,mydate->tm_min,mydate->tm_sec);
}
else{
if(strlen(end_time) < 8){
strcat(end_date,"-");
strcat(end_date,"23:59:59");//选择日期没有选择时间
}
else{
strcat(end_date,"-");
strcat(end_date,end_time);
}
}
char dev_id[3] = {0};
cgiFormString("dev_id",dev_id,20);
fprintf(cgiOut,"dev_id = %s\n",dev_id);
char device[100] = {0};
cgiFormString("device",device,100);
fprintf(cgiOut,"device = %s\n",device);
fprintf(cgiOut,"st_date = %s\n",st_date);
fprintf(cgiOut,"end_date = %s\n",end_date);
int res = system("cp /home/linux/www/html_data/basic.html /home/linux/www/html_data/data.html");
//where 事件时间 > %s and 事件时间 < %s
char buf[1024] = {0};
if(strlen(dev_id) == 0){//没有输入设备id
if(strcmp(device,"所有设备") == 0)
sprintf(buf,"sqlite3 -html /home/linux/www/db/event_show.db \"select * from event_table where 事件时间 > '%s' and 事件时间 < '%s';\" >> /home/linux/www/html_data/data.html",st_date,end_date);
else
sprintf(buf,"sqlite3 -html /home/linux/www/db/event_show.db \"select * from event_table where 事件时间 > '%s' and 事件时间 < '%s' and 事件对象 = '%s';\" >> /home/linux/www/html_data/data.html",st_date,end_date,device);
}
else{//输入了设备ID
char dev_id_8bit[9] = {0};
sprintf(dev_id_8bit,"%08d",atoi(dev_id));//8位设备id
sprintf(buf,"sqlite3 -html /home/linux/www/db/event_show.db \"select * from event_table where 事件时间 > '%s' and 事件时间 < '%s' and 设备ID = '%s';\" >> /home/linux/www/html_data/data.html",st_date,end_date,dev_id);
}
res = system(buf);
//html 显示返回
system("echo \"</tbody></table> <br> <a href=\"../his_data_query.html\"><b>返回</b></a>\" >> /home/linux/www/html_data/data.html");
//script 加入到网页中
system("cat /home/linux/www/html_data/script.html >> /home/linux/www/html_data/data.html");
//输出html
fprintf(cgiOut, "<meta http-equiv=\"refresh\" content=\"0;url=../html_data/data.html\">");//跳转到data.html页面 data.html 有查询数据的结果
return 0;
}
|
C
|
#include <stdio.h>
void ft_sort_int_tab(int *tab, int size);
int main()
{
int i;
int a[6] = {6, 2, 4, 3, 5, 1};
for(i = 0; i < 6; i++)
{
printf("%d, ", a[i]);
}
printf("\n");
ft_sort_int_tab(a, 6);
for(i = 0; i < 6; i++)
{
printf(": %d, ", a[i]);
}
}
|
C
|
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
/**
* main - generates passwords of random value
*
* Return: 0 always.
*/
int main(void)
{
int randomchar, sum = 0;
srand(time(0));
while (sum < 2772 - 127)
{
randomchar = rand() % 127;
if (randomchar > 32)
{
putchar(randomchar);
sum += randomchar;
}
}
putchar(2772 - sum);
return (0);
}
|
C
|
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/string.h>
#include <linux/vmalloc.h>
#include <linux/uaccess.h>
#include <linux/list.h>
#include <linux/ftrace.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Pablo Jimenez Cruz & Juan Chozas Sumbera");
DEFINE_SPINLOCK(sp);
#define BUFFER_LENGTH (PAGE_SIZE / 4)
#define MAX_BUFF_SIZE 257
static struct proc_dir_entry *proc_entry;
static struct list_head the_list;
struct list_item {
struct list_head links;
int data;
};
int digits(int n) {
int d = 1;
if (n < 10) {
return 1;
} else {
while (n >= 10) {
n = n / 10;
d++;
}
}
return d;
}
// añade un entero a la lista
void add_to_the_list(int n) {
struct list_item *item = vmalloc(sizeof(struct list_item)); // reserva memoria para struct list_item
spin_lock(&sp); // asignar dato
item->data = n;
list_add_tail(&item->links, &the_list); // añadir al final de la lista
spin_unlock(&sp);
trace_printk("\n[m0dLiSt] add: added %d to the list\n", n);
}
// borra enteros iguales a n de la lista
void remove_from_the_list(int n) {
struct list_item *item = NULL;
struct list_head *cur_node = NULL;
struct list_head *aux = NULL;
int nr_dels = 0;
spin_lock(&sp);
list_for_each_safe(cur_node, aux, &the_list) {
item = list_entry(cur_node, struct list_item, links);
if (item->data == n) {
nr_dels++;
list_del(cur_node); // borrar nodo de la lista
vfree(item); // liberar memoria del nodo
}
}
spin_unlock(&sp);
trace_printk("\n[m0dLiSt] remove: removed %d %d's from the list\n", nr_dels, n);
}
// vacía la lista
void cleanup_the_list(void) {
struct list_item *item = NULL;
struct list_head *cur_node = NULL;
struct list_head *aux = NULL;
int nr_dels = 0;
spin_lock(&sp);
list_for_each_safe(cur_node, aux, &the_list) {
item = list_entry(cur_node, struct list_item, links);
nr_dels++;
trace_printk("\n[m0dLiSt] cleanup: removed %d -%d digits\n", item->data, digits(item->data));
list_del(cur_node);
vfree(item);
}
spin_unlock(&sp);
trace_printk("\n[m0dLiSt] cleanup: %d items deleted\n", nr_dels);
}
// copia la lista a dest. devuelve un puntero a la
// primera posicion de memoria despues del último \n
char* write_list(char* dest) {
char* pnt = dest;
struct list_item *item = NULL;
struct list_head *cur_node = NULL;
int nr_byter = 0;
// escribir elementos en dest
list_for_each(cur_node, &the_list) {
item = list_entry(cur_node, struct list_item, links);
nr_byter += digits(item->data) + 1;
if (nr_byter <= MAX_BUFF_SIZE)
pnt += sprintf(pnt, "%d\n", item->data);
else
return NULL;
}
return pnt;
}
// modifica la lista con add, remove o cleanup
static ssize_t module_write(struct file *filp, const char __user *buf, size_t len, loff_t *off) {
int available_space = BUFFER_LENGTH - 1;
char buffer[BUFFER_LENGTH];
if ((*off) > 0) // the application can write in this entry just once !!
return 0;
if (len > available_space) {
trace_printk("\n[m0dLiSt:ERROR] not enough space for writing\n");
return -ENOSPC;
}
spin_lock(&sp);
// transfer data from user to kernel space
// copy_from_user(void* to, const void __user* from, unsigned long bytes_to_copy)
if (copy_from_user(buffer, buf, len))
return -EFAULT;
spin_unlock(&sp);
buffer[len] = '\0'; // Add the `\0' to convert to string
*off += len;
int num;
char cmd[len];
// parsear str
int retval = sscanf(buffer, "%s %d", cmd, &num);
// modificar m0dLiSt
if (retval == 1 && !strcmp(cmd, "cleanup")) {
cleanup_the_list();
} else if (retval == 2 && !strcmp(cmd, "add")) {
add_to_the_list(num);
} else if (retval == 2 && !strcmp(cmd, "remove")) {
remove_from_the_list(num);
} else {
trace_printk("\n[m0dLiSt:ERROR] could not parse command\n");
}
return len;
}
// imprime los contenidos de la lista
static ssize_t module_read(struct file *filp, char __user *buf, size_t len, loff_t *off) {
int nr_bytes = 0;
if ((*off) > 0) // there is nothing left to read
return 0;
// cantidad de digitos en la lista + un salto de linea por cada elem
char buffer[MAX_BUFF_SIZE];
spin_lock(&sp);
// copiar lista al buffer
char *pnt = write_list(buffer);
if (pnt == NULL){
return -ENOSPC;
}
spin_unlock(&sp);
// restar punteros para hallar cantidad de bytes escritos a buffer
nr_bytes = pnt - buffer;
// asegurar que caben nr_bytes en buf
if (len < nr_bytes)
return -ENOSPC;
spin_lock(&sp);
if (list_empty(&the_list)) {
trace_printk("\n[m0dLiSt] list empty\n");
} else {
trace_printk("\n[m0dLiSt] %d bytes in string(list):\n%s", nr_bytes, buffer);
}
// transfer data (elems de lista) from the kernel to userspace
// copy_to_user(void __user* to, const void* from, unsigned long bytes_to_copy)
if (copy_to_user(buf, buffer, nr_bytes))
return -EINVAL;
spin_unlock(&sp);
// update the file pointer
(*off) += len;
return nr_bytes;
}
static const struct file_operations proc_entry_fops = {
.read = module_read,
.write = module_write,
};
// inicializa el módulo
int init_modlist( void ) {
int ret = 0;
// initialize the list head
INIT_LIST_HEAD(&the_list);
// create /proc/m0dLiSt to interact with the list
proc_entry = proc_create( "m0dLiSt", 0666, NULL, &proc_entry_fops);
if (proc_entry == NULL) {
ret = -ENOMEM;
trace_printk("\n[m0dLiSt:ERROR] couldn't create entry in /proc\n");
} else {
trace_printk("\n[m0dLiSt] loaded\n");
}
return ret;
}
// destruye el módulo
void exit_modlist( void ) {
// borrar /proc/m0dLiSt
remove_proc_entry("m0dLiSt", NULL);
// liberar memoria si lista no está vacía
cleanup_the_list();
trace_printk("\n[m0dLiSt]: unloaded\n");
}
module_init(init_modlist);
module_exit(exit_modlist);
|
C
|
fillUsingRowColumnAnalysis()
{ n=0;
for(i=0 to 8)
{ value=0
Set currentRow=rows[i],temp=Set(1,2,..,9), temp2
temp= temp-currentRow
while((value=temp.getNextElement()))
for(j=0 to 8)
if( cells[i][j] to be filled)
if(cells[i][j].PossibleValues.search(value)= found)
{ temp2=cells[i][j].PossibleValues - getRowUnion(i,j)
if( |temp2| = 1)
{ setValueAt(i,j,temp2)
n++
}
}
}
for(j=0 to 8)
{ int value=0
Set currentColumn=columns[j],temp=Set(1,2,..,9), temp2
temp= temp-currentColumn
while((value=temp.getNextElement()))
for(int i=0 to 8)
if(cells[i][j] to be filled)
if(cells[i][j].PossibleValues.search(value)= found)
{ temp2=cells[i][j].PossibleValues - getColumnUnion(i,j)
if( |temp2| = 1)
{ setValueAt(i,j,temp2)
n++
}
}
}
return n
}
|
C
|
#include <stdio.h>
#define BUFSIZE 32
int main(void)
{
FILE *fp;
char buf[BUFSIZE];
char *retp;
fp = popen("cat /etc/passwd", "r");
/* if error */
while (1) {
retp = fgets(buf, BUFSIZE, fp);
if (retp == NULL) {
break;
}
printf("\033[31m%s\033[0m", buf);
fflush(stdout);
}
pclose(fp);
return 0;
}
|
C
|
/*
* uart.c
* @author: Jacob Vaughn, Nick Lorenze
* @date: Feb 21, 2019
*/
#include "uart.h"
// Initialize UART
void uart_init(void)
{
//Enable the UART module using the RCGCUART register
SYSCTL_RCGCUART_R |= 0b00000010;
//Enable the clock to the appropriate GPIO module via the RCGCGPIO register
SYSCTL_RCGCGPIO_R |= 0b00000010;
//Enable alternate function for PB0,PB1 and set functionality
GPIO_PORTB_AFSEL_R |= 0x03;
GPIO_PORTB_PCTL_R |= 0x00000011;
// Set digital or analog mode, and pin directions
GPIO_PORTB_DEN_R |= 0x03; //Set pins 0, 1 digital mode
GPIO_PORTB_DIR_R &= 0xF; // Set pin 0 (Rx) to input (0)
GPIO_PORTB_DIR_R |= 0xF; // Set pin 1 (Tx) to output (1)
// 2. Set up UART device
// A. Configure UART functionality, frame format and Baud speed
//Disable the UART by clearing the UARTEN bit in the UARTCTL register
UART1_CTL_R &= 0xFFFFFFFE; // search tm4c123gh6pm.h
//Set baud rate
//Write the integer portion of the BRD to the UARTIBRD register
UART1_IBRD_R = 8;
//Write the fractional portion of the BRD to the UARTFBRD register.
UART1_FBRD_R = 44;
//Write the desired serial parameters to the UARTLCRH register
UART1_LCRH_R = 0x60;
//Configure the UART clock source by writing to the UARTCC register
UART1_CC_R = 0x0;
// B. Setup UART1 interrupts
UART1_ICR_R |= 0b00010000; // Clear RX interrupt status flag
UART1_IM_R |= 0b00010000; // Enable RX interrupts
// 3. NVIC setup
// A. Configure NVIC to allow UART interrupts
NVIC_PRI1_R |= 0x00200000; //Set UART? IRQ pri to 1 (bits 15-13)
NVIC_EN0_R |= 0x00000040; //Enable UART? IRQ (IRQ 5)
// B. Bind UART1 interrupt requests to users Interrupt Handler
IntRegister(INT_UART1, UART1_Handler);
//Enable the UART by setting the UARTEN bit in the UARTCTL register
UART1_CTL_R |= 0x1;
IntMasterEnable(); //Globally allows CPU to service interrupts
}
void uart_sendChar(char data)
{
while ((UART1_FR_R & 0x20) != 0);
UART1_DR_R = data;
}
//
char uart_receive(void)
{
char rdata;
while ((UART1_FR_R & 0x10) != 0)
;
rdata = (char) (UART1_DR_R & 0xFF);
return rdata;
}
//UART1 ISR
void UART1_Handler()
{
// 1) Check if handler called due to a Rx event
if (UART1_MIS_R & 0b00010000)
{
UART1_ICR_R & 0b00010000; //clear interrupt flag
putty_char = uart_receive(); // receives char
putty_event = 1;
}
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "parse.h"
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
/*
Cameron Fabbri
Operating Systems Lab
shell.c
2-20-2015
Linux Shell written in C. Uses parse.h for a parser.
*/
/* Function Declarations */
void help ();
void history ();
void checkJobs ();
void quitShell ();
char *buildPrompt ();
void initializeJobs();
void killProcess (char *pid);
int isBuiltInCommand(char *cmd);
char *trim_ (char *cmdLine);
void executeHistory (char *lineNumber, parseInfo *info);
int executeCmd (char *cmd , parseInfo *info);
void addJob (pid_t childPid, char *cmd);
int backgroundJob (parseInfo *info);
/* array to store jobs and job id */
char *jobs[100][2];
/* built in commands */
enum BUILTIN_COMMANDS {NO_SUCH_BUILTIN=0, EXIT, JOBS, HISTORY, CD, KILL, HELP, EXECHIST};
/* various declarations */
int infile ;
int outfile ;
int stdoutback;
int stdinback ;
int status ;
int null_file ;
int main (int argc, char **argv)
{
int childPid;
char cwd[1024];
int counter = 1;
char *buf;
char *cmdLine;
struct commandType *com; /*com stores command name and Arg list for one command.*/
parseInfo *info; /*info stores all the information returned by parser.*/
buf = (char *)malloc(10*sizeof(char));
buf = getlogin();
/* removes history file for a fresh file on each usage of the shell */
remove("/tmp/.c_history");
initializeJobs();
printf("\nShell written for Linux in C. Type help to bring up the help screen.\n\n");
while(1)
{
FILE *f = fopen("/tmp/.c_history", "a");
/* retrieves and prints the current working directory */
getcwd (cwd, sizeof(cwd));
printf("%s@%s", buf, cwd);
#ifdef UNIX
cmdLine = readline(buildPrompt());
if (cmdLine == NULL)
{
fprintf(stderr, "Unable to read command\n");
continue;
}
#endif
if (f == NULL)
{
printf("Error opening history file");
exit(1);
}
/*calls the parser*/
info = parse(cmdLine);
if (info == NULL)
{
free(cmdLine);
continue;
}
/* Manages STDIN and STDOUT */
if (info->boolInfile == 1)
{
infile = open(info->inFile, O_RDONLY, 0666);
stdinback = dup(fileno(stdin));
dup2 (infile, fileno(stdin));
close(infile);
}
if (info->boolOutfile == 1)
{
outfile = open(info->outFile, O_CREAT | O_RDWR, 0666);
stdoutback = dup(fileno(stdout));
dup2 (outfile, fileno(stdout));
close(outfile);
}
/*com contains the info. of the command before the first "|"*/
com=&info->CommArray[0];
if ((com == NULL) || (com->command == NULL))
{
free_info(info);
free(cmdLine);
continue;
}
/*com->command tells the command name of com*/
if (isBuiltInCommand(com->command) == KILL ) killProcess(com->VarList[1]);
else if (isBuiltInCommand(com->command) == CD ) chdir(com->VarList[1]);
else if (isBuiltInCommand(com->command) == JOBS ) checkJobs();
else if (isBuiltInCommand(com->command) == EXIT ) quitShell();
else if (isBuiltInCommand(com->command) == HISTORY ) history();
else if (isBuiltInCommand(com->command) == HELP ) help();
else if (isBuiltInCommand(com->command) == EXECHIST)
{
parseInfo *info;
char *cmdLine_;
char *split_ = strtok(cmdLine, "!");
/* Executes the previous command */
if (strncmp(split_, "-1", strlen("-1")) == 0)
{
char tmp[1024];
char *cmdLine;
FILE *fp = fopen("/tmp/.c_history", "r");
while(!feof(fp)) fgets(tmp, 1024, fp);
cmdLine = trim_(tmp);
cmdLine_ = strtok(cmdLine, " ");
info = parse(cmdLine_);
executeHistory(cmdLine_, info);
} else executeHistory(split_, info);
}
else
{
executeCmd(cmdLine, info);
/* Returns to shell after STDIN and STDOUT */
if(info->boolInfile == 1)
{
dup2(stdinback, fileno(stdin));
close(stdinback);
}
if(info->boolOutfile == 1)
{
dup2(stdoutback, fileno(stdout));
close(stdoutback);
}
}
fprintf(f, "%d %s\n", counter, cmdLine);
fclose(f);
counter++;
free_info(info);
free(cmdLine);
}/* while(1) */
}
char *buildPrompt() { return "$ "; }
int isBuiltInCommand(char * cmd)
{
if ( strncmp(cmd, "exit" , strlen("exit" )) == 0) return EXIT;
if ( strncmp(cmd, "history", strlen("history")) == 0) return HISTORY;
if ( strncmp(cmd, "cd" , strlen("cd" )) == 0) return CD;
if ( strncmp(cmd, "kill" , strlen("kill" )) == 0) return KILL;
if ( strncmp(cmd, "help" , strlen("help" )) == 0) return HELP;
if ( strncmp(cmd, "job" , strlen("job" )) == 0) return JOBS;
if ( strncmp(cmd, "!" , strlen("!" )) == 0) return EXECHIST;
return NO_SUCH_BUILTIN;
}
void help()
{
printf("\n HELP AND USAGE: \n\n");
printf(" This is a shell written in C to be used with Linux. \n");
printf(" Commands in your $PATH variable are available to use. \n\n");
printf(" Functions: \n\n");
printf(" help: shows this help screen \n");
printf(" exit: exits the shell. If there are background processes \n");
printf(" still running, you will need to kill those first. \n");
printf(" history: shows the history of the current session, store \n");
printf(" in /tmp/.c_history. \n");
printf(" !: you can execute a command from your history using the !\n");
printf(" command follwed by the history number \n");
printf(" Typing in !-1 will run the previous command. \n\n");
printf(" cd <directory>: changes the current directory. \n\n");
printf(" kill <pid>: kills the process with that pid number \n\n");
printf(" background: putting a & at the end of a command will \n\n");
printf(" place it in the background \n\n");
printf(" job: lists the jobs running in the background with their \n");
printf(" respective pid. \n\n");
}
void history()
{
int c;
FILE *file;
file = fopen("/tmp/.c_history", "r");
if (file)
{
while ((c = getc(file)) != EOF) putchar(c);
fclose(file);
}
}
void checkJobs()
{
int i, j;
for (i = 0; jobs[i][1] != "..."; i++) {}
if (i == 0)
{
printf("No jobs running!\n");
}
else
{
fprintf(stderr, "\nID Process\n\n");
for (j = 0; j < i; j++)
{
printf("%s ", jobs[j][0]);
printf("%s\n", jobs[j][1]);
}
}
}
void quitShell()
{
int i;
for (i = 0; jobs[i][1] == "..."; i++){}
if (i == 100) exit(1);
else printf("You still have jobs running in the background!\n");
}
void killProcess(char *pid)
{
int status;
int result;
int i, j;
int kill_ID = atoi(pid);
for (i = 0; i < 100; i++)
{
if (strncmp(jobs[i][0], pid, strlen(pid)) == 0)
{
waitpid(kill_ID, &status, WNOHANG);
result = kill(kill_ID, SIGKILL);
if (result == -1) printf("Job %s killed successfully.\n", jobs[i][1]);
jobs[i][0] = "0";
jobs[i][1] = "...";
}
}
}
int backgroundJob(parseInfo *info)
{
return info->boolBackground;
}
void executeHistory(char * lineNumber, parseInfo *info)
{
FILE *histFile = fopen("/tmp/.c_history", "r");
char *cmdLine;
char tmp[256] = {0x0};
while (histFile != '\0' && fgets(tmp, sizeof(tmp), histFile) != '\0')
{
if (strstr(tmp, lineNumber))
{
const char *arguments[2];
char *cmdLine = strtok(tmp, lineNumber);
cmdLine = trim_ (cmdLine);
info = parse (cmdLine);
executeCmd(cmdLine, info);
break;
}
}
}
char *trim_(char *str)
{
char *end;
/* Trim leading space */
while(isspace(*str)) str++;
if(*str == 0) return str;
/* Trim trailing space */
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) end--;
/* Write new null terminator */
*(end+1) = 0;
return str;
}
void initializeJobs()
{
int i;
for (i = 0; i < 100; i++)
{
jobs[i][0] = malloc(10);
jobs[i][0] = "0";
jobs[i][1] = malloc(100);
jobs[i][1] = "...";
}
}
void addJob(pid_t childPid, char *cmd)
{
char *pid = malloc(10);
char *cmd_ = malloc(100);
int i;
memcpy(cmd_, cmd, strlen(cmd)+1);
sprintf(pid, "%d", childPid);
for (i = 0; jobs[i][1] != "..."; i++){}
jobs[i][0] = pid;
jobs[i][1] = cmd_;
fprintf(stderr, "added job: %s with pid: %s\n", cmd_, pid);
}
int executeCmd(char *cmd, parseInfo *info)
{
pid_t childPid;
int childStatus;
struct commandType *com;
com = &info->CommArray[0];
childPid = fork();
if (childPid == 0)
{
if (backgroundJob(info))
{
setpgid(0,0);
null_file = open("/dev/null", O_RDWR);
dup2(null_file, fileno(stdout));
close(null_file);
}
execvp(com->command, com->VarList);
exit(0);
}
else
{
char *cmd;
pid_t tpid;
cmd = (char*)com->command;
if (backgroundJob(info))
{
addJob(childPid, cmd);
}
else
{
while (tpid != childPid)
{
tpid = wait(&childStatus);
}
return childStatus;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include "phase2.h"
// You are free to use your own logic. The following points are just for getting started
/* Map Function
1) Each mapper selects a Mapper_i.txt to work with
2) Creates a list of letter, wordcount from the text files found in the Mapper_i.txt
3) Send the list to Reducer via pipes with proper closing of ends
*/
void phase2(int *pipefds, int c, int m){
// printf("%d\n", m);
pid_t pid;
int counts[26];
memset(&counts[0], 0, sizeof(counts));
if((pid = fork()) == -1){
perror("fork");
return;
}
if(pid == 0){
// child
// Calls phase2 recursively to create appropriate number of mappers
if(c < m-1){
phase2(pipefds, c+1, m);
exit(0);
}
exit(0);
}
else if(pid >0){
// parent
wait(NULL);
char * fl = (char *)malloc(sizeof(char)*26);
strcpy(&fl[0], "./MapperInput/Mapper_");
char int1[2];
sprintf(int1, "%d", c);
int len2 = strlen(int1);
strcpy(&fl[21], int1);
strcpy(&fl[21+len2], ".txt");
// printf("%s\n", fl);
FILE *fptr = fopen(fl, "r");
if(!fptr){
printf("Failed to open the file: %s\n", fl);
}
char txtFilePath[128];
while(fgets(txtFilePath, 128, fptr)){
// remove new line character ('\n') from path
strtok(txtFilePath, "\n");
// mark as readable, not writable (writable would cause contents to delete)
FILE *txtFilePtr = fopen(txtFilePath, "r");
char ch;
char word[100];
// Count letters case insesitive
while((fgets(word, 100, txtFilePtr)) != NULL){
ch = word[0];
if(ch >= 'a' && ch <= 'z'){
++counts[ch - 'a'];
}
else if(ch >= 'A' && ch <= 'Z'){
++counts[ch - 'A'];
}
}
fclose(txtFilePtr);
}
write(pipefds[1+(c*2)], counts, sizeof(counts)+1);
fclose(fptr);
free(fl);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int partition1(int A[], int m, int n);
void swap(int list[], int i, int j);
int kthSmall(int A[], int k, int lo, int n);
int main()
{
int num[] = {0, 53, 12, 98, 63, 18, 32, 80, 46, 72, 21};
int n = 10;
int d = 0;
int k = 2;
for (int i = 1; i <= n; i++)
printf("%d ", num[i]);
d = kthSmall(num, k, 1, n);
printf("\nThe 2nd smallest number is %d", d);
return 0;
}
void swap(int list[], int i, int j)
{
//swap list[i] and list[j]
int hold = list[i];
list[i] = list[j];
list[j] = hold;
} //end swap
int partition1(int A[], int m, int n)
{
void swap(int list[], int i, int j);
int pivot = A[m];
int lastSmall = m;
for (int i = m + 1; i <= n; i++)
{
if (A[i] < pivot)
{
++lastSmall;
swap(A, lastSmall, i);
}
}
swap(A, m, lastSmall);
return lastSmall;
}
int kthSmall(int A[], int k, int lo, int n)
{
int partition1(int A[], int m, int n);
int kShift = 1 + k - 1;
int dp = partition1(A, lo, n);
int d = 0;
if (dp != kShift)
{
if (kShift < dp)
{
n = dp - 1;
return kthSmall(A, k, lo, n);
}
else
{
lo = dp + 1;
return kthSmall(A, k, lo, n);
}
}
d = dp;
return A[d];
}
|
C
|
/*============================================================================
DPRNN(a,b; c1,c0)
Digit product.
Inputs
a, b : nonnegative BETA-digits.
Outputs
c1, c0 : the unique nonnegative BETA-digits such that a * b =
c1 * BETA + c0.
Note: This program assumes that BETA = 2^29.
============================================================================*/
#include "saclib.h"
void DPRNN(a,b, c1_,c0_)
Word a,b, *c1_,*c0_;
{
BDigit a0,a1,b0,b1,c0,c1,d0,d1,dp,p0,p1,p10,p11,p2;
const BDigit
m15 = (1 << 15) - 1,
m29 = (1 << 29) - 1,
m30 = (1 << 30) - 1;
Step1: /* Break apart the inputs. */
a0 = a & m15;
a1 = a >> 15;
b0 = b & m15;
b1 = b >> 15;
Step2: /* Multiply the parts. */
p0 = a0 * b0;
p1 = a1 * b0 + a0 * b1;
p2 = a1 * b1;
Step3: /* Add the products in base 2^30. */
p10 = p1 & m15;
p11 = p1 >> 15;
d0 = p0 + (p10 << 15);
dp = d0 >> 30;
d0 = d0 & m30;
d1 = p2 + p11 + dp;
Step4: /* Convert to base 2^29. */
c0 = d0 & m29;
dp = d0 >> 29;
c1 = (d1 << 1) | dp;
Return: /* Return c1 and c0. */
*c1_ = c1;
*c0_ = c0;
return;
}
|
C
|
#include<stdio.h>
main()
{
int a[]={10, 20, 30, 40, 50};
char *p;
p = (char *)a;
printf("%d\n", *(p+1));
printf("%d\n", *(p+16));
printf("%d\n", *((int *)p+4));
}
|
C
|
#include<stdio.h>
void main()
{
int a,b,n=0,i,j;
scanf("%d%d",&a,&b);
for(i=a;i<=b;i++)
{
for(j=2;j<=i/2;j++)
{
if(j*j==i)
{
n++;
}
}
}
printf("%d",n);
}
|
C
|
#include <stdio.h>
#define MAX_N 2000
#define MAX_L 1000
int n;
int ls[MAX_N];
int ms[MAX_L+1];
void sort(int n) {
for (int i = 0; i < n; i++) {
ms[ls[i]]++;
}
int i = 1;
int j = 0;
while (i < MAX_L+1) {
while (ms[i] > 0) {
ls[j++] = i;
ms[i]--;
}
i++;
}
}
/*
* Return the minimum index whose value is same or larger than the target value if exists, otherwise -1.
*
* l: lowest index
* h: highest index
* x: target value
*/
int search(int l, int h, int x) {
int ans;
if (ls[l] >= x) {
return l;
}
while (l <= h) {
int mid = (l + h) / 2;
if (ls[mid] < x) {
l = mid + 1;
} else if (ls[mid] >= x) {
ans = mid;
while (ans > l && ls[ans-1] == ls[ans]) {
ans--;
}
return ans;
}
}
return -1;
}
int solve(int n) {
int count = 0;
for (int i = n-1; i > 0; i--) {
for (int j = i-1; j > 0; j--) {
int a = ls[i];
int b = ls[j];
int min_c = a - b + 1;
int lim_ind = search(0, j-1, min_c);
// printf("%d %d %d\n", 0, j-1, lim_ind);
if (lim_ind < 0) {
break;
}
count += j - lim_ind;
}
}
return count;
}
int main(void) {
scanf("%d\n", &n);
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
ls[i] = x;
}
sort(n);
// for (int i = 0; i < n; i++) {
// printf("%d ", ls[i]);
// }
// printf("\n");
printf("%d\n", solve(n));
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int i,sum=0,r,temp,temp1;
clrscr();
for(i=0;i<200;i++)
{
temp=i;
temp1=i;
while(temp>0)
{
r=temp%10;
sum=sum*10+r;
temp=temp/10;
}
if(sum==temp1)
{
printf("%d\t",sum);
}
sum=0;
}
getch();
}
|
C
|
#include "byte_buffer.h"
#include "debug.h"
/* Allocate new byte buffer */
byte_buffer_t *byte_buffer_alloc()
{
byte_buffer_t *bb = (byte_buffer_t *)malloc(sizeof(byte_buffer_t));
bb->buf = (uint8_t *)malloc(FRAG);
memset(bb->buf, 0, FRAG);
bb->bufsize = FRAG;
bb->wpos = 0;
bb->rpos = 0;
return bb;
}
/* Appends an 8 bit unsigned integer (byte) to the byte buffer,
expanding it by FRAG-long fragments as needed
*/
void byte_buffer_put_byte(byte_buffer_t *bb, uint8_t ch)
{
bb->buf[bb->wpos] = ch;
bb->wpos++;
// Grow buffer
if((bb->wpos+1) > bb->bufsize)
{
uint8_t *tmp = bb->buf;
uint32_t bz = bb->bufsize + FRAG;
bb->buf = (uint8_t *)malloc(bz);
memset(bb->buf, 0, bz);
memcpy(bb->buf, tmp, bb->bufsize);
free(tmp);
bb->bufsize = bz;
}
}
/* Appends random data to the byte buffer */
void byte_buffer_put_rand(byte_buffer_t *bb, int ln)
{
uint8_t *bff = (uint8_t*)malloc(ln);
randombytes(bff, ln);
byte_buffer_put_bytes(bb, bff, ln);
free(bff);
}
/* Appends a byte array to the byte buffer */
void byte_buffer_put_bytes(byte_buffer_t *bb, uint8_t *bs, int ln)
{
for(int i = 0; i < ln; i++)
{
byte_buffer_put_byte(bb, bs[i]);
}
}
/* Appends a string to the byte buffer */
void byte_buffer_put_string(byte_buffer_t *bb, char *string)
{
byte_buffer_put_bytes(bb, (uint8_t*)string, strlen(string));
}
/* Destroys byte buffer memory allocations, making it unusable */
void byte_buffer_destroy(byte_buffer_t *bb)
{
memset(bb->buf, 0, bb->bufsize);
free(bb->buf);
memset(bb, 0, sizeof(byte_buffer_t));
free(bb);
}
/* INTEGER FUNCTIONS
===================================================
Appends a little-endian 64 bit unsigned integer to the byte buffer */
void byte_buffer_put_uint64(byte_buffer_t *bb, uint64_t v)
{
byte_buffer_put_byte(bb, (uint8_t)(v));
byte_buffer_put_byte(bb, (uint8_t)(v >> 8));
byte_buffer_put_byte(bb, (uint8_t)(v >> 16));
byte_buffer_put_byte(bb, (uint8_t)(v >> 24));
byte_buffer_put_byte(bb, (uint8_t)(v >> 32));
byte_buffer_put_byte(bb, (uint8_t)(v >> 40));
byte_buffer_put_byte(bb, (uint8_t)(v >> 48));
byte_buffer_put_byte(bb, (uint8_t)(v >> 56));
}
// Appends a little-endian 32 bit unsigned integer to the byte buffer
void byte_buffer_put_uint32(byte_buffer_t *bb, uint32_t v)
{
byte_buffer_put_byte(bb, (uint8_t)(v));
byte_buffer_put_byte(bb, (uint8_t)(v >> 8));
byte_buffer_put_byte(bb, (uint8_t)(v >> 16));
byte_buffer_put_byte(bb, (uint8_t)(v >> 24));
}
// Appends a little-endian 16-bit unsigned integer to the byte buffer
void byte_buffer_put_uint16(byte_buffer_t *bb, uint16_t v)
{
byte_buffer_put_byte(bb, (uint8_t)(v));
byte_buffer_put_byte(bb, (uint8_t)(v >> 8));
}
// Returns a little-endian 8-bit unsigned integer
uint8_t byte_buffer_get_byte(byte_buffer_t *bb)
{
if((bb->rpos+1) > bb->bufsize)
{
return 0;
}
uint8_t by = bb->buf[bb->rpos];
bb->rpos++;
return by;
}
// Returns a 64-bit unsigned integer
uint64_t byte_buffer_get_uint64(byte_buffer_t *bb)
{
return
(uint64_t)(byte_buffer_get_byte(bb)) |
(uint64_t)(byte_buffer_get_byte(bb)) << 8 |
(uint64_t)(byte_buffer_get_byte(bb)) << 16 |
(uint64_t)(byte_buffer_get_byte(bb)) << 24 |
(uint64_t)(byte_buffer_get_byte(bb)) << 32 |
(uint64_t)(byte_buffer_get_byte(bb)) << 40 |
(uint64_t)(byte_buffer_get_byte(bb)) << 48 |
(uint64_t)(byte_buffer_get_byte(bb)) << 56;
}
// Returns a 32-bit unsigned integer
uint32_t byte_buffer_get_uint32(byte_buffer_t *bb)
{
return
(uint32_t)(byte_buffer_get_byte(bb)) |
(uint32_t)(byte_buffer_get_byte(bb)) << 8 |
(uint32_t)(byte_buffer_get_byte(bb)) << 16 |
(uint32_t)(byte_buffer_get_byte(bb)) << 24;
}
// Returns a 16-bit unsigned integer
uint16_t byte_buffer_get_uint16(byte_buffer_t *bb)
{
return
(uint16_t)(byte_buffer_get_byte(bb)) |
(uint16_t)(byte_buffer_get_byte(bb)) << 8;
}
uint8_t *byte_buffer_get_bytes(byte_buffer_t *bb, int ln)
{
uint8_t *b = (uint8_t*)malloc(ln);
for(int i = 0; i < ln; i++)
{
b[i] = byte_buffer_get_byte(bb);
}
return b;
}
char *byte_buffer_get_string(byte_buffer_t *bb, char delimiter)
{
// Find location of delimiter, and calculate string size
int d_off = -1;
for(int i = bb->rpos; ;i++)
{
if(i == bb->wpos)
{
return NULL;
}
if(bb->buf[i] == (uint8_t)delimiter)
{
d_off = i + 1;
break;
}
}
if(d_off == -1)
{
return NULL;
}
// Create string buffer
int o_len = d_off - bb->rpos;
char *out = (char *)malloc(o_len + 1);
uint8_t *obuf = byte_buffer_get_bytes(bb, o_len);
memcpy(out, obuf, o_len);
free(obuf);
out[o_len] = '\0';
return out;
}
char *byte_buffer_get_dstring(byte_buffer_t *bb, char delimiter)
{
char *in = byte_buffer_get_string(bb, delimiter);
int sz = strlen(in);
char *out = malloc(sz);
memcpy(out, in, sz-1);
out[sz-1] = '\0';
free(in);
return out;
}
uint32_t secure_rand(uint32_t min, uint32_t max)
{
uint32_t range = max - min;
byte_buffer_t *bb = byte_buffer_alloc();
byte_buffer_put_rand(bb, 4);
uint32_t out = byte_buffer_get_uint32(bb);
out = out % range;
byte_buffer_destroy(bb);
return min + out;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "funcionesExtra.h"
int menuOpciones()
{
int opcion;
printf("1-Alta de alumnos \n");
printf("2-Ver listado de alumnos \n");
printf("3-Ordenar alfabeticamente \n");
printf("4-Alumnos aprobados \n");
printf("5-Alumnos cuyo nombre comienza con P \n");
printf("6-Alumno/s con nota mas alta \n");
printf("7-Modificar una nota por legajo: \n");
printf("8-Salir \n");
printf("Ingrese opcion: \n");
scanf("%d", &opcion);
system("cls");
return opcion;
}
|
C
|
/*
* This file is part of the OpenMV project.
*
* Copyright (c) 2013-2021 Ibrahim Abdelkader <iabdalkader@openmv.io>
* Copyright (c) 2013-2021 Kwabena W. Agyeman <kwagyeman@openmv.io>
*
* This work is licensed under the MIT license, see the file LICENSE for details.
*
* Rectangle functions.
*/
#include "imlib.h"
#include "array.h"
#include "xalloc.h"
rectangle_t *rectangle_alloc(int16_t x, int16_t y, int16_t w, int16_t h) {
rectangle_t *r = xalloc(sizeof(rectangle_t));
r->x = x;
r->y = y;
r->w = w;
r->h = h;
return r;
}
bool rectangle_equal(rectangle_t *r1, rectangle_t *r2) {
return ((r1->x == r2->x) && (r1->y == r2->y) && (r1->w == r2->w) && (r1->h == r2->h));
}
bool rectangle_intersects(rectangle_t *r1, rectangle_t *r2) {
return ((r1->x < (r2->x + r2->w)) &&
(r1->y < (r2->y + r2->h)) &&
((r1->x + r1->w) > r2->x) &&
((r1->y + r1->h) > r2->y));
}
// Determine subimg even if it is going off the edge of the main image.
bool rectangle_subimg(image_t *img, rectangle_t *r, rectangle_t *r_out) {
rectangle_t r_img;
r_img.x = 0;
r_img.y = 0;
r_img.w = img->w;
r_img.h = img->h;
bool result = rectangle_intersects(&r_img, r);
if (result) {
int r_img_x2 = r_img.x + r_img.w;
int r_img_y2 = r_img.y + r_img.h;
int r_x2 = r->x + r->w;
int r_y2 = r->y + r->h;
r_out->x = IM_MAX(r_img.x, r->x);
r_out->y = IM_MAX(r_img.y, r->y);
r_out->w = IM_MIN(r_img_x2, r_x2) - r_out->x;
r_out->h = IM_MIN(r_img_y2, r_y2) - r_out->y;
}
return result;
}
// This isn't for actually combining the rects standardly, but, to instead
// find the average rectangle between a bunch of overlapping rectangles.
static void rectangle_add(rectangle_t *r1, rectangle_t *r2) {
r1->x += r2->x;
r1->y += r2->y;
r1->w += r2->w;
r1->h += r2->h;
}
// This isn't for actually combining the rects standardly, but, to instead
// find the average rectangle between a bunch of overlapping rectangles.
static void rectangle_div(rectangle_t *r, int c) {
r->x /= c;
r->y /= c;
r->w /= c;
r->h /= c;
}
array_t *rectangle_merge(array_t *rectangles) {
array_t *objects; array_alloc(&objects, xfree);
array_t *overlap; array_alloc(&overlap, xfree);
/* merge overlaping detections */
while (array_length(rectangles)) {
/* check for overlaping detections */
rectangle_t *rect = (rectangle_t *) array_take(rectangles, 0);
for (int j = 0; j < array_length(rectangles); j++) {
// do not cache bound
if (rectangle_intersects(rect, (rectangle_t *) array_at(rectangles, j))) {
array_push_back(overlap, array_take(rectangles, j--));
}
}
/* add the overlaping detections */
int count = array_length(overlap);
for (int i = 0; i < count; i++) {
rectangle_t *overlap_rect = (rectangle_t *) array_pop_back(overlap);
rectangle_add(rect, overlap_rect);
xfree(overlap_rect);
}
/* average the overlaping detections */
rectangle_div(rect, count + 1);
array_push_back(objects, rect);
}
array_free(rectangles);
array_free(overlap);
return objects;
}
// Expands a bounding box with a point.
// After adding all points sub x from w and y from h.
void rectangle_expand(rectangle_t *r, int x, int y) {
if (x < r->x) {
r->x = x;
}
if (y < r->y) {
r->y = y;
}
if (x > r->w) {
r->w = x;
}
if (y > r->h) {
r->h = y;
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#define sz 1000
int main()
{
char arr[sz];
int n,i,sum=0,d,j;
scanf("%d",&n);
//printf("%d",sum);
for(i=0;i<n;i++)
{
scanf("%s",arr);
d=strlen(arr);
sum=0;
for(j=0;j<d;j++)
sum+=arr[j];
printf("Case %d: %d\n",i+1,sum);
}
return 0;
}
|
C
|
/******** mish.c **********/
// gcc -o mish mish.c
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_LINE 80
#define MAX_NUM_ARGS 10
size_t string_parser(char *input, char *word_array[]) {
size_t n = 0;
while (*input) {
while (isspace((unsigned char)*input))
++input;
if (*input) {
word_array[n++] = (char *)input;
while (*input && !isspace((unsigned char)*input))
++input;
*(input) = '\0';
++input;
}
}
word_array[n] = NULL;
return n;
}
int main(void) {
char *args[MAX_NUM_ARGS + 1]; /* command line (of 80) has max of 5 arguments */
char line[MAX_LINE + 1];
int should_run = 1;
int i;
while (should_run) {
printf("mish> ");
fgets(line,MAX_LINE,stdin);
line[strcspn(line, "\n")] = '\0';
// Separamos la línea en palabras separadas por espacio
// y las guardamos en args
if(strcmp(line,"exit")==0){// comparar cadenas
exit(0);// termina exitosamente
}
i = string_parser(line,args); // i contiene el número de argumentos
//printf("%d, %s %s\n", i, args[1],line); Es solo para pruebas borrar cuando esté listo
int pid = fork();// crea otro proceso
if(pid==0){
//hijo
execvp(args[0], &args[0]); // ejecutar comando guardado en args
printf("Programa no encontrado\n"); // si no se ejecuta imprime programa no encontrado
exit(1);// termina
}else if(pid>0){
//padre
wait(NULL);// espera al hijo
}else{
//default
exit(1);// error en el fork
}
fflush(stdout);
fflush(stdin);
line[0] = '\0';
}
return 0;
}
|
C
|
#include "ia.h"
#include "time.h"
/* ============================== FUNCIÓN PRINCIPAL ======================= */
void
tirar_ai(struct tablero *un_tablero)
{
/* Revisa si podemos comer y cuanto ganaríamos*/
int comer = podemosComer(un_tablero);
/* Revisa si nos pueden comer y cuanto perderíamos*/
int comidos = podemosSerComidos(un_tablero);
/* Es aquí donde toma la decisión de que hacer */
/* Si no podemos ni comer nada ni estamos por ser comidos pues mueve algo random*/
if(comer == 0 && comidos == 0)
{
MovimientoRandom(un_tablero);
return;
}
/* Si podemos comer o ser comido decide que es lo mejor y hazlo*/
if(comer <= comidos)
escapar(un_tablero);
else
ataca(un_tablero);
return;
}
/* =========== FUNCIONES EN LAS QUE EVALUAMOS LA SITUACIÓN ============================*/
/* ============================== Podemos comer =======================
- ¿Qué hace?
- Se va a encargar de revisar el tablero y ver si podemos comer una pieza, de ser no ser asi regresa 0
y si es posible regresa el valor asignado (8 por ejemplo si podemos comernos un caballo)
También va a modificar las coordenadas para que apunten a la pieza podemos comer y las coordenas de la pieza que
tenemos que mover para lograrlo
*/
int
podemosComer(struct tablero *un_tablero)
{
int valor;
return valor;
}
/* ============================== Podemos ser Comidos =======================
- ¿Qué hace?
- Se va a encargar de revisar el tablero y ver si estamos a punto de ser comidos, de ser no ser a si regresa 0
y si es posible regresa el valor asignado (8 por ejemplo si nos van a comer a un caballo)
También va a modificar las coordenadas para que apunten a la pieza que esta por ser comida y va a
poner las coordenadas de nuestro atacante*/
int
podemosSerComidos(struct tablero *un_tablero)
{
int valor;
return valor;
}
/* =========== FUNCIONES EN LAS QUE ACTUAMOS ==============================================*/
/* ============================== Escapar =======================
- ¿Qué hace?
- Se va a encargar de encontrar una pieza y buscar un movimiento valido y hacerlo
*/
void
escapar(struct tablero *un_tablero)
{
}
/* ============================== Atacar =======================
- ¿Qué hace?
- Se va a encargar de tomando las coordenadas de la pieza que podemos comer, realizar la acción de comerla
*/
void
atacar(struct tablero *un_tablero)
{
}
/* ============================== Movimiento Aleatorio =======================
- ¿Qué hace?
- Se va a encargar de generar un movimiento de pieza aleatorio si no vamos a comer o ser comidos
*/
void
MovimientoRandom(struct tablero *un_tablero)
{
/* Genera una semilla Random */
srand (time(NULL));
int i, j, k;
for(i=0;i<8;i++)
{
for(j=0;j<8;i++)
{
if(un_tablero == 'T')
{
/*A las coordenadas se les va a asignar la semilla rand para que mueva en un número no mayor a 8 y verificar la casilla*/
/* Es un Ejemplo por que no se usar el rand xd :*/
int x2,y2;
x2=rand()%7;
y2=rand()%7;
validar_movimiento_torre(tablero,x1,y1,x2,y2);
//Horizontal
for(k=i;k<8;k++)
{
//validaMovimiento()
}
//Vertical
/* NO se necesita volver a hacer ciclos y evaluar movimientos, para eso se hicieron las funciones de movimientos antes*/
//Horizontal
for(k=i;k<8;k++)
{
//validaMovimiento()
}
}
if(un_tablero == 'A')
{
}
if(un_tablero == 'P')
{
}
if(un_tablero == 'C')
{
}
if(un_tablero == 'D')
}
}
}
/* ============================== Funciones AUXILIARES =======================
/* ============================== Busca movimiento Valido =======================
- ¿Qué hace?
- Se encarga de ver que movimientos posibles tiene nuestras piezas
*/
/* #include <tablero.h> */
/* Sólo es un testing, de aquí se sacarán las jugadas que irán en las condicionales, se sigue trabajando en condicionales con la función principal y tablero, se trabaja en función principal, la función recibirá las coordenadas en cuanto se tenga la función solicitada se ingresará en el testing, por lo tanto, se coloca función en void, en espera de las demás funciones, se solicita ayuda de interfaz para el testing y el printf */
/*
void
testing ()
if (tablero[6][4] = 'P';)
{
}
if (tablero[0][1] = 'c';)
{
}
if (tablero[4][4] = 'P';)
{
}
if (tablero[2][2] = 'c';)
{
}
if (tablero[7][1] = 'C';)
{
}
if (tablero[0][6] = 'c';)
{
}
if (tablero[5][0] = 'C';)
{
}
if (tablero[2][7] = 'c';)
{
}
if (tablero[6][3] = 'P';)
{
}
if (tablero[3][4] = 'c';)
{
}
if (tablero[3][1] = 'C';)
{
}
if (tablero[4][2] = 'c';)
{
}
if (tablero[6][1] = 'P';)
{
}
if (tablero[1][6] = 'p';)
{
}
if (tablero[6][6] = 'P';)
{
}
if (tablero[4][6] = 'c';)
{
}
if (tablero[6][2] = 'P';)
{
}
if (tablero[0][5] = 'a';)
{
}
*/
|
C
|
#include "holberton.h"
void helper_err(int f, int c, char *str2i, int fd);
/**
* main - main function
* @argc: Amount of args
* @argv: Value of args
* Return: sometimes
*/
int main(int argc, char **argv)
{
char buffer[1024];
int file1, file2, written, closed;
ssize_t count;
helper_err(9, argc, argv[1], 0);
file1 = open(argv[1], O_RDONLY);
helper_err(6, file1, argv[1], 0);
file2 = open(argv[2], (O_WRONLY | O_TRUNC | O_CREAT), 00664);
if (file2 == -1)
{
closed = close(file1);
helper_err(10, closed, argv[1], file1);
dprintf(STDERR_FILENO, "Error: Can't write to %s\n", argv[2]);
exit(99);
}
while ((count = read(file1, buffer, sizeof(buffer))) != 0)
{
helper_err(4, count, argv[1], 0);
written = write(file2, buffer, count);
helper_err(7, written, argv[2], 0);
}
closed = close(file1);
helper_err(10, closed, argv[1], file1);
closed = close(file2);
helper_err(10, closed, argv[1], file2);
return (0);
}
/**
* helper_err - helper
* @f: Passes in a 4 for read, a 7 for write, a 10 for close, a 6 for file1,
* 9 if argc is too big
* @c: Value
* @str2: String to use somtimes
* @fd: File descriptor
* Return: Never
*/
void helper_err(int f, int c, char *str2, int fd)
{
if (f == 4 && c == -1)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", str2);
exit(98);
}
if (f == 7 && c == -1)
{
dprintf(STDERR_FILENO, "Error: Can't write to %s\n", str2);
exit(99);
}
if (f == 6 && c == -1)
{
dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", str2);
exit(98);
}
if (f == 9 && c != 3)
{
dprintf(STDERR_FILENO, "Usage: cp file_from file_to\n");
exit(97);
}
if (f == 10 && c == -1)
{
dprintf(STDERR_FILENO, "Error: Can't close fd %d", fd);
exit(100);
}
}
|
C
|
/*
** EPITECH PROJECT, 2020
** minishell
** File description:
** main file
*/
#include <stdlib.h>
#include "my.h"
void print_cmd_continue(minishell_t *shell)
{
my_putstr(BLUE);
my_putstr(shell->floca);
if (shell->result != 0)
my_putstr(RED);
else
my_putstr(GREEN);
my_putstr(" $ ");
my_putstr("\e[0;39m");
my_putstr("\e[96m");
}
void print_cmd(minishell_t *shell)
{
if (is_same_str(shell->name, "root", 4) == 0) {
my_putstr(BLUE);
my_putstr(shell->floca);
if (shell->result != 0)
my_putstr(RED);
else
my_putstr(GREEN);
my_putstr(" $ ");
my_putstr("\e[0;39m");
} else
return (print_cmd_continue(shell));
}
int my_exit(void)
{
my_putstr("exit\n");
exit(0);
}
int minishell(minishell_t *shell)
{
int loop = 0;
if (init_shell(shell) != 0) return (1);
shell->result = 0;
while (loop == 0) {
shell->name = get_username(shell);
print_cmd(shell);
shell->shell_cmd = get_next_line(0);
if (shell->shell_cmd == NULL) return (my_exit());
shell->cmd = detect_wave(shell, strtab(shell->shell_cmd));
if (shell->cmd == NULL) return (my_exit());
my_putstr("\e[0;39m");
shell->result = exec_command(shell);
if (shell->result == 66) return (my_exit());
shell->floca = get_cur_dir();
if (shell->floca == NULL) return (EXIT_FAILURE);
}
}
int main(int ac, char **arg, char **env)
{
minishell_t *shell = malloc(sizeof(minishell_t));
if (env == NULL) return (1);
shell->env_char = env;
minishell(shell);
return (EXIT_SUCCESS);
}
|
C
|
long repeatedString(char* s, long n) {
long i, num, a_ct, rem, ct = 0;
int len = strlen(s);
for(i=0; i<len; i++)
{
if(s[i] == 'a')
ct++;
}
num = n/strlen(s);
a_ct = ct * num;
if(n % len != 0)
{
rem = n % len;
for(i=0; i<rem; i++)
{
if(s[i] == 'a')
a_ct++;
}
}
return a_ct;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include"add.h"
int main()
{
int a = 10;
int b = 20;
int sum = ADD(a,b);
printf("%d\n",sum);
return 0;
}
|
C
|
/* Menu du TP 5 - Arbre AVL / quilibrage */
#include<stdio.h>
#include<stdlib.h>
#include "ab.h"
void purge(){
char c;
do{
scanf("%c", &c);
}while(c!='\n');
}
/* affiche l'arbre dans l'ordre croissant */
void afficher(t_noeud* n)
{
if(!arbre_vide(n)){
printf("%d ", val_noeud(n));
//printf("addr: %p\tpere : %p filsg : %p filsd: %p\n", n, n->pere, n->fg, n->fd);
if(filsg(n))
afficher(fg(n));
if(filsd(n))
afficher(fd(n));
}
}
int max(int a, int b){
return (a>b)?a:b;
}
int hauteur(t_noeud* n){
if(arbre_vide(n)){
return -1;
}
else return 1+max(hauteur(fg(n)), hauteur(fd(n)));
}
int est_equilibre(t_noeud* n){
if(feuille(n))
return 1;
else
return ( est_equilibre(fg(n)) && est_equilibre(fd(n)) && abs(hauteur(fg(n)) - hauteur(fd(n))) <= 1 );
}
/* fonction ok */
t_noeud* rotation_gauche(t_noeud* n)
{
t_noeud* rac = fd(n);
if(n && rac){
n->fd = fg(rac);
if(n->pere != NULL){
if(n->pere->fd == n)
n->pere->fd = rac;
else n->pere->fg = rac;
}
rac->pere = n->pere;
rac->fg = n;
n->pere = rac;
return rac;
}
else return n;
}
/* fonction ok */
t_noeud* rotation_droite(t_noeud* n)
{
t_noeud* rac = fg(n);
if( n && rac ){
n->fg = fd(rac);
if(n->pere != NULL){
if(n->pere->fd == n)
n->pere->fd = rac;
else n->pere->fg = rac;
}
rac->pere = n->pere;
rac->fd = n;
n->pere = rac;
return rac;
}
else return n;
}
void equilibrer(t_noeud* n)
{
if(arbre_vide(n))
return;
int hd, hg, diff; /* hauteur droit, gauche et difference */
if(filsg(n)){
equilibrer(fg(n));
hg = hauteur(fg(n));
}else hg = -1;
if(filsd(n)){
equilibrer(fd(n));
hd = hauteur(fd(n));
}else hd = -1;
diff = hd - hg;
if(diff >1){
equilibrer(rotation_droite(n));
}else if(diff < -1){
equilibrer(rotation_gauche(n));
}
}
/* fonction ok */
t_noeud* ajouter(t_noeud* r, int val)
{
if(arbre_vide(r))
return creer_noeud(val);
else if(val < val_noeud(r)){
if(!filsg(r))
return ajout_filsg(r, val);
else if(filsg(r))
return ajouter(fg(r), val);
}
else if(val_noeud(r)==val){
printf("valeur deja presente dans l'arbre\n");
return r;
}
else { // si val_noeud(r) < val
if(!filsd(r))
return ajout_filsd(r, val);
else if(filsd(r))
return ajouter(fd(r), val);
}
return NULL;
}
t_noeud* sousArb_desequilibre(t_noeud* n){
if(arbre_vide(n))
return NULL;
if(abs(hauteur(fg(n)) - hauteur(fd(n))) > 1)
return n;
return (sousArb_desequilibre(fg(n)))? sousArb_desequilibre(fg(n)): sousArb_desequilibre(fd(n)) ;
}
/*
void ajouter_equilibre(t_noeud* n, int val)
{
if(n = ajouter(n, val)){
if(!est_equilibre(n)){
n = sousArb_desequilibre(n);
if(hauteur(fg(n)) - hauteur(fd(n)) == 2){
}
}
}
printf("Ce traitement n'est pas encore disponible\n");
}*/
/* Programme principal */
int main(void)
{
int choix; /* Choix de l'utilisateur */
int val;
t_noeud* r = NULL;
do
{ /* Affichage du menu */
printf("\nMenu :\n");
printf(" 1 - Ajouter une valeur sans rquilibrage\n");
printf(" 2 - Ajouter une valeur\n");
printf(" 3 - Rotation gauche\n");
printf(" 4 - Rotation droite\n");
printf(" 5 - Equilibrer l'arbre\n");
printf(" 6 - Afficher l'arbre dans l'ordre croissant\n");
printf(" 7 - Afficher la hauteur de l'arbre\n");
printf(" 8 - Verifier si l'arbre est equilibr \n");
printf(" 9 - Quitter\n");
printf("Votre choix : ");
scanf("%i",&choix);
/* Traitement du choix de l'utilisateur */
switch(choix)
{
case 1:
printf("Quelle entier voulez vous ajouter ?\n");
purge();
scanf("%i", &val);
r = ajouter(r, val);
break;
case 2: ajouter_equilibre(); break;
case 3: printf("avant rotation\n");
afficher(r);
r = rotation_gauche(r);
printf("aprs rotation\n");
r=racine(r);
afficher(r);
break;
case 4: printf("avant rotation\n");
afficher(r);
r = rotation_droite(r);
printf("apres rotation\n");
r= racine(r);
afficher(r);
break;
case 5: equilibrer(r); break;
case 6: afficher(r); break;
case 7: printf("la hauteur est de %d\n", hauteur(r)); break;
case 8: printf("l'arbre est %s\n", (est_equilibre(r))? "equilibre" : "pas equilibre");
case 9: break;
default: printf("Erreur: votre choix doit tre compris entre 1 et 7\n");
}
r = racine(r);
}
while( choix != 9 );
printf("Au revoir !\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "matrix.h"
double _random(const double min, const double max)
{
return ((double) rand() / RAND_MAX) * (max - min + 1) + min;
}
int **createMatrix(size_t n, size_t m)
{
int **matrix;
if ((matrix = (int **) malloc(n * sizeof(int *))) == NULL)
{
return NULL;
}
for (size_t i = 0; i < n; i++)
{
matrix[i] = (int *) calloc(m, sizeof(int));
if (matrix[i] == NULL)
{
return NULL;
}
}
return matrix;
}
void fillMatrix(size_t n, size_t m, int **matrix, const int range[2])
{
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < m; j++)
{
matrix[i][j] = _random(range[0], range[1]);
}
}
}
void printMatrix(size_t n, size_t m, int **matrix)
{
for (size_t i = 0; i < n; i++, printf("\n"))
{
for (size_t j = 0; j < m; j++)
{
printf("%6d ", matrix[i][j]);
}
}
printf("\n");
}
void freeMatrix(size_t n, int **matrix)
{
for (size_t i = 0; i < n; i++)
{
free(matrix[i]);
}
free(matrix);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ git_oid_shorten ;
/* Variables and functions */
size_t MAX_OIDS ;
int /*<<< orphan*/ cl_assert (int) ;
int /*<<< orphan*/ cl_assert_equal_b (int,int) ;
int /*<<< orphan*/ free_oids (size_t,char**) ;
int /*<<< orphan*/ git_oid_shorten_free (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ * git_oid_shorten_new (int /*<<< orphan*/ ) ;
int insert_sequential_oids (char***,int /*<<< orphan*/ *,size_t,size_t) ;
scalar_t__ memcmp (char*,char*,int) ;
void test_object_raw_short__oid_shortener_stresstest_git_oid_shorten(void)
{
#define MAX_OIDS 1000
git_oid_shorten *os;
size_t i, j;
int min_len = 0, found_collision;
char **oids;
os = git_oid_shorten_new(0);
cl_assert(os != NULL);
/*
* Insert in the shortener 1000 unique SHA1 ids
*/
min_len = insert_sequential_oids(&oids, os, MAX_OIDS, MAX_OIDS);
cl_assert(min_len > 0);
/*
* Compare the first `min_char - 1` characters of each
* SHA1 OID. If the minimizer worked, we should find at
* least one collision
*/
found_collision = 0;
for (i = 0; i < MAX_OIDS; ++i) {
for (j = i + 1; j < MAX_OIDS; ++j) {
if (memcmp(oids[i], oids[j], min_len - 1) == 0)
found_collision = 1;
}
}
cl_assert_equal_b(true, found_collision);
/*
* Compare the first `min_char` characters of each
* SHA1 OID. If the minimizer worked, every single preffix
* should be unique.
*/
found_collision = 0;
for (i = 0; i < MAX_OIDS; ++i) {
for (j = i + 1; j < MAX_OIDS; ++j) {
if (memcmp(oids[i], oids[j], min_len) == 0)
found_collision = 1;
}
}
cl_assert_equal_b(false, found_collision);
/* cleanup */
free_oids(MAX_OIDS, oids);
git_oid_shorten_free(os);
#undef MAX_OIDS
}
|
C
|
#include <stdio.h>
#include "./libdoublylinkedlist/DoublyLinkedList.c"
int main() {
DoublyLinkedList* mylist = create_doubly_linked_list();
printf("Pushing numbers to linked list\n");
for (int i = 1; i <= 5; i++) {
printf("Pushing, %d...\n", i * 10);
push(i * 10, mylist);
}
printf("\nLinked List:\n");
printf("-> top address: %p\n", mylist->head);
printf("-> top: %d\n", mylist->head->value);
printf("-> tail address: %p\n", mylist->tail);
printf("-> tail: %d\n", mylist->tail->value);
printf("Elements:\n");
traverse(mylist);
// traverse_reverse(mylist);
printf("Popping, %d...\n", pop(mylist));
printf("Popping, %d...\n", pop(mylist));
printf("Shifting, %d...\n", shift(mylist));
printf("Shifting, %d...\n", shift(mylist));
printf("\nLinked List:\n");
printf("-> top address: %p\n", mylist->head);
printf("-> top: %d\n", mylist->head->value);
printf("-> tail address: %p\n", mylist->tail);
printf("-> tail: %d\n", mylist->tail->value);
printf("Elements:\n");
traverse(mylist);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <unistd.h>
int send_mode = 0;
int max_mail_len = 2000;
int max_output_line = 500;
int main(int argc, char** argv){
int sender = 0;
int data = 0;
char* mail_address = NULL;
char* title = NULL;
char body[max_mail_len];
for(int i = 0; i < max_mail_len; i++) body[i] = '\0';
if(argc == 2){
if(!strcmp(argv[1],"nadawca")) sender = 1;
else if(!strcmp(argv[1],"data")) data = 1;
else{
printf("Wrong arguments");
return -1;
}
}else if(argc >= 4){
mail_address = argv[1];
title = argv[2];
int i = 3;
while(argc - i > 0 && i < max_mail_len){
sprintf(body,"%s %s", body, argv[i]);
i++;
}
send_mode = 1;
}else{
printf("Wrong numbers of arguments: %d", argc);
return -1;
}
FILE *email_list;
char *command;
if(send_mode == 1){
command = malloc(sizeof(char)* max_mail_len);
sprintf(command, "echo '%s' | mail -s '%s' %s", title, body, mail_address);
printf("%s\n", command);
email_list = popen(command, "r");
if (email_list == NULL){
printf("Popen failed");
exit(-1);
}
//nie ma zwrotnej wiadomości
printf("mail send to receiver\n");
}else{
if(sender)command = "echo | mail -f /var/mail/zuzanna | awk '1;/Message/{exit}' | sed '1d;2d;3d;$d' | sort -k2";
else if(data) command = " echo | mail -f /var/mail/zuzanna | awk '1;/Message/{exit}' | sed '1d;2d;3d;$d' | sort -k4M -k5 -k6";
printf("sorted by: \n");
email_list = popen(command, "r");
if (email_list == NULL){
printf("Popen failed");
exit(1);
}
char line[max_output_line];
while(fgets(line, max_output_line, email_list) != NULL){
printf("%s", line);
}
}
return 0;
}
|
C
|
#include <unistd.h>
#include <stdlib.h>
void ft_putnbr(int nb)
{
int i;
if (nb < 0)
{
write(1, "-", 1);
nb *= -1;
}
i = '0' + (nb % 10);
if (nb > 9)
ft_putnbr(nb / 10);
write(1, &i, 1);
}
int main(int ac, char **av)
{
if (ac == 2)
{
ft_putnbr((atoi(av[1])));
}
}
|
C
|
#ifndef KFIFO_H_
#define KFIFO_H_
//声明 一个 结构体 kfifo
#include <stdint.h>
struct KFIFO
{
unsigned char *buffer; /* the buffer holding the data */
unsigned int size; /* the size of the allocated buffer */
unsigned int in; /* data is added at offset (in % size) */
unsigned int out; /* data is extracted from off. (out % size) */
/*STM32 只有一个核心,同一时刻只能写或者读,因此不需要*/
// volatile unsigned int *lock; /* protects concurrent modifications */
};
typedef struct KFIFO KFIFO;
unsigned int roundup_pow_of_two( unsigned int date_roundup_pow_of_two );
#ifdef KFIFO_DYNAMIC_ALLOCATE
// initialize a KFIFO struct using static buffer
// size: must be round power of 2 (16, 32, 64, 128, 256 ...)
struct KFIFO *kfifo_alloc(unsigned int size);
#endif
void kfifo_static_init(KFIFO* p, uint8_t* buf, unsigned int size);
unsigned int __kfifo_put(struct KFIFO *fifo, const unsigned char *buffer, unsigned int len);
unsigned int __kfifo_get(struct KFIFO *fifo, unsigned char *buffer, unsigned int len);
#endif
|
C
|
#include<stdio.h>
#include<sys/types.h>
void main()
{
pid_t pid;
pid = fork();
if(pid == 0)
{
printf("Child Process!\n");
}else{
printf("hi %d\n",pid);
}
}
|
C
|
#include <stdio.h>
#include "graph.h"
int main(){
Graph *graph = make_Graph();
int i;
int numOfNode, numOfEge;
int a, b, weight;
int *result;
int start;
/* 頂点の数と辺の数の入力 */
printf("頂点の数を入力してください: ");
scanf("%d", &numOfNode);
printf("辺の数を入力してください: ");
scanf("%d", &numOfEge);
/* ノードをつくる */
for(i = 0; i < numOfNode; i++) addNode_Graph(graph);
/* 辺をつくる */
printf("ノード1の番号とノード2の番号, 重みを入力してください.\n");
printf("例: 1番のノードと2番のノードをつないで5の重みをつけたいとき,\n");
printf("1 2 5 と入力する\n");
for(i = 0; i < numOfEge; i++){
printf("%d:", i+1);
scanf("%d %d %d", &a, &b, &weight);
link_Graph(graph, a, b, weight);
}
/* スタートのノードを決定する */
printf("始点を入力してください: ");
scanf("%d", &start);
/* ダイクストラで解く */
result = (int*)malloc(sizeof(int) * numOfNode);
solve_Dijkstra(graph, start, result);
/* 結果を表示 */
for(i = 0; i < numOfNode; i++)
printf("%d...%d\n", i+1, result[i]);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
__attribute__((used)) static int stem(
char **pz, /* The word being stemmed (Reversed) */
const char *zFrom, /* If the ending matches this... (Reversed) */
const char *zTo, /* ... change the ending to this (not reversed) */
int (*xCond)(const char*) /* Condition that must be true */
){
char *z = *pz;
while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
if( *zFrom!=0 ) return 0;
if( xCond && !xCond(z) ) return 1;
while( *zTo ){
*(--z) = *(zTo++);
}
*pz = z;
return 1;
}
|
C
|
/*--------------------------------------------------------------------------------------------------------------------------*/
/*---------------------------------------FreeRTOS General Example------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------*/
/*Tools used from FreeRTOS:
* - Concurrent performance of tasks.
* - Priority utilization.
* - Queues for inter-task communications.
* - Binary sempahores for multitask synchronization.
* - Group events for more complex task synchronization and signaling (To be added)
*
* Highest priority task creates 2 queues containing a list of color strings and RGB pins to activate associated colors.
* When a failing edge is detected on PortF pin0, a binary semaphore is released allowing synchronization with another task
* sending the color string via UART and writing RGB led with associated colors.
* A third task takes a peek from the queue without removing the item and used received value to set a bit in the group event byte.
*/
/*--------------------------------------------------------------------------------------------------------------------------*/
/*-------------------------------------------General personal Libraries-----------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------*/
#include "REG.h"
#include "DIO.h"
#include "PLL.h"
#include "UART0.h"
#include "itoaX.h"
/*--------------------------------------------------------------------------------------------------------------------------*/
/*-------------------------------------------FreeRTOS libraries-------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "semphr.h"
#include "event_groups.h"
#define SWITCHTASKSTACKSIZE 128
/*--------------------------------------------------------------------------------------------------------------------------*/
/*-------------------------------------------Type definitions-------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------*/
typedef unsigned char u8;
/*--------------------------------------------------------------------------------------------------------------------------*/
/*-------------------------------------------Initializing-------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------*/
QueueHandle_t First_Q,String_Q; //one queue for color strings and one queue for rgb pins in PortF
EventGroupHandle_t Group1; //to be added next
SemaphoreHandle_t Client_Sem; //binary sempahore to synchronize the arrival of new color with its execution
/*--------------------------------------------------------------------------------------------------------------------------*/
/*-------------------------------------------Data to be passed using queues-------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------*/
u8 colors[7] = {RED,BLUE,GREEN,YELLOW,CYAN,WHITE,PINK};
char *colors2[7] = {"RED","BLUE","GREEN","YELLOW","CYAN","WHITE","PINK"};
/*--------------------------------------------------------------------------------------------------*/
/*-------------------------------------------Task 1-------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/
/*Receive from queue after acknowledging the arrival of new color through semaphore*/
volatile u8 data = 0 ;
char str[];
void Task1(void * para){
Client_Sem = xSemaphoreCreateBinary(); //create sempahore "client_sem"
xSemaphoreTake( Client_Sem, (TickType_t)0 ); //intilaize it as already taken
u8 led_color = RED;
char * current_color = "RED";
while(1){
UART0_SendString("to receive queue");
UART0_Println();
/*will wait until the release of semaphore*/
xSemaphoreTake( Client_Sem, (TickType_t)portMAX_DELAY );
UART0_SendString("Semaphore taken"); //UART debugging
UART0_Println(); //using macro from UART.h
xQueueReceive( First_Q, ( void * ) &( led_color ), (TickType_t)0); //receive string from queue one
xQueueReceive( String_Q,( void * ) &(current_color), (TickType_t)0);//receive PortF RGB pins from queue two
/* UART0_SendString(itoaX(led_color, str, 10)); //UART send PortF RGB LED Pins for debugging
UART0_Println();*/
DIO_PortWrite(PortF,led_color,DIO_HIGH);//activate RGB
}
}
/*--------------------------------------------------------------------------------------------------*/
/*-------------------------------------------Task 2-------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/
/*Create 2 queues and send to each queue when failling edge is detected on PortF pin0 (connected to HW push-button)*/
//higher priority will run first to create queues
void Task2(void * para) {
First_Q = xQueueCreate( 2, sizeof(u8) ); //create RGB pins queue
String_Q = xQueueCreate( 2, sizeof(colors2) ); //create color strings
UART0_SendString("QueueCreate"); //UART debugging
UART0_Println();
u8 i = 0,led_color = RED,flag_low = Pin0 ; //to work on falling edge
char * current_color= "RED";
while(1)
{
DIO_PortRead(PortF,Pin0,&data);
if((data == DIO_LOW) && (flag_low == Pin0)) //active low , if button is pressed , and last time was high
{
UART0_SendString("-----------------");//Beginning of new queue item to be transmitted
UART0_Println();
//Bring new color
led_color = colors[i];
current_color = colors2[i];
//UART0_SendString(itoaX(led_color, str, 10));
//UART0_Println();
i++;//for next tranmission
xQueueSend( First_Q,( void * ) &led_color, (TickType_t )1000);
xQueueSend( String_Q,( void * ) ¤t_color, (TickType_t )1000);
UART0_SendString("queue item sent");//UART debugging
UART0_Println();
i = i%7;
if( xSemaphoreGive(Client_Sem) != pdTRUE )//give semaphore to synchronize next "receive" task
{
//pdTRUE if the semaphore was released. pdFALSE if an error occurred. Semaphores are implemented using queues.
}
}
flag_low = data;
vTaskDelay(100); //ever 10 tick, as 10 ms
}
}
void Task3(void * para){
//u8 led_color;
char * current_color ;
while(1){
if (xQueuePeek( String_Q, &(current_color), (TickType_t)0)!= pdTRUE ){//if there is an item in the queue
xQueuePeek( String_Q, &(current_color), (TickType_t)portMAX_DELAY); //takes a copy of the queue item without removing it from the queue
UART0_SendString("Peek OK:");
UART0_SendString(current_color);
UART0_Println();
//Set group event if color matched
}
vTaskDelay(50);
}
}
/*
void Task4(void * para){
u8 state = DIO_HIGH;
while(1){
xEventGroupWaitBits(Group1,Pin0|Pin1||Pin2 ,pdTRUE,pdTRUE,(TickType_t)portMAX_DELAY );
DIO_PortWrite(PortF,YELLOW,state);
state ^= 0xFF;
}
}
*/
int main(void) {
PLL_Init();//Selection of 80 MHz clock using phase locked loop and main oscillator
UART0_Init(9600,80000000);
DIO_PortInit(PortF, Pin0|Pin1|Pin2|Pin3|Pin4 , Pin0|Pin4);//Initilization of Pins on PortF and Pins to pullup for edge triggered buttons
DIO_PortDirection(PortF , Pin1|Pin2|Pin3, DIO_OUTPUT);
DIO_PortDirection(PortF , Pin0|Pin4, DIO_INPUT);
TaskHandle_t First_handle,Second_handle,Third_handle;//task declaration
//TaskHandle_t First_handle,Second_handle,Third_handle,Fourth_handle;
xTaskCreate(Task1, "Receive from queue",SWITCHTASKSTACKSIZE, NULL,1, &First_handle);//task1 initialization
xTaskCreate(Task2, "Create queue and send",SWITCHTASKSTACKSIZE, NULL,3, &Second_handle);//task2 initialization
xTaskCreate(Task3, "Peek queue",SWITCHTASKSTACKSIZE, NULL,2, &Third_handle);//task3 initialization
// xTaskCreate(Task4, "Task4",SWITCHTASKSTACKSIZE, NULL,1, &Fourth_handle);task4 initialization
UART0_Println();
UART0_SendString("--------------Start-------------");
UART0_Println();
vTaskStartScheduler();
return 0;
}
|
C
|
int printf(char *s, ...);
struct S { int i,j; };
struct S s0={30,40};
struct S const s1={50,60};
void f() { printf("f()\n"); }
void g() { printf("g()\n"); }
void f0(double x) {
struct S *p;
void *q;
printf("%d\n",x?10:20);
printf("%d\n",(x?s0:s1).j);
x?f():g();
printf("%d\n",(x?&s0:&s1)->j);
p=x?&s0:0;
if(p!=0) printf("%d\n",p->j); else printf("null\n");
q=x?&s0:(void *)&s1;
printf("%d\n",((struct S *)q)->j);
}
int main() {
double x;
struct S *p;
void *q;
printf("%d\n",1.?10:20);
printf("%d\n",(1.?s0:s1).j);
1.?f():g();
printf("%d\n",(1.?&s0:&s1)->j);
p=1.?&s0:0;
if(p!=0) printf("%d\n",p->j); else printf("null\n");
q=1.?&s0:(void *)&s1;
printf("%d\n",((struct S *)q)->j);
printf("%d\n",0.?10:20);
printf("%d\n",(0.?s0:s1).j);
0.?f():g();
printf("%d\n",(0.?&s0:&s1)->j);
p=0.?&s0:0;
if(p!=0) printf("%d\n",p->j); else printf("null\n");
q=0.?&s0:(void *)&s1;
printf("%d\n",((struct S *)q)->j);
x=1.;
printf("%d\n",x?10:20);
printf("%d\n",(x?s0:s1).j);
x?f():g();
printf("%d\n",(x?&s0:&s1)->j);
p=x?&s0:0;
if(p!=0) printf("%d\n",p->j); else printf("null\n");
q=x?&s0:(void *)&s1;
printf("%d\n",((struct S *)q)->j);
x=-0.;
printf("%d\n",x?10:20);
printf("%d\n",(x?s0:s1).j);
x?f():g();
printf("%d\n",(x?&s0:&s1)->j);
p=x?&s0:0;
if(p!=0) printf("%d\n",p->j); else printf("null\n");
q=x?&s0:(void *)&s1;
printf("%d\n",((struct S *)q)->j);
f0(1.); f0(-0.);
return 0;
}
|
C
|
/*-------------------------------------------------------------------------------------------------------------------------------
strinsert.c
Program to insert a string into another
DIVYA RAJ K
11-11-2018
---------------------------------------------------------------------------------------------------------------------------------*/
#include<stdio.h>
#include<stdlib.h>
void strinsert(int N,char S[20],char T[20],char U[20]);
main()
{
char S[20],T[20],U[20];
int N;
system("clear");
printf("Enter a string: ");
scanf("%s",S);
printf("\nEnter the second string which you have to insert into string 1: ");
scanf("%s",T);
printf("\nEnter the location:");
scanf("%d",&N);
strinsert(N,S,T,U);
printf("\nThe string after inserting: %s",U);
}
void strinsert(int N,char S[20],char T[20],char U[20])
{
int i=0,j=0,a,b,slen,tlen;
while(S[i]!='\0')
{
i++;
}
while(T[j]!='\0')
{
j++;
}
slen=i;
tlen=j;
a=0;
b=0;
while(a<=slen){
U[a]=S[a];
a++;
}
while(b<=tlen){
U[a]=T[j];
a++;
j++;
b++;
}
while(S[N]!='\0'){
U[a]=S[N];
a++;
N++;
}
}
|
C
|
#ifndef _UTILSC_
#define _UTILSC_
int isValid (char value, char * validChars) {
int i = 0;
while(validChars[i]){
if (value == validChars[i++]) return value;
}
printf("\nINVALID INPUT. Please try again.\n");
return 0;
}
#endif
|
C
|
/** @file utils.c
Various utility functions (not platform-specific, "portable")
*/
#include "utils.h"
#include "globals.h"
#include "log.h"
#include <sys/stat.h>
/** isprint(c) substitute
The standard function won't allow chars >= chr(128).
We'll accept anything that's neither a control char nor DEL.
*/
#define ISPRINT(c) ((c) >= 32 && (c) != 127)
// tiny 'inflate' (zlib decompressor), see tinfl.c
#define TINFL_HEADER_FILE_ONLY
#include "tinfl.c"
/// hex dump utility, prints `len` bytes from address `addr`
void hexdump(const uint8_t *addr, size_t len) {
char hex[49], *p;
char txt[17], *c;
size_t n;
for (n = 0; n < len; n += 16) {
register size_t i = n;
p = hex;
c = txt;
do {
p += sprintf(p, "%02x ", addr[i]);
*c++ = ISPRINT(addr[i]) ? addr[i] : '.';
} while ((++i % 16) && i < len);
*c = '\0';
log_info("hexdump", "0x%08X [%04X] %-48s- %s", addr + n, n, hex, txt);
}
}
/// Test if pointer references some gzipped data.
/// This is done by checking for special signature bytes (see RFC 1952).
inline bool is_gzipped(const char *data) {
return (data && data[0] == 31 && data[1] == -117); // 0x1F, 0x8B = gzip signature
}
// Gzip-decompression from an input buffer to (heap) memory.
// This function expects the data to start with a gzip-compatible header, and
// uses tinfl_decompress_mem_to_heap() for the actual decompression. In case of
// any error, it will return NULL. When successful, you will receive a (malloc)
// pointer to the decompressed data, and *decompressed_size will be set to the
// number of output bytes.
// Note: You are responsible for calling free() on the result later!
void *gzip_decompress(const char *data, size_t len, size_t *decompressed_size) {
if (!decompressed_size) {
error("%s(): you must pass a pointer to a decompressed_size variable!",
__func__);
return NULL;
}
*decompressed_size = 0;
if (!is_gzipped(data)) {
error("%s(): data at %p has no gzip signature!", __func__, data);
return NULL;
}
// let's check some header fields (see RFC 1952)
if (data[2] != 8) {
error("%s(): suspicious compression method (expected 8, got %d)",
__func__, data[2]);
return NULL;
}
if (data[3] & (~0x09)) {
// bit 0 indicates text/binary and can be safely ignored
// bit 3 is the only other flag we recognize and respect, it indicates presence of the original filename
error("%s(): unsupported header flags 0x%.2X", __func__, data[3]);
return NULL;
}
size_t offset = 10; // minimum header size, offset to actual start of compressed data
if (data[3] & 0x08) {
// original filename present (directly after the basic gzip header), get string length
int len_name = strlen(data + offset);
if (len_name <= 0) {
error("%s(): invalid length %d for original filename", __func__, len_name);
return NULL;
}
//debug("%s(): original filename was '%s'", __func__, data + offset);
offset += len_name + 1; // (skip filename and trailing NUL)
}
// a bit of pointer arithmetic (taking care of the header's length), and we're good to go!
len -= offset;
char *result = tinfl_decompress_mem_to_heap(data + offset, len, decompressed_size, 0);
if (!result)
error("%s(): gzip decompression FAILED!", __func__);
#if CFG_DEBUG
else
debug("%s(): successfully decompressed %u bytes to 0x%p",
__func__, *decompressed_size, result);
#endif
return result;
}
/// return the full path to the dynamic library (dir + filename + extension)
inline const char *get_dll_path(void) {
return lcfr_globals.dllpath;
}
/// return the DLL directory
/// (without the filename, but including the trailing path separator)
const char *get_dll_dir(void) {
static char DLL_DIR[PATH_MAX] = {0};
if (DLL_DIR[0] == 0) {
strncat(DLL_DIR, get_dll_path(), sizeof(DLL_DIR));
// starting at the end, remove any characters until a path separator is found
char *trailing;
for (trailing = strrchr(DLL_DIR, '\0'); --trailing >= DLL_DIR; ) {
if (*trailing == '/' || *trailing == '\\') break;
*trailing = '\0';
}
}
return DLL_DIR;
}
/// retrieve the image base (memory address) of the dynamic library
inline void *get_dll_image_base(void) {
return DLL_HANDLE;
}
/// test if a file (or directory) exists
inline bool file_exists(const char *filename) {
struct stat buffer;
return stat(filename, &buffer) == 0;
}
|
C
|
// fixed wear/unwear to use ETO, added obvious short-last change was 7/98 *Styx*
#include <std.h>
inherit ARMOUR;
void create(){
::create();
set_name("amulet");
set_id(({"amulet","amulet of warding"}));
set_obvious_short("%^BOLD%^%^CYAN%^wooden amulet%^RESET%^");
set_short("%^BOLD%^%^CYAN%^Amulet of warding%^RESET%^");
set_long("%^BOLD%^%^CYAN%^"
"This strange amulet depicts a crescent moon surrounded by flames. "
"The picture has been carved upon the wooden disc surface of the amulet and "
"the disc hangs from a plain straw like necklace. A faint glow "
"surrounds the disc.%^RESET%^"
);
set_weight(5);
set_value(200);
set_wear((: this_object(),"wearit" :));
set_remove((:this_object(),"removeit" :));
set_type("clothing");
set_item_bonus("magic resistance",2);
set_limbs(({"neck"}));
}
int wearit(){
if((int)ETO->query_level() < 25) {
write("As you wear the amulet it vanishes!");
TO->remove();
return 0;
}
write("%^BOLD%^%^CYAN%^You feel your body surrounded by a strange "
"force!%^RESET%^");
tell_room(environment(ETO), "%^BOLD%^%^CYAN%^A strange glow surrounds "
+ETOQCN+"!%^RESET%^" ,ETO);
return 1;
}
int removeit(){
write("%^BOLD%^%^CYAN%^The strange force that surrounded your body "
"suddenly fades away!%^RESET%^" );
tell_room(environment(ETO),
"%^BOLD%^%^CYAN%^Slowly a faint glow surrounding "+ETOQCN+" shimmers "
"briefly and vanishes!%^RESET%^",ETO);
return 1;
}
|
C
|
#include <stdio.h>
#include "matrix.h"
Matrix matrix_create(int row, int col)
{
Matrix mat = {.row=row, .col=col};
mat.values = malloc(sizeof(*(mat.values)) * row);
return_val_if_fail(mat.values != NULL, (Matrix){0});
mat.values[0] = calloc(row, sizeof(*(mat.values[0])) * col);
return_val_if_fail(mat.values[0] != NULL, (Matrix){0});
for (int i = 1; i < row; ++i)
mat.values[i] = mat.values[0] + i * col;
return mat;
}
void matrix_create_all(Matrix * const mats, int num_mat, int row, int col)
{
for (int i = 0; i < num_mat; ++i)
mats[i] = matrix_create(row, col);
}
Matrix create_mat_1s(int row, int col)
{
Matrix mat = matrix_create(row, col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
mat.values[i][j] = 1;
return mat;
}
Matrix create_val_per_col(int row, int col)
{
Matrix mat = matrix_create(row, col);
for (int j = 0; j < col; j++) {
mat.values[rand() % row][j] = rand() % 5 + 1;
mat.values[rand() % row][j] = rand() % 5;
}
return (mat);
}
Matrix matrix_read()
{
int row, col;
scanf("%d %d", &row, &col);
Matrix m = matrix_create(row, col);
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j)
scanf("%d", &(m.values[i][j]));
return m;
}
bool matrix_equal(const Matrix a, const Matrix b)
{
if (a.row != b.row || a.col != b.col)
return false;
for (int i = 0; i < a.row; ++i)
for (int j = 0; j < a.col; ++j)
if (a.values[i][j] != b.values[i][j])
return false;
return true;
}
void matrix_print(const Matrix m)
{
for (int i = 0; i < m.row; ++i) {
for (int j = 0; j < m.col; ++j) {
printf("%d ", m.values[i][j]);
}
puts("");
}
}
Matrix matrix_free(const Matrix m)
{
assert(m.values);
free(m.values[0]);
free(m.values);
return (Matrix){0};
}
void matrix_free_all(Matrix * const mats, int num_mat)
{
for (int i = 0; i < num_mat; ++i) {
mats[i] = matrix_free(mats[i]);
}
}
|
C
|
/*
Title : Find mid, Find_nth_from_list
Date : 15/12/19
Author : Sahana
Description : Input : Read input from user
Output : Display on screen
*/
#include "queue.h"
int main()
{
//Declaring variables
qlist *rear = NULL,*front = NULL;
data_t val;
int result,option;
while(1)
{
//Select options
printf("Enter the option:\n 1.Enqueue\n 2.Dequeue\n 3.Display\n 4.Exit\n Choice:: ");
scanf("%d", &option);
//Switch case
switch(option)
{
case 1:
//Read inpu from user
printf("Enter the data:\n");
scanf("%d", &val);
//Call function to enqueue the data
result = enqueue(&rear,&front,val);
(result == SUCCESS)? printf("Enqueue SUCCESS\n"): printf("Queue_Full\n");
break;
case 2:
//Call function to dequeue the data
result = dequeue(&front,&rear,val);
(result == Q_EMPTY)? printf("Queue_Empty\n"): printf("Dequeue SUCCESS\n");
break;
case 3:
//Call function to display data
display(front);
break;
case 4:
exit(1);
break;
}
}
return 0;
}
|
C
|
#include<stdio.h>
using namespace std;
// ãƳ Լ
int sort(int n, int Array_1[]) {
int i, j, temp;
int k, l, p;
int count = 0;
int result;
int* Array_2 = new int[n];
int* Array_3 = new int[n];
//Է°
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (Array_1[j] > Array_1[j + 1]) {
temp = Array_1[j];
Array_1[j] = Array_1[j + 1];
Array_1[j + 1] = temp;
}
}
}
count = n;
//ڱ⺸ ū ִ count
for (k = 0; k < n; k++) {
Array_2[k] = count;
count--;
}
//ǿ ´° ǥ
for (l = 0; l < n; l++) {
if (Array_1[l] <= Array_2[l]) {
Array_3[l] = 1;
}
}
//ش ū شϴ ã
for (p = 0; p < n; p++) {
if (Array_3[p] == 1) {
result = p;
}
}
//
printf("%d\n", Array_1[result]);
return 0;
}
//main()Լ
int main() {
int n;
scanf("%d", &n);
if (n < 1 || n > 1000) {
printf( " . α (1~1000)" );
return 0;
}
int* Array_1 = new int[n];
for (int i = 0; i < n; i++) {
scanf("%d", &Array_1[i]);
}
for (int i = 0; i < n; i++) {
if ((Array_1[i] > 10000) || (Array_1[i] < 0)) {
printf (" . α (0~10000)" );
return 0;
}
}
// ã Լ
sort(n, Array_1);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define N 3
int queue[3][N];
int front[3]={0,0,0};
int rear[3]={-1,-1,-1};
int item,pr;
void pqinsert(int);
void pqdelete();
void display();
int main()
{
int ch;
for(;;)
{
printf("\nPRIORITY QUEUE\n");
printf("*****************\n");
printf("\n\t1:PQ-INSERT\n");
printf("\n\t2:PQ-DELETE\n");
printf("\n\t3:PQ-DISPLAY\n");
printf("\n\t4:EXIT\n");
printf("\nENTER CHOICE:\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nENTER PRIORITY NUMBER\n");
scanf("%d",&pr);
if(pr>0 && pr<4)
pqinsert(pr-1);
else
printf("ONLY THREE PRIORITY EXITS 1 2 3\n");
break;
case 2:
pqdelete();
break;
case 3:
display();
break;
case 4:exit(0);
}
}
return 0;
}
void pqinsert(int pr)
{
if(rear[pr]==N-1)
printf("\nQUEUE OVERFLOW\n");
else
{
printf("\nENTER THE ITEM\n");
scanf("%d",&item);
rear[pr]++;
queue[pr][rear[pr]]=item;
}
}
void pqdelete()
{
int i;
for(i=0;i<3;i++)
{
if(rear[i]==front[i]-1)
printf("\nQUEUE EMPTY\n");
else
{
printf("DELETED ITEM IS %d OF QUEUE %d\n",queue[i][front[i]],i+1);
front[i]++;
}
}
}
void display()
{
int i,j;
for(i=0;i<3;i++)
{
if(rear[i]==front[i]-1)
printf("\nQUEUE EMPTY %d\n",i+1);
else
{
printf("\nQUEUE %d:",i+1);
for(j=front[i];j<=rear[i];j++)
printf("%d\t",queue[i][j]);
}
}
}
|
C
|
#include "listmaker.h"
task_t* createTask(unsigned int id, unsigned int arrival_time) {
task_t* new_task = (task_t*) malloc(sizeof(task_t));
if (new_task == NULL) {
perror("Error while creating a new task");
exit(EX_OSERR);
}
new_task->id = id;
new_task->arrival_time = arrival_time;
new_task->service_time = 0;
new_task->wait_time = 0;
new_task->core = -1; //non è di nessun core
new_task->pc = NULL;
new_task->instr_list = NULL;
new_task->last = NULL;
new_task->state = NEW;
new_task->next = new_task->prev = NULL;
return new_task;
}
void addTask_bottom(task_list_t * tasks, task_t * new_task) {
if(tasks->first == NULL) {
tasks->first = new_task;
new_task->prev = NULL;
}
else {
tasks->last->next = new_task;
new_task->prev = tasks->last;
}
new_task->next = NULL;
tasks->last = new_task;
return;
}
void addTask_sortedList(task_list_t * tasks, task_t * new_task) {
/*la funzione mantiene la lista ordinata per service time cercando il posto del task */
unsigned int serv_time = new_task->service_time;
task_t * p = tasks->first;
while (p != NULL && p->service_time <= serv_time) {
p = p->next;
}
if (p == NULL)
addTask_bottom(tasks, new_task);
else {
new_task->prev = p->prev;
if (p->prev != NULL)
p->prev->next = new_task;
else
tasks->first = new_task;
new_task->next = p;
p->prev = new_task;
}
return;
}
void addBlockedTask(task_list_t * tasks, task_t * new_task) {
//la lista ha nella prima metà i tasks del core0 ordinati per tempo di attesa crescente
//nella seconda metà sono ordinati in ordine decrescente quelli del core1
unsigned int wait_time = new_task->wait_time;
core_t core = new_task->core;
task_t * p;
if (core == -1) {
fprintf(stderr, "Internal error: core not set");
exit(EX_SOFTWARE);
}
if (core == CORE0) { //l'inserimento per il core0 avviene in testa
p = tasks->first;
while (p != NULL && p->core == core && p->wait_time <= wait_time)
p = p->next;
if (p == NULL)
addTask_bottom(tasks, new_task);
else {
new_task->prev = p->prev;
if (p->prev != NULL)
p->prev->next = new_task;
else
tasks->first = new_task;
new_task->next = p;
p->prev = new_task;
}
}
else { //l'inserimento per il core1 avviene in coda
p = tasks->last;
while (p != NULL && p->core == core && p->wait_time <= wait_time)
p = p->prev;
if (p == NULL) { //sono la testa oppure la lista è vuota
if (tasks->first == NULL)
tasks->last = new_task;
else
tasks->first->prev = new_task;
new_task->next = tasks->first;
tasks->first = new_task;
new_task->prev = NULL;
}
else {
new_task->next = p->next;
if (p->next != NULL)
p->next->prev = new_task;
else
tasks->last = new_task;
new_task->prev = p;
p->next = new_task;
}
}
}
task_t * removeTask(task_list_t * tasks, task_t * del) {
if (NULL == del) return NULL;
if (del == tasks->first)
tasks->first = del->next;
if (del == tasks->last)
tasks->last = del->prev;
if (NULL != del->next)
del->next->prev = del->prev;
if (NULL != del-> prev)
del->prev->next = del->next;
return del;
}
void moveTask(task_list_t task_lists[], state_t state_source, state_t state_dest, task_t * t) {
task_list_t * source = &task_lists[state_source];
task_list_t * dest = &task_lists[state_dest];
/* la cancellazione avviene in tutte le liste in modo uguale invocando removeTask
* l'inserimento avviene per:
* NEW,RUNNING,EXIT in coda
* READY in modo ordinato secondo la priorità del processo
* BLOCKED in modo ordinato secondo il tempo di attesa partendo dalla testa per core0 e dalla coda per core1
*/
//printf("%u from %d to %d\n", t->id, state_source, state_dest); //stampo id e numero delle liste from e to
if (state_dest == NEW || state_dest == RUNNING || state_dest == EXIT)
addTask_bottom(dest, removeTask(source, t));
else if (state_dest == READY)
addTask_sortedList(dest, removeTask(source, t));
else if (state_dest == BLOCKED)
addBlockedTask(dest, removeTask(source, t));
else {
fprintf(stderr, "Internal error: state not recognised");
freexit(task_lists, EX_SOFTWARE);
}
return;
}
instruction_t * createIstruction(unsigned int type_flag, unsigned int length) {
instruction_t* new_instr = (instruction_t*) malloc(sizeof(instruction_t));
if (new_instr == NULL) {
perror("Error while creating a new instruction");
exit(EX_OSERR);
}
new_instr->type_flag = type_flag;
new_instr->length = length;
new_instr->next = new_instr->prev = NULL;
return new_instr;
}
void addInstruction(task_t * task, instruction_t * new_instr) {
if(task->instr_list == NULL)
task->instr_list = task->pc = new_instr;
else {
task->last->next = new_instr;
new_instr->prev = task->last;
}
task->last = new_instr;
//incremento service_time
if (new_instr->type_flag == 0)
task->service_time += new_instr->length;
return;
}
bool read_input(task_list_t * tasks, char * filename) {
if (freopen(filename, "r", stdin) == NULL) { //Associa il file di input con stdin
perror("Looks like there's a problem with your input file");
exit(EX_OSFILE);
}
char c_read;
int n1, n2;
while (scanf("%c,%d,%d\n", &c_read, &n1, &n2) != EOF) { //Legge il file riga per riga
if (n1 < 0 || n2 < 0) {
fprintf(stderr, "Error: input file %s is incorrectly formatted (unexpected negative value).\n", filename);
exit(EX_DATAERR);
}
if (c_read == 't')
addTask_bottom(tasks, createTask(n1,n2));
else if (c_read == 'i') {
addInstruction(tasks->last, createIstruction(n1,n2));
}
else {
fprintf(stderr, "Error: input file %s is incorrectly formatted (unexpected character %c found).\n", filename, c_read);
exit(EX_DATAERR);
}
}
if (!feof(stdin)) { //errore nel raggiungere la fine del file
fprintf(stderr, "Error: end of file not reached");;
exit(EX_DATAERR);
}
fclose(stdin);
return true;
}
void freexit(task_list_t task_lists[], int EXIT_CODE) {
task_t * t, * t_tmp;
instruction_t * instr, * instr_tmp;
for (int i = 0; i < N_STATES; i++) {
t = task_lists[i].first;
while (t != NULL) {
instr = t->instr_list;
while ( instr != NULL) {
if (instr->next != NULL) {
instr_tmp = instr;
instr = instr->next;
free(instr_tmp);
}
else {
free(instr);
break;
}
}
if (t->next != NULL) {
t_tmp = t;
t = t->next;
free(t_tmp);
}
else {
free(t);
break;
}
}
}
printf("Exit with code: %d", EXIT_CODE);
exit(EXIT_CODE);
}
void freeOK(task_list_t task_lists[]) {
task_t * t, * t_tmp;
instruction_t * instr, * instr_tmp;
for (int i = 0; i < N_STATES; i++) {
t = task_lists[i].first;
while (t != NULL) {
instr = t->instr_list;
while (instr != NULL) {
if (instr->next != NULL) {
instr_tmp = instr;
instr = instr->next;
free(instr_tmp);
}
else {
free(instr);
break; //necessario! Perchè la free non mette a zero il contenuto
}
}
if (t->next != NULL) {
t_tmp = t;
t = t->next;
free(t_tmp);
}
else {
free(t);
break; //necessario! Perchè la free non mette a zero il contenuto
}
}
}
}
|
C
|
#include<stdio.h>
int main()
{
int i,n;
scanf("%d %d",&i,&n);
if((i*n)%2==0)
{
printf("even");
}
else
{
printf("odd");
}
}
|
C
|
// Wizard: Khojem
// orc3
// orc3.c
#include <std.h>
inherit ROOM;
int no_exit() { return 1;}
void init() {
::init();
if(this_player()->chk_my_mon()) {
add_action("no_exit","south");
add_action("no_exit","east");
add_action("no_exit","west");
}
}
void reset() {
::reset();
if (!present("half-orc guard" , this_object()) ) {
new("/wizards/khojem/new/mon/orc_guard")->move(this_object());
new("/wizards/khojem/new/mon/orc_guard")->move(this_object());
}
}
void create() {
::create();
set_property("light", 3);
set_property("indoors", 1);
set("short", "Central Meeting Chamber");
set("long", "Suddenly you emerge from the narrow passage to a "+
"large, well-lit chamber. The chamber is a large oval-shaped "+
"cavern with a huge pit in the center. This chamber "+
"serves as a central meeting area for the cave-dwelling "+
"Half-Orc clan."
);
add_exit("orc2","north");
add_exit("orc4","west");
add_exit("orc6","south");
add_exit("orc7","east");
add_exit("pit","pit");
set_pre_exit_functions(({"pit"}),({"go_pit"}));
set_items(([
({ "cave","cavern", "chamber", "meeting", "meeting room" }) :
"This large area affords you with plenty of space to "+
"maneuver for a fight. But you would still prefer to be "+
"outside in the open air.",
({ "walls", "floor" }) :
"The walls and floor are very hard, dry clay. Digging out "+
"would be an impossible task.",
({ "pit", "fire" }) :
"The pit contains a large fire fueled by hardwood logs "+
"from the surrounding forests. The fire rests in a depression "+
"a few feet below the surface of the chamber's floor. High "+
"above the cavern's chamber a hole allows the smoke to exit. "+
"The fire's logs burn in a hot, blue flame."
]));
set_smell("default", "A dank, musty smell fills the air. You can "+
"smell wood burning and food cooking.");
set_listen("default", "You can hear the pit fire burning with "+
"intensity.");
}
int go_pit(){
write("The hot, blue flame flickers across your skin singeing "+
"your eyebrows. You quickly jump out of the pit.\n");
this_player()->add_hp(-50);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int uint32_t ;
typedef int uint16_t ;
/* Variables and functions */
int /*<<< orphan*/ br_i15_decode (int*,unsigned char const*,size_t) ;
int /*<<< orphan*/ br_i15_muladd_small (int*,int,int const*) ;
int /*<<< orphan*/ br_i15_rshift (int*,int) ;
int /*<<< orphan*/ br_i15_zero (int*,int) ;
void
br_i15_decode_reduce(uint16_t *x,
const void *src, size_t len, const uint16_t *m)
{
uint32_t m_ebitlen, m_rbitlen;
size_t mblen, k;
const unsigned char *buf;
uint32_t acc;
int acc_len;
/*
* Get the encoded bit length.
*/
m_ebitlen = m[0];
/*
* Special case for an invalid (null) modulus.
*/
if (m_ebitlen == 0) {
x[0] = 0;
return;
}
/*
* Clear the destination.
*/
br_i15_zero(x, m_ebitlen);
/*
* First decode directly as many bytes as possible. This requires
* computing the actual bit length.
*/
m_rbitlen = m_ebitlen >> 4;
m_rbitlen = (m_ebitlen & 15) + (m_rbitlen << 4) - m_rbitlen;
mblen = (m_rbitlen + 7) >> 3;
k = mblen - 1;
if (k >= len) {
br_i15_decode(x, src, len);
x[0] = m_ebitlen;
return;
}
buf = src;
br_i15_decode(x, buf, k);
x[0] = m_ebitlen;
/*
* Input remaining bytes, using 15-bit words.
*/
acc = 0;
acc_len = 0;
while (k < len) {
uint32_t v;
v = buf[k ++];
acc = (acc << 8) | v;
acc_len += 8;
if (acc_len >= 15) {
br_i15_muladd_small(x, acc >> (acc_len - 15), m);
acc_len -= 15;
acc &= ~((uint32_t)-1 << acc_len);
}
}
/*
* We may have some bits accumulated. We then perform a shift to
* be able to inject these bits as a full 15-bit word.
*/
if (acc_len != 0) {
acc = (acc | (x[1] << acc_len)) & 0x7FFF;
br_i15_rshift(x, 15 - acc_len);
br_i15_muladd_small(x, acc, m);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "jlbmath.h"
int gcd_a, gcd_b;
float abs_a, sqrtv;
int main() {
printf("Enter first digit: ");
scanf("%d", &gcd_a);
printf("\nEnter second digit: ");
scanf("%d", &gcd_b);
printf("\nGCD is: %d\n", gcd(gcd_a, gcd_b));
printf("Enter number: ");
scanf("%f", &abs_a);
printf("\nAbsolute Value: %f", absl(abs_a));
printf("\nEnter number to sqrt: ");
scanf("%f", &sqrtv);
printf("\nSqrt of %f: %f\n", sqrtv, sqroot(sqrtv));
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 256
int compare(char p[], char t[])
{
int i;
for(i=0; i<MAX; i++)
{
if(p[i] != t[i])
{
return 0;
}
}
return 1;
}
void search(char p[], char t[])
{
int pl, tl, i;
char plc[MAX] ={0}, tlc[MAX]={0};
pl = strlen(p);
tl = strlen(t);
printf("%s\n", p);
printf("%s\n", t);
printf("%d, %d\n", pl, tl);
for(i=0; i<pl;i++)
{
plc[p[i]]++;
tlc[t[i]]++;
}
for(i=pl; i<tl ; i++)
{
if(compare(plc, tlc))
{
printf("%d\n", i-pl);
}
tlc[t[i]]++;
tlc[t[i-pl]]--;
}
if(compare(plc, tlc))
{
printf("%d\n", tl-pl);
}
}
void main()
{
char p[] = "ABC", t[]="AABBCABCBAAAACCBA";
search(p,t);
}
|
C
|
#include <stdio.h>
void exchange(int A[], int i, int j)
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
int partition(int A[], int left, int right)
{
int pivot = A[right];
int tail = left - 1;
for (int i = left; i < right; i++)
{
if (A[i] <= pivot)
{
tail++;
exchange(A, tail, i);
}
}
exchange(A, tail + 1, right);
return tail + 1;
}
void quicksort(int A[], int left, int right)
{
int pivot_index;
if (left < right)
{
pivot_index = partition(A, left, right);
quicksort(A, left, pivot_index-1);
quicksort(A, pivot_index+1, right);
}
}
int main()
{
int A[] = { 19 ,19 ,9 ,17 ,14 ,18 ,7 ,9 ,17 ,12 ,16 ,14 ,6 , 9, 3 ,8 ,5 ,17 ,13 ,16};
int n = sizeof(A) / sizeof(int);
quicksort(A, 0, n - 1);
printf(快速排序结果为:);
for (int i = 0; i < n; i++)
{
printf("%d ",A[i]);
}
printf("\n");
return 0;
}
|
C
|
编制程序,将N*N的矩阵转置。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 4
int main()
{
int a[N][N];
int i,j,temp;
//用随机数填充二维数组a
srand(time(0));
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
a[i][j] = rand()%100;
printf("%4d",a[i][j]);
}
printf("\n");
}
//矩阵转置
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
printf("\n转置后数组a:\n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf("%4d",a[i][j]);
printf("\n");
}
return 0;
}
|
C
|
// ----------------------------------------------------------------------------
//
// TIMERmain.c
//
// sets up periodic main loop timer and interrupt
// requires mainISR() to be the TIMER0A_Handler in Startup.s
//
// ----------------------------------------------------------------------------
// INCLUDE
// ----------------------------------------------------------------------------
#include "registers.h"
extern void DisableInterrupts(void);
extern void EnableInterrupts(void);
// PROTOTYPES
// ----------------------------------------------------------------------------
void setupTimerForMain(void);
void setupTimerInterrupt(void);
void clearTimerInterrupt(void);
// FUNCTIONS
// ----------------------------------------------------------------------------
// setup periodic main timer
void setupTimerForMain(void){
// enable clock
SYSCTL_RCGCTIMER |= 0x01;
while((SYSCTL_PRTIMER & 0x01) != 0x01);
// disable timer
TIMER0_CTL &=~ 0x01;
// select 16 bit timer mode
TIMER0_CFG &=~ 0x07;
TIMER0_CFG |= 0x04;
// set timer type to periodic
TIMER0_TAMR &=~ 0x03;
TIMER0_TAMR |= 0x02;
// set reload to 0.1 second
TIMER0_TAILR &=~ 0xFFFF;
TIMER0_TAPR &=~ 0xFF;
TIMER0_TAILR |= 0x186A;
TIMER0_TAPR |= 0xFF;
// enable timer
TIMER0_CTL |= 0x01;
}
// setup interrupts for periodic timer
void setupTimerInterrupt(void){
// disable all interrupts
DisableInterrupts();
// enable interrupt
TIMER0_IMR |= 0x01;
// enable TIMER interrupts
NVIC_EN0 |= 0x1 << 19;
// set priority = 0 (highest)
NVIC_PRI4 &=~ (unsigned)(0x7) << 29;
NVIC_PRI4 |= (unsigned)(0x0) << 29;
// set interrupt service routine
// done in startup.s
// clear any interrupts
clearTimerInterrupt();
// enable all interrupts
EnableInterrupts();
}
// clears interrupt
void clearTimerInterrupt(void){
TIMER0_ICR |= 0x01;
}
|
C
|
/*
Eric Brewer
9/10/09
CS252
Lab2_1 - 8-bit signed integer conversion
*/
#include <stdio.h>
#include <stdlib.h>
int main(){
int input = 0;
printf("Enter a signed decimal integer: ");
scanf("%i", &input);
//printf("\n");
if(input >= -128 && input <= 127){
if(input < 0)
input += 256;
int binArr[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
int i = 0;
int j = 0;
while(input){
binArr[i] = (input % 2);
input = input / 2;
i++;
}
printf("In 2's complement binary: ");
for(i = 7; i > -1; i--)
printf("%i", binArr[i]);
printf("\n");
}
else
printf("Your signed number won't fit into 8 bits.\n");
return 0;
}
|
C
|
//
// Created by Ivan's PC on 11/14/2019.
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * leer(){
char * cad = NULL;
int i = 0;
char c;
while ( (c=getchar())!='\n'){
if (i>0){
cad = (char*) realloc(cad, (i+2)* sizeof(char));
} else{
cad = (char*) malloc((i+2)* sizeof(char));
}
if (cad==NULL) return NULL;
cad[i++] = c;
}
if (cad){
cad[i] = '\0';
}
return cad;
}
char ** leerncad(int n){
char ** cad = NULL;
for (int j = 0; j < n; ++j) {
if (j>0){
cad = (char**) realloc(cad, (j+2)* sizeof(char*));
} else{
cad = (char**) malloc((j+2)* sizeof(char*));
}
if (cad==NULL) return NULL;
printf("Digite cadena %d ", j);
cad[j] = leer();
printf("\n");
}
return cad;
}
int main(){
int n; char ** arrcads;
char ** arrcadmod;
int cont;
printf("Cuantas cadenas leera?");
n = atoi(leer());
printf("\n");
arrcads = leerncad(n);
arrcadmod = (char **)malloc(n* sizeof(char*));
for (int i = 0; i < n; ++i) {
arrcadmod[i] = (char*) malloc(strlen(arrcads[i])* sizeof(char));
strcpy(arrcadmod[i], arrcads[i]);
}
for (int j = 0; j < n; ++j) {
cont = 0;
for (int i = 0; i < strlen(arrcadmod[j]); ++i) {
if (arrcadmod[j][i]!=' '){
arrcadmod[j][cont++] = arrcadmod[j][i];
}
}
arrcadmod[j][cont] = '\0';
arrcadmod[j] = (char *) realloc(arrcadmod[j], (strlen(arrcadmod[j])+1) * sizeof(char));
}
for (int k = 0; k < n; ++k) {
printf("Cadena %d leida: %s\n", k+1, arrcads[k]);
printf("Cadena %d modificada: %s\n", k+1, arrcadmod[k]);
}
}
int main2(){
char * texto = "56A<valor>5847</valor>4897<valor>87</valor>5445ggg";
char * ei = "<valor>";
char * ef = "</valor>";
int tam_ei = strlen(ei);
char * ptr_inicio;
char * ptr_fin;
char ** listado_cad = NULL;
int cant = 0;
int tmp;
ptr_inicio = texto;
while ( (ptr_inicio=strstr(ptr_inicio, ei))!= NULL){
ptr_inicio += tam_ei;
ptr_fin = strstr(ptr_inicio, ef);
if (ptr_fin==NULL){
break;
}
if (listado_cad==NULL){
listado_cad = (char **) malloc( 1 * sizeof(char*));
} else {
listado_cad = (char **) realloc(listado_cad, (cant+1) * sizeof(char*));
}
tmp = ptr_fin - ptr_inicio;
listado_cad[cant] = (char *) malloc( (tmp+1) * sizeof(char));
strncpy(listado_cad[cant], ptr_inicio, tmp);
listado_cad[cant][tmp] = '\0';
cant++;
}
for (int i = 0; i < cant; ++i) {
printf("%s\n", listado_cad[i]);
}
}
|
C
|
#ifndef EVENT_H
#define EVENT_H
#include <stdbool.h>
#include <stdint.h>
typedef enum {
E0 = 0u,
E1 = 1u,
E2 = 2u,
E3 = 3u,
END = 255u,
} Event;
#define QLEN (4) // the lenght of queue, must known in application design
typedef struct {
uint8_t curEvent; // the first event of queue
uint8_t q[QLEN];
} Queue;
extern Queue queue;
bool isEmpty(Queue* que);
void initQueue(Queue* que);
uint8_t pop(Queue* que);
void append(Queue* que, uint8_t ev);
#endif /* EVENT_H */
|
C
|
/*******************************************
* Game of Chance
*******************************************/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include "error_check.h"
#define DATAFILE "/var/chance.data" // Arquivo para armazenar os dados do usuário
// Struct padrão de usuário para armazenar informação sobre usuários
struct user
{
int uid;
int credits;
int highscore;
char name[100];
int (*current_game) ();
};
// Protótipos de função
int get_player_data();
void register_new_player();
void update_player_data();
void show_highscore();
void jackpot();
void input_name();
void print_cards(char *, char *, int);
int take_wager(int, int);
void play_the_game();
int pick_a_number();
int dealer_no_match();
int find_the_ace();
void fatal(char *);
// Variáveis glabais
struct user player; //Struct do jogador
int main ()
{
int choice, last_game;
srand(time(0)); //Inicia randonmizador com a hora
if (get_player_data() == -1) // Tenta ler os dados do jogador a partir do arquivo
register_new_player(); // Caso não haja dados, registra novo jogo
while (choice != 7)
{
printf("-=[ Game of Chance Menu ]=-\n");
printf("1 - Play the Pick a Number game\n");
printf("2 - Play the No Match Dealer game\n");
printf("3 - Play the Find the Ace game\n");
printf("4 - View current high score\n");
printf("5 - Change your user name\n");
printf("6 - Reset your account at 100 credits\n");
printf("7 - Quit\n");
printf("[Name: %s]\n", player.name);
printf("[You have %u credits] -> ", player.credits);
scanf("%d", &choice);
if ((choice < 1) || (choice > 7))
printf("\n[!!] The number %d is an invalid selection.\n\n", choice);
else if (choice < 4) // Se não, a escolha foi um jogo de algum outro tipo
{
if (choice != last_game) // Se a função ptr não foi definida
{
if (choice == 1) // então aponta para o jogo selecionado
player.current_game = pick_a_number;
else if (choice == 2)
player.current_game = dealer_no_match;
else
player.current_game = find_the_ace;
last_game = choice; // e define last_game
}
play_the_game(); // Jogar
}
else if (choice == 4)
show_highscore;
else if (choice == 5)
{
printf("\nChange user name\n");
printf("Enter your new name: ");
input_name();
printf("Your name has been changed.\n\n");
}
else if (choice == 6)
{
player.credits = 100;
printf("\nYour account has been reset with 100 credits.\n\n");
}
}
update_player_data();
printf("\nThanks for playing! Bye.\n");
return 0;
}
// Esta Função lê os dados do jogador para o uid corrente
// do arquivo. Ela retorna -1 se não encontrar os dados do jogador
// para o uid atual.
int get_player_data()
{
int fd, uid, read_bytes;
struct user entry;
uid = getuid();
fd = open(DATAFILE, O_RDONLY);
if (fd == -1) // Não consegue abrir o arquivo, talvez ele não exista
return -1;
read_bytes = read(fd, &entry, sizeof(struct user)); // Lê o primeiro bloco
while (entry.uid != uid && read_bytes > 0) // Loop até encontrar o uid.
read_bytes = read(fd, &entry, sizeof(struct user)); // Continua lendo
close (fd); // Fecha o arquivo
if (read_bytes < sizeof(struct user)) // Se chegou ao fim do arquivo
return -1;
else player = entry; // Copia a entrada lida para a struct do jogador
return 1; // Retorno bem sucedido
}
// Esta é a função para o registro de um novo usuário
// Isso criará uma nova conta de jogador e o cadastra no arquivo
void register_new_player()
{
int fd;
printf("-=-={ New Player Registration }=-=-\n");
printf("Enter your name: ");
input_name();
player.uid = getuid();
player.highscore = player.credits = 100;
fd = open(DATAFILE, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
if (fd == -1)
fatal("in register_new_player() while opening file");
write(fd, &player, sizeof(struct user));
close(fd);
printf("\nWelcome to the Game of Chance, %s.\n", player.name);
printf("You have been given %u credits\n", player.credits);
}
// Esta função grava os dados do jogador corrente no arquivo.
// A principio, ela é usada para atualizar os créditos após o jogo.
void update_player_data()
{
int fd, i, read_uid;
char burned_byte;
fd = open(DATAFILE, O_RDWR);
if (fd == -1) // Se a abertura falhar aqui, algo errado ocorreu
fatal("in update_player_data() while opening file");
read(fd, &read_uid, 4); // Lê o uid da primeira struct
while (read_uid != player.uid) // Loop ate que o uid correto seja encontrado.
{
for (i = 0; i < sizeof(struct user) - 4; ++i) // Ler todo o resto da struct
read(fd, &burned_byte, 1);
read(fd, &read_uid, 4); // Lê a struct do proximo uid
}
write(fd, &(player.credits), 4); // Atualiza creditos.
write(fd, &(player.highscore), 4); // Atualiza o maior score.
write(fd, &(player.name), 100); // Atualiza o nome.
close(fd);
}
// Esta função exibe o score atual mais alto e
// o nome da pessoa que alcançou essa pontuação.
void show_highscore()
{
unsigned int top_score = 0;
char top_name[100];
struct user entry;
int fd;
printf("\n===============| HIGH SCORE |===============\n");
fd = open(DATAFILE, O_RDONLY);
if (fd == -1)
fatal("in show_highscore() while opening file");
while (read(fd, &entry, sizeof(struct user)) > 0) // Loop até o fim do arquivo
{
if (entry.highscore > top_score) // Se há um score mais alto,
{
top_score = entry.highscore; // atribui este score para top_score
strcpy(top_name, entry.name); // e o nome ao top_name
}
}
close(fd);
if (top_score > player.highscore)
printf("%s has the high score of %u\n", top_name, top_score);
else
printf("You currently have the high score of %u credits!\n", player.highscore);
printf("============================================\n\n");
}
// Esta função atribui o grande premio para o jogo Pick a Number
void jackpot()
{
printf("*+*+*+*+*+ JACKPOT +*+*+*+*+*\n");
printf("You have won the jackpot of 100 credits!\n");
player.credits += 100;
}
// Esta função é usada para entrar com o nome do jogador, uma vez que
// scanf("%s", &whatever) sera interrompido assim que for informado uma barra de espaço
void input_name()
{
char *name_ptr, input_char='\n';
while (input_char == '\n') // Enquanto não for digitado nada
scanf("%c", &input_char); // caracteres da nova linha
name_ptr = (char *) &(player.name); // name_ptr = endereço do nome do jogador
while (input_char != '\n') // Loop até a nova linha
{
*name_ptr = input_char; // Coloca os caracteres de entrada no nome
scanf("%c", &input_char); // Incrementa o ponteiro do nome
name_ptr++; // Incrementa o ponteiro do nome
}
*name_ptr = 0; // Conclui a string
}
// Esta função imprime as 3 cartas para o jogo Find the Ace
// Ela recebe uma mensagem para exibir um ponteiro para apontar, um array de cartas
// e carta que o usuario pegou. Se user_pick for -1,
// então os numeros selecionados serrão exibidos
void print_cards(char *message, char *cards, int user_pick)
{
int i;
printf("\n\t*** %s ***\n", message);
printf(" \t._.\t._.\t._.\n");
printf("Cards:\t|%c|\t|%c|\t|%c|\n\t", cards[0], cards[1], cards[2]);
if (user_pick == -1)
printf(" 1 \t 2 \t 3\n");
else
{
for (i = 0; i < user_pick; ++i)
printf("\t");
printf(" ^-- your pick\n");
}
}
// Esta função entra com apostasy para os jogos No Match Dealer e
// Find the Ace. Ela recebe os créditos disponiveis e a aposta
// anterior como argumento. O previous_wager é importante somente
// para a segunda aposta no jogo Find the Ace. A função
// retorna -1 se a aposta é muito alta ou muito baixa, e retorna
// a soma da aposta.
int take_wager(int available_credits, int previous_wager)
{
int wager, total_wager;
printf("How many of your %d credits would you like to wager? ", available_credits);
scanf("%d", &wager);
if (wager < 1) // Certifica de que a aposta é maior que 0
{
printf("Nice try, but you must wager a positive number!\n");
return -1;
}
total_wager = previous_wager + wager;
if (total_wager > available_credits) // Confirma os creditos disponiveis
{
printf("Your total wager of %d is more than you have!\n", total_wager);
printf("You only have %d available credits, try again.\n", available_credits);
return -1;
}
return wager;
}
// Esta função contem um loop que permite que o jogo atual seja
// jogado novamente. Ela tambem grava o total dos novos creditos no arquivo
// após cada rodada.
void play_the_game()
{
int play_again = 1;
int (*game) ();
char selection;
while (play_again)
{
printf("\n[DEBUG] current_game pointer @ 0x%08x\n", player.current_game);
if (player.current_game() != -1) // Se o jogo segue sem erros e
{
if (player.credits > player.highscore) // um novo record é definido,
player.highscore = player.credits; // atualiza o score ao arquivo
printf("\nYou now have %u credits\n", player.credits);
update_player_data(); // Grava o total do novo score ao arquivo
printf("Would you like to play again? [y/n] ");
selection = '\n';
while (selection == '\n') // Aguarda algum comando ser digitado
scanf("%c", &selection);
if (selection == 'n')
play_again = 0;
}
else play_again = 0; // Se o jogo retornou algum erro, retorna ao menu principal.
}
}
// Esta função é o jogo Pick a Number.
// Ela retorna -1 se o jogador não possui créditos suficientes.
int pick_a_number()
{
int pick, winning_number;
printf("\n###### Pick a Number ######\n");
printf("This game costs 10 credits to play. Simply pick a number\n");
printf("between 1 and 20, and if you pick the winning number, you\n");
printf("will win the jackpot of 100 credits!\n\n");
winning_number = (rand() % 20) + 1; // Escolhe um numero entre 1 e 20
if (player.credits < 10)
{
printf("You only have %d credits. That's not enough to play!\n\n", player.credits);
return -1; // Sem creditos suficientes para jogar
}
player.credits -= 10; // Reduz 10 creditos
printf("10 credits have been deducted from your account.\n");
printf("Pick a number between 1 and 20: \n");
scanf("%d", &pick);
printf("The winning number is %d\n", winning_number);
if (pick == winning_number)
jackpot();
else printf("Sorry, you didn't win.\n");
return 0;
}
// Este é o jogo No Match Dealer
// Ele retorna -1 se o jogador não possuir creditos.
int dealer_no_match()
{
int i, j, numbers[16], wager = -1, match = -1;
printf("\n::::::: No Match Dealer :::::::\n");
printf("In this game, you can wager up to all of your credits.\n");
printf("The dealer will deal out 16 random numbers between 0 and 99.\n");
printf("If there are no matches among them, you double your money!\n\n");
if (player.credits == 0)
{
printf("You don't have any credits to wager!\n\n");
return -1;
}
while (wager == -1)
wager = take_wager(player.credits, 0);
printf("\t\t::: Dealing out 16 random numbers :::\n");
for (i = 0; i < 16; ++i)
{
numbers[i] = rand() % 100; // Escolhe um numero entre 0 e 99
printf("%2d\t", numbers[i]);
if (i%8 == 7) // Imprime uma quebra de linha a cada 8 numeros.
printf("\n");
}
for (i = 0; i < 15; ++i) // Loop que procura por numeros compativeis
{
j = i + 1;
while (j < 16)
{
if (numbers[i] == numbers[j])
match = numbers[i];
j++;
}
}
if (match != -1)
{
printf("The dealer matched the number %d!\n", match);
printf("You lose %d credits.\n", wager);
player.credits -= wager;
}
else
{
printf("There were no matches! you win %d credits!\n", wager);
player.credits += wager;
}
return 0;
}
// Este é o jogo Find the Ace.
// A função retorna -1 se o jogador não possuir creditos.
int find_the_ace()
{
int i, ace, total_wager;
int invalid_choice, pick = -1, wager_one = -1, wager_two = -1;
char choice_two, cards[3] = {'X', 'X', 'X'};
ace = rand() % 3; // Place the Ace randomly
printf("******* Find the Ace *******\n");
printf("In this game, you can wager up to all of your credits.\n");
printf("Three cards will be dealt out, two queens and one ace.\n");
printf("If you find the ace, you will win you wager.\n");
printf("After choosing a card, one of the queens will be revealed.\n");
printf("At this point, you may either select a different card or\n");
printf("incrase your wager\n");
if (player.credits == 0)
{
printf("You don't have any credits to wager!\n\n");
return -1;
}
while (wager_one == -1) // Loop até que uma carta válida seja feita.
wager_one = take_wager(player.credits, 0);
print_cards("Dealing cards", cards, -1);
pick = -1;
while ((pick < 1) || (pick > 3)) // Loop até que uma carta valida seja retirada.
{
printf("Select a card: 1,2 or 3 ");
scanf("%d", &pick);
}
pick --; // Ajusta a retirada a partir de uma carta começada por 0
i = 0;
while (i == ace || i == pick) // Manter loop até encontrar rainha valida para mostrar
i++;
cards[i] = 'Q';
print_cards("Revealing a queen", cards, pick);
invalid_choice = 1;
while (invalid_choice) // Loop até que uma escolha certa seja feita.
{
printf("Would you like to:\n[c]hange your pick\tor\t[i]ncrease your wager?\n");
printf("Select c or i: ");
choice_two = '\n';
while (choice_two == '\n') // Limpa linhas extras.
scanf("%c", &choice_two);
if (choice_two == 'i') // Aumenta a aposta
{
invalid_choice = 0; // Esta é uma escolha valida
while (wager_two == -1) // Loop até que a 2ª aposta valida seja feita.
wager_two = take_wager(player.credits, wager_one);
}
if (choice_two == 'c') // Troca a retirada
{
i = invalid_choice = 0; // Escolha valida
while (i == pick || cards[i] == 'Q') // Loop até que outra carta
i++; // seja encontrada,
pick = i; // e então troca a retirada.
printf("Your card pick has been changed to card %d\n", pick + 1);
}
}
for (i = 0; i < 3; ++i) // Revela todas as cartas.
{
if (ace == i)
cards[i] = 'A';
else
cards[i] = 'Q';
}
print_cards("End result", cards, pick);
if (pick == ace) // Identifica uma vitoria
{
printf("You have won %d credits from yout first wager\n", wager_one);
player.credits += wager_one;
if (wager_two != -1)
{
printf("and an additional %d credits from your second wager!\n", wager_two);
player.credits += wager_two;
}
}
else // Handle loss
{
printf("You have lost %d credits from yout first wager\n", wager_one);
player.credits -= wager_one;
if (wager_two != -1)
{
printf("and an additional %d credits from your seccond wager!\n", wager_two);
player.credits -= wager_two;
}
}
return 0;
}
|
C
|
/*
*
* Compiler for the Bare Bones programming language written in C
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct var
{
char key[10];
int value;
};
int main(int argc, char *argv[])
{
FILE *fptr;
struct var bones[200];
struct var *listptr = &bones[0]; // pointer for the variable list
int listlength = 0; // length of variable list
/*
// search testing
struct var b1, b2, b3;
strcpy(b1.key, "apple");
b1.value = 4;
strcpy(b2.key, "orange");
b2.value = 5;
strcpy(b3.key, "banana");
b3.value = 6;
bones[0] = b1;
bones[1] = b2;
bones[2] = b3;
listlength = 3;
//int index = search("orange", listlength, bones);
//printf("search for orange in bones: %d\n", index);
clear("banana", &listlength, bones);
clear("taco", &listlength, bones);
incr("banana", listlength, bones);
decr("orange", listlength, bones);
//printf("List length: %d\n banana value = %d", listlength, bones[search("banana", listlength, bones)].value);
//printf("List length: %d\n orange value = %d", listlength, bones[search("orange", &listlength, bones)].value);
*/
// print the name of the file
printf("Bare Bones file: %s\n", argv[1]);
// attempt to read file argument
if ((fptr = fopen(argv[1], "r")) == NULL)
{
printf("Error! opening file\n");
// Program exits if the file pointer returns NULL.
exit(1);
}
char line[ 256 ];
while(fgets(line, sizeof line, fptr) != NULL)
{
char command[10];
char variable[10];
char * lineptr = strtok(line, " ");
strcpy(command, lineptr);
lineptr = strtok(NULL, " ");
strcpy(variable, lineptr);
printf("%s %s\n", command, variable);
// Execute the desired command
execute(command, variable, &listlength, bones);
}
printf("We read it!\n");
fclose(fptr); // Close file when program is finished
exit(0);
}
int execute(char command[], char variable[], int *listlength, struct var bones[])
{
//printf("%d %d %d", listlength);
if(strcmp(command, "incr") == 0)
{
incr(variable, listlength, bones);
}
else if(strcmp(command, "decr") == 0)
{
decr(variable, listlength, bones);
}
else if(strcmp(command, "clear") == 0)
{
clear(variable, listlength, bones);
}
else if(strcmp(command, "print") == 0)
{
int index = search(variable, listlength, bones);
printf("%s: %d\n", variable, bones[index].value);
}
else
{
printf("Error, command %s does not exist", command);
return -1;
}
return 0;
}
int decr(char key[], int listlength, struct var bones[])
{
int index;
if((index = search(key, listlength, bones)) == -1)
{
printf("Unknown Variable Error: Var %s not declared!", key);
return -1;
}
if(bones[index].value == 0)
{
return 0;
}
return --bones[index].value;
}
int incr(char key[], int listlength, struct var bones[])
{
int index;
if((index = search(key, listlength, bones)) == -1)
{
printf("Unknown Variable Error: var %s not declared!", key);
return -1;
}
return ++bones[index].value;
}
int clear(char key[], int *listlength, struct var bones[])
{
struct var bone;
strcpy(bone.key, key);
bone.value = 0;
int index;
if((index = search(key, *listlength, bones)) == -1)
{
bones[*listlength] = bone;
*listlength = *listlength + 1;
return 0;
}
bones[index] = bone;
return -1;
}
// search finds var in map and returns ptr to var
// if var does not exist, returns NULL
int search(char key[], int listlength, struct var bones[])
{
int loc = 0;
//printf("%d", *listlength);
while(loc < listlength)
{
if(strcmp(bones[loc].key, key) == 0)
{
//printf("found it!");
return loc;
}
loc++;
}
return -1;
}
|
C
|
#include "xsal.h"
#include "xsal_i_assert.h"
#include <errno.h>
#include <string.h>
bool SAL_Create_Mutex(
SAL_Mutex_T* mutex,
const SAL_Mutex_Attr_T* attr)
{
SAL_Int_T status;
SAL_PRE(mutex != NULL);
if (attr == NULL)
{
/** Create mutex with default (system dependent) settings
*/
status = pthread_mutex_init(mutex, NULL);
}
else
{
pthread_mutexattr_t ptmutex_attr;
status = pthread_mutexattr_init(&ptmutex_attr);
if (status == EOK)
{
if (attr->recursive)
{
status = pthread_mutexattr_settype(
&ptmutex_attr,
PTHREAD_MUTEX_RECURSIVE_NP);
}
if (status == EOK)
{
status = pthread_mutex_init(mutex, &ptmutex_attr);
}
(void)pthread_mutexattr_destroy(&ptmutex_attr);
}
}
SAL_POST(status == EOK);
return (bool)(status == EOK);
}
|
C
|
/*
Parallelise PI program using loop construct
*/
#include<stdio.h>
#include<omp.h>
static long num_steps=100000;
double step;
int main()
{
int i;
double pi;
double sum=0.0;
step = 1.0/(double) num_steps;
#pragma omp parallel
{
double x;
#pragma omp for reduction(+:sum)
for(i=0;i<num_steps;i++)
{
x = (i + 0.5) * step;
sum += 4.0/(1.0+x*x);
}
}
pi = sum*step;
printf("The value of pi is: %f\n",pi);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "QueryUtil.h"
#include "SegUtil.h"
/**
* ORs the next 2 segments (2 fills) and stores result
*/
void fillORfill(activeWord *smallFill, activeWord *bigFill, activeWord *result){
word_32 runSize = getNumRuns(smallFill->seg[smallFill->currSeg],smallFill->length);
bigFill->seg[bigFill->currSeg] -= runSize;
if(getFillType(smallFill->seg[smallFill->currSeg],smallFill->length)==1 || getFillType(bigFill->seg[bigFill->currSeg],bigFill->length)==1){
runSize |= 1<<(smallFill->length-1);
}
if(getNumRuns(bigFill->seg[bigFill->currSeg],bigFill->length)==0) bigFill->currSeg++;
result->flag[0]=1;
result->seg[0]=runSize;
smallFill->currSeg++;
}
/**
* ORs the next 2 segments (2 lits) and stores result
*/
void litORlit(activeWord *lit1, activeWord *lit2, activeWord *result){
result->seg[0] = lit1->seg[lit1->currSeg] | lit2->seg[lit2->currSeg];
lit1->currSeg++;
lit2->currSeg++;
if(result->seg[0]==0){//all 0s - turn into one run of 0s (for consistency)
result->flag[0]=1;
result->seg[0]++;
}
else if(result->seg[0]==getOneLit(result->length+1)){//all 1s - turn into one run of 1s (for consistency)
result->flag[0]=1;
result->seg[0]=getOneFill(result->length+1)-1;
}
else{
result->flag[0]=0;
}
}
/**
* ORs the next 2 segments (1 fill, 1 lit) and stores result
*/
void fillORlit(activeWord *fill, activeWord *lit, activeWord *result){
if(getFillType(fill->seg[fill->currSeg],fill->length)==1){//run of 1s so result is all 1s
result->flag[0]=1;
result->seg[0]=(1<<(fill->length-1)) + 1;
}
else{//run of 0s so result is lit
result->flag[0]=0;
result->seg[0]=lit->seg[lit->currSeg];
if(result->seg[0]==0){//all 0s - turn into one run of 0s (for consistency)
result->flag[0]=1;
result->seg[0]++;
}
else if(result->seg[0]==getOneLit(result->length+1)){//all 1s - turn into one run of 1s (for consistency)
result->flag[0]=1;
result->seg[0]=getOneFill(result->length+1)-1;
}
}
lit->currSeg++;
fill->seg[fill->currSeg]--;
if(getNumRuns(fill->seg[fill->currSeg],fill->length)==0) fill->currSeg++;
}
/**
* ANDs the next 2 segments (2 fills) and stores result
*/
void fillANDfill(activeWord *smallFill, activeWord *bigFill, activeWord *result){
word_32 runSize = getNumRuns(smallFill->seg[smallFill->currSeg],smallFill->length);
bigFill->seg[bigFill->currSeg] -= runSize;
if(getFillType(smallFill->seg[smallFill->currSeg],smallFill->length)==1 && getFillType(bigFill->seg[bigFill->currSeg],bigFill->length)==1){//both runs of 1s
runSize |= 1<<(smallFill->length-1);
}
if(getNumRuns(bigFill->seg[bigFill->currSeg],bigFill->length)==0) bigFill->currSeg++;
result->flag[0]=1;
result->seg[0]=runSize;
smallFill->currSeg++;
}
/**
* ANDs the next 2 segments (2 lits) and stores results
*/
void litANDlit(activeWord *lit1, activeWord *lit2, activeWord *result){
result->seg[0] = lit1->seg[lit1->currSeg] & lit2->seg[lit2->currSeg];
lit1->currSeg++;
lit2->currSeg++;
if(result->seg[0]==0){//all 0s - turn into one run of 0s (for consistency)
result->flag[0]=1;
result->seg[0]++;
}
else if(result->seg[0]==getOneLit(result->length+1)){//all 1s - turn into one run of 1s (for consistency)
result->flag[0]=1;
result->seg[0]=getOneFill(result->length+1)-1;
}
else{
result->flag[0]=0;
}
}
/**
* ANDs the next 2 segments (1 fill, 1 lit) and stores result
*/
void fillANDlit(activeWord *fill, activeWord *lit, activeWord *result){
if((fill->seg[fill->currSeg])>>(fill->length-1)==1){//run of 1s so result is lit
result->flag[0]=0;
result->seg[0]=lit->seg[lit->currSeg];
if(result->seg[0]==0){//all 0s - turn into one run of 0s (for consistency)
result->flag[0]=1;
result->seg[0]++;
}
else if(result->seg[0]==getOneLit(result->length+1)){//all 1s - turn into one run of 1s (for consistency)
result->flag[0]=1;
result->seg[0]=getOneFill(result->length+1)-1;
}
}
else{//run of 0s so result is 0
result->flag[0]=1;
result->seg[0]=1;
}
lit->currSeg++;
fill->seg[fill->currSeg]--;
if(getNumRuns(fill->seg[fill->currSeg],fill->length)==0) fill->currSeg++;
}
/**
* Appends toAdd to the end of the result (to previous if possible; if previous is exhausted, saves previous into result[index])
*/
void append(word_32 *result, int *index, activeWord *previous, activeWord *toAdd){
//special case if there is nothing in previous (first segment of query)
if(previous->currSeg==-1){
previous->currSeg=0;
previous->flag[0]=toAdd->flag[0];
previous->seg[0]=toAdd->seg[0];
if(PRINT) printf("First append\n");
return;
}
word_32 typePrev = getFillType(previous->seg[previous->currSeg],previous->length);
word_32 typeNext = getFillType(toAdd->seg[0],toAdd->length);
if(previous->flag[previous->currSeg]==1 && toAdd->flag[0]==1 && typePrev==typeNext){//can consolidate
word_32 sizePrev = getNumRuns(previous->seg[previous->currSeg],previous->length);
word_32 sizeNext = getNumRuns(toAdd->seg[0],toAdd->length);
word_32 max = getOneLit(toAdd->length+1);//max runs is same as literal of ones
if(sizePrev+sizeNext>max){//exceeds limit, update previous to max and transfer next to previous (subtracted)
previous->seg[previous->currSeg] += (max-sizePrev);//transfer all we can not exceeding limit
toAdd->seg[0] -= (max-sizePrev);//subtract what we transfered from the next one
}
else{//can add it without exhausting the previous
previous->seg[previous->currSeg] += sizeNext;
return;
}
}
//cannot consolidate (either one of them is a literal or both are runs but of different types)
//special case: could consolidate but when we added number of runs, exceed the limit so need to move on
if(previous->flag[previous->currSeg]==1 && getNumRuns(previous->seg[previous->currSeg],previous->length)==1){//if the previous is only a run of 1
previous->flag[previous->currSeg]=0;//change it to a literal
if(typePrev==1){//need to save as literal of 1s
previous->seg[previous->currSeg]=getOneLit(previous->length+1);
}
else{//save a literal of 0s (just 0)
previous->seg[previous->currSeg]=0;
}
}
previous->currSeg++;//moving on to next segment
if(previous->currSeg>=previous->numSegs){//need to write first before adding
word_32 toWrite = createWord(previous);
result[(*index)++] = toWrite;
previous->currSeg=0;
}
//we've made sure previous is adequate (not run of 1s and made sure we wrote it if we exhausted it)
//so now we can save the next word as the previous segment
previous->flag[previous->currSeg] = toAdd->flag[0];
previous->seg[previous->currSeg] = toAdd->seg[0];
}
|
C
|
#include <stdio.h>
#include <time.h>
#include "myBmpGris.c"
/**
CoeffLeg : Cette fonction calcule les coefficients des polynomes de Legendre
jusqu' l'ordre n et renvoie une structure comprennant la matrice et ses dimensions
@param n : ordre du polynome de Legendre
*/
MATRIX CoeffLeg(int n)
{
int inc1,inc2;
MATRIX coeff_A;
double** tab = malloc(n*sizeof(double*));
for(inc1=0;inc1<n;inc1++)
tab[inc1] = calloc(n,sizeof(double));
tab[0][0] = 1;
tab[1][1] = 1;
for(inc1=2;inc1<n;inc1++)
{
for(inc2=0;inc2<=inc1;inc2++)
{
if (!inc2)
tab[inc1][inc2] = -((inc1-1)*tab[inc1-2][0])/inc1;
else
if (inc2 == inc1)
tab[inc1][inc2] = ((2*inc1-1)*tab[inc1-1][inc1-1])/inc1;
else
tab[inc1][inc2] = ((2*inc1-1)*tab[inc1-1][inc2-1])/inc1 -((inc1-1)*tab[inc1-2][inc2])/inc1;
}
}
coeff_A.matrice = tab;
coeff_A.dimLigne = inc1;
coeff_A.dimColonne = inc1;
return coeff_A;
}
/**
lambda : Cette fonction calcule les moments de Legendre
@param eta : structure comprennant la matrice de moments centrs et norms
*/
MATRIX lambda(MATRIX* eta)
{
int incp,incq,inci,inj;
double** a = CoeffLeg(N);
MATRIX matLambda;
matLambda.matrice=createMatrix(eta->dimLigne,eta->dimColonne);
for(incp = 0; incp < N ; incp++)
for(incq = 0; incq < N - incp; incq++)
{
for (inci = 0; inci <= p; inci++)
for (incj = 0; incj <= q; incj++)
res += a[incp][inci] * a[incq][incj] * eta.matrice[i][j];
res *= ((2*incp + 1)*(2*incq + 1))/4;
matLambda.matrice[incp][incq] = res;
}
freeMatrice(a,N);
return matLambda;
}
/**
freeMatrice : Cette fonction libre les matrices
@param mat : matrice carre librer
@param N : dimension de la matrice
*/
void freeMatrice( double** mat, int N) {
if( mat != NULL ){
int i;
for( i = 0; i < N; i++ )
free( mat[i] );
free( mat );
}
mat = NULL;
}
|
C
|
/************************The MSB bit of a number defines their sign. If the MSB bit is set, the number will be negative.******/
#include <stdio.h>
int main()
{
int sign = 0;
int data = 0;
int val;
printf("Enter a number:");
scanf("%d",&data);
sign = (data > 0) - (data < 0);
val = (data > 0);
printf("val = %d\n",val);
val = (data < 0);
printf("val = %d\n",val);
if(sign == 1){
printf("Entered number is +ve\n");
}
else if(sign == -1){
printf("Entered number is -ve\n");
}
else{
printf("Enterd numbet is 0\n");
}
return 0;
}
|
C
|
/* 先以只读模式"r"打开名为"abc"的文件,然后将它关闭。
* 当文件打开失败,fopen函数返回NULL时,会显示“无法打开文件"abc"。否则则证明文件可以正常打开,所以显示“成功打开文件"abc",并关闭文件。
*/
/* 代码清单13-1中的程序只能打开名为"abc"的文件。请将程序改为从键盘读入文件名,如果存在该名称的文件,就显示“该文件存在。”,否则就显示“该文件不存在。”。
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
/* argc -> 参数的个数 >= 1 */
/* argv[0] -> 这条命令的名字 */
if (argc != 2) {
printf("Usage: %s <filename> !\n", argv[0]);
return -2;
}
FILE* fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("该文件不存在。\n");
return -1;
}
printf("该文件存在。\n");
fclose(fp);
return 0;
}
|
C
|
#include <inttypes.h>
#include <stdlib.h>
uint64_t read();
void write(uint64_t val);
void matmul(uint32_t dim, uint64_t* c, uint64_t* a, uint64_t *b) {
uint32_t i, j, k;
// C = AB
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
uint64_t sum = 0;
for (k = 0; k < dim; k++)
sum += a[i * dim + k] * b[k * dim + j];
c[i * dim + j] = sum;
}
}
}
void read_mat(uint32_t dim, uint64_t* mat) {
uint32_t i, j;
for (i = 0; i < dim; i++)
for (j = 0; j < dim; j++)
mat[i * dim + j] = read();
}
void print_mat(uint32_t dim, uint64_t* mat) {
uint32_t i, j;
for (i = 0; i < dim; i++)
for (j = 0; j < dim; j++)
write(mat[i * dim + j]);
}
int main() {
uint32_t dim;
dim = read();
uint64_t* a = (uint64_t*)malloc(dim * dim * sizeof(uint64_t*));
uint64_t* b = (uint64_t*)malloc(dim * dim * sizeof(uint64_t*));
uint64_t* c = (uint64_t*)malloc(dim * dim * sizeof(uint64_t*));
read_mat(dim, a);
read_mat(dim, b);
matmul(dim, c, a, b);
print_mat(dim, c);
return 0;
}
|
C
|
#include<stdio.h>
#define MAX 1005
int main()
{
int n,a[MAX][3];
int i,j;
int at=0,bt=0,ar=0,br=0;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
for(i=0;i<n;i++)
{
if(a[i][0]==1)
{
at+=10;
ar+=a[i][1];
}
else
{
bt+=10;
br+=a[i][1];
}
}
if(ar>=(at/2))
printf("LIVE\n");
else
printf("DEAD\n");
if(br>=(bt/2))
printf("LIVE");
else
printf("DEAD");
return 0;
}
|
C
|
//
// Created by harsha on 2019-05-27.
//
#include "state.h"
cell *** create_singleton_state() {
cell *** state = create_cell_grid();
return state;
}
void write_to_singleton_state(cell *** oldstate, cell *** newstate) {
int i, j;
for (i = 0; i < ROWS; i++) {
for(j = 0; j < COLUMNS; j++){
if(newstate[i][j]->expression != NULL) {
oldstate[i][j]->expression = create_string(strlen(newstate[i][j]->expression));
strcpy(oldstate[i][j]->expression, newstate[i][j]->expression);
} else {
strcpy(oldstate[i][j]->val, newstate[i][j]->val);
}
}
}
}
|
C
|
#include<stdio.h>
int main()
{
int num,num_cp,num_sq,lastdigit;
printf("enter the no \n");
scanf("/d",&num);
num_cp=num;
num_sq=num*num;
while(num_sq>0)
{
lastdigit=num_sq%10;
if(lastdigit==num_cp)
printf("Automorphic no. %d",num);
else
printf("Not an Automorphic no. %d",num);
}
return 0;
}
|
C
|
//------------------------------------------------------------------------
// NAME: Mihail Kirov
// CLASS: XIb
// NUMBER: 19
// PROBLEM: #2
// FILE NAME: png-info.c
// FILE PURPOSE:
// get the width and height of PNG image
//------------------------------------------------------------------------
#include <stdint.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
//------------------------------------------------------------------------
// FUNCTION: read_image
// opens the path pointed to by filepath, reads the file and saves it to an array. Returns a pointer to that array
// PARAMETERS:
// const char* filepath -> path to the file we want to open
//------------------------------------------------------------------------
void* read_image(const char*);
//------------------------------------------------------------------------
// FUNCTION: main
// opens a png file given as parameter, reads it and returns the width and height of the file;
// PARAMETERS:
// argc -> argument count, argv -> list of parmeter strings, argv[1] should be the filepath
//------------------------------------------------------------------------
int main(int argc, char* argv[]){
if(argc < 2){
printf("Unable to open file");
return 1;
}
else{
unsigned char png_signature_codes[8] = {'\x89', '\x50', '\x4E', '\x47', '\x0D', '\x0A', '\x1A', '\x0A' };
unsigned char* file = (unsigned char*)read_image(argv[1]);
uint32_t* width_ptr;
uint32_t* height_ptr;
uint32_t width, height;
if(file == NULL){
printf("Unable to open file");
return 1;
}
int offset = 0;
for( ; offset < 8; offset++){
//printf("is: %d should be: %d\n", (unsigned char)file[offset], png_signature_codes[offset]);
if((unsigned char)file[offset] != png_signature_codes[offset]){
printf("Unable to parse file");
return 1;
}
}
int done = 0;
while(!done){
uint32_t* block_size_ptr = (uint32_t*)(file + offset);
uint32_t block_size = ntohl(*block_size_ptr);
//printf("block size: %d\n", block_size);
offset +=4; // moving 4 bytes after reading block size;
char block_type[5];
for(int i = 0; i < 4; i++){
block_type[i] = file[offset + i];
}
block_type[4] = '\0';
offset += 4; // moving 4 bytes after reading block type
//printf("%s\n", block_type);
if(strcmp(block_type, "IHDR") == 0){
width_ptr = (uint32_t*)(file + offset);
height_ptr = (uint32_t*)(file + offset + 4);
width = ntohl(*width_ptr);
height = ntohl(*height_ptr);
}
if(strcmp(block_type, "IEND") == 0){
done = 1;
}
for(int i = 0; i < block_size; offset++, i++) // move block_size bytes forward
{
//printf("moving a byte forward \n");
}
offset += 4; // move 4 bytes forward for CRC
}
printf("PNG image width: %d\n", width);
printf("PNG image height: %d\n", height);
printf("PNG file size: %d\n", offset);
free(file);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int nbOfE;
int* createArr(){
int *p = (int*)malloc(sizeof(int)*10000000);
return p;
}
void swap(int* a, int* b){
int tmp = *a;
*a = *b;
*b = tmp;
}
void generateArr(int* p, int n){
srand((int) time(0));
for(int i = 0; i< n; i++){
p[i] = rand();
}
}
void insertionSort(int *p, int n){
clock_t tstart,tfinish;
tstart= clock();
time_t t1,t2; time(&t1);
for(int i =1; i < n; i++){
int value = p[i];
while(i> 0 && value < p[i-1]){
p[i] = p[i-1];
i--;
}
p[i] = value;
}
time(&t2);
int durationinseconds = (int) (t2 - t1);
tfinish= clock();
float tcomp;
tcomp=(float)(tfinish-tstart)/CLOCKS_PER_SEC;
printf("Second: %d\n", durationinseconds);
printf("Tick: %f\n", tcomp);
}
void selectionSort (int *p, int n){
clock_t tstart,tfinish;
tstart= clock();
time_t t1,t2; time(&t1);
for(int i = 0; i< n; i++){
for(int j = i+ 1; j<n; j++){
if(p[j]< p[i]){
int tmp = p[j];
p[j] = p[i];
p[i] = tmp;
}
}
}
time(&t2);
int durationinseconds = (int) (t2 - t1);
tfinish= clock();
float tcomp;
tcomp=(float)(tfinish-tstart)/CLOCKS_PER_SEC;
printf("Second: %d\n", durationinseconds);
printf("Tick: %f\n", tcomp);
}
void heapify(int *p, int n, int i){
int largest = i;
int l = i*2 + 1;
int r = i*2 + 2;
if(l<n && p[l] > p[largest]){
largest = l;
}
if( r<n && p[r] > p[largest]){
largest = r;
}
if(largest != i){
swap(&p[largest], &p[i]);
heapify(p,n,largest);
}
}
void heapSort(int* p, int n){
//Build heap from bottom up
clock_t tstart,tfinish;
tstart= clock();
time_t t1,t2; time(&t1);
for(int i = n/2-1; i>=0; i--){
heapify(p, n, i);
}
//take out the biggest item, the heap -1 element
for(int i = n-1; i> 0; i--){
swap(&p[i], &p[0]);
heapify(p, i, 0);
}
time(&t2);
int durationinseconds = (int) (t2 - t1);
tfinish= clock();
float tcomp;
tcomp=(float)(tfinish-tstart)/CLOCKS_PER_SEC;
printf("Second: %d\n", durationinseconds);
printf("Tick: %f\n", tcomp);
}
int partition(int *p, int start, int end){
int pivot = p[end];
int index = start;
for(int i = start; i<=end; i++){
if(p[i]<=pivot){
swap(&p[i], &p[index]);
index++;
}
}
return index-1;
}
void quickSort(int* p, int start, int end){
if(start < end){
int k = partition(p, start, end);
quickSort(p, start, k-1);
quickSort(p, k+1, end);
}
else return;
}
void processQuickSort(int * p, int n){
clock_t tstart,tfinish;
tstart= clock();
time_t t1,t2; time(&t1);
int start = 0;
int end = n -1;
quickSort(p, start, end);
time(&t2);
int durationinseconds = (int) (t2 - t1);
tfinish= clock();
float tcomp;
tcomp=(float)(tfinish-tstart)/CLOCKS_PER_SEC;
printf("Second: %d\n", durationinseconds);
printf("Tick: %f\n", tcomp);
}
void merge(int* Left, int* Right, int* p, int l, int r){
int i, j, k;
i = j =k =0;
while (i < l && j< r){
if(Left[i]<=Right[j]){
p[k] = Left[i];
k++;
i++;
}
else{
p[k] = Right[j];
j++;
k++;
}
}
while(i<l){
p[k] = Left[i];
i++;
k++;
}
while(j<r){
p[k] = Right[j];
j++;
k++;
}
}
void mergeSort(int*p, int n){
if(n<2) return;
else{
int mid = n/2;
int Left[mid];
int Right[n-mid];
for(int i = 0; i< mid; i++){
Left[i] = p[i];
}
for(int j = mid; j< n; j++){
Right[j-mid] = p[j];
}
mergeSort(Left, mid);
mergeSort(Right, n-mid);
merge(Left, Right, p, mid, n-mid);
}
}
void processMergeSort(int*p, int n){
clock_t tstart,tfinish;
tstart= clock();
time_t t1,t2; time(&t1);
mergeSort(p,n);
time(&t2);
int durationinseconds = (int) (t2 - t1);
tfinish= clock();
float tcomp;
tcomp=(float)(tfinish-tstart)/CLOCKS_PER_SEC;
printf("Second: %d\n", durationinseconds);
printf("Tick: %f\n", tcomp);
}
int main(){
int* p = createArr();
int* k = createArr();
printf("1. Generate data\n2.Insertion Sort\n3.Selection Sort\n4.Heap Sort\n5.Quick Sort\n6. Merge Sort\n");
int mode;
do{
printf("Choose mode: ");
scanf("%d", &mode);
switch (mode)
{
case 0:; return 0;
case 1:;
printf("Enter the number of Element: ");
scanf("%d", &nbOfE);
generateArr(p, nbOfE);
for(int i = 0; i< nbOfE; i++){
k[i] = p[i];
}
break;
case 2:;
insertionSort(k, nbOfE);
for(int i = 0; i< nbOfE; i++){
k[i] = p[i];
}
break;
case 3:;
selectionSort(k, nbOfE);
for(int i = 0; i< nbOfE; i++){
k[i] = p[i];
}
break;
case 4:;
heapSort(k, nbOfE);
for(int i = 0; i< nbOfE; i++){
k[i] = p[i];
}
break;
case 5:;
processQuickSort(k, nbOfE);
for(int i = 0; i< nbOfE; i++){
k[i] = p[i];
}
break;
case 6:;
processMergeSort(k, nbOfE);
for(int i = 0; i< nbOfE; i++){
k[i] = p[i];
}
break;
default: printf("invalid!\n");
break;
}
} while(mode !=0);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int num1,num2;
clrscr();
printf("Enter any two numbers");
scanf("%d%d",&num1,&num2);
switch(num1>num2)
{
case 0:
printf("%d is maximum",num2);
break;
case 2:
printf("%d is maximum",num1);
break;
}
getch();
return 0;
}
|
C
|
#include<stdio.h>
typedef struct singleLL{
int data;
struct singleLL *next;
}node;
void create(node *l){
int i,ch;
while (1){
printf("Enter data:");
scanf ("%d",&l->data);
printf("Enter more data?(0/1)");
scanf ("%d",&ch);
if(ch==0){
l->next='\0';
break ;
}
node *t=(node*)malloc(sizeof(node));
l->next=t;
l=l->next;
}
}
void reverse(node *l){
int a[100],i=1,y;
node *x;
x=l;
while (x->next!='\0'){
a[i]=x->data;
i++;
x=x->next;
}
a[i]=x->data;
free(x);
/*int x=i;
printf("\n %d\n",i);
for(i=x;i>=1;i--){
printf("%d->",a[i]);
}*/
// node *l=(node*)malloc(sizeof(node));
// x->data=a[i];
while (1){
if(i==1)
break;
l->data=a[i];
node *t=(node*)malloc(sizeof(node));
l->next=t;
l=l->next;
i--;
}
l->data=a[i];
// printf("%d",x->data);
l->next='\0';
// return x;
}
void display (node *l){
while(l->next!='\0'){
printf("%d->",l->data);
l=l->next;
}
printf("%d\n",l->data);
}
int main (){
int x=0;
node *h;
h=(node*)malloc(sizeof(node));
create (h);
display (h);
reverse(h);
display(h);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** CPE_corewar_2017
** File description:
** Labels writter
*/
#include "asm/writter/labels_writter.h"
#include "asm/utils/clean_str.h"
void init_labels(label_t *label_s, asm_t *asm_s)
{
size_t i = 0;
for (; asm_s->labels[i] != NULL; i++) {
label_s[i].label = asm_s->labels[i];
label_s[i].label_call = malloc(sizeof(uint16_t));
label_s[i].offset = malloc(sizeof(uint16_t));
label_s[i].label_call[0] = 0;
label_s[i].label_define = 0;
label_s[i].calls = 0;
}
label_s[i].label = NULL;
}
void insert_label_define(uint32_t *new_len, label_t *label_s)
{
static size_t i = 0;
label_s[i++].label_define = new_len[0];
}
void insert_label_call(bool byte, char *label, uint32_t *call,
label_t *label_s)
{
static int count = 1;
label = clean_str(label);
label = substring(label, 2, my_strlen(label));
if (!label)
return;
for (size_t i = 0; label_s[i].label; i++) {
if (str_eq(label, label_s[i].label) == 1) {
label_s[i].label_call = realloc(label_s[i].label_call,
sizeof(uint16_t*) * count);
label_s[i].offset = realloc(label_s[i].offset,
sizeof(uint16_t*) * count);
label_s[i].label_call[label_s[i].calls] = call[0];
label_s[i].offset[label_s[i].calls] = call[1];
label_s[i].calls += 1;
label_s[i].bytes = byte;
count++;
}
}
free(label);
}
void free_struct(label_t *label_s, size_t label_count)
{
if (!label_s)
return;
for (size_t i = 0; i < label_count; i++) {
if (label_s[i].label_call)
free(label_s[i].label_call);
if (label_s[i].offset)
free(label_s[i].offset);
}
free(label_s);
}
|
C
|
#include <string.h>
#include "string_t.h"
/**
* Initializes all fields of string_t struct. If str.buf is already
* allocated, it is not freed.
*/
void string_set(string_t *str, const char *val) {
size_t val_len = strlen(val);
if (val_len >= string_t_initial_capacity) {
str->buf = (char *) calloc(val_len*2, sizeof(char));
str->capacity = val_len*2;
} else {
str->buf = (char *) calloc(string_t_initial_capacity, sizeof(char));
str->capacity = string_t_initial_capacity;
}
str->size = val_len;
memcpy(str->buf, val, val_len);
}
/**
* Initializes a string_t structure. Writes to all fields.
*/
void string_init(string_t *str) {
str->buf = (char *) calloc(string_t_initial_capacity, sizeof(char));
str->capacity = string_t_initial_capacity;
str->size = 0;
}
/**
* Reserves the buffer of str to have provided capacity.
*
* If str already had a malloced buffer, it is not freed.
*/
void string_reserve(string_t *str, size_t capacity) {
str->buf = (char *) calloc(capacity, sizeof(char));
str->capacity = capacity;
str->size = 0;
}
/**
* Returns negative number on error.
*/
int string_appendc(string_t *str, char c) {
if (str->size + 1 >= str->capacity) {
size_t new_cap = 2 * str->capacity;
if (new_cap < str->capacity) {
// overflow
return -2;
}
char *new_buf = (char *) realloc(str->buf, new_cap);
if (new_buf == NULL) {
return -1;
}
str->buf = new_buf;
str->capacity = new_cap;
}
str->buf[str->size++] = c;
str->buf[str->size] = 0x0;
return 0;
}
/**
* Returns negative number on error.
*/
int string_appends(string_t *str, const char *c) {
int status;
while ((*c) != 0x0) {
status = string_appendc(str, *c);
if (status < 0) {
return status;
}
c++;
}
return 0;
}
// /**
// * Returns negative number on error, 0 on success.
// */
// int string_appends(string_t *str, string_t *ap) {
// }
/**
* str.size should be checked before calling this. Calling
* this on an empty string returns 0;
*/
char string_pop(string_t *str) {
if (str->size > 0) {
char c = str->buf[str->size-1];
str->buf[str->size-1] = 0;
str->size--;
return c;
}
return 0;
}
/**
* Sets the string size to 0.
*
* NOTE: does not erase all memory contents.
*/
void string_clear(string_t *str) {
// memset(str->buf, 0, str->size);
str->size = 0;
str->buf[0] = 0x0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.