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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
210e35a5fb8babda0c58a22c99a3f939f1245f27 | C++ | robmayger/Neural-Net | /Net.cpp | UTF-8 | 10,435 | 2.671875 | 3 | [] | no_license | #include "Net.h"
#include "Neuron.h"
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
#include <fstream>
void Net::load_data() {
ifstream inputs;
inputs.open("C:/Users/Rob/Documents/Essex/NNaDL/NN/NN/In.csv");
if (!inputs.is_open())
{
cout << "***Error!***\n" << "Could Not Open Inputs File!\n";
}
ifstream outputs;
outputs.open("C:/Users/Rob/Documents/Essex/NNaDL/NN/NN/Out.csv");
if (!outputs.is_open())
{
cout << "***Error!***\n" << "Could Not Open Outputs File!\n";
}
string line;
string delimiter = ",";
while (getline(inputs, line))
{
trainInput1.push_back(stod(line.substr(0, line.find(delimiter))) / 5000);
trainInput2.push_back(stod(line.substr(line.find(delimiter) + 1, line.size())) / 5000);
}
while (getline(outputs, line))
{
trainOutput1.push_back((stod(line.substr(0, line.find(delimiter))) - 85) / 215);
trainOutput2.push_back((stod(line.substr(line.find(delimiter) + 1, line.size())) - 85) / 215);
}
ifstream testInputs;
testInputs.open("C:/Users/Rob/Documents/Essex/NNaDL/NN/NN/TestIn.csv");
if (!testInputs.is_open())
{
cout << "***Error!***\n" << "Could Not Open Inputs File!\n";
}
ifstream testOutputs;
testOutputs.open("C:/Users/Rob/Documents/Essex/NNaDL/NN/NN/TestOut.csv");
if (!testOutputs.is_open())
{
cout << "***Error!***\n" << "Could Not Open Outputs File!\n";
}
while (getline(testInputs, line))
{
testInput1.push_back(stod(line.substr(0, line.find(delimiter))) / 5000);
testInput2.push_back(stod(line.substr(line.find(delimiter) + 1, line.size())) / 5000);
}
while (getline(testOutputs, line))
{
testOutput1.push_back((stod(line.substr(0, line.find(delimiter))) -85 ) / 215);
testOutput2.push_back((stod(line.substr(line.find(delimiter) + 1, line.size())) - 85 ) / 215);
}
}
void Net::build_net(vector<int> &topology) {
for (int i = 0; i < topology.at(0) + 1; i++) {
inputLayer.push_back(Neuron(topology.at(1)));
inputLayer.back().setActivationFunction(actFunc);
}
for (int i = 0; i < topology.at(1) + 1; i++) {
hiddenLayer.push_back(Neuron(topology.at(2)));
hiddenLayer.back().setActivationFunction(actFunc);
}
for (int i = 0; i < topology.at(2); i++) {
outputLayer.push_back(Neuron(0));
outputLayer.back().setActivationFunction(actFunc);
}
inputLayer.at(0).val = 1;
hiddenLayer.at(0).val = 1;
printNet();
int in;
cin >> in;
}
void Net::assignInputVals(int index) {
vector<double> inputVals = getInputVals(index);
for (int i = 1; i < inputLayer.size(); i++) {
inputLayer.at(i).val = inputVals.at(i - 1);
}
}
void Net::feedForward() {
int num = epochNum;
double hi;
for (int i = 1; i < hiddenLayer.size(); i++) {
hi = 0;
for (int j = 0; j < inputLayer.size(); j++) {
hi += inputLayer.at(j).val * inputLayer.at(j).get_weight(i - 1);
}
hiddenLayer.at(i).activate(hi);
}
double yk;
for (int k = 0; k < outputLayer.size(); k++) {
yk = 0;
for (int i = 0; i < hiddenLayer.size(); i++) {
yk += hiddenLayer.at(i).val * hiddenLayer.at(i).get_weight(k);
}
outputLayer.at(k).activate(yk);
}
}
void Net::errorCheck() {
e1.push_back(expectedOut.at(0) - outputLayer.at(0).val);
e2.push_back(expectedOut.at(1) - outputLayer.at(1).val);
//cout << "============ERROR VALUES============\n";
//cout << "Error 1: " << e1.back() << " Error 2: " << e2.back() << "\n" << "\n";
}
void Net::outputGrads() {
if (actFunc == 1) { outputGradsLinear(); }
else if (actFunc == 2) { outputGradsRelu(); }
else if (actFunc == 3) { outputGradsSigmoid(); }
else if (actFunc == 4) { outputGradsTanh(); }
}
void Net::hiddenGrads() {
if (actFunc == 1) { hiddenGradsLinear(); }
else if (actFunc == 2) { hiddenGradsRelu(); }
else if (actFunc == 3) { hiddenGradsSigmoid(); }
else if (actFunc == 4) { hiddenGradsTanh(); }
}
void Net::outputGradsLinear() {
outputLayer.at(0).set_grad(e1.back());
outputLayer.at(1).set_grad(e2.back());
}
void Net::hiddenGradsLinear() {
double sum;
for (int i = 0; i < hiddenLayer.size(); i++) {
sum = 0;
for (int k = 0; k < outputLayer.size(); k++) {
sum += outputLayer.at(k).get_grad() * hiddenLayer.at(i).get_weight(k);
}
hiddenLayer.at(i).set_grad(sum);
}
}
void Net::outputGradsRelu() {
if (outputLayer.at(0).val > 0) {
outputLayer.at(0).set_grad(e1.back());
} else {
outputLayer.at(0).set_grad(0);
}
if (outputLayer.at(1).val > 0) {
outputLayer.at(1).set_grad(e2.back());
} else {
outputLayer.at(1).set_grad(0);
}
}
void Net::hiddenGradsRelu() {
double sum;
for (int i = 0; i < hiddenLayer.size(); i++) {
sum = 0;
if (hiddenLayer.at(i).val > 0) {
for (int k = 0; k < outputLayer.size(); k++) {
sum += outputLayer.at(k).get_grad() * hiddenLayer.at(i).get_weight(k);
}
hiddenLayer.at(i).set_grad(hiddenLayer.at(i).val * sum);
} else {
hiddenLayer.at(i).set_grad(0);
}
}
}
void Net::outputGradsSigmoid() {
outputLayer.at(0).set_grad(regParam * outputLayer.at(0).val * (1 - outputLayer.at(0).val) * e1.back());
outputLayer.at(1).set_grad(regParam * outputLayer.at(1).val * (1 - outputLayer.at(1).val) * e2.back());
}
void Net::hiddenGradsSigmoid() {
double sum;
for (int i = 0; i < hiddenLayer.size(); i++) {
sum = 0;
for (int k = 0; k < outputLayer.size(); k++) {
sum += outputLayer.at(k).get_grad() * hiddenLayer.at(i).get_weight(k);
}
hiddenLayer.at(i).set_grad(regParam * hiddenLayer.at(i).val * (1 - hiddenLayer.at(i).val) * sum);
}
}
void Net::outputGradsTanh() {
outputLayer.at(0).set_grad((1 - pow(outputLayer.at(0).val, 2)) * e1.back());
outputLayer.at(1).set_grad((1 - pow(outputLayer.at(1).val, 2)) * e2.back());
}
void Net::hiddenGradsTanh() {
double sum;
for (int i = 0; i < hiddenLayer.size(); i++) {
sum = 0;
for (int k = 0; k < outputLayer.size(); k++) {
sum += outputLayer.at(k).get_grad() * hiddenLayer.at(i).get_weight(k);
}
hiddenLayer.at(i).set_grad((1 - pow(hiddenLayer.at(i).val, 2)) * sum);
}
}
void Net::updateweights() {
double change;
for (int i = 0; i < hiddenLayer.size(); i++) {
for (int k = 0; k < outputLayer.size(); k++) {
change = lRate * outputLayer.at(k).get_grad() * hiddenLayer.at(i).val;
hiddenLayer.at(i).change_weight(k, change);
}
}
for (int j = 0; j < inputLayer.size(); j++) {
for (int i = 0; i < hiddenLayer.size() - 1; i++) {
change = lRate * hiddenLayer.at(i).get_grad() * inputLayer.at(j).val;
inputLayer.at(j).change_weight(i, change);
}
}
}
void Net::printNet() {
cout << "============CURRENT STATE============\n";
for (int j = 0; j < inputLayer.size(); j++) {
cout << "Neuron " << j << ": Value:" << inputLayer.at(j).val
<< " Gradient:" << inputLayer.at(j).get_grad() << "\n";
cout << "Weights:\n";
for (int i = 0; i < hiddenLayer.size() - 1; i++) {
cout << i << ": " << inputLayer.at(j).get_weight(i) << "\n";
}
cout << "\n";
}
for (int i = 0; i < hiddenLayer.size(); i++) {
cout << "Neuron " << i + inputLayer.size() << ": Value:"
<< hiddenLayer.at(i).val << " Gradient:"
<< hiddenLayer.at(i).get_grad() << "\n";
cout << "Weights:\n";
for (int k = 0; k < outputLayer.size(); k++) {
cout << k << ": " << hiddenLayer.at(i).get_weight(k) << "\n";
}
cout << "\n";
}
for (int k = 0; k < outputLayer.size(); k++) {
cout << "Neuron " << k + inputLayer.size() + hiddenLayer.size()
<< ": Value:" << outputLayer.at(k).val << " Gradient:"
<< outputLayer.at(k).get_grad() << "\n";
cout << "\n";
}
}
void Net::printErrors() {
for (int i = 0; i < e1.size(); i++) {
cout << "Error1: " << e1.at(i) << " Error2: " << e2.at(i) << "\n";
}
}
double Net::calcRMSE() {
double sumE1 = 0;
double sumE2 = 0;
double rmsE;
for (int i = 0; i < e1.size(); i++) {
sumE1 += pow(e1.at(i), 2);
sumE2 += pow(e2.at(i), 2);
}
rmsE = (sqrt(sumE1 / e1.size()) + sqrt(sumE2 / e1.size())) / 2;
return rmsE;
}
void Net::clearData() {
//printNet();
input1.clear();
input2.clear();
output1.clear();
output2.clear();
e1.clear();
e2.clear();
}
void Net::net_train_cycle()
{
//printNet();
feedForward();
//printNet();
errorCheck();
outputGrads();
hiddenGrads();
//printNet();
updateweights();
//printNet();
}
void Net::train() {
input1 = trainInput1;
input2 = trainInput2;
output1 = trainOutput1;
output2 = trainOutput2;
for (int i = 0; i < getDataSize(); i++) {
assignInputVals(i);
assignOutputVals(i);
net_train_cycle();
}
//printErrors();
cout << "Train RMSE: " << calcRMSE() << "\n";
}
void Net::net_test_cycle()
{
//printNet();
feedForward();
//printNet();
errorCheck();
}
void Net::test() {
input1 = testInput1;
input2 = testInput2;
output1 = testOutput1;
output2 = testOutput2;
for (int i = 0; i < getDataSize(); i++) {
assignInputVals(i);
assignOutputVals(i);
net_test_cycle();
}
double rmse = calcRMSE();
if (rmse < bestRMSE)
{
bestRMSE = rmse;
saveWeights();
}
cout << "Test RMSE: " << rmse << "\n";
}
vector <double> Net::net_run_cycle(double x1, double x2)
{
inputLayer.at(1).val = x1;
inputLayer.at(2).val = x2;
feedForward();
return{ outputLayer.at(0).val, outputLayer.at(1).val };
}
void Net::saveWeights()
{
bestInputWeights.clear();
bestHiddenWeights.clear();
vector<double> temp;
for (int i = 0; i < inputLayer.size(); i++)
{
for (int j = 0; j < hiddenLayer.size() - 1; j++)
{
temp.push_back(inputLayer.at(i).get_weight(j));
}
bestInputWeights.push_back(temp);
temp.clear();
}
for (int j = 0; j < hiddenLayer.size(); j++)
{
for (int k = 0; k < outputLayer.size(); k++)
{
temp.push_back(hiddenLayer.at(j).get_weight(k));
}
bestHiddenWeights.push_back(temp);
temp.clear();
}
}
void Net::set_best_weights()
{
for (int i = 0; i < inputLayer.size(); i++)
{
for (int j = 0; j < hiddenLayer.size() - 1; j++)
{
inputLayer.at(i).set_weight(j, bestInputWeights.at(i).at(j));
}
}
for (int j = 0; j < hiddenLayer.size(); j++)
{
for (int k = 0; k < outputLayer.size(); k++)
{
hiddenLayer.at(j).set_weight(k, bestHiddenWeights.at(j).at(k));
}
}
}
| true |
af33d2ffed51713b8fc2f7ae159eb80794fd65e5 | C++ | DhruvSharma845/topcoder | /cpp/health_food_3118.cpp | UTF-8 | 6,872 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
class HealthFood {
private:
auto findMeal(std::string diet, int dietIndex, std::vector<int>& protein, std::vector<int>& carbs, std::vector<int>& fat, std::vector<int>& calories, std::vector<int>& positions) -> int {
std::vector<int> filteredProtein;
std::vector<int> filteredCarb;
std::vector<int> filteredFat;
std::vector<int> filteredCal;
std::vector<int> filteredPos;
switch(diet[dietIndex]) {
case 'C': {
auto maxCarb = std::max_element(carbs.begin(), carbs.end());
for (size_t i = 0; i < protein.size(); i++) {
if(carbs[i] == *maxCarb) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
case 'c': {
auto minCarb = std::min_element(carbs.begin(), carbs.end());
for (size_t i = 0; i < protein.size(); i++) {
if(carbs[i] == *minCarb) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
case 'P': {
auto maxPro = std::max_element(protein.begin(), protein.end());
for (size_t i = 0; i < protein.size(); i++) {
if(protein[i] == *maxPro) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
case 'p': {
auto minPro = std::min_element(protein.begin(), protein.end());
for (size_t i = 0; i < protein.size(); i++) {
if(protein[i] == *minPro) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
case 'F': {
auto maxFat = std::max_element(fat.begin(), fat.end());
for (size_t i = 0; i < protein.size(); i++) {
if(fat[i] == *maxFat) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
case 'f': {
auto minFat = std::min_element(fat.begin(), fat.end());
for (size_t i = 0; i < protein.size(); i++) {
if(fat[i] == *minFat) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
case 'T': {
auto maxCal = std::max_element(calories.begin(), calories.end());
for (size_t i = 0; i < protein.size(); i++) {
if(calories[i] == *maxCal) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
case 't': {
auto minCal = std::min_element(calories.begin(), calories.end());
for (size_t i = 0; i < protein.size(); i++) {
if(calories[i] == *minCal) {
filteredProtein.push_back(protein[i]);
filteredCarb.push_back(carbs[i]);
filteredFat.push_back(fat[i]);
filteredPos.push_back(positions[i]);
filteredCal.push_back(calories[i]);
}
}
break;
}
}
if(filteredPos.size() == 1) {
return filteredPos[0];
}
else if(dietIndex == diet.length() - 1) {
return filteredPos[0];
}
else {
return findMeal(diet, dietIndex + 1, filteredProtein, filteredCarb, filteredFat, filteredCal, filteredPos);
}
}
public:
std::vector<int> selectMeals(std::vector<int>& protein, std::vector<int>& carbs, std::vector<int>& fat, std::vector<std::string>& dietPlans) {
std::vector<int> calories(protein.size(), 0);
for (size_t i = 0; i < protein.size(); i++) {
calories[i] = (protein[i] + carbs[i]) * 5 + fat[i] * 9;
}
std::vector<int> positions(protein.size(), 0);
for (size_t i = 0; i < protein.size(); i++) {
positions[i] = i;
}
std::vector<int> indices;
for(const auto& diet: dietPlans) {
int index = 0;
if(diet.length() != 0) {
index = findMeal(diet, 0, protein, carbs, fat, calories, positions);
}
indices.push_back(index);
}
return indices;
}
};
auto main() -> int {
HealthFood hf;
std::vector<int> p{18, 86, 76, 0, 34, 30, 95, 12, 21};
std::vector<int> c{26, 56, 3, 45, 88, 0, 10, 27, 53};
std::vector<int> f{93, 96, 13, 95, 98, 18, 59, 49, 86};
std::vector<std::string> dp{"f", "Pt", "PT", "fT", "Cp", "C", "t", "", "cCp", "ttp", "PCFt", "P", "pCt", "cP", "Pc"};
std::vector<int> res = hf.selectMeals(p, c, f, dp);
std::copy(res.begin(), res.end(), std::ostream_iterator<int>(std::cout, " "));
} | true |
9dc9c3541cfd9b5c08ddf93702ee9a758193ab0e | C++ | Workspace2110/University_Arduino | /單晶片系統實作/作業2_1071_3B_王政弘/Source Codes/hw02_1/hw02_1.ino | UTF-8 | 1,836 | 3.171875 | 3 | [] | no_license | /*
Coded by Jheng-Hong Wang (2018)
E-mail : workspace2110@gmail.com
Description:
題目: 數位時鐘(基本版)
接腳:
P11B(1~4) : 分別接微控板的 2 、3 、4 、5 腳
P11A(a~g) : 分別接微控板的 6 、7 、8 、9 、10 、11 、12 腳
P14 : 接微控板的 13 腳
DD : 接微控板的 A0 腳
P5-1 : 接微控板的 A1 腳
P6-5~P6-8 : 分別接微控板的 A2 、A3 、A4 、A5 腳
P6-1 : 接GND(低態動作)
功能:
(1)具有調整時、分的功能
(2)每隔5分鐘從蜂鳴器發出聲音
(3)每小時發出一段簡短音樂報時
*/
// Include library(s):
#include "Clock.h" //My library : 處理時鐘運作作業(詳情請看header檔)
//--------------------------------------------
// Declare variables:
// Output pins:
const int scan[] = {2, 3, 4, 5}; // 宣告掃描信號接腳
const int SEG[] = {6, 7, 8, 9, 10, 11, 12}; // 宣告顯示信號接腳(g~a)
const int BZ = 13; // 宣告蜂鳴器接腳
const int DD = A0; // 宣告閃秒LED接腳(":")
// ===========================================
// Input pins
const int DIPSW[] = {A1}; // 宣告指撥開關接腳
const int PB[] = {A2, A3, A4, A5}; // 宣告按鍵接腳
// ===========================================
// Data:
Clock* clock; // 宣告時鐘物件
// ===========================================
//--------------------------------------------
// Initializing system
void setup(){
clock = new Clock(SEG, scan, PB, 4, DIPSW, 1, BZ, DD); //Instance clock
}
//--------------------------------------------
// Main function
void loop(){
clock->runWork();// run clock
}
//--------------------------------------------
| true |
f916fded01d9adee8d3a72d6ba71e56eb651dac2 | C++ | draaronv/daily_programs | /leetcode/number_good_pairs/main.cpp | UTF-8 | 336 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int numIdenticalPairs(vector<int>&nums)
{
int count=0;
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
{
if(nums[i]==nums[j])
{
count++;
}
}
}
return count;
}
int main()
{
vector<int> nums={1,1,1,1};
cout<<numIdenticalPairs(nums)<<endl;
return 0;
}
| true |
c3408cac6e9882a4ffc32ff16e3ae75ed5024d17 | C++ | Adriantega12/PPD-Algoritmos | /line.cpp | UTF-8 | 2,309 | 3.375 | 3 | [] | no_license | #include "line.h"
// Recta dada una pendiente y una ordenada al origen
Line::Line(double _m, int _b, std::string _l) :
m(_m), b(_b), label(_l) { }
// Recta punto-pendiente
Line::Line(double m, int x, int y) :
Line(m, b = Line::calculateYCross(x, y, m)) { }
// Recta con dos puntos
Line::Line(int x1, int y1, int x2, int y2) :
Line( m = Line::calculateSlope(x1, y1, x2, y2), x1, y1) { }
// Recta paralela con ordenada al origen relativa
Line::Line(Line& l, int offset) :
Line(l.m, l.b + offset) { }
// Recta perpendicular que pasa por un punto definido de otra recta
Line::Line(Line& l, int x, int y) :
Line(Line::calculatePerpendicularSlope(l.m), x, y) { }
// Getters
double Line::getSlope() {
return m;
}
int Line::getYCross() {
return b;
}
// Setters
void Line::setSlope(double _m) {
m = _m;
}
void Line::setYCross(int _b) {
b = _b;
}
// Funciones útiles dada una recta definida
int Line::getY(int x) {
// y = mx + b
return m * x + b;
}
int Line::getX(int y) {
// x = (y - b) / m
return (y - b) / m;
}
void Line::setLabel(std::string str) {
label = str;
}
std::string Line::getLabel() {
return label;
}
// Obtener punto en X de intersección con otra línea
int Line::getIntersectPoint(Line& l) {
// y1 = m1x + b1
// y2 = m2x + b2
// m1x + b1 = m2x + b2
// m1x - m2x = b2 - b1
// x(m1 - m2) = b2 - b1
// x = (b2 - b1)/(m1 - m2)
return (l.b - b)/(m - l.m);
}
void Line::draw( cv::Mat& img, cv::Scalar color ) {
cv::line( img,
cv::Point( getX( getYCross() ), getYCross() ),
cv::Point( img.cols, getY( img.cols ) ),
color
);
/*
cv::putText( img, label, cv::Point( img.rows, getY( img.rows ) ),
cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0xFF, 0xFF, 0xFF), 1, 8, false);
cv::putText( img, label, cv::Point( getX( 0 ), 0 ),
cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0xFF, 0xFF, 0xFF), 1, 8);
*/
}
// Funciones útiles donde una recta no está definida
double Line::calculateSlope(int x1, int y1, int x2, int y2) {
// m = (y2 - y1) / (x2 - x1)
return (double)(y2 - y1) / (x2 - x1);
}
int Line::calculateYCross(int x, int y, double m) {
// y = mx + b
// b = y - mx
return y - m * x;
}
double Line::calculatePerpendicularSlope(double m) {
// m1 * m2 = -1
// m1 = -1 / m2
return -1 / m;
}
| true |
3a77dcfd3c98fe1f2cc8a7f442566db5116aba39 | C++ | LunevAE/blackjack | /blackjack/deck.cpp | UTF-8 | 789 | 3.296875 | 3 | [] | no_license | #include "deck.h"
#include <random>
#include <iostream>
deck::deck()
{
cards.reserve(52);
createDeck();
}
deck::~deck()
{}
void deck::createDeck()
{
clear();
for (int s = card::CLUBS; s <= card::SPADES; s++)
{
for (int r = card::ACE; r <= card::KING; r++)
{
add(new card(static_cast<card::rank>(r),
static_cast<card::suit>(s)));
}
}
}
void deck::shuffle()
{
random_shuffle(cards.begin(), cards.end());
}
void deck::deal(hand& h)
{
if (!cards.empty()) {
h.add(cards.back());
cards.pop_back();
}
else {
std::cout << "Out of cards. Unable to deal.";
}
}
void deck::additionalCards(genericPlayer& gp)
{
std::cout << std::endl;
while (!(gp.isBusted()) && gp.isHitting()) {
deal(gp);
std::cout << gp << std::endl;
if (gp.isBusted()) gp.bust();
}
}
| true |
736b5b229f4ac98f994c8ebeba1f530d448f66c9 | C++ | Lime5005/epitech-1 | /tek2/C++/Pool/cpp_d06/ex02/sickkoala.cpp | UTF-8 | 1,442 | 2.765625 | 3 | [] | no_license | /*
** sickkoala.cpp for cpp_d06 in /home/gogo/rendu/tek2/cpp_d06/ex02/sickkoala.cpp
**
** Made by Gauthier CLER
** Login <gauthier.cler@epitech.eu>
**
** Started on Mon Jan 09 14:14:19 2017 Gauthier CLER
** Last update Mon Jan 09 14:14:19 2017 Gauthier CLER
*/
#include <iostream>
#include <string>
#include <algorithm>
#include "sickkoala.h"
SickKoala::SickKoala(std::string name)
{
this->name = name;
}
std::string SickKoala::formatName()
{
return "Mr. " + this->name + ": ";
}
SickKoala::~SickKoala()
{
std::cout << this->formatName() << "Kreooogg!! Je suis gueriiii!" << std::endl;
}
void SickKoala::poke()
{
std::cout << this->formatName() << "Gooeeeeerrk!! :'(" << std::endl;
}
int SickKoala::takeDrug(std::string drug)
{
std::string lower = drug;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
if (lower == "mars") {
std::cout << this->formatName() << "Mars, et ca kreog!" << std::endl;
return true;
}else if (drug == "Buronzand"){
std::cout << this->formatName() << "Et la fatigue a fait son temps!" << std::endl;
return true;
}
std::cout << this->formatName() << "Goerkreog!" << std::endl;
return false;
}
void SickKoala::overDrive(std::string string)
{
std::string replaced;
size_t foundRet = 0;
replaced = string;
while ((foundRet = replaced.find("Kreog!")) != std::string::npos)
replaced.replace(foundRet, 6, "1337!");
std::cout << this->formatName() << replaced << std::endl;
} | true |
b794dc4395e8bf341e12b7873c265605bc2c63c7 | C++ | JuncoDH/CompetitiveProgramming | /Online_Judges/UVA/11402 - Ahoy, Pirates!.cpp | UTF-8 | 4,068 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
//#pragma GCC diagnostic ignored "-Wsign-compare"
using namespace std;
#define mp make_pair
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
#define fi first
#define se second
#define LSB(x) ((x) & (-(x)))
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
//This SegmentTree store the number of 1's in the binary string v. have 4 operations :
//in [al, qr] F: put 1's, E: put 0's, I: invert, S query how many 1's there are
vi tree, lazy;
string v;
void Build(int k, int l, int r) {
if(l == r) {tree[k] = v[l] == '1'; return;}
int mid = (l + r) >> 1;
Build(k<<1, l, mid);
Build(k<<1|1, mid + 1, r);
tree[k] = tree[k<<1] + tree[k<<1|1];
}
int Query(int k, int l, int r, int ql, int qr) {
if(lazy[k] == 1) {
tree[k] = r - l + 1;
if(l != r) lazy[k<<1] = lazy[k<<1|1] = 1;
}
else if(lazy[k] == 0) {
tree[k] = 0;
if(l != r) lazy[k<<1] = lazy[k<<1|1] = 0;
}
else if(lazy[k] == -1) {
tree[k] = r - l + 1 - tree[k];
if(l != r) {
if(lazy[k<<1] == -2) lazy[k<<1] = -1;
else if(lazy[k<<1] == -1) lazy[k<<1] = -2;
else if(lazy[k<<1] == 0) lazy[k<<1] = 1;
else lazy[k<<1] = 0;
if(lazy[k<<1|1] == -2) lazy[k<<1|1] = -1;
else if(lazy[k<<1|1] == -1) lazy[k<<1|1] = -2;
else if(lazy[k<<1|1] == 0) lazy[k<<1|1] = 1;
else lazy[k<<1|1] = 0;
}
}
lazy[k] = -2;
if(r < ql || qr < l) return 0;
if(ql <= l && r <= qr) return tree[k];
int mid = (l + r) >> 1;
int a = Query(k<<1, l, mid, ql, qr);
int b = Query(k<<1|1, mid + 1, r, ql, qr);
return a + b;
}
int Update(int k, int l, int r, int ql, int qr, char type) {
if(lazy[k] == 1) {
tree[k] = r - l + 1;
if(l != r) lazy[k<<1] = lazy[k<<1|1] = 1;
}
else if(lazy[k] == 0) {
tree[k] = 0;
if(l != r) lazy[k<<1] = lazy[k<<1|1] = 0;
}
else if(lazy[k] == -1) {
tree[k] = r - l + 1 - tree[k];
if(l != r) {
if(lazy[k<<1] == -2) lazy[k<<1] = -1;
else if(lazy[k<<1] == -1) lazy[k<<1] = -2;
else if(lazy[k<<1] == 0) lazy[k<<1] = 1;
else lazy[k<<1] = 0;
if(lazy[k<<1|1] == -2) lazy[k<<1|1] = -1;
else if(lazy[k<<1|1] == -1) lazy[k<<1|1] = -2;
else if(lazy[k<<1|1] == 0) lazy[k<<1|1] = 1;
else lazy[k<<1|1] = 0;
}
}
lazy[k] = -2;
if(r < ql || qr < l) return tree[k];
if(ql <= l && r <= qr) {
if(type == 'F') {
lazy[k] = 1;
return r - l + 1;
}
else if(type == 'E') return lazy[k] = 0;
else lazy[k] = -1;
return r - l + 1 - tree[k];
}
int mid = (l + r) >> 1;
int a = Update(k<<1, l, mid, ql, qr, type);
int b = Update(k<<1|1, mid + 1, r, ql, qr, type);
return tree[k] = a + b;
}
int main(){
ios::sync_with_stdio(false);
int n, m, t, j, i, q, nq, ql, qr, cases, z;
char type;
string s;
cin >> cases;
for(z = 1; z <= cases; ++z) {
cout << "Case " << z << ":\n";
cin >> m;
v = "";
for(i = 0; i < m; ++i) {
cin >> t;
cin >> s;
for(j = 0; j < t; ++j) v += s;
}
nq = 1;
n = v.length();
tree.assign(4 * n, 0);
lazy.assign(4 * n, -2);
Build(1, 0, n - 1);
cin >> q;
for(i = 0; i < q; ++i) {
cin >> type >> ql >> qr;
if(type == 'S') cout << "Q" << nq++ << ": " << Query(1, 0, n - 1, ql, qr) << "\n";
else Update(1, 0, n - 1, ql, qr, type);
}
}
return 0;
} | true |
5afad1eab1361ebe819410a0eab2f4814a048b6c | C++ | cokoyoh/cpp-pass-by-reference-using-pointers | /main.cpp | UTF-8 | 418 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
void cubeByReference(int*); //function prototype that takes a pointer
int main() {
int number{5};
cout << "The original value of number is " << number;
cubeByReference(&number);
cout << "\nThe new value of number is " << number << endl;
}
void cubeByReference(int* numberPointer) {
*numberPointer = *numberPointer * *numberPointer * *numberPointer;
}
| true |
eb6fdabda44dfbe72cbcd15cc52cd124de0260c6 | C++ | codingEzio/code_cpp_beginning_cpp17 | /Part_01/standalone_sizeof.cpp | UTF-8 | 409 | 3.59375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int height{50};
// Well.. Just use `sizeof()` is fine ...
cout << "The height occupies " << sizeof height << " bytes.\n"
<< "Type 'long long' occupies " << sizeof(long long) << " bytes.\n"
<< "The result of the expr 'height * height / 2' occupies "
<< sizeof(height * height / 2) << " bytes.\n"
<< endl;
} | true |
03aa4874098507f7287b95cece54d0ece5b64060 | C++ | Nurbain/CPOA | /csg/BoundingBox.h | UTF-8 | 2,177 | 3.421875 | 3 | [] | no_license | /**
* @author Nathan Urbain
* @date 22/11/2017
*/
#ifndef BOUNDINGBOX_H
#define BOUNDINGBOX_H
#include "../vectorMatrix/vector.h"
class BoundingBox{
protected:
// y _____p2
// | | |
// | | |
// | p1_____|
// |____________x
//
//
Vec2d pointMin; //p1
Vec2d pointMax; //p2
float largeur;
float hauteur;
public:
//Constructeur vide
BoundingBox();
/**
* @brief BoundingBox, constructeur par 4 points
* @param px, x bottom left
* @param py, y bottom left
* @param qx, x right top
* @param qy, y right top
*/
BoundingBox(const float px, const float py, const float qx, const float qy) {
pointMin = {px,py};
pointMax = {qx,qy};
largeur = qx - px ;
hauteur = qy-py ;
}
/**
* @brief BoundingBox, constructueur par 2 vecteurs s
* @param min, bottom left
* @param max, right top
*/
BoundingBox(const Vec2d& min, const Vec2d& max) {
pointMin = min;
pointMax = max;
largeur = max[0] - min[0] ;
hauteur = max[1] - min[1] ;
}
//Get/Set des 2 Vecteurs Min & Max
Vec2d getMin() const;
void setMin(Vec2d& point);
Vec2d getMax() const;
void setMax(Vec2d& point);
//Overload Operateur
BoundingBox operator=(const BoundingBox& box); //copy
BoundingBox operator+(const BoundingBox& box); //Union
BoundingBox operator-(const BoundingBox& box); //Différence
BoundingBox operator^(const BoundingBox& box); //Intersection
/**
* @brief isEmpty, Verifie si une bounding box est vide
* @return true si les points min & max sont egaux
*/
bool isEmpty();
/**
* @brief center, donne le centre de la bounding box
* @return Vec2d
*/
Vec2d center();
/**
* @brief isInBox, Regarde si un point est dans la bounding box
* @param point
* @return boolean
*/
bool isInBox(const Vec2d& point);
/**
* @brief addPoint, Agrandir la bounding box pour englober le point
* @param point
* @return
*/
BoundingBox addPoint(const Vec2d& point);
};
#endif
| true |
42092669793ed1c73554c883e2d249f2852209c4 | C++ | antsaukk/cpp-red | /week_5/priority_collection2.cpp | UTF-8 | 4,453 | 3.28125 | 3 | [] | no_license | #include "test_runner.h"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <memory>
#include <queue>
#include <map>
#include <cmath>
#include <utility>
#include <vector>
using namespace std;
template <typename T>
class PriorityCollection {
public:
using Id = size_t;/* identificator type */
PriorityCollection() : maxVal(make_pair(0u,0)) {} //def constr
void UpdateMax(Id id, int rating) {
if (maxVal.second < rating || (maxVal.second == rating && maxVal.first < id)) {
maxVal.first = id;
maxVal.second = rating;
}
}
void ClearMax() {
maxVal.first = 0u;
maxVal.second = 0;
}
void NewMax() {
ClearMax();
for (auto iter = priority.begin(); iter != priority.end(); ++iter) {
UpdateMax(iter->first, iter->second);
}
}
// Add object with zero priority
// using move semantics and return id
Id Add(T object) {
Id newId = collection.size(); //generate id
collection.push_back(move(object)); //move obect into collection
status.push_back(ALIVE); //update status
priority.insert((make_pair(newId, 0))); //update map
UpdateMax(newId, ZEROP);
return newId;
}
// Добавить все элементы диапазона [range_begin, range_end)
// с помощью перемещения, записав выданные им идентификаторы
// в диапазон [ids_begin, ...)
template <typename ObjInputIt, typename IdOutputIt>
void Add(ObjInputIt range_begin, ObjInputIt range_end, IdOutputIt ids_begin) {
for(auto it = range_begin; it != range_end; it++) {
Id nId = Add(move(*it));
*ids_begin = nId;
ids_begin++;
}
}
// Определить, принадлежит ли идентификатор какому-либо
// хранящемуся в контейнере объекту
bool IsValid(Id id) const {
return id > (status.size()-1) ? 0 : status[id];
}
// Получить объект по идентификатору
const T& Get(Id id) const {
return collection[id];
}
// Увеличить приоритет объекта на 1
void Promote(Id id) {
UpdateMax(id, ++priority.at(id));
}
// Получить объект с максимальным приоритетом и его приоритет
pair<const T&, int> GetMax() const {
return {collection[maxVal.first], maxVal.second};
}
// Аналогично GetMax, но удаляет элемент из контейнера
pair<T, int> PopMax() {
pair<Id, int> current_max = make_pair(maxVal.first, maxVal.second);
priority.erase(current_max.first);
status[current_max.first] = DEAD;
NewMax();
return make_pair(move(collection[current_max.first]), current_max.second);;
}
private:
// Приватные поля и методы
int ALIVE = 1;
int DEAD = 0;
int ZEROP = 0;
map<int, int> priority; // first index is identificator of max and second is priority
vector<T> collection; //identificator points to the respective index of element in the array
vector<int> status; //1 object with index id is alive 0 otherwise
pair<Id, int> maxVal; //store identificator and max value to fetch it quickly
};
class StringNonCopyable : public string {
public:
using string::string; // Позволяет использовать конструкторы строки
StringNonCopyable(const StringNonCopyable&) = delete;
StringNonCopyable(StringNonCopyable&&) = default;
StringNonCopyable& operator=(const StringNonCopyable&) = delete;
StringNonCopyable& operator=(StringNonCopyable&&) = default;
};
void TestNoCopy() {
PriorityCollection<StringNonCopyable> strings;
const auto white_id = strings.Add("white");
const auto yellow_id = strings.Add("yellow");
const auto red_id = strings.Add("red");
strings.Promote(yellow_id);
for (int i = 0; i < 2; ++i) {
strings.Promote(red_id);
}
strings.Promote(yellow_id);
{
const auto item = strings.PopMax();
ASSERT_EQUAL(item.first, "red");
ASSERT_EQUAL(item.second, 2);
}
{
const auto item = strings.PopMax();
ASSERT_EQUAL(item.first, "yellow");
ASSERT_EQUAL(item.second, 2);
}
{
const auto item = strings.PopMax();
ASSERT_EQUAL(item.first, "white");
ASSERT_EQUAL(item.second, 0);
}
cout << white_id << endl;
}
int main() {
TestRunner tr;
RUN_TEST(tr, TestNoCopy);
return 0;
}
| true |
86253c18a291c2089cbd510b04abeeb35134fded | C++ | MohabAyoub10/Problems-solutions | /Codeforces/A - Sereja and Dima.cpp | UTF-8 | 586 | 3.0625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, Spoints = 0, Dpoints = 0;
cin >> n;
deque<int> card;
for (int i = 0; i < n; ++i)
{
int x;
cin >> x;
card.push_back(x);
}
for (int i = 0; !card.empty(); ++i)
{
if (i % 2 == 0)
Spoints += max(card.front(), card.back());
else
Dpoints += max(card.front(), card.back());
if (card.front() > card.back())card.pop_front();
else card.pop_back();
}
cout << Spoints << " " << Dpoints;
}
| true |
7e5bdc7ff492f17fd3ccb7862adf68ecc13e2b04 | C++ | JoaoRMaia/URI | /Lista 1/12545.cc | UTF-8 | 266 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main () {
int n;
int moves;
string s1;
string s2;
cin >> n;
for ( int i = 0 ; i < n ; i++){
cin >> s1 >> s2;
cout << s1 << " " << s2 << endl;
}
return 0;
}
| true |
9c0c769cb8f14fdec7cd58979de8ec92d49e669e | C++ | ATEC-Mikas/programacao-cpp | /Mikas/FT 01/exercicio4.cpp | UTF-8 | 242 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
int x;
cout << "Digite um numero:";
cin >> x;
cout << "Antecedente: " + to_string(x-1) + "\nSucessor:" + to_string(x+1);
return 0;
}
| true |
fadc834c0b95d96e6abcc414feee6fd1cb34f639 | C++ | DT3264/ProgrammingContestsSolutions | /Codeforces/1257B.cpp | UTF-8 | 445 | 3.015625 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
int x, y;
bool can;
scanf("%d", &t);
while(t--){
can=true;
scanf("%d%d", &x, &y);
if(x==1 && y>1){
can=false;
}
if(x<=3 && y>3){
can=false;
}
printf("%s\n", (can ? "Yes" : "No"));
}
return 0;
} | true |
2dd2079f6ae3074c5adbff5cb7a5b50eb0f6a8a8 | C++ | Maddy0669/GeeksForGeeks-Problems | /Linked List/Detect loop in LL.cpp | UTF-8 | 324 | 2.765625 | 3 | [] | no_license | bool detectLoop(Node* head)
{
Node* slow=head;
Node* fast=head->next;
bool ans=false;
while(fast!=NULL and fast->next!=NULL and slow!=NULL){
if(fast==slow){
ans=true;
break;
}
fast=fast->next->next;
slow=slow->next;
}
return ans;
} | true |
72a860c1f3fe768467bf8cb43c79449cbfc03613 | C++ | HuangChiEn/open_datastructure | /main.cpp | UTF-8 | 1,286 | 2.65625 | 3 | [] | no_license | #include<iostream>
using std::cout;
#include<ctime>
#include<cstdlib>
#include<cstdint>
#include<string>
// DS-include
#include"header/DataStructure.h"
#include"source/DataStructure.cpp"
#include"testing/Blkbox_Tester.h"
int main(){
const uint32_t MAXLEN = 200;
const int32_t DIGRNG = 300;
srand(time(NULL));
int32_t* arr = uniform_data_gen(MAXLEN, DIGRNG);
//Sm_arr<int32_t> arr{11, 73, 21, 43, 85, 18, 26, 59, 10, 24};
AVL<int32_t> avl_tree;
//for(int idx=0 ; idx < MAXLEN ; ++idx)
// cout << " | " << arr[idx] << " ; ";
//cout << "\n\n" ;
for(int idx=0 ; idx < MAXLEN ; ++idx)
avl_tree.insert(arr[idx]);
avl_tree.BF_print();
cout << "\n\n\n";
avl_tree.remove(arr[0]);
avl_tree.remove(arr[2]);
avl_tree.remove(arr[4]);
//cout << "\n BFT Traversal \n " ;
avl_tree.BF_print();
cout << "done!";
return 0;
}
// TODO list -
/***************************************
* 0. Implement the remove function to the BST.
* 1. Test the adaptive extension & shrink function of hash_table.
* 2. Split the Hash_table definition and implementation into .h, .cpp respectively.
* 3. Design the abstract interface for each type of DS (e.g. lst type have same interface).
* 4. Design unit test class for the "container".
****************************************/ | true |
73facd8a2dc7f54ae725a4221c5fe96bfc2748a0 | C++ | jordsti/stigame | /StiGame/gui/ItemValue.h | UTF-8 | 390 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef ITEMVALUE_H
#define ITEMVALUE_H
#include "Item.h"
namespace StiGame
{
namespace Gui
{
enum ItemValueType {
IVT_Integer,
IVT_String,
IVT_ValueObject
};
class ItemValue
{
public:
ItemValue(Item *m_parent);
virtual ~ItemValue();
virtual ItemValueType getType(void) = 0;
Item* getParent(void);
private:
Item *parent;
};
}
}
#endif // ITEMVALUE_H
| true |
5b1f0d428b47f0d895040975f466b4cf10ee6256 | C++ | heechan3006/CS | /BOJ/BOJ_2331/BOJ_2331/소스.cpp | UTF-8 | 477 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#define MAX_N 300000
using namespace std;
int A, P;
int visited[MAX_N];
int ans;
int compute_num(int A, int P,int ans) {
if (A== 0) return ans;
compute_num(A / 10, P,ans+pow(A%10,P));
}
void dfs(int A) {
visited[A] += 1;
if (visited[A] == 3) return;
dfs(compute_num(A, P,0));
}
int main() {
cin >> A >> P;
dfs(A);
int cnt = 0;
for (int i = 0; i < MAX_N; i++) {
if (visited[i] == 1) {
cnt++;
}
}
printf("%d\n", cnt);
} | true |
21e8226c8b5452fbd5e21dba31d48a459e0a8315 | C++ | moevm/oop | /5382/lonchina/lab5/Figures/Rectangle.h | UTF-8 | 742 | 2.9375 | 3 | [] | no_license | #ifndef LONCHINA_RECTANGLE_H
#define LONCHINA_RECTANGLE_H
#include "AbstractShape.h"
#include "Point.h"
#include <vector>
#include <iostream>
#include <cmath>
class Rectangle: public AbstractShape
{
private:
std::vector<Point> coord;
Point center;
public:
// конструктор Треугольника
Rectangle(std::vector<Point> & coord, Point & center);
// вывод треугольника
void draw();
// сдвиг треугольника
void moveTo();
// поворот треугольника
void rotateOn(double angle);
// масштабирование треугольника
void scaleOn(double coef);
void calculateArea();
};
#endif //LONCHINA_RECTANGLE_H
| true |
94d314681a2636f7a97ece3c25f9674984bfa490 | C++ | rohitativy/turicreate | /src/platform/parallel/execute_task_in_native_thread.hpp | UTF-8 | 1,957 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef TURI_PARALLEL_EXECUTE_TASK_IN_NATIVE_THREAD_HPP
#define TURI_PARALLEL_EXECUTE_TASK_IN_NATIVE_THREAD_HPP
#include <functional>
namespace turi {
/**
* Takes a function and executes it in a native stack space.
* Used to get by some libjvm oddities when using coroutines / fibers.
*
* Returns an exception if an exception was thrown while executing the inner task.
* \ingroup threading
*/
std::exception_ptr execute_task_in_native_thread(const std::function<void(void)>& fn);
namespace native_exec_task_impl {
template <typename T>
struct value_type {
T ret;
T get_result() {
return ret;
}
template <typename F, typename ... Args>
void run_as_native(F f, Args... args) {
auto except = execute_task_in_native_thread([&](void)->void {
ret = f(args...);
});
if (except) std::rethrow_exception(except);
}
};
template <>
struct value_type<void> {
void get_result() { }
template <typename F, typename ... Args>
void run_as_native(F f, Args... args) {
auto except = execute_task_in_native_thread([&](void)->void {
f(args...);
});
if (except) std::rethrow_exception(except);
}
};
} // namespace native_exec_task_impl
/**
* Takes a function call and runs it in a native stack space.
* Used to get by some libjvm oddities when using coroutines / fibers.
*
* Returns an exception if an exception was thrown while executing the inner task.
*/
template <typename F, typename ... Args>
typename std::result_of<F(Args...)>::type run_as_native(F f, Args... args) {
native_exec_task_impl::value_type<typename std::result_of<F(Args...)>::type> result;
result.template run_as_native<F, Args...>(f, args...);
return result.get_result();
}
} // turicreate
#endif
| true |
b46bd09ce5b91777a4be216f60a11a44642f3987 | C++ | yao4ming/codeeval | /moderate/C++/RemoveCharacters/main.cpp | UTF-8 | 965 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
string trim(string str) {
string trimmedStr;
int i, j;
//trim left end
for (i= 0; i < str.size(); ++i) {
if (str[i] != ' ')
break;
}
trimmedStr = str.substr(i);
//trim right end
for (j = trimmedStr.size()-1; j >=0 ; --j) {
if (trimmedStr[j] != ' ')
break;
}
return trimmedStr.substr(0, j+1);
}
int main(int argc, char** argv) {
ifstream in(argv[1]);
string line;
while (getline(in, line)) {
stringstream ss(line);
string token;
vector<string> tokens;
while (getline(ss, token, ','))
tokens.push_back(trim(token));
for (int i = 0; i < tokens[0].size(); ++i) {
tokens[0].erase(remove(tokens[0].begin(), tokens[0].end(), tokens[1][i]), tokens[0].end());
}
cout << tokens[0] << endl;
}
}
| true |
ae11d29c65ad8782126ff3b4fdb3ac886b0318ca | C++ | LemonSpike/enigma | /reflector.cpp | UTF-8 | 2,063 | 3.28125 | 3 | [] | no_license | #include "reflector.h"
using namespace std;
int Reflector::read_reflector_config(const char *filename) {
ifstream input(filename);
if (input.fail()) {
err_stream << "Error opening reflector configuration file.";
return ERROR_OPENING_CONFIGURATION_FILE;
}
FileReader reader(err_stream);
int error_code = NO_ERROR;
int counter = 0;
while (!input.eof()) {
input >> ws;
if (input.peek() == EOF)
break;
int first_number = reader.read_number(input, error_code);
if (error_code != NO_ERROR)
return error_code;
input >> ws;
if (input.peek() == EOF) {
err_stream << "Incorrect (odd) number of parameters in reflector file ";
err_stream << "reflector.rf" << endl;
return INCORRECT_NUMBER_OF_REFLECTOR_PARAMETERS;
}
int second_number = reader.read_number(input, error_code);
if (error_code != NO_ERROR)
return error_code;
error_code = check_mapping(first_number, second_number);
if (error_code != NO_ERROR)
return error_code;
counter++;
}
if (counter < 13) {
err_stream << "Insufficient number of mappings in reflector file: ";
err_stream << "reflector.rf" << endl;
return INCORRECT_NUMBER_OF_REFLECTOR_PARAMETERS;
}
return NO_ERROR;
}
/**
* This checks the mapping doesn't contain duplicate mappings before updating
* the mapping array.
* @param first_number The number to be mapped.
* @param second_numbr The mapped number.
* @return check_mapping The error code is returned.
*/
int Reflector::check_mapping(int first_number, int second_number) {
if (mapping[first_number] != -1 || mapping[second_number] != -1 ||
first_number == second_number) {
err_stream << "The reflector configuration cannot have contacts mapped to ";
err_stream << "themselves or with more than one other contact." << endl;
return INVALID_REFLECTOR_MAPPING;
}
mapping[first_number] = second_number;
mapping[second_number] = first_number;
return NO_ERROR;
}
int Reflector::map_input(int input) {
return mapping[input];
}
| true |
02ce3a1800724fcd6785549ac33fe3abf275fd77 | C++ | lzabry/quantnet_cpp | /Level 1/Section 1.3/HW1.3/1.3.7/1.3.7/1.3.7.cpp | UTF-8 | 318 | 3.125 | 3 | [] | no_license | // 1.3.7.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <stdio.h>
void main()
{
int n=4;
int number=243;
int number2;
number2 = number << n;
printf("After mutiply %d by 2 to the power of %d, the final answer is %d", number, n, number2);
}
| true |
73c39d1d0d74b3c0f560b3bc34534e1b7535959c | C++ | PaulMcClernan/Forge | /CCommandNode.cpp | UTF-8 | 1,965 | 2.609375 | 3 | [
"Zlib"
] | permissive | /*
* CCommandNode.cpp
* HyperCompiler
*
* Created by Uli Kusterer on 10.05.07.
* Copyright 2007 M. Uli Kusterer. All rights reserved.
*
*/
#include "CCommandNode.h"
#include "CValueNode.h"
#include "CParseTree.h"
#include <assert.h>
#include "CNodeTransformation.h"
namespace Carlson
{
void CCommandNode::DebugPrint( std::ostream& destStream, size_t indentLevel )
{
INDENT_PREPARE(indentLevel);
destStream << indentChars << "Command \"" << mSymbolName << "\"" << std::endl
<< indentChars << "{" << std::endl;
std::vector<CValueNode*>::iterator itty;
for( itty = mParams.begin(); itty != mParams.end(); itty++ )
{
(*itty)->DebugPrint( destStream, indentLevel +1 );
}
destStream << indentChars << "}" << std::endl;
}
void CCommandNode::AddParam( CValueNode* val )
{
mParams.push_back( val );
mParseTree->NodeWasAdded(val);
}
void CCommandNode::Simplify()
{
CNode::Simplify();
std::vector<CValueNode*>::iterator itty;
for( itty = mParams.begin(); itty != mParams.end(); itty++ )
{
CValueNode * originalNode = *itty;
if( !originalNode )
continue;
originalNode->Simplify(); // Give subnodes a chance to apply transformations first. Might expose simpler sub-nodes we can then simplify.
CNode* newNode = CNodeTransformationBase::Apply( originalNode ); // Returns either originalNode, or a totally new object, in which case we delete the old one.
if( newNode != originalNode )
{
assert( dynamic_cast<CValueNode*>(newNode) != NULL );
*itty = (CValueNode*)newNode;
}
}
}
void CCommandNode::Visit( std::function<void(CNode*)> visitorBlock )
{
for( auto currParam : mParams )
{
if( currParam )
currParam->Visit( visitorBlock );
}
CNode::Visit( visitorBlock );
}
void CCommandNode::GenerateCode( CCodeBlock* inCodeBlock )
{
std::vector<CValueNode*>::iterator itty;
for( itty = mParams.begin(); itty != mParams.end(); itty++ )
{
(*itty)->GenerateCode( inCodeBlock );
}
}
} // namespace Carlson
| true |
71de3c941be96c026a41a15b8972ec33350ee828 | C++ | JohnLFX/COP3331-Final-Project | /myprogram/src/commands/CommandCreateNewUser.h | UTF-8 | 899 | 2.796875 | 3 | [
"MIT"
] | permissive | #ifndef INC_3331PROJECT_COMMANDCREATENEWUSER_H
#define INC_3331PROJECT_COMMANDCREATENEWUSER_H
#include "types/AuthenticatedCommand.h"
class CommandCreateNewUser : public Command {
public:
CommandCreateNewUser(FinalProject *finalProject) : Command(1, finalProject) {}
void execute() {
cout << "Enter the new username: ";
string username, password;
cin >> username;
cin.ignore();
password = this->promptForOptionalRandomPassword();
if (password.empty()) {
cout << "Enter password for the new user " << username << ": ";
cin.ignore(BC_STRING_MAX, '\n');
getline(cin, password);
cout << endl;
}
this->finalProject->authenticationDatabase.createUser(User(username, password));
}
};
#endif //INC_3331PROJECT_COMMANDCREATENEWUSER_H
| true |
42fdafa614dbf6400c227baebda82e33bf5fe238 | C++ | ailyanlu1/Contests | /DMOJ C++/dmopc16c3p6_long_lost_love/DMOPC16C3P6.cpp | UTF-8 | 3,218 | 2.609375 | 3 | [] | no_license | /*
* DMOPC16C3P6.cpp
*
* Created on: May 30, 2017
* Author: Wesley Leung
*/
#include <bits/stdc++.h>
#define MAXN 100000
#define MAXQ 500000
using namespace std;
int arr[MAXN + 1];
int revInd = 0;
int N, Q, x, y;
char c;
struct Node {
public:
Node* left;
Node* right;
int pre, suf, sum;
Node(int val) {
this->pre = val;
this->suf = val;
this->sum = val;
this->left = this->right = nullptr;
}
Node(Node* l, Node* r) {
this->left = l;
this->right = r;
this->pre = max(l->pre, r->pre + l->sum);
this->suf = max(l->suf + r->sum, r->suf);
this->sum = l->sum + r->sum;
}
}* rev[MAXQ];
struct Query {
public:
int pre, suf, sum;
bool isNull;
Query() {
this->pre = 0;
this->suf = 0;
this->sum = 0;
this->isNull = true;
}
Query(int pre, int suf, int sum) {
this->pre = pre;
this->suf = suf;
this->sum = sum;
this->isNull = false;
}
Query(Query l, Query r) {
this->pre = max(l.pre, r.pre + l.sum);
this->suf = max(l.suf + r.sum, r.suf);
this->sum = l.sum + r.sum;
this->isNull = false;
}
};
Node* build(int l, int r) {
if (l == r) return new Node(arr[l]);
int m = (l + r) >> 1;
return new Node(build(l , m), build(m + 1, r));
}
void init(int size) {
rev[0] = build(1, size);
}
Node* update(Node* cur, int l, int r, int ind) {
if (l <= ind && ind <= r) {
if (l == r) return new Node(arr[l]);
int m = (l + r) >> 1;
return new Node(update(cur->left, l, m, ind), update(cur->right, m + 1, r, ind));
}
return cur;
}
void update(int ind, int val) {
arr[ind] = val;
rev[revInd + 1] = update(rev[revInd], 1, N, ind);
revInd++;
}
Query query(Node* cur, int l, int r, int ql, int qr) {
if (l > qr || r < ql) return Query();
if (l >= ql && r <= qr) return Query(cur->pre, cur->suf, cur->sum);
int m = (l + r) >> 1;
Query left = query(cur->left, l, m, ql, qr);
Query right = query(cur->right, m + 1, r, ql, qr);
if (left.isNull) return right;
if (right.isNull) return left;
return Query(left, right);
}
int query(int type, int ql, int qr) {
if (type == 1) return query(rev[revInd], 1, N, ql, qr).pre;
return query(rev[revInd], 1, N, ql, qr).suf;
}
void revert(int x) {
rev[++revInd] = rev[x];
}
int main() {
scanf("%d", &N);
for (int i = 1; i <= N; i++) {
scanf("%d", &arr[i]);
}
scanf("%d", &Q);
init(N);
for (int i = 0; i < Q; i++) {
scanf("%c", &c);
if (c == 'U') {
scanf("%d%d", &x, &y);
update(x, y);
} else if (c == 'G') {
scanf("%d", &x);
revert(x);
} else if (c == 'P') {
scanf("%d%d", &x, &y);
printf("%d\n", query(1, x, y));
} else if (c == 'S') {
scanf("%d%d", &x, &y);
printf("%d\n", query(2, x, y));
} else {
i--;
}
}
return 0;
}
| true |
4b8b3f1b93db5af4e3fc559d7ad2f21a266a2406 | C++ | ritukeshbharali/ofeFRAC | /src/util/ObjectFactory.h | UTF-8 | 2,596 | 3.203125 | 3 | [] | no_license | /*
*
* Copyright (C) 2007 TU Delft. All rights reserved.
*
* This class implements a rather simple but generic object
* factory, following a column in gamedev.net.
*
* Usage:
*
* 1. Define a factory for a concrete super class:
*
* ObjectFactory<Material,int> MaterialFactory;
*
* 2. Register concrete classes to this factory
*
* MaterialFactory.register<HookeMaterial> (1);
*
* 3. When need to create an instance of HookeMaterial, then
*
* Material* HookeMaterial = MaterialFactory.create(1);
*
* Author: V.P. Nguyen, V.P.Nguyen@tudelft.nl
* Date: 30 August 2008
*
*/
#ifndef OBJECT_FACTORY_H
#define OBJECT_FACTORY_H
#include <map>
using std::map;
// -----------------------------------------------------------------------
// function CreateObject
// -----------------------------------------------------------------------
template <class BaseClass,
class ConcreteClass >
BaseClass* CreateObject ()
{
return new ConcreteClass ();
};
// -----------------------------------------------------------------------
// class ObjectFactory
// -----------------------------------------------------------------------
template <class BaseClass,
typename Identifier >
class ObjectFactory
{
public:
// -------------------------------------------------------------------
// some typedefs
// -------------------------------------------------------------------
typedef BaseClass* *() createObjectFunc;
typedef map<Identifier, createObjectFunc>::const_iterator cit;
typedef map<Identifier, createObjectFunc>::iterator it;
// -------------------------------------------------------------------
// register
// -------------------------------------------------------------------
template <class ConcreteClass>
bool register ( Identifier id )
{
cit iter = id2CreateMethodMap_.find ( id );
if ( iter != id2CreateMethodMap_.end () )
{
id2CreateMethodMap_[id] = &CreateObject<BaseClass,ConcreteClass> ( );
return true;
}
}
// -------------------------------------------------------------------
// create (id)
// -------------------------------------------------------------------
BaseClass* create ( Identifier id )
{
cit iter = id2CreateMethodMap_.find ( id );
if ( iter != id2CreateMethodMap_.end () )
{
return id2CreateMethodMap_[id].second ( );
}
}
protected:
private:
map<Identifier, createObjectFunc> id2CreateMethodMap_;
};
#endif
| true |
88f38b9cdaf9afa335dba48919967a60b26817dc | C++ | luiarthur/ucsc_litreview | /cytof/src/model3/sims/tests/bla.cpp | UTF-8 | 236 | 2.90625 | 3 | [] | no_license | #include <vector>
struct Bla {
Bla(int x, int y) : vec_x(2), vec_y(2) {
for (int z=0; z<2; z++) {
vec_x.resize(x);
vec_y.resize(y);
}
}
std::vector<int> vec_x;
std::vector<int> vec_y;
}
auto bla = Bla(3,5)
| true |
85bea85f5b709861eb14c72a7062b25db2e097c1 | C++ | ANKITPODDER2000/cpp | /basic/prog23.cpp | UTF-8 | 423 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int coef(int ,int );
int main()
{
int n,k;
cout << "Enter value of n & k = " ;
cin >> n >> k;
cout << "C(n,k) is : " << coef(n,k);
return 0;
}
int coef(int n,int k)
{
int matrix[n+1][k+1],i,j;
for(i=0;i<n+1;i++)
{
for(j=0; j<=i;j++)
{
if(j==0 || i==j)
matrix[i][j] = 1;
else
matrix[i][j] = matrix[i-1][j-1] + matrix[i-1][j];
}
}
return matrix[n][k];
} | true |
27e78817e0d1665049a0f1e754a330438a964a59 | C++ | FellowshipOfTheGame/Castella | /include/Input.hpp | UTF-8 | 668 | 2.828125 | 3 | [] | no_license | #ifndef INPUT_H
#define INPUT_H
#include <SDL/SDL.h>
//Handles the input
class Input
{
public:
enum InputValue{
NO_INPUT = 0,
UNDEFINED_INPUT,
QUIT,
MOUSE_LEFTCLICK,
};
public:
//Get the next input from the queue
static int get_input();
//Gets the mouse x and y coords into a SDL_Rect
static SDL_Rect get_mouse_offset();
//Finds out rather a key is pressed or not
static bool is_key_pressed(SDLKey key);
private:
static SDL_Event event;
//Stores mouse position
static int mouseX, mouseY;
};
#endif // INPUT_H
| true |
6678f0e81aaa5347a906a8b06e047712ae3059ed | C++ | Rthiskidw/Project1-CollegeTouring | /souvenirshop.cpp | UTF-8 | 4,810 | 2.625 | 3 | [] | no_license | #include "souvenirshop.h"
#include "ui_souvenirshop.h"
#include "endtour.h"
#include <QMessageBox>
#include <QVBoxLayout>
using namespace std;
souvenirShop::souvenirShop(double distance, QVector<QString> collegesVector, QWidget *parent) :
QWidget(parent),
ui(new Ui::souvenirShop)
{
ui->setupUi(this);
distanceTraveled = distance;
selectedColleges = collegesVector;
ui->label_collegeName->setText(selectedColleges[collegeCount]);
QSqlQueryModel* model=new QSqlQueryModel();
QSqlQuery* qry=new QSqlQuery();
qry->prepare("SELECT souvenirs, cost FROM Souvenirs WHERE college= (:college)");
qry->bindValue(":college", selectedColleges[collegeCount]);
if(qry->exec())
{
qDebug() << "Souvenirs updated";
}
model->setQuery(*qry);
ui->souvenir_tableView->setModel(model);
ui->souvenir_tableView->setColumnWidth(0, 195);
//initliazing purchased souvenirs scroll Area
container = new QWidget;
vBoxLayout = new QVBoxLayout;
container->setLayout(vBoxLayout);
ui->scrollArea_purchased->setWidget(container);
collegeCount++;
}
souvenirShop::~souvenirShop()
{
delete ui;
}
void souvenirShop::on_nextCollege_button_clicked()
{
clicked = false;
subCostList.append(QString::number(subCostAtCampus,'f', 2)); //adding subcost to list as a string
if(collegeCount < selectedColleges.size())
{
ui->label_collegeName->setText(selectedColleges[collegeCount]);
QSqlQueryModel* model=new QSqlQueryModel();
QSqlQuery* qry=new QSqlQuery();
qry->prepare("SELECT souvenirs, cost FROM Souvenirs WHERE college= (:college)");
qry->bindValue(":college", selectedColleges[collegeCount]);
if(qry->exec())
{
qDebug() << "Souvenirs updated";
}
model->setQuery(*qry);
ui->souvenir_tableView->setModel(model);
ui->souvenir_tableView->setColumnWidth(0, 195);
purchasedSouvAtCampus = 0; //reseting num of souvenirs bought at each campus
ui->label_purchasedSouvAtCampus->setText("Souvenirs Purchased Here: " + QVariant(purchasedSouvAtCampus).toString());
subCostAtCampus = 0; //reseting cost of souvenirs bought at each campus
ui->label_subCostAtCampus->setText("Cost of Souvenirs Purchased Here: $" + QString::number(subCostAtCampus,'f', 2));
collegeCount++;
}
else
{
QMessageBox::information(this, "Warning", "Your tour has ended. To continue, please click \"End Tour\"");
}
}
void souvenirShop::on_endTour_button_clicked()
{
if(collegeCount >= selectedColleges.size())
{
QString tempCost = "$" + QString::number(grandTotal, 'f', 2);
QString tempDistance = QString::number(distanceTraveled, 'f', 2) + " miles";
auto* endtour = new endTour(tempDistance, tempCost, selectedColleges, subCostList);
hide();
endtour->show();
}
else
{
QMessageBox::information(this, "Warning", "Your tour is not over. Please finish your tour before clicking \"End Tour\"");
}
}
void souvenirShop::on_souvenir_tableView_clicked(const QModelIndex &index)
{
clicked = true;
if(index.isValid())
{
int row = index.row();
tempSouvenir = index.sibling(row, 0).data().toString();
souvenirCost = index.sibling(row, 1).data().toString().replace("$", "").toDouble();
cost = index.sibling(row, 1).data().toString();
qDebug() << tempSouvenir << Qt::endl << souvenirCost << Qt::endl;
}
}
void souvenirShop::on_buy_button_clicked()
{
if (clicked){
customAmount = ui->customInput->value();
ui->customInput->setValue(1);
for (int i = 0; i<customAmount; i++){
grandTotal = grandTotal + souvenirCost;
purchasedSouvAtCampus++;
subCostAtCampus += souvenirCost;
}
QString customAmountStr = QString::number(customAmount);
QString customItemPrice = QString::number(souvenirCost*customAmount);
QString space = "";
QString space2 = "";
for (int i = 0; i<27-tempSouvenir.length(); i++)
space = space + " ";
for (int i = 0; i<8-customItemPrice.length(); i++)
space2 = space2 + " ";
QLabel *souvenirName = new QLabel(customAmountStr + " x\t"+ tempSouvenir + space + "$" + space2 + customItemPrice);
vBoxLayout->addWidget(souvenirName);
ui->label_purchasedSouvAtCampus->setText("Souvenirs Purchased Here: " + QVariant(purchasedSouvAtCampus).toString());
ui->label_subCostAtCampus->setText("Cost of Souvenirs Purchased Here: $" + QString::number(subCostAtCampus, 'f', 2));
}
else
{
QMessageBox::information(this, "Warning", "No Souvenir Selected");
}
}
| true |
936b118b1e04d3e4e530bbbd9330c62e87c945d9 | C++ | denkoRa/cses | /fenwick.cpp | UTF-8 | 5,819 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <stdio.h>
#include <cstdlib>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#define endl '\n'
#define sync_cin \
ios_base::sync_with_stdio(false); \
cin.tie(NULL)
#define sz(a) (int)a.size()
#define all(a) a.begin(), a.end()
#define TYPEMAX(type) std::numeric_limits<type>::max()
#define TYPEMIN(type) std::numeric_limits<type>::min()
using namespace std;
const int MOD = 1e9 + 7;
const int N = 2e5 + 5;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
//-----------------------------------------------------------------------------
template<typename T>
inline istream& operator>>(istream& is, vector<T>& v) {
for (int ii = 0; ii < sz(v); ++ii) {
is >> v[ii];
}
return is;
}
template<typename T1, typename T2>
inline istream& operator>>(istream& is, pair<T1, T2>& p) {
is >> p.first >> p.second;
return is;
}
template<typename T>
inline ostream& operator<<(ostream& os, vector<vector<T>>& mat) {
for (int ii = 0; ii < sz(mat); ++ii) {
for (int jj = 0; jj < sz(mat[0]); ++jj) {
os << mat[ii][jj] << " ";
}
os << endl;
}
return os;
}
//-----------------------------------------------------------------------------
// Basic FenwickTree for Point Update and Range Query.
class FenwickTree {
public:
FenwickTree(const vector<int>& in) {
n_ = sz(in);
bit_.resize(n_ + 1, 0);
for (int ii = 0; ii < n_; ++ii) {
Add(ii + 1, in[ii]);
}
}
// Add val at 1-based index idx.
void Add(int idx, const int val) {
for (; idx <= n_; idx += idx & -idx) {
bit_[idx] += val;
}
}
// Returns sum at interval [1, idx].
int Sum(int idx) const {
int ret = 0;
for (; idx >= 1; idx -= idx & -idx) {
ret += bit_[idx];
}
return ret;
}
// Returns sum at interval [l, r].
int Sum(int l, int r) const {
return Sum(r) - Sum(l - 1);
}
friend ostream& operator<<(ostream& os, const FenwickTree& ft) {
os << "Size=" << ft.n_ << endl;
for (int ii = 1; ii <= ft.n_; ++ii) {
os << ft.bit_[ii] << " ";
}
os << endl;
return os;
}
private:
vector<int> bit_;
int n_;
};
// FenwickTree RangeUpdate PointQuery
class FenwickTreeRUPQ : public FenwickTree {
public:
FenwickTreeRUPQ(const int sz) :
FenwickTree(vector<int>(sz, 0)) {
}
int Get(const int idx) const {
return Sum(idx);
}
void RangeAdd(const int l, const int r, const int val) {
Add(l, val);
Add(r + 1, -val);
}
private:
// Hide Add and Sum.
using FenwickTree::Add;
using FenwickTree::Sum;
};
// FenwickTree RangeUpdate RangeQuery
class FenwickTreeRURQ {
public:
FenwickTreeRURQ(const int sz) : n_(sz) {
b1_.resize(n_ + 1, 0);
b2_.resize(n_ + 1, 0);
}
FenwickTreeRURQ(const vector<int>& v) {
n_ = sz(v);
b1_.resize(n_ + 1, 0);
b2_.resize(n_ + 1, 0);
for (int ii = 0; ii < n_; ++ii) {
// Update just one at the time.
RangeAdd(ii + 1, ii + 1, v[ii]);
}
}
// Add val to all elements on interval [l, r].
void RangeAdd(const int l, const int r, const int val) {
Add(b1_, l, val);
Add(b1_, r + 1, -val);
Add(b2_, l, val * (l - 1));
Add(b2_, r + 1, -val * r);
}
// Prefix Sum [1, idx].
// After update (l, r, x):
// 3 cases for sum query:
// 1) i < l => Sum[1, i] = i * 0 - 0.
// 2) l <= i <= r => Sum[1, i] = val * i - val * (l - 1) = val * (i - l - 1).
// 3) r < i => Sum[1, i] = val * i + (-val) * i - val * (l - 1) -
// (-val) * r = val * (r - l + 1).
int Sum(const int idx) const {
return Sum(b1_, idx) * idx - Sum(b2_, idx);
}
// Range Sum [l, r].
int Sum(const int l, const int r) const {
return Sum(r) - Sum(l - 1);
}
friend ostream& operator<<(ostream& os, const FenwickTreeRURQ& ft) {
os << "Size=" << ft.n_ << endl;
for (int ii = 1; ii <= ft.n_; ++ii) {
os << ft.b1_[ii] << " ";
}
os << endl;
for (int ii = 1; ii <= ft.n_; ++ii) {
os << ft.b2_[ii] << " ";
}
os << endl;
return os;
}
private:
void Add(vector<int>& vec, int idx, const int val) {
for (; idx <= n_; idx += idx & -idx) {
vec[idx] += val;
}
}
int Sum(const vector<int>& vec, int idx) const {
int ret = 0;
for (; idx >= 1; idx -= idx & -idx) {
ret += vec[idx];
}
return ret;
}
private:
vector<int> b1_;
vector<int> b2_;
int n_;
};
int main() {
sync_cin;
cout << "===============" << endl;
cout << "Test: Point Update + Range Query" << endl;
vector<int> a{1, 3, 4, 8, 6, 1, 4, 2};
int n = sz(a);
FenwickTree ft(a);
cout << ft;
for (int ii = 1; ii <= n; ++ii) {
cout << ft.Sum(ii) << endl;
}
cout << ft;
cout << ft.Sum(4) - ft.Sum(3) << endl;
cout << ft.Sum(5) - ft.Sum(4) << endl;
cout << ft;
cout << "===============" << endl;
cout << "Test: Range Update + Point Query" << endl;
FenwickTreeRUPQ ft2(10 /* size */);
ft2.RangeAdd(3, 6, 11);
cout << ft2;
cout << ft2.Get(4) << endl;
ft2.RangeAdd(5, 7, 5);
cout << ft2.Get(6) << endl;
cout << ft2;
ft2.RangeAdd(6, 6, -1);
cout << ft2.Get(6) << endl;
cout << "===============" << endl;
cout << "Test: Range Update + Range Query" << endl;
vector<int> v{1, 3, 2, 7, 3, 4}; // S = 20
FenwickTreeRURQ ft3(v);
cout << ft3;
cout << ft3.Sum(1, 1) << endl;
cout << ft3.Sum(2, 2) << endl;
cout << ft3.Sum(3, 3) << endl;
cout << ft3.Sum(4, 4) << endl;
cout << ft3.Sum(5, 5) << endl;
cout << ft3.Sum(6, 6) << endl;
cout << ft3.Sum(1, 6) << endl;
ft3.RangeAdd(2, 4, -1);
cout << ft3.Sum(3, 3) << endl;
cout << ft3.Sum(1, 6) << endl;
return 0;
}
| true |
80bf576a1173a839b677d4f44be9d35b8139f49a | C++ | hhool/cmakelist_examples | /projects/l_project_cpugpu/picture.h | UTF-8 | 4,251 | 2.640625 | 3 | [] | no_license | #pragma once
#pragma pack (1)
class Picture
{
public:
typedef struct tag_BMP_FILEHEADER
{
unsigned short bfType; //2Bytes,必须为"BM",即0x424D 才是Windows位图文件
unsigned int bfSize; //4Bytes,整个BMP文件的大小
unsigned short bfReserved1; //2Bytes,保留,为0
unsigned short bfReserved2; //2Bytes,保留,为0
unsigned int bfOffBits; //4Bytes,文件起始位置到图像像素数据的字节偏移量
} BMP_FILEHEADER;
typedef struct tag_BMP_INFOHEADER
{
int biSize; //4Bytes,INFOHEADER结构体大小,存在其他版本I NFOHEADER,用作区分
int biWidth; //4Bytes,图像宽度(以像素为单位)
int biHeight; //4Bytes,图像高度,+:图像存储顺序为Bottom2Top,-:Top2Bottom
short biPlanes; //2Bytes,图像数据平面,BMP存储RGB数据,因此总为1
short biBitCount; //2Bytes,图像像素位数
int biCompression; //4Bytes,0:不压缩,1:RLE8,2:RLE4
int biSizeImage; //4Bytes,4字节对齐的图像数据大小
int biXPelsPerMeter; //4 Bytes,用象素/米表示的水平分辨率
int biYPelsPerMeter; //4 Bytes,用象素/米表示的垂直分辨率
int biClrUsed; //4 Bytes,实际使用的调色板索引数,0:使用所有的调色板索引
int biClrImportant; //4 Bytes,重要的调色板索引数,0:所有的调色板索引都重要
}BMP_INFOHEADER;
typedef struct tag_RGBQUAD
{
char rgbBlue; //指定蓝色强度
char rgbGreen; //指定绿色强度
char rgbRed; //指定红色强度
char rgbReserved; //保留,设置为0
} RGBQUAD;
typedef struct tag_BMP_HEADER
{
BMP_FILEHEADER fileHeader; // 文件头
BMP_INFOHEADER infoHeader; // 信息头
//RGBQUAD rgbquad; // 可选,调色板
}BMP_HEADER;
typedef struct tag_ImageProp
{
unsigned int pixelsH; // 水平像素个数 宽
unsigned int pixelsV; // 垂直像素个数 高
BMP_HEADER header; // bmp头
unsigned long int bytesH; // 单行水平像素的字节数 (内存宽度对齐, 所以有可能不是单纯的 pixelsH*3)
unsigned char* reserved; // bmp 头到图像数据间的冗余区
unsigned char** data; // 图像数据 二维数组 (高 * 水平像素的字节数)
}ImageProp;
typedef struct tag_Pixel
{
unsigned char R;
unsigned char G;
unsigned char B;
}Pixel;
typedef struct tag_Triplet
{
unsigned int a;
unsigned int b;
unsigned int c;
}Triplet;
Picture();
~Picture();
void read(const char* filepath);
void read(const void* pFile);
void write(const char* fildpath, const ImageProp& ip);
void write(const void* pFile, const ImageProp& ip);
// 水平-垂直翻转
virtual ImageProp* rolloverH();
virtual ImageProp* rolloverV();
// 角度旋转
virtual ImageProp* rotate(short angle);
// 模糊 (滤波器取均值)滤波器半径 r
virtual ImageProp* blurred(int r);
// rgb 24位 彩色图像变为 B&W 8位 图像
virtual ImageProp* tobwimage();
// gaussfilter 平滑滤波减小噪声
virtual ImageProp* gaussianfilter();
// 边缘增强
virtual ImageProp* sobel();
// B&W灰度转二值黑白图像
virtual ImageProp* threshold();
// 释放图像
void releaseImageProp(ImageProp** ppIp);
// 释放图像数据区
void releaseImagePropData(ImageProp* pIp);
// 滤波器取均值
Pixel wavefilter_avg(unsigned int x, unsigned int y, unsigned int r);
Triplet wavefilter_sum(unsigned int x, unsigned int y, unsigned int r);
unsigned int wavefilter_count(unsigned int r);
Triplet line_sum(unsigned int y, unsigned int x1, unsigned int x2 );
protected:
ImageProp _ip;
ImageProp* _prepareImageProp();
ImageProp* _prepareImagePropEx();
}; | true |
6c08f182fd7b1f0a1c2dbc04674000e677c62c16 | C++ | greenjava/fw4spl-swig | /fwBinding/include/fwBinding/Data.hpp | UTF-8 | 592 | 2.5625 | 3 | [] | no_license | #ifndef __FWBINDING_DATA_HPP__
#define __FWBINDING_DATA_HPP__
#include "fwBinding/config.hpp"
#include <string>
namespace fwBinding
{
/**
* @class Data
*/
class FWBINDING_CLASS_API Data
{
public:
/// Constructor.
FWBINDING_API Data(const std::string& objectType, const std::string& uid = "");
/// Desctructor.
FWBINDING_API virtual ~Data();
FWBINDING_API std::string getUID() const;
FWBINDING_API std::string getImplementation() const;
private:
std::string m_implementation;
std::string m_uid;
};
} // fwBinding
#endif // __FWBINDING_DATA_HPP__
| true |
65ebdbd6c3fb280cd2a7c3aada82156c73a463d6 | C++ | belyaev-mikhail/dddos | /Util/macros.h | UTF-8 | 2,507 | 2.53125 | 3 | [] | no_license | /*
* macros.h
*
* Created on: Dec 7, 2012
* Author: belyaev
*/
// GUARDS ARE NOT USED FOR A REASON!
// #ifndef MACROS_H_
// #define MACROS_H_
#ifdef CALLOPHRYS_MACROS_DEFINED
#error "macros.h included twice!"
#endif
#define CALLOPHRYS_MACROS_DEFINED
/*
* Macro for quick-writing one-liners with tricky typing.
* This can be used to replace the following (note the same `a+b` used twice):
*
* template<class A, class B>
* auto plus(A a, B b) -> decltype(a+b) { return a+b; }
*
* with this:
*
* template<class A, class B>
* auto plus(A a, B b) QUICK_RETURN(a+b)
*
* Note that the one-liners can be big and the impact will be significant.
*
* */
#define QUICK_RETURN(...) ->decltype(__VA_ARGS__) { return __VA_ARGS__; }
/*
#define BYE_BYE(type, msg) return exit<type>( \
__FILE__, \
__LINE__, \
__PRETTY_FUNCTION__, \
msg)
#define BYE_BYE_VOID(msg) { \
exit<void>( \
__FILE__, \
__LINE__, \
__PRETTY_FUNCTION__, \
msg); \
return; \
}
#define ASSERT(cond, msg) while(!(cond)){ exit<void>( \
__FILE__, \
__LINE__, \
__PRETTY_FUNCTION__, \
msg); }
#define ASSERTC(cond) while(!(cond)){ exit<void>( \
__FILE__, \
__LINE__, \
__PRETTY_FUNCTION__, \
#cond); }
*/
#define GUARD(...) typename ::std::enable_if<(__VA_ARGS__)>::type
#define GUARDED(TYPE, ...) typename std::enable_if<(__VA_ARGS__), TYPE>::type
// XXX: change this to [[noreturn]] when mother..cking g++ supports it
#define NORETURN __attribute__((noreturn))
#define DEFAULT_CONSTRUCTOR_AND_ASSIGN(CLASSNAME) \
\
CLASSNAME() = default; \
CLASSNAME(const CLASSNAME&) = default; \
CLASSNAME(CLASSNAME&&) = default; \
CLASSNAME& operator=(const CLASSNAME&) = default; \
CLASSNAME& operator=(CLASSNAME&&) = default;
#define PRETOKENPASTE(x, y) x ## y
#define TOKENPASTE(x, y) PRETOKENPASTE(x, y)
// #define ON_SCOPE_EXIT(LAMBDA) \
// auto TOKENPASTE(local_scope_guard_packed_lambda, __LINE__) = [&](){ LAMBDA; }; \
// ::util::scope_guard<decltype(TOKENPASTE(local_scope_guard_packed_lambda, __LINE__))> TOKENPASTE(local_scope_guard, __LINE__) { TOKENPASTE(local_scope_guard_packed_lambda, __LINE__) };
#ifdef __clang__
#define COMPILER clang
#elif defined(__GNUC__)
#define COMPILER gcc
#else
#error "You are trying to use an unsupported compiler. Either add it to macros.h or quit trying."
#endif
// #endif /* MACROS_H_ */
| true |
02055cd4ee1686f6b22825fe168c689a9ed64ae6 | C++ | DaehyunPY/lma2root | /lma2root/BinaryDump.cpp | UTF-8 | 1,234 | 2.796875 | 3 | [] | no_license | #include "BinaryDump.h"
#include<iostream>
BinaryDump::BinaryDump(const string fileName) :hitsFile(MyArchive::ArWriting)
{
hitsFile.newFile(fileName.data());
if (!hitsFile.fileIsOpen())
std::cout << "Can not open the Dump file: " << fileName;
}
BinaryDump::~BinaryDump()
{
if (hitsFile.fileIsOpen())
hitsFile.CloseFile();
}
void BinaryDump::OpenFile(const string fileName)
{
hitsFile.newFile(fileName.data());
if (!hitsFile.fileIsOpen())
std::cout << "Can not open the Dump file: " << fileName;
}
void BinaryDump::FlushBinFile()
{
hitsFile.FlushFile();
}
void BinaryDump::WriteData(MySortedEvent& se, unsigned int tag)
{
//--- File structure ---//
// UINT32 Tag
// INT16 Number of hits
// double time
// double x
// double y
// INT16 reconstructon method
// Write Tag
hitsFile << tag;
// For only 1 detector, det number is 0
MyDetektor &det = se.GetDetektor(0);
// Write Number of hits
hitsFile << static_cast<short>(det.GetNbrOfHits());
// Write hits (x,y,t, reconstruction methon)
for (size_t i = 0; i < det.GetNbrOfHits(); i++)
{
MyDetektorHit &hit = det.GetHit(i);
hitsFile << hit.X();
hitsFile << hit.Y();
hitsFile << hit.Time();
hitsFile << static_cast<short>(hit.RekMeth());
}
}
| true |
06008d205143ab289cab1491b573479e227f6b04 | C++ | zacharygking/BoulderBlast | /BoulderBlast/Actor.cpp | UTF-8 | 12,422 | 2.84375 | 3 | [] | no_license | #include "Actor.h"
#include "StudentWorld.h"
// Students: Add code to this file (if you wish), Actor.h, StudentWorld.h, and StudentWorld.cpp
//gets keypress, in the case of up down left or right the
//player checks if it can move in that direction, if it can
//it moves, if it is blocked it checks if it’s a boulder, if
//it is, it checks if the boulder can move, if it does the
//player and boulder then move, otherwise the function returns.
//In the case of escape it sets the player dead so that it will
//end the level in the studentworld function. In the case of space
//the player shoots in its direction and plays the shoot sound if
//ammo is available
void Player::doSomething()
{
if (!isLive())
return;
int ch=0;
if (getWorld()->getKey(ch))
{
switch (ch)
{
case KEY_PRESS_LEFT:
if (!getWorld()->blocksPlayer(getX()-1,getY()))
{
if (!getWorld()->boulderCheck(getX()-1,getY()))
moveTo(getX()-1,getY());
else
{
if(getWorld()->moveBoulder(getX()-1,getY(),GraphObject::left))
{
moveTo(getX()-1, getY());
}
}
}
setDirection(left);
break;
case KEY_PRESS_RIGHT:
if (!getWorld()->blocksPlayer(getX()+1,getY()))
{
if(!getWorld()->boulderCheck(getX()+1,getY()))
moveTo(getX()+1,getY());
else
{
if(getWorld()->moveBoulder(getX()+1,getY(),GraphObject::right))
{
moveTo(getX()+1,getY());
}
}
}
setDirection(right);
break;
case KEY_PRESS_UP:
if (!getWorld()->blocksPlayer(getX(),getY()+1))
{
if (!getWorld()->boulderCheck(getX(),getY()+1))
moveTo(getX(),getY()+1);
else
{
if(getWorld()->moveBoulder(getX(),getY()+1,GraphObject::up))
{
moveTo(getX(), getY()+1);
}
}
}
setDirection(up);
break;
case KEY_PRESS_DOWN:
if (!getWorld()->blocksPlayer(getX(), getY()-1))
{
if (!getWorld()->boulderCheck(getX(),getY()-1))
moveTo(getX(),getY()-1);
else
{
if(getWorld()->moveBoulder(getX(),getY()-1,GraphObject::down))
{
moveTo(getX(), getY()-1);
}
}
}
setDirection(down);
break;
case KEY_PRESS_ESCAPE:
setLife(false);
break;
case KEY_PRESS_SPACE:
if (getAmmo() > 0)
{
getWorld()->playSound(SOUND_PLAYER_FIRE);
getWorld()->newBullet(getX(),getY(),GraphObject::getDirection());
incAmmo(-1);
}
break;
}
}
return;
}
void Goodie::doSomething()
{
if (!isLive())
{
return;
}
if (getWorld()->playerX() == getX() && getWorld()->playerY() == getY() && !isStolen())
{
getWorld()->playSound(SOUND_GOT_GOODIE);
setLife(false);
reward();
}
return;
}
void Jewel::doSomething()
{
if (!isLive())
{
return;
}
if (getWorld()->playerX() == getX() && getWorld()->playerY() == getY())
{
getWorld()->increaseScore(50);
getWorld()->playSound(SOUND_GOT_GOODIE);
setLife(false);
getWorld()->decJewel();
}
return;
}
void LifeGoodie::reward()
{
getWorld()->increaseScore(1000);
getWorld()->incLives();
}
void AmmoGoodie::reward()
{
getWorld()->increaseScore(100);
getWorld()->getPlayer()->incAmmo(20);
}
void HealthGoodie::reward()
{
getWorld()->increaseScore(500);
getWorld()->getPlayer()->healthGoodie();
}
void Hole::doSomething()
{
if (!isLive())
{
return;
}
Actor* temp = getWorld()->getBoulder(getX(),getY());
if (temp != nullptr)
{
temp->setLife(false);
setLife(false);
}
return;
}
void Snarlbot::doSomething()
{
if (!isLive())
return;
if (shouldAct())
{
if (attemptShoot())
return;
if (canMove())
move();
else
setDirection(changeDirection());
}
return;
}
bool Robot::attemptShoot()
{
switch (getDirection())
{
case GraphObject::down:
if (getWorld()->playerSight(getX(), getY(), down))
{
getWorld()->newBullet(getX(),getY(),down);
getWorld()->playSound(SOUND_ENEMY_FIRE);
return true;
}
break;
case GraphObject::up:
if (getWorld()->playerSight(getX(), getY(), up))
{
getWorld()->newBullet(getX(),getY(),up);
getWorld()->playSound(SOUND_ENEMY_FIRE);
return true;
}
break;
case GraphObject::right:
if (getWorld()->playerSight(getX(), getY(), right))
{
getWorld()->newBullet(getX(),getY(),right);
getWorld()->playSound(SOUND_ENEMY_FIRE);
return true;
}
break;
case GraphObject::left:
if (getWorld()->playerSight(getX(), getY(), left))
{
getWorld()->newBullet(getX(),getY(),left);
getWorld()->playSound(SOUND_ENEMY_FIRE);
return true;
}
break;
default:
break;
}
return false;
}
void Bullet::doSomething()
{
if (!isLive())
return;
if (getWorld()->killsBullet(getX(), getY()))
{
setLife(false);
return;
}
else
{
if(!getWorld()->interactsBullet(getX(),getY()))
{
switch(getDirection())
{
case GraphObject::up:
moveTo(getX(), getY()+1);
break;
case GraphObject::down:
moveTo(getX(),getY()-1);
break;
case GraphObject::right:
moveTo(getX()+1, getY());
break;
case GraphObject::left:
moveTo(getX()-1, getY());
break;
default:
break;
}
}
else
{
setLife(false);
return;
}
if (getWorld()->interactsBullet(getX(), getY()))
{
setLife(false);
return;
}
}
return;
}
//reduces players health by 2 if this sets health below or equal
//to zero it sets the players life false and plays player dead
//otherwise plays player impact sound
void Player::damage()
{
shoot();
if (getHealth() == 0)
{
setLife(false);
getWorld()->playSound(SOUND_PLAYER_DIE);
}
else
getWorld()->playSound(SOUND_PLAYER_IMPACT);
}
void Robot::damage()
{
shoot();
if (getHealth() <= 0)
{
special();
setLife(false);
getWorld()->playSound(SOUND_ROBOT_DIE);
getWorld()->increaseScore(killBonus());
}
else
{
getWorld()->playSound(SOUND_ROBOT_IMPACT);
}
}
void Boulder::damage()
{
shoot();
if (getHealth() <= 0)
{
setLife(false);
}
}
bool Robot::shouldAct()
{
int k = (28-getWorld()->getLevel())/4;
if (m_tick % k == 0)
{
m_tick = 1;
return true;
}
m_tick++;
return false;
}
void KleptoBot::doSomething()
{
if (!isLive())
{
return;
}
if (shouldAct())
{
if (attemptShoot())
return;
Goodie* good;
if(getWorld()->goodieAt(getX(),getY(),good))
{
if (rand() % 10 == 0 && id_stolen == 0)
{
getWorld()->playSound(SOUND_ROBOT_MUNCH);
good->setStolen(true);
id_stolen = good->id();
return;
}
}
if (shouldMove() && canMove())
{
distleft--;
move();
}
else
{
resetDistance();
set<Direction> dir;
dir.clear();
Direction d = changeDirection();
setDirection(d);
while(dir.size() < 4 && !canMove())
{
dir.insert(d);
setDirection(d);
d = changeDirection();
}
if (!canMove())
{
setDirection(d);
}
else
{
move();
distleft--;
}
}
}
return;
}
void KleptoBot::special()
{
switch(id_stolen)
{
case(0):
break;
case 1:
getWorld()->addActor(new AmmoGoodie(getX(),getY(),getWorld()));
break;
case 2:
getWorld()->addActor(new LifeGoodie(getX(),getY(),getWorld()));
break;
case 3:
getWorld()->addActor(new HealthGoodie(getX(),getY(),getWorld()));
break;
default:
break;
}
}
bool Robot::move()
{
switch (getDirection())
{
case GraphObject::down:
moveTo(getX(),getY()-1);
break;
case GraphObject::up:
moveTo(getX(),getY()+1);
break;
case GraphObject::right:
moveTo(getX()+1,getY());
break;
case GraphObject::left:
moveTo(getX()-1,getY());
break;
default:
return false;
}
return false;
}
bool Robot::canMove()
{
switch (getDirection())
{
case GraphObject::down:
if (!getWorld()->blocksRobot(getX(),getY()-1))
return true;
break;
case GraphObject::up:
if (!getWorld()->blocksRobot(getX(),getY()+1))
return true;
break;
case GraphObject::right:
if (!getWorld()->blocksRobot(getX()+1,getY()))
return true;
break;
case GraphObject::left:
if (!getWorld()->blocksRobot(getX()-1,getY()))
return true;
break;
default:
return false;
}
return false;
}
Actor::Direction KleptoBot::changeDirection()
{
int k = rand()%4;
switch (k)
{
case 0:return up;break;
case 1:return down;break;
case 2:return left;break;
case 3:return right;break;
}
return none;
}
Actor::Direction Snarlbot::changeDirection()
{
switch(getDirection())
{
case up:return down;break;
case down:return up;break;
case left:return right;break;
case right:return left;break;
}
return none;
}
void KleptoBotFactory::doSomething()
{
if (getWorld()->census(getX(), getY()) < 3 && !getWorld()->kleptoAt(getX(),getY()))
{
if (rand()%50 == 0)
{
switch (m_type)
{
case ANGRY:
getWorld()->addActor(new AngryKleptoBot(getX(),getY(),getWorld()));
break;
case REGULAR:
getWorld()->addActor(new RegularKleptoBot(getX(),getY(),getWorld()));
break;
}
getWorld()->playSound(SOUND_ROBOT_BORN);
}
}
return;
}
void Exit::doSomething()
{
if(getWorld()->getJewel() == 0)
{
if(getWorld()->playerX() == getX() && getWorld()->playerY() == getY())
{
getWorld()->setCompleted();
getWorld()->playSound(SOUND_FINISHED_LEVEL);
}
}
}
| true |
be0064918c3616b5686f2ea85eb674d534c8ba98 | C++ | piyush2011257/GFG | /AMAZON/167/r1_q1.cpp | UTF-8 | 2,047 | 3.453125 | 3 | [] | no_license | /*
http://www.geeksforgeeks.org/amazon-interview-experience-set-167-sde-1-year-6-months-experience/
Given a list of N coins, their values (V1, V2, … , VN), and the total sum S. Find the minimum number of coins the sum of which is S (we can use as many coins of one type as we want), or report that it’s not possible to select coins in such a way that they sum up to S.
Example: Given coins with values 1, 3, and 5.
And the sum S is 11.
Output: 3, 2 coins of 3 and 1 coin of 5.
func(N,i) = min ( func(N-val(i),i) + 1 , func(N,i-1 ) )
N-val(i) >= 0
for i=0 first
FUNC[][]={-1} INITIALIZE ALL WITH -1
ALL FUNC[0][I]=0;
FOR ( I=V(0),J=1 ; I<=C; I+=V(0),J++ )
FUNC(I][0]=J;
FOR (i=1; i<n-1; i++ )
for ( j=0; j<v(1); j++ )
func(j)(i)=func(j)(i-1);
for (j=v(1); j<=C; j++ )
{ m1=func(j-v1(1),i)+1
m2=func(j,i-1)
func(j)(i)=min(m1,m2)
}
O(C*N)- time / space
Space can be optimize, since we need only 2 rows at max at a time- O(C) space
*/
#include<cstdio>
#include<climits>
using namespace std;
const int len=3;
// all are integers so max coins used <= sum if we use all 1. hence max value is sum+1
int main()
{ int coins[len]={1,2,3};
int sum=7;
int func[len][sum+1];
for ( int i=0; i<len; i++ )
for ( int j=0; j<=sum; j++ )
func[i][j]=INT_MAX;
for ( int i=0; i<len; i++ )
func[i][0]=0; // base case
for ( int i=coins[0], j=1; i<=sum; i+=coins[0], j++ )
func[0][i]=j; // initial for 0th row
for ( int i=1; i<len; i++ )
{ for ( int j=1; j<coins[i]; j++ )
func[i][j]=func[i-1][j];
for ( int j=coins[i]; j<=sum; j++ )
{ int m1=INT_MAX, m2=INT_MAX;
if ( func[i][j-coins[i]] != INT_MAX ) // if func[i][j-coins[i]] has a valid solution
m1=func[i][j-coins[i]]+1;
m2=func[i-1][j];
if ( m1 < m2 )
func[i][j]=m1;
else
func[i][j]=m2;
}
}
for ( int i=0; i<len; i++ )
{ for ( int j=0; j<=sum; j++ )
printf("%d\t", func[i][j]);
printf("\n");
}
printf("%d\n", func[len-1][sum]);
return 0;
}
/*
Finding minimum coins
for finding no. of ways
f(i,N) = f(i,N-1) + f(i-val(i),N)
*/
| true |
8f24f27eb3225149dfe3c022f1e11dfa87d431aa | C++ | CapSmollet/Info | /5/main.cpp | UTF-8 | 1,119 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
void put_snake(int** &a, int k, int s)
{
for (int i = 0; i < k; i++)
{
for (int j = 0; j < s; j++)
a[i][j] = 0;
}
a[0][s - 1] = 1;
int c = 1, i = 0, j = s - 1;
while (c < k * s)
{
while (j >= 1 && a[i][j - 1] == 0)
{
c++;
j--;
a[i][j] = c;
}
while (i + 1 < k && a[i + 1][j] == 0)
{
c++;
i++;
a[i][j] = c;
}
while (j + 1 < s && a[i][j + 1] == 0)
{
c++;
j++;
a[i][j] = c;
}
while (i >= 1 && a[i - 1][j] == 0)
{
c++;
i--;
a[i][j] = c;
}
}
}
int main()
{
int n, m;
cin >> n >> m;
int** Snake = new int*[n];
for (int i = 0; i < n; i++)
Snake[i] = new int[m];
put_snake(Snake, n, m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cout << Snake[i][j] << '\t';
cout << '\n';
}
delete[]Snake;
return 0;
} | true |
696590f6946e1265b1ad3c3dcbeb5a825a065997 | C++ | CoffeeIsLife87/Abstact_Class_Example_for_CPP | /AbstractClassExample/ActualImple.h | UTF-8 | 1,305 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "BasicInterface.h"
/*-------------------------------------------------------------------------------------------------------------------------------------*\
| This file contains the class with the actual implementation of the functions |
| For ActualImplementation to get added to a vector of BasicInterface* it must inherit BasicInteface |
| You can have as many functions as you want in here but only the functions defined in the interface can be declared override |
\*-------------------------------------------------------------------------------------------------------------------------------------*/
class ActualImplementaion: public BasicInterface
{
public:
ActualImplementaion() {};
~ActualImplementaion() {};
/*-----------------------------------------------------------------------------------------------------------------------------*\
| You will notice that not only the name, but the casing as well are the same as in the interface |
| the override specifier is what makes it so that the virtual function in the inherited class is replace with the real function |
\*-----------------------------------------------------------------------------------------------------------------------------*/
void PrintText() override;
}; | true |
ef10c4940ebd1ca1e6c78d9e06e5ceb1e9f81c0a | C++ | jesmur/HumansVsZombies | /Organism.h | UTF-8 | 1,042 | 2.90625 | 3 | [] | no_license | #ifndef HUMANSVSZOMBIES_ORGANISM_H
#define HUMANSVSZOMBIES_ORGANISM_H
#include <iostream>
#include "GameSpecs.h"
using namespace std;
class City;
enum species {HUMAN, ZOMBIE};
struct coord {
int x;
int y;
coord(int x, int y) {
this->x = x;
this->y = y;
}
};
class Organism {
protected:
int xPosition, yPosition, currentSteps;
bool moved, hasSpawned;
City *city;
public:
Organism();
Organism( City *city, int xPosition, int yPosition);
virtual ~Organism();
virtual void move() = 0;
virtual void spawn() = 0;
virtual species getSpecies() = 0; //this could also be coded concrete here
void setPosition(int x, int y);
bool hasMoved() const;
void setMoved(bool moved);
bool getHasSpawned() const;
void setHasSpawned(bool spawned);
int getCurrentSteps();
void setCurrentSteps(int steps);
bool isValidMove(int x, int y);
friend ostream& operator<<( ostream &output, Organism *organism );
};
#endif //HUMANSVSZOMBIES_ORGANISM_H
| true |
cdf3430de5b3c6aa865998829ed01851dbe4e0f6 | C++ | StrelokCH/woipv | /LocalSolverSat/LocalSolver/lsoperator.h | UTF-8 | 22,848 | 3.046875 | 3 | [] | no_license | // Copyright (C) 2018 Innovation 24, Aix-Marseille University, CNRS. All rights reserved.
#ifndef LS_LSOPERATOR_H
#define LS_LSOPERATOR_H
namespace localsolver {
/**
* Mathematical operators available for modeling. These operators are used to type
* the expressions created in a %LocalSolver mathematical optimization model.
*
* @see LSModel
* @see LSExpression
*/
enum LSOperator {
/**
* Boolean decision. Decisional operator with no operand.
* Decision variable with domain `{0,1}`.
*/
O_Bool,
/**
* Float decision. Operator with two operands that represent the lower bound
* and the upper bound of the decision (domain `[lb, ub]`).
* The bounds must be constants (integers or doubles).
*
* @since 4.0
*/
O_Float,
/**
* Constant. Operator with no argument. Constants can be booleans, integers
* or doubles. Note that constants 0 or 1 are considered as boolean.
* Constants are implicitly created when passing lsint or lsdouble arguments
* to {@link LSModel#createExpression} or {@link LSExpression#addOperand}.
* They can also be created with the dedicated function {@link LSModel#createConstant}.
*/
O_Const,
/**
* Sum. N-ary arithmetic operator. `SUM(e1, e2, ..., eN)` is equal to the sum
* of all operands `e1, e2, ..., eN`. This operator returns an integer if all
* the operands are booleans or integers and a double as soon as one
* operand is a double.
*
* ### With collections or ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create expressions with a dynamic number of operands.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and will sum all the
* values computed and returned by the function.
*/
O_Sum,
/**
* Substraction. Binary arithmetic operator.
* `SUB(x, y)` is equal to the value of `x - y`.
* This operator returns an integer if the two operands are booleans or
* integers, and a double as soon as one operand is a double.
*
* @since 4.0
*/
O_Sub,
/**
* Product. N-ary arithmetic operator. `PROD(e1, e2, ..., eN)` is equal to
* the product of all operands `e1, e2, ..., eN`. This operator returns an
* integer if all the operands are booleans or integers, and a double as
* soon as one operand is a double.
*
* ### With collections or ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create expressions with a dynamic number of operands.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and will compute the
* product of all the values returned by the function.
*/
O_Prod,
/**
* Maximum. N-ary arithmetic operator. `MAX(e1, e2, ..., eN)` is equal to
* the maximum value among all operands `e1, e2, ..., eN`. This operator
* returns an integer if all the operands are booleans or integers,
* and a double as soon as one operand is a double.
*
* ### With collections or ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create expressions with a dynamic number of operands.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and will find the maximum
* value among all the values returned by the function.
*/
O_Max,
/**
* Minimum. N-ary arithmetic operator. `MIN(e1, e2, ..., eN)` is equal to
* the minimum value among all operands `e1, e2, ..., eN`. This operator
* returns an integer if all the operands are booleans or integers,
* and a double as soon as one operand is a double.
*
* ### With collections or ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create expressions with a dynamic number of operands.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and will find the minimum
* value among all the values returned by the function.
*/
O_Min,
/**
* Equal. Binary relational operator.
* `EQ(a,b) = 1` if `a == b`, and `0` otherwise.
* This operator returns a boolean.
*/
O_Eq,
/**
* Not equal to. Binary relational operator.
* `NEQ(a,b) = 1` if `a != b`, and `0` otherwise.
* This operator returns a boolean.
*/
O_Neq,
/**
* Greater than or equal to. Binary relational operator.
* `GEQ(a,b) = 1` if `a >= b`, and `0` otherwise.
* This operator returns a boolean.
*/
O_Geq,
/**
* Lower than or equal to. Binary relational operator.
* `LEQ(a,b) = 1` if `a <= b`, and `0` otherwise.
* This operator returns a boolean.
*/
O_Leq,
/**
* Strictly greater than. Binary relational operator.
* `GT(a,b) = 1` if `a > b`, and `0` otherwise.
* This operator returns a boolean.
*/
O_Gt,
/**
* Strictly lower than. Binary relational operator.
* `LQ(a, b) = 1` if `a < b`, and `0` otherwise.
* This operator returns a boolean.
*/
O_Lt,
/**
* If-Then-Else. Ternary conditional operator.
* `IF(a, b, c)` is equal to `b` if `a = 1`, and `c` otherwise. The first
* operand must be a boolean (that is, equal to 0 or 1).
* This operator returns a boolean if the three operands are booleans,
* an integer if the second and third operands are integers, and a double
* if the second or the third operand is a double.
*/
O_If,
/**
* Not. Unary logical operator. `NOT(a) = 1 - a`.
* The operand must be boolean (that is, equal to 0 or 1).
* This operator returns a boolean.
*/
O_Not,
/**
* And. N-ary logical operator. `AND(e1, e2, ..., eN)` is equal to 1 (true)
* if all the operands `e1, e2, ..., eN` are 1, and 0 otherwise.
* All the operands must be boolean (that is, equal to 0 or 1).
* This operator returns a boolean.
*
* ### With collections or ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create expressions with a dynamic number of operands.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and will return 1 if all
* the values returned by the function are 1 and 0 otherwise.
*/
O_And,
/**
* Or. N-ary logical operator. `OR(e1, e2, ..., eN)` is equal to 0 (false)
* if all operands `e1, e2, ..., eN` are 0, and 1 otherwise.
* All the operands must be boolean (that is, equal to 0 or 1).
* This operator returns a boolean.
*
* ### With collections or ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create expressions with a dynamic number of operands.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and will return 0 if
* all the values returned by the function are 0 and 1 otherwise.
*/
O_Or,
/**
* Exclusive or (also called "xor"). N-ary logical operator.
* `XOR(e1, e2, ..., eN)` is equal to 0 if the number of operands with
* value 1 among `e1, e2, ..., eN` is even, and 1 otherwise.
* Remarkable case: `XOR(a,b) = 1` if `a == b`, and `0` otherwise.
* All the operands must be boolean (that is, equal to 0 or 1).
* This operator returns a boolean.
*
* ### With collections or ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create expressions with a dynamic number of operands.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and will return 0 if the
* number of value 1 returned by the function is even, and 1 otherwise.
*/
O_Xor,
/**
* Absolute value. Unary arithmetic operator. `ABS(e) = e >= 0 ? e : -e`.
* This operator returns an integer if the operand is a boolean or an integer,
* and a double otherwise.
*/
O_Abs,
/**
* Distance between two numbers. Binary arithmetic operator. `DIST(a,b) = ABS(a-b)`.
* This operator returns an integer if the two operands are booleans or integers,
* and a double as soon as one of the operand is a double.
*/
O_Dist,
/**
* Division. Binary arithmetic operator.
* This operator always returns a double. Note that until version 4.0,
* the division was an integer division if both operands were integers.
*/
O_Div,
/**
* Modulo (remainder of the integer division). Binary arithmetic operator.
* `MOD(a,b) = r` such that `a = q * b + r` with `q`, `r` integers and `|r| < b`.
* The operands must be integers or booleans. This operator returns an integer.
*/
O_Mod,
/**
* Array. An array is a collection of elements. Indexes begin at 0.
* It could be used with operators like {@link #O_At} or {@link #O_Scalar}.
* An array doesn't have a value by itself, but can contain operands
* of type boolean, integer, double or array (for multi-dimensional arrays).
* All the elements of an array must be of the same type.
*
* ### With ranges ###
* This operator can also be used with {@link #O_Range}, {@link #O_List}
* or {@link #O_Set} to create an array with a dynamic number of elements.
* In that case, this operator becomes a binary operator that takes a range,
* a list or a set as first operand and a function ({@link #O_Function} or
* {@link #O_NativeFunction}) as second operand. The operator will call the
* function on each value of the range, list or set and the returned values
* will be used to populate the array.
*
* @since 2.1
*/
O_Array,
/**
* Returns the element at specific coordinates of an array or a list.
*
* ### For arrays ###
* The first operand must be the array and the other operands must be the
* coordinates of the element to get. The number of coordinates depends
* on the dimension of the array. Thus AT(myArray, i) returns the i element
* of the one-dimensional array myArray. This operator returns a boolean,
* an integer or a double according to the type of the operands in the array.
* If one of the specified coordinate is out of range, the evaluation
* of the expression will fail.
*
* ### For lists ###
* The first operand must be the list and the second operand must be the
* index of the element to get. If the index is out of range
* (index < 0 or index > count(list)), the evaluation of the expression
* will not fail but will return -1.
*
* @since 2.1
*/
O_At,
/**
* Scalar product. `SCALAR(a, x) = sum(a[i]*x[i])` where `a` and `x` are two
* one-dimensional arrays. This operator returns an integer or a double
* according to the type of the operands in the arrays.
*
* @since 2.1
*/
O_Scalar,
/**
* Ceil. Unary arithmetic operator. Returns a value rounded to the next
* highest integer. The operand can be a boolean, an integer or a double.
* This operator returns an integer.
*
* @since 3.0
*/
O_Ceil,
/**
* Floor. Unary arithmetic operator. Returns a value rounded to the next
* lowest integer. The operand can be a boolean, an integer or a double.
* This operator returns an integer.
*
* @since 3.0
*/
O_Floor,
/**
* Round. Unary arithmetic operator. Returns a value rounded to the
* nearest integer. The operand can be a boolean, an integer or a double.
* This operator returns an integer.
*
* @since 3.0
*/
O_Round,
/**
* Square root. Unary arithmetic operator. The operand can be a boolean,
* an integer or a double. This operator returns a double.
*
* @since 3.0
*/
O_Sqrt,
/**
* Natural logarithm (base-e). Unary arithmetic operator. The operand
* can be a boolean, an integer or a double. This operator returns a double.
*
* @since 3.0
*/
O_Log,
/**
* Base-e exponential. Unary arithmetic operator. The operand can be a
* boolean, an integer or a double. This operator returns a double.
*
* @since 3.0
*/
O_Exp,
/**
* Power operator. `POW(x, y)` is equals to the value of `x` to the power of `y`.
* The operands can be booleans, integers or doubles. This operator
* returns a double.
*
* @since 3.0
*/
O_Pow,
/**
* Cosine. Unary arithmetic operator. The operand can be a
* boolean, an integer or a double. This operator returns a double.
*
* @since 3.0
*/
O_Cos,
/**
* Sine. Unary arithmetic operator. The operand can be a
* boolean, an integer or a double. This operator returns a double.
*
* @since 3.0
*/
O_Sin,
/**
* Tangent. Unary arithmetic operator. The operand can be a
* boolean, an integer or a double. This operator returns a double.
*
* @since 3.0
*/
O_Tan,
/**
* Integer decision variable. Operator with two operands that represent
* the lower bound and the upper bound of the decision (domain `[lb, ub]`).
* The bounds must be integer constants.
*
* @since 5.0
*/
O_Int,
/**
* Piecewise-linear function operator.
* The piecewise linear function is defined by two arrays of numbers
* giving the breakpoints of the function.
* This operator has exactly 3 operands: The first two operands must be
* two arrays of equal sizes (necessarily larger or equal to 2).
* These arrays must contain constant numbers (integers or doubles). The first
* array must contain numbers in ascending order. The third operand must
* be an integer or a double expression. The evaluation of the piecewise
* will fail if the value of the third operand is strictly smaller that
* the first element of the first array, or strictly larger than the last
* element of the first array. This operator returns a double.
*
* `PIECEWISE(x,y,z)` returns the image of z by the function defined by
* geometric points `(x[0],y[0]), (x[1],y[1]), ..., (x[n-1],y[n-1])`,
* For instance `PIECEWISE(ARRAY(0, 50, 100), ARRAY(0, 10, 100), 75)` returns `55`.
*
* Discontinuities are allowed in the definition of the function, that
* is to say that two geometric points can share the same x-coordinate.
* By convention the value taken by the function at such a discontinuous
* point is the one associated to the last occurrence of this
* x-coordinate in array x. For instance
* `PIECEWISE(ARRAY(0, 50, 50, 100), ARRAY(0, 0.1, 0.9, 1), 50)` returns `0.9`;
*
* @since 5.0
*/
O_Piecewise,
/**
* A list is an ordered collection of integers within a range `[0, n-1]` where `n`
* is the unique argument of this operator. Mathematically a list is a
* permutation of a subset of `[0, n-1]`. This operator takes exactly one
* operand: a strictly positive integer constant. All values in the list
* will be pairwise different, non negative and strictly smaller that this number.
*
* The elements of the list can be accessed individually with the operator {@link #O_At}.
*
* @since 5.5
*/
O_List,
/**
* The number of elements in a list or a set. This operator takes exactly
* one argument of type list or set and returns an integer.
*
* @since 5.5
*/
O_Count,
/**
* The index of a value in a list (-1 if the value is not in the list).
* This operator takes exactly two arguments: the first one is a list,
* the second one is an integer expression.
*
* @since 5.5
*/
O_IndexOf,
/**
* Partition. N-ary logical operator. `PARTITION(c1, c2, ..., cN)` is true
* if all lists or sets `c1, c2, ..., cN` form a partition of their common range.
* All the operands of this operator must be collections of the same type and
* on the same range.
*
* @since 5.5
*/
O_Partition,
/**
* Disjoint. N-ary logical operator. `DISJOINT(c1, c2, ..., cN)` is true if
* all lists or sets `c1, c2, ..., cN` are pairwise disjoint. All parameters of this
* operator must be collections of the same type and on the same range.
*
* @since 5.5
*/
O_Disjoint,
/**
* Native function. Native functions are used to compute the value
* of expressions from external functions written with your favorite
* programming language. Native functions are created with the dedicated
* method {@link LSModel#createNativeFunction}.
*
* @see LSNativeFunction
* @since 6.0
*/
O_NativeFunction,
/**
* Call a particular function. The first operand must be a function
* (like {@link #O_NativeFunction} or {@link #O_Function}).
* The other operands are passed to the function as arguments.
* If the function is not a native function, the number of operands
* must match the number of arguments of the function.
*
* @since 6.0
*/
O_Call,
/**
* Function. Functions are created with the dedicated method
* {@link LSModel#createFunction}.
*
* @since 7.0
*/
O_Function,
/**
* Argument of a function. Arguments are automatically and implicitely
* created when you create a function with method {@link LSModel#createFunction}.
*
* @since 7.0
*/
O_Argument,
/**
* Range expression. This operator takes exactly two integer operands.
* The first one is the lower bound (inclusive), the second one is the
* upper bound (exclusive).
*
* A range doesn't have a value by itself but can be
* used with N-ary operators like {@link #O_Sum}, {@link #O_Prod},
* {@link #O_Min}, {@link #O_Max}, {@link #O_Or}, {@link #O_And},
* {@link #O_Xor} or {@link #O_Array} to create expressions that have a
* dynamic number of operands.
*
* @since 7.0
*/
O_Range,
/**
* Contains. `contains(l, v)` is true if and only if the list `l` contains
* the value `v`. This operator takes exactly two arguments: the first
* one is a list, the second one is an integer expression.
*
* @since 7.5
*/
O_Contains,
/**
* A set is an unordered collection of integers within a range `[0, n-1]` where `n`
* is the unique argument of this operator. This operator takes exactly one
* operand: a strictly positive integer constant. All values in the set
* will be pairwise different, non negative and strictly smaller that this number.
* Contrary to the `O_List` operator, elements in a set are not ordered and cannot be
* indexed with `O_At`. Sets can only be manipulated with lambdas and n-ary operators like
* `O_Sum`, `O_Min`, `O_And`, ...
*
* @since 8.0
*/
O_Set
};
}
#endif
| true |
2dcb5a426e83d0d3c1881fe587d001e7f22b4b93 | C++ | hfutcgncas/ppqCode | /TabletennisCln/colorCamera/colorCamera/dataStruct.h | GB18030 | 1,451 | 2.71875 | 3 | [] | no_license | #pragma once
#include <vector>
using std::vector;
/*************************************************
class: BallPoint
Description: ƹ״̬
ļ¼ 2015/11/30
*************************************************/
class BallPoint
{
public:
#pragma region State x,y,z,Vx,Vy,Vz,Wx,Wy,Wz,t
double x; double y; double z;
double Vx; double Vy; double Vz;
double Wx; double Wy; double Wz;
double t;
#pragma endregion
#pragma region operator
void Copy(BallPoint src);
BallPoint operator*(double fac);
BallPoint operator+(BallPoint &A);
BallPoint operator-(BallPoint &A);
#pragma endregion
BallPoint();
void DispPoint();
bool isNan();
};
/*************************************************
class: cBallPosTemp
Description: ƹ״̬Ķ
ļ¼ 2015/11/30
*************************************************/
class cBallPosTemp
{
public:
vector<double> tempX;
vector<double> tempY;
vector<double> tempZ;
vector<double> tempVx;
vector<double> tempVy;
vector<double> tempVz;
vector<double> tempWx;
vector<double> tempWy;
vector<double> tempWz;
vector<double> tempTime;
void push_back(double x, double y, double z, double vx, double vy, double vz, double wx, double wy, double wz, double time);
void push_back(BallPoint newPoint);
void clear();
int size();
void del();//ɾͷ
void copy(cBallPosTemp src);
}; | true |
6df1f29a38db40f37a3e9fd43a0bcdb39ac1a173 | C++ | MasahiroOgawa/programmingcontest_challengebook | /2-4/stlmap.cpp | UTF-8 | 529 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <map>
using namespace std;
int main(){
map<int,string> m;
m.insert(make_pair(1,"one"));
m.insert(make_pair(10,"ten"));
auto it = m.find(1);
if(it != m.end()) cout << it->second << endl;
else cout << " 1 not found.\n";
it = m.find(2);
if(it != m.end()) cout << it->second << endl;
else cout << "2 not found.\n";
cout << m[10] << endl;
m.erase(10);
for(it = m.begin(); it != m.end(); ++it)
cout << it->first << ' ' << it->second << endl;
}
| true |
5a5ae58c2fa0980544c99d869cf4c10a4b1ee204 | C++ | lucifer1004/codeforces | /1402/a/a.cc | UTF-8 | 1,100 | 2.734375 | 3 | [
"CC-BY-4.0"
] | permissive | #include <iostream>
#include <stack>
#include <vector>
#define MOD 1000000007
using namespace std;
typedef int64_t ll;
struct Segment {
ll h, w;
};
stack<Segment> st;
ll ans = 0;
void insert(ll h, ll w) {
if (st.empty() || st.top().h < h)
st.push({h, w});
else if (st.top().h == h)
st.top().w += w;
}
void update(ll h, ll w, ll bh) {
h %= MOD, w %= MOD;
ll ch = h * (h + 1) / 2 % MOD;
ll cw = w * (w + 1) / 2 % MOD;
ll tot = ch * cw % MOD + cw * h % MOD * bh % MOD;
ans = (ans + tot) % MOD;
}
int main() {
int n;
cin >> n;
vector<ll> h(n + 1), w(n + 1);
for (int i = 0; i < n; ++i)
cin >> h[i];
for (int i = 0; i < n; ++i)
cin >> w[i];
for (int i = 0; i <= n; ++i) {
ll cw = w[i];
while (!st.empty() && st.top().h > h[i]) {
Segment first = st.top();
st.pop();
ll bh = h[i];
if (!st.empty() && st.top().h > h[i]) {
bh = st.top().h;
insert(st.top().h, first.w);
} else
cw += first.w;
ll dh = first.h - bh;
update(dh, first.w, bh);
}
insert(h[i], cw);
}
cout << ans;
} | true |
e3f87a59ff9719a7ee13b02fa7b0556e4d04055c | C++ | BlockJJam/MyCppStudy | /Chapter7_14(단언하기assert)/Chapter7_14.cpp | UHC | 582 | 3.375 | 3 | [] | no_license | /*
Assert - ܾϱ
뿡 Ȱϴ ִ
*/
#include <iostream>
#include <cassert> // assert.h
#include <array>
using namespace std;
void printValue(const array<int, 5> &my_array, const int& ix)
{
assert(ix >= 0);
assert(ix <= my_array.size() - 1);
cout << my_array[ix] << endl;
}
int main()
{
array<int, 5> my_array{ 1,2,3,4,5 };
printValue(my_array, 100);
// Ÿӿ Ű static_assert
const int x = 10;
//assert(x==5);
static_assert(x==5, "x should be 5(as)");
return 0;
} | true |
0fbee4531193a492b58b784fac7b8ba907e4427d | C++ | mailset/YingXiaohaoShengChengQi | /营销号生成器.cpp | UTF-8 | 944 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
string 参与者, 事件, 另一种说法;
cout << "营销号生成器 by mail_set\n";
cout << "请输入参与者:";
cin >> 参与者;
cout << "\n请输入事件:";
cin >> 事件;
cout << "\n请输入另一种说法:";
cin >> 另一种说法;
cout << "\n " << 参与者<< 事件 << "是怎么回事呢?" << 参与者 << "相信大家都很熟悉,但是" << 参与者 << 事件 << "是什么回事呢,下面就让小编带大家一起了解吧。\n";
cout << " " << 参与者 << 事件 << ",其实就是" << 另一种说法 << ",大家可能会很惊讶" << 参与者 << "怎么会" << 事件 << "呢?但事实就是这样,小编也感到非常惊讶。\n";
cout << " 这就是关于" << 参与者 << 事件 << "的事情了,大家有什么想法呢?欢迎在评论区告诉小编一起讨论哦!\n";
system("pause");
} | true |
8d1d16c7404fc08e5522c04a4e1dc4cf50ea9d02 | C++ | shauryauppal/Algo-DS-StudyMaterial | /Algorithm important/LCM.cpp | UTF-8 | 511 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
/*int main()
{
int a,b;
cin>>a>>b;
cout<<"\nLcm->";
for(int i=1;i<=a*b;i++)
if(i%a==0 && i%b==0)
{
cout<<i;
break;
}
}*/
//METHOD 2
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int lcm(int a,int b)
{
return (a*b)/gcd(a,b);
}
int main()
{
int a,b;
cin>>a>>b;
cout<<"\nGCD->"<<gcd(a,b);
cout<<"\nLCM->"<<lcm(a,b);
return 0;
}
| true |
db0b6d4779f71eefa04382511b9bd1774c9f30e1 | C++ | JonasEira/lab5 | /projects/assignment/code/Square.cpp | UTF-8 | 2,274 | 2.75 | 3 | [] | no_license | #include "Square.h"
#include "assignmentapp.h"
#include <iostream>
Square::Square() {}
Square::Square(float width, float height)
{
this->width = width;
this->height = height;
}
void Square::setColor(float r, float g, float b) {
this->c.r = r;
this->c.g = g;
this->c.b = b;
}
void Square::setPosition(Vector2D v)
{
this->position = Vector2D(v.getX() - this->width / 2.0f, v.getY() - this->height / 2.0f);
/*this->position = Vector2D(v);*/
}
void Square::setRotation(float rot)
{
this->rotation = rot;
}
void Square::update()
{
drawLines();
}
void Square::drawLines() {
for (int n = 0; n < 4; n++) {
App2D::BaseApp::LineData l;
lines.push_back(l);
}
Vector2D p1_norm = Vector2D(position.getX(), position.getY());
Vector2D p2_norm = Vector2D(position.getX() + width, position.getY());
Vector2D p3_norm = Vector2D(position.getX() + width, position.getY() + height);
Vector2D p4_norm = Vector2D(position.getX(), position.getY() + height);
Vector2D p1 = p1_norm.rotate(rotation);
Vector2D p2 = p2_norm.rotate(rotation);
Vector2D p3 = p3_norm.rotate(rotation);
Vector2D p4 = p4_norm.rotate(rotation);
Matrix2D m1 = Matrix2D(p1.getX(), p1.getY(), p2.getX(), p2.getY());
Matrix2D m2 = Matrix2D(p2.getX(), p2.getY(), p3.getX(), p3.getY());
Matrix2D m3 = Matrix2D(p3.getX(), p3.getY(), p4.getX(), p4.getY());
Matrix2D m4 = Matrix2D(p4.getX(), p4.getY(), p1.getX(), p1.getY());
lines.at(0).x1 = m1.getData(0, 0);
lines.at(0).y1 = m1.getData(0, 1);
lines.at(0).x2 = m1.getData(1, 0);
lines.at(0).y2 = m1.getData(1, 1);
lines.at(0).c1 = c;
lines.at(0).c2 = c;
lines.at(1).x1 = m2.getData(0, 0);
lines.at(1).y1 = m2.getData(0, 1);
lines.at(1).x2 = m2.getData(1, 0);
lines.at(1).y2 = m2.getData(1, 1);
lines.at(1).c1 = c;
lines.at(1).c2 = c;
lines.at(2).x1 = m3.getData(0, 0);
lines.at(2).y1 = m3.getData(0, 1);
lines.at(2).x2 = m3.getData(1, 0);
lines.at(2).y2 = m3.getData(1, 1);
lines.at(2).c1 = c;
lines.at(2).c2 = c;
lines.at(3).x1 = m4.getData(0, 0);
lines.at(3).y1 = m4.getData(0, 1);
lines.at(3).x2 = m4.getData(1, 0);
lines.at(3).y2 = m4.getData(1, 1);
lines.at(3).c1 = c;
lines.at(3).c2 = c;
for (App2D::BaseApp::LineData line : lines) {
Assignment::AssignmentApp::DrawLine(line);
}
}
Square::~Square()
{
}
| true |
8bb09024677624674df1b24a0616cb0307da6763 | C++ | SWSEP/Aspen | /src/attribute.cpp | UTF-8 | 2,091 | 2.75 | 3 | [
"MIT"
] | permissive | #include <string>
#include "mud.h"
#include "conf.h"
#include "attribute.h"
#include "world.h"
Attribute::Attribute(AttributeType type, AttributeApplication application, int mod, int id):
_type(type), _application(application), _mod(mod), _id(id)
{
}
AttributeType Attribute::GetType() const
{
return _type;
}
AttributeApplication Attribute::GetApply() const
{
return _application;
}
int Attribute::GetModifier() const
{
return _mod;
}
int Attribute::GetId() const
{
return _id;
}
int Attribute::GetAttributePoints(AttributeType t)
{
World* world = World::GetPtr();
switch(t)
{
default:
world->WriteLog("Tried to convert invalid attribute type.");
return 0;
case AttributeType::Health:
case AttributeType::Mana:
case AttributeType::MaxHealth:
case AttributeType::MaxMana:
return 1;
case AttributeType::Dex:
case AttributeType::Con:
case AttributeType::Str:
case AttributeType::Int:
case AttributeType::Wis:
return 5;
case AttributeType::MagicalArmor:
case AttributeType::PhysicalArmor:
return 4;
}
}
std::string Attribute::ToString(AttributeType t)
{
switch(t)
{
default:
return "unknown";
case AttributeType::Health:
return "health";
case AttributeType::Mana:
return "mana";
case AttributeType::MaxHealth:
return "max health";
case AttributeType::MaxMana:
return "max mana";
case AttributeType::Dex:
return "dexterity";
case AttributeType::Con:
return "constitution";
case AttributeType::Str:
return "strength";
case AttributeType::Int:
return "intelligence";
case AttributeType::Wis:
return "wisdom";
case AttributeType::MagicalArmor:
return "magical armor";
case AttributeType::PhysicalArmor:
return "physical armor";
}
}
| true |
7338d2c8134c5e07432e063a81b021062c1b0b36 | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/libs/multi_array/example/subview2.cpp | UTF-8 | 1,246 | 2.65625 | 3 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | // Copyright 2002 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Boost.MultiArray Library
// Authors: Ronald Garcia
// Jeremy Siek
// Andrew Lumsdaine
// See http://www.boost.org/libs/multi_array for documentation.
#include "boost/multi_array.hpp"
#include "boost/cstdlib.hpp"
int
main()
{
using boost::extents;
using boost::indices;
typedef boost::multi_array<int,3> array;
int data[] = {
0,1,2,3,
4,5,6,7,
8,9,10,11,
12,13,14,15,
16,17,18,19,
20,21,22,23
};
const int data_size=24;
array myarray(extents[2][3][4]);
myarray.assign(data,data+data_size);
//
// array_view dims:
// [base,stride,bound)
// [0,1,2), [1,1,3), [0,2,4)
//
typedef boost::multi_array_types::index_range range;
array::array_view<3>::type myview =
myarray[indices[range(0,2)][range(1,3)][range(0,4,2)]];
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 2; ++j)
for (array::index k = 0; k != 2; ++k)
assert(myview[i][j][k] == myarray[i][j+1][k*2]);
return boost::exit_success;
}
| true |
a0512ed3e8a86c4328752a575204bc10ea7026bd | C++ | Xnco/Data-Structures-and-Algorithms | /TitleProject_Cpp/0110_平衡二叉树.cpp | UTF-8 | 1,340 | 3.578125 | 4 | [] | no_license |
#include "pch.h";
#include <iostream>;
#include <vector>;
#include <sstream>;
#include <stack>;
#include <math.h>
using namespace std;
#pragma region 110_平衡二叉树
/*
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
// 每个子节点都得是平衡二叉树 - 16ms(99.37%), 16.3MB(99.06%)
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
int res = getHeight(root->left) - getHeight(root->right);
return abs(res) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
int getHeight(TreeNode* root)
{
if (root == nullptr) return 0;
int left = getHeight(root->left);
int right = getHeight(root->right);
int res = left > right ? left : right;
return res + 1;
}
};
#pragma endregion | true |
c34ea788400e581e573aa57cbcd9a34a5b9ad1ec | C++ | dipu-kr-sah/OOPS-BT-CSE-405 | /program-6/program-6.cpp | UTF-8 | 1,111 | 3.4375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class String
{
private:
string test;
public:
friend String operator +( String s1, String s2)
{
String s3;
s3.setTest(s1.getTest()+" "+s2.getTest());
return s3;
}
public:
void setTest(string name)
{
test=name;
}
void display()
{
cout<<getTest()<<endl;
}
string getTest()
{
return test;
}
bool check(string text)
{
if(text.length()==test.length())
{
for(int i=0;i<test.length();i++)
{
if(test[i]!=test[i])
return false;
}
return true;
}
return false;
}
bool check(string text1,string text2)
{
if(text2.length()==text1.length())
{
for(int i=0;i<text1.length();i++)
{
if(text2[i]!=text1[i])
return false;
}
return true;
}
return false;
}
};
int main()
{
String firstName;
String lastName;
firstName.setTest("dipu");
lastName.setTest("kumar");
firstName.display();
cout<<(firstName+lastName).getTest()<<endl;
(firstName.check(lastName.getTest(),lastName.getTest()))?cout<<"Matched"<<endl:cout<<"Not matched"<<endl;
return 0;
}
| true |
721a56a4863ce8e056685e0bf0bcd3c859c73c83 | C++ | showmic96/Online-Judge-Solution | /Gym/101652S/13586975_AC_30ms_3552kB.cpp | UTF-8 | 1,211 | 2.8125 | 3 | [] | no_license | // In the name of Allah the Most Merciful.
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string ar;
cin >> ar;
int l1 = 0 , r1 = 0 , l2 = 0 , r2 = 0 , now = 0 , mx1 = 0 , mx2 = 0 , last = 0;
for(int i=0;i<ar.size();i++){
if(ar[i]=='B')now++;
else now--;
if(now<0){
now = 0;
last = i+1;
}
if(now>mx1){
mx1 = now;
l1 = last+1;
r1 = i+1;
}
}
now = 0 , last = 0;
for(int i=0;i<ar.size();i++){
if(ar[i]=='B')now--;
else now++;
if(now<0){
now = 0;
last = i+1;
}
if(now>mx2){
mx2 = now;
l2 = last+1;
r2 = i+1;
}
}
if(r1-l1>r2-l2)cout << l1 << " " << r1 << endl;
else if(r1-l1<r2-l2)cout << l2 << " " << r2 << endl;
else{
if(l1<l2)cout << l1 << " " << r1 << endl;
else if(l1>l2)cout << l2 << " " << r2 << endl;
else{
if(r1<r2)cout << l1 << " " << r1 << endl;
else cout << l2 << " " << r2 << endl;
}
}
return 0;
}
| true |
e8b0fb3ec7d3fc5e51e5d2e1baf34694aa068f74 | C++ | gwanhyeon/algorithm_study | /beakjoon_algorithm/beakjoon_algorithm/브루트포스/NM시리즈(11).cpp | UTF-8 | 1,202 | 2.5625 | 3 | [] | no_license | //
// NM시리즈(11).cpp
// beakjoon_algorithm
//
// Created by kgh on 01/10/2019.
// Copyright © 2019 kgh. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <string>
using namespace std;
int n,m;
int arr[10001];
int check[10001];
vector<int> res;
set<string> s;
void go(int index, int cnt){
if(cnt == m){
bool tf = false;
string str = "";
for(int i=0; i<res.size(); i++){
char a = res[i] + '0';
str = str + a;
}
if(s.find(str) == s.end()){
s.insert(str);
tf = false;
}else {
tf = true;
}
if(tf == false){
for(int i=0; i<res.size(); i++){
cout << res[i] << ' ';
}
cout << '\n';
}
return;
}
for(int i=0; i<n; i++){
res.push_back(arr[i]);
go(i,cnt+1);
res.pop_back();
}
}
int main(void){
//중복순열
cin >> n >> m;
for(int i=0; i<n; i++){
cin >> arr[i];
}
sort(arr, arr+n);
go(0,0);
return 0;
}
| true |
eeed913264b0b6f4899d2931bc9fabaa1b4a55c3 | C++ | 4laconic/MiAPR | /First_K-means/kmeans.cpp | UTF-8 | 3,247 | 2.90625 | 3 | [] | no_license | #ifndef kmeanscpp
#define kmeanscpp
#include "Kmeans.h"
#define sqr(x) (x)*(x)
#define TCluster list<point>
#define TClusters vector<TCluster >
Kmeans::Kmeans(int countPoint, int countClus, int w, int h, TImage *pImg) {
n = countPoint;
k = countClus;
width = w;
height = h;
pImage = pImg;
}
inline void Kmeans::GenerateCentroids() {
centroids.assign(k, 0);
for (short i = 0; i < k; ++i) {
centroids[i] = clusters[i].front();
centroids[i].SetKernel();
}
}
inline void Kmeans::GeneratePoints() {
clusters.assign(k, TCluster());
for (int i = 0; i < n; ++i) {
int x = rand() % (width - 30) + 15;
int y = rand() % (height - 30) + 15;
point temp(x, y);
clusters[i % k].push_back(temp);
}
}
inline void Kmeans::GenerateClusters() {
vector<TClusters > newClusters(k, TClusters(k, TCluster()));
TClusters ResultCluster(k, TCluster());
genClusThread.assign(k, 0);
for (int i = 0; i < k; ++i) {
genClusThread[i] = new ThreadGen(true);
genClusThread[i]->InitNewClusters(&newClusters[i]);
genClusThread[i]->InitCentroids(¢roids);
genClusThread[i]->InitProcessedCluster(&clusters[i]);
genClusThread[i]->Resume();
}
for (int i = 0; i < k; ++i) {
genClusThread[i]->WaitFor();
for (int j = 0; j < k; ++j)
ResultCluster[j].insert(ResultCluster[j].begin(),
newClusters[i][j].begin(), newClusters[i][j].end());
}
clusters.clear();
clusters = ResultCluster;
}
inline bool Kmeans::ChangeCentroids(point &newCentroid, point &oldCentroid) {
oldCentroid.UnsetKernel();
newCentroid.SetKernel();
return newCentroid != oldCentroid;
}
inline bool Kmeans::CentroidWasChanged() {
TCentroids newCentroids(k, point());
selCentThread.assign(k, 0);
for (int i = 0; i < k; ++i) {
selCentThread[i] = new ThreadSel(true);
selCentThread[i]->InitProcessedCluster(&clusters[i]);
selCentThread[i]->InitCentroid(&newCentroids[i]);
selCentThread[i]->Resume();
}
bool centroidWasChanged = false;
for (int i = 0; i < k; ++i) {
selCentThread[i]->WaitFor();
centroidWasChanged |= ChangeCentroids(newCentroids[i], centroids[i]);
centroids[i] = newCentroids[i];
}
return centroidWasChanged;
}
inline void Kmeans::ClearScreen(TCanvas *pCanvas) {
pCanvas->Brush->Color = clWhite;
pCanvas->Pen->Color = clBlack;
pCanvas->Rectangle(0, 0, width, height);
}
inline void Kmeans::DrawPoint() {
ClearScreen(pImage->Canvas);
for (int i = 0; i < k; ++i) {
TCluster::iterator it;
for (it = clusters[i].begin(); it != clusters[i].end(); ++it)
it->Draw(pImage, i);
centroids[i].Draw(pImage, i);
}
}
inline void Kmeans::FreeMemory() {
for (int i = 0; i < k; ++i) {
if (!clusters[i].empty())
clusters[i].clear();
}
clusters.clear();
}
inline void Kmeans::Algorithm() {
GeneratePoints();
GenerateCentroids();
do {
GenerateClusters();
DrawPoint();
Sleep(100);
pImage->Refresh();
} while (CentroidWasChanged());
DrawPoint();
FreeMemory();
}
#endif
| true |
b09e42d35273c2ffdd59996822ffc5237e1c8ed5 | C++ | arthurarp/Maratonas-de-programacao | /tep/10/contest/B/main.cpp | UTF-8 | 386 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(void)
{
ios::sync_with_stdio(false);
int n; cin >> n;
vector<int> v;
for(int i = 0; i < n; ++i)
{
int number; cin >> number;
v.push_back(number);
}
double divisor = 0;
for(int i = 0; i < n; ++i)
divisor += (1.0 / v[i]);
double result = 1.0 / divisor;
cout << result << endl;
return 0;
}
| true |
6d2805ade9c9a0546a0a098e6c5295c548782292 | C++ | Pyerce/301Assignment4 | /person.cpp | UTF-8 | 583 | 2.984375 | 3 | [] | no_license | //
// person.cpp
// Assignment4
//
// Created by Pierce Findlay on 4/16/19.
// Copyright © 2019 Pierce Findlay. All rights reserved.
// Pierce Findlay
// Section 2
#include "person.h"
Person::Person()
{
payRate = 0;
hoursWorked = 0;
}
string Person::getFirstName()
{
return firstName;
}
string Person::getLastName()
{
return lastName;
}
string Person::fullName()
{
return firstName + " " + lastName;
}
float Person::getPayRate()
{
return payRate;
}
float Person::getHoursWorked()
{
return hoursWorked;
}
float Person::totalPay()
{
return (payRate * hoursWorked);
}
| true |
d9c0ef94c560fccd3374385f793af3c8f1e864a8 | C++ | ChunkyPastaSauce/LabVIEW-libsvm | /cpp/LVUtility.cpp | UTF-8 | 1,709 | 2.890625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | #include "stdafx.h"
#include "LVUtility.h"
#include "LVTypeDecl.h"
#include "LVException.h"
#include "extcode.h"
#include <codecvt>
void LVWriteStringHandle(LStrHandle &strHandle, const char* c_str, size_t length) {
// Check if handle state is good.
if (DSCheckHandle(strHandle) == noErr) {
// Reserve (resize) enough room for the pascal string.
MgErr err = DSSetHSzClr(strHandle, (sizeof(int32_t) + length));
if (err) {
strHandle = NULL;
throw LVException(__FILE__, __LINE__, "LabVIEW Memory Manager: Failed to allocate memory for string (Out of memory?)");
}
// Update pascal size property, and copy data into LabVIEW memory.
(*strHandle)->cnt = static_cast<int32>(length);
MoveBlock(c_str, (*strHandle)->str, length);
}
else
{
throw LVException(__FILE__, __LINE__, "The string handle passed to LVWriteStringHandle is not valid (out of zone/deleted?)");
}
}
void LVWriteStringHandle(LStrHandle &strHandle, const char* c_str) {
// Don't want to pass a nullpointer to strlen, behaviour is undefined.
size_t length;
if (c_str == NULL) {
length = 0;
}
else {
length = std::strlen(c_str);
}
LVWriteStringHandle(strHandle, c_str, length);
}
void LVWriteStringHandle(LStrHandle &strHandle, std::string str) {
LVWriteStringHandle(strHandle, str.c_str(), str.length());
}
void LVWriteStringHandle(LStrHandle &strHandle, std::wstring wstr){
// Setup converter
typedef std::codecvt_utf8<wchar_t> convert_type;
std::wstring_convert<convert_type, wchar_t> converter;
// Use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
std::string converted_str = converter.to_bytes(wstr);
LVWriteStringHandle(strHandle, converted_str.c_str(), converted_str.length());
}
| true |
d62e13f7d011d435a45a488c0c995fab5e7415de | C++ | c-pages/dia2code---Maxscript | /exemple/codeCPP_exemple 1/Gadget.cpp | UTF-8 | 1,560 | 2.515625 | 3 | [] | no_license | /////////////////////////////////////////////////
// Headers
/////////////////////////////////////////////////
#include <Gadget.h>
namespace gui {
public:
/////////////////////////////////////////////////
Gadget::Gadget ()
: m_actif ( true )
, m_visible ( true )
{
}
/////////////////////////////////////////////////
Gadget::Gadget (Gadget & original)
: m_actif ( true )
, m_visible ( true )
{
}
/////////////////////////////////////////////////
Gadget& Gadget::operator= (Gadget & original)
{
}
/////////////////////////////////////////////////
void Gadget::setActif (bool etat)
{
}
/////////////////////////////////////////////////
bool Gadget::getActif () const
{
}
/////////////////////////////////////////////////
void Gadget::setVisible (bool valeur)
{
}
/////////////////////////////////////////////////
bool Gadget::getVisible () const
{
}
/////////////////////////////////////////////////
void Gadget::initialiser ()
{
}
/////////////////////////////////////////////////
void Gadget::initialiser_composants ()
{
}
/////////////////////////////////////////////////
void Gadget::initialiser_interactions ()
{
}
/////////////////////////////////////////////////
void Gadget::actualiser ()
{
}
/////////////////////////////////////////////////
void Gadget::traiter_events (const sf::Event& evenement)
{
}
/////////////////////////////////////////////////
void Gadget::draw (sf::RenderTarget& target, sf::RenderStates states) const
{
}
} // fin namespace gui
| true |
bc06ff9c92e6aba2179aff175cae6886a6d2ffa8 | C++ | pomagma/pomagma | /src/platform/worker_pool_test.cpp | UTF-8 | 1,076 | 3.109375 | 3 | [
"MIT"
] | permissive | #include <pomagma/platform/util.hpp>
#include <pomagma/platform/worker_pool.hpp>
using namespace pomagma;
struct Task
{
std::chrono::milliseconds duration;
};
struct Processor
{
void operator() (const Task & task)
{
POMAGMA_DEBUG("sleeping for " << task.duration.count() << "ms");
std::this_thread::sleep_for(task.duration);
}
};
void test_threadpool (
size_t thread_count,
size_t max_duration,
size_t wait_count)
{
POMAGMA_INFO("Testing pool of " << thread_count << " threads");
POMAGMA_ASSERT_LT(0, thread_count);
Processor processor;
WorkerPool<Task, Processor> pool(processor, thread_count);
for (size_t duration = 0; duration <= max_duration; ++duration) {
POMAGMA_DEBUG("scheduling sleep for " << duration << "ms");
pool.schedule(Task({std::chrono::milliseconds(duration)}));
}
for (size_t i = 0; i < wait_count; ++i) {
pool.wait();
}
}
int main ()
{
test_threadpool(1, 20, 0);
test_threadpool(10, 100, 0);
test_threadpool(10, 20, 2);
return 0;
}
| true |
999f250d52d679401bed55a7513a5b4cc0d4e674 | C++ | ShashankSaumya123/CS-141 | /lab5_q12.cpp | UTF-8 | 592 | 3.859375 | 4 | [] | no_license | // Ask for month number and print number of days in that month
// including library
#include<iostream>
using namespace std;
int main()
{
// defining variables
int month;
// Asking for input
cout << "Please write the month number" << endl;
cin >> month;
// if else
if ((month == 1)||(month == 3)||(month == 5)||(month == 7)||(month == 8)||(month == 10)||(month == 12))
cout << "The number of days are 31" << endl;
else if (month == 2)
cout << "The number of days are 28" << endl; // considering year to be non leap year
else cout << "The number of days are 30" << endl;
return 0;
}
| true |
ed0afddffa2eb40fe0f3a6932442776b713a9207 | C++ | jtran8/Langtons-Ant | /ant.hpp | UTF-8 | 733 | 2.71875 | 3 | [] | no_license | /*******************************************************************************
** Author: Jacky Tran
** Date: 04/15/2019
** Description: This is the specification file for the ant class. This class
** keeps track of the ant's location and direction. This class
** also rotates and moves the ant.
*******************************************************************************/
#ifndef ANT_HPP
#define ANT_HPP
#include "board.hpp"
class Ant
{
private:
Board* antPosition;
char orientation;
int rows;
int cols;
int xCoord;
int yCoord;
public:
Ant(int, int, int, int);
void turn();
void move();
void print();
void deallocate();
};
#endif | true |
8bd580354a1b49f6070009fab7db006c6dc234b9 | C++ | vuongsoi/baitap | /baithiso2.cpp | UTF-8 | 395 | 2.65625 | 3 | [] | no_license | #include<stdio.h>
int main(){
int sonam;
float tongvon,tylesolai;
printf("tongvon la:\n");
scanf("%f",&tongvon);
printf("tylesolai la:\n");
scanf("%f",&tylesolai);
printf("sonam la:\n");
scanf("%d",&sonam);
for(int i=1;i<=sonam;++i){
float lai=(tongvon*tylesolai)/100;
tongvon+=lai;
printf("sonam:%d\n tien lai:%f\n tongtien:%f\n",i,lai,tongvon);
}
return 0;
}
| true |
4639336d3e1e388b17b4b28fec5705d0be2458c4 | C++ | RubisetCie/mario-constructor-master | /Sources/Miscs/effect_shard.cpp | UTF-8 | 895 | 2.71875 | 3 | [] | no_license | /* Creator : Matthieu (Rubisetcie) Carteron
Language: C++
*/
#include <SFML/Graphics.hpp>
#include "../../Headers/Miscs/effect_shard.hpp"
#define SHARD_ROTATESPEED 25
using namespace sf;
Effect_Shard::Effect_Shard(Texture* shardTexture, Vector2f speed, Vector2f position, float startangle, float height) : Effect(position)
{
m_sprite.setTexture(*shardTexture);
m_sprite.setOrigin(8, 8);
m_sprite.setRotation(startangle);
m_movedistance = speed;
m_startheight = height;
}
void Effect_Shard::update()
{
if (m_movedistance.x > 0)
m_sprite.rotate(SHARD_ROTATESPEED);
else
m_sprite.rotate(-SHARD_ROTATESPEED);
m_movedistance.y += 0.25;
m_sprite.move(m_movedistance);
if (m_sprite.getPosition().y > m_startheight + 480)
m_destroyed = true;
}
void Effect_Shard::draw(RenderTarget& target, RenderStates) const
{
target.draw(m_sprite);
}
| true |
c60258f71d6bdaddca8ae95d773e51f7c62615f0 | C++ | rotanov/fefu-mmorpg | /3rd/deku2d/2de_Math.cpp | UTF-8 | 6,237 | 2.875 | 3 | [] | no_license | #include "2de_Math.h"
#include <cstring>
#include <cstdio>
#include <limits>
#include <algorithm>
#include "2de_Vector2.h"
#include "2de_Matrix2.h"
namespace Deku2D
{
unsigned g_seed = 152406923;
//unsigned g_seed = time(NULL);
static float SineTable[Const::Math::SINE_COSINE_TABLE_DIM], CosineTable[Const::Math::SINE_COSINE_TABLE_DIM];
bool SqareEq(float a, float b, float c, float &t0, float &t1)
{
float d = b * b - 4.0f * a * c;
if (d < 0.0f)
return false;
d = static_cast<float>(sqrt(d));
float oo2a = 1.0f / (2.0f * a);
t0 = (- b + d) * oo2a;
t1 = (- b - d) * oo2a;
if (t1 > t0)
std::swap(t0, t1);
return true;
}
void GenSinTable()
{
float a = 0, add = static_cast<float>(Const::Math::PI) * 2 / static_cast<float>(Const::Math::SINE_COSINE_TABLE_DIM);
for (int i = 0; i < Const::Math::SINE_COSINE_TABLE_DIM; ++i)
{
SineTable[i] = static_cast<float>(sin(a));
CosineTable[i] = static_cast<float>(cos(a));
a += add;
}
}
float fSinr(float angle){return SineTable[static_cast<int>(angle * Const::Math::radanglem) % Const::Math::SINE_COSINE_TABLE_DIM];}
float fSind(float angle){return SineTable[static_cast<int>(angle * Const::Math::deganglem) % Const::Math::SINE_COSINE_TABLE_DIM];}
float fSini(int index){return SineTable[index % Const::Math::SINE_COSINE_TABLE_DIM];}
float fCosr(float angle){return CosineTable[static_cast<int>(angle * Const::Math::radanglem) % Const::Math::SINE_COSINE_TABLE_DIM];}
float fCosd(float angle){return CosineTable[static_cast<int>(angle * Const::Math::deganglem) % Const::Math::SINE_COSINE_TABLE_DIM];}
float fCosi(int index){return CosineTable[index % Const::Math::SINE_COSINE_TABLE_DIM];}
float HalfPlaneSign(const Vector2 &u0, const Vector2 &u1, const Vector2 &p) // Кстати, это площадь тругольника на этих трёх точках. // Или параллелограма.
{
return (u0.x - p.x) * (u1.y - p.y) -
(u0.y - p.y) * (u1.x - p.x);
}
bool IntersectLines(const Vector2 &u0, const Vector2 &u1, const Vector2 &v0, const Vector2 &v1, Vector2 &Result)
{
float a1 = u1.y - u0.y;
float b1 = u0.x - u1.x;
float a2 = v1.y - v0.y;
float b2 = v0.x - v1.x;
Matrix2 deltaMatrix(a1, b1, a2, b2);
float deltaDet = deltaMatrix.Determinant();
if (Equal(deltaDet, 0.0f))
return false; // Прямые параллельны, т.е. a1b2 - a2b1 == 0; Кстати, условие перпендикулярности: a1a2 == -b1b2;
// @todo А что, если прямые совпадают?
float c1 = u1.y * u0.x - u1.x * u0.y; //a1 * u0.x + b1 * u0.y;
float c2 = v1.y * v0.x - v1.x * v0.y; //a2 * v0.x + b2 * v0.y;
Result = Vector2(Matrix2(c1, b1, c2, b2).Determinant() / deltaDet,
Matrix2(a1, c1, a2, c2).Determinant() / deltaDet);
return true;
}
bool IntersectSegments(const Vector2 &u0, const Vector2 &u1, const Vector2 &v0, const Vector2 &v1, Vector2 &Result)
{
if (HalfPlaneSign(u0, u1, v0) * HalfPlaneSign(u0, u1, v1) > 0)
return false;
if (HalfPlaneSign(v0, v1, u0) * HalfPlaneSign(v0, v1, u1) > 0)
return false;
// In the "IntersectLines" lies check if lines are parallel, but at that point we're already know that they're not
if (!IntersectLines(u0, u1, v0, v1, Result))
return false;
return true;
}
bool AreSegmentsIntersect(const Vector2 &u0, const Vector2 &u1, const Vector2 &v0, const Vector2 &v1)
{
if (HalfPlaneSign(u0, u1, v0) * HalfPlaneSign(u0, u1, v1) > 0)
return false;
if (HalfPlaneSign(v0, v1, u0) * HalfPlaneSign(v0, v1, u1) > 0)
return false;
return true;
}
bool IntersectCircles(const Vector2 &p0, const float r0, const Vector2 &p1, const float r1, Vector2 &Normal, float &Depth)
{
Vector2 p0p1 = p1 - p0;
if ((Sqr(p0p1.x) + Sqr(p0p1.y)) >= Sqr(r0 + r1))
return false;
Normal = p0p1.Normalized();
Depth = std::fabs(r1 - r0);
return true;
}
bool PointInsidePolygon();
float DistanceToLine(const Vector2 &u0, const Vector2 &u1, const Vector2 &p)
{
return HalfPlaneSign(u0, u1, p) / (u0 - u1).Length();
}
float DistanceToSegment(const Vector2 &u0, const Vector2 &u1, const Vector2 &p)
{
Vector2 v = u1 - u0;
Vector2 w = p - u0;
float c1 = w * v;
if (c1 <= 0)
return (p - u0).Length() * Sign(HalfPlaneSign(u0, u1, p)); // Мы же хотим получить расстояние со знаком даже если это расстояние до концов отрезка.
float c2 = v * v;
if (c2 <= c1)
return (p - u1).Length() * Sign(HalfPlaneSign(u0, u1, p));
return HalfPlaneSign(u0, u1, p) / (u0 - u1).Length();
}
__INLINE void CalcConvexHull(std::vector<Vector2> &a)
{
class CalcConvexHullHelper
{
public:
static __INLINE bool cmp (Vector2 a, Vector2 b)
{
return a.x < b.x
|| (a.x == b.x
&& a.y < b.y);
}
/**
* cw and cww is some strange way to Implement HalfPlaneSign() with
* devilish copy-paste and having 3 instead of 2 multiplications
* @todo: replace by HalfPlaneSign
*/
static __INLINE bool cw (Vector2 a, Vector2 b, Vector2 c)
{
return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) < 0;
}
static __INLINE bool ccw (Vector2 a, Vector2 b, Vector2 c)
{
return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > 0;
}
};
if (a.size() == 1) return;
sort (a.begin(), a.end(), &CalcConvexHullHelper::cmp);
Vector2 p1 = a[0], p2 = a.back();
std::vector<Vector2> up, down;
up.push_back (p1);
down.push_back (p1);
for (size_t i=1; i<a.size(); ++i)
{
if (i==a.size()-1 || CalcConvexHullHelper::cw (p1, a[i], p2))
{
while (up.size()>=2 && !CalcConvexHullHelper::cw (up[up.size()-2], up[up.size()-1], a[i]))
up.pop_back();
up.push_back (a[i]);
}
if (i==a.size()-1 || CalcConvexHullHelper::ccw (p1, a[i], p2))
{
while (down.size()>=2 && !CalcConvexHullHelper::ccw (down[down.size()-2], down[down.size()-1], a[i]))
down.pop_back();
down.push_back (a[i]);
}
}
a.clear();
for (size_t i=0; i<up.size(); ++i)
a.push_back (up[i]);
for (size_t i=down.size()-2; i>0; --i)
a.push_back (down[i]);
}
} // namespace Deku2d
| true |
deb4e77e1ac676de65706bacad24bf7b10ab8341 | C++ | mahdialikhasi/Sharif-AI-Challenge-2019 | /myClient/client/src/Model/Interface/Hero.cpp | UTF-8 | 3,512 | 3.015625 | 3 | [
"CC0-1.0"
] | permissive | //
// Created by dot_blue on 1/23/19.
//
#include <iostream>
#include "Hero.h"
Hero::Hero(bool _isNull) {
if(_isNull) {
// this->_id = -1;
this->isNull = true;
}
}
Hero::~Hero() {// Check the vectors
for (std::vector<Ability *>::iterator it = _abilities.begin() ; it != _abilities.end(); ++it){
delete *it;
}
_abilities.clear();
}
Hero::Hero(Hero & _hero):_currentCell(_hero._currentCell) {
this->_id = _hero._id;
this->_currentHP = _hero._currentHP;
this->_remRespawnTime = _hero._remRespawnTime;
this->_heroConstants = _hero._heroConstants;
this->_recentPath = _hero._recentPath;
this->copy_abilities(_hero._abilities);
this->isNull = _hero.isNull;
}
//----------------id-------------------
int Hero::getId() const {
return _id;
}
//------------currentHP----------------
int Hero::getCurrentHP() const {
return _currentHP;
}
//------------respawnTime--------------
int Hero::getRemRespawnTime() const {
return _remRespawnTime;
}
//-----------heroConstants-------------
HeroConstants Hero::heroConstants() const {
return _heroConstants;
}
//-------------abilities---------------
std::vector<Ability *> Hero::getAbilities() const {
return _abilities;
}
void Hero::set_abilities(std::vector<Ability *> &_abilities) {
Hero::_abilities = _abilities;
for(std::vector<Ability *>::iterator it = _abilities.begin();
it < _abilities.end(); ++it){
if((*it)->getType() == AbilityType::OFFENSIVE){
_offensiveAbilities.push_back(*it);
} else if ((*it)->getType() == AbilityType::DODGE){
_dodgeAbilities.push_back(*it);
} else if ((*it)->getType() == AbilityType::DEFENSIVE){
_defensiveAbilities.push_back(*it);
}
}
}
void Hero::copy_abilities(std::vector<Ability *> &_abilities) {
std::vector<Ability *> cpy_abilities;
for(Ability * ability_ptr : _abilities){
Ability* tmp_ability_ptr = new Ability(*ability_ptr);
cpy_abilities.push_back(tmp_ability_ptr);
}
this->set_abilities(cpy_abilities);
}
std::vector<Ability *> Hero::getDodgeAbilities() const {
return _dodgeAbilities;
}
std::vector<Ability *> Hero::getDefensiveAbilities() const {
return _defensiveAbilities;
}
std::vector<Ability *> Hero::getOffensiveAbilities() const {
return _offensiveAbilities;
}
//-------------currentCell---------------
Cell& Hero::getCurrentCell() const {
return *_currentCell;
}
//-------------recentPath----------------
std::vector<Cell *> Hero::getRecentPath() const {
return _recentPath;
}
bool Hero::operator==(const Hero &_hero) {
return (this->_id == _hero.getId()) && (this->isNull == _hero.isNull);
}
bool Hero::operator!=(const Hero &_hero) {
return !(*this == _hero);
}
HeroName Hero::getName() const {
return _heroConstants.getName();
}
std::vector<AbilityName> Hero::getAbilityNames() const {
return _heroConstants.getAbilityNames();
}
int Hero::getMaxHP() const {
return _heroConstants.getMaxHP();
}
int Hero::getMoveAPCost() const {
return _heroConstants.getMoveAPCost();
}
int Hero::remainingRespawnTime() const {
return _heroConstants.getRespawnTime();
}
Ability Hero::getAbility(AbilityName _abilityName) {
for(Ability * tmp_ability : this->_abilities){
if(tmp_ability->getName() == _abilityName)
return *tmp_ability;
}
return Ability::NULL_ABILITY;
}
//Single tone
Hero Hero::NULL_HERO(true);
| true |
7f54ae112e250ed88314261ded0972aee15676dd | C++ | IvanDimitrov2002/school | /c/11/hw2/server/main.cpp | UTF-8 | 1,326 | 2.609375 | 3 | [] | no_license | #include "server.h"
#include "processauth.h"
#include "processusers.h"
#include <iostream>
int main(){
std::vector<std::string> paths;
paths.push_back("/login.html");
paths.push_back("/home.html");
paths.push_back("/api/login");
paths.push_back("/api/get_users");
std::vector<Process*> processes;
processes.push_back(new Process());
processes.push_back(new Process());
processes.push_back(new ProcessAuth());
processes.push_back(new ProcessUsers());
Server server = Server(paths, processes);
std::vector<std::string> args;
args.push_back("test");
args.push_back("1234");
Request* req1 = new Request("192.168.0.106", "/login.html");
Request* req2 = new Request("192.168.0.106", "/api/login", args);
Request* req3 = new Request("192.168.0.106", "/api/get_users");
Response* res1 = server.routeRequest(req1);
Response* res2 = server.routeRequest(req2);
Response* res3 = server.routeRequest(req3);
std::cout << res1->getStatus() << " " << res1->getMessage() << std::endl;
std::cout << res2->getStatus() << " " << res2->getMessage() << std::endl;
std::cout << res3->getStatus() << " " << res3->getMessage() << std::endl;
delete req1;
delete req2;
delete req3;
delete res1;
delete res2;
delete res3;
return 0;
} | true |
37fc00b498f8cb79aafcdbab42df8191ed46f96e | C++ | zuozhoulin/cpp | /note小知识/7-point_to_function_point指向函数指针的指针.cpp | UTF-8 | 1,350 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <functional>
using namespace std;
//定义func为函数
typedef int func(int);
//等价定义。
typedef int (*func2)(int);
//定义指向函数的指针
typedef func *func_ptr;
//定义指向函数指针的指针
typedef func_ptr *func_ptr_ptr;
/*
int (**p)(int);
(**p)(int)是个整数。**p 是个函数,返回一个整数。
于是 *p 是个函数的指针。 p 是个函数指针的指针。
按定义顺序解释:
int **p(int); 小括号的优先级最高:**p(int)实际上是先执行 p(int) 的,所以,这个定义
就是 **p(int) 是个整数,所以 *p(int) 就是整数的指针,而p(int) 就是指针的指针,
所以p就是函数的指针(实际上最后一步是个语法糖。
https://www.zhihu.com/question/38955439
*/
func_ptr_ptr p;
//另一种c++ 11 的方法
int f(int i)
{
cout << i << endl;
return 0;
}
typedef std::function<int(int)> fp;
using fp2=std::function<double(double, double)>;
int main(int argc, char const *argv[])
{
//使用decltype():
int (*p)(int) = f;//p是函数指针
decltype(p) *p2 = &p;//p2是指向函数指针的指针。
(*p2)(1024);
//另一种简洁的方式
fp fp_value=f;
auto fpp_value=&fp_value;
//decltype(fp_value) *fpp_value=&fp_value;
(*fpp_value)(1024);
return 0;
} | true |
f3323b98ff1a9992cfce3211467f3d2028aa87c5 | C++ | CompPhysics/ComputationalPhysics | /doc/Programs/OOExamples/solar-system/vec3.cpp | UTF-8 | 2,935 | 3.703125 | 4 | [
"CC0-1.0"
] | permissive | #include "vec3.h"
#include <cmath>
#include <iostream>
using namespace std;
vec3::vec3()
{
zeros();
}
vec3::vec3(double x, double y, double z)
{
components[0] = x;
components[1] = y;
components[2] = z;
}
void vec3::print()
{
// Will print matlab syntax vector. Output will be like: [2.09, 5.3, 9.1];
cout << "[" << components[0] << ", " << components[1] << ", " << components[2] << "]" << endl;
}
void vec3::print(string name)
{
// Will print matlab syntax vector with a name. Output will be like: A = [2.09, 5.3, 9.1];
cout << name << " = ";
print();
}
vec3 vec3::cross(vec3 otherVector)
{
return vec3(y()*otherVector.z()-z()*otherVector.y(), z()*otherVector.x()-x()*otherVector.z(), x()*otherVector.y()-y()*otherVector.x());
}
double vec3::dot(vec3 otherVector)
{
return otherVector[0]*components[0] + otherVector[1]*components[1] + otherVector[2]*components[2];
}
void vec3::normalize()
{
double length = this->length();
if(length > 0) {
components[0] /= length;
components[1] /= length;
components[2] /= length;
}
}
vec3 vec3::normalized()
{
vec3 newVector = *this;
newVector.normalize();
return newVector;
}
double vec3::lengthSquared()
{
// Returns the square of the length (or norm) of the vector
return components[0]*components[0]+components[1]*components[1]+components[2]*components[2];
}
double vec3::length()
{
// Returns the length (or norm) of the vector
return sqrt(lengthSquared());
}
void vec3::zeros()
{
components[0] = 0;
components[1] = 0;
components[2] = 0;
}
vec3 &vec3::operator+=(double rhs)
{
components[0] += rhs;
components[1] += rhs;
components[2] += rhs;
return *this;
}
vec3 &vec3::operator+=(vec3 rhs)
{
components[0] += rhs[0];
components[1] += rhs[1];
components[2] += rhs[2];
return *this;
}
vec3 &vec3::operator*=(double rhs)
{
components[0] *= rhs;
components[1] *= rhs;
components[2] *= rhs;
return *this;
}
vec3 &vec3::operator*=(vec3 rhs)
{
components[0] *= rhs[0];
components[1] *= rhs[1];
components[2] *= rhs[2];
return *this;
}
vec3 &vec3::operator-=(double rhs)
{
components[0] -= rhs;
components[1] -= rhs;
components[2] -= rhs;
return *this;
}
vec3 &vec3::operator-=(vec3 rhs)
{
components[0] -= rhs[0];
components[1] -= rhs[1];
components[2] -= rhs[2];
return *this;
}
vec3 &vec3::operator/=(double rhs)
{
components[0] /= rhs;
components[1] /= rhs;
components[2] /= rhs;
return *this;
}
vec3 &vec3::operator/=(vec3 rhs)
{
components[0] /= rhs[0];
components[1] /= rhs[1];
components[2] /= rhs[2];
return *this;
}
std::ostream &operator<<(std::ostream &os, const vec3 &myVector) // Allows cout << myVector << endl;
{
os << "[" << myVector.x() << ", " << myVector.y() << ", " << myVector.z() << "];";
return os;
}
| true |
395a60106f186c28674c2dafdff499447b851708 | C++ | ProfJust/TIN | /_Kap 05 - Quellcode/5_06_passwort.cpp | ISO-8859-1 | 1,054 | 2.96875 | 3 | [] | no_license | // ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
// passwort.cpp : Definiert den Einstiegspunkt fr die Konsolenanwendung.
// BSP02_06
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h> //exit()
#include <windows.h> //fr Sleep() und System()
char passwort[] = "TI NF";
char eingabe[20];
//---------------------------------------------------------------
int main() {
//Konsole Grn auf Wei einstellen (DOS-Befehl)
system("COLOR F2");
printf("Bitte Passwort eingeben! \n");
gets_s(eingabe);
//--- Vergleich der Strings mit strcmp() ----
if (strcmp(passwort, eingabe) == 0) {
puts("Passwort OK");
}
else {
printf("\n Falsches Passwort ! \n Programm wird beendet");
Sleep(2000); //Wartet 2000ms
exit(1); //Fehler => Programm abbrechen
}
printf("Programm wird ausgefuehrt .....");
Sleep(2000);
//--- hier kommt jetzt der weiter Programmcode hin ---
exit(0); //Korrektes Ende
}
| true |
362e74fda41506c8837b91fae75124f2f5b1388f | C++ | zarif98sjs/Competitive-Programming | /CodeForces/Contest/Round 649/D.cpp | UTF-8 | 4,739 | 2.8125 | 3 | [] | no_license |
/**
Start with an empty graph and keep adding vertices from 1 to K in increasing order, using a DSU to keep track of connected components. If you ever add an edge that joins two vertices that were already joined, you have a cycle of length at most K.
Otherwise, you have a forest of size K, and can split it into vertices of even and odd depth. The larger one will be an independent set of size at least (K+1)/2.
**/
/** Which of the favors of your Lord will you deny ? **/
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define PII pair<int,int>
#define PLL pair<LL,LL>
#define MP make_pair
#define F first
#define S second
#define INF INT_MAX
#define ALL(x) (x).begin(), (x).end()
#define DBG(x) cerr << __LINE__ << " says: " << #x << " = " << (x) << endl
#define READ freopen("alu.txt", "r", stdin)
#define WRITE freopen("vorta.txt", "w", stdout)
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class TIn>using indexed_set = tree<TIn, null_type, less<TIn>,rb_tree_tag, tree_order_statistics_node_update>;
/**
PBDS
-------------------------------------------------
1) insert(value)
2) erase(value)
3) order_of_key(value) // 0 based indexing
4) *find_by_order(position) // 0 based indexing
**/
template<class T1, class T2>
ostream &operator <<(ostream &os, pair<T1,T2>&p);
template <class T>
ostream &operator <<(ostream &os, vector<T>&v);
template <class T>
ostream &operator <<(ostream &os, set<T>&v);
inline void optimizeIO()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
const int nmax = 2e5+7;
const LL LINF = 1e17;
template <class T>
string to_str(T x)
{
stringstream ss;
ss<<x;
return ss.str();
}
//bool cmp(const PII &A,const PII &B)
//{
//
//}
vector<int>adj[nmax];
vector<int>adj2[nmax];
class DisjointSet
{
public:
unordered_map<int, int> parent;
void makeSet(int N)
{
for (int i = 1; i <= N; i++)
parent[i] = i;
}
int Find(int k)
{
// if k is root
if (parent[k] == k)
return k;
return parent[k] = Find(parent[k]);
}
void Union(int a, int b)
{
int x = Find(a);
int y = Find(b);
parent[y] = x;
}
void printParent(int N)
{
for (int i = 1; i <= N; i++)
cout<<parent[i]<<" ";
cout<<endl;
}
};
bool vis[nmax];
vector<int>cycle;
void dfs(int u,int p)
{
vis[u] = true;
cycle.push_back(u);
for(int v:adj[u])
{
if(v==p)
continue;
if(vis[v])
{
cout<<cycle.size()<<endl;
for(int x:cycle)
cout<<x<<" ";
cout<<endl;
exit(0);
}
dfs(v,u);
}
cycle.pop_back();
vis[u] = false;
}
vector<int>odd,ev;
void bicolor(int u,int p,int h)
{
// DBG(u);
vis[u] = true;
if(h&1)
odd.push_back(u);
else
ev.push_back(u);
for(int v:adj2[u])
{
if(v!=p && vis[v]==false)
bicolor(v,u,h+1);
}
}
int main()
{
optimizeIO();
int n,m,k;
cin>>n>>m;
k = ceil(sqrt(n));
// DBG(k);
for(int i=1; i<=m; i++)
{
int a,b;
cin>>a>>b;
if(a<=k && b<=k)
{
adj[a].push_back(b);
adj[b].push_back(a);
}
adj2[a].push_back(b);
adj2[b].push_back(a);
}
DisjointSet ds;
ds.makeSet(n);
bool isCycle = false;
int c = -1;
for(int i=1; i<=n; i++)
{
for(int v:adj[i])
{
if(v<i)
{
if(ds.Find(i)!=ds.Find(v))
ds.Union(i,v);
else
{
isCycle = true, c = i;
cout<<2<<endl;
dfs(c,-1);
return 0;
}
}
}
}
// memset(vis,0,sizeof vis);
for(int i=1; i<=k; i++)
if(vis[i]==false)
bicolor(i,-1,1);
vector<int>ans = odd;
if(odd.size()<ev.size())
ans = ev;
cout<<1<<endl;
for(int i=0; i<k; i++)
cout<<ans[i]<<" ";
cout<<endl;
return 0;
}
/**
**/
template<class T1, class T2>
ostream &operator <<(ostream &os, pair<T1,T2>&p)
{
os<<"{"<<p.first<<", "<<p.second<<"} ";
return os;
}
template <class T>
ostream &operator <<(ostream &os, vector<T>&v)
{
os<<"[ ";
for(int i=0; i<v.size(); i++)
{
os<<v[i]<<" " ;
}
os<<" ]";
return os;
}
template <class T>
ostream &operator <<(ostream &os, set<T>&v)
{
os<<"[ ";
for(T i:v)
{
os<<i<<" ";
}
os<<" ]";
return os;
}
| true |
d5965b6f6a8f6e1c6b554775bb5b41a77fd41de7 | C++ | saswatsamal/I2C_LCD_Arduino | /i2c_lcd.ino | UTF-8 | 623 | 2.640625 | 3 | [] | no_license | //Sample Code for I2C LCD Display
// Saswat Samal
// Libraries included: <........>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup() {
lcd.begin(16, 2);
}
void loop()
{
lcd.print("PUT YOUR TEXT HERE");
lcd.setCursor(0, 0);
delay(1500);
lcd.setCursor(0, 1);
lcd.print("PUT YOUR TEXT HERE");
delay(1500);
lcd.clear();
lcd.print("PUT YOUR TEXT HERE");
lcd.setCursor(8, 8);
delay(1500);
lcd.setCursor(0, 1);
lcd.print("PUT YOUR TEXT HERE");
delay(1500);
lcd.clear();
lcd.print("PUT YOUR TEXT HERE");
lcd.setCursor(8, 8);
delay(1500);
lcd.clear();
}
| true |
9eb9d1b959e9a1943082ea02ae48bcc00a8795a7 | C++ | sm99012/TextRPG.Ex2 | /TextRPG.Ex2/Entity_Moster.cpp | UHC | 2,053 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <conio.h>
#include <ctime>
#include "Entity.h"
#include "Entity_Monster.h"
#include "Entity_Player.h"
#include "Item.h"
//
Monster::Monster(string name, int lv, int hp, int mp, int sp, int dp, int speed, int exp, int gold = 0) : Entity(name, lv, hp, mp, sp, dp, speed)
{
this->nEXP = exp;
this->nDropGold = gold;
//EntityStatus();
}
// ü
void Monster::EntityStatus()
{
cout << "[̸: " << GetName() << ", LV: " << GetLV() << ", C_HP/M_HP: " << GetC_HP() << "/" << GetM_HP() << ", C_MP/M_MP: " << GetC_MP() << "/" << GetM_MP() << ", EXP: " << nEXP << "]" << endl;
}
// ü
void Monster::MonsterBattleStatus()
{
cout << "[̸: " << GetName() << ", LV: " << GetLV() << ", C_HP/M_HP: " << GetC_HP() << "/" << GetM_HP() << ", C_MP/M_MP: " << GetC_MP() << "/" << GetM_MP() << "]" << endl;
cout << endl;
}
// ý
void Monster::MonsterDropSystem(Player* player) // ü ϴ ? -> GameManager ұ???
{
player->nHaveGold += this->nDropGold;
srand(time(0));
queue <Item*> Queue = Queue_nDropItemList;
queue <int> Rate = Queue_nDropItem_Rate;
while (!Queue.empty())
{
int nRandom = rand() % 101;
int nDropRate = Rate.front();
Item* nDropItem = Queue.front();
if (nDropRate >= nRandom)
{
player->PlayerDrop(nDropItem);
cout << "[" << player->GetName() << "] [: + " << Queue.front()->GetItemName() << "]" << endl;
}
Queue.pop();
Rate.pop();
}
}
// Ͱ ϴ ϼ(, )
void Monster::SetDropItem(Item* item, int rate)
{
Queue_nDropItemList.push(item);
Queue_nDropItem_Rate.push(rate);
}
//
void Monster::DisplayDropItem()
{
queue <Item*> Queue = Queue_nDropItemList;
queue <int> Rate = Queue_nDropItem_Rate;
int Count = 1;
while (!Queue.empty())
{
cout << Count << ": " << Queue.front()->GetItemName() << ", %: " << Rate.front() << endl;
Queue.pop();
Rate.pop();
Count++;
}
} | true |
15e43666cd02135e7aaf750955304fdda66b0af7 | C++ | zjslj/Blue-Lotus-Platform | /blp/base/sample/Thread_test.cpp | UTF-8 | 643 | 2.609375 | 3 | [] | no_license | //Thread_test.cpp
#include "inc.h"
#include "Thread.h"
#include <iostream>
using namespace blp;
using namespace std;
void* threadPrint(void * para)
{
cout << "threadPrint==>" << endl;
return NULL;
}
void threadTest()
{
CThread oThread(&threadPrint, "zjslj");
oThread.start();
cout << oThread.name() << endl;
cout << CThread::count() << endl;
cout << oThread.started() << endl;
try
{
oThread.start();
}
catch(CException& ex)
{
cout << "started === errCode:" << ex.error() << ", errMsg:" << ex.what() << endl;
}
oThread.join();
cout << "----" << oThread.count() << endl;
}
| true |
4d18e66a5287f6ac8d873386b3d4fe3338c30e2b | C++ | Hakudon/DSA-Project-Visualization | /src/main.cpp | UTF-8 | 699 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <SFML/Graphics.hpp>
#include "../include/screens.hpp"
//#include "../include/background.hpp"
int main()
{
//Applications variables
std::vector<cScreen*> Screens;
int screen = 0;
//Window creation
sf::RenderWindow App(sf::VideoMode(800, 600), "DSA PROJECT");
//Background background(800, 600);
//Screens preparations
menu s0;
Screens.push_back(&s0);
QuickSort s1;
Screens.push_back(&s1);
Djks s2;
Screens.push_back(&s2);
Credits s3;
Screens.push_back(&s3);
//Main loop
while (screen >= 0)
{
//background.generate(App);
screen = Screens[screen]->Run(App);
}
return 0;
}
| true |
3cf309017fd4ab898b32a478b66149785de97fa3 | C++ | zenoalbisser/chromium | /third_party/WebKit/Source/core/animation/VisibilityStyleInterpolationTest.cpp | UTF-8 | 2,534 | 2.640625 | 3 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | #include "config.h"
#include "core/animation/VisibilityStyleInterpolation.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/StylePropertySet.h"
#include <gtest/gtest.h>
namespace blink {
class AnimationVisibilityStyleInterpolationTest : public ::testing::Test {
protected:
static PassOwnPtr<InterpolableValue> visibilityToInterpolableValue(const CSSValue& value)
{
return VisibilityStyleInterpolation::visibilityToInterpolableValue(value);
}
static PassRefPtrWillBeRawPtr<CSSValue> interpolableValueToVisibility(InterpolableValue* value, CSSValueID notVisible)
{
return VisibilityStyleInterpolation::interpolableValueToVisibility(value, notVisible);
}
static PassRefPtrWillBeRawPtr<CSSValue> roundTrip(PassRefPtrWillBeRawPtr<CSSValue> value, CSSValueID valueID)
{
return interpolableValueToVisibility(visibilityToInterpolableValue(*value).get(), valueID);
}
static void testPrimitiveValue(PassRefPtrWillBeRawPtr<CSSValue> value, CSSValueID valueID)
{
EXPECT_TRUE(value->isPrimitiveValue());
EXPECT_EQ(valueID, toCSSPrimitiveValue(value.get())->getValueID());
}
static InterpolableValue* getCachedValue(Interpolation& interpolation)
{
return interpolation.getCachedValueForTesting();
}
};
TEST_F(AnimationVisibilityStyleInterpolationTest, ValueIDs)
{
RefPtrWillBeRawPtr<CSSValue> value = roundTrip(CSSPrimitiveValue::createIdentifier(CSSValueVisible), CSSValueHidden);
testPrimitiveValue(value, CSSValueVisible);
value = roundTrip(CSSPrimitiveValue::createIdentifier(CSSValueCollapse), CSSValueCollapse);
testPrimitiveValue(value, CSSValueCollapse);
value = roundTrip(CSSPrimitiveValue::createIdentifier(CSSValueHidden), CSSValueHidden);
testPrimitiveValue(value, CSSValueHidden);
}
TEST_F(AnimationVisibilityStyleInterpolationTest, Interpolation)
{
RefPtr<Interpolation> interpolation = VisibilityStyleInterpolation::create(
*CSSPrimitiveValue::createIdentifier(CSSValueHidden),
*CSSPrimitiveValue::createIdentifier(CSSValueVisible),
CSSPropertyVisibility);
interpolation->interpolate(0, 0.0);
RefPtrWillBeRawPtr<CSSValue> value = interpolableValueToVisibility(getCachedValue(*interpolation), CSSValueHidden);
testPrimitiveValue(value, CSSValueHidden);
interpolation->interpolate(0, 0.5);
value = interpolableValueToVisibility(getCachedValue(*interpolation), CSSValueHidden);
testPrimitiveValue(value, CSSValueVisible);
}
}
| true |
40b079265162efe1163a196f1ab9c5f5f732510b | C++ | Filet-de-S/c_plusplus_yandex | /white/incognizable.cpp | UTF-8 | 362 | 2.734375 | 3 | [] | no_license | #include <algorithm>
#include <vector>
#include <iostream>
#include <cmath>
#include <map>
using namespace std;
class Incognizable {
public:
Incognizable() {}
Incognizable(int i) {}
Incognizable(int i, int j) {}
};
int main() {
Incognizable a;
Incognizable b = {};
Incognizable c = {0};
Incognizable d = {0, 1};
return 0;
} | true |
54f4091e0bd7f26c40156465be98d2e4988ff8e1 | C++ | aisenn/CPP_Piscine | /d07/ex02/Array.tpp | UTF-8 | 1,340 | 3.546875 | 4 | [] | no_license | #ifndef ARRAY_TPP
#define ARRAY_TPP
# include <exception>
#include <istream>
template<typename T>
class Array
{
private:
unsigned int _size;
T *_data;
public:
Array<T>(void) : _size(0) , _data(new T[_size]()) { return; }
Array<T>(int size) : _size(size < 0 ? 0 : size) , _data(new T[this->_size]()) { return; }
Array<T>(Array<T> const &cp) : _size(0) , _data() {
*this = cp;
}
~Array<T>(void) {
delete [] this->_data;
}
Array<T> &operator=(Array<T> const &rhs) {
delete [] this->_data;
this->_size = rhs._size > 0 ? rhs._size : 0;
this->_data = new T[this->_size]();
for (unsigned int i = 0; i < this->_size; i++)
this->_data[i] = rhs._data[i];
return *this;
}
const T &operator [](unsigned int i) const {
if (!this->_data || i >= this->_size)
throw std::out_of_range("Error: Out of range");
return this->_data[i];
}
T &operator[](unsigned int i) {
if (!this->_data || i >= this->_size)
throw std::out_of_range("Error: Out of range");
return this->_data[i];
}
unsigned int size(void) const {
return this->_size;
}
};
template<typename T>
std::ostream &operator<<(std::ostream &os, const Array<T> &array) {
os << "[ ";
for (int i = 0; i < array.size(); i++) {
os << array[i] << " ";
}
os << "], size = " << array.size() << std::endl;
return os;
}
#endif //ARRAY_TPP
| true |
d77d7149ece5fad57021ee9302f92f9f5a7e3dc9 | C++ | stumathews/2DGameDev | /2DGameDevLib/GameObjectMoveStrategy.cpp | UTF-8 | 4,547 | 2.90625 | 3 | [] | no_license | #include "pch.h"
#include "GameObjectMoveStrategy.h"
#include "Player.h"
#include "Room.h"
#include <Direction.h>
#include <common/Logger.h>
#include <exceptions/EngineException.h>
#include <util/SettingsManager.h>
#include "../game/LevelManager.h"
#include "movement/IMovement.h"
GameObjectMoveStrategy::GameObjectMoveStrategy(const std::shared_ptr<gamelib::GameObject>& gameObject, const std::shared_ptr<RoomInfo>& roomInfo)
{
this->gameObject = gameObject;
this->roomInfo = roomInfo;
debug = gamelib::SettingsManager::Get()->GetBool("player", "debugMovement");
ignoreRestrictions = gamelib::SettingsManager::Get()->GetBool("player", "ignoreRestrictions");
}
bool GameObjectMoveStrategy::MoveGameObject(const std::shared_ptr<gamelib::IMovement> movement)
{
auto isMoveValid = false;
if (IsValidMove(movement))
{
SetGameObjectPosition(CalculateGameObjectMove(movement, movement->GetPixelsToMove()));
isMoveValid = true;
}
return isMoveValid;
}
gamelib::Coordinate<int> GameObjectMoveStrategy::CalculateGameObjectMove(const std::shared_ptr<gamelib::IMovement>& movement, const int pixelsToMove) const
{
int resultingY = gameObject->Position.GetY();
int resultingX = gameObject->Position.GetX();
switch(movement->GetDirection())
{
case gamelib::Direction::Down: resultingY += pixelsToMove; break;
case gamelib::Direction::Up: resultingY -= pixelsToMove; break;
case gamelib::Direction::Left: resultingX -= pixelsToMove; break;
case gamelib::Direction::Right: resultingX += pixelsToMove; break;
case gamelib::Direction::None: THROW(0, "Direction is NOne", "PlayerMoveStrategy")
}
return {resultingX, resultingY};
}
void GameObjectMoveStrategy::SetGameObjectPosition(const gamelib::Coordinate<int> resultingMove) const
{
gameObject->Position.SetX(resultingMove.GetX());
gameObject->Position.SetY(resultingMove.GetY());
}
bool GameObjectMoveStrategy::IsValidMove(const std::shared_ptr<gamelib::IMovement>& movement) const
{
if (ignoreRestrictions) { return true;}
switch (movement->GetDirection())
{
case gamelib::Direction::Down: return CanGameObjectMove(gamelib::Direction::Down);
case gamelib::Direction::Left: return CanGameObjectMove(gamelib::Direction::Left);
case gamelib::Direction::Right: return CanGameObjectMove(gamelib::Direction::Right);
case gamelib::Direction::Up: return CanGameObjectMove(gamelib::Direction::Up);
case gamelib::Direction::None: THROW(0, "Direction is None", "PlayerMoveStrategy")
}
return false;
}
bool GameObjectMoveStrategy::CanGameObjectMove(const gamelib::Direction direction) const
{
std::shared_ptr<Room> targetRoom;
bool touchingBlockingWalls = false, hasValidTargetRoom;
const auto currentRoom = roomInfo->GetCurrentRoom();
if(!currentRoom) { return false; }
auto intersectsRectAndLine = [=](const SDL_Rect bounds, gamelib::Line line) -> bool
{
return SDL_IntersectRectAndLine(&bounds, &line.X1, &line.Y1, &line.X2, &line.Y2);
};
if (direction == gamelib::Direction::Right)
{
targetRoom = roomInfo->GetRightRoom();
hasValidTargetRoom = targetRoom != nullptr;
touchingBlockingWalls =
(hasValidTargetRoom && targetRoom->HasLeftWall() && intersectsRectAndLine(gameObject->Bounds, targetRoom->LeftLine)) ||
currentRoom->HasRightWall() && intersectsRectAndLine(gameObject->Bounds, currentRoom->RightLine);
}
else if (direction == gamelib::Direction::Left)
{
targetRoom = roomInfo->GetLeftRoom();
hasValidTargetRoom = targetRoom != nullptr;
touchingBlockingWalls =
(hasValidTargetRoom && targetRoom->HasRightWall() && intersectsRectAndLine(gameObject->Bounds, targetRoom->RightLine)) ||
currentRoom->HasLeftWall() && intersectsRectAndLine(gameObject->Bounds, currentRoom->LeftLine);
}
else if (direction == gamelib::Direction::Up)
{
targetRoom = roomInfo->GetTopRoom();
hasValidTargetRoom = targetRoom != nullptr;
touchingBlockingWalls =
(hasValidTargetRoom && targetRoom->HasBottomWall() && intersectsRectAndLine(gameObject->Bounds, targetRoom->BottomLine)) ||
currentRoom->HasTopWall() && intersectsRectAndLine(gameObject->Bounds, currentRoom->TopLine);
}
else if (direction == gamelib::Direction::Down)
{
targetRoom = roomInfo->GetBottomRoom();
hasValidTargetRoom = targetRoom != nullptr;
touchingBlockingWalls =
(hasValidTargetRoom && targetRoom->HasTopWall() && intersectsRectAndLine(gameObject->Bounds, targetRoom->TopLine)) ||
currentRoom->HasBottomWall() && intersectsRectAndLine(gameObject->Bounds, currentRoom->BottomLine);
}
return !touchingBlockingWalls;
}
| true |
3de3a094444f171f494eee3f0a684eb97ff51c95 | C++ | Connellj99/GameArch | /Bakaleinik.David/MidTerm/Unit.h | WINDOWS-1252 | 1,216 | 2.796875 | 3 | [] | no_license | #pragma once
#include <string>
#include "Animation.h"
#include "Trackable.h"
class System;
class Sprite;
class Unit : public Trackable //A class to hold state information for a game entity for now, it holds location info for an animation
{
friend class Game;
protected:
int mSourceY;
int mSourceX;
Animation mUnitAnimation;
bool mRunAnimation = true;
bool mShouldBeDeleted = false;
std::string mObjectType;
public:
Unit();
Unit(Animation* startingAnim, int x, int y);
~Unit();
std::string getID() { return mObjectType; };
bool getState() { return mShouldBeDeleted; };
void changeState() { mShouldBeDeleted = !mShouldBeDeleted; };
int getXloc() { return mSourceX; };
int getYloc() { return mSourceY; };
void setXLoc(int x) { mSourceX = x; };
void setYLoc(int y) { mSourceY = y; };
virtual void update(double dTime); //Call Animation's update
virtual void drawUnit(System *aSystem);
void setUnitAnimation(Animation* target);
Animation getUnitAnimation() { return mUnitAnimation; };
bool isAnimating() { return mRunAnimation; };
void toggleAnimation() { mRunAnimation = !mRunAnimation; };
bool checkCollision(int pointerX, int pointerY, int spriteSize);
//Centipede
}; | true |
a9b0941ba837ffa8a45c1a8453ba65512c6afa37 | C++ | gocpplua/awesome-book | /深入应用C++11:代码优化与工程级应用/src/1.6.2.cpp | UTF-8 | 784 | 3.875 | 4 | [
"MIT"
] | permissive | // 1.6.2 声明式的编程风格,简洁的代码
#include<iostream>
#include<functional>
#include<algorithm>
#include<vector>
using namespace std;
class CountEven
{
int &count_;
public:
CountEven(int& count):count_(count){
cout << __FUNCTION__ << endl;
}
void operator()(int val)
{
if (!(val & 1))
{
cout << __FUNCTION__ << endl;
++count_;
}
}
};
int main()
{
std::vector<int> v{1, 2, 3, 4};
int even_count = 0;
for_each(v.begin(), v.end(), CountEven(even_count));
cout << "[1]the number of even is:" << even_count << endl;
int even_count1 = 0;
CountEven e(even_count1) ;
for_each(v.begin(), v.end(), e);
cout << "[1]the number of even is:" << even_count << endl;
} | true |
e4302d6a13638777dc6c533750fc70f508d8c3ff | C++ | hello-lx/CodingTest | /3/894.cpp | UTF-8 | 1,050 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <vector>
#include <math.h>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <list>
#include <queue>
#include <stack>
using namespace std;
#define INT_MIN -99999999999
#define INT_MAX 99999999999
class Solution {
public:
/**
* @param array: an integer array
* @return: nothing
*/
void pancakeSort(vector<int> &array) {
// Write your code here
int n = array.size();
for(int i = n - 1; i > 0; i--) {
// 执行n-1次,因为最后剩一个最小的在第一个,不用处理。
int Max = 0;
for(int j = 1; j <= i; j++ ) {
if(array[j] > array[Max]){
Max = j;
}
}
if(Max != 0 && Max != i) {
FlipTool::flip(array, Max);
FlipTool::flip(array, i);
} else if(Max == 0) {
FlipTool::flip(array, i);
}
}
}
};
| true |
5c2c4c738c4cd2c16713334cedb489b2fc429555 | C++ | kurihara-lab-b4/algorithm_data_structure | /data_structure/4_4_doubly_linked_list_2.cpp | UTF-8 | 1,699 | 3.515625 | 4 | [] | no_license | /*
4.4 連結リスト
g++ -o 4_4_doubly_linked_list_2.exe 4_4_doubly_linked_list_2.cpp
./4_4_doubly_linked_list_2.exe
*/
#include <iostream>
#include<string>
using namespace std;
struct Node {
int key;
Node *prev, *next;
};
Node *nil;
void init();
void init() {
nil = (Node *)malloc(sizeof(Node));
nil -> next = nil;
nil -> prev = nil;
}
void insert(int key);
void insert(int key) {
Node *x = (Node *)malloc(sizeof(Node));
x -> key = key;
x -> next = nil -> next;
nil -> next -> prev = x;
nil -> next = x;
x -> prev = nil;
}
void deleteNode(Node *t);
void deleteNode(Node *t) {
if (t != nil ) {
t -> prev -> next = t -> next;
t -> next -> prev = t -> prev;
free(t);
}
}
void deleteFirst();
void deleteFirst() {
deleteNode(nil -> next);
}
void deleteLast();
void deleteLast() {
deleteNode(nil -> prev);
}
Node* listSearch(int key) {
Node *cur = nil -> next;
while ( cur != nil && cur -> key != key ) {
cur = cur -> next;
}
return cur;
}
void deleteKey(int key);
void deleteKey(int key) {
deleteNode(listSearch(key));
}
int main() {
int n, key;
char com[100];
scanf("%d", &n);
init();
for ( int i = 0; i < n; i++ ) {
scanf("%s %d", com, &key);
if ( com[0] == 'i' ) {
insert(key);
} else if (com[6] == 'F' ) {
deleteLast();
} else if (com[6] == 'L' ) {
deleteFirst();
} else {
deleteKey(key);
}
}
Node *cur = nil -> next;
while ( cur != nil ) {
cout << cur -> key << " ";
cur = cur -> next;
}
cout << endl;
return 0;
} | true |
d586162362dbd7bcf28dd93ad39fb373d20935c3 | C++ | Dedis23/SGBE | /src/gb/mmu.h | UTF-8 | 3,233 | 2.625 | 3 | [] | no_license | /************************************************************
* Created by: Dedi Sidi, 2020 *
* *
* The gameboy memory management unit *
************************************************************/
/*
The memory map of the gameboy:
0x000-0x00FF: 256 bytes of the bootstrap - after reading that, the gameboy can access these addresses again from the cartridge
0x0000-0x3FFF: 16K ROM bank (first rom bank of the cartridge)
---> 0x0100-0x014F: Cartridge header
0x4000-0x7FFF: Switchable 16K ROM banks (the cartridge can switch rom banks so that the cpu can access more memory. (up to 256 banks) minimum cartridge 32KB max 4MB
0x8000-0x9FFF: 8K Video RAM (internal video memory)
0xA000-0xBFFF: 8K External RAM banks (the cartridge can have additional RAM banks that the cpu can access, up to 4 banks)
0xC000-0xDFFF: 8K Internal RAM
0xE000-0xFDFF: Shadow RAM - exact copy of the internal RAM in: C000-DDFF - (7680 bytes excluding the higher 512 bytes)
0xFE00-0xFE9F: OAM - "Object Attribute Memory" - stores information about the sprites
0xFEA0-0xFEFF: Unusable memory
0xFF00-0xFF7F: MappedIO - holds controls values which are releated to I/O components
0xFF80-0xFFFF: Zero Page - high speed RAM of 128 bytes, includes the Interrupt Enable Register
*/
/*
info mostly taken from:
http://bgb.bircd.org/pandocs.htm#gameboytechnicaldata
http://imrannazar.com/GameBoy-Emulation-in-JavaScript:-Memory
https://realboyemulator.wordpress.com/2013/01/03/a-look-at-the-game-boy-bootstrap-let-the-fun-begin/
*/
#pragma once
#include <string>
#include <vector>
#include "gameboy.h"
#include "cartridge/cartridge.h"
#include "utility.h"
#include "timer.h"
/* special locations addresses in memory */
const word BOOTSTRAP_DONE_ADDR = 0xFF50;
/* serial data transfer addresses in memory */
const word SERIAL_TRANSFER_DATA_ADDR = 0xFF01;
const word SERIAL_TRANSFER_CONTROL_ADDR = 0xFF02;
/* size of memory components */
const word VRAM_SIZE = (0x9FFF - 0x8000 + 1);
const word RAM_SIZE = (0xFDFF - 0xC000 + 1); // including the shadow ram
const word OAM_SIZE = (0xFEFF - 0xFE00 + 1); // including the unusable section
const word MAPPED_IO_SIZE = (0xFF7F - 0xFF00 + 1);
const word ZERO_PAGE_SIZE = (0xFFFF - 0xFF80 + 1);
class GBInternals;
class MMU
{
public:
MMU(GBInternals& i_GBInternals, Cartridge& i_Cartridge);
virtual ~MMU() = default;
MMU(const MMU&) = delete;
MMU& operator=(const MMU&) = delete;
byte Read(word i_Address) const;
void Write(word i_Address, byte i_Value);
void DMATransfer(byte i_SourceAdress);
private:
byte readMappedIO(word i_Address) const;
void writeMappedIO(word i_Address, byte i_Value);
bool isBootstrapDone() const;
private:
/* memory modules */
Cartridge& m_Cartridge;
vector<byte> m_VRAM = vector<byte>(VRAM_SIZE, 0);
vector<byte> m_RAM = vector<byte>(RAM_SIZE, 0); // including the shadow ram
vector<byte> m_OAM = vector<byte>(OAM_SIZE, 0); // including the unusable section
vector<byte> m_MappedIO = vector<byte>(MAPPED_IO_SIZE, 0);
vector<byte> m_ZeroPageRAM = vector<byte>(ZERO_PAGE_SIZE, 0);
static const vector<byte> s_Bootstrap;
/* gameboy components ref */
GBInternals& m_GBInternals;
}; | true |
18c6c9d7e3e32929d68295dc4dbe273e63ebdc3a | C++ | Girl-Code-It/Beginner-CPP-Submissions | /Rishika/MILESTONE4/m4q4.cpp | UTF-8 | 280 | 3.046875 | 3 | [] | no_license | //q4- wap to calculate HCF of two numbers.
#include<iostream>
using namespace std;
int main()
{
int n1,n2,i,hcf=1,m;
cout<<"Enter two numbers- ";
cin>>n1>>n2;
m=min(n1,n2);
for(i=1;i<=m;i++)
{
if(n1%i==0 && n2%i==0)
{
hcf=i;
}
}
cout<<"hcf of number is= "<<hcf;
}
| true |
0b505163e89ce29aa05b0ca8970ed0462029681d | C++ | amit-shahwal/interviewbit-Hackerrank_questions | /journey_tomoon.cpp | UTF-8 | 1,491 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
vector<int>tt[1000000];
int visited[1000000];
int tocheck[1000000];
vector<int>same;
queue<int>q;
long long int bfs(int s)
{ int count=0;
q.push(s);
while (!q.empty()) {
int curr=q.front();
q.pop();
count++;
for(int i=0;i<tt[curr].size();i++)
{
if(visited[tt[curr][i]]==-1)
{
visited[tt[curr][i]]=1;
q.push(tt[curr][i]);
}
}
}
return count;
}
// Complete the journeyToMoon function below.
long long int journeyToMoon(int n, vector<vector<int>> astronaut) {
//long int ans=n*(n-1)/2;
long long int ans=(long long int)(n-1)*n/2;
for(int i=0;i<=n;i++)
{visited[i]=-1;tocheck[i]=0;}
for(int i=0;i<astronaut.size();i++)
{
tt[astronaut[i][0]].push_back(astronaut[i][1]);
tt[astronaut[i][1]].push_back(astronaut[i][0]);
tocheck[astronaut[i][0]]=1;
tocheck[astronaut[i][1]]=1;
}
for(int i= 0;i<n;i++)
{
if(visited[i]==-1 && tocheck[i]==1)
{ visited[i]=1;
long long int cc=bfs(i);
ans-= (cc*(cc-1))/2;
}
}
//cout<<ans;
return ans;
}
int main()
{
int n,k;
cin>>n;
cin>>k;
vector<vector<int>> tt;
vector<int>t;
for(int i=1;i<=k;i++)
{int x,y;
cin>>x>>y;
t.push_back(x);
t.push_back(y);
tt.push_back(t);
t.clear();
}
cout<<journeyToMoon(n,tt);
}
| true |
00c39a89d38e0a429f0a4fa54e524c25a05d2557 | C++ | mohsani/Geometry | /Geometry/Square.h | UTF-8 | 293 | 2.828125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "TwoDimensional.h"
class Square :
public TwoDimensional
{
private:
float side;
public:
Square(string color, float centerX, float centerY, float side);
float perimeter() override;
float area() override;
float getSide();
void setSide(float side);
};
| true |
e3a390c3f6783bd2a89952a0b74ae5179902efac | C++ | fmejbah/Code-Library | /Graph/Stable_Marriage_Problem.cpp | UTF-8 | 953 | 2.609375 | 3 | [] | no_license | /*
* Biborno
* fb.com/mfmejbah
* fmejbah@gmail.com
*
* Graph: Stable Marriage Problem
* Stable_Marriage_Problem.cpp
* Date: 27 Aug 2016
*/
#include <bits/stdc++.h>
using namespace std;
int n, x, y, m, m1, w, M[501][501], W[501][501], woman[501], m2w[501], w2m[501];
queue<int> fre;
bool engaged_man[501], engaged_woman[501];
void engaged( int m, int w ) {
m2w[m] = w;
w2m[w] = m;
}
void stableMatching() {
while(!fre.empty()) {
m = fre.front();
w = M[m][woman[m]++];
fre.pop();
if(!engaged_woman[w]) {
engaged(m, w);
} else {
m1 = w2m[w];
if( W[w][m1] > W[w][m] ) {
engaged_man[m1] = 0;
fre.push(m1);
engaged(m, w);
} else {
fre.push(m);
}
}
}
}
int main()
{
cin >> n;
memset(engaged_man, 0, sizeof(engaged_man));
memset(engaged_woman, 0, sizeof(engaged_woman));
memset(woman, 0, sizeof(woman));
for( int i = 1; i <= n; i++ )
fre.push(i);
}
| true |
945e27a89a842573f15f110df97483aaf4ad7344 | C++ | tz924/cs38 | /Homework3/ps3_p2.cpp | UTF-8 | 1,345 | 4 | 4 | [] | no_license | /**
* Assignment name: Problem Set 3
* File name: ps3_p2.cpp
* Author: Jing Zhang
*/
#include "ps3.h"
using namespace std;
/* Fibonacci Sequence using Vector */
void problem2()
{
const int MIN_NUM_TO_DISPLAY = 1;
const int FST_EL = 0;
const int SND_EL = 1;
const int START_INDEX = 2;
// Ask the user how many numbers they want displayed in the sequence
int nbrToDisplay;
do
{
cout << "How many Fibonacci numbers to display (at least one): ";
cin >> nbrToDisplay;
} while (nbrToDisplay < MIN_NUM_TO_DISPLAY); // At least 1
// Special case - one number to display
if (nbrToDisplay == MIN_NUM_TO_DISPLAY)
{
// Display the first number and return
cout << FST_EL << endl;
return;
}
// Create and "seed" the vector with the first two elements(0, 1)
vector<int> fiboSeq = { FST_EL, SND_EL };
/* Fill the vector with the remaining of elements in the sequence up to the
number specified by the user. */
int prev1 = SND_EL;
int prev2 = FST_EL;
int current;
// Start with the third
for (int index = START_INDEX; index < nbrToDisplay; index++)
{
// Get the current
current = prev1 + prev2;
// Push it to the vector
fiboSeq.push_back(current);
// Update the previous two
prev2 = prev1;
prev1 = current;
}
// Display the vector
for (int number : fiboSeq)
cout << number << endl;
}
| true |
efd90ad7787298cd2950adabf84c95fb1c3f0f78 | C++ | rajajitendra-b/Interview-Bit | /Hashing/Hash Search/Colorful Number.cpp | UTF-8 | 1,775 | 3.734375 | 4 | [] | no_license | /**************** QUESTION **************
For Given Number N find if its COLORFUL number or not
Return 0/1
COLORFUL number:
A number can be broken into different contiguous sub-subsequence parts.
Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245.
And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different
Example:
N = 23
2 3 23
2 -> 2
3 -> 3
23 -> 6
this number is a COLORFUL number since product of every digit of a sub-sequence are different.
Output : 1
*/
/*************** APPROACH *************
Consider the following number
3245
All combinations to find the uniqueness are expanded for observation.
3 32 324 3245
2 24 245
4 45
5
On observation, we find that we need to find the product of all combinations and check it there is any repetition.
Checking repitition can be done using a hash map.
*/
/*************** SOLUTION *************/
int Solution::colorful(int num)
{
map<int, bool> m;
vector<int> nums;
int A = num;
Get all the numbers in an array
while(A)
{
//This will get the numbers in reverse order to a vector
nums.push_back(A%10);
A /= 10;
}
//Check all combinations using 2 loops
for(int i = 0; i < nums.size(); i++)
{
int prod = 1;
for(int j = i; j < nums.size(); j++)
{
prod *= nums[j];
//Check if the combination already exists in hashmap
auto it = m.find(prod);
if(it != m.end())
{
return 0; //If already exists, not a colorful number
}
m.insert(make_pair(prod, true));
}
}
//No combinations exists already. So, this is a colorful number
return 1;
}
| true |
79889771fab619ae0c0dd1ca839e3df7436f2283 | C++ | GertVercruyssen/GameEngine | /ShapeColorNormalCube.cpp | UTF-8 | 5,547 | 2.625 | 3 | [] | no_license | #include "StdAfx.h"
#include "ShapeColorNormalCube.h"
#include "D3D10DeviceWrapper.h"
#include "DXWindow.h"
ShapeColorNormalCube::ShapeColorNormalCube(float width, float height, float depth, D3DXCOLOR color):
m_Width(width),m_Height(height),m_Depth(depth),m_Color(color)
{
BuildVertexBuffer();
BuildIndexBuffer();
}
ShapeColorNormalCube::~ShapeColorNormalCube(void)
{
}
bool ShapeColorNormalCube::Init()
{
return true;
}
void ShapeColorNormalCube::BuildVertexBuffer()
{
m_NumVertices=24;
// Create vertex array containing three elements in system memory
VertexPosColNormal *pVertices = new VertexPosColNormal[m_NumVertices];
int i = 0;
//front
//in origin
pVertices[i++] = VertexPosColNormal( -1.0f, -1.0f, -1.0f , 1.0f, 0.0f, 0.0f, 1.0f , 0.0f,0.0f,-1.0f);
//one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( -1.0f, 1.0f, -1.0f , 1.0f, 0.0f, 0.0f, 1.0f , 0.0f,0.0f,-1.0f);
//one unit on x axis (right)
pVertices[i++] = VertexPosColNormal( 1.0f, -1.0f, -1.0f , 1.0f, 0.0f, 0.0f, 1.0f , 0.0f,0.0f,-1.0f);
//one unit on x axis (right) and one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( 1.0f, 1.0f, -1.0f , 1.0f, 0.0f, 0.0f, 1.0f , 0.0f,0.0f,-1.0f);
//back
//in origin
pVertices[i++] = VertexPosColNormal( -1.0f, -1.0f, 1.0f , 0.0f, 1.0f, 0.0f, 1.0f , 0.0f,0.0f,1.0f);
//one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( -1.0f, 1.0f, 1.0f , 0.0f, 1.0f, 0.0f, 1.0f , 0.0f,0.0f,1.0f);
//one unit on x axis (right)
pVertices[i++] = VertexPosColNormal( 1.0f, -1.0f, 1.0f , 0.0f, 1.0f, 0.0f, 1.0f , 0.0f,0.0f,1.0f);
//one unit on x axis (right) and one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( 1.0f, 1.0f, 1.0f , 0.0f, 1.0f, 0.0f, 1.0f , 0.0f,0.0f,1.0f);
//left
//in origin
pVertices[i++] = VertexPosColNormal( -1.0f, -1.0f, -1.0f , 0.0f, 0.0f, 1.0f, 1.0f , -1.0f,0.0f,0.0f);
//one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( -1.0f, 1.0f, -1.0f , 0.0f, 0.0f, 1.0f, 1.0f , -1.0f,0.0f,0.0f);
//one unit on x axis (right)
pVertices[i++] = VertexPosColNormal( -1.0f, -1.0f, 1.0f , 0.0f, 0.0f, 1.0f, 1.0f , -1.0f,0.0f,0.0f);
//one unit on x axis (right) and one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( -1.0f, 1.0f, 1.0f , 0.0f, 0.0f, 1.0f, 1.0f , -1.0f,0.0f,0.0f);
//right
//in origin
pVertices[i++] = VertexPosColNormal( 1.0f, -1.0f, -1.0f , 1.0f, 1.0f, 0.0f, 1.0f , 1.0f,0.0f,0.0f);
//one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( 1.0f, 1.0f, -1.0f , 1.0f, 1.0f, 0.0f, 1.0f , 1.0f,0.0f,0.0f);
//one unit on x axis (right)
pVertices[i++] = VertexPosColNormal( 1.0f, -1.0f, 1.0f , 1.0f, 1.0f, 0.0f, 1.0f , 1.0f,0.0f,0.0f);
//one unit on x axis (right) and one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( 1.0f, 1.0f, 1.0f , 1.0f, 1.0f, 0.0f, 1.0f , 1.0f,0.0f,0.0f);
//top
//in origin
pVertices[i++] = VertexPosColNormal( -1.0f, 1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 1.0f , 0.0f,1.0f,0.0f);
//one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( -1.0f, 1.0f, -1.0f , 1.0f, 0.0f, 1.0f, 1.0f , 0.0f,1.0f,0.0f);
//one unit on x axis (right)
pVertices[i++] = VertexPosColNormal( 1.0f, 1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 1.0f , 0.0f,1.0f,0.0f);
//one unit on x axis (right) and one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( 1.0f, 1.0f, -1.0f , 1.0f, 0.0f, 1.0f, 1.0f , 0.0f,1.0f,0.0f);
//bottom
//in origin
pVertices[i++] = VertexPosColNormal( -1.0f, -1.0f, 1.0f , 1.0f, 1.0f, 1.0f, 1.0f , 0.0f,-1.0f,0.0f);
//one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( -1.0f, -1.0f, -1.0f , 1.0f, 1.0f, 1.0f, 1.0f , 0.0f,-1.0f,0.0f);
//one unit on x axis (right)
pVertices[i++] = VertexPosColNormal( 1.0f, -1.0f, 1.0f , 1.0f, 1.0f, 1.0f, 1.0f , 0.0f,-1.0f,0.0f);
//one unit on x axis (right) and one unit on y axis (up)
pVertices[i++] = VertexPosColNormal( 1.0f, -1.0f, -1.0f , 1.0f, 1.0f, 1.0f, 1.0f , 0.0f,-1.0f,0.0f);
//recalc according to wanted size and color
for(int count=0 ; count < i ; ++count)
{
pVertices[count].pos.x*=.5f*m_Width;
pVertices[count].pos.y*=.5f*m_Height;
pVertices[count].pos.z*=.5f*m_Depth;
pVertices[count].color=m_Color;
}
//fill a buffer description to copy the vertexdata into graphics memory
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DEFAULT;
bd.ByteWidth = sizeof( VertexPosColNormal ) * m_NumVertices;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pVertices;
//create a ID3D10Buffer in graphics meemory containing the vertex info
HR(GETD3D10DEVICE->CreateBuffer( &bd, &InitData, &m_pVertexBuffer ));
delete[] pVertices;
}
void ShapeColorNormalCube::BuildIndexBuffer()
{
m_NumIndices=36;
// Create index buffer
DWORD indices[] =
{
0,1,2,2,1,3,//front
4,6,5,5,6,7,//back
8,10,9,9,10,11,//left
12,13,14,14,13,15,//right
16,18,17,17,18,19,//top
20,21,22,22,21,23//bottom
};
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DEFAULT;
bd.ByteWidth = sizeof( DWORD ) * m_NumIndices;
bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = indices;
HR(GETD3D10DEVICE->CreateBuffer( &bd, &InitData, &m_pIndexBuffer ));
}
void ShapeColorNormalCube::Tick(float dTime)
{
}
| true |
3b93edd8f823d4d8825582e0422fffdbbcde824d | C++ | marc-hanheide/cogx | /tools/hardware/stereo/branches/stable-1/src/c++/components/StereoServer.h | UTF-8 | 3,176 | 2.53125 | 3 | [] | no_license | /**
* @author Michael Zillich
* @date June 2009
*/
#ifndef STEREO_SERVER_H
#define STEREO_SERVER_H
#include <stdexcept>
#include <vector>
#include <map>
#include <string>
#include <cast/core/CASTComponent.hpp>
#include <VideoClient.h>
#include "StereoCamera.h"
#include "Math.hpp"
#include "Stereo.hpp"
#include "gpustereo/CensusGPU.h"
namespace cast
{
class StereoServer;
/**
* Ice interface to a stereo server.
*/
class StereoServerI : public Stereo::StereoInterface
{
private:
StereoServer *stereoSrv;
public:
StereoServerI(StereoServer *_stereo) : stereoSrv(_stereo) {}
/**
* Returns the 3D point cloud.
*/
virtual void getPoints(bool transformToGlobal, VisionData::SurfacePointSeq& points, const Ice::Current&);
/**
* Returns part of the 3D point cloud inside given SOI.
*/
virtual void getPointsInSOI(bool transformToGlobal, const VisionData::SOIPtr &soi,
VisionData::SurfacePointSeq& points, const Ice::Current&);
virtual void getRectImage(Ice::Int side, Video::Image& image, const Ice::Current&);
};
class StereoServer : public CASTComponent,
public VideoClient
{
private:
/**
* Ice (servant) name for video interface
*/
std::string iceStereoName;
/**
* Ice port for video interface
*/
int iceStereoPort;
/**
* Camera IDs for getting left and right images
*/
std::vector<int> camIds;
/**
* component ID of the video server to connect to
*/
std::string videoServerName;
/**
* our ICE proxy to the video server
*/
Video::VideoInterfacePrx videoServer;
/**
* the ICE stereo server instance
*/
Stereo::StereoInterfacePtr hStereoServer;
/**
* Stereo parameters
*/
StereoCamera stereoCam;
/**
* The GPU stereo matching code.
*/
CensusGPU *census;
// stereo works better/faster with smaller images, so we might want to use a
// smaller resolution
int stereoWidth;
int stereoHeight;
/**
* Size of median filter for specle removeal in the disparity image.
* 0 = not median filtering
*/
int medianSize;
/**
* maximum disparity range we want to search
*/
int maxDisp;
IplImage *colorImg[2];
IplImage *rectColorImg[2];
IplImage *rectGreyImg[2];
IplImage *disparityImg;
bool doDisplay;
bool logImages;
/**
* Create Ice video interface.
*/
void setupMyIceCommunication();
void configure(const std::map<std::string,std::string> & _config)
throw(std::runtime_error);
virtual void start();
virtual void runComponent();
public:
StereoServer();
virtual ~StereoServer();
/**
* Returns the 3D point cloud.
*/
void getPoints(bool transformToGlobal, std::vector<VisionData::SurfacePoint> &points);
/**
* Returns part of the 3D point cloud inside given SOI.
*/
void getPointsInSOI(bool transformToGlobal, const VisionData::SOI &soi,
std::vector<VisionData::SurfacePoint> &points);
void getRectImage(int side, Video::Image& image);
/**
* The callback function for images pushed by the image server.
* To be overwritten by derived classes.
*/
virtual void receiveImages(const std::vector<Video::Image>& images);
};
}
#endif
| true |
e8a8bb29e5542de3e04081add7cd8f56484df987 | C++ | Alexklkv/base_server | /ability/effects/PiercingStrikeEffect.h | UTF-8 | 548 | 2.515625 | 3 | [] | no_license | #pragma once
#include "basic/CardAttackEffect.h"
#include "basic/NegativeEffect.h"
#include "misc.h"
class PiercingStrikeEffect final : public CardAttackEffect, public NegativeEffect
{
private:
mutable uint16_t start_target_health;
combatant_ptr_t get_target(combatant_ptr_t old_target) const;
protected:
bool on_attacker_before(CardAttackContext &ctx) const override;
bool on_attacker_after(CardAttackContext &ctx) const override;
public:
PiercingStrikeEffect(uint32_t id, ability::Type type, const policy_factory_t &policy_factory);
}; | true |
cdfba5e4128d85460e6f5cd4baa09a964e0b4e42 | C++ | kolak33/kryptoVol2 | /lista1/zad1/LCG and LFSR - crypto1/LCGBreaker.cpp | UTF-8 | 2,716 | 2.953125 | 3 | [] | no_license | #include "stdafx.h"
#include "LCGBreaker.h"
#include <iostream>
LCGBreaker::LCGBreaker()
: m_bPredictedParams(false)
{
}
void LCGBreaker::FindLCGParameters(std::vector<LL> &states)
{
LL lModulus = CompModulus(states);
LL lMultiplier = CompMultiplier(states, lModulus);
LL lIncrement = CompIncrement(states, lModulus, lMultiplier);
m_lcgParams.N = lModulus;
m_lcgParams.M = lMultiplier;
m_lcgParams.C = lIncrement;
m_lcgParams.State = states.back();
m_bPredictedParams = true;
}
LL LCGBreaker::PredictNext()
{
if (!m_bPredictedParams)
return -1;
ATLASSERT(m_lcgParams.N != 0);
m_lcgParams.State = PMod((m_lcgParams.State * m_lcgParams.M + m_lcgParams.C), m_lcgParams.N);
return m_lcgParams.State;
}
LL LCGBreaker::CompIncrement(std::vector<LL> &states, LL lModulus, LL lMultiplier)
{
// s1 = s0*m + c (mod n)
// c = s1 - s0*m (mod n)
ATLASSERT(states.size() >= 2);
return PMod((states[1] - states[0] * lMultiplier), lModulus);
}
LL LCGBreaker::CompMultiplier(std::vector<LL> &states, LL lModulus)
{
// s2 - s1 = m * (s1 - s0) (mod n)
// m = (s2 - s1) / (s1 - s0) (mod n)
ATLASSERT(states.size() >= 3);
LL lMultiplier = PMod((states[2] - states[1]) * ModInv(states[1] - states[0], lModulus), lModulus);
return lMultiplier;
}
LL LCGBreaker::CompModulus(std::vector<LL> &states)
{
//t0 = s1 - s0
//t1 = s2 - s1 = (s1*m + c) - (s0*m + c) = m * (s1 - s0) = m * t0(mod n)
//t2 = s3 - s2 = (s2*m + c) - (s1*m + c) = m * (s2 - s1) = m * t1(mod n)
//t3 = s4 - s3 = (s3*m + c) - (s2*m + c) = m * (s3 - s2) = m * t2(mod n)
//t2*t0 - t1*t1 = (m*m*t0 * t0) - (m*t0 * m*t0) = 0 (mod n)
ATLASSERT(states.size() >= 6);
std::vector<LL> diffs;
for (size_t i = 0; i < states.size() - 1; ++i)
diffs.push_back(states[i + 1] - states[i]);
std::vector<LL> congruentZeroes;
for (size_t i = 0; i < diffs.size() - 2; ++i)
congruentZeroes.push_back(diffs[i + 2] * diffs[i] - diffs[i + 1] * diffs[i + 1]);
LL lGCD = congruentZeroes[0];
for (size_t i = 1; i < congruentZeroes.size(); ++i)
lGCD = GCD(lGCD, congruentZeroes[i]);
LL lModulus = std::abs(lGCD);
return lModulus;
}
LL LCGBreaker::GCD(LL a, LL b)
{
if (a == 0) return b;
return GCD(b%a, a);
}
LL LCGBreaker::ModInv(LL b, LL n)
{
LL x, y;
LL res = -1;
LL g = GCDExt(b, n, x, y);
if (g != 1)
std::cout << "Inverse doesn't exist\n";
else
res = PMod(x, n);
return res;
}
LL LCGBreaker::GCDExt(LL a, LL b, LL &x, LL &y)
{
if (a == 0)
{
x = 0;
y = 1;
return b;
}
LL x1, y1; // To store results of recursive call
LL gcd = GCDExt(b%a, a, x1, y1);
// Update x and y using results of recursive call
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
LL LCGBreaker::PMod(LL i, LL n)
{
return (i % n + n) % n;
} | true |
7aa6895bc0a66d18e1f9f6ac2c3db0729a64629a | C++ | exposedtalent/CodingBlocks | /Assignment-2/permutations.cpp | UTF-8 | 526 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<set>
#include<cstring>
using namespace std;
void generatePermutations(char inp[], int i, set<string>&s){
if(inp[i] == '\0'){
s.insert(string(inp));
return;
}
for(int j = 0; j < strlen(inp); j++){
swap(inp[i], inp[j]);
generatePermutations(inp,i+1,s);
swap(inp[i], inp[j]);
}
}
int main(){
char input[6];
cin >> input;
set<string> s;
generatePermutations(input, 0, s);
for(string str : s) {
cout << str << endl;
}
} | true |
ca322621843e3204c4f93bd98a5978d9d931ac73 | C++ | idesign0/robotics | /OOP With C++/Chapter 15 'Manipulating Strings'/Programming Exercise/15.3 Print names which start with names 'B' and 'C'/main.cpp | UTF-8 | 446 | 3.046875 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<string>
using namespace std;
int main(){
char shorting[]={'B','C','A'};
string names[5];
names[0]="Chan";
names[1]="Book";
names[2]="Arial";
names[3]="Banana";
names[4]="Zoom";
for(int j=0;j<(sizeof(shorting)/sizeof(char));j++){
for(int i=0;i<5;i++){
if(names[i].at(0)==shorting[j]){
cout << names[i] << endl;
}
}
}
return 0;
}
| true |
541843f2c015f61b51a01fa21b4ead5b93b14a95 | C++ | iByster/Agenda | /Repository.h | UTF-8 | 2,918 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Activity.h"
#include "MyList.h"
#include <string>
#include <ostream>
//#include <vector>
#include <unordered_map>
using std::string;
using std::ostream;
class DefaultRepo {
protected:
double err;
public:
virtual void store(const Activity & a) = 0;
virtual void storeCurr(const Activity & a) = 0;
virtual void deleteAc(const Activity & a) = 0;
virtual void deleteAc2(const Activity & a) = 0;
virtual const Activity& search(string title) = 0;
virtual const Activity& search2(string title) const = 0;
virtual void modify(Activity & a, int cmd, string modify) = 0;
virtual vector<Activity> getAll() = 0;
virtual vector<Activity> getAll2() = 0;
virtual void destroy() = 0;
virtual ~DefaultRepo() = default;
virtual double getAll_err();
};
class Repository : public DefaultRepo{
protected:
unordered_map<string, Activity> ActivityList;
unordered_map<string, Activity> CurrActivityList;
/*
medota privata verifica daca exista deja a in repo
*/
//bool exist(const Activity& a) const;
//bool exist2(const Activity& a) const;
public:
Repository() = default;
//Repository(double err) : DefaultRepo(err) {};
Repository(const Repository& ot) = delete;
Repository(double v_err);
/*
Salvare activitate
arunca exceptie daca mai exista o activitate cu acelasi titlu si descriere
*/
virtual void store(const Activity& a);
void storeCurr(const Activity& a);
/*
Sterge activitate
*/
virtual void deleteAc(const Activity& a);
void deleteAc2(const Activity& a);
/*
Cauta
arunca exceptie daca nu exista activitea
*/
virtual const Activity& search(string title);
const Activity& search2(string title) const;
/*
Modifica o activitate, se poate modifica orice cand
*/
virtual void modify(Activity& a, int cmd, string modify);
/*
returneaza toate activitatiile salvate
*/
virtual vector<Activity> getAll();
vector<Activity> getAll2();
//vector<Activity> sameTitle(const string title);
void destroy();
};
class FileRepository : public Repository {
private:
string fName;
void loadFromFile();
void writeToFile();
public:
FileRepository(string fName, double err) : Repository(err), fName{ fName }{ loadFromFile(); }
~FileRepository() = default;
void store(const Activity& a) override;
void deleteAc(const Activity& a) override;
const Activity& search(string title) override;
void modify(Activity& a, int cmd, string modify) override;
vector<Activity> getAll() override;
};
class RepositoryException {
string msgs;
public:
RepositoryException(string m) :msgs{ m } {};
//functie friend (vreau sa folosesc membru privat msg)
friend ostream& operator<<(ostream& out, const RepositoryException& ex);
string getMsg() const { return msgs; };
};
ostream& operator<<(ostream& out, const RepositoryException& ex);
void testsRepo();
| true |