language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | /* 10.1 (a) integer type expression implicitly converted to a narrower or different signness underlying type */
#include <stdio.h>
char c = 'a';
short int w = -5;
int x = -6;
long int y = -7;
unsigned char uc = 56u;
unsigned short int uw = 5u;
unsigned int ux = 6u;
unsigned long int uy = 7u;
int main() {
c = w; /* not complaint */
w = x; /* not complaint */
c = uc; /* not complaint */
uc = c; /* not complaint */
return 0;
}
|
C | #include<stdio.h>
int main()
{
int N, s, m, h;
scanf("%d", &N);
m=N/60;
s=N%60;
h=m/60;
m=m%60;
printf("%d:%d:%d\n", h,m,s);
return 0;
}
|
C | /*
Interface: main.c
Author: Vicente Cunha
Date: September 2016
VERSÃO: WI16-26R1
*/
#include "serialParser.h"
#include "uart.h"
#include <avr/eeprom.h>
#include <avr/interrupt.h>
//==================//
//=== INTERRUPTS ===//
//==================//
volatile int ovfCounter1 = 0;
volatile int ovfCounter2 = 0;
volatile bool halfSecondFlag = false;
volatile bool oneSecondFlag = false;
ISR(TIMER0_OVF_vect)
{
ovfCounter1 += 1;
ovfCounter2 += 1;
const int ovfPerHalfSecond = 31;
const int ovfPerSecond = 61; // 15625 [cnts/s] / 256 [cnts/ovf]
if (ovfCounter1 > ovfPerHalfSecond) {
halfSecondFlag = true;
ovfCounter1 = 0;
}
if (ovfCounter2 > ovfPerSecond) {
oneSecondFlag = true;
ovfCounter2 = 0;
}
}
switches_t mySwitches;
treadmill_t myTreadmill;
volatile bool rxFlag = false;
ISR(USART_RX_vect)
{
rxFlag = true;
unsigned char rxByte = UDR0;
if (mySwitches.treadmill == DEBUG) uart_sendChar(rxByte);
else serialParser_parse(mySwitches.protocol, &myTreadmill, rxByte);
}
//============//
//=== MAIN ===//
//============//
int main()
{
float* currentDistance_ptr = (float*)sizeof(uint8_t);
float currentDistance_km = 0;
if (!eeprom_read_byte(0)){
eeprom_write_float(currentDistance_ptr, currentDistance_km);
eeprom_write_byte(0,1);
} else currentDistance_km = eeprom_read_float(currentDistance_ptr);
mySwitches = getSwitches();
myTreadmill = treadmill_init(mySwitches.treadmill);
sei(); // enable interrupts
treadmill_resetInclination();
switch(mySwitches.protocol) {
default:
case INBRAMED: uart_init(9600); break;
case TRACKMASTER_KMPH:
case TRACKMASTER_MPH: uart_init(4800); break;
}
// DEBUG:
//uart_sendChar(mySwitches.protocol + mySwitches.treadmill);
TCCR0B |= (1 << CS02)|(1 << CS00); // start time control, CLK = 15.625kHz
// SUPER LOOP:
while (true) {
if (mySwitches.treadmill != DEBUG) treadmill_update(&myTreadmill);
if (halfSecondFlag) {
halfSecondFlag = false;
if (rxFlag) rxFlag = false;
else if (myTreadmill.cds) myTreadmill.enableBelt = false;
}
if (oneSecondFlag) {
oneSecondFlag = false;
currentDistance_km += myTreadmill.speed_kmph/3600; // [km/h]/[s/h]
if (currentDistance_km > myTreadmill.lubDistance_km) {
currentDistance_km = 0;
PORTB |= (1 << PORTB2); // switch lub on
} else PORTB &= ~(1 << PORTB2); // switch lub off
if (eeprom_is_ready()) eeprom_write_float(currentDistance_ptr, currentDistance_km);
}
}
return 0;
}
|
C | //
// Created by Sheldon Benard
//
#ifndef PROJECT_CONSTANTS_H
#define PROJECT_CONSTANTS_H
//---Include libraries for the project---//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <math.h>
#include <stdint.h>
//---define static constants for the project---//
#define SFS_NAME "simple_file_system"
#define MAX_NUM_DIRECTORIES 1 //1 root directory
#define ROOT_DIR 0;
#define MAX_NUM_FILES 50 //We'll have max of 50 files
#define MAX_NUM_INODES MAX_NUM_DIRECTORIES+MAX_NUM_FILES //1 inode per file && directory
#define NEW_FILE -10 //We'll use this special flag to indicate a new file is being created
#define UNINITIALIZED_POINTER -1 //We'll use this special flag to indicate a uninitialized pointer
#define NO_FILE -1
#define FULL_IT -1
#define FULL_DT -1
#define FULL_FDT -1
#define NOT_IN_FDT -1
#define BLOCKSIZE 1024 //as per assignment recommendation
#define BLOCKSIZE_DOUBLE 1024.0 //for calculations
//We'll define a (MegaByte_SFS)MB File System;
#define MegaByte_SFS 5
#define NUM_BLOCKS BLOCKSIZE*MegaByte_SFS
//File name specification
#define MAX_FILE_NAME 16
#define MAX_FILE_EXT 3
#define PERIOD_IN_FILE_NAME 1
#define NULL_IN_FILE_NAME 1
#define FILE_TABLE_SIZE 32 //There will be 32 open files at any given time
#define ITABLE_NUM_BLOCKS 32 //Inode table will hold 32 blocks
#define DIRECTORY_NUM_BLOCKS 8 //Directory will hold 8 blocks
#define BITFIELD_BLOCKS 4 //Free bit map will hold 4 blocks
//Define direct pointers here; NUM_INDIR_PTRS will be a const int
#define NUM_DIR_PTRS 12
//define superblock constants
#define MAGIC_BLOCK 0xACBD0005
#define SUPER_BLOCK_INDEX 0
//define INDEX of important structures in data blocks
#define ITABLE_START_INDEX 1 //this is 32 blocks
#define DIRECTORY_BLOCK_START_INDEX 33 //this is 8 blocks
#define FREE_BIT_MAP_START_INDEX 41 //this is 4 blocks
#define DATA_BLOCK_START_INDEX 45
//Constants
static int const NUM_INDIR_PTRS = BLOCKSIZE/sizeof(int); //Indirect pointers: are int which are x bits, depending on comp
//With direct and indirect pointers defined, we can define max file length
static int const MAX_FILE_BLOCKS = NUM_DIR_PTRS + NUM_INDIR_PTRS;
static int const MAX_FILE_SIZE = BLOCKSIZE*MAX_FILE_BLOCKS;
static int const DATA_BLOCK_SIZE_IN_BYTES = ((NUM_BLOCKS - DATA_BLOCK_START_INDEX)/8) + 1;
static int const DATA_BLOCK_SIZE_IN_BITS = DATA_BLOCK_SIZE_IN_BYTES*8;
#endif //PROJECT_CONSTANTS_H
|
C | /*
* Implements Keychain Functionality using ECDSA.
*
* A Keychain consists of a Base Key Pair, a Chain Key, and a sequence of Key
* Pairs derived from them.
*
* d_b = Base Private Key = random integer in range [1, ec_n - 2**128)
* Q_b = Base Public Key = d_b * G
* k = Chain Key = random integer in range [0, 2**256)
*
* For key 'n', where n is a 128-bit integer
* offset = AES256(k,n)
* d_n = d_b + offset
* Q_n = Q_b + offset * G
*
*
* Note that the base private key is in a more restricted range, so that any
* derived private key never equals 0 (which is invalid).
*
*
* Designed by fpgaminer ([email protected]).
*
*/
#ifndef __KEYCHAIN_H__
#define __KEYCHAIN_H__
#include <stdint.h>
#include <strong-arm/finite_field.h>
#include <strong-arm/ecdsa.h>
/* Generate a random keychain */
void keychain_create (FF_NUM *const out_base_private_key, uint8_t out_chain_key[static 32]);
/* Calculate a derived key.
* out_privkey and out_pubkey may either or both be NULL.
*/
void keychain_calculate (FF_NUM *const out_privkey, EC_POINT *const out_pubkey, FF_NUM const *const base_private_key, uint8_t const chain_key[static 32], uint8_t const index[static 16]);
#endif
|
C | #include<stdio.h>
#include<stdlib.h>
#define N 100
typedef struct People
{
char name[20];
int age;
}sP;
int input(sP *pman,int n)
{
// printf("n in ip:%d\n",n);
printf("please input name:");
scanf("%s",pman->name);
printf("please input age:");
scanf("%d",&pman->age);
// printf("age:%d\n",pman->age);
// printf("n out ip:%d\n",n);
return n;
}
void compare(sP *pm, int n)
{
int i,max=0,a;
for(i=0;i<n;i++)
{
if(pm[i].age > max)
{
max = pm[i].age;
// printf("compare-->>pman.%d:%d",i,pman[i].age);
a=i;
}
}
printf("最大的年龄是%d,名字是%s\n",pm[a].age,pm[a].name);
}
int main()
{
int n,i;
printf("please input number of people:");
scanf("%d",&n);
// printf("n1:%d\n",n);
sP peop[N];
sP * pm;
pm = &peop[0];
// printf("n2:%d\n",n);
pm = (sP *)malloc((n+1)*(sizeof(sP)));
// printf("n3:%d\n",n);
for(i=0;i<n;i++)
{
pm = &peop[i];
// printf("n4:%d\n",n);
n=input(pm,n);
// printf("n5:%d\n",n);
printf("i:%d\n",i);
if(i == n-1)
{
break;
}
}
compare(&peop,n);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
struct element {
int data;
};
struct element stack[MAX_SIZE];
int top = -1;
void stackfull(void)
{
printf("Stack is full, cannot add element.\n");
exit(EXIT_FAILURE);
}
void push(struct element item)
{
if (top >= (MAX_SIZE - 1))
stackfull();
stack[++top] = item;
}
void print_stack(void)
{
int i;
if (top == -1) {
printf("No elements to print.\n");
} else {
for (i = top; i >= 0; i--) {
printf("Value of element at position %d is: %d\n", i, stack[i].data);
}
}
}
int main(void)
{
struct element *new;
if ((new = (struct element *) malloc(sizeof(struct element))) == NULL) {
printf("Failed to allocate memory for new element.\n");
exit(EXIT_FAILURE);
}
new->data = 10;
push(*new);
printf("Stack:\n");
print_stack();
return 0;
}
|
C | /*-------------------------------------------------------------------------
Include files:
--------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int height = 0;
int bSum = 0, bAmount = 0, gSum = 0, gAmount = 0;
printf("Students, please enter heights!\n");
while(scanf("%d",&height)== 1)
{
if(height==0)
{
printf("Error! Invalid height 0!\n");
return -1;
}
else if(height > 0)
{
gAmount++;
gSum += height;
}
else if(height < 0)
{
bAmount++;
bSum += height;
}
}
if(gAmount)
printf("Average girls height is: %.2f\n",(float)gSum/gAmount);
else
printf("No girls in class! :(");
if(bAmount)
printf("Average boys height is: %.2f\n",(float)-bSum/bAmount);
else
printf("No boys in class! :(\n");
return 0;
}
|
C |
#include <stdbool.h>
#include <stdio.h>
/*------------------------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------------------------*/
//int *start_vector(int *vector, int size){
void start_vector(int *vector, int size){
//int vector[size];
for(int i=0; i < size;i++){
vector[i] = -1;
}
//return vector;
}
// o indicador se a posicao esta vazia é -1
bool empty(int *fila, int size){
for(int i=0; i < size; i++){
if(fila[i] != -1){
return false;
}
}
return true;
}
int begin(int *fila){
return fila[0];
}
void erase(int *fila, int size, int remover){
fila[remover] = -1;
int i;
for(i = 0; i < size; i++){
if(fila[i] == -1){
break;
}
}
for(i; i < size; i++){
fila[i] = fila[i+1];
}
fila[size-1] = -1;
}
void push_back(int *fila, int size, int value){
int i;
for(i = 0; i < size; i++){
if(fila[i] == -1){
break;
}
}
fila[i] = value;
}
/*------------------------------------------------------------------------------------------------*/
int bfs(int size, int (*grafo)[size], int start){
bool visited[size];
for(int i = 0; i < size; i++){
visited[i] = false;
}
int q[size];
start_vector(q, size);
push_back(q, size, start);
char c;
visited[start] = true;
int vis;
while(!empty(q, size)){
vis = q[0];
erase(q, size, 0);
for (int i = 0; i < size; i++){
if(grafo[vis][i] == 1 && (!visited[i])){
push_back(q, size, i);
visited[i] = true;
}
}
}
int count = 0;
printf("grafos visitados a partir de %d\n", start);
for(int i = 0; i < size; i++){
printf("%c, ", (visited[i]? 'S': 'N'));
if(visited[i] == true){
count++;
}
}
printf("\n\n");
return count;
}
|
C | #include <stdio.h>
#include <string.h>
int main()
{
int n;
scanf("%d", &n);
getchar();
char c[n][20], i;
char *p[n];
for (i = 0; i < n; i++)
{
gets(c[i]);
p[i] = c[i];
}
void sort(int n, char *[]);
sort(n, p);
printf("Now,the sequence is:\n");
for (i = 0; i < n; i++)
printf("%s\n", p[i]);
}
void sort(int n, char *p[])
{
int i, j;
char min[25];
for (i = 0; i < n; i++)
{
strcpy(min, p[i]);
for (j = i; j < n; j++)
if (strcmp(p[j], min) < 0)
{
strcpy(min, p[j]);
strcpy(p[j], p[i]);
strcpy(p[i], min);
}
}
} |
C | /*
* main.c
*
* Created on: 2018 Apr 10 10:24:28
* Author: Conor
*/
#include <DAVE.h> //Declarations from DAVE Code Generation (includes SFR declaration)
/**
* @brief main() - Application entry point
*
* <b>Details of function</b><br>
* This routine is the application entry point. It is invoked by the device startup code. It is responsible for
* invoking the APP initialization dispatcher routine - DAVE_Init() and hosting the place-holder for user application
* code.
*/
enum state { RED, GREEN, AMBER, REDPED, REDPEDFLASH };
enum state current = RED;
bool hasWrapped;
bool buttonPressed;
uint32_t cylesSinceLastPedSeq = 1;
void ButtonHandler(void)
{
buttonPressed = true;
}
void ThirtyTimerHandler(void)
{
TIMER_Stop(&TMRThirty);
TIMER_Clear(&TMRThirty);
TIMER_ClearEvent(&TMRThirty);
current = GREEN;
TIMER_Start(&TMRForty);
}
void TenTimerHandler(void)
{
TIMER_Stop(&TMRTen);
TIMER_Clear(&TMRTen);
TIMER_ClearEvent(&TMRTen);
if(current == AMBER)
{
if(cylesSinceLastPedSeq > 3 && buttonPressed == true)
{
cylesSinceLastPedSeq = 0;
current = REDPED;
TIMER_Start(&TMRForty);
}
else
{
current = RED;
cylesSinceLastPedSeq++;
TIMER_Start(&TMRThirty);
}
}
if(current == REDPEDFLASH)
{
current = GREEN;
TIMER_Start(&TMRForty);
}
}
void FortyTimerHandler(void)
{
TIMER_Stop(&TMRForty);
TIMER_Clear(&TMRForty);
TIMER_ClearEvent(&TMRForty);
if(current == GREEN)
{
current = AMBER;
TIMER_Start(&TMRTen);
}
if(current == REDPED)
{
if(hasWrapped == true)
{
current = REDPEDFLASH;
hasWrapped = false;
TIMER_Start(&TMRTen);
}
else
{
hasWrapped=true;
TIMER_Start(&TMRForty);
}
}
}
int main(void)
{
DAVE_STATUS_t status;
status = DAVE_Init(); /* Initialization of DAVE APPs */
if(status != DAVE_STATUS_SUCCESS)
{
/* Placeholder for error handler code. The while loop below can be replaced with an user error handler. */
XMC_DEBUG("DAVE APPs initialization failed\n");
while(1U)
{
}
}
/* Placeholder for user application code. The while loop below can be replaced with user application code. */
while(1U)
{
switch(current)
{
case RED:
/* Turning Red LED on and previous LED's off */
DIGITAL_IO_SetOutputLow(&LEDAmber);
DIGITAL_IO_SetOutputHigh(&LEDRed);
break;
case GREEN:
/* Turning Green LED on and previous LED's off */
DIGITAL_IO_SetOutputLow(&LEDRed);
DIGITAL_IO_SetOutputHigh(&LEDGreen);
break;
case AMBER:
/* Turning Amber LED on and previous LED's off */
DIGITAL_IO_SetOutputLow(&LEDGreen);
DIGITAL_IO_SetOutputHigh(&LEDAmber);
break;
case REDPED:
/* Turing Red LED on, Pedestrain LED on and previous LED's off */
DIGITAL_IO_SetOutputLow(&LEDAmber);
DIGITAL_IO_SetOutputHigh(&LEDRed);
PWM_CCU4_SetDutyCycle(&PWMPedestrian, 10000);
PWM_CCU4_SetFreq(&PWMPedestrian, 100);
break;
case REDPEDFLASH:
/* Keeping Red LED on, Pedestrian LED to flashing */
PWM_CCU4_SetDutyCycle(&PWMPedestrian, 5000);
PWM_CCU4_SetFreq(&PWMPedestrian, 100);
}
}
}
|
C | int prime(int k)
{
int p=(int)sqrt(k);
int t;
for (t=3;t<=p;t+=2)
if (k%t==0) break;
if (t>p) return 1; else return 0;
}
main()
{
int n;
scanf("%d",&n);
if (n<=200000)
{
for (int i=3;i<=n/2;i+=2)
if (prime(i))
{
if (prime(n-i))
printf("%d %d\n",i,n-i);
}}
else printf("%d",n);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* arch_64.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jmancero <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/04/25 13:46:16 by jmancero #+# #+# */
/* Updated: 2014/04/27 11:59:01 by jmancero ### ########.fr */
/* */
/* ************************************************************************** */
#include "nm.h"
void ft_swap(struct nlist_64 *a, struct nlist_64 *b)
{
struct nlist_64 c;
ft_memcpy(&c , a, sizeof(struct nlist_64));
ft_memcpy(a , b, sizeof(struct nlist_64));
ft_memcpy(b , &c, sizeof(struct nlist_64));
}
struct nlist_64 *sort_struct(struct nlist_64 *tab, int nsyms, char *string_t)
{
int i;
i = 1;
while (i < nsyms)
{
if(ft_strcmp(string_t + tab[i - 1].n_un.n_strx,
string_t + tab[i].n_un.n_strx) > 0)
{
ft_swap(&tab[i - 1], &tab[i]);
i = 0;
}
i++;
}
return (tab);
}
struct nlist_64 *cpy_struct(int nsyms, struct nlist_64 *orig)
{
int i;
struct nlist_64 *cpy;
i = 0;
cpy = (struct nlist_64 *)malloc(sizeof(struct nlist_64) * nsyms);
while (i < nsyms)
{
ft_memcpy(&cpy[i], &orig[i], sizeof(struct nlist_64));
i++;
}
return (cpy);
}
int ft_put_exa(long long unsigned int n)
{
if (n < 16)
{
if (n < 10)
return (ft_putchar(n + '0'));
else
return (ft_putchar(n - 10 + 'a'));
}
else
{
if ((n % 16) < 10)
return (ft_put_exa((n / 16)) + ft_putchar((n % 16) + '0'));
else
return (ft_put_exa((n / 16)) + ft_putchar((n % 16) - 10 + 'a'));
}
}
int ft_count_exa(long long unsigned int n, int i)
{
if (n < 16)
{
if (n < 10)
return (i + 1);
else
return (i + 1);
}
else
{
if ((n % 16) < 10)
return (ft_count_exa((n / 16), i + 1));
else
return (ft_count_exa((n / 16), i + 1));
}
}
void ft_print_struct(struct nlist_64 *el, int i, char *string_t)
{
char c;
int j;
c = ((el[i].n_type & N_TYPE ) == N_UNDF) ? 'U' : ' ';
c = ((el[i].n_type & N_TYPE) == N_SECT) ? 'T' : c;
c = ((el[i].n_type & N_TYPE) == N_ABS) ? 'A' : c;
c = ((el[i].n_type & N_TYPE) == N_PBUD) ? ' ' : c;
c = ((el[i].n_type & N_TYPE) == N_INDR) ? ' ' : c;
if (el[i].n_value > 1
&& strncmp(string_t + el[i].n_un.n_strx, "radr", 4))
{
j = ft_count_exa(el[i].n_value, 0);
while (j++ < 16)
ft_putchar('0');
ft_put_exa(el[i].n_value);
}
else if (strncmp(string_t + el[i].n_un.n_strx, "radr", 4))
ft_printf(" ");
if (strncmp(string_t + el[i].n_un.n_strx, "radr", 4))
ft_printf(" %c %s\n", c, string_t + el[i].n_un.n_strx);
}
void print_output(int nsyms, int symoff, int stroff, char *ptr)
{
int i;
char *string_t;
struct nlist_64 *el;
el = cpy_struct(nsyms, (void *)(ptr + symoff));
string_t = ptr + stroff;
el = sort_struct(el , nsyms, string_t);
i = 0;
while (i < nsyms)
{
ft_print_struct(el, i, string_t);
i++;
}
}
int handle_64(char *ptr)
{
int n_cmds;
struct mach_header_64 *header;
struct load_command *lc;
int i;
struct symtab_command *sym;
i = 0;
header = (struct mach_header_64 *) ptr;
lc = (struct load_command *)((char *)ptr + sizeof(*header));
n_cmds = header->ncmds;
while (i < n_cmds)
{
if (lc->cmd == LC_SYMTAB)
{
sym = (struct symtab_command *) lc;
print_output(sym->nsyms, sym->symoff, sym->stroff, ptr);
break ;
}
lc = (struct load_command *)((char *)lc + lc->cmdsize);
i++;
}
if (header->filetype == MH_EXECUTE)
return (1);
return (0);
}
|
C | #include <stdio.h>
int x=10;
int main()
{
int x=20;
{
int x=30;
printf("\n%d",x);
}
printf("\n%d",x);
return 0;
}
|
C | #define GEPPETTO_NAME "matrix" // Must be defined before including geppetto.h
#define GEPPETTO_VERIFY_H "build/"GEPPETTO_NAME".h"
#define GEPPETTO_VERIFY_C "build/"GEPPETTO_NAME".verify.c"
#define NUM_BANKS 3
#include "geppetto.h"
#include "pinocchio.h"
#ifndef MQAP
#include <stdio.h>
#include <string.h>
#include "pinocchio.c"
#endif
// size of the matrix (plain multiplication takes SIZE^3 multiplications)
//#define SIZE 3
#define SIZE 40
//#define SIZE 80
// number of bits in the input matrix (controls the need for truncation)
#define WIDTH 10
#define PRINT (SIZE < 11)
#define BASE 0
typedef struct { unsigned int a[SIZE][SIZE]; } matrix;
void fill(matrix *M, int seed) {
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++) {
M->a[i][j] = ((i * 13 + j * 17 + SIZE * SIZE * 7) * seed) % (1 << WIDTH);
}
}
// limits the need & costs of truncation on the result
void boundm(matrix *M) {
if (WIDTH < 31)
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
M->a[i][j] = bound(M->a[i][j], 0, (1 << WIDTH) - 1);
}
void printm(matrix *M) {
#if PRINT
for (int j = 0; j < SIZE; j++) printf(" ----------");
printf("\n");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++)
printf("| %8d ", M->a[i][j]);
printf("|\n");
}
for (int j = 0; j < SIZE; j++) printf(" ----------");
printf("\n\n");
#endif
}
void mul(matrix *M, matrix *N, matrix *R) {
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++) {
R->a[i][j] = 0;
for (int k = 0; k < SIZE; k++)
R->a[i][j] += M->a[i][k] * N->a[k][j];
}
}
BANK(bankM, matrix);
BANK(bankN, matrix);
BANK(bankR, matrix);
bankR job(bankM m, bankN n) {
matrix M, N, R;
load_bankM(m, &M);
load_bankN(n, &N);
boundm(&M);
boundm(&N);
mul(&M, &N, &R);
return save_bankR(&R);
}
bankR halfjob(bankN n) {
matrix M, N, R;
fill(&M, 5425);
load_bankN(n, &N);
boundm(&M);
boundm(&N);
mul(&M, &N, &R);
return save_bankR(&R);
}
int main() {
init();
matrix M, N, R;
printf("matrix multiplication takes %d *\n\n", SIZE*SIZE*SIZE);
fill(&M, 5425);
fill(&N, 7653);
printm(&M);
printm(&N);
bankM m = save_bankM(&M);
bankN n = save_bankN(&N);
bankR r;
r = OUTSOURCE(job, m, n);
load_bankR(r, &R);
printm(&R);
r = OUTSOURCE(halfjob, n);
load_bankR(r, &R);
printm(&R);
}
|
C | #include "holberton.h"
/**
* _isdigit - This function checks whether c is an integer 0-9
* @c: The integer to check
* Return: 1 if c is a digit, otherwise 0
*/
int _isdigit(int c)
{
if (c >= '0' && c <= '9')
return (1);
else
return (0);
}
|
C | /** This file contain main function and gtk functions only
* GtkWidget are declared global since passing more than 1 GtkWidget does not work
*/
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <time.h>
#include "game.h"
typedef struct input inputType;
/* Declare Global GTKWidget */
GtkWidget * coin[ROWS][COLS];
GtkWidget * playerImage;
GtkWidget * winnerImage;
GtkWidget * levelButton[3];
GtkWidget * button[COLS];
GtkWidget * newGameButton;
GtkWidget * quitGameButton;
/* structure input for drop_button parameters*/
struct input{
boardType * bInput;
int slot;
};
/* Delete main windows when user click Quit Game*/
gint delete_event( GtkWidget *widget,GdkEvent *event, gpointer user_data ){
gtk_main_quit();
return(FALSE);
}
/* This function is fired when the drop coin button is clicked */
void drop_coin(GtkWidget *widget,gpointer user_data){
int randomMove=0;
int winner=0;
inputType *input = (inputType *)user_data;
if(gameStatus == complete)return;
if(input->bInput->heights[input->slot]==ROWS)return;
if(gameStatus == newgame){
init_board(input->bInput);
gameStatus=ongoing;
}
gtk_image_set_from_file(coin[input->bInput->heights[input->slot]][input->slot],"CoinA.png");
make_move(input->bInput,input->slot);
winner = winner_is(input->bInput);
if(winner==1){
gtk_image_set_from_file(winnerImage,"CoinAWIN.png");
gameStatus = complete;
init_board(input->bInput);
return;
}
gtk_image_set_from_file(playerImage,"CoinBTURN.png");
if(gameDifficultyLevel== 0){
randomMove = get_easy_difficulty_move(input->bInput);
}else if(gameDifficultyLevel == 1){
randomMove = get_medium_difficulty_move(input->bInput);
}else if(gameDifficultyLevel == 2){
randomMove = get_high_difficulty_move(input->bInput);
}
if(input->bInput->heights[randomMove]==ROWS){
return;
}
gtk_image_set_from_file(coin[input->bInput->heights[randomMove]][randomMove],"CoinB.png");
make_move(input->bInput,randomMove);
winner = winner_is(input->bInput);
if(winner==-1){
gtk_image_set_from_file(winnerImage,"CoinBWIN.png");
gameStatus = complete;
init_board(input->bInput);
return;
}
gtk_image_set_from_file(playerImage,"CoinATURN.png");
}
/* This function is fired when any difficulty levels button is clicked
* -enable board
*/
void set_game(gint temp){
if(gameStatus == ongoing) return;
if(gameStatus == complete) return;
gameStatus = ongoing;
reset_board(FALSE,TRUE);
gtk_image_set_from_file(playerImage,"CoinATURN.png");
gtk_widget_set_sensitive(levelButton[temp],TRUE);
gameDifficultyLevel=temp;
}
/* This function is fired when newgame button is clicked
* -reset interface
*/
void reset_game(GtkWidget *widget,gpointer user_data){
gameDifficultyLevel=0;
gameStatus = newgame;
reset_board(TRUE,FALSE);
}
/*
* reset board interface
*/
void reset_board(gboolean levelState,gboolean buttonState){
int i,j;
for(i=0;i<3;i++){
gtk_widget_set_sensitive(levelButton[i],levelState);
}
for(j=0;j<COLS;j++){
gtk_widget_set_sensitive(button[j],buttonState);
}
for(i=0;i<ROWS;i++){
for(j=0;j<COLS;j++){
gtk_image_set_from_file(coin[i][j],"CoinC.png");
}
}
gtk_image_set_from_file(winnerImage,"NoWINNER.png");
gtk_image_set_from_file(playerImage,"NoWINNER.png");
}
/*
* setup new window
*/
void new_window(GtkWidget *win){
gtk_container_set_border_width (GTK_CONTAINER (win), 10);
gtk_window_set_title (GTK_WINDOW (win), "Connect4 Game");
gtk_window_set_position (GTK_WINDOW (win), GTK_WIN_POS_CENTER);
gtk_widget_realize (win);
gtk_window_set_default_size(GTK_WINDOW(win), 867, 460);
gtk_window_set_resizable (GTK_WINDOW(win), FALSE);
/* Catch event close main window */
g_signal_connect (win, "delete_event", GTK_SIGNAL_FUNC (delete_event), NULL);
}
/*
* setup component in the window
*/
void display_setting(GtkWidget *win){
int i,j,t=5;
GtkWidget *mainTable;
GtkWidget *boardTable;
GtkWidget *image[COLS];
GtkWidget *frame1,*frame2,*frame3,*frame4,*frame5;
GtkWidget *label1,*turnLabel;
GtkWidget *hbox1,*hbox2,*hbox3;
GtkWidget *vbox1,*vbox2,*vbox3,*vbox4,*vbox5,*vbox6;
gchar* str = g_malloc(10);
mainTable = gtk_table_new(8,11,TRUE);
gtk_container_add (GTK_CONTAINER (win), mainTable);
frame1 = gtk_frame_new ("GAME INSTRUCTIONS");
gtk_table_attach_defaults (GTK_TABLE(mainTable), frame1, 0, 4, 0, 3);
vbox1 = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (frame1), vbox1);
/* Standard message dialog */
label1 = gtk_label_new ("To Win:\nCONNECT 4 COINS IN A ROW, COLUMN OR DIAGONAL.\nTo Play:\n1. Select Difficulty Level.\n2. Click any SLOT BUTTON to drop your coin.\nNew Game: To play new game.\nTo Exit:Click button 'x' at the top right corner.");
gtk_box_pack_start (GTK_BOX (vbox1), label1, FALSE, FALSE, 0);
gtk_label_set_line_wrap( GTK_LABEL( label1 ), TRUE );
frame2 = gtk_frame_new ("DIFFICULTY LEVEL");
gtk_table_attach_defaults (GTK_TABLE(mainTable), frame2, 0, 2, 3, 5);
vbox2 = gtk_vbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (vbox2), 5);
gtk_container_add (GTK_CONTAINER (frame2), vbox2);
levelButton[0] = gtk_button_new_with_label("Easy");
gtk_container_add (GTK_CONTAINER (vbox2), levelButton[0]);
levelButton[1] = gtk_button_new_with_label("Medium");
gtk_container_add (GTK_CONTAINER (vbox2), levelButton[1]);
levelButton[2] = gtk_button_new_with_label("Hard");
gtk_container_add (GTK_CONTAINER (vbox2), levelButton[2]);
frame3 = gtk_frame_new ("PLAYER'S TURN");
gtk_table_attach_defaults (GTK_TABLE(mainTable), frame3, 2, 4, 3, 5);
vbox3 = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (frame3), vbox3);
playerImage = gtk_image_new_from_file("NoWINNER.png");
gtk_container_add (GTK_CONTAINER (vbox3), playerImage);
frame4 = gtk_frame_new ("WINNER");
gtk_table_attach_defaults (GTK_TABLE(mainTable), frame4, 2, 4, 5, 7);
vbox4 = gtk_vbox_new (FALSE, 0);
gtk_container_add(GTK_CONTAINER (frame4),vbox4);
winnerImage= gtk_image_new_from_file("NoWINNER.png");
gtk_container_add(GTK_CONTAINER (vbox4),winnerImage);
frame5 = gtk_frame_new ("GAME");
gtk_table_attach_defaults (GTK_TABLE(mainTable), frame5, 0, 2, 5, 7);
vbox5 = gtk_vbox_new(FALSE,0);
gtk_container_add (GTK_CONTAINER (frame5), vbox5);
newGameButton = gtk_button_new_with_label("New");
gtk_container_add (GTK_CONTAINER (vbox5), newGameButton);
quitGameButton = gtk_button_new_with_label("Quit");
gtk_container_add (GTK_CONTAINER (vbox5), quitGameButton);
turnLabel = gtk_label_new("Design Copyright 2014 by bizz-enigma.");
gtk_table_attach_defaults (GTK_TABLE(mainTable), turnLabel, 0, 4+COLS, 1+ROWS, 2+ROWS);
for(j=0;j<COLS;j++){
g_snprintf(str,10, "slot%d.png",j);
button[j] = gtk_button_new();
image[j] = gtk_image_new_from_file(str);
gtk_button_set_image(button[j],image[j]);
gtk_table_attach_defaults (GTK_TABLE(mainTable), button[j], j+4, j+5, 0, 1);
gtk_widget_set_sensitive(button[j],FALSE);
}
boardTable = gtk_table_new (ROWS,COLS,FALSE);
gtk_table_attach_defaults (GTK_TABLE(mainTable), boardTable, 4, 4+COLS, 1, 1+ROWS);
for(i=0;i<ROWS;i++){
for(j=0;j<COLS;j++){
coin[i][j] = gtk_image_new_from_file("CoinC.png");
gtk_table_attach_defaults (GTK_TABLE(boardTable), coin[i][j], j, j+1, t, t+1);
}t-=1;
}
}
int main(int argc, char** argv) {
GtkWidget *win = NULL;
int i;
boardType * b = create_board(); //create board
init_board(b); //init board
srand (time(NULL));
gameStatus = newgame;
/* error handler lines commented out for future use and not require for software release*/
//g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, (GLogFunc) gtk_false, NULL); //delete at the end
gtk_init (&argc, &argv);
//g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, g_log_default_handler, NULL); //delete at the end
/*initialize new window from gtk library*/
win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
new_window(win);
/* setup window display */
display_setting(win);
/* start parsing data to gtk event */
inputType data[COLS];
for(i=0;i<COLS;i++){
data[i].bInput = b;
data[i].slot = i;
g_signal_connect (button[i], "clicked", G_CALLBACK (drop_coin),&data[i]);
}
for(i=0;i<3;i++){
gtk_signal_connect_object (levelButton[i], "clicked", G_CALLBACK(set_game),i);
}
gtk_signal_connect_object (newGameButton, "clicked", G_CALLBACK(reset_game),NULL);
gtk_signal_connect_object (quitGameButton, "clicked", G_CALLBACK(delete_event),NULL);
/* end parsing data to gtk event */
gtk_widget_show_all (win);
gtk_main ();
/* free up allocated memory from the application */
delete_board(b);
return 0;
}
|
C | #include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
char main()
{
char a[20];
scanf_s("\n");
scanf_s("%[^\n]%*c", &a[20]);
printf("\nhere is the output= %s", a);
return 0;
} |
C | #include<stdio.h>
#include<conio.h>
void main()
{
int num;
system("cls");
printf("The even Number from 1 to 30 are: \n");
for (num =2; num<=30; num+=2)
printf("%d\n", num);
}
|
C | ////
//// Created by ſ on 2017/8/14.
////
//#include <stdio.h>
//#include <malloc.h>
//#include <math.h>
//
//#define OK 1
//#define ERROR 0
//#define TRUE 1
//#define FALSE 0
//
//typedef int Status; /* StatusǺ,ֵǺ״̬,OK */
//typedef char TElemType;
//typedef enum {
// Link, Thread
//} PointerTag; /* Link==0ʾָҺָ, */
///* Thread==1ʾָǰ̵ */
//
//typedef struct BiThrNode {
// TElemType data; /**/
// struct BiThrNode *leftChild, *rightChild; /*ҽ*/
// PointerTag LTag, RTag; /*ұ־ָָָָ뻹*/
//} BiThrNode, *BiThrTree;
//
//TElemType Nil = '#';
//
//Status visit(TElemType e) {
// printf("%c", e);
// return OK;
//}
//
///* ǰнֵ,T */
///* 0()/ո(ַ)ʾս */
//Status CreateBiThrTree(BiThrTree *T) {
// TElemType h;
// scanf("%c", &h);
//
// if (h == Nil)
// *T = NULL;
// else {
// *T = (BiThrTree) malloc(sizeof(BiThrNode));
// if (!*T) /*ڴʧ*/
// exit(OVERFLOW);
// (*T)->data = h; /*ɸڵ*/
// CreateBiThrTree(&(*T)->leftChild); /*ݹ鴴ӣӵĵַݹ*/
// /*ɺжָ뻹*/
// if ((*T)->leftChild)
// (*T)->LTag = Link;
// /*ͬҺ*/
// CreateBiThrTree(&(*T)->rightChild);
// if ((*T)->rightChild)
// (*T)->RTag = Link;
// }
// return OK;
//}
//
//BiThrTree pre; /* ȫֱ,ʼָոշʹĽ */
///* */
///*˼·ԽҶӽ㾡ܶı¶ʹ
// Ϊյʱһεݹ飬ҵҶӽ*/
///*裺
// ΪҶӽʱΪǰ㣨˴ҪһȫֱǰϢ
// ţжǰǷڣǰĺΪǰҶӽڵ
// ǰΪǰ㣨ǰһʼǰҪָ */
//void InThreading(BiThrTree p) {
// if (p) {
// InThreading(p->leftChild); /*ҵߵҶӽڵ*/
// if (!p->leftChild) { /*ǰû*/
// p->LTag = Thread; /* ǰڵǰ */
// p->leftChild = pre;
// }
// if (!pre->rightChild) { /*ǰûҺӣעʹõǰǰһú */
// pre->RTag = Thread; /* ǰĺ */
// pre->rightChild = p; /* ǰҺָָ(ǰp) */
// }
// pre = p; /*preָpǰ*/
// InThreading(p->rightChild); /* ݹ */
// }
//}
//
///* T,,Theadָͷ */
///*Ϊ˱֤нһԣDz˫ͷ㣬һheadͷڱ֤һ*/
//Status InOrderThreading(BiThrTree *Thead,BiThrTree T){
// *Thead= (BiThrTree )malloc(sizeof(BiThrNode));
// if(!*Thead)
// exit(OVERFLOW);
// (*Thead)->LTag=Link; /* ͷ */
// (*Thead)->RTag=Thread;
// (*Thead)->rightChild=(*Thead); /* ָָ */
// if (!T) /* ,ָָ */
// (*Thead)->leftChild=(*Thead);
// else{
// (*Thead)->leftChild=T;
// pre=(*Thead);
// InThreading(T);
// pre->RTag=Thread; /* һ */
// pre->rightChild=(*Thead);
// (*Thead)->rightChild=pre; /*ͷָһ㣬γһ˫*/
// }
// return OK;
//}
//
///* T(ͷ)ķǵݹ㷨 */
//Status InOrderTraverse_Thr(BiThrTree T){
// BiThrTree p=T->leftChild; /*pָڵ*/
// while(p!=T){ /*߱ʱp==T*/
// while(p->LTag==Link) /*ҵһʼĽ*/
// p=p->leftChild;
// if(!visit(p->data)) /**/
// return ERROR; /*ǰΪգ쳣*/
// while(p->RTag==Thread&&p->rightChild!=T){ /*ѭм*/
// p=p->rightChild;
// visit(p->data);
// }
// p=p->rightChild; /*ָָҽڵ*/
// }
// return OK;
//}
//
///**/
//Status InReverse(BiThrTree T){
// BiThrTree p=T->rightChild;
// while(p!=T){
// while(p->RTag==Link)
// p=p->rightChild;
// if (!visit(p->data))
// exit(OVERFLOW);
// while(p->LTag==Thread&&p->leftChild!=T){
// p=p->leftChild;
// visit(p->data);
// }
// p=p->leftChild;
// }
// return OK;
//}
//
//void main() {
// BiThrTree H,T;
// printf("밴ǰ(:'ABDH##I##EJ###CF##G##')\n");
// CreateBiThrTree(&T); /* ǰ */
// InOrderThreading(&H,T); /* , */
// printf("():\n");
// InOrderTraverse_Thr(H); /* () */
// printf("\n");
// InReverse(H);
//}
|
C | /*
Program: Ch4_Ex4_29_MorgansLaws.c
Descripción: Morgan's Laws state that the expression !(condition1 && condition2)
is logically equivalent to the expression (!condition1 || !condition2).
Also, the expression !(condition1 || condition2) is logically
equivalent to the expression (!condition1 && !condition2).
Autor: Elle518
v1.0
This code is in the public domain.
*/
#include <stdio.h>
int main(void) {
int x, y, a, b, g, i, j;
// a)
x = 1;
y = 3;
if ((!(x < 5) && !(y >= 7)) == (!(x < 5 || y >= 7))) {
puts("!(x < 5) && !(y >= 7) and !(x < 5 || y >= 7) are equivalent.");
} else {
puts("!(x < 5) && !(y >= 7) and !(x < 5 || y >= 7) are not equivalent.");
}
puts("");
// b)
a = 1;
b = 3;
g = 5;
if ((!(a == b) || !(g != 5)) == (!(a == b && g != 5))) {
puts("!(a == b) || !(g != 5) and !(a == b && g != 5) are equivalent.");
} else {
puts("!(a == b) || !(g != 5) and !(a == b && g != 5) are not equivalent.");
}
puts("");
// c)
x = 1;
y = 3;
if ((!(x <= 8 && y > 4)) == (!(x <= 8) || !(y > 4))) {
puts("!(x <= 8 && y > 4) and !(x <= 8) || !(y > 4) are equivalent.");
} else {
puts("!(x <= 8 && y > 4) and !(x <= 8) || !(y > 4) are not equivalent.");
}
puts("");
// d)
i = 1;
j = 3;
if ((!(i > 4 || j <= 6)) == (!(i > 4) && !(j <= 6))) {
puts("!(i > 4 || j <= 6) and !(i > 4) && !(j <= 6) are equivalent.");
} else {
puts("!(i > 4 || j <= 6) and !(i > 4) && !(j <= 6) are not equivalent.");
}
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double Mask(int b, int w);
int main(void){
int b,w;
scanf("%d %d",&b,&w);
double mask = Mask(b,w);
printf("%x\n",(long long int)mask);
getchar();
return 0;
}
double Mask(int b, int w){
double mask = 0.0;
int i,j;
for(i=0;i<64;i++){
if(b==i){
for(j=b;j<(w+b);j++){
if(j==1){
mask = mask +1;
}else
{
mask = mask + pow(2.0,(double)(j-1));
}
}
}
}
return mask;
}
|
C | /*
* This file is part of ce.
*
* Copyright (c) 1990 by Chester Ramey.
*
* Permission is hereby granted to copy, reproduce, redistribute or
* otherwise use this software subject to the following:
* 1) That there be no monetary profit gained specifically from
* the use or reproduction of this software.
* 2) This software may not be sold, rented, traded or otherwise
* marketed.
* 3) This copyright notice must be included prominently in any copy
* made of this software.
*
* The author makes no claims as to the fitness or correctness of
* this software for any use whatsoever, and it is provided as is.
* Any use of this software is at the user's own risk.
*/
/*
* dir.c -- directory management functions
*
* originally by Ron Flax ([email protected]) and Mic Kaczmarczik, from mg2a
*/
#include "celibc.h"
#include "ce.h"
#ifndef NULL
#define NULL 0
#endif
char *wdir;
char home[512];
static char cwd[512];
extern char *tilde();
/*
* Initialize anything the directory management routines need
*/
void
dirinit()
{
char *pwd;
pwd = getenv("PWD");
if (pwd == NULL)
pwd = getenv("CWD");
if (pwd) {
strncpy(cwd, pwd, sizeof(cwd));
wdir = cwd;
} else {
if ((wdir = getcwd(cwd, sizeof(cwd))) == NULL)
panic("Can't get current directory!");
}
strncpy(home, getenv("HOME"), sizeof(home) - 1);
home[sizeof(home) -1] = '\0';
}
/*
* Change current working directory
*/
/*ARGSUSED*/
int
changedir(f, n)
int f, n;
{
register int s;
char bufc[NPAT], dbuf[NPAT], *d;
if ((s = mlgetfile("Change working directory: ", bufc, NPAT)) != TRUE)
return(s);
if (bufc[0] == '\0')
(void) strcpy(dbuf, wdir);
else {
d = tilde(bufc, dbuf, sizeof(dbuf));
if (d == 0) {
mlwrite("%s: no such directory", bufc);
return(FALSE);
}
}
if (chdir(dbuf) == -1) {
mlwrite("Can't change dir to %s", bufc);
return(FALSE);
} else {
if ((wdir = getcwd(cwd, sizeof(cwd))) == NULL)
panic("Can't get current directory!");
mlwrite("Current directory is now %s", wdir);
return(TRUE);
}
}
/*
* Show current directory
*/
/*ARGSUSED*/
int
showcwd(f, n)
int f, n;
{
mlwrite("Current directory: %s", wdir);
return(TRUE);
}
#ifndef HAVE_GETCWD
/*
* getcwd -- Posix 1003.1 get current directory function, built atop the
* 4.2 BSD getwd() function.
*
* This departs from the 1003.1 spec in that it returns an error message
* in `dir' if it fails. As in the spec, getcwd() returns NULL and sets
* errno appropriately on failure.
*/
#include <errno.h>
#include <sys/param.h>
#ifndef NULL
#define NULL 0x0
#endif
#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif
extern int errno;
extern char *getwd();
static char wd[MAXPATHLEN];
char *
getcwd(buf, size)
char *buf;
int size;
{
char *d;
if (size <= 0) {
errno = EINVAL;
return ((char *) NULL);
}
d = getwd(wd);
strncpy(buf, wd, size - 1);
buf[size - 1] = '\0';
if (d == NULL)
return ((char *) NULL);
if (strlen(wd) >= (size - 1)) {
errno = ERANGE;
return ((char *) NULL);
}
return (&buf[0]);
}
#endif
|
C | //
// bo2-6.h
// 实际应用链表类型
//
// Created by chilim on 2018/10/21.
// Copyright © 2018年 chilim. All rights reserved.
//
#ifndef bo2_6_h
#define bo2_6_h
#include <stdio.h>
#include "c2-5.h"
// 分配由p指向的值为e的结点。若分配失败,则退出
void MakeNode(Link *p,ElemType e);
// 释放p所指结点
void FreeNode(Link *p);
// 构造一个空的线性链表L
void InitList(PLinkList *L);
// 将线性链表L重置为空表,并释放原链表的结点空间
void ClearList(PLinkList *L);
// 将指针s(s->data为第一个数据元素)所指(彼此以指针相链,以NULL结尾)的
// 一串结点链接在线性链表L的最后一个结点之后,并改变链表L的尾指针指向新的尾结点
void Append(PLinkList *L,Link s);
// h指向L的一个结点,把h当做头结点,删除链表中的第一个结点并以q返回。
// 若链表为空(h指向尾结点),q=NULL,返回FALSE
Status DelFirst(PLinkList *L,Link h,Link *q);
//// h指向L的一个结点,把h当做头结点,将s所指结点插入在第一个结点之前
void InsFirst(PLinkList *L,Link h,Link s);
// 销毁线性链表L,L不再存在
void DestroyList(PLinkList *L);
// 已知p指向线性链表L中的一个结点,返回p所指结点的直接前驱的位置。若无前驱,则返回NULL
Position PriorPos(PLinkList L,Link p);
// 删除线性链表L中的尾结点并以q返回,改变链表L的尾指针指向新的尾结点
Status Remove(PLinkList *L,Link *q);
// 已知p指向线性链表L中的一个结点,将s所指结点插入在p所指结点之前,
// 并修改指针p指向新插入的结点
void InsBefore(PLinkList *L,Link *p,Link s);
// 已知p指向线性链表L中的一个结点,将s所指结点插入在p所指结点之后,
// 并修改指针p指向新插入的结点
void InsAfter(PLinkList *L, Link *p,Link s);
// 已知p指向线性链表中的一个结点,用e更新p所指结点中数据元素的值
void SetCurElem(Link p,ElemType e);
// 已知p指向线性链表中的一个结点,返回p所指结点中数据元素的值
ElemType GetCurElem(Link p);
// 若线性链表L为空表,则返回TRUE;否则返回FALSE
Status ListEmpty(PLinkList L);
// 返回线性链表L中元素个数
int ListLength(PLinkList L);
// 返回线性链表L中头结点的位置
Position GetHead(PLinkList L);
// 返回线性链表L中最后一个结点的位置
Position GetLast(PLinkList L);
// 已知p指向线性链表L中的一个结点,返回p所指结点的直接后继的位置。若无后继,则返回NULL
Position NextPos(Link p);
// 返回p指示线性链表L中第i个结点的位置,并返回OK,i值不合法时返回ERROR。i=0为头结点
Status LocatePos(PLinkList L,int i,Link *p);
// 返回线性链表L中第1个与e满足函数compare()判定关系的元素的位置,
Position LocateElem(PLinkList L,ElemType e,Status (*compare)(ElemType ,ElemType));
// 依次对L的每个数据元素调用函数visit()
void ListTraverse(PLinkList L,void(*visit)(ElemType));
// 已知L为有序线性链表,将元素e按非降序插入在L中。(用于一元多项式)
void OrderInsert(PLinkList *L, ElemType e,int (*comp)(ElemType,ElemType));
// 若升序链表L中存在与e满足判定函数compare()取值为0的元素,则q指示L中
// 第一个值为e的结点的位置,并返回TRUE;否则q指示第一个与e满足判定函数
Status LocateElem1(PLinkList L,ElemType e,Position *q,int (*compare)(ElemType,ElemType));
#endif /* bo2_6_h */
|
C | /*
============================================================================
Name :Abdikarim Ibrahim
Date : 06/13/18
Description : This program converts kilometers to miles.
============================================================================
*/
#include <stdio.h>
#define ADJUST 0 // one kind of symbolic constant
int main(void)
{
const double SCALE = 0.6214; // another kind of symbolic constant
double km, mile,i;
printf("Enter Km to be converted: \n");
scanf("%.2f",&km);
i = 100 ;
while (km < i) /* starting the while loop */
{ /* start of block */
mile = SCALE * km + ADJUST;
printf("%10.1f %15.2f miles\n", km, mile);
km = km + 1.0;
} /* end of block */
printf("That is it. You have converted \n");
return 0;
}
|
C | #include "Color.h"
Color ColorRGB(unsigned int r, unsigned int g, unsigned int b) {
Color newColor;
newColor.r = r;
newColor.g = g;
newColor.b = b;
return newColor;
} |
C | /*
Esse programa apresenta as iniciais das palavras digitadas por um usuário,
essas palavras tem o limite de 99 caracteres + \0;
O dado de entrada é ou são as palavras que o usuário digitar;
Esse dado é capturado por meio de um scanf() com o formato %c;
Esses caracteres serão armazenadas em um array unidimensional de 100 posições;
Feito por Marcus Vinícius Torres Silva em 04/09/2020.
*/
#include <stdio.h>
const int MAX = 100; /* Limite de posições. */
int
main()
{
unsigned char palavra[MAX]; // Array para armazenar os caracteres.
int c = 0; // Indexador.
// Lendo os caracteres que o usuário digitar através de um laço de repetição.
printf ("Digite uma palavra ou mais palavras: ");
do
{
scanf ("%c",&palavra[c]);
if (palavra[c] == '\n')
{
palavra[c] = '\0';
break;
}
c++;
} while (palavra[c] != '\n');
// Mostrando na tela as iniciais das palavras
c = 0;
printf ("%c",palavra[c]);
while (palavra[c] != '\0')
{
if (palavra[c] == ' ')
{
printf ("%c",palavra[c+1]);
}
c++;
}
return 0;
}
|
C | /*************************************************************************************
* This program is built based on SM4 S-box algorithm : *
* Ref. Boolean Matrix Masking : * *
* *
************************************************************************************/
#include "SM4sbox.h"
uint8_t M_A1_A2(uint8_t mask){
int i, j, k;
uint8_t A1 = 0xa7;
uint8_t A2 = 0xcb;
uint8_t flag1, flag2;
int r = 0;
uint8_t result[64];
/*calculate (A1*A2)*/
for(i = 0; i < 8; i++){
for(j = 0; j < 8; j++){
uint8_t mul = 0;
uint8_t tmp = A1 & A2;
for(k = 0; k < 8; k++){
mul ^= (tmp & 1);
tmp >>= 1;
}
result[r] = mul;
//printf("%d ", result[r]);
r++;
flag2 = (A2 & 0x80) >> 7;
A2 <<= 1;
A2 |= flag2;
}
flag1 = (A1 & 0x80) >> 7;
A1 <<= 1;
A1 |= flag1;
//printf("\n");
}
/*calculate (M*A1*A2)*/
int M = mask;
uint8_t MAA = 0;
for(i=0; i<8; i++){
uint8_t tmpAA[8]={0}; /*make AA from horizontal to vertical*/
uint8_t tmpMAA, tmp;
for(j=0; j<8; j++) tmpAA[i] |= (result[i + j*8] << j);
tmpMAA = M & tmpAA[i];
tmp = 0;
for(j=0; j<8; j++){
tmp ^= (tmpMAA & 1);
tmpMAA >>= 1;
}
MAA |= tmp << i;
}
return MAA;
}
void mask(FILE *op){
int i, j;
fprintf(op, "\n__________________________________SM4 S-box with masking__________________________________\n\n");
fprintf(op, "\t(sbox, maske_sbox, ref_out)\n");
for(i=0;i<=0xf;i++)fprintf(op, "\t%x\t",i);
fprintf(op, "\n");
for(i=0;i<=0xf;i++){
fprintf(op, "%x",i);
for(j=0;j<=0xf;j++){
int sbox = affine(0xa7,inverse(0x1f5,affine(0xa7, (i<<4)|j, 0xd3)), 0xd3);
uint8_t mask = 1;
int mask_input = ((i<<4)|j) ^ mask;
int masked_out = affine(0xa7,inverse(0x1f5,affine(0xa7, mask_input, 0xd3)), 0xd3);
int ref_out = sbox ^ M_A1_A2(mask);
fprintf(op, "\t(%02x, %02x, %02x)", sbox, masked_out, ref_out);
}
fprintf(op, "\n");
}
}
int main(void){
int i, j;
FILE *op;
op = fopen("output", "w");
if (op == NULL){
printf("Cannot open output file\n");
exit(0);
}
fprintf(op, "\n__________________________________SM4 S-box__________________________________\n\n");
for(i=0;i<=0xf;i++)fprintf(op, "\t%x",i);
fprintf(op, "\n");
for(i=0;i<=0xf;i++){
fprintf(op, "%x",i);
for(j=0;j<=0xf;j++){
fprintf(op, "\t%02x",affine(0xa7,inverse(0x1f5,affine(0xa7, (i<<4)|j, 0xd3)), 0xd3));
}
fprintf(op, "\n");
}
mask(op);
fclose(op);
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct {
char maSinhVien[50];
char ten[50];
char soDienThoai[50];
} SinhVien;
void removeStdChar(char array[]) {
if (strchr(array, '\n') == NULL) {
while (fgetc(stdin) != '\n');
}
}
FILE *fp;
int soSinhVien;
bool validateStudentNumber(int soSinhVien) {
if (soSinhVien == 10) {
printf("Ban da them qua muoi sinh vien!\n");
return false;
} else {
return true;
}
}
SinhVien sinhVien[10];
int themSinhVien() {
printf("Moi nhap thong tin sinh vien.\n");
int i = 0;
for (i = 0; i < 11; i++) {
soSinhVien = i;
bool isValidateStudentNumber = validateStudentNumber(soSinhVien);
if (isValidateStudentNumber == false) {
break;
} else {
printf("Moi nhap ma so sinh vien cua sinh vien thu %d: \n", i + 1);
fgets(sinhVien[i].maSinhVien, sizeof(sinhVien[i].maSinhVien), stdin);
removeStdChar(sinhVien[i].maSinhVien);
sinhVien[i].maSinhVien[strlen(sinhVien[i].maSinhVien) - 1] = ' ';
while (strlen(sinhVien[i].maSinhVien) < 6){
printf("Moi nhap lai ma sinh vien do khong du 5 ky tu: \n");
fgets(sinhVien[i].maSinhVien, sizeof(sinhVien[i].maSinhVien), stdin);
removeStdChar(sinhVien[i].maSinhVien);
sinhVien[i].maSinhVien[strlen(sinhVien[i].maSinhVien) - 1] = ' ';
}
printf("Moi nhap ten sinh vien: \n");
fgets(sinhVien[i].ten, sizeof(sinhVien[i].ten), stdin);
removeStdChar(sinhVien[i].ten);
sinhVien[i].ten[strlen(sinhVien[i].ten) - 1] = ' ';
printf("Moi nhap so dien thoai: \n");
fgets(sinhVien[i].soDienThoai, sizeof(sinhVien[i].soDienThoai), stdin);
removeStdChar(sinhVien[i].soDienThoai);
sinhVien[i].soDienThoai[strlen(sinhVien[i].soDienThoai) - 1] = ' ';
int choice2;
printf("Ban co muon tiep tuc? 1. Co | 2. Khong\n");
scanf("%d", &choice2);
getchar();
if(choice2 == 2){
return 0;
}
}
}
}
void hienThiDanhSachSV() {
printf("Danh sach sinh vien.\n");
printf("|%-20s|%-20s|%-20s|\n", "Ma sinh vien", "Ten sinh vien", "So dien thoai");
for (int i = 0; i < soSinhVien + 1; ++i) {
printf("|%-20s|%-20s|%-20s|\n", sinhVien[i].maSinhVien, sinhVien[i].ten,
sinhVien[i].soDienThoai);
}
}
void docDanhSach() {
fp = fopen("../danhsachsinhvien.txt", "r+");
printf("Danh sach sinh vien da luu trong file la:\n");
char varChar[1000];
while (fgets(varChar, 1000, fp) != NULL) {
printf("%s", varChar);
}
fclose(fp);
}
void luuDanhSach() {
fp = fopen("../danhsachsinhvien.txt", "w+");
fprintf(fp, "|%-20s", "Ma so sinh vien");
fprintf(fp, "|%-20s", "Ten sinh vien");
fprintf(fp, "|%-20s|\n", "So dien thoai");
for (int i = 0; i < soSinhVien + 1; ++i) {
fprintf(fp, "|%-20s", sinhVien[i].maSinhVien);
fprintf(fp, "|%-20s", sinhVien[i].ten);
fprintf(fp, "|%-20s|\n", sinhVien[i].soDienThoai);
}
fclose(fp);
printf("Da luu danh sach sinh vien ra file nhu sau:\n");
docDanhSach();
}
int main() {
int choice;
while(1) {
printf("Menu\n");
printf("1. Them moi sinh vien\n");
printf("2. Hien thi danh sach sinh vien\n");
printf("3. Luu danh sach sinh vien ra file\n");
printf("4. Doc danh sach sinh vien tu file\n");
printf("5. Thoat chuong trinh\n");
printf("Moi nhap lua chon 1|2|3|4|5\n");
scanf("%d", &choice);
getchar();
switch (choice) {
case 1:
themSinhVien();
break;
case 2:
hienThiDanhSachSV();
break;
case 3:
luuDanhSach();
break;
case 4:
docDanhSach();
break;
case 5:
printf("Thoat chuong trinh.\n");
return 0;
default:
printf("Nhap sai yeu cau. Moi nhap lai.\n");
continue;
}
}
} |
C | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* File: lcmTable.h *
* Course: CPSC457 *
* Author: Chris Wozniak *
* SID: 10109820 *
* *
* This module contains the primary support functions *
* for the 'table' method of finding the LCM of a list *
* of integers. Unsigned integers are used for output. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "arrayMgmt.h"
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* lcm *
* *
* lcm follows the method found on the assignment *
* which describes a 'table method' for determining *
* the lowest common multiple found in the following *
* link: *
* http://wikipedia.org/wiki/least_common_multiple *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
unsigned int lcm(struct intArray ia){
struct intArray primeArray = loadIntFile("primes.txt");
unsigned int val = 1;
int j = 0;
int currentPrime = primeArray.dataArray[j];
int i;
int currentPrimeRemains = 0;
int allValuesReduced = 0;
// If we have an array with values greater than 1
while (! allValuesReduced){
allValuesReduced = 1;
currentPrimeRemains = 0;
// Loop through the array
for (i = 0; i < ia.size; i++){
// if the value is not one
if (ia.dataArray[i] != 1){
// AND is divisible by the current prime number
if (ia.dataArray[i] % currentPrime == 0){
// We use the same prime again, and divide the
// result.
currentPrimeRemains = 1;
ia.dataArray[i] = ia.dataArray[i] / currentPrime;
} else {
allValuesReduced = 0;
}
}
}
// If the current prime needs to be reused
if (currentPrimeRemains){
val = val * (unsigned int)currentPrime;
currentPrimeRemains = 0;
allValuesReduced = 0;
} else {
// If we're not done
if (!allValuesReduced){
// non-reduced values means we step
// to the next prime and continue.
j++;
currentPrime = primeArray.dataArray[j];
currentPrimeRemains = 1;
}
}
}
return val;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*END OF FILE END OF FILE END OF FILE END OF FILE END OF FILE END OF FILE END *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
|
C | /* File: mfr32.c */
#include "port.h"
#include "mfr32.h"
EXPORT Frac16 mfr32SqrtC (Frac32);
/*******************************************************
* Misc 32-bit Fractional Math
*******************************************************/
Frac16 mfr32SqrtC (Frac32 x)
{
Frac16 Est;
Frac16 EstR;
Frac16 Bit = 0x4000;
Frac32 Temp;
UInt16 i;
Est = 0x0000;
for (i=0; i<14; i++)
{
Est = add(Est, Bit);
Temp = L_mult(Est,Est);
if (Temp > x)
{
Est = sub(Est, Bit);
}
Bit = shr (Bit, 1);
}
/* Choose between estimate & rounded estimate for most accurate result */
EstR = add(Est, 1);
if (L_abs(L_sub(x,L_mult(EstR, EstR))) < L_sub(x,L_mult(Est,Est)))
{
Est = EstR;
}
return Est;
}
|
C | #include <stdio.h>
#include <string.h>
#include "utc_hal_log.h"
#include "utc_hal_timer.h"
static u32 gSysTimerClk;
static u32 gSystemTick = 0;
static u8 gServiceSysTickTimer = 0;
p_system_tick_handle_t gSysTickFunc = NULL;
static u8 g_threadtimer = 1;
void closeThreadTimer(){
g_threadtimer = 0;
}
static inline void timer_1ms_handle(void)
{
if(gSysTimerClk)
{
gSysTimerClk--;
}
if(gSysTickFunc)
{
gSysTickFunc();
}
gSystemTick++;
}
static void *thread_timer_1ms_handle(void *arg)
{
//提供函数回调保护
while(g_threadtimer){
timer_1ms_handle();
utc_hal_log(TRMOD_TIMER, TRLEV_DEBUG, "thread1 is running\n");
#ifdef CONFIG_IDF_TARGET_ESP8266
usleep(500);
#else
usleep(1000);
#endif
}
vTaskDelete(NULL);
return NULL;
}
/*******************************************************************************
* Function : utc_hal_system_tick_register
* Description : 1ms系统时钟处理
* Input : typedef void (*SysTickHandle_t)(void);
* Output : none
* Return : OS_OK 注册成功
* other 注册失败
* Others :
*******************************************************************************/
s32 utc_hal_system_tick_register(p_system_tick_handle_t handler)
{
if (NULL != handler) {
gSysTickFunc = handler;
}
if (1 == gServiceSysTickTimer) {
return OS_OK;
}
gServiceSysTickTimer = 1;
utc_hal_log(TRMOD_TIMER, TRLEV_DEBUG, "utc_hal_system_tick_register\n");
xTaskCreate((void (*)(void *))thread_timer_1ms_handle, "timer", 2048, NULL, 5, NULL);
return OS_OK;
}
/*******************************************************************************
* Function : utc_system_tick_current
* Description : 系统启动后经历的ms数
* Input : none
* Output : none
* Return : >0 ms数
* <0 失败
* Others :
*******************************************************************************/
s32 utc_hal_system_tick_current(void)
{
return gSystemTick;
}
/*******************************************************************************
* Function : utc_hal_set_system_tick
* Description : 设置系统tick时间
* Input : ms
* Output : none
* Return : none
*
* Others :
*******************************************************************************/
void utc_hal_set_system_tick(u32 ms)
{
gSysTimerClk = ms;
}
/*******************************************************************************
* Function : DRV_DelayMs
* Description : 毫秒延时ms
* Input : Ms
* Output : none
* Return : none
*
* Others :
*******************************************************************************/
void utc_hal_delay_ms(u32 ms)
{
usleep(1000*ms);
}
/*******************************************************************************
* Function : utc_hal_delay_us
* Description : 微秒延时us
* Input : Ms
* Output : none
* Return : none
*
* Others :
*******************************************************************************/
void utc_hal_delay_us(u32 us)
{
usleep(us);
}
|
C | #include "crossover.h"
void crossMut(popptr p1){
int prob_crs=rand()%10;
if(prob_crs<PROB_CROSSOVER){
crossover(p1);
}
else{
mutation(p1);
}
}
void mutation(popptr p1){
printf("\n Mutation Started");
geneptr parent1=naryTrnment(p1);
geneptr child=createCopyGene(parent1);
int max_vms_to_be_removed=20;
int min_vms_to_be_removed=5;
int vms_to_be_removed=min_vms_to_be_removed+(rand()%(max_vms_to_be_removed-min_vms_to_be_removed));
printf("\n In Mutation: Removing %d Vms",vms_to_be_removed);
int removed_count=0;
for(int i=0;(i<child->npm)&&(removed_count<vms_to_be_removed);i++){
pmptr pm=child->pm_list[i];
for(int j=0;(j<pm->nvm)&&(removed_count<vms_to_be_removed);j++){
vmptr vm=pm->vm_list[j];
if(vm->utlz>VM_UNPACK_THRSHLD){
continue;
}
removeVm(vm,pm);
removed_count++;
}
}
int cn_absent[CNT_SIZE];
int absent_count=findAbsentContainers(child,cn_absent);
printf("\nIn Mutation: %d Containers Removed from %d vms",absent_count,removed_count);
heuristics2(child,cn_absent,absent_count);
printf("\nIn Mutation:End");
postCrossMut(child,p1);
}
void crossover(popptr p1){
printf("\nCrossover Started");
geneptr parent1=naryTrnment(p1);
geneptr parent2=naryTrnment(p1);
while(parent1==parent2){
parent2=naryTrnment(p1);
}
printf("\n\nparent 1 utilization:%f,parent 2 utilization:%f",parent1->utlz,parent2->utlz);
geneptr child1=crossover2(parent1, parent2, 0);
geneptr child2=crossover2(parent1, parent2, 1);
postCrossMut(child1,p1);
postCrossMut(child2,p1);
printf("\nCrossover Done");
}
geneptr naryTrnment(popptr h1){
geneptr genelist[TRN_SIZE];
for(int i=0;i<TRN_SIZE;i++){
int ran=rand()%h1->n;
genelist[i]=h1->gene_list[ran];
}
float best_utlz=0;
geneptr best_gene=NULL;
int random_gene_no=rand()%TRN_SIZE;
geneptr random_gene=genelist[random_gene_no];
for(int i=0;i<TRN_SIZE;i++){
if( best_utlz < genelist[i]->utlz ){
best_gene=genelist[i];
best_utlz=genelist[i]->utlz;
}
}
int dc=rand()%10;
if(dc<6){
return best_gene;
}
return random_gene;
}
//sub function of crossover, which takes 2 parents as input and returns a child pointer. if sort_pm_by_cpu is 1 pms are sorted by cpu.
geneptr crossover2(geneptr parent1,geneptr parent2,int sort_pm_by_cpu){
printf("\ncrossover2 started");
geneptr child=create_gene();
parent1=createCopyGene(parent1);
parent2=createCopyGene(parent2);
sortPmByUtlz(parent1,sort_pm_by_cpu);
sortPmByUtlz(parent2,sort_pm_by_cpu);
fitness(parent1);
fitness(parent2);
int min_npm = parent1->npm <= parent2->npm ? parent1->npm : parent2->npm;
pmptr pm_list_tobe_allocated[min_npm];
//creates a list of pms to be allocated to the child
for(int i=0;i<min_npm;i++){
if(sort_pm_by_cpu==1){
if( parent1->pm_list[i]->utlz >= parent2->pm_list[i]->utlz ){
pm_list_tobe_allocated[i]=createCopyPm(parent1->pm_list[i]);
}
else{
pm_list_tobe_allocated[i]=createCopyPm(parent2->pm_list[i]);
}
}
else{
if( parent1->pm_list[i]->mem_utlz >= parent2->pm_list[i]->mem_utlz ){
pm_list_tobe_allocated[i]=createCopyPm(parent1->pm_list[i]);
}
else{
pm_list_tobe_allocated[i]=createCopyPm(parent2->pm_list[i]);
}
}
}
addPmListToGene(pm_list_tobe_allocated,min_npm,child);
int duplicates_removed=removeDuplicateContainersFromGene(child);
printf("\nDuplicates removed:%d",duplicates_removed);
//printStats(child);
fitness1(child);
countContainers(child);
int cn_absent[CNT_SIZE];
int absent_count=findAbsentContainers(child,cn_absent);
//printStats(child);
printf("\nabsent count:%d",absent_count);
if(absent_count!=0){
//printf("\nIn Crossover: Before heuristics");
heuristics2(child,cn_absent,absent_count);
//printf("\nIn Crossover: After heuristics");
}
countContainers(child);
integrity_all_containers(child);
free(parent1);
free(parent2);
return child;
}
void postCrossMut(geneptr child,popptr h1){
unpackPm(child);
//fitness(child);
mergeVm(child);
//unpack_vm(child);
//printstats(child);
removeEmptyVmAndPms(child);
integrity_all_containers(child);
fitness(child);
//remove_empty_pm_vm(child);
if(uniqueness(child,h1)==1){
removeGene(h1,findWorstGene(h1));
addGene(h1,child);
}
}
|
C | #include <unistd.h>
#include <stdio.h>
int main(int argc, char** argv){
int var = 123456;
int pid = fork();
if(pid==0){
printf("Variable vista por el hijo: %d \n", var);
var=659684;
printf("Variable cambiada por el proceso hijo: %d \n", var);
} else {
printf("Variable vista por el padre: %d \n", var);
var=1839284;
printf("Variable cambiada por el proceso padre: %d \n",var);
}
return 0;
}
|
C | #include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern char **environ;
/**
* main - function to read a line
*
* Return: Always 0.
*/
int main(void)
{
char *builtins = NULL;
char *builtins_path = {"/bin/"};
size_t n = 1024;
ssize_t characters_read;
printf("$ ");
characters_read = getline(&builtins, &n, stdin);
if (characters_read != -1)
{
printf("%s", builtins);
builtins_path = strcat(builtins_path, builtins);
}
execve()
free(builtins);
return(0);
} |
C | /* Purpose: guess password */
/* File Name: hw05_03*/
/* Completion Date: 20210523*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int password, UserInput;
password = 5566;
printf("Please input 1000~9999 to guess the password\n");
scanf("%d", &UserInput);
if (UserInput == password) {
printf("Congrates! You input the right password\n");
} else {
printf("Sorry, the password you inputed are wrong!\n");
}
system ("pause");
return 0;
} |
C | #include <stdio.h>
#include <string.h>
#include "queue.h"
#include "stack.h"
#define CHARACTER_INSERTED 1
void insertParen(struct Queue * queue) {
int ops = 0;
int needed_parens = 0;
char ch;
struct Stack *s = createStack();
struct Stack *t = createStack();
while(queue->size > 0) {
push(s, qd(queue));
}
int done = 0;
while( ! done ) {
ch = peek(s);
switch(ch) {
case '+':
case '-':
case '*':
case '/':
ops++;
if (ops > needed_parens) {
done = 1;
} else {
push(t, pop(s));
}
break;
case ')':
needed_parens++;
default:
push(t, pop(s));
break;
}
if (s->size == 0 || done == 1) {
push(t, '(');
done = 1;
}
}
// drain whatever is left
while (s->size > 0) {
push(t, pop(s));
}
while (t->size > 0) {
qq(queue, pop(t));
}
return;
}
int handleCharacter(struct Queue * queue, char character) {
switch(character) {
case ' ':
break;
case ')':
qq(queue, character);
insertParen(queue);
return CHARACTER_INSERTED;
default:
qq(queue, character);
break;
}
return 0;
}
int main(int argc, char * argv[]) {
int i, res;
char * string = argv[1];
struct Queue *queue = createQueue();
for (i = 0; i < strlen(string); i++) {
res = handleCharacter(queue, string[i]);
if (res == CHARACTER_INSERTED) {
i++;
}
}
// print results
qp(queue);
return 0;
}
|
C | #include "holberton.h"
/**
* print_square - function that prints a square, followed by a new line
* @size: size of the square
*
* Return: void
*/
void print_square(int size)
{
int l = size;
int m = size;
if (size <= 0)
{
_putchar('\n');
}
else
{
while (size > 0)
{
while (l > 0)
{
_putchar('#');
l--;
}
l = m;
_putchar('\n');
size--;
}
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaaaron <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/06 13:35:38 by jaaaron #+# #+# */
/* Updated: 2018/11/12 22:10:36 by jaaaron ### ########.fr */
/* */
/* ************************************************************************** */
/*
** Applies the function f to each character of the string given as argument to
** create a “fresh” new string (with malloc(3)) resulting from the successive
** applications of f.
** Param #1 - The string to map.
** Param #2 - The function to apply to each character of s.
** Return value - The 'fresh' string created from the successive applications
** of f.
** Libc functions - malloc(3)
*/
#include "libft.h"
char *ft_strmap(char const *s, char (*f)(char))
{
char *new;
unsigned int i;
if (s && f)
{
new = ft_strnew(ft_strlen(s));
if (new == NULL)
return (NULL);
i = 0;
while (s[i] != '\0')
{
new[i] = f(s[i]);
i++;
}
return (new);
}
else
{
new = NULL;
return (new);
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int i=0,j=0,n;
scanf("%d",&n);
char before[n+1],after[n+1],dif[n+1];
scanf("%s",before);
scanf("%s",after);
for(i=0;i<n;i++){
if (before[i]<after[i]){
dif[i]=-1;
}
if (before[i]==after[i]){
dif[i]=0;
}
if (before[i]>after[i]){
dif[i]=1;
}
}
for(i = 0; i < n-1; i++){
if (dif[i] != 0){
if(dif[i] + dif[i+1] == 0)
dif[i+1] = 0;
j++;
}
}
if(dif[n-1]!=0)
j++;
printf("%d",j);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* quick_sort_name.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zkerkeb <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/13 17:50:50 by zkerkeb #+# #+# */
/* Updated: 2016/03/27 17:10:59 by zkerkeb ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
t_file *partition(t_file *head, t_file *end,
t_file **nhead, t_file **n_end)
{
t_file *pivot;
t_file *prev;
t_file *cur;
t_file *tail;
t_file *tmp;
pivot = end;
prev = NULL;
cur = head;
tail = pivot;
while (cur != pivot)
{
if (ft_strcmp(cur->dname, pivot->dname) < 0)
if_part(nhead, &cur, &prev);
else
part_else(&prev, &cur, &tail, &tmp);
}
if ((*nhead) == NULL && (*nhead = pivot))
;
(*n_end) = tail;
return (pivot);
}
t_file *quick_recur(t_file *head, t_file *end)
{
t_file *nhead;
t_file *n_end;
t_file *pivot;
t_file *tmp;
nhead = NULL;
n_end = NULL;
if (!head || head == end)
return (head);
pivot = partition(head, end, &nhead, &n_end);
if (nhead != pivot)
{
tmp = nhead;
while (tmp->next != pivot)
tmp = tmp->next;
tmp->next = NULL;
nhead = quick_recur(nhead, tmp);
tmp = get_tail(nhead);
tmp->next = pivot;
}
pivot->next = quick_recur(pivot->next, n_end);
return (nhead);
}
void quick_sort_name(t_file **head)
{
(*head) = quick_recur(*head, get_tail(*head));
return ;
}
|
C | #include <stdio.h>
#define swap(t,x,y) \
do { \
t = x; \
x = y; \
y = t; \
} while (0) \
int main()
{
int temp;
int x = 4;
int y = 20;
printf("\nPre Swap:");
printf("\nx = %d", x);
printf("\ny = %d", y);
swap(temp, x, y);
printf("\nPost Swap:");
printf("\nx = %d", x);
printf("\ny = %d", y);
char temp1;
char x1 = 'x';
char y1 = 'y';
printf("\nPre Swap:");
printf("\nx1 = %c", x1);
printf("\ny1 = %c", y1);
swap(temp1, x1, y1);
printf("\nPost Swap:");
printf("\nx1 = %c", x1);
printf("\ny1 = %c\n", y1);
}
|
C | /**
* Dynamic programming
*
* Task 1
*
* Количество маршрутов с препятствиями.
* Реализовать чтение массива с препятствием и нахождение количество маршрутов.
*
* @author Maxim Levitan <[email protected]>
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "tasks.h"
#include "helpers.h"
#include "dynamic.h"
void prepareRandomBarriers(int* barriersMap, int rowCount, int colCount, int barrierCount);
int task1()
{
int keyExite = 0;
int maxN = 100;
int maxM = 100;
int N = 0;
int M = 0;
int barriersMap[maxN][maxM];
int resultData[maxN][maxM];
do {
puts("Calculating chess king routes with barriers");
printf("Input N(1..%i):", maxN);
if (scanf("%d", &N) < 1) {
return 1;
}
if (N < 3 || N > maxN) {
printf("Wrong N, needs 3 < N < 100, try again.");
continue;
}
printf("Input M(1..%i):", maxM);
if (scanf("%d", &M) < 1) {
return 1;
}
if (M < 3 || M > maxM) {
printf("Wrong M, needs 3 < M < 100, try again.");
continue;
}
fill2DArrayIntByValue((int*) barriersMap, maxN, maxM, 1);
fill2DArrayIntByValue((int*) resultData, maxN, maxM, 0);
prepareRandomBarriers((int*) barriersMap, N, M, N);
puts("Prepared barriers map:");
print2DArray((int*) barriersMap, N, M);
countRoutsOfKingWithBarriers((int*) resultData, (int*) barriersMap, N, M);
puts("\nResult:");
print2DArray((int*) resultData, N, M);
printf("Try again? [1 or 0]:");
if (scanf("%d", &keyExite) < 1) {
return 1;
}
if (keyExite != 0) {
continue;
}
puts("");
break;
} while (1);
return 0;
}
void prepareRandomBarriers(int* barriersMap, int rowCount, int colCount, int barrierCount)
{
int minRand = 1;
int maxRand = (rowCount - 1) * (colCount - 1);
int randomIndex = minRand;
srand((unsigned) time(NULL));
for (int i = 0; i < barrierCount; i++) {
randomIndex = randNumber(minRand, maxRand);
*(barriersMap + randomIndex) = 0;
}
}
|
C | #include<stdio.h>
#include <string.h>
#include<GL/glut.h>
#include <stdlib.h>
int pat = 0, scan = 1;
int submenu;
float x1,y1,x2,y2,x3,y3,x4,y4;
void render(float x, float y, char *str){
glRasterPos2f(x,y);
for(int i = 0 ; i < strlen(str); i++){
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str[i]);
}
}
int edgedetect(float x1, float y1, float x2, float y2, int *le, int *re){
float mx, x, temp;
int i;
if ((y2-y1) < 0) {
temp = y1;
y1 = y2;
y2 = temp;
temp = x1;
x1 = x2;
x2 = temp;
}
if((y2-y1) != 0)
mx = (x2-x1)/(y2-y1);
else
mx = x2-x1;
x = x1;
for(i = y1; i <= y2; i++){
if(x < (float)le[i])
le[i] = (int)x;
if(x > (float)re[i])
re[i] = (int)x;
x += mx;
}
}
void drawpixel(int x, int y) {
/* code */
//glColor3f(1.0,1.0,0.0);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
void scanfill(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4){
int le[500], re[500];
int i,y;
for(i=0; i<500; i++){
le[i] = 500;
re[i] = 0;
}
edgedetect(x1,y1,x2,y2,le,re);
edgedetect(x2,y2,x3,y3,le,re);
edgedetect(x3,y3,x4,y4,le,re);
edgedetect(x4, y4, x1, y1, le, re);
for(y = 0; y < 500; y++){
if(le[y] <= re[y]){
for(i=(int)le[y]; i < (int)re[y]; i++){
drawpixel(i,y);
}
}
}
}
void display(){
//x1 = 200.0, y1 = 200.0, x2 = 100.0, y2 = 300.0, x3 = 200.0, y3 = 400.0, x4 = 300.0, y4 = 300.0;
if(!pat){
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_LOOP);
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
render(20,5,"1BI18CS026");
if(scan)
scanfill(x1,y1,x2,y2,x3,y3,x4,y4);
glFlush();
}
else{
GLubyte ini1[]=
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
};
GLubyte ini2[]= {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x80, 0x01, 0xC0, 0x06, 0xC0, 0x03, 0x60,
0x04, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x20,
0x04, 0x18, 0x18, 0x20, 0x04, 0x0C, 0x30, 0x20,
0x04, 0x06, 0x60, 0x20, 0x44, 0x03, 0xC0, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x66, 0x01, 0x80, 0x66, 0x33, 0x01, 0x80, 0xCC,
0x19, 0x81, 0x81, 0x98, 0x0C, 0xC1, 0x83, 0x30,
0x07, 0xe1, 0x87, 0xe0, 0x03, 0x3f, 0xfc, 0xc0,
0x03, 0x31, 0x8c, 0xc0, 0x03, 0x33, 0xcc, 0xc0,
0x06, 0x64, 0x26, 0x60, 0x0c, 0xcc, 0x33, 0x30,
0x18, 0xcc, 0x33, 0x18, 0x10, 0xc4, 0x23, 0x08,
0x10, 0x63, 0xC6, 0x08, 0x10, 0x30, 0x0c, 0x08,
0x10, 0x18, 0x18, 0x08, 0x10, 0x00, 0x00, 0x08
};
GLubyte ini3[] ={
0xff, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0xff, 0x01, 0xff, 0x01, 0x00, 0x01, 0x01, 0x01,
0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01,
0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01,
0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01,
0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01,
0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01,
0xff, 0x00, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
glClear(GL_COLOR_BUFFER_BIT);
//glColor3f(1.0,1.0,1.0);
glEnable(GL_POLYGON_STIPPLE);
switch (pat) {
case 1: glPolygonStipple(ini1);
break;
case 2: glPolygonStipple(ini2);
break;
case 3: glPolygonStipple(ini3);
break;
}
pat = 0;
/*glRectf (100.0, 100.0, 400.0, 400.0);*/
glBegin(GL_POLYGON);
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
glDisable(GL_POLYGON_STIPPLE);
glFlush();
}
}
void init(){
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(0.6,1.0,0.3);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
glShadeModel(GL_FLAT);
}
void menufunc(int n){
switch (n) {
case 1: glColor3f(1.0,0.0,0.0);
scan = 1;
break;
case 2 :glColor3f(0.2,0.4,0.6);
scan = 1;
break;
case 3 : glColor3f(0.6,0.2,0.4);
scan = 1;
break;
case 4 : pat = 1;
break;
case 5 : pat = 2;
break;
case 6 : pat = 3;
break;
case 7: exit(0);
break;
case 8: glColor3f(1.0,0.0,0.0);
scan = 0;
break;
case 9: glColor3f(0.0,1.0,1.0);
scan = 0;
break;
case 10:glColor3f(1.0,1.0,0.0);
scan = 0;
break;
}
glutPostRedisplay();
}
void reshape(int w, int h){
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D (0.0, (GLdouble) w, 0.0, (GLdouble) h);
}
int main(int argc, char **argv) {
printf("Enter the four edges of Quadrangle\n");
printf("First edge(x,y) \t");
scanf("%f%f",&x1,&y1);
printf("Second edge(x,y) \t");
scanf("%f%f",&x2,&y2);
printf("Third edge(x,y) \t");
scanf("%f%f",&x3,&y3);
printf("Fourth edge(x,y) \t");
scanf("%f%f",&x4,&y4);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(50,50);
glutCreateWindow("Scan Line Algo");
int sub1 = glutCreateMenu(menufunc);
glutAddMenuEntry("Red", 1);
glutAddMenuEntry("SomeColor1", 2);
glutAddMenuEntry("SomeColor2", 3);
int sub2 = glutCreateMenu(menufunc);
glutAddMenuEntry("Pattern 1", 4);
glutAddMenuEntry("Pattern 2", 5);
glutAddMenuEntry("Pattern 3", 6);
int sub3 = glutCreateMenu(menufunc);
glutAddMenuEntry("Red", 8);
glutAddMenuEntry("Cyan", 9);
glutAddMenuEntry("Yellow", 10);
glutCreateMenu(menufunc);
glutAddSubMenu("Colors", sub1);
glutAddSubMenu("Patterns", sub2);
glutAddSubMenu("Hollow", sub3);
glutAddMenuEntry("Exit", 7);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
init();
glutMainLoop();
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CANTVENTAS 3
#define CANTVENDEDORES 4
typedef char palabra[20];
typedef int vec[CANTVENTAS];
struct vendedores{
int legajo;
palabra nombre;
int zona;
vec ventas;
};
typedef struct vendedores vendedor;
typedef struct ventasCero vc;
int main()
{
int valorProm = 100;
vec ventCe[CANTVENDEDORES];
int *pVc;
pVc = ventCe;
vendedor ven[CANTVENDEDORES];
carga(ven);
int cant = promMayorX(ven,CANTVENDEDORES,valorProm);
printf("Cantidad que superan 10: %d",cant);
imprime(ven);
ordenar(ven,2);
imprime(ven,2);
ventasCero(ven,4,pVc);
}
carga(vendedor pun[]){
int i,j;
for(i=0;i<CANTVENDEDORES;i++){
printf("\n Legajo: ");
scanf("%d",&(pun[i].legajo));
printf(" Nombre: ");
scanf("%s",pun[i].nombre);
printf(" Zona: ");
scanf("%d",&(pun[i].zona));
for(j=0;j<CANTVENTAS;j++){
printf(" venta[%d]: ",j);
scanf("%d",&(pun[i].ventas[j]));
}
}
}
void imprime(vendedor v[]){
int i,j;
printf("\n--------------------------------------\n");
printf("\n\tLegajo\tNombre\tzona\tventas\n");
for(i=0;i<CANTVENDEDORES;i++){
printf("\n\t%d\t%s\t%d\t",v[i].legajo, v[i].nombre,v[i].zona);
for(j=0;j<CANTVENTAS;j++){
printf("|venta[%d]: ",v[i].ventas[j]);
}
}
printf("\n--------------------------------------\n");
printf("\n\n");
}
//Se tiene un array de N struct vendedor
//Funcion que reciba el vector de registros, el valor de N y un real --> cant vend que superen x
int promMayorX(vendedor ven[],int n, int x){
int i,j, totalSum = 0,vendMax=0;
float prom;
for(i=0;i<n;i++){
totalSum = 0;
for(j=0;j<CANTVENTAS;j++){
totalSum= totalSum + ven[i].ventas[j];
prom=totalSum/n;
}
if(prom > x){
vendMax = vendMax+1;
}
}
return vendMax;
}
//
void ventasCero(vendedor v[],int n,int *pv)
{
int i,j, totalSum = 0,vendMax=0,cont=0,pos;
float prom;
for(i=0;i<n;i++){
totalSum = 0;
for(j=0;j<CANTVENTAS;j++){
totalSum= totalSum + v[i].ventas[j];
prom=totalSum/n;
}
pos=i;
printf("\n --> total ventas %d = %d, pos: %d",i,totalSum,pos);
if(totalSum == 0){
pv[cont]= i;
cont++;
}
}
for(i=0;i<cont;i++){
printf("\n");
printf("| %d",pv[i]);
}
}
//ordenar por zona y por legajo
void ordenar(vendedor v[],int n){
vendedor aux,*p,aux2;
p=v;
for (int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(p[j].zona>p[j+1].zona){
aux= *(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)= aux;
if(p[j].legajo>p[j+1].legajo){
aux= *(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)= aux;
}
}
}
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct emplo
{
char ph[10];
char id[10];
char name[10];
};
struct emplo* add=NULL;
void ent()
{int i;
char ss[10];
struct emplo* em=(struct emplo*)malloc(sizeof(struct emplo*)*3);
add=em;
for(i=0;i<3;i++)
{
scanf("%s",ss);
strcpy((em+i)->ph,ss);
scanf("%s",ss);
strcpy((em+i)->id,ss);
scanf("%s",ss);
strcpy((em+i)->name,ss);
}
}
int main()
{
while(1)
{int c;
printf("enter the choice\n");
scanf("%d",&c);
switch(c)
{
case 1:ent();
break;
default:exit(0);
}
}
return 0;
}
|
C | /* 027.c COPYRIGHT FUJITSU LIMITED 2017 */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <numaif.h>
#include <errno.h>
#include <string.h>
#include "test_mck.h"
#include "numa.h"
static unsigned long max_node;
static unsigned long *node_mask = NULL;
static unsigned long nr_node_mask;
static char *buf = MAP_FAILED;
SETUP_FUNC(TEST_SUITE, TEST_NUMBER)
{
/* arg analyze and get max_node */
max_node = arg_analyze(tc_argc, tc_argv);
return NULL;
}
RUN_FUNC(TEST_SUITE, TEST_NUMBER)
{
long l_ret = -1;
struct mbind_args m_args[] = {
{ MPOL_BIND, 0x02, 0, 1 * PAGE_SIZE, },
{ MPOL_BIND, 0x01, 0, 1 * PAGE_SIZE, }
};
buf = (char *)mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
/* max_node check */
if (max_node == 0) {
usage_print();
tp_assert(0, "max_node = 0");
}
if (max_node < 2) {
printf("this TP is must have max_node of 2 or more.\n");
tp_assert(0, "max_node error");
}
/* create node_mask and tpassert(node_mask malloc) */
node_mask = (unsigned long *)create_node_mask(max_node, &nr_node_mask);
tp_assert(node_mask!=NULL, "node_mask malloc error");
m_args[0].addr = buf;
m_args[1].addr = buf;
/* ---------- mbind and get ---------- */
/* This TP congirms that if MPOL_MF_MOVE is specifed for
* flags and mode is not MPOL_DEFAULT, it a page exists in
* a memory area not following the specified policy,
* it will be error EIO.
*
* The assumed behavior is to fail with EIO
* because it mbinds to secure a physical page,
* mpinds MPOL_MF_STRICT to that area,
* mbinds with specifying a different policy,
* and does not follow the specified policy.
* This is because even if flags = 0,
* it is migreated.
*/
/* mbind and tpassert(mbind) */
l_ret = -1;
l_ret = mbind(m_args[0].addr, m_args[0].len,
m_args[0].mode, &m_args[0].node_mask, BITS_PER_LONG, 0);
tp_assert(l_ret==0, "mbind(flags=0) error");
*buf = 0;
/* mbind and tpassert(mbind) */
l_ret = -1;
l_ret = mbind(m_args[1].addr, m_args[1].len,
m_args[1].mode, &m_args[1].node_mask, BITS_PER_LONG, MPOL_MF_STRICT);
tp_assert(l_ret==-1, "mbind(flags=MPOL_MF_STRICT) not failed");
tp_assert(errno!=EIO, "errno != EIO");
munmap(buf, PAGE_SIZE);
buf = MAP_FAILED;
/* result OK */
return NULL;
}
TEARDOWN_FUNC(TEST_SUITE, TEST_NUMBER)
{
/* free node_mask */
destroy_node_mask(node_mask);
if (buf != MAP_FAILED) {
munmap(buf, PAGE_SIZE);
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* handle_quotes.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jonny <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/26 17:38:04 by jonny #+# #+# */
/* Updated: 2021/06/03 11:58:36 by jonny ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/msh.h"
static void handle_quotes2(t_ast **token, char *buf)
{
char *ptr;
char *str;
char c;
ptr = NULL;
str = "\0";
if ((*token)->value[0] == '\\' && (*token)->right && g_sig.dollar_quote)
{
c = (*token)->right->value[0];
if (is_ansi_c_quoting(&str, c))
{
ft_strcat(buf, str);
token_lst_remove(token);
ptr = &(*token)->value[1];
ft_strcat(buf, ptr);
}
else
ft_strcat(buf, (*token)->value);
}
else if ((*token)->value[0] != '\'')
ft_strcat(buf, (*token)->value);
}
int handle_first_quote(t_ast **token, char *buf,
enum e_type *type)
{
int len;
len = ft_strlen(buf);
if (*token)
{
*type = (*token)->type;
if (buf[len - 1] == '=')
{
ft_strcat(buf, (*token)->value);
token_lst_remove(token);
return (1);
}
else
token_lst_remove(token);
}
return (0);
}
void change_type(t_ast **token)
{
t_ast *ptr;
ptr = *token;
while (ptr)
{
if (!ft_strncmp(ptr->value, "\'", 2))
{
ptr->type = QUOTE;
break ;
}
ptr->type = ARG;
ptr = ptr->right;
}
}
void handle_quotes(t_ast **token, char *buf, t_env *env_lst)
{
enum e_type type;
type = QUOTE;
handle_first_quote(token, buf, &type);
if (type == QUOTE)
change_type(token);
while (*token)
{
if ((*token)->type == DOLLAR)
g_sig.dollar_quote = true;
if (type == DBLQUOTE)
handle_dbl_quotes(token, buf, env_lst);
else if (type == QUOTE)
handle_quotes2(token, buf);
if ((*token)->type == type)
break ;
token_lst_remove(token);
}
g_sig.dollar_quote = false;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <libgen.h>
#include <sys/select.h>
#include "readn_writen_readline.h"
#define ERR_EXIT(m) \
do { \
perror(m);\
exit(EXIT_FAILURE);\
}while(0)
void str_cli(FILE *fp, int sockfd) {
int maxfdp1, stdineof;
fd_set rset;
char buf[MAXLINE];
int n;
stdineof = 0;
FD_ZERO(&rset);
for(;;) {
if(stdineof == 0)
FD_SET(fileno(fp), &rset);
FD_SET(sockfd, &rset);
maxfdp1 = (sockfd > fileno(fp) ? sockfd : fileno(fp)) + 1;
if(select(maxfdp1, &rset, NULL, NULL, NULL) == -1)
ERR_EXIT("select");
if(FD_ISSET(sockfd, &rset)) { // socket readable
if((n = read(sockfd, buf, MAXLINE)) == 0) {
if(stdineof == 1)
return;
else
fprintf(stderr, "str_cli: server terminated prematurely");
}
write(fileno(stdout), buf, n);
}
if(FD_ISSET(fileno(fp), &rset)) { // input readable
if((n = read(fileno(fp), buf, MAXLINE)) == 0) {
stdineof = 1;
shutdown(sockfd, SHUT_WR); // send FIN
FD_CLR(fileno(fp), &rset);
continue;
}
writen(sockfd, buf, n);
}
}
}
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in servaddr;
if(argc != 2) {
printf("Usage: %s IP\n", basename(argv[0]));
exit(EXIT_FAILURE);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
ERR_EXIT("socket");
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(8888);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)
ERR_EXIT("connect");
str_cli(stdin, sockfd);
close(sockfd);
exit(EXIT_SUCCESS);
}
|
C | /***********************************************
#
# Filename: myerror.c
#
# Author: [email protected]
# Description: ---
# Create: 2018-01-10 11:14:00
# Last Modified: 2018-01-10 11:14:00
***********************************************/
#include "apue.h"
#include <errno.h>
int main(int argc, char *argv[])
{
fprintf(stderr, "EACCES: %s\n", strerror(EACCES));
errno = ENOENT;
perror(argv[0]);
exit(0);
}
|
C | /*Experiment to find out what happens when prints's argument string contains
\c, where c is some character not listed above*/
#include <stdio.h>
main(){
printf("hello, world\c");
}
//What happen is that the program print "hello, worldc"
|
C | /*
* NOME: Stefano Viola
* MATRICOLA: 863000253
*
*
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUF 1024
int main(int argc, char **argv)
{
char line[BUF];
char line2[BUF];
int strcount;
char **strarray = NULL;
int c;
int cflag = 0;
int dflag = 0;
int uflag = 0;
FILE *fp;
while((c = getopt(argc, argv, "cdu")) != -1){
switch(c){
case 'c':
cflag = 1;
break;
case 'd':
dflag = 1;
break;
case 'u':
uflag = 1;
break;
case 'h':
break;
case '?':
if(isprint(optopt))
fprintf(stderr, "Unknown option `-%c'.\nTry 'uniq -h' for usage message.\n", optopt);
default:
exit(1);
}
}
if(argv[optind] == NULL)
fp = stdin;
else{
if((fp = fopen(argv[optind], "r")) == NULL)
exit(-1);
}
int flag = 0;
int count = 0;
int fine = 0;
char *result;
while(1){
result = fgets(line,BUF, fp);
if(result == NULL){
if(fine)
break;
strcpy(line,"");
fine = 1;
}
if(!flag)
strcpy(line2,line);
else{
if(!strcmp(line,line2)){
count++;
}else{
if(count>0){
if(cflag && !uflag)
printf("--%6d %s",count+1, line2);
else if(!uflag)
printf("%s",line2);
}
else
if(cflag && !dflag)
printf("%6d %s",count+1, line2);
else if(!dflag)
printf("%s",line2);
strcpy(line2,line);
count = 0;
}
}
flag=1;
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"list.h"
#include"queue.h"
//Array Structure
//int nodes[4]={0,0,0,0};
struct Array
{
char code[7];
char name[4];
int credits;
int maxLimit;
struct List *regList;
struct Dlist *waitList;
};
struct Array *ptr[4];
//Single Linked List
struct List
{
char data[30];
struct List *link;
};
struct List *head[4];
//Double Linked List
struct Dlist
{
struct Dlist *llink;
char data[30];
struct Dlist *rlink;
};
struct Dlist *top[4];
struct Dlist *front=NULL,*rear=NULL,*temp2=NULL;
//IsEmpty Operation
int isEmpty(int index)
{
if(top[index]==NULL)
return 1;
else
return 0;
}
//Enqueue Operation
void Enqueue(int index)
{
char dup1[30];
struct Dlist *dnode=(struct Dlist*)malloc(sizeof(struct Dlist));
if(isEmpty(index)==1)
{
printf("Enter Name of the Student to be in WaitingList : ");
scanf("%s",dnode->data);
strcpy(dup1,dnode->data);
dnode->rlink=dnode->llink=NULL;
temp2=front=rear=top[index]=dnode;
}
else
{
printf("Enter Name of the Student to be in WaitingList : ");
scanf("%s",dnode->data);
strcpy(dup1,dnode->data);
temp2->rlink=dnode;
dnode->llink=temp2;
dnode->rlink=NULL;
rear=temp2=temp2->rlink;
}
struct Dlist *temp3=top[index];
printf("\nWAITING LIST : \n");
while(temp3)
{
printf("%s---",temp3->data);
temp3=temp3->rlink;
}
printf("\n");
}
//Dequeue Operation
void Dequeue(int index)
{
char copy2[30],copy1[30],p=0,q=0,count1=0,min,len1,i;
struct List *node=(struct List*)malloc(sizeof(struct List));
strcpy(node->data,front->data);
if(isEmpty(index)!=1)
{
if(head[index]==NULL)
{
head[index]=node;
node->link=NULL;
printf("\nREGISTERED LIST : \n");
printf("%s-->",node->data);
printf("\n");
}
else
{
struct List *temp1=head[index];
struct List *prev;
strcpy(copy2,node->data);
min=strlen(copy2);
//list contains only 1 node
if(temp1->link==NULL)
{
strcpy(copy1,temp1->data);
len1=strlen(copy1);
if(len1<min)
min=len1;
for(i=0;i<min;i++)
{
if(copy1[p]==copy2[q])
{
p++;
q++;
}
if(copy1[p]>copy2[q])
{
node->link=temp1;
head[index]=node;
temp1=node;
break;
}
if(copy1[p]<copy2[q])
{
temp1->link=node;
node->link=NULL;
break;
}
}//for
}//if
//list contain many nodes
else
{
temp1=head[index];
prev=temp1;
while(temp1)
{
p=0;
q=0;
count1=0;
strcpy(copy1,temp1->data);
len1=strlen(copy1);
if(len1<min)
min=len1;
for(i=0;i<min;i++)
{
if(copy1[p]==copy2[q])
{
p++;
q++;
}
if(copy1[p]>copy2[q])
{
count1=1;
node->link=temp1;
if(head[index]==temp1)
prev=node;
else
prev->link=node;
if(prev->link==head[index])
head[index]=prev;
break;
}
if(copy1[p]<copy2[q])
{
if(temp1->link!=NULL)
{
prev=temp1;
temp1=temp1->link;
}
else
{
temp1->link=node;
node->link=NULL;
count1=1;
}
break;
}
}//for
if(count1==1)
break;
}//while
}//else
//Printing List
struct List *temp=head[index];
printf("\nREGISTERED LIST :\n");
}//else
if(front!=rear)
{
top[index]=front=front->rlink;
free(front->llink);
}
else
{
top[index]=NULL;
free(front);
front=rear=temp2=NULL;
}
}
else
{
printf("\nWaiting List is Empty!!!");
top[index]=NULL;
}
return;
}
|
C | void ft_rev_int_tab(int *tab, int size)
{
int *start_tab;
int *end_tab;
int buff;
if (!size)
return ;
start_tab = tab;
end_tab = tab + size - 1;
while (start_tab < end_tab)
{
buff = *start_tab;
*start_tab = *end_tab;
*end_tab = buff;
++start_tab;
--end_tab;
}
}
|
C | #include <stdio.h>
int main(void)
{
int ABG_iArrayOne[10];
int ABG_iArrayTwo[10];
/***** ABG_iArrayone ******/
ABG_iArrayOne[0] = 5;
ABG_iArrayOne[1] = 10;
ABG_iArrayOne[2] = 15;
ABG_iArrayOne[3] = 20;
ABG_iArrayOne[4] = 25;
ABG_iArrayOne[5] = 30;
ABG_iArrayOne[6] = 35;
ABG_iArrayOne[7] = 40;
ABG_iArrayOne[8] = 45;
ABG_iArrayOne[9] = 50;
printf("Piece-meal (Hard-coded) Assignment And Display Of Elements to Array 'ABG_iArrayOne[10]': \n\n");
printf("1st Element Of Array 'ABG_iArrayOne[]' Or Element At 0th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[0]);
printf("2nd Element Of Array 'ABG_iArrayOne[]' Or Element At 1th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[1]);
printf("3rd Element Of Array 'ABG_iArrayOne[]' Or Element At 2th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[2]);
printf("4th Element Of Array 'ABG_iArrayOne[]' Or Element At 3th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[3]);
printf("5th Element Of Array 'ABG_iArrayOne[]' Or Element At 4th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[4]);
printf("6th Element Of Array 'ABG_iArrayOne[]' Or Element At 5th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[5]);
printf("7th Element Of Array 'ABG_iArrayOne[]' Or Element At 6th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[6]);
printf("8th Element Of Array 'ABG_iArrayOne[]' Or Element At 7th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[7]);
printf("9th Element Of Array 'ABG_iArrayOne[]' Or Element At 8th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[8]);
printf("10th Element Of Array 'ABG_iArrayOne[]' Or Element At 9th Index Of Array 'ABG_iArrayOne[]' = % d\n", ABG_iArrayOne[9]);
// ****** ABG_iArrayTwo[] ******
printf("\n\n");
printf("Enter 1st Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[0]);
printf("Enter 2nd Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[1]);
printf("Enter 3rd Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[2]);
printf("Enter 4th Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[3]);
printf("Enter 5th Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[4]);
printf("Enter 6th Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[5]);
printf("Enter 7th Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[6]);
printf("Enter 8th Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[7]);
printf("Enter 9th Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[8]);
printf("Enter 10th Element Of Array 'ABG_iArrayTwo[]' : ");
scanf("%d", &ABG_iArrayTwo[9]);
printf("\n\n");
printf("Piece-meal (User Input) Assignment And Display Of Elements to Array 'ABG_iArrayTwo[10]' : \n\n");
printf("1st Element Of Array 'ABG_iArrayTwo[]' Or Element At 0th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[0]);
printf("2nd Element Of Array 'ABG_iArrayTwo[]' Or Element At 1th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[1]);
printf("3rd Element Of Array 'ABG_iArrayTwo[]' Or Element At 2th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[2]);
printf("4th Element Of Array 'ABG_iArrayTwo[]' Or Element At 3th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[3]);
printf("5th Element Of Array 'ABG_iArrayTwo[]' Or Element At 4th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[4]);
printf("6th Element Of Array 'ABG_iArrayTwo[]' Or Element At 5th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[5]);
printf("7th Element Of Array 'ABG_iArrayTwo[]' Or Element At 6th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[6]);
printf("8th Element Of Array 'ABG_iArrayTwo[]' Or Element At 7th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[7]);
printf("9th Element Of Array 'ABG_iArrayTwo[]' Or Element At 8th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[8]);
printf("10th Element Of Array 'ABG_iArrayTwo[]' Or Element At 9th Index Of Array 'ABG_iArrayTwo[]' = % d\n", ABG_iArrayTwo[9]);
return(0);
} |
C | #ifndef QUEUE_H
#define QUEUE_H
/**
* @brief Queue is a linear data structure which follows a particular order in which the operations are performed.
* The order is First In First Out (FIFO).
* A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first.
* The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
*
* @param front index to the front item of the Queue (the one that will be dequeued when needed)
* @param rear index to the last item of the Queue (the last one that will be dequeed when needed)
* @param size the quantity of items that are in the Queue
* @param capacity the maximum capacity of items that the Queue can hold
* @param data is the array that holds the Queue items
*/
typedef struct Queue
{
int front;
int rear;
int size;
int capacity;
int *data;
} _queue_t;
/**
* @brief Creates a new Queue.
*/
_queue_t queue_create(int capacity);
/**
* @brief Adds a new item to the last position of the Queue.
*/
void queue_enqueue(_queue_t *queue, int item);
/**
* @brief Removes the top item of the Queue.
*/
int queue_dequeue(_queue_t *queue);
/**
* @brief Take a peek in to the top most item of the Queue but do not dequeue it.
*/
int queue_peek(_queue_t *queue);
/**
* @brief Destroys the Queue.
*/
void queue_destroy(_queue_t *queue);
/**
* @brief Check if the queue is empty.
*/
int queue_is_empty(_queue_t *queue);
/**
* @brief Check if the queue is full.
*/
int queue_is_full(_queue_t *queue);
/**
* @brief "Calculates" the next front position.
*/
int queue_calc_next_front(_queue_t *queue);
/**
* @brief "Calculates" the next rear position.
*/
int queue_calc_next_rear(_queue_t *queue);
#endif
|
C | /* Organização e recuperação da informação - Lista 01
Exercício 07
Aluno: Pedro Henrique Mendes */
#include <stdio.h>
#include "aluno.h"
#include "lista.h"
#include "cadastro.h"
int compare(struct aluno a1, struct aluno a2) {
if (a1.RA < a2.RA)
return -1;
else if (a1.RA > a2.RA)
return 1;
else
return 0;
}
int main(int argc, char *argv[]) {
if (argc == 2) {
lista alunos;
l_inicializa(&alunos, compare);
FILE *cad;
if (inicializar(&cad, argv[1], &alunos) == 1)
menu(&cad, &alunos);
if (cad != NULL)
fclose(cad);
if (l_inicializada(&alunos))
l_destroi(&alunos);
}
else
printf("chamada incorreta do programa, utilize o arquivo \"Alunos.dat\" como argumento");
return 0;
} |
C | #include "ia.h"
#include "database.h"
#include <stdio.h>
#include <string.h>
#define PERIOD_REFRESH 100
#define NB_IMAGES_GETERROR 1000
#define PATH_SAVE_GRAPH "train3_lr0.1_q0.85.csv"
#define TRAIN_NAME "train3_lr0.1_q0.85"
void train1(NN *nn, TDB *tdb, double lr, int count);
void train2(NN *nn, TDB *tdb, double lr, double q, int count);
void train3(NN *nn, TDB *tdb, double lr, double q, int count);
void train3_opti(NN *nn, TDB *tdb, double lr, double q, int count); // do not save graph
void SaveAsCSV(char *path, double *data, size_t count);
void replaceWithComa(char *str, double value);
int main(){
rand_set_seed();
//NN nn = InitializeNN(28*28,20,26);
NN nn = LoadNN("train_tdb2_20.nn");
TDB tdb = getTrainData("../../Ressources/Lettres/image2_tdb", "../../Ressources/Lettres/label2_tdb");
train3_opti(&nn, &tdb, 0.3, 1, 100);
SaveNN(&nn, "train_tdb2_20.nn");
double error = getErrorNN(&nn, &tdb, tdb.nb_images);
printf("\n%lf\n", error);
FreeTDB(&tdb);
FreeNN(&nn);
return 0;
}
/*
* lr -> learning rate
* count -> the number of loops that will do the training
*
* */
void train1(NN *nn, TDB *tdb, double lr, int count)
{
int nb_saves = count * (tdb->nb_images / PERIOD_REFRESH) + 1;
double *data = malloc(sizeof(double) * nb_saves);
int index = 0;
double error = getErrorNN(nn, tdb, NB_IMAGES_GETERROR);
data[index++] = error;
nn->lr = lr;
for (int a =0; a < count; a++){
int i = 0;
while (i + PERIOD_REFRESH < tdb->nb_images){
for (int b = i; b < i + PERIOD_REFRESH; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
double percent = (double)(i+1) * 100.0 / (double) tdb->nb_images;
printf("--> %.2f%c loop=%d\n", percent, '%', a);
i += PERIOD_REFRESH;
double error = getErrorNN(nn, tdb, NB_IMAGES_GETERROR);
data[index++] = error;
}
for (int b = i; b < tdb->nb_images; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
}
SaveAsCSV(PATH_SAVE_GRAPH, data, nb_saves);
free(data);
}
/*
* lr -> learning rate
* q -> the value that change the lr every loops
* count -> the number of loops that will do the training
*
* */
void train2(NN *nn, TDB *tdb, double lr, double q, int count)
{
int nb_saves = count * (tdb->nb_images / PERIOD_REFRESH) + 1;
double *data = malloc(sizeof(double) * nb_saves);
int index = 0;
double error = getErrorNN(nn, tdb, NB_IMAGES_GETERROR);
data[index++] = error;
nn->lr = lr;
for (int a =0; a < count; a++){
int i = 0;
while (i + PERIOD_REFRESH < tdb->nb_images){
for (int b = i; b < i + PERIOD_REFRESH; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
double percent = (double)(i+1) * 100.0 / (double) tdb->nb_images;
printf("\r--> %.2f%c loop=%d\n", percent, '%', a);
fflush(stdout);
i += PERIOD_REFRESH;
double error = getErrorNN(nn, tdb, NB_IMAGES_GETERROR);
data[index++] = error;
}
for (int b = i; b < tdb->nb_images; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
nn->lr *= q;
}
SaveAsCSV(PATH_SAVE_GRAPH, data, nb_saves);
free(data);
}
/*
* lr -> learning rate
* q -> the value that change the lr every loops
* count -> the number of loops that will do the training
*
* */
void train3(NN *nn, TDB *tdb, double lr, double q, int count)
{
int nb_saves = count * (tdb->nb_images / PERIOD_REFRESH) + 1;
double *data = malloc(sizeof(double) * nb_saves);
int index = 0;
double error = getErrorNN(nn, tdb, NB_IMAGES_GETERROR);
data[index++] = error;
nn->lr = lr;
for (int a =0; a < count; a++){
int i = 0;
while (i + PERIOD_REFRESH < tdb->nb_images){
for (int b = i; b < i + PERIOD_REFRESH; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
double percent = (double)(i+1) * 100.0 / (double) tdb->nb_images;
printf("\r--> %.2f%c loop=%d\n", percent, '%', a);
fflush(stdout);
i += PERIOD_REFRESH;
double error = getErrorNN(nn, tdb, NB_IMAGES_GETERROR);
data[index++] = error;
}
for (int b = i; b < tdb->nb_images; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
if(a % 4 == 0){
nn->lr *= q;
}
}
SaveAsCSV(PATH_SAVE_GRAPH, data, nb_saves);
free(data);
}
/*
* lr -> learning rate
* q -> the value that change the lr every loops
* count -> the number of loops that will do the training
*
* */
void train3_opti(NN *nn, TDB *tdb, double lr, double q, int count)
{
nn->lr = lr;
for (int a =0; a < count; a++){
int i = 0;
while (i + PERIOD_REFRESH < tdb->nb_images){
for (int b = i; b < i + PERIOD_REFRESH; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
double percent = (double)(i+1) * 100.0 / (double) tdb->nb_images;
printf("\r--> %.2f%c loop=%d", percent, '%', a);
fflush(stdout);
i += PERIOD_REFRESH;
}
for (int b = i; b < tdb->nb_images; b++){
trainNN(nn, tdb->images[b], tdb->labels[b]);
}
if(a % 4 == 0){
nn->lr *= q;
}
}
}
void SaveAsCSV(char *path, double *data, size_t count){
FILE *fs = fopen(path, "w");
if (fs == NULL){
printf("Unable to create file.\n");
exit(EXIT_FAILURE);
}
fprintf(fs, "Step;Values %s\n", TRAIN_NAME);
for (size_t i = 0; i < count; i++){
char value[8];
replaceWithComa(value, data[i]);
fprintf(fs, "%ld;%s\n", i, value);
}
fclose(fs);
}
void replaceWithComa(char *str, double value){
char str_value[8];
snprintf(str_value, 7, "%.3f", value);
int i = 0;
while (str_value[i]){
if (str_value[i] == '.')
str[i] = ',';
else
str[i] = str_value[i];
i++;
}
str[i] = '\0';
}
|
C | #include<stdio.h>
int main()
{
char a[10000];
gets(a);
int b[6] = {0};
int i;
for(i=0; a[i]!='\0'; i++)
{
if(a[i]=='P')
{
b[0]++;
}
else if(a[i]=='A')
{
b[1]++;
}
else if(a[i]=='T')
{
b[2]++;
}
else if(a[i]=='e')
{
b[3]++;
}
else if(a[i]=='s')
{
b[4]++;
}
else if(a[i]=='t')
{
b[5]++;
}
}
while(1)
{
if(b[0]!=0)
{
printf("%c", 'P');
b[0]--;
}
if(b[1]!=0)
{
printf("%c", 'A');
b[1]--;
}
if(b[2]!=0)
{
printf("%c", 'T');
b[2]--;
}
if(b[3]!=0)
{
printf("%c", 'e');
b[3]--;
}
if(b[4]!=0)
{
printf("%c", 's');
b[4]--;
}
if(b[5]!=0)
{
printf("%c", 't');
b[5]--;
}
if(b[0]==0&&b[1]==0&&b[2]==0&&b[3]==0&&b[4]==0&&b[5]==0)
{
break;
}
}
return 0;
} |
C | #include <stdio.h>
void distict_elements(int a[], int n);
int main()
{
int s, i, arr[20];
// Get the array size
scanf("%d", &s);
// Get the array elements
for(i=0; i<s; i++)
{
scanf("%d", &arr[i]);
}
// Function call to print the distinct elements in an array
distict_elements(arr, s);
return 0;
}
void distict_elements(int a[], int n)
{
int i, j;
// Pick all elements one by one
for (i=0; i<n; i++)
{
// Check if the picked element is already printed
for (j=0; j<i; j++)
{
if (a[i] == a[j])
break;
}
// If not printed earlier, then print it
if (i == j)
printf("%d ", a[i]);
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fill.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: daykim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/20 16:15:17 by daykim #+# #+# */
/* Updated: 2019/01/20 16:29:59 by daykim ### ########.fr */
/* */
/* ************************************************************************** */
int avlabl(int **num, int pos, int dgt);
int ft_strcmp(int *s1, int *s2)
{
int i;
i = 0;
while (s1[i])
{
if (s1[i] != s2[i])
break ;
i++;
}
return (s1[i] - s2[i]);
}
int ft_sdkcmp(int **num, int **num2)
{
int i;
i = 0;
while (i <= 8)
{
if (ft_strcmp(num[i], num2[i]))
return (0);
i++;
}
return (1);
}
int fillcell(int **num, int pos)
{
int value;
int row;
int col;
row = pos % 9;
col = pos / 9;
if (pos == 81)
return (1);
if (num[row][col] != 0)
return (fillcell(num, pos + 1));
value = 1;
while (value <= 9)
{
if (avlabl(num, pos, value))
{
num[row][col] = value;
if (fillcell(num, pos + 1))
return (1);
else
num[row][col] = 0;
}
value++;
}
return (0);
}
int fillcell_rev(int **num, int pos)
{
int value;
int row;
int col;
row = pos % 9;
col = pos / 9;
if (pos == 81)
return (1);
if (num[row][col] != 0)
return (fillcell_rev(num, pos + 1));
value = 9;
while (value >= 1)
{
if (avlabl(num, pos, value))
{
num[row][col] = value;
if (fillcell_rev(num, pos + 1))
return (1);
else
num[row][col] = 0;
}
value--;
}
return (0);
}
|
C | #include <stdio.h>
int main(void)
{
int num = 1, num1 = 9;
printf("출력할 단: ");
scanf("%d", &num);
while(num1>0)
{
printf("%d * %d = %d \n", num, num1, num*num1);
num1--;
}
return 0;
} |
C | /*
** c_users.c for users in /Users/pierre/Epitech/PSU/IRC/irc_server
**
** Made by Pierre Monge
** Login <[email protected]>
**
** Started on Sun Jun 11 03:22:27 2017 Pierre Monge
** Last update Sun Jun 11 16:53:40 2017 Pierre Monge
*/
#include "command.h"
#include "client_write.h"
#include "hash.h"
static void print_client_nick(t_client *client, t_hash_entry *entry)
{
t_list_head *head;
t_list_head *pos;
t_client *client_pos;
head = &entry->list;
pos = list_get_first(head);
while (pos != head)
{
client_pos = list_entry(pos, t_client, list);
client_write_buffer(client, RPL_393, client->nick, client_pos->nick);
pos = pos->next;
}
}
int command_users(t_client *client, t_client_command command)
{
int i;
(void)command;
i = 0;
if (!client->nick)
return (client_write_buffer(client, ERR_451), 0);
client_write_buffer(client, RPL_392, client->nick);
while (i < HASH_TABLE_SIZE)
{
print_client_nick(client, &server.clients.table[i]);
i++;
}
client_write_buffer(client, RPL_394, client->nick);
return (0);
}
|
C | #include <stdio.h>
#include <string.h>
char mem[8];
char buf[128];
void initBuf(char *pBuf)
{
int i, j;
mem[0] = '0';
mem[1] = '1';
mem[2] = '2';
mem[3] = '3';
mem[4] = '4';
mem[5] = '5';
mem[6] = '6';
mem[7] = '7';
//ascii table first 32 is not printable
for (i = 2; i < 8; i++)
{
for (j = 0; j < 16; j++)
pBuf[i * 16 + j] = i * 16 + j;
}
}
void prtBuf(char *pBuf)
{
int i, j;
for (i = 2; i < 8; i++)
{
for (j = 0; j < 16; j++)
printf("%c ", pBuf[i * 16 + j]);
printf("\n");
}
}
int main()
{
initBuf(buf);
prtBuf(buf);
return 0;
}
|
C | #if 0
set -e
src="$(basename $0)"
exe="$(echo $src | cut -f1 -d.)"
trap "rm -f $exe" EXIT
gcc -std=gnu99 -Wall -Werror -pedantic -O2 -g -o $exe $src
./$exe
exit $?
#endif
#include "base.h"
string remove_all(string s, int c) {
string t = (string){.len = s.len};
t.s = malloc(t.len + 1);
strcpy(t.s, s.s);
for (int i = 0; i < t.len;) {
if (t.s[i] == tolower(c) || t.s[i] == toupper(c)) {
memmove(&t.s[i], &t.s[i + 1], t.len - i);
t.len--;
continue;
}
i++;
}
return t;
}
int expand(string s, int i) {
int deleted = 0;
int j = i + 1;
for (; i >= 0 && j < s.len;) {
if (s.s[i] != s.s[j] && toupper(s.s[i]) == toupper(s.s[j])) {
deleted += 2;
s.s[i] = ' ';
s.s[j] = ' ';
} else {
break;
}
for (i = i - 1; s.s[i] == ' '; i--)
;
for (j = j + 1; s.s[j] == ' '; j++)
;
}
return deleted;
}
int simulate(string s) {
int newlen = s.len;
for (int i = 0; i < s.len - 1; i++) {
int c0 = s.s[i];
int c1 = s.s[i + 1];
if (c0 != c1 && toupper(c0) == toupper(c1)) {
int deleted = expand(s, i);
i += deleted / 2;
newlen -= deleted;
}
}
return newlen;
}
int main(void) {
char **lines = NULL;
int64_t num_lines = 0;
error err = file_read_lines("05.input.txt", &lines, &num_lines);
if (err != NULL) {
fatal("%s\n", err);
}
string line = cstr_copy(lines[0]);
printf("Part 1: %d\n", simulate(line));
line = cstr_copy(lines[0]);
int64_t min = INT64_MAX;
for (int c = 'a'; c <= 'z'; c++) {
int len = simulate(remove_all(line, c));
if (len < min) {
min = len;
}
}
printf("Part 2: %ld\n", min);
return 0;
}
|
C | #include <stdio.h>
#include <time.h>
// The cycle time
static const float cycle_duration = (float) 1 / (float) 3.1;
// How long takes the chrono to start and stop
static double residue;
void perf_init(){
struct timespec start, end;
clock_gettime(CLOCK_REALTIME, &start);
clock_gettime(CLOCK_REALTIME, &end);
residue = (end.tv_sec- start.tv_sec)*1e9 + (end.tv_nsec-start.tv_nsec);
return;
}
void flop_compute(char* message, unsigned long long int nb_operation, double cycles){
printf("%s %llu operations\n", message, nb_operation);
printf(" %5.3lf GFLOP/s\n", ((double) nb_operation) / (((double) (cycles - residue)) * cycle_duration));
}
|
C | //CSC 332 Group Project
//Authors: Leah Meza
//Due: 5/8/20
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10000
#include "list.h"
#include "tree.h"
//#include "path.h" #rei
#include "exit.h"
int main(void)
{
char* buffer = calloc (N, sizeof (char*)); //array of char from user input including whitespace
char history[4][7]; //hold history of commands
int count = 0;
int FLAG = 0; //only display environment if shell* was entered
if(buffer == NULL) //check buffer for successful memory allocation
{
printf("Memory Allocation failed.");
free(buffer);
exit(1);
}
//input stream loop; infinite loop broken by 'return' key
for(;;){
//input validation
if(FLAG == 1)
printf("==> ");
if (fgets(buffer, N, stdin) != NULL ) //reads line including whitespace from stdin
{
//break condition
if(strlen(buffer) == 1) //check length of buffer (1 because of nullpointer)
{
printf("Exited.\n");
break;
}
//valid options
if(!((strncmp("shell*\n", buffer, 6) == 0) || (strncmp("tree*\n", buffer, 6) == 0) || (strncmp("list*\n", buffer, 6) == 0) ||
(strncmp("path*\n", buffer, 6) == 0) || (strncmp("exit*\n", buffer, 6) == 0)))
{
printf("You didn't enter a valid option!\nOptions: tree*\tlist*\tpath*\texit*\n");
continue; //want to continue out of this loop (prevent a child)
}
}
//Event Handeling
if(strncmp("shell*\n", buffer, 6) == 0) //need to enter shell first to access
{
FLAG = 1;
strcpy(history[count++], "shell*");
}
if(strncmp("tree*\n", buffer, 6) == 0)
{
tree();
strcpy(history[count++], "tree*");
}
if(strncmp("list*\n", buffer, 6) == 0)
{
list();
printf("\n");
strcpy(history[count++], "list*");
}
if(strncmp("path*\n", buffer, 6) == 0)
{
//path();
printf("You chose path*\n"); //debugging purposes
strcpy(history[count++], "path*");
}
if(strncmp("exit*\n", buffer, 6) == 0)
{
exit_(history);
FLAG = 0;
}
}
free(buffer);
return 0;
}
|
C | #include <stdio.h>
#define MAXLINE 1000
/* Write a function reverse(s) that reverses the character string 's'
Use it to write a program that reverses its input line by line
*/
void reverse(char to[], char from[]);
int main() {
int c;
int i = 0;
char temp[MAXLINE];
char perm[MAXLINE];
while ((c = getchar()) != EOF) {
if(c != '\n'){
temp[i] = c;
} else {
i++;
}
reverse(perm, temp);
printf("%s\n", perm);
}
return 0;
}
void reverse(char to[], char from[]){
int i, j, k, charcount;
i = j = k = charcount= 0;
while(from[i] != '\0'){
charcount++;
i++;
}
k = charcount-1;
while((to[j] = from[k]) != '\0'){
i++;
k--;
}
}
|
C | #include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <windows.h>
#define LIN 5000
#define COL 6
#define JOGADOR 3
void imprimir(int *concurso[LIN][COL]){
int l, c;
for(l=0;l<LIN;l++){
for(c=0;c<COL;c++){
printf("|%02d| ",concurso[l][c]);
}
printf("\n\n");
}
}
void bubleSort(int *vetor[LIN][COL]){
int i, j, k, aux;
for(k=0;k<LIN;k++){
for(j=0;j<6;j++){
for(i=0;i<6-j-1;i++){
if(vetor[k][i]>vetor[k][i+1]){
aux = vetor[k][i];
vetor[k][i] = vetor[k][i+1];
vetor[k][i+1] = aux;
}//if
}//for I
}//for J
}//for K
}//ordenaSorteio
void estatistica(int *dezenas[], int *matriz[LIN][COL]){
int i;
int l, c, num;
//zerar o vetor
for(i=0;i<60;i++){
dezenas[i]=0;
}
//contagem de numeros
for(l=0;l<LIN;l++){
for(c=0;c<COL;c++){
num = matriz[l][c];
dezenas[num-1]++;
}
}
/*IMPRIME A ESTATISTICA DE NUMEROS SORTEADOS*/
printf("\n\n---- QUANTIDADE DE VEZES QUE UM NUMERO SAIU ----\n\n");
for(i=0;i<60;i++){
printf("Numero: %02d = %2d vezes\n",i+1, dezenas[i]);
}
printf("\n\n");
}//estatistica
void listarDuplas(int *matriz[LIN][COL]){
int i, j, l, c, e, num1=0, num2=0, duplas[61][61], cont, aux1, aux2, aux3;
struct numeros{
int numero1;
int numero2;
int quant;
};
struct numeros maisSorteados[1770];
/*ZERAR MATRIZ DUPLAS*/
for(i=0;i<61;i++){
for(j=0;j<61;j++){
duplas[i][j] = 0;
}
}
/*CONSTRUINDO MATRIZ DE DUPLAS*/
for(l=0;l<LIN;l++){
for(c=0;c<COL;c++){
for(e=c+1;e<COL;e++){
num1 = matriz[l][c];
num2 = matriz[l][e];
duplas[num1][num2] += 1;
}
}//FOR C
}//FOR L
/*PASSA A MATRIZ PARA A STRUCT*/
cont=0;
for(l=1;l<=60;l++){
for(c=1;c<=60;c++){
if(l != c){
if(l <= c){
maisSorteados[cont].numero1 = l;
maisSorteados[cont].numero2 = c;
maisSorteados[cont].quant = duplas[l][c];
cont++;
}
}
}//FOR C
}//FOR L
/*ORDERNAR A STRUCT*/
for(j=0;j<1770;j++){
for(i=0;i<1770-j-1;i++){
if(maisSorteados[i].quant>maisSorteados[i+1].quant){
aux1 = maisSorteados[i].numero1;
aux2 = maisSorteados[i].numero2;
aux3 = maisSorteados[i].quant;
maisSorteados[i].numero1 = maisSorteados[i+1].numero1;
maisSorteados[i].numero2 = maisSorteados[i+1].numero2;
maisSorteados[i].quant = maisSorteados[i+1].quant;
maisSorteados[i+1].numero1 = aux1;
maisSorteados[i+1].numero2 = aux2;
maisSorteados[i+1].quant = aux3;
}
}
}
/*IMPRIME A STRUCT*/
printf("---- AS 15 DUPLAS QUE MAIS SAIRAM ----\n\n");
for(i=1769;i>1754;i--){
printf("Numeros %02d e %02d = %d vezes.\n", maisSorteados[i].numero1, maisSorteados[i].numero2, maisSorteados[i].quant);
}
printf("\n\n");
}//LISTAR DUPLAS
void numerosUnicos(int *vetor[LIN][COL]){
int i, j, c, l, num, numMaisSorteados[61], maissort=0, aux1, aux2;
struct numeros
{
int numero;
int quant;
};
struct numeros numSorteados[61];
/*Zera o vetor numMaisSorteados*/
for(i=0;i<=60;i++){
numMaisSorteados[i]=0;
}
/*Passa a quantidade de numeros para o vetor numMaisSorteados*/
for(l=0;l<LIN;l++){
for(c=0;c<COL;c++){
num = vetor[l][c];
numMaisSorteados[num]++;
}
}
/*Passa os numeros para a struct*/
for(i=1;i<=60;i++){
numSorteados[i].numero = i;
numSorteados[i].quant = numMaisSorteados[i];
}
/*Ordena a Struct*/
for(j=1;j<=61;j++){
for(i=1;i<=61-j-1;i++){
if(numSorteados[i].quant>numSorteados[i+1].quant) {
aux1 = numSorteados[i].numero;
aux2 = numSorteados[i].quant;
numSorteados[i].numero = numSorteados[i+1].numero;
numSorteados[i].quant = numSorteados[i+1].quant;
numSorteados[i+1].numero = aux1;;
numSorteados[i+1].quant = aux2;
}
}
}
printf("\n\n---- OS 15 NUMEROS MAIS SORTEADOS ----\n\n");
/*Impresso do vetor*/
for(i=60;i>45;i--){
//printf("%d = %d\n", i, numMaisSorteados[i]);
printf("Numero %02d = %2d vezes\n", numSorteados[i].numero, numSorteados[i].quant);
}
printf("\n\n");
}
void quantidadeJogadas(int *vetor[LIN][COL]){
int i, j, l, c, num[61], saiu=0;
/*ZERA O VETOR NUM*/
for(i=0;i<61;i++){
num[i]=0;
}
for(i=1;i<=60;i++){
for(l=LIN-1;l>=0;l--){
for(c=0;c<COL;c++){
if(vetor[l][c] == i){
saiu = 1;
}//IF
}//FOR C
if(saiu == 0){
num[i]+=1;
}else{
break;
}
}//FOR L
if(saiu == 1){
saiu = 0;
continue;
}
}//FOR I
/*IMPRESSAO NUMEROS QUE SAIRAM NA QUANT JOGADAS*/
printf("\n\n---- QUANTIDADE DE JOGADAS QUE UM NUMERO DEMOROU A SAIR ----\n\n");
for(i=1;i<=60;i++){
if(num[i]==0){
printf("N %02d = saiu no ultimo sorteio.\n");
}else{
printf("N %02d = nao sai a %d sorteios seguidos\n", i, num[i]);
}
}//FOR
printf("\n\n");
}
void corrigirjogos(int *aposta[], int *sorteios[LIN][COL], char nome[]){
int acertos = 0, melhorresultado = 0, melhorjogo = 0;
int l, c, i;
for(l=0;l<LIN;l++){
acertos = 0;
for(i=0;i<COL;i++){
for(c=0;c<COL;c++){
if(aposta[i]==sorteios[l][c]){
acertos += 1;
}
}//FOR C
if(acertos > melhorresultado){
melhorresultado = acertos;
melhorjogo = l;
}
}//FOR I
}//FOR L
if(melhorresultado == 0){
printf("\n%s voc acertou %d numeros\n", nome, melhorresultado);
}else{
if(melhorresultado==6){
for(i=1;i<=10;i++){
if(i%2==0){
Sleep(100);
system("color 07");
}else{
Sleep(100);
system("color 47");
}
}
printf("\nParabns %s, voc acertou %d numeros! Sorteio [%04d]\n", nome, melhorresultado, melhorjogo+1);
}else{
printf("\nParabns %s, voc acertou %d numeros! Sorteio [%04d]\n", nome, melhorresultado, melhorjogo+1);
}
}
}//CORRIGIR JOGOS
int main() {
int l, c, i, k, op=0, teste=0, aux;
int j, num, igual=0, resultadojogo = 0;
int concurso[LIN][COL];
int dezenas[60], numaposta[6];
struct sena{
char nome[50];
char cpf[11];
int jogo[6];
};
struct sena aposta[3];
setlocale(LC_ALL, "Portuguese");//habilita a acentuao para o portugus
/*SORTEIA OS NUMEROS*/
srand(time(NULL));
for(l=0;l<LIN;l++){
for(c=0;c<COL;){
while(igual!=1){
num = rand()%61;
for(i=0;i<6;i++){
if((num == concurso[l][i]) || (num == 0)){
igual=1;
}
}//for i
if(igual==0){
concurso[l][c]=num;
c++;
}
}//while
igual=0;
}
}
/*FIM SORTEIA OS NUMEROS*/
bubleSort(concurso); //ORDENA OS NUMEROS NO SORTEIO
/*MENU*/
do{
do{
system("cls");
printf("MENU PRINCIPAL\n\n");
printf("\t1 - IMPRIMIR SORTEIOS\n");
printf("\t2 - LISTAR QUANTAS VEZES CADA NUMERO SAIU\n");
printf("\t3 - LISTAR 15 DUPLAS QUE MAIS SAIRAM NOS SORTEIOS\n");
printf("\t4 - LISTAR OS 15 NUMEROS UNICOS QUE MAIS SAIRAM NOS SORTEIOS\n");
printf("\t5 - QUANTIDADE DE JOGADAS DESDE A ULTIMA VEZ QUE UM NUMERO FOI SORTEADO\n");
printf("\t6 - LISTAR TODAS AS ESTATISTICAS\n");
printf("\t7 - FAZER JOGADAS\n");
printf("\t8 - IMPRIMIR AS APOSTAS\n");
printf("\t0 - SAIR\n");
scanf("%d", &op);
}while(op<0 || op>8);
switch(op){
case 1:
imprimir(concurso);
break;
case 2:
estatistica(dezenas, concurso);
break;
case 3:
listarDuplas(concurso);
break;
case 4:
numerosUnicos(concurso);
break;
case 5:
quantidadeJogadas(concurso);
break;
case 6:
estatistica(dezenas, concurso);
listarDuplas(concurso);
numerosUnicos(concurso);
quantidadeJogadas(concurso);
break;
case 7:
/*CAPTURA AS APOSTAS*/
for(i=0;i<JOGADOR;i++){
printf("Entre com o nome do jogador %d: ", i+1);
fflush(stdin);
gets(aposta[i].nome);
printf("Entre o seu CPF %s [s os numeros]: ", aposta[i].nome);
/*CAPTURA E TESTA O CPF*/
do{
fflush(stdin);
gets(aposta[i].cpf);
teste = strlen(aposta[i].cpf);
if(teste!=11){
printf("O CPF deve conter 11 digitos, insira um CPF valido: ");
}
}while(teste!=11);
for(j=0;j<6;j++){
printf("Entre com %d numero: ", j+1);
/*TESTE E CAPTURA AS DEZENAS DO JOGO*/
do{
scanf("%d", &teste);
if(teste<1 || teste>60){
printf("\tSo sao aceitos numeros de 1 a 60 insira um numero valido: ");
}
/*VALIDAAO DE NUMEROS REPETIDOS*/
for(k=0;k<=j+1;k++){
if(teste==aposta[i].jogo[k]){
printf("Numero nao pode ser repetido\n");
j--;
continue;
}
}
}while(teste<1 || teste>60);
aposta[i].jogo[j] = teste;
}
printf("\n\n");
}//FOR I
/*ORDERNAR OS NUMEROS DA JOGADA*/
for(k=0;k<JOGADOR;k++){
for(j=0;j<6;j++){
for(i=0;i<6-j-1;i++){
if(aposta[k].jogo[i]>aposta[k].jogo[i+1]){
aux = aposta[k].jogo[i];
aposta[k].jogo[i] = aposta[k].jogo[i+1];
aposta[k].jogo[i+1] = aux;
}//if
}//for I
}//for J
}
/*FIM ORDERNAR OS NUMEROS DA JOGADA*/
/*VERIFICA OS ACERTOS E O SORTEIO COM MAIOR PONTUAO*/
for(i=0;i<JOGADOR;i++){
corrigirjogos(aposta[i].jogo, concurso, aposta[i].nome);
printf("\n");
}
printf("\n\n");
break;
case 8:
/*IMPRIME AS JOGADAS*/
for(i=0;i<JOGADOR;i++){
printf("Jogador %d: %s\n", i+1, aposta[i].nome);
printf("CPF: %s\n", aposta[i].cpf);
printf("Jogo: ");
for(j=0;j<6;j++){
printf("[%02d] ", aposta[i].jogo[j]);
numaposta[j] = aposta[i].jogo[j];
}
corrigirjogos(aposta[i].jogo, concurso, aposta[i].nome);
printf("\n\n");
}
printf("\n\n");
break;
}//SWITCH
if(op!=0){
getch();
}
}while(op!=0);
printf("\nfim do programa\n");
return 0;
}
|
C | #include<stdio.h>
int main()
{
int money,i,j;
j=0;
do
{
printf("你有多少钱\n");
scanf("%d",&money);
}while(money<1&&printf("滚回家拿钱\n"));
for(i=1;i<=money;i++)
{
j++;
if(j%2==0)
j++;
}
printf("您能喝多少瓶饮料%d\n",j);
return 0;
}
|
C | /*
* file: wall.c
* author: GAndaLF
* brief: Wall detection task.
*/
#include "platform_specific.h"
#include "led/led.h"
#include "adc/adc.h"
#include "wall_sensor/adc2dist.h"
#include "wall_sensor/wall_sensor.h"
/** Function converting ADC value to distance for specific sensor. */
typedef int32_t (*adc2dist_fun)(int32_t);
/** Data structure containing wall sensor data. */
struct wall_sensor
{
int32_t photo_id;
int32_t led_id;
adc2dist_fun dist_fun;
int32_t val;
};
/** All wall sensor data. */
static struct wall_sensor wall_sensor_list[WALL_SENSOR_CNT];
/** Initialize single wall sensor struct. */
static void sensor_list_entry_init(int32_t index, int32_t photo_id, int32_t led_id, adc2dist_fun fun);
/**
* Wall sensor task handler.
*
* @param params Task parameters - unused.
*/
static void wall_task(void *params);
/**
* Update single sensor measurement.
*
* @param sensor Sensor data.
* @param val_off Ambient light measurement for this sensor.
*/
static void sensor_update(struct wall_sensor *sensor, int32_t val_off);
void wall_sensor_init(void)
{
/* led and adc initialized earlier by vbat task. */
sensor_list_entry_init(WALL_SENSOR_FRONT_L, ADC_PHOTO_FRONT_L, LED_IR_FRONT_L, adc2dist_front_l);
sensor_list_entry_init(WALL_SENSOR_FRONT_R, ADC_PHOTO_FRONT_R, LED_IR_FRONT_R, adc2dist_front_r);
sensor_list_entry_init(WALL_SENSOR_DIAG_L, ADC_PHOTO_DIAG_L, LED_IR_DIAG_L, adc2dist_diag_l);
sensor_list_entry_init(WALL_SENSOR_DIAG_R, ADC_PHOTO_DIAG_R, LED_IR_DIAG_R, adc2dist_diag_r);
sensor_list_entry_init(WALL_SENSOR_SIDE_L, ADC_PHOTO_SIDE_L, LED_IR_SIDE_L, adc2dist_side_l);
sensor_list_entry_init(WALL_SENSOR_SIDE_R, ADC_PHOTO_SIDE_R, LED_IR_SIDE_R, adc2dist_side_r);
rtos_task_create(wall_task, "wall", WALL_STACKSIZE, WALL_PRIORITY);
}
int32_t wall_sensor_dist_mm_get(int32_t sensor_id)
{
if ((0 > sensor_id) || (WALL_SENSOR_CNT <= sensor_id))
{
return WALL_SENSOR_ERROR;
}
return wall_sensor_list[sensor_id].val;
}
int32_t wall_sensor_side_l_dist_mm_get(void)
{
return wall_sensor_list[WALL_SENSOR_SIDE_L].val;
}
int32_t wall_sensor_side_r_dist_mm_get(void)
{
return wall_sensor_list[WALL_SENSOR_SIDE_R].val;
}
int32_t wall_sensor_diag_l_dist_mm_get(void)
{
return wall_sensor_list[WALL_SENSOR_DIAG_L].val;
}
int32_t wall_sensor_diag_r_dist_mm_get(void)
{
return wall_sensor_list[WALL_SENSOR_DIAG_R].val;
}
int32_t wall_sensor_front_l_dist_mm_get(void)
{
return wall_sensor_list[WALL_SENSOR_FRONT_L].val;
}
int32_t wall_sensor_front_r_dist_mm_get(void)
{
return wall_sensor_list[WALL_SENSOR_FRONT_R].val;
}
static void sensor_list_entry_init(int32_t index, int32_t photo_id, int32_t led_id, adc2dist_fun fun)
{
wall_sensor_list[index].photo_id = photo_id;
wall_sensor_list[index].led_id = led_id;
wall_sensor_list[index].dist_fun = fun;
wall_sensor_list[index].val = 0;
}
static void wall_task(void *params)
{
(void) params;
tick_t last;
int32_t i;
int32_t val_off[WALL_SENSOR_CNT];
while (1)
{
last = rtos_tick_count_get();
/* Measure ambient light. */
for (i = 0; i < WALL_SENSOR_CNT; i++)
{
val_off[i] = adc_val_get(wall_sensor_list[i].photo_id);
}
/* Measure distance. */
for (i = 0; i < WALL_SENSOR_CNT; i++)
{
sensor_update(&wall_sensor_list[i], val_off[i]);
}
rtos_delay_until(&last, 10);
}
}
static void sensor_update(struct wall_sensor *sensor, int32_t val_off)
{
int32_t val_on;
led_on(sensor->led_id);
rtos_delay(1);
val_on = adc_val_get(sensor->photo_id);
sensor->val = sensor->dist_fun(val_on - val_off);
led_off(sensor->led_id);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include "global.h"
// Rank of the root node
#define ROOT 0
// Indexing macro for local pres arrays
#define LP(row, col) ((row) + border) * (local_width + 2 * border) + ((col) + border)
// Arrays used by MPI_scatterv and MPI_gatherv for for each of the processes
static int *displs;
static int *counts;
// Distribute the diverg (bs) from root to all the processes
void distribute_diverg() {
MPI_Scatterv(diverg + imageSize + 3, // sendbuf
counts, // sendcnts
displs, // displs
pres_and_diverg_t, // sendtype
local_diverg, // recvbuf
1, // recvcnt
local_diverg_t, // recvtype
ROOT, // root
cart_comm); // comm
}
// Gather the results of the computation at the root
void gather_pres() {
MPI_Gatherv(local_pres0 + local_width + 3, // sendbuf
1, // sendcount
local_pres_t, // sendtype
pres + imageSize + 3, // recvebuf
counts, // recvcounts
displs, // displs
pres_and_diverg_t, // recvtype
ROOT, // root
cart_comm); // comm
}
// Called from 'exchange_borders', handles the MPI procedure calls
void exchange_border(float *out, float *in, int dst, MPI_Datatype type) {
int tag = dst + rank;
MPI_Send(out, 1, type, dst, tag, cart_comm);
MPI_Recv(in, 1, type, dst, tag, cart_comm, &status);
}
// Exchange borders between processes during computation
void exchange_borders() {
float *lp = local_pres;
if (north >= 0) {
exchange_border(lp + LP(0, 0), lp + LP(-1, 0), north, border_row_t);
}
if (south >= 0) {
exchange_border(lp + LP(local_height - 1, 0), lp + LP(local_height, 0), south, border_row_t);
}
if (west >= 0) {
exchange_border(lp + LP(0, 0), lp + LP(0, -1), west, border_col_t);
}
if (east >= 0) {
exchange_border(lp + LP(0, local_width - 1), lp + LP(0, local_width), east, border_col_t);
}
}
// Calculate the value for one element in the grid
float calculate_jacobi(int row, int col) {
float x1 = local_pres0[LP(row, col - 1)],
x2 = local_pres0[LP(row - 1, col)],
x3 = local_pres0[LP(row, col + 1)],
x4 = local_pres0[LP(row + 1, col)];
// If the element is on the border of 'pres', set to it's current value instead
if (north < 0 && row == 0) {
x2 = local_pres0[LP(row, col)];
}
if (south < 0 && row == local_height) {
x4 = local_pres0[LP(row, col)];
}
if (west < 0 && col == 0) {
x1 = local_pres0[LP(row, col)];
}
if (east < 0 && col == local_width) {
x3 = local_pres0[LP(row, col)];
}
return 0.25 * (x1 + x2 + x3 + x4 - local_diverg[row * local_width + col]);
}
// One jacobi iteration
void jacobi_iteration() {
for (int i = 0; i < local_height; i++) {
for (int j = 0; j < local_width; j++) {
local_pres[LP(i, j)] = calculate_jacobi(i, j);
}
}
}
// Calculates the displacements used in'gather_pres' and 'distribute_diverg'
// for each of the processes,
// and initializes 'local_pres' and 'local_pres0' to empty arrays
void init_local_pres() {
displs = malloc(sizeof(int) * size);
counts = malloc(sizeof(int) * size);
for (int i = 0; i < dims[0]; i++) {
for (int j = 0; j < dims[1]; j++) {
int index = i * dims[1] + j;
displs[index] = i * local_height * (imageSize + 2) + j * local_width;
counts[index] = 1;
}
}
for (int i = -1; i < local_height + 1; i++) {
for (int j = -1; j < local_width + 1; j++) {
int index = LP(i, j);
local_pres0[index] = 0.0;
local_pres[index] = 0.0;
}
}
}
// Solve linear system with jacobi method
void jacobi(int iter) {
init_local_pres();
distribute_diverg();
// // Jacobi iterations
for (int k = 0; k < iter; k++) {
jacobi_iteration();
exchange_borders();
// Rearrange the pointers after each iteration
float *temp_ptr = local_pres0;
local_pres0 = local_pres;
local_pres = temp_ptr;
}
gather_pres();
}
// For debugging purposes
void print_local_pres(float *jacobi) {
for(int i = -1; i < local_height + 1; i++) {
for (int j = -1; j < local_width + 1; j++) {
printf("%f ", jacobi[LP(i, j)]);
}
printf("\n");
}
}
|
C | //题目:字符串排序
//ps:计算输入字符个数的问题,sizeof的用法并不是直接算个数的,而是使用的空间,其次64位系统,指针是8位,wtm,比较的时候看清楚
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void swap(char * str1,char * str2);
int main()
{
char str1[20],str2[20],str3[20];
printf("输入3个字符串(每个以回车结束):\n");
fgets(str1,(sizeof(str1) / sizeof(str1[0])),stdin);
fgets(str2,(sizeof(str2) / sizeof(str2[0])),stdin);
fgets(str3,(sizeof(str3) / sizeof(str3[0])),stdin);
if (strcmp(str1,str2) > 0)
swap(str1,str2);
if (strcmp(str2,str3) > 0)
swap(str2,str3);
if (strcmp(str1,str2) > 0)
swap(str1,str2);
printf("排序后:\n");
printf("%s\n%s\n%s\n",str1,str2,str3);
return 0;
}
void swap(char * str1,char * str2)
{
char tem[20];
strcpy(tem,str1);
strcpy(str1,str2);
strcpy(str2,tem);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_alignement.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: letuffle <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/27 23:44:09 by letuffle #+# #+# */
/* Updated: 2020/07/27 23:44:12 by letuffle ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include "libft.h"
size_t set_length(t_formats *formats)
{
if (isnumbertype(formats->type[0]) && ft_atoi(formats->accuracy + 1) > 0)
return (ft_atoi(formats->accuracy + 1));
return (0);
}
char *set_width(char *param, t_formats *formats)
{
char *new_param;
char *complement;
char *sign;
size_t length;
sign = strfromchr('\0');
if (param[0] == '-' || param[0] == '+')
sign[0] = param[0];
length = set_length(formats);
if (ft_strlen(param) - ft_strlen(sign) < length)
{
length -= ft_strlen(param) - ft_strlen(sign);
new_param = malloc(length + ft_strlen(param) + 1);
ft_memcpy(new_param, param, ft_strlen(sign));
complement = ft_full('0', length);
ft_memcpy(new_param + ft_strlen(sign), complement, length);
ft_strlcpy(new_param + ft_strlen(sign) + length,
param + ft_strlen(sign), ft_strlen(param + ft_strlen(sign)) + 1);
free(complement);
free(param);
param = new_param;
}
free(sign);
return (param);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* s_operation.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hecampbe <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/18 19:27:11 by hecampbe #+# #+# */
/* Updated: 2019/09/24 14:36:11 by hecampbe ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int *sa(t_len *length, t_str *strings)
{
int tmp;
if (strings->str_a == NULL)
return (strings->str_a);
tmp = strings->str_a[0];
strings->str_a[0] = strings->str_a[1];
strings->str_a[1] = tmp;
tmp = strings->str_a[0];
return (intdup_a(length, strings->str_a));
}
int *sb(t_len *length, t_str *strings)
{
int tmp;
if (strings->str_b == NULL)
return (strings->str_b);
tmp = strings->str_b[0];
strings->str_b[0] = strings->str_b[1];
strings->str_b[1] = tmp;
return (intdup_b(length, strings->str_b));
}
int **ss(t_len *length, t_str *strings)
{
free(strings->str_both);
strings->str_both = (int **)malloc(sizeof(int *) * (2));
strings->str_both[0] = sa(length, strings);
strings->str_both[1] = sb(length, strings);
return (strings->str_both);
}
|
C | #include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <math.h>
#include <util/delay.h>
#include "serial.h"
#include "dynamixel.h"
#define PI 3.141592f
/// Control table address
#define P_CW_ANGLE_LIMIT_L 6
#define P_CCW_ANGLE_LIMIT_L 8
#define P_GOAL_POSITION_L 30
#define P_GOAL_POSITION_H 31
#define P_GOAL_SPEED_L 32
#define P_GOAL_SPEED_H 33
// Default setting
#define DEFAULT_BAUDNUM 1 // 1Mbps
#define NUM_ACTUATOR 4 // Number of actuators
#define STEP_THETA (PI / 100.0f) // Large value is more fast
#define CONTROL_PERIOD (10) // msec (Large value is more slow)
#define POSITION_CENTER 512
#define POSITION_LEFT_45 358
#define POSITION_RIGHT_45 666
#define NOMINAL_SPEED 20
void PrintCommStatus(int CommStatus);
void PrintErrorCode(void);
int main(void)
{
int ax12a_id[NUM_ACTUATOR];
int mx12w_id[NUM_ACTUATOR];
float offsets[NUM_ACTUATOR];
float speeds[NUM_ACTUATOR];
float theta = 0;
float degrees_to_position_units = 1023.0f / 300.0f;
int GoalPos;
int GoalSpeed;
int i;
int CommStatus;
unsigned char ReceivedData;
serial_initialize(57600);
dxl_initialize( 0, DEFAULT_BAUDNUM ); // Not using device index
sei(); // Interrupt Enable
printf( "\n\nSteve the servo controller\n\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
ax12a_id[i] = 10 + 10 * i;
mx12w_id[i] = 11 + 10 * i;
offsets[i] = 0.0f;
speeds[i] = 0.0f;
}
// Set wheel mode for mx12w (run once to store to eeprom)
/*
for( i=0; i<NUM_ACTUATOR; i++ )
{
dxl_write_word( mx12w_id[i], P_CW_ANGLE_LIMIT_L, 0 );
dxl_write_word( mx12w_id[i], P_CCW_ANGLE_LIMIT_L, 0 );
}
*/
// Set goal speed
dxl_write_word( BROADCAST_ID, P_GOAL_SPEED_L, 0 );
// Set goal position
dxl_write_word( BROADCAST_ID, P_GOAL_POSITION_L, POSITION_CENTER );
_delay_ms(1000);
while(1)
{
ReceivedData = getchar();
if(ReceivedData == 'w')
{
printf( "Forward\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
offsets[i] = 0.0f;
speeds[i] = (i < 2) ? -1.0f : +1.0f;
}
}
else if(ReceivedData == 's')
{
printf( "Backward\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
offsets[i] = 0.0f;
speeds[i] = (i < 2) ? +1.0f : -1.0f;
}
}
else if(ReceivedData == 'a')
{
printf( "Left\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
offsets[i] = (i == 0 || i == 3) ? -45.0f : +45.0f;
speeds[i] = +1.0f;
}
}
else if(ReceivedData == 'd')
{
printf( "Right\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
offsets[i] = (i == 0 || i == 3) ? -45.0f : +45.0f;
speeds[i] = -1.0f;
}
}
else if(ReceivedData == 'q')
{
printf( "Forward right\n" );
offsets[0] = +30.0f; speeds[0] = -0.447f;
offsets[1] = -30.0f; speeds[1] = -0.447f;
offsets[2] = +15.0f; speeds[2] = +1.0f;
offsets[3] = -15.0f; speeds[3] = +1.0f;
}
else if(ReceivedData == 'z')
{
printf( "Back right\n" );
offsets[0] = +30.0f; speeds[0] = +0.447f;
offsets[1] = -30.0f; speeds[1] = +0.447f;
offsets[2] = +15.0f; speeds[2] = -1.0f;
offsets[3] = -15.0f; speeds[3] = -1.0f;
}
else if(ReceivedData == 'e')
{
printf( "Forward left\n" );
offsets[0] = -15.0f; speeds[0] = -1.0f;
offsets[1] = +15.0f; speeds[1] = -1.0f;
offsets[2] = -30.0f; speeds[2] = +0.447f;
offsets[3] = +30.0f; speeds[3] = +0.447f;
}
else if(ReceivedData == 'c')
{
printf( "Back left\n" );
offsets[0] = -15.0f; speeds[0] = +1.0f;
offsets[1] = +15.0f; speeds[1] = +1.0f;
offsets[2] = -30.0f; speeds[2] = -0.447f;
offsets[3] = +30.0f; speeds[3] = -0.447f;
}
else if(ReceivedData == ' ')
{
printf( "Stop\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
//offsets[i] = 0.0f;
speeds[i] = 0.0f;
}
}
else if(ReceivedData == 'x')
{
printf( "Park\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
offsets[i] = (i == 0 || i == 3) ? +30.0f : -30.0f;
speeds[i] = 0.0f;
}
}
for( i=0; i<NUM_ACTUATOR; i++ )
{
GoalPos = POSITION_CENTER + (int)(offsets[i] * degrees_to_position_units);
printf( "%d ", GoalPos );
dxl_write_word( ax12a_id[i], P_GOAL_POSITION_L, GoalPos );
}
printf( "\n" );
for( i=0; i<NUM_ACTUATOR; i++ )
{
GoalSpeed = speeds[i] > 0 ?
1024 + (int)(speeds[i] * NOMINAL_SPEED) :
(int)(-speeds[i] * NOMINAL_SPEED);
printf( "%d ", GoalSpeed );
dxl_write_word( mx12w_id[i], P_GOAL_SPEED_L, GoalSpeed );
}
printf( "\n" );
CommStatus = dxl_get_result();
if( CommStatus == COMM_RXSUCCESS )
PrintErrorCode();
else
PrintCommStatus(CommStatus);
theta += STEP_THETA;
if( theta > 2*PI )
theta -= 2*PI;
_delay_ms(CONTROL_PERIOD);
}
return 0;
}
// Print communication result
void PrintCommStatus(int CommStatus)
{
switch(CommStatus)
{
case COMM_TXFAIL:
printf("COMM_TXFAIL: Failed transmit instruction packet!\n");
break;
case COMM_TXERROR:
printf("COMM_TXERROR: Incorrect instruction packet!\n");
break;
case COMM_RXFAIL:
printf("COMM_RXFAIL: Failed get status packet from device!\n");
break;
case COMM_RXWAITING:
printf("COMM_RXWAITING: Now recieving status packet!\n");
break;
case COMM_RXTIMEOUT:
printf("COMM_RXTIMEOUT: There is no status packet!\n");
break;
case COMM_RXCORRUPT:
printf("COMM_RXCORRUPT: Incorrect status packet!\n");
break;
default:
printf("This is unknown error code!\n");
break;
}
}
// Print error bit of status packet
void PrintErrorCode()
{
if(dxl_get_rxpacket_error(ERRBIT_VOLTAGE) == 1)
printf("Input voltage error!\n");
if(dxl_get_rxpacket_error(ERRBIT_ANGLE) == 1)
printf("Angle limit error!\n");
if(dxl_get_rxpacket_error(ERRBIT_OVERHEAT) == 1)
printf("Overheat error!\n");
if(dxl_get_rxpacket_error(ERRBIT_RANGE) == 1)
printf("Out of range error!\n");
if(dxl_get_rxpacket_error(ERRBIT_CHECKSUM) == 1)
printf("Checksum error!\n");
if(dxl_get_rxpacket_error(ERRBIT_OVERLOAD) == 1)
printf("Overload error!\n");
if(dxl_get_rxpacket_error(ERRBIT_INSTRUCTION) == 1)
printf("Instruction code error!\n");
}
|
C | //printing fibonacci series upto nth term
#include<stdio.h>
main()
{
int n,f1,f2,fib,i;
printf("Enter number of terms:");
scanf("%d",&n);
f1=0;
f2=1;
printf("%d\t%d\t",f1,f2);
i=3;
while(i<=n)
{
fib=f1+f2;
printf("%d\t",fib);
f1=f2;
f2=fib;
i++;
}
}
|
C | #include "board_usb.h"
#include "board_led.h"
/* USB Device Core handle declaration */
USBD_HandleTypeDef hUsbDeviceFS;
volatile int conn_init;
static void usb_vbus_exti_init(void)
{
/*
PA0 (OTG_VBUS) Init:
*/
/*
GPIO data struct to hold settings:
*/
static GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
__HAL_RCC_GPIOA_CLK_ENABLE();
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*
Set up interrupt prioroties and enable the interrupts:
*/
HAL_NVIC_SetPriority(EXTI9_5_IRQn, 1, 1);
HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
}
/*
User code section of the EXTI IRQ, called from HAL_GPIO_EXTI_IRQHandler
after interrupt flags are cleared:
*/
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if(GPIO_Pin == GPIO_PIN_9)
{
if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_9) == GPIO_PIN_RESET)
{
conn_init = 0;
board_led_off(LED1);
}
else
{
conn_init = 1;
board_led_on(LED1);
}
}
}
/*
EXTI IRQ Handlers. These call the generic EXTI IRQ handler from the Cube
HAL, which in turn call the user-defined generic EXTI Callback function
defined further below:
*/
void EXTI9_5_IRQHandler(void)
{
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9);
}
/* init function */
void board_usb_init(void)
{
conn_init=0;
usb_vbus_exti_init();
/* Init Device Library,Add Supported Class and Start the library*/
USBD_Init(&hUsbDeviceFS, &FS_Desc, DEVICE_FS);
USBD_RegisterClass(&hUsbDeviceFS, &USBD_CDC);
USBD_CDC_RegisterInterface(&hUsbDeviceFS, &USBD_Interface_fops_FS);
USBD_Start(&hUsbDeviceFS);
}
int board_usb_sendString(uint8_t *pbuf, int len)
{
if(len > 0)
{
if(conn_init)
{
if(CDC_Transmit_FS(pbuf, (uint16_t)len) == USBD_OK)
{
return len;
}
return -1;
}
return -1;
}
return -1;
} |
C | /* -------------------------------
Name: Luxi Liang
Student number: 165936188
Email: [email protected]
Section: SJJ
Date: August 2, 2019
----------------------------------
Assignment: 2
Milestone: 4
---------------------------------- */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
// +-------------------------------------------------+
// | NOTE: Include additional header files... |
// +-------------------------------------------------+
#include "contacts.h"
#include "contactHelpers.h"
// +-------------------------------------------------+
// | NOTE: Copy/Paste your Assignment-2 Milestone-3 |
// | source code below... |
// +-------------------------------------------------+
// getName:
void getName(struct Name* name) {
int request;
printf("Please enter the contact's first name: ");
scanf(" %30[^\n]s", name->firstName); //Get user input for their first name
clearKeyboard(); //Empties buffer
printf("Do you want to enter a middle initial(s)? (y or n): ");
request = yes(); //call the function yes() from connected source file
if (request)
{
printf("Please enter the contact's middle initial(s): ");
scanf(" %6[^\n]", name->middleInitial); //Get user input for their middle initial
clearKeyboard(); //Empties buffer
}
else
{
strcpy(name->middleInitial, "");
}
printf("Please enter the contact's last name: ");
scanf(" %35[^\n]", name->lastName); //Get user input for their last name
clearKeyboard(); //Empties buffer
}
// getAddress:
void getAddress(struct Address* address)
{
int request;
printf("Please enter the contact's street number: ");
address->streetNumber = getInt(); //call the function getInt() in order to receive an integer
while (address->streetNumber <= 0) //Integer provided for street number must be greater than zero
{
printf("*** INVALID STREET NUMBER *** <must be a positive number>: "); //Display message if user inputs integer less than zero
address->streetNumber = getInt();
}
printf("Please enter the contact's street name: ");
scanf(" %40[^\n]", address->street); //Get user input for their street name
clearKeyboard(); // Empties buffer
printf("Do you want to enter an apartment number? (y or n): ");
request = yes(); //call the function yes()
if (request) //Loop will only execute if user inputs 'y'
{
printf("Please enter the contact's apartment number: ");
address->apartmentNumber = getInt(); //Call the function getInt()
while (address->apartmentNumber <= 0)
{
printf("*** INVALID APARTMENT NUMBER *** <must be a positive number>: "); //Display message if user inputs integer less than zero
address->apartmentNumber = getInt();
}
}
else
{
address->apartmentNumber = 0;
}
printf("Please enter the contact's postal code: ");
scanf(" %7[^\n]", address->postalCode); //Get user input for their postal code
clearKeyboard(); //Empties buffer
printf("Please enter the contact's city: ");
scanf(" %40[^\n]", address->city); //Get user input for their city
clearKeyboard(); //Empties buffer
}
// getNumbers:
// HINT: Update this function to use the new helper
// function "getTenDigitPhone" where applicable
void getNumbers(struct Numbers* numbers)
{
int request;
printf("Please enter the contact's cell phone number: ");
getTenDigitPhone(numbers->cell); //Get user input for their cell phone number
printf("Do you want to enter a home phone number? (y or n): ");
request = yes(); //Call the function yes()
if (request) //Loop will only execute if user inputs 'y'
{
printf("Please enter the contact's home phone number: ");
getTenDigitPhone(numbers->home);
}
else
{
strcpy(numbers->home, "");
}
printf("Do you want to enter a business phone number? (y or n): ");
request = yes(); //Call the function yes()
if (request) //Loop will only execute if user inputs 'y'
{
printf("Please enter the contact's business phone number: ");
getTenDigitPhone(numbers->business);
}
else
{
strcpy(numbers->business, "");
}
}
// getContact
void getContact(struct Contact *contact) {
getName(&contact->name);
getAddress(&contact->address);
getNumbers(&contact->numbers);
}
|
C | #include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
char input[256];
while (1) {
printf("enter text 255 chars or less, type quit and press enter to quit: ");
fgets(input, 255, stdin);
if (!strcmp(input, "quit\n")) {
break;
} else {
printf("you said %s", input);
}
}
return 0;
}
|
C | #include<stdio.h>
int main()
{
int a;
scanf("%d",&a);
while(a!=0)
{
printf("%d\n",(a*(a+1)*(2*a+1))/6);
scanf("%d",&a);
}
return 0;
}
|
C | #include "../include/sysio.h"
size_t __sys_write(int fd, const void* buffer, size_t count){
switch(fd){
case STD_ERR:
case STD_OUT:
__print(STD_DISPLAY,buffer,count);break;
case REG_OUT:
__print(REG_DISPLAY,buffer,count);break;
default:
return -1;
}
}
size_t __sys_read(int fd, void* buffer, size_t count){
size_t nread;
switch(fd){
case STD_IN: {
nread=__read_from_stdin(fd, buffer,count);break;
}
default: nread=-1; break;
}
return nread;
}
size_t __read_from_stdin(int fd, void* buffer, size_t count){
_Sti();
size_t i;
char ch;
char* aux;
if(fd==STD_IN){
for(i=0;i<count;i++){
ch='\0';
while(ch=='\0'){
ch=getKBChar();
}
aux=(char*)buffer;
*(aux+i)=ch;
}
}
return i;
} |
C | #include<stdio.h>
int input();
int cetak();
int cari();
int main(void)
{
int keluar = 0;
int pilihan;
while(keluar != 1)
{
// Jika menggunakan UNIX/LINUX maka gunakan system("clear")
// Jika menggunakan Windows maka gunakan clrscr();
system("clear");
printf("====================\n");
printf("1. Input Data\n");
printf("2. Cetak Data\n");
printf("3. Cari Data\n");
printf("4. Keluar\n");
printf("====================\n");
printf("Pilih Menu: ");
scanf("%d", &pilihan);
switch(pilihan)
{
case 1:
keluar = input();
break;
case 2:
keluar = cetak();
break;
case 3:
keluar = cari();
break;
default:
system("clear");
printf("Yakin ingin keluar ? (y/n)");
char c;
scanf(" %c", &c);
if(c == 'y'){
keluar = 1;
} else {
keluar = 0;
}
break;
}
}
}
int cetak()
{
char pil;
system("clear");
printf("Fungsi cetak di sini\n\n");
printf("Kembali ke menu awal?(y/n): ");
scanf(" %c", &pil);
if( pil == 'y' )
{
return 0;
} else {
return 1;
}
}
int cari()
{
char pil;
system("clear");
printf("algoritma pencarian di sini\n\n");
printf("Kembali ke menu awal?(y/n): ");
scanf(" %c", &pil);
if( pil == 'y' )
{
return 0;
} else {
return 1;
}
}
int input()
{
char pil;
system("clear");
printf("Proses input data\n\n");
printf("Kembali ke menu awal?(y/n): ");
scanf(" %c", &pil);
if( pil == 'y' )
{
return 0;
} else {
return 1;
}
} |
C | #include <stdio.h>
#define MAXLINE 1000
/* maximum input line length */
int getline2(char line[], int maxline);
void copy(char to[], char from[]);
int strlen2(char s[]);
void squeeze(char s[], int c);
int main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getline2(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("Maxima Cadena: %s", longest);
return 0;
}
/* getline: read a line into s, return length*/
int getline2(char s[],int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
/* strlen: return length of s */
int strlen2(char s[])
{
int i;
while (s[i] != '\0')
++i;
return i;
}
/* squeeze: delete all c from s */
void squeeze(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}
|
C | #include <mqueue.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "shared.h"
int i = 0;
int produce_item() {
printf("Produziu %d\n", i++);
return i;
}
void consume_item(int item) {
printf("Consumiu %d\n", item);
}
void receive(mqd_t mq, struct Message *message) {
int n = mq_receive(mq, (char *) message, sizeof(struct Message), NULL);
if (n == -1) {
perror("mq_receive failed\n");
exit(EXIT_FAILURE);
}
}
int extract_item(struct Message *message) {
return message->id;
}
void build_message(struct Message *message, int item) {
message->id = item;
}
void send(mqd_t mq, struct Message *message) {
int n = mq_send(mq, (char *) message, sizeof(struct Message), 0);
if (n == -1) {
perror("mq_send failed\n");
exit(EXIT_FAILURE);
}
} |
C | #include<stdio.h>
int esprimo(int) ;
int main()
{
int n, resultado;
printf("Ingresar el numero a chequear.\n");
scanf("%d",&n);
if (n==0)
printf("\n No es primo ");
else if (n==1)
printf("\n No es primo ");
else if (n==-1)
printf("\n No es primo ");
else
resultado = esprimo(n);
if ( resultado == 1 )
printf("%d Es primo.\n", n);
else
printf("%d No es primo.\n", n);
return 0;
}
int esprimo(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{ if ( a%c == 0 )
return 0; }
return 1;
} |
C | /****************************************************************************
* file: card.h *
* author: kyle isom <[email protected]> *
* *
* Definition and utility functions for a card in the solitaire cipher. *
* *
* it is released under an ISC / public domain dual-license; see any of the *
* header files or the file "LICENSE" (or COPYING) under the project root. *
****************************************************************************/
/****************************************************************************
* the ISC license: *
* Copyright (c) 2011 Kyle Isom <[email protected]> *
* *
* Permission to use, copy, modify, and distribute this software for any *
* purpose with or without fee is hereby granted, provided that the above *
* copyright notice and this permission notice appear in all copies. *
* *
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES *
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR *
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES *
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN *
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF *
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *
****************************************************************************
* you may choose to follow this license or public domain. my intent with *
* dual-licensing this code is to afford you, the end user, maximum freedom *
* with the software. if public domain affords you more freedom, use it. *
****************************************************************************/
#ifndef __SOLITAIRE_CARD_H
#define __SOLITAIRE_CARD_H
/*
* declarations for various data types
*/
enum SUITE {
INVALID_SUITE = -1,
SPADE = 1,
CLUB,
HEART,
DIAMOND,
FIRST,
SECOND
};
enum FACE {
INVALID_FACE = -1,
ACE = 1,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
JOKER
};
struct card_s {
int suite;
int face;
};
/*
* function declarations
*/
/* fill a char[3] with a string representation of a card */
void card_str(struct card_s, char *);
struct card_s card_read(char *);
int card_is_valid(struct card_s *);
int card_cmp(struct card_s *, struct card_s *);
int cards_eq(struct card_s *card1, struct card_s *card2);
#endif
|
C | #ifndef HANSHU_H
#define HANSHU_H
#include"graphm.h"
#include"string.h"
#include"strstream"
#include"global.h"
#include "qdebug.h"
int minVertex(Graphm *G,int *D) //返回图G中最小的点
{
int i, v=-1;
for(i = 0; i<G->n(); i++)
if(G->getMark(i) == UNVISITED){ v=i; break;} //找出图G中没有被访问的点
for(i++; i<G->n(); i++)
if((G->getMark(i) == UNVISITED) && (D[i]<D[v]))
v = i;
return v;
}
void Dijkstra(Graphm *G,int *D, int s)
{
int i,v,w;
for(i=0; i<G->n(); i++) //数组D初始化
{
if(i != s)
D[i] = INFINITY;
else
D[i] = 0;
}
for(int i=0;i<G->n();i++)
b[i]="";
for(i=0; i<G->n(); i++)
{
v = minVertex(G,D);
if(D[v] == INFINITY) //为了让开始的节点为s,这一步很重要
return;
G->setMark(v, VISTED);
for(w=G->first(v); w<G->n(); w = G->next(v,w)) //很巧妙
{
strstream val;
string val1;
if(D[w] > D[v] + G->weight(v, w))
{
D[w] = D[v] + G->weight(v, w);
val << v;
val >> val1;
b[w]+=val1; //只有D[]路径被修改了,表明这个节点
}
}
}
for(int j=0;j<G->n();j++)
{
strstream val;
string val1;
val << j;
val >> val1;
b[j]+=val1;
}
}
void inserts(int i,string va,int k) //递归实现修改路径的值,很巧妙
{
int val=va[0]-'0';
if(val != k)
{
inserts(val,b[val],k);
b[i].insert(0,b[val]);
}
else
return;
}
void xiugai(Graphm *G,int k,int *D)
{
for(int i=0;i<G->n();i++)
{
if(D[i] != INFINITY)
inserts(i,b[i],k);
}
}
void add(Graphm *G) //非常重要
{
for(int j=0;j<G->n();j++)
{
char a=j+'0';
b[j]+=a;
}
}
void compa(Graphm *G)
{
for(int j=0;j<G->n();j++)
{
for(int i=0;i<b[j].size()-1;i++)
{
if(b[j][i] == b[j][i+1])
{
b[j].erase(i+1,i+2);
}
}
}
}
#endif // HANSHU_H
/*
strstream val;
string val1;
val << j;
val >> val1;
b[j]+=val1; */
|
C | #include "shell.h"
/**
*_getline - to recibe what user type in stdin
*Return: a pointer to what user typed
*/
char *_getline()
{
size_t num_bytes = 1024;
ssize_t chars;
char *buffer;
buffer = malloc(sizeof(char) * 1024);
chars = getline(&buffer, &num_bytes, stdin);
if (chars == EOF)
{
if (isatty(STDIN_FILENO))
write(STDIN_FILENO, "\n", 1);
free(buffer);
exit(0);
}
buffer[chars - 1] = '\0';
return (buffer);
}
|
C | // Julia Tan
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct {
int acctNum[3]; // Account number
char acctName[3][100]; // Account name
float balance[3]; // Account balance
} Account;
void info(Account a, int client){ // prints current account info of client
printf("Account Name: %s\n", a.acctName[client]);
printf("Account number: %d\n", a.acctNum[client]);
printf("Current balance: USD %.2f\n\n", a.balance[client]);
}
void deposit(Account a, int client, float num){ // client = which account, num = money to deposit
printf("\nUSD %.2f added to account.\n\n", num);
printf("Previous balance: USD %.2f\n\n", a.balance[client]);
a.balance[client] += num; // adds number input to total balance
info(a, client); // print account info
}
void withdraw(Account a, int client, float num){ // cleint = which account, num = money to withdraw
if (a.balance[client]-num < 0){ // If
printf("\nError: insufficient funds to do this.\n\n");
}else {
printf("\nUSD%.2f withdrawn from account.\n", num);
printf("Previous balance: %.2f\n\n", a.balance[client]);
}
a.balance[client] -= num; // subtract from balance
info(a, client); // print account info
}
int main(){
Account acc;
int num; // selects account
int wd; // withdraw or deposit
float sum; // amount of money to withdraw/deposit
int inUse = 1; // if making a transaction, equal to 1
strcpy(acc.acctName[1], "Noel Park");
strcpy(acc.acctName[2], "Sabrina Martinez");
srand(time(0));
for (int x = 1; x != 3; x ++){ // generates random acct number and acct balance
acc.acctNum[x] = (rand()%1000000);
acc.balance[x] = (rand()%1000000);
}
info(acc, 1);
info(acc, 2);
while (inUse){
printf("\nWhich account would you like to manage? (1)Noel Park (2)Sabrina Martinez\n");
scanf("%d", &num);
printf("Would you like to (1)Withdraw or (2)Deposit?\n");
scanf("%d", &wd);
if (wd == 1){
printf("How much would you like to withdraw?\n");
scanf("%f", &sum);
withdraw(acc, num, sum);
}else if (wd == 2){
printf("How much would you like to deposit?\n");
scanf("%f", &sum);
deposit(acc, num, sum);
}
printf("\nWould you like to make another transaction? (1)Yes (0)No\n");
scanf("%d", &inUse);
}
return 0;
}
|
C | #include "stdafx.h"
#include "mem.h"
typedef struct memS_atom {
struct memS_atom* link;
int capacity;
int offset;
byte* p;
}memS_atom;
typedef struct ST {
int cb;
struct memS_atom* pl;
}ST;
#define INIT_CAPACITY_S 128
ZENGINE_API memS_t memS_create() {
memS_t p = (memS_t)malloc(sizeof(ST));
assert(p);
p->cb = sizeof(ST);
p->pl = (memS_atom*)malloc(sizeof(memS_atom) + INIT_CAPACITY_S);
assert(p->pl);
p->pl->link = null;
p->pl->capacity = INIT_CAPACITY_S;
p->pl->offset = 0;
p->pl->p = (byte*)(p->pl + 1);
return p;
}
ZENGINE_API void memS_destroy(memS_t t) {
struct memS_atom* pa;
struct memS_atom* pt;
assert(t);
assert(t->cb == sizeof(ST));
pa = t->pl;
while (pa) {
pt = pa->link;
free(pa);
pa = pt;
}
free(t);
t = null;
}
ZENGINE_API void* memS_alloc(memS_t t, int size) {
struct memS_atom* pa;
struct memS_atom* pn;
byte* pbr;
int newc;
assert(t);
assert(t->cb == sizeof(ST));
assert(size > 0);
pa = t->pl;
if (size <= pa->capacity - pa->offset) {
pbr = pa->p + pa->offset;
pa->offset += size;
return pbr;
}
else {
newc = (pa->capacity + size) * 2;
pn = (struct memS_atom*)malloc(newc + sizeof(memS_atom));
assert(pn);
pn->capacity = newc;
pn->offset = 0;
pn->p = (byte*)(pn + 1);
pn->link = pa;
t->pl = pn;
return memS_alloc(t, size);
}
} |
C | #include "pthread.h"
#include "winint.h"
#include <winsock2.h>
typedef struct _helperStruct
{
void *param;
ptRoutine fcn;
}helperStruct;
uint32_t WINAPI helper_thread(void* p)
{
helperStruct* hs = (helperStruct*)p;
hs->fcn(hs->param);
free(hs);
return 0;
}
int pthread_create(void** h, void* attr, ptRoutine fcn, void* p)
{
HANDLE hThread = 0;
uint32_t threadId = 0;
helperStruct* hs = (helperStruct*)malloc(sizeof(helperStruct));
if(!hs){
return -1;
}
hs->param = p;
hs->fcn = fcn;
hThread = CreateThread(NULL, NULL, helper_thread, (void*)hs, NULL, &threadId);
if( !hThread ) {
free(hs);
return -1;
} else {
*h = hThread;
return 0;
}
}
int pthread_mutex_lock(pthread_mutex_t* m){
EnterCriticalSection((LPCRITICAL_SECTION)(*m));
return 0;
}
int pthread_mutex_unlock(pthread_mutex_t* m){
LeaveCriticalSection((LPCRITICAL_SECTION)(*m));
return 0;
}
int pthread_mutex_destroy(pthread_mutex_t* m)
{
DeleteCriticalSection((LPCRITICAL_SECTION)(*m));
free(*m);
return 0;
}
int pthread_mutex_init(pthread_mutex_t* m, void* d)
{
*((LPCRITICAL_SECTION*)m) = (CRITICAL_SECTION*)malloc(sizeof(CRITICAL_SECTION));
InitializeCriticalSection((LPCRITICAL_SECTION)(*m));
return 0;
}
int pthread_cond_init(pthread_cond_t* c, void* d)
{
*c = CreateEventA(NULL, FALSE, FALSE, NULL);
return 0;
}
int pthread_cond_signal(pthread_cond_t* c)
{
SetEvent(*c);
return 0;
}
int pthread_cond_destroy(pthread_cond_t* c)
{
CloseHandle(*c);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
void wytnijzn(char *napis1, char *napis2)
{
int i=0;
int j=0;
int czyjest[256]={};
for(i = 0; i < 256; i++)
{
czyjest[i]=0;
}
for(i = 0; *(napis2+i)!= 0; i++)
*(czyjest+(int)(*(napis2+i))) = 1;
for(i = 0; *(napis1+i)!= 0; i++)
{
if (*(czyjest+(int)(*(napis1+i)))==0)
{
if(j<i)
*(napis1+j)=*(napis1+i);
j++;
}
}
*(napis1+j)=0;
}
int zawart(wchar_t napis1, wchar_t *napis2)
{
int i=0;
for(i=0; *(napis2+i)!= 0; i++)
if(*(napis2+i)== napis1)
return 1;
return 0;
}
void wytnijzn2(wchar_t *napis1, wchar_t *napis2)
{
int i=0;
int j=0;
for(i=0; *(napis1+i)!=0; i++)
{
if(zawart(*(napis1+i), napis2)==0)
{
if(j<i)
*(napis1+j)=*(napis1+i);
j++;
}
}
*(napis1+j) = 0;
}
int main()
{
char *napis1 = malloc(20*sizeof(char));
char *napis2 = malloc(20*sizeof(char));
scanf("%s", napis1);
scanf("%s", napis2);
wytnijzn(napis1, napis2);
printf("Po wycieciu : %s\n", napis1);
wchar_t *napis3 = malloc(20*sizeof(wchar_t));
wchar_t *napis4 = malloc(20*sizeof(wchar_t));
wscanf(L"%s", napis3);
wscanf(L"%s", napis4);
wytnijzn2(napis3, napis4);
wprintf(L"Po wycieciu : %s\n", napis3);
return 0;
}
|
C | #include <stdio.h>
#define SIZE 5
double diff_max_min(double[], int);
int main(void)
{
double arr[SIZE] = { 0.5,9.0,5.3,6.0,1.2 };
double diff;
diff = diff_max_min(arr, SIZE);
printf("The diff between max and min of array is %5.2lf.\n", diff);
return 0;
}
double diff_max_min(double arr[], int n)
{
double max = arr[0];
double min = arr[0];
int i;
for (i = 1; i < n; i++)
{
if (max < arr[i])
max = arr[i];
if (min > arr[i])
min = arr[i];
}
return max - min;
} |
C | /*
* @lc app=leetcode.cn id=901 lang=c
*
* [901] 股票价格跨度
*/
// @lc code=start
typedef struct Node_ {
int price;
int preContinueNum;
struct Node_ *next;
} Node;
typedef struct {
int num;
Node *top;
} StockSpanner;
StockSpanner* stockSpannerCreate() {
StockSpanner *stack = NULL;
stack = (StockSpanner*)calloc(1, sizeof(StockSpanner));
if (stack == NULL) {
return NULL;
}
return stack;
}
void StackPush(StockSpanner *stack, int price, int preContinueNum)
{
Node *node = NULL;
if (stack == NULL) {
return;
}
node = (Node*)malloc(sizeof(Node));
if (node == NULL) {
return;
}
node->price = price;
node->preContinueNum = preContinueNum;
node->next = NULL;
if (stack->num == 0) {
stack->top = node;
} else {
node->next = stack->top;
stack->top = node;
}
(stack->num)++;
return;
}
void StackPop(StockSpanner *stack)
{
Node *node = NULL;
if ((stack == NULL) || (stack->num == 0)) {
return;
}
node = stack->top;
stack->top = node->next;
(stack->num)--;
free(node);
return;
}
Node* StackTop(StockSpanner *stack)
{
if ((stack == NULL) || (stack->num == 0)) {
return 0;
}
return stack->top;
}
int StackEmpty(StockSpanner *stack)
{
return (stack->num == 0) ? 1 : 0;
}
int stockSpannerNext(StockSpanner* obj, int price) {
int i;
int contDayNum = 1;
int preContDayNum = 0;
Node *node = NULL;
node = StackTop(obj);
while ((!StackEmpty(obj)) && (node->price <= price)) {
contDayNum += (node->preContinueNum + 1);
preContDayNum += (node->preContinueNum + 1);
StackPop(obj);
node = StackTop(obj);
}
StackPush(obj, price, preContDayNum);
return contDayNum;
}
void stockSpannerFree(StockSpanner* obj) {
int num;
if (obj == NULL) {
return;
}
num = obj->num;
while (num--) {
StackPop(obj);
}
free(obj);
return;
}
/**
* Your StockSpanner struct will be instantiated and called as such:
* StockSpanner* obj = stockSpannerCreate();
* int param_1 = stockSpannerNext(obj, price);
* stockSpannerFree(obj);
*/
// @lc code=end
|
C | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "gameService.h"
#include "menu.h"
int AnChessStatus[15][15];
int turn;
int main(){
int number;
ui();
int nRow=0 ;
int nCol =0;
int turn=0;
scanf("%d",&number);
switch (number)
{
case 1:
ui1();
init();
do
{
getStatus(nRow, nCol);
printf("%d", AnChessStatus[1][1]);
printDraw();
if (isWin(nRow, nCol) == 0)
{
printf("------------Black Win---------------");
}
else if(isWin(nRow, nCol) == -1)
{
printf("------------Black Win---------------");
}
printf("%d", isWin(nRow, nCol));
} while (isWin(nRow,nCol)==1);
system("pause");
break;
case 2:
return 0;
case 3:
return 0;
case 4:
printf("The project is developed by Zhii Wang;");
system("pause");
break;
case 5:
printf("五子棋为两人对战游戏,玩家执黑先行,率先连成五子者胜\n");
case 0:
exit(0);
return 0;
default:
exit(0);
break;
}
return 0;
} |
C | #include<stdio.h>
int sort(int *a,int size)
{
int i,j,t;
for(i=1;i<size;i++)
{
for(j=i;j>0&&a[j]<a[j-1];j--)
{
t=a[j];
a[j]=a[j-1];
a[j-1]=t;
}
}
return 0;
}
int read(int *a)
{
int size,i;
printf("Size: ");
scanf("%d",&size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
return size;
}
int main()
{
int a[100];
int size = read(a);
int i;
sort(a,size);
printf("Sorted array:\n");
for(i=0;i<size;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
|
C | #ifndef REPRESENTATION_H
#define REPRESENTATION_H
// *****************************************************************************
// Symboles possibles pour ecrire un nombre.
// On n'aura jamais une base plus grande que la longueur de cette chaine.
// *****************************************************************************
static const char SYMBOLES [] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx";
static const int BASE_MAX = 60;
static const int BASE_MIN = 2;
// *****************************************************************************
// typedef struct Representation
//
// Contient tous les attributs relatifs a la reprensentation d'un nombre dans
// une base quelconque.
//
// Attributs :
// int* nombre :
// Le tableau contenant les digits du nombre. La plus grande puissance
// est la premiere.
// int taille :
// La taille du tableau contenant les digits du nombre
// int base :
// La base dans laquelle le nombre est ecrit.
//
// Exemple :
// {{1, 1, 1, 0, 1, 1}, 6, 2} est une representation de 11 1011 en binaire.
// {{3, 11}, 2, 16} est une representation de 3B en hexadecimal.
// {{5, 9}, 2, 10} est une representation de 59 en decimal.
// {{2, 18}, 2, 20} est une representation de 2J en vicesimal
//
// *****************************************************************************
typedef struct{
int* nombre;
int taille;
int base;
} Representation;
// *****************************************************************************
// Representation constructeur(int taille, int base)
//
// Fabrique une representation de taille taille en base base et initialise son
// tableau nombre avec la taille taille.
//
// Postcondition :
// nb->nombre doit etre libere avec un free
//
// INPUT :
// int taille:
// La taille du nombre a fabriquer
// long base :
// La base du nombre a fabriquer
//
// OUTPUT :
// Representation nb avec
// nb->base = base,
// nb->taille = taille
// nb->nombre = un tableau de longueur taille. Son contenu n'est pas
// initialise. Il peut etre nul, il peut etre autre chose. Seule
// sa taille est garantie.
//
// Exemples :
// constructeur(2, 16) = {{0,0}, 2, 16}
// constructeur(11, 2) = {{0,0,0,0,0,0,0,0,0,0,0}, 11, 2}
// constructeur(3, 16) = {{0,0,0}, 3, 16}
// constructeur(2, 8) = {{0,0}, 2, 8}
//
// *****************************************************************************
Representation constructeur(int taille, int base);
// *****************************************************************************
// Representation traduireEntree(char* chaine, int base)
//
// Prend une chaine de caracteres (chaine) qui represente un nombre dans la base
// base fabrique une represnetation nb. La fonction met les indices appropries
// dans nb.nombre. Si chaine comprend des symboles qui depassent la base base,
// un message d'erreur est affiche et le programme s'arrete. L'appeleur est
// responsable de liberer la memoire utilisee par nb.nombre.
//
// Cette fonction est utile si on veut lire un nombre dans une base autre que
// la base 10.
//
// INPUT :
// char* chaine :
// Une chaine de caractere contenant un nombre dans la base base.
// int base :
// La base dans laquelle est ecrite chaine.
//
// OUTPUT :
// Une reprensentation du nombre entre dans la meme base.
//
// Exemples :
// traduireEntree("FF1", 16) = ({15, 15, 1}, 3, 16)
// traduireEntree("10001", 2) = ({1, 0, 0, 0, 1}, 5, 2)
// traduireEntree("9", 8) = ERREUR 9 n'est pas un symbole dans la base 8.
//
// *****************************************************************************
Representation traduireEntree(char* chaine, int base);
// *****************************************************************************
// Representation decimalABase(int baseCible, long valeurSource)
//
// Fabrique une representation pour un nombre de valeur valeurSource et en base
// baseCible. L'appeleur est responsable de liberer la memoire utilisee par
// nb->nombre. la variable valeurSource doit etre une valeur en decimal.
//
// Préconditions :
// baseCible doit etre entre 2 et BASE_MAX
//
// Postcondition :
// nb->nombre doit etre libere avec un free
//
// INPUT :
// int baseCible :
// La base cible
// long valeurSource :
// La valeur en decimal qu'on doit traduire dans la base cible
//
// OUTPUT :
// Representation nb avec
// nb->base = baseCible,
// nb->taille = longueur du nombre et
// nb->nombre = un tableau dans le tas contenant la representation en
// base baseCible de valeurSource.
//
// Exemples :
// decimalABase(16, 10) = {{10}, 1, 16}
// decimalABase( 2, 1025) = {{1,0,0,0,0,0,0,0,0,0,1}, 11, 2}
// decimalABase(16, 1025) = {{4,0,1}, 3, 16}
// decimalABase(16, 255) = {{15,15}, 2, 16}
// decimalABase( 8, 25) = {{3,1}, 2, 8}
//
// *****************************************************************************
Representation decimalABase(int base, long valeur);
// *****************************************************************************
// long baseADecimal(Representation* nb)
//
// Fabrique une representation pour un nombre de valeur valeurSource et en base
// baseCible. la representation place son nombre dans le tas avec un
// malloc. L'appeleur est responsable de liberer la memoire utilisee. la
// variable valeurSource doit etre une valeur en decimal.
//
// Préconditions :
// baseCible doit etre entre BASE_MIN et BASE_MAX
//
// Postconditions :
// nb->nombre doit etre libere avec un free
//
// INPUT :
// int baseCible :
// La base cible
// long valeurSource :
// La valeur en decimal qu'on doit traduire dans la base cible
//
// OUTPUT :
// Representation nb avec
// nb->base = baseCible,
// nb->taille = longueur du nombre et
// nb->nombre = un tableau dans le tas contenant la representation en
// base baseCible de valeurSource.
//
// Exemples :
// baseADecimal({{10}, 1, 16}) = 16
// baseADecimal({{1,0,0,0,0,0,0,0,0,0,1}, 11, 2}) = 1025
// baseADecimal({{4,0,1}, 3, 16}) = 1025
// baseADecimal({{15,15}, 2, 16}) = 255
// baseADecimal({{3,1}, 2, 8}) = 25
//
// *****************************************************************************
long baseADecimal(Representation* nb);
#endif
|
C | #include<stdio.h>
void main()
{
int row ;
printf(" the number of row:5\n");
for(int i=1;i<=3;i--)
if
printf("*");
else
{
printf(" ");
}
printf("\n");
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int COMPARE_COUNT=0;
int Swap( long x[], long i, long j)
{
int tmp;
tmp = x[i];
x[i] = x[j];
x[j] = tmp;
return 0;
}
int Quick_Sort(long x[], long min, long max)
{
long i,j,p;
if(min>=max)return 1;
p = x[(min+max)/2];
i = min;
j = max;
while(i<=j)
{
while(x[i]<p){ i++; COMPARE_COUNT++;}
COMPARE_COUNT++;
while(x[j]>p){ j--; COMPARE_COUNT++;}
COMPARE_COUNT++;
if(i>=j) break;
Swap(x,i,j);
i++; j--;
}
Quick_Sort(x,min,i-1);
Quick_Sort(x,j+1,max);
return 0;
}
int main(int argc, char *argv[])
{
long *Data;
long size;
int i,j,n,seed;
FILE *fp;
char *filename;
if(argc != 2)
{
printf("Please Input like this.\n");
printf("./a.out 10000\n");
return 0;
}
if(argc <0){
printf("Please Input more than 0\n");
printf("\n");
return 0;
}
/* alocation */
char *ends;
size = strtol(argv[1], &ends,10);
Data = (long*)malloc(sizeof(long)* size);
if (Data == NULL) {
printf( "memory allocation error\n" );
exit(EXIT_FAILURE);
}
/* Make Data */
srand((unsigned int)time(NULL)); //Hiroshi seedの工夫
for(i=0;i<size;i++) Data[i]=rand()%size;
/*Write data before sorting*/
filename = "before_sorting_quickSort" ;
fp = fopen(filename, "w");
for(i=0;i<size;i++)
{
for(j=0; j<10 ; j++){
fprintf( fp, "%ld\n", Data[i] );
}
}
/* Sort Data */
COMPARE_COUNT=0;
clock_t start, end;
start = clock();
Quick_Sort(Data,0,size-1);
printf("=Quick Sort=\t\tComparing: %d\n" , COMPARE_COUNT);
end = clock();
printf("time: %f[sec]\n", (double)(end - start) / CLOCKS_PER_SEC);
/*Write data after sorting*/
filename = "after_sorting_quickSort" ;
fp = fopen(filename, "w");
for(i=0;i<size;i++)
{
for(j=0; j<10 ; j++){
fprintf( fp, "%ld\n", Data[i] );
}
}
/* free memory */
free(Data);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.