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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0a7e17df64f57e5b6f924ea977a870487a7e5103 | C++ | aditya803/GFG-Solutions | /MATRIX/MEDIANMATRIX.CPP | UTF-8 | 1,816 | 3.8125 | 4 | [] | no_license | #QUESTION
Given a row wise sorted matrix of size RxC where R and C are always odd, find the median of the matrix.
Example 1:
Input:
R = 3, C = 3
M = [[1, 3, 5],
[2, 6, 9],
[3, 6, 9]]
Output: 5
Explanation:
Sorting matrix elements gives us
{1,2,3,3,5,6,6,9,9}. Hence, 5 is median.
Example 2:
Input:
R = 3, C = 1
M = [[1], [2], [3]]
Output: 2
Your Task:
You don't need to read input or print anything. Your task is to complete the function median() which takes the integers R and C along with the 2D matrix as input parameters and returns the median of the matrix.
Expected Time Complexity: O(32 * R * log(C))
Expected Auxiliary Space: O(1)
Constraints:
1<= R,C <=150
1<= matrix[i][j] <=1000
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#ANSWER
// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
int median(vector<vector<int>> &m, int r, int c){
// code here
int n=r*c,d=0;
vector<int> a(n);
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
a[d]= m[i][j];
d++;
}
}
sort(a.begin(),a.end());
if(n%2==0) return a[n/2+1];
else return a[n/2];
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int r, c;
cin>>r>>c;
vector<vector<int>> matrix(r, vector<int>(c));
for(int i = 0; i < r; ++i)
for(int j = 0;j < c; ++j)
cin>>matrix[i][j];
Solution obj;
cout<<obj.median(matrix, r, c)<<endl;
}
return 0;
} // } Driver Code Ends
| true |
f547935a846fd965b925078d67a3455aba71c10c | C++ | SunnyJaiswal5297/Basic_c_programs | /MCM_Memorization.cpp | UTF-8 | 1,345 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int dp[1001][1001];
int bracket[1001][1001];
void parenthesis(int i,int j,int n,char &ch)
{
if(i>=j)
{
cout<<ch++<<" ";
return ;
}
cout<<"(";
parenthesis(i,bracket[i][j],n,ch);
parenthesis(bracket[i][j]+1,j,n,ch);
cout<<")";
}
int solve_MCM(int a[],int i,int j)
{
if(i>=j)
return 0;
if(dp[i][j]!=-1)
return dp[i][j];
int ans=INT_MAX;
for(int k=i;k<j;k++)
{
int temp=solve_MCM(a,i,k) + solve_MCM(a,k+1,j) + a[i-1]*a[k]*a[j];
if(temp<ans)
{
ans=temp;
bracket[i][j]=k;
}
}
return dp[i][j]=ans;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n],i,j;
for(i=0;i<n;i++)
cin>>a[i];
memset(dp,-1,sizeof(dp));
memset(dp,-1,sizeof(bracket));
int res=solve_MCM(a,1,n-1);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
cout<<dp[i][j]<<" ";
cout<<endl;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
cout<<bracket[i][j]<<" ";
cout<<endl;
}
cout<<res<<endl;
char ch='A';
parenthesis(1,n-1,n,ch);
cout<<endl;
}
return 0;
} | true |
a968329f7ae8d2f3c65c10920fadd26467a44746 | C++ | Mohamed742/C-AIMS-SA-2018 | /second.cpp | UTF-8 | 322 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
#include<cmath>
using namespace std ;
double sumpro(int x,int y){
if (y == 0)
return 1;
else
return x*sumpro(x,y-1);
}
int main(){
int x;
int y;
cout <<"Enter value of x ";
cin >> x;
cout<<"Enter value of y " ;
cin >> y;
cout <<sumpro(x,y)<<endl;
return 0;
}
| true |
8f5472f0f08b34977cb7327dac4cadecee8f74fb | C++ | JehanneDussert/ft_containers_test | /srcs/vector/test_utils.cpp | UTF-8 | 3,276 | 2.875 | 3 | [] | no_license | #include "../../includes/vector_test.hpp"
bool mycomp (char c1, char c2) { return std::tolower(c1)<std::tolower(c2); }
int iterator_traits(std::ofstream &monFlux1, std::ofstream &monFlux2)
{
int err = 0;
typedef std::iterator_traits<int*> traits;
typedef ft::iterator_traits<int*> traits1;
if ((typeid(traits::iterator_category)==typeid(std::random_access_iterator_tag))
== (typeid(traits1::iterator_category)==typeid(std::random_access_iterator_tag)))
{
monFlux1 << "iterator_traits\n\n";
monFlux2 << "iterator_traits\n\n";
}
else
{
err++;
monFlux1 << "\nerror iterator_traits\n";
monFlux2 << "\nerror iterator_traits\n";
}
return err;
}
int is_integral(std::ofstream &monFlux1, std::ofstream &monFlux2)
{
int err = 0;
if (std::is_integral<char>::value == ft::is_integral<char>::value)
;
else
err++;
if (std::is_integral<int>::value == ft::is_integral<int>::value)
;
else
err++;
if (std::is_integral<float>::value == ft::is_integral<float>::value)
;
else
err++;
if (std::is_integral<bool>::value == ft::is_integral<bool>::value)
;
else
err++;
if (!err)
{
monFlux1 << "is_integral done\n\n";
monFlux2 << "is_integral done\n\n";
}
else
{
monFlux1 << "\nerror is_integral\n";
monFlux2 << "\nerror is_integral\n";
}
return err;
}
int lexicographical_compare(std::ofstream &monFlux1, std::ofstream &monFlux2)
{
char s1[] = "Bonjour";
char s2[] = "Bonsoir";
int err = 0;
if (std::lexicographical_compare(s1, s1 + 3, s2, s2 + 2) == ft::lexicographical_compare(s1, s1 + 3, s2, s2 + 2))
;
else
err++;
if (std::lexicographical_compare(s1, s1 + 3, s2, s2 + 2, mycomp) == ft::lexicographical_compare(s1, s1 + 3, s2, s2 + 2, mycomp))
;
else
err++;
if (!err)
{
monFlux1 << "is_integral done\n\n";
monFlux2 << "is_integral done\n\n";
}
else
{
monFlux1 << "\nerror is_integral\n";
monFlux2 << "\nerror is_integral\n";
}
return err;
}
int equal(std::ofstream &monFlux1, std::ofstream &monFlux2)
{
int tab[] = {10, 2, 4, 89};
int tab_err[] = {100, 4628};
std::vector<int> std_v;
ft::vector<int> ft_v;
int err = 0;
std_v.push_back(10); std_v.push_back(2); std_v.push_back(4); std_v.push_back(89);
ft_v.push_back(10); ft_v.push_back(2); ft_v.push_back(4); ft_v.push_back(89);
if (std::equal(std_v.begin(), std_v.end(), tab) == ft::equal(ft_v.begin(), ft_v.end(), tab))
;
else
err++;
if (std::equal(std_v.begin(), std_v.end(), tab_err) == ft::equal(ft_v.begin(), ft_v.end(), tab_err))
;
else
err++;
if (!err)
{
monFlux1 << "equal done\n\n";
monFlux2 << "equal done\n\n";
}
else
{
monFlux1 << "\nerror equal\n";
monFlux2 << "\nerror equal\n";
}
return err;
}
int main(void)
{
std::cout << "utils";
int err = 0;
std::ofstream monFlux1("logs/vector/ft_vector.utils.log");
std::ofstream monFlux2("logs/vector/std_vector.utils.log");
err += iterator_traits(monFlux1, monFlux2);
err += equal(monFlux1, monFlux2);
err += is_integral(monFlux1, monFlux2);
err += lexicographical_compare(monFlux1, monFlux2);
if (err)
std::cout << "\t\t\e[0;31m[💥]\e[0m";
else
std::cout << "\t\t\e[0;32m[⭐️]\e[0m";
monFlux1.close();
monFlux2.close();
std::cout << "\n";
return 0;
}
| true |
bb3b9fb2c0aae389d4b9403d91e81300a8e6df92 | C++ | DaEunKim/SW_coding | /2178미로탐색_2/2178미로탐색_2/main.cpp | UTF-8 | 1,362 | 2.78125 | 3 | [] | no_license | //
// main.cpp
// 2178미로탐색_2
//
// Created by 김다은 on 2020/03/26.
// Copyright © 2020 김다은. All rights reserved.
//
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int N, M;
int vis[101][101] = {0,};
int arr[101][101] = {0,};
queue<pair<int, int>> q;
void bfs(int a, int b){
q.push(make_pair(a, b));
vis[a][b] = 1;
while (!q.empty()) {
int nx = q.front().first;
int ny = q.front().second;
q.pop();
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
for(int i = 0;i<4;i++){
int x = nx + dx[i];
int y = ny + dy[i];
if(x<0 || y<0 || x>=N || y>=M)
continue;;
if(!vis[x][y] && arr[x][y]==1){
vis[x][y] = vis[nx][ny] + 1;
q.push(make_pair(x, y));
}
}
}
}
int main(int argc, const char * argv[]) {
cin >> N >>M;
string s;
for(int i = 0;i<N;i++){
cin >> s;
for(int j = 0;j<M;j++){
arr[i][j] = (int)(s.at(j) -'0');
}
}
for(int i = 0;i<N;i++){
for(int j = 0;j<M;j++){
if(!vis[i][j] && arr[i][j] == 1){
bfs(i, j);
}
}
}
cout<< vis[N-1][M-1] <<endl;
}
| true |
2b141c88d52d0cb591344dda265c596921b9ebd8 | C++ | EvanMcGorty/expression-evaluator | /documentation/minimal_example.cpp | UTF-8 | 2,641 | 3.359375 | 3 | [] | no_license | /*
this is a simple, minimal example use of the evaluator
when the terminal opens, try entering the following lines:
_funcs
prod(2,3)
push(8.4)
=my_double/
swap(=my_double,num.make(3.14))
=my_double
push(prod(=my_double,-1/2))
rotate(=my_double)
=my_double
print(glv)
swap(=my_vec/,vec.copy-make(glv))
vec.append(=my_vec,vec.list-make(12345))
print(=my_vec)
vec.swap(glv,=my_vec)
print(=my_vec)
rotate(=my_double)
vec.swap(glv,=my_vec)
print(=my_vec)
=my_vec\
_garb(=g/)
=g
drop(=g)
=g
_garb(=g)
=g
=my_double\
_garb(=g)
=g
strong(num.make(4))
_garb(=g)
=g
drop(=g\)
_exit
*/
#include <vector>
#include <iostream>
#include"../include/expression-evaluator/evaluator.h"
using namespace expr;
double multiply(double a, double b)
{
return a * b;
}
std::vector<double> global_vector;
void push(double a)
{
global_vector.push_back(a);
}
void rotate(double &a)
{
for (double &i : global_vector)
{
std::swap(a, i);
}
}
void print(std::vector<double> const &w)
{
for (auto const &i : w)
{
std::cout << i << '\n' << std::flush;
}
}
int main()
{
std::cout << "this code will run before the evaluator is used\n" << std::flush;
//by default uses a global rename dataset
declare_with_name<double>("num");
declare<std::vector<double>>();
//the environment that will hold variables and functions
environment env;
//use imports a function set. an empty string means to not use a namespace
env.functions.use<core>("").use<cpp_core>("")
//util<t> wraps t and provides basic functions. by not providing a string, the evaluator chooses a default name.
.use<util<std::vector<double>>>()
.use<util<double>>()
//a pretty syntax for binding functions. sfn takes a function pointer and turns it into something that env can use.
<< "prod" << sfn(multiply)
<< "push" << sfn(push)
<< "rotate" << sfn(rotate)
<< "print" << sfn(print)
//val creates a function that returns a copy of the value it is passed. passing a pointer to global_vector gives write access to the caller.
<< "glv" << refto(global_vector);
//there are alternate ways to expresss binding functions.
//function sets can also be imported with the << syntax using fs_functs
//and functions can be bound with method syntax with .add
//interpreter is a more complicated environment that interacts with iostreams and has settings (with default settings and cout/cin).
interpreter{ std::move(env) }.go();
std::cout << "this code will run after the user calls _exit from the interpreter\n" << std::flush;
char a;
std::cin >> a;
} | true |
166f604dba68340f2a36d49df5862108454401c1 | C++ | SangaviPandian/vowel1 | /digit.cpp | UTF-8 | 201 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int num,n=0;
cout<<"enter the number";
cin>>num;
while(num>0)
{
num=num/10;
n++;
}
cout<<"no of digits in an integer"<<n;
return 0;
}
| true |
48696ae66fd6768e728f2586b2afba5dd0bd17ec | C++ | t3kt/bkb | /bkbTextureTool/src/main.cpp | UTF-8 | 1,735 | 2.828125 | 3 | [] | no_license | #include <ofMain.h>
#include <ofxOBJModel.h>
#include <sstream>
#include <iomanip>
static void generateImage(const ofxOBJFace& face, int i) {
ofFbo fbo;
fbo.allocate(1024, 1024);
fbo.begin();
ofClear(ofFloatColor(0, 0, 0, 0));
ofPath path;
path.setColor(ofFloatColor(1, 1, 1, 1));
bool first = true;
for (const auto& uv : face.texCoords) {
if (first) {
path.moveTo(uv.x * 1024, uv.y * 1024);
first = false;
} else {
path.lineTo(uv.x * 1024, uv.y * 1024);
}
}
path.setFilled(true);
path.close();
path.draw();
fbo.end();
ofImage image;
image.allocate(1024, 1024, OF_IMAGE_COLOR_ALPHA);
fbo.readToPixels(image.getPixelsRef());
std::ostringstream name;
name << "segment-";
name << std::setw(3) << std::setfill('0') << std::right << i;
name << ".tif";
ofFile file(name.str(), ofFile::WriteOnly, true);
if (file.exists())
file.remove();
ofLogVerbose() << "writing image: " << file.path();
image.saveImage(file);
}
static void generateImages(const ofxOBJGroup& group, int& i) {
ofLogVerbose() << "writing group images: " << group.name;
for (const auto& face : group.faces) {
generateImage(face, i);
i++;
}
}
int main( ){
// for some reason without calling this, the data root path doesn't get
// set up properly and i don't feel like figuring out why
ofSetupOpenGL(1024,1024,OF_WINDOW);
ofSetLogLevel(OF_LOG_VERBOSE);
ofxOBJModel model;
model.load("bowl_walls.obj");
for (auto& name : model.getGroupNames()) {
ofLogVerbose() << "group: " << name;
}
int i = 0;
generateImages(*model.getGroup("left_wall"), i);
generateImages(*model.getGroup("right_wall"), i);
generateImages(*model.getGroup("middle_wall"), i);
}
| true |
27971c632043d8fc2cff22f672aa485354b664e6 | C++ | bartekz93/JumpAndRun | /JumpAndRun/Source/Renderer/Particles.cpp | UTF-8 | 2,350 | 2.65625 | 3 | [] | no_license | #pragma once
#include<time.h>
#include"Particles.h"
#include"../Framework/Messages.h"
using namespace FRAMEWORK;
using namespace RENDERER;
int super_rand()
{
return (rand() << 15) | rand();
}
float fRandom(float beg, float end)
{
UINT f = (end-beg)*100;
if (!f) return beg;
return (float)((super_rand()%f) + beg*100)/100;
}
Vec2 vRandom(Vec2 beg, Vec2 end)
{
float x = fRandom(beg.x, end.x);
float y = fRandom(beg.y, end.y);
return Vec2(x, y);
}
int iRandom(int beg, int end)
{
UINT i = end-beg;
if (!i) return 0.0f;
return (rand()%(i))+beg;
}
void ParticleEmitter::SetDesc(ParticleEmitterDesc& desc)
{
srand(time(NULL));
Desc = &desc;
Particles = new Particle[desc.MaxParticles];
for (UINT i=0;i<desc.MaxParticles;i++)
{
Particles[i].Age = 0.2f;
Particles[i].Dir = desc.Dir;
}
}
void ParticleEmitter::Clear()
{
Particle* p;
for (UINT i=0;i<Desc->MaxParticles;i++)
{
p = &Particles[i];
p->Age = p->LifeTime;
}
}
void ParticleEmitter::Update(float dt, bool c)
{
dt *= Desc->SimulationSpeed;
Particle* p;
for (UINT i=0;i<Desc->MaxParticles;i++)
{
p = &Particles[i];
float t = (p->Age / p->LifeTime);
if (p->Age + dt <= p->LifeTime && p->Age != 0.0f)
{
//if (p->Dir != Vec2(0.0f, 0.0f)) p->Dir = p->Dir.Normalize();
p->Color = (Desc->Color - Desc->Color0) * t + Desc->Color0;
p->Angle = (Desc->Angle - Desc->Angle0) * t + Desc->Angle0;
p->Alpha = (Desc->Alpha - Desc->Alpha0) * t + Desc->Alpha0;
p->Pos += p->Dir * p->Velocity * dt;
}
else if (c)
{
p->LifeCount ++;
p->Dir = Desc->Dir != Vec2(0.0f, 0.0f) ? Desc->Dir.Normalize() : p->Dir;
p->Pos = vRandom(Vec2(Pos.x-Desc->Width/2, Pos.y-Desc->Height/2),
Vec2(Pos.x+Desc->Width/2, Pos.y+Desc->Height/2));
//p->Dir = vRandom(Desc->Dir0, Desc->Dir);
if (Desc->Spread)
{
float a = ( fRandom(0.0f, Desc->Spread) - Desc->Spread*0.5 ) * (PI / 180.0f) + asinf(Desc->Dir.x);
p->Dir.y = -cos(a);
p->Dir.x = sin(a);
}
p->LifeTime = fRandom(Desc->LifeTime0, Desc->LifeTime);
p->Velocity = fRandom(Desc->Velocity0, Desc->Velocity);
p->Alpha = Desc->Alpha0;
p->Age = 0.2f;
}
//if (p->LifeCount > Desc->MaxLifeCount) continue;
Particles[i].Age += dt;
}
}
void ParticleEmitter::Release()
{
if (Particles) delete[] Particles;
} | true |
edcfd57a66eeea78aac6b7c6d4408f5aecc5319f | C++ | malvarez27/lmu-cmsi386 | /homework3/say.cpp | UTF-8 | 507 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <cassert>
using namespace std;
struct Adder {
//private:
string phrase = "";
public:
Adder operator()(string word) {
return Adder {phrase + (phrase != "" ? " " : "") + word };
}
string operator()() {
return phrase;
}
};
Adder f;
int main() {
assert(f() == "");
assert(f("all")() == "all");
assert(f("hi")("you")() == "hi you");
assert(f("all")("your")("tests")("pass")() == "all your tests pass");
cout << "Yep, all tests passed, LIT AF!\n";
}
| true |
9026c895d02d8a9400abadf54da772b9da5c82be | C++ | arshjot/Cpp-Practice | /Accelerated-Cpp/ch_5/ex_5-1/src/rotate.cpp | UTF-8 | 1,016 | 3.515625 | 4 | [] | no_license | #include <string>
#include <vector>
#include <numeric>
#include "rotate.h"
#include "split.h"
using std::string;
using std::accumulate;
using std::vector;
using std::copy;
// function to define the comparison of splitted strings
// comparison to be done in lowercase
bool compare(const Rotated_line& x, const Rotated_line& y)
{
return x.second_half < y.second_half;
}
vector<Rotated_line> rotate(const vector<string>& lines)
{
vector<string> line;
vector<Rotated_line> rot_lines;
// Loop over all the lines
for (vector<string>::size_type li=0; li!=lines.size(); ++li) {
// Split the line into words
line = split(lines[li]);
// Rotate the line and split each instance into two halves
for (vector<string>::size_type wi=0; wi!=line.size(); ++wi) {
Rotated_line rot;
rot.first_half.insert(rot.first_half.begin(), line.begin(), line.begin() + wi);
rot.second_half.insert(rot.second_half.begin(), line.begin() + wi, line.end());
rot_lines.push_back(rot);
}
}
return rot_lines;
}
| true |
7af4a3d83ca5704bd40bcbaf9704a7041f262b5c | C++ | Kangar000/KangIsaac_CSC5_Summer16_42576 | /Homework/Assignment_2/Gaddis_7thEd_Chapter3_Problem11_Currency/main.cpp | UTF-8 | 885 | 3.890625 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Isaac Kang
* Created on July 5, 2016, 2:36 PM
* Purpose: Currency
*/
//System Libraries
#include <iostream> //Input/Output Library
#include <iomanip>
using namespace std; //Namespace of the System Libraries
//User Libraries
//Global Constants
//Function Prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Declare Variables
float dollars, yen, euros;
//Input Data
cout << "Enter U.S. Dollars to convert to Yen and Euros: " << endl;
cin >> dollars;
//Process the Data
yen = dollars / 113.22;
euros = dollars / 0.6936;
//Output the processed Data
cout << "Amount in Yens is: " << fixed << setprecision(2) << showpoint << yen << endl;
cout << "Amount in Euros is: " << fixed << setprecision(2) << showpoint << euros << endl;
//Exit Stage Right!
return 0;
} | true |
63a086e2cf235d58797cfac8ba9a64522fcccaaa | C++ | dwivedir/coding | /codeforces/340D.cpp | UTF-8 | 669 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;
vector<int> seq;
int binary(int p,int q, int x)
{
if(q<p) return -1;
if(p==q)
{
if(seq[p] >= x) return p;
return -1;
}
int mid = (p+q)/2;
if(seq[mid]>=x)
return binary(p,mid,x);
else
return binary(mid+1,q,x);
}
int main()
{
int n,array[100005];
cin>>n;
for(int i=1; i<=n; i++)
cin>>array[i];
for(int i=1; i<=n; i++)
{
if(seq.empty() || seq[seq.size()-1] < array[i])
seq.push_back(array[i]);
else
{
int position = binary(0,seq.size()-1,array[i]);
seq[position] = array[i];
}
}
cout<<seq.size();
return 0;
}
| true |
8a84e91dc17500fbaceb37c3692e24c165f5e6cc | C++ | kmichaelfox/phase_01 | /src/ScoreManager.hpp | UTF-8 | 1,037 | 2.53125 | 3 | [] | no_license | //
// ScoreManager.hpp
// phase_01
//
// Created by Kelly Fox on 5/9/16.
//
//
#ifndef ScoreManager_hpp
#define ScoreManager_hpp
#include <iostream>
#include <vector>
#include "Player.hpp"
#include "ScoreScene.hpp"
class ScoreManager {
ScoreScene scene;
std::vector<Player *> players;
Sequence seq;
ofArduino ard;
bool bSetupArduino;
int numPlayers = 0;
int dimensions = 1;
float windowAspect;
int activePlayer = -1;
public:
ScoreManager();
~ScoreManager();
void draw();
void update();
void resize(int w, int h);
void addPlayer(Player * p);
void newSequence();
void activate(int playerNum);
void pause();
void resume();
void stop();
int getNumPlayers();
void setPlayerTempo(int playerNum, float tempo);
// arduino callbacks
void setupArduino(const int & version);
void analogPinChanged(const int & pinNum);
void updateArduino();
std::string analogVal;
};
#endif /* ScoreManager_hpp */
| true |
513505129f4ab352f1d1f1855555b5ff9b4e0d71 | C++ | hshachor/CPP-Lab | /Algorithms/removeIf.cpp | UTF-8 | 678 | 3.8125 | 4 | [] | no_license | // remove_if & remove_copy example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int myints[] = { 9,20,35,30,20,12,10,20 };
int* pbegin = myints;
int* pend = myints + 8;
pend = remove_if(pbegin, pend, [](int x) {return x % 3 == 0; });
cout << "range contains:";
for (int* p = pbegin; p != pend; ++p)
cout << ' ' << *p;
cout << endl;
vector<int> myvector(pend - pbegin);
remove_copy(myints, myints + (pend - pbegin), myvector.begin(), 20);
cout << "myvector contains:";
for (auto it = myvector.begin(); it != myvector.end(); ++it)
cout << ' ' << *it;
return 0;
} | true |
b612281406b26325d83e7045d1feda9f60c0efb6 | C++ | MdAbuNafeeIbnaZahid/Competitive-Programming | /CODEFORCES/Educational Codeforces Round 21/808 B. Average Sleep Time.cpp | UTF-8 | 1,238 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
#include <ext/pb_ds/detail/standard_policies.hpp>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
// Order Statistic Tree
/* Special functions:
find_by_order(k) --> returns iterator to the kth largest element counting from 0
order_of_key(val) --> returns the number of items in a set that are strictly smaller than our item
*/
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
/****** END OF HEADER *********/
#define SIZE 200009
long long n, k, aAr[SIZE];
long long sleepCnt, weekCnt, sum[SIZE];
double ans;
int main()
{
// freopen("input.txt", "r", stdin);
long long a, b, c, d, e, f;
cin >> n >> k;
for (a = 1 ; a <= n; a++)
{
scanf("%lld", &aAr[a]);
sum[a] = sum[a-1] + aAr[a];
}
for (a = 1; a <= n; a++)
{
b = a + k -1;
if (b > n)
{
break;
}
sleepCnt += (sum[b] - sum[a-1] );
weekCnt++;
}
ans = (1.0 * sleepCnt) / weekCnt;
printf("%0.8lf", ans);
return 0;
}
| true |
fee6aebb5116eeab4977cf7cf982e0041477e961 | C++ | Girl-Code-It/Beginner-CPP-Submissions | /Aayushi/milestone 5/check for prime number.cpp | UTF-8 | 696 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num, i, prime;
cout<<"enter a number : \n";
cin>>num;
for(i=2; i<num; i++) //a prime number is divisible by 1 and the number itself only
{
if(num%i==0)
{
prime=0; //prime is a flag variable.
break; // if prime=1 it is prime.
} // if prime=0 it is not prime.
else
{
prime=1;
}
}
if(prime==1)
{
cout<<"it is a prime number.";
}
else
{
cout<<"it is not a prime number.";
}
return 0;
}
| true |
d66335768057301f6498eaabffc62ae1c469a09d | C++ | metal32/tutorial_c | /smart_pointers/unique_pointer.cpp | UTF-8 | 350 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<memory>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle(int x, int y): width(x), height(y) {}
int area() {
return width * height;
}
};
int main() {
unique_ptr<Rectangle> p1(new Rectangle(5, 10));
unique_ptr<Rectangle> p2;
p2 = move(p1);
cout<<p2->area()<<endl;
return 0;
} | true |
c54bbdaaa40701e7e7f33949ed566613f63b3d4b | C++ | UPC-DESARROLLO-JUEGOS-1/DJ1-2017-II-TileEngine3D | /EngineUPC/FrameworkUPC/Vector3.h | UTF-8 | 2,211 | 3.265625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <math.h>
#include <glm\glm.hpp>
#include <glm\gtc\type_ptr.hpp>
class Vector3
{
public:
Vector3()
{
this->x = 0;
this->y = 0;
this->z = 0;
}
Vector3(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
~Vector3() {}
float x, y, z;
float Magnitude()
{
return sqrtf(x*x + y*y + z*z);
}
Vector3 Direction(Vector3 other)
{
float magnitude = Magnitude();
Vector3* result = new Vector3(0, 0, 0);
result->x = (other.x - x) / magnitude;
result->y = (other.y - y) / magnitude;
result->z = (other.z - z) / magnitude;
return *result;
}
Vector3 Normalize()
{
float magnitude = Magnitude();
return Vector3(x / magnitude, y / magnitude, z / magnitude);
}
static Vector3 Transform(Vector3 position, glm::mat4 matrix)
{
float* mtxPtr = glm::value_ptr(matrix);
return Vector3(
(position.x * *(mtxPtr + 0)) + (position.y * *(mtxPtr + 4)) + (position.z * *(mtxPtr + 8)) + *(mtxPtr + 12),
(position.x * *(mtxPtr + 1)) + (position.y * *(mtxPtr + 5)) + (position.z * *(mtxPtr + 9)) + *(mtxPtr + 13),
(position.x * *(mtxPtr + 2)) + (position.y * *(mtxPtr + 6)) + (position.z * *(mtxPtr + 10)) + *(mtxPtr + 14));
}
Vector3 Normalize(float magnitude) {}
Vector3 operator+(const Vector3& b) {
Vector3 vector;
vector.x = this->x + b.x;
vector.y = this->y + b.y;
vector.z = this->z + b.z;
return vector;
}
Vector3 operator-(const Vector3& b) {
Vector3 vector;
vector.x = this->x - b.x;
vector.y = this->y - b.y;
vector.z = this->z - b.z;
return vector;
}
Vector3 operator/(const Vector3& b) {
Vector3 vector;
vector.x = this->x / b.x;
vector.y = this->y / b.y;
vector.z = this->z / b.z;
return vector;
}
Vector3 operator*(const Vector3& b) {
Vector3 vector;
vector.x = this->x * b.x;
vector.y = this->y * b.y;
vector.z = this->z * b.z;
return vector;
}
static const Vector3 Zero;
static const Vector3 One;
static const Vector3 UnitX;
static const Vector3 UnitY;
static const Vector3 UnitZ;
static const Vector3 Up;
static const Vector3 Down;
static const Vector3 Right;
static const Vector3 Left;
static const Vector3 Forward;
static const Vector3 Backward;
}; | true |
c957912fa48e781ab457822976cfbb6f836e5121 | C++ | geg-antonyan/IntegerCalculator | /IntegerCalculator/src/utilites/EventData.h | WINDOWS-1251 | 729 | 2.859375 | 3 | [] | no_license | /* *** EventData.h ***
Event .
() CommnadDispatcher
*/
#ifndef EVENT_H
#define EVENT_H
#include <string>
class Event
{
public:
virtual ~Event() { }
protected:
Event() { }
};
class CommandEnteredEvent : public Event
{
public:
CommandEnteredEvent(std::string& command) : command_(command)
{ }
const std::string command() const { return command_; }
private:
std::string command_;
};
#endif // EVENT_H
| true |
872f8670ef2f6cfaf9cae630188146aaaeeb07f3 | C++ | sebseb7/gorge | /old-code/src/badguy.hpp | UTF-8 | 1,745 | 2.828125 | 3 | [] | no_license | class Bullet : public Object {
public:
Bullet(Vec2 pos, Vec2 velocity) {
init("media/bullet.png");
setPosition(pos);
vel = velocity;
playSound("media/bullet.wav", pos);
alive = true;
}
virtual bool update() {
move(vel);
updateCollisionPoly();
Vec2 pos = getPosition();
if (walls.checkCollision(poly) > 0) {
makeParticle<Hit>(pos);
return false;
}
if (pos.x < -40 || pos.x > 840) return false;
if (pos.y < -40 || pos.y > 640) return false;
return alive;
}
void die() { alive = false; }
protected:
Bullet() { alive = true; }
Vec2 vel;
bool alive;
virtual const Poly& getCollisionModel() const {
static const Poly model = {
Vec2(1, 1),
Vec2(1, -1),
Vec2(-1, -1),
Vec2(-1, 1),
};
return model;
}
};
extern std::forward_list<std::unique_ptr<Bullet>> bullets;
template<typename T, typename... Args>
void makeBullet(Args&&... args) {
bullets.emplace_front(std::unique_ptr<Bullet>(new T(args...)));
}
class BadGuy : public Object {
public:
BadGuy(int shield, int score)
: shield(shield), score(score) {}
virtual void takeHit(int damage) {
shield -= damage;
if (shield <= 0) {
player.raiseScore(score);
makeParticle<Explosion>(getPosition());
}
}
protected:
int shield;
bool checkCollisionWithLaser() {
for (auto& laser : lasers) {
if (checkCollision(*laser) > 0) {
makeParticle<Hit>(laser->getPosition());
laser->die();
takeHit(laser->getDamage());
if (shield <= 0) break;
}
}
return shield > 0;
}
private:
const int score;
};
extern std::forward_list<std::unique_ptr<BadGuy>> badGuys;
template<typename T, typename... Args>
void makeBadGuy(Args&&... args) {
badGuys.emplace_front(std::unique_ptr<BadGuy>(new T(args...)));
}
| true |
d7c1de603c4f58db6e9130017d717596bc0f5aad | C++ | KaushalPrajapat/Programming_CPP | /Using_CPP/CPP Advance/Initializer.cpp | UTF-8 | 631 | 3.78125 | 4 | [] | no_license | //initializer used to initialize a variable with some value
//initializer have to used in class when a const variable is decleard\
//Kaushal Prjapat 10.05.2021
//Example
#include<iostream>
using namespace std;
class test
{
private:
int var1=12;
const int var2; // We can't initialize a cont variable here
public:
test():var2(10) // This is use of initializer
//We can't assign any value to var2 without this method
{
var1=15;
}
void view()
{
cout<<"Var1 is : "<<var1<<endl<<"Var2 is : "<<var2;
}
};
int main()
{
cout<<"----------------KAUSHAL PRAJAPAT----------------------"<<endl;
test t1;
t1.view();
}
| true |
d7141d23031efb0e4e405df2d430b1a8b8536486 | C++ | Uros2323/System-Software | /assembly/src/main.cpp | UTF-8 | 864 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "AssemblyParser.h"
using namespace std;
#include <regex>
int main(int argc, const char *argv[])
{
string input_file;
string output_file;
string current = argv[1];
// cout << argv[1] << "#-o" << endl;
// cout << argv[2] << endl;
// cout << argv[3] << endl;
// cout << strcmp(argv[1], "-o") << endl;
if (current == "-o")
{
input_file = argv[3];
output_file = argv[2];
}
else
{
cout << "Output file does not exists!" << endl;
return -1;
}
AssemblyParser as(input_file, output_file);
if (as.compile() == false)
{
as.print_error_messages();
return -1;
}
as.print_symbol_table();
as.print_relocation_table();
as.print_section_table();
as.print_section_data();
return 0;
} | true |
c46873324853dccc83e788a3d3aaa8b718841c6e | C++ | MirunaRux/Dynamic-Programming | /prob2.cpp | UTF-8 | 2,725 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <limits.h>
using namespace std;
fstream f("date.in", ios :: in);
fstream g("date.out", ios :: out);
const int NMAX = 100;
int n, m, table[NMAX][NMAX], smax[NMAX][NMAX];
void citire()
{
f>>n>>m;
for(int i = 1; i <= n ; i++)
for(int j = 1; j <= m; j++)
f>>table[i][j];
f.close();
}
int max(int a, int b, int c)
{
int vmax = a;
if(b > vmax) vmax = b;
if(c > vmax) vmax = c;
return vmax;
}
int verif(int i, int j)
{
if(i > n || i < 1)
return INT_MIN;
else
return smax[i][j];
}
///functia intoarce acum linia pe care se afla maximul, deoarece am nevoie de ea cand reconstitui solutia
int determinare_maxim()
{
for(int i = 1; i <= n; i++)
smax[i][m] = table[i][m];
///matricea smax se completeaza pe coloane
for(int j = m - 1; j >= 1; j--)
for(int i = 1; i <= n; i++)
smax[i][j] = table[i][j] + max(verif(i - 1, j + 1), verif(i, j + 1), verif(i + 1, j + 1));
int maxx = smax[1][1];
int lmax = 1;
for(int i = 1; i <= n; i++)
if(maxx < smax[i][1])
{
maxx = smax[i][1];
lmax = i;
}
return lmax;
}
int coord_max(int i, int j, int &lin)
{
///functia intoarce numarul aparitiilor maximului intre cele 3 valori vecine, ca sa vezi daca solutia este unica sau nu
int k = 0;
if(smax[i - 1][j + 1] == max(smax[i - 1][j + 1], smax[i][j + 1], smax[i + 1][j + 1]))
lin = i - 1, k++;
if(smax[i][j + 1] == max(smax[i - 1][j + 1], smax[i][j + 1], smax[i + 1][j + 1]))
lin = i, k++;
if(smax[i + 1][j + 1] == max(smax[i - 1][j + 1], smax[i][j + 1], smax[i + 1][j + 1]))
lin = i + 1, k++;
return k;
}
///gasirea unui drum optim este mult mai simpla si nu necesita recursivitate neaparat
///practic, la fiecare pas, selectez linia de unde a fost selectat maximul in calculul lui smax
void drum_optim(int pmax)
{
int lcrt = pmax;
bool sol_unica = true;
for(int i = 1; i < m; i++)
{
g << lcrt << " " << i << endl;
int k = coord_max(lcrt, i, lcrt);
if(k != 1)
sol_unica = false;
}
///pentru ultima coloana nu mai calculez succesorul
g << lcrt << " " << m << endl;
g << (sol_unica ? "Traseul optim este unic" : "Traseul optim nu este unic");
g.close();
}
int main()
{
citire();
int pmax = determinare_maxim();
///maximul se gaseste pe linia pmax a primei coloane din smax
g << smax[pmax][1]<<'\n';
drum_optim(pmax);
g.close();
return 0;
}
| true |
5abd418cc4ba204e6e6a90f62863a1cf360a1ce7 | C++ | darkassazi/CourseDashboard | /src/models/AccountDAO.cpp | UTF-8 | 1,500 | 2.765625 | 3 | [] | no_license |
#include "AccountDAO.hpp"
AccountDAO::AccountDAO(
const String& email,
const ID& profileID,
const ID& id)
: m_Email(email),
m_ProfileID(profileID),
m_ID(id)
{}
//---------------------------------------------------------------------------------------
String AccountDAO::toString() const {
return "ID: " + std::to_string(m_ID) +
"\nProfileID: " + std::to_string(m_ProfileID) +
"\nEmail: " + m_Email +
"\n";
}
//---------------------------------------------------------------------------------------
const ID& AccountDAO::getID() const {
return m_ID;
}
//---------------------------------------------------------------------------------------
const ID& AccountDAO::getProfileID() const {
return m_ProfileID;
}
//---------------------------------------------------------------------------------------
const String& AccountDAO::getEmail() const {
return m_Email;
}
//---------------------------------------------------------------------------------------
void AccountDAO::setID(const ID& id) {
m_ID = id;
}
//---------------------------------------------------------------------------------------
void AccountDAO::setProfileID(const ID& studentID) {
m_ProfileID = studentID;
}
//---------------------------------------------------------------------------------------
void AccountDAO::setEmail(const String& email) {
m_Email = email;
}
| true |
f4bbe2cb024fe8ed92d32a6f99bfb52daf2af534 | C++ | KamalDGRT/ProgrammingPractice | /Fundamentals_Of_Programming/08_2D_Array/Question_14/question_14.cpp | UTF-8 | 364 | 2.78125 | 3 | [
"MIT"
] | permissive | // Uniformity Matrix
#include <iostream>
using namespace std;
int main() {
int n, i, j, c = 0;
int a[5][5];
cin >> n;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
cin >> a[i][j];
if (a[i][j] % 2)
c++;
}
(c == 0 || c == (n * n)) ? cout << "Yes" : cout << "No";
return 0;
}
| true |
83441f4827de3be0aa0e2d4ae281f156e993a166 | C++ | amandewatnitrr/Cpp | /String/identifying_and_counting_max_occurance_of_char_in_string.cpp | UTF-8 | 544 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <ctype.h>
using namespace std;
int main()
{
string str;
cout<<"\nEnter the string --> ";
getline(cin,str);
char maxc='a';
int count=0,max=0;
for(int i=97;i<=123;i++)
{
count = 0;
for(int j=0;j<str.length();j++)
{
if(str[j]==(char)i)
{
count++;
}
if(count>max)
{
max=count;
maxc = (char)i;
}
}
}
cout<<"\nThe character that appeared most of the time is "<<maxc<<" and it appeared "<<max<<" times.\n";
return 0;
}
| true |
e9ff00a114f6f944c14c84468d9868b9745ecacf | C++ | sienkiewiczkm/shabui | /source/cli/Main.cpp | UTF-8 | 678 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include "shabui/GLSLLoader.hpp"
int main(int argc, char **argv)
{
if (argc == 1)
{
std::cout << "usage: " << argv[0] << " shaderfile";
return EXIT_FAILURE;
}
sb::GLSLLoaderFileDependencyResolver resolver{argv[1]};
sb::GLSLLoader loader{resolver};
auto result = loader.loadFile(argv[1]);
std::cerr << "Vertex Shader Output:" << std::endl;
std::cerr << result.vertexShaderCode << std::endl;
std::cerr << "Fragment Shader Output:" << std::endl;
std::cerr << result.fragmentShaderCode << std::endl;
return EXIT_SUCCESS;
}
| true |
be822c1cee6fa752129a3637d431812ab308da79 | C++ | xjayleex/problem_solving | /boj/data_structure/boj9202/main.cpp | UTF-8 | 3,817 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <memory.h>
#include <algorithm>
using namespace std;
bool compare(const string &a, const string &b){
if(a.length() == b.length()){
return a < b;
} else {
return a.length() > b.length();
}
}
int toNumber(char ch) {
return ch - 'A';
}
struct Trie {
bool isTerminal; bool isHit;
Trie* child[26];
Trie() : isTerminal(false), isHit(false) {
memset(child,0,sizeof(child));
}
~Trie(){
for(int i = 0 ; i < 26 ; i++) {
if(child[i]) delete child[i];
}
}
void insert(const char *key){
if(*key =='\0'){
isTerminal = true;
}else {
int next = toNumber(*key);
if (child[next] == NULL){
child[next] = new Trie();
}
child[next]->insert(key+1);
}
}
Trie *find(const char *key){
if(*key == '\0')
return this;
int next = toNumber(*key);
if(child[next] == NULL)
return NULL;
return child[next]->find(key+1);
}
};
int dx [8] = {0,1,1,1,0,-1,-1,-1};
int dy [8] = {-1,-1,0,1,1,1,0,-1};
int scoring[9] = {0,0,0,1,1,2,3,5,11};
Trie *trie;
//vector <bool> isHit;
vector <string> ansList;
void dfs(int x, int y, string made, int len, vector<vector<bool>> &visited, const vector<string> &board) {
Trie *tp = trie->find(made.c_str()); // trie에서 현재까지 만들어진 문자열을 찾아.
if(tp == NULL) { // 그게 NULL 이면 더 볼 필요 없으니까 리턴
return;
} else { // 존재한다면,
if(tp->isTerminal) { // 종료점인지 검사해보자.
// Hit, and no return needed.
// map에 단어 추가.
if(!tp->isHit){
ansList.push_back(made);
tp->isHit = true;
}
}
}
if(len >= 8)
return;
for(int k = 0 ; k < 8 ; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if(nx < 0 || ny < 0 || nx >= 4 || ny >= 4)
continue;
if(visited[ny][nx])
continue;
visited[ny][nx] = true;
dfs(nx,ny,made+board[ny][nx],len+1,visited,board);
visited[ny][nx] = false;
}
}
int main() {
int W,B; string in;
scanf("%d",&W);
vector <string> words(W);
trie = new Trie();
for(int i = 0 ; i < W ; i++) {
cin >> in;
trie->insert(in.c_str());
words[i] = in;
}
cin >> B;
for(int k = 0 ; k < B ; k++){
/*cout << "-----------pre-test------------" <<'\n';
for(int j = 0 ; j < words.size();j++){
if(trie->find(words[j].c_str())->isHit) {
cout << words[j] << " Hit : On" <<'\n';
} else {
cout << words[j] << " Hit : Off" <<'\n';
}
}
cout << "-------------------------------" <<'\n';*/
vector<string> board;
vector<vector<bool>> visited(4,vector<bool>(4,false));
for(int j = 0 ; j < 4 ;j++){
cin >> in;
board.push_back(in);
}
for(int y = 0 ; y < 4; y++){
for(int x = 0; x < 4 ; x++) {
visited[y][x] = true;
dfs(x,y,string(1,board[y][x]),1,visited,board);
visited[y][x] = false;
}
}
sort(ansList.begin(),ansList.end(),compare);
int score = 0;
for (int j = 0 ; j < ansList.size();j++){
score += scoring[ ansList[j].length() ];
}
cout << score << ' ' << ansList[0] << ' ' << ansList.size() << '\n';
for (int j = 0 ; j < ansList.size();j++) {
trie->find(ansList[j].c_str())->isHit = false;
}
ansList.clear();
}
return 0;
} | true |
873e89cc66b8330bd0b37119f85d9ac0ea3e4430 | C++ | ShubhJ-coder/ELEC2018-19 | /NeoPixel/NeoPixel.ino | UTF-8 | 844 | 2.578125 | 3 | [] | no_license | // NeoPixel test sketch
// UBC: the UBC Submarine Design Team
#include <Adafruit_NeoPixel.h>
#define JEWEL_PIN 7
#define NEOPIXEL_COUNT 7
Adafruit_NeoPixel jewel(NEOPIXEL_COUNT, JEWEL_PIN, NEO_GRB + NEO_KHZ800);
int i=0,j=0;
uint32_t settings[3]={jewel.Color(153,51,0),jewel.Color(0,0,102),jewel.Color(128,0,128)};
uint32_t red;
void setup() {
jewel.begin();
//jewel.fill(jewel.Color(255, 0, 255));
jewel.setPixelColor(0,jewel.Color(0,154,50));
jewel.setBrightness(20);
jewel.show();
red=jewel.Color(255,0,0);
}
void loop() {
for (j=0;j<3;j++){
for (i=1;i<NEOPIXEL_COUNT;i++){
jewel.setPixelColor(i, red);
jewel.show();
delay(500);
}
for (i=1;i<NEOPIXEL_COUNT;i++){
jewel.setPixelColor(i, 0);
jewel.show();
delay(500);
}
jewel.setPixelColor(0,settings[j]);
}
}
| true |
997740159e0965ca7f263000da1f11c3da42fd71 | C++ | robojan/EmuAll | /Support/graphics/ShaderProgram.cpp | UTF-8 | 12,339 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive |
#include <emuall/graphics/ShaderProgram.h>
#include <emuall/graphics/texture.h>
#include <emuall/graphics/texture3D.h>
#include <emuall/graphics/BufferObject.h>
#include <emuall/graphics/bufferTexture.h>
#include <emuall/graphics/graphicsException.h>
#include <GL/glew.h>
#include <GL/GL.h>
#include <fstream>
#include <sstream>
#include <assert.h>
static GLenum GetGLShaderType(ShaderProgram::Type type) {
switch (type) {
case ShaderProgram::Vertex: return GL_VERTEX_SHADER;
case ShaderProgram::Fragment: return GL_FRAGMENT_SHADER;
case ShaderProgram::Geometry: return GL_GEOMETRY_SHADER;
case ShaderProgram::TessellationCtrl: return GL_TESS_CONTROL_SHADER;
case ShaderProgram::TessellationEval: return GL_TESS_EVALUATION_SHADER;
case ShaderProgram::Compute: return GL_COMPUTE_SHADER;
}
throw GraphicsException(GL_INVALID_ENUM, "Unknown shader type");
}
ShaderProgram::ShaderProgram() :
_program(0)
{
_name = nullptr;
_shaders = new std::vector<unsigned int>;
}
ShaderProgram::ShaderProgram(const char *name)
{
_name = new std::string(name);
_shaders = new std::vector<unsigned int>;
}
ShaderProgram::~ShaderProgram()
{
try {
Clean();
}
catch (GraphicsException &) {
}
if (_name != nullptr) {
delete _name;
_name = nullptr;
}
delete _shaders;
}
void ShaderProgram::AddShader(Type type, ShaderSource &source)
{
GLenum shaderType = GetGLShaderType(type);
// Create an shader object
GLuint shader;
GL_CHECKED(shader = glCreateShader(shaderType));
const char *src = source.GetSrc();
int srcLen = source.GetSrcLen();
Compile(type, shader, 1, &src, &srcLen);
_shaders->push_back(shader);
}
void ShaderProgram::Link()
{
// Create an new program
GL_CHECKED(_program = glCreateProgram());
// Attach all the shaders
for (auto &shader : *_shaders) {
GL_CHECKED(glAttachShader(_program, shader));
}
// Link the program
GL_CHECKED(glLinkProgram(_program));
GLint status;
glGetProgramiv(_program, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
std::stringstream stringstream;
GLint logLength;
glGetProgramiv(_program, GL_INFO_LOG_LENGTH, &logLength);
std::vector<char> log(logLength + 1);
glGetProgramInfoLog(_program, logLength + 1, &logLength, log.data());
stringstream << log.data();
GL_CHECKED(glDeleteProgram(_program));
_program = 0;
throw ShaderCompileException(stringstream.str().c_str(),
_name != nullptr ? _name->c_str() : nullptr);
}
}
void ShaderProgram::Clean()
{
// Delete all the shaders
for (auto &shader : *_shaders) {
if (glIsShader(shader)) {
GL_CHECKED(glDeleteShader(shader));
}
}
_shaders->clear();
if (glIsProgram(_program)) {
GL_CHECKED(glDeleteProgram(_program));
_program = 0;
}
}
void ShaderProgram::Begin() const
{
assert(glIsProgram(_program) == GL_TRUE);
assert(IsLinked());
GL_CHECKED(glUseProgram(_program));
}
void ShaderProgram::End() const
{
GL_CHECKED(glUseProgram(0));
}
bool ShaderProgram::IsLinked() const
{
GLint status;
if (glIsProgram(_program) == GL_FALSE) return false;
glGetProgramiv(_program, GL_LINK_STATUS, &status);
return status == GL_TRUE;
}
void ShaderProgram::SetUniform(const char *name, int val)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform1i(loc, val));
}
}
void ShaderProgram::SetUniform(const char *name, int val0, int val1)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform2i(loc, val0, val1));
}
}
void ShaderProgram::SetUniform(const char *name, int val0, int val1, int val2)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform3i(loc, val0, val1, val2));
}
}
void ShaderProgram::SetUniform(const char *name, int val0, int val1, int val2, int val3)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform4i(loc, val0, val1, val2, val3));
}
}
void ShaderProgram::SetUniform(const char *name, unsigned int val)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform1ui(loc, val));
}
}
void ShaderProgram::SetUniform(const char *name, unsigned int val0, unsigned int val1)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform2ui(loc, val0, val1));
}
}
void ShaderProgram::SetUniform(const char *name, unsigned int val0, unsigned int val1, unsigned int val2)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform3ui(loc, val0, val1, val2));
}
}
void ShaderProgram::SetUniform(const char *name, unsigned int val0, unsigned int val1, unsigned int val2, unsigned int val3)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform4ui(loc, val0, val1, val2, val3));
}
}
void ShaderProgram::SetUniform(const char *name, float val)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform1f(loc, val));
}
}
void ShaderProgram::SetUniform(const char *name, double val)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform1d(loc, val));
}
}
void ShaderProgram::SetUniform(const char *name, float val0, float val1)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform2f(loc, val0, val1));
}
}
void ShaderProgram::SetUniform(const char *name, float val0, float val1, float val2)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform3f(loc, val0, val1, val2));
}
}
void ShaderProgram::SetUniform(const char *name, float val0, float val1, float val2, float val3)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform4f(loc, val0, val1, val2, val3));
}
}
void ShaderProgram::SetUniform(const char *name, double val0, double val1)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform2d(loc, val0, val1));
}
}
void ShaderProgram::SetUniform(const char *name, double val0, double val1, double val2)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform3d(loc, val0, val1, val2));
}
}
void ShaderProgram::SetUniform(const char *name, double val0, double val1, double val2, double val3)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glUniform4d(loc, val0, val1, val2, val3));
}
}
void ShaderProgram::SetUniform(const char *name, int pos, BufferObject &object)
{
int loc = GetUniformBlockLocation(name);
if (loc != -1) {
GL_CHECKED(glUniformBlockBinding(_program, loc, pos));
GL_CHECKED(glBindBufferBase(GL_UNIFORM_BUFFER, pos, object._bo));
}
}
void ShaderProgram::SetUniform(const char *name, int pos, Texture &texture)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glActiveTexture(GL_TEXTURE0 + pos));
texture.Bind();
GL_CHECKED(glUniform1i(loc, pos));
}
}
void ShaderProgram::SetUniform(const char *name, int pos, Texture3D &texture)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glActiveTexture(GL_TEXTURE0 + pos));
texture.Bind();
GL_CHECKED(glUniform1i(loc, pos));
}
}
void ShaderProgram::SetUniform(const char *name, int pos, BufferTexture &texture)
{
int loc = GetUniformLocation(name);
if (loc != -1) {
GL_CHECKED(glActiveTexture(GL_TEXTURE0 + pos));
texture.Bind();
GL_CHECKED(glUniform1i(loc, pos));
}
}
void ShaderProgram::Compile(Type type, unsigned int shader, int count, const char * const * src, const int *len)
{
assert(glIsShader(shader) == GL_TRUE);
// Assign the source code to the shader
GL_CHECKED(glShaderSource(shader, count, src, len));
// Compile the shader
GL_CHECKED(glCompileShader(shader));
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
GLint logLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
std::vector<char> log(logLength+1);
glGetShaderInfoLog(shader, logLength+1, &logLength, log.data());
throw ShaderCompileException(type, log.data(), _name != nullptr ? _name->c_str() : nullptr);
}
}
int ShaderProgram::GetUniformLocation(const char *name)
{
int loc;
GL_CHECKED(loc = glGetUniformLocation(_program, name));
return loc;
}
int ShaderProgram::GetUniformBlockLocation(const char *name)
{
int loc;
GL_CHECKED(loc = glGetUniformBlockIndex(_program, name));
return loc;
}
ShaderCompileException::ShaderCompileException(ShaderProgram::Type type, const char *log, const char *name /*= nullptr*/)
{
_msg = new std::string("Error while compiling ");
switch (type) {
case ShaderProgram::Vertex:
_msg->append("vertex");
break;
case ShaderProgram::Fragment:
_msg->append("fragment");
break;
case ShaderProgram::TessellationCtrl:
_msg->append("tessellation control");
break;
case ShaderProgram::TessellationEval:
_msg->append("tessellation evaluation");
break;
case ShaderProgram::Geometry:
_msg->append("geometry");
break;
case ShaderProgram::Compute:
_msg->append("compute");
break;
default:
_msg->append("Unknown");
break;
}
_msg->append(" shader");
if (name) {
_msg->append(" in shader program \"");
_msg->append(name);
_msg->append("\"");
}
_msg->append(":\n");
_msg->append(log);
}
ShaderCompileException::ShaderCompileException(const char *log, const char *name /*= nullptr*/)
{
_msg = new std::string("Error while linking shader program");
if (name) {
_msg->append(" \"");
_msg->append(name);
_msg->append("\"");
}
_msg->append(":\n");
_msg->append(log);
}
ShaderCompileException::ShaderCompileException(ShaderCompileException &other)
{
_msg = new std::string(*other._msg);
}
ShaderCompileException::~ShaderCompileException()
{
delete _msg;
}
const char * ShaderCompileException::GetMsg()
{
return _msg->c_str();
}
ShaderCompileException & ShaderCompileException::operator=(ShaderCompileException &other)
{
*_msg = *other._msg;
return *this;
}
ShaderSource::ShaderSource(const char *src, int len /*= -1*/) :
_versionAdded(false), _source(new std::string)
{
AddSource(src, len);
}
ShaderSource::ShaderSource(const std::string &src) :
_versionAdded(false), _source(new std::string)
{
AddSource(src);
}
ShaderSource::ShaderSource(const unsigned char *src, unsigned int len /*= -1*/) :
_versionAdded(false), _source(new std::string)
{
AddSource((const char *)src, (int)len);
}
ShaderSource::ShaderSource(const ShaderSource &other):
_source(new std::string(*other._source)), _versionAdded(other._versionAdded)
{
}
ShaderSource::~ShaderSource()
{
delete _source;
}
ShaderSource & ShaderSource::operator=(const ShaderSource &other)
{
*_source = *other._source;
_versionAdded = other._versionAdded;
return *this;
}
void ShaderSource::AddVersionDirective(int version, bool compatibility /*= false*/)
{
if (_versionAdded) return;
std::string versionString("#version ");
versionString.append(std::to_string(version));
if (compatibility) {
versionString.append(" compatibility\n");
}
else {
versionString.append(" core\n");
}
versionString.append(*_source);
*_source = versionString;
_versionAdded = true;
}
void ShaderSource::AddSource(const std::string &src)
{
_source->append(src);
}
void ShaderSource::AddSource(const char *src, int len /*= -1*/)
{
if (len >= 0) {
_source->append(src, len);
}
else {
_source->append(src);
}
}
void ShaderSource::AddSource(const unsigned char *src, unsigned int len /*= -1*/)
{
AddSource((const char *)src, (int)len);
}
void ShaderSource::AddSourceFile(const std::string &path)
{
char *src = nullptr;
// Open the file
std::ifstream file(path, std::ios_base::in);
if (!file.is_open()) {
std::ostringstream stringStream;
stringStream << "Error opening file: " << strerror(errno) << std::endl;
throw std::exception(stringStream.str().c_str());
}
file.exceptions(std::ios_base::failbit | std::ios_base::badbit);
try {
// Get file size
file.seekg(0, std::ios_base::end);
std::istream::pos_type size = file.tellg();
file.seekg(0, std::ios_base::beg);
assert(size <= INT32_MAX);
// Create Source buffer
src = new char[(unsigned int)size];
// Read content of the file
file.read(src, size);
// Add the shader
_source->append(src);
// Delete the source
if (src != nullptr) {
delete src;
}
}
catch (std::ifstream::failure &e) {
// Delete the source
if (src != nullptr) {
delete src;
}
throw e;
}
}
const char * ShaderSource::GetSrc() const
{
return _source->c_str();
}
int ShaderSource::GetSrcLen() const
{
return _source->length();
}
| true |
412bda16f22f52b9886e263110495939e3d7ae93 | C++ | vctralcaraz/AlcarazVictor_46090 | /Lab/Lab16/Savitch_8thEd_Chap7_Prob4/main.cpp | UTF-8 | 5,130 | 3.53125 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Victor Alcaraz
* Created on July 16, 2015, 11:24 AM
* Purpose: To calculate the mean and standard deviation
*/
//System Libraries
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <ctime>
using namespace std;
//User Libraries
//Global Constants
const double MXRND=pow(2,31)-1;
//Function Prototypes
float normal();
void filAray(float [],int);
void prntAry(const float [],int,int);
float max(float [],int);
float min(float [],int);
float mean(float [],int);
float stdev(float [],int);
//Execution Begins Here!
int main(int argc, char** argv) {
//set the random number seed
srand(static_cast<unsigned int>(time(0)));
//Declare Variables
const int SIZE=500000;
float array[SIZE];
//initialize array
filAray(array,SIZE);
//output the initial array
//prntAry(array,SIZE,5);
//Print the statistics
cout<<"The max value of the array = "<<max(array,SIZE)<<endl;
cout<<"The min value of the array = "<<min(array,SIZE)<<endl;
cout<<"The mean value of the array = "<<mean(array,SIZE)<<endl;
cout<<"The standard deviation in the array = "<<stdev(array,SIZE)<<endl;
//Exit stage right!
return 0;
}
/**********************************************
* Standard Deviation of the Array *
**********************************************
* Purpose: To find the standard deviation
* Input:
* n-> the size of the array
* a-> the float array
* Output:
* standard deviation
**********************************************/
float stdev(float a[],int n){
//Declare and initialize variables
float std=0,avg=mean(a,n);
//loop to find the
for(int i=0;i<n;i++){
float amavg=(a[i]-avg);
std+=amavg*amavg;
//std+=(a[i]-mean(a,n)*a[i]-mean(a,n));
}
//return value
return sqrt(std/(n-1));
}
/**********************************************
* Mean of the Array *
**********************************************
* Purpose: To find the mean
* Input:
* n-> the size of the array
* a-> the float array
* Output:
* mean value
**********************************************/
float mean(float a[],int n){
//Declare and initialize variables
float mean=0;
//loop to find the
for(int i=0;i<n;i++){
mean+=a[i];
}
//return value
return mean/n;
}
/**********************************************
* Max of the Array *
**********************************************
* Purpose: To find the maximum
* Input:
* n-> the size of the array
* a-> the float array
* Output:
* maximum value
**********************************************/
float max(float a[],int n){
//Declare and initialize variables
float max=a[0];
//loop to find the
for(int i=1;i<n;i++){
if(max<a[i])max=a[i];
}
//return value
return max;
}
/**********************************************
* Min of the Array *
**********************************************
* Purpose: To find the minimum
* Input:
* n-> the size of the array
* a-> the float array
* Output:
* minimum value
**********************************************/
float min(float a[],int n){
//Declare and initialize variables
float min=a[0];
//loop to find the
for(int i=1;i<n;i++){
if(min>a[i])min=a[i];
}
//return value
return min;
}
/**********************************************
* Normal Distribution Approximation *
**********************************************
* Purpose:
* Output:
* Normal density function approximation
**********************************************/
void prntAry(const float a[],int n,int nCols){
//format
cout<<fixed<<showpoint<<setprecision(4);
cout<<endl;
//loop and output every element in the array
for(int i=0;i<n;i++){
cout<<setw(8)<<a[i];
//When column is reached go to next line
if((i%nCols)==(nCols-1))cout<<endl;
}
//separate outputs
cout<<endl;
}
/**********************************************
* Normal Distribution Approximation *
**********************************************
* Purpose:
* Output:
* Normal density function approximation
**********************************************/
void filAray(float a[],int n){
for(int i=0;i<n;i++){
a[i]=normal();
}
}
/**********************************************
* Normal Distribution Approximation *
**********************************************
* Purpose:
* Output:
* Normal density function approximation
**********************************************/
float normal(){
//delcare variables
float norm=0; //[-6,6]
//loop 12 times
for(int i=1;i<=12;i++){
norm+=(rand()/MXRND-0.5); //[-0.5,0.5]
}
return norm;
} | true |
bd721281e7f1d3825bb31b4604f2206accff404e | C++ | AlexanderDBolton/Regimes_RJMCMC | /Code/binary.h | UTF-8 | 1,045 | 3.109375 | 3 | [
"MIT"
] | permissive | #ifndef BINARY_H
#define BINARY_H
class binary {
public:
binary(const double & log_likelihood = 0, const int & left_index = 0);
double get_log_likelihood() {return m_log_likelihood;}
void set_log_likelihood(const double & log_likelihood) {m_log_likelihood = log_likelihood;}
void increase_log_likelihood(const double & increase) {m_log_likelihood += increase;}
void set_left_index(const int & index) {m_left_index = index;}
void increase_left_index(const int & change) {m_left_index += change;}
int get_left_index() {return m_left_index;}
//void set_right_index(const int & index) {m_right_index = index;}
//int get_right_index() {return m_right_index;}
protected:
double m_log_likelihood; // the log_likelihood for the interval defined by the binary
int m_left_index; // the index of the changepoint that bounds the binary to the left
};
binary::binary(const double & log_likelihood, const int & left_index):m_log_likelihood(log_likelihood), m_left_index(left_index){
}
#endif
| true |
c4b0aea4a2a1015a491f1cde9082c07c7cfee64a | C++ | AlfredoPiedra/Vector_Processor | /vector_processor/clock.cpp | UTF-8 | 445 | 2.984375 | 3 | [] | no_license | #include "clock.h"
unsigned char Clock::clock = 0;
Clock::Clock(){
pthread_t clock_tid;
pthread_create(&clock_tid,0,ClockThread,0);
pthread_detach(clock_tid);
}
void* Clock::ClockThread(void *ptr){
while(1){
usleep(10000);
clock = !clock;
std::cout << "Hola desde el clock" << (int)clock << std::endl;
}
pthread_exit(ptr);
}
void Clock::StartClock(){
}
void Clock::StopClock(){
}
| true |
e8579d134b8258a43584c74f1cacf4cf2224eef2 | C++ | S-Hucks/cs2400 | /files2.cc | UTF-8 | 890 | 3.21875 | 3 | [] | no_license | /*
* File: files.cc
* Author: Nasseef Abukamail
* Date: February 25, 2019
* Description: A program to demonstrate text files.
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
//1
#include <fstream>
using namespace std;
//function prototypes
int main(int argc, char const *argv[]) {
//2
ifstream inStream;
string fileName;
cout << "Enter a file name: ";
cin >> fileName;
//3
inStream.open(fileName.c_str());
if (inStream.fail()) {
cout << "Error: file does not exist" <<endl;
exit(1);
}
//4
int num;
int total = 0;
while(inStream >> num){ //inStream.eof() == false
cout << "Num = " << num << endl;
total += num;
}
cout << "Total = " << total << endl;
// inStream >> num;
// cout << "Num = " << num << endl;
//5
inStream.close();
return 0;
}// main | true |
0cd6649cbb5ee3f634656fa77e171cc82a80d973 | C++ | mdjmedellin/PlanetaryEngine | /TempEngine/MathUtilities.cpp | UTF-8 | 9,285 | 3.203125 | 3 | [] | no_license | #include "MathUtilities.hpp"
#include "Vector2.hpp"
#include "Vector3.hpp"
#include "Vector4.h"
#include <vector>
#include <cmath>
#include <math.h>
#include <algorithm>
int GetNearestInt(float f)
{
return static_cast< int > ( floor( f + .5f) );
}
float RoundFloatToNearestInt(float f)
{
return floor ( f + .5f );
}
float GetMaxFloat(float a, float b, float c)
{
return GetMaxFloat(a,GetMaxFloat(b,c));
}
float GetMaxFloat(float a, float b, float c, float d)
{
return GetMaxFloat(GetMaxFloat(a,b),GetMaxFloat(c,d));
}
float GetMinFloat(float a, float b, float c)
{
return GetMinFloat(a,GetMinFloat(b,c));
}
float GetMinFloat(float a, float b, float c, float d)
{
return GetMinFloat(GetMinFloat(a,b),GetMinFloat(c,d));
}
int GetMaxInt(int a, int b, int c)
{
return GetMaxInt(a,GetMaxInt(b,c));
}
int GetMaxInt(int a, int b, int c, int d)
{
return GetMaxInt(GetMaxInt(a,b),GetMaxInt(c,d));
}
int GetMinInt(int a, int b, int c)
{
return GetMinInt(a,GetMinInt(b,c));
}
int GetMinInt(int a, int b, int c, int d)
{
return GetMinInt(GetMinInt(a,b),GetMinInt(c,d));
}
float ClampFloatWithinRange(float minimumFloatValue, float maximumFloatValue, float floatToClamp)
{
if( floatToClamp < minimumFloatValue )
{
return minimumFloatValue;
}
else if( floatToClamp > maximumFloatValue )
{
return maximumFloatValue;
}
return floatToClamp;
}
int ClampIntWithinRange(int minimumIntValue, int maximumIntValue, int intToClamp)
{
if(intToClamp <= maximumIntValue)
{
if(intToClamp >= minimumIntValue)
{
return intToClamp;
}
return minimumIntValue;
}
return maximumIntValue;
}
float ConvertDegreesToRadians(float degrees)
{
return (degrees * ( PI / 180.f));
}
float ConvertRadiansToDegrees(float radians)
{
return (radians * (180.f / PI));
}
float CalcAngularDistanceDegrees(float degreesA, float degreesB)
{
float angularDistanceDegrees = fabs(degreesA - degreesB);
if (angularDistanceDegrees > 180.f)
{
angularDistanceDegrees = fmod(angularDistanceDegrees, 360.f);
if (angularDistanceDegrees > 180.f)
{
angularDistanceDegrees = 360 - angularDistanceDegrees;
}
}
return angularDistanceDegrees;
}
float CalcAngularDistanceRadians(float radiansA, float radiansB)
{
float angularDistanceRadians = fabs(radiansA - radiansB);
while (angularDistanceRadians > PI)
{
angularDistanceRadians = fmod(angularDistanceRadians,( 2 * PI ));
if (angularDistanceRadians > PI)
{
angularDistanceRadians = (2 * PI) - angularDistanceRadians;
}
}
return angularDistanceRadians;
}
float CalcAngularDisplacementDegrees(float startDegrees, float endDegrees)
{
float angularDisplacementDegrees = endDegrees - startDegrees;
while( angularDisplacementDegrees > 180.f )
{
angularDisplacementDegrees -= 360.f;
}
while( angularDisplacementDegrees < -180.f )
{
angularDisplacementDegrees += 360.f;
}
return angularDisplacementDegrees;
}
float CalcAngularDisplacementRadians(float startRadians, float endRadians)
{
float angularDisplacementRadians = endRadians - startRadians;
while( angularDisplacementRadians > PI )
{
angularDisplacementRadians -= ( 2.f * PI );
}
while( angularDisplacementRadians < -PI )
{
angularDisplacementRadians += ( 2.f * PI );
}
return angularDisplacementRadians;
}
bool CheckIfIsPowerOfTwo(int a)
{
bool isPowerOfTwo = false;
int argumentMinusOne = a-1;
if ( (a & argumentMinusOne) == 0x0 )
{
isPowerOfTwo = true;
}
return isPowerOfTwo;
}
float InterpolateFloat(float startFloatValue, float endFloatValue, float fractionComplete)
{
return ((startFloatValue * (1.f - fractionComplete)) + (endFloatValue * fractionComplete));
}
int InterpolateInt(int startIntValue, int endIntValue, float fractionComplete)
{
float floatInterpolationValue = InterpolateFloat((float)(startIntValue), float(endIntValue), fractionComplete);
return (int)(floatInterpolationValue);
}
//Range Mapping
//
float RangeMapFloat( float currentValue, float currentStartingPoint, float currentEndPoint,
float newStartingPoint, float newEndPoint, bool clamp,
FilterFunctionPtr filterFunction)
{
//we return the midpoint if the current starting point and end point are the same
if( currentStartingPoint == currentEndPoint )
{
return ( newStartingPoint * .5f + newEndPoint * .5f );
}
float fraction = ( currentValue - currentStartingPoint ) / ( currentEndPoint - currentStartingPoint );
//clamping the value if the user desired to
if( clamp )
{
if( fraction < 0.f )
{
fraction = 0.f;
}
else if( fraction > 1.f )
{
fraction = 1.f;
}
}
//Apply any desired transformation
//
if (filterFunction)
{
fraction = filterFunction(fraction);
}
//mapping the value into the new range
float newValue = newStartingPoint + fraction * ( newEndPoint - newStartingPoint );
return newValue;
}
float SmoothStartFilter( float value )
{
// x^2
return ( value * value );
}
float SmoothStopFilter( float value )
{
// 1 - ( 1 - x )^2
return ( 1 - ( ( 1 - value ) * ( 1 - value ) ) );
}
float SmoothStepFilter( float value )
{
//( 1 - x )( x^2 ) + x[ 1 - ( 1 - x )^2 ]
// = 3x^2 - 2x^3
return ( ( 3 * value * value ) - ( 2 * value * value * value ) );
}
float LinearFilter( float value )
{
return value;
}
float SlingshotFilter( float value )
{
float topPart = ( 1.280776406f * 1.280776406f ) * value;
float bottomPart = ( value * value ) + ( 1.280776406f * .5f );
return topPart/bottomPart;
}
//
bool isPointBehindFace( const Vector2& faceStart, const Vector2& faceEnd, const Vector2& pointToCheck )
{
//calculating the normal of the edge made by the two points
Vector2 normalVector = faceEnd - faceStart;
normalVector.RotateMinus90Degrees();
//checking if the point lies behind the face
Vector2 startToTestPoint = pointToCheck - faceStart;
float dotProduct = startToTestPoint.DotProduct(normalVector);
bool isTestPointBehind = ( dotProduct < 0.f );
return isTestPointBehind;
}
Vector2 getNormal( const Vector2& startPoint, const Vector2& endPoint )
{
Vector2 normalVector = endPoint - startPoint;
normalVector.RotateMinus90Degrees();
return normalVector;
}
float dotProduct( const Vector2& vectorA, const Vector2& vectorB )
{
return vectorA.x * vectorB.x + vectorA.y * vectorB.y;
}
float dotProduct( const Vector3& vectorA, const Vector3& vectorB )
{
return vectorA.x * vectorB.x + vectorA.y * vectorB.y + vectorA.z * vectorB.z;
}
float getSign( float value )
{
return ( value >= 0.f ? 1.f : -1.f );
}
unsigned int toRGBA( float r, float g, float b, float a /*= 1.0f */ )
{
return ( ( static_cast< unsigned int >( r * 255.0f ) & 0xFF ) << 0 ) |
( ( static_cast< unsigned int >( g * 255.0f ) & 0xFF ) << 8 ) |
( ( static_cast< unsigned int >( b * 255.0f ) & 0xFF ) << 16 ) |
( ( static_cast< unsigned int >( a * 255.0f ) & 0xFF ) << 24 );
}
void separateData( const std::string& dataString, std::vector< std::string >& dataStrings, std::vector< float >& weightsOfData )
{
//construct the list of choices
std::vector< std::string > choices = splitString( dataString, ',' );
//separate the list of choices into strings with weights
std::vector< std::string > currentChoiceData;
std::for_each( choices.begin(), choices.end(), [&]( const std::string& currentChoiceString )
{
currentChoiceData = splitString( currentChoiceString, '@' );
//if the data returns with only one parameter, then we don't add it into the pool of choices
if( currentChoiceData.size() > 1 )
{
dataStrings.push_back( currentChoiceData[0] );
weightsOfData.push_back( float( atof( currentChoiceData[1].c_str() ) ) );
}
});
}
std::vector< std::string > splitString( const std::string& dataString, const char& key )
{
size_t keyLocation = 0;
size_t startIndex = 0;
size_t currentIndex = 0;
std::string substring;
std::vector< std::string > stringContainer;
keyLocation = dataString.find( key, currentIndex );
while ( keyLocation != std::string::npos )
{
substring = dataString.substr( startIndex, keyLocation-startIndex );
//remove whitespace
removeFrontAndBackWhiteSpace( substring );
//if the string is not empty, then we add it to the container of keys
if( !substring.empty() )
{
stringContainer.push_back( substring );
}
startIndex = keyLocation+1;
keyLocation = dataString.find( key, startIndex );
}
if( startIndex < dataString.size() )
{
substring = dataString.substr( startIndex );
//remove whitespace
removeFrontAndBackWhiteSpace( substring );
//if the string is not empty, then we add it to the container of keys
if( !substring.empty() )
{
stringContainer.push_back( substring );
}
}
return stringContainer;
};
void removeWhiteSpace( std::string& line, bool front )
{
size_t index = std::string::npos;
if( front )
{
index = line.find_first_not_of( " \t\n" );
if( index == std::string::npos )
{
line.clear();
}
else
{
line.erase( 0, index );
}
}
else
{
index = line.find_last_not_of( " \t\n" );
if( index == std::string::npos )
{
line.clear();
}
else
{
line = line.substr( 0, index + 1 );
}
}
}
void removeFrontAndBackWhiteSpace( std::string& textBlock )
{
removeWhiteSpace( textBlock, true );
removeWhiteSpace( textBlock, false );
}
float RandZeroToOne()
{
return float( rand() ) / float( RAND_MAX );
}
| true |
7ce55a353f20460a2b5f9500e459f50c0924b1e7 | C++ | qianlv/learning | /cplusplusprimer/10/generic_algorithm.h | UTF-8 | 1,099 | 2.6875 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: generic_algorithm.h
*
* Description: generic_algorithm.h
*
* Version: 1.0
* Created: 2016年01月01日 16时33分25秒 CST
* Revision: none
* Compiler: gcc
*
* Author: qianlv (), qianlv7@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <iostream>
using std::ostream;
#include <string>
using std::string;
#include <vector>
using std::vector;
bool isShorter(const string &s1, const string &s2);
void elimDups(vector<string> &words);
void biggies(vector<string> &words, vector<string>::size_type sz);
void biggies(vector<string> &words, vector<string>::size_type sz, ostream &os, char c);
void biggies_p(vector<string> &words, vector<string>::size_type sz);
void biggies_sp(vector<string> &words, vector<string>::size_type sz);
void biggies_bp(vector<string> &words, vector<string>::size_type sz);
bool check_size(const string &s, string::size_type sz);
| true |
6b1afb0901724614ea039dcd21aef5c9aef6ee2f | C++ | aruskey/katiss | /speedlimit/speedlimit/speedlimit.cpp | UTF-8 | 443 | 2.921875 | 3 | [] | no_license | // speedlimit.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int start;
int time, speed;
while(cin >> start){
if (start == -1) {
break;
}
int sumD = 0;
int past = 0;
for (int i = 0;i < start;i++) {
cin >> speed >> time;
sumD += speed * (time - past);
past = time;
}
cout << sumD << " miles\n";
}
return 0;
}
| true |
440eea7ff0de4484781d55135ad480a2256c7772 | C++ | Imran4424/C-Plus-Plus-Object-Oriented | /1. Input Output/3. IO manipulators/5.showbase_noshowbse.cpp | UTF-8 | 948 | 3.5625 | 4 | [
"MIT"
] | permissive | /*
write a program to demonstrate I/O manipulators showbase, noshowbase
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char const *argv[])
{
int num = 200;
cout<< endl <<"Hexadecimal: "<<endl;
cout << hex << showbase << num <<endl;
cout << hex << noshowbase << num <<endl<<endl;
cout<<"Decimal: "<<endl;
cout << dec << showbase << num <<endl;
cout << dec << noshowbase << num <<endl<<endl;
cout<<"Octal: "<<endl;
cout << oct << showbase << num <<endl;
cout << oct << noshowbase << num <<endl<<endl;
return 0;
}
/*
showbase - to show the base of the number system
noshowbase - to hide the base of the number system
by default noshowbase is activated
these are the memebers of iomanip headers
sometimes we need to include the header like this,
#include <iomanip>
sometimes it work without including the header iomanip
In update compilers don't need to include iomanip
*/ | true |
116e1326551ae7bb5d168f8a4554e16c9b58c21c | C++ | catch4/taehunlee | /2020_09_week_2/b5884_감시카메라.cpp | UTF-8 | 584 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int N;
unordered_map<int, int> mapX;
unordered_map<int, int> mapY;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> N;
int count = 0;
for(int i = 0; i < N; i++) {
int x, y;
cin >> x >> y;
if(!mapX[x] && !mapY[y]) {
mapX[x] = 1;
mapY[y] = 1;
count++;
if(count > 3) {
break;
}
}
}
cout << (count > 3 ? 0 : 1);
return 0;
} | true |
cdeed8b81c4517ca45607d3350b6674474f10924 | C++ | ramnathj/CodeArena | /C++Codes/HackerEarth/SpecialStrings.cpp | UTF-8 | 1,202 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <limits.h>
#include <map>
using namespace std;
map<string, bool> M;
vector<string> A;
vector<int> B;
bool Check( string s ) {
if( M[ s ] ) {
return false;
}
M[ s ] = true;
int i, n = A.size(), val;
for( i = 0;i < n;i++ ) {
val = A[ i ].find( s );
if( !( ( val >= 0 ) && ( val < A[ i ].length() ) ) )
return false;
}
return true;
}
int main()
{
ios_base::sync_with_stdio( false );
int n, i, pos, minVal, len, count, j;
cin >> n;
pos = -1;
minVal = INT_MAX;
string p;
for( i = 0;i < n;i++ ) {
cin >> p;
A.push_back( p );
B.push_back( p.length() );
if( B[ i ] < minVal ) {
minVal = B[ i ];
pos = i;
}
}
string s = A[ pos ];
len = B[ pos ];
count = 0;
for( i = 0;i < len;i++ ) {
string str = "";
str = s[ i ];
if( Check( str ) )
count++;
for( j = 1;j < len - i;j++ ) {
if( s[ i + j ] < s[ i + j - 1 ] ) {
break;
}
string s2 = "";
s2 = s[ i + j ];
str = str + s2;
if( Check( str ) )
count++;
}
}
cout << count << "\n";
return 0;
}
| true |
194973dd898caee18c039c388aaa0326eef408d9 | C++ | n-fallahinia/UoU_Genral_Class | /src/TimeHandler.cpp | UTF-8 | 1,947 | 3.1875 | 3 | [
"MIT"
] | permissive | // Function definitions for the TimeHandler class
#include "TimeHandler.h"
#include <sched.h>
// Constructor
TimeHandler::TimeHandler()
{
// Set up the one-second timespec structure
one_second.tv_sec = 1;
one_second.tv_nsec = 0L;
// Define the number of nanoseconds in one second
nanoseconds = 1000000000;
// Define the CPU core to be used for tracking the time
my_cpu = 3;
// Determine the number of clicks per second
current_clicks = clicks_per_second();
// Begin timing from the current time
time_start = 0.0;
time_start = current_time();
}
// Destructor
TimeHandler::~TimeHandler()
{
}
// Use HPET to get the current time
inline unsigned long long int TimeHandler::hpet_time()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
//return output_value;
return ((unsigned long long int)ts.tv_sec * nanoseconds + (unsigned long long int)ts.tv_nsec);
} // hpet_time
// Gets the number of clicks per second.
// Also binds the process to the CPU core.
inline long long int TimeHandler::clicks_per_second()
{
// Bind the process to my_cpu
cpu_set_t cpuMask;
CPU_ZERO(&cpuMask);
CPU_SET(my_cpu, &cpuMask);
sched_setaffinity(0, sizeof(cpuMask), &cpuMask);
// Measure number of clicks during 1 second
unsigned long long int curr_time = hpet_time();
nanosleep(&one_second, (struct timespec *)NULL);
// Return the difference
return (long long int)(hpet_time() - curr_time);
} // clicks_per_second
// Resets the starting time to the current time
void TimeHandler::reset_timer()
{
// Start the timer over at zero
time_start = 0.0;
time_start = current_time();
} // reset_timer
// Retrieves the current time (in seconds) with the starting offset time removed
double TimeHandler::current_time()
{
return (((double)hpet_time()) / ((double)current_clicks) - time_start);
} // current_time
| true |
9ac8b6f3fd3fdbcbd400090b38cd1421b7f8427a | C++ | Davidah121/GLib | /include/ext/GLFont.h | UTF-8 | 2,119 | 2.78125 | 3 | [] | no_license | #pragma once
#ifdef USE_OPENGL
#include "MathExt.h"
#include "ext/GLSingleton.h"
#include "ext/GLSprite.h"
#include "ext/GLModel.h"
#include "BitmapFont.h"
namespace glib
{
class GLFont : public Font
{
public:
/**
* @brief Creates a GLBitmapFont Object.
* GLBitmapFont extends from the Font class and as the name suggest, it uses an Image to
* store and display characters.
* Two file types are supported. .ft and .fnt
* .ft is a custom format for font that uses a relatively simple format to store information about each character.
* .fnt is a format used by BitmapFontGenerator located here: https://www.angelcode.com/products/bmfont
* Note that only the xml file format is supported for .fnt
* @param filename
* The name of the file to load for font data.
*/
GLFont(File file);
/**
* @brief Destroys a GLBitmapFont Object.
*/
~GLFont();
//Object and Class Stuff
static const Class globalClass;
/**
* @brief Get the texture where the desired character is stored.
* The texture can contain other characters than just the desired character.
* If the index is out of range and USE_EXCEPTIONS is defined, an OutOfBounds Error is thrown.
* If not, a nullptr is returned.
* @param index
* The desired character.
* @return Image*
* A nullptr is returned if no texture was found. Otherwise, a valid GLTexture* is returned.
*/
GLTexture* getTexture(int index);
/**
* @brief Gets the Model for the specified character.
* This model will be the width and height of the character and will
* also have the correct texture coordinates.
* If nullptr is returned, the font does not have data for the character.
*
* @param index
* The desired character.
* @return GLModel*
*/
GLModel* getModel(int index);
private:
void convertBitmapFont(BitmapFont& p);
GLSprite img = GLSprite();
std::vector<GLModel*> models = std::vector<GLModel*>();
std::vector<size_t> imgPage = std::vector<size_t>();
};
}
#endif | true |
3070256808de54775f31e48f8e61bfea387a6912 | C++ | shobhit-saini/DP | /Factorial/mfact.cpp | UTF-8 | 365 | 2.90625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int dp[INT_MAX];
int fact(int N)
{
if(N == 0)
{
return 1;
}
else if(dp[N] != -1)
{
return dp[N];
}
else
{
dp[N] = N*(dp[N-1] = fact(N-1));
}
return dp[N];
}
int main()
{
int N, result;
cout << "Enter the no.:";
cin >> N;
for(int i = 0; i <= N; i++)
{
dp[i] = -1;
}
cout << fact(N);
}
| true |
5052706a25656e811f6494e6c309dc7471fd958f | C++ | rqgao0422a/OCS | /multi-way-semi-OCS.cpp | UTF-8 | 1,449 | 2.890625 | 3 | [] | no_license | /*
input:
n, number of elements in each tuple
output:
gmin, minimum Gamma that appears in a feasible solution of the stricter LP
gmax, maximum Gamma that appears in a feasible solution of the stricter LP
latex link:
https://www.overleaf.com/3486144463wrhdwyywfqhy
*/
#include<bits/stdc++.h>
using namespace std;
const int N=100000055;
const long double eps=1e-15;
long double f[N];
int main(){
int n;
while(scanf("%d",&n)!=EOF){//n<=100,000,000
int m=n;
f[0]=1;
for(int k=1;k<=m+5;k++)
f[k]=f[k-1]*(1.-1./(long double)n)*(1-(long double)min(k-1,n-1)/(long double)n/(long double)(n-min(k-1,n-1)));
for(int k=0;k<=m+5;k++)
f[k]=1.-f[k];
/*for(int k=0;k<=m+5;k++)
printf("%.12Lf ",f[k]);puts("");*/
long double l=0,r=1;
while(l+eps<r){
long double mid=(l+r)/2.;
long double b=mid/(long double)n;
bool isok=true;
for(int k=1;k<=m+1;k++){
b=(long double)(n+1)/(long double)(n)*b-1./(long double)n*(f[k]-f[k-1]);
if(b>f[k+1]-f[k]){isok=false;break;}
}
if(b>0) isok=false;
if(!isok) r=mid; else l=mid;
}
long double gmax=r;
l=0,r=1;
while(l+eps<r){
long double mid=(l+r)/2.;
long double b=mid/(long double)n;
bool isok=true;
for(int k=1;k<=m+1;k++){
b=(long double)(n+1)/(long double)(n)*b-1./(long double)n*(f[k]-f[k-1]);
if(f[k+1]-f[k]<0){isok=false;break;}
}
if(!isok) l=mid; else r=mid;
}
long double gmin=l;
printf("%.12Lf %.12Lf\n",gmin,gmax);
}
}
| true |
0b82a3067400d23a2ed5fe3981f0668ea43438f5 | C++ | copiner/cplus | /Primer/swap/rswap.cpp | UTF-8 | 321 | 3.53125 | 4 | [] | no_license | #include<iostream>
using namespace std;
void rswap(int &,int &);
int main(){
int i = 10;
int j = 20;
int &ri = i, &rj = j;
cout<<"Before swap: "<< i <<"--"<<j<<endl;
rswap(i,j);
cout<<"After swap: "<< i <<"--"<<j<<endl;
return 0;
}
void rswap(int &v1,int &v2){
int tmp = v2;
v2 = v1;
v1 = tmp;
}
| true |
cc536027e2a1f948b70a4589f93aba1eea3675fc | C++ | LargeDumpling/Programming-Contest | /OnlineJudges/UVa(29)/10943 How do you add/code.cpp | UTF-8 | 601 | 2.59375 | 3 | [] | no_license | /*
Author: LargeDumpling
Email: LargeDumpling@qq.com
Edit History:
2016-03-15 File created.
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int C[205][205];
void calc_C()
{
C[0][0]=1;
for(int i=1;i<=200;i++)
{
C[i][0]=1;
for(int j=1;j<=i;j++)
C[i][j]=(C[i-1][j-1]+C[i-1][j])%1000000;
}
return;
}
int main()
{
freopen("code.in","r",stdin);
freopen("code.out","w",stdout);
int n,k;
calc_C();
while(scanf("%d%d",&n,&k)!=-1&&(n||k))
printf("%d\n",C[n+k-1][k-1]);
fclose(stdin);
fclose(stdout);
return 0;
}
| true |
9076626c732d35e9b636458814c8717573456492 | C++ | BenjaminTanguay/COMP345_Pandemic | /A1/Nick's Roles&Actions/RoleCard.h | WINDOWS-1252 | 3,739 | 3.140625 | 3 | [] | no_license | #pragma once
#include <string>
#include <iostream>
//#include "Role.h"
//#include "EventCard.h"
class RoleCard {
protected:
std::string name;
std::string description;
public:
RoleCard(std::string) {
this->name = name;
}
RoleCard() {};
std::string getName() {
return this->name;
}
std::string getDescription() {
return this->description;
}
std::string getRole() {
return this->getName() + "\n" + this->getDescription();
}
virtual bool costRole(RoleCard& role) { return true; }
//virtual void doRole();
};
class ContigencyPlanner : public RoleCard {
public:
ContigencyPlanner() {
this->name = "Contigency Planner";
this->description = "The Contingency Planner may, as an action, take an\n"
"Event card from anywhere in the Player Discard Pile\n"
"and place it on his Role card.Only 1 Event card can be\n"
"on his role card at a time.It does not count against his\n"
"hand limit.\n"
"When the Contingency Planner plays the Event card on his role card,\n"
"remove this Event card from the game(instead of discarding i";
std::cout << this->getRole()<< std::endl;
}
};
class OperationExpert : public RoleCard {
public:
OperationExpert() {
this->name = "Operations Expert";
this->description = "The Operations Expert may, as an action, either:\n"
" build a research station in his current city\n"
"without discarding(or using) a City card, or \n"
" once per turn, move from a research station to any city\n"
"by discarding any City card.";
std::cout << this->getRole() << std::endl;
}
};
class Dispatcher : public RoleCard {
public:
Dispatcher() {
this->name = "Dispatcher";
this->description = "The Dispatcher may, as an action, either:\n"
" move any pawn, if its owner agrees, to any city\n"
"containing another pawn, or \n"
" move another players pawn, if its owner agrees,\n"
"as if it were his own, discarding your own cards.";
std::cout << this->getRole() << std::endl;
}
};
class QuarantineSpecialist : public RoleCard {
public:
QuarantineSpecialist() {
this->name = "Quarantine Specialist";
this->description = "The Quarantine Specialist prevents both outbreaks and\n"
"the placement of disease cubes in the city she is in\n"
"and all cities connected to that city.She does not affect\n"
"cubes placed during setup.";
std::cout << this->getRole() << std::endl;
}
};
class Researcher : public RoleCard {
public:
Researcher() {
this->name = "Researcher";
this->description = "As an action, the Researcher may give any City card from\n"
"her hand to another player in the same city as her, without\n"
"this card having to match her city.The transfer must be\n"
"from her hand to the other players hand, but it can occur\n"
"on either player's turn.";
std::cout << this->getRole() << std::endl;
}
};
class Medic : public RoleCard {
public:
Medic() {
this->name = "Medic";
this->description = "The Medic removes all cubes, not 1, of the same color\n"
"when doing the Treat Disease action.\n"
"If a disease has been cured, he automatically removes\n"
"all cubes of that color from a city, simply by entering it\n"
"or being there.This does not take an action. The Medics automatic removal of cubes can occur on other players'\n"
"turns, if he is moved by the Dispatcher or the Airlift Event";
std::cout << this->getRole() << std::endl;
}
};
class Scientist : public RoleCard {
public:
Scientist() {
this->name = "Scientist";
this->description = "he Scientist needs only 4 (not 5) City cards of\n"
"the same disease color to Discover a Cure for that\n"
"disease.";
std::cout << this->getRole() << std::endl;
}
}; | true |
e4f21222465b8cb94fe09ad368a1339a3f3cda06 | C++ | nwaiting/wolf-ai | /wolf_alg/Data_structures_and_algorithms_cpp/20181228-dp.cpp | UTF-8 | 1,975 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <stdint.h>
#include <algorithm>
using namespace std;
/*
* 编辑距离:
* 编辑距离又叫Levenshtein(莱文斯坦)距离
* 指两个字串之间,由一个转成另一个所需的最少编辑操作次数
* 俄罗斯科学家Vladimir Levenshtein在1965年提出这个概念
*
* 编辑操作:
* 1、替换一个字符
* 2、插入一个字符
* 3、删除一个字符
*
*/
int edit_dis(const std::string &s1, const std::string &s2)
{
std::vector<std::vector<int32_t>> editdis;
std::vector<int32_t> initdata(s2.size()+1, 0);
for (auto i = 0; i <= s1.size(); i++) {
editdis.push_back(initdata);
}
//先进行初始化
for (auto i = 0; i <= s1.size(); i++) {
editdis[i][0] = i;
}
for (auto i = 0; i <= s2.size(); i++) {
editdis[0][i] = i;
}
//增、删、改三步
for (auto i = 1; i <= s1.size(); i++) {
for (auto j = 1; j <= s2.size(); j++) {
//增和删
int32_t tmp_min = (std::min)(editdis[i - 1][j] + 1, editdis[i][j - 1] + 1);
int32_t d = 0;
if (s1[i-1] != s2[j-1]) {
d = 1;
}
//改
tmp_min = (std::min)(tmp_min, editdis[i - 1][j - 1] + d);
editdis[i][j] = tmp_min;
}
}
#ifdef DEBUG
for (auto &iti : editdis) {
for (auto &itj : iti) {
std::cout << itj << " ";
}
std::cout << std::endl;
}
#endif
return editdis[s1.size()][s2.size()];
}
void showDistance(const std::string &s1, const std::string &s2)
{
std::cout << s1.c_str() << " - " << s2.c_str() << " -> " << edit_dis(s1, s2) << std::endl;
}
int main()
{
showDistance("sailn", "failing"); //1
//由于每个汉字两个字符 所以结果为2
showDistance("汽车音响改装线路","汽车音响改装线路图"); //2
std::cin.get();
return 0;
}
| true |
32f002f385f2cbff9f8215640455c7e313041262 | C++ | KarimIO/Microelectronics-Mosfet-Logic | /graph.hpp | UTF-8 | 3,580 | 2.9375 | 3 | [] | no_license | #ifndef GRAPH_H
#define GRAPH_H
#include <iostream>
#include <string>
#include <map>
enum Network {
PUN = 0,
PDN
};
enum NodeType {
INNODE = 0,
NOTNODE,
ORNODE,
ANDNODE
};
typedef unsigned int uint;
class Node {
public:
virtual NodeType GetType() const = 0;
virtual std::string Traverse() const = 0;
virtual Node *Invert() const = 0;
virtual Node *DeMorgan() const = 0;
virtual uint longestPath() const = 0;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count, float width, float length) const = 0;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count) const = 0;
friend std::ostream& operator<<(std::ostream& os, const Node& dt);
virtual ~Node() {};
};
class InNode : public Node {
public:
InNode(std::string name);
virtual inline NodeType GetType() const;
virtual std::string Traverse() const;
virtual Node *Invert() const;
virtual Node *DeMorgan() const;
virtual uint longestPath() const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count, float width, float length) const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count) const;
virtual ~InNode();
private:
std::string name_;
};
class NotNode : public Node {
public:
NotNode(Node *a);
virtual inline NodeType GetType() const;
virtual std::string Traverse() const;
virtual Node *Invert() const;
virtual Node *DeMorgan() const;
virtual uint longestPath() const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count, float width, float length) const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count) const;
virtual ~NotNode();
private:
Node *a_;
};
class OrNode : public Node {
public:
OrNode(Node *a, Node *b);
virtual inline NodeType GetType() const;
virtual std::string Traverse() const;
virtual Node *Invert() const;
virtual Node *DeMorgan() const;
virtual uint longestPath() const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count, float width, float length) const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count) const;
virtual ~OrNode();
private:
Node *a_;
Node *b_;
};
class AndNode : public Node {
public:
AndNode(Node *a, Node *b);
virtual inline NodeType GetType() const;
virtual std::string Traverse() const;
virtual Node *Invert() const;
virtual Node *DeMorgan() const;
virtual uint longestPath() const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count, float width, float length) const;
virtual std::string Mosfet(std::string up, std::string down, Network network, std::map<std::string, unsigned int> &inverters, unsigned int &transistors_count) const;
virtual ~AndNode();
private:
Node *a_;
Node *b_;
};
#endif | true |
99e130099112434fd4043f0439c6816e918f1d17 | C++ | bryanmlyr/School-Projects | /cpp_pool/cpp_d06/ex00/main.cpp | UTF-8 | 537 | 2.984375 | 3 | [] | no_license | //
// EPITECH PROJECT, 2018
// piscine cpp
// File description:
// ex00
//
#include <string>
#include <fstream>
#include <iostream>
int main(int ac, char **av)
{
std::string str;
if (ac <= 1)
std::cout << "my_cat: Usage: "
<< av[0] << " file [...]" << std::endl;
for (int x = 1; x < ac; x++) {
std::ifstream file(av[x]);
if (!file.is_open()) {
std::cerr << "my_cat: " << av[x]
<< ": No such file or directory" << std::endl;
} else {
while (std::getline(file, str, '\0'))
std::cout << str;
}
}
return 0;
} | true |
9e502ae9e40a098d9ab795250183205417afee2c | C++ | AsiaKorushkina/msu_cpp_autumn_2019 | /02/LinearAllocator.h | UTF-8 | 681 | 3.46875 | 3 | [] | no_license | #include <iostream>
class LinearAllocator
{
size_t maxsize;
size_t cursize;
char* beg;
public:
LinearAllocator(size_t max_Size){
maxsize = max_Size;
cursize = 0;
beg = new char[maxsize];
};
char* alloc(size_t size){
if (size + cursize > maxsize){
return nullptr;
}
char* p = beg + cursize;
cursize += size;
return p;
}
void reset(){
cursize = 0;
}
size_t get_cursize(){
return cursize;
}
char* get_beg(){
return beg;
}
~LinearAllocator(){
maxsize = 0;
cursize = 0;
delete [] beg;
}
}; | true |
f061720226313017aed049769f6db6d50b2fa0dd | C++ | yossy2/Tactics | /MonsterTacics/MonsterTacics/Input/Mouse.cpp | SHIFT_JIS | 2,160 | 2.71875 | 3 | [] | no_license | #include "Mouse.h"
#include <algorithm>
#include <DxLib.h>
#include "../Common/Common.h"
#include "../Mouseable/MouseableObject.h"
int Mouse::CurrentButtonState()const
{
return buttonState_[currentBufferNum_];
}
int Mouse::OldButtonState()const
{
return buttonState_[Wrap(currentBufferNum_ - 1, 0, static_cast<int>(_countof(buttonState_)))];
}
void Mouse::Update()
{
// obt@ւ
currentBufferNum_ = Wrap(currentBufferNum_ + 1, 0, static_cast<int>(_countof(buttonState_)));
// W
GetMousePoint(&pos_.x, &pos_.y);
// NbN
buttonState_[currentBufferNum_] = GetMouseInput();
wheelRotateVolume_ = GetMouseWheelRotVol();
ClearHoldingObject();
}
bool Mouse::GetButtonDown(MOUSE_BUTTON button) const
{
return (CurrentButtonState() & static_cast<int>(button)) && !(OldButtonState() & static_cast<int>(button));
}
bool Mouse::GetButton(MOUSE_BUTTON button) const
{
return (CurrentButtonState() & static_cast<int>(button));
}
bool Mouse::GetButtonUp(MOUSE_BUTTON button) const
{
return !(CurrentButtonState() & static_cast<int>(button)) && (OldButtonState() & static_cast<int>(button));
}
Position2 Mouse::GetPosition() const
{
return pos_;
}
void Mouse::Hold(std::shared_ptr<MouseableObject> obj) const
{
obj->Hold();
holdingObjects_.push_back(obj);
}
bool Mouse::EqualHoldingObject(std::shared_ptr<MouseableObject> obj) const
{
auto it = std::find_if(holdingObjects_.begin(), holdingObjects_.end(), [obj](std::weak_ptr<MouseableObject>& m)
{
return m.lock() == obj;
});
return (it != holdingObjects_.end());
}
std::vector<std::weak_ptr<MouseableObject>>& Mouse::GetHoldingObjects() const
{
return holdingObjects_;
}
void Mouse::ClearHoldingObject() const
{
holdingObjects_.erase(std::remove_if(holdingObjects_.begin(), holdingObjects_.end(),
[](std::weak_ptr<MouseableObject>& m) {
// ɗꂽł͂ȂAactiveɂȂƂAɂȂĂƂȂǂlj\
if (m.expired()) return true;
return m.lock()->IsRelease();
}), holdingObjects_.end());
}
int Mouse::GetWheelRotateVolume() const
{
return wheelRotateVolume_;
}
| true |
4c9613481f68f51f8f50167aa22e64778f13cdce | C++ | marcelgreim/ifi10bcpp | /Notenrechner.cpp | ISO-8859-1 | 1,497 | 3.609375 | 4 | [
"Unlicense"
] | permissive | #include <iostream> // Laden I/O Bibliothek
#include <iomanip> // Laden der Konsolenmanipulationsbibliothek
using namespace std; // Standard Namespace verwenden
int main (void) { // Einsprungpunkt Hauptprogramm
float note; // Variable fr Noteneingabe
float summe; // Variable zum zusammenrechnen
float counter; // Counter fr Anzahl der Noten
char abfrage; // Abfrage der Weiterausfhrung
float schnitt; // Schnitt als Float berechnen
do { // Beginn der Schleife fr die "Hauptfunktion"
cout << "Bitte geben Sie eine Note ein" << endl; // Ausgabe der Abfrage fr die Note
cin >> note; // Note einlesen in Variable Note
if (note >=1 && note <=6) // Abgleich ob es eine gltige Note ist oder nicht, wenn ja dann Zusammenrechnen und Counter +1 setzen
{
summe=summe+note; // Rechnung
counter++; // Counter +1
}
else // Fehlermeldung ausgeben
{
cout << "Dies ist keine Note!" << endl; // Ausgabe des Fehler
}
cout << "Wollen Sie noch eine Note eingeben? Drcken Sie bitte J!" << endl; // Abfrage ob noch eine Note eingegeben werden soll
cin >> abfrage; // Einlesen der Abfrage
}
while (abfrage=='J'); // do-Schleife bis Abfrage gro J entspricht
schnitt=summe/counter; // Berechnen des Schnittes
cout << "Ihr Schnitt betrgt: " << schnitt << endl; // Ausgabe Schnitt
cout << "Sie haben: " << counter << " Noten eingegeben!" << endl; // Ausgabe Counter
}
| true |
c408b0773b81a827aa5292af6f9bff0e35ef3497 | C++ | 99002478/Genisis_Mini_Project_2478 | /Aviation_management_c--main/passenger.h | UTF-8 | 729 | 2.78125 | 3 | [] | no_license | #ifndef __PASSENGER_H
#define __PASSENGER_H
#include<string>
#include"Flight.h"
class Passenger: public Flight{
protected:
std::string PID;
std::string P_name;
std::string email;
std::string phno;
public:
// Constructor
Passenger();
Passenger(std::string ,std::string,std::string ,std::string ,std::string ,std::string,std::string,std::string,double);
//Operations
double computeFare() ;
double computeTravelTime() ;
//getters
std:: string getid();
std::string getname();
std::string getemail();
std::string getphno();
std::string getflight_name();
std::string getflight_id();
std:: string getOrigin();
std:: string getDestination();
double getDistance();
};
#endif
| true |
1acd136b6504576f5489edb9c340dcdd47353773 | C++ | redexpress/CppPrimer5thSolutions | /Sales_data.cpp | UTF-8 | 1,421 | 3.125 | 3 | [] | no_license | //
// Sales_data.cpp
//
// Created by Gavin Yang on 14-7-26.
// Copyright (c) 2014年 redexpress.github.com. All rights reserved.
//
#include "Sales_data.h"
using std::cout;
using std::cin;
std::istream& read(std::istream &in, Sales_data &s){
double price;
in >> s.bookNo >> s.units_sold >> price;
if (in)
s.revenue = s.units_sold * price;
else
s = Sales_data(); // input failed: reset object to default state
return in;
}
std::ostream& print(std::ostream &out, const Sales_data &s){
out << s.isbn() << ' ' << s.units_sold << ' ' << s.revenue << '\n';
return out;
}
std::istream& operator>>(std::istream &in, Sales_data &s){
return read(in, s);
}
std::ostream& operator<<(std::ostream &out, const Sales_data &s){
return print(out, s);
}
bool operator== (const Sales_data &s1, const Sales_data &s2){
return s1.isbn() == s2.isbn();
}
Sales_data::Sales_data(std::istream &is){
read(is, *this);
}
Sales_data& Sales_data::combine (const Sales_data &s){
units_sold += s.units_sold;
revenue += s.revenue;
return *this;
}
Sales_data& Sales_data::operator+= (const Sales_data &s){
return combine(s);
}
double Sales_data::avg_price() const{
if (units_sold)
return revenue / units_sold;
else
return 0;
}
Sales_data add(Sales_data &lhs, Sales_data &rhs){
Sales_data sum = lhs;
sum.combine(rhs);
return sum;
} | true |
2dd5e8277a12316a87d97c688e9f7ed49f6bcce9 | C++ | hemant1170/myprojects | /minmax.cpp | UTF-8 | 8,535 | 3.328125 | 3 | [] | no_license | //This is implementation of Mini-Max algorithm on Tic-Tac-Toe game using C/C++
//This code is not complete as I am working on it nowadays
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
typedef struct data_returned_from_minmax
{
int value;
int path;
}MOVE;
void Go(int n,int turn,int *board); //takes the player to nth postion and records his symbol at that location
void UndoGo(int n,int *board); // Undo the work done by Go
int Posswin(char player,int *board); //returns 0 if no winning position is available with respect to the player being passed otherwise the position which
int Static(int position,char player,int *board,char first_player); //heuristic function returning value taking into consideration the player being passed
int * Movegen(int position, char player,int *board); //generates all plausible moves for the player being passed from its current position
int DeepEnough(int depth,int depthlimit);
char Opposite(char player);
int Win(char player, int * board);
MOVE MinMax(int position,int depth,int depthlimit, int turn, char player, int *board, char player_who_played_first);
using namespace std;
int main()
{
int depthlimit, mov_pos, board[10]={2,2,2,2,2,2,2,2,2,2}, turn=1, current, depth=0;
MOVE my_mov;
char option;
cout<<"\nInput the depth Upto which processing is to be done:";
cin>>depthlimit;
cout<<"\nYou wanna play First or second(f/s):";
cin>>option;
if(option=='f')
{
do
{
cout<<"\nEnter your move position";
cin>>mov_pos;
if(turn==1)
{
if(mov_pos==1)
current=4;
else
current=0;
}
Go(mov_pos-1,turn,board);
cout<<"\nyou moved to position"<<mov_pos;
if(Win('X',board))
{
cout<<"Human has won";
for(int i=0;i<9;i++)
cout<<"\n"<<board[i]<<"\t";
sleep(5);
exit(0);
}
turn++;
my_mov=MinMax(current,depth,depthlimit,turn,'0',board,'H');
Go(my_mov.path,turn,board);
cout<<"\nComputer moved to position"<<(my_mov.path+1);
if(Win('0',board))
{
cout<<"Computer has won";
sleep(5);
exit(0);
}
current=my_mov.path;
turn++;
depth++;
}while(turn<=9);
}
else
{
current=0;
do
{
my_mov=MinMax(current,depth,depthlimit,turn,'X',board,'C');
Go(my_mov.path,turn,board);
cout<<"\nComputer moved to position"<<(my_mov.path+1);
if(Win('X',board))
{
cout<<"Computer has won";
sleep(5);
exit(0);
}
current=my_mov.path;
turn++;
depth++;
cout<<"Enter your move position";
cin>>mov_pos;
Go(mov_pos-1,turn,board);
cout<<"\nyou moved to position"<<mov_pos;
if(Win('0',board))
{
cout<<"Human has won";
for(int i=0;i<9;i++)
cout<<"\n"<<board[i]<<"\t";
sleep(5);
exit(0);
}
turn++;
}while(turn<=9);
}
sleep(5);
return 0;
}
void Go(int n,int turn,int *board)
{
if(turn%2==1) //odd turn
board[n]=3;
else
board[n]=5;
}
void UndoGo(int n,int *board)
{
board[n]=2;
}
int Posswin(char player, int *board)
{
int i,j;
if(player=='X')
{
for(i=0;i<7;i+=3)
{
if(board[i]*board[i+1]*board[i+2]==18) // row wise checking
{
if(board[i]==2)
return i;
else if(board[i+1]==2)
return i+1;
else
return i+2;
}
}
for(i=0;i<3;i++)
{
if(board[i]*board[i+3]*board[i+6]==18) //column wise checking
{
if(board[i]==2)
return i;
else if(board[i+3]==2)
return i+3;
else
return i+6;
}
}
if(board[0]*board[4]*board[8]==18) //diagonal 1
{
if(board[0]==2)
return 0;
else if(board[4]==2)
return 4;
else
return 8;
}
else if(board[2]*board[4]*board[6]==18) //diagonal 2
{
if(board[2]==2)
return 2;
else if(board[4]==2)
return 4;
else
return 6;
}
return 0;
}
else
{
for(i=0;i<7;i+=3)
{
if(board[i]*board[i+1]*board[i+2]==50) // row wise checking
{
if(board[i]==2)
return i;
else if(board[i+1]==2)
return i+1;
else
return i+2;
}
}
for(i=0;i<3;i++)
{
if(board[i]*board[i+3]*board[i+6]==50) //column wise checking
{
if(board[i]==2)
return i;
else if(board[i+3]==2)
return i+3;
else
return i+6;
}
}
if(board[0]*board[4]*board[8]==50) //diagonal 1
{
if(board[0]==2)
return 0;
else if(board[4]==2)
return 4;
else
return 8;
}
else if(board[2]*board[4]*board[6]==50) //diagonal 2
{
if(board[2]==2)
return 2;
else if(board[4]==2)
return 4;
else
return 6;
}
return 0;
}
}
int DeepEnough(int depth,int depthlimit)
{
if(depth>=depthlimit)
return 1;
else
return 0;
}
char Opposite(char player)
{
if(player=='X')
{return '0'; }
else if(player=='0')
{return 'X'; }
}
int Static(int position,char player,int *board,char first_player) //heuristic function returning value taking into consideration the player being passed
{
int wp;//Winning Probability
int mf;//mf:multiplying factor
wp=Posswin(Opposite(player),board);
if((player=='X'&&first_player=='C')||(player=='0'&&first_player=='H'))
mf=1;
if((player=='X'&&first_player=='H')||(player=='0'&&first_player=='C'))
mf=-1;
if(wp==1)
{
return(50*mf);
}
else
{
if (position%2==0)
return(1*mf);
else if(position==5)
return(5*mf);
else
return(3*mf);
}
}
int * Movegen(int position, char player,int *board)
{
int *succ=new int[9];
int count=0,i;
for(i=0;i<9;i++)
{
succ[i]=-1;
}
for(i=0;i<9;i++)
{
if(board[i]==2)
{
succ[count]=i;
count++;
}
}
return(succ);
sleep(5);
}
int Win(char player, int * board)
{
int i,j;
if(player=='X')
{
for(i=0;i<7;i+=3)
{
if(board[i]*board[i+1]*board[i+2]==27) // row wise checking
{
return 1;
}
}
for(i=0;i<3;i++)
{
if(board[i]*board[i+3]*board[i+6]==27) //column wise checking
{
return 1;
}
}
if(board[0]*board[4]*board[8]==27) //diagonal 1
{
return 1;
}
else if(board[2]*board[4]*board[6]==18) //diagonal 2
{
return 1;
}
return 0;
}
else
{
for(i=0;i<7;i+=3)
{
if(board[i]*board[i+1]*board[i+2]==125) // row wise checking
{
return 1;
}
}
for(i=0;i<3;i++)
{
if(board[i]*board[i+3]*board[i+6]==125) //column wise checking
{
return 1;
}
}
if(board[0]*board[4]*board[8]==125) //diagonal 1
{
return 1;
}
else if(board[2]*board[4]*board[6]==125) //diagonal 2
{
return 1;
}
return 0;
}
}
MOVE MinMax(int position,int depth,int depthlimit,int turn, char player, int *board, char first_playing_player)
{
int count=0, val=0, i, *succ=NULL, newvalue, pos, undo=0, bestscore=-1000;
MOVE record,result; //record= new MOVE[9-(depth+1)]; //only this number of new children can be generated at this depth
if(DeepEnough(depth,depthlimit))
{
record.value=Static(position,player,board,first_playing_player);
record.path=0;
return(record);
}
else
{
succ=Movegen(position,player,board);
for(i=0;i<9;i++)
{
if(succ[i]!=-1)
count++;
}
if(count==0)
{
record.value=Static(position,player,board,first_playing_player);
record.path=0;
return(record);
}
else
{
for(i=0;(i<9&&succ[i]!=-1);i++)
{
printf("\n Succ[%d]=%d",i,succ[i]);
Go(succ[i],turn,board); ///changed*****
turn++;
record=MinMax(succ[i],depth+1,depthlimit,turn,Opposite(player),board,first_playing_player); //recursive call
sleep(5);
newvalue=-1*(record.value); //negation of value
if(newvalue>bestscore)
{
cout<<"\nnewvalue :"<<newvalue;
UndoGo(succ[i],board);
turn--; //if better previous best value is attained the move made in the previous best cell is undone
bestscore=newvalue;
result.value=newvalue;
result.path=succ[i];
}
else
{
UndoGo(succ[i],board);
turn--;
}
}
}
}
return(result);
}
| true |
46cd29c11ac0fa0bbb8fa729280bcdf0daad58b5 | C++ | github-jiang/serial_port | /source/test.cpp | GB18030 | 754 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include "SerialPort.h"
using namespace std;
int main()
{
unsigned int Serial_N1 = 1;
CSerialPort mySerialPort1;
if (!mySerialPort1.InitPort(Serial_N1))
{
cout << " ʼ ʧ !" << std::endl;
}
else
{
cout << " ʼ ɹ !" << std::endl;
}
if (!mySerialPort1.OpenListenThread())
{
std::cout << "OpenListenThread fail !" << std::endl;
}
else
{
std::cout << "OpenListenThread success !" << std::endl;
}
cout << "High-speed parallel data transmission system " << endl;
while (1)
{
/*cin >> send_data;
temp[0] = send_data;
mySerialPort1.WriteData(temp, 1);*/
}
return 0;
} | true |
c5954f34b746afc62363b0a46a394508fa11c5bc | C++ | JMarcu/CS1D | /CS1D Final Project/DateMethods.cpp | UTF-8 | 3,369 | 3.171875 | 3 | [] | no_license | /*************************************************************************
* CS1D Final Project
* -----------------------------------------------------------------------
* AUTHORS : James Marcu & Phillip Doyle
* STUDENT IDs : 374443 & 911579
* CLASS : CS1D
* SECTION : TTh 3:30 PM
* DUE DATE : 12/9/2014
*************************************************************************/
#include"DateClass.h"
#include "header.h"
//CONSTRUCTOR
Date:: Date()
{
day = 1;
month = JAN;
year = 0;
}
Date:: Date(Months newMonth, int newDay, int newYear)
{
day = newDay;
month = newMonth;
year = newYear;
}
//DESTRUCTOR
Date:: ~Date()
{
}
//SET-MEMBERS: Members that allow the client to change private data values
void Date::setDay(int newDay)
{
day = newDay;
}
void Date::setYear(int newYear)
{
year = newYear;
}
void Date::setMonth(Months newMonth)
{
month = newMonth;
}
void Date::setDate(Months newMonth, int newDay, int newYear)
{
day = newDay;
month = newMonth;
year = newYear;
}
//GET MEMBERS: Allow client to access private data values
int Date::getDay() const
{
return day;
}
int Date::getYear() const
{
return year;
}
Months Date::getMonth() const
{
return month;
}
//OPERATOR-OVERLOAD: Overloads of comparison operators
// to compare two dates
bool Date::operator == (Date compareTo) const
{
return (day == compareTo.day && month == compareTo.month &&
year == compareTo.year);
}
bool Date::operator > (Date compareTo) const
{
return ((day > compareTo.day)
&& (month > compareTo.month)
&& (year > compareTo.year));
}
bool Date::operator < (Date compareTo) const
{
return ((day < compareTo.day)
&& (month < compareTo.month)
&& (year < compareTo.year));
}
bool Date::operator <= (Date compareTo) const
{
if(year < compareTo.getYear())
{
return true;
}
else if (year > compareTo.getYear())
{
return false;
}
else
{
if(month < compareTo.getMonth())
{
return true;
}
else if (month > compareTo.getMonth())
{
return false;
}
else
{
if(day <= compareTo.getDay())
{
return true;
}
else
{
return false;
}
}
}
}
bool Date::operator >= (Date compareTo) const
{
return ((day >= compareTo.day)
&& (month >= compareTo.month)
&& (year >= compareTo.year));
}
/*************************************************************************
* FUNCTION PrintData
* _______________________________________________________________________
* This method outputs the date in a formatted style
* _______________________________________________________________________
* PRE-CONDITIONS
* none
* POST-CONDTIONS
* This function will output the date
************************************************************************/
string Date::printDate() const
{
std::ostringstream output;
if( month < 10)
{
output << '0';
}
output << month;
output << '/';
if( day < 10)
{
output << '0';
}
output << day;
output << '/';
output << year;
return output.str();
}
| true |
c6925906ca493a14cf1b819034a4599d691a32ec | C++ | mnunberg/epoxy | /src/buffer.h | UTF-8 | 3,591 | 2.75 | 3 | [] | no_license | #ifndef LCBPROXY_BUFFER_H
#define LCBPROXY_BUFFER_H
#include <cstdlib>
#include <vector>
#include "common.h"
// This is a miniature version of rdb_ROPE implemented in C++
// rather than C
namespace Epoxy {
class BufferPool;
class Buffer;
class BufferPool {
public:
BufferPool();
~BufferPool();
void put(Buffer*);
Buffer* get(size_t n = 0);
private:
std::vector<Buffer*> buffers;
size_t itemCapacity;
size_t itemBlockSize;
};
class Buffer {
public:
/**
* Creates a new buffer object
* @param n The capacity of the buffer
*/
Buffer(size_t n, BufferPool *pool);
~Buffer();
/**
* Get the current capacity of the buffer
* @return The maximum number of bytes which may be written to the buffer
*/
size_t capacity() const { return allocated - (offset+ndata); }
/**
* Get the size of used data in the buffer
* @return The number of bytes which may be read from the buffer
*/
size_t size() const { return ndata; }
/** @brief equivalent to size() == 0 */
bool empty() const { return ndata == 0; }
/**
* Obtain a pointer to the first byte in the buffer. This buffer may be
* used for reading data up to size() bytes
* @return A pointer to the first used byte
*/
char *getReadHead() { return data + offset; }
/**
* Obtain a pointer to the first unused byte in the buffer. This buffer
* may be used for adding data up to capacity() bytes.
* @return a pointer to the first unused byte.
*/
char *getWriteHead() { return data + offset + ndata; }
/**
* Indicate that bytes in the buffer are no longer required. This will
* have the effect of consuming the specified number of bytes (from the
* beginning of the buffer) so that subsequent reads will not return
* these bytes.
*
* @param n The number of bytes no longer required
*/
void consumed(size_t n);
/**
* Indicate that data has been added to the buffer
* @param the total number of bytes which may have been added to the buffer
* @return The number of actual bytes added to the buffer
* @note This method is intended to be used if reading into an iovec-like
* structure where there are multiple Buffer objects. In such a scenario
* the socket recv() routine only reports the total number of bytes received.
* The intended use case is to traverse all the elements in the iovec array,
* calling each element's corresponding Buffer::added() function and
* decrementing the total number of bytes read by the return value from this
* method.
*/
size_t added(size_t nw);
/** Clear the buffer. This resets all offsets */
void clear();
void ref() { refcount++; }
void unref();
void fillIovec(iovec& iov) { iov.iov_base = getWriteHead(); iov.iov_len = capacity(); }
private:
size_t ndata;
size_t refcount;
size_t offset;
size_t allocated;
char *data;
BufferPool *parent;
friend class BufferPool;
};
struct ReadContext {
ReadContext() { chopFirst = false; }
bool chopFirst;
iovec iov[EPOXY_NREAD_IOV];
Buffer *bk[EPOXY_NREAD_IOV];
};
class Rope {
public:
Rope(BufferPool* pool);
bool getContig(char *s, size_t n);
void getFrags(size_t n, std::vector<Buffer*>& bufs, std::vector<iovec>& iov);
void getReadBuffers(ReadContext&);
void setReadAdded(ReadContext&, size_t n);
void consumed(size_t n);
size_t size();
private:
std::list<Buffer *> bufs;
BufferPool *bp;
};
}
#endif
| true |
a81c35ad9360d887010ff69ce640fd47ea692d3f | C++ | Nadezhda-Frantseva/Object-oriented-programming | /MyAccount.hpp | UTF-8 | 576 | 2.9375 | 3 | [] | no_license | #pragma once
#include <string>
#include "Cart.hpp"
class MyAccount
{
public:
MyAccount();
MyAccount(const std::string& name, const std::string& email, const std::string& password);
void enter_name(std::string name);
void enter_emai(std::string email);
void enter_password(std::string password);
void set_name(const std::string& new_name);
void set_email(const std::string& new_email);
void set_password(const std::string& new_password);
std::string get_username()const;
private:
std::string name;
std::string email;
std::string password;
Cart MyCart;
};
| true |
2aef8a6f4418e07a392e3ea7e7a9f675a0dd1e31 | C++ | jpeterson1823/AdventOfCode | /2021/c/day6/day6.cpp | UTF-8 | 672 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
// get input
string input;
cin >> input;
// create fish vector
vector<unsigned long> days = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
// log initial fish
for (char c : input) {
if (c != ',')
days[c - '0']++;
}
// loop for n days
for (int day = 0; day < 256; day++) {
// group each fish by it's day
int today = day % 9;
// push fish group by 7
days[(today+7) % 9] += days[today];
}
// sum up all fish
unsigned long numFish = 0;
for (unsigned long day : days)
numFish += day;
cout << "Number of fish: " << numFish << endl;
return 0;
} | true |
50ca90f8718ca8e95c1514ce2d4560955dc72e8c | C++ | Jesse-Rug/ComputerGraphics | /raytracer/raytracerframework_cpp/Code/shapes/sphere.cpp | UTF-8 | 2,803 | 3.265625 | 3 | [
"MIT"
] | permissive | #include "sphere.h"
#include "solvers.h"
#include <cmath>
using namespace std;
Hit Sphere::intersect(Ray const &ray)
{
// Sphere formula: ||x - position||^2 = r^2
// Line formula: x = ray.O + t * ray.D
Vector L = ray.O - position;
double a = ray.D.dot(ray.D);
double b = 2 * ray.D.dot(L);
double c = L.dot(L) - r * r;
double t0;
double t1;
if (not Solvers::quadratic(a, b, c, t0, t1))
return Hit::NO_HIT();
// t0 is closest hit
if (t0 < 0) // check if it is not behind the camera
{
t0 = t1; // try t1
if (t0 < 0) // both behind the camera
return Hit::NO_HIT();
}
// calculate normal
Point hit = ray.at(t0);
Vector N = (hit - position).normalized();
// determine orientation of the normal
if (N.dot(ray.D) > 0)
N = -N;
return Hit(t0, N);
}
Sphere::Sphere(Point const &pos, double radius)
:
position(pos),
r(radius),
axis( Vector(0, 1, 0)),
angle(0.0)
{}
Sphere::Sphere(Point const &pos, double radius, Vector const &rotation, double angle)
:
position(pos),
r(radius),
axis(rotation),
angle(angle)
{
Vector rAxis = rotation.normalized().cross(Vector(0, 1, 0));
double cos = rotation.normalized().dot(Vector(0, 1, 0));
double theta = std::acos(cos);
Vector S0(0, -rAxis.z, rAxis.y);
Vector S1(rAxis.z, 0, -rAxis.x);
Vector S2(-rAxis.y, rAxis.x, 0);
Vector ST0(S0.x, S1.x, S2.x);
Vector ST1(S0.y, S1.y, S2.y);
Vector ST2(S0.z, S1.z, S2.z);
Vector Ssq0(S0.dot(ST0), S0.dot(ST1), S0.dot(ST2));
Vector Ssq1(S1.dot(ST0), S1.dot(ST1), S1.dot(ST2));
Vector Ssq2(S2.dot(ST0), S2.dot(ST1), S2.dot(ST2));
rotMatrix[0] = Vector(1, 0, 0) + (S0 * theta) + (Ssq0 * (1 - cos));
rotMatrix[1] = Vector(0, 1, 0) + (S1 * theta) + (Ssq1 * (1 - cos));
rotMatrix[2] = Vector(0, 0, 1) + (S2 * theta) + (Ssq2 * (1 - cos));
}
//https://www.gamedev.net/forums/topic/61727-aligning-two-vectors/
Vector Sphere::getTextureCoord(Point hit)
{
Point point((hit - position).normalized());
double pi = 3.14159265359;
Point normal;
normal.x = point.dot(rotMatrix[0]);
normal.y = point.dot(rotMatrix[1]);
normal.z = point.dot(rotMatrix[2]);
normal.normalize();
//normal is now a point on a unit sphere that points up(ish), centered around the origin
double u = atan2(normal.x , normal.z) / (2* pi) + 0.5 + (angle / 360);
for(; u > 1.0; u -= 1.0 ); // or while (u > 1.0) u -= 1.0;
double v = 0.5 - (asin(normal.y) / pi);
// std::atan2 returns on the range of [-PI, PI], dividing by 2 PI mapping to [-.5, .5] and finally to [0,1]
// the final part adds the angle disposition
// https://en.wikipedia.org/wiki/UV_mapping
return Vector(u, v, 0);
}
| true |
1918e3e5b23eaa15bfa82c1822114b5f45df049e | C++ | v-str/SpecialCalculator | /Styles/label_styler.cpp | UTF-8 | 1,407 | 2.875 | 3 | [] | no_license | #include "label_styler.h"
#include <QLabel>
#include <QString>
void LabelStyler::SetLabel(QLabel *label, int style) {
QString label_text = label->text();
QString background_format = "color";
QString image = "";
if (label_text == "Number:") {
background_format = "image";
image = "url(:/motogp_logo.jpg)";
} else if (label_text == "Result:") {
background_format = "image";
image = "url(:/moto.jpg)";
}
switch (style) {
case 0:
SetStyleSheet(label, label_text, "green", background_format, "black");
break;
case 1:
SetStyleSheet(label, label_text, "#CC6600", background_format, "#404040");
break;
case 2:
SetStyleSheet(label, "", "white", background_format, image);
break;
}
}
void LabelStyler::SetStyleSheet(QLabel *label, const QString &text_of_label,
const QString &text_color,
const QString &background_format,
const QString &background) {
label->setText(text_of_label);
QString temporary_background_format = "background-color: ";
if (background_format == "image") {
temporary_background_format = "background-image: ";
}
QString style_sheet =
"QLabel {"
"color: %1;"
"%2%3;"
"}";
label->setStyleSheet(
style_sheet.arg(text_color, temporary_background_format, background));
}
| true |
6f8702c2c16d7eae336d439ab8935e8d493426a1 | C++ | breezy1812/MyCodes | /Algorithm/ACM-POJ/POJ-2155-SegmentTree/solution.cpp | UTF-8 | 2,223 | 2.546875 | 3 | [] | no_license | // Author: David
// Email: youchen.du@gmail.com
// Created: 2016-07-05 14:38
// Last modified: 2016-07-06 10:10
// Filename: solution.cpp
// Description:
#include <cstdio>
#include <cstring>
using namespace std;
#define ll long long
#define N 1010
int A[N];
int x1, y1, x2, y2;
int n, t;
bool tree[N<<2][N<<2];
int ans;
void editY(int i, int l, int r, int j, int y1, int y2)
{
if(l>=y1&&r<=y2)
{
tree[i][j] ^= 1;
return;
}
int mid = (l+r)>>1;
if(y2<=mid)
editY(i, l, mid, j*2, y1, y2);
else if(y1>mid)
editY(i, mid+1, r, j*2+1, y1, y2);
else
{
editY(i, l, mid, j*2, y1, y2);
editY(i, mid+1, r, j*2+1, y1, y2);
}
}
void editX(int i, int l, int r, int x1, int y1, int x2, int y2)
{
if(l>=x1&&r<=x2)
{
editY(i, 1, n, 1, y1, y2);
return;
}
int mid = (l+r)>>1;
if(x2<=mid)
editX(2*i, l, mid, x1, y1, x2, y2);
else if(x1>mid)
editX(2*i+1, mid+1, r, x1, y1, x2, y2);
else
{
editX(2*i, l, mid, x1, y1, x2, y2);
editX(2*i+1, mid+1, r, x1, y1, x2, y2);
}
}
void queryY(int i, int l, int r, int j, int y)
{
ans ^= tree[i][j];
if(l==r)
return;
int mid = (l+r)>>1;
if(y<=mid)
queryY(i, l, mid, j*2, y);
else
queryY(i, mid+1, r, j*2+1, y);
}
void queryX(int i, int l, int r, int x, int y)
{
queryY(i, 1, n, 1, y);
if(l==r)
return;
int mid = (l+r)>>1;
if(x<=mid)
queryX(i*2, l, mid, x, y);
else
queryX(i*2+1, mid+1, r, x, y);
}
int main()
{
int CASE;
char c[3];
scanf("%d", &CASE);
while(CASE--)
{
memset(tree, 0, sizeof(tree));
scanf("%d%d", &n, &t);
for(int zz=1;zz<=t;zz++)
{
scanf("%s", c);
if(c[0]=='C')
{
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
editX(1, 1, n, x1, y1, x2, y2);
}
else if(c[0]=='Q')
{
ans = 0;
scanf("%d%d", &x1, &y1);
queryX(1, 1, n, x1, y1);
printf("%d\n", ans);
}
}
if(CASE)
printf("\n");
}
return 0;
}
| true |
5fdad067f60e0f7dd73417168bf938309ab8c259 | C++ | huaweicloud/huaweicloud-sdk-cpp-v3 | /gaussdb/src/v3/model/ModifyPortRequest.cpp | UTF-8 | 1,327 | 2.53125 | 3 | [] | permissive |
#include "huaweicloud/gaussdb/v3/model/ModifyPortRequest.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Gaussdb {
namespace V3 {
namespace Model {
ModifyPortRequest::ModifyPortRequest()
{
port_ = 0;
portIsSet_ = false;
}
ModifyPortRequest::~ModifyPortRequest() = default;
void ModifyPortRequest::validate()
{
}
web::json::value ModifyPortRequest::toJson() const
{
web::json::value val = web::json::value::object();
if(portIsSet_) {
val[utility::conversions::to_string_t("port")] = ModelBase::toJson(port_);
}
return val;
}
bool ModifyPortRequest::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("port"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("port"));
if(!fieldValue.is_null())
{
int32_t refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setPort(refVal);
}
}
return ok;
}
int32_t ModifyPortRequest::getPort() const
{
return port_;
}
void ModifyPortRequest::setPort(int32_t value)
{
port_ = value;
portIsSet_ = true;
}
bool ModifyPortRequest::portIsSet() const
{
return portIsSet_;
}
void ModifyPortRequest::unsetport()
{
portIsSet_ = false;
}
}
}
}
}
}
| true |
fb4498fd17a098b233e1a4aaefca6502a1ec6be7 | C++ | aminb7/SuperMario | /source/Koopa.cpp | UTF-8 | 1,627 | 3.109375 | 3 | [] | no_license | #include "Koopa.hpp"
Koopa::Koopa(Point _position ) :position(_position){}
Point Koopa::getPosition(){
return position;
}
void Koopa::setDirection(string _direction){
direction = _direction;
}
void Koopa::setSituation(string _situation){
situation = _situation;
}
void Koopa::setFallingVelocity(int velocity){
fallingVelocity = velocity;
}
void Koopa::setKickingSituation(int _kickingSituation){
kickingSituation = _kickingSituation;
}
string Koopa::getSituation(){
return situation;
}
int Koopa::getWidth(){
return width;
}
int Koopa::getHeight(){
return height;
}
string Koopa::getDirection(){
return direction;
}
int Koopa::getKickingSituation(){
return kickingSituation;
}
string Koopa::imageAddress(){
string imageAddress = KOOPA_ADDRESS;
imageAddress.append(SLASH);
imageAddress.append(situation);
if(situation != DYING){
imageAddress.append(MINUS);
imageAddress.append(direction);
}
imageAddress.append(".png");
return imageAddress;
}
void Koopa::move(){
if(direction == RIGHT)
position = Point(position.x + 2, position.y);
if(direction == LEFT)
position = Point(position.x - 2, position.y);
}
void Koopa::kick(){
if(direction == RIGHT)
position = Point(position.x + 10, position.y);
if(direction == LEFT)
position = Point(position.x - 10, position.y);
}
void Koopa::fall(){
position = Point(position.x , position.y + fallingVelocity);
}
void Koopa::changWalkingStyle(){
if(situation == WALKING_TYPE1){
situation = WALKING_TYPE2;
return;
}
if(situation == WALKING_TYPE2){
situation = WALKING_TYPE1;
return;
}
}
| true |
addb967fdd75595c12405116e90fb242b645c14d | C++ | xb-hub/PAT-Advanced-Level-Practice | /1047 Student List for Course/main.cpp | UTF-8 | 666 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n, k, c, course;
scanf("%d %d", &n, &k);
vector<string> record[2501];
for(int i = 0; i < n; i++)
{
string name;
cin >> name >> c;
for(int j = 0; j < c; j++)
{
scanf("%d", &course);
record[course].push_back(name);
}
}
for(int i = 1; i <= k; i++)
{
sort(record[i].begin(), record[i].end());
printf("%d %d\n", i, record[i].size());
for(int j = 0; j < record[i].size(); j++)
{
printf("%s\n", record[i][j].c_str());
}
}
} | true |
f7ac737709de1198fdc720f93ebb42db0a354379 | C++ | rjtsdl/CPlusPlus | /Interview Play CPP/a261GraphValidTree.cpp | UTF-8 | 1,060 | 2.921875 | 3 | [] | no_license | //
// a261GraphValidTree.cpp
// Interview Play CPP
//
// Created by Jingtao Ren on 9/18/20.
// Copyright © 2020 Jingtao Ren. All rights reserved.
//
#include <stdio.h>
#include <vector>
#include <list>
using namespace std;
class Solution {
public:
bool validTree(int n, vector<vector<int>>& edges) {
if (edges.size() != n-1) return false;
vector<list<int>> grf(n);
for (vector<int>& e : edges) {
int f = e[0];
int t = e[1];
grf[f].push_back(t);
grf[t].push_back(f);
}
vector<bool> visited(n, false);
int startNode = 0;
int counter = 0;
dfs(grf, startNode, visited, counter);
return counter == n;
}
void dfs(vector<list<int>>& grf, int startNode, vector<bool>& visited, int& counter) {
if (visited[startNode]) return;
visited[startNode] = true;
counter++;
for (int a : grf[startNode]) {
dfs(grf, a, visited, counter);
}
}
};
| true |
f10b719d99487d570fe44605c0de38eb5f1bcd9a | C++ | isongbo/MyCode | /01_Code/10_STL/day01/macro.cpp | UTF-8 | 407 | 3.46875 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define MAX(T) \
T max_##T (T x, T y) { \
return x > y ? x : y; \
}
MAX (int) // int max_int (int x, int y) {...}
MAX (double)
MAX (string)
#define max(T) max_##T
int main (void) {
cout << max(int) (123, 456) << endl;
// cout << max_int (123, 456) << endl;
cout << max(double) (1.23, 4.56) << endl;
cout << max(string) ("hello", "world")
<< endl;
return 0;
}
| true |
49be7d8041c0474eb475131e753ecfc33fe77438 | C++ | joaovicmendes/ic | /src/list.cpp | UTF-8 | 1,838 | 3.21875 | 3 | [] | no_license | #include <queue>
#include "./list.h"
unsigned int List::Schedule(unsigned int no_machines, std::queue<unsigned int> job_list)
{
unsigned int makespan;
unsigned int *loads = new unsigned int[no_machines];
for (unsigned int i = 0; i < no_machines; i++)
loads[i] = 0;
while (!job_list.empty())
{
// Recebendo a próxima tarefa
unsigned int job = job_list.front();
job_list.pop();
// Decisão gulosa: escalonar a tarefa atual na maquina menos carregada
loads[0] += job;
List::sort(no_machines, loads);
}
// Definindo makespan (máquina mais carregada)
makespan = loads[no_machines-1];
delete [] loads;
return makespan;
}
unsigned int List::min(unsigned int no_machines, const unsigned int *loads)
{
unsigned int min_load = UINT_MAX, min_index = 0;
for (unsigned int i = 0; i < no_machines; i++)
{
if (loads[i] < min_load)
{
min_index = i;
min_load = loads[i];
}
}
return min_index;
}
unsigned int List::max(unsigned int no_machines, const unsigned int *loads)
{
unsigned int max_load = 0, max_index = 0;
for (unsigned int i = 0; i < no_machines; i++)
{
if (loads[i] > max_load)
{
max_index = i;
max_load = loads[i];
}
}
return max_index;
}
void List::sort(unsigned int no_machines, unsigned int *loads, unsigned int index)
{
bool swapped = true;
while (swapped && index < no_machines-1)
{
if (loads[index] > loads[index+1])
{
unsigned int aux = loads[index+1];
loads[index+1] = loads[index];
loads[index] = aux;
swapped = true;
index++;
}
else
swapped = false;
}
}
| true |
d133a1849c564274711755a3634b37b971d01f6d | C++ | Orb-H/nojam | /source/nojam/1865.cpp | UTF-8 | 1,326 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <tuple>
#define INF 1073741823
#define ti3 tuple<int, int, int>
using namespace std;
int main() {
int tc;
int n, m, w;
int src, dst, dis;
cin >> tc;
for (int i = 0; i < tc; i++) {
cin >> n >> m >> w;
vector<ti3> path;
vector<int> dist(n + 1, INF);
int flag = 1;
for (int j = 0; j < m; j++) {
cin >> src >> dst >> dis;
path.push_back({src, dst, dis});
path.push_back({dst, src, dis});
}
for (int j = 0; j < w; j++) {
cin >> src >> dst >> dis;
path.push_back({src, dst, -dis});
}
dist[1] = 0;
for (int j = 0; j < n - 1; j++) {
for (vector<ti3>::iterator it = path.begin(); it < path.end(); it++) {
if (dist[get<0>(*it)] + get<2>(*it) < dist[get<1>(*it)]) {
dist[get<1>(*it)] = dist[get<0>(*it)] + get<2>(*it);
}
}
}
for (vector<ti3>::iterator it = path.begin(); it < path.end(); it++) {
if (dist[get<0>(*it)] + get<2>(*it) < dist[get<1>(*it)]) {
flag = 0;
cout << "YES\n";
break;
}
}
if (flag)
cout << "NO\n";
}
} | true |
44377577ff628f9a9ee05eb9fbdeb9b8c52a0568 | C++ | jang7y/BJ | /BJ_10868.cpp | UTF-8 | 373 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> arr;
int a, b;
int x, y;
int main()
{
scanf("%d %d", &a, &b);
arr.resize(a + 1, 0);
for (int i = 1; i <= a; i++)
{
scanf("%d", &arr[i]);
}
for (int i = 1; i <= b; i++)
{
scanf("%d %d", &x, &y);
printf("%d\n", *min_element(arr.begin() + x , arr.begin() + y+1));
}
} | true |
61f71e53fa3e0c8c0ae045d8409d698af136e321 | C++ | tonisor/ext | /src/testing.cpp | UTF-8 | 16,082 | 2.796875 | 3 | [] | no_license | #include <random>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <utility>
#include <tuple>
#include <array>
#include <regex>
#include <string>
#include <memory>
#include "ext/type_traits.hpp"
#include "ext/cmath.hpp"
#include "ext/bigint.hpp"
#include "ext/enum.hpp"
template <typename T>
T RandomInRange(const T& minValue, const T& maxValue)
{
static std::mt19937 randomNumberGenerator;
randomNumberGenerator.seed(static_cast<decltype(randomNumberGenerator)::result_type>(__rdtsc()));
return minValue + randomNumberGenerator() % (maxValue - minValue + 1);
}
//inline constexpr uint_least8_t gcd()
//{
// return 0;
//}
//
//template <typename TFirst, typename... TTail> inline constexpr
//widest_type_t<make_unsigned_or_keep_t<std::decay_t<TFirst>>, make_unsigned_or_keep_t<std::decay_t<TTail>>...>
//gcd(TFirst&& first, TTail&&... tail)
//{
// //static_assert(std::is_integral<Ta>::value, "First parameter should be of an integral type.");
// //static_assert(std::is_integral<Tb>::value, "Second parameter should be of an integral type.");
// return sizeof...(tail) == 0 ? abs(first) :
// sizeof...(tail) == 1 ? (abs(tail...) == 0 ? abs(first) : gcd(abs(tail...), abs(first) % abs(tail...))) :
// gcd(first, gcd(tail...));
//}
//template <char VariableName, typename TVariableFactor = int_max_t>
//struct EquationTerm
//{
// static const decltype(VariableName) variableName = Name;
// typedef TVariableFactor factorType;
//};
//template <typename> T
//struct
//
//template <std::size_t NVariables = 2, char X = 'x', char Y = 'y', typename CX = int_fast32_t, typename CY = int_fast32_t, typename CC = int_fast32_t>
//class Equation
//{
//public:
// constexpr explicit Equation() :
//
//private:
//
//};
//template <typename T = void>
//struct Op1Square
//{
// template <typename T1>
// auto operator()(T1&& v1) const
// {
// return static_cast<T1&&>(v1) * static_cast<T1&&>(v1);
// }
//};
template <typename T> struct type_c;
template <typename ...T> struct tuple_c;
template <typename T>
struct type_c
{
constexpr type_c() {}
using type = T;
template <typename TOther>
friend constexpr auto operator+(const type_c<T>& left, const type_c<TOther>& right)
{
return tuple_c<T, TOther>{};
}
template <typename ...TOther>
friend constexpr auto operator+(const type_c<T>& left, const tuple_c<TOther...>& other)
{
return tuple_c<T, TOther...>{};
}
};
template <typename ...T>
struct tuple_c
{
constexpr tuple_c() {}
using type = std::tuple<T...>;
template <typename TOther>
friend constexpr auto operator+(const tuple_c<T...>& left, const type_c<TOther>& right)
{
return tuple_c<T..., TOther>{};
}
template <typename ...TOther>
friend constexpr auto operator+(const tuple_c<T...>& left, const tuple_c<TOther...>& other)
{
return tuple_c<T..., TOther...>{};
}
};
template <std::size_t N>
struct base_struct
{
using membersType = tuple_c<>;
typename membersType::type members_;
template <std::size_t I>
const auto& get() const { return std::get<I>(members_); }
template <std::size_t I>
auto& get() { return std::get<I>(members_); }
};
struct s0
{
using membersType = tuple_c<>;
static constexpr auto memberCount = std::tuple_size_v<typename membersType::type>;
static constexpr std::array<const char*, memberCount> memberNames_ = { {} };
typename membersType::type members_;
template <std::size_t I>
const auto& get() const { return std::get<I>(members_); }
template <std::size_t I>
auto& get() { return std::get<I>(members_); }
};
constexpr std::size_t strlen_c(const char* str)
{
return *str != char{0} ? 1 + strlen_c(str + 1) : 0;
}
constexpr bool strequal_c(const char* left, const char* right)
{
return *left == char{0}
? *right == char{0}
? true
: false
: *right == char{0}
? false
: (*left != *right)
? false
: strequal_c(left + 1, right + 1)
;
}
template <std::size_t N, std::size_t I = N - 1>
constexpr auto find(const std::array<const char*, N>& a, const char* str) -> std::enable_if_t<(I >= N), std::pair<std::size_t, bool>>
{
return find<N, N - 1>(a, str);
}
template <std::size_t N, std::size_t I = N - 1>
constexpr auto find(const std::array<const char*, N>& a, const char* str) -> std::enable_if_t<(N > 0) && I == 0, std::pair<std::size_t, bool>>
{
return std::make_pair(0, strequal_c(a[0], str));
}
template <std::size_t N, std::size_t I = N - 1>
constexpr auto find(const std::array<const char*, N>& a, const char* str) -> std::enable_if_t<(I < N) && (I > 0), std::pair<std::size_t, bool>>
{
return N < 1
? std::make_pair(std::size_t{}, false)
: strequal_c(a[I], str)
? std::make_pair(I, true)
: find<N, I - 1>(a, str)
;
}
//template <std::size_t I = 1>
//constexpr std::pair<std::size_t, bool> find(const std::array<const char*, 2>& a, const char* str)
//{
// return (I == 0
// ? std::make_pair(I, strequal_c(a[0], str))
// : (strequal_c(a[I], str)
// ? std::make_pair(I, true)
// : find<I - 1>(a, str)))
// ;
//}
//
//template <>
//constexpr std::pair<std::size_t, bool> find<0>(const std::array<const char*, 2>& a, const char* str)
//{
// return std::make_pair(0, strequal_c(a[0], str));
//}
struct s2
{
using membersType = std::tuple<int, bool>;
static constexpr auto memberCount = std::tuple_size_v<membersType>;
static constexpr std::array<const char*, memberCount> memberNames_ = { { "range", "valid" } };
membersType members_;
template <std::size_t I>
const auto& get() const
{
static_assert(I < memberCount, "Template parameter I is too large");
return std::get<I>(members_);
}
template <std::size_t I>
auto& get()
{
static_assert(I < memberCount, "Template parameter I is too large");
return std::get<I>(members_);
}
//const auto& get(const char* member) const
//{
// constexpr std::pair<std::size_t, bool> findResult = find(memberNames_, member);
// static_assert(findResult.second, "Member not found in struct");
// return get<findResult.first>();
//}
//auto& get(const char* member)
//{
// constexpr std::pair<std::size_t, bool> findResult = find(memberNames_, member);
// static_assert(findResult.second, "Member not found in struct");
// return get<findResult.first>();
//}
const auto& range() const { return get<0>(); }
auto& range() { return get<0>(); }
const auto& valid() const { return get<1>(); }
auto& valid() { return get<1>(); }
private:
template <std::size_t I>
static constexpr std::size_t find_impl(const char* str)
{
return strequal_c(memberNames_[I], str) ? I : find_impl<I + 1>(str);
}
template <>
static constexpr std::size_t find_impl<memberCount>(const char* str)
{
return memberCount;
}
public:
static constexpr std::size_t find(const char* str)
{
return find_impl<0>(str);
}
};
//#define DECLARE_STRUCT(name, type1, member1, type2, member2) \
// struct name { \
// using membersType = tuple_c<type1, type2>; \
// static constexpr auto memberCount = std::tuple_size_v<typename membersType::type>; \
// static constexpr std::array<const char*, memberCount> memberNames_ = { { #member1, #member2 } }; \
// typename membersType::type members_; \
// template <std::size_t I> \
// const auto& get() const { return std::get<I>(members_); } \
// template <std::size_t I> \
// auto& get() { return std::get<I>(members_); } \
// const auto& ##member1() const { return get<0>(); } \
// auto& ##member1() { return get<0>(); } \
// const auto& ##member2() const { return get<1>(); } \
// auto& ##member2() { return get<1>(); } \
// };
//
//DECLARE_STRUCT(macroStruct,
// int, range,
// bool, valid)
class object_t
{
public:
template <typename T>
object_t(T v) : self_(std::make_shared<model<T>>(std::move(v))) {}
std::string to_string() const
{
return self_->to_string();
}
private:
struct concept_t
{
virtual ~concept_t() = default;
virtual std::string to_string() const = 0;
};
template <typename T>
class model : concept_t
{
model(T v) : data_(std::move(v)) {}
std::string to_string() const { return std::string(); }
T data_;
};
std::shared_ptr<const concept_t> self_;
};
template <typename T>
void my_println(const T& v)
{
std::cout << v << std::endl;
}
template <typename T>
void my_println(const std::vector<T>& v)
{
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
void test1()
{
std::vector<int> a(10);
std::vector<int> b(10, 10);
int x = 3;
std::generate(a.begin(), a.end(), [&x]() { return x++; });
my_println(a);
my_println(b);
std::remove_copy(b.begin(), b.begin() + 5, a.begin() + 5, 10);
my_println(a);
my_println(b);
int i; std::cin >> i;
}
struct ZZ
{
int x;
ZZ(int z) : x(z) {}
};
struct Bau
{
Bau() {}
Bau(const ZZ& z) {}
Bau(const ZZ&&) = delete;
};
//template <typename T>
//struct szt
//{
// static constexpr int value = int(sizeof(T));
// char* value(char* currentValue, const T& value)
// {
// return currentValue + sizeof(value);
// }
//};
template <typename T>
void GenericSave(char*& currentValue, const T& value, size_t sizeOfValue)
{
currentValue += sizeof(value);
}
//#define GENERIC_SAVE(currentValue, value) { currentValue += sizeof(value); }
//#define xstr(TUse, currentValue, value) GENERIC_SAVE(TUse, currentValue, value)
//#define GENERIC_SAVE(TUse, currentValue, value) { GenericSave##TUse(currentValue, value); }
constexpr int bau(const int x) { return sizeof(decltype(x)); }
enum SaveUse : uint8_t
{
kSave,
kAddSaveSize,
};
template <SaveUse TUse> struct generic_save;
template<> struct generic_save<kSave> { typedef char* type; };
template<> struct generic_save<kAddSaveSize> { typedef uintptr_t type; };
template <SaveUse TUse>
using generic_save_t = typename generic_save<TUse>::type;
template <SaveUse TUse, typename T>
auto gensave(T&& value) -> std::enable_if_t<TUse == kSave, generic_save_t<TUse>>
{
std::cout << value;
return nullptr;
}
template <SaveUse TUse, typename T>
constexpr auto gensave(T&& value) -> std::enable_if_t<TUse == kAddSaveSize, generic_save_t<TUse>>
{
return sizeof(value);
}
class Obj
{
int mInt;
bool mBool;
enum HelperType : uint8_t
{
eSave,
eGetSaveSize,
};
template <HelperType Type>
std::conditional_t<Type == eSave, char*, size_t> Generic(char* buffer = nullptr) const;
public:
int getInt() const { return mInt; }
bool getBool() const { return mBool; }
char* Save(char* buffer) const { return Generic<eSave>(buffer); }
size_t GetSaveSize() const { return Generic<eGetSaveSize>(); }
};
template <Obj::HelperType Type>
std::conditional_t<Type == Obj::eSave, char*, size_t> Obj::Generic(char* buffer) const
{
typedef std::conditional_t<Type == eSave, char*, size_t> TRetVal;
TRetVal retval = reinterpret_cast<TRetVal>(Type == eSave ? buffer : 0);
auto process = [&retval](auto&& v) {
if (Type == eSave)
retval += sizeof(v);
else
retval += 2 * sizeof(v);
};
process(mInt);
process(getBool());
//xstr(Type, retval, mInt);
return retval;
}
template <typename T>
constexpr int f(T& n) { return sizeof(T); }
int n = 0;
//constexpr int i = f(n);
struct Date
{
int32_t year;
int8_t month;
int8_t day;
};
bool operator<(const Date& lhs, const Date& rhs)
{
return std::tie(lhs.year, lhs.month, lhs.day) < std::tie(rhs.year, rhs.month, rhs.day);
}
class ZZZ
{
public:
constexpr ZZZ(std::array<int, 2> v) : ma(v) {}
std::array<int, 2> ma;
};
void testEnums()
{
constexpr auto TState = ext::make_enum(4.5, 5.4, 3.4f);
constexpr auto TExtension = ext::make_enum("jpg", "gif", "png");
auto f = 44;
switch (TState(f))
{
case TState(4.5):
std::cout << "first" << std::endl;
break;
case TState(5.4):
std::cout << "second" << std::endl;
break;
case TState(3.4f):
std::cout << "third" << std::endl;
break;
case TState.Unknown:
std::cout << "unknown" << std::endl;
}
std::copy(TState.cbegin(), TState.cend(), std::ostream_iterator<decltype(TState)::underlying_type>(std::cout, " "));
const char* ext = "png";
switch (TExtension(ext))
{
case TExtension("jpg"):
std::cout << "jpg" << std::endl;
break;
case TExtension("gif"):
std::cout << "gif" << std::endl;
break;
case TExtension("png"):
std::cout << "png" << std::endl;
break;
case TExtension.Unknown:
std::cout << "unknown" << std::endl;
}
std::copy(TExtension.cbegin(), TExtension.cend(), std::ostream_iterator<decltype(TExtension)::underlying_type>(std::cout, " "));
}
//template <typename T, std::size_t N>
//constexpr std::array<T, N> sort(std::array<T, N> ain)
//{
// auto aout = ain;
// for (std::size_t i = 0; i < N - 1; i++)
// {
// for (std::size_t j = i + 1; j < N; j++)
// {
// if (aout[j] < aout[i])
// std::swap(aout[i], aout[j]);
// }
// }
// return aout;
//}
int main()
{
//constexpr std::array<int, 3> ain{ { 3, 2, 1 }};
//constexpr auto aout = sort(ain);
testEnums();
//auto rex = Date{ 999, 9, 22 } < Date{ 999, 10, 11 };
{
BigUint<128> large(123456789123456789);
large %= 47;
BigUint<128> l2(123456789123);
l2 /= 345;
}
{
//static_assert(std::tuple_size_v<decltype(macroStruct::memberNames_)> == 2, "");
//macroStruct m;
//m.range() = 3;
static_assert(s2::memberNames_[0][0] == 'r', "");
static_assert(strlen_c(s2::memberNames_[0]) == 5, "");
static_assert(strequal_c(s2::memberNames_[0], "range"), "");
static_assert(strequal_c(s2::memberNames_[0], "rang") == false, "");
static_assert(strequal_c(s2::memberNames_[0], "ranger") == false, "");
//constexpr auto im = s2::isMember<1>("fasfa");
//constexpr auto vvv = s2::memberPosition("rangee");
//constexpr auto findResult = find(s2::memberNames_, "valid");
s2 ns2;
ns2.get<0>() = 33;
ns2.get<1>() = false;
//auto& r1 = ns2.get2<"range">();
//constexpr auto i2 = s2::find("valid");
//auto& r2 = ns2.get<i2>();
//auto& r3 = ns2.range();
//auto& r4 = ns2.valid();
//constexpr std::array<const char*, 2> aa{{"range", "valid"}};
//constexpr auto vvv = bau(aa, "rangee");
//static_assert(vvv.second == false, "");
{
tuple_c<int, float> t1;
type_c<bool> b1;
constexpr auto res = t1 + b1;
static_assert(std::is_same_v<typename decltype(res)::type, std::tuple<int, float, bool>>, "");
}
{
tuple_c<int, float> t1;
tuple_c<bool, double> t2;
constexpr auto res = t1 + t2;
static_assert(std::is_same_v<typename decltype(res)::type, std::tuple<int, float, bool, double>>, "");
}
{
tuple_c<int, float> t1;
type_c<bool> b1;
constexpr auto res = b1 + t1;
static_assert(std::is_same_v<typename decltype(res)::type, std::tuple<bool, int, float>>, "");
}
{
tuple_c<int, float> t1;
tuple_c<bool, double> t2;
constexpr auto res = t2 + t1;
static_assert(std::is_same_v<typename decltype(res)::type, std::tuple<bool, double, int, float>>, "");
}
}
auto af = []() { return std::make_pair(0, 'a'); };
//int ai;
char ac;
std::tie(std::ignore, ac) = af();
int ai = sin(6);
//generic_save_t<kAddSaveSize> cvalue = 0;
constexpr auto resai = gensave<kAddSaveSize>(ai);
static_assert(resai == 4, "");
//ZZ qwerq(3);
//Bau asdf(ZZ(3));
std::vector<std::string> words;
std::string str("at b c d e");
const auto r = std::regex("[b-d]+");
auto it = std::sregex_token_iterator(str.begin(), str.end(), r);
std::copy(it, std::sregex_token_iterator(), std::back_inserter(words));
for (const auto& s : words)
std::cout << s << ",";
std::cout << std::endl;
//const auto& eit = std::sregex_token_iterator();
////std::vector<std::string> words;
//std::copy(std::sregex_token_iterator(str.begin(), str.end(), std::regex("(\\+|-)?[[:digit:]]+")),
// eit,
// std::back_inserter(words));
test1();
//auto a = ext::gcd();
//ext::narrowest_type_t<float, char> aa;
//constexpr auto x = ext::gcd((unsigned int)8, (unsigned int)0, (unsigned int)600, (unsigned int)200, (unsigned int)72);
//constexpr auto y = ext::min((unsigned int)800, (unsigned int)900, (unsigned int)600, (unsigned int)200, (unsigned int)72);
return 0;
}
| true |
683051f71ccddf4381702f1ab4590d733026a017 | C++ | niyaznigmatullin/nncontests | /utils/IdeaProject/archive/unsorted/2019.12/20191214_vkcup/f.cpp | UTF-8 | 4,365 | 2.59375 | 3 | [] | no_license | /**
* Niyaz Nigmatullin
*/
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(time(NULL));
struct interactor {
virtual long long ask(int i, int j) = 0;
virtual void answer(long long ans) const = 0;
};
struct myinteractor : interactor {
vector<vector<long long>> z;
map<pair<int, int>, long long> asked;
int n;
int k;
int count;
myinteractor(int n, int m, int k) : z(n), n(n), k(k) {
count = 0;
for (int i = 0; i < m; i++) {
z[rng() % n].push_back(i);
}
}
long long ask(int i, int j) {
assert(j >= 0 && j < (int) z[i].size());
if (asked.find({i, j}) != asked.end()) return asked[{i, j}];
++count;
return asked[{i, j}] = z[i][j];
}
void answer(long long ans) const {
assert(ans == this->k);
cerr << count << " queries\n";
}
};
struct stdinteractor : interactor {
long long ask(int i, int j) {
cout << "? " << i + 1 << ' ' << j + 1 << endl;
long long ret;
cin >> ret;
return ret;
}
void answer(long long ans) const {
cout << "! " << ans << endl;
}
};
struct solver {
interactor &d;
int n;
vector<int> a;
int k;
solver(interactor &d, int n, vector<int> const &a, int k) : d(d), n(n), a(a), k(k) {}
void solve() {
vector<int> id(n);
for (int i = 0; i < n; i++) id[i] = i;
vector<int> left(n, 0), right(a);
vector<int> ask(n);
vector<pair<long long, int>> replies;
while (true) {
int have = 0;
for (int i = 0; i < n; i++) {
if (right[i] - left[i] > k + 1) {
right[i] = left[i] + k + 1;
}
}
for (int i = 0; i < n; i++) have += right[i] - left[i];
for (int i = 0; i < n; i++) {
int value = have - k - 1;
if (right[i] - left[i] > value + 1) {
int sub = (right[i] - left[i] - (value + 1));
left[i] += sub;
have -= sub;
k -= sub;
}
}
long long minValue = 1LL << 60;
int whereMin = -1;
long long maxValue = 0;
int whereMax = -1;
int low = 0;
int high = 0;
replies.clear();
for (int i = 0; i < n; i++) {
if (left[i] < right[i]) {
ask[i] = (int) ((long long) k * (right[i] - left[i]) / have) + left[i];
low += ask[i] - left[i];
high += right[i] - ask[i] - 1;
long long z = d.ask(i, ask[i]);
if (z < minValue) {
minValue = z;
whereMin = i;
}
if (z > maxValue) {
maxValue = z;
whereMax = i;
}
replies.push_back({z, i});
}
cerr << "(" << left[i] << ", " << right[i] << ") ";
}
// assert(low < k + 1);
// assert(high < have - k - 1);
cerr << endl;
cerr << "k = " << k << ", have = " << have << ", low = " << low << ", high = " << high << endl;
if (whereMin == whereMax) {
d.answer(minValue);
return;
}
sort(replies.begin(), replies.end());
// int addLeft = (low < k ? 1 : 0) + ask[whereMin] - left[whereMin];
// int addRight = (high + 1 <= have - k - 1 ? 1 : 0) + right[whereMax] - ask[whereMax] - 1;
// k -= addLeft;
// have -= addLeft;
// left[whereMin] += addLeft;
// have -= addRight;
// right[whereMax] -= addRight;
for (auto &e : replies) {
if (low > k) break;
int addLeft = (low < k ? 1 : 0) + ask[e.second] - left[e.second];
low += right[e.second] - ask[e.second];
k -= addLeft;
have -= addLeft;
left[e.second] += addLeft;
}
reverse(replies.begin(), replies.end());
for (auto &e : replies) {
if (high > have - (k + 1)) {
break;
}
int addRight = (high + 1 <= have - (k + 1) ? 1 : 0) + right[e.second] - ask[e.second] - 1;
have -= addRight;
right[e.second] -= addRight;
high += ask[e.second] - left[e.second] + 1;
}
}
vector<long long> all;
for (int i = 0; i < n; i++) {
for (int j = left[i]; j < right[i]; j++) {
all.push_back(d.ask(i, j));
}
}
sort(all.begin(), all.end());
d.answer(all[k]);
}
};
int main() {
// int w, n;
// cin >> w >> n;
// for (int i = 0; i < w; i++) {
// vector<int> a(n);
// for (int i = 0; i < n; i++) cin >> a[i];
// int k;
// cin >> k;
// --k;
// stdinteractor d;
// solver s(d, n, a, k);
// s.solve();
// }
while (true) {
// int n = 2 + (int) (rng() % 4);
int n = 5;
int m = (int) (rng() % 100000) + 100000;
int k = (int) (rng() % m);
myinteractor d(n, m, k);
vector<int> a(n);
for (int i = 0; i < n; i++) a[i] = (int) d.z[i].size();
solver s(d, n, a, k);
s.solve();
cerr << n << ' ' << m << ' ' << k << endl;
}
}
| true |
9be86fe26815fa6a7d51bd70531fe2cc3d9c09fa | C++ | green-fox-academy/hbence97 | /week-01/day-03/13 - SecondsInADay/main.cpp | UTF-8 | 880 | 3.96875 | 4 | [] | no_license | #include <iostream>
int main(int argc, char* args[]) {
// Write a program that prints the remaining seconds (as an integer) from a
// day if the current time is represented by the variables
int currentHours = 14;
int currentMinutes = 34;
int currentSeconds = 42;
int a = 24 - currentHours;
int b = 60 - currentMinutes;
int c = 60 - currentSeconds;
int anHourInSeconds = 60 * 60;
int aMinuteInSeconds = 60;
std::cout << a << "hours left" << std::endl;
std::cout << b << "minutes left" << std::endl;
std::cout << c << "seconds left" << std::endl;
std::cout << anHourInSeconds << " is 1 hour in seconds " << std::endl;
std::cout << anHourInSeconds * 10 << " is 10 hours in seconds" << std::endl;
std::cout << (anHourInSeconds * 10) + 60*(60 - 34) + (c) << " seconds left in a day!" << std::endl;
return 0;
} | true |
a01119037549809ba2878e4780ae89c441aa647f | C++ | volzkzg/Tempus-Fugit-Code-Machine | /TeamTraining/7_25/K.cpp | UTF-8 | 2,473 | 2.53125 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
int m, n, p, q;
struct Plane {
int a, b, c, d;
void read() {
scanf("%d%d%d%d", &a, &b, &c, &d);
}
}plane[110];
struct Sphere {
int x, y, z, r;
void read() {
scanf("%d%d%d%d", &x, &y, &z, &r);
}
}sphere[20];
struct Point {
int x, y, z;
void read() {
scanf("%d%d%d", &x, &y, &z);
}
} A[210], B[2010];
__inline long long sqr(long long w)
{
return w * w;
}
inline long long calc_plane(const Point &u, const Plane &v)
{
return ((long long)v.a * u.x + (long long)v.b * u.y +
(long long)v.c * u.z + v.d);
}
inline int calc_sphere(const Point &u, const Sphere &v)
{
long long w = sqr(u.x - v.x) + sqr(u.y - v.y) + sqr(u.z - v.z);
if (w < sqr(v.r)) return 1;
else return -1;
}
int main()
{
int T;
scanf("%d", &T);
while (T--) {
scanf("%d%d%d%d", &m, &n, &p, &q);
for (int i = 1; i <= m; ++i)
plane[i].read();
for (int i = 1; i <= n; ++i)
sphere[i].read();
for (int i = 1; i <= p; ++i)
A[i].read();
for (int i = 1; i <= q; ++i)
B[i].read();
bool flag = true;
int ans = 1;
for (int i = 1; i <= p; ++i) {
int tmp = 1;
for (int k = 1; k <= m; ++k) {
long long calc;
calc = calc_plane(A[i], plane[k]);
calc /= abs(calc);
if (calc < 0) calc = 0;
tmp ^= calc;
}
for (int k = 1; k <= n; ++k) {
int calc;
calc = calc_sphere(A[i], sphere[k]);
if (calc < 0) calc = 0;
tmp ^= calc;
}
if (i == 1) ans = tmp;
if (i != 1 && ans != tmp) {
flag = false;
goto out;
}
}
out:;
if (flag) {
for (int i = 1; i <= q; ++i) {
int status = 2;
if (p > 0) {
int cnt = 0;
for (int k = 1; k <= m; ++k) {
long long calc1, calc2;
calc1 = calc_plane(A[1], plane[k]);
calc2 = calc_plane(B[i], plane[k]);
calc1 /= abs(calc1);
calc2 /= abs(calc2);
if (calc1 * calc2 < 0)
cnt++;
}
for (int k = 1; k <= n; ++k) {
int calc1, calc2;
calc1 = calc_sphere(A[1], sphere[k]);
calc2 = calc_sphere(B[i], sphere[k]);
if (calc1 * calc2 < 0)
cnt++;
}
if (cnt & 1) {
status = 1;
} else {
status = 0;
}
}
switch (status) {
case 2:printf("Both\n"); break;
case 1:printf("R\n"); break;
case 0:printf("Y\n"); break;
}
}
} else {
printf("Impossible\n");
}
if (T != 0) puts("");
}
return 0;
}
| true |
e59c1aad6e87bc2914a4a7ba76740daf7dd694a1 | C++ | ngoquanghuy99/Graph-Theory-Implementations | /counting_components_adjlist.cpp | UTF-8 | 865 | 3 | 3 | [] | no_license | /*
Author: Ngo Quang Huy
Problem: Counting the number of paths in an unweighted undirected graph
*/
#include <iostream>
#include <stack>
#include <vector>
#include <cstring>
using namespace std;
int const MAX = 1001;
int n, m;
vector <int> ke[MAX];
bool unused[MAX];
void init(){
cin >> n >> m;
memset(unused, true, n);
while (m--){
int u, v; cin >> u >> v;
ke[u].push_back(v);
ke[v].push_back(u);
}
}
void DFS(int u){
stack <int> s;
s.push(u);
cout<<u<<" ";
unused[u] = false;
while(!s.empty()){
u = s.top();
s.pop();
for(int i=0; i<ke[u].size(); i++){
int v;
v = ke[u][i];
if(unused[v]){
cout<<v<<" ";
unused[v] = false;
s.push(u);
s.push(v);
break;
}
}
}
}
int main(){
int count = 0;
init();
for(int i=1; i<=n; i++)
if(unused[i]){
count++;
cout<<"TPLT "<<count<<": ";
DFS(i);
cout<<endl;
}
}
| true |
0c35b72ef51a02b22203a7a76dff377682aa7fc8 | C++ | mariatomy9/DSA-DIARIES | /DSA/Array/search.cpp | UTF-8 | 321 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int arraySearch(int arr[], int n, int x)
{
for(int i = 0; i < n; i++)
{
if(arr[i]==x)
{
return i;
}
}
return -1;
}
int main()
{
int A[] = {1,2,3,4};
int n = sizeof(A)/sizeof(A[0]);
cout<<arraySearch(A,n,2);
}
| true |
35841396badce8e2141523ed72f2590563fb4991 | C++ | MichelleZ/leetcode | /algorithms/cpp/sequentialDigits/sequentialDigits.cpp | UTF-8 | 589 | 3.1875 | 3 | [] | no_license | // Source: https://leetcode.com/problems/sequential-digits/
// Author: Miao Zhang
// Date: 2021-04-21
class Solution {
public:
vector<int> sequentialDigits(int low, int high) {
vector<int> res;
for (int i = 1; i < 10; i++) {
int num = i;
for (int j = i + 1; j < 10; j++) {
num = num * 10 + j;
if (num >= low && num <= high) {
res.push_back(num);
}
if (num >= high) break;
}
}
sort(begin(res), end(res));
return res;
}
};
| true |
b50038f2b5d5523873ea56df51c17120047ad920 | C++ | diogodutra/board_cpp | /board.hpp | UTF-8 | 626 | 2.71875 | 3 | [] | no_license | #ifndef BOARD_H
#define BOARD_H
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <vector>
#include "note.hpp"
using namespace std;
class Board
{
public:
const int indexNotFound = -1;
void addNote(const string title
, const string text
, const vector<string> tags);
void addNote(const Note note);
bool deleteNote(const int indexNote);
int searchByTitle(const string title);
int searchByText(const string text);
int searchByTag(const string tag);
bool printNote(const int indexNote);
void printAllNotes();
private:
vector<Note> notes = {};
};
#endif | true |
e07512540979964ebe752b3077600893948972d4 | C++ | gauravsingh9891/INDL_CPP | /Lecture-6/Pattern2.cpp | UTF-8 | 422 | 2.90625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n;
cin>>n;
char ch='A';
int number=1;
for(int line=0;line<=n;line++){
for(int spaces=1;spaces<=n-line;spaces++){
cout<<" ";
}
for(int j=1;j<=2*line-1;j++){
if(j==1||j==2*line-1){
cout<<ch;
ch++;
}
else if(j==line){
cout<<number;
number++;
}
else{
cout<<"*";
}
}
cout<<endl;
}
cout<<endl;
return 0;
} | true |
f3df08e527b9a3de2cd598477a87e46abd98a489 | C++ | mingkaic/CNNet | /tenncor/src/graph/variable/constant.ipp | UTF-8 | 1,152 | 2.640625 | 3 | [
"MIT"
] | permissive | //
// constant.ipp
// cnnet
//
// Created by Mingkai Chen on 2016-08-29.
// Copyright © 2016 Mingkai Chen. All rights reserved.
//
#ifdef constant_hpp
namespace nnet
{
// CONSTANT IMPLEMENTATION
// template <typename T>
// constant<T>::constant (const constant<T>& other, std::string name) :
// ileaf<T>(other, name) {}
// template <typename T>
// ivariable<T>* constant<T>::clone_impl (std::string name)
// {
// return new constant(*this, name);
// }
template <typename T>
constant<T>::constant (T scalar) :
ileaf<T>(std::vector<size_t>{1},
new const_init<T>(scalar),
nnutils::formatter() << scalar)
{
this->out_->allocate();
(*this->init_)(*this->out_);
this->is_init_ = true;
}
template <typename T>
constant<T>::constant (std::vector<T> raw, tensorshape shape) :
ileaf<T>(shape,
new typename ileaf<T>::dyn_init(*this->out_),
nnutils::formatter() << raw.front() << ".." << raw.back() << raw.end())
{
this->out_->allocate();
(*this->init_) = raw;
this->is_init_ = true;
}
template <typename T>
constant<T>* constant<T>::clone (void)
{
return new constant<T>(*this);
// return static_cast<constant<T>*>(clone_impl(name));
}
}
#endif | true |
df236a992a1268e3d8c855dfc96b8c5f6a1dc7ab | C++ | mastersin/charybdis | /include/ircd/buffer/unique_buffer.h | UTF-8 | 3,329 | 2.609375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | // Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2018 Jason Volk <jason@zemos.net>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_BUFFER_UNIQUE_BUFFER_H
/// Like unique_ptr, this template holds ownership of an allocated buffer
///
template<class buffer,
uint alignment>
struct ircd::buffer::unique_buffer
:buffer
{
buffer release();
unique_buffer(const size_t &size);
unique_buffer(std::unique_ptr<char[]> &&, const size_t &size);
explicit unique_buffer(const buffer &);
unique_buffer();
unique_buffer(unique_buffer &&) noexcept;
unique_buffer(const unique_buffer &) = delete;
unique_buffer &operator=(unique_buffer &&) noexcept;
unique_buffer &operator=(const unique_buffer &) = delete;
~unique_buffer() noexcept;
};
template<class buffer,
uint alignment>
ircd::buffer::unique_buffer<buffer, alignment>::unique_buffer()
:buffer
{
nullptr, nullptr
}
{}
template<class buffer,
uint alignment>
ircd::buffer::unique_buffer<buffer, alignment>::unique_buffer(const buffer &src)
:buffer{[&src]() -> buffer
{
std::unique_ptr<char[]> ret
{
new __attribute__((aligned(16))) char[size(src)]
};
const mutable_buffer dst
{
ret.get(), size(src)
};
copy(dst, src);
return dst;
}()}
{
}
template<class buffer,
uint alignment>
ircd::buffer::unique_buffer<buffer, alignment>::unique_buffer(const size_t &size)
:unique_buffer<buffer, alignment>
{
std::unique_ptr<char[]>
{
//TODO: Can't use a template parameter to the attribute even though
// it's known at compile time. Hardcoding this until fixed with better
// aligned dynamic memory.
//new __attribute__((aligned(alignment))) char[size]
new __attribute__((aligned(16))) char[size]
},
size
}
{
// Alignment can only be 16 bytes for now
assert(alignment == 16);
}
template<class buffer,
uint alignment>
ircd::buffer::unique_buffer<buffer, alignment>::unique_buffer(std::unique_ptr<char[]> &&b,
const size_t &size)
:buffer
{
typename buffer::iterator(b.release()), size
}
{}
template<class buffer,
uint alignment>
ircd::buffer::unique_buffer<buffer, alignment>::unique_buffer(unique_buffer &&other)
noexcept
:buffer
{
std::move(static_cast<buffer &>(other))
}
{
get<0>(other) = nullptr;
}
template<class buffer,
uint alignment>
ircd::buffer::unique_buffer<buffer, alignment> &
ircd::buffer::unique_buffer<buffer, alignment>::operator=(unique_buffer &&other)
noexcept
{
this->~unique_buffer();
static_cast<buffer &>(*this) = std::move(static_cast<buffer &>(other));
get<0>(other) = nullptr;
return *this;
}
template<class buffer,
uint alignment>
ircd::buffer::unique_buffer<buffer, alignment>::~unique_buffer()
noexcept
{
delete[] data(*this);
}
template<class buffer,
uint alignment>
buffer
ircd::buffer::unique_buffer<buffer, alignment>::release()
{
const buffer ret{static_cast<buffer>(*this)};
static_cast<buffer &>(*this) = buffer{};
return ret;
}
| true |
338b62409399380861afabb369450fa364f5feb9 | C++ | 99002613/Genesis | /Set 2/Currency/currency.cc | UTF-8 | 1,529 | 3.234375 | 3 | [] | no_license |
#include<iostream>
#include "currency.h"
Currency::Currency():m_rupees(0),m_paise(0) {
}
Currency::Currency(int a,int b):m_rupees(a),m_paise(b) {
}
Currency::Currency(int d):m_rupees(d) {
}
Currency Currency::operator+(const Currency &ref) {
int tmins = m_paise + ref.m_paise;
int thrs = m_rupees+ref.m_rupees;
return Currency(thrs, tmins);
}
Currency Currency::operator-(const Currency &ref) {
int tmins = m_paise - ref.m_paise;
int thrs = m_rupees - ref.m_rupees;
return Currency(thrs, tmins);
}
Currency Currency::operator*(const Currency &ref) {
int tmins = m_paise * ref.m_paise;
int thrs = m_rupees * ref.m_rupees;
return Currency(thrs, tmins);
}
Currency& Currency:: operator++() {
++m_paise; // TODO: mm > 60
return *this;
}
Currency Currency:: operator++(int dummy) {
Currency orig(*this);
++m_rupees; // TODO: mm > 60
return orig;
}
bool Currency::operator==(const Currency &ref) {
return m_rupees == ref.m_rupees && m_paise == ref.m_paise;
}
int Currency::operator< (const Currency &ref){
int les=16;
// bool True
if(ref.m_rupees<les)
return 1;
else
return 0;
}
bool Currency::operator> (const Currency &ref){
int gre=16;
// bool True
if(ref.m_rupees>gre)
return true;
else
return false;
}
int Currency::getP(){
return m_paise;
}
void Currency::display() {
std::cout<<m_rupees<<":"<<m_paise<<"\n";
}
| true |
1986525591be6a121b96ca1b8c7fc16a24083c08 | C++ | kunal-k2/AdvanceCPP | /initialization_fiasco/sol_1/singleton.cpp | UTF-8 | 385 | 2.90625 | 3 | [] | no_license | #include "singleton.h"
#include "dog.h"
#include "cat.h"
Dog* Singleton::pd = 0;
Cat* Singleton::pc = 0;
Cat* Singleton::getCat()
{
if(!pc) pc = new Cat("xyz");
return pc;
}
Dog* Singleton::getDog()
{
if(!pd) pd = new Dog("abc");
return pd;
}
Singleton::~Singleton()
{
if(pd) delete pd;
if(pc) delete pc;
pd = 0;
pc = 0;
}
| true |
bf6056c07e73f53dbe62b8629ddcfbec9c34f49a | C++ | MosmannJuan/AED | /10-Tipo Polígono/Poligono.h | UTF-8 | 2,260 | 3.3125 | 3 | [] | no_license | /*Mosmann, Juan Ignacio
AED 2020
Curso K1051
16/09/2020*/
#pragma once
#include <array>
#include <cstdint>
#include <cstring>
struct Punto{double x,y;};
struct Color {uint8_t r, g, b ;};
struct Nodo{
Punto p;
Nodo* SigNodo;
};
struct Poligono {
Nodo* PrimerPunto;
Color c;};
//Declaración de colores
const Color rojo {255, 0, 0};
const Color verde {0, 255, 0};
const Color azul {0, 0, 255};
const Color cyan {0, 255, 255};
const Color magenta {255, 0, 255};
const Color amarillo {255, 255, 0};
const Color blanco = {255, 255, 255};
const Color negro = {0, 0, 0};
// Funciones de Polígono
void AddVertice (Poligono&, const Punto&); //Agrega al final del array de puntos del poligono el punto ingresado en el argumento
Punto GetVertice (const Poligono&, const unsigned&); //Retorna el valor del Punto del poligono ubicado en la posicion indicada
void SetVertice (Poligono &, const unsigned& , const Punto&); //Setea el valor del punto ingresado en la posicion indicada
void RemoveVertice (Poligono &); //Quita el punto en la ultima posición del polígono ingresado como argumento
unsigned GetCantidadDeLados (const Poligono&); //Retorna la cantidad de lados que posee el polígono ingresado (coincide con la cantidad de vertices)
double GetPerimetro (const Poligono&); //Retorna un double correspondiente al perímetro del polígono ingresado
bool IsIgual (const Poligono&, const Poligono&); //Retorna un booleano true si los dos polígonos ingresados son iguales o false si no lo son
void MostrarPoligono(const Poligono&);
//Funciones necesarias de Punto
double GetDistancia(const Punto&, const Punto&); //Necesaria para la función de calculo de perimetro de poligonos
bool IsIgualPunto (const Punto&, const Punto&); //Necesaria para la función de comparación de polígonos
Punto RestarPuntos(const Punto& , const Punto&); //Necesaria para la función GetDistancia
void MostrarPunto (Punto);
//Funciones necesarias de Color
bool IsIgualColor (const Color&, const Color&); //Necesaria para la función de comparación de polígonos
std::string GetHtmlrgb (const Color&); //Retorna una cadena correspondiente al color en formato "rgb(r,g,b)"
| true |
bcc674a43370568618174c277f1fd52a6304da87 | C++ | peterlopez/CS-coursework | /COMSC 165/assignments/07-Function-Templates/Assignment07-1.cpp | UTF-8 | 1,085 | 3.890625 | 4 | [] | no_license | /***************************************************************
Problem: Function Templates
Question: 1 - Minimum/Maximum Templates
Name: Peter Lopez Ruszel
ID: 1611543
Date: 4/9/19
Status: complete
****************************************************************/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template<typename T>
T maxValue(T value1, T value2)
{
return (value1 > value2) ? value1 : value2;
}
template<typename T>
T minValue(T value1, T value2)
{
return (value1 < value2) ? value1 : value2;
}
int main()
{
cout << "Max between 1 and 5 is: " << maxValue(1, 5) << endl;
cout << "Max between 5.1 and 7.2 is: " << maxValue(5.1, 7.2) << endl;
cout << "Max between 'abc' and 'def' is: " << maxValue("abc", "def") << endl;
cout << "--" << endl;
cout << "Min between 1 and 5 is: " << minValue(1, 5) << endl;
cout << "Min between 5.1 and 7.2 is: " << minValue(5.1, 7.2) << endl;
cout << "Min between 'abc' and 'def' is: " << minValue("abc", "def") << endl;
return 0;
}
| true |
f67b714dba161d1c76ce1b0a4fd2303d88aa0118 | C++ | yash12khatri/codechef | /Temple_Land.cpp | UTF-8 | 436 | 2.84375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool valid(int arr[],int n)
{
if(!(n&1))
return false;
int l=n/2;
n--;
for(int i=0;i<=l;i++)
{
if(arr[i]!=i+1||arr[i]!=arr[n-i])
return false;
}
return true;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
if(valid(arr,n))
cout<<"yes\n";
else
cout<<"no\n";
}
}
| true |
1f0501a2eb58f624800144d710e91650d68c0513 | C++ | getSideEffect/AntVM | /main.cpp | UTF-8 | 615 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include "AntVM.h"
using namespace ant_vm;
int main() {
//create an ant-vm instance
AntVM myVM;
//create a place-holder for the final solution
Variable finalValue;
//instructions for final_value = 1.0 + 2.0
myVM.addInstruction(Ins(InsCode::LOAD_CONST, 1.0));
myVM.addInstruction(Ins(InsCode::LOAD_CONST, 2.0));
myVM.addInstruction(Ins(InsCode::SUB));
myVM.addInstruction(Ins(InsCode::SET, finalValue));
//run the virtual machine
myVM.run();
//display the results
std::cout<<"Value of finalValue is "<<finalValue.get();
return 0;
}
| true |
5c8fcf1c986578cb98c442e65e084367541c730b | C++ | GamesTrap/LearnCPP | /StringView/src/main.cpp | UTF-8 | 741 | 3.640625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include "StringView.h"
int main()
{
StringView emptyStringView;
std::cout << "Empty StringView. Length = " << emptyStringView.length() << '\n';
StringView stringView("Hello");
std::cout << "Hello: Length = " << stringView.length() << '\n';
display(std::cout, stringView);
std::cout << '\n' << "Character by character:" << '\n';
for (char i : stringView)
std::cout << '*' << i;
std::cout << '*' << '\n';
for (auto c : stringView)
std::cout << '_' << c;
std::cout << '_' << '\n';
const StringView secondStringView = stringView;
std::cout << "Assgiend StringView: ";
display(std::cout, secondStringView);
std::cout << '\n';
std::cout << "Press Enter to continue . . . ";
std::cin.get();
return 0;
} | true |
ec6a535cb1936297e8781674e609f1c74f99381a | C++ | saxenism/testRCppPackage | /src/rcpp_hello_world.cpp | UTF-8 | 529 | 3.015625 | 3 | [] | no_license | #include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double addCpp(NumericVector x)
{
double total = 0.0;
int n = x.size();
for(int i = 0; i < n; i++)
total += x[i];
return total;
}
// [[Rcpp::export]]
double multiplyCpp(NumericVector x)
{
double total = 1.0;
int n = x.size();
for(int i = 0; i < n; i++)
total *= x[i];
return total;
}
// [[Rcpp::export]]
double subtractCpp(double x, double y)
{
return (x - y);
}
// [[Rcpp::export]]
double divideCpp(double x, double y)
{
return (x/y);
}
| true |
3a34a4dcad712b2d5bc8f6d6eeb95ddebb5a26c1 | C++ | cramacha/practice | /ctci/chp5/6.cpp | UTF-8 | 625 | 3.859375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int
flip(int a, int b)
{
/*
* e.g a = 1001, b = 0110
* a ^ b = 1111. This gives the number of bits which are
* different between a and b.
*
* The bits can be counted in the Kernighan way i.e. n & n - 1
* This will keep resetting the least significant bit until we
* reach 0.
*/
unsigned int c;
int count = 0;
for (c = a ^ b; c != 0; c = c & c - 1)
count++;
return (count);
}
int
main(int argc, char **argv)
{
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = flip(a, b);
cout << "a = " << a << " b = " << b
<< " c = " << c << endl;
return (0);
}
| true |
afdc1c58dbe31bb58e02c8b0b4fff1540508d4ba | C++ | aqfaridi/Competitve-Programming-Codes | /SPOJ/SPOJ/GARDENAR.cpp | UTF-8 | 1,534 | 3.3125 | 3 | [
"MIT"
] | permissive | /**
* SPOJ Problem Set (classical)
* 5240. Area of a Garden
* Problem code: GARDENAR
*
* One rich person decided to make himself a great garden. The garden
* should have a from of equilateral triangle. There should be a
* gazebo inside the garden. The gazebo will be connected with the
* triangle vertexes by roads. The lengths of all three roads are
* known. Those numbers are sacred for this rich man. The expense of
* building such a garden will depend on the area of the garden. Help
* the rich man by calculating what will be the area of his garden.
* Input
*
* The first line of the input contains number t . the amount of
* tests. Then t test descriptions follow. Each test consist of three
* integers a, b, c - the lengths of the roads. It is guaranteed that
* it's possible to build such a garden.
* Constraints
*
* 1 <= t <= 1000
* 1 <= a, b, c <= 1000
* Output
*
* For each test print the area of the garden with two digits in the
* fractional part.
* Example
*
* Input:
* 1
* 3 4 5
*
* Output:
* 19.83
* */
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int t,d,e,f;
double a1,a2,a3,area,s;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d",&d,&e,&f);
s=(d+e+f)/2.0;
a1=sqrt(3)*d*d/4;
a2=sqrt(3)*e*e/4;
a3=sqrt(3)*f*f/4;
area=0.5*(a1+a2+a3+3*sqrt(s*(s-d)*(s-e)*(s-f)));
printf("%.2lf\n",area);
}
return 0;
}
| true |
b815ea82e28c6cf2cb69b2214fee9c0114a5a05f | C++ | henry-banks/NovExercises | /Exercises/DataStuff/tvector.h | UTF-8 | 2,530 | 3.640625 | 4 | [] | no_license | #pragma once
#include <cassert>
//THIS IS GOING TO BE VERY CLUTTERED BECAUSE ALL THE TEMPLATES HAVE TO BE DECLARED AND DEFINED IN THE SAME FILE.
template<typename T>
class tvector
{
private:
T *m_data;
size_t m_size;
public:
tvector()
{
m_size = 0;
m_data = new T;
}
~tvector()
{
m_size = 0;
if (m_data != nullptr)
delete[] m_data;
}
tvector(const tvector & o) //Copy Constructor
{
m_data = new T[o.m_size];
size_t i = 0;
while (i < o.m_size)
m_data[i] = o.m_data[i++];
m_size = i;
}
tvector(tvector && o) //Move Constructor
{
m_data = o.m_data;
m_size - o.m_size;
//Since this is a 'move' operator, we need to clear the other object.
o.m_data = nullptr;
o.m_size = 0;
}
//Assignment Move
tvector &operator=(const tvector & o)
{
m_size = 0;
if (m_data != nullptr)
delete[] m_data;
//COPY STUFF
m_data = new T[m_size];
size_t i = 0;
for(int j = 0; j < o.m_size; j++) //For some reason, using a while loop and incrementing i doesn't work; i becomes 1
m_data[i] = o.m_data[i++];
m_size = i;
return *this;
}
//Assignment Copy
tvector &operator=(tvector &o)
{
m_size = 0;
if (m_data != nullptr)
delete[] m_data;
//COPY STUFF
m_data = o.m_data;
m_size = o.m_size;
o.m_data = nullptr;
o.m_size = 0;
return *this;
}
//Mutable
T&operator[](size_t idx)
{
assert(idx < m_size); //Make sure the index is valid
return m_data[idx];
}
//Const
T &operator[](size_t idx) const
{
assert(idx < m_size); //Make sure the index is valid
return m_data[idx];
}
size_t append(T val)
{
T *tempData = new T[m_size + 1];
for (int i = 0; i < m_size; i++)
tempData[i] = m_data[i];
//tempData[++m_size] = val; //Finally, we assign the new value to the last index in the array...
delete[] m_data; //...delete the old array...
m_data = tempData; //..then assign m_data to it.
m_data[m_size] = val;
tempData = nullptr;
m_size++;
return m_size;
}
size_t remove(size_t idx)
{
T *tempData = new T[m_size - 1];
int j = 0;
for (int i = 0; i < m_size; i++)
{
if (i != idx) //Make sure not to include the deleted value
tempData[j++] = m_data[i];
}
delete[] m_data; //Finally, we delete the old array...
m_data = tempData; //..then assign m_data to it.
tempData = nullptr;
m_size--;
return m_size;
}
size_t size();
T* data();
};
//Getters
template<typename T>
size_t tvector<T>::size() { return m_size; }
template<typename T>
T * tvector<T>::data() { return m_data; } | true |
f5b6515d8a6aa7057d2f0a37ae5832dcab85368d | C++ | deep-bansal/C-Lectures | /STRINGS AND CHAR ARRAY/STRING ROTATION/main.cpp | UTF-8 | 474 | 2.859375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void rotatestring(char* ch,int k)
{
int i=strlen(ch);
while(i>=0)
{
ch[i+k]=ch[i];
i--;
}
i=strlen(ch);
int j=i-k,s=0;
while(j<i)
{
ch[s]=ch[j];
j++;
s++;
}
ch[i-k]='\0';
cout<<ch;
}
int main()
{
char ch[100];
cin.getline(ch,100);
int k;
cin>>k;
rotatestring(ch,k);
return 0;
}
| true |
caeb5b80b294eb9358e30ad092cf61ce0736bb15 | C++ | redru/Pacman2D | /Pacman2D/src/Triangle.cpp | UTF-8 | 1,127 | 2.953125 | 3 | [] | no_license | #include "Triangle.h"
static const float vertices[] = {
0.0f, 0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.0f, 1.0f
};
const float* Triangle::_vertices = vertices;
Triangle::Triangle(Engine& engine) : Entity(engine) {
vbo = 0;
vao = 0;
glGenBuffers(1, &vbo); // Generato VBO
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), Triangle::_vertices, GL_STATIC_DRAW); // Buffer data to GPU memory using the VBO
glGenVertexArrays(1, &vao); // Generate VAO
glBindVertexArray(vao); // Bind VAO
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
glBindVertexArray(0); // Unbind VAO
}
Triangle::~Triangle() {
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
}
void Triangle::draw() {
ShaderProgram& program(Entity::engine().getShadersFactory().getProgram("default"));
glUseProgram(program.programId());
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3); // Draw points from 0 to 3 from the currently bound VAO with current in-use shader
glBindVertexArray(0);
}
| true |
f6fde5fd8539719e8e71104c6fb183f65b40d616 | C++ | iElden/MyGIMP | /src/ImageOperations/Selection/ShrinkSelection.hpp | UTF-8 | 1,168 | 2.609375 | 3 | [
"MIT"
] | permissive | /*
** EPITECH PROJECT, 2020
** MyGimp
** File description:
** ShrinkSelection.hpp
*/
#ifndef MYGIMP_SHRINKSELECTION_HPP
#define MYGIMP_SHRINKSELECTION_HPP
#include "../ImageOperation.hpp"
namespace Mimp {
//! @brief Define the ShrinkSelection.
class ShrinkSelection : public ImageOperation {
public:
//! @brief Do not call it directly. Use ShrinkSelection::click.
static void _removePointIfNoPointNearby(unsigned i, unsigned j, Mimp::Image &image, const SelectedArea &area, int range) noexcept;
//! @brief Do not call it directly. Use ShrinkSelection::click.
static void _run(Image &image, int range=1) noexcept;
//! @brief Constructor of the Shrink Selection Operation
ShrinkSelection();
//! @brief Handles the click of the ShrinkMore Selection Operation.
//! @details Shrink the selection on the image.
//! @param gui The global gui (unused).
//! @param image The image to edit.
//! @param window The focused window (unused).
//! @param editor The global editor (unused).
void click(tgui::Gui &gui, CanvasWidget::Ptr image, tgui::ChildWindow::Ptr window, Editor &editor) const override;
};
}
#endif //MYGIMP_SHRINKSELECTION_HPP
| true |
cecc115fa9896aee539a4be2d53c9ea11dc65f9d | C++ | dascheltfortner/pl-survey | /examples/vec-add/normal_vec-add.cpp | UTF-8 | 1,003 | 3.671875 | 4 | [] | no_license | /**
*
* This is an example of a simple C++ program to add together two arrays.
* This comes from the Easy introduction to cuda from the Developer's
* website:
*
* https://devblogs.nvidia.com/even-easier-introduction-cuda/
*
* */
#include <iostream>
#include <math.h>
// function to add the elements of two arrays
void add(int n, float *dst, float *src)
{
for (int i = 0; i < n; i++)
dst[i] = src[i] + src[i];
}
int main(void)
{
int N = 100<<20; // 100M elements
float *src = new float[N];
float *dst = new float[N];
// initialize x and y arrays on the host
for (int i = 0; i < N; i++) {
src[i] = 1.0f;
dst[i] = 2.0f;
}
// Run kernel on N elements on the CPU
add(N, dst, src);
// Check for errors (all values should be 3.0f)
float maxError = 0.0f;
for (int i = 0; i < N; i++)
maxError = fmax(maxError, fabs(y[i]-3.0f));
std::cout << "Max error: " << maxError << std::endl;
// Free memory
delete [] src;
delete [] dst;
return 0;
}
| true |
91bc924336cb279c01d8bcbb8f969dbf4a830b9a | C++ | ashish25-bit/data-structure-algorithms | /Trees/Kth-Largest-Smallest.cpp | UTF-8 | 1,650 | 3.8125 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
Node* insert(Node* root, int value) {
if (!root) return new Node(value);
if (value > root->data)
root->right = insert(root->right, value);
else (value < root->data)
root->left = insert(root->left, value);
return root;
}
// ##########################
void kthLargest(Node* root, int k, int &c, int &ans) {
if (!root || c > k) return;
kthLargest(root->right, k, c, ans);
c = c+1;
if (c == k) {
ans = root->data;
return;
}
kthLargest(root->left, k, c, ans);
}
int kthLargest(Node* root, int k) {
int ans = -1;
int c = 0;
kthLargest(root, k, c, ans);
return ans;
}
// ##########################
// ##########################
void kthSmallest(Node* root, int k, int &c, int &ans) {
if (!root || c > k) return;
kthSmallest(root->left, k, c, ans);
c = c+1;
if (c == k) {
ans = root->data;
return;
}
kthSmallest(root->right, k, c, ans);
}
int kthSmallest(Node* root, int k) {
int ans = -1;
int c = 0;
kthSmallest(root, k, c, ans);
return ans;
}
// ##########################
int main() {
vector<int> arr = {10, 8, 15, 13, 18};
Node* root = insert(NULL, arr[0]);
for (int i=1; i<arr.size(); i++)
insert(root, arr[i]);
for (int i=1; i <= arr.size(); i++)
cout << i << "th largest: " << kthLargest(root, i) << endl;
cout << endl;
for (int i=1; i <= arr.size(); i++)
cout << i << "th smallest: " <<
kthSmallest(root, i) << endl;
return 0;
}
| true |