language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * Copyright (c) 2019 Kevin Townsend (KTOWN) * * SPDX-License-Identifier: Apache-2.0 */ #include <errno.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <zsl/zsl.h> #include <zsl/matrices.h> /* * WARNING: Work in progress! * * The code in this module is very 'naive' in the sense that no attempt * has been made at efficiency. It is written from the perspective * that code should be written to be 'reliable, elegant, efficient' in that * order. * * Clarity and reliability have been absolutely prioritized in this * early stage, with the key goal being good unit test coverage before * moving on to any form of general-purpose or architecture-specific * optimisation. */ // TODO: Introduce local macros for bounds/shape checks to avoid duplication! int zsl_mtx_entry_fn_empty(struct zsl_mtx *m, size_t i, size_t j) { return zsl_mtx_set(m, i, j, 0); } int zsl_mtx_entry_fn_identity(struct zsl_mtx *m, size_t i, size_t j) { return zsl_mtx_set(m, i, j, i == j ? 1.0 : 0); } int zsl_mtx_entry_fn_random(struct zsl_mtx *m, size_t i, size_t j) { /* TODO: Determine an appropriate random number generator. */ return zsl_mtx_set(m, i, j, 0); } int zsl_mtx_init(struct zsl_mtx *m, zsl_mtx_init_entry_fn_t entry_fn) { int rc; for (size_t i = 0; i < m->sz_rows; i++) { for (size_t j = 0; j < m->sz_cols; j++) { /* If entry_fn is NULL, assign 0.0 values. */ if (entry_fn == NULL) { rc = zsl_mtx_entry_fn_empty(m, i, j); } else { rc = entry_fn(m, i, j); } /* Abort if entry_fn returned an error code. */ if (rc) { return rc; } } } return 0; } int zsl_mtx_from_arr(struct zsl_mtx *m, zsl_real_t *a) { memcpy(m->data, a, (m->sz_rows * m->sz_cols) * sizeof(zsl_real_t)); return 0; } int zsl_mtx_copy(struct zsl_mtx *mdest, struct zsl_mtx *msrc) { #if CONFIG_ZSL_BOUNDS_CHECKS /* Ensure that msrc and mdest have the same shape. */ if ((mdest->sz_rows != msrc->sz_rows) || (mdest->sz_cols != msrc->sz_cols)) { return -EINVAL; } #endif /* Make a copy of matrix 'msrc'. */ memcpy(mdest->data, msrc->data, sizeof(zsl_real_t) * msrc->sz_rows * msrc->sz_cols); return 0; } int zsl_mtx_get(struct zsl_mtx *m, size_t i, size_t j, zsl_real_t *x) { #if CONFIG_ZSL_BOUNDS_CHECKS if ((i >= m->sz_rows) || (j >= m->sz_cols)) { return -EINVAL; } #endif *x = m->data[(i * m->sz_cols) + j]; return 0; } int zsl_mtx_set(struct zsl_mtx *m, size_t i, size_t j, zsl_real_t x) { #if CONFIG_ZSL_BOUNDS_CHECKS if ((i >= m->sz_rows) || (j >= m->sz_cols)) { return -EINVAL; } #endif m->data[(i * m->sz_cols) + j] = x; return 0; } int zsl_mtx_get_row(struct zsl_mtx *m, size_t i, zsl_real_t *v) { int rc; zsl_real_t x; for (size_t j = 0; j < m->sz_cols; j++) { rc = zsl_mtx_get(m, i, j, &x); if (rc) { return rc; } v[j] = x; } return 0; } int zsl_mtx_set_row(struct zsl_mtx *m, size_t i, zsl_real_t *v) { int rc; for (size_t j = 0; j < m->sz_cols; j++) { rc = zsl_mtx_set(m, i, j, v[j]); if (rc) { return rc; } } return 0; } int zsl_mtx_get_col(struct zsl_mtx *m, size_t j, zsl_real_t *v) { int rc; zsl_real_t x; for (size_t i = 0; i < m->sz_rows; i++) { rc = zsl_mtx_get(m, i, j, &x); if (rc) { return rc; } v[i] = x; } return 0; } int zsl_mtx_set_col(struct zsl_mtx *m, size_t j, zsl_real_t *v) { int rc; for (size_t i = 0; i < m->sz_rows; i++) { rc = zsl_mtx_set(m, i, j, v[i]); if (rc) { return rc; } } return 0; } int zsl_mtx_unary_op(struct zsl_mtx *m, zsl_mtx_unary_op_t op) { /* Execute the unary operation component by component. */ for (size_t i = 0; i < m->sz_cols * m->sz_rows; i++) { switch (op) { case ZSL_MTX_UNARY_OP_INCREMENT: m->data[i] += 1.0; break; case ZSL_MTX_UNARY_OP_DECREMENT: m->data[i] -= 1.0; break; case ZSL_MTX_UNARY_OP_NEGATIVE: m->data[i] = -m->data[i]; break; case ZSL_MTX_UNARY_OP_ROUND: m->data[i] = ZSL_ROUND(m->data[i]); break; case ZSL_MTX_UNARY_OP_ABS: m->data[i] = ZSL_ABS(m->data[i]); break; case ZSL_MTX_UNARY_OP_FLOOR: m->data[i] = ZSL_FLOOR(m->data[i]); break; case ZSL_MTX_UNARY_OP_CEIL: m->data[i] = ZSL_CEIL(m->data[i]); break; case ZSL_MTX_UNARY_OP_EXP: m->data[i] = ZSL_EXP(m->data[i]); break; case ZSL_MTX_UNARY_OP_LOG: m->data[i] = ZSL_LOG(m->data[i]); break; case ZSL_MTX_UNARY_OP_LOG10: m->data[i] = ZSL_LOG10(m->data[i]); break; case ZSL_MTX_UNARY_OP_SQRT: m->data[i] = ZSL_SQRT(m->data[i]); break; case ZSL_MTX_UNARY_OP_SIN: m->data[i] = ZSL_SIN(m->data[i]); break; case ZSL_MTX_UNARY_OP_COS: m->data[i] = ZSL_COS(m->data[i]); break; case ZSL_MTX_UNARY_OP_TAN: m->data[i] = ZSL_TAN(m->data[i]); break; case ZSL_MTX_UNARY_OP_ASIN: m->data[i] = ZSL_ASIN(m->data[i]); break; case ZSL_MTX_UNARY_OP_ACOS: m->data[i] = ZSL_ACOS(m->data[i]); break; case ZSL_MTX_UNARY_OP_ATAN: m->data[i] = ZSL_ATAN(m->data[i]); break; case ZSL_MTX_UNARY_OP_SINH: m->data[i] = ZSL_SINH(m->data[i]); break; case ZSL_MTX_UNARY_OP_COSH: m->data[i] = ZSL_COSH(m->data[i]); break; case ZSL_MTX_UNARY_OP_TANH: m->data[i] = ZSL_TANH(m->data[i]); break; default: /* Not yet implemented! */ return -ENOSYS; } } return 0; } int zsl_mtx_unary_func(struct zsl_mtx *m, zsl_mtx_unary_fn_t fn) { int rc; for (size_t i = 0; i < m->sz_rows; i++) { for (size_t j = 0; j < m->sz_cols; j++) { /* If fn is NULL, do nothing. */ if (fn != NULL) { rc = fn(m, i, j); if (rc) { return rc; } } } } return 0; } int zsl_mtx_binary_op(struct zsl_mtx *ma, struct zsl_mtx *mb, struct zsl_mtx *mc, zsl_mtx_binary_op_t op) { #if CONFIG_ZSL_BOUNDS_CHECKS if ((ma->sz_rows != mb->sz_rows) || (mb->sz_rows != mc->sz_rows) || (ma->sz_cols != mb->sz_cols) || (mb->sz_cols != mc->sz_cols)) { return -EINVAL; } #endif /* Execute the binary operation component by component. */ for (size_t i = 0; i < ma->sz_cols * ma->sz_rows; i++) { switch (op) { case ZSL_MTX_BINARY_OP_ADD: mc->data[i] = ma->data[i] + mb->data[i]; break; case ZSL_MTX_BINARY_OP_SUB: mc->data[i] = ma->data[i] - mb->data[i]; break; case ZSL_MTX_BINARY_OP_MULT: mc->data[i] = ma->data[i] * mb->data[i]; break; case ZSL_MTX_BINARY_OP_DIV: if (mb->data[i] == 0.0) { mc->data[i] = 0.0; } else { mc->data[i] = ma->data[i] / mb->data[i]; } break; case ZSL_MTX_BINARY_OP_MEAN: mc->data[i] = (ma->data[i] + mb->data[i]) / 2.0; case ZSL_MTX_BINARY_OP_EXPON: mc->data[i] = ZSL_POW(ma->data[i], mb->data[i]); case ZSL_MTX_BINARY_OP_MIN: mc->data[i] = ma->data[i] < mb->data[i] ? ma->data[i] : mb->data[i]; case ZSL_MTX_BINARY_OP_MAX: mc->data[i] = ma->data[i] > mb->data[i] ? ma->data[i] : mb->data[i]; case ZSL_MTX_BINARY_OP_EQUAL: mc->data[i] = ma->data[i] == mb->data[i] ? 1.0 : 0.0; case ZSL_MTX_BINARY_OP_NEQUAL: mc->data[i] = ma->data[i] != mb->data[i] ? 1.0 : 0.0; case ZSL_MTX_BINARY_OP_LESS: mc->data[i] = ma->data[i] < mb->data[i] ? 1.0 : 0.0; case ZSL_MTX_BINARY_OP_GREAT: mc->data[i] = ma->data[i] > mb->data[i] ? 1.0 : 0.0; case ZSL_MTX_BINARY_OP_LEQ: mc->data[i] = ma->data[i] <= mb->data[i] ? 1.0 : 0.0; case ZSL_MTX_BINARY_OP_GEQ: mc->data[i] = ma->data[i] >= mb->data[i] ? 1.0 : 0.0; default: /* Not yet implemented! */ return -ENOSYS; } } return 0; } int zsl_mtx_binary_func(struct zsl_mtx *ma, struct zsl_mtx *mb, struct zsl_mtx *mc, zsl_mtx_binary_fn_t fn) { int rc; #if CONFIG_ZSL_BOUNDS_CHECKS if ((ma->sz_rows != mb->sz_rows) || (mb->sz_rows != mc->sz_rows) || (ma->sz_cols != mb->sz_cols) || (mb->sz_cols != mc->sz_cols)) { return -EINVAL; } #endif for (size_t i = 0; i < ma->sz_rows; i++) { for (size_t j = 0; j < ma->sz_cols; j++) { /* If fn is NULL, do nothing. */ if (fn != NULL) { rc = fn(ma, mb, mc, i, j); if (rc) { return rc; } } } } return 0; } int zsl_mtx_add(struct zsl_mtx *ma, struct zsl_mtx *mb, struct zsl_mtx *mc) { return zsl_mtx_binary_op(ma, mb, mc, ZSL_MTX_BINARY_OP_ADD); } int zsl_mtx_add_d(struct zsl_mtx *ma, struct zsl_mtx *mb) { return zsl_mtx_binary_op(ma, mb, ma, ZSL_MTX_BINARY_OP_ADD); } int zsl_mtx_sum_rows_d(struct zsl_mtx *m, size_t i, size_t j) { #if CONFIG_ZSL_BOUNDS_CHECKS if ((i >= m->sz_rows) || (j >= m->sz_rows)) { return -EINVAL; } #endif /* Add row j to row i, element by element. */ for (size_t x = 0; x < m->sz_cols; x++) { m->data[(i * m->sz_cols) + x] += m->data[(j * m->sz_cols) + x]; } return 0; } int zsl_mtx_sum_rows_scaled_d(struct zsl_mtx *m, size_t i, size_t j, zsl_real_t s) { #if CONFIG_ZSL_BOUNDS_CHECKS if ((i >= m->sz_rows) || (j >= m->sz_cols)) { return -EINVAL; } #endif /* Set the values in row 'i' to 'i[n] += j[n] * s' . */ for (size_t x = 0; x < m->sz_cols; x++) { m->data[(i * m->sz_cols) + x] += (m->data[(j * m->sz_cols) + x] * s); } return 0; } int zsl_mtx_sub(struct zsl_mtx *ma, struct zsl_mtx *mb, struct zsl_mtx *mc) { return zsl_mtx_binary_op(ma, mb, mc, ZSL_MTX_BINARY_OP_SUB); } int zsl_mtx_sub_d(struct zsl_mtx *ma, struct zsl_mtx *mb) { return zsl_mtx_binary_op(ma, mb, ma, ZSL_MTX_BINARY_OP_SUB); } int zsl_mtx_mult(struct zsl_mtx *ma, struct zsl_mtx *mb, struct zsl_mtx *mc) { #if CONFIG_ZSL_BOUNDS_CHECKS /* Ensure that ma has the same number as columns as mb has rows. */ if (ma->sz_cols != mb->sz_rows) { return -EINVAL; } /* Ensure that mc has ma rows and mb cols */ if ((mc->sz_rows != ma->sz_rows) || (mc->sz_cols != mb->sz_cols)) { return -EINVAL; } #endif ZSL_MATRIX_DEF(ma_copy, ma->sz_rows, ma->sz_cols); ZSL_MATRIX_DEF(mb_copy, mb->sz_rows, mb->sz_cols); zsl_mtx_copy(&ma_copy, ma); zsl_mtx_copy(&mb_copy, mb); for (size_t i = 0; i < ma_copy.sz_rows; i++) { for (size_t j = 0; j < mb_copy.sz_cols; j++) { mc->data[j + i * mb_copy.sz_cols] = 0; for (size_t k = 0; k < ma_copy.sz_cols; k++) { mc->data[j + i * mb_copy.sz_cols] += ma_copy.data[k + i * ma_copy.sz_cols] * mb_copy.data[j + k * mb_copy.sz_cols]; } } } return 0; } int zsl_mtx_mult_d(struct zsl_mtx *ma, struct zsl_mtx *mb) { #if CONFIG_ZSL_BOUNDS_CHECKS /* Ensure that ma has the same number as columns as mb has rows. */ if (ma->sz_cols != mb->sz_rows) { return -EINVAL; } /* Ensure that mb is a square matrix. */ if (mb->sz_rows != mb->sz_cols) { return -EINVAL; } #endif zsl_mtx_mult(ma, mb, ma); return 0; } int zsl_mtx_scalar_mult_d(struct zsl_mtx *m, zsl_real_t s) { for (size_t i = 0; i < m->sz_rows * m->sz_cols; i++) { m->data[i] *= s; } return 0; } int zsl_mtx_scalar_mult_row_d(struct zsl_mtx *m, size_t i, zsl_real_t s) { #if CONFIG_ZSL_BOUNDS_CHECKS if (i >= m->sz_rows) { return -EINVAL; } #endif for (size_t k = 0; k < m->sz_cols; k++) { m->data[(i * m->sz_cols) + k] *= s; } return 0; } int zsl_mtx_trans(struct zsl_mtx *ma, struct zsl_mtx *mb) { #if CONFIG_ZSL_BOUNDS_CHECKS /* Ensure that ma and mb have the same shape. */ if ((ma->sz_rows != mb->sz_cols) || (ma->sz_cols != mb->sz_rows)) { return -EINVAL; } #endif zsl_real_t d[ma->sz_cols]; for (size_t i = 0; i < ma->sz_rows; i++) { zsl_mtx_get_row(ma, i, d); zsl_mtx_set_col(mb, i, d); } return 0; } int zsl_mtx_adjoint_3x3(struct zsl_mtx *m, struct zsl_mtx *ma) { /* Make sure this is a square matrix. */ if ((m->sz_rows != m->sz_cols) || (ma->sz_rows != ma->sz_cols)) { return -EINVAL; } #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure this is a 3x3 matrix. */ if ((m->sz_rows != 3) || (ma->sz_rows != 3)) { return -EINVAL; } #endif /* * 3x3 matrix element to array table: * * 1,1 = 0 1,2 = 1 1,3 = 2 * 2,1 = 3 2,2 = 4 2,3 = 5 * 3,1 = 6 3,2 = 7 3,3 = 8 */ ma->data[0] = m->data[4] * m->data[8] - m->data[7] * m->data[5]; ma->data[1] = m->data[7] * m->data[2] - m->data[1] * m->data[8]; ma->data[2] = m->data[1] * m->data[5] - m->data[4] * m->data[2]; ma->data[3] = m->data[6] * m->data[5] - m->data[3] * m->data[8]; ma->data[4] = m->data[0] * m->data[8] - m->data[6] * m->data[2]; ma->data[5] = m->data[3] * m->data[2] - m->data[0] * m->data[5]; ma->data[6] = m->data[3] * m->data[7] - m->data[6] * m->data[4]; ma->data[7] = m->data[6] * m->data[1] - m->data[0] * m->data[7]; ma->data[8] = m->data[0] * m->data[4] - m->data[3] * m->data[1]; return 0; } int zsl_mtx_adjoint(struct zsl_mtx *m, struct zsl_mtx *ma) { /* Shortcut for 3x3 matrices. */ if (m->sz_rows == 3) { return zsl_mtx_adjoint_3x3(m, ma); } #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure this is a square matrix. */ if (m->sz_rows != m->sz_cols) { return -EINVAL; } #endif zsl_real_t sign; zsl_real_t d; ZSL_MATRIX_DEF(mr, (m->sz_cols - 1), (m->sz_cols - 1)); for (size_t i = 0; i < m->sz_cols; i++) { for (size_t j = 0; j < m->sz_cols; j++) { sign = 1.0; if ((i + j) % 2 != 0) { sign = -1.0; } zsl_mtx_reduce(m, &mr, i, j); zsl_mtx_deter(&mr, &d); d *= sign; zsl_mtx_set(ma, i, j, d); } } return 0; } #ifndef CONFIG_ZSL_SINGLE_PRECISION int zsl_mtx_vec_wedge(struct zsl_mtx *m, struct zsl_vec *v) { #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure the dimensions of 'm' and 'v' match. */ if (v->sz != m->sz_cols || v->sz < 4 || m->sz_rows != (m->sz_cols - 1)) { return -EINVAL; } #endif zsl_real_t d; ZSL_MATRIX_DEF(A, m->sz_cols, m->sz_cols); ZSL_MATRIX_DEF(Ai, m->sz_cols, m->sz_cols); ZSL_VECTOR_DEF(Av, m->sz_cols); ZSL_MATRIX_DEF(b, m->sz_cols, 1); zsl_mtx_init(&A, NULL); A.data[(m->sz_cols * m->sz_cols - 1)] = 1.0; for (size_t i = 0; i < m->sz_rows; i++) { zsl_mtx_get_row(m, i, Av.data); zsl_mtx_set_row(&A, i, Av.data); } zsl_mtx_deter(&A, &d); zsl_mtx_inv(&A, &Ai); zsl_mtx_init(&b, NULL); b.data[(m->sz_cols - 1)] = d; zsl_mtx_mult(&Ai, &b, &b); zsl_vec_from_arr(v, b.data); return 0; } #endif int zsl_mtx_reduce(struct zsl_mtx *m, struct zsl_mtx *mr, size_t i, size_t j) { size_t u = 0; zsl_real_t x; zsl_real_t v[mr->sz_rows * mr->sz_rows]; #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure mr is 1 less than m. */ if (mr->sz_rows != m->sz_rows - 1) { return -EINVAL; } if (mr->sz_cols != m->sz_cols - 1) { return -EINVAL; } if ((i >= m->sz_rows) || (j >= m->sz_cols)) { return -EINVAL; } #endif for (size_t k = 0; k < m->sz_rows; k++) { for (size_t g = 0; g < m->sz_rows; g++) { if (k != i && g != j) { zsl_mtx_get(m, k, g, &x); v[u] = x; u++; } } } zsl_mtx_from_arr(mr, v); return 0; } int zsl_mtx_reduce_iter(struct zsl_mtx *m, struct zsl_mtx *mred) { /* TODO: Properly check if matrix is square. */ if (m->sz_rows == mred->sz_rows) { zsl_mtx_copy(mred, m); return 0; } ZSL_MATRIX_DEF(my, (m->sz_rows - 1), (m->sz_cols - 1)); zsl_mtx_reduce(m, &my, 0, 0); zsl_mtx_reduce_iter(&my, mred); return 0; } int zsl_mtx_augm_diag(struct zsl_mtx *m, struct zsl_mtx *maug) { zsl_real_t x; /* TODO: Properly check if matrix is square, and diff > 0. */ size_t diff = (maug->sz_rows) - (m->sz_rows); zsl_mtx_init(maug, zsl_mtx_entry_fn_identity); for (size_t i = 0; i < m->sz_rows; i++) { for (size_t j = 0; j < m->sz_rows; j++) { zsl_mtx_get(m, i, j, &x); zsl_mtx_set(maug, i + diff, j + diff, x); } } return 0; } int zsl_mtx_deter_3x3(struct zsl_mtx *m, zsl_real_t *d) { /* Make sure this is a square matrix. */ if (m->sz_rows != m->sz_cols) { return -EINVAL; } #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure this is a 3x3 matrix. */ if (m->sz_rows != 3) { return -EINVAL; } #endif /* * 3x3 matrix element to array table: * * 1,1 = 0 1,2 = 1 1,3 = 2 * 2,1 = 3 2,2 = 4 2,3 = 5 * 3,1 = 6 3,2 = 7 3,3 = 8 */ *d = m->data[0] * (m->data[4] * m->data[8] - m->data[7] * m->data[5]); *d -= m->data[3] * (m->data[1] * m->data[8] - m->data[7] * m->data[2]); *d += m->data[6] * (m->data[1] * m->data[5] - m->data[4] * m->data[2]); return 0; } int zsl_mtx_deter(struct zsl_mtx *m, zsl_real_t *d) { /* Shortcut for 1x1 matrices. */ if (m->sz_rows == 1) { *d = m->data[0]; return 0; } /* Shortcut for 2x2 matrices. */ if (m->sz_rows == 2) { *d = m->data[0] * m->data[3] - m->data[2] * m->data[1]; return 0; } /* Shortcut for 3x3 matrices. */ if (m->sz_rows == 3) { return zsl_mtx_deter_3x3(m, d); } #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure this is a square matrix. */ if (m->sz_rows != m->sz_cols) { return -EINVAL; } #endif /* Full calculation required for non 3x3 matrices. */ int rc; zsl_real_t dtmp; zsl_real_t cur; zsl_real_t sign; ZSL_MATRIX_DEF(mr, (m->sz_rows - 1), (m->sz_rows - 1)); /* Clear determinant output before starting. */ *d = 0.0; /* * Iterate across row 0, removing columns one by one. * Note that these calls are recursive until we reach a 3x3 matrix, * which will be calculated using the shortcut at the top of this * function. */ for (size_t g = 0; g < m->sz_cols; g++) { zsl_mtx_get(m, 0, g, &cur); /* Get value at (0, g). */ zsl_mtx_init(&mr, NULL); /* Clear mr. */ zsl_mtx_reduce(m, &mr, 0, g); /* Remove row 0, column g. */ rc = zsl_mtx_deter(&mr, &dtmp); /* Calc. determinant of mr. */ sign = 1.0; if (rc) { return -EINVAL; } /* Uneven elements are negative. */ if (g % 2 != 0) { sign = -1.0; } /* Add current determinant to final output value. */ *d += dtmp * cur * sign; } return 0; } int zsl_mtx_gauss_elim(struct zsl_mtx *m, struct zsl_mtx *mg, struct zsl_mtx *mi, size_t i, size_t j) { int rc; zsl_real_t x, y; zsl_real_t epsilon = 1E-6; /* Make a copy of matrix m. */ rc = zsl_mtx_copy(mg, m); if (rc) { return -EINVAL; } /* Get the value of the element at position (i, j). */ rc = zsl_mtx_get(mg, i, j, &y); if (rc) { return rc; } /* If this is a zero value, don't do anything. */ if ((y >= 0 && y < epsilon) || (y <= 0 && y > -epsilon)) { return 0; } /* Cycle through the matrix row by row. */ for (size_t p = 0; p < mg->sz_rows; p++) { /* Skip row 'i'. */ if (p == i) { p++; } if (p == mg->sz_rows) { break; } /* Get the value of (p, j), aborting if value is zero. */ zsl_mtx_get(mg, p, j, &x); if ((x >= 1E-6) || (x <= -1E-6)) { rc = zsl_mtx_sum_rows_scaled_d(mg, p, i, -(x / y)); if (rc) { return -EINVAL; } rc = zsl_mtx_sum_rows_scaled_d(mi, p, i, -(x / y)); if (rc) { return -EINVAL; } } } return 0; } int zsl_mtx_gauss_elim_d(struct zsl_mtx *m, struct zsl_mtx *mi, size_t i, size_t j) { return zsl_mtx_gauss_elim(m, m, mi, i, j); } int zsl_mtx_gauss_reduc(struct zsl_mtx *m, struct zsl_mtx *mi, struct zsl_mtx *mg) { zsl_real_t v[m->sz_rows]; zsl_real_t epsilon = 1E-6; zsl_real_t x; zsl_real_t y; /* Copy the input matrix into 'mg' so all the changes will be done to * 'mg' and the input matrix will not be destroyed. */ zsl_mtx_copy(mg, m); for (size_t k = 0; k < m->sz_rows; k++) { /* Get every element in the diagonal. */ zsl_mtx_get(mg, k, k, &x); /* If the diagonal element is zero, find another value in the * same column that isn't zero and add the row containing * the non-zero element to the diagonal element's row. */ if ((x >= 0 && x < epsilon) || (x <= 0 && x > -epsilon)) { zsl_mtx_get_col(mg, k, v); for (size_t q = 0; q < m->sz_rows; q++) { zsl_mtx_get(mg, q, q, &y); if ((v[q] >= epsilon) || (v[q] <= -epsilon)) { /* If the non-zero element found is * above the diagonal, only add its row * if the diagonal element in this row * is zero, to avoid undoing previous * steps. */ if (q < k && ((y >= epsilon) || (y <= -epsilon))) { } else { zsl_mtx_sum_rows_d(mg, k, q); zsl_mtx_sum_rows_d(mi, k, q); break; } } } } /* Perform the gaussian elimination in the column of the * diagonal element to get rid of all the values in the column * except for the diagonal one. */ zsl_mtx_gauss_elim_d(mg, mi, k, k); /* Divide the diagonal element's row by the diagonal element. */ zsl_mtx_norm_elem_d(mg, mi, k, k); } return 0; } int zsl_mtx_gram_schmidt(struct zsl_mtx *m, struct zsl_mtx *mort) { ZSL_VECTOR_DEF(v, m->sz_rows); ZSL_VECTOR_DEF(w, m->sz_rows); ZSL_VECTOR_DEF(q, m->sz_rows); for (size_t t = 0; t < m->sz_cols; t++) { zsl_vec_init(&q); zsl_mtx_get_col(m, t, v.data); for (size_t g = 0; g < t; g++) { zsl_mtx_get_col(mort, g, w.data); /* Calculate the projection of every column vector * before 'g' on the 't'th column. */ zsl_vec_project(&w, &v, &w); zsl_vec_add(&q, &w, &q); } /* Substract the sum of the projections on the 't'th column from * the 't'th column and set this vector as the 't'th column of * the output matrix. */ zsl_vec_sub(&v, &q, &v); zsl_mtx_set_col(mort, t, v.data); } return 0; } int zsl_mtx_cols_norm(struct zsl_mtx *m, struct zsl_mtx *mnorm) { ZSL_VECTOR_DEF(v, m->sz_rows); for (size_t g = 0; g < m->sz_cols; g++) { zsl_mtx_get_col(m, g, v.data); zsl_vec_to_unit(&v); zsl_mtx_set_col(mnorm, g, v.data); } return 0; } int zsl_mtx_norm_elem(struct zsl_mtx *m, struct zsl_mtx *mn, struct zsl_mtx *mi, size_t i, size_t j) { int rc; zsl_real_t x; zsl_real_t epsilon = 1E-6; /* Make a copy of matrix m. */ rc = zsl_mtx_copy(mn, m); if (rc) { return -EINVAL; } /* Get the value to normalise. */ rc = zsl_mtx_get(mn, i, j, &x); if (rc) { return rc; } /* If the value is 0.0, abort. */ if ((x >= 0 && x < epsilon) || (x <= 0 && x > -epsilon)) { return 0; } rc = zsl_mtx_scalar_mult_row_d(mn, i, (1.0 / x)); if (rc) { return -EINVAL; } rc = zsl_mtx_scalar_mult_row_d(mi, i, (1.0 / x)); if (rc) { return -EINVAL; } return 0; } int zsl_mtx_norm_elem_d(struct zsl_mtx *m, struct zsl_mtx *mi, size_t i, size_t j) { return zsl_mtx_norm_elem(m, m, mi, i, j); } int zsl_mtx_inv_3x3(struct zsl_mtx *m, struct zsl_mtx *mi) { int rc; zsl_real_t d; /* Determinant. */ zsl_real_t s; /* Scale factor. */ /* Make sure these are square matrices. */ if ((m->sz_rows != m->sz_cols) || (mi->sz_rows != mi->sz_cols)) { return -EINVAL; } #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure 'm' and 'mi' have the same shape. */ if (m->sz_rows != mi->sz_rows) { return -EINVAL; } if (m->sz_cols != mi->sz_cols) { return -EINVAL; } /* Make sure these are 3x3 matrices. */ if ((m->sz_cols != 3) || (mi->sz_cols != 3)) { return -EINVAL; } #endif /* Calculate the determinant. */ rc = zsl_mtx_deter_3x3(m, &d); if (rc) { goto err; } /* Calculate the adjoint matrix. */ rc = zsl_mtx_adjoint_3x3(m, mi); if (rc) { goto err; } /* Scale the output using the determinant. */ if (d != 0) { s = 1.0 / d; rc = zsl_mtx_scalar_mult_d(mi, s); } else { /* Provide an identity matrix if the determinant is zero. */ rc = zsl_mtx_init(mi, zsl_mtx_entry_fn_identity); if (rc) { return -EINVAL; } } return 0; err: return rc; } int zsl_mtx_inv(struct zsl_mtx *m, struct zsl_mtx *mi) { int rc; zsl_real_t d = 0.0; /* Shortcut for 3x3 matrices. */ if (m->sz_rows == 3) { return zsl_mtx_inv_3x3(m, mi); } /* Make sure we have square matrices. */ if ((m->sz_rows != m->sz_cols) || (mi->sz_rows != mi->sz_cols)) { return -EINVAL; } #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure 'm' and 'mi' have the same shape. */ if (m->sz_rows != mi->sz_rows) { return -EINVAL; } if (m->sz_cols != mi->sz_cols) { return -EINVAL; } #endif /* Make a copy of matrix m on the stack to avoid modifying it. */ ZSL_MATRIX_DEF(m_tmp, mi->sz_rows, mi->sz_cols); rc = zsl_mtx_copy(&m_tmp, m); if (rc) { return -EINVAL; } /* Initialise 'mi' as an identity matrix. */ rc = zsl_mtx_init(mi, zsl_mtx_entry_fn_identity); if (rc) { return -EINVAL; } /* Make sure the determinant of 'm' is not zero. */ zsl_mtx_deter(m, &d); if (d == 0) { return 0; } /* Use Gauss-Jordan elimination for nxn matrices. */ zsl_mtx_gauss_reduc(m, mi, &m_tmp); return 0; } int zsl_mtx_cholesky(struct zsl_mtx *m, struct zsl_mtx *l) { #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure 'm' is square. */ if (m->sz_rows != m->sz_cols) { return -EINVAL; } /* Make sure 'm' is symmetric. */ zsl_real_t a, b; for (size_t i = 0; i < m->sz_rows; i++) { for (size_t j = 0; j < m->sz_rows; j++) { zsl_mtx_get(m, i, j, &a); zsl_mtx_get(m, j, i, &b); if (a != b) { return -EINVAL; } } } /* Make sure 'm' and 'l' have the same shape. */ if (m->sz_rows != l->sz_rows) { return -EINVAL; } if (m->sz_cols != l->sz_cols) { return -EINVAL; } #endif zsl_real_t sum, x, y; zsl_mtx_init(l, zsl_mtx_entry_fn_empty); for (size_t j = 0; j < m->sz_cols; j++) { sum = 0.0; for (size_t k = 0; k < j; k++) { zsl_mtx_get(l, j, k, &x); sum += x * x; } zsl_mtx_get(m, j, j, &x); zsl_mtx_set(l, j, j, ZSL_SQRT(x - sum)); for (size_t i = j + 1; i < m->sz_cols; i++) { sum = 0.0; for (size_t k = 0; k < j; k++) { zsl_mtx_get(l, j, k, &x); zsl_mtx_get(l, i, k, &y); sum += y * x; } zsl_mtx_get(l, j, j, &x); zsl_mtx_get(m, i, j, &y); zsl_mtx_set(l, i, j, (y - sum) / x); } } return 0; } int zsl_mtx_balance(struct zsl_mtx *m, struct zsl_mtx *mout) { int rc; bool done = false; zsl_real_t sum; zsl_real_t row, row2; zsl_real_t col, col2; /* Make sure we have square matrices. */ if ((m->sz_rows != m->sz_cols) || (mout->sz_rows != mout->sz_cols)) { return -EINVAL; } #if CONFIG_ZSL_BOUNDS_CHECKS /* Make sure 'm' and 'mout' have the same shape. */ if (m->sz_rows != mout->sz_rows) { return -EINVAL; } if (m->sz_cols != mout->sz_cols) { return -EINVAL; } #endif rc = zsl_mtx_copy(mout, m); if (rc) { goto err; } while (!done) { done = true; for (size_t i = 0; i < m->sz_rows; i++) { /* Calculate sum of components of each row, column. */ for (size_t j = 0; j < m->sz_cols; j++) { row += ZSL_ABS(mout->data[(i * m->sz_rows) + j]); col += ZSL_ABS(mout->data[(j * m->sz_rows) + i]); } /* TODO: Extend with a check against epsilon? */ if (col != 0.0 && row != 0.0) { row2 = row / 2.0; col2 = 1.0; sum = col + row; while (col < row2) { col2 *= 2.0; col *= 4.0; } row2 = row * 2.0; while (col > row2) { col2 /= 2.0; col /= 4.0; } if ((col + row) / col2 < 0.95 * sum) { done = false; row2 = 1.0 / col2; for (int k = 0; k < m->sz_rows; k++) { mout->data[(i * m->sz_rows) + k] *= row2; mout->data[(k * m->sz_rows) + i] *= col2; } } } row = 0.0; col = 0.0; } } err: return rc; } int zsl_mtx_householder(struct zsl_mtx *m, struct zsl_mtx *h, bool hessenberg) { size_t size = m->sz_rows; if (hessenberg == true) { size--; } ZSL_VECTOR_DEF(v, size); ZSL_VECTOR_DEF(v2, m->sz_rows); ZSL_VECTOR_DEF(e1, size); ZSL_MATRIX_DEF(mv, size, 1); ZSL_MATRIX_DEF(mvt, 1, size); ZSL_MATRIX_DEF(id, size, size); ZSL_MATRIX_DEF(vvt, size, size); ZSL_MATRIX_DEF(h2, size, size); /* Create the e1 vector, i.e. the vector (1, 0, 0, ...). */ zsl_vec_init(&e1); e1.data[0] = 1.0; /* Get the first column of the input matrix. */ zsl_mtx_get_col(m, 0, v2.data); if (hessenberg == true) { zsl_vec_get_subset(&v2, 1, size, &v); } else { zsl_vec_copy(&v, &v2); } /* Change the 'sign' value according to the sign of the first * coefficient of the matrix. */ zsl_real_t sign = 1.0; if (v.data[0] < 0) { sign = -1.0; } /* Calculate the vector 'v' that will later be used to calculate the * Householder matrix. */ zsl_vec_scalar_mult(&e1, -sign * zsl_vec_norm(&v)); zsl_vec_add(&v, &e1, &v); zsl_vec_scalar_div(&v, zsl_vec_norm(&v)); /* Calculate the H householder matrix by doing: * H = IDENTITY - 2 * v * v^t. */ zsl_mtx_from_arr(&mv, v.data); zsl_mtx_trans(&mv, &mvt); zsl_mtx_mult(&mv, &mvt, &vvt); zsl_mtx_init(&id, zsl_mtx_entry_fn_identity); zsl_mtx_scalar_mult_d(&vvt, -2); zsl_mtx_add(&id, &vvt, &h2); /* If Hessenberg set to true, augment the output to the size of 'm'. * If Hessenberg set to false, this line of code will do nothing but * copy the matrix 'h2' into the output matrix 'h', */ zsl_mtx_augm_diag(&h2, h); return 0; } int zsl_mtx_qrd(struct zsl_mtx *m, struct zsl_mtx *q, struct zsl_mtx *r, bool hessenberg) { ZSL_MATRIX_DEF(r2, m->sz_rows, m->sz_cols); ZSL_MATRIX_DEF(hess, m->sz_rows, m->sz_cols); ZSL_MATRIX_DEF(h, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(h2, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(qt, m->sz_rows, m->sz_rows); zsl_mtx_init(&h, NULL); zsl_mtx_init(&qt, zsl_mtx_entry_fn_identity); zsl_mtx_copy(r, m); for (size_t g = 0; g < (m->sz_rows - 1); g++) { /* Reduce the matrix by 'g' rows and columns each time. */ ZSL_MATRIX_DEF(mred, (m->sz_rows - g), (m->sz_cols - g)); ZSL_MATRIX_DEF(hred, (m->sz_rows - g), (m->sz_rows - g)); zsl_mtx_reduce_iter(r, &mred); /* Calculate the reduced Householder matrix 'hred'. */ if (hessenberg == true) { zsl_mtx_householder(&mred, &hred, true); } else { zsl_mtx_householder(&mred, &hred, false); } /* Augment the Householder matrix to the input matrix size. */ zsl_mtx_augm_diag(&hred, &h); zsl_mtx_mult(&h, r, &r2); /* Multiply this Householder matrix by the previous ones, * stacked in 'qt'. */ zsl_mtx_mult(&h, &qt, &h2); zsl_mtx_copy(&qt, &h2); if (hessenberg == true) { zsl_mtx_mult(&r2, &h, &hess); zsl_mtx_copy(r, &hess); } else { zsl_mtx_copy(r, &r2); } } /* Calculate the 'q' matrix by transposing 'qt'. */ zsl_mtx_trans(&qt, q); return 0; } #ifndef CONFIG_ZSL_SINGLE_PRECISION int zsl_mtx_qrd_iter(struct zsl_mtx *m, struct zsl_mtx *mout, size_t iter) { int rc; ZSL_MATRIX_DEF(q, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(r, m->sz_rows, m->sz_rows); /* Make a copy of 'm'. */ rc = zsl_mtx_copy(mout, m); if (rc) { return -EINVAL; } for (size_t g = 1; g <= iter; g++) { /* Perform the QR decomposition. */ zsl_mtx_qrd(mout, &q, &r, false); /* Multiply the results of the QR decomposition together but * changing its order. */ zsl_mtx_mult(&r, &q, mout); } return 0; } #endif #ifndef CONFIG_ZSL_SINGLE_PRECISION int zsl_mtx_eigenvalues(struct zsl_mtx *m, struct zsl_vec *v, size_t iter) { zsl_real_t diag; zsl_real_t sdiag; size_t real = 0; /* Epsilon is used to check 0 values in the subdiagonal, to determine * if any coimplekx values were found. Increasing the number of * iterations will move these values closer to 0, but when using * single-precision floats the numbers can still be quite large, so * we need to set a delta of +/- 0.001 in this case. */ zsl_real_t epsilon = 1E-6; ZSL_MATRIX_DEF(mout, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(mtemp, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(mtemp2, m->sz_rows, m->sz_rows); /* Balance the matrix. */ zsl_mtx_balance(m, &mtemp); /* Put the balanced matrix into hessenberg form. */ zsl_mtx_qrd(&mtemp, &mout, &mtemp2, true); /* Calculate the upper triangular matrix by using the recursive QR * decomposition method. */ zsl_mtx_qrd_iter(&mtemp2, &mout, iter); zsl_vec_init(v); /* If the matrix is symmetric, then it will always have real * eigenvalues, so treat this case appart. */ if (zsl_mtx_is_sym(m) == true) { for (size_t g = 0; g < m->sz_rows; g++) { zsl_mtx_get(&mout, g, g, &diag); v->data[g] = diag; } return 0; } /* * If any value just below the diagonal is non-zero, it means that the * numbers above and to the right of the non-zero value are a pair of * complex values, a complex number and its conjugate. * * SVD will always return real numbers so this can be ignored, but if * you are calculating eigenvalues outside the SVD method, you may * get complex numbers, which will be indicated with the return error * code '-ECOMPLEXVAL'. * * If the imput matrix has complex eigenvalues, then these will be * ignored and the output vector will not include them. * * NOTE: The real and imaginary parts of the complex numbers are not * available. This only checks if there are any complex eigenvalues and * returns an appropriate error code to alert the user that there are * non-real eigenvalues present. */ for (size_t g = 0; g < (m->sz_rows - 1); g++) { /* Check if any element just below the diagonal isn't zero. */ zsl_mtx_get(&mout, g + 1, g, &sdiag); if ((sdiag >= epsilon) || (sdiag <= -epsilon)) { /* Skip two elements if the element below * is not zero. */ g++; } else { /* Get the diagonal element if the element below * is zero. */ zsl_mtx_get(&mout, g, g, &diag); v->data[real] = diag; real++; } } /* Since it's not possible to check the coefficient below the last * diagonal element, then check the element to its left. */ zsl_mtx_get(&mout, (m->sz_rows - 1), (m->sz_rows - 2), &sdiag); if ((sdiag >= epsilon) || (sdiag <= -epsilon)) { /* Do nothing if the element to its left is not zero. */ } else { /* Get the last diagonal element if the element to its left * is zero. */ zsl_mtx_get(&mout, (m->sz_rows - 1), (m->sz_rows - 1), &diag); v->data[real] = diag; real++; } /* If the number of real eigenvalues ('real' coefficient) is less than * the matrix dimensions, then there must be complex eigenvalues. */ v->sz = real; if (real != m->sz_rows) { return -ECOMPLEXVAL; } /* Put the zeros to the end. */ zsl_vec_zte(v); return 0; } #endif #ifndef CONFIG_ZSL_SINGLE_PRECISION int zsl_mtx_eigenvectors(struct zsl_mtx *m, struct zsl_mtx *mev, size_t iter, bool orthonormal) { size_t b = 0; /* Total number of eigenvectors. */ size_t e_vals = 0; /* Number of unique eigenvalues. */ size_t count = 0; /* Number of eigenvectors for an eigenvalue. */ size_t ga = 0; zsl_real_t epsilon = 1E-6; zsl_real_t x; /* The vector where all eigenvalues will be stored. */ ZSL_VECTOR_DEF(k, m->sz_rows); /* Temp vector to store column data. */ ZSL_VECTOR_DEF(f, m->sz_rows); /* The vector where all UNIQUE eigenvalues will be stored. */ ZSL_VECTOR_DEF(o, m->sz_rows); /* Temporary mxm identity matrix placeholder. */ ZSL_MATRIX_DEF(id, m->sz_rows, m->sz_rows); /* 'm' minus the eigenvalues * the identity matrix (id). */ ZSL_MATRIX_DEF(mi, m->sz_rows, m->sz_rows); /* Placeholder for zsl_mtx_gauss_reduc calls (required param). */ ZSL_MATRIX_DEF(mid, m->sz_rows, m->sz_rows); /* Matrix containing all column eigenvectors for an eigenvalue. */ ZSL_MATRIX_DEF(evec, m->sz_rows, m->sz_rows); /* Matrix containing all column eigenvectors for an eigenvalue. * Two matrices are required for the Gramm-Schmidt operation. */ ZSL_MATRIX_DEF(evec2, m->sz_rows, m->sz_rows); /* Matrix containing all column eigenvectors. */ ZSL_MATRIX_DEF(mev2, m->sz_rows, m->sz_rows); /* TODO: Check that we have a SQUARE matrix, etc. */ zsl_mtx_init(&mev2, NULL); zsl_vec_init(&o); zsl_mtx_eigenvalues(m, &k, iter); /* Copy every non-zero eigenvalue ONCE in the 'o' vector to get rid of * repeated values. */ for (size_t q = 0; q < m->sz_rows; q++) { if ((k.data[q] >= epsilon) || (k.data[q] <= -epsilon)) { if (zsl_vec_contains(&o, k.data[q], epsilon) == 0) { o.data[e_vals] = k.data[q]; /* Increment the unique eigenvalue counter. */ e_vals++; } } } /* If zero is also an eigenvalue, copy it once in 'o'. */ if (zsl_vec_contains(&k, 0.0, epsilon) > 0) { e_vals++; } /* Calculates the null space of 'm' minus each eigenvalue times * the identity matrix by performing the gaussian reduction. */ for (size_t g = 0; g < e_vals; g++) { count = 0; ga = 0; zsl_mtx_init(&id, zsl_mtx_entry_fn_identity); zsl_mtx_scalar_mult_d(&id, -o.data[g]); zsl_mtx_add_d(&id, m); zsl_mtx_gauss_reduc(&id, &mid, &mi); /* If 'orthonormal' is true, perform the following process. */ if (orthonormal == true) { /* Count how many eigenvectors ('count' coefficient) * there are for each eigenvalue. */ for (size_t h = 0; h < m->sz_rows; h++) { zsl_mtx_get(&mi, h, h, &x); if ((x >= 0.0 && x < epsilon) || (x <= 0.0 && x > -epsilon)) { count++; } } /* Resize evec* placeholders to have 'count' cols. */ evec.sz_cols = count; evec2.sz_cols = count; /* Get all the eigenvectors for each eigenvalue and set * them as the columns of 'evec'. */ for (size_t h = 0; h < m->sz_rows; h++) { zsl_mtx_get(&mi, h, h, &x); if ((x >= 0.0 && x < epsilon) || (x <= 0.0 && x > -epsilon)) { zsl_mtx_set(&mi, h, h, -1); zsl_mtx_get_col(&mi, h, f.data); zsl_vec_neg(&f); zsl_mtx_set_col(&evec, ga, f.data); ga++; } } /* Orthonormalize the set of eigenvectors for each * eigenvalue using the Gram-Schmidt process. */ zsl_mtx_gram_schmidt(&evec, &evec2); zsl_mtx_cols_norm(&evec2, &evec); /* Place these eigenvectors in the 'mev2' matrix, * that will hold all the eigenvectors for different * eigenvalues. */ for (size_t gi = 0; gi < count; gi++) { zsl_mtx_get_col(&evec, gi, f.data); zsl_mtx_set_col(&mev2, b, f.data); b++; } } else { /* Orthonormal is false. */ /* Get the eigenvectors for every eigenvalue and place * them in 'mev2'. */ for (size_t h = 0; h < m->sz_rows; h++) { zsl_mtx_get(&mi, h, h, &x); if ((x >= 0.0 && x < epsilon) || (x <= 0.0 && x > -epsilon)) { zsl_mtx_set(&mi, h, h, -1); zsl_mtx_get_col(&mi, h, f.data); zsl_vec_neg(&f); zsl_mtx_set_col(&mev2, b, f.data); b++; } } } } /* Since 'b' is the number of eigenvectors, reduce 'mev' (of size * m->sz_rows times b) to erase columns of zeros. */ mev->sz_cols = b; for (size_t s = 0; s < b; s++) { zsl_mtx_get_col(&mev2, s, f.data); zsl_mtx_set_col(mev, s, f.data); } /* Checks if the number of eigenvectors is the same as the shape of * the input matrix. If the number of eigenvectors is less than * the number of columns in the input matrix 'm', this will be * indicated by EEIGENSIZE as a return code. */ if (b != m->sz_cols) { return -EEIGENSIZE; } return 0; } #endif #ifndef CONFIG_ZSL_SINGLE_PRECISION int zsl_mtx_svd(struct zsl_mtx *m, struct zsl_mtx *u, struct zsl_mtx *e, struct zsl_mtx *v, size_t iter) { ZSL_MATRIX_DEF(aat, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(upri, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(ata, m->sz_cols, m->sz_cols); ZSL_MATRIX_DEF(at, m->sz_cols, m->sz_rows); ZSL_VECTOR_DEF(ui, m->sz_rows); ZSL_MATRIX_DEF(ui2, m->sz_cols, 1); ZSL_MATRIX_DEF(ui3, m->sz_rows, 1); ZSL_VECTOR_DEF(hu, m->sz_rows); zsl_real_t d; size_t pu = 0; size_t min = m->sz_cols; zsl_real_t epsilon = 1E-6; zsl_mtx_trans(m, &at); /* Calculate 'm' times 'm' transposed and viceversa. */ zsl_mtx_mult(m, &at, &aat); zsl_mtx_mult(&at, m, &ata); /* Set the value 'min' as the minimum of number of columns and number * of rows. */ if (m->sz_rows <= m->sz_cols) { min = m->sz_rows; } /* Calculate the eigenvalues of the square matrix 'm' times 'm' * transposed or the square matrix 'm' transposed times 'm', whichever * is smaller in dimensions. */ ZSL_VECTOR_DEF(ev, min); if (min < m->sz_cols) { zsl_mtx_eigenvalues(&aat, &ev, iter); } else { zsl_mtx_eigenvalues(&ata, &ev, iter); } /* Place the square root of these eigenvalues in the diagonal entries * of 'e', the sigma matrix. */ zsl_mtx_init(e, NULL); for (size_t g = 0; g < min; g++) { zsl_mtx_set(e, g, g, ZSL_SQRT(ev.data[g])); } /* Calculate the eigenvectors of 'm' times 'm' transposed and set them * as the columns of the 'v' matrix. */ zsl_mtx_eigenvectors(&ata, v, iter, true); for (size_t i = 0; i < min; i++) { zsl_mtx_get_col(v, i, ui.data); zsl_mtx_from_arr(&ui2, ui.data); zsl_mtx_get(e, i, i, &d); /* Calculate the column vectors of 'u' by dividing these * eniegnvectors by the square root its eigenvalue and * multiplying them by the input matrix. */ zsl_mtx_mult(m, &ui2, &ui3); if ((d >= 0.0 && d < epsilon) || (d <= 0.0 && d > -epsilon)) { pu++; } else { zsl_mtx_scalar_mult_d(&ui3, (1 / d)); zsl_vec_from_arr(&ui, ui3.data); zsl_mtx_set_col(u, i, ui.data); } } /* Expand the columns of 'u' into an orthonormal basis if there are * zero eigenvalues or if the number of columns in 'm' is less than the * number of rows. */ zsl_mtx_eigenvectors(&aat, &upri, iter, true); for (size_t f = min - pu; f < m->sz_rows; f++) { zsl_mtx_get_col(&upri, f, hu.data); zsl_mtx_set_col(u, f, hu.data); } return 0; } #endif #ifndef CONFIG_ZSL_SINGLE_PRECISION int zsl_mtx_pinv(struct zsl_mtx *m, struct zsl_mtx *pinv, size_t iter) { zsl_real_t x; size_t min = m->sz_cols; zsl_real_t epsilon = 1E-6; ZSL_MATRIX_DEF(u, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(e, m->sz_rows, m->sz_cols); ZSL_MATRIX_DEF(v, m->sz_cols, m->sz_cols); ZSL_MATRIX_DEF(et, m->sz_cols, m->sz_rows); ZSL_MATRIX_DEF(ut, m->sz_rows, m->sz_rows); ZSL_MATRIX_DEF(pas, m->sz_cols, m->sz_rows); /* Determine the SVD decomposition of 'm'. */ zsl_mtx_svd(m, &u, &e, &v, iter); /* Transpose the 'u' matrix. */ zsl_mtx_trans(&u, &ut); /* Set the value 'min' as the minimum of number of columns and number * of rows. */ if (m->sz_rows <= m->sz_cols) { min = m->sz_rows; } for (size_t g = 0; g < min; g++) { /* Invert the diagonal values in 'e'. If a value is zero, do * nothing to it. */ zsl_mtx_get(&e, g, g, &x); if ((x < epsilon) || (x > -epsilon)) { x = 1 / x; zsl_mtx_set(&e, g, g, x); } } /* Transpose the sigma matrix. */ zsl_mtx_trans(&e, &et); /* Multiply 'u' (transposed) times sigma (transposed and with inverted * eigenvalues) times 'v'. */ zsl_mtx_mult(&v, &et, &pas); zsl_mtx_mult(&pas, &ut, pinv); return 0; } #endif int zsl_mtx_min(struct zsl_mtx *m, zsl_real_t *x) { zsl_real_t min = m->data[0]; for (size_t i = 0; i < m->sz_cols * m->sz_rows; i++) { if (m->data[i] < min) { min = m->data[i]; } } *x = min; return 0; } int zsl_mtx_max(struct zsl_mtx *m, zsl_real_t *x) { zsl_real_t max = m->data[0]; for (size_t i = 0; i < m->sz_cols * m->sz_rows; i++) { if (m->data[i] > max) { max = m->data[i]; } } *x = max; return 0; } int zsl_mtx_min_idx(struct zsl_mtx *m, size_t *i, size_t *j) { zsl_real_t min = m->data[0]; *i = 0; *j = 0; for (size_t _i = 0; _i < m->sz_rows; _i++) { for (size_t _j = 0; _j < m->sz_cols; _j++) { if (m->data[_i * m->sz_cols + _j] < min) { min = m->data[_i * m->sz_cols + _j]; *i = _i; *j = _j; } } } return 0; } int zsl_mtx_max_idx(struct zsl_mtx *m, size_t *i, size_t *j) { zsl_real_t max = m->data[0]; *i = 0; *j = 0; for (size_t _i = 0; _i < m->sz_rows; _i++) { for (size_t _j = 0; _j < m->sz_cols; _j++) { if (m->data[_i * m->sz_cols + _j] > max) { max = m->data[_i * m->sz_cols + _j]; *i = _i; *j = _j; } } } return 0; } bool zsl_mtx_is_equal(struct zsl_mtx *ma, struct zsl_mtx *mb) { int res; /* Make sure shape is the same. */ if ((ma->sz_rows != mb->sz_rows) || (ma->sz_cols != mb->sz_cols)) { return false; } res = memcmp(ma->data, mb->data, sizeof(zsl_real_t) * (ma->sz_rows + ma->sz_cols)); return res == 0 ? true : false; } bool zsl_mtx_is_notneg(struct zsl_mtx *m) { for (size_t i = 0; i < m->sz_rows * m->sz_cols; i++) { if (m->data[i] < 0.0) { return false; } } return true; } bool zsl_mtx_is_sym(struct zsl_mtx *m) { zsl_real_t x; zsl_real_t y; zsl_real_t diff; zsl_real_t epsilon = 1E-6; for (size_t i = 0; i < m->sz_rows; i++) { for (size_t j = 0; j < m->sz_cols; j++) { zsl_mtx_get(m, i, j, &x); zsl_mtx_get(m, j, i, &y); diff = x - y; if (diff >= epsilon || diff <= -epsilon) { return false; } } } return true; } int zsl_mtx_print(struct zsl_mtx *m) { int rc; zsl_real_t x; for (size_t i = 0; i < m->sz_rows; i++) { for (size_t j = 0; j < m->sz_cols; j++) { rc = zsl_mtx_get(m, i, j, &x); if (rc) { printf("Error reading (%zu,%zu)!\n", i, j); return -EINVAL; } /* Print the current floating-point value. */ printf("%f ", x); } printf("\n"); } printf("\n"); return 0; }
C
#include <scurl.h> #include <struct.h> // // url_encode - url 编码, 需要自己free // s : url串 // len : url串长度 // nlen : 返回编码后串长度 // return : 返回编码后串的首地址 // char * url_encode(const char * s, int len, int * nlen) { register uint8_t c; uint8_t * to, * st; const uint8_t * from, * end; DEBUG_CODE({ if (!s || !*s || len < 0) return NULL; }); from = (uint8_t *)s; end = (uint8_t *)s + len; st = to = (uint8_t *)calloc(3 * len + 1, sizeof(uint8_t)); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; continue; } // [a-z] [A-Z] [0-9] [&-./:=?_] 以外字符采用二进制替代 if ((c < '0' && c != '&' && c != '-' && c != '.' && c != '/') || (c < 'A' && c > '9' && c != ':' && c != '=' && c != '?') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = (uint8_t)"0123456789ABCDEF"[c >> 4]; to[2] = (uint8_t)"0123456789ABCDEF"[c & 15]; to += 3; continue; } *to++ = c; } *to = '\0'; // 返回结果 if (nlen) *nlen = to - st; return (char *)st; } // 2字节变成16进制数表示 inline static char _htoi(uint8_t * s) { int value, c; c = s[0]; // 小写变大写是兼容性写法 if (islower(c)) c = toupper(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10) * 16; c = s[1]; if (islower(c)) c = toupper(c); value += (c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10); return (char)value; } // // url_decode - url 解码,解码后也是放在s[]中 // s : 待解码的串 // len : 解码串长度 // return : 返回解码串的长度, < 0 表示失败 // int url_decode(char s[], int len) { char * dest, * data, c; DEBUG_CODE({ if (!s || !*s || len <= 0) return ErrParam; }); dest = data = s; while (len--) { c = *data++; // 反向解码 if (c == '+') *dest = ' '; else if (c == '%' && len >= 2 && isxdigit(data[0]) && isxdigit(data[1])) { *dest = _htoi((uint8_t *)data); data += 2; len -= 2; } else *dest = c; ++dest; } *dest = 0; return dest - s; }
C
/* * Implement strsep() but only use a single delimiter. * * char *strsepc(char **stringp, int c); */ #include <stdio.h> #include <assert.h> char * strsepc(char **stringp, int c) { char *orig = *stringp; char *s = *stringp; if (s == NULL) return (NULL); while (*s != '\0' && *s != c) { #if 0 printf("%c\n", *s); // debug print #endif s++; } /* * The pointer to the next character after the delimiter character (or * NULL, if the end of the string was reached) is stored in *stringp. */ if (*s != '\0') { *s = '\0'; *stringp = s + 1; } else { *stringp = NULL; } /* The original value of *stringp is returned. */ return (orig); } int main(int argc, char **argv) { char *orig, *new; assert(argc == 3); #if 1 new = argv[1]; #else /* This may crash the process based on what compiler you use. */ new = "foo,bar"; #endif while ((orig = strsepc(&new, argv[2][0])) != NULL) { printf("%s\n", orig); } }
C
#include<stdio.h> #include<string.h> int main() { char a[10],b[10]; printf("Enter the string"); scanf("%s",&a[10]); b[10]=strrev(a); printf("The reverse is %s",b[10]); }
C
// Copyright (C) 2015 Mars Saxman. All rights reserved. // Permission is granted to use at your own risk and distribute this software // in source and binary forms provided all source code distributions retain // this paragraph and the above copyright notice. THIS SOFTWARE IS PROVIDED "AS // IS" WITH NO EXPRESS OR IMPLIED WARRANTY. #include <stdlib.h> div_t div(int num, int den) { return (div_t){ num/den, num%den }; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> int react(char skip) { struct stat sb; int fd = open("day5.txt", O_RDONLY); fstat(fd, &sb); char *buf = mmap(NULL, sb.st_size, PROT_WRITE, MAP_PRIVATE, fd, 0); int pos = -1; for (int i = 0; i < sb.st_size; i++) { char c = buf[i]; if (skip && (c == skip || c - 32 == skip)) { continue; } if (pos >= 0 && (buf[pos] == (c ^ ' '))) { pos--; } else { pos++; buf[pos] = c; } } buf[pos] = 0; munmap(buf, sb.st_size); return pos; } int main() { int len = react(0); printf("length: %i\n", len); char min_s; int min = INT_MAX; for (char s = 'A'; s <= 'Z'; s++) { len = react(s); if (len < min) { min = len; min_s = s; } } printf("length when skipping %c: %i\n", min_s, min); }
C
#include <stdio.h> #include <stdlib.h> #include "scanner.h" #include "parser.h" #include "display.h" #include "stmt.h" #include "allocator.h" #include "interpreter.h" #include "preprocessor.h" static void p(const char* name, size_t size){ printf("\n%s : %lu bytes", name, size); } static void printSize(){ p("Expression", sizeof(Expression)); p("Statement", sizeof(Statement)); } int main(int argc, char **argv){ // printSize(); if(argc != 2) return 2; FILE *f = fopen(argv[1], "rb"); if(f == NULL){ printf(error("Unable to open file %s!"), argv[1]); return 1; } char *string = read_all(f); string = preprocess(string); // printf(debug("Final source : \n%s\n"), string); initScanner(string); TokenList *tokens = scanTokens(); if(hasScanErrors()){ printf(error("%d errors occured while scanning. Correct them and try to run again.\n"), hasScanErrors()); memfree_all(); return 1; } // printList(tokens); Code all = parse(tokens); if(hasParseError()){ printf(error("%d errors occured while parsing. Correct them and try to run again.\n"), hasParseError()); memfree_all(); return 1; } freeList(tokens); interpret(all); memfree_all(); printf("\n"); return 0; }
C
/** * Exercise 1-6 * * Verify that the expression * getchar() != EOF * is 0 to 1. */ #include <stdio.h> int main() { int c; printf("%d\n", getchar() != EOF); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int* shortestSeq(int* big, int bigSize, int* small, int smallSize, int* returnSize){ if (big == NULL || small == NULL) { *returnSize = 0; return NULL; } int* res = (int*)malloc(sizeof(int) * 2); memset(res, 0, sizeof(int) * 2); int hash[100001] = {0}; for (int i = 0; i < smallSize; i++) { hash[small[i]]++; } int left = 0; int right = 0; int match = 0; int minLength = INT_MAX; while (right < bigSize) { if (hash[big[right]] == 1) { match++; } while (match == smallSize) { // 首次找全了。 minLength = (right - left + 1) < minLength ? (right - left + 1) : minLength; printf("right=%d, left=%d\n", right, left); while (left < right) { if (hash[big[left]] == 1) { match--; left++; break; } left++; } } right++; } printf("\nmin=%d\n", minLength); *returnSize = 2; return res; } int main(void) { int big[] = {7,5,9,0,2,1,3,5,7,9,1,1,5,8,8,9,7}; int small[] = {1,5,9}; int returnSize = 0; shortestSeq(big, sizeof(big) / sizeof(big[0]), small, sizeof(small) / sizeof(small[0]), &returnSize); system("pause"); }
C
// challenge 3 #include "KDB-Files.c" #include "md5.c" int main(int argc, const char *argv[]){ unsigned char jpgBuf[4], temp[2], magicStart[4]; unsigned char standard[4] = {0xFF, 0xD8, 0xFF, 0xe0}; unsigned char jpegEnd[2] = {0xFF, 0xD9}; long offset, inputSize; int fileSize = 0, endCheck = 0; // call readKdb to get magic bytes from given file. unsigned char *readResult = readKDB(argv[1], 1); int i; for (i = 0; i < 3; i++) { magicStart[i] = *(readResult + i); } magicStart[3] = 0xe0; // standard jpeg start FILE *fp = fopen(argv[2], "rb"); char *dirName = strcat(argv[2], "_Repaired"); mkdir(dirName); chdir(dirName); fseek(fp, 0, SEEK_END); inputSize = ftell(fp); fseek(fp, 0, SEEK_SET); while(ftell(fp) < inputSize){ fread(&jpgBuf, 1, sizeof(jpgBuf), fp); if (memcmp(magicStart, jpgBuf, 4) == 0){ // save the offset where the byte pattern was found offset = ftell(fp); offset -= 4; char fileName[20]; sprintf(fileName, "%x.jpeg", offset); FILE *fp1 = fopen(fileName, "wb"); fwrite(standard, 1, sizeof(standard), fp1); fread(&temp, 1, sizeof(temp), fp); while (endCheck != 1){ if (memcmp(temp, jpegEnd, 2) == 0){ fwrite(temp, 1, 2, fp1); endCheck = 1; } else{ fwrite(temp, 1, 2, fp1); fread(&temp, 1, sizeof(temp), fp); } } fileSize = ftell(fp) - offset; fclose(fp1); unsigned char data[fileSize - 1]; fp1 = fopen(fileName, "rb"); // read for to string for hash int num = fread(&data, 1, fileSize - 1, fp1); fclose(fp1); unsigned *hash = md5(data, num); WBunion u; int reset = ftell(fp) % 16; fseek(fp, fileSize + offset - reset, SEEK_SET); endCheck = 0; printf("File: %s\n", fileName); printf("Offset found: %x\n", offset); printf("File Size: %d Bytes\n", fileSize); printf("File Path from current directory : %s/%s\n", dirName, fileName); printf("MD5 Hash: "); int i,j; printf("= 0x"); for (i=0;i<4; i++){ u.w = hash[i]; for (j=0;j<4;j++) printf("%02x",u.b[j]); } printf("\n"); printf("\n"); printf("End of File Data\n"); printf("\n\n"); } } fclose(fp); return 0; }
C
/* * Copyright (C) 2021 William Manley <[email protected]> * * Fault injection system * ====================== * * This allows us to inject faults into pulsevideo to deterministically create * failures at various points in the system. It's controlled by environment * variables. So if I set: * * fdpay_buffer="skip skip usleep=1000000 skip abort" pulsevideo ... * * The video stream will pause for 1s on the 3rd buffer and abort on the 4th * one. * * The commands are: * * * `usleep=<usecs>` - sleep for `<usecs>` microseconds. Note: unlike with * the other commands, after the sleep the next command will be executed. * * `skip` - don't inject a fault on this invocation * * `gerror` - return an error * * `abort` - crash with SIGABRT * * The injection points are: * * * `pre_attach` - called in the handler for the incoming DBus request before * returning the value to the client. This happens after the socket has * been created and been added to the `multisocketsink`. * * `fdpay_buffer` - called in the streaming thread for every buffer to be * sent. */ #ifndef __FAULT_H__ #define __FAULT_H__ #include <glib.h> #include <err.h> #include <stdlib.h> #include <string.h> #ifdef ENABLE_FAULT_INJECTION static const gboolean FAULT_INJECTION = 1; #else static const gboolean FAULT_INJECTION = 0; #endif struct FaultInjectionPoint { const char * const name; GMutex mutex; char *cmds; }; #define FAULT_INJECTION_POINT(name) {name, {0}, NULL} static gboolean inject_fault (struct FaultInjectionPoint* p, GError **err) { if (!FAULT_INJECTION) return TRUE; gboolean res = TRUE; g_mutex_lock (&p->mutex); if (!p->cmds) { const gchar *e = g_getenv (p->name); p->cmds = g_strdup (e ? e : ""); } while (p->cmds[0] != '\0') { if (p->cmds[0] == ' ') p->cmds++; else if (memcmp ("usleep=", p->cmds, 7) == 0) { p->cmds += 7; int duration_us = strtol(p->cmds, &p->cmds, 10); warnx ("inject_fault %s: sleeping %i us", p->name, duration_us); g_mutex_unlock (&p->mutex); g_usleep(duration_us); g_mutex_lock (&p->mutex); } else if (memcmp ("gerror", p->cmds, 6) == 0) { p->cmds += 6; warnx ("inject_fault %s: return GError", p->name); g_set_error (err, G_FILE_ERROR, G_FILE_ERROR_NOENT, "Fault injected from %s", p->name); res = FALSE; break; } else if (memcmp ("abort", p->cmds, 5) == 0) { warnx ("inject_fault %s: aborting", p->name); raise(SIGABRT); } else if (memcmp ("skip", p->cmds, 4) == 0) { p->cmds += 4; /* This allows us to not error first time */ warnx ("inject_fault %s: skip", p->name); break; } else { warnx ("inject_fault %s: Ignoring invalid description: %s", p->name, p->cmds); p->cmds = ""; break; } } g_mutex_unlock (&p->mutex); return res; } #endif /* __FAULT_H__ */
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <signal.h> static void sighandler(int s) { kill(0, SIGQUIT); } static void sighandler2(int s) { printf("bye-bye\n"); exit(1); } int main(void) { pid_t pid; int i; signal(SIGALRM, sighandler); signal(SIGQUIT, sighandler2); for (i = 0; i < 5; i++) { pid = fork(); //if error if (pid == 0) { while (1) { printf("pid: %ld, ppid:%ld, pgid:%ld, sid:%ld\n",\ getpid(), getppid(), getpgrp(), getsid(0)); sleep(1); } exit(0); } } alarm(5); while (1); exit(0); }
C
#include <stdio.h> void function1() { printf("Hello from function1\n"); } int function2(int id,float score) { if(score > 50) { printf("ID = %d -> Pass\n",id); } printf("Hello from function2\n"); return(score); } char function3(char name[], int score, char sex) { char grade; if(score > 79) grade = 'S'; else grade = 'U'; printf("Hello from function3\n"); return(grade); } int getandprint() { FILE *inf,*out; int id,score,cnt=0; char name[25],sex; inf = fopen("student.txt","r"); out = fopen("report.txt","w"); fscanf(inf,"%d%s%d %c",&id,&name,&score,&sex); while(!feof(inf)) { fprintf(out,"id=%d,name=%s,score=%d,sex=%c\n",id,name,score,sex); cnt++; fscanf(inf,"%d%s%d %c",&id,&name,&score,&sex); } fprintf(out,"Total student = %d\n",cnt); fclose(inf); return(cnt); } void getandprint1(int *cnt) { FILE *inf,*out; int id,score; char name[25],sex; inf = fopen("student.txt","r"); out = fopen("report.txt","w"); printf("Cnt = %d\n",*cnt); fscanf(inf,"%d%s%d %c",&id,&name,&score,&sex); while(!feof(inf)) { fprintf(out,"id=%d,name=%s,score=%d,sex=%c\n",id,name,score,sex); (*cnt)++; fscanf(inf,"%d%s%d %c",&id,&name,&score,&sex); } fprintf(out,"Total student = %d\n",*cnt); fclose(inf); } void getandprint2(int id[],char name[][25],int score[],char sex[],int *cnt) { FILE *inf,*out; inf = fopen("student.txt","r"); out = fopen("report.txt","w"); fscanf(inf,"%d%s%d %c",&id[*cnt],&name[*cnt],&score[*cnt],&sex[*cnt]); while(!feof(inf)) { fprintf(out,"id=%d,name=%s,score=%d,sex=%c\n",id[*cnt],name[*cnt],score[*cnt],sex[*cnt]); (*cnt)++; fscanf(inf,"%d%s%d %c",&id[*cnt],&name[*cnt],&score[*cnt],&sex[*cnt]); } fprintf(out,"Total student = %d\n",*cnt); fclose(inf); } int main() { int ans=0,i; char grade; FILE *out1; int id[10],score[10]; char name[10][25],sex[10]; out1 = fopen("list.txt","w"); /* printf("call function1\n"); function1(); printf("call function2\n"); ans = function2(1101,65.75); printf("call function3\n"); grade = function3("Sirinthorn",68,'f'); printf("Grade = %c\n",grade); printf("call getandprint\n"); //ans = getandprint(); getandprint1(&ans);*/ getandprint2(id,name,score,sex,&ans); printf("Total student = %d\n",ans); for(i=0; i<ans; i++) { fprintf(out1,"id=%d,name=%s,score=%d,sex=%c\n",id[i],name[i],score[i],sex[i]); } fprintf(out1,"Total student = %d\n",ans); return 0; }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #define PORT 6969 int main(int argc, char const *argv[]) { int sock = 0, readvalue; struct sockaddr_in serv_addr; char *msg = "Leave one Client alive and the Server are never safe. (Message from Client)"; char buffer[1024] = {0}; // Creating socket file descriptor if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) { printf("\nThe Client is no one.\n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed\n"); return -1; } send(sock , msg , strlen(msg) , 0 ); printf("The Client remembers! (Message from Client)\n"); readvalue = read( sock , buffer, 1024); printf("%s\n",buffer ); return 0; }
C
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <sys/random.h> #include <errno.h> #include "monocypher/monocypher.h" void _free(void* buf, int bufsize) { if (buf != NULL) { crypto_wipe(buf, bufsize); free(buf); } } int _fclose(FILE **fp) { int rv = fclose(*fp); *fp = NULL; return rv; } int _read(FILE* fp, uint8_t *buf, size_t bufsize) { return fread(buf, 1, bufsize, fp) == bufsize ? 0 : -1; } int _write(FILE* fp, const uint8_t *buf, size_t bufsize) { return (fwrite(buf, 1, bufsize, fp) == bufsize && errno == 0) ? 0 : -1; } int _random(uint8_t *buf, size_t bufsize) { return getrandom(buf, bufsize, 0) == -1 ? -1 : 0; }
C
// gcc -o leak-sensor-monitor leak-sensor-monitor.c -l bcm2835 // sudo chown root ./leak-sensor-monitor; sudo chmod +s ./leak-sensor-monitor // ./leak-sensor-monitor // to install bcm2835 see http://www.airspayce.com/mikem/bcm2835/ // you have to download the tarball and compile it locally // Inspired by a sample by Mike McCauley. #include <bcm2835.h> #include <stdio.h> // Connect the sensor's "ground" wire to pin GPIO12, and // sensor's the "live" wire to pin GPIO6. // The GPIO6 pin is driven to 3.3v as an output, and the // GPIO12 pin is pulled down. // The 3.3v rail could be used instead of an output pin // but with the minipitft taking up both 3.3v rail pins // it's just easier to use an output pin. // RPI_BPLUS_GPIO_J8_XX refers to pin XX on the pinout, not the "BCM" // number, nor the GPIO number. #define SENSOR1_PIN RPI_BPLUS_GPIO_J8_32 // GPIO12 (sensing pin) #define POWER1_PIN RPI_BPLUS_GPIO_J8_31 // GPIO6 (output 3.3v) #define SENSOR2_PIN RPI_BPLUS_GPIO_J8_36 // GPIO16 (sensing pin) #define POWER2_PIN RPI_BPLUS_GPIO_J8_35 // GPIO19 (output 3.3v) int main(int argc, char **argv) { setvbuf(stdout, NULL, _IONBF, 0); if (!bcm2835_init()) { printf("bcm2835 library initialization failure\n"); return 1; } // Configure sensor pin 1 to use a pull-down resistor. bcm2835_gpio_fsel(SENSOR1_PIN, BCM2835_GPIO_FSEL_INPT); bcm2835_gpio_set_pud(SENSOR1_PIN, BCM2835_GPIO_PUD_DOWN); // Configure sensor pin 2 to use a pull-down resistor. bcm2835_gpio_fsel(SENSOR2_PIN, BCM2835_GPIO_FSEL_INPT); bcm2835_gpio_set_pud(SENSOR2_PIN, BCM2835_GPIO_PUD_DOWN); // Sensor should be connected to 3.3v rail (not ground); // here we configure two pins to act as that rail. bcm2835_gpio_fsel(POWER1_PIN, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_set(POWER1_PIN); bcm2835_gpio_fsel(POWER2_PIN, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_set(POWER2_PIN); while (1) { uint8_t sensor1 = bcm2835_gpio_lev(SENSOR1_PIN); uint8_t sensor2 = bcm2835_gpio_lev(SENSOR2_PIN); uint8_t result = sensor1 | (sensor2 << 1); printf("%c", result); delay(100); } bcm2835_close(); return 0; }
C
void *real2(void *sth) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); int sit, a, b; while (!stop) // rand()함수는 실제로 랜덤하지 않으므로 시간있으면 다른함수로 { sit = rand() % 4; //case가 0이면 -- 1이면 -+ 2면 +- 3이면 ++ a = rand() % 10 + 1; b = rand() % 9 + 1; //시작층과 도착층이 같게하지 않기위함 swtich(sit) { case 0: if (comparisonforDS(a) == 1) { if (a <= b) { b++; addFirst(&nheadSP[a], a, b); } else addFirst(&nheadSM[a], a, b); } else { switch (miniDS(a)) { case 0: // 대기인 상태가 없다 if (a <= b) { b++; addFirst(&nheadSP[a], a, b); } else addFirst(&nheadSM[a], a, b); break; case 1: //D1 을 작동시킴! break; case 2: //D2 break; case 3: //A1 break; case 4: //A2 break; } } break; //걍 DS를 위한 함수 한번에 만들어야할듯? case 1: b += 10; addFirst(&nheadWP[a], a, b); break; case 2: a += 10; addFirst(&nheadWM[a], a, b); break; case 3: a += 10; b += 10; if (a <= b) { b++; addFirst(&nheadSP[a], a, b); } else addFirst(&nheadSM[a], a, b); break; } Sleep(100); } } void real() { int a, b; while (!stop) { a = rand() % 20 + 1; b = rand() % 19 + 1; //시작층과 도착층이 같게하지 않기위함 if (a <= b) //P의 조건 { b = b + 1; // 같지않게 if (a <= 10) { if (b <= 10) { if (comparsionforDS(a) != 0) addFirst(&nheadSP[a], a, b); else { switch (miniDS(a)) { case 0: // 대기인 상태가 없다 addFirst(&nheadSP[a], a, b); break; case 1: //D1 break; case 2: //D2 break; case 3: //A1 break; case 4: //A2 break; } } } else addFirst(&nheadWP[a], a, b); } else { if (b >= 11) addFirst(&nheadSP[a], a, b); else addFirst(&nheadWP[a], a, b); } } else { //M의 조건 if (a <= 10) { if (b <= 10) addFirst(&nheadSM[a], a, b); else addFirst(&nheadWM[a], a, b); } else { if (b >= 11) addFirst(&nheadSM[a], a, b); else addFirst(&nheadWM[a], a, b); } } Sleep(100); } } void *make(void *sth) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); int a, b; while (!stop) { int am, bm = 1; a = rand() % 20 + 1; b = rand() % 19 + 1; //시작층과 도착층이 같게하지 않기위함 if (a <= b) //P의 조건 { b = b + 1; // 같지않게 } if (a <= 10) am = -1; if (b <= 10) bm = -1; if (am * bm == 1) { if (a < b) addFirst(&nheadSP[a], a, b); else addFirst(&nheadSM[a], a, b); } else addFirst(&nheadW[a], a, b); Sleep(100); } } void *figureout(void *sth) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); int a, b; while (!stop) { a = rand() % 20 + 1; b = rand() % 19 + 1; //시작층과 도착층이 같게하지 않기위함 if (a <= b) //P의 조건 { b = b + 1; // 같지않게 } if (a <= 10 && b <= 10) { if (a < b) { if (comparsionforDS(a) != 0) addFirst(&nheadSP[a], a, b); else { switch (miniDS(a)) { case 0: // 대기인 상태가 없다 addFirst(&nheadSP[a], a, b); break; case 1: D1.state break; case 2: //D2 break; case 3: //A1 break; case 4: //A2 break; } } } else { if (comparsionforDS(a) != 0) addFirst(&nheadSM[a], a, b); else { switch (miniDS(a)) { case 0: // 대기인 상태가 없다 addFirst(&nheadSM[a], a, b); break; case 1: D1.state break; case 2: //D2 break; case 3: //A1 break; case 4: //A2 break; } } } if (comparsionforDS(a) != 0) { if (a < b) addFirst(&nheadSP[a], a, b); else addFirst(&nheadSM[a], a, b); } else { switch (miniDS(a)) { case 0: // 대기인 상태가 없다 if (a < b) addFirst(&nheadSP[a], a, b); else addFirst(&nheadSM[a], a, b); break; case 1: D1.state break; case 2: //D2 break; case 3: //A1 break; case 4: //A2 break; } } } else if (a >= 10 && b >= 10) { if (comparsionforUS(a) != 0) { if (a < b) addFirst(&nheadSP[a], a, b); else addFirst(&nheadSM[a], a, b); } else { switch (miniUS(a)) { case 0: // 대기인 상태가 없다 if (a < b) addFirst(&nheadSP[a], a, b); else addFirst(&nheadSM[a], a, b); break; case 1: //U1 break; case 2: //U2 break; case 3: //A1 break; case 4: //A2 break; } } } else { if (comparsionforA(a) != 0) addFirst(&nheadW[a], a, b); else { int ans = miniA(a); if (ans == 0) addFirst(&nheadW[a], a, b); else if (ans == 1) //A1 else //A2 } } Sleep(100); } } if (comparsionforDS(a) != 0) { if (a < b) addFirst(&nheadSP[a], a, b); else addFirst(&nheadSM[a], a, b); } else { switch (miniDS(a)) { case 0: // 대기인 상태가 없다 if (a < b) addFirst(&nheadSP[a], a, b); else addFirst(&nheadSM[a], a, b); break; case 1: D1.state break; case 2: //D2 break; case 3: //A1 break; case 4: //A2 break; } } } int main(void) { //각 원소마다 기준이될 층을 입력 /*for (int i = 1; i <= 20; i++) { nheadSP[i].start = i; nheadSM[i].start = i; nheadW[i].start = i; } */ //초기화 굳이? int sc; while (sc != -1) { system("clear"); printmenu(); scanf("%d", &sc); if (sc == 1) { system("clear"); printbuilding(); //뼈대 출력 pthread_create(&el, NULL, &elevatorD1, NULL); //엘레베이터 쓰레드 실행 X6 pthread_create(&fo, NULL, &figureout, NULL); //입력받는 쓰레드 실행 pthread_create(&printel, NULL, &printelevator, NULL); //6개의 엘레베이터 상황을 찍어주는 쓰레드 //pthread_create(&printing, NULL, &print, NULL); for (int i = 0; i < 50; i++) { pthread_cond_signal(&thread_cond); printf("%d", D1.nfloor); fflush(stdout); Sleep(100); } gotoxy(0, 44); fflush(stdout); system("clear"); stop = 1; pthread_cancel(el); printf("2"); pthread_cancel(printel); printf("3"); int rc = pthread_join(el, NULL); if (rc == 0) { printf("Completed join with thread1"); } else { printf("ERROR; return code from pthread_join()1"); return -1; } rc = pthread_join(printel, NULL); if (rc == 0) { printf("Completed join with thread2"); } else { printf("ERROR; return code from pthread_join()2"); return -1; } rc = pthread_join(fo, NULL); if (rc == 0) { printf("Completed join with thread2"); } else { printf("ERROR; return code from pthread_join()2"); return -1; } //pthread_cond_destroy(&thread_cond); fflush(stdout); Sleep(1000); } if (sc == 2) { //종료 } } stop = 1; // stop변수는 쓰레드 종료하려고 넣었음... 쓰레드에있는 while문을 while(1)로 돌리면 종료가 안되서.. 그냥 전역변수로 while문이 끝나게했음.. cancel로 종료가 안되요 ㅠㅠ return 0; } pthread_mutex_lock(&mutex_lock); pthread_cond_wait(&thread_cond, &mutex_lock); printf("\033[s"); gotoxy(4, 42 - 2 * D1.nfloor); printf("here"); gotoxy(15, 42 - 2 * D2.nfloor); printf("here"); gotoxy(26, 42 - 2 * U1.nfloor); printf("here"); gotoxy(37, 42 - 2 * U2.nfloor); printf("here"); gotoxy(48, 42 - 2 * A1.nfloor); printf("here"); gotoxy(59, 42 - 2 * A2.nfloor); printf("here"); printf("\033[u"); fflush(stdout); pthread_mutex_unlock(&mutex_lock); while (D1.state != 0) { for (int i = 0; i < get_len(&mystackD1[D1.nfloor]); i++) // 현재층 엘베 스택에서 값을 모두 내보냄 { NODE *temp = mystackD1[D1.nfloor].next; printf("출발 층이 %d 이고 도착 층이 %d인 사람이 내렸습니다", temp->start, temp->end); removeFirst(&mystackD1[D1.nfloor]); } if (D1.nfloor == D1.ofloor) { for (int i = D1.nfloor; i <= 5 + 5 * D1.state; i += D1.state) // 0층은 원래없음 { if ((D1.state == 1 && !isEmpty(&nheadSP[i])) || (D1.state == -1 && !isEmpty(&nheadSM[i]))) D1.ofloor = i; } D1.state = 0; // 대기상태로 만든다 break; } for (int i = 0; i < get_len(&nheadSP[D1.nfloor]); i++) // 현재층 스택에서 값을 모두 불러온다 { NODE *temp = popfromin(&nheadSP[D1.nfloor]); addNode(&mystackD1[temp->end], temp); if ((temp->end - D1.ofloor) * D1.state > 0) // 목적지를 초과하는 목적입력이 들어오면 { D1.ofloor = temp->end; // 목적지를 변경함 } } D1.nfloor = D1.nfloor + D1.state; // ++or -- Sleep(1000); } if (D1.state != 0) { int dothis = 1; while (dothis) //while (D1.nfloor != D1.ofloor) { for (int i = 0; i < get_len(&nheadSP[D1.nfloor]); i++) { NODE *temp = popfromin(&nheadSP[D1.nfloor]); addNode(&mystackD1[temp->end], temp); if ((temp->end - D1.ofloor) * D1.state > 0) // 목적지를 초과하는 목적입력이 들어오면 { D1.ofloor = temp->end; // 목적지를 변경함 } } for (int i = 0; i < get_len(&mystackD1[D1.nfloor]); i++) { NODE *temp = mystackD1[D1.nfloor].next; printf("출발 층이 %d 이고 도착 층이 %d인 사람이 내렸습니다", temp->start, temp->end); removeFirst(&mystackD1[D1.nfloor]); } //현재층에 해당하는 입력들을 (목적지가 현재층인 입력들을) 모두 출력후 삭제 D1.nfloor = D1.nfloor + D1.state; if (D1.nfloor == D1.ofloor) { for (int i = D1.nfloor; i <= 5 + 5 * D1.state; i += D1.state) // 0층은 원래없음 { if ((D1.state == 1 && !isEmpty(&nheadSP[i])) || (D1.state == -1 && !isEmpty(&nheadSM[i]))) D1.ofloor = i; } dothis = 0; // 대기상태로 만든다 } Sleep(1000); } D1.state = 0; } while (D1.state != 0) { printf("정신차려\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); fflush(stdout); for (int i = 0; i < get_len(&mystackD1[D1.nfloor]); i++) // 현재층 엘베 스택에서 값을 모두 내보냄 { NODE *temp = mystackD1[D1.nfloor].next; printf("출발 층이 %d 이고 도착 층이 %d인 사람이 내렸습니다", temp->start, temp->end); removeFirst(&mystackD1[D1.nfloor]); } if (D1.nfloor == D1.ofloor) { for (int i = D1.nfloor; i <= 5 + 5 * D1.state; i += D1.state) // 0층은 원래없음 { if ((D1.state == 1 && !isEmpty(&nheadSP[i])) || (D1.state == -1 && !isEmpty(&nheadSM[i]))) D1.ofloor = i; } D1.state = 0; // 대기상태로 만든다 break; } for (int i = 0; i < get_len(&nheadSP[D1.nfloor]); i++) // 현재층 스택에서 값을 모두 불러온다 { NODE *temp = popfromin(&nheadSP[D1.nfloor]); addNode(&mystackD1[temp->end], temp); if ((temp->end - D1.ofloor) * D1.state > 0) // 목적지를 초과하는 목적입력이 들어오면 { D1.ofloor = temp->end; // 목적지를 변경함 } } D1.nfloor = D1.nfloor + D1.state; // ++or -- Sleep(1000); } printf("\033[s"); gotoxy(4, 42 - 2 * D1.nfloor); printf(" "); D1.nfloor = D1.nfloor + D1.state; // ++or -- gotoxy(4, 40 - 2 * D1.nfloor); marking(&D1); printf("\033[u"); fflush(stdout);
C
#include <stdlib.h> #include <stdint.h> #include <string.h> #include <errno.h> #include "libtlv.h" /** * 4BVARL uses simple 7-bit VARQ encoding of 28-bit data * where bit7 means more data following (28-bit = 4-byte) * to avoid 0xff as padding, 0x80 byte can be prepended * * DIG | HEX | SHORTEST | AVOID FF | * ----------|-----------|-------------|-------------| * 0 | 0x0000000 | 00 | 00 | * 127 | 0x000007F | 7F | 7F | * 128 | 0x0000100 | 81 00 | 81 00 | * 16255 | 0x0003F7F | FE 7F | FE 7F | * 16256 | 0x0003F80 | FF 00 | 80 FF 00 | * 16383 | 0x0003FFF | FF 7F | 80 FF 7F | * 16384 | 0x0004000 | 81 80 00 | 81 80 00 | * 2080767 | 0x01FBFFF | FE 7F 7F | FE 7F 7F | * 2080768 | 0x01FC000 | FF 80 80 | 80 FF 80 80 | * 2097151 | 0x01FFFFF | FF FF 7F | 80 FF FF 7F | * 2097152 | 0x0200000 | 81 80 80 00 | 81 80 80 00 | * 266338303 | 0xFDFFFFF | FE FF FF 7F | FE FF FF 7F | * 266338304 | 0xFE00000 | FF 80 80 00 | | * 268435455 | 0xFFFFFFF | FF FF FF 7F | | */ /** * LIBTLV_OPT_TSZMAX - get max value of type from opt * * Encoding | No padding | FF padding * -------------|------------|----------- * 1 byte | 0xFF | 0xFE * 2 bytes | 0xFFFF | 0xFEFF * 4 var byets | 0xFFFFFFF | 0xFDFFFFF * * @opt: LIBTLV_OPT_... * Return: max value allowed for type */ static inline unsigned int LIBTLV_OPT_TSZMAX(unsigned int opt) { unsigned int ret; switch (opt & LIBTLV_OPT_TSZMASK) { case 0: #if ENABLE_LIBTLV_PADDING_SUPPORT if (opt & LIBTLV_OPT_PADDING) ret = 0xFE; else #endif/*ENABLE_LIBTLV_PADDING_SUPPORT*/ ret = 0xFF; break; case LIBTLV_OPT_T2BYTES: #if ENABLE_LIBTLV_PADDING_SUPPORT if (opt & LIBTLV_OPT_PADDING) ret = 0xFEFF; else #endif/*ENABLE_LIBTLV_PADDING_SUPPORT*/ ret = 0xFFFF; break; #if ENABLE_LIBTLV_VARLEN_SUPPORT case LIBTLV_OPT_T4BVARL: #if ENABLE_LIBTLV_PADDING_SUPPORT if (opt & LIBTLV_OPT_PADDING) ret = 0xFDFFFFF; else #endif/*ENABLE_LIBTLV_PADDING_SUPPORT*/ ret = 0xFFFFFFF; break; #endif/*ENABLE_LIBTLV_VARLEN_SUPPORT*/ default: ret = 0; break; } return ret; } /** * LIBTLV_OPT_LZMAX - get max value of length from opt * * Encoding | No padding | FF padding * -------------|------------|----------- * 1 byte | 0xFF | 0xFF * 2 bytes | 0xFFFF | 0xFFFF * 4 var byets | 0xFFFFFFF | 0xFFFFFFF * * @opt: LIBTLV_OPT_... * Return: max value allowed for type */ static inline unsigned int LIBTLV_OPT_LSZMAX(unsigned int opt) { unsigned int ret; switch (opt & LIBTLV_OPT_LSZMASK) { case 0: ret = 0xFF; break; case LIBTLV_OPT_L2BYTES: ret = 0xFFFF; break; #if ENABLE_LIBTLV_VARLEN_SUPPORT case LIBTLV_OPT_L4BVARL: ret = (1U << 28) - 1; break; #endif/*ENABLE_LIBTLV_VARLEN_SUPPORT*/ default: ret = 0; break; } return ret; } /** * LIBTLV_OPT_GETTTLVSZ - get t,l,v size from opt, t, l * * @opt: LIBTLV_OPT_... * @t: type value * @l: length value * @tsz: [OUT] type encoded size * @lsz: [OUT] length encoded size * Return: encoded size for t,l,v */ static inline unsigned int LIBTLV_OPT_GETTLVSZ(unsigned int opt, unsigned int t, unsigned int l, unsigned int *tsz, unsigned int *lsz) { unsigned int ret = (opt & LIBTLV_OPT_PUT_NULLV) ? 0 : l; unsigned int len; switch (opt & LIBTLV_OPT_TSZMASK) { case 0: len = 1; break; case LIBTLV_OPT_T2BYTES: len = 2; break; #if ENABLE_LIBTLV_VARLEN_SUPPORT case LIBTLV_OPT_T4BVARL: if (opt & LIBTLV_OPT_PUT_MAXTL) /* reserve max size */ { len = 4; } else #if ENABLE_LIBTLV_PADDING_SUPPORT if (opt & LIBTLV_OPT_PADDING) /* avoid 0x7F|0x80 */ { if (t < (1U << 7)) /* 7 bits: 7F */ len = 1; else if (t < 0x3F80U) /* 14 bits: 3FFF */ len = 2; else if (t < 0x1FC000U) /* 21 bits: 1FFFFF */ len = 3; else /* < 0xFE00000U */ /* 28 bits: FFFFFFF */ len = 4; } else /* no padding */ #endif/*ENABLE_LIBTLV_PADDING_SUPPORT*/ { if (t < (1U << 7)) /* 7 bits: 7F */ len = 1; else if (t < (1U << 14)) /* 14 bits: 3FFF */ len = 2; else if (t < (1U << 21)) /* 21 bits: 1FFFFF */ len = 3; else /* < 0x10000000 */ /* 28 bits: FFFFFFF */ len = 4; } break; #endif/*ENABLE_LIBTLV_VARLEN_SUPPORT*/ default: len = 0; break; } if (tsz) { *tsz = len; } ret += len; switch (opt & LIBTLV_OPT_LSZMASK) { case 0: len = 1; break; case LIBTLV_OPT_L2BYTES: len = 2; break; #if ENABLE_LIBTLV_VARLEN_SUPPORT case LIBTLV_OPT_L4BVARL: if (opt & LIBTLV_OPT_PUT_MAXTL) /* reserve max size */ len = 4; else if (l < (1U << 7)) /* 7 bits: 7F */ len = 1; else if (l < (1U << 14)) /* 14 bits: 3FFF */ len = 2; else if (l < (1U << 21)) /* 21 bits: 1FFFFF */ len = 3; else /* < 0x10000000 */ /* 28 bits: FFFFFFF */ len = 4; break; #endif/*ENABLE_LIBTLV_VARLEN_SUPPORT*/ default: len = 0; break; } if (lsz) { *lsz = len; } ret += len; return ret; } /** * LIBTLV_OPT_GETALIGN - get alignment bytes from from opt, tsz, lsz, ptr * * @opt: LIBTLV_OPT_... * @tsz: type encoded size * @lsz: length encoded size * @ptr: start position * Return: number of bytes for alignment */ static inline unsigned int LIBTLV_OPT_GETALIGN(unsigned int opt, unsigned int tsz, unsigned int lsz, uintptr_t ptr) { #if ENABLE_LIBTLV_ALIGN_SUPPORT unsigned int ret = 0; unsigned int mask; mask = (opt & LIBTLV_OPT_ALNCNT) >> (__builtin_ffs(LIBTLV_OPT_ALNCNT)-1); if (mask == 0) { return 0; } mask = (1U << mask) - 1; switch (opt & LIBTLV_OPT_ALNSEL) { case LIBTLV_OPT_ALIGNT: break; case LIBTLV_OPT_ALIGNL: ptr += tsz; break; case LIBTLV_OPT_ALIGNV: ptr += tsz + lsz; break; default: return 0; } if (ptr & mask) { ret = (~ptr & mask) + 1; } return ret; #else /*ENABLE_LIBTLV_ALIGN_SUPPORT*/ return 0; #endif/*ENABLE_LIBTLV_ALIGN_SUPPORT*/ } /** * LIBTLV_OPT_GETTYPE - get next type assuming size > 0 * padding can be skipped here */ #if ENABLE_LIBTLV_PADDING_SUPPORT #define LIBTLV_OPT_GETTYPE_PADDING(_opt, _type, _ptr, _size, _nul, _end, _err) \ if (_opt & LIBTLV_OPT_PADDING) \ { \ while (*(uint8_t*)_ptr == 0xFF) \ { \ ++_ptr; \ if (--_size == 0) \ _end; \ } \ } #else /*ENABLE_LIBTLV_PADDING_SUPPORT*/ #define LIBTLV_OPT_GETTYPE_PADDING(_opt, _type, _ptr, _size, _nul, _end, _err) #endif/*ENABLE_LIBTLV_PADDING_SUPPORT*/ #if ENABLE_LIBTLV_VARLEN_SUPPORT #define LIBTLV_OPT_GETTYPE_VARLEN(_opt, _type, _ptr, _size, _nul, _end, _err) \ case LIBTLV_OPT_T4BVARL: \ /* byte 0 cannot be zero */ \ if ((_type = *(uint8_t*)_ptr)) \ { \ _type &= 0x7FU; \ ++_ptr; \ --_size; \ } \ else /* at end */ \ _nul; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) == 0) \ break; \ /* byte 1 */ \ if (_size == 0) \ _err; \ _type <<= 7; \ _type |= *(uint8_t*)_ptr++ & 0x7FU; --_size; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) == 0) \ break; \ /* byte 2 */ \ if (_size == 0) \ _err; \ _type <<= 7; \ _type |= *(uint8_t*)_ptr++ & 0x7FU; --_size; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) == 0) \ break; \ /* byte 3 */ \ if (_size == 0) \ _err; \ _type <<= 7; \ _type |= *(uint8_t*)_ptr++ & 0x7FU; --_size; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) != 0) \ _err; \ break; #else /*ENABLE_LIBTLV_VARLEN_SUPPORT*/ #define LIBTLV_OPT_GETTYPE_VARLEN(_opt, _type, _ptr, _size, _nul, _end, _err) #endif/*ENABLE_LIBTLV_VARLEN_SUPPORT*/ #define LIBTLV_OPT_GETTYPE(_opt, _type, _ptr, _size, _nul, _end, _err) \ LIBTLV_OPT_GETTYPE_PADDING(_opt, _type, _ptr, _size, _nul, _end, _err) \ switch (_opt & LIBTLV_OPT_TSZMASK) \ { \ case 0: \ if ((_type = *(uint8_t*)_ptr)) \ { \ ++_ptr; \ --_size; \ } \ else /* at end */ \ _nul; \ break; \ case LIBTLV_OPT_T2BYTES: \ if (_size < 2) \ _err; \ if ((_type = (((((uint16_t)(((uint8_t*)_ptr)[0]))) << 8) | \ ((uint8_t*)_ptr)[1]))) \ { \ _ptr += 2; \ _size -= 2; \ } \ else /* at end */ \ _nul; \ break; \ LIBTLV_OPT_GETTYPE_VARLEN(_opt, _type, _ptr, _size, _nul, _end, _err) \ } \ /** * LIBTLV_OPT_GETLENGTH - get next length assuming size > 0 */ #if ENABLE_LIBTLV_VARLEN_SUPPORT #define LIBTLV_OPT_GETLENGTH_VARLENG(_opt, _length, _ptr, _size, _err) \ case LIBTLV_OPT_L4BVARL: \ /* byte 0 */ \ _length = *(uint8_t*)_ptr++ & 0x7FU; --_size; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) == 0) \ break; \ /* byte 1 */ \ if (_size == 0) \ _err; \ _length <<= 7; \ _length |= *(uint8_t*)_ptr++ & 0x7FU; --_size; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) == 0) \ break; \ /* byte 2 */ \ if (_size == 0) \ _err; \ _length <<= 7; \ _length |= *(uint8_t*)_ptr++ & 0x7FU; --_size; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) == 0) \ break; \ /* byte 3 */ \ if (_size == 0) \ _err; \ _length <<= 7; \ _length |= *(uint8_t*)_ptr++ & 0x7FU; --_size; \ if ((((uint8_t*)_ptr)[-1] & 0x80U) != 0) \ _err; \ break; #else /*ENABLE_LIBTLV_VARLEN_SUPPORT*/ #define LIBTLV_OPT_GETLENGTH_VARLENG(_opt, _length, _ptr, _size, _err) #endif/*ENABLE_LIBTLV_VARLEN_SUPPORT*/ #define LIBTLV_OPT_GETLENGTH(_opt, _length, _ptr, _size, _err) \ switch (_opt & LIBTLV_OPT_LSZMASK) \ { \ case 0: \ _length = *(uint8_t*)_ptr++; \ --_size; \ break; \ case LIBTLV_OPT_L2BYTES: \ if (_size < 2) \ _err; \ _length = (((((uint16_t)((uint8_t*)_ptr)[0])) << 8) | \ ((uint8_t*)_ptr)[1]); \ _ptr += 2; \ _size -= 2; \ break; \ LIBTLV_OPT_GETLENGTH_VARLENG(_opt, _length, _ptr, _size, _err) \ } \ /** * libtlv_get - get tlv * * caller needs to check *t to see if it matches * tvl ends with single 0 (no length/value) * * @opt: options * @buf: tlv buffer * @size: buffer size * @t: [INOUT] null to find end, ->0 to find next, or ->type to match * @l: [INOUT] null to ignore length, ->0 for get ptr in v, otherwise->max of v, return actual length * @v: [OUT] null to ignore value, ptr to value if l->0, otherwise copy value (max *l) * Return: negative error or offset at end or after found tlv */ int libtlv_get(unsigned int opt, void *buf, size_t size, unsigned int *t, unsigned int *l, void *v) { int ret = size; int found = 0; unsigned int max = (l ? *l : 0); if (ret < 0) { return -E2BIG; } if (buf == NULL && size > 0) { return -EINVAL; } if (t && *t > LIBTLV_OPT_TSZMAX(opt)) { return -EINVAL; } if ((t == NULL) && (l != NULL || v != NULL)) { return -EINVAL; } if ((l == NULL) && (v != NULL)) { return -EINVAL; } while (size > 0) { void *ptr = buf; unsigned int type, length; LIBTLV_OPT_GETTYPE(opt, type, ptr, size, goto out, goto out, return -EFAULT) if (size == 0) { return -EFAULT; } LIBTLV_OPT_GETLENGTH(opt, length, ptr, size, return -EFAULT) if (size < length) { return -EFAULT; } size -= length; buf = ptr + length; if (t == NULL) /* seek eof */ { continue; } if (*t == 0 || *t == type) { if (*t == 0) { *t = type; /* next */ } if (l) { *l = length; if (v) { if (max == 0) { if (length == 0) ptr = NULL; if (((unsigned long)v) & (__alignof__(void*)-1)) memcpy(v, &ptr, sizeof(void*)); else *(void**)v = ptr; } else if (length) { memcpy(v, ptr, length > max ? max : length); } } } if (opt & LIBTLV_OPT_GET_LAST) { found = 1; continue; } return ret - size; } } out: if (!found && t) { *t = 0; } return ret - size; } /** * libtlv_put - put tlv * * @opt: options * @buf: tlv buffer * @size: buffer size * @t: type * @l: length * @v: value * Return: negative error or offset at end or after put tlv */ int libtlv_put(unsigned int opt, void *buf, size_t size, unsigned int t, unsigned int l, void *v) { int ret = size; if (ret < 0) { return -E2BIG; } if (buf == NULL && size > 0) { return -EINVAL; } if (t > LIBTLV_OPT_TSZMAX(opt) || l > LIBTLV_OPT_LSZMAX(opt)) { return -EINVAL; } if (t && l && !v && !(opt & LIBTLV_OPT_PUT_NULLV)) { return -EINVAL; } while (size > 0) { void *ptr = buf; unsigned int type, length; LIBTLV_OPT_GETTYPE(opt, type, ptr, size, break, return -ENOSPC, return -EFAULT) if (size == 0) { return -EFAULT; } if (type == 0) { if (t) { #if ENABLE_LIBTLV_ALIGN_SUPPORT unsigned int pad, tsz, lsz; unsigned int sz = LIBTLV_OPT_GETTLVSZ(opt, t, l, &tsz, &lsz); if (size < sz) return -ENOSPC; pad = LIBTLV_OPT_GETALIGN(opt, tsz, lsz, (uintptr_t)ptr); if (pad > 0) { if (size < pad+sz) return -ENOSPC; memset(ptr, (opt & LIBTLV_OPT_PUT_CLRTL) ? 0 : 0xff, pad); ptr += pad; sz += pad; } #else /*ENABLE_LIBTLV_ALIGN_SUPPORT*/ unsigned int sz = LIBTLV_OPT_GETTLVSZ(opt, t, l, NULL, NULL); if (size < sz) return -ENOSPC; #endif/*ENABLE_LIBTLV_ALIGN_SUPPORT*/ if (opt & LIBTLV_OPT_PUT_CLRTL) { if (opt & LIBTLV_OPT_PUT_NULLV) { memset(ptr, 0, sz); ptr += sz; } else /* sz includes l */ { memset(ptr, 0, sz-l); ptr += sz-l; } goto put_value; } /* put type */ switch (opt & LIBTLV_OPT_TSZMASK) { case 0: *(uint8_t*)(ptr++) = t; break; case LIBTLV_OPT_T2BYTES: *(uint8_t*)(ptr++) = (t >> 8); *(uint8_t*)(ptr++) = (t & 0xFF); break; #if ENABLE_LIBTLV_VARLEN_SUPPORT case LIBTLV_OPT_T4BVARL: if (t < (1U << 7)) { if (opt & LIBTLV_OPT_PUT_MAXTL) /* use max size */ { *(uint8_t*)(ptr++) = 0x80; *(uint8_t*)(ptr++) = 0x80; *(uint8_t*)(ptr++) = 0x80; } *(uint8_t*)(ptr++) = t; } else if (t < (1U << 14)) { if (opt & LIBTLV_OPT_PUT_MAXTL) /* use max size */ { *(uint8_t*)(ptr++) = 0x80; *(uint8_t*)(ptr++) = 0x80; } *(uint8_t*)(ptr++) = ((t >> 7) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = (t & 0x7F); } else if (t < (1U << 21)) { if (opt & LIBTLV_OPT_PUT_MAXTL) /* use max size */ { *(uint8_t*)(ptr++) = 0x80; } *(uint8_t*)(ptr++) = ((t >> 14) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = ((t >> 7) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = (t & 0x7F); } else { *(uint8_t*)(ptr++) = ((t >> 21) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = ((t >> 14) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = ((t >> 7) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = (t & 0x7F); } break; #endif/*ENABLE_LIBTLV_PADDING_SUPPORT*/ } /* put length */ switch (opt & LIBTLV_OPT_LSZMASK) { case 0: *(uint8_t*)(ptr++) = l; break; case LIBTLV_OPT_L2BYTES: *(uint8_t*)(ptr++) = (l >> 8); *(uint8_t*)(ptr++) = (l & 0xFF); break; #if ENABLE_LIBTLV_VARLEN_SUPPORT case LIBTLV_OPT_L4BVARL: if (l < (1U << 7)) { if (opt & LIBTLV_OPT_PUT_MAXTL) /* use max size */ { *(uint8_t*)(ptr++) = 0x80; *(uint8_t*)(ptr++) = 0x80; *(uint8_t*)(ptr++) = 0x80; } *(uint8_t*)(ptr++) = l; } else if (l < (1U << 14)) { if (opt & LIBTLV_OPT_PUT_MAXTL) /* use max size */ { *(uint8_t*)(ptr++) = 0x80; *(uint8_t*)(ptr++) = 0x80; } *(uint8_t*)(ptr++) = ((l >> 7) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = (l & 0x7F); } else if (l < (1U << 21)) { if (opt & LIBTLV_OPT_PUT_MAXTL) /* use max size */ { *(uint8_t*)(ptr++) = 0x80; } *(uint8_t*)(ptr++) = ((l >> 14) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = ((l >> 7) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = (l & 0x7F); } else { *(uint8_t*)(ptr++) = ((l >> 21) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = ((l >> 14) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = ((l >> 7) & 0x7F) | 0x80; *(uint8_t*)(ptr++) = (l & 0x7F); } break; } #endif/*ENABLE_LIBTLV_PADDING_SUPPORT*/ /* put value */ put_value: if (!(opt & LIBTLV_OPT_PUT_NULLV) && l) { memcpy(ptr, v, l); } size -= sz; } return ret - size; } LIBTLV_OPT_GETLENGTH(opt, length, ptr, size, return -EFAULT) if (size < length) { return -EFAULT; } size -= length; buf = ptr + length; if ((type == t) && (opt & LIBTLV_OPT_PUT_ONCE)) { return -EEXIST; } } return -ENOSPC; } /* * Local Variables: * c-file-style: "stroustrup" * indent-tabs-mode: nil * End: * * vim: set ai cindent et sta sw=4: */
C
#include "mnist.h" #include <errno.h> #include <fcntl.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int mnist_train_label_info[LEN_LABEL_INFO]; int mnist_train_image_info[LEN_IMAGE_INFO]; int mnist_test_label_info[LEN_LABEL_INFO]; int mnist_test_image_info[LEN_IMAGE_INFO]; double mnist_count_label[10]; uint8_t mnist_train_label[NUM_MNIST_TRAIN][1]; uint8_t mnist_train_image[NUM_MNIST_TRAIN][SIZE_MNIST]; uint8_t mnist_test_label[NUM_MNIST_TEST][1]; uint8_t mnist_test_image[NUM_MNIST_TEST][SIZE_MNIST]; double mnist_train_label_mean[10][SIZE_MNIST]; double mnist_train_label_varience[10][SIZE_MNIST]; int is_little_endian() { uint16_t test = 0x0001; uint8_t *b = (uint8_t *) &test; return (*b) ? LITTLE_ENDIAN : BIG_ENDIAN; } void read_or_fail(int fd, void *usr_buf, size_t n) { if (rio_readn(fd, usr_buf, n) < 0) { perror("read"); fprintf(stderr, "read fail\n"); exit(EXIT_FAILURE); } } ssize_t rio_readn(int fd, void *usr_buf, size_t n) { size_t nleft = n; ssize_t nread; char *bufp = usr_buf; while (nleft > 0) { if ((nread = read(fd, bufp, nleft)) < 0) { if (errno == EINTR) /* interrupted by sig handler return */ nread = 0; /* and call read() again */ else return -1; /* errno set by read() */ } else if (nread == 0) break; /* EOF */ nleft -= nread; bufp += nread; } return (n - nleft); /* return >= 0 */ } int open_or_fail(char *path, int flag) { int fd; if ((fd = open(path, flag)) == -1) { perror("open"); fprintf(stderr, "Could open %s\n", path); exit(EXIT_FAILURE); } return fd; } void swap(uint8_t *b1, uint8_t *b2) { *b1 ^= *b2; *b2 ^= *b1; *b1 ^= *b2; } void swap_bytes(uint8_t *ptr, size_t len) { for (int i = 0; i < len / 2; i++) swap(ptr + i, ptr + len - 1 - i); } void statistic_mnist_train_data() { /*get mean*/ for (int i = 0; i < NUM_MNIST_TRAIN; i++) { int label = mnist_train_label[i][0]; for (int j = 0; j < SIZE_MNIST; j++) { mnist_train_label_mean[label][j] += mnist_train_image[i][j]; } mnist_count_label[label]++; } for (int i = 0; i < 10; i++) for (int j = 0; j < SIZE_MNIST; j++) mnist_train_label_mean[i][j] /= mnist_count_label[i]; /*get varience*/ for (int i = 0; i < NUM_MNIST_TRAIN; i++) { int label = mnist_train_label[i][0]; for (int j = 0; j < SIZE_MNIST; j++) { mnist_train_label_varience[label][j] += pow( mnist_train_image[i][j] - mnist_train_label_mean[label][j], 2); } } for (int i = 0; i < 10; i++) for (int j = 0; j < SIZE_MNIST; j++) { mnist_train_label_varience[i][j] = sqrt(mnist_train_label_varience[i][j] / mnist_count_label[i]); } } void read_mnist(char *path, int len_info, int data_info[], int num_data, int size, uint8_t data[][size]) { int fd; uint8_t *ptr; fd = open_or_fail(path, O_RDONLY); read_or_fail(fd, data_info, len_info * sizeof(int)); if (is_little_endian()) for (int i = 0; i < len_info; i++) { ptr = (uint8_t *) (data_info + i); swap_bytes(ptr, sizeof(int)); ptr += sizeof(int); } for (int i = 0; i < num_data; i++) { read_or_fail(fd, data[i], size * sizeof(uint8_t)); } close(fd); } int get_MNIST_train_size() { return SIZE_MNIST; } void load_mnist() { read_mnist(PATH_MNISTTRAIN_LABEL, LEN_LABEL_INFO, mnist_train_label_info, NUM_MNIST_TRAIN, 1, mnist_train_label); read_mnist(PATH_MNISTTRAIN_IMAGE, LEN_IMAGE_INFO, mnist_train_image_info, NUM_MNIST_TRAIN, SIZE_MNIST, mnist_train_image); read_mnist(PATH_MNISTTEST_LABEL, LEN_LABEL_INFO, mnist_test_label_info, NUM_MNIST_TEST, 1, mnist_test_label); read_mnist(PATH_MNISTTEST_IMAGE, LEN_IMAGE_INFO, mnist_test_image_info, NUM_MNIST_TEST, SIZE_MNIST, mnist_test_image); statistic_mnist_train_data(); } mnist_info *get_mnist_info() { mnist_info *info = malloc(sizeof(mnist_info)); info->train_size = NUM_MNIST_TRAIN; info->test_size = NUM_MNIST_TEST; info->label_class_size = 10; info->image_size = 28 * 28; return info; } mnist_data *get_mnist_data() { mnist_data *data = malloc(sizeof(mnist_data)); data->train_image = (uint8_t **) malloc(NUM_MNIST_TRAIN * sizeof(uint8_t *)); for (int i = 0; i < NUM_MNIST_TRAIN; i++) data->train_image[i] = (uint8_t *) malloc(SIZE_MNIST * sizeof(uint8_t)); data->train_label = (uint8_t *) malloc(NUM_MNIST_TRAIN * sizeof(uint8_t)); data->test_image = (uint8_t **) malloc(NUM_MNIST_TEST * sizeof(uint8_t *)); for (int i = 0; i < NUM_MNIST_TEST; i++) data->test_image[i] = (uint8_t *) malloc(SIZE_MNIST * sizeof(uint8_t)); data->test_label = (uint8_t *) malloc(NUM_MNIST_TEST * sizeof(uint8_t)); for (int i = 0; i < NUM_MNIST_TRAIN; i++) for (int j = 0; j < SIZE_MNIST; j++) data->train_image[i][j] = mnist_train_image[i][j]; for (int i = 0; i < NUM_MNIST_TRAIN; i++) data->train_label[i] = mnist_train_label[i][0]; for (int i = 0; i < NUM_MNIST_TEST; i++) for (int j = 0; j < SIZE_MNIST; j++) data->test_image[i][j] = mnist_test_image[i][j]; for (int i = 0; i < NUM_MNIST_TEST; i++) data->test_label[i] = mnist_test_label[i][0]; return data; } void free_mnist_info(mnist_info *info) { free(info); } void free_mnist_data(mnist_data *data) { for (int i = 0; i < NUM_MNIST_TRAIN; i++) free(data->train_image[i]); for (int i = 0; i < NUM_MNIST_TEST; i++) free(data->test_image[i]); free(data->train_image); free(data->train_label); free(data->test_image); free(data->test_label); free(data); }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> int main(){ int sock0; struct sockaddr_in addr; struct sockaddr_in client; socklen_t len; int sock1,sock2; /* ソケットの作成 */ sock0 = socket(AF_INET, SOCK_STREAM, 0); /* ソケットの設定 */ addr.sin_family = AF_INET; addr.sin_port = htons(11111); addr.sin_addr.s_addr= INADDR_ANY; bind(sock0, (struct sockaddr *)&addr, sizeof(addr)); /* TCPクライアントからの接続要求を待てる状態にする */ listen(sock0, 5); /* TCPクライアントからの接続要求を受け付ける */ len = sizeof(client); sock1 = accept(sock0, (struct sockaddr *)&client, &len); /* 6文字送信('H', 'E', 'L', 'L', 'O', '\0') */ write(sock1, "HELLO", 6); /* TCPセッション1の終了 */ close(sock1); /* TCPクライアントからの接続要求を受け付ける */ len = sizeof(client); sock2 = accept(sock0, (struct sockaddr *)&client, &len); /* 5文字送信('H', 'O', 'G', 'E', '\0') */ write(sock2, "HOGE", 5); /* TCPセッション2の終了 */ close(sock2); /* lisentするsocketの終了 */ close(sock0); return 0; }
C
#include <stdio.h> #include <string.h> #define BUFHEIGHT 350 #define BUFWIDTH 50 #define ARRLENGTH(x) (sizeof(x)/sizeof((x)[0])) int num_trees(char chart[][BUFWIDTH], int h, int w, int vector[2]) { int x = 0; int y = 0; int trees = 0; for (int y = 0; y < h; y+=vector[1]) { char pos = chart[y][x]; if (pos == '#') { trees += 1; } x = (x + vector[0]) % w; } return trees; } int main(int argc, char **argv) { char chart[BUFHEIGHT][BUFWIDTH]; FILE *f = fopen("input.txt", "r"); int h = 0; int w = 0; for (int i = 0; fgets(chart[i], sizeof(chart[0]), f) && !feof(f); i++) { int line_length = strlen(chart[i]); if (chart[i][line_length - 1] == '\n') { chart[i][line_length - 1] = '\0'; } h++; } fclose(f); w = strlen(chart[0]); int vector[2] = {3,1}; printf("Step 1: %d\n", num_trees(chart, h, w, vector)); unsigned long long product = 1; int vectors[][2] = {{1, 1}, {3, 1}, {5, 1}, {7, 1}, {1, 2}}; for (int i = 0; i < ARRLENGTH(vectors); i++) { product *= num_trees(chart, h, w, vectors[i]); } printf("Step 2: %llu\n", product); return 0; }
C
#include"common.h" #include"genasm.h" void common_output(FILE* des) { fprintf(des , ".data\n"); vt_process(des); fprintf(des , "_prompt: .asciiz \"Enter an integer:\"\n"); fprintf(des , "_ret: .asciiz \"\\n\"\n"); fprintf(des , ".globl main\n"); fprintf(des , ".text\n"); fprintf(des , "read:\n"); fprintf(des , "\tli $v0, 4\n"); fprintf(des , "\tla $a0, _prompt\n"); fprintf(des , "\tsyscall\n"); fprintf(des , "\tli $v0, 5\n"); fprintf(des , "\tsyscall\n"); fprintf(des , "\tjr $ra\n"); fprintf(des , "\n"); fprintf(des , "write:\n"); fprintf(des , "\tli $v0, 1\n"); fprintf(des , "\tsyscall\n"); fprintf(des , "\tli $v0, 4\n"); fprintf(des , "\tla $a0, _ret\n"); fprintf(des , "\tsyscall\n"); fprintf(des , "\tmove $v0, $0\n"); fprintf(des , "\tjr $ra\n"); fprintf(des , "\n"); return; } void vt_process(FILE* des) { struct InterCodes* intercode_p = code_head; while(intercode_p->next != code_head) { intercode_p = intercode_p->next; switch(intercode_p->code.kind) { case ADD: case SUB: case MUL: case DIV: add_space_in_alop(intercode_p , des); break; case ADD_ASSIGN: case REF_ASSIGN: case ASSIGN_REF: case ASSIGN: add_space_in_assign(intercode_p , des); break; case CALLFUNC: add_space_in_call(intercode_p , des); break; case PARAM: add_space_in_param(intercode_p , des); break; case READ: add_space_in_read(intercode_p , des); break; case DEC: fprintf(des , "_v%d: .space %d\n" , intercode_p->code.u.dec.x->u.var_no , intercode_p->code.u.dec.size); } } } void add_space_in_alop(struct InterCodes* p , FILE* des) { Operand op = p->code.u.alop.x; switch(op->kind) { case VARIABLE: add_v(op , des); break; case TEMP: add_t(op , des); break; } } void add_space_in_assign(struct InterCodes* p , FILE* des) { Operand op = p->code.u.assignop.x; switch(op->kind) { case VARIABLE: add_v(op , des); break; case TEMP: add_t(op , des); break; } } void add_space_in_call(struct InterCodes* p , FILE* des) { Operand op = p->code.u.callfunc.x; switch(op->kind) { case VARIABLE: add_v(op , des); break; case TEMP: add_t(op , des); break; } } void add_space_in_param(struct InterCodes* p , FILE* des) { Operand op = p->code.u.param.x; switch(op->kind) { case VARIABLE: add_v(op , des); break; case TEMP: add_t(op , des); break; } } void add_space_in_read(struct InterCodes* p , FILE* des) { Operand op = p->code.u.read.x; switch(op->kind) { case VARIABLE: add_v(op , des); break; case TEMP: add_t(op , des); break; } } void add_v(Operand op , FILE* des) { struct vt_chain* p = v_chain_head; while(p->next != NULL) { p = p->next; if(p->op->kind == VARIABLE && op->kind == VARIABLE && p->op->u.var_no == op->u.var_no) return ; } fprintf(des , "_v%d: .space %d\n" , op->u.var_no , 4); p->next = (struct vt_chain*)malloc(sizeof(struct vt_chain)); p->next->op = op; p->next->next = NULL; return ; } void add_t(Operand op , FILE* des) { struct vt_chain* p = t_chain_head; while(p->next!= NULL) { p = p->next; if(p->op->kind == TEMP && op->kind == TEMP && p->op->u.var_no == op->u.var_no) return ; } fprintf(des , "_t%d: .space %d\n" , op->u.var_no , 4); p->next = (struct vt_chain*)malloc(sizeof(struct vt_chain)); p->next->op = op; p->next->next = NULL; return ; } void init_regfile() { int i = 0; for( ; i < 10 ; i++) reg_t[i].op = NULL; i = 0; for(; i < 9 ; i++) reg_s[i].op = NULL; i = 0; for(; i < 4 ; i++) reg_a[i].op = NULL; i = 0; for(; i < 2 ; i++) reg_v[i].op = NULL; } void init_vt_chain() { v_chain_head = (struct vt_chain*)malloc(sizeof(struct vt_chain)); v_chain_head->op = NULL; v_chain_head->next = NULL; t_chain_head = (struct vt_chain*)malloc(sizeof(struct vt_chain)); t_chain_head->op = NULL; t_chain_head->next = NULL; } void gen_asm(FILE* des) { init_regfile(); init_vt_chain(); common_output(des); param_cnt = 0; replace_num = 0; last_free = 0; read_addr_reg = 4; struct InterCodes* intercode_p = code_head; while(intercode_p->next != code_head) { intercode_p = intercode_p->next; switch(intercode_p->code.kind) { case LABEL: outasmlabel(intercode_p , des); break; case FUNCTION: outasmfunc(intercode_p , des); break; case ADD: outasmadd(intercode_p , des); break; case SUB: outasmsub(intercode_p , des); break; case MUL: outasmmul(intercode_p , des); break; case DIV: outasmdiv(intercode_p , des); break; case ADD_ASSIGN: case REF_ASSIGN: case ASSIGN_REF: case ASSIGN: outasmassign(intercode_p , des); break; case GOTO: outasmgoto(intercode_p , des); break; case RELOP_GOTO: outasmrelopgoto(intercode_p , des); break; case RETURN: outasmreturn(intercode_p , des); break; case DEC: outasmdec(intercode_p , des); break; case ARG: outasmarg(intercode_p , des); break; case CALLFUNC: outasmcallfunc(intercode_p , des); break; case PARAM: outasmparam(intercode_p , des); break; case READ: outasmread(intercode_p , des); break; case WRITE: outasmwrite(intercode_p , des); break; } } } void outasmlabel(struct InterCodes* p , FILE* des) { // store_reg(des); fprintf(des , "label%d:\n" , p->code.u.label.x->u.label_no); return; } void outasmfunc(struct InterCodes* p , FILE* des) { fprintf(des , "%s:\n" , p->code.u.function.f->u.func_name); int i = 0; for(; i < 9 ; i++) { if(reg_s[i].op != NULL) { Operand replaced_op = reg_s[i].op; fprintf(des , "\tla $t2, _"); if(replaced_op->kind == VARIABLE) fprintf(des , "v%d\n" , replaced_op->u.var_no); else if(replaced_op->kind == TEMP) fprintf(des , "t%d\n" , replaced_op->u.temp_no); fprintf(des , "\tsw $s%d, 0($t2)\n" , i); reg_s[i].op = NULL; } } return; } void outasmadd(struct InterCodes* p , FILE* des) { if(p->code.u.alop.y->kind == CONSTANT && p->code.u.alop.z->kind == CONSTANT) { int reg_num = get_reg(p->code.u.alop.x , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.y->u.value); fprintf(des , "\tli $t1, %d\n" , p->code.u.alop.z->u.value); fprintf(des , "\tadd "); if(reg_num < 10) fprintf(des , "$t%d" , reg_num); else fprintf(des , "$s%d" , reg_num - 10); fprintf(des , " $t0, $t1\n"); return; } else { if(p->code.u.alop.y->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.z , des); fprintf(des , "\taddi "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); fprintf(des , "%d\n" , p->code.u.alop.y->u.value); return; } else if(p->code.u.alop.z->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); fprintf(des , "\taddi "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); fprintf(des , "%d\n" , p->code.u.alop.z->u.value); return ; } else { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); int reg_num3 = get_reg(p->code.u.alop.z , des); fprintf(des , "\tadd "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); if(reg_num3 < 10) fprintf(des , "$t%d" , reg_num3); else fprintf(des , "$s%d" , reg_num3 - 10); fprintf(des , "\n"); return ; } } } void outasmsub(struct InterCodes* p , FILE* des) { if(p->code.u.alop.y->kind == CONSTANT && p->code.u.alop.z->kind == CONSTANT) { int reg_num = get_reg(p->code.u.alop.x , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.y->u.value); fprintf(des , "\tli $t1, %d\n" , p->code.u.alop.z->u.value); fprintf(des , "\tsub "); if(reg_num < 10) fprintf(des , "$t%d" , reg_num); else fprintf(des , "$s%d" , reg_num - 10); fprintf(des , " $t0, $t1\n"); return ; } else { if(p->code.u.alop.y->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.z , des); fprintf(des , "\taddi "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); fprintf(des , "-%d\n" , p->code.u.alop.y->u.value); return ; } else if(p->code.u.alop.z->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); fprintf(des , "\taddi "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); fprintf(des , "-%d\n" , p->code.u.alop.z->u.value); return ; } else { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); int reg_num3 = get_reg(p->code.u.alop.z , des); fprintf(des , "\tsub "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); if(reg_num3 < 10) fprintf(des , "$t%d" , reg_num3); else fprintf(des , "$s%d" , reg_num3 - 10); fprintf(des , "\n"); return ; } } } void outasmmul(struct InterCodes* p , FILE* des) { if(p->code.u.alop.y->kind == CONSTANT && p->code.u.alop.z->kind == CONSTANT) { int reg_num = get_reg(p->code.u.alop.x , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.y->u.value); fprintf(des , "\tli $t1, %d\n" , p->code.u.alop.z->u.value); fprintf(des , "\tmul "); if(reg_num < 10) fprintf(des , "$t%d" , reg_num); else fprintf(des , "$s%d" , reg_num - 10); fprintf(des , " $t0, $t1\n"); return ; } else { if(p->code.u.alop.y->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.z , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.y->u.value); fprintf(des , "\tmul "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); fprintf(des , "$t0, "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , "\n"); return ; } else if(p->code.u.alop.z->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.z->u.value); fprintf(des , "\tmul "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", $t0\n"); return ; } else { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); int reg_num3 = get_reg(p->code.u.alop.z , des); fprintf(des , "\tmul "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); if(reg_num3 < 10) fprintf(des , "$t%d" , reg_num3); else fprintf(des , "$s%d" , reg_num3 - 10); fprintf(des , "\n"); return ; } } } void outasmdiv(struct InterCodes* p , FILE* des) { if(p->code.u.alop.y->kind == CONSTANT && p->code.u.alop.z->kind == CONSTANT) { int reg_num = get_reg(p->code.u.alop.x , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.y->u.value); fprintf(des , "\tli $t1, %d\n" , p->code.u.alop.z->u.value); fprintf(des , "\tdiv $t0, $t1\n"); fprintf(des , "\tmflo "); if(reg_num < 10) fprintf(des , "$t%d" , reg_num); else fprintf(des , "$s%d" , reg_num - 10); fprintf(des , "\n"); return ; } else { if(p->code.u.alop.y->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.z , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.y->u.value); fprintf(des , "\tdiv "); fprintf(des , "$t0, "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , "\n\tmflo "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , "\n"); return ; } else if(p->code.u.alop.z->kind == CONSTANT) { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); fprintf(des , "\tli $t0, %d\n" , p->code.u.alop.z->u.value); fprintf(des , "\tdiv "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", $t0\n"); fprintf(des , "\tmflo "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , "\n"); return ; } else { int reg_num1 = get_reg(p->code.u.alop.x , des); int reg_num2 = get_reg(p->code.u.alop.y , des); int reg_num3 = get_reg(p->code.u.alop.z , des); fprintf(des , "\tdiv "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , ", "); if(reg_num3 < 10) fprintf(des , "$t%d" , reg_num3); else fprintf(des , "$s%d" , reg_num3 - 10); fprintf(des , "\n"); fprintf(des , "\tmflo "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , "\n"); return ; } } } void outasmassign(struct InterCodes* p , FILE* des) { if(p->code.u.assignop.y->kind == CONSTANT) { int reg_num = get_reg(p->code.u.assignop.x , des); fprintf(des , "\tli "); if(reg_num < 10) fprintf(des , "$t%d" , reg_num); else fprintf(des , "$s%d" , reg_num - 10); fprintf(des , ", %d\n" , p->code.u.assignop.y->u.value); return; } else if(p->code.u.assignop.y->kind == READ_ADDRESS) { Operand new_op = (Operand)malloc(sizeof(struct Operand_)); new_op->kind = TEMP; new_op->u.temp_no = p->code.u.assignop.y->u.temp_no; int reg_num1 = get_reg(p->code.u.assignop.x , des); int reg_num2= get_reg(new_op , des); fprintf(des , "\tlw "); if(reg_num1 < 10) fprintf(des , "$t%d, " , reg_num1); else fprintf(des , "$s%d, " , reg_num1 - 10); if(reg_num2 < 10) fprintf(des , "0($t%d)\n" , reg_num2); else fprintf(des , "0($s%d)\n" , reg_num2 - 10); return; } else if(p->code.u.assignop.x->kind == READ_ADDRESS) { Operand new_op = (Operand)malloc(sizeof(struct Operand_)); new_op->kind = TEMP; new_op->u.temp_no = p->code.u.assignop.x->u.temp_no; int reg_num2 = get_reg(p->code.u.assignop.y , des); int reg_num1= get_reg(new_op , des); fprintf(des , "\tsw "); if(reg_num2 < 10) fprintf(des , "$t%d, " , reg_num2); else fprintf(des , "$s%d, " , reg_num2 - 10); if(reg_num1 < 10) fprintf(des , "0($t%d)\n" , reg_num1); else fprintf(des , "0($s%d)\n" , reg_num1 - 10); return; } else { int reg_num1 = get_reg(p->code.u.assignop.x , des); int reg_num2 = get_reg(p->code.u.assignop.y , des); fprintf(des , "\tmove "); if(reg_num1 < 10) fprintf(des , "$t%d" , reg_num1); else fprintf(des , "$s%d" , reg_num1 - 10); fprintf(des , ", "); if(reg_num2 < 10) fprintf(des , "$t%d" , reg_num2); else fprintf(des , "$s%d" , reg_num2 - 10); fprintf(des , "\n"); return; } } void outasmgoto(struct InterCodes* p , FILE* des) { // store_reg(des); fprintf(des , "\tj label%d\n" , p->code.u.gotolabel.x->u.label_no); } void outasmrelopgoto(struct InterCodes* p , FILE* des) { if(p->code.u.relopgoto.x->kind == CONSTANT && p->code.u.relopgoto.y->kind == CONSTANT) { // store_reg(des); fprintf(des , "\tli $t0, %d\n" , p->code.u.relopgoto.x->u.value); fprintf(des , "\tli $t1, %d\n" , p->code.u.relopgoto.y->u.value); switch(p->code.u.relopgoto.relop->u.relop) { case 0: fprintf(des , "\tbgt ");break; case 1: fprintf(des , "\tblt ");break; case 2: fprintf(des , "\tbge ");break; case 3: fprintf(des , "\tble ");break; case 4: fprintf(des , "\tbeq ");break; case 5: fprintf(des , "\tbne ");break; } fprintf(des , "$t0, $t1, label%d\n" , p->code.u.relopgoto.z->u.label_no); return; } else { if(p->code.u.relopgoto.x->kind == CONSTANT) { int reg_num = get_reg(p->code.u.relopgoto.y , des); // store_reg(des); fprintf(des , "\tli $t0, %d\n" , p->code.u.relopgoto.x->u.value); switch(p->code.u.relopgoto.relop->u.relop) { case 0: fprintf(des , "\tbgt ");break; case 1: fprintf(des , "\tblt ");break; case 2: fprintf(des , "\tbge ");break; case 3: fprintf(des , "\tble ");break; case 4: fprintf(des , "\tbeq ");break; case 5: fprintf(des , "\tbne ");break; } if(reg_num < 10) fprintf(des , "$t0, $t%d" , reg_num); else fprintf(des , "$t0, $s%d" , reg_num - 10); fprintf(des , ", "); fprintf(des , "label%d\n" , p->code.u.relopgoto.z->u.label_no); return; } else if(p->code.u.relopgoto.y->kind == CONSTANT) { int reg_num = get_reg(p->code.u.relopgoto.x , des); // store_reg(des); fprintf(des , "\tli $t0, %d\n" , p->code.u.relopgoto.y->u.value); switch(p->code.u.relopgoto.relop->u.relop) { case 0: fprintf(des , "\tbgt ");break; case 1: fprintf(des , "\tblt ");break; case 2: fprintf(des , "\tbge ");break; case 3: fprintf(des , "\tble ");break; case 4: fprintf(des , "\tbeq ");break; case 5: fprintf(des , "\tbne ");break; } if(reg_num < 10) fprintf(des , "$t%d, $t0" , reg_num); else fprintf(des , "$s%d, $t0" , reg_num - 10); fprintf(des , ", "); fprintf(des , "label%d\n" , p->code.u.relopgoto.z->u.label_no); return ; } else { int reg_num1 = get_reg(p->code.u.relopgoto.x , des); int reg_num2 = get_reg(p->code.u.relopgoto.y , des); // store_reg(des); switch(p->code.u.relopgoto.relop->u.relop) { case 0: fprintf(des , "\tbgt ");break; case 1: fprintf(des , "\tblt ");break; case 2: fprintf(des , "\tbge ");break; case 3: fprintf(des , "\tble ");break; case 4: fprintf(des , "\tbeq ");break; case 5: fprintf(des , "\tbne ");break; } if(reg_num1 < 10) fprintf(des , "$t%d, " , reg_num1); else fprintf(des , "$s%d, " , reg_num1 - 10); if(reg_num2 < 10) fprintf(des , "$t%d, " , reg_num2); else fprintf(des , "$s%d, " , reg_num2 - 10); fprintf(des , "label%d\n" , p->code.u.relopgoto.z->u.label_no); return ; } } } void outasmdec(struct InterCodes* p , FILE* des) { return ; } void outasmreturn(struct InterCodes* p , FILE* des) { if(p->code.u.ret.x->kind == CONSTANT) { fprintf(des , "\tli $t1, %d\n" , p->code.u.ret.x->u.value); fprintf(des , "\tmove $v0, $t1\n"); } else { int reg_num = get_reg(p->code.u.ret.x , des); fprintf(des , "\tmove $v0, "); if(reg_num < 10) fprintf(des , "$t%d\n" , reg_num); else fprintf(des , "$s%d\n" , reg_num - 10); } fprintf(des, "\tjr $ra\n"); } void outasmarg(struct InterCodes* p , FILE* des) { int reg_num = get_reg(p->code.u.arg.x , des); fprintf(des , "\tmove $a%d, " , param_cnt); param_cnt++; if(reg_num < 10) fprintf(des , "$t%d\n" , reg_num); else fprintf(des , "$s%d\n" , reg_num - 10); return ; } void outasmcallfunc(struct InterCodes* p , FILE* des) { int reg_num = get_reg(p->code.u.callfunc.x , des); param_cnt = 0;//清空reg_a fprintf(des , "\taddi $sp, $sp, -4\n"); fprintf(des , "\tsw $ra, 0($sp)\n"); fprintf(des , "\tjal %s\n" , p->code.u.callfunc.f->u.func_name); fprintf(des , "\tlw $ra, 0($sp)\n"); fprintf(des , "\tmove "); if(reg_num < 10) fprintf(des , "$t%d, " , reg_num); else fprintf(des , "$s%d, " , reg_num - 10); fprintf(des , "$v0\n"); return ; } void outasmparam(struct InterCodes* p , FILE* des) { } void outasmread(struct InterCodes* p , FILE* des) { int reg_num = get_reg(p->code.u.read.x , des); fprintf(des , "\taddi $sp, $sp, -4\n"); fprintf(des , "\tsw $ra, 0($sp)\n"); fprintf(des , "\tjal read\n"); fprintf(des , "\tlw $ra, 0($sp)\n"); fprintf(des , "\tmove "); if(reg_num < 10) fprintf(des , "$t%d, " , reg_num); else fprintf(des , "$s%d, " , reg_num - 10); fprintf(des , "$v0\n"); } void outasmwrite(struct InterCodes* p , FILE* des) { int reg_num = get_reg(p->code.u.write.x , des); fprintf(des , "\tmove $a0, "); if(reg_num < 10) fprintf(des , "$t%d\n" , reg_num); else fprintf(des , "$s%d\n" , reg_num - 10); fprintf(des , "\taddi $sp, $sp, -4\n"); fprintf(des , "\tsw $ra, 0($sp)\n"); fprintf(des , "\tjal write\n"); fprintf(des , "\tlw $ra, 0($sp)\n"); return; } int get_reg(Operand op , FILE* des)//op可能是一个变量,临时变量或者地址或者要读取地址中的内容 { Operand new_op; if(op->kind == ADDRESS) { fprintf(des , "\tla $t2, _v%d\n" , op->u.var_no); return 2; } else if(op->kind == READ_ADDRESS) { new_op = (Operand)malloc(sizeof(struct Operand_)); new_op->kind = TEMP; new_op->u.temp_no = op->u.temp_no; } else new_op = op; int i = 0; int hit = -1; int free = -1; /* for(; i < 4 ; i++) { if(reg_a[i].op == NULL) continue; if(reg_a[i].op->kind == new_op->kind) { if(new_op->kind == VARIABLE && reg_t[i].op->u.var_no == new_op->u.var_no) { hit = i; break; } else if(new_op->kind == TEMP && reg_t[i].op->u.temp_no == new_op->u.temp_no) { hit = i; break; } } } if(hit != -1) return -hit;//因为结构体和数组不作为参数,所以可以直接返回 */ i = 5; hit = -1; for(; i < 10 ; i++) { if(reg_t[i].op == NULL) { if(free == -1) free = i; continue; } if(reg_t[i].op->kind == new_op->kind) { if(new_op->kind == VARIABLE && reg_t[i].op->u.var_no == new_op->u.var_no) { hit = i; break; } else if(new_op->kind == TEMP && reg_t[i].op->u.temp_no == new_op->u.temp_no) { hit = i; break; } } } if(hit != -1) goto here; else if(free != -1) { reg_t[free].op = new_op; goto here; } i = 0; hit = -1; free = -1; for(;i < 9 ; i++) { if(reg_s[i].op == NULL) { if(free == -1) free = i; continue; } if(reg_s[i].op->kind == new_op->kind) { if(new_op->kind == VARIABLE && reg_s[i].op->u.var_no == new_op->u.var_no) { hit = i; break; } else if(new_op->kind == TEMP && reg_s[i].op->u.temp_no == new_op->u.temp_no) { hit = i; break; } } } if(hit != -1) { hit += 10; goto here; } else if(free != -1) { reg_s[free].op = op; free += 10; goto here; } here: if(op->kind == VARIABLE) { if(hit != -1) { last_free = hit; return hit; } else if(free != -1) { last_free = free; return free; } else { replace_num = replace_num%14 + 5; if(last_free == replace_num) replace_num = (replace_num + 1)%14 + 5; if(replace_num < 10) { Operand replaced_op = reg_t[replace_num].op; fprintf(des , "\tla $t2, _"); if(replaced_op->kind == VARIABLE) fprintf(des , "v%d\n" , replaced_op->u.var_no); else if(replaced_op->kind == TEMP) fprintf(des , "t%d\n" , replaced_op->u.temp_no); fprintf(des , "\tsw $t%d, 0($t2)\n" , replace_num); reg_t[replace_num].op = new_op; return replace_num++; } else { Operand replaced_op = reg_s[replace_num - 10].op; fprintf(des , "\tla $t2, _"); if(replaced_op->kind == VARIABLE) fprintf(des , "v%d\n" , replaced_op->u.var_no); else if(replaced_op->kind == TEMP) fprintf(des , "t%d\n" , replaced_op->u.temp_no); fprintf(des , "\tsw $s%d, 0($t2)\n" , replace_num - 10); reg_s[replace_num-10].op = new_op; return replace_num++; } } } else if(op->kind == TEMP) { if(hit != -1) { last_free = hit; return hit; } else if(free != -1) { last_free = free; return free; } else { replace_num = replace_num%14 + 5; if(replace_num == last_free) replace_num = (replace_num + 1)%14 + 5; if(replace_num < 10) { Operand replaced_op = reg_t[replace_num].op; fprintf(des , "\tla $t2, _"); if(replaced_op->kind == VARIABLE) fprintf(des , "v%d\n" , replaced_op->u.var_no); else if(replaced_op->kind == TEMP) fprintf(des , "t%d\n" , replaced_op->u.temp_no); fprintf(des , "\tsw $t%d, 0($t2)\n" , replace_num); reg_t[replace_num].op = new_op; return replace_num++; } else { Operand replaced_op = reg_s[replace_num - 10].op; fprintf(des , "\tla $t2, _"); if(replaced_op->kind == VARIABLE) fprintf(des , "v%d\n" , replaced_op->u.var_no); else if(replaced_op->kind == TEMP) fprintf(des , "t%d\n" , replaced_op->u.temp_no); fprintf(des , "\tsw $s%d, 0($t2)\n" , replace_num - 10); reg_s[replace_num-10].op = new_op; return replace_num++; } } } else if(op->kind == READ_ADDRESS) { if(read_addr_reg == 4) read_addr_reg = 3; else read_addr_reg = 4; if(hit == -1) { fprintf(des , "\tla $t2, _t%d\n" , new_op->u.temp_no); fprintf(des , "\tlw $t%d, 0($t2)\n" , read_addr_reg); return read_addr_reg; } else { fprintf(des , "\tlw $t%d, " , read_addr_reg); if(hit < 10) fprintf(des , "0($t%d)\n" , hit); else fprintf(des , "0($s%d)\n" , hit - 10); return read_addr_reg; } } else { fprintf(stderr , "something unexcepted here %s %d\n" , __FILE__ , __LINE__); return 0; } } void store_reg(FILE* des) { int i = 5; for(;i < 10 ; i++) { if(reg_t[i].op != NULL) { if(reg_t[i].op->kind == VARIABLE) { fprintf(des , "\tla $t2, _v%d\n" , reg_t[i].op->u.var_no); fprintf(des , "\tsw $t%d, 0($t2)\n" , i); reg_t[i].op = NULL; } else { fprintf(des , "\tla $t2, _t%d\n" , reg_t[i].op->u.temp_no); fprintf(des , "\tsw $t%d, 0($t2)\n" , i); reg_t[i].op = NULL; } } } i = 0; for(; i < 9 ; i++) { if(reg_s[i].op != NULL) { if(reg_s[i].op->kind == VARIABLE) { fprintf(des , "\tla $t2, _v%d\n" , reg_s[i].op->u.var_no); fprintf(des , "\tsw $s%d, 0($t2)\n" , i); reg_s[i].op = NULL; } else { fprintf(des , "\tla $t2, _t%d\n" , reg_s[i].op->u.temp_no); fprintf(des , "\tsw $s%d, 0($t2)\n" , i); reg_s[i].op = NULL; } } } }
C
/* * Copyright 1994, 1995 University of Washington * All rights reserved. * See COPYRIGHT file for a full description * * HISTORY * 26-Mar-96 Przemek Pardyak (pardy) at the University of Washington * Added unlock_unlocked. * * 10-Dec-94 Emin Gun Sirer (egs) at the University of Washington * Created. Log functions for use in debugging. */ #define SPLEXTREME 7 #define LOGSIZE 8192 char printlog[LOGSIZE]; int logend = 0, logstart = 0; void plog(char *s) { long i, spl; if(s == 0) return; spl = SpinSwapIpl(SPLEXTREME); for(i = 0; i < strlen(s); ++i) { printlog[logend] = s[i]; logend = (logend + 1) % LOGSIZE; if(logend == logstart) logstart = (logstart + 1) % LOGSIZE; } SpinSwapIpl(spl); } void plogi(long l) { char buf[1024]; long i, spl; spl = SpinSwapIpl(SPLEXTREME); sprintf(buf, "%d", l); plog(buf); SpinSwapIpl(spl); } void plogx(long l) { char buf[1024]; long i, spl; spl = SpinSwapIpl(SPLEXTREME); sprintf(buf, "%lx", l); plog(buf); SpinSwapIpl(spl); } void dumplog() { int i; long spl; spl = SpinSwapIpl(SPLEXTREME); for(i = logstart; i != logend; i = (i + 1) % LOGSIZE) { printf("%c", printlog[i]); } SpinSwapIpl(spl); } void unlock_unlocked () { printf("ERROR >> attempt to unlock an unlocked lock\n"); Debugger(); }
C
#include <stdio.h> #include "function.h" void flooding(int R, int C, int pr, int pc){ //initial if(pr == 0) Map[pr][pc] = 'W'; //left if(pc != 0){ if(Map[pr][pc - 1] == 'H'){ Map[pr][pc - 1] = 'W'; flooding(R, C, pr, pc - 1); } } //right if(pc != C - 1){ if(Map[pr][pc + 1] == 'H'){ Map[pr][pc + 1] = 'W'; flooding(R, C, pr, pc + 1); } } //up if(pr != 0){ if(Map[pr - 1][pc] == 'H'){ Map[pr - 1][pc] = 'W'; flooding(R, C, pr - 1, pc); } } //down if(pr != R - 1){ if(Map[pr + 1][pc] == 'H'){ Map[pr + 1][pc] = 'W'; flooding(R, C, pr + 1, pc); } } return; }
C
#include <stdio.h> #include <math.h> #include "sistlinear.h" Matriz criaA(); Matriz criaB(); void teste(); int main(int argc, const char * argv[]) { double b1[3] = {3, 3, -6}, b2[6] = {2.5, 1.5, 1, 1, 1.5, 2.5}; Matriz A, B; printf("Teste Matriz A:\n"); A = criaA(); teste(3, A, b1); printf("Teste Matriz B:\n"); B = criaB(); teste(6, B, b2); return 0; } Matriz criaA() { Matriz A = mat_cria(3, 3); A[0][0] = 1; A[0][1] = 2; A[0][2] = -1; A[1][0] = 2; A[1][1] = 1; A[1][2] = -2; A[2][0] = -3; A[2][1] = 1; A[2][2] = 1; return A; } Matriz criaB() { int i, j; Matriz B = mat_cria(6, 6); for (i = 0; i < 6; i++) { for (j = 0; j < 6; j++) { if (i == j) { B[i][j] = 3; } else if (i+j == 5) { B[i][j] = 0.5; } else { B[i][j] = 0; } if (j == i+1 || i == j+1) { B[i][j] = -1; } } } return B; } void teste(int n, Matriz M, double * b) { int i, * p; double * x; // Teste fatoracao printf("Matriz\n"); mat_imprime(n, n, M, "%.3g"); printf("\nFatoracao\np = { "); p = fatoracao(n, M); for (i = 0; i < n; i++) printf("%d ", p[i]); printf("}\n"); // Teste substituicao printf("\nSubstituicao\nx = { "); x = substituicao(n, M, p, b); for (i = 0; i < n; i++) printf("%g ", x[i]); printf("}\n\n"); }
C
#ifndef ORION_SINGLETON_H #define ORION_SINGLETON_H // singleton #define SINGLETON(className)\ private:\ className() {}\ ~className() {}\ public:\ static className& Instance() {\ static className instance;\ return instance;\ }\ className(className&&) = delete; \ className(className const&) = delete; \ className& operator=(className&&) = delete; \ className& operator=(className const&) = delete; \ // unable copy #define UNABLE_COPY(className)\ public:\ className() = default; \ ~className() = default; \ className(className&&) = delete;\ className(className const&) = delete;\ className& operator=(className&&) = delete;\ className& operator=(className const&) = delete;\ #endif // ORION_SINGLETON_H
C
#include "grille.h" void visuGrille(char grille[NBRE_LIGNE][NBRE_COL]){ char i = 0, j =0, k = 0, l = 0; for(i=0; i<NBRE_LIGNE; i = i+3){ for(j=0; j<NBRE_LIGNE/3; j++){ for(k=0; k<NBRE_COL/3; k++){ for(l=0; l<NBRE_COL/3; l++){ printf("%d ", grille[i+j][k*3+l]); } printf(" "); } printf("\n"); } printf("\n"); } } int nbreDeValPoss(char grille[NBRE_LIGNE][NBRE_COL], S_elem *e, char ligne, char col){ bool tab[10] = {false}; char i = 0, nbre_poss = 0; searchElemImpLigne(grille[ligne], tab, &(e->l_elem_imp), ligne, col); searchElemImpCol(grille, tab, &(e->l_elem_imp), ligne, col); searchElemImpBloc(grille, tab, &(e->l_elem_imp), ligne, col); for(i=9; i>0; i--){ //on commence par 9 => comme ca, la liste des val possibles sera triée dans l'ordre croissant if(!tab[i]){ nbre_poss++; ajoutElemValPoss(&(e->l_val_poss), i); } } return nbre_poss; } void searchElemImpLigne(char grille[NBRE_COL], bool tab[10], liste_elem_imp *l_elem_imp, char lig, char col){ char j = 0; S_pos pos; pos.lig = lig; for(j=0; j<NBRE_COL; j++){ if(j != col){ if(grille[j] == 0){ pos.col = j; ajoutElemElemImp(l_elem_imp, &grille[j], pos); } else{ tab[grille[j]] = true; } } } } void searchElemImpCol(char grille[NBRE_LIGNE][NBRE_COL], bool tab[10], liste_elem_imp *l_elem_imp, char ligne, char col){ char i = 0; S_pos pos; pos.col = col; for(i=0; i<NBRE_COL; i++){ if(i != ligne){ if(grille[i][col] == 0){ pos.lig = i; ajoutElemElemImp(l_elem_imp, &grille[i][col], pos); } else{ tab[grille[i][col]] = true; } } } } void searchElemImpBloc(char grille[NBRE_LIGNE][NBRE_COL], bool tab[9], liste_elem_imp *l_elem_imp, char ligne, char col){ char debut_l = (ligne/3)*3, fin_l = debut_l+3; char debut_c = (col/3)*3, fin_c = debut_c+3; char i = 0, j = 0; S_pos pos; for(i=debut_l; i<fin_l; i++){ for(j=debut_c; j<fin_c; j++){ if(i != ligne && j != col){ if(grille[i][j] == 0){ pos.lig = i; pos.col = j; ajoutElemElemImp(l_elem_imp, &grille[i][j], pos); } else{ tab[grille[i][j]] = true; } } } } } bool verificationReponse(char grille[NBRE_LIGNE][NBRE_COL]){ return verifLigne(grille) && verifCol(grille) && verifBlocs(grille); } void reInitTab(char tab[10], char taille){ char i = 0; for(i=0; i<taille; i++){ tab[i] = 0; } } bool verifLigne(char grille[NBRE_LIGNE][NBRE_COL]){ int i = 0, j = 0; char tab[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(i=0; i<NBRE_LIGNE; i++){ for(j=0; j<NBRE_COL; j++){ if((tab[grille[i][j]]++) > 1){ return false; } } reInitTab(tab, 10); } return true; } bool verifCol(char grille[NBRE_LIGNE][NBRE_COL]){ int i = 0, j = 0; char tab[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(i=0; i<NBRE_COL; i++){ for(j=0; j<NBRE_LIGNE; j++){ if((tab[grille[j][i]]++) > 1){ return false; } } reInitTab(tab, 10); } return true; } bool verifBlocs(char grille[NBRE_LIGNE][NBRE_COL]){ char i = 0, j =0, k = 0, l = 0; char tab[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(i=0; i<NBRE_LIGNE; i = i+3){ for(j=0; j<NBRE_COL; j=j+3){ for(k=i; k<i+3; k++){ for(l=j; l<j+3; l++){ if((tab[grille[k][l]]++)>1){ return false; } } } reInitTab(tab, 10); } } return true; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "hi_fstool.h" void ShowHelp() { #ifdef __HuaweiLite__ printf("mkfs usage:sample clusterSize(KB) mode partition\n" "\n" "description\n" "clusterSize(KB) : 64 \n" "mode : -a(advanced) or -d(discard) \n" "partition : such as /dev/mmcblk0p0 \n"); #else printf("mkfs usage:./himkfs.vfat clusterSize(KB) mode partition\n" "\n" "description\n" "clusterSize(KB) : 64 \n" "mode : -a(advanced) or -d(discard) \n" "partition : such as /dev/mmcblk0p1 \n"); #endif } #ifdef __HuaweiLite__ int app_main(int argc, char* argv[]) #else int main(int argc, char* argv[]) #endif { int ret = 0; unsigned int cluSize = 0; if (((argc == 2) && !strcmp("--help", argv[1])) || argc != 4) { ShowHelp(); return 1; } cluSize = 1024* atoi(argv[1]); HI_FSTOOL_FORMAT_CFG_S stFstoolCfg; stFstoolCfg.u32ClusterSize = cluSize; stFstoolCfg.enable4KAlignCheck = 0; if (!strcmp("-a", argv[2])) { stFstoolCfg.enMode = HI_FSTOOL_FORMAT_MODE_ADVANCED; ret = HI_FSTOOL_Format(argv[3], &stFstoolCfg); } else if (!strcmp("-d", argv[2])) { stFstoolCfg.enMode = HI_FSTOOL_FORMAT_MODE_DISCARD; ret = HI_FSTOOL_Format(argv[3], &stFstoolCfg); } else { ShowHelp(); return 1; } if (0 != ret) { printf("[himkfs]:mkfs fail with errno:0x%x\n", ret); } return ret; }
C
#include <stdio.h> #include <stdlib.h> int test(char **, char*); int main(int argc, char **argv) { if (argc == 2) { printf("%s\n", ++*argv); } int i; for (i=0; i < 10; i++) { printf("%d:%d\t", i, i % 2); } printf("\n"); /* int j; for (j=0; j < 50; j++) { printf("%d\n",j ); } */ char *a[] = {"goat", "lion", "elephant", 0}; printf("%d\n", test(a, "animal")); return 0; } int test(char **x, char *c) { while (*x) { printf("%s: %s\n", *x, c); x++; } }
C
#ifndef ALGORITHMS_COUNTINGSORT_H #define ALGORITHMS_COUNTINGSORT_H void countingSort (int *a, int n) { int max = a[n - 1], min = a[0]; for (int i = 0; i < n; i++) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; } int *c = new int[max + 1 - min]; for (int i = 0; i < max + 1 - min; i++) { c[i] = 0; } for (int i = 0; i < n; i++) { c[a[i] - min] = c[a[i] - min] + 1; } int i = 0; for (int j = min; j < max + 1; j++) { while (c[j-min] != 0) { a[i] = j; c[j-min]--; i++; } } } #endif //ALGORITHMS_COUNTINGSORT_H
C
#include <exception> using namespace std; #include "SelectionSort.h" SelectionSort::SelectionSort() { } SelectionSort::~SelectionSort() { } void SelectionSort::SortData(int *data, size_t count) { for (int i = 0 ; i<count; i++) { int min = i; for (int j=i+1; j< count; j++) { if (data[j] < data[min]) { min=j; } } if (min != i) swap(data[min], data[i]); } }
C
#include <stdio.h> #include <stdlib.h> FILE *Fin; FILE *Fout; int smax; void clear() { char jj; int i; int full = 0; int sol = 0; fscanf(Fin, "%d", &smax); fscanf(Fin, "%c", &jj); for (i = 0; i < (smax + 1); i++) { fscanf(Fin, "%c", &jj); if (full < i) { sol = (sol + i) - full; full = i; } full = (full + jj) - '0'; } fprintf(Fout, "%d\n", sol); } int Main(int argc, char *argv[]) { char rm_direction; int full; int i; Fin = fopen(argv[1], "r"); Fout = fopen("out", "w"); if ((Fin == 0) || (Fout == 0)) { printf("Fitxer out.\n"); } else { fscanf(Fin, "%d", &full); fscanf(Fin, "%c", &rm_direction); for (i = 0; i < full; i++) { fprintf(Fout, "Case #%d: ", i + 1); clear(); } fclose(Fin); fclose(Fout); } return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; int height; int lc; int rc; struct node* left; struct node* right; }node; int height(struct node *N) { if (N == NULL) return 0; return N->height; } int max(node* a,node* b) { if(a!=NULL && b!=NULL) return (a->height)>(b->height)?a->height:b->height; if(a!=NULL) return a->height; if(b!=NULL) return b->height; else return 0; } node* srl(node** head) { node *u,*v,*v1; v=(*head)->left; v1=v->right; u=(*head); int r1=u->rc,r2=v->rc,r3=v->lc; v->right=u; u->left=v1; u->lc-=r3+1; v->rc=r2+r1+1; u->height=max(u->left,u->right)+1; v->height=max(v->left,v->right)+1; //printf("srl\n"); return v; } node* srr(node** head) { node *u,*v,*v1; v=(*head)->right; v1=v->left; u=(*head); int l1=u->lc,l2=v->lc; v->left=u; u->right=v1; u->rc=l2; v->lc=l1+l2+1; u->height=max(u->left,u->right)+1; v->height=max(v->left,v->right)+1; //printf("srr\n"); return v; } node* drl(node** head) { (*head)->left=srr(&((*head)->left)); //printf("drl\n"); return srl(head); } node* drr(node** head) { (*head)->right=srl(&((*head)->right)); //printf("drr\n"); return srr(head); } void insert (node** head,int dat) { if(*head==NULL) { node* temp; temp=(node*)malloc(sizeof(node)); temp->data=dat; temp->height=1; temp->lc=0; temp->rc=0; temp->left=NULL; temp->right=NULL; *head=temp; return; } else { if(dat>=(*head)->data) { (*head)->rc+=1; //printf("hi\n"); insert(&((*head)->right),dat); } else { (*head)->lc+=1; insert(&((*head)->left),dat); } (*head)->height=(max((*head)->left,(*head)->right))+1; if(height((*head)->left)-height((*head)->right)>1) { if(height(((*head)->left)->left)>=height(((*head)->left)->right)) *head=srl(head); else *head=drl(head); } else if(height((*head)->right)-height((*head)->left)>1) { if(height(((*head)->right)->right)>=height(((*head)->right)->left)) *head=srr(head); else *head=drr(head); } } return; } void print(node** head) { if(*head==NULL) return; print(&((*head)->left)); printf("%d,%d,%d,%d; ",(*head)->data,(*head)->height,(*head)->lc,(*head)->rc); print(&((*head)->right)); return; } int search(node** head,int dat) { if(*head==NULL) { //printf("%d not found\n",dat); return 0; } if((*head)->data==dat) { //printf("%d found\n",dat); return 1; } else { if(dat>=(*head)->data) search(&((*head)->right),dat); else search(&((*head)->left),dat); } } struct node * minValueNode(struct node* node) { struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current; } void deleteNode(node** head, int data) { // STEP 1: PERFORM STANDARD BST DELETE if (*head == NULL) return; // If the data to be deleted is smaller than the *head's data, // then it lies in left subtree if ( data < (*head)->data ) { (*head)->lc--; deleteNode(&(*head)->left, data); } // If the data to be deleted is greater than the *head's data, // then it lies in right subtree else if( data > (*head)->data ) { (*head)->rc--; deleteNode(&(*head)->right, data); } // if data is same as *head's data, then This is the node // to be deleted else { // node with only one child or no child if( ((*head)->left == NULL) || ((*head)->right == NULL) ) { struct node *temp = (*head)->left ? (*head)->left : (*head)->right; // No child case if(temp == NULL) { temp = *head; *head = NULL; } else // One child case *head = temp; // Copy the contents of the non-empty child //free(temp); } else { // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode((*head)->right); // Copy the inorder successor's data to this node (*head)->data = temp->data; // Delete the inorder successor deleteNode(&(*head)->right, (*head)->data); } } // If the tree had only one node then return if (*head == NULL) return; (*head)->height=(max((*head)->left,(*head)->right))+1; if(height((*head)->left)-height((*head)->right)>1) { if(height(((*head)->left)->left)>=height(((*head)->left)->right)) *head=srl(head); else *head=drl(head); } else if(height((*head)->right)-height((*head)->left)>1) { if(height(((*head)->right)->right)>=height(((*head)->right)->left)) *head=srr(head); else *head=drr(head); } return ; } int kamin(node* head,int dat) { if(head!=NULL){ if(head->lc == dat-1){ //printf("Entered on equal %d\n",head->data); return head->data; } if(head->lc > dat-1) { //printf("Entered Left\n"); return kamin(head->left,dat); } else if(head->lc < dat-1) { //printf("Entered Right\n"); return kamin(head->right,dat-(head->lc)-1); } } //return 0; } int top=0; int co(node* head,int dat) { if(head!=NULL){ if(head->data<dat) { //printf("Entered right @ %d lc : %d\n",head->data,head->lc); top+=(head->lc)+1; return co(head->right,dat); } else { //printf("Entered left @ %d lc : %d\n",head->data,head->lc); return co(head->left,dat); } return 0; } //else } int main() { int Q,i,num=0; node* head=NULL; scanf("%d",&Q); for(i=0;i<Q;i++) { int x; char a[10]; scanf("%s %d",a,&x); if(a[0]=='I') { int y=search(&head,x); if(y==0) { num++; insert(&head,x); } } if(a[0]=='D') { int y=search(&head,x); if(y==1) { num--; deleteNode(&head,x); //print(&head); } } if(a[0]=='K') { if(x>num) printf("invalid\n"); else printf("%d\n",kamin(head,x)); } if(a[0]=='C') { top=0; co(head,x); printf("%d\n",top); } } return 0; }
C
#include <stdint.h> #include <avr/io.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include "led.h" #include "sleep_led.h" #ifndef SLEEP_LED_TIMER # define SLEEP_LED_TIMER 1 #endif #if SLEEP_LED_TIMER == 1 # define TCCRxB TCCR1B # define TIMERx_COMPA_vect TIMER1_COMPA_vect # if defined(__AVR_ATmega32A__) // This MCU has only one TIMSK register # define TIMSKx TIMSK # else # define TIMSKx TIMSK1 # endif # define OCIExA OCIE1A # define OCRxx OCR1A #elif SLEEP_LED_TIMER == 3 # define TCCRxB TCCR3B # define TIMERx_COMPA_vect TIMER3_COMPA_vect # define TIMSKx TIMSK3 # define OCIExA OCIE3A # define OCRxx OCR3A #else error("Invalid SLEEP_LED_TIMER config") #endif /* Software PWM * ______ ______ __ * | ON |___OFF___| ON |___OFF___| .... * |<-------------->|<-------------->|<- .... * PWM period PWM period * * 256 interrupts/period[resolution] * 64 periods/second[frequency] * 256*64 interrupts/second * F_CPU/(256*64) clocks/interrupt */ #define SLEEP_LED_TIMER_TOP F_CPU / (256 * 64) /** \brief Sleep LED initialization * * FIXME: needs doc */ void sleep_led_init(void) { /* Timer1 setup */ /* CTC mode */ TCCRxB |= _BV(WGM12); /* Clock selelct: clk/1 */ TCCRxB |= _BV(CS10); /* Set TOP value */ uint8_t sreg = SREG; cli(); OCRxx = SLEEP_LED_TIMER_TOP; SREG = sreg; } /** \brief Sleep LED enable * * FIXME: needs doc */ void sleep_led_enable(void) { /* Enable Compare Match Interrupt */ TIMSKx |= _BV(OCIExA); } /** \brief Sleep LED disable * * FIXME: needs doc */ void sleep_led_disable(void) { /* Disable Compare Match Interrupt */ TIMSKx &= ~_BV(OCIExA); } /** \brief Sleep LED toggle * * FIXME: needs doc */ void sleep_led_toggle(void) { /* Disable Compare Match Interrupt */ TIMSKx ^= _BV(OCIExA); } /** \brief Breathing Sleep LED brighness(PWM On period) table * * (64[steps] * 4[duration]) / 64[PWM periods/s] = 4 second breath cycle * * http://www.wolframalpha.com/input/?i=%28sin%28+x%2F64*pi%29**8+*+255%2C+x%3D0+to+63 * (0..63).each {|x| p ((sin(x/64.0*PI)**8)*255).to_i } */ static const uint8_t breathing_table[64] PROGMEM = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 6, 10, 15, 23, 32, 44, 58, 74, 93, 113, 135, 157, 179, 199, 218, 233, 245, 252, 255, 252, 245, 233, 218, 199, 179, 157, 135, 113, 93, 74, 58, 44, 32, 23, 15, 10, 6, 4, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; ISR(TIMERx_COMPA_vect) { /* Software PWM * timer:1111 1111 1111 1111 * \_____/\/ \_______/____ count(0-255) * \ \______________ duration of step(4) * \__________________ index of step table(0-63) */ static union { uint16_t row; struct { uint8_t count : 8; uint8_t duration : 2; uint8_t index : 6; } pwm; } timer = {.row = 0}; timer.row++; // LED on if (timer.pwm.count == 0) { led_set(1 << USB_LED_CAPS_LOCK); } // LED off if (timer.pwm.count == pgm_read_byte(&breathing_table[timer.pwm.index])) { led_set(0); } }
C
main() { int a[10],sum1=0,sum2=0,i; printf("enter ten numbers"); for(i=0;i<=9;i++) { scanf("%d",&a[i]); if(a[i]%2==0) { sum1=sum1+a[i]; } else { sum2=sum2+a[i]; } } printf("sum of even number is %d and sum of odd number is %d",sum1,sum2); getch(); }
C
#include <stdint.h> #include <stdarg.h> #include <string.h> #include <wchar.h> int wcscmp(const wchar_t* str1, const wchar_t* str2) { while ((*str1) && (*str1 == *str2)) { str1++; str2++; } return *(uint16_t*)str1 - *(uint16_t*)str2; } size_t wcslen(const wchar_t* str) { size_t length = 0; while (*str != L'\0') { length++; str++; } return length; } wchar_t* wcscpy(wchar_t* dest, const wchar_t* source) { size_t length = wcslen(source); memcpy(dest, source, length * sizeof(wchar_t)); return dest; } wchar_t* wcsncpy(wchar_t* dest, const wchar_t* source, size_t num) { memcpy(dest, source, num * sizeof(wchar_t)); return dest; } //Internal protypes int kvwprintf(wchar_t const* fmt, void (*func)(int, void*), void* arg, int radix, va_list ap); wchar_t* kswprintn(wchar_t* nbuf, uintmax_t num, int base, int* len, int upper); //TODO: convert/rewrite these routines, or at lease source them #define NBBY 8 /* number of bits in a byte */ /* Max number conversion buffer length: an unsigned long long int in base 2, plus NUL byte. */ #define MAXNBUF (sizeof(intmax_t) * NBBY + 1) wchar_t const hex2wchar_t_data[] = L"0123456789abcdefghijklmnopqrstuvwxyz"; #define hex2ascii(hex) (hex2wchar_t_data[hex]) #define toupper(c) ((c) - 0x20 * (((c) >= L'a') && ((c) <= L'z'))) typedef size_t ssize_t; inline int imax(int a, int b) { return (a > b ? a : b); } /* int swprintf(wchar_t* const _Buffer, size_t const _BufferCount, wchar_t const* const _Format, ...) { int retval; va_list ap; va_start(ap, _Format); retval = kvwprintf(_Format, NULL, (void*)_Buffer, 10, ap); _Buffer[retval] = L'\0'; va_end(ap); return (retval); } */ /* int vwprintf(wchar_t* const _Buffer, wchar_t const* const _Format, va_list _ArgList) { int retval; retval = kvwprintf(_Format, NULL, (void*)_Buffer, 10, _ArgList); _Buffer[retval] = L'\0'; return (retval); } */ /* * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse * order; return an optional length and a pointer to the last character * written in the buffer (i.e., the first character of the string). * The buffer pointed to by `nbuf' must have length >= MAXNBUF. */ wchar_t* kswprintn(wchar_t* nbuf, uintmax_t num, int base, int* lenp, int upper) { wchar_t* p, c; p = nbuf; *p = L'\0'; do { c = hex2ascii(num % base); *++p = upper ? toupper(c) : c; } while (num /= base); if (lenp) * lenp = (int)(p - nbuf); return (p); } /* * Scaled down version of printf(3). * * Two additional formats: * * The format %b is supported to decode error registers. * Its usage is: * * printf("reg=%b\n", regval, "<base><arg>*"); * * where <base> is the output base expressed as a control character, e.g. * \10 gives octal; \20 gives hex. Each arg is a sequence of characters, * the first of which gives the bit number to be inspected (origin 1), and * the next characters (up to a control character, i.e. a character <= 32), * give the name of the register. Thus: * * kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE"); * * would produce output: * * reg=3<BITTWO,BITONE> * * XXX: %D -- Hexdump, takes pointer and separator string: * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX * ("%*D", len, ptr, " " -> XX XX XX XX ... */ int kvwprintf(wchar_t const* fmt, void (*func)(int, void*), void* arg, int radix, va_list ap) { #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; } wchar_t nbuf[MAXNBUF]; wchar_t* d; const wchar_t* p, * percent, * q; wchar_t* up; int ch, n; uintmax_t num; int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot; int cflag, hflag, jflag, tflag, zflag; int bconv, dwidth, upper; wchar_t padc; int stop = 0, retval = 0; num = 0; q = NULL; if (!func) d = (wchar_t*)arg; else d = NULL; if (fmt == NULL) fmt = L"(fmt null)\n"; if (radix < 2 || radix > 36) radix = 10; for (;;) { padc = ' '; width = 0; while ((ch = (wchar_t)* fmt++) != L'%' || stop) { if (ch == L'\0') return (retval); PCHAR(ch); } percent = fmt - 1; qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0; sign = 0; dot = 0; bconv = 0; dwidth = 0; upper = 0; cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0; reswitch: switch (ch = (wchar_t)* fmt++) { case L'.': dot = 1; goto reswitch; case L'#': sharpflag = 1; goto reswitch; case L'+': sign = 1; goto reswitch; case L'-': ladjust = 1; goto reswitch; case L'%': PCHAR(ch); break; case L'*': if (!dot) { width = va_arg(ap, int); if (width < 0) { ladjust = !ladjust; width = -width; } } else { dwidth = va_arg(ap, int); } goto reswitch; case L'0': if (!dot) { padc = L'0'; goto reswitch; } /* FALLTHROUGH */ case L'1': case L'2': case L'3': case L'4': case L'5': case L'6': case L'7': case L'8': case L'9': for (n = 0;; ++fmt) { n = n * 10 + ch - L'0'; ch = *fmt; if (ch < L'0' || ch > L'9') break; } if (dot) dwidth = n; else width = n; goto reswitch; case L'b': ladjust = 1; bconv = 1; goto handle_nosign; case L'c': width -= 1; if (!ladjust && width > 0) while (width--) PCHAR(padc); PCHAR(va_arg(ap, int)); if (ladjust && width > 0) while (width--) PCHAR(padc); break; case L'D': up = va_arg(ap, wchar_t*); p = va_arg(ap, wchar_t*); if (!width) width = 16; while (width--) { PCHAR(hex2ascii(*up >> 4)); PCHAR(hex2ascii(*up & 0x0f)); up++; if (width) for (q = p; *q; q++) PCHAR(*q); } break; case L'd': case L'i': base = 10; sign = 1; goto handle_sign; case L'h': if (hflag) { hflag = 0; cflag = 1; } else hflag = 1; goto reswitch; case L'j': jflag = 1; goto reswitch; case L'l': if (lflag) { lflag = 0; qflag = 1; } else lflag = 1; goto reswitch; case L'n': if (jflag) * (va_arg(ap, intmax_t*)) = retval; else if (qflag) * (va_arg(ap, long long*)) = retval; else if (lflag) * (va_arg(ap, long*)) = retval; else if (zflag) * (va_arg(ap, size_t*)) = retval; else if (hflag) * (va_arg(ap, short*)) = retval; else if (cflag) * (va_arg(ap, char*)) = retval; else *(va_arg(ap, int*)) = retval; break; case L'o': base = 8; goto handle_nosign; case L'p': base = 16; sharpflag = (width == 0); sign = 0; num = (uintptr_t)va_arg(ap, void*); goto number; case L'q': qflag = 1; goto reswitch; case L'r': base = radix; if (sign) goto handle_sign; goto handle_nosign; case L's': p = va_arg(ap, wchar_t*); if (p == NULL) p = L"(null)"; if (!dot) n = (int)wcslen(p); else for (n = 0; n < dwidth && p[n]; n++) continue; width -= n; if (!ladjust && width > 0) while (width--) PCHAR(padc); while (n--) PCHAR(*p++); if (ladjust && width > 0) while (width--) PCHAR(padc); break; case L't': tflag = 1; goto reswitch; case L'u': base = 10; goto handle_nosign; case L'X': upper = 1; //__attribute__((fallthrough)); // For GCC to stop warning about a fallthrough here case L'x': base = 16; goto handle_nosign; case L'y': base = 16; sign = 1; goto handle_sign; case L'z': zflag = 1; goto reswitch; handle_nosign: sign = 0; if (jflag) num = va_arg(ap, uintmax_t); else if (qflag || (width == 16)) //HACK? Apparently "qx" is the old way to do 64bit? this lets us not use the q if we have %16x num = va_arg(ap, unsigned long long); else if (tflag) num = va_arg(ap, ptrdiff_t); else if (lflag) num = va_arg(ap, unsigned long); else if (zflag) num = va_arg(ap, size_t); else if (hflag) num = (unsigned short)va_arg(ap, int); else if (cflag) num = (unsigned char)va_arg(ap, int); else num = va_arg(ap, unsigned int); if (bconv) { q = va_arg(ap, wchar_t*); base = *q++; } goto number; handle_sign: if (jflag) num = va_arg(ap, intmax_t); else if (qflag) num = va_arg(ap, long long); else if (tflag) num = va_arg(ap, ptrdiff_t); else if (lflag) num = va_arg(ap, long); else if (zflag) num = va_arg(ap, ssize_t); else if (hflag) num = (short)va_arg(ap, int); else if (cflag) num = (wchar_t)va_arg(ap, int); else num = va_arg(ap, int); number: if (sign && (intmax_t)num < 0) { neg = 1; num = -(intmax_t)num; } p = kswprintn(nbuf, num, base, &n, upper); tmp = 0; // There's weird behavior here with #. Don't use # to get 0x with zero-padding // (e.g. use 0x%016qx instead, not %#016qx or %#018qx, the latter of which will pad // 16 characters for nonzero numbers but zeros will have 18 characters). // Same with octal: use a leading zero and don't rely on # if you want zero-padding. // # works if you don't need zero padding, though. if (sharpflag && num != 0) { if (base == 8) tmp++; else if (base == 16) tmp += 2; } if (neg) tmp++; if (!ladjust && padc == L'0') dwidth = width - tmp; width -= tmp + imax(dwidth, n); dwidth -= n; if (!ladjust) while (width-- > 0) PCHAR(L' '); if (neg) PCHAR(L'-'); if (sharpflag && num != 0) { if (base == 8) { PCHAR(L'0'); } else if (base == 16) { PCHAR(L'0'); PCHAR(L'x'); } } while (dwidth-- > 0) PCHAR(L'0'); while (*p) PCHAR(*p--); if (bconv && num != 0) { /* %b conversion flag format. */ tmp = retval; while (*q) { n = *q++; if (num & (1ll << ((uintmax_t)n - 1))) { PCHAR(retval != tmp ? L',' : L'<'); for (; (n = *q) > L' '; ++q) PCHAR(n); } else for (; *q > L' '; ++q) continue; } if (retval != tmp) { PCHAR(L'>'); width -= retval - tmp; } } if (ladjust) while (width-- > 0) PCHAR(L' '); break; default: while (percent < fmt) PCHAR(*percent++); /* * Since we ignore a formatting argument it is no * longer safe to obey the remaining formatting * arguments as the arguments will no longer match * the format specs. */ stop = 1; break; } } #undef PCHAR } /* typedef void* _locale_t; int __stdio_common_vswprintf( unsigned __int64 const options, wchar_t* const buffer, size_t const buffer_count, wchar_t const* const format, _locale_t const locale, va_list const arglist ) { return vwprintf(buffer, format, arglist); } */ /* int vswprintf(wchar_t* const _Buffer, size_t const _BufferCount, wchar_t const* const _Format, va_list _ArgList) { int retval; retval = kvwprintf(_Format, NULL, (void*)_Buffer, 10, _ArgList); _Buffer[retval] = L'\0'; return (retval); } */ int swprintf(wchar_t* const _Buffer, size_t const _BufferCount, wchar_t const* const _Format, ...) { int _Result; va_list _ArgList; va_start(_ArgList, _Format); _Result = vswprintf(_Buffer, _BufferCount, _Format, _ArgList); va_end(_ArgList); return _Result; } //TODO: use _BufferCount int vswprintf(wchar_t* const _Buffer, size_t const _BufferCount, wchar_t const* const _Format, va_list _ArgList) { int retval; retval = kvwprintf(_Format, NULL, (void*)_Buffer, 10, _ArgList); _Buffer[retval] = L'\0'; return (retval); }
C
#include "client.h" #include "global.h" #include <assert.h> #include <stdlib.h> #include <stdio.h> // Array of all the client requests struct client_request *creq = NULL; size_t creq_size = 0; int prepare_clients(const struct settings * settings, void *data) { unsigned int clientthreads = 0; unsigned int i; assert ( settings != NULL ); assert ( settings->test != NULL ); assert ( creq == NULL ); assert ( creq_size == 0 ); // Malloc one space for each core combination creq_size = settings->clientcores; // Malloc one space for each core creq = calloc ( creq_size, sizeof(*creq) ); if ( !creq ) { creq_size = 0; fprintf(stderr, "%s:%d calloc() error\n", __FILE__, __LINE__ ); return -1; } // Loop through clientserver looking for each client we need to create for ( i = 0; i < settings->tests; i++) { const struct test * test = &settings->test[i]; struct client_request *c; struct client_request_details *details; // find an exisiting creq with this core combo for ( c = creq; c < &creq[creq_size]; c++) { if ( c->settings == NULL || c->cores == test->clientcores ) break; } assert ( c < &creq[creq_size] ); // Check if we haven't set up this client thread yet if ( c->settings == NULL ) { c->settings = settings; c->cores = test->clientcores; clientthreads++; } // Malloc the request details details = calloc( 1, sizeof( *details ) ); if ( !details ) { fprintf(stderr, "%s:%d calloc() error\n", __FILE__, __LINE__ ); return -1; } // Add this new details before the other details details->next =c->details; c->details = details; details->n = test->connections; details->addr = test->addr; details->addr_len = test->addr_len; } // Double check we made the correct number of clients assert ( creq[creq_size - 1].settings != NULL ); return clientthreads; } int create_clients(const struct settings *settings, void *data) { unsigned int i; assert ( settings != NULL ); assert ( creq != NULL ); for (i = 0; i < creq_size; i++) { cpu_set_t cpus; assert ( creq[i].settings != NULL ); // If we are in quiet mode, we don't send anything, so lets not even create client thread if (creq[i].settings->quiet) { // But we must still say we are ready threads_signal_parent ( SIGNAL_READY_TO_GO, settings->threaded_model ); continue; } cpu_setup( &cpus, creq[i].cores ); //For now let's keep the client using the threaded model if ( create_thread( client_thread, &creq [i] , sizeof(cpus), &cpus, settings->threaded_model) ) { fprintf(stderr, "%s:%d create_thread() error\n", __FILE__, __LINE__ ); return -1; } } return 0; } void cleanup_clients() { unsigned int i; if ( creq ) { assert ( creq_size != 0 ); for (i = 0; i < creq_size; i++) { // Free the chain of details struct client_request_details *c = creq[i].details; while ( c != NULL ) { struct client_request_details *nextC = c->next; free ( c ); c = nextC; } } free( creq ); creq = NULL; creq_size = 0; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amoutik <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/09 10:11:03 by amoutik #+# #+# */ /* Updated: 2018/11/10 08:19:59 by amoutik ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void len_initial(t_type *type) { type->length.hh = 0; type->length.ll = 0; type->length.h = 0; type->length.l = 0; type->length.j = 0; type->length.z = 0; type->length.t = 0; } int s_print(t_type *types, const char **format, char **string, va_list args) { flags_handling(types, format); fields_handling(types, format, args); precision_handling(types, format, args); lenght_handling(&types->length, format); if (integer_handling(types, format, string, args)) { (*format)++; return (1); } else if (handling_oct_hex(types, format, string, args)) { (*format)++; return (1); } else if (handling_char(types, format, string, args)) { (*format)++; return (1); } else if (handling_string(types, format, string, args)) { (*format)++; return (1); } return (0); } void addition_chars(const char **format, char **string) { ft_putchar(*(*string) = *(*format)); *(*format) ? (*string)++ : 0; } int ft_vsprintf(char *buf, const char *format, va_list args) { char *string; t_type types; string = buf; while (*format) { while (*format && *format != '%') ft_putchar(*string++ = *format++); if (*format == '%') { ++format; len_initial(&types); if (s_print(&types, &format, &string, args)) continue; else if (*format == 'n') { if (handling_n(&buf, &types.length, &string, args)) continue; } else addition_chars(&format, &string); } (*format) ? format++ : 0; } return (string - buf); } int ft_printf(const char *format, ...) { char buf[50000]; va_list args; int ret; va_start(args, format); ret = ft_vsprintf(buf, format, args); va_end(args); return (ret); }
C
#include <stdio.h> int main(){ int n,i,valor,cont=0,fora=0; scanf("%d", &n); for(i=1;i<=n;i++){ scanf("%d", &valor); if((valor >= 10)&&(valor <= 20)){ cont++; }else{ fora++; } } printf("%d in\n", cont); printf("%d out\n", fora); return 0; }
C
#include <stdio.h> #include <string.h> #define INIT_VALUE 999 int findSubstring(char *str, char *substr); int main() { char str[40], substr[40], *p; int result = INIT_VALUE; printf("Enter the string: \n"); fgets(str, 80, stdin); if (p = strchr(str, '\n')) *p = '\0'; printf("Enter the substring: \n"); fgets(substr, 80, stdin); if (p = strchr(substr, '\n')) *p = '\0'; result = findSubstring(str, substr); if (result == 1) printf("findSubstring(): Is a substring\n"); else if (result == 0) printf("findSubstring(): Not a substring\n"); else printf("findSubstring(): An error\n"); return 0; } int findSubstring(char *str, char *substr) { while (*str) { if (*str == *substr) { int i; for (i = 1; substr[i] && str[i] == substr[i]; i++) ; if (!substr[i]) return 1; } str++; } return 0; }
C
#include <stdio.h> #include "assemble.h" #include "cerr.h" #include "word.h" int main(){ int i; WORD r; char *str[] = { "#32768", "#-1", "#G", "#FFFF", "#0", "#1", "#ab", "#AB", "#20" "0", "01", "1a", "-5G", "123", "32767", "32768", "32769", "-1", "-2345", "-32768", "-32769", "-32770" }; cerr_init(); /* エラーの初期化 */ addcerrlist_word(); for(i = 0; i < sizeof(str)/sizeof(str[0]); i++) { cerr->num = 0; r = nh2word(str[i]); printf("%s\t#%04X", str[i], r); if(cerr->num > 0) { printf("\tError - %d\t%s", cerr->num, cerr->msg); } printf("\n"); } freecerr(); return 0; }
C
#include<stdio.h> #include<string.h> void main() { char a[20]="hello",b[20]="world",des[20]; memcpy(des,a,5); memcpy(a,b,5); memcpy(b,des,5); printf("%s %s %s",des,a,b); }
C
int count_alpha(const char *str) { int c; int i; c = 0; i = 0; while (str[i] != '\0') { if ((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 && str[i] <= 122)) { c++; } i++; } return (c); } char *reverse_letter(const char *str) { char *rev; int i; int j; int a; a = count_alpha(str); rev = (char*)malloc(sizeof(char) * a + 1); i = 0; j = 0; rev[a--] = '\0'; while (str[i] != '\0' && a >= 0) { if ((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 && str[i] <= 122)) { rev[a--] = str[i]; } i++; } return (rev); //coding and coding.. }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> static void my_exit0(int, void *); static void my_exit1(void); static void my_exit2(void); char str[9] = "for test"; int main(void) { if (atexit(my_exit2) != 0) { perror("can't register my_exit2"); exit(-1); } if (atexit(my_exit1) != 0) { perror("can't register my_exit1"); exit(-1); } if (on_exit(my_exit0, (void *)str) != 0) { perror("can't register my_exit0"); exit(-1); } printf("main is done\n"); exit(1234); } static void my_exit2(void) { printf("second exit handler\n"); } static void my_exit1(void) { printf("first exit handler\n"); } static void my_exit0(int status, void *arg) { printf("zero exit handler\n"); printf("exit %d\n", status); printf("arg=%s\n", (char *)arg); }
C
#include <stdio.h> #include <string.h> #define NUM_STUDENT 4 #define NAME 0 #define ID 1 int main(int argc, char* argv[]) { char IdBook[NUM_STUDENT][2][10] = { {"KDS", "20201234"}, {"KYW", "20192535"}, {"LJH", "20187854"}, {"HPC", "20180301"} }; char buf[255] = { 0 }; printf("Enter the student name: "); scanf("%s", buf); for (int i = 0; i < NUM_STUDENT; i++) { if (!strcmp(IdBook[i][NAME], buf)) { // Find! printf("%s's ID = %s\n", IdBook[i][NAME], IdBook[i][ID]); return 0; } } printf("Fail to find %s in the list.\n", buf); return 0; }
C
#pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTMotor) #pragma config(Sensor, S1, , sensorI2CMuxController) #pragma config(Motor, motorA, , tmotorNormal, openLoop) #pragma config(Motor, motorB, , tmotorNormal, openLoop) #pragma config(Motor, motorC, , tmotorNormal, openLoop) #pragma config(Motor, mtr_S1_C1_1, Ltread, tmotorNormal, openLoop, encoder) #pragma config(Motor, mtr_S1_C1_2, Rtread, tmotorNormal, openLoop, reversed, encoder) #pragma config(Motor, mtr_S1_C2_1, acquirer, tmotorNormal, openLoop, encoder) #pragma config(Motor, mtr_S1_C2_2, crateflipper, tmotorNormal, openLoop, encoder) #pragma config(Motor, mtr_S1_C3_1, Lfrontconveyor, tmotorNormal, PIDControl, encoder) #pragma config(Motor, mtr_S1_C3_2, Rfrontconveyor, tmotorNormal, PIDControl, reversed, encoder) #pragma config(Motor, mtr_S1_C4_1, Lbackconveyor, tmotorNormal, PIDControl, encoder) #pragma config(Motor, mtr_S1_C4_2, Rbackconveyor, tmotorNormal, PIDControl, reversed, encoder) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "JoystickDriver.c" #define WAIT_TIME 15 //calculate the difference between the encoder values of //the back right and left conveyors //I'm not entirely sure if it works- the initial code assumed we always wanted positive stuff int backError() { return abs(nMotorEncoder[Rbackconveyor])-abs(nMotorEncoder[Lbackconveyor]); } void backCorrect(float correctionConst) { float correction = (float)backError()*correctionConst; correction=(int)correction; //if the error is positive, it means the right back conveyor has moved faster //so then we slow down the right back and speed up the left back //we also make sure that we only set them to speeds between -100 and 100 if (correction>=0) { if (motor[Rbackconveyor]-abs(correction)<-100) motor[Rbackconveyor]=-100; else motor[Rbackconveyor] = motor[Rbackconveyor] - abs(correction); if (motor[Lbackconveyor]+abs(correction)>100) motor[Lbackconveyor]=100; else { motor[Lbackconveyor] = motor[Lbackconveyor] + abs(correction); } } //if the error is negative, it means the left back conveyor has moved faster //so then we slow down the left back and speed up the right back //again, we make sure we only set them to speeds between -100 and 100 else { if (motor[Lbackconveyor]-abs(correction)<-100) motor[Lbackconveyor]=-100; else motor[Lbackconveyor] = motor[Lbackconveyor] -abs(correction); if (motor[Rbackconveyor]+abs(correction)>100) motor[Rbackconveyor]=100; else { motor[Rbackconveyor]= motor[Rbackconveyor]+ abs(correction); } } } //takes two parameters, interval and a correction constant //calculates the error every interval milliseconds //then corrects the conveyors based on this calculation and the correction constant //the correction constant controls the magnitude of the correction //large intervals will produce more error and consequently require small correction constants //conversely, small intervals will prouduce less error and require larger correction constants void correctConveyors(int interval, float correctionConst) { wait1Msec(interval); backCorrect(correctionConst); } task main(){ int iconveyorpower; // int nMaxRegulatedSpeed; // nMaxRegulatedSpeed = 5; nxtDisplayCenteredTextLine(1, "Program x"); bFloatDuringInactiveMotorPWM = false; nMotorEncoder[Lfrontconveyor]=0; nMotorEncoder[Rfrontconveyor]=0; nMotorEncoder[Lbackconveyor]=0; nMotorEncoder[Rbackconveyor]=0; /* nMotorPIDSpeedCtrl[Lfrontconveyor] = mtrSyncRegMaster; nMotorPIDSpeedCtrl[Rfrontconveyor] = mtrSyncRegSlave; nMotorPIDSpeedCtrl[Lbackconveyor] = mtrSyncRegMaster; nMotorPIDSpeedCtrl[Rbackconveyor] = mtrSyncRegSlave; */ /* nMotorEncoderTarget[Lfrontconveyor]=980; nMotorEncoderTarget[Rfrontconveyor]=980; nMotorEncoderTarget[Lbackconveyor]=980; nMotorEncoderTarget[Lbackconveyor]=980; */ //iconveyorpower = 30; while(true){ nxtDisplayCenteredTextLine(0, "LFront:"+nMotorEncoder[Lfrontconveyor]); nxtDisplayCenteredTextLine(1, "Rfront:"+nMotorEncoder[Rfrontconveyor]); nxtDisplayCenteredTextLine(2, "LBack:"+nMotorEncoder[Lbackconveyor]); nxtDisplayCenteredTextLine(3, "RBack:"+nMotorEncoder[Rbackconveyor]); if(joy1Btn(4)) { /* motor[Lfrontconveyor] = 0.9*iconveyorpower; motor[Rfrontconveyor] = 0.9*iconveyorpower; motor[Lbackconveyor] = 0.89*iconveyorpower; motor[Rbackconveyor] = 1.4*iconveyorpower; */ motor[Lfrontconveyor]=iconveyorpower; motor[Rfrontconveyor]=iconveyorpower; motor[Lbackconveyor] =iconveyorpower; motor[Rbackconveyor] =iconveyorpower; correctConveyors(10, 1.0); } else { motor[Lfrontconveyor] = 0; motor[Rfrontconveyor] = 0; motor[Lbackconveyor] = 0; motor[Rbackconveyor] = 0; } } }
C
// This header provides an API for the HiTechnic gyro sensor. // Version 0.4, made by Xander Soldaat. #ifndef __HTGYRO_H__ #define __HTGYRO_H__ #pragma systemFile #ifndef __COMMON_H__ #include "common.h" #endif // __COMMON_H__ float HTGYROreadRot(tSensors link); float HTGYROstartCal(tSensors link); float HTGYROreadCal(tSensors link); void HTGYROsetCal(tSensors link, int offset); #ifdef __HTSMUX_SUPPORT__ float HTGYROreadRot(tMUXSensor muxsensor); float HTGYROstartCal(tMUXSensor muxsensor); float HTGYROreadCal(tMUXSensor muxsensor); void HTGYROsetCal(tMUXSensor muxsensor, int offset); #endif // __HTSMUX_SUPPORT__ // Array for offset values. Default is 620. float HTGYRO_offsets[][] = {{620.0, 620.0, 620.0, 620.0}, {620.0, 620.0, 620.0, 620.0}, {620.0, 620.0, 620.0, 620.0}, {620.0, 620.0, 620.0, 620.0}}; // Reads the value of the gyro. // `link`: Port number of gyro. float HTGYROreadRot(tSensors link) { // Make sure the sensor is configured as type sensorRawValue. if (SensorType[link] != sensorAnalogInactive) { SetSensorType(link, sensorAnalogInactive); wait1Msec(100); } return (SensorValue[link]-HTGYRO_offsets[link][0]); } // Calibrate gyro by calculating the average offset of 25 // readings. Takes about 50*5=250ms, or 1/4th of a second. // Returns the new offset value for the gyro. // `link`: Port number of gyro. float HTGYROstartCal(tSensors link) { // Make sure the sensor is configured as type sensorRawValue. if (SensorType[link] != sensorAnalogInactive) { SetSensorType(link, sensorAnalogInactive); wait1Msec(100); } long _avgdata = 0; hogCPU(); wait1Msec(100); // Give the gyro time to initialize. int temp_reading = SensorValue[link]; // Flush out bad readings. // Take 50 readings and average them out. // NOTE: When changing limits on `i`, make sure to change // the number `_avgdata` is averaged by as well! for (int i=0; i<50; i++) { _avgdata += SensorValue[link]; wait1Msec(5); } releaseCPU(); // Store & return new offset value. HTGYRO_offsets[link][0] = (float)_avgdata/50.0; return HTGYRO_offsets[link][0]; } // Manually override the current offset for the gyro. // `link`: Port number. void HTGYROsetCal(tSensors link, int offset) { HTGYRO_offsets[link][0] = offset; } // Retrieve the current offset for the gyro. // `link`: Port number. float HTGYROreadCal(tSensors link) { return HTGYRO_offsets[link][0]; } #ifdef __HTSMUX_SUPPORT__ // Reads the value of the gyro. // `muxsensor`: SMUX sensor port number. float HTGYROreadRot(tMUXSensor muxsensor) { return HTSMUXreadAnalogue(muxsensor) - HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)]; } // Calibrate gyro by calculating the avg offset of 50 raw // readings. Takes about 50*5=250ms, or 1/4th of a second. // Returns the new offset value for the gyro. // `muxsensor`: SMUX sensor port number. float HTGYROstartCal(tMUXSensor muxsensor) { long _avgdata = 0; hogCPU(); wait1Msec(100); // Give the gyro time to initialize. int temp_reading = HTSMUXreadAnalogue(muxsensor); // Flush out bad readings. // Take 50 readings and average them out. // NOTE: When changing limits on `i`, make sure to change // the number `_avgdata` is averaged by as well! for (int i=0; i<50; i++) { _avgdata += HTSMUXreadAnalogue(muxsensor); wait1Msec(5); } releaseCPU(); // Store new offset value. HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)] = (_avgdata/50.0); // Return new offset value. return HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)]; } // Manually override the current offset for the gyro. // `muxsensor`: SMUX sensor port number. void HTGYROsetCal(tMUXSensor muxsensor, int offset) { HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)] = offset; } // Retrieve the current offset for the gyro. // `muxsensor`: SMUX sensor port number. float HTGYROreadCal(tMUXSensor muxsensor) { return HTGYRO_offsets[SPORT(muxsensor)][MPORT(muxsensor)]; } #endif // __HTSMUX_SUPPORT__ #endif // __HTGYRO_H__
C
// Parallel sum of array #include <stdio.h> #include <stdlib.h> #include <time.h> #include "mpi.h" #define N 900000000 int main(int argc, char *argv[]) { int numtasks, rank, len, rc, i, sidx; double etime, stime, a[N], value, localsum; char hostname[MPI_MAX_PROCESSOR_NAME]; // initialize MPI MPI_Init (&argc, &argv); // get number of tasks MPI_Comm_size (MPI_COMM_WORLD, &numtasks); // get my rank MPI_Comm_rank (MPI_COMM_WORLD, &rank); // this one is obvious MPI_Get_processor_name (hostname, &len); // printf ("Number of tasks=%d My rank=%d Running on %s\n", numtasks, rank, hostname); // random initialization srand(time(NULL)); value = abs((numtasks-rank)*(20210401-rand()))%N; sidx = rank*N/numtasks; for (i=sidx; i<sidx+N/numtasks ; i++) a[i] = value; // compute local sum localsum=0.0; stime = MPI_Wtime(); for (i=sidx; i<sidx+N/numtasks ; i++) localsum += a[i]; etime = MPI_Wtime(); printf ("%d: Time to sum: %lf\n", rank, etime - stime); // done with MPI MPI_Finalize(); }
C
int main() { int n,i,j; char a[50][33]; cin >> n; cin.ignore (); for(i=0 ; i< n ; i++) cin >> a[i]; for(i=0 ; i< n ; i++) { j = strlen(a[i]); if(a[i][j-2] == 'e') { if(a[i][j-1] == 'r') a[i][j-2] = '\0'; } if(a[i][j-2] == 'l') { if(a[i][j-1] == 'y') a[i][j-2] = '\0'; } if(a[i][j-3] == 'i') { if(a[i][j-2] == 'n' && a[i][j-1] == 'g') a[i][j-3] = '\0'; } cout<<a[i]<<endl; } return 0; }
C
#include "uvsqgraphics.h" int main() { init_graphics(600,400); // Debut du code POINT bg, hd; int min, max, imin, imax; int T[20]; int i; imin = 0; imax = 0; min = 100; max = 0; bg.y = 50; for (i=0 ; i<20 ; i=i+1) { T[i] = alea_int(100); bg.x = 100 + (20*i); hd.x = 100 + 20*i + 19; hd.y = 50 + 3*T[i]; draw_fill_rectangle(bg, hd, blue); if (T[i] < min) //min est à 100 au début { // si la valeur aléa est plus ptite que 100, ca devient le new min min = T[i]; imin = i; //du coup on save le i minimum } if (T[i] > max) { //pareil pour max max = T[i]; imax = i; } } //et on rajoute des rectangles avec les imin et min bg.x = 100 + (20* imin); hd.x = 100 + 20*imin +19; hd.y = 50 + 3*min; draw_fill_rectangle(bg, hd, blanc); bg.x = 100 + (20* imax); hd.x = 100 + 20*imax +19; hd.y = 50 + 3*max; draw_fill_rectangle(bg, hd, blanc); // Fin du code wait_escape(); exit(0); }
C
#include<stdio.h> int main() { int t,n,sum,k,p; scanf("%d",&t); while(t--) { sum=0; scanf("%d",&n); p=n; while(p>0) { k=p%10; if(n%k==0) { sum=sum+1; } p=p/10; } printf("%d",sum); } return 0; }
C
/* * File: LCDDisplay.c * Author: dd69 * * Created on February 7, 2019, 5:10 PM */ #include <xc.h> #include "LCDDisplay.h" #include "spiConfiguration.h" void InitPMP(void) { // PMP initialization. See my notes in Sec 13 PMP of Fam. Ref. Manual PMCON = 0x8303; // Following Fig. 13-34. Text says 0x83BF (it works) * PMMODE = 0x03FF; // Master Mode 1. 8-bit data, long waits. PMAEN = 0x0001; // PMA0 enabled } void InitLCD(void) { // PMP is in Master Mode 1, simply by writing to PMDIN1 the PMP takes care // of the 3 control signals so as to write to the LCD. PMADDR = 0; // PMA0 physically connected to RS, 0 select Control register PMDIN1 = 0b00111000; // 8-bit, 2 lines, 5X7. See Table 9.1 of text Function set ms_delay(1); // 1ms > 40us PMDIN1 = 0b00001100; // ON, cursor off, blink off ms_delay(1); // 1ms > 40us PMDIN1 = 0b00000001; // clear display ms_delay(2); // 2ms > 1.64ms PMDIN1 = 0b00000110; // increment cursor, no shift ms_delay(2); // 2ms > 1.64ms } // InitLCD char ReadLCD(int addr) { // As for dummy read, see 13.4.2, the first read has previous value in PMDIN1 int dummy; while (PMMODEbits.BUSY); // wait for PMP to be available PMADDR = addr; // select the command address dummy = PMDIN1; // initiate a read cycle, dummy while (PMMODEbits.BUSY); // wait for PMP to be available return ( PMDIN1); // read the status register } // ReadLCD // In the following, addr = 0 -> access Control, addr = 1 -> access Data #define BusyLCD() ReadLCD( 0) & 0x80 // D<7> = Busy Flag #define AddrLCD() ReadLCD( 0) & 0x7F // Not actually used here #define getLCD() ReadLCD( 1) // Not actually used here. void WriteLCD(int addr, char c) { while (BusyLCD()); while (PMMODEbits.BUSY); // wait for PMP to be available PMADDR = addr; PMDIN1 = c; } // WriteLCD // In the following, addr = 0 -> access Control, addr = 1 -> access Data #define putLCD( d) WriteLCD( 1, (d)) #define CmdLCD( c) WriteLCD( 0, (c)) #define HomeLCD() WriteLCD( 0, 2) // See HD44780 instruction set in #define ClrLCD() WriteLCD( 0, 1) // Table 9.1 of text book void putsLCD(char *s) { while (*s) putLCD(*s++); // See paragraph starting at bottom, pg. 87 text } //putsLCD void SetCursorAtLine(int i) { int a; if (i == 1) { CmdLCD(0x80); //Sets DRAM Address for HD44780 instruction set //To enable DRAM, hex 0x80 is translated to binary: 1000 0000 } else if (i == 2) { CmdLCD(0xC0); //Sets DRAM Address for HD44780 instruction set //To enable DRAM, hex 0xC0 is translated to binary: 1100 0000 } else { TRISA = 0x00; // hex for zero, sets PORTA<0:7> for output for (a = 1; a < 20; a++) //Loop to flash LEDs for 5 seconds at 2Hz { PORTA = 0xFF; //Turns LEDs on ms_delay(1000); //Delays half of the cycle // On For 2 Seconds PORTA = 0x00; //Turns LEDs off ms_delay(500); //Delays half of the cycle // Off For 1 Seconds } } }
C
#include "shell.h" /* holaaa */ /** * _strlen - calculates the length of the string pointed to * @str: First string to be compare *Return: the number of characters of the string pointed to */ int _strlen(const char *str) { int len; for (len = 0; str[len]; len++) { } return (len); } /** * _strcat - concatenates two strings. * @dest: First string to concatenate * @src: second string to concatenate *Return: The resultant concatenated string */ char *_strcat(char *dest, const char *src) { int i = 0, j = 0; while (dest[i]) { i++; } while ((dest[i] = src[j]) != 0) { i++; j++; } dest[i] = '\0'; return (dest); } /** * _strcpy1 - copies the string pointed by src to the character array dest. * @dest: destination string * @src: source string to copy * @flag: add special character to the end of string *Return: The copied array */ char *_strcpy1(char *dest, char *src, int flag) { int i; for (i = 0; src[i]; i++) { dest[i] = src[i]; } if (flag == 1) { dest[i] = '/'; i++; } else if (flag == 2) { dest[i] = ':'; dest[++i] = ' '; i++; } dest[i] = '\0'; return (dest); } /** * _strstr - The first occurrence of the substring needle in the str haystack * @haystack: The main string to be scanned * @needle: Is the small string to be searched with haystack *Return: A pointer to the first occurrence in haystack */ char *_strstr(char *haystack, char *needle) { int i; int j = 0; if (needle[j] == 0) return (haystack); for (i = 0; haystack[i] != 0; i++) { if (haystack[i] == needle[0]) { for (j = 0; needle[j] != 0; j++) { if (needle[j] != haystack[j + i]) break; } if (needle[j] == 0) { return (haystack + i); } } } return (haystack = '\0'); } /** * _strdup - duplicate a string * @str: String to duplicate *Return: A pointer to null-terminated byte string. */ char *_strdup(char *str) { unsigned int i; char *s; unsigned int size = 0; if (str == 0) return (0); for (i = 0; str[i] != 0; i++) { size += 1; } s = malloc(sizeof(char) * (size + 1)); if (s == 0) return (0); for (i = 0; i < size; i++) { s[i] = str[i]; } s[i] = 0; return (s); }
C
#include<stdio.h> int main() { char string[] = {"\x48\x45\x58\x20\x52\x6f\x63\x6b\x73\x21\x0a"}; printf("%s", string); return 0; }
C
#include "tluac-thread.h" #include "../tluac-epoll/tluac-epoll.h" #include "../util/produce-consume.h" int listenFd; void thread_new() { memset(&buffer, 0, sizeof(buffer) ); thread_create(); thread_wait(); } struct context ctxs[THREADS + 1]; void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); int i = 0; for (i = 1; i < THREADS + 1; i++) { init(&buffer[i]); ctxs[i].buffer = &buffer[i]; ctxs[i].threadId = i; ctxs[i].event_num = -1; if ((temp = pthread_create(&thread[i], NULL, thread_worker, &ctxs[i])) != 0) printf("线程 %d 创建失败!\n", i); else printf("线程 %d 被创建 buffer : %p %p\n", i, &ctxs[i], &buffer[i]); } struct context ctx_listen; ctxs[0] = ctx_listen; /*创建线程*/ if ((temp = pthread_create(&thread[0], NULL, thread_listen, &ctx_listen)) != 0) printf("线程 监听 创建失败!\n"); else printf("线程 监听 被创建\n"); } void thread_wait(void) { /*等待线程结束*/ int i = 0; for (; i < THREADS + 1; i ++) { if (thread[i] != 0) { pthread_join(thread[i], NULL); printf("线程 %d 已经结束\n", i); } } } void *thread_listen(void *arg) { listenFd = socket(AF_INET, SOCK_STREAM, 0); fcntl(listenFd, F_SETFL, O_NONBLOCK); // set non-blocking printf("server listen fd=%d\n", listenFd); // bind & listen sockaddr_in sin; bzero(&sin, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(8888); if (bind(listenFd, (const sockaddr*) &sin, sizeof(sin)) < 0){ printf("bind error [%d] %s\n", errno, strerror(errno)); } if (listen(listenFd, 5) < 0){ printf("listen error [%d] %s\n", errno, strerror(errno)); } int l_epollFd; // create epoll l_epollFd = epoll_create(MAX_EVENTS); if (l_epollFd <= 0) printf("create epoll failed.%d\n", l_epollFd); struct context *ctx = (struct context *)arg; ctx->epollFd = l_epollFd; printf("thread listen : %p %d %ld\n", ctx, listenFd,l_epollFd); // create & bind listen socket, and add to epoll, set non-blocking InitListenSocket(ctx, listenFd); epoll_new(ctx, 1); return (void *) 0; } void *thread_worker(void *arg) { struct context *ctx = (struct context*) arg; printf("thread : %p \n", ctx); luanew(ctx); luareg(ctx); luadofile(ctx, "t.lua"); epoll_new(ctx, 0); return (void *) 0; }
C
#include "adds.h" void validarOperacion(char mensaje [],char mensajeError[], int devolucion){ if(devolucion == 1){ printf("%s",mensaje); }else{ printf("%s",mensajeError); } } int getInt(char mensaje[],char mensajeError[],int piso, int techo){ int entero; printf("%s",mensaje); scanf("%d",&entero); while (entero < piso || entero>techo ){ printf("%s",mensajeError); scanf("%d",&entero); } return entero; } void getString(char mensaje[],char lugar[]){ printf("%s",mensaje); fflush(stdin); gets(lugar); } char getChar(char mensaje[]){ char caracter; printf("%s",mensaje); fflush(stdin); scanf("%c",&caracter); return caracter; }
C
void ft_putchar(char c) { write(1, &c, 1); } void ft_putstr(char *str) { while (*str != '\0') { ft_putchar(str); str++; } } void sastantua(int size) { int i; int space; int rows; int k; i = 1; space = 1; rows = 0; k = 0; while (i <= rows) { while (space <= (rows - i)) { ft_putchar(' '); space++; } while (k != (2 * i - 1)) { ft_putstr("* "); k++; } k = 0; ft_putchar('\n'); i++; } } int main(int argc, char **argv) { if (argc > 1) return (0); if (argv[1] == 0) return (0); sastantua(argv[1]); return (0); } void ft_putspaces(int space) { int col_nbr; col_nbr = 0; while (col_nbr < space) { ft_putchar(' '); col_nbr++; } } void ft_putrow(int size, int tier, int row_len, int row_nbr) { int col_nbr; col_nbr = 0; while (col_nbr < row_len) { if (col_nbr == 0) ft_putchar('/'); else if (col_nbr == row_len - 1) ft_putchar('\\'); else ft_putchar('*'); col_nbr++; } }
C
#include "Buses.h" #include "Processor.h" #include "MainMemory.h" #include <string.h> #include <stdlib.h> // Function that simulates the delivery of an address by means of the address bus // from a hardware component register to another hardware component register int Buses_write_AddressBus_From_To(int fromRegister, int toRegister) { int data; switch (fromRegister) { case MAINMEMORY: data=MainMemory_GetMAR(); break; case CPU: data=Processor_GetMAR(); break; default: return Bus_FAIL; } switch (toRegister) { case MAINMEMORY: MainMemory_SetMAR(data); break; default: return Bus_FAIL; } return Bus_SUCCESS; } // Function that simulates the delivery of memory word by means of the data bus // from a hardware component register to another hardware component register int Buses_write_DataBus_From_To(int fromRegister, int toRegister) { MEMORYCELL *data = (MEMORYCELL *) malloc(sizeof(MEMORYCELL)); switch (fromRegister) { case MAINMEMORY: MainMemory_GetMBR(data); break; case CPU: Processor_GetMBR(data); break; default: free(data); return Bus_FAIL; } switch (toRegister) { case MAINMEMORY: MainMemory_SetMBR(data); break; case CPU: Processor_SetMBR(data); break; default: free(data); return Bus_FAIL; } free(data); return Bus_SUCCESS; }
C
#ifndef _MY_SIMPLE_SORT #define _MY_SIMPLE_SORT #include <stdlib.h> #include <string.h> #define LT(a,b) ((a) < (b)) #define LQ(a,b) ((a) <= (b)) #define GT(a,b) ((a) > (b)) #define GQ(a,b) ((a) >= (b)) typedef void (*visitSqList)(int a); typedef void (*setArrayData)(void *target,char *data,int pos); typedef struct{ int *elemArray; int length; }SqList; typedef struct{ int data; int next; }BLNode; typedef struct{ BLNode *array; int length; }SLinkList; typedef struct elemLink{ int key; struct elemLink *next; }elemLink; //初始化线性列表 void InitSqList(SqList *sq,char *elems); //排序线性表(插入排序) void SortSqList(SqList *sq); //折半插入排序 void BInsertSort(SqList *sq); //二路查找排序 void TwoPartInsertSort(SqList *sq); //访问sqlist void VisitSqList(SqList sq,visitSqList vsq); //表插入排序 void TableInsertSort(SLinkList *sll,int *arr,int len); //表位置调整 void Arrange(SLinkList *sll); //访问表 void visitTableList(SLinkList sll,visitSqList vst); //初始化线性链表 void InitElemLink(elemLink *header,char *elems); //排序线性链表 void SortElemLink(elemLink *header); #endif
C
/* getuser.c A function in misclib. ------------------------------------------------------------------------ char *getuser(str) char *str; Returns the user's login name in str. The value is determined simply by looking up the current value of the environmental variable USER. Returns pointer to str, so can be used as an intermediary to feed char arguments to functions that expect strings. Example: getuser(username); if (strcmp(getuser(username),"hmonoyer") != 0) Written: 09/03/92 Randy Deardorff. USEPA Seattle. Modification log: (all changes are by the author unless otherwise noted) ------------------------------------------------------------------------ */ #include <stdio.h> #include <stdlib.h> #include <string.h> char *getuser(str) char *str; { strcpy(str, getenv ("USER")); return(str); }
C
#ifndef GREP_H #define GREP_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include "linkedList.h" /* -- Arguments (structure) Structure of arguments : options, pattern and files Cf. getArgs() */ typedef struct Arguments { Maillon* options; char* pattern; Maillon* files; } Arguments; /** --FileLine Structure of intel concerning the content of a file line by line members: -line(char*) : a string containing a line of the file -line_index(int) : the index of the line (starting at 1) -path(char*) : the path of the file **/ typedef struct FileLine { char* line; int line_index; char* path; } FileLine; Arguments* getArgs(int, char**); char* toLowerCase(char*); short int optExists(char*, int, char); short int optIsAdded(Maillon*, char); short int hasOption(char, Maillon*); short int isWholeWord(char*, char*, char*); int listSize(Maillon*); void addCharToStr(char**, int*, char); void displayFileLine(Maillon*, int, short); void displayWithOptions(Maillon*, Arguments*); Maillon* extractWithPattern(Maillon*, char*, short, short, short); Maillon* fileLoader(char*); Maillon* nFileLoader(Arguments*); #endif
C
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include "arm_neon.h" #define NUM_RANDOM 524288 // pow(2, 19) // NUM_RANDOM * 32 MACs #define NUM_REPEAT 256 // XNOR -> bitcount using ARMv7-A NEON intrinsics int main() { int * weight = (int *)malloc(sizeof(int) * NUM_RANDOM); int * inputs = (int *)malloc(sizeof(int) * NUM_RANDOM); int * tmp = (int *)malloc(sizeof(int) * 4); if (weight == NULL || inputs == NULL || tmp == NULL) { printf("not enough memory\n"); return -1; } for (int i = 0; i < NUM_RANDOM; ++i) { weight[i] = rand(); inputs[i] = rand(); } // weight, inputs frozen now struct timeval start, end; gettimeofday(&start, NULL); int zeros[] = {0, 0, 0, 0}; int bias_data[] = {-16, -16, -16, -16}; int tt_data[] = {2, 2, 2 ,2}; int32x4_t accum = vld1q_s32(zeros); int32x4_t bias = vld1q_s32(bias_data); int32x4_t tt = vld1q_s32(tt_data); for (int r = 0; r < NUM_REPEAT; ++r) { for (int i = 0; i < NUM_RANDOM; i += 4) { // xnor for (int j = 0; j < 4; ++j) { tmp[j] = ~(inputs[i + j] ^ weight[i + j]); } // pack char for_load[16]; for (int j = 0; j < 4; ++j) { int tmp_s8 = tmp[j]; for (int k = 0 ; k < 4; ++k) { for_load[j * 4 + k] = (char)(tmp_s8 & 0xFF); tmp_s8 >>= 8; } } // bitcount & accum accum = vaddq_s32(accum, vaddq_s32(vpaddlq_s16(vpaddlq_s8(vcntq_s8(vld1q_s8(for_load)))), bias)); } // times 2 accum = vmulq_s32(accum, tt); } gettimeofday(&end, NULL); printf("spent %lf seconds\n", end.tv_sec - start.tv_sec + (double)(end.tv_usec - start.tv_usec) / 1000000); free(weight); free(inputs); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct Node { int val; struct Node* left; struct Node* right; } Node_t; void insert(int key, Node_t** root) { if ((*root) == NULL) { (*root) = (Node_t*) malloc (sizeof(Node_t)); (*root)->val = key; (*root)->left = NULL; (*root)->right = NULL; } else { if (key < (*root)->val) insert(key, &(*root)->left); else insert(key, &(*root)->right); } } Node_t* search(int key, Node_t* root) { if (root == NULL || root->val == key) return root; else if (key < root->val) { return search(key, root->left); } else return search(key, root->right); } /**. The node existence in treee. */ int isChild(Node_t* root, Node_t* node) { if (!root) return 0; if (root == node) return 1; // Recursively traverse the tree to see if // the node matches the nodes in the tree. return isChild(root->left, node) || isChild(root->right, node); } Node_t* leastCommonAncestor(Node_t* root, Node_t* node1, Node_t* node2) { // Both node1 and node2 belongs to left side. if (isChild(root->left, node1) && isChild(root->left, node2)) return leastCommonAncestor(root->left, node1, node2); // Both node1 and node2 belongs to right side. else if(isChild(root->right, node1)&& isChild(root->right, node2)) return leastCommonAncestor(root->right, node1, node2); else return root; } Node_t* leastCommonAncestor2(Node_t* root, Node_t* node1, Node_t* node2) { if (!root) { return NULL; } if (root == node1 || root == node2) return root; Node_t* left = leastCommonAncestor2(root->left, node1, node2) ; Node_t* right = leastCommonAncestor2(root->right, node1, node2); if ((left == node1 && right == node2)||(left == node2 && right == node1)) return root; // I do not know why this line is here. return left? left : right; } void delete(int key, Node_t** root) { Node_t *prev; if ((*root) == NULL) return; else if (key == (*root)->val) { if ((*root)->left == NULL) { // free root prev = *root; (*root) = (*root)->right; free(prev); } else if ((*root)->right == NULL) { // free previous root; prev = *root; (*root) = (*root)->left; free(prev); } else { Node_t* trace = *root; Node_t* traceParent; while (trace->left) { traceParent = trace; trace = trace->left; } prev = trace; (*root)->val = trace->val; traceParent->right = trace->right; free(prev); } } else if (key < (*root)->val) { delete(key, &(*root)->left); } else delete (key, &(*root)->right); } void pre_order(Node_t* root) { if (root == NULL) return; printf("%d\n", root->val); pre_order(root->left); pre_order(root->right); } void in_order(Node_t* root) { if(root == NULL) return; in_order(root->left); printf("%d\n", root->val); in_order(root->right); } void post_order(Node_t* root) { if(root == NULL) return; post_order(root->left); post_order(root->right); printf("%d\n", root->val); } typedef struct LLNode { // LLNode(Node_t* t, struct LLNode* n) : next(n), tree(t) {} struct LLNode* next; Node_t* node; } LLNode_t; typedef struct ListOfLists { // ListOfLists() : next(NULL), data(NULL) {} struct ListOfLists* next; LLNode_t* data; }ListOfLists_t; int maxdepth(Node_t* root) { if (root == NULL) return 0; return maxdepth(root->left) > maxdepth(root->right) ? \ 1+maxdepth(root->left) : 1+maxdepth(root->right); } int mindepth(Node_t* root) { if (root == NULL) return 0; return maxdepth(root->left) < maxdepth(root->right) ? \ 1+maxdepth(root->left) : 1+maxdepth(root->right); } /* Pseudo code. * @brief Find the in-order successor of a node of a binary search * tree. Suppose each node has a link to its parent. * * If the node is root and has right child. The successor is its right * child's left most child. * * Otherwise the successor is the first node whose parent's left child is * itself. */ /* Node_t* inorderSuccessor(Node_t* node) { Node_t* par; if (node->parent == NULL || node->right != NULL) { return leftMostChild(node->right); } else { while (par = node->parent) { if (par->left == node) break; node = parent; } return par; } } Node_t* leftMostChild(Node_t* node) { if (!node) return NULL; // C language passes by value. while(node->left) node = node->left; return node; } */ int main() { Node_t* root = NULL; insert(5, &root); insert(2, &root); insert(6, &root); insert(4, &root); insert(7, &root); insert(1, &root); in_order(root); printf("MAX Depth = %d\nMIN Depth = %d\n", maxdepth(root), mindepth(root)); Node_t* index = search(2, root); printf("index (2) = %d\n", index->val); printf("------------------\n"); // delete(2, &root); in_order(root); printf("Test isChild.\n"); int key; for (key = 0; key < 10; key++) { Node_t* node = search(key, root); if (isChild(root, node)) printf("Node %d exists \n", key); else printf("Node %d does not exist\n", key); } printf("Test leastCommonAncestor\n"); Node_t* node1 = search(1, root); Node_t* node2 = search(4, root); Node_t* node3 = leastCommonAncestor2(root, node1, node2); printf("Ancestor for Node 1 and Node 4 is Node %d\n", node3->val); node2 = search(7, root); node3 = leastCommonAncestor2(root, node1, node2); printf("Ancestor for Node 1 and Node 7 is Node %d\n", node3->val); return 0; }
C
#include <msp430.h> /** * main.c */ int main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer PM5CTL0 &= ~LOCKLPM5; //unlocks the gpio pins P1DIR |= BIT0; //sets direction while(1){ P1OUT ^= BIT0; //toggles led __delay_cycles(1000000); //delays so we can see the led blink } return (0); }
C
#include <stdio.h> #include <stdlib.h> int main() { int i; int tamanho; char nome[50]; printf("Digite o nome\n"); scanf("%s",&nome); for(i=1; i<=50;i++){ if(*(nome+i)== NULL){ tamanho= i; break; } } for(i=0;i<tamanho;i++){ printf("\n%s",nome); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* output.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sghezn <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/27 20:58:55 by sghezn #+# #+# */ /* Updated: 2019/04/27 20:58:57 by sghezn ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" /* ** A function which reads a list of tetriminos from the file descriptor. */ t_list *ft_read(int fd, char current) { t_list *list; t_piece *piece; char *buffer; int len; int last; buffer = ft_strnew(21); list = NULL; while ((len = read(fd, buffer, 21)) >= 20) { last = len; if (!(piece = ft_construct_piece(buffer, current++, len))) { ft_memdel((void**)&buffer); return (ft_free_list(list)); } ft_lstadd(&list, ft_lstnew(piece, sizeof(t_piece))); ft_memdel((void**)&piece); } ft_memdel((void**)&buffer); if (len != 0 || (len == 0 && last == 21)) return (ft_free_list(list)); ft_lstrev(&list); return (list); } /* ** A function which frees a tetrimino. */ void ft_free_piece(t_piece *piece) { int i; i = 0; while (i < piece->y_len) { ft_memdel((void**)&(piece->arr[i])); i++; } ft_memdel((void**)&(piece->arr)); ft_memdel((void**)&piece); } /* ** A function which frees a list and returns NULL -- ** in case our input is invalid, or if we solved a map. */ t_list *ft_free_list(t_list *list) { t_list *ptr; t_piece *piece; while (list) { piece = (t_piece*)list->content; ptr = list->next; ft_free_piece(piece); ft_memdel((void**)&list); list = ptr; } return (NULL); } /* ** A function which frees a map. */ void ft_free_map(t_map *map) { int i; i = 0; while (i < map->size) ft_memdel((void**)&map->arr[i++]); ft_memdel((void**)&map->arr); ft_memdel((void**)&map); } /* ** A function which prints a map. */ void ft_print(t_map *map) { int i; i = 0; while (i < map->size) { ft_putstr(map->arr[i]); ft_putchar('\n'); i++; } }
C
#include<stdio.h> struct ListNode { int val; struct ListNode *next; }; struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { int nSum = 0,nL1 = 0,nL2 = 0; int nNodeCnt = 0; struct ListNode *result = NULL; struct _STACK { int val; struct _STACK *pre; }; struct ListNode *tmpl1 = l1; struct ListNode *tmpl2 = l2; struct _STACK *tmps1 = NULL; struct _STACK *tmps2 = NULL; if(NULL == l1 || NULL == l2) { return NULL; } while(NULL != tmpl1) { static nL1Cnt = 0; struct _STACK *sl1 = (struct _STACK*)malloc(sizeof(struct _STACK)); memset(sl1,0,sizeof(struct _STACK)); sl1->val = tmpl1->val; if(nL1Cnt) { sl1->pre = tmps1; } tmpl1 = tmpl1->next; tmps1 = sl1; nL1Cnt++; } while(NULL != tmpl2) { static nL2Cnt = 0; struct _STACK *sl2 = (struct _STACK*)malloc(sizeof(struct _STACK)); memset(sl2,0,sizeof(struct _STACK)); sl2->val = tmpl2->val; if(nL2Cnt) { sl2->pre = tmps2; } tmpl2 = tmpl2->next; tmps2 = sl2; nL2Cnt++; } while(NULL != tmps1) { struct _STACK *tmp = NULL; nL1 = nL1*10 + tmps1->val; tmp = tmps1; tmps1 = tmps1->pre; free(tmp); } while(NULL != tmps2) { struct _STACK *tmp = NULL; nL2 = nL2*10 + tmps2->val; tmp = tmps2; tmps2 = tmps2->pre; free(tmp); } nSum = nL1 + nL2; while(nSum) { static struct ListNode *tmp = NULL; int val = 0; val = nSum % 10; struct ListNode *newnode = (struct ListNode*)malloc(sizeof(struct ListNode)); memset(newnode,0,sizeof(struct ListNode)); newnode->val = val; newnode->next = NULL; if(nNodeCnt) { tmp->next = newnode; } else { result = newnode; } tmp = newnode; nSum = nSum / 10; nNodeCnt++; } return result; } int main(void) { int i = 0; struct ListNode l1[6] = {0}; struct ListNode l2[6] = {0}; struct ListNode* ret = NULL; for(i = 0; i < 5; i++) { l1[i].val = i+1; l1[i].next = &l1[i+1]; l2[i].val = i+1; l2[i].next = &l2[i+1]; } ret = addTwoNumbers(l1,l2); printf("sum list node is:"); while(ret) { printf("%d\t",ret->val); ret = ret->next; } return 0; }
C
/*Hay q hacerlo con valores conocidos para comprobarlo!!*/ /*Contemplar la posibilidad de q la muestra sea vacia * de q la muestra unicamente tenga un valor.... * Y demas situaciones q puedan ser problematicas*/ #include <stdio.h> #include <math.h> #include <unistd.h> #include <stdlib.h> /*0 es falso y verdadero el resto de los valores*/ struct lista{ int val,Fi; struct lista *sig; }*l,*lo; void error(char *s){ printf("%s",s); exit(1); } void add(struct lista *nodo){ struct lista *aux; if (l==NULL){ l=nodo; //printf("Insertado primero\n"); }else{ aux=l; while(aux->sig!=NULL){ aux=aux->sig; } aux->sig=nodo; //printf("Insertado\n"); } } void addOrd(struct lista *nodo){ struct lista *aux; if (lo==NULL){ lo=nodo; //printf("Insertado primero, lista vacia\n"); }else{ aux=lo; if(aux->val>nodo->val){ nodo->sig=aux; aux=nodo; printf("Primero insertado, lista vacia\n"); } while((aux->sig!=NULL)&&(nodo->val>=aux->sig->val)){ aux=aux->sig; } nodo->sig=aux->sig; aux->sig=nodo; //printf("Insertado ordenadamente\n"); } } void lista (struct lista *list){ struct lista *aux; aux=list; while(aux!=NULL){ printf("Numero nodo: %i\n",aux->val); printf("Frecuencia absoluta: %i\n",aux->Fi); printf("****************\n"); aux=aux->sig; } } struct lista *DevuelveDato (int x){ struct lista *aux; if (l!=NULL){ aux=l; while((aux!=NULL)&&(aux->val!=x)) { aux=aux->sig; } if(aux!=NULL){ return aux; }else{ return NULL; } }else{ return NULL; } } int EstaRepetido(struct lista *lis,int n){ struct lista *aux; if (lis!=NULL){ aux=lis; while((aux!=NULL)&&(aux->val!=n)) { aux=aux->sig; } if(aux!=NULL){ aux->Fi++; return 1; }else{ return 0; } }else{ //printf("lista vacia!!\n"); return 0; } } //Leemos el fichero completo void Read_Ln (void) { FILE *fich; int c; struct lista *aux; if((fich=fopen("./muestras.dat","r"))<0) error("No se ha podido abrir el fichero\n"); c=getc(fich); while (c!=EOF){ if(c!='\n') { c-=48; //printf("hola!!\n"); //OPTIMIZAR!!! if(!EstaRepetido(l,c)){ aux=(struct lista*)malloc(sizeof(struct lista)); aux->val=c; aux->Fi=1; add(aux); } } c=getc(fich); } fclose(fich); } //Inicializar todos las variables int n (struct lista *lis){ struct lista *aux; int a=0; if(lis!=NULL){ aux=lis; while(aux!=NULL){ a++; aux=aux->sig; } }else{ printf("La lista pasada esta vacia\n"); } return a; } int n2 (void){ struct lista *aux; int a=0; if(l!=NULL){ aux=l; while(aux!=NULL){ a+=aux->Fi; aux=aux->sig; } }else{ printf("La lista de desordenados esta vacia\n"); } return a; } float fi(int x){ struct lista *aux; float fi=0.0; aux=DevuelveDato(x); if (aux !=NULL) fi=(float)aux->Fi/n2(); return fi; } double MArit (void){ struct lista *aux; int aux2=0; double ma=0.0; if(l!=NULL){ aux=l; while(aux!=NULL){ aux2+=aux->val * aux->Fi; aux=aux->sig; } }else{ printf("LISTA VACIA!!!\n"); } ma=(double)aux2/n2(); return ma; } double MArm (void){ struct lista *aux; double mar=0.0, aux2=0.0, aux3=0.0; aux=l; while(aux!=NULL){ if(!aux->val) printf("Un valor de la muestra es cero\n"); aux2+=((double) 1/aux->val) * aux->Fi; aux=aux->sig; } mar=(double)aux2/n2(); return mar; } //PROBAR CON UNA MUESTRA Q SEPAMOS LOS VALORES!! double Dt (void){ struct lista *aux; double dt=0.0,ma=0.0,aux2=0.0,aux3=0.0; ma=MArit(); printf("media aritmetica %f\n",ma); aux=l; while(aux!=NULL){ aux2=aux->val - ma; aux2=aux2*aux2; //aux2=pow(aux->val - ma,2); aux2=aux->Fi * aux2; aux3+=aux2; aux=aux->sig; } aux3=(double)aux3/n2(); aux3=sqrt(aux3); return aux2; } //PROBAR CON UNA MUESTRA Q SEPAMOS LOS VALORES!! double Cv (void){ return ((double)Dt()/MArit()); } //PROBAR double Dm (void){ struct lista *aux; double dt=0.0,ma=0.0,aux2=0.0; ma=MArit(); aux=l; while(aux!=NULL){ aux2=fabs(aux->val - ma); aux2=aux->Fi * aux2; aux2+=aux2; aux=aux->sig; } aux2=(double)aux2/n2(); return aux2; } double Mediana (){ struct lista *aux; int cont=0,cont2=0; double res=0.0; if(lo!=NULL){ cont=n2(); //printf("Numero de elementos de lo: %i\n",cont); cont2=cont/2; aux=lo; while((aux!=NULL)&&(cont2-1>0)){ aux=aux->sig; cont2--; } if((cont%2==0)&&(aux!=NULL)){ res=(double)(aux->val + aux->sig->val)/2; return res; }else{ return (double)aux->sig->val; } } } //PROBAR double Ca (void){ FILE *fich; int c; struct lista *aux; double ma=0.0; //ma=MArit(); if((fich=fopen("./muestras.dat","r"))<0) error("No se ha podido abrir el fichero\n"); c=getc(fich); //lo=(struct lista *)malloc(sizeof(struct lista)); while (c!=EOF){ if(c!='\n') { c-=48; aux=(struct lista*)malloc(sizeof(struct lista)); aux->val=c; aux->Fi=0; addOrd(aux); } c=getc(fich); } fclose(fich); //lista(lo); return ((MArit()-Mediana())/Dt()); } //PROBAR double Cap(){ struct lista *aux; double dt=0.0,ma=0.0,aux2=0.0,inv=0.0; ma=MArit(); aux=l; while(aux!=NULL){ aux2=((double)aux->val - ma); aux2=aux->Fi * aux2; aux2+=aux2; aux=aux->sig; } aux2=(double)aux2/n2(); inv=((double)1/pow(Dt(),4)); aux2=inv * aux2; return aux2; } /*void comprueba (void){ if (!n(l)-n2()){ printf("Los indices son iguales\n"); }else{ printf("ERROR\n"); } }*/ Fi(){ struct lista *aux; aux=l; while(aux!=NULL){ printf("Xi es: %i Y la Fi: %i\n",aux->val,aux->Fi); aux=aux->sig; } } int main (int argc, char *argv[]) { int a=2; Read_Ln(); /*lista(l); printf("Frecuencia relativa de %i: %f\n",a,fi(a)); printf("Media aritmetica: %f\n",MArit()); printf("Media armonica %f\n",MArm());*/ //printf("Desviacion tipica: %f\n",Dt()); /*printf("Coeficiente de asimetria: %f\n",Ca()); printf("Coeficiente de variacion: %f\n",Cv()); printf("Desviacion media: %f\n",Dm()); printf("Coeficiente de apuntamiento: %f\n",Cap()); printf("Mediana: %f\n",Mediana());*/ Fi(); free(l); return 0; }
C
// write a program to compute the sum and mean of the elements of a two-dimensional array #include <stdio.h> int main() { int num[5][5], sum[5] = {0, 0, 0, 0, 0}; float mean[5] = {0.0, 0.0, 0.0, 0.0, 0.0}; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("num[%d][%d] = ", i, j); scanf("%d", &num[i][j]); } } printf("\n\nsum of the numbers in column wise : \n\n"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { sum[i] += num[i][j]; } } for (int i = 0; i < 5; i++) mean[i] = sum[i] / 2; for (int i = 0; i < 5; i++) { printf("sum[%d] = %d mean[%d] = %.2f\n", i, sum[i], i, mean[i]); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ecruz-go <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/16 14:19:12 by ecruz-go #+# #+# */ /* Updated: 2021/04/16 14:19:13 by ecruz-go ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /** * Realiza una iteración sobre la lista ’lst’ y aplica * la función ’f’ al contenido de cada elemento. Crea * una nueva lista que resulta de las aplicaciones * sucesivas de ’f’. Disponemos de la función ’del’ si * hay que elminar el contenido de algún elemento. */ t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)) { t_list *lstresult; t_list *elem; t_list *aux; lstresult = NULL; if (lst) { elem = ft_lstnew(f(lst->content)); if (!elem) return (NULL); lstresult = elem; aux = lst->next; while (aux) { elem = ft_lstnew(f(aux->content)); if (!elem) { ft_lstclear(&lst, del); return (NULL); } aux = aux->next; ft_lstadd_back(&lstresult, elem); } } return (lstresult); }
C
#define ALIEN_DEFORMATION_MAX_VERTICES 16 enum { AlienDeformDirectionForward, AlienDeformDirectionBackwards}; typedef struct { unsigned int Frame, Frames, Direction; float OriginalPosition[3], DeformedPosition[3]; } structAlienDeformationPoint; typedef struct { unsigned int VerticeIndexes[ALIEN_DEFORMATION_MAX_VERTICES], MinFrames, MaxFrames, VerticeCount; float MinDistance, MaxDistance; structAlienDeformationPoint DeformationPoints[ALIEN_MAX_COUNT][ALIEN_DEFORMATION_MAX_VERTICES]; } structAlienDeformation; /////////////////////////////////////////////////////////////////////// structAlienDeformation gKinaDeformation = { .VerticeIndexes = { 7,8,9,10, 20,21,22,23, 33,34,35,36, 46,47,48,49}, .VerticeCount = 16, .MinDistance = -0.25f, .MaxDistance = 0.25f, .MinFrames = 10, .MaxFrames = 20 }; /////////////////////////////////////////////////////////////// void AlienDeformationReset(unsigned int deformationIndex, unsigned int alienIndex) { // Set random offset on the Vertice for (unsigned int xyz = 0; xyz < 3; xyz++) { float delta; randMinMaxFloat(gKinaDeformation.MinDistance, gKinaDeformation.MaxDistance, &delta); gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].DeformedPosition[xyz] = gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].OriginalPosition[xyz] + delta; } // Set the time to a random value randMinMax(gKinaDeformation.MinFrames, gKinaDeformation.MaxFrames, &gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frames); gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frame = 0; gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Direction = AlienDeformDirectionForward; } void AlienDeformationPointInitialise(unsigned int deformationIndex, unsigned int alienIndex) { for (unsigned int xyz = 0; xyz < 3; xyz++) { gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].OriginalPosition[xyz] = gAliens[alienIndex].Vertices[(gKinaDeformation.VerticeIndexes[deformationIndex] * 3) + xyz]; } AlienDeformationReset(deformationIndex, alienIndex); } void AlienDeformationInitialise(unsigned int alienIndex) { for (unsigned int dd = 0; dd < gKinaDeformation.VerticeCount; dd++) { AlienDeformationPointInitialise(dd, alienIndex); } // gAliens[alienIndex].DeformationOriginalPointsSet = TRUE; } //////////////////////////////////////// void AlienDeformPoint(unsigned int deformationIndex, unsigned int alienIndex) { float deltaRatio = (float)gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frame / (float)gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frames; for (unsigned int xyz = 0; xyz < 3; xyz++) { float originalPos = gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].OriginalPosition[xyz], delta = (gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].DeformedPosition[xyz] - originalPos) * deltaRatio; gAliens[alienIndex].Vertices[(gKinaDeformation.VerticeIndexes[deformationIndex] * 3) + xyz] = originalPos + delta; } // Ping pong effect gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frame += (gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Direction == AlienDeformDirectionForward) ? 1 : -1; if (gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frame == gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frames) { gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Direction = AlienDeformDirectionBackwards; } if (gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Frame == 0 && gKinaDeformation.DeformationPoints[alienIndex][deformationIndex].Direction == AlienDeformDirectionBackwards) { AlienDeformationReset(deformationIndex, alienIndex); } } void AlienDeform(unsigned int alienIndex) { for (unsigned int dd = 0; dd < gKinaDeformation.VerticeCount; dd++) { AlienDeformPoint(dd, alienIndex); } }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <time.h> #include <sys/time.h> #include <stdlib.h> #include <sys/select.h> #include "protocol.h" #define TIMEOUT_INTERVAL 1E5 #define EMPTY 0 #define WAITING 1 #define ACKED 2 #define OUT_OF_ORDER 3 #define TIMEOUT 4 struct segment *SEGs[MAX_SEG_NUM]; int status[MAX_SEG_NUM]; double time_difference(struct timeval *start_time) { double start_us = (double)start_time->tv_sec * 1E6 + start_time->tv_usec; struct timeval now_time; gettimeofday(&now_time, NULL); double now_us = (double)now_time.tv_sec * 1E6 + now_time.tv_usec; return now_us - start_us; } int ACK_ready(int sockfd, int sec, int usec) { fd_set rfds; struct timeval tv; FD_ZERO(&rfds); FD_SET(sockfd, &rfds); tv.tv_sec = sec; tv.tv_usec = usec; if(select(sockfd + 1, &rfds, NULL, NULL, &tv)) return 1; return 0; } int main(int argc, char **argv) // IP, PORT, source file { int AGENT_SENDER_PORT = atoi(argv[2]); struct sockaddr_in agent_sender; int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); agent_sender.sin_family = AF_INET; agent_sender.sin_port = htons(AGENT_SENDER_PORT); inet_aton(argv[1], &agent_sender.sin_addr); int agent_sender_len = sizeof(agent_sender); struct segment SEG_SYN, SEG_SYNACK; SEG_SYN.HDR.SYN = 1; SEG_SYN.HDR.ACK = 0; sendto(sockfd, &SEG_SYN, sizeof(struct segment), 0, &agent_sender, sizeof(agent_sender)); puts("send\tSYN"); recvfrom(sockfd, &SEG_SYNACK, sizeof(struct segment), 0, &agent_sender, &agent_sender_len); puts("receive\tSYNACK"); int sender_port = SEG_SYNACK.HDR.dest_port; FILE *input = fopen(argv[3], "rb"); clock_t start_time; int cwnd = 1; int ssthresh = 16; int base = 1; int Seq_FIN = MAX_SEG_NUM + 1; while(base != Seq_FIN) { puts("****************************************"); printf("base = %d cwnd = %d\n", base, cwnd); int i; for(i = base; i < base + cwnd && i < Seq_FIN; i++) { if(status[i] == EMPTY) { struct segment *SEG = (struct segment *)malloc(sizeof(struct segment)); SEG->HDR.source_port = sender_port; SEG->HDR.dest_port = AGENT_SENDER_PORT; SEG->HDR.data_length = fread(SEG->data, sizeof(char), MAX_DATA_SIZE, input); if(SEG->HDR.data_length == 0) Seq_FIN = i; else { if(feof(input)) Seq_FIN = i + 1; // make a new segment SEG->HDR.Seq = i; SEG->HDR.ACK = 0; SEGs[i] = SEG; printf("send\tdata\t#%d\twinSize = %d\n", i, cwnd); sendto(sockfd, SEG, sizeof(struct segment), 0, &agent_sender, sizeof(agent_sender)); } } else // retransmit because of timeout or out of order { printf("resnd\tdata\t#%d\twinSize = %d\n", i, cwnd); sendto(sockfd, SEGs[i], sizeof(struct segment), 0, &agent_sender, sizeof(agent_sender)); } status[i] = WAITING; } // monitor if sockfd become ready for recv struct timeval start_time; gettimeofday(&start_time, NULL); int ACK_num = 0; while(time_difference(&start_time) <= TIMEOUT_INTERVAL && ACK_num != cwnd) { if(ACK_ready(sockfd, 0, 1000)) { struct segment SEG_ACK; recvfrom(sockfd, &SEG_ACK, sizeof(struct segment), 0, &agent_sender, &agent_sender_len); printf("recv\tack\t#%d\n", SEG_ACK.HDR.ACK); status[SEG_ACK.HDR.ACK] = ACKED; ACK_num++; } } if(ACK_num == cwnd || ACK_num == (Seq_FIN - base)) { base = base + ACK_num; if(cwnd >= ssthresh) cwnd = cwnd + 1; else cwnd *= 2; } else { // timeout int gap = 0; for(i = base; i < base + cwnd && i < Seq_FIN; i++) { if(status[i] == WAITING) { status[i] = TIMEOUT; if(gap == 0) gap = i; } if(status[i] == ACKED) { if(gap == 0) free(SEGs[i]); // This segment has been sent successfully else status[i] = OUT_OF_ORDER; } } base = gap; if(cwnd > 2) ssthresh = cwnd / 2; else ssthresh = 1; cwnd = 1; printf("time out\tthreshold = %d\n", ssthresh); } } fclose(input); // send FIN struct segment SEG_FIN; SEG_FIN.HDR.source_port = sender_port; SEG_FIN.HDR.dest_port = AGENT_SENDER_PORT; SEG_FIN.HDR.FIN = 1; SEG_FIN.HDR.ACK = 0; printf("send\tfin\n"); sendto(sockfd, &SEG_FIN, sizeof(struct segment), 0, &agent_sender, sizeof(agent_sender)); while(!ACK_ready(sockfd, 1, 0)) sendto(sockfd, &SEG_FIN, sizeof(struct segment), 0, &agent_sender, sizeof(agent_sender)); struct segment SEG_FINACK; recvfrom(sockfd, &SEG_FINACK, sizeof(struct segment), 0, &agent_sender, &agent_sender_len); if(SEG_FINACK.HDR.FIN == 1 && SEG_FINACK.HDR.ACK == 1) printf("recv\tfinack\n"); close(sockfd); return 0; }
C
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<stdlib.h> void main() { printf("pid : %d!\n" , getpid()) ; printf("uid : %d!\n" , getuid()) ; printf("groupid : %d\n" , getgid()) ; printf("groupid : %d\n" , gettid()) ; printf("groupid : %d\n" , getppid()) ; printf("environment variable(USER): %s\n", getenv("USER")) ; }
C
#include <stdio.h> #include "holberton.h" /** * print_array - print a elements of an array. * @a: the array in a parameter * @n: Is the length of the array * */ void print_array(int *a, int n) { int i; for (i = 0; i < n; i++) { if (i != n - 1) { printf("%d, ", a[i]); } else printf("%d", a[i]); } printf("\n"); }
C
// Changes some entries in the palette, starting at index color_index /* e.g. "TERM=xterm-256color ./test_colors 3366FF FF0000 3a4682" */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ncurses.h> #include <unistd.h> int main(int argc, char* argv[]) { int i; initscr(); start_color(); if (!can_change_color()) { printw("can't change colors :(\n"); refresh(); sleep(2); endwin(); exit(0); }; printw("can change colors.\n"); printw("%d colors, %d pairs available\n", COLORS, COLOR_PAIRS); int color_index = 3; int pair_index = 2; double magic = 1000/255.0; /* init_color( */ for(i = 1; i < argc; ++i) { const char* hexcolor = argv[i]; int r, g, b; if (hexcolor[0] == '#') { ++hexcolor; } sscanf(hexcolor, "%02x%02x%02x", &r, &g, &b); init_color(color_index, (int)(r * magic), (int)(g * magic), (int)(b * magic)); init_pair(pair_index, color_index, 0); attrset(COLOR_PAIR(pair_index)); printw("#%02x%02x%02x\n", r, g, b); refresh(); ++pair_index; ++color_index; } getch(); endwin(); }
C
#if defined(_WIN32) #include <windows.h> #include <wincrypt.h> typedef unsigned int uint32_t; #else #include <stdint.h> #endif #include <string.h> #include <stdio.h> #include "ed25519-donna.h" #include "ed25519-ref10.h" static void print_diff(const char *desc, const unsigned char *a, const unsigned char *b, size_t len) { size_t p = 0; unsigned char diff; printf("%s diff:\n", desc); while (len--) { diff = *a++ ^ *b++; if (!diff) printf("____,"); else printf("0x%02x,", diff); if ((++p & 15) == 0) printf("\n"); } printf("\n"); } static void print_bytes(const char *desc, const unsigned char *bytes, size_t len) { size_t p = 0; printf("%s:\n", desc); while (len--) { printf("0x%02x,", *bytes++); if ((++p & 15) == 0) printf("\n"); } printf("\n"); } /* chacha20/12 prng */ void prng(unsigned char *out, size_t bytes) { static uint32_t state[16]; static int init = 0; uint32_t x[16], t; size_t i; if (!init) { #if defined(_WIN32) HCRYPTPROV csp = NULL; if (!CryptAcquireContext(&csp, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { printf("CryptAcquireContext failed\n"); exit(1); } if (!CryptGenRandom(csp, (DWORD)sizeof(state), (BYTE*)state)) { printf("CryptGenRandom failed\n"); exit(1); } CryptReleaseContext(csp, 0); #else FILE *f = NULL; f = fopen("/dev/urandom", "rb"); if (!f) { printf("failed to open /dev/urandom\n"); exit(1); } if (fread(state, sizeof(state), 1, f) != 1) { printf("read error on /dev/urandom\n"); exit(1); } #endif init = 1; } while (bytes) { for (i = 0; i < 16; i++) x[i] = state[i]; #define rotl32(x,k) ((x << k) | (x >> (32 - k))) #define quarter(a,b,c,d) \ x[a] += x[b]; t = x[d]^x[a]; x[d] = rotl32(t,16); \ x[c] += x[d]; t = x[b]^x[c]; x[b] = rotl32(t,12); \ x[a] += x[b]; t = x[d]^x[a]; x[d] = rotl32(t, 8); \ x[c] += x[d]; t = x[b]^x[c]; x[b] = rotl32(t, 7); for (i = 0; i < 12; i += 2) { quarter( 0, 4, 8,12) quarter( 1, 5, 9,13) quarter( 2, 6,10,14) quarter( 3, 7,11,15) quarter( 0, 5,10,15) quarter( 1, 6,11,12) quarter( 2, 7, 8,13) quarter( 3, 4, 9,14) }; if (bytes <= 64) { memcpy(out, x, bytes); bytes = 0; } else { memcpy(out, x, 64); bytes -= 64; out += 64; } /* don't need a nonce, so last 4 words are the counter. 2^136 bytes can be generated */ if (!++state[12]) if (!++state[13]) if (!++state[14]) ++state[15]; } } typedef struct random_data_t { unsigned char sk[32]; unsigned char m[128]; } random_data; typedef struct generated_data_t { unsigned char pk[32]; unsigned char sig[64]; int valid; } generated_data; static void print_generated(const char *desc, generated_data *g) { printf("%s:\n", desc); print_bytes("pk", g->pk, 32); print_bytes("sig", g->sig, 64); printf("valid: %s\n\n", g->valid ? "no" : "yes"); } static void print_generated_diff(const char *desc, const generated_data *base, generated_data *g) { printf("%s:\n", desc); print_diff("pk", base->pk, g->pk, 32); print_diff("sig", base->sig, g->sig, 64); printf("valid: %s\n\n", (base->valid == g->valid) ? "___" : (g->valid ? "no" : "yes")); } int main() { const size_t rndmax = 128; static random_data rnd[128]; static generated_data gen[3]; random_data *r; generated_data *g; unsigned long long dummylen; unsigned char dummysk[64]; unsigned char dummymsg[2][128+64]; size_t rndi, geni, i, j; uint64_t ctr; printf("fuzzing: "); printf(" ref10"); printf(" ed25519-donna"); #if defined(ED25519_SSE2) printf(" ed25519-donna-sse2"); #endif printf("\n\n"); for (ctr = 0, rndi = rndmax;;ctr++) { if (rndi == rndmax) { prng((unsigned char *)rnd, sizeof(rnd)); rndi = 0; } r = &rnd[rndi++]; /* ref10, lots of horrible gymnastics to work around the wonky api */ geni = 0; g = &gen[geni++]; memcpy(dummysk, r->sk, 32); /* pk is appended to the sk, need to copy the sk to a larger buffer */ crypto_sign_pk_ref10(dummysk + 32, dummysk); memcpy(g->pk, dummysk + 32, 32); crypto_sign_ref10(dummymsg[0], &dummylen, r->m, 128, dummysk); memcpy(g->sig, dummymsg[0], 64); /* sig is placed in front of the signed message */ g->valid = crypto_sign_open_ref10(dummymsg[1], &dummylen, dummymsg[0], 128 + 64, g->pk); /* ed25519-donna */ g = &gen[geni++]; ed25519_publickey(r->sk, g->pk); ed25519_sign(r->m, 128, r->sk, g->pk, g->sig); g->valid = ed25519_sign_open(r->m, 128, g->pk, g->sig); #if defined(ED25519_SSE2) /* ed25519-donna-sse2 */ g = &gen[geni++]; ed25519_publickey_sse2(r->sk, g->pk); ed25519_sign_sse2(r->m, 128, r->sk, g->pk, g->sig); g->valid = ed25519_sign_open_sse2(r->m, 128, g->pk, g->sig); #endif /* compare implementations 1..geni against the reference */ for (i = 1; i < geni; i++) { if (memcmp(&gen[0], &gen[i], sizeof(generated_data)) != 0) { printf("\n\n"); print_bytes("sk", r->sk, 32); print_bytes("m", r->m, 128); print_generated("ref10", &gen[0]); print_generated_diff("ed25519-donna", &gen[0], &gen[1]); #if defined(ED25519_SSE2) print_generated_diff("ed25519-donna-sse2", &gen[0], &gen[2]); #endif exit(1); } } /* print out status */ if (ctr && (ctr % 0x1000 == 0)) { printf("."); if ((ctr % 0x20000) == 0) { printf(" ["); for (i = 0; i < 8; i++) printf("%02x", (unsigned char)(ctr >> ((7 - i) * 8))); printf("]\n"); } } } }
C
#include <stdio.h> #include <ctype.h> int main(){ int index=0; char target; char new; scanf ("%c", &target); if (isdigit(target)) { index=target-48; scanf ("%c",&target); scanf ("%c",&target); } scanf ("%c",&new); //printf ("index %d, target %c\n", index,target); int i; for (i=index; new!=target;i++){ scanf ("%c",&new); if (new==' ') scanf ("%c",&new); //printf ("%c is %d, %c not %c\n",new,i,new,target); } printf ("%d\n",i-1); return 0; }
C
/*输入三角形的三边长求三角形的面积 * 参数:double a,b,c * */ #include <stdio.h> #include <math.h> int main() { double a,b,c,s,area; printf("input three wigth:"); scanf("%lf%lf%lf",&a,&b,&c); s=(a+b+c)/2; area=sqrt(s*(s-a)*(s-b)*(s-c)); printf("%f\t%f\t%f,area=%f\n",a,b,c,area); return getchar(); }
C
// // main.c // q3.c // // Created by Jacqueline Liao on 3/2/19. // Copyright © 2019 Jacqueline Liao. All rights reserved. // #include <stdio.h> #include <string.h> int main(int argc, const char * argv[]) { int phrase_length = 0; for (int i = 1; i < argc; ++i) { phrase_length += strlen(argv[i]); } //checking length of entire phrase char str[phrase_length]; //allocating array for entire phrase, no spaces for (int i = 1; i < argc; ++i) {//turning phrase into one array if (i== 1) { strcpy(str, argv[i]); } else { strcat(str, argv[i]); } } int begin = 0; //used as forward-looking checker in palindrome checker int end = strlen(str) - 1; //used as backward-looking checker in palindrome checker char final_str[phrase_length + argc];//build original phrase back up, including spaces, to print for (int i = 1; i < argc; ++i) { if (i== 1) { strcpy(final_str, argv[i]); strcat(final_str, " "); } else { strcat(final_str, argv[i]); strcat(final_str, " "); } } final_str[strlen(final_str)-1] = 0;//getting rid of last space while (end > begin) { //palindrome checker if (str[begin++] != str[end--]) { printf("\"%s\" is NOT a palindrome!\n", final_str); return 0; } } printf("\"%s\" is a palindrome!\n", final_str); }
C
#include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { int d = get_int(); int board[d][d], vmax =(d*d)-1 ; for (int i =0; i<d; i++) { for (int j=0; j<d; j++) { board[i][j] = vmax; vmax--; } } if (d%2 == 0) { int temp =0; temp = board[d-1][d-2]; board[d-1][d-2] =board[d-1][d-3]; board[d-1][d-3] = temp; } for (int i =0; i<d; i++) { for (int j=0; j<d; j++) { if (board[i][j]!=0) { printf("\t %2i", board[i][j]); } else printf(" "); } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int i; /* e n pܼ */ double dtotal, dx; int n; /* ϥΪ̿J n */ printf("Jn[`: "); scanf("%d", &n); for (dtotal=0, dx=1, i=1; i <= n; i++, dx *= 2.0) { dtotal += 1.0/dx; /* [` 1/(2^i) */ printf("e %2d `M = %f\n", i,dtotal); } system("pause"); return(0); }
C
#include "stack.h" void initStack(Stack **p) { (*p) = NULL; } int EmptyStack(Stack* p) { if ( p == NULL) return 1; else return 0; } Elm top(Stack* p) { if (!EmptyStack(p)) return p->info; else printf("Eror: Stack Kosong! "); } void push(Stack** p, Elm e) { Stack* q; q = (Stack*)malloc(sizeof(Stack)); q->info = e; q->svt = (*p); (*p) = q; } void pop(Stack** p, Elm* e) { Stack *top; top = (*p); (*p) = top->svt; *e = top->info; free(top); } Stack* infixtoPostfix(Elm* t, int n) { Stack *p, *r; Elm x; int i; initStack(&p); initStack(&r); for(i = 0; i < n; i++) { if(operande(t[i])) push(&r, t[i]); else if(operateur(t[i])) { while((!EmptyStack(p))&&(operateur(top(p)))&&(priorite(t[i]) >= priorite(top(p)))) { pop(&p, &x); push(&r, x); } push(&p, t[i]); } else if(t[i].val == 6.0) push(&p, t[i]); else { while((!EmptyStack(p)) && !((top(p).val == 6.0)&&(!top(p).operand))) { pop(&p, &x); push(&r, x); } pop(&p, &x); } } while(!EmptyStack(r)) { pop(&r, &x); push(&p, x); } return p; } void PrintStack(Stack* p, Stack* r) { printf("\t[ p ]\t\t[ r ]\n"); /*on va traiter les piles comme des liste chaines simples pour ne pas perdre les élément*/ Stack* pTmp; Stack* rTmp; for( pTmp = p, rTmp = r; (pTmp)&&(rTmp); pTmp = pTmp->svt, rTmp = rTmp->svt) { printf("\t"); afficheElm(pTmp->info); printf("\t\t"); afficheElm(rTmp->info); printf("\n"); } for( ;(pTmp); pTmp = pTmp->svt) { printf("\t"); afficheElm(pTmp->info); printf("\n"); } for( ;(rTmp); rTmp = rTmp->svt) { printf("\t\t\t"); afficheElm(rTmp->info); printf("\n"); } } double Evaluate(Stack** p) { Elm resultat, x, x1, x2; resultat.operand = 1; Stack *r; initStack(&r); while(!EmptyStack((*p))) { PrintStack( *p, r); pop(p, &x); if (operande(x)) push(&r, x); else { pop(&r, &x2); pop(&r, &x1); resultat.val = operation(x1, x, x2); push(&r, resultat); } //printf("----------------------------------\n"); } return top(r).val; }
C
#include<stdio.h> #include<stdlib.h> /* * This is an enum. Also called an enumerable set. * By default, they are assigned values starting with 0, * unless custom values are specified. * If we assign the value 3 to mon, and no other values * for the consecutive constants, the values 4, 5 6 and so on * will be assigned. Custom values for each constant can also * be assigned. Note that only integer values can be used. */ //Globally declared enums. enum days { mon = 1, tue, wed, thu, fri, sat, sun }; enum directions { north = 0, north_east = 45, east = 90, south_east = 135, south = 180, south_west = 225, west = 270, north_west = 315}; void which_day(void); void which_direction(void); int main(void) { which_day(); which_direction(); exit(EXIT_SUCCESS); } void which_day(void) { unsigned char day_of_week; printf("What day is it?\n"); printf("1\tMonday\n"); printf("2\tTuesday\n"); printf("3\tWednesgay\n"); printf("4\tThursday\n"); printf("5\tFriday\n"); printf("6\tSaturday\n"); printf("7\tSunday\n"); printf("[1/2/3/4/5/6/7]?\n: "); scanf("%hhd", &day_of_week); switch(day_of_week) { case mon: printf("It's Monday.\n"); break; case tue: printf("It's Tuesday.\n"); break; case wed: printf("It's Wednesday.\n"); break; case thu: printf("It's Thursday.\n"); break; case fri: printf("It's Friday.\n"); break; case sat: printf("It's Saturday.\n"); break; case sun: printf("It's Sunday.\n"); default: printf("I don't know that day.\n"); } } void which_direction(void) { unsigned short direction; printf("Which direction are you facing?\n"); printf("1\t North\n"); printf("2\t North-East\n"); printf("3\t East\n"); printf("4\t South-East\n"); printf("5\t South\n"); printf("6\t South-West\n"); printf("7\t West\n"); printf("8\t North-West\n"); printf("[1/2/3/4/5/6/7/8]?\n: "); scanf("%hd", &direction); switch(direction) { case 1: printf("North is %hd degrees.\n", north); break; case 2: printf("North-East is %hd degrees.\n", north_east); break; case 3: printf("East is %hd degrees.\n", east); break; case 4: printf("South-East is %hd degrees.\n", south_east); break; case 5: printf("South is %hd degrees.\n", south); break; case 6: printf("South-West is %hd degrees.\n", south_west); break; case 7: printf("West is %hd degrees.\n", west); break; case 8: printf("North-West is %hd degrees.\n", north_west); break; default: printf("I don't know that direction.\n"); } }
C
#include <string.h> #include <stdio.h> int my_strlen(char str[]); main() { char str[20]="paidikumar"; int i; i = my_strlen(str); printf("strlen--->=%d\n",i); } int my_strlen(char str[]) { int i=0; while(str[i]!='\0') i++; return i; } /*#include <string.h> #include <stdio.h> main() { char str[20]="paidikumar"; int i=0; while(str[i]!='\0') i++; printf("strlen--->=%d\n",i); } */
C
#include <stdio.h> int main() { int * a = NULL; printf("%d", *a); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> #include<unistd.h>  #include "book.h" #include "account.h" #include "borrowreturn.h" #include "menu.h" void borrow(){ char pa[10],pa1[10]; char us[10],bn[10]; char i; int f=0; FILE *fp; account *p; book *p1,*head; p=loadaccount(); printf("Please enter your username.\n"); gets(us); while(p!=NULL){ if(p!=NULL&&strcmp(us,p->usrname)==0){ printf("Please enter password.\n"); scanf("%s",pa); getchar(); if(strcmp(pa,p->password)==0){ printf("Verification passed.\n"); break; } else{ printf("Verification failed.Soon back menu.\n"); Sleep(3000); menu(); } } p=p->next; } if(p==NULL){ printf("This user is not existed.Soon back menu.\n"); Sleep(3000); menu(); } head=loadbook(); p1=head; printf("Please enter the name of book that you want.\n"); gets(bn); while(p1->next!=NULL){ if(p1->next!=NULL&&strcmp(bn,p1->name)==0){ printf("Number:%s Name:%s Author:%s Publisher:%s Status:%d Borrower:%s \n",p1->number,p1->name,p1->author,p1->publisher,p1->l,p1->f); if(p1->l==0){ printf("This book is been borrowed.\n"); printf("Press any key to back menu.\n"); getch(); menu(); } else{ printf("Press 1 to confirm | Press 2 to continue \n"); } f=1; while(1){ i=getch(); if(i=='1'){ p1->l=0; strcpy(p1->f,p->usrname); fp=fopen("book.txt","w"); fclose(fp); p1=head; do{ savebook(p1); p1=p1->next; }while(p1->next!=NULL); printf("Succeed.\n"); printf("Press any key to back menu.\n"); getch(); menu(); } if(i=='2'){ f=0; break; } } } p1=p1->next; } if(f==0){ printf("No more result.Press any key to back menu.\n"); getch(); menu(); } } void returnbook(){ char pa[10],pa1[10]; char us[10],bn[10]; char i; int f=0; FILE *fp; account *p; book *p1,*head; p=loadaccount(); printf("Please enter your username.\n"); gets(us); while(p!=NULL){ if(p!=NULL&&strcmp(us,p->usrname)==0){ printf("Please enter password.\n"); scanf("%s",pa); getchar(); if(strcmp(pa,p->password)==0){ printf("Verification passed.\n"); break; } else{ printf("Verification failed.Soon back menu.\n"); Sleep(3000); menu(); } } p=p->next; if(p==NULL){ printf("This user is not existed.Soon back menu.\n"); Sleep(3000); menu(); } } head=loadbook(); p1=head; printf("Please enter the name of book that you want to return.\n"); gets(bn); while(p1->next!=NULL){ if(p1->next!=NULL&&strcmp(bn,p1->name)==0){ f=1; printf("Number:%s Name:%s Author:%s Publisher:%s Status:%d Borrower:%s \n",p1->number,p1->name,p1->author,p1->publisher,p1->l,p1->f); printf("Press 1 to confirm | Press 2 to continue \n"); } while(1){ i=getch(); if(i=='1'){ if(strcmp(us,p1->f)!=0){ printf("You have not borrowed this book.\n"); printf("Press any key to back menu.\n"); getch(); menu(); } p1->l=1; strcpy(p1->f,"N"); fp=fopen("book.txt","w"); fclose(fp); if(fp==NULL){ printf("loading is failed"); } p1=head; do{ savebook(p1); p1=p1->next; }while(p1->next!=NULL); printf("Succeed.\n"); printf("Press any key to back menu.\n"); getch(); menu(); } if(i=='2'){ f=0; break; } } p1=p1->next; } if(f==0){ printf("No more result.Press any key to back menu.\n"); getch(); menu(); } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #define MAXLINE 1000 #define MAXOP 100 #define NUMBER '0' int getop(char[]); void push(double); double pop(void); void main( void ){ int type; double op2; char s[MAXOP]; while( (type = getop(s)) != EOF){ switch(type){ case NUMBER: push( atof(s) ); break; case '+': push( pop() + pop() ); break; case '*': push( pop() * pop() ); break; case '-': op2 = pop(); push( pop() - op2 ); break; case '/': op2 = pop(); if(op2 != 0.0){ push( pop() / op2 ); } else { printf("division by zero"); } break; case '\n': printf("result: %g", pop()); break; default: printf("result: %g", pop()); break; } } } int sp = 0; void push( double f ){ if( sp < MAXVAL ) }
C
/* * mpi_communication.c * * Created on: 2015年7月7日 * Author: ron */ #include <stdio.h> #include <assert.h> #include <mpi.h> #include <stdlib.h> #include "../structure_tool/log.h" #include "mpi_communication.h" static void printf_msg_status(mpi_status_t* status) { assert(status != NULL); char s[512]; int len; MPI_Error_string(status->error_num, s, &len); log_write(LOG_DEBUG, "The information comes from MPI status The MPI source is %d, The MPI tag is %d The MPI error is %s", status->source, status->tag, s); } void mpi_send(void* msg, int dst, int tag, int len) { assert(msg != NULL); int source = get_mpi_rank(); if(dst < 0) { log_write(LOG_ERR, "destination is wrong when sending message"); return; } log_write(LOG_INFO, "sending message to receiver %d from sender %d the length is %d", dst, source, len); MPI_Send(msg, len, MPI_CHAR, dst, tag, MPI_COMM_WORLD); } //receiving message from sender and if souce equal to -1 it will receiving //message from any souce, the same to tag void mpi_recv(void* msg, int source, int tag, int len, mpi_status_t* status_t) { assert(msg != NULL); int dst = get_mpi_rank(); MPI_Status status; //-2 means MPI_ANY_SOURCE if(source < -2) { log_write(LOG_ERR, "destination is wrong when sending message"); return; } if(source == -1) source = MPI_ANY_SOURCE; if(tag == -1) tag = MPI_ANY_TAG; MPI_Recv(msg, len, MPI_CHAR, source, tag, MPI_COMM_WORLD, &status); log_write(LOG_INFO, "received message from sender %d and the receiver is %d the length is %d", status.MPI_SOURCE, dst, status.count); if(status_t != NULL) { status_t->error_num = status.MPI_ERROR; status_t->size = status.count; status_t->source = status.MPI_SOURCE; status_t->tag = status.MPI_TAG; #ifdef MPI_COMMUNICATION_DEBUG printf_msg_status(status_t); #endif } } void mpi_server_recv(void* msg, int len, mpi_status_t* status) { mpi_recv(msg, MPI_ANY_SOURCE, MPI_ANY_TAG, len, status); } int get_mpi_size() { int pro_num; MPI_Comm_size(MPI_COMM_WORLD, &pro_num); return pro_num; } int get_mpi_rank() { int id; MPI_Comm_rank(MPI_COMM_WORLD, &id); return id; } void mpi_init_with_thread(int* argc, char ***argv) { int provided; MPI_Init_thread(argc, argv, MPI_THREAD_MULTIPLE, &provided); if(provided != MPI_THREAD_MULTIPLE) { log_write(LOG_ERR, "could not support multiple threads in mpi process"); exit(1); } } void mpi_finish() { MPI_Finalize(); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include "shadowvpn.h" #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> static const char *help_message = "usage: shadowvpn -c config_file [-s start/stop/restart] [-v]\n" "\n" " -h, --help show this help message and exit\n" " -s start/stop/restart control shadowvpn process. if omitted, will run\n" " in foreground\n" " -c config_file path to config file\n" " -v verbose logging\n" "\n"; static void print_help() __attribute__ ((noreturn)); static void load_default_args(shadowvpn_args_t *args); static int process_key_value(shadowvpn_args_t *args, const char *key, const char *value); static void print_help() { printf("%s", help_message); exit(1); } static int parse_config_file(shadowvpn_args_t *args, const char *filename) { char buf[512]; char *line; FILE *fp; size_t len = sizeof(buf); int lineno = 0; fp = fopen(filename, "rb"); if (fp == NULL) { err("fopen"); errf("Can't open config file: %s", filename); return -1; } while ((line = fgets(buf, len, fp))) { char *sp_pos; lineno++; sp_pos = strchr(line, '\r'); if (sp_pos) *sp_pos = '\n'; sp_pos = strchr(line, '\n'); if (sp_pos) { *sp_pos = 0; } else { errf("line %d too long in %s", lineno, filename); return -1; } if (*line == 0 || *line == '#') continue; sp_pos = strchr(line, '='); if (!sp_pos) { errf("%s:%d: \"=\" is not found in this line: %s", filename, lineno, line); return -1; } *sp_pos = 0; sp_pos++; if (0 != process_key_value(args, line, sp_pos)) return 1; } if (!args->mode) { errf("mode not set in config file"); return -1; } if (!args->server) { errf("server not set in config file"); return -1; } if (!args->port) { errf("port not set in config file"); return -1; } if (!args->password) { errf("password not set in config file"); return -1; } return 0; } static int parse_user_tokens(shadowvpn_args_t *args, char *value) { char *sp_pos; char *start = value; int len = 0, i = 0; if (value == NULL) { return 0; } len++; while (*value) { if (*value == ',') { len++; } value++; } args->user_tokens_len = len; args->user_tokens = calloc(len, 8); bzero(args->user_tokens, 8 * len); value = start; while (*value) { int has_next = 0; sp_pos = strchr(value, ','); if (sp_pos > 0) { has_next = 1; *sp_pos = 0; } int p = 0; while (*value && p < 8) { unsigned int temp; int r = sscanf(value, "%2x", &temp); if (r > 0) { args->user_tokens[i][p] = temp; value += 2; p ++; } else { break; } } i++; if (has_next) { value = sp_pos + 1; } else { break; } } free(start); return 0; } static int process_key_value(shadowvpn_args_t *args, const char *key, const char *value) { if (strcmp("password", key) != 0) { if (-1 == setenv(key, value, 1)) { err("setenv"); return -1; } } if (strcmp("server", key) == 0) { args->server = strdup(value); } else if (strcmp("port", key) == 0) { args->port = atol(value); } else if (strcmp("concurrency", key) == 0) { errf("warning: concurrency is temporarily disabled on this version, make sure to set concurrency=1 on the other side"); args->concurrency = atol(value); if (args->concurrency == 0) { errf("concurrency should >= 1"); return -1; } if (args->concurrency > 100) { errf("concurrency should <= 100"); return -1; } } else if (strcmp("password", key) == 0) { args->password = strdup(value); } else if (strcmp("user_token", key) == 0) { parse_user_tokens(args, strdup(value)); } else if (strcmp("net", key) == 0) { char *p = strchr(value, '/'); if (p) *p = 0; in_addr_t addr = inet_addr(value); if (addr == INADDR_NONE) { errf("warning: invalid net IP in config file: %s", value); } args->netip = ntohl((uint32_t)addr); } else if (strcmp("mode", key) == 0) { if (strcmp("server", value) == 0) { args->mode = SHADOWVPN_MODE_SERVER; } else if (strcmp("client", value) == 0) { args->mode = SHADOWVPN_MODE_CLIENT; } else { errf("warning: unknown mode in config file: %s", value); return -1; } } else if (strcmp("mtu", key) == 0) { long mtu = atol(value); if (mtu < 68 + SHADOWVPN_OVERHEAD_LEN) { errf("MTU %ld is too small", mtu); return -1; } if (mtu > MAX_MTU) { errf("MTU %ld is too large", mtu); return -1; } args->mtu = mtu; } else if (strcmp("intf", key) == 0) { args->intf = strdup(value); } else if (strcmp("pidfile", key) == 0) { args->pid_file = strdup(value); } else if (strcmp("logfile", key) == 0) { args->log_file = strdup(value); } else if (strcmp("up", key) == 0) { args->up_script = strdup(value); } else if (strcmp("down", key) == 0) { args->down_script = strdup(value); } else { errf("warning: config key %s not recognized by shadowvpn, will be passed to shell scripts anyway", key); } return 0; } static void load_default_args(shadowvpn_args_t *args) { args->intf = "tun0"; args->mtu = 1440; args->pid_file = "/var/run/shadowvpn.pid"; args->log_file = "/var/log/shadowvpn.log"; args->concurrency = 1; } int args_parse(shadowvpn_args_t *args, int argc, char **argv) { int ch; bzero(args, sizeof(shadowvpn_args_t)); while ((ch = getopt(argc, argv, "hs:c:v")) != -1) { switch (ch) { case 's': if (strcmp("start", optarg) == 0) args->cmd = SHADOWVPN_CMD_START; else if (strcmp("stop", optarg) == 0) args->cmd = SHADOWVPN_CMD_STOP; else if (strcmp("restart", optarg) == 0) args->cmd = SHADOWVPN_CMD_RESTART; else { errf("unknown command %s", optarg); print_help(); } break; case 'c': args->conf_file = strdup(optarg); break; case 'v': verbose_mode = 1; break; default: print_help(); } } if (!args->conf_file) print_help(); load_default_args(args); return parse_config_file(args, args->conf_file); }
C
#include "UartReceiver.h" #include "UartFinder.h" #include "string.h" #include "TcTime.h" u8 _readByteViaUart(USART_TypeDef *uart){ u8 res; while(USART_GetFlagStatus(uart, USART_FLAG_RXNE) == 0); res=USART_ReceiveData(uart); USART_ClearFlag(uart, USART_FLAG_RXNE); return res; } int _readBytesViaUart(USART_TypeDef *uart,u8 *buffer,int length){ for(int i=0;i<length;i++) buffer[i]=_readByteViaUart(uart); return length; } u32 _readByteViaUartWithTimeout(USART_TypeDef *uart,u8 *out,u32 timeout){ u32 anchor; anchor=getCurrentTime(); while(!USART_GetFlagStatus(uart, USART_FLAG_RXNE) &&timeout) timeout=timeout>(getCurrentTime()-anchor)?(timeout-(getCurrentTime()-anchor)):0; if(!timeout) return 0; *out=USART_ReceiveData(uart); USART_ClearFlag(uart, USART_FLAG_RXNE); return timeout; } u32 _readBytesViaUartWithTimeout(USART_TypeDef *uart,u8 *buffer,int length,u32 timeout){ u32 remain=timeout; for(int i=0;i<length&&remain>0;i++) remain=_readByteViaUartWithTimeout(uart,buffer+i,remain); return remain; } /*-----------------------------------------public----------------------------------*/ u8 readByteViaUart(int uart){ USART_TypeDef *pUart=findUSARTPointer(uart); if(pUart==NULL) return 0; return _readByteViaUart(pUart); } u8 readByteViaUart4(void){ return readByteViaUart(SERIAL_4); } u8 readByteViaUart6(void){ return readByteViaUart(SERIAL_6); } u8 readByteViaUart7(void){ return 0; } void readBytesViaUart(int uart,u8 *out,int length){ USART_TypeDef *pUart=findUSARTPointer(uart); if(pUart==NULL) return ; _readBytesViaUart(pUart,out,length); } void readBytesViaUart4(u8 *out,int size){ readBytesViaUart(SERIAL_4,out,size); } void readBytesViaUart6(u8 *out,int size){ readBytesViaUart(SERIAL_6,out,size); } void readBytesViaUart7(u8 *out,int size){ } u32 readBytesViaUartWithTimeout(int uart,u8 *out,int length,u32 timeout){ USART_TypeDef *uartPointer=findUSARTPointer(uart); if(uart==NULL) return 0; return _readBytesViaUartWithTimeout(uartPointer,out,length,timeout); } u32 readBytesViaUart4WithTimeout(u8 *out,int length,u32 timeout){ return readBytesViaUartWithTimeout(SERIAL_4,out,length,timeout); } u32 readBytesViaUart6WithTimeout(u8 *out,int length,u32 timeout){ return readBytesViaUartWithTimeout(SERIAL_6,out,length,timeout); } u32 readBytesViaUart7WithTimeout(u8 *out,int length,u32 timeout){ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #define offsetof(TYPE, MEMBER) ((size_t)&((TYPE *)0)->MEMBER) #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member));}) #define GOLDEN_RATIO_PRIME_32 0x9E370001UL #define pid_hashfn(nr, ns) \ hash_long((unsigned long)nr + (unsigned long)ns, pidhash_shift) struct hlist_head { struct hlist_node *first; }; struct hlist_node { struct hlist_node *next, **pprev; }; void hlist_add_head(struct hlist_node *n, struct hlist_head *h) { struct hlist_node *first = h->first; n->next = first; if(first) first->pprev = &n->next; h->first = n; n->pprev = &h->first; } unsigned int hash_32(unsigned int val, unsigned int bits) { unsigned int hash = val * GOLDEN_RATIO_PRIME_32; return hash >> (32-bits); } //-------------- User Program -------------- #define HASH_MAX 8 #define PERSON_NUM 30 typedef struct { int id; struct hlist_node hash; } PERSON; int log_2(int x) { return (int)(log(x) / log(2)); } unsigned hash_long(unsigned val, unsigned bits) { unsigned int hash = val * GOLDEN_RATIO_PRIME_32; return hash >> (32 - bits); } int hash_func(int i) { return hash_long(i, log_2(HASH_MAX)); // return i % HASH_MAX; } void display(struct hlist_head *head) { system("clear"); for(int i=0; i<HASH_MAX; i++) { struct hlist_node *temp; PERSON *p; printf("[%d]", i); for(temp = head[i].first; temp; temp=temp->next) { p = container_of(temp, PERSON, hash); printf("<->[%d]", p->id); } printf("\n"); } getchar(); } int main() { struct hlist_head heads[HASH_MAX] = {0,}; int hash_num, id; PERSON p[PERSON_NUM] = {0,}; display(heads); for (int i=0; i<PERSON_NUM; i++) { id = 1000+i; p[i].id = id; hash_num = hash_func(id); hlist_add_head(&p[i].hash, &heads[hash_num]); display(heads); } }
C
#include<stdio.h> main(){ char name[100]; int c=0,i; char *pointer; pointer=name; printf("enter string : "); gets(name); for(i=0;name[i]!='\0';i++){ if(name[i]==' ') c++; } printf("the amount of word is %d",c); }
C
#include "stepper.h" #include <avr/io.h> int main(void) { uint8_t step, state = STEPPER_INIT; for(;;) { step = next_step(&state, FULL_STEP | FWD); PORTB &= 0xF0; PORTB |= step; } return 0; }
C
void int_radix_sort(int *lst, int *dst, int n){ int group = 8; int buckets = 1 << group; int mask = buckets - 1; int cnt[buckets]; int map[buckets]; for(int k = 0; k < 32; k += 8){ memset(cnt, 0, sizeof(cnt)); memset(map, 0, sizeof(map)); for(int i = 0; i < n; i++){ cnt[(lst[i] >> k) & mask]++; } map[0] = 0; for(int i = 1; i < buckets; i++){ map[i] = map[i - 1] + cnt[i - 1]; } for(int i = 0; i < n; i++){ dst[map[(lst[i] >> k) & mask]++] = lst[i]; } for(int i = 0; i < n; i++){ lst[i] = dst[i]; } } } void float_radix_sort(float *lst2, float *dst, int n){ unsigned int group = 8; unsigned int buckets = 1 << group; unsigned int mask = buckets - 1; unsigned int cnt[buckets]; unsigned int map[buckets]; unsigned int *lst = (unsigned int*) lst2; for(unsigned int k = 0; k < 32; k += 8){ memset(cnt, 0, sizeof(cnt)); memset(map, 0, sizeof(map)); for(unsigned i = 0; i < n; i++){ cnt[(lst[i] >> k) & mask]++; } map[0] = 0; for(unsigned i = 1; i < buckets; i++){ map[i] = map[i - 1] + cnt[i - 1]; } for(unsigned i = 0; i < n; i++){ dst[map[(lst[i] >> k) & mask]++] = lst2[i]; } for(unsigned i = 0; i < n; i++){ lst2[i] = dst[i]; } } } void correct(float *lst, float *dst, int n){ int neg_index = 0; for(int i = n; i > 0; i--){ if(lst[i] < 0){ dst[neg_index] = lst[i]; neg_index++; } } for(int i = 0; i < n; i++){ if(lst[i] >= 0){ dst[i + neg_index] = lst[i]; } } for(int i = 0; i < n; i++){ lst[i] = dst[i]; } }
C
#include<stdio.h> #define min(x,y)(x < y? x:y) char a[200],b[200]; int as,bs; int main(){ while(scanf(" %d %s %d %s",&as,a,&bs,b) == 4){ int dp[as+1][bs+1]; for(int i = 0; i <= as;++i) dp[i][0] = i; for(int i = 0; i <= bs;++i) dp[0][i] = i; for(int i = 1;i <= as;++i){ for(int j = 1; j <= bs;++j){ dp[i][j] = min(dp[i-1][j],dp[i][j-1])+1; dp[i][j] = min(dp[i-1][j-1] + (a[i-1] != b[j-1]),dp[i][j]); } } printf("%d\n",dp[as][bs]); } return 0; }
C
#include "func.h" void sig_handle(int sig) { printf("sig comes\n"); } void makeprocess(int num,int* pairs) { int i,fd; int ret; for(i=0;i<num;i++) {//父进程 ret=socketpair(AF_LOCAL,SOCK_STREAM,0,pairs+2*i); if(-1==ret) { perror("socketpair"); return ; } } for(i=0;i<num;i++) { if(fork()) {//父进程 }else { // signal(SIGPIPE,sig_handle); while(1) { // printf("I am the %dth child\n",i); recv_fd(getpair_r(pairs,i),&fd); // printf("now I get the %dmission!\n",fd); int se=sendfile(fd,FILENAME); if(se==-1) printf("mission %d failed!\n",fd); // send_fd(getpair_r(pairs,i),fd); send(getpair_r(pairs,i),&fd,4,0); // exit(0); } } } } int getpair_r(int* pairs,int num) { return *(pairs+num*2); } int getpair_w(int* pairs,int num) { return *(pairs+num*2+1); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include "allvars.c" /*routine to read the file with the particle coordinates.*/ int readfile(char *filename, int Nparticles) { int i; FILE *pf = NULL; pf = fopen(filename,"r"); for(i=0;i<Nparticles;i++) { fscanf(pf,"%lf %lf\n",&part[i].pos[0],&part[i].pos[1]); } fclose(pf); return 0; } /*distance between two particles*/ double distance(double xj, double xi, double yj, double yi) { double d; d = sqrt((xj-xi)*(xj-xi) +(yj-yi)*(yj-yi)); return d; } /*sorting indexed arrays..*/ int sort(int Nparticles, double *d, int *ID) { int i,j, tempID; float temp; int N; N = Nparticles -1; for(i=0;i<(N-1);i++) { for(j=0;j< N -1 -i; ++j) { if(d[j] > d[j+1]) { temp = d[j+1]; d[j+1] = d[j]; d[j] = temp; tempID = ID[j+i]; ID[j+1] = ID[j]; ID[j] = tempID; } } } return 0; } /*routine to look the two nearest neighbors of each particle. It need the positions of the partciles */ int construct_triangles(struct particle *part) { FILE *pf = NULL; int i,k,j; double *d = NULL; size_t *ID = NULL; d = (double *)malloc((size_t)(Nparticles-1) * sizeof(double)); ID = (size_t *)malloc((size_t)(Nparticles-1) *sizeof(size_t)); pf = fopen("vertices.dat","w"); for(i=0;i<Nparticles;i++) { k = 0; id[i]=i; for(j=0;j<Nparticles;j++) { if(i != j) { d[k]=distance(part[j].pos[0],part[i].pos[0],part[j].pos[1],part[i].pos[1]); k++; } } //sorting the array: if you want to use bubble sort algorithm, call the funtion "sort" as: sort(Nparticles,d,ID); //this time we will use gsl to made the sorting gsl_sort_index(ID,d,1,Nparticles-1); //add neighbors of the particle i to the structure part[i].ngb[0] = id[i]; part[i].ngb[1] = ID[0]; part[i].ngb[2] = ID[1]; fprintf(pf,"%d %d %d\n", part[i].ngb[0], part[i].ngb[1], part[i].ngb[2]); //vertices of the triangle } printf("the file with the vertices was wrtten\n"); free(ID); fclose(pf); return 0; } /*routine to count the number of triangles formed by a single particle It needs to compute the from every particle to the center, so cx and cy are the center coordinates. */ int triangle_counter(struct particle *part, double cx, double cy) { int *v1 = NULL, *v2 = NULL; FILE *pf = NULL; int i,j; v1 = (int *)malloc((size_t)Nparticles * sizeof(int)); v2 = (int *)malloc((size_t)Nparticles * sizeof(int)); pf = fopen("vertices.dat","r"); printf("counting triangles..\n"); for(j=0;j<Nparticles;j++) { //distance from particles to the center dc[j]=distance(part[j].pos[0], cx, part[j].pos[1], cy); part[j].triangles = 1; for(i=0;i<Nparticles;i++) { fscanf(pf,"%d %d %d\n",&(id[i]),&(v1[i]),&(v2[i])); if(v1[i] == j) { part[j].triangles += 1; } if(v2[i] == j) { part[j].triangles += 1 ; } } } free(v1); free(v2); fclose(pf); //write a file with the data of distances to the center and number of triangles per particle pf = fopen("num_triang_distances.dat","w"); printf("written file with distances and number of triangles..\n"); for(i=0;i<Nparticles;i++) { fprintf(pf,"%lf %d\n",dc[i],part[i].triangles); } fclose(pf); gsl_sort(dc,1,Nparticles); //organice the dc array in ascending numerical order to assing particles in the rings return 0; } /* composite simpson rule to computee the total mass inside a radii r, computed as the integral of the surface density over the ring's area a and b are the end points of the interval. "struct rings *ring" contains the information of the density and the radii of each ring */ double composite_simpson(struct rings * ring, int Npoints, double a, double b) { int i; double h,c,P,I; double Mtot; c = 0.33333333333; h = (b-a)/ Npoints; //a and b are the interval ends, in this case b = Rf P = 0.0; I = 0.0; if (Npoints == 0) Mtot = 0; else { for(i=0;i<=Npoints/2 -1;i++) { P += ring[2*i].density * ring[2*i].r; I += ring[2*i +1].density * ring[2*i + 1].r; } Mtot = 2 * M_PI * h * c *(4.0*I + 2.0*P + ring[Npoints-1].density * b); } return Mtot; } /*routine to interpolate the points: surface density as a function of r*/ int my_interpolation(int Nrings, double *S, double *R, gsl_spline * spline, gsl_interp_accel *acc) { double Ri, Si; FILE *file = NULL; file = fopen("interpolation.dat","w"); //gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, (size_t) Nrings); gsl_spline_init (spline, R, S, (size_t) Nrings); //gsl_interp_accel *acc = gsl_interp_accel_alloc (); //returns a pointer to an accelerator object for (Ri = R[0]; Ri < R[Nrings -1]; Ri += 0.01) { Si = gsl_spline_eval (spline, Ri, acc); fprintf (file,"%lf\t %lf\n", Ri, Si); } //gsl_spline_free (spline); //gsl_interp_accel_free (acc); fclose(file); return 0; } /*routine to find the roots. It returns Re at which: density = (central_density / e) */ double spline_root( gsl_spline * spline, gsl_interp_accel * acc, double alpha, double a0, double a1, double epsilon, int nmax) { double a2, err, fa0, fa1, fa2; int nsteps = 0; fa0 = gsl_spline_eval(spline,a0,acc) - alpha; fa1 = gsl_spline_eval(spline,a1,acc) - alpha; printf("finding root of %e\n",alpha); printf("a0 = %lf \t a1 = %lf\n",a0,a1); printf("\t fa0 = %lf \t fa1 = %lf\n",fa0,fa1); if(a1 > a0) { if (fa0*fa1 > 0) { printf("warning: function has same sgn on both bounds\n"); printf("root may not be found or may not be unique\n"); printf("proceed with caution\n"); } a2 = 0.5*(a1+a0); err = 0.5*fabs(a0-a1); fa2 = gsl_spline_eval(spline,a2,acc) - alpha; while (err > epsilon && nsteps < nmax){ if (fa0*fa2 < 0){ //a0 = a0 a1 = a2; fa1 = gsl_spline_eval(spline,a1,acc) - alpha; } else{ //a1 = a1 a0 = a2; fa0 = gsl_spline_eval(spline,a0,acc) - alpha; } ++nsteps; a2 = 0.5*(a1+a0); err = 0.5*fabs(a0-a1); fa2 = gsl_spline_eval(spline,a2,acc)-alpha; //we must shift the fuction by alpha in order to use the bisection method } if (nsteps >= nmax){ printf("Did not converge. Do not trust this answer.\n"); } } return a2; }
C
#pragma warning(disable:4996) #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char str1[100]; //Է¹ 迭 char word[10][100]; //и ܾ ߹迭 char firstword[100] = ""; // ܾ 迭 char* p1; // int len1; //Է¹ ڿ int i, j; int cnt = 0; //ܾ //ڿ Է, ڿ gets(str1); len1 = strlen(str1); i = 0; //i, j 0 ʱȭ j = 0; // ؼ ܾ word迭 for (p1 = str1; p1 <= str1 + len1; ++p1) // -> ݺ { if (*p1 != ' ') //*p1 ƴϸ word迭 *p1 { word[i][j++] = *p1; } else if (*p1 == ' ') // ´ٸ { word[i][j] = '\0'; //word '\0' ؼ ڿ ϼѴ. j = 0; //j 0 ʱȭϰ i 1Ŵ i++; } } cnt = i + 1; //ܾ //и ܾ for (i = 0; i < cnt; ++i) puts(word[i]); strcpy(firstword, word[0]); //켱 firstword word迭 ù° ܾ for (i = 1; i < cnt; ++i) { if (strcmp(firstword, word[i]) > 0) // firstword ִ ܾ word[i] ִ ܾ ٸ firstword word[i] . { strcpy(firstword, word[i]); } } // firstword puts(firstword); return 0; }
C
#include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" void ff(int f) { if(f<1) return; ff(f-1); ff(f-2); return; } int main() { sleep(10); int pid = fork(); if(pid == 0) { sleep (10); int ppid = fork(); if(ppid == 0) { ff(33); printf(1,"P1\n"); //#endif } else { ff(39); printf(1,"P2\n"); wait(); //#endif } } else { ff(36); printf(1,"P3\n"); wait(); // #endif } exit(); }
C
#include <stdlib.h> #include <assert.h> #include <stdbool.h> #include "dict.h" #include "list.h" #include "pair.h" #include "index.h" #include "data.h" struct _dict_t { list_t lista; unsigned int size; }; unsigned int size = 0; unsigned int dict_length(dict_t diccionario) { assert(diccionario != NULL); return (diccionario->size); } dict_t dict_empty(void) { dict_t result = NULL; result = calloc(1, sizeof(struct _dict_t)); assert(result != NULL); result->lista = list_empty(); assert(dict_length(result) == 0); return (result); } dict_t dict_destroy(dict_t diccionario) { assert(diccionario != NULL); diccionario->lista = list_destroy(diccionario->lista); free(diccionario); diccionario = NULL; return diccionario; } bool dict_is_equal(dict_t diccionario, dict_t otro) { bool result = false; assert(diccionario != NULL); assert(otro != NULL); result = list_is_equal(diccionario->lista, otro->lista); return (result); } bool dict_exists(dict_t diccionario, word_t palabra) { bool result = true; assert(diccionario != NULL); assert(palabra != NULL); index_t indice = index_from_string(palabra); if ((list_search(diccionario->lista, indice)) == NULL) { result = false; } indice = index_destroy(indice); return (result); } def_t dict_search(dict_t diccionario, word_t palabra) { assert(diccionario != NULL); assert(palabra != NULL); assert(dict_exists(diccionario, palabra) == true); def_t result = NULL; index_t indice = index_from_string(palabra); result = data_to_string(list_search(diccionario->lista, indice)); indice = index_destroy(indice); assert(result != NULL); return (result); } dict_t dict_add(dict_t dict, word_t word, def_t def) { unsigned int size = dict_length(dict); list_t lista = dict->lista; assert(dict != NULL); assert(word != NULL); assert(def != NULL); assert(dict_exists(dict, word) != true); index_t indice = NULL; indice = index_from_string(word); data_t definicion = NULL; definicion = data_from_string(def); dict->lista = list_append(lista, indice, definicion); dict->size = size + 1; assert((dict->size) == dict_length(dict)); return (dict); } dict_t dict_remove(dict_t dict, word_t word) { unsigned int size = dict_length(dict); list_t lista = dict->lista; assert(dict != NULL); assert(word != NULL); assert(dict_exists(dict, word) == true); index_t indice = index_from_string(word); dict->lista = list_remove(lista, indice); dict->size = size - 1; indice = index_destroy(indice); return (dict); } dict_t dict_copy(dict_t dict) { dict_t dict2 = NULL; dict2 = calloc(1, sizeof(struct _dict_t)); dict2->lista = list_copy(dict->lista); assert(dict2 != NULL); assert(dict_is_equal(dict, dict2)); return (dict2); } void dict_dump(dict_t dict, FILE * fd) { list_t lista = dict->lista; assert(dict != NULL); list_dump(lista, fd); }