blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
b9fd13b80d3aa8f5e639affe27d6141a87c34524 | C++ | lepexys/projects | /home/home/home.cpp | UTF-8 | 6,535 | 2.96875 | 3 | [] | no_license | #include "pch.h"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <clocale>
#include <iomanip>
using namespace std;
struct Shower
{
bool* u,*s,*ls;
int n;
Shower(unsigned v,int num)
{
n = num;
u = new bool[n];
for (int i = 0; i < n; i++)
{
u[i] = true;
if (i == v)
u[i] = false;
}
s = new bool[n];
ls = new bool[n];
for (int i = 0; i < n; i++)
{
ls[i] = false;
s[i] = false;
if (i == v)
{
s[i] = true;
}
}
}
bool Copy()
{
bool k = false;
for (int i = 0; i < n; i++)
{
if (s[i])
k = true;
ls[i] = s[i];
s[i] = false;
}
return k;
}
void Show(int **mat,int v)
{
for (int j = 0; j < n; j++)
{
if (mat[v][j] == 1)
if (u[j])
{
cout << j;
u[j] = false;
s[j] = true;
}
}
}
void Check(int **mat)
{
if(Copy())
{
for (int i = 0; i < n; i++)
{
if (ls[i])
{
Show(mat, i);
}
}
Check(mat);
}
}
void Show(int *mat, int v, int c)
{
for (int j = 0; j < c; j+=2)
{
if ((mat[j] == v))
if (u[mat[j + 1]])
{
cout << mat[j+1];
u[mat[j+1]] = false;
s[mat[j+1]] = true;
}
if (mat[j + 1] == v)
if (u[mat[j]])
{
cout << mat[j];
u[mat[j]] = false;
s[mat[j]] = true;
}
}
}
void Check(int *mat, int c)
{
if (Copy())
{
for (int i = 0; i < c; i+=2)
{
if (ls[mat[i]])
{
Show(mat, mat[i], c);
}
}
Check(mat,c);
}
}
};
int main()
{
int **mat = nullptr, **ormat = nullptr, *list = nullptr;
int n = 0;
bool k = true;
setlocale(LC_ALL, "rus");
while (k)
{
unsigned t = NULL;
cout << "Матрица(\"1\") или список (\"2\")" << endl;
cin >> t;
if (!t)
{
cout << "Неправильное значение";
break;
}
if (t == 1)
{
k = false;
cout << "Матрица задаётся следующим образом:" << endl;
cout << "Сначале в файле пишется степень матрицы, затем через пробел её элементы" << endl;
cout << "(Если элементов нехватает, матрица дополняется нулями, используются только 0 и 1)" << endl;
ifstream file;
char buff[20];
file.open("matrix.txt");
if (file.is_open())
cout << "file is open"<<endl;
else
{
cout << "file is not open" << endl;
break;
}
file >> n;
mat = new int*[n];
ormat = new int*[n];
for (int i = 0; i < n; i++)
{
mat[i] = new int[n];
ormat[i] = new int[n];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!file.eof())
file >> ormat[i][j];
else
ormat[i][j] = 0;
if (mat[i][j] != 1)
mat[i][j] = ormat[i][j];
if (mat[i][j] == 1)
mat[j][i] = 1;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout<<mat[i][j];
}
cout << endl;
}
unsigned v;
do {
cout << "Введите номер вершины, из которой происходит обход...";
cin >> v;
} while (v >= n);
cout << "Очерёдность обхода :";
Shower* sh = new Shower(v,n);
sh->Check(mat);
cout << endl;
int count = 0;
cout << " ";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i != j)
{
if (ormat[i][j] == 1)
{
count++;
cout << i << "->" << j << " ";
}
}
}
}
cout << endl;
int **incmat;
incmat = new int*[n];
for (int i = 0; i < n; i++)
{
incmat[i] = new int[count];
for (int j = 0; j < count; j++)
incmat[i][j] = 0;
}
int p = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i != j)
{
if (ormat[i][j] == 1)
{
incmat[i][p] = -1;
incmat[j][p] = 1;
p++;
}
}
}
}
for (int i = 0; i < n; i++)
{
printf("%2d", i);
for (int j = 0; j < count; j++)
printf("%4d ", incmat[i][j]);
cout << endl;
}
}
else if (t == 2)
{
k = false;
cout << "Матрица задаётся следующим образом:" << endl;
cout << "Сначале в файле пишется степень матрицы, затем через пробел её элементы" << endl;
cout << "(Если элементов нехватает, матрица дополняется нулями, используются только 0 и 1)" << endl;
ifstream file;
char buff[20];
file.open("matrix.txt", ifstream::in);
if (file.is_open())
cout << "file is open" << endl;
else
{
cout << "file is not open" << endl;
break;
}
file >> n;
int cnt = 0;
mat = new int*[n];
ormat = new int*[n];
for (int i = 0; i < n; i++)
{
mat[i] = new int[n];
ormat[i] = new int[n];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!file.eof())
{
file >> ormat[i][j];
if ((ormat[i][j] == 1) && (i != j))
cnt += 2;
}
else
ormat[i][j] = 0;
if (mat[i][j] != 1)
mat[i][j] = ormat[i][j];
if (mat[i][j] == 1)
mat[j][i] = 1;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << mat[i][j];
}
cout << endl;
}
list = new int[cnt];
int d = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if ((ormat[i][j] == 1) && (i != j))
{
list[d] = i;
list[d + 1] = j;
d += 2;
}
}
}
unsigned v;
do {
cout << "Введите номер вершины, из которой происходит обход...";
cin >> v;
} while (v >= n);
cout << "Очерёдность обхода :";
Shower* sh = new Shower(v, n);
sh->Check(list, cnt);
cout << endl;
cout << " ";
for (int i = 0; i < cnt; i+=2)
{
cout << list[i] << "->" << list[i+1] << " ";
}
cout << endl;
int **incmat;
incmat = new int*[n];
for (int i = 0; i < n; i++)
{
incmat[i] = new int[cnt/2];
for (int j = 0; j < cnt/2; j++)
incmat[i][j] = 0;
}
int p = 0;
for (int i = 0; i < cnt; i+=2)
{
incmat[list[i]][p] = -1;
incmat[list[i+1]][p] = 1;
p++;
}
for (int i = 0; i < n; i++)
{
printf("%2d", i);
for (int j = 0; j < cnt/2; j++)
printf("%4d ", incmat[i][j]);
cout << endl;
}
}
}
return NULL;
} | true |
90f67249eda49be313682dbae142df0668f08715 | C++ | glw3d/_GLW3D | /glw/src/glw/RenderTarget.hpp | UTF-8 | 2,900 | 2.609375 | 3 | [] | no_license | /**
Author: Mario J. Martin <dominonurbs$gmail.com>
A frame buffer is basically used for off-screen rendering.
*******************************************************************************/
#ifndef _HGW_FRAMEBUFFER_H
#define _HGW_FRAMEBUFFER_H
#include "common/log.h"
#include "common/check_malloc.h"
#include "signatures.h"
#include "defines.h"
#include "gwdata.h"
#include "Stream.hpp"
#include "RenderBuffer.hpp"
#include "Frame.hpp"
namespace gw
{
/* */
class RenderTarget : public gwRenderTarget
{
public:
int signature;
RenderBuffer render_buffer;
/* List of cameras to be rendered */
DynamicStack<Frame> list_frames;
RenderTarget()
{
width = 0;
height = 0;
background_color = gwColorBlack;
color_texture = &(render_buffer.color.image);
signature = _GW_SIGNATURE_RENDER_TARGET;
/* Ovewrite the signature of the texture in the render buffer */
render_buffer.color.signature = _GW_SIGNATURE_RENDER_BUFFER;
}
/* Checks and updates the buffers if the dimensions have changed */
void update( const int screen_width, const int screen_height )
{
if (width == 0 || height == 0){
if (screen_width != render_buffer.buffer_width
|| screen_height != render_buffer.buffer_height)
{
render_buffer.generateBuffers( screen_width, screen_height );
}
}
else{
if (width != render_buffer.buffer_width
|| height != render_buffer.buffer_height)
{
render_buffer.generateBuffers( width, height );
}
}
}
gwViewPort clear()
{
GLfloat bgc_r = (GLfloat)background_color.r / 255;
GLfloat bgc_g = (GLfloat)background_color.g / 255;
GLfloat bgc_b = (GLfloat)background_color.b / 255;
GLfloat bgc_a = (GLfloat)background_color.a / 255;
glClearColor( bgc_r, bgc_g, bgc_b, bgc_a );
glBindFramebuffer( GL_FRAMEBUFFER, render_buffer.fbo );
glViewport( 0, 0, render_buffer.buffer_width, render_buffer.buffer_height );
glScissor( 0, 0, render_buffer.buffer_width, render_buffer.buffer_height );
GLenum att[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers( 1, att );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
gwViewPort viewport;
viewport.x0 = 0;
viewport.y0 = 0;
viewport.width = render_buffer.buffer_width;
viewport.height = render_buffer.buffer_height;
viewport.fbo = render_buffer.fbo;
return viewport;
}
};
} /* end namespace */
#endif
| true |
531243d2a3c6faf483a88ce4b52e60ab32ab2aa8 | C++ | duncalucian/Fundamental-algorithms | /AF/Lab3/main.cpp | UTF-8 | 3,525 | 2.921875 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "Profiler.h"
#define LEFT(i) 2*i
#define RIGHT(i) 2*i+1
#define PARENT(i) i/2
#define MAX_SIZE 10000
Profiler p("heaps");
/* Observatii
Se poate observa din grafic ca constructia Bottom Up este mai eficienta decat constructia Top Down. In implementare Bottom UP
se reduce numarul de noduri verificate prin considerarea frunzelor ca fiind deja heap uri astfel complexitatea fiind O(n). La
metoda Top Down complexitatea este in medie O(n logN).
In worst case se observa mult mai bine diferenta dintre cele 2 tipuri de algoritmi, Bottom up (O(n)) avand un numar mult mai
mic de operatii fata de top down (O(n logN)).
*/
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void print(int *arr) {
for (int i = 1; i <= arr[0]; ++i)
printf("%d ", arr[i]);
printf("\n");
}
//Bottom UP
void maxHeapify(int *arr, int i, int n) {
Operation mHeap_SUM = p.createOperation("BottomUp_SUM", n);
int l = LEFT(i);
int r = RIGHT(i);
int max;
mHeap_SUM.count(1);
if (l <= arr[0] && arr[l] > arr[i])
max = l;
else max = i;
mHeap_SUM.count(1);
if (r <= arr[0] && arr[r] > arr[max])
max = r;
if (max != i) {
mHeap_SUM.count(3);
swap(&arr[i], &arr[max]);
maxHeapify(arr, max, n);
}
}
void maxHeapBottomUp(int *arr) {
for (int i = arr[0] / 2; i >= 1; --i) {
maxHeapify(arr, i, arr[0]);
}
}
//TOP_DOWN
void heapIncreaseKey(int *arr, int i, int key, int n) {
Operation mHeapInsert_SUM = p.createOperation("TopDown_SUM", n);
arr[i] = key;
mHeapInsert_SUM.count(2);
while (i > 1 && arr[PARENT(i)] < arr[i]) {
mHeapInsert_SUM.count(3);
swap(&arr[i], &arr[PARENT(i)]);
i = PARENT(i);
}
}
void maxHeapInsert(int *arr, int key, int n) {
++arr[0];
arr[arr[0]] =(int)-INFINITY;
heapIncreaseKey(arr, arr[0], key, n);
}
void maxHeapTopBottom(int *arr) {
int n = arr[0];
arr[0] = 1;
for (int i = 2; i <= n; ++i)
maxHeapInsert(arr, arr[i], n);
}
//HeapSort
void heapSort(int *arr) {
maxHeapBottomUp(arr);
int n = arr[0];
for (int i = n; i >= 2; --i) {
swap(&arr[1], &arr[i]);
--arr[0];
maxHeapify(arr, 1, n);
}
arr[0] = n;
}
//Average
void generateAverage() {
int *x = (int*)malloc(MAX_SIZE * 4);
int *y = (int*)malloc(MAX_SIZE * 4);
for (int i = 1; i <= 5; ++i) {
for (int j = 100; j <= MAX_SIZE; j += 100) {
FillRandomArray(x, j + 1);
x[0] = j ;
memcpy(y, x, j * 4);
maxHeapBottomUp(x);
maxHeapTopBottom(y);
}
}
p.divideValues("BottomUp_SUM", 5);
p.divideValues("TopDown_SUM", 5);
p.createGroup("SUM_av", "TopDown_SUM","BottomUp_SUM");
free(x);
free(y);
}
void generateWorst() {
int *x = (int*)malloc(MAX_SIZE * 4);
int *y = (int*)malloc(MAX_SIZE * 4);
for (int j = 100; j <= MAX_SIZE; j += 100) {
FillRandomArray(x, j+1,1,12000,true,1);
x[0] = j ;
memcpy(y, x, j * 4);
maxHeapBottomUp(x);
maxHeapTopBottom(y);
}
p.createGroup("Comparations_worst", "TopDown_Comp", "BottomUp_Comp");
p.createGroup("Assignments_worst", "TopDown_Assign", "BottomUp_Assign");
p.createGroup("SUM_worst", "TopDown_SUM", "BottomUp_SUM");
free(x);
free(y);
}
void generateSorted() {
int x[30] = { 14,2,8,14,23,55,15,21,43,23,61,82,34,57,18 };
print(x);
heapSort(x);
print(x);
}
int main() {
generateAverage();
p.reset("Worst");
generateWorst();
p.showReport();
generateSorted();
} | true |
6d8d301d92d0d5aae7776a5248eb001e5ceba4f1 | C++ | mmmaxou/imac-cpp | /TP8/Error.cpp | UTF-8 | 428 | 2.78125 | 3 | [] | no_license | #include "./Error.hpp"
#include <string>
#include <iostream>
Error::Error()
: _message("")
{};
Error::Error(const std::string &message)
: _message(message)
{};
Error::~Error() {};
const char* Error::what() const noexcept {
std::string message = std::string("Error::At " + std::string(__FILE__) + ":" + std::to_string(__LINE__) + " :\n Message: "+ _message).c_str();
std::cout << message;
return message.c_str();
}; | true |
6ed96191d82ae1b6f499dce86f51f83a4aa93b33 | C++ | brandonalfred/ParallelProgramingExamples | /99s-openmp.cpp | UTF-8 | 2,932 | 3.34375 | 3 | [] | no_license | #include <omp.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <stdio.h>
using namespace std;
int main()
{
int count = 0, i;
int parCount = 0;
int const size = 10000000; // 10,000,000
//int myArray [size];
int *myArray = new int[size];
double start_time, end_time;
double omp_start_time, omp_end_time;
//initialize random number generator
srand((unsigned)time(NULL));
// Initialize the array using random numbers
for (i = 0; i < size; i++)
myArray[i] = rand() % 100;
//Serial Code
start_time = omp_get_wtime();
for (i = 0; i < size; i++)
if (myArray[i] == 99)
count++;
end_time = omp_get_wtime();
printf ("The serial code indicates that there are %d 99s in the array.\n", count);
printf ("The serial code used %f seconds to complete the execution.\n\n", end_time - start_time);
// Parallel Code (2 Threads)
omp_set_num_threads(2);
omp_start_time = omp_get_wtime();
#pragma omp parallel for private(i) shared(myArray)
for (i = 0; i < size; i++)
{
if (myArray[i] == 99)
{
#pragma omp atomic
parCount++;
}
}
omp_end_time = omp_get_wtime();
printf ("The parallel (2 threads) code indicates that there are %d 99s in the array.\n", parCount);
printf ("The parallel (2 threads) code used %f seconds to complete the execution.\n", omp_end_time - omp_start_time);
cout << "Speedup: " << (end_time - start_time) / (omp_end_time - omp_start_time) << "\n\n";
// Parallel Code (4 Threads)
parCount = 0;
omp_set_num_threads(4);
omp_start_time = omp_get_wtime();
#pragma omp parallel for private(i) shared(myArray)
for (i = 0; i < size; i++)
{
if (myArray[i] == 99)
{
#pragma omp atomic
parCount++;
}
}
omp_end_time = omp_get_wtime();
printf ("The parallel (4 threads) code indicates that there are %d 99s in the array.\n", parCount);
printf ("The parallel (4 threads) code used %f seconds to complete the execution.\n", omp_end_time - omp_start_time);
cout << "Speedup: " << (end_time - start_time) / (omp_end_time - omp_start_time) << "\n\n";
// Parallel Code (8 Threads)
parCount = 0;
omp_set_num_threads(8);
omp_start_time = omp_get_wtime();
#pragma omp parallel for private(i) shared(myArray)
for (i = 0; i < size; i++)
{
if (myArray[i] == 99)
{
#pragma omp atomic
parCount++;
}
}
omp_end_time = omp_get_wtime();
printf ("The parallel (8 threads) code indicates that there are %d 99s in the array.\n", parCount);
printf ("The parallel (8 threads) code used %f seconds to complete the execution.\n", omp_end_time - omp_start_time);
cout << "Speedup: " << (end_time - start_time) / (omp_end_time - omp_start_time) << "\n\n";
delete [] myArray;
return 0;
} | true |
f6cf2c338f14242861f5dfb085af5319c0908b80 | C++ | Jy411/CPPAssignmentTest | /FinalReport.cpp | UTF-8 | 2,471 | 2.796875 | 3 | [] | no_license | //
// Created by Jinyung Tan on 23/06/2018.
//
#include "FinalReport.h"
FinalReport::FinalReport() {}
FinalReport::FinalReport(int studentNo, const string &fullName, char gender, int classID, const string &className,
int yearForm, char yearGrade, int subjectID, const string &subjectName, char subjectType,
double score) : studentNo(studentNo), fullName(fullName), gender(gender), classID(classID),
className(className), yearForm(yearForm), yearGrade(yearGrade),
subjectID(subjectID), subjectName(subjectName), subjectType(subjectType),
score(score) {}
int FinalReport::getStudentNo() const {
return studentNo;
}
void FinalReport::setStudentNo(int studentNo) {
FinalReport::studentNo = studentNo;
}
const string &FinalReport::getFullName() const {
return fullName;
}
void FinalReport::setFullName(const string &fullName) {
FinalReport::fullName = fullName;
}
char FinalReport::getGender() const {
return gender;
}
void FinalReport::setGender(char gender) {
FinalReport::gender = gender;
}
int FinalReport::getClassID() const {
return classID;
}
void FinalReport::setClassID(int classID) {
FinalReport::classID = classID;
}
const string &FinalReport::getClassName() const {
return className;
}
void FinalReport::setClassName(const string &className) {
FinalReport::className = className;
}
int FinalReport::getYearForm() const {
return yearForm;
}
void FinalReport::setYearForm(int yearForm) {
FinalReport::yearForm = yearForm;
}
char FinalReport::getYearGrade() const {
return yearGrade;
}
void FinalReport::setYearGrade(char yearGrade) {
FinalReport::yearGrade = yearGrade;
}
int FinalReport::getSubjectID() const {
return subjectID;
}
void FinalReport::setSubjectID(int subjectID) {
FinalReport::subjectID = subjectID;
}
const string &FinalReport::getSubjectName() const {
return subjectName;
}
void FinalReport::setSubjectName(const string &subjectName) {
FinalReport::subjectName = subjectName;
}
char FinalReport::getSubjectType() const {
return subjectType;
}
void FinalReport::setSubjectType(char subjectType) {
FinalReport::subjectType = subjectType;
}
double FinalReport::getScore() const {
return score;
}
void FinalReport::setScore(double score) {
FinalReport::score = score;
}
| true |
b422fbbaea18bcfac9b4602e65f3b61f8fc9aa66 | C++ | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-Naziaislam91 | /src/homework/tic_tac_toe/tic_tac_toe.cpp | UTF-8 | 2,520 | 3.359375 | 3 | [
"MIT"
] | permissive | #include "tic_tac_toe.h"
using std::string;
#include<iostream>
#include<string>
//cpp
bool TicTacToe::game_over()
{
if (check_column_win() == true || check_row_win() == true || check_diagonal_win() == true)
{
set_winner();
return true;
}
else if (check_board_full() == true)
{
winner = 'C';
return true;
}
return false;
}
void TicTacToe::start_game(std::string first_player)
{
if (first_player == "X" || first_player == "O")
{
player = first_player;
}
else
{
throw Error("Player must be X or O");
}
//player = first_player;
clear_board();
}
void TicTacToe::clear_board()
{
for (auto &peg : pegs)
{
peg = " ";
}
}
void TicTacToe::mark_board(int position) // change for homework 9
{
if (position < 1 || position > pegs.size())
{
throw Error("if you choose 3 then Position must be 1 to 9 or if you choose 4 then position must be 1 to 16");
}
if (player.empty())
{
throw Error("Must start game first.");
}
pegs[position - 1] = player;
if (game_over() == false) // changing this statement for homework 8
{
set_next_player();
}
}
void TicTacToe::set_next_player()
{
if (player == "X")
{
player = "O";
}
else
{
player = "X";
}
}
/*void TicTacToe::display_board() const
{
for (int i = 0; i < 9; i += 3)
{
std::cout << pegs[i] << "|" << pegs[i + 1] << "|" << pegs[i + 2] << "\n";
}
}*/
bool TicTacToe::check_board_full()
{
for (std::size_t i = 0; i < pegs.size(); ++i)
{
if (pegs[i] == " ")
return false;
}
return true;
}
bool TicTacToe::check_column_win()
{
return false;
}
bool TicTacToe::check_row_win()
{
return false;
}
bool TicTacToe::check_diagonal_win()
{
return false;
}
void TicTacToe::set_winner()
{
if (player == "X")
{
winner = 'X';
}
else
{
winner = 'O';
}
}
std::istream & operator>>(std::istream & in, TicTacToe & b)
{
try
{
int position{ 0 };
std::cout << "The user " << b.get_player() << " for the position" << "\n";
in >> position;
b.mark_board(position);
std::cout << "\n";
}
catch (Error e)
{
std::cout << e.get_message() << "\n";
}
return in;
}
std::ostream & operator<<(std::ostream & out, const TicTacToe & b) //change for homework 9
{
if (b.pegs.size() == 9)
{
for (int i = 0; i < 9; i += 3)
{
out << b.pegs[i] << "|" << b.pegs[i + 1] << "|" << b.pegs[i + 2] << "\n";
}
}
else if (b.pegs.size() == 16)
{
for (int i = 0; i < 16; i += 4)
{
out << b.pegs[i] << "|" << b.pegs[i + 1] << "|" << b.pegs[i + 2] << "|" << b.pegs[i + 3] << "\n";
}
}
return out;
}
| true |
2863fbd3cd05c290fb0621f5bbdc573de2ab7818 | C++ | chadaustin/sphere | /sphere/source/particle_engine/ParticleSystemParent.cpp | UTF-8 | 13,557 | 2.765625 | 3 | [] | no_license | #include "ParticleSystemParent.hpp"
////////////////////////////////////////////////////////////////////////////////
/*
* - Calls the on_update callback and updates the descendants.
*/
void
ParticleSystemParent::Update()
{
if (IsExtinct() || IsHalted())
return;
if (IsDead() && m_Descendants.size() == 0)
{
m_Extinct = true;
return;
}
// callback
if (m_ScriptInterface.HasOnUpdate())
m_ScriptInterface.OnUpdate();
// update descendants
std::list<Descendant>::iterator iter = m_Descendants.begin();
while (iter != m_Descendants.end())
{
Descendant d = *iter;
// update adopted descendant's body
if (d.Type == ADOPTED)
m_Updater(d.System->GetBody());
// handle death
if (!d.System->IsDead() && d.System->GetBody().Life <= 0)
d.System->Kill(this);
d.System->Update();
// handle extinction
if (d.System->IsExtinct())
{
if (d.Type == ADOPTED && !IsCursed() && !IsDead())
{
m_Initializer(m_Body, d.System->GetBody());
d.System->Revive(this);
}
else
{
d.System->Release();
iter = m_Descendants.erase(iter);
}
}
if (iter != m_Descendants.end())
++iter;
} // end update descendants
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Calls the on_render callback, renders the descendants and finally renders itself.
*/
void
ParticleSystemParent::Render()
{
if (IsExtinct() || IsHidden())
return;
// render descendants
std::list<Descendant>::iterator iter;
for (iter = m_Descendants.begin(); iter != m_Descendants.end(); ++iter)
(*iter).System->Render();
// render itself, if alive
if (!IsDead())
m_Renderer(m_Body);
// callback
if (m_ScriptInterface.HasOnRender())
m_ScriptInterface.OnRender();
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Initializes and adds a new system to the descendants list as ADOPTED.
* - An adopted system's body will be always updated and initialized.
*/
void
ParticleSystemParent::Adopt(ParticleSystemBase* system)
{
if (!system || !system->Borrow())
return;
m_Initializer(m_Body, system->GetBody());
system->Revive(this);
m_Descendants.push_back(Descendant(system, ADOPTED));
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Adds a new system to the descendants list as HOSTED.
* - A hosted system's body will be neither initialized nor updated.
* - Hosted systems are disposed of once they are dead.
*/
void
ParticleSystemParent::Host(ParticleSystemBase* system)
{
if (!system || !system->Borrow())
return;
m_Descendants.push_back(Descendant(system, HOSTED));
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Goes through the descendants list and removes all duplicates.
*/
void
ParticleSystemParent::Unique()
{
if (m_Descendants.size() <= 1)
return;
std::list<Descendant>::iterator iter = m_Descendants.begin();
while (iter != m_Descendants.end())
{
std::list<Descendant>::iterator iter_temp = iter;
++iter_temp;
while (iter_temp != m_Descendants.end())
{
if ((*iter).System->GetID() == (*iter_temp).System->GetID())
{
(*iter_temp).System->Release();
iter_temp = m_Descendants.erase(iter_temp);
}
else
{
++iter_temp;
}
}
++iter;
}
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Applies a function on all system objects in the descendants list.
*/
void
ParticleSystemParent::Apply(ScriptInterface::Applicator appl)
{
// we need to work on a copy, because the apply function can alter the descendants list
std::list<Descendant> copy = m_Descendants;
// reference the copies, so things can't be screwed up
// we doesn't care here for the return value of Borrow(), because the objects
// are already protected, so the return value will be always 'true'
std::list<Descendant>::iterator iter;
for (iter = copy.begin(); iter != copy.end(); ++iter)
(*iter).System->Borrow();
// now we are safe to apply the function
// we will stop, if an error occurred while executing it
for (iter = copy.begin(); iter != copy.end(); ++iter)
if (!appl((*iter).System->GetScriptInterface().GetObject()))
break;
// dereference the copies
for (iter = copy.begin(); iter != copy.end(); ++iter)
(*iter).System->Release();
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Functions implementing the Merge sort algorithm using a compare function.
* - If an error occurs during the sorting process, the sorting will be stopped immediately.
*/
template<typename T> bool
merge(std::list<T>& in_left,
std::list<T>& in_right,
std::list<T>& out,
ScriptInterface::Comparator& comp)
{
while (!in_left.empty() && !in_right.empty())
{
bool left_goes_first;
if (!comp(in_left.front().System->GetScriptInterface().GetObject(),
in_right.front().System->GetScriptInterface().GetObject(),
left_goes_first))
{
// error occurred while executing the compare function
return false;
}
if (left_goes_first)
{
out.push_back(in_left.front());
in_left.erase(in_left.begin());
}
else
{
out.push_back(in_right.front());
in_right.erase(in_right.begin());
}
}
while (!in_left.empty())
{
out.push_back(in_left.front());
in_left.erase(in_left.begin());
}
while (!in_right.empty())
{
out.push_back(in_right.front());
in_right.erase(in_right.begin());
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
template<typename T> bool
merge_sort(std::list<T>& in,
std::list<T>& out,
ScriptInterface::Comparator& comp)
{
std::list<T> left, right;
if (in.size() <= 1)
{
out = in;
return true;
}
dword middle = in.size() / 2;
typename std::list<T>::iterator iter = in.begin();
for (dword i = 0; i < middle; ++i)
{
left.push_back(*iter);
++iter;
}
for (dword i = middle; i < in.size(); ++i)
{
right.push_back(*iter);
++iter;
}
std::list<T> result_left, result_right;
if (!merge_sort<T>(left, result_left, comp))
return false;
if (!merge_sort<T>(right, result_right, comp))
return false;
if (!merge<T>(result_left, result_right, out, comp))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Sorts the descendants list using a compare function.
* - The sort is done using a custom implementation of Merge sort (see above).
*/
void
ParticleSystemParent::Sort(ScriptInterface::Comparator comp)
{
// we need to create copies and reference them, so changes to the descendants list
// during the sorting process from within the compare function can't screw things up
std::list<Descendant> copy = m_Descendants;
// reference the copies
// we doesn't care here for the return value of Borrow(), because the objects
// are already protected, so the return value will be always 'true'
std::list<Descendant>::iterator iter;
for (iter = copy.begin(); iter != copy.end(); ++iter)
(*iter).System->Borrow();
// now we are safe to sort the list
std::list<Descendant> sorted;
if (merge_sort<Descendant>(m_Descendants, sorted, comp))
m_Descendants = sorted;
// dereference the copies
for (iter = copy.begin(); iter != copy.end(); ++iter)
(*iter).System->Release();
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Searches the descendants list for a system with the id and returns true
* if found, else false is returned.
*/
bool
ParticleSystemParent::ContainsDescendant(dword id)
{
std::list<Descendant>::iterator iter;
for (iter = m_Descendants.begin(); iter != m_Descendants.end(); ++iter)
if ((*iter).System->GetID() == id)
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Searches the descendants list for any system related to the group and returns
* true if found, else false is returned.
*/
bool
ParticleSystemParent::ContainsDescendantGroup(int group)
{
std::list<Descendant>::iterator iter;
for (iter = m_Descendants.begin(); iter != m_Descendants.end(); ++iter)
if ((*iter).System->GetGroup() == group)
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Searches the descendants list for a system with the id and returns it.
* - If no system with the id could be found, NULL is returned.
*/
ParticleSystemBase*
ParticleSystemParent::GetDescendant(dword id)
{
std::list<Descendant>::iterator iter;
for (iter = m_Descendants.begin(); iter != m_Descendants.end(); ++iter)
if ((*iter).System->GetID() == id)
return (*iter).System;
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Searches the descendants list for all systems related to the group
* and returns them packed in an std::vector.
* - The returned vector will be empty, if no such systems could be found.
*/
std::vector<ParticleSystemBase*>
ParticleSystemParent::GetDescendantGroup(int group)
{
std::vector<ParticleSystemBase*> group_package;
std::list<Descendant>::iterator iter;
for (iter = m_Descendants.begin(); iter != m_Descendants.end(); ++iter)
if ((*iter).System->GetGroup() == group)
group_package.push_back((*iter).System);
return group_package;
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Searches the descendants list for a system with the id, removes it
* from the descendants list and returns it.
* - If no system with the id could be found, NULL is returned.
*/
ParticleSystemBase*
ParticleSystemParent::ExtractDescendant(dword id)
{
std::list<Descendant>::iterator iter = m_Descendants.begin();
while (iter != m_Descendants.end())
{
if ((*iter).System->GetID() == id)
{
ParticleSystemBase* system = (*iter).System;
(*iter).System->Release();
iter = m_Descendants.erase(iter);
return system;
}
else
{
++iter;
}
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Searches the descendants list for all systems related to the group,
* removes them from the descendants list and returns them packed in an std::vector.
* - The returned vector will be empty, if no such systems could be found.
*/
std::vector<ParticleSystemBase*>
ParticleSystemParent::ExtractDescendantGroup(int group)
{
std::vector<ParticleSystemBase*> group_package;
std::list<Descendant>::iterator iter = m_Descendants.begin();
while (iter != m_Descendants.end())
{
if ((*iter).System->GetGroup() == group)
{
group_package.push_back((*iter).System);
(*iter).System->Release();
iter = m_Descendants.erase(iter);
}
else
{
++iter;
}
}
return group_package;
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Removes all systems from the descendants list, which have the id.
*/
void
ParticleSystemParent::RemoveDescendant(dword id)
{
std::list<Descendant>::iterator iter = m_Descendants.begin();
while (iter != m_Descendants.end())
{
if ((*iter).System->GetID() == id)
{
(*iter).System->Release();
iter = m_Descendants.erase(iter);
}
else
{
++iter;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Removes all systems from the descendants list, which are related to the group.
*/
void
ParticleSystemParent::RemoveDescendantGroup(int group)
{
std::list<Descendant>::iterator iter = m_Descendants.begin();
while (iter != m_Descendants.end())
{
if ((*iter).System->GetGroup() == group)
{
(*iter).System->Release();
iter = m_Descendants.erase(iter);
}
else
{
++iter;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/*
* - Clears the descendants list, removing all systems.
*/
void
ParticleSystemParent::Clear()
{
std::list<Descendant>::iterator iter;
for (iter = m_Descendants.begin(); iter != m_Descendants.end(); ++iter)
(*iter).System->Release();
m_Descendants.clear();
}
| true |
217cfff2f4613d215c40d7a3d7c75d7a95532ff0 | C++ | FreshSJQ/RayTracer | /Rectangle.h | UTF-8 | 2,374 | 2.9375 | 3 | [] | no_license | #ifndef RAYTRACER_RECTANGLE_H
#define RAYTRACER_RECTANGLE_H
#include "Hitable.h"
class RECTXY : public Hitable {
public:
double x0, x1, y0, y1, k;
Material *mat_ptr;
RECTXY() {}
RECTXY(double x_0, double x_1, double y_0, double y_1, double kt, Material *mat) :
x0(x_0), x1(x_1), y0(y_0), y1(y_1), k(kt), mat_ptr(mat) {}
bool hit(const Ray &r, double t_min, double t_max, HitRecord &rec) const override;
bool bounding_box(AxisAlignedBoundingBox &box) const override{
box = AxisAlignedBoundingBox(Vec3(x0, y0, k - 0.0001), Vec3(x1, y1, k + 0.0001));
return true;
}
};
class RECTXZ : public Hitable {
public:
double x0, x1, z0, z1, k;
Material *mat_ptr;
RECTXZ() {}
RECTXZ(double x_0, double x_1, double z_0, double z_1, double kt, Material *mat) :
x0(x_0), x1(x_1), z0(z_0), z1(z_1), k(kt), mat_ptr(mat) {}
bool hit(const Ray &r, double t_min, double t_max, HitRecord &rec) const override;
bool bounding_box(AxisAlignedBoundingBox &box) const override{
box = AxisAlignedBoundingBox(Vec3(x0, k - 0.0001, z0), Vec3(x1, k + 0.0001, z1));
return true;
}
double pdfValue(const Vec3& o, const Vec3& v) const override {
HitRecord hrec;
if(this->hit(Ray(o, v), 0.001, DBL_MAX, hrec)) {
double area = (x1 - x0) * (z1 - z0);
double distance_squared = hrec.t * hrec.t * v.squared_length();
double cosine = fabs(dot(v, hrec.normal) / v.length());
return distance_squared / (cosine * area);
}
else return 0;
}
Vec3 random(const Vec3& o) const override {
Vec3 randomPoint = Vec3(x0 + randNum01() * (x1 - x0), k, z0 + randNum01() * (z1 - z0));
return randomPoint - o;
}
};
class RECTYZ : public Hitable {
public:
double y0, y1, z0, z1, k;
Material *mat_ptr;
RECTYZ() {}
RECTYZ(double y_0, double y_1, double z_0, double z_1, double kt, Material *mat) :
y0(y_0), y1(y_1), z0(z_0), z1(z_1), k(kt), mat_ptr(mat) {}
bool hit(const Ray &r, double t_min, double t_max, HitRecord &rec) const override;
bool bounding_box(AxisAlignedBoundingBox &box) const override{
box = AxisAlignedBoundingBox(Vec3(k - 0.0001, y0, z0), Vec3(k + 0.0001, y1, z1));
return true;
}
};
#endif //RAYTRACER_RECTANGLE_H
| true |
69bde8991a8b5c67ac2647d9c9592c91b1b22e5e | C++ | nqnliu/CSE167-Final-Project | /Galaxy/Galaxy/Vector3.cpp | UTF-8 | 2,078 | 3.890625 | 4 | [] | no_license | #include "Vector3.h"
//construction
Vector3::Vector3()
{
for (int i = 0; i < 3; ++i)
{
v[i] = 0;
}
}
Vector3::Vector3(double x,double y,double z)
{
v[0] = x;
v[1] = y;
v[2] = z;
}
//overload operator '+' for addition
Vector3 Vector3::operator+(const Vector3& v2)
{
Vector3 res;
res.v[0] = v[0] + v2.v[0];
res.v[1] = v[1] + v2.v[1];
res.v[2] = v[2] + v2.v[2];
return res;
}
//overload operator '-' for substraction
Vector3 Vector3::operator-(const Vector3& v2)
{
Vector3 res;
res.v[0] = v[0] - v2.v[0];
res.v[1] = v[1] - v2.v[1];
res.v[2] = v[2] - v2.v[2];
return res;
}
//negation
Vector3 Vector3::negate()
{
Vector3 newv;
newv = *this;
newv.v[0] *= -1;
newv.v[1] *= -1;
newv.v[2] *= -1;
return newv;
}
//scale (multiplication with scalar value)
Vector3 Vector3::scale(double s)
{
Vector3 newv;
newv = *this;
newv.v[0] *= s;
newv.v[1] *= s;
newv.v[2] *= s;
return newv;
}
//dot product, returns result
double Vector3::dot(const Vector3& v2)
{
double res = 0;
res += v[0] * v2.v[0];
res += v[1] * v2.v[1];
res += v[2] * v2.v[2];
return res;
}
//cross product, returns result and puts it in calling vector
Vector3 Vector3::cross(const Vector3& v2)
{
Vector3 res;
res.v[0] = v[1] * v2.v[2] - v[2] * v2.v[1];
res.v[1] = v[2] * v2.v[0] - v[0] * v2.v[2];
res.v[2] = v[0] * v2.v[1] - v[1] * v2.v[0];
return res;
}
//length of the vector
double Vector3::length()
{
double res = 0;
res += v[0] * v[0];
res += v[1] * v[1];
res += v[2] * v[2];
res = sqrt(res);
return res;
}
//normalize the vector (make it so that its length is equal to one)
Vector3 Vector3::normalize()
{
double len = length();
Vector3 newv;
newv = *this;
newv.v[0] /= len;
newv.v[1] /= len;
newv.v[2] /= len;
return newv;
}
//print x, y and z components of the vector after a comment string
void Vector3::print(char comment[])
{
printf("%s\n", comment);
printf("[ %lf, %lf, %lf ]\n", v[0], v[1], v[2]);
printf("\n");
}
| true |
20c7e5eeb4316221a0203eac896c0e94bdc87eb2 | C++ | ChristopherCanfield/canfield_ant_simulator | /tests/Node_tests.cpp | UTF-8 | 3,191 | 2.90625 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "CppUnitTest.h"
#include "../sim/nav/Node.hpp"
#include "../sim/nav/GridLocation.hpp"
#include "../sim/nav/Edge.hpp"
#include <memory>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace cdc;
using namespace std;
namespace tests
{
TEST_CLASS(Node_tests)
{
public:
TEST_METHOD(Node_create)
{
GridLocation location(5, 1);
Node node(location, 100, 200);
}
TEST_METHOD(Node_addEdge)
{
GridLocation location(5, 1);
Node node1(location, 100, 200);
Node node2(location, 100, 200);
auto edge = make_shared<Edge>(node1, node2, 10);
node1.addEdge(edge);
}
TEST_METHOD(Node_getEdgeList)
{
GridLocation location(5, 1);
Node node(location, 100, 200);
auto list = node.getEdgeList();
}
TEST_METHOD(Node_getEdge)
{
GridLocation location(5, 1);
Node node1(location, 100, 200);
Node node2(location, 100, 200);
auto edge = make_shared<Edge>(node1, node2, 10);
node1.addEdge(edge);
const auto edge2 = node1.getEdge(0);
auto edge3 = node1.getEdgeList()[0];
Assert::IsTrue(*edge3 == edge2);
Assert::IsTrue(*edge == edge2);
}
TEST_METHOD(Edge_edgeExists1)
{
Node startNode(GridLocation(1, 2), 20, 30);
Node endNode(GridLocation(1, 2), 20, 30);
auto edge = make_shared<Edge>(startNode, endNode, 10);
startNode.addEdge(edge);
Assert::IsTrue(startNode.edgeExists(edge));
}
TEST_METHOD(Edge_edgeExists2)
{
Node startNode(GridLocation(1, 2), 20, 30);
Node endNode(GridLocation(1, 2), 20, 30);
Node otherNode(GridLocation(2, 2), 25, 35);
auto edge = make_shared<Edge>(startNode, endNode, 10);
startNode.addEdge(edge);
auto edge2 = make_shared<Edge>(startNode, otherNode, 10);
startNode.addEdge(edge2);
Assert::IsTrue(startNode.edgeExists(edge));
Assert::IsTrue(startNode.edgeExists(edge2));
}
TEST_METHOD(Edge_edgeExists3)
{
Node startNode(GridLocation(1, 2), 20, 30);
Node endNode(GridLocation(1, 2), 20, 30);
Node otherNode(GridLocation(2, 2), 25, 35);
auto edge = make_shared<Edge>(startNode, endNode, 10);
startNode.addEdge(edge);
auto edge2 = make_shared<Edge>(startNode, otherNode, 10);
Assert::IsFalse(startNode.edgeExists(edge2));
}
TEST_METHOD(Node_getPixelX)
{
GridLocation location(5, 1);
Node node(location, 100, 200);
auto pixelX = node.getPixelX<int>();
Assert::AreEqual(pixelX, 100);
}
TEST_METHOD(Node_getPixelY)
{
GridLocation location(5, 1);
Node node(location, 100, 200);
auto pixelY = node.getPixelY<int>();
Assert::AreEqual(pixelY, 200);
}
TEST_METHOD(Node_getRow)
{
GridLocation location(5, 1);
Node node(location, 100, 200);
auto row = node.getRow();
Assert::AreEqual(row, 5u);
}
TEST_METHOD(Node_getColumn)
{
GridLocation location(5, 1);
Node node(location, 100, 200);
auto column = node.getColumn();
Assert::AreEqual(column, 1u);
}
TEST_METHOD(Node_getBoundingBox)
{
GridLocation location(5, 1);
Node node(location, 100, 200);
sf::Rect<float> boundingBox(100.f - 3.f, 200.f - 3.f, 6.f, 6.f);
Assert::IsTrue(boundingBox == node.getBoundingBox());
}
};
} | true |
cad6f9f8341bf9f8f7139017b8da453630298786 | C++ | KeshavChaurasia/leetcode | /diameter-of-binary-tree/diameter-of-binary-tree.cpp | UTF-8 | 840 | 3.28125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
pair<int,int> diameter(TreeNode* root){
if(root == nullptr) return {0,0};
pair<int,int> left = diameter(root->left);
pair<int,int> right = diameter(root->right);
int height = max(left.first, right.first) + 1;
int diam = max({left.second, right.second, left.first + right.first});
return {height, diam};
}
int diameterOfBinaryTree(TreeNode* root) {
return diameter(root).second;
}
}; | true |
ab8d878a8a32836d35eec91f7411b4d0aa59590a | C++ | junamai2000/Emwd | /include/core/Request.h | UTF-8 | 2,944 | 2.828125 | 3 | [] | no_license | // vim:set noexpandtab sts=0 ts=4 sw=4 ft=cpp fenc=utf-8 ff=unix:
/*
* Request.h
*
* Created on: 2014/09/06
* Author: Junya Namai
*/
#ifndef EMWD_CORE_REQUEST_H_
#define EMWD_CORE_REQUEST_H_
// C++ headers
#include <map>
namespace Emwd { namespace core {
class Response;
/**
* Request class
*/
class Request
{
public:
/**
* Request Method
* do not use string, converts into enum under a oncrete class
*/
enum REQUEST_METHOD {R_GET=1, R_POST, R_PUT, R_DELETE, R_UPDATE};
/**
* get a Get param from http request
* @param key
* @return value
*/
virtual const char* getGet(const char* key) = 0;
/**
* set Get requests
* @return get parameters by using std::map
*/
virtual std::map <const char*, const char*> getGets() = 0;
/**
* set a Get param from http request
* @param key get name
* @param value get value
*/
virtual void setGet(const char* key, const char* value) = 0;
/**
* set Get parameters
* @param gets map object which contains all get parameters
*/
virtual void setGets(std::map <const char*, const char*> gets) = 0;
/**
* get a Post param from http request
* @param key
* @return value
*/
virtual const char* getPost(const char* key) = 0;
/**
* set Posts requests
* @return post parameters with std::map
*/
virtual std::map <const char*, const char*> getPosts() = 0;
/**
* set a Post param from http request
* @param key get name
* @param value get value
*/
virtual void setPost(const char* key, const char *value) = 0;
/**
* set Post parameters
* @param Posts map object which contains all Post parameters
*/
virtual void setPosts(std::map <const char*, const char*> gets) = 0;
/**
* set content type
* @param type ex: text/plain
*/
virtual void setContentType(const char* type) = 0;
/**
* get contents type
* @return content type header
*/
virtual const char* getContentType() = 0;
/**
* set request url
* @param url
*/
virtual void setRequestUrl(const char* url) = 0;
/**
* get request url
* @return
*/
virtual const char* getRequestUrl() = 0;
/**
* set status code
* ex: 404, 503 etc....
* @param http status code
*/
virtual void setStatusCode(int code) = 0;
/**
* set request method
* @param method
*/
virtual void setRequestMethod(REQUEST_METHOD method) = 0;
/**
*
* @param key
* @param value
*/
virtual void setHeader(const char* key, const char value) = 0;
/**
*
* @param headers
*/
virtual void setHeaders(std::map <const char*, const char*> headers) = 0;
/**
*
* @param key
* @return
*/
virtual const char* getHeader(const char* key) = 0;
/**
*
* @return
*/
virtual std::map <const char*, const char*> getHeaders() = 0;
/**
* get request method
* @return request method enum
*/
virtual REQUEST_METHOD getRequestMethod() = 0;
/**
* destructor
*/
virtual ~Request()
{
}
};
} }
#endif /* EMWD_CORE_REQUEST_H_ */
| true |
c2eee93c8ed0227ae6738588c493ef1f67d64e6b | C++ | anagorko/informatyka | /home/lukom/geny.cpp | UTF-8 | 3,063 | 3.03125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<fstream>
#include<string>
using namespace std;
class genotyp {
public:
string s;
bool odporny_na_zmeczenie() const;
int ilosc_genow() const;
int jaki_najdluzszy_gen() const;
bool silnie_odporny() const;
bool odporny() const;
vector <string> geny(string s1) const;
}M[1000];
bool genotyp::odporny() const {
vector <string> v = geny(s);
string s1;
for(int i=s.length()-1;i>=0;i--) s1+=s[i];
vector <string> v1 = geny(s1);
string g,g1;
for(int i=0;i<v.size();i++) g+=v[i];
for(int i=0;i<v1.size();i++) g1+=v1[i];
if(g1 == g) return true;
else return false;
}
bool genotyp::silnie_odporny() const {
for(int i = 0;i<s.length()/2;i++){
if(s[i] != s[s.length()-1-i]) return false;
}
return true;
}
int genotyp::jaki_najdluzszy_gen() const {
vector <string> v = geny(s);
int wmax = 0;
for(int i =0;i<v.size();i++) if(v[i].length() > wmax) wmax = v[i].length();
return wmax;
}
int genotyp::ilosc_genow() const{
return geny(s).size();
}
vector <string> genotyp::geny(string s1) const {
vector <string> v;
bool znalazlem_poc = false;
bool znalazlem_kon = false;
for(int i=0;i<s1.length();i++){
while(i < s1.length()-1){
if(s1.substr(i,2) == "AA"){
znalazlem_poc = true;
break;
}else i++;
}
int j = i;
while(j < s1.length()-1){
if(s1.substr(j,2) == "BB"){
znalazlem_kon = true;
j+=1;
break;
}else j++;
}
if(znalazlem_poc && znalazlem_kon){
v.push_back(s1.substr(i, j-i+1));
//cout<<v[v.size()-1]<<endl;
znalazlem_poc = false;
znalazlem_kon = false;
}
}
return v;
}
bool genotyp::odporny_na_zmeczenie() const {
string G = "BCDDC";
vector <string> v = geny(s);
for(int i=0;i<v.size();i++){
for(int j=2;j<v[i].length() - 4;j++){
if(v[i].substr(j,5) == G) return true;
}
}
return false;
}
void wczytanie(){
fstream plik;
plik.open("../../zbior_zadan/69/dane_geny.txt");
for(int i =0;i<1000;i++){
plik >> M[i].s;
// cout << M[i].s<<endl;
}
plik.close();
}
void pyt1(){
int dl[501];
for(int i=0;i<501;i++) dl[i] = 0;
for(int i=0;i<1000;i++) dl[M[i].s.length()]++;
int ile=0;
int maxil = 0;
for(int i=0;i<501;i++){
if(dl[i] > 0) ile++;
if(maxil < dl[i]) maxil = dl[i];
}
cout<<"jest "<<ile<<" gatunkow"<<endl;
cout<<"maksymalna liczba reprezentantow gatunku: "<<maxil<<endl;
}
void pyt2(){
int w = 0;
for(int i=0;i<1000;i++) if(M[i].odporny_na_zmeczenie()) w++;
cout<<w<<" osobnikow jest odpornych na zmeczenie\n";
}
void pyt3(){
int dlmax = 0;
int ilmax = 0;
for(int i=0;i<1000;i++){
if(ilmax < M[i].ilosc_genow()) ilmax = M[i].ilosc_genow();
if(dlmax < M[i].jaki_najdluzszy_gen()) dlmax = M[i].jaki_najdluzszy_gen();
}
cout<<"najwieksza liczba genow: "<<ilmax<<endl;
cout<<"najdluzszy gen: "<<dlmax<<endl;
}
void pyt4(){
int so=0;
int o =0;
for(int i =0;i<1000;i++){
if(M[i].silnie_odporny())so++;
else if(M[i].odporny())o++;
}
cout<<"odpornych jest: "<<o<<endl;
cout<<"silnie odpornych jest: "<<so<<endl;
}
int main(){
wczytanie();
// pyt1();
// pyt2();
// pyt3();
// pyt4();
}
| true |
95ec3fba096648ff7772213f8b04c4cfaab1b5f1 | C++ | debacoding/exercism-cpp | /triangle/triangle.cpp | UTF-8 | 597 | 3.25 | 3 | [] | no_license | #include "triangle.h"
#include <stdexcept>
#include <iostream>
using namespace std;
namespace triangle
{
triangles_t kind(double a, double b, double c)
{
triangles_t type;
if (a<=0 || b<=0 || c<=0)
{
throw domain_error("Error");
}
if ((a+b)<c || (a+c)<b || (b+c)<a)
{
throw domain_error("Error");
}
if (a==b && b==c)
{
type = equilateral;
}
else if (a==b || b==c || a==c)
{
type = isosceles;
}
return type;
}
}
| true |
247dfd342cd8365de2fd1822e4ad1aef3c098f4c | C++ | msrLi/portingSources | /ACE/ACE_wrappers/tests/Object_Manager_Test.cpp | UTF-8 | 2,816 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive |
//=============================================================================
/**
* @file Object_Manager_Test.cpp
*
* Tests the basic functions of the ACE_Object_Manager.
*
* @author David L. Levine <levine@cs.wustl.edu>
*/
//=============================================================================
#include "test_config.h"
#include "ace/Object_Manager.h"
#include "ace/OS_Memory.h"
#include "ace/Init_ACE.h"
static u_int *ip;
extern "C"
void
hook1 (void)
{
delete ip;
ip = 0;
}
extern "C"
void
hook2 (void * /* object */, void *param)
{
u_int *paramp = reinterpret_cast<u_int *> (param);
// We can use ACE_Log_Msg in an ACE_Object_Manager cleanup hook.
// But NOT in an ACE_OS::atexit () hook! However, the ACE_END_TEST
// invocation in main () will prevent this from being output to the
// log stream.
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("hook2: %d\n"),
*paramp));
delete paramp;
}
int
run_main (int, ACE_TCHAR *[])
{
ACE::init ();
ACE_START_TEST (ACE_TEXT ("Object_Manager_Test"));
u_int errors = 0;
// If hook1 never gets called, this will show up as a memory leak.
ACE_NEW_RETURN (ip,
u_int,
-1);
const int starting_up =
ACE_Object_Manager::instance ()->starting_up ();
const int shutting_down =
ACE_Object_Manager::instance ()->shutting_down ();
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("starting_up: %d, shutting_down: %d\n"),
starting_up,
shutting_down));
if (starting_up || shutting_down)
{
++errors;
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("starting_up and shutting_down are supposed to ")
ACE_TEXT (" be 0!!!!")));
}
if (ACE_OS::atexit (hook1) != 0)
{
++errors;
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("ACE_OS::atexit () returned non-zero!!!!")));
}
for (u_int i = 0; i < 10; ++i)
{
u_int *paramp;
ACE_NEW_RETURN (paramp,
u_int,
-1);
*paramp = i;
// The first paramp argument is only used to distinguish the
// at_exit entries. The ACE_Object_Manager only allows one
// at_exit per object. It's not used in the hook.
if (ACE_Object_Manager::instance ()->at_exit (paramp,
hook2,
paramp))
{
++errors;
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("ACE_Object_Manager::at_exit () ")
ACE_TEXT ("returned non-zero!!!!")));
}
}
ACE_END_TEST;
ACE::fini ();
return errors == 0 ? 0 : 1;
}
| true |
3d20582e3424b9739ff9faee1c2a415c9829c5a2 | C++ | will-fawcett/exogaia | /exogaia.cpp | UTF-8 | 27,987 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <random>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <bitset>
#include <string>
#include <ios>
using namespace std;
//********* MICROBES ****************
class microbe { // class for our microbe species
public:
int genome;
int population;
double nutrient;
int biomass;
int waste;
};
//********** SORTING ****************
struct myclass { // rank species by population, largest first
bool operator() ( microbe i, microbe j) { return (i.population > j.population);}
} sorting_rule;
//********* CHOOSE INDIVIDUAL *********
// code to chose a random individual from the system
int chooseAgent(vector< microbe > &species, int p) {
double r = 0;
double p_num = drand48();
for (int j = 0; j < species.size(); j++){
r+= species[j].population;
if (p*p_num <= r){
return j;
}
}
return -1; // happens if life goes extinct
}
//********* GREATER COMMON DENOMENATOR ***************
int GCD(int a, int b)
{
while( 1 )
{
a = a % b;
if( a == 0 )
return b;
b = b % a;
if( b == 0 )
return a;
}
}
//******** NUTRIENT GENOME INTERACTIONS **************
vector < vector <int> > nutrient_genome_interactions(int genome_length, int num_nutrients, default_random_engine &generator){
// this maps which geomones will code for which metabolisms
vector <int> cons_ex_vector (2*num_nutrients, 0); // consumption excretion vector
vector <int> temp(num_nutrients, 0);
vector < vector <int> > all_metabolisms;
for (int i = 0; i < pow(2,genome_length); i++){
int cons = 0;
int exc = 0;
for (int j = 0; j < 2*num_nutrients; j++) { cons_ex_vector[j] = 0; }
cons = floor(drand48()*num_nutrients);
exc = floor(drand48()*num_nutrients);
while (cons == exc) { exc = floor( drand48()*num_nutrients ); } // canot eat and excrete the same chemical species / nutrient
cons_ex_vector[cons] = 1;
cons_ex_vector[exc+num_nutrients] = 1;
all_metabolisms.push_back(cons_ex_vector);
}
return all_metabolisms;
}
//************ CREATE GEOLOGICAL LINKS **************
vector < vector <double> > environment_setup_links(double num_nutrients, double link_probability) {
vector< vector <double> > geological_links( num_nutrients , vector<double>(num_nutrients, 0));
for (int k = 0; k < num_nutrients; k++){
for (int l = k+1; l < num_nutrients; l++){ // prevents repeats ie [1][2] = [2][1]
if (drand48() <= link_probability && k != l) { // are the two linked at all
double wt = drand48(); // 50 50 chance of nutrients flowing one way or the other
double link_strength = drand48();
if (wt < 0.5) {
geological_links[k][l] = link_strength; // flow from k to l
geological_links[l][k] = 0;
} else {
geological_links[l][k] = link_strength; // flow from l to k
geological_links[k][l] = 0; // doesn't flow both ways
}
}
}
}
for (int k = 0; k < num_nutrients; k++){
double total_out = 0.0;
for (int l = 0; l < num_nutrients; l++){
if (k != l) { total_out += geological_links[k][l]; }
}
geological_links[k][k] = total_out;
if (total_out > 1) {
for (int l = 0; l < num_nutrients; l++) {
geological_links[k][l] = geological_links[k][l] / double(total_out);
}
}
}
return geological_links;
}
//****************************** ABIOTIC TRICKLE *********************
double update_abiotic(vector <double> &environment, int num_nutrients, vector <double> node_abiotic, double abiotic_env, double abiotic_T){
double reflected = 0.0;
double insulated = 0.0;
for (int j = 0; j < num_nutrients; j++){
if (node_abiotic[j] < 0) { reflected += -1.0*(node_abiotic[j]*100) * tanh(environment[j]/75000.0); }
else if (node_abiotic[j] > 0) { insulated += (node_abiotic[j]*100) * tanh(environment[j]/75000.0); }
}
if (reflected > 100) { reflected = 100; }
if (insulated > 100) { insulated = 100; }
double current_env = abiotic_T;
double incoming = abiotic_env * (100.0 - reflected)/100.0;
double residual = current_env * insulated / 100.0;
return incoming + residual - abiotic_T;
}
//****************** UPDATE ENVIRONMENT *****************
vector <double> update_environment(vector <double> &environment, int num_nutrients, double percentage_outflow, vector < vector <double> > &geological_links, vector <double> &influx_nodes){
vector <double> nutrient_trickle (num_nutrients,0);
for (int j = 0; j < num_nutrients; j++) { // outflow inflow
nutrient_trickle[j] = environment[j]*(1.0-percentage_outflow) + influx_nodes[j];
}
for (int j = 0; j < num_nutrients; j++) { // geological processes
double cur = nutrient_trickle[j];
for (int l = 0; l < num_nutrients; l++){
nutrient_trickle[l] += cur*geological_links[j][l];
nutrient_trickle[j] -= cur*geological_links[j][l];
}
}
for (int j = 0; j < num_nutrients; j++){
nutrient_trickle[j] -= environment[j]; // difference with the current environment
}
return nutrient_trickle;
}
// ************* SET UP INFLUX NODES / CHEMICAL SPECIES **************************
vector < double > create_nodes(int num_nutrients, int num_source, int max_nutrient_inflow){
vector < double > influx_nodes (num_nutrients, 0);
for (int j = 0; j < num_source; j++){ // create the source nodes randomly
int new_nut = 0;
int loc_n = floor(drand48()*num_nutrients);
while (new_nut == 0) {
if (influx_nodes[loc_n] == 0) { influx_nodes[loc_n] = max_nutrient_inflow; new_nut = 1; }
else { loc_n = floor(drand48()*num_nutrients); }
}
}
return influx_nodes;
}
//***** SET UP INSULATING / REFLECTING PROPERTIES OF EACH CHEMICAL SPECIES ******
vector < double > ab_nodes(int num_nutrients, double abiotic_prob){
vector < double > node_abiotic (num_nutrients, 0);
for (int j = 0; j < num_nutrients; j++){
if (drand48() < abiotic_prob) { // chance chemical species will have non-zero effect on temp
node_abiotic[j] = (2.0*drand48()-1.0); // +ve means insulating, -ve means reflecting
}
}
return node_abiotic;
}
//************ MAIN CODE ************************
int main(int argc, char **argv) {
//***** MICROBE PARAMETERS*****
int i; // this is a marker for chosing and individual
const int initial_population = 100; // initial population
const int genome_length = 8; // length of genes in genome, each gene can be either '0' or '1'
const int reproduction_thresh = 120; // biomass threashold to reproduce
const int starve_thresh = 50; // if somethings biomass drops below this, it dies
const int max_consumption = 10; // maximum number of nutrients a microbe can eat at once
const double nutrient_conversion_eff = 0.6; // efficiency of microbe metabolism
const int maintainence_cost = 1; // how much biomass it costs per timestep to live
const double p_mut = 0.01; // probability per gene of mutation in reproduction event
const double p_kill = 0.002; // probability of dead due to causes other than starvation
const double prefered_abiotic = 1000.0; // abstract temperature
const bool reseed_on = false; // reseed with life after extinction?
//***** ENVIRONMENT PARAMETERS *******
const int num_nutrients = 8; // number of different types of nutrients/chemicals in system
const int num_source = 2; // number of nutrients with influx. Must be <= num_nutrients!
const double percentage_outflow = 0.0001; // to calculate outflow
const int max_nutrient_inflow = 75; // per source node
const double abiotic_start = 500.0; // incoming heat from 'sun'. If start and end are different, world wil gradually warm/cool
const double abiotic_end = 500.0;
double abiotic_env = abiotic_start; // starting environmental temperature
double abiotic_trickle = 0; // used to update environment between timestep iterations
double abiotic_prob = 1.0; // probability of heating / cooling for each node (chemical species)
//***** RANDOM NUMBER GENERATORS ****
int t1 = atoi(argv[1]); // number to initialise the chemical set (heating / cooling properties)
srand48 (t1);
mt19937 rng(t1);
default_random_engine generator;
generator.seed(t1); // provide seed for randomness in different runs
vector < double > node_abiotic = ab_nodes(num_nutrients, abiotic_prob); // abiotic affect of the nodes
vector < double > influx_nodes = create_nodes(num_nutrients, num_source, max_nutrient_inflow);
double abiotic_T = abiotic_start; // set initial temperature to the start temperature
vector<double> environment(num_nutrients, 0); // initally no chemicals in 'atmosphere'
vector<double> nutrient_trickle(num_nutrients,0); // for updating environment in between iterations
int t2 = atoi(argv[2]); // number to initialise geochemistry (links)
srand48 (t2);
generator.seed(t2);
const double link_probability = 0.4; // how likely for two nodes to be connected
vector< vector<double> > geological_links = environment_setup_links(num_nutrients, link_probability);
//***** RANDOM NUMBER GENERATORS ****
int t = atoi(argv[3]); // number to initialise microbe metabolisms
srand48 (t);
generator.seed(t); // provide seed for randomness in different runs
// METABOLISM SET UP
vector < vector< int > > n_g_interacts = nutrient_genome_interactions(genome_length, num_nutrients, generator);
//***** SPECIES VARIABLES ********
vector < microbe > species;
int total_population = initial_population;
double average_biomass;
int i_biomass;
double species_nutrient_avg;
double species_biomass_avg;
int nutrient_available;
const double abiotic_scaling = 0.015; // microbe sensitivity to temperature
double satisfaction; // a measure of how 'fit' the microbes are in their current environment
double factor_i;
microbe temp_mutant;
int did_we_mutate = 0;
int genome_new = floor(drand48()*pow(2,genome_length)); // randomly generate microbes
microbe new_microbe;
new_microbe.population = initial_population;
new_microbe.genome = genome_new;
new_microbe.nutrient = 0;
new_microbe.biomass = 80*initial_population;
new_microbe.waste = 0;
species.push_back(new_microbe);
// VARIABLES FOR KEEPING TRACK OF TIME
int timestep_length = total_population; // number of timestep iterations determined by total population at start of timestep
int number_gens = 0; // number of timesteps that have passed
int timestep_counter = 0; // for counting iterations within a timestep
int max_timesteps = 50*pow(10,4); // max length of experiment
int init_period = 5*pow(10,4); // after this time has passed if habitable conditions haven't been reached, seed anyway
int init_counter = 0; // for tracking time before life is seeded
int non_ideal = 1; // switches to 0 when environment is ideal and life can be seeded
int death_iteration = 0; // if a microbe dies at the start of iteration, skip to next iteration (a dead microbe can't eat etc)
// DATA FILES
int file_num = atoi(argv[4]); // data file number
ofstream macro_data ("exogaia_macro_data_"+to_string(file_num)+".txt"); // macro properties - total pop, temp, etc
ofstream pop_data ("exogaia_pop_data_"+to_string(file_num)+".txt"); // population of each species alive at timestep
ofstream nutrient_data ("exogaia_nutrient_data_"+to_string(file_num)+".txt"); // chemical species levels over time
ofstream genome_data ("exogaia_genome_data_"+to_string(file_num)+".txt"); // which genomes exist over time
ofstream nutrient_genome ("exogaia_nutrient_genome_"+to_string(file_num)+".txt"); // chemicals being consumed at each timestep
ofstream waste_genome ("exogaia_waste_data_"+to_string(file_num)+".txt"); // chemicals being excreted over time
ofstream geological_net ("exogaia_geological_network_dat.txt"); // the geochemical network
for (int j = 0; j < num_nutrients; j++){
geological_net << influx_nodes[j] << " ";
}
geological_net << endl;
for (int j = 0; j < num_nutrients; j++){
geological_net << node_abiotic[j] << " ";
}
geological_net << endl;
for (int k = 0; k < num_nutrients; k++){
for (int l = 0; l < num_nutrients; l++){
geological_net << geological_links[k][l] << " ";
}
geological_net << endl;
}
geological_net.close();
while (init_counter < init_period && non_ideal == 1) { // INITIALISE OUR ENVIRONMENT
/* ********************************************************************************
NUTRIENT FLOW
********************************************************************************/
// only update the flow once every time step
// nutrient outflow
abiotic_trickle = update_abiotic(environment, num_nutrients, node_abiotic, abiotic_env, abiotic_T);
abiotic_T += abiotic_trickle;
nutrient_trickle = update_environment(environment, num_nutrients, percentage_outflow, geological_links, influx_nodes);
for (int j = 0; j < num_nutrients; j++){
environment[j] += nutrient_trickle[j];
nutrient_trickle[j] = 0;
}
abiotic_trickle = 0;
if (abiotic_T >= 1000 && abiotic_T <= 1050) { // seeding window
for (int k = 0; k < num_nutrients; k++){
if (environment[k] > 1000) {
non_ideal = 0; // environment is suitable for seeding with life
}
}
} // seed once conditions are habitable for life
init_counter++;
double reflected = 0.0;
double insulated = 0.0;
for (int j = 0; j < num_nutrients; j++){
if (node_abiotic[j] < 0) { reflected += -1.0*(node_abiotic[j]*100) * tanh(environment[j]/75000.0); }
else if (node_abiotic[j] > 0) { insulated += (node_abiotic[j]*100) * tanh(environment[j]/75000.0); }
}
if (reflected > 100) { reflected = 100; }
if (insulated > 100) { insulated = 100; }
macro_data << init_counter << " 0 0 0 " << abiotic_T << " " << insulated << " " << reflected << endl;
}
//************************** SEED **************************************
int suit_metab = 0; // find a suitable metabolism - food suitable for the species' metabolism must be available
while (suit_metab == 0) {
species[0].genome = floor(drand48()*pow(2,genome_length));
for (int q = 0; q < num_nutrients; q++){
if (n_g_interacts[species[0].genome][q] > 0 && environment[q] > 1000) { // food source available?
suit_metab = 1;
}
}
}
while (number_gens < max_timesteps) {
/* ********************************************************************************
RECORD DATA
********************************************************************************/
if (timestep_counter >= timestep_length){
timestep_counter = 0;
timestep_length = total_population;
number_gens++;
stable_sort (species.begin(), species.end(), sorting_rule);
double reflected = 0.0;
double insulated = 0.0;
for (int j = 0; j < num_nutrients; j++){
if (node_abiotic[j] < 0) { reflected += -1.0*(node_abiotic[j]*100) * tanh(environment[j]/75000.0); }
else if (node_abiotic[j] > 0) { insulated += (node_abiotic[j]*100) * tanh(environment[j]/75000.0); }
}
if (reflected > 100) { reflected = 100; }
if (insulated > 100) { insulated = 100; }
factor_i = abiotic_scaling*sqrt(pow(abiotic_T - prefered_abiotic, 2.0));
satisfaction = exp (-1.0*pow(factor_i,2.0));
int total_count_eat = floor(max_consumption * satisfaction);
// Record data here!!!!!
macro_data << number_gens+init_counter << " " << total_population << " " << species[0].population << " " << species.size() << " " << abiotic_T << " " << insulated << " " << reflected << endl;
genome_data << number_gens;
pop_data << number_gens;
nutrient_genome << number_gens;
waste_genome << number_gens;
for (int j = 0; j < species.size(); j++){
pop_data << " " << species[j].population;
genome_data << " " << species[j].genome;
int eat_in = 0;
int waste_out = 0;
for (int l = 0; l < num_nutrients; l++) {
if (n_g_interacts[species[j].genome][l] > 0) { eat_in = l+1; }
if (n_g_interacts[species[j].genome][l+num_nutrients] > 0) { waste_out = l+1; }
}
nutrient_genome << " " << eat_in;
waste_genome << " " << waste_out;
}
pop_data << endl;
genome_data << endl;
nutrient_genome << endl;
waste_genome << endl;
nutrient_data << number_gens;
for (int j = 0; j < num_nutrients; j++) {
nutrient_data << " " << environment[j];
}
nutrient_data << endl;
/************************************************************************************
CALCULATE NUTRIENT TRICKLE
**************************************************************************************/
abiotic_env += (abiotic_end - abiotic_start) / max_timesteps;
abiotic_trickle = update_abiotic(environment, num_nutrients, node_abiotic, abiotic_env, abiotic_T);
if (timestep_length > 0) { abiotic_trickle = abiotic_trickle / (1.0*timestep_length); }
nutrient_trickle = update_environment(environment, num_nutrients, percentage_outflow, geological_links, influx_nodes);
if (timestep_length > 0) {
for (int j = 0; j < num_nutrients; j++){
nutrient_trickle[j] = nutrient_trickle[j]/(1.0*timestep_length);
}
}
}
/* ********************************************************************************
NUTRIENT FLOW
********************************************************************************/
// have a trickle every iteration adding up to the alloted count per timestep
// nutrient outflow
for (int j = 0; j < num_nutrients; j++ ){
environment[j] += nutrient_trickle[j];
if (environment[j] < 0) { environment[j] = 0; }
}
abiotic_T += abiotic_trickle;
/*********************************************************************************
RESEED IF PLANET IS EXTINCT (Only happens if reseed_on == True)
*********************************************************************************/
if (abiotic_T >= 1000 && abiotic_T < 1050 && total_population == 0 && reseed_on){
int genome_news = floor(drand48()*pow(2,genome_length)); // randomly generate microbes
microbe try_microbe;
try_microbe.population = initial_population;
try_microbe.genome = genome_news;
try_microbe.nutrient = 0;
try_microbe.biomass = 80*initial_population;
try_microbe.waste = 0;
species.push_back(try_microbe);
total_population = initial_population;
int suit_metab = 0; // find a suitable metabolism for current environment
while (suit_metab == 0) {
species[0].genome = floor(drand48()*pow(2,genome_length));
for (int q = 0; q < num_nutrients; q++){
if (n_g_interacts[species[0].genome][q] > 0 && environment[q] > 1000) {
suit_metab = 1;
}
}
}
}
/* ********************************************************************************
KILL
********************************************************************************/
// NEED TO REMOVE BIOMASS WHEN AN INDIVIDUAL DIES
i = chooseAgent(species, total_population);
death_iteration = 0; // Reset at start of each iteration. Becomes 1 if chosen microbe at start of iteration dies
// If a microbe dies it cannot eat / reproduce etc therefore there is one less possible eating etc event
// within the current timestep
if (i > -1) {
// death event starvation
average_biomass = species[i].biomass/(1.0*species[i].population);
normal_distribution<double> biomass_dist( average_biomass, average_biomass*0.01 ); // distribution of biomass in population
i_biomass = floor(biomass_dist(generator));
species_nutrient_avg = 1.0*species[i].nutrient/species[i].population;
normal_distribution<double> nutrient_species_dist( species_nutrient_avg, species_nutrient_avg*0.1);
nutrient_available = floor(nutrient_species_dist(generator)); // we'll just round down as can't use half a nutrient
if (i_biomass <= starve_thresh) {
// dies if biomass lower than starvation threshold
species[i].population--;
species[i].biomass -= i_biomass; // remove biomass of dead microbe
species[i].nutrient -= nutrient_available; // remove the undigested food of the dead microbe
total_population--;
if (species[i].biomass < 1) { species[i].biomass = 0; species[i].population = 0; } // if there is no biomass, extinct
if (species[i].population == 0){
species.erase(species.begin() + i); // remove species from list if extinct
}
death_iteration = 1;
}
else if (drand48() <= p_kill && species[i].population > 0) {
species[i].population--;
species[i].biomass -= i_biomass; // remove biomass of dead microbe
species[i].nutrient -= nutrient_available; // remove the undigested food of the dead microbe
total_population--;
if (species[i].population == 0){
species.erase(species.begin() + i); // remove from species list if extinct
}
death_iteration = 1;
}
}
/* ********************************************************************************
MAINTENANCE COST
********************************************************************************/
i = chooseAgent(species, total_population);
if (i > -1 && death_iteration == 0) {
species[i].biomass--;
}
/* ********************************************************************************
METABOLISM
********************************************************************************/
// metabolism event
i = chooseAgent(species, total_population);
if( i > -1 && death_iteration == 0) {
factor_i = abiotic_scaling*sqrt(pow(abiotic_T - prefered_abiotic, 2.0));
satisfaction = exp (-1.0*pow(factor_i,2.0));
int minimum_count_eat = 0; // the minumum total number of nutrients microbe can intake
int max_count_eat = 0;
int nut_num;
for (int k = 0; k < num_nutrients; k++) {
if (n_g_interacts[species[i].genome][k] > 0) { nut_num = k; } // which nutrient / chemical species does this microbe eat?
}
double total_count_eat = max_consumption * satisfaction;
if (environment[nut_num] < total_count_eat) { total_count_eat = environment[nut_num]; }
environment[nut_num] -= total_count_eat;
species[i].nutrient += total_count_eat;
if (environment[nut_num] < 0) { cout << "NUTRIENT EATING PROBLEM" << endl; } // bug check - has never happened
}
/* ********************************************************************************
BIOMASS CREATION
********************************************************************************/
i = chooseAgent(species, total_population);
if (i > -1 && death_iteration == 0){
species_nutrient_avg = 1.0*species[i].nutrient/species[i].population;
normal_distribution<double> nutrient_species_dist( species_nutrient_avg, species_nutrient_avg*0.1);
nutrient_available = floor(nutrient_species_dist(generator)); // we'll just round down as can't use half a nutrient
while ( nutrient_available >= 5) {
species[i].nutrient -= 5;
nutrient_available -= 5;
species[i].biomass += int(5.0*nutrient_conversion_eff);
species[i].waste += int(5*(1.0 - nutrient_conversion_eff));
}
}
/*********************************************************************************
WASTE
**********************************************************************************/
i = chooseAgent(species, total_population);
if (i > -1 && death_iteration == 0){
double species_waste_avg = 1.0*species[i].waste/species[i].population;
normal_distribution<double> waste_species_dist( species_waste_avg, species_waste_avg*0.1);
int waste_available = floor(waste_species_dist(generator));
if (waste_available > species[i].waste) { waste_available = species[i].waste; }
for (int k = 0; k < num_nutrients; k++) {
if (n_g_interacts[species[i].genome][k+num_nutrients] > 0) { // microbe excretes this chemical species as waste
species[i].waste -= waste_available;
environment[k] += waste_available;
}
}
}
/* ********************************************************************************
REPRODUCTION
********************************************************************************/
// reproduction event
i = chooseAgent(species, total_population);
if (i > -1 && death_iteration == 0){
species_biomass_avg = (1.0*species[i].biomass)/species[i].population; // average biomass per indiviual
normal_distribution<double> biomass_species_dist( species_biomass_avg, species_biomass_avg*0.01 );
i_biomass = floor(biomass_species_dist(generator));
if (i_biomass >= reproduction_thresh) {
// DO WE MUTATE?
bitset<genome_length> mutant_genome(species[i].genome);
did_we_mutate = 0;
for (int j = 0; j < genome_length; j++){
if (drand48() <= p_mut){
did_we_mutate = 1;
if (mutant_genome[j] == 1) {
mutant_genome[j] = 0;
} else {
mutant_genome[j] = 1;
}
}
}
if (did_we_mutate == 1) {
int mutant_number = int(mutant_genome.to_ulong());
int species_exists = 0;
for (int q = 0; q < species.size(); q++){ // check to see if species exists
if (species[q].genome == mutant_number){
species[q].population++;
species[q].biomass += int(i_biomass / 2.0); // half biomass goes to new mutant
species[i].biomass -= int(i_biomass / 2.0);
species_exists = 1;
break;
}
}
if (species_exists == 0){ // add species if it doesn't exist
temp_mutant.genome = mutant_number;
temp_mutant.nutrient = 0; // no nutrient count to begin with
temp_mutant.biomass = int(i_biomass / 2.0); // half biomass goes to new mutant
species[i].biomass -= int(i_biomass / 2.0);
temp_mutant.population = 1; // initial population of 1
temp_mutant.waste = 0;
species.push_back(temp_mutant);
}
total_population++;
} else { // no mutation takes place, we add one to the population
species[i].population++;
total_population++;
}
}
}
timestep_counter++; // increment our timestep counter
/*********** END OF WHILE LOOP ***************/
}
macro_data.close();
pop_data.close();
nutrient_data.close();
genome_data.close();
nutrient_genome.close();
waste_genome.close();
return 0;
}
| true |
f71a608afe3724f7ae481e564132ecf3a84799c9 | C++ | utkusenocak/CppEssentialTraining | /Essential/jump.cpp | UTF-8 | 1,131 | 3.421875 | 3 | [] | no_license | #include <iostream>
using namespace std;
const char* prompt();
int jump(const char*);
void fa() { printf("this is fa()\n"); };
void fb() { printf("this is fb()\n"); };
void fc() { printf("this is fc()\n"); };
void fd() { printf("this is fd()\n"); };
void fe() { printf("this is fe()\n"); };
void (*funcs[])() = { fa, fb, fc, fd, fe };
int main()
{
while (jump(prompt()));
printf("\nDone \n");
return 0;
}
const char* prompt()
{
printf("Choose an option:\n");
printf("1. Function fa()\n");
printf("2. Function fb()\n");
printf("3. Function fc()\n");
printf("4. Function fd()\n");
printf("5. Function fe()\n");
printf("Q. Quit\n");
printf(">>");
fflush(stdout);
const int buffer_size = 16;
static char response[buffer_size];
cin >> response;
return response;
}
int jump(const char* rs)
{
char code = rs[0];
if (code == 'q' || code == 'Q') return 0;
//lengt of the funcs array
int func_length = sizeof(funcs) / sizeof(funcs[0]);
int i = (int)code - '0'; // convert ASCII numeral to int
if (i < 1 || i > func_length) {
printf("invalid choice\n");
return 1;
}
else {
funcs[i - 1]();
return 1;
}
} | true |
4d0cc846279d41ef7e7e7a5133f58f2be823792a | C++ | ammarsalman94/Projects | /WindowsTextSearch/test/cpps/Entry.cpp | UTF-8 | 2,983 | 2.953125 | 3 | [] | no_license | /////////////////////////////////////////////////////////////////////
// Entry.cpp - Test stub for NoSqlDb package //
// Ver 1.0 //
// Application: Project #1 - No-SQL Database - CSE-687 //
// Platform: Dell Inspiron 5520, Win 10, Visual Studio 2015 //
// Author: Ammar Salman, EECS, Syracuse University //
// (313) 788-4694 hoplite.90@hotmail.com //
/////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <vector>
#include "..\RegularExpression\RegularExpression.h"
#include "Element.h"
#include "NoSqlDb.h"
using namespace std;
// test stub for Element<T> and NoSQLDB<KeyType, Type>
#ifdef TEST_NOSQLDB
Element<string> TestElement() {
Element<string> e1;
e1.SetKey("key1");
e1.SetName("element1");
e1.SetCategory("C++");
e1.SetDescription("example element");
e1.SetData("i love c++");
e1.AddChild("key2");
e1.AddChild("key3");
cout << "\n Testing Element<string> ";
cout << "\n ========================= ";
cout << "\n Printing element:";
cout << "\n" << e1.ToString();
cout << "\n\n Printing element to XML:";
cout << "\n" << e1.ToXMLString();
return e1;
}
int main() {
// testing element
Element<string> e1 = TestElement();
Element<string> e2;
e2.SetKey("key2");
e2.SetName("element2");
e2.SetCategory("C#");
e2.SetDescription("example element two");
e2.SetData("i love c#");
e2.AddChild("key3");
e2.AddChild("key4");
cout << "\n\n\n Testing NoSQLDB<string> ";
cout << "\n ================================= ";
cout << "\n\n Creating database";
NoSQLDB<string> db;
cout << "\n\n Adding elements to database:";
if (db.AddEntry(e1.GetKey(), e1) && db.AddEntry(e2.GetKey(), e2))
cout << "\n Entries added:\n" << e1.ToString()
<< "\n" << e2.ToString();
cout << "\n\n Importing Database from 'database.xml'";
db.ImportXML("database.xml");
cout << "\n" << db.ToString();
cout << "\n\n Executing query: { get data='dummy' and (name='ammar' or category='python') }";
vector<string> output = db.ExecuteQuery("get data='dummy' and (name='ammar' or category='python')");
cout << "\n obtained keys and their information:";
int size = output.size();
for (int i = 0; i < size; i++)
cout << "\n Key: " << output[i] << "; Data: " << db.GetElement(output[i]).GetData()
<< "; Name: " << db.GetElement(output[i]).GetName() << "; Category: " << db.GetElement(output[i]).GetCategory();
cout << "\n\n Adding element using regular expression: ";
cout << "\n { add key='key10' name='ammar' category='mongodb' description='testquery'";
cout << "\n data = 'something' children = 'key1,key2,key3' }";
db.ExecuteQuery("add key='key10' name='ammar' category='mongodb' description='testquery' data='something' children='key1,key2,key3'");
cout << "\n Printing out the new element:\n" << db.GetElement("key10").ToString() << "\n";
db.StoreXML("database2.xml");
return 0;
}
#endif | true |
affee8261cba838b3eda648bd6a349aff9001367 | C++ | AnastasiyaKuznetsova99/09_03 | /09_03/1.cpp | UTF-8 | 1,439 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <vector>
#include <chrono>
#include <random>
#include <iterator>
#include <array>
class Timer
{
using clock_t = std::chrono::steady_clock;
using timepoint_t = clock_t::time_point;
private:
timepoint_t begin;
public:
Timer() : begin(clock_t::now())
{}
~Timer() noexcept
{
/*auto end = clock_t::now();
std::cout << "lead time: " << std::chrono::duration_cast <std::chrono::microseconds>(end -
begin).count() << std::endl;*/
}
void stop()
{
auto end = clock_t::now();
std::cout << "lead time: " << std::chrono::duration_cast <std::chrono::microseconds>(end -
begin).count() << std::endl;
}
};
int main()
{
std::mt19937 gen;
gen.seed(time(0));
std::set<int> mySet;
Timer myTimer_2;
std::vector<int> myVector;
for (int i = 0; i < 10; i++)
{
myVector.push_back(gen());
}
std::sort(myVector.begin(), myVector.end());
myTimer_2.stop();
Timer myTimer_1;
for (int i = 0; i < 10; i++)
{
mySet.insert(myVector[i]);
}
myTimer_1.stop();
Timer myTimer_3;
std::array<int, 10> myArray;
for (int i = 0; i < 10; i++)
{
myArray[i] = myVector[i];
}
std::sort(myArray.begin(), myArray.end());
myTimer_3.stop();
/*std::cout << "mySet" << std::endl;
for (auto& item : mySet)
{
std::cout << item << std::endl;
}
std::cout << "Vector" << std::endl;
for (int i = 0; i < 10; i++)
{
std::cout << myVector[i] << std::endl;
}*/
return 0;
} | true |
c98b349021a33e10ca98b34232be15690c2ae0b3 | C++ | Vincent-Renard/mpi-td-tutos | /TD6-Mandelbrot/Mandel/Mandelbrot.cpp | UTF-8 | 4,838 | 2.703125 | 3 | [] | no_license | //#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <ctime>
#include <cstring>
#include <omp.h>
using namespace std;
int i4_min ( int i1, int i2 ){
int value;
if ( i1 < i2 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
void i4pp_delete ( int **a, int m, int n ){
int i;
for ( i = 0; i < m; i++ )
{
delete [] a[i];
}
delete [] a;
return;
}
//****************************************************************************80
int **i4pp_new ( int m, int n ){
int **a;
int i;
a = new int *[m];
if ( a == NULL )
{
cerr << "\n";
cerr << "I4PP_NEW - Fatal error!\n";
cerr << " Unable to allocate row pointer array.\n";
exit ( 1 );
}
for ( i = 0; i < m; i++ )
{
a[i] = new int[n];
if ( a[i] == NULL )
{
cerr << "\n";
cerr << "I4PP_NEW - Fatal error!\n";
cerr << " Unable to allocate row array.\n";
exit ( 1 );
}
}
return a;
}
//****************************************************************************
int main ( int argc, char *argv[] ){
int n_nodes = atoi(argv[1]);
int m = 1000;
int n = 1000;
int **b;
int c;
int c_max;
int count_max = 2000;
int count = 0;
int **g;
int i;
int ierror;
int j;
int jhi;
int jlo;
int k;
string filename = "mandelbrot.ppm";
ofstream output;
int **r;
double wtime;
double wtime_total;
double x_max = 1.25;
double x_min = - 2.25;
double x;
double x1;
double x2;
double y_max = 1.75;
double y_min = - 1.75;
double y;
double y1;
double y2;
b = i4pp_new ( m, n );
g = i4pp_new ( m, n );
r = i4pp_new ( m, n );
cout << "\n";
cout << "MANDELBROT_OPENMP\n";
cout << " C++/OpenMP version\n";
cout << "\n";
cout << " Create an ASCII PPM image of the Mandelbrot set.\n";
cout << "\n";
cout << " For each point C = X + i*Y\n";
cout << " with X range [" << x_min << "," << x_max << "]\n";
cout << " and Y range [" << y_min << "," << y_max << "]\n";
cout << " carry out " << count_max << " iterations of the map\n";
cout << " Z(n+1) = Z(n)^2 + C.\n";
cout << " If the iterates stay bounded (norm less than 2)\n";
cout << " then C is taken to be a member of the set.\n";
cout << "\n";
cout << " An ASCII PPM image of the set is created using\n";
cout << " M = " << m << " pixels in the X direction and\n";
cout << " N = " << n << " pixels in the Y direction.\n";
wtime = omp_get_wtime ( );
//***************** Partie à paralléliser
//#pragma omp task
#pragma omp parallel for private(x,y,x1,x2,y1,y2,c,i,j,k)
for (i = 0; i < m; i++) {
#pragma omp task
//untied
for (j = 0; j < n; j++) {
x = ((double) (j - 1) * x_max + (double) (m - j) * x_min) / (double) (m - 1);
y = ((double) (i - 1) * y_max + (double) (n - i) * y_min) / (double) (n - 1);
count = 0;
x1 = x;
y1 = y;
for (k = 1; k <= count_max; k++) {
x2 = x1 * x1 - y1 * y1 + x;
y2 = 2 * x1 * y1 + y;
if (x2 < -2.0 || 2.0 < x2 || y2 < -2.0 || 2.0 < y2) {
count = k;
break;
}
x1 = x2;
y1 = y2;
}
if ((count % 2) == 1) {
r[i][j] = 255;
g[i][j] = 255;
b[i][j] = 255;
} else {
c = (int) (255.0 * sqrt(sqrt(sqrt(((double) (count) / (double) (count_max))))));
r[i][j] = 3 * c / 5;
g[i][j] = 3 * c / 5;
b[i][j] = c;
}
}
}
wtime = omp_get_wtime ( ) - wtime;
cout << "\n";
cout << " Time = " << wtime << " seconds.\n";
//Write data to an ASCII PPM file.
output.open ( filename.c_str ( ) );
output << "P3\n";
output << n << " " << m << "\n";
output << 255 << "\n";
for ( i = 0; i < m; i++ ){
for ( jlo = 0; jlo < n; jlo = jlo + 4 ){
jhi = i4_min ( jlo + 4, n );
for ( j = jlo; j < jhi; j++ ){
output << " " << r[i][j]
<< " " << g[i][j]
<< " " << b[i][j] << "\n";
}
output << "\n";
}
}
output.close ( );
cout << "\n";
cout << " Graphics data written to \"" << filename << "\".\n";
// Free memory.
i4pp_delete ( b, m, n );
i4pp_delete ( g, m, n );
i4pp_delete ( r, m, n );
// Terminate.
cout << "\n";
cout << "MANDELBROT_OPENMP\n";
cout << " Normal end of execution.\n";
cout << "\n";
//2.31489 seconds. seq
return 0;
}
| true |
01528fb41c39c40e5d8fca4f56b598667ba1ff36 | C++ | FrodoAlves/AEDA | /aeda/Voo.h | UTF-8 | 1,201 | 2.796875 | 3 | [] | no_license | #ifndef VOO_H
#define VOO_H
#include <iostream>
#include <vector>
#include "Passageiro.h"
#include "Date.h"
#include "Aviao.h"
using namespace std;
class Voo
{
vector<Date> data;
Aviao* aviao; //aviao alocado //datas de partida e chegada
vector <Passageiro *> Passageiros;
int lugares_ocupados;
//fazer aeroportos para 2a parte do trabalho
public:
vector<Date> getDatas();
Voo(Aviao* aviao, vector<Date> datas, vector <Passageiro *> pass); //posteriormente adicionar aeroporto de partida/chegada
~Voo();
int No_lugares_vazios();
void adicionarPassageiro(Passageiro * p);
int getLugares_ocupados();
//remover passageiro
};
class VooComercial: public Voo
{
string partida, destino;
int id_voo;
public:
VooComercial(Aviao* aviao,vector<Date> datas, vector <Passageiro *> pass,string partida, string destino);
~VooComercial();
void setId_voo(int id);
int getId_voo();
};
class VooAlugado: public Voo
{
string partida, destino;
int id_voo;
public:
VooAlugado(Aviao* aviao, vector<Date> datas, vector <Passageiro *> pass, string partida, string destino);
~VooAlugado();
void setId_voo(int id);
int getId_voo();
};
# endif | true |
fc7d2bb6d7e6f000a239af006425db0f8fb21766 | C++ | velamen2009/HackerRank | /Algorithm/Implementation/P21-Non-Divisible-Subset.cpp | UTF-8 | 692 | 2.609375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n, k;
cin >> n >> k;
vector<int> num(n);
vector<int> mod(k);
for(int i = 0; i < n; ++i){
cin >> num[i];
num[i] %= k;
mod[num[i]]++;
}
int cnt = 0;
if(mod[0] > 0){ cnt = 1; }
for(int i = 1; i <= k / 2; ++i){
if(i == k - i){
if(mod[i] > 0){
++cnt;
}
}
else{
cnt += max(mod[i], mod[k - i]);
}
}
cout << cnt << endl;
return 0;
} | true |
bb82301e6e5aa442dd184e50edd065672b0668b1 | C++ | IshaKawatra/HelloWorld | /modratewindow.cpp | UTF-8 | 1,134 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include "modratewindow.h"
#include "ratewindow.h"
ModRateWindow::ModRateWindow(Movie* trytofind, Netflix *n){
this->n = n; //initialize netflix class
this->trytofind = trytofind;
QVBoxLayout *mainLayout = new QVBoxLayout; //the V means vertical
QHBoxLayout *buttonLayout = new QHBoxLayout; //the H means horizontal!!
mainLayout->addWidget(new QLabel ("Would you like to change your previous rating for this movie?"));
modButton = new QPushButton ("&Modify Rating"); //the ampersand means that alt-Q will work
quitButton = new QPushButton("&I want to keep this rating");
connect(modButton,SIGNAL(clicked()),this,SLOT(modPressed())); //connect functionalities to events
connect(quitButton, SIGNAL(clicked()), this, SLOT(quitPressed()));
buttonLayout->addWidget(modButton);
buttonLayout->addWidget(quitButton);
mainLayout->addLayout(buttonLayout); //nesting layouts
setLayout(mainLayout);
}
void ModRateWindow::modPressed(){
//RateWindow *r = new RateWindow(temp, n);
//r->show();
close();
}
void ModRateWindow::quitPressed(){
close();
}
| true |
e2da690bff264f71f3064d845eab5e5c2d88cf99 | C++ | Murzaza/WinterProject | /src/model.h | UTF-8 | 802 | 2.71875 | 3 | [] | no_license | #include<vector>
#ifdef __APPLE__
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
class Model
{
public:
Model();
//Setters
void setVerts(std::vector<std::vector<GLfloat> > set);
void setNorms(std::vector<std::vector<GLfloat> > set);
void setTex(std::vector<std::vector<GLfloat> > set);
void setFaces(std::vector<std::vector<int> > set);
//Getters
std::vector<std::vector<GLfloat> > getVerts();
std::vector<std::vector<GLfloat> > getNorms();
std::vector<std::vector<GLfloat> > getTex();
std::vector<std::vector<int> > getFaces();
bool hasTex;
bool hasNorm;
GLfloat x, y, z;
private:
std::vector<std::vector<GLfloat> > verts;
std::vector<std::vector<GLfloat> > norms;
std::vector<std::vector<GLfloat> > tex;
std::vector<std::vector<int> > faces;
};
| true |
4f72e92dbd31b8ae49816ff88d74403f33c1200b | C++ | jinhyo/POCU | /Assignment2/Boatplane.cpp | UHC | 1,764 | 3.1875 | 3 | [
"MIT"
] | permissive | #include "Boatplane.h"
namespace assignment2
{
Boatplane::Boatplane(unsigned int maxPassengersCount)
: Vehicle(maxPassengersCount)
{
}
Boatplane::Boatplane(Boatplane&& other)
{
mMaxPassengerNumber = other.mMaxPassengerNumber;
mPassengerCount = other.mPassengerCount;
mPassengers = other.mPassengers;
// ̰ ʿѰ ƴ
for (size_t i = 0; i < mPassengerCount; i++)
{
other.mPassengers[i] = NULL;
}
other.mPassengers = NULL;
}
Boatplane& Boatplane::operator=(Boatplane&& other)
{
mMaxPassengerNumber = other.mMaxPassengerNumber;
mPassengerCount = other.mPassengerCount;
mPassengers = other.mPassengers;
for (size_t i = 0; i < mPassengerCount; i++)
{
other.mPassengers[i] = NULL;
}
other.mPassengers = NULL;
return *this;
}
Boatplane::~Boatplane()
{
}
unsigned int Boatplane::GetFlySpeed() const
{
unsigned int x = GetMaxPassengersWeight();
mFlySpeed = 150.0 * exp((-1.0 * x + 500.0) / 300.0);
mFlySpeed = static_cast<unsigned int>(round(mFlySpeed));
return static_cast<unsigned int>(mFlySpeed);
}
unsigned int Boatplane::GetSailSpeed() const
{
unsigned int x = GetMaxPassengersWeight();
mSailSpeed = 800.0 - 1.7 * x;
mSailSpeed = static_cast<unsigned int>(round(mSailSpeed));
// ڵ
return mSailSpeed > 20 ? mSailSpeed : 20;
}
// ʿ?
unsigned int Boatplane::GetMaxSpeed() const
{
// ڵ
return GetFlySpeed() > GetSailSpeed() ? mFlySpeed : mSailSpeed;
}
void Boatplane::Move()
{
if (mMoveCount < 1)
{
mMoveCount++;
mDistance += GetMaxSpeed();
return;
}
if (mMoveCount == 1)
{
mBreakCount++;
}
if (mBreakCount == 3)
{
mMoveCount = 0;
mBreakCount = 0;
}
}
} | true |
e39eb4649c0d7b192744522afc116cb07e7c096f | C++ | templateaholic10/testrepo | /EM_algorithm/pdist.hpp | UTF-8 | 4,332 | 2.75 | 3 | [] | no_license | #ifndef PDIST
#define PDIST
#include <iostream>
#include <fstream>
#include <array>
#include <random>
#include <functional>
#include "statistic_util.hpp"
#include "../lab/util.hpp"
namespace statistic {
template <int dim>
using dvector = statistic_util::dvector <dim>;
template <int dim>
using dmatrix = statistic_util::dmatrix <dim>;
// メタ関数
// 未知の分布
struct UNKNOWN
{
using type = UNKNOWN;
};
// 正規分布
struct GAUSSIAN
{
using type = GAUSSIAN;
};
// 混合正規分布
template <int mixture_num>
struct GAUSSIAN_MIXTURES
{
using type = GAUSSIAN_MIXTURES <mixture_num>;
};
// プライマリテンプレート
template <int dim, class distribution>
class Probability_distribution
{
};
// 正規分布の確率分布
template <int dim>
class Probability_distribution <dim, GAUSSIAN>
{
public:
Probability_distribution() = delete;
Probability_distribution(const dvector <dim> &mu, const dmatrix <dim> &A);
~Probability_distribution() = default;
double pdf(const dvector <dim> &x) const; // 確率密度関数
dvector <dim> generate(); // 確率分布からデータを1つ生成する関数
template <int ... Meshes>
void output(std::ostream &os, const statistic_util::Range <dim> &range, const statistic_util::FORMAT format) const; // ファイルに書き出す
void outparam(std::ostream &os, const statistic_util::FORMAT format) const; // パラメータをファイルに書き出す
private:
const dvector <dim> _mu; // 平均ベクトル
const dmatrix <dim> _sigma; // 分散共分散行列 _sigma := _A * _A^T
// 以下冗長
const dmatrix <dim> _A; // 変換行列
dmatrix <dim> _sigmaInverse; // 精度行列
const double _sigmaDeterminant; // 分散共分散行列のディターミナント
// 乱数生成器
std::random_device _rnd; // 非決定的乱数生成器
std::mt19937 _mt; // メルセンヌ・ツイスタ
std::normal_distribution <> _stdnorm; // 1次元標準正規分布に従う乱数生成器
};
// 混合正規分布の確率分布
template <int dim, int mixture_num>
class Probability_distribution <dim, GAUSSIAN_MIXTURES <mixture_num> >
{
public:
Probability_distribution() = delete;
Probability_distribution(const std::array <double, mixture_num> &pi, const std::array <dvector <dim>, mixture_num> &mus, const std::array <dmatrix <dim>, mixture_num> &As);
~Probability_distribution() = default;
double pdf(const dvector <dim> &x) const; // 確率密度関数
dvector <dim> generate(); // 確率分布からデータを1つ生成する関数
template <int ... Meshes>
void output(std::ostream &os, const statistic_util::Range <dim> &range, const statistic_util::FORMAT format) const; // ファイルに書き出す
void outparam(std::ostream &os, const statistic_util::FORMAT format) const; // パラメータをファイルに書き出す
private:
const std::array <double, mixture_num> _pi; // 混合比
const std::array <dvector <dim>, mixture_num> _mus; // 平均ベクトル
const std::array <dmatrix <dim>, mixture_num> _As; // 変換行列
std::array <dmatrix <dim>, mixture_num> _sigmas; // 分散共分散行列 _sigma := _A * _A^T
// 以下冗長
std::array <dmatrix <dim>, mixture_num> _sigmaInverses; // 精度行列
std::array <double, mixture_num> _sigmaDeterminants; // 分散共分散行列のディターミナント
// 乱数生成器
std::random_device _rnd; // 非決定的乱数生成器
std::mt19937 _mt; // メルセンヌ・ツイスタ
std::normal_distribution <> _stdnorm; // 1次元標準正規分布に従う乱数生成器
std::uniform_real_distribution <> _mixvoter; // 一様分布に従う乱数生成器
};
void testgaussian();
// void testgaussian_mixtures();
}
#include "detail/pdist.hpp"
#endif
| true |
621f7fbcf82cfdca2d855f613217cacd94e4dc91 | C++ | majabedi/memilio | /cpp/models/abm/testing_scheme.h | UTF-8 | 1,540 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef EPI_ABM_TESTING_SCHEME_H
#define EPI_ABM_TESTING_SCHEME_H
#include "abm/time.h"
#include "abm/parameters.h"
#include "abm/time.h"
#include <functional>
namespace mio
{
class Person;
/**
* Testing Scheme to regular test people
*/
class TestingScheme
{
public:
/**
* create a testing scheme.
* @param interval the interval in which people who go to the location get tested
* @param probability probability with which a person gets tested
*/
TestingScheme(TimeSpan interval, double probability);
/**
* create a default testing scheme such that no regular testing happens
*/
TestingScheme();
/**
* get the time interval of this testing scheme
*/
TimeSpan get_interval() const
{
return m_time_interval;
}
/**
* get probability of this testing scheme
*/
double get_probability() const
{
return m_probability;
}
/**
* set the time interval of this testing scheme
*/
void set_interval(TimeSpan t)
{
m_time_interval = t;
}
/**
* set probability of this testing scheme
*/
void set_probability(double p)
{
m_probability = p;
}
/**
* runs the testing scheme and tests a person if necessary
* @return if the person is allowed to enter the location
*/
bool run_scheme(Person& person, const GlobalTestingParameters& params) const;
private:
TimeSpan m_time_interval;
double m_probability;
};
} // namespace mio
#endif
| true |
79b70cc4f879804064b6c3d5d3f0a83749a1c852 | C++ | swati2917/C- | /sum.cpp/sum.cpp/Sum.cpp | UTF-8 | 214 | 3.25 | 3 | [] | no_license | // this is a sum program
#include <iostream>
using namespace std;
int a = 4;
int b = 5;
double c = 3.406678;
float d = 4.1;
double result;
int main()
{
c = c + d;
result = a - d;
cout << result << endl;
} | true |
e598b1df0887f1c2d8ff0606d18adbe00edae4c9 | C++ | futureshocked/ESP32-For-Busy-People-1 | /04-050_Analog_input_with_pot/04-050_Analog_input_with_pot.ino | UTF-8 | 1,493 | 2.859375 | 3 | [
"MIT"
] | permissive | /* 04.050 - ESP32 Analog input with potentiometer
This sketch shows you how to read the state of a potentiometer using an ESP32.
As you turn the potentiometer knob, see the measured value in the serial monitor.
This sketch was written by Peter Dalmaris using information from the
ESP32 datasheet and examples.
Components
----------
- ESP32 Dev Kit v4
- 10 KOhm potentiometer
IDE
---
Arduino IDE with ESP32 Arduino Code
(https://github.com/espressif/arduino-esp32)
Libraries
---------
- None
-
Connections
-----------
Refer to wiring diagram for a visual wiring guide
ESP32 Dev Kit | Potentiometer
------------------------------
GND | Pin 1
GPIO36 | Pin 2 (middle)
GND | Pin 3
Other information
-----------------
1. ESP32 Datasheet: https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf
2. Espressif Docs: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/adc.html#configuration-and-reading-adc
Created on March 26 2019 by Peter Dalmaris
*/
const byte POT_GPIO = 36;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// print out the value you read:
Serial.println(analogRead(POT_GPIO));
}
| true |
880989c2ef1d112217617a79a03f18c5d1d0f90c | C++ | luismalta/analise_algoritmos_2 | /Algoritmos/Topological sorting for Directed Acyclic Graph/Kahn.cpp | UTF-8 | 2,762 | 3.59375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Graph
{
int V; //Número de vertices
// Ponteiro para uma vetor contendo listas de adjacências
list<int> *adj;
public:
Graph(int V); // Constructor
// Função que adiciona aresta ao grafo
void addEdge(int u, int v);
// Imprimi um grafo Topologico ordenado do grafo completo
void topologicalSort();
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int u, int v)
{
adj[u].push_back(v);
}
// A função do Grafo Topologico Ordenado
void Graph::topologicalSort()
{
// Cria um vetor para armazenar todos os vértices indevidos.
// Inicialize todos os indevidos como 0.
vector<int> in_degree(V, 0);
// Atravessa a listas de adjacência para preencher os vértices
// indevidos. Este passo leva o tempo de O (V + E).
for (int u=0; u<V; u++)
{
list<int>::iterator itr;
for (itr = adj[u].begin(); itr != adj[u].end(); itr++)
in_degree[*itr]++;
}
// Crie uma fila e em fila todos os vértices indevidos com 0
queue<int> q;
for (int i = 0; i < V; i++)
if (in_degree[i] == 0)
q.push(i);
// Inicializa contagem de vértices visitados
int cnt = 0;
// Cria um vetor para armazenar o resultado
// (Uma ordenação topológica dos vértices)
vector <int> top_order;
// One by one dequeue vertices from queue and enqueue
// adjacents if indegree of adjacent becomes 0
while (!q.empty())
{
// Extract front of queue (or perform dequeue)
// and add it to topological order
int u = q.front();
q.pop();
top_order.push_back(u);
// Iterate through all its neighbouring nodes
// of dequeued node u and decrease their in-degree
// by 1
list<int>::iterator itr;
for (itr = adj[u].begin(); itr != adj[u].end(); itr++)
// If in-degree becomes zero, add it to queue
if (--in_degree[*itr] == 0)
q.push(*itr);
cnt++;
}
// Checa se tem um ciclo no grafo
if (cnt != V)
{
printf("Existe um ciclo no grafo\n");
return;
}
// Imprime a ordenação topologica do grafo
for (int i=0; i<top_order.size(); i++)
printf("%d ", top_order[i]);
printf("\n");
}
int main()
{
int n, a, b;
scanf("%d", &n);
Graph g(n); // Tamanho do Grafo
for (int i = 0; i < n; i++)
{
// O grafo é direcionado do nó a para o nó b
scanf("%d %d", &a, &b);
g.addEdge(a, b);
}
printf("A seguir uma ordenação Topologica do grafo:\n");
g.topologicalSort();
return 0;
}
| true |
ba8d5bdd2d06fa1e70c54a6737daf36d964ae0f4 | C++ | pke456/POKEMON | /main/Player.cpp | UTF-8 | 1,517 | 2.734375 | 3 | [] | no_license | #include "stdafx.h"
#include "Player.h"
Player::Player(){}
Player::~Player(){}
HRESULT Player::init(void)
{
_playerRC = RectMakeCenter(WINSIZEX / 2, WINSIZEY / 2, 50, 50);
menu.init();
LEFT = RIGHT = UP = DOWN = menuToggle = false;
return E_NOTIMPL;
}
void Player::release(void)
{
}
void Player::update(void)
{
menu.update();
//Charecter Movement
if (!menuToggle)
{
if (KEYMANAGER->isStayKeyDown(VK_LEFT))
{
_playerRC.left -= 5;
_playerRC.right -= 5;
}
if (KEYMANAGER->isStayKeyDown(VK_RIGHT))
{
_playerRC.left += 5;
_playerRC.right += 5;
}
if (KEYMANAGER->isStayKeyDown(VK_UP))
{
_playerRC.top -= 5;
_playerRC.bottom -= 5;
}
if (KEYMANAGER->isStayKeyDown(VK_DOWN))
{
_playerRC.top += 5;
_playerRC.bottom += 5;
}
}
//MENU
if(menuToggle)
{
if (KEYMANAGER->isOnceKeyDown(VK_UP))
{
menu.selectMenu--;
}
if (KEYMANAGER->isOnceKeyDown(VK_DOWN))
{
menu.selectMenu++;
}
if (KEYMANAGER->isOnceKeyDown('Z'))
{
switch (menu.selectMenu)
{
case 0:
break;
case 1:
break;
case 2:
menuToggle = false;
break;
default:
break;
}
}
}
if (!menuToggle)
{
menu.selectMenu = 0;
if (KEYMANAGER->isOnceKeyDown('X'))
{
menuToggle = true;
}
}
if (menuToggle)
{
if(KEYMANAGER->isOnceKeyDown('X'))
{
menuToggle = false;
}
}
}
void Player::render(HDC hdc)
{
if (menuToggle)
{
menu.render(hdc);
}
Rectangle(hdc, _playerRC.left, _playerRC.top, _playerRC.right, _playerRC.bottom);
} | true |
6092e89d429797d48179634ef5fe436e87b81620 | C++ | katherine0504/Uva | /10107.cpp | UTF-8 | 446 | 2.734375 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <algorithm>
#define MAX 10010
using namespace std;
int arr[MAX];
int cnt = 0, input;
int main() {
while(scanf("%d", &input) != EOF) {
arr[cnt++] = input;
sort(arr, arr+cnt);
if (cnt == 1) {
printf("%d\n", input);
}
else if (cnt%2 == 0) {
printf("%d\n", (arr[cnt/2] + arr[cnt/2-1])/2);
}
else{
printf("%d\n", arr[cnt/2]);
}
}
return 0;
}
| true |
ecc0ae95422da1af63618eeba0380507c43a2a89 | C++ | LucasPauloOP/AED | /Trabalho_de_revisão_ex1.cpp | UTF-8 | 677 | 3.21875 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include<string.h>
#include<locale.h>
typedef struct {
char nome[30];
char sexo[2];
int idade;
float altura;
}Pessoa;
int main()
{
setlocale(LC_ALL,"portuguese");
Pessoa p;
printf("\nDigite um nome: ");
gets(p.nome);
printf("\nDigite F para sexo feminino e M para sexo masculino: ");
gets(p.sexo);
printf("\nDigite a idade da pessoa: ");
scanf("%d",&p.idade);
printf("\nDigite a sua altura: ");
scanf("%f",&p.altura);
printf("\nO nome digitado foi: %s",p.nome);
printf("\nO sexo digitado foi: %s",p.sexo);
printf("\nA idade digitada foi: %d",p.idade);
printf("\nA altura digitada foi: %2.f",p.altura);
}
| true |
ac5195cbfcb7ddbe30e332ed21e95a956b67ec21 | C++ | xzqingzi/LeetCodeEx | /src/49_Group_Anagrams.cpp | UTF-8 | 705 | 3.125 | 3 | [] | no_license | class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,int> mymap;
vector<vector<string>> output;
string temp;
int i = 0;
for (string s : strs) {
temp = s;
sort(temp.begin(), temp.end()); // sort the string
if (!mymap.count(temp)) {
vector<string> in(1,s); //output is a matrix, the first level could only push into a vector
output.push_back(in);
mymap[temp] = i;
i++;
}
else {
output[mymap[temp]].push_back(s);
}
}
return output;
}
}; | true |
663f839cbddc139e6e18fab29c09b8736c96e122 | C++ | iPalash/allconnect | /c1.cpp | UTF-8 | 6,136 | 2.640625 | 3 | [] | no_license | #include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
#include <vector>
#define FOR(i,n) for (int i = 0; i < n; i++)
#define INF 1000000
#define PB push_back
#include "feature.cpp"
using namespace std;
/* Complete the function below to print 1 integer which will be your next move
*/
int N, M, K, player;
int DEPTH_LIMIT;
vector<string> board;
int totaltime = 47;
int starttime;
int moves,moveCount;
void update(int n)
{
for(int i = 0; i < N; i++)
if(board[i][n] == '.')
{
board[i][n] = 'X';
return;
}
}
void updateother(int n)
{
for(int i = 0; i < N; i++)
if(board[i][n] == '.')
{
board[i][n] = 'O';
return;
}
}
void printboard(){
for(int i=N-1; i>=0; i--)cout << board[i] << endl;
}
int eval()
{
if (moveCount<M*N/6)
return retEval(board, N, M, K,1);
else if (moveCount<M*N/3)
return retEval(board, N, M, K,0);
else
return retEval(board, N, M, K,-1);
}
int mini(int,int,int);
int maxi(int,int,int);
int mini(int alpha,int beta, int depth){
vector<int> v;
for(int j = M/2; j>=0; j--)
{
if(board[N-1][j] == '.')
{
v.push_back(j);
}
if(board[N-1][M-j-1] == '.' && M-j-1 != j)
{
v.push_back(M-j-1);
}
}
if(v.size() == 0 || depth > DEPTH_LIMIT)return eval();
int ret = INF;
FOR(ii, v.size()){
int col = v[ii];
updateother(col);
int temp=maxi(alpha,beta,depth+1);
ret = min(ret, temp);
beta=min(beta,temp);
for(int i=N-1; i>= 0; i--){
if(board[i][col] != '.') {
board[i][col] = '.';
break;
}
}
if (alpha>=beta) return ret;
}
return ret;
}
int maxi(int alpha,int beta, int depth){
vector<int> v;
for(int j = M/2; j>=0; j--)
{
if(board[N-1][j] == '.')
{
v.push_back(j);
}
if(board[N-1][M-j-1] == '.' && M-j-1 != j)
{
v.push_back(M-j-1);
}
}
if(v.size() == 0 || depth > DEPTH_LIMIT)return eval();
int ret = -INF;
FOR(ii, v.size()){
int col = v[ii];
update(col);
int temp=mini(alpha,beta,depth+1);
ret = max(ret, temp);
alpha=max(alpha,temp);
for(int i=N-1; i>=0; i--){
if(board[i][col] != '.'){
board[i][col] = '.';
break;
}
}
if (alpha>=beta) return ret;
}
return ret;
}
int nextMove()
{
moveCount++;
DEPTH_LIMIT = (10 -log10(6*M*N*(M+N)))*(totaltime - (time(0) - starttime))/log10(M);
DEPTH_LIMIT /= moves;
int iSecret;
vector<int> v;
for(int j = M/2; j>=0; j--)
{
if(board[N-1][j] == '.')
{
v.push_back(j);
}
if(board[N-1][M-j-1] == '.' && M-j-1 != j)
{
v.push_back(M-j-1);
}
}
iSecret = v[0];
int mu = -INF;
FOR(ii, v.size()){
int col = v[ii];
// cout << "Col: "<<col << endl;
update(col);
int u = mini(-INF,INF,1);
if(u > mu){
mu = u;
iSecret = col;
}
for(int i=N-1; i>=0; i--){
if(board[i][col] != '.'){
board[i][col] = '.';
break;
}
}
}
cout << "We: " << iSecret << endl;
update(iSecret);
printboard();
moves --;
return iSecret;
}
int main(int argc, char *argv[])
{
starttime = time(0);
int sockfd = 0, n = 0;
char recvBuff[1024];
char sendBuff[1025];
struct sockaddr_in serv_addr;
if(argc != 3)
{
printf("\n Usage: %s <ip of server> <port no> \n",argv[0]);
return 1;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[2]));
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
cout<<"Connect(N,M,K) will start"<<endl;
memset(recvBuff, '0',sizeof(recvBuff));
n = read(sockfd, recvBuff, sizeof(recvBuff)-1);
recvBuff[n] = 0;
sscanf(recvBuff, "%d", &N);
cout<<"N: "<<N<<endl;
memset(recvBuff, '0',sizeof(recvBuff));
n = read(sockfd, recvBuff, sizeof(recvBuff)-1);
recvBuff[n] = 0;
sscanf(recvBuff, "%d", &M);
cout<<"M: "<<M<<endl;
memset(recvBuff, '0',sizeof(recvBuff));
n = read(sockfd, recvBuff, sizeof(recvBuff)-1);
recvBuff[n] = 0;
sscanf(recvBuff, "%d", &K);
cout<<"K: "<<K<<endl;
memset(recvBuff, '0',sizeof(recvBuff));
n = read(sockfd, recvBuff, sizeof(recvBuff)-1);
recvBuff[n] = 0;
sscanf(recvBuff, "%d", &player);
cout<<"Player "<<player<<endl;
moves = M * N / 2;
string temp = "";
for(int j = 0; j< M; j++)
temp += ".";
FOR(i, N)
board.PB(temp);
if(player == 1)
{
//cout << "hello" << endl;
memset(sendBuff, '0', sizeof(sendBuff));
int temp = nextMove();
//cout << "temp" << endl;
snprintf(sendBuff, sizeof(sendBuff), "%d", temp);
write(sockfd, sendBuff, strlen(sendBuff));
}
while(1)
{
int nextColumn;
memset(recvBuff, '0',sizeof(recvBuff));
n = read(sockfd, recvBuff, sizeof(recvBuff)-1);
recvBuff[n] = 0;
sscanf(recvBuff, "%d", &nextColumn);
//cout << "Rec: "<< nextColumn << endl;
updateother(nextColumn);
cout << nextColumn << endl;
memset(sendBuff, '0', sizeof(sendBuff));
int temp = nextMove();
//cout << "temp" << endl;
snprintf(sendBuff, sizeof(sendBuff), "%d", temp);
write(sockfd, sendBuff, strlen(sendBuff));
}
return 0;
}
| true |
32ae35abea5a5cc5f3f57f647002f2cf2bc72218 | C++ | newMember1/toyPBRT | /materials/basicbrdfmaterial.h | UTF-8 | 1,212 | 2.65625 | 3 | [] | no_license | #ifndef BASICBRDFMATERIAL_H
#define BASICBRDFMATERIAL_H
#include <vector>
#include "../core/materialBase.h"
using namespace glm;
class basicBRDFMaterial : public materialBase
{
public:
basicBRDFMaterial(std::shared_ptr<textureBase> textureBase);
basicBRDFMaterial(std::shared_ptr<textureBase> textureBase, float m, float r);
void setMetallic(float m);
void setRoughness(float r);
glm::vec3 albedo(const hitRecord &hitRec, const glm::vec3 &lightDirec, const glm::vec3 &eyeDirec) override;
private:
vec3 fresnelSchlick(float cosTheta, vec3 F0);
float DistributionGGX(vec3 N, vec3 H, float roughness);
float GeometrySchlickGGX(float NdotV, float roughness);
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness);
float metallic = 0;
float roughness = 0;
std::vector<glm::vec3> lightPositions =
{
glm::vec3(-10.0f, 10.0f, 10.0f),
glm::vec3(10.0f, 10.0f, 10.0f),
glm::vec3(-10.0f, -10.0f, 10.0f),
glm::vec3(10.0f, -10.0f, 10.0f),
};
std::vector<glm::vec3> lightColors =
{
glm::vec3(300.0f, 300.0f, 300.0f),
glm::vec3(300.0f, 300.0f, 300.0f),
glm::vec3(300.0f, 300.0f, 300.0f),
glm::vec3(300.0f, 300.0f, 300.0f)
};
};
#endif // BASICBRDFMATERIAL_H
| true |
16fb409390bc26d399b156e8f9ec57ba66ffd948 | C++ | Crasader/mygamelogic | /Classes/core/U2PoolingObjectManager.h | UTF-8 | 6,836 | 2.75 | 3 | [] | no_license | #ifndef __U2PoolingObjectManager_H__
#define __U2PoolingObjectManager_H__
#include "U2Prerequisites.h"
#include "U2IteratorWrapper.h"
#include "U2FactoryManager.h"
U2EG_NAMESPACE_BEGIN
class ObjectFactory;
template <class T>
class PoolingObjectManager
{
protected:
/// <guid, T*>
typedef std::map<String, T*> ObjectQueue;
/// <type, ObjectQueue>
typedef std::map<String, ObjectQueue> ObjectQueueMap;
public:
/** Default constructor - should never get called by a client app.
*/
PoolingObjectManager();
/** Default destructor.
*/
virtual ~PoolingObjectManager();
T* createOrReuseObject(const String& type);
const T* retrieveObject(const String& guid) const;
T* retrieveObject(const String& guid);
bool hasObject(const String& guid) const;
void recycleObject(T* obj);
void destoryUnusedObject(const String& type);
typedef MapIterator<ObjectQueue> ObjectQueueIterator;
/** Get an iterator over the Archives in this Manager. */
ObjectQueueIterator getObjectIterator(const String& type)
{
ObjectQueue& queue = mObjects[type];
return ObjectQueueIterator(queue.begin(), queue.end());
}
protected:
T* _createObject(const String& type);
T* _reuseObject(const String& type);
protected:
/// Currently loaded archives
ObjectQueueMap mUsingObjects;
ObjectQueueMap mUnusedObjects;
ObjectQueue mAllObjects;
};
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
template <class T>
PoolingObjectManager<T>::PoolingObjectManager()
{
}
//-----------------------------------------------------------------------
template <class T>
PoolingObjectManager<T>::~PoolingObjectManager()
{
for (ObjectQueue::iterator itr = mAllObjects.begin();
itr != mAllObjects.end();
++itr)
{
FactoryManager::getSingleton().destroyObject(itr->second);
}
mAllObjects.clear();
// Empty the list
mUsingObjects.clear();
// Empty the list
mUnusedObjects.clear();
}
//-----------------------------------------------------------------------
template <class T>
T* PoolingObjectManager<T>::createOrReuseObject(const String& type)
{
do
{
// has unused object?
ObjectQueueMap::iterator itr = mUnusedObjects.find(type);
if (itr != mUnusedObjects.end())
{
ObjectQueue& unusedQueue = itr->second;
if (unusedQueue.size() > 0)
{
break;
}
}
// create
_createObject(type);
} while (false);
return _reuseObject(type);
}
//-----------------------------------------------------------------------
template <class T>
const T* PoolingObjectManager<T>::retrieveObject(const String& guid) const
{
ObjectQueue::const_iterator itr = mAllObjects.find(guid);
if (itr != mAllObjects.end())
{
Object* pObj = itr->second;
ObjectQueueMap::const_iterator itr2 = mUsingObjects.find(pObj->getType());
if (itr2 != mUsingObjects.end())
{
const ObjectQueue& queue = itr2->second;
ObjectQueue::const_iterator itr3 = queue.find(guid);
if (itr3 != queue.end())
{
return itr3->second;
}
}
}
return nullptr;
}
//-----------------------------------------------------------------------
template <class T>
T* PoolingObjectManager<T>::retrieveObject(const String& guid)
{
return const_cast<T*>(this->retrieveObject(guid));
}
//-----------------------------------------------------------------------
template <class T>
bool PoolingObjectManager<T>::hasObject(const String& guid) const
{
return nullptr != retrieveObject(guid);
}
//-----------------------------------------------------------------------
template<class T>
void PoolingObjectManager<T>::recycleObject(T* obj)
{
ObjectQueueMap::iterator itr = mUsingObjects.find(obj->getType());
if (itr != mUsingObjects.end())
{
ObjectQueue& usingQueue = mUsingObjects[obj->getType()];
ObjectQueue::iterator itr2 = usingQueue.find(obj->getGuid());
if (itr2 != usingQueue.end())
{
obj->preRecycleByPool();
// remove from using queue
usingQueue.erase(itr2);
// add to unused queue
ObjectQueue& unusedQueue = mUnusedObjects[obj->getType()];
unusedQueue[obj->getGuid()] = obj;
return;
}
}
}
//-----------------------------------------------------------------------
template<class T>
T* PoolingObjectManager<T>::_createObject(const String& type)
{
T* pObj = dynamic_cast<T*>(FactoryManager::getSingleton().createObject(type, BLANK));
// add to unused queue
ObjectQueue& queue = mUnusedObjects[pObj->getType()];
queue[pObj->getGuid()] = pObj;
// add to all queue
mAllObjects[pObj->getGuid()] = pObj;
return pObj;
}
//-----------------------------------------------------------------------
template<class T>
T* PoolingObjectManager<T>::_reuseObject(const String& type)
{
T* pObj = nullptr;
// Reuse
ObjectQueueMap::iterator itr = mUnusedObjects.find(type);
if (itr != mUnusedObjects.end())
{
ObjectQueue& unusedQueue = itr->second;
if (unusedQueue.size() > 0)
{
// remove from unused pool
ObjectQueue::iterator itr2 = unusedQueue.begin();
pObj = itr2->second;
unusedQueue.erase(itr2);
// add to using pool
ObjectQueue& usingQueue = mUsingObjects[pObj->getType()];
usingQueue[pObj->getGuid()] = pObj;
pObj->postReuseFromPool();
}
}
return pObj;
}
//-----------------------------------------------------------------------
template<class T>
void PoolingObjectManager<T>::destoryUnusedObject(const String& type)
{
ObjectQueueMap::iterator itr = mUnusedObjects.find(type);
if (itr != mUnusedObjects.end())
{
ObjectQueue& queue = itr->second;
for (ObjectQueue::iterator itr2 = queue.begin();
itr2 != queue.end();
++itr2)
{
T* pObj = itr2->second;
// erase from unused queue
queue.erase(itr2);
// erase from all queue
ObjectQueue::iterator itr3 = mAllObjects.find(obj->getGuid());
if (itr3 != mAllObjects.end())
{
mAllObjects.erase(itr3);
}
// delete object
FactoryManager::getSingleton().destroyObject(obj);
}
}
}
U2EG_NAMESPACE_END
#endif // __U2TypedObjectManager_H__
| true |
cbd8b941f87a38c4e02a4c7511427dae20b2a17c | C++ | Padmina91/STLspielwiese | /Logger.cpp | UTF-8 | 1,103 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include "Logger.hpp"
#include "Date.hpp"
#include "Time.hpp"
void Logger::print_date() {
Date now = Date::get_current_date();
DateFormatNumeric df;
now.set_format(&df);
_f << now << " ";
}
void Logger::print_time() {
Time now = Time::get_current_time();
_f << now.to_string() << " ";
}
void Logger::print_level(Logger::Level lvl) {
switch(lvl) {
case Level::INFO:
_f << "[INFO ]: ";
break;
case Level::WARN:
_f << "[WARN ]: ";
break;
case Level::ERROR:
_f << "[ERROR]: ";
break;
default:
_f << "Fehler. Konnte Warnstufe nicht finden.\n";
break;
}
}
Logger::Logger(const std::string& filename) {
_f.open(filename, std::ios::app);
if (!_f) {
std::cout << "failed to open " << filename << std::endl;
}
}
Logger::~Logger() {
_f.close();
}
void Logger::log(Logger::Level lvl, const std::string& message) {
print_date();
print_time();
print_level(lvl);
_f << message << std::endl;
} | true |
641cffdcc9a1c54737c3b6acba8cdd6c2a9c8a48 | C++ | PLUkraine/c8 | /tests/test_c8_read.cc | UTF-8 | 1,548 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | #include "gtest/gtest.h"
#include <iostream>
#include <fstream>
#include <string>
#include "common.h"
#include "c8_read.h"
class c8_read : public ::testing::Test {
protected:
std::string sample_filepath;
const uint8_t data[15] = { 0x03, 0xFA, 0xAA, 0x98, 0x90, 0x32, 0x20, 0x34, 0xAB, 0xDE, 0xAD, 0xBE, 0xEF };
uint8_t buffer[0xFFF];
c8_read()
{
sample_filepath = "example.bin";
}
~c8_read() {}
virtual void SetUp()
{
std::ofstream sample_file(sample_filepath, std::ios::out | std::ios::binary);
sample_file.write((const char *)data, NELEMS(data));
sample_file.close();
memset(buffer, 0x00, NELEMS(buffer));
}
virtual void TearDown()
{
remove(sample_filepath.c_str());
}
};
TEST_F(c8_read, wrong_path)
{
size_t bytes_read = C8_read_program("bad_path.lol", buffer, NELEMS(buffer));
EXPECT_EQ(0, bytes_read);
}
TEST_F(c8_read, correct_file)
{
size_t bytes_read = C8_read_program(sample_filepath.c_str(), buffer, NELEMS(buffer));
EXPECT_EQ(NELEMS(data), bytes_read);
EXPECT_EQ(0, memcmp(buffer, data, NELEMS(data)));
memset(buffer, 0x00, NELEMS(buffer));
bytes_read = C8_read_program(sample_filepath.c_str(), buffer, NELEMS(buffer));
EXPECT_EQ(NELEMS(data), bytes_read);
EXPECT_EQ(0, memcmp(buffer, data, NELEMS(data)));
}
TEST_F(c8_read, small_buffer)
{
uint8_t small_b[5];
size_t bytes_read = C8_read_program(sample_filepath.c_str(), small_b, NELEMS(small_b));
EXPECT_EQ(0, bytes_read);
}
| true |
f7973575a8bcf5c543a164ab3c2e69664437944b | C++ | qcscine/kiwi | /src/Kiwi/Kiwi/KiwiOpt/Bisection.h | UTF-8 | 3,831 | 3 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#ifndef KIWI_BISECTION_H
#define KIWI_BISECTION_H
#include "Kiwi/KiwiUtils/Data.h"
#include <iomanip>
#include <iostream>
namespace Scine {
namespace Kiwi {
namespace Optimization {
/**
* @class Bisection @file Bisction
* @brief Performs a bisection of a function in an interval [a,b].
*/
class Bisection {
public:
double getLowerBound() const {
return lowerBound;
}
void setLowerBound(double lb) {
lowerBound = lb;
}
double getUpperBound() const {
return upperBound;
}
void setUpperBound(double ub) {
upperBound = ub;
}
double getTolerance() const {
return tolerance;
}
void setTolerance(double tol) {
tolerance = tol;
}
int getMaxIterations() const {
return maxIterations;
}
int getIterations() const {
return iteration;
}
void setMaxIterations(int maxIt) {
maxIterations = maxIt;
}
bool wasSuccessful() const {
return wasSuccessful_;
}
private:
double lowerBound = 1;
double midPoint;
double upperBound = 1000;
double valueLB;
double valueMidPoint;
double valueUB;
double tolerance = 1e-10;
int iteration = 0;
int maxIterations = 500;
bool wasSuccessful_ = false;
bool hasBoundaryError_ = false;
public:
bool hasBoundaryError() const {
return hasBoundaryError_;
}
public:
Bisection() = default;
static auto sgn(double val) -> int {
return (double(0) < val) - (val < double(0));
}
/**
* @brief Bisection algorithm.
* @tparam FunctionEvaluator Class that contains the function of which we want to find the zero.
* --> The FunctionEvaluator must have a method `FunctionEvaluator.evaluate(double) -> double`.
* @param evaluator
* @param verbose
* @return solution of the bisection algorithm.
*/
template<class FunctionEvaluator>
auto compute(FunctionEvaluator& evaluator, bool verbose = true) -> double {
if (verbose) {
std::cout << "----------------------------\n";
std::cout << " Bisection\n";
std::cout << "----------------------------\n";
std::cout << " Iteration Error \n";
std::cout << "----------------------------\n";
}
if (upperBound < lowerBound) {
throw std::runtime_error("Error in Bisection. Upper bound is lower than lower bound.");
}
valueLB = evaluator.evaluate(lowerBound);
valueUB = evaluator.evaluate(upperBound);
if (sgn(valueUB) == sgn(valueLB)) {
std::cout << "Lower bound = " << valueLB << std::endl;
std::cout << "Upper bound = " << valueUB << std::endl;
std::cout << "Error in Bisection. Values at upper bound and lower bound have the same sign." << std::endl;
hasBoundaryError_ = true;
return 0;
}
iteration = 0;
for (; iteration < maxIterations; ++iteration) {
midPoint = (lowerBound + upperBound) / 2;
valueMidPoint = evaluator.evaluate(midPoint);
if (verbose) {
std::cout << std::right << std::setw(10) << iteration << std::string(3, ' ') << std::setw(15) << std::scientific
<< std::setprecision(5) << valueMidPoint << std::endl;
}
if (std::abs(valueMidPoint) < tolerance || upperBound - lowerBound / 2 < tolerance) {
wasSuccessful_ = true;
break;
}
if (sgn(valueMidPoint) == sgn(valueLB)) {
lowerBound = midPoint;
}
else {
upperBound = midPoint;
}
}
if (verbose) {
std::cout << "----------------------------\n";
}
return midPoint;
}
};
} // namespace Optimization
} // namespace Kiwi
} // namespace Scine
#endif // KIWI_BISECTION_H
| true |
ca86fc1842821146863e283eaea8b614d2efafb5 | C++ | HarshitDhingra/Competitive-Programming | /Mo's algorithm/square root decomposition.cpp | UTF-8 | 954 | 2.96875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int query(int blocks[], int a[], int l, int r, int rn)
{
int ans = 0;
while (l < r && l % r != 0)
{
ans += a[l];
l++;
}
while (l + rn < r)
{
int index = l / rn;
ans += blocks[index];
l += rn;
}
while (l <= r)
{
ans += a[l];
l++;
}
return ans;
}
void update(int blocks[], int a[], int i, int val, int rn)
{
int index = i / rn;
blocks[index] += val - a[i];
a[i] = val;
}
int main() {
int a[] = {1, 3, 5, 2, 7, 6, 3, 1, 4, 8};
int n = sizeof(a) / sizeof(int);
int rn = sqrt(n);
int blocks[n + 1] = {0};
for (int i = 0; i < n; i++)
{
int index = i / rn;
blocks[index] += a[i];
}
int l, r;
cin >> l >> r;
update(blocks, a, 2, 15, rn);
cout << query(blocks, a, l, r, rn);
}
| true |
20e36be4459a6250cbf01e6566aef59108b8ae1f | C++ | kreczko/swatch | /core/include/swatch/core/ThreadPool.hxx | UTF-8 | 1,578 | 2.546875 | 3 | [] | no_license |
#ifndef __SWATCH_CORE_THREADPOOL_HXX__
#define __SWATCH_CORE_THREADPOOL_HXX__
#include <boost/function.hpp>
#include <boost/bind.hpp>
namespace swatch {
namespace core {
template<class OBJECT, class ResourceGuardType>
void ThreadPool::addTask(OBJECT* aCmd,
boost::function<void(OBJECT*, boost::shared_ptr<ResourceGuardType>, const XParameterSet&)> aFunction,
const boost::shared_ptr<ResourceGuardType>& aResourceGuard,
const XParameterSet& aParamSet)
{
// create packed_task
boost::packaged_task<void> task(boost::bind(aFunction, aCmd, aResourceGuard, boost::ref(aParamSet)));
{
// lock mutex
boost::lock_guard<boost::mutex> guard(mQueueMutex);
if (mStop) {
throw OperationOnStoppedThreadPool(
"ThreadPool is stopped, cannot schedule tasks.");
}
mTasks.push_back(boost::move(task));
}
mCondition.notify_one();
}
template<class OBJECT, class ResourceGuardType>
void ThreadPool::addTask( OBJECT* aCmd , boost::function<void(OBJECT*, boost::shared_ptr<ResourceGuardType>)> aFunction, const boost::shared_ptr<ResourceGuardType>& aResourceGuard )
{
// create packed_task
boost::packaged_task<void> task(boost::bind(aFunction, aCmd, aResourceGuard));
{
// lock mutex
boost::lock_guard<boost::mutex> guard(mQueueMutex);
if (mStop) {
throw OperationOnStoppedThreadPool(
"ThreadPool is stopped, cannot schedule tasks.");
}
mTasks.push_back(boost::move(task));
}
mCondition.notify_one();
}
} // namespace core
} // namespace swatch
#endif /* __SWATCH_CORE_THREADPOOL_HXX__ */
| true |
bbf2710e5a340a20a1c24961a5240ddd6122e5d2 | C++ | Nuos/Elements-of-Programming-Interview | /5.16 Generate uniform Random Numbers/main.cpp | UTF-8 | 495 | 2.96875 | 3 | [] | no_license | /* */
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int randomOneZero(){
return rand()%2;
}
int generateRandom(int a, int b){
int total_num = b-a+1;
int result = total_num;
while(result >= total_num){
result = 0;
for(int i = 0; (1 << i) < total_num; i++){
result = (result << 1) | randomOneZero() ;
}
}
return result + a;
}
int main(){
for(int i = 1; i < 10; i ++ ){
cout << generateRandom(4, 6) << endl;
}
return 1;
}
| true |
42f4210c9653f2c2a60cd3e9539927fdb9f1a4d3 | C++ | mvodya/bkv-labs | /software-engineering/lab5/calculator_v1/calc/functions/const.h | UTF-8 | 397 | 2.734375 | 3 | [] | no_license | #pragma once
#include "../symbol.h"
#include <cmath>
namespace calc {
class Const : public Symbol {
const double value;
public:
Const(double v) : value(v) {};
double call() { return value; }
double call(double a) { return value; }
double call(double a, double b) { return value; }
void set(double v) {}
bool rewritable() { return false; };
Type getType() { return S_VAR; }
};
} | true |
49b8401a807c905dbda1d8f14bb87a86b84ca54c | C++ | enjoy82/atcodersyozin | /c++学習用/ABC132c.cpp | UTF-8 | 272 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include <algorithm>
#include<vector>
using namespace std;
int main(){
int n;cin>>n;
vector<int> a(n);
for(int i = 0; i<n; i++){
cin >> a[i];
}
sort(a.begin(), a.end());
int an = n/2;
cout << a[an]-a[an-1] << endl;
} | true |
25590934d3c79de78ce4b690467c8d3c9be617ba | C++ | redeff/cmp | /cf/1088/E/main.cpp | UTF-8 | 1,498 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const ll INF = 333333333;
struct Node {
ll parent;
vector<ll> children;
};
int main() {
ll n;
cin >> n;
vector<ll> weis(n);
for(ll i = 0; i < n; ++i) cin >> weis[i];
vector<vector<ll>> conns(n);
for(ll i = 0; i < n - 1; ++i) {
ll a, b;
cin >> a >> b;
--a; --b;
conns[a].push_back(b);
conns[b].push_back(a);
}
vector<ll> depths(n, INF);
{
function<void(ll, ll)> dfs = [&](ll node, ll depth) {
if(depths[node] > depth) {
depths[node] = depth;
for(ll conn : conns[node]) dfs(conn, depth + 1);
}
};
dfs(0, 0);
}
vector<Node> tree(n);
for(int i = 0; i < n; ++i) {
for(ll conn : conns[i]) {
if(depths[conn] < depths[i]) tree[i].parent = conn;
else tree[i].children.push_back(conn);
}
}
tree[0].parent = 0;
vector<ll> global_max(n);
{
function<void(ll)> dfs = [&](ll node) {
global_max[node] = weis[node];
for(ll ch : tree[node].children) {
dfs(ch);
global_max[node] += max(global_max[ch], 0ll);
}
};
dfs(0);
}
ll mx = *max_element(global_max.begin(), global_max.end());
ll total = 0;
vector<ll> fit_all(n);
{
function<void(ll)> dfs = [&](ll node) {
global_max[node] = weis[node];
for(ll ch : tree[node].children) {
dfs(ch);
global_max[node] += max(global_max[ch], 0ll);
}
if(global_max[node] == mx) {
global_max[node] = 0;
total++;
}
};
dfs(0);
}
cout << mx * total << " " << total << endl;
}
| true |
7799ce29606b9562ef61b6276029fa3ab4f69498 | C++ | Rocketng/Algorithm | /决赛第五题.cpp | UTF-8 | 855 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct edge{
int from,to,cost;
};
//edge es[1000];
int d[10001];
int V,E;
void shortest_path(int s,vector<edge>&es){
for(int i=0;i<V;i++){
d[i] = INT_MAX;
}
d[s] = 0;
while(true){
bool update =false;
for(int i=0;i<E;i++){
edge e=es[i];
if(d[e.from]!=INT_MAX && d[e.to]>d[e.from]+e.cost){
d[e.to] = d[e.from] +e.cost;
update = true;
}
}
if(!update)
break;
}
}
int main(){
int N,f,t;
cin>>N>>f>>t;
int i=0;
vector<edge> es;
while(true){
int a,b,c;
cin>>a>>b>>c;
if(a==-1&&b==-1&&c==-1)
break;
edge ea,eb;
ea.from = a-1;
ea.to = b-1;
ea.cost = c;
i++;
eb.from = b-1;
eb.to = a-1;
eb.cost = c;
i++;
es.push_back(ea);
es.push_back(eb);
}
V = N;
E = i;
shortest_path(f-1,es);
cout<<d[t-1];
return 0;
}
| true |
8573368dce606b98412385fb722caf04b1af5948 | C++ | Mr-Poseidon/CFile | /AcWing/285没有上司的误舞会(树形DP).cpp | GB18030 | 1,517 | 3.109375 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=6010;
int h[N],e[N],ne[N],idx;//άڽӱ
int happy[N];//άÿ˵Ŀֵ
int f[N][2];//f[i][0] ѡ i˵Ŀֵf[i][1] ѡ i˵Ŀֵ
bool has_father[N];//άijǷиڵ
int n;
void insert(int a,int b)//ڽӱ
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void dfs(int k)//
{
if(f[k][0]!=0)return;//õѾ߹ֱӷ
f[k][1]=happy[k];//ѡkҪkĿֵ
for(int i=h[k];i!=-1;i=ne[i])//kӽڵ
{
int j=e[i];
dfs(j);//j
f[k][0]+=max(f[j][0],f[j][1]);//ѡkʱkӽڵѡҲԲѡ
f[k][1]+=f[j][0];//ѡkʱkӽڵֻܲѡ
}
}
int main()
{
memset(h,-1,sizeof h);//ʼڽӱ
int n;
cin>>n;
for(int i=1;i<=n;i++)cin>>happy[i];//ÿ˵Ŀֵ
for(int i=0;i<n-1;i++)//ڽӱ
{
int a,b;
cin>>a>>b;
insert(b,a);
has_father[a]=true;//¼õиڵ
}
int root;
for(int i=1;i<=n;i++)//ҵڵ㣬˾
if(!has_father[i])
root=i;
dfs(root);//ɸڵ㿪ʼ
printf("%d",max(f[root][0],f[root][1]));//ڵѡ벻ѡֵΪ
return 0;
}
| true |
686b2e16bf4e9b80aa8cc070df543ef3f0f3c265 | C++ | jwvg0425/boj | /solutions/10815/10815.cpp11.cpp | UTF-8 | 470 | 2.546875 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <stack>
#include <math.h>
#include <memory.h>
#include <queue>
#include <set>
int main()
{
std::set<int> set;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int a;
scanf("%d", &a);
set.insert(a);
}
int m;
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
int a;
scanf("%d", &a);
printf("%d ", set.find(a) != set.end() ? 1 : 0);
}
} | true |
2e2347fe28f82732afcf1ecf5c2189136ba948d8 | C++ | AlexHang/DSA | /HW4/Ex2/Queue.h | UTF-8 | 1,075 | 3.3125 | 3 | [] | no_license | #define NMAX 5
#include <stdio.h>
class Queue {
private:
Message queueArray[NMAX];
int head, tail, size;
public:
void enqueue(Message x) {
if (size == NMAX) {
fprintf(stderr, "Error 101 - The queue is full!\n");
return;
}
queueArray[tail] = x;
tail = (tail + 1) % NMAX;
size++;
}
Message dequeue() {
if (isEmpty()) {
fprintf(stderr, "Error 102 - The queue is empty!\n");
return Message();
}
Message x = queueArray[head];
head = (head + 1) % NMAX;
size--;
return x;
}
Message peek() {
if (isEmpty()) {
fprintf(stderr, "Error 103 - The queue is empty!\n");
Message x;
return x;
}
return queueArray[head];
}
int isEmpty() {
return (size == 0);
}
Queue() {
head = tail = size = 0;
}
};
| true |
0d90321549f46888f8107acd0c856ade3c8ac5df | C++ | borjafdezgauna/DSG | /2013/JuegoDSG/src/MaterialTexture.cpp | UTF-8 | 1,223 | 2.8125 | 3 | [] | no_license | #include "../inc/MaterialTexture.h"
MaterialTexture::MaterialTexture(void)
{
m_blendu= true;
m_blendv= true;
m_clamp= false;
m_cc= false;
m_mm[0]=0;
m_mm[1]=1;
m_offset[0]=0;
m_offset[1]=0;
m_offset[2]=0;
m_scale[0]=1;
m_scale[1]=1;
m_scale[2]=1;
m_turbulence[0]=0;
m_turbulence[1]=0;
m_turbulence[2]=0;
m_bumpMultiplier=-1;
m_textureId = 0;
}
MaterialTexture::MaterialTexture(bool blendu,bool blendv,float bumpMultiplier,bool cc,bool clamp,int mm[2],int o[3],int s[3],int t[3],int texres,std::string filename)
{
m_blendu=blendu;
m_blendv=blendv;
m_bumpMultiplier=bumpMultiplier;
m_cc=cc;
m_clamp=clamp;
memcpy(m_mm,mm,2);
memcpy(m_offset,o,3);
memcpy(m_scale,s,3);
memcpy(m_turbulence,t,3);
m_resolution=texres;
m_filename=filename;
}
void MaterialTexture::loadTexture()
{
char textureName[256];
if(m_filename!=""){
sprintf_s(textureName,256,"texturas/%s",m_filename.c_str());
m_textureId= SOIL_load_OGL_texture( textureName,SOIL_LOAD_RGBA,0,SOIL_FLAG_INVERT_Y);
if(m_textureId==0){
throw TextureFileNotFound(m_filename);
}
else{
std::cout << "Texture file: " << m_filename << " loaded successfully" << std::endl;
}
}
}
MaterialTexture::~MaterialTexture(void)
{
}
| true |
9b75d4fafc3efc9718f2630c7b766ec707f0f136 | C++ | olokex/bachelors-thesis | /src/anf/formula.hpp | UTF-8 | 954 | 2.765625 | 3 | [] | no_license | /**
* Subject: Bachelor's thesis
* Author: Adam Sedlacek | xsedla1e@vutbr.cz
* Year: 2021
* Description:
* Formula's header file.
*
*/
#ifndef FORMULA_H
#define FORMULA_H
#include "../reference_bits.hpp"
#include "parameters.hpp"
#include "literal.hpp"
#include <vector>
class Formula {
public:
unsigned int fitness = UINT_MAX;
Formula(const int term_count, const unsigned int arity, const ReferenceBits &reference_bits);
void print_circuit(const int inputs_count);
void print_circuit_ascii_only();
void print_bits(const int term_count, const int inputs_count);
void mutate(const Parameters ¶meters, const ReferenceBits &reference_bits);
void calculate_fitness(const ReferenceBits &reference_bits, const int idx_out);
std::vector<std::vector<int>> non_zeros;
std::vector<Literal> literals;
private:
Bitset evaluate_term(const int bits_count, const int input_count, const int start);
};
#endif /* FORMULA_H */ | true |
930dfbce401f6d327e0c4161ce24b873c297ef43 | C++ | SaricZarko/Data-Flow-Machine | /Token.h | UTF-8 | 1,299 | 3.078125 | 3 | [] | no_license | #ifndef _TOKEN_H
#define _TOKEN_H
#include<string>
#include<vector>
#include"Exception.h"
using namespace std;
class Operator;
class Token
{
public:
Token() :name_(""), operation_(nullptr), value_(0.0), timeDelay_(0), id_(""), function_(""), startTime_(0),
endTime_(0){}
string getName() { return this->name_; }
void setName(string name) { this->name_ = name; }
Operator* getOperator() { return this->operation_; }
void setOperator(Operator* op) { this->operation_ = op; }
void setValue(double val) { this->value_ = val; }
double getValue() { return this->value_; }
void setOperands(string nam) { this->operands_.push_back(nam); };
vector<string>getOperands() { return this->operands_; }
void WriteInOperands(int k, string s) { this->operands_[k] = s; }
void setTimeDel(int del) { this->timeDelay_.push_back(del); }
vector<int> getTimeDel() { return this->timeDelay_; }
string getId() { return this->id_; }
void setId(string id) { this->id_ = id; }
string getFunction() { return this->function_; }
void setFunction(string fun) { this->function_ = fun; }
private:
friend class Machine;
string name_;
Operator* operation_;
double value_;
vector<string> operands_;
vector<int> timeDelay_;
string id_;
string function_;
int startTime_;
int endTime_;
};
#endif // !_TOKEN_H
| true |
45a1b70b521c6db7563a408cfece5b2fcf707b7e | C++ | Asad51/Leetcode-Problem-Solving | /653. Two Sum IV - Input is a BST.cpp | UTF-8 | 871 | 3.15625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
bool isFound;
TreeNode *head;
map<int, int> mp;
public:
void findNum(TreeNode *root, int target)
{
if (!root || isFound)
return;
if (mp[target - root->val])
{
isFound = true;
return;
}
mp.insert(make_pair(root->val, 1));
findNum(root->left, target);
if (mp[target - root->val])
{
isFound = true;
return;
}
findNum(root->right, target);
}
bool findTarget(TreeNode *root, int k)
{
isFound = false;
head = root;
findNum(root, k);
return isFound;
}
};
| true |
f153ec11433088266d20cf6229b95043028de804 | C++ | PSJ0724/C-Samples | /90.구조체와 함수/main.cpp | WINDOWS-1252 | 337 | 2.90625 | 3 | [] | no_license | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct phone {
char n[20];
int p;
}PHONE;
int show(PHONE ph) {
printf("%s,", ph.n);
printf("%d", ph.p);
}
int main(int argc, char** argv) {
PHONE ph={"Ʈ", 2000};
show(ph);
return 0;
}
| true |
50e5a68f8570533b68d4edba8405fdb67979b1d3 | C++ | gustiir/Degree-Project | /Asteroids/Asteroids/Asteroids/Engine.cpp | UTF-8 | 875 | 2.59375 | 3 | [] | no_license | #include "SDL2\SDL.h"
#include <cassert>
#include <iostream>
#include "Engine.h"
static SDL_Window* Window;
static SDL_Renderer* Renderer;
static bool IsOpen = false;
void engineInitialization()
{
SDL_Init(SDL_INIT_VIDEO);
Window = SDL_CreateWindow("Asteroids", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED);
if (!Renderer)
{
std::cout << SDL_Error << std::endl;
}
IsOpen = true;
}
void engineUpdate()
{
SDL_RenderPresent(Renderer);
engineClear();
//delay ?
}
void engineClose()
{
IsOpen = false;
}
void engineDestroy()
{
SDL_DestroyRenderer(Renderer);
SDL_DestroyWindow(Window);
Renderer = nullptr;
Window = nullptr;
SDL_Quit();
}
void engineClear()
{
SDL_SetRenderDrawColor(Renderer, 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(Renderer);
}
| true |
dac46230f914e439346b36a22db461f1a4665059 | C++ | zhangsht/cplusplus | /C++程序练习/第八周/quick_sort.cpp | UTF-8 | 958 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
template <class Record>
void quick_sort(Record* startPointer, Record* endPointer) {
if (startPointer < endPointer) {
Record *bottom = startPointer, *top = endPointer - 1;
Record privot = *startPointer;
while (bottom < top) {
while (bottom < top && *top > privot) top--;
if (bottom < top) {
*bottom = *top;
bottom++;
}
while (bottom < top && *bottom < privot) bottom++;
if (bottom < top) {
*top = *bottom;
top--;
}
}
*bottom = privot;
quick_sort(startPointer, bottom);
quick_sort(bottom + 1, endPointer);
}
}
//int main() {
// int a[12] = {6 , 8 , 7, -1, 2,10, 988, 5, 3, 1, 4, 2};
// quick_sort(a, a + 12);
// for (int i = 0; i < 12; i++) cout << a[i] << ' ';
//}
| true |
5a6e4f248459e3286e39d14446e2083f3dcf8a0e | C++ | TzashiNorpu/Algorithm | /Clion/zero/1400_1600/maxArea_1465.cpp | UTF-8 | 1,015 | 2.828125 | 3 | [
"MIT"
] | permissive | //
// Created by TzashiNorpu on 2023/6/28.
//
#include "../header/header.h"
using namespace zero;
int Solution::maxArea(int h, int w, vector<int> &horizontalCuts, vector<int> &verticalCuts) {
//
vector<int> heights, widths;
int hCuts = horizontalCuts.size();
std::sort(horizontalCuts.begin(), horizontalCuts.end());
heights.push_back(horizontalCuts[0]);
for (int i = 1; i < hCuts; ++i) {
heights.push_back(horizontalCuts[i] - horizontalCuts[i - 1]);
}
heights.push_back(h - horizontalCuts[hCuts - 1]);
int maxHeight = *std::max_element(heights.begin(), heights.end());
int vCuts = verticalCuts.size();
std::sort(verticalCuts.begin(), verticalCuts.end());
widths.push_back(verticalCuts[0]);
for (int i = 1; i < vCuts; ++i) {
widths.push_back(verticalCuts[i] - verticalCuts[i - 1]);
}
widths.push_back(w - verticalCuts[vCuts - 1]);
int maxWidth = *std::max_element(widths.begin(), widths.end());
int MOD = 1000000007;
return ((long long) maxHeight * maxWidth) % MOD;
} | true |
7e2a98c96a474732a186576adebc6049c1b2270d | C++ | xingkungao/LeetCode_solutions | /n_queens_II.cpp | UTF-8 | 1,222 | 2.875 | 3 | [] | no_license | /*************************************************************************
> File Name: n_queens_II.cpp
> Author: lax
> Mail: xingkungao@gmail.com
> Created Time: Wed 10 Dec 2014 09:38:24 PM CST
************************************************************************/
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <cassert>
using namespace std;
class Solution { public:
int totalNQueens(int n) {
int *p = new int[n];
int *a = new int[n];
int *b = new int[2 * n];
int *c = new int[2 * n];
memset(a, 0, sizeof(int) * n);
memset(b, 0, sizeof(int) * 2 * n);
memset(c, 0, sizeof(int) * 2 * n);
int cnt = 0;
solveNQueensRecursive(n, a, b, c, 0, cnt);
return cnt;
}
void solveNQueensRecursive(int n, int *a, int *b, int *c, int l, int &cnt) {
if (l == n && n) {
cnt++;
return;
}
for (int i = 0; i < n; i++) {
if (!a[i] && !b[l + i] && !c[(n + i - l)]) {
a[i] = b[l+i] = c[(n+i-l)] = 1;
solveNQueensRecursive(n, a, b, c, l+1, cnt);
a[i] = b[l+i] = c[(n+i-l)] = 0;
}
}
}
void test() {
int n;
while (1)
{
cin >> n;
cout << totalNQueens(n) << endl;
}
}
};
int main() {
Solution s;
s.test();
}
| true |
5ddf8f1626b1c554b7f277e7ca31f960877e0ebf | C++ | Hiker-Xu/nowcoder_algorithm | /primary_class/practice/Code_03_StackAndQueueConvert.cpp | UTF-8 | 1,605 | 3.703125 | 4 | [] | no_license | // 如何仅用队列结构实现栈结构?
// 如何仅用栈结构实现队列结构?
# include <stdio.h>
# include <iostream>
# include <stack>
# include <queue>
using namespace std;
class twoStackQueue{
public:
void push(int num){
stackPush.push(num);
}
bool empty(){
return (stackPop.empty() && stackPush.empty())?true:false;
}
void pop(){
if(empty()){
return;
}
if(stackPop.empty()){
decant();
}
stackPop.pop();
}
int front(){
if(empty()){
return NULL;
}
if(stackPop.empty()){
decant();
}
stackPop.top();
}
int back(){
if(empty()){
return NULL;
}
if(!stackPush.empty()){
return stackPush.top();
}
else{
swap(stackPush, stackPop);
decant();
int t = stackPop.top();
swap(stackPush, stackPop);
}
}
void decant(){
while(!stackPush.empty()){
stackPop.push(stackPush.top());
stackPush.pop();
}
}
private:
stack<int> stackPush;
stack<int> stackPop;
};
class myStack{
public:
bool empty(){
return major.empty();
}
void push(int num){
major.push(num);
}
void pop(){
if(empty())
return;
while(major.size()!=1){
help.push(major.front());
major.pop();
}
major.pop();
major.swap(help);
}
int top(){
if(empty())
return;
return major.back();
}
private:
queue<int> major;
queue<int> help;
}; | true |
0164ab9c40ade7ad0b0e61637447a61adc17d205 | C++ | asdlei99/Play-Advent-of-Code | /2019/Day-03- Crossed-Wires/cpp-2019-03/main_part_1.cpp | UTF-8 | 1,690 | 3.046875 | 3 | [] | no_license | /// Source : https://adventofcode.com/2019/day/3
/// Author : liuyubobobo
/// Time : 2020-12-03
#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>
#include <set>
#include <unordered_map>
using namespace std;
class Solution{
public:
int solve(const string& s1, const string& s2){
set<pair<int, int>> set1 = go(s1);
set<pair<int, int>> set2 = go(s2);
int res = INT_MAX;
for(const pair<int, int>& p: set2)
if(set1.count(p)){
int d = abs(p.first) + abs(p.second);
if(d && d < res) res = d;
}
return res;
}
private:
set<pair<int, int>> go(const string& s){
unordered_map<char, int> dx = {{'R', 1}, {'L', -1}, {'U', 0}, {'D', 0}};
unordered_map<char, int> dy = {{'R', 0}, {'L', 0}, {'U', 1}, {'D', -1}};
set<pair<int, int>> res;
int x = 0, y = 0;
res.insert({x, y});
for(int start = 0, i = start + 1; i <= s.size(); i ++)
if(i == s.size() || s[i] == ','){
char d = s[start];
int step = atoi(s.substr(start + 1, i - (start + 1)).c_str());
for(int k = 0; k < step; k ++){
x += dx[d], y += dy[d];
res.insert({x, y});
}
start = i + 1;
i = start;
}
return res;
}
};
int main() {
ifstream input;
// input.open("../../input_test.txt");
input.open("../../input.txt");
assert(input.is_open());
string s1, s2;
input >> s1 >> s2;
cout << Solution().solve(s1, s2) << endl;
input.close();
return 0;
}
| true |
b59b95dc68556566344d88e03be71faa1f4dd165 | C++ | carljwmeisner/rc2016-machine-learning | /logisticRegression/include/data.h | UTF-8 | 1,113 | 3.078125 | 3 | [] | no_license | #ifndef data_hpp
#define data_hpp
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
typedef std::vector <double> record_t;
typedef std::vector <record_t> data_t;
class Data
{
public:
std::vector<std::vector<double> > dataSet;
std::vector< std::vector<double> > getQuestions(); //this will return a vector containing all of the questions
std::vector<double> getQuestion(int ARG); //this will return a vector, but only containing one entry of questions
std::vector< std::vector<double> > getAnswers(); //similar to question, but with answers
std::vector<double> getAnswer(int ARG); //see above
std::vector< std::vector<double> > getBoth(); //gets everything
bool readInFile(std::string TARGET); //read in a file from location given by TARGET returning true indicates everything worked
bool acceptEntry(std::vector<double>); //sticks another entry into this data set
Data(); //simply creates the vector o' vectors
Data(std::string TARGET); //fills the dataSet with info from the file at TARGET - TARGET needs to be a .csv file right meow
};
#endif /* data_hpp */ | true |
b390b9a0fc5923bf854be3a15169e4a9e715c700 | C++ | fatimamujahid07/mywork | /q6.cpp | UTF-8 | 427 | 2.71875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int arr[]={1,2,4,6,3,7,8};
int i,k=0,n,j,n1,n2;
n=sizeof(arr)/sizeof(arr[0]);
cout<<endl;
//ORIGINAL ARRAY
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
n1=arr[0];
n2=arr[i-1];
for(i=0;i<n;i++)
{
n1++;
for(j=i+1;j<n;j++)
{
if(n1==arr[j])
{
break;
}
}
if(n1==arr[j]);
else
{
cout<<n1;
break;
}
}
return 0;
}
| true |
907dedecbe0efaa983dde75bc65cfbedd6aabf32 | C++ | KevinEsh/linear-algebra-api | /LinearAlgebra_def.h | UTF-8 | 38,427 | 3.078125 | 3 | [
"MIT"
] | permissive | using namespace std;
LinearAlgebra::LinearAlgebra(int n1, int n2)
{
N1 = n1, N2 = n2, N3 = n2;
Matrix = nullptr, inp_vector = nullptr, out_vector = nullptr;
//Alocacion de memoria.
try{
Matrix = new double[N1*N2];
inp_vector = new double[N3];
out_vector = (double*)malloc(N3*sizeof(double));
}
catch(bad_alloc&){
cout<<"Problemas en la alocación de memoria. Todas las funciones serán desactivadas"<<endl;
solve_method =-1;
return;
}
solve_method = 1; //se resolverá el sistema con elim_gaussiana por defecto.
cache["diag_dom"] = 0; // 0: aun no se sabe, 1: false, 2: true
}
LinearAlgebra::~LinearAlgebra()
{
delete[] Matrix;
delete[] inp_vector;
delete[] out_vector;
delete[] Q;
delete[] R;
for (int i=0; i<num_eigens; i++) delete[] eigenvectors[i];
}
void LinearAlgebra::set_Matrix(string file_name, bool header=false){
ifstream inp_file (file_name);
string line;
double value;
int i=0, j=0;
regex pattern_of_numbers("[+-]*[0-9]+\\.?[0-9]*");
if (!inp_file.is_open()){
cout<<"Archivo "<<file_name<<" no encontrado. Intente de nuevo"<<endl;
return;
}
if (header){
getline(inp_file, line);
}
while(getline(inp_file, line)){
regex_iterator<string::iterator> numbers ( line.begin(), line.end(), pattern_of_numbers);
regex_iterator<string::iterator> endline;
while (numbers!=endline){
istringstream string_to_double(numbers->str());
string_to_double >> value;
Matrix[i*N2+j] = value;
j++;
++numbers;
}
i++;
j=0;
}
inp_file.close();
}
void LinearAlgebra::set_inp_vector(string file_name, bool header=false){
ifstream inp_file(file_name);
string line;
double value;
int i=0;
regex pattern_of_numbers("[+-]*[0-9]+\\.?[0-9]*");
if (!inp_file.is_open()){
cout<<"Archivo "<<file_name<<" no encontrado. Intente de nuevo"<<endl;
return;
}
if (header){
getline(inp_file, line);
}
while(getline(inp_file, line)){
regex_iterator<string::iterator> numbers ( line.begin(), line.end(), pattern_of_numbers);
regex_iterator<string::iterator> endline;
istringstream string_to_double(numbers->str());
string_to_double >> value;
inp_vector[i] = value;
i++;
}
inp_file.close();
}
void LinearAlgebra::set_inp_vector(double* vector, int size){
if (N3 < size){
free(out_vector);
delete[] inp_vector;
N3 = size;
inp_vector = new double[N3];
}
for (int i=0; i<N3; i++) inp_vector[i] = vector[i]; //Lo pasamos a la memoria heap
}
void LinearAlgebra::set_out_vector(double* vector, int n3){
if (N3 < n3){
delete[] out_vector;
N3 = n3;
out_vector = new double[N3];
}
for (int i=0; i<N3; i++) out_vector[i] = vector[i]; //Lo pasamos a la memoria heap
}
void LinearAlgebra::solve_diag(){
if (N1!=N2){
printf("Matriz no es cuadrada, en cambio dimension (%d,%d) fue dada",N1,N2);
return;
}
else if (N1!=N3){
printf("Matriz (%d,%d) y vector (%d) no son compatibles",N1,N2,N3);
return;
}
double deno;
for (int i=0; i<N1; i++){
deno = Matrix[i*N2+i];
if (deno == 0.0){
cout<<"El sistema de ecuaciones no tiene solucion, columna de zeros fue encontrada"<<endl;
return;
}
out_vector[i] = inp_vector[i]/deno;
}
}
void LinearAlgebra::solve_triang_sup(int diag = 0)
{
if (N1!=N2){
printf("Matriz no es cuadrada, en cambio dimension (%d,%d) fue dada",N1,N2);
return;
}
else if (N1!=N3){
printf("Matriz (%d,%d) y vector (%d) no son compatibles",N1,N2,N3);
return;
}
double sum, deno;
//Reduccion hacia atras
if (diag==0) deno = Matrix[(N1-1)*N2 + N1-1];
else deno = 1;
if (deno == 0.0){
cout<<"El sistema de ecuaciones no tiene solucion, columna de zeros fue encontrada"<<endl;
return;
}
out_vector[N1-1] = inp_vector[N1-1]/deno;
for (int i = N1-2; i >=0 ; i--){
if (diag==0) deno = Matrix[i*N2+i];
else deno=1;
if (deno == 0.0){
cout<<"El sistema de ecuaciones no tiene solucion, columna de zeros fue encontrada"<<endl;
return;
}
sum=0.0;
for (int j = i+1; j < N2; j++){
sum += Matrix[i*N2 + j]*out_vector[j];
}
out_vector[i] = (inp_vector[i] - sum)/deno;
}
}
void LinearAlgebra::elim_gausiana()
{
if (N1!=N2){
printf("Matriz no es cuadrada, en cambio dimension (%d,%d) fue dada",N1,N2);
return;
}
if (N1!=N3) {
printf("Numero de filas de matriz y vector deben de ser iguales. En cambio (%d,%d) y (%d) fue dado", N1,N2,N3);
return;
}
double deno;
double nume;
for (int k = 0; k < N1-1;k++){
pivot(k);
deno = Matrix[k*N2+k];
if (deno == 0.0){
if (!pivot(k)){//si no encontro un pivote diferente de cero, regresa
cout<<"No se puede resolver el sistema de ecuaciones"<<endl;
return;
}
deno = Matrix[k*N2+k]; //denominador actualizado
}
for (int i = k+1; i < N1; i++){
nume = Matrix[i*N2+k];
for (int j = k; j < N2; j++){
Matrix[i*N2+j] -= (nume*Matrix[k*N2+j])/deno;
}
inp_vector[i] -= (nume*inp_vector[k])/deno;
}
}
solve_triang_sup();
}
void LinearAlgebra::solve_triang_inf(int diag = 0)
{
if (N1!=N2){
printf("Matriz no es cuadrada, en cambio una de dimension (%d,%d) fue dada",N1,N2);
return;
}
else if (N1!=N3){
printf("Matriz A (%d,%d) y vector b (%d) no son compatibles",N1,N2,N3);
return;
}
double sum, deno;
//Reduccion hacia atras
if (diag==0) deno = Matrix[0];
else deno = 1;
if (deno == 0.0){
cout<<"El sistema de ecuaciones no tiene solucion, columna de zeros fue encontrada"<<endl;
return;
}
out_vector[0] = inp_vector[0]/deno;
for (int i = 1; i < N1; i++){
if (diag==0) deno = Matrix[i*N2+i];
else diag = 1;
if (deno == 0.0){
cout<<"El sistema de ecuaciones no tiene solucion, columna de zeros fue encontrada"<<endl;
return;
}
sum = 0.0;
for (int j = 0; j < i; j++){
sum += Matrix[i*N2+j]*out_vector[j];
}
out_vector[i] = (inp_vector[i] - sum)/deno;
}
}
void LinearAlgebra::print_array()
{
for (int i=0; i<N1; i++){
cout<<"[";
for (int j=0; j<N2; j++){
cout<<Matrix[i*N2+j]<<", ";
}
cout<<"]"<<endl;
}
cout<<endl;
}
void LinearAlgebra::print_inp_vector()
{
cout<<"[";
for (int i=0; i<N3; i++) cout<<inp_vector[i]<<", ";
cout<<"]"<<endl<<endl;
}
void LinearAlgebra::print_out_vector()
{
cout<<"[";
for (int i=0; i<N3; i++) cout<<out_vector[i]<<", ";
cout<<"]"<<endl<<endl;
};
void LinearAlgebra::change_rows(int row1, int row2){
double aux;
for (int k = 0; k < N2; k++){
aux = Matrix[row1*N2+k];
Matrix[row1*N2+k] = Matrix[row2*N2+k];
Matrix[row2*N2+k] = aux;
aux = inp_vector[row1];
inp_vector[row1] = inp_vector[row2];
inp_vector[row2] = aux;
}
}
bool LinearAlgebra::pivot(int row1){
double max = 0, elem;
int row2, zeros=0;
for (int i = row1; i<N1; i++){
elem = abs(Matrix[i*N2+row1]); //barre la fila desde la diagonal
if (elem == 0.0) zeros++;
else if (elem > max){
max = elem;
row2 = i;
}
}
if (N1-row1==zeros){
cout<<"Matriz singular, fila de zeros fue encontrada."<<endl;
return false; //no hay fila sustituible
}
change_rows(row1,row2);
return true;
}
double LinearAlgebra::cuadratic_error(double* vector1, int n1, double* vector2, int n2){
if (n1!=n2){
printf("Vectores no son de la misma dimension, (%d) y (%d) fueron dados\n",n1,n2);
return 0.0;
}
double error=0;
for (int i=0; i<n1; i++) error+= pow(vector1[i]-vector2[i],2);
return error;
}
double LinearAlgebra::relative_error(double* vector1, int n1, double* vector2, int n2){
if (n1!=n2){
printf("Vectores no son de la misma dimension, (%d) y (%d) fueron dados\n",n1,n2);
return 0.0;
}
double error=0;
for (int i=0; i<n1; i++) error+= abs(vector1[i]-vector2[i])/abs(vector1[i]);
return error;
}
double LinearAlgebra::L1_norm(double* inp_vector1, int n1){
double norm=0;
for (int i=0; i<n1; i++){
norm+= abs(inp_vector[i]);
}
return norm;
}
double LinearAlgebra::Linf_norm(double* inp_vector1, int n1){
double norm = 0, elem;
for (int i=0; i<n1; i++){
elem = abs(inp_vector[i]);
if (elem > norm){
norm = elem;
}
}
return norm;
}
void LinearAlgebra::LU_factorization(){
double sum, deno;
for(int k=0; k<N1; k++){
for (int j=k; j<N1; j++){
sum = 0;
for (int s=0; s<=k-1; s++){
sum += Matrix[k*N2+s]*Matrix[s*N2+j]; //es lo mismo que L[k,s]*U[s,j]
}
Matrix[k*N2+j] -= sum; // es lo mismo que U[k,j]=Matrix[k,j]-sum
}
deno = Matrix[k*N2+k];
if (deno==0.0){ //U[k,k]==0
if(!pivot(k)){
cout<<"No existe factorizacion LU"<<endl;
return;
}
deno = Matrix[k*N2+k];
}
for (int i=k+1; i<N1; i++){
sum =0;
for (int s=0; s<=k-1; s++){
sum+= Matrix[i*N2+s]*Matrix[s*N2+k]; //sum = L[i,k]*U[s,k]
}
Matrix[i*N2+k] = (Matrix[i*N2+k]- sum)/deno; //L[i,k] = (Matrix[i,k]-sum)/U[k,k]
}
}
solve_method = 2;
}
void LinearAlgebra::LDL_factorization(){
double sum;
// Elementos de la diagonal Matriz[i,i] -> D[i,i]
for(int j=0; j<N1; j++){
sum = 0.0;
for (int s=0; s<=j-1; s++){
sum += Matrix[s*N2+s] * Matrix[j*N2+s] * Matrix[j*N2+s]; // sum += D[s,s]*L[j,s]^2
}
Matrix[j*N2+j] -= sum; //D[j,j] = Matrix[j,j]-sum
if (Matrix[j*N2+j]==0){ //U[k,k]==0
cout<<"No existe factorizacion LDL"<<endl;
return;
}
//Elementos fuera de la diagonal, matriz simetrica Matrix[i,j]== Matrix[j,i] -> L[i,j]==L[j,i]
for(int i = j+1; i<N1; i++){
sum = 0.0;
for (int s=0; s<=j-1; s++){
sum += Matrix[s*N2+s] * Matrix[i*N2+s] * Matrix[j*N2+s]; //D[s,s]*L[i,s]*L[j,s]
}
Matrix[i*N2+j] = (Matrix[i*N2+j]-sum)/Matrix[j*N2+j]; //L[i,j] = (Matrix[i,j]-sum)/D[j,j]
Matrix[j*N2+i] = Matrix[i*N2+j]; //L=L^T
}
}
solve_method = 3;
}
void LinearAlgebra::solve(){
double* new_vec = new double[N3]; //para conservar inp_intacto,
//se debe de crear un vector auxiliar que guarde su informacion
//hasta que la solucion del sistema quede hecha en new_vec. Despues
//new_vector será la direccion de memorio de out_vector miestras que el viejo será eliminado
switch (solve_method){
case 1: //Eliminacion Gausiana
elim_gausiana();
break;
case 2: //Factorizacion LU
solve_triang_inf(1);
change_ptr(&inp_vector, &out_vector); //inp->out out->inp //("la direccion de * esta en la variable *")
change_ptr(&new_vec, &out_vector); //inp->new, new->out**
solve_triang_sup();
change_ptr(&new_vec,&inp_vector); //inp->inp** out->new**
break;
case 3: //Factorizacion LDL
solve_triang_inf(1);
change_ptr(&inp_vector, &out_vector); //inp->out out->inp ("la direccion de * esta en la variable *")
change_ptr(&new_vec, &out_vector); //inp->new, new->out
solve_diag();
change_ptr(&inp_vector, &out_vector); //new->inp out->out**
solve_triang_sup(1);
change_ptr(&new_vec, &inp_vector); //inp->inp** new->new**
break;
case 4:
solve_tridiagonal_system();
break;
case 5: //Gradiente Conjugado
conjugated_gradient(1000, 1e-8);
break;
case 6: //Simple multiplicacion de la matriz inversa
solve_for_inv_method();
break;
}
delete[] new_vec; //adios, gracias por ayudar :)
}
void LinearAlgebra::sum_rows(double* ext_vector){
double sum;
for (int i=0; i<N1; i++){
sum=0;
for(int j=0; j<N2; j++) sum+= Matrix[i*N2+j];
ext_vector[i]=sum;
}
}
void LinearAlgebra::sum_colms(double* ext_vector){
double sum;
for (int j=0; j<N2; j++){
sum = 0;
for(int i=0; i<N1; i++) sum+= Matrix[i*N2+j];
ext_vector[j]=sum;
}
}
bool LinearAlgebra::is_diag_dom(){
if(cache["diag_dom"] == 1) return false;
if(cache["diag_dom"] == 2) return true;
double sum;
for (int i=0; i<N1; i++){
sum=0;
for(int j=0; j<N2; j++) sum+= Matrix[i*N2+j];
if (abs(Matrix[i*N2+i])<abs(sum-Matrix[i*N2+i])){
cache["diag_dom"] = 1;
return false;
}
}
cache["diag_dom"] = 2;
return true;
}
void LinearAlgebra::jacobbi(int max_iter = 1000, double epsilon = 0.001){
double sum, diag, error;
double* temp = new double[N3];
if (!is_diag_dom()) cout<<"Matriz no es diagonalmente dominante, es posible que el metodo de jacobbi no converja"<<endl;
sum_rows(out_vector); //primer vector de iteracion, igual a la suma de las filas de la matrix dada
for (int iter = 0; iter < max_iter; iter++){
for (int i =0; i<N1; i++){
sum = 0;
diag = Matrix[i*N2+i];
if (diag==0){
cout<<"Metodo jacobbi no resoluble. Cero en diagonal"<<endl;
delete[] temp;
return;
}
for (int j=0; j<N2; j++) sum+=Matrix[i*N2+j]*out_vector[j];
sum-= diag*out_vector[i];
temp[i] = (inp_vector[i] -sum)/diag;
}
error = cuadratic_error(out_vector,N3, temp,N3);
//intercambio de punteros
change_ptr(&temp, &out_vector);
if(error < epsilon){
delete[] temp;
return;
}
}
cout<<"Metodo de jacobbi, no convergio en "<<max_iter<<" iteraciones"<<endl;
}
void LinearAlgebra::gauss_seidel(int max_iter = 1000, double epsilon = 0.001){
double sum1, sum2, diag, error;
double* temp = new double[N3];
if (!is_diag_dom()) cout<<"Matriz no es diagonalmente dominante, es posible que el metodo gauss seidel no converja"<<endl;
sum_rows(out_vector); //primer vector de iteracion, igual a la suma de las filas de la matrix dada
for (int iter = 0; iter < max_iter; iter++){
for (int i =0; i<N1; i++){
sum1 = 0;
sum2 = 0;
diag = Matrix[i*N2+i];
if (diag==0){
cout<<"Metodo gauss-seidel no resoluble. Cero en diagonal"<<endl;
delete[] temp;
return;
}
for (int j=0; j<i; j++) sum1+=Matrix[i*N2+j]*temp[j];
for (int j=i+1; j<N2; j++) sum2+= Matrix[i*N2+j]*out_vector[j];
temp[i] = (inp_vector[i]-sum1-sum2)/diag;
}
error = cuadratic_error(out_vector,N3,temp,N3);
//intercambio de punteros
change_ptr(&temp, &out_vector);
if(error < epsilon){
delete[] temp;
return;
}
}
cout<<"Metodo de gauss-seidel, no convergio en "<<max_iter<<" iteraciones"<<endl;
delete[] temp;
}
void LinearAlgebra::set_Matrix_as_tridiagonal(double* vector1, double* vector2, double* vector3){
down_diagonal = vector1;
diagonal = vector2;
up_diagonal = vector3;
solve_method = 4;
}
void LinearAlgebra::solve_tridiagonal_system(){
// La matriz tiene que ser necesariamente simetrica para que el sistema funcione
double* L = new double[N3];
double* D = new double[N3];
double* auxptr = nullptr; //puntero auxiliar
//Factorizacon LDL
L[0] = 0, D[0] = diagonal[0];
for(int i=1; i<N3; i++){
L[i] = up_diagonal[i-1]/D[i-1];
D[i] = diagonal[i] - D[i-1] * pow(L[i],2);
}
//Resolviendo el sistema tridiagonal
//Triangular Inferior
out_vector[0]=0;
for (int i=0; i<N3; i++) out_vector[i] = inp_vector[i] - L[i]*out_vector[i];
auxptr = inp_vector, inp_vector = out_vector, out_vector = auxptr;
//Diagonal
for(int i=0; i<N3; i++) out_vector[i] = inp_vector[i]/D[i];
auxptr = inp_vector, inp_vector = out_vector, out_vector = auxptr;
//Triangular Superior
out_vector[N3-1] = inp_vector[N3-1];
for (int i=N3-2; i>=0; i--) out_vector[i] = inp_vector[i] - L[i+1]*out_vector[i+1];
delete[] L;
delete[] D;
}
//-----------
void LinearAlgebra::change_ptr(double** ptr1, double** ptr2){
double* aux = nullptr;
aux = *ptr1, *ptr1 = *ptr2, *ptr2 = aux;
return;
}
double LinearAlgebra::dot(double* vector1, double* vector2, int size){
double sum = 0;
for(int i=0; i<size; i++) sum+= vector1[i]*vector2[i];
return sum;
}
double LinearAlgebra::max(double* vector, int size){
double max = 0;
for (int i=0; i<size; i++) if(vector[i]>max) max = vector[i];
return max;
}
double LinearAlgebra::max_abs(double* vector, int size){
double max = 0;
for (int i=0; i<size; i++) if(abs(vector[i])>max) max = abs(vector[i]);
return max;
}
double LinearAlgebra::min(double* vector, int size){
double min;
min = numeric_limits<double>::max();
for (int i=0; i<size; i++) if(vector[i] < min) min = vector[i];
return min;
}
double LinearAlgebra::min_abs(double* vector, int size){
double min;
min = numeric_limits<double>::max();
for (int i=0; i<size; i++) if(abs(vector[i]) < min) min = abs(vector[i]);
return min;
}
void LinearAlgebra::divide_for(double* vector, double scalar, int size){
for(int i = 0; i<size; i++) vector[i]/=scalar;
}
void LinearAlgebra::norm_vec(double* vector, int size){
divide_for(vector, sqrt(dot(vector,vector, size)),size);
}
double* LinearAlgebra::ones(int size){
double* ones_vector= new double[size];
for (int i=0; i < size; i++) ones_vector[i]=1;
return ones_vector;
}
void LinearAlgebra::pow_method(double* temp1, int max_iter = 1000, double epsilon = 0.001){
if (N1!=N2 || N1!= N3) {
cout<<"Matriz no es cuadrada"<<endl;
return;
}
double* aux_ptr = nullptr;
double* temp2 = new double[N3]; //este se convertirá en la nueva allocacion de eigenvector
double lambda1 = 0;
double lambda2 = 0; //inicializar eigenvalores
double sum;
//Metodo de la potencia
for (int iter=0; iter<max_iter; iter++){
for(int i=0; i<N1; i++){
sum = 0;
for (int j=0; j<N2; j++) sum += Matrix[i*N2+j] * temp1[j];
temp2[i]= sum;
}
//lambda2 = dot(temp2, temp2, N3)/dot(temp2, temp1, N3);
lambda2 = temp2[0]/temp1[0];
if (abs(lambda2-lambda1) < epsilon){
eigenvalues.emplace_back(lambda2);
norm_vec(temp2, N3);
eigenvectors.emplace_back(temp2);
num_eigens++;
delete[] temp1;
return;
}
else{
divide_for(temp2, max_abs(temp2, N3), N3);
aux_ptr = temp1, temp1 = temp2, temp2 = aux_ptr; //cambiamos los punteros
lambda1 = lambda2;
}
}
cout<<"Metodo de potencia no convergio. Se retornara eigenvector vacio"<<endl;
eigenvalues.emplace_back(0);
delete[] temp2;
delete[] temp1;
return;
}
void LinearAlgebra::inverse_pow_method(double* temp1, int max_iter = 1000, double epsilon = 0.001){
if (N1!=N2 || N1 != N3) {
cout<<"Matriz no es cuadrada"<<endl;
return;
}
double* aux_ptr = nullptr;
double* temp2 = new double[N3]; //este se convertirá en la nueva allocacion de eigenvector
double lambda1 = 0;
double lambda2 = 0; //inicializar eigenvalores
set_inp_vector(temp1, N3); //lo inicializamos como vector lleno de unos. default case
//Metodo de la potencia inversa
for (int iter=0; iter<max_iter; iter++){
solve(); //solucion en out_vector
//lambda2 = dot(out_vector, inp_vector, N3)/dot(out_vector, out_vector, N3);
lambda2 = inp_vector[0]/out_vector[0];
if ( abs(lambda2-lambda1) < epsilon){
eigenvalues.emplace_back(lambda2);
for (int i=0; i<N3; i++) temp2[i] = out_vector[i]; //copia de la solucion. out_vector se puede usar para otras cosas
norm_vec(temp2, N3);
eigenvectors.emplace_back(temp2);
num_eigens++;
return;
}
else{
divide_for(inp_vector, max_abs(inp_vector,N3), N3);
aux_ptr = inp_vector, inp_vector = out_vector, out_vector = aux_ptr; //cambiamos los punteros
lambda1 = lambda2;
}
}
cout<<"Metodo de potencia inverso no convergio. Se retornará eigenvector vacio"<<endl;
eigenvalues.emplace_back(0);
delete[] temp2;
delete[] temp1;
return;
}
void LinearAlgebra::getall_eigens(string method ="pow_method", int maxiter = 1000){
num_eigens = 0;
double* temp1 = new double[N3];
sum_rows(temp1);//inicializar el eigenvector
divide_for(temp1,max_abs(temp1,N3),N3); //para evitar numeros grandes
if(method=="pow_method") pow_method(temp1);
if(method=="inverse_pow_method") LU_factorization(), inverse_pow_method(temp1);
//if(method=="jacobi") jacobi_eigens(maxiter);
}
void LinearAlgebra::minus_proy(double* vector1, double* vector2, int size){
for(int i=0; i<size; i++) vector1[i]-= dot(vector1, vector2, size);
}
//--------------
void LinearAlgebra::jacobi_eigens(double** Q_eigen, double** P_eigen, bool save_eigens = true, int maxiter = 1000){
double max, angle, ZERO = 1e-8;
int index1, index2;
double* Q_eigenvecs = new double[N1*N2];
double* P_eigenvals = new double[N1*N2];
//Copia de la matriz
for(int i = 0; i <N1; i++){
for (int j = 0; j<N2; j++){
P_eigenvals[i*N2+j] = Matrix[i*N2+j];
Q_eigenvecs[i*N2+j] = 0; //matriz unitaria
}
Q_eigenvecs[i*N2+i] = 1;
}
//METODO DE JACOBI PARA ENCONTRAR EIGENVALORES Y EIGENVECTORES
for(int i=0; i<N1-1; i++){
max = 0;
for(int j = i+1; j<N2; j++){ // poner toda la fila i por debajo de ZERO
if (max < abs(P_eigenvals[i*N2+j])){ //encontramos el maximo absoluto
max = abs(P_eigenvals[i*N2+j]);
index1 = i, index2 = j; //indice fila, indice columna
}
}
if (max > ZERO){ //Rotacion
rotation_jacobi_eigens(P_eigenvals,Q_eigenvecs,N1, N2, index1, index2);
}
}
//Refinamiento de los eigenvectores y eigevalores (debido a que poner ceros en las otras filas puede quitar los ceros de otras filas)
for(int iter = 0; iter < maxiter; iter++){ //damos un numero maxiter de intentos
max = max_abs_Mat(P_eigenvals, N1, N2, index1, index2, true, false); //encuentra el maximo de la matriz simetrica y no consideres la diagonal
if(max > ZERO){
rotation_jacobi_eigens(P_eigenvals, Q_eigenvecs, N1, N2, index1, index2);
}
else { //Se ha conseguido la matriz diagonal con margen de error menor a ZERO
//Gaurdamos los eigenvalores y eivectores en otra ubicacion accesible para el usuario
if (save_eigens){
double* aux;
for(int j = 0; j < N2; j++){
aux = new double[N1];
for (int i = 0; i<N1; i++){
aux[j] = Q_eigenvecs[i*N2+j];
}
eigenvectors.push_back(aux);
eigenvalues.push_back(P_eigenvals[j*N2+j]);
}
num_eigens = N2;
delete[] P_eigenvals;
delete[] Q_eigenvecs;
return;
}
else{
*Q_eigen = Q_eigenvecs;
*P_eigen = P_eigenvals;
return;
}
}
}
cout<<"No se ha conseguido la diagonalizacion completa de la matriz con el metodo de Jacobi en "<<maxiter<<" iteraciones. Se retornara vector y eigenvalore vacios"<<endl;
delete[] Q_eigenvecs;
delete[] P_eigenvals;
}
void LinearAlgebra::rotation_jacobi_eigens(double* matrix, double* Rmatrix, int n1, int n2, int index1, int index2){
double angle = 0.5*atan2( 2*matrix[index1*n2+index2], matrix[index1*n2+index1]-matrix[index2*n2+index2]);
double* a = new double[n1];
//Actualizacion de la matriz de eigenvectores (Producto matricial por la nueva matriz de rotación)
//copia del vector
for (int i =0; i<n1; i++) a[i] = Rmatrix[i*n2+index1];
for (int k = 0; k <n2; k++){
Rmatrix[k*n2+index1] = Rmatrix[k*n2+index1]*cos(angle)+Rmatrix[k*n2+index2]*sin(angle);
Rmatrix[k*n2+index2] = Rmatrix[k*n2+index2]*cos(angle)-a[k]*sin(angle);
}
//Primera rotacion
for (int i =0; i<n1; i++) a[i] = matrix[i*n2+index1];
for (int k = 0; k <n1; k++){
matrix[k*n2+index1] = matrix[k*n2+index1]*cos(angle)+matrix[k*n2+index2]*sin(angle);
matrix[k*n2+index2] = matrix[k*n2+index2]*cos(angle)-a[k]*sin(angle);
}
//Segunda rotacion
for (int i =0; i<n2; i++) a[i] = matrix[index1*n2+i];
for(int k = 0; k<n2; k++){
matrix[index1*n2+k] = matrix[index1*n2+k]*cos(angle)+matrix[index2*n2+k]*sin(angle);
matrix[index2*n2+k] = matrix[index2*n2+k]*cos(angle)-a[k]*sin(angle);
}
delete[] a;
}
double LinearAlgebra::max_abs_Mat(const double *matrix, int n1, int n2, int& index1, int &index2, bool simetric = false, bool diag = true){
double max = 0;
if (simetric && diag){ //si es simetrica e inclusimos la diagonal
for(int i=0; i<n1-1; i++){
for (int j=i; j<n2; j++){
if (max < abs(matrix[i*n2+j])){
max = abs(matrix[i*n2+j]);
index1 = i, index2 = j;
}
}
}
}
else if (simetric && !diag){ //simetrica y no incluimos la diagonal
for(int i=0; i<n1-1; i++){
for (int j=i+1; j<n2; j++){
if (max < abs(matrix[i*n2+j])){
max = abs(matrix[i*n2+j]);
index1 = i, index2 = j;
}
}
}
}
else{ //Busqueda completa
for(int i=0; i<n1-1; i++){
for (int j = 0; j<n2; j++){
if (max < abs(matrix[i*n2+j])){
max = abs(matrix[i*n2+j]);
index1 = i, index2 = j;
}
}
}
}
return max;
}
// Tarea 9------------------
void LinearAlgebra::QR_factorization(){
Q = new double[N1*N2];
R = new double[N1*N2];
double* aux1 = new double[N1];
double* aux2 = new double[N1];
double sum;
//Copiando la matriz en Q y aux, R es la matriz cero
for(int j = 0; j < N2; j++){
for(int i = 0; i< N1; i++){
Q[i*N2+j] = Matrix[i*N2+j];
aux1[i] = Matrix[i*N2+j];
aux2[i] = Matrix[i*N2+j];
R[i*N2+j] = 0;
}
//Normalizando la columna j de Q
sum = 0;
for(int i=0; i<N1; i++) sum += pow(Q[i*N2+j],2.0);
sum = sqrt(sum);
for(int i=0; i<N1; i++) Q[i*N2+j] /= sum; // esto es qj columna
//Obteniedo los valores de R fuera de la diagonal
for(int k=0; k<j; k++){
sum = 0;
for(int i=0; i<N1; i++) sum += Q[i*N2+j]*aux1[i]; //esto es qk^T aj
R[k*N2+j] = sum; //esto es rkj
sum = 0;
for (int i=0; i<N1; i++) aux2[i] -= R[k*N2+j]*Q[i*N2+k];
}
//Termino de la diagonal en R
sum = 0;
for (int i =0; i<N1; i++) sum+= pow(aux2[i], 2.0);
R[j*N2+j] = sqrt(sum);
}
for (int i=0; i<N1; i++){
cout<<"[";
for (int j=0; j<N2; j++){
cout<<Q[i*N2+j]<<", ";
}
cout<<"]"<<endl;
}
cout<<endl;
for (int i=0; i<N1; i++){
cout<<"[";
for (int j=0; j<N2; j++){
cout<<R[i*N2+j]<<", ";
}
cout<<"]"<<endl;
}
cout<<endl;
delete[] aux1;
delete[] aux2;
solve_method = 4; //resolver sistema de ecuacione en modo QR
}
void LinearAlgebra::subspace_eigens(int DIM, int maxiter = 1000, double epsilon = 1e-8){
if (N1 != N2){
printf("No es posible hacer iteracion en el subespacio. Matriz no cuadrada de dimension (%d, %d) fue dada\n", N1,N2);
return;
}
//print_array();
double* sub_Matrix1 = new double[N1*DIM];
double* sub_Matrix2 = new double[N1*DIM];
double *B1 = new double[N1*DIM];
double *B2 = new double[DIM*DIM];
double *Q_eigenvecs, *P_eigenvals;
int iter = 0, N;
//Inicializadno matriz en el subespacio
for(int i =0; i<N1; i++){
for (int j = 0; j<DIM; j++) {
sub_Matrix1[i*DIM+j] = 0;
sub_Matrix2[i*DIM+j] = 0;
}
}
for(int i =0; i<DIM; i++){
sub_Matrix1[i*DIM+i] = 1;
sub_Matrix2[i*DIM+i] = 1;
}
//METODO DE ITERACION EN EL SUBESPACIO CON JACOBI
N = N1;
N1 = DIM, N2 = DIM; //necesario para que funcione jacobi
while(iter< maxiter){
B1 = dot_mat(Matrix, N, N, sub_Matrix1, N, DIM); //La salida es B1 con dimensiones N1xDIM
sub_Matrix2 = transpose(sub_Matrix1, N, DIM); //trasposicion de la matrix de subespacio
B2 = dot_mat(sub_Matrix2, DIM, N, B1, N, DIM); //La salida es B2 con dimensiones DIMxDIM
change_ptr(&B2,&Matrix);
jacobi_eigens(&Q_eigenvecs, &P_eigenvals, false);
change_ptr(&B2, &Matrix);
//Resta matricial B1 = B2 - P_eigenvals
for (int i =0; i<DIM; i++){
for(int j=0; j<DIM; j++) B1[i*DIM+j] = B2[i*DIM+j] - P_eigenvals[i*DIM+j];
}
if(frobenius_norm(B1, DIM, DIM, 2.0) < epsilon){ //se cumple el criterio
//Guardamos los eigenvalores y los eigenvectores
double* aux;
for(int j = 0; j < DIM; j++){
aux = new double[DIM];
for (int i = 0; i < DIM; i++){
aux[j] = Q_eigenvecs[i*DIM+j];
}
eigenvectors.push_back(aux);
eigenvalues.push_back(P_eigenvals[j*DIM+j]);
}
num_eigens = DIM;
N1 = N, N2 = N;
delete[] P_eigenvals;
delete[] Q_eigenvecs;
delete[] sub_Matrix1;
delete[] sub_Matrix2;
delete[] B1;
delete[] B2;
return;
}
else{
delete[] sub_Matrix2;
sub_Matrix2 = dot_mat(sub_Matrix1, N, DIM, Q_eigenvecs, DIM, DIM);
gram_schmit(sub_Matrix2, N, DIM);
delete[] sub_Matrix1;
sub_Matrix1 = dot_mat(Matrix, N, N, sub_Matrix2, N, DIM);
gram_schmit(sub_Matrix1, N, DIM);
iter++;
}
}
cout<<"Metodo de iteracion en el subespacio no convergio en "<<maxiter<<" iteraciones"<<endl;
N1 = N, N2 = N;
delete[] P_eigenvals;
delete[] Q_eigenvecs;
delete[] sub_Matrix1;
delete[] sub_Matrix2;
delete[] B1;
delete[] B2;
return;
}
double* LinearAlgebra::dot_mat( const double* mat1, int sizef1, int sizec1, const double* mat2, int sizef2, int sizec2){
if (sizec1 != sizef2){
printf("dimensiones de matrices no concuerdan. (%d, %d) y (%d, %d) fueron dadas\n", sizef1, sizec2, sizef2, sizec2);
return nullptr;
}
double* mat3 = new double[sizef1*sizec2];
double sum;
for (int i=0; i < sizef1; i++){
for (int j=0; j < sizec2; j++){
sum=0;
for (int m = 0; m < sizec1; m++) sum += mat1[i*sizec1+m] * mat2[m*sizec2+j];
mat3[i*sizec2 + j] = sum;
}
}
return mat3;
}
double* LinearAlgebra::transpose(double* mat, int sizef, int sizec){
double* aux = new double[sizef*sizec];
for (int i = 0; i < sizef; i++){
for (int j = 0; j<sizec; j++) aux[j*sizef+i] = mat[i*sizec+j];
}
return aux;
}
double LinearAlgebra::frobenius_norm(double* mat, int sizef, int sizec, double p = 2.0){
double sum=0;
for (int i =0; i<sizef; i++){
for (int j=0; j<sizec; j++) sum += pow(mat[i*sizec+j], p);
}
return pow(sum, 1.0/p);
}
void LinearAlgebra::gram_schmit(double* mat, int sizef, int sizec){
double* vec1 = new double[sizef];
double* vec2 = new double[sizef];
double sum, scalar;
for (int j = 0; j < sizec; j++){
for (int i=0; i < sizef; i++) vec1[i] = mat[i*sizec+j]; //Copia de la columna j
//Resta de la proyeccion de los otros vectores
for ( int k =0; k < j; k++){
for (int i =0; i<sizef; i++) vec2[i] = mat[i*sizec+k]; //Copia de la columna k < j
scalar = dot(vec1, vec2, sizef); //producto punto de las columnas
for (int i =0; i < sizef; i++) mat[i*sizec+j] -= scalar*vec2[i];
}
//Normalizacion de la columna j
sum = 0;
for (int i = 0; i<sizef; i++) sum += pow(mat[i*sizec+j],2.0);
sum = sqrt(sum);
for (int i =0; i< sizef; i++) mat[i*sizec+j] /=sum;
}
delete[] vec1;
delete[] vec2;
}
//TAREA 10--------------------------------------------------------------------------
void LinearAlgebra::conjugated_gradient(double maxiter = 5000, double epsilon = numeric_limits<double>::min()){
if (N1 != N2){
printf("Matriz no es cuadrada, no se puede resolver con el metodo de gradiente conjugado. Dimensiones (%d, %d) fueron dadas\n", N1, N2);
return;
}
double *residual_vec,*conjugated_vec, *aux_vec;
double delta, deltaOld, beta, alpha, error, k = 0;
//METODO DEL GRADIENTE CONJUGADO
for(int i = 0; i< N3; i++){
out_vector[i] = 0;
}
residual_vec = dot_mat(Matrix, N1, N2, out_vector, N3, 1); //calcula el residuo
for (int i = 0; i< N3; i++){
residual_vec[i] = inp_vector[i] - residual_vec[i];
}
delta = sqrt(dot(residual_vec, residual_vec, N3));
while(delta > epsilon && k < maxiter){
if (k==0){
conjugated_vec = copy(residual_vec, N3, 1);
}
else{
beta = delta/deltaOld;
for (int i = 0; i< N3; i++){
conjugated_vec[i] = residual_vec[i] + beta*conjugated_vec[i];
}
}
aux_vec = dot_mat(Matrix, N1, N2, conjugated_vec, N3, 1);
alpha = delta/dot(conjugated_vec, aux_vec, N3);
for(int i=0; i< N3; i++){
out_vector[i] = out_vector[i] +alpha*conjugated_vec[i];
residual_vec[i] = residual_vec[i] - alpha*aux_vec[i];
}
deltaOld = delta;
delta = dot(residual_vec, residual_vec, N3);
delete[] aux_vec;
k++;
}
if(k == maxiter) {
cout<<"Gradiente Conjugado no convergio en "<<maxiter<<" iteraciones"<<endl;
}
else{
cout<<"Numero de iteraciones para convergencia: "<<k<<endl;
error = sqrt(dot(residual_vec,residual_vec, N3))/N3;
cout<<"El error residual es "<<error<<endl;
}
delete[] aux_vec;
delete[] residual_vec;
delete[] conjugated_vec;
return;
}
double* LinearAlgebra::copy(double* mat, int sizef, int sizec){
double* aux = new double[sizef*sizec];
for (int i=0; i< sizef; i++){
for (int j = 0; j<sizec; j++){
aux[i*sizec+j] = mat[i*sizec+j];
}
}
return aux;
}
void LinearAlgebra::add_mat(double* mat1, int sizef1, int sizec1, double* mat2, int sizef2, int sizec2, double* mat3){
if(sizef1 != sizef2 || sizec1 != sizec2){
printf("No es posble haber la suma de matrices. Dimensiones (%d, %d) y (%d, %d) fueron dadas\n", sizef1, sizec1, sizef2, sizec2);
return;
}
for(int i=0; i<sizef1; i++){
for (int j =0; j<sizec1; j++){
mat3[i*sizec1+j] = mat1[i*sizec1+j] + mat2[i*sizec1+j];
}
}
return;
}
void LinearAlgebra::subtraction_mat(double* mat1, int sizef1, int sizec1, double* mat2, int sizef2, int sizec2, double* mat3){
if(sizef1 != sizef2 || sizec1 != sizec2){
printf("No es posble haber la suma de matrices. Dimensiones (%d, %d) y (%d, %d) fueron dadas\n", sizef1, sizec1, sizef2, sizec2);
return;
}
for(int i=0; i<sizef1; i++){
for (int j =0; j<sizec1; j++){
mat3[i*sizec1+j] = mat1[i*sizec1+j] - mat2[i*sizec1+j];
}
}
return;
}
void LinearAlgebra::set_solve_method(string new_method){
if (new_method == "inv_method") solve_method = 6;
else cout<<"Metodo no encontrado"<<endl;
}
void LinearAlgebra::solve_for_inv_method(){
delete[] out_vector;
out_vector = dot_mat(Matrix, N1, N2, inp_vector, N3,1);
return;
} | true |
fd3cc73097c69fe54d9e2b4d0c107038c68c92fe | C++ | ClericX/Projects | /Plat2D/Plat2D/PacketParser.cpp | UTF-8 | 1,405 | 2.703125 | 3 | [] | no_license | #include "PacketParser.h"
#include "Main.h"
void PacketParser(const char *Packet)
{
switch (Packet[0])
{
// Movement packet.
case PacketHeaders.MovementPacket:
{
MOVEMENTPACKET *mp = (MOVEMENTPACKET*)Packet;
if (mp->ID != Player.ID)
{
CPlayer *ply = Textures.GetPlayerByID(mp->ID);
if (ply == 0) //Character has not been loaded.
{
ply = new CPlayer();
ply->ID = mp->ID;
ply->CurrentMapID = mp->MapID;
ply->SetLT( Player.LT );
OtherPlayers.push_back( ply );
}
else if (ply != 0 && ply->CurrentMapID == Player.CurrentMapID)
{
ply->X = mp->XPos;
ply->Y = mp->YPos;
}
else if (ply->CurrentMapID != Player.CurrentMapID)
{
OtherPlayers.remove( ply );
delete ply;
}
}
}
break;
// Chat packet
case PacketHeaders.ChatPacket:
{
CHATPACKET *cp = (CHATPACKET*)Packet;
cout << cp->ID << " :: " << cp->Text << endl;
}
break;
// Login packet
case PacketHeaders.LoginPacket:
{
LOGINPACKET *lp = (LOGINPACKET*)Packet;
if (lp->UserID != 0)
{
Player.ID = lp->UserID;
//LoginSuccess = 1;
}
else
{
MessageBox(NULL, "Login failed.", "Epic fail has occurred.", MB_OK | MB_ICONEXCLAMATION);
//LoginSuccess = -1;
}
}
break;
default:
{
printf("WARNING: Recieved packet structure not recognized. Header: %s \n", (int)((char)Packet[0]));
}
break;
}
} | true |
1841aa2e37a74e02cc458433e9f1fdf814e0dd0d | C++ | FeiZhao0531/BasicAlgorithm | /Graph/ReadGraph.h | UTF-8 | 1,205 | 3.1875 | 3 | [
"MIT"
] | permissive | /// Template Class for Graph Algorithm to read a existing graph in .txt file
/// Author: Fei
/// Create: Aug-19-2019
#ifndef READGRAPH_H
#define READGRAPH_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cassert>
using std::string;
using std::ifstream;
using std::stringstream;
using std::cout;
using std::endl;
template <typename Graph>
class ReadGraph
{
public:
ReadGraph( Graph &graph, const string &fileName) {
//ctor
ifstream file( fileName);
string line;
int V; // nums of vertexes
int E; // nums of edges
assert( file.is_open());
assert( getline( file, line));
stringstream ss( line);
ss >> V >> E;
//cout << "V = " << V << ", E = " << E << endl;
assert( V == graph.getNumsVertex());
for( int i = 0; i < E; ++ i)
{
assert( getline( file, line));
stringstream ss( line);
int v, w;
ss >> v >> w;
assert( v >= 0 && v < V);
assert( w >= 0 && w < V);
graph.addEdge( v, w);
}
}
protected:
private:
};
#endif // READGRAPH_H
| true |
bc186a432a8e16b70fe3bafb82fa7b569b6e5c1e | C++ | Yangmila/c_code | /乘法口诀.cpp | UTF-8 | 253 | 2.71875 | 3 | [] | no_license | #include<stdio.h>
void chengfa(int n)
{
int i,j,result;
for(i=1;i<=n;++i)
{
for(j=1;j<=i;++j)
{
result=i*j;
printf("%d*%d=%d\t",j,i,result);
}
printf("\n");
}
}
int main()
{
int n;
scanf("%d",&n);
chengfa(n);
return 0;
}
| true |
da9450b7cdfaceecee244b52d61517cf8b0f954f | C++ | ericosur/myqt | /sha3test/readthread.cpp | UTF-8 | 1,020 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "readthread.h"
ReadThread::ReadThread()
{
qDebug() << Q_FUNC_INFO << "created...";
flag = true;
}
void ReadThread::run()
{
qDebug() << Q_FUNC_INFO << "run start...";
const int REPEAT_TIMES = 4000000;
qint64 current = QDateTime::currentMSecsSinceEpoch();
for (int i = 0 ; i < REPEAT_TIMES ; ++i) {
test(i);
if (!flag)
break;
}
qDebug() << "time elapse:" << QDateTime::currentMSecsSinceEpoch() - current;
//QThread::msleep(WAIT_MSEC_LENGTH);
qDebug() << Q_FUNC_INFO << "run finished...";
}
QString ReadThread::test(int i)
{
QString str = QString("repeat no %1").arg(i);
QString md5 = md5sum(str.toUtf8().data(), str.toUtf8().size());
QString sha3 = sha3_256sum(str.toUtf8().data(), str.toUtf8().size());
return md5 + sha3;
}
void ReadThread::setFlag(bool b)
{
mutex.lock();
flag = b;
mutex.unlock();
}
bool ReadThread::getFlag()
{
mutex.lock();
bool ret = flag;
mutex.unlock();
return ret;
} | true |
5e46fcce0f69ad7253ad3282951d6585bb1da547 | C++ | Ra1nWarden/Online-Judges | /UVa/12093.cpp | UTF-8 | 1,735 | 2.546875 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <cstring>
#define MAXN 10005
#define INF 2000000000
using namespace std;
int n, c1, c2;
int a, b;
vector<int> adjList[MAXN];
int dp[MAXN][3][4];
// dp[u][i][j]
// at node u
// put i
// j=0 : parent edge not connected
// j=1 : parent edge connected
// j=2 : parent and children edge connected
// j=3 : parent and children/grandchildren edge connecteed
int f(int root, int parent, int device, int mode) {
if(dp[root][device][mode] != -1)
return dp[root][device][mode];
int ans = 0;
if(mode == 0) {
ans = INF;
} else {
for(int i = 0; i < adjList[root].size(); i++) {
int u = adjList[root][i];
if(u == parent)
continue;
ans += min(min(f(u, root, 0, mode-1), f(u, root, 1, 2)), f(u, root, 2, 3));
}
}
int tmp = 0;
for(int i = 0; i < adjList[root].size(); i++) {
int u = adjList[root][i];
if(u == parent)
continue;
tmp += min(min(f(u, root, 0, 1), f(u, root, 1, 2)), f(u, root, 2, 3));
}
for(int i = 0; i < adjList[root].size(); i++) {
int u = adjList[root][i];
if(u == parent)
continue;
ans = min(ans, tmp - min(min(f(u, root, 0, 1), f(u, root, 1, 2)), f(u, root, 2, 3)) + f(u, root, 2, 3));
}
if(device == 1)
ans += c1;
if(device == 2)
ans += c2;
return dp[root][device][mode] = ans;
}
int main() {
while(scanf("%d %d %d", &n, &c1, &c2) != EOF && (n || c1 || c2)) {
for(int i = 1; i <= n; i++)
adjList[i].clear();
for(int i =0 ; i < n - 1; i++) {
scanf("%d %d", &a, &b);
adjList[a].push_back(b);
adjList[b].push_back(a);
}
memset(dp, -1, sizeof dp);
printf("%d\n", min(min(f(1, 0, 0, 1), f(1, 0, 1, 2)), f(1, 0, 2, 3)));
}
return 0;
}
| true |
d8385abf8f6686c740fed52ff925f4c4ca0dcf0a | C++ | sknjpn/Lonely-Creatures | /Lonely-Creatures/Field.h | SHIFT_JIS | 3,002 | 2.78125 | 3 | [
"MIT"
] | permissive | #pragma once
class Assets;
struct Field;
struct Chip;
struct Material;
enum struct MType {
Leaf,
Meat,
Iron,
Fertilizer,
};
enum struct CType {
Clematis,
Slug,
Cricket,
};
enum struct CState {
Egg,
Seed,
Child,
Adult,
};
//bIuWFNg
struct Object {
int age;
Chip* registeredChip;
bool enabled;
double y;
double vy;
Vec2 v;
Vec2 pos;
Vec2 angle;
static Field* field;
static Assets* assets;
Object()
: age(0)
, registeredChip(nullptr)
, enabled(true)
, y(0.0)
, vy(0.0)
, v(Vec2::Zero())
, pos(Vec2::Zero())
, angle(RandomVec2())
{}
virtual Vec2 drawPos() const {
return pos.movedBy(0, -y);
}
virtual String name() const {
return U"Object";
}
};
//IuWFNg
struct Creature : Object {
int mCount; //}eAn
int timer;
int health;
CType type;
CState state;
static int numEnabled;
Creature()
: timer(0)
, mCount(0)
{
Creature::numEnabled++;
}
int maxHealth() const;
double size() const;
void erase();
void addMaterial(MType _type, double _force = 0.0, int _num = 1);
String name() const {
switch (type)
{
case CType::Clematis: return U"Clematis";
case CType::Slug: return U"Slug";
case CType::Cricket: return U"Cricket";
default: return U"Hoge";
}
}
};
//}eAIuWFNg
struct Material : Object {
MType type;
static int numEnabled;
Material() { Material::numEnabled++; }
double size() const { return 4.0; }
void erase();
String name() const {
switch (type)
{
case MType::Fertilizer: return U"Fertilizer";
case MType::Iron: return U"Iron";
case MType::Leaf: return U"Leaf";
case MType::Meat: return U"Meat";
default: return U"Hoge";
}
}
Vec2 drawPos() const {
return pos.movedBy(0, -y - 0.8 + 0.4*sin(age / 20.0));
}
};
struct Chip {
Array<Creature*> creatures;
Array<Material*> materials;
void remove(Creature* _creature);
void remove(Material* _material);
void set(Creature* _creature);
void set(Material* _material);
};
struct Table {
Grid<Chip> chips;
double width;
Size size;
Table(double _width, const Size& _size);
//ł]l̍̂ԂA0.0ȉ̂̂ȂꍇAnullptrԂ
Creature* searchCreature(Vec2 _pos, double _range, double(*func)(Vec2, Creature*)) const;
Material* searchMaterial(Vec2 _pos, double _range, double(*func)(Vec2, Material*)) const;
Chip* chip(const Vec2& _pos);
};
//tB[h
struct Field {
bool drawHealthBar;
RectF region;
Table table;
Assets* assets;
size_t maxNumCreatures;
size_t maxNumMaterials;
Array<Creature> creatures;
Array<Material> materials;
Field(Assets* _assets);
void update();
void draw() const;
Creature* newCreature(CType _type, CState _state, const Vec2& _pos);
Creature* newCreature(CType _type, CState _state);
Material* newMaterial(MType _type, const Vec2& _pos);
Material* newMaterial(MType _type);
void updateClematis(Creature* _c);
void updateSlug(Creature* _c);
}; | true |
0c1856edc19af15eb46ec88147b64b44fbc8a35f | C++ | OutOfTheVoid/FRC-2605-Robot-Code-2014 | /src/Behaviors/BehaviorController.cpp | UTF-8 | 2,255 | 3.015625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | #include "BehaviorController.h"
BehaviorController :: BehaviorController ()
{
Behaviors = new Vector <BehaviorControllerList_t> ();
};
BehaviorController :: ~BehaviorController ()
{
for ( uint32_t i = 0; i < Behaviors -> GetLength (); i ++ )
if ( ( * Behaviors ) [ i ].Active )
( * Behaviors ) [ i ].Item -> Stop ();
};
void BehaviorController :: AddBehavior ( const char * Name, Behavior * NewBehavior )
{
if ( Name == NULL || NewBehavior == NULL )
return;
if ( GetBehaviorIndex ( Name ) != -1 )
return;
BehaviorControllerList_t BehaviorListElement;
BehaviorListElement.Name = Name;
BehaviorListElement.Item = NewBehavior;
BehaviorListElement.Active = false;
Behaviors -> Push ( BehaviorListElement );
};
void BehaviorController :: RemoveBehavior ( const char * Name )
{
int32_t Index = GetBehaviorIndex ( Name );
if ( Index == -1 )
return;
if ( ( * Behaviors ) [ Index ].Active )
( * Behaviors ) [ Index ].Item -> Stop ();
Behaviors -> Remove ( Index, 1 );
};
void BehaviorController :: StartBehavior ( const char * Name )
{
int32_t Index = GetBehaviorIndex ( Name );
if ( Index != -1 )
{
if ( ! ( * Behaviors ) [ Index ].Active )
{
( * Behaviors ) [ Index ].Active = true;
( * Behaviors ) [ Index ].Item -> Start ();
}
else
( * Behaviors ) [ Index ].Item -> Restart ();
}
};
void BehaviorController :: StopBehavior ( const char * Name )
{
int32_t Index = GetBehaviorIndex ( Name );
if ( Index != -1 )
{
if ( ( * Behaviors ) [ Index ].Active )
{
( * Behaviors ) [ Index ].Active = false;
( * Behaviors ) [ Index ].Item -> Stop ();
}
}
};
bool BehaviorController :: GetBehaviorActive ( const char * Name )
{
int32_t Index = GetBehaviorIndex ( Name );
if ( Index != -1 )
return ( * Behaviors ) [ Index ].Active;
return false;
};
void BehaviorController :: Update ()
{
for ( uint32_t i = 0; i < Behaviors -> GetLength (); i ++ )
if ( ( * Behaviors ) [ i ].Active )
( * Behaviors ) [ i ].Item -> Update ();
};
int32_t BehaviorController :: GetBehaviorIndex ( const char * Name )
{
for ( uint32_t i = 0; i < Behaviors -> GetLength (); i ++ )
if ( strcmp ( Name, ( * Behaviors ) [ i ].Name ) == 0 )
return i;
return -1;
};
| true |
72ceb3e5502103c7c39963bb236c35b744b1de88 | C++ | nikoladimitroff/trinity | /src/FormulaParser.cpp | UTF-8 | 5,813 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <mutex>
#include <string>
#include <stack>
#include <queue>
#include <stdlib.h>
#include <math.h>
#include "FormulaParser.h"
#include "TreeNode.h"
using namespace std;
static bool RequiresTwoArguments(const string& token)
{
return token=="+"||
token=="-" ||
token=="*" ||
token=="/" ||
token=="%" ||
token=="^" ||
token=="max"||
token=="min";
}
static bool IsOperator(const string& token) {
return token == "+" ||
token == "-" ||
token == "*" ||
token == "/" ||
token == "%" ||
token == "^" ||
token == "%";
}
static bool IsFunction(const string& token){
return token=="min" ||
token=="max" ||
token=="sin" ||
token=="cos" ||
token=="tan" ||
token=="cotan" ||
token=="asin" ||
token=="floor" ||
token=="ceil" ||
token=="sqrt";
}
double FormulaParser::RPNParse(double x, double y, double z, TreeNode* root)
{
if(root->HasValue())
{
if(root->Parameter == "x")
return x;
else if(root->Parameter == "y")
return y;
else if(root->Parameter == "z")
return z;
else
return root->Value;
}
double left, right;
bool hasRight = root->Right != nullptr;
bool hasLeft = root->Left != nullptr;
if(hasLeft)
left = RPNParse(x, y, z, root->Left);
if(hasRight)
right = RPNParse(x, y, z, root->Right);
switch (root->Op)
{
case TreeOperator::Plus:
return left + right;
case TreeOperator::Minus:
return left - right;
case TreeOperator::Divide:
return left / right;
case TreeOperator::Mult:
return left * right;
case TreeOperator::Pow:
return pow(left,right);
case TreeOperator::Mod:
return (int)left % (int)right;
case TreeOperator::Max:
return max(left,right);
case TreeOperator::Min:
return min(left,right);
case TreeOperator::Sin:
return sin(right);
case TreeOperator::Cos:
return cos(right);
case TreeOperator::Tan:
return tan(right);
case TreeOperator::Cotan:
return 1/tan(right);
case TreeOperator::Asin:
return asin(right);
case TreeOperator::Floor:
return floor(right);
case TreeOperator::Ceil:
return ceil(right);
case TreeOperator::Sqrt:
return sqrt(right);
default:
throw new exception();
}
}
static void AddToQueue(queue<string>& q, string el)
{
if(el != "")
q.push(el);
}
static bool IsLeftPare(const string& token)
{
return token == "(";
}
static bool IsRightPare(const string& token)
{
return token == ")";
}
static int PrecedenceOf(const string& token) {
if (token == "%") return -1;
if (token == "+" || token == "-") return 0;
if (token == "*" || token == "/" || token == "%") return 1;
if (token == "^") return 2;
return -1;
}
static bool PrecedenceCmp(const string& tokenOne, const string& tokenTwo)
{
int PrecedenceOne = PrecedenceOf(tokenOne);
int PrecedenceTwo = PrecedenceOf(tokenTwo);
if(PrecedenceOne==2 && PrecedenceTwo==2)
{
return false;
}
return (PrecedenceOf(tokenOne)>=PrecedenceOf(tokenTwo));
}
enum TokenType{
Function,
LeftPare,
RightPare,
Operator,
Number
};
static TokenType switchHelper(const string& token)
{
if(IsFunction(token))return Function;
if(IsLeftPare(token))return LeftPare;
if(IsRightPare(token))return RightPare;
if(IsOperator(token))return Operator;
return Number;
}
static vector<string> ShuntingYard(queue<string> tokens)
{
string result="";
stack<string> operatorsStack;
queue<string> outputQueue;
int tokensSize = tokens.size();
for(int i = 0; i<tokensSize;++i)
{
string currentToken=tokens.front();
tokens.pop();
switch (switchHelper(currentToken))
{
case Function:
{
operatorsStack.push(currentToken);
break;
}
case LeftPare:
operatorsStack.push(currentToken);
break;
case RightPare:
{
if(!operatorsStack.empty())
{
while(operatorsStack.top()!="(")
{
outputQueue.push(operatorsStack.top());
operatorsStack.pop();
if(operatorsStack.empty())break;
}
operatorsStack.pop();
if(!operatorsStack.empty())
{
if(IsFunction(operatorsStack.top()))
{
outputQueue.push(operatorsStack.top());
operatorsStack.pop();
}
}
}
break;
}
case Operator:
{
while(!operatorsStack.empty()
&& PrecedenceCmp(operatorsStack.top(),currentToken))
{
outputQueue.push(operatorsStack.top());
operatorsStack.pop();
}
operatorsStack.push(currentToken);
break;
}
case Number: outputQueue.push(currentToken);
}
}
while(!operatorsStack.empty()){
if(operatorsStack.top()!="(")outputQueue.push(operatorsStack.top());
operatorsStack.pop();
}
vector<string> vec;
while(!outputQueue.empty())
{
vec.push_back(outputQueue.front());
outputQueue.pop();
}
return vec;
}
namespace FormulaParser{
queue<string> tokenize(string input){
queue<string> tokens;
int tBegin=0;
for(unsigned int i=0;i<input.length();++i)
{
if(input[i]==' '||input[i]==',')
{
AddToQueue(tokens, input.substr(tBegin,i-tBegin));
tBegin = i+1;
}
if(input[i]=='('||input[i]==')')
{
AddToQueue(tokens, input.substr(tBegin,i-tBegin));
AddToQueue(tokens, (input.substr(i,1)));
tBegin = i+1;
}
}
if(tBegin != input.length())
{
string s = input.substr(tBegin,input.length()-tBegin);
AddToQueue(tokens, s);
}
return tokens;
}
}
TreeNode* FormulaParser::GenerateTree(string input)
{
return Treenify(ShuntingYard(FormulaParser::tokenize(input)));
}
| true |
38ea035d1de9bbd3bdf2eb4caf33010e1118f5d0 | C++ | TahseenSust/Competitive-programming | /uva/10340.cpp | UTF-8 | 412 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
string s,t;
while(cin>>s>>t){
int cnt=0;
for(int i=0,j=0;i<t.size();i++){
if(s[j]==t[i]){
cnt++;
j++;
}
}
if(cnt==s.size()){
cout<<"Yes\n";
}else{
cout<<"No\n";
}
}
}
| true |
791a45e13a7fc218f79fbab96653ade9ce9330a7 | C++ | wolfjagger/coopnet | /src/coopnet/sat/solving/solver.cpp | UTF-8 | 614 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "solver.h"
using namespace coopnet;
Solver::~Solver() { }
auto CompleteSolver::solve() -> Solution {
auto solution = do_solve();
if (solution.status == SolutionStatus::Undetermined)
throw std::exception("Complete solver has undetermined solution.");
return solution;
}
auto IncompleteSolver::solve() -> Solution {
for (unsigned int i = 0; i < retry_count(); ++i) {
auto possible_solution = try_single_solve();
if (possible_solution.status != SolutionStatus::Undetermined) {
return possible_solution;
}
}
return Solution{ SolutionStatus::Undetermined, nullptr, 0 };
}
| true |
9c7a08e01fd834976301d79fa81b70a354e97340 | C++ | vamsikrishna1417/Advanced_computer_architecture | /OpenCL/main.cpp | UTF-8 | 8,567 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <chrono>
#include <string>
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#include <CL/cl.h>
#define MAX_SOURCE_SIZE (0x100000)
// C version of matrix multiplcation. Use this function for result validation and execution time comaprison
void matrix_mul_sequence (int *A_mat,
int *B_mat,
int *C_mat)
{
for (int j=0; j<SIZE; j++) {
for (int i=0; i<SIZE; i++)
for (int k=0; k<SIZE; k++)
C_mat[j*SIZE + i] += A_mat[j*SIZE + k] * B_mat[k*SIZE + i];
}
}
void get_time(cl_device_id device_id)
{
// A, B are input matrix, C is the output matrix for OpenCL, C_seq is the output matrix for reference implementation.
int *A = new int[SIZE*SIZE];
int *B = new int[SIZE*SIZE];
int *C = new int[SIZE*SIZE];
int *C_seq = new int[SIZE*SIZE];
//Initialize matrix
for(int j=0; j<SIZE; j++) {
for(int i=0; i<SIZE; i++) {
A[j*SIZE + i] = 1;
B[j*SIZE + i] = i+1;
C[j*SIZE + i] = 0;
C_seq[j*SIZE + i] = 0;
}
}
std::chrono::high_resolution_clock::time_point t1, t2;
t1 = std::chrono::high_resolution_clock::now();
matrix_mul_sequence(A, B, C_seq);
t2 = std::chrono::high_resolution_clock::now();
std::cout << "Reference C matrix multiplication: "
<< (float)(std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count())/1000000
<< " sec"
<< std::endl;
// Load the kernel source code into the array source_str
FILE *fp;
char *source_str;
size_t source_size;
cl_int ret;
fp = fopen("matrix_mul.cl", "r");
if (!fp) {
fprintf(stderr, "Failed to load kernel.\n");
exit(1);
}
source_str = (char*)malloc(MAX_SOURCE_SIZE);
source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp);
fclose( fp );
// Create an OpenCL context
cl_context context = clCreateContext( NULL, 1, &device_id, NULL, NULL, &ret);
// Create a command queue with the capability of performance profiling for target device
cl_command_queue command_queue = clCreateCommandQueue(context, device_id, CL_QUEUE_PROFILING_ENABLE, &ret);
// Create memory buffers on the device for each matrix
cl_mem a_mem_obj = clCreateBuffer(context, CL_MEM_READ_WRITE, SIZE*SIZE*sizeof(int), NULL, &ret);
cl_mem b_mem_obj = clCreateBuffer(context, CL_MEM_READ_WRITE, SIZE*SIZE*sizeof(int), NULL, &ret);
cl_mem c_mem_obj = clCreateBuffer(context, CL_MEM_READ_WRITE, SIZE*SIZE*sizeof(int), NULL, &ret);
// Copy the matrix A, B and C to each device memory counterpart
ret = clEnqueueWriteBuffer(command_queue, a_mem_obj, CL_TRUE, 0, SIZE*SIZE*sizeof(int), A, 0, NULL, NULL);
ret = clEnqueueWriteBuffer(command_queue, b_mem_obj, CL_TRUE, 0, SIZE*SIZE*sizeof(int), B, 0, NULL, NULL);
ret = clEnqueueWriteBuffer(command_queue, c_mem_obj, CL_TRUE, 0, SIZE*SIZE*sizeof(int), C, 0, NULL, NULL);
// Create a program from the kernel source
cl_program program = clCreateProgramWithSource(context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret);
// Build and compile the OpenCL kernel program
std::string build_option = "-DTILE_SIZE=" + std::to_string(TILE_SIZE);
ret = clBuildProgram(program, 1, &device_id, build_option.c_str(), NULL, NULL);
if (ret == CL_BUILD_PROGRAM_FAILURE) { // If compile failed, print the error message
// Determine the size of the log
size_t log_size;
clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
char *log = (char *) malloc(log_size);
// Get the log and print it
clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, log_size, log, NULL);
printf("%s\n", log);
}
// Create the OpenCL kernel
cl_kernel kernel;
#ifdef ENABLE_TILE_KERNEL
kernel = clCreateKernel(program, "matrix_mul_tile", &ret);
#else
kernel = clCreateKernel(program, "matrix_mul", &ret);
#endif
// Set the arguments of the kernel
ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&a_mem_obj);
ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&b_mem_obj);
ret = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&c_mem_obj);
int dimention = 2; // In this example, We will use 2 dimention index
size_t global_item_size[] = {SIZE, SIZE, 1};
size_t local_item_size[] = {TILE_SIZE, TILE_SIZE, 1};
cl_event perf_event;
cl_ulong start, end;
// Execute the OpenCL kernel
ret = clEnqueueNDRangeKernel(command_queue, kernel, dimention, NULL, global_item_size, local_item_size, 0, NULL, &perf_event);
// Capture performance event from target device. In this case the event is to retrive the execution time.
ret = clWaitForEvents(1, &perf_event);
ret = clGetEventProfilingInfo(perf_event, CL_PROFILING_COMMAND_START, sizeof(start), &start, NULL);
ret = clGetEventProfilingInfo(perf_event, CL_PROFILING_COMMAND_END, sizeof(end), &end, NULL);
std::cout << "OpenCL matrix multiplication: " << (float)(end - start)/1000000000 << " sec" << std::endl;
// Read the memory buffer C from the device into the local variable C
ret = clEnqueueReadBuffer(command_queue, c_mem_obj, CL_TRUE, 0, SIZE*SIZE*sizeof(int), C, 0, NULL, NULL);
// Make sure all the command in the command queue has been executed
ret = clFinish(command_queue);
bool validate = true;
for(int j=0; j<SIZE; j++) {
for(int i=0; i<SIZE; i++) {
if (C[j*SIZE + i] != C_seq[j*SIZE + i])
validate = false;
}
}
if (validate == false)
std::cout << "The results are mismatched !!" << std::endl;
// Clean up
ret = clReleaseKernel(kernel);
ret = clReleaseProgram(program);
ret = clReleaseMemObject(a_mem_obj);
ret = clReleaseMemObject(b_mem_obj);
ret = clReleaseMemObject(c_mem_obj);
ret = clReleaseCommandQueue(command_queue);
ret = clReleaseContext(context);
//std::cout << "Press Enter to finish..." << std::endl;
//getchar();
}
int main(void)
{
struct
{
cl_device_type type;
const char* name;
cl_uint count;
}
devices[] =
{
{ CL_DEVICE_TYPE_CPU, "CL_DEVICE_TYPE_CPU", 0 },
{ CL_DEVICE_TYPE_GPU, "CL_DEVICE_TYPE_GPU", 0 }
};
const int NUM_OF_DEVICE_TYPES = sizeof(devices)/sizeof(devices[0]);
// Get platform and device information
cl_uint ret_num_platforms = 0;
cl_int ret = clGetPlatformIDs(0, 0, &ret_num_platforms);
std::cout << "Number of available platforms: " << ret_num_platforms << std::endl;
cl_platform_id* platform_id = new cl_platform_id[ret_num_platforms];
// get IDs for all platforms:
ret = clGetPlatformIDs(ret_num_platforms, platform_id, 0);
for(cl_uint i = 0; i < ret_num_platforms; i++)
{
cl_platform_id platform = platform_id[i];
for(int j = 0; j < NUM_OF_DEVICE_TYPES; ++j)
{
ret = clGetDeviceIDs(
platform,
devices[j].type,
0,
0,
&devices[j].count
);
if(CL_DEVICE_NOT_FOUND == ret)
{
// that's OK to fall here, because not all types of devices, which
// you query for may be available for a particular system
devices[i].count = 0;
ret = CL_SUCCESS;
}
//std::cout<< " " << devices[i].name << ": " << devices[i].count << std::endl;
cl_uint cur_num_of_devices = devices[j].count;
if(cur_num_of_devices == 0)
{
// there is no devices of this type; move to the next type
continue;
}
// Retrieve a list of device IDs with type selected by type_index
cl_device_id* device_id = new cl_device_id[cur_num_of_devices];
ret = clGetDeviceIDs(
platform,
devices[j].type,
cur_num_of_devices,
device_id,
0
);
// Iterate over all devices of the current device type
for(cl_uint device_index = 0;
device_index < cur_num_of_devices;
++device_index
)
{
std::cout
<< "\n"
<< devices[j].name
<< "[" << device_index << "]\n";
cl_device_id device = device_id[device_index];
get_time(device);
}
}
}
return 0;
}
| true |
d6dcf89d48bc7259c58ee6de0b057c4bfbea4d38 | C++ | savageblossom/cpp | /abramyan.cpp | UTF-8 | 740 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
float RingS(int R1, int R2) {
float Pi = 3.14;
if(R1 > R2) return Pi*(pow(R1, 2)-pow(R2,2));
else return 666;
}
int main() {
// // while 3
// // 15 / 3 = 5
// // 15 12 9 6 3
// int N, K, acc = 0;
// cout << "Enter N and K (N/K): ";
// cin >> N >> K;
// while(N>=K) {
// acc++;
// N -= K;
// }
// cout << "Result of divion: " << acc << endl
// << "Remaining: " << N << endl;
//
// proc 19
int R1, R2;
cout << "Enter R1 and R2 to find S of circles (R1 > R2!): ";
cin >> R1 >> R2;
cout << "S of trianles equals to: " << RingS(R1, R2) << endl;
}
| true |
066d1321e68f1132959cdeede06d3b0fb703a6d4 | C++ | Lozoute/Rtype | /API/API_Mutex/API_Mutex.hpp | UTF-8 | 827 | 2.59375 | 3 | [] | no_license | #ifndef API_MUTEX_HPP_
# define API_MUTEX_HPP_
# include <iostream>
# include <string>
# include "API_Error.hpp"
namespace API_Mutex
{
class IMutex
{
public:
virtual ~IMutex () {}
virtual bool lock() = 0;
virtual bool tryLock() = 0;
virtual bool try_lock() = 0;
virtual bool unLock() = 0;
virtual bool unlock() = 0;
}; /* !class IMutex */
# if defined(WIN32) || defined (_WIN32)
// Microsoft
# define EXPORT __declspec(dllexport)
# define IMPORT __declspec(dllimport)
# elif defined(linux) || defined (__unix__)
// UNIX
# define EXPORT __attribute__((visibility("default")))
# define IMPORT
# else
// do nothing and hope for the best?
# define EXPORT
# define IMPORT
# pragma warning Unknown dynamic link import/export semantics.
# endif
}
#endif /* !API_MUTEX_HPP_ */
| true |
701281adc638aecfa39f89b283c7d560b8c66625 | C++ | EugeneH5837/Hackerrank | /Vector-sort.cpp | UTF-8 | 432 | 2.890625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin >> n;
//n = size
vector<int> vec;
for (int i = 0; i < n; i++) {
int b;
cin >> b;
vec.push_back(b);
}
sort(vec.begin(), vec.end());
for (int i = 0; i < n; i++) {
cout << vec[i] << " ";
}
return 0;
}
| true |
10860a000c232983081ae0299f6ebd541f6ede1d | C++ | zackkk/leetcode | /Word Ladder.cpp | UTF-8 | 1,427 | 3.078125 | 3 | [] | no_license | class Solution {
public:
// bfs, word queue + dist queue
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start == "") return 0;
queue<string> wordQueue;
queue<int> distQueue;
wordQueue.push(start);
distQueue.push(1);
while(!wordQueue.empty()){
string curWord = wordQueue.front();
wordQueue.pop();
int curDist = distQueue.front();
distQueue.pop();
if(curWord == end) return curDist;
// put all words in dict that have distance one, of the current word
// O(26 * len(word))
for(int i = 0; i < curWord.size(); i++){
for(char c = 'a'; c <= 'z'; c++){
if(c != curWord[i]){
// replace one charcter each time
string tmpStr = curWord;
tmpStr[i] = c;
// add it into the queue
if(dict.find(tmpStr) != dict.end()){
wordQueue.push(tmpStr);
distQueue.push(curDist+1);
dict.erase(tmpStr); // avoid loop
}
}
}
}
}
return 0;
}
}; | true |
ac9458803ec38737fbc36eda244c17d6f9699fb6 | C++ | sandiya11/sandiya | /92.cpp | UTF-8 | 196 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int i, n, sum=0, num;
cout<<"enter the value"<<endl;
cin>>n;
for(i=0;i<n;i++)
{
cin>>num;
sum=sum+num;
}
cout<<sum;
return 0;
}
| true |
a07ba3f89efbd72fe68cc0eb655c2ac068625f00 | C++ | pradeep0995/competitive-codes | /arrat.cpp | UTF-8 | 1,576 | 2.65625 | 3 | [] | no_license | #include <cmath>
#include<stdio.h>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
bool search;
int test,R,C,r,c;
cin>>test;
while(test--)
{
int flag;
// input the first array
cin>>R>>C;
char a[R][C];
for(int i=0; i<R; i++)
for(int j=0; j<C; j++)
cin>>a[i][j];
// input the second array
cin>>r>>c;
char b[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cin>>b[i][j];
//checking whether array b is in a
long coutn;
for(int i=0;i<=R-r;i++)
{
for(int j=0;j<=C-c;j++)
{
coutn=0,search=true;
//check
if(a[i][j]==b[0][0])
{
flag=1;
for(int k=0; k<r;++k)
{
for(int l=0; l<c ;++l)
{
if(a[i+k][j+l]==b[k][l])
coutn++;
else {
flag=0;
break;
}
}
if(flag==0)break;
}
if(coutn==r*c)
{
cout<<"YES\n";
search=false;
}
}
if(search==false)break;
else continue;
}
if(search==false)break;
}
if(search==true)cout<<"NO\n";
}
return 0;
}
| true |
491b62bc568e1781dce5b097bf6924a6f08ed86d | C++ | niteshbhatia008/eeg-toolkit | /toolkit/toolkit/visgoth/collectd.cpp | UTF-8 | 1,977 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "collectd.hpp"
#include <errno.h>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include "../json11/json11.hpp"
#include "../helpers.hpp"
using namespace std;
using namespace json11;
Collectd::Collectd()
{
struct sockaddr_un addr;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
cout << "Socket error: " << errno << endl;
exit(-1);
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1);
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
cout << "Connect error: " << errno << endl;
exit(-1);
}
}
Collectd::~Collectd()
{
close(fd);
}
vector<string> Collectd::list()
{
uint numvalues = _cmd("LISTVAL");
return _readlines(numvalues);
}
vector<string> Collectd::get(string val, bool flush)
{
uint numvalues = _cmd("GETVAL \"" + val + "\"");
vector <string> lines = _readlines(numvalues);
if (flush)
{
_cmd("FLUSH identifier=\"" + val + "\"");
}
return lines;
}
uint Collectd::_cmd(string cmd)
{
cmd += "\n";
if (write(fd, cmd.c_str(), cmd.size()) < 0)
{
cout << "Write error: " << errno << endl;
exit(-1);
}
string line = _readline();
if (!line.size()) {
return 0;
} else {
vector<string> stat = split(line, ' ');
return stoi(stat[0]);
}
}
string Collectd::_readline()
{
string line = "";
char data = ' ';
while (data != '\n')
{
read(fd, &data, sizeof(data));
if (data != '\n')
{
line += data;
}
}
return line;
}
vector<string> Collectd::_readlines(uint nlines)
{
vector<string> lines;
while (1)
{
string line = _readline();
if (!line.size())
{
break;
}
lines.push_back(line);
if (nlines && lines.size() >= nlines)
{
break;
}
}
return lines;
}
| true |
e58e3f89fe5b439900a67080339bbaa609c82998 | C++ | jal535c/FlappyB | /bird.cpp | UTF-8 | 1,330 | 3.1875 | 3 | [] | no_license | #include "bird.h"
#include <sstream>
Bird::Bird()
{
x = 96;
y = 240;
t.loadFromFile("assets/bird.png");
s.setTexture(t);
s.setOrigin(20, 15); //referencia en el centro del sprite
buffer.loadFromFile("assets/flap.wav");
flap.setBuffer(buffer);
}
void Bird::fly() {
if (alive == 1)
flap.play(); //sonido
dy = -2; //vuela (sube en el eje y)
}
void Bird::update() {
dy += 0.1; //gravedad
if (dy<0)
angle = -30; //si subo cambia angulo (setRotation gira en el sentido del reloj)
else
angle = 0;
y += dy; //el pajaro cae
checkHeight();
s.setPosition(x, y);
s.setRotation(angle);
}
void Bird::checkHeight() { //comprueba altura
if (y > 420) //game over si toca suelo
alive = 0;
}
void Bird::reset() {
y = 240;
dy = 0;
counter = 0;
alive = 1;
}
void Bird::draw(sf::RenderWindow& win) {
win.draw(s);
}
std::string Bird::getStrPoints() {
std::ostringstream bo; //buffer de salida
bo << counter;
return bo.str(); //devuelve como string
}
float Bird::getX() {
return x;
}
float Bird::getY() {
return y;
}
int Bird::getCounter() {
return counter;
}
bool Bird::isAlive() {
return alive;
}
void Bird::setAlive(bool b) {
alive = b;
}
void Bird::addCounter() {
counter++;
} | true |
460af7b2923d3089dbd12a6850bd0fc312585d12 | C++ | tanertopal/CppND-Capstone-Route-Finder-Game | /src/player.h | UTF-8 | 450 | 2.625 | 3 | [] | no_license | #ifndef PLAYER_H
#define PLAYER_H
#include <tuple>
#include <vector>
#include "SDL.h"
#include "world.h"
class Player {
public:
enum class Direction { kUp, kDown, kLeft, kRight };
Player(World::Map &map);
void Walk(Direction direction);
std::tuple<size_t, size_t> GetPosition() const;
std::vector<std::tuple<size_t, size_t>> GetPath() const;
private:
std::vector<std::tuple<size_t, size_t>> _path;
World::Map &_map;
};
#endif
| true |
6668372fffb59e1912d194b31e6f7b0d489f53fa | C++ | NesterovN/Homework | /26.12.18/5.cpp | UTF-8 | 528 | 2.9375 | 3 | [] | no_license |
#include <iostream>
using namespace std;
int main()
{
int M;
cin >> M;
int N;
int *m = new int[N];
int *c = new int[N];
double *w = new double[N];
for (int i = 0; i < N; i++)
{
cin >> m[i];
cin >> c[i];
w[i] = m[i] / c[i];
}
double max = w[0];
int j = 0;
for(int i = 1; i < N; i++)
{
if(max < w[i])
{
max = w[i];
j = i;
}
}
double W = M / m[j];
cout << W*c[j];
return 0;
}
| true |
7a206fe2e8a46a06275238b695b1579519dd501c | C++ | uLoyd/RPN_Calculator | /Linux/ONPCalculator/uts/InfixConverter.cpp | UTF-8 | 7,396 | 3.46875 | 3 | [] | no_license | //
// Created by dawpa on 02.10.2021.
//
#include <gtest/gtest.h>
#include <BasicElementCreator.hpp>
#include "InfixConverter.hpp"
#include "EquationParser.hpp"
class InfixConverterTest : public ::testing::Test {
protected:
static constexpr std::pair add{"+", Symbol::Add};
static constexpr std::pair subtract{"-", Symbol::Subtract};
static constexpr std::pair divide{"/", Symbol::Divide};
static constexpr std::pair multiply{"*", Symbol::Multiply};
static constexpr std::pair power{"^", Symbol::Power};
static constexpr std::pair parenthesisOpen{"(", Symbol::ParenthesisOpen};
static constexpr std::pair parenthesisClose{")", Symbol::ParenthesisClose};
BasicElementCreator creator{
{
add,
subtract,
multiply,
divide,
power,
parenthesisOpen,
parenthesisClose
}
};
EquationParser parser{std::make_shared<BasicElementCreator>(creator)};
InfixConverter converter{std::make_shared<EquationParser>(parser)};
static bool compareQueues(std::queue<Element> expected, std::queue<Element> actual){
if(expected.size() != actual.size()){
return false;
}
while(!expected.empty()){
const auto& left = expected.front();
const auto& right = actual.front();
if(left.getValue() != right.getValue() || left.getSymbol() != right.getSymbol()){
return false;
}
expected.pop();
actual.pop();
}
return true;
};
static std::queue<Element> queueFromVector(const std::vector<Element>& vec){
std::queue<Element> result;
for(const auto& elem : vec) {
result.push(elem);
}
return result;
}
InfixConverterTest()= default;
~InfixConverterTest() override = default;
void SetUp() override {};
void TearDown() override {};
};
TEST_F(InfixConverterTest, smoke) {
std::vector<Element> equation = { creator.createElement("2") };
auto expected{queueFromVector(equation)};
EXPECT_TRUE(compareQueues(expected, converter.convertToQueue(equation)));
}
TEST_F(InfixConverterTest, GivenPostfixEquation22PlusConvertToQueueReturns2Plus2) {
std::vector<Element> equation{
creator.createElement("2"),
creator.createElement("2"),
creator.createElement("+")
};
std::queue<Element> expected{ queueFromVector({
creator.createElement("("),
creator.createElement("2"),
creator.createElement("+"),
creator.createElement("2"),
creator.createElement(")")
})};
EXPECT_TRUE(compareQueues(expected, converter.convertToQueue(equation)));
}
TEST_F(InfixConverterTest, GivenInfixEquationConvertToQueueReturnsLogicError) {
std::vector<Element> equation{
creator.createElement("2"),
creator.createElement("+"),
creator.createElement("2")
};
EXPECT_THROW(converter.convertToQueue(equation), std::logic_error);
}
TEST_F(InfixConverterTest, GivenInfixEquationCheckReturnsFalse) {
std::vector<Element> equation{
creator.createElement("2"),
creator.createElement("+"),
creator.createElement("2")
};
EXPECT_FALSE(converter.check(equation));
}
TEST_F(InfixConverterTest, GivenPostfixEquationCheckReturnsTrue) {
std::vector<Element> equation{
creator.createElement("2"),
creator.createElement("2"),
creator.createElement("+")
};
EXPECT_TRUE(converter.check(equation));
}
TEST_F(InfixConverterTest, Given22PlusEquationConvertToStringReturns2Plus2InsideParentheses) {
std::vector<Element> equation{
creator.createElement("2"),
creator.createElement("2"),
creator.createElement("+")
};
auto expected{"(2+2)"};
EXPECT_EQ(converter.convertToString(equation), expected);
}
TEST_F(InfixConverterTest, GivenEquationWithoutOperatorBetweenTwoParenthesesCheckReturnsFalse){
std::vector<Element> equation{
creator.createElement("1.55"), creator.createElement("+"),
creator.createElement("("), creator.createElement("3.75"),
creator.createElement(")"), creator.createElement("("),
creator.createElement("("), creator.createElement("8.23"),
creator.createElement("+"), creator.createElement("1"),
creator.createElement(")"), creator.createElement("/"),
creator.createElement("3"), creator.createElement(")")
};
auto actual(converter.check(equation));
EXPECT_FALSE(actual);
}
TEST_F(InfixConverterTest, GivenPostfixEquation22PowerConvertToQueueReturns2ToThePowerOf2) {
std::vector<Element> equation{
creator.createElement("2"),
creator.createElement("2"),
creator.createElement("^")
};
std::queue<Element> expected{ queueFromVector({
creator.createElement("("),
creator.createElement("2"),
creator.createElement("^"),
creator.createElement("2"),
creator.createElement(")")
})};
EXPECT_TRUE(compareQueues(expected, converter.convertToQueue(equation)));
}
TEST_F(InfixConverterTest, GivenComplexPostfixEquationWithPowersConvertToQueueReturnsCorrectEquation) {
// 9 2 ^ 5 12 * / 10 24 13 2 + / 1 - ^ +
std::vector<Element> equation{
creator.createElement("9"), creator.createElement("2"),
creator.createElement("^"), creator.createElement("5"),
creator.createElement("12"), creator.createElement("*"),
creator.createElement("/"), creator.createElement("10"),
creator.createElement("24"), creator.createElement("13"),
creator.createElement("2"), creator.createElement("+"),
creator.createElement("/"), creator.createElement("1"),
creator.createElement("-"), creator.createElement("^"),
creator.createElement("+")
};
// (((9 ^ 2) / (5 * 12)) + (10 ^ ((24 / (13 + 2)) - 1)))
std::queue<Element> expected{ queueFromVector({
creator.createElement("("), creator.createElement("("),
creator.createElement("("), creator.createElement("9"),
creator.createElement("^"), creator.createElement("2"),
creator.createElement(")"), creator.createElement("/"),
creator.createElement("("), creator.createElement("5"),
creator.createElement("*"), creator.createElement("12"),
creator.createElement(")"), creator.createElement(")"),
creator.createElement("+"), creator.createElement("("),
creator.createElement("10"), creator.createElement("^"),
creator.createElement("("), creator.createElement("("),
creator.createElement("24"), creator.createElement("/"),
creator.createElement("("), creator.createElement("13"),
creator.createElement("+"), creator.createElement("2"),
creator.createElement(")"), creator.createElement(")"),
creator.createElement("-"), creator.createElement("1"),
creator.createElement(")"), creator.createElement(")"),
creator.createElement(")")
})};
EXPECT_TRUE(compareQueues(expected, converter.convertToQueue(equation)));
} | true |
e9866093a6afc63300d0bedaa405abcd5cee49b6 | C++ | newenclave/bitchain-test | /varint.h | UTF-8 | 4,359 | 2.90625 | 3 | [] | no_license | #ifndef VARINT_H
#define VARINT_H
#include <string>
#include "byte_order.h"
#include "etool/details/byte_order.h"
namespace bchain {
struct varint {
typedef std::uint64_t size_type;
static const std::size_t min_length = sizeof(std::uint8_t);
static const std::size_t max_length = sizeof(size_type) + min_length;
using u16_little = etool::details::byte_order_little<std::uint16_t>;
using u32_little = etool::details::byte_order_little<std::uint32_t>;
using u64_little = etool::details::byte_order_little<std::uint64_t>;
enum prefix_value {
PREFIX_VARINT_MIN = 0xFD,
PREFIX_VARINT16 = 0xFD,
PREFIX_VARINT32 = 0xFE,
PREFIX_VARINT64 = 0xFF,
PREFIX_VARINT_MAX = 0xFF,
};
static
std::size_t len_by_prefix( std::uint8_t prefix )
{
switch (prefix) {
case PREFIX_VARINT64:
return sizeof(std::uint64_t) + min_length;
case PREFIX_VARINT32:
return sizeof(std::uint32_t) + min_length;
case PREFIX_VARINT16:
return sizeof(std::uint16_t) + min_length;
default:
break;
}
return min_length;
}
static
std::size_t result_length( size_type len )
{
if( len < PREFIX_VARINT_MIN ) {
return sizeof(std::uint8_t);
} else if( len <= 0xFFFF ) {
return sizeof(std::uint16_t) + min_length;
} else if( len <= 0xFFFFFFFF ) {
return sizeof(std::uint32_t) + min_length;
} else {
return sizeof(std::uint64_t) + min_length;
}
}
static
std::size_t packed_length( const void *data, size_t len )
{
if( len > 0 ) {
auto u8 = *static_cast<const std::uint8_t *>(data);
auto res = len_by_prefix(u8);
return (res >= len) ? res : 0;
}
return 0;
}
template <typename U>
static
std::size_t write( size_type size, U *result )
{
std::uint8_t *res = reinterpret_cast<std::uint8_t *>(result);
if( size < PREFIX_VARINT_MIN ) {
res[0] = static_cast<std::uint8_t>(size);
return min_length;
} else if( size <= 0xFFFF ) {
res[0] = static_cast<std::uint8_t>(PREFIX_VARINT16);
return u16_little::write( size, &res[1] ) + min_length;
} else if( size <= 0xFFFFFFFF ) {
res[0] = static_cast<std::uint8_t>(PREFIX_VARINT32);
return u32_little::write( size, &res[1] ) + min_length;
} else {
res[0] = static_cast<std::uint8_t>(PREFIX_VARINT64);
return u64_little::write( size, &res[1] ) + min_length;
}
}
static
void append( size_type size, std::string &res )
{
std::size_t last = res.size( );
res.resize(last + result_length(size));
write( size, &res[last] );
}
template <typename U>
static
size_type read( const U *data, size_t length, size_t *len )
{
const std::uint8_t *d = static_cast<const std::uint8_t *>(data);
length = length * sizeof(U);
std::size_t len_ = len_by_prefix( *d );
if( length < len_ ) {
return 0;
}
size_type res_ = 0;
if( len_ == min_length ) {
res_ = static_cast<size_type>(*d);
} else {
switch (*d) {
case PREFIX_VARINT16:
res_ = u16_little::read( d + min_length );
break;
case PREFIX_VARINT32:
res_ = u32_little::read( d + min_length );
break;
case PREFIX_VARINT64:
res_ = u64_little::read( d + min_length );
break;
default:
break;
}
}
if( len ) {
*len = len_;
}
return res_;
}
};
}
#endif // VARINT_H
| true |
d55c054170eab6d4fd5213b0f005c56ccd92223f | C++ | techtronics/blackhat | /src/mom_conf_inline.h | UTF-8 | 19,122 | 2.609375 | 3 | [] | no_license | #ifndef MOM_CONF_INLINE_H_
#define MOM_CONF_INLINE_H_
//! inserts a new momentum
/**
\param m complex momentum to be inserted
\return integer label of the inserted momentum
*/
int orderless_key2(int,int);
template <class T> inline const Cmom<T>& momentum_configuration<T>::p(size_t n) const {
if (n<=momentum_configuration<T>::nbr){
if ( n>_offset ) {
return momentum_configuration<T>::ps[n-_offset-1];
}
else
{
return _parent->p(n);
}
}
else{_WARNING5("Too large momentum index in sub_momentum_configuration::p: ",n," (max=",momentum_configuration<T>::nbr,")" );throw BHerror("Mom_conf error"); }
}
template <class T> inline std::complex<T> momentum_configuration<T>::m2(size_t n) const {
if (n<=momentum_configuration<T>::nbr){
if ( n>_offset ) {
return momentum_configuration<T>::ms[n-_offset-1];
}
else
{
return _parent->m2(n);
}
}
else{_WARNING5("Too large momentum index in sub_momentum_configuration::ms: ",n," (max=",momentum_configuration<T>::nbr,")" );throw BHerror("Mom_conf error"); }
}
template <class T> inline int momentum_configuration<T>::insert(const lambdat<T>& l1,const lambda<T>& l2){
return insert(Cmom<T>(l1,l2));
}
template <class T> inline int momentum_configuration<T>::insert(const momentum<std::complex<T> >& p){
return insert(Cmom<T>(p));
}
template <class T> inline int momentum_configuration<T>::insert(const momentum<std::complex<T> >& p,momentum_type type){
return insert(Cmom<T>(p,type));
}
template <class T> inline int momentum_configuration<T>::insert(const lambda<T>& l1,const lambdat<T>& l2){
return insert(Cmom<T>(l2,l1));
}
//! spinor product \<i j\>
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\return spinor product \<i j\> of the momenta with labels i and j
*/
// DAK 070925 Track sign, use orderless_key2
template <class T> inline std::complex<T> momentum_configuration<T>::spa(int i,int j){
#if _WITH_CACHING
if (i==j) return std::complex<T>(0.,0.);
int key=orderless_key2(i,j);
std::complex<T> res;
typename std::map<int,std::complex<T> >::iterator pos=Mspa.find(key);
T sign = (i < j) ? 1 : -1;
#if _CACHE_STATISTICS
find_and_stat<int,T>("Spa",key,Mspa, sign*p(i).L()*p(j).L() ,p(i).L()*p(j).L(),res );
#else
if (pos != Mspa.end()){
res = sign * pos->second ;
}
else {
res=p(i).L()*p(j).L();
Mspa.insert(pair<int,std::complex<T> >(key,sign*res));
}
#endif
return res;
#else
return p(i).L()*p(j).L();
#endif
}
//! spinor product [i j]
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\return spinor product [i j] of the momenta with labels i and j
*/
// DAK 070925 Track sign
template <class T> inline std::complex<T> momentum_configuration<T>::spb(int i,int j){
#if _WITH_CACHING
if (i==j) return std::complex<T>(0.,0.);
int key=orderless_key2(i,j);
std::complex<T> res;
T sign = (i < j) ? 1 : -1;
#if _CACHE_STATISTICS==0
find_and_stat<int,T>("Spb",key,Mspb, sign*p(i).Lt()*p(j).Lt() ,p(i).Lt()*p(j).Lt(),res );
#else
typename std::map<int,std::complex<T> >::iterator pos=Mspb.find(key);
if (pos != Mspb.end()){
res = sign * pos->second ;
}
else {
res=p(i).Lt()*p(j).Lt();
Mspb.insert(pair<int,std::complex<T> >(key,sign*res));
}
#endif
return res;
#else
return p(i).Lt()*p(j).Lt();
#endif
}
//! spinor product \<i|j|k]
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\return spinor product <i|j|k] of the momenta with labels i, j and k
*/
template <class T> std::complex<T> momentum_configuration<T>::spab(int i,int j,int k){
if ((i==j)||(j==k)) return std::complex<T>(0.,0.);
#if _WITH_CACHING
std::complex<T> res;
std::string key=GenKey("spab",i,j,k);
#if _CACHE_STATISTICS
find_and_stat<std::string,T>("Spab",key,cache, L(i)*Sm(j)*Lt(k) ,L(i)*Sm(j)*Lt(k),res );
#else
typename hash_map<std::string, std::std::complex<T>, hash<std::string> >::iterator pos=cache.find(key);
if (pos != cache.end()) {
res=pos->second;
}
else {
res=L(i)*Sm(j)*Lt(k);
cache[key]=res;
}
#endif
return res;
#else
return L(i)*Sm(j)*Lt(k);
#endif
}
//! spinor product \<i|p1+p2+...+pn|k] for a sum of vectors
/**
The slashed matrix inserted in the spinor product corresponds to the sum of the momenta with the labels from the vector v. The values are computed once and cached for later use.
\param i integer label of the first momentum
\param v vector of integer labels
\param k integer label of the third momentum
\return spinor product <i|p1+...+pn|k] of the momenta with labels i,{p1,...,pn} and k
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spab(int i,const std::vector<int>& v,int k){
return this->spab(i,Sum(v),k);
}
//! spinor product \<i|p1+p2+...+pn|k] for a sum of the vectors represented by the plabels in v
/**
The slashed matrix inserted in the spinor product corresponds to the sum of the momenta with the labels from the plabel vector v. The values are computed once and cached for later use.
\param i integer label of the first momentum
\param v vector of plabels
\param k integer label of the third momentum
\return spinor product <i|p1+...+pn|k] of the momenta with labels i,{p1,...,pn} and k
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spab(int i,const std::vector<plabel>& v,int k){
return this->spab(i,Sum(v),k);
}
//! spinor product [i|p1+p2+...+pn|k\> for a sum of vectors
/**
The slashed matrix inserted in the spinor product corresponds to the sum of the momenta with the labels from the vector v. The values are computed once and cached for later use.
\param i integer label of the first momentum
\param v vector of integer labels
\param k integer label of the third momentum
\return spinor product [i|p1+...+pn|k\> of the momenta with labels i,{p1,...,pn} and k
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spba(int i,const std::vector<int>& v,int k){
return this->spba(i,Sum(v),k);
}
//! spinor product [i|p1+p2+...+pn|k\> for a sum of the vectors represented by the plabels in v
/**
The slashed matrix inserted in the spinor product corresponds to the sum of the momenta with the labels from the plabel vector v. The values are computed once and cached for later use.
\param i integer label of the first momentum
\param v vector of plabels
\param k integer label of the third momentum
\return spinor product [i|p1+...+pn|k\> of the momenta with labels i,{p1,...,pn} and k
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spba(int i,const std::vector<plabel>& v,int k){
return this->spba(i,Sum(v),k);
}
//! spinor product \[i|j|k>
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\return spinor product [i|j|k> of the momenta with labels i, j and k
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spba(int i,int j,int k){
if ((i==j)||(j==k)) return std::complex<T>(0.,0.);
return momentum_configuration<T>::spab(k,j,i);
}
//! spinor product \<i|j|k|l\>
/**
the values are cached
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the fourth momentum
\return spinor product \<i|j|k|l\> of the momenta with labels i, j, k and l
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spaa(int i,int j,int k ,int l){
if ((i==j)||(k==l)) return std::complex<T>(0.,0.);
#if _WITH_CACHING
std::string key=GenKey("spaa",i,j,k,l);
complex<T> res;
#if _CACHE_STATISTICS
find_and_stat("Spaa4", key,this , L(i)*Sm(j)*Sm(k)*L(l),L(i)*Sm(j)*Sm(k)*L(l), res );
#else
if ( !get_value(key,res) ){
res=L(i)*Sm(j)*Sm(k)*L(l);
put_value(key,res);
}
#endif /* _CACHE_STATISTICS */
return res;
#else
return L(i)*Sm(j)*Sm(k)*L(l);
#endif
}
//! spinor product [i|j|k|l]
/**
the values are cached
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the fourth momentum
\return spinor product [i|j|k|l] of the momenta with labels i, j, k and l
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spbb(int i,int j,int k ,int l){
if ((i==j)||(k==l)) return std::complex<T>(0.,0.);
#if _WITH_CACHING
std::string key=GenKey("spbb",i,j,k,l);
std::complex<T> res;
#if _CACHE_STATISTICS
find_and_stat("Spbb4", key,this ,p(i).Lt()*p(j).Sm()*p(k).Sm()*p(l).Lt(),p(i).Lt()*p(j).Sm()*p(k).Sm()*p(l).Lt(), res );
#else
if ( !get_value(key,res) ){
res= p(i).Lt()*p(j).Sm()*p(k).Sm()*p(l).Lt();
put_value(key,res);
}
#endif /* _CACHE_STATISTICS */
return res;
#else
return p(i).Lt()*p(j).Sm()*p(k).Sm()*p(l).Lt();
#endif
}
//! spinor product <i|j|k|l|m]
/**
the values are cached
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the fourth momentum
\param m integer label of the fifth momentum
\return spinor product <i|j|k|l|m] of the momenta with labels i, j, k, l and m
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spab(int i,int j,int k ,int l,int m){
if ((i==j)||(m==l)) return std::complex<T>(0.,0.);
#if _WITH_CACHING
std::complex<T> res;
std::string key=GenKey("spab",i,j,k,l,m);
#if _CACHE_STATISTICS
find_and_stat("Spab5", key,this ,L(i)*Sm(j)*Sm(k)*Sm(l)*Lt(m),L(i)*Sm(j)*Sm(k)*Sm(l)*Lt(m), res );
#else
typename hash_map<std::string, std::complex<T>, hash<std::string> >::iterator pos=cache.find(key);
if (pos != cache.end()) {
res=pos->second;
}
else {
res=L(i)*Sm(j)*Sm(k)*Sm(l)*Lt(m);
cache[key]=res;
}
#endif /* _CACHE_STATISTICS */
return res;
#else
return L(i)*Sm(j)*Sm(k)*Sm(l)*Lt(m);
#endif
}
//! spinor product [i|j|k|l|m>
/**
the values are cached
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the fourth momentum
\param m integer label of the fifth momentum
\return spinor product [i|j|k|l|m> of the momenta with labels i, j, k, l and m
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spba(int i,int j,int k ,int l,int m){
if ((i==j)||(m==l)) return std::complex<T>(0.,0.);
return spab(m,l,k,j,i);
}
//! spinor product \<i|j|k|l|m|n\>
/**
the values are cached
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the fourth momentum
\param m integer label of the fifth momentum
\param n integer label of the fifth momentum
\return spinor product \<i|j|k|l|m|n\> of the momenta with labels i, j, k, l, m and n
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spaa(int i,int j,int k ,int l,int m,int n){
if ((i==j)||(m==n)) return std::complex<T>(0.,0.);
#if _WITH_CACHING
std::complex<T> res;
std::string key=GenKey("spaa",i,j,k,l,m,n);
#if _CACHE_STATISTICS
find_and_stat("Spaa6", key,this ,L(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*L(n),L(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*L(n), res );
#else
typename hash_map<std::string, std::complex<T>, hash<std::string> >::iterator pos=cache.find(key);
if (pos != cache.end()) {
res=pos->second;
}
else {
res=L(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*L(n);
cache[key]=res;
}
#endif /* _CACHE_STATISTICS */
return res;
#else
return L(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*L(n);
#endif
// if ((i==j)||(m==n)) return 0;
// return p(i).L()*p(j).Sm()*p(k).Sm()*p(l).Sm()*p(m).Sm()*p(n).L();
}
//! spinor product [i|j|k|l|m|n]
/**
the values are cached
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the fourth momentum
\param m integer label of the fifth momentum
\param n integer label of the fifth momentum
\return spinor product [i|j|k|l|m|n] of the momenta with labels i, j, k, l, m and n
*/
template <class T> inline std::complex<T> momentum_configuration<T>::spbb(int i,int j,int k ,int l,int m,int n){
if ((i==j)||(m==l)) return std::complex<T>(0.,0.);
#if _WITH_CACHING
std::complex<T> res;
std::string key=GenKey("spbb",i,j,k,l,m,n);
#if _CACHE_STATISTICS
find_and_stat("Spbb6", key,this ,Lt(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*Lt(n),Lt(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*Lt(n), res );
#else
typename hash_map<std::string, std::complex<T>, hash<std::string> >::iterator pos=cache.find(key);
if (pos != cache.end()) {
res=pos->second;
}
else {
res=Lt(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*Lt(n);
cache[key]=res;
}
#endif /* _CACHE_STATISTICS */
return res;
#else
return Lt(i)*Sm(j)*Sm(k)*Sm(l)*Sm(m)*Lt(n);
#endif
}
//! invariant s(i,j)
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\return invariant (pi+pj)^2 of the momenta with labels i, j
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(int i,int j){
// it makes only sense to push the sum of the four vectors into the mom_conf if it is cachedd and we have a chance to reuse it
#if _WITH_CACHING
return m2(Sum(i,j));
#if _CACHE_STATISTICS
find_and_stat<int,T>("S(i,j)",key,Mspa, sign*p(i).L()*p(j).L() ,p(i).L()*p(j).L(),res );
#endif
#else
momentum<std::complex<T> > p=mom(i)+mom(j); return p*p;
#endif
}
//! invariant s(i,j,k)
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\return invariant (pi+pj+pk)^2 of the momenta with labels i, j and k
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(int i,int j,int k){
// it makes only sense to push the sum of the four vectors into the mom_conf if it is cachedd and we have a chance to reuse it
#if _WITH_CACHING
return m2(Sum(i,j,k));
#if _CACHE_STATISTICS
find_and_stat<int,T>("S(i,j,k)",key,Mspa, sign*p(i).L()*p(j).L() ,p(i).L()*p(j).L(),res );
#endif
#else
momentum<std::complex<T> > p=mom(i)+mom(j)+mom(k); return p*p;
#endif
}
//! invariant s(i,j,k,l)
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the third momentum
\return invariant (pi+pj+pk+pl)^2 of the momenta with labels i, j, k and l
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(int i,int j,int k,int l){
// it makes only sense to push the sum of the four vectors into the mom_conf if it is cachedd and we have a chance to reuse it
#if _WITH_CACHING
return m2(Sum(i,j,k,l));
#if _CACHE_STATISTICS
find_and_stat<int,T>("S(i,j,k,l)",key,Mspa, sign*p(i).L()*p(j).L() ,p(i).L()*p(j).L(),res );
#endif
#else
momentum<std::complex<T> > p=mom(i)+mom(j)+mom(k)+mom(l); return p*p;
#endif
}
//! invariant s(i,j,k,l,m)
/**
the values are computed once and cached for later use.
\param i integer label of the first momentum
\param j integer label of the second momentum
\param k integer label of the third momentum
\param l integer label of the third momentum
\return invariant (pi+pj+pk+pl+pm)^2 of the momenta with labels i, j, k, l and m
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(int i,int j,int k,int l,int m){
// it makes only sense to push the sum of the four vectors into the mom_conf if it is cachedd and we have a chance to reuse it
#if _WITH_CACHING
return m2(Sum(i,j,k,l,m));
#if _CACHE_STATISTICS
find_and_stat<int,T>("S(i,j,k,l)",key,Mspa, sign*p(i).L()*p(j).L() ,p(i).L()*p(j).L(),res );
#endif
#else
momentum<std::complex<T> > p=mom(i)+mom(j)+mom(k)+mom(l)+mom(m); return p*p;
#endif
}
//! invariant s for a set of momenta
/**
the values are computed once and cached for later use.
\param v vector of integer label of the momenta
\return invariant (p1+...+pn)^2 of the momenta labelled by the integers in the vector v.
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(const std::vector<int>& v){
#if _WITH_CACHING
return m2(Sum(v));
#else
momentum<std::complex<T> > sum(std::complex<T>(0.,0.),std::complex<T>(0.,0.),std::complex<T>(0.,0.),std::complex<T>(0.,0.));
for (size_t i=0;i< v.size();i++){
sum+=mom(v[i]);
}
return sum*sum;
#endif
}
//! invariant s for two sets of momenta
/**
the values are computed once and cached for later use.
\param v1 vector of integer label of the momenta
\param v2 vector of integer label of the momenta
\return invariant (p1+...+pn)^2 of the momenta labelled by the integers in the vector v.
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(const std::vector<int>& v1,const std::vector<int>& v2){
return m2(Sum(v1,v2));
}
//! invariant s for a set of momenta
/**
the values are computed once and cached for later use.
\param v1 vector of plabel of momenta
\param v2 vector of plabel of momenta
\return invariant (p1+...+pn)^2 of the momenta labelled by the plabels in the vector v.
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(const std::vector<plabel>& v1,const std::vector<plabel>& v2){
return m2(Sum(v1,v2));
}
//! invariant s for a set of momenta
/**
the values are computed once and cached for later use.
\param v vector of plabel of momenta
\return invariant (p1+...+pn)^2 of the momenta labelled by the plabels in the vector v.
*/
template <class T> inline std::complex<T> momentum_configuration<T>::s(const std::vector<plabel>& v){
return m2(Sum(v));
}
//! scalar product p.q
/**
\param i integer label of the first momentum
\param j integer label of the second momentum
\return the scalar product pi.pj of the momenta with labels i, j
*/
template <class T> inline std::complex<T> momentum_configuration<T>::sp(int i,int j){
return p(i).P()*p(j).P();
}
//! puts a std::complex value in the cache
/** Puts a value into the cache. It there is already a value, the old value is overwritten. The key can be generated wit GenKey \sa GenKey \sa put_label \sa get_value*/
template <class T> inline void momentum_configuration<T>::put_value(const std::string& key, std::complex<T> &value){
cache[key]=value;
}
//! puts a label in the cache
/** Puts the new label into the label cache. It there is already a label with this key, the old label is overwritten. The key can be generated wit GenKey \sa GenKey \sa put_label \sa get_label*/
template <class T> inline void momentum_configuration<T>::put_label(const std::string& key,size_t &value){
labelscache[key]=value;
}
#endif /*MOM_CONF_INLINE_H_*/
| true |
7e0b755e5d2a1ea8a8dbee0d49d68c6c7663e7c6 | C++ | paullewallencom/cocos2d-978-1-7839-8526-5 | /_src/Chapter 8/Classes/Environment.cpp | UTF-8 | 4,140 | 2.796875 | 3 | [] | no_license | #include "Environment.h"
Environment::Environment()
{}
Environment::~Environment()
{}
Environment* Environment::create()
{
Environment* environment = new Environment();
if(environment && environment->init())
{
environment->autorelease();
return environment;
}
CC_SAFE_DELETE(environment);
return NULL;
}
bool Environment::init()
{
if(!CCNode::init())
return false;
CreateSky();
CreateHills();
CreatePier();
CreateBoat();
return true;
}
void Environment::CreateSky()
{
// create the blue gradient for the sky that is half the size of the screen
CCLayerGradient* sky = CCLayerGradient::create(ccc4(135, 219, 255, 255), ccc4(158, 245, 255, 255));
sky->setContentSize(CCSizeMake(SCREEN_SIZE.width, SCREEN_SIZE.height * 0.5f));
sky->setPosition(ccp(0, SCREEN_SIZE.height * 0.5f));
addChild(sky);
// create clouds
CreateCloud(120.0f, "CH_04.png");
CreateCloud(130.0f, "CH_04.png");
CreateCloud(120.0f, "CH_03.png");
CreateCloud(130.0f, "CH_03.png");
CreateCloud(100.0f, "CH_02.png");
CreateCloud(95.0f, "CH_01.png");
// create the blue gradient for the water that is half the size of the screen
CCLayerGradient* water = CCLayerGradient::create(ccc4(63, 159, 183, 255), ccc4(104, 198, 184, 255));
water->setContentSize(CCSizeMake(SCREEN_SIZE.width, SCREEN_SIZE.height * 0.5f));
addChild(water);
}
void Environment::CreateCloud(float duration, const char* frame_name)
{
// randomly position the clouds in the upper half of the screen
CCPoint position = ccp(SCREEN_SIZE.width * CCRANDOM_0_1(), 450.0f + SCREEN_SIZE.height * 0.45f * CCRANDOM_0_1());
CCSprite* cloud = CCSprite::create(frame_name);
cloud->setPosition(position);
addChild(cloud);
// duration 1 -> move from starting point to left edge of screen
float duration1 = (position.x / (SCREEN_SIZE.width + cloud->getContentSize().width)) * duration;
// duration 2 -> move from right edge of screen to starting point
float duration2 = duration - duration1;
// animate the cloud's movement -> start point-TO-left edge-TO-right edge-TO-start point
CCMoveTo* move_left1 = CCMoveTo::create(duration1, ccp(-cloud->getContentSize().width, position.y));
CCPlace* place_right = CCPlace::create(ccp(SCREEN_SIZE.width + cloud->getContentSize().width, position.y));
CCMoveTo* move_left2 = CCMoveTo::create(duration2, position);
CCSequence* cloud_movement = CCSequence::create(move_left1, place_right, move_left2, NULL);
// repeat forever
cloud->runAction(CCRepeatForever::create(cloud_movement));
}
void Environment::CreateHills()
{
ccTexParams tex_params;
// setup the hill texture to repeat
tex_params.minFilter = GL_NEAREST;
tex_params.magFilter = GL_NEAREST;
tex_params.wrapS = GL_REPEAT;
tex_params.wrapT = GL_REPEAT;
CCSprite* hills = CCSprite::create("bg_03.png");
hills->getTexture()->setTexParameters(&tex_params);
hills->setTextureRect(CCRectMake(0, 0, SCREEN_SIZE.width, hills->getContentSize().height));
hills->setPosition(ccp(SCREEN_SIZE.width * 0.5f, SCREEN_SIZE.height * 0.53f));
addChild(hills);
}
void Environment::CreatePier()
{
// create two pillars for the pier
CCSprite* pier_base_pillar = NULL;
pier_base_pillar = CCSprite::create("platform_banboo2.png");
pier_base_pillar->setPosition(ccp(780.0f, 0.0f));
addChild(pier_base_pillar);
pier_base_pillar = CCSprite::create("platform_banboo2.png");
pier_base_pillar->setPosition(ccp(1100.0f, 0.0f));
addChild(pier_base_pillar);
// create a batch node for the pier floor
CCSpriteBatchNode* pier_base_batch = CCSpriteBatchNode::create("platform_base.png", 10);
addChild(pier_base_batch);
CCPoint offset = ccp(SCREEN_SIZE.width, SCREEN_SIZE.height * 0.2f);
for(int i = 0; i < 10; ++i)
{
CCSprite* pier_base = CCSprite::create("platform_base.png");
pier_base->setPosition(ccp(offset.x - (i * 65), offset.y));
pier_base_batch->addChild(pier_base);
}
}
void Environment::CreateBoat()
{
// the launch boat
CCSprite* boat = CCSprite::create("boat_base.png");
boat->setPosition(ccp(25.0f, 100.0f));
addChild(boat);
}
| true |
31b1a37a715391faf83539d373263c5c6addc154 | C++ | iCoder0020/Competitive-Coding | /USACO/sprime.cpp | UTF-8 | 741 | 2.578125 | 3 | [] | no_license | /*
ID: ishansa2
PROG: sprime
LANG: C++
*/
#include <bits/stdc++.h>
using namespace std;
ofstream fout("sprime.out");
ifstream fin("sprime.in");
#define int long long
#define INF 1LL<<32
vector<int>ans;
int N;
void solve(int x, int i)
{
bool push = true;
for(int j = 2; j*j<=x; j++)
{
if(x%j == 0)
{
push = false;
break;
}
}
if(!push)
return;
if(i == N)
{
ans.push_back(x);
return;
}
for(int j = 1; j<=9; j+=2)
{
if(j == 5)
continue;
solve(x*10+j, i+1);
}
}
int32_t main()
{
fin>>N;
vector<int>primes = {2,3,5,7};
for(auto it: primes)
solve(it, 1);
sort(ans.begin(), ans.end());
for(auto it: ans)
fout<<it<<endl;
return 0;
} | true |
a31a87a87cba3e10542703d4db86b4085ebdc3c2 | C++ | Sookmyung-Algos/2021algos | /algos_semina/4th_seminar/seminar_3/2nd_grade/정영주_yeongjujeong1021/3474.cpp | UTF-8 | 332 | 2.6875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t, n, a, b;
cin >> t;
while (t--) {
a = 0, b = 0;
cin >> n;
for (int i = 2; i <= n; i *= 2) a += n / i;
for (int i = 5; i <= n; i *= 5) b += n / i;
cout << min(a, b) << '\n';
}
return 0;
}
| true |
57f39418661538f6ea4175b95df8b7d61930c79e | C++ | 0general/practice-cpp | /cpp100/cpp17/string.cpp | UTF-8 | 319 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
string my_country = "korea";
string my_jop = "developer";
cout << "Country : " << my_country << endl;
cout << "Job : " << my_jop << endl;
string my_info = my_country + ", " + my_jop;
cout << "My Info : " << my_info << endl;
return 0;
} | true |
0bd72bfaf62200bf33eec325c32e3338f13d3d8a | C++ | weigewansui/Hashtable | /satdata.h | UTF-8 | 1,083 | 2.765625 | 3 | [] | no_license | /**
* satdata.h
*
* AE552 HW2
* Wei Ding
* 03597803
*/
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
template <class KEY, class VALUE>
struct HASHTABLE {
KEY key;
VALUE value;
struct HASHTABLE* next;
};
struct Key {
string name;
string country;
string owner;
};
// struct orb_element{
// double Long;
// int perigee;
// int apog;
// double ecce;
// double incl;
// double period;
// };
struct orb_element{
string Long;
string perigee;
string apog;
string ecce;
string incl;
string period;
};
struct Value {
string country;
string owner;
string purpose;
string orbit_class;
//structure of orbital elements;
orb_element orb;
};
template <class KEY, class VALUE>
VALUE get(HASHTABLE<KEY,VALUE> *ht, KEY k);
template <class KEY,class VALUE>
bool contains(HASHTABLE<KEY,VALUE> *ht, KEY k);
template <class KEY, class VALUE>
void put(HASHTABLE<KEY,VALUE> *ht, KEY k, VALUE v);
template <class KEY,class VALUE>
int hashfunc(HASHTABLE <KEY,VALUE> *ht, KEY k);
template <class KEY>
bool isequal(KEY k1, KEY k2);
| true |
337e2f823d6dd1e2c01cdf192c4a5113c728c0f4 | C++ | tanejamohit/CodepathIBit | /BinarySearchAndHeaps/DistinctNumbersInWindow.cpp | UTF-8 | 622 | 2.59375 | 3 | [] | no_license | vector<int> Solution::dNums(vector<int> &A, int B) {
vector<int> result;
std::unordered_map<int, int> seen;
int pos = 0;
while(pos<B) {
if (seen.find(A[pos]) == seen.end()) { seen[A[pos]] = 0; }
seen[A[pos]] += 1;
pos++;
}
while(pos<=A.size()) {
result.push_back(seen.size());
if (seen[A[pos-B]] == 1) {
seen.erase(seen.find(A[pos-B]));
}
else {
seen[A[pos-B]] -= 1;
}
if (seen.find(A[pos]) == seen.end()) { seen[A[pos]] = 0; }
seen[A[pos]] += 1;
pos++;
}
return result;
}
| true |
a0d6d8adf89ef1a478da898c9fe4bf330b337b75 | C++ | RDDiaz/Stock-Trading-Simulation | /blsh_strategy.h | UTF-8 | 569 | 2.640625 | 3 | [] | no_license | #ifndef _BLSH_STRATEGY_H
#define _BLSH_STRATEGY_H
#include "trading_strategy.h"
namespace csis3700{
class blsh_strategy : virtual public trading_strategy
{
private:
int red_bar_count;
int red_limit;
int buy_count;
public:
blsh_strategy();
virtual void process_bar(price_bar b);
virtual int quantity_to_buy() const;
virtual int quantity_to_sell() const;
virtual void set_buy_count(int bc);
virtual int get_buy_cout() const
{
return buy_count;
}
};
}
#endif // _BLSH_STRATEGY_H
| true |
189e7ee8f65438a087ea9fc2b9273bd468861072 | C++ | AdrianNostromo/CodeSamples | /CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/base/exceptions/NotImplementedException.h | UTF-8 | 291 | 2.578125 | 3 | [] | no_license | #pragma once
#include <exception>
#include "Exception.h"
struct NotImplementedException : public Exception {
public:
NotImplementedException()
: Exception()
{
//void
}
const char * what() const throw () {
return "NotImplementedException";
}
};
| true |
eaf875adcfecbdc8f766bf8c46ab5a230c1ac905 | C++ | Eugene851001/MovingSprite | /Player.cpp | UTF-8 | 2,032 | 3.03125 | 3 | [] | no_license | #include "Player.h"
#include <cmath>
Player::Player(int x, int y, int width, int height, float speed, HANDLE hndSprite, RECT window)
{
this->x= x;
this->y = y;
this->width = width;
this->height= height;
this->speed = speed;
this->window = window;
angle = 0;
scale = 1;
GetObject(hndSprite, sizeof(BITMAP), &Bmp);
}
void Player::moveRight(float time)
{
int newX = x + speed * time;
if(newX + width * scale/ 2 < window.right - window.left)
x = newX;
}
void Player::moveLeft(float time)
{
int newX = x - speed * time;
if(newX - width * scale / 2 > 0)
x = newX;
}
void Player::moveDown(float time)
{
int newY = y + speed * time;
if(newY + height * scale/ 2 < window.bottom - window.top)
y = newY;
}
void Player::moveUp(float time)
{
int newY = y - speed * time;
if(newY - height * scale / 2 > 0)
y = newY;
}
int Player::getX()
{
return x;
}
int Player::getY()
{
return y;
}
int Player::getWidth()
{
return width;
}
int Player::getHeight()
{
return height;
}
void Player::drawPlayer(HDC memDC, HWND hWnd, HANDLE hndSprite)
{
showBitmap(memDC, hndSprite);
// ReleaseDC(hWnd, hdc);
}
void Player::showBitmap(HDC winDC, HANDLE hndSprite)
{
HDC memDC = CreateCompatibleDC(winDC);
SelectObject(memDC, hndSprite);
StretchBlt(winDC, x - width * scale / 2, y - height *scale / 2,
width * scale, height * scale, memDC, 0, 0, Bmp.bmWidth, Bmp.bmHeight, SRCCOPY);
DeleteDC(memDC);
}
void Player::rotateRight(float deltaAngle)
{
angle += deltaAngle;
}
void Player::rotateLeft(float deltaAngle)
{
angle -= deltaAngle;
}
void Player::changeScale(float deltaScale)
{
this->scale += deltaScale;
if(scale < 1)
scale = 1;
}
void Player::checkForBorders(RECT window)
{
if(x + width * scale / 2 > window.right)
x = window.right - width / 2;
if(x - width * scale/ 2 < 0)
x = width / 2;
if(y + height * scale / 2 > window.bottom)
y = window.bottom - height / 2;
if(y - height * scale / 2 < 0)
y = height / 2;
}
void Player::setWindow(RECT window)
{
this->window = window;
}
| true |
0f03ab481a33d1be42b2c7fd9b219abd488f007d | C++ | tmdarwen/ArmCortexSynth | /Tests/AudioGeneration-UT/WaveFileWriter.cpp | UTF-8 | 7,327 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <AudioGeneration-UT/WaveFileWriter.h>
#include <AudioGeneration-UT/Exception.h>
WaveFileWriter::WaveFileWriter(const std::string& filename, std::size_t sampleRate) :
filename_{filename}, sampleRate_{sampleRate}, sampleCount_{0}
{
fileStream_.open(filename_, std::ios::out | std::ios::binary);
if(!fileStream_.is_open())
{
throw Exception("Failed to open wave file for writing");
}
// Write some blank space for the wave header. (The actual wave header will be written when the file is closed as
// we don't know some of the values until we're ready to close the file).
uint8_t blankSpace[sizeof(WaveHeader)];
fileStream_.write(reinterpret_cast<const char*>(blankSpace), sizeof(WaveHeader));
if(!fileStream_.good())
{
throw Exception("Failed to write blank data to wave file header");
}
}
WaveFileWriter::~WaveFileWriter()
{
WriteWaveHeader();
fileStream_.close();
}
void WaveFileWriter::AppendAudioData(uint16_t* buffer, std::size_t bufferSize)
{
// Note that the audio output to the DAC of the synthesizer uses unsigned 16 bit sample values
// that range from 0 to 65536 but the wave file format uses signed values that range from
// -32768 to 32767.
const int32_t conversionFactorFromUnsignedToSign(32768);
if(bufferSize == 0)
{
return;
}
for(std::size_t i = 0; i < bufferSize; ++i)
{
int16_t convertedSampleValue = (buffer[i] - conversionFactorFromUnsignedToSign);
fileStream_.write(reinterpret_cast<const char*>(&convertedSampleValue), sizeof(int16_t));
if(!fileStream_.good())
{
throw Exception("Failed to write the wave file");
}
}
sampleCount_ += bufferSize;
}
/*
The following info comes from http://soundfile.sapp.org/doc/WaveFormat/
The canonical WAVE format starts with the RIFF header:
0 4 ChunkID Contains the letters "RIFF" in ASCII form
(0x52494646 big-endian form).
4 4 ChunkSize 36 + SubChunk2Size, or more precisely:
4 + (8 + SubChunk1Size) + (8 + SubChunk2Size)
This is the size of the rest of the chunk
following this number. This is the size of the
entire file in bytes minus 8 bytes for the
two fields not included in this count:
ChunkID and ChunkSize.
8 4 Format Contains the letters "WAVE"
(0x57415645 big-endian form).
The "WAVE" format consists of two subchunks: "fmt " and "data":
The "fmt " subchunk describes the sound data's format:
12 4 Subchunk1ID Contains the letters "fmt "
(0x666d7420 big-endian form).
16 4 Subchunk1Size 16 for PCM. This is the size of the
rest of the Subchunk which follows this number.
20 2 AudioFormat PCM = 1 (i.e. Linear quantization)
Values other than 1 indicate some
form of compression.
22 2 NumChannels Mono = 1, Stereo = 2, etc.
24 4 SampleRate 8000, 44100, etc.
28 4 ByteRate == SampleRate * NumChannels * BitsPerSample/8
32 2 BlockAlign == NumChannels * BitsPerSample/8
The number of bytes for one sample including
all channels. I wonder what happens when
this number isn't an integer?
34 2 BitsPerSample 8 bits = 8, 16 bits = 16, etc.
2 ExtraParamSize if PCM, then doesn't exist
X ExtraParams space for extra parameters
The "data" subchunk contains the size of the data and the actual sound:
36 4 Subchunk2ID Contains the letters "data"
(0x64617461 big-endian form).
40 4 Subchunk2Size == NumSamples * NumChannels * BitsPerSample/8
This is the number of bytes in the data.
You can also think of this as the size
of the read of the subchunk following this
number.
44 * Data The actual sound data.
*/
void WaveFileWriter::WriteWaveHeader()
{
WaveHeader waveHeader;
waveHeader.chunkID_[0] = 'R';
waveHeader.chunkID_[1] = 'I';
waveHeader.chunkID_[2] = 'F';
waveHeader.chunkID_[3] = 'F';
uint32_t subChunk2Size{static_cast<uint32_t>(sampleCount_) * static_cast<uint32_t>(sizeof(int16_t))};
uint32_t chunkSize{4 + (8 + SIZE_OF_SUBCHUNK1) + (8 + subChunk2Size)};
waveHeader.chunkSize_[0] = chunkSize & 0xFF;
waveHeader.chunkSize_[1] = (chunkSize >> 8) & 0xFF;
waveHeader.chunkSize_[2] = (chunkSize >> 16) & 0xFF;
waveHeader.chunkSize_[3] = (chunkSize >> 24) & 0xFF;
waveHeader.format_[0] = 'W';
waveHeader.format_[1] = 'A';
waveHeader.format_[2] = 'V';
waveHeader.format_[3] = 'E';
waveHeader.subChunk1ID_[0] = 'f';
waveHeader.subChunk1ID_[1] = 'm';
waveHeader.subChunk1ID_[2] = 't';
waveHeader.subChunk1ID_[3] = ' ';
waveHeader.subChunk1Size_[0] = SIZE_OF_SUBCHUNK1 & 0xFF;
waveHeader.subChunk1Size_[1] = (SIZE_OF_SUBCHUNK1 >> 8) & 0xFF;
waveHeader.subChunk1Size_[2] = (SIZE_OF_SUBCHUNK1 >> 16) & 0xFF;
waveHeader.subChunk1Size_[3] = (SIZE_OF_SUBCHUNK1 >> 24) & 0xFF;
waveHeader.audioFormat_[0] = PCM_AUDIO_FORMAT & 0xFF;
waveHeader.audioFormat_[1] = (PCM_AUDIO_FORMAT >> 8) & 0xFF;
waveHeader.channels_[0] = CHANNELS & 0xFF;
waveHeader.channels_[1] = 0;
waveHeader.sampleRate_[0] = sampleRate_ & 0xFF;
waveHeader.sampleRate_[1] = (sampleRate_ >> 8) & 0xFF;
waveHeader.sampleRate_[2] = (sampleRate_ >> 16) & 0xFF;
waveHeader.sampleRate_[3] = (sampleRate_ >> 24) & 0xFF;
uint32_t byteRate{static_cast<uint32_t>(sampleRate_) * static_cast<uint32_t>(sizeof(int16_t))};
waveHeader.byteRate_[0] = byteRate & 0xFF;
waveHeader.byteRate_[1] = (byteRate >> 8) & 0xFF;
waveHeader.byteRate_[2] = (byteRate >> 16) & 0xFF;
waveHeader.byteRate_[3] = (byteRate >> 24) & 0xFF;
uint32_t blockAlign{static_cast<uint32_t>(sizeof(int16_t))};
waveHeader.blockAlign_[0] = blockAlign & 0xFF;
waveHeader.blockAlign_[1] = (blockAlign >> 8) & 0xFF;
uint16_t bitsPerSample = sizeof(int16_t) * 8;
waveHeader.bitsPerSample_[0] = bitsPerSample & 0xFF;
waveHeader.bitsPerSample_[1] = (bitsPerSample >> 8) & 0xFF;
waveHeader.subChunk2ID_[0] = 'd';
waveHeader.subChunk2ID_[1] = 'a';
waveHeader.subChunk2ID_[2] = 't';
waveHeader.subChunk2ID_[3] = 'a';
waveHeader.subChunk2Size_[0] = subChunk2Size & 0xFF;
waveHeader.subChunk2Size_[1] = (subChunk2Size >> 8) & 0xFF;
waveHeader.subChunk2Size_[2] = (subChunk2Size >> 16) & 0xFF;
waveHeader.subChunk2Size_[3] = (subChunk2Size >> 24) & 0xFF;
fileStream_.seekp(0);
fileStream_.write(reinterpret_cast<const char*>(&waveHeader), sizeof(WaveHeader));
if(!fileStream_.good())
{
throw Exception("Failed to write wave file header");
}
}
| true |
46fa5f88fff35885050231bb40a3f11982c56f54 | C++ | Stephen321/FYP | /include/Camera.h | UTF-8 | 307 | 2.609375 | 3 | [] | no_license | #pragma once
#include "SFML\Graphics.hpp"
class Camera
{
public:
Camera();
void init(float windowWidth, float windowHeight, int moveSpeed);
sf::View getView() const;
void update(float dt);
void pollEvents(sf::Event evt);
private:
sf::View m_view;
float m_zoom;
bool m_zooming;
int m_moveSpeed;
}; | true |