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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fb40fc29224800a16a67ecaee051f254ce8d9403 | C++ | denisneuling/jserialport | /jserialport-native/src/main/cpp/JavaConverter.cc | UTF-8 | 1,203 | 2.875 | 3 | [] | no_license | #include "JavaConverter.h"
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
jobject JavaConverter::ArrayList_from_Vector_chars(JNIEnv *env, std::vector<char*> v){
jclass clazz = (*env).FindClass("java/util/ArrayList");
jobject list = (*env).NewObject(clazz, (*env).GetMethodID(clazz, "<init>", "()V"));
for(unsigned int i=0; i<v.size(); i++){
char* str = (char*) static_cast<char*>(v[i]);
jstring javaString = (*env).NewStringUTF(str);
(*env).CallBooleanMethod(list, (*env).GetMethodID(clazz, "add", "(Ljava/lang/Object;)Z"), javaString);
}
return list;
};
jobject JavaConverter::ArrayList_from_Vector_strings(JNIEnv *env, std::vector<std::string> v){
jclass clazz = (*env).FindClass("java/util/ArrayList");
jobject list = (*env).NewObject(clazz, (*env).GetMethodID(clazz, "<init>", "()V"));
for(unsigned int i=0; i<v.size(); i++){
const char* str = (char*) static_cast<const char*>(v[i].c_str());
jstring javaString = (*env).NewStringUTF(str);
(*env).CallBooleanMethod(list, (*env).GetMethodID(clazz, "add", "(Ljava/lang/Object;)Z"), javaString);
}
return list;
}; | true |
1a3e77072bdec0856b7178edf507ad31aebb7ff3 | C++ | fossabot/YAODAQ | /src/Exception.cpp | UTF-8 | 1,300 | 3.109375 | 3 | [
"MIT"
] | permissive | #include "Exception.hpp"
std::string Exception::m_Format{"\n\t[Code] : {Code}\n\t[Description] : {Description}\n\t[File] : {File}\n\t[Function] : {Function}\n\t[Line] : {Line}\n\t[Column] : {Column}\n"};
fmt::text_style Exception::m_Style={fg(fmt::color::crimson) | fmt::emphasis::bold};
Exception::Exception(const StatusCode& statusCode, std::string description,const source_location& location)
: source_location(location), m_Code(static_cast<std::int_least32_t>(statusCode)), m_Description(std::move(description))
{
constructMessage();
}
const char* Exception::what() const noexcept
{
return m_Message.c_str();
}
const char* Exception::description() const noexcept
{
return m_Description.c_str();
}
int_least32_t Exception::code() const noexcept
{
return m_Code;
}
Exception::Exception(const int_least32_t& code, std::string description,const source_location& location):source_location(location), m_Code(static_cast<int_least32_t>(code)), m_Description(std::move(description))
{
constructMessage();
}
void Exception::constructMessage()
{
m_Message = fmt::format(m_Style, m_Format, fmt::arg("Code", m_Code), fmt::arg("Description", m_Description), fmt::arg("File", file_name()), fmt::arg("Function", function_name()), fmt::arg("Column", column()), fmt::arg("Line", line()));
}
| true |
8d0b04fd54224448b040a71c2bea350e1a143ff3 | C++ | wowns9270/code_up | /codility/EquiLeader.cpp | UTF-8 | 692 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int solution(vector<int> A) {
map<int, int> arr;
for (int i = 0; i < A.size(); i++) {
int k = A[i];
if (arr.find(k) == arr.end()) {
arr[k] = 1;
}
else {
arr[k]++;
}
}
int r = 0;
int ret = 0;
for (auto it = arr.begin(); it != arr.end(); it++) {
if (r < it->second) {
r = it->second;
ret = it->first;
}
}
int cnt = 0;
int ans = 0;
for (int i = 0; i < A.size()-1; i++) {
if (A[i] == ret) {
cnt++;
}
int half_1 = (i + 1) / 2;
int half_2 = (A.size() - i - 1)/2;
if (half_1 < cnt && half_2 < r - cnt) ans++;
}
return ans;
}
int main() {
cout << solution({ 4,3,4,4,4,2 });
return 0;
} | true |
c0b92a01ec566cae87921841e21ca0a93b09184f | C++ | brendenforbes/CPP-and-Me | /JumblePuzzle/JumblePuzzle/jumble.cpp | UTF-8 | 6,459 | 3.65625 | 4 | [] | no_license |
#include <stdlib.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <time.h>
#include <ctime>
#include "jumble.h"
using namespace std;
//Bad Jumble Exception
BadJumbleException::BadJumbleException(const string & message) :message(message) {}
string & BadJumbleException::what() { return message; }
void JumblePuzzle::generateRandomPuzzle()
{
bool complete = true; //Bool variable to be used for placing target word
int randSize = this->size - 1; //Random number for the range of where to put the word.
string directions = "news"; //North East West South
string alphabet = "abcdefghijklmnopqrstuvwxyz"; //Alphabet
srand(time(NULL));
int direction = rand() % 3; //Random number between 0 and 3 ...indexes for the directions string
char move = directions[direction]; //pick a random direction
//Pick a random start row and start column
int row = rand() % randSize;
int column = rand() % randSize;
//Set private column and row attributes
this->rowPos = row;
this->colPos = column;
//Create new charArrayPtr*
charArrayPtr* jumbl = new charArrayPtr[this->size];
for (int i = 0; i < this->size; i++) {
jumbl[i] = new char[this->size + 1]; //Set each array in the charArrayPtr* to size+1 to compensate for the final NULL value
}
//Set each value to the null char
for (int i = 0; i < this->size; i++) {
for (int x = 0; x < this->size; x++) {
jumbl[i][x] = (char)0;
}
jumbl[i][this->size] = '\0';
}
//Length of the hidden word
int hiddenWordLength = this->toHide.size();
//Placing the characters for the target word;
//This algorithm works by placing the characters from the starting position and starting to place in a certain direction
//if the next index is out of bounds then choose a different direction and break from the for loop.
//else if all the words are placed then set the complete variable to false so the while loop terminates.
while (complete) { //While true
int y = row; //start row
int x = column;// start column
switch (move) { //recall: move was the direction you are placing the words
case 'n':
//Try to place all the characters in the upper direction
for (int j = 0; j < hiddenWordLength ; j++) {
if (y - j < 0) { //If y - j is out of bounds
move = directions[rand() % 3]; //Pick a new random direction
break; //Exit for loop
}
else
jumbl[y - j][x] = this->toHide[j]; //Add current char to position
if (j == hiddenWordLength - 1) //If able to add all characters
complete = !complete; //Set complete to false in order to terminate loop
}
break;
case 'e':
for (int j = 0; j < hiddenWordLength ; j++) {
if (x + j >= this->size) {
move = directions[rand() % 3];
break;
}
else
jumbl[y][x + j] = this->toHide[j];
if (j == hiddenWordLength - 1)
complete = !complete;
}
break;
case 'w':
for (int j = 0; j < hiddenWordLength ; j++) {
if (x - j < 0) {
move = directions[rand() % 3];
break;
}
else
jumbl[y][x - j] = this->toHide[j];
if (j == hiddenWordLength - 1)
complete = !complete;
}
break;
case 's':
for (int j = 0; j < hiddenWordLength ; j++) {
if (y + j >= this->size) {
move = directions[rand() % 3];
break;
}
else
jumbl[y + j][x] = this->toHide[j];
if (j == hiddenWordLength - 1)
complete = !complete;
}
break;
}
}
//set direction private attribute
this->direction = move;
//fill up array with random letters from the indexes that have null values
for (int y = 0; y < this->size; y++) {
for (int x = 0; x < this->size; x++) {
if (jumbl[y][x] == (char)0)
jumbl[y][x] = alphabet[rand() % 25];
}
}
//set jumble private attribute
this->jumble = jumbl;
}
JumblePuzzle::JumblePuzzle(const string & toHide, const string & difficulty):toHide(toHide)
{
int size = toHide.size(); //size of word
if (size < 3 || size > 10)
throw BadJumbleException("Size of the word to hide must be between 3 and 10!"); //Size of word must be between 3 and 10
if (difficulty != "easy" && difficulty != "medium" && difficulty != "hard")
throw BadJumbleException("This is not a valid difficulty!must choose from difficulties : \"easy\", \"medium\" or \"hard\" ");
else
this->difficulty = difficulty; //set difficulty
//Pick size
if (this->difficulty == "easy") {
this->size = 2 * size;
}
else if (this->difficulty == "medium") {
this->size = 3 * size;
}
else if (this->difficulty == "hard") {
this->size = 4 * size;
}
//generateRandomPuzzle!
generateRandomPuzzle();
}
JumblePuzzle::JumblePuzzle(const JumblePuzzle & right)
{
this->toHide = right.toHide;
this->difficulty = right.difficulty;
this->size = right.size;
this->rowPos = right.rowPos;
this->colPos = right.colPos;
this->direction = right.direction;
charArrayPtr* newJumble = new charArrayPtr[this->size];
for (int j = 0; j < this->size; j++) {
newJumble[j] = new char[this->size + 1];
}
for (int y = 0; y < this->size; y++) {
for (int x = 0; x < this->size + 1; x++) {
newJumble[y][x] = right.jumble[y][x];
}
}
this->jumble = newJumble;
}
JumblePuzzle::~JumblePuzzle()
{
for (int y = 0; y < this->size; y++) {
delete jumble[y];
jumble[y] = nullptr; //Destroy each pointer in the outer array
}
delete jumble;
jumble = nullptr;
}
JumblePuzzle & JumblePuzzle::operator=(const JumblePuzzle & right)
{
if (this != &right) {
for (int y = 0; y < this->size; y++) {
delete this->jumble[y];
this->jumble[y] = nullptr;
}
delete this->jumble;
jumble = nullptr;
this->toHide = right.toHide;
this->difficulty = right.difficulty;
this->size = right.size;
this->rowPos = right.rowPos;
this->colPos = right.colPos;
this->direction = right.direction;
jumble = new charArrayPtr[right.size];
for (int j = 0; j < right.size; j++)
jumble[j] = new char[right.size + 1];
for (int y = 0; y < this->size; y++) {
for (int x = 0; x < this->size + 1; x++) {
jumble[y][x] = right.jumble[y][x];
}
}
}
return *this;
}
//GETTERS
charArrayPtr * JumblePuzzle::getJumble()
{
return this->jumble;
}
const int JumblePuzzle::getSize()
{
return this->size;
}
const int JumblePuzzle::getRowPos()
{
return this->rowPos;
}
const int JumblePuzzle::getColPos()
{
return this->colPos;
}
const char JumblePuzzle::getDirection()
{
return this->direction;
}
| true |
89425464d36d64bf1b4e4a8f5a213bca00ba9e92 | C++ | lelelexxx/leetCode-ptrOffer | /ptrOffer/ptrOffer_31.cpp | GB18030 | 615 | 3.46875 | 3 | [] | no_license | //31,ջѹ뵯
class Solution {
public:
bool IsPopOrder(vector<int> pushV, vector<int> popV) {
reverse(popV.begin(), popV.end()); //pushVpopVתջֱͨӱȽջƺʱpopʱpush
reverse(pushV.begin(), pushV.end());
stack<int, vector<int>> popS(popV);
stack<int, vector<int>> pushS(pushV);
stack<int> temp;
while (!pushS.empty())
{
temp.push(pushS.top());
pushS.pop();
while (temp.top() == popS.top())
{
temp.pop();
popS.pop();
if (temp.empty() || popS.empty())
break;
}
}
return temp.empty();
}
}; | true |
30dc238ce37e361c6a5efbaacbc669e3fc54e204 | C++ | LucaZilli/Numerical-Simulation | /exercises/esercitazione10/esercizio10.2/esercizio10.2.cpp | UTF-8 | 7,134 | 2.734375 | 3 | [] | no_license | #include "GeneticAlgorithm.h"
#include <iostream>
#include <cmath>
#include "mpi.h"
using namespace std;
vector < vector<double> > ReadRows( const char* filename , int N,int M);
int main (int argc, char *argv[]){
int size, rank, itag=0;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Status stat1;
if(size != 4){
cerr<<endl<<"use 4 processors"<<endl;
return 1;
}
Random* rnd1;
rnd1=new Random;
//Random rnd;
int seed[4];
int p1, p2,t1,t2;
ifstream Primes("Primes");
if (Primes.is_open()){
for(int i=0; i<size; i++) {
Primes >> t1 >> t2;
if(rank==i) {
p1=t1;
p2=t2;
}
}
} else cerr << "PROBLEM: Unable to open Primes" << endl;
Primes.close();
ifstream input("seed.in");
string property;
if (input.is_open()){
while ( !input.eof() ){
input >> property;
if( property == "RANDOMSEED" ){
input >> seed[0] >> seed[1] >> seed[2] >> seed[3];
rnd1->SetRandom(seed,p1,p2);
}
}
input.close();
} else cerr << "PROBLEM: Unable to open seed.in" << endl;
//Initialization of the variables of the GA
int Npop=100;
int Ncity=32;
int Ngen=600;
int Nprocess=4;
int imigration=20;
vector <double> x_y;
int Bestsend[Ncity];
int Bestreceive[Ncity];
int order[Nprocess+1];
//Coordinates:
vector < vector <double> > coordinates_square;
coordinates_square=ReadRows("coordinates_square.txt",32,2);
vector <double> BestPath_Length2_square;
vector <double> BestHalf_Length2_square;
vector <int> BestPath_square;
//I create object of class GA
GeneticAlgorithm MyGA_sqaure(rnd1,Npop,Ncity,coordinates_square);
//I create a new offspring 5000 times
for(int i=0 ; i< Ngen; i ++)
{
MyGA_sqaure.NewGeneration();
/*
cout<<"Bestsend:"<<endl;
for(int j=0 ; j< Ncity; j ++){
cout<<Bestsend[j]<<endl;
}
*/
if(i%50==0)
{
//I calculate the Legth of path:
cout<<"number of steps: "<<i<<endl;
BestPath_Length2_square.push_back( MyGA_sqaure.GetTheBestFitness() );
BestHalf_Length2_square.push_back( MyGA_sqaure.GetAverageFitness() );
}
if((i%imigration==0)&&(i!=0)) {
/*
if(rank==0){
cout<<endl<<"i am the rank "<<rank<<" and the best is : "<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
if(rank==1){
cout<<endl<<"i am the rank "<<rank<<" and the best is :"<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
if(rank==2){
cout<<endl<<"i am the rank "<<rank<<" and the best is :"<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
if(rank==3){
cout<<endl<<"i am the rank "<<rank<<" and the best is :"<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
cout<<endl;
*/
if(rank==0) {
vector<int> rank_list(4);
iota(rank_list.begin(), rank_list.end(), 0);
rank_list.push_back(0);
//cout<<endl<<"rank list:"<<endl;Print(rank_list);cout<<endl;
random_shuffle(rank_list.begin()+1, rank_list.end()-1);
//cout<<endl<<"rank list:"<<endl;Print(rank_list);cout<<endl;
for(int i=0; i<=size; i++) order[i]=rank_list[i];
}
MPI_Bcast(order,size+1,MPI_INT,0, MPI_COMM_WORLD);//I want that all the ranks are aware of the order
//labelsend=MyGA_sqaure.SendTheBest();
vector <int> Best(32);
Best=MyGA_sqaure.GetTheBestChromosome();
for(int k=0; k<Ncity; k++)Bestsend[k]=Best[k];
//for(int k=0; k<Ncity; k++)cout<<Bestsend[k]<<" ";cout<<endl;
for(int iorder=0; iorder<size; iorder++) {
if(rank==order[iorder]) {
itag=1;
MPI_Send(Bestsend, Ncity, MPI_INT, order[iorder+1], itag, MPI_COMM_WORLD);
}
if(rank==order[iorder+1]) {
itag=1;
MPI_Recv(Bestreceive, Ncity, MPI_INT, order[iorder], itag, MPI_COMM_WORLD, &stat1);
}
}
//for(int k=0; k<Ncity; k++)cout<<Bestreceive[k]<<" ";cout<<endl;
MyGA_sqaure.ReceiveTheBest(Bestreceive);
/*
if(rank==0){
cout<<endl<<"i am the rank "<<rank<<" and the best is : "<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
if(rank==1){
cout<<endl<<"i am the rank "<<rank<<" and the best is :"<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
if(rank==2){
cout<<endl<<"i am the rank "<<rank<<" and the best is :"<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
if(rank==3){
cout<<endl<<"i am the rank "<<rank<<" and the best is :"<<MyGA_sqaure.GetTheBestFitness()<<endl;
}
cout<<endl;
*/
}
if(i !=Ngen-1 )
MyGA_sqaure.Mutation();
}
//output:
cout<<endl<<endl<<"In the square: "<<endl;
BestPath_square=MyGA_sqaure.GetTheBestChromosome();
cout<<"The Best path: "<<endl;
Print( BestPath_square );
cout<<endl<<"The Best Length^2: "<<BestPath_Length2_square[ BestPath_Length2_square.size()-1 ]<<endl;
string string_best_path_L2="BestPath_Length2_rank" + to_string(rank) + ".txt";
string string_best_half_L2="BestHalf_Length2_rank" + to_string(rank) + ".txt";
string string_best_path="BestPath_rank" + to_string(rank) + ".txt";
Print(string_best_path_L2,BestPath_Length2_square);
Print(string_best_half_L2,BestHalf_Length2_square);
Print(string_best_path,BestPath_square);
cout<<endl;
MPI_Finalize();
rnd1->SaveSeed();
return 0;
}
vector < vector<double> > ReadRows( const char* filename , int N,int M) {
vector < vector<double> > v;
vector<double> x_y;
ifstream fin (filename);
assert(fin && "file non esiste");
if( !fin )
{
cout << "file non esistente" << endl;
exit(0);
}
else
{
for( int k=0 ; k<N ; k++) {
x_y.clear();
for( int j=0 ; j<M ; j++){
double valore=0;
fin >> valore;
x_y.push_back(valore);
}
v.push_back(x_y);
assert(!(fin.eof()) && "lettura file terminata");
if( fin.eof() ) {
cout << "ho finito i dati" << endl;
exit(1);
}
}
}
return v;
}
| true |
e4254b0bb4f2564266d58f37c618a4b52a079113 | C++ | TimBunk/tb2d | /tb2d/contactListener.cpp | UTF-8 | 1,606 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "contactListener.h"
ContactListener::ContactListener() {
}
ContactListener::~ContactListener() {
}
void ContactListener::BeginContact(b2Contact* contact) {
// Get fixture a and b from the contact
b2Fixture* fa = contact->GetFixtureA();
b2Fixture* fb = contact->GetFixtureB();
// Check if the received data is null and check if it is a B2Entity otherwise return
if (fa == NULL || fb == NULL) { return; }
if (fa->GetUserData() == NULL || fb->GetUserData() == NULL) { return; }
if (static_cast<B2Entity*>(fa->GetUserData()) == NULL || static_cast<B2Entity*>(fb->GetUserData()) == NULL) { return; }
// Add the contacts to the b2entity
static_cast<B2Entity*>(fa->GetUserData())->AddContact(static_cast<B2Entity*>(fb->GetUserData()));
static_cast<B2Entity*>(fb->GetUserData())->AddContact(static_cast<B2Entity*>(fa->GetUserData()));
}
void ContactListener::EndContact(b2Contact* contact) {
// Get fixture a and b from the contact
b2Fixture* fa = contact->GetFixtureA();
b2Fixture* fb = contact->GetFixtureB();
// Check if the received data is null and check if it is a B2Entity otherwise return
if (fa == NULL || fb == NULL) { return; }
if (fa->GetUserData() == NULL || fb->GetUserData() == NULL) { return; }
if (static_cast<B2Entity*>(fa->GetUserData()) == NULL || static_cast<B2Entity*>(fb->GetUserData()) == NULL) { return; }
// remove the contacts from the b2entity
static_cast<B2Entity*>(fa->GetUserData())->RemoveContact(static_cast<B2Entity*>(fb->GetUserData()));
static_cast<B2Entity*>(fb->GetUserData())->RemoveContact(static_cast<B2Entity*>(fa->GetUserData()));
}
| true |
bf3f7277e49c95c4659fefc70595e7ce60ff2c6e | C++ | UPCACM/DuckKnowNothing | /src/GraphAlgorithm/ShotestPath/Dijkstra+Priority_queue.cpp | UTF-8 | 1,218 | 3.0625 | 3 | [] | no_license | const int maxn = 1007, INF = 0x3f3f3f3f;
vector<pair<int, int> > edge[maxn];
int m, n, dist[maxn];
bool vis[maxn];
struct cmp {//重载优先队列比较方法
bool operator () (pair<int, int> y, pair<int, int> x) {//这里第一个是y,第二个是x
if(x.second == y.second) return x.first < y.first;
return x.second < y.second;
}
};
int dijkstra_heap(int start, int end) {//返回从start到end的最短路径
clr(dist, INF);
clr(vis, 0);
priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> que;
//以自定义的比较方式创建优先队列
dist[start] = 0;
que.push(make_pair(start,0));
while(!que.empty()) {
pair<int, int> now = que.top();
que.pop();
int u = now.first, v, w;
if(vis[u]) continue;//每个点只访问一次
vis[u] = true;
for(vector<pair<int ,int> >::iterator i=edge[u].begin() ; i!=edge[u].end() ; i++) {
v = (*i).first, w = (*i).second;
if(dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
que.push(make_pair(v, dist[v]));//这里入队的是v和dist[v],别写错了!
}
}
}
return dist[end];
}
| true |
ef6376a026ea9daaa179cef1a496965a5df92b36 | C++ | UkZya/C | /20181028_baekjoon_1002/20181028_baekjoon_1002/main.cpp | UTF-8 | 1,919 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#define UPLIMIT 10000
#define BOLIMIT -10000
typedef struct _testcase {
int ix1;
int ix2;
int iy1;
int iy2;
int ir1;
int ir2;
}testcase;
bool isCondition(testcase stTC) {
if (BOLIMIT <= stTC.ix1 && stTC.ix1 <= UPLIMIT && BOLIMIT <= stTC.ix2 && stTC.ix2 <= UPLIMIT &&
BOLIMIT <= stTC.iy1 && stTC.iy1 <= UPLIMIT && BOLIMIT <= stTC.iy2 && stTC.iy2 <= UPLIMIT &&
stTC.ir1 <= UPLIMIT && stTC.ir2 <= UPLIMIT) {
return 1;
}
else {
return 0;
}
}
int main(void) {
int iTestCase = 0;
int iOutput = 0;
testcase *stTC;
scanf("%d", &iTestCase);
stTC = (testcase*)malloc(sizeof(testcase) * iTestCase);
for (int i = 0; i < iTestCase; i++) {
scanf("%d", &stTC[i].ix1);
scanf("%d", &stTC[i].iy1);
scanf("%d", &stTC[i].ir1);
scanf("%d", &stTC[i].ix2);
scanf("%d", &stTC[i].iy2);
scanf("%d", &stTC[i].ir2);
if (isCondition(stTC[i])) {
continue;
}
else {
printf("Out of condition!!\n");
return -1;
}
}
for (int i = 0; i < iTestCase; i++) {
double dxDiff = 0;
double dyDiff = 0;
double drDiff = 0;
double drDiff2 = 0;
int iOutput = 0;
dxDiff = stTC[i].ix1 - stTC[i].ix2;
dyDiff = stTC[i].iy1 - stTC[i].iy2;
dxDiff = dxDiff * dxDiff;
dyDiff = dyDiff * dyDiff;
drDiff = sqrt(dxDiff + dyDiff);
if (stTC[i].ix1 == stTC[i].ix2 && stTC[i].iy1 == stTC[i].iy2 && stTC[i].ir1 != stTC[i].ir2) {
iOutput = 0;
printf("%d\n", iOutput);
continue;
}
else if (stTC[i].ix1 == stTC[i].ix2 && stTC[i].iy1 == stTC[i].iy2 && stTC[i].ir1 == stTC[i].ir2) {
iOutput = -1;
printf("%d\n", iOutput);
continue;
}
drDiff2 = stTC[i].ir1 + stTC[i].ir2;
if (drDiff == drDiff2 || abs(stTC[i].ir1 - stTC[i].ir2) == drDiff) {
iOutput = 1;
}
else if (drDiff < drDiff2 && abs(stTC[i].ir1 - stTC[i].ir2) < drDiff) {
iOutput = 2;
}
else {
iOutput = 0;
}
printf("%d\n", iOutput);
}
return 0;
} | true |
3c044371487a90f8667f84fa85f3d9924ea9c8ea | C++ | yudonlee/ReviseCPlusPlus | /chap5/complex_number.cc | UTF-8 | 5,571 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstdlib>
class Complex{
private:
double real , img;
public:
Complex(const char* str);
Complex(double real, double img) : real(real), img(img){}
Complex(const Complex& c){real = c.real, img = c.img;
std::cout<<"복사생성자 호출"<<std::endl;
}
//Complex operator+(const Complex& c, const char* str) const;
Complex operator+(const char* str) const;
Complex operator+(const Complex& c) const; //const 붙여주는 이유! 내부 인자가 바뀌지 않기떄문에 const를 붙여준다.
Complex operator-(const Complex& c) const;
Complex operator*(const Complex& c) const;
Complex operator/(const Complex& c) const;
//Complex& 를 사용하지 않는 이유: reference로 리턴하게 되면 속도저하는 발생하지 않지만 처리되는 결과에서 의도하지 않는 결과들이 일어날 수 있다. 내부에서 읽기만 수행되고 값이 바뀌지 않기 때문에 const키워드를 붙이는게 옳다. 인자의 값이 함수내부에서 바뀌지 않는다고 확신할떄는 const 키워드를 붙여준다. 상수 함수로 선언할 수 있을경우 상수로 선언하고, 사칙연산은 반드시 값을 리턴해주어야 한다.
Complex& operator=(const Complex& c);
Complex& operator+=(const Complex& c);
Complex& operator-=(const Complex& c);
Complex& operator*=(const Complex& c);
Complex& operator/=(const Complex& c);
void println(){ std::cout << "( "<<real << " , "<<img<<")\n";}
};
Complex::Complex(const char* str){
real = 0.0, img = 0.0;
std::string s(str);
int starting_point_of_partition = -1;
int length = s.length();
for(int i = length -1 ; i > -1; i--){
if( str[i] == '+' || str[i] == '-'){
starting_point_of_partition = i;
break;
}
}
if(starting_point_of_partition == 0 || starting_point_of_partition == -1){
if(str[length-1] == 'i')
img = atof( (s.substr(0, starting_point_of_partition)).c_str());
else
real = atof(str);
}
else{
if(str[starting_point_of_partition-1] == 'i'){
img = atof((s.substr(0, starting_point_of_partition-1)).c_str());
real = atof((s.substr(starting_point_of_partition)).c_str());
}
else{
real = atof((s.substr(0, starting_point_of_partition)).c_str());
img = atof((s.substr(starting_point_of_partition, length - starting_point_of_partition-1)).c_str());
}
}
/*std::string s(str);
double number = atof(str);
if(number == 0.0){
if(str == "0.0" || str == "0")
real = number; //str은 실수(actual number)
else{
int length = s.length();
int starting_point_of_partition = -1;
for(int i = length -1 ; i > -1; i++){
if( str[i] == '+' || str[i] == '-'){
starting_point_of_partition = i;
break;
}
}
if(starting_point_of_partition == -1 || starting_point_of_partition == 0){
img = atof((s.substr(length-1)).c_str());
}
else{
const char* front_part = (s.substr(0,starting_point_of_partition)).c_str();
const char* back_part = (s.substr(starting_point_of_partition)).c_str();
std::cout <<"back part is: "<<back_part<<std::endl;
if(str[length - 1] == 'i')
real = atof(front_part), img = atof(back_part);
else
real = atof(back_part), img = atof(front_part);
}
}
}
else
real = number; //str is actual number
std::cout << "real is : "<<real <<"image is : "<< img<<std::endl;
*/
}
Complex Complex::operator+(const char* str)const {
Complex cstr(str);
Complex temp(real + cstr.real, img + cstr.img);
return temp;
}
Complex Complex::operator+(const Complex& c) const{
Complex temp(real + c.real, img + c.img);
return temp;
}
Complex Complex::operator-(const Complex& c) const{
Complex temp(real - c.real, img - c.img);
return temp;
}
Complex Complex::operator*(const Complex& c) const{
Complex temp(real * c.real - img * c.img, real * c.img + img * c.real);
return temp;
}
Complex Complex::operator/(const Complex& c) const{
Complex temp( (real * c.real + img * c.img) / ((c.real) * (c.real) + (c.img)*(c.img)), ((img * c.real) - (c.img * real))/( c.real * c.real + c.img * c.img));
return temp;
}
Complex& Complex::operator=(const Complex& c){
real = c.real;
img = c.img;
return *this;
}
Complex& Complex::operator+=(const Complex& c){
(*this) = (*this) + c;
//real += c.real;
//img += c.img;
return *this;
}
Complex& Complex::operator-=(const Complex& c){
(*this) = (*this) - c;
// real -= c.real;
// img -= c.img;
return *this;
}
Complex& Complex::operator*=(const Complex& c){
(*this) = (*this) * c;
//real = real * c.real - img * c.img;
//img = real * c.img + img + c.real;
return *this;
}
Complex& Complex::operator/=(const Complex& c){
(*this) = (*this) / c;
//real = ( real * c.real + img * c.img) / ( c.real * c.real + c.img * c.img);
//img = ( c.real * img - real * c.img) / ( c.real * c.real + c.img * c.img);
return *this;
}
int main() {
/*Complex a(1.0, 2.0);
Complex b(3.0, -2.0);
Complex c(0.0, 0.0);
c = a * b + a / b + a + b;
c.println();
Complex d = c; //이때는 대입연산자가 아닌 복사생성자가 호출된다 선언후 대입연산자를 사용하면 복사생성자가 호출되지 않는다.
a += b;
a.println();
b /= a;
b.println();*/
Complex i("2i+3");
Complex j("3+2i");
Complex k("2i");
Complex s("3");
Complex t = i + j;
Complex r = i + k;
Complex a("-50");
i.println();
j.println();
k.println();
s.println();
t.println();
r.println();
a.println();
a = a + "-1.1+3i";
a.println();
return 0;
}
| true |
30f012bb141a1f526bd086a504e91dd5b6e1fa00 | C++ | NamNamju/Algorithm | /DP/baekjoon_11722.cpp | UHC | 766 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
// A ־ , ϴ κ ϴ α ۼϽÿ.
// baekjoon_11053 ſ . Ǯ ȴ.
int main() {
int arr[1002] = { 0, };
int num;
int dp[1002] = { 0, };
int max = 0;
cin >> num;
for (int i = 1; i <= num; i++) {
cin >> arr[i];
}
for (int i = num; i > 0; i--) { // ϴ κм ϱ Ųٷ for .
int min = 0;
for (int j = num + 1; j > i; j--) { // j ƹ͵ num+1 Ѵ.
if (arr[i] > arr[j]) {
if (min < dp[j]) min = dp[j];
}
}
dp[i] = min + 1;
if (max < dp[i]) max = dp[i];
}
cout << max;
return 0;
} | true |
70eef444b86003744a186536fb459c80460001b8 | C++ | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/1005.k-次取反后最大化的数组和.cpp | UTF-8 | 1,890 | 3.578125 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=1005 lang=cpp
*
* [1005] K 次取反后最大化的数组和
*
* https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations/description/
*
* algorithms
* Easy (50.90%)
* Likes: 35
* Dislikes: 0
* Total Accepted: 6.6K
* Total Submissions: 12.9K
* Testcase Example: '[4,2,3]\n1'
*
* 给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K
* 次。(我们可以多次选择同一个索引 i。)
*
* 以这种方式修改数组后,返回数组可能的最大和。
*
*
*
* 示例 1:
*
* 输入:A = [4,2,3], K = 1
* 输出:5
* 解释:选择索引 (1,) ,然后 A 变为 [4,-2,3]。
*
*
* 示例 2:
*
* 输入:A = [3,-1,0,2], K = 3
* 输出:6
* 解释:选择索引 (1, 2, 2) ,然后 A 变为 [3,1,0,2]。
*
*
* 示例 3:
*
* 输入:A = [2,-3,-1,5,-4], K = 2
* 输出:13
* 解释:选择索引 (1, 4) ,然后 A 变为 [2,3,-1,5,4]。
*
*
*
*
* 提示:
*
*
* 1 <= A.length <= 10000
* 1 <= K <= 10000
* -100 <= A[i] <= 100
*
*
*/
#include "vector"
#include "numeric"
#include "algorithm"
using namespace std;
// @lc code=start
class Solution
{
public:
int largestSumAfterKNegations(vector<int> &A, int K)
{
if (A.size() == 1)
{
return -A[0];
}
else
{
sort(A.begin(), A.end());
int index = 0;
while (A[index] < 0 && K > 0)
{
A[index++] *= -1;
K--;
}
if (A[index] != 0 && K % 2)
{
sort(A.begin(), A.end());
A[0] *= -1;
}
return accumulate(A.begin(), A.end(), 0);
}
}
};
// @lc code=end
| true |
7cea05eb35462ebd407a23fd7079ddcf7f1bb6cc | C++ | theozornelas/throw-catch | /src/source/shoppingcart.cpp | UTF-8 | 3,642 | 2.65625 | 3 | [] | no_license | #include "shoppingcart.h"
#include "ui_shoppingcart.h"
#include "../header/shoppingcart.h"
/**
* @brief ShoppingCart::ShoppingCart Initializes the ui to appear on the screen.
* @param parent
*/
ShoppingCart::ShoppingCart(QWidget *parent) :
QWidget(parent),
ui(new Ui::ShoppingCart)
{
ui->setupUi(this);
}
/**
* @brief ShoppingCart::~ShoppingCart Destructor, closes the ui properly.
*/
ShoppingCart::~ShoppingCart()
{
delete ui;
}
/**
* @brief ShoppingCart::setList Initializes all needed functionality for ui
* to display a table (QTreeWidget) on the gui
* with sub-cost, total cost, total quantity
* of each item from the customer's shopping
* experience. Along with an overall grand total.
* @param shoppingCart
* @param stadiums
*/
void ShoppingCart::setList(QVector<Souvenir*> shoppingCart, skiplist<int, Stadium*> stadiums) {
if(shoppingCart.empty()) {
ui->shoppingCart->hide();
}
else {
ui->shoppingCart->clear();
QString currentStadium = "";
QString nextStadium = "";
double stadiumTotal = 0;
double grandTotal = 0;
QString souvenirName;
double subtotal;
unsigned int qty;
double souvenirTotal;
// Sets the iterator to begin at the start of the list
QVector<Souvenir*>::iterator it = shoppingCart.begin();
QTreeWidgetItem *parent = new QTreeWidgetItem(ui->shoppingCart);
ui->shoppingCart->addTopLevelItem(parent);
currentStadium = (*stadiums.get((*it)->getStadiumID()))->getStadiumName();
parent->setText(0, currentStadium);
ui->shoppingCart->setColumnWidth(0, 200);
ui->shoppingCart->setColumnWidth(1, 70);
ui->shoppingCart->setColumnWidth(2, 70);
ui->shoppingCart->setColumnWidth(3, 70);
while(it != shoppingCart.end())
{
nextStadium = (*stadiums.get((*it)->getStadiumID()))->getStadiumName();
if(currentStadium != nextStadium) {
parent->setText(3, QString::number(stadiumTotal, 'f', 2));
grandTotal += stadiumTotal;
stadiumTotal = 0;
parent = new QTreeWidgetItem(ui->shoppingCart);
ui->shoppingCart->addTopLevelItem(parent);
parent->setText(0, nextStadium);
ui->shoppingCart->addTopLevelItem(parent);
currentStadium = nextStadium;
}
souvenirName = (*it)->getName();
subtotal = (*it)->getPrice();
qty = (*it)->getQuantity();
souvenirTotal = (*it)->getPrice() * (*it)->getQuantity();
QTreeWidgetItem *itm = new QTreeWidgetItem();
itm->setText(0, souvenirName);
itm->setText(1, "$" + QString::number(subtotal, 'f', 2));
itm->setTextAlignment(1, Qt::AlignCenter);
itm->setText(2, QString::number(qty));
itm->setTextAlignment(2, Qt::AlignCenter);
itm->setText(3, "$" + QString::number(souvenirTotal, 'f', 2));
itm->setTextAlignment(3, Qt::AlignCenter);
stadiumTotal += souvenirTotal;
parent->addChild(itm);
// Iterator increments to the next node
it++;
}
parent->setText(3, QString::number(stadiumTotal, 'f', 2));
grandTotal += stadiumTotal;
stadiumTotal = 0;
ui->grandTotalAmount->setText("$" + QString::number(grandTotal, 'f', 2));
ui->shoppingCart->expandAll();
}
}
| true |
02665ff32dac80225ebdca658656d34a062c4e44 | C++ | sanjusss/leetcode-cpp | /0/400/480/483.cpp | UTF-8 | 1,134 | 2.5625 | 3 | [] | no_license | /*
* @Author: sanjusss
* @Date: 2021-06-18 08:29:42
* @LastEditors: sanjusss
* @LastEditTime: 2021-06-18 09:08:07
* @FilePath: \0\400\480\483.cpp
*/
#include "leetcode.h"
class Solution {
public:
string smallestGoodBase(string n) {
uint64_t i = stoull(n);
int ones = 64;
while (!((1ull << (ones - 1)) & i)) {
--ones;
}
for (; ones > 0; --ones) {
uint64_t left = 2;
uint64_t right = i - 1;
uint64_t mid;
while (left <= right) {
mid = left + (right - left) / 2;
uint64_t val = 0;
int j = 0;
for (; j < ones && (i - 1) / mid >= val; ++j) {
val = val * mid + 1;
}
if (j < ones || val > i) {
right = mid - 1;
}
else if (val == i) {
return to_string(mid);
}
else {
left = mid + 1;
}
}
}
return ""s;
}
};
TEST(&Solution::smallestGoodBase) | true |
68e737c5909c85bb643a6bc7328c1dd6c276e2b2 | C++ | tanlin816/xuexi | /Imageprocessing/Opencvexample/cmake/caper2/最邻近插值/main.cpp | UTF-8 | 1,526 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include<opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat srcimage = imread("72dpi.jpg");
if(!srcimage.data)
{
cout << "image read is error!" << endl;
return 0;
}
cout << "image Info:Height:" << srcimage.size().height << " Width:" << srcimage.size().width << endl;
imshow("origin",srcimage);
int n=2;
int W=srcimage.rows;
int H=srcimage.cols;
int w=W*n;
int h=H*n;
Mat dstimage; //定义一个输出图像;
dstimage.create(w,h,srcimage.type()); //定义输出图像的大小、类型;
for(int i=0;i<w;i++)
{
for(int j=0;j<h;j++)
{
int x=int(float(i)/float(n)+0.5);
int y=int(float(j)/float(n)+0.5);
dstimage.at<Vec3b>(i,j)[0] = srcimage.at<Vec3b>(x,y)[0];
dstimage.at<Vec3b>(i,j)[1] = srcimage.at<Vec3b>(x,y)[1];
dstimage.at<Vec3b>(i,j)[2] = srcimage.at<Vec3b>(x,y)[2];
}
}
//这里添加上最后一行
for(int j=0; j<h; j++)
{
dstimage.at<cv::Vec3b>(w-1,j)[0] = dstimage.at<cv::Vec3b>(w-2,j)[0];
dstimage.at<cv::Vec3b>(w-1,j)[1] = dstimage.at<cv::Vec3b>(w-2,j)[1];
dstimage.at<cv::Vec3b>(w-1,j)[2] = dstimage.at<cv::Vec3b>(w-2,j)[2];
}
imshow("fangdatu",dstimage);
imwrite("fada150.jpg", dstimage);
waitKey(0);
return 0;
}
| true |
0f9538b2d78b42c7243485dea489fa35c2fa1527 | C++ | ParadoxGameConverters/Vic2ToHoI4 | /src/V2World/Countries/CountryBuilder.h | UTF-8 | 2,122 | 3.140625 | 3 | [
"MIT"
] | permissive | #ifndef COUNTRY_BUILDER_H
#define COUNTRY_BUILDER_H
#include "src/V2World/Countries/Country.h"
#include <memory>
namespace Vic2
{
class Country::Builder
{
public:
Builder() { country = std::make_unique<Country>(); }
std::unique_ptr<Country> Build() { return std::move(country); }
Builder& SetTag(const std::string& tag)
{
country->tag = tag;
return *this;
}
Builder& addNameInLanguage(const std::string& language, const std::string& name)
{
country->namesByLanguage.insert(std::make_pair(language, name));
return *this;
}
Builder& setHuman()
{
country->human = true;
return *this;
}
Builder& setColor(const commonItems::Color& color)
{
country->color = color;
return *this;
}
Builder& setCapital(int capital)
{
country->capital = capital;
return *this;
}
Builder& setRulingParty(const Party& rulingParty)
{
country->rulingParty = rulingParty;
return *this;
}
Builder& addActiveParty(const Party& party)
{
country->activeParties.insert(party);
return *this;
}
Builder& setUpperHouseComposition(const std::map<std::string, double>& upperHouseComposition)
{
country->upperHouseComposition = upperHouseComposition;
return *this;
}
Builder& setLastElection(const date& lastElection)
{
country->lastElection = lastElection;
return *this;
}
Builder& setRevanchism(double revanchism)
{
country->revanchism = revanchism;
return *this;
}
Builder& setWarExhaustion(double warExhaustion)
{
country->warExhaustion = warExhaustion;
return *this;
}
Builder& setAtWar(bool atWar)
{
country->atWar = atWar;
return *this;
}
Builder& addTechOrInvention(const std::string& tech)
{
country->technologiesAndInventions.insert(tech);
return *this;
}
Builder& addProvince(int provinceNum, std::shared_ptr<Province> province)
{
country->provinces.insert(std::make_pair(provinceNum, province));
return *this;
}
Builder& setGovernment(const std::string& government)
{
country->government = government;
return *this;
}
private:
std::unique_ptr<Country> country;
};
} // namespace Vic2
#endif // COUNTRY_BUILDER_H | true |
54ed0c4c4d4bfed196e8127955470d880b2f107b | C++ | alexdgarland/KRC | /Ch1/ProcessLine/MainSource/ProcessLine.cpp | UTF-8 | 3,510 | 3.15625 | 3 | [] | no_license | #include "ProcessLine.h"
#ifdef _WIN32
using std::string;
#endif
void main(int argc, char* argv[])
{
#ifdef __linux__
const char* options;
#endif
#ifdef _WIN32
TCHAR* options;
#endif
options = PROCESSLINE_GETOPT_OPTIONS;
int ArgumentIdentifier;
char* RunModeArgument = NULL;
char* NumericArgument = NULL;
int ParsedNumericArgument;
RunMode* selectedRunMode;
while ((ArgumentIdentifier = getopt(argc, argv, options)) != -1)
{
switch (ArgumentIdentifier)
{
case 'm':
RunModeArgument = optarg;
break;
case 'n':
NumericArgument = optarg;
break;
}
}
PopulateModeList();
if((selectedRunMode = GetRunMode(RunModeArgument)) == NO_RUNMODE)
{
ReportBadArgsAndExit();
}
if (NumericArgument == NULL)
{
RunWithoutNumericArg(selectedRunMode);
}
else if (TryParseIntArg(NumericArgument, &ParsedNumericArgument))
{
RunWithNumericArg(selectedRunMode, ParsedNumericArgument);
}
else
{
ReportBadArgsAndExit();
}
FreeModeList();
exit(0);
}
int PopulateModeList()
{
AddRunMode('T', "Trim", &RunTrim, "Remove trailing blanks from each line.", NO_NUMARG);
AddRunMode('R', "Reverse", &RunReverse, "Reverses the order of characters in each line.", NO_NUMARG);
AddRunMode('S', "Strip", &RunStripComments, "Strips out code comments.", NO_NUMARG);
NumericArgument* MaxWidthNumArg = CreateNumArg("Sets maximum line width", 40);
AddRunMode('W', "Wrap", &RunWrapText, "Wraps text in each line.", MaxWidthNumArg);
NumericArgument* SpacesPerTabNumArg = CreateNumArg("Sets number of spaces per tab", 4);
AddRunMode('D', "Detab", &RunDetab, "Converts tabs to spaces.", SpacesPerTabNumArg);
AddRunMode('E', "Entab", &RunEntab, "Converts spaces to tabs.", SpacesPerTabNumArg);
NumericArgument* MinLengthNumArg = CreateNumArg("Sets minimum line length", 80);
AddRunMode('M', "Minimum", &RunGetLinesOfMinimumLength, "Gets lines of a minimum length.", MinLengthNumArg);
AddRunMode('L', "Longest", &RunGetLongestLine, "Returns longest line from set of lines entered.", NO_NUMARG);
AddRunMode('V', "ValidArgs", &ListValidArguments, "List valid command line arguments for this program.", NO_NUMARG);
AddRunMode('U', "UnitTest", &RunTests, "Run unit tests for internal functions.", NO_NUMARG);
return 0;
}
short TryParseIntArg(char* InputArg, int* Output)
{
/*
This function checks whether the input string is too long to be an integer, or has any non-numeric characters.
If it does, it sets the numeric output to zero and returns false.
Otherwise, we've done a partial/ incomplete check that it's parseable to an int
so performs the conversion, assigns to the output and returns true.
Almost certainly there are better standard functions in C if we were writing production code...
this is just for practice/ learning purposes :-)
*/
int i, in_length;
if ((in_length = (int)strlen(InputArg)) > 9)
{
*Output = '\0';
return FALSE;
}
for(i = 0; i < in_length; i++)
{
if (!IsNumericChar(InputArg[i]))
{
*Output = '\0';
return FALSE;
}
}
*Output = atoi(InputArg);
return TRUE;
}
short IsNumericChar(char input)
{
return (input >= '0' && input <= '9') ? TRUE : FALSE;
}
| true |
3f75cc4a7f386e358ddee6c2903fff1030705de9 | C++ | sachin2805/All-c-lab-manual | /resultantTime.cpp | UTF-8 | 1,529 | 4.09375 | 4 | [] | no_license | /*Add two values times and display resultant time in the hr.: min: sec
form using friend function(overload binary + operator)
a. T1- 2:40:35
b. T2- 3:35:30
c. Resultant time is- 06:16:05*/
#include<iostream>
using namespace std;
class time
{
int hr,m,s;
public:
void set(int x)
{
cout<<"\nEnter the "<<x<<" time \n ";
cout<<"\nEnter the hr= ";
cin>>hr;
cout<<"\nEnter the minute= ";
cin>>m;
cout<<"\nEnter the sec= ";
cin>>s;
cout<<"\nThe "<<x<<" time is = "<<hr<<":"<<m<<":"<<s;
}
friend time operator+
(time , time );
void display()
{
if(s>60)
{
m=m+1;
s=s-60;
}
if(m>60)
{
hr=hr+1;
m=m-60;
}
cout<<"\n\nResultant time is = "<<hr<<":"<<m<<":"<<s;
}
};
time operator+(time a , time b)
{
time temp;
temp.hr=a.hr+b.hr;
temp.m=a.m+b.m;
temp.s=a.s+b.s;
return temp;
}
int main()
{
time a,b;
a.set(1);
b.set(2);
a=a+b;
a.display();
return 0;
}
/*OUTPUT
PS F:\PROFOUND\PRACTICAL\cpp\cpp lab manual> g++ resultantTime.cpp
PS F:\PROFOUND\PRACTICAL\cpp\cpp lab manual> ./a.exe
Enter the 1 time
Enter the hr= 2
Enter the minute= 40
Enter the sec= 35
The 1 time is = 2:40:35
Enter the 2 time
Enter the hr= 3
Enter the minute= 35
Enter the sec= 30
The 2 time is = 3:35:30
Resultant time is = 6:16:5
PS F:\PROFOUND\PRACTICAL\cpp\cpp lab manual>
*/ | true |
7456c8df3e37c2fd649f4a7d5e211f05ba06a058 | C++ | huongnguyenduc/OOP_Summer_Fsoft_Test | /OOP_Summer/OOP_Summer.cpp | UTF-8 | 10,490 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstdio>
#include <fstream>
#include <vector>
#include <memory>
using namespace std;
enum JobTitle {
DEVELOPER,
MANAGER,
TESTER
};
class Employee {
public:
Employee(int id = 0, string name = "None", JobTitle jobTitle = DEVELOPER) {
this->id = id;
this->name = name;
this->jobTitle = jobTitle;
}
int getId() {
return id;
}
void setId(int id) {
this->id = id;
}
string getName() {
return name;
}
void setName(string name) {
this->name = name;
}
string getJobTitle() {
if (jobTitle == DEVELOPER) {
return "Developer";
}
if (jobTitle == MANAGER) {
return "Manager";
}
if (jobTitle == TESTER) {
return "Tester";
}
}
void setJobTitle(JobTitle jobTitle) {
this->jobTitle = jobTitle;
}
virtual void ShowInformation() = 0;
private:
int id;
string name;
JobTitle jobTitle;
virtual void DisplayDailyWork() = 0;
};
class Developer : public Employee {
private:
string recentProject;
public:
Developer(int id = 0, string name = "None", JobTitle jobTitle = DEVELOPER, string recentProject = "None") : Employee(id, name, jobTitle){
this->recentProject = recentProject;
}
string getRecentProject() {
return recentProject;
}
string setRecentProject(string recentProject) {
this->recentProject = recentProject;
}
void ShowInformation() {
cout << "Ma So Nhan Vien: " << getId() << endl;
cout << "Ho Va Ten: " << getName() << endl;
cout << "Ten Bo Phan: " << getJobTitle() << endl;
cout << "Ten Du An Dang Lam: " << getRecentProject() << endl;
}
void DisplayDailyWork() {
}
};
class Manager : public Employee {
private:
string recentCustomer;
public:
Manager(int id = 0, string name = "None", JobTitle jobTitle = MANAGER, string recentCustomer = "None") : Employee(id, name, jobTitle) {
this->recentCustomer = recentCustomer;
}
string getRecentCustomer() {
return recentCustomer;
}
string setRecentCustomer(string recentCustomer) {
this->recentCustomer = recentCustomer;
}
void ShowInformation() {
cout << "Ma So Nhan Vien: " << getId() << endl;
cout << "Ho Va Ten: " << getName() << endl;
cout << "Ten Bo Phan: " << getJobTitle() << endl;
cout << "Ten Khach Hang Dang Quan Ly: " << getRecentCustomer() << endl;
}
void DisplayDailyWork(){
}
};
class Tester : public Employee {
public:
Tester(int id = 0, string name = "None", JobTitle jobTitle = TESTER) : Employee(id, name, jobTitle) {
}
void ShowInformation() {
cout << "Ma So Nhan Vien: " << getId() << endl;
cout << "Ho Va Ten: " << getName() << endl;
cout << "Ten Bo Phan: " << getJobTitle() << endl;
}
void DisplayDailyWork() {
}
};
class Company {
private:
vector<unique_ptr<Employee>> employeeList;
vector<string> employeeNameList;
public:
unique_ptr<Employee> add(string name = "None") {
int choice;
int id;
string recent;
if (name == "None") {
cout << "Nhap ten nhan vien: ";
cin.ignore();
getline(cin, name);
}
else cout << "Nhan vien " << name << ": " << endl;
cout << "Nhap loai nhan vien (0. Developer | 1. Manager | 2. Tester): ";
cin >> choice;
cout << "Nhap ma so nhan vien: ";
cin >> id;
unique_ptr<Employee> tempp;
switch (choice) {
case 0:
cout << "Nhap ten du an dang lam: ";
cin.ignore();
getline(cin, recent);
tempp = make_unique<Developer>(id, name, DEVELOPER, recent);
break;
case 1:
cout << "Nhap ten khach hang đang quan ly: ";
cin.ignore();
getline(cin, recent);
tempp = make_unique<Manager>(id, name, MANAGER, recent);
break;
case 2:
tempp = make_unique<Tester>(id, name, TESTER);
break;
default:
break;
}
return tempp;
}
int deleteFromEmployeeList() {
int deleteId;
cout << "Nhap ma so nhan vien can xoa: ";
cin >> deleteId;
int n = employeeList.size();
int i;
for (i = 0; i < n; i++) {
if (employeeList[i]->getId() == deleteId) {
employeeList.erase(employeeList.begin() + i);
cout << "Da xoa thanh cong nhan vien " << deleteId << " !\n";
cout << "Ban co muon xoa them nhan vien khong? (1. Co | 2. Khong): ";
break;
}
}
if (i==n) cout << "Khong co nhan vien nay!\n (Nhap lai: 1 | Quay lai: 2): ";
int choose;
cin >> choose;
if (choose == 1) return 1;
return 0;
}
void idSort() {
int n = employeeList.size();
for (int i = 1; i < n; i++) {
int temp = employeeList[i]->getId();
int j = i - 1;
unique_ptr<Employee> tempp = move(employeeList[i]);
while (j >= 0 && temp <= employeeList[j]->getId()) {
employeeList[j + 1] = move(employeeList[j]);
j--;
}
employeeList[j+1] = move(tempp);
}
}
void ShowInformationList() {
for (vector<unique_ptr<Employee>>::iterator it = employeeList.begin(); it != employeeList.end(); ++it)
(*it)->ShowInformation();
}
void nameSort() {
int n = employeeNameList.size();
for (int i = 1; i < n; i++) {
string temp = employeeNameList[i];
int j = i - 1;
while (j >= 0 && temp.substr((int)temp.rfind(" ") + 1, temp.length() - (int)temp.rfind(" ") - 1) <=
employeeNameList[j].substr((int)employeeNameList[j].rfind(" ") + 1, employeeNameList[j].length() - (int)employeeNameList[j].rfind(" ") - 1)) {
employeeNameList[j + 1] = employeeNameList[j];
j--;
}
employeeNameList[j + 1] = temp;
}
}
void displayEmployeeName() {
int n = employeeNameList.size();;
for (int i = 0; i < n; i++) {
cout << employeeNameList[i] << endl;
}
}
void setEmployeeNameList(vector<string> employeeNameList) {
this->employeeNameList = employeeNameList;
}
void setEmployeeList() {
for (vector<string>::iterator it = employeeNameList.begin(); it != employeeNameList.end(); ++it) {
employeeList.push_back(add(*it));
}
cout << "Da them danh sach nhan vien!" << endl;
}
void setEmployee() {
employeeList.push_back(add());
}
void searchEmployeeWithId() {
int id;
cout << "Nhap ma so nhan vien can tim: ";
cin >> id;
for (vector<unique_ptr<Employee>>::iterator it = employeeList.begin(); it != employeeList.end(); ++it)
if ((*it)->getId() == id) {
cout << "Da tim thay nhan vien " << id << "!\n";
(*it)->ShowInformation();
return;
}
cout << "Khong tim thay nhan vien!\n";
}
};
vector<string> readFromFile(FILE* file) {
vector<string> employeeNameList;
std::ifstream fileInput(file);
while (!fileInput.eof())
{
char name[255];
fileInput.getline(name, 255);
employeeNameList.push_back((string)(name));
}
return employeeNameList;
}
int main()
{
cout << "____MANAGE EMPLOYEE APPLICATION BY NGUYEN DUC HUONG____\n";
Company Fsoft;
const char* filePath = "D:/employee_list.txt";
FILE* file;
file = fopen(filePath, "r");
if (!file)
std::cout << "Can not open this file" << std::endl;
else
std::cout << "File is opened" << std::endl;
Fsoft.idSort();
cout << "Cac chuc nang cua chuong trinh:\n";
cout << "1. Nhap danh sach ten nhan vien tu file txt (D:/employee_list.txt)\n";
cout << "2. Nhap them thong tin cho danh sach ten nhan vien.\n";
cout << "3. Sap xep ten nhan vien.\n";
cout << "4. In danh sach ten nhan vien.\n";
cout << "5. Sap xep nhan vien theo ma so nhan vien.\n";
cout << "6. In thong tin day du danh sach nhan vien.\n";
cout << "7. Them nhan vien vao danh sach.\n";
cout << "8. Xoa nhan vien khoi danh sach.\n";
cout << "9. Tim kiem nhan vien.\n";
cout << "0. Thoat chuong trinh.\n";
int choice;
char choosePrint;
do {
cout << "Chon chuc nang: ";
cin >> choice;
switch (choice) {
case 1:
Fsoft.setEmployeeNameList(readFromFile(file));
cout << "Da nhap danh sach ten nhan vien thanh cong!\n";
break;
case 2:
Fsoft.setEmployeeList();
break;
case 3:
Fsoft.nameSort();
cout << "Da sap xep danh sach ten nhan vien. Ban co muon xem khong? (y: Xem/n: Quay lai): ";
cin >> choosePrint;
if (choosePrint == 'y') Fsoft.displayEmployeeName();
break;
case 4:
Fsoft.displayEmployeeName();
break;
case 5:
Fsoft.idSort();
cout << "Da sap xep danh sach nhan vien theo ma so. Ban co muon xem khong? (y: Xem/n: Quay lai): ";
cin >> choosePrint;
if (choosePrint == 'y') Fsoft.ShowInformationList();
break;
case 6:
Fsoft.ShowInformationList();
break;
case 7:
int num;
cout << "Nhap so luong nhan vien can them: "; cin >> num;
for (int i = 0; i < num; i++) Fsoft.setEmployee();
cout << "Da them " << num << " nhan vien vao danh sach!\n";
break;
case 8:
int choose;
do choose = Fsoft.deleteFromEmployeeList();
while (choose == 1);
break;
case 9:
char chooseSearch;
do {
Fsoft.searchEmployeeWithId();
cout << "Ban co muon tim kiem them nhan vien khong? (y: Tim/n: Quay lai): ";
cin >> chooseSearch;
} while (chooseSearch == 'y');
break;
default:
break;
}
} while (choice != 0);
fclose(file);
return 0;
}
| true |
3e8a3f0106407255140d19a8e55cda5952d51152 | C++ | hexagonal-sun/mattuliser | /src/dsp/dsp.h | UTF-8 | 2,143 | 2.53125 | 3 | [] | no_license | /****************************************
*
* dsp.h
* Declare a DSP plugin class.
*
* This file is part of mattulizer.
*
* Copyright 2010 (c) Matthew Leach.
*
* Mattulizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mattulizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Mattulizer. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _DSP_H_
#define _DSP_H_
#include <stdint.h>
/**
* A pure abstract class for defining a DSP plugin.
*/
class DSP
{
public:
/**
* This function is called to process the PCM data. It is called by the
* DSP worker thread and should run as fast as possible. If work is still
* happening when the DSPManager class receives the next batch of audio data
* then that batch of samples is discarded. You can use the SEQ number to
* detect this. It will be incremented every time the DSPManager
* class attempts to process PCM data.
* @param data the raw 16 bit signed PCM data.
* @param len the number of samples in the buffer data.
* @param SEQ the sequence number of this batch of PCM data.
*/
virtual void processPCMData(int16_t* data, int len, int SEQ) = 0;
/**
* This function is called by the visualiser class to get the PCM data.
* @note this should trigger a mutex to not allow any processing happen
* whilst the data is being processed.
* @returns a void pointer to the processed PCM data.
*/
virtual void* getDSPData() = 0;
/**
* This function should be called by the visualiser plugin to signify that
* it has finished using this batch of DSP data and processing can occur
* during the next cycle.
*/
virtual void relenquishDSPData() = 0;
};
#endif
| true |
9888dd4dd56871552b117d20cc1b864d09009b6b | C++ | AksanaKuzmitskaya/introductiontocpp | /transpose.cpp | UTF-8 | 428 | 3.6875 | 4 | [] | no_license | /*Write a function that returns the length of a string (char *), excluding the final NULL
character. It should not use any standard-library functions. You may use arithmetic and
dereference operators, but not the indexing operator ([]).*/
#include <iostream>
using namespace std;
int main()
{
const char *h = "hello";
int len = 0;
while (*(h + len) != '\0')
{
len++;
}
cout << len << endl;
}
| true |
be0630e3e0f9afecd48230cd4bfabce36d69fe4d | C++ | Adven00/ARender | /src/core/render_utils.h | UTF-8 | 1,245 | 2.578125 | 3 | [] | no_license | #ifndef UTILS_H_
#define UTILS_H_
#include "vertex.h"
namespace utils {
struct BoundingBox2D {
int x_min;
int y_min;
int x_max;
int y_max;
};
// square of screen triangle
float ScreenTriangleSquare(const Triangle &tri);
bool InTriangle(const std::array<float, 3> &bc);
// return 2D boundingbox of triangle
BoundingBox2D BoundingBox(const Triangle &tri);
// judge whether vertex.coord.csc is in clip space
bool InClipSpace(Vertex *v);
// interpolate vertex.attr for fragment shader
Attr Interpolate(const std::array<float, 3> &coeff, const Triangle &tri);
std::array<float, 3> PespectiveCorrection(const std::array<float, 3> &bc, const Triangle &tri);
// calculate vertex.coord.ndc
void HomogeneousDivision(Vertex *v);
// calculate vertex.coord.screen and vertex.coord.screen_int
void ViewPortTransform(int width, int height, Vertex *v);
// interpolate depth for depth test
float InterpolateDepth(const std::array<float, 3> &coeff, const Triangle &tri);
// calculate barycentric coordinate of (x, y) in tri
std::array<float, 3> BarycentricCoordinate(int x, int y, float s, const Triangle &tri);
};
#endif // UTILS_H_ | true |
8bcf37ff3ccb1e219fba7609a4c21737402da769 | C++ | axard/Rubetek-Test-Assignment | /task_1/test/test_solver.cpp | UTF-8 | 1,446 | 2.84375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <main.h>
TEST(test_has_variable, test_solver)
{
std::string input = "8 - 10 * x + 3";
Parser p(input);
auto ast = p.parse();
auto result = Solver::hasVariable(ast);
ASSERT_EQ(result, true);
}
TEST(test_has_not_variable, test_solver)
{
std::string input = "8 - 10 + 3";
Parser p(input);
auto ast = p.parse();
auto result = Solver::hasVariable(ast);
ASSERT_EQ(result, false);
}
TEST(test_simplify_expr_without_variable, test_solver)
{
std::string input = "8 - 10 + 3";
Parser p(input);
auto ast = p.parse();
auto result = Solver::simplify(ast);
ASSERT_EQ(result, true);
auto number = dynamic_cast<Number*>(ast.get());
ASSERT_NE(number, nullptr);
ASSERT_EQ(number->value, 1);
}
TEST(test_solve_X_eq_7_plus_3_minus_1, test_solver)
{
std::string input = "x = 7 + 3 - 1";
Parser p(input);
auto ast = p.parse();
int result;
auto solved = Solver::solve(ast, result);
ASSERT_EQ(solved, true);
ASSERT_EQ(result, 9);
}
TEST(test_solve_8_minus_5_mult_X_plus_6_div_2_eq_9_minus_8, test_solver)
{
std::string input = "8 - 5*x + 6/2 = 9 - 8";
Parser p(input);
auto ast = p.parse();
int result;
auto solved = Solver::solve(ast, result);
ASSERT_EQ(solved, true);
ASSERT_EQ(result, 2);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
b80ac5b16554dc30a56a95215404bc7180ac47f6 | C++ | nadavmarkus/advanced_programming_ex3 | /main.cpp | UTF-8 | 1,695 | 2.75 | 3 | [] | no_license | #include <cassert>
#include <string>
#include <iostream>
/* We resort to raw getopt since we don't have boost :( */
#include <getopt.h>
#include <stdlib.h>
#include "TournamentManager.h"
int main(int argc, char *const argv[])
{
struct option options[] {
{"threads", required_argument, nullptr, 0},
{"path", required_argument, nullptr, 0},
{nullptr, 0, nullptr, 0}
};
TournamentManager &tournament_manager = TournamentManager::getInstance();
int longindex;
while (-1 != getopt_long_only(argc, argv, "", options, &longindex)) {
switch(longindex) {
case 0:
/* Thread count. */
try {
size_t count = static_cast<size_t>(std::stoi(std::string(optarg)));
if (0 == count) {
std::cerr << "The count of threads should be at least 1." << std::endl;
return -1;
}
tournament_manager.setThreadCount(count);
} catch (const std::exception &error) {
std::cerr << "Failed to parse the number of threads: " << optarg << std::endl;
return -1;
}
break;
case 1:
/* Set the path. */
tournament_manager.setSODirectory(std::string(optarg));
break;
default:
/* Should not happen. */
assert(false);
break;
}
}
tournament_manager.run();
return 0;
}
| true |
496c1c93688ee944277ce189db7caa27d384ecfc | C++ | Mesywang/EPSILON_Noted | /EPSILON/core/common/inc/common/spline/polynomial.h | UTF-8 | 6,906 | 2.8125 | 3 | [
"MIT"
] | permissive | #ifndef _CORE_COMMON_INC_COMMON_SPLINE_POLYNOMIAL_H__
#define _CORE_COMMON_INC_COMMON_SPLINE_POLYNOMIAL_H__
#include <assert.h>
#include "common/basics/basics.h"
#include "common/math/calculations.h"
#include "common/spline/lookup_table.h"
namespace common {
/**
* @brief Polynomial class, coeffs are stored in reversed order
* The parameterization is given by
* f(s) = coeff_(n) + coeff_(n-1)/1!^s + ... + coeff_(0)/(n!)*s^n
* f(s) = coeff_normal_order_(0) + coeff_normal_order_(1)^s + ... +
* coeff_normal_order_(n)*s^n
* coeffs are scaled to have straightforward physical
* meaning, also improve the efficiency when evaluating the derivatives.
*/
template <int N_DEG> class Polynomial {
public:
typedef Vecf<N_DEG + 1> VecNf;
enum { NeedsToAlign = (sizeof(VecNf) % 16) == 0 };
Polynomial() {
set_zero();
}
Polynomial(const VecNf& coeff) : coeff_(coeff) {
update();
}
/**
* @brief Return coefficients of the polynomial
*/
VecNf coeff() const {
return coeff_;
}
/**
* @brief Set coefficients of the polynomial
*/
void set_coeff(const VecNf& coeff) {
coeff_ = coeff;
update();
}
void update() {
for (int i = 0; i < N_DEG + 1; i++) {
coeff_normal_order_[i] = coeff_[N_DEG - i] / fac(i);
}
}
/**
* @brief Set coefficients of the polynomial to zero
*/
void set_zero() {
coeff_.setZero();
coeff_normal_order_.setZero();
}
/**
* @brief Return position of polynomial with respect to parameterization
* @param s value of polynomial parameterization
*/
inline decimal_t evaluate(const decimal_t& s, const int& d) const {
// Use horner's rule for quick evaluation
decimal_t p = coeff_(0) / fac(N_DEG - d);
for (int i = 1; i <= N_DEG - d; i++) {
p = (p * s + coeff_(i) / fac(N_DEG - i - d));
}
return p;
// After testing, above is generally faster than below (obvious when d = 1,
// less obvious as d increases)
// decimal_t p = coeff_normal_order_[N_DEG] * fac(N_DEG) / fac(N_DEG - d);
// for (int i = 1; i <= N_DEG - d; i++) {
// p = (p * s + coeff_normal_order_[N_DEG - i] * fac(N_DEG - i) /
// fac(N_DEG - i - d));
// }
// return p;
}
inline decimal_t evaluate(const decimal_t& s) const {
// Use horner's rule for quick evaluation
// note that this function is much faster than evaluate(s, 0);
decimal_t p = coeff_normal_order_[N_DEG];
for (int i = 1; i <= N_DEG; i++) {
p = (p * s + coeff_normal_order_[N_DEG - i]);
}
return p;
}
inline decimal_t J(decimal_t s, int d) const {
if (d == 3) {
// integration of squared jerk
return coeff_(0) * coeff_(0) / 20.0 * pow(s, 5) + coeff_(0) * coeff_(1) / 4 * pow(s, 4)
+ (coeff_(1) * coeff_(1) + coeff_(0) * coeff_(2)) / 3 * pow(s, 3) + coeff_(1) * coeff_(2) * s * s
+ coeff_(2) * coeff_(2) * s;
} else if (d == 2) {
// integration of squared accleration
return coeff_(0) * coeff_(0) / 252 * pow(s, 7) + coeff_(0) * coeff_(1) / 36 * pow(s, 6)
+ (coeff_(1) * coeff_(1) / 20 + coeff_(0) * coeff_(2) / 15) * pow(s, 5)
+ (coeff_(0) * coeff_(3) / 12 + coeff_(1) * coeff_(2) / 4) * pow(s, 4)
+ (coeff_(2) * coeff_(2) / 3 + coeff_(1) * coeff_(3) / 3) * pow(s, 3) + coeff_(2) * coeff_(3) * s * s
+ coeff_(3) * coeff_(3) * s;
} else {
assert(false);
}
return 0.0;
}
/**
* @brief Generate jerk-optimal primitive with boundary condition
* @note The polynomial should have degree >= quintic (5)
* @param p1, x0 position
* @param dp1, x0 velocity
* @param ddp1, x0 acceleration
* @param p2, x1 position
* @param dp2, x1 velocity
* @param ddp2, x1 acceleration
* @param S, duration
*/
void GetJerkOptimalConnection(const decimal_t p1, const decimal_t dp1, const decimal_t ddp1, const decimal_t p2,
const decimal_t dp2, const decimal_t ddp2, const decimal_t S) {
assert(N_DEG >= 5);
Vecf<6> b;
b << p1, dp1, ddp1, p2, dp2, ddp2;
coeff_.setZero();
// NOTE: fix the singularity of S=0 caused
// by stopping traj
if (S < kEPS) {
Vecf<6> c;
c << 0.0, 0.0, 0.0, ddp1, dp1, p1;
coeff_.template segment<6>(N_DEG - 5) = c;
return;
}
MatNf<6> A_inverse;
if (!LookUpCache(S, &A_inverse)) {
A_inverse = GetAInverse(S);
}
auto coeff = A_inverse * b;
coeff_[N_DEG - 5] = coeff(0) * fac(5);
coeff_[N_DEG - 4] = coeff(1) * fac(4);
coeff_[N_DEG - 3] = coeff(2) * fac(3);
coeff_[N_DEG - 2] = coeff(3) * fac(2);
coeff_[N_DEG - 1] = coeff(4) * fac(1);
coeff_[N_DEG - 0] = coeff(5);
update();
// coeff_.template segment<6>(N_DEG - 5) = A_inverse * b;;
}
/**
* @Get look up cached A inverse
*/
bool LookUpCache(const decimal_t S, MatNf<6>* A_inverse) {
auto it = kTableAInverse.find(S);
if (it != kTableAInverse.end()) {
*A_inverse = it->second;
return true;
} else {
return false;
}
}
/**
* @brief Debug function
*/
void print() const {
std::cout << std::fixed << std::setprecision(7) << coeff_.transpose() << std::endl;
}
private:
VecNf coeff_;
VecNf coeff_normal_order_;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign)
};
template <int N_DEG, int N_DIM> class PolynomialND {
public:
PolynomialND() {}
PolynomialND(const std::array<Polynomial<N_DEG>, N_DIM>& polys) : polys_(polys) {}
/**
* @brief Return a reference to a certain 1D polynomial
* @param j index of the dimension
*/
Polynomial<N_DEG>& operator[](int j) {
assert(j < N_DIM);
return polys_[j];
}
/**
* @brief Return evaluated vector
* @param s evaluation point
* @param d derivative to take
*/
inline void evaluate(const decimal_t s, int d, Vecf<N_DIM>* vec) const {
for (int i = 0; i < N_DIM; i++) {
(*vec)[i] = polys_[i].evaluate(s, d);
}
}
inline void evaluate(const decimal_t s, Vecf<N_DIM>* vec) const {
for (int i = 0; i < N_DIM; i++) {
(*vec)[i] = polys_[i].evaluate(s);
}
}
void print() const {
for (int i = 0; i < N_DIM; i++)
polys_[i].print();
}
private:
std::array<Polynomial<N_DEG>, N_DIM> polys_;
};
} // namespace common
#endif | true |
ee6cdd73d4fbf4b8967ee1f6b5a08121b5c58800 | C++ | venkatarajasekhar/tortuga | /packages/core/include/PropertySetDetail.h | UTF-8 | 6,021 | 2.640625 | 3 | [] | no_license | /*
* Copyright (C) 2009 Robotics at Maryland
* Copyright (C) 2009 Joseph Lisee <jlisee@umd.edu>
* All rights reserved.
*
* Author: Joseph Lisee <jlisee@umd.edu>
* File: packages/core/include/PropertySetDetail.h
*/
#ifndef RAM_CORE_PROPERTYSETDETAIL_H_04_11_2009
#define RAM_CORE_PROPERTYSETDETAIL_H_04_11_2009
namespace ram {
namespace core {
template <typename T>
void PropertySet::addProperty(const std::string& name, const std::string& desc,
T defaultValue, T* valuePtr)
{
addProperty(core::PropertyPtr(
new core::VariableProperty<T>(name, desc, defaultValue, valuePtr)));
}
template <typename T>
void PropertySet::addProperty(const std::string& name, const std::string& desc,
T defaultValue,
typename FunctionProperty<T>::GetterFunc getter,
typename FunctionProperty<T>::SetterFunc setter)
{
addProperty(core::PropertyPtr(
new core::FunctionProperty<T>(name, desc, defaultValue, getter,
setter)));
}
template <typename T>
void PropertySet::addProperty(core::ConfigNode config, bool requireInConfig,
const std::string& name, const std::string& desc,
T defaultValue, T* valuePtr)
{
core::PropertyPtr prop(
new core::VariableProperty<T>(name, desc, defaultValue, valuePtr));
addProperty(prop);
loadValueFromConfig<T>(config, prop, requireInConfig);
}
template <typename T>
void PropertySet::addProperty(core::ConfigNode config, bool requireInConfig,
const std::string& name, const std::string& desc,
T defaultValue, T* valuePtr, T min, T max)
{
core::PropertyPtr prop(
new core::VariableProperty<T>(name, desc, defaultValue, valuePtr, min,
max));
addProperty(prop);
loadValueFromConfig<T>(config, prop, requireInConfig);
}
template <typename T>
void PropertySet::addProperty(core::ConfigNode config, bool requireInConfig,
const std::string& name, const std::string& desc,
T defaultValue,
typename FunctionProperty<T>::GetterFunc getter,
typename FunctionProperty<T>::SetterFunc setter)
{
core::PropertyPtr prop(
new core::FunctionProperty<T>(name, desc, defaultValue, getter,
setter));
addProperty(prop);
loadValueFromConfig<T>(config, prop, requireInConfig);
}
template <typename T>
void PropertySet::addProperty(core::ConfigNode config, bool requireInConfig,
const std::string& name, const std::string& desc,
T defaultValue,
typename FunctionProperty<T>::GetterFunc getter,
typename FunctionProperty<T>::SetterFunc setter,
T min, T max)
{
core::PropertyPtr prop(
new core::FunctionProperty<T>(name, desc, defaultValue, getter,
setter, min, max));
addProperty(prop);
loadValueFromConfig<T>(config, prop, requireInConfig);
}
template <typename T>
void PropertySet::loadValueFromConfig(core::ConfigNode config,
core::PropertyPtr prop,
bool requireInConfig)
{
std::string name(prop->getName());
if (requireInConfig)
assert(config.exists(name) && "Value does not exist in config file");
core::ConfigNode valueNode(config[name]);
loadValueFromNode<T>(config, valueNode, prop);
}
template <typename T>
void PropertySet::loadValueFromNode(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop)
{
// You need a specific specialization for this type
BOOST_STATIC_ASSERT(sizeof(T) == 0);
}
// See PropertySet.cpp for the specialization implementations
template <>
void PropertySet::loadValueFromNode<int>(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
template <>
void PropertySet::loadValueFromNode<double>(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
template <>
void PropertySet::loadValueFromNode<bool>(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
#ifdef RAM_WITH_MATH
template <>
void PropertySet::loadValueFromNode<math::Radian>(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
template <>
void PropertySet::loadValueFromNode<math::Degree>(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
template <>
void PropertySet::loadValueFromNode<math::Vector2>(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
template <>
void PropertySet::loadValueFromNode<math::Vector3>(core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
template <>
void PropertySet::loadValueFromNode<math::Quaternion>(
core::ConfigNode config,
core::ConfigNode valueNode,
core::PropertyPtr prop);
#endif // RAM_WITH_MATH
} // namespace core
} // namespace ram
#endif // RAM_CORE_PROPERTYSETDETAIL_H_04_11_2009
| true |
fbb8dc29d8120c0822a27e93c23d73eea1dfb873 | C++ | sebasutp/tests | /primes/my_sieve.cpp | UTF-8 | 1,940 | 3.546875 | 4 | [] | no_license | /**
* Finds how many prime numbers are there up to a certain value passed as
* parameter
*/
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
uint64_t map_sieve_ix(uint64_t ix) {
return (ix - 3) / 2;
}
struct Sieve {
std::vector<bool> sieve;
uint64_t limit;
uint64_t N;
bool is_prime(uint64_t x) const {
return (x==2) || sieve[map_sieve_ix(x)];
}
uint64_t count() const {
return N;
}
void add_prime(uint64_t x) {
N++;
//std::cout << x << std::endl;
for (uint64_t i = x*x; i <= limit; i += 2*x) {
sieve[map_sieve_ix(i)] = false; // all multiples are not prime
}
}
Sieve(uint64_t limit) {
this->limit = limit;
if (limit < 2) {
N = 0;
return;
}
N = 1; // The number 2 is prime, check from 3 onwards
if (N == 2) return;
sieve = std::vector<bool>(map_sieve_ix(limit)+2, true);
//std::cout << "17: " << is_prime(17) << std::endl;
for (uint64_t p=3; p<=limit; p+=2) {
if (is_prime(p)) {
add_prime(p);
//std::cout << "17: " << is_prime(17) << std::endl;
}
}
}
};
using namespace std;
int main(int argc, char* argv[]) {
try {
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "print usage message")
("limit,l", po::value<uint64_t>(), "up to which number do we count primes");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")){
cout << desc << endl;
return 1;
}
if (vm.count("limit") == 0) {
cout << "you must pass a limit (use --limit, check help)" << endl;
return 1;
}
uint64_t limit = vm["limit"].as<uint64_t>();
Sieve s(limit);
cout << s.count() << endl;
} catch (std::exception& ex) {
cerr << "Error: " << ex.what() << endl;
return 1;
}
}
| true |
12ddd1b128836589560936341aa954639ff59216 | C++ | JennyChen9827/Calculate-pi-value-with-c- | /Collatz.cpp | UTF-8 | 570 | 3.375 | 3 | [] | no_license | #include<iostream>
#include <cstdlib>
using namespace std;
void collatz_demo(int n){
if(n == 0)
return;
if(n % 2 == 0){
n = n / 2;
if( n == 1)
cout << n << endl;
else {
cout << n << ", ";
collatz_demo(n);
}
}
else{
n = (n * 3) + 1;
cout << n << ", ";
collatz_demo(n);
}
}
int main(int argc, char* argv[]){
int n = atoi(argv[1]);
if(n <= 0){
cout << "Positive natural number only!" << endl;
return 0;
}
cout << "Start Collatz sequence for " << n << ":\n";
collatz_demo(n);
return 0;
} | true |
09cdd0997d63fdc578f16278a99f927aa02feea8 | C++ | walker-zheng/code | /concurrency/sender.h | UTF-8 | 354 | 2.921875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "queue.h"
namespace messaging {
class sender {
queue * q;
public:
sender() :
q(nullptr)
{}
explicit sender(queue * q_) :
q(q_)
{}
template<typename Message>
void send(Message const & msg)
{
if (q)
{
q->push(msg);
}
}
};
}
| true |
a85c34c6eb724e5592e93eb7fc6a2b2e25b0ffdd | C++ | geosender/Cannon_Practice | /Cannon Practice/Game420Lab7/WoodenBox.cpp | UTF-8 | 1,771 | 2.734375 | 3 | [] | no_license | #include "WoodenBox.h"
WoodenBox::WoodenBox(b2World* world, float x, float y)
:GameObject(world)
{
CreateBox2dObject(x, y);
LoadTexture("images\\wood_box.bmp");
LoadTexture("images\\wood_box_mask.bmp", true);
}
WoodenBox::~WoodenBox(void)
{
}
void WoodenBox::CreateBox2dObject(float x, float y)
{
// Define the dynamic body. We set its position and call the body factory.
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
//bodyDef.position.Set(0.0f, 50.0f);
bodyDef.position.Set(x, y);
bodyDef.angularVelocity = 0.0f;
b2Vec2 v(0, 1.0f);
//bodyDef.linearVelocity = v;
body = world->CreateBody(&bodyDef);
// Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(2.5f, 2.5f);
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
// Set the box density to be non-zero, so it will be dynamic.
fixtureDef.density = 1.0f;
// Override the default friction.
//fixtureDef.friction = 0.3f;
// Add the shape to the body.
//fixtureDef.restitution = 0.5f;
body->CreateFixture(&fixtureDef);
}
void WoodenBox::Render()
{
b2Vec2 position = body->GetPosition();
float32 angle = body->GetAngle();
glPushMatrix();
glTranslatef(position.x, position.y, 0);
glRotated(angle * 180 / 3.14159265, 0, 0, 1.0f);
glColor3f(1.0f, 1.0f, 1.0f);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ZERO);
glEnable(GL_TEXTURE_2D);
glBindTexture( GL_TEXTURE_2D, texture );
//glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
glBegin(GL_QUADS);
glTexCoord2i( 0, 1 );
glVertex2f(-2.5f, 2.5f);
glTexCoord2i( 0, 0 );
glVertex2f(-2.5f, -2.5f);
glTexCoord2i( 1, 0 );
glVertex2f(2.5f, -2.5f);
glTexCoord2i( 1, 1 );
glVertex2f(2.5f, 2.5f);
glEnd();
glPopMatrix();
} | true |
cd4f858df3faebf3be5149eee32ff0b0249a201d | C++ | zsmountain/leetcode | /c++/convert_sorted_array_to_binary_search_tree.cpp | UTF-8 | 1,240 | 3.984375 | 4 | [
"Apache-2.0"
] | permissive | /*
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
*/
/*
* Similar to "Convert Sorted List to Binary Search Tree"
*/
#include "helper.h"
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* 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 {
public:
TreeNode *sortedArrayToBST(vector<int> &nums) {
if (nums.empty()) {
return NULL;
}
return traverse(nums, 0, nums.size());
}
TreeNode *traverse(vector<int> &nums, int start, int end) {
if (start >= end) {
return NULL;
}
int mid = (start + end) / 2;
TreeNode *root = new TreeNode(nums[mid]);
root->left = traverse(nums, start, mid);
root->right = traverse(nums, mid + 1, end);
return root;
}
};
int main() {
Solution s;
vector<int> nums({1, 2, 3, 4, 5});
TreeNode *root = s.sortedArrayToBST(nums);
root->print();
return 0;
}
| true |
588d39ef0ddd7bad5a2f6c103c11f58a8ba54403 | C++ | hidoopos/cbf-ht | /hashtable.cpp | GB18030 | 7,301 | 2.9375 | 3 | [] | no_license | #include "hashtable.h"
#include <memory.h>
#include <assert.h>
#define TABLE_SIZE (1024*1024)
#define MAX_LOAD_FACTOR 0.5
// ӽڵ
void addChild(AuxTreeNode* nParent, AuxTreeNode* nChild) {
if (nChild == NULL){
printf("NULL\n");
return;
}
if(nParent == NULL){
printf("NULL\n");
return;
}
nChild->nextSibling = nParent->firstChild;
nChild->parent = nParent;
nParent->firstChild = nChild;
}
// ɾӽڵ
void removeChild(AuxTreeNode* nParent, AuxTreeNode* nChild) {
if (nChild == NULL){
printf("NULL\n");
return;
}
if(nParent == NULL){
printf("NULL\n");
return;
}
if (nParent != nChild->parent)
return;
if (nParent->firstChild == nChild)
nParent->firstChild = nChild->nextSibling;
else {
AuxTreeNode* pre = nParent->firstChild;
while (pre->nextSibling != NULL) {
if (pre->nextSibling == nChild) {
pre->nextSibling = nChild->nextSibling;
break;
}
pre = pre->nextSibling;
}
}
nChild->nextSibling = NULL;
nChild->parent = NULL;
}
// нʵǰнڵΪ/
void setNonrealNodesInSubtreeTo(AuxTreeNode* nNode, NodeType type) {
if (nNode == NULL){
printf("NULL\n");
return;
}
if(nNode->type != Real) nNode->type = type;
AuxTreeNode* ptr = nNode->firstChild;
while (ptr != NULL) {
if (ptr->type != Real)
setNonrealNodesInSubtreeTo(ptr, type);
ptr = ptr->nextSibling;
}
}
// ɾӽڵ
void removeAllChild(AuxTreeNode* nNode) {
if(nNode == NULL){
printf("NULL\n");
return;
}
AuxTreeNode* temp;
while (nNode->firstChild != NULL) {
temp = nNode->firstChild->nextSibling;
removeAllChild(nNode->firstChild);
delete nNode->firstChild;
nNode->firstChild = temp;
}
}
/* constructor of struct kv */
static void init_kv(struct kv* kv)
{
kv->next = NULL;
}
/* the classic Times33 hash function */
static unsigned int hash_33(const char* key)
{
unsigned int hash = 0;
while (*key) {
hash = (hash << 5) + hash + *key++;
}
return hash;
}
/* new a HashTable instance */
HashTable* hash_table_new(uint64 htSize)
{
HashTable* ht = (HashTable* )malloc(sizeof(HashTable));
if (NULL == ht) {
hash_table_delete(ht);
assert(0==1);
return NULL;
}
ht->table = (kv ** )malloc(sizeof(struct kv*) * htSize);
if (NULL == ht->table) {
assert(0==1);
hash_table_delete(ht);
return NULL;
}
memset(ht->table, 0, sizeof(struct kv*) * htSize);
ht->content = 0;
ht->tableSize = htSize;
ht->conflict = 0;
return ht;
}
/* delete a HashTable instance */
void hash_table_delete(HashTable* ht)
{
if (ht) {
if (ht->table) {
uint64 i = 0;
for (i = 0; i<ht->tableSize; i++) {
struct kv* p = ht->table[i];
struct kv* q = NULL;
while (p) {
q = p->next;
p = q;
}
}
free(ht->table);
ht->table = NULL;
}
free(ht);
}
}
char* copyString(const char *src){
//string dst = src;
assert(src!= nullptr);
char *dst = new char[strlen(src)+1];
for(int i = 0; i <= strlen(src); i++){
dst[i] = src[i];
}
return dst;
}
/* insert or update a value indexed by key for CBF-HT*/
int hash_table_put(HashTable* ht, string key, ForwardInfo info)
{
uint64 i = CityHash64(key.c_str(), key.length()) % ht->tableSize;
struct kv* p = ht->table[i];
struct kv* prep = p;
while (p) { /* if key is already stored, update its value */
if (strcmp(key.c_str(), p->key) == 0) {
p->info = info;
ht->conflict ++;
break;
}
prep = p;
p = p->next;
}
if (p == NULL) {/* if key has not been stored, then add it */
struct kv * mkv = (struct kv*)malloc(sizeof(struct kv));
if (NULL == mkv) {
assert(0==1);
return -1;
}
mkv->next = NULL;
mkv->info = info;
mkv->key = copyString(key.c_str());
//mkv->key = new char[key.length()+1];
//strcpy(mkv->key, key.c_str());
//printf(" %s %d\n",mkv->key,strlen(mkv->key));
if (prep == NULL) {
ht->table[i] = mkv;
}
else {
prep->next = mkv;
}
ht->content ++;
}
return 0;
}
/* insert or update a value indexed by key for HPT*/
int hash_table_put2(HashTable* ht, string key, AuxTreeNode *value)
{
// uint64 i = CityHash64(key.c_str(), key.length()) % ht->tableSize;
// struct kv* p = ht->table[i];
// struct kv* prep = p;
//
// while (p) { /* if key is already stroed, update its value */
// if (strcmp(key.c_str(), p->key) == 0) {
// p->value = value;
// ht->conflict ++;
// break;
// }
// prep = p;
// p = p->next;
// }
//
// if (p == NULL) {/* if key has not been stored, then add it */
// struct kv * mkv = (struct kv*)malloc(sizeof(struct kv));
// if (NULL == mkv) {
// return -1;
// }
// mkv->next = NULL;
// mkv->value = new AuxTreeNode;
// mkv->value = value;
// mkv->key = copyString(key.c_str());
//
//
// if (prep == NULL) {
// ht->table[i] = mkv;
// }
// else {
// prep->next = mkv;
// }
//
// ht->content ++;
// }
//
// return 0;
}
/* get a value indexed by key */
void* hash_table_get(HashTable* ht, string key)
{
uint64 i = CityHash64(key.c_str(), key.length()) % ht->tableSize;
assert( i>=0 );
struct kv* p = ht->table[i];
while (p) {
if (strcmp(key.c_str(), p->key) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
/* remove a value indexed by key */
void hash_table_rm(HashTable* ht, string key)
{
uint64 i = CityHash64(key.c_str(), key.length()) % ht->tableSize;
struct kv* p = ht->table[i];
struct kv* prep = p;
while (p) {
if (strcmp(key.c_str(), p->key) == 0) {
if (p == prep) {
ht->table[i] = p->next;
}
else {
prep->next = p->next;
}
ht->content --;
break;
}
prep = p;
p = p->next;
}
}
const uint64 gettableSize(HashTable* ht){
return ht->tableSize;
}
const uint64 getContentSize(HashTable* ht){
return ht->content;
}
const uint64 getConflict(HashTable* ht){
return ht->conflict;
}
const double gethtLF(HashTable* ht){
ht->loadFactor = (double)ht->content/ht->tableSize;
return ht->loadFactor;
} | true |
f500e254190d3eeba8d8a59c8a275ae4c2a1b251 | C++ | heyihong/algorithm-contest-solution | /topcoder/srm652 div1/500_WA.cpp | UTF-8 | 1,964 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
const int MAXN(1010);
const long long INF(1LL << 60);
class MaliciousPath {
public:
long long minPath(int N, int K, vector <int> from, vector <int> to, vector <int> cost);
};
int q[MAXN];
long long dist[MAXN], _dist[MAXN];
bool bo[MAXN];
vector<pair<int, int> > g[MAXN], _g[MAXN];
int next(int x) {
return (x + 1) % MAXN;
}
void spfa(int N) {
int t = 0;
memset(bo, false, sizeof(bo));
for (int i = 0; i != N; ++i) {
dist[i] = INF;
}
dist[N - 1] = 0;
bo[N - 1] = true;
q[t++] = N - 1;
for (int h = 0; h != t; h = next(h)) {
for (pair<int, int> ed : _g[q[h]])
if (dist[ed.first] > dist[q[h]] + ed.second) {
dist[ed.first] = dist[q[h]] + ed.second;
if (!bo[ed.first]) {
bo[ed.first] = true;
q[t] = ed.first;
t = next(t);
}
}
bo[q[h]] = false;
}
}
void update_dist(int N) {
int t = 0;
for (int i = 0; i != N - 1; ++i) {
q[t++] = i;
bo[i] = true;
}
for (int h = 0; h != t; h = next(h)) {
long long val = INF;
for (pair<int, int> ed : g[q[h]]) {
val = min(val, dist[ed.first] + ed.second);
}
if (val > dist[q[h]]) {
for (pair<int, int> ed : _g[q[h]]) {
if (dist[ed.first] == dist[q[h]] + ed.second && !bo[ed.first]) {
bo[ed.first] = true;
q[t] = ed.first;
t = next(t);
}
}
dist[q[h]] = val;
}
bo[q[h]] = false;
}
}
long long MaliciousPath :: minPath(int N, int K, vector <int> from, vector <int> to, vector <int> cost) {
for (int i = 0; i != from.size(); ++i) {
g[from[i]].push_back(make_pair(to[i], cost[i]));
_g[to[i]].push_back(make_pair(from[i], cost[i]));
}
spfa(N);
if (dist[0] == INF)
return -1;
for (int i = 0; i != K; ++i) {
memcpy(_dist, dist, sizeof(dist));
for (int j = 0; j != N - 1; ++j) {
for (pair<int, int> ed : g[j])
dist[j] = max(dist[j], _dist[ed.first] + ed.second);
}
update_dist(N);
}
return dist[0];
}
| true |
95c45a26d74cd15dfdc2954605482c6cf69a1edd | C++ | shike1239/autonomous_exploration-1 | /src/my_move_base/include/my_move_base/HybricAStar.h | UTF-8 | 3,063 | 2.828125 | 3 | [] | no_license | //
// Created by parallels on 2/10/20.
//
#ifndef SRC_HYBRICASTAR_H
#define SRC_HYBRICASTAR_H
#include <vector>
#include <nav_msgs/OccupancyGrid.h>
using namespace std;
class HybricAStar{
public:
class cell{
public:
cell(){};
cell(int x,int y,int index):x(x),y(y),index(index){} ;
cell(int x,int y,int index,double g, double h,double f,int parent_index):
x(x),y(y),index(index),g(g),h(h),f(f),parent_index(parent_index){} ;
cell(int x,int y,int index,double g, double h,double f,int parent_index,double x_coord,double y_coord,double theta,double vs,double steering_angle):
x(x),y(y),index(index),g(g),h(h),f(f),parent_index(parent_index),x_coord(x_coord),y_coord(y_coord),theta(theta),vs(vs),steering_angle(steering_angle){} ;
cell(int x,int y,int index,double g, double h,double f,int parent_index,double x_coord,double y_coord,double theta,double vs,double steering_angle,int parent_id,int id):
x(x),y(y),index(index),g(g),h(h),f(f),parent_index(parent_index),x_coord(x_coord),y_coord(y_coord),theta(theta),vs(vs),steering_angle(steering_angle),parent_id(parent_id),id(id){} ;
int x = 0; // grid index
int y = 0; // grid index
double x_coord = 0; // coord in map
double y_coord = 0; // coord in map
double theta = 0;//based on x axis, -pi to pi; direction of the car heading
int index = 0;
double g = 0;
double f = 0;
double h = 0 ;
int parent_index = 0 ;
double vs = 0;
double steering_angle = 0;
int id = 0;
int parent_id = 0;
};
HybricAStar(){
delta_t = 0.4;//0.12 0.3N 0.6Y
length_of_car = 0.5075;
previous_id_count = 0;
id_for_use = 0;
};
~HybricAStar(){};
nav_msgs::OccupancyGrid my_map;
nav_msgs::OccupancyGrid close_list_map_;//used for display the points in the close list
nav_msgs::OccupancyGrid neighbor_map_;//used for display the points named neighbor
vector<HybricAStar::cell> openlist;
vector<HybricAStar::cell> closelist;
HybricAStar::cell starting_point;
HybricAStar::cell goal;
vector<HybricAStar::cell> path;
bool search_success_ = true;
void A_star_search();
vector<double > grid_to_coord(int* gridXY);
std::vector<int> coord_to_grid(std::vector<double> coord);
void initialize();
void SetStartingGoalPoint(double x_coord_s,double y_coord_s,double theta_s,double x_coord_g,double y_coord_g);
private:
double delta_t ;//0.12 0.3N 0.6Y
double length_of_car ;
vector<double> discrete_vs;// m/s
vector<double> discrete_steering_angles;//radian alpha
int previous_id_count ;
int id_for_use ;
bool compare(HybricAStar::cell c1,HybricAStar::cell c2);
double get_distance(HybricAStar::cell c1,HybricAStar::cell c2);
double get_distance_1(int x1,int y1,int x2,int y2);
vector<HybricAStar::cell> get_neighbor(HybricAStar::cell cell);
void set_path_id();
};
#endif //SRC_HYBRICASTAR_H
| true |
f80d4c95dfe4d27ae9c556937111cc4aa5e5c692 | C++ | zysundar/CPP_Programming | /structer.cpp | UTF-8 | 382 | 2.9375 | 3 | [] | no_license | #include<conio.h>
#include<iostream>
using namespace std;
int main()
{struct book
{char book[30];
int pages;
int price;
}b;
cout<<"enter the book name";
cin>>b.book;
cout<<"enter the pages";
cin>>b.pages;
cout<<"enter the price";
cin>>b.price;
cout<<"the element of the book are"<<endl;;
cout<<b.book<<endl;
cout<<b.pages<<endl;
cout<<b.price<<endl;
getch();
}
| true |
4313753e3a4df3a36e8b61c43b5edb323799a0f5 | C++ | vvivek92/data-structures-and-algorithms | /trees/sum_less_than_k.cpp | UTF-8 | 1,868 | 3.65625 | 4 | [] | no_license | #include <queue>
#include <iostream>
using namespace std;
struct node {
struct node * left;
struct node * right;
int data;
};
node *newNode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
node * create_tree(void) {
int i=0;
node* root=new node();
root->left=root->right=NULL;
root->data=i++;
queue<node *> q;
q.push(root);
while(i<13) {
node * temp=q.front();
q.pop();
temp->left=new node ();
q.push(temp->left);
temp->left->left=temp->left->right=NULL;
temp->left->data=i++;
temp->right=new node ();
q.push(temp->right);
temp->right->right=temp->right->left=NULL;
temp->right->data=i++;
}
return root;
}
void print (node * root) {
if(root==NULL) return;
cout<<endl<<root->data<<endl;
print(root->left);
print(root->right);
}
node * remove(node * root, int sum, int k) {
if(root==NULL) return NULL;
int sum_new=sum+ root->data;
if(sum_new>=k) return root;
root->left=remove(root->left,sum_new,k);
root->right=remove(root->right,sum_new,k);
if(!root->right && !root->left) {
delete root;
return NULL;
}
else
return root;
}
int main(void) {
node* root = newNode(1);
root->left = newNode(100);
root->right = newNode(2);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
print(root);
int sum=0;
root=remove(root,sum,99);
cout<<root->data<<" 00000000000000000000"<<endl;
print(root);
}
| true |
f40136711c0e87870f5ca2aacf7d40874b74b77e | C++ | Roagen7/3d | /usage/CollisionScene.cpp | UTF-8 | 3,760 | 2.53125 | 3 | [] | no_license | //
// Created by roagen on 26.08.2021.
//
#include "CollisionScene.h"
#include "../src/spatial/collider/SphereCollider.h"
CollisionScene::CollisionScene() {
this->initMaterials();
this->initObjects();
}
void CollisionScene::initMaterials() {
auto m1 = Material();
m1.getTextureFromFile("../assets/texture/moon.jpg");
this->materials.push_back(m1);
}
void CollisionScene::initObjects() {
auto sph1 = Mesh::loadFromObj("../assets/mesh/sphere.obj", true);
auto sph2 = Mesh::loadFromObj("../assets/mesh/sphere.obj", true);
sph1.material = &this->materials[1];
sph2.material = &this->materials[1];
auto col1 = SphereCollider(0);
col1.radius = 1;
auto col2 = SphereCollider(1);
col2.radius = 1;
this->pushMesh(sph1);
this->pushSphereCollider(col1);
this->pushMesh(sph2);
this->pushSphereCollider(col2);
auto n1 = BallNode(&this->meshes[0], &this->sphereColliders[0]);
auto n2 = BallNode(&this->meshes[1], &this->sphereColliders[1]);
n1.position = {0,0,5};
n2.position = {10,0,0};
n1.mass = 1;
n2.mass = 3;
n1.setTranslation(n1.position);
n1.velocity = {0,0,-0.04};
n2.setTranslation(n2.position);
n2.velocity = {-0.1,0,0};
this->balls.push_back(n1);
this->balls.push_back(n2);
}
void CollisionScene::updateProperties(double timeDelta, std::vector<sf::Keyboard::Key> keysPressed, sf::Vector2<double> mouseDelta) {
const double LOOKSENS = 0.002;
const double MOVESPEED = 2;
for(auto key : keysPressed){
if(key == sf::Keyboard::A){
this->camera.pos += Matrix::getRotationMatrixAxisY(1.63).multiplyByVector(this->camera.lookDir() * MOVESPEED);
}
if(key == sf::Keyboard::D){
this->camera.pos -= Matrix::getRotationMatrixAxisY(1.63).multiplyByVector(this->camera.lookDir() * MOVESPEED);
}
if(key == sf::Keyboard::W){
this->camera.pos += this->camera.lookDir() * MOVESPEED;
}
if(key == sf::Keyboard::S){
this->camera.pos -= this->camera.lookDir() * MOVESPEED;
}
if(key == sf::Keyboard::Space){
this->camera.pos += {0,-MOVESPEED,0} ;
}
if(key == sf::Keyboard::LShift){
this->camera.pos -= {0,-MOVESPEED,0} ;
}
}
this->camera.pitch = std::max(-2.8,std::min(2.8, this->camera.pitch));
this->camera.yaw -= mouseDelta.x * LOOKSENS;
this->camera.pitch -= mouseDelta.y * LOOKSENS;
for(auto &n : this->balls){
n.position += n.velocity;
n.setTranslation(n.position);
}
for(int i = 0; i < this->balls.size(); i++){
for(int j = i + 1; j < this->balls.size(); j++){
auto& n1 = this->balls[i];
auto& n2 = this->balls[j];
if(SphereCollider::checkCollision(*n1.sphCollider,*n2.sphCollider)){
std::cout << "tutajj" << std::endl;
// auto x1 = n1.position;
// auto x2 = n2.position;
// auto m1 = n1.mass;
// auto m2 = n2.mass;
//
// auto v1 = n1.velocity;
// auto v2 = n2.velocity;
//
// auto r = x2-x1;
// auto rLenSq = VectorUtils::dot(r,r) * VectorUtils::dot(r,r);
//
// sf::Vector3<double> v1p = v1 - (x1 - x2) * VectorUtils::dot(v1-v2,x1-x2) * (double) 2 * m2 /(m1 + m2) / rLenSq;
// sf::Vector3<double> v2p = v2 - (x2 - x1) * VectorUtils::dot(v2-v1,x2-x1) * (double) 2 * m1 /(m1 + m2) / rLenSq;
// n1.velocity = v1p;
// n2.velocity = v2p;
// n1.position += -2.0 * v1p;
// n2.position += -2.0 * v2p;
}
}
}
}
| true |
e11fb95a66ffdaad0ae823305cca910460e20f13 | C++ | HsuJv/Note | /Code/C/College/Algorithm/Ex4/RSA.cpp | GB18030 | 2,093 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int ext_euclid(int a, int b, int f, int e){
// e * 0 + * 1 = (1)
// e * 1 + * 1 = e (2)
// e * (0 - 1 * ( / e)) + ..... = % e
// eͦջʣһijһʽҲĦ % e == 1
// ʱʽe˵ϵҪde^ (-1)
// (1)ʽe˵ϵaʾ(2)ʽe˵ϵbʾm = / e; n = % e
int m, n, t;
if (e == 1) return b;
m = f / e;
n = f % e;
t = a - b * m;
ext_euclid(b, t, e, n);
}
int main() {
// pq
int p, q;
cout << "һp(101): ";
cin >> p;
cout << "һq(113): ";
cin >> q;
// n = p * qֵ
int n = p * q;
cout << "ʱÿĴСܳn = p * q = ";
cout << n << endl;
// æ(n) = (p - 1) * (q - 1)ֵ
int f = (p - 1) * (q - 1);
cout << "ģ(n) = (p - 1) * (q - 1) = ";
cout << f << endl << endl;
// ѡȡ(n)ʵĹԿe
int e;
cout << "(n)ʵĹԿe(3533):";
cin >> e;
// eͦ(n)˽Կd
int d = ext_euclid(0, 1, f, e);
while (d <= 0) d += f;
cout << "ͨչŷ㷨ԿdΪ" << d << endl;
// ɵĹԿ{e, n}Mм
int M, C;
cout << "ڹԿ{e, n}˽Կ{d, n}ϡ\n\nҪݽ";
cout << "м(9726)";
cin >> M;
C = 1;
for(int i = 1; i <= e; i++ ) {
C = C * M % n;
}
cout << "M = " << M << "ܺõC = M^e(mod n)" << C << endl;
// ɵ˽Կ˽Կ{e, n}Cн
M = 1;
for(int i = 1; i <= d; i++ ) {
M = M * C % n;
}
cout << "C = " << C << "ܺõM = C^d(mod n)" << M << endl;
}
| true |
77fa82ef6b01621264e83a76d105697bf9e08df1 | C++ | avatarbuss/dotnet-api-docs | /samples/snippets/cpp/VS_Snippets_CLR/console.beep/CPP/beep.cpp | UTF-8 | 857 | 3.390625 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive |
//<snippet1>
// This example demonstrates the Console.Beep() method.
using namespace System;
int main()
{
array<String^>^args = Environment::GetCommandLineArgs();
int x = 0;
//
if ( (args->Length == 2) && (Int32::TryParse( args[ 1 ], x ) == true) && ((x >= 1) && (x <= 9)) )
{
for ( int i = 1; i <= x; i++ )
{
Console::WriteLine( "Beep number {0}.", i );
Console::Beep();
}
}
else
Console::WriteLine( "Usage: Enter the number of times (between 1 and 9) to beep." );
}
/*
This example produces the following results:
>beep
Usage: Enter the number of times (between 1 and 9) to beep
>beep 9
Beep number 1.
Beep number 2.
Beep number 3.
Beep number 4.
Beep number 5.
Beep number 6.
Beep number 7.
Beep number 8.
Beep number 9.
*/
//</snippet1>
| true |
d3de7ceefc9e4af008ca6f1876d0208ac2f0a401 | C++ | TopHK/fightcode | /ArrowOffer/find_special_numbers.cpp | UTF-8 | 1,109 | 3.5 | 4 | [] | no_license | #include<vector>
#include<iostream>
using namespace std;
int FindSpecialNumbers(const vector<int>& nums) {
int result = 0;
for (const auto& num : nums) {
result ^= num;
}
return result;
}
vector<int> FindSpecialNumbersV2(const vector<int>& nums) {
int flag = 0;
for (const auto& num : nums) {
flag ^= num;
}
int result1 = 0, result2 = 0;
for (int i = 0; i < 32; ++i) {
int is_bit_one = flag & (1 << i);
if(is_bit_one) {
for (const auto& num : nums) {
if ((num & (1 << i)) == is_bit_one) {
result1 ^= num;
} else {
result2 ^= num;
}
}
break;
}
}
return {result1, result2};
}
int main() {
// vector<int> nums = {1, 5, 3, 5, 8, 1, 3};
// cout << FindSpecialNumbers(nums) << endl;
vector<int> nums = {2, 3, 5, 3, 2, 1, 8, 9, 9, 8};
vector<int> results = FindSpecialNumbersV2(nums);
for (const auto& num : results) {
cout << num << " ";
}
cout << endl;
return 0;
} | true |
a825ee24f08a4488e2f2f996c28fd1bd7bb34189 | C++ | ahme5760/BasicGraphicsEngine | /Lighting and shading/a3_ahme5760/a3/src/a3.cpp | UTF-8 | 14,958 | 2.75 | 3 | [] | no_license | /**
* CP411 Assignment 3.
* Khaja Ali Ahmed
* 110425760
*
*/
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include "World.hpp"
#include "Camera.hpp"
#include "Light.hpp"
GLint winWidth = 800, winHeight = 800;
GLfloat red = 1.0, green = 1.0, blue = 1.0; //color
GLint moving = 0, xBegin = 0, coordinate = 1, type = 4, selected=0; // choose 0 because we're only dealing with cube
bool isShading = false;
bool isSolar = false;
bool OPENGL = false;
//Declare a world containing all objects to draw.
World myWorld;
Camera myCamera;
Light myLight;
void display(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
myCamera.setProjectionMatrix();
myWorld.draw_world(); // draw all objects in the world
myLight.draw();
glFlush();
glutSwapBuffers();
}
void winReshapeFcn(GLint newWidth, GLint newHeight) {
glViewport(0, 0, newWidth, newHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
winWidth = newWidth;
winHeight = newHeight;
}
void mouseAction(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
moving = 1;
xBegin = x;
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
moving = 0;
}
}
void mouseMotion(GLint x, GLint y) {
GLfloat rx, ry, rz, theta;
if (moving) {
if (coordinate == 1 && type == 1) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = myWorld.list[selected]->getMC().mat[0][0];
ry = myWorld.list[selected]->getMC().mat[1][0];
rz = myWorld.list[selected]->getMC().mat[2][0];
myWorld.list[selected]->rotate_mc(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 1 && type == 2) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = myWorld.list[selected]->getMC().mat[0][1];
ry = myWorld.list[selected]->getMC().mat[1][1];
rz = myWorld.list[selected]->getMC().mat[2][1];
myWorld.list[selected]->rotate_mc(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 1 && type == 3) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = myWorld.list[selected]->getMC().mat[0][2];
ry = myWorld.list[selected]->getMC().mat[1][2];
rz = myWorld.list[selected]->getMC().mat[2][2];
myWorld.list[selected]->rotate_mc(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 1 && type == 4) {
theta = (xBegin - x < 0) ? 1 : -1;
myWorld.list[selected]->scale_change(theta * 0.02);
}
else if (coordinate == 2 && type == 1) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = 1;
ry = 0;
rz = 0;
myWorld.list[selected]->rotate_origin(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 2 && type == 2) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = 0;
ry = 1;
rz = 0;
myWorld.list[selected]->rotate_origin(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 2 && type == 3) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = 0;
ry = 0;
rz = 1;
myWorld.list[selected]->rotate_origin(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 2 && type == 4) {
theta = (xBegin - x < 0) ? 1 : -1;
myWorld.list[selected]->translate(theta * 0.02, 0, 0);
}
else if (coordinate == 2 && type == 5) {
theta = (xBegin - x < 0) ? 1 : -1;
myWorld.list[selected]->translate(0, theta * 0.02, 0);
}
else if (coordinate == 2 && type == 6) {
theta = (xBegin - x < 0) ? 1 : -1;
myWorld.list[selected]->translate(0, 0, theta * 0.02);
}
else if (coordinate == 3 && type == 1) {
theta = (xBegin - x < 0) ? 1 : -1;
rx=1;
ry=0;
rz=0;
myCamera.rotate(rx,ry,rz, theta);
}
else if (coordinate == 3 && type == 2) {
theta = (xBegin - x < 0) ? 1 : -1;
rx=0;
ry=1;
rz=0;
myCamera.rotate(rx,ry,rz, theta);
}
else if (coordinate == 3 && type == 3) {
theta = (xBegin - x < 0) ? 1 : -1;
rx=0;
ry=0;
rz=1;
myCamera.rotate(rx,ry,rz, theta);
}
else if (coordinate == 3 && type == 4) {
theta = (xBegin - x < 0) ? 1 : -1;
rx=1*theta*0.2;
ry=0;
rz=0;
myCamera.translate(rx,ry,rz);
}
else if (coordinate == 3 && type == 5) {
theta = (xBegin - x < 0) ? 1 : -1;
rx=0;
ry=1*theta*0.2;
rz=0;
myCamera.translate(rx,ry,rz);
}
else if (coordinate == 3 && type == 6) {
theta = (xBegin - x < 0) ? 1 : -1;
rx=0;
ry=0;
rz=1*theta*0.2;
myCamera.translate(rx,ry,rz);
}
else if (coordinate == 3 && type == 7) {
theta = (xBegin - x < 0) ? 1 : -1;
if (myCamera.nearDist + theta*0.2 > 0){
myCamera.nearDist += theta*0.2;
}
}
else if (coordinate == 3 && type == 8) {
theta = (xBegin - x < 0) ? 1 : -1;
if (myCamera.farDist + theta*0.2 > 0){
myCamera.farDist += theta*0.2;
}
}
else if (coordinate == 3 && type == 9) {
theta = (xBegin - x < 0) ? 1 : -1;
myCamera.viewAngle += theta;
}
else if (coordinate == 5 && type == 5) {
theta = (xBegin - x < 0) ? 1 : -1;
myCamera.viewAngle += theta;
}
else if (coordinate == 4 && type == 1) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = 1;
ry = 0;
rz = 0;
myLight.rotate_origin(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 4 && type == 2) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = 0;
ry = 1;
rz = 0;
myLight.rotate_origin(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 4 && type == 3) {
theta = (xBegin - x > 0) ? 1 : -1;
rx = 0;
ry = 0;
rz = 1;
myLight.rotate_origin(rx, ry, rz, theta * 0.5);
}
else if (coordinate == 4 && type == 4) {
theta = (xBegin - x < 0) ? 1 : -1;
myLight.translate(theta * 0.02, 0, 0);
}
else if (coordinate == 4 && type == 5) {
theta = (xBegin - x < 0) ? 1 : -1;
myLight.translate(0, theta * 0.02, 0);
}
else if (coordinate == 4 && type == 6) {
theta = (xBegin - x < 0) ? 1 : -1;
myLight.translate(0, 0, theta * 0.02);
}
else if (coordinate == 4 && type == 7) {
theta = (xBegin - x < 0) ? 1 : -1;
myLight.Increment(theta * 0.02, 0, 0);
}
else if (coordinate == 4 && type == 8) {
theta = (xBegin - x < 0) ? 1 : -1;
myLight.Increment(0, 0, theta * 0.02);
}
else if (coordinate == 4 && type == 9) {
theta = (xBegin - x < 0) ? 1 : -1;
myLight.Increment(0, theta * 0.02, 0);
}
glutPostRedisplay();
}
}
void init(void) {
glClearColor(0.0, 0.0, 0.0, 1.0); // Set display-window color to black
glColor3f(red, green, blue);
myCamera.setProjectionMatrix();
myLight.translate(1, 1, 1);
}
void MCTransMenu(GLint transOption) {
switch (transOption) {
case 1: {
coordinate = 1;
type = 1;
}
break;
case 2: {
coordinate = 1;
type = 2;
}
break;
case 3: {
coordinate = 1;
type = 3;
}
break;
case 4: {
coordinate = 1;
type = 4;
}
break;
}
glutPostRedisplay();
}
void WCTransMenu(GLint transOption) {
switch (transOption) {
case 1: {
coordinate = 2;
type = 1;
}
break;
case 2: {
coordinate = 2;
type = 2;
}
break;
case 3: {
coordinate = 2;
type = 3;
}
break;
case 4: {
coordinate = 2;
type = 4;
}
break;
case 5: {
coordinate = 2;
type = 5;
}
break;
case 6: {
coordinate = 2;
type = 6;
}
break;
}
glutPostRedisplay();
}
void move(void){
GLfloat rx,ry,rz;
if (!OPENGL&&moving == 0){
if(!isSolar) {
rx = myWorld.list[selected]->getMC().mat[0][1];
ry = myWorld.list[selected]->getMC().mat[1][1];
rz = myWorld.list[selected]->getMC().mat[2][1];
myWorld.list[selected]->rotate_mc(rx, ry, rz, -0.05);
//cube
} else{
//solar system
rx = myWorld.list[1]->getMC().mat[0][1];
ry = myWorld.list[1]->getMC().mat[1][1];
rz = myWorld.list[1]->getMC().mat[2][1];
myWorld.list[1]->rotate_mc(rx, ry, rz, -0.1);
myWorld.list[2]->rotate_origin(0,1,0, -0.5);
myWorld.list[3]->rotate_origin_new(0,1,0, -0.5);// dont know how to rotate moon around earth, instead i rotate around sun
}
glutPostRedisplay();
}
if (OPENGL){//opengl light and shading
// Create light components
float Ra = myLight.Ra;
float Rd = myLight.Rd;
float I = myLight.I;
float posn0 = myLight.getMC().mat[0][3];
float posn1 = myLight.getMC().mat[1][3];
float posn2 = myLight.getMC().mat[2][3];
GLfloat light0_ambient[] = { Ra,Ra,Ra, 1.0f };
GLfloat light0_diffuse[] = { Rd, Rd, Rd, 1.0f };
GLfloat emissionLight[] = { I,I,I, 1.0f };
GLfloat light0_position[] = {posn0,posn1, posn2, 1.0f};
// Assign created components to GL_LIGHT0
glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
glLightfv(GL_LIGHT0, GL_EMISSION, emissionLight);
glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
float colorOrangeRed[] = { 1.0f, 0.2f, 0.0f, 1.0f };
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colorOrangeRed);
}
glutPostRedisplay();
}
void reset(void) {
glutIdleFunc(NULL);
isSolar = false;
isShading = false;
OPENGL = false;
glDisable( GL_LIGHTING );
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHT0);
myWorld.reset();
glutPostRedisplay();
}
void LightMenu(GLint transOption) {
coordinate = 4;
type = transOption;
if (type == 10) {
myLight.On = true;
}
if (type == 11) {
myLight.On = false;
}
glutPostRedisplay();
}
void mainMenu(GLint option) {
switch (option) {
case 1: {
reset();
moving = 0; xBegin = 0; coordinate = 1; type = 4; selected=0;
}
break;
case 2: exit(0);
}
glutPostRedisplay();
}
void VCTransMenu(GLint transOption) {
switch (transOption) {
case 1: {
coordinate = 3;
type = 1;
}
break;
case 2: {
coordinate = 3;
type = 2;
}
break;
case 3: {
coordinate = 3;
type = 3;
}
break;
case 4: {
coordinate = 3;
type = 4;
}
break;
case 5: {
coordinate = 3;
type = 5;
}
break;
case 6: {
coordinate = 3;
type = 6;
}
break;
case 7: {
coordinate = 3;
type = 7;
}
break;
case 8: {
coordinate = 3;
type = 8;
}
break;
case 9: {
coordinate = 3;
type = 9;
}
break;
}
glutPostRedisplay();
}
void A3Menu(GLint option) {
glutIdleFunc(NULL);
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
isSolar = false;
if(option == 1){ // my backface
isShading = false;
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
} else if(option == 2){
isShading = true;
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
} else if(option == 3){
isShading = false;
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
}
else if(option == 4){
isShading = false;
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// Create light components
float Ra = myLight.Ra;
float Rd = myLight.Rd;
float I = myLight.I;
float posn0 = myLight.getMC().mat[0][3];
float posn1 = myLight.getMC().mat[1][3];
float posn2 = myLight.getMC().mat[2][3];
GLfloat light0_ambient[] = { Ra,Ra,Ra, 1.0f };
GLfloat light0_diffuse[] = { Rd, Rd, Rd, 1.0f };
GLfloat emissionLight[] = { I,I,I, 1.0f };
GLfloat light0_position[] = {posn0,posn1, posn2, 1.0f};
// Assign created components to GL_LIGHT0
glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
glLightfv(GL_LIGHT0, GL_EMISSION, emissionLight);
glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
float colorBlue[] = { 1.0f, 0.33f, 0.0f, 1.0f };
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colorBlue);
OPENGL = true;
glutIdleFunc(move);
/// light setting
}
else if(option == 5){ //cube animation
moving = 0;
isSolar = false;
glutIdleFunc(move);
}
else if(option == 6){ //solar system
isSolar = true;
myLight.On = false;
myWorld.list[1]->scale_change(-0.6);
myWorld.list[2]->scale_change(-0.9);
myWorld.list[3]->scale_change(-0.95);
myWorld.list[2]->translate(1, 0, 1);
myWorld.list[3]->translate(1.2, 0, 1.2);
glutIdleFunc(move);
}
glutPostRedisplay();
}
void menu() {
GLint WCTrans_Menu, VCTrans_Menu, MCTrans_Menu;
MCTrans_Menu = glutCreateMenu(MCTransMenu);
glutAddMenuEntry(" Rotate x ", 1);
glutAddMenuEntry(" Rotate y ", 2);
glutAddMenuEntry(" Rotate z", 3);
glutAddMenuEntry(" Scale", 4);
WCTrans_Menu = glutCreateMenu(WCTransMenu);
glutAddMenuEntry(" Rotate x ", 1);
glutAddMenuEntry(" Rotate y ", 2);
glutAddMenuEntry(" Rotate z", 3);
glutAddMenuEntry(" Translate x ", 4);
glutAddMenuEntry(" Translate y ", 5);
glutAddMenuEntry(" Translate z", 6);
VCTrans_Menu = glutCreateMenu(VCTransMenu);
glutAddMenuEntry(" Rotate x ", 1);
glutAddMenuEntry(" Rotate y ", 2);
glutAddMenuEntry(" Rotate z", 3);
glutAddMenuEntry(" Translate x ", 4);
glutAddMenuEntry(" Translate y ", 5);
glutAddMenuEntry(" Translate z", 6);
glutAddMenuEntry(" Clipping Near ", 7);
glutAddMenuEntry(" Clipping Far ", 8);
glutAddMenuEntry(" Angle ", 9);
GLint Light_Menu = glutCreateMenu(LightMenu);
glutAddMenuEntry(" Rotate x ", 1);
glutAddMenuEntry(" Rotate y ", 2);
glutAddMenuEntry(" Rotate z", 3);
glutAddMenuEntry(" Translate x ", 4);
glutAddMenuEntry(" Translate y ", 5);
glutAddMenuEntry(" Translate z", 6);
glutAddMenuEntry(" Point Light Intensity I", 7);
glutAddMenuEntry(" Point Light Reflection Rd", 8);
glutAddMenuEntry(" Ambient Reflection Ra",9);
glutAddMenuEntry(" Show Point Light ", 10);
glutAddMenuEntry(" Hide Point Light ", 11);
//A_3 menu
GLint A3_Menu = glutCreateMenu(A3Menu);
glutAddMenuEntry(" My Hidden Face Removal", 1);
glutAddMenuEntry(" My Light & Shading ", 2);
glutAddMenuEntry(" OpenGL Hidden Face Removal", 3);
glutAddMenuEntry(" OpenGL Light & Shading", 4);
glutAddMenuEntry(" Cube Animation ", 5);
glutAddMenuEntry(" Simple Solar System", 6);
glutCreateMenu(mainMenu); // Create main pop-up menu.
glutAddMenuEntry(" Reset ", 1);
glutAddSubMenu(" Model Transformations ", MCTrans_Menu);
glutAddSubMenu(" WC Transformations ", WCTrans_Menu);
glutAddSubMenu(" View Transformations ", VCTrans_Menu);
glutAddSubMenu(" Light Transformations ", Light_Menu);
glutAddSubMenu(" A3 Menu", A3_Menu);
glutAddMenuEntry(" Quit", 2);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(winWidth, winHeight);
glutCreateWindow("Ali Ahmed A2");
init();
menu();
glutDisplayFunc(display);
glutMotionFunc(mouseMotion);
glutMouseFunc(mouseAction);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
return 0;
}
| true |
0fe3d5330c5ba53687c93dc5ea00f9a957b6d8a1 | C++ | cstollw/visionaray | /include/visionaray/math/detail/rectangle.inl | UTF-8 | 2,786 | 3.03125 | 3 | [
"MIT"
] | permissive | // This file is distributed under the MIT license.
// See the LICENSE file for details.
namespace MATH_NAMESPACE
{
//--------------------------------------------------------------------------------------------------
// rectangle : xywh_layout
//
template <typename T>
inline rectangle<xywh_layout, T>::rectangle()
{
}
template <typename T>
inline rectangle<xywh_layout, T>::rectangle(T x, T y, T w, T h)
: xywh_layout<T>(x, y, w, h)
{
}
template <typename T>
inline rectangle<xywh_layout, T>::rectangle(T const data[4])
: xywh_layout<T>(data)
{
}
template <typename T>
inline T* rectangle<xywh_layout, T>::data()
{
return reinterpret_cast<T*>(this);
}
template <typename T>
inline T const* rectangle<xywh_layout, T>::data() const
{
return reinterpret_cast<T const*>(this);
}
template <typename T>
inline T& rectangle<xywh_layout, T>::operator[](size_t i)
{
return data()[i];
}
template <typename T>
inline T const& rectangle<xywh_layout, T>::operator[](size_t i) const
{
return data()[i];
}
//-------------------------------------------------------------------------------------------------
// Comparisons
//
template <typename T>
bool operator==(rectangle<xywh_layout, T> const& a, rectangle<xywh_layout, T> const& b)
{
return a.x == b.x && a.y == b.y && a.w == b.w && a.h == b.h;
}
template <typename T>
bool operator!=(rectangle<xywh_layout, T> const& a, rectangle<xywh_layout, T> const& b)
{
return !(a == b);
}
//--------------------------------------------------------------------------------------------------
// Geometric functions
//
template <typename T>
bool overlapping(rectangle<xywh_layout, T> const& a, rectangle<xywh_layout, T> const& b)
{
vector<2, T> a1(a.x, a.y);
vector<2, T> a2(a.x + a.w, a.y + a.h);
vector<2, T> b1(b.x, b.y);
vector<2, T> b2(b.x + b.w, b.y + b.h);
return !(a1[0] > b2[0] || a2[0] < b1[0] || a1[1] > b2[1] || a2[1] < b1[1]);
}
template <typename T>
inline rectangle<xywh_layout, T> combine(rectangle<xywh_layout, T> const& a,
rectangle<xywh_layout, T> const& b);
template <typename T>
inline rectangle<xywh_layout, T> intersect(rectangle<xywh_layout, T> const& a,
rectangle<xywh_layout, T> const& b)
{
if (overlapping(a, b))
{
vector<2, T> a1(a.x, a.y);
vector<2, T> a2(a.x + a.w, a.y + a.h);
vector<2, T> b1(b.x, b.y);
vector<2, T> b2(b.x + b.w, b.y + b.h);
T x = std::max( a1[0], b1[0] );
T y = std::max( a1[1], b1[1] );
return rectangle<xywh_layout, T>
(
x, y,
std::min(a2[0], b2[0]) - x,
std::min(a2[1], b2[1]) - y
);
}
else
{
return rectangle<xywh_layout, T>( T(0), T(0), T(0), T(0) );
}
}
} // MATH_NAMESPACE
| true |
a38a2d32c6da10a6a72405f6173f671268970328 | C++ | Pinyupen/possumwood | /src/plugins/cgal/properties.h | UTF-8 | 2,298 | 3.109375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <algorithm>
#include <cassert>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <boost/iterator/indirect_iterator.hpp>
#include "property.h"
namespace possumwood {
template <typename T>
class Property;
/// A simple container class designed to hold properties of items of a polyhedron.
class Properties {
public:
Properties();
Properties(const Properties& p);
Properties& operator=(const Properties& p);
typedef boost::indirect_iterator<std::vector<std::unique_ptr<PropertyBase>>::const_iterator> const_iterator;
const_iterator begin() const;
const_iterator end() const;
const_iterator find(const std::string& name) const;
template <typename T>
Property<T>& addProperty(const std::string& name, const T& defaultValue);
bool hasProperty(const std::string& name) const;
void removeProperty(const std::string& name);
template <typename T>
Property<T>& property(const std::string& name);
template <typename T>
const Property<T>& property(const std::string& name) const;
bool operator==(const Properties& p) const;
bool operator!=(const Properties& p) const;
protected:
private:
std::size_t addSingleItem();
std::vector<std::unique_ptr<PropertyBase>> m_properties;
template <typename T>
friend class Property;
};
template <typename T>
Property<T>& Properties::addProperty(const std::string& name, const T& defaultValue) {
assert(find(name) == end() && "property naming has to be unique");
// add a new Property instance
std::unique_ptr<PropertyBase> ptr(new Property<T>(name, defaultValue));
m_properties.push_back(std::move(ptr));
std::sort(m_properties.begin(), m_properties.end(),
[](const std::unique_ptr<PropertyBase>& v1, const std::unique_ptr<PropertyBase>& v2) {
return v1->name() < v2->name();
});
return property<T>(name);
}
template <typename T>
Property<T>& Properties::property(const std::string& name) {
auto it = find(name);
assert(it != end());
return dynamic_cast<Property<T>&>(*it);
}
template <typename T>
const Property<T>& Properties::property(const std::string& name) const {
auto it = find(name);
assert(it != end());
return dynamic_cast<const Property<T>&>(*it);
}
} // namespace possumwood
#include "property.inl"
| true |
c3a6585816a87bae803af23e8ad34f084c5877da | C++ | shengxiaoyi1993/algorithm | /leetecode/combination_sum/main.cpp | UTF-8 | 718 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include"solution.hpp"
using namespace std;
int main(){
Solution tmp;
int vals[]={2,3,5};
int size_vals=3;
vector<int> candidates;
for (size_t i = 0; i < size_vals; i++) {
candidates.push_back(vals[i]);
}
int target=8;
for (size_t i = 0; i < candidates.size(); i++) {
cout<<i<<": "<<candidates[i]<<endl;
}
vector<vector<int> > results= tmp.combinationSum(candidates,target);
std::cout << "main:" << '\n';
for (size_t i = 0; i < results.size(); i++) {
std::cout <<i<< ":" <<" ";
for (size_t j = 0; j < results[i].size(); j++) {
std::cout << results[i][j] << " ";
}
std::cout << '\n';
}
return 0;
}
| true |
2bb2f5c91b5f19be02894f63d7d0053a08fb955c | C++ | schwadri/granular | /code/core/math/linalg/traits/detail/vector_traits_spec.hpp | UTF-8 | 3,017 | 2.9375 | 3 | [] | no_license | #ifndef _vector_traits_spec_hpp_
#define _vector_traits_spec_hpp_
/* \file vector_traits_spec.hpp Contains specializations of the field
* and dimension metafunctions
* \author Adrian Schweizer
* \created $Di 08 Jul 11:03:32 am CEST 2008 schwadri@guest-docking-hg-1-155.ethz.ch$
* \modified $Di 08 Jul 11:08:49 am CEST 2008 schwadri@guest-docking-hg-1-155.ethz.ch$
*/
#include <boost/mpl/size_t.hpp>
#include "fwd_decls.hpp"
namespace core {
namespace math {
namespace linalg {
//fwd decl
template <typename V>
struct dimension;
template <typename V>
struct field;
namespace detail {
template <typename T, std::size_t N>
struct static_dimension_impl : mpl::size_t<N>
{
static std::size_t get(const T& t)
{
return N;
}
};
template <typename T>
struct stl_dynamic_dimension_impl : mpl::size_t<0>
{
static std::size_t get(const T& t)
{
return t.size();
}
};
} // namespace detail
template <typename T, std::size_t N>
struct dimension<boost::array<T, N> >
: detail::static_dimension_impl<boost::array<T, N>, N>
{ };
template <typename T, std::size_t N>
struct dimension<T[N]>
: detail::static_dimension_impl<T[N], N>
{ };
template <typename T, typename A>
struct dimension<std::vector<T, A> >
: detail::stl_dynamic_dimension_impl<std::vector<T, A> >
{ };
template <typename T>
struct dimension<std::valarray<T> >
: detail::stl_dynamic_dimension_impl<std::valarray<T> >
{ };
//specialization for Point, Index, std::vector, std::valarray, boost::array and builtin static arrays
template <typename T, std::size_t N>
struct field<boost::array<T, N> >
{
typedef T type;
};
template <typename T, std::size_t N>
struct field<T[N] >
{
typedef T type;
};
template <typename T, typename A>
struct field<std::vector<T, A> >
{
typedef T type;
};
template <typename T>
struct field<std::valarray<T> >
{
typedef T type;
};
//TODO:queries to determine the behaviour of the different operator implementations of the vectors
} // namespace linalg
} // namespace math
} // namespace core
#endif // _vector_traits_spec_hpp_
| true |
e848b1e069a47f55ddba503d9a7b96ca6e6f521e | C++ | geraldolsribeiro/contests | /ACM/2007/Regional/D-Mario/mario.cpp | UTF-8 | 2,192 | 3 | 3 | [] | no_license | /***************************************************************************
* D-Mario Maratona de Programacao - Regional 2007
*
* Autor: Vinicius J. S. Souza
* Data: 10/09/2009
* Tecnicas: busca binaria
* Complexidade: O(nlgn)
**************************************************************************/
#include<iostream>
#include<cstdlib>
#include<vector>
#define TAM 100010
#define MAX 987654321
using namespace std;
int K, N;
int bsearchL(vector<int> &vet, int x, int inf, int sup)
{
if (sup - inf == 1)
{
if (vet[inf] > x && inf-1 >= 0)
return inf-1;
else return inf;
}
if ( sup - inf == 2 )
{
if (x >= vet[inf+1])
return inf+1;
else if (x >= vet[inf])
return inf;
else if (inf - 1 >= 0)
return inf-1;
else
return inf;
}
int middle = (sup + inf) / 2;
if (vet[middle] == x)
return middle;
else if (vet[middle] > x)
return bsearchL(vet, x, inf, middle);
else
return bsearchL(vet, x, middle, sup);
}
int bsearchR(vector<int> &vet, int x, int inf, int sup)
{
if (sup - inf == 1)
{
if (vet[inf] < x && inf+1 < N)
return inf+1;
else return inf;
}
if ( sup - inf == 2 )
{
if (x <= vet[inf])
return inf;
else if (x <= vet[inf+1])
return inf+1;
else if (sup < N)
return sup;
else
return inf;
}
int middle = (sup + inf) / 2;
if (vet[middle] == x)
return middle;
else if (vet[middle] > x)
return bsearchR(vet, x, inf, middle+1);
else
return bsearchR(vet, x, middle+1, sup);
}
int main()
{
while (true)
{
scanf("%d %d", &K, &N);
if (!K && !N)
break;
int minimo = MAX;
int missing = K-1;
vector<int> vet(N, 0);
for (int i = 0; i < N; i++)
scanf("%d", &vet[i]);
for (int i = 0; i < N; i++)
{
if (vet[i] + missing < 100000)
{
int num = vet[i] + missing;
int loc = bsearchR(vet, num, 0, N);
int dif = abs(missing - (loc-i));
if (vet[loc] != num)
dif++;
if (dif < minimo)
minimo = dif;
}
if (vet[i] >= K)
{
int num = vet[i] - missing;
int loc = bsearchL(vet, num, 0, N);
int dif = abs(missing - (i-loc));
if (vet[loc] != num)
dif++;
if (dif < minimo)
minimo = dif;
}
}
printf("%d\n", minimo);
}
return 0;
}
| true |
d15fa711ab8aa2343de640a88124db663574b46b | C++ | Barboros6167/IoT1929-Kampi | /1. Hafta Problem Setleri/Arduino Problem Seti 4/APS_4_Kod.ino | UTF-8 | 1,640 | 2.9375 | 3 | [
"MIT"
] | permissive | /*
* Yıldıray KARACA IoT1929 Kampı İçin Arduino Problem Seti 4 Çözümü.
* mail: yildiraykaraca@icloud.com
* github: https://github.com/yildiraykaraca
*/
#define POT A0 // A0 Pinini POT Adında Tutturdum.
#define DC 3 // 3. Pini DC Adında Tutturdum.
#define LED 2 // 2. Pini LED Adında Tutturdum.
int Pot_Deger=0; // Potansiyometre Değeri İçin Oluşturduğum Değişken.
int Rpm_Deger=0; // Ledi Yaktırmak İçin Kullanacağım Değişken.
void setup()
{
pinMode(DC,OUTPUT); // DC Motor çıkış.
pinMode(LED,OUTPUT); // LED bir çıkış.
Serial.begin(9600); // Seri Haberleşmeyi Başlattım.
}
void loop()
{
Pot_Deger=analogRead(POT); // Potansiyometre Değerini Okuyup Oluşturduğum Değikenime Atadım.
Pot_Deger= map(Pot_Deger, 0, 1023, 0, 255); // PWM Pini 0-255 Arasında İşlem Yaptığından Oranı Sabitleyerek Pot Değeriyle Oranladım.
analogWrite(DC,Pot_Deger); // Oranladığım Pot Değerinden Gelen PWM İçin Uygun Değeri DC Motora Yazdırdım.
Rpm_Deger=map(Pot_Deger, 0, 255, 0, 5555); // Oranladığım Değer 0,255 olduğundan Rpmi Hesaplamak İçin Oran Orantı Yaptım.
if(Rpm_Deger>2700) // Eğer Rpm Değeri 2700 Den Yüksek ise
{
digitalWrite(LED, HIGH); //Ledi Yak
}
else // Değilse
{
digitalWrite(LED,LOW); // Ledi Kapat
}
Serial.print("POT DEGERI: " + String(Pot_Deger)); // POT Değerini Seri Monitöre Yazdırdım.
Serial.println(" RPM HIZI: " + String(Rpm_Deger)); // RPM Değerini Seri Monitöre Yazdırdım
delay(250); // 250 Milisaniye = 0.25 Saniye Bekle
}
| true |
00ae6a7b22b53821506b162315bf0d41043a5772 | C++ | BarishNamazov/IOI | /ioi2014_wall.cpp | UTF-8 | 1,618 | 2.546875 | 3 | [] | no_license | #include "grader.h"
#include <bits/stdc++.h>
using namespace std;
const int INF = 2000000000;
const int maxx = 2000005;
#define mn first
#define mx second
pair <int, int> t[maxx << 2];
void relax(int v, int l, int r) {
if (l != r) {
int lc = v << 1, rc = v << 1 | 1;
t[lc] = {max(min(t[lc].mn, t[v].mn), t[v].mx), max(min(t[lc].mx, t[v].mn), t[v].mx)};
t[rc] = {max(min(t[rc].mn, t[v].mn), t[v].mx), max(min(t[rc].mx, t[v].mn), t[v].mx)};
}
}
void update(int v, int l, int r, int i, int j, int val, int oq) {
relax(v, l, r);
if (i > r || j < l) {
return;
}
if (i <= l && r <= j) {
if (oq == 1) {
t[v].mn = max(t[v].mn, val);
t[v].mx = max(t[v].mx, val);
} else {
t[v].mn = min(t[v].mn, val);
t[v].mx = min(t[v].mx, val);
}
return;
}
t[v].mn = INF, t[v].mx = -INF;
int mid = (l + r) >> 1;
update(v << 1, l, mid, i, j, val, oq);
update(v << 1 | 1, mid + 1, r, i, j, val, oq);
}
int query(int v, int l, int r, int i) {
relax(v, l, r);
if (l == r) {
return t[v].mn;
}
int mid = (l + r) >> 1;
if (i <= mid) {
return query(v << 1, l, mid, i);
} else {
return query(v << 1 | 1, mid + 1, r, i);
}
}
void buildWall(int n, int k, int op[], int left[], int right[], int height[], int finalHeight[]){
for (int i = 0; i < k; i++) {
update(1, 1, n, left[i] + 1, right[i] + 1, height[i], op[i]);
}
for (int i = 1; i <= n; i++) {
finalHeight[i - 1] = query(1, 1, n, i);
}
return;
}
| true |
75687518a45b6e552ade764d37aefca25f7c31ea | C++ | congtrung2k1/Algorithms | /SPOJ/Some-Solutions/CPRMT.cpp | UTF-8 | 582 | 2.71875 | 3 | [] | no_license | //two strings given: say, abcad and ebada we have to find characters present in both as a subsequence, i.e., aabd in alphabetic order.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAXN=1010;
char a[MAXN],b[MAXN];
int cnt[26];
void solve()
{
memset(cnt,0,sizeof(cnt));
for(int i=0;a[i];++i)
cnt[a[i]-'a']++;
sort(b,b+strlen(b));
for(int i=0;b[i];++i)
if(cnt[b[i]-'a'])printf("%c",b[i]),cnt[b[i]-'a']--;
printf("\n");
}
int main()
{
while(scanf("%s%s",a,b)!=EOF)
solve();
return 0;
}
| true |
afa0a5773024410ae91b9d783920f1f72e39f465 | C++ | ailyanlu1/Arithmetic | /Competition/Multi-University/4/1006.cpp | GB18030 | 2,780 | 2.546875 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int MAXN=100007;
int sa[MAXN];//SA飬ʾSnСź
//ĺĿͷλ˳ηSA
int t1[MAXN],t2[MAXN],c[MAXN];//SAҪмҪֵ
int ran[MAXN],height[MAXN];
//ַsУs[0]s[n-1],Ϊn,ֵСm,
//s[n-1]s[i]0r[n-1]=0
//Ժsa
void build_sa(int s[],int n,int m)
{
int i,j,p,*x=t1,*y=t2;
//һֻsֵܴɸΪ
for(i=0;i<m;i++)c[i]=0;
for(i=0;i<n;i++)c[x[i]=s[i]]++;
for(i=1;i<m;i++)c[i]+=c[i-1];
for(i=n-1;i>=0;i--)sa[--c[x[i]]]=i;
for(j=1;j<=n;j<<=1)
{
p=0;
//ֱsaڶؼ
for(i=n-j;i<n;i++)y[p++]=i;//jڶؼΪյС
for(i=0;i<n;i++)if(sa[i]>=j)y[p++]=sa[i]-j;
//yľǰյڶؼĽ
//һؼ
for(i=0;i<m;i++)c[i]=0;
for(i=0;i<n;i++)c[x[y[i]]]++;
for(i=1;i<m;i++)c[i]+=c[i-1];
for(i=n-1;i>=0;i--)sa[--c[x[y[i]]]]=y[i];
//saxµx
swap(x,y);
p=1;x[sa[0]]=0;
for(i=1;i<n;i++)
x[sa[i]]=y[sa[i-1]]==y[sa[i]] && y[sa[i-1]+j]==y[sa[i]+j]?p-1:p++;
if(p>=n)break;
m=p;//´λֵ
}
}
void getHeight(int s[],int n)
{
int i,j,k=0;
for(i=0;i<=n;i++)ran[sa[i]]=i;
for(i=0;i<n;i++)
{
if(k)k--;
j=sa[ran[i]-1];
while(s[i+k]==s[j+k])k++;
height[ran[i]]=k;
}
}
char str[MAXN],x[3];
int s[MAXN];
vector<int>locx;
vector<int>::iterator it;
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int T;
scanf("%d",&T);
int kase=0;
while(T--)
{
locx.clear();
scanf("%s",x);
scanf("%s",str);
int n=strlen(str);
for(int i=0;i<=n;i++){
if(str[i]==x[0]){
locx.push_back(i);
}
}
for(int i=0;i<=n;i++)s[i]=str[i];
build_sa(s,n+1,128);
getHeight(s,n);
long long ans=0;
for(int i=0;i<=n;i++){
it=lower_bound(locx.begin(),locx.end(),sa[i]);
if(it!=locx.end()) {
ans+=n-max(sa[i]+height[i],*it);
}
}
printf("Case #%d: %I64d\n",++kase,ans);
}
return 0;
}
| true |
d921c4225e22d5e4b1642a909326ca1d8dd068d5 | C++ | ennis/graal-old | /include/graal/ext/geometry.hpp | UTF-8 | 5,261 | 2.609375 | 3 | [] | no_license | #pragma once
#include <graal/buffer.hpp>
#include <graal/ext/vertex_traits.hpp>
#include <graal/vertex_array.hpp>
#include <fstream>
#include <glm/glm.hpp>
#include <optional>
#include <tiny_obj_loader.h>
#include <vector>
#include <span>
#include <string_view>
namespace graal {
enum class topology {
points,
lines,
line_strips,
triangles,
triangle_strips,
};
struct vertex_2d {
glm::vec2 position;
glm::vec2 texcoord;
};
template <> struct vertex_traits<vertex_2d> {
static constexpr std::array<vertex_attribute, 2> attributes{
{{data_type::float_, 2, offsetof(vertex_2d, position)},
{data_type::float_, 2, offsetof(vertex_2d, texcoord)}}};
static constexpr void set_attribute(vertex_2d &vtx, semantic s, float x,
float y, float z, float w) {
if (s == semantic::position) {
vtx.position = glm::vec2{x, y};
} else if (s == semantic::texcoord) {
vtx.texcoord = glm::vec2{x, y};
}
}
};
/// @brief Represents some geometry.
// Geometry objects are immutable. They can't change after having been created.
//
template <typename VertexType> class geometry {
public:
struct draw_item {
topology topology;
size_t start_vertex;
size_t num_vertices;
};
/// @brief Binds the vertex array and vertex buffers to the OpenGL pipeline.
void bind() const;
std::span<const draw_item> draw_items() const noexcept { return std::span{draw_items_}; }
/// @brief Loads geometry from an OBJ file.
/// @param path path to the OBJ file to load.
/// @return
static geometry<VertexType> load_obj(std::string_view file_name);
private:
// uninitialized constructor, do not expose
geometry() = default;
topology topo_;
size_t vertex_stride_;
buffer<VertexType> vertex_buffer_;
std::vector<draw_item> draw_items_;
// std::optional<buffer<uint32_t>> index_data_;
};
//=============================================================================
template <typename VertexType>
geometry<VertexType>
geometry<VertexType>::load_obj(std::string_view file_name) {
std::ifstream file{std::string{file_name}};
if (!file) {
throw std::runtime_error{
fmt::format("could not open file: `{}`", file_name)};
}
std::string err;
std::string warn;
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, &file);
// create VAO
vertex_array_builder vao_builder;
size_t offset = 0;
size_t normals_offset = 0;
size_t texcoords_offset = 0;
int attrib_index = 0;
const bool has_normals = !attrib.normals.empty();
const bool has_texcoords = !attrib.texcoords.empty();
vao_builder.set_attribute(attrib_index++, 0, {data_type::float_, 3, offset});
offset += 3 * sizeof(float);
if (has_normals) {
// got normals
normals_offset = offset;
vao_builder.set_attribute(attrib_index++, 0,
{data_type::float_, 3, offset});
offset += 3 * sizeof(float);
}
if (has_texcoords) {
// got texcoords
texcoords_offset = offset;
vao_builder.set_attribute(attrib_index++, 0,
{data_type::float_, 2, offset});
offset += 2 * sizeof(float);
}
const size_t stride = offset;
const int num_attribs = attrib_index;
const size_t num_vertices = attrib.vertices.size() / 3; // close enough
std::vector<draw_item> draw_items;
draw_items.reserve(shapes.size());
std::vector<VertexType> vertices;
vertices.reserve(num_vertices);
for (int i = 0; i < shapes.size(); i++) {
const auto &shape = shapes[i];
const auto & mesh = shape.mesh;
const auto start_vertex = vertices.size();
for (int j = 0; j < mesh.indices.size(); j++) {
auto indices = mesh.indices[j];
// yes, we don't de-duplicate vertices here, but whatever. OBJ is a shitty
// format anyway; eventually I'll use a better one
VertexType v;
vertex_traits<VertexType>::set_attribute(v,
semantic::position, attrib.vertices[indices.vertex_index * 3 + 0],
attrib.vertices[indices.vertex_index * 3 + 1],
attrib.vertices[indices.vertex_index * 3 + 2], 1.0f);
vertex_traits<VertexType>::set_attribute(v,
semantic::normal, attrib.normals[indices.normal_index * 3 + 0],
attrib.normals[indices.normal_index * 3 + 1],
attrib.normals[indices.normal_index * 3 + 2], 0.0f);
vertex_traits<VertexType>::set_attribute(v,
semantic::texcoord, attrib.texcoords[indices.texcoord_index * 2 + 0],
attrib.texcoords[indices.texcoord_index * 2 + 1], 0.0f, 0.0f);
vertices.push_back(v);
}
draw_items.push_back(draw_item{
.topo = topology::triangle,
.start_vertex = start_vertex,
.num_vertices = mesh.indices.size(),
});
}
// create buffer
buffer vertex_buffer{std::as_bytes(std::span{vertices_interleaved})};
geometry<VertexType> geo;
geo.topo_ = topology::triangles;
geo.vao_ = vao_builder.get_vertex_array();
geo.vertex_buffer_ = std::move(vertex_buffer);
geo.vertex_stride_ = stride;
return geo;
}
} // namespace graal | true |
b2b100e659461eee916eeb2895f31b368a144255 | C++ | mnksnz/aeplanner | /aeplanner/include/aeplanner/data_structures.h | UTF-8 | 1,937 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef DATA_STRUCTURES_H
#define DATA_STRUCTURES_H
#include <ros/ros.h>
#include <octomap/OcTree.h>
namespace aeplanner
{
class RRTNode
{
public:
Eigen::Vector4d state_;
RRTNode* parent_;
std::vector<RRTNode*> children_;
double gain_;
bool gain_explicitly_calculated_;
RRTNode() : parent_(NULL), gain_(0.0), gain_explicitly_calculated_(false)
{
}
~RRTNode()
{
for (typename std::vector<RRTNode*>::iterator node_it = children_.begin();
node_it != children_.end(); ++node_it)
{
delete (*node_it);
(*node_it) = NULL;
}
}
RRTNode* getCopyOfParentBranch()
{
RRTNode* current_node = this;
RRTNode* current_child_node = NULL;
RRTNode* new_node;
RRTNode* new_child_node = NULL;
while (current_node)
{
new_node = new RRTNode();
new_node->state_ = current_node->state_;
new_node->gain_ = current_node->gain_;
new_node->gain_explicitly_calculated_ = current_node->gain_explicitly_calculated_;
new_node->parent_ = NULL;
if (new_child_node)
{
new_node->children_.push_back(new_child_node);
new_child_node->parent_ = new_node;
}
current_child_node = current_node;
current_node = current_node->parent_;
new_child_node = new_node;
}
return new_node;
}
double score(double lambda)
{
if (this->parent_)
return this->parent_->score(lambda) +
this->gain_ * exp(-lambda * this->distance(this->parent_));
else
return this->gain_;
}
double cost()
{
if (this->parent_)
return this->distance(this->parent_) + this->parent_->cost();
else
return 0;
}
double distance(RRTNode* other)
{
Eigen::Vector3d p3(this->state_[0], this->state_[1], this->state_[2]);
Eigen::Vector3d q3(other->state_[0], other->state_[1], other->state_[2]);
return (p3 - q3).norm();
}
};
} // namespace aeplanner
#endif
| true |
90ddc7d9fe4563f64ebd2002ecae2144dec57838 | C++ | mcu786/RCControl | /gps_receiver.cpp | UTF-8 | 8,042 | 3.21875 | 3 | [] | no_license | #include "gps_receiver.h"
/**
* Initialise the serial port used to talk to the GPS unit.
*/
GPSReceiver::GPSReceiver(void) {
serial = new SerialPort(GPS_PORT, 9600);
_connected = serial->connected();
memset(&time, sizeof(time), 0x00);
memset(&pos, sizeof(pos), 0x00);
lock = false;
_updateMutex = CreateMutex(NULL, FALSE, NULL);
this->_thread = _beginthread(gps_thread, 0, this);
if( !this->_thread ) {
cout << "Error starting GPS thread. Exiting." << endl;
exit(1);
}
}
GPSReceiver::~GPSReceiver(void) {
}
bool GPSReceiver::connected() {
return _connected;
}
/**
* Read input until a comma occurs, storing each characater into output.
* Sets output to be a null terminated string of everything up to the comma.
* Returns the new position for next time the function is called.
* \param input A char* pointing to a null terminated string
* \param output A char* pointing to a buffer that must be as big as input
* \param position The previous position in the string, i.e. the starting point
*/
unsigned int GPSReceiver::parse_until_comma(char* input, char* output, unsigned int position) {
unsigned int output_index = 0;
unsigned int size = (unsigned int)strlen(input);
output[output_index] = 0x00;
while( position < size ) {
if( input[position] != ',' ) {
output[output_index++] = input[position];
output[output_index] = 0x00;
} else {
return position + 1;
}
position++;
}
return position;
}
/**
* Check the serial port handler for new lines and parse any GGRMC sentences.
* This function updates the class's internal state.
* You should always call update() before accessing class members.
*/
void GPSReceiver::update() {
char buffer[128];
unsigned int i, buffer_length;
//Process the next line in the buffer
serial->read_line(buffer, 128);
buffer_length = (unsigned int)strlen(buffer);
fflush(NULL);
//The first character should always be a $
if( buffer[0] != '$' )
return;
//All valid GPS related sentences start GP
if( buffer[1] != 'G' || buffer[2] != 'P' )
return;
//We are only interested in the RMC sentences
if( buffer[3] != 'R' || buffer[4] != 'M' || buffer[5] != 'C' )
return;
//After the message type there should be a ','
if( buffer[6] != ',' )
return;
//If everything so far is good, check the checksum
//Find the original checksum
char msg_checksum[2];
msg_checksum[0] = buffer[buffer_length - 2];
msg_checksum[1] = buffer[buffer_length - 1];
//Calculate the message checksum (XOR all characters)
char calc_checksum = buffer[1];
for( i=2; i<(buffer_length - 3); i++ ) {
calc_checksum ^= buffer[i];
}
//Store the new checksum as two hex characters
char calc_checksum_str[3];
sprintf_s(calc_checksum_str, 3, "%.2X", calc_checksum);
//Compare the two
if( strncmp( msg_checksum, calc_checksum_str, 2 ) != 0 ) {
return;
}
// Now acquire the mutex lock as we are going to go through with the update
WaitForSingleObject(_updateMutex, INFINITE);
//Store the fields as they are parsed
char field[128];
unsigned int buffer_index = 0;
//Get the sentence type
buffer_index = parse_until_comma(buffer, field, buffer_index);
//Get the time
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
time.hours = 10*((int)(field[0]) - 48) + ((int)field[1] - 48);
time.minutes = 10*((int)(field[2]) - 48) + ((int)field[3] - 48);
time.seconds = 10*((int)(field[4]) - 48) + ((int)field[5] - 48);
time.milliseconds = 100*((int)field[7] - 48) + 10*((int)field[8] - 48);
time.milliseconds += ((int)field[9] - 48);
}
//printf("Time: %.2i:%.2i:%.2i.%.3i UTC\n", time.hours, time.minutes, time.seconds, time.milliseconds);
//Get the lock status
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 && field[0] == 'A' ) {
lock = true;
//cout << "GPS position lock obtained." << endl;
} else {
//If there is no lock, there's no point parsing anything else.
//The only other field available is the date, everything else
// is empty.
lock = false;
//cout << "No GPS position lock." << endl;
ReleaseMutex(_updateMutex);
return;
}
//Get the latitude
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
char minutes[16];
strncpy_s(minutes, 16, &field[2], strlen(field) - 3);
pos.lat_minutes = atof(minutes);
pos.lat_degrees = 10*(field[0] - 48) + (field[1] - 48);
}
//Get latitude direction
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
pos.lat_direction = field[0];
}
//printf("Lat: %i degrees %f minutes %c\n", pos.lat_degrees, pos.lat_minutes, pos.lat_direction);
//Get the longitude
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
char minutes[16];
strncpy_s(minutes, 16, &field[3], strlen(field) - 4);
pos.lon_minutes = atof(minutes);
pos.lon_degrees = 100*(field[0] - 48);
pos.lon_degrees += 10*(field[1] - 48);
pos.lon_degrees += (field[1] - 48);
}
//Get latitude direction
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
pos.lon_direction = field[0];
}
//printf("Lon: %d degrees %f minutes %c\n", pos.lon_degrees, pos.lon_minutes, pos.lon_direction);
//Get groundspeed in knots
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
speed_knots = atof(field);
}
//printf("Speed:\n\t%f knots\n\t%f m/s\n\t%f mph\n", get_speed_knots(), get_speed_ms(), get_speed_mph());
//Get track angle
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
track_angle = atof(field);
}
//printf("Heading: %f degrees\n", track_angle);
//Get the date
buffer_index = parse_until_comma(buffer, field, buffer_index);
if( strlen(field) > 0 ) {
time.day = 10*(field[0] - 48) + (field[1] - 48);
time.month = 10*(field[2] - 48) + (field[3] - 48);
time.year = 10*(field[4] - 48) + (field[5] - 48);
}
//printf("Date: %.2d/%.2d/%.2d\n", time.day, time.month, time.year);
//We could get the magnetic field variation but there's not much
// point. Instead, we stop here. If you did want this data, just
// repeat the same procedure as for everything else. Note that
// the final field, the direction of the variation, is terminated
// with a * and not a ,.
ReleaseMutex(_updateMutex);
printf("update() released mutex\r\n");
}
///Return the GPStime struct
GPStime GPSReceiver::get_time() {
WaitForSingleObject(_updateMutex, INFINITE);
GPStime result = time;
ReleaseMutex(_updateMutex);
return result;
}
///Return the GPSpos struct
GPSpos GPSReceiver::get_pos() {
WaitForSingleObject(_updateMutex, INFINITE);
GPSpos result = pos;
ReleaseMutex(_updateMutex);
return result;
}
///Return the lock status
bool GPSReceiver::has_lock() {
WaitForSingleObject(_updateMutex, INFINITE);
bool result = lock;
ReleaseMutex(_updateMutex);
return result;
}
///Return current speed in knots
double GPSReceiver::get_speed_knots() {
WaitForSingleObject(_updateMutex, INFINITE);
double result = speed_knots;
ReleaseMutex(_updateMutex);
return result;
}
///Return current speed in metres per sec
double GPSReceiver::get_speed_ms() {
WaitForSingleObject(_updateMutex, INFINITE);
double result = speed_knots * 0.51444;
ReleaseMutex(_updateMutex);
return result;
}
///Return current speed in miles per hour
double GPSReceiver::get_speed_mph() {
WaitForSingleObject(_updateMutex, INFINITE);
double result = speed_knots * 1.15078;
ReleaseMutex(_updateMutex);
return result;
}
///Return current heading
double GPSReceiver::get_track_angle() {
WaitForSingleObject(_updateMutex, INFINITE);
double result = track_angle;
ReleaseMutex(_updateMutex);
return result;
}
///Constantly read the serial port to check for updates
void gps_thread(void* void_gps_receiver) {
GPSReceiver* gps_receiver = (GPSReceiver*) void_gps_receiver;
for(;;) {
gps_receiver->update();
Sleep(5);
}
} | true |
0a0b78e0e59f29c3c370d11a1bb28751a7782f25 | C++ | lord-przemas/learn_cpp | /boost_library/any/main.cpp | UTF-8 | 1,372 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <boost/any.hpp>
using boost::any_cast;
typedef std::vector<boost::any> many;
void append_int(many & values, int value)
{
boost::any to_append = value;
values.push_back(to_append);
}
void append_string(many & values, const std::string & value)
{
values.push_back(value);
}
void append_char_ptr(many & values, const char * value)
{
values.push_back(value);
}
void append_any(many & values, const boost::any & value)
{
values.push_back(value);
}
void append_nothing(many & values)
{
values.push_back(boost::any());
}
int main()
{
many values {};
append_int(values, 123);
append_string(values, "std::string object");
append_char_ptr(values, "char pointer");
append_int(values, 456);
append_int(values, 789);
auto is_int = [](const boost::any& o)
{
return (o.type() == typeid(int));
};
auto is_string = [](const boost::any& o)
{
return (o.type() == typeid(std::string));
};
int count_int = std::count_if(values.begin(), values.end(), is_int);
std::cout << "count_int: " << count_int << std::endl;
for(auto e : values)
{
if(is_int(e))
std::cout << "value: " << boost::any_cast<int>(e) << std::endl;
else if(is_string(e))
std::cout << "value: " << boost::any_cast<std::string>(e) << std::endl;
}
return 0;
}
| true |
41a070cb4f4021e55a2c37deadfe2d9cd06a4758 | C++ | jdelezenne/Sonata | /Sources/Engine/Graphics/Animation/NodeAnimationTrack.h | UTF-8 | 1,667 | 2.546875 | 3 | [
"MIT"
] | permissive | /*=============================================================================
NodeAnimationTrack.h
Project: Sonata Engine
Author: Julien Delezenne
=============================================================================*/
#ifndef _SE_NODEANIMATIONTRACK_H_
#define _SE_NODEANIMATIONTRACK_H_
#include "Core/Core.h"
#include "Graphics/Common.h"
#include "Graphics/Animation/AnimationTrack.h"
#include "Graphics/Animation/TransformKeyFrame.h"
#include "Graphics/Scene/SceneObject.h"
#include "Graphics/System/RenderData.h"
namespace SonataEngine
{
/**
@brief Node animation track.
A node track represents the animation of a node transformation.
*/
class SE_GRAPHICS_EXPORT NodeAnimationTrack : public AnimationTrack
{
protected:
SceneObject* _node;
public:
/** @name Constructors / Destructor. */
//@{
/** Constructor. */
NodeAnimationTrack();
/** Destructor. */
virtual ~NodeAnimationTrack();
//@}
/** Properties. */
//@{
SceneObject* GetNode() const { return _node; }
void SetNode(SceneObject* value) { _node = value; }
//@}
virtual TransformKeyFrame* GetNodeKeyFrame(int index) const;
/** Fills an array with translational key data used for key frame animation. */
void GetTranslationKeys(BaseArray<KeyVector3>& translationKeys);
/** Fills an array with rotational key data used for key frame animation. */
void GetRotationKeys(BaseArray<KeyQuaternion>& rotationKeys);
/** Fills an array with scale key data used for key frame animation. */
void GetScaleKeys(BaseArray<KeyVector3>& scaleKeys);
virtual void Update(const TimeValue& timeValue);
protected:
virtual KeyFrame* _CreateKeyFrame(const TimeValue& timeValue);
};
}
#endif
| true |
ee99f462a587404bba178883f12799679e23344b | C++ | halfhiddencode/cpp-code | /converdattype2.cpp | UTF-8 | 479 | 3.4375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class complex
{
int a,b;
public:
void setdata(int x,int y)
{
a=x;
b=y;
}
operator int()
{
return(a);
}
void showdata()
{
cout<<a<<" "<<b<<endl;
}
};
int main()
{
complex c1;
int x;
c1.setdata(7,4);
x=c1; //if you want change class to premitive then use operator keyword and type of premitive
//just like that operator int()
//operator float() it depend upon which type x is;
c1.showdata();
cout<<x<<endl;
}
| true |
e7ee3025fc8dc5309f77b35725bbd32d0d3b527a | C++ | Miceroy/yam2d | /Tutorials/5_CustomMapCreation/source/main.cpp | UTF-8 | 2,699 | 2.6875 | 3 | [] | no_license | // Include OpenGL ES Engine utils
#include <es_util.h>
// Include map class
#include <Map.h>
// Camera class
#include <Camera.h>
#include <Tileset.h>
#include <Layer.h>
#include <TileComponent.h>
using namespace yam2d;
namespace
{
// Pointer to TmxMap-object
TmxMap* map = 0;
// Component Factory is used to create new components.
ComponentFactory* componentFactory = 0;
class CustomComponentFactory : public yam2d::DefaultComponentFactory
{
public:
virtual Component* createNewComponent(const std::string& type, Entity* owner, const yam2d::PropertySet& properties)
{
// TODO: Implementation... Use now default implementation instead.
return DefaultComponentFactory::createNewComponent(type, owner, properties);
}
virtual Entity* createNewEntity(ComponentFactory* componentFactory, const std::string& type, Entity* parent, const yam2d::PropertySet& properties)
{
// TODO: Implementation... Use now default implementation instead.
return DefaultComponentFactory::createNewEntity(componentFactory, type, parent, properties);
}
};
}
// Initialize the game
bool init ( ESContext *esContext )
{
// Create new TmxMap object
map = new TmxMap();
componentFactory = new CustomComponentFactory();
// Load map file
bool okay = map->loadMapFile("level.tmx",componentFactory);
if( okay )
{
// Move camera to middle of map.
map->getCamera()->setPosition( vec2(map->getWidth()/2.0f - 0.5f, map->getHeight()/2.0f - 0.5f));
}
return okay;
}
// Deinitialize the game
void deinit ( ESContext *esContext )
{
// Delete map.
delete map;
delete componentFactory;
}
// Update game
void update( ESContext* ctx, float deltaTime )
{
// Update map. this will update all GameObjects inside a map layers.
map->update(deltaTime);
}
// Draw game
void draw ( ESContext *esContext )
{
// Set OpenGL clear color (dark gray)
glClearColor( 0.1f, 0.1f, 0.1f, 1.0f );
// Clear the color buffer
glClear (GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Set screen size to camera.
map->getCamera()->setScreenSize(esContext->width,esContext->height, 720, 1280.0f/720.0f);
// Render map and all of its layers containing GameObjects to screen.
map->render();
}
int main ( int argc, char *argv[] )
{
ESContext esContext;
esInitContext ( &esContext );
esCreateWindow( &esContext, "Custom map creation", 1280, 720, ES_WINDOW_DEFAULT );
esRegisterInitFunc( &esContext, init );
esRegisterDrawFunc( &esContext, draw );
esRegisterUpdateFunc( &esContext, update );
esRegisterDeinitFunc( &esContext, deinit);
esMainLoop ( &esContext );
return 0;
}
| true |
b25ddf98f280cf7316b9a2dacf44bf76ce25c7fe | C++ | blackpc/ai-homework2 | /src/Board.cpp | UTF-8 | 3,995 | 3 | 3 | [
"MIT"
] | permissive | /**
* Filename: Board.cpp
* Author: Igor Makhtes
* Date: Dec 12, 2014
*
* The MIT License (MIT)
*
* Copyright (c) 2014
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <ai-homework2/Board.h>
Board::Board(int32_t width, int32_t height) {
width_ = width;
height_ = height;
boardArray_ = new Cell[width * height];
for (int i = 0; i < width_ * height_; ++i)
boardArray_[i] = Board::CellEmpty;
}
Board::Board(const Board& board) {
this->width_ = board.width_;
this->height_ = board.height_;
boardArray_ = new Cell[width_ * height_];
for (int i = 0; i < width_ * height_; ++i)
boardArray_[i] = board.boardArray_[i];
}
void Board::operator =(const Board& board) {
this->width_ = board.width_;
this->height_ = board.height_;
boardArray_ = new Cell[width_ * height_];
for (int i = 0; i < width_ * height_; ++i)
boardArray_[i] = board.boardArray_[i];
}
Board::~Board() {
delete[] boardArray_;
}
void Board::setCell(int32_t x, int32_t y, Cell cell) {
boardArray_[width_ * y + x] = cell;
}
void Board::setCell(const Point& point, Cell cell) {
setCell(point.x, point.y, cell);
}
void Board::setCell(const CellPoint& cellPoint) {
setCell(cellPoint.point.x, cellPoint.point.y, cellPoint.cellValue);
}
bool Board::isEmpty(int32_t x, int32_t y) const {
return getCell(x, y) == Board::CellEmpty;
}
bool Board::isEmpty(const Point& point) const {
return isEmpty(point.x, point.y);
}
bool Board::isInBounds(int32_t x, int32_t y) const {
return x >= 0 && x < width_ &&
y >= 0 && y < height_;
}
bool Board::isInBounds(const Point& point) const {
return isInBounds(point.x, point.y);
}
const string Board::cellToString(Cell cell) const {
if (cell == Board::CellBlack)
return "○";
if (cell == Board::CellWhite)
return "●";
if (cell == Board::CellEmpty)
return "░";
throw new string("Invalid cell value");
}
uint32_t Board::getBlackCellsCount() const {
uint32_t counter = 0;
for (int32_t i = 0; i < width_ * height_; ++i)
if (boardArray_[i] == Board::CellBlack)
counter++;
return counter;
}
uint32_t Board::getWhiteCellsCount() const {
uint32_t counter = 0;
for (int32_t i = 0; i < width_ * height_; ++i)
if (boardArray_[i] == Board::CellWhite)
counter++;
return counter;
}
uint32_t Board::getEmptyCellsCount() const {
uint32_t counter = 0;
for (int32_t i = 0; i < width_ * height_; ++i)
if (boardArray_[i] == Board::CellEmpty)
counter++;
return counter;
}
const string Board::toString() const {
stringstream stream;
for (int y = 0; y < height_; ++y) {
for (int x = 0; x < width_; ++x) {
const string& cellString = cellToString(getCell(x, y));
stream << cellString << " ";
}
stream << endl;
}
return stream.str();
}
| true |
abde20ec17a6fbc83d2ed6dee26e8d1115754457 | C++ | ishankhanna28/Data-Structures-and-Algorithms | /string/str_tok.cpp | UTF-8 | 396 | 3.078125 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<string>
#include<cstring> //for strtok()
using namespace std;
int main()
{ char s1[80], str[10];
cout<<"Input a string..."<<endl;
gets(s1);
cout<<"Enter delimiter string..."<<endl;
gets(str);
char *ptr=strtok(s1,str);
cout<<ptr<<endl;
while(ptr!=NULL)
{
ptr=strtok(NULL,str);
cout<<ptr<<endl;
}
return 0;
}
| true |
20ccd8ecaa26b85a0243dd94ddde4509e6362ac0 | C++ | X1XJoker/C-C-Qt-course | /DZ #11/dz11.cpp | UTF-8 | 3,496 | 3.15625 | 3 | [] | no_license | //Менеджер Страничной памяти
//Киселев И.
#include <iostream>
#include <time.h>
#include <vector>
#include <algorithm>
using namespace std;
#define MEMSIZE 500
//Проверка на свободную память для помещения в него нового эл-та
bool chk_is_free(vector <int> &a, int start, int size)
{
for (int i=0; i<size; i++)
{
if (a[i+start]!=0)
return false;
}
return true;
}
//Проверка оставшейся памяти
vector<pair<int,int> > left_mem(vector<int> &a)
{
int cnt = 0;
vector<pair<int,int> > result;
int first = -1;
for (int i=0; i<a.size(); i++)
{
if (a[i]==0)
{
if (first == -1)
first = i;
cnt++;
}
else
{
if (first != -1)
{
result.push_back(pair<int,int>{first,cnt});
}
first = -1;
cnt = 0;
}
}
if (first != -1)
{
result.push_back(pair<int,int>{first,cnt});
}
return result;
}
//Получение первого индекса для заполнения
int get_start_pos(vector<int> &a, int size)
{
vector<pair<int, int> > l_mem = left_mem(a);
for (int i=0; i<l_mem.size(); i++)
{
if (l_mem[i].second >= size)
return l_mem[i].first;
}
return -1;
}
//Создание страницы в памяти
bool fvect(vector<int> &a) //,int size, int num
{
int size, num;
cout << "Введите размер \"страницы\": ";
cin >> size;
cout << "Введите номер \"страницы\": ";
cin >> num;
srand(time(NULL));
int start_num = get_start_pos(a,size);
if (start_num == -1)
{
return false;
}
for(int i=0; i<size; i++)
{
a[i+start_num] = num;
}
return true;
}
//Дефрагментация памяти
void defrag(vector <int> &a)
{
sort(a.begin(),a.end(),greater<int>());
}
//Удаление страницы
void free_val(vector <int> &a)
{
int num;
cout << "Введите номер удаляемой страницы: ";
cin >> num;
for(int i = 0; i < a.size(); i++)
{
if (a[i] == num)
a[i] = 0;
}
}
int main()
{
vector <int> a(MEMSIZE);
int size,num,mod=1;
for (int i=0; i<MEMSIZE; i++)
a[i] = 0;
cout << "Добро пожаловать в Менеджер Памяти" << endl;
while (mod != 0)
{
cout << "1.Добавить \"страницу\"" << endl;
cout << "2.Удалить \"страницу\"" << endl;
cout << "3.Дефрагментировать память" << endl;
cout << "4.Вывод текущего состояния памяти" << endl;
cout << "0. Выход" << endl;
cin >> mod;
switch(mod)
{
case 1:
{
if (fvect(a))
cout << "Заполнение прошло успешно\n";
else
cout << "Не достаточно памяти!\n";
break;
}
case 2:
free_val(a);
break;
case 3:
defrag(a);
break;
case 4:
{
system("clear");
for (auto i=0; i<a.size(); i++)
cout << a[i] << " ";
cout << endl;
break;
}
}
}
return 0;
}
| true |
6f255b5ae100e0ec844d258c9342815c7b539ece | C++ | alexandraback/datacollection | /solutions_5708284669460480_0/C++/juho/b1.cpp | UTF-8 | 1,347 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
void init();
void runCase();
int main()
{
init();
int T;
scanf("%d", &T);
for (int t = 1; t <= T; ++t) {
printf("Case #%d: ", t);
runCase();
}
}
// algorithms
int K, L, S;
char keys[101];
int keycnt[26];
char target[101];
void init() {
}
void initKeycnt()
{
for (int i = 0; i < 26; i++) {
keycnt[i] = 0;
}
for (int i = 0; i < K; i++) {
keycnt[keys[i] - 'A']++;
}
}
char tests[101];
int totalCnt;
int maxCnt;
int numTests;
void check()
{
int cnt = 0;
for (int i = 0, n = S - L + 1; i < n; i++) {
char* cur = &tests[i];
bool matched = true;
for (int j = 0; j < L; j++) {
if (target[j] != cur[j]) {
matched = false;
break;
}
}
if (matched) {
cnt++;
}
}
totalCnt += cnt;
if (maxCnt < cnt) {
maxCnt = cnt;
}
numTests++;
}
void getAll(int depth)
{
if (depth == S) {
check();
return;
}
for (int i = 0; i < K; i++) {
tests[depth] = keys[i];
getAll(depth + 1);
}
}
void runCase()
{
scanf("%d %d %d", &K, &L, &S);
scanf("%s", keys);
scanf("%s", target);
maxCnt = 0;
totalCnt = 0;
numTests = 0;
getAll(0);
double avgCnt = (double)totalCnt / numTests;
printf("%.9llf\n", (double)maxCnt - avgCnt);
}
| true |
bba757ccdd72e66634080418b4b7618aa174afd2 | C++ | Rick-Huang/Smart-Connect | /support.cpp | UTF-8 | 14,539 | 3.484375 | 3 | [] | no_license | #include "support.h"
#include "provided.h"
#include <iostream>
#include <vector>
using namespace std;
int determineBestComputerMove(Scaffold& s, int color, int& rating, int nWin, int depth)
{
int otherRating = -2; // initialize otherRating variable that stores the rating of the best human move, intialize to -2, which is considered null value
int winner = -2; // initialize winner variable that stores the color of the winner, initialize to -2, which is considered null value
int opposing = -2; // initialize opposing variable that stores the color of the opponent, initialize to -2, which is considered null value
vector<int> ratings; // create a vector that stores the ratings of each column
if(color == BLACK) // set opposing to be the correct color, the color of the opposing player
opposing = RED;
else
opposing = BLACK;
for(int i = 1; i <= s.cols(); i++) { // visit every column in the scaffold and play a move
if(s.makeMove(i, color) == true) {
if(completedSupport(s, winner, nWin) == true && winner == color) { // if a win results, store that value into the vector
ratings.push_back(5000000 - depth);
}
else if(completedSupport(s, winner, nWin) == true && winner == TIE_GAME) { // if a tie results, store that value into the vector
ratings.push_back(0 + depth);
}
else { // if no win or tie found, call determineBestHumanMove to determine the best next move of a human player and store that into the vector of ratings
determineBestHumanMove(s, opposing, otherRating, nWin, depth + 1);
ratings.push_back(otherRating); // store the rating of the human move into the vector
}
s.undoMove(); // undo the move that was made
}
else
ratings.push_back(-999999999); // if a column is full, push a very negative value that should never be chosen to serve as a placeholder in the vector
continue;
}
int bestMove = 1; // declare a variable that stores the column of the best move, initially set at 1
int bestScore = ratings[0]; // declare a variable that stores the rating of the best move, initially set as the rating of the first column
for(int j = 1; j < s.cols(); j++) // go through for loop, if a column has a higher rating than the initially set values, set those as the new bestMove and bestScore
{
if(ratings[j] > bestScore) {
bestMove = j+1;
bestScore = ratings[j];
}
}
rating = bestScore; // set rating to be that of the bestScore
return bestMove; // return the column of the best move
}
int determineBestHumanMove(Scaffold& s, int color, int& rating, int nWin, int depth)
{
int otherRating = -2; // initialize otherRating variable that stores the rating of the best human move, intialize to -2, which is considered null value
int winner = -2; // initialize winner variable that stores the color of the winner, initialize to -2, which is considered null value
int opposing = -2; // initialize opposing variable that stores the color of the opponent, initialize to -2, which is considered null value
vector<int> ratings; // create a vector that stores the ratings of each column
if(color == BLACK) // set opposing to be the correct color, the color of the opposing player
opposing = RED;
else
opposing = BLACK;
for(int i = 1; i <= s.cols(); i++) { // visit every column in the scaffold and play a move
if(s.makeMove(i, color) == true) {
if(completedSupport(s, winner, nWin) == true && winner == color) { // if a win results, store that value into the vector
ratings.push_back(-5000000 + depth);
}
else if(completedSupport(s, winner, nWin) == true && winner == TIE_GAME) { // if a tie results, store that value into the vector
ratings.push_back(0 - depth);
}
else { // if no win or tie found, call determineBestComputerMove to determine the best next move of a human player and store that into the vector of ratings
determineBestComputerMove(s, opposing, otherRating, nWin, depth + 1);
ratings.push_back(otherRating); // store the rating of the human move into the vector
}
s.undoMove(); // undo the move that was made
}
else // if the column is full, push a very positive number that should never be chosen to serve as a placeholder in the vector
ratings.push_back(999999999);
continue;
}
int bestMove = 1; // declare a variable that stores the column of the best move, initially set at 1
int bestScore = ratings[0]; // declare a variable that stores the rating of the best move, initially set as the rating of the first column
for(int j = 1; j < s.cols(); j++) // go through for loop, if a column has a lower rating than the initially set values, set those as the new bestMove and bestScore
{
if(ratings[j] < bestScore) {
bestMove = j+1;
bestScore = ratings[j];
}
}
rating = bestScore; // return the lowest score
return bestMove; // return the column of the lowest score
}
bool completedSupport(const Scaffold& board, int& winner, int nToWin)
{
int counterType = -2; // initialize a variable to store the color of the
int counter = 0;
if(board.cols() >= nToWin) { // if there are enough columns for there to be a horizonal win
for(int i = 1; i <= board.levels(); i++) { // check horizontal
counterType = -2;
counter = 0;
for(int j = 1; j <= board.cols(); j++) {
if(board.checkerAt(j, i) == VACANT) { // if a vacant spot is found, reset the counter back to 0
counter = 0;
counterType = -2;
continue;
}
else if(board.checkerAt(j, i) != VACANT) { // if the spot is not vacant
if(counterType == -2) { // if the counterType is set at null, set counterType to be the color of that node and set counter to be 1
counterType = board.checkerAt(j, i);
counter = 1;
continue;
}
else if(board.checkerAt(j, i) == counterType) { // if the checker is the same as the counterType, increment counter by 1
counter++;
}
else { // if the checker is the opposite color as counterType, set counter to 1 and set counterType to be that color
counter = 1;
counterType = board.checkerAt(j, i);
continue;
}
}
if(counter == nToWin) { // if the counter is the same number as the number of connections needed to win, return the color and return true
winner = counterType;
return true;
}
}
}
}
counterType = -2; // reset values of counter and counterType
counter = 0;
if(board.levels() >= nToWin) // if there are enough levels for there to be a vertical win
for(int j = 1; j <= board.cols(); j++) { // check vertical wins
counterType = -2;
counter = 0;
for(int i = 1; i<= board.levels(); i++) {
if(board.checkerAt(j, 1) == VACANT) // if the vertical is vacant, move on to the next column
break;
if(board.checkerAt(j, i) == VACANT) { //if a vacant spot is found, reset the values of counter and counterType
counter = 0;
counterType = -2;
continue;
}
else if(board.checkerAt(j, i) != VACANT) { // if a spot isn't vacant
if(counterType == -2) { // if the counterType is previously set as null, set it to the color of the checker at that space and set counter to 1
counterType = board.checkerAt(j, i);
counter = 1;
continue;
}
else if(board.checkerAt(j, i) == counterType) { // if the checker at a space is the same color as counterType, increment the counter
counter++;
}
else { // if the checker at a space is not the same color as counterType, set counterType to be that color and reset counter to 1
counter = 1;
counterType = board.checkerAt(j, i);
continue;
}
}
if(counter == nToWin) { // if counter reaches the number of connections to win, return the winner and return true
winner = counterType;
return true;
}
}
}
counterType = -2; // reset values of counterType and counter
counter = 0;
if(board.levels() >= nToWin) { // this program checks the diagonals for wins from the bottom left corner and then continuing to the right
for(int x = board.cols(); x >= 1; x--) {
counterType = -2;
counter = 0;
int i = 1;
int j = x;
while(i <= board.levels() && j <= board.cols()) { // the way that counterType and counter is incremented and changed is the same way as in the check for horizontal and vertical wins
if(board.checkerAt(j, i) == VACANT) {
counter = 0;
counterType = -2;
}
else if(board.checkerAt(j, i) != VACANT) {
if(counterType == -2) {
counterType = board.checkerAt(j, i);
counter = 1;
}
else if(board.checkerAt(j, i) == counterType) {
counter++;
}
else {
counter = 1;
counterType = board.checkerAt(j, i);
}
}
if(counter == nToWin) {
winner = counterType;
return true;
}
i++;
j++;
}
}
counterType = -2;
counter = 0;
for(int x = board.levels(); x >= 1; x--) { // check for diagonal wins starting from the bottom left corner and continuing upwards
counterType = -2;
counter = 0;
int i = x;
int j = 1;
while(i <= board.levels() && j <= board.cols()) { // the way that counterType and counter is incremented and changed is the same way as in the check for horizontal and vertical wins
if(board.checkerAt(j, i) == VACANT) {
counter = 0;
counterType = -2;
}
else if(board.checkerAt(j, i) != VACANT) {
if(counterType == -2) {
counterType = board.checkerAt(j, i);
counter = 1;
}
else if(board.checkerAt(j, i) == counterType) {
counter++;
}
else {
counter = 1;
counterType = board.checkerAt(j, i);
}
}
if(counter == nToWin) {
winner = counterType;
return true;
}
i++;
j++;
}
}
counterType = -2;
counter = 0;
for(int x = 1; x <= board.cols(); x++) { // check for diagonal wins starting at the top left corner and continuing downwards
counterType = -2;
counter = 0;
int i = 1;
int j = x;
while(i <= board.levels() && j >= 1) {
if(board.checkerAt(j, i) == VACANT) { // the way that counterType and counter is incremented and changed is the same way as in the check for horizontal and vertical wins
counter = 0;
counterType = -2;
}
else if(board.checkerAt(j, i) != VACANT) {
if(counterType == -2) {
counterType = board.checkerAt(j, i);
counter = 1;
}
else if(board.checkerAt(j, i) == counterType) {
counter++;
}
else {
counter = 1;
counterType = board.checkerAt(j, i);
}
}
if(counter == nToWin) {
winner = counterType;
return true;
}
i++;
j--;
}
}
counterType = -2;
counter = 0;
for(int x = board.levels(); x >= 1; x--) { // check for diagonal wins starting from the top right corner and continuing downwards
counterType = -2;
counter = 0;
int i = x;
int j = board.cols();
while(i <= board.levels() && j >= 1) { // the way that counterType and counter is incremented and changed is the same way as in the check for horizontal and vertical wins
if(board.checkerAt(j, i) == VACANT) {
counter = 0;
counterType = -2;
}
else if(board.checkerAt(j, i) != VACANT) {
if(counterType == -2) {
counterType = board.checkerAt(j, i);
counter = 1;
}
else if(board.checkerAt(j, i) == counterType) {
counter++;
}
else {
counter = 1;
counterType = board.checkerAt(j, i);
}
}
if(counter == nToWin) {
winner = counterType;
return true;
}
i++;
j--;
}
}
}
if(board.numberEmpty() == 0) { // return true and winner is a tie if there are no more free positions on the board
winner = TIE_GAME;
return true;
}
return false;
}
| true |
85dfa07fe1b4b0241e0a606588a1152ee7b57757 | C++ | 20SecondsToSun/NatureSystems | /AutonomousSystem/src/Vehicle.h | UTF-8 | 2,612 | 2.9375 | 3 | [] | no_license | #pragma once
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "FlowField.h"
#include "cinder/Rand.h"
#include "Path.h"
using namespace ci;
using namespace ci::app;
using namespace ci::gl;
using namespace std;
class Vehicle
{
public:
Vehicle(const double x = 0, const double y = 0)
:velocity(Vec2d::zero()),
acceleration(Vec2d::zero())
{
location = Vec2d(x, y);
velocity = Vec2d(1,1);
maxSpeed = 10;//Vec2d(40, 40);
maxForce = 0.3;// Vec2d(0.5, 0.5);
};
~Vehicle(){};
void update()
{
velocity += acceleration;
velocity.limit(maxSpeed);
location += velocity;
acceleration *= 0;
}
void draw()
{
gl::color(Color::gray(0.5));
drawSolidCircle(location, 10, 20);
}
void applyForce(Vec2d force)
{
acceleration += force;
}
void seek(Vec2d target)
{
Vec2d desired = target - location;
desired.normalize();
desired *= maxSpeed;
Vec2d steer = desired - velocity;
steer.limit(maxForce);// = clamp(steer, maxForce);
applyForce(steer);
}
void arrive(Vec2d target)
{
Vec2d desired = target - location;
float d = desired.length();
desired.normalize();
if (d < 100)
{
float m = map(d, 0, 100, 0, maxSpeed);
desired *= m;
}
else
{
desired *= maxSpeed;
}
Vec2d steer = desired - velocity;
steer.limit(maxForce);
applyForce(steer);
}
void follow(FlowField flow)
{
Vec2d desired = flow.lookup(location);
desired *= maxSpeed;
Vec2d steer = desired - velocity;
steer.limit(maxForce);
applyForce(steer);
}
void follow(Path path)
{
Vec2d predictVel = velocity;
predictVel.normalize();
predictVel *= 10;
Vec2d predictLoc = location + predictVel;
Vec2d a = path.getStart();
Vec2d b = path.getEnd();
Vec2d normalPoint = getNormalPoint(predictLoc, a, b );
Vec2d dir = b - a;
dir.normalize();
dir *= 5;
Vec2d target = normalPoint + dir;
float distance = normalPoint.distance(predictLoc);
if(distance > path.getRadius())
seek(target);
}
void stayAtBounds(Rectf rect)
{
if(!rect.contains(location))
{
location = randVec2f();
location.x *= rect.getWidth();
location.y *= rect.getHeight();
}
}
float map(float value,
float istart,
float istop,
float ostart,
float ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}
Vec2d getNormalPoint(Vec2d p, Vec2d a, Vec2d b)
{
Vec2d ap = p - a;
Vec2d ab = b - a;
ab.normalize();
ab *= ap.dot(ab);
return a + ab;
}
private:
Vec2d location;
Vec2d velocity;
Vec2d acceleration;
double maxForce;
double maxSpeed;
}; | true |
42bafd32648baabbe6cdedb14f6fb0ac80d894d8 | C++ | romeric/SoftComp | /function_space/one_d/Line.h | UTF-8 | 4,653 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef LINE_H
#define LINE_H
#include "quadrarure_rules/QuadratureRule.h"
namespace SoftComp {
class Line {
public:
vector<real> bases;
vector<real> grad_bases;
Line() = default;
SC_INLINE Line(integer C, real xi, boolean equally_spaced=false) {
auto n = C+2;
auto quad = QuadratureRule();
vector<real> eps;
if (!equally_spaced) {quad.GaussLobatto(C+1); eps = quad.points;}
else {quad.Gauss(C+1,-1.,1.); eps = quad.points;}
auto A = zeros(n,n);
for (auto i=0; i<n; ++i) {
A(i,0) = 1.;
}
for (auto j=0; j<n; ++j)
for (auto i=1; i<n; ++i)
A(j,i) = pow(eps[j],i);
bases = zeros(n);
grad_bases = zeros(n);
for (auto ishape=0; ishape<n; ishape++) {
auto RHS = zeros(n);
RHS[ishape] = 1.;
// Solve linear system (dense LU)
vector<real> coeff = solve(A,RHS);
// Build shape functions
for (auto incr=0; incr<n; incr++)
bases[ishape] += coeff[incr]*pow(xi,incr);
// Build derivate of shape functions
for (auto incr=0; incr<n-1; incr++)
grad_bases[ishape] += (incr+1)*coeff[incr+1]*pow(xi,incr);
}
}
};
#include "mesh/nodal_arrangement.h"
class Quad {
public:
vector<real> bases;
matrix<real> grad_bases;
Quad() = default;
SC_INLINE Quad(integer C, real zeta, real eta, boolean equally_spaced=false, boolean arrange=true) {
// Allocate
auto nsize = (C+2)*(C+2);
bases = zeros(nsize);
grad_bases = zeros(nsize,2);
// Compute bases
auto line_func_zeta = Line(C, zeta, equally_spaced);
auto line_func_eta = Line(C, eta, equally_spaced);
auto &Nzeta = line_func_zeta.bases;
auto &Neta = line_func_eta.bases;
// Compute gradient of bases functions
auto &gNzeta = line_func_zeta.grad_bases;
auto &gNeta = line_func_eta.grad_bases;
// Don't pass directly product expressions to functions receiving eigen generic expressions
// matrix<real> dum0 = Neta*transpose(Nzeta);
// vector<real> dum1 = flatten(dum0);
// matrix<real> dum2 = gNeta*transpose(Nzeta);
// matrix<real> dum3 = Neta*transpose(gNzeta);
// vector<real> dum4 = flatten(dum2);
// vector<real> dum5 = flatten(dum3);
vector<real> dum1 = flatten(outer(Neta,Nzeta));
vector<real> dum4 = flatten(outer(gNeta,Nzeta));
vector<real> dum5 = flatten(outer(Neta,gNzeta));
// Ternsorial product
if (arrange==1) {
auto node_arranger = NodalArrangement("quad",C+1);
for (auto i=0; i< size(bases); ++i) {
bases(i) = dum1(node_arranger.element_arrangement(i));
grad_bases(i,0) = dum4(node_arranger.element_arrangement(i));
grad_bases(i,1) = dum5(node_arranger.element_arrangement(i));
}
}
else {
bases.head(nsize) = dum1;
grad_bases.col(0) = dum4;
grad_bases.col(1) = dum5;
}
}
SC_INLINE void Compute(integer C, real zeta, real eta, boolean equally_spaced=false, boolean arrange=true) {
// Allocate
auto nsize = (C+2)*(C+2);
bases = zeros(nsize);
grad_bases = zeros(nsize,2);
// Compute bases
auto line_func_zeta = Line(C, zeta, equally_spaced);
auto line_func_eta = Line(C, eta, equally_spaced);
auto &Nzeta = line_func_zeta.bases;
auto &Neta = line_func_eta.bases;
// Compute gradient of bases functions
auto &gNzeta = line_func_zeta.grad_bases;
auto &gNeta = line_func_eta.grad_bases;
// Don't pass directly product expressions to functions receiving eigen generic expressions
vector<real> dum1 = flatten(outer(Neta,Nzeta));
vector<real> dum4 = flatten(outer(gNeta,Nzeta));
vector<real> dum5 = flatten(outer(Neta,gNzeta));
// Ternsorial product
if (arrange==1) {
auto node_arranger = NodalArrangement("quad",C+1);
for (auto i=0; i< size(bases); ++i) {
bases(i) = dum1(node_arranger.element_arrangement(i));
grad_bases(i,0) = dum4(node_arranger.element_arrangement(i));
grad_bases(i,1) = dum5(node_arranger.element_arrangement(i));
}
}
else {
bases.head(nsize) = dum1;
grad_bases.col(0) = dum4;
grad_bases.col(1) = dum5;
}
}
};
}
#endif // LINE_H
| true |
764fa91a60d8b3e0713c19b8822019751e0f51c5 | C++ | Lingfei-Li/leetcode | /archive/45-Jump Game II - 2.cpp | UTF-8 | 2,241 | 2.78125 | 3 | [] | no_license | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
#include<ctime>
#include<cmath>
#include<cstdlib>
#include<stack>
#include<set>
#include<map>
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void printVector(vector<int>& v);
void printArray(int* A, int n);
void printListkedList(ListNode *u);
void genVector(vector<int>& v, int n);
void genArray(int* A, int n);
ListNode* genLinkedList(int n);
static const int maxn = 1e5;
int INF = 1<<30;
int dp[maxn];
int jump(vector<int>& nums) {
if(nums.size() == 1) return 0;
memset(dp, 0, sizeof(dp));
dp[nums.size() - 1] = 0;
for(int i = nums.size() - 2; i >= 0; i --) {
int minstep = INF;
for(int j = 1; j <= nums[i]; j ++) {
if(i+j >= nums.size()) break;
minstep = min(minstep, dp[i+j]) + 1;
}
// printf("i:%d %d, minstep:%d\n", i, nums[i], minstep);
dp[i] = minstep;
}
return dp[0];
}
int main() {
srand(time(NULL));
vector<int> v;
genVector(v, 10);
printVector(v);
cout<<jump(v)<<endl;
return 0;
}
void printVector(vector<int>& v) {
for(int i = 0; i < v.size(); i ++) printf("%d ", v[i]);
printf("\n");
}
void printArray(int* A, int n) {
for(int i = 0; i < n; i ++) printf("%d ", A[i]);
printf("\n");
}
void printListkedList(ListNode *u) {
while(u) {
printf("%d -> ", u->val);
u = u->next;
}
printf("\n");
}
void genVector(vector<int>& v, int n) {
for(int i = 0; i < n; i ++) v.push_back(rand()%5+1);
// sort(v.begin(), v.end());
}
void genArray(int* A, int n) {
for(int i = 0; i < n; i ++) A[i] = rand()%20-9;
sort(A, A+n);
}
ListNode* genLinkedList(int n) {
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
ListNode* h = head;
for(int i = 0; i < n; i ++) {
h->val = i;
if(i!=n-1)h->next = (ListNode*)malloc(sizeof(ListNode));
else h->next = 0;
h = h->next;
}
return head;
}
| true |
506ffa16000eccaa66e514cfb7ca337b63811964 | C++ | adevore3/Computer_Vision | /Project3/skeleton/PSM/src/Depths.cpp | UTF-8 | 4,402 | 3.046875 | 3 | [] | no_license | #include "Depths.h"
#include "CVector.h"
#include "CMatrixSparse.h"
#include "cg.h"
#define CGEPSILON .5
namespace {
void copyDepths(const CVector<double> & z,
const CIntImage & zind,
DepthImage * depths)
{
double minD=z(0);
double maxD=z(0);
for(int i=0;i<z.Length();i++)
{
maxD = max(z(i),maxD);
minD = min(z(i),minD);
}
cout << "z range (" << minD << ", " << maxD << ")" << endl;
for (int y = 0; y < depths->Shape().height; y++)
for (int x = 0; x < depths->Shape().width; x++)
{
int index = zind.Pixel(x,y,0);
if (index == -1)
depths->Pixel(x,y,0) = 0;
else
depths->Pixel(x,y,0) = float(z(index)-minD);
}
}
bool
pixvalid(const CIntImage &i, int x, int y)
{
return i.Shape().InBounds(x,y) && (i.Pixel(x,y,0) != -1);
}
void makeMmatrix(CMatrixSparse<double> & M, const CIntImage & zind,
const NormalImage &normals)
{
int i,j;
int n=0;
printf("Making M matrix\n");
///////////////////////////////////////////////////////////
// TODO: fill in the entries of the M matrix. It need not
// have entries in every row.
//
/***** BEGIN *****/
int width = zind.Shape().width;
int height = zind.Shape().height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double row = zind.Pixel(x, y, 0);
if (row < 0) // If pixel outside mask, don't use it.
continue;
int rightNeighborPixel = zind.Pixel(x+1, y, 0); // Neighbor pixel to the right
int topNeighborPixel = zind.Pixel(x, y+1, 0); // Nieghbor pixel to the top
float n_z = normals.Pixel(x, y, 0).z;
if (rightNeighborPixel != -1) // If pixel outside mask, don't use it.
{
M(row * 2, row) = -n_z;
M(row * 2, rightNeighborPixel) = n_z;
}
if (topNeighborPixel != -1) // If pixel outside mask, don't use it.
{
M(row * 2 + 1, row) = -n_z;
M(row * 2 + 1, topNeighborPixel) = n_z;
}
}
}
/***** END *****/
}
void makeVvector(CVector<double> & v, const CIntImage & zind,
const NormalImage & normals)
{
int i,j,n=0;
assert(zind.Shape() == normals.Shape());
printf("Making v vector\n");
///////////////////////////////////////////////////////
// TODO: fill in the entries of the v vector. It need
// not have entries in every row.
//
/***** BEGIN *****/
int width = zind.Shape().width;
int height = zind.Shape().height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double row = zind.Pixel(x, y, 0);
if (row != -1)
{
v[row * 2] = -normals.Pixel(x, y, 0).x;
v[row * 2 + 1] = -normals.Pixel(x, y, 0).y;
}
}
}
/***** END *****/
}
} // unnamed namespace
void
computeDepths(DepthImage *depths, const NormalImage *normals,
const ColorImage *mask)
{
const int width = normals->Shape().width;
const int height = normals->Shape().height;
/* Construct an index map showing for each pixel
it's corresponding index in the depth vector.
Also figure out how many pixels there are
inside the mask. */
int numvars = 0;
CIntImage zind(width,height,1);
for (int y = 0; y<height; y++)
for (int x = 0; x<width; x++)
{
if (mask && !mask->Pixel(x,y,0))
zind.Pixel(x,y,0) = -1;
else
zind.Pixel(x,y,0) = numvars++;
}
/* The vector z will contain the depths for each
pixel. */
CVector<double> z(numvars);
z.clear();
/* This is the number of constraints we have.
At most, we'll have two constraints for each
pixel, to its left and right neighbour. */
int numConstraints = 2*numvars; // can be a loose upper bound
/* The constraint matrix. One row for every constraint, one
column for every variable. */
CMatrixSparse<double> M(numConstraints,numvars);
makeMmatrix(M,zind,*normals);
/* The constraint vector. One row for every constraint. */
CVector<double> v(numConstraints);
makeVvector(v,zind,*normals);
/* We want to solve Mz = v in a least squares sense. The
solution is M^T M z = M^T v. We denote M^T M as A and
M^T v as b, so A z = b. */
CMatrixSparse<double> A(M.mTm());
assert(A.isSymmetric());
CVector<double> r = A*z; /* r is the "residual error" */
CVector<double> b(v*M);
// solve the equation A z = b
solveQuadratic<double>(A,b,z,300,CGEPSILON);
// copy the depths back from the vector z into the image depths
copyDepths(z,zind,depths);
}
| true |
6ab652762ff18b22dd40a7743edb564a0883ac39 | C++ | Vaa3D/vaa3d_tools | /hackathon/LLF/neuron_factor_tree/neuron_factor_tree_tools.cpp | UTF-8 | 32,147 | 2.734375 | 3 | [
"MIT"
] | permissive | /*neuron_factor_tree_tools.cpp
*funcs for neuron_factor_tree struct.
*/
#include "neuron_factor_tree_plugin.h"
#include <QtGlobal>
void calculate_branches(const NeuronTree &neuron, vector<V3DLONG> &branches)
{
//calculate a node's branch num;
V3DLONG neuron_siz = neuron.listNeuron.size();
branches = vector<V3DLONG>(neuron_siz,0);
for (V3DLONG i = 0; i < neuron_siz; i++)
{
if (neuron.listNeuron[i].pn < 0) continue;//root
V3DLONG pid = neuron.hashNeuron.value(neuron.listNeuron[i].pn);//hash:node no.to list no.
branches[pid]++;
}
cout<<"Calculate branches at "<<neuron_siz<<" nodes"<<endl;
}
void get_leaf_branch_nodes(const NeuronTree &neuron, vector<V3DLONG> branches, set<V3DLONG> &leaf_node_set, set<V3DLONG> &branch_node_set)
{
V3DLONG neuron_siz = neuron.listNeuron.size();
//find leaf nodes and branche nodes;
for (V3DLONG i = 0; i < neuron_siz; i++)
{
if(branches[i]==0)
leaf_node_set.insert(i);
else if(branches[i]>1)
branch_node_set.insert(i);
}
if (!branch_node_set.count(0)) branch_node_set.insert(0);//if root have only one branch, still insert it in the nft_node_set;
cout<<"Find leaf nodes finish.The number of leaf nodes is "<<leaf_node_set.size()<<endl;
cout<<"Find branch nodes finish.The number branch nodes is "<<branch_node_set.size()<<endl;
}
void get_nft_node_relation_map(const NeuronTree &neuron, vector<V3DLONG> branches, set<V3DLONG> nft_node_set, map<V3DLONG,V3DLONG> &nft_parent_map, map<V3DLONG,V3DLONG> &nft_child_map, map<V3DLONG, V3DLONG> &nft_sibling_map)
{
//Initializae map;
for(auto it = nft_node_set.begin(); it!=nft_node_set.end(); it++)
{
nft_child_map[*it] = -1;
nft_parent_map[*it] = -1;
nft_sibling_map[*it] = -1;
}
//renew values
for(auto it = nft_node_set.begin(); it!=nft_node_set.end(); it++)
{
V3DLONG current = *it;
//V3DLONG parent = neuron.hashNeuron.value(neuron.listNeuron[parent].pn);
if(current==0) continue;//for nft root don't have a parent;
V3DLONG parent = neuron.hashNeuron.value(neuron.listNeuron[current].pn);
for (;parent!=0 && branches[parent]<=1;parent = neuron.hashNeuron.value(neuron.listNeuron[parent].pn));//go to a parent node;
//if(parent==0) continue;//
nft_parent_map[current] = parent;
if(nft_child_map[parent] != -1)
{
auto sib = nft_child_map[parent];
while (nft_sibling_map[sib] != -1) sib = nft_sibling_map[sib];//this could collect all the children node in siblings;
nft_sibling_map[sib] = current;//Add current to the list's tail;
}
else
nft_child_map[parent] = current;
}
cout<<"Get a nft relation map for nft nodes"<<endl;
}
//create a neuron_factor_treee from a neuron_tree;
NeuronFactorTree create_neuron_factor_tree(const NeuronTree &neuron)
{
vector<V3DLONG> branches;
calculate_branches(neuron, branches);
set<V3DLONG> leaf_node_set;
set<V3DLONG> branch_node_set;
get_leaf_branch_nodes(neuron, branches, leaf_node_set, branch_node_set);//find leaf nodes and branch nodes;
set<V3DLONG> nft_node_set = branch_node_set;
nft_node_set.insert(leaf_node_set.begin(), leaf_node_set.end());//use leaf nodes and branch nodes as nft nodes;
map<V3DLONG, V3DLONG> nft_parent_map;//record each nft nodes' parent node;
map<V3DLONG, V3DLONG> nft_child_map;//record each nft nodes' child node;
map<V3DLONG, V3DLONG> nft_sibling_map;
get_nft_node_relation_map(neuron, branches, nft_node_set, nft_parent_map, nft_child_map, nft_sibling_map);
NeuronFactors nfs;//neuron factors map;
NeuronFactor nft_root;//record tree root;
vector<int> marked(neuron.listNeuron.size()+1, 0);//record how many child node is visited;
queue<V3DLONG> q;
for each (auto l in leaf_node_set)
{
q.push(l);
}
while (!q.empty()) {
auto current = q.front();
V3DLONG pa, ch, ch_sb, sib;
pa = nft_parent_map.at(current);
sib = nft_sibling_map.at(current);
ch = nft_child_map.at(current);
ch_sb = (ch != -1 ? nft_sibling_map.at(ch) : -1);
NeuronFactor nf_current(1, current, neuron.listNeuron[current].x, neuron.listNeuron[current].y, neuron.listNeuron[current].z, pa, ch, ch_sb, sib);
//sib = (nft_child_map.at(pa) == current ? nft_sibling_map.at(current) : nft_child_map.at(pa));
if (branches[current] != 0 && pa!=-1)//for leaf don,t calculate features;
{
sib = (nft_child_map.at(pa) == current ? nft_sibling_map.at(current) : nft_child_map.at(pa));
//for feature caluculation, make sure sib is exsitted(SIB.sib = current, current.sib = -1 => curent.sib = SIB);
calculate_features_at_node(neuron, nf_current, ch, ch_sb, sib, pa, nfs);//don,t calculate features at 0;
}
nfs[current] = nf_current;
if (nft_parent_map[current] == -1) nft_root = nf_current;//the nft_root may NOT BE the neuron root(branches[root]==1), let the first branch be nft_root;
if (pa != -1)
{
marked[pa] = marked[pa] + 1;
if (marked[pa] == 2) q.push(pa);//if one node's two children is visited, means feature could calculated from it, enqueue;
}
q.pop();
}
//if (nft_root.label == -1) nft_root = NeuronFactor(1, 0, neuron.listNeuron[0].x, neuron.listNeuron[0].y, neuron.listNeuron[0].z, -1, nft_child_map[0], -1);//let root be nft_root;
cout << "Get NeuronFactor Tree root at nft_node:" << nft_root.label << "." << endl;
NeuronFactorTree nft = NeuronFactorTree(1, neuron.file.toStdString(), nft_root, nfs);
cout << "NeuronFactor Tree constructed." << endl;
return nft;
}
void save_neuron_factor_tree(const NeuronFactorTree nft, const QString path)
{
/*Save nft
*saves XYZ coordinates for visualization
*folleowed by features in comments format
*so that nft could shown in vaa3d.
*/
cout<<"Saving NeuronFactor Tree."<<endl;
FILE * fp;
fp = fopen(path.toLatin1(), "w");
cout<<"Open file :"<<qPrintable(path)<<endl;
if (fp==NULL)
{
cout<<"ERROR! Can't open file "<<qPrintable(path)<<endl;
}
cout<<"neuron factor num is :"<<nft.neuron_factors.size()<<endl;
//header
fprintf(fp, "#neuronFactorTree.nft format, nft node start with id 0;\n"
"#to get the node id in neuronTree, use neuron.listNeuron[node];\n"
"#level:the level neuronfactortree is from;\n"
"#neuron path:the absolute path of swc file;\n"
"#nf info:V3DLONG id;label for visualization color(2 for red);float x, y, z;radius as 0.05;\n"
"#V3DLONG parent_id,child_id,child_sibling_id,sibling_id(-1 for don't exist);\n"
"#nf feature values:For root node and leaf node DONOT have any values;\n");
//feature names
fprintf(fp, "#FEATURES: fea_dist_c1 fea_dist_c2 fea_dist_soma fea_bif_angle_remote fea_path_len_1 fea_contraction_1 fea_diameter_avg_1 fea_area_avg_1 fea_surface_1 fea_volume_1 "
"fea_path_len_2 fea_contraction_2 fea_diameter_avg_2 fea_area_avg_2 fea_surface_2 fea_volume_2 fea_bif_angle_local"
/*" fea_tilt_angle_remote fea_tilt_angle_local fea_torque_remote fea_torque_local "
"fea_child_ratio"*/
" fea_direction_x fea_direction_y fea_direction_z fea_tips_num fea_tips_asymmetry\n");//define feature names;
//save level
fprintf(fp, "#LEVEL: %d\n", nft.level);
//save swc path
fprintf(fp, "#NEURONPATH: ");
fprintf(fp, nft.neuron_path.c_str());
fprintf(fp, "\n");
//save the xyz coordinates in swc format, so that file could display in vaa3d;
for (auto it = nft.neuron_factors.begin(); it!=nft.neuron_factors.end();it++)
{
//cout<<it->second.label<<it->second.x<< it->second.y<<it->second.z<<it->second.parent<<endl;
fprintf(fp, "%ld %d %5.3f %5.3f %5.3f %5.3f %ld %ld %ld %ld\n",
it->second.label, 2, it->second.x, it->second.y, it->second.z, 0.05,
it->second.parent, it->second.child, it->second.child_sibling, it->second.sibling);
//it->second.label, it->second.x, it->second.y, it->second.z, it->second.parent, it->second.child, it->second.sibling);
//print features
fprintf(fp, "#VALUES:");
for(int i=0; i<it->second.feature_vector.size(); i++)
{
fprintf(fp, " %5.3f", it->second.feature_vector[i]);
}
fprintf(fp, "\n");
}
cout<<"NeuronFactor Tree saved at path:"<<qPrintable(path)<<endl;
fclose(fp);
}
NeuronFactorTree read_neuron_factor_tree(const QString path)
{
cout<<"Reading NeuronFactor Tree."<<endl;
NeuronFactorTree nft;
QFile qf(path);
if (! qf.open(QIODevice::ReadOnly | QIODevice::Text))
{
v3d_msg(QString("open file at [%1] failed!").arg(path));
return nft;
}
//nft members
NeuronFactor neuron_factor_tree_root;
NeuronFactors neuron_factors;
QStringList feature_names;//record feature names in string;
while (! qf.atEnd())
{
NeuronFactor nf;
/************************************************************************/
/* nf members
int level;
V3DLONG label;
float x, y, z;
unordered_map<string,double> feature;
vector<double> feature_vector;
V3DLONG parent;
V3DLONG child;
V3DLONG child_sibling;
V3DLONG sibling; */
/************************************************************************/
//nf features
unordered_map<string,double> feature;
vector<double> feature_vector;
QStringList feature_values;//record feature values in string;
char _buf[1000], *buf;
qf.readLine(_buf, sizeof(_buf));
for (buf=_buf; (*buf && *buf==' '); buf++); //skip space
if (buf[0]=='\0') continue;//empty
if (buf[0]=='#')//headers
{
if (buf[1] == 'L'&&buf[2] == 'E'&&buf[3] == 'V'&&buf[4] == 'E'&&buf[5] == 'L'&&buf[6] == ':') nft.level = QString("%1").arg(buf + 8).toInt();//skip "";
else if (buf[1] == 'N'&&buf[2] == 'E'&&buf[3] == 'U'&&buf[4] == 'R'&&buf[5] == 'O'&&buf[6] == 'N'&&
buf[7] == 'P'&&buf[8] == 'A'&&buf[9] == 'T'&&buf[10] == 'H'&&buf[11] == ':')
nft.neuron_path = QString("%1").arg(buf + 13).toStdString();//skip a blank;
else if (buf[1]=='F'&&buf[2]=='E'&&buf[3]=='A'&&buf[4]=='T'&&buf[5]=='U'&&buf[6]=='R'&&buf[7]=='E'&&buf[8]=='S'&&buf[9]==':')
{
QString feature_name_str = QString("%1").arg(buf+10);
feature_names = feature_name_str.split(" ", QString::SkipEmptyParts);
}
continue;
}
//First line for nf members;
QStringList msl = QString(buf).trimmed().split(" ",QString::SkipEmptyParts);//members string list;
if (msl.size()==0) continue;//empty string
nf.level = nft.level;
for (int i=0; i<msl.size(); i++)
{
msl[i].truncate(99);//in case it's too long;
if (i==0) nf.label = msl[i].toLong();
//skip msl[1] which just control color;
else if (i==2) nf.x = msl[i].toFloat();
else if (i==3) nf.y = msl[i].toFloat();
else if (i==4) nf.z = msl[i].toFloat();
//skip msl[5] which is for radius;
else if (i==6) nf.parent = msl[i].toLong();
else if (i==7) nf.child = msl[i].toLong();
else if (i == 8) nf.child_sibling = msl[i].toLong();
else nf.sibling = msl[i].toLong();
}
//Second line for faeture values;
qf.readLine(_buf, sizeof(_buf));
buf = _buf;
if (buf[0] == '#'&&buf[1] == 'V'&&buf[2] == 'A'&&buf[3] == 'L'&&buf[4] == 'U'&&buf[5] == 'E'&&buf[6] == 'S'&&buf[7] == ':')
{
QString features_str = QString("%1").arg(buf + 8);
feature_values = features_str.split(" ", QString::SkipEmptyParts);
if (feature_values.size() != 1) {//for don't have any values, skip;
for (int i = 0; i < feature_names.size(); i++)
{
feature[feature_names[i].toStdString()] = feature_values[i].toDouble();
feature_vector.push_back(feature_values[i].toDouble());
nf.feature = feature;
nf.feature_vector = feature_vector;
}
}
}
neuron_factors[nf.label] = nf;
if (nf.parent==-1) neuron_factor_tree_root = nf;
}
nft.neuron_factor_tree_root = neuron_factor_tree_root;
nft.neuron_factors = neuron_factors;
cout<<"Reading NeuronFactor Tree finish."<<endl;
cout<<"NeuronFactor Tree size:"<<nft.neuron_factors.size()<<endl;
return nft;
}
NeuronFactorSequences serialization(const NeuronFactorTree nft)
{
NeuronFactor current = nft.neuron_factor_tree_root;
NeuronFactorSequences nfseqs;
NeuronFactorSequence sequence;
sequence.push_back(current);
while (1)
{
while (current.child!=-1)
{
current = nft.neuron_factors.at(current.child);
sequence.push_back(current);
}
nfseqs.push_back(sequence);
current = sequence.back();
sequence.pop_back();//pop out last;
for (;current.sibling==-1 && current.parent!=-1;current = nft.neuron_factors.at(current.parent))sequence.pop_back();//find a node which has a sibling
if (current.sibling==-1 ) {break;}//means get to the root node, break;
current = nft.neuron_factors.at(current.sibling);
sequence.push_back(current);
}
//unordered_map<V3DLONG, bool> marked;
//(nft.neuron_factors.begin(), nft.neuron_factors.end(), [&marked](const pair<int, NeuronFactor> p) {marked[p.first] = false; });
cout<<"NeuronFactor Tree serializated."<<endl;
cout<<"Got sequences:"<<nfseqs.size()<<endl;
return nfseqs;
}
void save_neuron_factor_sequences(const NeuronFactorSequences &nfseqs, const string neuron_file_path, const QString path)
{
/*
*.nfss files for neuronfactor sequences;
*in format:
*#FEATURES : feaeture names
*#LEVEL:
*#SEQ_SIZE:
*#ROOT : a seq begins
*#VALUES:
*#VALUES:
*...
*#LEAF : a seq ends
*...
*/
if (nfseqs.size() == 0) { cout<<"Sequences is empty!"; return; }
cout<<"Saving NeuronFactor Sequences."<<endl;
FILE * fp;
fp = fopen(path.toLatin1(), "w");
cout<<"Open file :"<<qPrintable(path)<<endl;
if (fp==NULL)
{
cout<<"ERROR! Can't open file "<<qPrintable(path)<<endl;
}
cout<<"neuron sequence num is :"<<nfseqs.size()<<endl;
//header for features
fprintf(fp, "#FEATURES: fea_dist_c1 fea_dist_c2 fea_dist_soma fea_bif_angle_remote fea_path_len_1 fea_contraction_1 fea_diameter_avg_1 fea_area_avg_1 fea_surface_1 fea_volume_1 "
"fea_path_len_2 fea_contraction_2 fea_diameter_avg_2 fea_area_avg_2 fea_surface_2 fea_volume_2 fea_bif_angle_local"
/*" fea_tilt_angle_remote fea_tilt_angle_local fea_torque_remote fea_torque_local "
"fea_child_ratio"*/
" fea_direction_x fea_direction_y fea_direction_z fea_tips_num fea_tips_asymmetry\n");//define feature names;
//save level
fprintf(fp, "#LEVEL: %d\n", nfseqs[0].front().level);
//save neuron file path
fprintf(fp, "#NEURONPATH: ");
fprintf(fp, neuron_file_path.c_str());
fprintf(fp, "\n");
//a block for a sequence;
for (auto seq = nfseqs.begin(); seq != nfseqs.end(); seq++)
{
fprintf(fp, "#SEQ_SIZE: %d\n",(*seq).size());
fprintf(fp, "#NODES:");
for (auto nf = (*seq).begin(); nf != (*seq).end(); nf++)
{
fprintf(fp, " %d", nf->label);
}
fprintf(fp, "\n");
//feature1,feature2,...featuren,
for(auto nf = (*seq).begin(); nf != (*seq).end(); nf++)
{
if (nf->parent == -1) fprintf(fp, "#ROOT\n");//mark root;
else if (nf->child == -1) fprintf(fp, "#LEAF\n");//mark leaf;
else//print values;
{
fprintf(fp, "#VALUES:");
auto f_vector = (*nf).feature_vector;
for (int i = 0; i < f_vector.size(); i++)
{
double f = f_vector[i];
fprintf(fp, " %5.3lf", f);
}
fprintf(fp, "\n");
}
}
fprintf(fp, "\n");
}
cout << "NeuronFactor Sequences saved at path:" << qPrintable(path) << endl;
fclose(fp);
}
void assemble_neuron_tree_from(const QString gen_file_path)
{
/*Input: .gen file, constituted by neuron factor origin sequences.
*format:
*node index, node origin swc file, node origin id, node parent index.
*/
QString neuron_tree_file = gen_file_path.mid(0, gen_file_path.lastIndexOf(".")) + ".swc";
auto branches = collect_neuron_factor_infos(gen_file_path);
vector<NeuronSWC> neuron = adjust_branches(branches);
save_swc_file(neuron_tree_file, neuron);
cout<<"Neuron swc file saved at ["<<qPrintable(neuron_tree_file)<<"].";
}
vector<Branch> collect_neuron_factor_infos(const QString file_path)
{
cout << qPrintable(file_path) << endl;
QFile qf(file_path);
vector<Branch> branch_vector;
if (!qf.open(QIODevice::ReadOnly | QIODevice::Text))
{
v3d_msg(QString("open file [%1] failed!").arg(file_path));
return branch_vector;
}
while (!qf.atEnd())
{
char buf[1000];
qf.readLine(buf, sizeof(buf));
if (buf[0] != '#')
{
Branch branch;
QString str = QString("%1").arg(buf);
QStringList factor_infos = str.split(" ");
if (factor_infos.size() == 1) continue;//ship empty line;
int branch_id = factor_infos[0].toInt();
QString origin_swc = factor_infos[1];
int origin_node = factor_infos[2].toInt();
int parent_branch_id = factor_infos[3].toInt();
if (origin_node == 0)
{
branch_vector.push_back(branch);//for root and leaf node, put a fake branch to keep vector index right;
continue;//skip root and leaf;
}
//collect branch nodes;
NeuronTree neuron = readSWC_file(origin_swc);
vector<V3DLONG> branches;
calculate_branches(neuron, branches);
origin_node = neuron.hashNeuron.value(origin_node);//from swc node id (start with 1) to list id (start with 0).
int left_or_right = 0;
V3DLONG child_branch_root_id[2] = { -1, -1};//two child branches' root id, unhash;
auto getCoordxyz = [](const NeuronSWC node) { return Coordxyz(node.x, node.y, node.z); };//get coord from a NeuronSWC;
for each (auto node in neuron.listNeuron)
{
if (branches[neuron.hashNeuron.value(node.n)] != 1)
{
V3DLONG parent = neuron.hashNeuron.value(node.pn);
for (; parent != 0 && branches[parent] <= 1; parent = neuron.hashNeuron.value(neuron.listNeuron[parent].pn));
if (parent == origin_node)//node's nf parent is origin_node, collect those between node and origin_node;
{
branch.branch_end[left_or_right] = node.pn;//two branch_end;
branch.branch_edge_coord[left_or_right] = Coordxyz(node.x, node.y, node.z);
//cout << branch.branch_edge_coord[left_or_right] << endl;
//record a branch's edege coord so that child branch coord can use;
child_branch_root_id[left_or_right] = node.n;//get child branchs' root id;
left_or_right++;
for (auto pa = neuron.hashNeuron.value(node.pn); pa != origin_node; pa = neuron.hashNeuron.value(neuron.listNeuron[pa].pn))
{
branch.branch_nodes.push_back(neuron.listNeuron[pa]);
//cout << neuron.listNeuron[pa].n << endl;
}
//cout << "one stem finish." << endl;
}
}
}
branch.branch_nodes.push_back(neuron.listNeuron[origin_node]);//a branch finish, collect parent node also;
cout << "Branch nodes collected." << endl;
/*Update 2019-06-09, record child branchs' directions, so that could adjust generation branch's direction in future;*/
//record a branch's child bracnch's direction vector;
Coordxyz child_branch1_end[2];
Coordxyz child_branch1_root;
int child_branch1_left_or_right = 0;
Coordxyz child_branch2_end[2];
Coordxyz child_branch2_root;
int child_branch2_left_or_right = 0;
for each (auto node in neuron.listNeuron)
{
if (branches[neuron.hashNeuron.value(node.n)] != 1)
{
V3DLONG parent = neuron.hashNeuron.value(node.pn);
for (; parent != 0 && branches[parent] <= 1; parent = neuron.hashNeuron.value(neuron.listNeuron[parent].pn));
if (parent == neuron.hashNeuron.value(child_branch_root_id[0]))//node's nf parent is one child branch root, get a vector from root to it;
{
child_branch1_root = getCoordxyz(neuron.listNeuron[parent]);
child_branch1_end[child_branch1_left_or_right] = getCoordxyz(node);
child_branch1_left_or_right++;
}
else if (parent == neuron.hashNeuron.value(child_branch_root_id[1]))//another child branch root;
{
child_branch2_root = getCoordxyz(neuron.listNeuron[parent]);
child_branch2_end[child_branch2_left_or_right] = getCoordxyz(node);
child_branch2_left_or_right++;
}
}
}
Coordxyz child1_direction, child2_direction;
auto root2child1 = child_branch1_end[0] - child_branch1_root;
auto root2child2 = child_branch1_end[1] - child_branch1_root;
//child1_direction = (root2child1 / root2child1.length()) + (root2child2 / root2child2.length());//direction_1;
child1_direction = root2child1 + root2child2;//direction_1;
root2child1 = child_branch2_end[0] - child_branch2_root;
root2child2 = child_branch2_end[1] - child_branch2_root;
child2_direction = root2child1 + root2child2;//direction_2;
branch.child_branch_direction[0] = child1_direction;
branch.child_branch_direction[1] = child2_direction;
//For branch don't have a child branch; use vector from root to leaf node as direction;
if (child_branch1_root.x == -1 && child_branch1_root.y == -1 && child_branch1_root.z == -1)
{
branch.child_branch_direction[0] = branch.branch_edge_coord[0]
- getCoordxyz(branch.branch_nodes[branch.branch_nodes.size()-1]);
}
if (child_branch2_root.x == -1 && child_branch2_root.y == -1 && child_branch2_root.z == -1)
{
branch.child_branch_direction[1] = branch.branch_edge_coord[1]
- getCoordxyz(branch.branch_nodes[branch.branch_nodes.size() - 1]);
}
//cout << "D1 : " << branch.child_branch_direction[0] << endl;
//cout << "D2 : " << branch.child_branch_direction[1] << endl;
cout << "Got child branch directions." << endl;
//collect rest;
branch.branch_id = branch_id;
branch.branch_parent = parent_branch_id;
//cout << "Branch info : " << branch.branch_id<<" "<<branch.branch_parent<<" "<<branch.branch_end[0]<<"-"<<branch.branch_end[1] << endl;
//collect in vector;
branch_vector.push_back(branch);
}
}
return branch_vector;
}
//adjust the id of collected neuronSWC;
vector<NeuronSWC> adjust_branches(vector<Branch> branches)
{
/*Input : structured NeuronSWC, vector<Branch> <- Branch <- NeuronSWC;
*Return : a battery of index-adjusted NeuronSWC vector<NeuronSWC>;
*/
vector<NeuronSWC> ret_vec;
int index = 1;//global index;
int parent;//current branch's parent swc node e.g. one branch end node in parent branch;
Coordxyz parent_edge_coord;//current branch's start coord e.g. parent branch's edge coord;
auto getCoordxyz = [](const NeuronSWC node) { return Coordxyz(node.x, node.y, node.z); };//get coord from a NeuronSWC;
auto adjust_coord = [](NeuronSWC &node, const Coordxyz new_coord)
{node.x = new_coord.x, node.y = new_coord.y, node.z = new_coord.z; };//adjust NeuronSWC's coord with a Coordxyz;
for(int i = 0; i < branches.size();i++)
{
auto &branch = branches[i];
//cout << branch.branch_parent << endl;
//cout << branch.branch_id << endl;
if (branch.branch_id == -1) continue;//skip fake branch;
if (branch.branch_parent == -1)//first branch, don't have parent branch;
{
parent = -1;
parent_edge_coord = Coordxyz(0.0, 0.0, 0.0);
}
else
{
//current branch's parent branch;
auto &parent_branch = branches[branch.branch_parent];//the current branch's parent branch;
parent = parent_branch.branch_end[parent_branch.left_or_right];//the current branch's parent branch's end node index;
parent_edge_coord = parent_branch.branch_edge_coord[parent_branch.left_or_right];//the current branch's start coord, record in parent branch;
//parent_branch.left_or_right = (parent_branch.left_or_right) + 1;
}
//Adjust ids;
//the current branch's root
auto branch_root_node = branch.branch_nodes[branch.branch_nodes.size() - 1];//current branch's root node;
int parent_in_branch_old = branch_root_node.n;//the parent id in branch before adjust;
int parent_in_branch_new = index;//the parent id in branch after adjust;
//cout << branch_root_node.n << endl;
for (int i = (branch.branch_nodes.size() - 1); i >= 0; i--)//nodes in branch, stores in leaf->...->leaf_another->...->root;
{
auto &curr_node = branch.branch_nodes[i];
if (curr_node.n == branch.branch_end[0])
branch.branch_end[0] = index;
if (curr_node.n == branch.branch_end[1])
branch.branch_end[1] = index;
//cout << "Old:" << curr_node.n << ", Parent" << curr_node.parent <<endl;
curr_node.n = index;
if (curr_node.parent == parent_in_branch_old)
curr_node.parent = parent_in_branch_new;//if parent is branch_root, renew it to new index of branch_root;
else
curr_node.parent = parent;//else going down;
//cout << "New:" << curr_node.n << ", Parent" << curr_node.parent << endl;
parent = index++;
}
cout << "Index adjusted." << endl;
//cout << "Branch end point" << branch.branch_end[0] << "," << branch.branch_end[1] << endl;
if (branch.branch_parent == -1)//For first branch, don't need coords and direction adjust;
{
for each (auto node in branch.branch_nodes)
ret_vec.push_back(node);
continue;
}
//Adjust coords;
//a shifting vector;
Coordxyz shifting = getCoordxyz(branch_root_node) - parent_edge_coord;
for (int i = (branch.branch_nodes.size() - 1); i >= 0; i--)//nodes in branch, stores in leaf->...->leaf_another->...->root;
{
//cout << "Old coord:" <<getCoordxyz(branch.branch_nodes[i]) << endl;
auto new_coord = getCoordxyz(branch.branch_nodes[i]) - shifting;//coord to adjust;
adjust_coord(branch.branch_nodes[i], new_coord);//adjust it;
//cout << "New coord:" << getCoordxyz(branch.branch_nodes[i]) << endl;
}
//branch_edge coord adjust;
branch.branch_edge_coord[0] = branch.branch_edge_coord[0] - shifting;
branch.branch_edge_coord[1] = branch.branch_edge_coord[1] - shifting;
/*Update 2019-06-09*/
//Adjust branch direction;
branch_root_node = branch.branch_nodes[branch.branch_nodes.size() - 1];//get current branch's root node, adjusted;
auto coord_root = getCoordxyz(branch_root_node);//current bracnch's root coordinante;
//Get vector from root to children;
auto root2child1 = branch.branch_edge_coord[0] - coord_root;//A vector from root to child1;
auto root2child2 = branch.branch_edge_coord[1] - coord_root;//A vector from root to child1;
//uniformazition;
/*
root2child1 = root2child1 / root2child1.length();
root2child2 = root2child2 / root2child2.length();*/
//current branch's direction;
auto branch_direction = root2child1 + root2child2;//set a branch's direction as middle of two vectors;
//branch_direction = branch_direction / branch_direction.length();//uniformation;
cout << "Get branch direction." << endl;
//parent branch;
//cout << branch.branch_parent << endl;
auto &parent_branch = branches[branch.branch_parent];//the current branch's parent branch;
auto branch_direction_new = parent_branch.child_branch_direction[parent_branch.left_or_right];//current branch's target direction;
//branch_direction_new = branch_direction_new / branch_direction_new.length();//uniformation;
cout << "Get target branch direction." << endl;
/*Func : adjust_direction(direction, &parent_branch, &branch)*/
//projection to XOY;
auto branch_direction_p = branch_direction;
branch_direction_p.z = 0.0;
auto branch_direction_new_p = branch_direction_new;
branch_direction_new_p.z = 0.0;
const double PI = 3.1415926;
auto angle_of = [PI](const Coordxyz v1, const Coordxyz v2)->double { double angle = acos((v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / v1.length() / v2.length()) * 180 / PI; return angle; };
//cout << branch_direction_p << endl;
//cout << branch_direction_new_p << endl;
auto angle = angle_of(branch_direction_p, branch_direction_new_p);//the two vectors' angle;
if (branch_direction_p.cross_product(branch_direction_new_p).z < 0)//need anticlockwise rotate;
angle = 360-angle;
//cout << "angle : " << angle << endl;
auto angle_ = angle * PI / 180.0;//radian angle;
//cout << "angle_ : " << angle_ << endl;
auto sin_angle = sin(angle_);
auto cos_angle = cos(angle_);
//cout << sin_angle << " " << cos_angle << endl;
cout << "Rotate angle calculated." << endl;
//move branch root to O(0, 0, 0)
auto shiftting_from_o2root = coord_root - Coordxyz(0.0, 0.0, 0.0);//shiffting;
auto coord_after_rotate_theta_with_Z = [sin_angle, cos_angle](const Coordxyz coord)->Coordxyz
{
auto coord_x_rotated = (coord.x * cos_angle) - (coord.y * sin_angle);//rotate with Z-axis;
auto coord_y_rotated = (coord.x * sin_angle) + (coord.y * cos_angle);//rotate with Z-axis;
auto coord_z_rotated = coord.z;//rotate with Z-axis;
auto coord_after_rotate = Coordxyz(coord_x_rotated, coord_y_rotated, coord_z_rotated);
return coord_after_rotate;
};
for (int i =0; i < branch.branch_nodes.size(); i++)
{
//cout << "Before rotate : " << getCoordxyz(branch.branch_nodes[i]) << endl;
auto coord_after_shiftting = getCoordxyz(branch.branch_nodes[i]) - shiftting_from_o2root;//target position;
auto coord_after_rotate = coord_after_rotate_theta_with_Z(coord_after_shiftting);
//cout << "After rotate : " << coord_after_rotate << endl;
auto coord_target = coord_after_rotate + shiftting_from_o2root;
adjust_coord(branch.branch_nodes[i], coord_target);
}
cout << "Branch direction adjusted." << endl;
//adjust branch_edge_coord also;
auto new_edge_coord_0 = coord_after_rotate_theta_with_Z(branch.branch_edge_coord[0] - shiftting_from_o2root) + shiftting_from_o2root;
branch.branch_edge_coord[0] = new_edge_coord_0;
auto new_edge_coord_1 = coord_after_rotate_theta_with_Z(branch.branch_edge_coord[1] - shiftting_from_o2root) + shiftting_from_o2root;
branch.branch_edge_coord[1] = new_edge_coord_1;
//Adjust child_branch_direction also;
branch.child_branch_direction[0] = coord_after_rotate_theta_with_Z(branch.child_branch_direction[0]);
branch.child_branch_direction[1] = coord_after_rotate_theta_with_Z(branch.child_branch_direction[1]);
//cout << branch.child_branch_direction[0] << endl;
//cout << branch.child_branch_direction[1] << endl;
parent_branch.left_or_right = (parent_branch.left_or_right) + 1;//renew left_or_right flag;
//cout << "Edge coord:" << branch.branch_edge_coord[0] << endl;
//cout << "Edge coord:" << branch.branch_edge_coord[1] << endl;
cout << "Coordinate adjusted." << endl;
for each (auto node in branch.branch_nodes)
ret_vec.push_back(node);
}
cout << "Node adjusted." << endl;
return ret_vec;
}
//save a created neuron(as a vector of NeuronSWC);
void save_swc_file(const QString swc_file, const vector<NeuronSWC> neuron)
{
/*From a series of NeuronSWC save a swc file*/
FILE * fp = fopen(swc_file.toLatin1(), "wt");
fprintf(fp, "##n,type,x,y,z,radius,parent\n");
NeuronSWC * p_pt = 0;
for (int i = 0; i < neuron.size(); i++)
{
p_pt = (NeuronSWC *)(&(neuron.at(i)));
fprintf(fp, "%ld %d %5.3f %5.3f %5.3f %5.3f %ld\n",
p_pt->n, /*p_pt->type*/3, p_pt->x, p_pt->y, p_pt->z, p_pt->r, p_pt->pn);
}
cout << "Neuron saved." << endl;
fclose(fp);
}
//USELESS func : collect_nfss
//collect a nfss file:file_path:*.nfss -> fp:features.txt
void collect_nfss(const QString file_path, FILE * fp, int &sequence_total_count, const QString class_name)
{
fprintf(fp, qPrintable("#CLASS:" + class_name + "\n"));//start to collect one classs into file, marked by #CLASS;
QFile qf(file_path);
if (!qf.open(QIODevice::ReadOnly | QIODevice::Text))
{
v3d_msg(QString("open file [%1] failed!").arg(file_path));
}
while (!qf.atEnd())
{
char buf[1000];
qf.readLine(buf, sizeof(buf));
while (buf[0] == '#'&&buf[1] == 'V'&&buf[2] == 'A'&&buf[3] == 'L'&&buf[4] == 'U'&&buf[5] == 'E'&&buf[6] == 'S'&&buf[7] == ':')
{
QString feature_str = QString("%1").arg(buf + 9);//skip a blank;
fprintf(fp, qPrintable(feature_str));
qf.readLine(buf, sizeof(buf));
}
if (buf[0] == '#'&&buf[1] == 'L'&&buf[2] == 'E'&&buf[3] == 'A'&&buf[4] == 'F')
{
fprintf(fp, "\n"); sequence_total_count++;
}
continue;
}
} | true |
7507992714db25e306f627e171e5e09b4065f3ab | C++ | coord-e/icsservo | /src/bin/get_id.cpp | UTF-8 | 451 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "ics-servo/ics.h"
#include <iostream>
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "get_id <device> <en_pin>" << std::endl;
return 1;
}
const std::string device {argv[1]};
const std::uint8_t en_pin = static_cast<std::uint8_t>(strtol(argv[2], nullptr, 0));
auto sa = std::make_shared<ICSServo::IOProvider>(device, en_pin);
std::cout << static_cast<int>(sa->get_id()) << std::endl;
sa->close();
}
| true |
246c4405e08bb977e75896f3ad8775c59400de71 | C++ | NewieVentures/Obelisk | /src/app/colour.h | UTF-8 | 444 | 2.625 | 3 | [
"MIT"
] | permissive | #ifndef OBELISK_COLOUR_H
#define OBELISK_COLOUR_H
#include "Particle.h"
class Colour {
uint8_t mRed, mGreen, mBlue;
bool mIsValid;
public:
Colour(uint8_t, uint8_t, uint8_t);
Colour(String);
uint8_t getRed() const;
uint8_t getGreen() const;
uint8_t getBlue() const;
bool isValid();
String toString();
};
bool operator==(const Colour& lhs, const Colour& rhs);
bool operator!=(const Colour& lhs, const Colour& rhs);
#endif
| true |
6b1946c91b47ef2fb57df916d6e06e30e6b6d879 | C++ | JBamberger/oberon0-compiler | /ast/include/Identifier.h | UTF-8 | 1,164 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2020 Jannik Bamberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <ostream>
#include <string>
#include <utility>
struct Identifier {
std::string name;
FilePos pos;
Identifier(std::string name, FilePos pos) : name(std::move(name)), pos(std::move(pos))
{
}
friend std::ostream& operator<<(std::ostream& os, const Identifier& obj)
{
return os << "Identifier(" << obj.name << ", " << obj.pos << ")";
}
friend std::string operator+(const std::string& lhs, const Identifier& rhs)
{
std::stringstream s;
s << lhs << rhs;
return s.str();
}
};
| true |
d56cd961f1625873e8481e6731ec0d33b446a76f | C++ | gveenblade/testrepo | /CodeForces-103A.cpp | UTF-8 | 245 | 2.625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
long long int n,sum=0;
cin>>n;
for(int i=1;i<=n;i++)
{
long long int t;
cin>>t;
if(t>1) sum+=i*(t-1)+1;
else sum+=t;
}
cout<<sum;
return 0;
} | true |
8256b7b880d88c3072d5d6ac5fcc4a63fd6f47b6 | C++ | DonRumata710/NetCowork | /Generator/function.h | UTF-8 | 481 | 2.625 | 3 | [
"MIT"
] | permissive | #ifndef FUNCTION_H
#define FUNCTION_H
#include "types.h"
#include "codeelement.h"
#include "parameter.h"
#include <vector>
class Function : public CodeElement
{
public:
explicit Function(const std::string& name);
void add_param(const Parameter& type);
const Parameter* get_param(size_t i) const;
size_t get_params_count() const;
const std::vector<Parameter>& get_parameters() const;
private:
std::vector<Parameter> params;
};
#endif // FUNCTION_H
| true |
f3701745118ec58178e6b152f3761a8527724317 | C++ | fms13/fauxpar | /fauxpar/Setting.h | UTF-8 | 585 | 2.984375 | 3 | [
"BSD-2-Clause"
] | permissive | /**
* \file FSetting.h
*
* \date Dec 22, 2015
* \author Frank M. Schubert
* \copyright BSD License
*/
#ifndef SETTING_H_
#define SETTING_H_
#include <memory>
#include <string>
#include <iostream>
namespace FauxPar {
class Setting {
public:
typedef std::shared_ptr<Setting> ptr;
Setting(std::string _name);
virtual ~Setting();
std::string get_name() const {
return name;
}
friend std::ostream& operator<<(std::ostream& os, const Setting& setting);
protected:
virtual std::string print() const = 0;
std::string name;
};
} /* namespace FauxPar */
#endif /* SETTING_H_ */
| true |
a90f10252fe26d74785bc10dc0eb29fca22f3e67 | C++ | dkim828/MyGameEngine | /Game/w14 Engine/AlarmGlobals.h | UTF-8 | 433 | 2.75 | 3 | [] | no_license | #ifndef ALARMGLOBALS_H
#define ALARMGLOBALS_H
/**
\ingroup ALARM
<summary> Each of these flags are associated with which Alarm the user may want to interact
with through Alarmable::setAlarm(), Alarmable::cancelAlarm(), Alarmable::getTimeLeftOnAlarm(),
or Alarmable::addTimeToAlarm().
</summary>
*/
namespace Alarm
{
enum ID
{
ID_0 = 0,
ID_1 = 1,
ID_2 = 2
};
const int MAX_ALARM_EVENTS = 3;
};
#endif //ALARMGLOBALS_H | true |
c543d213468fea7143881592ae9d90160d3b5a3d | C++ | JJungwoo/algorithm | /baekjoon/math1/11050.cpp | UTF-8 | 451 | 2.53125 | 3 | [] | no_license | /*
[boj] 11050. 이항 계수1
https://www.acmicpc.net/problem/11050
*/
#include <iostream>
#define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
typedef long long ll;
int n, k;
ll factorial(int start, int reply){
ll res = 1;
for(int i=start;i>start-reply;i--){
res *= i;
}
return res;
}
int main()
{
io;
cin>>n>>k;
cout<<(factorial(n, k)/factorial(k, k))<<"\n";
return 0;
}
| true |
8b65d80d07f10e75256e1544cceb2be7a420c742 | C++ | OKullmann/oklibrary | /Experimentation/Investigations/RamseyTheory/GreenTaoProblems/plans/CountingProgressions.hpp | UTF-8 | 18,526 | 2.90625 | 3 | [] | no_license | // Oliver Kullmann, 10.5.2010 (Swansea)
/* Copyright 2010 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation and included in this library; either version 3 of the
License, or any later version. */
/*!
\file Experimentation/Investigations/RamseyTheory/GreenTaoProblems/plans/CountingProgressions.hpp
\brief On counting arithmetic progressions in the primes
\todo Connections
<ul>
<li> See
Structures/NumberTheory/PrimeNumbers/plans/GrosswaldHagisFormula.hpp. </li>
<li> See
ComputerAlgebra/RamseyTheory/Lisp/GreenTao/plans/Asymptotics.hpp. </li>
</ul>
\todo The distribution of arithmetic progressions amongst primes
<ul>
<li> The task is to find a nice (thus very likely approximated) law for
the values in the list ln_arithprog_primes_c(k,n) (see
ComputerAlgebra/NumberTheory/Lisp/PrimeNumbers.mac) for fixed k >= 1. </li>
<li> One can consider the densities
ln_arithprog_primes_c(k,n) / create_list(i,i,1,n). </li>
<li> Hard to believe that there is nothing in the literature / on the
Internet: We should enter for example ln_arithprog_primes_c(3,30) =
[0,0,0,1,2,2,3,5,7,9,11,11,13,16,17,20,23,24,26,30,32,36,40,44,46,49,53,56,59,64]
into that database of integer sequences and see whether there is information
in it. </li>
<li> Yes, this sequence is A125505 in
http://www.research.att.com/~njas/sequences/Seis.html (see
http://www.research.att.com/~njas/sequences/A125505). </li>
<li> There it is only listed for n=64; this we can easily extend, and
perhaps we should do so. </li>
<li> And apparently for k >= 4 there is nothing entered there --- we
should change this.
<ol>
<li> Say, up to k=10. </li>
<li> For k=10 for example the first 315 values are 0, and then
at least until index 3000 the value is constant 1; for such sequences
we need a compressed representation. </li>
</ol>
</li>
<li> The best internet resource seems to be
http://primes.utm.edu/top20/page.php?id=14 . </li>
<li> Ploted via %e.g.
\verbatim
plot2d([discrete,create_list(i,i,1,1000),ln_arithprog_primes_c(3,1000)]);
\endverbatim
</li>
<li> For k = 1,2 this is trivial. </li>
<li> For k >= 3 regression is to be performed; most powerful is using R,
but for initial considerations also simple_linear_regression (use
'load("stats")') can be used. </li>
</ul>
\todo The Grosswald-Hagis-formula
<ul>
<li> In [Grosswald, Hagis, 1979, Arithmetic progressions consisting only of
primes, Mathematics of Computation, 33(148):1343-1352] the Hardy-Littlewood
estimations have been specialised for arithmetic progressions. </li>
<li> The conjecture is that nhyp_arithprog_primes_hg(k,n) is asymptotically
equal to C_k / (2*(k-1)) * n^2 / (log n)^(k-2). This is proven for k <= 4.
</li>
<li> This estimations is gh_nhyp_arithprog_primes_hg(k,n). </li>
<li> As stated in "Improving the Grosswald-Hagis estimation" in
ComputerAlgebra/RamseyTheory/Lisp/GreenTao/plans/Asymptotics.hpp, one would
expect that using logarithmic integrals should yield a more precise formula.
</li>
</ul>
\todo Computing the Grosswald-Hagis coefficients C_k
<ul>
<li> We have C_2 = 1. </li>
<li> The following data has been computed by
\verbatim
> GrosswaldHagisFormula-O3-DNDEBUG 3,20 1000000000
Precision in bits: 416
The first prime number not taken into account: 1000000007
> GrosswaldHagisFormula-O3-DNDEBUG 11,20 4000000000
Precision in bits: 416
The first prime number not taken into account: 4000000007
> GrosswaldHagisFormula-O3-DNDEBUG 3,20 100000000000
Precision in bits: 448
The first prime number not taken into account: 100000000003
\endverbatim
</li>
<li> Computation of C_3:
\verbatim
C_3 = 1.3203236317546366339
Finite and infinite part: 1.5, 0.88021575450309108924
1 - first remaining factor: 9.99999988000000108e-19
C_3 = 1.3203236316942413054
Finite and infinite part: 1.5, 0.88021575446282753695
1 - first remaining factor: 9.9999999996e-23
\endverbatim
while GH give the value 1.32032; a guess is C_3 = 1.320323631... . </li>
<li> Computation of C_4:
\verbatim
C_4 = 2.8582485961147147258
Finite and infinite part: 4.5, 0.63516635469215882796
1 - first remaining factor: 2.999999966000000288e-18
C_4 = 2.8582485957224816583
Finite and infinite part: 4.5, 0.63516635460499592406
1 - first remaining factor: 2.9999999999e-22
\endverbatim
while GH give the value 2.85825; let's guess C_4 = 2.85824859... . </li>
<li> Computation of C_5:
\verbatim
C_5 = 4.1511808643862090045
Finite and infinite part: 6.591796875, 0.62974951187133007712
1 - first remaining factor: 5.999999936000000507e-18
C_5 = 4.1511808632468886479
Finite and infinite part: 6.591796875, 0.62974951169849095933
1 - first remaining factor: 5.99999999984e-22
\endverbatim
while GH give the value 4.15118; let's guess C_5 = 4.15118086... . </li>
<li> Computation of C_6:
\verbatim
C_6 = 10.131794954669182916
Finite and infinite part: 24.71923828125, 0.40987488527728368616
1 - first remaining factor: 9.999999900000000735e-18
C_6 = 10.131794950034614014
Finite and infinite part: 24.71923828125, 0.40987488508979534818
1 - first remaining factor: 9.9999999998e-22
\endverbatim
while GH give the value 10.1318; let's guess C_6 = 10.1317949... . </li>
<li> Computation of C_7:
\verbatim
C_7 = 17.298612323552886198
Finite and infinite part: 33.392508824666341146, 0.51803871384394953143
1 - first remaining factor: 1.4999999860000000945e-17
C_7 = 17.298612311683576106
Finite and infinite part: 33.392508824666341146, 0.5180387134885012435
1 - first remaining factor: 1.49999999998e-21
\endverbatim
while GH give the value 17.2986; let's guess C_7 = 17.2986123... . </li>
<li> Computation of C_8:
\verbatim
C_8 = 53.971948352406135059
Finite and infinite part: 146.09222610791524251, 0.36943751074433075237
1 - first remaining factor: 2.0999999818000001113e-17
C_8 = 53.971948300560721615
Finite and infinite part: 146.09222610791524251, 0.36943751038944935433
1 - first remaining factor: 2.099999999986e-21
\endverbatim
while GH give the value 53.9720; let's guess C_8 = 53.9719483... . </li>
<li> Computation of C_9:
\verbatim
C_9 = 148.55162885563210856
Finite and infinite part: 639.15348922212918599, 0.23241933488687408369
1 - first remaining factor: 2.7999999776000001218e-17
C_9 = 148.55162866536732961
Finite and infinite part: 639.15348922212918599, 0.23241933458919163
1 - first remaining factor: 2.8e-21
\endverbatim
while GH give the value 148.552; let's guess C_9 = 148.551628... . </li>
<li> Computation of C_10:
\verbatim
C_10 = 336.034327307194497
Finite and infinite part: 2796.2965153468151887, 0.12017120697427801113
1 - first remaining factor: 3.5999999736000001242e-17
C_10 = 336.03432675383279702
Finite and infinite part: 2796.2965153468151887, 0.12017120677638708757
1 - first remaining factor: 3.600000000024e-21
\endverbatim
while GH give the value 336.034; let's guess C_10 = 336.034326... . </li>
<li> Computation of C_11:
\verbatim
C_11 = 511.42228312047417728
C_11 = 511.42228230839231811
Finite and the infinite part: 2884.6653988745989106, 0.17728998396414178893
1 - first remaining factor: 2.8124999953125000046e-18
C_11 = 511.42228206774875224
Finite and infinite part: 2884.6653988745989106, 0.17728998388072013248
1 - first remaining factor: 4.50000000006e-21
\endverbatim
while GH give the value 511.422; let's guess C_11 = 511.422282... . </li>
<li> Computation of C_12:
\verbatim
C_12 = 1312.3197146277008806
Finite and infinite part: 13882.452232084007257, 0.094530828753350440844
1 - first remaining factor: 5.499999967000000099e-17
C_12 = 1312.3197120808120353
Finite and the infinite part: 13882.452232084007257, 0.094530828569889420933
1 - first remaining factor: 3.4374999948437500039e-18
C_12 = 1312.3197113260945073
Finite and infinite part: 13882.452232084007257, 0.094530828515524564108
1 - first remaining factor: 5.50000000011e-21
\endverbatim
while GH give the value 1312.32; let's guess C_12 = 1312.31971... . </li>
<li> Computation of C_13:
\verbatim
C_13 = 2364.598970504069348
Finite and infinite part: 13428.850937459748114, 0.17608349228957677085
1 - first remaining factor: 6.5999999648000000693e-17
C_13 = 2364.5989649971453789
Finite and the infinite part: 13428.850937459748114, 0.17608349187949522368
1 - first remaining factor: 4.1249999945000000027e-18
C_13 = 2364.5989633652830187
Finite and infinite part: 13428.850937459748114, 0.17608349175797608791
1 - first remaining factor: 6.600000000176e-21
\endverbatim
while GH give the value 2364.60; let's guess C_13 = 2364.59896... . </li>
<li> Computation of C_14:
\verbatim
C_14 = 7820.6000583800047652
Finite and infinite part: 70011.873897902124282, 0.11170390996511158496
1 - first remaining factor: 7.7999999636000000273e-17
C_14 = 7820.6000368550459882
Finite and the infinite part: 70011.873897902124282, 0.11170390965766432525
1 - first remaining factor: 4.8749999943125000011e-18
C_14 = 7820.6000304765722324
Finite and infinite part: 70011.873897902124282, 0.11170390956655872557
1 - first remaining factor: 7.80000000026e-21
\endverbatim
while GH give the value 7820.61; let's guess C_14 = 7820.60003... .
So here we have a descrepancy. </li>
<li> Computation of C_15:
\verbatim
C_15 = 22938.908728604769022
Finite and infinite part: 365009.82172812513753, 0.062844634207379343627
1 - first remaining factor: 9.0999999635999999727e-17
C_15 = 22938.908654946451496
Finite and the infinite part: 365009.82172812513753, 0.062844634005581164122
1 - first remaining factor: 5.6874999943124999989e-18
C_15 = 22938.908633119341404
Finite and infinite part: 365009.82172812513753, 0.062844633945782471615
1 - first remaining factor: 9.100000000364e-21
\endverbatim
while GH give the value 22939; let's guess C_15 = 22938.9086... . </li>
<li> Computation of C_16:
\verbatim
C_16 = 55651.462823015330355
Finite and infinite part: 1902993.9143221524098, 0.029244162266718764193
1 - first remaining factor: 1.0499999964999999906e-16
C_16 = 55651.4626168225131
Finite and the infinite part: 1902993.9143221524098, 0.029244162158366963537
1 - first remaining factor: 6.5624999945312499963e-18
C_16 = 55651.462555721561157
Finite and infinite part: 1902993.9143221524098, 0.029244162126259161466
1 - first remaining factor: 1.050000000049e-20
\endverbatim
while GH give the value 55651; let's guess C_16 = 55651.462... . </li>
<li> Computation of C_17:
\verbatim
C_17 = 91555.111732881423894
Finite and infinite part: 1539516.4947250383578, 0.059470042735224739834
1 - first remaining factor: 1.1999999967999999826e-16
C_17 = 91555.111345203124141
Finite and the infinite part: 1539516.4947250383578, 0.059470042483406522178
1 - first remaining factor: 7.4999999949999999932e-18
C_17 = 91555.111230322724999
Finite and infinite part: 1539516.4947250383578, 0.059470042408785432027
1 - first remaining factor: 1.200000000064e-20
\endverbatim
while GH give the value 91555; let's guess C_17 = 91555.111.... </li>
<li> Computation of C_18:
\verbatim
C_18 = 256474.86146297656364
Finite and infinite part: 8527979.2287552010855, 0.030074517606489678389
1 - first remaining factor: 1.3599999972799999735e-16
C_18 = 256474.86023216558505
Finite and the infinite part: 8527979.2287552010855, 0.030074517462163461642
1 - first remaining factor: 8.4999999957499999896e-18
C_18 = 256474.85986744035674
Finite and infinite part: 8527979.2287552010855, 0.030074517419395389801
1 - first remaining factor: 1.3600000000816e-20
\endverbatim
while GH give the value 256480; let's guess C_18 = 256474.85... .
So here we have a descrepancy. </li>
<li> Computation of C_19:
\verbatim
C_19 = 510992.01391519899563
Finite and infinite part: 6579820.4950027289514, 0.077660479385917816586
1 - first remaining factor: 1.5299999979599999633e-16
C_19 = 510992.01115644361769
Finite and the infinite part: 6579820.4950027289514, 0.077660478966642643345
1 - first remaining factor: 9.5624999968124999857e-18
C_19 = 510992.01033894385383
Finite and infinite part: 6579820.4950027289514, 0.07766047884239916824
1 - first remaining factor: 1.530000000102e-20
\endverbatim
while GH give the value 510990; let's guess C_19 = 510992.01... . </li>
<li> Computation of C_20:
\verbatim
C_20 = 1900972.5998672649484
Finite and infinite part: 38473077.653099090942, 0.049410463519653916442
1 - first remaining factor: 1.7099999988599999521e-16
C_20 = 1900972.5883968371188
Finite and the infinite part: 38473077.653099090942, 0.049410463221512241035
1 - first remaining factor: 1.0687499998218749981e-17
C_20 = 1900972.5849978144616
Finite and infinite part: 38473077.653099090942, 0.04941046313316415805
1 - first remaining factor: 1.7100000001254e-20
\endverbatim
while GH give the value 1901000; let's guess C_20 = 1900972.5... . </li>
</ul>
\todo Using curve-fitting
<ul>
<li> The role model for curve-fitting is implemented by "fit_greentao"
in OKlib/Statistics/R/GreenTao.R. </li>
<li> One can also consider n_arithprog_primes_nc[k,n] (the non-cumulative
data, i.e., as list the difference list of the above list):
\verbatim
plot2d([discrete,create_list(i,i,1,1000),create_list(n_arithprog_primes_nc[3,n],n,1,1000)]);
\endverbatim
Though it seems that the accumulated data is easier to handle (since being
smoother). </li>
<li> Perhaps it is more appropriate to consider only changes here, that
is, skipping n-values where no new arithmetic progression is added).
This is plotted in non-cumulative resp. cumulative form by
\verbatim
plot2d([discrete, sizes_strata_indmon_ohg(arithprog_primes_ohg(3,1000))]);
plot2d([discrete, sizes_cstrata_indmon_ohg(arithprog_primes_ohg(3,1000))]);
\endverbatim
</li>
<li> At the C++-level we have
Applications/RamseyTheory/CountProgressions_GreenTao.cpp. </li>
</ul>
\todo k=3
<ul>
<li> Using Applications/RamseyTheory/CountProgressions_GreenTao.cpp
and linear regression in R:
\verbatim
> f = fit_greentao(3,1000)
Number of observations (changes) = 995
Max nhyp = 40510
Coefficients: 17.11290 -2.962008 21.49815 -57.41431 ; 0.3300809
Residual range: -37.03781 45.99563
> f(100)
578.0767
> f = fit_greentao(3,10000)
Number of observations (changes) = 9995
Max nhyp = 3091531
Coefficients: 321.6195 -3.338598 30.12935 -101.7892 ; 0.3300809
Residual range: -715.0495 930.5577
f(100)
790.0139
\endverbatim
(where the correct value for f(100) is 579). </li>
<li> So f_3(n) = 321.6195 + 0.3300809*n^2/log(n) * (1 +
-3.338598/log(n) + 30.12935/log(n)^2 - 101.7892/log(n)^3) is a good model.
</li>
<li> For N=30000 we obtain:
\verbatim
> f = fit_greentao(3,30000)
Number of observations (changes) = 29995
Max nhyp = 25000740
Coefficients: 843.0986 -3.324593 30.58643 -107.2370 ; 0.3300809
Residual range: -3259.890 3230.183
f(100)
1289.139
\endverbatim
So f_3(n) = 843.0986 + 0.3300809*n^2/log(n) * (1 +
-3.324593/log(n) + 30.58643/log(n)^2 - 107.2370/log(n)^3) is a good model.
</li>
<li> For N=100000 we need a C++ program which doesn't store the
progressions. </li>
</ul>
\todo k=4
<ul>
<li>
\verbatim
TO BE UPDATED:
> f = fit_greentao(4,20000)
Number of observations (changes) = 19975
Max nhyp = 1462656
Coefficients: 165.4101 0.3400277 0.684767 -4.955831
Residual range: -499.0341 410.999
> f = fit_greentao(4,40000)
Number of observations (changes) = 39975
Max nhyp = 5148933
Coefficients: -549.0156 0.4599897 -1.662170 6.5372
Residual range: -1115.498 923.5618
\endverbatim
</li>
</ul>
\todo k=5
<ul>
<li>
\verbatim
TO BE UPDATED:
> f = fit_greentao(5,40000)
Number of observations (changes) = 39347
Max nhyp = 462282
Coefficients: -219.7298 0.5031083 -2.683063 10.54289
Residual range: -230.2833 290.1797
> f = fit_greentao(5,80000)
Number of observations (changes) = 79347
Max nhyp = 1545857
Coefficients: -84.72713 0.4143196 -0.8405665 0.9811276
Residual range: -448.2709 539.9275
\endverbatim
</li>
</ul>
\todo k=6
<ul>
<li>
\verbatim
TO BE UPDATED:
> f = fit_greentao(6,80000)
Number of observations (changes) = 70976
Max nhyp = 234774
Coefficients: -113.8172 0.8496358 -4.188096 14.99478
Residual range: -168.2007 163.1515
80000 - 70976
9024
> f = fit_greentao(6,160000)
Number of observations (changes) = 150810
Max nhyp = 749499
Coefficients: -102.2112 0.7783336 -2.665443 6.869895
Residual range: -322.2387 365.8506
160000 - 150810
9190
\endverbatim
</li>
</ul>
\todo k=7
<ul>
<li>
\verbatim
TO BE UPDATED:
> f = fit_greentao(7,160000)
Number of observations (changes) = 59909
Max nhyp = 78058
Coefficients: -3.696913 0.8696752 -0.3139054 -13.02317
Residual range: -159.1105 169.4958
160000 - 59909
100091
> f = fit_greentao(7,500000)
Number of observations (changes) = 298388
Max nhyp = 497046
Coefficients: 703.3813 -0.3935023 32.41404 -224.6832
Residual range: -681.7677 457.4785
500000 - 298388
201612
> f = fit_greentao(7,1000000)
Number of observations (changes) = 736449
Max nhyp = 1558942
Coefficients: -1097.584 1.736234 -23.11872 137.8766
Residual range: -529.4176 1079.641
1000000 - 736449
263551
\endverbatim
</li>
</ul>
\todo k=8
<ul>
<li>
\verbatim
TO BE UPDATED:
> f = fit_greentao(8,1000000)
Number of observations (changes) = 230866
Max nhyp = 268082
Coefficients: -170.0498 2.566231 -13.61017 54.1059
Residual range: -189.4731 201.5056
1000000 - 230866
769134
> f = fit_greentao(8,2000000)
Number of observations (changes) = 649644
Max nhyp = 812685
Coefficients: 186.8815 3.010198 -22.80165 96.40528
Residual range: -882.6667 537.2372
2000000 - 649644
1350356
> f = fit_greentao(8,4000000)
TO BE UPDATED:
Number of observations (changes) = 1781803
Max nhyp = 2491439
Coefficients: -675.2275 6.202912 -31.85938 883.982
Residual range: -863.7256 977.2554
4000000 - 1781803
2218197
> f = fit_greentao(8,8000000)
TO BE UPDATED:
Number of observations (changes) = 4688545
Max nhyp = 7728990
Non-linear model nhyp = a * n^b:
a b
4.218958e-05 1.631506e+00
Residual range: -10123.48 6262.802
8000000 - 4688545
3311455
\endverbatim
</li>
</ul>
*/
| true |
7077e45a12a0348fb7fe6f3fb2e6f25de16e0d23 | C++ | dandugula/leetcode_random | /find_replace_pattern.cpp | UTF-8 | 924 | 2.84375 | 3 | [] | no_license | class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
std::vector<string> res;
std::for_each(words.begin(), words.end(),
[&res, &pattern](auto& aWord) {
std::vector<int> letterMap(26, -1);
std::vector<bool> letterRec(26, false);
int i = 0;
bool match = true;
std::for_each(pattern.begin(), pattern.end(),
[&aWord, &letterMap, &letterRec, &i, &match] (auto& aLetter) {
if(letterMap.at(aLetter - 'a') == -1 && !letterRec.at(aWord[i] - 'a')) {
letterMap[aLetter - 'a'] = aWord[i];
letterRec[aWord[i] - 'a'] = true;
}else if(letterMap.at(aLetter - 'a') != aWord[i]) {
match = false;
return;
}
++i;
});
if(match)
res.push_back(aWord);
});
return res;
}
};
| true |
40d298d579d0ea9b42520c6451c3c426d2668d33 | C++ | justinctlam/MarbleStrike | /game/code/common/engine/system/stringutilities.cpp | UTF-8 | 3,368 | 2.703125 | 3 | [
"MIT"
] | permissive | //////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////
#include "common/engine/system/assert.hpp"
#include "common/engine/system/stringutilities.hpp"
#include <stdlib.h>
#include <string.h>
//////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
//////////////////////////////////////////////////////
namespace System
{
//===========================================================================
void StringCopy( char* dst, int dstSize, const char* src )
{
int lengthSrc = static_cast<int>( strlen( src ) );
UNUSED_ALWAYS( lengthSrc );
Assert( dstSize >= lengthSrc + 1, "" );
#if defined ( PLAT_PC ) || defined ( PLAT_WINDOWS_PHONE ) || defined( PLAT_WINDOWS_8 )
strcpy_s( dst, dstSize, src );
#else
strcpy( dst, src );
#endif
}
//===========================================================================
void StringNCopy( char* dst, int dstSize, const char* src, int numToCopy )
{
Assert( dstSize >= numToCopy, "" );
#if defined ( PLAT_PC ) || defined ( PLAT_WINDOWS_PHONE ) || defined( PLAT_WINDOWS_8 )
strncpy_s( dst, dstSize, src, numToCopy );
#else
strncpy( dst, src, numToCopy );
#endif
}
//===========================================================================
void StringConcat( char* dst, int dstSize, const char* src )
{
int lengthDst = static_cast<int>( strlen( dst ) ) ;
int lengthSrc = static_cast<int>( strlen( src) ) ;
int totalLength = lengthDst + lengthSrc + 1;
UNUSED_ALWAYS( totalLength );
Assert( totalLength <= dstSize, "" );
#if defined ( PLAT_PC ) || defined ( PLAT_WINDOWS_PHONE ) || defined( PLAT_WINDOWS_8 )
strcat_s( dst, dstSize, src );
#else
strcat( dst, src );
#endif
}
//===========================================================================
char* StringToken( char* str, const char* delim, char** nextToken )
{
#if defined ( PLAT_PC ) || defined ( PLAT_WINDOWS_PHONE ) || defined( PLAT_WINDOWS_8 )
return strtok_s( str, delim, nextToken );
#else
return strtok( str, delim );
#endif
}
//===========================================================================
int StringICmp( const char* str1, const char* str2 )
{
#if defined ( PLAT_PC ) || defined ( PLAT_XBOX360 ) || defined ( PLAT_WINDOWS_PHONE ) || defined( PLAT_WINDOWS_8 )
return _stricmp( str1, str2 );
#endif
#if defined( PLAT_PS3 ) || defined( PLAT_IOS ) || defined( PLAT_ANDROID )
return strcasecmp( str1, str2 );
#endif
}
//===========================================================================
int StringHash( const char* str )
{
int hash = 5381;
int c = *str++;
while ( c )
{
hash = ( ( hash << 5 ) + hash ) + c; /* hash * 33 + c */
c = *str++;
}
return hash;
}
//===========================================================================
void ConvertToWChar( const char* input, wchar_t* output, size_t outputSize )
{
const size_t inputSize = strlen( input ) + 1;
int lengthSrc = static_cast<int>( strlen( input ) ) ;
UNUSED_ALWAYS( lengthSrc );
Assert( outputSize > inputSize, "" );
#if defined PLAT_IOS || defined PLAT_ANDROID
UNUSED_ALWAYS( outputSize );
mbstowcs( output, input, inputSize );
#else
size_t returnChar = 0;
mbstowcs_s( &returnChar, output, outputSize, input, inputSize );
#endif
}
}
| true |
6f2c4a8b82761c196f79214cf91764dc0bbfe010 | C++ | UmmeHabiba-7119/Computer-Graphics | /Three/main.cpp | UTF-8 | 1,279 | 2.65625 | 3 | [] | no_license | #include<windows.h>
#ifdef __APPLE__
//#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
float x_position = -10.0;
int state = 1;
void init(){
glClearColor(0.0f,0.0f,0.0f,1.0f);
glOrtho(-10,10,-10,10,3,-3);
}
void display(){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f,1.0f,0.0f);
glBegin(GL_QUADS);
glVertex2f(x_position+2.0,1.0);
glVertex2f(x_position+2.0,-1.0);
glVertex2f(x_position,-1.0);
glVertex2f(x_position,1.0);
glEnd();
glFlush();
}
void timer(int){
glutPostRedisplay();
glutTimerFunc(1000/60,timer,0);
switch(state)
{
case 1:
if(x_position<8){
x_position += 0.1;
}
else{
state = -1;
}
break;
case -1:
if(x_position > -10){
x_position -= 0.1;
}
else{
state = 1;
}
break;
}
}
int main(){
glutInitDisplayMode(GLUT_RGB);
glutInitWindowPosition(200,100);
glutInitWindowSize(600,600);
glutCreateWindow("Window 1");
glutDisplayFunc(display);
glutTimerFunc(0,timer,0);
init();
glutMainLoop();
return 0;
}
| true |
2b006546ecec975f40664481bf2ab4100507166d | C++ | eunbin62/rep | /practice01/quiz.cpp | UTF-8 | 697 | 3.03125 | 3 | [] | no_license | # include <iostream>
#include <stdlib.h>
int main(int argc, const char * argv){
char buff[1000];
std::cout<<"Enter the expression. " << std::endl;
std::cin.getline(buff, 1000);
int i;
int j;
char k;
std::cout << i << k << j << std::endl;
std::cout<<buff[0]<<"k"<<buff[1] <<std::endl;
//char opr =;
switch(k){
case '+':
std::cout << i+j;
break;
case '-':
std::cout << i-j;
break;
case '*'';
std::cout << i *j;
break;
case '/':
std::cout << (double) i/j ;
break;
}
return 0;
} | true |
83f20037ede2970d9e0e80b03387cbf0ab38aabc | C++ | MuhammadSherifW/Competitive-Programming | /Graphs/Dijkstra/Dijkstra-K-Shortest-Path.cpp | UTF-8 | 1,311 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
#include <string>
#include <queue>
#include <ctime>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <algorithm>
#include <bitset>
#include <cstdint>
#include <climits>
using namespace std;
class Edge
{
public:
int to;
long long w;
Edge(int to, long long w)
{
this->to = to;
this->w = w;
}
bool operator < (const Edge& e) const
{
return w > e.w;
}
};
const int nodesSize = 100000 + 9;
int n, m, k;
vector<vector<Edge>> adjList(nodesSize);
priority_queue<Edge> q;
vector<vector<long long>> dis(nodesSize, vector<long long >(10, LLONG_MAX));
vector<int> timesVisited(nodesSize);
void Dijkstra(int start)
{
q.push(Edge(start, 0));
while (!q.empty())
{
Edge minEdge = q.top();
q.pop();
if (timesVisited[minEdge.to] == k)
{
continue;
}
timesVisited[minEdge.to]++;
dis[minEdge.to][timesVisited[minEdge.to]] = minEdge.w;
for (int i = 0; i < (int)adjList[minEdge.to].size(); i++)
{
Edge edgeToRelx = adjList[minEdge.to][i];
q.push(Edge(edgeToRelx.to, edgeToRelx.w + minEdge.w));
}
}
}
// Problems to Solve
// UVA 10740
// SPOJ ROADS
| true |
21ab9fb349b32ba7028fe56a8e6f4d02b70c6f12 | C++ | aha4765/leetcode | /dynamic-programming/064.cpp | UTF-8 | 790 | 2.859375 | 3 | [] | no_license | class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int nrow = grid.size();
int ncol = grid[0].size();
if ((nrow == 0) || (ncol == 0)) return 1;
vector<vector<int> > table(nrow, vector<int>(ncol, 0));
table[0][0] = grid[0][0];
for (int i = 1; i < ncol; ++i) {
table[0][i] = table[0][i-1] + grid[0][i];
}
for (int i = 1; i < nrow; ++i) {
table[i][0] = table[i-1][0] + grid[i][0];
}
for (int i = 1; i < nrow; ++i) {
for (int j = 1; j < ncol; ++j) {
table[i][j] = (table[i-1][j] < table[i][j-1] ? table[i-1][j] : table[i][j-1]) + grid[i][j];
}
}
return table[nrow-1][ncol-1];
}
};
| true |
e4cfbc85965c5634ebe9ef2cd757e30d62313e0d | C++ | cesarus777/mipt-mips | /simulator/infra/cache/t/unit_test.cpp | UTF-8 | 4,284 | 2.515625 | 3 | [
"MIT"
] | permissive | /**
* Tests for CacheTagArray
* @author Oleg Ladin, Denis Los
*/
#include <catch.hpp>
// Module
#include "../cache_tag_array.h"
#include <infra/replacement/cache_replacement.h>
#include <infra/types.h>
#include <fstream>
#include <map>
#include <vector>
static const uint32 LINE_SIZE = 4; // why not 32?
static const uint32 cache_size = 4;
static const uint32 cache_ways = 4;
static const uint32 cache_line_size = 1;
static const uint32 addr_size_in_bits = 32;
TEST_CASE( "pass_wrong_arguments: Pass_Wrong_Arguments_To_CacheTagArraySizeCheck")
{
// size_in_bytes = 128
// ways = 0
// line_size = 4
// addr_size_in_bits = 32
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 128, 0, 4, 32), CacheTagArrayInvalidSizeException);
// size_in_bytes = 0
// ways = 16
// line_size = 4
// addr_size_in_bits = 32
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 0, 16, 4, 32), CacheTagArrayInvalidSizeException);
// size_in_bytes = 128
// ways = 16
// line_size = 0
// addr_size_in_bits = 32
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 128, 16, 0, 32), CacheTagArrayInvalidSizeException);
// size_in_bytes = 128
// ways = 16
// line_size = 4
// addr_size_in_bits = 0
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 128, 16, 4, 0), CacheTagArrayInvalidSizeException);
// size_in_bytes = 0
// ways = 0
// line_size = 0
// addr_size_in_bits = 0
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 0, 0, 0, 0), CacheTagArrayInvalidSizeException);
// size_in_bytes is power of 2,
// but the number of ways is not
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 64, 9, 4, 32), CacheTagArrayInvalidSizeException);
// the number of ways is power of 2,
// but size_in_bytes is not
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 500, 16, 4, 32), CacheTagArrayInvalidSizeException);
// line_size is not power of 2
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 512, 16, 12, 32), CacheTagArrayInvalidSizeException);
// address is 48 bits
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 128, 4, 4, 48), CacheTagArrayInvalidSizeException);
// too small cache
CHECK_THROWS_AS( CacheTagArray::create( "LRU", 8, 4, 4, 32), CacheTagArrayInvalidSizeException);
// wrong mode
CHECK_THROWS_AS( CacheTagArray::create( "abracadabra", 4096, 16, 64, 32), CacheReplacementException);
}
TEST_CASE( "Check always_hit CacheTagArrayCache model")
{
auto test_tags = CacheTagArray::create( "always_hit", cache_size, cache_ways, cache_line_size, addr_size_in_bits);
test_tags->write( 0); // noop
for ( uint32 i = 0; i < cache_ways * 5; i++) {
CHECK( test_tags->lookup( i));
CHECK( test_tags->set( i) == 0);
CHECK( test_tags->tag( i) == i);
}
}
TEST_CASE( "Check infinite CacheTagArrayCache model ( fully-associative)")
{
auto test_tags = CacheTagArray::create( "infinite", cache_size, cache_ways, cache_line_size, addr_size_in_bits);
for ( uint32 i = 0; i < cache_ways * 5; i++)
test_tags->write( i);
//make sure that there was no replacement
for ( uint32 i = 0; i < cache_ways * 5; i++) {
CHECK( test_tags->lookup( i));
CHECK( test_tags->set( i) == 0);
CHECK( test_tags->tag( i) == i);
}
}
TEST_CASE( "Infinite cache: WaW case")
{
auto test_tags = CacheTagArray::create( "infinite", cache_size, cache_ways, cache_line_size, addr_size_in_bits);
auto result = test_tags->write( 0x1000);
CHECK( test_tags->read_no_touch( 0x1000).first);
CHECK( test_tags->write( 0x1000) == result);
CHECK( test_tags->read_no_touch( 0x1000).first);
CHECK( test_tags->read_no_touch( 0x1000).second == result);
}
TEST_CASE( "Check infinite CacheTagArray model with multiple sets")
{
auto test_tags = CacheTagArray::create( "infinite", cache_size * 4, cache_ways, cache_line_size, addr_size_in_bits);
//make sure that addresses have same sets
for ( uint32 i = 0; i < cache_ways + 1; i++)
{
CHECK ( test_tags->set( i * 0x10000000) == 0);
test_tags->write( i * 0x10000000);
}
//make sure that there was no replacement
for ( uint32 i = 0; i < cache_ways + 1; i++)
CHECK( test_tags->lookup( i * 0x10000000) == true);
}
| true |
55b2a003b7f5c4298e8de1952c82fb1062c88dfe | C++ | Adil-sc/Batman-vs-Riddler-Adventure-Game | /Menu.cpp | UTF-8 | 2,939 | 3.328125 | 3 | [] | no_license | /*********************************************************************
** Author: Adil Chaudhry
** Date: Late December
** Description: Outlines the class functions for the Menu class
** Citation: Inspired by https://github.com/jessicaspeigel/cs162-fantasy-combat-game/blob/master/Menu.cpp
*********************************************************************/
#include "Menu.h"
#include <string>
using std::cout;
using std::cin;
/*********************************************************************
** Setter Functions
*********************************************************************/
void Menu::setMenuOptions(vector<string> newMenuOptions) {
menuOptions.clear();
//For each string item in the newMenuOptions vector paramater, push it to the menuOptions vector
for (int i = 0; i < newMenuOptions.size(); i++) {
menuOptions.push_back(newMenuOptions[i]);
}
}
void Menu::setMenuHeader(string t) {
menuHeader = t;
}
string Menu::getMenuHeader() {
return menuHeader;
}
/*********************************************************************
** Default Constrtuctor
*********************************************************************/
Menu::Menu(vector<string> newMenuOptions) {
setMenuOptions(newMenuOptions);
setMenuHeader("");
}
/*********************************************************************
** Overloaded Constructor that accepts a menu header
*********************************************************************/
Menu::Menu(string menuHeader, vector<string> newMenuOptions) {
setMenuHeader(menuHeader);
setMenuOptions(newMenuOptions);
}
/*********************************************************************
** Display Menu Options list
*********************************************************************/
void Menu::displayMenuOptions() {
//Loop through the vector and display each element as a startGame option
for (int i = 0; i < menuOptions.size(); i++) {
//Display the list of options in the startGame
cout << i + 1 << ". " << menuOptions[i] << "\n";
}
}
/*********************************************************************
** Display Menu, get the users menu choice as well as input validation for that choice. Return an int repersenting the menu choice
*********************************************************************/
int Menu::displayMenu() {
int menuChoice = 0;
if (getMenuHeader() != "") {
cout << "\n" << getMenuHeader() << "\n";
}
displayMenuOptions();
cin >> menuChoice;
while (cin.fail() || (menuChoice < 1 || menuChoice > menuOptions.size()) || (cin.peek() != '\r' && cin.peek() != '\n') ) {
cin.clear();
cin.ignore(1000, '\n');
cout << "Please select an option between 1 and " << menuOptions.size() << std::endl;
cout << getMenuHeader() << std::endl;
displayMenuOptions();
cin >> menuChoice;
}
return menuChoice;
}
| true |
ae96893b908e05712926c9d6a9f9d0593bdef026 | C++ | thiyaguleet/LeetCode | /Maximum Product of Three Numbers.cpp | UTF-8 | 1,009 | 3.171875 | 3 | [] | no_license | class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n=nums.size();
int max_1=nums[n-1]*nums[n-2]*nums[n-3];
int max_2=nums[0]*nums[1]*nums[n-1];
return max_1>max_2? max_1:max_2;
}
};
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int MAX1 = INT_MIN, MAX2 = INT_MIN, MAX3 = INT_MIN;
int MIN1 = INT_MAX, MIN2 = INT_MAX;
for(const int num:nums){
if(num > MAX1){
MAX3 = MAX2;
MAX2 = MAX1;
MAX1 = num;
}else if(num > MAX2){
MAX3 = MAX2;
MAX2 = num;
}else if(num > MAX3){
MAX3 = num;
}
if(num < MIN1){
MIN2 = MIN1;
MIN1 = num;
}else if(num < MIN2){
MIN2 = num;
}
}
return max(MAX1*MAX2*MAX3, MAX1*MIN1*MIN2);
}
};
| true |
84441896edf55b9079777e21d1ab6413293dbaf4 | C++ | tanishq1g/cp_codes | /GeeksForGeeks/Circular tour.cpp | UTF-8 | 1,110 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <bitset>
#include <climits>
#include <list>
#include <queue>
#include <stack>
#include <utility>
using namespace std;
#define INF 1e7
// STACK AND HEAPS
/*
The structure of petrolPump is
struct petrolPump
{
int petrol;
int distance;
};*/
/*You are required to complete this method*/
int tour(petrolPump p[],int n){
if(n == 1){
if(p[0].petrol >= p[0].distance)
return 0;
else
return -1;
}
int start = 0, end = 1, le;
while(start < n){
le = 0;
for(int i = 0; i < n; i++){
le += p[start + i].petrol - p[start + i].distance;
if(le < 0){
start++;
if(start == end){
end = (end + 1) % n;
}
break;
}
end = (end + 1) % n;
}
if(start == end){
return start;
}
}
return -1;
} | true |
7418a83a636a3e7665323dbc87bf6014eb05e8e2 | C++ | Etherealblade/CSAPP | /Chapter2/71/xbyte/xbyte/main.cpp | GB18030 | 1,014 | 3.6875 | 4 | [] | no_license | /*
4зֽڷװһ32λunsigned
xbyte(packet_t word, int bytenum)
ڶbytenumʲô˼
*/
#include <cstdio>
#include <stdio.h>
#include <assert.h>
typedef unsigned packet_t;
int error_demo(packet_t word, int bytenum)
{
// This func can't extract a negative
// byte number from word
int retval = (word >> (bytenum << 3)) & 0xff;
return retval;
}
int xbyte(packet_t word, int bytenum)
{
/*
pay attention when byte we want is negative
assume sizeof(unsigned) is 4
first shift left 8*(4-1-bytenum)
then arithmetic shift right 8*(4-1) reserve
significant bit
*/
int size = sizeof(unsigned);
int shift_left_val = (size - 1 - bytenum) << 3;
int shift_right_val = (size - 1) << 3;
int retval = (int)word << shift_left_val >> shift_right_val;
return retval;
}
int main()
{
assert(xbyte(0xAABBCCDD, 1) == 0xFFFFFFCC);
assert(xbyte(0x00112233, 2) == 0x11);
if (error_demo(0xAABBCCDD, 1) != 0xFFFFFFCC)
{
printf("error_demo\n");
}
return 0;
} | true |
f4d507989f8182381f402f02b6a7e11203246f94 | C++ | Zaktansnake/CS3201-HappyPotatoes | /source/PKB/Header/Modifies.h | UTF-8 | 585 | 2.59375 | 3 | [] | no_license | #ifndef MODIFIES_H
#define MODIFIES_H
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Modifies
{
public:
// add item to ModifiesTable
static void addModifiesTable(string varName, int stmtLine);
// get ModifiesTable
static std::vector<int> getModifiesTable(string varName);
static vector<string> getModVariables(string stmtLine);
private:
int index;
vector<int> ansModifiesTable;
// constructors
Modifies();
~Modifies();
static bool isContains(string varName);
static int findPosition(string varName);
};
#endif | true |
692bb94b09ecb3e8f7d8d1ff180161754c375c7d | C++ | NataliaAlonso/CS8 | /WordTest/word.h | UTF-8 | 2,653 | 3.4375 | 3 | [] | no_license | #ifndef WORD_H
#define WORD_H
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class word
{
public:
word();
word(string &w, int &p, int &l, int &size);
/** Default destructor */
~word();
/** Copy constructor
* \param other Object to copy from
*/
word(const word& other);
/** Assignment operator
* \param other Object to assign from
* \return A reference to this
*/
word& operator=(const word& rhs);
/** Access paragraph
* \return The current value of paragraph
*/
int getParagraph() { return paragraph; }
/** Access line
* \return The current value of line
*/
int getSentence() { return sentence; }
/** Access length
* \return The current value of length
*/
int getLength() { return length; }
void copy(const word& other);
void display();
void setParagraph(int s);
void setSentence(int s);
void setLength(int s);
friend
ostream& operator<<(ostream& out, word& x);
friend
bool operator==(word& x, word &y);
friend
bool operator>(word& x, word &y);
friend
bool operator<(word& x, word &y);
friend
bool operator!=(word& x, word &y);
friend
bool operator>=(word& x, word &y);
friend
bool operator<=(word& x, word &y);
private:
int paragraph; //!< Member variable "paragraph"
int sentence; //!< Member variable "line"
int length; //!< Member variable "length"
string name;
};
#endif // WORD_H
| true |
33763aa82ffe7f8950996b5aba600a26656c84f2 | C++ | nier0525/SchoolAssignment | /Assignment/2학년 1학기/C++/0426/유저 캐릭터,아이템 관리_싱글톤/GameManager.cpp | UHC | 1,572 | 2.890625 | 3 | [] | no_license | #include "GameManager.h"
GameManager* GameManager::pthis = nullptr;
GameManager* GameManager::GetInstance() {
if (!pthis) {
pthis = new GameManager();
}
CharacterManager::GetInstance();
ItemStore::GetInstance();
return pthis;
}
void GameManager::Destory() {
if (pthis) {
delete pthis;
pthis = nullptr;
}
CharacterManager::Destory();
ItemStore::Destory();
}
GameManager::GameManager() {
}
GameManager::~GameManager() {
}
void GameManager::Init() {
CharacterManager::GetInstance()->Init();
ItemStore::GetInstance()->Init();
}
void GameManager::Run() {
while (1) {
switch (GameMenu()) {
case NEW:
CharacterManager::GetInstance()->NewChar();
break;
case DEL:
CharacterManager::GetInstance()->DelChar();
break;
case SELECT:
CharacterManager::GetInstance()->SelChar();
break;
case BUY:
ItemStore::GetInstance()->Sell();
break;
case SELL:
ItemStore::GetInstance()->Buy();
break;
case LOGOUT:
LoginManager::GetInstance()->Logout();
return;
case DELLOG:
LoginManager::GetInstance()->Delete();
return;
}
}
}
int GameManager::GameMenu() {
while (1) {
int sel;
cout << "< >\n" << "1. ij \n" << "2. ij \n" << "3. ij \n"
<< "4. \n" << "5. Ǹ\n" << "6. αƿ\n" << "7. ȸŻ\n";
cout << " : ";
cin >> sel;
if (cin.failbit) {
cin.clear();
cin.ignore(256, '\n');
}
if (sel < 1 || sel > 7) {
cout << "< Error >" << endl;
continue;
}
return sel;
}
} | true |
7f823db8953e1c34fe28f2a2673c82cc7bad2987 | C++ | Fjdklsajf/baseball-league-map | /graph_list.h | UTF-8 | 26,603 | 3.03125 | 3 | [] | no_license | /*********************************************
* Authors: Dacheng Lin
* Assig #7: MST & SHORTEST PATH ALOGRITHM
* Class: CS 008
* Section: MW 9:45-11:10 TTH 9:45-11:50
* Due Date: 05/01/2020
*********************************************/
#ifndef GRAPH_LIST_H
#define GRAPH_LIST_H
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <cassert>
#include <set>
#include <vector>
#include <functional>
#include "location_info.h"
#include <QTextStream>
#include <QFile>
#include <QString>
#include <QSaveFile>
#include <QtDebug>
#include <QDebug>
#include <string>
#include <QFileDialog>
#include <QPainter>
#include <ctime>
using namespace std;
const bool debugging_tool = false; // Debugging check
template <class Item_Type, class Element>
class Graph_List
{
public:
//--------STATIC ARRAY STORAGE---------
const static int STORAGE = 200;
//--------CONSTURCTOR----------
Graph_List(int capacity = 100);
~Graph_List();
//---------ACCESSOR---------
int get_size() const
{
return _size;
}
Item_Type start_vertex_at(int index) const;
int vertex_index_of(const Item_Type& target) const;
//---------MODIFICATIONS----------
void add_vertex(const int& vertex_index,
Item_Type vertex_neighbor);
void remove_vertex(const int& vertex_index,
Item_Type vertex_neighbor);
//---------OVERLOADING OPERATORS-----------
List<Item_Type>& operator[](const int index)
{
List<Item_Type>* walker = _list; // Assign a walker
walker+= index; // Walk to the assigned position
return *walker; // Return the index's list
}
const List<Item_Type>& operator[](const int index) const
{
List<Item_Type>* walker = _list; // Assign a walker
walker+= index; // Walk to the assigned position
return *walker; // Return the index's list
}
//---------OVERLOADING OSTREAM OPERATOR-----------
template<class TYPE>
friend ostream & operator <<(ostream& outs,
const Graph_List<TYPE,Element> & g)
{
List<Item_Type>* walker = g._list; // Assign walker to walk through
cout << g.get_size() << endl;
for(int i = 0; i < g.get_size(); i++,walker++)
{
outs << *walker << endl; // Print the first item
}
return outs;
}
//--------MST ALOGRITHMS-------
vector<Item_Type> * Dijkstra_Algorithm(const Item_Type& start,
int & v_size,
int path_costs[]);
void Prim_Algorithm();
void Kruskal_Algorithm();
private:
List<Item_Type> * _list; // A list of sorted vertex list
int _mst[STORAGE]; // List of the minimum spanning tree
int _distance[STORAGE]; // List of shortest cost
int _size; // Size of the list
int _capacity; // Capacity for the dynamic space
void reserve(int new_capacity); // Reallocation for space
// Initialize the static array
void init_1D(int*one_D, int col, int item = -1)
{
int* walker = one_D; // Assign a pointer for 1D space
for(; walker - one_D < col; walker++)
{
*walker = item; // Initialize all the elements to be
// same as the target item
}
}
};
/*************************************************
* Graph Constructor
* ----------------------------------------------
* Precondition: The valid value of the capacity for
* dynamic space
* -----------------------------------------------
* Postcondition: The dynamic spaces for the data
* will be created with specific capacity.
**************************************************/
template <class Item_Type,class Element>
Graph_List<Item_Type,Element>::Graph_List(int capacity)
{
reserve(capacity); // Reserve space for dynamic space
init_1D(_distance,capacity,-1); // Initialize the distance array
init_1D(_mst,capacity,-1); // Initialize the distance array
_size = 0;
}
/*************************************************
* Graph Destructor
* ----------------------------------------------
* Precondition: No parameter needed
* -----------------------------------------------
* Postcondition: The dynamic spaces for the data
* will be released in a 2D-deallocation style.
**************************************************/
template <class Item_Type,class Element>
Graph_List<Item_Type,Element> ::~Graph_List()
{
List<Item_Type>* walker; // List walker
node<Item_Type>* tracker; // Tracker to help delete each list
_list += _size -1; // Go to very last position of
// the dyname space
// Go through the list
for(;_size > 0; _size--,_list--)
{
walker = _list;
tracker = walker->Begin();
// Assign the Iterator
for(;walker->get_size() > 0;tracker = walker->Begin())
{
walker->Delete(tracker);
// Delete all the items in one list
}
}
_list = nullptr; // Release the whole list
_size = 0;
}
/*************************************************
* Helper: Reallocate 1D
* ----------------------------------------------
* Precondition: The new capacity for the space
* -----------------------------------------------
* Postcondition: The dynamic spaces will be expand
* or shrink
**************************************************/
template <class Item_Type,class Element>
void Graph_List<Item_Type,Element> ::reserve(int new_capacity)
{
//**********ASSERTION
assert(new_capacity > 0);// Only allows non-negative
_capacity = new_capacity;
// Enlarge the dynamic space when needed
if(_size >= (_capacity) / 2)
_capacity *= 2;
_list = new List<Item_Type> [_capacity]; // Reserve that many spaces
// to the freestore
}
/*************************************************
* Start_vertex_at
* ----------------------------------------------
* Precondition: The index of that list
* -----------------------------------------------
* Postcondition: The start vertex of a list will
* be returned.
**************************************************/
template <class Item_Type, class Element>
Item_Type Graph_List<Item_Type,Element>::start_vertex_at
(int index) const
{
List<Item_Type>* walker = _list; // Assign a walker
walker+= index; // Walk to the assigned position
// Use node finder to find the walker's begin item
node<Item_Type>* finder = walker->Begin();
return finder->_item; // Return the begin item
}
/*************************************************
* vertex_index_of
* ----------------------------------------------
* Precondition: The target item in that list
* -----------------------------------------------
* Postcondition: The index of the target vertex
**************************************************/
template <class Item_Type, class Element>
int Graph_List<Item_Type,Element>:: vertex_index_of
(const Item_Type& target) const
{
List<Item_Type>* finder;
node<Item_Type>* find_here;
int i = 0;
for(; i < get_size(); ++i)
{
finder = _list; // Go through the start vertex of
finder += i; // Go through list
find_here = finder->Begin(); // Each list
if(find_here->_item == target) // If the target was found
return i;
}
assert(i != get_size()); // Assert if Not found
return -1; // If not found return -1
}
/*************************************************
* Add_vertex
* ----------------------------------------------
* Precondition: The index of that list and the item
* -----------------------------------------------
* Postcondition: The item will be inserted into the
* correct index's list.
**************************************************/
template <class Item_Type, class Element>
void Graph_List<Item_Type,Element> ::add_vertex(const int& vertex_index,
Item_Type vertex_neighbor)
{
// A list of location list pointer of 2-D pointer
List<Location_info<Element>>* walker = _list;
walker += vertex_index; // Let walker walker to the correct position
// Insert the sorted information
walker->InsertSorted(vertex_neighbor);
if(vertex_index > _size-1) // Increase size if at a new position
_size++;
}
/*************************************************
* remove_vertex
* ----------------------------------------------
* Precondition: The index of that list and the item
* -----------------------------------------------
* Postcondition: The item will be removed at the
* correct index's list.
**************************************************/
template <class Item_Type, class Element>
void Graph_List<Item_Type,Element> ::remove_vertex(const int& vertex_index,
Item_Type vertex_neighbor)
{
// A list of location list pointer of 2-D pointer
List<Location_info<Element>>* walker = _list;
walker += vertex_index; // Let walker walker to the correct position
// Find the specific item for the deletion
node<Item_Type>* finder = walker->Search(vertex_neighbor);
assert(finder!= nullptr); // Item should found in the list
walker->Delete(finder); // Delete the specific item
if(walker->get_size() == 0) // If the list empty
_size--;
}
/*************************************************
* Dijkstra_Algorithm
* ----------------------------------------------
* Precondition: a non-empty list of edge lists
* -----------------------------------------------
* Postcondition: The solution will be outputed
* after the algorithm is performed
**************************************************/
template <class Item_Type, class Element>
vector<Item_Type>* Graph_List<Item_Type,Element> ::Dijkstra_Algorithm(
const Item_Type& start,
int & v_size,
int path_costs[])
{
// Define a set of locations as a vector
vector<Item_Type>* solution = new vector<Item_Type>[STORAGE];
set<Item_Type> answer_set; // Item type is location info here
set<Location_info<Stadium>>::iterator it;
Item_Type processor_u;
bool shortest_path_found = false;
bool Element_exists = false;
int edge_cost;
int vertex_index;
int lowest_cost;
int lowest_cost_index;
// If the starting point is differnt swap them
if(start != start_vertex_at(0))
{
cout << start_vertex_at(2)<< endl;
int index_ = vertex_index_of(start);
assert(index_!= -1); // assert if not found
List<Item_Type> *track = _list;
track += index_;
List<Item_Type> new_start =
*track;
// Switch the starting point
*track = *_list;
*_list = new_start;
cout << *this << endl;
}
// Step 1: Insert the first vertex to the set
answer_set.insert(start_vertex_at(0));
_distance[0]= 0; // Distance at itself is zero as always
it = answer_set.begin();
processor_u = *it; // let the start vertex be the
// start processor
// Put the start vertex into every solution set
for(int h = 0; h < get_size(); h++)
{
solution[h].push_back(start_vertex_at(0));
}
Location_info<Element> next; // The next vertice of processor
//------------------------------------------------------
// Walk through all the vertices in the list
for(int n = 1; n < get_size()*2; n++)
{
// Find the processor u 's index for (u,v)
vertex_index =
vertex_index_of(processor_u);
shortest_path_found = false; // Reset the bool for element searching
// Check to see if the next is the set already
for(int i = 1; i < _list[vertex_index].get_size();i++)
{
Element_exists = false;
// Get the next vertex neighbor in the list.
next = _list[vertex_index].operator[](i);
// Check to see if the neighbor vertex is in the set
for(it = answer_set.begin(); it != answer_set.end();it++)
{
if(next == *it)
Element_exists = true; // Element found in set
}
if(!Element_exists) // If element not found in set
{
if(!shortest_path_found)
{
// When first time finding the shortest path of u
// Update the new processor
shortest_path_found = true;
processor_u = next; // Initialize the processor candicate
}
}
}
// work through the Edge list with walker to update distance
for(int v = 1; v < _list[vertex_index].get_size();v++)
{
next = _list[vertex_index].operator[](v); // Walk through v for(u,v)
// Examine the edge cost (processor's cost + current)
edge_cost = _distance[vertex_index] + next.get_cost();
// Get the vertex index from the list of edge lists
int search_index;
search_index = vertex_index_of(next);
// If previous cost is infinite or less than current cost
if(_distance[search_index] == -1 ||
edge_cost <= _distance[search_index])
{
// Find the index of that shortest path
// Update that path with the processor
solution[vertex_index_of(next)] = solution[vertex_index];
solution[vertex_index_of(next)].push_back(next);
_distance[search_index] = edge_cost; // Change cost
// at distance array
}
}
// After updating all the path cost, choose the best processor
// Use the initialize processor to compare with others
lowest_cost_index = vertex_index_of(processor_u);
lowest_cost = _distance[lowest_cost_index]; // Initialize the lowest cost
// *Debugging purpose
if(debugging_tool)
cout << n << " Pi: " << processor_u << " "
<< processor_u .get_cost()<< endl;
// Go through the entire path cost for each place to select the lowest
for(int distance_index = 1; distance_index < get_size(); distance_index++)
{
Element_exists = false;
// Lowest path cost is found
if(_distance[distance_index] != -1 &&
_distance[distance_index] < lowest_cost)
{
Item_Type current_element = start_vertex_at(distance_index);
// And check to see if the next processor is in the set
for(it=answer_set.begin();it != answer_set.end();it++)
{
if(current_element == *it)
Element_exists = true;
}
// set the non-existed element to be a
// candicate for the procesoor
if(!Element_exists)
{
lowest_cost_index = distance_index;
lowest_cost = _distance[lowest_cost_index];
}
}
}
// Candicate is finalized at the end with lowest cost
processor_u = start_vertex_at(lowest_cost_index);
bool duplicates = false;
// Check for duplicates for the processor in the
// answer set, otherwise reset the processor to beginning
for(it=answer_set.begin();it != answer_set.end();it++)
{
if(*it == processor_u)
duplicates = true;
}
//**** Rest position may vary for relatively complicated map
// Random assign index will be a better idea
srand(time(nullptr));
//***** If there is duplicates, back_track to
// previously visited locations to continue mapping
// the whole map
if(duplicates)
{
// Get the size of the previously visited locations
int size_set = static_cast<int>(answer_set.size());
// Randomly select a index size based on the size
int rand_select_processor_index = rand() %
(size_set);
set<Location_info<Stadium>> :: iterator check_it;
check_it = answer_set.begin(); // Assign iterator
// walk the iterator to that specific index
for(int y = 0; y <= rand_select_processor_index; y++,check_it++)
{
// Reset the processor
// choose from the answer set
if(y == rand_select_processor_index)
processor_u = *check_it;
}
}
// Reset the path cost with its asociatted path cost
if(processor_u.get_cost() == 0)
processor_u.set_cost(_distance[lowest_cost_index]);
answer_set.insert(processor_u); // Add the distinct candicate to set
// *Debugging purposes
if (debugging_tool)
{
cout << n << " Pf: " << processor_u << " "
<< processor_u .get_cost()<< endl;
for(it=answer_set.begin();it != answer_set.end();it++)
{
cout << *it << " ";
}
cout << endl;
}
}
//------------------------------------------------------
// Print out the Alogrithm output
for(int u = 0; u < get_size();u++)
{
cout << _distance[u] << " ";
for(size_t g = 0; g < solution[u].size(); g++)
{
cout << solution[u].at(g).get_start() << " ";
}
cout << endl;
}
cout << endl;
vector<Item_Type>* walker = solution; // Assign the solution
v_size = get_size();
for(int k = 0; k < v_size; k++)
{
path_costs[k] = _distance[k];
}
init_1D(_distance,STORAGE); // Reset all the distance cost once finished
return walker;
}
/*************************************************
* Prim_Algorithm
* ----------------------------------------------
* Precondition: a non-empty list of edge lists
* -----------------------------------------------
* Postcondition: The solution will be outputed
* after the algorithm is performed
**************************************************/
template <class Item_Type, class Element>
void Graph_List<Item_Type,Element>::Prim_Algorithm()
{
// Define a set of locations as a vector
vector<Location_info<string>> answer_set;
bool item_found = false;
int vertex_index;
int lowest_edge_cost;
int start_vertex;
//------------------------------------------------------
List<Item_Type>* walker = _list;
node<Item_Type>* finder = walker->Begin() +1;
// Initialize the lowerset cost from the sorted edge list
lowest_edge_cost = finder->_item.get_cost();
// Go through the list to find the best starting place
for(int i =0; i < get_size(); i++,walker++ )
{
finder = walker->Begin() +1;
// Swap the value if find the smaller start cost
if(finder->_item.get_cost() <= lowest_edge_cost)
{
// Get the lower cost
lowest_edge_cost = finder->_item.get_cost();
// Find the index of that place
start_vertex = vertex_index_of(finder->_item);
}
}
// Push back the initial starting cost first
answer_set.push_back(start_vertex_at(start_vertex));
Location_info<string> next; // The next vertice of processor
// Walk through the entir list of Edge list to finish spanning
for(int n = 0; n < get_size(); n++)
{
walker = _list; // Assign walker at the front
// Find the processor u 's index for (u,v)
vertex_index =
vertex_index_of(answer_set[answer_set.size()-1]);
walker += (vertex_index); // Walk to processor vertex index
// Check to see if the next is the set already
for(int i = 1; i < walker->get_size();i++)
{
item_found = false; // Reset the bool for element searching
// Get the next vertex neighbor in the list.
next = walker->operator[](i);
// Search the neighbor in the set
for(size_t j = 0; j < answer_set.size(); j++)
{
if(next == answer_set[j])
item_found = true; // Set true if found
}
if(!item_found) // If neighbor vertex not in the set
{
answer_set.push_back(next); // Insert the vertex into set
break; // Break the for loop
}
}
}
//------------------------------------------------------
node<Item_Type>* searcher;
int search_index;
// Print out the Alogrithm output
for(size_t t = 0 ; t < answer_set.size(); t++)
{
walker = _list;
if(t != answer_set.size()-1)
{
cout << "(";
cout << answer_set[t] << ", " << answer_set[t+1]
<< ") ";
search_index = vertex_index_of(answer_set[t]); // Find processor
walker += search_index; // Assign walker to here
searcher = walker->Search(answer_set[t+1]); // Find the second item
// of the list
cout << searcher->_item.get_cost();
}
cout << endl;
}
}
/*************************************************
* Kruskal_Algorithm
* ----------------------------------------------
* Precondition: a non-empty list of edge lists
* -----------------------------------------------
* Postcondition: The solution will be outputed
* after the algorithm is performed
**************************************************/
template <class Item_Type, class Element>
void Graph_List<Item_Type,Element>::Kruskal_Algorithm()
{
// Define a set of Edges with locations as a vector
vector<Location_info<string>> answer_set;
List<Location_info<string>> _pair_vertices_;
List<Location_info<string>>::Iterator it;
bool item_duplicated = false;
List<Item_Type>* walker = _list;
node<Item_Type>* vertex_u = walker->Begin();
node<Item_Type>* vertex_v = walker->Begin() +1;
int lowest_edge_cost = vertex_v->_item.get_cost();
int lowest_start_vertex;
Item_Type lowest_Item_start;
Element lowest_end_name;
int start_vertex; // Index of start vertex u
Item_Type Item_start_index;
Element end_vertex_name;
//------------------------------------------------------
// Find the least costly edge to and add it to the answer set
for(int p = 0; p < _size;p++,walker++)
{
vertex_u = walker->Begin();
vertex_v = walker->Begin() + 1;
// Find the lowest edge cost in the list to start
if(vertex_v->_item.get_cost() < lowest_edge_cost)
{
lowest_edge_cost = vertex_v->_item.get_cost();
lowest_start_vertex = vertex_index_of(vertex_u->_item);
lowest_end_name = vertex_v->_item.get_start();
}
}
// Define the Edge the with start and ending location
Item_start_index = start_vertex_at(lowest_start_vertex);
Item_start_index.set_end(lowest_end_name);
Item_start_index.set_cost(lowest_edge_cost);
// Add the lowest cost edge to the list
answer_set.push_back(Item_start_index);
_pair_vertices_.InsertSorted(Item_start_index);
walker = _list;
// Go through the list to sort all the edge info to list
for(int i =0; i < _size; i++,walker++ )
{
vertex_u = walker->Begin(); // Start vertex
// Walk throught each edge list
for( int k = 1; k < walker->get_size(); k++)
{
vertex_v = walker->Begin() + k;
start_vertex = vertex_index_of(vertex_u->_item);
// Define the Edge the with start and ending location
Item_start_index = start_vertex_at(start_vertex);
Item_start_index.set_end(vertex_v->_item.get_start());
Item_start_index.set_cost(vertex_v->_item.get_cost());
// Insert the Edge info as sorted into the list
_pair_vertices_.InsertSorted(Item_start_index);
}
}
int allowed_repeats = 0;
size_t max_size = static_cast<size_t>(_size -2);
// cout << _pair_vertices_.get_size() << " eeeee\n";
// Walker through the edge info in the list to fill the answer set
for(it = _pair_vertices_.Begin();
answer_set.size() != max_size && it != _pair_vertices_.End();it++)
{
item_duplicated = false;
for(size_t h = 0; h < answer_set.size(); h++)
{
// If the Edge info is not duplicated in the set
if( it->_item.get_start() == answer_set[h].get_start() ||
(it->_item.get_start() == answer_set[h].get_start() &&
it->_item.get_end() == answer_set[h].get_end() ) ||
(it->_item.get_start() == answer_set[h].get_end() &&
it->_item.get_end() == answer_set[h].get_start() ) ||
it->_item.get_end() == answer_set[0].get_start() ||
it->_item.get_cost() == answer_set[h].get_cost())
{
// Only allowed the starting vertex to repeat
if((it->_item.get_start() == answer_set[h].get_start() &&
it->_item.get_end() != answer_set[h].get_end() )
)
allowed_repeats++;
else
item_duplicated = true;
}
}
// cout << *it << " "; // Debug
// If not duplicated add into the solution
if(!item_duplicated)
answer_set.push_back(*it);
}
// cout << "----------------------------------------\n";
for(size_t y =0;y < answer_set.size(); y++)
{
cout << "(" << answer_set[y].get_start()
<< ", " << answer_set[y].get_end() << ")"
<< " " << answer_set[y].get_cost() << endl;
}
}
#endif // MY_GRAPH_H
| true |
876c7560df4a9d44072b2cfd2cf2a867569851c5 | C++ | ngangwar962/C_and_Cpp_Programs | /practise/hackwithinfy/xor_question.cpp | UTF-8 | 514 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,k,n;
cin>>n;
int a[n];
int temp=0;
for(i=0;i<n;i++)
{
cin>>a[i];
temp=temp^a[i];
}
int b[n-1];
int temp2=0;
for(i=0;i<n-1;i++)
{
cin>>b[i];
temp=temp^b[i];
temp2=temp2^b[i];
}
cout<<temp<<"\n";
int temp3=0;
int c[n-2];
for(i=0;i<n-2;i++)
{
cin>>c[i];
temp2=temp2^c[i];
temp3=temp3^c[i];
}
cout<<temp2<<"\n";
int d[n-3];
for(i=0;i<n-3;i++)
{
cin>>d[i];
temp3=temp3^d[i];
}
cout<<temp3<<"\n";
return 0;
}
| true |
b4842d57be08b23b514e635523896766fb687f5f | C++ | chrisjakins/ice-cream | /src/test_customer.cpp | UTF-8 | 268 | 3 | 3 | [] | no_license | #include <iostream>
#include "customer.h"
int main() {
Customer cust("Bob", 9901050, "817-990-1050");
if (cust.name() != "Bob") {
std::cerr << "Bob test failed - expected Bob got: " << cust.name() << std::endl;
return 1;
}
return 0;
} | true |
f7b3e78e08f4f47141a6a4bb93828bc8c6ba4597 | C++ | TissueFluid/Algorithm | /LintCode/Sort Colors II.cc | UTF-8 | 1,071 | 3.84375 | 4 | [] | no_license | // Sort Colors II
#include <iostream>
#include <vector>
using namespace std;
class Solution{
public:
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
void sortColors2(vector<int> &colors, int k) {
const int size = colors.size();
int start = 1;
int end = k;
int left = 0;
int right = size - 1;
while (start < end) {
for (int i = left; i <= right; ) {
if (colors[i] == start) {
swap(colors[i], colors[left]);
left++;
i++;
} else if (colors[i] == end) {
swap(colors[i], colors[right]);
right--;
} else {
i++;
}
}
start++;
end--;
}
}
};
int main() {
vector<int> v({3, 2, 2, 1, 4});
Solution s;
s.sortColors2(v, 4);
for (const auto &item : v) {
cout << item << endl;
}
return 0;
}
| true |
b804feb2c144d8d52294efc01f35e2b6172312ce | C++ | sirAdarsh/CP-files | /CodeForces/1334-B.cpp | UTF-8 | 549 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
ll n,x;
cin >> n >> x;
ll arr[n]={};
ll p;
ll diff=0;
ll ans=0;
for(ll i=0;i<n;i++){
cin >> p;
if(p >= x ){
ans++;
diff += p-x;
}else{
arr[i] = p;
}
}
sort( arr,arr+n, greater<>() );
for(ll i =0;i<n;i++){
if(arr[i]==0){
break;
}
if( x-arr[i] > diff || diff==0 ){
break;
}
if( x - arr[i] <= diff ){
ans++;
diff -= (x-arr[i]);
}
}
cout<<ans<<endl;
}
}
| true |
8b0adbc6831f2575d7b082765abc7997dc01e68e | C++ | epw7856/CashFlowManager | /CashFlowManager/Income/salaryincometablemodel.cpp | UTF-8 | 3,713 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "currencyutilities.h"
#include "dateutilities.h"
#include "incomeinterface.h"
#include <QBrush>
#include <QFont>
#include "salaryincome.h"
#include "salaryincometablemodel.h"
SalaryIncomeTableModel::SalaryIncomeTableModel(IncomeInterface &localIncomeInterface, int localYear)
:
incomeInterface(localIncomeInterface),
numColumns(3),
year(localYear)
{
std::pair<QDate, QDate> dates = DateUtilities::getYearlyDates(year);
startDatePeriod = dates.first;
endDatePeriod = dates.second;
}
int SalaryIncomeTableModel::rowCount(const QModelIndex&) const
{
return static_cast<int>(salaryIncomeTransactions.size()) + 2;
}
int SalaryIncomeTableModel::columnCount(const QModelIndex&) const
{
return numColumns;
}
QVariant SalaryIncomeTableModel::data(const QModelIndex& index, int role) const
{
if(role == Qt::DisplayRole)
{
int numRows = rowCount(index);
if((index.row() < numRows - 2) && (index.column() < numColumns))
{
auto rowUint = static_cast<quint32>(index.row());
// Date column
if(index.column() == 0)
{
return salaryIncomeTransactions[rowUint]->getDate().toString("MM/dd");
}
// Amount column
else if(index.column() == 1)
{
return QString::fromStdString(CurrencyUtilities::formatCurrency(salaryIncomeTransactions[rowUint]->getAmount()));
}
// Overtime column
else if(index.column() == 2)
{
return QString::number(salaryIncomeTransactions[rowUint]->getOvertime());
}
}
if((index.row() == numRows - 1) && (index.column() < numColumns))
{
// Date column
if(index.column() == 0)
{
return "Total";
}
// Amount column
else if(index.column() == 1)
{
return QString::fromStdString(CurrencyUtilities::formatCurrency(incomeInterface.getSalaryIncomeTotalByTimePeriod(startDatePeriod,
endDatePeriod)));
}
// Overtime column
else if(index.column() == 2)
{
return QString::number(incomeInterface.getYearlyOvertimeTotal());
}
}
}
if(role == Qt::TextAlignmentRole)
{
int numRows = rowCount(index);
if((index.row() < numRows) && (index.column() < numColumns))
{
if(index.column()!= 0)
{
return Qt::AlignCenter;
}
}
}
if((role == Qt::FontRole) && (index.row() == rowCount(index)-1))
{
QFont font;
font.setBold(true);
return font;
}
return {};
}
QVariant SalaryIncomeTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role == Qt::DisplayRole)
{
if(orientation == Qt::Horizontal)
{
if(section == 0)
{
return QString("Date");
}
else if(section == 1)
{
return QString("Amount");
}
else if(section == 2)
{
return QString("Overtime ");
}
}
}
return {};
}
void SalaryIncomeTableModel::setSalaryIncomeTransactions()
{
salaryIncomeTransactions = incomeInterface.getSalaryIncomeTransactionsByTimePeriod(startDatePeriod,
endDatePeriod);
}
| true |
cbf6c0ec1b1f54bcd3b26cda82af53721e3f1c1e | C++ | Naryadchikov/CS-E5520-ACG-assignment-3 | /src/base/InstantRadiosity.cpp | UTF-8 | 5,497 | 2.75 | 3 | [] | no_license | #include "InstantRadiosity.hpp"
namespace FW
{
void InstantRadiosity::castIndirect(RayTracer* rt, MeshWithColors* scene, const LightSource& ls, int num)
{
// If the caller requests a different number of lights than before, reallocate everything.
// (This is OpenGL resource management stuff, don't touch unless you specifically need to)
if (m_indirectLights.size() != unsigned(num))
{
printf("Deleting %i indirect light sources.\n", num);
for (auto& iter : m_indirectLights) // = m_indirectLights.begin(); iter != m_indirectLights.end(); iter++)
iter.freeShadowMap();
m_indirectLights.resize(num);
for (auto& iter : m_indirectLights) // = m_indirectLights.begin(); iter != m_indirectLights.end(); iter++)
iter.setEnabled(false);
}
// Request #num exiting rays from the light.
std::vector<Vec3f> origs, dirs, E_times_pdf;
ls.sampleEmittedRays(num, origs, dirs, E_times_pdf);
// You'll probably want to implement the sampleEmittedRays() function before the rest of this function,
// because otherwise you won't have much to trace.
//
// At this point m_indirectLights holds #num lights that are off.
//
// Loop through the rays and fill in the corresponding lights in m_indirectLights
// based on what happens to the ray.
for (int i = 0; i < num; ++i)
{
RaycastResult result = rt->raycast(origs[i], dirs[i]);
if (result.tri != nullptr)
{
// YOUR CODE HERE (R4):
// Ray hit the scene, now position the light m_indirectLights[i] correctly,
// color it based on the texture or diffuse color, etc. (see the LightSource declaration for the list
// of things that a light source needs to have)
// A lot of this code is like in the Assignment 2's corresponding routine.
const Vec3i& indices = result.tri->m_data.vertex_indices;
// check for backfaces => don't accumulate if we hit a surface from below!
if (FW::dot(dirs[i], -result.tri->normal()) < 0.f)
{
continue;
}
// fetch barycentric coordinates
float alpha = result.u;
float beta = result.v;
Vec3f Ei;
// check for texture
const auto mat = result.tri->m_material;
if (mat->textures[MeshBase::TextureType_Diffuse].exists())
{
// read diffuse texture like in assignment1
const Texture& tex = mat->textures[MeshBase::TextureType_Diffuse];
const Image& texImg = *tex.getImage();
Vec2f uv = alpha * scene->vertex(indices[0]).t +
beta * scene->vertex(indices[1]).t +
(1.f - alpha - beta) * scene->vertex(indices[2]).t;
Ei = texImg.getVec4f(FW::getTexelCoords(uv, texImg.getSize())).getXYZ();
}
else
{
// no texture, use constant albedo from material structure.
Ei = mat->diffuse.getXYZ();
}
m_indirectLights[i].setEmission(E_times_pdf[i] * Ei);
m_indirectLights[i].setOrientation(FW::formBasis(-result.tri->normal()));
m_indirectLights[i].setPosition(result.point);
m_indirectLights[i].setFOV(m_indirectFOV);
// Replace this with true once your light is ready to be used in rendering:
m_indirectLights[i].setEnabled(true);
}
else
{
// If we missed the scene, disable the light so it's skipped in all rendering operations.
m_indirectLights[i].setEnabled(false);
}
}
}
void InstantRadiosity::renderShadowMaps(MeshWithColors* scene)
{
// YOUR CODE HERE (R4):
// Loop through all lights, and call the shadow map renderer for those that are enabled.
// (see App::renderFrame for an example usage of the shadow map rendering call)
for (auto it = m_indirectLights.begin(); it != m_indirectLights.end(); ++it)
{
if (it->isEnabled())
{
it->renderShadowMap(m_gl, scene, &m_smContext);
}
}
}
//////////// Stuff you probably will not need to touch:
void InstantRadiosity::setup(GLContext* gl, Vec2i resolution)
{
m_gl = gl;
// Clear any existing reserved textures
for (auto iter = m_indirectLights.begin(); iter != m_indirectLights.end(); iter++)
iter->freeShadowMap();
// Set up the shadow map buffers
m_smContext.setup(resolution);
}
void InstantRadiosity::draw(const Mat4f& worldToCamera, const Mat4f& projection)
{
// Just visualize all the light source positions
for (auto iter = m_indirectLights.begin(); iter != m_indirectLights.end(); iter++)
{
if (iter->isEnabled())
{
iter->draw(worldToCamera, projection, true, false);
}
}
}
GLContext::Program* InstantRadiosity::getShader()
{
return m_gl->getProgram("MeshBase::draw_generic");
}
}
| true |
057588ebd9c6dbc1df150f7f730b47750a3e043a | C++ | barmi/WindowsProgramming2016 | /Shape/Shape.cpp | UHC | 853 | 3.375 | 3 | [] | no_license | // Shape.cpp : ܼ α մϴ.
//
#include "stdafx.h"
class CShape {
protected:
int _x, _y; // ߽ ġ
public:
CShape() {}
CShape(int x, int y) : _x(x), _y(y) {}
~CShape() {}
virtual void draw() = 0;
};
class CRectangle : public CShape {
private:
int _width, _height;
public:
CRectangle() {}
CRectangle(int x, int y, int w, int h) : CShape(x, y), _width(w), _height(h) {}
~CRectangle() {}
void draw() {}
};
class CCircle : public CShape {
private:
int _radius;
public:
CCircle() {}
CCircle(int x, int y, int r) : CShape(x, y), _radius(r) {}
~CCircle() {}
void draw() {}
};
int main()
{
CShape *shape1 = new CRectangle(100, 100, 60, 40);
CShape *shape2 = new CCircle(100, 100, 30);
shape1->draw();
shape2->draw();
delete shape1;
delete shape2;
return 0;
}
| true |
26ef2f379ac344017b84b4523623b9b42c931c4d | C++ | schiebermc/CP_Lib | /HackerRank/Practice/InterviewPrep/StringManipulation/CommonChild/code.cpp | UTF-8 | 1,305 | 2.796875 | 3 | [] | no_license | //#include <bits/stdc++.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <map>
#include <set>
#include <climits>
using namespace std;
typedef long long int ll;
ll best_from_here(string& a, string& b, ll i, ll j, unsigned long na, unsigned long nb, map<pair<ll, ll>, ll>& saved);
void solution(string a, string b){
map<pair<ll, ll>, ll> saved;
ll count = best_from_here(a, b, (ll)a.size(), (ll)b.size(), a.size(), b.size(), saved);
printf("%lld\n", count);
}
ll best_from_here(string& a, string& b, ll i, ll j, unsigned long na, unsigned long nb, map<pair<ll, ll>, ll>& saved){
if(saved.find(make_pair(i, j)) != saved.end())
return saved[make_pair(i, j)];
if(i == -1 or j == -1)
return 0;
ll count1 = 0;
ll count2 = 0;
ll count3 = 0;
if(a[i] == b[j])
count1 = 1 + best_from_here(a, b, i-1, j-1, na, nb, saved);
else
count2 = best_from_here(a, b, i-1, j, na, nb, saved);
count3 = best_from_here(a, b, i, j-1, na, nb, saved);
ll ans = max(max(count1, count2), count3);
saved[make_pair(i, j)] = ans;
return ans;
}
int main() {
// variables
string n, m;
cin >> n;
cin >> m;
solution(n, m);
return 0;
}
| true |
db5f7840fe1e9cd4f91899b711b1f7ce9a488103 | C++ | AsderYork/ShortGame1 | /GameSimulation/LandscapeChunkController.h | UTF-8 | 9,682 | 2.8125 | 3 | [] | no_license | #pragma once
#include "LandscapeChunk.h"
#include "LandscapeMeshGenerator.h"
#include <LinearMath\btVector3.h>
#include <cstdint>
#include <vector>
#include <memory>
#include <functional>
#include <map>
#include <algorithm>
namespace GEM::GameSim
{
/**!
More text. Becouse I have no idea, how to implement this.
Let's start from the begining.
Player connects to a server and requests chunks.
Techicly speacking, server will know the position of a player at this moment, so it can predict it's request.
But can it predict all the chunks, that player already have on a hard drive? Well, it probably can, but it's actually
difficult, so let's say that it can't. In that case player's request will consist of vector of pairs[chunkVersion, ChunkPos].
When server recives this messages, it should, for every specified chunk:
1)Check that this chunk is visible for a player(Security check). If it's not, make warning and ignore this request
2)Check version of chunk. If it's up to date, reply the same way player did. If it's not, prepare to send a chunk
After every chunk is processed, server should form the responce. Responce, for every chunk, looks like this:
[Version][Pos]. And at the end, there is [IsThereChunkPack]<ChunkPackData>.
In the meantime, player should load required chunks from the disk, maybe even start showing them, but mark them as not-verified.
It's assumed, that respond will be recived in a 0.6s. Then maybe we should not process chunks? Ok, so we do not process them then.
When player recives server's responce, it should mark all the chunks, which version is equal to one in responce and then, if there is
a chunkPack, it must unpack it and update corresponding chunks, also marking then as confirmed.
And so chunks are now restored. For evry confirmed chunk, a mesh should be generated and then presented.
Controller should generate meshes in a separate thread and when it's ready, it should mark which exact chunkMeshes were created.
It's important to remember, that chunk, for which mesh is generated, shoud not be altered from any other place during that process.
In this way, we can also provide std::optional<const Node*> GetClosestNode(pos); interface to read-only access to allready loaded,
verified chunks.
Next thing is alteration. It's a difficult thing, actually. When we alter a chunk, we create a temporary copy of a chunk(preferably
not the full one) of alterationg chunk with said alterations, and send an alterationRequest to a server. Request consists of
sessionUnique ID and altered nodes with their positions. Request also, probably, should somehow reference a reason, why it was called.
For example if player dug the ground, the alteration request should contain reference to that event, so that it validity can be checked
by checking validity of that request. We can, probably, do this by injecting request in an event. Or even more, should this system
be responsible for alterations at all? Well, it should provide temporary chunk facility and that's it. Then actual events should go with
confirmations, and this confirmations, in turn, should validate or invalidate change in a chunk.
One more thing about chunk loading. We can fetch all requested chunks, but we also should track chunks, that are not used anymore.
We can give a ticket to every player, and every time player moves we also update position of a player in chunk system, and then check
for the chunks we're need and for ones we're don't anymore.
*/
/**!
Something about the size of a map.
It's fixed. Map centered at 0,0 with MapSize/2-1 and 1MapSize/2 as the maximum and minimum coordinates.
It's also a square.
*/
/**!
And another part of text.
After some thought, I came to a conclusion, that all we basically need is a way to determine, what chunks entered view in a frame
what chunks left it and what chunks is visible for every loader.
The most straightforward aproach would be to just iterate through every chunk in a map(we have a limited now, so it's doable, but
slow) and test if it's visible for any Loader. this is an O(n*n*l) task with n - size of a map, l, number of loaders.
Then we go through every chunk once again to determine, and compare it's visibility with visibility in a previous frame.
Which is O(n*n) task.
It's possible to make first task faster. We could iterate through every loader and just mark chunks, that is visible for it.
Then on the second pass, chunk is count as visible, if at least one loader sees it.
But can we somehow decrease the complexity of a second pass?
What if for every loader we would just make a list of visible chunks and also store a list of previously visible ones.
Then on the second pass we just concat all "visible" lists of all the loaders. Wait a little. We can, instead of building
individual visibility list, build a huge one, and also sorted. We We can assign unique value for every chunk(x+size*y) and
then, for every visible chunk of a loader, we simply try to add it in a map. We will succeed, if it's first time the chunk is visible by
someone during this pass, and we will silently fail and continue, if it's allready added.
Then we can compare this array with the one from previous tick. Elements that is in a new array, but not in the previous
are just entered the view. Elements that is in a previous but not in a new, are just left the view. And during first
part we also record every visible chunk on a per-loader basis, so we also have a chunks for every loader.
But I just remembered, that we aslo need a NewChunks on a per-loader basis.
New addition: some beautiful stranger in the internet provided a solutuin for "Find elements from two sorted arrays, that are
unique for that arrays" problem that is O(m+n) in worst case.
Ok, So that way we can find:
Visible chunks per loader
Newly visible chunks per loader
Newly visible chunks.
Chunks, that are no more visible.
*/
template<typename T>
std::pair<std::vector<T>, std::vector<T>> FindDifferences(std::vector<T>& A1, std::vector<T>& A2)
{
int i = 0, j = 0;
std::vector<T> A1Unique, A2Unique;
while (i < A1.size() || j < A2.size())
{
if (j >= A2.size()) { A1Unique.push_back(A1[i]); i++; }
else if (i >= A1.size()) { A2Unique.push_back(A2[j]); j++; }
else
{
auto& el1 = A1[i];
auto& el2 = A2[j];
if (el1 != el2)
{
if (el1 < el2) {
A1Unique.push_back(el1);
i++;
}
else
{
A2Unique.push_back(el2);
j++;
}
}
else
{
if (i < A1.size()) { i++; }
if (j < A2.size()) { j++; }
}
}
}
return std::make_pair(A1Unique, A2Unique);
}
class LandscapeChunkController
{
public:
struct ChunkPos
{
int x;
int z;
ChunkPos(int _x, int _z) : x(_x), z(_z) {};
static ChunkPos getChunkFromPoint(float x, float y, float z)
{
return ChunkPos(static_cast<int>(ceil(abs(x)) * (std::signbit(x) ? -1 : 1)) / 16 + (std::signbit(x) ? -1 : 0),
static_cast<int>(ceil(abs(z)) * (std::signbit(z) ? -1 : 1)) / 16 + (std::signbit(z) ? -1 : 0));
}
static ChunkPos getChunkFromPoint(btVector3 vec)
{
return ChunkPos(static_cast<int>(ceil(abs(vec.x())) * (std::signbit(vec.x()) ? -1 : 1)) / 16 + (std::signbit(vec.x()) ? -1 : 0),
static_cast<int>(ceil(abs(vec.z())) * (std::signbit(vec.z()) ? -1 : 1)) / 16 + (std::signbit(vec.z()) ? -1 : 0));
}
friend bool operator<(const ChunkPos& l, const ChunkPos& r)
{
return std::tie(l.x, l.z) < std::tie(r.x, r.z);
}
friend bool operator> (const ChunkPos& lhs, const ChunkPos& rhs) { return rhs < lhs; }
friend bool operator<=(const ChunkPos& lhs, const ChunkPos& rhs) { return !(lhs > rhs); }
friend bool operator>=(const ChunkPos& lhs, const ChunkPos& rhs) { return !(lhs < rhs); }
friend bool operator==(const ChunkPos& lhs, const ChunkPos& rhs) {
return std::tie(lhs.x, lhs.z) == std::tie(rhs.x, rhs.z);
}
friend bool operator!=(const ChunkPos& lhs, const ChunkPos& rhs) { return !(lhs == rhs); }
};
struct LoaderType
{
using LoaderIDType = uint64_t;
private:
static LoaderIDType LastLoaderUniqueID;
public:
std::function<btVector3()> posFunc;
std::vector<ChunkPos> visbleChunks;
std::vector<ChunkPos> newlyVisibleChunks;
LoaderIDType loaderUniqueID;
LoaderType(std::function<btVector3()> _posFunc) : loaderUniqueID(LastLoaderUniqueID++), posFunc(_posFunc) {};
};
private:
std::vector<ChunkPos> m_globalyVisibleChunks;
std::vector<ChunkPos> m_noLongerVisibleChunks;
std::vector<ChunkPos> m_newlyGlobalyVisibleChunks;
std::vector<LoaderType> m_loaders;
int m_loadRadius;
LoaderType* findLoader(LoaderType::LoaderIDType id);
public:
std::vector<std::pair<int, int>> getVisibleChunksOfLoader(LoaderType::LoaderIDType id);
LandscapeChunkController() : m_loadRadius(3){};
inline void setloadRadius(unsigned int newVal) { m_loadRadius = newVal; }
inline LoaderType::LoaderIDType createNewLoader(std::function<btVector3()> PosFunc)
{
m_loaders.emplace_back(PosFunc);
return m_loaders.back().loaderUniqueID;
}
inline bool RemoveLoader(LoaderType::LoaderIDType loaderID)
{
auto Loader = std::find_if(m_loaders.begin(), m_loaders.end(), [&](LoaderType& loader) {return loader.loaderUniqueID == loaderID; });
if (Loader == m_loaders.end()) { return false; }
m_loaders.erase(Loader);
return true;
}
inline std::vector<ChunkPos>& getGlobalyNewlyVisibleChunks() { return m_newlyGlobalyVisibleChunks; }
inline std::vector<ChunkPos>& getGlobalyNoLongerVisibleChunks() { return m_noLongerVisibleChunks; }
void ProcessChunks();
};
} | true |