language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*
* hal_flash.c
*
* Created on: Nov 8, 2019
* Author: caijie
*/
#include "hal_flash.h"
#ifdef HAL_FLASH
#ifdef STM32F4
#if (BOARD_FLASH_SIZE == 512)
#define STM32_FLASH_NPAGES 8
static const uint32_t flash_memmap[STM32_FLASH_NPAGES] = {
KB(16), KB(16), KB(16), KB(16), KB(64),
KB(128), KB(128), KB(128)
};
#elif (BOARD_FLASH_SIZE == 1024)
#define STM32_FLASH_NPAGES 12
static const uint32_t flash_memmap[STM32_FLASH_NPAGES] = {
KB(16), KB(16), KB(16), KB(16), KB(64),
KB(128), KB(128), KB(128), KB(128), KB(128), KB(128), KB(128)
};
#elif (BOARD_FLASH_SIZE == 2048)
#define STM32_FLASH_NPAGES 24
static const uint32_t flash_memmap[STM32_FLASH_NPAGES] = {
KB(16), KB(16), KB(16), KB(16), KB(64),
KB(128), KB(128), KB(128), KB(128), KB(128), KB(128), KB(128),
KB(16), KB(16), KB(16), KB(16), KB(64),
KB(128), KB(128), KB(128), KB(128), KB(128), KB(128), KB(128)};
#endif
#endif
#ifdef STM32F7
#if (BOARD_FLASH_SIZE == 1024)
#define STM32_FLASH_NPAGES 8
static const uint32_t flash_memmap[STM32_FLASH_NPAGES] = {
KB(32), KB(32), KB(32), KB(32), KB(128), KB(256), KB(256), KB(256)
};
#elif (BOARD_FLASH_SIZE == 2048)
#define STM32_FLASH_NPAGES 12
static const uint32_t flash_memmap[STM32_FLASH_NPAGES] = {
KB(32), KB(32), KB(32), KB(32), KB(128), KB(256), KB(256), KB(256),
KB(256), KB(256), KB(256), KB(256) };
#endif
#endif
uint8_t flash_get_sector(uint32_t address)
{
#ifdef STM32F1
return ((address - STM32_FLASH_BASE) / 1024);
#else
uint32_t memmap = STM32_FLASH_BASE;
for(uint8_t sector = 0; sector < STM32_FLASH_NPAGES; sector++) {
memmap = flash_memmap[sector] + memmap;
if(address < memmap) {
return sector;
}
}
return STM32_FLASH_NPAGES - 1;
#endif
}
uint32_t flash_func_sector_size(uint8_t sector)
{
#ifdef STM32F1
return 1024U;
#else
return flash_memmap[sector];
#endif
}
uint32_t flash_func_sector_address(uint8_t sector)
{
#ifdef STM32F1
return (STM32_FLASH_BASE + sector * 1024);
#else
uint32_t adder = 0;
for(uint8_t i = 0; i < sector; i++) {
adder += flash_memmap[i];
}
return adder + STM32_FLASH_BASE;
#endif
}
int flash_sector_erase(uint32_t sector, uint32_t num)
{
FLASH_EraseInitTypeDef flash_erase = {0};
uint32_t error = 0;
#ifdef STM32F1
flash_erase.TypeErase = FLASH_TYPEERASE_PAGES;
flash_erase.NbPages = num;
flash_erase.PageAddress = flash_func_sector_address(sector);
#else
flash_erase.TypeErase = FLASH_TYPEERASE_SECTORS;
flash_erase.Sector = sector;
flash_erase.NbSectors = num;
flash_erase.VoltageRange = FLASH_VOLTAGE_RANGE_3;
#endif
flash_erase.Banks = (num == 1)?(0):(FLASH_BANK_1);
if((HAL_FLASHEx_Erase(&flash_erase, &error) != HAL_OK) && (error != 0xFFFFFFFFU)) {
printf("HAL_FLASHEx_Erase err \r\n");
return 0;
}
if(FLASH_WaitForLastOperation(FLASH_WAITE_TIME) != HAL_OK) {//ȴϴβ
printf("FLASH_WaitForLastOperation time out \r\n");
return 0;
}
return 1;
}
uint8_t flash_read_byte(uint32_t address)
{
return *(volatile uint8_t *)address;
}
uint32_t flash_read_word(uint32_t address)
{
return *(volatile uint32_t *)address;
}
void flash_read_array_byte(uint32_t address, uint8_t *buffer, uint32_t length)
{
for(uint32_t i = 0; i < length; i++) {
buffer[i] = flash_read_byte(address);
address++;
}
}
void flash_read_array_word(uint32_t address, uint32_t *buffer, uint32_t length)
{
for(uint32_t i = 0; i < length; i++) {
buffer[i] = flash_read_word(address);
address += 4;
}
}
int flash_write_array_byte(uint32_t address, uint8_t *buffer, uint32_t length)
{
uint32_t addrx = address;
uint32_t endaddr = address + length;
#ifdef STM32F1
uint16_t temp = 0;
uint32_t type_program = FLASH_TYPEPROGRAM_HALFWORD;
#else
uint32_t type_program = FLASH_TYPEPROGRAM_BYTE;
#endif
if((address < STM32_FLASH_BASE) || (address % 4) || (endaddr >= 0x1FFF0000)) {
return -1;
}
HAL_FLASH_Unlock();
while(addrx < endaddr) {
if(flash_read_word(addrx) != 0xFFFFFFFF) {
if(!flash_sector_erase(flash_get_sector(addrx), 1)) {
HAL_FLASH_Lock();
return 0;
}
}
else {
addrx += 4;
}
}
addrx = address;
while(addrx < endaddr) {
#ifdef STM32F1
if((length % 2 == 1) && (addrx == endaddr -1)){
temp = 0xFF << 8 | (*buffer);
}
else{
temp = *(uint16_t*)buffer;
}
if(HAL_FLASH_Program(type_program, addrx, temp) != HAL_OK) {
HAL_FLASH_Lock();
return 0;
}
#else
if(HAL_FLASH_Program(type_program, addrx, *buffer) != HAL_OK) {
HAL_FLASH_Lock();
return 0;
}
#endif
#ifdef STM32F1
addrx += 2;
buffer += 2;
#else
addrx++;
buffer++;
#endif
}
/* Locks the FLASH control register access */
HAL_FLASH_Lock();
return 1;
}
int flash_write_array_word(uint32_t address, uint32_t *buffer, uint32_t length)
{
#ifdef STM32F1
return flash_write_array_byte(address, (uint8_t*)buffer, length * 2);
#else
return flash_write_array_byte(address, (uint8_t*)buffer, length * 4);
#endif
}
#if defined(USE_UBOOT) || defined(USE_USER_PARAMS)
struct flash_param flash_params = {0};
void flash_read_param(struct flash_param *param)
{
if(param == NULL)
param = &flash_params;
flash_read_array(ADDR_FLASH_PARAM, (uint8_t *)param, sizeof(struct flash_param));
}
int flash_write_param(struct flash_param *param)
{
if(param == NULL)
param = &flash_params;
return flash_write_array(ADDR_FLASH_PARAM, (uint8_t *)param, sizeof(struct flash_param));
}
#endif
#endif
|
C
|
#define BOUND 7
int kappa;
int input,output;
#include <assert.h>
#include <math.h>
#include <stdlib.h>
int inputs[] = {2,5,3,1,4};
int calculate_output(int);
int calculate_outputm1(int);
int calculate_outputm2(int);
int calculate_outputm3(int);
int calculate_outputm4(int);
int calculate_outputm5(int);
int calculate_outputm6(int);
int calculate_outputm7(int);
int calculate_outputm8(int);
int calculate_outputm9(int);
int calculate_outputm10(int);
int calculate_outputm11(int);
int calculate_outputm12(int);
int calculate_outputm13(int);
int calculate_outputm14(int);
int calculate_outputm15(int);
int calculate_outputm16(int);
int calculate_outputm17(int);
int calculate_outputm18(int);
int calculate_outputm19(int);
int calculate_outputm20(int);
int a167 = 33;
int a52 = 9;
int a166 = 33;
int a176 = 7;
int a175 = 6;
int cf = 1;
int a62 = 32;
int calculate_outputm1(int input) {
if(((( cf==1 && a166 == 33) && (input == 3)) && a176 == 6)) {
cf = 0;
a166 = 36 ;
a62 = 33 ;
//printf("%d\n", 21);
}
if((a166 == 33 && (((input == 2) && cf==1 ) && a176 == 6))) {
cf = 0;
//printf("%d\n", 19);
}
if(((( cf==1 && a166 == 33) && (input == 4)) && a176 == 6)) {
cf = 0;
a166 = 32 ;
a52 = 9;
//printf("%d\n", 26);
}
}
int calculate_outputm2(int input) {
if((a166 == 33 && (( cf==1 && (input == 4)) && a176 == 7))) {
cf = 0;
a166 = 36 ;
a62 = 33 ;
//printf("%d\n", 21);
}
if((a176 == 7 && ((input == 3) && (a166 == 33 && cf==1 )))) {
cf = 0;
a176 = 11;
//printf("%d\n", 26);
}
}
int calculate_outputm3(int input) {
if(((((input == 5) && cf==1 ) && a166 == 33) && a176 == 8)) {
cf = 0;
a166 = 35 ;
a175 = 6;
//printf("%d\n", 19);
}
if((a166 == 33 && (( cf==1 && (input == 2)) && a176 == 8))) {
cf = 0;
a166 = 36 ;
a62 = 32 ;
//printf("%d\n", 19);
}
if(((a176 == 8 && ( cf==1 && (input == 4))) && a166 == 33)) {
cf = 0;
a166 = 36 ;
a62 = 33 ;
//printf("%d\n", 26);
}
}
int calculate_outputm4(int input) {
if(((input == 1) && ((a166 == 33 && cf==1 ) && a176 == 10))) {
cf = 0;
a176 = 12;
//printf("%d\n", 25);
}
}
int calculate_outputm5(int input) {
if((a176 == 11 && ((input == 5) && (a166 == 33 && cf==1 )))) {
cf = 0;
a166 = 34 ;
a167 = 32 ;
//printf("%d\n", 21);
}
if((((input == 2) && ( cf==1 && a176 == 11)) && a166 == 33)) {
cf = 0;
a176 = 10;
//printf("%d\n", 23);
}
if(((a166 == 33 && ((input == 1) && cf==1 )) && a176 == 11)) {
cf = 0;
a166 = 35 ;
a175 = 8;
//printf("%d\n", 25);
}
}
int calculate_outputm6(int input) {
if((a176 == 12 && ((a166 == 33 && cf==1 ) && (input == 4)))) {
cf = 0;
//printf("%d\n", 19);
}
if(((a176 == 12 && ((input == 2) && cf==1 )) && a166 == 33)) {
cf = 0;
a166 = 36 ;
a62 = 32 ;
//printf("%d\n", 21);
}
if((a176 == 12 && (a166 == 33 && ((input == 3) && cf==1 )))) {
cf = 0;
a176 = 10;
//printf("%d\n", 23);
}
}
int calculate_outputm7(int input) {
if((a52 == 5 && ((input == 3) && (a166 == 32 && cf==1 )))) {
cf = 0;
a166 = 36 ;
a62 = 32 ;
//printf("%d\n", 19);
}
}
int calculate_outputm8(int input) {
if(((input == 4) && ((a166 == 32 && cf==1 ) && a52 == 7))) {
cf = 0;
//printf("%d\n", 20);
}
if(((a52 == 7 && (a166 == 32 && cf==1 )) && (input == 5))) {
cf = 0;
a166 = 35 ;
a175 = 8;
//printf("%d\n", 21);
}
}
int calculate_outputm9(int input) {
if((a166 == 32 && (((input == 4) && cf==1 ) && a52 == 8))) {
cf = 0;
a52 = 9;
//printf("%d\n", 25);
}
}
int calculate_outputm10(int input) {
if((((input == 3) && (a52 == 9 && cf==1 )) && a166 == 32)) {
cf = 0;
//printf("%d\n", 25);
}
if((a52 == 9 && (((input == 2) && cf==1 ) && a166 == 32))) {
cf = 0;
//printf("%d\n", 25);
}
}
int calculate_outputm11(int input) {
if(((input == 1) && (a167 == 33 && (a166 == 34 && cf==1 )))) {
cf = 0;
a166 = 36 ;
a62 = 33 ;
//printf("%d\n", 25);
}
if(((( cf==1 && a167 == 33) && (input == 5)) && a166 == 34)) {
cf = 0;
a166 = 36 ;
a62 = 35 ;
//printf("%d\n", 25);
}
}
int calculate_outputm12(int input) {
if(((( cf==1 && a167 == 32) && (input == 4)) && a166 == 34)) {
cf = 0;
a167 = 35 ;
//printf("%d\n", 23);
}
if(((( cf==1 && (input == 1)) && a167 == 32) && a166 == 34)) {
cf = 0;
a166 = 32 ;
a52 = 5;
//printf("%d\n", 19);
}
if((((input == 5) && ( cf==1 && a167 == 32)) && a166 == 34)) {
cf = 0;
a167 = 34 ;
//printf("%d\n", 21);
}
}
int calculate_outputm13(int input) {
if(((a167 == 34 && ( cf==1 && (input == 1))) && a166 == 34)) {
cf = 0;
a166 = 32 ;
a52 = 9;
//printf("%d\n", 20);
}
if((a166 == 34 && (((input == 4) && cf==1 ) && a167 == 34))) {
cf = 0;
a166 = 33 ;
a176 = 11;
//printf("%d\n", 21);
}
}
int calculate_outputm14(int input) {
if((a166 == 34 && ((input == 5) && (a167 == 35 && cf==1 )))) {
cf = 0;
a167 = 32 ;
//printf("%d\n", 25);
}
if((((a167 == 35 && cf==1 ) && a166 == 34) && (input == 3))) {
cf = 0;
a166 = 36 ;
a62 = 32 ;
//printf("%d\n", 20);
}
if(((input == 2) && (a166 == 34 && ( cf==1 && a167 == 35)))) {
cf = 0;
a166 = 36 ;
a62 = 32 ;
//printf("%d\n", 25);
}
}
int calculate_outputm15(int input) {
if(((((input == 1) && cf==1 ) && a166 == 35) && a175 == 4)) {
cf = 0;
a166 = 33 ;
a176 = 11;
//printf("%d\n", 21);
}
if((a175 == 4 && ((a166 == 35 && cf==1 ) && (input == 2)))) {
cf = 0;
a175 = 8;
//printf("%d\n", 21);
}
}
int calculate_outputm16(int input) {
if(((( cf==1 && a175 == 6) && (input == 2)) && a166 == 35)) {
cf = 0;
a166 = 33 ;
a176 = 8;
//printf("%d\n", 25);
}
if(((input == 1) && ((a166 == 35 && cf==1 ) && a175 == 6))) {
cf = 0;
a166 = 33 ;
a176 = 6;
//printf("%d\n", 25);
}
}
int calculate_outputm17(int input) {
if((a166 == 35 && (((input == 5) && cf==1 ) && a175 == 8))) {
cf = 0;
a166 = 32 ;
a52 = 7;
//printf("%d\n", 26);
}
if((a166 == 35 && (( cf==1 && (input == 3)) && a175 == 8))) {
cf = 0;
a175 = 4;
//printf("%d\n", 19);
}
}
int calculate_outputm18(int input) {
if((a166 == 36 && (( cf==1 && (input == 1)) && a62 == 33))) {
cf = 0;
a62 = 35 ;
//printf("%d\n", 21);
}
if(((a166 == 36 && ( cf==1 && a62 == 33)) && (input == 3))) {
cf = 0;
a166 = 35 ;
a175 = 6;
//printf("%d\n", 20);
}
if(((a62 == 33 && ( cf==1 && (input == 4))) && a166 == 36)) {
cf = 0;
a166 = 32 ;
a52 = 8;
//printf("%d\n", 19);
}
}
int calculate_outputm19(int input) {
if(((a166 == 36 && (a62 == 32 && cf==1 )) && (input == 3))) {
cf = 0;
a62 = 33 ;
//printf("%d\n", 21);
}
if(((input == 5) && (a62 == 32 && (a166 == 36 && cf==1 )))) {
cf = 0;
//printf("%d\n", 25);
}
if((((a166 == 36 && cf==1 ) && a62 == 32) && (input == 1))) {
cf = 0;
//printf("%d\n", 25);
}
}
int calculate_outputm20(int input) {
if((((input == 3) && (a166 == 36 && cf==1 )) && a62 == 35)) {
cf = 0;
a62 = 32 ;
//printf("%d\n", 25);
}
if((((input == 1) && ( cf==1 && a166 == 36)) && a62 == 35)) {
cf = 0;
a166 = 34 ;
a167 = 33 ;
//printf("%d\n", 23);
}
}
int calculate_output(int input) {
cf = 1;
if((a166 == 33 && cf==1 )) {
if((a176 == 6 && cf==1 )) {
calculate_outputm1(input);
}
if(( cf==1 && a176 == 7)) {
calculate_outputm2(input);
}
if((a176 == 8 && cf==1 )) {
calculate_outputm3(input);
}
if(( cf==1 && a176 == 10)) {
calculate_outputm4(input);
}
if((a176 == 11 && cf==1 )) {
calculate_outputm5(input);
}
if((a176 == 12 && cf==1 )) {
calculate_outputm6(input);
}
}
if((a166 == 32 && cf==1 )) {
if((a52 == 5 && cf==1 )) {
calculate_outputm7(input);
}
if(( cf==1 && a52 == 7)) {
calculate_outputm8(input);
}
if(( cf==1 && a52 == 8)) {
calculate_outputm9(input);
}
if(( cf==1 && a52 == 9)) {
calculate_outputm10(input);
}
}
if((a166 == 34 && cf==1 )) {
if(( cf==1 && a167 == 33)) {
calculate_outputm11(input);
}
if((a167 == 32 && cf==1 )) {
calculate_outputm12(input);
}
if((a167 == 34 && cf==1 )) {
calculate_outputm13(input);
}
if(( cf==1 && a167 == 35)) {
calculate_outputm14(input);
}
}
if(( cf==1 && a166 == 35)) {
if(( cf==1 && a175 == 4)) {
calculate_outputm15(input);
}
if(( cf==1 && a175 == 6)) {
calculate_outputm16(input);
}
if(( cf==1 && a175 == 8)) {
calculate_outputm17(input);
}
}
if((a166 == 36 && cf==1 )) {
if(( cf==1 && a62 == 33)) {
calculate_outputm18(input);
}
if((a62 == 32 && cf==1 )) {
calculate_outputm19(input);
}
if(( cf==1 && a62 == 35)) {
calculate_outputm20(input);
}
}
if( cf==1 )
{
//printf(stderr, "Invalid input: %d\n", input);
}
}
int main()
{
kappa = 0;
// main i/o-loop
int symb;
for (int FLAG=0;FLAG<BOUND;FLAG++)
{
scanf("%d", &symb);
// operate eca engine
// read input
// operate eca engine
if((symb != 2) && (symb != 5) && (symb != 3) && (symb != 1) && (symb != 4))
return -2;
calculate_output(symb);
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <windows.h>
void Check(int arr[], int len){
int i = 0;
int tmp = 0;
int k = 0;
int s = 0;
//ֻһֵĽtmp
for (i = 0; i < len; i++){
tmp = tmp^arr[i];
}
//ҳĵһΪ1λcount
int count = 0;
for (i =31; i >= 0; i--){
if((tmp >> i) &1){
count = i;
}
}
//ֳ飬ÿֻһһε
for (i = 0; i < len; i++){
if ((arr[i] >> count )& 1){
k = k^arr[i];
}
else{
s = s^arr[i];
}
}
//ֱҳֻһεִӡ
printf("%d\n", k);
printf("%d\n", s);
}
int main(){
int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3 };
int len = sizeof(arr) / sizeof(arr[0]);
Check(arr,len);
system("pause");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* freeanderrors.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aait-ihi <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/23 00:14:09 by aait-ihi #+# #+# */
/* Updated: 2019/11/23 00:17:22 by aait-ihi ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void ft_lstonedel(t_list **to_del)
{
t_list *tmp;
if (to_del && *to_del)
{
tmp = *to_del;
*to_del = tmp->next;
free(tmp->content);
free(tmp);
}
}
void freecontent(void *content, size_t contentsize)
{
ft_bzero(content, contentsize);
free(content);
}
void freetab (char **tab)
{
int i;
i = 0;
while (tab[i])
{
free(tab[i]);
i++;
}
free(tab);
tab = NULL;
}
void ft_print_error(char *str, int er, char c)
{
if (er < 8)
{
ft_putstr(str);
ft_putstr(": ");
}
er == ERR_CMDNTFD ? ft_putendl("Command not found.") : 0;
er == ERR_PRMDND ? ft_putendl("Permission denied.") : 0;
er == ERR_MNARGS ? ft_putendl("Too many arguments.") : 0;
er == ERR_FWARGS ? ft_putendl("Too few arguments.") : 0;
er == ERR_ALFA ? ft_putendl("Variable name must contain alphanum chars.") : 0;
er == ERR_FSTLTR ? ft_putendl("Variable name must begin with a letter.") : 0;
er == ERR_NTFOUND ? ft_putendl("No such file or directory.") : 0;
er == ERR_UNMATCHED ? ft_putstr("Unmatched ") : 0;
er == ERR_UKNUSR ? ft_putstr("Unknown user: ") : 0;
er == ERR_NOT_DIR ? ft_putendl("Not a directory") : 0;
if (er >= 8)
{
er == ERR_UNMATCHED ? ft_putchar(c) : 0;
er == ERR_UKNUSR ? ft_putstr(str) : 0;
ft_putendl(".");
}
}
|
C
|
#include <stdio.h>
#define BR_ELEMENTI 100
void pecati_niza(int *a, int m);
void zameni(int *a, int *b);
void modificiraj(int a[], int m);
int main() {
int a[BR_ELEMENTI], i, m;
printf("Vnesete broj na elementi M:");
scanf("%d", &m);
printf("\nVnesete ja nizata:\n");
for (i=0;i<m;i++) {
printf("a[%d]=", i);
scanf("%d", &a[i]);
}
printf("Nemodificiranata niza e:\n");
pecati_niza(a,m);
modificiraj(a,m);
printf("\nModificiranata niza e:\n");
pecati_niza(a,m);
return 0;
}
void pecati_niza(int *a, int m) {
int i=0;
while(m>i)
printf("%d ", *(a+i++));
printf("\n");
}
void zameni(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void modificiraj(int a[], int m) {
int i=0;
while (m>i) {
if (a[i]%2 != 0 && a[i+1]%2 != 0) { zameni(a+i, a+i+1); i++; }
i++;
}
}
|
C
|
#include <stdio.h>
#include <time.h>
#define N 1E7
#define d 1E-7
#define d2 1E-14
int main (int argc, char* argv[])
{
clock_t begin = clock(), end;
double pi=0.0, result=0.0,x2=0.0;
int i=0;
for (i=0; i<N; i+=1)
{
x2=d2*i*i;
result+=1.0/(1.0+x2);
}
pi=4*d*result;
end = clock();
printf("PI = %lf\t Time = %lf\n", pi, ((double)(end-begin))/CLOCKS_PER_SEC);
return 0;
}
|
C
|
#include <stdio.h>
struct point {
int x;
int y;
};
struct rect {
struct point pt1;
struct point pt2;
};
struct point makepoint(int x, int y)
{
struct point temp;
temp.x = x;
temp.y = y;
return temp;
}
struct point addpoint(struct point p1, struct point p2)
{
p1.x += p2.x;
p1.y += p2.y;
return p1;
}
main()
{
struct rect screen;
struct point middle;
screen.pt1 = makepoint(0, 0);
screen.pt2 = makepoint(100, 100);
middle = makepoint((screen.pt1.x + screen.pt2.x) / 2,
(screen.pt1.y + screen.pt2.y) / 2);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
/*
struct Person {
int code;
char name[255];
int age;
char address[255];
};*/
struct Person {
int code;
char *name; // 8 b
int age;
char *address; // 8 b
};
struct Person *funcao() {
// ...
}
int main(int argc, char *argv[]) {
// 1.a declaracao
struct Person p; // stack (4+255+4+255)
// 2.a declaracao
struct Person p; // stack (4+8+4+8)
struct Person *p; // stack (8 bytes)
int p[20]; // 20 * 4 bytes na Stack
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
double sqrt_iter(int n){
int i;
double s;
if(n % 2 == 0) n--;
s = 0;
for(i = n; i >= 1; i -= 2){
s = sqrt(s + i);
}
return s;
}
double sqrt_rek(int i, int n){
if(n % 2 == 0) n--;
if(n == i) return sqrt(i);
return sqrt(i + sqrt_rek(i + 2, n));
}
main(){
int n;
printf("Unesite broj: ");
scanf("%d", &n);
printf("%lf\n", sqrt_iter(n));
printf("%lf\n", sqrt_rek(1, n));
//printf("rek = %lf\niter = %lf\n", sqrt_rek(n), sqrt_iter(n));
}
|
C
|
#include "lpc17xx.h"
#include "led.h"
#include <math.h>
/* Ex1 */
void led4and11_On(void) {
LPC_GPIO2->FIOSET |= 0x00000081;
};
/* Ex 2 */
void voidled4_Off(void) {
LPC_GPIO2->FIOCLR |= 0x00000080;
};
/* Ex 3 */
void ledEvenOn_OddOf(void) {
/*
* In order to avoid modifications on other PINs, we use FIOMASK
* with 0s at the interested bits that must change. Then we use
* FIOMASK in WRITE mode to change the PINs.
*/
LPC_GPIO2->FIOMASK |= 0xFFFFFF00; // Ensure that all initial PINs are on 1
LPC_GPIO2->FIOMASK &= 0xFFFFFF00; // Ensure that the 8 final bits are on 0
LPC_GPIO2->FIOPIN = 0x000000AA; // Set every odd PIN in ON 1010 1010
};
/* Ex 4 */
void LED_On(unsigned int num) {
if(num > 7)
return;
else
LPC_GPIO2->FIOSET |= 0x00000080 >> num;
}
/* Ex 5 */
void LED_Off(unsigned int num) {
if(num > 7)
return;
else
LPC_GPIO2->FIOCLR |= 0x00000080 >> num;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BLOCK_SIZE 512
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
FILE *inptr = fopen(argv[1], "r");
if (inptr == NULL)
{
fprintf(stderr, " Could not open %s.\n", argv[1]);
return 1;
}
char filename[8];
int countRecovered = 0;
FILE *output = NULL;
BYTE buffer[BLOCK_SIZE];
//Read blocks of 512 BYTES until end of file
while (fread(&buffer, sizeof(BYTE), BLOCK_SIZE, inptr))
{
//IF is the start of a new JPEG
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] >= 0xe0 && buffer[3] <= 0xef)
{
// If there is an open file close it to star writing a new one
if (output != NULL)
{
fclose(output);
}
//Get the name of the file
sprintf(filename, "%03i.jpg", countRecovered);
//Open output file
output = fopen(filename, "w");
//Add one to countRecovered so the file names increase by one
countRecovered ++;
// If output is not NULL the write the block in it
if (output != NULL)
{
fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, output);
}
}
else
{
//If it is not a new JPEG and there is an output file then write the block in it
if (output != NULL)
{
fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, output);
}
}
}
//Clos both files
fclose(output);
fclose(inptr);
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int i,T,j;
char s[1001];
scanf("%d",&T);
while(T--)
{
scanf(" %[^\n]",s);
int count[26]={0};
for(j=0; j<strlen(s); j++)
{
if(s[j]>='A' && s[j]<='Z')
{
count[s[j]-'A']++;
}
}
for(j=0; j<26; j++)
{
if(count[j]!=0)
{
printf("%d\n",count[j]);
}
}
printf("\n");
}
return 0;
}
|
C
|
//#include <stdio.h>
//
//int main()
//{
// long long bitmask = 0;
// int input;
// int num_diff_r = 0;
// for (int i = 0; i < 10; ++i)
// {
// scanf("%d", &input);
// if ((bitmask & (long long)1 << (input % 42)) == 0)
// {
// bitmask |= (long long)1 << (input % 42);
// num_diff_r++;
// }
// }
//
// printf("%d\n", num_diff_r);
// return 0;
//}
|
C
|
#include "ElemSN.h"
void InversePrint(ElemSN *h)
{
ElemSN *p = NULL, *pend = NULL;
while(pend - h)
{
for ( p = h; p->next - pend; p = p->next);
printf("%d\t", p->data);
pend = p;
}
}
int main()
{
ElemSN *head = NULL;
head = CreateLink1(a);
PrintLink(head);
InversePrint(head);
return 0;
}
|
C
|
#include "game.h"
/**
* @file game.c
* @brief The main of the game
* @author Aymen Benabderrahmane
* @version 1.0
* @date 6 janvier 2020
*/
int main(){
int player = 0;
struct matrix_t mat;
/* Matrix allocation */
mat = alloc(6, 7);
init_matrix(&mat);
printf("===== Bienvenue dans notre magnifique jeu Connect 4======\n");
while(mat.ncol>0)
{
display_matrix(mat);
player =(player%2)+1;
play(mat, player);
}
printf("Le joueur %d a gagné", player);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
// Given two strings, determine if the first is a permutation of the second
int str_is_permutation(char *first_str, char *second_str)
{
if (strlen(first_str) != strlen(second_str)) {
printf("Not a permutation");
return 1;
};
int ascii[255] = { 0 };
// Set occurances of each char in first string
for (int i = 0; i < strlen(first_str); i++) {
int first_str_atoi = (int)first_str[i];
ascii[first_str_atoi] = ascii[first_str_atoi] + 1;
}
// Do opposite for second string
for (int i = 0; i < strlen(second_str); i++) {
int second_str_atoi = (int)second_str[i];
ascii[second_str_atoi] = ascii[second_str_atoi] - 1;
}
// Ensure net result is equal
for (int i = 0; i < strlen(first_str); i++) {
int first_str_atoi = (int)first_str[i];
if (ascii[first_str_atoi] != 0) {
printf("Not a permutation");
return 1;
}
}
printf("Permutation");
return 0;
}
int main(int argc, char *argv[])
{
return str_is_permutation(argv[1], argv[2]);
}
|
C
|
void Del_x(LinkList L,int x){
LNode *p; //p指向待删除结点
if(L==NULL) //递归出口
return ;
if(L->data==x){ //若L所指的结点的值为x
p=L; //删除*L,并让L指向下一个结点。
p=L->next;
free(p);
Del_x(L,x); //递归调用
}
else //若L所指的结点值不为x
Del_x(L->next,x); //递归调用
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* semicolon.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hmiso <hmiso@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/25 12:32:57 by hmiso #+# #+# */
/* Updated: 2020/11/29 20:28:29 by hmiso ### ########.fr */
/* */
/* ************************************************************************** */
#include "../minishell.h"
static void init_semic(t_semic *semic)
{
semic->i = 0;
semic->flag = 0;
semic->count = 0;
}
static void semicolon_res(char *line, t_semic *semic)
{
while (line[semic->i] != '\0')
{
if ((line[semic->i] == '\'' || line[semic->i] == '"')
&& semic->flag == 0 && line[semic->i + 1] != '\0')
{
semic->flag = 1;
semic->i++;
}
else if ((line[semic->i] == '\'' || line[semic->i] == '"')
&& semic->flag == 1 && line[semic->i + 1] != '\0')
{
semic->flag = 0;
semic->i++;
}
else if (semic->flag == 0 && line[semic->i] == ';')
{
semic->count++;
semic->i++;
}
else
semic->i++;
}
}
static void semicolon_res_2(char *line, t_semic *semic)
{
while (line[semic->i] != '\0')
{
if ((line[semic->i] == '\'' || line[semic->i] == '"')
&& semic->flag == 0)
semic->flag = 1;
else if ((line[semic->i] == '\'' || line[semic->i] == '"')
&& semic->flag == 1)
semic->flag = 0;
if (semic->flag == 0 && line[semic->i] == ';')
{
semic->argv[semic->count] = ft_substr(line, 0, semic->i);
line = &line[semic->i + 1];
semic->count++;
semic->i = 0;
continue ;
}
if (line[semic->i] != '\0' && line[semic->i + 1] == '\0')
{
semic->argv[semic->count] = ft_substr(line, 0, semic->i + 1);
semic->count++;
}
semic->i++;
}
}
char **semicolon(char *line)
{
t_semic semic;
init_semic(&semic);
semicolon_res(line, &semic);
semic.argv = malloc(sizeof(char*) * (semic.count + 2));
semic.i = 0;
semic.count = 0;
semic.flag = 0;
semicolon_res_2(line, &semic);
semic.argv[semic.count] = NULL;
semic.count = 0;
return (semic.argv);
}
|
C
|
/*
* =======================================================================================
*
* Filename: ip.c
* Description: IP handling
* Compiler: gcc
* Author: Simon L. J. Robin | https://sljrobin.org
* Created: 2015-04-30 15:28:41
* Modified: 2016-02-13 13:40:59
*
* =======================================================================================
*/
#include <arpa/inet.h>
#include <pcap.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "../utils/clrprnt.h"
#include "eth.h"
#include "ip.h"
/**
* rosn_prots_ipv4_getprot()
*
* Get IPv4 protocol
* pkt: the packet
* Return IPv4 protocol
*/
uint8_t rosn_prots_ipv4_getprot(const u_char *pkt)
{
struct rosn_ipv4hdr *ipv4hdr; /* IPv4 Header */
uint8_t ipprot; /* IPv4 Protocol */
ipv4hdr = (struct rosn_ipv4hdr *)(pkt + sizeof(struct rosn_ethhdr)); /* Pointing to the IPv4 Header */
ipprot = ipv4hdr->prot; /* Getting the protocol */
return ipprot;
}
/**
* rosn_prots_ipv4_handle()
*
* Handle IPv4
* pkt: the packet
* pktlen: packet length
*/
void rosn_prots_ipv4_handle(const u_char *pkt, uint32_t pktlen)
{
char *addrdst = NULL; /* Destination Address */
char *addrsrc = NULL; /* Source Address */
char buf_addrdst[INET_ADDRSTRLEN] = {0}; /* Buffer for the Destination Address */
char buf_addrsrc[INET_ADDRSTRLEN] = {0}; /* Buffer for the Source Address */
struct rosn_ipv4hdr *ipv4hdr; /* IPv4 Header */
/* Printers */
rosn_clrset ptipv4;
rosn_clrset ptipv4_addrdst;
rosn_clrset ptipv4_addrsrc;
rosn_clrset ptipv4_csum;
rosn_clrset ptipv4_foff;
rosn_clrset ptipv4_hlen;
rosn_clrset ptipv4_id;
rosn_clrset ptipv4_prot;
rosn_clrset ptipv4_tlen;
rosn_clrset ptipv4_tos;
rosn_clrset ptipv4_ttl;
rosn_clrset ptipv4_v;
rosn_clrset ptsep;
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_init(&ptipv4), ROSN_ATTR_UNDERLINE); /* IPv4 */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_addrdst), ROSN_CLR_CYAN), ROSN_ATTR_NONE); /* IPv4 Destination Address */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_addrsrc), ROSN_CLR_BLUE), ROSN_ATTR_NONE); /* IPv4 Source Address */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_csum), ROSN_CLR_YELLOW), ROSN_ATTR_NONE); /* IPv4 Checksum */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_foff), ROSN_CLR_YELLOW), ROSN_ATTR_NONE); /* IPv4 Fragment Offset Field */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_hlen), ROSN_CLR_MAGENTA), ROSN_ATTR_NONE); /* IPv4 Header length */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_id), ROSN_CLR_RED), ROSN_ATTR_NONE); /* IPv4 Identification */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_prot), ROSN_CLR_GREEN), ROSN_ATTR_NONE); /* IPv4 Protocol */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_tlen), ROSN_CLR_MAGENTA), ROSN_ATTR_NONE); /* IPv4 Total length */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_tos), ROSN_CLR_YELLOW), ROSN_ATTR_NONE); /* IPv4 Type Of Service */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_ttl), ROSN_CLR_YELLOW), ROSN_ATTR_NONE); /* IPv4 Time To Live */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv4_v), ROSN_CLR_GREEN), ROSN_ATTR_NONE); /* IPv4 Version */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptsep), ROSN_CLR_WHITE), ROSN_ATTR_NONE); /* Separator */
ipv4hdr = (struct rosn_ipv4hdr *)(pkt + sizeof(struct rosn_ethhdr)); /* Pointing to the IPv4 Header */
addrdst = strndup(inet_ntop(AF_INET, &(ipv4hdr->addrdst), buf_addrdst, sizeof(buf_addrdst)), sizeof(buf_addrdst)); /* Duplicating the Destination Address into its buffer */
addrsrc = strndup(inet_ntop(AF_INET, &(ipv4hdr->addrsrc), buf_addrsrc, sizeof(buf_addrsrc)), sizeof(buf_addrsrc)); /* Duplicating the Source Address into its buffer */
cprintf(&ptsep, "¤"); printf("["); cprintf(&ptipv4, "IPv4"); printf("]"); /* IPv4 */
printf("["); cprintf(&ptipv4_v, "%d", ipv4hdr->v); printf("]"); /* IPv4 Version */
printf("["); cprintf(&ptipv4_hlen, "%d", ipv4hdr->hlen * 4); printf("]"); /* IPv4 Header length */
printf("["); cprintf(&ptipv4_tos, "%d", ipv4hdr->tos); printf("]"); /* IPv4 Type Of Service */
printf("["); cprintf(&ptipv4_tlen, "%d", ntohs(ipv4hdr->tlen)); printf("]"); /* IPv4 Total length */
printf("["); cprintf(&ptipv4_id, "%d", ntohs(ipv4hdr->id)); printf("]"); /* IPv4 Identification */
printf("["); cprintf(&ptipv4_foff, "%d", ipv4hdr->foff); printf("]"); /* IPv4 Fragment Offset Field */
printf("["); cprintf(&ptipv4_ttl, "%d", ipv4hdr->ttl); printf("]"); /* IPv4 Time To Live */
printf("["); cprintf(&ptipv4_prot, "%x", ipv4hdr->prot); printf("]"); /* IPv4 Protocol */
printf("["); cprintf(&ptipv4_csum, "%d", ipv4hdr->csum); printf("]"); /* IPv4 Checksum */
printf("["); cprintf(&ptipv4_addrsrc, "%s", addrsrc); printf("]"); /* IPv4 Source Address */
printf("["); cprintf(&ptipv4_addrdst, "%s", addrdst); printf("]"); /* IPv4 Destination Address */
}
/**
* rosn_prots_ipv6_handle()
*
* Handle IPv6
* pkt: the packet
* pktlen: packet length
*/
void rosn_prots_ipv6_handle(const u_char *pkt, uint32_t pktlen)
{
char *addrdst = NULL; /* Destination Address */
char *addrsrc = NULL; /* Source Address */
char buf_addrdst[INET6_ADDRSTRLEN] = {0}; /* Buffer for the Destination Address */
char buf_addrsrc[INET6_ADDRSTRLEN] = {0}; /* Buffer for the Source Address */
struct rosn_ipv6hdr *ipv6hdr; /* IPv6 header */
/* Printers */
rosn_clrset ptipv6;
rosn_clrset ptipv6_addrdst;
rosn_clrset ptipv6_addrsrc;
rosn_clrset ptipv6_fl;
rosn_clrset ptipv6_hlmt;
rosn_clrset ptipv6_lenp;
rosn_clrset ptipv6_nhdr;
rosn_clrset ptipv6_tc;
rosn_clrset ptipv6_v;
rosn_clrset ptsep;
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_init(&ptipv6), ROSN_ATTR_UNDERLINE); /* IPv6 */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_addrdst), ROSN_CLR_CYAN), ROSN_ATTR_NONE); /* IPv6 Destination Address */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_addrsrc), ROSN_CLR_BLUE), ROSN_ATTR_NONE); /* IPv6 Source Address */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_fl), ROSN_CLR_YELLOW), ROSN_ATTR_NONE); /* IPv6 Flow Label */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_hlmt), ROSN_CLR_YELLOW), ROSN_ATTR_NONE); /* IPv6 Hop Limit */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_lenp), ROSN_CLR_MAGENTA), ROSN_ATTR_NONE); /* IPv6 Payload length */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_nhdr), ROSN_CLR_GREEN), ROSN_ATTR_NONE); /* IPv6 Next Header */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_tc), ROSN_CLR_RED), ROSN_ATTR_NONE); /* IPv6 Traffic Class */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptipv6_v), ROSN_CLR_GREEN), ROSN_ATTR_NONE); /* IPv6 Version */
rosn_utils_clrprnt_setattr(rosn_utils_clrprnt_setfg(rosn_utils_clrprnt_init(&ptsep), ROSN_CLR_WHITE), ROSN_ATTR_NONE); /* Separator */
ipv6hdr = (struct rosn_ipv6hdr *)(pkt + sizeof(struct rosn_ethhdr)); /* Pointing to the IPv6 Header */
addrdst = strndup(inet_ntop(AF_INET6, &(ipv6hdr->addrdst), buf_addrdst, sizeof(buf_addrdst)), sizeof(buf_addrdst)); /* Duplicating the Destination Address into its buffer */
addrsrc = strndup(inet_ntop(AF_INET6, &(ipv6hdr->addrsrc), buf_addrsrc, sizeof(buf_addrsrc)), sizeof(buf_addrsrc)); /* Duplicating the Source Address into its buffer */
cprintf(&ptsep, "¤"); printf("["); cprintf(&ptipv6, "IPv6"); printf("]"); /* IPv6 */
printf("["); cprintf(&ptipv6_v, "%d", ipv6hdr->v); printf("]"); /* IPv6 Version */
printf("["); cprintf(&ptipv6_tc, "%d", ipv6hdr->tc); printf("]"); /* IPv6 Traffic Class */
printf("["); cprintf(&ptipv6_fl, "%d", ipv6hdr->fl); printf("]"); /* IPv6 Flow Label */
printf("["); cprintf(&ptipv6_lenp, "%d", ntohs(ipv6hdr->lenp)); printf("]"); /* IPv6 Payload length */
printf("["); cprintf(&ptipv6_nhdr, "%d", ipv6hdr->nhdr); printf("]"); /* IPv6 Next Header */
printf("["); cprintf(&ptipv6_hlmt, "%d", ipv6hdr->hlmt); printf("]"); /* IPv6 Hop Limit */
printf("["); cprintf(&ptipv6_addrsrc, "%s", addrsrc); printf("]"); /* IPv6 Source Address */
printf("["); cprintf(&ptipv6_addrdst, "%s", addrdst); printf("]"); /* IPv6 Destination Address */
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* minimap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rmass <rmass@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/08 17:50:58 by rmass #+# #+# */
/* Updated: 2020/12/08 17:50:59 by rmass ### ########.fr */
/* */
/* ************************************************************************** */
#include "cub.h"
int g_size = 11;
void draw_block(t_cub *cub, int x, int y, unsigned int color)
{
int tx;
int ty;
int min;
int bl_s;
tx = 0;
ty = 0;
min = (cub->s_height < cub->s_width) ? cub->s_height : cub->s_width;
bl_s = min / (g_size + 2) / 5;
while (tx < bl_s)
{
ty = 0;
while (ty < bl_s)
{
my_mlx_pixel_put(cub, x * bl_s + tx, y * bl_s + ty, color);
ty++;
}
tx++;
}
}
void draw_mm_frame(t_cub *cub)
{
int x;
int y;
x = 0;
while (x < g_size + 2)
{
y = 0;
while (y < g_size + 2)
{
if (x == 0 || x == g_size + 1 || y == 0 || y == g_size + 1)
draw_block(cub, x, y, cub->f_color);
y++;
}
x++;
}
}
void draw_mm(t_cub *cub)
{
int x;
int y;
int xm;
int ym;
x = 1;
draw_mm_frame(cub);
xm = floorf(cub->player.pos.x) - g_size / 2;
while (x <= g_size)
{
y = 1;
ym = floorf(cub->player.pos.y) - g_size / 2;
while (y <= g_size)
{
if (cfrommap(cub, xm, ym) == '1')
draw_block(cub, x, y, 0xFFFFFF);
if (cfrommap(cub, xm, ym) == '2')
draw_block(cub, x, y, 0x000000);
y++;
ym++;
}
x++;
xm++;
}
draw_block(cub, g_size / 2 + 1, g_size / 2 + 1, 0xFFFF00);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void){
float numero_1, numero_2;
printf("Digite dois numeros para ser feita a analise deles.\nN1: ");
scanf("%f", &numero_1);
printf("N2: ");
scanf("%f", &numero_2);
if (numero_1 == numero_2){
puts("Os dois numeros sao iguas!");
}else{
if (numero_1 > numero_2)
printf("O maior dentre eles eh o primeiro numero %.2f", numero_1);
if (numero_1 < numero_2)
printf("O maior dentre eles eh o segundo numero %.2f", numero_2);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int j,i,lw,up,temp,a,arm=0;
scanf("%d",&lw);
scanf("%d",&up);
for(j=lw;j<up;j++)
{
temp=j;
for(i=0;temp!=0;i++)
{
a=temp%10;
arm=arm+(a*a*a);
temp=temp/10;
}
if(j==arm)
printf("\n%d",arm);
arm=0;
return0 ;
}
|
C
|
//
// main.c
// Prog11
//
// Created by Fallingstar on 2017. 3. 21..
// Copyright © 2017년 Fallingstar. All rights reserved.
//
#include <stdio.h>
#include <GLUT/glut.h>
#include <math.h>
#define SC_FACT 3
void init();
void display();
void rotate(GLfloat *v, GLfloat angle);
void translate(GLfloat *v, GLfloat *t);
void scaling(GLfloat *v, GLfloat *s);
void timer();
double angle = 0;
double delay = 10;
GLfloat t[3] = {-25,-25,-25};
GLfloat s[3] = {SC_FACT, SC_FACT, SC_FACT};
int main(int argc, const char * argv[]) {
glutInit(&argc, (char**)argv);
glutInitWindowSize(500, 500);
glutCreateWindow("Prog07 - my first 3D");
glutDisplayFunc(display);
glutTimerFunc(delay, timer, 0);
init();
glutMainLoop();
return 0;
}
void init(){
glClearColor(0, 0, 0, 0);
glOrtho(-100, 100, -100, 100, -100, 100);
glEnable(GL_DEPTH_TEST);
}
void display(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLfloat v0[3] = {15,15,35}, v1[3] = {35,15,35}, v2[3] = {35,35,35}, v3[3] = {15,35,35};
GLfloat v4[3] = {40,20,15}, v5[3] = {20,20,15}, v6[3] = {40,40,15}, v7[3] = {20,40,15};
translate(v0, t);
translate(v1, t);
translate(v2, t);
translate(v3, t);
translate(v4, t);
translate(v5, t);
translate(v6, t);
translate(v7, t);
scaling(v0, s);
scaling(v1, s);
scaling(v2, s);
scaling(v3, s);
scaling(v4, s);
scaling(v5, s);
scaling(v6, s);
scaling(v7, s);
rotate(v0, angle);
rotate(v1, angle);
rotate(v2, angle);
rotate(v3, angle);
rotate(v4, angle);
rotate(v5, angle);
rotate(v6, angle);
rotate(v7, angle);
glColor3f(1, 0, 0);
glBegin(GL_POLYGON);
glVertex3fv(v0);
glVertex3fv(v1);
glVertex3fv(v2);
glVertex3fv(v3);
glEnd();
glColor3f(0, 1, 0);
glBegin(GL_POLYGON);
glVertex3fv(v0);
glVertex3fv(v1);
glVertex3fv(v4);
glVertex3fv(v5);
glEnd();
glColor3f(0, 0, 1);
glBegin(GL_POLYGON);
glVertex3fv(v5);
glVertex3fv(v4);
glVertex3fv(v6);
glVertex3fv(v7);
glEnd();
glColor3f(1, 1, 0);
glBegin(GL_POLYGON);
glVertex3fv(v7);
glVertex3fv(v6);
glVertex3fv(v2);
glVertex3fv(v3);
glEnd();
glColor3f(0, 1, 1);
glBegin(GL_POLYGON);
glVertex3fv(v0);
glVertex3fv(v5);
glVertex3fv(v7);
glVertex3fv(v3);
glEnd();
glColor3f(1, 0, 1);
glBegin(GL_POLYGON);
glVertex3fv(v1);
glVertex3fv(v4);
glVertex3fv(v6);
glVertex3fv(v2);
glEnd();
glFlush();
}
void translate(GLfloat *v, GLfloat *t) {
int i;
for (i = 0; i < 3; i++) {
v[i] += t[i];
}
}
void rotate(GLfloat *v, GLfloat angle) {
GLfloat x,y,z;
double PI = atan(1.0)*4.0;
double theta = angle*PI / 180.0;
x = v[0] * cos(theta) + v[2] * sin(theta);
y = v[1];
z = v[0] * -sin(theta) + v[2] * cos(theta);
v[0] = x;
v[1] = y;
v[2] = z;
}
void scaling(GLfloat *v, GLfloat *s) {
int i;
static double scal = 1.0;
static int isUp = 0;
for (i = 0; i < 3; i++) {
v[i] *= scal;
}
if (isUp == 0) {
scal -= 0.001;
if (scal <= 0.1) {
isUp = 1;
}
}else{
scal += 0.001;
if (scal >= 1.0) {
isUp = 0;
}
}
}
void timer() {
glutPostRedisplay();
glutTimerFunc(delay, timer, 0);
angle += 1.0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct polynode{
int coef;
int expon;
}pNode;
typedef struct polynomial{
pNode *poly;
int size;
}Polynomial;
Polynomial* readPoly(){
int N,e,c;
Polynomial *p;
scanf("%d",&N);
printf("%d\n",N);
p=(Polynomial*)malloc(sizeof(Polynomial));
p->size=N;
p->poly=(pNode*)malloc(N*sizeof(pNode));
while(N--){
scanf("%d %d",&c,&e);
printf("%d %d\n",c,e);
p->poly[N].coef=c;
p->poly[N].expon=e;
}
return p;
}
int main(){
Polynomial *p1;
p1=readPoly();
return 0;
}
|
C
|
//LAB4 Task2 Part1
//Chase Austin Deitner
//ECE 474 SP2020
//Replecates a traffic light with a pedestrian cross signal
// uses external LCD touch screen. User must hold buttons
// for at least 2 seconds for the system to register
//Initializes LCD Screen to support all traffic light funtions
#include <stdint.h>
#include "SSD2119_Display.h"
#include "SSD2119_Touch.h"
#include "Lab_3_Driver.h"
#include "LAB4.h"
//traffic light states
enum TL_States {TL_Start, TL_Off, TL_TurnOn, TL_Go,
TL_Warn, TL_Stop, TL_TurnOff} TL_State;
//User buttons Pressed
unsigned char pedX_button;
unsigned char SS_button;
//interupt flags
volatile unsigned int flag0; //interrupt flag 0
volatile unsigned int flag1; //interrupt flag 1
volatile unsigned int flag2; //interrupt flag 2
void init_timer0(void);
void timer(void);
void init_timerSS(void);
void init_timerPedX(void);
void green_on(void);
void yellow_on(void);
void red_on(void);
void LEDS_off(void);
void Timer0_ISR (void);
void Timer1_ISR (void);
void Timer2_ISR (void);
unsigned char StartStop(void);
unsigned char PedX(void);
void Traffic_Light(void);
void updateTouch(void);
void init_TrafficLightLCD(void);
//Initialize then run FSM forever
int main()
{
init_timer0(); //5 second timer
init_timerSS(); //2 second timer (startstop)
init_timerPedX(); //2 second timer (PedX)
NVIC_EN0_R = 0xA80000; //enable timer interupts
LCD_Init(); //LCD Sreen
Touch_Init(); //Touch screen
init_TrafficLightLCD(); //Set up user interface
while(1) {
Traffic_Light();
updateTouch();
}
return 0;
}
//initializes screen with buttons and lights
void init_TrafficLightLCD(void)
{
//create buttons
LCD_ColorFill(Color4[0]);
LCD_DrawRect(0, 120, 159, 119, Color4[15]);
LCD_DrawRect(160, 120, 159, 119, Color4[15]);
char buffer[50];
LCD_SetCursor(50,176);
sprintf(buffer, "PedX Cross");
LCD_PrintString(buffer);
LCD_SetCursor(210,176);
sprintf(buffer, "Start-Stop");
LCD_PrintString(buffer);
//Create lights
LCD_DrawCircle(100, 60, 20, Color4[12]); //red light
LCD_DrawCircle(160, 60, 20, Color4[14]); //yellow light
LCD_DrawCircle(220, 60, 20, Color4[10]); //green light
}
//run the FSM
void Traffic_Light()
{
//State Transitions
switch(TL_State) {
case TL_Start:
TL_State = TL_Off;
break;
case TL_Off:
if(StartStop()) {
TL_State = TL_TurnOn;
} else {
TL_State = TL_Off;
}
break;
case TL_TurnOn:
if(SS_button) { //must release ss button
TL_State = TL_TurnOn;
} else {
flag0 = 0;
TL_State = TL_Stop;
timer(); //reset/start timer
}
break;
case TL_Go:
if(StartStop()) {
TL_State = TL_TurnOff;
} else if (PedX()){
TL_State = TL_Warn;
timer(); //reset/start timer
} else if (flag0) { //if timer flag is thrown
flag0 = 0;
TL_State = TL_Stop;
timer(); //reset/start timer
}
break;
case TL_Warn:
if(StartStop()) {
TL_State = TL_TurnOff;
} else if (flag0) { //if timer flag is thrown
flag0 = 0;
TL_State = TL_Stop;
timer(); //reset/start timer
}
break;
case TL_Stop:
if(StartStop()) {
TL_State = TL_TurnOff;
} else if (flag0) { //if timer flag is thrown
flag0 = 0;
TL_State = TL_Go;
timer(); //reset/start timer
}
break;
case TL_TurnOff:
if(SS_button) { //must release ss button
TL_State = TL_TurnOff;
} else {
TL_State = TL_Off;
}
break;
default:
TL_State = TL_Start;
break;
}
//State Actions
switch(TL_State) {
case TL_Start:
LEDS_off();
break;
case TL_Off:
LEDS_off();
break;
case TL_TurnOn:
LEDS_off();
break;
case TL_Go:
green_on();
break;
case TL_Warn:
yellow_on();
break;
case TL_Stop:
red_on();
break;
case TL_TurnOff:
LEDS_off();
break;
default:
LEDS_off();
break;
}
}
//initialize 5 second timer
void init_timer0(void)
{
volatile unsigned short delay = 0;
SYSCTL_RCGCTIMER_R |= 0x1; //Enable GPTimer module 0
delay++;
delay++;
TIMER0_CTL_R = 0x0; //Disable Timer while initializing
TIMER0_CFG_R = 0x0; //Configure to 32-Bit timer
TIMER0_TAMR_R |= 0x2; //set to periodic mode
TIMER0_TAMR_R &= ~0x10; //set to cound down
TIMER0_TAILR_R = 0x4C4B400; //count down from 80 million (5sec)
TIMER0_IMR_R = 0x1; //configure the GPTMIMR register for interupts
TIMER0_CTL_R &= ~0x1; //disable Timer
}
//reset the 5 second timer
void timer(void)
{
TIMER0_CTL_R |= 0x1; //enable Timer
TIMER0_TAILR_R = 0x4C4B400; //set timer to 80 million (5sec)
}
//initialize start stop 2 second timer
void init_timerSS(void)
{
volatile unsigned short delay = 0;
SYSCTL_RCGCTIMER_R |= 0x2; //Enable GPTimer module 0
delay++;
delay++;
TIMER1_CTL_R = 0x0; //Disable Timer while initializing
TIMER1_CFG_R = 0x0; //Configure to 32-Bit timer
TIMER1_TAMR_R |= 0x2; //set to periodic mode
TIMER1_TAMR_R &= ~0x10; //set to cound down
TIMER1_TAILR_R = 0x1E84800; //count down from 32 million (2sec)
TIMER1_IMR_R = 0x1; //configure the GPTMIMR register for interupts
TIMER1_CTL_R &= ~0x1; //disable Timer
}
void init_timerPedX(void)
{
volatile unsigned short delay = 0;
SYSCTL_RCGCTIMER_R |= 0x4; //Enable GPTimer module 0
delay++;
delay++;
TIMER2_CTL_R = 0x0; //Disable Timer while initializing
TIMER2_CFG_R = 0x0; //Configure to 32-Bit timer
TIMER2_TAMR_R |= 0x2; //set to periodic mode
TIMER2_TAMR_R &= ~0x10; //set to cound down
TIMER2_TAILR_R = 0x1E84800; //count down from 32 million (2sec)
TIMER2_IMR_R = 0x1; //configure the GPTMIMR register for interupts
TIMER2_CTL_R &= ~0x1; //disable Timer
}
// turn on only the green light
void green_on(void) {
LCD_DrawFilledCircle(100, 60, 19, 0x000000); //red light off
LCD_DrawFilledCircle(160, 60, 19, 0x000000); //yellow light off
LCD_DrawFilledCircle(220, 60, 19, Color4[10]); //green light on
}
// turn on only the yellow light
void yellow_on(void) {
LCD_DrawFilledCircle(220, 60, 19, 0x000000); //green light off
LCD_DrawFilledCircle(100, 60, 19, 0x000000); //red light off
LCD_DrawFilledCircle(160, 60, 19, Color4[14]); //yellow light on
}
// turn on only the red light
void red_on(void) {
LCD_DrawFilledCircle(220, 60, 19, 0x000000); //green light off
LCD_DrawFilledCircle(160, 60, 19, 0x000000); //yellow light off
LCD_DrawFilledCircle(100, 60, 19, Color4[12]); //red light on
}
// turn off all lights
void LEDS_off(void) {
LCD_DrawFilledCircle(100, 60, 19, 0x000000); //red light off
LCD_DrawFilledCircle(160, 60, 19, 0x000000); //yellow light off
LCD_DrawFilledCircle(220, 60, 19, 0x000000); //green light off
}
void Timer0_ISR (void)
{
flag0 = 1;
TIMER0_ICR_R |= 0x1;
}
void Timer1_ISR (void)
{
flag1 = 1;
TIMER1_ICR_R |= 0x1;
}
void Timer2_ISR (void)
{
flag2 = 1;
TIMER2_ICR_R |= 0x1;
}
//Start Stop button check
unsigned char StartStop(void)
{
if (SS_button) { //if button is pressed
TIMER1_CTL_R |= 0x1; //turn timer on
} else {
TIMER1_CTL_R &= ~0x1; //turn timer off
TIMER1_TAILR_R = 0x1E84800; //reset timer
}
if (SS_button && flag1) { //if button is still pressed after 2 sec
flag1 = 0; //reset flag
TIMER1_CTL_R &= ~0x1; //turn timer off
TIMER1_TAILR_R = 0x1E84800; //reset timer
return 1;
} else {
return 0;
}
}
//Pedestrian Crossing button check
unsigned char PedX(void)
{
if (pedX_button) { //if button is pressed
TIMER2_CTL_R |= 0x1; //turn timer on
} else {
TIMER2_CTL_R &= ~0x1; //turn timer off
TIMER2_TAILR_R = 0x1E84800; //reset timer
}
if (pedX_button && flag2) { //if button is still pressed after 2 sec
flag2 = 0; //reset flag
TIMER2_CTL_R &= ~0x1; //turn timer off
TIMER2_TAILR_R = 0x1E84800; //reset timer
return 1;
} else {
return 0;
}
//return (GPIO_PORTE_DATA_R & 0x2); // 0x2 (pressed) or 0 (not pressed)
}
void updateTouch (void)
{
unsigned long touch_X;
unsigned long touch_Y;
touch_X = Touch_ReadX();
touch_Y = Touch_ReadY();
//if(pedX_button)
if (touch_X < 1500 && touch_X > 100 && touch_Y > 800) {
pedX_button = 0x1;
LCD_DrawRect(5, 125, 149, 109, Color4[15]); //show button is pressed
} else {
pedX_button = 0x0;
LCD_DrawRect(5, 125, 149, 109, Color4[0]);
}
//if(SS_button)
if (touch_X > 1500 && touch_Y < 1200) {
SS_button = 0x1;
LCD_DrawRect(165, 125, 149, 109, Color4[15]); //show button is pressed
} else {
SS_button = 0x0;
LCD_DrawRect(165, 125, 149, 109, Color4[0]);
}
}
|
C
|
#ifndef READLINE_H
#define READLINE_H
#include <stddef.h>
// readline reads a single line of input. If more than one line is read, the
// pointer arguments provide enough state to restart the next line in the
// buffer. buf is automatically resized to fit the line.
//
// buf is a pointer to a char buffer. If this is NULL, a new buffer is
// allocated
//
// len is a pointer to the size of the buffer. The size is automatically
// updated as the buffer grows
//
// readlen is a pointer that indicates the length of the buffer that is valid
// data. This is used to restore the state of the reader on successive calls
//
// linelen is the length of the first line present in the buffer. This is also
// used to restore the state of the reader
//
// On successive calls, the returned value should be the value passed as
// linelen
size_t readline(char **buf, size_t *len, size_t *readlen, size_t linelen);
#endif
|
C
|
#include "libft.h"
char *ft_strdup(const char *s)
{
char *ptr;
int i;
if (!(ptr = (char *)malloc(ft_strlen((char *)s) + 1)))
return (NULL);
i = 0;
while (*s)
{
*ptr++ = *s++;
i++;
}
*ptr = '\0';
return (ptr - i);
}
|
C
|
/*
GPIO ports
1. 18 outputs (LED)
a. set1(PB0-PB7, PA4)
b. set2(PD2-PD3, PD6-PD7, PC5-PC7, PE0,PE3)
2. 3 inputs (Buttons) (PF0,PF4,PE5)
3. 2 inputs (ADC) (PE1-PE2)
4. 2 outputs (PWM) (PC4,PE4)
*/
/*
Definitions for the Tic Tac Toe game functions.
*/
/***
Winning Score for Player:9
Winning Score for Bot: 12
Player's Score is incremented by: 3
Bot's Score is incremented by: 4
***/
#include "tm4c123gh6pm.h"
#include "TicTacToe.h"
#include "ST7735.h"
#include <stdint.h>
unsigned long In;
struct Positions {
int freePositions[9];
int takePositionsA[5];
int takePositionsB[4];
//Center wins
//[0,4,8],[1,4,7],[2,4,6],[3,4,5]
uint8_t winCenter[4];
//[0,3,6], [2,5,8]
uint8_t winMod[2];
//[0,1,2], [6,7,8]
uint8_t winBelow[2];
};
struct LEDS {
uint8_t PlayerLEDS [3][3];
uint8_t BotLEDS [3][3];
};
struct Status {
bool GameStart;
bool GamePlayDumbAI;
bool GamePlaySmartAI;
bool gameOver;
bool botWon;
bool playerWon;
uint8_t playerMoves;
uint8_t freeTiles;
uint8_t centerTile;
};
struct AnalogAttributes {
uint8_t analogValueR;
uint8_t analogValueC;
};
struct Positions gamePositions;
struct Status gameStatus;
struct LEDS gameLeds = {
{{0x01, 0x02, 0x04},
{0x08, 0x10, 0x20},
{0x40, 0x80, 0x10},},
{{0x04, 0x08, 0x40},
{0x80, 0x20, 0x40},
{0x80, 0x01, 0x08},}
};
struct AnalogAttributes g = {
0,
0
};
//The player is met with this function. The beginning of the game.
void GameStart(){
ST7735_FillScreen(0x0); // set screen to black
ST7735_SetCursor(0,0);
ResetFlags();
//Reset the boards and positions
ResetBoard();
ST7735_OutString("\n TIC TAC TOE...\n SW1: Dumb AI\n SW2: Smart AI\n Press to Play\n");
while(!gameStatus.gameOver){
In = GPIO_PORTE_DATA_R&0x10; // read PE4 into In
if(In == 0x00){ // PE4 is low
ClearAllLeds();
} else{ // PE4 is high
LightAllLeds();
}
if (gameStatus.GamePlayDumbAI){
GamePlayDumbAI();
ST7735_OutString("\n GameOver \n ");
}
else if (gameStatus.GamePlaySmartAI){
GamePlaySmartAI();
}
}
GameOver();
}
//The game plays with a dumb AI.
void GamePlayDumbAI(){
ST7735_FillScreen(0x0); // set screen to black
ST7735_SetCursor(0,0);
ST7735_OutString("\n TIC TAC TOE...\n Dumb AI\n Play!\n");
ClearAllLeds();
while (!gameStatus.gameOver){
LightAnalogLed();
LightPlayerLeds();
LightBotLeds();
}
}
void GamePlaySmartAI(){
ST7735_FillScreen(0x0); // set screen to black
ST7735_SetCursor(0,0);
ST7735_OutString("\n TIC TAC TOE...\n Smart AI\n Play SMART!\n");
ClearAllLeds();
while(!gameStatus.gameOver){
LightAnalogLed();
LightPlayerLeds();
LightBotLeds();
}
};
//The game ends.
void GameOver(){
ST7735_SetCursor(0,0);
ST7735_FillScreen(0x0);
PrintResults();
ClearAllLeds();
while(gameStatus.gameOver){
if(gameStatus.botWon){
LightBotLeds();
}
else if (gameStatus.playerWon){
LightPlayerLeds();
}
else {
LightPlayerLeds();
LightBotLeds();
}
}
}
void PrintResults(){
if(gameStatus.GamePlayDumbAI)
ST7735_OutString("\n DumbAI MODE");
else
ST7735_OutString("\n SmartAI MODE");
if(gameStatus.botWon)
ST7735_OutString("\n BOT WON");
else if(gameStatus.playerWon)
ST7735_OutString("\n Player Won");
else
ST7735_OutString("\n Draw");
ST7735_OutString("\n PlayerMoves: ");
ST7735_OutUDec(gameStatus.playerMoves);
}
//Reset the Tic Tac Toe board
void ResetBoard(){
int i;
//Reset all the positions to free on the board.
for ( i = 0; i<=8; i++){
gamePositions.freePositions[i] = i;
}
//Reset the taken A positions to none.
for ( i = 0; i<=4; i++){
gamePositions.takePositionsA[i] = -1;
}
//Reset the taken B positions to none.
for ( i = 0; i<=3; i++){
gamePositions.takePositionsB[i] = -1;
}
}
//Reset Status and Flags
void ResetFlags(){
int i;
gameStatus.gameOver = false;
gameStatus.GamePlaySmartAI = false;
gameStatus.GamePlayDumbAI = false;
gameStatus.playerWon = false;
gameStatus.botWon = false;
gameStatus.playerMoves = 0;
gameStatus.freeTiles = 9;
gameStatus.centerTile = 0;
for ( i = 0; i<=3; i++){
gamePositions.winCenter[i] = 0;
}
for ( i = 0; i<=1; i++){
gamePositions.winMod[i] = 0;
gamePositions.winBelow[i] = 0;
}
}
//Checks if the game has ended
//if check(true) check the player
bool CheckGameOver(bool check){
int i;
//Checks the player's tile
if (gameStatus.playerMoves > 1 ){
//Check center victory
if (gameStatus.centerTile == 1){ //only check if center tile is in Player's hand
for (i = 0; i <=3; i++){
if (gamePositions.winCenter[i] == 9){
ST7735_OutString("\nWIN");
gameStatus.playerWon = true;
return true;
}
}
}
if (gameStatus.centerTile == 2) {
for (i = 0; i <=3; i++){
if (gamePositions.winCenter[i] == 12){
ST7735_OutString("\nWIN");
gameStatus.botWon = true;
return true;
}
}
}
for (i = 0; i <= 1; i++){
if (gamePositions.winBelow[i] == 9){
gameStatus.playerWon = true;
return true;
}
if (gamePositions.winBelow[i] == 12){
ST7735_OutString("\nWIN");
gameStatus.botWon = true;
return true;
}
if (gamePositions.winMod[i] == 9){
gameStatus.playerWon = true;
return true;
}
if (gamePositions.winMod[i] == 12){
gameStatus.botWon = true;
return true;
}
}
}
if (gameStatus.freeTiles == 0){
ST7735_OutString("\nGameEnd");
return true;
}
return false;
}
//Clears the LEDS on the tic tac toe board
void ClearAllLeds(){
GPIO_PORTA_DATA_R &= ~0x10;
GPIO_PORTB_DATA_R &= ~0xFF;
GPIO_PORTD_DATA_R &= ~0xCC;
GPIO_PORTC_DATA_R &= ~0xE0;
GPIO_PORTE_DATA_R &= ~0x09;
}
void LightAllLeds(){
GPIO_PORTA_DATA_R |= 0x10;
GPIO_PORTB_DATA_R |= 0xFF;
GPIO_PORTD_DATA_R |= 0xCC;
GPIO_PORTC_DATA_R |= 0xE0;
GPIO_PORTE_DATA_R |= 0x09;
}
void LightPlayerLeds(){
int i;
In = GPIO_PORTE_DATA_R&0x10; // read PE4 into In
if(gameStatus.playerMoves > 0 ){
if (In == 0x00){ // PE4 is low
for (i = 0; i < gameStatus.playerMoves; i++){
if(gamePositions.takePositionsA[i]!=8)
GPIO_PORTB_DATA_R &=
~gameLeds.PlayerLEDS[gamePositions.takePositionsA[i]/3][gamePositions.takePositionsA[i]%3];
else
GPIO_PORTA_DATA_R &=
~gameLeds.PlayerLEDS[gamePositions.takePositionsA[i]/3][gamePositions.takePositionsA[i]%3];
}
}
else
for (i = 0; i < gameStatus.playerMoves; i++){
if(gamePositions.takePositionsA[i]!=8)
GPIO_PORTB_DATA_R |=
gameLeds.PlayerLEDS[gamePositions.takePositionsA[i]/3][gamePositions.takePositionsA[i]%3];
else
GPIO_PORTA_DATA_R |=
gameLeds.PlayerLEDS[gamePositions.takePositionsA[i]/3][gamePositions.takePositionsA[i]%3];
}
}
}
void LightBotLeds(){
int i;
In = GPIO_PORTE_DATA_R&0x10; // read PE4 into In
if(gameStatus.playerMoves > 0 ){
if (In == 0x00) { // PE4 is low
for (i = 0; i < gameStatus.playerMoves; i++){
if (i <= 3){
if(gamePositions.takePositionsB[i] < 4)
GPIO_PORTD_DATA_R &=
~gameLeds.BotLEDS[gamePositions.takePositionsB[i]/3][gamePositions.takePositionsB[i]%3];
else if(gamePositions.takePositionsB[i] < 7)
GPIO_PORTC_DATA_R &=
~gameLeds.BotLEDS[gamePositions.takePositionsB[i]/3][gamePositions.takePositionsB[i]%3];
else
GPIO_PORTE_DATA_R &=
~gameLeds.BotLEDS[gamePositions.takePositionsB[i]/3][gamePositions.takePositionsB[i]%3];
}
}
}
else {
for (i = 0; i < gameStatus.playerMoves; i++){
if(i <= 3){
if(gamePositions.takePositionsB[i] < 4)
GPIO_PORTD_DATA_R |=
gameLeds.BotLEDS[gamePositions.takePositionsB[i]/3][gamePositions.takePositionsB[i]%3];
else if(gamePositions.takePositionsB[i] < 7)
GPIO_PORTC_DATA_R |=
gameLeds.BotLEDS[gamePositions.takePositionsB[i]/3][gamePositions.takePositionsB[i]%3];
else
GPIO_PORTE_DATA_R |=
gameLeds.BotLEDS[gamePositions.takePositionsB[i]/3][gamePositions.takePositionsB[i]%3];
}
}
}
}
}
void LightAnalogLed(){
In = GPIO_PORTC_DATA_R&0x10; // read PC4 into In
if(In == 0x00){ // PC4 is low
if (g.analogValueC == 2 && g.analogValueR == 2)
GPIO_PORTA_DATA_R &= ~0x10;
else
GPIO_PORTB_DATA_R &= ~gameLeds.PlayerLEDS[g.analogValueR][g.analogValueC];
} else{ // PC4 is high
if (g.analogValueC == 2 && g.analogValueR == 2)
GPIO_PORTA_DATA_R |= 0x10;
else
GPIO_PORTB_DATA_R |= gameLeds.PlayerLEDS[g.analogValueR][g.analogValueC];
}
}
bool AddPosition(uint8_t position){
int arrayPosition = FreePosition(position);
if (arrayPosition != -1){
gamePositions.takePositionsA[gameStatus.playerMoves] = arrayPosition;
gameStatus.playerMoves++;
if (arrayPosition == 4)
gameStatus.centerTile = 1;
gameStatus.freeTiles--;
AddWinScore(true, position);
return true;
}
else return false;
}
bool AddPositionBotSmart(uint8_t position){
int arrayPosition = FreePosition(position);
if (arrayPosition != -1){
//gameStatus.PlayermMoves has to be decremented because it increases
// the player's moves.
gamePositions.takePositionsB[gameStatus.playerMoves-1] = arrayPosition;
if (arrayPosition == 4)
gameStatus.centerTile = 2;
gameStatus.freeTiles--;
AddWinScore(false, position);
return true;
}
else return false;
}
void AddPositionBotAuto(){
uint8_t arrayCounter = 0;
while (gamePositions.freePositions[arrayCounter] == -1){
++arrayCounter;
}
if (arrayCounter == 4)
gameStatus.centerTile = 2;
gamePositions.takePositionsB[gameStatus.playerMoves-1] =
gamePositions.freePositions[arrayCounter];
gamePositions.freePositions[arrayCounter] = -1;
AddWinScore(false, arrayCounter);
gameStatus.freeTiles--;
}
void AddWinScore(bool check, uint8_t position){
//Center wins, Mod wins, Below wins
//[0,4,8],[1,4,7],[2,4,6],[3,4,5]
//[0,3,6], [2,5,8]
//[0,1,2], [6,7,8]
int i;
if (check){
if(position == 4){
for (i = 0; i <= 3; i++){
gamePositions.winCenter[i] += 3; //[0,4,8],[1,4,7],[2,4,6],[3,4,5]
}
}
else if (position < 4){
gamePositions.winCenter[position%4] += 3; //[0,4,8],[1,4,7],[2,4,6],[3,4,5]
if(position < 3)
gamePositions.winBelow[0] += 3; //[0,1,2]
if (position%3 == 0)
gamePositions.winMod[0] += 3; //[0,3,6]
if (position%3 == 2)
gamePositions.winMod[1] += 3; //[2,5,8]
}
else {
gamePositions.winCenter[8-position]+=3; //[0,4,8],[1,4,7],[2,4,6],[3,4,5]
if(position > 5)
gamePositions.winBelow[1] += 3; //[6,7,8]
if (position%3 == 0)
gamePositions.winMod[0] += 3; //[0,3,6]
if (position%3 == 2)
gamePositions.winMod[1] += 3; //[2,5,8]
}
}
//
//
else {
if(position == 4){
for ( i = 0; i <= 3; i++){
gamePositions.winCenter[i] += 4; //[0,4,8],[1,4,7],[2,4,6],[3,4,5]
}
}
else if (position < 4){
gamePositions.winCenter[position%4] += 4; //[0,4,8],[1,4,7],[2,4,6],[3,4,5]
if(position < 3)
gamePositions.winBelow[0] += 4; //[0,1,2]
if (position%3 == 0)
gamePositions.winMod[0] += 4; //[0,3,6]
if (position%3 == 2)
gamePositions.winMod[1] += 4; //[2,5,8]
}
else {
gamePositions.winCenter[8-position]+=4; //[0,4,8],[1,4,7],[2,4,6],[3,4,5]
if(position > 5)
gamePositions.winBelow[1] += 4; //[6,7,8]
if (position%3 == 0)
gamePositions.winMod[0] += 4; //[0,3,6]
if (position%3 == 2)
gamePositions.winMod[1] += 4; //[2,5,8]
}
}
}
int FreePosition(uint8_t position){
int i;
for (i = 0; i<=8; i++){
if (position == gamePositions.freePositions[i]){
gamePositions.freePositions[i] = -1;
return i;
}
}
return -1;
}
bool SearchElement (int element, bool check){
int i;
if (check){
for (i = 0; i < gameStatus.playerMoves; i++){
if (gamePositions.takePositionsA[i] == element)
return true;
}
}
else {
for (i = 0; i < gameStatus.playerMoves; i++){
if (gamePositions.takePositionsB[i] == element)
return true;
}
}
return false;
}
int MakeAIMove(){
if (gameStatus.playerMoves > 1){
if(AvailableWin())
return 0;
if(AvailableBlock())
return 0;
}
if (gameStatus.playerMoves == 2 || gameStatus.playerMoves == 3){
if(AvailableFork())
return 0;
if(BlockFork())
return 0;
}
if (AvailableCenter())
return 0;
if(AvailableOppositeCorner())
return 0;
if(AvailableEmptyCorner())
return 0;
if(AvailableEmptySide())
return 0;
return 0;
}
//AI checks for an Available Win and adds the position
bool AvailableWin(){
int i;
if (gameStatus.centerTile == 2) {
for (i = 0; i <=3; i++){
if (gamePositions.winCenter[i] == 8 && (AddPositionBotSmart(8-i) || AddPositionBotSmart(i%4))){
ST7735_OutString("\nWIN");
return true;
}
}
}
for(i = 0; i<=1; i++){
if (gamePositions.winBelow[i] == 8){
if (i == 0 && (AddPositionBotSmart(0) || AddPositionBotSmart(1) || AddPositionBotSmart(2)))
return true;
if (i == 1 && (AddPositionBotSmart(6) || AddPositionBotSmart(7) || AddPositionBotSmart(8)))
return true;
}
if (gamePositions.winMod[i] == 8){
if (i == 0 && (AddPositionBotSmart(0) || AddPositionBotSmart(3) || AddPositionBotSmart(6)))
return true;
if (i == 1 && (AddPositionBotSmart(2) || AddPositionBotSmart(5) || AddPositionBotSmart(8)))
return true;
}
}
return false;
}
//AI checks for an Avaliable Block (win)
bool AvailableBlock(){
int i;
if (gameStatus.centerTile == 1) {
for (i = 0; i <=3; i++){
if (gamePositions.winCenter[i] == 6 && (AddPositionBotSmart(8-i) || AddPositionBotSmart(i%4))){
return true;
}
}
}
for(i = 0; i<=1; i++){
if (gamePositions.winBelow[i] == 6){
if (i == 0 && (AddPositionBotSmart(0) || AddPositionBotSmart(1) || AddPositionBotSmart(2)))
return true;
if (i == 1 && (AddPositionBotSmart(6) || AddPositionBotSmart(7) || AddPositionBotSmart(8)))
return true;
}
if (gamePositions.winMod[i] == 6){
if (i == 0 && (AddPositionBotSmart(0) || AddPositionBotSmart(3) || AddPositionBotSmart(6)))
return true;
if (i == 1 && (AddPositionBotSmart(2) || AddPositionBotSmart(5) || AddPositionBotSmart(8)))
return true;
}
}
return false;
}
//AI checks for an Available Fork
bool AvailableFork(){
if(SearchElement(2,false)&& SearchElement(6,false) && AddPositionBotSmart(5))
return true;
if(SearchElement(0,false)&& SearchElement(8,false) && AddPositionBotSmart(3))
return true;
if(gameStatus.centerTile == 2){
if(SearchElement(0,false)&& SearchElement(4,false) && (AddPositionBotSmart(2) || AddPositionBotSmart(6)))
return true;
if(SearchElement(2,false)&& SearchElement(4,false) && (AddPositionBotSmart(0) || AddPositionBotSmart(8)))
return true;
if(SearchElement(6,false)&& SearchElement(4,false) && (AddPositionBotSmart(0) || AddPositionBotSmart(8)))
return true;
if(SearchElement(8,false)&& SearchElement(4,false) && (AddPositionBotSmart(2) || AddPositionBotSmart(6)))
return true;
}
return false;
}
//AI checks for a fork to block
bool BlockFork(){
if(SearchElement(2,true)&& SearchElement(6,true) && AddPositionBotSmart(5))
return true;
if(SearchElement(0,true)&& SearchElement(8,true) && AddPositionBotSmart(3))
return true;
return false;
}
//AI checks for an Available Center
bool AvailableCenter(){
if (gameStatus.centerTile==0){
AddPositionBotSmart(4);
return true;
}
return false;
}
////AI checks for an opposite corner
bool AvailableOppositeCorner(){
//corners available are 0,2,6,8
//sets [8,0], [0,8], [2,6],[6,2]
if (SearchElement(0, true) && AddPositionBotSmart(8))
return true;
if (SearchElement(8, true) && AddPositionBotSmart(0))
return true;
if (SearchElement(2, true) && AddPositionBotSmart(6))
return true;
if (SearchElement(6, true) && AddPositionBotSmart(2))
return true;
return false;
}
////AI checks for an Empty Corner
bool AvailableEmptyCorner(){
if (AddPositionBotSmart(0))
return true;
if (AddPositionBotSmart(2))
return true;
if (AddPositionBotSmart(6))
return true;
if (AddPositionBotSmart(8))
return true;
return false;
}
//AI checks for an Empty Side
bool AvailableEmptySide(){
if (AddPositionBotSmart(1))
return true;
if (AddPositionBotSmart(3))
return true;
if (AddPositionBotSmart(5))
return true;
if (AddPositionBotSmart(7))
return true;
return false;
}
void DelayWait10ms(uint32_t n){uint32_t volatile time;
while(n){
time = 727240*2/91; // 10msec
while(time){
time--;
}
n--;
}
}
void GPIOPortF_Handler(){
if ((GPIO_PORTF_RIS_R&0x01) == 0x01 ) { // detects if switch 2 is pressed
GPIO_PORTF_ICR_R = 0x01; // acknowledge flag0
GPIO_PORTF_DATA_R = 0x04;
gameStatus.GamePlaySmartAI = true;
if(gameStatus.gameOver)
gameStatus.gameOver = false;
}
else if ((GPIO_PORTF_RIS_R&0x10) == 0x10 ) { // detects if switch 1 is pressed
GPIO_PORTF_ICR_R = 0x10; // acknowledge flag0
GPIO_PORTF_DATA_R = 0x08;
gameStatus.GamePlayDumbAI = true;
if(gameStatus.gameOver)
gameStatus.gameOver = false;
}
}
void ADC1Seq2_Handler(void){
uint32_t Adirection[2];
ADC1_PSSI_R = 0x0004; // 1) initiate SS2 (pg845)
while((ADC1_RIS_R&0x04)==0){}; // 2) wait for conversion done ADC raw interrupt status,
// checks for SS2, pg823
Adirection[0] = ADC1_SSFIFO2_R&0xFFF; // read second result, y direction read.
Adirection[1] = ADC1_SSFIFO2_R&0xFFF; // read first result, x direction read.
if((gameStatus.GamePlayDumbAI == true || gameStatus.GamePlaySmartAI == true) && !gameStatus.gameOver){
if (Adirection[1] >= 3700){
GPIO_PORTF_DATA_R = 0x08;
GPIO_PORTB_DATA_R &= ~gameLeds.PlayerLEDS[g.analogValueR][g.analogValueC];
g.analogValueC += 1;
g.analogValueC %= 3;
DelayWait10ms(100);
}
else if (Adirection[1] <= 400){
GPIO_PORTF_DATA_R = 0x08;
GPIO_PORTB_DATA_R &= ~gameLeds.PlayerLEDS[g.analogValueR][g.analogValueC];
g.analogValueC += 2;
g.analogValueC%=3;
DelayWait10ms(100);
}
else {
GPIO_PORTB_DATA_R &= ~0xff;
GPIO_PORTA_DATA_R &= ~0x10;
}
if (Adirection[0] >= 3000){
GPIO_PORTF_DATA_R = 0x08;
GPIO_PORTB_DATA_R &= ~gameLeds.PlayerLEDS[g.analogValueR][g.analogValueC];
g.analogValueR += 2;
g.analogValueR %= 3;
DelayWait10ms(100);
}
else if (Adirection[0] <= 1200){
GPIO_PORTF_DATA_R = 0x08;
GPIO_PORTB_DATA_R &= ~gameLeds.PlayerLEDS[g.analogValueR][g.analogValueC];
g.analogValueR+=1;
g.analogValueR%=3;
DelayWait10ms(100);
}
else {
GPIO_PORTB_DATA_R &= ~0xff;
GPIO_PORTA_DATA_R &= ~0x10;
}
}
ADC1_ISC_R = 0x0004; // 4) clear interrupt, ADC interrupt status and clear, pg 803,823
}
void GPIOPortE_Handler(){
if ((GPIO_PORTE_RIS_R&0x20) == 0x20 ) { // detects if PE5 is pressed
GPIO_PORTE_ICR_R = 0x20; // acknowledge flag0
GPIO_PORTF_DATA_R = 0x04;
//allows the player to finalize a position on the board
if ((gameStatus.GamePlayDumbAI || gameStatus.GamePlaySmartAI) && !gameStatus.gameOver){
if(AddPosition(((3*g.analogValueR)+g.analogValueC))){
gameStatus.gameOver = CheckGameOver(true);
DelayWait10ms(700);
if(!gameStatus.gameOver ) {
if (gameStatus.GamePlayDumbAI)
AddPositionBotAuto();
else
MakeAIMove();
gameStatus.gameOver = CheckGameOver(false);
}
}
else {ST7735_OutString("\n Position Not Added!\n");
ST7735_OutUDec((3*g.analogValueR)+g.analogValueC);
}
}
}
DelayWait10ms(300);
}
|
C
|
#include<stdio.h>
void main()
{
int n,f=1,x;
printf("enter a number");
scanf("%d",&n);
x=n;
while(n>=1)
{
f=f*n;
n--;
}
printf("factorial of %d is%d",x,f);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<math.h>
#include "timer.h"
double sequential_pi(int number_of_steps){
double pi = 0;
for(int i; i<number_of_steps; i++){
if(i%2 == 0) pi += 1.0/(2.0*i+1.0);
else pi -= 1.0/(2.0*i+1.0);
}
return 4*pi;
}
int main(int argc, char *argv[]){
if(argc<2){
fprintf(stderr, "Digite: %s <numero_de_iterações>\n", argv[0]);
return 1;
}
int number_of_steps = atoi(argv[1]);
double pi = sequential_pi(number_of_steps);
printf("sequential pi = %.15lf\n", pi);
printf("reference pi = %.15lf\n", M_PI);
return 0;
}
|
C
|
/* -*- c -*- */
/*
* Arduino Tunes with piezo buzzer and PWM.
*
* Connect the positive side of the buzzer to pin 3, then the negative
* side to a 300 Ohm resistor.
* Connect the other side of the resistor to ground (GND) pin
* on the Arduino.
*
* Based on the code by Dipto Pratyaksa.
* Rewritten by Valery V. Vorotyntsev.
*
* TODO:
* - Reduce memory footprint by using bit fields for struct Note.
* - Use PROGMEM.
* - Get a second buzzer to play bass notes on.
*
* References:
* 0. http://www.mariopiano.com/mario-sheet-music-overworld-main-theme.html
* 1. http://www.princetronics.com/supermariothemesong/
* 2. http://www.linuxcircle.com/2013/03/31/playing-mario-bros-tune-with-arduino-and-piezo-buzzer/
*/
#define __ASSERT_USE_STDERR
#include <assert.h> /* defines assert(); uses __assert() defined below */
#include "notes.h"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
enum {
PIN_BUZZER = 3,
PIN_LED = 13,
};
enum Note_Type {
NT_NOTE,
NT_REST,
NT_MM /**< metronome mark */
};
/** Default metronome mark, crotchets per minute. */
enum { DEFAULT_MM = 120 };
/** The duration of the whole note, miliseconds. */
static unsigned int whole_note;
struct Note {
enum Note_Type n_type;
/** See enum Note_Freq for values. */
unsigned int n_frequency;
/**
* Inverted note value.
*
* 1 - whole (semibreve),
* 2 - half (minim),
* 4 - quarter (crotchet),
* 8 - eighth (quaver),
* etc.
*
* If .n_type == NT_MM, then .n_value specifies the number
* of crotchets per minute.
*/
unsigned int n_value;
/** Whether to "join" this note with the next one. */
bool n_slur;
};
static bool note_invariant(const struct Note *note)
{
return note != NULL &&
(note->n_type >= NT_NOTE && note->n_type <= NT_MM) &&
note->n_value != 0 &&
/* only NOTEs can have .n_slur set */
(!note->n_slur || note->n_type == NT_NOTE) &&
/* only NOTEs can have non-zero .n_frequency */
(note->n_frequency == 0 || note->n_type == NT_NOTE);
}
#define n(pitch, value) { NT_NOTE, NOTE_ ## pitch, (value), false }
#define ns(pitch, value) { NT_NOTE, NOTE_ ## pitch, (value), true }
#define r(value) { NT_REST, 0, (value), false }
#define mm(value) { NT_MM, 0, (value), false }
/* https://en.wikipedia.org/wiki/Note_value */
static unsigned int dot(unsigned int inverted_value)
{
/* Add 1 to compensate for integer division. */
return (inverted_value + 1) * 2 / 3;
}
/* https://youtu.be/P5L6Qgmcjfw */
static const struct Note sherlock[] = {
mm(200),
#define XXX_LEFTY 1
#if XXX_LEFTY
n(C3,4), n(G3,4), n(G2,4), n(G3,4),
n(C3,4), n(G3,4), n(G2,4), n(G3,4),
#else
r(1),
r(1),
#endif
n(C4,4), n(G4,2), n(G4,4),
n(FS4,8), n(G4,8), n(GS4,2), n(G4,4),
n(F4,4), ns(C5,dot(2)),
n(C5,1),
n(F4,4), n(C5,2), n(C5,4),
n(B4,8), n(C5,8), n(D5,2), n(C5,4),
ns(DS5,1),
n(DS5,1),
n(G5,4), n(C5,2), n(C5,4),
n(D5,4), n(DS5,4), n(D5,4), n(C5,4),
n(F5,4), n(C5,4), r(2),
r(2), r(4), n(C5,8), n(D5,8),
n(DS5,4), n(DS5,8), n(F5,8), n(D5,4), n(D5,8), n(DS5,8),
n(C5,4), n(C5,8), n(D5,8), n(B4,4), n(GS4,8), n(G4,8),
n(C5,1),
};
#if 0 /* XXX -------------------------------------------------------- */
static struct Note mario_overworld[] = {
mm(400), // XXX Not sure about this.
n(E5,4), n(E5,4), r(4), n(E5,4), r(4), n(C5,4), n(E5,4), r(4),
n(G5,4), r(4), r(4), r(4), n(G4,4), r(4), r(4), r(4),
n(C5,4), r(4), r(4), n(G4,4), r(4), r(4), n(E4,4), r(4),
r(4), n(A4,4), r(4), n(B4,4), r(4), n(AS4,4), n(A4,4), r(4),
n(G4,3), n(E5,3), n(G5,3), n(A5,4), r(4), n(F5,4), n(G5,4),
r(4), n(E5,4), r(4), n(C5,4), n(D5,4), n(B4,4), r(4), r(4),
n(C5,4), r(4), r(4), n(G4,4), r(4), r(4), n(E4,4), r(4),
r(4), n(A4,4), r(4), n(B4,4), r(4), n(AS4,4), n(A4,4), r(4),
n(G4,3), n(E5,3), n(G5,3), n(A5,4), r(4), n(F5,4), n(G5,4),
r(4), n(E5,4), r(4), n(C5,4), n(D5,4), n(B4,4), r(4), r(4)
};
static struct Note mario_underworld[] = {
{ NOTE_C4, 12 }, { NOTE_C5, 12 }, { NOTE_A3, 12 }, { NOTE_A4, 12 },
{ NOTE_AS3, 12 }, { NOTE_AS4, 12 }, { 0, 6 },
{ 0, 3 },
{ NOTE_C4, 12 }, { NOTE_C5, 12 }, { NOTE_A3, 12 }, { NOTE_A4, 12 },
{ NOTE_AS3, 12 }, { NOTE_AS4, 12 }, { 0, 6 },
{ 0, 3 },
{ NOTE_F3, 12 }, { NOTE_F4, 12 }, { NOTE_D3, 12 }, { NOTE_D4, 12 },
{ NOTE_DS3, 12 }, { NOTE_DS4, 12 }, { 0, 6 },
{ 0, 3 },
{ NOTE_F3, 12 }, { NOTE_F4, 12 }, { NOTE_D3, 12 }, { NOTE_D4, 12 },
{ NOTE_DS3, 12 }, { NOTE_DS4, 12 }, { 0, 6 },
{ 0, 6 }, { NOTE_DS4, 18 }, { NOTE_CS4, 18 }, { NOTE_D4, 18 },
{ NOTE_CS4, 6 }, { NOTE_DS4, 6 },
{ NOTE_DS4, 6 }, { NOTE_GS3, 6 },
{ NOTE_G3, 6 }, { NOTE_CS4, 6 },
{ NOTE_C4, 18 }, { NOTE_FS4, 18 }, { NOTE_F4, 18 },
{ NOTE_E3, 18 }, { NOTE_AS4, 18 }, { NOTE_A4, 18 },
{ NOTE_GS4, 10 }, { NOTE_DS4, 10 }, { NOTE_B3, 10 },
{ NOTE_AS3, 10 }, { NOTE_A3, 10 }, { NOTE_GS3, 10 },
{ 0, 3 }, { 0, 3 }, { 0, 3 },
};
static struct Note mario_death[] = {
{ NOTE_C5, 24 }, { NOTE_CS5, 24 }, { NOTE_D5, 36 }, { 0, 12 }, { 0, 6 },
{ NOTE_B4, 12 }, { NOTE_F5, 12 }, { 0, 12 }, { NOTE_F5, 12 },
{ NOTE_F5, 9 }, { NOTE_E5, 9 }, { NOTE_D5, 9 },
{ NOTE_C5, 12 }, { NOTE_E4, 12 }, { 0, 12 }, { NOTE_E4, 12 },
{ NOTE_C4, 12 }, { 0, 12 }, { 0, 6 },
};
/* http://www.8notes.com/scores/1110.asp */
static struct Note happy_birthday[] = {
n(C4,dot(8)), n(C4,16),
n(D4,4), n(C4,4), n(F4,4),
n(E4,2), n(C4,dot(8)), n(C4,16),
n(D4,4), n(C4,4), n(G4,4),
n(F4,2), n(C4,dot(8)), n(C4,16),
n(C5,4), n(A4,4), n(F4,4),
n(E4,4), n(D4,4), n(AS4,dot(8)), n(AS4,16),
n(A4,4), n(F4,4), n(G4,4),
n(F4,dot(2)),
};
/* https://youtu.be/xAMsLDQi2b0 */
static struct Note monkey_island_intro[] = {
mm(120),
ns(E4,16), ns(B4,16), ns(E5,16), ns(FS5,16), ns(FS5,dot(2)), n(FS5,1),
ns(E6,16), ns(B5,16), ns(G5,16), ns(FS5,16), n(FS5,2), n(D5,4),
n(E5,4), n(FS5,4), n(D5,4), n(E5,4),
n(B4,2), ns(G3,4), ns(A3,4),
ns(B3,1),
ns(D4,2), ns(CS4,2),
ns(D4,2), ns(E4,2),
ns(F4,4), ns(G4,4), ns(A4,2),
ns(B4,2), n(D5,2),
mm(88),
n(E3,16), ns(E4,16), ns(G4,16), n(E4,16), ns(B4,16), ns(G4,16), n(E4,8), n(D3,16), ns(D4,16), ns(F4,16), n(D4,16),
n(E3,16), ns(E4,16), ns(G4,16), n(E4,16), ns(B4,16), ns(G4,16), n(E4,8), n(D3,16), ns(D4,16), ns(F4,16), n(D4,16), n(E3,16), ns(E4,16), ns(G4,16), n(E4,16),
n(E5,8), ns(E5,16), ns(G5,16), ns(FS5,16), n(E5,16), n(D5,8), n(E5,4), r(4), n(D5,8),
ns(D5,16), ns(C5,16), ns(B4,16), ns(D5,16), n(C5,dot(8)), n(C5,dot(8)), n(B4,4), r(4), n(E5,dot(8)),
n(E5,dot(8)), ns(G5,16), ns(FS5,16), ns(E5,16), n(D5,8), ns(E5,4), n(E5,dot(8)), n(FS5,16),
n(G5,dot(8)), n(G5,dot(8)), n(A5,4), n(FS5,dot(8)), ns(G5,16), ns(FS5,16), ns(E5,16), ns(D5,16), ns(FS5,16),
n(G5,dot(8)), n(G5,dot(8)), n(FS5,4), n(E5,dot(8)), ns(G5,16), ns(FS5,16), ns(E5,16), ns(D5,16), ns(FS5,16),
n(G5,dot(8)), n(G5,dot(8)), n(FS5,4), n(E5,dot(8)), ns(G5,16), ns(FS5,16), ns(E5,16), ns(D5,8),
n(E5,dot(8)), n(E5,dot(8)), n(E5,dot(4)), n(E5,8), ns(D5,16), ns(C5,16), ns(B4,16), ns(D5,16), n(C5,dot(8)), n(C5,dot(8)),
n(B4,4), r(4), r(4),
r(4), r(4), n(B4,8), n(D5,8),
ns(C6,8), n(G5,8), n(G5,4), ns(C6,16), ns(B5,16), ns(A5,16), ns(C6,16),
ns(B5,8), n(G5,8), n(G5,dot(4)), n(B4,4), n(G5,8),
ns(A5,8), n(D5,8), n(D5,dot(8)), ns(A5,16), ns(B5,16), ns(A5,16), ns(G5,16), n(A5,16),
ns(B5,8), n(G5,dot(8)), ns(G5,8), n(E5,dot(8)), n(E5,4), n(F4,8), n(G4,8),
ns(A4,16), ns(F4,16), ns(C5,16), ns(A4,16), ns(F5,16), ns(C5,16), ns(A5,16), ns(F5,16), ns(C5,16), ns(A4,16), ns(F5,16), ns(C5,16), ns(A5,16), ns(F5,16), ns(C6,16), n(F6,16),
ns(G5,8), n(E5,dot(8)), n(E5,dot(8)), n(G5,16), n(FS5,dot(8)), n(G5,dot(8)), n(FS5,16), n(G5,16), n(E5,16), n(G5,16),
r(16), ns(C4,16), ns(G4,16), ns(DS4,16), ns(C5,16), ns(G4,16), ns(C5,16), ns(DS5,16), r(16), ns(G4,16), ns(E5,16), ns(C5,16), ns(G5,16), ns(E5,16), ns(G5,16), n(C6,16),
r(8), n(FS5,dot(8)), n(FS5,dot(8)), n(FS5,16), n(E5,dot(8)), n(FS5,dot(8)), n(E5,16), n(FS5,16), n(D5,8),
n(E5,dot(8)), ns(E5,16), ns(G5,16), ns(FS5,16), ns(E5,16), n(D5,dot(8)), n(E5,4), r(8), n(D5,8),
/* XXX WIP */
};
#endif /* XXX ------------------------------------------------------- */
#undef mm
#undef r
#undef s
#undef n
static void _play(const struct Note *score, size_t score_len, const char *name)
{
const struct Note *note;
unsigned int duration;
whole_note = 240000 / DEFAULT_MM;
if (name != NULL)
Serial.println(name);
for (size_t i = 0; i < score_len; ++i) {
note = &score[i];
assert(note_invariant(note));
if (note->n_type == NT_MM) {
/* MM * t/4 = 60s ==> t = 240s / MM */
whole_note = 240000 / note->n_value;
continue;
}
duration = whole_note / note->n_value;
if (note->n_type == NT_REST) {
delay(duration);
continue;
}
assert(note->n_type == NT_NOTE);
if (note->n_slur) {
buzz(note->n_frequency, duration);
} else {
buzz(note->n_frequency, 0.7 * duration);
delay(0.3 * duration); /* pause between notes */
}
}
}
#define play(score) _play(score, ARRAY_SIZE(score), #score)
/*
* `frequency' is the number of cycles per second.
* `duration' is measured in miliseconds.
*/
static void buzz(long frequency, long duration)
{
assert(frequency != 0);
digitalWrite(PIN_LED, HIGH);
/*
* Delay between transitions =
* 1 second's worth of microseconds / frequency / 2,
* where 2 is number of phases (HIGH and LOW) per cycle.
*/
long delay = 1000000 / frequency / 2;
long ncycles = frequency * duration / 1000;
for (long i = 0; i < ncycles; i++) {
digitalWrite(PIN_BUZZER, HIGH);
delayMicroseconds(delay);
digitalWrite(PIN_BUZZER, LOW);
delayMicroseconds(delay);
}
digitalWrite(PIN_LED, LOW);
}
/** Handle diagnostic informations given by assertion and abort program. */
void __assert(const char *__func, const char *__file, int __lineno,
const char *__sexp)
{
Serial.print(__file);
Serial.print(':');
Serial.print(__lineno, DEC);
Serial.print(" (");
Serial.print(__func);
Serial.print("): ");
Serial.println(__sexp);
Serial.flush();
abort();
}
void setup(void)
{
pinMode(PIN_BUZZER, OUTPUT);
pinMode(PIN_LED, OUTPUT);
Serial.begin(9600);
}
void loop()
{
/* play(mario_overworld); */
/* play(mario_underworld); */
/* play(mario_death); */
play(sherlock);
/* play(happy_birthday); */
/* play(monkey_island_intro); */
}
|
C
|
struct LCA {
vector<vector<int>> adj;
vector<vector<int>> p;
vector<int> h; // h[1] = 1
int n, logn = 0, root = 1;
LCA(int n): n(n) {
while ((1 << logn) <= n) logn++;
adj.resize(n + 1);
p = vector<vector<int>>(n + 1, vector<int>(logn + 1));
h.resize(n + 1);
}
// adding an edge to undirected tree, 1-based index
void addEdge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs(int u, int par) {
h[u] = h[par] + 1;
p[u][0] = par;
for (auto i: adj[u]) {
if (i != par) {
dfs(i, u);
}
}
}
void initJumps() {
for (int j = 1; j <= logn; j++) {
for (int i = 1; i <= n; i++) {
p[i][j] = p[p[i][j - 1]][j - 1];
}
}
}
// run this after adding all edges
void setup(int root = 1) {
dfs(root, 0);
initJumps();
}
int lca(int u, int v){
if (h[u] < h[v]) swap(u, v);
if (h[v] < h[u]) {
for (int i = logn; i >= 0; i--) {
if (h[p[u][i]] >= h[v]) u = p[u][i];
}
}
for (int i = logn; i >= 0; i--) {
if (p[u][i] != p[v][i]) {
u = p[u][i];
v = p[v][i];
}
}
if (u != v) u = p[u][0];
return u;
}
int getKthAnc(int u, int k) {
for (int i = logn; i >= 0; i--) {
if (k >= (1 << i)) {
k -= (1 << i);
u = p[u][i];
}
}
return u;
}
};
|
C
|
/*
** teams_tools.c for team tools in /home/mille_j/Documents/zappy/serveur/src/cmd_line
**
** Made by john mille
** Login <mille_j@epitech.net>
**
** Started on Wed Jun 15 09:01:04 2011 john mille
** Last update Fri Jul 8 23:37:51 2011 john mille
*/
#include <stdlib.h>
#include <stdio.h>
#include "zappy.h"
#include "my.h"
t_teams *create_team(char *name,
int id,
unsigned int max_members)
{
t_teams *new;
new = my_xmalloc(sizeof(*new));
new->name = my_strdup(name);
new->id = id;
new->nb_members = 0;
new->max_members = max_members;
new->max_members_init = max_members;
new->next = NULL;
return (new);
}
t_teams *add_team(t_teams *head, t_teams *new)
{
t_teams *fst;
if (head)
{
fst = head;
while (head->next)
head = head->next;
head->next = new;
return (fst);
}
return (new);
}
|
C
|
//
// Created by ayumu on 2020/06/12.
//
#include "model/token.h"
#include "lexer.h"
#include "../utility/string_util.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
Either(char*) consume_operator_lexer(char *str);
unsigned issignal(char ch);
unsigned isequal(char ch);
unsigned isoperator(char *str);
unsigned isid(char ch);
unsigned isbracket(char ch);
unsigned issemicolon(char ch);
Token *root_token;
Either(Token*) tokenize(char *str) {
root_token = root_token == NULL ? calloc(sizeof(Token), 1) : root_token;
*root_token = ROOT_TOKEN;
return _tokenize(str, root_token);
}
static Either(Token*) _tokenize(char *str, Token *token) {
if (str[0] == '\0') {
Token t = END_TOKEN;
new_token(t, token);
return (Either(Token*)) {.left = NULL, .right = (RIGHT_T *) root_token};
}
if (isspace(str[0]) || str[0] == '\n') return _tokenize(str + 1, token);
if (issemicolon(str[0])) {
return _tokenize(str + 1, ({
Token t = {.kind = T_SEMICOLON, .value = {str[0], '\0'}};
new_token(t, token);
}));
}
if (issignal(str[0])) {
return _tokenize(str + 1, ({
Token t = {.kind = T_SIGNAL, .value = {str[0], '\0'}};
new_token(t, token);
}));
}
if (isbracket(str[0])) {
return _tokenize(str + 1, ({
Token t = {.kind = T_BRACKET, .value = {str[0], '\0'}};
new_token(t, token);
}));
}
if (isoperator(str)) {
Either(char *) either = consume_operator_lexer(str);
if (is_left(either)) return either;
if (is_right(either)) {
char *next = (char *) either.right;
return _tokenize(next, ({
Token t = {.kind = T_OPERATOR, .value = 0};
long len = next - str;
strncpy(t.value, str, len);
new_token(t, token);
}));
}
}
if (isequal(str[0])) {
return _tokenize(str + 1, ({
Token t = {.kind = T_EQUAL, .value = {str[0], '\0'}};
new_token(t, token);
}));
}
if (isid(str[0])) {
return _tokenize(str + 1, ({
Token t = {.kind = T_ID, .value = {str[0], '\0'}};
new_token(t, token);
}));
}
return error_occurred("error in tokenize");
}
unsigned issignal(char ch) {
return ch == '1' || ch == '0';
}
unsigned isoperator(char *str) {
for (int i = binary_start; i < binary_end + 1; ++i) {
if (equal_substring(binary_name[i], str, strlen(binary_name[i]))) return true;
}
for (int i = unary_start; i < unary_end + 1; ++i) {
if (equal_substring(unary_name[i], str, strlen(unary_name[i]))) return true;
}
return false;
}
unsigned isbracket(char ch) {
return ch == '(' || ch == ')';
}
Either(char *) consume_operator_lexer(char *str) {
for (int i = binary_start; i < binary_end + 1; ++i) {
unsigned len = strlen(binary_name[i]);
if (equal_substring(binary_name[i], str, len)) return (Either(char*)) {.right = (RIGHT_T *) (str + len)};
}
for (int i = unary_start; i < unary_end + 1; ++i) {
unsigned len = strlen(unary_name[i]);
if (equal_substring(unary_name[i], str, len)) return (Either(char*)) {.right = (RIGHT_T *) (str + len)};
}
return ({
char message[256] = {0};
sprintf(message, "expect operator but got %s", str);
error_occurred(message);
});
}
unsigned isid(char ch) {
return 'a' <= ch && ch <= 'z';
}
unsigned isequal(char ch) {
return ch == '=';
}
unsigned issemicolon(char ch) {
return ch == ';';
}
|
C
|
#include <stdio.h>
#define MAXLINE 1000
int main() {
char *line = NULL;
char finalline[MAXLINE];
size_t linecap = 0;
ssize_t linelen;
int i, j,fi;
char c;
// read the line
while ((linelen = getline(&line, &linecap, stdin)) > 0 ) {
fi = 0;
for (i=0; (i < linelen) && (line[i] == '-'); i++) {;}
linelen--;
while (line[--linelen] == '-') { ; }
while (i<=linelen) {
if (line[i+1] == '-') {
j = i;
// chase the next non - symbol
while (line[++i] == '-') {;}
for (c=line[j]; c < line[i]; c++) {
finalline[fi++] = c;
}
} else {
finalline[fi++] = line[i++];
}
}
finalline[fi] = '\0';
printf("%s\n", finalline);
}
}
|
C
|
//LCD-keybard
//enter more than 4 digits --> 4 stars
//enter admin password --> flashing LED
sbit LCD_RS at RB4_bit; //or PORTB.RB4
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
unsigned short Userpass[15], kp;
//Keypad module connections
char keypadPort at PORTD; //used for keypad initialization
//end keypad module connections
char i;
char message[]="Elec402 KeyLock";
char pass[4]={'1','4','2','5'};
void code_enter(){
kp=0; //reset key code variable
//wait for the key to be pressed and released
do{
kp=Keypad_Key_Click(); //store key code in kp variable
}while(!kp);
//prepare value for output, transform key into it's ASCI value
switch(kp){
case 1: kp=49; break; //1 //or if we don't know the ASCII code we can write kp='1'
case 2: kp=50; break; //2
case 3: kp=51; break; //3
case 4: kp=65; break; //A
case 5: kp=52; break; //4
case 6: kp=53; break; //5
case 7: kp=54; break; //6
case 8: kp=66; break; //B
case 9: kp=55; break; //7
case 10: kp=56; break; //8
case 11: kp=57; break; //9
case 12: kp=67; break; //C
case 13: kp=42; break; //*
case 14: kp=48; break; //0
case 15: kp=35; break; //#
case 16: kp=68; break; //D
}
Userpass[i]=kp;
Lcd_Chr(2,i+1,'*');
i++;
}
void main() {
ANSEL = 0; //configure AN pins as digital
ANSELH = 0;
C1ON_bit = 0; //disable comparators
C2ON_bit = 0;
TRISE.F0=0; PORTE.F0=0;
Keypad_Init(); //Initializes port for working with the keyboard
Lcd_Init(); //Initilize LCD
Lcd_Cmd(_LCD_CLEAR); //Clear display
Lcd_Cmd(_LCD_CURSOR_OFF); //Cursor off
Lcd_Out(1,1,message); //write text in the first row
Delay_ms(1500); //give it time to initialize because the controller might be faster
do{
Lcd_Cmd(_LCD_Clear);
Lcd_Out(1,1,"Enter Password:");
i=0;
do{
code_enter();
Delay_ms(100);
}while(i<5);
if(Userpass[0]==pass[0] && Userpass[1]==pass[1] && Userpass[2]==pass[2] && Userpass[3]==pass[3] && Userpass[4]=='#'){ //
Lcd_Cmd(_LCD_CLEAR); //LCD Clear
Lcd_Out(1,4,"Door Open"); //Door Open
PORTE.F0=1;
Delay_ms(2000);
PORTE.F0=0;
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(1,4,"Door Closed");
Delay_ms(2000);
}
Userpass[0]=0; Userpass[1]=0;
Userpass[2]=0; Userpass[3]=0;
Userpass[4]=0;
}while(1);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
int *funk (int *tab1,int *tab2, int *tab3, int n)
{
int i;
int *tab4=malloc(n*sizeof(int*));
for (i=0;i<n;i++)
{
if (*tab1>=0) *(tab4+i)=*(tab2+i);
else *(tab4+i)=*(tab3+i);
}
return tab4;
}
int main ()
{
int a[4]={-1,-2,3,4},b[4]={1,3,5,7},c[4]={2,4,6,8},i;
int *tab4=funk(a,b,c,4);
for (i=0;i<4;i++) printf("%d",tab4[i]);
return 0;
}
|
C
|
#include<stdio.h>
void main(int h)
{
int i=0;
do
{
h=0;
printf("Height:");
i=scanf("%d",&h);
char c;
while((c = getchar()) != '\n' && c != EOF);
//printf("h:%d\n",h);
}
while( i==0 || h<=0 || h>23);
// printf("%d",h);
if(h>0 && h<24)
{
for(int i=0;i<h;i++)
{
for(int j=0;j<h;j++)
{
if(j<h-i-1)
{
printf(" ");
}
else
{
printf("#");
}
}
printf(" ");
for(int j=h+2;j<h+3+i;j++)
{
printf("#");
}
/*
for(int j=0;j<h+3+i;j++)
{
if(j<h-i-1)
{
printf(" ");
}
else if(j>=h-i-1 && j<h)
{
printf("#");
}
else if(j>=h+2)
{
printf("#");
}
else
{
printf(" ");
}
}
*/
printf("\n");
}
}
else
printf("\n");
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>
#include<sys/time.h>
#include<errno.h>
typedef struct{
int listenSd, connectSd;
struct sockaddr_in srvAddr, clntAddr;
int clntAddrLen, readLen, strLen;
char rBuff[BUFSIZ];
int maxFd;
fd_set defaultFds, rFds;
int res, i;
}allvalue;
void errProc(const char*);
void startServer(allvalue *,char **);
void binding(allvalue *);
void listening(allvalue *);
void reading(allvalue *);
void writing(allvalue *);
int main(int argc, char** argv)
{
allvalue all;
all.maxFd = 0;
if(argc !=2)
{
printf("Usage : %s [Port Number]\n",argv[0]);
return -1;
}
startServer(&all,argv);
binding(&all);
listening(&all);
FD_ZERO(&all.defaultFds);
FD_SET(all.listenSd, &all.defaultFds);
all.maxFd = all.listenSd;
all.clntAddrLen = sizeof(all.clntAddr);
while(1)
{
all.rFds = all.defaultFds;
printf("Monitoring ...\n");
if((all.res = select(all.maxFd + 1, &all.rFds, 0,0,NULL)) == -1) break;
for(all.i = 0; all.i<all.maxFd+1;all.i++)
{
if(FD_ISSET(all.i, &all.rFds))
{
if(all.i==all.listenSd)
{
all.connectSd = accept(all.listenSd, (struct sockaddr *)&all.clntAddr,&all.clntAddrLen);
if(all.connectSd == -1)
{
fprintf(stderr,"Accept Error");
continue;
}
fprintf(stderr,"A client is connected...\n");
FD_SET(all.connectSd, &all.defaultFds);
if(all.maxFd < all.connectSd)
{
all.maxFd = all.connectSd;
}
}
else
{
all.readLen = read(all.i , all.rBuff, sizeof(all.rBuff)-1);
if(all.readLen ==0)
{
fprintf(stderr,"A client is disconnected ... \n");
FD_CLR(all.i , &all.defaultFds);
close(all.i);
continue;
}
all.rBuff[all.readLen] = '\0';
printf("Client(%d): %s\n",all.i-3,all.rBuff);
write(all.i,all.rBuff, strlen(all.rBuff));
}
}
}
}
close(all.listenSd);
return 0;
}
void startServer(allvalue *all,char **argv)
{
printf("Server start...\n");
all->listenSd=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
if(all->listenSd == -1) errProc("socket");
memset(&all->srvAddr, 0, sizeof(all->srvAddr));
all->srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
all->srvAddr.sin_family = AF_INET;
all->srvAddr.sin_port = htons(atoi(argv[1]));
}
void binding(allvalue *all)
{
if(bind(all->listenSd,(struct sockaddr *)&all->srvAddr,sizeof(all->srvAddr))==-1)
errProc("bind\n");
}
void listening(allvalue *all)
{
if(listen(all->listenSd,5)<0) errProc("listen");
}
void errProc(const char *str)
{
fprintf(stderr, "%s: %s",str,strerror(errno));
exit(10);
}
|
C
|
#include "CHINESE.H"
FILE *hzk_p;
char mat0[32],mat1[72],mat2[128],mat3[288];
void chinese(int x,int y,char *s,int color,int type,char ziti)//x,y 输出位置 字符组 颜色 大小 字体
{
int a=x;
switch(type)
{
case 16:
switch(ziti)
{
case 'F':
open_hzk("hzk\\HZK16F");
break;
case 'H':
open_hzk("hzk\\HZK16H");
break;
case 'K':
open_hzk("hzk\\HZK16K");
break;
case 'S':
open_hzk("hzk\\HZK16S");
break;
}
break;
case 24:
switch(ziti)
{
case 'F':
open_hzk("hzk\\HZK24f");
break;
case 'H':
open_hzk("hzk\\HZK24h");
break;
case 'K':
open_hzk("hzk\\HZK24k");
break;
case 'S':
open_hzk("hzk\\HZK24s");
break;
}
break;
case 32:
switch(ziti)
{
case 'F':
open_hzk("hzk\\HZK32F");
break;
case 'H':
open_hzk("hzk\\HZK32H");
break;
case 'K':
open_hzk("hzk\\HZK32K");
break;
case 'S':
open_hzk("hzk\\HZK32S");
break;
}
break;
case 48:
switch(ziti)
{
case 'F':
open_hzk("hzk\\HZK48F");
break;
case 'H':
open_hzk("hzk\\HZK48H");
break;
case 'K':
open_hzk("hzk\\HZK48K");
break;
case 'S':
open_hzk("hzk\\HZK48S");
break;
}
break;
}
while (*s!=NULL)
{
while (x<1024 && (*s!=NULL))
{
dishz(x,y,s,color,type);
x+=(type+1);
s+=2;
}
x=a;
y+=(type+5);
}
// getch();
fclose(hzk_p);
}
void open_hzk(char * path)
{
hzk_p=fopen(path,"rb");
if (!hzk_p)
{
printf("The HZK does not exist! press any key to half\n");
getch();
exit(1);
}
}
void get_hz(char incode[],char bytes[],int type)
{
unsigned char qh,wh;
unsigned long offset;
unsigned long size;
size=type*type/8;
qh=incode[0]-0xa0; /*得到区号*/
wh=incode[1]-0xa0; /*得到位号*/
offset=(94*(qh-1)+(wh-1))*size; /*得到偏移位置*/
fseek(hzk_p,offset,SEEK_SET); /*移文件指针到要读取的汉字字模处*/
fread(bytes,size,1,hzk_p); /*读取32 个汉字的汉字字模*/
}
void dishz(int x0,int y0,char code[],int color,int type)
{
unsigned char mask[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};
/*屏蔽字模每行各位的数组*/
int i,j,x,y,pos;
int t;
switch(type)
{
case 16:
get_hz(code,mat0,type);
y=y0;
for (i=0;i<type;++i)
{
x=x0;
pos=type/8*i;
for(j=0;j<type;++j)
{
/*屏蔽出汉字字模的一个位,即一个点是1 则显示,否则不显示该点*/
if ((mask[j%8]&mat0[pos+j/8])!=NULL)
{
setpixel(x,y,color);
}
++x;
}
++y;
}
break;
case 24:
get_hz(code,mat1,type);
y=y0;
for (i=0;i<type;++i)
{
x=x0;
pos=type/8*i;
for(j=0;j<type;++j)
{
/*屏蔽出汉字字模的一个位,即一个点是1 则显示,否则不显示该点*/
if ((mask[j%8]&mat1[pos+j/8])!=NULL)
{
setpixel(x,y,color);
}
++x;
}
++y;
}
break;
case 32:
get_hz(code,mat2,type);
y=y0;
for (i=0;i<type;++i)
{
x=x0;
pos=type/8*i;
for(j=0;j<type;++j)
{
/*屏蔽出汉字字模的一个位,即一个点是1 则显示,否则不显示该点*/
if ((mask[j%8]&mat2[pos+j/8])!=NULL)
{
setpixel(x,y,color);
}
++x;
}
++y;
}
break;
case 48:
get_hz(code,mat3,type);
y=y0;
for (i=0;i<type;++i)
{
x=x0;
pos=type/8*i;
for(j=0;j<type;++j)
{
/*屏蔽出汉字字模的一个位,即一个点是1 则显示,否则不显示该点*/
if ((mask[j%8]&mat3[pos+j/8])!=NULL)
{
setpixel(x,y,color);
}
++x;
}
++y;
}
break;
}
}
void Read_Asc16(char key,unsigned char *buf)
{
int handle;
long address;
handle=open("hzk\\asc16",O_RDONLY|O_BINARY);
address=key*16l;
lseek(handle,address,SEEK_SET);
read(handle,buf,16);
close(handle);
}
void Put_Asc16(int cx,int cy,char key,int fcolor)
{
int a,b;
unsigned char buf[16];
Read_Asc16(key,buf);
for(a=0;a<16;a++)
for(b=0;b<8;b++)
if((buf[a]>>7-b)&1)
setpixel(cx+a,cy+b,fcolor);
}
void Put_Asc16_Size(int cx,int cy,int xsize,int ysize,char key,int fcolor)
{
int a,b,o,k;
unsigned char buf[16];
Read_Asc16(key,buf);
for(a=0;a<16;a++)
for(o=1;o<=ysize;o++)
for(b=0;b<8;b++)
for(k=1;k<=xsize;k++)
if((buf[a]>>7-b)&1)
setpixel(cx+b*xsize+k,cy+o+a*ysize,fcolor);
}
/* 显示英文和数字 */
void put_asc(int cx,int cy,int xsize,int ysize,char *s,int color )
{
int index;
for(index=0;s[index]!=0;index++)
{
Put_Asc16_Size(cx+index*xsize*8,cy,xsize,ysize,s[index],color);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Find the largest palindrome made from the product of two 3-digit numbers.
#define BUFFER_LEN 8
int is_palindrome(int p) {
char pstr[BUFFER_LEN];
snprintf(pstr, BUFFER_LEN, "%d", p);
int plen = strlen(pstr);
for(int i = 0; i < plen/2; i++) {
if(pstr[i] != pstr[plen-1-i]) {
return 0;
}
}
return 1;
}
int main(int argc, char* argv[]) {
int a = 0, b = 0;
for(int i = 999; i > 99; i--) {
for(int j = i; j > 99; j--) {
if(is_palindrome(i * j) && (i * j) > (a * b)) {
a = i;
b = j;
}
}
}
printf("Largest palindrome found: %d x %d = %d\n", a, b, a * b);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct Employee* create_node(struct Employee* );
struct Employee* insert(struct Employee* , struct Employee *);
struct Employee* delnode(struct Employee*,char *);
struct Employee *search(struct Employee * , char *, struct Employee **);
void display(struct Employee *);
struct Employee* create_list();
int isValid(char *);
int isValidPIN(int );
void Details(struct Employee *);
void updateCity(struct Employee *);
void updateContact(struct Employee *);
//"%lld
struct address
{
char city[20];
long long int contact;
};
struct Employee
{
char name[15];
char id[10];
struct address add;
char qualification[20];
struct Employee *left_child;
struct Employee *right_child;
};
struct Employee* create_node(struct Employee *root)
{
struct Employee *p,*parent,*temp;
p = malloc(sizeof(struct Employee));
parent = p;
printf("\n\t\t\t Enter the name of Employee : ");
fflush(stdin);
gets(p->name);
while(1)
{
printf("\n\t\t\t Enter the id of Employee Format(e.g. 19BCE246 ) : ");
gets(p->id);
int k = isValid(p->id);
if(k==0)
{
printf("\n\t\t\t Enter valid id !!");
}
else
{
temp = search(root,p->id,&parent);
if(temp == NULL)
break;
else
{
printf("\n\t\t\t The user with above id already exists.");
printf("\n\t\t\t Enter new ID");
}
}
}
printf("\n\t\t\t Enter the address of Employee ");
printf("\n\t\t\t City : ");
gets(p->add.city);
do
{
printf("\n\t\t\t Enter the CONTACT in the format 9640010451[only a 10-digit number]: ");
fflush(stdin);
scanf("%lld",&p->add.contact);
if(isValidContact(p->add.contact))
break;
else
printf("\n\t\t\t Contact Number should be exactly 10-digit number !!");
}while(1);
printf("\n\t\t\t Qualification : ");
fflush(stdin);
gets(p->qualification);
fflush(stdin);
p->left_child = NULL;
p->right_child = NULL;
return p;
}
struct Employee *insert(struct Employee *root,struct Employee *New)
{
int priority = strcmpi(root->id,New->id);
if(priority>0)
{
if(root->left_child == NULL)
root->left_child = New;
else
insert(root->left_child , New);
}
else if(priority<0)
{
if(root->right_child == NULL)
root->right_child = New;
else
insert(root->right_child , New);
}
}
struct Employee *delnode(struct Employee *root, char *id)
{
struct Employee *temp,*parent,*temp_succ;
temp = search(root,id,&parent);
if(temp == NULL)
{
printf("\n\t\t\t Sorry the Employee with the following id does not exist.");
return root;
}
else if(temp->left_child !=NULL && temp->right_child != NULL)
{
parent = temp;
temp_succ = temp->left_child;
while(temp_succ->left_child!=NULL)
{
parent = temp_succ;
temp_succ = temp_succ->left_child;
}
strcpy(temp->name,temp_succ->name);
strcpy(temp->id,temp_succ->id);
strcpy(temp->add.city,temp_succ->add.city);
temp->add.contact = temp_succ->add.contact;
strcpy(temp->qualification,temp_succ->qualification);
parent->left_child = NULL;
printf("\n\t\t\t Deleted Successfully");
return root;
}
else if(temp->left_child != NULL && temp->right_child == NULL)
{
if(temp == root)
{
root = temp -> left_child;
}
else if(parent->left_child == temp)
parent->left_child = temp->left_child;
else
parent->right_child = temp->left_child;
temp = NULL;
free(temp);
printf("\n\t\t\t Deleted Successfully");
return root;
}
else if(temp->left_child == NULL && temp->right_child != NULL)
{
if(temp == root)
{
root = temp -> right_child;
}
else if(parent->left_child == temp)
parent->left_child = temp->right_child;
else
parent->right_child = temp->right_child;
temp = NULL;
free(temp);
printf("\n\t\t\t Deleted Successfully");
return root;
}
else // if(temp->left_child == NULL && temp->right_child == NULL)
{
if(temp == root)
root = NULL;
else if(parent->left_child == temp)
parent->left_child = NULL;
else
parent->right_child = NULL;
printf("\n\t\t\t Deleted Successfully");
return root;
}
}
//This function is to find that if the entered ID by the user is valid [return 1] or not [return 0] according to the given conditions.
//For each and every invalidity, a proper message is printed along with returning the value 0
int isValid(char *id)
{
if(strlen(id)!=8) //If the entered ID length is not 8, it is invalid and a proper message is printed
{
printf("\n\t\t\t Not enough numbers of characters in the ID No.");
return 0;
}
if(isdigit(id[0]) && isdigit(id[1])){} //The entered ID should have numbers at index 0 and 1
else
{
printf("\n\t\t\t First 2 spaces of the ID needs to be integer.");
return 0;
}
if(isupper(id[2]) && isupper(id[3]) && isupper(id[4])) //The entered ID should have uppercase letters at index 2, 3 and 4
{
if(id[2]=='B' || id[2]=='M'){} ////The entered ID should have B or M at index 2
else
{
printf("\n\t\t\t4th character of the ID can be either 'B' or 'M'.");
return 0;
}
}
else
{
printf("\n\t\t\t Space number 3, 4 and 5 need to be UpperCase alphabets.\n");
return 0;
}
if(isdigit(id[5]) && isdigit(id[6]) && isdigit(id[7])){} //The entered ID should have numbers at index 5, 6 and 7
else
{
printf("\n\t\t\t Space number 6, 7 and 8 need to be numbers.\n");
return 0;
}
return 1; //If all conditions are satisfied, returned value is 1 i.e. ID is correct
}
//This function checks if the Contact Number entered by the user is valid[10-digit number] or not.
int isValidContact(long long int n)
{
int c = 0;
//long long int k = 10; //c counts the number of digits
while(n!=0) //Unless the contact number is 0, the loop will continue
{
n/=10; //Every time the loop is run, Contact Number is divided by 10
c++; //Every time the loop is run, counter is incremented by 1
}
if(c==10) //If number of digits counted is 10, returned value is 1
return 1;
else //Else the contact number is not valid
return 0;
}
//This function performs the task to find a searched node and return the pointer to the searched node or a NULL pointer if no ID id found
struct Employee *search(struct Employee *root , char *s, struct Employee **parent)
{
struct Employee *temp;
temp = root; //temporary node pointing to the Root of the BST
while(temp!=NULL) //Unless temp is NULL, loop will continue
{
if(strcmpi(temp->id , s)== 0)
{
printf("\n\t\t\t The name of the Employee is : %s",temp->name); //If the ID of a particular Employee matches the searched ID, it returns the pointer to the Employee Node it matched
return temp;
}
*parent = temp;
if(strcmpi(temp->id , s)> 0)
temp = temp->left_child; //If searched ID is lesser than the current node ID, it will navigate to the left node
else if(strcmpi(temp->id , s)< 0) //If searched ID is greater than the current node ID, it will navigate to the right node
temp = temp->right_child;
}
return NULL; //If no ID is matched in the BST, NULL pointer is returned
};
//This function performs the task to search for an employee in the Employee list and also displays the info about the employee
void Details(struct Employee *root)
{
struct Employee *temp,*parent;
char id_key[10];
printf("\n\t\t\t Enter the id of the Employee : "); //ID of the Employee to be searched
fflush(stdin);
gets(id_key); //ID scanned
int k = isValid(id_key); //To check if the format of the ID is correct
if(k==0) //If not correct,
printf("\n\t\t\t Enter valid id !!"); //Appropriate message is printed
else //ELSE
{
temp = search(root,id_key,&parent); //ID is being searched from the BST
if(temp == NULL) //If ID is not found, a proper message is printed
{
printf("\n\t\t\t Sorry the Employee with the following id does not exist.");
}
else //If ID is found
{
printf("\n\t\t\t Employee details"); //All the details of the employee is printed
printf("\n\t\t------------------------------------------\n");
printf("\n\t\t\t Name : %s",temp->name);
printf("\n\t\t\t Id : %s",temp->id);
printf("\n\t\t\t City : %s",temp->add.city);
printf("\n\t\t\t Contact : %lld",temp->add.contact);
printf("\n\t\t\t Qualification : %s",temp->qualification);
}
}
}
//This function is used to display the details of all the employees in ascending order according to their IDs.
//It displays all the nodes according to the InOrder Display.
//It follows the process of Recursion using the Stack.
//As per the ascending order of the IDs -> Name, ID, City, Contact No. and Qualification of the employee will be displayed.
void display(struct Employee *temp)
{
if(temp!=NULL)
{
display(temp->left_child); //This function calls the left child of the current node.
printf("\n\t\t------------------------------------------\n"); //This 6 lines prints Name, ID, City, Contact No. and Qualification of the employee.
printf("\n\t\t\t Name : %s",temp->name);
printf("\n\t\t\t Id : %s",temp->id);
printf("\n\t\t\t City : %s",temp->add.city);
printf("\n\t\t\t Contact : %lld",temp->add.contact);
printf("\n\t\t\t Qualification : %s",temp->qualification);
display(temp->right_child); //This function calls the right child of the current node.
}
}
//This function updates the residing city of the employee
void updateCity(struct Employee *root)
{
char id_key[10];
struct Employee *parent;
printf("\n\t\t\t Enter the id of the Employee whose City is to be updated : "); //The ID of the Employee is inputted
fflush(stdin); //Clears the input channel
gets(id_key); //City of the employee with this ID will be updated
int k = isValid(id_key); //To check if the entered ID of the employee is valid or not
if(k==0) //If invalid
printf("\n\t\t\t Enter valid id !!"); //a proper message is displayed
else //If Valid
{
struct Employee *node = search(root,id_key,&parent); //Node with the entered ID is searched
if(node==NULL) //If ID does not exist a NULL value will lead to termination of the function with an appropriate message.
{
printf("\n\t\t\tID does not exist.");
return;
} //ELSE
printf("\n\t\t\tEnter you new residential city : "); //New city is inputted
scanf("%s",node -> add.city); //New City is scanned
printf("\n\t\t\tNew city updated successfully."); //At the end , a valid message is printed
}
}
//This function updates the contact number of the employee
void updateContact(struct Employee *root)
{
char id_key[10];
struct Employee *parent;
printf("\n\t\t\t Enter the id of the Employee whose Contact is to be updated : "); //The ID of the Employee is inputted
fflush(stdin); //Clears the input channel
gets(id_key); //Contact of the employee with this ID will be updated
int k = isValid(id_key); //To check if the entered ID of the employee is valid or not
if(k==0) //If invalid
printf("\n\t\t\t Enter valid id !!"); //a proper message is displayed
else //If Valid
{
struct Employee *node = search(root,id_key,&parent); //Node with the entered ID is searched
if(node==NULL) //If ID does not exist a NULL value will lead to termination of the function with an appropriate message.
{
printf("\n\t\t\tID does not exist.");
return;
} //ELSE
printf("\n\t\t\tEnter you new contact number : "); //New contact is inputted
scanf("%lld", &node->add.contact); //New Contact is scanned
//New contact is assigned with the old contact
printf("\n\t\t\tNew Number updated successfully."); //At the end , a valid message is printed
}
}
void main()
{
printf("\n\n\n\n\n");
printf("\n\t\t\t **-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
printf("\n\t\t\t =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
printf("\n\t\t\t = WELCOME =");
printf("\n\t\t\t = TO =");
printf("\n\t\t\t = Employee Record =");
printf("\n\t\t\t = MANAGEMENT =");
printf("\n\t\t\t = SYSTEM =");
printf("\n\t\t\t =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
printf("\n\n\t\t\t**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
printf("\n\n\n\t\t\t Enter any key to continue.....");
getch();
system("cls");
printf("\t\t\t\t###########################################################################");
printf("\n\t\t\t############ ############");
printf("\n\t\t\t############ Employee Record Management System Project in C ############");
printf("\n\t\t\t############ ############");
printf("\n\t\t\t###########################################################################");
printf("\n\t\t\t---------------------------------------------------------------------------\n");
printf("\n\t\t\t----------------------------------------------------------------------------");
struct Employee *root,*New,*parent,*temp;
root = NULL;
char id_key[10];
while(1)
{
int n;
printf("\n\t\t\t MAIN MENU \n");
printf("\n\t\t\t 1 : Add an Employee");
printf("\n\t\t\t 2 : Delete an Employee");
printf("\n\t\t\t 3 : Display the Existing list");
printf("\n\t\t\t 4 : View Employee detail");
printf("\n\t\t\t 5 : Update Employee detail");
printf("\n\t\t\t 0 : exit the program");
printf("\n\n\t\t\t Enter your choice : ");
scanf("%d",&n);
switch(n)
{
case 1 :
if(root == NULL)
root = create_node(root);
else
{
New = create_node(root);
insert(root,New);
}
break;
case 2 :
if(root == NULL)
{
printf("\n\t\t\t No record exists !! ");
}
else
{
printf("\n\t\t\t Enter the id of Employee you wish to delete : ");
fflush(stdin);
gets(id_key);
int k = isValid(id_key);
if(k==0)
printf("\n\t\t\t Enter valid id !!");
else
{
root = delnode(root,id_key);
}
}
break;
case 3 :
if(root == NULL)
printf("\n\t\t\t Record is not created ");
else
{
printf("\n\t\t\t Employee details are as follows ");
printf("\n\t*******************************************************");
display(root);
}
break;
case 4 :
if(root == NULL)
{
printf("\n\t\t\t Create a list first (i.e. select option 1 to make the first entry).");
break;
}
else
{
Details(root);
}
break;
case 5 :
if(root == NULL)
{
printf("\n\t\t\tNo employee details to be updated.");
break;
}
int z;
printf("\n\t\t\t 1. To update your Residential City");
printf("\n\t\t\t 2. To update your Contact Number");
printf("\n\t\t\t Enter your choice : ");
scanf("%d",&z);
switch(z)
{
case 1:
updateCity(root);
break;
case 2:
updateContact(root);
break;
default:
printf("\n\t\t\tInvalid choice.");
break;
}
break;
case 0 :
printf("\n\n\n\n\n");
printf("\n\t\t\t **-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
printf("\n\t\t\t =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
printf("\n\t\t\t = Thank you =");
printf("\n\t\t\t = :) =");
printf("\n\t\t\t = Visit Again =");
printf("\n\t\t\t =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
printf("\n\n\t\t\t**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
exit(0);
break;
default :
printf("\n\t\t\t Wrong Input\n\t\t\t :( \n\t\t\t Try again\n\n");
fflush(stdin);
}
printf("\n-----------------------------------------------------------------------\n");
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* builtin_unalias.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmousson <mmousson@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/14 08:24:21 by mmousson #+# #+# */
/* Updated: 2019/05/24 21:09:54 by mmousson ### ########.fr */
/* */
/* ************************************************************************** */
#include "unalias.h"
/*
** Simply deletes an existing alias definition identified by 'token'
** from the current alias list
** We loop through the list, and if the 'token' argument is equals to
** the 'token' key of the list's link we are currently on, we delete
** all the keys, and the link itself, then update the list hierarchy
** After all is done, we return (0) the the built-in caller
**
** In case no match has been found, we return (1) and the main builtin
** function will display an appropriate error message
**
** Arguments:
** token -> The string identifier which will be used to find which alias
** definition needs to be deleted
**
** Return Value:
** 0 -> An alias definition matching the 'token' argument has been found
** and correctly deleted
** -1 -> No alias defintion matching the 'token' argument has been found,
** display an error message to the user
*/
static int delete_element(char *token)
{
t_alias *prev;
t_alias *current;
prev = NULL;
current = g_alias_list;
while (current)
{
if (ft_strequ(current->token, token))
{
if (prev)
prev->next = current->next;
else if (!prev)
g_alias_list = current->next;
ft_strdel(&(current->token));
ft_strdel(&(current->replacement));
ft_memdel((void **)&(current));
utility_write_alias_list_to_file();
return (0);
}
prev = current;
current = current->next;
}
return (-1);
}
/*
** This function will free all alias list's links and empty the file located
** in the user's HOME directory
**
** Arguments: NONE
**
** Return Value: Always (1)
*/
static int remove_all_aliases(void)
{
utility_free_alias_list();
utility_write_alias_list_to_file();
return (1);
}
/*
** ============================= BUITLIN COMMAND =============================
** Main function for the 'unalias' utility function
** Accepted option is "-a". Of course, this option will be ignored and treated
** as a regular argument if the double-hyphen operand "--" is provided
** beforehand
** Effect of "-a" option is to flush the entire alias list
** The normal behaviour of this utility is to delete every alias definition
** defined in each of the arguments
**
** Return Value:
** 0 -> Everything went well
** 1 -> An error occured
*/
int blt_unalias(int argc, char **argv, char ***env)
{
int options_on;
int ret;
(void)env;
ret = 0;
options_on = 1;
while (--argc > 0)
{
++argv;
if (options_on && ft_strequ("-a", argv[0]))
return (remove_all_aliases());
else if (options_on && ft_strequ("--", argv[0]))
{
options_on = 0;
continue;
}
else if (delete_element(argv[0]) == -1)
{
ft_putstr_fd("42sh: unalias: ", STDERR_FILENO);
ft_putstr_fd(argv[0], STDERR_FILENO);
ft_putendl_fd(": not found", STDERR_FILENO);
ret = 1;
}
}
return (ret);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstnew.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ydonse <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/19 10:51:17 by ydonse #+# #+# */
/* Updated: 2018/11/19 17:50:22 by ydonse ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
t_list *ft_lstnew(void const *content, size_t content_size)
{
t_list *liste;
if (!(liste = (t_list *)malloc(sizeof(t_list))))
return (NULL);
if (!content)
{
liste->content = NULL;
liste->content_size = 0;
}
else
{
if (!(liste->content = malloc(content_size)))
return (NULL);
ft_memcpy(liste->content, (void *)(content),
content_size);
liste->content_size = content_size;
}
liste->next = NULL;
return (liste);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int n;
int partition(int arr[n],int l,int h)
{
int pivot,i,j,temp;
pivot=arr[h];
i=l-1;
for(j=l;j<n;j++)
{
if(pivot>arr[j])
{
i++;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
temp=arr[i+1];
arr[i+1]=pivot;
arr[h]=temp;
printf("****************\n");
for(j=0;j<n;j++)
{
printf("%d\n",arr[j]);
}
return (i+1);
}
void quick(int arr[n],int l,int h)
{
int pi;
if(l<h)
{
pi=partition(arr,l,h);
quick(arr,l,pi-1);
quick(arr,pi+1,h);
}
}
int main()
{
scanf("%d",&n);
int i,arr[n];
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("**********\n");
quick(arr,0,n);
// for(i=0;i<n;i++)
//{
// printf("%d",arr[i]);
// }
}
|
C
|
/* Author: Marcus Ross
* MR867434
*/
#include <stdlib.h>
#include "list.h"
#include "const.h"
/* This function's arguments are a pointer to a hash table of struct opcodeNodes of size specified by the constant OPCODE_HASH_SIZE. It populates the hash table with instructions specified contained in the array specified by the constant INSTRUCTIONS. */
void buildOpcodeTable(opcodeNode** opcodeTable) {
opcodeNode *node;
char *instruction[NUM_INSTR] = INSTRUCTIONS; /* INSTRUCTIONS is an constant array holding all valid operations */
int iHash;
int i; /* for loop counter */
for (i = 0; i < NUM_INSTR; i++) { /* for each element of the instruction array */
node = (opcodeNode *) malloc(sizeof(opcodeNode));
iHash = hash(instruction[i], OPCODE_HASH_SIZE); /* get the hash of the instruction */
node->opcode = i; /* the instructions are ordered by opcode, ascending, so opcode = i */
node->instruction = instruction[i];
node->next = opcodeTable[iHash]; /* insert new node at the start of the list */
opcodeTable[iHash] = node;
}
}
/* This function's arguments are a pointer to a hash table of struct opcodeNodes, and a string containing an instruction. The hash table is searched for the instruction and the opcode of that instruction is returned as an int if it's found. If it's not found, -1 is returned. */
int findOpcode(opcodeNode** opcodeTable, char* instruction) {
int opcode = -1;
int iHash;
opcodeNode *node;
iHash = hash(instruction, OPCODE_HASH_SIZE); /* get the symbol's hash */
node = opcodeTable[iHash]; /* get the head of the list at that index */
while (node) { /* until the end of the list is reached */
if (strcmp(node->instruction, instruction) == 0) { /* if this node matches the argument */
opcode = node->opcode; /* this is the right node, so take the opcode */
break;
}
node = node->next; /* repeat with next node */
}
return opcode;
}
|
C
|
/*
This function converts the last pushed variable, which is assumed to
hold a string, to a list of one element. The string variable is
discarded after use. The formed list, containing one element, is copied
onto the stack to the former position of the string variable.
*/
#include "opcodefun.ih"
void o_atol()
{
Variable tmp;
listcons_charPtr(&tmp, string_charp(stack_top()));
virtual_assign(stack_top(), &tmp);
listDestructor(&tmp);
}
|
C
|
/**********************************************************************
* This code is representing my tests of Hashtable *
* Lab: OL-79 *
* Author: Yonatan Vologdin *
* Reviewer: Dvir Breitbart *
* Date: 28.12.19 *
**********************************************************************/
#include <stdio.h> /*printf*/
#include <stdlib.h> /*malloc ,free*/
#include <assert.h> /*assert*/
#include <math.h> /*sqrt*/
#include "hashtable.h"
#include "../../yoni_utils.h"
/*Uncomment the line below in order to activate white-box tests*/
#define WHITE_BOX_TEST
#ifdef WHITE_BOX_TEST
#include "dllist.h"
struct hash
{
hash_func_t hash_func;
is_match_t match_func;
size_t num_of_buckets;
dl_list_t **table;
};
#endif
int HashCreateTest();
int HashInsertTest();
int HashRemoveTest();
int HashFindTest();
int HashIsEmptyTest();
int HashSizeTest();
int HashForEachTest();
int HashGetLoadFactorTest();
int HashGetStandardDeviationTest();
size_t HashFunc(const void *key);
int IsMatch(const void *current_data, const void *data_to_compare);
int IsMatchDllist(const void *data, const void *param);
int CounterFunc(void *data, void *action_param);
int main()
{
RUN_SEQUENCE("HashCreateTest", HashCreateTest());
RUN_SEQUENCE("HashInsertTest", HashInsertTest());
RUN_SEQUENCE("HashRemoveTest", HashRemoveTest());
RUN_SEQUENCE("HashFindTest", HashFindTest());
RUN_SEQUENCE("HashIsEmptyTest", HashIsEmptyTest());
RUN_SEQUENCE("HashSizeTest", HashSizeTest());
RUN_SEQUENCE("HashForEachTest", HashForEachTest());
RUN_SEQUENCE("HashGetLoadFactorTest", HashGetLoadFactorTest());
RUN_SEQUENCE("HashGetStandardDeviationTest", HashGetStandardDeviationTest());
return 0;
}
int HashCreateTest()
{
hash_table_t *hash_table = HashCreate(10 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
HashDestroy(hash_table);
return 0;
}
int HashInsertTest()
{
int insert1 = 1;
int insert2 = 2;
int insert3 = 3;
int insert4 = 4;
int insert5 = 5;
int insert11 = 11;
int insert12 = 12;
int insert13 = 13;
int insert14 = 14;
int insert15 = 15;
#ifdef WHITE_BOX_TEST
dl_list_t **bucket = NULL;
dll_iter_t found_iter = NULL;
void *found_data = NULL;
#endif
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
RUN_TEST("insert1 successful", 0 == HashInsert(hash_table, &insert1));
RUN_TEST("insert2 successful", 0 == HashInsert(hash_table, &insert2));
RUN_TEST("insert3 successful", 0 == HashInsert(hash_table, &insert3));
RUN_TEST("insert4 successful", 0 == HashInsert(hash_table, &insert4));
RUN_TEST("insert5 successful", 0 == HashInsert(hash_table, &insert5));
RUN_TEST("insert11 successful", 0 == HashInsert(hash_table, &insert11));
RUN_TEST("insert12 successful", 0 == HashInsert(hash_table, &insert12));
RUN_TEST("insert13 successful", 0 == HashInsert(hash_table, &insert13));
RUN_TEST("insert14 successful", 0 == HashInsert(hash_table, &insert14));
RUN_TEST("insert15 successful", 0 == HashInsert(hash_table, &insert15));
#ifdef WHITE_BOX_TEST
bucket = hash_table->table + 0;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert1, IsMatchDllist);
RUN_TEST("wb find empty bucket", 1 == DLListIsSameIterator(DLListEnd(*bucket), found_iter));
bucket = hash_table->table + 0;
RUN_TEST("wb is bucket size", 0 == DLListSize(*bucket));
bucket = hash_table->table + 1;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert1, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert1", &insert1 == found_data);
bucket = hash_table->table + 1;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert11, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert11", &insert11 == found_data);
bucket = hash_table->table + 1;
RUN_TEST("wb is bucket size", 2 == DLListSize(*bucket));
bucket = hash_table->table + 2;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert2, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert2", &insert2 == found_data);
bucket = hash_table->table + 2;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert12, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert12", &insert12 == found_data);
bucket = hash_table->table + 2;
RUN_TEST("wb is bucket size", 2 == DLListSize(*bucket));
bucket = hash_table->table + 3;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert3, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert3", &insert3 == found_data);
bucket = hash_table->table + 3;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert13, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert13", &insert13 == found_data);
bucket = hash_table->table + 3;
RUN_TEST("wb is bucket size", 2 == DLListSize(*bucket));
bucket = hash_table->table + 4;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert4, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert4", &insert4 == found_data);
bucket = hash_table->table + 4;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert14, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert14", &insert14 == found_data);
bucket = hash_table->table + 4;
RUN_TEST("wb is bucket size", 2 == DLListSize(*bucket));
bucket = hash_table->table + 5;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert5, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert5", &insert5 == found_data);
bucket = hash_table->table + 5;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert15, IsMatchDllist);
found_data = DLListGetData(found_iter);
RUN_TEST("wb find insert15", &insert15 == found_data);
bucket = hash_table->table + 5;
RUN_TEST("wb is bucket size", 2 == DLListSize(*bucket));
#endif
HashDestroy(hash_table);
return 0;
}
int HashRemoveTest()
{
int insert1 = 1;
int insert2 = 2;
int insert3 = 3;
int insert4 = 4;
int insert5 = 5;
int insert11 = 11;
int insert12 = 12;
int insert13 = 13;
int insert14 = 14;
int insert15 = 15;
#ifdef WHITE_BOX_TEST
dl_list_t **bucket = NULL;
dll_iter_t found_iter = NULL;
#endif
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
HashInsert(hash_table, &insert1);
HashInsert(hash_table, &insert2);
HashInsert(hash_table, &insert3);
HashInsert(hash_table, &insert4);
HashInsert(hash_table, &insert5);
HashInsert(hash_table, &insert11);
HashInsert(hash_table, &insert12);
HashInsert(hash_table, &insert13);
HashInsert(hash_table, &insert14);
HashInsert(hash_table, &insert15);
HashRemove(hash_table, &insert1);
#ifdef WHITE_BOX_TEST
bucket = hash_table->table + 1;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert1, IsMatchDllist);
RUN_TEST("wb find removed insert 1", 1 == DLListIsSameIterator(DLListEnd(*bucket), found_iter));
bucket = hash_table->table + 1;
RUN_TEST("wb is bucket size\t", 1 == DLListSize(*bucket));
#endif
HashRemove(hash_table, &insert11);
#ifdef WHITE_BOX_TEST
bucket = hash_table->table + 1;
found_iter = DLListFind(DLListBegin(*bucket), DLListEnd(*bucket), &insert11, IsMatchDllist);
RUN_TEST("wb find removed insert 11", 1 == DLListIsSameIterator(DLListEnd(*bucket), found_iter));
bucket = hash_table->table + 1;
RUN_TEST("wb is bucket size\t", 0 == DLListSize(*bucket));
#endif
HashDestroy(hash_table);
return 0;
}
int HashFindTest()
{
int insert1 = 1;
int insert2 = 2;
int insert3 = 3;
int insert4 = 4;
int insert5 = 5;
int insert11 = 11;
int insert12 = 12;
int insert13 = 13;
int insert14 = 14;
int insert15 = 15;
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
HashInsert(hash_table, &insert1);
HashInsert(hash_table, &insert2);
HashInsert(hash_table, &insert3);
HashInsert(hash_table, &insert4);
HashInsert(hash_table, &insert5);
HashInsert(hash_table, &insert11);
HashInsert(hash_table, &insert12);
HashInsert(hash_table, &insert13);
HashInsert(hash_table, &insert14);
HashInsert(hash_table, &insert15);
RUN_TEST("found insert1", &insert1 == HashFind(hash_table, &insert1));
RUN_TEST("found insert2", &insert2 == HashFind(hash_table, &insert2));
RUN_TEST("found insert3", &insert3 == HashFind(hash_table, &insert3));
RUN_TEST("found insert4", &insert4 == HashFind(hash_table, &insert4));
RUN_TEST("found insert5", &insert5 == HashFind(hash_table, &insert5));
RUN_TEST("found insert11", &insert11 == HashFind(hash_table, &insert11));
RUN_TEST("found insert12", &insert12 == HashFind(hash_table, &insert12));
RUN_TEST("found insert13", &insert13 == HashFind(hash_table, &insert13));
RUN_TEST("found insert14", &insert14 == HashFind(hash_table, &insert14));
RUN_TEST("found insert15", &insert15 == HashFind(hash_table, &insert15));
HashDestroy(hash_table);
return 0;
}
int HashIsEmptyTest()
{
int insert1 = 1;
int insert2 = 2;
int insert3 = 3;
int insert4 = 4;
int insert5 = 5;
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
RUN_TEST("before inserts", 1 == HashIsEmpty(hash_table));
HashInsert(hash_table, &insert1);
HashInsert(hash_table, &insert2);
HashInsert(hash_table, &insert3);
HashInsert(hash_table, &insert4);
HashInsert(hash_table, &insert5);
RUN_TEST("after inserts", 0 == HashIsEmpty(hash_table));
HashRemove(hash_table, &insert1);
HashRemove(hash_table, &insert2);
HashRemove(hash_table, &insert3);
HashRemove(hash_table, &insert4);
HashRemove(hash_table, &insert5);
RUN_TEST("after removes", 1 == HashIsEmpty(hash_table));
HashDestroy(hash_table);
return 0;
}
int HashSizeTest()
{
int insert2 = 2;
int insert4 = 4;
int insert5 = 5;
int insert11 = 11;
int insert12 = 12;
int insert14 = 14;
int insert15 = 15;
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
RUN_TEST("before inserts", 0 == HashSize(hash_table));
HashInsert(hash_table, &insert2);
HashInsert(hash_table, &insert4);
HashInsert(hash_table, &insert5);
RUN_TEST("half inserts", 3 == HashSize(hash_table));
HashInsert(hash_table, &insert11);
HashInsert(hash_table, &insert12);
HashInsert(hash_table, &insert14);
HashInsert(hash_table, &insert15);
RUN_TEST("after inserts", 7 == HashSize(hash_table));
HashDestroy(hash_table);
return 0;
}
int HashForEachTest()
{
int insert1 = 1;
int insert2 = 2;
int insert3 = 3;
int insert4 = 4;
int insert5 = 5;
int insert11 = 11;
int insert12 = 12;
int insert13 = 13;
int insert14 = 14;
int insert15 = 15;
size_t counter = 0;
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
HashInsert(hash_table, &insert1);
HashInsert(hash_table, &insert2);
HashInsert(hash_table, &insert3);
HashInsert(hash_table, &insert4);
HashInsert(hash_table, &insert5);
HashInsert(hash_table, &insert11);
HashInsert(hash_table, &insert12);
HashInsert(hash_table, &insert13);
HashInsert(hash_table, &insert14);
HashInsert(hash_table, &insert15);
HashForEach(hash_table, CounterFunc, &counter);
RUN_TEST("counter", 10 == counter);
HashDestroy(hash_table);
return 0;
}
int HashGetLoadFactorTest()
{
int insert1 = 1;
int insert2 = 2;
int insert3 = 3;
int insert4 = 4;
int insert5 = 5;
double res = 0;
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
HashInsert(hash_table, &insert1);
HashInsert(hash_table, &insert2);
HashInsert(hash_table, &insert3);
HashInsert(hash_table, &insert4);
HashInsert(hash_table, &insert5);
res = HashGetLoadFactor(hash_table);
RUN_TEST("load factor", (5/6) == res);
HashDestroy(hash_table);
return 0;
}
int HashGetStandardDeviationTest()
{
int insert1 = 1;
int insert2 = 2;
int insert3 = 3;
int insert4 = 4;
int insert5 = 5;
double res = 0;
hash_table_t *hash_table = HashCreate(6 ,HashFunc, IsMatch);
if (NULL == hash_table)
{
return 1;
}
HashInsert(hash_table, &insert1);
HashInsert(hash_table, &insert2);
HashInsert(hash_table, &insert3);
HashInsert(hash_table, &insert4);
HashInsert(hash_table, &insert5);
res = HashGetStandardDeviation(hash_table);
RUN_TEST("stantard dev", 9.1287092917527690e-01 == res);
HashDestroy(hash_table);
return 0;
}
int CounterFunc(void *data, void *action_param)
{
UNUSE(data);
*(size_t *)action_param += 1;
return 0;
}
int IsMatchDllist(const void *data, const void *param)
{
return (*(int *)data == *(int *)param);
}
size_t HashFunc(const void *key)
{
size_t index = *(int *)key % 10;
return index;
}
int IsMatch(const void *current_data, const void *data_to_compare)
{
return (*(int *)current_data == *(int *)data_to_compare);
}
|
C
|
/*
============================================================================
Name : OpPhone.c
Author : leen
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define MAXSIZE 1024
#define ROWSIZE 200
#define APK_DIR_NAME "ApkDir"
#define ADB_DIR_NAME "Adb"
#define CFG_DIR_NAME "cfg"
#define CFG_FILE_NAME "setting"
#define CFG_SEC_TIME "Time"
char* get_current_path(char* szPath, int nLen)
{
int cnt = readlink("/proc/self/exe", szPath, nLen);
if(cnt<0 || cnt>=nLen)
{
printf("Error:Get current directory!\n");
return NULL;
}
int i;
for(i=cnt; i>=0; --i)
{
if(szPath[i] == '/')
{
szPath[i+1] = '\0';
break;
}
}
//printf("Current absolute path:%s\n", szPath);
return szPath;
}
//从INI文件读取字符串类型数据
char *GetIniKeyString(char *title, char *key, char *filename) {
FILE *fp;
char szLine[1024] = { 0 };
static char tmpstr[1024];
int rtnval;
int i = 0;
int flag = 0;
char *tmp;
if ((fp = fopen(filename, "r")) == NULL) {
printf("have no such file \n");
return "";
}
while (!feof(fp)) {
rtnval = fgetc(fp);
if (rtnval == EOF) {
break;
} else {
szLine[i++] = rtnval;
}
if (rtnval == '\n') {
//#ifndef WIN32
// i--;
//#endif
szLine[--i] = '\0';
i = 0;
tmp = strchr(szLine, '=');
if ((tmp != NULL) && (flag == 1)) {
if (strstr(szLine, key) != NULL) {
//注释行
if ('#' == szLine[0]) {
} else if ('/' == szLine[0] && '/' == szLine[1]) {
} else {
//找打key对应变量
strcpy(tmpstr, tmp + 1);
fclose(fp);
return tmpstr;
}
}
} else {
strcpy(tmpstr, "[");
strcat(tmpstr, title);
strcat(tmpstr, "]");
if (strncmp(tmpstr, szLine, strlen(tmpstr)) == 0) {
//找到title
flag = 1;
}
}
}
}
fclose(fp);
return "";
}
//从INI文件读取整类型数据
int GetIniKeyInt(char *title, char *key, char *filename) {
return atoi(GetIniKeyString(title, key, filename));
}
int install_android_apk(char* szApk)
{
char shellComm[MAXSIZE] = { 0 };
char szPath[MAXSIZE] = { 0 };
char szApkPath[MAXSIZE] = { 0 };
char szAdbPath[MAXSIZE] = { 0 };
get_current_path(szPath, MAXSIZE);
sprintf(szApkPath, "%s%s/%s", szPath, APK_DIR_NAME, szApk);
sprintf(szAdbPath, "%s%s/%s", szPath, ADB_DIR_NAME, "adb");
sprintf(shellComm, "%s install %s", szAdbPath, szApkPath);
system(shellComm);
return 0;
}
char* get_download_time()
{
char szPath[MAXSIZE] = { 0 };
get_current_path(szPath, MAXSIZE);
sprintf(szPath, "%s%s/%s", szPath, CFG_DIR_NAME, CFG_FILE_NAME);
char* szTime;
szTime= GetIniKeyString(CFG_SEC_TIME, "lastdownload", szPath);
return GetIniKeyString(CFG_SEC_TIME, "lastdownload", szPath);
}
int main(int argc, char* argv[]) {
//get_download_time();
if(argc<2 || !strcmp(argv[1], "--help"))
{
printf("The arguments is fault.The command should be \"OpPhone -op apk\" \n");
}
if(!strcmp(argv[1], "-i") || !strcmp(argv[1], "--install"))
install_android_apk(argv[2]);
//if(!strcmp(argv[1], "-l") || !strcmp(argv[1], "--last"))
return EXIT_SUCCESS;
}
|
C
|
#include "DHT11.h"
#include "delay.h"
#include "stdio.h"
void DHT11_output(){
GPIO_InitTypeDef settings;
settings.GPIO_Mode=GPIO_Mode_Out_PP;
settings.GPIO_Pin=DHT11_PIN_DATA;
settings.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&settings);
}
void DHT11_input(){
GPIO_InitTypeDef settings;
settings.GPIO_Mode=GPIO_Mode_IN_FLOATING;
settings.GPIO_Pin=DHT11_PIN_DATA;
settings.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&settings);
}
void DHT11_init(){
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
DHT11_output();
GPIO_SetBits(GPIOA,DHT11_PIN_DATA);//DHT11
delay_init();
}
void DHT11_begin(){
GPIO_ResetBits(GPIOA,DHT11_PIN_DATA);//DHT1120ms
delay_ms(25);
GPIO_SetBits(GPIOA,DHT11_PIN_DATA);//DHT1130us
delay_us(30);
}
void DHT11_waitAck(){
uint8_t time_out=200;
while(GPIO_ReadInputDataBit(GPIOA,DHT11_PIN_DATA) && time_out-->0)delay_us(1);//ȴDHT11
if(time_out==0)return;
time_out=200;
while(!GPIO_ReadInputDataBit(GPIOA,DHT11_PIN_DATA) && time_out-->0)delay_us(1);//ȴDHT11
if(time_out==0)return;
}
uint8_t DHT11_buffer[5];//ԭʼ
void DHT11_receive(){
uint8_t time_out;
for(uint8_t index=0;index<5;index++){
for(uint8_t index_bit=0;index_bit<8;index_bit++){
DHT11_buffer[index]<<=1;
time_out=200;
while(GPIO_ReadInputDataBit(GPIOA,DHT11_PIN_DATA) && time_out-->0)delay_us(1);//ȴDHT11
if(time_out==0)return;
time_out=200;
while(!GPIO_ReadInputDataBit(GPIOA,DHT11_PIN_DATA) && time_out-->0)delay_us(1);//ȴDHT11
if(time_out==0)return;
delay_us(50);
if(GPIO_ReadInputDataBit(GPIOA,DHT11_PIN_DATA)){
DHT11_buffer[index]|=1;
}else{
DHT11_buffer[index]&=~0x01;
}
}
}
}
uint8_t DHT11_update(){
DHT11_output();//лΪģʽ
DHT11_begin();//ʼź
DHT11_input();//лΪģʽ
DHT11_waitAck();//ȴDHT11Ӧ
DHT11_receive();//DHT11
DHT11_output();//лΪģʽ
GPIO_SetBits(GPIOA,DHT11_PIN_DATA);//
//У: 8bitУ=8bitʪ+8bitʪС+8bi¶+8bit¶С
if(((DHT11_buffer[0]+DHT11_buffer[1]+DHT11_buffer[2]+DHT11_buffer[3])&0xff)==DHT11_buffer[4]){
return 1;
}else{
return 0;
}
}
float DHT11_readTemp(){
float decimal=0;
decimal=DHT11_buffer[3];//¶8bitС
while(decimal>=1){
decimal/=10.0f;
}
return (float)DHT11_buffer[2]+decimal;
}
float DHT11_readHum(){
float decimal=0;
decimal=DHT11_buffer[1];//¶8bitС
while(decimal>=1){
decimal/=10.0f;
}
return (float)DHT11_buffer[0]+decimal;
}
|
C
|
Daniel Bonnin
CS362 Fall 2015
bonnind@oregonstate.edu
BugsInTeammates.c
This file contains documentation of the bugs I found during testing of
teammates` code for Assignment 5.
Teammate 1 (Victor Hernandez):
Name:
adventurerCard() causes segFault when deck is empty.
File:
dominion.c
Severity:
HIGH (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
drawCard() does not check for empty deck.
Status:
OPEN
Description:
When drawCard() is called in adventurerCard() on an empty
deck, it returns -1 and does not increment handCount.
adventurerCard() decrements handcount, however, so handCount
goes negative.
Steps to Reproduce:
Initialize a struct gameState with a handCount[0] and
deckCount[0] of 0. Call adventurerCard() on player 0.
Expected Results:
adventurerCard() should return with no change in state.
Name:
villageCard() not discarding card properly.
File:
dominion.c
Severity:
MEDIUM (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
discardCard() is being called with the trash flag set.
Status:
OPEN
Description:
villageCard() should discard the played Village card into
the playedCards array so that at the end of the turn, it
can be recycled into the current player's deck.
Instead, the card is simply being removed from play.
Steps to Reproduce:
Compare deckCount, handCount, playedCardsCount
and discardCount before and after calling villageCard().
Expected Results:
VillageCard should be in playedCards array.
Name:
great_hallCard() draws 2X too many cards into hand.
File:
dominion.c
Severity:
MEDIUM (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
drawCard() invoked twice.
Status:
OPEN
Description:
great_hallCard() should draw 1 card and add 1 action.
Instead, great_hallCard() draws 2 cards and adds 1 action.
Steps to Reproduce:
Compare handCount[0] before and after calling villageCard()
on player 0.
Expected Results:
handCount[0] should be increased by 1.
Name:
isGameOver() returns false negative on certain empty cards.
File:
dominion.c
Severity:
MEDIUM (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
Loop in isGameOver() does not iterate through all the card
types.
Description:
The halting condition in the for loop is i == 25, so it
does not reach treasure_map.
Therefore, if 2 card types are empty, and treasure_map is
empty, isGameOver returns false where it should return true.
Status:
OPEN
Steps to Reproduce:
Initialize a gameState in which values in supplyCoun**************
Expected Results:
handCount[0] should be increased by 1.
Teammate 2 (Billy Kerns):
Name:
adventureCard() causes segFault when deck is empty.
File:
dominion.c
Severity:
HIGH (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
drawCard() does not check for empty deck.
Status:
OPEN
Description:
When drawCard() is called in adventurerCard() on an empty
deck, it returns -1 and does not increment handCount.
adventurerCard() decrements handcount, however, so handCount
goes negative.
Steps to Reproduce:
Initialize a struct gameState with a handCount[0] and
deckCount[0] of 0. Call adventurerCard() on player 0.
Expected Results:
adventureCard() should return with no change in state.
Name:
adventureCard() loses 1 card from deck on every call.
File:
dominion.c
Severity:
MEDIUM (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
adventureCard() is not discarding temp array completely.
Description:
The while loop that iterates through tempArray to move all cards
to discard array, does not process every element of tempArray.
Therefore, the first non-treasure card that is drawn from the
deck after adventureCard() is invoked will be lost.
Status:
OPEN
Steps to Reproduce:
Initialize a gameState in which the deck[0] has as its first
4 elements: copper, copper, village, village. Initialize
discardCount[0] to 0. Set deckCount[0] to 4.
Call adventurerCard() on player 0.
Expected Results:
discardCount[0] should equal 2.
Name:
smithyCard() not discarding card properly.
File:
dominion.c
Severity:
MEDIUM (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
discardCard() is being called with the trash flag set.
Status:
OPEN
Description:
smithyCard() should discard the played Smithy card into
the playedCards array so that at the end of the turn, it
can be recycled into the current player's deck.
Instead, the card is simply being removed from play.
Steps to Reproduce:
Compare deckCount, handCount, playedCardsCount
and discardCount before and after calling smithyCard().
Expected Results:
Smithy Card should be in playedCards array.
Name:
isGameOver() returns false negative on certain empty cards.
File:
dominion.c
Severity:
MEDIUM (High/Medium/Low)
Priority:
MEDIUM (High/Medium/Low)
Reported Date:
11/19/2015
Reason:
Loop in isGameOver() does not iterate through all the card
types.
Description:
The halting condition in the for loop is i == 25, so it
does not reach treasure_map.
Therefore, if 2 card types are empty, and treasure_map is
empty, isGameOver returns false where it should return true.
Status:
OPEN
Steps to Reproduce:
Initialize a gameState in which value of
supplyCount[treasure_map] and 2 other elements of supplyCount are equal to 0.
Set all other elements to positive numbers. Call isGameOver() on this game state.
Expected Results:
isGameOver() should return 1.
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "../../color.h"
void show_infos(color_t* c) {
printf("c = ");
color_print_rgb(c);
printf("\n"
"c = ");
color_print_hsv(c);
printf("\n"
"alpha = %d\n\n", color_alpha(c));
}
int main(int argc, char* argv[]) {
int opt = 0;
color_t* c;
int i, j, k;
for (i = 0; i < argc; i++) {
if (**(argv + i) == '-') {
opt++;
switch (*(*(argv + i) + 1)) {
case 'h':
fprintf(stderr, "Usage: lzw-ppm [options] src\n");
fprintf(stderr, "options:\n");
fprintf(stderr, "\t-h prints this help\n");
fprintf(stderr, "\t-u to uncompress src\n");
return -1;
}
}
}
if (argc == 4) {
i = atoi(argv[1]);
j = atoi(argv[2]);
k = atoi(argv[3]);
c = color_create_rgb(i, j, k);
show_infos(c);
color_set_hsv(c, i, j, k);
show_infos(c);
free(c);
return 0;
}
// From RGB
// hsv(21, 255, 200)
c = color_create_rgb(200, 100, 0);
show_infos(c);
// hsv(64, 255, 200)
color_set_rgb(c, 100, 200, 0);
show_infos(c);
// hsv(106, 255, 200)
color_set_rgb(c, 0, 200, 100);
show_infos(c);
// hsv(149, 255, 200)
color_set_rgb(c, 0, 100, 200);
show_infos(c);
// hsv(235, 255, 200)
color_set_rgb(c, 200, 0, 100);
show_infos(c);
// hsv(191, 255, 200)
color_set_rgb(c, 100, 0, 200);
show_infos(c);
// hsv(0, 0, 0)
color_set_rgb(c, 0, 0, 0);
show_infos(c);
// hsv(0, 0, 255)
color_set_rgb(c, 255, 255, 255);
show_infos(c);
// From HSV
// rgb(0, 0, 0)
color_set_hsv(c, 200, 100, 0);
show_infos(c);
// rgb(0, 0, 0)
color_set_hsv(c, 100, 200, 0);
show_infos(c);
// rgb(100, 22, 22)
color_set_hsv(c, 0, 200, 100);
show_infos(c);
// rgb(200, 122, 122)
color_set_hsv(c, 0, 100, 200);
show_infos(c);
// rgb(100, 100, 100)
color_set_hsv(c, 200, 0, 100);
show_infos(c);
// rgb(200, 200, 200)
color_set_hsv(c, 100, 0, 200);
show_infos(c);
// rgb(0, 0, 0)
color_set_hsv(c, 0, 0, 0);
show_infos(c);
// rgb(255, 0, 0)
color_set_hsv(c, 255, 255, 255);
show_infos(c);
free(c);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct EDGE
{
int u,v;
int w;
}EDGE;
void Sort(EDGE arr[], int n)
{
int i, j;
EDGE tmp;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j].w > arr[j+1].w)
{
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
int aktar(EDGE * gr, int matris[100][100],int n)
{
int k=0,i,j;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(matris[i][j]!=0){
gr[k].u = i;
gr[k].v = j;
gr[k].w = matris[i][j];
k++;
}
}
}
return k;
}
void yaz(int labelCount,int * label,int n)
{
int d = 1;
int i,j=0;
while(d<=labelCount)
{
printf("\n%d. Gruptaki Dugumler",d);
for(i=0;i<n;i++)
{
if(label[i]==d)
{
printf(" %d ",i);
}
}
printf("\n");
d++;
}
}
int Kruskal(int kume,int k,int * label,int n,EDGE * gr)
{
int i=0;
int j=0;
int kalanDugum = n;
int labelCount = 0;
int uu;
int vv;
while( (kalanDugum > 0) && (j < k) )
{
if(kalanDugum != kume-labelCount)
{
uu=gr[j].u;
vv=gr[j].v;
if(label[uu]+label[vv]==0){
if(labelCount<kume)
{
labelCount++;
label[uu] = labelCount;
label[vv] = labelCount;
i++;
j++;
kalanDugum -= 2;
}
else
{
j++;
}
}
else
{
if(label[uu] == 0 || label[vv] == 0 )
{
if(label[uu]==0)
{
label[uu] = label[vv];
i++;
j++;
kalanDugum--;
}
else
{
label[vv] = label[uu];
i++;
j++;
kalanDugum--;
}
}
else
{
j++;
}
}
}
else
{
for(i=0;i<n;i++)
{
if(label[i]==0)
{
labelCount++;
label[i] = labelCount;
}
}
}
}
return labelCount;
}
int oku(int matris[100][100])
{
int a,i=0,j=0;
FILE * Dosya = fopen("data.txt","r");
while(!feof(Dosya)){
fscanf(Dosya,"%d",&a);
matris[i][j] = a;
j++;
if(fgetc(Dosya) != ',')
{
i++;
j = 0;
}
} return i;
}
void Mesafe(int a,int b,EDGE gr[],int *label,int n,int son){
int i,j,p;
while(j<son)
{
for(i=0;i<n;i++)
{
if( label[i]==a && i==gr[j].u)
{
for(p=0;p<n;p++)
{
if(label[p]==b && p==gr[j].v)
{
printf("En Kisa Mesafe = %d \n%d ile %d Dugumleri arasinda",gr[j].w,gr[j].u,gr[j].v);
return;
}
}
}
}
for(i=0;i<n;i++)
{
if( label[i]==b && i==gr[j].u)
{
for(p=0;p<n;p++)
{
if(label[p]==a && p==gr[j].v)
{
printf("En Kisa Mesafe = %d \n%d ile %d Dugumleri arasinda",gr[j].w,gr[j].u,gr[j].v);
return;
}
}
}
}
j++;
}
// gr[i].u
// gr[i].v
}
int main(){
int k=0,n;
int i=0,j=0;
int matris[100][100];
int *label;
int labelCount = 0;
int uu;
int vv;
int kume;
int kalanDugum;
EDGE gr[100];
n = oku(matris);
k = aktar(gr,matris,n);
Sort(gr,k);
label = (int*) malloc (sizeof(int)*n);
for(i=0;i<n;i++)
label[i] = 0;
printf("k sayisini giriniz");
scanf("%d",&kume);
labelCount = Kruskal(kume,k,label,n,gr);
yaz(labelCount,label,n);
int a,b;
printf("En Kisa Mesafe icin 2 Kume girin");
scanf("%d %d",&a,&b);
Mesafe(a,b,gr,label,n,k);
return 0;
}
|
C
|
#include <stdio.h>
/* (POLI 87) Dados n e uma seqncia de n nmeros inteiros, determinar quantos segmentos de nmeros iguais consecutivos compem essa seqncia.
Exemplo: A seguinte seqncia formada por 5 segmentos de nmeros iguais: 5, 2, 2, 3, 4, 4, 4, 4, 1, 1 */
int main()
{
int seq, cont, seqq, i;
printf("\n\tDeterminacao da quantidade de numeros iguais em uma sequencia.\n\n");
printf("Entre com a sequencia de numeros: ");
scanf("%d", &seq);
cont = 0;
seqq = seq;
for(i = 0; i < 10; i++){
while(seq > 0){
if((seq % 10) == i){
cont++;
}
seq /= 10;
}
seq = seqq;
}
printf("\nA sequencia %d possui %d seguimentos de numeros iguais.\n\n", seqq, cont);
return 0;
}
|
C
|
#ifndef MISC_H
#define MISC_H
typedef struct {
LOCK_T lock;
void *list_ptr ;
int count;
}dlist_t;
typedef struct {
void *next;
void *prev;
}dlist_element_t;
#define DLIST_RESET(dlist) { dlist->list_ptr=dlist->count=0; }
#define DLIST_APPEND(dlist,node) \
{ \
if(list_ptr==0) { \
list_ptr=node; \
else { \
(dlist_element*)node->next=dlist->list_ptr; \
(dlist_element*)list_ptr->prev=node; \
list_ptr=(void*)node; \
} \
dlist->count++; \
}
#define DLIST_REMOVE(dlist,node) \
{ \
dlist_element_t *prev; \
(node->prev!=0) { \
/* first element */ \
dlist->list_ptr =(dlist_element_t*)node->next; \
dlist->list_ptr->prev=0; \
}else { \
prev=(dlist_element_t*)node->prev; \
prev->next=node->next; \
node->next->prev=prev; \
MEM_FREE(node); \
} \
}
#endif
|
C
|
#include "../my_util.h"
/*
values, weights
arr[] = {{60, 10}, {100, 20}, {120, 30}}
6, 5, 4
Knapsack Capacity, W = 50;
*/
double fractional_knapsack(const vector<int>& values,
const vector<int>& weights, int W) {
struct Item {
int value = 0;
int weight = 0;
};
vector<Item> items(values.size());
double result = 0;
for (int i = 0; i < values.size(); i++) {
// Don't call push_back. since we already have reserved the memory.
items[i] = {values[i], weights[i]};
}
sort(items.begin(), items.end(), [](const Item& I1, const Item& I2) {
double IPW1 = (double)I1.value / (double)I1.weight;
double IPW2 = (double)I2.value / (double)I2.weight;
// Sort in decreasing Order
return IPW1 > IPW2;
});
int current_weight = 0;
for (auto item : items) {
if ((current_weight + item.weight) <= W) {
current_weight += item.weight;
result += item.value;
} else {
int remaining_weight = (W - current_weight);
result += remaining_weight * ((double)item.value / (double)item.weight);
break;
}
}
return result;
}
void test_fractional_knapsack() {
PRINT(fractional_knapsack({60, 100, 120}, {10, 20, 30}, 50));
PRINT_MSG;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("%d\n", 31);
printf("%o\n", 0x19);
printf("%x\n", 49);
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<search.h>
#pragma warning (disable:4996)
//void printf_arr1(int arr[3][5],int row,int col)
//{
// int i = 0;
// for(i = 0; i < row; i++){
// int j = 0;
// for(j = 0; j < col; j++){
// printf("%d",arr[i][j]);
// }
// printf("\n");
// }
//}
//void printf_arr2(int (*arr)[5],int row, int col)
//{
// int i = 0;
// for(i = 0; i < row; i++){
// int j = 0;
// for(j = 0; j < col; j++){
// printf("%d",arr[i][j]);
// }
// printf("\n");
// }
//}
//int int_cmp(const void *p1,const void *p2)
//{
// return (*(int *)p1 > *(int *)p2);
//}
//
//int int_cmp(const void *p1, const void *p2)
//{
// return (*(int *)p1 > *(int *)p2);
//}
//void _swap(void *p1, void *p2, int size)
//{
// int i = 0;
// for(i = 0; i < size; i++){
// char tmp = *((char *)p1 + i);
// *((char *)p1 + i) = *((char *)p2 + i);
// *((char *)p2 + i) = tmp;
// }
//}
//void bubble(void *base, int count, int size, int(*cmp)(void *,void *))
//{
// int i = 0;
// int j = 0;
// for(i = 0; i < count - 1; i++){
// for(j = 0; j < count-i-1; j++){
// if(cmp((char *)base + j*size,(char *)base + (j+1)*size) > 0){
// _swap((char *)base + j*size,(char *)base + (j+1)*size, size);
// }
// }
// }
//}
int main()
{
/*int arr[] = {1,3,5,7,9,2,4,6,8,0};
int i = 0;
bubble(arr, sizeof(arr)/sizeof(arr[0]),sizeof(int),int_cmp);
for(i = 0; i < sizeof(arr)/sizeof(arr[0]); i++){
printf("%d",arr[i]);
}
printf("\n");*/
/*qsortʹ*/
//int arr[] = {1,3,5,7,9,2,4,6,8,0};
//int i = 0;
//qsort(arr,sizeof(arr)/sizeof(arr[10]),sizeof(int),int_cmp);
//for(i = 0; i < sizeof(arr)/sizeof(arr[0]); i++){
// printf("%d",arr[i]);
//}
//printf("\n");
/*ָʹ*/
//int arr[3][5] = {1,2,3,4,5,6,7,8,9,10};
//printf_arr1(arr,3,5);
//arrʾַ
//άԪǶάĵһ
//ﴫݵarr,ʵ൱ڵһеĵַһάĵַ
//ָ
//printf_arr2(arr,3,5);
/*&*/
//int arr[10] = {0};
//printf("arr = %p\n",arr);//0046F9B8 Ԫصĵַ
//printf("&arr = %p\n",&arr);//0046F9B8 ĵַַָ
//printf("arr+1 = %p\n",arr+1);//0046F9BC arrarr+1ֵΪ4
//printf("&arr+1 = %p\n",&arr+1);//0046F9E0 &arr+1&arrֵΪ40ָ1Ǽָָ͵ĴС
//int *p1[10];//ָ
//int (*p2)[10];//ָ
//ַ
//char str1[] = "hello wanghong.";
//char str2[] = "hrllo wanghong.";
//char str3 = "hello wanghong.";
//char str4 = "hello wanghong.";
//if(str1 == str2){//str1str2ͬijַʼͬ飬ٳͬڴ顣
// printf("str1 and str2 are same\n");
//}
//else{
// printf("str1 and str2 are not same\n");
//}
//if(str3 == str4){//str3str4ָͬһڴ档
// printf("str3 and str4 are same\n");
//}
//else{
// printf("str3 and str4 are not same\n");
//}
system("pause");
return 0;
}
|
C
|
/* Program to search an element in the array using Binary search Technique
Example:
Enter array size:5
Enter elements:4 8 2 6 1
Enter number to search:6
6 is found at location 4*/
#include<stdio.h>
void search(int,int);
int arr[20];
void main()
{
int n,i,j,a,temp;
printf("Enter array size:");
scanf("%d",&n);
printf("Enter elements:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter number to search:");
scanf("%d",&a);
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j] > arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
/* for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}*/
search(n,a);
}
void search(int n,int a)
{
int i,first,last,mid;
int c=0;
first=0;
last=n-1;
while(first<=last)
{
mid=(first+last)/2;
if(arr[mid]==a)
{
c=1;
break;
}
else if(a < arr[mid])
{
last=mid-1;
}
else
{
first=mid+1;
}
}
if(c==0)
{
printf("Element not found");
}
else
{
printf("%d is found at location %d",a,mid+1);
}
}
|
C
|
/**
* pthread_mutex_timedlock函数实例
*
*当线程试图获取一个已经加锁的互斥量时,pthread_mutex_timedlock允许指定线程的阻塞时间,
*达到超时时间时,pthread_mutex_timedlock返回错误码ETIMEDOUT
*/
#include "apue.h"
#include <pthread.h>
#include <time.h>
int main(void)
{
int err;
struct timespec tout;
struct tm *tmp;
char buf[64];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock); /* 对互斥量加锁 */
printf("mutex a locked\n");
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("current time is %s\n", buf);
tout.tv_sec += 10; /* 从现在起等待超过10秒 */
// err = pthread_mutex_lock(&lock); /* 这会造成死锁 */
err = pthread_mutex_timedlock(&lock, &tout);
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("the time is now %s\n", buf);
if (err == 0) {
printf("mutex locked again!\n");
} else {
printf("can't lock mvtex again:%s\n", strerror(err));
}
exit(0);
}
/*
实验:
[dendi875@192 Chapter-11-Threads]$ ./timedlock
mutex a locked
current time is 11:45:12 PM
the time is now 11:45:22 PM
can't lock mvtex again:Connection timed out
struct timeval {
time_t tv_sec; // 秒
long tv_usec; // 微秒
};
struct timespec {
time_t tv_sec; // 秒
long tv_nsec; // 纳秒
};
*/
|
C
|
/*
Description: The ANSI C code of the PRVNS approach
Programmer: Wesklei Migliorini
E-mail: wesklei.m@gmail.com
Date: 04/11/2014
Lisence: Free
Note: The system was developed using Linux.
To compile: Type: make
To run: ./algorithm input.in
*/
#include "functions.h"
void prepararObjFunc(int* FUNCTION, double* lb, double* ub)/*{{{*/
{
switch (*FUNCTION) {
case 0: //Rastrigin
*lb = -5.12;
*ub = 5.12;
break;
case 1: //Schaffer
*lb = -100.00;
*ub = 100.00;
break;
case 2: //Griewank
*lb = -600.00;
*ub = 600.00;
break;
case 3: //Ackley
*lb = -32.00;
*ub = 32.00;
break;
case 4: //Rosenbrock
*lb = -30.00;
*ub = 30.00;
break;
case 5: //Sphere
*lb = -100.00;
*ub = 100.00;
break;
case 6: //MPE
*lb = 0;
*ub = 5;
break;
case 7: //SCHAFFER_F6
*lb = -100.00;
*ub = 100.00;
break;
case 8: //Generalized Schwefel's function 2.26
*lb = -500.00;
*ub = 500.00;
break;
case 9: // Step function
*lb = -100.00;
*ub = 100.00;
break;
case 11: // Generalized Penalized function #1
*lb = -500.00;
*ub = 500.00;
break;
case 12: // Levy Function
*lb = -10.00;
*ub = 10.00;
break;
case 13: // Zakharov
*lb = -5.00;
*ub = 10.00;
break;
case 14: // EggHolder
*lb = -512.00;
*ub = 512.00;
break;
case 15: // Holzman
*lb = -10.00;
*ub = 10.00;
break;
case 16: // Michalewitz
*lb = 0.00;
*ub = PI;
break;
case 17: // Generalized penalized function #2
*lb = -50.00;
*ub = 50.00;
break;
case 18: // Powell
*lb = -4.00;
*ub = 5.00;
break;
case 19: // Rana
*lb = -512.00;
*ub = 512.00;
break;
case 20: // Shubert
*lb = -10.00;
*ub = 10.00;
break;
case 21: //StretchedV
*lb = -10.00;
*ub = 10.00;
break;
case 22: // Multimod
*lb = -10.00;
*ub = 10.00;
break;
case 23: // Schwefels 222
*lb = -10.00;
*ub = 10.00;
break;
//Shifted functions
case 25: //Shifted Sphere
*lb = -100.00;
*ub = 100.00;
break;
case 26: //Shifted Schwefel's Problem 2.21
*lb = -100.00;
*ub = 100.00;
break;
case 27: //Shifted Rosenbrock
*lb = -100.00;
*ub = 100.00;
break;
case 28: //Shifted Rastrigin
*lb = -5.12;
*ub = 5.12;
break;
case 29: //Shifted Griewank
*lb = -600.00;
*ub = 600.00;
break;
case 30: //Shifted Ackley
*lb = -32.00;
*ub = 32.00;
break;
case 31: //Shifted Schwefel 2.22
*lb = -10.00;
*ub = 10.00;
break;
case 32: //Shifted Schwefel 1.2
*lb = -65.536;
*ub = 65.536;
break;
case 33: //Shifted Extended_f10
*lb = -100.00;
*ub = 100.00;
break;
case 34: //Shifted Bohachevsky
*lb = -15.00;
*ub = 15.00;
break;
case 35: //Shifted schaffer
*lb = -100.00;
*ub = 100.00;
break;
//Hybrid functions
case 36: //Hybrid 1
*lb = -100.00;
*ub = 100.00;
break;
case 37: //Hybrid 2
*lb = -5.00;
*ub = 5.00;
break;
case 38: //Hybrid 3
*lb = -10.00;
*ub = 10.00;
break;
case 39: //Hybrid 4
*lb = -100.00;
*ub = 100.00;
break;
case 40: //Hybrid 5
*lb = -100.00;
*ub = 100.00;
break;
case 41: //Hybrid 6
*lb = -100.00;
*ub = 100.00;
break;
case 42: //Hybrid 7
*lb = -5.00;
*ub = 5.00;
break;
case 43: //Hybrid 8
*lb = -10.00;
*ub = 10.00;
break;
default:
printf("Info: Invalid function.\n") ;
exit(0);
}
}/*}}}*/
double objfunc(double sol[],const int* FUNCTION, const int* DIM, int *cont)/*{{{*/
{
*cont+=1;
switch (*FUNCTION) {
case 0: //Rastrigin
return rastrigin(sol,*DIM);
case 1: //Schaffer
return schaffer(sol,*DIM);
case 2: //Griewank
return griewank(sol,*DIM);
case 3: //Ackley
return ackley(sol,*DIM);
case 4: //Rosenbrock
return rosenbrock(sol,*DIM);
case 5: //Sphere
return sphere(sol,*DIM);
case 6: //MPE
return mpe(sol,*DIM);
case 7: //SCHAFFER_F6
return schaffer_f6(sol,*DIM);
break;
case 8: //Generalized Schwefel's function 2.26
return g_schwefels(sol,*DIM);
break;
case 9: // Step Function
return step(sol,*DIM);
break;
case 11: // Generalized Penalized function #1
return penalized1(sol,*DIM);
break;
case 12: // Levy Function
return levy(sol,*DIM);
break;
case 13: // Zakharov
return zakharov(sol,*DIM);
break;
case 14: // EggHolder
return egg_holder(sol,*DIM);
break;
case 15: // Holzman
return holzman(sol,*DIM);
break;
case 16: // Michalewitz
return michalewitz(sol,*DIM);
break;
case 17: // Generalized Penalized function #2
return penalized2(sol,*DIM);
break;
case 18: // Powell
return powell(sol,*DIM);
break;
case 19: // Rana
return rana(sol,*DIM);
break;
case 20: // Shubert
return shubert(sol,*DIM);
break;
case 21: // StretchedV
return stretchedV(sol,*DIM);
break;
case 22: // Multimod
return multimod(sol,*DIM);
break;
case 23: // Schwefel's function 2.22
return schwefels222(sol,*DIM);
break;
//Shifted functions
case 25: //Shifted_Sphere
return shifted_sphere(sol,*DIM);
break;
case 26: //Shifted Schwefel Problem 2.21
return shifted_schwefel_221(sol,*DIM);
break;
case 27: //Shifted_Rosenbrock
return shifted_rosenbrock(sol,*DIM);
break;
case 28: //Shifted Rastrigin
return shifted_rastrigin(sol,*DIM);
break;
case 29: //Shifted Griewank
return shifted_griewank(sol,*DIM);
break;
case 30://Shifted Ackley
return shifted_ackley(sol,*DIM);
break;
case 31: //Shifted Schwefel 2.22
return shifted_schwefel_222(sol,*DIM);
break;
case 32: //Shifted Schwefel 1.2
return shifted_schwefel_12(sol,*DIM);
break;
case 33: //Shifted Extended_f10
return shifted_extended_f10(sol,*DIM);
break;
case 34: //Shifted Bohachevsky
return shifted_bohachevsky(sol,*DIM);
break;
case 35: //Shifted schaffer
return shifted_schaffer(sol,*DIM);
break;
//Hybrid functions
case 36: //Hybrid 1
return hybrid_1(sol,*DIM);
break;
case 37: //Hybrid 2
return hybrid_2(sol,*DIM);
break;
case 38: //Hybrid 3
return hybrid_3(sol,*DIM);
break;
case 39: //Hybrid 4
return hybrid_4(sol,*DIM);
break;
case 40: //Hybrid 5
return hybrid_5(sol,*DIM);
break;
case 41: //Hybrid 6
return hybrid_6(sol,*DIM);
break;
case 42: //Hybrid 7
return hybrid_7(sol,*DIM);
break;
case 43: //Hybrid 8
return hybrid_8(sol,*DIM);
break;
default:
printf("Info: Invalid function.\n") ;
exit(0);
}
}/*}}}*/
char *getFunctionName(int FUNCTION){/*{{{*/
switch (FUNCTION) {
case 0: //Rastrigin
return "Rastrigin";
case 1: //Schaffer
return "Schaffer F7";
case 2: //Griewank
return "Griewank";
case 3: //Ackley
return "Ackley";
case 4: //Rosenbrock
return "Rosenbrock";
case 5: //Sphere
return "Sphere";
case 6: //MPE
return "Molecular Potential Energy";
case 7: //SCHAFFER_F6
return "Schaffer F6";
break;
case 8: //G_SCHWEFELS
return "Generalized Schwefels 2.26";
break;
case 9: // Step function
return "Step";
break;
case 11: // Generalized Penalized function #1
return "Generalized Penalized function #1";
break;
case 12: // Levy
return "Levy";
break;
case 13: // Zakharov
return "Zakharov";
break;
case 14: // Egg holder
return "Egg holder";
break;
case 15: // Generalized Holzman
return "Generalized Holzman";
break;
case 16: // Michalewitz
return "Michalewitz";
break;
case 17: // Generalized penalized function #2
return "Generalized penalized function #2";
break;
case 18: // Powell
return "Powell";
break;
case 19: // Rana
return "Rana";
break;
case 20: // Shubert
return "Shubert";
break;
case 21: //StretchedV
return "StretchedV";
break;
case 22: //Multimod
return "Multimod";
break;
case 23: // Schwefel's function 2.22
return "Schwefel's function 2.22";
break;
//Shifted functions
case 25: //Shifted Sphere
return "Shifted Sphere";
break;
case 26: //Shifted Schwefel's Problem 2.21
return "Shifted Schwefel's Problem 2.21";
break;
case 27: //Shifted Rosenbrock
return "Shifted Rosenbrock";
break;
case 28: //Shifted Rastrigin
return "Shifted Rastrigin";
break;
case 29: //Shifted Griewank
return "Shifted Griewank";
break;
case 30: //Shifted Ackley
return "Shifted Ackley";
break;
case 31: //Shifted Schwefel 2.22
return "Shifted Schwefel 2.22";
break;
case 32: //Shifted Schwefel 1.2
return "Shifted Schwefel 1.2";
break;
case 33: //Shifted Extended_f10
return "Shifted Extended_f10";
break;
case 34: //Shifted Bohachevsky
return "Shifted Bohachevsky";
break;
case 35: //Shifted schaffer
return "Shifted Schaffer";
break;
//Hybrid functions
case 36: //Hybrid 1
return "Hybrid 1";
break;
case 37: //Hybrid 2
return "Hybrid 2";
break;
case 38: //Hybrid 3
return "Hybrid 3";
break;
case 39: //Hybrid 4
return "Hybrid 4";
break;
case 40: //Hybrid 5
return "Hybrid 5";
break;
case 41: //Hybrid 6
return "Hybrid 6";
break;
case 42: //Hybrid 7
return "Hybrid 7";
break;
case 43: //Hybrid 8
return "Hybrid 8";
break;
default:
printf("Info: Invalid function.\n") ;
exit(0);
}
}/*}}}*/
double rastrigin( double sol[], int DIM){/*{{{*/
//sol[] -> the population set
//DIM the dimension of sol[]
int j;
double top = 0.00;
for(j=0;j<DIM;j++)
{
top=top+(pow(sol[j],(double)2)-10*cos(2*M_PI*sol[j])+10);
}
return top;
}/*}}}*/
double schaffer( double sol[], int DIM){/*{{{*/
//sol[] -> the population set
//DIM the dimension of sol[]
int j;
double top = 0.00 , top1 = 0.00;
for(j=0;j<DIM;j++)
{
top=top+(pow(sol[j],(double)2));
}
top = pow(top,(double)0.25);
for(j=0;j<DIM;j++)
{
top1=top1+(pow(sol[j],(double)2));
}
top1=pow(top1,(double)0.1);
top1 = pow(sin(50*top1),(double)2) +1.0;
return top*top1;
}/*}}}*/
double griewank( double sol[], int DIM){/*{{{*/
//sol[] -> the population set
//DIM the dimension of sol[]
int j;
double top = 0.00 , top1 = 0.00, top2 = 0.00;
for(j=0;j<DIM;j++)
{
top1=top1+pow((sol[j]),(double)2);
top2=top2*cos((((sol[j])/sqrt((double)(j+1)))*M_PI)/180);
}
top=(1/(double)4000)*top1-top2+1;
return top;
}/*}}}*/
double ackley( double sol[], int DIM){/*{{{*/
//sol[] -> the population set
//DIM the dimension of sol[]
int i;
double aux = 0.0;
double aux1 = 0.0;
for (i = 0; i < DIM; i++)
{
aux += sol[i]*sol[i];
}
for (i = 0; i < DIM; i++)
{
aux1 += cos(2.0*M_PI*sol[i]);
}
return (-20.0*(exp(-0.2*sqrt(1.0/(float)DIM*aux)))-exp(1.0/(float)DIM*aux1)+20.0+exp(1));
}/*}}}*/
double rosenbrock( double sol[], int DIM){/*{{{*/
//sol[] -> the population set
//DIM the dimension of sol[]
int i;
double top = 0.00;
for (i = 0; i < DIM-1; i++)
{
top=top+100.*pow((sol[i+1] - pow(sol[i],2.)),2) + pow((1. - sol[i]),2);
}
return top;
}/*}}}*/
double sphere( double sol[], int DIM){/*{{{*/
//sol[] -> the population set
//DIM the dimension of sol[]
int j;
double top = 0.00;
for(j=0;j<DIM;j++)
{
top=top+sol[j]*sol[j];
}
return top;
}/*}}}*/
double shubert(double sol[], int DIM){/*{{{*/
//sol[] -> the population set
//DIM the dimension of sol[]
//Shubert
/*
- Domain |x| <= 10.0
- Number of local minimum = 400
- Global minimum fmin = -24.062499 at the ff. points
- (-6.774576, -6.774576), ..., (5.791794, 5.791794)
*/
double sum = 0.0;
int i;
for (i = 0; i < DIM; i++) {
sum += -sin(2.0*sol[i]+1.0)
-2.0*sin(3.0*sol[i]+2.0)
-3.0*sin(4.0*sol[i]+3.0)
-4.0*sin(5.0*sol[i]+4.0)
-5.0*sin(6.0*sol[i]+5.0);
}
return sum/(DIM/2.0);
}/*}}}*/
double schaffer_f6( double sol[], int DIM){/*{{{*/
double top=0;
double top1=0;
double top2=0;
int j;
for(j=0;j<DIM-1;j++)
{
top1 = pow( sin( sqrt( pow(sol[j],(double)2) + pow(sol[j+1],(double)2) ) ), (double)2) - 0.5;
top2 = pow( 1.0 + 0.001* ( pow(sol[j],(double)2) + pow(sol[j+1],(double)2) ), (double)2);
top = top + (0.5 + top1/top2);
}
return top;
}/*}}}*/
double g_schwefels( double sol[], int DIM){/*{{{*/
//known_optimal = -418.982887272433 at sol(i)=420.9687
int i;
double aux = 0.0;
for (i=0;i<DIM;i++)
{
aux += (-1 * sol[i]) * sin(sqrt(fabs(sol[i])));
}
return(aux);
}/*}}}*/
double mpe( double sol[], int DIM){/*{{{*/
//[0,5] fmin=-0.411183034 * n
int i;
double aux1=0.0,aux2=0.0;
for (i=0;i<DIM;i++)
{
aux1 += 1 + cos(3*sol[i]);
aux2 += (pow(-1,i) / (sqrt(fabs(10.60099896-4.141720682 * cos(sol[i])))));
}
return aux1 + aux2;
}/*}}}*/
double michalewitz( double sol[], int DIM){/*{{{*/
int i;
double aux;
//Michalewitz
/*
Dimension: n
Domain: 0< | x[i] | <= PI
Global minimum: x[] = -0.966*n
*/
aux=0;
for (i=0;i<DIM;i++) {
aux = aux + sin(sol[i]) * pow(sin((i+1)*sol[i]*sol[i]/(float)PI), 2.0 * 10.0);
}
return(-1*aux);
}/*}}}*/
double powell( double sol[], int DIM){/*{{{*/
int j;
double aux; //Powell
/*
Dimension: n > 4
Domain: -4<= x[i] <= 5
Global minimum: at (3, -1, 0, 1, ..., 3, -1, 0, 1) with fmin = 0
*/
aux = 0.0;
for (j = 1; j <= (int)DIM/4; j++) {
aux += pow(sol[4*j-4] + 10 * sol[4*j-3],2.0)
+ 5 * pow(sol[4*j-2] - sol[4*j-1],2.0)
+ pow(sol[4*j-3] - 2 * sol[4*j-2], 4.0)
+ 10 * pow(sol[4*j - 4] - sol[4*j-1], 4.0);
}
return aux;
}/*}}}*/
double levy( double sol[], int DIM)/*{{{*/
{
//Levy Function
double aux,*y;
int i;
//x[i] = 1 f(x[i])=0
y = (double*) malloc (DIM * sizeof(double));
for (i = 0; i< DIM; i++)
y[i] = 1+(sol[i]-1)/4.0;
aux = pow(sin(PI*y[0]),2.0);
for (i = 0; i<DIM-1;i++)
aux = aux + pow(y[i]-1,2.0)*(1+10*pow(sin(PI*y[i]+1),2.0));
aux = aux+pow(y[DIM-1]-1,2.0)*(1+pow(sin(2*PI*y[DIM-1]),2.0) );
free (y);
return ( aux );
}/*}}}*/
double zakharov( double sol[], int DIM)/*{{{*/
{
// Zakharov function //x[i] = 0 f(x[i])=0
//
double aux,aux1;
int j;
aux = aux1 = 0.0;
for (j = 0; j< DIM; j++)
{
aux = aux + pow(sol[j],2.0);
aux1 = aux1+0.5*j*sol[j];
}
return ( aux+pow(aux1,2.0)+pow(aux1,4.0) );
}/*}}}*/
double egg_holder( double sol[], int DIM)/*{{{*/
{
//Egg holder
/*
- Dimension: n
- Domain: -512 < | x_i | < 512
- Minimum for n=2 fmin(512, 404.2319) = -959.641
*/
double aux;
int i;
aux = 0.0;
for (i = 0; i < DIM-1; i++)
{
aux += -(sol[i+1] + 47.0) * sin(sqrt(fabs(sol[i+1] + sol[i] * 0.5 + 47.0))) + sin(sqrt(fabs(sol[i] - (sol[i+1] + 47.0)))) * (-sol[i]);
}
return (aux);
}/*}}}*/
double rana( double sol[], int DIM)/*{{{*/
{
//Rana
/*
Dimension: n
Domain: -520<= x[i] <= 520
Global minimum: ???
*/
double sum,t1,t2;
int i;
sum = 0.0;
for (i = 0; i < DIM-1; i++) {
/* if(sol[i] < -520.00f || sol[i] > 520.00f) */
/* printf("rana %f\n",sol[i]); */
t1 = sqrt(fabsf(sol[i+1] + sol[i] + 1.0));
t2 = sqrt(fabsf(sol[i+1] - sol[i] + 1.0));
sum += (sol[i+1] + 1.0) * cos(t2) * sin(t1) + cos(t1) * sin(t2) * sol[i];
}
return sum/(double)(DIM-1);
}/*}}}*/
double holzman( double sol[], int DIM){/*{{{*/
//Generalized Holzman
/*
Dimension: n
Domain: | x[i] | <= 10
Global minimum: 0 at x[i] = 0
*/
int i;
double aux = 0.0;
for (i = 0; i < DIM; i++)
{
aux += i * pow(sol[i] , 4);
}
return aux;
}/*}}}*/
double schwefels222( double sol[], int DIM){/*{{{*/
// Schwefel's function 2.22
/*
- Domain: | x_i | <= 10.0
Global minimum is 0.0 at x_i = 0.00
*/
int i;
double aux = 0.0,aux1=0.0;
for (i=0;i<DIM;i++)
{
aux += fabs(sol[i]);
aux1 *= fabs(sol[i]);
}
return (aux+aux1);
}/*}}}*/
double stretchedV( double sol[], int DIM){/*{{{*/
//StretchedV
/*
- Domain: | x_i | <= 10.0
Global minimum is 0.0 at x_i = 0.00
*/
double sum = 0.0;
double aux;
int i;
for (i = 0; i < DIM-1; i++) {
aux = sol[i+1]*sol[i+1] + sol[i]*sol[i];
sum += pow(aux, 0.25) * (pow(sin(50.0 * pow(aux, 0.1)), 2.0)+1.0);
}
return sum;
}/*}}}*/
double step(double sol[], int DIM){/*{{{*/
// Step function
/*
- Domain: | x_i | < 100.0
- Global minimum is 0.0 at x_i = 0.5
*/
double aux,aux1=0.0;
int i;
for (i=0;i<DIM;i++)
{
aux = (sol[i]+0.5);
aux1 += aux*aux;
}
return (aux1);
}/*}}}*/
double tempValue(double x,int a,int k,int m)/*{{{*/
{
double temp = 0.0;
if( x > a)
{
temp = k*pow(x-a,m);
}
else if( x <= a && x >= -a)
{
temp = 0.0;
}
else
{
temp = k*pow(-x-a,m);
}
return temp;
}/*}}}*/
double penalized1(double sol[], int DIM){/*{{{*/
//Generalized Penalized function #1
// -500 <= xi <= 500
//known_optimal = 1.57044103551786e-032;
double aux=0.0;
double aux1=0.0;
int i;
double *y = (double*) malloc (DIM * sizeof(double));
for (i=0;i<DIM;i++)
{
y[i]=0.0;
}
for (i=0;i<DIM;i++)
{
y[i]=1+(sol[i]+1)/4.0;
}
for (i=0;i<DIM-1;i++)
{
aux += pow(y[i]-1,2.0)*(1.0+10.0*pow(sin(PI*y[i+1]),2.0));
}
for (i=0;i<DIM;i++)
{
aux1 += tempValue(sol[i],10,100,4);
}
aux = (10.0*pow(sin(PI*y[0]),2.0)+aux+pow(y[DIM-1]-1,2))*PI/DIM+aux1;
free(y);
return ( aux );
}/*}}}*/
double penalized2(double sol[], int DIM){/*{{{*/
//Generalized Penalized function #2
//known_optimal = 1.34969464963992e-032;
double aux= 0.0;
double aux1=0.0;
int i;
for (i=0;i<DIM-1;i++)
{
aux += pow(sol[i]-1,2.0)*(1.0+10.0*pow(sin(3*PI*sol[i+1]),2.0));
}
for (i=0;i<DIM;i++)
{
aux1 += tempValue(sol[i],5,100,4);
}
return ( (pow(sin(3.0*PI*sol[0]),2.0)+aux+pow(sol[DIM-1]-1,2.0)
*(1.0+pow(sin(2.0*PI*sol[DIM-1]),2.0)))/10.0+aux1 );
}/*}}}*/
double multimod(double sol[], int DIM){/*{{{*/
//Multimod
/*
Dimension: n
Domain: -10<= x[i] <= 10
Global minimum: x[0] = 0
*/
double s,p,t;
int i;
s = p = fabs(sol[0]);
for (i = 1; i < DIM; i++) {
t = fabs(sol[i]);
s += t;
p *= t;
}
return s + p;
}/*}}}*/
//=== Shifted Functions
double shifted_sphere( double sol[], int DIM){/*{{{*/
// x* = o , F(x*) = f_bias1 = - 450
int i;
double Fx = 0.0;
double z = 0.0;
for(i=0;i<DIM;i++){
z = sol[i] - sphere_data[i];
Fx += z*z;
}
return Fx + f_bias[0];
}/*}}}*/
double shifted_schwefel_221( double sol[], int DIM){/*{{{*/
//Shifted Schwefel Problem 2.21
// x* = o , F(x*) = f_bias1 = - 450
int i;
double Fx = 0.0;
double z = 0.0;
Fx = abss(sol[0]);
for(i=1;i<DIM;i++){
z = sol[i] - schwefel_data[i];
Fx = max(Fx , abss(z));
}
return Fx + f_bias[1];
}/*}}}*/
double shifted_rosenbrock( double sol[], int DIM){/*{{{*/
int i;
double Fx = 0.0;
double zx[DIM];
//Shifted_Rosenbrock
// x* = o , F(x* ) = f_bias3 = 390
for(i=0;i<DIM;i++) zx[i] = sol[i] - rosenbrock_data[i] + 1;
for(i=0;i<DIM-1;i++){
Fx = Fx + 100*( pow((pow(zx[i],2)-zx[i+1]) , 2) ) + pow((zx[i]-1) , 2);
}
return Fx + f_bias[2];
}/*}}}*/
double shifted_rastrigin( double sol[], int DIM){/*{{{*/
int i;
double Fx = 0.0;
double z = 0.0;
double pi = acos(-1.0);
//Shifted Rastrigin
//x* = o , F( x * ) = f_bias4 = - 330
for(i=0;i<DIM;i++){
z = sol[i] - rastrigin_data[i];
Fx = Fx + ( pow(z,2) - 10*cos(2*pi*z) + 10);
}
return Fx + f_bias[3];
}/*}}}*/
double shifted_griewank( double sol[], int DIM){/*{{{*/
int i;
double z = 0.0;
double top1 = 0.00, top2 = 0.00;
//Shifted Griewank
//x* = o , F(x* ) = f_bias5 = -180
top1 = 0;
top2 = 1;
for(i=0;i<DIM;i++){
z = sol[i] - griewank_data[i];
top1 = top1 + ( pow(z,2) / 4000 );
top2 = top2 * ( cos(z/sqrt(i+1)));
}
return (top1 - top2 + 1 + f_bias[4]);
}/*}}}*/
double shifted_ackley( double sol[], int DIM){/*{{{*/
int i;
double Fx = 0.0;
double z = 0.0;
double top1 = 0.00, top2 = 0.00;
double pi = acos(-1.0);
double e = exp(1.0);
//Shifted Ackley
// x* = o , F(x* ) = f_bias6 = - 140
top1 = 0;
top2 = 0;
Fx = 0;
for(i=0;i<DIM;i++){
z = sol[i] - ackley_data[i];
top1 = top1 + pow(z , 2 );
top2 = top2 + cos(2*pi*z);
}
Fx = -20*exp(-0.2*sqrt(top1/DIM)) -exp(top2/DIM) + 20 + e + f_bias[5];
return Fx;
}/*}}}*/
double shifted_schwefel_222(double sol[], int DIM) /*{{{*/
{
double sum, currentGen, prod;
int i;
sum = 0.0;
prod = 1.0;
for (i = 0; i < DIM; i++)
{
currentGen = fabs(sol[i]-data_shif_schwefels_222[i]);
sum += currentGen;
prod *= currentGen;
}
return sum + prod;
}/*}}}*/
double shifted_schwefel_12(double sol[], int DIM)/*{{{*/
{
double Sum=0.0, Val=0.0;
int i;
for (i = 0; i < DIM; i++)
{
Val += sol[i]-data_shif_schwefels_12[i];
Sum += Val * Val;
}
return Sum;
}/*}}}*/
double f_10(double x, double y)/*{{{*/
{
double p, z, t;
p=(x*x+y*y);
z=pow(p, 0.25);
t=sin(50.0*pow(p, 0.1));
t=t*t+1.0;
return z*t;
}/*}}}*/
double shifted_extended_f10(double sol[], int DIM)/*{{{*/
{
double suma=0.0;
int i;
for(i=0; i<DIM-1; i++)
suma+=f_10(sol[i]-data_shif_extendedf10[i], sol[i+1]-data_shif_extendedf10[i+1]);
suma+=f_10(sol[DIM-1]-data_shif_extendedf10[DIM-1], sol[0]-data_shif_extendedf10[0]);
return suma;
}/*}}}*/
double shifted_bohachevsky(double sol[], int DIM) /*{{{*/
{
double sum = 0.0;
int i;
double currentGen;
double nextGen;
currentGen = sol[0]-data_shif_bohachevsky[0];
for (i = 1; i < DIM; i++)
{
nextGen = sol[i]-data_shif_bohachevsky[i];
sum += currentGen * currentGen + 2.0 * nextGen * nextGen;
sum += -0.3 * cos(3.0 * PI * currentGen) -0.4 * cos(4.0 * PI * nextGen) + 0.7;
currentGen = nextGen;
}
return sum;
}/*}}}*/
double shifted_schaffer(double sol[], int DIM) /*{{{*/
{
int i=0;
double sum;
double aux, aux2;
double currentGen, nextGen;
sum = 0.0;
currentGen = sol[0]-data_shif_schaffer[i];
currentGen = currentGen * currentGen;
for (i = 1; i < DIM; i++)
{
nextGen = sol[i]-data_shif_schaffer[i];
nextGen = nextGen * nextGen;
aux = currentGen + nextGen;
currentGen = nextGen;
aux2 = sin(50. * pow(aux, 0.1));
sum += pow(aux, 0.25) * (aux2 * aux2 + 1.0);
}
return sum;
}/*}}}*/
//=== Hybrid Functions
static void divideFunctions(double sol[], int DIM, double *part1, double *part2, double m, int *psize1, int *psize2) {/*{{{*/
int shared;
int rest, i, total;
double *partrest;
if (m <= 0.5) {
partrest = part2;
}
else {
partrest = part1;
m = 1-m;
}
shared = (int) floor(DIM*m);
rest = 2*shared;
for (i = 0; i < shared; i++) {
part1[i] = sol[i*2];
part2[i] = sol[i*2+1];
}
total = DIM-shared;
for (i = 0; i < total-shared; i++) {
partrest[i+shared] = sol[i+rest];
}
*psize1 = shared;
*psize2 = DIM-shared;
if (partrest == part1) {
int temp = *psize1;
*psize1 = *psize2;
*psize2 = temp;
}
}/*}}}*/
double Extended_f_10NoDesplazamiento(double sol[], int DIM)/*{{{*/
{
double suma=0.0;
int i;
for(i=0; i<DIM-1; i++)
suma+=f_10(sol[i], sol[i+1]);
suma+=f_10(sol[DIM-1], sol[0]);
return suma;
}/*}}}*/
double f_BohachevskyNoDesplazamiento(double sol[], int DIM) /*{{{*/
{
double sum = 0.0;
int i;
double currentGen;
double nextGen;
currentGen = sol[0];
for (i = 1; i < DIM; i++)
{
nextGen = sol[i];
sum += currentGen * currentGen + 2.0 * nextGen * nextGen;
double c1=cos(3.0 * PI * currentGen);
double c2=cos(4.0 * PI * nextGen);
sum += 0.7 -(0.3*c1+0.4*c2);
currentGen = nextGen;
}
return sum;
}/*}}}*/
double f_Schwefel2_22NoDesplazamiento(double sol[], int DIM) /*{{{*/
{
double sum, currentGen, prod;
sum = 0.0;
prod = 1.0;
int i;
for (i = 0; i < DIM; i++)
{
currentGen = fabs(sol[i]);
sum += currentGen;
prod *= currentGen;
}
return sum + prod;
}/*}}}*/
double hybrid_1(double sol[], int DIM) /*{{{*/ //12
{
double part1[DIM], part2[DIM];
int size1, size2;
double f1, f2;
divideFunctions(sol, DIM, part1, part2, 0.25, &size1, &size2);
f1=Extended_f_10NoDesplazamiento(part1,size1);
f2=shifted_sphere(part2,size2)-f_bias[0];
assert(f1 >= 0);
assert(f2 >= 0);
return f1+f2;
}/*}}}*/
double hybrid_2(double sol[], int DIM) /*{{{*/ //13
{
double part1[DIM], part2[DIM];
int size1, size2;
double f1, f2;
divideFunctions(sol, DIM, part1, part2, 0.25, &size1, &size2);
f1=Extended_f_10NoDesplazamiento(part1,size1);
f2=shifted_rosenbrock(part2,size2)-f_bias[2];
return f1+f2;
}/*}}}*/
double hybrid_3(double sol[], int DIM) /*{{{*/ //14
{
double part1[DIM], part2[DIM];
int size1, size2;
double f1, f2;
divideFunctions(sol, DIM, part1, part2, 0.25, &size1, &size2);
f1=Extended_f_10NoDesplazamiento(part1,size1);
f2=shifted_rastrigin(part2,size2)-f_bias[3];
return f1+f2;
}/*}}}*/
double hybrid_4(double sol[], int DIM) /*{{{*/ //15
{
double part1[DIM], part2[DIM];
double desp[DIM];
int size1, size2;
double f1, f2;
int i;
for (i = 0; i < DIM; ++i) {
desp[i] = sol[i] - f15[i];
}
divideFunctions(desp, DIM, part1, part2, 0.25, &size1, &size2);
f1=f_BohachevskyNoDesplazamiento(part1, size1);
f2=f_Schwefel2_22NoDesplazamiento(part2, size2);
return f1+f2;
}/*}}}*/
double hybrid_5(double sol[], int DIM) /*{{{*/ //16new
{
double part1[DIM], part2[DIM];
int size1, size2;
double f1, f2;
divideFunctions(sol, DIM, part1, part2, 0.5, &size1, &size2);
f1=Extended_f_10NoDesplazamiento(part1,size1);
assert(f1 >= 0);
f2=shifted_sphere(part2, size2)-f_bias[0];
assert(f2 >= 0);
return f1+f2;
}/*}}}*/
double hybrid_6(double sol[], int DIM) /*{{{*/ //17new
{
double part1[DIM], part2[DIM];
int size1, size2;
double f1, f2;
divideFunctions(sol, DIM, part1, part2, 0.75, &size1, &size2);
f1=Extended_f_10NoDesplazamiento(part1, size1);
f2=shifted_rosenbrock(part2, size2)-f_bias[2];
return f1+f2;
}/*}}}*/
double hybrid_7(double sol[], int DIM) /*{{{*/ //18new
{
double part1[DIM], part2[DIM];
int size1, size2;
double f1=0;
double f2=0;
divideFunctions(sol, DIM, part1, part2, 0.75, &size1, &size2);
f1=Extended_f_10NoDesplazamiento(part1, size1);
f2=shifted_rastrigin(part2, size2)-f_bias[3];
assert(isfinite(f1));
assert(isfinite(f2));
return f1+f2;
}/*}}}*/
double hybrid_8(double sol[], int DIM) /*{{{*/ //19new
{
double part1[DIM], part2[DIM];
int size1, size2;
double desp[DIM];
double f1, f2;
int i;
for (i = 0; i < DIM; ++i) {
desp[i] = sol[i] - f19[i];
}
divideFunctions(desp, DIM, part1, part2, 0.75, &size1, &size2);
f1=f_BohachevskyNoDesplazamiento(part1, size1);
f2=f_Schwefel2_22NoDesplazamiento(part2, size2);
return f1+f2;
}/*}}}*/
|
C
|
#include "alloc.h"
#include "error.h"
#include <stdlib.h>
#include <stdio.h>
#include <SDL2/SDL.h>
void sn_abort(const char *reason)
{
// TODO:
// 1: should not be allocating memory in an error handler
// 2: should not be blindly using a 1024 character buffer for the error message
// 3: should not be repeating this for both error handlers
char *message = sn_alloc(SN_ERROR_BUFFER_LENGTH * sizeof(char));
snprintf(message, SN_ERROR_BUFFER_LENGTH, "Critical failure: %s\n", reason);
sn_show_error(message);
sn_free(message);
abort();
}
void sn_sdl_error()
{
char *message = sn_alloc(SN_ERROR_BUFFER_LENGTH * sizeof(char));
snprintf(message, SN_ERROR_BUFFER_LENGTH, "SDL Error: %s\n", SDL_GetError());
sn_show_error(message);
sn_free(message);
abort();
}
static void sn_show_error(const char *message)
{
int result = SDL_ShowSimpleMessageBox(
SDL_MESSAGEBOX_ERROR,
"Error",
message,
NULL);
if (result != 0)
{
fputs(message, stderr);
}
}
|
C
|
/*
* NXHelp - demo.c
* by Lance Lovette
* Code and display copyright 1992, by Lance Lovette.
* All Rights Reserved
*
* This code demonstrates the creation of a help menu
* on the menu bar using the help facility described in the README.
*/
#include <Xm/Xm.h>
#include <Xm/Label.h>
#include <Xm/Form.h>
#include <Xm/PushB.h>
#include <Xm/RowColumn.h>
#include <Xm/CascadeB.h>
#include "NXHelp.h" /* Include file for help callbacks. */
#define HELPFILE "demo.hlp"
XtAppContext context;
XmStringCharSet char_set=XmSTRING_DEFAULT_CHARSET;
Widget toplevel, form, label, menu_bar;
Widget file_menu;
Widget quit_item;
Widget help_menu;
Widget overviewButton;
Widget aboutButton;
Widget deferredButton;
Widget hiddenButton;
Widget indexButton;
void menuCB(w,client_data,call_data)
Widget w;
char *client_data;
XmAnyCallbackStruct *call_data;
/* callback routine used for all menus */
{
if (strcmp(client_data,"Quit")==0) /* if quit seen, then exit */
exit(0);
}
Widget make_menu_item(item_name,client_data,menu)
char *item_name;
caddr_t client_data;
Widget menu;
/* adds an item into a menu. */
{
int ac;
Arg al[10];
Widget item;
ac = 0;
XtSetArg(al[ac],XmNlabelString,
XmStringCreateLtoR(item_name,char_set)); ac++;
item=XmCreatePushButton(menu,item_name,al,ac);
XtManageChild(item);
XtAddCallback(item,XmNactivateCallback,menuCB,client_data);
XtSetSensitive(item,True);
return(item);
}
Widget make_menu(menu_name,menu_bar)
char *menu_name;
Widget menu_bar;
/* creates a menu on the menu bar */
{
int ac;
Arg al[10];
Widget menu, cascade;
menu=XmCreatePulldownMenu(menu_bar,menu_name,NULL,0);
ac=0;
XtSetArg (al[ac],XmNsubMenuId, menu); ac++;
XtSetArg(al[ac],XmNlabelString,
XmStringCreateLtoR(menu_name,char_set)); ac++;
cascade=XmCreateCascadeButton(menu_bar,menu_name,al,ac);
XtManageChild(cascade);
return(menu);
}
Widget make_help_menu(menu_name, menu_bar)
char *menu_name;
Widget menu_bar;
/* Creates a new menu on the menu bar. */
{
int ac;
Arg al[10];
Widget menu, cascade;
ac = 0;
menu = XmCreatePulldownMenu (menu_bar, menu_name, al, ac);
ac = 0;
XtSetArg (al[ac], XmNsubMenuId, menu); ac++;
XtSetArg(al[ac], XmNlabelString,
XmStringCreateLtoR(menu_name, XmSTRING_DEFAULT_CHARSET)); ac++;
cascade = XmCreateCascadeButton (menu_bar, menu_name, al, ac);
XtManageChild (cascade);
/* Wire the help menu into the rowcol widget's help menu resource. */
ac=0;
XtSetArg(al[ac],XmNmenuHelpWidget,cascade); ac++;
XtSetValues(menu_bar,al,ac);
return(menu);
}
void create_menus(menu_bar)
Widget menu_bar;
/* creates all the menus for this program */
{
/* create the file menu */
file_menu=make_menu("File",menu_bar);
quit_item=make_menu_item("Quit","Quit",file_menu);
/* Create the help menu. */
help_menu=make_help_menu("Help",menu_bar);
/* Create some buttons and register their help callbacks. */
aboutButton=XmCreatePushButton(help_menu, "About", NULL, 0);
XtManageChild(aboutButton);
XtAddCallback(aboutButton, XmNactivateCallback, XnHelpCB, "About");
indexButton=XmCreatePushButton(help_menu, "Index", NULL, 0);
XtManageChild(indexButton);
XtAddCallback(indexButton, XmNactivateCallback, XnHelpCB, "Index");
overviewButton=XmCreatePushButton(help_menu, "Overview", NULL, 0);
XtManageChild(overviewButton);
XtAddCallback(overviewButton, XmNactivateCallback, XnHelpCB, "Overview");
deferredButton=XmCreatePushButton(help_menu, "Deferred", NULL, 0);
XtManageChild(deferredButton);
XtAddCallback(deferredButton, XmNactivateCallback, XnHelpCB, "Deferred");
hiddenButton=XmCreatePushButton(help_menu, "Hidden", NULL, 0);
XtManageChild(hiddenButton);
XtAddCallback(hiddenButton, XmNactivateCallback, XnHelpCB, "Hidden");
}
void main(argc,argv)
int argc;
char *argv[];
{
Arg al[10];
int ac;
/* create the toplevel shell */
toplevel = XtAppInitialize(&context,"",NULL,0,&argc,argv,NULL,NULL,0);
/* Initialize the XnHelpCB callback. */
XnInitializeHelp(context, toplevel, HELPFILE, True);
/* resize the window */
ac=0;
XtSetArg(al[ac],XmNheight,200); ac++;
XtSetArg(al[ac],XmNwidth,200); ac++;
XtSetValues(toplevel,al,ac);
/* create a form widget */
ac=0;
form=XmCreateForm(toplevel,"form",al,ac);
XtManageChild(form);
/* create a label widget */
ac=0;
XtSetArg(al[ac],XmNlabelString,
XmStringCreate("I'm a label", char_set)); ac++;
label=XmCreateLabel(form,"label",al,ac);
XtManageChild(label);
/* create the menu bar */
ac=0;
menu_bar=XmCreateMenuBar(form,"menu_bar",al,ac);
XtManageChild(menu_bar);
/* attach the menu bar to the form */
ac=0;
XtSetArg(al[ac],XmNtopAttachment,XmATTACH_FORM); ac++;
XtSetArg(al[ac],XmNrightAttachment,XmATTACH_FORM); ac++;
XtSetArg(al[ac],XmNleftAttachment,XmATTACH_FORM); ac++;
XtSetValues(menu_bar,al,ac);
/* attach the label to the form */
ac=0;
XtSetArg(al[ac],XmNtopAttachment,XmATTACH_WIDGET); ac++;
XtSetArg(al[ac],XmNtopWidget,menu_bar); ac++;
XtSetArg(al[ac],XmNrightAttachment,XmATTACH_FORM); ac++;
XtSetArg(al[ac],XmNleftAttachment,XmATTACH_FORM); ac++;
XtSetArg(al[ac],XmNbottomAttachment,XmATTACH_FORM); ac++;
XtSetValues(label,al,ac);
create_menus(menu_bar);
XtRealizeWidget(toplevel);
XtAppMainLoop(context);
}
|
C
|
/*Excersie 8 Program 2
AUMRUDH LAL KUMAR TJ*/
//Program To Print emplyee details
#include<stdio.h>
struct employee
{
int eid;
char name[20];
char dep[20];
float bpay;
float da;
float hra;
float gpay;
float npay;
float pf;
}em[50];
main()
{
int n,i;
printf("Enter the number of employee\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the employee id\n");
scanf("%d",&em[i].eid);
printf("Enter the employee name\n");
scanf("%s",em[i].name);
printf("Enter the employee department\n");
scanf("%s",em[i].dep);
printf("Enter the Basic Pay\n");
scanf("%f",&em[i].bpay);
em[i].da=em[i].bpay*0.5;
em[i].hra=em[i].bpay*0.05;
em[i].gpay=em[i].bpay+em[i].da+em[i].hra;
em[i].pf=em[i].bpay*0.10;
em[i].npay=em[i].gpay-em[i].pf;
}
printf("The Employee Details are\n");
printf("\n--------------------------------------------------------------------------------------------------------------------------------------------\n");
printf("\nEmployee ID \t Name \t Department \t Basicpay \t DA \t\t HRA \t\tPF \t\t Gross Pay \t\tNetpay\n");
printf("\n--------------------------------------------------------------------------------------------------------------------------------------------\n");
for(i=0;i<n;i++)
{
printf("%d\t\t%s\t\t%s\t%f\t%f\t%f\t%f\t%f\t\t%f",em[i].eid,em[i].name,em[i].dep,em[i].bpay,em[i].da,em[i].hra,em[i].pf,em[i].gpay,em[i].npay);
printf("\n");
}
}
|
C
|
/*
* Find the Difference
*
* Given two strings s and t which consist of only lowercase letters.
*
* String t is generated by random shuffling string s and then add one more letter
* at a random position.
*
* Find the letter that was added in t.
*
* Example:
* Input: s = "abcd", t = "abcde"
* Output: e
* Explanation: 'e' is the letter that was added.
*/
class Solution {
public:
char findTheDifference(string s, string t) {
char c = t[t.length()-1];
for (int i = 0; i < s.length(); i++) {
c ^= s[i];
c ^= t[i];
}
return c;
}
};
|
C
|
// POS47-C: Noncompliant Code Example
volatile int a = 5;
volatile int b = 10;
/* Lock to enable threads to access a and b safely */
pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER;
void* worker_thread(void* dummy) {
int i;
int c;
int result;
if ((result = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&i)) != 0) {
/* handle error */
}
while (1) {
if ((result = pthread_mutex_lock(&global_lock)) != 0) {
/* handle error */
}
c = b;
b = a;
a = c;
if ((result = pthread_mutex_unlock(&global_lock)) != 0) {
/* handle error */
}
}
return NULL;
}
int main(void) {
int result;
pthread_t worker;
if ((result = pthread_create( &worker, NULL, worker_thread, NULL)) != 0) {
/* handle error */
}
/* .. Do stuff...meanwhile worker thread runs for some time */
/* since we don't know when the character is read in, the program could continue at any time */
if ((result = pthread_cancel(worker)) != 0) {
/* handle error */
}
/* pthread_join waits for the thread to finish up before continuing */
if ((result = pthread_join(worker, 0)) != 0) {
/* handle error */
}
if ((result = pthread_mutex_lock(&global_lock)) != 0) {
/* handle error */
}
printf("a: %i | b: %i", a, b);
if ((result = pthread_mutex_unlock(&global_lock)) != 0) {
/* handle error */
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "pila.h"
///6. Pasar el primer elemento (tope)
///de la pila DADA a su ltima posicin (base), dejando los restantes elementos en el mismo orden.
int main()
{
Pila DADA;
Pila AUX;
int numero;
inicpila(&AUX);
inicpila(&DADA);
char seguir;
do
{
leer(&DADA);
printf("Desea seguir ingresando valores? s/n \n");
fflush(stdin);
scanf("%c", &seguir);
}
while(seguir == 's');
if (!pilavacia(&DADA))
{
numero = desapilar(&DADA);
}
while (!pilavacia(&DADA))
{
apilar(&AUX, desapilar(&DADA));
}
apilar(&DADA,numero);
while (!pilavacia(&AUX))
{
apilar(&DADA,desapilar(&AUX));
}
return 0;
}
|
C
|
/*
* jying FastCGI Process Manager
*
* Copyright (C) 2020
*
* Website: https://www.cnblogs.com/jying
*
* 2020/12/06 Created.
*
* Description: This file mainly includes the functions about
*
*/
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif //_WIN32_WINNT
#include <windows.h>
#include <winsock.h>
#include <wininet.h>
#include <stdbool.h>
#define SHUT_RDWR SD_BOTH
#ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
#define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE (0x2000)
#endif
HANDLE FcpJobObject; // 定义句柄
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
// 新加用于日志文件
#include <stdarg.h>
#include <time.h>
#define MAX_PROCESSES 1024
#define FILE_MAX_SIZE (1024 * 1024) // 定义文件大小,超过该大小,会启动清空删除操作。
static const char version[] = "Revision: 2020.12.06";
static char *prog_name;
int number = 1;
int port = 9000;
char *ip = "127.0.0.1";
char *user = "";
char *root = "";
char *path = "";
char *group = "";
int listen_fd;
struct sockaddr_in listen_addr; // sockaddr_in 数据结构体,允许把port和addr 分开存储在两个变量中
int process_fp[MAX_PROCESSES];
int process_idx = 0;
pthread_t threads[MAX_PROCESSES];
static struct option longopts[] =
{
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'v'},
{"number", required_argument, NULL, 'n'},
{"ip", required_argument, NULL, 'i'},
{"port", required_argument, NULL, 'p'},
{"user", required_argument, NULL, 'u'},
{"group", required_argument, NULL, 'g'},
{"root", required_argument, NULL, 'r'},
{NULL, 0, NULL, 0}};
static char opts[] = "hvnipugr";
// 输出可用参数
static void usage(FILE *where)
{
//
fprintf(where, ""
"Usage: %s path [-n number] [-i ip] [-p port]\n"
"Manage FastCGI processes.\n"
"\n"
" -n, --number number of processes to keep\n"
" -i, --ip ip address to bind\n"
" -p, --port port to bind, default is 8000\n"
" -u, --user start processes using specified linux user\n"
" -g, --group start processes using specified linux group\n"
" -r, --root change root direcotry for the processes\n"
" -h, --help output usage information and exit\n"
" -v, --version output version information and exit\n"
"",
prog_name);
exit(where == stderr ? 1 : 0);
}
static void print_version()
{
printf("\n %s %s\n FastCGI Process Manager\n Copyright 2020 https://www.cnblogs.com/jying\n Compiled on %s\n", prog_name, version, __DATE__);
exit(0);
}
/*
获得文件大小
@param filename [in]: 文件名
@return 文件大小
*/
long get_file_size(char *filename)
{
long length = 0;
FILE *fp = NULL;
fp = fopen(filename, "rb");
if (fp != NULL)
{
fseek(fp, 0, SEEK_END);
length = ftell(fp);
}
if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
return length;
}
int write_log(char *filename, const char *format, ...)
{
if (filename != NULL && format != NULL)
{
long length = get_file_size(filename);
// fprintf(stdout, "file length = %d\n", length);
if (length > FILE_MAX_SIZE)
{
unlink(filename); // 删除文件
}
FILE *pFile = fopen(filename, "a+b");
if (pFile != NULL)
{
va_list arg;
int done;
va_start(arg, format);
time_t time_log = time(NULL);
struct tm *tm_log = localtime(&time_log);
fprintf(pFile, "%04d-%02d-%02d %02d:%02d:%02d :", tm_log->tm_year + 1900, tm_log->tm_mon + 1, tm_log->tm_mday, tm_log->tm_hour, tm_log->tm_min, tm_log->tm_sec);
done = vfprintf(pFile, format, arg);
va_end(arg);
fflush(pFile);
fclose(pFile);
pFile = NULL;
return done;
}
}
return 0;
}
static int try_to_bind()
{
listen_addr.sin_family = PF_INET;
listen_addr.sin_addr.s_addr = inet_addr(ip);
listen_addr.sin_port = htons(port);
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == bind(listen_fd, (struct sockaddr *)&listen_addr, sizeof(struct sockaddr_in)))
{
fprintf(stderr, "failed to bind %s:%d\n", ip, port);
write_log("error_log.txt", "failed to bind %s:%d\r\n", ip, port);
return -1;
}
listen(listen_fd, MAX_PROCESSES);
return 0;
}
static void *spawn_process(void *arg)
{
int idx = process_idx++, ret; // process_idx 初始值0
while (1)
{
STARTUPINFO si = {0}; //
PROCESS_INFORMATION pi = {0};
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = (HANDLE)listen_fd;
si.hStdOutput = INVALID_HANDLE_VALUE;
si.hStdError = INVALID_HANDLE_VALUE;
ret = CreateProcess( // WIN32API函数CreateProcess用来创建一个新的进程和它的主线程,这个新进程运行指定的可执行文件。如果函数执行成功,返回非零值。
NULL, // 指定可执行模块
path, // 指定要执行的命令行,此处为 php-cgi.exe
NULL, // 决定是否返回的句柄可以被子进程继承。如果lpProcessAttributes参数为空(NULL),那么句柄不能被继承。
NULL, // 默认进程安全性,同上,不过这个参数决定的是线程是否被继承.通常置为NULL.
TRUE, // 指定当前进程内句柄可以被子进程继承
CREATE_NO_WINDOW | CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,
// CREATE_NO_WINDOW 为新进程不创建新的控制台窗口, CREATE_SUSPENDED 新进程的 主线程会以暂停的状态被创建,直到调用 ResumeThread函数被调用时才运行。
// 当一个进程被加入到Job中后,没有特殊的说明,那么该进程的所有子进程都将被纳入到Job里。当然,通过JOB_OBJECT_LIMIT_BREAKAWAY_OK或者JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK。
// Job内进程的子进程就可以不被自动纳入到Job中,两者区别在于,后者将所有子进程自动的赶出Job,而前者的子进程需要在CreateProcess时指定CREATE_BREAKAWAY_FROM_JOB。
NULL, // 使用本进程的环境变量。指向一个新进程的环境块。如果此参数为空,新进程使用调用进程的环境。
NULL, // 使用本进程的驱动器和目录。指定子进程的工作路径。如果这个参数为空,新进程将使用与调用进程相同的驱动器和目录。
&si,
&pi);
if (0 == ret)
{
fprintf(stderr, "failed to create process %s, ret=%d\n", path, ret); // 进程创建失败
write_log("error_log.txt", "failed to create process %s, ret=%d\r\n", path, ret); // 进程创建失败
return NULL;
}
else
{
fprintf(stdout, "successful to create process %s, ret=%d\n", path, ret); // 进程创建成功
write_log("log.txt", "successful to create process %s, ret=%d\r\n", path, ret); // 进程创建成功
}
/* Use Job Control System */
if (!AssignProcessToJobObject(FcpJobObject, pi.hProcess))
{
TerminateProcess(pi.hProcess, 1);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
write_log("error_log.txt", "AssignProcessToJobObject:failed\r\n");
return NULL;
}
if (!ResumeThread(pi.hThread))
{
TerminateProcess(pi.hProcess, 1);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
write_log("error_log.txt", "ResumeThread:failed\r\n");
return NULL;
}
process_fp[idx] = (int)pi.hProcess;
WaitForSingleObject(pi.hProcess, INFINITE); // 等待函数可使线程自愿进入等待状态,直到一个特定的内核对象变为已通知状态为止。
/* 第一个参数hObject标识一个能够支持被通知/未通知的内核对象。
第二个参数dwMilliseconds允许该线程指明,为了等待该对象变为已通知状态,它将等待多长时间。(INFINITE为无限时间量,INFINITE已经定义为0xFFFFFFFF(或-1))
传递INFINITE有些危险。如果对象永远不变为已通知状态,那么调用线程永远不会被唤醒,它将永远处于死锁状态,不过,它不会浪费宝贵的C P U时间。*/
process_fp[idx] = 0;
CloseHandle(pi.hThread);
write_log("log.txt", "WaitForSingleObject:Ready to create a new process\r\n");
}
}
static int start_processes()
{
int i;
pthread_attr_t attr; // 线程属性,线程具有属性,用pthread_attr_t表示,在对该结构进行处理之前必须进行初始化,在使用后需要对其去除初始化。
pthread_attr_init(&attr); // 调用pthread_attr_init之后,pthread_t结构所包含的内容就是操作系统实现支持的线程所有属性的默认值。
pthread_attr_setstacksize(&attr, 64 * 1024); //64KB ,设置堆栈大小
for (i = 0; i < number; i++)
{
if (pthread_create(&threads[i], &attr, spawn_process, NULL) == -1)
{ // pthread_create是c++系统函数-创建线程, spawn_process是自定义的函数
fprintf(stderr, "failed to create thread %d\n", i);
write_log("error_log.txt", "failed to create thread %d\r\n", i);
}
}
for (i = 0; i < number; i++)
{
pthread_join(threads[i], NULL); // 线程回收 pthread_join,阻塞等待线程退出,获取线程退出状态,对应进程中 waitpid() 函数,成功:0;失败:错误号
}
return 0;
}
void init_win32()
{
/* init win32 socket */
static WSADATA wsa_data; // WSADATA 存放windows socket初始化信息.
if (WSAStartup((WORD)(1 << 8 | 1), &wsa_data) != 0) // 使用Socket的程序在使用Socket之前必须调用WSAStartup函数。以后应用程序就可以调用所请求的Socket库中的其它Socket函数了。该函数执行成功后返回0。
exit(1);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit; // JOBOBJECT_EXTENDED_LIMIT_INFORMATION 扩展后的基本限额所对应的数据结构,作业中的某种类型吧
FcpJobObject = (HANDLE)CreateJobObject(NULL, NULL); // CreateJobObject 创建作业
if (FcpJobObject == NULL)
exit(1);
/* let all processes assigned to this job object // 将所有进程分配给此作业对象
* being killed when the job object closed */
// 作业对象关闭时被杀死
if (!QueryInformationJobObject(FcpJobObject, JobObjectExtendedLimitInformation, &limit, sizeof(limit), NULL))
{
CloseHandle(FcpJobObject);
exit(1);
}
limit.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if (!SetInformationJobObject(FcpJobObject, JobObjectExtendedLimitInformation, &limit, sizeof(limit)))
{
CloseHandle(FcpJobObject);
exit(1);
}
}
/*
启动入口,关于main函数的介绍可以访问:https://www.cnblogs.com/bianchengzhuji/p/9783772.html,本例使用第五种方法。
argc:入参命令行参数个数
**argv 入参命令行参数数组,通常用于实现需要从命令行获取参数的功能。C 语言*号可表示指针,** 表示复合指针
举例我们执行了:xffpm php-cgi.exe -n 5 -p 8081
*/
int main(int argc, char **argv)
{
/*如果要注销或关闭系统返回 1 否则返回 0*/
prog_name = strrchr(argv[0], '/');
// strrchr()查找一个字符c在另一个字符串str中末次出现的位置(也就是从str的右侧开始查找字符c首次出现的位置),并返回这个位置的地址。
// 如果未能找到指定字符,那么函数将返回NULL。使用这个地址返回从最后一个字符c到str末尾的字符串。
// 比如 char *ptr = strrchr("There are two rings", 'r'); 输出ptr是rings,但是这里要注意:ptr是指针,而不是java,php语言中的变量,输出 ptr+1 结果是 ings
// 输出第一个参数中的文件路径,此处对应为得到xxfpm
if (prog_name == NULL)
prog_name = strrchr(argv[0], '\\');
if (prog_name == NULL)
prog_name = argv[0];
else
prog_name++; // 本例得到xxfpm
if (argc == 1)
usage(stderr); // 如果只有一个参数,输出到您的屏幕
path = argv[1]; // 得到 php-cgi.exe
opterr = 0;
for (;;)
{ // 相当于 while(1)
int ch;
if ((ch = getopt_long(argc, argv, opts, longopts, NULL)) == EOF) // 依次获取参数,直到结束字符,此处为依次检查参数h, v, n, i, p, u, g, r
// 关于 getopt 和 getopt_long 可参看 https://www.cnblogs.com/chenliyang/p/6633739.html
// getopt_long(5, php-cgi.exe -n 5 -p 8081, "hvnipugr", [自定义的longopts], null) , EOF 表示 End Of File 的缩写,使用EOF是为了避免因试图在文件结尾处进行输入而产生的错误。
// 直到到达文件的结尾,EOF函数都返回False。对于为访问Random或Binary而打开的文件,直到最后一次执行的Get语句无法读出完整的记录时,EOF都返回False。
break;
char *av = argv[optind]; // optind 为 argv的当前索引值, 此处为 *av 依次获取参数 h, v, n, i, p, u, g, r 对应的值
switch (ch)
{ // 获取各参数对应的值
case 'h':
usage(stdout); // stdout 输出显示到屏幕
break;
case 'v':
print_version();
break;
case 'n':
number = atoi(av); // 取整
if (number > MAX_PROCESSES)
{ // MAX_PROCESSES = 1024
fprintf(stderr, "exceeds MAX_PROCESSES!\n");
write_log("error_log.txt", "exceeds MAX_PROCESSES!\r\n");
number = MAX_PROCESSES;
}
break;
case 'u':
user = av;
break;
case 'r':
root = av;
break;
case 'g':
group = av;
break;
case 'i':
ip = av;
break;
case 'p':
port = atoi(av);
break;
default:
usage(stderr);
break;
}
}
init_win32(); // 自定义的init_win32函数, 注册作业监控进程?
int ret;
ret = try_to_bind(); // 绑定准备要监听的 ip 和 端口,已经被占用,则为-1,否则为0
if (ret != 0)
return ret;
ret = start_processes(); // 监听进程
if (ret != 0)
return ret;
CloseHandle(FcpJobObject);
WSACleanup(); // 清理作业
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char* argv[]) {
float a, b, c, delta, raiz_unica, raiz_dist1, raiz_dist2, raiz_quad;
printf("Digite os coeficientes da equaçao do segundo grau: ");
scanf("%f %f %f", &a, &b, &c);
delta = b * b - 4 * a * c;
if (delta < 0) {
printf("As raizes sao imaginarias, e portanto nao e possivel calcula-las no conjunto dos reais\n");
} else if (delta == 0) {
raiz_unica = -b / 2 * a;
printf("A equaçao possui raiz unica e seu valor e: %f\n", raiz_unica);
} else if (delta > 0) {
raiz_quad = sqrt(delta);
raiz_dist1 = -b + raiz_quad / 2 * a;
raiz_dist2 = -b - raiz_quad / 2 * a;
printf("A equaçao possui raizes distintas e seus valores sao: %f %f\n", raiz_dist1, raiz_dist2);
}
return 0;
}
|
C
|
/*
* 24C256 und 24C512 sind beide kompatibel bezüglich Adressierung
*
* Achtung!!!! Wenn auf EEPROM geschrieben und gleich wieder gelesen
* wird, kann es zu fehlerhaften Ausgaben kommen. Unbedingt ein paar
* Milisekunden Delay einbauen bevor zurückgelesen wird...
*
* EEWrite_8(1, 1, 123);
* _delay_ms(50);
* test=EERead_8(1, 1);
* lcd_print(test);
*
*
* */
#define F_CPU 16000000UL // 1 MHz
#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>
#include "grn_TWI.h"
/*
* Device Addressing
*
* 1010 000 0
* Control code Chip select W/R (0=Write; 1=Read)
* */
#define EEPROM_1_W 0b10100000 //EEPROM Adresse und schreiben
#define EEPROM_1_R 0b10100001 //EEPROM Adresse und lesen
#define EEPROM_2_W 0b10100010 //EEPROM Adresse und schreiben
#define EEPROM_2_R 0b10100011 //EEPROM Adresse und lesen
#define EEPROM_3_W 0b10100100 //EEPROM Adresse und schreiben
#define EEPROM_3_R 0b10100101 //EEPROM Adresse und lesen
#define EEPROM_4_W 0b10100110 //EEPROM Adresse und schreiben
#define EEPROM_4_R 0b10100111 //EEPROM Adresse und lesen
uint8_t EEWrite_8(uint16_t u16addr, uint8_t EENumber, uint8_t u8data)
{
uint8_t addr_l, addr_h, ew;
addr_l = u16addr;
addr_h = (u16addr>>8);
ew=0;
switch(EENumber)
{
case 1: ew = EEPROM_1_W;
break;
case 2: ew = EEPROM_2_W;
break;
case 3: ew = EEPROM_3_W;
break;
case 4: ew = EEPROM_4_W;
break;
}
TWIStart();
if(TWIGetStatus() != 0x08)return 1;
TWIWrite(ew);
if(TWIGetStatus() != 0x18)return 2;
TWIWrite(addr_l);
if(TWIGetStatus() != 0x28)return 3;
TWIWrite(addr_h);
if(TWIGetStatus() != 0x28)return 4;
TWIWrite(u8data);
if(TWIGetStatus() != 0x28)return 5;
TWIStop();
_delay_ms(5); //EEPROM braucht Zeit zum schreiben
return 0;
}
uint8_t EERead_8(uint16_t u16addr, uint8_t EENumber)
{
uint8_t addr_l, addr_h,er, ew, retdata;
addr_l = u16addr;
addr_h = (u16addr>>8);
ew=0;
er=0;
retdata=0;//Data to be returned
/*
* richtige schreib- / leseadresse
* gemäss gewähltem EEprom
*/
switch(EENumber)
{
case 1: ew = EEPROM_1_W;
er = EEPROM_1_R;
break;
case 2: ew = EEPROM_2_W;
er = EEPROM_2_R;
break;
case 3: ew = EEPROM_3_W;
er = EEPROM_3_R;
break;
case 4: ew = EEPROM_4_W;
er = EEPROM_4_R;
break;
}
TWIStart();
if(TWIGetStatus() != 0x08)return 6; //0x08 = Start condition
TWIWrite(ew);
if(TWIGetStatus() != 0x18)return 7;
TWIWrite(addr_l);
if(TWIGetStatus() != 0x28)return 8;
TWIWrite(addr_h);
if(TWIGetStatus() != 0x28)return 9;
TWIStart();
if(TWIGetStatus() != 0x10)return 10;
TWIWrite(er);
if(TWIGetStatus() != 0x40)return 11;
retdata = TWIReadNACK();
if(TWIGetStatus() != 0x58)return 12;
TWIStop();
return retdata;
}
uint8_t EEWrite_16(uint16_t u16addr, uint8_t EENumber, uint16_t u16data)
{
uint8_t data_l, data_h;
data_h = (u16data>>8);
data_l = u16data;
EEWrite_8(u16addr, EENumber, data_h);
EEWrite_8((u16addr+1), EENumber, data_l);
return 0;
}
uint16_t EERead_16(uint16_t u16addr, uint8_t EENumber)
{
uint8_t data_l, data_h;
uint16_t data;
data_h= EERead_8(u16addr, EENumber);
data_l=EERead_8((u16addr+1), EENumber);
data = (data_l | (data_h<<8));
return data;
}
|
C
|
int minDistance(int src[][],int x_low,int x_high)
{
if (x_low == x_high) return distance(src[x_low)
}
int main()
{
int src[][2] = {(1,3),(2,4),(5,7),(3,9),(6,8)};
}
|
C
|
#include <stdio.h>
#define TAMVECTOR 12
void main() {
// ESTA ES LA FORMA DE DECLARAR E INICIALIZAR UN VECTOR
//float vectorTemp[12] = { 3.5, 5.8, 10.5, 13.8, 15.0, 20, 25, 30, 22, 18, 15, 5.0};
float vectorTemp[TAMVECTOR];
float media = 0;
int i;
for (i = 0; i < TAMVECTOR; i++) {
printf("Introduce la temp media del mes %d\n", i+1);
scanf_s("%f", &vectorTemp[i]);
}
for (i = 0; i < TAMVECTOR; i++) {
media = media + vectorTemp[i];
}
media = media / TAMVECTOR;
// PARA IMPRIMIR LAS COMPONENTES DEL VECTOR
for (i = 0; i < TAMVECTOR; i++) {
printf("vector[%d]=%f\n", i, vectorTemp[i]);
}
printf("Media del vector = %f\n", media);
system("PAUSE");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sorting_hat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rrika <rrika@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/26 16:18:11 by rrika #+# #+# */
/* Updated: 2019/08/13 17:35:13 by rrika ### ########.fr */
/* */
/* ************************************************************************** */
#include "../push_swap.h"
void sa_ra_sort(t_stack *stack)
{
if (!is_sorted(stack->a))
action("sa", &(stack->a), &(stack->b), stack->flags);
if (stack->a->num != ft_lstmin(stack->a))
{
if (stack->a->next->num == ft_lstmin(stack->a))
action("ra", &(stack->a), &(stack->b), stack->flags);
else
action("rra", &(stack->a), &(stack->b), stack->flags);
}
}
void pa_pb_sort(t_stack *stack)
{
while (!ft_lstsorted(stack->a) && ft_lstsize(stack->a) > 3)
{
prep_b(stack);
action("pb", &(stack->a), &(stack->b), stack->flags);
}
sa_ra_sort(stack);
while (stack->b)
{
prep_a(stack);
action("pa", &(stack->a), &(stack->b), stack->flags);
}
fix_a(stack);
}
void pb_ra_sort(t_stack *stack, int lmax)
{
while ((stack->a) && stack_contains(stack->a, lmax))
{
if (stack->a->num <= lmax)
{
prep_b(stack);
action("pb", &stack->a, &stack->b, stack->flags);
}
else
action("ra", &(stack->a), &(stack->b), stack->flags);
}
fix_b(stack);
}
void sorting_hat(t_stack *stack)
{
int chunk;
int temp;
int i;
chunk = 0;
temp = 0;
i = 0;
if (ft_lstsize(stack->a) <= 3)
sa_ra_sort(stack);
else if (ft_lstsize(stack->a) <= 40)
pa_pb_sort(stack);
else
temp = (ft_lstsize(stack->a) <= 200 ? 5 : 11);
if (temp)
{
chunk = (ft_lstmax(stack->a) - ft_lstmin(stack->a)) / temp;
while (++i < temp)
pb_ra_sort(stack, chunk * i);
pb_ra_sort(stack, ft_lstmax(stack->a) + 1);
back_to_a(&(stack->a), &(stack->b), stack->flags);
}
}
|
C
|
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include "xalloc.h"
void *
xmalloc(size_t size)
{
void *p;
p = malloc(size);
if (p == NULL) {
perror("xmalloc");
exit(EXIT_FAILURE);
}
return p;
}
void
xfree(void *ptr)
{
free(ptr);
}
|
C
|
#include <stdio.h>
int main()
{
float i,j;
for(i=0.0;i<2.02;i=i+0.2){
for(j=1.0;j<=3.0;j++){
printf("I=%g J=%g\n",i,j+i);
}
}
}
|
C
|
/*numPass=6, numTotal=6
Verdict:ACCEPTED, Visibility:1, Input:"1 0 0 1", ExpOutput:"(1.000,1.000)
", Output:"(1.000,1.000)"
Verdict:ACCEPTED, Visibility:1, Input:"1 0 1 0", ExpOutput:"INF
", Output:"INF"
Verdict:ACCEPTED, Visibility:1, Input:"-1.25 0 5 4", ExpOutput:"(-0.800,1.250)
", Output:"(-0.800,1.250)"
Verdict:ACCEPTED, Visibility:0, Input:"1 -2 -100 201", ExpOutput:"(203.000,101.000)
", Output:"(203.000,101.000)"
Verdict:ACCEPTED, Visibility:0, Input:"-1000 1 2000 -2", ExpOutput:"INF
", Output:"INF"
Verdict:ACCEPTED, Visibility:0, Input:"0 1 0.0000001 1", ExpOutput:"(-0.000,1.000)
", Output:"(-0.000,1.000)"
*/
#include<stdio.h>
int main(){
float a1,b1,a2,b2; /*a1,b1,a2,b2 are variables of the given line */
scanf("%f%f%f%f",&a1,&b1,&a2,&b2);/* values of a1,a2,b1,b2 are given by user */
float X=(b2-b1)/((b2*a1-b1*a2));/* x-coordinate of intersection point*/
float Y=(a2-a1)/((b1*a2)-(a1*b2));/*y-coordinate of intersection point*/
if (a1*b2==b1*a2) /*condition for no intersection*/
{printf("INF");}/*if above boolean exp is true*/
else
{printf("(%.3f,%.3f)",X,Y);}/*if above boolean exp is false*/
return 0;
}
|
C
|
#include<stdio.h>
void main(){
float x;
scanf("%f",&x);
if ((x - (int)x) >= 0.5)
printf("%d",(int)x+1);
else
printf("%d",(int)x);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "xxhash.h"
#include "ida_search_core.h"
#include "ida_search_444.h"
unsigned int centers_444[NUM_CENTERS_444] = {
6, 7, 10, 11,
22, 23, 26, 27,
38, 39, 42, 43,
54, 55, 58, 59,
70, 71, 74, 75,
86, 87, 90, 91
};
struct wings_for_edges_recolor_pattern_444*
init_wings_for_edges_recolor_pattern_444()
{
struct wings_for_edges_recolor_pattern_444 *result = NULL;
struct wings_for_edges_recolor_pattern_444 *curr= NULL;
result = malloc(sizeof(struct wings_for_edges_recolor_pattern_444) * NUM_EDGES_444);
curr = result;
/*
wings_for_edges_recolor_pattern_444 = (
('0', 2, 67), # upper
('1', 3, 66),
('2', 5, 18),
('3', 8, 51),
('4', 9, 19),
('5', 12, 50),
('6', 14, 34),
('7', 15, 35),
('8', 21, 72), # left
('9', 24, 37),
('a', 25, 76),
('b', 28, 41),
('c', 53, 40), # right
('d', 56, 69),
('e', 57, 44),
('f', 60, 73),
('g', 82, 46), # down
('h', 83, 47),
('i', 85, 31),
('j', 88, 62),
('k', 89, 30),
('l', 92, 63),
('m', 94, 79),
('n', 95, 78)
)
*/
curr->edge_index[0] = '0';
curr->square_index = 2;
curr->partner_index = 67;
curr++;
curr->edge_index[0] = '1';
curr->square_index = 3;
curr->partner_index = 66;
curr++;
curr->edge_index[0] = '2';
curr->square_index = 5;
curr->partner_index = 18;
curr++;
curr->edge_index[0] = '4';
curr->square_index = 9;
curr->partner_index = 19;
curr++;
curr->edge_index[0] = '3';
curr->square_index = 8;
curr->partner_index = 51;
curr++;
curr->edge_index[0] = '5';
curr->square_index = 12;
curr->partner_index = 50;
curr++;
curr->edge_index[0] = '6';
curr->square_index = 14;
curr->partner_index = 34;
curr++;
curr->edge_index[0] = '7';
curr->square_index = 15;
curr->partner_index = 35;
curr++;
curr->edge_index[0] = '8';
curr->square_index = 21;
curr->partner_index = 72;
curr++;
curr->edge_index[0] = 'a';
curr->square_index = 25;
curr->partner_index = 76;
curr++;
curr->edge_index[0] = '9';
curr->square_index = 24;
curr->partner_index = 37;
curr++;
curr->edge_index[0] = 'b';
curr->square_index = 28;
curr->partner_index = 41;
curr++;
curr->edge_index[0] = 'c';
curr->square_index = 53;
curr->partner_index = 40;
curr++;
curr->edge_index[0] = 'e';
curr->square_index = 57;
curr->partner_index = 44;
curr++;
curr->edge_index[0] = 'd';
curr->square_index = 56;
curr->partner_index = 69;
curr++;
curr->edge_index[0] = 'f';
curr->square_index = 60;
curr->partner_index = 73;
curr++;
curr->edge_index[0] = 'g';
curr->square_index = 82;
curr->partner_index = 46;
curr++;
curr->edge_index[0] = 'h';
curr->square_index = 83;
curr->partner_index = 47;
curr++;
curr->edge_index[0] = 'i';
curr->square_index = 85;
curr->partner_index = 31;
curr++;
curr->edge_index[0] = 'k';
curr->square_index = 89;
curr->partner_index = 30;
curr++;
curr->edge_index[0] = 'j';
curr->square_index = 88;
curr->partner_index = 62;
curr++;
curr->edge_index[0] = 'l';
curr->square_index = 92;
curr->partner_index = 63;
curr++;
curr->edge_index[0] = 'm';
curr->square_index = 94;
curr->partner_index = 79;
curr++;
curr->edge_index[0] = 'n';
curr->square_index = 95;
curr->partner_index = 78;
curr++;
return result;
}
// ===========================================================================
// step 10
// ===========================================================================
struct ida_heuristic_result
ida_heuristic_reduce_333_444 (
char *cube,
unsigned int max_cost_to_goal,
struct key_value_pair **reduce_333_444,
char *reduce_333_edges_only,
char *reduce_333_centers_only,
struct wings_for_edges_recolor_pattern_444 *wings_for_recolor)
{
int cost_to_goal = 0;
unsigned long edges_state_bucket = 0;
unsigned long centers_state_bucket = 0;
unsigned int edges_cost = 0;
unsigned int centers_cost = 0;
char lt_state[NUM_EDGES_AND_CENTERS_444+2];
char edges_state[NUM_EDGES_444+1];
char centers_state[NUM_CENTERS_444+1];
char i_wing_str[2];
char j_wing_str[2];
char tmp_char;
struct wings_for_edges_recolor_pattern_444 *i_wings_for_recolor = wings_for_recolor;
struct wings_for_edges_recolor_pattern_444 *j_wings_for_recolor = wings_for_recolor;
struct ida_heuristic_result result;
memset(&result, 0, sizeof(struct ida_heuristic_result));
centers_state[NUM_EDGES_444] = '\0';
memset(edges_state, '\0', NUM_EDGES_444+1);
unsigned int flip_wing_str = 0;
// Record the two edge_indexes for each of the 12 edges
for (int i = 0; i < NUM_EDGES_444; i++) {
// If we already populated this one move on
if (edges_state[i] != '\0') {
i_wings_for_recolor++;
continue;
}
//j_wings_for_recolor = wings_for_recolor;
i_wing_str[0] = cube[i_wings_for_recolor->square_index];
i_wing_str[1] = cube[i_wings_for_recolor->partner_index];
flip_wing_str = 0;
// Flip BU around to UB, etc. We do this so the two use the same wing_str.
// U, D, L, and F should always be the first charcter.
if (i_wing_str[1] == 'U' || i_wing_str[1] == 'D') {
if (i_wing_str[0] == 'B' || i_wing_str[0] == 'L' || i_wing_str[0] == 'R' || i_wing_str[0] == 'F') {
flip_wing_str = 1;
}
} else if (i_wing_str[1] == 'L' || i_wing_str[1] == 'R') {
if (i_wing_str[0] == 'B' || i_wing_str[0] == 'F') {
flip_wing_str = 1;
}
}
if (flip_wing_str) {
tmp_char = i_wing_str[0];
i_wing_str[0] = i_wing_str[1];
i_wing_str[1] = tmp_char;
}
j_wings_for_recolor = i_wings_for_recolor;
j_wings_for_recolor++;
for (int j = i+1; j < NUM_EDGES_444; j++) {
// If we already populated this one move on
if (i == j || edges_state[j] != '\0') {
j_wings_for_recolor++;
continue;
}
j_wing_str[0] = cube[j_wings_for_recolor->square_index];
j_wing_str[1] = cube[j_wings_for_recolor->partner_index];
flip_wing_str = 0;
// Flip BU around to UB, etc. We do this so the two use the same wing_str.
// U, D, L, and F should always be the first charcter.
if (j_wing_str[1] == 'U' || j_wing_str[1] == 'D') {
if (j_wing_str[0] == 'B' || j_wing_str[0] == 'L' || j_wing_str[0] == 'R' || j_wing_str[0] == 'F') {
flip_wing_str = 1;
}
} else if (j_wing_str[1] == 'L' || j_wing_str[1] == 'R') {
if (j_wing_str[0] == 'B' || j_wing_str[0] == 'F') {
flip_wing_str = 1;
}
}
if (flip_wing_str) {
tmp_char = j_wing_str[0];
j_wing_str[0] = j_wing_str[1];
j_wing_str[1] = tmp_char;
}
if (i_wing_str[0] == j_wing_str[0] && i_wing_str[1] == j_wing_str[1]) {
edges_state[i] = j_wings_for_recolor->edge_index[0];
edges_state[j] = i_wings_for_recolor->edge_index[0];
//LOG("i %d, j %d, wing_str %s, i->edge_index %s, j->edge_index %s\n", i, j, i_wing_str, i_wings_for_recolor->edge_index, j_wings_for_recolor->edge_index);
break;
}
j_wings_for_recolor++;
}
i_wings_for_recolor++;
}
edges_state_bucket = XXH32(edges_state, NUM_EDGES_444, 0) % BUCKETSIZE_EDGES_444;
edges_cost = hex_to_int(reduce_333_edges_only[edges_state_bucket]);
// centers cost
for (int i = 0; i < NUM_CENTERS_444; i++) {
centers_state[i] = cube[centers_444[i]];
}
centers_state_bucket = XXH32(centers_state, NUM_CENTERS_444, 0) % BUCKETSIZE_CENTERS_444;
centers_cost = hex_to_int(reduce_333_centers_only[centers_state_bucket]);
sprintf(result.lt_state, "%s%s", centers_state, edges_state);
//LOG("edges_state %s, edges_cost %d\n", edges_state, edges_cost);
//LOG("centers_state %s, centers_cost %d\n", centers_state, centers_cost);
//LOG("lt_state %s\n", result.lt_state);
int original_cost_to_goal = max(edges_cost, centers_cost);
if (original_cost_to_goal > 0) {
struct key_value_pair *hash_entry = NULL;
hash_entry = hash_find(reduce_333_444, result.lt_state);
if (hash_entry) {
cost_to_goal = hash_entry->value;
} else {
// The higher this number the less you honor the heuristic_stats
// - 0 uses the heuristic_stats exactly as reported
// - 1 subtracts 1 from the heuristic_stats value
// - 99 disables heuristic_stats
//
// You want to put this as high as you can but low enough
// to still speed up the slow IDA searches.
//
// For cube RLLLBDUURUDLBDRULDLBFRRFLLLFFBBFDBUBFBBULFBBLDDUFLRLRDDDRUURFDFDUUDRLLLDBRRURBUDDBFBUFFFRFBURRFU
// 99 : I let it run for an hour and gave up
// 3 : gave up after a few minutes
// 2 : 15 moves, 16s
// 1 : 15 moves, 7s
// 0 : 16 moves, 2.3s
// For cube LRRFDDDULDUFFRFFRDLLULRDDLRLRFLULULDDBBBFFBBBFDDLULBFUDRUUUUBDRFBBDURRLFLRLUUBLDDFUURBFBBFFBRBRR
// 2 : 15 moves, 4.5s
// 1 : 15 moves, 7.4s
// 0 : 15 moves, 13s
unsigned int heuristic_stats_error = 1;
cost_to_goal = original_cost_to_goal + heuristic_stats_error;
// These stats come from back when I was using python IDA here. These are not
// admissible but it DRASTICALLY speeds up this search.
switch (centers_cost) {
case 0:
switch (edges_cost) {
case 0:
cost_to_goal = 1;
break;
case 2:
cost_to_goal = 7;
break;
default:
break;
}
break;
case 1:
switch (edges_cost) {
case 1:
cost_to_goal = 2;
break;
case 2:
cost_to_goal = 9;
break;
case 3:
cost_to_goal = 8;
break;
case 4:
cost_to_goal = 6;
break;
default:
break;
}
case 2:
switch (edges_cost) {
case 1:
cost_to_goal = 7;
break;
case 2:
cost_to_goal = 3;
break;
case 3:
cost_to_goal = 4;
break;
case 4:
cost_to_goal = 5;
break;
case 5:
cost_to_goal = 7;
break;
case 6:
cost_to_goal = 9;
break;
case 10:
cost_to_goal = 14;
break;
case 11:
cost_to_goal = 14;
break;
default:
break;
}
break;
case 3:
switch (edges_cost) {
case 1:
cost_to_goal = 4;
break;
case 2:
cost_to_goal = 4;
break;
case 3:
cost_to_goal = 4;
break;
case 4:
cost_to_goal = 6;
break;
case 5:
cost_to_goal = 7;
break;
case 6:
cost_to_goal = 10;
break;
case 7:
cost_to_goal = 11;
break;
case 8:
cost_to_goal = 12;
break;
case 9:
cost_to_goal = 12;
break;
case 10:
cost_to_goal = 13;
break;
case 11:
cost_to_goal = 15;
break;
default:
break;
}
break;
case 4:
switch (edges_cost) {
case 1:
cost_to_goal = 5;
break;
case 2:
cost_to_goal = 6;
break;
case 3:
cost_to_goal = 6;
break;
case 4:
cost_to_goal = 6;
break;
case 5:
cost_to_goal = 7;
break;
case 6:
cost_to_goal = 10;
break;
case 7:
cost_to_goal = 11;
break;
case 8:
cost_to_goal = 12;
break;
case 9:
cost_to_goal = 13;
break;
case 10:
cost_to_goal = 14;
break;
case 11:
cost_to_goal = 15;
break;
default:
break;
}
break;
case 5:
switch (edges_cost) {
case 2:
cost_to_goal = 6;
break;
case 3:
cost_to_goal = 6;
break;
case 4:
cost_to_goal = 7;
break;
case 5:
cost_to_goal = 8;
break;
case 6:
cost_to_goal = 9;
break;
case 7:
cost_to_goal = 11;
break;
case 8:
cost_to_goal = 12;
break;
case 9:
cost_to_goal = 13;
break;
case 10:
cost_to_goal = 14;
break;
case 11:
cost_to_goal = 15;
break;
case 12:
cost_to_goal = 14;
break;
default:
break;
}
break;
case 6:
switch (edges_cost) {
case 3:
cost_to_goal = 7;
break;
case 4:
cost_to_goal = 10;
break;
case 5:
cost_to_goal = 9;
break;
case 6:
cost_to_goal = 9;
break;
case 7:
cost_to_goal = 10;
break;
case 8:
cost_to_goal = 11;
break;
case 9:
cost_to_goal = 13;
break;
case 10:
cost_to_goal = 14;
break;
case 11:
cost_to_goal = 15;
break;
case 12:
cost_to_goal = 16;
break;
default:
break;
}
break;
case 7:
switch (edges_cost) {
case 5:
cost_to_goal = 12;
break;
case 6:
cost_to_goal = 11;
break;
case 7:
cost_to_goal = 11;
break;
case 8:
cost_to_goal = 12;
break;
case 9:
cost_to_goal = 13;
break;
case 10:
cost_to_goal = 14;
break;
case 11:
cost_to_goal = 14;
break;
case 12:
cost_to_goal = 15;
break;
default:
break;
}
break;
case 8:
switch (edges_cost) {
case 6:
cost_to_goal = 13;
break;
case 7:
cost_to_goal = 13;
break;
case 8:
cost_to_goal = 13;
break;
case 9:
cost_to_goal = 13;
break;
case 10:
cost_to_goal = 14;
break;
case 11:
cost_to_goal = 15;
break;
case 12:
cost_to_goal = 14;
break;
default:
break;
}
break;
case 9:
switch (edges_cost) {
case 8:
cost_to_goal = 13;
break;
case 9:
cost_to_goal = 13;
break;
case 10:
cost_to_goal = 14;
break;
case 11:
cost_to_goal = 15;
break;
default:
break;
}
break;
default:
break;
}
cost_to_goal -= heuristic_stats_error;
// If the heuristic_error is set too high and it gives us a cost_to_goal
// that is below both the centers_cost and edges_cost then we know we
// have subtracted too much in this scenario. Go back to using the max
// among centers_cost and edges_cost.
if (cost_to_goal < original_cost_to_goal) {
cost_to_goal = original_cost_to_goal;
}
// The table we loaded is 6-deep
int MAX_DEPTH = 6;
cost_to_goal = max(cost_to_goal, MAX_DEPTH+1);
}
} else {
cost_to_goal = 0;
}
result.cost_to_goal = cost_to_goal;
return result;
}
int
ida_search_complete_reduce_333_444 (char *cube)
{
// Are the centers solved?
if (cube[6] == cube[7] && cube[10] == cube[11] && cube[6] == cube[10] &&
cube[22] == cube[23] && cube[26] == cube[27] && cube[22] == cube[26] &&
cube[38] == cube[39] && cube[42] == cube[43] && cube[38] == cube[42] &&
cube[54] == cube[55] && cube[58] == cube[59] && cube[54] == cube[58] &&
cube[70] == cube[71] && cube[74] == cube[75] && cube[70] == cube[74] &&
cube[86] == cube[87] && cube[90] == cube[91] && cube[86] == cube[90]) {
// Are the centers valid? U and D must be on opposite sides, etc
if ((cube[6] == 'U' && cube[22] == 'L' && cube[38] == 'F' && cube[54] == 'R' && cube[70] == 'B' && cube[86] == 'D') ||
(cube[6] == 'U' && cube[22] == 'R' && cube[38] == 'B' && cube[54] == 'L' && cube[70] == 'F' && cube[86] == 'D') ||
(cube[6] == 'D' && cube[22] == 'L' && cube[38] == 'B' && cube[54] == 'R' && cube[70] == 'F' && cube[86] == 'U') ||
(cube[6] == 'D' && cube[22] == 'R' && cube[38] == 'F' && cube[54] == 'L' && cube[70] == 'B' && cube[86] == 'U')) {
// Are all edges paired?
if ( cube[2] == cube[3] && cube[5] == cube[9] && cube[8] == cube[12] && cube[14] == cube[15] &&
cube[18] == cube[19] && cube[21] == cube[25] && cube[24] == cube[28] && cube[30] == cube[31] &&
cube[34] == cube[35] && cube[37] == cube[41] && cube[40] == cube[44] && cube[46] == cube[47] &&
cube[50] == cube[51] && cube[53] == cube[57] && cube[56] == cube[60] && cube[62] == cube[63] &&
cube[66] == cube[67] && cube[69] == cube[73] && cube[72] == cube[76] && cube[78] == cube[79] &&
cube[82] == cube[83] && cube[85] == cube[89] && cube[88] == cube[92] && cube[94] == cube[95]) {
return 1;
}
}
}
return 0;
}
|
C
|
#include "libmx.h"
int mx_memcmp(const void *s1, const void *s2, size_t n) {
char *c1 = (char*) s1;
char *c2 = (char*) s2;
size_t i;
for (i = 0; i < n; i++) {
if (*c1 - *c2 != 0)
return *c1 - *c2;
c1++;
c2++;
}
return 0;
}
/*#include <stdio.h>
int main() {
char src[10]="123456wdw";
char dst[10] = "12348wwed";
printf("%d", mx_memcmp(src, dst, 7));
}*/
|
C
|
/*
* M41T0M6F.h
*
* Created on: July 22, 2020
* Author: LongHD
*/
/******************************************************************************/
/******************************************************************************/
/* INCLUDE FILES */
/******************************************************************************/
#include "Hard/I2C/I2C.h"
#include "M41T0M6F.h"
/******************************************************************************/
/* EXPORTED TYPES and DEFINITIONS */
/******************************************************************************/
/******************************************************************************/
/* PRIVATE DATA */
/******************************************************************************/
/******************************************************************************/
/* EXPORTED DATA */
/******************************************************************************/
/******************************************************************************/
/* FUNCTIONS */
/******************************************************************************/
static uint8_t M41T0M6F_BCDToBin(uint8_t bcd);
static uint8_t M41T0M6F_BinToBCD(uint8_t bin);
static uint8_t M41T0M6F_ValidRange(uint8_t val, uint8_t min, uint8_t max);
/******************************************************************************/
/**
* @func M41T0M6F_BCDToBin
* @brief Convert BCD format to Binary format
* @param BCD value
* @retval None
*/
static uint8_t M41T0M6F_BCDToBin(uint8_t bcd){
uint8_t retVal = 10 * (bcd >> 4);
retVal += bcd & 0x0F;
return retVal;
}
/**
* @func M41T0M6F_BcdToBin
* @brief Convert Binary format to BCD format
* @param Bin value
* @retval None
*/
static uint8_t M41T0M6F_BinToBCD(uint8_t bin){
uint8_t low = 0;
uint8_t high = 0;
/* High nibble */
high = bin / 10;
/* Low nibble */
low = bin - (high * 10);
/* Return */
return high << 4 | low;
}
/**
* @func M41T0M6F_ValidRange
* @brief Valid value in range min -> max
* @param Max and min value
* @retval Value
*/
static uint8_t M41T0M6F_ValidRange(uint8_t val, uint8_t min, uint8_t max){
if (val < min) {
return min;
} else if (val > max) {
return max;
}
return val;
}
/**
* @func M41T0M6F_GetTime
* @brief Get date time
* @param Date Time output
* @retval None
*/
void M41T0M6F_GetTime(DateTime_t *dateTime){
uint8_t data[7] = {0};
/* Read multi bytes */
I2C_ReadMulti(M41T0M6F_I2C, M41T0M6F_SLAVE_ID, M41T0M6F_SECONDS_REG, data, 7);
/* Fill data */
dateTime->Seconds = M41T0M6F_BCDToBin(data[M41T0M6F_SECONDS_REG] & 0x7F); // 7 bits
dateTime->Minutes = M41T0M6F_BCDToBin(data[M41T0M6F_MINUTES_REG] & 0x7F); // 7 bits
dateTime->Hours = M41T0M6F_BCDToBin(data[M41T0M6F_HOURS_REG] & 0x3F); // 6 bits
dateTime->Day = M41T0M6F_BCDToBin(data[M41T0M6F_DAY_REG] & 0x03); // 3 bits
dateTime->Date = M41T0M6F_BCDToBin(data[M41T0M6F_DATE_REG] & 0x3F); // 6 bits
dateTime->Month = M41T0M6F_BCDToBin(data[M41T0M6F_MONTH_REG] & 0x1F); // 5 bits
dateTime->Years = M41T0M6F_BCDToBin(data[M41T0M6F_YEARS_REG] & 0xFF); // 8 bits
}
/**
* @func M41T0M6F_SetTime
* @brief Set date time
* @param Date Time output
* @retval None
*/
void M41T0M6F_SetTime(DateTime_t *dateTime){
uint8_t data[7] = {0};
/* Format data */
data[M41T0M6F_SECONDS_REG] = M41T0M6F_BinToBCD(M41T0M6F_ValidRange(dateTime->Seconds, 0, 59));
data[M41T0M6F_MINUTES_REG] = M41T0M6F_BinToBCD(M41T0M6F_ValidRange(dateTime->Minutes, 0, 59));
data[M41T0M6F_HOURS_REG] = M41T0M6F_BinToBCD(M41T0M6F_ValidRange(dateTime->Hours, 0, 23));
data[M41T0M6F_DAY_REG] = M41T0M6F_BinToBCD(M41T0M6F_ValidRange(dateTime->Day, 1, 7));
data[M41T0M6F_DATE_REG] = M41T0M6F_BinToBCD(M41T0M6F_ValidRange(dateTime->Date, 1, 31));
data[M41T0M6F_MONTH_REG] = M41T0M6F_BinToBCD(M41T0M6F_ValidRange(dateTime->Month, 1, 12));
data[M41T0M6F_YEARS_REG] = M41T0M6F_BinToBCD(M41T0M6F_ValidRange(dateTime->Years, 0, 99));
/* Write multi bytes */
I2C_WriteMulti(M41T0M6F_I2C, M41T0M6F_SLAVE_ID, M41T0M6F_SECONDS_REG, data, 7);
}
|
C
|
/*Etapa 4 - Piscar o Leds D1 em PF9 com o SysTick e um contador */
#include "stm32f4xx.h"
void Systick_Wait(uint32_t delay){
SysTick->LOAD = delay - 1;
SysTick->VAL = 0;
while((SysTick->CTRL & 0x00010000) == 0) { //aguarda at zerar o contador do SysTick
}
}
/* Funo que cria delay em X *1ms */
void My_delay(uint32_t delay_ms){
uint32_t i;
for (i=0; i< delay_ms; i++){
Systick_Wait(SystemCoreClock/1000);} //configura o SysTick para 1ms
}
int main(void){
/*local variable */
/*setup GPIO F */
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOFEN_Msk; //1) Enable clock on GPIOF
GPIOF->MODER |= GPIO_MODER_MODE9_0; //2) Set PF10 and PF9 mode (output)
/* inicializa o Systick */
__disable_irq();
SysTick->CTRL = 0; //desabilita o systick
SysTick->LOAD = 0x00FFFFFF; //carrega o valor maximo
SysTick->CTRL = 0x5; //habilita o SysTick sem interrupo
__enable_irq();
//Endless loop
while(1){
GPIOF->ODR &= ~GPIO_ODR_OD9_Msk; //turn on LED D1
My_delay(250); //delay
GPIOF->ODR |= GPIO_ODR_OD9_Msk; //turn off LED D1
My_delay(250); //delay
}
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "utils.h"
#define BUFFER_HEAD_LEN 20
extern MYSQL *mysql;
int timestamp = -1;
int getCurrentTimestamp()
{
time_t t;
return time(&t);
}
int query_alerts_and_send()
{
MYSQL_RES *res_ptr;
MYSQL_ROW mysql_row;
int nRet = 0;
int nCount = 0;
int nClock = 0;
char row_data[1024] = {0};
char buffer_to_send[1024] = {0};
char sql[1024] = {0};
sprintf(sql, "select clock,message,alerttype from alerts where clock>%d order by eventid asc", timestamp);
printf("%s\n", sql);
int res = mysql_query(mysql, sql);
if (res)
{
fprintf(stderr, "SELECT error: %s\n", mysql_error(mysql));
return -1;
}
else
{
res_ptr = mysql_store_result(mysql);
if (res_ptr)
{
nCount = mysql_num_rows(res_ptr);
if(nCount <= 0)
{
mysql_free_result(res_ptr);
return 0;
}
while((mysql_row = mysql_fetch_row(res_ptr)))
{
strcpy(row_data, mysql_row[1]);
nClock = atoi(mysql_row[0]);
timestamp = nClock>timestamp?nClock:timestamp;
//printf("[0:%s\n1:%s\n2:%s]\n", mysql_row[0], row_data, mysql_row[2]);
sprintf(buffer_to_send, "%20u%s", (unsigned int)strlen(row_data), row_data);
printf("%s\n", buffer_to_send);
nRet = send_sock(buffer_to_send, strlen(row_data)+BUFFER_HEAD_LEN);
if(nRet <=0 )
{
break;
nRet = -1;
}
}
if(mysql_errno(mysql))
{
fprintf(stderr, "Retrive error: %s\n", mysql_error(mysql));
nRet = -1;
}
mysql_free_result(res_ptr);
}
}
return nRet;
}
int main(int argc, char ** argv)
{
char server_ip[64];
int server_port = -1;
char mysql_ip[64]={0};
int mysql_port = -1;
char mysql_username[512] = {0};
char mysql_pass[512] = {0};
char mysql_db[512] = {0};
int time_interval = 5;
//timestamp = 1447131104;//getCurrentTimestamp();
timestamp = getCurrentTimestamp();
printf("timestamp %d\n", timestamp);
if(argc<8)
{
printf("use age<path><server ip><server port><mysql ip><mysql user name><mysql password><mysql port><mysql database>\n");
return -1;
}
strcpy(server_ip, argv[1]);
server_port = atoi(argv[2]);
strcpy(mysql_ip, argv[3]);
strcpy(mysql_username, argv[4]);
strcpy(mysql_pass, argv[5]);
mysql_port = atoi(argv[6]);
strcpy(mysql_db, argv[7]);
printf("server_ip:%s, port:%d, mysql ip:%s, mysql user name:%s, mysql port:%d, mysql db:%s\n",
server_ip, server_port, mysql_ip, mysql_username, mysql_port, mysql_db);
for (;;)
{
if (0!=connect_db(mysql_ip, mysql_port, mysql_db, mysql_username, mysql_pass))
{
printf("connect mysql faild: server=%s,port=%d,username=%s,database=%s failed(%s)\n",
mysql_ip, mysql_port, mysql_username, mysql_db, strerror(errno));
sleep(time_interval);
continue;
}
if (0!=connect_sock(server_ip, server_port))
{
printf("connect socket failed: server:%s, port:%d\n", server_ip, server_port);
disconnect_db();
sleep(time_interval);
continue;
}
printf("---------------\n");
for(;;)
{
if(query_alerts_and_send()<0)
{
break;
}
sleep(1);
}
disconnect_sock();
disconnect_db();
sleep(1);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
char number[105];
printf("Enter the number\n");
scanf("%s",number);
int i=0;
int a=0,b=0;
while(number[i]!='\0')
{
if(number[i]=='.')
{
a++;
if(number[i+1]!='\0')
b=1;
}
i++;
}
if(a==1 && b==1)
printf("Valid\n");
else
printf("Invalid\n");
}
|
C
|
#include "proxy.h"
char* communicate(int requestType, char* host, int robot_number, char* robot_id, int data){
int sock; /* Socket descriptor */
struct sockaddr_in echoServAddr; /* Echo server address */
int port = -1; /* Echo server port */
char filename[30]; /* The save name for output */
char fileRequest[100];
char payload[1024];
char* doc = NULL;
char requestMsg[300]; /* String to send to echo server */
char buffer[1024]; /* Buffer for echo string */
int bytesRec; /* Bytes read in single recv()
and total bytes read */
char request[60];
unsigned int totalBytes=0;
char payloadSize[30];
int i;
switch(requestType) {
//Image request
case 2:
port = 8081;
sprintf(request, "/snapshot?topic=/robot_%d/image?width=600?height=500", robot_number);
sprintf(filename,"output2.jpg");
break;
//GPS request
case 4:
port = 8082;
sprintf(request, "/state?id=%s", robot_id);
sprintf(filename,"output4.txt");
break;
//DGPS request
case 8:
port = 8084;
sprintf(request, "/state?id=%s", robot_id);
sprintf(filename,"output8.txt");
break;
//lasers request
case 16:
port = 8083;
sprintf(request, "/state?id=%s", robot_id);
sprintf(filename,"output16.txt");
break;
//move request
case 32:
port = 8082;
sprintf(request, "/twist?id=%s&lx=%d", robot_id, data);
sprintf(filename,"output32.txt");
break;
//turn request
case 64:
port = 8082;
sprintf(request, "/twist?id=%s&az=%d", robot_id, data);
sprintf(filename,"output64.txt");
break;
//stop request
case 128:
port = 8082;
sprintf(request, "/twist?id=%s&lx=0", robot_id);
sprintf(filename,"output128.txt");
break;
default:
break;
}
if(access(filename, F_OK) != -1){
remove(filename);
}
/* Create a reliable, stream socket using TCP */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return "fail";
/* Construct the server address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_port = htons(port); /* Server port */
struct hostent *he;
if ( (he = gethostbyname(host) ) == NULL )
return "fail";
memcpy(&echoServAddr.sin_addr, he->h_addr_list[0], he->h_length);
// This establishes a connection.
if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0){
return "fail";
}
sprintf(requestMsg, "GET %s HTTP/1.1\r\nHOST: %s\r\n\r\n", request, host);
/* This sends the request to the server */
if (send(sock, requestMsg, strlen(requestMsg), 0) < 0)
return "fail";
memset(requestMsg, 0, 300);
FILE *fp = fopen(filename, "wb");
memset(buffer, 0, 1024);
bytesRec = recv(sock, buffer, 1024, 0);
if(bytesRec<0) return "fail";
memset(payload, 0, sizeof(payload));
//process the image request differntly because it is an HTTP 1.0 response
if(requestType==2){
//remove the header
sprintf(payload, "%s", strtok(buffer, "\n"));
for(i=0; i<7; i++)
sprintf(payload, "%s", strtok(NULL, "\n"));
memset(payload, 0, sizeof(payload));
memset(buffer, 0, bytesRec);
while ((bytesRec = recv(sock, buffer, 1024, 0)) > 0){
totalBytes+=bytesRec;
fwrite(buffer, 1, bytesRec, fp);
memset(buffer, 0, bytesRec);
//if the robot goes down, alert the client
if(bytesRec<0) return "fail";
}
}
//process the other responses by removing the header and then saving the payload
else{
//remove the header
sprintf(payload, "%s", strtok(buffer, "\n"));
sprintf(payload, "%s", strtok(NULL, " "));
sprintf(payloadSize, "%s", strtok(NULL, "\n"));
for(i=0; i<5; i++)
{-
sprintf(payload, "%s", strtok(NULL, "\n"));
}
if(strlen(payload)>26){
fwrite(payload, 1, atoi(payloadSize), fp);
totalBytes+=atoi(payloadSize);
}
memset(payload, 0, sizeof(payload));
memset(buffer, 0, bytesRec);
while (totalBytes != atoi(payloadSize) && (bytesRec = recv(sock, buffer, 1024, 0)) > 0){
totalBytes+=bytesRec;
fwrite(buffer, 1, bytesRec, fp);
memset(buffer, 0, bytesRec);
//if the robot goes down, alert the client
if(bytesRec<0) return "fail";
}
}
//printf("\ntotal bytes read %u\n", totalBytes);
fclose(fp);
close(sock);
char * returnString = filename;
return returnString;
}
|
C
|
#ifndef CAR_H
#define CAR_H
#include <raylib.h>
#include "track.h"
enum car_controls_e {
CONTROL_UP,
CONTROL_LEFT,
CONTROL_RIGHT
};
typedef struct car_t {
Model model;
Color color;
Vector3 acceleration;
float angle;
Quaternion direction;
particle_t particle_head;
particle_t particle_tail;
unsigned int controls[3];
} car_t;
void car_init(car_t* car, Model model, Color color, unsigned int controls[3]);
void car_update(car_t* car, track_cell_t track[MAP_SIZE_Z][MAP_SIZE_X]);
void car_draw(car_t* car);
#endif
#ifdef CAR_H_IMPLEMENTATION
#undef CAR_H_IMPLEMENTATION
void car_init(car_t* car, Model model, Color color, unsigned int controls[3]){
car->model = model;
car->color = color;
car->controls[CONTROL_UP] = controls[CONTROL_UP];
car->controls[CONTROL_LEFT] = controls[CONTROL_LEFT];
car->controls[CONTROL_RIGHT] = controls[CONTROL_RIGHT];
car->particle_tail.position.x += 0.1f;
car->particle_tail.position.z += 0.1f;
}
static void car_update_control(car_t* car){
car->acceleration = Vector3Zero();
car->acceleration.z += 0.04f * IsKeyDown(car->controls[CONTROL_UP]);
car->angle += 0.05f * IsKeyDown(car->controls[CONTROL_LEFT]);
car->angle -= 0.05f * IsKeyDown(car->controls[CONTROL_RIGHT]);
car->direction = QuaternionFromAxisAngle((Vector3){0, 1.0f, 0}, car->angle);
// Since we are in a 3D space, we need to use quaternions, 2D angles does not work on 3D unless you force it.
car->acceleration = Vector3RotateByQuaternion(car->acceleration, car->direction);
car->particle_head.position = Vector3Add(car->particle_head.position, car->acceleration);
}
void car_update(car_t* car, track_cell_t track[MAP_SIZE_Z][MAP_SIZE_X]){
/*
* It's important to calculate the cell where the particle is BEFORE updating the particle position, or else,
* the adjusment at the end of the loop will be calculated with a wrong track tile
*/
particle_calculate_cel(&car->particle_head, track);
particle_calculate_cel(&car->particle_tail, track);
// The controls of the car
car_update_control(car);
/*
* The car is just 2 particles, back and tail, this creates the illusion of drift. The
* car model is orientated on the two particles.
*/
particle_update(&car->particle_head, 0.95);
particle_update(&car->particle_tail, 0.96);
// The particles must be 1 car appart, no more, no less.
particle_fix_distance(&car->particle_head, &car->particle_tail);
// We fix the particle position based on the cell bounds.
particle_restrict(&car->particle_head, 48.5f);
particle_restrict(&car->particle_tail, 48.5f);
}
void car_draw(car_t* car){
car->model.transform = MatrixRotateY(Vector2Angle((Vector2){car->particle_tail.position.x, car->particle_tail.position.z}, (Vector2){car->particle_head.position.x, car->particle_head.position.z}) / RAD2DEG);
DrawModel(car->model, car->particle_head.position, 0.5f, car->color);
}
#endif
|
C
|
int main()
{
int m1,n1;
cin >> m1 >> n1;
int m=m1,n=n1;
int a[m];
int b[n];
int i,j,k;
for(i=0;i<m;i++)
{
cin>> a[i];
}
for(i=0;i<n;i++)
{
cin >> b[i];
}
for(i=0;i<m-1;i++)
{
for(j=0;j<m-1-i;j++)
{
if(a[j]>a[j+1])
{
k=a[j];a[j]=a[j+1];a[j+1]=k;
}
}
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(b[j]>b[j+1])
{
k=b[j];b[j]=b[j+1];b[j+1]=k;
}
}
}
for(i=0;i<m;i++)
{
cout << a[i] << " ";
}
for(i=0;i<n-1;i++)
{
cout << b[i] << " ";
}
cout << b[n-1] << endl;
cin.get();cin.get();cin.get();
return 0;
}
|
C
|
#include <stdio.h>
int main ()
{
int x, y, i, s = 1;
float m;
printf("Enter x & y: ");
scanf("%d %d", &x, &y);
for(i = 1; i <= y; i++)
{
s = s*x;
}
m = 1.00/s;
printf("%f", m);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_nodbin_functions.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edavid <edavid@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/26 12:29:03 by edavid #+# #+# */
/* Updated: 2021/09/28 17:34:36 by edavid ### ########.fr */
/* */
/* ************************************************************************** */
#include "../headers/ft_philosophers.h"
t_node_binary *ft_nodbinnew(void *content)
{
t_node_binary *new_el;
new_el = malloc(sizeof(*new_el));
if (new_el == NULL)
return (NULL);
new_el->content = content;
new_el->next = NULL;
new_el->prev = NULL;
return (new_el);
}
void ft_nodbinadd_front(t_node_binary **lst, t_node_binary *new)
{
if (lst == NULL || new == NULL)
return ;
new->next = *lst;
*lst = new;
if (new->next)
new->next->prev = new;
new->prev = NULL;
}
void ft_nodbinclear(t_node_binary **lst, void (*del)(void *), int n)
{
t_node_binary *tmp;
t_node_binary *cur;
if (lst == NULL || del == NULL)
return ;
cur = *lst;
while (cur && n)
{
tmp = cur->next;
ft_nodbindelone(cur, del);
cur = tmp;
if (n > 0 && !--n)
break ;
}
*lst = NULL;
}
void ft_nodbindelone(t_node_binary *lst, void (*del)(void *))
{
if (lst == NULL || del == NULL)
return ;
(*del)(lst);
}
void ft_nodbindel(void *node)
{
if (node == NULL)
return ;
if (((t_node_binary *)node)->content)
free(((t_node_binary *)node)->content);
free(node);
}
|
C
|
#ifndef _XNB_LZ4MG_H_
#define _XNB_LZ4MG_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
/* Decompresses LZ4 from MonoGame. The original C lib has a lot of modes and configs, but
* MonoGame only uses the core 'block' part, which is a fairly simple LZ77 (has one command
* to copy literal and window values, with variable copy lengths).
*
* This is a basic re-implementation (not tuned for performance) for practice/test purposes,
* that handles streaming decompression as a state machine since we can run out of src or dst
* bytes anytime and LZ4 allows any copy length, with copy window as a circular buffer. Not
* sure what's the best/standard way to do it though. Info:
* - https://github.com/lz4/lz4
* - https://github.com/MonoGame/MonoGame/blob/develop/MonoGame.Framework/Utilities/Lz4Stream/Lz4DecoderStream.cs
*/
#define LZ4MG_OK 0
#define LZ4MG_ERROR -1
#define LZ4MG_WINDOW_SIZE (1 << 16)
#define LZ4MG_WINDOW_BYTES 2
#define LZ4MG_MIN_MATCH_LEN 4
#define LZ4MG_VARLEN_MARK 15
#define LZ4MG_VARLEN_CONTINUE 255
typedef enum {
READ_TOKEN,
READ_LITERAL,
COPY_LITERAL,
READ_OFFSET,
READ_MATCH,
SET_MATCH,
COPY_MATCH
} lz4mg_state_t;
typedef struct {
lz4mg_state_t state;
uint8_t token;
int literal_len;
int offset_cur;
int offset_pos;
int match_len;
int match_pos;
int window_pos;
uint8_t window[LZ4MG_WINDOW_SIZE];
} lz4mg_context_t;
typedef struct {
lz4mg_context_t ctx;
uint8_t *next_out; /* next bytes to write (reassign when avail is 0) */
int avail_out; /* bytes available at next_out */
int total_out; /* written bytes, for reference (set to 0 per call if needed) */
const uint8_t *next_in; /* next bytes to read (reassign when avail is 0) */
int avail_in; /* bytes available at next_in */
int total_in; /* read bytes, for reference (set to 0 per call if needed) */
} lz4mg_stream_t;
static void lz4mg_reset(lz4mg_stream_t* strm) {
memset(strm, 0, sizeof(lz4mg_stream_t));
}
/* Decompress src into dst, returning a code and number of bytes used. Caller must handle
* stop (when no more input data or all data has been decompressed) as LZ4 has no end markers. */
static int lz4mg_decompress(lz4mg_stream_t* strm) {
lz4mg_context_t* ctx = &strm->ctx;
uint8_t* dst = strm->next_out;
const uint8_t* src = strm->next_in;
int dst_size = strm->avail_out;
int src_size = strm->avail_in;
int dst_pos = 0;
int src_pos = 0;
uint8_t next_len, next_val;
/* MSVC 64 19.30+ has a /O2 bug where some states aren't handled properly unless a fallthrough is used.
* Seems related to src_pos and doesn't seem fixed by using sub-functions or avoiding gotos. */
while (1) {
/* mostly linear state machine, but it may break anytime when reaching dst or src
* end, and resume from same state in next call */
switch(ctx->state) {
case READ_TOKEN:
if (src_pos >= src_size)
goto buffer_end;
ctx->token = src[src_pos++];
ctx->literal_len = (ctx->token >> 4) & 0xF;
if (ctx->literal_len == LZ4MG_VARLEN_MARK)
ctx->state = READ_LITERAL;
else
ctx->state = COPY_LITERAL;
break;
case READ_LITERAL:
do {
if (src_pos >= src_size)
goto buffer_end;
next_len = src[src_pos++];
ctx->literal_len += next_len;
} while (next_len == LZ4MG_VARLEN_CONTINUE);
ctx->state = COPY_LITERAL;
break;
case COPY_LITERAL:
while (ctx->literal_len > 0) { /* may be 0 */
if (src_pos >= src_size || dst_pos >= dst_size)
goto buffer_end;
next_val = src[src_pos++];
dst[dst_pos++] = next_val;
ctx->window[ctx->window_pos++] = next_val;
if (ctx->window_pos == LZ4MG_WINDOW_SIZE)
ctx->window_pos = 0;
ctx->literal_len--;
};
/* LZ4 is designed to reach EOF with a literal in this state with some empty values */
ctx->offset_cur = 0;
ctx->offset_pos = 0;
ctx->state = READ_OFFSET;
break;
case READ_OFFSET:
do {
if (src_pos >= src_size)
goto buffer_end;
ctx->offset_pos |= (src[src_pos++] << ctx->offset_cur*8);
ctx->offset_cur++;
} while (ctx->offset_cur < LZ4MG_WINDOW_BYTES);
ctx->match_len = (ctx->token & 0xF);
if (ctx->match_len == LZ4MG_VARLEN_MARK)
ctx->state = READ_MATCH;
else
ctx->state = SET_MATCH;
break;
case READ_MATCH:
do {
if (src_pos >= src_size)
goto buffer_end;
next_len = src[src_pos++];
ctx->match_len += next_len;
} while (next_len == LZ4MG_VARLEN_CONTINUE);
ctx->state = SET_MATCH;
//break; // Falthrough for MSVC
case SET_MATCH:
ctx->match_len += LZ4MG_MIN_MATCH_LEN;
ctx->match_pos = ctx->window_pos - ctx->offset_pos;
if (ctx->match_pos < 0) /* circular buffer so negative is from window end */
ctx->match_pos = LZ4MG_WINDOW_SIZE + ctx->match_pos;
ctx->state = COPY_MATCH;
//break; // Fallthrough for MSVC
case COPY_MATCH:
while (ctx->match_len > 0) {
if (dst_pos >= dst_size)
goto buffer_end;
next_val = ctx->window[ctx->match_pos++];
if (ctx->match_pos == LZ4MG_WINDOW_SIZE)
ctx->match_pos = 0;
dst[dst_pos++] = next_val;
ctx->window[ctx->window_pos++] = next_val;
if (ctx->window_pos == LZ4MG_WINDOW_SIZE)
ctx->window_pos = 0;
ctx->match_len--;
};
ctx->state = READ_TOKEN;
break;
default:
goto fail;
}
}
buffer_end:
strm->next_out += dst_pos;
strm->next_in += src_pos;
strm->avail_out -= dst_pos;
strm->avail_in -= src_pos;
strm->total_out += dst_pos;
strm->total_in += src_pos;
return LZ4MG_OK;
fail:
return LZ4MG_ERROR;
}
#if 0
/* non-streamed form for reference, assumes buffers are big enough */
static void decompress_lz4mg(uint8_t* dst, size_t dst_size, const uint8_t* src, size_t src_size) {
size_t src_pos = 0;
size_t dst_pos = 0;
uint8_t token;
int literal_len, match_len, next_len;
int match_pos, match_offset;
int i;
while (src_pos < src_size && dst_pos < dst_size) {
token = src[src_pos++];
if (src_pos > src_size)
break;
/* handle literals */
literal_len = token >> 4;
if (literal_len == 15) {
do {
next_len = src[src_pos++];
literal_len += next_len;
if (src_pos > src_size)
break;
} while (next_len == 255);
}
for (i = 0; i < literal_len; i++) {
dst[dst_pos++] = src[src_pos++];
}
/* can happen at EOF */
if (dst_pos >= dst_size)
break;
/* handle window matches */
match_offset = src[src_pos++];
match_offset |= (src[src_pos++] << 8);
match_len = (token & 0xF);
if (match_len == 15) {
do {
next_len = src[src_pos++];
match_len += next_len;
if (src_pos > src_size)
break;
} while (next_len == 255);
}
match_len += 4; /* min len */
match_pos = dst_pos - match_offset;
for(i = 0; i < match_len; i++) {
dst[dst_pos++] = dst[match_pos++]; /* note RLE with short offsets */
}
}
}
#endif
#endif /* _XNB_LZ4MG_H_ */
|
C
|
/*************************************************************/
/**
* @file MyApplication.c
* @brief Default file for creating custom applications based on the default project
* @author Timo Bayer
*
* @date 25.05.2016
* @version 1.0
*************************************************************/
#include <stdio.h>
#include "MyModule.h"
/**
* @brief Add a number to another number
*
* The function provides the functionality to add to integer numbers. The result is the sum of the two numbers
*
* @param[in] a the first number
* @param[in] b the second number
*
* @return The sum of the two values passed
*/
int add (int a, int b){
return a+b;
}
/**
* @brief The main function of the example application
*
* This function is automatically called on application startup
* The arguments are passed via the runtime environment
*
* @param[in] argc the number of arguments
* @param[in] argv the arguments passed via the runtime environment
*
* @return The status of the execution after the function is terminated
*/
int main(int argc, char **argv) {
add(1,2);
sub(12,2);
}
|
C
|
/*
** EPITECH PROJECT, 2020
** PSU_minishell2_2019
** File description:
** setenv
*/
#include <my_tools.h>
#include <minishell.h>
int my_setenv(char **cmd, data_t *data)
{
if (my_setenv_error_case(cmd, true) == -1) return 84;
if (my_strlentab(cmd) == 1) print_dlist_begin(data->list);
if (my_strlentab(cmd) == 2) {
char tmp[my_strlen(cmd[1]) + 1];
my_strcpy(tmp, cmd[1]);
tmp[my_strlen(cmd[1])] = '=';
tmp[my_strlen(cmd[1]) + 1] = '\0';
pop_list(&data->list, tmp, &cmp_node, free_charptr_node);
push_back(&data->list, my_strdup(tmp), 0);
} else if (my_strlentab(cmd) == 3) {
char tmp[my_strlen(cmd[1]) + my_strlen(cmd[2]) + 1];
my_strcpy(tmp, cmd[1]);
tmp[my_strlen(cmd[1])] = '=';
tmp[my_strlen(cmd[1]) + 1] = '\0';
pop_list(&data->list, tmp, &cmp_node, free_charptr_node);
push_back(&data->list, my_strdup(my_strcat(tmp, cmd[2])), 0);
}
list_to_char_tab(data->list, &data->env);
return 0;
}
int my_unsetenv(char **cmd, data_t *data)
{
if (my_setenv_error_case(cmd, false) == -1) return 84;
for (int i = 1; cmd[i] != NULL; i++) {
char tmp[my_strlen(cmd[i]) + 1];
pop_list(&data->list, my_strcat(my_strcpy(tmp, cmd[i]), "="),
&cmp_node, free_charptr_node);
}
list_to_char_tab(data->list, &data->env);
return 0;
}
|
C
|
#include <string.h>
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
struct List_T {
void * val;
struct List_T * next;
};
extern struct List_T * List_init(void);
extern struct List_T * List_push(struct List_T * list, void * val);
extern int List_length(struct List_T * list);
extern void ** List_toArray(struct List_T * list);
extern struct List_T * List_append(struct List_T * list, struct List_T * tail);
extern struct List_T * List_copy(struct List_T * list);
extern int List_pop(struct List_T ** list);
struct List_T * List_init(void) {
struct List_T * list;
list = (struct List_T * ) malloc(sizeof(struct List_T));
list -> next = NULL;
return list;
}
struct List_T * List_push(struct List_T * list, void * val) {
struct List_T * new_elem = (struct List_T * ) malloc(sizeof(struct List_T));
new_elem -> val = val;
new_elem -> next = list;
return new_elem;
}
int List_length(struct List_T * list) {
int n;
for (n = 0; list; list = list -> next)
n++;
return n;
}
void ** List_toArray(struct List_T * list) {
int i, n = List_length(list);
void ** array = (void ** ) malloc((n + 1) * sizeof( * array));
for (i = 0; i < n; i++) {
array[i] = list -> val;
list = list -> next;
}
array[i] = NULL;
return array;
}
struct List_T * List_append(struct List_T * list, struct List_T * tail) {
struct List_T * p = list;
while (p -> next != NULL) {
p = p -> next;
}
p -> next = tail;
return list;
}
void print_list(char ** array) {
int i;
for (i = 0; array[i]; i++)
printf("%s", array[i]);
printf("\n");
}
int main() {
struct List_T * list1, * list2, * list3;
char ** str1;
list1 = List_push(NULL, "Dang ");
list1 = List_push(list1, "Hoang ");
list1 = List_push(list1, "Hai ");
printf("List 1: ");
str1 = (char ** ) List_toArray(list1);
print_list(str1);
list2 = List_push(NULL, "Siemens");
list2 = List_push(list2, "Graphics ");
list2 = List_push(list2, "Mentor ");
printf("List 2: ");
print_list((char ** ) List_toArray(list2));
list3 = List_append(list1, list2);
printf("Test append list2 into list1: ");
print_list((char ** ) List_toArray(list3));
return 0;
}
|
C
|
/* pow() - program to print square, cube and fourth power of a given number without doing any unnecessary calculations */
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
float x;
clrscr();
printf("Enter a number: ");
scanf("%f", &x);
printf("Square = %f \n", pow(x, 2));
printf("Cube = %f \n", pow(x, 3));
printf("Fourth power = %f \n", pow(x, 4));
getch();
}
/*
Output:
Enter a number: 2.5
Square = 6.250000
Cube = 15.625000
Fourth power = 39.062500
*/
|
C
|
// ConsoleApplication50.cpp : ļ "main" ִнڴ˴ʼ
//
#include <iostream>
#pragma warning(disable:4996)
using namespace std;
template<class T>
struct BSTNode
{
BSTNode(const T& data = T()) :_data(data), _Left(nullptr), _Right(nullptr)
{
}
public:
struct BSTNode<T>* _Left;
struct BSTNode<T>* _Right;
T _data;
};
template<class T>
struct BSTree//СҴ
{
typedef BSTNode<T> node;
public:
BSTree(node* root = nullptr) : _root(root)
{
}
~BSTree()
{
Destroy(_root);
}
node* Find(const T& data)
{
node* root = _root;
while (root)
{
if (root->_data > data)
{
root = root->_Left;
}
else if (root->_data < data)
{
root = root->_Right;
}
else if (root->_data == data)
{
return root;
}
}
return nullptr;
}
bool Insert(const T& data)
{
if (_root == nullptr)
{
_root = new node(data);
return true;
}
node* root = _root;
node* parents = nullptr;//ɵvs
while (root)
{
parents = root;
if (root->_data > data)
{
root = root->_Left;
}
else if (root->_data < data)
{
root = root->_Right;
}
else if (root->_data == data)
{
return false;
}
}
root = new node(data);
if (parents->_data > data)
{
parents->_Left = root;
return true;
}
if (parents->_data < data)
{
parents->_Right = root;
return true;
}
return false;
}
bool Delete(T data)
{
if (nullptr == _root)
return false;
node* root = _root;
node* parents = nullptr;
while (root)
{
parents = root;
if (root->_data == data)
break;
if (root->_data < data)
{
root = root->_Right;
}
if (root->_data > data)
{
root = root->_Left;
}
}
if (nullptr == root)
{
return false;
}
if (root->_Left == nullptr)
{
if (root == _root)
{
_root = root->_Right;
delete root;
return true;
}
if (parents->_Left == root)
{
root->_Right = parents->_Left;
}
else if (parents->_Right == root)
{
root->_Right = parents->_Right;
}
}
if (root->_Right == nullptr && root->_Left != nullptr)
{
if (root == _root)
{
_root = root->_Left;
delete root;
return true;
}
if (parents->_Left == root)
{
root->_Left = parents->_Left;
}
else if (parents->_Right == root)
{
root->_Left = parents->_Right;
}
}
delete root;
return true;
if (root->_Left != nullptr && root->_Right != nullptr)
{
node* pparent = nullptr;
node* Rigroot = root->_Right;
while (Rigroot->_Left)
{
pparent = Rigroot;
Rigroot = Rigroot->_Left;
}
root->_data = Rigroot->_data;
if (Rigroot == pparent->_Left)
{
pparent->_Left = Rigroot->_Right;
}
else
{
pparent->_Right = Rigroot->_Right;
}
delete Rigroot;
}
return true;
}
void Destroy(node*& root)
{
if (root)
{
Destroy(root->_Left);
Destroy(root->_Right);
delete root;
root = nullptr;
}
}
private:
node* _root;
};
int main()
{
BSTNode<int> a;
BSTree<int> b;
b.Insert(1);
b.Insert(2);
b.Insert(3);
b.Insert(4);
b.Delete(1);
}
// г: Ctrl + F5 >ʼִ()˵
// Գ: F5 >ʼԡ˵
// ʹü:
// 1. ʹýԴ/ļ
// 2. ʹŶԴӵԴ
// 3. ʹڲ鿴Ϣ
// 4. ʹôбڲ鿴
// 5. תĿ>ԴµĴļתĿ>ԽдļӵĿ
// 6. ҪٴδĿתļ>>Ŀѡ .sln ļ
|
C
|
#include<stdio.h>
int main()
{
int arr[] ={1, 2,43};
printf("%p\n" , arr + 1 * sizeof());
printf("%")
}
|
C
|
#include <stdio.h>
#include <time.h>
main(){
int x, i;
time_t start, end;
int reps = 1000;
unsigned int size = reps * 1000;
start = time(NULL);
printf("\n");
for (i = 0; i < size; i++){
x = (rand() % 100)%2;
printf("%d ", x);
if (i % 80 == 0)
printf("\n");
}
printf("\n");
end = time(NULL) - start;
printf("The algorithm took %ld seconds.\n", end);
}
|
C
|
#include "semantic.h"
#include "hashTable.h"
#include <string.h>
int structFlag;
int funcParamFlag;
void Program(Node* root){
if(!root) return;
hashInit();
structFlag = funcParamFlag = 0;
ExtDefList(root->child);
//for 2.1
for(int i = 0;i < HASH_SIZE;i++){
if(hashtable[i]){
Entry* cur = hashtable[i];
while(cur){
if(cur->value->kind && cur->value->kind->kind == FUNCTION){
Function* func = (Function*) cur->value->val;
if(func->status == DECLARE){
printf("Error type 18 at Line %d: Undefined function \"%s\".\n", func->line, cur->name);
}
}
cur = cur->next;
}
}
}
}
void ExtDefList(Node* root){
if(!root) return;
ExtDef(root->child);
ExtDefList(root->child->sibling);
}
void ExtDef(Node* root){
if(!root || !root->child) return;
Type* type = Specifier(root->child);
if(!type) return;
Node* second = root->child->sibling;
if(!second) return;
//Specifier ExtDecList SEMI
if(strcmp(second->data, "ExtDecList") == 0){
ExtDecList(second, type);
return;
}
//Specifier SEMI
if(strcmp(second->data, "SEMI") == 0){
return;
}
if(strcmp(second->data, "FunDec") == 0){
//Specifier FunDec CompSt
if(!strcmp(second->sibling->data, "CompSt")){
funcParamFlag = 1;
pushDepth();
FunDec(second, type, 0);
funcParamFlag = 0;
CompSt(second->sibling, type, 0);
return;
}
//Specifier FunDec SEMI
else{
funcParamFlag = 1;
pushDepth();
FunDec(second, type, 1);
popDepth();
funcParamFlag = 0;
return;
}
}
assert(0);
}
Type* Specifier(Node* root){
if(!root || !root->child) return NULL;
Node* child = root->child;
if(strcmp(child->data, "int") == 0){
Type* ret = (Type*)malloc(sizeof(Type));
ret->kind = BASIC;
ret->u.basic = BASIC_INT;
return ret;
}
if(strcmp(child->data, "float") == 0){
Type* ret = (Type*)malloc(sizeof(Type));
ret->kind = BASIC;
ret->u.basic = BASIC_FLOAT;
return ret;
}
if(strcmp(child->data, "StructSpecifier") == 0){
return StructSpecifier(child);
}
assert(0);
return NULL;
}
Type* StructSpecifier(Node* root){
if(!root || !root->child || !root->child->sibling) return NULL;
Node* second = root->child->sibling;
//STRUCT OptTag LC DefList RC
if(strcmp(second->data, "OptTag") == 0){
Type* ret = (Type*)malloc(sizeof(Type));
ret->kind = STRUCTURE;
char* name = second->child->data;
if(hashRead(name)){
printf("Error type 16 at Line %d: Duplicated name \"%s\".\n", second->line, name);
free(ret);
return NULL;
}
Node* fourth = second->sibling->sibling;
structFlag++;
ret->u.structure = DefList(fourth);
structFlag--;
//struct A{};
// if(!ret->u.structure){
// free(ret);
// return NULL;
// }
if(name) {
Value* value = (Value*)malloc(sizeof(Value));
value->kind = ret;
value->val = NULL; // for structure, no other info need to record
hashInsert(name, value);
}
return ret;
}
if(strcmp(second->data, "LC") == 0){
Type* ret = (Type*)malloc(sizeof(Type));
ret->kind = STRUCTURE;
Node* third = second->sibling;
structFlag++;
ret->u.structure = DefList(third);
structFlag--;
return ret;
}
//STRUCT Tag
if(strcmp(second->data, "Tag") == 0){
Value* ret = hashRead(second->child->data);
if(!ret){
printf("Error type 17 at Line %d: Undefined structure \"%s\".\n",second->child->line, second->child->data);
return NULL;
}
return ret->kind;
}
return NULL;
}
void ExtDecList(Node* root, Type* type){
if(!root || !root->child) return;
// VarDec
VarDec(root->child, type);
// VarDec COMMA ExtDecList
if(root->child->sibling){
ExtDecList(root->child->sibling->sibling, type);
}
}
void FunDec(Node* root, Type* type, int isDeclaration){
if(!root || !root->child || !root->child->sibling || !root->child->sibling->sibling) return;
Value* value = hashRead(root->child->data);
if(value && value->kind->kind == FUNCTION && ((Function*)(value->val))->status == DEFINE && !isDeclaration){
printf("Error type 4 at Line %d: Redefined function \"%s\".\n", root->child->line, root->child->data);
return;
}
Node* third = root->child->sibling->sibling;
FieldList* args = NULL;
//ID LP VarList RP
if(!strcmp(third->data, "VarList")){
args = VarList(third);
}
//ID LP RP
if(value && value->kind->kind == FUNCTION){
if(!fieldListEqual(args, ((Function*)(value->val))->arg) || !typeEqual(type, ((Function*)(value->val))->returnType)){
printf("Error type 19 at Line %d: Inconsistent declaration of function \"%s\".\n",root->child->line, root->child->data);
}
}
if(!value){
Function* function = (Function*)malloc(sizeof(Function));
function->returnType = type;
function->line = root->child->line;
function->arg = args;
function->status = isDeclaration;
Value* val = (Value*)malloc(sizeof(Value));
Type* funcType = (Type*)malloc(sizeof(Type));
funcType->kind = FUNCTION;
val->kind = funcType;
val->val = function;
hashInsertDepth(root->child->data, val, 0);
}
if(value && value->kind->kind == FUNCTION && ((Function*)(value->val))->status == DECLARE && !isDeclaration){
((Function*)(value->val))->status = DEFINE;
}
}
FieldList* VarList(Node* root){
if(!root || !root->child) return NULL;
FieldList* ret = ParamDec(root->child);
if(!ret) return NULL;
//ParamDec
//ParamDec COMMA VarList
if(root->child->sibling) {
while(ret->next) ret = ret->next;
ret->next = VarList(root->child->sibling->sibling);
}
return ret;
}
FieldList* ParamDec(Node* root){
if(!root || !root->child || !root->child->sibling) return NULL;
Type* type = Specifier(root->child);
return VarDec(root->child->sibling, type);
}
void CompSt(Node* root, Type* returnType, int addLevel){
if(!root || !root->child || !root->child->sibling || !root->child->sibling->sibling) return;
//LC DefList(**Could be empty**) StmtList RC
if(addLevel) pushDepth();
if(!strcmp(root->child->sibling->data, "DefList")){
DefList(root->child->sibling);
StmtList(root->child->sibling->sibling, returnType);
}
else{
StmtList(root->child->sibling, returnType);
}
popDepth();
}
void StmtList(Node* root, Type* returnType){
if(!root) return;
Stmt(root->child, returnType);
if(root->child) StmtList(root->child->sibling, returnType);
}
void Stmt(Node* root, Type* returnType){
if(!root) return;
char* keyword = root->child->data;
//Exp SEMI
if(!strcmp(keyword, "Exp")){
Exp(root->child);
return;
}
//CompSt
if(!strcmp(keyword, "CompSt")){
CompSt(root->child, returnType, 1);
return;
}
//RETURN Exp SEMI
if(!strcmp(keyword, "RETURN")){
Type* expType = Exp(root->child->sibling);
if(!typeEqual(expType, returnType)){
printf("Error type 8 at Line %d: Type mismatched for return.\n", root->child->sibling->line);
}
return;
}
//IF LP Exp RP Stmt
//IF LP Exp RP Stmt ELSE Stmt
if(!strcmp(keyword, "IF")){
Node* third = root->child->sibling->sibling;
Type* type = Exp(third);
//if(!type) return;
if(type && (type->kind != BASIC || type->u.basic != BASIC_INT)){
printf("Error type 11 at Line %d: Not an integer in if statement.\n", third->line);
return;
}
Node* fifth = third->sibling->sibling;
Stmt(fifth, returnType);
if(fifth->sibling) Stmt(fifth->sibling->sibling, returnType);
return;
}
//WHILE LP Exp RP Stmt
if(!strcmp(keyword, "WHILE")){
Node* third = root->child->sibling->sibling;
Type* type = Exp(third);
if(!type) return;
if(type->kind != BASIC || type->u.basic != BASIC_INT){
printf("Error type 11 at Line %d: Not an integer in while statement.\n", third->line);
return;
}
Node* fifth = third->sibling->sibling;
Stmt(fifth, returnType);
return;
}
assert(0);
return;
}
FieldList* DefList(Node* root){
if(!root || !root->child) return NULL;
FieldList* ret = Def(root->child);
if(!ret) return NULL;
FieldList* tail = ret;
while(tail->next) tail = tail->next;
tail->next = DefList(root->child->sibling);
return ret;
}
FieldList* Def(Node* root){
if(!root || !root->child || !root->child->sibling) return NULL;
Type* type = Specifier(root->child);
return DecList(root->child->sibling, type);
}
FieldList* DecList(Node* root, Type* type){
if(!root || !root->child) return NULL;
FieldList* ret = Dec(root->child, type);
if(!ret) return NULL;
// Dec
if(!root->child->sibling) return ret;
// Dec COMMA DecList
ret->next = DecList(root->child->sibling->sibling, type);
return ret;
}
FieldList* Dec(Node* root, Type* type){
if(!root || !root->child) return NULL;
//VarDec
FieldList* ret = VarDec(root->child, type);
if(!ret) return NULL;
//VarDec ASSIGNOP Exp
if(root->child->sibling){
if(structFlag){
printf("Error type 15 at Line %d: Cannot assign value in struct definition.\n", root->child->line);
return ret;
}
Type* expType = Exp(root->child->sibling->sibling);
if(!expType) return NULL;
if(!typeEqual(ret->type, expType)){
printf("Error type 5 at Line %d: Type mismatched for assignment.\n", root->child->sibling->sibling->line);
}
}
return ret;
}
//Use FieldList instead of Type because name property is assigned here
FieldList* VarDec(Node* root, Type* type){
if(!root || !root->child) return NULL;
//ID
if(root->child->type == ENUM_ID){
FieldList* ret = (FieldList*)malloc(sizeof(FieldList));
ret->name = root->child->data;
Value* readVal = hashRead(ret->name);
if(readVal && (readVal->depth == curDepth || readVal->kind->kind == STRUCTURE || readVal->kind->kind == FUNCTION)){
if(structFlag) printf("Error type 15 at Line %d: Redefined field \"%s\".\n",root->child->line, ret->name);
else printf("Error type 3 at Line %d: Redefined variable \"%s\".\n", root->child->line, ret->name);
free(ret);
return NULL;
}
ret->type = type;
ret->next = NULL;
Value* value = (Value*)malloc(sizeof(Value));
value->kind = type;
value->val = ret;
//if(!funcParamFlag) hashInsert(ret->name, value);
hashInsert(ret->name, value);
return ret;
}
//VarDec LB INT RB
else if(strcmp(root->child->data, "VarDec") == 0){
int num = atoi(root->child->sibling->sibling->data);
Type* childType = (Type*)malloc(sizeof(Type));
childType->kind = ARRAY;
childType->u.array.elem = type;
childType->u.array.size = num;
return VarDec(root->child, childType);
}
assert(0);
return NULL;
}
Type* Exp(Node* root){
if(!root || !root->child) return NULL;
if(strcmp(root->child->data, "Exp") == 0){
char* keyword = root->child->sibling->data;
// Exp ASSIGNOP Exp
if(strcmp(keyword, "ASSIGNOP") == 0){
Node* child = root->child;
int error6 = 0;
Node* first = child->child;
if(!first) error6 = 1;
else{
if(!first->sibling){
//ID
if(first->type != ENUM_ID) error6 = 1;
}
else{
Node* second = first->sibling;
if(!second) error6 = 1;
else{
Node* third = second->sibling;
if(!third) error6 = 1;
else{
Node* fourth = third->sibling;
if(fourth){
//Exp LB Exp RB
if(!(!strcmp(first->data, "Exp") && !strcmp(second->data, "LB") && !strcmp(third->data, "Exp") && !strcmp(fourth->data, "RB"))){
error6 = 1;
}
}
//Exp DOT ID
else{
if(!(!strcmp(first->data, "Exp") && !strcmp(second->data, "DOT") && third->type == ENUM_ID)){
error6 = 1;
}
}
}
}
}
}
if(error6){
printf("Error type 6 at Line %d: The left-hand side of an assignment must be a variable.\n", child->line);
return NULL;
}
Type* type1 = Exp(child);
Type* type2 = Exp(child->sibling->sibling);
if(!type1 || !type2) return NULL;
if(!typeEqual(type1, type2)){
printf("Error type 5 at Line %d: Type mismatched for assignment.\n", child->line);
return NULL;
}
return type1;
}
// Exp AND Exp
// Exp OR Exp
if(!strcmp(keyword, "AND") || !strcmp(keyword, "OR")){
Type* type1 = Exp(root->child);
Type* type2 = Exp(root->child->sibling->sibling);
if(!type1 || !type2) return NULL;
if(type1->kind != BASIC || type2->kind != BASIC || type1->u.basic != BASIC_INT || type2->kind != BASIC_INT){
printf("Error type 7 at Line %d: Type mismatched for operands.\n", root->child->line);
return NULL;
}
return type1;
}
// Exp LB Exp RB
if(!strcmp(keyword, "LB")){
Type* type1 = Exp(root->child);
if(!type1) return NULL;
if(type1->kind != ARRAY){
printf("Error type 10 at Line %d: \"%s\" is not an array.\n", root->child->line, root->child->child->data);
return NULL;
}
Node* third = root->child->sibling->sibling;
Type* type2 = Exp(third);
if(type2->kind != BASIC || type2->u.basic != BASIC_INT){
printf("Error type 12 at Line %d: \"%s\" is not an integer.\n", third->line, third->child->data);
return NULL;
}
return type1->u.array.elem;
}
// Exp DOT ID
if(!strcmp(keyword, "DOT")){
Type* type = Exp(root->child);
if(!type) return NULL;
if(type->kind != STRUCTURE){
printf("Error type 13 at Line %d: Illegal use of \".\".\n", root->child->line);
return NULL;
}
char* field = root->child->sibling->sibling->data;
FieldList* fieldList = type->u.structure;
while(fieldList){
if(!strcmp(field, fieldList->name)){
return fieldList->type;
}
fieldList = fieldList->next;
}
printf("Error type 14 at Line %d: Non-existent field \"%s\".\n", root->child->sibling->sibling->line, field);
return NULL;
}
// Exp RELOP/ADD/MINUS/STAR/DIV Exp
Type* type1 = Exp(root->child);
Type* type2 = Exp(root->child->sibling->sibling);
if(!type1 || !type2) return NULL;
if(type1->kind != BASIC || type2->kind != BASIC || type1->u.basic != type2->u.basic){
printf("Error type 7 at Line %d: Type mismatched for operands.\n", root->child->line);
return NULL;
}
return type1;
}
//LP Exp RP
if(!strcmp(root->child->data, "LP")){
return Exp(root->child->sibling);
}
//MINUS Exp
if(!strcmp(root->child->data, "MINUS")){
Type* type = Exp(root->child->sibling);
if(!type) return NULL;
if(type->kind != BASIC){
printf("Error type 7 at Line %d: Operands type mismatched.\n", root->child->sibling->line);
return NULL;
}
return type;
}
//NOT Exp
if(!strcmp(root->child->data, "NOT")){
Type* type = Exp(root->child->sibling);
if(!type) return NULL;
if(type->kind != BASIC || type->u.basic != BASIC_INT){
printf("Error type 7 at Line %d: Operands type mismatched.\n", root->child->sibling->line);
return NULL;
}
return type;
}
if(root->child->type == ENUM_ID){
char* name = root->child->data;
//ID
if(!root->child->sibling){
Value* value = hashRead(name);
if(!value && !funcParamFlag){
printf("Error type 1 at Line %d: Undefined variable \"%s\".\n", root->child->line, name);
return NULL;
}
return value->kind;
}
Node* third = root->child->sibling->sibling;
if(!third) return NULL;
//ID LP RP
//ID LP Args RP
if(!strcmp(root->child->sibling->data, "LP")){
if(!strcmp(name, "read") || !strcmp(name, "write")) return NULL;
Value* value = hashRead(name);
if(!value){
printf("Error type 2 at Line %d: Undefined function \"%s\".\n", root->child->line, name);
return NULL;
}
if(value->kind->kind != FUNCTION){
printf("Error type 11 at Line %d: \"%s\" is not a function.\n", root->child->line, root->child->data);
return NULL;
}
if(!strcmp(third->data, "Args")){
FieldList* arg = Args(third);
FieldList* arg2 = ((Function*)(value->val))->arg;
if(!fieldListEqual(arg, arg2)) {
printf("Error type 9 at Line %d: Function \"%s\" is not applicable for given arguments.\n",
third->line, name);
return NULL;
}
}
return ((Function*)(value->val))->returnType;
}
assert(0);
return NULL;
}
//INT
if(root->child->type == ENUM_INT){
Type* ret = (Type*)malloc(sizeof(Type));
ret->kind = BASIC;
ret->u.basic = BASIC_INT;
return ret;
}
//FLOAT
if(root->child->type == ENUM_FLOAT){
Type* ret = (Type*)malloc(sizeof(Type));
ret->kind = BASIC;
ret->u.basic = BASIC_FLOAT;
return ret;
}
return NULL;
}
FieldList* Args(Node* root){
if(!root || !root->child) return NULL;
//Exp
//Exp COMMA Args
FieldList* ret = (FieldList*)malloc(sizeof(FieldList));
ret->type = Exp(root->child);
if(root->child->sibling){
ret->next = Args(root->child->sibling->sibling);
}
else ret->next = NULL;
return ret;
}
int typeEqual(Type* type1, Type* type2){
if(!type1 && !type2) return 1;
if(!type1 || !type2) return 0;
if(type1->kind != type2->kind) return 0;
if(type1->kind == BASIC){
return type1->u.basic == type2->u.basic;
}
if(type1->kind == ARRAY){
return typeEqual(type1->u.array.elem, type2->u.array.elem);
}
if(type1->kind == STRUCTURE){
return fieldListEqual(type1->u.structure, type2->u.structure);
}
return 0;
}
int fieldListEqual(FieldList* f1, FieldList* f2){
if(!f1 || !f2) return 0;
while(f1 && f2){
if(!typeEqual(f1->type, f2->type)) return 0;
f1 = f1->next;
f2 = f2->next;
}
if(f1 || f2) return 0;
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bitrank/bitrankw32int.h"
#include "bitrank/bit_array.h"
#define num_threads __cilkrts_get_nworkers()
#define FACTOR 20 // bitmap usage
typedef unsigned int symbol;
symbol* read_text_from_file(const char* fn, unsigned long* n) {
FILE* fp = fopen(fn, "r");
size_t read;
if (!fp) {
fprintf(stderr, "Error opening file \"%s\".\n", fn);
exit(-1);
}
fseek(fp, 0L, SEEK_END);
*n = (unsigned long)ftell(fp);
symbol* t;
t = malloc(*n);
*n = *n / sizeof(symbol); // Number of symbols
fseek(fp, 0L, SEEK_SET);
read = fread(t, sizeof(symbol), *n, fp);
if(read != *n){
fprintf(stderr, "Error reading file \"%s\".\n", fn);
exit(-1);
}
fclose(fp);
return t;
}
BIT_ARRAY** compute_bitarrays(symbol* T, unsigned long n, unsigned int alphabet) {
unsigned int levels = log2(alphabet);
BIT_ARRAY** bit_arrays = (BIT_ARRAY**)malloc(levels * sizeof(BIT_ARRAY*));
for (uint i = 0; i < levels; i++) {
// Number of nodes in the i-th level
unsigned int nnum = 1 << i;
// Allocating memory to save the number of symbols on each node of the wavelet tree
unsigned int* counters = (unsigned int*)calloc(nnum, sizeof(unsigned int));
bit_arrays[i] = bit_array_create(n);
symbol k;
unsigned int schunk = 0;
unsigned int desp1 = levels - i, desp2 = desp1 - 1;
// Counting the number of symbols on each node
for (uint j = 0; j < n; j++) {
k = T[j];
schunk = (unsigned int)k >> desp1;
counters[schunk]++;
}
// Offsets
unsigned int cnt = 0, aux = 0;
for(uint z = 0; z < nnum; z++) {
aux = counters[z];
counters[z] = cnt;
cnt += aux;
}
// Filling the bit arrays
for (uint j = 0; j < n; j++) {
k = T[j];
schunk = (unsigned int)k >> desp1;
k &= 1 << desp2;
if (k)
bit_array_set_bit(bit_arrays[i], counters[schunk]);
counters[schunk]++;
}
free(counters);
}
return bit_arrays;
}
bitRankW32Int** rank_select_wt(BIT_ARRAY** bit_arrays, unsigned int alphabet) {
unsigned int levels = log2(alphabet);
bitRankW32Int** wtree = (bitRankW32Int**)malloc(levels * sizeof(bitRankW32Int*));
for (unsigned int i = 0; i < levels; i++) {
wtree[i] = createBitRankW32Int(bit_arrays[i]->words,
bit_arrays[i]->num_of_bits, 1, FACTOR);
}
return wtree;
}
unsigned int _wt_rank_0(bitRankW32Int* level, unsigned int idx) {
return ((1 + idx) - rank(level, idx));
}
unsigned int _wt_rank_1(bitRankW32Int* level, unsigned int idx) {
return rank(level, idx);
}
uint wt_access(bitRankW32Int** wtree, uint idx, uint alphabet) {
uint lls = 0; // Lower limit of the sequence
uint uls = lenght_in_bits(wtree[0]) - 1; ; // Upper limit of the sequence
int levels = log2(alphabet);
uint lla = 0; // Lower limit of the alphabet
uint ula = alphabet - 1; // Upper limit of the alphabet
uint crank = 0;
for (uint i = 0; i < levels; i++) {
if(isBitSet(wtree[i], idx + lls) != 1) {
crank = _wt_rank_0(wtree[i], lls + idx) - _wt_rank_0(wtree[i], lls-1);
idx = crank - 1;
ula = (lla + ula) / 2;
uls -= _wt_rank_1(wtree[i], uls) - _wt_rank_1(wtree[i], lls-1);
} else {
crank = _wt_rank_1(wtree[i], lls + idx) - _wt_rank_1(wtree[i], lls - 1);
idx = crank - 1;
lla = ((lla + ula) / 2) + 1;
lls += _wt_rank_0(wtree[i], uls) - _wt_rank_0(wtree[i], lls - 1);
}
}
return lla;
}
uint wt_rank(bitRankW32Int** wtree, uint alphabet, uint idx, symbol sym) {
uint lls = 0; // Lower limit of the sequence
uint uls = lenght_in_bits(wtree[0]) - 1; ; // Upper limit of the sequence
int levels = log2(alphabet);
uint crank = 0;
symbol k;
for (uint i = 0; i < levels; i++) {
uint desp = levels - i - 1;
k = sym & (1 << desp);
if(k) {
crank = _wt_rank_1(wtree[i], lls + idx) - _wt_rank_1(wtree[i], lls - 1);
idx = crank - 1;
lls += _wt_rank_0(wtree[i], uls) - _wt_rank_0(wtree[i], lls - 1);
} else {
crank = _wt_rank_0(wtree[i], lls + idx) - _wt_rank_0(wtree[i], lls-1);
idx = crank - 1;
uls -= _wt_rank_1(wtree[i], uls) - _wt_rank_1(wtree[i], lls-1);
}
}
k = sym & 1;
if(k)
crank = _wt_rank_1(wtree[levels-1], lls + idx) - _wt_rank_1(wtree[levels-1],
lls - 1);
else
crank = _wt_rank_0(wtree[levels-1], lls + idx) -
_wt_rank_0(wtree[levels-1], lls-1);
return crank;
}
int main(int argc, char* argv[]) {
if(argc != 3){
fprintf(stderr, "Execute: %s <input file> <alphabet size>\n", argv[0]);
exit(-1);
}
unsigned long n; // Size of the input sequence
symbol* text = read_text_from_file(argv[1], &n); // Input sequence
unsigned int alphabet = (unsigned int)atoi(argv[2]); // Size of the alphabet
struct timespec stime, etime;
double t;
if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &stime)) {
fprintf(stderr, "clock_gettime failed");
exit(-1);
}
// Wavelet tree construction
BIT_ARRAY** bit_arrays = compute_bitarrays(text, n, alphabet);
bitRankW32Int** wtree = rank_select_wt(bit_arrays, alphabet);
if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &etime)) {
fprintf(stderr, "clock_gettime failed");
exit(-1);
}
t = (etime.tv_sec - stime.tv_sec) + (etime.tv_nsec - stime.tv_nsec) / 1000000000.0;
printf("%d,%s,%lu,%lf\n", 1, argv[1], n, t);
uint ii = 9, sym = 156;
printf("rank(%u): %u\n", ii, wt_rank(wtree, alphabet, ii, sym));
free(text);
return EXIT_SUCCESS;
}
|
C
|
#ifndef __ARPOISON__DEBUG
#define __ARPOISON__DEBUG
#include "ip_address.h"
#include "mac_address.h"
inline void print(MACAddress address){
for(int i = 0; i < MAC_ADDRESS_LEN - 1; ++i){
printf("%.2X:", address.octets[i]);
}
printf("%.2X\n", address.octets[MAC_ADDRESS_LEN - 1]);
}
inline void print(IPv4Address address){
for(int i = 0; i < IP_ADDRESS_LEN - 1; ++i){
printf("%d.", address.octets[i]);
}
printf("%d\n", address.octets[IP_ADDRESS_LEN - 1]);
}
void debug_buffer(uint8_t buffer[]){
for(int i = 0; i < 42; ++i){
printf("%.2X", buffer[i]);
}
printf("\n");
}
#endif
|
C
|
/* bench.c
Rémi Attab (remi.attab@gmail.com), 23 Jan 2016
FreeBSD-style copyright and disclaimer apply
*/
#include "bench.h"
#include "utils/time.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// -----------------------------------------------------------------------------
// utils
// -----------------------------------------------------------------------------
static double scale_elapsed(double t, char *s)
{
static const char scale[] = "smunp";
size_t i = 0;
for (i = 0; i < sizeof(scale); ++i) {
if (t >= 1.0) break;
t *= 1000.0;
}
*s = scale[i];
return t;
}
// -----------------------------------------------------------------------------
// iota_bench
// -----------------------------------------------------------------------------
struct iota_bench
{
void **setup_data;
bool started;
struct timespec start;
bool stopped;
struct timespec stop;
};
void *iota_bench_setup(struct iota_bench *bench, void *data)
{
if (data) *bench->setup_data = data;
return *bench->setup_data;
}
void iota_bench_start(struct iota_bench *bench)
{
assert(!bench->started);
bench->started = true;
clock_monotonic(&bench->start);
}
void iota_bench_stop(struct iota_bench *bench)
{
iota_no_opt_clobber(); // make sure everything is done before we stop.
clock_monotonic(&bench->stop);
bench->stopped = true;
}
// -----------------------------------------------------------------------------
// utils
// -----------------------------------------------------------------------------
static double sec() { return 1; }
static double msec() { return sec() / 1000; }
static double usec() { return msec() / 1000; }
static double nsec() { return usec() / 1000; }
static double bench_elapsed(struct iota_bench *bench)
{
return
(bench->stop.tv_sec - bench->start.tv_sec) +
((bench->stop.tv_nsec - bench->start.tv_nsec) * nsec());
}
static double run_bench(
struct iota_bench *bench,
iota_bench_fn_t fn,
void *ctx,
size_t id,
size_t n)
{
fn(bench, ctx, id, n);
if (!bench->stopped) iota_bench_stop(bench);
assert(bench->started);
return bench_elapsed(bench);
}
int cmp_elapsed(const void *_lhs, const void *_rhs)
{
double lhs = *((const double *) _lhs);
double rhs = *((const double *) _rhs);
if (lhs < rhs) return -1;
if (lhs > rhs) return 1;
return 0;
}
static void bench_report(const char *title, size_t n, double *dist, size_t dist_len)
{
for (size_t i = 0; i < dist_len; ++i) dist[i] /= n;
qsort(dist, dist_len, sizeof(double), cmp_elapsed);
char p0_mul = ' ';
double p0_val = scale_elapsed(dist[0], &p0_mul);
char p50_mul = ' ';
double p50_val = scale_elapsed(dist[dist_len / 2], &p50_mul);
char p90_mul = ' ';
double p90_val = scale_elapsed(dist[(dist_len * 90) / 100], &p90_mul);
printf("bench: %-30s %8lu p0:%6.2f%c p50:%6.2f%c p90:%6.2f%c\n",
title, n, p0_val, p0_mul, p50_val, p50_mul, p90_val, p90_mul);
}
void iota_bench(const char *title, iota_bench_fn_t fn, void *ctx)
{
const double duration = 1 * msec();
const size_t iterations = 1000;
size_t dist_len = iterations;
double dist[dist_len];
memset(dist, 0, dist_len * sizeof(double));
size_t n = 1;
double elapsed = -1;
for (; elapsed < duration; n *= 2) {
assert(n < 100UL * 1000 * 1000 * 1000);
void *setup_data;
struct iota_bench bench = { .setup_data = &setup_data };
elapsed = run_bench(&bench, fn, ctx, 0, n);
}
for (size_t i = 0; i < iterations; ++i) {
void *setup_data;
struct iota_bench bench = { .setup_data = &setup_data };
dist[i] = run_bench(&bench, fn, ctx, 0, n);
}
bench_report(title, n, dist, dist_len);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.