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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ad63787adc606f1a0914f50c427e7df7f759dfd6 | C++ | rishabh2d/Monopoly | /hoardingCpp/readRules.cpp | UTF-8 | 3,047 | 2.71875 | 3 | [
"MIT"
] | permissive | //
// Created by Rishabh 2 on 2/4/18.
//
#include <iostream>
#include <vector>
#include "readRules.h"
// Setters
void Monopoly::RulesClass::setStartingCash(unsigned long startingCashSetter) {
startingCash = startingCashSetter;
}
unsigned long Monopoly::RulesClass::getStartingCash() const { // Getter
return startingCash;
}
void Monopoly::RulesClass::setTurnLimit2endGame (unsigned long turnLimit2endGameSetter) { // Setter
turnLimit2endGame = turnLimit2endGameSetter;
}
unsigned long Monopoly::RulesClass::getTurnLimit2endGame() const { // Getter
return turnLimit2endGame;
}
void Monopoly::RulesClass::setNumOfPlayers2endGame (unsigned long numOfPlayers2endGameSetter) { // Setter
numOfPlayers2endGame = numOfPlayers2endGameSetter;
}
unsigned long Monopoly::RulesClass::getNumOfPlayers2endGame() const { // Getter
return numOfPlayers2endGame;
}
void Monopoly::RulesClass::setPropertySetMultiplier (unsigned long propertySetMultiplierSetter) { // Setter
propertySetMultiplier = propertySetMultiplierSetter;
}
// Getters
unsigned long Monopoly::RulesClass::getpropertySetMultiplier() const { // Getter
return propertySetMultiplier;
}
void Monopoly::RulesClass::setNumberOfHouses_BeforeHotels (unsigned long NumberOfHouses_BeforeHotelsSetter) { // Setter
NumberOfHouses_BeforeHotels = NumberOfHouses_BeforeHotelsSetter;
}
unsigned long Monopoly::RulesClass::getNumberOfHouses_BeforeHotels() const {
return NumberOfHouses_BeforeHotels;
}
void Monopoly::RulesClass::setGOSalaryMultiplier (unsigned long GOSalaryMultiplierSetter) { // Setter
GOSalaryMultiplier = GOSalaryMultiplierSetter;
}
unsigned long Monopoly::RulesClass::getGOSalaryMultiplier() const { // Getter
return GOSalaryMultiplier;
}
void Monopoly::RulesClass::setTotalNumOfProperties (unsigned long totalNumOfPropertiesSetter) {
totalNumOfProperties = totalNumOfPropertiesSetter;
}
unsigned long Monopoly::RulesClass::getTotalNumOfProperties () const {
return totalNumOfProperties;
}
void Monopoly::RulesClass::setTotalRerollsAllowed (unsigned long RerollSetter) {
totalRerolls = RerollSetter;
}
unsigned long Monopoly::RulesClass::getRerollsAllowed () const {
return totalRerolls;
}
void Monopoly::RulesClass::setBHE (std::string BHEanswer) { // Setter
if (BHEanswer == "Yes") {
BuildHousesEvenly = true;
} else {
BuildHousesEvenly = false;
}
}
bool Monopoly::RulesClass::getBHE() const {
return BuildHousesEvenly;
};
void Monopoly::RulesClass::setAuction (std::string auctionAnswer) { // Setter
if (auctionAnswer == "Yes") {
AuctionProperty = true;
} else{
AuctionProperty = false;
}
}
bool Monopoly::RulesClass::getAuction() const{
return AuctionProperty;
}
void Monopoly::RulesClass::setFreeParkingOption (std::string setter){
if (setter == "Yes") {
FreeParkingOption = true;
}
else{
AuctionProperty = false;
}
}
bool Monopoly::RulesClass::getFreeParkingOption() const {
return FreeParkingOption;
}
| true |
a3fe4fb4884a17715174998363b2e663bf50b2db | C++ | jimkhan/UvaOnline | /10235 - Simply Emirp.cpp | UTF-8 | 1,231 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int nprime,mark[100000002];
vector<int> v;
void seive()
{
int n=10000009;
int i,j,lim=sqrt(n*1.)+2;
mark[1]=1;
for(i=4; i<=n; i+=2)
{
mark[i]=1;
}
v.push_back(2);
for(i=3; i<=n; i+=2)
{
if(mark[i]==0)
{
v.push_back(i);
}
if(i<=lim)
{
for(j=i*i; j<=n; j= j+(i*2))
{
mark[j]=1;
}
}
}
}
int rev(int x)
{
int i,j=0,k,l;
k=x;
while(k!=0)
{
l=k%10;
j=(j*10)+l;
k/=10;
}
return j;
}
int main()
{
//freopen("output.txt", "w", stdout);
int i,j,k,l,p,c,t;
seive();
while(cin>>l )
{
if(mark[l]!=0)
{
printf("%d is not prime.\n",l);
}
else if(mark[l]==0)
{
k=rev(l);
if( mark[k]==0 && k!=l)
{
printf("%d is emirp.\n",l);
}
else
{
printf("%d is prime.\n",l);
}
}
}
return 0;
}
| true |
4ab7eea793397abbc17a0c7a8950e5c66bb11c30 | C++ | pratmangalore/CNE | /Lab3/Error Detection/CRC.cpp | UTF-8 | 1,935 | 3.515625 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
string getRem(string input, string divisor) {
string res = input;
for (int i = 0; i < divisor.length() - 1; i++) {
res += "0";
}
for (int p2 = 0; p2 < res.length() - divisor.length() + 1; p2++) {
if (res[p2] == '0') {
continue;
}
for (int j = 0; j < divisor.length(); j++) {
res[p2+j] = '0' + ((res[p2+j] - '0') ^ (divisor[j] - '0'));
}
}
string remain;
for (int i = res.length() - divisor.length() + 1; i < res.length(); i++) {
remain += res[i];
}
return remain;
}
string checkRem(string input, string divisor) {
string res = input;
for (int p2 = 0; p2 < input.length() - divisor.length() + 1; p2++) {
if (res[p2] == '0') {
continue;
}
for (int j = 0; j < divisor.length(); j++) {
res[p2+j] = '0' + ((res[p2+j] - '0') ^ (divisor[j] - '0'));
}
}
return res;
}
void genCRC() {
cout << "input: ";
string input;
cin >> input;
string divisor = "1010";
string remain = getRem(input, divisor);
cout << "Remainder: " << remain << endl;
cout << "CRC: " << input + remain << endl;
}
void checkCRC() {
cout << "CRC: ";
string crc;
cin >> crc;
string divisor = "1010";
string remain = checkRem(crc, divisor);
cout << "Remainder: " << remain << endl;
}
int main() {
while (1) {
cout<<"Select ::\n";
cout<<"1.Enter 'g' to generate a CRC.\n2.Enter 'c' to check CRC.\n3.Enter 'e' to exit \n";
char ch;
cin >> ch;
switch(ch) {
case 'g':
genCRC();
break;
case 'c':
checkCRC();
break;
case 'e':
return 0;
default:
cout<<"Enter valid choice\n";
}
}
return 0;
}
| true |
956649bbb45e62c47d39872d1356481c9137e2a3 | C++ | vyas007kapil/temp | /Hamiltonian/ham.cpp | UTF-8 | 2,045 | 3.53125 | 4 | [] | no_license | //============================================================================
// Name : hamiltonian.cpp
// Author : KAPIL
// Version :
// Copyright : TE 10
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
class hamiltonian{
int **a,n,*path;
public:
hamiltonian(int no){
n=no;
a=new int*[n];
path=new int[n];
for(int i=0;i<n;i++){
path[i]=-1;
a[i]=new int[n];
}
}
void input();
void hampath();
int findnext(int);
bool issafe(int,int);
void display();
void printsolution(int*);
};
void hamiltonian::display(){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<a[i][j]<<"\t";
}
cout<<"\n";
}
}
void hamiltonian:: input(){
int s,d;
cout<<"Enter source,destination!!!";
while(true){
cin>>s>>d;
if(s>n || d>n){
cout<<"wrong vertex...";
break;
}
if(s==-1 || d==-1)
break;
a[s][d]=1;
a[d][s]=1;
}
}
bool hamiltonian::issafe(int v,int pos){
if(pos==0)
return true;
if(a[path[pos-1]][v]==0)
return false;
for(int i=0;i<pos;i++){
if(path[i]==v)
return false;
}
return true;
}
int hamiltonian::findnext(int pos){
int i;
if(pos==0){
if(path[pos]==-1)
return 0;
else if(path[pos]<n-1)
return path[pos]+1;
else return -1;
}
if(pos>=n)
return -1;
else{
i=path[pos]+1;
while(i<n){
if(issafe(i,pos))
return i;
i++;
}
}
return -1;
}
void hamiltonian::hampath(){
int pos=0,v;
while(true){
v=findnext(pos);
if(v==-1){
path[pos--]=-1;
if(pos==-1)
return;
}
else{
path[pos++]=v;
if(pos==n){
printsolution(path);
path[--pos]=-1;
pos--;
}
}
}
}
void hamiltonian::printsolution(int *path){
int i;
for(i=0;i<n;i++)
cout<<path[i]<<"->";
if(a[path[i-1]][path[0]])
cout<<path[0]<<endl;
cout<<endl;
}
int main() {
int n;
cout<<"Enter vertices";
cin>>n;
hamiltonian h(n);
h.input();
h.display();
h.hampath();
cout << "WELCOME" << endl; // prints WELCOME
return 0;
}
| true |
8e41bf4a2d9c4e3b84950567dc3f60aa3193fbfd | C++ | meyerfn/FiniteVolume_1D | /test/timediscretization/eulerForwardTimeDiscretization_unittest.cpp | UTF-8 | 1,317 | 2.734375 | 3 | [] | no_license | #include "../../src/timediscretization/eulerForwardTimeDiscretization/eulerForwardTimeDiscretization.hpp"
#include "../../src/timediscretization/timeDiscretizationInterface.hpp"
#include "gmock/gmock.h"
using namespace ::testing;
class RightHandSideMock : public TimeDiscretizationInterface
{
public:
MOCK_METHOD(std::vector<float>, computeRightHandSide,
(const std::vector<float>& solutionVector), (override));
};
class EulerForwardTest : public Test
{
protected:
float m_testDeltaT = 0.1;
unsigned int m_testNumberOfTimesteps = 1U;
};
TEST_F(EulerForwardTest, PerformOneEulerTimeStepWhenRightHandSideIsIdentity)
{
std::vector<float> solutionVector{1.};
auto expectedSolution =
solutionVector[0] + m_testDeltaT * solutionVector[0];
auto rhs_mock = std::make_shared<RightHandSideMock>();
EXPECT_CALL(*rhs_mock, computeRightHandSide(solutionVector));
ON_CALL(*rhs_mock, computeRightHandSide(solutionVector))
.WillByDefault(Invoke(
[](std::vector<float> solutionVector) { return solutionVector; }));
EulerForwardTimeDiscretization m_testEulerForwardTimeDisc(
m_testDeltaT, m_testNumberOfTimesteps, rhs_mock);
m_testEulerForwardTimeDisc.timestep(solutionVector);
ASSERT_THAT(solutionVector, Each(expectedSolution));
} | true |
653ad8a3d2ac7f9c12c98bdcad7497c9617126c0 | C++ | AlexLiuyuren/Qt-StudentInformationManager | /student.cpp | UTF-8 | 524 | 2.78125 | 3 | [] | no_license | #include "student.h"
#include <QString>
#include <iostream>
#include <QDebug>
using namespace std;
Student::Student(QString t_studentNum, QString t_name, QString t_gender, QString t_date, QString t_birthPlace, QString t_major)
{
studentNum = t_studentNum;
name = t_name;
gender = t_gender;
date = t_date;
birthPlace = t_birthPlace;
major = t_major;
}
void Student::print(){
qDebug() << studentNum << " " << name << " " << gender << " " << date << " " << birthPlace << " " << major << endl;
}
| true |
f96277c334bc543694c15896d22eb6cc1d9a3043 | C++ | amsiljak/c9-Projects | /Programming-Techniques/T8/Z4/main.cpp | UTF-8 | 1,235 | 3.078125 | 3 | [] | no_license | //TP 2018/2019: Tutorijal 8, Zadatak 4
#include <iostream>
#include <string>
#include <map>
std::string ZamijeniPremaRjecniku(std::string s,std::map<std::string,std::string> m)
{
std::string novi;
for(int i=0;i<s.size();i++)
{
if(s[i]==' ')
{
novi.push_back(s[i]);
continue;
}
auto j=i;
while(j!=s.size() && s[j]!=' ') j++;
std::string word;
while(i!=j)
{
word.push_back(s[i]);
i++;
}
auto it=m.find(word);
if(it==m.end())
{
i-=word.size();
while(i!=j)
{
novi.push_back(s[i]);
i++;
}
}
else{
auto temp =it->second;
for(auto i=0;i<temp.size();i++)
{
novi.push_back(temp[i]);
}
}
if(i==s.size()-1) break;
i--;
}
return novi;
}
int main ()
{
std::map<std::string, std::string> moj_rjecnik{{"jabuka", "apple"},
{"da", "yes"}, {"kako", "how"}, {"ne", "no"}, {"majmun", "monkey"}};
std::cout << ZamijeniPremaRjecniku("kako da ne", moj_rjecnik);
return 0;
} | true |
da4dd0a96044b103d937b463df72b18aa3eac5b8 | C++ | ronandoolan2/c-_codility_lessons_solutions | /prefix-set.cpp | UTF-8 | 630 | 3.140625 | 3 | [] | no_license |
// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
#include <algorithm>
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
vector<int> A2 = A;
sort(A.begin(), A.end());
A.erase(unique(A.begin(), A.end()), A.end());
int count = 0;
for (vector<int>::const_iterator i = A2.begin(); i != A2.end(); ++i)
{
A.erase(std::remove(A.begin(), A.end(), *i), A.end());
if(A.size() == 0)
{
return count;
}
count++;
}
}
| true |
dec915cb8f3e6356c508cb7285d4d90e93343d13 | C++ | CanTinGit/SoftRenderer | /SoftRenderer/my_thread.h | UTF-8 | 766 | 2.546875 | 3 | [] | no_license | #pragma once
#include <thread>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <list>
#include <functional>
#include <cstdio>
#include <vector>
class ThreadPool
{
public:
using Task = std::function<void(void)>;
explicit ThreadPool(int num);
explicit ThreadPool();
void Init(int num);
~ThreadPool();
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool &rhs) = delete;
void append(const Task &task);
void append(Task &&task);
void start();
void stop();
bool finishTask();
private:
bool isrunning;
int threadNum;
bool noTask;
void work(int id);
std::mutex m;
std::mutex newmutex;
std::condition_variable cond;
public:std::list<Task> tasks;
std::vector<std::shared_ptr<std::thread>> threads;
};
| true |
200e36f8ac7387ad9d5188d2a2befebf06e606c5 | C++ | heineman/algorithms-nutshell-2ed | /Code/Graph/Graph.cxx | UTF-8 | 4,310 | 3.640625 | 4 | [
"MIT"
] | permissive | /**
* @file Graph.cxx Implementation of Graph concept
* @brief
* Contains the implementation of the Graph class.
*
* @author George Heineman
* @date 6/15/08
*/
#include <stdio.h>
#include <string.h>
#include "Graph.h"
/**
* Load graph from file.
*
* File contains:
* <pre>
* Header
* V E
* v1,v2
* v1,v5
* ...
* </pre>
*
* \param fileName contains the graph information.
*/
void Graph::load (char *fileName) {
FILE *fp = fopen (fileName, "r");
int nv, ne;
// sufficient space? we hope so!
char buf[4096];
// read header as a whole line.
fgets (buf, 4096, fp);
// read n and e
int nr = fscanf (fp, "%d %d %s\n", &nv, &ne, buf);
if (nr != 3) {
printf ("Invalid file format %s\n", fileName);
n_=0;
delete [] vertices_;
return;
}
if (!strcmp (buf, "directed")) {
directed_ = true;
} else {
directed_ = false;
}
vertices_ = new VertexList [nv];
n_ = nv;
// since graph is known to be directed or undirected, we only need
// to call addEdge once, since the implementation will do the right
// thing.
while (ne-- > 0) {
int src, tgt, weight;
int nr = fscanf (fp, "%d,%d,%d\n", &src, &tgt, &weight);
if (nr == 2) {
addEdge (src, tgt);
} else if (nr == 3) {
addEdge (src, tgt, weight);
}
}
fclose(fp);
}
/**
* Does the edge (u,v) exist in the graph?
* \param u integer identifier of a vertex
* \param v integer identifier of a vertex
* \return true if edge exists, otherwise false
*/
bool Graph::isEdge (int u, int v) const {
for (VertexList::const_iterator ei = vertices_[u].begin();
ei != vertices_[u].end();
++ei) {
if (ei->first == v) {
return true;
}
}
return false;
}
/**
* Does the edge (u,v) exist in the graph? And if so, what is its weight?
* \param u integer identifier of a vertex
* \param v integer identifier of a vertex
* \param w returned weight of the edge, should it exist
* \return true if edge exists (and w contains meaningful information), otherwise false (and w is not meaningful).
*/
bool Graph::isEdge (int u, int v, int &w) const {
for (VertexList::const_iterator ei = vertices_[u].begin();
ei != vertices_[u].end();
++ei) {
if (ei->first == v) {
w = ei->second;
return true;
}
}
return false;
}
/**
* Add edge to graph structure from (u,v).
* If the graph is undirected, then we must add in reverse as well.
* It is up to user to ensure that no edge already exists. The check
* will not be performed here.
*
* \param u integer identifier of a vertex
* \param v integer identifier of a vertex
* \param w planned weight.
*/
void Graph::addEdge (int u, int v, int w) {
if (u > n_ || v > n_) {
throw "Graph::addEdge given vertex larger than graph size";
}
pair<int,int> edge(v,w);
vertices_[u].push_front(edge);
// undirected have both.
if (!directed_) {
pair<int, int> edgeR (u,w);
vertices_[v].push_front(edgeR);
}
}
/**
* Remove edge, and if undirected, remove its opposite as well.
* \param u integer identifier of a vertex
* \param v integer identifier of a vertex
* \return true if edge was removed, false otherwise
*/
bool Graph::removeEdge (int u, int v) {
bool found = false;
for (VertexList::const_iterator ei = vertices_[u].begin();
ei != vertices_[u].end();
++ei) {
if (ei->first == v) {
vertices_[u].remove(*ei);
found = true;
break;
}
}
// not found at all? return
if (!found) return false;
if (!directed_) {
for (VertexList::const_iterator ei = vertices_[v].begin();
ei != vertices_[v].end();
++ei) {
if (ei->first == u) {
vertices_[v].remove(*ei);
break;
}
}
}
return true;
}
/**
* Return edge weight, or INT_MIN if not present.
* \param u integer identifier of a vertex
* \param v integer identifier of a vertex
* \return INT_MIN if edge doesn't exist, otherwise return its weight.
*/
int Graph::edgeWeight (int u, int v) const {
for (VertexList::const_iterator ei = vertices_[u].begin();
ei != vertices_[u].end();
++ei) {
if (ei->first == v) {
return ei->second;
}
}
return numeric_limits<int>::min();
}
| true |
6bcc22a7615db9be11e761d1adc35c19df729499 | C++ | ArsenijPercov/eyden-tracer-02 | /src/ShaderPhong.h | UTF-8 | 1,722 | 2.84375 | 3 | [] | no_license | #pragma once
#include "ShaderFlat.h"
class CScene;
class CShaderPhong : public CShaderFlat
{
public:
/**
* @brief Constructor
* @param scene Reference to the scene
* @param color The color of the object
* @param ka The ambient coefficient
* @param kd The diffuse reflection coefficients
* @param ks The specular refelection coefficients
* @param ke The shininess exponent
*/
CShaderPhong(CScene& scene, Vec3f color, float ka, float kd, float ks, float ke)
: CShaderFlat(color)
, m_scene(scene)
, m_ka(ka)
, m_kd(kd)
, m_ks(ks)
, m_ke(ke)
{}
virtual ~CShaderPhong(void) = default;
virtual Vec3f Shade(const Ray& ray) const override
{
Vec3f sol_a;
Vec3f diff_sum = 0;
Vec3f spec_sum = 0;
Ray ray2;
Vec3f refl_dir;
std::optional<Vec3f> intens;
sol_a = m_ka*RGB(1,1,1);
ray2.org = ray.org + ray.t*ray.dir;
ray2.t = std::numeric_limits<float>::infinity();
for (auto it = m_scene.m_vpLights.begin();it != m_scene.m_vpLights.end();++it)
{
intens = (*it).get()->Illuminate(ray2);
if (!m_scene.Occluded(ray2))
{
diff_sum += *intens *max(0.0f,ray2.dir.dot(ray.hit->GetNormal(ray)));
refl_dir = ray2.dir - 2 * (ray2.dir.dot(ray.hit->GetNormal(ray))) * ray.hit->GetNormal(ray);
float dp = ray.dir.dot(refl_dir);
if (dp<0) dp =0;
spec_sum += *intens*pow(dp,m_ke);
}
}
Vec3f sol_d = m_kd*CShaderFlat::Shade(ray).mul(diff_sum);
Vec3f sol_e = m_ks*RGB(1,1,1)*spec_sum;
return sol_a + sol_d + sol_e;
}
private:
CScene& m_scene;
float m_ka; ///< ambient coefficient
float m_kd; ///< diffuse reflection coefficients
float m_ks; ///< specular refelection coefficients
float m_ke; ///< shininess exponent
};
| true |
80da49644d58a2ab1ff3aa443d342d80f3410f86 | C++ | progrematic/FreezeFrame | /FreezeFrame/Classes/Graphics/Effect.cpp | UTF-8 | 1,397 | 2.90625 | 3 | [] | no_license | #include "Effect.h"
#define CLOSE_ENOUGH 0.0000000005f
Effect::Effect()
{
SetFunction(sin);
SetValues(1, 1, 0, 0);
absolute = false;
Reset();
}
Effect::Effect(float _amplitude, float _period, float _xOffset, float _yOffset) : Effect()
{
SetValues(_amplitude, _period, _xOffset, _yOffset);
}
float Effect::Calculate()
{
return Calculate(clock.getElapsedTime().asSeconds());
}
float Effect::Calculate(float x)
{
float val = amplitude * (func(period * (x - xOffset))) + yOffset;
int diff = 0;
if (lastVal > val)
diff = -1;
else
diff = 1;
if (diff == 1 && lastDiff == -1)
{
botHits++;
if (topHits == botHits)
cycles++;
}
else if (diff == -1 && lastDiff == 1)
{
topHits++;
if (topHits == botHits)
cycles++;
}
//printf("%d --- %d::%d\n", cycles, topHits, botHits);
lastVal = val;
lastDiff = diff;
return absolute ? abs(val) : val;
}
void Effect::SetFunction(float(*_func)(float))
{
func = _func;
}
void Effect::SetValues(float _amplitude, float _period, float _xOffset, float _yOffset)
{
amplitude = _amplitude;
period = _period;
xOffset = _xOffset;
yOffset = _yOffset;
}
void Effect::SetAbsolute(bool _absolute)
{
absolute = _absolute;
}
void Effect::Reset()
{
lastVal = 0;
lastDiff = 1;
cycles = 0;
topHits = 0;
botHits = 0;
clock.restart();
}
int Effect::GetCycles()
{
return cycles;
}
sf::Clock& Effect::GetClock()
{
return clock;
} | true |
993fc8c073f9a76b4a762c40b840a5adf4234c7c | C++ | hakgagik/GaleEngine | /GaleEngine/Physics/PhysicsObjects/PhysicsObject.cpp | UTF-8 | 3,348 | 2.5625 | 3 | [] | no_license | #include "PhysicsObject.h"
#include "../Particles/Particle.h"
#include "../Forces/Force.h"
#include "../Forces/BoundingForce.h"
#include "../AABB.h"
#include "../../Managers/Physics_Manager.h"
#include <glm/glm.hpp>
using namespace Physics;
using namespace Particles;
using namespace PhysicsObjects;
using namespace Forces;
using namespace Managers;
using namespace glm;
using namespace std;
PhysicsObject::~PhysicsObject() { }
void PhysicsObject::AddForce(string name, Force* force) {
forceList[name] = force;
}
void PhysicsObject::InitParticles() {
for (auto kv : particleList) {
Particle* particle = kv.second;
particle->x = particle->x0;
particle->v = particle->v0;
particle->w = 1.0f / particle->m;
}
}
void PhysicsObject::ApplyForces() {
float dt = Physics_Manager::Get().dt;
for (auto kv : particleList) {
Particle* particle = kv.second;
vec3 forceAccum;
for (auto kv : forceList) {
forceAccum += kv.second->GetForce(particle);
}
particle->v += forceAccum * particle->w * dt;
}
}
void PhysicsObject::PredictPositions() {
float dt = Physics_Manager::Get().dt;
for (auto kv : particleList) {
Particle* particle = kv.second;
particle->p += dt * particle->v;
}
}
void PhysicsObject::CalculatePotentialInteractions() { }
void PhysicsObject::CollideWithBounds(vector<float> &bounds) {
float xmin = bounds[0];
float xmax = bounds[1];
float ymin = bounds[2];
float ymax = bounds[3];
float zmin = bounds[4];
float zmax = bounds[5];
float epsilon = std::min(std::min((xmax - xmin) / 1000, (ymax - ymin) / 1000), (zmax - zmin) / 1000);
for (auto kv : particleList) {
vec3 &p = kv.second->p;
if (p.x < xmin) {
p.x = xmin + epsilon;
dynamic_cast<BoundingForce*>(forceList["x_min_bound"])->AddParticle(kv.second);
}
if (p.x > xmax) {
p.x = xmax - epsilon;
dynamic_cast<BoundingForce*>(forceList["x_max_bound"])->AddParticle(kv.second);
}
if (p.y < ymin) {
p.y = ymin + epsilon;
dynamic_cast<BoundingForce*>(forceList["y_min_bound"])->AddParticle(kv.second);
}
if (p.y > ymax) {
p.y = ymax - epsilon;
dynamic_cast<BoundingForce*>(forceList["y_max_bound"])->AddParticle(kv.second);
}
if (p.z < zmin) {
p.z = zmin + epsilon;
dynamic_cast<BoundingForce*>(forceList["z_min_bound"])->AddParticle(kv.second);
}
if (p.z > zmax) {
p.z = zmax - epsilon;
dynamic_cast<BoundingForce*>(forceList["z_max_bound"])->AddParticle(kv.second);
}
}
}
void PhysicsObject::FinalizeParticles() {
float dt = Physics_Manager::Get().dt;
for (auto kv : particleList) {
Particle* particle = kv.second;
particle->v = (particle->p - particle->x) / dt;
particle->x = particle->p;
}
}
void PhysicsObject::UpdateAABB() {
vec3 p = particleList.begin()->second->x;
boundingBox->xmin = boundingBox->xmax = p.x;
boundingBox->ymin = boundingBox->ymax = p.y;
boundingBox->zmin = boundingBox->zmax = p.z;
for (auto kv : particleList) {
p = kv.second->x;
if (p.x < boundingBox->xmin) {
boundingBox->xmin = p.x;
}
else if (p.x > boundingBox->xmax) {
boundingBox->xmax = p.x;
}
if (p.y < boundingBox->ymin) {
boundingBox->ymin = p.y;
}
else if (p.y > boundingBox->ymax) {
boundingBox->ymax = p.y;
}
if (p.z < boundingBox->zmin) {
boundingBox->zmin = p.z;
}
else if (p.z > boundingBox->zmax) {
boundingBox->zmax = p.z;
}
}
} | true |
a66754fb66ac225202fabb8238a041fb5b76430a | C++ | AmandaNiy23/SCAPES | /source/savefileascontrol.cpp | UTF-8 | 1,717 | 2.515625 | 3 | [] | no_license | #include "savefileascontrol.h"
#include <inputmanager.h>
#include <QMessageBox>
#include <QTextStream>
#include <QFileDialog>
#include <QFileInfo>
SaveFileAsControl::SaveFileAsControl(InputManager* const inputmanager)
{
manager = inputmanager;
saved = false;
}
/*
saveFileAs
purpose: save a file and prompt the user for a file name
in:
QString: text - contents of the file
*/
void SaveFileAsControl::saveFileAs(QString text)
{
//full file path
QFileDialog fileDialog;
QString fullPath = QFileDialog::getSaveFileName(0, " Save As");
//file directory
QDir absoluteDir = QFileInfo(fullPath).absoluteDir();
QString absolute=absoluteDir.absolutePath();
//file name
QString name = QFileInfo(fullPath).fileName();
manager->setFileDirectory(absolute);
QFile file(fullPath);
//Try opening the file with Write Only capabilities, if this fails, display an error message
if(!file.open(QIODevice::WriteOnly | QFile::Text)){
QMessageBox::warning(nullptr, "Warning", "Cannot save file: " + file.errorString());
return;
}
//Update the current file name and the window title
manager->updateFileName(name);
//update full path
manager->setFullPath(fullPath);
//setWindowTitle(fileName);
//copy the text from the textEdit area, convert it to plain text, and output it to the file
QTextStream out(&file);
out << text;
file.close();
saved = true;
//ui->actionSave->setEnabled(true);
//saveFileAsControlResponse();
}
SaveFileAsControl::~SaveFileAsControl()
{
}
/*
isSaved
purpose: verify if the file has been saved or not
*/
bool SaveFileAsControl::isSaved(){
return saved;
}
| true |
2b972d52aff29546d84c43b959ffed77ecbf709b | C++ | pointhi/sulong | /tests/com.oracle.truffle.llvm.tests.sulongcpp/cpp/test013.cpp | UTF-8 | 701 | 3.296875 | 3 | [
"BSD-3-Clause",
"NCSA",
"MIT"
] | permissive |
#include <stdio.h>
class Base {
public:
virtual int foo() {
return 13;
}
};
class A : public Base {
public:
int foo() {
return 11;
}
int tar() {
return 77;
}
};
class B : public Base {
public:
int foo() {
return 15;
}
int bar() {
return 99;
}
};
int foo(int a) {
if (a == 0) {
throw B();
}
return a;
}
int main(int argc, char *argv[]) {
try {
foo(0);
return 0;
} catch (const char *msg) {
return 1;
} catch (long value) {
return 2;
} catch (int *value) {
return 3;
} catch (A &value) {
printf("Catch A\n");
return value.foo();
} catch (Base &value) {
printf("Catch B\n");
return value.foo();
}
} | true |
ddbb404772fa861a328ef76760f86ada41680ce0 | C++ | KingaMilaszkiewicz/2-tablica_2d_szachownica | /2-tablica_2d_szachownica/2-tablica_2d_szachownica.cpp | UTF-8 | 1,817 | 3.421875 | 3 | [] | no_license | // 2-tablica_2d_szachownica.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
int main() {
char tab[8][8];
int x = 0;
std::cout << " A B C D E F G H" << std::endl;
std::cout << " _________________" << std::endl;
for (int i = 0; i < 8; i++) {
std::cout << i+1 << "|";
for (int j = 0; j < 8; j++) {
if (i == 0 || i == 2) { // write "o" for every second row in columns 0 and 2 starting with the second row
if (j % 2 == 1) {
tab[i][j] = 'o';
}
else {
tab[i][j] = ' ';
}
}
if (i == 1) { // write "o" for every second row in column 1 starting with the first row
if (j % 2 == 0) {
tab[i][j] = 'o';
}
else {
tab[i][j] = ' ';
}
}
if (i == 3 || i == 4) { // write " " for every row in columns 3 and 4
tab[i][j] = ' ';
}
if (i == 5 || i == 7) {// write "x" for every second row in columns 5 and 7 starting with the first row
if (j % 2 == 0) {
tab[i][j] = 'x';
}
else {
tab[i][j] = ' ';
}
}
if (i == 6) { // write "x" for every second row in column 6 starting with the second row
if (j % 2 == 1) {
tab[i][j] = 'x';
}
else {
tab[i][j] = ' ';
}
}
std::cout << tab[i][j] << "|";
}
std::cout << std::endl << " _________________" << std::endl;
}
}
| true |
f343e67545f59e4e6b9e270201386b8d46822245 | C++ | hermanzdosilovic/bachelor-thesis-project | /Layouter/Source/Layouter/Spacer/Spacer.cpp | UTF-8 | 988 | 2.765625 | 3 | [] | no_license | #include "Spacer.hpp"
namespace layouter::spacer
{
OcrResult space( SpacerVariant const & spacerVariant, OcrResult const & ocrResult )
{
return std::visit
(
[ & ocrResult ] ( auto parameter )
{
return space( parameter, ocrResult );
},
spacerVariant
);
}
OcrResult space( CompositeSpacerVariant const & compositeSpacerVariant, OcrResult const & ocrResult )
{
return std::visit
(
[ & ocrResult ] ( auto parameter )
{
return space( parameter, ocrResult );
},
compositeSpacerVariant
);
}
OcrResult space( std::vector< SpacerVariant > const & spacerVariants, OcrResult const & ocrResult )
{
OcrResult spacedResult{ ocrResult };
for ( auto const & variant : spacerVariants )
{
spacedResult = space( variant, spacedResult );
}
return spacedResult;
}
}
| true |
eec33e524924d138b85ef6174981e696b1005ec6 | C++ | WildBoarGonnaGo/42-Piscine-CPP | /day00/train00/Sample.class.cpp | UTF-8 | 310 | 2.828125 | 3 | [] | no_license | #include "Sample.class.hpp"
Sample::Sample(void)
{
std::cout << "Constructor is called" << std::endl;
return ;
}
Sample::~Sample(void)
{
std::cout << "Destructor is called" << std::endl;
return ;
}
void Sample::bar(void)
{
std::cout << "Member of class Sample (bar) is called" << std::endl;
return ;
} | true |
0d74baae5d79fcfd6e4a24c88d930e66bcc243d4 | C++ | ccdxc/logSurvey | /data/crawl/wget/new_hunk_2790.cpp | UTF-8 | 188 | 3.078125 | 3 | [] | no_license | if (write_error < 0)
{
logprintf (LOG_VERBOSE, _("Failed writing to proxy: %s.\n"),
fd_errstr (sock));
CLOSE_INVALIDATE (sock);
return WRITEFAILED;
}
| true |
12dcecb1086658dbb8a84de6b4d8714a6dec9134 | C++ | hanming-lu/cc3k | /cc3k/Human.cc | UTF-8 | 481 | 2.953125 | 3 | [] | no_license | // Notes left for Suri on dropGold, needs Suri's HumanHoard.h to compile
#include "Human.h"
#include "Normal.h"
#include "Info.h"
// returns the most detailed Type
Type Human::getType() const {
return Type::Human;
}
// HumanHoard ctor needs to check if x,y has a Human, if yes, delete that human
// does not give gold directly, calls HumanHoard ctor
int Human::dropGold() {
return 0;
}
// ctor calls Enemy's ctor
Human::Human(int x, int y) : Enemy(140, 20, 20, x, y) {}
| true |
7624625bf4d3faaa81cc2e33ded839669c29ca42 | C++ | jrahman-zz/CS307 | /gamelib/include/Enemy.h | UTF-8 | 437 | 2.671875 | 3 | [] | no_license | #ifndef ENEMY_H
#define ENEMY_H
#include "Moveable.h"
#include "Hero.h"
#include "json/json.h"
class Enemy : public Moveable {
public:
Enemy(Json::Value value);
virtual ~Enemy();
virtual bool interact(Interactable& target);
protected:
/*
* Ban default construction
*/
Enemy() = delete;
virtual bool interact_impl(Hero& target);
virtual bool interact_impl(Enemy& target);
};
#endif // ENEMY_H
| true |
453272d51e3ceebe4d3808f738a5c0468243f063 | C++ | tanaytoshniwal/CPP-Programs | /File Handling/createfile.cpp | UTF-8 | 229 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
ofstream file("Student.txt");
cout<<"Input your name";
string data;
getline(cin ,data);
file<<data;
return 0;
} | true |
451aabc5b9578a47acbaa85d5a942246fe534c9a | C++ | TomMagdaci/Design-Patterns | /Builder.cpp | UTF-8 | 1,196 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <string.h>
#include <unordered_map>
#include <cstring>
using namespace std;
class Robot;
class RobotBuilder {
string name;
int id;
double mass;
int flyable;
friend class Robot;
public:
RobotBuilder(string nname, int nid): name(nname), id(nid), mass(0), flyable(0) {}
RobotBuilder& setMass(double nmass) {
mass = nmass;
return *this;
}
RobotBuilder& setFlyable(int nflyable) {
flyable=nflyable;
return *this;
}
Robot* buildRobot();
};
class Robot {
public:
const string name;
const int id;
const double mass;
const int flyable;
Robot(RobotBuilder* rb): name(rb->name), id(rb->id), mass(rb->mass), flyable(rb->flyable){}
};
Robot* RobotBuilder::buildRobot() {
return new Robot(this);
}
/*int main()
{
RobotBuilder rb("tom",313);
Robot* robot = rb.setFlyable(1).setMass(5555).buildRobot();
cout<<"I have built the next robot: "<<robot->name<<" "<<robot->id<<" "<<robot->mass<<" "<<robot->flyable<<endl;
return 0;
}*/
| true |
ef10e432a3e7609b9993d6d7f3865cf2756e334a | C++ | PawelBocian/Arduino-nRF24L01-Radio-Communication-project | /src/message/Response.h | UTF-8 | 348 | 2.84375 | 3 | [] | no_license | #include <stdint.h> //library to use uint variable
#include <Arduino.h>
//Class represents response
class Response {
private:
uint8_t id = 99;
uint16_t value;
public:
//Setters
void setId(uint8_t id);
void setValue(uint16_t val);
//Getters
uint8_t getId();
uint16_t getValue();
};
| true |
457b4470a93fdd0550a42909a1a1d44f64eb6e4b | C++ | thextroid/edunote | /2216.cpp | UTF-8 | 828 | 2.59375 | 3 | [] | no_license | #include <ionumbeream>
#include <stdio.h>
#include <cnumbering>
#include <vector>
#include <map>
using namespace std;
#define FOR(i,a,b)for (int i = (a); (i) < (b); ++i)
#define si if
bool solve(numbering &s,numbering &t){
numbering temp = "";
temp = s[4] + temp;
numbering::size_type M = t.find(temp);
map<char,int> mp;
if( M != numbering::npos){
FOR(i,0,s.size())if(i!=4)mp[ s[i] ]++;
FOR(i,0,t.size()){
si(i==(int)M)continue;
si( mp[ t[i] ]>0 )
mp[ t[i] ] --;
else
return false;
}
return true;
}
return false;
}
int main(){
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
numbering s,ti;
int Q;
while(cin>>s){
scanf("%d",&Q);
while(Q--){
cin>>ti;
( solve(s,ti) && ti.size()>3)?printf("%s is valid\n", &ti[0]):printf("%s is invalid\n", &ti[0]);
}
}
return 0;
}
| true |
ba1c888918855d12b6bff5d2cca57c3c18142dd1 | C++ | maybeabhishek/CodingChallenges | /LeetCode/560-subarray-sm-equals-k/sum.cpp | UTF-8 | 397 | 2.671875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n = nums.size();
int ans = 0;
int pref = 0;
unordered_map<int,int> count;
count[pref]++;
for(int R = 0; R < n; R++){
pref+=nums[R];
int need = pref - k;
ans+=count[need];
count[pref]++;
}
return ans;
}
}; | true |
6b1ff5e8fb2a180a653ee2dc76f35875ba9167d7 | C++ | PurcarasPaul/Algorithm-Problems | /Kattis/Week 7/Saving Princess Peach.cpp | UTF-8 | 586 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
vector<int> obstacles;
void read()
{
int N, Y;
cin >> N >> Y;
for (int i = 0;i < N;i++)
{
obstacles.push_back(i);
}
for (int i = 0;i < Y;i++)
{
int temp;
cin >> temp;
obstacles[temp]=-1;
}
}
void print()
{
int ct_obstacles_found = 0;
for (int i = 0;i < obstacles.size();i++)
{
if (obstacles[i] >= 0)
cout << obstacles[i] << endl;
else ct_obstacles_found++;
}
cout << "Mario got " << ct_obstacles_found << " of the dangerous obstacles." << endl;
}
int main()
{
read();
print();
return 0;
} | true |
94ce0cae19096ec98fc04dc5eff87120f7354732 | C++ | a5221985/algorithms | /c_plus_plus/runtime_polymorphism.cpp | UTF-8 | 1,080 | 3.84375 | 4 | [] | no_license | #include <iostream>
using namespace std;
// Base class
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int width) {
this->width = width;
}
void setHeight(int height) {
this->height = height;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle : public Shape {
public:
int getArea() {
return width * height;
}
};
class Triangle : public Shape {
public:
int getArea() {
return (width * height) / 2;
}
};
int main(void) {
Shape *rectangle = new Rectangle();
Shape *triangle = new Triangle();
rectangle->setWidth(5);
rectangle->setHeight(7);
cout << "Total Rectangle area: " << rectangle->getArea() << endl;
triangle->setWidth(9);
triangle->setHeight(8);
cout << "Total Triangle area: " << triangle->getArea() << endl;
delete rectangle;
delete triangle;
return 0;
}
| true |
e3b3a9e62a29d6a1ba7b0cc3785718494dbfd901 | C++ | JosuaKugler/uni | /1_ws19_20/ipi/ipiclib/Programm.cc | UTF-8 | 2,736 | 3.40625 | 3 | [] | no_license | // Konstruktor fuer leeres Programm
Programm::Programm ()
{
zeilen = 0; // noch keine gueltige Zeile
fertig = false;
}
// Fuege eine Zeile in die Zustandsuebrgangstabelle hinzu
void Programm::zeile (int q_ein, char s_ein, char s_aus, R richt, int q_aus)
{
if (fertig) {
print("Programm war schon abgeschlossen!");
return;
}
Qaktuell[zeilen] = q_ein;
eingabe[zeilen] = s_ein;
ausgabe[zeilen] = s_aus;
richtung[zeilen] = richt;
Qfolge[zeilen] = q_aus;
zeilen = zeilen+1;
}
// Definiere letzte Zeile in der Zustandsuebergangstabelle
void Programm::zeile (int endzustand)
{
if (fertig) {
print("Programm war schon abgeschlossen!");
return;
}
Qaktuell[zeilen] = endzustand;
zeilen = zeilen+1;
fertig = true;
print("Programm mit ",zeilen," Zeilen definiert",0);
print("Anfangszustand ",Anfangszustand(),0);
print("Endzustand ",Endzustand(),0);
}
// Ermittle zu schreibendes Zeichen
char Programm::Ausgabe (int q, char symbol)
{
// wurde Zeile als letztes benutzt ?
if ( letztesQ==q && letzteEingabe==symbol )
return ausgabe[letzteZeile];
// suche Zeile im Programm
if (FindeZeile(q,symbol))
return ausgabe[letzteZeile];
// Fehler: es gibt keine solche Zeile
print(q," , ",symbol,0);
print(" nicht definiert!");
return 0;
}
// Ermittle Richtung
Programm::R Programm::Richtung (int q, char symbol)
{
// wurde Zeile als letztes benutzt ?
if ( letztesQ==q && letzteEingabe==symbol )
return richtung[letzteZeile];
// suche Zeile im Programm
if (FindeZeile(q,symbol))
return richtung[letzteZeile];
// Fehler: es gibt keine solche Zeile
print(q," , ",symbol,0);
print(" nicht definiert!");
return links;
}
// Ermittle Folgezustand
int Programm::Folgezustand (int q, char symbol)
{
// wurde Zeile als letztes benutzt ?
if ( letztesQ==q && letzteEingabe==symbol )
return Qfolge[letzteZeile];
// suche Zeile im Programm
if (FindeZeile(q,symbol))
return Qfolge[letzteZeile];
// Fehler: es gibt keine solche Zeile
print(q," , ",symbol,0);
print(" nicht definiert!");
return -1;
}
// Gebe Anfangszustand zurueck
int Programm::Anfangszustand ()
{
return Qaktuell[0];
}
// Gebe Endzustand zurueck
int Programm::Endzustand ()
{
return Qaktuell[zeilen-1];
}
// Finde Zeile in der Zustandsuebergangstabelle zu gegebenem
// Zustand und Symbol. Merke Eingabe und Zeilennummer damit
// bei wiederholtem Zugriff nicht gesucht werden muss.
bool Programm::FindeZeile (int q, char symbol)
{
for (int i=0; i<zeilen; i=i+1)
if ( Qaktuell[i]==q && eingabe[i]==symbol )
{
letzteZeile = i;
letztesQ = Qaktuell[letzteZeile];
letzteEingabe = eingabe[letzteZeile];
return true;
}
return false;
}
| true |
520a1a3cbf8d19b6446604050cfb685ada37b554 | C++ | xuelei7/AOJ | /Volume0(PCK)/aoj0070_CombinationOfNumberSequences.cpp | UTF-8 | 1,479 | 3.265625 | 3 | [] | no_license | // Combination of Number Sequences
// 0 から 9 までの整数を使った n 個の数の並び k1, k2, ..., kn を考えます。正の整数 n と s を読み込んで、
// k1+2×k2+3×k3+ ... +n×kn=s
// となっているような n 個の数の並びが何通りあるかを出力するプログラムを作成してください。ただし、1 つの「n 個の数の並び」には同じ数が 2 回以上現われないものとします。
// Input
// 入力は複数のデータセットからなります。各データセットとして、n (1 ≤ n ≤ 10) と s (0 ≤ s ≤ 10,000)が空白区切りで1行に与えられます。
// データセットの数は 100 を超えません。
// Output
// データセットごとに、n 個の整数の和が s になる組み合わせの個数を1行に出力します。
// [new]: fill's usage
#include <bits/stdc++.h>
using namespace std;
int dp[1100][1000][11];
int n,s;
int f(int sta, int sum, int num) {
if (dp[sta][sum][num] != -1) return dp[sta][sum][num];
if (num == n) return sum == s;
if (sum > s) return 0;
int ret = 0;
for (int i = 0; i < 10; i++) {
if ((sta >> i) & 1) continue;
ret += f(sta | (1 << i), sum + i * (num + 1), num + 1);
}
return dp[sta][sum][num] = ret;
}
int main() {
while (cin >> n >> s) {
fill(dp[0][0],dp[1099][999],-1);
cout << f(0,0,0) << endl;
}
return 0;
} | true |
d9da21c12f37a34e1a88d115c1a45646a2b0a070 | C++ | sPHENIX-Collaboration/coresoftware | /offline/packages/trackbase/TrkrClusterContainerv1.cc | UTF-8 | 1,736 | 2.765625 | 3 | [] | no_license | /**
* @file trackbase/TrkrClusterContainerv1.cc
* @author D. McGlinchey
* @date June 2018
* @brief Implementation of TrkrClusterContainerv1
*/
#include "TrkrClusterContainerv1.h"
#include "TrkrCluster.h"
#include <cstdlib>
void TrkrClusterContainerv1::Reset()
{
while (m_clusmap.begin() != m_clusmap.end())
{
delete m_clusmap.begin()->second;
m_clusmap.erase(m_clusmap.begin());
}
return;
}
void TrkrClusterContainerv1::identify(std::ostream& os) const
{
os << "-----TrkrClusterContainerv1-----" << std::endl;
ConstIterator iter;
os << "Number of clusters: " << size() << std::endl;
for (iter = m_clusmap.begin(); iter != m_clusmap.end(); ++iter)
{
int layer = TrkrDefs::getLayer(iter->first);
os << "clus key " << iter->first << " layer " << layer << std::endl;
(iter->second)->identify();
}
os << "------------------------------" << std::endl;
return;
}
void TrkrClusterContainerv1::addClusterSpecifyKey(const TrkrDefs::cluskey key, TrkrCluster* newclus)
{
const auto [iter, success] = m_clusmap.insert(std::make_pair(key, newclus));
if (!success)
{
std::cout << "TrkrClusterContainerv1::AddClusterSpecifyKey: duplicate key: " << key << " exiting now" << std::endl;
exit(1);
}
}
void TrkrClusterContainerv1::removeCluster(TrkrDefs::cluskey key)
{
m_clusmap.erase(key);
}
TrkrClusterContainer::ConstRange
TrkrClusterContainerv1::getClusters() const
{
return std::make_pair(m_clusmap.cbegin(), m_clusmap.cend());
}
TrkrCluster*
TrkrClusterContainerv1::findCluster(TrkrDefs::cluskey key) const
{
auto it = m_clusmap.find(key);
return it == m_clusmap.end() ? nullptr : it->second;
}
unsigned int TrkrClusterContainerv1::size() const
{
return m_clusmap.size();
}
| true |
1834577c2eb8a2ab14d1f786be9d915a8ae1f3b6 | C++ | yutaka-watanobe/problem-solving | /AOJ/0039/0039.cpp | UTF-8 | 493 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include<map>
#include<string>
using namespace std;
main(){
map<char, int> M;
M[' '] = 0;
M['I'] = 1;
M['V'] = 5;
M['X'] = 10;
M['L'] = 50;
M['C'] = 100;
M['D'] = 500;
M['M'] = 1000;
string line;
while( cin >> line ){
line += ' ';
int sum = 0;
for ( int i = 0; i < line.size()-1; i++ ){
if ( M[line[i]] < M[line[i+1]] ){
sum -= M[line[i]];
} else {
sum += M[line[i]];
}
}
cout << sum << endl;
}
}
| true |
b91b30a9c9ee156ce3f1ae053d166e36a256ec95 | C++ | juarezpaulino/coderemite | /problemsets/UVA/10911.cpp | UTF-8 | 977 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int N;
int X[20], Y[20];
double D[20][20];
double DP[1<<20];
double go(int k) {
double &ret = DP[k];
if (ret < 1E10-10) return ret;
if (!k) return ret = 0;
int i = __builtin_ctz(k);
for (int j = i+1; j < N; j++) if (k&(1<<j))
ret = min(ret, D[i][j]+go(k^(1<<i)^(1<<j)));
return ret;
}
int main() {
int c = 1;
while (scanf("%d", &N)) {
if (!N) break;
N *= 2;
for (int i = 0; i < N; i++)
scanf("%*s %d %d", X+i, Y+i);
for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) {
double dy = Y[i]-Y[j], dx = X[i]-X[j];
D[i][j] = D[j][i] = sqrt(dx*dx+dy*dy);
}
for (int i = 0; i < 1<<N; i++) DP[i] = 1E10;
double ret = go((1<<N)-1);
printf("Case %d: %.2lf\n", c++, ret);
}
return 0;
}
| true |
0789ba18a4deac0daf70210926a7c768513307f7 | C++ | pkriachu/CoDroid | /smaliutil/smaliparse.cpp | UTF-8 | 15,865 | 2.640625 | 3 | [] | no_license | #include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <dirent.h>
#include <pthread.h>
#include <vector>
#include "smaliparse.h"
using namespace std;
using namespace smali;
/**
* tokenize a string
*
* @param string [in] the string to be tokenized
* @param delim [in] list of delimiters
* @param tokens [out] obtained tokens
* @returns number of tokens
*/
unsigned
smali::tokenize(const char *string, const char *delim, tokens_t &tokens) {
char *token, *saveptr, buf[65536];
tokens.clear();
strncpy(buf, string, sizeof(buf));
token = strtok_r(buf, delim, &saveptr);
while(token != NULL) {
tokens.push_back(token);
token = strtok_r(NULL, delim, &saveptr);
}
return tokens.size();
}
/**
* Return the current timestamp in second.microsecond format
*
* @return a second.microsecond string
*/
std::string
smali::timestamp(bool showdiff) {
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static struct timeval lasttv = { 0, 0 };
long long delta = 0LL;
struct timeval tv;
char buf[64];
gettimeofday(&tv, NULL);
pthread_mutex_lock(&mutex);
if(showdiff && lasttv.tv_sec != 0) {
delta = (tv.tv_sec - lasttv.tv_sec) * 1000000;
delta += tv.tv_usec;
delta -= lasttv.tv_usec;
}
lasttv = tv;
pthread_mutex_unlock(&mutex);
#ifdef __APPLE__
#define TSFORMAT "%ld.%06d"
#else
#define TSFORMAT "%ld.%06ld"
#endif
if(showdiff) {
snprintf(buf, sizeof(buf), TSFORMAT "(+%.3f)", tv.tv_sec, tv.tv_usec, 0.000001 * delta);
} else {
snprintf(buf, sizeof(buf), TSFORMAT, tv.tv_sec, tv.tv_usec);
}
#undef TSFORMAT
return buf;
}
/**
* Find files recursively.
* This is an internal function called by find_files
*
* @param rootdir [in] path to the directory
* @param suffix [in] filename extention, can be NULL
* @param suffixlen [in] length of suffix, must be 0 if suffix is NULL
* @param pathlist [out] reference to the list storing filenames (in string)
* @return number of matched files
*/
static int
find_files_recursive(const char *rootdir, const char *suffix, int suffixlen, pathlist_t &pathlist) {
DIR *dir;
int name_max, entlen, fcount = 0;
struct dirent *ent, *result = NULL;
struct stat st;
if((dir = opendir(rootdir)) == NULL) {
return 0;
}
name_max = pathconf(rootdir, _PC_NAME_MAX);
if (name_max == -1) /* Limit not defined, or error */
name_max = 255; /* Take a guess */
entlen = sizeof(struct dirent) + name_max + 1;
if((ent = (struct dirent *) malloc(entlen)) == NULL) {
perror("malloc(dirent)");
closedir(dir);
return 0;
}
bzero(ent, entlen);
while(readdir_r(dir, ent, &result) == 0) {
string fullname = rootdir;
if(result == NULL)
break;
if(strcmp(ent->d_name, ".") == 0)
continue;
if(strcmp(ent->d_name, "..") == 0)
continue;
fullname += "/";
fullname += ent->d_name;
if(stat(fullname.c_str(), &st) != 0)
continue;
if(S_ISDIR(st.st_mode)) {
fcount += find_files_recursive(fullname.c_str(), suffix, suffixlen, pathlist);
continue;
}
if(!S_ISREG(st.st_mode)) {
continue;
}
if(suffixlen > 0) {
if(strcmp(suffix, fullname.c_str()+fullname.size()-suffixlen) != 0)
continue;
}
//fprintf(stderr, "# file: %s\n", fullname.c_str());
pathlist.push_back(fullname);
fcount++;
}
free(ent);
closedir(dir);
return fcount;
}
/**
* Find files recursively.
*
* @param rootdir [in] path to the directory
* @param suffix [in] filename extention, can be NULL
* @param pathlist [out] reference to the list storing filenames (in string)
* @return number of matched files
*/
int
smali::find_files(const char *rootdir, const char *suffix, std::list<std::string> &pathlist) {
pathlist.clear();
return find_files_recursive(rootdir, suffix, suffix == NULL ? 0 : strlen(suffix), pathlist);
}
/**
* Load a file into memory.
*
* @parm smali [in] path to the smali filename
* @param codes [out] store all loaded source codes
* @param classlist [out] output identified classes
* @param methodlist [out] output identified methods
* @return always returns 0, or terminate program on error.
*
* The key to 'codes' and 'classlist' is the class name.
* The key to 'methodlist' is 'classname->methodname', include method parameters and return value.
* Note that each smali file must only contain one class.
*/
int
smali::load_a_file(const char *smali, codelist_t &codes, classlist_t &classlist, methodlist_t &methodlist) {
FILE *fin;
char buf[65536];
string classname = "";
string methodname = "";
class_t myclass;
//vector<string> lines;
vector<code_t> lines;
unsigned lineno = 0;
unsigned method_locals = 0;
unsigned method_flags = 0;
unsigned method_start = 0;
if((fin = fopen(smali, "rt")) == NULL)
return 0;
while(fgets(buf, sizeof(buf), fin) != NULL) {
char *begin, *end;
char *token, *saveptr;
vector<string> tokens;
string lasttoken = "";
code_t code;
// remove leading spaces
for(begin = buf; *begin && isspace(*begin); begin++)
;
// move to end
for(end = begin; *end; end++)
;
// remove tailing spaces
for(--end; end >= begin; end--) {
if(isspace(*end))
*end = '\0';
else
break;
}
//
code.raw = begin;
lines.push_back(code);
lineno++;
#define DELIM " \t\n\r\f\v"
if((token = strtok_r(begin, DELIM, &saveptr)) == NULL)
continue;
lines.back().instruction = token;
//
if(strcmp(token, ".method") != 0
&& strcmp(token, ".end") != 0
&& strcmp(token, ".locals") != 0
&& strcmp(token, ".field") != 0
&& strcmp(token, ".super") != 0
&& strcmp(token, ".class") != 0)
continue;
do {
tokens.push_back(token);
} while((token = strtok_r(NULL, DELIM, &saveptr)) != NULL);
#undef DELIM
if(tokens[0] == ".class") {
if(classname != "") {
fprintf(stderr, "# smali/load_a_file: duplicated class name definition @ %s:%u\n",
classname.c_str(), lineno);
exit(-1);
}
classname = tokens.back();
myclass.classname = classname;
} else if(tokens[0] == ".super") {
myclass.super = tokens[1];
} else if(tokens[0] == ".locals") {
method_locals = strtol(tokens[1].c_str(), NULL, 0);
} else if(tokens[0] == ".field") {
string tmpname = "";
field_t field;
std::size_t pos;
unsigned i;
field.line = lineno-1;
// identify the fieldname:type
for(i = 1; i < tokens.size(); i++) {
if(tokens[i] == "=") {
tmpname = tokens[i-1];
field.value = tokens[i+1];
break;
}
}
if(i == tokens.size())
tmpname = tokens.back();
// separate fieldname and type
if((pos = tmpname.find(':')) != string::npos) {
field.name = tmpname.substr(0, pos);
#define min(x, y) ((x) < (y) ? (x) : (y))
field.type = tmpname.substr(min(pos+1, tmpname.size()));
#undef min
} else {
field.name = tmpname;
field.type = "___UNKNOWN___";
}
myclass.fields[field.name] = field;
} else if(tokens[0] == ".method") {
methodname = tokens.back();
method_locals = 0;
method_flags = 0;
method_start = lineno-1;
if(tokens.size() > 2) {
for(unsigned i = 1; i < tokens.size()-1; i++) {
if(tokens[i] == "abstract") { method_flags |= SMALI_METHOD_FLAG_ABSTRACT; }
else if(tokens[i] == "bridge") { method_flags |= SMALI_METHOD_FLAG_BRIDGE; }
else if(tokens[i] == "constructor") { method_flags |= SMALI_METHOD_FLAG_CONSTRUCTOR; }
else if(tokens[i] == "declared-synchronized") { method_flags |= SMALI_METHOD_FLAG_DECLAREDSYNC; }
else if(tokens[i] == "final") { method_flags |= SMALI_METHOD_FLAG_FINAL; }
else if(tokens[i] == "native") { method_flags |= SMALI_METHOD_FLAG_NATIVE; }
else if(tokens[i] == "private") { method_flags |= SMALI_METHOD_FLAG_PRIVATE; }
else if(tokens[i] == "protected") { method_flags |= SMALI_METHOD_FLAG_PROTECTED; }
else if(tokens[i] == "public") { method_flags |= SMALI_METHOD_FLAG_PUBLIC; }
else if(tokens[i] == "static") { method_flags |= SMALI_METHOD_FLAG_STATIC; }
else if(tokens[i] == "synthetic") { method_flags |= SMALI_METHOD_FLAG_SYNTHETIC; }
else if(tokens[i] == "varargs") { method_flags |= SMALI_METHOD_FLAG_VARARGS; }
else if(tokens[i] == "synchronized") { method_flags |= SMALI_METHOD_FLAG_SYNCHRONIZED; }
else {
fprintf(stderr, "smali/load_a_file[FATAL]: unknown .method specifiers (%s), PLEASE CHECK!\n", tokens[i].c_str());
exit(1);
}
}
}
} else if(tokens[0] == ".end" && tokens.size() > 1 && tokens.back() == "method") {
method_t m;
m.classname = classname;
m.methodname = methodname;
m.flags = method_flags;
m.locals = method_locals;
m.start = method_start;
m.end = lineno-1;
methodlist[classname + "->" + methodname] = m;
myclass.methods[methodname] = m;
}
}
fclose(fin);
//
codes[classname] = lines;
classlist[classname] = myclass;
//
return 0;
}
/**
* Load files into memory. This function basically calls smali::load_files(filename, ...)
*
* @param pathlist [in] list of file paths to be loaded
* @param codes [out] store all loaded source codes
* @param classlist [out] output identified classes
* @param methodlist [out] output identified methods
* @return always returns 0
*/
int
smali::load_files(pathlist_t &pathlist, codelist_t &codes, classlist_t &classlist, methodlist_t &methodlist) {
pathlist_t::iterator pi;
for(pi = pathlist.begin(); pi != pathlist.end(); pi++) {
smali::load_a_file((*pi).c_str(), codes, classlist, methodlist);
}
return 0;
}
/**
* Add one line for caller/callee
*
* @param graph [in] The graph used to store the result
* @param a [in] origin function
* @param b [in] destination function
*
* This function can be used to build both forward and reverse call graph.
* For example,
* do callgraph_build_connect(caller_graph, a, b) and then
* do callgraph_build_connect(callee_graph, b, a)
*/
static void
callgraph_build_connect(callgraph_t &graph, string a, string b) {
callgraph_t::iterator ci;
map<string,int>::iterator cj;
if((ci = graph.find(a)) == graph.end()) {
map<string,int> m;
m[b] = 1;
graph[a] = m;
return;
}
if((cj = ci->second.find(b)) == ci->second.end()) {
ci->second[b] = 1;
return;
}
ci->second[b] = ci->second[b] + 1;
return;
}
/**
* Build callgraph from smali source codes
*
* @param smali [in] path to the smali file
* @param methodlist [in/out] list of all methods in the parsed smali
* @param caller [in/out] caller relationships
* @param callee [in/out] callee relationships
* @return 0 on success, of -1 on error
*
* If function A calls function B, the relationship is created as follows:
* - caller[A] = { [B,counter] }, where counter is the number of times that A calls B
* - callee[B] = { [A,counter] }, where counter is the number of times that B is called by A
*/
int
smali::callgraph_build(const char *smali, methodlist_t &methodlist, callgraph_t &caller, callgraph_t &callee) {
FILE *fin;
char buf[65536];
string classname = "";
string methodname = "";
unsigned lineno = 0;
unsigned method_start = 0;
if((fin = fopen(smali, "rt")) == NULL)
return 0;
#define DELIM " \t\n\r\f\v"
#define TYPE_UNKNOWN 0
#define TYPE_CLASS 1
#define TYPE_METHOD 2
#define TYPE_INVOKE 3
#define TYPE_END 4
while(fgets(buf, sizeof(buf), fin) != NULL) {
char *saveptr;
char *token = strtok_r(buf, DELIM, &saveptr);
int type = TYPE_UNKNOWN;
string lasttoken = "";
method_t l;
//
lineno++;
if(token == NULL) {
continue;
} else if(strncmp(token, "invoke-", 7) == 0) {
type = TYPE_INVOKE;
} else if(strcmp(token, ".method") == 0) {
type = TYPE_METHOD;
} else if(strcmp(token, ".end") == 0) {
type = TYPE_END;
} else if(strcmp(token, ".class") == 0) {
type = TYPE_CLASS;
} else {
continue;
}
// get the last token
while((token = strtok_r(NULL, DELIM, &saveptr)) != NULL) {
lasttoken = token;
}
if(type == TYPE_CLASS) { classname = lasttoken; }
else if(type == TYPE_METHOD) {
methodname = lasttoken;
method_start = lineno-1;
} else if(type == TYPE_END && lasttoken == "method") {
l.classname = classname;
l.start = method_start;
l.end = lineno-1;
methodlist[classname + "->" + methodname] = l;
} else if(type == TYPE_INVOKE) {
string a = classname + "->" + methodname;
string b = lasttoken;
// a calls b
callgraph_build_connect(caller, a, b);
callgraph_build_connect(callee, b, a);
}
}
#undef DELIM
#undef TYPE_UNKNOWN
#undef TYPE_CLASS
#undef TYPE_METHOD
#undef TYPE_INVOKE
#undef TYPE_END
fclose(fin);
return 0;
}
/**
* Build callgraph from preloaded source codes
*
* @param codes [in] preloaded source codes
* @param codes [in] preloaded function list
* @param caller [in/out] caller relationships
* @param callee [in/out] callee relationships
* @return 0 on success, of -1 on error
*
* If function A calls function B, the relationship is created as follows:
* - caller[A] = { [B,counter] }, where counter is the number of times that A calls B
* - callee[B] = { [A,counter] }, where counter is the number of times that B is called by A
*/
int
smali::callgraph_build(codelist_t &codes, methodlist_t &methodlist, callgraph_t &caller, callgraph_t &callee) {
codelist_t::iterator ci;
methodlist_t::iterator fi;
string classname, methodname, lasttoken;
unsigned i, start, end;
size_t pos;
// for each function
for(fi = methodlist.begin(); fi != methodlist.end(); fi++) {
classname = fi->second.classname;
methodname = fi->first;
start = fi->second.start;
end = fi->second.end;
//
ci = codes.find(fi->second.classname);
// scan each line of the function
for(i = start+1; i < end; i++) {
if(strncmp("invoke-", ci->second[i].raw.c_str(), 7) != 0)
continue;
if((pos = ci->second[i].raw.rfind(' ')) == string::npos)
continue;
lasttoken = ci->second[i].raw.substr(pos+1);
// methodname calls lasttoken
callgraph_build_connect(caller, methodname, lasttoken);
callgraph_build_connect(callee, lasttoken, methodname);
}
}
return 0;
}
/**
* Remove methods not provided in the package
*
* @param methodlist [in] The methodlist contains all the methods in the package
* @param caller [in/out] The caller graph to be removed
* @param callee [in/out] The callee graph to be removed
*/
void
smali::callgraph_remove_external(methodlist_t &methodlist, callgraph_t &caller, callgraph_t &callee) {
bool stable;
callgraph_t::iterator ci, ci_next, ci_remove;
map<string,int>::iterator cj, cj_next, cj_remove;
do {
stable = true;
for(ci = caller.begin(); ci != caller.end(); ci = ci_next) {
if(ci->second.size() == 0) {
ci_remove = ci;
ci_next = ++ci;
caller.erase(ci_remove);
stable = false;
continue;
}
for(cj = ci->second.begin(); cj != ci->second.end(); cj = cj_next) {
if(methodlist.find(cj->first) == methodlist.end()) {
callee.erase(cj->first);
cj_remove = cj;
cj_next = ++cj;
ci->second.erase(cj_remove);
stable = false;
continue;
}
cj_next = ++cj;
}
ci_next = ++ci;
}
} while(!stable);
return;
}
/**
* Identify methods used by caller/callee.
* Functions made no calls or funcions not called are ignored.
*
* @param methodused [out] The resulted function list
* @param methodlist [in] List of all methods
* @param caller [in] The caller graph
* @param callee [in] The callee graph
*
* The output methodlist contains the key in either caller graph or the callee graph
*/
void
smali::callgraph_methods_used(methodlist_t &methodused, methodlist_t &methodlist, callgraph_t &caller, callgraph_t &callee) {
callgraph_t::iterator ci;
methodused.clear();
for(ci = caller.begin(); ci != caller.end(); ci++) {
methodused[ci->first] = methodlist[ci->first];
}
for(ci = callee.begin(); ci != callee.end(); ci++) {
methodused[ci->first] = methodlist[ci->first];
}
return;
}
| true |
6d36712e9809330174eee46d18cea138b3766cf6 | C++ | mr-d-self-driving/PNC | /Planning/toolkits/deciders/destination.cpp | UTF-8 | 3,853 | 2.515625 | 3 | [] | no_license |
#include "../../toolkits/deciders/destination.h"
#include <algorithm>
#include <limits>
#include <unordered_set>
#include "../../common/get_now_time.h"
#include "../../common/frame.h"
#include "../../toolkits/deciders/utill.h"
extern ConfigParam g_config_param;
extern VehicleParam g_vehicle_config;
namespace planning {
using common::Status;
Destination::Destination(const TrafficRuleConfig& config) : TrafficRule(config) {}
Status Destination::ApplyRule(Frame* const frame,
ReferenceLineInfo* const reference_line_info) {
vehicle_state_ = reference_line_info->GetVehicleState();
if (!FindDestination(reference_line_info)) {
return Status::OK;
}
MakeDecisions(frame, reference_line_info);
return Status::OK;
}
bool Destination::FindDestination(ReferenceLineInfo* const reference_line_info){
auto destination = reference_line_info->reference_line().MapRoute().GetDestination();
if( destination.id >0){
cout<<"route contain terminal id ="<<destination.id<<endl;
destination_ = destination;
return true;
}
return false;
}
void Destination::MakeDecisions( Frame* const frame,
ReferenceLineInfo* const reference_line_info){
BuildStopDecision( frame, reference_line_info, &destination_);
}
bool Destination::BuildStopDecision( Frame* const frame,
ReferenceLineInfo* const reference_line_info,
hdmap::Terminal* const destination ){
// check
const auto& reference_line = reference_line_info->reference_line();
if (!WithinBound(0.0, reference_line.Length() +
config_.one_of_config.destination.stop_distance,
destination->start_s)) {
cout<< " destination s =:" << destination->start_s
<< " destination id =:"<< destination->id
<< " reference_line.Length = "<<reference_line.Length()<<endl;
return true;
}
// create virtual stop wall obstacle_id is negative
const double stop_s =
destination->start_s - config_.one_of_config.destination.stop_distance;// 1.0 meter
int32_t virtual_obstacle_id = destination->id * (-1);
auto* obstacle = frame->CreateStopObstacle(
reference_line_info, virtual_obstacle_id, stop_s);
if (!obstacle) {
cout << "Failed to create destination virtual obstacle["
<< virtual_obstacle_id << "]"<<endl;
return false;
}
PathObstacle* stop_wall = reference_line_info->AddObstacle(obstacle);
if (!stop_wall) {
cout<< "Failed to create path_obstacle for " << virtual_obstacle_id<<endl;
return false;
}
// build stop decision
auto stop_point = reference_line.GetReferencePoint(stop_s);
double stop_heading = reference_line.GetReferencePoint(stop_s).theta;
ObjectDecisionType decision_type_;
decision_type_.has_stop = true;
decision_type_.object_tag_case = 7;
auto* stop_decision = &decision_type_.stop;
stop_decision->reason_code = StopReasonCode::STOP_REASON_DESTINATION ;
stop_decision->distance_s = stop_s;
stop_decision->stop_heading = stop_heading;
stop_decision->stop_point.x = stop_point.x;
stop_decision->stop_point.y = stop_point.y;
stop_decision->stop_point.z = 0.0;
auto* path_decision = reference_line_info->path_decision();
if (!path_decision->MergeWithMainStop(decision_type_.stop, stop_wall->Id(),
reference_line_info->reference_line(),
reference_line_info->AdcSlBoundary() ) ) {
cout<< "bus station " << destination->id
<< " is not the closest stop."<<endl;
return false;
}
path_decision->AddLongitudinalDecision(GetName(config_.rule_id),
stop_wall->Id(), decision_type_);
return true;
}
} // namespace planning
| true |
7856d5b9a37538984aa7364d5eed4aec3614acd6 | C++ | AlineTheAlien/Comp345_DnD | /DungeonsAndDragons/DungeonsAndDragons/EditorGUI.h | UTF-8 | 1,415 | 2.890625 | 3 | [] | no_license | //! @file
//! @brief Header file for the EditorGUI class
//! The following class implements the GUI of the Editor to allow user to use the MapEditor and CampaignEditor
//! It allows a user to modify, and create campaigns and maps
//! The user can also load previously created maps and campaigns and save new ones
//! The library used for the GUI is SFML 2.4. It was used because of its efficiency and simplicity
//! The GUI is presented in a window with multiple views. According to the state change, different
//! functions are used to display different views.
#pragma once
#include "Resources.h"
#include "Map.h"
#include "MapEditor.h"
#include "CampaignEditor.h"
#include <vector>
#include <SFML/Graphics.hpp>
#include "GameState.h"
#include "UserDrivenEditor.h"
using namespace std;
class EditorGUI
{
private:
MapEditor *mapEditor;
CampaignEditor *campaignEditor;
sf::RenderWindow *window;
Resources textures;
GameState state;
public:
const static int WINDOW_SCALE = 800;
EditorGUI();
EditorGUI(sf::RenderWindow &window);
void openEditorWindow();
//Map Editor views
void openMapEditorWindow();
void openNewMapWindow();
void openLoadMapWindow();
void openMapView();
//Campaign Editor views
void openCampaignEditorWindow();
void openMapListSelectionWindow();
void openLoadCampaignWindow();
void openCampaignView();
//
void Start();
void Update();
void Display();
~EditorGUI();
};
| true |
a281f3f2f9d573671006cc91687bfadc3af3a5ef | C++ | ale97dro/Grafica | /Esercitazione2-MatematicaPerGrafica/Esercizio4/Esercizio4/Triangolo.cpp | UTF-8 | 1,489 | 2.875 | 3 | [] | no_license | #define GLM_ENABLE_EXPERIMENTAL
#include <iostream>
#include "../glm/glm/glm.hpp"
#include "../glm/glm/gtc/matrix_transform.hpp"
#include "../glm/glm/gtx/string_cast.hpp"
int main()
{
//Vertici
glm::vec4 vertici[3];
vertici[0] = glm::vec4(-15.0f, 0.0f, -50.0f, 1.0f);
vertici[1] = glm::vec4(15.0f, 0.0f, -50.0f, 1.0f);
vertici[2] = glm::vec4(0.0f, 15.0f, -50.0f, 1.0f);
//Funzioni
glm::mat4 t1 = glm::scale(glm::mat4(1.0f), glm::vec3(0.5f));
glm::mat4 t2 = glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f));
glm::mat4 t3 = glm::translate(glm::mat4(1.0f), glm::vec3(10.0f, 0.0f, 0.0f));
//Matrice di proiezione per coordinate clip
glm::mat4 perspective_matrix{ glm::perspective(glm::radians(45.0f), 1.0f, 1.0f, 100.0f) };
//Clip coordinates
glm::mat4 pipeline = perspective_matrix * t3 * t2 * t1;
glm::vec4 pipeline_coordinates[3];
for (int i = 0; i < 3; i++)
{
pipeline_coordinates[i] = pipeline * vertici[i];
std::cout << glm::to_string(pipeline_coordinates[i]) << std::endl;
}
//Normalized device coordinates
std::cout << "----------------------------------------------" << std::endl << std::endl;
glm::vec3 ndc[3];
for (int i = 0; i < 3; i++)
{
ndc[i].x = pipeline_coordinates[i].x / pipeline_coordinates[i].w;
ndc[i].y = pipeline_coordinates[i].y / pipeline_coordinates[i].w;
ndc[i].z = pipeline_coordinates[i].z / pipeline_coordinates[i].w;
std::cout << glm::to_string(ndc[i]) << std::endl;
}
return 0;
} | true |
58976d6410146cdfaa036d7e67af292143867d15 | C++ | liuzhuocpp/algorithm | /lz/kmp.h | UTF-8 | 3,407 | 3.09375 | 3 | [] | no_license | #ifndef KMP_H
#define KMP_H
#include <algorithm>
#include <vector>
namespace lz {
using std::vector;
using std::string;
class Kmp
{
public:
template<typename RandomIterator>
static vector<int> computePrefix(RandomIterator first, RandomIterator end)
{
int n = end - first;
RandomIterator s = first;
vector<int> p(n);
for(int k = p[0] = -1, i = 1; i < n; ++ i)
{
while(k != -1 && !(s[k + 1] == s[i]) ) k = p[k];
if(k != -1) k ++;
else if(s[0] == s[i]) k = 0;
p[i] = k;
}
return std::move(p);
}
template<typename RandomIteratorS, typename RandomIteratorT>
static RandomIteratorT search(RandomIteratorS sfirst, RandomIteratorS send,
RandomIteratorT tfirst, RandomIteratorT tend)
{
vector<int> p = computePrefix(sfirst, send);
return search(p, sfirst, send, tfirst, tend);
}
template<typename RandomIteratorS, typename RandomIteratorT>
static RandomIteratorT search(const vector<int> &p, RandomIteratorS sfirst, RandomIteratorS send,
RandomIteratorT tfirst, RandomIteratorT tend)
{
RandomIteratorS s = sfirst;
RandomIteratorT t = tfirst;
int ns = send - sfirst, nt = tend - tfirst;
for(int i = -1, j = 0; j < nt; ++ j)
{
while(i != -1 && !(s[i + 1] == t[j]) ) i = p[i];
if(i != -1) i ++;
else if(s[0] == t[j]) i = 0;
if(i == ns - 1) return t + j - i;
}
return tend;
}
};
class ExtendKmp
{
template<typename RandomIterator>
struct Node
{
RandomIterator sf, tf;
int sn;
Node(RandomIterator _sf, RandomIterator _tf, int _sn):
sf(_sf),tf(_tf), sn(_sn) {}
decltype(*sf) operator[](int i)
{
if(i < sn) return sf[i];
else return tf[i - sn];
}
};
template<typename RandomIterator>
static vector<int> _computePrefix(RandomIterator s, int n)
{
vector<int> p(n);
if(n == 0) return p;
p[0] = n - 1;
if(n == 1) return p;
int L = 1, R = 0;
for(int i = 1; i < n && s[i] == s[i - 1]; ++ i) R = i;
p[1] = R - L;
for(int i = 2; i < n; ++ i)
{
if(i <= R)
{
if(p[i - L] < R - i) p[i] = p[i - L];
else
{
while(R + 1 < n && s[R + 1 - i] == s[R + 1]) R ++;
L = i;
p[i] = R - i;
}
}
else
{
L = i, R = i - 1;
while(R + 1 < n && s[R + 1 - i] == s[R + 1]) R ++;
p[i] = R - i;
}
}
return std::move(p);
}
public:
template<typename RandomIterator>
static vector<int> computePrefix(RandomIterator first, RandomIterator end)
{
return std::move(_computePrefix(first, end - first));
}
template<typename RandomIterator>
static vector<int> computePrefix(RandomIterator sf, RandomIterator se,
RandomIterator tf, RandomIterator te)
{
int ns = se - sf, nt = te - tf;
Node<RandomIterator> f(sf, tf, ns);
vector<int> p = _computePrefix(f, ns + nt);
for(int i = ns; i < ns + nt; ++ i) p[i - ns] = p[i];
p.resize(nt);
return p;
}
};
} // namespace lz
#endif // KMP_H | true |
3375da878a5e5706ad23c08c23d2659c9bed4e8f | C++ | chrisstopher/A_Star_Algorithm | /Node.cpp | UTF-8 | 713 | 3.125 | 3 | [
"MIT"
] | permissive | #include "Node.h"
Node::Node(Vec2i pos, Score scor, std::shared_ptr<Node> par)
: position(pos), score(scor), parent(par) {
}
Vec2i& Node::getPosition() {
return position;
}
const Vec2i& Node::getPosition() const {
return position;
}
Score& Node::getScore() {
return score;
}
std::shared_ptr<Node>& Node::getParent() {
return parent;
}
void Node::setParent(const std::shared_ptr<Node>& newParent) {
parent = newParent;
}
std::ostream& operator<<(std::ostream& os, const Node& node) {
os << "\n"
<< "Pos: " << node.position
<< " Score: " << node.score
<< " Me: " << &node
<< " Parent: " << node.parent.get()
<< "\n";
return os;
}
| true |
86399f26872e9fb008b03ae193ab9eeaa24fe5b1 | C++ | Pakleni/ImageEditor | /h/InvalidFile.h | UTF-8 | 196 | 2.828125 | 3 | [] | no_license | #pragma once
#include <exception>
class InvalidFile : public std::exception {
public:
const char* what() const throw () {
return "Invalid file data or doesn't exist on specified path";
}
};
| true |
e52706d722b56e5e5f09d8182ab9e4adefaa893a | C++ | 15zhazhahe/LeetCode | /C++/477. Total Hamming Distance.cpp | UTF-8 | 363 | 2.890625 | 3 | [] | no_license | class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int ans = 0;
for(int i=0;i<32;i++)
{
int tmp = 0;
for(auto &num: nums)
{
if((num>>i)%2==1)
tmp++;
}
ans += tmp*(nums.size()-tmp);
}
return ans;
}
}; | true |
5da73a261086905603c089c506dbbcb8a5e96fd5 | C++ | makio93/leetcode-daily-challenge | /2021Oct/Day22/source1a.cpp | UTF-8 | 528 | 2.96875 | 3 | [] | no_license | // 想定解法1 : 出現頻度ごとに文字列構築
// Time:O(N),Space:O(N)
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string frequencySort(string s) {
int n = s.length();
unordered_map<char, int> ccnt;
for (char ci : s) ccnt[ci]++;
vector<string> slst(n+1);
for (auto pi : ccnt) slst[pi.second].append(pi.second, pi.first);
string res;
for (int i=n; i>=0; --i) if (!slst[i].empty()) res.append(slst[i]);
return res;
}
};
| true |
08be36a429c52288c4c1e224c2d69567112c2281 | C++ | FolwaR/Test | /R17Tests/binary.cpp | UTF-8 | 1,940 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct Planet
{
char name[20];
double population;
double g;
};
const char * file = "planety.dat";
inline void eatline() { while (std::cin.get() != '\n') continue; }
int main()
{
Planet pl;
cout << fixed << right;
ifstream fin;
fin.open(file,ios_base::binary | ios_base::in);
if (fin.is_open())
{
cout << "Oto aktualna zawartość pliku " <<file<<": ";
while (fin.read((char *) &pl, sizeof pl))
{
cout << setw(20) << pl.name << ": " << setprecision(0) << setw(12)
<< pl.population << setprecision(0) << setw(6) << pl.g << endl;
}
fin.close();
}
ofstream fout(file, ios_base::binary | ios_base::out | ios_base::app);
if (!fout.is_open())
{
cerr << "Nie mozna otworzyć pliku " << file << endl;
exit(EXIT_FAILURE);
}
cout << "Podaj nazwę planety: (koniec, aby zakończyć)"<< endl;
cin.get(pl.name, 20);
while (pl.name[0] != '\0')
{
cout << "Podaj zaludnienie planety: ";
cin >> pl.population;
cout << "Podaj przyspieszenie grawitacyjne na planecie: ";
cin >> pl.g;
eatline();
fout.write((char *) &pl, sizeof pl);
cout << "Podaj nazwę planety (aby zakończyć, wprowadź pusty wiersz):\n";
cin.get(pl.name, 20);
}
fout.close();
fin.clear();
fin.open(file, ios_base::in | ios_base::binary);
if (fin.is_open())
{
cout << "Oto nowa zawartość pliku " << file << ":\n";
while (fin.read((char *) &pl, sizeof pl))
{
cout << setw(20) << pl.name << ": " << setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << endl;
}
fin.close();
}
cout << "Koniec.\n";
return 0;
}
| true |
dcd1e7979054fc49ab339f483babf1e6bcab4e0a | C++ | kuningfellow/Kuburan-CP | /yellowfellow-ac/CodeChef/CDQU3/10788117_AC_0ms_15257kB.cpp | UTF-8 | 873 | 2.703125 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while (t>0)
{
long long int n;
scanf("%lld",&n);
int i;
int num[32];
for (i=0;i<32;i++)num[i]=0;
int index=0;
int dead,ran=0;
while(n>1)
{
ran=1;
dead=0;
for (i=9;i>1;i--)
{
if (n%i==0)
{
n/=i;
num[index]=i;
index++;
break;
}
else dead++;
}
if (dead==8)
{
break;
}
}
if (n==1&&ran==0)printf ("11\n");
else if (dead==8)printf ("-1\n");
else if (num[1]==0)printf ("1%i\n",num[0]);
else
{
for (i=index-1;i>=0;i--)
{
printf ("%i",num[i]);
}
printf ("\n");
}
t--;
}
return 0;
}
| true |
0fbead1753d5a7d20b02b4b215c97236c616b68d | C++ | yhondri/EDA | /2_3/aer_316/aer_316/main.cpp | UTF-8 | 1,115 | 2.640625 | 3 | [] | no_license | //
// main.cpp
// aer_316
//
// Created by Yhondri Josué Acosta Novas on 06/12/2018.
// Copyright © 2018 Yhondri. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void leerDatos(vector<int> &datos, int numDatos);
void resolverCaso(vector<int> datos, int numDatos);
int main(int argc, const char * argv[]) {
// ajustes para que cin extraiga directamente de un fichero
#ifndef DOMJUDGE
ifstream in("/Users/yhondri/Documents/universidad/eda/eda/2_3/juez/aer_316/aer_316/casos");
auto cinbuf = cin.rdbuf(in.rdbuf());
#endif
int numCasos, numDatos;
cin >> numCasos;
while (numCasos > 0) {
cin >> numDatos;
vector<int> datos(numDatos);
leerDatos(datos, numDatos);
numCasos--;
}
#ifndef DOMJUDGE
cin.rdbuf(cinbuf);
// system("PAUSE");
#endif
return 0;
}
void leerDatos(vector<int> &datos, int numDatos) {
int nuevoDato;
for (int i = 0; i < numDatos; i++) {
cin >> nuevoDato;
datos[i] = nuevoDato;
}
}
void resolverCaso(vector<int> datos, int numDatos) {
}
| true |
690694a42660ddca4d4734ba0e380f84c7b460ab | C++ | z974890869/hello-world | /ComputerRoom/Identity.h | GB18030 | 610 | 2.625 | 3 | [] | no_license | #pragma once
#include<string>
using std::string;
extern string computer_file;
extern string order_file;
extern string student_file;
extern string teacher_file;
extern string admin_file;
enum class input{ exit = 0,stu = 1,tea = 2,admin =3};
std::istream& operator>>(std::istream& is, input& item);
class Identity
{
public:
virtual ~Identity() = default;//̬
// openMenu() virtual
// =0:pure virtual ܶ Indentity k;
virtual void openMenu() = 0;
//鿴ԤԼ
void showAllOrder();
protected:
string name;
string pswd;
}; | true |
af6827e82034cbf6dfb13c14402d0651d10479bb | C++ | haegar80/Images2WavefrontObj | /Images2WavefrontObj/WavefrontObject/SubMesh.h | UTF-8 | 852 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Material.h"
#include <vector>
struct ObjFaceIndices
{
int VertexIndex;
int NormalIndex;
int TextureIndex;
};
struct ObjFace
{
std::vector<ObjFaceIndices> Indices;
};
class SubMesh
{
public:
SubMesh(Material* p_Material);
~SubMesh() = default;
void AddNewFace();
void AddExistingFace(ObjFace p_existingFace);
void AddFaceIndices(int p_vertexIndex, int p_textureIndex = 0, int p_normalIndex = 0);
void UpdateExistingFace(int p_faceVectorIndex, ObjFace p_existingFace);
ObjFace DeleteFace(int p_faceVectorIndex);
Material* GetMaterial() const {
return m_material;
}
std::vector<ObjFace> GetFaces() const {
return m_faces;
}
private:
Material* m_material{ nullptr };
std::vector<ObjFace> m_faces;
void AddTriangledFace(ObjFace p_originalFace);
};
| true |
c5ff49a1474f08b89af71148e4c7ff6267ff196b | C++ | snumrl/DistributedDeepMimic | /bipedenv/cpp/Render/Camera3D.cpp | UTF-8 | 5,169 | 2.859375 | 3 | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | #include<cmath>
#include<iostream>
#include "Render/Camera3D.h"
// Camera3D
const int EVENT_ROTATION = 1;
const int EVENT_TRANSLATION = 2;
const int EVENT_ZOOM = 4;
const int EVENT_DOLY = 8;
const double PI = acos(-1);
Camera3D::Camera3D(Eigen::Vector3d origin, Eigen::Vector3d camera, Eigen::Vector3d up, double FOV) :
origin(origin), camera(camera), up(up), FOV(FOV){
status = Ox = Oy = 0;
Eigen::Vector3d cam = (camera - origin).normalized();
up = (up - cam.dot(up) * cam).normalized();
rot = Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d(1, 0, 0), cam);
Eigen::Vector3d tmp = rot._transformVector(Eigen::Vector3d(0, 1, 0));
rot = Eigen::AngleAxisd(atan2(tmp.cross(up).dot(cam), tmp.dot(up)), cam) * rot;
printf("DOLY : x + drag (up/down)\n");
printf("ZOOM : z + drag (up/down)\n");
}
void Camera3D::display()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(FOV, (GLfloat)width / (GLfloat)height, .1f, 1e3);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(camera[0], camera[1], camera[2],
origin[0], origin[1], origin[2],
up[0], up[1], up[2]);
if(status){
glPushMatrix();
glTranslated(origin[0], origin[1], origin[2]);
glBegin(GL_LINES);
glColor3f(1.0, 0.0, 0.0); glVertex3d(0.0, 0.0, 0.0); glVertex3d(1.0, 0.0, 0.0);
glColor3f(0.0, 1.0, 0.0); glVertex3d(0.0, 0.0, 0.0); glVertex3d(0.0, 1.0, 0.0);
glColor3f(0.0, 0.0, 1.0); glVertex3d(0.0, 0.0, 0.0); glVertex3d(0.0, 0.0, 1.0);
glEnd();
glPopMatrix();
}
}
void Camera3D::keyboard(unsigned char key, int x, int y){
switch(key){
case 'x': addFlag(status, EVENT_DOLY); break;
case 'z': addFlag(status, EVENT_ZOOM); break;
}
}
void Camera3D::keyboardUp(unsigned char key, int x, int y){
switch(key){
case 'x': removeFlag(status, EVENT_DOLY); break;
case 'z': removeFlag(status, EVENT_ZOOM); break;
}
}
void Camera3D::special(int key, int x, int y){
}
void Camera3D::specialUp(int key, int x, int y){
}
void Camera3D::mouse(int button, int state, int x, int y){
int flag = 0;
switch(button){
case GLUT_LEFT_BUTTON: flag = EVENT_ROTATION; break;
case GLUT_RIGHT_BUTTON: flag = EVENT_TRANSLATION; break;
default: return;
}
switch(state){
case GLUT_DOWN: addFlag(status, flag); Ox = x; Oy = y; break;
case GLUT_UP: removeFlag(status, flag); break;
}
}
void Camera3D::zoom(int dy){
FOV += 0.05 * dy;
if( FOV < 10 ) FOV = 10;
if( FOV > 130 ) FOV = 130;
}
void Camera3D::doly(int dy){
camera += (camera - origin) * (0.01f * dy);
}
void Camera3D::translate(int dx, int dy){
Eigen::Vector3d dv = (origin - camera).normalized() * (dy * FOV / 1000) +
up.cross(origin - camera).normalized() * (dx * FOV / 1000);
dv = Eigen::Vector3d(dv[0], 0, dv[2]); //.normalized() * t;
origin += dv; camera += dv;
}
void Camera3D::rotate(Eigen::Quaterniond rotation){
up = rotation._transformVector(up);
camera = rotation._transformVector(camera - origin) + origin;
rot = rotation * rot;
}
void Camera3D::rotate(int Ox, int Oy, int x, int y){
const double R = 400.0;
auto proj = [](Eigen::Vector3d vec){
if(vec.norm() >= 1) vec.normalize();
else vec[0] = -sqrt(1 - vec.dot(vec));
return vec;
};
Eigen::Vector3d start = proj(Eigen::Vector3d(0, Oy/R, Ox/R));
Eigen::Vector3d end = proj(Eigen::Vector3d(0, y/R, x/R));
start = rot._transformVector(start);
end = rot._transformVector(end);
Eigen::Quaterniond move = Eigen::Quaterniond::FromTwoVectors(end, start);
rotate(move * move);
}
void Camera3D::rotate(Eigen::Vector2d joystickAxis){
rotate(Eigen::Quaterniond(
Eigen::AngleAxisd(joystickAxis[0] * 0.1, Eigen::Vector3d(0, 1, 0))));
Eigen::Vector3d dir = (origin-camera).normalized();
Eigen::Vector3d left = dir.cross(up);
double angle = atan2(dir.cross(Eigen::Vector3d(0, 1, 0)).dot(left),
dir.dot(Eigen::Vector3d(0, 1, 0)));
double dx = -joystickAxis[1] * 0.1;
if(angle + dx > PI - 0.1) dx = PI - 0.1 - angle;
if(angle + dx < 0.1) dx = 0.1 - angle;
rotate(Eigen::Quaterniond(
Eigen::AngleAxisd(-dx, left)));
}
void Camera3D::motion(int x, int y){
if (isFlagSet(status, EVENT_ZOOM)) zoom(y-Oy);
else if(isFlagSet(status, EVENT_DOLY)) doly(y-Oy);
else if(isFlagSet(status, EVENT_TRANSLATION)) translate(x-Ox, y-Oy);
else if(isFlagSet(status, EVENT_ROTATION))
rotate(Ox-width/2, Oy-height/2, x-width/2, y-height/2);
Ox = x; Oy = y;
}
void Camera3D::mouse_button_callback(GLFWwindow* window, int button, int action, int mode){
int flag = 0;
double x, y; glfwGetCursorPos(window, &x, &y);
switch(button){
case GLFW_MOUSE_BUTTON_LEFT: flag = EVENT_ROTATION; break;
case GLFW_MOUSE_BUTTON_RIGHT: flag = EVENT_TRANSLATION; break;
default: return;
}
switch(action){
case GLFW_PRESS: addFlag(status, flag); Ox = x; Oy = y; break;
case GLFW_RELEASE: removeFlag(status, flag); break;
}
}
void Camera3D::cursor_position_callback(GLFWwindow* window, double xpos, double ypos){
motion(xpos, ypos);
}
void Camera3D::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){
switch(action){
case GLFW_PRESS: switch(key){
case GLFW_KEY_X: flipFlag(status, EVENT_DOLY); break;
case GLFW_KEY_Z: flipFlag(status, EVENT_ZOOM); break;
}
}
} | true |
e127c5008ea680d4f67eef7662a58eabac5ffc39 | C++ | dmilos/math | /src/math/geometry/projective/camera/va2d.hpp | UTF-8 | 984 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef math_geometry_projective_camera_va2d
#define math_geometry_projective_camera_va2d
// ::math::geometry::projective::camera::va2d( h_alpha, aspect )
namespace math
{
namespace geometry
{
namespace projective
{
namespace camera
{
template < typename scalar_name >
scalar_name
va2d
(
scalar_name const& vertical_alpha //!< vertical angle of view
,scalar_name const& aspect //!< Aspect ration width::height .e.g. 16:9
)
{
scalar_name vertical_scale = scalar_name(2) * tan( vertical_alpha / scalar_name(2) );
scalar_name horizontal_scale = vertical_scale * aspect;
scalar_name diagonal = sqrt( horizontal_scale* horizontal_scale + vertical_scale * vertical_scale );
return scalar_name(2) * atan( diagonal / scalar_name(2) );
}
}
}
}
}
#endif
| true |
ac8fa033bc0293245bd79d8a6453d409835ac308 | C++ | AliEissa2077/speedopoint | /SpeedoPoint/airport.h | UTF-8 | 328 | 2.546875 | 3 | [] | no_license | #pragma once
#ifndef AIRPORT_H
#define AIRPORT_H
#include "country.h"
class airport {
private:
std::string name;
country ctry;
int cityIndex;
public:
airport();
airport(std::string airport_name, country count, int index);
country getCountry();
std::string getName();
int getIndex();
};
#endif AIRPORT_H
| true |
93900ddf8be5f1a53cd4566bdbbb826f4978e5ce | C++ | github188/SPlayer | /SisecPlayer/VCA/VideoSource/YUVRec.h | UTF-8 | 1,291 | 2.78125 | 3 | [] | no_license | #ifndef __YUVREC_H__
#define __YUVREC_H__
class CYUVRec
{
public:
typedef enum{
YUV_NONE,
YUY2,
UYVY,
YV12,
GRAY,
}YUVTYPE;
typedef struct
{
DWORD type;
DWORD width;
DWORD height;
}YUVHEADER;
public:
CYUVRec(void);
~CYUVRec(void);
BOOL Open(LPCTSTR lpFilename, BOOL bWrite, DWORD type = 0, DWORD width = 0, DWORD height = 0);
void Close();
BOOL Write(DWORD index, BYTE* buf, DWORD size);
BOOL Read(DWORD index, BYTE* buf, DWORD size);
YUVHEADER* GetHeader(){return &m_YUVHeader;}
UINT GetTotalFrames(){return (m_hFile)?m_TotalFrames:0;}
private:
FILE* m_hFile;
YUVHEADER m_YUVHeader;
BOOL m_bWritten;
UINT m_TotalFrames;
UINT GetTotalFrames_i();
};
inline UINT GetFrameSize(CYUVRec::YUVHEADER &h)
{
if(CYUVRec::GRAY == h.type){
return (h.width*h.height);
}else if(CYUVRec::YV12 == h.type){
return (h.width*h.height*3)/2;
}else if(CYUVRec::YUY2 == h.type || CYUVRec::UYVY == h.type){
return (h.width*h.height*2);
}
return 0;
}
inline UINT GetFrameSize(CYUVRec::YUVHEADER *h)
{
if(CYUVRec::GRAY == h->type){
return (h->width*h->height);
}else if(CYUVRec::YV12 == h->type){
return (h->width*h->height*3)/2;
}else if(CYUVRec::YUY2 == h->type || CYUVRec::UYVY == h->type){
return (h->width*h->height*2);
}
return 0;
}
#endif | true |
260bbe3e1e538d791f3df6bfcf07cb967f0cbe53 | C++ | chanchoi829/simulation | /include/Torpedo_boat.h | UTF-8 | 1,103 | 3.03125 | 3 | [] | no_license | /*
A Torpedo_boat is similar to a Cruiser, but when commanded to attack, a Torpedo_boat
closes with its target by changing its course on every update. When it is close enough,
it fires at the target and continues until the target is sunk like Cruiser. However,
if a Torpedo_boat is fired upon, instead of counter-attacking like Cruiser, it runs away
to an Island of refuge.
Initial values:
fuel capacity and initial amount: 800, maximum speed 12., fuel consumption 5.tons/nm,
resistance 9, firepower 3, maximum attacking range 5
*/
#ifndef TORPEDO_BOAT_H
#define TORPEDO_BOAT_H
#include "Warship.h"
struct Point;
class Torpedo_boat : public Warship
{
public:
Torpedo_boat(const std::string& name_, Point position_);
// When target is out of range this Torpedo_boat can move,
// set the target's loation as the destination.
void update() override;
// Describe this Torpedo_boat's state
void describe() const override;
// Perform Torpedo_boat specific behavior for receive_hit
void receive_hit(int hit_force, std::shared_ptr<Ship> attacker_ptr) override;
};
#endif | true |
35c0e9960f5a9056ac1ba27ebe8e6b1545651e0d | C++ | abhilasha007/Dynamic-Programming | /Trees/Diameter.cpp | UTF-8 | 1,120 | 3.359375 | 3 | [] | no_license | // O(n) TIME
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int solve(TreeNode* root, int &res) {
//Base
if(root==NULL) return 0;
// Hypothesis
int lh = solve(root->left, res);
int rh = solve(root->right, res);
//Induction
int temp = 1 + max(lh, rh); // when the root is not including itself as turning root of diameter
int ans = max(temp, lh+rh+1); // when root is considering itself to be turning part of diameter
res = max(res, ans);
return temp;
}
int diameterOfBinaryTree(TreeNode* root) {
int res = INT_MIN; //this will have no. of nodes in longest path after calling solve
int t = solve(root, res);
return res-1; // longest path length aka diameter
}
};
| true |
0bd271ef41531a03d4daecf1e95373d0c2585e53 | C++ | nijiahe/code | /code/windows/c_c++_code/c++ primer/10_3_4bind参数绑定.cpp | GB18030 | 1,851 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <string>
#include <vector>
bool isBiggerOrEqual(const std::string &s, std::string::size_type sz)
{
return s.size() >= sz;
}
int mainmain10_3_4()
{
/*
龰:еĿɵòIJб㷨ҪIJƥ,:
1.㷨IJlambdaʽ,lambdaʽֵ,Ȼ亯ڵдõĿɵò
2.ͨbindֵ㷨,bindͨռλһֻռλռIJλõº,βδֵ
std::cout << typeid(isB).name() << std::endl,std::bindصһܸӵĶ
std::bindԸ,ڵ˳,:
auto g = bind(f,a,b,_2,c,_1);//fһ5ĺ
g(_1,_2)ӦӳΪf(a,b,_2,c,_1);
bind´,ostream,ܱ,ʱͨref(),ref()funcitonalͷļ
*/
//ϰ
std::vector<std::string> v1{ "the","quick","red","fox","jumps","over","the","slow","red","turtle" };
int sz = 4;
auto isB = std::bind(isBiggerOrEqual, std::placeholders::_1, sz);
int count = std::count_if(v1.begin(), v1.end(), isB);
std::cout << "There is " << count << " numbers of words compatible with the condition" << std::endl;
std::string str("123456");
bind(isBiggerOrEqual, std::placeholders::_1, str.size());
std::vector<std::string>::iterator it = std::find_if(v1.begin(), v1.end(), bind(isBiggerOrEqual, std::placeholders::_1, str.size()));
std::cout << "The first words compatible with the condition is '" << *it << "'" <<std::endl;
system("pause");
return 0;
} | true |
d420138071a965f9ec418787ae9341790d4589ac | C++ | intrinsicD/basics_lab | /libs/bcg_library/math/vector/bcg_vector.h | UTF-8 | 1,693 | 2.5625 | 3 | [] | no_license | //
// Created by alex on 23.11.20.
//
#ifndef BCG_GRAPHICS_BCG_VECTOR_H
#define BCG_GRAPHICS_BCG_VECTOR_H
#include "math/matrix/bcg_matrix.h"
#include "Eigen/Geometry"
namespace bcg{
template<typename T, int N>
using Vector = Matrix<T, N, 1>;
template<int N>
using VectorS = Vector<bcg_scalar_t, N>;
template<int N>
using VectorI = Vector<bcg_index_t , N>;
// Zero vector constants.
template<int N>
[[maybe_unused]] inline const auto zeroi = VectorI<N>::Zero();
[[maybe_unused]] inline const auto zero2i = VectorI<2>::Zero();
[[maybe_unused]] inline const auto zero3i = VectorI<3>::Zero();
[[maybe_unused]] inline const auto zero4i = VectorI<4>::Zero();
// One vector constants.
template<int N>
[[maybe_unused]] inline const auto onei = VectorI<N>::Ones();
[[maybe_unused]] inline const auto one2i = VectorI<2>::Ones();
[[maybe_unused]] inline const auto one3i = VectorI<3>::Ones();
[[maybe_unused]] inline const auto one4i = VectorI<4>::Ones();
// Zero vector constants.
template<int N>
[[maybe_unused]] inline const auto zeros = VectorS<N>::Zero();
[[maybe_unused]] inline const auto zero2s = VectorS<2>::Zero();
[[maybe_unused]] inline const auto zero3s = VectorS<3>::Zero();
[[maybe_unused]] inline const auto zero4s = VectorS<4>::Zero();
// One vector constants.
template<int N>
[[maybe_unused]] inline const auto ones = VectorS<N>::Ones();
[[maybe_unused]] inline const auto one2s = VectorS<2>::Ones();
[[maybe_unused]] inline const auto one3s = VectorS<3>::Ones();
[[maybe_unused]] inline const auto one4s = VectorS<4>::Ones();
template<int N>
inline auto unit(bcg_index_t i) {
VectorS<N> u(zeros<N>);
u[i] = 1;
return u;
}
}
#endif //BCG_GRAPHICS_BCG_VECTOR_H
| true |
084ee89f16dba3722db82c56197ec15bb2eb83af | C++ | Chung-god/DailyCoding | /Question_from1098/Question_from1098/Question_from1098.cpp | UTF-8 | 1,647 | 2.796875 | 3 | [] | no_license | // Question_from1098.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include <stdio.h>
int main()
{
int board[100][100] = { 0, };
int w, h, n;
int l, d, x, y;
int i,j;
scanf_s("%d%d%d", &w, &h, &n);
for (i = 0; i < n;i++) {
scanf_s("%d %d %d %d", &l, &d, &x, &y);
if (d == 0) {
while (l > 0) {
board[x][y++] = 1;
--l;
}
}
else {
while (l > 0) {
board[x++][y] = 1;
--l;
}
}
}
for (i = 1;i <= w;i++) {
for (j = 1; j <= h; j++)
printf("%d ", board[i][j]);
printf("\n");
}
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| true |
dc7dfbbbd18839b9750109e1489d9a4108ca9766 | C++ | RyanCPeters/Winter_2017 | /peer_code/NyeM/ass4/CSS343-Assignment4/stored_data/movie/movie.h | UTF-8 | 4,268 | 3.046875 | 3 | [] | no_license | // -------------------------------------- movie.h ----------------------------
//
// Programmer Name Course Section Number: Team 7 (Daniel Bragaru - CSS 343 B)
// Creation Date: 02/28/18
// Date of Last Modification: 02/28/18
// ---------------------------------------------------------------------------
// Purpose - This is the design for the Movie class, which is used as the
// - stored data within the Manager class.
// - its essential properties are the attributes and counters
// - and the compare methods
// ---------------------------------------------------------------------------
// Notes on specifications, special algorithms, and assumptions.
// ---------------------------------------------------------------------------
#ifndef MOVIE_H_
#define MOVIE_H_
#include <string>
#include "media.h"
//#include "movieattribute.h"
#include <vector>
#include "stored_data/storeddata.h"
enum class MType {COMEDY = 0, DRAMA = 1, CLASSICAL = 2, DEFAULT = -1};
class Movie : public StoredData
{
friend std::ostream& operator<<(std::ostream& , const Movie&);
public:
/*
* Name:
(no-arg) constructor for Movie
* Description:
Will initialize a Movie object
*/
explicit Movie(char movieType);
/**
*
* @param genre
* @param init_stock
* @param title mebbe
* @param director
* @param releaseY
*/
Movie(std::string genre, int init_stock, std::string title,
std::string director, std::string releaseY, std::string actor = "");
/*
* Name:
Destructor
* Description:
Will properly delete a Movie object and its children
*/
~Movie() override;
std::string getType() const;
int getStock() const;
Media getMedia() const;
void setMedia(Media media);
bool setStock(int);
//
// bool setReleaseYear(std::string);
/*
* Name:
hash()
* Description:
Will calculate a hash based on the Movie instance and
return an index at which to insert into the Movie list.
The hash will be an open hash, so collision detection is
not necessary. It will be overridden by child classes
* Return:
The index at which to insert into the Movie list
*/
//virtual int hash() const override = 0;
/*
* Name:
getAttributes
* Description:
Gets a copy of the Movie Attributes
* Return:
A vector of MovieAttributes
*/
//std::vector<MovieAttribute *> getAttributes() const;
// /*
// * Name:
// parse
// * Description:
// Parses the input string and populates the current movie instance
// * Parameter:
// A string that will be parsed into the Movie instance (if successfull)
// * Return:
// Whether or not the string was actually parsed.
// */
// virtual bool parse(std::string, bool hasStock);
// //TODO: Document
// virtual Movie* copy() const;
//TODO: Document
virtual std::string toString() const;
/*
* Name:
operator == overload
* Description:
Checks whether or not the Movies are equal
* Parameter:
Another movie
* Return:
A boolean based whether or not the the two Movies are equal
*/
virtual bool operator==(const Movie&) const;
/*
* Name:
operator != overload
* Description:
Checks whether or not the Movies are not equal
* Parameter:
Another movie
* Return:
A boolean based whether or not the two Movies are equal
*/
virtual bool operator!=(const Movie&) const;
private:
const std::string movieType; // the type will distinguish the movies
// on highest level
Media mediaType; // the media type
int stock;
const std::string director;
const std::string title;
const std::string date_released;
//std::vector<MovieAttribute *> movieAttributes; //A vector of MovieAttributes
protected:
struct Comparable {
MType genre;
std::string first;
std::string second;
Comparable():genre(MType::DEFAULT),
first(std::string()),
second(std::string()){};
Comparable(MType gnr, std::string frst, std::string sec)
: genre(gnr), first(frst), second(sec){}
}comp;
/*
* Name:
addAttribute
* Description:
Adds the given Movie Attribute to the Movie Object
(If the Movie allows for that Movie Attribute)
* Parameter:
The MovieAttribute to add to the vector
* Return:
Whether or not the Movie Attribute was added
*/
//virtual bool addAttribute(MovieAttribute*) = 0;
};
#endif /* MOVIE_H_ */
| true |
7b970df6bc8456a6d05434ad506b6e83ea0b2f67 | C++ | mako2501/opencv_maze | /main.cpp | UTF-8 | 8,059 | 2.84375 | 3 | [] | no_license | #include <opencv.hpp>
#include <highgui/highgui_c.h>
#include <iostream>
#include <cv.h>
/*
NAI - PJATK
OpenCV Projekt - Labirynt
Program odczytuje z kartki labirynt, interpretuje odpowiednio pola, znajduje start i wyszukuje wyjście.
#2013
*/
using namespace std;
using namespace cv;
// kierunki ruchu Tezeusza
enum direction { North, East, South, West };
// zwraca prostokat->kontur najwiekszego bloba z mattresha -> parametr
Rect biggestContour(Mat thr){
int largest_area=0;
int largest_contour_index=0;
Rect bounding_rect;
vector<vector<Point>> contours; // wektor do przechowania konturow http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours
vector<Vec4i> hierarchy;
findContours( thr, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // szuka wszystkich konturow w obrazie
for( int i = 0; i< contours.size(); i++ ) // po kazdym
{
double a=contourArea( contours[i],false); // oblicza powieszchniê obszaru
if(a>largest_area){
largest_area=a;
largest_contour_index=i; //zachowaj index jesli jest to wiekszy obszar
bounding_rect=boundingRect(contours[i]); // zbuduj bounding rec
}
}
return bounding_rect;
}
// rysuje zielon¹ liniê w macierzy pomiedzy dwoma punktami
void drawLine( Mat img, Point start, Point end )
{
int thickness = 2;
int lineType = 8;
line( img,
start,
end,
Scalar( 0, 255, 0 ),
thickness,
lineType );
}
//sprawdza czy punkt jest poza prost. - labiryntem
bool isOutside(Point p,Rect r){
cout<<"isOutside point=["<<p<<"], is "<<(!r.contains(p))<<"\n";
return (!r.contains(p));
}
// sprawdza czy w zadanym kierunku po kroku jest sciana
bool wallExist(Mat m, Point t, int step, direction d){
Point p = t;
switch(d){
case North: p.y-=step;break;
case South: p.y+=step;break;
case West: p.x-=step;break;
case East: p.x+=step;break;
}
//cout<<"wallExist checkDir=["<<d<<"], point=["<<p<<"], isExist "<<(m.at<uchar>(p.y,p.x) == 0)<<"\n";
// uwaga na punkt poza macierz¹
if(p.x>=0 && p.y>=0 && p.x<=m.cols && p.y<=m.rows)
{
Point3_<uchar>* c = m.ptr<Point3_<uchar> >(p.y,p.x);
// if(m.at<uchar>(p.y,p.x) == 0) return true;
if(c->x == 0)return true;
else
return false;
}
return false;
}
// zwraca punkt nastepnego prawidlowego kroku
Point addPoint(Mat m, Point t, int step,direction d){
Point p = t;
switch(d){
case North: p.y-=step;break;
case South: p.y+=step;break;
case West: p.x-=step;break;
case East: p.x+=step;break;
}
//drawLine(m,p,p);
cout<<"addPoint point=["<<p<<"]\n";
return p;
}
//wypala miejsce - tu by³em
void mark(Mat m, Point p,int step)
{
cout<<"mark point=["<<p<<"]\n";
rectangle(m,Point(p.x-step/2+2,p.y-step/2+2),Point(p.x+step/2-2, p.y+step/2-2),Scalar(125,125,125),CV_FILLED );
}
// odznacza miejce tu by³em
void unMark(Mat m, Point p,int step)
{
cout<<"unMark point=["<<p<<"]\n";
rectangle(m,Point(p.x-step/2+2,p.y-step/2+2),Point(p.x+step/2-2, p.y+step/2-2),Scalar(255,255,255),CV_FILLED );
}
// sprawdza czy byl
bool isMarked(Mat m, Point p){
uchar b = m.data[m.channels()*(m.cols*p.y + p.x) + 0];
cout<<"isMarked ["<<(b == 125)<<"]\n";
if(b == 125) return true;
else
return false;
}
// sprawdza czy bedac na danym polu jest poza labiryntem:
// tak - koniec zwraca true
// nie sprawdza czy mozna sie ruszyc w jakims kierunku
// nie - koniec false, tak - wywolaj rekurencyjnie samego siebie
bool solveLab(Mat m, Point p, int step,Rect r,int ix,Point* exitPoints)
{
cout<<"\nsolveLab point=["<<p<<"]\n";
if (isOutside(p,r)) return true;//jezeli jestem poza labiryntem to koniec
if(isMarked(m,p)) return false; //jezeli tu by³em koniec
mark(m,p,step); // oznacz pole na ktorym stoisz
exitPoints[ix]=p; //zapamietuje pozycje
ix++;
for (int i=0;i<4;i++){
direction dir = direction(i);
if(!wallExist(m,p,step,dir))
{
cout << "goto "<<dir<<endl;
if(solveLab(m,addPoint(m,p,step,dir),step,r,ix,exitPoints))
{
return true;
}
}
}
unMark(m,p,step); // tu nie ma wyjscia, odznacz, skasuj punkt zwroc false
exitPoints[ix]=Point(-1,-1);
return false;
}
int main( int argc, char** argv ) {
double w,h,fps;
bool continueCapture = true;
cv::namedWindow( "src", CV_WINDOW_AUTOSIZE );
cv::namedWindow( "Theseus", CV_WINDOW_AUTOSIZE );
cv::namedWindow( "labMat", CV_WINDOW_AUTOSIZE );
cv::VideoCapture cap(0);
if ( !cap.isOpened() ) return -1;
w = cap.get( CV_CAP_PROP_FRAME_WIDTH ); //get the width of frames of the video
h = cap.get( CV_CAP_PROP_FRAME_HEIGHT ); //get the height of frames of the video
fps = cap.get( CV_CAP_PROP_FPS ); // ile mamy klatek na sekunde?
bool tesFree = false; //jesli Tezeusz bedzie wolny to true
Rect tesRect, labRect;
Mat src;
Mat thr(src.rows,src.cols,CV_8UC1); // do okrelenia biggestBloba labiryntu
Mat teseusMat(src.rows,src.cols,CV_8UC1); // w niej szukam Tezeusza - czerwony
Mat labiryntMat(src.rows,src.cols,CV_8UC1); // w nim jest poszukiwane wyjcie
while( true ) {
if ( cap.read( src ) ) {
//src = imread("lab3.jpg",CV_LOAD_IMAGE_COLOR); // wczytywanie z obrazka
flip(src,src,1);
// szukanie tezeusza - po kolorze
blur(src,teseusMat,Size(2,2));
cvtColor(teseusMat,teseusMat,CV_BGR2HSV);
//inRange(teseusMat,Scalar(100, 50, 50),Scalar(250, 240, 240),teseusMat); //120 179
inRange(teseusMat,Scalar(150, 50, 50),Scalar(200, 240, 240),teseusMat); //- dobry dla druknietego labiryntu wiat³o ja¿eniowka
// inRange(teseusMat,Scalar(0, 135, 135),Scalar(30, 255, 400),dstA);
//inRange(teseusMat, Scalar(330, 135, 135), Scalar(360, 255, 400), dstB);
//bitwise_or(dstA,dstB,teseusMat);
tesRect = biggestContour(teseusMat); // prost. dooko³a Tezeusza
// przygotowanie obrazu labiryntu
blur(src, labiryntMat, Size(2,2));
cvtColor(labiryntMat,labiryntMat,CV_RGB2GRAY ); //konw. na szary
threshold(labiryntMat, labiryntMat,100, 255,THRESH_BINARY); //100
// prost dooko³a labiryntu
cvtColor(src,thr,CV_BGR2GRAY);
threshold(thr, thr,25, 255,THRESH_BINARY);
bitwise_not(thr, thr); // odwroc kolory
labRect = biggestContour(thr);
rectangle(src, labRect, Scalar(0,255,0),1, 8,0); //rysuje dooko³a labiryntu i teszeusza prost
rectangle(src, tesRect, Scalar(0,255,0),1, 8,0);
int step = tesRect.width-1; // d³ugoæ kroku Tezeusza
Point tes = Point(tesRect.x+tesRect.width/2,tesRect.y+tesRect.height/2); // punkt wyjciowy
int ix=0; // do tablicy wsp. kroków
// zacznij szukanie tylko jeli punkt jest wewnatrz labiryntu (kamerka czasem lapie rozne rzeczy)
if(labRect.contains(tesRect.tl()) && labRect.contains(tesRect.br())){
// wielkosc tablicy nie jest wieksza niz ilosc wszystkich pol na mapie
int n = (labRect.width/tesRect.width)*(labRect.height/tesRect.height);
Point* exitPoints=new Point[n]; // tablica wspolrzednych krokow
for(int i=0;i<n;i++)exitPoints[i]=Point(-1,-1);
tesFree=solveLab(labiryntMat,tes,step,labRect,ix,exitPoints);
//wyp. wspolrzedne
for(int i=0;i<n;i++){
cout<<exitPoints[i];
if(exitPoints[i+1].x!=-1 )
drawLine(src,exitPoints[i],exitPoints[i+1]);
}
if(tesFree){
imwrite("tesIsFree.jpg",src);
imwrite("tesIsFreeLab.jpg",labiryntMat);
}
delete [] exitPoints;
}
imshow( "src", src );
imshow( "labMat", labiryntMat );
imshow( "Theseus", teseusMat );
} else break;
if( waitKey( 30 ) == 27 || tesFree) break; //----|---------------------
//if( waitKey( 30 ) == 27) break;
}
if(tesFree){
teseusMat=imread("tesIsFree.jpg",CV_LOAD_IMAGE_COLOR);
imshow( "Theseus", teseusMat );
waitKey();
}
return 0;
}
| true |
22ac889ac828003f3d53cb231ef221c7e112a443 | C++ | AMROZIA-MAZHAR/string_task | /string_task5.cpp | UTF-8 | 4,110 | 3.421875 | 3 | [] | no_license | /*Write a program that can be used to train the user to use less gender baised language by
suggesting alternative versions of sentences given by the user. The program will ask for a
sentence, read the sentence into a string variable, and replace all occurrences of masculine
pronouns with gender-neutral pronouns. For example, it will replace "he" with "she or he".
Thus, the input sentence.
See an adviser, talk to him, and listen to him.
should produce the following suggested changed version of the sentence:
See an adviser, talk to her or him, and listen to her or him.
Be sure to preserve uppercase letters for the first word of the sentence. The pronoun "his"
can be replaced by "her (s)"; your program need not decide between "her" and "hers".
Allow the user to repeat this for more sentences until the user says she or he is done.
This will be a long program that requires a good deal of patience. Your program should not
replace the string "he" when it occurs inside another word, such as "here". A word is any
string consisting of the letters of the alphabet and delimited at each end by a blank, the end
of the line, or any other character that is not a letter. Allow your sentences to be up to 100
characters long.*/
#include<iostream>
#include<string>
using namespace std;
string get_input();
string conversion(string);
string get_input(){
string my_string;
cout<<"Enter the string you want to replace "<<endl;
getline(cin,my_string);
return my_string;
}
string conversion(string my_string){
string cmp;
string new_string;
for(int i=0;i<=my_string.length();i++){
if(my_string[i] ==' ' || int(my_string[i])==0)
{
if(cmp=="he"||cmp=="she"||cmp=="He"||cmp=="She"){
if(char(cmp[0])>='a'&&(cmp[0])<='z')
new_string=new_string+" she or he";
if(char(cmp[0])>='A'&&(cmp[0])<='Z')
new_string=new_string+" She or He";
cmp.erase();
if(int(my_string[i])==0)
{
return new_string;
}
}
else if(cmp == "him" || cmp== "her" || cmp== "Her" ||cmp== "Him")
{
if(char(cmp[0])>='a'&&(cmp[0])<='z')
new_string=new_string+" her or him";
if(char(cmp[0])>='A'&&(cmp[0])<='Z')
new_string=new_string+" Her or Him";
cmp.erase();
if(int(my_string[i])==0)
{
return new_string;
}
}
else if(cmp== "his" || cmp== "her" || cmp== "Her" || cmp== "His")
{
if(char(cmp[0])>='a'&&(cmp[0])<='z')
new_string=new_string+" her or his";
if(char(cmp[0])>='A'&&(cmp[0])<='Z')
new_string=new_string+" Her or His";
cmp.erase();
if(int(my_string[i])==0)
{
return new_string;
}
}
else if (cmp == "himself" || cmp== "herself" || cmp== "Herself" || cmp== "Himself")
{
if(char(cmp[0])>='a'&&(cmp[0])<='z')
new_string=new_string+" herself or himself";
if(char(cmp[0])>='A'&&(cmp[0])<='Z')
new_string=new_string+" Herself or Himself";
cmp.erase();
if(int(my_string[i])==0)
{
return new_string;
}
}
else
{
new_string=new_string+' '+cmp;
cmp.erase();
}
}
else
{
cmp=cmp+my_string[i];
}
}
}
int main(){
string first_string=get_input();
//conversion(my_string);
string converted_string=conversion(first_string);
cout<<"after conversion: "<<converted_string<<endl;;
return 0;
}
| true |
7b33906d427f882afea7e772f48d23dd8c1d0ea1 | C++ | MahiAlJawad/Competitive-Programming | /UVa/Uva 1203 Argus.cpp | UTF-8 | 749 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node
{
int id= 0;
int tm= 0;
};
bool operator <(const node &a, const node &b)
{
if(a.tm == b.tm) return a.id>b.id;
else return a.tm>b.tm;
}
int main()
{
int n, i, t, q, j;
string s;
vector<int> x, y;
priority_queue<node> pq;
while(cin>>s)
{
if(s== "#") break;
scanf("%d%d", &q, &t);
x.push_back(q);
y.push_back(t);
}
scanf("%d", &n);
int sz= x.size();
int z= n;
for(i= 0; i<sz; i++)
{
for(j= 1; j<=z; j++)
{
node a;
a.id= x[i];
a.tm= y[i]*j;
pq.push(a);
}
}
for(i=1; i<=n; i++)
{
node a= pq.top();
pq.pop();
printf("%d\n", a.id);
}
return 0;
}
| true |
8803278118a6d5e009fdadb1f7d721ff8a815abb | C++ | zhoulike/algorithms | /cc150/4.1.cc | UTF-8 | 2,215 | 3.578125 | 4 | [] | no_license | #include <algorithm>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include "tree.h"
using namespace std;
template <class T>
int treeHeight(Tree<T> *root)
{
if (!root)
return 0;
else
return max(treeHeight(root->left), treeHeight(root->right)) + 1;
}
template <class T>
bool isBalanced1(Tree<T> *root)
{
if (!root)
return true;
if (abs(treeHeight(root->left) - treeHeight(root->right)) > 1)
return false;
else
return isBalanced1(root->left) && isBalanced1(root->right);
}
template <class T>
bool helper2(Tree<T> *root, int &height)
{
if (!root) {
height = 0;
return true;
}
int leftHeight, rightHeight;
if (!helper2(root->left, leftHeight))
return false;
if (!helper2(root->right, rightHeight))
return false;
height = max(leftHeight, rightHeight) + 1;
if (abs(leftHeight - rightHeight) > 1)
return false;
else
return true;
}
template <class T>
bool isBalanced2(Tree<T> *root)
{
int tmp;
if (!root)
return true;
else
return helper2(root, tmp);
}
template <class T>
int helper3(Tree<T> *root)
{
if (!root)
return 0;
int leftHeight = helper3(root->left);
if (leftHeight == -1)
return -1;
int rightHeight = helper3(root->right);
if (rightHeight == -1)
return -1;
if (abs(leftHeight - rightHeight) > 1)
return -1;
else
return max(leftHeight, rightHeight) + 1;
}
template <class T>
bool isBalanced3(Tree<T> *root)
{
return helper3(root) != -1;
}
int main(int argc, char *argv[])
{
Tree<int> *root = nullptr;
assert(isBalanced1(root));
assert(isBalanced2(root));
assert(isBalanced3(root));
root = new Tree<int>(0);
assert(isBalanced1(root));
assert(isBalanced2(root));
assert(isBalanced3(root));
root->left = new Tree<int>(1);
assert(isBalanced1(root));
assert(isBalanced2(root));
assert(isBalanced3(root));
root->left->left = new Tree<int>(2);
assert(!isBalanced1(root));
assert(!isBalanced2(root));
assert(!isBalanced3(root));
cout << "All passed!" << endl;
return 0;
}
| true |
20df967e1393a83d123b381470eaaea737106f79 | C++ | Apple7xi/ThoughtWorksHomework2018 | /thoughtworks_homework/main.cpp | UTF-8 | 8,329 | 3.375 | 3 | [] | no_license | /*
* 2017/10/16;
* by alex;
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
/*
#define SIX_YEAR 2190
#define THREE_YEAR 1095
*/
using std::vector;using std::cin;using std::cout;using std::string;using std::endl;
//日期类定义
struct time_class{
int year;
int month;
int day;
time_class(){};
time_class(const int &yearA,const int &monthA,const int &dayA):year(yearA),month(monthA),day(dayA){};
};
//车辆类定义
class car{
private:
string number;
string brand;
time_class time;
int distance;
bool fix;
public:
car(){}
car(const string &num,const string &brd,const int &yea,const int &mon,const int &da,const int &dis,const bool &fx):number(num),brand(brd),time(yea,mon,da),distance(dis),fix(fx){}
string get_number() const { return number; }
string get_brand() const { return brand; }
int get_distance() const { return distance; }
bool get_fix() const { return fix; }
time_class get_time() const { return time; }
};
//car类比较函数
bool camp(const car &car1,const car &car2){
if(car1.get_brand() != car2.get_brand())
return car1.get_brand() < car2.get_brand();
else
return car1.get_number() < car2.get_number();
}
//计算报废日期
time_class time_fly(const time_class &time,const bool &fix){
int temp, decrease = 0, new_year = time.year, new_month = time.month, new_day = time.day;
if(fix)
temp = 3;
else
temp = 6;
for(int i = 0;i < temp;i++){
if(new_month <= 2 ){
if(new_year % 400 == 0 || (new_year % 4 ==0 && new_year % 100 != 0))
decrease++;
}else{
if((new_year + 1) % 400 == 0 ||((new_year + 1) % 4 ==0 && (new_year + 1 )% 100 != 0))
decrease++;
}
new_year++;
}
new_day -= decrease;
if(new_day < 0){//回退一个月;
switch(new_month){
case 1:new_day = new_day + 31;new_month = 12;new_year--;break;
case 2:new_day = new_day + 31;new_month --;break;
case 3:new_day = new_day + ((new_year % 400 == 0||(new_year % 4 == 0&&new_year %100 != 0))?29:28);new_month --;break;
case 4:new_day = new_day + 31;new_month --;break;
case 5:new_day = new_day + 30;new_month --;break;
case 6:new_day = new_day + 31;new_month --;break;
case 7:new_day = new_day + 30;new_month --;break;
case 8:new_day = new_day + 31;new_month --;break;
case 9:new_day = new_day + 31;new_month --;break;
case 10:new_day = new_day + 30;new_month --;break;
case 11:new_day = new_day + 31;new_month --;break;
case 12:new_day = new_day + 30;new_month --;break;
}
}
return time_class(new_year,new_month,new_day);
}
/*
time_class time_fly(const time_class &time,const int &duration){
int dur = duration;
int new_year = time.year,new_month = time.month,new_day = time.day;
dur = dur + new_day - 1;
new_day = 1;
while(dur >= 0){
switch(new_month){
case 1:dur -= 31;new_month++;break;
case 2:dur -= ((new_year % 400 == 0 || (new_year % 4 ==0 && new_year % 100 != 0))?29:28);new_month++;break;
case 3:dur -= 31;new_month++;break;
case 4:dur -= 30;new_month++;break;
case 5:dur -= 31;new_month++;break;
case 6:dur -= 30;new_month++;break;
case 7:dur -= 31;new_month++;break;
case 8:dur -= 31;new_month++;break;
case 9:dur -= 30;new_month++;break;
case 10:dur -= 31;new_month++;break;
case 11:dur -= 30;new_month++;break;
case 12:dur -= 31;new_month = 1;new_year++;break;
}
}
if(dur < 0){//回退一个月;
switch(new_month){
case 1:new_day = new_day + dur + 31;new_month = 12;new_year--;break;
case 2:new_day = new_day + dur + 31;new_month --;break;
case 3:new_day = new_day + dur + ((new_year % 400 == 0||(new_year % 4 == 0&&new_year %100 != 0))?29:28);new_month --;break;
case 4:new_day = new_day + dur + 31;new_month --;break;
case 5:new_day = new_day + dur + 30;new_month --;break;
case 6:new_day = new_day + dur + 31;new_month --;break;
case 7:new_day = new_day + dur + 30;new_month --;break;
case 8:new_day = new_day + dur + 31;new_month --;break;
case 9:new_day = new_day + dur + 31;new_month --;break;
case 10:new_day = new_day + dur + 30;new_month --;break;
case 11:new_day = new_day + dur + 31;new_month --;break;
case 12:new_day = new_day + dur + 30;new_month --;break;
}
}
return time_class(new_year,new_month,new_day);
}
*/
//报废判断:1:已报废;2:提醒报废;3:无提醒;
int write_off(const car &n_car,const time_class &n_time){
time_class w_time;
if(n_car.get_fix())
w_time = time_fly(n_car.get_time(),n_car.get_fix());
// w_time = time_fly(n_car.get_time(),THREEYEAR);
else
w_time = time_fly(n_car.get_time(),n_car.get_fix());
// w_time = time_fly(n_car.get_time(),SIXYEAR);
int temp = (w_time.year - n_time.year) * 12 + w_time.month - n_time.month;
if(temp < 0)
return 1;
else if(temp == 0){
if(w_time.day <= n_time.day)
return 1;
else
return 2;
}
else if(temp == 1)
return 2;
else
return 3;
}
//里程保养判断:1:提醒保养;2:无提醒;
int distance_related(const car &n_car){
int n_dis = n_car.get_distance();
int temp = n_dis % 10000;
if(temp >= 9500 || temp == 0)
return 1;
else
return 2;
}
//时间保养判断:1:提醒保养;2:无提醒;
int time_related(const car &n_car,const time_class &n_time){
int temp;
time_class time = n_car.get_time();
bool fix = n_car.get_fix();
if(fix)
temp = (3 - ((n_time.year - time.year) * 12 + n_time.month - time.month) % 3) % 3;
else{
if(n_time.year - time.year >= 3)
temp =(6 - ((n_time.year - time.year) * 12 + n_time.month - time.month) % 6) % 6;
else
temp = (12 - ((n_time.year - time.year) * 12 + n_time.month - time.month) % 12) % 12;
}
if(temp == 0){
if(n_time.day < time.day)
return 1;
else
return 2;
}else if(temp == 1)
return 1;
else
return 2;
}
//输出车辆vector信息;
void print_cars(const vector<car> &n_cars){
for(auto member = n_cars.cbegin();member != n_cars.cend();){
vector<car> temp;
unsigned int ix = 1;
temp.push_back(*member);
member++;
while(member != n_cars.cend() && member->get_brand() == (member-1)->get_brand()){
temp.push_back(*member);
member++;
}
cout <<(*(temp.cbegin())).get_brand() << ": " << temp.size() << " ";
for(auto t_member = temp.cbegin();t_member != temp.cend();t_member++,ix++){
if(ix == 1)
cout << "(";
else
cout <<", ";
cout << t_member->get_number();
if(ix == temp.size())
cout << ")" << endl;
}
}
}
int main(void){
string input;
vector<car> cars,w_cars,d_cars,t_cars;
time_class n_time;
//当前日期读入;
getline(cin,input);
{
auto pos = input.find_first_of("1234567890");
int now_year = stoi(input.substr(pos,4));
int now_month = stoi(input.substr(pos+5,2));
int now_day = stoi(input.substr(pos+8,2));
n_time = time_class(now_year,now_month,now_day);
}
//车辆信息读入;
while(getline(cin,input)){
auto pos1 = input.find('|');
auto pos2 = input.find('|',pos1+1);
auto pos3 = input.find('|',pos2+1);
auto pos4 = input.find('|',pos3+1);
string num = input.substr(0,pos1-0);
string time = input.substr(pos1+1,pos2-pos1-1);
string brand = input.substr(pos2+1,pos3-pos2-1);
int distance = stoi(input.substr(pos3+1,pos4-pos3-1));
bool fix = (input.substr(pos4+1,1))=="T"?true:false;
int year = stoi(time.substr(0,4));
int month = stoi(time.substr(5,2));
int day = stoi(time.substr(8,2));
cars.emplace_back(num,brand,year,month,day,distance,fix);
}
//车辆分类;
for(auto member = cars.cbegin();member != cars.cend();member++){
int temp = write_off(*member,n_time);
if(temp == 1)
continue;
else if(temp == 2){
w_cars.push_back(*member);
continue;
}
temp = distance_related(*member);
if(temp == 1){
d_cars.push_back(*member);
continue;
}
temp = time_related(*member,n_time);
if(temp == 1){
t_cars.push_back(*member);
continue;
}
}
//各类车辆vector排序,便于输出处理;
sort(w_cars.begin(),w_cars.end(),camp);
sort(t_cars.begin(),t_cars.end(),camp);
sort(d_cars.begin(),d_cars.end(),camp);
cout << "Reminder" << endl;
cout << "==================" << endl << endl;
cout << "* Time-related maintenance coming soon..." << endl;
print_cars(t_cars);
cout << endl;
cout << "* Distance-related maintenance coming soon..." << endl;
print_cars(d_cars);
cout << endl;
cout << "* Write-off coming soon..." << endl;
print_cars(w_cars);
return 0;
}
| true |
257470deee22cd39320b9b7602a59edaea13e72b | C++ | CJW-MAPU/InfoChecking_Program | /MFC Client/MFC Client/SHA256.cpp | UTF-8 | 394 | 2.796875 | 3 | [] | no_license | #include "Main.h"
void sha256(char * string, char outputBuffer[SIZE / 5])
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
int i = 0;
for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[SIZE / 5 - 1] = 0;
} | true |
12f3219a55c7fb5f36690b84c63ed533b89e7b3a | C++ | liyenjun/C-_CPP | /Sample codes/ch12/Prog12-10.cpp | BIG5 | 438 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
class CMouse {
public:
CMouse(); // POW٬ۦPNOغc
private:
int ix, iy; // ѹ_lm
};
CMouse::CMouse() {
ix = 1; iy = 1;
cout << "ix = " << ix << ", iy = " << iy << endl;
}
int main(void) {
cout << "mouseX ܼƫإ߫e" << endl;
CMouse mouseX;
cout << "mouseX ܼƫإ߫" << endl;
system("pause"); return(0);
} | true |
7426323e195e8f0a1203eb97e794f97011b4e3f8 | C++ | eduardoceretta/cg-projects | /ScreenSpaceAmbientOcclusion/libs/TecGraf/include/sciutils/actelem/bubblecolorscale.h | UTF-8 | 1,463 | 2.5625 | 3 | [] | no_license | //* bubblecolorscale.h
// An active color scale for bubble map.
// Tecgraf/PUC-Rio
// Oct 2006
#ifndef vis_actelem_bubblecolorscale_h
#define vis_actelem_bubblecolorscale_h
#include <sciutils/actelem2dhv.h>
#include <sciutils/colorscale.h>
#include <sciutils/defines.h>
//* *SciActiveBubbleColorScale* Class
class SCI_API SciActiveBubbleColorScale : public Sci2DActiveElementHV
{
public:
SciActiveBubbleColorScale(const char* name);
virtual ~SciActiveBubbleColorScale();
void SetNumberOfProperties(int p);
void SetPropertyName( int prop, const char* name );
void SetPropertyColor( int prop, unsigned char color[3] );
void SetPropertyMaxValue( int prop, float v );
virtual void SetDrawableAreaH (float x, float y, float w, float h);
virtual void SetDrawableAreaV (float x, float y, float w, float h);
/**
* Method that does the actual render of the element.
* Must be defined in all derived classes.
*/
virtual void doRender();
/**
* Pick method.
* Returns true if given normalized coordinate lies inside the element,
* false otherwise.
*/
virtual bool Pick(float x, float y)
{
return false;
}
private:
int m_bubbleMapNProperties; // number of properties on a bubble (max = 4)
char* m_bubbleMapPropertiesName[4];
float m_bubbleMapMaxWellPropertiesValues[4];
unsigned char m_bubbleMapPropertiesColor[12];
GLUquadricObj *d_quadric;
};
#endif
| true |
832dd3f6adf196785a1fa2ff67f7dc9653a0ae2c | C++ | ljxia1994/leetcode111 | /最长公共前缀.cpp | GB18030 | 735 | 3.328125 | 3 | [] | no_license | ////ǰ
//#include<iostream>
//#include<vector>
//#include<cstring>
//
//using namespace std;
//
//string longestCommonPrefix(vector<string>& strs) {
// string s;
// if (strs.empty()) return s;
// for (int index=0; index < strs[0].size(); index++)
// {
// char temp = strs[0][index];
// for (int i = 1; i < strs.size(); i++)
// {
// if ((strs[i][index] != temp) || (i==strs[index].size()))
// {
// return strs[0].substr(0, index);
// }
// }
// }
// return strs[0];
//}
//
//int main()
//{
// vector<string> strs{ "dog","racecar","car"};
// string s=longestCommonPrefix(strs);
// cout << s << endl;
// return 0;
//} | true |
984e8ba7cb4f5165e68bc6d639b4d36010632108 | C++ | wastegas/monster | /monster/monster.h | UTF-8 | 525 | 2.671875 | 3 | [] | no_license | //
// monster.h
// monster
//
// Created by Ronnie Baron on 3/29/14.
// Copyright (c) 2014 Ronnie Baron. All rights reserved.
//
#ifndef __monster__monster__
#define __monster__monster__
#include "character.h"
class Monster : public Character
{
private:
public:
enum Weapons
{
MISSED,
STOMP,
SWIPE,
FIRE
};
Monster(const std::string n) : Character(n) {}
void attack(Character&);
std::string getWeapon(Weapons) const;
};
#endif /* defined(__monster__monster__) */
| true |
b43d99fddd1d078e6116820f115e5eb096063d0e | C++ | SGBon/advgraph | /ass3/boid.hpp | UTF-8 | 1,424 | 2.9375 | 3 | [] | no_license | #ifndef TRIBES_BOID_H
#define TRIBES_BOID_H
#include <glm/glm.hpp>
enum tribes{
RED,
BLUE
};
class boid{
public:
/* detection radius around boid */
static const float FLOCK_RADIUS;
static const float MAX_ACCELERATION;
/* constructor, argument is starting position and member tribe */
boid(const glm::vec3 startPos, enum tribes tribe);
/* update the position, velocity, and acceleration based on timestep */
void step(const float timestep);
/* add acceleration to the boid's acceleration */
void addAcceleration(const glm::vec3 acceleration);
/* set the acceleration of the boid */
void setAcceleration(const glm::vec3 acceleration);
/* set the x coordinate that the boid has to reach */
void setGoal(const glm::vec3 goal);
/* set the bounds that the boid should not cross over */
static void setBounds(const float x1, const float y1,
const float x2, const float y2);
/* return position */
glm::vec3 getPosition() const;
/* return velocity */
glm::vec3 getVelocity() const;
/* return forward direction of boid */
glm::vec3 getDirection() const;
/* return goal direction */
glm::vec3 goalDirection() const;
/* return tribe */
enum tribes getTribe() const;
void flipGoal();
private:
glm::vec3 position;
glm::vec3 velocity;
glm::vec3 acceleration;
glm::vec3 goal;
static float bounds[4];
enum tribes tribe;
bool atGoal();
};
#endif
| true |
906f7f0cc7d81a252b000b221bddd1f6f4b458d3 | C++ | Ankurrana/ProgrammingTemplates | /NCR/NCR.cpp | UTF-8 | 483 | 2.53125 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
typedef long long int lld;
long long NChooseK(int n,int k){
if(k > n) return 0;
if(2*k > n) k = n-k;
if(k==1) return n;
long long result = n;
for(int i=2;i<=k;i++){
result *= (n-i+1);
result /= i;
}
return result;
}
long long nPr(lld n, lld r, lld mod){
lld ans = 1;
for(lld i = n;i>n-r;i--) ans = (ans * i)%mod;
return ans;
}
int main(){
// cout << NChooseK(31,7) << endl;
cout << nPr(5,2,1e12) << endl;
return 0;
} | true |
119e29c3cf59cc41e4b9b0d3fcb9ea1925af3b03 | C++ | hearnadam/chess | /include/Piece.h | UTF-8 | 2,732 | 3.90625 | 4 | [] | no_license | #ifndef PIECE_H
#define PIECE_H
#include <iostream>
#include <string>
class Square;
class Player;
class Piece {
public:
/**
* @brief Construct a new Piece object with the color passed in.
*
* @param color the color of the piece to be constructed.
*/
Piece(std::string color);
/**
* @brief Destroy the Piece object.
*/
virtual ~Piece() = default;
/**
* @brief Set the square the piece is on.
*
* @param square the square where it will be set.
*/
virtual void setLocation(Square* square);
/**
* @brief Move this piece to the square specified if possible.
*
* @param byPlayer the player moving the piece.
* @param to the square the piece is being moved to.
* @return true if the piece moved.
* @return false if the piece did not move.
*/
virtual bool moveTo(Player& byPlayer, Square& to);
/**
* @brief Returns the color of the piece as a const.
*
* @return const std::string color of piece.
*/
const std::string color() const;
/**
* @brief Returns true if the piece is on the board.
*
* @return true if piece is on board.
* @return false if piece is not on the board.
*/
const bool isOnBoard() const;
/**
* @brief Gets the location of the piece.
*
* @return Square& the reference to the square the piece is on.
*/
Square& getLocation() const;
/**
* @brief Returns true if the piece can move to the square passed in.
*
* @param location the square to be checked if the piece can move to.
* @return true if the piece can move there.
* @return false if the piece can not move there.
*/
virtual bool canMoveTo(Square& location) const = 0;
/**
* @brief Returns an int of the value of the piece.
*
* @return const int the value of the piece.
*/
virtual const int value() const = 0;
/**
* @brief Outputs the piece's string representation to outStream.
*
* @param outStream the ostream to output to.
*/
virtual void display(std::ostream& outStream) const = 0;
private:
/**
* @brief Construct a new Piece object
*/
Piece() = default;
// The string representation of the piece color.
const std::string _color;
// Where the piece thinks it is.
Square* _square;
}; // Piece
#endif
| true |
df949523f83d5c01338379b6101667126f7e0ee4 | C++ | diagnosa/N-Queen---Hill-Climbing | /queen.cpp | UTF-8 | 4,370 | 3.25 | 3 | [] | no_license | /*
Program N-Queen menggunakan HillClimbing
Kelompok 7
AI C 2014/2015
Input : jumlah pion Queen
Output : solved jika mencapai solusi
nilai H saat ini jika tidak terdapat solusi
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> kolom;
vector< vector<int> > papan;
vector<int> hvalue;
vector<int> hvalue1;
void inisialisasi(int n){
//inisialisasi dilakukan dengan merandom posisi baris tiap kolomnya
int i, j, b;
srand(time(NULL));
for(i=0;i<n;i++){
kolom.push_back(0);
hvalue.push_back(0);
hvalue1.push_back(0);
}
for(i=0;i<n;i++){
papan.push_back(kolom);
}
for(i=0;i<n;i++){
b= rand()%n;
papan[b][i]=1;
kolom[i]=b;
}
}
void cetak(int n){
int i, j;
cout <<endl;
for(i=0; i<n; i++){
for(j=0;j<n;j++){
cout << papan[i][j] << " ";
}
cout << endl;
}
}
void swap(int *i, int*j){
int *temp=i;
i=j;
j=temp;
}
void cetakh(int n){
int i;
cout << endl << "hvalue bawah:" << endl;
for(i=0; i<n; i++){
cout << hvalue[i] << " ";
}
cout << endl << "hvalue atas:" << endl;
for(i=0; i<n; i++){
cout << hvalue1[i] << " ";
}
cout << endl;
}
int getPair (int len, int baris, int kolom){
//fungsi ini untuk mencari jumlah ratu yang menyerang pion pada posisi : papan[baris][kolom]
//serangan dari sisi kiri diabaikan karena dianggap sudah dihitung pion sebelumnya untuk menghindari redudansi
int h = 0, j=0;
for(int i=kolom; i<len;){
i++;
if(papan[baris][i]&&i!=kolom) h++; //hitung h horizontal
}
j=baris;
for(int i=kolom; i<len&&j<len; ){
i++;
j++;
if(papan[j][i]) h++; //hitung h kanan bawah
}
j=baris;
for(int i=kolom; i<len&&j>0;){
i++;
j--;
if(papan[j][i]) h++; //hitung h kanan atas
}
return h;
}
int getCurrentH(int max){
int h=0;
for (int i=0; i<max; i++)
{
int j=kolom[i];
h+=getPair(max, j, i);
}
return h;
}
void cekHValue(int max){
int h, j, temp, l;
for(int k=0; k<=max; k++){
h=0;
for (l=0; l<=max; l++)
{
if (papan[l][k]==1) break;
}
/*mencari hvalue kalo dipindah ke bawah atau bisa disebut tetangga bawah*/
if(l==max) temp=0;
else temp=l+1;
swap(papan[l][k], papan[temp][k]);
for (int i=0; i<max; i++)
{
for (j=0; j<=max; j++)
{
if (papan[j][i]==1) break;
}
h+=getPair(max, j, i);
}
hvalue[k]=h;
swap(papan[l][k], papan[temp][k]);
/*------------------------------------*/
/*mencari hvalue kalo dipindah ke atas atau bisa disebut tetangga atas*/
if(l==0) temp=max;
else temp=l-1;
swap(papan[l][k], papan[temp][k]);
for (int i=0; i<max; i++)
{
for (j=0; j<=max; j++)
{
if (papan[j][i]==1) break;
}
h+=getPair(max, j, i);
}
hvalue1[k]=h;
swap(papan[l][k], papan[temp][k]);
/*------------------------------------*/
}
}
void hillClimbing (int maxLen){
int hmin, indeks=0, cek, atas;
while(1){
if(getCurrentH(maxLen) == 0){
cout << endl << "Solved" <<endl; //menghentikan fungsi ketika h saat ini 0
return;
}
hmin=999;
cekHValue(maxLen);
/*-------mencari hvalue terkecil-------*/
for(int i=0; i<=maxLen; i++){
if(hmin>hvalue[i]){
hmin=hvalue[i];
indeks=i;
atas=0;
}
if(hmin>hvalue1[i]){
hmin=hvalue1[i];
indeks=i;
atas=1;
}
}
/*--------------------------------------*/
cetakh(maxLen+1);
if(getCurrentH(maxLen)<hmin) { //menghentikan fungsi ketika tidak ada lagi solusi yang lebih baik dari state sekarang
cout<< endl << "Tidak ditemukan solusi" << endl
<< "H saat ini : " << getCurrentH << endl;
return;
}
int temp, i;
i=kolom[indeks];
if(atas){
if(i==0) temp=maxLen;
else temp=i-1;
}
else{
if(i==maxLen) temp=0;
else temp=i+1;
}
swap(papan[i][indeks], papan[temp][indeks]);
kolom[indeks]=temp;
cetak(maxLen+1);
}
}
int main(){
double total_time1;
clock_t start, end;
int n, j , i;
cout << "isi banyak queen : ";
cin >> n;
while(n<4){
cout << "Banyak Queen Minimal 4" << endl;
cout << "isi banyak queen : ";
cin >> n;
}
inisialisasi(n);
cetak(n);
start = clock();
hillClimbing(n-1);
end = clock();//time count stops
total_time1 = ((double) (end - start)) / CLOCKS_PER_SEC;//calulate total time
cout << "Running Time : " << total_time1 << " s" <<endl;
return 0;
}
| true |
04e83bb85d26a39a4d00f9927b85fa786a578472 | C++ | mario206/MyLeetcode | /Two Sum.cpp | UTF-8 | 628 | 2.921875 | 3 | [] | no_license | class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
// 使用coolshell的方法
map<int,int> list;
vector<int> result;
for(int i = 0;i < numbers.size();++i)
{
if(list.find(numbers[i]) == list.end())
{
// 没找到
list[target - numbers[i]] = i;
}
else
{
//找到
result.push_back(list[numbers[i]] + 1);
result.push_back(i + 1);
}
}
return result;
}
};
| true |
7f0b1dadaab439f2ca61bd8273039c023cebd0f1 | C++ | leomrocha/musicapps | /MusicChallenge/candidate_libs/MIDITrail (2)/MIDITrail/MTLogo.h | SHIFT_JIS | 2,480 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | //******************************************************************************
//
// MIDITrail / MTLogo
//
// MIDITrail S`NX
//
// Copyright (C) 2010 WADA Masashi. All Rights Reserved.
//
//******************************************************************************
#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include "MTFontTexture.h"
//******************************************************************************
// p[^`
//******************************************************************************
//^Cg
#define MTLOGO_TITLE _T("MIDITrail")
//S`ʒu
#define MTLOGO_POS_X (20.0f) //`ʒux
#define MTLOGO_POS_Y (-15.0f) //`ʒuy
#define MTLOGO_MAG (0.1f) //g嗦
//^C
#define MTLOGO_TILE_NUM (40)
//Of[VԊԊu(msec)
#define MTLOGO_GRADATION_TIME (1000)
//******************************************************************************
// MIDITrail S`NX
//******************************************************************************
class MTLogo
{
public:
//RXgN^^fXgN^l
MTLogo(void);
virtual ~MTLogo(void);
//
int Create(LPDIRECT3DDEVICE9 pD3DDevice);
//ϊ
int Transform(LPDIRECT3DDEVICE9 pD3DDevice);
//`
int Draw(LPDIRECT3DDEVICE9 pD3DDevice);
//j
void Release();
private:
//_obt@\
struct MTLOGO_VERTEX {
D3DXVECTOR3 p; //_W
D3DXVECTOR3 n; //@
DWORD c; //fBt[YF
D3DXVECTOR2 t; //eNX`摜ʒu
};
//_obt@[̃tH[}bg̒`FWϊς݂w
DWORD _GetFVFFormat(){ return (D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX1); }
private:
//tHgeNX`
MTFontTexture m_FontTexture;
MTLOGO_VERTEX* m_pVertex;
unsigned long m_StartTime;
unsigned long m_GradationTime;
int _CreateTexture(LPDIRECT3DDEVICE9 pD3DDevice);
int _CreateVertex();
int _GetTextureUV(
TCHAR target,
D3DXVECTOR2* pV0,
D3DXVECTOR2* pV1,
D3DXVECTOR2* pV2,
D3DXVECTOR2* pV3
);
void _SetVertexPosition(
MTLOGO_VERTEX* pVertex,
float x,
float y,
float magRate
);
void _SetGradationColor();
void _SetTileColor(
MTLOGO_VERTEX* pVertex,
float color
);
};
| true |
50b5ffe0b19df97068d9e3308431b12981747037 | C++ | luqian2017/Algorithm | /LintCode/1189_MInesweeper/1189_MInesweeper.cpp | UTF-8 | 1,531 | 2.84375 | 3 | [] | no_license | class Solution {
public:
/**
* @param board: a board
* @param click: the position
* @return: the new board
*/
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int m = board.size();
int n = board[0].size();
if (m == 0 || n == 0) return {};
queue<pair<int, int>> q;
q.push({click[0], click[1]});
while(!q.empty()) {
pair<int, int> curNode = q.front();
q.pop();
int mineCount = 0;
int x = curNode.first, y = curNode.second;
if (board[x][y] == 'M') {
board[x][y] = 'X';
return board;
}
vector<pair<int, int>> neighborNodes;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
int newX = x + i;
int newY = y + j;
if (newX < 0 || newX >= m || newY < 0 || newY >= n) continue;
if (board[newX][newY] == 'M') mineCount++;
else if (board[newX][newY] == 'E') neighborNodes.push_back({newX, newY});
}
}
if (mineCount > 0) {
board[x][y] = mineCount + '0';
} else {
for (auto n : neighborNodes) {
board[n.first][n.second] = 'B';
q.push(n);
}
}
}
return board;
}
}; | true |
1dd5e9d083d019ac2c7aa4d427ac40aefc88f44c | C++ | otgaard/zapPlayer | /module/spectrogram.cpp | UTF-8 | 1,893 | 2.5625 | 3 | [] | no_license | /* Created by Darren Otgaar on 2016/12/04. http://www.github.com/otgaard/zap */
#include "spectrogram.hpp"
#include <zap/maths/algebra.hpp>
#include <zap/graphics2/plotter/plotter.hpp>
#define LOGGING_ENABLED
#include <zap/tools/log.hpp>
using namespace zap;
using namespace zap::maths;
using namespace zap::graphics;
struct spectrogram::state_t {
plotter plot;
sampler1D<vec3b, decltype(interpolators::nearest<vec3b>)> colour_sampler_;
state_t() : plot(vec2f(0.f, 1.f), vec2f(0.f, 1.f), .1f) { }
};
spectrogram::spectrogram() : state_(new state_t()), s(*state_.get()) {
}
spectrogram::~spectrogram() = default;
bool spectrogram::initialise() {
if(!s.plot.initialise()) {
LOG_ERR("Error initialising plotter");
return false;
}
s.colour_sampler_.data.resize(8);
s.colour_sampler_.data[0] = vec3b(255, 255, 255);
s.colour_sampler_.data[1] = vec3b(255, 0, 255);
s.colour_sampler_.data[2] = vec3b(100, 100, 255);
s.colour_sampler_.data[3] = vec3b(0, 255, 255);
s.colour_sampler_.data[4] = vec3b(0, 255, 0);
s.colour_sampler_.data[5] = vec3b(255, 255, 0);
s.colour_sampler_.data[6] = vec3b(255, 0, 0);
s.colour_sampler_.data[7] = vec3b(255, 255, 255);
s.colour_sampler_.inv_u = 1.f/7.f;
s.colour_sampler_.fnc = interpolators::linear<vec3b>;
return true;
}
void spectrogram::resize(int width, int height) {
auto hwidth = width - 20, hheight = height/4;
s.plot.world_transform.scale(vec2f(hwidth, hheight));
s.plot.world_transform.translate(vec2f(10, height - hheight - 10));
}
void spectrogram::update(float dt, const std::vector<float>& samples) {
sampler1D<float, decltype(interpolators::cubic<float>)> sampler(samples, interpolators::cubic<float>);
s.plot.live_plot(sampler, s.colour_sampler_, 2000);
}
void spectrogram::draw(const zap::renderer::camera& cam) {
s.plot.draw(cam);
}
| true |
7227b6c27373d98dcbd2aa23ff2ad94a20f91a92 | C++ | chinhph97/webGL | /Translation/InternshipFW/Singleton.h | UTF-8 | 610 | 3.234375 | 3 | [] | no_license | #pragma once
template <class T>
class Singleton
{
private:
static T* instance;
public:
static T* GetInstance();
static void FreeInstance();
Singleton(void);
virtual ~Singleton(void);
};
template <class T>
T* Singleton<T>::instance = 0;
template <class T>
Singleton<T>::Singleton(void)
{
instance = (T*) this;
}
template <class T>
Singleton<T>::~Singleton(void)
{
instance = 0;
}
template <class T>
void Singleton<T>::FreeInstance(void)
{
if ( instance )
delete instance;
instance = 0;
}
template <class T>
T* Singleton<T>::GetInstance(void)
{
if ( ! instance )
new T;
return instance;
} | true |
cc434b9edaed2f6ada0599e5972d3b14622228a0 | C++ | ppeschke/hexar | /GameInputHandler.cpp | UTF-8 | 4,616 | 2.921875 | 3 | [] | no_license | #include "GameInputHandler.h"
#include "game.h"
#include "NetworkClient.h"
NetworkClient* getClient();
bool getHovered(Game* thegame, int& i, int& p);
base* getHexagon(Game* thegame, int i, int p);
base* getItem(Game* thegame, int i, int p);
string toString(int i);
GameInputHandler::GameInputHandler(Game* g, NetworkClient* c) : InputHandler(g, c)
{
}
GameInputHandler::~GameInputHandler()
{
}
void GameInputHandler::handleMouseClick(InputEvent e)
{
int i = -1, p = -1;
switch(thegame->command)
{
case 'B':
if(thegame->sel1 == nullptr)
{
//may set i and p
getHovered(thegame, i, p);
if(i != -1 && p != -1)
{
thegame->sel1 = getHexagon(thegame, i, p);
string sendString = "_buy base ";
sendString += toString(thegame->sel1->i);
sendString += ' ';
sendString += toString(thegame->sel1->p);
Client->Send(sendString.c_str());
thegame->command = ' ';
}
thegame->sel1 = nullptr;
}
break;
case 'M':
if(thegame->sel1 == nullptr)
{
//may set i and p
getHovered(thegame, i, p);
if(i != -1 && p != -1)
{
thegame->sel1 = getHexagon(thegame, i, p);
base* item = getItem(thegame, thegame->sel1->i, thegame->sel1->p);
if(item == nullptr)
{
thegame->messages.AddMessage("You must select a tile with something on it!", 3);
thegame->sel1 = nullptr;
}
}
else
thegame->messages.AddMessage("Please select a tile.", 3);
}
else if(thegame->sel2 == nullptr)
{
//may set i and p
getHovered(thegame, i, p);
if(i != -1 && p != -1)
{
thegame->sel2 = getHexagon(thegame, i, p);
string sendString = "_move ";
sendString += toString(thegame->sel1->i);
sendString += ' ';
sendString += toString(thegame->sel1->p);
sendString += ' ';
sendString += toString(thegame->sel2->i);
sendString += ' ';
sendString += toString(thegame->sel2->p);
Client->Send(sendString.c_str());
thegame->command = ' ';
thegame->sel1 = nullptr;
thegame->sel2 = nullptr;
}
else
thegame->messages.AddMessage("Please select a tile.", 3);
}
break;
case 'W':
if(thegame->sel1 == nullptr)
{
//may set i and p
getHovered(thegame, i, p);
if(i != -1 && p != -1)
{
thegame->sel1 = getHexagon(thegame, i, p);
string sendString = "_buy walker ";
sendString += toString(thegame->sel1->i);
sendString += ' ';
sendString += toString(thegame->sel1->p);
Client->Send(sendString.c_str());
thegame->command = ' ';
}
thegame->sel1 = nullptr;
}
break;
case 'T':
if(thegame->sel1 == nullptr)
{
//may set i and p
getHovered(thegame, i, p);
if(i != -1 && p != -1)
{
thegame->sel1 = getHexagon(thegame, i, p);
string sendString = "_buy turret ";
sendString += toString(thegame->sel1->i);
sendString += ' ';
sendString += toString(thegame->sel1->p);
Client->Send(sendString.c_str());
thegame->command = ' ';
}
thegame->sel1 = nullptr;
}
break;
default:
//may set i and p
getHovered(thegame, i, p);
if(i != -1 && p != -1)
{
thegame->sel1 = getHexagon(thegame, i, p);
string sendString = "_grab ";
sendString += toString(thegame->sel1->i);
sendString += ' ';
sendString += toString(thegame->sel1->p);
Client->Send(sendString.c_str());
thegame->command = ' ';
}
thegame->sel1 = nullptr;
break;
}
}
void GameInputHandler::handleButtonPress(InputEvent e)
{
if(thegame->typing)
{
switch(e.getPressed())
{
case (char)27: //escape
thegame->typing = false;
break;
case (char)9: //tab
thegame->typing = false;
break;
case (char)8: //backspace
if(thegame->chatString.size() > 0)
thegame->chatString = thegame->chatString.substr(0, thegame->chatString.size() - 1);
break;
case (char)10: //line feed
case (char)13: //carriage return
getClient()->Send(thegame->chatString.c_str());
thegame->chatString = "";
thegame->typing = false;
break;
default:
if(thegame->typing)
thegame->chatString += e.getPressed();
break;
}
}
else
{
switch(e.getPressed())
{
case (char)27: //escape
thegame->over = true;
break;
case (char)9: //tab
thegame->typing = true;
break;
case 't':
case 'T':
thegame->command = 'T';
break;
case 'w':
case 'W':
thegame->command = 'W';
break;
case 'b':
case 'B':
thegame->command = 'B';
break;
case 'm':
case 'M':
thegame->command = 'M';
break;
case 'g':
case 'G':
thegame->command = 'G';
break;
case ' ':
getClient()->Send("_endturn");
thegame->command = ' ';
break;
default:
break;
}
}
}
| true |
fd4ccf2abae7d232ebf2e7b85d3eb2eb883a5f23 | C++ | taquayle/ITAD123 | /Assignment_05/Assign_05_03 - Overloaded Hospital/Assign_05_03 - Overloaded Hospital/Assign_05_03 - Overloaded Hospital.cpp | WINDOWS-1258 | 2,880 | 3.359375 | 3 | [] | no_license | // Assign_05_03 - Overloaded Hospital.cpp : Defines the entry point for the console application.
/*
Overloaded Hospital
Write a program that computes and displays the charges for a patients hospital stay.
First, the program should ask if the patient was admitted as an in-patient or an outpatient.
the following data should be entered:
The number of days spent in the hospital
The daily rate
Hospital medication charges
Charges for hospital services (lab tests, etc.)
*/
// Tyler Quayle - SIN: 950416426
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const string ERROR = ("\n\nERROR: INVALID INPUT\n\n");
double hospital_bill(double, double, double, double);
double hospital_bill(double, double);
void patientInfo(double&, double&, double&, double&);
void patientInfo(double&, double&);
bool validate(double);
int main()
{
int patientType;
double daysIn, dailyRate, serviceCharges, medicineBill ,totalBill;
do
{
cout << "Patient type? 0 - In Patient || 1 - Out Patient" << endl;
cin >> patientType;
if(patientType == 0)
{
patientInfo(daysIn, dailyRate, medicineBill, serviceCharges);
totalBill = hospital_bill(daysIn, dailyRate, medicineBill, serviceCharges);
}
else if (patientType-- == 1)
{
patientInfo(medicineBill, serviceCharges);
totalBill = hospital_bill(medicineBill, serviceCharges);
}
else
cout << ERROR;
}while(patientType);
cout << setprecision(2) << left << fixed;
cout << setw(50) << "\n\nTotal Bill for this visit is:" << "$"<< totalBill << "\n\n";
system("Pause");
return 0;
}
void patientInfo(double& days, double& rate, double& medicine, double& charges)
{
cout << left << fixed;
do{
cout << setw(48) << "Please enter the number of days checked in:" << "$";
cin >> days;
}while (!validate(days));
do{
cout << setw(48) << "Please enter the daily rate:" << "$";
cin >> rate;
}while (!validate(rate));
do{
cout << setw(48) << "Please enter the medicine cost:" << "$";
cin >> medicine;
}while (!validate(medicine));
do{
cout << setw(48) << "Plese enter any additional service charges:" << "$";
cin >> charges;
}while(!validate(charges));
}
void patientInfo(double& medicine, double& charges)
{
cout << left << fixed;
do{
cout << setw(48) << "Please enter the medicine cost:" << "$";
cin >> medicine;
}while (!validate(medicine));
do{
cout << setw(48) << "Plese enter any additional service charges:" << "$";
cin >> charges;
}while(!validate(charges));
}
double hospital_bill(double days, double rate, double medicine, double charges)
{
return (days * rate) + medicine + charges;
}
double hospital_bill(double medicine, double charges)
{
return medicine + charges;
}
bool validate(double test)
{
if(test < 0)
{
cout << ERROR;
return false;
}
else
return true;
} | true |
ca48080c3b84149a3af445e0516d9a6d7e75acfc | C++ | xingoxu/leetcode | /377.cpp | UTF-8 | 684 | 3.359375 | 3 | [] | no_license |
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution
{
unordered_map<int, int> cache;
int dfs(vector<int> &nums, int remain)
{
if (remain == 0)
return 1;
auto p = cache.find(remain);
if (p != cache.end())
{
return p->second;
}
int ret = 0;
for (auto &x : nums)
{
if (remain - x >= 0)
ret += dfs(nums, remain - x);
}
return cache[remain] = ret;
}
public:
int combinationSum4(vector<int> &nums, int target)
{
return dfs(nums, target);
}
};
int main()
{
vector<int> nums{1, 2, 3};
cout << Solution().combinationSum4(nums, 4) << endl;
return 0;
}
| true |
2384da7490eb5e104a9a2dfe62f5fd84e98adc02 | C++ | dldhk97/AcmicpcStudy | /SolveByStep/11727.cpp | UHC | 2,027 | 3.921875 | 4 | [] | no_license | //#11727
//
//
//2n Ÿϸ 2
//
//
//
//2n 簢 21 22 ŸϷ ä ϴ α ۼϽÿ.
//
//Ʒ 217 簢 ä Ѱ ̴.
//
//Է
//
//ù° ٿ n ־. (1 n 1, 000)
//
//
//ù° ٿ 2n ũ 簢 ä 10, 007 Ѵ.
#include <iostream>
using namespace std;
//տ Ǭ 11726 , 2xn Ÿϸ 2 ߴ.
//̹ 2*2 Ÿ ߰.
// 鼭 ȭ .
//n=1 1*2Ÿ ϳ => 1
//n=2 1*2Ÿ ΰ or 2*1Ÿ ΰ or 2*2 Ÿ ϳ => 3
//n=3 n=2 1*2Ÿ ϳ ߰ or n=1 Ŀ 2*2Ÿ ä Ѵ.
// n=1 Ŀ 2*2 ä 1*2 2 ֱ or 2*1 ΰ ֱ or 2*2 ϳ ֱε, 1*2 2 ִ n=2 İ ģ.
//, n=1 Ŀ 2*2 ä ȿ , 2*1 2 ִ Ŀ, 2*2 ϳ ִ , 2.
//, n=3϶ n-1 n=2 Ŀ ڶ 1*2Ÿ ϳ ߰ϴ => 3
// n-2 n=1 Ŀ 2*2 ȿϰ ä => 2̹Ƿ
// ϸ 5̴.
//̷ ȭ f(n) = f(n-1) + (f-2) * 2 ȴ.
//(δ n=5϶ غ鼭 ȭ ãҴ.)
int arr[1001];
int solution(int n)
{
if (n == 1)
return 1;
if (n == 2)
return 3;
if (arr[n - 1] == 0)
arr[n - 1] = solution(n - 1);
if (arr[n - 2] == 0)
arr[n - 2] = solution(n - 2);
return (arr[n - 1] + (arr[n - 2]) * 2) % 10007;
}
int main()
{
int input;
cin >> input;
cout << solution(input) << "\n";
return 0;
} | true |
a8e9939c8218f1f736ba1704a76772c244c97873 | C++ | redclock/leetcode | /cpp/Implement strStr().cpp | UTF-8 | 812 | 3.59375 | 4 | [] | no_license | /*
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*/
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.length() < needle.length())
return -1;
if (needle.length() == 0) return 0;
int len = haystack.length() - needle.length();
for (int i = 0; i <= len; i++) {
if (haystack[i] == needle[0]) {
bool found = true;
for (int j = 1; j < needle.length(); j++) {
if (needle[j] != haystack[i + j]) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
}; | true |
4e84d66af7205bc23f58b7d4409dec830d7e4e18 | C++ | HexaRAM/GL | /src/etat/etat35.cpp | UTF-8 | 750 | 2.671875 | 3 | [] | no_license | #include "etat35.h"
#include "etat41.h"
#include "etat30.h"
#include "etat31.h"
#include "etat29.h"
#include "../config.h"
Etat35::Etat35(string pName) : Etat(pName){}
Etat35::Etat35(){}
Etat35::~Etat35(){}
bool Etat35::transition(Automate & automate, Symbole * s ){
int idSym = *s ;
switch (idSym) {
case pf :
automate.decalage(s, new Etat41("41"));
break;
case add :
automate.decalage(s, new Etat30("30"));
break;
case moins :
automate.decalage(s, new Etat31("31"));
break;
case OA :
automate.decalage(s, new Etat29("29"));
break;
default : break;
}
return false;
}
Etat* Etat35::next(Symbole* s)
{
switch (*s)
{
case OA:
return new Etat29("29");
break;
default:
return NULL;
break;
}
}
| true |
2c710edd8e3018e5ca4186afc07d0a462019a970 | C++ | css521/c | /leetcode/JudgeSquareSum.cpp | UTF-8 | 473 | 3.578125 | 4 | [] | no_license |
/*
Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
*/
class Solution {
public:
bool judgeSquareSum(int c)
{
for(int i=0;i<=sqrt(c);++i)
if((int)sqrt(c-i*i)==sqrt(c-i*i)) //Just judge whether it's right or wrong.
return true;
return false;
}
}; | true |
83a0b9af445022cfe8a42850b4da2d28c330c8d2 | C++ | weigaofei/apollo_3.0_planning | /planning/tasks/dp_poly_path/test.cc | UTF-8 | 125 | 2.671875 | 3 | [] | no_license | #include<iostream>
int main()
{
bool a, b;
a = true;
b = true;
std::cout << a+b<< std::endl;
return 0;
} | true |
6d835aa6dfc4137bf52305000af41d27ab1f0f62 | C++ | npkhang99/Competitive-Programming | /UVa/674.cpp | UTF-8 | 405 | 2.53125 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
using namespace std;
int n, c[] = {1,5,10,25,50};
long long memo[6][7500] = {};
long long btrack(int t, int n){
if(n == 0) return 1;
if(t > 4 || n < 0) return 0;
return btrack(t+1, n) + btrack(t, n-c[t]);
}
int main(){
memset(memo,-1,sizeof(memo));
while(~scanf("%d",&n))
printf("%lld\n",btrack(0,n));
return 0;
}
| true |
c2d442c40328f2c3498320c27edb8828337d26b8 | C++ | anokta/CS7055-CS7057 | /IET/Camera.cpp | UTF-8 | 657 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "Camera.h"
#include "EntityManager.h"
Camera::Camera(std::vector<GenericShader*> &s, glm::vec3 &e, glm::vec3 &t, glm::vec3 &u) : shaders(s), eye(e), target(t), up(u)
{
EntityManager::GetInstance()->AddUpdatable(this);
}
void Camera::Update(float deltaTime)
{
glm::mat4 V = glm::lookAt(eye, target, up);
for(unsigned int i=0; i<shaders.size(); ++i)
{
// skybox shader
if(shaders[i]->GetName().compare("Skybox") == 0)
{
glm::mat4 Vcopy(V);
Vcopy[3] = shaders[i]->GetViewMatrix()[3];
shaders[i]->SetViewMatrix(Vcopy);
}
// model shaders
else
{
shaders[i]->SetViewMatrix(V);
shaders[i]->SetEyeVector(eye);
}
}
} | true |
330a78a50ab8c5fd92d50ac5bf36e3cb6e318920 | C++ | Sabahet/Triangles | /Triangle1.cpp | UTF-8 | 500 | 2.71875 | 3 | [] | no_license | //
// Triangle1.cpp
// Lab 6
//
// Created by Sabahet Alovic on 11/5/19.
// Copyright © 2019 Sabahet Alovic. All rights reserved.
//
#include "Triangle1.hpp"
#include "Triangle.h"
int test(int x, int y, int z){
while (x+y > z && x+z > y && z+y > x){
if(x!=y && x!=z && y!= z ){
return 0;
}
if(x==y && z==x && y==z ){
return 2;
}
if(x==y || z==x || y==z ){
return 1;
}
}
return 3;
}
| true |
1e431f33f8cdc015512ac178c16e794d1d7f384d | C++ | huanjihgh/Object | /object/UInt32.cpp | UTF-8 | 458 | 2.671875 | 3 | [] | no_license | #include"../include/UInt32.hpp"
namespace object {
//UInt32::UInt32() {
// this->_value.UINT32 = 0;
//}
UInt32::UInt32(uint32_t value) {
this->_value = value;
}
std::string UInt32::identify() const {
return "UInt32";
}
DataType UInt32::getDataType() {
return DataType::OUInt32_H;
}
UInt32::operator uint32_t() {
return this->_value;
}
std::string UInt32::toString() {
std::stringstream ss;
ss << *this;
return ss.str();
}
}
| true |
8e3d2c0fab77bbd9fcb1fed3f141ddeda2a2e1d1 | C++ | fsq/leetcode | /2315. Count Asterisks.cpp | UTF-8 | 410 | 2.859375 | 3 | [] | no_license | class Solution {
public:
int countAsterisks(string s) {
int ans = count(s.begin(), s.end(), '*');
for (int j=0, i=0; i<s.size(); )
if (s[i] != '|')
++i;
else {
for (j=i+1; j<s.size() && s[j]!='|'; ++j) {
if (s[j]=='*') --ans;
}
i = j + 1;
}
return ans;
}
}; | true |
410ed81dc9650074d7e069159f9b4a6e8096a594 | C++ | dinuionica08/Projects.Cpp | /TicTacToe Game/main.cpp | UTF-8 | 4,626 | 3.171875 | 3 | [] | no_license | //tic tac toe game version 1.1
#include <iostream>
#include <windows.h>
using namespace std;
char matrix[3][3] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
char player = 'X';
int a, n;
void draw()
{
system("color 1a");
system("cls");
cout << "--------------------------------------------------------------------------------" << endl << endl;
cout << " T I C T A C T O E G A M E " << endl << endl;
cout << " F I R S T P L A Y E R: X " << endl << endl;
cout << " S E C O N D P L A Y E R: Y " << endl << endl;
cout << "--------------------------------------------------------------------------------" << endl << endl;
for (int i = 0; i < 3; i++)
{
cout << " ";
for (int j = 0; j < 3; j++)
{
cout << "| ";
cout << "__" << matrix[i][j] << "__";
}
cout << "| " << endl;
}
cout << endl;
}
void input()
{
cout << "Enter the field do you want to change : ";
cin >> a;
if (a == 1)
{
if (matrix[0][0] == ' ')
matrix[0][0] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 2)
{
if (matrix[0][1] == ' ')
matrix[0][1] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 3)
{
if (matrix[0][2] == ' ')
matrix[0][2] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 4)
{
if (matrix[1][0] == ' ')
matrix[1][0] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 5)
{
if (matrix[1][1] == ' ')
matrix[1][1] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 6)
{
if (matrix[1][2] == ' ')
matrix[1][2] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 7)
{
if (matrix[2][0] == ' ')
matrix[2][0] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 8)
{
if (matrix[2][1] == ' ')
matrix[2][1] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
else if (a == 9)
{
if (matrix[2][2] == ' ')
matrix[2][2] = player;
else
{
cout << "This fiel is already use,try again..." << endl;
input();
}
}
}
char change_player()
{
if (player == 'X')
{
player = 'O';
cout << "It is the turn of the Player O" << endl;
}
else
{
player = 'X';
cout << "It is the turn of the Player X" << endl;
}
return player;
}
char logic()
{
// 00 01 02
// 10 11 12
// 20 21 22
// IF X WIN
if (matrix[0][0] == 'X' && matrix[0][1] == 'X' && matrix[0][2] == 'X')
return 'X';
if (matrix[1][0] == 'X' && matrix[1][1] == 'X' && matrix[1][2] == 'X')
return 'X';
if (matrix[2][0] == 'X' && matrix[2][1] == 'X' && matrix[2][2] == 'X')
return 'X';
if (matrix[0][0] == 'X' && matrix[1][0] == 'X' && matrix[2][0] == 'X')
return 'X';
if (matrix[0][1] == 'X' && matrix[1][1] == 'X' && matrix[2][1] == 'X')
return 'X';
if (matrix[0][2] == 'X' && matrix[1][2] == 'X' && matrix[2][2] == 'X')
return 'X';
if (matrix[0][0] == 'X' && matrix[1][1] == 'X' && matrix[2][2] == 'X')
//IF O WIN
if (matrix[0][0] == 'O' && matrix[1][1] == 'O' && matrix[2][2] == 'O')
return 'O';
if (matrix[0][0] == 'O' && matrix[1][0] == 'O' && matrix[2][0] == 'O')
return 'O';
if (matrix[0][2] == 'O' && matrix[1][2] == 'O' && matrix[2][2] == 'O')
return 'O';
if (matrix[1][0] == 'O' && matrix[1][1] == 'O' && matrix[1][2] == 'O')
return 'O';
if (matrix[2][0] == 'O' && matrix[2][1] == 'O' && matrix[2][2] == 'O')
return 'O';
if (matrix[0][0] == 'O' && matrix[1][1] == 'O' && matrix[2][2] == 'O')
return 'O';
if (matrix[0][2] == 'O' && matrix[1][1] == 'O' && matrix[2][0] == 'O')
return 'O';
return 'd';
}
int main()
{
n = 0;
draw();
while (1)
{
n++;
input();
draw();
if (logic() == 'X')
{
cout << "Player X wins" << endl;
break;
}
else if (logic() == 'O')
{
cout << "Player O wins";
break;
}
else if (logic() == 'd' && n == 9)
{
cout << "It is a draw" << endl;
break;
}
change_player();
}
return 0;
}
| true |
c743f39940263df8a095448d6ec7faefa66ebada | C++ | doyubkim/fluid-engine-dev | /src/tests/unit_tests/animation_tests.cpp | UTF-8 | 882 | 2.5625 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <jet/animation.h>
#include <gtest/gtest.h>
using namespace jet;
TEST(Frame, Constructors) {
Frame frame;
EXPECT_EQ(0, frame.index);
EXPECT_DOUBLE_EQ(1.0 / 60.0, frame.timeIntervalInSeconds);
}
TEST(Frame, TimeInSeconds) {
Frame frame;
frame.index = 180;
EXPECT_DOUBLE_EQ(3.0, frame.timeInSeconds());
}
TEST(Frame, Advance) {
Frame frame;
frame.index = 45;
for (int i = 0; i < 9; ++i) {
frame.advance();
}
EXPECT_EQ(54, frame.index);
frame.advance(23);
EXPECT_EQ(77, frame.index);
EXPECT_EQ(78, (++frame).index);
EXPECT_EQ(78, (frame++).index);
EXPECT_EQ(79, frame.index);
}
| true |
47b7f7c71be5be8c66d81d69999fdbcdc04de3ad | C++ | danniekot/programming | /Practice/05/C++/05/05/05.cpp | UTF-8 | 667 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL, "RUSSIAN");
cout << "Введите начальную точку, начальную скорость и время падения предмета\n";
double x0, v0, t, xt; // Именно double, поскольку физические величины редко бывают целыми.
cin >> x0 >> v0 >> t;
xt = x0 + v0 * t - 9.8 * t * t / 2; // Данный вариант верный, поскольку в другом варианте последний член равен 0 в связи с делением целой 1 на целую 2.
cout << abs(xt - x0);
} | true |
5bfd348d99801310ac645880b3a6ddb428dd8d5a | C++ | anorange7417/BOJ-PS | /2133/2133.cpp | UTF-8 | 407 | 3.015625 | 3 | [] | no_license | /*
1차원 dp식으로도 풀 수 있습니다
*/
#include <iostream>
using namespace std;
int n;
int d[100]={0};
int main(){
cin >> n;
d[0]=1;
d[1]=0;
d[2]=3;
for (int i=4 ; i<=n ; i++){
if (i%2!=0)continue; //홀수면 패스
d[i]= d[i-2]*3;
for(int j=4;j<=i;j+=2){
d[i]+=2*d[i-j];
}
}
cout<<d[n]<<endl;
}
| true |
af96155609b6105fb6d0cadac12234db03748394 | C++ | umangdhiman/LeetCode | /26. Remove Duplicates from Sorted Array.cpp | UTF-8 | 423 | 2.921875 | 3 | [] | no_license | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int i,len=nums.size();
if(nums.size()==0)
return 0;
if(nums.size()==1)
return 1;
for(i=0;i<nums.size()-1;){
if(nums[i]==nums[i+1]){
nums.erase(nums.begin()+i+1);
len--;
}
else i++;
}
return len;
}
};
| true |
e92fcba0e4f316b7cc8eeb3d847a5981aefe41f8 | C++ | FeronCompany/WebServer | /commlib/db/MySQLPool.cpp | UTF-8 | 1,878 | 2.546875 | 3 | [] | no_license |
#include "MacroAssemble.h"
#include "Exception.h"
#include "MySQLPool.h"
namespace CWSLib
{
MySQLConnectionPool::MySQLConnectionPool()
{
mConnIndex = 0;
}
MySQLConnectionPool::~MySQLConnectionPool()
{
std::lock_guard<std::mutex> guard(mConnLock);
for (auto conn : mConnList)
{
mysql_close(conn.get());
}
}
void MySQLConnectionPool::init(
const std::string& ip,
const uint32_t port,
const std::string& user,
const std::string& passwd,
const std::string& db,
const uint32_t min_size)
{
for (uint32_t i = 0; i < min_size; i++)
{
MYSQL* mysqlPtr = new MYSQL();
mysql_init(mysqlPtr);
bool reconnect = true;
mysql_options(mysqlPtr, MYSQL_OPT_RECONNECT, &reconnect);
if (!mysql_real_connect(mysqlPtr, ip.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, NULL, CLIENT_FOUND_ROWS))
{
ERROR_LOG("Failed to connect to database, %s", mysql_error(mysqlPtr));
throw Exception(-1, mysql_error(mysqlPtr));
}
else
{
mConnList.push_back(std::shared_ptr<MYSQL>(mysqlPtr));
}
}
}
MYSQL* MySQLConnectionPool::getConnection()
{
std::lock_guard<std::mutex> guard(mConnLock);
if (mConnList.size() == 0)
{
ERROR_LOG("Connection pool is empty!");
throw Exception(-2, "Connection pool is empty");
}
if (mConnIndex >= mConnList.size())
{
mConnIndex = 0;
}
MYSQL* conn = mConnList[mConnIndex].get();
mConnIndex++;
return conn;
}
int MySQLConnectionPool::getSize()
{
return mConnList.size();
}
} // namespace CWSLib
| true |
6332fe6dd68664ea7ad7a97f894bd5dbf63e377f | C++ | WIZARD-CXY/pp | /1011.cpp | UTF-8 | 1,188 | 2.765625 | 3 | [] | no_license | /*************************************************************************
> File Name: 1011.cpp
> Author: Wizard
> Mail: wizard_cxy@hotmail.com
> Created Time: Wed 12 Feb 2014 09:54:26 PM CST
************************************************************************/
#include <iostream>
using namespace std;
#include <cstdio>
int main(){
double max1=-1,max2=-1,max3=-1;
double a[3];
int maxIndex1=0;
for(int j=0; j<3; j++){
cin>>a[j];
if(max1<a[j]){
max1=a[j];
maxIndex1=j;
}
}
if(maxIndex1==0) cout<<"W ";
else if(maxIndex1==1) cout<<"T ";
else cout<<"L ";
int maxIndex2=0;
for(int j=0; j<3; j++){
cin>>a[j];
if(max2<a[j]){
max2=a[j];
maxIndex2=j;
}
}
if(maxIndex2==0) cout<<"W ";
else if(maxIndex2==1) cout<<"T ";
else cout<<"L ";
int maxIndex3=0;
for(int j=0; j<3; j++){
cin>>a[j];
if(max3<a[j]){
max3=a[j];
maxIndex3=j;
}
}
if(maxIndex3==0) cout<<"W ";
else if(maxIndex3==1) cout<<"T ";
else cout<<"L ";
printf("%.2lf",(max1*max2*max3*0.65-1)*2);
}
| true |
a4072d526015907ccb2f25de5c6f653d41ed278f | C++ | mrparaszt/Suli_stuff | /rekurziv_atlag/main.cpp | UTF-8 | 2,192 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
float atlag(int n, int *a, int nr);
void beolvas(const char *c,int *n, int *a);
void kiir(int *n, int *a);
int mina(int n, int *a);
int lnko(int a, int b);
int sumo(int a);
int minx(int a);
void kiirx(int x);
int main()
{
const char *c = "input.txt";
int n=5, *a;
a = (int*) malloc (n * sizeof(int));
beolvas(c, &n, a);
kiir(&n, a);
cout<<"Atlag:"<<atlag(n, a, 0)<<"\n";
cout<<"minimum"<<mina(n, a)<<"\n";
cout<<"lnko"<<lnko(15, 5)<<"\n";
cout<<"sum:"<<sumo(15)<<"\n";
cout<<"min_szj:"<<minx(5447)<<"\n";
kiirx(175);
free(a);
return 0;
}
void beolvas(const char *c,int *n, int *a)
{
ifstream f;
f.open(c);
f >> *n;
for (int i = 0 ; i< *n; ++i)
{
f >> a[i];
}
f.close();
}
void kiir(int *n, int *a)
{
for (int i = 0; i < *n; ++i)
{
cout<<a[i]<<" ";
}
cout<<"\n";
}
float atlag(int n, int *a, int nr)
{
if (nr == 0)
return (atlag(n, a, nr+1) + a[nr]) / n;
if (n > nr+1)
return atlag(n, a, nr+1) + a[nr];
else
return a[n-1];
}
int mina(int n, int *a)
{
if (n > 1)
{
int x;
x = a[n-1];
if (mina(n-1, a) > x)
return x;
else
return mina(n-1, a);
}
if (n == 1)
return a[0];
}
int lnko(int a, int b)
{
if (a == b)
return a;
else
{
if (a > b)
return lnko(a-b, b);
else
return lnko(a, b-a);
}
}
int sumo(int a)
{
if (a % 10 == 0)
return a;
else
return sumo(a/10)+a % 10;
}
int minx(int a)
{
if (a % 10 == 0)
return a;
else
{
if (a % 10 < minx(a / 10))
return a % 10;
else
return a / 10 % 10;
}
}
void kiirx(int x)
{
if (x % 100 == 0)
{
cout<<x<<"\n";
return ;
}
else
{
cout<<x% 10<<"\n";
return kiirx(x / 10);
}
}
| true |
e2ad3cb5f90ed6be489dec7ccbe1dd89d5c8e324 | C++ | mcmonkey/cglory | /cglory/PlayerOwned.cpp | UTF-8 | 2,547 | 2.796875 | 3 | [] | no_license | #include "StdAfx.h"
#include "PlayerOwned.h"
#include "Cell.h"
#include "Map.h"
void PlayerOwned::setCell(Cell* c)
{
GameObject::setCell(c);
reevaluateVisibleCells();
}
Player* PlayerOwned::getOwner()
{
return owner;
}
bool PlayerOwned::isEnemy(PlayerOwned & other)
{
if(!other.getOwner() || !getOwner())
return true;
return other.getOwner()->isEnemy(*getOwner());
}
// Sets the player to p. Accepts NULL(0) as a way to remove this unit from the owner's roster.
void PlayerOwned::setOwner(Player* p)
{
if(owner)
{
blind(); // Removes old sight from old player.
owner->releaseObject(this);
}
owner = p;
grantVision(); // Adds sight for the new player.
}
// -_-
void PlayerOwned::reevaluateVisibleCells()
{
blind();
grantVision();
}
// Hides all cells from this unit.
// Multiple calls do nothing, as the visible cells vector is cleared.
void PlayerOwned::blind()
{
if(sightCanChange)
{
for(auto i = visibleCells.begin(); i < visibleCells.end(); i++)
{
(*i)->cell->removeSight(*owner);
}
visibleCells.clear();
}
}
// Reveals all the cells from this unit.
// Fails if no cell or player is set.
// Multiple do nothing.
void PlayerOwned::grantVision()
{
if(container && owner && visibleCells.size() == 0 && sightCanChange)
{
visibleCells = container->owner->reachableCells(container, sightRange, POwnedTraversalHelper(this, &PlayerOwned::visibilityTraverse));
for(auto i = visibleCells.begin(); i < visibleCells.end(); i++)
{
(*i)->cell->addSight(*owner);
}
}
}
void PlayerOwned::draw()
{
gSprite.color = owner && visibleTo(*PlayManager::getActivePlayer())? owner->getColor() : D3DXCOLOR(1, 1, 1, 1);
GameObject::draw();
D3DXVECTOR2 absPosition = -*Utility::camera + container->position;
RECT r = RECT();
r.left = absPosition.x;
r.top = absPosition.y;
r.right = r.left + Stats::getTilesize();
r.bottom = r.top + Stats::getTilesize();
}
void PlayerOwned::destroy()
{
GameObject::destroy();
setOwner(0x0);
}
PlayerOwned::PlayerOwned(void)
{
owner = 0x0;
sightRange = 0;
}
PlayerOwned::~PlayerOwned(void)
{
}
// *********************************** UnitTraversalHelper Methods **********************************
int POwnedTraversalHelper::cost(Cell* from, Cell* to)
{
return (*attachedUnit.*function)(from, to);
}
POwnedTraversalHelper::POwnedTraversalHelper(PlayerOwned* inAttached, PCostFunc inFunc)
{
attachedUnit = inAttached;
function = inFunc;
}
// Currently line of sight is very simple.
int PlayerOwned::visibilityTraverse(Cell* from, Cell* to)
{
return 1;
} | true |
edc2136f0d3e24c85eac26f2e15fd4d0ac66d38e | C++ | Temikmapper77/Coursera-WhiteBelt | /Week 04/Task 05 - Formatting tables/main.cpp | UTF-8 | 1,270 | 3.171875 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <vector>
using namespace std;
int main() {
ifstream input("input.txt");
string rows_string;
string cols_string;
string number;
vector<int> numbers{};
if (input) {
// getline(input, rows_string, ' ');
// getline(input, cols_string, '\n');
input >> rows_string >> cols_string;
input.ignore(1);
/* while (cols_string == "") {
getline(input, cols_string, '\n');
}
/* cout << rows_string;
cout << "\"" << cols_string << "\"";*/
int rows = atoi(rows_string.c_str());
int cols = atoi(cols_string.c_str());
for (int i = 0; i < rows; i++) {
for (int n = 0; n < cols-1; n++) {
getline(input, number, ',');
cout << setw(10) << number << ' ';
numbers.push_back(atoi(number.c_str()));
number = {};
}
getline(input, number, '\n');
cout << setw(10) << number << endl;
numbers.push_back(atoi(number.c_str()));
number = {};
}
/* unsigned int k = 0;
for (int i = 0; i < rows; i++) {
for (int n = 0; n < cols; n++) {
cout << setw(10) << numbers[k] << ' ';
if (n != cols - 1) {
cout << ' ';
}
++k;
}
if (k != numbers.size()) {
cout << endl;
}
}*/
}
return 0;
} | true |
1086855ee56caae5868d3396c1a67e4f866fb5fa | C++ | mayankamencherla/Data-Structures-and-Algorithms | /Data-Structures/Week-2/merging_tables.cpp | UTF-8 | 2,221 | 3.421875 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::max;
using std::vector;
struct DisjointSetsElement {
int size, parent, rank;
DisjointSetsElement(int size = 0, int parent = -1, int rank = 0):
size(size), parent(parent), rank(rank) {}
};
struct DisjointSets {
int size;
int max_table_size;
vector <DisjointSetsElement> sets;
// size variable initialized and sets is of size size!
DisjointSets(int size): size(size), max_table_size(0), sets(size) {
for (int i = 0; i < size; i++)
// each element has parent set to itself
// each sets[i] has its size initialized in the input
sets[i].parent = i;
}
int getParent(int i) {
// find parent and compress path
// converted to 0 based indexing
if(i != sets[i].parent)
sets[i].parent = getParent(sets[i].parent); // path compression
return sets[i].parent;
}
void merge(int destination, int source) {
int realDestination = getParent(destination);
int realSource = getParent(source);
if (realDestination != realSource) {
// merge two components
// use union by rank heuristic
// update max_table_size
// set source's parent to destinations parent
sets[realSource].parent = realDestination;
// increment size of destination
sets[realDestination].size += sets[realSource].size;
// set size of source to 0 as well
sets[realSource].size = 0;
//max_table_size = max(sets.begin().size,sets.end().size)
if(sets[realDestination].size > max_table_size)
max_table_size = sets[realDestination].size;
}
}
};
int main() {
int n, m;
cin >> n >> m;
DisjointSets tables(n);
for (int i=0; i<n; i++) {
cin >> tables.sets[i].size; // setting each elemeent's size = input
tables.max_table_size = max(tables.max_table_size, tables.sets[i].size);
}
for (int i = 0; i < m; i++) {
int destination, source;
cin >> destination >> source;
--destination;
--source;
tables.merge(destination, source);
cout << tables.max_table_size << endl;
}
return 0;
}
| true |