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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
43633e9ecbd75031b50fa718285699a38a8e59b7 | C++ | chr1shr/am225_examples | /2b_lapack+krylov/blas_test.cc | UTF-8 | 2,003 | 2.875 | 3 | [] | no_license | #include <cstdio>
// Include the BLAS functions
#include "blas.h"
#include "omp.h"
// Amount of time (in seconds) to run each test for
const double duration=4.;
int main() {
// Maximum array size to try: set to 2^26, or 64 MB
const int n=1<<26;
// Create large arrays and fill with data
double *a=new double[n],*b=new double[n];
for(int i=0;i<n;i++) a[i]=b[i]=double(i);
// Open output file
FILE *f=fopen("btest.out","w");
if(f==NULL) {
fputs("Can't open output file\n",stderr);
return 1;
}
// Loop over a variety of different array sizes
double alpha=0.12,t0,t1,t2,t3;
int l=1,num_for1,num_for2,num_blas;
for(int k=4096;k<=n;k<<=1) {
num_for1=num_for2=num_blas=0;
// Test manual routine for doing b=b+alpha*a. First approach uses
// a simple for-loop indexed on i.
t0=omp_get_wtime();
do {
for(int i=0;i<k;i++) b[i]+=alpha*a[i];
t1=omp_get_wtime();num_for1++;
} while(t1<t0+duration);
// Second approach uses pointers
do {
for(double *ap=a,*bp=b;ap<a+k;ap++,bp++) *bp+=*ap*alpha;
t2=omp_get_wtime();num_for2++;
} while(t2<t1+duration);
// Test corresponding BLAS routine. Due to C++/Fortran calling
// conventions, all entries are passed as pointers, and there is an
// underscore after the name.
do {
daxpy_(&k,&alpha,a,&l,b,&l);
t3=omp_get_wtime();num_blas++;
} while(t3<t2+duration);
// Print timing info, dividing test durations by the number of trials
t0=(t1-t0)/num_for1;
t1=(t2-t1)/num_for2;
t2=(t3-t2)/num_blas;
printf("Array size %d: for(i) %g s, for(ptr) %g s, BLAS %g s\n",k,t0,t1,t2);
fprintf(f,"%d %g %g %g %d %d %d\n",k,t0,t1,t2,num_for1,num_for2,num_blas);
}
// Free the dynamically allocated memory and close file
fclose(f);
delete [] a;
delete [] b;
}
| true |
4ce5f36e5e4032abb2acffe83c1cea8a51dcfdf8 | C++ | MinaPecheux/Advent-Of-Code | /2019/C++/src/day5.cpp | UTF-8 | 2,813 | 3.46875 | 3 | [] | no_license | /**
* \file day5.cpp
* \brief AoC 2019 - Day 5 (C++ version)
* \author Mina Pêcheux
* \date 2019
*
* [ ADVENT OF CODE ] (https://adventofcode.com)
* ---------------------------------------------
* Day 5: Sunny with a Chance of Asteroids
* =============================================
*/
#include "utils.hpp"
#include "parser.hpp"
#include "intcode.hpp"
// [ Computation functions ]
// -------------------------
/*------------------------------------------------------------------------------
Part I + II
------------------------------------------------------------------------------*/
/**
* \fn int processInputs(std::vector<long long> inputs, int input, bool debug=false)
* \brief Executes the Intcode program on the provided inputs and computes the
* final result.
*
* \param inputs List of long long integers to execute as an Intcode program.
* \param input Specific input for the program execution.
* \param debug Whether or not the IntcodeProgram should debug its execution at
* each instruction processing.
* \return Final output of the program.
*/
int processInputs(std::vector<long long> inputs, int input, bool debug=false) {
// create program
IntcodeProgram* program = new IntcodeProgram(inputs, debug);
// insert input in memory
program->pushMemory(input);
// execute memory
program->run();
// extract result
int result = (int)(program->getLastOutput());
// clean up data
delete program;
return result;
}
// [ Base tests ]
// --------------
/**
* \fn void makeTests()
* \brief Performs tests on the provided examples to check the result of the
* computation functions is ok.
*/
void makeTests() {
// Part I + II
std::vector<long long> inputs1 = { 3,0,4,0,99 };
assert(processInputs(inputs1, 1) == 1);
std::vector<long long> inputs2 = { 3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9 };
assert(processInputs(inputs2, 0) == 0);
assert(processInputs(inputs2, 1) == 1);
std::vector<long long> inputs3 = { 3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,
20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104, 999,1105,1,46,
1101,1000,1,20,4,20,1105,1,46,98,99 };
assert(processInputs(inputs3, 1) == 999);
assert(processInputs(inputs3, 8) == 1000);
assert(processInputs(inputs3, 12) == 1001);
}
int main(int argc, char const *argv[]) {
// check function results on example cases
makeTests();
// get input data
std::string dataPath = "../data/day5.txt";
std::string data = readFile(dataPath);
std::vector<long long> inputs = parseWithDelimiter<long long>(data, ",");
// Part I
int solution1 = processInputs(inputs, 1);
std::cout << "PART I: solution = " << solution1 << '\n';
// Part II
int solution2 = processInputs(inputs, 5);
std::cout << "PART II: solution = " << solution2 << '\n';
return 0;
}
| true |
ad1af0fd6cddaa4d49571572b7c04760cd284833 | C++ | Rituresh143/DSA-Practice | /algo/binary-search/search-in-rotated-array.cpp | UTF-8 | 744 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int binary_search(int arr[],int l,int r,int k)
{
while(l<=r)
{
int mid = l + (r-l)/2;
if(arr[mid]<k)
l=mid+1;
else if(arr[mid]>k)
r=mid-1;
else
return mid;
}
return -1;
}
int pivot(int arr[],int n)
{
int l=0,r=n-1;
while(l<r)
{
int mid = (l+r)>>1;
if(arr[mid]<arr[r])
r=mid;
else
l=mid+1;
}
return l;
}
int main() {
int t;
cin>>t;
while(t--)
{
int n,x;
cin>>n>>x;
int a[n],p;
for(int i=0;i<n;i++) cin>>a[i];
if(a[0]< a[n-1]) p = 0;
else
p=pivot(a,n);
if(a[n-1]<x)
cout<<binary_search(a,0,p-1,x);
else
cout<<binary_search(a,p,n-1,x);
cout<<"\n";
}
return 0;
}
| true |
c47822d1358687951bd7bd21b281b3828c6cfb0f | C++ | johnBuffer/Tree2D | /include/scaffold.hpp | UTF-8 | 640 | 2.5625 | 3 | [] | no_license | #pragma once
#include "tree.hpp"
namespace v2
{
namespace scaffold
{
struct Node
{
Vec2 direction;
float length;
uint32_t index;
uint32_t branch_index;
Node()
: direction()
, length(0.0f)
, index(0)
, branch_index(0)
{}
Node(Vec2 dir, float l, uint32_t i, uint32_t branch)
: direction(dir)
, length(l)
, index(i)
, branch_index(branch)
{}
Vec2 getVec() const
{
return direction * length;
}
};
struct Branch
{
std::vector<Node> nodes;
Branch(const Node& n)
: nodes{ n }
{}
};
struct Tree
{
std::vector<Branch> branches;
};
}
}
| true |
53cba98433f8966e30d73b42fbf254348c1c0220 | C++ | ealpizarp/data_structures | /Tareas/Tarea_4/Tarea_4_PT2/Tarea_4/include/Queue.h | UTF-8 | 581 | 3.203125 | 3 | [] | no_license | #ifndef QUEUE_H
#define QUEUE_H
#define DEFAULT_MAX_SIZE 1024
template <typename T>
class Queue {
private:
void operator =(const Queue&) {}
Queue(const Queue& obj) {}
public:
Queue() {}
virtual ~Queue() {}
virtual void enqueue(T element) = 0;
virtual T dequeue() = 0;
virtual T frontValue() = 0;
virtual void clear() = 0;
virtual bool isEmpty() = 0;
virtual int getSize() = 0;
virtual void print() = 0;
virtual T dequeueRear() = 0;
virtual T rearValue() = 0;
virtual void enqueueFront(T element) = 0;
};
#endif // QUEUE_H
| true |
ded4070d1526e63fb0f3fb9ee021f59d06a9a7d9 | C++ | Stypox/olympiad-exercises | /more/szkopul/pra.cpp | UTF-8 | 1,756 | 2.78125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define int long long
struct Range {
int index;
int from, to;
};
bool setCmp(const Range* a, const Range* b) {
return a->to < b->to;
}
signed main() {
int N;
unsigned int K;
cin>>N>>K;
vector<Range> ranges(N);
for (int n=0;n<N;++n){
ranges[n].index = n+1;
cin>>ranges[n].from>>ranges[n].to;
}
sort(ranges.begin(), ranges.end(), [](const Range& a, const Range& b) { return a.from < b.from; });
int bestRangesLength = 0;
multiset<Range*, decltype(&setCmp)> rangeSet(&setCmp);
for (int n=0;n<N;++n){
Range testRng;
testRng.to = ranges[n].from;
//cerr<<n<<" a "; for (auto e : rangeSet) cerr<<e->index<<" "; cerr<<"\n";
rangeSet.erase(rangeSet.begin(), rangeSet.upper_bound(&testRng));
rangeSet.insert(&ranges[n]);
if (rangeSet.size() > K) {
auto end = rangeSet.begin();
end++;
rangeSet.erase(rangeSet.begin(), end);
}
assert(rangeSet.size() <= K);
if (rangeSet.size() == K) {
int length = (*rangeSet.begin())->to - ranges[n].from;
if (length > bestRangesLength) {
bestRangesLength = length;
}
}
}
rangeSet.clear();
for (int n=0;n<N;++n){
Range testRng;
testRng.to = ranges[n].from;
rangeSet.erase(rangeSet.begin(), rangeSet.upper_bound(&testRng));
rangeSet.insert(&ranges[n]);
if (rangeSet.size() > K) {
auto end = rangeSet.begin();
end++;
rangeSet.erase(rangeSet.begin(), end);
}
assert(rangeSet.size() <= K);
if (rangeSet.size() == K) {
int length = (*rangeSet.begin())->to - ranges[n].from;
if (length == bestRangesLength) {
break;
}
}
}
assert(rangeSet.size() == K);
assert(bestRangesLength > 0);
cout << bestRangesLength << "\n";
for (auto r : rangeSet) {
cout << r->index << " ";
}
}
| true |
e65a673c77c7d3253419b102061e210372c2bd7b | C++ | harryge00/algorithm | /test.cpp | UTF-8 | 629 | 3.15625 | 3 | [] | no_license | // my first program in C++
#include <iostream>
#include <climits>
#include <string.h>
struct s1{
char a;
int b;
};
struct s2{
char a; char c;
int b;
};
struct s3{
char a;
int b;
char c;
};
using namespace std;
int main()
{
if(int k = 0) {
std::cout<<0<<endl;
}
if(int k = 1) {
std::cout<<(k = 91)<<endl;
}
std::cout << sizeof(s1)<<endl;
std::cout << strlen("abc")<<endl;
std::cout << sizeof(s2)<<endl;
std::cout << sizeof(s3)<<endl;
int *a, *b;
std::cout << a<<b<<endl;
int c=132;
b= &c;
std::cout << a<<b<<endl;
string s ="asdfadf";
std::cout << s[5]<<s.length()<<endl;
}
| true |
7a03123ac3f4f875f399498aab38011a24eca8c1 | C++ | caozh/Portfolio | /Cpp/Augmented_Reality/Source_code/Main.cpp | UTF-8 | 3,474 | 2.515625 | 3 | [] | no_license | #include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <iostream>
#include "MarkerDetector.h"
using namespace cv;
int main() {
cv::VideoCapture capWebcam(0); // initialize camera and select camera 0
if (capWebcam.isOpened() == false) { // check if valid
std::cout << "can not access the webcam\n\n";
return(0); // exit program
}
cv::Mat imgOriginal; // input image
cv::Mat imgGray; // convert to Gray
MarkerDetector m_detector; //construct marker detector
Point3f marker_corners[] ={ //marker corner 3d coordinate
Point3f(-0.5f, -0.5f, 0),
Point3f(-0.5f, 0.5f, 0),
Point3f(0.5f, 0.5f, 0),
Point3f(0.5f, -0.5f, 0)
};
std::vector<Point3f> axis ={ //axis 3d vector
Point3f(0.5, 0, 0), //x
Point3f(0, 0.5, 0), //y
Point3f(0, 0, -0.5) //z
};
float camera_matrix[] = { //my camera matrix obtain from calibrateCamera()
848.069f, 0.0f, 268.697f,
0.0f, 847.687f, 264.266f,
0.0f, 0.0f, 1.0f
};
float distortion[] = { -0.445957f, 0.278828f, -0.002213f, -0.000656f }; //distortion coefficients
std::vector<Point3f> m_marker_corners;
m_marker_corners = std::vector<Point3f>(marker_corners, marker_corners + 4); //marker corners vector
cv::Mat m_camera_matrix;
m_camera_matrix = Mat(3, 3, CV_32FC1, camera_matrix).clone(); //Camera Matrix
cv::Mat m_distortion;
m_distortion = Mat(1, 4, CV_32FC1, distortion).clone(); //Distortion coefficient
std::vector<Point2f> imgpts; //declear my axis projection points
//float m_model_view_matrix[16];
char charCheckForEscKey = 0;
while (charCheckForEscKey != 27 && capWebcam.isOpened()) { //Esc key or webcam lose connection to exit
bool blnFrameReadSuccessfully = capWebcam.read(imgOriginal); //load frame
if (!blnFrameReadSuccessfully || imgOriginal.empty()) { // check if frame load successfully
std::cout << "fail to load frame from webcam\n";
break;
}
cv::cvtColor(imgOriginal, imgGray, CV_RGBA2GRAY); //convet to gray img
m_detector.startDetect(imgGray, 100); //load img into marker detector component (input img, marker min-length)
Mat m_rotation, m_translation; //declear rotation and tranlation
std::vector<Marker>& markers = m_detector.get_marker(); //obtain markers from the marker detector component
for (int i = 0; i < markers.size(); ++i){ //for each detected marker
//use camera parameters to calculate the rotation and tranlation matrix
markers[i].marker_solvePnP(m_marker_corners, m_camera_matrix, m_distortion, m_rotation, m_translation);
//call projectPoints() to project 3d object(axis) into the camera img
projectPoints(axis, m_rotation, m_translation, m_camera_matrix, m_distortion, imgpts); //return imgpts (projection vector)
//draw to camera image
markers[i].drawImg(imgOriginal, 2, imgpts); //(input img, thickness, draw img)
}
// declare windows
cv::namedWindow("imgOriginal", CV_WINDOW_AUTOSIZE);
cv::imshow("imgOriginal", imgOriginal); // show results
charCheckForEscKey = cv::waitKey(1); // waitKey
} // end while
return(0);
}
| true |
e9d9943c833f368dd50978a2251db35ea8c13637 | C++ | suyash0103/Competitive-Coding | /Practice Comp code/changAndPerfectFunction.cpp | UTF-8 | 1,061 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cmath>
#define MAX 1000005
using namespace std;
vector <int> divisors[MAX];
int main()
{
int A, B;
long long ans = 0;
cin >> A >> B;
int sqrtB = (int)sqrt(B);
for ( int i = 1; i <= sqrtB; i++ ) {
for ( int j = i; j <= B; j += i ) {
divisors[j].push_back(i);
if ( j/i > sqrtB ) divisors[j].push_back(j/i);
}
}
for ( int y = 1; y <= B; y++ ) {
for ( int j = 0; j < (int)divisors[y].size(); j++ ) {
int k_plus_x = divisors[y][j], k_minus_x = y/divisors[y][j];
if ( k_plus_x >= k_minus_x ) {
if ( (k_plus_x + k_minus_x)%2 == 0 && (k_plus_x - k_minus_x)%2 == 0 ) {
int k = (k_plus_x + k_minus_x)/2;
int x = (k_plus_x - k_minus_x)/2;
if ( x >= 1 && x <= A ) ans++;
}
}
}
}
cout << ans << endl;
return 0;
}
| true |
637a42d3c651a5527ee4b6882d354fb4030f82a8 | C++ | rafaelrds/competitive-programming | /uri/1098-SequenciaIJ4.cpp | UTF-8 | 234 | 2.875 | 3 | [] | no_license | #include <cstdio>
using namespace std;
int main(){
float x = 0, y = 0;
for (int n = 1; n < 45; ++n)
{
if ( n%4 != 0 ){
x = 0.2 * (n-n%4)/4;
y = n % 4;
printf("I=%lg J=%lg\n", x, x+y);
}
}
}
| true |
50e605da2c07bb26899443b65fa266279bd16bcb | C++ | elliotwoods/ofxRulr | /Plugin_Scrap/src/ofxRulr/Models/Transform.h | UTF-8 | 1,690 | 2.625 | 3 | [] | no_license | #pragma once
#include "ofxCeres.h"
#include <glm/gtx/matrix_decompose.hpp>
namespace ofxRulr {
namespace Models {
template<typename T>
struct Transform_ {
Transform_(const T* const translationParameters
, const T* const rotationParameters)
: translation(translationParameters[0]
, translationParameters[1]
, translationParameters[2])
, rotation(rotationParameters[0]
, rotationParameters[1]
, rotationParameters[2])
{
}
Transform_(const glm::tvec3<T> & translation
, const glm::tvec3<T> & rotation)
: translation(translation)
, rotation(rotation)
{
}
Transform_(const glm::tmat4x4<T> & matrix) {
glm::vec3 scale;
glm::quat orientation;
glm::vec3 translation, skew;
glm::vec4 perspective;
glm::decompose(matrix
, scale
, orientation
, translation
, skew
, perspective);
this->translation = (glm::tvec3<T>) translation;
this->rotation = (glm::tvec3<T>) glm::eulerAngles(orientation);
}
Transform_() {
}
glm::tvec3<T> translation;
glm::tvec3<T> rotation;
glm::tmat4x4<T> getTransform() const
{
return ofxCeres::VectorMath::createTransform(this->translation, this->rotation);
}
glm::tvec3<T> applyTransform(const glm::tvec3<T>& point) const
{
return ofxCeres::VectorMath::applyTransform(this->getTransform()
, point);
}
template<typename T2>
Transform_<T2> castTo() const
{
return Transform_<T2>((glm::tvec3<T2>) this->translation
, (glm::tvec3<T2>) this->rotation);
}
};
typedef Transform_<float> Transform;
}
} | true |
8425e806843c59c90378b71ad92e5c4955d0e0d8 | C++ | cp-profiler/cp-profiler | /src/cpprofiler/pixel_views/pixel_image.cpp | UTF-8 | 3,100 | 3 | 3 | [] | no_license | #include "pixel_image.hh"
#include "../utils/debug.hh"
#include <QImage>
#include <cassert>
namespace cpprofiler
{
namespace pixel_view
{
PixelImage::PixelImage()
{
image_.reset(new QImage());
resize({width_, height_});
}
PixelImage::~PixelImage() = default;
void PixelImage::setPixel(std::vector<uint32_t> &buffer, int x, int y,
QRgb color)
{
assert(x >= 0 && y >= 0);
if (x >= width_ || x < 0 || y >= height_ || y < 0)
{
return;
}
uint32_t r = qRed(color);
uint32_t g = qGreen(color);
uint32_t b = qBlue(color);
uint32_t pixel_color = (0xFF << 24) + (r << 16) + (g << 8) + (b);
buffer[y * width_ + x] = pixel_color;
}
void PixelImage::resize(const QSize &size)
{
width_ = size.width() - 10;
height_ = size.height() - 10;
buffer_.clear();
buffer_.resize(width_ * height_);
clear();
update();
}
void PixelImage::clear()
{
/// set all pixels to white
std::fill(buffer_.begin(), buffer_.end(), 0xFFFFFF);
}
void PixelImage::update()
{
auto buf = reinterpret_cast<uint8_t *>(buffer_.data());
image_.reset(new QImage(buf, width_, height_, QImage::Format_RGB32));
}
void PixelImage::zoomIn()
{
pixel_size_ += 1;
}
void PixelImage::zoomOut()
{
if (pixel_size_ > 1)
{
--pixel_size_;
}
}
void PixelImage::drawRect(int x, int y, int width, QRgb color)
{
const auto BLACK = qRgb(0, 0, 0);
assert(y >= 0 && width > 0);
/// the rectange
if (x < 0)
{
/// the rectangle is cut off
width += x;
x = 0;
}
const int x_begin = x * pixel_size_;
const int y_begin = y * pixel_size_;
const int x_end = (x + width) * pixel_size_;
const int y_end = (y + 1) * pixel_size_;
/// Horizontal lines
for (auto col = x_begin; col < x_end; ++col)
{
setPixel(buffer_, col, y_begin, BLACK);
}
for (auto col = x_begin; col < x_end; ++col)
{
setPixel(buffer_, col, y_end - 1, BLACK);
}
/// Vertical lines
for (auto row = y_begin; row < y_end; ++row)
{
setPixel(buffer_, x_begin, row, BLACK);
setPixel(buffer_, x_end - 1, row, BLACK);
}
/// Fill the rect
for (auto col = x_begin + 1; col < x_end - 1; ++col)
{
for (auto row = y_begin + 1; row < y_end - 1; ++row)
{
setPixel(buffer_, col, row, color);
}
}
}
void PixelImage::drawPixel(int x, int y, QRgb color)
{
assert(x >= 0 && y >= 0);
int x0 = x * pixel_size_;
int y0 = y * pixel_size_;
/// TODO(maxim): experiment with using std::fill to draw rows
/// TODO(maxim): experiment with drawing row by row
for (int column = 0; column < pixel_size_; ++column)
{
auto x = x0 + column;
if (x >= width_)
break;
for (int row = 0; row < pixel_size_; ++row)
{
auto y = y0 + row;
if (y >= height_)
break;
setPixel(buffer_, x, y, color);
}
}
}
} // namespace pixel_view
} // namespace cpprofiler
| true |
1e1c2e8502c54bcf98bc77ac8d3ac842ff46900b | C++ | huyinhou/leetcode | /783.minimum-distance-between-bst-nodes.cpp | UTF-8 | 2,185 | 3.40625 | 3 | [] | no_license | /*
* @lc app=leetcode id=783 lang=cpp
*
* [783] Minimum Distance Between BST Nodes
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// #define LEETCODE
#ifdef LEETCODE
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <string>
#include <ostream>
#include <iterator>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#endif
class Solution {
public:
int minDiffInBST(TreeNode* root) {
int diff = INT_MAX;
TreeNode *prev = nullptr;
inOrderBST(root, prev, diff);
return diff;
}
void inOrderBST(TreeNode *root, TreeNode *&prev, int &diff) {
int dist = 0;
if (root->left != nullptr) {
inOrderBST(root->left, prev, diff);
}
if (prev) {
dist = abs(prev->val - root->val);
if (diff > dist) {
diff = dist;
}
}
prev = root;
if (root->right) {
inOrderBST(root->right, prev, diff);
}
}
};
#ifdef LEETCODE
TreeNode *buildTree(vector<int> &vals) {
vector<TreeNode*> nodes(vals.size());
for (int i = vals.size() - 1; i >= 0; i--) {
// cout<<i<<" ";
if (!vals[i]) {
continue;
}
TreeNode *node = new TreeNode(vals[i]);
node->val = vals[i];
int child = 2 * i + 1;
if (child < vals.size() && vals[child]) {
node->left = nodes[child];
}
child++;
if (child < vals.size() && vals[child]) {
node->right = nodes[child];
}
nodes[i] = node;
}
return nodes[0];
}
int main(int argc, char *argv[]) {
Solution s;
vector<int> t1{4,2,6,1,3};
TreeNode *r1 = buildTree(t1);
assert(1 == s.minDiffInBST(r1));
vector<int> t2{8,5,14,1,7,11};
TreeNode *r2 = buildTree(t2);
assert(1 == s.minDiffInBST(r2));
return 0;
}
#endif
| true |
4ea17f784691f83637a208ca8291314e03fd5d14 | C++ | yewenhui/linuxserver | /logging/LogStream.h | GB18030 | 2,949 | 2.84375 | 3 | [
"MIT"
] | permissive | #ifndef _LOG_STREAM_H_
#define _LOG_STREAM_H_
#include <assert.h>
#include <string.h>
#include <string>
#include <boost/noncopyable.hpp>
using std::string;
namespace detail
{
const int SAMLL_BUFFER = 4000;
const int LARGE_BUFFER = 4000 * 1000;
template<int SIZE>
class FixedBuffer
: private boost::noncopyable
{
public:
FixedBuffer()
: m_pCur(m_Data)
{
}
~FixedBuffer() {
}
void Append(const char* pStrBuf, int nLength) {
if (GetAvail() > nLength) {
memcpy(m_pCur, pStrBuf, nLength);
m_pCur += nLength;
}
}
const char* GetData() const { return m_Data; }
int GetLength() const { return m_pCur - m_Data; }
char* GetCurrent() const { return m_pCur; }
int GetAvail() const { return static_cast<int>(end() - m_pCur); }
void Add(size_t unLength) { m_pCur += unLength; }
void Reset() { m_pCur = m_Data; }
void BZero() { ::bzero(m_Data, sizeof(m_Data)); }
string AsString() const { return string(m_Data, GetLength()); }
const char* DebugString() { *m_pCur = '\0'; return m_Data; }
private:
const char* end() const { return m_Data + sizeof(m_Data); }
private:
char m_Data[SIZE];
char* m_pCur;
// CookieFunc m_CookieFunc;
void (*m_CookieFunc)();
};
}
// helper࣬Ϊڱʱַ֪
class T
{
public:
T(const char* pStr, int nLength)
: m_pStr(pStr), m_unLength(nLength)
{
assert(strlen(pStr) == m_unLength);
}
const char* m_pStr;
const size_t m_unLength;
};
class LogStream
: private boost::noncopyable
{
enum {
MAX_NUMERIC_SIZE = 32,
};
public:
typedef detail::FixedBuffer<detail::SAMLL_BUFFER> Buffer;
LogStream& operator<<(bool bVal);
LogStream& operator<<(short sVal);
LogStream& operator<<(unsigned short usVal);
LogStream& operator<<(int nVal);
LogStream& operator<<(unsigned int unVal);
LogStream& operator<<(long lVal);
LogStream& operator<<(unsigned long ulVal);
LogStream& operator<<(long long llVal);
LogStream& operator<<(unsigned long long ullVal);
LogStream& operator<<(float fVal);
LogStream& operator<<(double dVal);
LogStream& operator<<(char cVal);
LogStream& operator<<(const void* pVoid);
LogStream& operator<<(const char* pCVal);
LogStream& operator<<(const T& val);
LogStream& operator<<(const string& rStr);
void Append(const char* pStrData, int nLength) { m_Buffer.Append(pStrData, nLength); }
const Buffer& GetBuffer() const { return m_Buffer; }
void ResetBuffer() { m_Buffer.Reset(); }
private:
void staticCheck();
template<typename T>
void formatInteger(T v);
private:
Buffer m_Buffer;
};
class Fmt
{
public:
template<typename T>
Fmt(const char* pStrFmt, T val);
const char* GetData() const { return m_pStrBuffer; }
int GetLength() const { return m_nLength; }
private:
char m_pStrBuffer[32];
int m_nLength;
};
inline LogStream& operator<<(LogStream& stream, const Fmt& fmt) {
stream.Append(fmt.GetData(), fmt.GetLength());
return stream;
}
#endif // _LOG_STREAM_H_
| true |
987fddec6c8d7b300b985f9676d82f1ce4e4ad1a | C++ | jfellus/pgide_old | /src/commands/CommandUntagSelection.h | UTF-8 | 1,424 | 2.59375 | 3 | [] | no_license | /*
* CommandUntagSelection.h
*
* Created on: 14 nov. 2014
* Author: jfellus
*/
#ifndef CommandUntagSelection_H_
#define CommandUntagSelection_H_
#include <commands/Command.h>
#include <module/Document.h>
#include <module/Module.h>
#include <module/Link.h>
#include "../style/Tags.h"
using namespace libboiboites;
namespace pgide {
class CommandUntagSelection : public Command {
public:
std::string tagname;
std::vector<Module*> modules;
std::vector<Link*> links;
public:
CommandUntagSelection(Document* doc, const std::string& tagname) : tagname(tagname), modules(doc->selected_modules), links(doc->selected_links) {
}
virtual ~CommandUntagSelection() {
}
virtual void execute() {
Tag* t = Tags::get(tagname);
if(!t) {ERROR("No such tag : " << tagname); return;}
for(uint i=0; i<modules.size(); i++) t->remove(modules[i]);
for(uint i=0; i<links.size(); i++) t->remove(links[i]);
Document::cur()->fire_change_event();
ZoomableDrawingArea::cur()->repaint();
}
virtual void undo() {
Tag* t = Tags::get(tagname);
if(!t) {ERROR("No such tag : " << tagname); return;}
for(uint i=0; i<modules.size(); i++) t->add(modules[i]);
for(uint i=0; i<links.size(); i++) t->add(links[i]);
Document::cur()->fire_change_event();
ZoomableDrawingArea::cur()->repaint();
}
virtual std::string get_text() {
return "Untag selection";
}
};
}
#endif /* CommandUntagSelection_H_ */
| true |
3a8b4b9346d66a42d0363a6441dc35b57115270b | C++ | earl-stephens/4jun20 | /square.cpp | UTF-8 | 303 | 3.921875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main () {
// Declare n as a floating-pt variable.
double n;
// Prompt and input value of n.
cout << "Input a number and press ENTER: ";
cin >> n;
// Calculate and output the square.
cout << "The square is: " << n * n << endl;
return 0;
}
| true |
2ea7c20ce5be1a7cb5b9f27d64f9a9ce4d405201 | C++ | AlexMachiu/Laborator7 | /StringVar.h | UTF-8 | 1,339 | 2.828125 | 3 | [] | no_license | #pragma once
#include <iostream>
using std::ostream; using std::istream;
using std::cout; using std::cin; using std::endl;
const int MAX_STRING_LENGTH = 100;
class StringVar
{
public:
StringVar(int lungime);
// Initializeaza obiectul care poate avea lungime maxima "lungime".
// Seteaza valoarea obiectului cu sirul vid.
StringVar();
// Initializeaza obiectul care poate avea lungime maxima 255.
// Seteaza valoarea obiectului cu sirul vid.
StringVar(const char a[]);
// Preconditie: Sirul a contine caractere terminate cu '\0'.
// Initializeaza obiectul cu valoarea lui "a" si cu lungimea maxima egala cu strlen("a").
StringVar(const StringVar &obiect_sir);
// Constructorul de copiere
~StringVar();
// Returneaza memoria dinamica folosita de obiect in heap.
int length() const;
// Returneaza lungimea obiectului apelat.
void citeste_linie(istream &intrare);
// Actiune: se citesc caracterele pana la primul '\n' intalnit.
// Daca obiectul apelat nu are suficient spatiu de memorie pentru toate caracterele, atunci se trunchiaza.
friend ostream &operator <<(ostream &iesire, const StringVar &sir);
// Supraincarca operatorul << pentru a afisa valori de tip StringVar.
// Actiune: se citeste primul sir de caractere diferit de spatii.
private:
char *valoare; // pointer catre sirul dinamic.
int lungime_maxima;
}; | true |
ae23b1c8f21878db00da00daff17fdfc034875d1 | C++ | blenz3/leetcode | /ex1290_convert_binary_number_in_list/solution.cpp | UTF-8 | 973 | 3.1875 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// Copy and or the bits in
int getDecimalValue(ListNode* head) {
std::vector<bool> values;
while (head != nullptr) {
values.push_back(head->val);
head = head->next;
}
int64_t value(0), num_bits(static_cast<int64_t>(values.size()));
for (size_t i = 0; i < num_bits; ++i) {
value |= (values[i] << (num_bits - i - 1));
}
return static_cast<int32_t>(value);
}
#if 0
// Just shift and add
int getDecimalValue(ListNode* head) {
int64_t value(0);
while (head != nullptr) {
value = (value << 1) + head->val;
head = head->next;
}
return static_cast<int32_t>(value);
}
#endif
};
| true |
4d0837527a9c7638685d61b2b052d7be95eea084 | C++ | jckling/Learn-C | /Task/12/Homework12-9.cpp | UTF-8 | 1,031 | 3.375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
void packCharacters(char a, char b);
int main()
{
char a, b;
scanf("%c %c", &a, &b);
packCharacters(a, b);
return 0;
}
void packCharacters(char a, char b)
{
unsigned displaymask = 1 << 15;
unsigned contract;
char c1, c2;
int c;
c1 = a;
c2 = b;
contract = a;
contract <<= 8;
printf("\n\'%c\' in bits as an unsigned integers is:\n",a);
printf("%10u = ", a);
for (c = 0; c < 8; c++)
putchar('0');
putchar(' ');
for (c = 1; c <= 8; c++)
{
putchar(a&displaymask ? '1' : '0');
a <<= 1;
}
printf("\n\'%c\' in bits as an unsigned integers is:\n", b);
printf("%10u = ", b);
for (c = 0; c < 8; c++)
putchar('0');
putchar(' ');
for (c = 1; c <= 8; c++)
{
putchar(b&displaymask ? '1' : '0');
b <<= 1;
}
printf("\n\'%c\' and \'%c\' packed in an unsigned integer:\n", c1, c2);
contract = contract | c2;
printf("%10u = ", contract);
for (c = 1; c <= 16; c++)
{
putchar(contract&displaymask ? '1' : '0');
contract <<= 1;
if (c % 8 == 0)
putchar(' ');
}
} | true |
f435062dab72dc85c19b5a421d99f92d8248b345 | C++ | tranducson25082000/v-l-i-vu-ng | /draw spuare .cpp | UTF-8 | 3,922 | 2.78125 | 3 | [] | no_license |
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <turtlesim/Pose.h>
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
float x, y, theta, v, vt;
float prevx, prevy;
int state = 0;
float target_angle;
float target_distance;
ros::Publisher pub;
const float PI = 3.14159265;
float rate = 35;
geometry_msgs::Twist getMessage(double linear_x, double angular_z)
{
geometry_msgs::Twist msg;
msg.linear.x = linear_x;
msg.angular.z = angular_z;
return msg;
}
void handleStateRotate()
{
if (abs(target_angle-theta) > 1.0/rate) {
pub.publish(getMessage(0, (target_angle-theta)));
} else if (abs(target_angle-theta) > 1e-5) {
pub.publish(getMessage(0, (target_angle-theta)*rate));
} else {
pub.publish(getMessage(0, 0));
state = 0;
}
}
void handleStateStraightForward()
{
cout << "target=" << target_distance << endl;
if (target_distance <= 1e-5) {
pub.publish(getMessage(0, 0));
state = 0;
} else {
if (target_distance > 1.0 / rate)
pub.publish(getMessage(1, 0));
else
pub.publish(getMessage(target_distance*rate, 0));
}
}
void poseCallback(const turtlesim::Pose::ConstPtr& msg)
{
static bool firstCall = true;
// cout << "firstCall=" << boolalpha << firstCall << endl;
prevx = x, prevy = y;
// cout << "x=" << msg->x << " y=" << msg->y
// << " theta=" << msg->theta << " v=" << msg->linear_velocity
// << " vtheta=" << msg->angular_velocity << endl;
x = msg->x, y = msg->y, theta = msg->theta,
v = msg->linear_velocity, vt = msg->angular_velocity;
float dist = sqrt((x-prevx)*(x-prevx)+(y-prevy)*(y-prevy));
if (!firstCall) target_distance -= dist;
firstCall = false;
}
void rotate(float angle)
{
state = 1;
target_angle = angle;
}
void straight_forward(float distance)
{
state = 2;
target_distance = distance;
}
struct Action
{
int type;
float target_angle;
float target_distance;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "myturtle_control");
ros::NodeHandle h;
pub = h.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 1000);
ros::Subscriber sub =
h.subscribe("/turtle1/pose", 1000, poseCallback);
ros::Rate loopRate(rate);
float tx = 8, ty = 8;
queue<Action> q;
q.push({2, 0, 5});
q.push({1, PI/2, 0});
q.push({2, 0, 5});
q.push({1, PI, 0});
q.push({2, 0, 5});
q.push({1,3*PI/2, 0});
q.push({2, 0, 5});
for(int i=1;i<6;i++){
q.push({1,0, 0});
q.push({2,0,0.5});
q.push({1,PI/2,0});
q.push({2,0,5});
q.push({1,0,0});
q.push({2,0,0.5});
q.push({1,PI+PI/2,0});
q.push({2,0,5});
}
for(int i=1;i<6;i++)
{
q.push({1,PI/2,0});
q.push({2,0,0.5});
q.push({1,PI,0});
q.push({2,0,5});
q.push({1,PI/2,0});
q.push({2,0,0.5});
q.push({1,0,0});
q.push({2,0,5});
q.push({1,PI+PI/2,0});
}
bool in_action = false;
while (ros::ok()) {
//pub.publish(getMessage(linear_x, 5.0));
//linear_x += 1.0;
if (state == 0 && !in_action) {
if (q.size() > 0) {
Action a = q.front();
q.pop();
if (a.type == 1) rotate(a.target_angle);
else if (a.type == 2) straight_forward(a.target_distance);
in_action = true;
cout << "state=" << state
<< " action=" << a.type << " " << a.target_distance << " " << a.target_angle << endl;
}
}
else if (state == 0 && in_action) {
in_action = false;
}
else if (state == 1) handleStateRotate();
else if (state == 2) handleStateStraightForward();
loopRate.sleep();
ros::spinOnce();
}
return 0;
}
| true |
0386d8c0c44be3b8a3734fb050318c92cb4939e0 | C++ | unagi11/Git_test | /src/main.cpp | UTF-8 | 267 | 3.328125 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
using namespace std;
void func(int&,int&);
int main(int argc, char* argv[]) {
int a, b;
func(a, b);
cout << "Hello, world!" << endl;
cout << "a = "<< a << ", b = "<< b << endl;
return 0;
}
void func(int& a, int& b) {
a = 200;
b = 100;
} | true |
181d9fdb7eaecae3e7b8a03db3cfbf00be61a88f | C++ | alex555155/FlightDirectorAttitudeIndicator | /Software/Xtest/Xtest.ino | UTF-8 | 1,722 | 2.78125 | 3 | [] | no_license | #define XYE_EN PD6
#define X_STEP PD7
#define X_DIR PC5
#define PORTa 0
#define PORTb 1
#define PORTc 2
#define PORTd 3
#define stepperDwellTime 1//in milliseconds
uint8_t IO[3];//controls the IO
void enableXYE(){
//we must turn PD6 low. 2^6=64. and with 191
IO[PORTd] &= 191;
refreshPortD();
}
void disableXYE(){
//we must turn PD6 high. 2^6=64. or with 64
IO[PORTd] |= 64;
refreshPortD();
}
void setXdir(uint8_t dir){
//X dir is pin PC5. 2^5=32
if(dir){//if dir positive, assert high
IO[PORTc]|=32;
}
else{
IO[PORTc]&=223;
}
refreshPortC();
}
void singleStepX(){
//X step is pin PD7. 2^7=128
//The Plan: turn on, wait, turn off
IO[PORTd] |= 128;//Turn ON
refreshPortD();
delay(stepperDwellTime);//wait
IO[PORTd] &= 127;//Turn Off
refreshPortD();
}
void stepX(long n, uint8_t dly){
while(n>0){
singleStepX();
delay(dly);
n--;
}
}
uint8_t refreshPortA(){//writes to port from IO array
uint8_t val = IO[PORTa];
portWrite(PORTa,val);
return val;
}
uint8_t refreshPortB(){//writes to port from IO array
uint8_t val = IO[PORTb];
portWrite(PORTb,val);
return val;
}
uint8_t refreshPortC(){//writes to port from IO array
uint8_t val = IO[PORTc];
portWrite(PORTc,val);
return val;
}
uint8_t refreshPortD(){//writes to port from IO array
uint8_t val = IO[PORTd];
portWrite(PORTd,val);
return val;
}
void refreshAll(){
refreshPortA();
refreshPortB();
refreshPortC();
refreshPortD();
}
void setup() {
//Initialize Ports C and D
portMode(PORTc,OUTPUT);
portMode(PORTd,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
enableXYE();
stepX(100,10);
disableXYE();
delay(1000);
}
| true |
9a22d509f4f781ef93f4d883ff9a5550463f8726 | C++ | preboy/9DayGame | /libWorld/src/LibGraphics/Src/DX11/VertexBuffer.cpp | GB18030 | 1,204 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include "VertexBuffer.h"
#include "RenderDevice_DX11.h"
using namespace LibGraphics;
CVertexBuffer::CVertexBuffer()
{
m_vertexBuffer = nullptr;
}
CVertexBuffer::~CVertexBuffer()
{
}
bool CVertexBuffer::CreateBuffer(const RenderDevice_DX11* pRenderDevice, const void* pData, UINT ByteWidth)
{
return true;
}
bool CVertexBuffer::UpdateBuffer(const RenderDevice_DX11* pRenderDevice, const void* pData, UINT ByteWidth)
{
// ״Ҫʼ;
if(!m_vertexBuffer)
{
if(!CreateBuffer(pRenderDevice, pData, ByteWidth))
{
return false;
}
}
D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT hResult = pRenderDevice->GetDeviceContext()->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if(FAILED(hResult))
{
return false;
}
memcpy(mappedResource.pData, pData, ByteWidth);
pRenderDevice->GetDeviceContext()->Unmap(m_vertexBuffer, 0);
return true;
}
void CVertexBuffer::Release()
{
if(m_vertexBuffer)
{
m_vertexBuffer->Release();
m_vertexBuffer = nullptr;
}
}
ID3D11Buffer* CVertexBuffer::GetVertexBuffer()const
{
return m_vertexBuffer;
}
| true |
d4798bde363d686dad966c5d2674b4dc140fe272 | C++ | wincentbalin/DDB | /db.hpp | UTF-8 | 1,393 | 2.640625 | 3 | [
"MIT"
] | permissive | /**
* db.hpp
*
* Database abstraction include part of Disc Data Base.
*
* Copyright (c) 2010-2011 Wincent Balin
*
* Based upon ddb.pl, created years before and serving faithfully until today.
*
* Uses SQLite database version 3.
*
* Published under MIT license. See LICENSE file for further information.
*/
#ifndef DB_HPP
#define DB_HPP
#include <iostream>
#include <string>
#include <vector>
#include "sqlite3.h"
#include "error.hpp"
#include "print.hpp"
class DB
{
public:
DB(Print* print);
virtual ~DB(void) throw(DBError);
void open(const char* dbname, bool initialize = false) throw(DBError);
void close(void) throw(DBError);
bool has_correct_format(void) throw(DBError);
bool is_disc_present(const char* disc_name) throw(DBError);
void add_disc(const char* disc_name, const char* starting_directory) throw(DBError);
void remove_disc(const char* disc_name) throw(DBError);
void list_discs(void) throw(DBError);
void list_files(const char* disc_name, bool directories_only = false) throw(DBError);
void search_text(const char* text, bool directories_only = false) throw(DBError);
private:
void init(void);
private:
// Printer
Print* p;
// Database handle
sqlite3* db;
// Database version
int version;
// Database creation SQL statements
std::vector<std::string> format;
};
#endif /* DB_HPP */
| true |
32791abbd9161d28ca12f6194b75b5f19e92751c | C++ | Dgriffin12/511_Past | /Project2/Nausea.cpp | UTF-8 | 710 | 3.25 | 3 | [] | no_license | #include "Nausea.h"
#include <iostream>
using namespace std;
Nausea::Nausea()
{
if(throw_where == 0 && trigger <= 1)
{
cout << "Throwing default ctor exception\n";
cout << "Trigger = " << trigger << endl;
throw "default ctor failed!";
}
trigger--;
}
Nausea::Nausea(const Nausea& s)
{
if(throw_where == 1 && trigger <= 1)
{
cout << "Throwing copy ctor exception\n";
cout << "Trigger = " << trigger << endl;
throw "copy ctor failed!";
}
trigger--;
}
Nausea& Nausea::operator=(const Nausea& s)
{
if(throw_where == 2 && trigger <= 1)
{
cout << "Throwing operator exception\n";
cout << "Trigger = " << trigger << endl;
throw "operator failed!";
}
trigger--;
return *this;
}
| true |
b762fdbb8a905e8392fcc3fc7323d4f2737383f2 | C++ | ttendohv/vh2436779 | /CSC5 WIN14/Savitch_8thEd_Chap7_Prob11_NB_012914/main.cpp | UTF-8 | 2,233 | 3.578125 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Victoria Hodnett
* Created on January 29, 2014, 10:18 AM
* Savitch 8th Edition Chapter 7 Problem 11
* Seating Chart
*/
//System libraries
#include <iostream>
#include <iomanip>
using namespace std;
//Global Constants
const unsigned short COLS = 500;
//Function Prototypes
void initial(bool [][COLS],unsigned short[],int,int);
void display(const bool [][COLS],const unsigned short[],int);
bool whtSeat(bool [][COLS],const unsigned short[],int);
//Execution Begins
int main(int argc, char** argv) {
//Declares variables
const int ROWS = 500;
bool seat[ROWS][COLS];
int rowUtil=15, colUtil=12;
unsigned short pCol[ROWS];
//Initialize arrays
initial(seat,pCol,rowUtil,colUtil);
do{
//Display the seating array
display(seat,pCol,rowUtil);
//Prompt for desired seat
}while(whtSeat(seat,pCol,rowUtil));
//Exit
return 0;
}
void initial(bool seat[][COLS],unsigned short pCol[],int ROWS,int colMax){
//Initialize the arrays
for(int row = 0;row < ROWS; row++){
for (int col = 0;col < COLS; col++){
seat[row][col] = false;
}
pCol[row] = colMax;
}
}
void display(const bool seat[][COLS],const unsigned short pCol[],int ROWS){
//Display the seating arrangement
char view = 'A';
cout << endl;
for(int row = 0;row < ROWS; row++){
cout << setw(2) << row+1;
for (int col = 0;col < pCol[row]; col++){
if(seat[row][col]) cout << setw(2) << "X";
else cout << setw(2) << static_cast<char>(view + col);
}
cout << endl;
pCol[row];
}
}
bool whtSeat(bool seat[][COLS],const unsigned short pCol[],int ROWS){
//Prompt user for seat desired
cout << "Choose Seat to take i.e. 3C " << endl;
int rowSeat; char colSeat;
cin >> rowSeat >> colSeat;
rowSeat--;
colSeat-='A';
//Check if valid seats
if(rowSeat <= ROWS && (colSeat) <= pCol[rowSeat]){
if(!seat[rowSeat][colSeat]){
seat[rowSeat][colSeat] = true;
}else{
cout << "Seat already taken!"<< endl;
}
}else{
cout << "Not a Seat" << endl;
return false;
}
return true;
} | true |
2cddd3e8a002bd4a956f73f80a6b993269765618 | C++ | madhav-bits/Coding_Practice | /leetMonotoneIncDig.cpp | UTF-8 | 4,363 | 3.71875 | 4 | [] | no_license | /*
*
//****************************************************738. Monotone Increasing Digits.*********************************************
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.
(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)
Example 1:
Input: N = 10
Output: 9
Example 2:
Input: N = 1234
Output: 1234
Example 3:
Input: N = 332
Output: 299
Note: N is an integer in the range [0, 10^9].
//These are the examples I had tweaked and worked on.
233332, 3356 10.
10
332
99799
567389
5674573
57143
2341
1234
357143
789289
99799
12743
1232
56684
88888
7798
7796
8887
668841
// Time Complexity: O(n).
// Space Complexity: O(1).
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
*/
//************************************************************Solution 1:************************************************************
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
// Time Complexity: O(n).
// Space Complexity: O(1).
//The algorithm is to find the first occurence where an digit is less than prev. digit. Then replacing all digits following that by "9"
// and then dec. the preceding digit by "1". If the pre. digit is equal ot it's preceding digit, then dec the prev. digit by "1" as long as
// values are equal leaving the last equal digit.
// We are replacing by "9" as we need largest lesser valued int. satisfying the condition.
class Solution {
public:
int monotoneIncreasingDigits(int n) {
int a=0;
string s=to_string(n);
int len=s.length();
if(len==1)
return n;
//cout<<"stirng is: "<<s<<endl;
for(a=0;a<len-1;a++){
if(s[a]>s[a+1]) //"a+1" digit is voilating the desired property.
break;
}
if(a==len-1)
return n;
else{
//cout<<" a is: "<<a<<endl;
for(int i=a+1;i<len;i++) //Starting the first violation replacing all following digits by "9".
s.replace(i,1,"9");
if(a>=0){
while(a-1>=0 && s[a-1]==s[a]){ // Dec. all prev. digits equal to "a" indexed digit except the last one/(Start of string).
s.replace(a,1,"9");
a--;
}
s.replace(a,1,to_string(s[a]-1-48));// Dec. the "a" index by "1" after the above while loop if while loop satisfied.
} // Dec. the non-equal value or equal value if while is satisfied.
}
return stoi(s);
}
};
//************************************************************Solution 2:************************************************************
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
// Time Complexity: O(n).
// Space Complexity: O(1).
// The algorithm is observation based. Here, we are trying to find index where we have to decrease the value and assign all the right
// side indices to '9'. One exception we see is cases like 88886, where the first change index and it's left index will be having same
// value, so their values would be affected, we first the last 8s value to 7, thus the first change index would be 0 and a result the
// changed num. to 79999
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string res=to_string(N); // Init. the final result string.
int marker=res.length(); // Tracks first index to be changed.
for(int i=res.length()-1;i>0;i--){ // Iter. in reverse order.
if(res[i-1]>res[i]){ // If values decrease.
marker=i; // Mark the index to start changing to '9'.
res[i-1]--; // Dec. the first change index value by 1.
} // Using above step we can also find the prev. indices with same val.
}
for(int i=marker;i<res.length();i++) res[i]='9'; // Changing the val. to '9' starting marker index.
return stoi(res); // Convert result str to int and return.
}
}; | true |
8cfa3486b7561f64490d623595d14c4548a2c3a7 | C++ | jhasaurabh312/InterviewBit | /Maths/unique_path.cpp | UTF-8 | 167 | 2.640625 | 3 | [] | no_license | int calc(int a, int b){
if(a==0 || b==0) return 1;
return (calc(a-1,b)+calc(a,b-1));
}
int Solution::uniquePaths(int m, int n) {
return calc(m-1,n-1);
}
| true |
7c377ef9cf45204f506eb04857e881c43607d507 | C++ | WathisLove/PokemonAE | /src/inventory/items/components/EvoluStatComponent.cpp | UTF-8 | 513 | 2.5625 | 3 | [] | no_license | #include "EvoluStatComponent.hpp"
#include "../../../pokemons/Pokemon.hpp"
EvoluStatComponent::EvoluStatComponent(StatName stat, float factor) :
StatBoostComponent(stat, factor) {
}
ItemEffect* EvoluStatComponent::onStat(int& statValue, StatName stat, PokemonID holder) const {
// Apply the Stat boost if there is an evolution
if(Pokemon::hasEvolution(holder)){
StatBoostComponent::onStat(statValue, stat, holder);
}
// No need to send an item effect
return nullptr;
}
| true |
2efb17adc7be7c714c58dc93b953409080961b2e | C++ | GValiente/butano | /butano/include/bn_intrusive_forward_list_fwd.h | UTF-8 | 944 | 2.59375 | 3 | [
"Zlib",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright (c) 2020-2023 Gustavo Valiente gustavo.valiente@protonmail.com
* zlib License, see LICENSE file.
*/
#ifndef BN_INTRUSIVE_FORWARD_LIST_FWD_H
#define BN_INTRUSIVE_FORWARD_LIST_FWD_H
/**
* @file
* bn::intrusive_forward_list declaration header file.
*
* @ingroup intrusive_forward_list
*/
#include "bn_common.h"
namespace bn
{
/**
* @brief To be part of a bn::intrusive_forward_list, values must inherit this class.
*
* @ingroup intrusive_forward_list
*/
class intrusive_forward_list_node_type;
/**
* @brief `std::forward_list` like container that doesn't contain values, it just references them.
*
* It doesn't throw exceptions. Instead, asserts are used to ensure valid usage.
*
* @tparam Type Element type (it must inherit bn::intrusive_forward_list_node_type class).
*
* @ingroup intrusive_forward_list
*/
template<typename Type>
class intrusive_forward_list;
}
#endif
| true |
20a279688f287188bd86a420c1d82a29f7e5be19 | C++ | LopezPedrosaAlex/Smash-Fighters-Raylib-Library- | /Shot.hpp | UTF-8 | 1,238 | 3.15625 | 3 | [] | no_license | //
// Shots.hpp
// Smash_Fighters
//
// Created by Alex Lopez on 22/11/19.
// Copyright © 2019 Alex Lopez . All rights reserved.
//
#ifndef Shot_hpp
#define Shot_hpp
#include <iostream>
#include "raylib.h"
using namespace std;
class shot {
Vector2 position;
Vector2 shotvelocity;
int direction;
public:
shot(Vector2 pos, Vector2 vel, int direction);
bool out();
float position_x() { return position.x; }
float position_y() { return position.y; }
void draw(int i);
void move();
};
shot::shot(Vector2 pos, Vector2 vel, int direction) {
position.y = pos.y + 20;
if(direction == 1) { position.x = pos.x + 60; }
if(direction == -1) { position.x = pos.x; }
shotvelocity = vel;
}
void shot::move() {
position.x += shotvelocity.x;
position.y += shotvelocity.y;
}
void shot::draw(int i) {
if(i == 1) {
DrawTextureEx(TXbullet1, position , 0, 0.5, WHITE);
}
if(i == -1) {
DrawTextureEx(TXbullet1Inverse, position , 0, 0.5, WHITE);
}
}
bool shot::out() {
if(position.x < 0 or position.x > SCREENWIDTH or
position.y < 0 or position.y > SCREENHEIGHT) {
return true;
}
else return false;
}
#endif /* Shot_hpp */
| true |
cfd102cdb69b21e00f1a077c597963fc43968308 | C++ | wwllww/webrtcpuher | /third/util/strutil.cpp | UTF-8 | 3,738 | 2.9375 | 3 | [] | no_license | #include <algorithm>
#include <string.h>
#include <sstream>
#include <locale>
#include <codecvt>
#include "strutil.h"
namespace util {
namespace str
{
#define STR_TO_NUM(type) \
std::stringstream ss; \
ss << strNumber; \
type num = 0; \
ss >> num; \
return num; \
std::vector<std::string> string_split(const std::string &strSource, const char &chSplitChar)
{
std::vector<std::string> ret;
std::string::size_type last = 0;
std::string::size_type index = strSource.find(chSplitChar, last);
while (index != std::string::npos)
{
ret.push_back(strSource.substr(last, index - last));
last = index + 1;
index = strSource.find(chSplitChar, last);
}
if (index - last > 0)
{
ret.push_back(strSource.substr(last, index - last));
}
return ret;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::stringstream ss(s);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::string string_concat(const std::vector<std::string> &strv, const std::string &c)
{
std::string ret;
std::vector<std::string>::const_iterator cit = strv.begin();
for (; cit != strv.end(); cit++)
{
ret += *cit;
ret += c;
}
if (ret.size() > 0)
ret.erase(ret.end() - 1);
return ret;
}
std::string string_trim(const std::string &str, const char c)
{
std::string::size_type pos = str.find_first_not_of(c);
if (pos == std::string::npos)
{
return str;
}
std::string::size_type pos2 = str.find_last_not_of(c);
if (pos2 != std::string::npos)
{
return str.substr(pos, pos2 - pos + 1);
}
return str.substr(pos);
}
std::string& replace_all(std::string& str, const std::string& old_value, const std::string& new_value)
{
while (true)
{
size_t pos = 0;
if ((pos = str.find(old_value, 0)) != std::string::npos)
str.replace(pos, old_value.length(), new_value);
else break;
}
return str;
}
uint64_t str_to_UINT64(const std::string &strNumber)
{
STR_TO_NUM(uint64_t);
}
int32_t str_to_INT32(const std::string &strNumber)
{
STR_TO_NUM(int32_t);
}
const std::string bytesToStr(const std::vector<char>& bytes, std::string& str, unsigned maxLen)
{
unsigned len = (maxLen == 0) ? bytes.size() : std::min(maxLen, (unsigned)bytes.size());
str.resize(len);
memcpy(&str[0], &bytes[0], len);
return str;
}
const std::string bytesToStr(const std::vector<char>& bytes, unsigned maxLen)
{
std::string tempStr;
return bytesToStr(bytes, tempStr, maxLen);
}
const void strToBytes(const std::string& str, std::vector<char>& bytes)
{
bytes.resize(str.size());
memcpy(&bytes[0], &str[0], str.size());
}
std::string getRawString(std::string const& s)
{
std::ostringstream out;
out << '\"';
out << std::hex;
for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
{
// AND 0xFF will remove the leading "ff" in the output,
// So that we could get "\xab" instead of "\xffab"
out << " " << (static_cast<short>(*it) & 0xff);
}
out << '\"';
return out.str();
}
std::string toHexString(const char* buf, int len, const std::string& token)
{
std::string output;
output.reserve(len * (2 + token.size()));
char temp[8];
for (int i = 0; i < len; ++i)
{
sprintf(temp, "%.2x", (uint8_t)buf[i]);
output.append(temp, 2);
output.append(token);
}
return output;
}
unsigned string2int(const std::string& str)
{
unsigned num = 0;
for (unsigned i = 0; i < str.size(); ++i) {
num += (unsigned)str[i];
}
return num;
}
}
}
| true |
e9a1386a156b36f17cd81805b718793101e31751 | C++ | programmerjake/hashlife-voxels | /graphics/image.h | UTF-8 | 4,469 | 2.53125 | 3 | [] | no_license | /*
* Copyright (C) 2012-2017 Jacob R. Lifshay
* This file is part of Voxels.
*
* Voxels is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Voxels is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Voxels; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#ifndef GRAPHICS_IMAGE_H_
#define GRAPHICS_IMAGE_H_
#include <memory>
#include <cstdint>
#include "color.h"
namespace programmerjake
{
namespace voxels
{
namespace io
{
struct InputStream;
}
namespace graphics
{
class Image final
{
Image(const Image &) = delete;
Image &operator=(const Image &) = delete;
private:
struct PrivateAccess final
{
friend class Image;
private:
PrivateAccess() = default;
};
private:
std::uint8_t *pixels;
public:
class Loader
{
friend class Image;
private:
mutable const Loader *next = nullptr;
static const Loader *head;
public:
virtual ~Loader() = default;
const std::size_t signatureSize;
explicit Loader(std::size_t signatureSize) : signatureSize(signatureSize)
{
}
virtual bool signatureMatches(const unsigned char *bytes, std::size_t byteCount) const
noexcept = 0;
virtual std::shared_ptr<Image> load(
const std::shared_ptr<io::InputStream> &inputStream) const = 0;
};
public:
const std::size_t width;
const std::size_t height;
static constexpr std::size_t bytesPerPixel = 4;
public:
Image(std::size_t width, std::size_t height, PrivateAccess)
: pixels(nullptr), width(width), height(height)
{
}
Image(const Image &other, PrivateAccess)
: pixels(new std::uint8_t[other.width * other.height * bytesPerPixel]),
width(other.width),
height(other.height)
{
for(std::size_t i = 0; i < other.width * other.height * bytesPerPixel; i++)
pixels[i] = other.pixels[i];
}
~Image()
{
delete[] pixels;
}
std::shared_ptr<Image> duplicate() const
{
return std::make_shared<Image>(*this, PrivateAccess());
}
static std::shared_ptr<Image> make(std::size_t width, std::size_t height)
{
auto retval = std::make_shared<Image>(width, height, PrivateAccess());
retval->pixels = new std::uint8_t[width * height * bytesPerPixel];
for(std::size_t i = 0; i < width * height * bytesPerPixel; i++)
retval->pixels[i] = 0;
return retval;
}
std::uint8_t *data()
{
return pixels;
}
const std::uint8_t *data() const
{
return pixels;
}
std::size_t index(std::size_t x, std::size_t y) const noexcept
{
constexprAssert(x < width && y < height);
return (x + y * width) * bytesPerPixel;
}
std::uint8_t *data(std::size_t x, std::size_t y) noexcept
{
return pixels + index(x, y);
}
const std::uint8_t *data(std::size_t x, std::size_t y) const noexcept
{
return pixels + index(x, y);
}
void setPixel(std::size_t x, std::size_t y, const ColorU8 &color) noexcept
{
auto *pixel = data(x, y);
pixel[0] = color.red;
pixel[1] = color.green;
pixel[2] = color.blue;
pixel[3] = color.opacity;
}
ColorU8 getPixel(std::size_t x, std::size_t y) const noexcept
{
auto *pixel = data(x, y);
return rgbaU8(pixel[0], pixel[1], pixel[2], pixel[3]);
}
void copy(const Image &source) noexcept
{
constexprAssert(width == source.width && height == source.height);
for(std::size_t i = 0, end = width * height * bytesPerPixel; i < end; i++)
pixels[i] = source.pixels[i];
}
static std::shared_ptr<Image> load(const std::shared_ptr<io::InputStream> &inputStream);
static void registerLoader(std::unique_ptr<Loader> loader) noexcept;
static void init();
};
}
}
}
#endif /* GRAPHICS_IMAGE_H_ */
| true |
151c2f395d2e1be142197206a4d25aaa1a4c72a3 | C++ | abhishekxix/Programs | /cpp_course/declare-a-class.cpp | UTF-8 | 786 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Player //defining a class.
{
//attributes
string name {"Player"};
int health {100}, xp {3};
//methods
void talk(string);
bool is_dead();
};
class Account
{
//attributes
string name {"Account"};
double balance {0.0};
//methods
bool deposit(double);
bool withdraw(double);
};
int main()
{
Player frank, hero; //declaring objects
Player *enemy {nullptr}; //creaing a pointer to the class
Player players[] {frank, hero}; //creating an array of objects.
enemy = new Player;
delete enemy;
vector <Player> players1 {frank};
players1.push_back(hero);
Account frank_account, jim_account;
return 0;
} | true |
9d53cb0f3d27f3a819a1aa89f17c06855ec4a550 | C++ | hj690/OS_Lab | /TwoPassLinker/Module.cpp | UTF-8 | 866 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include "Module.h"
void Module::show(){
int defcount = getDefcount().getDefcount();
vector<pair<Symbol, Raddress> > deflist = getDeflist();
int usecount = getUsecount().getUsecount();
vector<Symbol> uselist = getUselist();
int codecount = getCodecount().getCodecount();
vector<pair<Type, Instr> > program = getProgram();
cout << defcount << " ";
for(int i = 0; i < deflist.size(); i++){
cout << deflist.at(i).first.getSymbol() << " " << deflist.at(i).second.getAddress()<< " ";
}
cout << endl;
cout << usecount << " ";
for(int i = 0; i < uselist.size(); i++){
cout << uselist.at(i).getSymbol()<< " ";
}
cout << endl;
cout << codecount << " ";
for(int i = 0; i < program.size(); i++){
cout << program.at(i).first.getType() << " " << program.at(i).second.getInstr() << " ";
}
cout << endl;
} | true |
1a63181657462a0623e01c2d7b75f42f9784779d | C++ | emonnemo/Zoo | /src/animals/animal/animal.h | UTF-8 | 4,692 | 3.28125 | 3 | [] | no_license | // file : animal.h
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>
#include <set>
using namespace std;
/** \brief Class Animal
* \details Kelas abstrak untuk hewan dalam zoo
*/
class Animal {
public:
Animal();
/**
* \brief Constructor
* \details Menciptakan Animal
* \param _id id jenis animal
* \param _number nomor pada jenisnya
* \param _legend penanda hewan pada peta
* \param _weight berat badan* \param _eat persentase makan 0-100%
* \param _type karnivor, herbivor, omnivor
* \param _position posisi hewan
*/
Animal(string _id,
int _number,
char _legend,
float _weight,
float _eat,
char _type,
pair<int,int> _position);
/** \brief Destructor.
*/
virtual ~Animal();
/** \brief Copy Constructor
* \details copy constructor menjamin tidak bitwise copy.
* \param a Animal yang ingin di-copy
*/
Animal(const Animal& a);
/** \brief Operator =
* \details operator sama dengan, menjamin tidak bitwise copy
* \param a Animal yang ingin di-copy
* \return Animal yang sama dengan a
*/
Animal& operator=(const Animal& a);
/**
* \brief GetId
* \details Mengembalikan id Animal
* \return kode unik untuk jenis Animal tersebut
*/
string GetId() const;
/**
* \brief GetNumber
* \details Mengembalikan nomor number di Animal tersebut
* \return nomor number Animal, pembeda dengan Animal lain yang sejenis
*/
int GetNumber() const;
/** \brief GetWeight
* \details mengembalikan nilai weight dari suatu Animal
*/
float GetWeight() const;
/**
* \brief GetEat
* \details mengembalikan nilai persentase makanan Animal
* \return persentase makanan yang dikonsumsi Animal
*/
float GetEat() const;
/** \brief GetPos
* \details mengembalikan nilai posisi dari suatu Animal
* \return posisi Animal saat itu
*/
pair<int,int> GetPos() const;
/** \brief GetType
* \details mengembalikan type dari suatu Animal
* \return tipe dari Animal (karnivor, herbivor, omnivor)
*/
char GetType() const;
/**
* \brief GetLegend
* \details mengembalikan legenda suatu Animal
* \return legenda Animal tersebut
*/
char GetLegend() const;
/**
* \brief GetHabitat
* \details mengembalikan habitat
* \return habitat yang dapat ditinggali hewan
*/
set<char> GetHabitat() const;
/** \brief SetWeight
* \details mengatur berat badan suatu Animal
* \param _weight nilai berat badan yang ingin di tetapkan untuk suatu Animal
*/
void SetWeight(float _weight);
/** \brief SetPos
* \details mengatur posisi suatu Animal
* \param _position nilai posisi yang ingin di tetapkan untuk suatu Animal
*/
void SetPos(pair<int,int> _position);
/**
* \brief GetCompatible
* \details mengembalikan set compatible
* \return hewan yang dapat tinggal bersama Animal ini dalam 1 kandang
*/
set<string> GetCompatible() const;
/**
* \brief Act
* \details mengoutput kelakuan Animal tersebut
*/
virtual void Act() const = 0;
/**
* \brief Interact
* \details mengoutput hasil interaksi dengan Animal
*/
virtual void Interact() const = 0;
/**
* \brief Description
* \details mengoutput deskripsi Animal tersebut
* \param a jenis binatang
*/
void Description(string a) const;
/**
* \brief Move
* \details Berpindah sejauh 1 langkah ke arah sesuai direction
* I.S.: arah untuk direction sudah pasti masih dalam cage
* \param direction 0 ke atas, 1 ke kiri, 2 ke kanan, 3 ke bawah
*/
void Move(int direction);
protected:
string id; /**< identifier unik untuk jenis hewan tersebut*/
int number; /**< identifier unik untuk hewan pada jenisnya tersebut*/
char legend; /**< legenda hewan pada peta*/
float weight; /**< berat hewan tersebut dalam kilogram*/
float eat; /**< persentase makanan terhadap berat hewan*/
char type; /**< karnivor, herbivor, atau omnivor*/
pair<int,int> position; /**< posisi baris dan kolom hewan*/
set<string> compatible; /**< list jenis hewan lain yang dapat disatukan dengan hewan tersebut*/
set<char> habitat; /**< list habitat yang dapat ditinggali hewan*/
};
#endif
| true |
571cbe7bba8ae90a2f0748428020df25b0e8d33e | C++ | Welease/Data-structures-and-algorithms | /lab1/Stack.h | UTF-8 | 859 | 2.984375 | 3 | [] | no_license | //
// Created by tanzilya on 26.02.2021.
//
#ifndef LAB1_STACK_H
#define LAB1_STACK_H
#include <stdlib.h>
#include <iostream>
#include <random>
# define BLUE "\e[34m"
# define DEFAULT "\e[39m\e[0m"
# define GREEN "\e[92m"
# define RED "\e[31m"
typedef struct s_node {
int data;
s_node *next;
} t_node;
typedef struct s_stack {
t_node *top;
size_t size;
} t_stack;
t_stack * getNewStack();
int getSize(t_stack *stack);
bool isEmpty(t_stack *stack);
int getTopsData(t_stack *stack);
void push(t_stack *stack, int data);
void pop(t_stack *stack);
void clear(t_stack *stack);
void printAllStackData(t_stack *stack);
void pushRandomElements(t_stack *stack);
void moveElement(t_stack *stack, t_stack *additionalStack);
#endif //LAB1_STACK_H
| true |
c215a79745bbf569f061be06dc5952585622135e | C++ | Foxious/phEngine | /src/phEngine/application/DeviceState.h | UTF-8 | 261 | 2.640625 | 3 | [] | no_license | #ifndef DEVICE_STATE_H
#define DEVICE_STATE_H
#include <vector>
enum ButtonStates
{
BTN_RELEASE = 0x01,
BTN_DOWN = 1 << 1,
BTN_HELD = BTN_DOWN | BTN_RELEASE,
};
struct DeviceState
{
std::vector<unsigned char> buttons;
std::vector<float> axes;
};
#endif | true |
c91ae9c05395ec496d1722d717d877c304f6d5ea | C++ | felipejoribeiro/Iniciativa_Rayleigh | /Project_RECAP/OpenGlcpp/OpenGlcpp/src/Difusion.h | UTF-8 | 1,383 | 2.734375 | 3 | [] | no_license | #pragma once
// basic Libs
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
// Math Libs
#define _USE_MATH_DEFINES // M_PI constant
#include <math.h>
#include <vector>
// Useful defines
#define log(x) std::cout << x << std::endl
//#define read(x) std::cin >> read
//int read;
class Simulation
{
public:
Simulation();
~Simulation();
const int N = 31; // Number of cells (x = 22 , y = 22)
const double L = 4.0; // Length of the simulation square domain (meters)
const double ds = (double)L / (N - 1); // Cells length
const double alpha = (double) 97.0; // Thermal condutivity (aluminium)
const double cfl = 1.0; // valor de convergencia
double dt = pow(L / (400 - 1), 2) / (4 * alpha); // time step length (seconds)
const double tempo = 5.0; // Time (seconds)
const double u = 5.0; // X velocity (m/s)
const double v = 5.0; // Y velocity (m/s)
const double incremento = (double)1 * pow(10, -9); // Imcrement for the implicit method
};
| true |
d2d8cd497aec8fffddbcebe1775b22a6e503c413 | C++ | robertmitola/Compilers | /compiler.cpp | UTF-8 | 6,942 | 2.875 | 3 | [] | no_license | /*
ROBERT MITOLA
ALAN LABOUSEUR
MARIST COLLEGE
CMPT 432 - DESIGN OF COMPILERS
14 APRIL 2016
*/
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <sstream>
#include <iomanip>
#include <queue>
#include <unordered_map>
#include <vector>
#include "lexer.h" // The Lexer
#include "parser.h" // The Parser
#include "semantic_analyzer.h" // The Semantic Analyzer
#include "code_generator.h" // The Code Generator
using namespace std;
using std::string;
using std::queue;
using std::setw;
using std::cout;
int main(int argc, char *argv[])
{
////////// SETUP ////////////////////////////////////////////////
string fileName; // variable to store the source program filepath
ifstream sourceFile; // variable to store the filestream
bool verbose = false; // true if verbose output should occur
if(argc > 1) // if the user entered a program filepath for compiling
{
fileName = argv[1]; // set the source variable to that program filepath
if(argc > 2)
{
string arg = argv[2];
if(arg == "verbose") verbose = true;
}
}
else // if s/he didn't...
{
cout << endl << "The filepath to your program must be entered as an argument when running this parser." << endl;
return 1; // exit with errors
}
cout << endl << "Opening source program file..." << endl;
sourceFile.open(fileName.c_str()); // open the given file
if(sourceFile.fail()) // if the file cannot be opened
{
cout << "Error opening source program file. Please make sure the specified path to the file is correct." << endl; // print appropriate error message
return 1; // exit with error
}
// read source file into a string
string source((istreambuf_iterator<char>(sourceFile)), (istreambuf_iterator<char>()));
// split the source into multiple programs (if necessary)
regex eof("([$]|[^$]+)"); // match anything and EOF and anything after
regex_iterator<string::iterator> regIt(source.begin(), source.end(), eof);
regex_iterator<string::iterator> regEnd;
string toAdd = "";
bool leftover = false;
queue<string> programs; // queue to hold all programs
while(regIt != regEnd)
{
string txt = regIt->str();
if(txt == "$")
{
programs.push(toAdd+"$");
toAdd = "";
leftover = false;
}else{
toAdd = txt;
leftover = true;
}
++regIt;
}
if(leftover) programs.push(toAdd); // add program with forgotten $
// compile all the programs in order
int progNum = 0; // program number for keeping track of which is being compiled
while(!programs.empty())
{
++progNum; // so increment the program number
if(progNum > 1) // if not compiling first program
{
cout << endl << "PRESS ENTER TO COMPILE NEXT PROGRAM... (Ctrl+C to stop.)" << endl << endl;
cin.ignore(); // cin to pause program compilation
}
cout << " _____________________________" << endl <<
"| COMPILING PROGRAM No. " << setw(5) << progNum << " |" << endl <<
"+_____________________________+_______________________________________"<< endl;
////////// LEX //////////////////////////////////////////////////
cout << "Performing Lexical Analysis..." << endl;
Lexer lex(programs.front()); // run the lexer by constructing one
queue<Token> que = lex.tokQue; // retreive the token queue
// report lexical errors here
cout << "[" << lex.numErrors << " lexical error(s) found.]"
<< " [" << lex.numWarnings << " lexical warning(s) found.]" << endl;
// exit if lexical errors were found
if(lex.numErrors > 0)
{
// skip to next program
programs.pop(); // on to the next program
continue;
}
// print out the token information if verbose is on
if(verbose)
{
cout <<
"______________________________________________________________________" << endl <<
setw(30) << left << "" << "TOKEN LIST" << setw(30) << right << "" << endl <<
"______________________________________________________________________" << endl;
while(!que.empty())
{
cout << left <<
"[NAME: " << setw(15) << que.front().name << "]" <<
"[VALUE: " << setw(10) << que.front().value << "]" <<
"[LINE: " << setw(20) << que.front().lineNum << "]" << endl;
que.pop();
}
cout << "______________________________________________________________________" << endl;
}
// indicate completion of lexical analysis
cout << "Lexical Analysis complete!" << endl;
////////// PARSE ////////////////////////////////////////////////
cout << "Performing Parsing..." << endl;
Parser parse(lex.tokQue, verbose); // run the Parser by constructing one
// report parser errors here
cout << "[" << parse.numErrors << " parse error(s) found.]" << endl;
// exit if parser errors were found
if(parse.numErrors > 0)
{
// skip to next program
programs.pop(); // on to the next program
continue;
}
// indicate completion of parsing
cout << "Parsing complete!" << endl;
////////// SEMANTIC ANALYSIS ///////////////////////////////////
cout << "Performing Semantic Analysis..." << endl;
Semantic_Analyzer semantics(parse.CST, verbose);
// report semantic errors here
cout << "[" << semantics.numErrors << " semantic error(s) found.]"
<< " [" << semantics.numWarn << " semantic warning(s) found.]" << endl;
// exit if semantic errors were found
if(semantics.numErrors > 0)
{
// skip to next program
programs.pop(); // on to the next program
continue;
}
// indicate completion of semantic analysis
cout << "Semantic Analysis complete!" << endl;
////////// CODE GENERATION /////////////////////////////////////
cout << "Performing Code Generation..." << endl;
Code_Generator codeGen(semantics.AST, semantics.stringsMap, verbose);
// report code gen errors here
cout << "[" << codeGen.numErrors << " code generation error(s) found.]"
<< " [" << codeGen.numWarn << " code generation warning(s) found.]" << endl;
// exit if code gen errors were found
if(codeGen.numErrors > 0)
{
// skip to next program
programs.pop(); // on to the next program
continue;
}
// indicate completion of code generation
cout << "Code Generation complete!" << endl;
////////// PRINT HEX CODE //////////////////////////////////////
// cout << codeGen.hex << endl;
stringstream outFileName;
outFileName << fileName << "_" << progNum << ".txt";
ofstream outFile(outFileName.str());
// turn the hex string into a const char *
const char * c = codeGen.hex.c_str();
// write to outfile
outFile.write(c, codeGen.hex.length()); // 768
// close outfile
outFile.close();
programs.pop(); // on to the next program
}
cout << "End of compilation." << endl;
cout << "______________________________________________________________________" << endl;
return 0; // exit successful
} | true |
d207a5508e8e52cb488a841a89cc934010c710a4 | C++ | nmlgc/ssg | /GIAN07/LZ_UTY.H | UTF-8 | 2,179 | 2.625 | 3 | [
"MIT"
] | permissive | /*
* Packfiles and compression
*
*/
#pragma once
#include "platform/buffer.h"
#include "platform/unicode.h"
#include <array>
// Format
// ------
using fil_checksum_t = uint32_t;
using fil_size_t = uint32_t;
using fil_no_t = uint32_t;
constexpr const std::array<char, 4> PBG_HEADNAME = { 'P', 'B', 'G', 0x1A };
struct PBG_FILEHEAD {
std::array<char, PBG_HEADNAME.size()> name = PBG_HEADNAME;
fil_checksum_t sum = 0;
fil_no_t n = 0;
};
struct PBG_FILEINFO {
fil_size_t size_uncompressed;
fil_size_t offset;
fil_checksum_t checksum_compressed;
};
// ------
class BIT_DEVICE_READ {
struct {
size_t byte = 0;
uint8_t bit = 0;
void operator +=(unsigned int bitcount) {
bit += bitcount;
byte += (bit / 8);
bit %= 8;
}
} cursor;
public:
const BYTE_BUFFER_BORROWED buffer;
BIT_DEVICE_READ(const BYTE_BUFFER_BORROWED buffer) :
buffer(buffer) {
}
BIT_DEVICE_READ(const void* mem,size_t size) :
buffer({ reinterpret_cast<const uint8_t *>(mem), size }) {
}
// Returns 0xFF if we're at the end of the stream.
uint8_t GetBit();
// Returns 0xFFFFFFFF if we're at the end of the stream. Supports a maximum
// of 24 bits.
uint32_t GetBits(unsigned int bitcount);
};
struct BIT_DEVICE_WRITE {
BYTE_BUFFER_GROWABLE buffer;
uint8_t bit_cursor:3 = 0;
void PutBit(uint8_t bit);
void PutBits(uint32_t bits,unsigned int bitcount);
bool Write(const PATH_LITERAL s) const;
};
struct BIT_FILE_READ : public BIT_DEVICE_READ {
const BYTE_BUFFER_OWNED file;
BIT_FILE_READ(BYTE_BUFFER_OWNED &&file) :
BIT_DEVICE_READ(file.get(),file.size()),
file(std::move(file)) {
}
};
struct PACKFILE_READ {
const BYTE_BUFFER_OWNED packfile;
const std::span<const PBG_FILEINFO> info;
PACKFILE_READ(std::nullptr_t null = nullptr) {
}
PACKFILE_READ(
BYTE_BUFFER_OWNED &&packfile, const std::span<const PBG_FILEINFO> info
) :
packfile(std::move(packfile)),
info(info) {
}
BYTE_BUFFER_OWNED MemExpand(fil_no_t filno) const;
};
struct PACKFILE_WRITE {
std::vector<BYTE_BUFFER_BORROWED> files;
bool Write(const PATH_LITERAL s) const;
};
BIT_FILE_READ BitFilCreateR(const PATH_LITERAL s);
PACKFILE_READ FilStartR(const PATH_LITERAL s);
| true |
dc80e656dfe981d97434640684e75723ab617f14 | C++ | grriffin/cs235-list | /wholeNumber.h | UTF-8 | 1,375 | 3.5625 | 4 | [] | no_license | #ifndef wholeNumber_h
#define wholeNumber_h
#include <ostream>
#include "list.h"
/************************************************
* WHOLE NUMBER
* A class to represent an arbitrary large whole
* number. Currently supports:
* INSERTION : for displaying the number w/o thousands separator
* += : add one WholeNumber onto this
* = (int) : assign an integer to the current value
* = : assign one WholeNumber onto this
***********************************************/
class WholeNumber
{
public:
// constructors. We will use the default destructor
WholeNumber() { data.push_back(0); }
WholeNumber(unsigned int value) { *this = value; }
WholeNumber(const WholeNumber &rhs) { *this = rhs; }
// display the number
friend std::ostream &operator<<(std::ostream &out,
const WholeNumber &rhs);
// fetch a given number
friend std::istream &operator>>(std::istream &in, WholeNumber &rhs);
// add onto a given whole number
WholeNumber &operator+=(const WholeNumber &rhs);
// assignment operator for numbers
WholeNumber &operator=(unsigned int value);
// assignment operator for values
WholeNumber &operator=(const WholeNumber &rhs)
{
data = rhs.data;
return *this;
}
private:
typedef custom::list<int> list_type;
list_type data;
};
#endif // WHOLE_NUMBER_H | true |
872fad8f20f7195e0fb2617bb6852bbdb6a8a9d4 | C++ | sparclusive/project-system | /code/userprog/frameprovider.cc | UTF-8 | 2,687 | 2.8125 | 3 | [
"MIT-Modern-Variant"
] | permissive | // stackmgr.cc
// Routines to manage user stacks
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "frameprovider.h"
#include "system.h"
#include "addrspace.h"
/**
* data_end_at indicate where the data segment end.
* Suppose code & segment contiguous and code start at 0x0
**/
FrameProvider::FrameProvider(int allocation_strategy)
{
alloc_strat = allocation_strategy;
total_frame_number=NumPhysPages;
number_of_free_frame = total_frame_number; // If we block the first page, we will need to add -1
// Create bitmap
bitmap = new BitMap(total_frame_number);
// Can not bock the first page, at least for now... It contains the first lines of code,
// so can not make it trigger page fault.
}
FrameProvider::~FrameProvider()
{
// De-alocate bitmap
delete bitmap;
}
/**
* GetNewFrameProvider return address in user space corresponding to Physical Frame, NULL if
* no more memory
**/
int FrameProvider::GetEmptyFrame(unsigned int *page)
{
int index;
unsigned int frame_addr;
// Find a clear bit according to the choosen strategy
switch(alloc_strat)
{
case FIRST:
{
index = bitmap->FindFirst();
break;
}
case LAST:
{
index = bitmap->FindLast();
break;
}
case RANDOM:
{
index = bitmap->FindRandom();
break;
}
default:
{
printf("Unexpected allocation strategy type %d\n", alloc_strat);
ASSERT(FALSE);
break;
}
}
// If error, return -1
if (index == -1)
return -1;
// Compute Physical addr
frame_addr = index*PageSize;
// Clear frame
bzero(machine->mainMemory + frame_addr,PageSize);
// we allocated a frame, so one less free now
number_of_free_frame--;
*page = frame_addr;
return 0;
}
/**
* FreeFrame
* address : int corresponding to the frame freed
* return -1 if invalid addr
**/
int FrameProvider::ReleaseFrame(unsigned int addr)
{
unsigned int frame_index;
// Check if addr does not goes out memory
if (addr > MemorySize-1)
return -1;
// Check if it is the begin of a frame
if ((addr) % PageSize != 0)
return -1;
// Compute frame index
frame_index = addr / PageSize;
// Check if frame is used
if (!bitmap->Test(frame_index))
return -1;
// Clean frame
bitmap->Clear(frame_index);
// We freed a frame, so one more now
number_of_free_frame++;
return 0;
}
int FrameProvider::NumAvailFrame()
{
return number_of_free_frame;
}
| true |
f68e109596f0fda1fd2ed221fd0e09ca812d2ada | C++ | nexon-97/BSUIR-Study | /CSN/WinSockLab/Lab01/AppEntry.cpp | UTF-8 | 995 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <ctime>
#include "Server.h"
using namespace std;
const int REQ_WINSOCK_VER = 2; // Minimum winsock version required
const int DEFAULT_PORT = 4444;
const int TEMP_BUFFER_SIZE = 128;
int main(int argc, char* argv[])
{
int iRet = 1;
Server* AppServer = new Server();
WSADATA wsaData;
if (WSAStartup(MAKEWORD(REQ_WINSOCK_VER, 0), &wsaData) == NULL)
{
// Check if major version is at least REQ_WINSOCK_VER
if (LOBYTE(wsaData.wVersion) >= REQ_WINSOCK_VER)
{
int port = (argc > 1) ? atoi(argv[1]) : DEFAULT_PORT;
AppServer->SetPortNumber(port);
if (AppServer->Start())
{
iRet = 0;
}
}
else
{
perror("Required version not supported!");
}
// Cleanup winsock
if (WSACleanup() != NULL)
{
perror("Cleanup failed!\r\n");
iRet = 1;
}
}
else
{
perror("WSA Startup failed!\r\n");
}
delete AppServer;
printf("Exit code: %d\r\n", iRet);
system("pause");
return iRet;
}
| true |
16461a4c97f93ef85648cc714e5f0b87b02293cd | C++ | akure/experiments | /moderncpp/oops_dp/observer.cpp | UTF-8 | 1,156 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<memory>
#include<functional>
#include<vector>
using namespace std;
struct observer
{
observer() { std::cout << "ctor observer." << std::endl; }
virtual void notify() = 0;
virtual ~observer() { std::cout << "dtor observer." << std::endl; }
};
struct observer_1 final : public observer
{
observer_1() { std::cout << "ctor observer_1." << std::endl; }
virtual ~observer_1() { std::cout << "dtor observer_1." << std::endl; }
public :
virtual void notify() override
{
std::cout <<"observer_1 notify." << std::endl;
}
};
struct subject
{
public:
void register_observer(unique_ptr<observer> o)
{
observers.push_back(std::move(o));
}
void notify() // To observer
{
for (auto && o : observers)
{
o->notify();
}
}
private:
std::vector<unique_ptr<observer>> observers;
// std::vector<std::reference_wrapper<observer>> observers;
};
int main()
{
subject sub;
unique_ptr<observer> o(new observer_1());
sub.register_observer(std::move(o));
sub.notify();
return 0;
}
| true |
9374dc0c880c37875bf276f3b3a0d78609998cf3 | C++ | VB6Hobbyst7/ModularRoboticManipulator-MRM | /Arduino Code/ArduinoCode.ino | UTF-8 | 7,314 | 2.796875 | 3 | [] | no_license | #include "Pins.h"
#include "Joint.h"
Joint JA(A_STEP_PIN, A_DIR_PIN, A_ENABLE_PIN, A_ENDSTOP_PIN, A_INITIAL_ANGLE, JOINT_TYPE_1);
Joint JB(B_STEP_PIN, B_DIR_PIN, B_ENABLE_PIN, B_ENDSTOP_PIN, B_INITIAL_ANGLE, JOINT_TYPE_2);
Joint JC(C_STEP_PIN, C_DIR_PIN, C_ENABLE_PIN, C_ENDSTOP_PIN, C_INITIAL_ANGLE, JOINT_TYPE_2);
const int tam_cmd = 50;
char cmd[tam_cmd];
char num[tam_cmd];
bool moving = false;
void goHomeAll();
void goHomePArcial(bool _joint[]);
void interpretaComando();
void cleanNUM();
void cleanCMD();
void setup() {
Serial.begin(9600);
Serial.setTimeout(10);
JA.startConfig();
JB.startConfig();
JC.startConfig();
}
void loop() {
if(!moving && Serial.available()){
Serial.readBytesUntil(';', cmd, tam_cmd);
//Serial.print("Received: ");
//Serial.println(cmd);
interpretaComando();
}
if(moving == true && !JA.stepper->isRunning() && !JB.stepper->isRunning() && !JC.stepper->isRunning()){
Serial.println("#");
moving = false;
}
JA.stepper->run();
JB.stepper->run();
JC.stepper->run();
}
void interpretaComando(){
//Comands G:
if(cmd[0] == 'G' || cmd[0] == 'g'){
//Comand G1 (Moves to a target angle (in degree)):
if(cmd[1] == '1'){
int index = 2;
// Run through the string, catching every comands
while(cmd[index] != '\0'){
// Blank space, jump over
if(cmd[index]==' '){
index++;
}
//Number without a joint as reference (error)
else if(cmd[index] >= '0' && cmd[index] <= '9'){
break;
}
// Comand for joint A
else if(cmd[index]=='A' || cmd[index]=='a'){
index++;
// Check if it is a number after the comand
if(cmd[index] >= '0' && cmd[index] <= '9'){
int counter = 0;
//Read the whole number
while(!(cmd[index] == ' ' || cmd[index] == '\0'|| (cmd[index]>='a' && cmd[index]<='c') || (cmd[index]>='A' && cmd[index]<='C'))){
num[counter] = cmd[index];
counter++;
index++;
}
double valor = atof(num);
JA.moveToDegree(valor);
moving = true;
}else{ //A referenced joint without any value associated (error)
break;
}
cleanNUM();
}
// Comand for joint B
else if(cmd[index]=='B' || cmd[index]=='b'){
index++;
// Check if it is a number after the comand
if(cmd[index] >= '0' && cmd[index] <= '9'){
int counter = 0;
//Read the whole number
while(!(cmd[index] == ' ' || cmd[index] == '\0' || (cmd[index]>='a' && cmd[index]<='c') || (cmd[index]>='A' && cmd[index]<='C'))){
num[counter] = cmd[index];
counter++;
index++;
}
double valor = atof(num);
JB.moveToDegree(valor);
moving = true;
}else{ //A referenced joint without any value associated (error)
break;
}
cleanNUM();
}
// Comand for joint C
else if(cmd[index]=='C' || cmd[index]=='c'){
index++;
// Check if it is a number after the comand
if(cmd[index] >= '0' && cmd[index] <= '9'){
int counter = 0;
//Read the whole number
while(!(cmd[index] == ' ' || cmd[index] == '\0' || (cmd[index]>='a' && cmd[index]<='c') || (cmd[index]>='A' && cmd[index]<='C'))){
num[counter] = cmd[index];
counter++;
index++;
}
double valor = atof(num);
JC.moveToDegree(valor);
moving = true;
}else{ //A referenced joint without any value associated (error)
break;
}
cleanNUM();
}
}
}
//Comand G28 (Moves to endstops (detecting it)):
if(cmd[1]=='2' && cmd[2]=='8'){
bool foundParameter = false;
bool homeJoints[3] = {false,false,false};
int index = 3;
// Run through the string, catching every comands
while(cmd[index] != '\0'){
// Blank space, jump over
if(cmd[index]==' '){
index++;
}
//Number without a joint as reference (error)
else if(cmd[index] >= '0' && cmd[index] <= '9'){
break;
}
// Comand for joint A
else if(cmd[index]=='A' || cmd[index]=='a'){
index++;
homeJoints[0] = true;
foundParameter = true;
}
// Comand for joint B
else if(cmd[index]=='B' || cmd[index]=='b'){
index++;
homeJoints[1] = true;
foundParameter = true;
}
// Comand for joint C
else if(cmd[index]=='C' || cmd[index]=='c'){
index++;
homeJoints[2] = true;
foundParameter = true;
}
}
if(!foundParameter){
goHomeAll();
}else{
goHomeParcial(homeJoints);
}
}
}
//Comands M:
else if(cmd[0] == 'M' || cmd[0] == 'm'){
//Comand M114 (Get current positions):
if(cmd[1] == '1' && cmd[2] == '1' && cmd[3] == '4'){
JA.getPosition();
Serial.print(", ");
JB.getPosition();
Serial.print(", ");
JC.getPosition();
Serial.println(";");
}
}
cleanCMD();
}
//
void goHomeAll(){
bool hit_a = false, hit_b = false, hit_c = false;
JA.startHoming();
JB.startHoming();
JC.startHoming();
while(true){
if(digitalRead(B_ENDSTOP_PIN) == LOW && hit_b == false){
JB.hitHome();
hit_b = true;
//Serial.println(">> HIT B");
}else{
JB.runJoint();
}
if(digitalRead(C_ENDSTOP_PIN) == LOW && hit_c == false){
JC.hitHome();
hit_c = true;
//Serial.println(">> HIT C");
}else{
JC.runJoint();
}
if(hit_b && hit_c){
break;
}
}
while(true){
if(digitalRead(A_ENDSTOP_PIN) == LOW && hit_a == false){
JA.hitHome();
hit_a = true;
//Serial.println(">> HIT A");
break;
}else{
JA.runJoint();
}
}
Serial.println("#");
}
void goHomeParcial(bool _joint[]){
bool hit_a = true, hit_b = true, hit_c = true;
if(_joint[0]){
JA.startHoming();
hit_a = false;
}
if(_joint[1]){
JB.startHoming();
hit_b = false;
}
if(_joint[2]){
JC.startHoming();
hit_c = false;
}
while(true){
if(digitalRead(A_ENDSTOP_PIN) == LOW && hit_a == false){
JA.hitHome();
hit_a = true;
//Serial.println(">> HIT A");
}else{
JA.runJoint();
}
// ###########
if(digitalRead(B_ENDSTOP_PIN) == LOW && hit_b == false){
JB.hitHome();
hit_b = true;
//Serial.println(">> HIT B");
}else{
JB.runJoint();
}
// ###########
if(digitalRead(C_ENDSTOP_PIN) == LOW && hit_c == false){
JC.hitHome();
hit_c = true;
//Serial.println(">> HIT C");
}else{
JC.runJoint();
}
// ###########
if(hit_a && hit_b && hit_c){
break;
}
}
Serial.println("#");
}
void cleanCMD(){
for(int i=0; i<tam_cmd;i++){
cmd[i] = '\0';
}
}
void cleanNUM(){
for(int i=0; i<tam_cmd;i++){
num[i] = '\0';
}
} | true |
8ea110f9c5f2ac38dcc64ab317867094ab4c2d42 | C++ | xandemnf/EstudosCpp | /aula45_ArquivosOI.cpp | UTF-8 | 624 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<fstream>
using namespace std;
int main(){
//ofstream, ifstream, fstream;
ofstream arquivoO;
arquivoO.open("aula45_ArquivosIO.txt"/*, ios::app*/); //Posiciona o ponteiro no final do arquivo;
int i=0;
//do{
arquivoO << "Alexandre\n";
arquivoO << "Goncalves\n";
arquivoO << "Teixeira\n";
i++;
//}while(i<50);
arquivoO.close();
ifstream arquivoI;
string linha;
arquivoI.open("aula45_ArquivosIO.txt");
if(arquivoI.is_open()){
while(getline(arquivoI, linha)){
cout << linha << endl;
}
arquivoI.close();
}else{
cout << "Nao foi possivel abrir o arquivo" << endl;
}
return 0;
}
| true |
9ecf4764bb0faee0a6b8a8a46cda0e8264c3b07e | C++ | abhisheknrl/MPRAscore | /code/types/stringfun.cpp | ISO-8859-1 | 10,259 | 2.71875 | 3 | [] | no_license | /***********************************************************************************
*
* stringfun.cpp -- String utility functions
*
* Erik Persson and Bjrn Nilsson, 1998-
*
*/
#include <stdio.h>
#include <locale> // For toupper and tolower
// #include <stdlib.h>
// #include <stdarg.h>
#include "string.h"
#include "stringfun.h"
#define FORMAT_BUFFER_SIZE (0x8000)
CString Format(const char *ach, ...)
{
// NOTE: vsprintf was changed to _vsnprintf because of the classical
// security breach: no check against buffer size.
va_list args;
va_start(args,ach);
char aBuf[FORMAT_BUFFER_SIZE ];
vsnprintf(aBuf, FORMAT_BUFFER_SIZE , ach, args);
va_end(args);
return CString(aBuf);
}
CString FormatVA(const char *ach, va_list argptr)
{
// NOTE: vsprintf was changed to _vsnprintf because of the classical
// security breach: no check against buffer size.
char aBuf[FORMAT_BUFFER_SIZE];
vsnprintf(aBuf, FORMAT_BUFFER_SIZE, ach, argptr);
return CString(aBuf);
}
bool ParseInt(const char *ach, int *pResult)
{
// TODO: Write a new version of this that checks for garbage at end
return sscanf(ach,"%d",pResult)==1;
}
const char *strreverse(char *ach)
{
// Reverses the order of the characters in a string
// Returns the pointer to the original string (redundant)
size_t n= strlen(ach) >> 1;
for (size_t i=0;i<n;i++)
ach[i]= ach[n-1-i];
return ach;
}
int strcmp_nocase(const char *ach, const char *ach2)
{
/* Case-insensitive strcmp */
while (*ach)
{
int c, c2;
c= tolower(*ach);
c2= tolower(*ach2);
if (c>c2) return 1;
if (c<c2) return -1;
ach++;
ach2++;
}
if (*ach2)
return -1; /* Had a bug: returned 1 */
else
return 0;
}
int strfind(const char *a0, const CVector<CString> &v)
{
for (int i=0;i<v.GetSize();i++)
if (strcmp(a0, v[i])==0)
return i;
return -1;
}
int strfind(const char *a0, const CVector<const char *> &v)
{
for (int i=0;i<v.GetSize();i++)
if (strcmp(a0, v[i])==0)
return i;
return -1;
}
int strfind_nocase(const char *a0, const CVector<CString> &v)
{
for (int i=0;i<v.GetSize();i++)
if (strcmp_nocase(a0, v[i])==0)
return i;
return -1;
}
int strfind_nocase(const char *a0, const CVector<const char *> &v)
{
for (int i=0;i<v.GetSize();i++)
if (strcmp_nocase(a0, v[i])==0)
return i;
return -1;
}
bool strmatch_recursive(const char *a0, size_t n0, const char *aF, size_t nF)
{
// a0, n0= string
// aF, nF= string with * or ? wildcards
// Also accepts @ as wildcard for letter, and $ as wildcard for a number
// TODO: Replace with standard regexp syntax
size_t j= 0;
for (size_t i=0;i<nF;i++)
{
if (aF[i]=='*')
{
if (i+1==nF)
return true;
for (size_t k=j;k<n0;k++)
if (strmatch_recursive(&a0[k], n0-k, &aF[i+1], nF-(i+1)))
return true;
return false;
}
/*
else if (aF[i]=='[')
{
CVector<bool> v_accepted(256);
v_accepted.Fill(false);
int i1= i+1;
int last= 0;
while (i1<nF && i1!=']')
{
}
if (!v_accepted[a0[j]
i= i1+1;
}
*/
else if (
aF[i]==a0[j] ||
aF[i]=='?' ||
(aF[i]=='@' && ((a0[j]>='a' && a0[j]<='z') || (a0[j]>='A' && a0[j]<='Z'))) ||
(aF[i]=='$' && a0[j]>='0' && a0[j]<='9'))
{
j++;
}
else
return false;
}
return j==n0;
}
bool strmatch_recursive_nocase(const char *a0, size_t n0, const char *aF, size_t nF)
{
// a0, n0= string
// aF, nF= string with * or ? wildcards
size_t j= 0;
for (size_t i=0;i<nF;i++)
{
if (aF[i]=='*')
{
if (i+1==nF)
return true;
for (size_t k=j;k<n0;k++)
if (strmatch_recursive_nocase(&a0[k], n0-k, &aF[i+1], nF-(i+1)))
return true;
return false;
}
else if (tolower(aF[i])==tolower(a0[j]) || aF[i]=='?')
j++;
else
return false;
}
return j==n0;
}
bool strmatch(const char *a0, const char *aF)
{
// a0= string
// aF= string, potentially with * or ? wildcards
return strmatch_recursive(a0, strlen(a0), aF, strlen(aF));
}
bool strmatch_nocase(const char *a0, const char *aF)
{
// a0= string
// aF= string, potentially with * or ? wildcards
return strmatch_recursive_nocase(a0, strlen(a0), aF, strlen(aF));
}
int strinset(const char *a0, const char *aset, const char csep)
{
// checks if a given string is included in a string set (multiple strings separated by csep)
// csep must not be in a0
// returns index within set, or -1
size_t n= strlen(a0);
int p= 0;
while (*aset)
{
size_t i=0;
for (;i<n;i++)
if (a0[i]!=aset[i])
break;
if (i==n && (aset[i]==0 || aset[i]==csep))
return p; // found
while (*aset && *aset!=csep)
aset++;
if (*aset)
aset++;
p++;
}
return -1;
}
bool MatchPrefixNoCase(const char *ach, const char *aPrefix)
{
/* Case-insensitive prefix match. aPrefix must be lowercase */
/* Return true if ach matches the prefix */
char cm;
while ((cm= *(aPrefix++)))
{
if (tolower(*ach) != cm)
return false;
ach++;
}
return true;
}
CString ToLower(CString s)
{
size_t n= s.GetLength();
bool bDiff= false;
for (size_t i= 0; i<n; i++)
if (s[i] != tolower(s[i]))
bDiff= true;
if (bDiff)
{
// Must modify string
char *a= s.LockBuffer();
for (size_t i= 0; i<n; i++)
a[i]= tolower(a[i]);
s.UnlockBuffer();
}
return s;
}
CString ToUpper(CString s)
{
size_t n= s.GetLength();
bool bDiff= false;
for (size_t i= 0; i<n; i++)
if (s[i] != toupper(s[i]))
bDiff= true;
if (bDiff)
{
// Must modify string
char *a= s.LockBuffer();
for (size_t i= 0; i<n; i++)
a[i]= toupper(a[i]);
s.UnlockBuffer();
}
return s;
}
CString BumpName(CString sBaseName)
{
size_t i= 2;
size_t baselen= sBaseName.GetLength();
// Check for decimal number at end
size_t digs= 0;
while (baselen && sBaseName[baselen-1] >= '0' && sBaseName[baselen-1] <= '9')
{
digs++;
baselen--;
}
if (digs)
{
// Convert from decimal and use as starting number
i= 0;
for (size_t pos= 0; pos<digs; pos++)
{
i *= 10;
i += sBaseName[baselen+pos]-'0';
}
// Increase the number to get a unique name
i++;
// Strip off the digits
sBaseName= sBaseName.Left(baselen);
}
// Generate a unique name
return Format("%s%d", (const char *)sBaseName,i);
}
// NOTE: Some functions rely on GetUniqueName to return a name
// with a digit part that is always higher than or equal to
// the digit part at the end of the base name.
CString GetUniqueName(CString sBaseName, void *pObj, bool (*nameIsUsed)(void *, const char *) )
{
// Bump name until it gets unique
while (nameIsUsed(pObj, sBaseName))
sBaseName= BumpName(sBaseName);
return sBaseName;
}
CString ToForwardSlash(CString s)
{
for (size_t i=s.GetLength();--i>=0;)
if (s[i]=='\\')
s.SetAt(i, '/');
return s;
}
CString ToBackSlash(CString s)
{
for (size_t i=s.GetLength();--i>=0;)
if (s[i]=='/')
s.SetAt(i, '\\');
return s;
}
CString ToLinefeedOnly(CString s)
{
// Convert from general format EOL ::= LF | CR LF*
// To Linefeed-only EOL ::= LF
CString sOut;
const char *ach= (const char *) s;
while (char c= *ach++)
{
if (c==13)
{
while (*ach == 10) // skip LF*
++ach;
sOut += char(10);
}
else
sOut += c;
}
return sOut;
}
CString ToCrlf(CString s)
{
// Convert from general format EOL ::= LF | CR LF*
// To CRLF EOL ::= CR LF
CString sOut;
const char *ach= (const char *) s;
while (char c= *ach++)
{
if (c==13)
{
while (*ach == 10) // skip LF*
++ach;
sOut += char(13);
sOut += char(10);
}
else if (c==10)
{
sOut += char(13);
sOut += char(10);
}
else
sOut += c;
}
return sOut;
}
// Added May 2008/BN
void SplitAtChar(const CString &s, const char c, CVector<CString> &vS)
{
// Identify substrings of s delimited by c. Leading/trailing spaces are removed.
vS.SetSize(0);
const char *ach= s;
if (!(*ach))
return;
while (true)
{
while (*ach==32) // Discard space prefix
ach++;
const char *ach0= ach;
while (*ach && *ach!=c)
ach++;
const char *ach1=ach; // Discard space suffix
while (ach1>ach0 && *(ach1-1)==32)
ach1--;
vS.Add(CString(ach0, ach1-ach0));
if (!(*ach))
return;
ach++;
}
}
/***********************************************************************************/
// Common parsing functions, moved here from lingo.h/cpp
const char *Scan_UnsignedInt(const char *ach, int *presult) // BN 040123
{
// Int ::= ("0b" BinDigit BinDigit* | "0x" HexDigit HexDigit* | DecDigit DecDigit*)
bool bOk= false;
int d;
char c= ach[0];
if (c == '0' && ach[1]=='b' && IsBinDigit(ach[2]))
{
// Binary constant
bOk= true;
d= GetBinDigit(ach[2]);
ach += 3;
while (IsBinDigit(c= ach[0]))
{
d= (d<<1) + GetBinDigit(c);
ach++;
}
}
else if (c == '0' && ach[1]=='x' && IsHexDigit(ach[2]))
{
// Binary constant
bOk= true;
d= GetHexDigit(ach[2]);
ach += 3;
while (IsHexDigit(c= ach[0]))
{
d= (d<<4) + GetHexDigit(c);
ach++;
}
}
else if (IsDecDigit(c))
{
// Dec constant
bOk= true;
d= GetDecDigit(c);
ach++;
while (IsDecDigit(c= ach[0]))
{
d= d*10 + GetDecDigit(c);
ach++;
}
}
if (bOk)
{
*presult= d;
return ach;
}
return 0;
}
const char *Scan_Int(const char *ach, int *presult)
{
// Int ::= [-] ("0b" BinDigit BinDigit* | "0x" HexDigit HexDigit* | DecDigit DecDigit*)
bool bNeg= false;
if (ach[0]=='-')
{
bNeg= true;
ach++;
}
int d;
if (!Scan_UnsignedInt(ach, &d))
return 0;
if (bNeg)
d= -d;
*presult= d;
return ach;
}
const char *Scan_Ident(const char *ach)
{
// Return new position or NULL if failed
// Lingo uses C identifiers
char c= *(ach++);
if ((c>='a' && c<='z') || (c>='A' && c<='Z') || c=='_')
{
while (((c= *(ach))>='a' && c<='z') ||
(c>='A' && c<='Z') ||
(c>='0' && c<='9') ||
c=='_')
++ach;
return ach;
}
return 0; // Not a valid identifier
}
| true |
fcabdc878ec551b74985839834eda93229a33c6d | C++ | kurenaif/kyopro | /max_flow.cpp | UTF-8 | 859 | 3.03125 | 3 | [] | no_license | class MaxFlow {
struct Edge {
int to, cap, rev;
Edge(int t, int c, int r) :to(t), cap(c), rev(r){}
};
public:
vector<vector<Edge> > G;
vector<bool > used;
MaxFlow(int MAX_V) :G(MAX_V), used(MAX_V) {}
void add_edge(int from, int to, int cap) {
G[from].push_back(Edge(to,cap,G[to].size()));
G[to].push_back(Edge(from, 0, G[from].size() - 1));
}
int dfs(int v,int t,int f) {
if (v == t) return f;
used[v] = true;
for (int i = 0; i < G[v].size(); ++i) {
Edge &e = G[v][i];
if (!used[e.to] and e.cap>0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
while (true) {
fill(ALL(used), false);
int f = dfs(s, t, 0x3f3f3f3f);
if(f == 0) return flow;
flow += f;
}
}
}; | true |
7c96ea39929940dc59cb8c5ccdab7ad81bbe03bc | C++ | RoynerOM/Piedra-papel-tijera | /main.cpp | UTF-8 | 16,392 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <iomanip>
using namespace std;
//Variables globales y arreglos
int perdidas = 0, ganes = 0, empates = 0,puntos=0, perdidasM = 0, ganesM = 0, empatesM = 0,puntosM=0,Njugadores=0,Nmaquinas=0;
char Jugadas[][20] ={"Piedra", "Papel", "Tijera"};
char Estados[][20] ={"Empate","Perdiste","Ganaste"};
bool Inicio = false;
//Estructuras para usarlos en el histrial del juego
struct Maquinas{
char Nombre[13],FechaHora[20];
int Ganes,Empates,Perdidas,Puntos;
}maquinas[100];//Vector maquinas de tipo Maquinas
struct Jugador{
char Nombre[20],FechaHora[20];
int Ganes,Empates,Perdidas,Puntos;
}jugador[100];//Vector jugador de tipo Jugador
struct Jugador1{
char Nombre[20],FechaHora[20];
int Ganes,Empates,Perdidas,Puntos;
}jugador1[100];//Vector jugador1 de tipo Jugador1
struct Jugador2{
char Nombre[20],FechaHora[20];
int Ganes,Empates,Perdidas,Puntos;
}jugador2[100];//Vector jugador2 de tipo Jugador2
int main();//Declaracion de la funcion main
//Metodo para mostrar los puntos
void mostrarPuntos(bool modo){
if (modo==false){
cout << jugador1[Njugadores].Nombre << " Puntos: "<<puntos<< " Ganadas: " << ganes << " Perdidas: " << perdidas << " Empates: " << empates << endl;
cout<<endl;
cout << jugador2[Njugadores].Nombre << " Puntos: "<<puntosM<< " Ganadas: " << ganesM << " Perdidas: " << perdidasM << " Empates: " << empatesM << endl;
}else{
cout << maquinas[Nmaquinas].Nombre << " Puntos: "<<puntosM<< " Ganadas: " << ganesM << " Perdidas: " << perdidasM << " Empates: " << empatesM << endl;
cout<<endl;
cout << jugador[Nmaquinas].Nombre << " Puntos: "<<puntos<< " Ganadas: " << ganes << " Perdidas: " << perdidas << " Empates: " << empates << endl;
}}
void JugadorVSmaquina(){
bool Salir = false;
int opcion = 0, contador = 0, x = 0,guardar;
Nmaquinas++;
cin.ignore();
cout << "Ingrese su nombre: "; cin.getline(jugador[Nmaquinas].Nombre,20,'\n');
strcpy(maquinas[Nmaquinas].Nombre,"DeepBlue2020");//Se agrega el nombre a la maquina
system("cls");
while (!Salir){
fflush(stdin);
cout << "\n\nIngrese (1) Piedra (2) Papel (3) Tijera (4) Salir" << endl;
cout << "\nEliga una opcion: "; cin >> opcion;
x = 1 + rand() % 3;//Numero aleatorio opciones de para la maquina
system("cls");
switch (opcion){
case 1:
if (x == 1){
//Se incrementan los resultados
empates++; empatesM++; puntos++; puntosM++;
contador=0;
}else if (x == 2){
perdidas++; puntosM+=2; ganesM++;
contador=1;
}else if (x == 3){
//Se incrementan los resultados
ganes++; puntos+=2; perdidasM++;
contador=2;
}
mostrarPuntos(true); cout<<"\n\n";
cout << Estados[contador]<<" elegiste " << Jugadas[opcion-1] << " DeepBlue2020 " << Jugadas[x-1] << endl;break;
case 2:
if (x == 1){
ganes++; perdidasM++; puntos+=2;
contador=2;
}else if (x == 2){
//Se incrementan los resultados
empates++; empatesM++; puntos++; puntosM++;
contador=0;
}else if(x==3){
//Se incrementan los resultados
perdidas++; ganesM++; puntosM+=2;
contador=1;
}
mostrarPuntos(true); cout<<"\n\n";
cout << Estados[contador]<<" elegiste " << Jugadas[opcion-1] << " DeepBlue2020 " << Jugadas[x-1] << endl; break;
case 3:
if (x == 1){
//Se incrementan los resultados
ganesM++; perdidas++; puntosM+=2;
contador=1;
}else if (x == 2){
perdidasM++; ganes++;
puntos+=2; contador=2;
}else if(x==3){
//Se incrementan los resultados
empates++; empatesM++; puntos++; puntosM++;
contador=0;
}
mostrarPuntos(true); cout<<"\n\n";
cout << Estados[contador]<<" elegiste " << Jugadas[opcion-1] << " DeepBlue2020 " << Jugadas[x-1] << endl; break;
case 4:
cout << "Desea guardar los resultados 0 (si),1 (no): "; cin >> guardar;//Se pide si quiere guardar los resultados
system("cls");
switch (guardar) {
case 0:
cin.ignore();
cout<<"\n Ingrese la fecha y hora de hoy para guardar los resultados: ";
cin.getline(jugador[Nmaquinas].FechaHora,20,'\n');//Se pide la Fecha y la hora
strcpy(maquinas[Nmaquinas].FechaHora,jugador[Nmaquinas].FechaHora);
//Se guarda el resultado de cada jugado en el vector maquinas y jugador
maquinas[Nmaquinas].Ganes=ganesM; maquinas[Nmaquinas].Empates=empatesM;
maquinas[Nmaquinas].Perdidas=perdidasM; maquinas[Nmaquinas].Puntos=puntosM;
jugador[Nmaquinas].Ganes=ganes; jugador[Nmaquinas].Empates=empates;
jugador[Nmaquinas].Perdidas=perdidas; jugador[Nmaquinas].Puntos=puntos;
//Los contadores pasan a cero
ganes=0; empates=0;
perdidas=0; puntos=0;
ganesM=0; empatesM=0;
perdidasM=0; puntosM=0;
cout<<"Guardando...\n"; system("timeout 2");
cout<<"Los resultados se guardaron correctamente"<<endl; system("timeout 1");
Salir = true;
main();break;
default:
cout<<"Regresando al menu principal..."<<endl;
//Para que los resultados no se guarden todos los arreglos se pone en 0
maquinas[Nmaquinas].Ganes=0; maquinas[Nmaquinas].Empates=0;
maquinas[Nmaquinas].Perdidas=0; maquinas[Nmaquinas].Puntos=0;
jugador[Nmaquinas].Ganes=0; jugador[Nmaquinas].Empates=0;
jugador[Nmaquinas].Perdidas=0; jugador[Nmaquinas].Puntos=0;
//Los contadores pasan a cero
ganes=0; empates=0;
perdidas=0; puntos=0;
ganesM=0; empatesM=0;
perdidasM=0; puntosM=0;
Nmaquinas--;
system("timeout 2");
main();
} break;
default: cout<<"La opcion eligida no existe"; system("timeout 3"); break;
}}}
void JugadorVSjugador(){
bool Salir = false;
int opcion = 0, x = 0,guardar;
Njugadores++;
cin.ignore();
//Se pide el nombre de el jugador1 y 2
cout << "Jugador 1, Ingrese su nombre: "; cin.getline(jugador1[Njugadores].Nombre,20,'\n');
cout << "Jugador 2, Ingrese su nombre: "; cin.getline(jugador2[Njugadores].Nombre,20,'\n');
system("cls");
while (!Salir){
fflush(stdin);
//Se piden las jugadas de los jugadores
cout << "\nIngrese (1) Piedra (2) Papel (3) Tijera (4) Salir\n" << endl;
cout <<jugador1[Njugadores].Nombre<<" Eliga una opcion: "; cin >> opcion;
cout << "\nIngrese (1) Piedra (2) Papel (3) Tijera (4) Salir\n" << endl;
cout <<jugador2[Njugadores].Nombre<<" Eliga una opcion: "; cin>>x;
system("cls");
switch (opcion){
case 1:
if (x == 1){
//Se incrementan los resultados
empates++; empatesM++; puntos++; puntosM++;
mostrarPuntos(false);
cout<<"\n Empates "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Empates "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
}else if (x == 2){
//Se incrementan los resultados
perdidas++; puntosM+=2; ganesM++;
mostrarPuntos(false);
cout<<"\n Pierde "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Gana "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
}else if (x == 3){
ganes++; puntos+=2; perdidasM++;
mostrarPuntos(false);
cout<<"\n Gana "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Perdio "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
}break;
case 2:
if (x == 1){
//Se incrementan los resultados
ganes++; perdidasM++; puntos+=2;
mostrarPuntos(false);
cout<<"\n Gana "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Perdio "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
}else if (x == 2){
//Se incrementan los resultados
empates++; empatesM++; puntos++; puntosM++;
mostrarPuntos(false);
cout<<"\n Empates "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Empates "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
}else if(x==3){
//Se incrementan los resultados
perdidas++; ganesM++; puntosM+=2;
mostrarPuntos(false);
cout<<"\n Pierde "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Gana "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
} break;
case 3:
if (x == 1){
//Se incrementan los resultados
ganesM++; perdidas++; puntosM+=2;
mostrarPuntos(false);
cout<<"\n Pierde "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Gana "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
}else if (x == 2){
//Se incrementan los resultados
perdidasM++; ganes++; puntos+=2;
mostrarPuntos(false);
cout<<"\n Gana "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Pierde "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
}else if(x==3){
//Se incrementan los resultados
empates++; empatesM++; puntos++; puntosM++;
mostrarPuntos(false);
cout<<"\n Empates "<<jugador1[Njugadores].Nombre<<" Elegiste: "<<Jugadas[opcion-1]<<endl;
cout<<" Empates "<<jugador2[Njugadores].Nombre<<" Elegiste: "<<Jugadas[x-1]<<endl;
} break;
case 4:
cout << "Desea guardar los resultados 0 (si),1 (no): "; cin >> guardar;
system("cls");
switch (guardar) {
case 0:
cin.ignore();
cout<<"\n Ingrese la fecha y hora de hoy para guardar los resultados: ";
cin.getline(jugador1[Njugadores].FechaHora,20,'\n');
strcpy(jugador2[Njugadores].FechaHora,jugador1[Njugadores].FechaHora);//Se fecha ingresada se guarda tanto en el hitorial de maquina y el de Jugador
//Se guarda el resultado de cada jugador en el vector Jugador1 y Jugador2
jugador1[Njugadores].Ganes=ganesM; jugador1[Njugadores].Empates=empatesM;
jugador1[Njugadores].Perdidas=perdidasM; jugador1[Njugadores].Puntos=puntosM;
jugador2[Njugadores].Ganes=ganes; jugador2[Njugadores].Empates=empates;
jugador2[Njugadores].Perdidas=perdidas; jugador2[Njugadores].Puntos=puntos;
ganes=0; empates=0;
perdidas=0; puntos=0;
ganesM=0; empatesM=0;
perdidasM=0; puntosM=0;
cout<<"Guardando...\n"; system("timeout 2");
cout<<"Los resultados se guardaron correctamente"<<endl; system("timeout 1");
Salir = true;
main();break;
default:
cout<<"Regresando al menu principal..."<<endl;
jugador1[Njugadores].Ganes=0; jugador1[Njugadores].Empates=0;
jugador1[Njugadores].Perdidas=0; jugador1[Njugadores].Puntos=0;
jugador2[Njugadores].Ganes=0; jugador2[Njugadores].Empates=0;
jugador2[Njugadores].Perdidas=0; jugador2[Njugadores].Puntos=0;
ganes=0; empates=0;
perdidas=0; puntos=0;
ganesM=0; empatesM=0;
perdidasM=0; puntosM=0;
Njugadores--;
system("timeout 2");
main();
} break;
default:
cout<<"La opcion eligida no existe";
system("timeout 3"); break;
}}}
void Historial(){
int opcion;
while (opcion!=3){
cout<<"(1) Partida vs Maquina\n(2) Partida vs Jugador\n(3) Regresar al Menu Principal\n\nEliga una opcion: ";cin>>opcion;
system("cls");
switch (opcion){
case 1:
if (Nmaquinas==0){
cout<<"\nNo hay historial\n"<<endl;
}else{//Se imprime el historial de el modo Jugador vs Maquina
for (int i = 1; i <= Nmaquinas; i++){
cout<<"\n";
cout<<" Nombre: "<<jugador[i].Nombre<<" Ganes: "<<jugador[i].Ganes;
cout<<" Perdidas: "<<jugador[i].Perdidas<<" Empates: "<<jugador[i].Empates;
cout<<" Puntos: "<<jugador[i].Puntos<<" Fecha/hora: "<<jugador[i].FechaHora;
cout<<"\n";
cout<<" Nombre: "<<maquinas[i].Nombre<<" Ganes: "<<maquinas[i].Ganes;
cout<<" Perdidas: "<<maquinas[i].Perdidas<<" Empates: "<<maquinas[i].Empates;
cout<<" Puntos: "<<maquinas[i].Puntos<<" Fecha/hora: "<<maquinas[i].FechaHora;
cout<<"\n\n";
}}break;
case 2:
if (Njugadores==0){
cout<<"\nNo hay historial\n"<<endl;
}else{//Se imprime el historial de el modo Jugador vs Jugador
for (int i = 1; i <= Njugadores; i++){
cout<<"\n";
cout<<" Nombre: "<<jugador1[i].Nombre<<" Ganes: "<<jugador1[i].Ganes;
cout<<" Perdidas: "<<jugador1[i].Perdidas<<" Empates: "<<jugador1[i].Empates;
cout<<" Puntos: "<<jugador1[i].Puntos<<" Fecha/hora: "<<jugador1[i].FechaHora;
cout<<"\n";
cout<<" Nombre: "<<jugador2[i].Nombre<<" Ganes: "<<jugador2[i].Ganes;
cout<<" Perdidas: "<<jugador2[i].Perdidas<<" Empates: "<<jugador2[i].Empates;
cout<<" Puntos: "<<jugador2[i].Puntos<<" Fecha/hora: "<<jugador2[i].FechaHora;
cout<<"\n\n";
}}break;
case 3: main();break;
default:cout<<"La opcion que ingresaste no existe!"<<endl; break;
}}}
int main(){
srand(time(NULL));
int opc = 0;
system("cls");
while (!Inicio){
cout << "\n(1) Partida vs Maquina\n(2) Partida vs jugador2\n(3) Historial del juego\n(4) Cerrar" << endl;
cout << "\nCual opcion desea elegir: "; cin >> opc; //Se guarda la opcion elegida
system("cls");
switch (opc){
case 1: JugadorVSmaquina(); break;
case 2: JugadorVSjugador(); break;
case 3: Historial();
case 4: Inicio=true; break;
default: cout<<"La Opcion no existe:\n"; break;
}}
getch();
return 0;
} | true |
a7a254a7e9b16654c7e9503362d61ae6702e8860 | C++ | jianxinzhu/Chapter-7-Class-Template-Array-and-Vector-Catching-Exceptions | /PrintArray.cpp | UTF-8 | 467 | 3.34375 | 3 | [] | no_license | /* name: jianxin zhu
date: july/20/2020
*/
#include<array>
#include<iostream>
using namespace std;
const int SIZE = 20;
void printArray(array<int, SIZE>a1, size_t beginNumber, size_t endNumber)
{
if (beginNumber < endNumber)
{
cout << a1[beginNumber]<<" ";
printArray(a1, beginNumber+1, endNumber);
}
}
int main()
{
array<int, SIZE>a1{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
cout << "Print Array: ";
printArray(a1, 0, SIZE);
}
| true |
222798209da77d71dc9985b8327bd7345ed4e514 | C++ | cipriancus/WormNET | /SeachEngine/ChordFiles/AnonymousChordLibrary/p2p/protocols/chord/ChordNode.h | UTF-8 | 3,878 | 2.546875 | 3 | [] | no_license | #ifndef CHORDNODE_H
#define CHORDNODE_H
#include "IOverlay.h"
#include "AbstractChord.h"
#include "TransportHTTP.h"
#include <string>
#include <map>
#include <vector>
#include <ctime>
class Stabilization;
using namespace std;
struct contact {
ChordNode *node;
Node *selectedNode;
transportCode tr;
map<string, string> queryParams;
};
class ChordNode : public AbstractChord {
public:
ChordNode();
/* Constructor & Destructor */
ChordNode(const string &ip, int port, const string &overlayIdentifier,
const string &rootDirectory);
~ChordNode();
/* Setters */
void setIdentifier(const string &iD) {
overlayIdentifier = iD;
}
string getIdentifier() {
return overlayIdentifier;
}
TransportHTTP* getTransport() {
return transport;
}
void setTransport(TransportHTTP *t) {
transport = t;
}
/* Action Methods */
virtual string sendRequest(Request *request, Node* destination);
virtual string sendRequestTimeout(Request *request, Node* destination, int timeout) ;
virtual void fixBrokenPointers(Node* node);
virtual bool isAlone();
virtual void checkStable();
virtual void shutDown();
/* Override Methods */
void notify(Node *n);
void stabilize();
/* IOverlay Pure METHODS */
void put(string key, string value);
string get(string key);
void removekey(string key);
string getDataOrPrecedingNode(char *id);
/* data CRUD */
void saveData(string filename, string value);
string openData(string filename);
string serializeData(string data);
string unserializeData(string data);
/* tools methods */
Query* searchForQueryByHash(string hash);
unsigned int getIntSHA1(string key);
char *getHexSHA1(string str);
time_t getStartTime() {
return startTime;
}
std::vector<Node*> getFingerTable() {
return fingerTable;
}
Node* getThisNode() {
return thisNode;
}
string serialize(ChordNode *node);
ChordNode* deserialize(string data);
bool getQueryForHash(string hash, Query *query);
Query* getHandledQueryForHash(string hash);
Node* getNodeForIP(string ip);
vector<Node*> getPassedQueryForHash(string hash);
void addPassedQuery(string hash, vector<Node*> predSucc);
void addHandledQuery(Query *query) {
this->handledQueries.push_back(query);
}
string randomWalk(string key);
void phaseOne(Query *query);
void getNodeKey(Node *node, Query *query, string &in_key, string &in_iv);
string crypt(string plaintext_string, unsigned char *key, unsigned char *iv);
string decrypt(string cryptotext_string, unsigned char *key, unsigned char *iv);
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & fingerTable;
}
string send_request_with_timeout(Node *selectedNode, transportCode tr, int noOfSecondsToWait, map<string, string> &queryParams);
pthread_mutex_t calculating = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t done = PTHREAD_COND_INITIALIZER;
char* itoa(int num, char* str, int base);
void reverse(char str[], int length);
private:
TransportHTTP* transport;
/* One thread for the stabilization of each node */
Stabilization* stableThread;
/* The id of the overlay */
string overlayIdentifier;
/* node notification */
bool notified;
/* Part of the DHT */
typedef std::pair<string, string> data;
typedef std::map<string, string> dataMap;
dataMap table;
//all processed queries over a time length
map<string, vector<Node*>> passedQueries;
time_t startTime;
vector<Query*> allQueries; //all my queries
vector<Query*> handledQueries; //queries handled and passed
};
#endif
| true |
6cb0552d03eab50ccdf3fedaf5d2471969bcf922 | C++ | jeffdk/SpecClass2011 | /Iryna/Assignment02Iryna/Executables/TestAssignment02Iryna.cpp | UTF-8 | 1,666 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include "MyVector.hpp"
#include "OptionParser.hpp"
#include "ReadFileIntoString.hpp"
#include "UtilsForTesting.hpp"
#include "Require.hpp"
#include "Assignment02Iryna.hpp"
int main(int /*argc*/, char** /*argv*/) {
//Try out the new sumVectors function
//First, create a couple of vectors, then add them together
OptionParser p(ReadFileIntoString("Vectors.input"));
MyVector<double> A = p.Get<MyVector<double> >("FirstVectorToAdd");
MyVector<double> B = p.Get<MyVector<double> >("SecondVectorToAdd");
const double C = p.Get<double>("DoubleToDivideBy");
// Check that C isn't equal to 0
UtilsForTesting u;
IS_TRUE(C != 0.0, "ERROR: DoubleToDivideBy can't be 0.0");
//REQUIRE(divisor != 0.0, "ERROR: DoubleToDivideBY can't be 0.0");
//Next, make a vector to store the result
MyVector<double> result(MV::Size(A.Size()),0.);
//Add the vectors together
result = addDivideVectors(A,B,C);
//Print out the results
std::cout << "Vector A = " << A << std::endl;
std::cout << "Vector B = " << B << std::endl;
std::cout << "Result = " << result << std::endl;
double resultMagnitudeSq = 0.0;
for(int i=0; i<result.Size(); ++i){
resultMagnitudeSq += result[i]*result[i];
}
IS_ZERO(resultMagnitudeSq, "Sum of vector and its negative nonzero.");
//Return success
return u.NumberOfTestsFailed();
}
| true |
e57bb66e31b08641b69e2e6645fab2887337c8ea | C++ | NEWPLAN/OJ | /data_struct/src/src_ch03/CH03-4.cpp | GB18030 | 383 | 2.875 | 3 | [] | no_license | /*********************************************
* P93 㷨3.7 ͳƶҶӽ㷨
**********************************************/
int count_leafs(BTreePtr pbt)
{
if( pbt== NULL ){
return 0;
}
if((pbt->lchild == NULL) && (pbt->rchild == NULL)){
return 1;
}
return(count_leaf_BT(pbt->lchild) + count_leaf_BT(pbt->rchild) );
} | true |
d55cafd1036f288f84918b176bb4f62e65d3046f | C++ | code0monkey1/Competitive | /zigzag.cpp | UTF-8 | 1,548 | 2.890625 | 3 | [] | no_license | //zig zag topcoder
#include<bits/stdc++.h>
using namespace std;
int zigzag(const std::vector<int> & v){
int maxi=0;
bool is_negative=0;
int inter_max=0;
bool positive_switch=0;
bool negative_switch=0;
bool start_count=0;
for(int i=0;i<v.size()-1;i++){
if(!start_count){
if(v[i]-v[i+1]<0){
is_negative=1;
negative_switch=1;
}
else positive_switch=1;
start_count=1;
inter_max++;
}
else if(is_negative){
if(v[i]-v[i+1]>=0 && negative_switch){
inter_max++;
negative_switch=0;
}
else if((!negative_switch) && v[i]-v[i+1]<0 ){
inter_max++;
negative_switch=1;
}
else{
maxi=max(maxi,inter_max);
start_count=0;
inter_max=0;
i--;
}
}
else{
if(v[i]-v[i+1]<0 && positive_switch){
inter_max++;
positive_switch=0;
}
else if((!positive_switch) && v[i]-v[i+1]>=0 ){
inter_max++;
positive_switch=1;
}
else{
maxi=max(maxi,inter_max);
start_count=0;
inter_max=0;
i--;
}
}
}
maxi=max(inter_max,maxi);
return maxi+1;
}
int main(){
string line;
while(getline(cin,line)){
stringstream ss(line);
string token;
while(getline(ss,token,' ')){
reverse(token.begin(), token.end());
cout<<token<<" ";
}
cout<<endl;
}
return 0;
} | true |
c723cfe57dc8f848013c021097ea36a308e22de1 | C++ | naturerun/LALRAnalysisGenerator | /LALRAnalysis/DirectedGraph.h | GB18030 | 9,825 | 3.484375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include <vector>
using std::vector;
template <typename V, typename E> //V,E붨忽캯ƸֵԼ
class Graph //ͼ,洢ṹΪʮ
{
friend class RELALRParsing;
public:
class GraphVertexNode;
struct GraphEdgeNode //߽ڵ
{
typename vector<GraphVertexNode*>::size_type head = 0; //ͷӦ
typename vector<GraphVertexNode*>::size_type tail = 0; //βӦ
E* Edgedatafield = nullptr; //ָ߽ڵָ
GraphEdgeNode* sameheadptr = nullptr; //ָͷͬһ߽ڵ
GraphEdgeNode* sametailptr = nullptr; //ָβͬһ߽ڵ
GraphEdgeNode() = default;
GraphEdgeNode(typename vector<GraphVertexNode*>::size_type sh, typename vector<GraphVertexNode*>::size_type st, E* Edge) :head(sh), tail(st), Edgedatafield(Edge) {}
~GraphEdgeNode() { delete Edgedatafield; }
};
struct GraphVertexNode
{
typename vector<GraphVertexNode*>::size_type number = 0; //
V* Vertexdatafield = nullptr; //ָָ
GraphEdgeNode* firstheadptr = nullptr; //ָԶΪͷĵһ߽ڵ
GraphEdgeNode* firsttailptr = nullptr; //ָԶΪβĵһ߽ڵ
GraphVertexNode* seilring = nullptr; //Իָָ㱾,Ϊ
E* Edgeseilring = nullptr; //ָڶϵԻָ
GraphVertexNode() = default;
GraphVertexNode(typename vector<GraphVertexNode*>::size_type num, V* Ver) :Vertexdatafield(Ver), number(num) {}
~GraphVertexNode() { delete Vertexdatafield; delete Edgeseilring; }
};
Graph() = default;
Graph(typename vector<GraphVertexNode*>::size_type n) :SetOfVertex(n, nullptr) {} //SetOfVertexʼΪСΪnĶ,ԪָָΪ
virtual ~Graph();
Graph<V, E>* Copy(); //ΪĿĶͼָõͼָ
typename vector<typename Graph<V, E>::GraphVertexNode*>::size_type addVertex(V* vertex); //ͼһ㣬öΪvertexָ,Ķ
bool addEdge(typename vector<GraphVertexNode*>::size_type vertex1, typename vector<GraphVertexNode*>::size_type vertex2, E* edge); //ͼvertex1Ϊβ,vertex2Ϊͷı,vertex1,vertex2ڣȣӳɹtrue,false
Graph<V, E>* merge(Graph<V, E>& Bemerged, bool copyOrNot); //ΪĿĶͼBemergedϲ,copyOrNot=trueĿĶBemergedĿĶϲغϲͼָ룬BemergedֱӺϲĿĶnullptr
typename vector<GraphVertexNode*>::size_type getVertexNum() { return SetOfVertex.size(); } //ͼж
void ReversalGraph(); //ΪĿĶͼÿ߷תͷͻβ
protected:
vector<GraphVertexNode*> SetOfVertex; //ͼ㹹ɵļ
};
template <typename V, typename E>
void Graph<V, E>::ReversalGraph()
{
for (typename vector<GraphVertexNode*>::size_type scan = 0; scan < SetOfVertex.size(); ++scan)
{
for (GraphEdgeNode* q = SetOfVertex[scan]->firsttailptr; q != nullptr; )
{
swap(q->head, q->tail);
GraphEdgeNode* temp = q->sametailptr;
swap(q->sameheadptr, q->sametailptr);
q = temp;
}
swap(SetOfVertex[scan]->firstheadptr, SetOfVertex[scan]->firsttailptr);
}
}
template <typename V, typename E>
Graph<V, E>* Graph<V, E>::Copy()
{
Graph<V, E>* temp = new Graph<V, E>(SetOfVertex.size());
for (typename vector<GraphVertexNode*>::size_type scan = 0; scan < SetOfVertex.size(); ++scan)
{
temp->SetOfVertex[scan] = new GraphVertexNode(SetOfVertex[scan]->number, new V(*(SetOfVertex[scan]->Vertexdatafield)));
if (SetOfVertex[scan]->seilring != nullptr)
{
temp->SetOfVertex[scan]->seilring = temp->SetOfVertex[scan];
temp->SetOfVertex[scan]->Edgeseilring = new E(*(SetOfVertex[scan]->Edgeseilring));
}
GraphEdgeNode* p = nullptr;
for (GraphEdgeNode* q = SetOfVertex[scan]->firsttailptr; q != nullptr; q = q->sametailptr)
{
if (p == nullptr)
{
p = temp->SetOfVertex[scan]->firsttailptr = new GraphEdgeNode(q->head, q->tail, new E(*(q->Edgedatafield)));
}
else
{
p = p->sametailptr = new GraphEdgeNode(q->head, q->tail, new E(*(q->Edgedatafield)));
}
}
}
for (typename vector<GraphVertexNode*>::size_type scan = 0; scan < SetOfVertex.size(); ++scan)
{
GraphEdgeNode* p = nullptr;
for (GraphEdgeNode* q = SetOfVertex[scan]->firstheadptr; q != nullptr; q = q->sameheadptr)
{
GraphEdgeNode* m = temp->SetOfVertex[q->tail]->firsttailptr;
for (; ; m = m->sametailptr)
{
if (m->head == scan)
break;
}
if (p == nullptr)
{
p = temp->SetOfVertex[scan]->firstheadptr = m;
}
else
{
p = p->sameheadptr = m;
}
}
}
return temp;
}
template <typename V, typename E>
Graph<V, E>::~Graph()
{
for (typename vector<GraphVertexNode*>::size_type scan = 0; scan < SetOfVertex.size(); ++scan)
{
GraphEdgeNode* ptr = nullptr;
while (SetOfVertex[scan]->firsttailptr != nullptr)
{
ptr = SetOfVertex[scan]->firsttailptr;
SetOfVertex[scan]->firsttailptr = ptr->sametailptr;
SetOfVertex[ptr->head]->firstheadptr = ptr->sameheadptr;
delete ptr;
}
}
while (SetOfVertex.empty() == false)
{
delete SetOfVertex.back();
SetOfVertex.pop_back();
}
}
template <typename V, typename E>
typename vector<typename Graph<V, E>::GraphVertexNode*>::size_type Graph<V, E>::addVertex(V* vertex)
{
SetOfVertex.push_back(new GraphVertexNode(SetOfVertex.size(), vertex));
return SetOfVertex.size() - 1;
}
template <typename V, typename E>
bool Graph<V, E>::addEdge(typename vector<GraphVertexNode*>::size_type vertex1, typename vector<GraphVertexNode*>::size_type vertex2, E* edge) //vertex1Ϊβ,vertex2Ϊͷ
{
if (vertex1 == vertex2)
{
SetOfVertex[vertex1]->seilring = SetOfVertex[vertex1];
SetOfVertex[vertex1]->Edgeseilring = new E(*edge);
return true;
}
GraphEdgeNode* start = SetOfVertex[vertex1]->firsttailptr;
GraphEdgeNode* pre = nullptr;
if (start == nullptr)
{
SetOfVertex[vertex1]->firsttailptr = new GraphEdgeNode(vertex2, vertex1, edge);
if (SetOfVertex[vertex2]->firstheadptr == nullptr)
{
SetOfVertex[vertex2]->firstheadptr = SetOfVertex[vertex1]->firsttailptr;
return true;
}
}
else
{
for (; start != nullptr; )
{
if (start->head == vertex2)
return false;
else if (start->head < vertex2)
{
pre = start;
start = start->sametailptr;
}
else
{
if (pre == nullptr)
{
pre = SetOfVertex[vertex1]->firsttailptr;
SetOfVertex[vertex1]->firsttailptr = new GraphEdgeNode(vertex2, vertex1, edge);
SetOfVertex[vertex1]->firsttailptr->sametailptr = pre;
if (SetOfVertex[vertex2]->firstheadptr == nullptr)
{
SetOfVertex[vertex2]->firstheadptr = SetOfVertex[vertex1]->firsttailptr;
return true;
}
pre = SetOfVertex[vertex1]->firsttailptr;
}
else
{
pre->sametailptr = new GraphEdgeNode(vertex2, vertex1, edge);
pre->sametailptr->sametailptr = start;
if (SetOfVertex[vertex2]->firstheadptr == nullptr)
{
SetOfVertex[vertex2]->firstheadptr = pre->sametailptr;
return true;
}
pre = pre->sametailptr;
}
break;
}
}
if (start == nullptr)
{
if (pre->head == vertex2)
return false;
pre->sametailptr = new GraphEdgeNode(vertex2, vertex1, edge);
if (SetOfVertex[vertex2]->firstheadptr == nullptr)
{
SetOfVertex[vertex2]->firstheadptr = pre->sametailptr;
return true;
}
pre = pre->sametailptr;
}
}
if (pre == nullptr)
{
pre = SetOfVertex[vertex1]->firsttailptr;
}
GraphEdgeNode* p = nullptr;
for (GraphEdgeNode* start = SetOfVertex[vertex2]->firstheadptr; start != nullptr; )
{
if (start->tail < vertex1)
{
p = start;
start = start->sameheadptr;
}
else
{
if (p == nullptr)
{
p = SetOfVertex[vertex2]->firstheadptr;
SetOfVertex[vertex2]->firstheadptr = pre;
pre->sameheadptr = p;
}
else
{
p->sameheadptr = pre;
pre->sameheadptr = start;
}
return true;
}
}
p->sameheadptr = pre;
return true;
}
template <typename V, typename E>
Graph<V, E>* Graph<V, E>::merge(Graph<V, E>& Bemerged, bool copyOrNot/*trueĿĶ,fasle,ֱӺϲĿĶ*/)
{
Graph<V, E>* temp1 = nullptr;
typename vector<GraphVertexNode*>::size_type Ca1 = 0;
if (copyOrNot)
{
temp1 = Copy();
Ca1 = temp1->SetOfVertex.size();
}
else
{
Ca1 = SetOfVertex.size();
}
{
Graph<V, E>* temp2 = Bemerged.Copy();
for (typename vector<GraphVertexNode*>::size_type p = 0; p < temp2->SetOfVertex.size(); ++p)
{
if (copyOrNot)
{
temp1->SetOfVertex.push_back(temp2->SetOfVertex[p]);
}
else
{
SetOfVertex.push_back(temp2->SetOfVertex[p]);
}
}
while (temp2->SetOfVertex.empty() == false)
{
temp2->SetOfVertex.pop_back();
}
delete temp2;
}
for (typename vector<GraphVertexNode*>::size_type p = Ca1; ; ++p)
{
Graph<V, E>::GraphEdgeNode* q = nullptr;
if (copyOrNot)
{
if (p >= temp1->SetOfVertex.size())
break;
temp1->SetOfVertex[p]->number = p;
q = temp1->SetOfVertex[p]->firsttailptr;
}
else
{
if (p >= SetOfVertex.size())
break;
SetOfVertex[p]->number = p;
q = SetOfVertex[p]->firsttailptr;
}
for (; q != nullptr; q = q->sametailptr)
{
q->head = q->head + Ca1;
q->tail = q->tail + Ca1;
}
}
if (copyOrNot)
return temp1;
else
return nullptr;
} | true |
6635fa7a680e630da3cb608a0b9691d18944d363 | C++ | przemek29/C_plus_plus | /Chapter 10 - Class/10_13/10_13.cpp | UTF-8 | 399 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "person.h"
void presentation(person &someone);
int main()
{
person composer, author;
composer.remember("Fryderyk Chopin", 36);
author.remember("Marcel Proust", 34);
presentation(composer);
presentation(author);
}
void presentation(person &someone)
{
cout << "I have the honor to present you, \nHere in person: ";
someone.print();
}
| true |
4fd2861c817b5b86120fc96df3cfe5652318acdb | C++ | icare4mm/mastermind-strategy | /lib/Compare.cpp | UTF-8 | 17,287 | 2.828125 | 3 | [
"MIT"
] | permissive | ///////////////////////////////////////////////////////////////////////////
// Codeword comparison routines.
#include <cassert>
#include <utility>
#include "util/simd.hpp"
#include "util/intrinsic.hpp"
#include "Algorithm.hpp"
//#include "util/call_counter.hpp"
/// Define the following macro to 1 to enable a specialized comparison routine
/// when one of the codewords (specifically, the secret) contains no repeated
/// colors. This marginally improves the performance at the cost of increased
/// code complexity and memory footprint. Therefore, it is not enabled by
/// default.
#define SPECIALIZE_NONREPEATED_GENERIC 0
namespace Mastermind {
/// Codeword comparer for generic codewords (with or without repetition).
class GenericComparer
{
// Lookup table that converts (nA<<4|nAB) -> feedback.
// Both nA and nAB must be >= 0 and <= 15.
struct lookup_table_t
{
Feedback table[0x100];
lookup_table_t()
{
for (int i = 0; i < 0x100; i++)
{
int nA = i >> 4;
int nAB = i & 0xF;
table[i] = Feedback(nA, nAB - nA);
}
}
};
static const lookup_table_t lookup;
typedef util::simd::simd_t<uint8_t,16> simd_t;
simd_t secret;
simd_t secret_colors;
public:
GenericComparer(const Codeword &_secret)
: secret(*reinterpret_cast<const simd_t *>(&_secret))
{
// Change 0xff in secret to 0x0f.
secret &= (uint8_t)0x0f;
// Cache the color part of the secret.
secret_colors = util::simd::keep_right<MM_MAX_COLORS>(secret);
}
/**
* In VC++, it's extremely subtle how the C++ code will compile into
* assembly. Effectively equivalent code may lead to significantly
* different performance. Usually the performance difference comes
* from redundant memory reads/writes. Hence it's always a good idea
* to examine the ASM after compiling the code.
*
* The following C++ code is hand-crafted so that the generated ASM
* by VC++ is almost optimal. The generated instructions for a loop
* that compares codewords and increment the frequencies are:
*
* movdqa xmm0,xmmword ptr [r10] ; xmm0 := *guesses
* add r10,10h ; ++guesses
* movdqa xmm1,xmm0
* pminub xmm0,xmm3
* pcmpeqb xmm1,xmm4
* psadbw xmm0,xmm5
* pand xmm1,xmm2
* pextrw edx,xmm0,4
* pextrw eax,xmm0,0
* add edx,eax
* psadbw xmm1,xmm5
* pextrw ecx,xmm1,4
* mov ecx,ecx ; *
* or rdx,rcx
* movsx rax,byte ptr [rdx+r11] ; rax := lookup_table[mask]
* inc dword ptr [r9+rax*4] ; ++freq[Feedback]
* dec r8 ; --count
* jne ... ; continue loop
*
* The instruction marked with a (*) is redundant and would have been
* eliminated if the intrinsic function returns @c size_t instead of
* @c int.
*/
Feedback operator () (const Codeword &_guess) const
{
// Create mask for use later.
const simd_t mask_pegs = util::simd::fill_left<MM_MAX_PEGS>((uint8_t)0x10);
// const simd_t mask_colors = util::simd::fill_right<MM_MAX_COLORS>((uint8_t)0xff);
const simd_t guess(*reinterpret_cast<const simd_t *>(&_guess));
// Compute nA.
// It turns out that there's a significant (20%) performance hit if
// <code>sum<8,16>(...)</code> is changed to <code>sum<0,16>(...)</code>
// In the latter case, VC++ generates an extra (redundant) memory read.
// Therefore we try to be save every instruction possible.
unsigned int nA_shifted = util::simd::sum(util::simd::make_slice
<MM_MAX_PEGS <= 8 ? 8 : 0, 16>((guess == secret) & mask_pegs));
// Compute nAB.
unsigned int nAB = util::simd::sum(util::simd::make_slice
<0, MM_MAX_COLORS <= 8 ? 8 : 16> (min(guess, secret_colors)));
Feedback nAnB = lookup.table[nA_shifted|nAB];
return nAnB;
}
};
const GenericComparer::lookup_table_t GenericComparer::lookup;
/// Specialized codeword comparer for codewords without repetition.
class NoRepeatComparer
{
// Pre-computed table that converts a comparison bitmask of
// non-repeatable codewords into a feedback.
//
// Note that the performance impact of the table lookup can be subtle.
// The VC++ compiler tends to generate a MOVZX (32-bit) or MOVSXD (64-bit)
// instruction if the integer sizes do not match. What's worse, because
// an SSE2 intrinsic function in use returns an <code>int</code>, there
// is no way to get rid of the MOVSXD instruction which deteriates
// performance by 30%!
//
// Hence, the best we could do is probably to compile under 32-bit, and
// access the table directly.
struct lookup_table_t
{
Feedback table[0x10000];
lookup_table_t()
{
for (int i = 0; i < 0x10000; i++)
{
int nA = util::intrinsic::pop_count((unsigned short)(i >> MM_MAX_COLORS));
int nAB = util::intrinsic::pop_count((unsigned short)(i & ((1<<MM_MAX_COLORS)-1)));
table[i] = Feedback(nA, nAB - nA);
}
}
};
static const lookup_table_t lookup;
typedef util::simd::simd_t<int8_t,16> simd_t;
simd_t secret;
public:
NoRepeatComparer(const Codeword &_secret)
: secret(*reinterpret_cast<const simd_t *>(&_secret))
{
// Change 0xFF in secret to 0x0F
secret &= (int8_t)0x0f;
// Set zero counters in secret to 0xFF, so that if a counter in the
// guess and secret are both zero, they won't compare equal.
secret |= util::simd::keep_right<MM_MAX_COLORS>(secret == simd_t::zero());
}
/**
* The following code translates into the following ASM:
*
* movdqa xmm0,xmmword ptr [rbx] ; xmm0 := *guesses
* movdqa xmm1,xmm2 ; xmm1 := this->secret
* lea rbx,[rbx+10h] ; ++guesses
* pcmpeqb xmm1,xmm0
* pmovmskb eax,xmm1
* movsxd rcx,eax ; *
* movsx rax,byte ptr [rcx+rdx] ; rax := lookup_table[mask]
* inc dword ptr [rbp+rax*4] ; ++freq[Feedback]
* dec rsi ; --count
* jne ... ; continue loop
*
* Note that we could save the instruction (*) if the intrinsic
* function for @c pmovmskb has return type int64 instead of int.
*/
Feedback operator () (const Codeword &guess) const
{
return lookup.table
[ util::simd::byte_mask(*reinterpret_cast<const simd_t *>(&guess) == secret) ];
}
};
const NoRepeatComparer::lookup_table_t NoRepeatComparer::lookup;
/// Function object that appends a feedback to a feedback list.
class FeedbackUpdater
{
Feedback * feedbacks;
public:
explicit FeedbackUpdater(Feedback *fbs) : feedbacks(fbs) { }
void operator () (const Feedback &fb)
{
*(feedbacks++) = fb;
}
};
/// Function object that increments the frequency statistic of a feedback.
class FrequencyUpdater
{
unsigned int * freq;
public:
// We do not zero the memory here. It must be initialized by the caller.
explicit FrequencyUpdater(unsigned int *_freq) : freq(_freq) { }
void operator () (const Feedback &fb)
{
++freq[fb.value()];
}
};
/// Function object that invokes two functions.
template <class T1, class T2>
class CompositeUpdater
{
T1 u1;
T2 u2;
public:
CompositeUpdater(T1 updater1, T2 updater2)
: u1(updater1), u2(updater2) { }
void operator () (const Feedback &fb)
{
u1(fb);
u2(fb);
}
};
/// Compares a secret to a list of codewords using @c Comparer, and
/// processes each feedback using @c Updater.
template <class Comparer, class Updater>
static inline void compare_codewords(
const Codeword &secret,
const Codeword *_guesses,
size_t _count,
Updater _update)
{
// The following redundant copy is to make VC++ happy treat the value
// of @c _update as constant in the loop.
Updater update(_update);
Comparer compare(secret);
size_t count = _count;
const Codeword *guesses = _guesses;
for (; count > 0; --count)
{
Feedback nAnB = compare(*guesses++);
update(nAnB);
}
}
/// Compares a secret to a list of codewords using @c Comparer, and
/// update the feedback and/or frequencies.
template <class Comparer>
static inline void compare_codewords(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result,
unsigned int *freq)
{
if (freq && result)
{
FeedbackUpdater u1(result);
FrequencyUpdater u2(freq);
CompositeUpdater<FeedbackUpdater,FrequencyUpdater> update(u1,u2);
compare_codewords<Comparer>(secret, guesses, count, update);
}
else if (freq)
{
FrequencyUpdater update(freq);
compare_codewords<Comparer>(secret, guesses, count, update);
}
else if (result)
{
FeedbackUpdater update(result);
compare_codewords<Comparer>(secret, guesses, count, update);
}
}
#if 0
void compare_codewords(
const Rules &rules,
const Codeword &secret,
const Codeword *guesses,
size_t count,
unsigned int *freq)
{
FrequencyUpdater update(freq);
if (rules.repeatable())
compare_codewords<GenericComparer>(secret, guesses, count, update);
else
compare_codewords<NoRepeatComparer>(secret, guesses, count, update);
}
#endif
#if SPECIALIZE_NONREPEATED_GENERIC
/// Specialized codeword comparer for generic codewords where the secret
/// doesn't contain repeated colors.
class SpecializedComparer
{
// Pre-computed table that converts a comparison bitmask into a feedback.
struct lookup_table_t
{
Feedback table[0x10000];
lookup_table_t()
{
for (int i = 0; i < 0x10000; i++)
{
int nA = util::intrinsic::pop_count((unsigned short)(i >> MM_MAX_COLORS));
int nAB = util::intrinsic::pop_count((unsigned short)(i & ((1<<MM_MAX_COLORS)-1)));
table[i] = Feedback(nA, nAB - nA);
}
}
};
static const lookup_table_t lookup;
typedef util::simd::simd_t<uint8_t,16> simd_t;
simd_t secret;
simd_t barrier;
static const simd_t _barrier;
public:
SpecializedComparer(const Codeword &_secret)
: secret(_secret.value()), barrier(_barrier)
{
// Change 0xFF in secret to 0x0F
secret &= (uint8_t)0x0f;
// Set zero counters in secret to 0xFF, so that if a counter in the
// guess and secret are both zero, they won't compare equal.
secret |= util::simd::keep_right<MM_MAX_COLORS>(secret == simd_t::zero());
// Make a copy of barrier so that VC++ will not read the static memory
// in a tight loop every time.
}
/**
* The following code translates into the following ASM:
*
* movdqa xmm0,xmmword ptr [rdx] ; xmm0 := *guesses
* add rdx,10h ; ++guesses
* pminub xmm0,xmm1 ; xmm0 := min(xmm0, barrier)
* pcmpeqb xmm0,xmm2 ; xmm0 := cmp(xmm0, secret)
* pmovmskb eax,xmm0 ; eax := movemask(xmm0)
* movsxd rcx,eax ; *
* movsx rax,byte ptr [rcx+r10] ; feedback := map(eax)
* inc dword ptr [r11+rax*4] ; ++freq[feedback]
* dec r8 ; --count
* jne ... ; continue loop
*
* Note that we could save the instruction (*) if the intrinsic function
* for @c pmovmskb had return type int64 instead of int.
*/
Feedback operator () (const Codeword &guess) const
{
// Create a mask to convert color counters greater than one to one.
// register simd_t barrier = _barrier;
// Create a mask with the equal bytes in (augmented) secret and
// (augmented) guess set to 0xFF.
simd_t mask = util::simd::min(simd_t(guess.value()), barrier) == secret;
// Maps the mask to a feedback value and return.
return lookup.table[ util::simd::byte_mask(mask) ];
}
};
const SpecializedComparer::simd_t SpecializedComparer::_barrier =
util::simd::fill_left<MM_MAX_PEGS>(0xFF) |
util::simd::fill_right<MM_MAX_COLORS>(0x01);
const SpecializedComparer::lookup_table_t SpecializedComparer::lookup;
#endif
#if 0
static void compare_codewords_generic(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result,
unsigned int *freq)
{
#if SPECIALIZE_NONREPEATED_GENERIC
if (secret.has_repetition())
return compare_codewords<GenericComparer>(secret, guesses, count, result, freq);
else
return compare_codewords<SpecializedComparer>(secret, guesses, count, result, freq);
#else
return compare_codewords<GenericComparer>(secret, guesses, count, result, freq);
#endif
}
static void compare_codewords_norepeat(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result,
unsigned int *freq)
{
return compare_codewords<NoRepeatComparer>(secret, guesses, count, result, freq);
}
#endif
#if 0
/// [Test] Codeword comparer for generic codewords where the secret doesn't
/// contain repetitive colors.
class TestComparer
{
// Pre-computed table that converts a comparison bitmask into a feedback.
struct lookup_table_t
{
Feedback table[0x10000];
lookup_table_t()
{
for (int i = 0; i < 0x10000; i++)
{
int nA = util::intrinsic::pop_count((unsigned short)(i >> MM_MAX_COLORS));
int nAB = util::intrinsic::pop_count((unsigned short)(i & ((1<<MM_MAX_COLORS)-1)));
table[i] = Feedback(nA, nAB - nA);
}
}
};
static const lookup_table_t lookup;
typedef util::simd::simd_t<uint8_t,16> simd_t;
simd_t secret;
public:
TestComparer(const Codeword &_secret)
: secret(_secret.value())
{
// Change 0xFF in secret to 0x0F
secret &= (uint8_t)0x0f;
// Set zero counters in secret to 0xFF, so that if a counter in the
// guess and secret are both zero, they won't compare equal.
secret |= util::simd::keep_right<MM_MAX_COLORS>(secret == simd_t::zero());
}
/**
* The following code translates into the following ASM:
*
* movdqa xmm0,xmmword ptr [rdx] ; xmm0 := *guesses
* add rdx,10h ; ++guesses
* pminub xmm0,xmm1 ; xmm0 := min(xmm0, barrier)
* pcmpeqb xmm0,xmm2 ; xmm0 := cmp(xmm0, secret)
* pmovmskb eax,xmm0 ; eax := movemask(xmm0)
* movsxd rcx,eax ; *
* movsx rax,byte ptr [rcx+r10] ; feedback := map(eax)
* inc dword ptr [r11+rax*4] ; ++freq[feedback]
* dec r8 ; --count
* jne ... ; continue loop
*
* Note that we could save the instruction (*) if the intrinsic function
* for @c pmovmskb had return type int64 instead of int.
*/
Feedback operator () (const Codeword &guess) const
{
// Create a mask to convert color counters greater than one to one.
const simd_t barrier =
util::simd::fill_left<MM_MAX_COLORS>(0xFF) |
util::simd::fill_right<MM_MAX_COLORS>(0x01);
// Create a mask with the equal bytes in (augmented) secret and
// (augmented) guess set to 0xFF.
simd_t mask = util::simd::min(simd_t(guess.value()), barrier) == secret;
// Maps the mask to a feedback value and return.
return lookup.table[ util::simd::byte_mask(mask) ];
}
};
const TestComparer::lookup_table_t TestComparer::lookup;
static void compare_codewords_test(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result,
unsigned int *freq)
{
if (secret.has_repetition())
return compare_codewords<GenericComparer>(secret, guesses, count, result, freq);
else
return compare_codewords<TestComparer>(secret, guesses, count, result, freq);
}
REGISTER_ROUTINE(ComparisonRoutine, "test", compare_codewords_test)
#endif
/// Compares generic codewords and returns feedbacks.
void CompareGeneric1(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result)
{
FeedbackUpdater update(result);
compare_codewords<GenericComparer>(secret, guesses, count, update);
}
/// Compares generic codewords and returns frequencies.
void CompareGeneric2(
const Codeword &secret,
const Codeword *guesses,
size_t count,
unsigned int *freq)
{
FrequencyUpdater update(freq);
compare_codewords<GenericComparer>(secret, guesses, count, update);
}
/// Compares generic codewords and returns feedbacks and frequencies.
void CompareGeneric3(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result,
unsigned int *freq)
{
FeedbackUpdater u1(result);
FrequencyUpdater u2(freq);
CompositeUpdater<FeedbackUpdater,FrequencyUpdater> update(u1,u2);
compare_codewords<GenericComparer>(secret, guesses, count, update);
}
/// Compares norepeat codewords and returns feedbacks.
void CompareNorepeat1(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result)
{
FeedbackUpdater update(result);
compare_codewords<NoRepeatComparer>(secret, guesses, count, update);
}
/// Compares norepeat codewords and returns frequencies.
void CompareNorepeat2(
const Codeword &secret,
const Codeword *guesses,
size_t count,
unsigned int *freq)
{
FrequencyUpdater update(freq);
compare_codewords<NoRepeatComparer>(secret, guesses, count, update);
}
/// Compares norepeat codewords and returns feedbacks and frequencies.
void CompareNorepeat3(
const Codeword &secret,
const Codeword *guesses,
size_t count,
Feedback *result,
unsigned int *freq)
{
FeedbackUpdater u1(result);
FrequencyUpdater u2(freq);
CompositeUpdater<FeedbackUpdater,FrequencyUpdater> update(u1,u2);
compare_codewords<NoRepeatComparer>(secret, guesses, count, update);
}
} // namespace Mastermind
| true |
a4e789e8638eaf3dda31737ad5c165bff024b3cd | C++ | fastpath/LittleIrritations | /Polygon.h | UTF-8 | 689 | 2.796875 | 3 | [] | no_license | #pragma once
#include <vector>
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics.hpp>
#include <boost/shared_ptr.hpp>
#include <cmath>
class Polygon;
typedef boost::shared_ptr<Polygon> PolygonPtr;
class Polygon
{
public:
Polygon(void);
~Polygon(void);
void addPoint(float p_x, float p_y);
void addPoint(sf::Vector2f& p_point);
bool isIn(float p_x, float p_y);
bool isIn(sf::Vector2f& p_point);
bool isIn(sf::Vector2f& p_start, sf::Vector2f& p_end);
void draw(boost::shared_ptr<sf::RenderWindow> p_app) const;
unsigned int GetPointCount() const;
sf::Vector2f GetPoint(unsigned int index) const;
private:
std::vector<boost::shared_ptr<sf::Vector2f>> m_points;
};
| true |
8fd327a7d78d3cfcb74d6c9b542ec76564df077d | C++ | kbc15gc/game | /game/Decide/Decide/GameObject/History/Chip.h | SHIFT_JIS | 1,494 | 2.59375 | 3 | [] | no_license | /**
* `bvNX̒`.
*/
#pragma once
#include "fbEngine\_Object\_GameObject\GameObject.h"
#include "fbEngine\_Object\_GameObject\SoundSource.h"
#include "HistoryInfo.h"
class Player;
class HistoryMenuSelect;
static const float ChipTimer = 4.0f;
/**
* `bvNX.
* ĵ.
*/
class Chip : public GameObject
{
public:
/**
* RXgN^.
*/
Chip(const char* name) :
GameObject(name)
{
}
/**
* fXgN^.
*/
~Chip()
{
}
/**
* RXgN^̏.
*/
void Awake()override;
/**
* .
*/
void Start()override;
/**
* XV.
*/
void Update()override;
/*
* `.
*/
void Render()override;
/**
* `bvIDݒ.
*/
void SetChipID(ChipID chipID);
/**
* Ghbṽ`bvIDݒ.
*/
void SetDropChipID(ChipID chipID, const Vector3& pos);
/**
* 擾ł܂ł̎Ԃݒ.
*/
inline void SetGetTime(float time)
{
_GetTime = time;
}
private:
/**
* nʂɍ킹.
*/
void _FitGround();
private:
/** `bvID. */
ChipID _ChipID;
/** vC[̃|C^. */
Player* _Player = nullptr;
/** TEh̃|C^. */
SoundSource* _SE = nullptr;
//f
SkinModel* _Model = nullptr;
//}eA
Material* _Material = nullptr;
//擾ł悤ɂȂ܂ł̎
float _GetTime;
//擾ł悤ɂȂ܂ł̎Ԃv
float _GetTimer;
}; | true |
28bbf9545c03cb83180cf3f274bec70a1b24244f | C++ | ilijabc/AngryGL | /source/frameworks/glplus/GLView.h | UTF-8 | 1,468 | 2.53125 | 3 | [] | no_license | #ifndef GLVIEW_H
#define GLVIEW_H
#include "glplus_private.h"
class GLView
{
public:
enum DrawingMode
{
Quads = 0,
Triangles,
Lines,
LineLoop
};
private:
class IVertex
{
public:
IVertex* normal(float x, float y, float z);
IVertex* color(unsigned int rgba);
IVertex* texcoord(float u, float v);
friend class GLView;
};
public:
GLView();
virtual ~GLView();
void setup();
void beginGui(int width = 0, int height = 0);
void endGui();
void beginScene2D(float left, float right, float bottom, float top);
float beginScene2DWide(float height);
void endScene2D();
void beginScene3D();
void endScene3D();
void drawRect(float x1, float y1, float x2, float y2);
void drawCube(float sx, float sy, float sz, float *color_array = 0);
void setSize(int width, int height);
int getWidth() const { return mWidth; }
int getHeight() const { return mHeight; }
//void renderCube(float x, float y, float z);
//void pushTexture(GLTexture *tex);
//void popTexture();
//void multMatrix(const matrix4f& mat);
//void setColor(Color c);
//void beginPicking(int x, int y, float sense);
//int endPicking();
vector3f pickPoint3D(int x, int y);
vector2f pickPoint2D(float x, float y, float z);
// intermetiate mode
void begin(DrawingMode mode);
IVertex* vertex(float x, float y, float z);
void end();
private:
float mPerspectiveNear;
float mPerspectiveFar;
float mPerspectiveFOV;
int mWidth;
int mHeight;
};
#endif //GLVIEW_H
| true |
a40da0ea4bb09ed79d922689594c7980f561f3be | C++ | oliffur/learning | /Exercises/MinJumps.cpp | UTF-8 | 1,804 | 4.09375 | 4 | [] | no_license | /* given an array of non-negative integers, you are initially positioned at the
* first index of the array; each element in the array represents your maximum
* jump length at that position
*
*/
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int findMinJumps(vector<int> jumpArray){
// save the size of the array
int arrSize = jumpArray.size();
// if the array is empty, return 0
if (arrSize == 0) return 0;
// keeps track of the min jumps required to get to each index position
vector<int> minJumpArray(arrSize, -1);
// initiate the first number in this array at 0
minJumpArray[0] = 0;
// loop through the array
for (int i = 0; i<arrSize; i++){
// if we cannot reach this point, return -1
if (minJumpArray[i] == -1){
return -1;
}
else{
// update min jump table:
//
// start at the farthest jump possible using current cell, but cap
// it at the max index; loop down until you hit i again
//
// update all -1s (meaning indices that haven't been filled out yet)
// to 1 more than the current minJumpArray value
for (int j = min(i+jumpArray[i],arrSize -1); j>i; j--){
// if we hit a cell that has already been filled out, no need
// to go further; break the loop
if (minJumpArray[j] != -1){
break;
}
else{
minJumpArray[j] = minJumpArray[i] + 1;
}
}
}
}
return minJumpArray[arrSize-1];
}
int main(){
vector<int> jumpArray = {2,3,1,1,4,1,2,3,4,2,3,1,1,1,1,1,1,1,1};
cout << findMinJumps(jumpArray) << endl;
return 0;
}
| true |
a21c2c22171ac050704fc874a9d31ad8c17d8888 | C++ | Devilsider/Tencent_Cloud_Backup | /20190521/zuoye/cowString.cc | UTF-8 | 3,932 | 3.453125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
using std::cout;
using std::endl;
class CowString{
public:
CowString();
CowString(const char *);
CowString(const CowString &rhs);
CowString &operator=(const CowString &rhs);
~CowString();
const char *c_str(){
return _pstr;
}
int size()const{
return strlen(_pstr);
}
int refcount(){
return *((int *)(_pstr-4));
}
char &operator[](int idx);
friend std::ostream &operator<<(std::ostream &os,const CowString &rhs);
private:
void initRefcount(){
*((int *)(_pstr-4))=1;
}
void increaseRefcount(){
++*((int *)(_pstr-4));
}
void decreaseRefcount(){
--*((int *)(_pstr-4));
}
void release(){
decreaseRefcount();
if(0==refcount()){
delete [](_pstr-4);
cout<<">>delete _pstr"<<endl;
}
}
private:
char *_pstr;
};
CowString::CowString()
:_pstr(new char[5]()+4)
{
cout<<"CowString()"<<endl;
initRefcount();
}
CowString::CowString(const char * str)
:_pstr(new char[5+strlen(str)]()+4)
{
initRefcount();
cout<<"CowString(const char *)"<<endl;
strcpy(_pstr,str);
}
CowString::CowString(const CowString &rhs)
:_pstr(new char[5+strlen(rhs._pstr)]()+4)
{
initRefcount();
cout<<"CowString(const CowString &)"<<endl;
strcpy(_pstr,rhs._pstr);
}
CowString & CowString::operator=(const CowString &rhs){
if(this!=&rhs){
release();
_pstr=rhs._pstr;
increaseRefcount();
}
return *this;
}
CowString::~CowString(){
release();
}
std::ostream &operator<<(std::ostream &os,const CowString &rhs){
os<<rhs._pstr;
return os;
}
char & CowString::operator[](int idx){
cout<<"CowString::operator[]"<<endl;
if(idx>=0&&idx<size()){
if(refcount()>1){
decreaseRefcount();
char *ptemp=new char[5+strlen(_pstr)]()+4;
strcpy(ptemp,_pstr);
_pstr=ptemp;
initRefcount();
}
return _pstr[idx];
}
else {
static char nullchar='\0';
cout<<"pointer crossing"<<endl;
return nullchar;
}
}
int main()
{
CowString s0;
cout << "s0 = " << s0 << endl;
CowString s1("hello,world");
CowString s2(s1);
CowString s3("shenzhen");
s3[0] = 'S';//refcount = 1
s3 = s2;
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
printf("s1's address: %p\n", s1.c_str());
printf("s2's address: %p\n", s2.c_str());
printf("s3's address: %p\n", s3.c_str());
cout << "s1's refcount() = " << s1.refcount() << endl;
cout << "s2's refcount() = " << s2.refcount() << endl;
cout << "s3's refcount() = " << s3.refcount() << endl;
cout << endl << ">>> 执行s1[0] = 'x' 之后:" << endl;
s1[0] = 'x';
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
printf("s1's address: %p\n", s1.c_str());
printf("s2's address: %p\n", s2.c_str());
printf("s3's address: %p\n", s3.c_str());
cout << "s1's refcount() = " << s1.refcount() << endl;
cout << "s2's refcount() = " << s2.refcount() << endl;
cout << "s3's refcount() = " << s3.refcount() << endl;
cout << endl << ">>> 执行 cout << s2[0] << endl 之后:" << endl;
cout << "s2[0] = " << s2[0] << endl;// 在这里不应该进行深拷贝
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
printf("s1's address: %p\n", s1.c_str());
printf("s2's address: %p\n", s2.c_str());
printf("s3's address: %p\n", s3.c_str());
cout << "s1's refcount() = " << s1.refcount() << endl;
cout << "s2's refcount() = " << s2.refcount() << endl;
cout << "s3's refcount() = " << s3.refcount() << endl;
return 0;
}
| true |
92561d6d48ceb2a98ded5c73be07cc61a2a5cd08 | C++ | rashedcs/Data-Structure-and-Algorithm | /Graph/BFS GRID.cpp | UTF-8 | 2,007 | 2.734375 | 3 | [] | no_license | //Codechef : https://www.codechef.com/status/CDZ14C,rashedcs
#include<bits/stdc++.h>
using namespace std;
int arr[20][20];
int vis[20][20];
int dist[20][20];
int dr[]={1,0,-1,0};
int dc[]={0,1,0,-1};
int n, m, ans;
int safe(int x,int y)
{
return x>=0 && y>=0 && x<n && y<m;
}
void bfs(int sx, int sy, int dx, int dy)
{
ans = INT_MAX;
queue< pair<int,int> > q;
q.push(make_pair(sx,sy));
vis[sx][sy]=1;
dist[sx][sy]=0;
while(!q.empty())
{
int r=q.front().first;
int c=q.front().second;
q.pop();
if(arr[r][c]==0 )
{
// ans = -1 //No need to initialize ans = -1 because it at first initialize INT_MIN
break;
}
if(dx==r && dy==c)
{
ans = 1; //If destination is found then ans=true, break;
break;
}
for(int i=0; i<4; i++)
{
int a = r + dr[i];
int b = c + dc[i];
if(safe(a,b) && !vis[a][b] && arr[a][b])
{
q.push(make_pair(a,b));
dist[a][b] = dist[r][c]+1;
vis[a][b]=1;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
int tc, dx, dy;
cin>>tc;
while(tc--)
{
cin>>n>>m;
memset(arr,0,sizeof(arr));
memset(vis, 0, sizeof(vis));
memset(dist, 0, sizeof(dist));
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin>>arr[i][j];
}
}
cin>>dx>>dy;
bfs(0,0,dx,dy);
if(ans==1) // If destination node is possible
cout<<dist[dx][dy]<<endl;
else // Otherwise -1
cout<<"-1"<<endl;
}
return 0;
}
| true |
669b6be0935d0c9ed4fc6515eea40da679527982 | C++ | starcatneko/TeamProject | /Android/Android1/Android1.NativeActivity/LoadMane.h | UTF-8 | 852 | 2.609375 | 3 | [] | no_license | #pragma once
#include "Typedef.h"
#include <map>
#include <vector>
#include <string>
class LoadMane
{
public:
// デストラクタ
~LoadMane();
// インスタンス変数の取得
static LoadMane* Get(void) {
return instance;
}
// インスタンス化
static void Create(void);
// 破棄
static void Destroy(void);
// 画像の読み込み
int Load(std::string fileName);
// サウンドの読み込み
int LoadSound(std::string fileName);
// CSV読み込み
std::vector<int>LoadCsv(std::string fileName);
private:
// コンストラクタ
LoadMane();
// クリア
void Clear(void);
// インスタンス変数
static LoadMane* instance;
// 画像データ
std::map<std::string, int>data;
// マスクデータ
std::map<std::string, int>mask;
// サウンドデータ
std::map<std::string, int>sound;
};
| true |
0fca9aa25dd17f5a37b32fdb8d676544d758fc6e | C++ | alecnunn/bookresources | /GameDevelopment/Programming Role Playing Games with DirectX (Second Edition)/BookCode/Chap12/Chars/Chars.cpp | UTF-8 | 67,672 | 2.609375 | 3 | [] | no_license | #include "Core_Global.h"
#include "Frustum.h"
#include "MCL.h"
#include "MIL.h"
#include "MSL.h"
#include "Chars.h"
#include "Spell.h"
cCharacterController::cCharacterController()
{
m_Graphics = NULL; // Clear cGraphics pointer
m_Font = NULL; // Clear cFont pointer
m_Frustum = NULL; // Clear frustum pointer
m_MIL = NULL; // Clear MIL pointer
m_MSL = NULL; // Clear MSL pointer
m_CharacterParent = NULL; // Clear character list
m_NumCharacters = 0;
m_DefinitionFile[0] = 0; // Clear definition filename
m_NumMeshes = 0; // Clear mesh data
m_Meshes = NULL;
m_TexturePath[0] = 0;
m_NumAnimations = 0; // Clear animation data
m_Animations = NULL;
m_SpellController = NULL; // Clear spell controller
}
cCharacterController::~cCharacterController()
{
Shutdown();
}
BOOL cCharacterController::Init( \
cGraphics *Graphics, \
cFont *Font, char *DefinitionFile, \
sItem *MIL, sSpell *MSL, \
long NumCharacterMeshes, \
char **MeshNames, \
char *MeshPath, char *TexturePath, \
long NumAnimations, \
sCharAnimationInfo *Anims, \
cSpellController *SpellController)
{
long i;
Free(); // Free prior init
// Get parent graphics object and error checking
if((m_Graphics = Graphics) == NULL || MeshNames == NULL || \
DefinitionFile == NULL)
return FALSE;
// Get font object pointer
m_Font = Font;
// Copy definition file name
strcpy(m_DefinitionFile, DefinitionFile);
// Store MIL and MSL pointer
m_MIL = MIL;
m_MSL = MSL;
// Copy over mesh path (or set default)
if(MeshPath != NULL)
strcpy(m_MeshPath, MeshPath);
else
strcpy(m_MeshPath, ".\\");
// Copy over texture path (or set default)
if(TexturePath != NULL)
strcpy(m_TexturePath, TexturePath);
else
strcpy(m_TexturePath, ".\\");
// Get mesh names
if((m_NumMeshes = NumCharacterMeshes)) {
m_Meshes = new sCharacterMeshList[NumCharacterMeshes]();
for(i=0;i<m_NumMeshes;i++)
strcpy(m_Meshes[i].Filename, MeshNames[i]);
}
// Get animation data
if((m_NumAnimations = NumAnimations)) {
m_Animations = new sCharAnimationInfo[m_NumAnimations]();
for(i=0;i<m_NumAnimations;i++) {
memcpy(&m_Animations[i], &Anims[i], \
sizeof(sCharAnimationInfo));
}
}
// Store spell controller pointer
m_SpellController = SpellController;
return TRUE;
}
BOOL cCharacterController::Shutdown()
{
Free();
// Release mesh list
delete [] m_Meshes;
m_Meshes = NULL;
m_NumMeshes = 0;
// Release animation data
m_NumAnimations = 0;
delete [] m_Animations;
m_Animations = NULL;
// Clear graphics object
m_Graphics = NULL;
// Clear paths
m_DefinitionFile[0] = 0;
m_MeshPath[0] = 0;
m_TexturePath[0] = 0;
// Clear spell controller
m_SpellController = NULL;
return TRUE;
}
BOOL cCharacterController::Free()
{
// Release character structures
delete m_CharacterParent;
m_CharacterParent = NULL;
m_NumCharacters = 0;
return TRUE;
}
BOOL cCharacterController::Add( \
long IDNum, long Definition, \
long Type, long AI, \
float XPos, float YPos, float ZPos, \
float Direction)
{
sCharacter *CharPtr;
FILE *fp;
char Path[MAX_PATH];
long i;
// Error checking
if(m_Graphics==NULL || m_Meshes==NULL || !m_DefinitionFile[0])
return FALSE;
// Allocate a new structure
CharPtr = new sCharacter();
// Assign data
CharPtr->Definition = Definition;
CharPtr->ID = IDNum;
CharPtr->Type = Type;
CharPtr->AI = AI;
CharPtr->XPos = XPos;
CharPtr->YPos = YPos;
CharPtr->ZPos = ZPos;
CharPtr->Direction = Direction;
CharPtr->Enabled = TRUE;
// Set a random charge amount
CharPtr->Charge = (float)(rand() % 101);
// Load character definition
if((fp=fopen(m_DefinitionFile, "rb"))==NULL) {
delete CharPtr;
return FALSE;
}
fseek(fp, sizeof(sCharacterDefinition)*Definition, SEEK_SET);
fread(&CharPtr->Def, 1, sizeof(sCharacterDefinition), fp);
fclose(fp);
// Load character ICS
if(CharPtr->Def.ItemFilename[0]) {
CharPtr->CharICS = new cCharICS();
CharPtr->CharICS->Load(CharPtr->Def.ItemFilename);
}
// Set character stats
CharPtr->HealthPoints = CharPtr->Def.HealthPoints;
CharPtr->ManaPoints = CharPtr->Def.ManaPoints;
// Load mesh and animation if needed
if(!m_Meshes[CharPtr->Def.MeshNum].Count) {
m_Meshes[CharPtr->Def.MeshNum].Mesh.Load(m_Graphics, \
m_Meshes[CharPtr->Def.MeshNum].Filename, \
m_TexturePath);
m_Meshes[CharPtr->Def.MeshNum].Animation.Load( \
m_Meshes[CharPtr->Def.MeshNum].Filename, \
&m_Meshes[CharPtr->Def.MeshNum].Mesh);
// Set animation loops
if(m_NumAnimations) {
for(i=0;i<m_NumAnimations;i++)
m_Meshes[CharPtr->Def.MeshNum].Animation.SetLoop( \
m_Animations[i].Loop, \
m_Animations[i].Name);
}
}
// Configure graphics object
CharPtr->Object.Create(m_Graphics, \
&m_Meshes[CharPtr->Def.MeshNum].Mesh);
m_Meshes[CharPtr->Def.MeshNum].Count++;
// Load and configure weapon (if any)
if(m_MIL != NULL && CharPtr->Def.Weapon != -1 && \
m_MIL[CharPtr->Def.Weapon].MeshFilename[0]) {
// Build the mesh path
sprintf(Path, "%s%s", m_MeshPath, \
m_MIL[CharPtr->Def.Weapon].MeshFilename);
// Load the weapon mesh
CharPtr->WeaponMesh.Load(m_Graphics, Path, m_TexturePath);
// Create the weapon object
CharPtr->WeaponObject.Create(m_Graphics, \
&CharPtr->WeaponMesh);
// Orient and attach the weapon
CharPtr->WeaponObject.Move(0.0f, 0.0f, 0.0f);
CharPtr->WeaponObject.Rotate(0.0f, 0.0f, 0.0f);
CharPtr->WeaponObject.AttachToObject(&CharPtr->Object, \
"WeaponHand");
}
// Link in to head of list
if(m_CharacterParent != NULL)
m_CharacterParent->Prev = CharPtr;
CharPtr->Next = m_CharacterParent;
m_CharacterParent = CharPtr;
return TRUE;
}
BOOL cCharacterController::Remove(long IDNum)
{
return Remove(GetCharacter(IDNum));
}
BOOL cCharacterController::Remove(sCharacter *Character)
{
// Error checking
if(Character == NULL)
return FALSE;
// Decrease mesh count and release if no more
m_Meshes[Character->Def.MeshNum].Count--;
if(!m_Meshes[Character->Def.MeshNum].Count) {
m_Meshes[Character->Def.MeshNum].Mesh.Free();
m_Meshes[Character->Def.MeshNum].Animation.Free();
}
// Remove from list and free resource
if(Character->Prev != NULL)
Character->Prev->Next = Character->Next;
else
m_CharacterParent = Character->Next;
if(Character->Next != NULL)
Character->Next->Prev = Character->Prev;
if(Character->Prev == NULL && Character->Next == NULL)
m_CharacterParent = NULL;
Character->Prev = Character->Next = NULL;
delete Character;
return TRUE;
}
BOOL cCharacterController::Save(long IDNum, char *Filename)
{
char ICSFilename[MAX_PATH];
sCharacter *CharPtr;
FILE *fp;
// Get pointer to character in list
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Open file
if((fp=fopen(Filename, "wb"))==NULL)
return FALSE;
// Output character data
fwrite(&CharPtr->Def, 1, sizeof(sCharacterDefinition), fp);
fwrite(&CharPtr->HealthPoints, 1, sizeof(long), fp);
fwrite(&CharPtr->ManaPoints, 1, sizeof(long), fp);
fwrite(&CharPtr->Ailments, 1, sizeof(long), fp);
fwrite(&CharPtr->XPos, 1, sizeof(float), fp);
fwrite(&CharPtr->YPos, 1, sizeof(float), fp);
fwrite(&CharPtr->ZPos, 1, sizeof(float), fp);
fwrite(&CharPtr->Direction, 1, sizeof(float), fp);
// Close file
fclose(fp);
// Save inventory
if(CharPtr->CharICS != NULL) {
sprintf(ICSFilename, "ICS%s", Filename);
CharPtr->CharICS->Save(ICSFilename);
}
return TRUE;
}
BOOL cCharacterController::Load(long IDNum, char *Filename)
{
char ICSFilename[MAX_PATH];
sCharacter *CharPtr;
FILE *fp;
// Get pointer to character in list
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Open file
if((fp=fopen(Filename, "rb"))==NULL)
return FALSE;
// Read in character data
fread(&CharPtr->Def, 1, sizeof(sCharacterDefinition), fp);
fread(&CharPtr->HealthPoints, 1, sizeof(long), fp);
fread(&CharPtr->ManaPoints, 1, sizeof(long), fp);
fread(&CharPtr->Ailments, 1, sizeof(long), fp);
fread(&CharPtr->XPos, 1, sizeof(float), fp);
fread(&CharPtr->YPos, 1, sizeof(float), fp);
fread(&CharPtr->ZPos, 1, sizeof(float), fp);
fread(&CharPtr->Direction, 1, sizeof(float), fp);
// Close file
fclose(fp);
// Load inventory
if(CharPtr->CharICS != NULL) {
sprintf(ICSFilename, "ICS%s", Filename);
CharPtr->CharICS->Load(ICSFilename);
}
return TRUE;
}
BOOL cCharacterController::Update(long Elapsed)
{
sCharacter *CharPtr, *NextChar;
float XMove, YMove, ZMove;
static long EffectCounter = 0;
BOOL ToProcess, DeadChar;
// Return success if no characters to update
if((CharPtr = m_CharacterParent) == NULL)
return TRUE;
// Update effect counter
EffectCounter += Elapsed;
// Loop through all characters
while(CharPtr != NULL) {
// Remember next character
NextChar = CharPtr->Next;
// Only update if enabled, not asleep or paralyzed
if(CharPtr->Enabled == TRUE) {
// Update action timer if in use
if(CharPtr->ActionTimer != 0) {
CharPtr->ActionTimer -= Elapsed;
if(CharPtr->ActionTimer < 0)
CharPtr->ActionTimer = 0;
}
// Update text message timer
if(CharPtr->MessageTimer > 0)
CharPtr->MessageTimer -= Elapsed;
// Reset charge counter if attacking, spell, or item
if(CharPtr->Action == CHAR_ATTACK || \
CharPtr->Action == CHAR_SPELL || \
CharPtr->Action == CHAR_ITEM)
CharPtr->Charge = 0.0f;
// Kill character if no health left
if(CharPtr->HealthPoints <= 0 && \
CharPtr->Action != CHAR_DIE) {
SetAction(CharPtr, CHAR_DIE, 2000);
}
// Mark that processing can continue later on
ToProcess = TRUE;
// Mark character as still alive
DeadChar = FALSE;
// Don't allow an update if asleep or paralyzed
if((CharPtr->Ailments & AILMENT_SLEEP) || \
(CharPtr->Ailments & AILMENT_PARALYZE))
ToProcess = FALSE;
// Process non-idle, non-walk actions
if(CharPtr->Action != CHAR_IDLE && \
CharPtr->Action != CHAR_MOVE && \
!CharPtr->ActionTimer) {
switch(CharPtr->Action) {
case CHAR_ATTACK:
// Process attack
if(ToProcess == TRUE)
Attack(CharPtr, CharPtr->Victim);
break;
case CHAR_SPELL:
// Manually cast a spell
if(m_SpellController != NULL && m_MSL != NULL && \
ToProcess == TRUE) {
m_SpellController->Add(CharPtr->SpellNum, \
CharPtr, CharPtr->SpellTarget, \
CharPtr->XPos, \
CharPtr->YPos, \
CharPtr->ZPos, \
CharPtr->TargetX, \
CharPtr->TargetY, \
CharPtr->TargetZ);
}
break;
case CHAR_ITEM:
if(ToProcess == TRUE)
Item(CharPtr, CharPtr, \
CharPtr->ItemNum, CharPtr->CharItem);
break;
case CHAR_DIE:
Death(CharPtr->Attacker, CharPtr);
DeadChar = TRUE; // Mark character as dead
ToProcess = FALSE; // Don't allow updates
break;
}
}
// Clear movement
XMove = YMove = ZMove = 0.0f;
// Only continue if allowed (in case character died)
if(ToProcess == TRUE) {
// Only allow updates if lock/timer not in use
if(CharPtr->Enabled == TRUE && \
!CharPtr->ActionTimer && \
CharPtr->Locked == FALSE) {
// Reset action
CharPtr->Action = CHAR_IDLE;
// Get movement
if(CharPtr->Type == CHAR_PC)
PCUpdate(CharPtr, Elapsed, &XMove, &YMove, &ZMove);
else
CharUpdate(CharPtr, Elapsed, &XMove,&YMove,&ZMove);
// Check for validity of movement (clear if invalid)
if(CheckMove(CharPtr,&XMove,&YMove,&ZMove)==FALSE) {
XMove = YMove = ZMove = 0.0f;
CharPtr->Action = CHAR_IDLE;
}
}
// Process movement of character
ProcessUpdate(CharPtr, XMove, YMove, ZMove);
// Increase action charge of character
CharPtr->Charge += ((float)Elapsed / 1000.0f * \
GetCharge(CharPtr));
if(CharPtr->Charge > 100.0f)
CharPtr->Charge = 100.0f;
}
// Process timed ailments (only on live characters)
if(DeadChar == FALSE && CharPtr->Ailments) {
// Sleeping characters have 4% to wake up
if(CharPtr->Ailments & AILMENT_SLEEP && (rand()%100)<4)
CharPtr->Ailments &= ~AILMENT_SLEEP;
// Paralyzed character have 2% chance to recover
if(CharPtr->Ailments & AILMENT_PARALYZE && \
(rand() % 100) < 2)
CharPtr->Ailments &= ~AILMENT_PARALYZE;
// Posion removes 2 hp every 2 seconds
if(CharPtr->Ailments & AILMENT_POISON && \
EffectCounter >= 4000) {
CharPtr->HealthPoints -= 2;
SetMessage(CharPtr, "Poison -2 HP", 500, \
D3DCOLOR_RGBA(0,255,64,255));
}
}
}
// Go to next character
CharPtr = NextChar;
}
// Reset effect counter (after 4 seconds)
if(EffectCounter >= 4000)
EffectCounter = 0;
return TRUE;
}
BOOL cCharacterController::Render( \
long Elapsed, \
cFrustum *Frustum, \
float ZDistance)
{
cFrustum ViewFrustum; // Local viewing frustum
float Radius; // Bounding radius
sCharacter *CharPtr;
DWORD Time;
// Variables for printing messages
BOOL GotMatrices = FALSE;
D3DXMATRIX matWorld, matView, matProj;
D3DXVECTOR3 vecPos;
D3DVIEWPORT9 vpScreen;
float MaxY;
// Error checking
if(m_Graphics == NULL)
return FALSE;
// Return success if no character to draw
if((CharPtr = m_CharacterParent) == NULL)
return TRUE;
// Construct the viewing frustum (if none passed)
if((m_Frustum = Frustum) == NULL) {
ViewFrustum.Construct(m_Graphics, ZDistance);
m_Frustum = &ViewFrustum;
}
// Get time to update animations (30fps) if
// elapsed value passed == -1
if(Elapsed == -1)
Time = timeGetTime() / 30;
// Loop through each character and draw
while(CharPtr != NULL) {
// Update animation based on elapsed time passed
if(Elapsed != -1) {
CharPtr->LastAnimTime += (Elapsed/30);
Time = CharPtr->LastAnimTime;
}
CharPtr->Object.GetBounds(NULL,NULL,NULL, \
NULL,&MaxY,NULL,&Radius);
// Draw character if in viewing frustum
if(m_Frustum->CheckSphere(CharPtr->Object.GetXPos(), \
CharPtr->Object.GetYPos(), \
CharPtr->Object.GetZPos(), \
Radius) == TRUE) {
CharPtr->Object.UpdateAnimation(Time, TRUE);
CharPtr->Object.Render();
// Draw character's weapon
if(CharPtr->Def.Weapon != -1)
CharPtr->WeaponObject.Render();
// Draw message if needed
if(CharPtr->MessageTimer > 0) {
// Get the matrices and viewport if not done already
if(GotMatrices == FALSE) {
GotMatrices = TRUE;
// Get the world, projection, and view transformations
D3DXMatrixIdentity(&matWorld);
m_Graphics->GetDeviceCOM()->GetTransform( \
D3DTS_VIEW, &matView);
m_Graphics->GetDeviceCOM()->GetTransform( \
D3DTS_PROJECTION, &matProj);
// Get viewport
m_Graphics->GetDeviceCOM()->GetViewport(&vpScreen);
}
// Project coordinates to screen
D3DXVec3Project(&vecPos, \
&D3DXVECTOR3(CharPtr->XPos, \
CharPtr->YPos+(MaxY*0.5f), \
CharPtr->ZPos), \
&vpScreen, &matProj, &matView, &matWorld);
// Print message
m_Font->Print(CharPtr->Message, \
(long)vecPos.x, (long)vecPos.y, \
0, 0, CharPtr->MessageColor);
}
}
// go to next character
CharPtr = CharPtr->Next;
}
return TRUE;
}
float cCharacterController::GetXZRadius(sCharacter *Character)
{
float MinX, MaxX, MinZ, MaxZ;
float x, z;
// Error checking
if(Character == NULL)
return 0.0f;
Character->Object.GetBounds(&MinX, NULL, &MinZ, \
&MaxX, NULL, &MaxZ, NULL);
x = (float)max(fabs(MinX), fabs(MaxX));
z = (float)max(fabs(MinZ), fabs(MaxZ));
return max(x, z);
}
///////////////////////////////////////////////////////////
// Set/Get Functions
///////////////////////////////////////////////////////////
sCharacter *cCharacterController::GetParentCharacter()
{
return m_CharacterParent;
}
sCharacter *cCharacterController::GetCharacter(long IDNum)
{
sCharacter *CharPtr;
// Scan through all characters
if((CharPtr = m_CharacterParent) != NULL) {
while(CharPtr != NULL) {
// Return character
if(IDNum == CharPtr->ID)
return CharPtr;
// Go to next character
CharPtr = CharPtr->Next;
}
}
return NULL;
}
float cCharacterController::GetSpeed(sCharacter *Character)
{
float Speed;
// Error checking
if(Character == NULL)
return 0.0f;
// Calculate adjusted speed
Speed = Character->Def.Speed;
if(Character->Ailments & AILMENT_SLOW)
Speed *= 0.5f;
if(Character->Ailments & AILMENT_FAST)
Speed *= 1.5f;
// Bounds check value
if(Speed < 1.0f)
Speed = 1.0f;
return Speed;
}
long cCharacterController::GetAttack(sCharacter *Character)
{
long Attack;
// Error checking
if(Character == NULL)
return 0;
// Calculate adjusted attack
Attack = Character->Def.Attack;
// Adjust attack based on item value (in %(Value/100)+1)
if(Character->Def.Weapon != -1 && m_MIL != NULL) {
Attack = (long)((float)Attack * \
(((float)m_MIL[Character->Def.Weapon].Value / \
100.0f) + 1.0f));
}
if(Character->Ailments & AILMENT_WEAK)
Attack = (long)((float)Attack * 0.5f);
if(Character->Ailments & AILMENT_STRONG)
Attack = (long)((float)Attack * 1.5f);
return Attack;
}
long cCharacterController::GetDefense(sCharacter *Character)
{
long Defense;
// Error checking
if(Character == NULL)
return 0;
// Calculate adjusted defense
Defense = Character->Def.Defense;
if(Character->Def.Armor != -1 && m_MIL != NULL)
Defense = (long)((float)Defense * \
(((float)m_MIL[Character->Def.Armor].Value / \
100.0f) + 1.0f));
if(Character->Def.Shield != -1 && m_MIL != NULL)
Defense = (long)((float)Defense * \
(((float)m_MIL[Character->Def.Shield].Value / \
100.0f) + 1.0f));
if(Character->Ailments & AILMENT_WEAK)
Defense = (long)((float)Defense * 0.5f);
if(Character->Ailments & AILMENT_STRONG)
Defense = (long)((float)Defense * 1.5f);
// Bounds check value
if(Defense < 0)
Defense = 0;
return Defense;
}
long cCharacterController::GetAgility(sCharacter *Character)
{
long Agility;
// Error checking
if(Character == NULL)
return 0;
// Calculate adjusted agility
Agility = Character->Def.Agility;
if(Character->Ailments & AILMENT_CLUMSY)
Agility = (long)((float)Agility * 0.75f);
if(Character->Ailments & AILMENT_SUREFOOTED)
Agility = (long)((float)Agility * 1.5f);
return Agility;
}
long cCharacterController::GetResistance(sCharacter *Character)
{
long Resistance;
// Error checking
if(Character == NULL)
return 0;
// Calculate adjusted resistance
Resistance = Character->Def.Resistance;
if(Character->Ailments & AILMENT_ENCHANTED)
Resistance = (long)((float)Resistance * 0.5f);
if(Character->Ailments & AILMENT_BARRIER)
Resistance = (long)((float)Resistance * 1.5f);
return Resistance;
}
long cCharacterController::GetMental(sCharacter *Character)
{
long Mental;
// Error checking
if(Character == NULL)
return 0;
// Calculate adjusted mental
Mental = Character->Def.Mental;
if(Character->Ailments & AILMENT_DUMBFOUNDED)
Mental = (long)((float)Mental * 0.5f);
return Mental;
}
long cCharacterController::GetToHit(sCharacter *Character)
{
long ToHit;
// Error checking
if(Character == NULL)
return 0;
// Calculate adjusted to hit
ToHit = Character->Def.ToHit;
if(Character->Ailments & AILMENT_BLIND)
ToHit = (long)((float)ToHit * 0.75f);
if(Character->Ailments & AILMENT_HAWKEYE)
ToHit = (long)((float)ToHit * 1.5f);
return ToHit;
}
float cCharacterController::GetCharge(sCharacter *Character)
{
float Charge;
// Error checking
if(Character == NULL)
return 0;
// Calculate adjusted charge
Charge = Character->Def.ChargeRate;
if(Character->Ailments & AILMENT_SLOW)
Charge = Charge * 0.75f;
if(Character->Ailments & AILMENT_FAST)
Charge = Charge * 1.5f;
return Charge;
}
cCharICS *cCharacterController::GetICS(long IDNum)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return NULL;
return CharPtr->CharICS;
}
BOOL cCharacterController::SetLock(long IDNum, BOOL State)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new value
CharPtr->Locked = State;
return TRUE;
}
BOOL cCharacterController::SetActionTimer(long IDNum, long Timer)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new value
CharPtr->ActionTimer = Timer;
return TRUE;
}
BOOL cCharacterController::SetAction(sCharacter *Character, \
long Action, \
long AddTime)
{
long MeshNum;
// Error checking
if(Character == NULL)
return FALSE;
// Make sure attack, spell, and item has supporting charge
if(Action == CHAR_ATTACK || Action == CHAR_SPELL ||
Action == CHAR_ITEM) {
if(Character->Charge < 100.0f)
return FALSE;
}
// Set action
Character->Action = Action;
// Play sound effect
ActionSound(Character);
// Get mesh number
MeshNum = Character->Def.MeshNum;
// Set action time (or set to 1 is addtime = -1)
if(AddTime == -1)
Character->ActionTimer = 1;
else
Character->ActionTimer = AddTime + \
m_Meshes[MeshNum].Animation.GetLength( \
m_Animations[Action].Name) * 30;
return TRUE;
}
BOOL cCharacterController::SetDistance( \
long IDNum, float Distance)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new value
CharPtr->Distance = Distance;
return TRUE;
}
float cCharacterController::GetDistance(long IDNum)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return 0.0f;
return CharPtr->Distance;
}
BOOL cCharacterController::SetRoute(long IDNum, \
long NumPoints, \
sRoutePoint *Route)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Free old route
delete [] CharPtr->Route;
CharPtr->Route = NULL;
// Set new route
if((CharPtr->NumPoints = NumPoints) != NULL) {
CharPtr->Route = new sRoutePoint[NumPoints];
memcpy(CharPtr->Route,Route,NumPoints*sizeof(sRoutePoint));
CharPtr->CurrentPoint = 0;
}
return TRUE;
}
BOOL cCharacterController::SetScript(long IDNum, \
char *ScriptFilename)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new script
strcpy(CharPtr->ScriptFilename, ScriptFilename);
return TRUE;
}
char *cCharacterController::GetScript(long IDNum)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return NULL;
return CharPtr->ScriptFilename;
}
BOOL cCharacterController::SetEnable(long IDNum, BOOL Enabled)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new value
CharPtr->Enabled = Enabled;
return TRUE;
}
BOOL cCharacterController::GetEnable(long IDNum)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
return CharPtr->Enabled;
}
BOOL cCharacterController::SetMessage(sCharacter *Character, \
char *Text, long Timer, \
D3DCOLOR Color)
{
strcpy(Character->Message, Text);
Character->MessageTimer = Timer;
Character->MessageColor = Color;
return TRUE;
}
BOOL cCharacterController::Move( \
long IDNum, \
float XPos, float YPos, float ZPos)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new values
CharPtr->XPos = XPos;
CharPtr->YPos = YPos;
CharPtr->ZPos = ZPos;
return TRUE;
}
BOOL cCharacterController::GetPosition( \
long IDNum, \
float *XPos, float *YPos, float *ZPos)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
if(XPos != NULL)
*XPos = CharPtr->XPos;
if(YPos != NULL)
*YPos = CharPtr->YPos;
if(ZPos != NULL)
*ZPos = CharPtr->ZPos;
return TRUE;
}
BOOL cCharacterController::SetBounds( \
long IDNum, \
float MinX, float MinY, float MinZ, \
float MaxX, float MaxY, float MaxZ)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new values
CharPtr->MinX = min(MinX, MaxX);
CharPtr->MinY = min(MinY, MaxY);
CharPtr->MinZ = min(MinZ, MaxZ);
CharPtr->MaxX = max(MinX, MaxX);
CharPtr->MaxY = max(MinY, MaxY);
CharPtr->MaxZ = max(MinZ, MaxZ);
return TRUE;
}
BOOL cCharacterController::GetBounds( \
long IDNum, \
float *MinX, float *MinY, float *MinZ, \
float *MaxX, float *MaxY, float *MaxZ)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
if(MinX != NULL)
*MinX = CharPtr->MinX;
if(MinY != NULL)
*MinY = CharPtr->MinY;
if(MinZ != NULL)
*MinZ = CharPtr->MinZ;
if(MaxX != NULL)
*MaxX = CharPtr->MaxX;
if(MaxY != NULL)
*MaxY = CharPtr->MaxY;
if(MaxZ != NULL)
*MaxZ = CharPtr->MaxZ;
return TRUE;
}
BOOL cCharacterController::SetType(long IDNum, long Type)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new value
CharPtr->Type = Type;
return TRUE;
}
long cCharacterController::GetType(long IDNum)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return 0;
return CharPtr->Type;
}
BOOL cCharacterController::SetAI(long IDNum, long Type)
{
sCharacter *CharPtr;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Set new value
CharPtr->AI = Type;
return TRUE;
}
long cCharacterController::GetAI(long IDNum)
{
sCharacter *CharPtr;
if((CharPtr = GetCharacter(IDNum)) == NULL)
return 0;
return CharPtr->AI;
}
BOOL cCharacterController::SetTargetCharacter(long IDNum, \
long TargetNum)
{
sCharacter *CharPtr, *CharTarget;
// Get pointer to character
if((CharPtr = GetCharacter(IDNum)) == NULL)
return FALSE;
// Clear if TargetNum == -1
if(TargetNum == -1)
CharPtr->TargetChar = NULL;
else {
// Scan through list and target 1st TargetNum found
CharTarget = m_CharacterParent;
while(CharTarget != NULL) {
if(CharTarget->ID == TargetNum) {
CharPtr->TargetChar = CharTarget;
break;
}
CharTarget = CharTarget->Next;
}
// Clear target if not found in list
if(CharTarget == NULL)
CharPtr->TargetChar = NULL;
}
return TRUE;
}
BOOL cCharacterController::CharUpdate( \
sCharacter *Character, long Elapsed, \
float *XMove, float *YMove, float *ZMove)
{
float MoveX, MoveY, MoveZ, Speed;
float XDiff, YDiff, ZDiff, Dist, Radius;
float y1, y2;
long i, SpellNum;
BOOL SpellCast;
sCharacter *CharPtr;
// Error checking
if(Character == NULL)
return FALSE;
// Clear movements and action
MoveX = MoveY = MoveZ = 0.0f;
// Calculate movement speed
Speed = (float)Elapsed / 1000.0f * GetSpeed(Character);
// Move character based on their type
switch(Character->AI) {
case CHAR_STAND:
break;
case CHAR_WANDER:
// Calculate new distance and direction if needed
Character->Distance -= Elapsed;
if(Character->Distance <= 0.0f) {
// Calculate a new distance to travel
Character->Distance = (float)(rand() % 2000) + 2000.0f;
// Calculate a new direction
Character->Direction = (float)(rand()%360)*0.01744444f;
}
// Process walk or stand still
if(Character->Distance > 1000.0f) {
MoveX = (float)sin(Character->Direction) * Speed;
MoveZ = (float)cos(Character->Direction) * Speed;
Character->Action = CHAR_MOVE;
} else {
// Stand still for one second
Character->Action = CHAR_IDLE;
}
break;
case CHAR_ROUTE:
// Determine if character has reached point
XDiff = (float)fabs(Character->XPos - \
Character->Route[Character->CurrentPoint].XPos);
YDiff = (float)fabs(Character->YPos - \
Character->Route[Character->CurrentPoint].YPos);
ZDiff = (float)fabs(Character->ZPos - \
Character->Route[Character->CurrentPoint].ZPos);
Dist = XDiff*XDiff + YDiff*YDiff + ZDiff*ZDiff;
Radius = GetXZRadius(Character) * 0.25f;
// Go to next point if reached
if(Dist < (Radius*Radius)) {
Character->CurrentPoint++;
if(Character->CurrentPoint >= Character->NumPoints)
Character->CurrentPoint = 0;
// Calculate new differences and distance
XDiff = (float)fabs(Character->XPos - \
Character->Route[Character->CurrentPoint].XPos);
YDiff = (float)fabs(Character->YPos - \
Character->Route[Character->CurrentPoint].YPos);
ZDiff = (float)fabs(Character->ZPos - \
Character->Route[Character->CurrentPoint].ZPos);
Dist = XDiff*XDiff + YDiff*YDiff + ZDiff*ZDiff;
}
// Setup movement towards target
Dist = (float)sqrt(Dist);
if(Speed > Dist)
Speed = Dist;
MoveX=(Character->Route[Character->CurrentPoint].XPos - \
Character->XPos) / Dist * Speed;
MoveZ=(Character->Route[Character->CurrentPoint].ZPos - \
Character->ZPos) / Dist * Speed;
// Set new direction
Character->Direction = (float)atan2(MoveX, MoveZ);
// Set new action
Character->Action = CHAR_MOVE;
break;
case CHAR_FOLLOW:
if(Character->TargetChar != NULL) {
// Check distance between characters
XDiff = (float)fabs(Character->XPos - \
Character->TargetChar->XPos);
YDiff = (float)fabs(Character->YPos - \
Character->TargetChar->YPos);
ZDiff = (float)fabs(Character->ZPos - \
Character->TargetChar->ZPos);
Dist = XDiff*XDiff + YDiff*YDiff + ZDiff*ZDiff;
// Update if further then distance
if(Dist > (Character->Distance*Character->Distance)) {
// Setup movement towards target
Dist = (float)sqrt(Dist);
if(Speed > Dist)
Speed = Dist;
MoveX = (Character->TargetChar->XPos - \
Character->XPos) / Dist * Speed;
MoveZ = (Character->TargetChar->ZPos - \
Character->ZPos) / Dist * Speed;
// Set new direction
Character->Direction = (float)atan2(MoveX, MoveZ);
// Set new action
Character->Action = CHAR_MOVE;
}
}
break;
case CHAR_EVADE:
if(Character->TargetChar != NULL) {
// Check distance between characters
XDiff = (float)fabs(Character->XPos - \
Character->TargetChar->XPos);
YDiff = (float)fabs(Character->YPos - \
Character->TargetChar->YPos);
ZDiff = (float)fabs(Character->ZPos - \
Character->TargetChar->ZPos);
Dist = XDiff*XDiff + YDiff*YDiff + ZDiff*ZDiff;
// Update if closer then distance
if(Dist < (Character->Distance*Character->Distance)) {
// Setup movement away from target
Dist = (float)sqrt(Dist);
if(Speed > Dist)
Speed = Dist;
MoveX = -(Character->TargetChar->XPos - \
Character->XPos) / Dist * Speed;
MoveZ = -(Character->TargetChar->ZPos - \
Character->ZPos) / Dist * Speed;
// Set new direction
Character->Direction = (float)atan2(MoveX, MoveZ);
// Set new action
Character->Action = CHAR_MOVE;
}
}
break;
}
// Process monster actions if at full charge
if(Character->Type == CHAR_MONSTER && \
Character->Charge >= 100.0f) {
// Determine chance of attacking
if((rand() % 100) <= Character->Def.ToAttack) {
// Scan through list and pick a character
CharPtr = m_CharacterParent;
while(CharPtr != NULL) {
// Randomly pick enabled target (a PC),
// and make sure the target is not hurt or dead.
if(CharPtr != Character && CharPtr->Type==CHAR_PC && \
(rand() % 100) < 50 && \
CharPtr->Enabled == TRUE && \
CharPtr->Action != CHAR_DIE && \
CharPtr->Action != CHAR_HURT) {
// Get distance to target
XDiff = (float)fabs(Character->XPos - CharPtr->XPos);
YDiff = (float)fabs(Character->YPos - CharPtr->YPos);
ZDiff = (float)fabs(Character->ZPos - CharPtr->ZPos);
Dist = XDiff * XDiff + YDiff * YDiff + ZDiff * ZDiff;
// Make sure in range to attack
Radius = GetXZRadius(Character);
Radius += Character->Def.Range;
// Attack if in range
if((Radius*Radius) >= Dist) {
// Set attack data
Character->Victim = CharPtr;
CharPtr->Attacker = Character;
// Clear movement
MoveX = MoveY = MoveZ = 0.0f;
// Point towards target character
XDiff = CharPtr->XPos - Character->XPos;
ZDiff = CharPtr->ZPos - Character->ZPos;
Character->Direction = (float)atan2(XDiff, ZDiff);
// Perform attack action
SetAction(Character, CHAR_ATTACK);
break;
}
}
// Go to next character
CharPtr = CharPtr->Next;
}
} else
// Determine chance of spell casting
if((rand() % 100) <= Character->Def.ToMagic && \
m_MSL != NULL && m_SpellController != NULL) {
// Flag no spells cast
SpellCast = FALSE;
// If health is less then half, then there's a 50% chance
// of healing (if the monster knows any heal spells)
if(Character->HealthPoints <= \
(Character->Def.HealthPoints / 2)) {
// Search for a known heal spell
for(i=0;i<64;i++) {
if(m_MSL[i].Name[0] && \
m_MSL[i].Effect == ALTER_HEALTH && \
m_MSL[i].Value[0] > 0.0f && \
Character->ManaPoints >= m_MSL[i].Cost && \
Character->Def.MagicSpells[i/32] & (1<<(i&31))) {
// This is the spell, determine chance to heal
if((rand() % 100) < 50) {
// Set spell data
Character->Victim = Character;
Character->Attacker = Character;
Character->SpellNum = i;
Character->SpellTarget = CHAR_MONSTER;
// Store target coordinates
Character->TargetX = Character->XPos;
Character->TargetY = Character->YPos;
Character->TargetZ = Character->ZPos;
// Clear movement
MoveX = MoveY = MoveZ = 0.0f;
// Perform spell action
SetAction(Character, CHAR_SPELL);
// Flag spell as cast
SpellCast = TRUE;
break;
}
}
}
}
// If there are bad status ailments, then there's a
// 50% chance of dispeling magic.
if(Character->Ailments & AILMENT_POISON || \
Character->Ailments & AILMENT_SLEEP || \
Character->Ailments & AILMENT_PARALYZE || \
Character->Ailments & AILMENT_ENCHANTED || \
Character->Ailments & AILMENT_DUMBFOUNDED || \
Character->Ailments & AILMENT_SLOW || \
Character->Ailments & AILMENT_BLIND || \
Character->Ailments & AILMENT_SILENCED && \
SpellCast == FALSE) {
// Search for a known dispel spell
for(i=0;i<64;i++) {
if(m_MSL[i].Name[0] && \
m_MSL[i].Effect == DISPEL_MAGIC && \
Character->ManaPoints >= m_MSL[i].Cost && \
Character->Def.MagicSpells[i/32] & (1<<(i&31))) {
// This is the spell, determine chance to dispel
if((rand() % 100) < 50) {
// Set spell data
Character->Victim = Character;
Character->Attacker = Character;
Character->SpellNum = i;
Character->SpellTarget = CHAR_MONSTER;
// Store target coordinates
Character->TargetX = Character->XPos;
Character->TargetY = Character->YPos;
Character->TargetZ = Character->ZPos;
// Clear movement
MoveX = MoveY = MoveZ = 0.0f;
// Perform spell action
SetAction(Character, CHAR_SPELL);
// Flag spell as cast
SpellCast = TRUE;
break;
}
}
}
}
// If now spells already cast, then pick a random one
if(SpellCast == FALSE) {
// Pick a random spell to attack with
SpellNum = rand() % 64;
// Scan through list until a spell is found the
// monster can cast.
for(i=0;i<64;i++) {
if(m_MSL[SpellNum].Name[0] && \
Character->Def.MagicSpells[SpellNum / 32] & \
(1 << (SpellNum & 31)) && \
Character->ManaPoints >= m_MSL[SpellNum].Cost && \
(rand() % 100) < 50) {
// Scan through list and pick a character
CharPtr = m_CharacterParent;
while(CharPtr != NULL) {
// Randomly pick an enabled target (a PC),
// and make sure the target is not hurt or dead.
// Also, don't cast self-targeting spells here.
if(CharPtr != Character && \
CharPtr->Type == CHAR_PC && \
m_MSL[SpellNum].Target != TARGET_SELF && \
(rand() % 100) < 50 && \
CharPtr->Enabled == TRUE && \
CharPtr->Action != CHAR_DIE && \
CharPtr->Action != CHAR_HURT) {
// Get heights of attacker and target
// for line of sight checking
Character->Object.GetBounds(NULL,NULL,NULL, \
NULL,&y1,NULL,NULL);
y1 = (y1 * 0.5f) + Character->YPos;
CharPtr->Object.GetBounds(NULL,NULL,NULL, \
NULL,&y2,NULL,NULL);
y2 = (y2 * 0.5f) + CharPtr->YPos;
// Get distance to target
XDiff = (float)fabs(Character->XPos - \
CharPtr->XPos);
YDiff = (float)fabs(Character->YPos - \
CharPtr->YPos);
ZDiff = (float)fabs(Character->ZPos - \
CharPtr->ZPos);
Dist = XDiff*XDiff+YDiff*YDiff+ZDiff*ZDiff;
// Reduce distance by character's radius
Radius = GetXZRadius(CharPtr);
Dist -= (Radius*Radius);
// Get spell radius
Radius = m_MSL[SpellNum].Distance;
// Make sure target is in range and in sight
if(LineOfSight(Character, CharPtr, \
Character->XPos, y1, \
Character->ZPos, \
CharPtr->XPos, y2, \
CharPtr->ZPos) && \
Dist <= (Radius * Radius)) {
// Set the spell data
Character->Victim = CharPtr;
CharPtr->Attacker = Character;
Character->SpellNum = SpellNum;
Character->SpellTarget = CHAR_PC;
// Store target coordinates
Character->TargetX = CharPtr->XPos;
Character->TargetY = CharPtr->YPos;
Character->TargetZ = CharPtr->ZPos;
// Face toward target (only if not self)
if(m_MSL[SpellNum].Target != TARGET_SELF) {
XDiff = CharPtr->XPos - Character->XPos;
ZDiff = CharPtr->ZPos - Character->ZPos;
Character->Direction = \
(float)atan2(XDiff, ZDiff);
}
// Clear movement
MoveX = MoveY = MoveZ = 0.0f;
// Set the spell action
SetAction(Character, CHAR_SPELL);
// Flag spell as cast
SpellCast = TRUE;
break;
}
}
// Go to next character
CharPtr = CharPtr->Next;
}
break;
}
// Go to next spell
SpellNum = (SpellNum + 1) % 64;
}
}
// If still no spell cast, try casting a known
// self-enhancing ailment-effecting spell.
if(SpellCast == FALSE) {
for(i=0;i<64;i++) {
if(m_MSL[i].Name[0] && \
m_MSL[i].Effect == CAUSE_AILMENT && \
Character->ManaPoints >= m_MSL[i].Cost && \
Character->Def.MagicSpells[i/32]&(1<<(i&31)) && \
(rand()%100) < 10) {
// Make sure it's self-enhancing
if((long)m_MSL[i].Value[0]&AILMENT_STRONG || \
(long)m_MSL[i].Value[0]&AILMENT_BARRIER || \
(long)m_MSL[i].Value[0]&AILMENT_SUREFOOTED || \
(long)m_MSL[i].Value[0]&AILMENT_FAST || \
(long)m_MSL[i].Value[0]&AILMENT_HAWKEYE) {
// Make sure ailment not already set
if(!(Character->Ailments & \
(long)m_MSL[i].Value[0])) {
// Set spell data
Character->Victim = Character;
Character->Attacker = Character;
Character->SpellNum = i;
Character->SpellTarget = CHAR_MONSTER;
// Store target coordinates
Character->TargetX = Character->XPos;
Character->TargetY = Character->YPos;
Character->TargetZ = Character->ZPos;
// Clear movement
MoveX = MoveY = MoveZ = 0.0f;
// Perform spell action
SetAction(Character, CHAR_SPELL);
break;
}
}
}
}
}
}
}
// Store movement and return
*XMove = MoveX;
*YMove = MoveY;
*ZMove = MoveZ;
return TRUE;
}
BOOL cCharacterController::CheckMove(sCharacter *Character, \
float *XMove, float *YMove, float *ZMove)
{
sCharacter *CharPtr;
float XDiff, YDiff, ZDiff, Dist;
float Radius1, Radius2;
float XPos, YPos, ZPos;
float MinX, MaxX, MinZ, MaxZ;
// Error checking
if(Character == NULL)
return FALSE; // Don't allow movement
XPos = Character->XPos + (*XMove);
YPos = Character->YPos + (*YMove);
ZPos = Character->ZPos + (*ZMove);
// Get character's X/Z radius
Character->Object.GetBounds(&MinX, NULL, &MinZ, \
&MaxX, NULL, &MaxZ, NULL);
Radius1 = max(MaxX-MinX, MaxZ-MinZ) * 0.5f;
// Check movement against other characters
if((CharPtr = m_CharacterParent) != NULL) {
while(CharPtr != NULL) {
// Don't check against self or disabled characters
if(Character != CharPtr && CharPtr->Enabled == TRUE) {
// Don't check against other PC characters
if(Character->Type == CHAR_PC && \
CharPtr->Type == CHAR_PC)
break;
// Get distance between characters
XDiff = (float)fabs(XPos - CharPtr->XPos);
YDiff = (float)fabs(YPos - CharPtr->YPos);
ZDiff = (float)fabs(ZPos - CharPtr->ZPos);
Dist = XDiff*XDiff + YDiff*YDiff + ZDiff*ZDiff;
// Get checking character's X/Z bounding radius
CharPtr->Object.GetBounds(&MinX, NULL, &MinZ, \
&MaxX, NULL, &MaxZ, NULL);
Radius2 = max(MaxX-MinX, MaxZ-MinZ) * 0.5f;
// Don't allow movement if intersecting
if(Dist <= (Radius1*Radius1 + Radius2*Radius2))
return FALSE;
}
CharPtr = CharPtr->Next;
}
}
// Bounds check movement if MinX != MaxX
if(Character->MinX != Character->MaxX) {
if(XPos < Character->MinX || XPos > Character->MaxX)
*XMove = 0.0f;
if(YPos < Character->MinY || YPos > Character->MaxY)
*YMove = 0.0f;
if(ZPos < Character->MinZ || ZPos > Character->MaxZ)
*ZMove = 0.0f;
// Return no movement at all
if(!(*XMove) && !(*YMove) && !(*ZMove))
return FALSE;
}
// Call overloaded check custom collisions (maps, etc)
if(ValidateMove(Character, XMove, YMove, ZMove) == FALSE)
return FALSE; // Don't allow movement
return TRUE;
}
BOOL cCharacterController::ProcessUpdate( \
sCharacter *Character,
float XMove, float YMove, float ZMove)
{
// Move character
Character->XPos += XMove;
Character->YPos += YMove;
Character->ZPos += ZMove;
// Move object and point in direction
Character->Object.Move(Character->XPos, \
Character->YPos, \
Character->ZPos); \
Character->Object.Rotate(0.0f, Character->Direction, 0.0f);
// Set new animation
if(Character->LastAnim != Character->Action) {
Character->LastAnim = Character->Action;
if(m_NumAnimations && m_Animations != NULL) {
Character->LastAnimTime = timeGetTime() / 30;
Character->Object.SetAnimation( \
&m_Meshes[Character->Def.MeshNum].Animation, \
m_Animations[Character->Action].Name, \
Character->LastAnimTime);
}
}
return TRUE;
}
BOOL cCharacterController::Attack(sCharacter *Attacker, \
sCharacter *Victim)
{
// Error checking
if(Attacker == NULL || Victim == NULL)
return FALSE;
// Don't attack dead or hurt people
if(Victim->Action == CHAR_DIE || Victim->Action == CHAR_HURT)
return FALSE;
// Set attacker and victim
Victim->Attacker = Attacker;
Attacker->Victim = Victim;
// Return if hit missed
if((rand() % 1000) > GetToHit(Attacker)) {
SetMessage(Victim, "Missed!", 500);
return FALSE;
}
// Return if hit dodged
if((rand() % 1000) <= GetAgility(Victim)) {
SetMessage(Victim, "Dodged!", 500);
return FALSE;
}
// If character is asleep, randomly wake them up (50% chance)
if(Victim->Ailments & AILMENT_SLEEP) {
if((rand() % 100) < 50)
Victim->Ailments &= ~AILMENT_SLEEP;
}
// Attack landed, apply damage
Damage(Victim, TRUE, GetAttack(Attacker), -1, -1);
return TRUE;
}
BOOL cCharacterController::Damage(sCharacter *Victim, \
BOOL PhysicalAttack, \
long Amount, \
long DmgClass, \
long CureClass)
{
char Text[128];
float Resist;
float Range;
long DmgAmount;
// Error checking
if(Victim == NULL)
return FALSE;
// Can't attack if already dead or being hurt (or not enabled)
if(Victim->Enabled == FALSE || \
Victim->Action==CHAR_DIE || \
Victim->Action==CHAR_HURT)
return FALSE;
// Adjust for defense if physical attack
if(PhysicalAttack == TRUE) {
// Random value for less/more damage (-+20%)
Range = (float)((rand() % 20) + 90) / 100.0f;
DmgAmount = (long)((float)Amount * Range);
// Subtract for defense of victim (allow -20% difference)
Range = (float)((rand() % 20) + 80) / 100.0f;
DmgAmount -= (long)((float)GetDefense(Victim) * Range);
} else {
// Adjust for magical attack
Resist = 1.0f - ((float)GetResistance(Victim) / 100.0f);
DmgAmount = (long)((float)Amount * Resist);
}
// Bounds check value
if(DmgAmount < 0)
DmgAmount = 0;
// Check for double damage
if(Victim->Def.Class == DmgClass)
DmgAmount *= 2;
// Check for cure damage
if(Victim->Def.Class == CureClass)
DmgAmount = -(labs(DmgAmount)/2);
// If no physical damage is dealt then randomly deal
// 10-20% of damage from the original amount.
if(!DmgAmount && PhysicalAttack == TRUE) {
Range = (float)((rand() % 10) + 10) / 100.0f;
DmgAmount = (long)((float)Amount * Range);
}
// Subtract damage amount
Victim->HealthPoints -= DmgAmount;
// Set hurt status and display message
if(DmgAmount >= 0) {
sprintf(Text, "-%lu HP", DmgAmount);
SetMessage(Victim, Text, 500, D3DCOLOR_RGBA(255,64,0,255));
// Only set hurt if any damage (and idle or moving)
if(DmgAmount) {
if(Victim->Action==CHAR_MOVE || Victim->Action==CHAR_IDLE)
SetAction(Victim, CHAR_HURT);
}
}
// Display cure amount
if(DmgAmount < 0) {
sprintf(Text, "+%lu HP", -DmgAmount);
SetMessage(Victim, Text, 500, D3DCOLOR_RGBA(0,64,255,255));
}
return TRUE;
}
BOOL cCharacterController::Death(sCharacter *Attacker, \
sCharacter *Victim)
{
char Text[128];
// If a PC or NPC dies, then don't remove from list
if(Victim->Type == CHAR_PC) {
// Mark character as disabled so no updates
Victim->Enabled = FALSE;
// Call outside death function for PC's
if(Victim->Type == CHAR_PC)
PCDeath(Victim);
else
NPCDeath(Victim);
} else {
// Give attacker the victim's experience
if(Attacker != NULL) {
if(Experience(Attacker, Victim->Def.Experience) == TRUE) {
sprintf(Text, "+%lu exp.", Victim->Def.Experience);
SetMessage(Attacker, Text, 500);
}
}
// Drop character's money
if(m_MIL != NULL && Victim->Def.Money)
DropMoney(Victim->XPos, Victim->YPos, Victim->ZPos, \
Victim->Def.Money);
// Randomly drop an item (as specified in definition)
if((rand() % 100) < Victim->Def.DropChance)
DropItem(Victim->XPos, Victim->YPos, Victim->ZPos, \
Victim->Def.DropItem);
// Decrease mesh count and release if no more
m_Meshes[Victim->Def.MeshNum].Count--;
if(!m_Meshes[Victim->Def.MeshNum].Count) {
m_Meshes[Victim->Def.MeshNum].Mesh.Free();
m_Meshes[Victim->Def.MeshNum].Animation.Free();
}
// Remove dead character from list
if(Victim->Prev != NULL)
Victim->Prev->Next = Victim->Next;
else
m_CharacterParent = Victim->Next;
if(Victim->Next != NULL)
Victim->Next->Prev = Victim->Prev;
if(Victim->Prev == NULL && Victim->Next == NULL)
m_CharacterParent = NULL;
Victim->Prev = Victim->Next = NULL;
delete Victim;
}
return TRUE;
}
BOOL cCharacterController::Spell(sCharacter *Caster, \
sSpellTracker *SpellTracker, \
sSpell *Spells)
{
float XDiff, YDiff, ZDiff, Dist, YDist, XZDist;
float MinX, MaxX, MinY, MaxY, MinZ, MaxZ;
float SpellRadius, XZRadius, YRadius;
sSpell *SpellPtr;
sCharacter *CharPtr, *ClosestChar;
float Closest;
BOOL Allow;
// Error checking
if(Caster == NULL || SpellTracker == NULL || Spells == NULL)
return TRUE;
// Get pointer to spell
SpellPtr = &Spells[SpellTracker->SpellNum];
// Reduce magic
Caster->ManaPoints -= SpellPtr->Cost;
if(Caster->ManaPoints < 0)
Caster->ManaPoints = 0;
// Can't cast if silenced
if(Caster->Ailments & AILMENT_SILENCED) {
SetMessage(Caster, "Silenced!", 500);
return FALSE;
}
// Get radius of spell
SpellRadius = SpellPtr->Range * SpellPtr->Range;
// Handle self-targeting spells instantly
if(SpellPtr->Target == TARGET_SELF) {
SpellEffect(Caster, Caster, SpellPtr);
return TRUE;
}
// Reset closest character pointer
ClosestChar = NULL;
Closest = 0.0f;
// Scan through all characters and look for hits
if((CharPtr = m_CharacterParent) == NULL)
return FALSE;
while(CharPtr != NULL) {
// Only bother with characters of allowed types
// as well as not targeting self. Also, allow
// a RAISE_DEAD PC spell to affect any character.
Allow = FALSE;
if(CharPtr!=Caster && SpellTracker->Type==CharPtr->Type)
Allow = TRUE;
if(CharPtr->Type==CHAR_PC && SpellPtr->Effect==RAISE_DEAD)
Allow = TRUE;
// Find target(s) if allowed
if(Allow == TRUE) {
// Get distance from target to character
XDiff = (float)fabs(CharPtr->XPos - SpellTracker->TargetX);
YDiff = (float)fabs(CharPtr->YPos - SpellTracker->TargetY);
ZDiff = (float)fabs(CharPtr->ZPos - SpellTracker->TargetZ);
// Get X/Z and Y distances
XZDist = (XDiff * XDiff + ZDiff * ZDiff) - SpellRadius;
YDist = (YDiff * YDiff) - SpellRadius;
// Get target X/Z and Y radius
CharPtr->Object.GetBounds(&MinX,&MinY,&MinZ,
&MaxX,&MaxY,&MaxZ,NULL);
XZRadius = max(MaxX-MinX, MaxZ-MinZ) * 0.5f;
YRadius = (MaxY-MinY) * 0.5f;
// Check if character in range
if(XZDist - (XZRadius * XZRadius) <= 0.0f &&
YDist - (YRadius * YRadius) <= 0.0f) {
// Determine what to do if in range
if(SpellPtr->Target == TARGET_SINGLE) {
// Record closest character in range
Dist = XDiff * XDiff + YDiff * YDiff + ZDiff * ZDiff;
if(ClosestChar == NULL) {
ClosestChar = CharPtr;
Closest = Dist;
} else {
if(Dist < Closest) {
ClosestChar = CharPtr;
Closest = Dist;
}
}
} else {
// Spell hit target if area target
SpellEffect(Caster, CharPtr, SpellPtr);
}
}
}
// Go to next character
CharPtr = CharPtr->Next;
}
// Process spell on closest character if needed
if(SpellPtr->Target==TARGET_SINGLE && ClosestChar!=NULL)
SpellEffect(Caster, ClosestChar, SpellPtr);
return TRUE;
}
BOOL cCharacterController::SpellEffect(sCharacter *Caster, \
sCharacter *Target, \
sSpell *Spell)
{
BOOL CanHit;
long Chance;
char Text[64];
// Error checking
if(Target == NULL || Spell == NULL)
return FALSE;
// Calculate chance of hitting
if(Caster != NULL) {
// A spell always lands if target=caster
if(Caster == Target)
Chance = 100;
else
Chance = (long)(((float)GetMental(Caster) / 100.0f + \
1.0f) * (float)Spell->Chance);
} else {
Chance = Spell->Chance;
}
// Alter chance by target's resistance
if(Caster != Target)
Chance = (long)((1.0f - (float)GetResistance(Target) / \
100.0f) * (float)Chance);
// See if spell failed
if(Chance != 100 && (rand() % 100) >= Chance) {
SetMessage(Target, "Failed!", 500);
return FALSE;
}
// Flag character to allow effect
CanHit = TRUE;
if(Target->Action==CHAR_HURT || Target->Action==CHAR_DIE)
CanHit = FALSE;
// Store attacker and victim
if((Target->Attacker = Caster) != NULL)
Caster->Victim = Target;
// Process spell effect
switch(Spell->Effect) {
case ALTER_HEALTH: // Alter health
if(CanHit == FALSE)
break;
// Apply damage if value < 0
if(Spell->Value[0] < 0.0f)
Damage(Target,FALSE,-(long)Spell->Value[0], \
Spell->DmgClass, Spell->CureClass);
// Cure damage if value > 0
if(Spell->Value[0] > 0.0f) {
Target->HealthPoints += (long)Spell->Value[0];
if(Target->HealthPoints > Target->Def.HealthPoints)
Target->HealthPoints = Target->Def.HealthPoints;
// Display amount healed
sprintf(Text, "+%lu HP", (long)Spell->Value[0]);
SetMessage(Target,Text,500,D3DCOLOR_RGBA(0,64,255,255));
}
break;
case ALTER_MANA: // Alter mana
if(CanHit == FALSE)
break;
// Alter mana value
Target->ManaPoints += (long)Spell->Value[0];
if(Target->ManaPoints < 0)
Target->ManaPoints = 0;
if(Target->ManaPoints > Target->Def.ManaPoints)
Target->ManaPoints = Target->Def.ManaPoints;
// Display remove mana message
if(Spell->Value[0] < 0.0f) {
sprintf(Text, "%ld MP", (long)Spell->Value[0]);
SetMessage(Target,Text,500,D3DCOLOR_RGBA(0,128,64,255));
}
// Display add mana message
if(Spell->Value[0] > 0.0f) {
sprintf(Text, "+%lu MP", (long)Spell->Value[0]);
SetMessage(Target,Text,500,D3DCOLOR_RGBA(0,255,0,255));
}
break;
case CURE_AILMENT: // Clear ailment flag
if(CanHit == FALSE)
break;
// Apply ailment and display message
Target->Ailments |= ~(long)Spell->Value[0];
SetMessage(Target, "Cure", 500);
break;
case CAUSE_AILMENT: // Set ailment flag
if(CanHit == FALSE)
break;
// Cure ailment and display message
Target->Ailments |= (long)Spell->Value[0];
SetMessage(Target, "Ailment", 500);
break;
case RAISE_DEAD: // Raise from dead
if(Target->Action == CHAR_DIE) {
Target->HealthPoints = 1;
Target->ManaPoints = 0;
Target->Action = CHAR_IDLE;
Target->Locked = FALSE;
Target->ActionTimer = 0;
Target->Ailments = 0;
Target->Enabled = TRUE;
}
break;
case INSTANT_KILL: // Kill character
if(CanHit == FALSE)
break;
// Set die action
SetAction(Target, CHAR_DIE);
break;
case DISPEL_MAGIC: // Remove all ailments
if(CanHit == FALSE)
break;
// Clear all ailments
Target->Ailments = 0;
break;
case TELEPORT: // Teleport PC/NPC/MONSTER
if(CanHit == FALSE)
break;
// Teleport PCs from seperate function from rest
if(Target->Type == CHAR_PC)
PCTeleport(Caster, Spell);
else {
Target->XPos = Spell->Value[0];
Target->YPos = Spell->Value[1];
Target->ZPos = Spell->Value[2];
}
break;
}
return TRUE;
}
BOOL cCharacterController::Equip(sCharacter *Character, \
long ItemNum, long Type, \
BOOL Equip)
{
char Path[MAX_PATH];
// Error checking
if(m_MIL == NULL || Character == NULL)
return FALSE;
// Make sure restritions allow equiping of item
if(!CheckUsageBit(m_MIL[ItemNum].Usage,Character->Def.Class))
return FALSE;
// Remove current item first and equip new one
switch(Type) {
case WEAPON:
// Remove current item of type
Character->Def.Weapon = -1;
Character->WeaponObject.Free();
Character->WeaponMesh.Free();
// Equip new item of correct type
if(Equip==TRUE && m_MIL[ItemNum].Category == WEAPON) {
Character->Def.Weapon = ItemNum;
// Setup new weapon mesh and object
if(m_MIL[ItemNum].MeshFilename[0]) {
// Build the mesh path
sprintf(Path, "%s%s", m_MeshPath, \
m_MIL[Character->Def.Weapon].MeshFilename);
// Load the new mesh
Character->WeaponMesh.Load(m_Graphics, Path, \
m_TexturePath);
// Create the weapon object
Character->WeaponObject.Create(m_Graphics, \
&Character->WeaponMesh);
// Orient and attach the weapon
Character->WeaponObject.Move(0.0f, 0.0f, 0.0f);
Character->WeaponObject.Rotate(0.0f, 0.0f, 0.0f);
Character->WeaponObject.AttachToObject( \
&Character->Object, "WeaponHand");
}
}
break;
case ARMOR:
// Remove current item of type
Character->Def.Armor = -1;
// Equip new item of correct type
if(Equip==TRUE && m_MIL[ItemNum].Category == ARMOR)
Character->Def.Armor = ItemNum;
break;
case SHIELD:
// Remove current item of type
Character->Def.Shield = -1;
// Equip new item of correct type
if(Equip==TRUE && m_MIL[ItemNum].Category == SHIELD)
Character->Def.Shield = ItemNum;
break;
case ACCESSORY:
// Remove current item of type
Character->Def.Accessory = -1;
// Equip new item of correct type
if(Equip==TRUE && m_MIL[ItemNum].Category == ACCESSORY)
Character->Def.Accessory = ItemNum;
break;
default: return FALSE;
}
return TRUE;
}
BOOL cCharacterController::Item(sCharacter *Owner, \
sCharacter *Target, \
long ItemNum, \
sCharItem *CharItem)
{
sItem *Item;
// Error checking
if(Owner == NULL || Target == NULL || m_MIL == NULL)
return FALSE;
// Make sure restritions allow equiping of item
if(!CheckUsageBit(m_MIL[ItemNum].Usage, Target->Def.Class))
return FALSE;
// Get pointer to item
Item = (sItem*)&m_MIL[ItemNum];
// Use specified item
switch(Item->Category) {
case EDIBLE:
case HEALING:
// Alter health
Owner->HealthPoints += Item->Value;
break;
}
// Decrease quanity (and remove object) if needed
if(CheckItemFlag(Item->Flags,USEONCE) && CharItem != NULL) {
CharItem->Quantity--;
if(CharItem->Quantity <= 0 && Owner->CharICS != NULL)
Owner->CharICS->Remove(CharItem);
}
return TRUE;
}
BOOL cCharacterController::Drop(sCharacter *Character,
sCharItem *Item, long Quantity)
{
// Error checking
if(Item == NULL || m_MIL == NULL || Character == NULL)
return FALSE;
// Make sure item can be dropped
if(!CheckItemFlag(m_MIL[Item->ItemNum].Flags,CANDROP))
return FALSE;
// Decrease quantity from item
Item->Quantity -= Quantity;
// Remove item from ICS if no more left
if(Item->Quantity <= 0 && Character->CharICS != NULL)
Character->CharICS->Remove(Item);
return TRUE;
}
| true |
6c2991eb66a8121a59384fb1acb02f22cd35d092 | C++ | sanjusss/nowcoder | /huawei/005计算字符个数.hpp | GB18030 | 980 | 3.234375 | 3 | [] | no_license | #pragma once
/*
Ŀ
дһһĸɵַһַȻַкиַĸִСд
:
һһĸԼոɵַڶһַ
:
ַкиַĸ
ʾ1
ABCDEF
A
1
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <list>
#include <set>
#include <iterator>
#include <string>
#include <stack>
#include <queue>
#include <random>
#include <ctime>
#include <limits>
#include <unordered_set>
#include <unordered_map>
using namespace std;
int main()
{
string line;
getline(cin, line);
char t;
cin >> t;
t = toupper(t);
int count = 0;
for (auto i : line)
{
if (toupper(i) == t)
{
++count;
}
}
cout << count << endl;
} | true |
8133478aea931e62faf22759eb1de6bcd9f15ad8 | C++ | optimisticlucifer/My_Cpp_Journey | /btd.cpp | UTF-8 | 250 | 2.765625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int btd(int n){
int x=1,sum=0;
while(n>0){
int a=n%10;
sum+=a*x;
x*=2;
n/=10;
}
return sum;
}
int main()
{
int n;
cin>>n;
cout<<btd(n)<<endl;
} | true |
9254ba6c6826cf669c07574ea158cd236c8ccc7a | C++ | groosik/Api | /DikiApi/src/WebsiteFetcher.cpp | UTF-8 | 1,297 | 2.921875 | 3 | [] | no_license | #include "WebsiteFetcher.h"
#include <codecvt>
std::wstring WebsiteFetcher::downloadWebsite(const std::wstring& link)
{
//TODO: implement
return L"..\\additional files\\dog.html";
}
void WebsiteFetcher::loadFileIntoMemory()
{
int i=0;
std::wstring line;
while(getline(fileHandler, line))
codeLines.push_back(line);
}
void WebsiteFetcher::closeAndDeleteFile()
{
if(fileHandler.is_open())
fileHandler.close();
deleteFile();
}
void WebsiteFetcher::downloadAndOpenFile(std::wstring link)
{
fetchedFilePath=downloadWebsite(link);
fileHandler.open(fetchedFilePath, std::wfstream::in);
if(fileHandler.good()==false)
throw std::exception("Invalid link. ");
const std::locale utf8_locale = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
fileHandler.imbue(utf8_locale);
}
WebsiteFetcher::WebsiteFetcher(std::wstring link)
{
downloadAndOpenFile(link);
loadFileIntoMemory();
closeAndDeleteFile();
}
void WebsiteFetcher::deleteFile()
{
//TODO: implement
}
std::wstring WebsiteFetcher::getLineOfCode(int index)
{
if(getLinesQuantity()<=index || index<0)
throw std::out_of_range("Called function WebsiteFetcher::getLineOfCode() with invalid index.");
return codeLines[index];
}
int WebsiteFetcher::getLinesQuantity() const
{
return codeLines.size();
}
| true |
7823435fc98f052c8c1d2cc0685e433567156feb | C++ | riscy/a_star_on_grids | /src/benchmarks.cpp | UTF-8 | 2,401 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <fstream>
using namespace std;
#include "benchmarks.h"
#include "graph.h"
#include "heuristics.h"
#include "algorithms.h"
#include "stats.h"
const int RANDOM_SEED = 10;
/// Test a random set of problems
void benchmark_all_algorithms(Graph & graph, int num_problems,
unsigned int (*heuristic)(Node*, Node*),
bool print_stats) {
Stats stats_lrta_basic("LRTA* (suboptimal)");
srand(RANDOM_SEED);
for (int ii = 0; ii < num_problems; ++ ii) {
Node *ss = 0, *gg = 0;
while (ss == gg) {
ss = graph.random_node();
gg = graph.random_node();
}
lrta_basic(graph, ss, gg, stats_lrta_basic, heuristic);
}
if (print_stats)
stats_lrta_basic.print();
Stats stats_astar_basic("Basic A*");
srand(RANDOM_SEED);
for (int ii = 0; ii < num_problems; ++ ii) {
Node *ss = 0, *gg = 0;
while (ss == gg) {
ss = graph.random_node();
gg = graph.random_node();
}
astar_basic(graph, ss, gg, stats_astar_basic, heuristic);
}
if (print_stats)
stats_astar_basic.print();
Stats stats_fringe_search("Fringe search");
srand(RANDOM_SEED);
for (int ii = 0; ii < num_problems; ++ ii) {
Node *ss = 0, *gg = 0;
while (ss == gg) {
ss = graph.random_node();
gg = graph.random_node();
}
fringe_search(graph, ss, gg, stats_fringe_search, heuristic);
}
if (print_stats)
stats_fringe_search.print();
Stats stats_astar_heap("A* with a heap and tiebreaking on larger g");
srand(RANDOM_SEED);
for (int ii = 0; ii < num_problems; ++ ii) {
Node *ss = 0, *gg = 0;
while (ss == gg) {
ss = graph.random_node();
gg = graph.random_node();
}
astar_heap(graph, ss, gg, stats_astar_heap, heuristic);
}
if (print_stats)
stats_astar_heap.print();
}
void benchmark_grid_costs() {
size_t num_problems = 100000;
Graph graph;
graph.load_ascii_map("../maps/example.map", EDGES_OCTILE, true);
benchmark_all_algorithms(graph, 100, &octile_heuristic); // warm the cache
int test_costs[4][2] = {{70, 99}, {2, 3}, {50, 99}, {1, 1}};
for (size_t ii = 0; ii < 4; ++ ii) {
cout << endl << "Diagonal: " << test_costs[ii][0]
<< "/Cardinal: " << test_costs[ii][1] << endl;
grid_costs(test_costs[ii][0], test_costs[ii][1]);
benchmark_all_algorithms(graph, num_problems, &octile_heuristic, true);
}
}
| true |
02e94825a4883ca5577a582bfddeea1e59f06b3d | C++ | pjha1994/javatempfiles | /gcd_lcm.cpp | UTF-8 | 353 | 3.015625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int gcd1(int a,int b){
return b==0?a:gcd1(b,a%b);
}
int main(){
int T;
cin>>T;
int *gcd = new int[T];
int *lcm = new int[T];
int temp=T;
while(T-->0){
int a,b;
cin>>a>>b;
gcd[T] = gcd1(a,b);
lcm[T] = (a*b)/gcd[T];
}
T=temp;
for(int i=T-1;i>=0;i--)
cout<<gcd[i]<<" "<<lcm[i]<<"\n";
return 0;
} | true |
667dfba99506a57800e9ece5904ec3991bd734e4 | C++ | NicoJiao/DatasetGenerator | /utils/bel2yolo.cpp | UTF-8 | 3,051 | 2.8125 | 3 | [] | no_license | // STD; STL
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
// OpenCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
void loadImages(const std::string& path, std::vector<cv::Mat>& imgs, const int& mode)
{
std::vector<cv::String> strBuffer;
cv::glob(path, strBuffer, false);
for (auto& it : strBuffer)
{
imgs.push_back(cv::imread(it, mode));
}
}
std::vector<std::string> split(const std::string &s, char delim)
{
std::stringstream ss(s);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim))
{
elems.push_back(std::move(item));
}
return elems;
}
/*
CSV format:
-----------
Filename - Image file the following information applies to
Roi.x1,Roi.y1,
Roi.x2,Roi.y2 - Location of the sign within the image
(Images contain a border around the actual sign
of 10 percent of the sign size, at least 5 pixel)
ClassId - The class of the traffic sign
*/
enum AnnotationFormat
{
NAME = 0,
RX1 = 1,
RY1 = 2,
RX2 = 3,
RY2 = 4,
CLASS = 5
};
int main(int argc, char **argv)
{
// Bad args
if (argc < 3)
{
std::cerr << "Usage: ./" << argv[0] << " annotation_csv path_2_images" << std::endl;
return 1;
}
// Open csv with annotation
std::ifstream infile(argv[1]);
std::string line;
std::string path(argv[2]);
cv::Mat m;
double x, y, imgW, imgH, signW, signH;
try
{
// Skip header
//std::getline(infile, line);
// Loop over records
while (std::getline(infile, line))
{
// Parse comma-separated line
std::vector<std::string> vec = split(line, ';');
//std::cerr << vec.at(NAME) << " " << vec.at(RX1) << " " << vec.at(RX2)
// << " " << vec.at(RY1) << " " << vec.at(RY2) << " " << vec.at(CLASS) << std::endl;
// Create annotation file
std::string annot = vec.at(NAME);
annot = annot.substr(0, annot.find_last_of('.')) + ".txt";
std::ofstream annotFile("annotation/" + annot, std::ios_base::app);
// Load annotated image
m = cv::imread(path + "/" + vec.at(NAME), cv::IMREAD_UNCHANGED);
// Calculate YOLO relative annotations
x = std::stoi(vec.at(RX1));
y = std::stoi(vec.at(RY1));
imgW = 1628;
imgH = 1236;
signW = std::stoi(vec.at(RX2)) - std::stoi(vec.at(RX1));
signH = std::stoi(vec.at(RY2)) - std::stoi(vec.at(RY1));
annotFile << vec.at(CLASS) << " ";
annotFile << x / imgW << " ";
annotFile << y / imgH << " ";
annotFile << signW / imgW << " ";
annotFile << signH / imgH << std::endl;
// Test
/*cv::Point pt {x, y};
cv::Point pt2{x + signW, y + signH};
cv::rectangle(m, pt, pt2, cv::Scalar{0, 255, 0}, 3);
cv::Mat m2;
cv::resize( m, m2, cv::Size{407, 309} );
cv::imshow("1", m2); cv::waitKey(0);*/
}
}
catch (std::exception& e)
{
std::cerr << "Anntotaion has incorrect format. ("
+ std::string(e.what()) + ")" << std::endl;
}
return 0;
} | true |
1795b9afafaf00c190ec9028882bfefba3601b1e | C++ | graphisoft-python/DGLib | /Support/Modules/GSRoot/ThreadSpecificStorage.hpp | UTF-8 | 4,207 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive |
// *****************************************************************************
//
// Declaration and implementation of ThreadSpecificStorage<T> class
//
// Module: GSRoot
// Namespace: GS
// Contact person: SN
//
// *****************************************************************************
#ifndef GS_THREADSPECIFICSTORAGE_HPP
#define GS_THREADSPECIFICSTORAGE_HPP
#pragma once
// --- Includes ----------------------------------------------------------------
#include "GSDebug.hpp"
#include "ThreadSpecificStorageImpl.hpp"
// --- ThreadSpecificStorage<T> class ------------------------------------------
namespace GS {
template<typename T>
class ThreadSpecificStorage {
#if defined (DEBUVERS)
static char ST[(sizeof (T) <= sizeof (void*)) ? 1 : -1] GCC_UNUSED;
#endif
// Data members:
private:
ThreadSpecificStorageImpl* m_impl;
// Construction / destruction:
public:
ThreadSpecificStorage ();
ThreadSpecificStorage (const ThreadSpecificStorage<T>& rhs);
virtual ~ThreadSpecificStorage ();
// Operator overloading:
public:
const ThreadSpecificStorage<T>& operator = (const ThreadSpecificStorage<T>& rhs);
// Operations:
public:
T Get () const;
void Set (T value);
};
////////////////////////////////////////////////////////////////////////////////
// ThreadSpecificStorage implementation
////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// Default constructor
// -----------------------------------------------------------------------------
template<typename T>
inline ThreadSpecificStorage<T>::ThreadSpecificStorage () :
m_impl (ThreadSpecificStorageImpl::Create ())
{
// Empty constructor body
}
// -----------------------------------------------------------------------------
// Copy constructor
// -----------------------------------------------------------------------------
template<typename T>
inline ThreadSpecificStorage<T>::ThreadSpecificStorage (const ThreadSpecificStorage<T>& rhs) :
m_impl (rhs.m_impl->Clone ())
{
// Empty constructor body
}
// -----------------------------------------------------------------------------
// Destructor
// -----------------------------------------------------------------------------
template<typename T>
inline ThreadSpecificStorage<T>::~ThreadSpecificStorage ()
{
delete m_impl;
}
////////////////////////////////////////////////////////////////////////////////
// Operator overloading
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// operator =
// -----------------------------------------------------------------------------
template<typename T>
inline const ThreadSpecificStorage<T>& ThreadSpecificStorage<T>::operator = (const ThreadSpecificStorage<T>& rhs)
{
if (m_impl != rhs.m_impl) {
if (m_impl != nullptr) {
delete m_impl;
}
m_impl = rhs.m_impl->Clone ();
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// Operations
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// Get
// -----------------------------------------------------------------------------
template<typename T>
inline T ThreadSpecificStorage<T>::Get () const
{
#if defined (_MSC_VER)
#pragma warning(push)
#pragma warning (disable: 4311 4800)
#endif
return T (m_impl->Get ());
#if defined (_MSC_VER)
#pragma warning(pop)
#endif
}
// -----------------------------------------------------------------------------
// Set
// -----------------------------------------------------------------------------
template<typename T>
inline void ThreadSpecificStorage<T>::Set (T value)
{
#if defined (_MSC_VER)
#pragma warning(push)
#pragma warning (disable: 4312 4800)
#endif
m_impl->Set (IntPtr (value));
#if defined (_MSC_VER)
#pragma warning(pop)
#endif
}
}
#endif // GS_THREADSPECIFICSTORAGE_HPP
| true |
6f856f3c59e8873537f2ad9bb74d225ea1d063b6 | C++ | pochka15/OpenGL-GKOM | /gkom-gl/zs2_dzwig/Vertex.h | UTF-8 | 436 | 2.984375 | 3 | [] | no_license | #pragma once
#include <glm/glm.hpp>
class Vertex
{
public:
glm::vec3 Position;
glm::vec3 Color;
glm::vec2 TextureCoords;
Vertex()
{
}
Vertex(glm::vec3 position)
: Position(position)
{
}
Vertex(glm::vec3 position, glm::vec3 color)
: Position(position), Color(color)
{
}
Vertex(glm::vec3 position, glm::vec3 color, glm::vec2 textureCoords)
: Position(position), Color(color), TextureCoords(textureCoords)
{
}
}; | true |
7c626f81e1a1ab68bc84bc06d92f6259985ebd45 | C++ | azcbuell/mixr | /include/mixr/simulation/AbstractPlayer.inl | UTF-8 | 3,004 | 2.625 | 3 | [] | no_license | //------------------------------------------------------------------------------
// Class: AbstractPlayer
// Description: inline functions
//------------------------------------------------------------------------------
#ifndef __mixr_models_AbstractPlayer_Inline__
#define __mixr_models_AbstractPlayer_Inline__
// True if player's ID matches
inline bool AbstractPlayer::isID(const unsigned short tst) const
{
return (tst == id);
}
// The player's ID
inline unsigned short AbstractPlayer::getID() const
{
return id;
}
//-----------------------------------------------------------------------------
// True if the player's name matches
inline bool AbstractPlayer::isName(const base::Identifier* const tst) const
{
return (*tst == pname);
}
// True if the player's name matches
inline bool AbstractPlayer::isName(const char* const tst) const
{
return (tst == pname);
}
// The player's name
inline const base::Identifier* AbstractPlayer::getName() const
{
return &pname;
}
//-----------------------------------------------------------------------------
// Current mode ( INACTIVE, ACTIVE, DETONATED ... )
inline AbstractPlayer::Mode AbstractPlayer::getMode() const
{
return mode;
}
// True if player's mode is active
inline bool AbstractPlayer::isActive() const
{
return mode == ACTIVE;
}
// True if player's mode is killed
inline bool AbstractPlayer::isKilled() const
{
return (mode == KILLED);
}
// True if player's mode is crashed
inline bool AbstractPlayer::isCrashed() const
{
return (mode == CRASHED);
}
// True if player has detonated (weapons only)
inline bool AbstractPlayer::isDetonated() const
{
return (mode == DETONATED);
}
// True if player's mode is inactive
inline bool AbstractPlayer::isInactive() const
{
return mode == INACTIVE;
}
// True if player is currently this mode
inline bool AbstractPlayer::isMode(const Mode tst) const
{
return mode == tst;
}
// True if player is not currently this mode
inline bool AbstractPlayer::isNotMode(const Mode tst) const
{
return mode != tst;
}
// True if player's mode is dead
inline bool AbstractPlayer::isDead() const
{
return isKilled() || isCrashed() || isDetonated();
}
//-----------------------------------------------------------------------------
// True if this is a networked player
inline bool AbstractPlayer::isNetworkedPlayer() const
{
return (nib != nullptr);
}
// True if this is a local player
inline bool AbstractPlayer::isLocalPlayer() const
{
return (nib == nullptr);
}
// ID of a networked player's controlling network model
inline int AbstractPlayer::getNetworkID() const
{
return netID;
}
// Networked player's Nib object
inline AbstractNib* AbstractPlayer::getNib()
{
return nib;
}
// Networked player's Nib object (const version)
inline const AbstractNib* AbstractPlayer::getNib() const
{
return nib;
}
// is player output to the network enabled?
inline bool AbstractPlayer::isNetOutputEnabled() const
{
return enableNetOutput;
}
#endif
| true |
d78d4010b1f58c46b21f00f291328f3e7efae5a9 | C++ | BhawanaWadhwani/InterviewBit | /Math/Find Nth Fibonacci.cpp | UTF-8 | 1,599 | 2.84375 | 3 | [] | no_license | // [ F1 F2 ] * Transition Matrix = [F2 F3]
// [ F1 F2 ] * [ P Q ] = [F2 F3]
// [ R S ]
// F1 * P + F2 * R = F2
// F1 * Q + F2 * S = F3 (F1 + F2)
//we get P=0 && R=1
//and Q=1 && S=1
// [ F1 F2 ] * [ 0 1 ] = [F2 F3]
// [ 1 1 ]
// [ F1 F2 ] * [ 0 1 ] ^ (n-1) = [Fn Fn+1]
// [ 1 1 ]
#define ll long long
#define mod 1000000007
ll Identity_Matrix[3][3]; //1 based indexing
ll Transition_Matrix[3][3];
void mul(ll A[3][3], ll B[3][3], ll dimension)
{
ll ans[dimension+1][dimension+1];
for(int i=1;i<=dimension;i++)
{
for(int j=1;j<=dimension;j++)
{
ans[i][j]=0;
for(int k=1;k<=dimension;k++)
{
ans[i][j]+=((A[i][k]*B[k][j])%mod);
}
}
}
for(int i=1;i<=dimension;i++)
{
for(int j=1;j<=dimension;j++)
{
A[i][j]=ans[i][j];
}
}
}
int Solution::solve(int A)
{
if(A<=2)
return 1;
Identity_Matrix[1][1]=Identity_Matrix[2][2]=1;
Identity_Matrix[1][2]=Identity_Matrix[2][1]=0;
Transition_Matrix[1][1]=0;
Transition_Matrix[1][2]=Transition_Matrix[2][1]=Transition_Matrix[2][2]=1;
A--;
while(A)
{
if(A%2==1)
{
mul(Identity_Matrix, Transition_Matrix, 2);
A--;
}
else
{
mul(Transition_Matrix, Transition_Matrix, 2);
A/=2;
}
}
// F1 * I[1][1] + F2 * I[2][1] ...here F1 = F2 =1
ll x=(Identity_Matrix[1][1]+Identity_Matrix[2][1])%mod;
return x;
}
| true |
c3351951122bbcf7ae6be38ec273984074d6b363 | C++ | snehalmparmar/CPP_Algorithms | /Variant_Parity.cpp | UTF-8 | 864 | 3.140625 | 3 | [] | no_license | #include "Variant_Parity.h"
#include <iostream>
#include <cmath>
/* This algorithm takes O(n) time
unsigned Variant1_Parity(unsigned long x) {
unsigned long result{ 1 };
short count{ 0 };
unsigned long y{ x };
while (result ^= (x & 1)) { //O(n)
//result ^= (x & 1);
count++; //O(1)
x >>= 1;//O(1)
}
return (x = y + (pow(2, count) - 1));//O(1)
}*/
//checkout the link for other bit operations: https://gist.github.com/stephenLee/4024869
unsigned Variant1_Parity(unsigned long x, int n=1) {
//unsigned long result{ 1 };
//x |= (x - 1);//O(1). Right propagate the rightmost set bit in x, e.g, turns (0101 0000) to (0101 1111)
//x %= unsigned(pow(2, n));//O(1). Compute x mode power of 2, e,g., returns 13 for 77 mod 64
x = ((x % 2) == 0); //O(1). Test if x is power of 2, i.e., evaluates to true for x = 1,2,4,6,7....false for all others.
return x;
} | true |
9bd21e9ec07fc0327a8a9e9cf03736081476fe4d | C++ | asokolov1104/vs2019repo | /cnsVirtFunc/mainVirtFunc.cpp | UTF-8 | 411 | 3.15625 | 3 | [] | no_license | //
#include <iostream>
//
int main()
{
class Base
{
virtual void method() { std::cout << "called from Based" << std::endl; }
public:
virtual ~Base() { method(); }
void baseMethod() { method(); }
};
class A : public Base
{
void method() { std::cout << "called from A \n" << std::endl; }
public:
~A() { method(); }
};
Base* pBase = new A;
pBase->baseMethod();
delete pBase;
return 0;
} | true |
3c623f5ceeebe2095eaf46cc2f1e9fd0d6f2f91d | C++ | coder965/flame | /src/flame/spare_list.h | UTF-8 | 2,448 | 2.546875 | 3 | [
"MIT"
] | permissive | //MIT License
//
//Copyright (c) 2018 wjs
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
#pragma once
#include <map>
#include <vector>
#include <list>
#include <functional>
namespace flame
{
class SpareList
{
protected:
unsigned int capacity;
std::map<void*, int> map;
std::list<int> spare_list;
public:
SpareList(unsigned int _capacity) :
capacity(_capacity)
{
for (int i = 0; i < capacity; i++)
spare_list.push_back(i);
}
int get_capacity() const
{
return capacity;
}
int get_size() const
{
return map.size();
}
int add(void *p)
{
{
auto it = map.find(p);
if (it != map.end())
return -2;
}
if (spare_list.size() == 0)
return -1;
{
auto it = spare_list.begin();
auto index = *it;
map[p] = index;
spare_list.erase(it);
return index;
}
}
void remove(void *p)
{
auto it = map.find(p);
if (it == map.end())
return;
auto index = it->second;
map.erase(it);
spare_list.push_back(index);
}
void iterate(const std::function<bool(int index, void *p, bool &remove)>
&callback)
{
for (auto it = map.begin(); it != map.end(); )
{
bool remove = false;
auto index = it->second;
auto _continue = callback(index, it->first, remove);
if (remove)
{
it = map.erase(it);
spare_list.push_back(index);
}
else
it++;
if (!_continue)
break;
}
}
};
}
| true |
3c350c74668bb50f8a8ad7165fddad7b0ab11f3f | C++ | raobystorm/algorithms | /LCOJ_223/LCOJ_223.cpp | UTF-8 | 453 | 2.75 | 3 | [] | no_license | // LCOJ_223.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
if (E >= C || G <= A || B >= H || F >= D)
return (C - A)*(D - B) + (G - E)*(H - F);
else
return (C - A)*(D - B) + (G - E)*(H - F) - abs(max(A, E) - min(C, G))*abs(max(B, F) - min(D, H));
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| true |
febff2461151d2a7519f9022e346ee04904e2654 | C++ | tachyon83/code-rhino | /DAY450~499/DAY482-PROGRAMMERS오픈채팅방/bumjin.cpp | UTF-8 | 987 | 3.09375 | 3 | [] | no_license | #include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;
vector<string> solution(vector<string> record) {
vector<string> answer, state;
map<string, string> user;
for(int i = 0; i < record.size(); i++)
{
string str[3];
string token;
stringstream ss(record[i]);
int index = 0;
while(ss >> token)
str[index++] = token;
if(str[0] == "Enter")
{
state.push_back("님이 들어왔습니다.");
answer.push_back(str[1]);
user[str[1]] = str[2];
}
else if(str[0] == "Leave")
{
state.push_back("님이 나갔습니다.");
answer.push_back(str[1]);
}
else
user[str[1]] = str[2];
}
for(int i = 0; i < answer.size(); i++)
answer[i] = user[answer[i]] + state[i];
return answer;
}
| true |
fe89da4d1bc2a03fa6cb45160c68cc02d4b88df0 | C++ | VijayEluri/ads | /cpp/sorting/mergesort.cpp | UTF-8 | 1,744 | 3.859375 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <queue>
using namespace std;
template <class T>
void print(const T &data) {
cout << " " << data;
}
/* Sort a vector of type T
*
* Copying a vector around like this (i.e. v = mergesort(...)) is
* highly inefficient, the right way would be to use pointers or
* iterators but still this way is more readable and easier to
* understand.
*
* I would never write a thing like this in Real Code.
*/
template <class T>
vector<T> mergesort(vector<T> v, int from_idx, int to_idx) {
int i;
if (from_idx < to_idx) {
int middle = (from_idx + to_idx) / 2;
v = mergesort(v, from_idx, middle);
v = mergesort(v, middle + 1, to_idx);
/* merge the two lists, the former from from_idx to middle
* and the latter from middle + 1 to to_idx
*/
queue<T> q1, q2;
for (i = from_idx; i <= middle; i++) q1.push(v[i]);
for (i = middle + 1; i <= to_idx; i++) q2.push(v[i]);
i = from_idx;
while (!(q1.empty() || q2.empty())) {
if (q1.front() <= q2.front()) {
v[i++] = q1.front();
q1.pop();
} else {
v[i++] = q2.front();
q2.pop();
}
}
while (!q1.empty()) { v[i++] = q1.front(); q1.pop(); };
while (!q2.empty()) { v[i++] = q2.front(); q2.pop(); };
}
return v;
}
int
main(int argc, char **argv) {
vector<int> v(8);
v[0] = 1;
v[1] = 14;
v[2] = 82;
v[3] = 62;
v[4] = 5;
v[5] = 75;
v[6] = 24;
v[7] = 55;
cout << "Before: ";
for_each(v.begin(), v.end(), print<int>);
cout << endl;
v = mergesort(v, 0, v.size() - 1);
cout << " After: ";
for_each(v.begin(), v.end(), print<int>);
cout << endl;
return EXIT_SUCCESS;
}
| true |
96e95bcc4e36ecc0a1560ab974ab525cc6b3e67c | C++ | ranshiwei/Leetcode | /ReversePolishNotation.cpp | UTF-8 | 1,135 | 3.34375 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <stack>
#include <vector>
#include<boost/regex.hpp>
#include <stdlib.h>
using namespace std;
class Solution{
public:
int evalRPN(vector<string> &tokens)
{
first = tokens.begin();
last = tokens.end();
while(first != last)
{
if(Regex.match(*first,pattren))
{
cout<<"This is a number";
numst.push(atoi(*first));
}
else
{
front = numst.top();
numst.pop();
last = numst.top();
numst.pop();
if(Regex.match(*first,"+"))
{
numst.push(front+last);
}else if(Regex.match(*first,"-"))
{
numst.push(front-last);
}else if(Regex.match(*first,"*"))
{
numst.push(front*last);
}else if(Regex.match(*first,"/"))
{
if(last != 0)
numst.push(front/last);
}
}
first++;
}
return numst.top();
}
private:
vector<string>::iterator first,last;
stack<int> numst;
string pattern = "^-?/d+$";
int front,back;
};
int main(int argc,char *argv[])
{
Solution s;
vector<string> ss = {"1","1","+"};
int result = s.evalRPN(ss);
cout<<result<<endl;
}
| true |
a7cfdf08db97d683f0c0123b6dd1372d61178884 | C++ | joostrijneveld/Euler-Project | /problem79.cpp | UTF-8 | 1,176 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#include <string>
#include <sstream>
#include "bigint/BigIntegerLibrary.hh"
using namespace std;
string int2str (int n) {
stringstream ss;
ss << n;
return ss.str();
}
int str2int (string str) {
stringstream ss(str);
int n;
ss >> n;
return n;
}
int main () {
string digits[] = { "319","680","180","690","129","620","762","689","762","318","368","710","720","710","629","168","160","689","716","731","736","729","316","729","729","710","769","290","719","680","318","389","162","289","162","718","729","319","790","680","890","362","319","760","316","729","380","319","728","716" };
string temp;
int a,b,c;
bool flag;
for (int i=100;i<1000000000;i++) {
flag = true;
for (int j=0;j<50;j++) {
temp = int2str(i);
a = temp.find(digits[j].substr(0,1));
if (a + 1 > 0) {
b = temp.find(digits[j].substr(1,1), a);
if (b + 1 > 0) {
c = temp.find(digits[j].substr(2,1), b);
if (c + 1 == 0) {
flag = false;
break;
}
}
else {
flag = false;
break;
}
}
else {
flag = false;
break;
}
}
if (flag == true) {
cout << i;
break;
}
}
return 0;
} | true |
57a8463b7262efd78389dcae985b1fad4113b99d | C++ | Shristy-Gupta/Leetcode-top-interview-q | /palindrome LCS.cpp | UTF-8 | 1,262 | 2.796875 | 3 | [
"MIT"
] | permissive | #include<string.h>
class Solution {
public:
string longestPalindrome(string s) {
//https://www.youtube.com/watch?v=wuOOOATz_IA&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go&index=26
if(s.length()<1){return s;}
if(s.length()==1){return s;}
string t=s;
reverse(t.begin(),t.end());
string ans="";
int n=s.length();
int dp[n+1][n+1];
for(int i=0;i<=n;i++){
dp[i][0]=0;
dp[0][i]=0;
}
//cout<<s<<" "<<t<<endl;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(s[i-1]==t[j-1]){
//cout<<s[i-1]<<" "<<t[j-1]<<endl;
//ans+=s[i-1];
dp[i][j]=1+dp[i-1][j-1];
}
else{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}
int i=n,j=n;
while(i>0 && j>0){
if(s[i-1]==t[j-1]){
ans+=s[i-1];
i--;j--;
}
else{
if(dp[i-1][j]>dp[i][j-1]){
i--;
}
else{
j--;
}
}
}
return ans;
}
};
| true |
832979129cb7defbee5f5c098aabf0b097941f26 | C++ | ZhaohuiSun/About_Tree | /About_Tree.cpp | UTF-8 | 4,443 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include<stack>
#include<queue>
#include<fstream>
#include<cstdlib>
using namespace std;
//定义节点
typedef struct node
{
struct node *lchild;
struct node *rchild;
char data;
}BiTreeNode, *BiTree;
//按照前序顺序建立二叉树
void createBiTree(BiTree &T) //&的意思是传进来节点指针的引用,括号内等价于 BiTreeNode* &T,目的是让传递进来的指针发生改变
{
char c;
cin >> c;
if ('#' == c) //当遇到#时,令树的根节点为NULL,从而结束该分支的递归
T = NULL;
else
{
T = new BiTreeNode;
T->data = c;
createBiTree(T->lchild);
createBiTree(T->rchild);
}
}
//前序遍历二叉树并打印
void preTraverse(BiTree T)
{
stack<BiTreeNode*> s;
BiTreeNode* p = T;
while (p || !s.empty())
{
if (p)
{
cout << p->data << ' ';
s.push(p);
p = p->lchild;
}
else
{
p = s.top()->rchild;
s.pop();
}
}
}
//中序遍历二叉树并打印
void midTraverse(BiTree T)
{
stack<BiTreeNode*> s;
BiTreeNode* p = T;
while (p || !s.empty())
{
if (p)
{
s.push(p);
p = p->lchild;
}
else
{
cout << s.top()->data << ' ';
p = s.top()->rchild;
s.pop();
}
}
}
//后续遍历二叉树并打印
void postTraverse(BiTree T)
{
BiTreeNode* pre = nullptr;
BiTreeNode* cur = T;
stack<BiTreeNode*> s;
s.push(cur);
while (!s.empty())
{
cur = s.top();
if ((!cur->lchild && !cur->rchild) || pre &&((pre == cur->lchild || pre == cur->rchild)))
{ // 确保可以正确输出第一个节点(例如:在左斜树中,pre初始化就是NULL,
// cur指向的第一个节点的right指针也是NULL,只判断pre==cur->right的话就会直接输出根节点)。
cout << cur->data << ' ';
pre = cur;
s.pop();
}
else
{
if (cur->rchild) //先入栈右节点,再入左节点,出站在前面的才是左节点
s.push(cur->rchild);
if (cur->lchild)
s.push(cur->lchild);
}
}
}
void LevelOrder(BiTree T)
{
BiTreeNode* p=T;
queue<BiTreeNode*> q;
q.push(p);
while (!q.empty())
{
p = q.front();
cout << p->data << ' ';
q.pop();
if (p->lchild != NULL)
q.push(p->lchild);
if (p->rchild != NULL)
q.push(p->rchild);
}
}
int CountNodes(BiTree T)
{
if (T == NULL)
return 0;
return CountNodes(T->lchild) + CountNodes(T->rchild) + 1;
//非递归方法可通过前序遍历实现
}
BiTreeNode* FindLCA(BiTree T, BiTreeNode * target1, BiTreeNode * target2) //求两个节点的最低公共祖先节点
{
if (T == nullptr)
return nullptr;
if (T == target1 || T == target2)
return T;
BiTreeNode * left = FindLCA(T->lchild, target1, target2);
BiTreeNode * right = FindLCA(T->rchild, target1, target2);
if (left && right) //分别在左右子树
return T;
return left ? left : right; //都在左子树或右子树
}
int GetDepth(BiTree T,BiTreeNode* target) //得到树中某一点的深度
{
if (T == target)
return 0;
if (T == NULL)
return -999999;
int left_depth = GetDepth(T->lchild, target) + 1;
int right_depth = GetDepth(T->rchild, target) + 1;
return left_depth > right_depth ? left_depth : right_depth;
}
void Distance_of_Nodes(BiTree T, BiTreeNode * target1, BiTreeNode* target2) //求两节点之间的距离转化为先求
{
BiTreeNode* p = FindLCA(T, target1, target2); //最低公共祖先节点,然后求以此节点为根的子树下
cout << "两个节点之间的距离为:" << GetDepth(p, target1) + GetDepth(p, target2); //两节点所在深度的和
}
int main()
{
BiTree T; //声明一个指向二叉树根节点的指针
createBiTree(T);
cout << "二叉树创建完成!" << endl;
cout << "前序遍历二叉树:" << endl;
preTraverse(T);
cout << endl;
cout << "中序遍历二叉树:" << endl;
midTraverse(T);
cout << endl;
cout << "后序遍历二叉树:" << endl;
postTraverse(T);
cout << endl;
cout << "层次遍历二叉树:" << endl;
LevelOrder(T);
cout << endl;
cout << "二叉树共有 " << CountNodes(T) << " 个节点";
cout << endl;
BiTreeNode * target1=T->rchild->rchild;
BiTreeNode * target2=T->rchild->lchild->lchild;
cout<<"测试用例中的公共节点:"<<FindLCA(T, target1, target2)->data;
cout << endl;
cout << "target2 的深度:" << GetDepth(T, target2);
cout << endl;
Distance_of_Nodes(T, target1, target2);
cout << endl;
system("pause");
return 0;
}
| true |
7360487a08bbc1debfed87a03c5336abd0f38833 | C++ | warguss/ProjectRTS | /ServerRoot/server2N/server/include/common/CUser.cpp | UTF-8 | 828 | 2.5625 | 3 | [] | no_license | #include "CUser.h"
CUser::CUser()
{
_x = 0;
_y = 0;
_accelX = 0;
_accelY = 0;
_killInfo = 0;
_deathInfo = 0;
_nickName = "unknown";
_fd = 0;
_health_point = 0;
_score = 0;
}
CUser::CUser(int fd, int32_t x, int32_t y)
{
_x = 0;
_y = 0;
_accelX = 0;
_accelY = 0;
_score = 0;
_fd = fd;
_x = x;
_y = y;
}
CUser::~CUser()
{
}
bool CUser::setData(int fd, int type)
{
_fd = fd;
_type = type;
return true;
}
void CUser::userKillDeathScoreCalc()
{
int32_t tmpKillInfo = _killInfo;
if ( tmpKillInfo < 0 )
{
tmpKillInfo = 0;
}
int32_t tmpDeathInfo = _deathInfo;
if ( tmpDeathInfo < 0 )
{
tmpDeathInfo = 0;
}
_score = (tmpKillInfo * 3) + (tmpDeathInfo * -2);
LOG_DEBUG("User(%d:%s) Kill(%d) Death(%d) Score(%d)", _fd, _nickName.c_str(), _killInfo, _deathInfo, _score);
}
| true |
55286c02f0e79d60b4a535b748f192a5da768b6b | C++ | Mikeiladay/TP_lab_1 | /TP_1_12/checkInput.cpp | WINDOWS-1251 | 1,254 | 3.265625 | 3 | [] | no_license | #include "checkInput.h"
bool isInt(char c)
{
if (c >= '0' && c <= '9')
return true;
else
return false;
}
bool isSplit(char c)
{
if (c == '.' || c == '/')
return true;
else
return false;
}
bool isInt(string s)
{
if (s.size() < 1)
return false;
for (int i = 0; i < s.size(); i++)
if (s[i] < '0' || s[i] > '9')
return false;
return true;
}
bool checkDate(string date)
{
if (date.size() == 10)
{
if (isInt(date[0]) && isInt(date[1]) && isSplit(date[2]) &&
isInt(date[3]) && isInt(date[4]) && isSplit(date[5]) &&
isInt(date[6]) && isInt(date[7]) && isInt(date[8]) && isInt(date[9]))
return true;
}
return false;
}
int inputInt(int minInput, int maxInput) {
while (true)
{
int method;
std::cin >> method;
if (std::cin.fail() || method < minInput || method > maxInput)
{
std::cin.clear();
std::cout << " .\n : ";
}
else
{
std::cin.ignore(32767, '\n');
std::cin.clear();
return method;
}
std::cin.ignore(32767, '\n');
}
}
string inputDate()
{
while (true)
{
string date;
getline(cin, date);
if (checkDate(date))
return date;
cout << " . : ";
}
} | true |
91e747c9181c6b9f61d34bde0ebab18d3af6e51c | C++ | xianjimli/Elastos | /Elastos/LibCore/src/Elastos/Net/Apache/Protocol/Http/CFixedLengthOutputStream.cpp | UTF-8 | 1,623 | 2.671875 | 3 | [] | no_license |
#include "CFixedLengthOutputStream.h"
ECode CFixedLengthOutputStream::Close()
{
// TODO: Add your code here
if (mClosed) {
return NOERROR;
}
mClosed = TRUE;
if (mBytesRemaining > 0) {
return E_IO_EXCEPTION;
};
return NOERROR;
}
ECode CFixedLengthOutputStream::Flush()
{
// TODO: Add your code here
if (mClosed) {
return NOERROR; // don't throw; this stream might have been closed on the caller's behalf
}
return mSocketOut->Flush();
}
ECode CFixedLengthOutputStream::Write(
/* [in] */ Int32 oneByte)
{
// TODO: Add your code here
return E_NOT_IMPLEMENTED;
}
ECode CFixedLengthOutputStream::WriteBuffer(
/* [in] */ const ArrayOf<Byte> & buffer)
{
// TODO: Add your code here
return E_NOT_IMPLEMENTED;
}
ECode CFixedLengthOutputStream::WriteBufferEx(
/* [in] */ Int32 offset,
/* [in] */ Int32 count,
/* [in] */ const ArrayOf<Byte> & buffer)
{
// TODO: Add your code here
CheckNotClosed();
CheckBounds(buffer, offset, count);
if (count > mBytesRemaining) {
return E_IO_EXCEPTION;
}
mSocketOut->WriteBufferEx(offset, count, buffer);
mBytesRemaining -= count;;
return NOERROR;
}
ECode CFixedLengthOutputStream::CheckError(
/* [out] */ Boolean * pHasError)
{
// TODO: Add your code here
return E_NOT_IMPLEMENTED;
}
ECode CFixedLengthOutputStream::constructor(
/* [in] */ IOutputStream * pSocketOut,
/* [in] */ Int32 bytesRemaining)
{
// TODO: Add your code here
mSocketOut = pSocketOut;
mBytesRemaining = bytesRemaining;
return NOERROR;
}
| true |
d55d381b25eb6eea43f86b98e4d9ca9f419cf0c9 | C++ | felixsoum/420J11AS-CppPractice | /CppPractice/CppPractice/Hero.h | UTF-8 | 227 | 2.640625 | 3 | [] | no_license | #include "Monster.h"
#include <memory>
class Hero
{
public:
void attack(const Monster* monster) const;
void attack(std::shared_ptr<Monster> monster);
void attack(std::unique_ptr<Monster>& monster);
private:
int level;
};
| true |
9a1b77311efdbb54579fbd13ad1236be6fc4d1e6 | C++ | emiruner/simge-examples | /polylineeditor/Editor.hpp | UTF-8 | 3,219 | 2.796875 | 3 | [] | no_license | #ifndef MY_EDITOR_HPP_INCLUDED
#define MY_EDITOR_HPP_INCLUDED
#include <simge/glut/Planar.hpp>
#include <simge/util/Polyline.hpp>
#include <vector>
#include <string>
typedef simge::util::Polyline<simge::geom::Point<2> > Polyline2D;
typedef std::vector<Polyline2D> Polyline2DVec;
struct EditorState;
class Editor : public simge::glut::Planar
{
public:
Editor(char const* name, char const* filename);
~Editor();
Polyline2DVec const& getLines() const
{
return lines_;
}
Polyline2DVec& getLines()
{
return lines_;
}
protected:
void paintGL();
void keyboardGL(unsigned char key, int x, int y);
void mouseGL(int button, int state, int x, int y);
void passiveMotionGL(int x, int y);
void motionGL(int x, int y);
private:
std::string file_;
Polyline2DVec lines_;
EditorState* state_;
friend struct EditorState;
void changeState(EditorState* newState)
{
state_ = newState;
}
};
/**
* Serves both as a base state class and idle state.
*/
struct EditorState
{
static EditorState instance_;
static EditorState* instance() { return &instance_; }
virtual ~EditorState()
{
}
virtual void onKeypress(Editor* editor, unsigned char key, int x, int y);
virtual void onMouseDown(Editor* editor, int button, int x, int y) {}
virtual void onMouseMove(Editor* editor, int x, int y) {}
virtual void onMouseUp(Editor* editor, int button, int x, int y) {}
virtual void onPaint(Editor* editor);
/**
* Do steps required before being selected as the new state.
* This is required because we are a singleton.
*/
virtual void beforeChange(Editor* editor) {}
protected:
void changeState(Editor* editor, EditorState* newState)
{
newState->beforeChange(editor);
editor->changeState(newState);
}
};
struct UserDrawingState : public EditorState
{
static UserDrawingState instance_;
static UserDrawingState* instance() { return &instance_; }
void beforeChange(Editor*)
{
current_.color = simge::util::Color::red();
current_.points.clear();
oldx_ = -1;
}
void onKeypress(Editor* editor, unsigned char key, int x, int y);
void onPaint(Editor* editor);
void onMouseDown(Editor* editor, int button, int x, int y);
void onMouseMove(Editor* editor, int x, int y);
Polyline2D current_;
int oldx_;
int oldy_;
};
struct DeletePointState : public EditorState
{
static DeletePointState instance_;
static DeletePointState* instance() { return &instance_; }
void onMouseDown(Editor* editor, int button, int x, int y);
};
struct MovePointState : public EditorState
{
static MovePointState instance_;
static MovePointState* instance() { return &instance_; }
void beforeChange(Editor*)
{
idx = -1;
}
void onMouseDown(Editor* editor, int button, int x, int y);
void onMouseUp(Editor* editor, int button, int x, int y);
void onMouseMove(Editor* editor, int x, int y);
void onPaint(Editor* editor);
int idx;
Polyline2DVec::iterator line;
};
#endif
| true |
1d5dc4abceaadc90ed12443d2f71d2727f5dea4e | C++ | aanoguchi/ECC_CS1_F19 | /Quizzes/Q8.cpp | UTF-8 | 2,559 | 4.0625 | 4 | [] | no_license | // Purpose: Take in the text and be able to find the most common word and output
// it.
// Input:
// txt - String of words separated by spaces where a word consists of
// alpha-numeric characters.
// Output: The most frequent word in the string
string most_common_word(string txt);
// Tests
// ---
// Input Output
// "The cat ate the food" "the"
// "The cat ate the cat food" "the"
// "thecatatethecatfood" "thecatatethecatfood"
// " " ""
// "20 cats ate 20 biscuits" "20"
// "dddd" "dddd"
// "A B C D D" "D"
// "Cat the cat" "cat"
// "hello hello cat" "hello"
// Template
// int i = 0;
// while(i < s.length()){
// ..s[i]..
// i = i + 1;
// }
//Pseudo Code
//* identify words and separate them into a list.
//** until we run out of words.
//** find the last word.
//*** find the last letter.
//*** find the first letter of the last word.
//*** get the substring between the first and last letter.
//** transfer word to list.
//** chop off the last word.
//* find the most frequent word in the list of words.
//** Count the amount of times each word appears.
//** Put it in a list in the same location as the first instance of the word.
//** Go back through the list of numbers and grab the highest one.
//** Identify the word associated with that number.
string most_common_word(string txt){
vector<string> words = split_by_word(txt);
string word = most_frequent(words);
return word;
}
// Identify words and separate them into a list.
vector<string> split_by_word(string txt){
int i = txt.length() - 1;
vector<string> words = [];
//** until we run out of words.
while (i >= 0){
//*** find the last word.
words.push_back(find_last_word())
//**** find the last letter.
//**** find the first letter of the last word.
//**** get the substring between the first and last letter.
i = i - 1;
}
//** transfer word to list.
//** chop off the last word.
}
string find_last_word(string txt) {
int i = txt.length() - 1;
string word;
while(i >= 0 && alpha_numeric(txt[i])) {
i = i - 1;
}
get_substring(txt, i, txt.length());
return word;
}
//* find the most frequent word in the list of words.
string most_frequent(vector<string> words){
}
//** Count the amount of times each word appears.
//** Put it in a list in the same location as the first instance of the word.
//** Go back through the list of numbers and grab the highest one.
//** Identify the word associated with that number.
| true |
d79b57be9a7aefb6d3b58652786e43d0c2c817d6 | C++ | DionysiosB/LeetCode | /26-RemoveDuplicatesFromSortedArray.cpp | UTF-8 | 346 | 2.734375 | 3 | [] | no_license | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0){return 0;}
int index(0);
for(int p = 1; p < nums.size(); p++){
if(nums[p] != nums[index]){
++index;
nums[index] = nums[p];
}
}
return (index + 1);
}
};
| true |
ab69d6374691e512bed2eb5549e0898ff5e78c6c | C++ | zyzkevin/Introduction-to-Computing | /Big Homework/bot2.cpp | UTF-8 | 9,932 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include<cmath>
#include <string>
#include <queue>
#include <cstdlib>
#include <ctime>
#include <cstring>
#define GRIDSIZE 8
#define OBSTACLE 2
#define grid_black 1
#define grid_white -1
using namespace std;
double K = 0.2;
int currBotColor;
int gridInfo[GRIDSIZE][GRIDSIZE] = { 0 };
int dx[8] = { -1,-1,-1,0,0,1,1,1 };
int dy[8] = { -1,0,1,-1,1,-1,0,1 };
int Qwhite[GRIDSIZE][GRIDSIZE] = { 0 };
int Qblack[GRIDSIZE][GRIDSIZE] = { 0 };
int Kwhite[GRIDSIZE][GRIDSIZE] = { 0 };
int Kblack[GRIDSIZE][GRIDSIZE] = { 0 };
int temp[GRIDSIZE][GRIDSIZE] = { 0 };
int mobility[GRIDSIZE][GRIDSIZE] = { 0 };
struct position
{
int x, y;
int s;
};
int visK_W[GRIDSIZE][GRIDSIZE] = { 0 }, visK_B[GRIDSIZE][GRIDSIZE] = { 0 };
int visQ_W[GRIDSIZE][GRIDSIZE] = { 0 }, visQ_B[GRIDSIZE][GRIDSIZE] = { 0 };
inline bool inMap(int x, int y)
{
if (x >= 0 && x < GRIDSIZE&&y >= 0 && y < GRIDSIZE)
return true;
else
return false;
}
void K_move_W(position pre)
{
position st, next;
queue<position>W;
W.push(pre);
while (!W.empty())
{
st = W.front();
W.pop();
for (int k = 0; k < 8; k++)
{
next.x = st.x + dx[k];
next.y = st.y + dy[k];
next.s = st.s + 1;
if (temp[next.x][next.y] == 0 && visK_W[next.x][next.y] == 0 && inMap(next.x, next.y))
{
Kwhite[next.x][next.y] = min(Kwhite[next.s][next.y], next.s);
visK_W[next.x][next.y] = 1;
W.push(next);
}
}
}
}
void Q_move_W(position pre)
{
position st, next;
queue<position>W;
W.push(pre);
while (!W.empty())
{
st = W.front();
W.pop();
for (int k = 0; k < 8; k++)
{
next.x = st.x;
next.y = st.y;
next.s = st.s + 1;
while (1)
{
next.x += dx[k];
next.y += dy[k];
if (visQ_W[next.x][next.y] == 1)
{
continue;
}
if (temp[next.x][next.y] == 0 && visQ_W[next.x][next.y] == 0 && inMap(next.x, next.y))
{
Qwhite[next.x][next.y] = min(Qwhite[next.x][next.y], next.s);
visQ_W[next.x][next.y] = 1;
W.push(next);
}
else
break;
}
}
}
}
void K_move_B(position pre)
{
position st, next;
queue<position>B;
B.push(pre);
while (!B.empty())
{
st = B.front();
B.pop();
for (int k = 0; k < 8; k++)
{
next.x = st.x + dx[k];
next.y = st.y + dy[k];
next.s = st.s + 1;
if (temp[next.x][next.y] == 0 && visK_B[next.x][next.y] == 0 && inMap(next.x, next.y))
{
Kblack[next.x][next.y] = min(Kblack[next.s][next.y], next.s);
visK_B[next.x][next.y] = 1;
B.push(next);
}
}
}
}
void Q_move_B(position pre)
{
position st, next;
queue<position>B;
B.push(pre);
while (!B.empty())
{
st = B.front();
B.pop();
for (int k = 0; k < 8; k++)
{
next.x = st.x;
next.y = st.y;
next.s = st.s + 1;
while (1)
{
next.x += dx[k];
next.y += dy[k];
if (visQ_B[next.x][next.y] == 1)
{
continue;
}
if (temp[next.x][next.y] == 0 && visQ_B[next.x][next.y] == 0 && inMap(next.x, next.y))
{
Qblack[next.x][next.y] = min(Qblack[next.x][next.y], next.s);
visQ_B[next.x][next.y] = 1;
B.push(next);
}
else
break;
}
}
}
}
double m()
{
double mob = 0;
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
mobility[i][j] = 0;
}
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
for (int k = 0; k < 8; k++)
{
if (i + dx[k] >= 0 && i + dx[k] < GRIDSIZE&&j + dy[k] >= 0 && j + dy[k] < GRIDSIZE)
{
if (temp[i + dx[k]][j + dy[k]] == 0)
{
mobility[i][j]++;
}
else
break;
}
}
}
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
if (temp[i][j] == 0)
{
for (int k = 0; k < 8; k++)
{
int m1 = i, m2 = j;
int count = 0;
while (1)
{
count++;
m1 += dx[k];
m2 += dy[k];
if (m1 >= 0 && m1 < GRIDSIZE&&m2 >= 0 && m2 < GRIDSIZE)
{
if (temp[m1][m2] == grid_black)
{
mob += mobility[i][j] / count * 1.0*currBotColor;
break;
}
else if (temp[m1][m2] == grid_white)
{
mob -= mobility[i][j] / count * 1.0*currBotColor;
break;
}
else if (temp[m1][m2] == OBSTACLE)
{
break;
}
else
continue;
}
else
break;
}
}
}
}
return mob;
}
void getMove()
{
position w;
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
if (temp[i][j] == grid_white)
{
w.x = i;
w.y = j;
w.s = 0;
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
visQ_W[i][j] = 0;
visK_W[i][j] = 0;
}
visQ_W[i][j] = 1;
visK_W[i][j] = 1;
Q_move_W(w);
K_move_W(w);
}
if (temp[i][j] == grid_black)
{
w.x = i;
w.y = j;
w.s = 0;
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
visQ_B[i][j] = 0;
visK_B[i][j] = 0;
}
visQ_B[i][j] = 1;
visK_B[i][j] = 1;
Q_move_B(w);
K_move_B(w);
}
}
}
double t1 = 0, t2 = 0, p1 = 0, p2 = 0, mob = 0;
void getValue()
{
double tempB = 1, tempW = 1;
t1 = t2 = p1 = p2 = mob = 0;
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
if (temp[i][j] == 0)
{
for (int k = 0; k < Qblack[i][j]; k++)
{
tempB *= 0.5;
}
for (int k = 0; k < Qwhite[i][j]; k++)
{
tempW *= 0.5;
}
p1 += (tempB - tempW)*currBotColor*1.0;
p2 += min(1.0, max(-1.0, ((Kwhite[i][j] - Kblack[i][j]) / 6.0)))*currBotColor*1.0;
if (Qblack[i][j] < Qwhite[i][j])
{
t1 += 1 * currBotColor;
}
if (Qblack[i][j] > Qwhite[i][j])
{
t1 -= 1 * currBotColor;
}
if (Qblack[i][j] == Qwhite[i][j] && Qblack[i][j] != 10000)
{
t1 -= K * currBotColor;
}
if (Kblack[i][j] < Kwhite[i][j])
{
t2 += 1 * currBotColor;
;
}
if (Kblack[i][j] > Kwhite[i][j])
{
t2 -= 1 * currBotColor;
}
if (Kblack[i][j] == Kwhite[i][j] && Kblack[i][j] != 10000)
{
t2 -= K * currBotColor;
}
}
}
p1 *= 2;
p2 *= 2;
mob = m();
}
double v(int turn)
{
double value = 0;
int turn1 = turn * 2;
if (currBotColor == grid_white)
{
if (turn1 <= 10)
{
value = 0.2*t1 + 0.48*t2 + 0.11*p1 + 0.11*p2 + 0.2*mob;
}
else if (turn1 >= 11 && turn1 <= 30)
{
value = 0.4*t1 + 0.25*t2 + 0.2*p1 + 0.2*p2 + 0.05*mob;
}
else if (turn1 >= 31)
{
value = 0.8*t1 + 0.1*t2 + 0.05*p1 + 0.05*p2;
}
}
else
{
if (turn1 <= 14)
{
value = 0.2*t1 + 0.48*t2 + 0.11*p1 + 0.11*p2 + 0.2*mob;
}
else if (turn1 >= 15 && turn1 <= 48)
{
value = 0.4*t1 + 0.25*t2 + 0.2*p1 + 0.2*p2 + 0.05*mob;
}
else if (turn1 >= 49)
{
value = 0.8*t1 + 0.1*t2 + 0.05*p1 + 0.05*p2;
}
}
return value;
}
bool Move(int x0, int y0, int x1, int y1, int x2, int y2, int color, bool check_only)
{
if ((!inMap(x0, y0)) || (!inMap(x1, y1)) || (!inMap(x2, y2)))
return false;
if (gridInfo[x0][y0] != color || gridInfo[x1][y1] != 0)
return false;
if ((gridInfo[x2][y2] != 0) && !(x2 == x0 && y2 == y0))
return false;
if (!check_only)
{
gridInfo[x0][y0] = 0;
gridInfo[x1][y1] = color;
gridInfo[x2][y2] = OBSTACLE;
}
return true;
}
int main()
{
int x0, y0, x1, y1, x2, y2;
gridInfo[0][(GRIDSIZE - 1) / 3] = gridInfo[(GRIDSIZE - 1) / 3][0]
= gridInfo[GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)][0]
= gridInfo[GRIDSIZE - 1][(GRIDSIZE - 1) / 3] = grid_black;
gridInfo[0][GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)] = gridInfo[(GRIDSIZE - 1) / 3][GRIDSIZE - 1]
= gridInfo[GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)][GRIDSIZE - 1]
= gridInfo[GRIDSIZE - 1][GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)] = grid_white;
int turnID;
cin >> turnID;
currBotColor = grid_white;
for (int i = 0; i < turnID; i++)
{
cin >> x0 >> y0 >> x1 >> y1 >> x2 >> y2;
if (x0 == -1)
currBotColor = grid_black;
else
{
Move(x0, y0, x1, y1, x2, y2, -currBotColor, false);
}
if (i < turnID - 1)
{
cin >> x0 >> y0 >> x1 >> y1 >> x2 >> y2;
if (x0 >= 0)
Move(x0, y0, x1, y1, x2, y2, currBotColor, false);
}
}
int startX = -1, startY = -1, resultX = -1, resultY = -1, obstacleX = -1, obstacleY = -1;
double maxValue = -1000;
double valueP = 0;
for (int i0 = 0; i0 < GRIDSIZE; ++i0) {
for (int j0 = 0; j0 < GRIDSIZE; ++j0) {
for (int k1 = 0; k1 < 8; ++k1) {
for (int delta1 = 1; delta1 < GRIDSIZE; delta1++) {
int xx = i0 + dx[k1] * delta1;
int yy = j0 + dy[k1] * delta1;
if (gridInfo[xx][yy] != 0 || !inMap(xx, yy))
break;
for (int l = 0; l < 8; ++l) {
for (int delta2 = 1; delta2 < GRIDSIZE; delta2++) {
int xxx = xx + dx[l] * delta2;
int yyy = yy + dy[l] * delta2;
if (!inMap(xxx, yyy))
break;
if (gridInfo[xxx][yyy] != 0 && !(i0 == xxx && j0 == yyy))
break;
if (Move(i0, j0, xx, yy, xxx, yyy, currBotColor, true))
{
memcpy(temp, gridInfo, sizeof(gridInfo));
temp[i0][j0] = 0;
temp[xx][yy] = currBotColor;
temp[xxx][yyy] = OBSTACLE;
for (int i = 0; i < GRIDSIZE; i++)
for (int j = 0; j < GRIDSIZE; j++)
{
Qblack[i][j] = 1000;
Qwhite[i][j] = 1000;
Kblack[i][j] = 1000;
Kwhite[i][j] = 1000;
}
getMove();
getValue();
valueP = v(turnID);
if (maxValue < valueP)
{
maxValue = valueP;
startX = i0;
startY = j0;
resultX = xx;
resultY = yy;
obstacleX = xxx;
obstacleY = yyy;
}
cout << startX << ' ' << startY << ' ' << resultX << ' ' << resultY << ' ' << obstacleX << ' ' << obstacleY << endl;
} | true |
0832b7e656c6cdc4ef633729d43b0ad9a1e284a4 | C++ | Wizardyi/MyFirstProject | /main/src/socket/Socket.h | UTF-8 | 793 | 2.5625 | 3 | [] | no_license | #pragma once
#include<stdlib.h>
#include<memory>
#include<sys/socket.h>
#include<netinet/in.h>
#include <arpa/inet.h>
#include<iostream>
#include<string.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
#define BUFF_SIZE 1024*100
class CSocket
{
public:
CSocket(){
memset(&serv_addr_, 0, sizeof(serv_addr_));
memset(&clnt_addr_, 0, sizeof(clnt_addr_));
}
~CSocket(){
}
//初始化
void Init(std::string& ip,int port);
//监听
void Listen();
//建立链接
void Connect();
//接收数据
void AcceptData();
//发送数据
void SendData();
private:
int serv_sock_;//服务器套接字
int client_sock_;//客户端套接字
struct sockaddr_in serv_addr_;
struct sockaddr_in clnt_addr_;
char buffer[BUFF_SIZE];//缓存区
};
| true |
627517da910cd64738db83ee072795d6373b52e7 | C++ | gysevvlad/viewapp | /src/tests/reactor_test.cpp | UTF-8 | 9,720 | 2.75 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "src/Reactor.h"
#include "src/helper.h"
template<class HoldFunctor>
class FunctorEventHandler : public Reactor::IEventHandler, HoldFunctor
{
public:
template<class ParamFunctor>
FunctorEventHandler(Reactor & reactor, ParamFunctor && functor) :
HoldFunctor(std::forward<ParamFunctor>(functor)),
IEventHandler(reactor)
{
}
virtual LRESULT onEvent(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) override
{
return HoldFunctor::operator()(hWnd, message, wParam, lParam);
}
};
template<class Functor>
FunctorEventHandler(Reactor & reactor, Functor && functor)
->FunctorEventHandler<std::remove_reference_t<Functor>>;
HWND createTestWindow(std::wstring_view class_name, Reactor::IEventHandler * event_handler)
{
return CreateWindowW(
class_name.data(),
L"test app",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
nullptr, nullptr,
GetModuleHandleW(nullptr),
event_handler);
}
TEST(Reactor, BaseUsage)
{
Reactor reactor;
WindowHandle window_handle;
auto message_counter = 0;
auto handler = FunctorEventHandler{ reactor,
[&window_handle, &message_counter] (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
if (message == WM_CREATE) {
message_counter++;
PostMessageW(hWnd, WM_CLOSE, 0, 0);
return 0;
}
else if (message == WM_CLOSE) {
message_counter++;
window_handle = nullptr;
return 0;
}
else if (message == WM_DESTROY) {
message_counter++;
return 0;
}
else {
return DefWindowProcW(hWnd, message, wParam, lParam);
}
}
};
WindowClass window_class(Reactor::WndProc);
window_handle = createTestWindow(window_class.getClassName(), &handler);
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_NE(window_handle, nullptr);
ASSERT_EQ(reactor.handleEvents(), 0);
ASSERT_EQ(message_counter, 3);
}
TEST(Reactor, WmCreateWithException)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
if (message == WM_CREATE) {
throw std::exception();
}
else {
return DefWindowProcW(hWnd, message, wParam, lParam);
}
}
};
WindowClass window_class(Reactor::WndProc);
auto window_handle = createTestWindow(window_class.getClassName(), &handler);
ASSERT_ANY_THROW(reactor.throwIfHasException());
ASSERT_EQ(window_handle, nullptr);
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(Reactor, WmCreateWithBadReturn)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
if (message == WM_CREATE) {
return -1;
}
else {
return DefWindowProcW(hWnd, message, wParam, lParam);
}
}
};
WindowClass window_class(Reactor::WndProc);
auto window_handle = createTestWindow(window_class.getClassName(), &handler);
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_EQ(window_handle, nullptr);
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorRegisterDeathTest, BaseUsage)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
return 0;
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
Reactor::WndProc(hwnd, WM_APP, 0, 0);
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
ASSERT_DEATH(reactor.onEvent(hwnd, WM_APP, 0, 0), "");
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorRegisterDeathTest, DoubleRegister)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
return 0;
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
ASSERT_DEATH(Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct)), ".*");
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorRegisterDeathTest, BadReturn)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
return -1;
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
ASSERT_DEATH(reactor.onEvent(hwnd, WM_APP, 0, 0), "");
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorRegisterDeathTest, Exception)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
throw std::exception();
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
ASSERT_DEATH(reactor.onEvent(hwnd, WM_APP, 0, 0), "");
ASSERT_ANY_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorUnRegisterDeathTest, BaseUsage)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
if (message == WM_APP) {
return 12345;
}
else {
return 0;
}
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
ASSERT_EQ(Reactor::WndProc(hwnd, WM_APP, 0, 0), 12345);
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
Reactor::WndProc(hwnd, WM_APP, 0, 0);
ASSERT_DEATH(reactor.onEvent(hwnd, WM_APP, 0, 0), "");
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorUnRegisterDeathTest, BadReturn)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
if (message == WM_CREATE) {
return 0;
}
else if (message == WM_DESTROY) {
return -1;
}
else {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
Reactor::WndProc(hwnd, WM_APP, 0, 0);
ASSERT_DEATH(reactor.onEvent(hwnd, WM_APP, 0, 0), "");
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorUnRegisterDeathTest, Exception)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
if (message == WM_CREATE) {
return 0;
}
else if (message == WM_DESTROY) {
throw std::exception();
}
else {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
Reactor::WndProc(hwnd, WM_APP, 0, 0);
ASSERT_DEATH(reactor.onEvent(hwnd, WM_APP, 0, 0), "");
ASSERT_ANY_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
TEST(ReactorUnRegisterDeathTest, DoubleUnRegister)
{
Reactor reactor;
auto handler = FunctorEventHandler{ reactor,
[](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
return DefWindowProc(hWnd, message, wParam, lParam);
}
};
HWND hwnd = reinterpret_cast<HWND>(0x0F0F0F0F);
CREATESTRUCTW create_struct;
create_struct.lpCreateParams = &handler;
Reactor::WndProc(hwnd, WM_CREATE, 0, reinterpret_cast<LPARAM>(&create_struct));
Reactor::WndProc(hwnd, WM_DESTROY, 0, 0);
ASSERT_DEATH(Reactor::WndProc(hwnd, WM_DESTROY, 0, 0), "");
ASSERT_NO_THROW(reactor.throwIfHasException());
ASSERT_EQ(reactor.handleEvents(), 0);
}
| true |
e6dd3d71f9eb1c06adfb72126f671498ed5f6211 | C++ | Hanzhuo-Gong/Foothill-Work-CPP | /CS 2C Lab6/CS 2C Lab6/CS2CLab6.cpp | UTF-8 | 4,668 | 3.1875 | 3 | [] | no_license | // CS2CLab6.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <string>
#include <ctime>
#include "Penguin.hpp"
using namespace std;
//-------------------Global Prototype-----------------------------
int Hash(int key);
int Hash(const string & key);
int Hash(const Penguin & key);
//int getKey(const Penguin &p);
string getKey(const Penguin &p);
#include "FHhashQPwFind.h"
//---------------------Global Definition-----------------------------
int Hash(const string & key)
{
unsigned int k, retVal = 0;
for (k = 0; k < key.length(); k++)
retVal = 37 * retVal + key[k];
return retVal;
}
int Hash(int key)
{
return key;
}
// we have to define how to get the number to hash for a Penguin object
int Hash(const Penguin & p)
{
// TODO: fill this in to get a number for string or int.
// They will call the Hash functions from above.
// (write both, but comment out one at a time)
//For ID
//return getKey(p);
//For Name
unsigned int i, retVal = 0;
string penguinName = p.getName();
for (i = 0; i < penguinName.length(); i++)
retVal = 37 * retVal + penguinName[i];
return retVal;
}
string getKey(const Penguin &p) {
return p.getName();
}
//int getKey(const Penguin &p) {
// return p.getBirdIdNumber();
//}
//--------------------------Main-----------------------
int main()
{
srand((unsigned)time(NULL));
//FHhashQPwFind<Penguin, int> hashTable; // for ID equality
FHhashQPwFind<Penguin, string> hashTable; // for any string equality
const int NUM_RANDOM_INDICES = 25;
int randomIndices[NUM_RANDOM_INDICES];
int k, arraySize, randIndex;
float randFrac;
Penguin onePenguin;
PenguinDataReader penguinInput("penguinData.txt");
if (penguinInput.readError()) {
cout << "couldn't open " << penguinInput.getFileName()
<< " for input.\n";
exit(1);
}
cout << penguinInput.getFileName() << endl;
cout << penguinInput.getNumPenguins() << endl;
arraySize = penguinInput.getNumPenguins();
cout << "arraySize is: " << arraySize << endl;
//Insert all the penguin to the hash table
for (int i = 0; i < arraySize; i++)
hashTable.insert(penguinInput[i]);
cout << "Size of this hash table is " << hashTable.size() << endl;
//Generate random number
for (k = 0; k < NUM_RANDOM_INDICES; k++)
{
randFrac = rand() / (float)RAND_MAX;
randIndex = randFrac * arraySize;
randomIndices[k] = randIndex;
//cout << randIndex << " ";
}
//Display the penguin
cout << "\n-----------------Display the penguin------------" << endl;
for (int i = 0; i < NUM_RANDOM_INDICES; i++) {
cout << "Penguin " << i << " properties:" << endl;
cout << "Name: " << penguinInput[randomIndices[i]].getName() << endl;
cout << "ID: " << penguinInput[randomIndices[i]].getBirdIdNumber()
<< endl;
cout << endl;
}
// attempt to find on the selected key
cout << "The same random penguins from the hash table " << endl;
for (int k = 0; k < NUM_RANDOM_INDICES; k++)
{
try
{
//for ID
//onePenguin = hashTable.find(penguinInput[randomIndices[k]].getBirdIdNumber());
//for name
onePenguin = hashTable.find(penguinInput[randomIndices[k]].getName());
cout << "PENGUIN FOUND: " << onePenguin.getName() << " "
<< onePenguin.getBirdIdNumber();
}
catch (...)
{
cout << "this penguin is not in the hash table, probably lives in a different colony ";
}
cout << endl;
}
//test known failures exceptions:
cout << "\n--------------Test for failure of find---------------" << endl;
try
{
//onePenguin = hashTable.find(-3);
onePenguin = hashTable.find( "albatross" );
cout << "Penguin Found! " << onePenguin.getName() << endl;
}
catch (...)
{
cout << "That is not a penguin. " << endl;
}
try
{
//onePenguin = hashTable.find(4001);
onePenguin = hashTable.find( "penguin who know Java" );
cout << "Penguin Found! " << onePenguin.getName() << endl;
}
catch (...)
{
cout << "That is not a penguin. " << endl;
}
try
{
//onePenguin = hashTable.find(300);
onePenguin = hashTable.find( "CEOpenguin" );
cout << "Penguin Found! " << onePenguin.getName() << endl;
}
catch (...)
{
cout << "That is not a penguin. " << endl;
}
return 0;
}
| true |
5db3bf286e61ae94fb987dc5fd1f88e420a84e8a | C++ | LedgerHQ/lib-ledger-core | /core/src/utils/endian.h | UTF-8 | 4,255 | 2.59375 | 3 | [
"MIT"
] | permissive | /*
*
* endian
* ledger-core
*
* Created by Pierre Pollastri on 15/09/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#undef BIG_ENDIAN
#undef LITTLE_ENDIAN
#ifndef LEDGER_CORE_ENDIAN_H
#define LEDGER_CORE_ENDIAN_H
#include <cstddef>
#include <cstdint>
#include <cstdlib>
/**
* Ledger global namespace
*/
namespace ledger {
namespace core {
/**
* Endianness management functions
* @headerfile endian.h <ledger/core/utils/endian.h>
*/
namespace endianness {
enum struct Endianness {
BIG = 1,
LITTLE
};
/**
* Checks if the current system uses big endian or little bytes order.
* @headerfile endian.h <ledger/core/utils/endian.h>
* @return
*/
Endianness getSystemEndianness();
/**
* Returns true if the current runtime uses big endian bytes order.
* @return
*/
bool isSystemBigEndian();
/**
* Returns true if the current runtime uses little endian bytes order.
* @return
*/
bool isSystemLittleEndian();
/**
* Swaps ptr bytes to big endian bytes order if the current runtime uses little endia bytes order.
* @param ptr The buffer to force in big endian bytes order
* @param size The size of the buffer
* @return
*/
void *swapToBigEndian(void *ptr, size_t size);
/**
* Swaps ptr bytes to little endian bytes order if the current runtime uses big endia bytes order.
* @param ptr The buffer to force in little endian bytes order
* @param size The size of the buffer
* @return
*/
void *swapToLittleEndian(void *ptr, size_t size);
/**
* Swaps ptr bytes to final endianness only if necessary
* @param ptr The buffer to force in "final" endianness
* @param size The size of the buffer
* @param current The current byte order of ptr
* @param final The desired final byte order of ptr
* @return
*/
void *swapToEndianness(void *ptr, size_t size, Endianness current, Endianness final);
const void *int_to_array(int i, Endianness endianness);
const void *unsigned_long_long_to_array(unsigned long long i, Endianness endianness);
template <typename T>
void *scalar_type_to_array(T i, Endianness endianness) {
uint8_t *data = (uint8_t *)std::malloc(sizeof(i));
auto ptr = (const uint8_t *)(&i);
for (auto index = 0; index < sizeof(i); index++) {
data[index] = ptr[index];
}
swapToEndianness(data, sizeof(i), getSystemEndianness(), endianness);
return (void *)data;
}
} // namespace endianness
} // namespace core
} // namespace ledger
#endif // LEDGER_CORE_ENDIAN_H
| true |
051c43cf88347e8a2aa6bab1bf1da04a7879bfc6 | C++ | gardenappl/oop-lab1-queue-ip | /src/sorted_vector.h | UTF-8 | 1,241 | 3.828125 | 4 | [] | no_license | #pragma once
#include "comparator.h"
#include <vector>
template<typename T>
struct sorted_vector
{
private:
/*!
* The underlying data vector.
*/
std::vector<T> data_vector;
/*!
* The comparison function to use for sorting the array.
*/
comparator<T> sort_comparator;
public:
/*!
* Constructs a standard sorted vector.
*/
sorted_vector();
/*!
* Constructs a sorted vector, which sorts values using the specified comparator function.
*/
explicit sorted_vector(comparator<T> comparator);
/*!
* Insert an element into the vector at an appropriate position.
* @param element the element to be inserted
* @return the index of the element
*/
size_t insert(const T& element);
/*!
* Returns the number of elements stored in the vector.
* @return the number of elements
*/
size_t get_size() const;
/*!
* Removes the last element from the array and returns its value.
* @return the removed value
*/
T pop_back();
/*!
* Read-only access to the element by its index in the array.
* @param index the index
* @return the element associated with the index
*/
const T& operator[](std::size_t index) const;
};
#include "sorted_vector.tpp"
| true |
c90d3f608a2bd196db6a1e2dd77183ee693924f6 | C++ | icylight/fr | /common/ThreadPool.cpp | UTF-8 | 5,326 | 2.546875 | 3 | [] | no_license |
#include "stdafx.h"
#include "ThreadPool.h"
DWORD BeginTime;
LONG ItemCount;
HANDLE CompleteEvent = NULL;
FORCEINLINE
VOID
InitializeListHead(
__out PLIST_ENTRY ListHead
)
{
ListHead->Flink = ListHead->Blink = ListHead;
}
__checkReturn
BOOLEAN
FORCEINLINE
IsListEmpty(
__in const LIST_ENTRY * ListHead
)
{
return (BOOLEAN)(ListHead->Flink == ListHead);
}
FORCEINLINE
BOOLEAN
RemoveEntryList(
__in PLIST_ENTRY Entry
)
{
PLIST_ENTRY Blink;
PLIST_ENTRY Flink;
Flink = Entry->Flink;
Blink = Entry->Blink;
Blink->Flink = Flink;
Flink->Blink = Blink;
return (BOOLEAN)(Flink == Blink);
}
FORCEINLINE
PLIST_ENTRY
RemoveHeadList(
__inout PLIST_ENTRY ListHead
)
{
PLIST_ENTRY Flink;
PLIST_ENTRY Entry;
Entry = ListHead->Flink;
Flink = Entry->Flink;
ListHead->Flink = Flink;
Flink->Blink = ListHead;
return Entry;
}
FORCEINLINE
PLIST_ENTRY
RemoveTailList(
__inout PLIST_ENTRY ListHead
)
{
PLIST_ENTRY Blink;
PLIST_ENTRY Entry;
Entry = ListHead->Blink;
Blink = Entry->Blink;
ListHead->Blink = Blink;
Blink->Flink = ListHead;
return Entry;
}
FORCEINLINE
VOID
InsertTailList(
__inout PLIST_ENTRY ListHead,
__inout __drv_aliasesMem PLIST_ENTRY Entry
)
{
PLIST_ENTRY Blink;
Blink = ListHead->Blink;
Entry->Flink = ListHead;
Entry->Blink = Blink;
Blink->Flink = Entry;
ListHead->Blink = Entry;
}
FORCEINLINE
VOID
InsertHeadList(
__inout PLIST_ENTRY ListHead,
__inout __drv_aliasesMem PLIST_ENTRY Entry
)
{
PLIST_ENTRY Flink;
Flink = ListHead->Flink;
Entry->Flink = Flink;
Entry->Blink = ListHead;
Flink->Blink = Entry;
ListHead->Flink = Entry;
}
/************************************************************************/
/* Test Our own thread pool. */
/************************************************************************/
DWORD WINAPI WorkerThread(PVOID pParam)
{
PTHREAD_POOL pThreadPool = (PTHREAD_POOL)pParam;
HANDLE Events[2];
Events[0] = pThreadPool->QuitEvent;
Events[1] = pThreadPool->WorkItemSemaphore;
for(;;)
{
DWORD dwRet = WaitForMultipleObjects(2, Events, FALSE, INFINITE);
if(dwRet == WAIT_OBJECT_0)
break;
//
// execute user's proc.
//
else if(dwRet == WAIT_OBJECT_0 +1)
{
PWORK_ITEM pWorkItem;
PLIST_ENTRY pList;
EnterCriticalSection(&pThreadPool->WorkItemLock);
//_ASSERT(!IsListEmpty(&pThreadPool->WorkItemHeader));
pList = RemoveHeadList(&pThreadPool->WorkItemHeader);
LeaveCriticalSection(&pThreadPool->WorkItemLock);
pWorkItem = CONTAINING_RECORD(pList, WORK_ITEM, List);
pWorkItem->UserProc(pWorkItem->UserParam);
InterlockedDecrement(&pThreadPool->WorkItemCount);
free(pWorkItem);
}
else
{
//_ASSERT(0);
break;
}
}
return 0;
}
BOOL InitializeThreadPool(PTHREAD_POOL pThreadPool, LONG ThreadNum)
{
pThreadPool->QuitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
pThreadPool->WorkItemSemaphore = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL);
pThreadPool->WorkItemCount = 0;
InitializeListHead(&pThreadPool->WorkItemHeader);
InitializeCriticalSection(&pThreadPool->WorkItemLock);
pThreadPool->ThreadNum = ThreadNum;
pThreadPool->ThreadsArray = (HANDLE*)malloc(sizeof(HANDLE) * ThreadNum);
for(int i=0; i<ThreadNum; i++)
{
pThreadPool->ThreadsArray[i] = CreateThread(NULL, 0, WorkerThread, pThreadPool, 0, NULL);
}
return TRUE;
}
VOID DestroyThreadPool(PTHREAD_POOL pThreadPool)
{
SetEvent(pThreadPool->QuitEvent);
for(int i=0; i<pThreadPool->ThreadNum; i++)
{
WaitForSingleObject(pThreadPool->ThreadsArray[i], INFINITE);
CloseHandle(pThreadPool->ThreadsArray[i]);
}
free(pThreadPool->ThreadsArray);
CloseHandle(pThreadPool->QuitEvent);
CloseHandle(pThreadPool->WorkItemSemaphore);
DeleteCriticalSection(&pThreadPool->WorkItemLock);
while(!IsListEmpty(&pThreadPool->WorkItemHeader))
{
PWORK_ITEM pWorkItem;
PLIST_ENTRY pList;
pList = RemoveHeadList(&pThreadPool->WorkItemHeader);
pWorkItem = CONTAINING_RECORD(pList, WORK_ITEM, List);
free(pWorkItem);
}
}
BOOL PostWorkItem(PTHREAD_POOL pThreadPool, WORK_ITEM_PROC UserProc, PVOID UserParam)
{
PWORK_ITEM pWorkItem = (PWORK_ITEM)malloc(sizeof(WORK_ITEM));
if(pWorkItem == NULL)
return FALSE;
pWorkItem->UserProc = UserProc;
pWorkItem->UserParam = UserParam;
EnterCriticalSection(&pThreadPool->WorkItemLock);
InsertTailList(&pThreadPool->WorkItemHeader, &pWorkItem->List);
LeaveCriticalSection(&pThreadPool->WorkItemLock);
InterlockedIncrement(&pThreadPool->WorkItemCount);
ReleaseSemaphore(pThreadPool->WorkItemSemaphore, 1, NULL);
return TRUE;
}
| true |