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
10059c3da381866a71882a3dcc9cd962bf96820f
C++
DVDVideoSoft/free3dphotomaker
/Free3DPhotoMaker/Components/3DAnaglyph/src/3dmakeanaglyph.cpp
WINDOWS-1251
17,587
2.546875
3
[]
no_license
#include "_3DAnaglyph.h" double cnMaxSize = 8192; const double cnMaxSparse = 800*600; const int cnMaxShift = 50; const int cShift = 20; #define _SAFE_RELEASE_(v) if (v) cvReleaseImage(&v); /* [pDst] [pSrc]. . : IPL_DEPTH_8U, . IPL_DEPTH_8U , . NOERROR - ERR_INVALID_PARAMS - */ static int _MakeDepthMap(IplImage* pSrc, IplImage* pDst, progress_func f) { int res = NOERROR; // if (pSrc == NULL || pDst == NULL) return ERR_INVALID_PARAMS; if (pSrc->depth != IPL_DEPTH_8U || pSrc->depth != pDst->depth) return ERR_INVALID_PARAMS; if (pSrc->nChannels != 3 && pSrc->nChannels != 1) return ERR_INVALID_PARAMS; if (pDst->nChannels != 1) return ERR_INVALID_PARAMS; if (pSrc->width != pDst->width || pSrc->height != pDst->height) return ERR_INVALID_PARAMS; // . double image_size = pSrc->width*pSrc->height; int n1 = (int) sqrt(image_size / cnMaxSparse); n1 = n1 < 1 ? 1:n1; int n2 = (int) sqrt(image_size / cnMaxSize); n2 = n2 < 1 ? 1: n2; CvSize s,s1,s2; s.height = pSrc->height;s.width = pSrc->width; s1.height = s.height / n1; s1.width = s.width / n1; s2.height = s.height / n2; s2.width = s.width / n2; // IplImage* src1 = NULL; // IplImage* src2 = NULL; // IplImage* sdepth_map = NULL;// IplImage* sdm = NULL;// IplImage* fdepth_map = NULL;// try { // src1 = cvCreateImage(s1,pSrc->depth, pSrc->nChannels); if (src1 == NULL) throw ERR_MEMORY; src2 = cvCreateImage(s2,pSrc->depth, pSrc->nChannels); if (src2 == NULL) throw ERR_MEMORY; sdepth_map = cvCreateImage(s1, IPL_DEPTH_8U, 1); if (sdepth_map == NULL) throw ERR_MEMORY; sdm = cvCreateImage(s2, IPL_DEPTH_8U, 1); if (sdm == NULL) throw ERR_MEMORY; fdepth_map = cvCreateImage(s2, IPL_DEPTH_8U, 1); if (fdepth_map == NULL) throw ERR_MEMORY; cvResize(pSrc, src1); cvResize(pSrc, src2); if (f != NULL) f(30); MakeSparceDepthMap(src1,sdepth_map); cvResize(sdepth_map, sdm); if (MakeFullDepthMap(src2, sdm, fdepth_map) != NOERROR) throw ERR_MAKE_DEPTH; if (f != NULL) f(70); cvResize(fdepth_map, pDst); #ifdef _DEBUG cvSaveImage("debug_full.png",pDst); cvShowImage("sdepth", sdepth_map); #endif } catch(int& a) { res = a; _SAFE_RELEASE_(src1) _SAFE_RELEASE_(src2) _SAFE_RELEASE_(sdepth_map) _SAFE_RELEASE_(sdm) _SAFE_RELEASE_(fdepth_map) return res; } // _SAFE_RELEASE_(src1) _SAFE_RELEASE_(src2) _SAFE_RELEASE_(sdepth_map) _SAFE_RELEASE_(sdm) _SAFE_RELEASE_(fdepth_map) return res; } int _RemoveBorder(IplImage* src, IplImage* dst, int lx, int rx) { if (src == NULL || dst == NULL) return ERR_INVALID_PARAMS; if (lx < 0 || lx > cnMaxShift || rx < 0 || rx > cnMaxShift) return ERR_INVALID_PARAMS; IplImage* tmp = NULL; CvSize s; s.height = src->height; s.width = src->width - lx - rx; tmp = cvCreateImage(s, src->depth, src->nChannels); if (tmp == NULL) return ERR_MEMORY; // awpColor _awpColor* psrc = NULL;// _awpColor* ptmp = NULL;// for (int y = 0; y < src->height; y++) { int c = 0; psrc = (_awpColor*)((unsigned char*)src->imageData + y*src->widthStep); ptmp = (_awpColor*)((unsigned char*)tmp->imageData + y*tmp->widthStep); for (int x = lx; x < src->width - rx; x++) { ptmp[c++] = psrc[x]; } } cvResize(tmp, dst); cvReleaseImage(&tmp); return NOERROR; } // // //1. //2. //3. //4. //5. //6. //7. // static int _Make3DAnaglyph(IplImage* pSrc, IplImage* pDst, progress_func f, int options) { if (options > 4) return ERR_INVALID_PARAMS; int res = NOERROR; CvSize s; s.width = pSrc->width;s.height = pSrc->height; IplImage* dm = cvCreateImage(s, IPL_DEPTH_8U, 1); res = _MakeDepthMap(pSrc, dm,f); if (res < 0) { cvReleaseImage(&dm); return res; } IplImage* lep = NULL; // IplImage* rep = NULL; // // lep = cvCreateImage(s, pSrc->depth, pSrc->nChannels); rep = cvCreateImage(s, pSrc->depth, pSrc->nChannels); if (lep == NULL || rep == NULL) { if (lep != NULL) cvReleaseImage(&lep); if (rep != NULL) cvReleaseImage(&rep); return ERR_CREATE_STEREOPAIR;// () } Displace(pSrc, dm, lep, -cShift); Displace(pSrc, dm, rep, cShift); if (f != NULL) f(90); #ifdef _DEBUG cvSaveImage("debug_lep.png", lep); cvSaveImage("debug_rep.png", rep); cvShowImage("depth", dm); #endif IplImage* tmp = NULL; tmp = cvCreateImage(s, pSrc->depth, pSrc->nChannels); MakeAnaglyph(lep,rep, tmp, NULL, options); _RemoveBorder(tmp, pDst, cShift, cShift); if (f != NULL) f(99); cvReleaseImage(&tmp); cvReleaseImage(&lep); cvReleaseImage(&rep); cvReleaseImage(&dm); return res; } // static int _Make3DTile(IplImage* pSrc, IplImage* pDst) { int res = NOERROR; CvSize s; s.width = pSrc->width;s.height = pSrc->height; IplImage* dm = cvCreateImage(s, IPL_DEPTH_8U, 1); res = _MakeDepthMap(pSrc, dm, NULL); if (res < 0) { cvReleaseImage(&dm); return res; } IplImage* lep = NULL; // IplImage* rep = NULL; // // lep = cvCreateImage(s, pSrc->depth, pSrc->nChannels); rep = cvCreateImage(s, pSrc->depth, pSrc->nChannels); if (lep == NULL || rep == NULL) { if (lep != NULL) cvReleaseImage(&lep); if (rep != NULL) cvReleaseImage(&rep); return ERR_MEMORY;// () } IplImage* tmp = cvCreateImage(s, pSrc->depth, pSrc->nChannels); if (tmp == NULL) { cvReleaseImage(&lep); cvReleaseImage(&rep); cvReleaseImage(&dm); return ERR_MEMORY; } Displace(pSrc, dm, tmp, -cShift); _RemoveBorder(tmp,lep,0,cShift); Displace(pSrc, dm, tmp,cShift); _RemoveBorder(tmp,rep,cShift,0); #ifdef _DEBUG cvSaveImage("debug_lep.png", lep); cvSaveImage("debug_rep.png", rep); #endif MakeTile(lep,rep, pDst); cvReleaseImage(&lep); cvReleaseImage(&rep); cvReleaseImage(&dm); return res; } // static int _InsertContFrame(IplImage* fr, IplImage* cnt, int x, int y) { int i,j; unsigned char* b = (unsigned char*)cnt->imageData; unsigned char* f = (unsigned char*)fr->imageData; for (i = 0; i < cnt->height; i++) { for (j = 0; j < cnt->widthStep; j++) { f[(i + y)*fr->widthStep + j + 3*x] = b[i*cnt->widthStep + j]; } } return NOERROR; } // static int _Make3DVideo(IplImage* src, const char* lpDstName, int options) { if (options <6 || options > 8) return ERR_INVALID_PARAMS; int res = NOERROR; CvSize s; s.width = src->width;s.height = src->height; IplImage* dm = cvCreateImage(s, IPL_DEPTH_8U, 1); res = _MakeDepthMap(src, dm, NULL); if (res < 0) { cvReleaseImage(&dm); return res; } int w,h,w1,h1,x,y; float alfa1 = 1; float alfa2 = 1; switch(options) { case VGAAvi: w1 = 640;h1 = 480; break; case HDAvi720: w1 = 1280; h1 = 720; break; case HDAvi1080: w1 = 1920; h1 = 1080; break; } alfa1 = (float)w1 / (float)h1; alfa2 = (float)src->width / (float)src->height; // float alfa = 1.f; if (alfa1 > alfa2) { alfa = (float)src->height / (float)h1; w = (int)(src->width / alfa); h = h1; y = 0; x = abs(w1 - w) / 2; } else { alfa = (float)w1 / (float)src->width; h = (int)(src->height * alfa); w = w1; x = 0; y = abs(h1 - h) / 2; } s.height = h; s.width = w; CvSize sf; sf.height = h1; sf.width = w1; IplImage* frame = cvCreateImage(sf, IPL_DEPTH_8U, 3); IplImage* cont = cvCreateImage(s, IPL_DEPTH_8U, 3); IplImage* tmp = cvCreateImage(s, src->depth, src->nChannels); IplImage* src1 = cvCreateImage(s, IPL_DEPTH_8U, 3); IplImage* dm1 = cvCreateImage(s, IPL_DEPTH_8U, 1); cvResize(src, src1); cvResize(dm, dm1); CvVideoWriter* writer = NULL; double fps = 24; writer = cvCreateVideoWriter(lpDstName, 0, fps,sf); int delta = -20; for (int i = 0; i < 40; i++) { cvZero(frame); delta += 1; Displace1(src1, dm1, tmp, delta); _RemoveBorder(tmp,cont, 20,20); _InsertContFrame(frame,cont,x,y); cvWriteFrame(writer, frame); } cvReleaseVideoWriter(&writer); cvReleaseImage(&dm); cvReleaseImage(&frame); cvReleaseImage(&cont); cvReleaseImage(&src1); cvReleaseImage(&dm1); cvReleaseImage(&tmp); return res; } #define WAIT_TIME 50 static int _ConvertVideo23D(const char* lpSrcName, const char* lpDstName, int Options) { int res = NOERROR; if (lpSrcName == NULL || lpDstName == NULL || Options < 10) return ERR_INVALID_PARAMS; CvCapture* capture = NULL; CvVideoWriter* writer = NULL; capture = cvCaptureFromFile(lpSrcName); if (capture == NULL) return ERR_LOAD_SOURCE; // double val = 0; CvSize s; val = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); s.width = (int)val; val = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); s.height = (int)val; val = cvGetCaptureProperty(capture, CV_CAP_PROP_FPS); double fps = val; val = cvGetCaptureProperty(capture, CV_CAP_PROP_FOURCC); int fourcc = (int)val; val = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT); #ifdef _DEBUG printf("%i\n",(int)val); #endif writer = cvCreateVideoWriter(lpDstName, 0, fps, s); if (writer == NULL) { cvReleaseCapture(&capture); return ERR_CREATE_DESTINATION; } IplImage* pimg = NULL; IplImage* pdst = NULL; int c = 0; #ifdef _DEBUG int KeyCode = 0; cvNamedWindow("src"); cvNamedWindow("depth"); cvNamedWindow("sdepth"); #endif do { #ifdef _DEBUG KeyCode = cvWaitKey(50); if (KeyCode == VK_ESCAPE) break; #endif pimg = cvQueryFrame(capture); if (pimg == NULL) break; CvSize s1; s1.height = pimg->height; s1.width = pimg->width; pdst = cvCreateImage(s1, pimg->depth, pimg->nChannels); if (pdst == NULL) break; //cvCopy(pimg, pdst); _Make3DAnaglyph(pimg, pdst, NULL, ColorAnaglyph); // cvSaveImage("out.jpg", pdst); #ifdef _DEBUG cvShowImage("src", pdst); #endif cvWriteFrame(writer, pdst); cvReleaseImage(&pdst); c++; #ifdef _DEBUG if (c % 100 == 0) printf("."); #endif }while(true); cvReleaseCapture(&capture); cvReleaseVideoWriter(&writer); return res; } int Make3DAnaglyph(const char* lpSrcName, const char* lpDstName, progress_func f, int options) { if (lpSrcName == NULL || lpDstName == NULL || options < 0 || options > 10) return ERR_INVALID_PARAMS; if (!AcceptFileName(lpSrcName, options, true)) return ERR_INVALID_PARAMS; if (!AcceptFileName(lpDstName, options, false)) return ERR_INVALID_PARAMS; IplImage* pSrc = NULL; IplImage* pDst = NULL; // if (options < 10) { pSrc = cvLoadImage(lpSrcName); if (pSrc == NULL) return ERR_LOAD_SOURCE; // } CvSize s; int result = 0; if (options < 5) { s.width = pSrc->width; s.height = pSrc->height; pDst = cvCreateImage(s, pSrc->depth, pSrc->nChannels); if (pDst == NULL) { cvReleaseImage(&pSrc); return ERR_MEMORY; // } result = _Make3DAnaglyph(pSrc,pDst, f, options); if (result == NOERROR) { // // result = cvSaveImage(lpDstName, pDst) == 0? ERR_SAVE_ANAGLYPH:0; } cvReleaseImage(&pDst); } else if (options == 5) { //todo: s.width = 2*pSrc->width; s.height = pSrc->height; pDst = cvCreateImage(s, pSrc->depth, pSrc->nChannels); if (pDst == NULL) { cvReleaseImage(&pSrc); return ERR_MEMORY; // } result = _Make3DTile(pSrc,pDst); if (result == NOERROR) { // // result = cvSaveImage(lpDstName, pDst) == 0? ERR_SAVE_ANAGLYPH:0; } cvReleaseImage(&pDst); } else if (options < 9) { //todo: result = _Make3DVideo(pSrc, lpDstName, options); } else if (options == 9) { //todo: GIF } else // result = _ConvertVideo23D(lpSrcName, lpDstName, options); cvReleaseImage(&pSrc); return result; } /* // */ int Make3DAnaglyphPair(const char* lpSrcName1, const char* lpSrcName2, const char* lpDstName, progress_func f, int options) { if (lpSrcName1 == NULL || lpSrcName2 == NULL || lpDstName == NULL || options < 0 || options > 4) return ERR_INVALID_PARAMS; if (!AcceptFileName(lpSrcName1, options, true)) return ERR_INVALID_PARAMS; if (!AcceptFileName(lpSrcName2, options, true)) return ERR_INVALID_PARAMS; if (!AcceptFileName(lpDstName, options, false)) return ERR_INVALID_PARAMS; IplImage* lep = NULL; IplImage* rep = NULL; IplImage* pDst = NULL; lep = cvLoadImage(lpSrcName1); rep = cvLoadImage(lpSrcName2); if (lep == NULL || rep == NULL) { cvReleaseImage(&lep); cvReleaseImage(&rep); return ERR_LOAD_SOURCE; } // if (lep->width != rep->width || lep->height != rep->height || lep->nChannels != rep->nChannels || lep->depth != rep->depth) { cvReleaseImage(&lep); cvReleaseImage(&rep); return ERR_INVALID_PARAMS; } CvSize s;s.width = lep->width; s.height = lep->height; int result = 0; pDst = cvCreateImage(s, lep->depth, lep->nChannels); if (pDst == NULL) { cvReleaseImage(&lep); cvReleaseImage(&rep); return ERR_MEMORY; } MakeAnaglyph(lep,rep, pDst, f, options); cvSaveImage(lpDstName, pDst); cvReleaseImage(&lep); cvReleaseImage(&rep); cvReleaseImage(&pDst); return result; }
true
af8b5a706b9d53e584b21c9373b09c00ffedd979
C++
MughalUsama/Object-Oriented-Programming
/Lab 3 Mor+Eve/Project1/Project1/Source.cpp
UTF-8
1,844
3.578125
4
[]
no_license
#include <iostream> using namespace std; class Information { private: char name[50]; char address[50]; int age; long int phNo; public: void setName(char * enteredName); void setAddress(char * enteredAddress); void setAge(int enteredAge); void setPhNo(long int phoneNo); char* getName(); char * getAddress(); int getAge(); long int getPhNo(); }; void inputInformation(Information &person); void displayInformation(Information &person); int main() { Information my, family, friend1; inputInformation(my); inputInformation(family); inputInformation(friend1); displayInformation(my); displayInformation(family); displayInformation(friend1); cout << "\n"; system("pause"); return 0; } void Information::setName(char * enteredName) { strcpy_s(name, enteredName); } void Information::setAddress(char * enteredAddress) { strcpy_s(address, enteredAddress); } void Information::setAge(int enteredAge) { age = enteredAge; } void Information::setPhNo(long int phoneNo) { phNo = phoneNo; } char * Information::getName() { return name; } char * Information::getAddress() { return address; } int Information::getAge() { return age; } long int Information::getPhNo() { return phNo; } void inputInformation(Information &person) { char pName[50], pAddress[50]; int pAge; long int phone; cout << "\nEnter the name :"; cin>>pName; person.setName(pName); cout << "Enter the address :"; cin>>pAddress; person.setAddress(pAddress); cout << "Enter the age : "; cin >> pAge; person.setAge(pAge); cout << "Enter Phone no : "; cin >> phone; person.setPhNo(phone); } void displayInformation(Information &person) { cout << "\n\nName : "<< person.getName(); cout << "\nAddress :" << person.getAddress(); cout << "\nAge : " << person.getAge(); cout << "\nPhone no : " << person.getPhNo(); } /**/
true
e3e875af8bf1c8b6ecbb1a591cbf972266b530c3
C++
jackthgu/K-AR_HYU_Deform_Simulation
/src/taesooLib/BaseLib/utility/TArray.h
UTF-8
12,045
3.078125
3
[ "MIT" ]
permissive
#ifndef _TARRAY_H_ #define _TARRAY_H_ #if _MSC_VER>1000 #pragma once #endif #include "stdtemplate.h" #if _MSC_VER > 1000 #pragma warning (disable: 4786) #endif #include "stdlib.h" // factory 를 어떤거를 쓰는가에 따라 메모리 관리 방식이 달라진다. 메모리 관리는 스스로 책임지기 바람. // deprecated. std::vector<boost::shared_ptr<...>> 조합 또는 TVector를 사용할 것. template <class T> class TArray { /** * 기본적인 사용법은 CArray나 std::vector등과 유사하다. 가장 큰 차이점은 Factory에 따라 원소의 초기화를 다르게 할수 있다는 점이다. * 특히 TDefaultFactory를 사용한경우(bReference=false인 경우) 모든 원소의 생성자가 call 된다. 이는 모든 원소가 factory를 통해 생성되기 때문에 가능하다. * 내부적 구현은 *의 array로, std::vector와 다르다. 만약 bReference==false 이면, new를 call하지 않고, 원소가 NULL로 초기화된다. * \Todo * n을 입력받는 생성자 함수 두개로 나눌생각. (int, bool) (int, TFactory<T>*) 로... */ public: TArray(int n, bool bReference=false); //!< Use default factory if pF==NULL. if(bReference=true) this class do not "new" or "delete" elements. TArray(int n, TFactory<T>* pF); TArray(bool bReference=false); //!< use TDefaultFactory if bReference=false, else use TFactory TArray(TFactory<T>* pF); TArray(const TArray& other); //!< copy constructor. (size가 0이 아니면 동작하지 않는다.) virtual ~TArray(); void init(int nsize); void resize(int nsize); void release(); int size() const; T& operator[](int nIndex) const; T& data(int nIndex) const { return (*this)[nIndex]; } T& back() const { return (*this)[size()-1]; } T* ptr(int nIndex) const { return m_apElement[nIndex];} void swap(int i, int j); void replace(int i, T* pElement); void pushBack(T* pElement) { resize(size()+1); replace(size()-1, pElement);} //! compare func는 T의 **를 입력으로 받는다. 출력은 element1과 element2의 크기를 비교해서 1,0,-1을 각각 클때, 같을때, 작을때 return한다. void sort(int start, int end, int (*compareFunc)(const void** ppElement1, const void** ppElement2)); void changeFactory(TFactory<T>* pF) {ASSERT(m_nSize==0); release(); delete m_pFactory; m_pFactory=pF; } void changeFactory(TArray<T>& other) const { other.changeFactory(m_pFactory->clone()); } void assign(const TArray<T>& other); void extract(const TArray<T>& other, int nElt, int* aiElt); void pushBack(const TArray<T>& other); void pushBack(const TArray<T>& other, int nElt, int* aiElt); // end이하는 end-start만큼 위로 올라간다. 즉 크기가 end-start만큼 작아진다. void remove(int start, int end); protected: T* initElt(int index); void deinitElt(int index); TFactory<T>* m_pFactory; T **m_apElement; // m_apElement[0]부터 m_apElement[m_nSize-1]까지는 NULL이 아닌 pointer를 갖는다. // m_apElement[m_nSize]부터 m_apElement[m_nCapacity]까지는 NULL pointer를 갖는다. // 그 이후를 사용하려하면 m_apElement자체가 doubling된다. int m_nSize; int m_nCapacity; }; //#include "stdafx.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// template <class T> TArray<T>::TArray(int n, bool bReference) { m_nSize=0; m_nCapacity=0; if(bReference) m_pFactory=new TFactory<T>(); else m_pFactory=new TDefaultFactory<T>(); init(n); } template <class T> TArray<T>::TArray(const TArray& other) { ASSERT(other.m_nSize==0); m_nSize=0; m_nCapacity=0; m_pFactory=other.m_pFactory->clone(); init(0); } template <class T> void TArray<T>::remove(int start, int end) { // end이하는 end-start만큼 위로 올라간다. 즉 matrix크기가 end-start만큼 세로로 작아진다. int numCols=end-start; for(int i=start; i<end; i++) deinitElt(i); for(int i=end; i<size(); i++) { m_apElement[i-numCols]=m_apElement[i]; } int newSize=size()-numCols; for(int i=newSize; i<size(); i++) m_apElement[i]=NULL; m_nSize=newSize; } template <class T> TArray<T>::TArray(int n, TFactory<T>* pF) { m_nSize=0; m_nCapacity=0; m_pFactory=pF; init(n); } template <class T> TArray<T>::TArray(bool bReference) { m_nSize=0; m_nCapacity=0; if(bReference) m_pFactory=new TFactory<T>(); else m_pFactory=new TDefaultFactory<T>(); } template <class T> TArray<T>::TArray(TFactory<T>* pF) { m_nSize=0; m_nCapacity=0; m_pFactory=pF; } template <class T> T* TArray<T>::initElt(int index) { return m_pFactory->create(index); } template <class T> void TArray<T>::deinitElt(int index) { m_pFactory->release(m_apElement[index]); m_apElement[index]=NULL; } template <class T> TArray<T>::~TArray() { release(); delete m_pFactory; } template <class T> int TArray<T>::size() const { return m_nSize; } template <class T> void TArray<T>::swap(int i, int j) { T* temp; temp=m_apElement[i]; m_apElement[i]=m_apElement[j]; m_apElement[j]=temp; } template <class T> void TArray<T>::replace(int i, T* pElement) { ASSERT(i<m_nSize); deinitElt(i); m_apElement[i]=pElement; } template <class T> void TArray<T>::resize(int nsize) { ASSERT(m_nSize<=m_nCapacity); if(nsize<=m_nSize) { for(int i=nsize; i<m_nSize; i++) deinitElt(i); m_nSize=nsize; } else if(nsize<=m_nCapacity) { for(int i=m_nSize; i<nsize; i++) { m_apElement[i]=initElt(i); } m_nSize=nsize; } else { ASSERT(nsize>m_nCapacity && nsize>m_nSize); if(m_nCapacity==0) { init(nsize); return; } // m_nCapacity가 nsize를 포함할때까지 doubling for(;m_nCapacity<nsize;) m_nCapacity*=2; T** apTempElement=new T*[m_nCapacity]; for(int i=0; i<m_nSize; i++) // copy apTempElement[i]=m_apElement[i]; for(int i=m_nSize; i<nsize; i++) apTempElement[i]=initElt(i); for(int i=nsize; i<m_nCapacity; i++) apTempElement[i]=NULL; delete[] m_apElement; m_apElement=apTempElement; m_nSize=nsize; } } template <class T> void TArray<T>::init(int nsize) { release(); m_nSize=nsize; m_nCapacity=nsize; m_apElement=new T*[nsize]; for(int i=0; i<m_nSize; i++) { m_apElement[i]=initElt(i); } } template <class T> void TArray<T>::release() { if(m_nSize==0) return; for(int i=0; i<m_nSize; i++) deinitElt(i); delete[] m_apElement; m_nSize=0; m_nCapacity=0; } template <class T> T& TArray<T>::operator[](int nIndex) const { ASSERT(nIndex>=0 && nIndex<size()); return *m_apElement[nIndex]; } template <class T> void TArray<T>::sort(int start, int end, int (*compareFunc)(const void** ppElement1, const void** ppElement2)) { qsort((void*)&(m_apElement[start]), end-start, sizeof(T*), (int (*)(const void*, const void*))compareFunc); } template <class T> void TArray<T>::extract(const TArray<T>& other, int nelt, int* aielt) { changeFactory(new TFactory<T>()); // reference resize(nelt); for(int j=0; j<nelt; j++) { ASSERT(ptr(j)==NULL); replace(j, other.ptr(aielt[j])); } } template <class T> void TArray<T>::assign(const TArray<T>& other) { changeFactory(new TFactory<T>()); // reference resize(other.size()); for(int j=0; j<other.size(); j++) { ASSERT(ptr(j)==NULL); replace(j, other.ptr(j)); } } template <class T> void TArray<T>::pushBack(const TArray<T>& other) { for(int j=0; j<other.size(); j++) { pushBack(other.ptr(j)); } } template <class T> void TArray<T>::pushBack(const TArray<T>& other, int nElt, int* aiElt) { for(int j=0; j<nElt; j++) { pushBack(other.ptr(aiElt[j])); } } /// CTArray class is deprecated. do not use this class template <class T> class CTArray { public: CTArray(int n); CTArray(); CTArray(T* (*factory_func)(void* param, int index)); virtual ~CTArray(); void Init(int nsize, void* param=NULL); //!< param은 factory의 parameter로 들어간다. param==NULL이면 default param사용 void Resize(int nsize, void* param=NULL);//!< 줄이거나 늘리는것 모두 가능. param==NULL이면 default param사용 void Release(); int Size() const; T& operator[](int nIndex) const; void Swap(int i, int j); void Replace(int i, T* pElement); void pushBack(T* pElement) { Resize(Size()+1); Replace(Size()-1, pElement);} //! compare func는 T의 **를 입력으로 받는다. 출력은 element1과 element2의 크기를 비교해서 1,0,-1을 각각 클때, 같을때, 작을때 return한다. void Sort(int start, int end, int (*compareFunc)(const void** ppElement1, const void** ppElement2)); void ChangeFactory(T* (*factory_func)(void* param, int index)) {ASSERT(m_nSize==0); Release(); m_factoryFunc=factory_func; } void ChangeDefaultParam(void* param) { m_defaultParam=param;}; protected: T* (*m_factoryFunc)(void* param, int index); static T* default_factory(void* param, int index) { return new T();} void* m_defaultParam; T **m_apElement; // m_apElement[0]부터 m_apElement[m_nSize-1]까지는 NULL이 아닌 pointer를 갖는다. // m_apElement[m_nSize]부터 m_apElement[m_nCapacity]까지는 NULL pointer를 갖는다. // 그 이후를 사용하려하면 m_apElement자체가 doubling된다. int m_nSize; int m_nCapacity; }; //#include "stdafx.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// template <class T> CTArray<T>::CTArray(int n) { m_nSize=0; m_nCapacity=0; m_defaultParam=NULL; Init(n); } template <class T> CTArray<T>::CTArray() { m_nSize=0; m_nCapacity=0; m_defaultParam=NULL; m_factoryFunc=default_factory; } template <class T> CTArray<T>::CTArray(T* (*factory_func)(void* param, int index)) { m_nSize=0; m_nCapacity=0; m_defaultParam=NULL; m_factoryFunc=factory_func; } template <class T> CTArray<T>::~CTArray() { Release(); } template <class T> int CTArray<T>::Size() const { return m_nSize; } template <class T> void CTArray<T>::Swap(int i, int j) { T* temp; temp=m_apElement[i]; m_apElement[i]=m_apElement[j]; m_apElement[j]=temp; } template <class T> void CTArray<T>::Replace(int i, T* pElement) { ASSERT(i<m_nSize); ASSERT(pElement!=NULL); delete m_apElement[i]; m_apElement[i]=pElement; } template <class T> void CTArray<T>::Resize(int nsize, void* param) { if(param==NULL) param=m_defaultParam; ASSERT(m_nSize<=m_nCapacity); if(nsize<=m_nSize) { for(int i=nsize; i<m_nSize; i++) { delete m_apElement[i]; m_apElement[i]=NULL; } m_nSize=nsize; } else if(nsize<=m_nCapacity) { for(int i=m_nSize; i<nsize; i++) { m_apElement[i]=m_factoryFunc(param, i); } m_nSize=nsize; } else { ASSERT(nsize>m_nCapacity && nsize>m_nSize); if(m_nCapacity==0) { Init(nsize); return; } // m_nCapacity가 nsize를 포함할때까지 doubling for(;m_nCapacity<nsize;) m_nCapacity*=2; T** apTempElement=new T*[m_nCapacity]; for(int i=0; i<m_nSize; i++) // copy apTempElement[i]=m_apElement[i]; for(int i=m_nSize; i<nsize; i++) apTempElement[i]=m_factoryFunc(param, i); for(int i=nsize; i<m_nCapacity; i++) apTempElement[i]=NULL; delete[] m_apElement; m_apElement=apTempElement; m_nSize=nsize; } } template <class T> void CTArray<T>::Init(int nsize, void* param) { if(param==NULL) param=m_defaultParam; Release(); m_nSize=nsize; m_nCapacity=nsize; m_apElement=new T*[nsize]; for(int i=0; i<m_nSize; i++) { m_apElement[i]=m_factoryFunc(param, i); } } template <class T> void CTArray<T>::Release() { if(m_nSize==0) return; for(int i=0; i<m_nSize; i++) { delete m_apElement[i]; } delete[] m_apElement; m_nSize=0; m_nCapacity=0; } template <class T> T& CTArray<T>::operator[](int nIndex) const { ASSERT(nIndex>=0 && nIndex<Size()); return *m_apElement[nIndex]; } template <class T> void CTArray<T>::Sort(int start, int end, int (*compareFunc)(const void** ppElement1, const void** ppElement2)) { qsort((void*)&(m_apElement[start]), end-start, sizeof(T*), (int (*)(const void*, const void*))compareFunc); } #endif
true
4fecc4c9a5d50e88728547302d3266c6c991b59f
C++
eduhirt/CG
/t1/SCV 4.2.2 CodeBlocks/include/SCV/Mathematic.h
UTF-8
2,171
3.28125
3
[ "BSD-2-Clause" ]
permissive
/*! \file Mathematic.h \brief Basic operations of mathematics. \author SCV Team */ #ifndef __SCV_MATHEMATICS_H__ #define __SCV_MATHEMATICS_H__ #ifndef DOXYGEN_SKIP_THIS #include "Point.h" #endif // DOXYGEN_SKIP_THIS namespace scv { /*! Mathematic functions * \ingroup util */ namespace math { /*! \verbatim P11__________ | | | P21__|_______ | | | | |_______|____| | | | |____________| p12 = width and height from p11 square. p22 = width and height from p21 square. \endverbatim */ /*! Widths are positive and should grow to right and down. \return Return true if intersection area not exist. */ inline bool isInside(scv::Point p11, scv::Point p12, scv::Point p21, scv::Point p22) { if (p12.x <= 0 || p12.y <= 0 || p22.x <= 0 || p22.y <= 0) return true; int tx1 = p11.x; int ty1 = p11.y; int rx1 = p21.x; int ry1 = p21.y; int tx2 = tx1 + p12.x; int ty2 = ty1 + p12.y; int rx2 = rx1 + p22.x; int ry2 = ry1 + p22.y; if (tx1 < rx1) tx1 = rx1; if (ty1 < ry1) ty1 = ry1; if (tx2 > rx2) tx2 = rx2; if (ty2 > ry2) ty2 = ry2; if (tx2 < tx1) tx1 = tx2; if (ty2 < ty1) ty1 = ty2; if (std::abs(tx1 - tx2) * std::abs(ty1 - ty2)) return true; return false; } //! Return the nearest value from 'p'. inline double nearestValue(double p, double p1, double p2) { if (std::abs(p - p1) < std::abs(p2 - p)) return p1; return p2; } /*! \verbatim P11__________ | | | P21__|_______ | | | | |_______|____P12 | | | |____________P22 \endverbatim */ //! return New square points by reference. inline void intersectSquare(scv::Point &p11, scv::Point &p12, scv::Point &p21, scv::Point &p22) { if (p11.x < p21.x) p11.x = p21.x; if (p11.y < p21.y) p11.y = p21.y; if (p12.x > p22.x) p12.x = p22.x; if (p12.y > p22.y) p12.y = p22.y; if (p12.x < p11.x) p11.x = p12.x; if (p12.y < p11.y) p11.y = p12.y; } } // namespace math } // namespace scv #endif // __SCV_MATHEMATICS_H__
true
bd7bb2ca94d20826e46e584ab0f8e00c11892fbf
C++
zwondd/Algorithm
/codility/lesson/5_CountDiv.cpp
UTF-8
893
3.109375
3
[]
no_license
// 21-02-21 // 5_PrefixSums_CountDiv #include <vector> #include <algorithm> #include <cstring> #include <limits> using namespace std; // My Solution 1 4min (50%) O(B-A) // timeout error int solution(int A, int B, int K) { // write your code in C++14 (g++ 6.2.0) int divisible=0; for(int i=A; i<=B; i++) { if ( i%K==0 ) { divisible++; } } return divisible; } // My Solution 2 15smin (62%) O(1) // wrong answer int solution(int A, int B, int K) { return B/K-(A-1)/K; } // My Solution 3 2min (87%) // wrong answer (MAX_INT case) int solution(int A, int B, int K) { int ans=0; if ( A==0 ) ans++; return ans+(B/K-(A-1)/K); } // My Solution 4 2min (100%) O(1) int solution(int A, int B, int K) { long ans=0; if ( A==0 ) { ans++; ans+=B/K; } else { ans=(B/K-(A-1)/K); } return ans; }
true
a170e8e64743b0cb6c11d80c7a2573f901156603
C++
codemonkey-uk/pentago
/pentago.h
UTF-8
9,115
3.15625
3
[ "MIT" ]
permissive
#ifndef PENTAGO_H_INCLUDED #define PENTAGO_H_INCLUDED #include <cstdint> #include <cstring> #include <string> namespace pentago { enum state { empty = 0, white = 1, black = 2, invalid = 3 }; state fromchar( char c ); char tochar( state s ); inline state turntostate(int turn) { return (state)(1+(turn&1)); } // 0-5 x 0-5 typedef unsigned int UInt; class position { public: position() : mV(0) {} position(const position& rhs) : mV(rhs.mV) {} position(UInt x, UInt y) : mV(calc(x,y)) { } UInt getx() const { return mV%width; } UInt gety() const { return mV/width; } UInt get() const { return mV; } void set(UInt x, UInt y) { mV = calc(x,y); } void setx(UInt x) { set(x, gety()); } void sety(UInt y) { set(getx(), y); } bool operator==(const position& rhs) { return rhs.mV==mV; } position& operator+=(const position& rhs) { // x1+y1*width + x2+y2*width == x1+x2 + (y1+y2)*width // so mV += rhs.mV; return *this; } private: // note, mV is encoded as a "tightly packed" index into the board array static const UInt width = 6; static inline uint8_t calc(UInt x, UInt y) { return x+y*width; } uint8_t mV; }; inline position operator + ( position lhs, const position& rhs ) { lhs += rhs; return lhs; } // 4 bit board byte layout // [123-456-][789-ABC-] // simplifies get/set code // as it gives exact 2/byte class board_18 { public: board_18() { clear(); } void clear() { memset(mV,0,18); } state get(position p)const { UInt b = bits_per*p.get(); UInt bit = b%8; UInt byte = b/8; UInt result = (mV[byte] >> bit) & bit_mask; return (state)(result); } state get(UInt x, UInt y)const { position p(x,y); return get(p); } void set(position p, state s) { UInt b = bits_per*p.get(); UInt bit = b%8; UInt byte = b/8; mV[byte] |= (s << bit); } void clear(position p) { UInt b = bits_per*p.get(); UInt bit = b%8; UInt byte = b/8; mV[byte] &= ~(bit_mask << bit); } // clear and set void setx(position p, state s) { UInt b = bits_per*p.get(); UInt bit = b%8; UInt byte = b/8; mV[byte] &= ~(bit_mask << bit); mV[byte] |= (s << bit); } void set(UInt x, UInt y, state s) { position p(x,y); set(p, s); } // quadrant rotations, affecting : // aaabbb // a-ab-b // aaabbb // cccddd // c-cd-d // cccddd // clockwise rotation by default // method with "r" suffix for counter-clockwise void transpose_a(); void transpose_ar(); void transpose_b(); void transpose_br(); void transpose_c(); void transpose_cr(); void transpose_d(); void transpose_dr(); // per quadrant tests for rotational symmetry // returns true if transpose_X == transpose_Xr bool symetrical_a() const; bool symetrical_b() const; bool symetrical_c() const; bool symetrical_d() const; // methods to return the winning state of any: // row (along x axis) // column (along y axis) // and diagnal // winning being the colour that holds 5 in a row state winningrow(UInt index)const; state winningcol(UInt index)const; state winningdiag()const; state winning()const; static board_18 fromstring( const char* str ); private: void transpose(const position & offset); void transpose_r(const position & offset); // 3 bits per node gives misaligned bytes // (get/set more complicated) but 12b array // 4 bits per locale wastes 6 bytes with 18b array static const UInt bits_per = 4; static const UInt bit_mask = 7; uint8_t mV[18]; }; typedef board_18 board; std::string tostring( const board& b ); std::string tostring_fancy( const board& b ); class rotation { public: // rotation, quadrant and direction, stored as a byte // 4 quadrants: 00 = A, 01 = B, 10 = C, 11 = D, 1st & 2nd bits: enum quadrant { A = 0, B = 1, C = 2, D = 3 }; // 2 directions of spin, 0, & 1, 3rd bit: enum direction { clockwise = 0, anticlockwise = 4 }; rotation() : mV(0) { } rotation( quadrant q, direction d ) : mV(q | d) { } quadrant get_quadrant() const { return (quadrant)(mV & 3); } direction get_direction() const { return (direction)(mV & 4); } rotation invert() const { rotation result(*this); result.mV ^= 4; return result; } void apply(board_18* board) const { typedef void (board_18::*BoardTransformFn)(void); static const BoardTransformFn lut[] = { &board_18::transpose_a, &board_18::transpose_b, &board_18::transpose_c, &board_18::transpose_d, &board_18::transpose_ar, &board_18::transpose_br, &board_18::transpose_cr, &board_18::transpose_dr, }; ((*board).*(lut[mV]))(); } bool symetrical(const board_18* board) const { typedef bool (board_18::*BoardFn)(void)const; static const BoardFn lut[] = { &board_18::symetrical_a, &board_18::symetrical_b, &board_18::symetrical_c, &board_18::symetrical_d, }; return ((*board).*(lut[get_quadrant()]))(); } void next() { ++mV; } bool valid() const { return mV<8; } private: uint8_t mV; }; struct move { move( const position& p , const rotation& r ) : mP(p), mR(r) { } // default ctor required for vector.resize(0) to compile move() : mP(0,0), mR() { } void apply(board_18* board, UInt turn) const; void undo(board_18* board) const; position mP; rotation mR; static move fromstring( const char* str ); }; std::string tostring( const move& b ); // move_generator class empty_positions { public: empty_positions( const board& b ) : mB(b) , mP(0,0) { if (!valid()) next(); } void next(); position get(); bool finished(); private: bool valid(); void step(); const board& mB; position mP; }; } #endif
true
f7ba5ddddde212c8744d8c3d219359d54c25bb02
C++
thijse/Lightuino-Code-and-Libraries
/lightuino5/lightuinoSourceDriver.h
UTF-8
1,985
2.546875
3
[]
no_license
/*? <section name="lightuino"> */ #include "lightuino.h" #ifndef lightuinoSourceDriverH #define lightuinoSourceDriverH //?? The number of source driver lines available to you. #define Lightuino_NUMSRCDRVR 16 //?<class name="LightuinoSourceDriver"> // This class controls the source drivers on the Lightuino board. There are 16 source drivers which are capable of // providing a maximum of 500mA of current each at the voltage that you select. Note however these chips do not have // the heat dissipation to turn them all on full power at the same time -- that is not their purpose. // The onboard LM317 voltage regulator supports 1.5A. So in practice you are limited to a total of 1.5A. class LightuinoSourceDriver { public: //? <ctor>The constructor takes which digital pins are connected to the source driver chip(s).</ctor> LightuinoSourceDriver(unsigned char clkPin=Lightuino_SRC_CLOCK_PIN, unsigned char dataPin=Lightuino_SRC_DATA_PIN, unsigned char strobePin=Lightuino_SRC_STROBE_PIN, unsigned char enaPin=Lightuino_SRC_ENABLE_PIN); unsigned char clkPin; unsigned char dataPin; unsigned char strobePin; unsigned char enaPin; //? <method> Pass in a 16 bit number. Bit 0 controls whether driver line 0 is on, bit one for driver line // one and so on. </method> void set(unsigned int bitMap); //? <method> Line 0 gets the passed "bit" state. line 1 gets line 0's state, 2 gets 1 and so forth.</method> void shift(unsigned char bit); //? <method> Turn them all off. The state is retained... "output enable" is simply turned off</method> void off(void); //? <method> Turn them all on. "output enable" is simply turned on. Note that shift and set automatically // do this. </method> void on(void); }; //?</class> //? <class name="Mic5891">This is the same class as LightuinoSourceDriver, just named by the chip used.</class> #define Mic5891 LightuinoSourceDriver #endif //?</section>
true
f542fc257d89c2de85fd4020d9f063dfd8c10fda
C++
Charptr0/Escape-the-Maze
/main.cpp
UTF-8
2,901
3.59375
4
[ "Apache-2.0" ]
permissive
#include <iostream> //cout, cin #include <vector> //std::vector #include "setup/player.cpp" #include "setup/enemy.cpp" #include "setup/operators.cpp" using std::cout; using std::cin; //global variables----------------------------------- Player player; std::vector<Enemy>enemies; std::vector<std::vector<int>>deathPosition; bool gameOver = false; bool victory = false; int totalMoves = 0; //--------------------------------------------------- //based on the area of the map, it will spawn the apprioate amount of enemies void spawnEnemies() { int area = MAX_X * MAX_Y; int totalEnemies = area / 10; for(int i = 0; i < totalEnemies; i++) { Enemy e; enemies.push_back(e); deathPosition.push_back({e.x(), e.y()}); } } //draw the board, the player, and the enemies void draw() { for(int i = 0; i < MAX_Y; i++) { cout << "*"; for(int j = 0; j < MAX_X; j++) { if(i == 0 || i == (MAX_Y-1) || j == (MAX_X-1)) {cout << "*"; continue;} //handles the borders if(player.x() == j && player.y() == i) {cout << "P"; continue;} //draw the player for(size_t k = 0; k < enemies.size(); k++) //handle the enemies { if(deathPosition[k][axis::x] == j && deathPosition[k][axis::y] == i) {cout << "X"; break;} else if(k == (enemies.size()-1)) {cout << "-";} } if(i == EXIT_Y && j == EXIT_X) {cout << "\bE";} //the exit } cout << "\n"; } } //get the user input and move the player void getUserInput() { char input; cout << "Move with W,A,S,D" << "\n"; cout << "Total Moves: " << totalMoves << "\n"; cout << "Input: "; cin >> input; if(player.checkUserInput(input)) {player.move(input);} else return; } //move the enemy, update the death position vector, determine the fate of the player void logic() { deathPosition.clear(); if(player.x() == EXIT_X && player.y() == EXIT_Y) {victory = true; gameOver = true;} //if the player has reached the exit totalMoves++; for(Enemy enemy : enemies) { if(player == enemy) {gameOver = true; break;} //if the player's pos and the enemy's pos equal, the player lose the game enemy.move(); //move the enemy deathPosition.push_back({enemy.x(), enemy.y()}); } } void mainMenu() { cout << "Escape the Maze\n"; system("pause"); } int main() { mainMenu(); spawnEnemies(); while(!gameOver) { draw(); getUserInput(); logic(); } draw(); //draw the map one last time if(victory) {printf("You have escaped the maze\n");} //if the player has escaped else {printf("You have died in the maze\n");} //if the player has died printf("Total Moves: %d\n", totalMoves); //show the score system("pause"); //pause the console }
true
0cbdadf95d836880d7336d0bbcc250f0f8efc574
C++
msclar/tc-chaco-2016
/dia9/1610_DuduServiceMaker.cpp
UTF-8
917
3.265625
3
[]
no_license
#include <iostream> #include <set> #include <queue> using namespace std; int main () { // Esta implementación es un Topological Sort del grafo // Otra opción sería hacer un DFS int t, a, b, n, m; cin >> t; for (int tc = 0; tc < t; tc++) { cin >> n >> m; vector<set<int> > out(n); vector<set<int> > in(n); for (int i = 0; i < m; i++) { cin >> a >> b; a--; b--; out[a].insert(b); in[b].insert(a); } queue<int> colaVacios; for (int i = 0; i < n; i++) if (in[i].size() == 0) colaVacios.push(i); int analizados = 0; while (!colaVacios.empty()) { int t = colaVacios.front(); colaVacios.pop(); analizados++; for (std::set<int>::iterator it=out[t].begin(); it!=out[t].end(); ++it) { in[*it].erase(t); if (in[*it].size() == 0) colaVacios.push(*it); } } if (analizados == n) cout << "NAO" << endl; else cout << "SIM" << endl; } }
true
754eb8cab081077dd1e4281f7e120c95aaa1ed20
C++
tianlang0704/UO2016WCIS422AddressBook
/Database_Prototype1/Driver.cpp
UTF-8
2,643
3.234375
3
[]
no_license
#include <iostream> #include "Database.h" #include "Util.h" #define ADDRESSBOOK_NAME "ADDRESSBOOK5" using namespace std; int main() { Database db("test.db"); vector<string> colNames = { "FIRSTNAME", "LASTNAME", "ADDRESS", "ZIPCODE", "PHONENUMBER" }; db.AddTable(ADDRESSBOOK_NAME, colNames); map<string, string> entry = { {"FIRSTNAME", "JOHN"}, {"LASTNAME", "JOHN2"}, { "ADDRESS", "JJJJJ 1111 2312" }, { "ZIPCODE", "97401" }, { "PHONENUMBER", "123-456-789" } }; cout << "=============================ADD RECORD============================" << endl; db.AddRecord(ADDRESSBOOK_NAME, entry); db.AddRecord(ADDRESSBOOK_NAME, entry); db.PrintTable(ADDRESSBOOK_NAME); cout << "===================ADD COLUMN IN EXISTING TABLE====================" << endl; db.AddField(ADDRESSBOOK_NAME, "MORECOLUMN"); db.PrintTable(ADDRESSBOOK_NAME); cout << "===============UPDATING EXISTING ENTRY IN THE TABLE================" << endl; db.UpdateRecordByID(ADDRESSBOOK_NAME, "1", pair<string, string>("ADDRESS", "ADDRESS changed")); db.PrintTable(ADDRESSBOOK_NAME); cout << "===============DELETE EXISTING ENTRY IN THE TABLE==================" << endl; db.DeleteRecordByID(ADDRESSBOOK_NAME, "1"); db.PrintTable(ADDRESSBOOK_NAME); cout << "=================GETTING AN EXISTING ENTRY BY ID===================" << endl; map<string, string> returnedEntry; db.GetRecordByID(ADDRESSBOOK_NAME, 2, &returnedEntry); cout << "retrieved entry:" << endl; for (auto& i : returnedEntry) cout << i.first << " = " << i.second << endl; cout << endl; cout << "======GETTING AN EXISTING ENTRY BY FIELD VALUE CONDITION===========" << endl; db.AddRecord(ADDRESSBOOK_NAME, entry); vector< map<string, string> > entryList; map<string, string> condFields = { { "FIRSTNAME", "JOHN" }, { "LASTNAME", "JOHN2" } }; db.GetRecordByFields(ADDRESSBOOK_NAME, condFields, &entryList); cout << "retrieved entry id:" << endl; for (auto& i : entryList) cout << "ID = " << i.at("ID") << endl; cout << endl; cout << "=================CHECK IF TABLE EXISTS=============================" << endl; if (db.IsTableExist(ADDRESSBOOK_NAME)) cout << "Table " << ADDRESSBOOK_NAME << " exists" << endl; else cout << "Table " << ADDRESSBOOK_NAME << " does not exist" << endl; cout << "=================DELETE EXISTING TABLE=============================" << endl; db.DeleteTable(ADDRESSBOOK_NAME); if (db.IsTableExist(ADDRESSBOOK_NAME)) cout << "Table " << ADDRESSBOOK_NAME << " exists" << endl; else cout << "Table " << ADDRESSBOOK_NAME << " does not exist" << endl; system("pause"); return 0; }
true
e87cb937126829a7b14e22cb8e6c64cfe1f89ef3
C++
thecodingwizard/competitive-programming
/alphastar/alphastar-cs501ab-usaco-platinum-summer-2018-s2/12-advanced-greedy-methods/01 - Gangs of Istanbull-Cowstantinople.cpp
UTF-8
6,097
3.015625
3
[]
no_license
/* Gangs of Istanbull/Cowstantinople ================================= Life is tough on the farm, and when life is tough you have to get tough. The cows have formed gangs (conveniently numbered 1 to M). The gangs coexisted in peace for a while, but now things are really getting out of control! The cows are competing over control of a great grazing field. This conflict happens over a series of minutes. Each minute a single cow walks into the field. If the field is empty the new cow's gang is considered to take control of the field. If the field is already controlled by the new cow's gang then the cow just starts grazing. Otherwise, a single cow from the controlling gang that is grazing confronts the new cow. These confrontations between two cows start with some arguing and inevitably end up with the pair coming to realize how much more more alike than different they are. The cows, seeing the error in their way, leave the gang and the field and get a cold glass of soy milk at FJ's tavern. If after this confrontation the field is empty than no gang controls the field. Bessie realizes how these confrontations will occur. She knows how many cows are in each gang. Bessie really wants her gang to control the field after the conflict is over and all cows are either on the field or at FJ's tavern. Help Bessie determine if it is possible for her gang, labeled 1, to control the field in the end. If it is possible, Bessie wants to know the maximum number of cows from her gang that could be on the field at the end. Output this number and the lexicographically earliest ordering of cows that results in this number of cows from Bessie's gang at the end. An ordering X is said to be lexicographically earlier than Y if there is some k such that X[k] < Y[k] and X[i]=Y[i] for i < k. PROBLEM NAME: gangs INPUT FORMAT: * Line 1: N (1 <= N <= 100) and M (1 <= M <= N) separated by a space. The total number of cows in all the gangs will be N. The total number of gangs is M. * Lines 2..1+M: The (1+i)th line indicates how many members are in gang i. Each gang has at least 1 member. SAMPLE INPUT: 5 3 2 1 2 INPUT DETAILS: There are 5 cows and 3 gangs. Bessie's gang (gang 1) has 2 members, gang 2 has 1 member, and gang 3 has 2 members. OUTPUT FORMAT: * Line 1: Output YES on a single line if Bessie's gang can control the field after the conflict. Otherwise output NO on a single line. * Line 2: If Bessie's gang can control the field after the conflict output the maximum number of cows that could be on the field on a single line. * Lines 3..2+N: On the (i+2)th line output the index of the gang of the cow that appears in the ith minute in the lexicographically earliest ordering that leaves the maximum number of cows on the field after the conflict. SAMPLE OUTPUT: YES 1 1 3 2 3 1 OUTPUT DETAILS: Only one cow from Bessie's gang can end up on the field. */ #include <iostream> #include <string> #include <utility> #include <sstream> #include <algorithm> #include <stack> #include <vector> #include <queue> #include <map> #include <set> #include <bitset> #include <cmath> #include <cstring> #include <iomanip> #include <math.h> #include <assert.h> using namespace std; #define INF 1000000000 #define LL_INF 0xfffffffffffffffLL #define LSOne(S) (S & (-S)) #define EPS 1e-9 #define A first #define B second #define mp make_pair #define PI acos(-1.0) typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; vi cowCount; int n, m; int curCowsOnField = 0, curGang = -1; int send(int startGang) { priority_queue<ii, vii> pq; for (int i = 2; i <= m; i++) { if (i == startGang && cowCount[i] == 1) continue; if (cowCount[i] == 0) continue; pq.push(mp((i == startGang ? cowCount[i] - 1 : cowCount[i]), i)); } int cowsOnField = 1, gang = startGang; if (curGang == startGang) { cowsOnField += curCowsOnField; } else { if (curCowsOnField == cowsOnField) { cowsOnField = 0; } else if (curCowsOnField > cowsOnField) { cowsOnField = curCowsOnField - cowsOnField; gang = curGang; } else { cowsOnField = cowsOnField - curCowsOnField; } } while (!pq.empty()) { ii cow = pq.top(); pq.pop(); if (cow.B == gang) { cowsOnField += cow.A; continue; } if (cowsOnField == 0) { cowsOnField = cow.A; gang = cow.B; } else { cowsOnField--; if (cow.A > 1) pq.push(mp(cow.A - 1, cow.B)); } } if (startGang == 1) return cowCount[1] - cowsOnField - 1; return cowCount[1] - cowsOnField; } int main() { cin >> n >> m; cowCount.resize(m+10); for (int i = 1; i <= m; i++) { cin >> cowCount[i]; } vi order; int answer = -INF; while (order.size() < n) { int best = -INF, bestGang; for (int i = 1; i <= m; i++) { if (cowCount[i] == 0) continue; int left = send(i); if (best < left) { best = left; bestGang = i; } } int cowsOnField = 1, gang = bestGang; if (curGang == bestGang) { cowsOnField += curCowsOnField; } else { if (curCowsOnField == cowsOnField) { cowsOnField = 0; } else if (curCowsOnField > cowsOnField) { cowsOnField = curCowsOnField - cowsOnField; gang = curGang; } else { cowsOnField = cowsOnField - curCowsOnField; gang = bestGang; } } curCowsOnField = cowsOnField; curGang = gang; cowCount[bestGang]--; order.push_back(bestGang); if (answer == -INF) answer = best; } if (answer <= 0) { cout << "NO" << endl; return 0; } cout << "YES" << endl << answer << endl; for (int cow : order) cout << cow << endl; return 0; }
true
04e0bc2cc3d87dece494e5ffee2b0881230ba5b7
C++
tsutaj/cpp_library
/graph/graph_005_kruskal.cpp
UTF-8
794
3.4375
3
[]
no_license
// クラスカル法 (最小全域木問題) // Edgeには from, to, cost の情報が必須。計算量( |E| log|V| ) // Union-find木を使うので、それも忘れずに組み込むこと。 template <typename T> T kruskal(vector< vector< Edge<T> > > &G) { int V = G.size(); vector< Edge<T> > es; for(size_t i=0; i<V; i++) { for(size_t j=0; j<G[i].size(); j++) { es.push_back(G[i][j]); } } int E = es.size(); sort(es.begin(), es.end()); UnionFind uf(V); T res = 0; for(int i=0; i<E; i++) { Edge<T> e = es[i]; if(!uf.same(e.from, e.to)) { uf.unite(e.from, e.to); res += e.cost; } } return res; } // 最小全域有向木 (有向グラフ)
true
8e825fea5bb096c74b63a7bc89dacab17f236527
C++
FantasyAlpha/Phase-1
/playground/playground game/Game.cpp
UTF-8
11,035
2.546875
3
[]
no_license
#include "Game.h" global_variable Game_Resources Resources; float screenWidth; float screenHeight; global_variable SceneManager Game_Scene; //Movement AutomaticDirections dir; void AutomaticMove(char *ActorName, float velocity, float delta) { // if collide change your direction if (dir.Rigth) { if (!Game_Scene.CollisionManager.GetCollider(ActorName)->rigth) { Game_Scene.ActorManager.GetTransform(ActorName)->Position.X += velocity*delta*40.0f; /*float temp = Game_Scene.ActorManager.GetTransform(ActorName)->Position.X; Game_Scene.CollisionManager.GetCollider(ActorName)->pos->X = temp;*/ //Movable->collider.pos.X += velocity*0.016f*40.0f; Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.X = velocity*delta*40.0f; dir.counter++; if (dir.counter > velocity*100.0f) { dir.Rigth = false; dir.Left = true; dir.counter = 0; } } else { dir.Rigth = false; dir.Left = true; dir.counter = 0; } } if (dir.Left) { if (!Game_Scene.CollisionManager.GetCollider(ActorName)->left) { Game_Scene.ActorManager.GetTransform(ActorName)->Position.X -= velocity*delta*40.0f; // Movable->collider.pos.X -= velocity*0.016f*40.0f; /*float temp = Game_Scene.ActorManager.GetTransform(ActorName)->Position.X; Game_Scene.CollisionManager.GetCollider(ActorName)->pos->X = temp;*/ Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.X = -velocity*delta*40.0f; dir.counter++; if (dir.counter > velocity*100.0f) { dir.Rigth = true; dir.Left = false; dir.counter = 0; } } else { dir.Rigth = true; dir.Left = false; dir.counter = 0; } } } float Accelerate(float flGoal, float flCurrent, float delta){ float flDifference = flGoal - abs(flCurrent); if (flDifference > delta) // vdash= v+at // new velocity= current velocity + delta * acceleration constant return abs(flCurrent) + delta * Game_Scene.CollisionManager.physics.acceleration; if (flDifference < -delta) return abs(flCurrent) - delta* Game_Scene.CollisionManager.physics.acceleration; return flGoal; } vec2f currentvelocity=0.0f; void Move(char *ActorName, vec2f goalVelocity, float delta, Game_Input *input, bool Run) { currentvelocity.X = Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.X; if ((input->RIGHT.KeyUp) && (input->LEFT.KeyUp)/*!input->LEFT.KeyDown&&!input->RIGHT.KeyDown*/){ Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.X = 0.0f; currentvelocity.X = 0.0f; } else if (input->RIGHT.KeyDown) { if (Game_Scene.CollisionManager.GetCollider(ActorName)->rigth == false) { //currentvelocity.X = Accelerate(goalVelocity.X, currentvelocity.X, delta); currentvelocity.X = goalVelocity.X*delta; Game_Scene.ActorManager.GetTransform(ActorName)->Position.X += currentvelocity.X; Game_Scene.ActorManager.GetTransform(ActorName)->Scale.X = 1; Game_Scene.MainCamera.Eye.X += currentvelocity.X; /*float temp = Game_Scene.TransformManager.GetTransform(ActorName)->Position.X; Game_Scene.CollisionManager.GetCollider(ActorName)->pos->X = temp;*/ Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.X = currentvelocity.X; } } else if (input->LEFT.KeyDown) { if (Game_Scene.CollisionManager.GetCollider(ActorName)->left == false) { //currentvelocity.X = -1.0f * Accelerate(goalVelocity.X, currentvelocity.X, delta); currentvelocity.X = -1.0f*goalVelocity.X*delta; Game_Scene.ActorManager.GetTransform(ActorName)->Position.X += currentvelocity.X; Game_Scene.MainCamera.Eye.X += currentvelocity.X; Game_Scene.ActorManager.GetTransform(ActorName)->Scale.X = -1; /*float temp = Game_Scene.TransformManager.GetTransform(ActorName)->Position.X; Game_Scene.CollisionManager.GetCollider(ActorName)->pos->X = temp;*/ Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.X = currentvelocity.X; } } //std::cout << "player velocity " << currentvelocity.X << std::endl; } float fallSpeed = 0.0f; bool jumpflag = false; //float Gravity = 2.0f; float jumpSpeed = 13.0f; void jumpHandle(char*ActorName, Game_Input *input, float delta) { bool groundCheck = false; bool Jump; Jump = Game_Scene.CollisionManager.GetCollider(ActorName)->jump; if (Jump) { groundCheck = true; } if (groundCheck) { //Jump = true; fallSpeed = 0; Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.Y = 0; } if (input->Space.KeyDown&&groundCheck) { // reset jumpSpeed = 13.0f; jumpflag = true; Jump = false; groundCheck = false; } if (Game_Scene.CollisionManager.GetCollider(ActorName)->up) { jumpflag = false; } if (jumpflag&&fallSpeed == 0){ Game_Scene.ActorManager.GetTransform(ActorName)->Position.Y += jumpSpeed; // Game_Scene.CollisionManager.GetCollider(ActorName)->pos->Y += jumpSpeed; Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.Y = jumpSpeed; jumpSpeed -= Game_Scene.CollisionManager.physics.Gravity*delta * 10.0f; if (jumpSpeed <= 0){ jumpflag = false; // Reset jump speed ****************importatnt jumpSpeed = 13.0f; } } else if (!groundCheck) { fallSpeed += (Game_Scene.CollisionManager.physics.Gravity*delta*25.0f); Game_Scene.ActorManager.GetTransform(ActorName)->Position.Y -= fallSpeed; //Game_Scene.CollisionManager.GetCollider(ActorName)->pos->Y -= fallSpeed; Game_Scene.CollisionManager.GetCollider(ActorName)->velocity.Y = fallSpeed; } } GAME_DLL GAME_INIT(Game_Init) { { screenWidth = dimensions.Width; screenHeight = dimensions.Height; } { InitResources(); } InitGameWorld(); } float x, y; bool debug = false; //Render the game GAME_DLL GAME_RENDER(Game_Render) { Game_Scene.RenderScene(debug); } //Update the game //Game_Input *input GAME_DLL GAME_UPDATE(Game_Update) { Game_Scene.MousePos.X = input->MousePos.X - (screenWidth / 2.0f); Game_Scene.MousePos.Y = -input->MousePos.Y + (screenHeight / 2.0f); if (input->P.KeyDown) { debug = true; } if (input->D .KeyDown) { debug = false; } Game_Scene.ActorManager.GetTransform("KAI2")->Rotation.Z += 1; AutomaticMove("brick", 2.0f, delta); Game_Scene.CollisionManager.CheckGroundCollision("player"); jumpHandle("player", input, 0.016f); Move("player", 400.0f, delta, input, false); Game_Scene.UpdateScene(0.016f); } GAME_DLL GAME_SHUTDOWN(Game_Shutdown) { } void InitResources() { // add resources : Textures AddTexture(&Resources, LoadTexture("resources\\textures\\tile1.png"), "Tile1"); AddTexture(&Resources, LoadTexture("resources\\textures\\tile2.png"), "Tile2"); AddTexture(&Resources, LoadTexture("resources\\textures\\empty.png"), "Empty"); AddTexture(&Resources, LoadTexture("resources\\textures\\player_2.png"), "PLAYER"); AddTexture(&Resources, LoadTexture("resources\\textures\\Neo In.png"), "neo"); AddTexture(&Resources, LoadTexture("resources\\textures\\back.png"), "Back"); AddTexture(&Resources, LoadTexture("resources\\textures\\star.png"), "star"); AddTexture(&Resources, LoadTexture("resources\\textures\\grayCube.png"), "cube"); } void InitGameWorld() { { Game_Scene.MainCamera = Camera(vec2f(screenWidth, screenHeight)); Game_Scene.MainCamera.Type = CameraType::ORTHOGRAPHIC; } { Game_Scene.InitScene(100); } { // Actor creations Game_Scene.ActorManager.AddActor("KAI2", Transform{}); Game_Scene.ActorManager.AddActor("backGround", Transform{}); Game_Scene.ActorManager.AddActor("player", Transform{}); Game_Scene.ActorManager.AddActor("platform", Transform{}); Game_Scene.ActorManager.AddActor("brick", Transform{}); Game_Scene.ActorManager.AddActor("wall", Transform{}); } { // Modify Transforms Game_Scene.ActorManager.GetTransform("backGround")->Position = vec3f(0, 0, 0); Game_Scene.ActorManager.GetTransform("platform")->Position = vec3f(0, -330.0f, 0); Game_Scene.ActorManager.GetTransform("KAI2")->Position = vec3f(-200.0f, 200.0f, 0); Game_Scene.ActorManager.GetTransform("brick")->Position = vec3f(0.0f, -290.0f, 0); Game_Scene.ActorManager.GetTransform("wall")->Position = vec3f(500.0f, 0.0f, 0); Game_Scene.ActorManager.GetTransform("player")->Position = vec3f(200.0f, -200.0f, 0); } { // Animation components uint32 frames[4]; frames[0] = 4; frames[1] = 5; frames[2] = 6; frames[3] = 7; Game_Scene.AnimationManager.AddComponent("a1", 4, 2, frames, 4, 0.001f, true); } { // Render components //Game_Scene.AnimationManager.GetAnimationClip("a1") Game_Scene.RendererManager.InitMainShader("resources\\shaders\\vertex shader 120.vert", "resources\\shaders\\fragment shader 120.frag"); Game_Scene.RendererManager.InitDebugShader("resources\\shaders\\vertex shader 120_2.vert", "resources\\shaders\\fragment shader 120_2.frag"); Game_Scene.RendererManager.AddComponent("backGround" , vec2f(screenWidth * 2.0f, screenHeight) , Material{ GetTexture(&Resources, "Back"), vec4f{ 1, 1, 1, 1 } }); Game_Scene.RendererManager.AddComponent("brick" , vec2f(100.0f, 50.0f) , Material{ GetTexture(&Resources, "Empty"), vec4f{ 1, .3f, .5f, 1 } }); Game_Scene.RendererManager.AddComponent("wall" , vec2f(50.0f, screenHeight) , Material{ GetTexture(&Resources, "Empty"), vec4f{ 0, .3f, .5f, 1 } }); Game_Scene.RendererManager.AddComponent("player" , vec2f(100.0f, 200.0f) , Material{ GetTexture(&Resources, "neo"), vec4f{ 1, 1, 1, 1 } }); Game_Scene.RendererManager.AddComponent("KAI2" , vec2f(50.0f, 50.0f) , Material{ GetTexture(&Resources, "star"), vec4f{ 1, 1, 1, 1 } }); Game_Scene.RendererManager.AddComponent("platform" , vec2f(screenWidth * 2.0f, 50.0f) , Material{ GetTexture(&Resources, "Empty"), vec4f{ 1, 1, 1, 1 } }); } { //Collision component // Addcomponent (actorName , vec3f *pos , vec2 size ,bool ground ,bool wall ,bool trigger) Game_Scene.CollisionManager.AddComponent("KAI2", &Game_Scene.ActorManager.GetTransform("KAI2")->Position, Game_Scene.RendererManager.GetRenderable("KAI2")->Size, false, false, false); Game_Scene.CollisionManager.AddComponent("brick", &Game_Scene.ActorManager.GetTransform("brick")->Position, Game_Scene.RendererManager.GetRenderable("brick")->Size , true, false, false); Game_Scene.CollisionManager.AddComponent("wall", &Game_Scene.ActorManager.GetTransform("wall")->Position, Game_Scene.RendererManager.GetRenderable("wall")->Size , true, true, false); Game_Scene.CollisionManager.AddComponent("player", &Game_Scene.ActorManager.GetTransform("player")->Position, vec2f(50.0f, 175.0f), false, false, false); Game_Scene.CollisionManager.AddComponent("platform", &Game_Scene.ActorManager.GetTransform("platform")->Position, Game_Scene.RendererManager.GetRenderable("platform")->Size , true, false, false); } } void computetime(clock_t start, clock_t end){ double elapsedtime = ((double)(end - start) / (double)(CLOCKS_PER_SEC)) * 1000.0f; std::cout << "game render time is : " << elapsedtime << " ms" << std::endl; }
true
1215da8c7176021d508885584743bb092ce83194
C++
theisen1337/LogicCapStone
/DevSprint1/World.h
UTF-8
888
3.28125
3
[]
no_license
//! World Class /*! Manages multiple chunks that make up the entire world. */ #pragma once #include <vector> #include "Chunk.h" class World { private: int worldSize = 2; /*!< World Size*/ int offset = 3/2; /*!< (Not Used) Offset of the world*/ public: //! 2D vector of the chunks in the world std::vector<std::vector<Chunk>> world; //! World Constructor World(); //! World Initalization. /*! Used to initalize the world after the objects creation. */ void InitalizeClass(); //! Chunk Initial Generation. /*! Used to generate the chunks. */ void initialGeneration(); //! Update World Method /*! Used to update the map when the player able to see chunks that are not generated. Used for Infinite Map. */ void updateWorld(int charWorldW, int charWorldH); //! World 2D vector Getter. std::vector<std::vector<Chunk>> getChunk() { return world; }; };
true
d77a80d5d75a211343b8a341a05d516a4111b398
C++
Sunshine-Rain/trees
/BinaryTree/BinaryTree/BST/BinarySearchTree.hpp
UTF-8
2,378
2.75
3
[]
no_license
// // BinarySearchTree.hpp // BinaryTree // // Created by quan on 2019/1/28. // Copyright © 2019 quan. All rights reserved. // #ifndef BinarySearchTree_hpp #define BinarySearchTree_hpp #include <stdio.h> #include "BinaryTree.hpp" template <typename T> class BinarySearchTree: public BinaryTree<T> { BinaryNodePosi(T) & searchIn(BinaryNodePosi(T) & v, const T& e, BinaryNodePosi(T) & hot); protected: BinaryNodePosi(T) _hot; BinaryNodePosi(T) connect34(BinaryNodePosi(T), BinaryNodePosi(T), BinaryNodePosi(T), BinaryNodePosi(T),BinaryNodePosi(T),BinaryNodePosi(T),BinaryNodePosi(T)); BinaryNodePosi(T) rotateAt(BinaryNodePosi(T) x); public: virtual BinaryNodePosi(T) & search(const T& e); virtual BinaryNodePosi(T) insert(const T& e); virtual bool remove(const T& e); }; template <typename T> BinaryNodePosi(T) & BinarySearchTree<T>::searchIn(BinaryNodePosi(T) & v, const T& e, BinaryNodePosi(T) & hot) { if (!v || v->data == e) return v; hot = v; return searchIn((v->data < e) ? v->rightChild : v->leftChild, e, hot); } template <typename T> BinaryNodePosi(T) & BinarySearchTree<T>::search(const T& e) { return searchIn(this->_root, e, _hot = NULL); } template <typename T> BinaryNodePosi(T) BinarySearchTree<T>::insert(const T& e) { BinaryNodePosi(T) & posi = search(e); if (posi) return posi; posi = new BinaryTreeNode<T>(e, _hot); this->_size++; this->updateHeightAbove(posi); return posi; } template <typename T> bool BinarySearchTree<T>::remove(const T& e) { BinaryNodePosi(T) & posi = search(e); if (!posi) return false; removeAt(posi, _hot); this->_size--; this->updateHeightAbove(posi); return true; } template <typename T> static BinaryNodePosi(T) removeAt(BinaryNodePosi(T)& x, BinaryNodePosi(T)& hot) { BinaryNodePosi(T) w = x; BinaryNodePosi(T) succ = NULL; if(!HasLChild(*x)) { succ = x = x->rightChild; } else if (!HasRChild(*x)) { succ = x = x->leftChild; } else { w = w->succ(); swap(x->data, w->data); BinaryNodePosi(T) u = w->parent; ((u == x) ? u->rightChild : u->leftChild) = succ = w->rightChild; } hot = w->parent; if (succ) succ->parent = hot; delete w; return succ; } #endif /* BinarySearchTree_hpp */
true
8ff542843ee5afb14fa45e78642c44494b5aa8a7
C++
tamamu/algonote
/atcoder-abc047b.cpp
UTF-8
657
2.890625
3
[]
no_license
#include <iostream> int main() { using namespace std; int32_t W, H, N; cin >> W >> H >> N; int32_t xl = 0, xr = W, yt = 0, yb = H; for (auto j = 0; j < N; ++j) { int32_t x, y, a; cin >> x >> y >> a; switch(a) { case 1: xl = max(xl, x); break; case 2: xr = min(xr, x); break; case 3: yt = max(yt, y); break; case 4: yb = min(yb, y); break; } } auto area = max(0,xr-xl)*max(0,yb-yt); cout << area << endl; }
true
353b9d8a96315411496cdb889dd170f21d861300
C++
LuckyGrx/PAT_Basic_Level
/C++/1054.cpp
UTF-8
2,247
3.171875
3
[]
no_license
#include<iostream> #include<string> #include<sstream> #include<stdio.h> using namespace std; stringstream ss; bool isLegalNumber(string a); bool isThreePoint(string a); int getPointNumber(string a); bool isAllNumber(string a); bool isContainNumber(string a); int main() { int n; cin >> n; string* a = new string[n]; for (int i = 0; i < n; i++) cin >> a[i]; double sum = 0.0; int count = 0; for (int i = 0; i < n; i++) { if (isLegalNumber(a[i])) { count++; double temp; ss << a[i]; ss >> temp; sum += temp; ss.clear(); } else { cout << "ERROR: " << a[i] << " is not a legal number" << endl; } } if (count >= 2) { printf("%s %d %s %.2f\n", "The average of", count, "numbers is", sum / count); } else if (count == 1) { printf("%s %d %s %.2f\n", "The average of", count, "number is", sum / count); } else{ cout << "The average of 0 numbers is Undefined" << endl; } return 0; } bool isLegalNumber(string a) { if (getPointNumber(a) > 1) return false; else if (getPointNumber(a) == 1) { if (isThreePoint(a)) { if (isAllNumber(a)) { if (isContainNumber(a)) return true; else return false; } else return false; } else return false; } else { if (isAllNumber(a)) { if (isContainNumber(a)) return true; else return false; } else return false; } } bool isThreePoint(string a) { if (a.size() - a.find('.') > 3) return false; else return true; } int getPointNumber(string a) { int number = 0; for (int i = 0; i < a.size(); i++) if (a[i] == '.') number++; return number; } bool isAllNumber(string a) { if (a.size() > 1) { if (!(a[0] == '-' || a[0] == '+' || a[0] >= '0'&&a[0] <= '9' || a[0] == '.')) return false; for (int i = 1; i < a.size(); i++) if (!(a[i] >= '0'&&a[i] <= '9'||a[i]=='.')) return false; return true; } else { if ((a[0] >= '0'&&a[0] <= '9')) return true; else return false; } } bool isContainNumber(string a) { double tempDouble; ss << a; ss >> tempDouble; ss.clear(); if (tempDouble <= 1000.0&&tempDouble >= -1000.0) return true; else return false; }
true
4ab37feb553a5d34dd52a12ddbbc8ff3f75c2d26
C++
3l-d1abl0/DS-Algo
/cpp/practise/turtles_path_he.cpp
UTF-8
2,690
2.53125
3
[]
no_license
#include <iostream> using namespace std; #define MOD 1000000007 bool isPrime[1000000]; int valid[2000][2000]; int ar[2000][2000]; int F[2000][2000]; int n, m; void seive () { for ( int i = 2; i <= 200000; i ++ ) { if ( ! isPrime[i] ) { for ( int j = i + i; j <= 200000; j += i) { isPrime[j] = 1; } } } } int vis[3000][3000]; void print_index ( int i, int j) { //cout <<i <<"^"<< j << endl; vis[i][j] = 1; if (i == 0 and j == 0 ) { return; } if (valid[i-1][j -1] == 0 and !vis[i-1][j-1]) { print_index ( i - 1, j - 1) ; } if (valid[i-1][j] == 0 and !vis[i-1][j] ) { print_index ( i - 1, j ) ; } if (valid[i][j -1] == 0 and !vis[i][j-1] ) { print_index ( i , j - 1) ; } } void karo ( int i, int j ) { cout << i << " "<<j << endl; if ( i== n and j == m ) return; if ( vis[i+1][j+1] and !valid[i+1][j+1] ) karo(i+1, j+1); else if ( vis[i+1][j] and !valid[i+1][j] ) karo(i+1, j); else if ( vis[i][j+1] and !valid[i][j+1] ) karo(i, j+1); } int main() { cin >> n >> m; for ( int i = 0; i <= n; i++ ) for ( int j = 0; j <= m; j++ ) valid[i][j] = 1; seive(); for ( int i = 1; i <= n; i ++ ) for ( int j = 1; j <= m; j++ ) { int x; cin >> x; valid[i][j] = isPrime[x]; } /* for ( int i = 1; i <= n; i++ ){ for ( int j = 1; j <= m; j++ ) { cout << valid[i][j] <<" "; } cout <<endl; }*/ // for ( int j = 1; j <= m; j++ ) ar[1][j] = !valid[1][j]; ar[0][0] = 1; valid[0][0] = 0; for ( int i = 1; i <= n; i++ ) { for ( int j = 1; j <= m; j++ ) { long acc = 0; if ( valid[i][j] == 1) continue; if ( valid[i-1][j-1] == 0) { acc += ar[i-1][j-1]; } if ( valid[i-1][j] == 0 ) { acc += ar[i-1][j]; } if ( valid[i][j-1] == 0 ) { acc += ar[i][j-1]; } acc %= MOD; ar[i][j] = acc; } } cout <<ar[n][m]<<endl; if (ar[n][m] == 0 ) return 0; print_index(n,m); for(int i=1;i<=n;i++){ for(int j=1; j<=m;j++){ cout<<valid[i][j]<<" "; } cout<<endl; } for(int i=1;i<=n;i++){ for(int j=1; j<=m;j++){ cout<<vis[i][j]<<" "; } cout<<endl; } karo(1,1); return 0; } //http://ideone.com/OspjDM
true
af99703c1273e78a3f76edb7928701d312284f65
C++
xupeiwust/pv-meshless
/sph/KernelCusp.h
UTF-8
2,440
3.03125
3
[]
no_license
// filename: // KernelCusp.hpp // description: // A concrete kernel class. // authors: // Sven Ganzenmueller <ganzenmu@informatik.uni-tuebingen.de> // Frank Heuser <heuserf@informatik.uni-tuebingen.de> // last modified: // $Date: 2005/03/08 08:28:41 $ // project: // sph2000 // filetype: // c++-class // #ifndef CUSP_HPP #define CUSP_HPP #include "Kernel.h" #include "Vector.hpp" /** * A parabolic sector as kernel named "cusp". * See Speith (1998), p.81. * <br> * This Kernel has a well-developed peak in the center. */ class VTK_EXPORT KernelCusp : public Kernel { public: /** * Constructor to initialize the data members and * pre-calculate some factors to save time when calling w() and gradW(). */ KernelCusp(int dim, double smoothingLength); /** * Calculates the kernel value for the given distance of two particles. * The used formula is Speith (3.133). */ virtual double w(double distance) const; virtual double w(double h, double distance) const; /** * Calculates the kernel derivation for the given distance of two particles. * The used formula is Speith (3.134) for the value with (3.21) for the direction of the * gradient vector. * Be careful: grad W is antisymmetric in r (3.25)!. */ virtual Vector gradW(double distance, const Vector& distanceVector) const; virtual Vector gradW(double h, double distance, const Vector& distanceVector) const; /** return the maximum distance at which this kernel is non zero */ virtual double maxDistance() const; /** return the multiplier between smoothing length and max cutoff distance */ virtual double getDilationFactor() const { return 1.0; } private: /** The assignment operator. * This class does not need an assignment operator. * By declaring it privat, without defining it * (no implementation in the cpp source file), * we prevent the compiler from generating one * (See Scott Meyers, Effective C++, Lections 11+27 for more details!) */ KernelCusp& operator=(const KernelCusp& non); /** Normalization factor */ double norm; /** Auxiliary factors for intermediate results: The inverse smoothing length */ double Hinverse; double maxRadius; /** Auxiliary factors for intermediate results: A pre-factor for w */ double factorW; /** Auxiliary factors for intermediate results: A pre-factor for grad w */ double factorGradW; }; #endif
true
75a5622f8c3243a391aa7327bd2eec9b00198292
C++
gmc1322/FreeTime
/2017/BehaviorTree/BehaviorTreeDLL/Source/BehaviorTree_MultiBranch.h
UTF-8
1,621
2.921875
3
[]
no_license
#pragma once #include "BehaviorTree_Stack.h" namespace BehaviorTreeSpace { class MultiBranch { public: /** * \brief The constructor for the Multi Branch * * \param FunctionPtr - The function for the Branch to run * \param DataStorageKey - The Key to the Data Storage for the Branch to use, default = 0 */ BehaviorTreeDLL_API MultiBranch( BranchFunctionPtr FunctionPtr, size_t DataStorageKey = 0 ) noexcept; public: /** * \brief Runs the Branch's execution flow * * \param DataStoragePtr - The Data Storage to access * \param ParentStack - The stack for the parents of this branch * * \exception BadDataThrow - Your Data Storage is bad! * \exception BadDataKeyThrow - The Data Storage Key provided to a Branch was bad! * \exception BadBranchThrow - The Branch execution flow value was bad! * * \return If we are done running or not */ BehaviorTreeDLL_API bool RunBranch( TreeDataStoragePtr DataStoragePtr, StackClass &ParentStack ) ThrowingElse( noexcept( false ), noexcept ); public: Branches MultiBranches; // Map containing all of the Nodes connected one deep to this Branch protected: int BranchReturn_ = Current; // The return value to know which Branch to run. If -1 run this Branch, if -2 run prev private: BranchFunctionPtr FunctionPtr_; // What to run when this Branch is selected const size_t DataStorageKey_; // Key to know which Data Storage to use }; }
true
fc6150f9dafc09335d39bd2f18a709f803ac5d17
C++
IshwarKulkarni/ToyTracer
/vec2.h
UTF-8
3,669
3.421875
3
[]
no_license
/*************************************************************************** * Vec2.h * * * * Vec2 is a trivial encapsulation of 2D floating-point coordinates. * * It has all of the obvious operators defined as inline functions. * * * * History: * * 04/01/2003 Initial coding. * * * ***************************************************************************/ #ifndef __VEC2_INCLUDED__ #define __VEC2_INCLUDED__ #include <cmath> #include <iostream> struct Vec2 { inline Vec2() : x(0.), y(0.) {} inline Vec2( double a, double b ) : x(a), y(b) {} inline ~Vec2() {} inline void Zero() { x = 0.0; y = 0.0; } double x; double y; }; inline double LengthSquared( const Vec2 &A ) { return A.x * A.x + A.y * A.y; } inline double Length( const Vec2 &A ) { return sqrt( LengthSquared( A ) ); } inline Vec2 operator+( const Vec2 &A, const Vec2 &B ) { return Vec2( A.x + B.x, A.y + B.y ); } inline Vec2 operator-( const Vec2 &A, const Vec2 &B ) { return Vec2( A.x - B.x, A.y - B.y ); } // Unary minus operator. inline Vec2 operator-( const Vec2 &A ) { return Vec2( -A.x, -A.y ); } inline Vec2 operator*( double a, const Vec2 &A ) { return Vec2( a * A.x, a * A.y ); } inline Vec2 operator*( const Vec2 &A, double a ) { return Vec2( a * A.x, a * A.y ); } // Inner product of A and B. inline double operator*( const Vec2 &A, const Vec2 &B ) { return (A.x * B.x) + (A.y * B.y); } inline Vec2 operator/( const Vec2 &A, double c ) { return Vec2( A.x / c, A.y / c ); } // Pad A & B with a zero z component, then return the z-component // of the cross product of the resulting 3D vectors. inline double operator^( const Vec2 &A, const Vec2 &B ) { return A.x * B.y - A.y * B.x; } inline Vec2 & operator+=( Vec2 &A, const Vec2 &B ) { A.x += B.x; A.y += B.y; return A; } inline Vec2 & operator-=( Vec2 &A, const Vec2 &B ) { A.x -= B.x; A.y -= B.y; return A; } inline Vec2 & operator*=( Vec2 &A, double a ) { A.x *= a; A.y *= a; return A; } inline Vec2 & operator/=( Vec2 &A, double a ) { A.x /= a; A.y /= a; return A; } // Remove component of A that is parallel to B. inline Vec2 operator/( const Vec2 &A, const Vec2 &B ) { const double x( LengthSquared( B ) ); return ( x > 0.0 ) ? ( A - (( A * B ) / x) * B ) : A; } // Return a normalized version of the vector A. inline Vec2 Unit( const Vec2 &A ) { const double d( LengthSquared( A ) ); return d > 0.0 ? A / sqrt(d) : Vec2(0,0); } // Return a normalized version of the vector (x,y). inline Vec2 Unit( double x, double y ) { const double d( (x * x) + (y * y) ); return d > 0.0 ? Vec2(x,y) / sqrt(d) : Vec2(0,0); } // Euclidean distance from A to B. inline double dist( const Vec2 &A, const Vec2 &B ) { return Length( A - B ); } inline std::ostream & operator<<( std::ostream &out, const Vec2 &A ) { out << "(" << A.x << ", " << A.y << ")"; return out; } #endif
true
94cf032f23d72f93a3139a27570970f8ee4a9fa2
C++
MarnickHuysmans/Minigin
/Minigin/SceneManager.cpp
UTF-8
1,662
2.859375
3
[]
no_license
#include "MiniginPCH.h" #include "SceneManager.h" #include "Scene.h" void dae::SceneManager::CreateScene(const std::string& name, const std::function<void(Scene&)>& sceneFunction) { auto it = std::find_if(std::begin(m_Scenes), std::end(m_Scenes), [&name](const std::pair<std::string, std::function<void(Scene&)>>& scene) { return scene.first == name; }); if (it != std::end(m_Scenes)) { return; } m_Scenes.push_back({ name, sceneFunction }); } std::weak_ptr<dae::Scene> dae::SceneManager::GetCurrentScene() const { return m_CurrentScene; } void dae::SceneManager::SwitchScene(const std::string& name) { auto it = std::find_if(std::begin(m_Scenes), std::end(m_Scenes), [&name](const std::pair<std::string, std::function<void(Scene&)>>& scene) { return scene.first == name; }); if (it == std::end(m_Scenes)) { return; } m_SwitchIndex = std::distance(std::begin(m_Scenes), it); m_Switch = true; } void dae::SceneManager::SwitchScene(size_t index) { if (index >= m_Scenes.size()) { return; } m_SwitchIndex = index; m_Switch = true; } void dae::SceneManager::Start() { if (m_Scenes.empty()) { m_CurrentScene = std::shared_ptr<Scene>(new Scene("EmptyScene")); } else { auto& startScene = m_Scenes[m_SwitchIndex]; m_CurrentScene = std::shared_ptr<Scene>(new Scene(startScene.first)); startScene.second(*m_CurrentScene); } m_CurrentScene->Start(); } void dae::SceneManager::Update() { if (m_Switch) { Start(); m_Switch = false; } m_CurrentScene->Update(); } void dae::SceneManager::Render() const { m_CurrentScene->Render(); } void dae::SceneManager::RenderUi() const { m_CurrentScene->RenderUi(); }
true
a0718548f9e8e07d2cf9c485dd59e445b571cda2
C++
Lanysc/UVA-CODES
/UVA - 11286.cpp
UTF-8
683
2.8125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int r, aux, maior; while(scanf("%d",&r) && r != 0) { map<vector<int>,int> mp; aux = 0; maior = 0; while(r--) { vector<int> vec; int x[5]; scanf("%d %d %d %d %d",&x[0],&x[1],&x[2],&x[3],&x[4]); for(int i = 0; i < 5; i++) { vec.push_back(x[i]); } sort(vec.begin(),vec.end()); mp[vec]++; } for(map<vector<int>,int>::iterator i = mp.begin(); i != mp.end(); i++) { //cout << i->second << endl; if(i->second > aux) { aux = i->second; maior = 0; } if(i->second == aux) maior += aux; } printf("%d\n",maior); } }
true
cd96e03e675c2302ec84c8b94eb98b72e3d1c43a
C++
GobySoft/goby3-clang
/pubsub_entry.h
UTF-8
4,684
2.65625
3
[]
no_license
#ifndef PUBSUB_ENTRY_20190801H #define PUBSUB_ENTRY_20190801H #include <string> #include "yaml_raii.h" namespace viz { class Thread; } namespace goby { namespace clang { enum class Layer { UNKNOWN = -1, INTERTHREAD = 0, INTERPROCESS = 1, INTERVEHICLE = 2 }; struct PubSubEntry { PubSubEntry(Layer l, const YAML::Node& yaml, const std::map<std::string, std::shared_ptr<viz::Thread>> threads); PubSubEntry(Layer l, const YAML::Node& yaml, const std::string& th = "") { layer = l; auto thread_node = yaml["thread"]; if (thread_node) thread = thread_node.as<std::string>(); else thread = th; group = yaml["group"].as<std::string>(); scheme = yaml["scheme"].as<std::string>(); type = yaml["type"].as<std::string>(); auto inner_node = yaml["inner"]; if (inner_node && inner_node.as<bool>()) is_inner_pub = true; } PubSubEntry(Layer l, std::string th, std::string g, std::string s, std::string t) : layer(l), thread(th), group(g), scheme(s), type(t) { } Layer layer{Layer::UNKNOWN}; std::string thread; std::string group; std::string scheme; std::string type; void write_yaml_map(YAML::Emitter& yaml_out, bool include_thread = true, bool inner_pub = false) const { goby::yaml::YMap entry_map(yaml_out, false); entry_map.add("group", group); entry_map.add("scheme", scheme); entry_map.add("type", type); if (include_thread) entry_map.add("thread", thread); // publication was automatically added to this scope from an outer publisher if (inner_pub) entry_map.add("inner", "true"); } bool is_inner_pub{false}; }; inline std::ostream& operator<<(std::ostream& os, const PubSubEntry& e) { return os << "layer: " << static_cast<int>(e.layer) << ", thread: " << e.thread << ", group: " << e.group << ", scheme: " << e.scheme << ", type: " << e.type; } inline bool operator<(const PubSubEntry& a, const PubSubEntry& b) { if (a.layer != b.layer) return a.layer < b.layer; if (a.thread != b.thread) return a.thread < b.thread; if (a.group != b.group) return a.group < b.group; if (a.scheme != b.scheme) return a.scheme < b.scheme; return a.type < b.type; } inline bool connects(const PubSubEntry& a, const PubSubEntry& b) { return a.layer == b.layer && a.group == b.group && (a.scheme == b.scheme || a.scheme == "CXX_OBJECT" || b.scheme == "CXX_OBJECT") && a.type == b.type; } inline void remove_disconnected(PubSubEntry pub, PubSubEntry sub, std::set<PubSubEntry>& disconnected_pubs, std::set<PubSubEntry>& disconnected_subs) { disconnected_pubs.erase(pub); disconnected_subs.erase(sub); auto cxx_sub = sub; cxx_sub.scheme = "CXX_OBJECT"; disconnected_subs.erase(cxx_sub); } } // namespace clang } // namespace goby namespace viz { struct Thread { Thread(std::string n, std::set<std::string> b = std::set<std::string>()) : name(n), bases(b) {} Thread(std::string n, const YAML::Node& y, std::set<std::string> b = std::set<std::string>()) : name(n), bases(b), yaml(y) { } void parse_yaml() { auto publish_node = yaml["publishes"]; for (auto p : publish_node) interthread_publishes.emplace(goby::clang::Layer::INTERTHREAD, p, most_derived_name()); auto subscribe_node = yaml["subscribes"]; for (auto s : subscribe_node) interthread_subscribes.emplace(goby::clang::Layer::INTERTHREAD, s, most_derived_name()); } std::string most_derived_name() { if (parent) return parent->most_derived_name(); else return name; } std::string name; std::set<std::string> bases; YAML::Node yaml; // child thread instance if we're not a direct base of SimpleThread std::shared_ptr<Thread> child; // this thread has a parent who isn't a direct base of SimpleThread std::shared_ptr<Thread> parent; std::set<goby::clang::PubSubEntry> interthread_publishes; std::set<goby::clang::PubSubEntry> interthread_subscribes; }; } // namespace viz inline goby::clang::PubSubEntry::PubSubEntry( Layer l, const YAML::Node& yaml, const std::map<std::string, std::shared_ptr<viz::Thread>> threads) : PubSubEntry(l, yaml) { if (threads.count(thread)) thread = threads.at(thread)->most_derived_name(); } #endif
true
72c522ce491049b56bbb3d2b907523080a3a0239
C++
llkrakerll/teamwork
/OurProject/OurProject/MethodsDriverList.cpp
WINDOWS-1251
9,954
3.046875
3
[]
no_license
#include "stdafx.h" #include <iostream> #include <windows.h> #include <conio.h> #include <iomanip> #include "ClassDriverList.h" #include "GlobalMethods.h" using namespace std; // DriverList DriverList::~DriverList() // { while (!setPtrsDrivers.empty()) // , { // iter = setPtrsDrivers.begin(); delete *iter; setPtrsDrivers.erase(iter); } } //--------------------------------------------------------- void DriverList::insertDriver(Driver* ptrD) { setPtrsDrivers.push_back(ptrD); // } //-------------------------------------------------------- void DriverList::Editing() { color(0); cout << " ID , : " << endl; cin >> IDforEdit; iter = setPtrsDrivers.begin(); // while (iter != setPtrsDrivers.end()) // { // ( ID ID ) sID = (*iter)->GetID(); if (IDforEdit == sID) // id id { cout << " : "; cin >> EditFam; (*iter)->Fam = EditFam; cout << " : "; cin >> EditName; (*iter)->Name = EditName; cout << " : "; cin >> EditOtch; (*iter)->Otch = EditOtch; cout << " : "; cin >> EditCity; (*iter)->City = EditCity; cout << " : "; cin >> EditStreet; (*iter)->Street = EditStreet; cout << " : "; do { cin >> EditNumberHome; CheckInt(EditNumberHome); } while (EditNumberHome < 0); (*iter)->NumberHome = EditNumberHome; cout << " : "; do { cin >> EditNumberFlat; CheckInt(EditNumberFlat); } while (EditNumberFlat < 0); (*iter)->NumberFlat = EditNumberFlat; cout << " : "; do { cin >> EditPhone; CheckLong(EditPhone); } while (EditPhone < 0); (*iter)->Phone = EditPhone; cout << " : "; do { cin >> EditNarushen; CheckLong(EditNarushen); } while (EditNarushen < 0); (*iter)->Narushen = EditNarushen; cout << " :"; do { cin >> EditNumberCar; CheckLong(EditNumberCar); } while (EditNumberCar < 0); (*iter)->NumberCar = EditNumberCar; cout << " : "; cin >> EditMarkCar; (*iter)->MarkCar = EditMarkCar; cout << " ? (Y() N())" << endl; do // { cin >> EditLife; if (EditLife == "Y") { (*iter)->Life = ""; } else if (EditLife == "N") { (*iter)->Life = "̸"; } else { cout << " Y N"; } } while ((EditLife != "Y") && (EditLife != "N")); } iter++; } void enterProbel(); // } void DriverList::DisplayLife() // { string tLife; // ( ) color(1); cout << setw(100) << "--------------------------" << endl; cout << setw(100) << "| |" << endl; cout << setw(100) << "--------------------------" << endl; color(2); cout << "\n\n-----------------------------------------------------------------------" << endl; cout << "|| ID || || || || /̸ ||" << endl; cout << "-----------------------------------------------------------------------" << endl; if (setPtrsDrivers.empty()) // cout << "\n\n*** . .***\n" << endl; // , ) else { iter = setPtrsDrivers.begin(); while (iter != setPtrsDrivers.end()) // { tLife = (*iter)->GetLife(); // if (tLife != "") // ... { color(0); cout << "||" << setw(4) << (*iter)->GetID() << "||" << setw(15) << (*iter)->GetFam() << "||" << setw(13) << (*iter)->GetName() << "||" << setw(16) << (*iter)->GetOtch() << "||" << setw(11) << (*iter)->GetLife() << "||" << endl; *iter++; color(2); cout << "-----------------------------------------------------------------------" << endl; } else *iter++; } } color(0); cout << "\n\n"; void enterProbel(); // } //-------------------------------------------------------- void DriverList::DisplayNarushen() // { int tNarushen; // color(1); cout << setw(100) << "-------------------------------" << endl; cout << setw(100) << "| |" << endl; cout << setw(100) << "-------------------------------" << endl; color(2); cout << "\n\n-----------------------------------------------------------------------------------" << endl; cout << "|| ID || || || || ||" << endl; cout << "-----------------------------------------------------------------------------------" << endl; if (setPtrsDrivers.empty()) // cout << "\n\n*** . .***\n" << endl; // , ) else { iter = setPtrsDrivers.begin(); while (iter != setPtrsDrivers.end()) // { tNarushen = (*iter)->GetNarushen(); // if (tNarushen > 0) // ... { color(0); cout << "||" << setw(4) << (*iter)->GetID() << "||" << setw(15) << (*iter)->GetFam() << "||" << setw(13) << (*iter)->GetName() << "||" << setw(16) << (*iter)->GetOtch() << "||" << setw(23) << (*iter)->GetNarushen() << "||" << endl; *iter++; color(2); cout << "-----------------------------------------------------------------------------------" << endl; } else *iter++; } } color(0); cout << "\n\n"; void enterProbel(); // } //-------------------------------------------------------- void DriverList::display() // ( ) { color(2); cout << "\n\n"; cout << "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" << endl; cout << "|| ID || || || || || || || || || || || || /̸ ||" << endl; cout << "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" << endl; color(0); if (setPtrsDrivers.empty()) // cout << "\n\n*** . .***\n" << endl; // , else { iter = setPtrsDrivers.begin(); while (iter != setPtrsDrivers.end()) // { color(0); cout << "||" << setw(5) << (*iter)->GetID() << "||" << setw(13) << (*iter)->GetFam() << "||" << setw(13) << (*iter)->GetName() << "||" << setw(16) << (*iter)->GetOtch() << "||" << setw(15) << (*iter)->GetCity() << "||" << setw(19) << (*iter)->GetStreet() << "||" << setw(8) << (*iter)->GetNumberHome() << "||" << setw(12) << (*iter)->GetNumberFlat() << "||" << setw(13) << (*iter)->GetPhone() << "||" << setw(17) << (*iter)->GetNarushen() << "||" << setw(10) << (*iter)->GetNumberCar() << "||" << setw(17) << (*iter)->GetMarkCar() << "||" << setw(11) << (*iter)->GetLife() << "||" << endl; *iter++; color(2); cout << "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" << endl; } } } //---------------------------------------------------------
true
1c4399e260385bdd8ff3efc18803cd1c3e2769d4
C++
berkAktug/OpenGL_FishSimilator
/CS405-OpenGL-v0.5/ResourceManager.h
UTF-8
5,001
3
3
[]
no_license
#ifndef RESOURCE_MANAGER_H #define RESOURCE_MANAGER_H #include <map> #include "shader.h" #include "texture.h" //#include <SOIL.h> class ResourceManager { public: // Resource storage static std::map<std::string, Shader> Shaders; static std::map<std::string, Texture3D> Textures; // Loads (and generates) a shader program from file loading vertex, fragment (and geometry) shader's source code. If gShaderFile is not nullptr, it also loads a geometry shader static Shader LoadShader(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile, std::string name); // Retrieves a stored sader static Shader GetShader(std::string name); // Loads (and generates) a texture from file // Possible bug here. static Texture3D LoadTexture(const GLchar *file, GLboolean alpha, std::string name); // Retrieves a stored texture static Texture3D GetTexture(std::string name); // Properly de-allocates all loaded resources static void Clear(); private: // Private constructor, that is we do not want any actual resource manager objects. Its members and functions should be publicly available (static). ResourceManager() { } // Loads and generates a shader from file static Shader loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile = nullptr); // Loads a single texture from file static Texture3D loadTextureFromFile(const GLchar *file, GLboolean alpha); }; // Instantiate static variables std::map<std::string, Texture3D> ResourceManager::Textures; std::map<std::string, Shader> ResourceManager::Shaders; Shader ResourceManager::LoadShader(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile, std::string name) { Shaders[name] = loadShaderFromFile(vShaderFile, fShaderFile, gShaderFile); return Shaders[name]; } Shader ResourceManager::GetShader(std::string name) { return Shaders[name]; } Texture3D ResourceManager::GetTexture(std::string name) { return Textures[name]; } void ResourceManager::Clear() { // (Properly) delete all shaders for (auto iter : Shaders) glDeleteProgram(iter.second.getID()); // (Properly) delete all textures for (auto iter : Textures) glDeleteTextures(1, &iter.second.ID); } Shader ResourceManager::loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile) { // 1. Retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::string geometryCode; try { // Open files std::ifstream vertexShaderFile(vShaderFile); std::ifstream fragmentShaderFile(fShaderFile); std::stringstream vShaderStream, fShaderStream; // Read file's buffer contents into streams vShaderStream << vertexShaderFile.rdbuf(); fShaderStream << fragmentShaderFile.rdbuf(); // close file handlers vertexShaderFile.close(); fragmentShaderFile.close(); // Convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); // If geometry shader path is present, also load a geometry shader if (gShaderFile != nullptr) { std::ifstream geometryShaderFile(gShaderFile); std::stringstream gShaderStream; gShaderStream << geometryShaderFile.rdbuf(); geometryShaderFile.close(); geometryCode = gShaderStream.str(); } } catch (std::exception e) { std::cout << "ERROR::SHADER: Failed to read shader files" << std::endl; } const GLchar *vShaderCode = vertexCode.c_str(); const GLchar *fShaderCode = fragmentCode.c_str(); const GLchar *gShaderCode = geometryCode.c_str(); // 2. Now create shader object from source code Shader shader; //Shader shader(vShaderFile, fShaderFile, gShaderFile != nullptr ? gShaderCode : nullptr); shader.Compile(vShaderCode, fShaderCode, gShaderFile != nullptr ? gShaderCode : nullptr); return shader; } Texture3D ResourceManager::loadTextureFromFile(const GLchar *file, GLboolean alpha) { // Create Texture object Texture3D texture; if (alpha) { texture.setInternal_Format(GL_RGBA); texture.setImage_Format(GL_RGBA); } // Load image int width, height, nrComponents; unsigned char *data = stbi_load(file, &width, &height, &nrComponents, 0); if (data) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, texture.ID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << file << std::endl; stbi_image_free(data); } return texture; } #endif
true
a3e3fb0247eb1dc551b891b3e27a77df23328c86
C++
sahmed19/PokemonCPlusPlus
/PokemonProject/PokemonProject/Pokemon.cpp
UTF-8
7,759
2.671875
3
[]
no_license
#include "Pokemon.h" #include "Pokedex.h" #include "TypeData.h" using namespace std; const float NatureData::natureMultiplierLookupTable[25][6] = { { 0, 1, 1, 1, 1, 1 }, { 0, 1.1f, 0.9f, 1, 1, 1 }, { 0, 1.1f, 1, 1, 1, 0.9f }, { 0, 1.1f, 1, 0.9f, 1, 1 }, { 0, 1.1f, 1, 1, 0.9f, 1 }, { 0, 0.9f, 1.1f, 1, 1, 1 }, { 0, 1, 1, 1, 1, 1 }, { 0, 1, 1.1f, 1, 1, 0.9f }, { 0, 1, 1.1f, 0.9f, 1, 1 }, { 0, 1, 1.1f, 1, 0.9f, 1 }, { 0, 0.9f, 1, 1, 1, 1.1f }, { 0, 1, 0.9f, 1, 1, 1.1f }, { 0, 1, 1, 1, 1, 1 }, { 0, 1, 1, 0.9f, 1, 1.1f }, { 0, 1, 1, 1, 0.9f, 1.1f }, { 0, 0.9f, 1, 1.1f, 1, 1 }, { 0, 1, 0.9f, 1.1f, 1, 1 }, { 0, 1, 1, 1.1f, 1, 0.9f }, { 0, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1.1f, 0.9f, 1 }, { 0, 0.9f, 1, 1, 1.1f, 1 }, { 0, 1, 0.9f, 1, 1.1f, 1 }, { 0, 1, 1, 1, 1.1f, 0.9f }, { 0, 1, 1, 0.9f, 1.1f, 1 }, { 0, 1, 1, 1, 1, 1 } }; float NatureData::getNatureStatMultiplier(int _nature, int _stat) { return natureMultiplierLookupTable[_nature][_stat]; } string NatureData::NatureToString(Nature _nature) { const string natureStrings[25] = { "HARDY", "LONELY", "BRAVE", "ADAMANT", "NAUGHTY", "BOLD", "DOCILE", "RELAXED", "IMPISH", "LAX", "TIMID", "HASTY", "SERIOUS", "JOLLY", "NAIVE", "MODEST", "MILD", "QUIET", "BASHFUL", "RASH", "CALM", "GENTLE", "SASSY", "CAREFUL", "QUIRKY" }; return natureStrings[(int)_nature]; } Nature NatureData::getRandomNature() { int index = rand() % 24; return (Nature)index; } Pokemon::Pokemon(PokemonData* _pokemonData, Gender _gender, Nature _nature, bool _shiny, bool _pokerus, string _ability, int _IV_HP, int _IV_ATK, int _IV_DEF, int _IV_SPA, int _IV_SPD, int _IV_SPE, string _nickname, int _level, int _EV_HP, int _EV_ATK, int _EV_DEF, int _EV_SPA, int _EV_SPD, int _EV_SPE, MoveData* _moves[4], Status _status) : pokemonData(_pokemonData), gender(_gender), nature(_nature), shiny(_shiny), pokerus(_pokerus), ability(_pokemonData->checkAbility(_ability)), IV_HP(_IV_HP), IV_ATK(_IV_ATK),IV_DEF(_IV_DEF), IV_SPA(_IV_SPA),IV_SPD(_IV_SPD), IV_SPE(_IV_SPE), nickname(_nickname), level(_level), XP(PokemonData::getLevelEXP(_pokemonData->getGrowthRateString(), _level)), EV_HP(_EV_HP), EV_ATK(_EV_ATK), EV_DEF(_EV_DEF), EV_SPA(_EV_SPA), EV_SPD(_EV_SPD), EV_SPE(_EV_SPE), status(_status), ID(Pokedex::Instance()->getNewID()) { setMoves(_moves); updateStats(); } Pokemon::Pokemon(PokemonData* _pokemonData, int _level) : pokemonData(_pokemonData), gender(_pokemonData->getRandomGender()), nature(NatureData::getRandomNature()), shiny((int) (rand()* SHINY_CHANCE) == 2), pokerus((int) (rand()* SHINY_CHANCE) == 2), ability(_pokemonData->getRandomAbility()), IV_HP ((int)(rand() % 32)), IV_ATK((int)(rand() % 32)), IV_DEF((int)(rand() % 32)), IV_SPA((int)(rand() % 32)), IV_SPD((int)(rand() % 32)), IV_SPE((int)(rand() % 32)), nickname(""), level(_level), XP(PokemonData::getLevelEXP(_pokemonData->getGrowthRateString(), _level)), EV_HP(0), EV_ATK(0), EV_DEF(0), EV_SPA(0), EV_SPD(0), EV_SPE(0), status(Status::NO_STATUS), ID(Pokedex::Instance()->getNewID()) { setMoves(_pokemonData->getBestMovesAtLevel(level)); updateStats(); modHP(100000); } Pokemon::~Pokemon() { } void Pokemon::setMoves(MoveData* _moves[4]) { for (int i = 0; i < 4; i++) { moves[i] = _moves[i]; } } void Pokemon::modHP(int amount) { currentHP += amount; if (currentHP < 0) { currentHP = 0; status = Status::FAINTED; } else if(currentHP > HP){ currentHP = HP; } } bool Pokemon::checkForDeath() { if (currentHP <= 0) { status = Status::FAINTED; return true; } return false; } string Pokemon::getName(bool realNameToo) { if (nickname != "") { if (realNameToo) { return "\"" + nickname + "\" " + pokemonData->getName(); } return nickname; } return pokemonData->getName(); } int Pokemon::getNumberOfMoves() { int numMoves = 0; for (int i = 0; i < 4; i++) { if (moves[i] != nullptr) { numMoves++; } } return numMoves; } bool Pokemon::isType(PokemonType _type) { return (_type == pokemonData->getPokemonType1()) || (_type == pokemonData->getPokemonType2()); } string Pokemon::afflictStatus(Status _status) { if (_status == Status::NO_STATUS || status == Status::NO_STATUS) { status = _status; const string fx[8] = { "was cured!", "fell asleep!", "was poisoned!", "was badly poisoned!", "was burned!", "was paralyzed!", "was frozen solid!", "fucking died!"}; return fx[(int)status]; } else { } } float Pokemon::getTypeEffectivenessAgainst(PokemonType type) const { return TypeData::getTypeEffectiveness(type, pokemonData->getPokemonType1()) * TypeData::getTypeEffectiveness(type, pokemonData->getPokemonType2()); } void Pokemon::print(bool detailedStats) { const char* genderArray = "NMF"; cout << "--BASIC" << endl; cout << "Name: " << pokemonData->getName() << endl; cout << "Level: " << level << endl; cout << "Gender: " << genderArray[gender] << endl; cout << "Nature: " << NatureData::NatureToString(nature) << endl; cout << "Shiny: " << shiny << endl; cout << "Pokerus: " << pokerus << endl; cout << "Ability: " << ability << endl << endl; cout << "--MOVES" << endl; for (int i = 0; i < 4; i++) { if (moves[i] != nullptr) { moves[i]->print(); } else { cout << "{NO MOVE}" << endl; } cout << "###" << endl; } if (detailedStats) { cout << "--IVs" << endl; cout << "HP: " << IV_HP << endl; cout << "ATK: " << IV_ATK << endl; cout << "DEF: " << IV_DEF << endl; cout << "SPA: " << IV_SPA << endl; cout << "SPD: " << IV_SPD << endl; cout << "SPE: " << IV_SPE << endl << endl; cout << "--EVs" << endl; cout << "HP: " << EV_HP << endl; cout << "ATK: " << EV_ATK << endl; cout << "DEF: " << EV_DEF << endl; cout << "SPA: " << EV_SPA << endl; cout << "SPD: " << EV_SPD << endl; cout << "SPE: " << EV_SPE << endl << endl; } cout << "--Final Stats" << endl; cout << "HP: " << HP << endl; cout << "ATK: " << attack << endl; cout << "DEF: " << defense << endl; cout << "SPA: " << specialAttack << endl; cout << "SPD: " << specialDefense << endl; cout << "SPE: " << speed << endl << endl; } void Pokemon::updateStats() { previousLevelXP = PokemonData::getLevelEXP(pokemonData->getGrowthRateString(), level); nextLevelXP = PokemonData::getLevelEXP(pokemonData->getGrowthRateString(), level + 1); //HP - Stat = floor((2 * B + I + E) * L / 100 + L + 10) float HPRatio = getHPRatio(); HP = (int) ((2.0f * pokemonData->getHP() + IV_HP + EV_HP) * (level / 100.0f) + level + 10); currentHP = (int) (HP * getHPRatio()); //OTHERS - Stat = floor(floor((2 * B + I + E) * L / 100 + 5) * N) attack = (int)((int)( (2.0f * pokemonData->getATK() + IV_ATK + EV_ATK) * (level / 100.0f) + 5) * NatureData::getNatureStatMultiplier(nature, Stat::ATK)); defense = (int)((int)( (2.0f * pokemonData->getDEF() + IV_DEF + EV_DEF) * (level / 100.0f) + 5) * NatureData::getNatureStatMultiplier(nature, Stat::DEF)); specialAttack = (int)((int)( (2.0f * pokemonData->getSPA() + IV_SPA + EV_SPA) * (level / 100.0f) + 5) * NatureData::getNatureStatMultiplier(nature, Stat::SPA)); specialDefense = (int)((int)( (2.0f * pokemonData->getSPD() + IV_SPD + EV_SPD) * (level / 100.0f) + 5) * NatureData::getNatureStatMultiplier(nature, Stat::SPD)); speed = (int)((int)( (2.0f * pokemonData->getSPE() + IV_SPE + EV_SPE) * (level / 100.0f) + 5) * NatureData::getNatureStatMultiplier(nature, Stat::SPE)); } bool Pokemon::checkForLevelUp() { int prev = level; while (level < 100 && XP > nextLevelXP) { level++; updateStats(); } return level > prev; }
true
b21fdbb09090b88e6340f69f21de2bd067851c1b
C++
JasenRatnam/vehicleRentalManagement
/Assignment_2/CashPayment.h
UTF-8
622
2.796875
3
[]
no_license
/* * Author: Jasen Ratnam 40094237 * Date: 2/2/2019 * Due date: 11/2/2019 * Assignment 2 * CashPayment class, inheritance from payment * File that contains the specification of the class CashPayment. * Initializes the functions and variables used in the class CashPayment. */ #ifndef CASHPAYMENT_H #define CASHPAYMENT_H #include "Payment.h" class CashPayment : public Payment { public: //constructors CashPayment(); // default CashPayment(float payment); // regualr ~CashPayment(); // destructor // print payment details void paymentDetails() const; }; #endif /* CASHPAYMENT_H */
true
c208f38a400905612dfcdb52ac7050c0a81273c4
C++
Viral-Doshi/DSA
/016_Count_Inversions.cpp
UTF-8
1,312
2.984375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int cnt = 0; void Merge(int arr[], int l, int m, int r){ int n1 = m-l+1, n2 = r-m; int* left = new int[n1]; int* right = new int[n2]; for(int i =0; i<n1; i++) left[i] = arr[l+i]; for(int j=0; j<n2; j++) right[j] = arr[m+1+j]; int i=0, j=0, k=l, rel_pos; while (i < n1 && j < n2){ if (left[i] <= right[j]){ arr[k] = left[i]; rel_pos = i - (k-l); rel_pos = (rel_pos > 0 ? rel_pos:0); cnt += rel_pos; i++; } else{ arr[k] = right[j]; rel_pos = (n1+j) - (k-l); rel_pos = (rel_pos > 0 ? rel_pos:0); cnt += rel_pos; j++; } k++; } while(i<n1){ arr[k] = left[i]; i++; k++; } while(j<n2){ arr[k] = right[j]; j++; k++; } } void MergeSort(int arr[], int l, int r){ if (l >= r) return; int m = (l+r)/2; MergeSort(arr, l, m); MergeSort(arr, m+1, r); Merge(arr,l,m,r); } int main(){ int n,temp; cin >> n; int* arr = new int[n]; for(int i=0; i<n; i++){ cin >> temp; arr[i] = temp; } MergeSort(arr,0,n-1); cout << cnt; return 0; }
true
eb0c0623821dc2a06c81a1723849e15d22850a89
C++
arceciemat/GAMOS
/source/SEAL_Foundation/SealBase/tests/Time02.cpp
UTF-8
911
2.578125
3
[]
no_license
#include "SealTest/SealTest.h" #include "SealBase/Time.h" #include "SealBase/Signal.h" #include <iostream> #include <iomanip> using namespace seal; int seal_test::Time02(int, char **argv) { Signal::handleFatal (argv[0]); Time t = Time::current (); unsigned d = Time::toDosDate (t); Time t2 = Time::fromDosDate (d); seal_test::out << "time: " << t << std::endl << "dos: " << d << std::endl << "undos: " << t2 << std::endl << std::endl; CPPUNIT_ASSERT_DOUBLES_EQUAL( t.second(true), t2.second(true), 1 ); t += 5 * 30 * TimeConst::SECS_PER_DAY * TimeConst::SEC_NSECS; d = Time::toDosDate (t); t2 = Time::fromDosDate (d); seal_test::out << "time: " << t << std::endl << "dos: " << d << std::endl << "undos: " << t2 << std::endl; CPPUNIT_ASSERT_DOUBLES_EQUAL( t.second(true), t2.second(true), 1 ); return 0; }
true
82c287f504503a0fbd390c71411a40575be29be4
C++
ankurkamthe/arduino-nano33-ble
/toggle_rgb_1/toggle_rgb_1.ino
UTF-8
1,778
3.234375
3
[ "MIT" ]
permissive
/* This sketch changes led colors on the board. The sketch only uses the loop() and delay() to keep led in a particular state (color). Note: Using the pinMode and digitalWrite function in an unconventional way. Typically, setting HIGH should turn on the led, but my I played around with this the opposite worked. Not spending too much time on this now... */ #define PIN_LED (13u) #define LED_BUILTIN PIN_LED #define LEDR (22u) #define LEDG (23u) #define LEDB (24u) #define LED_PWR (25u) const int arr[] = {LED_BUILTIN, LEDR, LEDG, LEDB}; int adv_type = 0; const int ledPin = LED_BUILTIN; // pin to use for the LED char buffer[100]; void only_red() { int led = arr[1]; //sprintf(buffer, "toggle: %d", led); //Serial.println(buffer); pinMode(led, OUTPUT); digitalWrite(led, LOW); delay(5000); pinMode(led, INPUT); } void only_green() { int led = arr[2]; pinMode(led, OUTPUT); digitalWrite(led, LOW); delay(5000); pinMode(led, INPUT); } void only_blue() { int led = arr[3]; pinMode(led, OUTPUT); digitalWrite(led, LOW); delay(5000); pinMode(led, INPUT); } bool changeLeds(void *) { Serial.println("change colors..."); switch (adv_type) { case 0: Serial.println("red"); only_red(); adv_type = 1; Serial.println("done"); break; case 1: Serial.println("green"); only_green(); adv_type = 2; Serial.println("done"); break; case 2: Serial.println("blue"); only_blue(); adv_type = 0; Serial.println("done"); break; default: Serial.println("should not print"); break; } return true; } void setup() { Serial.println("Setup Done"); } void loop() { changeLeds(NULL); }
true
8c17fa497d433ff80010f775562eaf7d0ca9378d
C++
glareprotector/active_site
/src/cpp_caller.h
UTF-8
15,560
2.84375
3
[]
no_license
#ifndef CPP_CALLER_H #define CPP_CALLER_H #include <Python.h> //#include <cstring> #include <string> //#include <string.h> //#include "nums.h" #include <set> #include "globals.h" typedef double num; using namespace std; // this function will allow one to call module functions(not member functions of any object) // will need to specify the module name, function name. extern set<string> added_paths; class cpp_caller{ public: static PyObject* call_PyFunc(string module_name, string fxn_name, PyObject* pArgs){ // load module PyObject* pFunc = get_module_PyObject(module_name, fxn_name); PyObject* pValue = PyObject_CallObject(pFunc, pArgs); return pValue; } // imports module, assuming it is in path. returns new reference static PyObject* _get_module(string module_name){ char* module_name_char = new char[1000]; strcpy(module_name_char, module_name.c_str()); PyObject* pName = PyString_FromString(module_name_char); PyObject* pModule = PyImport_Import(pName); Py_DECREF(pName); delete[] module_name_char; return pModule; } // gets object from module, assuming path is correctly set. returns borrowed reference static PyObject* _get_module_PyObject(string module_name, string obj_name){ // convert arguments to char* char* obj_name_char = new char[1000]; strcpy(obj_name_char, obj_name.c_str()); PyObject *pModule, *pDict, *pObj; pModule = _get_module(module_name); // new if(pModule == NULL){ cout<<"no module "<<module_name<<" "<<obj_name<<endl; } pDict = PyModule_GetDict(pModule); // borrowed pObj = PyDict_GetItemString(pDict, obj_name_char); // borrowed Py_DECREF(pModule); delete[] obj_name_char; return pObj; } // adds module path to sys.path if needed. returns borrowed reference static PyObject* get_module_PyObject(string module_name, string obj_name, string module_path = string(".")){ // if module path is not in paths, add it if(added_paths.find(module_path) == added_paths.end()){ // get reference to sys.path PyObject* pSysPath = _get_module_PyObject(string("sys"), string("path")); PyObject* pPathString = PyString_FromString(module_path.c_str()); PyList_Insert(pSysPath, 0, pPathString); Py_DECREF(pPathString); } PyObject* pObj = _get_module_PyObject(module_name, obj_name); return pObj; } // returns attribute of object static PyObject* get_object_attr(PyObject* pObj, string attr_name){ PyObject* pAttr_name = PyString_FromCPPString(attr_name); PyObject* pResult = PyObject_GetAttr(pObj, pAttr_name); Py_DECREF(pAttr_name); return pResult; } // returns new empty param object static PyObject* get_new_empty_param(){ PyObject* pParamDict = PyDict_New(); PyObject* pMakeNewParamArgs = PyTuple_New(1); PyTuple_SetItem(pMakeNewParamArgs, 0, pParamDict); PyObject* pParams = call_PyFunc(string("param"), string("param"), pMakeNewParamArgs); Py_DECREF(pMakeNewParamArgs); return pParams; } // sets param key to val, with the type(in python) of val indicated static void set_param(PyObject* pParams, string key, void* val_p, int type){ PyObject* pKey = PyString_FromCPPString(key); PyObject* pObj; switch(type){ case globals::INT_TYPE: pObj = PyInt_FromLong(*((int*)val_p)); break; case globals::NUM_TYPE: pObj = PyFloat_FromDouble(*(num*)val_p); break; case globals::STRING_TYPE: pObj = PyString_FromCPPString(*(string*)val_p); break; case globals::STRING_VECT: pObj = cpp_caller::cpp_string_vect_to_py_string_list(*(arbi_array<string1d>*)val_p); break; case globals::NUM_VECT: pObj = cpp_caller::cpp_num_vect_to_py_float_list(*(arbi_array<num1d>*)val_p); break; case globals::STRING_MAT: pObj = cpp_caller::CPPString_mat_to_py_string_mat(*(arbi_array<string2d>*)val_p); break; case globals::INT_VECT: pObj = cpp_caller::cpp_int_vect_to_py_int_list(*(arbi_array<int1d>*)val_p); break; } PyObject* pMethodName = PyString_FromCPPString(string("set_param")); PyObject* pResult = PyObject_CallMethodObjArgs(pParams, pMethodName, pKey, pObj, NULL); Py_DECREF(pKey); Py_DECREF(pObj); Py_DECREF(pMethodName); Py_DECREF(pResult); } // retrieves param from pParams of given key static PyObject* get_param(PyObject* pParams, string key){ PyObject* pMethodName = PyString_FromCPPString(string("get_param")); PyObject* pKey = cpp_caller::PyString_FromCPPString(key); PyObject* pResult = PyObject_CallMethodObjArgs(pParams, pMethodName, pKey, NULL); Py_DECREF(pMethodName); Py_DECREF(pKey); return pResult; } // converts python list of float to c++ array of nums static arbi_array<num1d> py_float_list_to_cpp_num_vect(PyObject* pList, bool decref = false){ if(pList == NULL) throw 20; int len = PyList_Size(pList); arbi_array<num1d> result(len); for(int i = 0; i < len; i++){ result(i) = (num)PyFloat_AsDouble(PyList_GetItem(pList, i)); } if(decref) Py_DECREF(pList); return result; } // convert c++ array of nums to python list of floats static PyObject* cpp_num_vect_to_py_float_list(arbi_array<num1d> x){ int size = x.size().i0; PyObject* pX = PyList_New(size); for(int i = 0; i < size; i++){ PyList_SetItem(pX, i, PyFloat_FromDouble(x(i))); } return pX; } // converts python list of ints to c++ array of ints static arbi_array<int1d> py_int_list_to_cpp_int_vect(PyObject* pList, bool decref = false){ if(pList == NULL) throw 20; int len = PyList_Size(pList); arbi_array<int1d> result; result.resize(len); for(int i = 0; i < len; i++){ result(i) = PyInt_AsLong(PyList_GetItem(pList, i)); } if(decref) Py_DECREF(pList); return result; } // convert c++ array of nums to python list of floats static PyObject* cpp_int_vect_to_py_int_list(arbi_array<int1d> x){ int size = x.size().i0; PyObject* pX = PyList_New(size); for(int i = 0; i < size; i++){ PyList_SetItem(pX, i, PyInt_FromLong(x(i))); } return pX; } // convert python float list to c++ list of strings static arbi_array<string1d> py_string_list_to_cpp_string_vect(PyObject* pList, bool decref = false){ if(pList == NULL) throw 20; int len = PyList_Size(pList); arbi_array<string1d> result(len); for(int i = 0; i < len; i++){ result(i) = cpp_caller::CPPString_From_PyString(PyList_GetItem(pList, i)); } if(decref) Py_DECREF(pList); return result; } // convert c++ list of strings to python float list static PyObject* cpp_string_vect_to_py_string_list(arbi_array<string1d> x){ int size = x.size().i0; PyObject* pList = PyList_New(size); for(int i = 0; i < size; i++){ PyList_SetItem(pList, i, PyString_FromCPPString(x(i))); } return pList; } // prints a python object static void py_print(PyObject* pObj){ PyObject* pFunc = cpp_caller::get_module_PyObject(string("new_new_objects"), string("print_stuff")); PyObject_Print(pObj, stdout, 0); PyObject_Print(pFunc, stdout, 0); PyObject* pResult = PyObject_CallFunctionObjArgs(pFunc, pObj, NULL); Py_DECREF(pResult); } // convert python mat of strings to c++ mat of strings static arbi_array<string2d> py_string_mat_to_cpp_string(PyObject* pMat, bool decref = false){ if(pMat == NULL) throw 20; int size0 = PyList_Size(pMat); PyObject* pRow = PyList_GetItem(pMat, 0); int size1 = PyList_Size(pRow); arbi_array<string2d> xx(size0, size1); for(int a = 0; a < size0; a++){ PyObject* pRow = PyList_GetItem(pMat, a); for(int j = 0; j < size1; j++){ xx(a,j) = CPPString_From_PyString(PyList_GetItem(pRow, j)); } } if(decref) Py_DECREF(pMat); return xx; } // convert c++ mat of strings to python mat of strings static PyObject* CPPString_mat_to_py_string_mat(arbi_array<string2d> x){ PyObject* pMat = PyList_New(x.size().i0); for(int i = 0; i < x.size().i0; i++){ PyObject* pVect = PyList_New(x.size().i1); for(int j = 0; j < x.size().i1; j++){ PyList_SetItem(pVect, j, PyString_FromCPPString(x(i,j))); } PyList_SetItem(pMat, i, pVect); } return pMat; } static PyObject* cpp_num_mat_to_py_float_mat(arbi_array<num2d> x){ PyObject* pX = PyList_New(x.size().i0); for(int i = 0; i < x.size().i0; i++){ PyObject* pY = PyList_New(x.size().i1); for(int j = 0; j < x.size().i1; j++){ PyList_SetItem(pY, j, PyFloat_FromDouble(x(i,j))); } PyList_SetItem(pX, i, pY); } return pX; } // convert python float matrix(list of lists) to c++ matrix of nums static arbi_array<num2d> py_float_mat_to_cpp_num_mat(PyObject* pMat, bool decref = false){ if(pMat == NULL) {cout<<"NULL!";throw 20;} // get dimensions of mat int height = PyList_Size(pMat); int width = PyList_Size(PyList_GetItem(pMat, 0)); arbi_array<num2d> x(height, width); PyObject* pTemp; for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ pTemp = PyList_GetItem(PyList_GetItem(pMat, i), j); x(i,j) = PyFloat_AsDouble(pTemp); } } if(decref) Py_DECREF(pMat); return x; } // convert c++ matrix of nums to python matrix(list of lists) of floats static PyObject* cpp_int_mat_to_py_int_mat(arbi_array<int2d> x){ PyObject* pX = PyList_New(x.size().i0); for(int i = 0; i < x.size().i0; i++){ PyObject* pY = PyList_New(x.size().i1); for(int j = 0; j < x.size().i1; j++){ PyList_SetItem(pY, j, PyInt_FromLong(x(i,j))); } PyList_SetItem(pX, i, pY); } return pX; } static arbi_array<int2d> py_int_mat_to_cpp_int_mat(PyObject* pMat, bool decref = false){ if(pMat == NULL) throw 20; // get dimensions of mat int height = PyList_Size(pMat); int width = PyList_Size(PyList_GetItem(pMat, 0)); arbi_array<int2d> x(height, width); PyObject* pTemp; for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ pTemp = PyList_GetItem(PyList_GetItem(pMat, i), j); x(i,j) = PyInt_AsLong(pTemp); } } if(decref) Py_DECREF(pMat); return x; } // returns new reference to python string static PyObject* PyString_FromCPPString(string s){ PyObject* pString; char* char_temp = new char[1000]; strcpy(char_temp, s.c_str()); pString = PyString_FromString(char_temp); delete[] char_temp; return pString; } // converts python string to c++ string static string CPPString_From_PyString(PyObject* pStr){ //cout<<"2222"<<endl; PyObject_Print(pStr, stdout, 0); //cout<<"3333"<<endl; return string(PyString_AsString(pStr)); } // returns new reference to python pdb_name_struct static PyObject* cpp_pdb_name_struct_to_py_pdb_name_struct(pdb_name_struct pdb){ string pdb_name = pdb.pdb_name; string chain_letter = pdb.chain_letter; int start = pdb.start; int end = pdb.end; PyObject* pPdb_name = PyString_FromCPPString(pdb_name); PyObject* pChain_letter = PyString_FromCPPString(chain_letter); PyObject* pStart = PyInt_FromLong(start); PyObject* pEnd = PyInt_FromLong(end); // ERROR PyObject* pConstructor = cpp_caller::get_module_PyObject(string("cross_validation_pseudo"), string("pdb_name_struct")); PyObject* pResult = PyObject_CallFunctionObjArgs(pConstructor, pPdb_name, pChain_letter, pStart, pEnd, NULL); Py_DECREF(pConstructor); Py_DECREF(pPdb_name); Py_DECREF(pChain_letter); Py_DECREF(pStart); Py_DECREF(pEnd); return pResult; } // need to convert python pdb_name_struct list to c++ version. don't need to do reverse but oh well static pdb_name_struct py_pdb_name_struct_to_cpp_pdb_name_struct(PyObject* pPdb){ PyObject* pPdb_name = get_object_attr(pPdb, string("pdb_name")); PyObject* pChain_letter = get_object_attr(pPdb, string("chain_letter")); PyObject* pStart = get_object_attr(pPdb, string("start")); PyObject* pEnd = get_object_attr(pPdb, string("end")); pdb_name_struct ans = pdb_name_struct(CPPString_From_PyString(pPdb_name), CPPString_From_PyString(pChain_letter), PyInt_AsLong(pStart), PyInt_AsLong(pEnd)); Py_DECREF(pPdb_name); Py_DECREF(pChain_letter); Py_DECREF(pStart); Py_DECREF(pEnd); return ans; } static arbi_array<pdb_name_struct[1]> py_pdb_name_struct_list_to_cpp_pdb_name_struct_list(PyObject* pList, bool decref=false){ //cout<<"INSIDE!"<<endl; if(pList == NULL) throw 20; //cout<<"after"<<endl; int len = PyList_Size(pList); //cout<<"f"<<endl; arbi_array<pdb_name_struct[1]> result(len); //cout<<"g"<<endl; for(int i = 0; i < len; i++){ result(i) = cpp_caller::py_pdb_name_struct_to_cpp_pdb_name_struct(PyList_GetItem(pList, i)); } //cout<<"h"<<endl; if(decref) Py_DECREF(pList); //cout<<"i"<<endl; return result; } static PyObject* cpp_pdb_name_struct_list_to_py_pdb_name_struct_list(arbi_array<pdb_name_struct[1]> x){ int size = x.size().i0; PyObject* pList = PyList_New(size); for(int i = 0; i < size; i++){ PyList_SetItem(pList, i, cpp_pdb_name_struct_to_py_pdb_name_struct(x(i))); } return pList; } static PyObject* cpp_pdb_results_struct_to_py_pdb_results_struct(pdb_results_struct res){ PyObject* pScores = cpp_num_vect_to_py_float_list(res.scores); PyObject* pTrue_classes = cpp_int_vect_to_py_int_list(res.true_classes); PyObject* pPdb_structs = cpp_pdb_name_struct_list_to_py_pdb_name_struct_list(res.pdb_structs); PyObject* pSample_lengths = cpp_int_vect_to_py_int_list(res.sample_lengths); PyObject* pConstructor = cpp_caller::get_module_PyObject(string("cross_validation_pseudo"), string("pdb_results_struct")); PyObject* pResult = PyObject_CallFunctionObjArgs(pConstructor, pScores, pTrue_classes, pPdb_structs, pSample_lengths, NULL); Py_DECREF(pConstructor); return pResult; } }; //set<string> cpp_caller::added_paths; class cached_obj_getter: public cpp_caller{ public: // takes in param object that is already set and calls the specified wrapper_instance static PyObject* call_wrapper(string wrapper_module, string wrapper_name, PyObject* pParams, bool recalculate, bool to_pickle, bool to_filelize, bool always_recalculate = false){ // convert the bools to python bools PyObject* pRecalculate; PyObject* pTo_Pickle; PyObject* pTo_Filelize; PyObject* pAlways_Recalculate; if(recalculate){ pRecalculate = Py_True;} else{ pRecalculate = Py_False;} if(to_pickle){ pTo_Pickle = Py_True;} else{ pTo_Pickle = Py_False;} if(to_filelize){ pTo_Filelize = Py_True;} else{ pTo_Filelize = Py_False;} if(always_recalculate){ pAlways_Recalculate = Py_True;} else{ pAlways_Recalculate = Py_False;} // get the wrapper class reference(not an instance) PyObject* pWrapper = get_module_PyObject(wrapper_module, wrapper_name); // get wc.get_stuff reference PyObject* pGetStuff = get_module_PyObject(string("wc"), string("get_stuff")); // call method PyObject* pResult = PyObject_CallFunctionObjArgs(pGetStuff, pWrapper, pParams, pRecalculate, pTo_Pickle, pTo_Filelize, pAlways_Recalculate, NULL); if(pResult == NULL){ py_print(pParams); cout<<"BAD"<<wrapper_name<<endl; } return pResult; } }; #endif #include "cpp_param.h"
true
75e93d855594e20e39a510e4e1bf070894225c56
C++
nihk/SDL2-Pong
/Pong/Messageable.h
UTF-8
672
2.578125
3
[]
no_license
#pragma once // data types passed with Messageable::message() can vary // depending on which class receives the message. See comments // within each classes implementation of message() for clarification enum class MessageId { NONE = -1, SET_Y_VELOCITY, HANDLE_COLLISION, PADDLE_BOUNCE, X_OUT_OF_SCREEN_BOUNDS, Y_OUT_OF_SCREEN_BOUNDS, UPDATE_SCORE, COUNT }; // My intention with this class was to use it like a Java interface class Messageable { public: virtual ~Messageable() = default; // @param reply is to be used as an OUT parameter virtual bool message(const MessageId messageId, const void* data = nullptr, void* reply = nullptr) = 0; };
true
498401d476984fe4b94fe27c26831e9971f1b45f
C++
AjayThakur12/opendatastructures
/spec/src/helpers/lists/deque_check.cpp
UTF-8
692
3.421875
3
[]
no_license
void dequeCheck(IDeque<int> &deque){ cout << "Testing deque interface:" << endl; for (int i = 0; i < 3; i++){ cout << " adding value " << i << "to end" << endl; deque.addLast(i); } // 0 // 0 1 // 0 1 2 for (int i = 3; i < 6; i++){ cout << " adding value " << i << "to front" << endl; deque.addFirst(i); } // 3 0 1 2 // 4 3 0 1 2 // 5 4 3 0 1 2 for (int i = 0; i < 2; i++){ cout << " removed value " << deque.removeFirst() << "from front" << endl; } // Expect to get: // 5 // 4 // Leaving: // 3 0 1 2 for (int i = 0; i < 4; i++){ cout << " removed value " << deque.removeLast() << "from end" << endl; } // Expect to get: // 2 // 1 // 0 // 3 }
true
c75cb358287f43ed5d2742de0dc2fd8581fae15c
C++
Jas03x/GKit
/src/core/src/io/filesystem.cpp
UTF-8
345
2.703125
3
[]
no_license
#include <gk/core/io/filesystem.hpp> Filesystem::Path::Path(const std::string& path) { size_t index = path.find_last_of('/'); if (index == std::string::npos) { this->filename = path; } else { index++; this->directory = path.substr(0, index); this->filename = path.substr(index); } }
true
f654e1614e16b72fc384c6d4aae7dc72e3d948f8
C++
BornIncompetence/fast_io
/include/fast_io_core_impl/ospan.h
UTF-8
3,028
2.859375
3
[ "MIT" ]
permissive
#pragma once namespace fast_io { template<std::integral ch_type,std::size_t extent=std::dynamic_extent,bool override_not_overflow=false> class ospan { public: using char_type = ch_type; using span_type = std::span<char_type,extent>; span_type span; using pointer = typename span_type::pointer; pointer current; template<typename... Args> requires std::constructible_from<span_type,Args...> constexpr ospan(Args&& ...args):span(std::forward<Args>(args)...),current(span.data()){} constexpr auto data() const noexcept { return span.data(); } constexpr auto data() noexcept { return span.data(); } constexpr std::size_t size() const noexcept { return current-span.data(); } constexpr void clear() noexcept {current=span.data();} }; template<std::integral char_type,std::size_t extent,bool override_not_overflow> inline constexpr auto obuffer_begin(ospan<char_type,extent,override_not_overflow>& sp) noexcept { return sp.data(); } template<std::integral char_type,std::size_t extent,bool override_not_overflow> inline constexpr auto obuffer_curr(ospan<char_type,extent,override_not_overflow>& sp) noexcept { return sp.current; } template<std::integral char_type,std::size_t extent,bool override_not_overflow> inline constexpr auto obuffer_end(ospan<char_type,extent,override_not_overflow>& sp) noexcept { return std::to_address(sp.span.end()); } template<std::integral char_type,std::size_t extent,bool override_not_overflow> inline constexpr auto obuffer_set_curr(ospan<char_type,extent,override_not_overflow>& sp,char_type* ptr) noexcept { sp.current=ptr; } template<std::integral char_type,std::size_t extent,bool override_not_overflow> inline constexpr void overflow(ospan<char_type,extent,override_not_overflow>&,char_type) noexcept{} template<std::integral char_type,std::size_t extent> inline constexpr void overflow_never(ospan<char_type,extent,true>&) noexcept{} template<std::integral char_type,std::size_t extent,bool override_not_overflow,std::contiguous_iterator Iter> requires (std::same_as<char_type,std::iter_value_t<Iter>>||std::same_as<char,char_type>) inline constexpr void write(ospan<char_type,extent,override_not_overflow>& ob,Iter cbegin,Iter cend) noexcept { if constexpr(std::same_as<char_type,std::iter_value_t<Iter>>) { std::size_t sz(cend-cbegin); if constexpr(override_not_overflow) { std::size_t const remain_space(ob.span.size()-ob.size()); if(remain_space<sz)[[unlikely]] sz=remain_space; } details::non_overlapped_copy_n(cbegin,sz,ob.current); ob.current+=sz; } else { write(ob,reinterpret_cast<char const*>(std::to_address(cbegin)), reinterpret_cast<char const*>(std::to_address(cend))); } } template<typename... Args> ospan(Args&& ...args) -> ospan<typename std::remove_cvref_t<decltype(std::span(std::forward<Args>(args)...))>::value_type, std::remove_cvref_t<decltype(std::span(std::forward<Args>(args)...))>::extent,false>; }
true
7cd549377680a983cc5abcc2f5fb3af7b1453cc2
C++
guili116345/MyTestCode2021
/Qml/TestQml_20210717_IpInput/Clipboard.cpp
UTF-8
2,957
2.96875
3
[]
no_license
#include "Clipboard.h" #include <QGuiApplication> #include <QClipboard> #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QRegExp> #include <QDebug> void Clipboard::copyIp(QStringList ip) { QStringList item_list; QString ip_text; if(ip.size()==4){ //空文本直接作为0处理 for(QString &item : ip) item_list.append(QString::number(item.toInt())); ip_text=item_list.join('.'); }else if(ip.size()==1){ ip_text=QString::number(ip.first().toInt()); } if(!ip_text.isEmpty()){ QClipboard *clip_board=QGuiApplication::clipboard(); clip_board->setText(ip_text); } qDebug()<<"copy ip"<<ip<<ip_text; } QStringList Clipboard::pasteIp() { QClipboard *clip_board=QGuiApplication::clipboard(); QString ip_text=clip_board->text(); //可以加上其他分隔符判断 //可以用正则来判断数据合法性 QStringList item_list=ip_text.split('.'); QStringList ip; bool ret; int val; if(item_list.size()==4){ /*for(QString item : item_list) { ret=true; if(item.size()>0&&item.size()<=3){ for(QChar c : item) { ret&=c.isDigit(); //可以直接在这里完成数字转换 } if(ret){ val=item.toInt(); if(val>255||val<0){ ret=false; } if(val>255||val<0){ ret=false; } } }else{ ret=false; } if(!ret){ ip.clear(); break; } ip.append(QString::number(val)); }*/ //改为正则匹配 if(checkIPv4(ip_text)){ for(QString item : item_list) ip.append(QString::number(item.toInt())); } }else if(item_list.size()==1){ //这个懒得写正则了 QString item=item_list.first(); ret=true; if(item.size()>0&&item.size()<=3){ for(QChar c : item) { ret&=c.isDigit(); } if(ret){ val=item.toInt(); if(val>=0&&val<=255){ ip.append(QString::number(val)); } } } } qDebug()<<"paste ip"<<ip<<ip_text; return ip; } bool Clipboard::checkIPv4(const QString str) { QString section="(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])"; QString exp=QString("^%1\\.%1\\.%1\\.%1$").arg(section); //Qt4 //QRegExp reg1(exp); //qDebug()<<reg1.exactMatch(str); //Qt5 QRegularExpression reg2(QRegularExpression::anchoredPattern(exp)); QRegularExpressionMatch match=reg2.match(str); //qDebug()<<match.hasMatch(); return match.hasMatch(); }
true
0ea978c22a2b1a66da7b6935eac5f94338d4174a
C++
hbsun2113/LeetCodeCrawler
/0717.1-bit-and-2-bit-characters/1-bit-and-2-bit-characters.cpp
UTF-8
537
2.796875
3
[]
no_license
class Solution { public: //自己没有想出来,因此看了hint。这个问题可能不值得一做? bool isOneBitCharacter(vector<int>& bits) { if(bits[bits.size()-1]==1) return false; return isvalid(bits,0); } bool isvalid(vector<int>& bits,int pos){ //cout<<pos<<endl; if(pos==bits.size()-1 && bits[pos]==0) return true; if(pos>=bits.size()) return false; if(bits[pos]==0) return isvalid(bits,pos+1); else return isvalid(bits,pos+2); } };
true
9a7a1d1207fd315c327956a8993f56a56e1ad8a8
C++
ckong2001/jungleChess
/direction.cpp
UTF-8
908
2.78125
3
[]
no_license
/* CCCU 21105 Object-Oriented Programming Assignment : Jungle Chess Game Team Number : 39 Team member : Lo Ka Ming 54063815 Tse Shing Kung 54049126 Michael Romano 54073009 Tung Ka Lok 54059120 */ #include "direction.h" direction :: direction () { dy = 0 ; dx = 0 ; } direction :: direction ( int dy , int dx ) { this->dy = dy ; this->dx = dx ; } bool direction :: getValid () { return valid ; } void direction :: setValid ( bool Valid ) { this -> valid = Valid ; } direction :: ~direction () {} void direction :: setDy ( int y ) { dy = y ; } void direction :: setDx ( int x ) { dx = x ; } int direction :: getDx () { return dx ; } int direction :: getDy () { return dy ; }
true
7ae163c599143167dd0e936c3f26f98666a572d6
C++
georgerapeanu/c-sources
/petresq_simulare_izho1/dragonball/dragonball.cpp
UTF-8
4,412
2.515625
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; FILE *f = fopen("dragonball.in","r"); FILE *g = fopen("dragonball.out","w"); typedef long long ll; const ll BASE = 1e14; const int LGMAX = 800; class Bignum { public: ll cf[LGMAX]; int lst_cf; Bignum() { lst_cf = 0; } void build(char *a) { lst_cf = 0; ll num = 0; int len = 0; while(*(a + len) != '\0' && *(a + len) != '\n') { len++; } ll p10 = 1; while(len > 0) { len--; if(p10 >= BASE) { p10 = 1; cf[lst_cf++] = num; num = 0; } num += p10 * (*(a + len) - '0'); p10 *= 10; } if(num > 0 || lst_cf == 0) { cf[lst_cf++] = num; } } Bignum operator / (int val) { Bignum ans; ans.lst_cf = this->lst_cf; ll t = 0; for(int i = lst_cf - 1; i >= 0; i--) { t += cf[i]; ans.cf[i] = (t / val); t %= val; t *= BASE; } t = (t > 0); for(int i = 0; t; i++) { t += ans.cf[i]; ans.cf[i] = t % BASE; t /= BASE; } while(ans.lst_cf > 1 && ans.cf[ans.lst_cf - 1] == 0) { ans.lst_cf--; } return ans; } Bignum operator - (Bignum &other) { Bignum ans; ans.lst_cf = 0; int t = 0; for(int i = 0; i < lst_cf; i++) { ans.cf[ans.lst_cf++] = (t + cf[i] - other.cf[i]); if(ans.cf[ans.lst_cf - 1] < 0) { ans.cf[ans.lst_cf - 1] += BASE; t = -1; } else { t = 0; } } while(ans.lst_cf > 1 && ans.cf[ans.lst_cf - 1] == 0) { ans.lst_cf--; } return ans; } bool operator < (const Bignum &other)const { if(this->lst_cf != other.lst_cf) { return this->lst_cf < other.lst_cf; } int len = this->lst_cf - 1; while(len >= 0 && this->cf[len] == other.cf[len]) { len--; } if(len < 0) { return 0; } return this->cf[len] < other.cf[len]; } void afis() { fprintf(g,"%lld",cf[lst_cf - 1]); for(int i = lst_cf - 2; i >= 0; i--) { ll cb = BASE / 10; while(cb > 1 && cb > cf[i]) { fprintf(g,"0"); cb /= 10; } fprintf(g,"%lld",cf[i]); } fprintf(g,"\n"); } }; int n,t; char tmp[10005]; Bignum stuff[1005]; Bignum residue[1005]; int cnt[1005]; int heap[1005]; int len = 0; void heappush(int id) { len++; heap[len] = id; residue[id] = stuff[id] / cnt[id]; int idx = len; while(idx > 1 && residue[heap[idx / 2]] < residue[heap[idx]]) { swap(heap[idx],heap[idx / 2]); idx /= 2; } } int heappop() { int ans = heap[1]; swap(heap[1],heap[len]); len--; int idx = 1; while(idx * 2 <= len) { if(idx * 2 + 1 > len) { if(residue[heap[idx * 2]] < residue[heap[idx]]) { break; } swap(heap[idx * 2],heap[idx]); idx *= 2; continue; } if(residue[heap[idx * 2]] < residue[heap[idx]] && residue[heap[idx * 2 + 1]] < residue[heap[idx]]) { break; } if(residue[heap[idx * 2]] < residue[heap[idx * 2 + 1]]) { swap(heap[idx * 2 + 1],heap[idx]); idx = idx * 2 + 1; } else { swap(heap[idx * 2],heap[idx]); idx = idx * 2; } } return ans; } int main() { fscanf(f,"%d %d %s\n",&n,&t,tmp); stuff[++n].build(tmp); for(int i = 1; i < n; i++) { fscanf(f,"%s\n",tmp); stuff[i].build(tmp); } for(int i = n; i > 1; i--) { stuff[i] = stuff[i] - stuff[i - 1]; } for(int i = 1; i <= n; i++) { cnt[i] = 1; heappush(i); // heapafis(); } while(t--) { int tmp = heappop(); // tmp.first.first.afis(); // printf("%d\n",tmp.second); cnt[tmp]++; heappush(tmp); } int ans = heappop(); residue[ans].afis(); fclose(f); fclose(g); return 0; }
true
5882b2cb8823e084d79f0beb10a298f4759a6edb
C++
rebo95/Portfolio
/UCM Projects/Data Structures and Algorithms/VIP_Queue.cpp
ISO-8859-1
6,337
3.453125
3
[]
no_license
//Grupo VJ01, Aaron Reboredo Vzquez //Grupo VJ01, Pablo Martn Garca //Este ejercicio nos permite gestionar la cola de una discoteca en funcin de las prioridades de los asistentes. Para ello hacemos uso de la clase ColaVip. //todas aquellas llegadas tales que exista espacio en la discoteca entran directamente aumenando el nmero de personas dentro. // en caso de que el aforo est lleno, las personas se irn posicionando por orden de llegada en nuestra cola, hacemos uso del mtodo nuestro mtodo push. // en caso de que salga una persona de la discoteca, el contador de personas dentro disminuir y se proceder a introducir una persona de la cola en caso de haberla. // Ahora, la seleccin de la persona que va a entrar ir en funcin de las prioridades, vamos comparando en la cola las prioridades de los elementos y seleccionamos la primera // de las mayores prioridades, es decir, el elemento con el nmero de prioridad ms bajo y que se encuentre antes que los equivalentes en la cola. Con pop, eliminamos ese elemento // e incrementamos el contador de personas en la discoteca. Gestionamos el problema de esta manera hasta terminar con el nmero de movimientos. #include <iostream> using namespace std; //HEADER DE LA CLASE template <typename T> class colaVIP { private: //Clase Nodo class Nodo { public: int priority = 0; T id = 0; Nodo* sig = nullptr; Nodo(const int& p, const T& ident, Nodo* n) : priority(p), id(ident), sig(n) {} //Constructor }; size_t nelems = 0; //Nmero de eltos de la cola //Punteros al primer y ltimo nodo Nodo* pri = nullptr; Nodo* ult = nullptr; //Prioridades de la cola int prioridad = 0; public: colaVIP(); colaVIP(int p); ~colaVIP(); void push(const int& p, const T& ident); T const& front() const; void pop(); bool empty() const; size_t size() const; }; //CPP DE LA CLASE template <typename T> colaVIP<T>::colaVIP() { } //Crea una cola que admite hasta p prioridades //Este mtodo tiene un coste O(1) template <typename T> colaVIP<T>::colaVIP(int p) { //Creamos un nodo fantasma que sea el primero de la lista prioridad = p; Nodo* fant = new Nodo(-1, -1, nullptr); pri = fant; ult = fant; nelems = 0; } template <typename T> colaVIP<T>::~colaVIP() { } //Introducimos un elemnto con su prioridad e identificador al final de la cola //Este mtodo tiene un coste de O(1) template <typename T> void colaVIP<T>::push(const int& p, const T& ident) { Nodo* node = new Nodo(p, ident, ult->sig); ult->sig = node; ult = node; nelems++; } //Devuelve el primer elemento, considerando prioridades //Este mtodo tiene un coste O(n) siendo n el tamao de la cola template <typename T> T const& colaVIP<T>::front() const { int max_p = prioridad + 1; Nodo* act = pri->sig; Nodo* imp = nullptr; if (!empty()) { while (act != nullptr) { if (act->priority < max_p) { max_p = act->priority; imp = act; } act = act->sig; } } else std::cout << "Cola vacia"; return imp->id; } //Elimina el primer nodo de la lista, considerando prioridades // el coste del mtodo es O(n + m) siendo n el numero de personas en la cola y m la distancia entre el primer elemeto y el primero de mayor prioridad. // en el peor de los casos el elemento se encuentra al final de la cola , el coste es O(2n) -> O(n), siendo n el nmero de elementos en la cola. template <typename T> void colaVIP<T>::pop() { T e_id = front(); // coste O(n) donde n es el nmero de personas en la cola int i = 1; Nodo* act = pri->sig; Nodo* imp = pri; Nodo* ant = pri; if (size() == 1) { imp = act; pri = ant; } else { while (act->id != e_id){ ant = act; act = act->sig; i++; } imp = act; } ant->sig = imp->sig; if(i == size()) ult = ant; nelems--; //El coste de este condicional es O(m) siendo m la "distancia" desde el primer elemento de la cola hasta el deseado(que nos lo da el mtodo front) es decir, el //primero con mayor prioridad. } //Comprueba si la cola est vaca //Este mtodo tiene un coste de O(1) template <typename T> bool colaVIP<T>::empty() const { return size() == 0; } //Devuelve el tamao de la cola //Este mtodo tiene un coste de O(1) template <typename T> size_t colaVIP<T>::size() const { return nelems; } //FUNCIONES A USAR EN EL PROGRAMA PRINCIPAL void resuelve_caso(); void salida(colaVIP<int>& c); int main() { int numCasos; cin >> numCasos; for (int i = 0; i < numCasos; i++) resuelve_caso(); return 0; } //Funcin que resuelve un caso propuesto //Esta funcin tiene un coste O(m * n) siendo m la cantidad de movimientos(gente que entra y gente que sale) que se van a hacer en la cola //y n la cantidad de gente que hay en la cola. En el peor de los casos la gente que habr en la cola ser equivalente al nmero de personas (num pers en el caso de una discoteca // de aforo 0 o numpersonas - 1 en el caso de una discoteca de aforo 1 (num pers aprox = num pers -1). De esta manera, // el coste es O(m*n) donde m ser el nmero de movimientos y n el nmero de personas. void resuelve_caso() { int p_cola, mov, aforo, pers; char op; pers = 0; //Personas que hay dentro de la discoteca inicialmente cin >> p_cola >> mov >> aforo; colaVIP<int> cola = colaVIP<int>(p_cola); for (int i = 0; i < mov; i++) // repetimos m veces, siendo m el nmero de movimientos realizados. Repetimos m veces instruccin de coste O(n) { cin >> op; if (op == '-') { pers--; if (cola.size() > 0) // condicion con coste O(1) { cola.pop(); // pop coste O(n) donde n, va a ser el tamao de la cola en cada momento. pers++; } } else { int p, ident; cin >> p >> ident; cola.push(p, ident); if (pers < aforo && cola.size() > 0) { cola.pop(); // pop coste O(n) donde n, va a ser el tamao de la cola en cada momento. pers++; } }// coste del condicional O(n) } salida(cola); } //Funcin que gestiona la salida que debe devolver el programa //Esta funcin tiene un coste O(n) siendo n el tamao de la cola void salida(colaVIP<int>& c) { int tam = c.size(); // size() coste O(1) if (tam > 0) { for (int i = 0; i < tam; i++) //n veces O(1), siendo n el tamao de la cola { cout << c.front() << " "; c.pop(); // pop coste O(1) } } else cout << "NADIE"; cout << endl; }
true
4b7cc3a34e1aecc22bdfec6c8e87a55271396454
C++
Stereogram/test.rpg
/test.rpg/gui/TextBox.cpp
UTF-8
1,064
2.5625
3
[]
no_license
#include <Thor\Resources\SfmlLoaders.hpp> #include "SFML\Graphics\Font.hpp" #include "TextBox.hpp" #include "Label.hpp" #include "..\Game.hpp" gui::TextBox::TextBox(const unsigned int maxLines) : _font(Game::Cache->acquire(thor::Resources::fromFile<sf::Font>("assets/fonts/kenpixel_high_square.ttf"))) , _max(maxLines) { _animator.addAnimation("move", [] (Label& label, float progress) {label.move(0.f, progress * -2.f); }, sf::seconds(0.5f)); } void gui::TextBox::add(const std::string& item) { _animator.playAnimation("move"); if (_lines.size() >= _max) _lines.pop_front(); _lines.push_back(std::unique_ptr<Label>(new Label(*_font, item))); } void gui::TextBox::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); for (const auto& item : _lines) { item->draw(target, states); } for (const auto& child : _children) { child->draw(target, states); } } void gui::TextBox::update(const sf::Time& dt) { _animator.update(dt); for (const auto& label : _lines) { _animator.animate(*label); } }
true
11eb5487115e3e5d8e5f6cff29e31ff378452612
C++
lakrias/AntivirusMTUCI
/Antivirus(23.04.2020)/Base.h
WINDOWS-1251
333
2.578125
3
[]
no_license
#pragma once #include "Record.h" /* 2. ( ) */ class Base { DWORD recordcount; public: Record _Record; Base(); Base(DWORD RecordCount); };
true
0afc86bb9b5889bc126a5e599b02d157c01821f3
C++
dskleviathan/contest
/AOJ0033.cpp
UTF-8
532
2.859375
3
[]
no_license
#include <iostream> using namespace std; int N, H[10]; void solve() { int big=0, small=0; bool flag = true; for (int i = 0; i < 10; i++) { if (H[i] > big) big = H[i]; else if (H[i] > small) small = H[i]; else { flag = false; break; } } if (flag) cout << "YES" << endl; else cout << "NO" << endl; } int main(){ cin >> N; for (int i = 0; i < N; i++) { for (int j = 0; j < 10; j++) cin >> H[j]; solve(); } return 0; }
true
7edf1bbe68109ff6b3364eee42d291dc748ec5bf
C++
keigezellig/fruitHAP
/clientapps/SensorTest/statemachine/door.cpp
UTF-8
1,552
2.6875
3
[]
no_license
#include "door.h" #include <QDebug> Door::Door(QObject *parent): QObject(parent), m_doorMachine(*this) { m_approvalTimer = new QTimer(this); m_unlockedTimer = new QTimer(this); m_approvalTimer->setInterval(20000); m_unlockedTimer->setInterval(25000); connect(m_approvalTimer, &QTimer::timeout, this, &Door::approvalTimerExpired); connect(m_unlockedTimer, &QTimer::timeout, this, &Door::unlockedTimerExpired); } void Door::init() { m_doorMachine.enterStartState(); } Door::~Door() { delete m_approvalTimer; delete m_unlockedTimer; } void Door::startApprovalTimer() { m_approvalTimer->start(); } void Door::stopApprovalTimer() { m_approvalTimer->stop(); } void Door::startUnlockedTimer() { m_unlockedTimer->start(); } void Door::stopUnlockedTimer() { m_unlockedTimer->stop(); } void Door::onFaceDetected(const QByteArray &image) { emit imageWithFaceIsAvailable(image); } void Door::onApproved() { emit personApproved(); } void Door::onNotApproved() { emit personNotApproved(); } void Door::initialAction() { emit initialize(); } void Door::onApprovalTimeOut() { emit noAnswer(); } void Door::faceHasBeenDetected(const QByteArray &image) { m_doorMachine.FaceDetected(image); } void Door::approve(bool isApproved) { m_doorMachine.Approval(isApproved); } void Door::reset() { m_doorMachine.Reset(); } void Door::approvalTimerExpired() { m_doorMachine.ApprovalTimeOut(); } void Door::unlockedTimerExpired() { m_doorMachine.UnlockedTimerTimeOut(); }
true
1bc89c2251c82b5324ead4690efa78c746c0b9f1
C++
lmw40/mpMap
/src/sharedArray.hpp
UTF-8
466
3.140625
3
[]
no_license
#ifndef _SHARED_ARRAY_H #define _SHARED_ARRAY_H #include <memory> //helper struct for a reference-counter array template<typename T> struct arrayDeleter { void operator()(T* p) { delete [] p; } }; template<typename T> class sharedArray : public std::shared_ptr<T> { public: sharedArray(T* t) : std::shared_ptr<T>(t, arrayDeleter<T>()) {} sharedArray() : std::shared_ptr<T>() {} T& operator[](int i) { return this->get()[i]; } }; #endif
true
8237084fc573dbf11e3aa7d0ae03d52d03276956
C++
piggy2303/int1008_40
/chusolonnhat.cpp
UTF-8
702
3.21875
3
[]
no_license
#include <cmath> #include <iostream> using namespace std; int main() { // int n, count_uoc = 0; // cin >> n; // for (int i = 1; i <= n/2; i++) // { // if (n % i == 0) // { // count_uoc++; // } // } // if (count_uoc == 2) // { // cout << "yes" << endl; // } // else // { // cout << "no" << endl; // } int n; cin >> n; // cach 1 int k = sqrt(n); if (k * k == n) { cout << "yes" << endl; } // cach2 for (int i = 1; i < (n / 2); i++) { if (i * i == n) { cout << "yes" << endl; break; } } return 0; }
true
8e65b7a95d948b742f86ce589f39353dc0e70c5e
C++
danwsong/programming-contests
/CCC/2006/J3.cpp
UTF-8
1,326
2.828125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int presses(char c) { if (c >= 'a' && c <= 'c') return c - 'a' + 1; if (c >= 'd' && c <= 'f') return c - 'd' + 1; if (c >= 'g' && c <= 'i') return c - 'g' + 1; if (c >= 'j' && c <= 'l') return c - 'j' + 1; if (c >= 'm' && c <= 'o') return c - 'm' + 1; if (c >= 'p' && c <= 's') return c - 'p' + 1; if (c >= 't' && c <= 'v') return c - 't' + 1; if (c >= 'w' && c <= 'z') return c - 'w' + 1; return -1; } int key(char c) { if (c >= 'a' && c <= 'c') return 2; if (c >= 'd' && c <= 'f') return 3; if (c >= 'g' && c <= 'i') return 4; if (c >= 'j' && c <= 'l') return 5; if (c >= 'm' && c <= 'o') return 6; if (c >= 'p' && c <= 's') return 7; if (c >= 't' && c <= 'v') return 8; if (c >= 'w' && c <= 'z') return 9; return -1; } int main() { string s; cin >> s; while (s != "halt") { int t = 0, currNum = -1; for (int i = 0; i < s.size(); i++) { t += presses(s[i]); if (key(s[i]) == currNum) t += 2; currNum = key(s[i]); } cout << t << endl; cin >> s; } return 0; }
true
5fe5bddeedb4c7e51839566cd894c890ee20da90
C++
ecodespace/EE361-Work
/HW_4/HW_4_Roulette/HW_4_Roulette/NumGroup.cpp
UTF-8
339
2.984375
3
[]
no_license
#include "NumGroup.h" NumGroup::NumGroup() { num_size = 0; nums[num_size] = { }; } NumGroup::NumGroup(int num_arr[]) { num_size = sizeof(num_arr) / sizeof(int); nums[num_size] = num_arr[num_size]; } bool NumGroup::contains(int num) { for (int i = 0; i < num_size; ++i) { if (nums[i] == num) return true; } return false; }
true
c3826f1ce830ff045399b8e791473d1bbbf828ba
C++
chensguo8099/practice
/cppPrimer/firstStep/test14.cpp
UTF-8
1,464
3.71875
4
[]
no_license
/* > File Name: test14.cpp > Author: JerryChen > Created Time: 2019年02月23日 星期六 22时49分56秒 */ #include <iostream> using namespace std; //图形类 称之为抽象类 //不管这个类中有无成员属性,只要这个类有纯虚函数,就是一个抽象类。 //抽象类是不能实例化对象的 class Shape{ public: //求图形面积的方法 //表示图形类声明一个方法getArea(),它是一个纯虚函数,没有函数的实现。 virtual double getArea() = 0; }; //正方形 //如果说一个普通类继承拥有纯虚函数的类,必须要重写这个纯虚函数 //如果说不去重写纯虚函数,继承过来的类仍是抽象类,不能被实例化 class Rect : public Shape{ public: Rect(int a){ this->a = a; } virtual double getArea(){ cout << "正方形面积" << endl; return a*a; } private: int a;//正方形边长 }; class Circle:public Shape{ public: Circle(int r){ this->r = r; } virtual double getArea(){ cout << "圆型面积" << endl; return 3.14*r*r; } private: int r; }; //抽象类接口 //x写接口后则不需要再让main与各个抽象类的实例进行交互 //直接可以让main函数与该函数进行交互,该函数将抽象类转化为实例 void printArea(Shape *sp){ sp->getArea(); } int main(){ Shape *sp = new Circle(20); sp->getArea(); return 0; }
true
9f68eb5d2388b57190f72d68caf18009ff8c71a4
C++
groverjeenu/RTLP
/13CS30042_13CS30043_server.cpp
UTF-8
17,353
2.703125
3
[]
no_license
// Assignment 3 // Developing a Reliable Transport Layer Protocol using Raw Sockets // Objective // The objective of this assignment is to develop a reliable transport layer protocol on the top of the IP layer. // Group Details // Member 1: Jeenu Grover (13CS30042) // Member 2: Ashish Sharma (13CS30043) // Filename: server.cpp -- Implementation of Server #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <iomanip> #include <netinet/ip.h> #include <netinet/tcp.h> #define MAX_PACKET_LEN 8192 #define MAX_DATA_LEN 8100 using namespace std; #define SIZE_IP sizeof(iphdr) // Header structure for RTLP -- 18 bytes (Actually SIZE is 20 NOT 18 because of rounding to multiples of 4.) typedef struct RLTPhdr { unsigned short int sPort; unsigned short int dPort; unsigned int syn; unsigned int ack; unsigned int chkSum; unsigned short int option; // 0-SYN, 1-DATA, 2-FIN, 3-ACK(For SYN+ACK), 4-ACK(For FIN+ACK) } RTLP_Header; #define SIZE_RLTP sizeof(RTLP_Header) // Function to compute checksum unsigned int adler32(char *data, size_t len) { const int MOD_ADLER = 65521; unsigned int a = 1, b = 0; size_t index; /* Process each byte of the data in order */ for (index = 0; index < len; ++index) { //cout<<"Here "<<index<<endl; a = (a + data[index]) % MOD_ADLER; b = (b + a) % MOD_ADLER; } return (b << 16) | a; } // Decoding the Checksum received bool decode_checksum_new(char *buffer,int buflen) { //int buflen = sizeof(buffer); RTLP_Header *RTL = (RTLP_Header *)(buffer+SIZE_IP); char *new_buffer = new char[buflen]; unsigned int temp = RTL->chkSum; RTL->chkSum = 0; unsigned int val = adler32(buffer+SIZE_IP,buflen-SIZE_IP); RTL->chkSum = temp; //cout<<"ch: "<<val<<endl; return (val == temp); } // Send the Acknowledgement of the received data void send_ACK(int servfd,char *src_IP,char *dest_IP,int ack_no,RTLP_Header *RTL,char *msg) { char new_msg_1[MAX_DATA_LEN]; char new_msg_2[MAX_DATA_LEN]; // Extract the ECHO REQ Number int i = 0; while(msg[i]!=' ') { i++; } i++; while(msg[i]!=' ') { i++; } i++; int j = 0; while(msg[i]!='\0') { new_msg_1[j] = msg[i]; i++; j++; } new_msg_1[j] = '\0'; int no1 = atoi(new_msg_1); no1++; stringstream out; out<<"ECHO RES "<<(no1); strcpy(new_msg_2,out.str().c_str()); cout<<"Message sent as ACK: "<<new_msg_2<<endl; char buffer[MAX_PACKET_LEN]; memset(buffer,0,MAX_PACKET_LEN); struct iphdr ip; RTLP_Header rltp; int seq_no = ntohl(RTL->syn); struct sockaddr_in sin,din; sin.sin_family = AF_INET; din.sin_family = AF_INET; sin.sin_port = 0; din.sin_port = 0; inet_pton(AF_INET,src_IP,(struct in_addr *)&sin.sin_addr.s_addr); inet_pton(AF_INET,dest_IP,(struct in_addr *)&din.sin_addr.s_addr); // Set the IP Header Parameters ip.ihl = 5; ip.version = 4; ip.tos = 16; // Low delay ip.tot_len = sizeof(struct iphdr)+sizeof(struct RLTPhdr)+strlen(new_msg_2); //### ip.frag_off = 0; ip.ttl = 64; // hops ip.protocol = IPPROTO_RAW; ip.saddr = sin.sin_addr.s_addr; ip.daddr = din.sin_addr.s_addr; ip.check = 0; memcpy(buffer,(char*)&ip,sizeof(ip)); // Set the RTLP Header Parameters rltp.sPort = 0; rltp.dPort = 0; rltp.syn = htonl(ack_no+strlen(new_msg_2)); rltp.ack = htonl(seq_no); rltp.chkSum = 0; memcpy(buffer+ sizeof(struct iphdr),&rltp,sizeof(rltp)); // Copy the Msg in the buffer memcpy(buffer + sizeof(struct iphdr) + sizeof(rltp), new_msg_2,strlen(new_msg_2)); // Compute the CheckSum rltp.chkSum = adler32(buffer+sizeof(struct iphdr),sizeof(rltp)+strlen(new_msg_2)); memcpy(buffer+ sizeof(struct iphdr),&rltp,sizeof(rltp)); memcpy(buffer + sizeof(struct iphdr) + sizeof(rltp), new_msg_2,strlen(new_msg_2)); //printf("Using::Source IP: %s port: %d, Target IP: %s port: %d.\n", src_IP, src_port,dest_IP, dest_port); // Send the Packet if(sendto(servfd, buffer, ip.tot_len, 0, (struct sockaddr *)&din, (socklen_t)sizeof(din)) < 0) { perror("sendto() error"); exit(-1); } else cout<<"Successfully sent to :"<<dest_IP<<endl; } // Send SYN+ACK for Accepting Connection request void send_SYN_ACK(int servfd,char *src_IP, char *dest_IP,int seq_no,int send_seq) { char buffer[MAX_PACKET_LEN]; memset(buffer,0,MAX_PACKET_LEN); struct iphdr ip; RTLP_Header rltp; struct sockaddr_in sin,din; sin.sin_family = AF_INET; din.sin_family = AF_INET; sin.sin_port = 0; din.sin_port = 0; inet_pton(AF_INET,src_IP,(struct in_addr *)&sin.sin_addr.s_addr); inet_pton(AF_INET,dest_IP,(struct in_addr *)&din.sin_addr.s_addr); // Set the IP Header Parameters ip.ihl = 5; ip.version = 4; ip.tos = 16; // Low delay ip.tot_len = sizeof(struct iphdr) + sizeof(struct RLTPhdr); //### ip.frag_off = 0; ip.ttl = 64; // hops ip.protocol = IPPROTO_RAW; ip.saddr = sin.sin_addr.s_addr; ip.daddr = din.sin_addr.s_addr; ip.check = 0; memcpy(buffer,(char*)&ip,sizeof(ip)); // Set the RTLP Header Parameters rltp.sPort = 0; rltp.dPort = 0; rltp.syn = htonl(send_seq); rltp.ack = htonl(seq_no); rltp.chkSum = 0; memcpy(buffer+ sizeof(struct iphdr),&rltp,sizeof(rltp)); // Compute the CheckSum rltp.chkSum = adler32(buffer+sizeof(struct iphdr),sizeof(rltp)); memcpy(buffer+ sizeof(struct iphdr),&rltp,sizeof(rltp)); //printf("Using::Source IP: %s port: %d, Target IP: %s port: %d.\n", src_IP, src_port,dest_IP, dest_port); // Send the Packet if(sendto(servfd, buffer, ip.tot_len, 0, (struct sockaddr *)&din, (socklen_t)sizeof(din)) < 0) { perror("sendto() error"); exit(-1); } else cout<<"Successfully sent to :"<<dest_IP<<endl; } // Receive the SYN Request void receive_SYN(int servfd,char *src_IP,int send_seq,int *seq_no,int *ack_no) { struct iphdr *IP; RTLP_Header *RTL; char *dest_IP = new char[100]; // Receive SYN From Client char *output; int prev = -1,cnt = 0; while(1) { // Receive until 3-Way Handshake has completed successfully output = new char[MAX_PACKET_LEN]; struct sockaddr_in saddr; int saddr_len = sizeof(saddr); // Receive the message int buflen=recvfrom(servfd,output,MAX_PACKET_LEN,0,(struct sockaddr *)(&saddr),(socklen_t *)&saddr_len); if(buflen<0) { printf("error in reading recvfrom function\n"); return; } RTL = (RTLP_Header *)(output+SIZE_IP); IP = (struct iphdr *)(output); //cout<<"iphg :"<<(unsigned int)IP->tot_len<<endl; // Get the IP of Sender from IP Header inet_ntop(AF_INET, &(IP->saddr), dest_IP, INET_ADDRSTRLEN); //cout<<"Successfully Received "<<buflen<<": "<<output+SIZE_IP+SIZE_RLTP<<" SEQ: "<<ntohl(RTL->syn)<<" ACK: "<<ntohl(RTL->ack)<<" chkSum: "<<RTL->chkSum<<endl; // Do Checksum Check if(decode_checksum_new(output,buflen)) { // Print the data cout<<"Successfully Received "<<buflen<<": "<<output+SIZE_IP+SIZE_RLTP<<" SEQ: "<<ntohl(RTL->syn)<<" ACK: "<<ntohl(RTL->ack)<<" chkSum: "<<RTL->chkSum<<endl; prev = RTL->syn; } else continue; if(RTL->option != 0) continue; fd_set read_fd_set; FD_ZERO(&read_fd_set); FD_SET(servfd, &read_fd_set); struct timeval tv; tv.tv_sec = 5; // Extract RTLP_Header RTL = (RTLP_Header *)(output+SIZE_IP); // Send SYN+ACK send_SYN_ACK(servfd,src_IP,dest_IP,ntohl(RTL->syn),send_seq); // Wait for ACK till timeout -- If Expired repeat the process again if(select(4, &read_fd_set, NULL, NULL, &tv) > 0) { if(FD_ISSET(servfd, &read_fd_set)) { output = (char *)malloc(MAX_PACKET_LEN*sizeof(char)); int saddr_len = sizeof(saddr); // Receive the message int buflen=recvfrom(servfd,output,MAX_PACKET_LEN,0,(struct sockaddr *)(&saddr),(socklen_t *)&saddr_len); //if(decode_checksum_new(output,buflen)) if(buflen<0) { printf("error in reading recvfrom function\n"); return; } else { RTL = (RTLP_Header *)(output+SIZE_IP); cout<<"Successfully Received "<<buflen<<": "<<output+SIZE_IP+SIZE_RLTP<<" SEQ: "<<ntohl(RTL->syn)<<" ACK: "<<ntohl(RTL->ack)<<" chkSum: "<<RTL->chkSum<<endl; if(RTL->option != 3) continue; *seq_no = ntohl(RTL->syn); *ack_no = ntohl(RTL->ack); break; } } } else continue; } } // Send SYN+ACK for Accepting Connection request void send_FIN_ACK(int servfd,char *src_IP, char *dest_IP,int seq_no,int send_seq) { cout<<"dest_IPnew: "<<dest_IP<<endl; char buffer[MAX_PACKET_LEN]; memset(buffer,0,MAX_PACKET_LEN); struct iphdr ip; RTLP_Header rltp; struct sockaddr_in sin,din; sin.sin_family = AF_INET; din.sin_family = AF_INET; sin.sin_port = 0; din.sin_port = 0; inet_pton(AF_INET,src_IP,(struct in_addr *)&sin.sin_addr.s_addr); inet_pton(AF_INET,dest_IP,(struct in_addr *)&din.sin_addr.s_addr); // Set the IP Header Parameters ip.ihl = 5; ip.version = 4; ip.tos = 16; // Low delay ip.tot_len = sizeof(struct iphdr) + sizeof(struct RLTPhdr); //### ip.frag_off = 0; ip.ttl = 64; // hops ip.protocol = IPPROTO_RAW; ip.saddr = sin.sin_addr.s_addr; ip.daddr = din.sin_addr.s_addr; ip.check = 0; memcpy(buffer,(char*)&ip,sizeof(ip)); // Set the RTLP Header Parameters rltp.sPort = 0; rltp.dPort = 0; rltp.syn = htonl(send_seq); rltp.ack = htonl(seq_no); rltp.chkSum = 0; memcpy(buffer+ sizeof(struct iphdr),&rltp,sizeof(rltp)); // Compute the CheckSum rltp.chkSum = adler32(buffer+sizeof(struct iphdr),sizeof(rltp)); memcpy(buffer+ sizeof(struct iphdr),&rltp,sizeof(rltp)); //printf("Using::Source IP: %s port: %d, Target IP: %s port: %d.\n", src_IP, src_port,dest_IP, dest_port); // Send the Packet if(sendto(servfd, buffer, ip.tot_len, 0, (struct sockaddr *)&din, (socklen_t)sizeof(din)) < 0) { perror("sendto() error"); exit(-1); } else cout<<"Successfully sent to :"<<dest_IP<<endl; } // Receive the FIN Request void receive_FIN(int servfd,char *src_IP,char *dest_IP,int send_seq,int seq_no,int *ack_no) { struct iphdr *IP; RTLP_Header *RTL; char *output; //char *dest_IP = (char *)malloc(100*sizeof(char)); // Receive SYN From Client int prev = -1,cnt = 0; int flag = 0; while(1) { struct sockaddr_in saddr; int saddr_len = sizeof(saddr); if(flag != 0) { // Receive until 3-Way Handshake for Termination has completed successfully dest_IP = (char *)malloc(100*sizeof(char)); output = (char *)malloc(MAX_PACKET_LEN*sizeof(char)); // Receive the message int buflen=recvfrom(servfd,output,MAX_PACKET_LEN,0,(struct sockaddr *)(&saddr),(socklen_t *)&saddr_len); if(buflen<0) { printf("error in reading recvfrom function\n"); return; } RTL = (RTLP_Header *)(output+SIZE_IP); IP = (struct iphdr *)(output); // Get the IP Of the Client inet_ntop(AF_INET, &(IP->saddr), dest_IP, INET_ADDRSTRLEN); // Do Checksum Check if(decode_checksum_new(output,buflen)) { // Print the data cout<<"Succesfully Received "<<buflen<<": "<<output+SIZE_IP+SIZE_RLTP<<" SEQ: "<<ntohl(RTL->syn)<<" ACK: "<<ntohl(RTL->ack)<<" chkSum: "<<RTL->chkSum<<endl; prev = RTL->syn; seq_no = RTL->syn; } else continue; if(RTL->option != 2) continue; } flag = 1; fd_set read_fd_set; FD_ZERO(&read_fd_set); FD_SET(servfd, &read_fd_set); struct timeval tv; tv.tv_sec = 5; // Extract RTLP_Header RTL = (RTLP_Header *)(output+SIZE_IP); cout<<"FIN+ACK"<<endl; // Send SYN+ACK send_FIN_ACK(servfd,src_IP,dest_IP,seq_no,send_seq); if(select(4, &read_fd_set, NULL, NULL, &tv) > 0) { if(FD_ISSET(servfd, &read_fd_set)) { output = (char *)malloc(MAX_PACKET_LEN*sizeof(char)); int saddr_len = sizeof(saddr); // Receive the message int buflen=recvfrom(servfd,output,MAX_PACKET_LEN,0,(struct sockaddr *)(&saddr),(socklen_t *)&saddr_len); //if(decode_checksum_new(output,buflen)) if(buflen<0) { printf("error in reading recvfrom function\n"); return; } else { RTL = (RTLP_Header *)(output+SIZE_IP); cout<<"Succesfully Received "<<buflen<<": "<<output+SIZE_IP+SIZE_RLTP<<" SEQ: "<<ntohl(RTL->syn)<<" ACK: "<<ntohl(RTL->ack)<<" chkSum: "<<RTL->chkSum<<endl; //*seq_no = ntohl(RTL->syn); *ack_no = ntohl(RTL->ack); if(RTL->option != 4) continue; break; } } } else continue; } } // Function for Receiving the packets from client and taking required actions void general_receive(int servfd,char *src_IP,int ack_no,int *seq_no,int *ack_no_1) { struct iphdr *IP; RTLP_Header *RTL; char *dest_IP = (char *)malloc(100*sizeof(char)); // Receive SYN From Client char *output; int cnt = 0; while(1) { output = new char[MAX_PACKET_LEN]; struct sockaddr_in saddr; int saddr_len = sizeof(saddr); // Receive the message int buflen=recvfrom(servfd,output,MAX_PACKET_LEN,0,(struct sockaddr *)(&saddr),(socklen_t *)&saddr_len); if(buflen<0) { printf("error in reading recvfrom function\n"); return; } // Do Checksum Computation RTL = (RTLP_Header *)(output+SIZE_IP); IP = (struct iphdr *)(output); int opt = RTL->option; inet_ntop(AF_INET, &(IP->saddr), dest_IP, INET_ADDRSTRLEN); if(decode_checksum_new(output,buflen)) { // Print the data cout<<"Succesfully Received "<<buflen<<": "<<output+SIZE_IP+SIZE_RLTP<<" SEQ: "<<ntohl(RTL->syn)<<" ACK: "<<ntohl(RTL->ack)<<" chkSum: "<<RTL->chkSum<<endl; } else continue; if(opt == 1) { // Recieve Data send_ACK(servfd,src_IP,dest_IP,ntohl(RTL->ack),RTL,output+SIZE_IP+SIZE_RLTP); } else if(opt == 2) { receive_FIN(servfd,src_IP,dest_IP,ntohl(RTL->ack),ntohl(RTL->syn),ack_no_1); break; } } } int main(int argc, char * argv[]) { int servfd,send_seq = 100; int temp = 1; int seq_no,ack_no; servfd = socket(AF_INET,SOCK_RAW,IPPROTO_RAW); if(servfd<0) { perror("Socket() error"); exit(-1); } if(setsockopt(servfd,IPPROTO_IP,IP_HDRINCL,&temp,sizeof(temp)) < 0) { perror("setsockopt() error"); exit(-1); } while(1) { cout<<"Waiting for new Connection"<<endl; printf("\033[H\033[J"); // receive a new Connection request receive_SYN(servfd,argv[1],send_seq,&seq_no,&ack_no); cout<<"New Connection Established"<<endl; cout<<"Seq_no: "<<seq_no<<"\tack_no: "<<ack_no<<endl; // Receive DATA or FIN from the client general_receive(servfd,argv[1],ack_no,&seq_no,&ack_no); cout<<"Connection Closed..."<<endl; cout<<"Do you want to continue(y/n): "<<endl; string s; cin>>s; if(s=="y" || s== "y\n") continue; else break; } return 0; }
true
3e2e02b913dbc721776d8a64342df91c94608e67
C++
meishaoming/cpp_primer_5th_answer
/ch03/ex3_22.cc
UTF-8
472
3.15625
3
[ "MIT" ]
permissive
#include <iostream> #include <string> #include <vector> using std::cin; using std::cout; using std::endl; using std::string; using std::vector; int main() { vector<string> text; string str; while (getline(cin, str)) { text.push_back(str); } for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) { for (auto iter = it->begin(); iter != it->end(); ++iter) { *iter = toupper(*iter); } cout << *it << endl; } return 0; }
true
8c7fdff32d54843c0b7c6526650eb7c80d564500
C++
paulolemus/sandwich-social
/guiTests/MenuV1.h
UTF-8
899
2.734375
3
[]
no_license
//intro stuff // #ifndef _MENU_H #define _MENU_H #define NUM_C 5 #include<ncurses.h> #include<string> using namespace std; class myMenus{ private: int yMax; int xMax; int yBeg; int xBeg; int Depth; int Width; int Fraction; int num_choices; string choices [NUM_C]; WINDOW * menuTemplate; public: myMenus(); myMenus(int a, int b); void setyMax(int a); void setxMax(int a); //double inputs void setyBeg(int a, int b); void setxBeg(int a, int b); void setDepth(int a, int b); void setWidth(int a, int b); void setFraction (int a); void setmenuTemplate(int a, int b, int c, int d); //getters int getyMax(); int getxMax(); int getyBeg(); int getxBeg(); int getDepth(); int getWidth(); WINDOW * getmenuTemplate(); //print void print_menu(WINDOW * w, int h, int n, string s[], int d); }; #endif // _MENU_H
true
26d4833d406ee36b47f5865f83d74a2e3a865530
C++
onlyonename/algo
/floodfill.cpp
UTF-8
1,086
3.5
4
[]
no_license
#include <iostream> #include <string> using namespace std; //是否在二维数组里 bool in_area(int hor, int col, int x, int y) { if((x >= 0 && x <= hor) && (y >= 0 && y <= col)) { return true; } return false; } int fill(int (&src)[3][3], int x, int y, int ori_color, int dst_color) { if(!in_area(3, 3, x, y)) return -1; if(src[x][y] != ori_color) return -2; if(src[x][y] == -1) return -3; src[x][y] = -1; //先标记,记下状态,表示这个结点已处理,防止死循环 fill(src, x, y - 1, ori_color, dst_color); fill(src, x - 1, y, ori_color, dst_color); fill(src, x, y + 1, ori_color, dst_color); fill(src, x + 1, y, ori_color, dst_color); src[x][y] = dst_color; return 0; } void print(int (&src)[3][3]) { for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) cout << src[i][j] << " "; cout << endl; } } int main() { int src[3][3] = {{1,1,1},{1,1,0},{1,0,1}}; cout << "before:" << endl; print(src); int x = 1; int y = 1; int color = 2; fill(src, 1, 1, 1, 2); cout << "after:" << endl; print(src); return 0; }
true
8f08e852696627075f0c0d434eddc7dcc56933d7
C++
mmer547/delfem2
/include/delfem2/points.h
UTF-8
4,646
2.59375
3
[ "MIT" ]
permissive
/* * Copyright (c) 2020 Nobuyuki Umetani * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * @file interfaces for functions that handle coordinates of points stored in a flat vector. * @brief interfaces for functions that handle coordinates of points stored in a flat vector. * @details this file should not depends on anything except for std::vector */ #ifndef DFM2_POINTS_H #define DFM2_POINTS_H #include <vector> #include "delfem2/dfm2_inline.h" // ----------------- // work on points namespace delfem2 { /** * @brief update minimum and maximum coordinates * @details implemented for "float" and "double" */ template<typename T> DFM2_INLINE void updateMinMaxXYZ( T &x_min, T &x_max, T &y_min, T &y_max, T &z_min, T &z_max, T x, T y, T z); /** * @param bb3 (out) bounding box in the order of <minx, miny, minz, maxx, maxy, maxz> * @param vtx_xyz (in) array of 3D coordinates of points * @param num_vtx (in) number of points * @details implemented for "float" and "double" */ template<typename T> DFM2_INLINE void BoundingBox3_Points3( T min3[3], T max3[3], const T *vtx_xyz, const size_t num_vtx); // center & width template<typename T> DFM2_INLINE void CenterWidth_Point3( T &cx, T &cy, T &cz, T &wx, T &wy, T &wz, const T *vtx_xyz, const size_t num_vtx); template<typename T> DFM2_INLINE void CenterWidth_Points3( T &cx, T &cy, T &cz, T &wx, T &wy, T &wz, const std::vector<T> &vtx_xyz); template<typename T> DFM2_INLINE void CenterWidth_Points3( T c[3], T w[3], const std::vector<T> &vtx_xyz); // local coordinate DFM2_INLINE void GetCenterWidthLocal( double &lcx, double &lcy, double &lcz, double &lwx, double &lwy, double &lwz, const std::vector<double> &aXYZ, const double lex[3], const double ley[3], const double lez[3]); // ------------------------------------------ /** * @brief rotate with the Bryant angle (in the order of XYZ) around the origin. * @details the angles are in the radian. */ template<typename T> DFM2_INLINE void Rotate_Points3( std::vector<T> &vec_xyz, T radx, T rady, T radz); // ---- template<typename T> DFM2_INLINE void Translate_Points( T *vtx_coords, const size_t num_vtx, const unsigned int ndim, const T *translation); template<typename T> DFM2_INLINE void Translate_Points2( std::vector<T> &aXY, T tx, T ty); template<typename T> DFM2_INLINE void Translate_Points3( std::vector<T> &aXYZ, T tx, T ty, T tz); // ---- template<typename T> DFM2_INLINE void Scale_PointsX( std::vector<T> &vtx_xyz, T scale); template<typename T> DFM2_INLINE void Scale_Points( T *vtx_coords, size_t num_vtx, unsigned int ndim, T scale); /** * @brief uniformly scale & translate the coordinate of opints * specifying the longest edge of AABB and the center of AABB is origin * @param length_longest_edge_boundingbox length of longest edge of axis-aligned bounding box */ template<typename REAL> DFM2_INLINE void Normalize_Points3( std::vector<REAL> &vtx_xyz, REAL length_longest_edge_boundingbox = 1); /** * @brief scale each vector to make norm == 1 * @param aVec coordinates packed in a single std::vector array * @param ndim dimension (must be either 2 or 3) */ template<typename REAL> DFM2_INLINE void NormalizeVector_Points( REAL *aVec, unsigned int np, unsigned int ndim); DFM2_INLINE double Size_Points3D_LongestAABBEdge( const std::vector<double> &aXYZ); /** * @details implemented for "float" and "double" */ template<typename T> DFM2_INLINE void CG_Point3( T *center_of_gravity, const std::vector<T> &vtx_xyz); DFM2_INLINE double EnergyKinetic( const double *aUVW, size_t np); template<typename T> DFM2_INLINE void Points_RandomUniform( T *aOdir, size_t npo, unsigned int ndim, const T *minCoords, const T *maxCoords); DFM2_INLINE void TangentVector_Points3( std::vector<double> &aOdir, const std::vector<double> &aNorm); class CKineticDamper { public: void Damp(std::vector<double> &aUVW) { aEnergy.push_back(EnergyKinetic(aUVW.data(), aUVW.size() / 3)); if (aEnergy.size() > 3) { aEnergy.erase(aEnergy.begin()); const double g0 = aEnergy[1] - aEnergy[0]; const double g1 = aEnergy[2] - aEnergy[1]; if (g0 > 0 && g1 < 0) { aUVW.assign(aUVW.size(), 0.0); } } } public: std::vector<double> aEnergy; }; } // delfem2 #ifndef DFM2_STATIC_LIBRARY # include "delfem2/points.cpp" #endif #endif
true
c02a68c2518fa0e28d9c6fc7ffeb7ee360c3952b
C++
larreguin1/Cs256
/Desktop/cs 256/Homework/project2.cpp
UTF-8
7,676
3.515625
4
[]
no_license
#include <iostream> #include <fstream> using namespace std; /*Bank Account Class*/ class bankAccount { public: bankAccount(double, double); virtual void deposit(double&, double&, int); virtual void withdraw(double&, double&, int); virtual void calcInt(double, double); virtual void monthlyProc(double, double&, double, int&, int&); protected: double monthlyServiceCharges; double monthlyInterestRate; double monthlyInterest; const double minBalance = 25.00; }; bankAccount::bankAccount(double initialBalance, double interestRate) { } void bankAccount::deposit(double& balance, double& amount, int numDeposits) { balance += amount; numDeposits++; } void bankAccount::withdraw(double& balance, double& amount, int numWithdrawals) { balance -= amount; numWithdrawals++; } void bankAccount::calcInt(double interestRate, double balance) { monthlyInterestRate = (interestRate / 12); monthlyInterest = balance * monthlyInterestRate; balance += monthlyInterest; } void bankAccount::monthlyProc(double interestRate, double& balance, double monthlyServiceCharges, int& numDeposits, int& numWithdrawals) { balance -= monthlyServiceCharges; calcInt(interestRate, balance); ofstream outputFile; outputFile.open("bankOutput.txt"); outputFile << "Withdrawals: "<< numWithdrawals << "\n"; outputFile << "Deposits: " << numDeposits << "\n"; outputFile << "Service Charges: " << monthlyServiceCharges << "\n"; outputFile << "Ending balance: " << balance << "\n"; //Close File outputFile.close(); numWithdrawals = 0; numDeposits = 0; monthlyServiceCharges = 0; } /*Savings Account class*/ class savingsAccount : public bankAccount { public: savingsAccount(double, double); void deposit(double); void withdraw(double); void calcInt(double); void monthlyProc(); protected: const double withdrawalCharge = 1.00; double interestRate; double savingsBalance; int numDeposits; int numWithdrawals; bool status = true; double monthlyInterest; double monthlyInterestRate; private: }; savingsAccount::savingsAccount(double initialBalance, double interestRate) : bankAccount(initialBalance, interestRate) { savingsBalance = initialBalance; interestRate = interestRate; numWithdrawals = 0; numDeposits = 0; } void savingsAccount::deposit(double amount) { bankAccount::deposit(savingsBalance, amount, numDeposits); if (savingsBalance < minBalance) { status = false; } else if (savingsBalance >= minBalance) { status = true; } } void savingsAccount::withdraw(double amount) { bankAccount::withdraw(savingsBalance, amount, numWithdrawals); if (savingsBalance < minBalance) { status = false; } else if (savingsBalance >= minBalance) { status = true; } } void savingsAccount::calcInt(double interestRate) { bankAccount::calcInt(interestRate, savingsBalance); } void savingsAccount::monthlyProc() { if (numWithdrawals > 4) { monthlyServiceCharges = (numWithdrawals - 4) * withdrawalCharge; } bankAccount::monthlyProc(interestRate, savingsBalance, monthlyServiceCharges, numDeposits, numWithdrawals); if (savingsBalance < minBalance) { status = false; } else if (savingsBalance >= minBalance) { status = true; } } /*Checkings Account Class*/ class checkingAccount : public bankAccount { public: checkingAccount(double, double); void deposit(double); void withdraw(double); void calcInt(double); void monthlyProc(); protected: double interestRate; double checkingBalance; int numDeposits; int numWithdrawals; double monthlyInterest; double monthlyInterestRate; const double monthlyFee = 5.00; const double perWithdrawalFee = 0.10; const double serviceCharge = 15.00; private: }; checkingAccount::checkingAccount(double initialBalance, double interestRate) : bankAccount(initialBalance, interestRate) { checkingBalance = initialBalance; interestRate = interestRate; numWithdrawals = 0; numDeposits = 0; } void checkingAccount::deposit(double amount) { bankAccount::deposit(checkingBalance, amount, numDeposits); } void checkingAccount::withdraw(double amount) { if ((checkingBalance - amount) < 0) { checkingBalance -= serviceCharge; return; } bankAccount::withdraw(checkingBalance, amount, numWithdrawals); } void checkingAccount::calcInt(double interestRate) { bankAccount::calcInt(interestRate, checkingBalance); } void checkingAccount::monthlyProc() { monthlyServiceCharges = monthlyFee + (numWithdrawals * perWithdrawalFee); bankAccount::monthlyProc(interestRate, checkingBalance, monthlyServiceCharges, numDeposits, numWithdrawals); } /*Main*/ void menu(checkingAccount, savingsAccount); int main() { double initialCBalance; double initialSBalance; double interestRate = 0; //Output ofstream outputFile; outputFile.open("bankOutput.txt"); //Input ifstream inputFile; inputFile.open("demofile.txt"); outputFile << "What is the initial balance in the savings account? $"; inputFile >> initialSBalance; outputFile << "What is the initial balance in the checking account? $"; inputFile >> initialCBalance; outputFile << "What is the annual interest rate? "; outputFile << interestRate; inputFile >> interestRate; outputFile << interestRate; outputFile << "\n\n"; outputFile.close(); inputFile.close(); checkingAccount checking(initialCBalance, interestRate); savingsAccount savings(initialSBalance, interestRate); menu(checking, savings); system("PAUSE"); return 0; } void menu(checkingAccount checking, savingsAccount savings) { int menu_choice; double amount; //Output ofstream outputFile; outputFile.open("bankOutput.txt"); //Input ifstream inputFile; inputFile.open("demofile.txt"); outputFile << "******** BANK ACCOUNT MENU ********" << "\n\n"; outputFile << "1. Savings Account Deposit\n"; outputFile << "2. Checking Account Deposit\n"; outputFile << "3. Savings Account Withdrawal\n"; outputFile << "4. Checking Account Withdrawal\n"; outputFile << "5. Update and Display Account Statistics\n"; outputFile << "6. Exit\n"; do { outputFile << "Your choice, please: (1-6) "; outputFile << menu_choice; inputFile >> menu_choice; outputFile << menu_choice; if (menu_choice <= 0 || menu_choice >= 7) { outputFile << "Invalid option selected!\n"; } } while (menu_choice <= 0 || menu_choice >= 7); switch (menu_choice) { case 1: outputFile << "Enter amount to deposit: $"; inputFile >> amount; savings.deposit(amount); outputFile << "\n\n"; menu(checking, savings); break; case 2: outputFile << "Enter amount to deposit: $"; inputFile >> amount; checking.deposit(amount); outputFile << "\n\n"; menu(checking, savings); break; case 3: outputFile << "Enter amount to withdraw: $"; inputFile >> amount; savings.withdraw(amount); outputFile << "\n\n"; menu(checking, savings); break; case 4: outputFile << "Enter amount to withdraw: $"; inputFile >> amount; checking.withdraw(amount); outputFile << "\n\n"; menu(checking, savings); break; case 5: outputFile << "\n"; outputFile << "SAVINGS ACCOUNT MONTHLY STATISTICS:\n"; savings.monthlyProc(); outputFile << "\n"; outputFile << "CHECKING ACCOUNT MONTHLY STATISTICS:\n"; checking.monthlyProc(); outputFile << "\n\n"; menu(checking, savings); break; case 6: outputFile << "\n\n"; break; default: break; } inputFile.close(); outputFile.close(); }
true
49187542baf9ce8d72e043f88b11a63610f8f5a6
C++
danon360/Risque-le-game
/Player.cpp
UTF-8
37,237
3.15625
3
[]
no_license
#include "Player.h" //local using namespace std; using std::vector; // Default Constructor Player::Player() { ID = new int(-1); countriesOwned = new vector<Country*>; playerHand = new Hand; name = new string(); myDice = new Dice(); myCountry = new Country(); hasConqueredThisTurn = new bool(false); } Player::Player(string* _name, int id, Map* map) { ID = new int(id); countriesOwned = new vector<Country*>; myCountry = new Country(); playerHand = new Hand; name = _name; myDice = new Dice(); gameMap = map; hasConqueredThisTurn = new bool(false); hasConqueredThisTurn = new bool(false); } // Destructor Player::~Player() { delete myCountry; delete myDice; delete countriesOwned; myCountry = NULL; countriesOwned = NULL; myDice = NULL; } void Player::addACountry(Country* toAdd) { countriesOwned->push_back(toAdd); } struct attackPossibilities { Country* source; vector<Country*>* destination; }; // Attack Method void Player::attack() { int sourceIndex; Country* source = nullptr; Country* destination = nullptr; vector<struct attackPossibilities*>* attackTree = new vector<struct attackPossibilities*>; std::cout << "************************************************************************" << std::endl; std::cout << " Attack : " << getName() << std::endl; std::cout << "************************************************************************" << std::endl; gameStats(); string willAttack; generateAttackTree(this, attackTree); if (attackTree->size() <= 0) { // if nothing in attack tree then you cannot attack this turn -> skip attack phase std::cout << "No armies in your countries can attack this turn.\n" << std::endl; return; } bool continueAttacking = strategy->attackDecision(this); Notify(*this->getID(), "Attacking", " and selecting countries to attack from"); while (continueAttacking) { // find the country to attack from source = strategy->chooseSourceCountryToAttackFrom(this, source, attackTree, &sourceIndex); // find the country to attack destination = strategy->chooseDestinationCountryToAttack(this, source, attackTree, sourceIndex); // start the fight sequence fight(source, destination); // destroy data structure and regenerate it after the fight (will have change if a country changed hands) attackTree->clear(); deleteAttackTree(attackTree); attackTree = new vector<struct attackPossibilities*>; generateAttackTree(this, attackTree); // need to regenerate tree as countries can change ownership after a fight if (attackTree->size() <= 0) { // if nothing in attack tree then you cannot attack this turn -> skip attack phase std::cout << "No countries left to attack!.\n" << std::endl; return; } // does user want to attack another country? continueAttacking = strategy->continueAttacking(this); } std::cout << "Ending attack... proceeding to Reinforce phase.\n" << std::endl; deleteAttackTree(attackTree); } void Player::fight(Country* source, Country* destination) { // implement the rest of the fight mechanism Player* defender = static_cast<Player*>(destination->owner); int attackerRoll = 3; int defenderRoll = 2; int attackerTroopCount; int defenderTroopCount; bool continueAttacking = true; while (destination->getTroopCount() > 0 && continueAttacking) { gameStats(); attackerTroopCount = source->getTroopCount(); defenderTroopCount = destination->getTroopCount(); // Rolling dice of attacking and defending players respectively std::cout << getName() << " is attacking " << defender->getName() << " from " << source->getName() << "(" << source->getTroopCount() << ") to " << destination->getName() << "(" << destination->getTroopCount() << ")" << std::endl; cout << getName() << "'s turn to roll dice..." << endl; int numAttackDice = strategy->attackerChooseDice(this, defender, source, destination); this->diceFacility(&attackerRoll, &attackerTroopCount, numAttackDice); cout << " " << endl; cout << defender->getName() << "'s turn to roll dice..." << endl; int numDefendDice = strategy->defenderChooseDice(defender, this, destination, source); defender->diceFacility(&defenderRoll, &defenderTroopCount, numDefendDice); this->compareDiceObjects(defender, source, destination); gameStats(); if(source->getTroopCount() > 1) { continueAttacking = strategy->keepFightingAtCountry(this, defender, source, destination); } else { std::cout << getName() << " does not have enough armies to keep attacking " << defender->getName() << " at " << destination->getName() << std::endl; break; } } // will change the owner and display victory message if troop count is 0. if (destination->getTroopCount() <= 0) { changeOwner(destination, source); } } void Player::changeOwner(Country* conquered, Country* winner) { int armiesToTransfer; std::cout << "\n***Glory to " << this->getName() << "!! " << conquered->getName() << " has been conquered!\n" << std::endl; // remove conquered country from looser player's country list Player* looser = static_cast<Player*>(conquered->owner); vector<Country*>* loosersCountries = looser->countriesOwned; // find index of country to delete int indexToRemove; for (int i = 0; i < loosersCountries->size(); ++i) { if (conquered->equals(loosersCountries->at(i))) { indexToRemove = i; break; } } loosersCountries->erase(loosersCountries->begin() + indexToRemove); conquered->setOwnerID(*this->getID()); conquered->owner = this; this->addACountry(conquered); *hasConqueredThisTurn = true; // this will get reset in the GameEngine main game loop armiesToTransfer = strategy->howManyTroopsToTranferAfterAWin(this, conquered, winner); winner->addToTroopCount(-armiesToTransfer); conquered->addToTroopCount(armiesToTransfer); // check if looser has any countries left, if not then remove him from the game if (looser->getCountriesOwned()->size() <= 0) { // TODO: remove the player from the vector of players in the game } gameStats(); } void Player::deleteAttackTree(vector<struct attackPossibilities*>* attackTree) { for (int i = 0; i < attackTree->size(); ++i) { delete attackTree->at(i); } } void Player::printSourceCountries(vector<struct attackPossibilities*>* attackTree) { for (int i = 0; i < attackTree->size(); ++i) { std::cout << i + 1 << ": " << attackTree->at(i)->source->toString() << std::endl; // print each valid source country } } void Player::printDestinationCountries(vector<struct attackPossibilities*>* attackTree, int sourceIndex) { struct attackPossibilities* current = attackTree->at(sourceIndex); vector<Country*>* destinationOptions = current->destination; for (int i = 0; i < destinationOptions->size(); ++i) { std::cout << (i + 1) << ": " << destinationOptions->at(i)->toString() << std::endl; } } void Player::generateAttackTree(Player* player, vector<struct attackPossibilities*>* attackTree) { vector<Country*>* owned = player->getCountriesOwned(); Country* source; for (int i = 0; i < owned->size(); ++i) { vector<Country*>* destinations = new vector<Country*>; source = owned->at(i); if (source->getTroopCount() > 1) { // first check: only owned countries with >1 troop can be source vector<Country*>* unvalidatedDestinations = source->getAdjacencyList(); for (int j = 0; j < unvalidatedDestinations->size(); ++j) { Country* destination = unvalidatedDestinations->at(j); if (destination->getOwnerID() != source->getOwnerID()) { // second check: only countries not owned by me can be destinations destinations->push_back(destination); } } } if (destinations->size() > 0) { // only add a possibility if there are countries that can be attacked struct attackPossibilities* possibility = new attackPossibilities{ source, destinations }; attackTree->push_back(possibility); } } } void Player::setTroopCount(int troop, Country* country) { country->setTroopCount(troop); } int Player::getTroopCount(Country* country) { return country->getTroopCount(); } Hand* Player::getHand() { return playerHand; } vector<Country*>* Player::getCountriesOwned() { return countriesOwned; } Country* Player::selectCountry(std::vector<Country*>* countries) { int userChoice; std::cout << "Source countries with available target countries:" << std::endl; for (int i = 0; i < countries->size(); i++) { std::cout << i + 1 << ". " << countries->at(i)->toString() << std::endl; } std::cout << std::endl; std::cout << ">>> "; do { std::cin >> userChoice; while (std::cin.fail())// || (nArmies < 1) || nArmies > remainingArmies) { std::cout << "Invalid input: enter a country in range above." << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> userChoice; } std::cout << std::endl; } while ((userChoice < 1) || (userChoice > countries->size())); return countries->at(userChoice - 1); } int Player::selectArmiesToReinforce(Country& source, int remainingArmies) { int nArmies; std::cout << source.getName() << " has " << source.getTroopCount() << " armies." << std::endl; std::cout << "Enter the number of armies you want to move to " << source.getName() << " (max " << remainingArmies << ")." << std::endl; std::cout << ">>> "; std::cin >> nArmies; while (std::cin.fail())// || (nArmies < 1) || nArmies > remainingArmies) { std::cout << "Invalid input: must be a number between 0 and " << remainingArmies << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> nArmies; } std::cout << std::endl; return nArmies; } int Player::continentBonus() { int bonusTally = 0; // index 0 will hold the number of countries owned that are of continent 0 vector<int> continentCounter(gameMap->continents->size()); // initialize the vector for (int i = 0; i < continentCounter.size(); i++) { continentCounter.at(i) = 0; } int h; for (int i = 0; i < getCountriesOwned()->size(); i++) { // hold the continent id of this country h = countriesOwned->at(i)->getContinentNumber(); // for each country in continent h, add 1 to the counter ++continentCounter.at(h); } // check the counters vs the #of countries in that continent, if equal then player owns that continent and get the bonus for (int i = 0; i < continentCounter.size(); i++) { Continent* c = gameMap->continents->at(i); if (continentCounter.at(i) == c->countries->size()) { bonusTally += c->getTroopBonus(); } } return bonusTally; } void Player::reinforce() { int armiesFromExchange = 0; int armiesFromContinent = 0; int armiesFromCountry = 0; std::cout << "**********************************************************************************" << std::endl; std::cout << " Reinforce : " << getName() << std::endl; std::cout << "**********************************************************************************" << std::endl; Notify(*this->getID(), "Reinforcing", ""); // Strategy pattern decision point: Does player want to exchange cards this turn armiesFromCountry = strategy->doExchangeOfCards(this); armiesFromCountry = std::max((int)countriesOwned->size() / 3, 3); armiesFromContinent = continentBonus(); int totalArmies = armiesFromCountry + armiesFromExchange + armiesFromContinent; // Strategy pattern decision point: what Country to assign the bonus troop strategy->whereToAssignReinforceArmies(this, totalArmies); } bool Player::equals(Player* other) { return (*ID == *(other->getID())); } // COUNTRY METHODS // Method that adds countries void Player::addCountries(Country* country) { countriesOwned->push_back(country); } // Displays the countries owned by this player void Player::collectionOfCountries() { for (int i = 0; i < countriesOwned->size(); ++i) cout << countriesOwned->at(i)->toString() << endl; cout << " " << endl; } void Player::fortify() { std::cout << "************************************************************************" << std::endl; std::cout << " Fortify : " << getName() << std::endl; std::cout << "************************************************************************" << std::endl; // does user want to fortify this turn? ----------------------------------------------------------------- if (strategy->fortifyDecision(this)) { Notify(*this->getID(), "Fortifying", ""); // get the country to move troops from ----------------------------------------------------------------- Country* countryFrom = strategy->whereToFortifyFrom(this); if (countryFrom == nullptr) { std::cout << "No source country for fortify." << std::endl; return; } Country* countryTo = strategy->whereToFortifyTo(this, countryFrom); // get country to move to ------------------------------------------------------------------------------- if (countryTo == nullptr) { std::cout << "No country can be fortied." << std::endl; return; } // get troop count to move ------------------------------------------------------------------------------------ int armiesMoved = strategy->howManyArmiesToFortifyWith(this, countryFrom, countryTo); std::cout << this->getName() << " moved " << armiesMoved << " armies from " << countryFrom->getName() << " to " << countryTo->getName() << std::endl << std::endl; } else { std::cout << this->getName() << " chose not to fortify this turn." << std::endl; } } // DICE METHODS void Player::diceFacility(int* maxRoll, int* numOfArmies, int numDiceToRoll) { myDice->rollDice(maxRoll, numOfArmies, numDiceToRoll); } void Player::compareDiceObjects(Player* player, Country* attackingCountry, Country* defendingCountry) { int numDiceToCompare = std::min(*this->myDice->numOfRolls, *player->myDice->numOfRolls); // take the min to compare that amount of dice int* attackerDice = this->myDice->container; int* defencerDice = player->myDice->container; for (int i = 0; i < numDiceToCompare; ++i) { if (attackerDice[i] > defencerDice[i]) { defendingCountry->addToTroopCount(-1); cout << player->getName() << " has lost this round and loses one army " << endl; } else { attackingCountry->addToTroopCount(-1); cout << this->getName() << " has lost this round and loses one army " << endl; } } } /************************************************************************************* PlayerStrategies **************************************************************************************/ // Constructors / Destructors -------------------------------------------------------- PlayerStrategies::PlayerStrategies() { } PlayerStrategies::~PlayerStrategies() { } // Setup methods --------------------------------------------------------------------- void PlayerStrategies::printSourceCountries(vector<struct attackPossibilities*>* attackTree) { for (int i = 0; i < attackTree->size(); ++i) { std::cout << i + 1 << ": " << attackTree->at(i)->source->toString() << std::endl; // print each valid source country } } void PlayerStrategies::printDestinationCountries(vector<struct attackPossibilities*>* attackTree, int sourceIndex) { struct attackPossibilities* current = attackTree->at(sourceIndex); vector<Country*>* destinationOptions = current->destination; for (int i = 0; i < destinationOptions->size(); ++i) { std::cout << (i + 1) << ": " << destinationOptions->at(i)->toString() << std::endl; } } // Reinforce methods ----------------------------------------------------------------- // Attack methods -------------------------------------------------------------------- // Fortify methods ------------------------------------------------------------------- /************************************************************************************* PlayerStrategies **************************************************************************************/ // Constructors / Destructors -------------------------------------------------------- HumanStrategy::HumanStrategy() { } HumanStrategy::~HumanStrategy() { } // Setup methods --------------------------------------------------------------------- // Reinforce methods ----------------------------------------------------------------- int HumanStrategy::doExchangeOfCards(Player* player) { int armiesFromExchange = 0; int user; Hand* playerHand = player->getHand(); if (playerHand->size() > 4) { while (playerHand->size() > 4) { // to cover the case of killing off other players and getting a ton of cards cout << " You have more than 4 cards so you have to exchange " << endl; armiesFromExchange = playerHand->exchange(); } } else if (playerHand->isExchangePossible()) { do { cout << "Do you want to exchange? press 1 for Yes and 0 for NO" << endl; cin >> user; if (user == 0) { armiesFromExchange = 0; } if (user == 1) { armiesFromExchange = playerHand->exchange(); } } while (user != 0 && user != 1); } return armiesFromExchange; } void HumanStrategy::whereToAssignReinforceArmies(Player* player, int totalArmies) { do { // Select country to reinforce std::cout << "\nYou have " << totalArmies << " remaining soldiers to add. "; std::cout << "Please select the country you would like to add soldiers to.\n"; Country* country = player->selectCountry(player->getCountriesOwned()); // Select number of armies to reinforce for the selected country int armies = player->selectArmiesToReinforce(*country, totalArmies); vector<Country*>* cntry = player->getCountriesOwned(); for (auto& c : *cntry) { if (c->getName() == country->getName()) { c->addToTroopCount(armies); std::cout << c->getName() << " now has " << c->getTroopCount() << " armies after reinforcing. " << std::endl; } } totalArmies -= armies; std::cout << std::endl; } while (totalArmies > 0); } // Attack methods -------------------------------------------------------------------- bool HumanStrategy::attackDecision(Player* player) { string willAttack; std::cout << "Do you want to attack? "; std::cin >> willAttack; std::cout << std::endl; if (willAttack.compare("yes") == 0 || willAttack.compare("YES") == 0 || willAttack.compare("y") == 0 || willAttack.compare("Y") == 0) return true; else return false; } Country* HumanStrategy::chooseSourceCountryToAttackFrom(Player* player, Country* eventualSource, vector<struct attackPossibilities*>* attackTree, int* sourceIndex) { const int minChoice = 1; const int maxChoice = attackTree->size(); int userChoice; do { std::cout << "Which country do you want to attack from?" << std::endl; printSourceCountries(attackTree); std::cout << ">>> "; cin >> userChoice; while (std::cin.fail()) // some error check to ensure interger input { std::cout << "Invalid input: enter a country in range (" << minChoice << " to " << maxChoice << ")" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> userChoice; } std::cout << std::endl; } while (userChoice < minChoice || userChoice >> maxChoice); // set the source index and country eventualSource = attackTree->at(userChoice - 1)->source; // set the country *sourceIndex = userChoice - 1; // set the index of the chose country (used in chooseDestinationCountry()) return eventualSource; } Country* HumanStrategy::chooseDestinationCountryToAttack(Player* player, Country* eventualSource, vector<struct attackPossibilities*>* attackTree, int sourceIndex) { Country* source = attackTree->at(sourceIndex)->source; const int minChoice = 1; const int maxChoice = source->getAdjacencyList()->size(); int userChoice; do { std::cout << "Attacking from " << source->getName() << ". Which country do you want to attack?" << std::endl; printDestinationCountries(attackTree, sourceIndex); std::cout << ">>> "; cin >> userChoice; while (std::cin.fail()) // some error check to ensure interger input { std::cout << "Invalid input: enter a country in range (" << minChoice << " to " << maxChoice << ")" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> userChoice; } std::cout << std::endl; } while (userChoice < minChoice || userChoice > maxChoice); // set the destination to what user selected Country* eventualDestination = attackTree->at(sourceIndex)->destination->at(userChoice - 1); return eventualDestination; } int HumanStrategy::attackerChooseDice(Player* attacker, Player* defender, Country* source, Country* destination) { int numDice = std::min(3, source->getTroopCount()); // hard-coded for the attack->Risk rules: attacker has max = 3 dice int diceToRoll; std::cout << "Roll from 1 to " << numDice << " dice (you have " << source->getTroopCount() << " armies)" << std::endl; cin >> diceToRoll; while (std::cin.fail() || diceToRoll < 1 || diceToRoll > numDice) { std::cout << "Error: Roll from 1 to " << numDice << " dice (you have " << source->getTroopCount() << " armies)" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> diceToRoll; } std::cout << std::endl; return diceToRoll; } int HumanStrategy::defenderChooseDice(Player* defender, Player* attacker, Country* source, Country* destination) { const int numDice = std::min(2, destination->getTroopCount()); // hard-coded for the attack->Risk rules: attacker has max = 3 dice int diceToRoll; std::cout << "Roll from 1 to " << numDice << " dice (you have " << destination->getTroopCount() << " armies)" << std::endl; cin >> diceToRoll; while (std::cin.fail() || diceToRoll < 1 || diceToRoll > numDice) { std::cout << "Error: Roll from 1 to " << numDice << " dice (you have " << destination->getTroopCount() << " armies)" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> diceToRoll; } std::cout << std::endl; if (diceToRoll < 0) diceToRoll = 1; return diceToRoll; } bool HumanStrategy::continueAttacking(Player* player) { string willAttack; std::cout << "Do you want to attack again? "; std::cin >> willAttack; std::cout << std::endl; if (willAttack.compare("yes") == 0 || willAttack.compare("YES") == 0 || willAttack.compare("y") == 0 || willAttack.compare("Y") == 0) return true; else return false; } int HumanStrategy::howManyTroopsToTranferAfterAWin(Player* player, Country* conquered, Country* winner) { const int minArmiesToTransfer = 1; const int maxArmiesToTransfer = winner->getTroopCount() - 1; int armiesToTransfer; cout << "Please select how many armies you'd like to transfer from " << winner->getName() << " to " << conquered->getName() << " (minimum: " << 1 << ", maximum: " << winner->getTroopCount() - 1 << " )" << endl; cin >> armiesToTransfer; while (cin.fail() || armiesToTransfer < minArmiesToTransfer || armiesToTransfer >= maxArmiesToTransfer) { cin.clear(); cout << "Error: Invalid number. Please try again." << endl; cin >> armiesToTransfer; } return armiesToTransfer; } bool HumanStrategy::keepFightingAtCountry(Player* attacker, Player* defender, Country* source, Country* destination) { string continueAttacking; std::cout << "Do you want to keep attacking " << defender->getName() << " at " << destination->getName() << std::endl; cin >> continueAttacking; std::cout << std::endl; if (continueAttacking.compare("yes") == 0 || continueAttacking.compare("YES") == 0 || continueAttacking.compare("y") == 0 || continueAttacking.compare("Y") == 0) return true; else return false; } // Fortify methods ------------------------------------------------------------------- bool HumanStrategy::fortifyDecision(Player* player) { string answer; std::cout << "Do you want to fortify (yes/no)? "; //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip endline from previous 'cin' cin >> answer; if (answer.compare("no") == 0 || answer.compare("NO") == 0) return false; else return true; } Country* HumanStrategy::whereToFortifyFrom(Player* player) { vector<Country*> validMoveCountries; vector<Country*>* playersOwnedCountries = player->getCountriesOwned(); for (int i = 0; i < playersOwnedCountries->size(); ++i) { Country* current = playersOwnedCountries->at(i); if (current->getTroopCount() > 1) { validMoveCountries.push_back(current); } } for (int i = 0; i < validMoveCountries.size(); ++i) { std::cout << i + 1 << ": " << validMoveCountries.at(i)->toString() << std::endl; } int input = 0; std::cout << std::endl << "Please select the country you want to move armies from.\n"; std::cout << ">>> "; std::cout << std::endl; cin >> input; //in case the user provides an invalid input or out of range while (std::cin.fail() || input < 1 || input > validMoveCountries.size()) { std::cout << "Invalid input, please choose a number in the range" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> input; } return validMoveCountries.at(input - 1); } Country* HumanStrategy::whereToFortifyTo(Player* player, Country* countryFrom) { int input; vector<Country*> validMoveCountries; vector<Country*>* neighbours = countryFrom->getAdjacencyList(); for (int i = 0; i < neighbours->size(); ++i) { // each neighbour of a country that I own Country* current = neighbours->at(i); if (player->equals(static_cast<Player*>(current->owner))) { validMoveCountries.push_back(current); } } std::cout << "Please select a destination country to move troop to (moving from: " << countryFrom->getName() << "):" << std::endl; std::cout << std::endl; for (int i = 0; i < validMoveCountries.size(); ++i) { std::cout << i + 1 << ": " << validMoveCountries.at(i)->toString() << std::endl; } std::cout << ">>> "; cin >> input; //in case the user proviedes an invalid input or out of range while (std::cin.fail() || input < 1 || input > validMoveCountries.size()) { std::cout << "Invalid input, please choose a number in the range" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> input; } std::cout << std::endl; return validMoveCountries.at(input - 1); } int HumanStrategy::howManyArmiesToFortifyWith(Player* player, Country* countryFrom, Country* countryTo) { int input; int maxTroopsToMove = countryFrom->getTroopCount() - 1; std::cout << "How many troops to move (you can move up to " << maxTroopsToMove << " troops)" << std::endl; std::cout << ">>> "; cin >> input; //in case the user proviedes an invalid input or out of range while (std::cin.fail() || input < 0 || input > maxTroopsToMove) { std::cout << "Invalid input, please choose a number in the range" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> input; } std::cout << std::endl; countryTo->addToTroopCount(input); countryFrom->addToTroopCount(-input); return input; } /************************************************************************************* AgressiveStrategy **************************************************************************************/ // Constructors / Destructors -------------------------------------------------------- AgressiveStrategy::AgressiveStrategy() { } AgressiveStrategy::~AgressiveStrategy() { } // Setup methods --------------------------------------------------------------------- // Reinforce methods ----------------------------------------------------------------- int AgressiveStrategy::doExchangeOfCards(Player* player) { int armiesFromExchange = 0; Hand* playerHand = player->getHand(); if (playerHand->size() > 4) { while (playerHand->size() > 4) { // to cover the case of killing off other players and getting a ton of cards cout << " You have more than 4 cards so you have to exchange." << endl; armiesFromExchange = playerHand->exchange(); } } else if (playerHand->isExchangePossible()) { cout << " You have exchanged cards." << endl; armiesFromExchange = playerHand->exchange(); } return armiesFromExchange; } // Attack methods -------------------------------------------------------------------- bool AgressiveStrategy::attackDecision(Player* player) { return true; // Blood for the Blood God! } Country* AgressiveStrategy::chooseSourceCountryToAttackFrom(Player* player, Country* eventualSource, vector<struct attackPossibilities*>* attackTree, int* sourceIndex) { vector<Country*>* owned = player->getCountriesOwned(); bool foundMaxCountryBorderingEnemy = false; Country* maxTroopCountry; vector<Country*>* neighbours; /* NOTE: this is incomplete, it should find the max country and check if there are enemies if there are some, return the max country. If not, find the second max and do same check (not implemented). */ maxTroopCountry = findMaxTroopCountry(owned); // find your country with the most troops neighbours = maxTroopCountry->getAdjacencyList(); for (int i = 0; i < neighbours->size(); ++i) { Country* potentialEnemy = neighbours->at(i); if (potentialEnemy->getOwnerID() != *player->getID()) { // ie. an enemy country foundMaxCountryBorderingEnemy = true; } } if (foundMaxCountryBorderingEnemy) return maxTroopCountry; else return nullptr; } Country* AgressiveStrategy::chooseDestinationCountryToAttack(Player* player, Country* source, vector<struct attackPossibilities*>* attackTree, int sourceIndex) { std::vector<Country*>* neighbours = source->getAdjacencyList(); std::vector<Country*> enemies; Country* possibleEnemy; for (int i = 0; i < neighbours->size(); ++i) { possibleEnemy = neighbours->at(i); if (source->getOwnerID() != possibleEnemy->getOwnerID()) { enemies.push_back(possibleEnemy); } } Country* toAttack = findMinTroopCountry(&enemies); return toAttack; } int AgressiveStrategy::attackerChooseDice(Player* attacker, Player* defender, Country* source, Country* destination) { int numDice = std::min(3, source->getTroopCount()); if (numDice < 0) numDice = 1; return numDice;// as many dice as he can... always! } int AgressiveStrategy::defenderChooseDice(Player* defender, Player* attacker, Country* source, Country* destination) { int numDice = std::min(2, source->getTroopCount()); if (numDice < 0) numDice = 1; return numDice; // as many dice as he can... always! } bool AgressiveStrategy::continueAttacking(Player* player) { return true; } bool AgressiveStrategy::keepFightingAtCountry(Player* attacker, Player* defender, Country* source, Country* destination) { return true; } int AgressiveStrategy::howManyTroopsToTranferAfterAWin(Player* player, Country* conquered, Country* winner) { return winner->getTroopCount() - 1; } // Fortify methods ------------------------------------------------------------------- bool AgressiveStrategy::fortifyDecision(Player* player) { return true; } int AgressiveStrategy::howManyArmiesToFortifyWith(Player* player, Country* countryFrom, Country* countryTo) { return countryFrom->getTroopCount() - 1; } Country* AgressiveStrategy::whereToFortifyFrom(Player* player) { // get the country with the min number of troops Country* fortifiee = findMinTroopCountry(player->getCountriesOwned()); // get the list of adjacent countries to it vector<Country*>* candidateToReinforceMax = fortifiee->getAdjacencyList(); // take the neighbour with the max troops to reinforce Country* fortifier = findMaxTroopCountry(candidateToReinforceMax); return fortifier; // this can be nullptr } Country* AgressiveStrategy::whereToFortifyTo(Player* player, Country* countryFrom) { return findMaxTroopCountry(countryFrom->getAdjacencyList()); // this can be nullptr } // Private helper methods ------------------------------------------------------------ Country* AgressiveStrategy::findMinTroopCountry(vector<Country*>* validMoveCountries) { Country* minTroopCountry = validMoveCountries->at(0); for (int i = 1; i < validMoveCountries->size(); ++i) { Country* temp = validMoveCountries->at(i); if (temp->getTroopCount() < minTroopCountry->getTroopCount()) minTroopCountry = temp; } return minTroopCountry; } Country* AgressiveStrategy::findMaxTroopCountry(vector<Country*>* validMoveCountries) { Country* minTroopCountry = validMoveCountries->at(0); for (int i = 1; i < validMoveCountries->size(); ++i) { Country* temp = validMoveCountries->at(i); if (temp->getTroopCount() > minTroopCountry->getTroopCount()) minTroopCountry = temp; } return minTroopCountry; } /************************************************************************************* BenevolentStrategy **************************************************************************************/ // Constructors / Destructors -------------------------------------------------------- BenevolentStrategy::BenevolentStrategy() { } BenevolentStrategy::~BenevolentStrategy() { } // Setup methods --------------------------------------------------------------------- // Reinforce methods ----------------------------------------------------------------- int BenevolentStrategy::doExchangeOfCards(Player* player) { int armiesFromExchange = 0; Hand* playerHand = player->getHand(); if (playerHand->size() > 4) { while (playerHand->size() > 4) { // to cover the case of killing off other players and getting a ton of cards cout << " You have more than 4 cards so you have to exchange." << endl; armiesFromExchange = playerHand->exchange(); } } else if (playerHand->isExchangePossible()) { cout << " You have exchanged cards." << endl; armiesFromExchange = playerHand->exchange(); } return armiesFromExchange; } // Attack methods -------------------------------------------------------------------- bool BenevolentStrategy::attackDecision(Player* player) { return false; // I'm too young to die! } int BenevolentStrategy::attackerChooseDice(Player* attacker, Player* defender, Country* source, Country* destination) { int numDice = std::min(1, source->getTroopCount()); if (numDice < 0) numDice = 1; return numDice; // as few dice as he can... bring our boys home! } int BenevolentStrategy::defenderChooseDice(Player* defender, Player* attacker, Country* source, Country* destination) { int numDice = std::min(1, source->getTroopCount()); if (numDice < 0) numDice = 1; return std::min(1, source->getTroopCount()); // as few dice as he can... bring our boys home! } bool BenevolentStrategy::continueAttacking(Player* player) { return false; } bool BenevolentStrategy::keepFightingAtCountry(Player* attacker, Player* defender, Country* source, Country* destination) { return false; } int BenevolentStrategy::howManyTroopsToTranferAfterAWin(Player* player, Country* conquered, Country* winner) { return winner->getTroopCount() - 1; } // Fortify methods ------------------------------------------------------------------- bool BenevolentStrategy::fortifyDecision(Player* player) { return true; } int BenevolentStrategy::howManyArmiesToFortifyWith(Player* player, Country* countryFrom, Country* countryTo) { return countryFrom->getTroopCount() - 1; } Country* BenevolentStrategy::whereToFortifyFrom(Player* player) { // get the country with the max number of troops Country* fortifiee = findMinTroopCountry(player->getCountriesOwned()); // get the list of adjacent countries to it vector<Country*>* candidatesToReinforceMax = fortifiee->getAdjacencyList(); // take the neighbour with the max troops to reinforce Country* fortifier = findMaxTroopCountry(candidatesToReinforceMax); return fortifier; // this can be nullptr } Country* BenevolentStrategy::whereToFortifyTo(Player* player, Country* countryFrom) { return findMinTroopCountry(countryFrom->getAdjacencyList()); // this can be nullptr } // Private helper methods ------------------------------------------------------------ Country* BenevolentStrategy::findMinTroopCountry(vector<Country*>* validMoveCountries) { Country* minTroopCountry = validMoveCountries->at(0); for (int i = 1; i < validMoveCountries->size(); ++i) { Country* temp = validMoveCountries->at(i); if (temp->getTroopCount() < minTroopCountry->getTroopCount()) minTroopCountry = temp; } return minTroopCountry; } Country* BenevolentStrategy::findMaxTroopCountry(vector<Country*>* validMoveCountries) { Country* minTroopCountry = validMoveCountries->at(0); for (int i = 1; i < validMoveCountries->size(); ++i) { Country* temp = validMoveCountries->at(i); if (temp->getTroopCount() > minTroopCountry->getTroopCount()) minTroopCountry = temp; } return minTroopCountry; } void Player::gameStats() { Map* map = this->gameMap; vector<Country*>* allCountries = map->countries; std::cout << "Country Stats" << std::endl; std::cout << getName() << " has ID = " << *getID() << std::endl; for (int i = 0; i < allCountries->size(); ++i) { std::cout << allCountries->at(i)->toString() << std::endl; } std::cout << std::endl; }
true
b85be1c2e3b3684c71b98127e175f95ebfeb8b7c
C++
mpdivecha/Particle-Filter-Vehicle-Localization
/src/particle_filter.cpp
UTF-8
10,455
2.96875
3
[ "MIT" ]
permissive
/* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; /** * Initializes particle filter by initializing particles to Gaussian * distribution around first position and all the weights to 1. * @param {double} x Initial x position [m] (simulated estimate from GPS) * @param {double} y Initial y position [m] * @param {double} theta Initial orientation [rad] * @param {double[]} std Array of dimension 3 [standard deviation of x [m], standard deviation of y [m] * standard deviation of yaw [rad]] */ void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and others in this file). /* We create 1000 particles to begin with. We initialize three distributions * for x, y and theta respectively. The mean and std devs are as supplied. * We sample the initial configurlations of each particle from these distributions */ default_random_engine gen; num_particles = 500; normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); for (int i = 0; i < num_particles; i++) { Particle p; p.id = i; p.x = dist_x(gen); p.y = dist_y(gen); p.theta = dist_theta(gen); particles.push_back(p); } weights.resize(num_particles); is_initialized = true; } /** * prediction Predicts the state for the next time step * using the process model. * @param delta_t Time between time step t and t+1 in measurements [s] * @param std_pos[] Array of dimension 3 [standard deviation of x [m], standard deviation of y [m] * standard deviation of yaw [rad]] * @param velocity Velocity of car from t to t+1 [m/s] * @param yaw_rate Yaw rate of car from t to t+1 [rad/s] */ void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ // Some short names double dt = delta_t; double v = velocity; double yr = yaw_rate; // lightweight random generator default_random_engine gen; for (int i = 0; i < num_particles; i++) { double x_0 = particles[i].x; double y_0 = particles[i].y; double theta_0 = particles[i].theta; // The CTRV model double x_1, y_1, theta_1; if (yr != 0) { x_1 = x_0 + v/yr*(sin(theta_0 + yr*dt) - sin(theta_0)); y_1 = y_0 + v/yr*(cos(theta_0) - cos(theta_0 + yr*dt)); theta_1 = theta_0 + yr*dt; } else { x_1 = x_0 + v*dt*cos(theta_0); y_1 = y_0 + v*dt*sin(theta_0); theta_1 = theta_0; } // Gaussian distributions for x, y and theta normal_distribution<double> dist_x(x_1, std_pos[0]); normal_distribution<double> dist_y(y_1, std_pos[1]); normal_distribution<double> dist_theta(theta_1, std_pos[2]); // Update the particle state with predictions particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); } } /** * dataAssociation Finds which observations correspond to which landmarks (likely by using * a nearest-neighbors data association). * @param predicted Vector of predicted landmark observations * @param observations Vector of landmark observations */ void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. } /** * updateWeights Updates the weights for each particle based on the likelihood of the * observed measurements. * @param sensor_range Range [m] of sensor * @param std_landmark[] Array of dimension 2 [Landmark measurement uncertainty [x [m], y [m]]] * @param observations Vector of landmark observations * @param map Map class containing map landmarks */ void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { // TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read // more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution // NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located // according to the MAP'S coordinate system. You will need to transform between the two systems. // Keep in mind that this transformation requires both rotation AND translation (but no scaling). // The following is a good resource for the theory: // https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm // and the following is a good resource for the actual equation to implement (look at equation // 3.33 // http://planning.cs.uiuc.edu/node99.html /** * First transform the observations to map coordinates. * Associate each observation with the nearest map landmark using the dist() function * (this can be done in the above function) * Assign weights to each of the particles */ double& sig_x = std_landmark[0]; // reference instead of copy for speed double& sig_y = std_landmark[1]; // reference instead of copy for speed double gauss_norm= (1/(2 * M_PI * sig_x * sig_y)); //weights.clear(); for(int i = 0; i < num_particles; i++) { Particle& p = particles[i]; double P_weight = 1.0f; // Clear the associations p.associations.clear(); p.sense_x.clear(); p.sense_y.clear(); // Transform from vehicle to map coordinates for (LandmarkObs o : observations) { double x_m = p.x + cos(p.theta)*o.x - sin(p.theta)*o.y; double y_m = p.y + sin(p.theta)*o.x + cos(p.theta)*o.y; // Find the nearest landmark to be associated with this observation double best_dist = 9999999; Map::single_landmark_s best_landmark; for (Map::single_landmark_s l : map_landmarks.landmark_list) { double range = dist(x_m, y_m, l.x_f, l.y_f); if (range <= sensor_range && range < best_dist) { best_dist = range; best_landmark = l; } } o.id = best_landmark.id_i; // Set-up associations and coords p.associations.push_back(o.id); p.sense_x.push_back(x_m); p.sense_y.push_back(y_m); // The exponent double exponent = (pow((x_m - best_landmark.x_f),2))/(2*pow(sig_x,2)) + (pow((y_m - best_landmark.y_f),2))/(2*pow(sig_y,2)); // The weight double weight = gauss_norm * exp(-exponent); P_weight *= weight; } // Update the particle weight p.weight = P_weight; weights[i] = P_weight; } } /** * resample Resamples from the updated set of particles to form * the new set of particles. */ void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution default_random_engine gen; discrete_distribution<int> sampler(weights.begin(), weights.end()); // Create a new vector. The old vector should not be overwritten until after // the sampling is done. vector<Particle> newParticles; for (int i = 0; i < num_particles; i++) { newParticles.push_back(particles[sampler(gen)]); } particles.clear(); particles = newParticles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
true
3499018d7fb5226b81b477a63011c67de5d08070
C++
kalleand/id1217
/lab4/uppg8/unisex.cpp
UTF-8
5,315
3.640625
4
[]
no_license
/** * Simulation of a unisex bathroom using monitor to * provide synchronization. * * To run the program use the make file using default rule. * Number of men and women can be specified using NRW and NRM. * This will compile the program as well. To compile the program * without running it use the rule unisex in Makefile. * * Example compile: * make unisex * * Example run and compile: * NRW=5 NRM=8 make */ #ifndef _REENTRANT #define _REENTRANT #endif #include <iostream> #include <cstdlib> #include <pthread.h> #include "monitor.h" #define MAX_WOMEN 20 /* Max number of women. */ #define MAX_MEN 20 /* Max number of men. */ #define MAX_TIMES 40 /* Max times inside bathroom. */ #define MAX_TOILET_TIME 3 /* Max time inside bathroom. */ #define MIN_TOILET_TIME 1 /* Min time in bathroom. */ #define MAX_WAIT_TIME 10 /* Max time between visits. */ #define MIN_WAIT_TIME 2 /* Min time between visits. */ void * man(void *); /* Simulation method for men. */ void * woman(void *); /* Simulation method for women. */ /* Counters to hold number of men, women and the number of * times the bathroom has been used. */ int men, women, times_used; /* Lock for the counter to exit the simulation. */ pthread_mutex_t counter_lock; /* The monitor for the bathroom. */ monitor * mon; /** * Main method. First initializes and then reads the input of how * many men and women that should be in the simulation. Then * creates the threads and then joins them again. */ int main(int argc, char ** argv) { pthread_t persons[MAX_MEN + MAX_WOMEN]; /* The threads are saved here. */ pthread_attr_t attr; /* Attributes for the pthreads. */ long index; /* For 64-bit systems. */ /* Set counter of bathroom visits to 0. */ times_used = 0; if(argc < 3) /* If unsufficient amount of arguments were supplied. */ { std::cout << "Usage ./unisex NRW NRM" << std::endl; return EXIT_FAILURE; } else /* Read the number of men and women. */ { /* We cap them at MAX_WOMEN and MAX_MEN. */ women = (atoi(argv[1]) > MAX_WOMEN) ? MAX_WOMEN : atoi(argv[1]); men = (atoi(argv[2]) > MAX_MEN) ? MAX_MEN : atoi(argv[2]); } /* Initialize the attributes. */ pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); /* Initialize the lock. */ pthread_mutex_init(&counter_lock, NULL); /* Seed the randomizer with the time to provide different result every run. */ srand(time(NULL)); mon = new monitor(); /* Create the monitor. */ for(index = 0; index < men; ++index) /* Spawn the men threads. */ { pthread_create(&persons[index], &attr, man, (void *) index); } for(index = 0; index < men; ++index) /* Spawn the women threads. */ { pthread_create(&persons[men + index], &attr, woman, (void *) index); } for(int i = 0; i < men + women; ++i) /* Joins the threads again. */ { pthread_join(persons[i], NULL); } delete mon; /* Delete the monitor when done. */ return EXIT_SUCCESS; } /** * Women method for simulating bathroom visits to a unisex toilet. * * First sleeps to simulate the time between bathroom breaks and then calls the * monitor method woman_enter. Then simulate the bathroom visit by sleeping and * finally exits the bathroom by calling the monitor method woman_exit. */ void * woman(void * input) { long number = (long) input; while(true) { /* Sleep to simulate time before a bathroom visit is necessary. */ sleep((rand() % (MAX_WAIT_TIME - MIN_WAIT_TIME)) + MIN_WAIT_TIME); if(times_used >= MAX_TIMES) /* If the simulation is done. */ { pthread_exit(NULL); } /* Enter the bathroom. */ mon->woman_enter(number); /* Sleep to simulate a bathroom visit. */ sleep((rand() % (MAX_TOILET_TIME - MIN_TOILET_TIME)) + MIN_TOILET_TIME); /* Update times_used. */ pthread_mutex_lock(&counter_lock); times_used++; pthread_mutex_unlock(&counter_lock); /* Exit the bathroom. */ mon->woman_exit(number); } } /** * Men method for simulating bathroom visits to a unisex toilet. * * First sleeps to simulate the time between bathroom breaks and then calls the * monitor method man_enter. Then simulate the bathroom visit by sleeping and * finally exits the bathroom by calling the monitor method man_exit. */ void * man(void * input) { long number = (long) input; while(true) { /* Sleep to simulate time before a bathroom visit is necessary. */ sleep((rand() % (MAX_WAIT_TIME - MIN_WAIT_TIME)) + MIN_WAIT_TIME); if(times_used >= MAX_TIMES) /* If the simulation is done. */ { pthread_exit(NULL); } /* Enter the bathroom. */ mon->man_enter(number); /* Sleep to simulate a bathroom visit. */ sleep((rand() % (MAX_TOILET_TIME - MIN_TOILET_TIME)) + MIN_TOILET_TIME); /* Update times_used. */ pthread_mutex_lock(&counter_lock); times_used++; pthread_mutex_unlock(&counter_lock); /* Exit the bathroom. */ mon->man_exit(number); } }
true
40667b72d1c7b9d633eec6791ed21ba1471509b8
C++
fjrp1412/algorithm_and_dataStructures
/toolkit_algoritms/week2/c_code/fibonacci_again.cpp
UTF-8
766
3.46875
3
[]
no_license
#include <iostream> long long Pisano_period(long long m){ long long prev = 0; long long curr = 1; long long result = 0; for(int i = 0; i < m*m; i++){ long long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; if(prev == 0 && curr == 1){ result = i+1; } } return result; } long long fib_again(long long n, long long m){ long long pisano = Pisano_period(m); n = n % pisano; long long prev = 0; long long curr = 1; if(n == 0){ return 0; } else if(n == 1){ return 1; } for(int i = 0; i < n-1; i++){ long long temp = 0; temp = curr; curr = (prev + curr) % m; prev = temp; } return curr % m; } int main(){ long long n,m; std::cin >> n >> m; std::cout << fib_again(n,m) << "\n"; return 0; }
true
b78b07e66dd05969d19dad0556e1121a9d46872c
C++
kit234/MATHF
/operation_string.cpp
GB18030
1,861
3.390625
3
[]
no_license
//operation_string.cppַйصĺ #include "operation.h" #include "common.h" using std::string; typedef string String_Type; //ַ static bool IsOperator(char); //жַǷ static void check(string) throw(string,const char*); //ַǷϷ bool IsOperator(char c){ if(c == '+') return true; return false; } string operation_string(string str){ check(str); String_Type but; str = "+" + str; str = str + "+"; do{ bool exit{true}; for(decltype(str.length()) i{0};i < str.length();++i){ if(str[i] == '+'){ if(i == str.length()-1) break; exit = false; auto e{i+1}; for(;e < str.length();++e){ if(str[e] == '\''){ for(auto j{e+1};j < str.length();++j) if(str[j] == '\''){e = j; break;} } else if(str[e] == '"'){ for(auto j{e+1};j < str.length();++j) if(str[j] == '"'){e = j;break;} } else if(IsOperator(str[e])) break; } if(GetTypeOf(str.substr(i+1,e-i-1))!="string") throw "stringδ֪ͣ"; but += str.substr(i+2,e-i-3); i = e-1; } } }while(!exit); return but; } void check(string str) throw(string,const char*){ if(IsOperator(str[0]) || IsOperator(str[str.length()-1])) throw "string˫ĿԴ"; for(auto itr = str.begin();itr != str.end();++itr){ if(*itr == '\''){ for(auto p = itr + 1;p != str.end();++p) if(*p == '\''){itr = p; break;} continue; } if(*itr == '"'){ for(auto p = itr + 1;p != str.end();++p) if(*p == '"'){itr = p; break;} continue; } if(IsOperator(*itr) && (IsOperator(*(itr-1)) || IsOperator(*(itr+1)))) throw "stringظ֣"; } }
true
852e2ed1ce8a569ed35502492a7d0cf0b76fff6e
C++
dan64ml/cracking_coding_interview
/src/10_sort_search/problem_8.cpp
UTF-8
1,485
3.40625
3
[]
no_license
/********************************************************************************* * Дан массив с числами от 1 до не более 32000. Массив может содержать дубликаты. * Вывести все дубликаты используя не более 4К памяти. ********************************************************************************/ #include "chapter_10.h" #include <vector> #include <ostream> #include <array> using namespace std; namespace ch10 { template<int Size> class BitVector { private: array<uint8_t, Size> data_ = {}; public: BitVector() = default; bool GetBit(int idx) { int byte_num = idx / 8; int bit_num = idx % 8; return data_[byte_num] & (0x1 << bit_num); } void SetBit(int idx) { int byte_num = idx / 8; int bit_num = idx % 8; data_[byte_num] |= (0x1 << bit_num); } }; // 4К памяти и максимальное число 32000 очень намекают на битовый вектор. // Здесь очень простой битовый велосипед, хотя просится std::bitset(). void DisplayDublicates(ostream& os, const vector<int>& vec) { BitVector<4096> bv; for (auto e : vec) { if (bv.GetBit(e)) { os << e << ','; } else { bv.SetBit(e); } } } } // namespace ch10
true
4105bb8cb1959d99dcef4db725c068d99ebdfd8e
C++
ViniciusTM/ai_class_tp1
/cLib/structures.cpp
UTF-8
17,088
2.8125
3
[]
no_license
#include <vector> #include <queue> #include <stack> #include <string> #include <sstream> #include <ctime> #include <iostream> #include <fstream> #include <cmath> #include <cstring> #include "structures.h" // Internal functions int simple_dist(const State& s) { int side = static_cast<int>(std::sqrt(s.config.size())); int dist = 0; for (int i=0; i<s.config.size(); i++) { int right_pos = s.config[i] - 1; int pos = i; if (right_pos == -2) { right_pos = 8; } if (right_pos != pos) { dist += 1; } } return dist; } int city_block_dist(const State& s) { int side = static_cast<int>(std::sqrt(s.config.size())); int dist = 0; for (int i=0; i<s.config.size(); i++) { int right_pos = s.config[i] - 1; int pos = i; if (right_pos == -2) { right_pos = 8; } dist += std::abs(right_pos / side - (pos) / side) + std::abs(right_pos % side - (pos) % side); } return dist; } // Node Node::Node(int n) { for (int i=0; i<n; i++) { children.push_back(NULL); } } TabuList::TabuList(int n) { root = new Node(n); size = 0; } TabuList::~TabuList() { clear_tree(root); } void TabuList::clear_tree(Node *node) { if (node != NULL) { for (Node* n : node->children) { clear_tree(n); } delete node; } } bool TabuList::find(State s) { Node *current; current = root; for (int i : s.config) { bool stop = true; if (i == -1) { if (current->children[0]) { current = current->children[0]; stop = false; } } else { if (current->children[i]) { current = current->children[i]; stop = false; } } if (stop) { return false; } } return true; } bool TabuList::find_and_add(State s) { Node *current; current = root; for (int i : s.config) { bool stop = true; if (i == -1) { if (current->children[0]) { current = current->children[0]; stop = false; } } else { if (current->children[i]) { current = current->children[i]; stop = false; } } if (stop) { this->add(s); return false; } } if (current->depth > s.steps.size()) { current->depth = s.steps.size(); return false; } else { return true; } } void TabuList::add(State s) { int i = 0; int n = s.config.size(); Node *current; current = root; while(current && i<n) { bool stop = true; int idx = s.config[i]; if (idx == -1) { if (current->children[0]) { current = current->children[0]; i++; stop = false; } } else { if (current->children[idx]) { current = current->children[idx]; i++; stop = false; } } if (stop) { break; } } for (int k=i; k<n; k++) { int j = s.config[k]; if (j == -1) { current->children[0] = new Node(n); current = current->children[0]; } else { current->children[j] = new Node(n); current = current->children[j]; } } current->depth = s.steps.size(); size ++; } // State State::State(State *s) { config = s->config; steps = s->steps; emptyPos = s->emptyPos; n = s->n; } State::State(int size) { n = size; config.resize(size); for (int i=0; i<size; i++) { config[i] = -1; } } State::State() {} State State::make_move(int i, int j, int move) { State s(this); std::swap(s.config[i], s.config[j]); s.emptyPos = j; s.steps.push_back(move); return s; } std::vector<State> State::generate_actions() { std::vector<State> results; int side = static_cast<int>(std::sqrt(n)); if (this->emptyPos / side == (this->emptyPos - 1) / side && (this->emptyPos - 1 >= 0)) { results.push_back(this->make_move(this->emptyPos, this->emptyPos - 1, LEFT)); } if (this->emptyPos / side == (this->emptyPos + 1) / side && (this->emptyPos + 1 < this->config.size())) { results.push_back(this->make_move(this->emptyPos, this->emptyPos + 1, RIGHT)); } if (this->emptyPos - side >= 0) { results.push_back(this->make_move(this->emptyPos, this->emptyPos - side, UP)); } if (this->emptyPos + side < this->config.size()) { results.push_back(this->make_move(this->emptyPos, this->emptyPos + side, DOWN)); } return results; } bool State::check() { for (int i=1; i<9; i++) { if (config[i-1] != i) { return false; } } return true; } void State::print_steps() { for (int i : this->steps) { switch(i) { case UP: std::cout << "UP "; continue; case DOWN: std::cout << "DOWN "; continue; case LEFT: std::cout << "LEFT "; continue; case RIGHT: std::cout << "RIGHT "; continue; default: ; } } std::cout << std::endl; } void State::print_state() { int side = static_cast<int>(std::sqrt(n)); for (int i=0; i<n; i++) { std::cout << config[i] << " "; if (i % side == side-1) { std::cout << std::endl; } } std::cout << std::endl; } void State::print_steps(std::ofstream& file) { for (int i : this->steps) { switch(i) { case UP: file << "UP "; continue; case DOWN: file << "DOWN "; continue; case LEFT: file << "LEFT "; continue; case RIGHT: file << "RIGHT "; continue; default: ; } } file << std::endl; } // Solution Solution::Solution() { nStatesVisited = 0; stopWatch = clock(); } void Solution::print_output(std::ofstream& file) { if (!solvable) { file << "SOLUTION NOT FOUND" << std::endl; file << std::endl; return ; } else { state.print_steps(file); } file << state.steps.size() << " " << nStatesVisited << " " << elapsedTime << std::endl; file << std::endl; } // Game Game::Game(State &config) { state.config = config.config; n = state.config.size(); state.n = n; } Game::Game(std::string& config, int size) { n = static_cast<int>(pow(size, 2)); state.config.reserve(n); state.n = n; std::stringstream line(config); int value; while(line >> value) { state.config.push_back(value); if (value == -1) { state.emptyPos = state.config.size() - 1; } } } Solution Game::bfs() { std::queue<State> q; TabuList tabu(this->n); Solution sol; if (this->state.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&this->state); return sol; } for (State state : this->state.generate_actions()) { q.push(state); tabu.add(state); } while (q.size() != 0) { State s = q.front(); q.pop(); sol.nStatesVisited += 1; if (s.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&s); return sol; } if (s.steps.size() > 31) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = false; return sol; } for (State state : s.generate_actions()) { if (tabu.find(state)) { continue; } else { q.push(state); tabu.add(state); } } } std::cout << "algo deu bem errado" << std::endl; } void Game::dfs(int k, Solution& sol) { TabuList tabu(this->n); if (this->state.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&this->state); return ; } std::stack<State> stack; for (State state : this->state.generate_actions()) { stack.push(state); tabu.add(state); } while (stack.size() > 0) { State s = stack.top(); stack.pop(); //s.print_steps(); sol.nStatesVisited += 1; if (s.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&s); return ; } for (State state : s.generate_actions()) { if (state.steps.size() > k) { continue; } if (tabu.find_and_add(state)) { continue; } stack.push(state); } } //std::cout << "size: " << tabu.size << std::endl; } Solution Game::ids() { Solution sol; sol.solvable = false; for (int k=1; k<=31; k++) { this->dfs(k, sol); if (sol.solvable) { return sol; } } return sol; } Solution Game::ucs() { TabuList tabu(this->n); Solution sol; auto comp = [](State a, State b) {return a.steps.size() > b.steps.size(); }; std::priority_queue<State, std::vector<State>, decltype(comp)> queue(comp); if (this->state.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&this->state); return sol; } for (State state : this->state.generate_actions()) { queue.push(state); tabu.add(state); } while (queue.size() != 0) { State s = queue.top(); queue.pop(); sol.nStatesVisited += 1; if (s.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&s); return sol; } if (s.steps.size() > 31) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = false; return sol; } for (State state : s.generate_actions()) { if (tabu.find(state)) { continue; } else { queue.push(state); tabu.add(state); } } } } Solution Game::greedy_bfs(std::string heuristic) { Solution sol; if (std::strcmp(heuristic.c_str(),"city block") != 0 && std::strcmp(heuristic.c_str(),"simple dist") != 0) { std::cout << "Invalid heuristic" << std::endl; return sol; } TabuList tabu(this->n); auto comp = [](State a, State b) {return a.heuristic_dist > b.heuristic_dist; }; std::priority_queue<State, std::vector<State>, decltype(comp)> queue(comp); if (this->state.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&this->state); return sol; } for (State state : this->state.generate_actions()) { if (std::strcmp(heuristic.c_str(),"city block") == 0) { state.heuristic_dist = city_block_dist(state); } else { state.heuristic_dist = simple_dist(state); } queue.push(state); tabu.add(state); } while (queue.size() != 0) { State s = queue.top(); queue.pop(); sol.nStatesVisited += 1; if (s.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&s); return sol; } for (State state : s.generate_actions()) { if (tabu.find_and_add(state)) { continue; } if (std::strcmp(heuristic.c_str(),"city block") == 0) { state.heuristic_dist = city_block_dist(state); } else { state.heuristic_dist = simple_dist(state); } queue.push(state); } } } Solution Game::a_star(std::string heuristic) { Solution sol; if (std::strcmp(heuristic.c_str(),"city block") != 0 && std::strcmp(heuristic.c_str(),"simple dist") != 0) { std::cout << "Invalid heuristic" << std::endl; return sol; } TabuList tabu(this->n); auto comp = [](State a, State b) {return a.heuristic_dist > b.heuristic_dist; }; std::priority_queue<State, std::vector<State>, decltype(comp)> queue(comp); if (this->state.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&this->state); return sol; } for (State state : this->state.generate_actions()) { if (std::strcmp(heuristic.c_str(),"city block") == 0) { state.heuristic_dist = city_block_dist(state); } else { state.heuristic_dist = simple_dist(state); } queue.push(state); tabu.add(state); } while (queue.size() != 0) { State s = queue.top(); queue.pop(); sol.nStatesVisited += 1; if (s.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&s); return sol; } // if (s.steps.size() > 31) { // sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; // sol.solvable = false; // return sol; // } for (State state : s.generate_actions()) { if (tabu.find_and_add(state)) { continue; } else { if (std::strcmp(heuristic.c_str(),"city block") == 0) { state.heuristic_dist = s.steps.size() + city_block_dist(state); } else { state.heuristic_dist = s.steps.size() + simple_dist(state); } queue.push(state); } } } } Solution Game::local_search(std::string heuristic) { Solution sol; if (std::strcmp(heuristic.c_str(),"city block") != 0 && std::strcmp(heuristic.c_str(),"simple dist") != 0) { std::cout << "Invalid heuristic" << std::endl; return sol; } TabuList tabu(this->n); auto comp = [](State a, State b) {return a.heuristic_dist > b.heuristic_dist; }; State current(&this->state); if (std::strcmp(heuristic.c_str(),"city block") == 0) { current.heuristic_dist = city_block_dist(state); } else { current.heuristic_dist = simple_dist(state); } while (true) { if (current.check()) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = true; sol.state = State(&current); return sol; } sol.nStatesVisited += 1; State best; best.heuristic_dist = 1000; bool stop = true; for (State state : current.generate_actions()) { if (tabu.find(state)) { continue; } if (std::strcmp(heuristic.c_str(),"city block") == 0) { state.heuristic_dist = city_block_dist(state); } else { state.heuristic_dist = simple_dist(state); } if (state.heuristic_dist <= current.heuristic_dist) { if (state.heuristic_dist < best.heuristic_dist) { tabu.add(state); best = state; stop = false; } } } if (stop) { sol.elapsedTime = static_cast<double>(clock() - sol.stopWatch) / CLOCKS_PER_SEC; sol.solvable = false; return sol; } current = best; } }
true
7f99b0f07ca0211ce4e654d385b0070686c97131
C++
PrachiSinghal86/Leetcode
/Math/numers atmost n given digits .cpp
UTF-8
670
2.609375
3
[]
no_license
class Solution { public: int atMostNGivenDigitSet(vector<string>& digits, int n) { string s=to_string(n); int c=0; int x=digits.size(); sort(digits.begin(),digits.end()); for(int i=1;i<s.size();i++) { c=c+x; x=x*digits.size(); } for(int j=0;j<s.size();j++) { int i=0; while(i<digits.size()&&digits[i][0]<s[j]) { c=c+pow(digits.size(),s.size()-1-j); i++; } if(i==digits.size()||digits[i][0]>s[j]) return c; } c+=1; return c; } };
true
7a3bb7789903eac5d2aa8ff842f5ff972df42ef9
C++
mstfknn/malware-sample-library
/Carbanak/Carbanak - part 1/botep/core/source/ThroughTunnel.cpp
WINDOWS-1251
1,110
2.796875
3
[]
no_license
#include "core\ThroughTunnel.h" #include "core\socket.h" #include "core\debug.h" ThroughTunnel::ThroughTunnel( int _portIn, const char* _ipOut, int _portOut ) : portIn(_portIn), portOut(_portOut) { Str::Copy( ipOut, sizeof(ipOut), _ipOut ); } ThroughTunnel::~ThroughTunnel() { } static DWORD WINAPI ThroughTunnelThread( void* data ) { ThroughTunnel* through = (ThroughTunnel*)data; through->Start(); return 0; } bool ThroughTunnel::Start() { Loop(); return true; } bool ThroughTunnel::StartAsync() { return RunThread( ThroughTunnelThread, this ); } int ThroughTunnel::Connected( int sc ) { return 0; } void ThroughTunnel::Loop() { DbgMsg( " ThroughTunnel, : %d", portIn ); int sc = Socket::CreateListen(portIn); if( !sc ) return; bool stop = false; while( !stop ) { int scIn = Socket::Accept(sc); if( scIn == SOCKET_ERROR ) break; int scOut = Connected(scIn); if( scOut <= 0 ) scOut = Socket::ConnectIP( ipOut, portOut ); if( scOut > 0 ) Socket::StartTunnel( scIn, scOut ); else Socket::Close(scIn); } DbgMsg( " ThroughTunnel" ); }
true
7acc5ff259fcadb3a277c30dd81644a16d7c5a25
C++
folguera/DTTrigger
/doc/referece_code/analyzer/mpredundantfilter.h
UTF-8
2,040
2.703125
3
[]
no_license
/** * Project: * Subproject: tracrecons * File name: mpredundantfilter.h * Language: C++ * * ********************************************************************* * Description: * * * To Do: * * Author: Jose Manuel Cela <josemanuel.cela@ciemat.es> * * ********************************************************************* * Copyright (c) 2018-03-06 Jose Manuel Cela <josemanuel.cela@ciemat.es> * * For internal use, all rights reserved. * ********************************************************************* */ #ifndef MPREDUNDANTFILTER_H #define MPREDUNDANTFILTER_H #include "analtypedefs.h" #include "i_filter.h" #include "muonpath.h" #include "ringbuffer.h" using namespace CIEMAT; namespace CMS { /* * Esta clase implementa un filtro que elimina elementos MuonPath duplicados. * * Se basa en mantener un buffer con los últimos (64) elementos --distintos * entre sí-- localizados y usarlos para comparar los nuevos elementos que * se van extrayendo de la fifo de entrada. Si un nuevo elemento extraído * es igual a alguno en el buffer, dicho elemento no es enviado a la fifo de * salida y es descartado * Si el elemento localizado no se encuentra en el buffer es insertado en él * como nuevo MP para comparaciones futuras, y una copia del mismo es enviada * a la salida. * Si el buffer está lleno, antes de insertar el nuevo elemento el más antiguo * es eliminado. */ class MPRedundantFilter : public I_Filter { public: MPRedundantFilter(I_Popper &dataIn, I_Pusher &dataOut, int bufSize = 64); virtual ~MPRedundantFilter(); void filter(void); void reset(void); private: /* * En este buffer se mantienen los ultimos "bufSize" elementos procesados * (se mantienen copias de los mismos), de tal manera que sirven de * elementos de comparacion para eliminar aquellos que, entrando por el * "dataIn", sean identicos a algunos de los almacenados */ RingBuffer buffer; bool isInBuffer(MuonPath* mPath); }; } #endif
true
3c5d6eef3215681c8a8bc1bd91374f1755dba42f
C++
camhellstern/Chapter6HW
/router.cpp
UTF-8
3,424
2.65625
3
[]
no_license
#include "router.h" Router::Router(QObject *parent, int dramSize, int storageParam) : QObject(parent) { cost = 0; if(dramSize == 1) { if(storageParam == 1) { LoadBalancer *loadb1 = new LoadBalancer(this, 4, false); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 4, false); lb2 = loadb2; } else if(storageParam == 2) { LoadBalancer *loadb1 = new LoadBalancer(this, 4, true); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 4, false); lb2 = loadb2; } else if(storageParam == 3) { LoadBalancer *loadb1 = new LoadBalancer(this, 4, true); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 4, true); lb2 = loadb2; } } else if(dramSize == 2) { if(storageParam == 1) { LoadBalancer *loadb1 = new LoadBalancer(this, 16, false); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 16, false); lb2 = loadb2; } else if(storageParam == 2) { LoadBalancer *loadb1 = new LoadBalancer(this, 16, true); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 16, false); lb2 = loadb2; } else if(storageParam == 3) { LoadBalancer *loadb1 = new LoadBalancer(this, 16, true); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 16, true); lb2 = loadb2; } } else if(dramSize == 3) { if(storageParam == 1) { LoadBalancer *loadb1 = new LoadBalancer(this, 32, false); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 32, false); lb2 = loadb2; } else if(storageParam == 2) { LoadBalancer *loadb1 = new LoadBalancer(this, 32, true); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 32, false); lb2 = loadb2; } else if(storageParam == 3) { LoadBalancer *loadb1 = new LoadBalancer(this, 32, true); lb1 = loadb1; LoadBalancer *loadb2 = new LoadBalancer(this, 32, true); lb2 = loadb2; } } cost = lb1->lbCost() + lb2->lbCost()+ROUTERCOST; connect(this, &Router::sendLB1, lb1, &LoadBalancer::processRequest); connect(this, &Router::sendLB2, lb2, &LoadBalancer::processRequest); connect(lb1, &LoadBalancer::sendResponse, this, &Router::processResponse); connect(lb2, &LoadBalancer::sendResponse, this, &Router::processResponse); } Router::~Router() { } int Router::routerCost() { return cost; } void Router::processRequest(RequestPacket request) { if(request.ipAddress >= ipStart && request.ipAddress <= ipEnd) { if(request.ipAddress <= (ipStart+ipEnd)/2) emit sendLB1(request); else emit sendLB2(request); } } void Router::setIPRange(int startIP, int endIP) { ipStart = startIP; ipEnd = endIP; } void Router::processResponse(ResponseType *response) { emit sendResponse(response); }
true
c0ef45f573124310eda4b918152357205bcce5cc
C++
RobotElliot/C--primerplus-answer
/ch06/6-3.cpp
UTF-8
688
3.609375
4
[]
no_license
#include <iostream> using namespace std; int main() { cout << "Please enter one of the following choices: "<<endl; cout << "c) carnivore"<<" "<< "p) pianist"<<endl; cout << "t) tree"<<" "<< "g) game"<<endl; char ch,flag = 1; cin>> ch; while(flag) { switch(ch) { case 'c': cout << "carnivore"<<endl; flag = 0; break; case 'p': cout << "pianist"<<endl; flag = 0; break; case 't': cout << "tree"<<endl; flag = 0; break; case 'g': cout<<"game"<<endl; flag = 0; break; default: cout<<"Please enter a c,p,t, or g : "; cin>>ch; break; } } return 0; }
true
3d1849200f7cebffc0e6b117531e1820541c2f54
C++
technoligest/kmeansII
/lib/runners/kmeans.cc
UTF-8
2,874
2.859375
3
[ "MIT" ]
permissive
// // Created by Yaser Alkayale on 2017-08-28. // /* * Run a single kmeans instance with any given commandLine args. To know the args needed, * just run the program without any args. */ #include <iostream> #include <cassert> #include "../algorithm/kmeans.h" using std::endl; using std::cout; int main(int argc, char **argv) { //std::cout << "Algorithm: " << args.algorithm << " l:" << args.l << " r: " << args.r << " dataset is: " // << dataset.size() << "X" << dataset[0].size() << std::endl; kmeans::KmeansArgs args; if(!args.parse_args(argc, argv)) { std::cout << "Usage: ./kmeans -i <inputFile> -a <algorithm name> -k <k value>" << std::endl; return 1; } kmeans::NewSeedPicker newSeedPicker(args.l, args.r); kmeans::LloydIterationRunner lloydIterationRunner(200); kmeans::KmeansBase *algo; if(args.algorithm == "kmeans") { algo = new kmeans::Kmeans<>(); } else if(args.algorithm == "kmeans++") { algo = new kmeans::Kmeanspp<>(); } else if(args.algorithm == "kmeansNew") { assert(args.l != -1 && args.r != -1); algo = new kmeans::KmeansConsensus<>(&lloydIterationRunner, &newSeedPicker); } else if(args.algorithm == "kmeansII") { assert(args.l != -1 && args.r != -1); algo = new kmeans::KmeansII<kmeans::LloydIterationRunner, kmeans::LloydIterationRunner>(args.l, args.r); } else { std::cout << "Inputted algorithm [" << args.algorithm << "] is not found. Please enter one of (kmeans, kmeans++ or kmeansII)."; exit(1); } std::ifstream inputFile; inputFile.open(args.inputFileName); assert(inputFile.good()); kmeans::Dataset dataset = kmeans::readCSVDataset(inputFile); std::vector<kmeans::Instance> centres; algo->cluster(dataset, args.k, centres); using kmeans::operator<<; std::ofstream realOutFile; std::ofstream optionsOutFile; if(args.outputFileName != "none") { realOutFile.open(args.outputFileName, std::ios::out); optionsOutFile.open(args.outputFileName + ".extra", std::ios::out); } std::ostream &o = (args.outputFileName != "none") ? realOutFile : std::cout; std::ostream &o2 = (args.outputFileName != "none") ? optionsOutFile : std::cout; for(auto centre:centres) { o << centre << std::endl; } o2 << "Input:" << args.inputFileName << std::endl; o2 << "Iterations time:" << algo->iterationRunnerTime() << std::endl; o2 << "Seeding tim:" << algo->seedPickerTime() << std::endl; o2 << "Distance squared:" << algo->distanceSquared() << endl; realOutFile.flush(); realOutFile.close(); optionsOutFile.flush(); optionsOutFile.close(); delete algo; return 0; } //l:5 r:5 k:50file: /Users/yaseralkayale/Documents/classes/current/honours/kmeansII/generatedFiles/datasets/dataset0.csv //l:-1 r:-1 k:5file: /Users/yaseralkayale/Documents/classes/current/honours/kmeansII/generatedFiles/datasets/dataset0.csv
true
a961cdc24fc19b80909ddd06cf865e578fb5c885
C++
RogerYong/leetcode
/数据结构/线性表/链表/24.两两交换链表中的节点.cpp
UTF-8
1,113
3.28125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class ListNode { public: int val; ListNode *next; // ListNode() : val(0), next(nullptr) {} // ListNode(int x) : val(x), next(nullptr) {} // ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode *swapPairs(ListNode *head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode *newHead = head->next; ListNode *preNode = nullptr; ListNode *firstNode = head; ListNode *secondNode = nullptr; while (firstNode != nullptr && firstNode->next != nullptr) { // secondNode = firstNode->next; // 维护3个节点的next if (preNode != nullptr) { preNode->next = secondNode; } firstNode->next = secondNode->next; secondNode->next = firstNode; // 维护3个Node变量 preNode = firstNode; firstNode = preNode->next; } return newHead; } };
true
d95562115b964fb6db7918de49deb82501455005
C++
AshMagorian/GA-AStar-Pathfinding
/AI Genetic alogrithm/AStar.cpp
UTF-8
6,624
3.109375
3
[]
no_license
#include "AStar.h" #include "Node.h" AStar::AStar() { dx[0] = 1; dy[0] = 0; dx[1] = 1; dy[1] = 1; dx[2] = 0; dy[2] = 1; dx[3] =-1; dy[3] = 1; dx[4] =-1; dy[4] = 0; dx[5] =-1; dy[5] = -1; dx[6] = 0; dy[6] = -1; dx[7] = 1; dy[7] = -1; } AStar::~AStar() { } void AStar::RunProgram(int _w, int _h, std::vector<int> _mapData) { for (int i = 0; i < 20; i++) // initialise all map values to 1 { for (int j = 0; j < 20; j++) { map[i][j] = 1; } } for (int i = 0; i < _h; i++) // put the map data into the array { for (int j = 0; j < _w; j++) { map[j][i] = _mapData.at(j + (_w * i)); std::cout << map[j][i]; if (map[j][i] == 2) { xStart = j; yStart = i; } if (map[j][i] == 3) { xFinish = j; yFinish = i; } } std::cout << std::endl; } std::cout << "Map Size (X,Y): " << _w << "," << _h << std::endl; std::cout << "Start: " << xStart << "," << yStart << std::endl; std::cout << "Finish: " << xFinish << "," << yFinish << std::endl; clock_t start = clock(); std::string route = pathFind(xStart, yStart, xFinish, yFinish); if (route == "") { std::cout << "An empty route generated!" << std::endl; } clock_t end = clock(); double time_elapsed = double(end - start); std::cout << "Time to calculate the route (ms): " << time_elapsed << std::endl; if (route.length() > 0) { int j; char c; int x = xStart; int y = yStart; for (int i = 0; i < route.length(); i++) { c = route.at(i); j = atoi(&c); x = x + dx[j]; y = y + dy[j]; map[x][y] = 4; } map[x][y] = 3; } } std::string AStar::pathFind(const int & xStart, const int & yStart, const int & xFinish, const int & yFinish) { static std::priority_queue<Node> pq[2]; // list of open (not-yet-tried) nodes static int pqi; // pq index static Node* n0; static Node* m0; static int i, j, x, y, xdx, ydy; static char c; pqi = 0; // reset the node maps for (y = 0; y < m; y++) { for (x = 0; x < n; x++) { closed_nodes_map[x][y] = 0; open_nodes_map[x][y] = 0; } } // create the start node and push into list of open nodes n0 = new Node(xStart, yStart, 0, 0); n0->updatePriority(xFinish, yFinish); pq[pqi].push(*n0); open_nodes_map[x][y] = n0->getPriority(); // mark it on the open nodes map // A* search while (!pq[pqi].empty()) { // get the current node w/ the highest priority // from the list of open nodes n0 = new Node(pq[pqi].top().getxPos(), pq[pqi].top().getyPos(), pq[pqi].top().getLevel(), pq[pqi].top().getPriority()); x = n0->getxPos(); y = n0->getyPos(); pq[pqi].pop(); // remove the node from the open list open_nodes_map[x][y] = 0; // mark it on the closed nodes map closed_nodes_map[x][y] = 1; // quit searching when the goal state is reached //if((*n0).estimate(xFinish, yFinish) == 0) if (x == xFinish && y == yFinish) { // generate the path from finish to start // by following the directions std::string path = ""; while (!(x == xStart && y == yStart)) { j = dir_map[x][y]; c = '0' + (j + dir / 2) % dir; path = c + path; x += dx[j]; y += dy[j]; } // garbage collection delete n0; // empty the leftover nodes while (!pq[pqi].empty()) pq[pqi].pop(); return path; } // generate moves (child nodes) in all possible directions for (i = 0; i < dir; i++) { xdx = x + dx[i]; ydy = y + dy[i]; if (!(xdx<0 || xdx>n - 1 || ydy<0 || ydy>m - 1 || map[xdx][ydy] == 1 || closed_nodes_map[xdx][ydy] == 1)) { // generate a child node m0 = new Node(xdx, ydy, n0->getLevel(), n0->getPriority()); m0->nextLevel(i, dir); m0->updatePriority(xFinish, yFinish); // if it is not in the open list then add into that if (open_nodes_map[xdx][ydy] == 0) { open_nodes_map[xdx][ydy] = m0->getPriority(); pq[pqi].push(*m0); // mark its parent node direction dir_map[xdx][ydy] = (i + dir / 2) % dir; } else if (open_nodes_map[xdx][ydy] > m0->getPriority()) { // update the priority info open_nodes_map[xdx][ydy] = m0->getPriority(); // update the parent direction info dir_map[xdx][ydy] = (i + dir / 2) % dir; // replace the node // by emptying one pq to the other one // except the node to be replaced will be ignored // and the new node will be pushed in instead while (!(pq[pqi].top().getxPos() == xdx && pq[pqi].top().getyPos() == ydy)) { pq[1 - pqi].push(pq[pqi].top()); pq[pqi].pop(); } pq[pqi].pop(); // remove the wanted node // empty the larger size pq to the smaller one if (pq[pqi].size() > pq[1 - pqi].size()) pqi = 1 - pqi; while (!pq[pqi].empty()) { pq[1 - pqi].push(pq[pqi].top()); pq[pqi].pop(); } pqi = 1 - pqi; pq[pqi].push(*m0); // add the better node instead } else delete m0; // garbage collection } } delete n0; // garbage collection } return ""; // no route found } void AStar::Present(int _w, int _h) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw std::exception(); } SDL_Event event; const int blockSize = 40; bool quit = false; SDL_Window *window = SDL_CreateWindow("AI", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, _w*blockSize, _h*blockSize, SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL); // create the window if (!SDL_GL_CreateContext(window)) { throw std::exception(); } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0); // create the renderer if (!renderer) { throw std::exception(); } SDL_Rect block{ 0, 0, blockSize, blockSize }; // create the drawing block for (int i = 0; i < _h; i++) // put the map data into window { for (int j = 0; j < _w; j++) { switch (map[j][i]) { case 0: SDL_SetRenderDrawColor(renderer, 200, 200, 200, 200); // grey if empty space break; case 1: SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); // black if wall break; case 2: SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // red if start break; case 3: SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); // green if finish break; case 4: SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255); // blue represents the path travelled default: break; } block.x = (j % _w) * blockSize; // set block x position block.y = (i % _h) * blockSize; // set block y position SDL_RenderFillRect(renderer, &block); // draw the block } } SDL_RenderPresent(renderer); while (!quit) // display loop { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { quit = true; } } } SDL_DestroyWindow(window); SDL_Quit(); }
true
758eef9f13834ae2398becdf1858b48c908e8416
C++
shivam-tripathi/code
/practice/threading/test.cpp
UTF-8
449
2.78125
3
[]
no_license
// Compile as g++ test.cpp p_threads_class.cpp -std=c++11 -lpthreads -o3 #include "p_threads_class.h" #include <bits/stdc++.h> using namespace std; class TestThread : public PThreadsClass{ public: void run(){ cout << " Test thread Running " << endl; } }; int main(){ PThreadsClass *thread = new TestThread; thread->setJoinable(true); thread->startThread(); thread->join(); thread->endThread(); return 0; }
true
179f7538340889dd360945265e0b68aea25d0889
C++
fullsaildevelopment/FSGDEngine
/EDSolutions/sphereSolutions.cpp
UTF-8
6,411
2.515625
3
[]
no_license
#include "precompiled.h" #include "../EDUtilities/PrintConsole.h" #include "../EDMath/sphere.h" #include "../EDCollision/EDCollision.h" #include "../EDCollision/segment.h" #include "../EDCollision/triangle.h" using EDUtilities::PrintConsole; using EDMath::Float3; namespace EDCollision { float ClosestPtSphereSolution( const Sphere& s, const Float3& p, Float3& cp ) { static bool added = false; if(!added) { PrintConsole::GetReference().AddSolution(L"ED3", "Sphere Collision", Float3(1.0f, 0.0f, 0.0f), L"EDCollision::ClosestPtSphereSolution"); added = true; } Float3 v = p - s.center; float dSq = v.squaredMagnitude(); if( dSq < s.radius*s.radius ) { cp = p; return dSq; } v *= 1.0f / sqrtf(dSq); cp = s.center + v * s.radius; return dSq; } /***/ bool SphereToSphereSolution( const Sphere& sphere1, const Sphere& sphere2, Contact* contact ) { static bool added = false; if(!added) { PrintConsole::GetReference().AddSolution(L"ED3", "Sphere Collision", Float3(1.0f, 0.0f, 0.0f), L"EDCollision::SphereToSphereSolution"); added = true; } Float3 v = sphere1.center - sphere2.center; float dSq = v.squaredMagnitude(); float r = sphere1.radius + sphere2.radius; if( dSq < r*r ) { if( contact ) { float d = sqrtf( dSq ); float pd = r - d; if( d == 0.0f ) return false; contact->Normal = v * (1.0f / d); contact->PenetrationDepth = pd; contact->Point[0] = sphere1.center - contact->Normal * sphere1.radius; contact->numPoints = 1; } return true; } return false; } bool SphereToCapsuleSolution( const Sphere& sphere, const Capsule& capsule, Contact* contact ) { static bool added = false; if(!added) { PrintConsole::GetReference().AddSolution(L"ED3", "Sphere Collision", Float3(1.0f, 0.0f, 0.0f), L"EDCollision::SphereToCapsuleSolution"); added = true; } float offset = capsule.height * 0.5f; Float3 s1 = capsule.center - capsule.direction * offset; Float3 s2 = capsule.center + capsule.direction * offset; float r = sphere.radius + capsule.radius; Float3 cp; Float3 d = s2 - s1; Float3 v = sphere.center - s1; float s = Clamp( DotProduct( v, d ) / DotProduct( d, d ), 0.0f, 1.0f ); cp = s1 + d * s; Float3 n = sphere.center - cp; float sqD = n.squaredMagnitude(); if( sqD < r*r ) { if( contact ) { float d = sqrtf( sqD ); float pd = r - d; if( d == 0.0f ) return false; contact->Normal = n * (1.0f / d); contact->PenetrationDepth = pd; contact->Point[0] = sphere.center - contact->Normal * sphere.radius; contact->numPoints = 1; } return true; } return false; } bool SphereToAabbSolution( const Sphere& sphere, const Aabb& aabb, Contact* contact ) { static bool added = false; if(!added) { PrintConsole::GetReference().AddSolution(L"ED3", "Sphere Collision", Float3(1.0f, 0.0f, 0.0f), L"EDCollision::SphereToAabbSolution"); added = true; } Float3 cp = sphere.center; for(int i = 0; i < 3; ++i) { if( cp.v[i] < aabb.center.v[i] - aabb.extents.v[i] ) cp.v[i] = aabb.center.v[i] - aabb.extents.v[i]; if( cp.v[i] > aabb.center.v[i] + aabb.extents.v[i] ) cp.v[i] = aabb.center.v[i] + aabb.extents.v[i]; } Float3 v = sphere.center - cp; float sqD = v.squaredMagnitude(); if( sqD < sphere.radius * sphere.radius ) { if( contact ) { if( sqD > 0.0f ) { float d = sqrtf(sqD); float pd = sphere.radius - d; contact->Normal = v * (1.0f / d); contact->PenetrationDepth = pd; contact->Point[0] = sphere.center - contact->Normal * sphere.radius; contact->numPoints = 1; } else { Float3 axis(0.0f, 0.0f, 0.0f); int bestAxis = 0; v = sphere.center - aabb.center; float bestDistance = v.x / aabb.extents.x; sqD = v.squaredMagnitude(); if( sqD == 0.0f ) return false; float newDistance = v.y / aabb.extents.y; if( abs(newDistance) > abs(bestDistance) ) { bestDistance = newDistance; bestAxis = 1; } newDistance = v.z / aabb.extents.z; if( abs(newDistance) > abs(bestDistance) ) { bestDistance = newDistance; bestAxis = 2; } axis.v[bestAxis] = (bestDistance < 0.0f ? -1.0f : 1.0f); float d = abs(v.v[bestAxis]); float r = sphere.radius + aabb.extents.v[bestAxis]; float pd = r - d; contact->Normal = axis; contact->PenetrationDepth = pd; contact->Point[0] = sphere.center - contact->Normal * sphere.radius; contact->numPoints = 1; } } return true; } return false; } bool SphereToTriangleSolution( const Sphere& sphere, const Float3& a, const Float3& b, const Float3& c, Contact* contact ) { static bool added = false; if(!added) { PrintConsole::GetReference().AddSolution(L"ED3", "Sphere Collision", Float3(1.0f, 0.0f, 0.0f), L"EDCollision::SphereToTriangleSolution"); added = true; } Float3 cp; float sqD = ClosestPtTriangleSolution( sphere.center, a, b, c, cp ); if( sqD < sphere.radius * sphere.radius ) { if( contact ) { float d = sqrtf(sqD); float pd = sphere.radius - d; if( d == 0.0f || pd < 0.001f ) return false; Float3 tN; CrossProduct( tN, b-a, c-b ); Float3 N = (sphere.center - cp) * (1.0f / d);; if( DotProduct( tN, N ) < 0.0f ) return false; contact->Normal = N; contact->PenetrationDepth = pd; contact->Point[0] = sphere.center - contact->Normal * sphere.radius; contact->numPoints = 1; } return true; } return false; } bool SphereToObbSolution( const Sphere& sphere, const Obb& obb, Contact* contact ) { static bool added = false; if(!added) { PrintConsole::GetReference().AddSolution(L"ED3", "Sphere Collision", Float3(1.0f, 0.0f, 0.0f), L"EDCollision::SphereToObbSolution"); added = true; } Aabb aabb; aabb.center.makeZero(); aabb.extents = obb.extents; Sphere oSphere = sphere; InvTransformPoint( oSphere.center, sphere.center, obb.transform ); if( SphereToAabbSolution( oSphere, aabb, contact ) ) { if( contact ) { TransformPoint( contact->Point[0], contact->Point[0], obb.transform ); TransformVector( contact->Normal, contact->Normal, obb.transform ); } return true; } return false; } /***/ }
true
5608504c8495c1f4d64090ba8eb1a860d87d1f58
C++
valdirSalgueiro/puzzleGame
/GreenJuiceTeam/GreenJuiceTeam.Shared/game/font/TreeNode.h
UTF-8
715
2.640625
3
[]
no_license
#ifndef _TREENODE_H_INCLUDED_ #define _TREENODE_H_INCLUDED_ #include "Allocator.h" class FTBitmapChar; class TreeNode { public: TreeNode(); TreeNode(int x, int y, int width, int height); ~TreeNode(); void Set(int x, int y, int width, int height); bool Add(FTBitmapChar* pFTBitmapChar); bool IsEmpty() const { return m_pLeaf1 == NULL && m_pLeaf2 == NULL; } static Allocator<TreeNode>& GetAllocator() { return m_allocator; } private: void CreateBranches(FTBitmapChar* pFTBitmapChar); bool Fits(FTBitmapChar* pFTBitmapChar); int m_x; int m_y; int m_width; int m_height; TreeNode* m_pLeaf1; TreeNode* m_pLeaf2; static Allocator<TreeNode> m_allocator; }; #endif // _TREENODE_H_INCLUDED_
true
b0a9d706fcdc2f5ebbd2762c562eede100ba3869
C++
Eternity-AIBN/NJU-Practice-of-Fundamental-Programming
/PlaneWar/PlaneWar/Bullet.h
GB18030
910
2.765625
3
[]
no_license
#pragma once #include<atlimage.h> #include<vector> using namespace std; extern void transparent(CImage &img); class Bullet { int positionX, positionY; //ӵ int height, width; bool direction; //ӵķ,1,0 public: static CImage image; //ӵͼƬ bool whoShoot; //˭ӵ0һ1л int getX() const { return positionX; } int getY() const { return positionY; } int getHeight() const { return height; } int getWidth() const { return width; } Bullet() { height = 20; width = 10; } Bullet(int x, int y, bool dir, bool who, int(*flag)[680]); void reset(int(*flag)[680]){ flag[positionX - 17][positionY - 5] = 0; } void bulletMove(int(*flag)[680]); //ӵƶ bool hit(); //жǷб߽ const CImage &getImage() const { return image; } void initImage(); };
true
560202362fd72f2cbca179ec651d0929b026522f
C++
KyungminYu/Algorithm
/BOJ/4343 Arctic Network.cpp
UTF-8
1,159
2.875
3
[]
no_license
#include <stdio.h> #include <algorithm> #include <math.h> using namespace std; struct edge { int s1, s2; double len; edge() {}; edge(int s1, int s2, double len) { this->s1 = s1; this->s2 = s2; this->len = len; } int operator < (edge e) const { return len < e.len; } }E[124751]; struct pos { double x, y; pos() {}; void read() { scanf("%lf %lf", &x, &y); } }S[501]; int parent[501]; int find(int v) { if (v == parent[v]) return v; return parent[v] = find(parent[v]); } double dist(pos& p1, pos& p2) { return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } int main() { int t; scanf("%d", &t); while (t--) { int s, p, ind = 0; scanf("%d %d", &s, &p); for (int i = 0; i < p; i++) { S[i].read(); parent[i] = i; } for (int i = 0; i < p - 1; i++) { for (int j = i + 1; j < p; j++) E[ind++] = { i, j, dist(S[i], S[j]) }; } sort(E, E + ind); double res = 0.0; for (int i = 0; i < ind && s < p; i++) { int s1 = find(E[i].s1); int s2 = find(E[i].s2); if (s1 != s2) { p--; parent[s2] = s1; res = E[i].len; } } printf("%.2lf\n", res); } return 0; }
true
ececff995ff005717912023801e5a961f738ac1e
C++
KunalWasHere/GeekForGeeks-solutions
/greedy problems/page faults in lru.cpp
UTF-8
3,038
2.640625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct newnode { struct newnode *next,*prev; int data; }; int main() { int t,n,i,arr[1000],cap,freq,set; cin>>t; while(t--) { struct newnode *head,*tail,*node,*p; freq=0; head=NULL; tail=NULL; cin>>n; for(i=0;i<n;i++) { cin>>arr[i]; } cin>>cap; i=0; for(i=0;i<n;i++) { if(freq>=cap) break; set=0; p=head; while(p!=NULL) { if(p->data==arr[i]) { //cout<<"hi"; p->prev->next=p->next; if(p->next!=NULL) p->next->prev=p->prev; p->next=head;//commit head->prev=p; p->prev=NULL; head=p;//cout<<i; i++; set=1; continue;; } else p=p->next; } cout<<set; if(set) {cout<<"hi";i--;continue;} node=(newnode*)malloc(sizeof(struct newnode));//cout<<"hi"; freq++; node->data=arr[i]; node->next=head; if(head!=NULL) head->prev=node; node->prev=NULL; head=node; //i++;//cout<<"hiy"; } if(i==n) { cout<<freq<<endl; continue; } //cout<<"hi"; p=head; while(p->next!=NULL) p=p->next; tail=p; //cout<<tail->data; for(i=i;i<n;i++) { set=0; p=head; while(p!=NULL) { if(p->data==arr[i]) { if(p->next==NULL) tail=p->prev; p->prev->next=p->next; if(p->next!=NULL) p->next->prev=p->prev; p->next=head; head->prev=p; p->prev=NULL; head=p; i++; set=1; continue; } p=p->next; } if(set) {i--;continue;} tail->data=arr[i];//cout<<"hi 1"; tail->prev->next=NULL;//cout<<"hi 2"; node=tail;//cout<<"hi 3"; tail=tail->prev;//cout<<"hi 4"; node->next=head;//cout<<"hi 5"; head->prev=node; node->prev=NULL; head=node; freq++;//cout<<"hi"<<arr[i]; } cout<<freq<<endl; } }
true
f46070f28e7df6ca18d5a16370ead65e46fe2492
C++
tixsys/esteid
/minidriver/tags/initial_import/cardlib/ManagerInterface.h
UTF-8
4,540
2.90625
3
[]
no_license
/*! \file ManagerInterface.h \copyright (c) Kaido Kert ( kaidokert@gmail.com ) \licence BSD \author $Author: kaidokert $ \date $Date: 2008-10-30 18:16:34 +0200 (N, 30 okt 2008) $ */ // Revision $Revision: 134 $ #pragma once typedef unsigned int uint; typedef unsigned char byte; typedef unsigned short word; typedef unsigned long dword; typedef unsigned short ushort; /// shorthand for std::vector<unsigned char>, used everywhere typedef std::vector<byte> ByteVec; struct ConnectionBase; /// Abstraction of system smarcard managers /** ManagerInterface is abstraction of system smartcard managers. Concrete managers are PCSCManager and CTAPIManager. Example additional derivations might be direct communications driver or even serial/USB port */ class ManagerInterface { private: //disable object copying ManagerInterface(const ManagerInterface &); ManagerInterface& operator=(const ManagerInterface &); public: ManagerInterface(void): mLogger(NULL) {} virtual ~ManagerInterface(void) {} /// number of installed readers virtual uint getReaderCount() = 0; /// name of the reader at index virtual std::string getReaderName(uint index) = 0; /// string form of reader status at index, EMPTY, POWERED etc virtual std::string getReaderState(uint index) = 0; /// hex representation of card ATR in reader at index, empty string if no card is present virtual std::string getATRHex(uint index) = 0; /// connects instance of card to reader at index, forceT0 is used for cards that cant speak T1 virtual ConnectionBase * connect(uint index,bool forceT0=false) = 0; /// reconnect using a different protocol virtual ConnectionBase * reconnect(ConnectionBase *c,bool forceT0=false) {return c;} /// use given stream as APDU log inline void setLogging(std::ostream *logStream) {mLogger = logStream;} protected: std::ostream *mLogger; friend struct ConnectionBase; friend struct Transaction; friend class CardBase; friend class SmartCardManager; friend struct SmartCardConnection; virtual void makeConnection(ConnectionBase *c,uint idx) = 0; virtual void deleteConnection(ConnectionBase *c) = 0; virtual void beginTransaction(ConnectionBase *c) = 0; virtual void endTransaction(ConnectionBase *c,bool forceReset = false) = 0; virtual void execCommand(ConnectionBase *c,std::vector<byte> &cmd,std::vector<byte> &recv, unsigned int &recvLen) = 0; virtual void execPinEntryCommand(ConnectionBase *c,std::vector<byte> &cmd) { throw std::runtime_error("This manager does not support PIN entry commands"); } virtual void execPinChangeCommand(ConnectionBase *c,std::vector<byte> &cmd ,size_t oldPinLen,size_t newPinLen) { throw std::runtime_error("This manager does not support PIN change commands"); } /// tell if given connection is using T1 (true) or T0 virtual bool isT1Protocol(ConnectionBase *c) = 0; }; /// Represents connection to smart card reader /** ConnectionBase represents a connection of a smart card instance to reader, and holds the connection parameters. Concrete derivations are PCSCConnection and CTAPIConnection */ struct ConnectionBase { /// reference to Manager ManagerInterface &mManager; /// reader index uint mIndex; /// force T0 protocol for connection bool mForceT0; /// if false, we are using application-supplied connection handle bool mOwnConnection; /// tells if the manager has a secure PIN input method, true for CTAPI virtual bool isSecure() {return false;} ConnectionBase(ManagerInterface &manager) : mManager(manager),mIndex(-1),mForceT0(false),mOwnConnection(false) {} ConnectionBase(ManagerInterface &manager,unsigned int index,bool f) : mManager(manager),mIndex(index),mForceT0(f),mOwnConnection(true) { mManager.makeConnection(this,index); } virtual ~ConnectionBase() { if (mOwnConnection) mManager.deleteConnection(this); } }; /// Wraps a beginTransaction/endTransaction pair /** Transaction wraps a beginTransaction/endTransaction pair, so functions can be performed on cards without interruptions. It needs to be instanced from a given smart card function that needs to be performed as an atomic unit */ struct Transaction { ManagerInterface& mManager; ConnectionBase *mConnection; Transaction(ManagerInterface& manager,ConnectionBase *connection): mManager(manager),mConnection(connection) { mManager.beginTransaction(mConnection); } ~Transaction() { mManager.endTransaction(mConnection); } };
true
497f2a1e5fc8705879585e6efab239c8f084f437
C++
MohamadIsmail/Online-Judges-solutions
/Level3/string to palindrome.cpp
UTF-8
899
2.734375
3
[]
no_license
//#include<iostream> //#include<cstring> //#include<string> //#include<cctype> //#include<vector> //using namespace std; // //int DP[1003][1003]; //string arr; // //int min(int x, int y, int z) //{ // int t = x < y ? x : y; // return t = z < t ? z : t; //} // //int Edit_distance(int i ,int j, int mid) //{ // if(i>=j) // return 0; // if(DP[i][j]!=-1) // return DP[i][j]; // // if(arr[i]==arr[j]) // DP[i][j]=Edit_distance(i+1,j-1,mid); // else // { // int first=Edit_distance(i, j-1,mid)+1; // int sec=Edit_distance(i+1, j, mid)+1; // int eq=Edit_distance(i+1,j-1 ,mid)+1; // DP[i][j] = min(first,sec,eq); // } // return DP[i][j]; //} // //int main() //{ // int t,counter=1; // cin>>t; // cin.ignore(); // // while(t--) // { // memset(DP,-1,sizeof(DP)); // getline(cin,arr); // cout<<"Case "<<counter++<<": "<<Edit_distance(0,arr.size()-1,arr.size()/2)<<endl; // } // return 0; //}
true
b316d3fbbdedebbe830d977956a83f0113cd2b48
C++
dfm066/Programming
/Codility/fib_frog.cpp
UTF-8
3,789
3.546875
4
[ "MIT" ]
permissive
// The Fibonacci sequence is defined using the following recursive formula: // F(0) = 0 // F(1) = 1 // F(M) = F(M - 1) + F(M - 2) if M >= 2 // A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N. // The leaves on the river are represented in an array A consisting of N integers. Consecutive elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s: // 0 represents a position without a leaf; // 1 represents a position containing a leaf. // The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf. // For example, consider array A such that: // A[0] = 0 // A[1] = 0 // A[2] = 0 // A[3] = 1 // A[4] = 1 // A[5] = 0 // A[6] = 1 // A[7] = 0 // A[8] = 0 // A[9] = 0 // A[10] = 0 // The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5. // Write a function: // def solution(A) // that, given an array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1. // For example, given: // A[0] = 0 // A[1] = 0 // A[2] = 0 // A[3] = 1 // A[4] = 1 // A[5] = 0 // A[6] = 1 // A[7] = 0 // A[8] = 0 // A[9] = 0 // A[10] = 0 // the function should return 3, as explained above. // Write an efficient algorithm for the following assumptions: // N is an integer within the range [0..100,000]; // each element of array A is an integer that can have one of the following values: 0, 1. #include <iostream> #include <vector> #include <algorithm> #include "Library/C++/utils.h" #include <assert.h> using namespace std; int solution(vector<int> &A); int main() { std::mt19937 gen; // Seed the engine with an unsigned int gen.seed(1); int N = 5000; vector<int> A(N); std::generate(A.begin(), A.end(), [&gen]() {return gen()&1;}); auto st = GET_HRTIME(); cout << solution(A) << endl; auto en = GET_HRTIME(); fmt::print("Execution Time : {}ms\n", ms(en-st).count()); return 0; } vector<int> fibs2n(int n) { vector<int> fibs; int f1 = 1, f2 = 1; while (f2 <= n) { fibs.emplace_back(f2); f2 = f1 + f2; f1 = f2 - f1; } return fibs; } int solution(vector<int> &A) { if (A.size() == 0) return 1; int N = A.size(); vector<int> fibs = fibs2n(N+1); vector<int> leaf_pos; leaf_pos.reserve(N/4); leaf_pos.emplace_back(-1); for (int i = 0; i < N; ++i) if(A[i] == 1) leaf_pos.emplace_back(i); leaf_pos.emplace_back(N); vector<int> dp(N+2, N+1); for (int i = leaf_pos.size()-2; i > 0; --i) dp[leaf_pos[i]] = N+1; dp[N] = 0; dp[N+1] = N + 1; for (int i = int(leaf_pos.size())-1; i > 0; --i) { if (dp[leaf_pos[i]] == N+1) continue; for (int j = 0; j < int(fibs.size()); ++j) { int pos = leaf_pos[i]-fibs[j]; if ((pos >= 0 && A[pos])) dp[pos] = min(dp[leaf_pos[i]] + 1, dp[pos]); if (pos == -1) dp[N+1] = min(dp[leaf_pos[i]] + 1, dp[N+1]); } } if (dp[N+1] == N+1) return -1; return dp[N+1]; }
true
81de3d1fa9753f5188f5b7832adb6e95759fd258
C++
Thuney/Jotunn
/Jotunn/Engine/src/Graphics/Mesh.cpp
UTF-8
1,727
2.53125
3
[]
no_license
#include "Graphics/Mesh.h" #include "Graphics/Shader.h" namespace Jotunn { MeshGeometry::MeshGeometry(std::unique_ptr<VertexArray>& vao, std::shared_ptr<VertexBuffer> vbo, const BufferLayout& vbo_layout, std::shared_ptr<IndexBuffer> ibo) { this->vao.reset(nullptr); this->vao.swap(vao); this->vbo = vbo; this->vbo_layout = vbo_layout; this->ibo = ibo; SetUpGraphics(); } MeshGeometry::MeshGeometry() { } MeshGeometry::~MeshGeometry() { } void MeshGeometry::Bind() { this->vao->Bind(); } void MeshGeometry::SetUpGeometry() { this->vao.reset(VertexArray::Create()); this->vbo.reset(VertexBuffer::Create(nullptr, 0)); this->ibo = nullptr; }; void MeshGeometry::SetUpGraphics() { this->vbo->SetLayout(this->vbo_layout); this->vao->AddVertexBuffer(this->vbo); this->vao->SetIndexBuffer(this->ibo); JOTUNN_CORE_TRACE("Graphics Set Up"); } //------------------------------------------------------------------------- MeshMaterial::MeshMaterial(std::unique_ptr<std::vector<Uniform*>>& material_uniforms) { this->uniforms.reset(nullptr); this->uniforms.swap(material_uniforms); } MeshMaterial::~MeshMaterial() { } void MeshMaterial::Bind(Shader& shader) { if (this->uniforms != nullptr) { for (Uniform* u : *(this->uniforms)) { if(u != nullptr) shader.UploadUniform(*u); } } } //------------------------------------------------------------------------- Mesh::Mesh(std::shared_ptr<MeshGeometry> geometry, std::shared_ptr<MeshMaterial> material) { this->geometry = geometry; this->material = material; } Mesh::~Mesh() { } void Mesh::Bind(Shader& shader) { this->geometry->Bind(); this->material->Bind(shader); } }
true
6f45d96b616ac190a10f64a09caf2cf2f980c9b8
C++
tomwillow/Credible-Spider
/src/Control/TRadioButtonGroup.cpp
UTF-8
1,011
2.546875
3
[]
no_license
#include "TRadioButtonGroup.h" void TRadioButtonGroup::LinkControl(HWND hDlg, std::vector<int> id_group, std::vector<int> values) { assert(uSet.empty()); assert(id_group.size() == values.size()); for (size_t i = 0; i < id_group.size(); ++i) { TCheckBox rb; uMap[id_group[i]] = { rb,values[i] }; uMap[id_group[i]].rb.LinkControl(hDlg, id_group[i]); uSet.insert(id_group[i]); } } int TRadioButtonGroup::ReceiveCommand(int id) { if (uSet.find(id) != uSet.end()) { for (auto& pr : uMap) { pr.second.rb.SetChecked(pr.first == id); } nowId = id; nowValue = uMap[id].value; return nowValue; } else return nowValue; } void TRadioButtonGroup::SetChecked(int id) { assert(uSet.find(id) != uSet.end()); ReceiveCommand(id); } int TRadioButtonGroup::GetValue() { return nowValue; } void TRadioButtonGroup::SetEnable(bool bEnable) { for (auto& pr : uMap) pr.second.rb.SetEnable(bEnable); } bool TRadioButtonGroup::GetEnable() { return (*uMap.begin()).second.rb.GetEnable(); }
true
c5205c86306dad9cadc4ae4b721a51fc76d7b0fb
C++
oklodhi/CS200
/Labs/Lab8/Part4.cpp
UTF-8
857
3.578125
4
[]
no_license
#include <iostream> #include <string> using namespace std; void displayStudents(string students[3]); void updateNames(string students[3]); int main() { string students[3]; int choice; bool done = false; while (!done) { displayStudents(students); cout << "\n\n1. UPDATE NAME \t 2. QUIT\n"; cin >> choice; switch (choice) { case 1: updateNames(students); break; case 2: done = true; break; } } } void displayStudents(string students[3]) { cout << "--------------------------\n"; cout << "STUDENT ID \t STUDNET NAME \n"; for (int i = 0; i < 3; i++) { cout << "\t" << i << "\t" << students[i] << endl; } } void updateNames(string students[3]) { int id; string* ptrStudent = nullptr; cout << "Student ID: "; cin >> id; ptrStudent = &students[id]; cout << "New Student Name: "; cin >> *ptrStudent; }
true
967655dc40fc95263e79055ebede9f46f902b9f9
C++
CSPshala/dangerzone
/DX11/source/messaging/IMessageListener.h
UTF-8
1,262
2.84375
3
[]
no_license
/////////////////////////////////////////////////////////////////////////// // File Name : "IMessageListener.h" // // Author Name : JC Ricks // // Purpose : Defines an interface for message listeners to recieve messages /////////////////////////////////////////////////////////////////////////// #ifndef _IMESSAGELISTENER_H #define _IMESSAGELISTENER_H //////////////////////////////////////// // INCLUDES //////////////////////////////////////// //////////////////////////////////////// // FORWARD DECLARATIONS //////////////////////////////////////// class IMessage; //////////////////////////////////////// // MISC //////////////////////////////////////// class IMessageListener { public: /********** Construct / Deconstruct / OP Overloads ************/ /********** Public Utility Functions ************/ virtual void RegisterForMessages() = 0; virtual void ReceiveMessage(IMessage* message) = 0; virtual void UnRegisterForMessages() = 0; /********** Public Accessors ************/ /********** Public Mutators ************/ private: /********** Private Members ************/ /********** Private Accessors ************/ /********** Private Mutators ************/ /********** Private Utility Functions ************/ }; #endif
true
8fe684f47b1726c9531cc13823eea23ea25cb2be
C++
softwaytostars/LearnChess
/infosconfiguration.h
UTF-8
2,706
2.625
3
[]
no_license
#ifndef INFOSCONFIGURATION_H #define INFOSCONFIGURATION_H #include <QString> #include "TypeDemo.hpp" #include "Types/TypePreferences.h" #include "Types/TypeLangage.h" class InfosConfiguration { public: static InfosConfiguration* instance (); static void kill (); void setLastFileNameForDemo (const QString& aFileName, eTypeInitiation aTypeInitiation); QString getLastFileNameForDemo(eTypeInitiation aTypeInitiation) const; void setLastFileNameForTrainingMove (const QString& aFileName, eTypeInitiation aTypeInitiation); QString getLastFileNameForTrainingMove(eTypeInitiation aTypeInitiation) const; void setLastDirForPGNFiles (const QString& aDir) {_LastDirForPGNFiles = aDir;} const QString& getLastDirForPGNFiles() const {return _LastDirForPGNFiles;} void setLastTypePieces (ePreferencesPieces aPrefPieces) {_PreferencesPieces = (int) aPrefPieces;} ePreferencesPieces getLastTypePieces() const { return (ePreferencesPieces) _PreferencesPieces;} void setLastStyleApp (ePreferenceStyle aPrefStyle) {_PreferencesStyle = (int) aPrefStyle;} ePreferenceStyle getLastStyleApp() const { return (ePreferenceStyle) _PreferencesStyle;} void setLanguage (eLangue aLangue) {_PreferencesLanguage = (int) aLangue;} QString getLastLanguageAppToStr() const; const tMapPrefLangueName& get_MapPrefLangueName () {return _MapLangueToStr;} void setModeConfigurateur (bool aModeConfigurateur) {_ModeConfigurateur = aModeConfigurateur;} bool getModeConfigurateur () const {return _ModeConfigurateur;} private: InfosConfiguration(); static InfosConfiguration* _instance; QString _LastFileNameForDemoPiecesMove; /**< Nom fichier pour la demo des Pieces moves */ QString _FileConfigName; QString _LastFileNameForTrainingPiecesMove;/**< Nom fichier pour le training des Pieces moves */ QString _LastDirForPGNFiles; QString _LastFileNameForDemoSpecialMoves; QString _LastFileNameForTrainingSpecialMoves; QString _LastFileNameForDemoPatternsMat; QString _LastFileNameForTrainingPatternsMat; QString _LastFileNameForDemoTactics; QString _LastFileNameForTrainingTactics; int _PreferencesPieces; int _PreferencesStyle; int _PreferencesLanguage; tMapPrefLangueName _MapLangueToStr; /**< map entre le enum langage et sa valeur string */ bool _ModeConfigurateur;//sera pas sauve dans fichier void ReadString (std::ifstream &afilestream, QString &aValue); void WriteString (std::ofstream& afilestream, const QString& aValue); void ReadInt (std::ifstream &afilestream, int &aValue); void WriteInt (std::ofstream& afilestream, int aValue); }; #endif // INFOSCONFIGURATION_H
true
07b8cf911112bd62078d71ec916260a86775c873
C++
saifpathan/cpp-programs
/src/10_cout_cin/6_bankdetails.cpp
UTF-8
1,339
3.40625
3
[]
no_license
using namespace std; #include<iostream> #include<string.h> class bankdetails { int accountno; char name[20]; double deposit; char branch[20]; public: bankdetails() { this->accountno = 100; strcpy(this->name, "not given"); this->deposit = 15454.55; strcpy(this->branch, "Pune"); } bankdetails(int ac, char* nm, double d, char*b) { this->accountno = ac; strcpy(this->name, nm); this->deposit = d; strcpy(this->branch, b); } void setAccountno(int ac) { this->accountno = ac; } void setName(char* nm) { strcpy(this->name, nm); } void setDeposit(double d) { this->deposit = d; } void setBranch(char*b) { strcpy(this->branch, b); } int getAccountno() { return this->accountno; } char* getName() { return this->name; } double getDeposit() { return this->deposit; } char* getBranch() { return this->branch; } void display() { cout<<"\nBank deposit details=(using display())"; cout<<"\nAccount no. is="<<this->accountno; cout<<"\nName is="<<this->name; cout<<"\nDeposit Amount is="<<this->deposit; cout<<"\nBranch name is="<<this->branch; cout<<"\n\n"; } }; int main() { bankdetails*ptr; ptr = new bankdetails(); ptr->display(); delete ptr; bankdetails*p1; p1 = new bankdetails(62498, "Saif", 20000, "Omerga"); p1->display(); delete p1; cout<<"\n\n"; }
true
5ac576dbf1723ad8838572fdb77b0279e479cb1b
C++
rypcer/OpenglFootballGame
/ball.cpp
UTF-8
2,991
2.515625
3
[]
no_license
#include "ball.h" //---------This is used for the football ball-------// GLUquadricObj* quadricFootball; void ball::drawBall() { glPushMatrix(); glFrontFace(GL_CCW); glTranslatef(x, y, z); glRotatef(angle,1, 0, 0); // Create and texture the ball glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureID); // glDisable(GL_LIGHTING); glColor3f(0.5, 0.5, 0.5); quadricFootball = gluNewQuadric(); gluQuadricDrawStyle(quadricFootball, GLU_FILL); gluQuadricNormals(quadricFootball, GLU_SMOOTH); gluQuadricOrientation(quadricFootball, GLU_OUTSIDE); gluQuadricTexture(quadricFootball, GL_TRUE); gluSphere(quadricFootball, r, 50, 35); glDisable(GL_TEXTURE_2D); glPopMatrix(); } void ball::updateBall(std::vector<target> &targets,int &score,int &shotsLeft ) { // Update position if (shot) { // Reset velocity to beggining if (!ini) { vX = vXR; vY = vYR; ini = true; angleAmount = 7; shotsLeft--; } // Move Ball z -= 15; x += vX; y += vY; // Apply Gravity vY-=0.25f; // Apply rotation to ball and decrease rotation Amount angle+=angleAmount; if(angleAmount > 0) angleAmount-=0.1f; } // If Ball outside or Hit target Reset if (z <= -480) { z = startZ; x = startX; y = startY; shot = false; ini = false; } // If ball on ground if (y <= 25) y = 25; // Check if collided with any targets // //for (target t : targets) //{ // float dx = x - t.getX(); // float dy = y - t.getY(); // float distance = sqrt(dx * dx + dy * dy); // // Checks in x y for circle collision and for z if it is at the wall // if (distance < r + t.getR() && z <= -470 && t.getHit()==false) { // t.setHit(true); // score += t.getPoints(); // } //} for (int i = 0 ; i<targets.size(); i++) { float dx = x - targets[i].getX(); float dy = y - targets[i].getY(); float distance = sqrt(dx * dx + dy * dy); // Checks in x y for circle collision and for z if it is at the wall if (distance < r + targets[i].getR() && z <= -470 && targets[i].getHit() == false) { targets[i].setHit(true); score += targets[i].getPoints(); } } } void ball::resetPos() { x = startX; y = startY; z = startZ; vXR = 0; vYR = 0; } GLfloat ball::getX() { return x; } GLfloat ball::getY() { return y; } GLfloat ball::getZ() { return z; } void ball::setStartX(GLfloat _x) { startX = _x; } void ball::setStartY(GLfloat _y) { startY = _y; } void ball::setStartZ(GLfloat _z) { startZ = _z; } void ball::setR(GLfloat _r) { r = _r; } void ball::setShot(GLfloat _shot) { shot = _shot; } bool ball::getShot() { return shot; } void ball::setVX(GLfloat amount, bool addSub) { (!addSub) ? vXR -= amount : vXR += amount; } void ball::setVY(GLfloat amount, bool addSub) { (!addSub) ? vYR -= amount : vYR += amount;}
true
6f97072f5734741c35d57bb1622b1a66764df29b
C++
mornydew/thor
/src/slam.cpp
UTF-8
2,308
2.5625
3
[ "MIT", "Apache-2.0", "curl" ]
permissive
// ************************************ // Copyrights by Jin Fagang // 1/15/19-15-11 // slam // jinfagang19@gmail.com // CTI Robotics // ************************************ // // Created by jintain on 1/15/19. // #ifdef USE_OPENCV #include "include/slam.h" using namespace thor; void slam::getKeyPointsColor(const cv::Mat &img1, const cv::Mat &img2, vector <cv::KeyPoint> &kp1, vector <cv::KeyPoint> &kp2) { // calculate keypoints /** * "FAST" – FastFeatureDetector "STAR" – StarFeatureDetector "SIFT" – SIFT (nonfree module) "SURF" – SURF (nonfree module) "ORB" – ORB "MSER" – MSER "GFTT" – GoodFeaturesToTrackDetector "HARRIS" – GoodFeaturesToTrackDetector with Harris detector enabled "Dense" – DenseFeatureDetector "SimpleBlob" – SimpleBlobDetector */ cerr << "this function not implemented, using getGoodMatchesColor() directly.\n"; } void slam::getGoodMatchesColor(const cv::Mat &img1, const cv::Mat &img2, vector<cv::DMatch> &good_matches, vector <cv::KeyPoint> &kp1, vector <cv::KeyPoint> &kp2, bool show) { // ORB is the best feature extractor for now, but not work with (Scale-invariant) cv::Ptr<cv::ORB> detector = cv::ORB::create(); cv::Ptr<cv::FlannBasedMatcher> matcher; vector<cv::DMatch> all_matches; cv::Mat descriptor1, descriptor2; detector->detectAndCompute(img1, cv::Mat(), kp1, descriptor1); detector->detectAndCompute(img2, cv::Mat(), kp2, descriptor2); matcher->match(descriptor1, descriptor2, all_matches); if(descriptor1.type()!=CV_32F) { descriptor1.convertTo(descriptor1, CV_32F); } if(descriptor2.type()!=CV_32F) { descriptor2.convertTo(descriptor2, CV_32F); } // filter good matches double min_dist = 9999; for (int i = 0; i < all_matches.size(); ++i) { if ( all_matches[i].distance < min_dist ){ min_dist = all_matches[i].distance; } } for (int j = 0; j < all_matches.size(); ++j) { if (all_matches[j].distance < 4*min_dist) { good_matches.push_back(all_matches[j]); } } // now we get all matches if (show) { cv::Mat match_res; cv::drawMatches(img1, kp1, img2, kp2, good_matches, match_res); cv::imshow( "good matches", match_res); cv::waitKey(0); } } #endif
true
df63b0d599bd1b04de3b0965ec4b4c9fa190752a
C++
MateusAvilla/Meus-Projetos-Tecnico
/2º Semestre/Programação de Sistemas/Dev C++ Projects/Estrutura Seletiva Múltipla (Switch)/3. Lanchonete.cpp
ISO-8859-1
1,261
2.6875
3
[ "MIT" ]
permissive
#include <stdio.h> #include <iostream> #include <conio.h> #include <string.h> #include <locale.h> using namespace std; int main() { setlocale(LC_ALL,"Portuguese"); int codigo, quantidade; double preco; cout<<"\n Digite o cdigo do lanche desejado: "; cin>> codigo; cout<<"\n Digite a quantidade desejada: "; cin>> quantidade; switch (codigo) { case 100 : { preco = quantidade * 1.20; cout<< "\n O preo a ser pago ser de R$" << preco; break; } case 101 : { preco = quantidade * 1.30; cout<< "\n O preo a ser pago ser de R$" << preco; break; } case 102 : { preco = quantidade * 1.50; cout<< "\n O preo a ser pago ser de R$" << preco; break; } case 103 : { preco = quantidade * 1.20; cout<< "\n O preo a ser pago ser de R$" << preco; break; } case 104 : { preco = quantidade * 1.30; cout<< "\n O preo a ser pago ser de R$" << preco; break; } case 105 : { preco = quantidade * 1.00; cout<< "\n O preo a ser pago ser de R$" << preco; break; } } getch(); //ou system("pause"); }
true
2a15df03a5795dc79058f701d268a535774714d6
C++
musou1500/tt
/ford_folkerson.hh
UTF-8
1,284
2.953125
3
[]
no_license
#ifndef FORD_FOLKERSON_HH #define FORD_FOLKERSON_HH #include <vector> namespace tt { struct MinCostEdge { int to, cap, rev; MinCostEdge(int to, int cap, int rev) : to(to), cap(cap), rev(rev) {} }; void AddEdge(std::vector<std::vector<MinCostEdge>> &g, int from, int to, int cap) { int idx = g[to].size(), rev_idx = g[from].size(); g[from].emplace_back(to, cap, idx); g[to].emplace_back(from, 0, rev_idx); } class FordFolkerson { std::vector<std::vector<MinCostEdge>> g_; std::vector<bool> used_; int DFS(int v, int t, int f) { if (v == t) { return f; } used_[v] = true; for (auto &edge : g_[v]) { if (used_[edge.to] || edge.cap <= 0) { continue; } int d = DFS(edge.to, t, f < 0 || f > edge.cap ? edge.cap : f); if (d > 0) { edge.cap -= d; g_[edge.to][edge.rev].cap += d; return d; } } return 0; } public: FordFolkerson(std::vector<std::vector<MinCostEdge>> &g) : g_(g), used_(g_.size()) {} int operator()(int s, int t) { int flow = 0, f; while (true) { fill(used_.begin(), used_.end(), false); f = DFS(s, t, -1); if (f == 0) { return flow; } flow += f; } } }; } // namespace tt #endif
true
19ca25dc58f1124e266e8f3079ebf0545cc99c98
C++
ezefranca/estudos-cpp
/Fibonnaci/Fibonnaci/main.cpp
UTF-8
651
3.1875
3
[]
no_license
// // main.cpp // Fibonnaci // // Created by Ezequiel on 14/04/17. // Copyright © 2017 Ezequiel. All rights reserved. // #include <iostream> int main(int argc, const char * argv[]) { int i, input, first=0, second=1, next; std::cout << "Fibonnaci C++ 🙃 \n"; first=0; second=1; std::cout<<"Digite a quantidade de numeros: "; std::cin>>input; std::cout<<"Fibonacci 📣: \n"; for(i = 0; i < input; i++) { std::cout<<first; next = first + second; first = second; second = next; std::cout<<"\n"; } return 0; }
true
2aeae92aa92a2561355b70537c375db161c8c728
C++
pepborrell/AP2
/contenidors/easy.cc
UTF-8
1,218
3.265625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <set> #include <algorithm> using namespace std; vector<string> settovec(const set<string>& s){ int n = s.size(); vector<string> v(n); auto it = s.begin(); for (int i=0; i<n; ++i){ v[i] = *it; ++it; } return v; } bool comp(const string& a, const string& b){ int n = a.size(), m = b.size(); if (n != m) return n < m; else { return a < b; } } void move_string(const string& p, set<string>& s, set<string>& was_s) { if (s.find(p) == s.end()) { s.insert(p); was_s.erase(p); } else { s.erase(p); was_s.insert(p); } } void print_output(int i, const set<string>& s, const set<string>& was_s) { cout << "GAME #" << i << endl; cout << "HAS:" << endl; for (const string& x : s) { cout << x << endl; } cout << endl << "HAD:" << endl; vector<string> v = settovec(was_s); sort(v.begin(), v.end(), comp); for (const string& x : v) { cout << x << endl; } } int main() { string p; int i = 1; while (p != "QUIT") { set<string> s; set<string> was_s; cin >> p; while (p != "END" and p != "QUIT") { move_string(p, s, was_s); cin >> p; } print_output(i, s, was_s); ++i; if(p != "QUIT") cout << endl; } }
true
12e9322b06e10c5a02dad29baeeb3366b8e2a957
C++
xfcherish/codeforces
/362/C.cpp
UTF-8
3,354
2.78125
3
[]
no_license
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <queue> #include <vector> #include <map> using namespace std; typedef long long LL; map<pair<LL,LL>,LL> m; vector<LL> get_root(LL u) { vector<LL> res; while( u != 1) { // cout << "u = " << u << endl; res.push_back(u); u /= 2; } res.push_back(1LL); reverse(res.begin(), res.end()); // cout << " u = " << u << endl; // for(int i = 0; i < res.size(); i++) // cout << res[i] << " "; // cout << endl; return res; } vector<LL> merge_path(vector<LL> path1, vector<LL> path2) { vector<LL> res; LL gca; for(int i = 0, j = 0; i < path1.size() && j < path2.size();) { if(path1[i] == path2[j]) { gca = path1[i]; i++; j++; } else break; } // cout << "gca = " << gca << endl; for(int i = path1.size()-1; i >= 0; i--) { res.push_back(path1[i]); if(path1[i] == gca) break; } bool start = false; for(int i = 0 ; i < path2.size(); i++) { if(start) res.push_back(path2[i]); if(path2[i] == gca) { start = true; } } // cout << "common_path :" << endl; // for(int i = 0; i < res.size(); i++) // cout << res[i] << " "; // cout << endl; return res; } int main() { // freopen("test.in","r",stdin); // freopen("test.out","w",stdout); LL q,u,v,w; int type; cin >> q; while(q--) { cin >> type; if(type == 1) { cin >> u >> v >> w; vector<LL> path1,path2,common_path; path1 = get_root(u); path2 = get_root(v); common_path = merge_path(path1,path2); for(int i = 0; i+1 < common_path.size(); i++) { LL tmp_a = common_path[i]; LL tmp_b = common_path[i+1]; m[pair<LL,LL> (tmp_a,tmp_b)] += w; m[pair<LL,LL> (tmp_b,tmp_a)] += w; } // cout << "tpye = 1" << endl; // cout << " u = " << u << " v = " << v << endl; // cout << "path 1 :" << endl; // for(int i = 0 ; i < path1.size(); i++) { // cout << path1[i] << " "; // } // cout << endl; // cout << "path 2 :" << endl; // for(int i = 0 ; i < path2.size(); i++) { // cout << path2[i] << " "; // } // cout << endl; // cout << "common_path :" << endl; // for(int i = 0; i < common_path.size(); i++) { // cout << common_path[i] << " "; // } // cout << endl << endl << endl; } else if(type == 2) { cin >> u >> v; vector<LL> path1,path2,common_path; path1 = get_root(u); path2 = get_root(v); common_path = merge_path(path1,path2); LL ans = 0; for(int i = 0; i+1 < common_path.size(); i++) { LL tmp_a = common_path[i]; LL tmp_b = common_path[i+1]; // cout << "m[" << tmp_a << "," << tmp_b << "]=" // << m[pair<LL,LL> (tmp_a,tmp_b)] << endl; ans += m[pair<LL,LL> (tmp_a,tmp_b)]; } // cout << "tpye = 2" << endl; // cout << " u = " << u << " v = " << v << endl; // cout << "path 1 :" << endl; // for(int i = 0 ; i < path1.size(); i++) { // cout << path1[i] << " "; // } // cout << endl; // cout << "path 2 :" << endl; // for(int i = 0 ; i < path2.size(); i++) { // cout << path2[i] << " "; // } // cout << endl; // cout << "common_path :" << endl; // for(int i = 0; i < common_path.size(); i++) { // cout << common_path[i] << " "; // } // cout << endl; // cout << "ans = " << ans << endl; // cout << endl << endl << endl; cout << ans << endl; } } return 0; }
true
c358f2ef5b328397964dd358d509537b0cdaaeec
C++
ttyang/sandbox
/sandbox/mp_math/libs/mp_math/test/unbounded/signed/random.cpp
UTF-8
2,157
2.71875
3
[ "BSL-1.0" ]
permissive
// Copyright Kevin Sopp 2008 - 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/test/unit_test.hpp> #include "prerequisite.hpp" BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer1, int_type, IntTypes) { const int_type min(0), max(128); boost::mp_math::uniform_integer<int_type> g(min, max); boost::mt19937 e; for (int i = 0; i < 128; ++i) { const int_type x = g(e); BOOST_REQUIRE_GE(x, min); BOOST_REQUIRE_LE(x, max); } } BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer2, int_type, IntTypes) { const int_type min(11), max("26546549"); boost::mp_math::uniform_integer<int_type> g(min, max); boost::mt19937 e; for (int i = 0; i < 1000; ++i) { const int_type x = g(e); BOOST_REQUIRE_GE(x, min); BOOST_REQUIRE_LE(x, max); } } BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer_bits1, int_type, IntTypes) { BOOST_CHECK_EQUAL( boost::mp_math::uniform_integer_bits<int_type>::has_fixed_range, false); } BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer_bits2, int_type, IntTypes) { boost::mp_math::uniform_integer_bits<int_type> g(512); boost::mt19937 e; const int_type x = g(e); BOOST_CHECK_EQUAL(x.precision(), 512U); } BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer_bits3, int_type, IntTypes) { boost::mp_math::uniform_integer_bits<int_type> g(71); boost::mt19937 e; const int_type x = g(e); BOOST_CHECK_EQUAL(x.precision(), 71U); } BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer_bits4, int_type, IntTypes) { boost::mp_math::uniform_integer_bits<int_type> g(1001); boost::mt19937 e; const int_type x = g(e); BOOST_CHECK_EQUAL(x.precision(), 1001U); } BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer_bits5, int_type, IntTypes) { boost::mp_math::uniform_integer_bits<int_type> g(8); BOOST_CHECK_EQUAL(g.min(), 128U); BOOST_CHECK_EQUAL(g.max(), 255U); } BOOST_AUTO_TEST_CASE_TEMPLATE(uniform_integer_bits6, int_type, IntTypes) { boost::mp_math::uniform_integer_bits<int_type> g(11); BOOST_CHECK_EQUAL(g.min(), 1024U); BOOST_CHECK_EQUAL(g.max(), 2047U); }
true
24a84e0318d472723c46de796444fb5568dc900c
C++
gerstle/LightWalker
/tests/controller/sketch_jan25a/sketch_jan25a.ino
UTF-8
1,709
2.75
3
[ "Apache-2.0" ]
permissive
#include <SPI.h> #include <TCL.h> const int STR_LENGTH = 25; const int STR_COUNT = 2; const int PIXEL_COUNT = STR_LENGTH * STR_COUNT; unsigned long currentMillis; long previousMillis = 0; long interval = 30; const int PATTERN_COUNT = 3; int pattern_index = 0; int pixel_index = 0; byte colorpattern[PATTERN_COUNT][3]; void setup() { Serial.begin(115200); // <gerstle> green colorpattern[0][0] = 0x00; colorpattern[0][1] = 0xff; colorpattern[0][2] = 0x00; // <gerstle> blue colorpattern[1][0] = 0x00; colorpattern[1][1] = 0x00; colorpattern[1][2] = 0xff; // <gerstle> purple colorpattern[2][0] = 0x80; colorpattern[2][1] = 0x00; colorpattern[2][2] = 0x80; TCL.begin(); TCL.sendEmptyFrame(); // <gerstle> blank out everything for (int i = 0; i < (STR_LENGTH * STR_COUNT); i++) { TCL.sendColor(0x00,0x00,0x00); } TCL.sendEmptyFrame(); } void loop() { String message = "top: pattern index: "; message = message + pattern_index + " pixel index: " + pixel_index; Serial.println(message); currentMillis = millis(); if ((currentMillis - previousMillis) > interval) { Serial.println("--------------------> setting light"); previousMillis = currentMillis; set_light(); } Serial.println("bottom"); } void set_light() { if (pixel_index >= PIXEL_COUNT) { TCL.sendEmptyFrame(); pixel_index = 0; pattern_index++; if (pattern_index >= PATTERN_COUNT) pattern_index = 0; } TCL.sendColor(colorpattern[pattern_index][0], colorpattern[pattern_index][1], colorpattern[pattern_index][2]); pixel_index++; }
true
0053c5426f4c4b2e87f53908fd706ca1999cb706
C++
DhaliwalX/grok
/src/vm/codegen.cc
UTF-8
779
2.515625
3
[ "Apache-2.0" ]
permissive
#include "vm/codegen.h" namespace grok { namespace vm { CodeGenerator::CodeGenerator() : IR{}, Builder{} { Builder = InstructionBuilder::CreateBuilder(); } void CodeGenerator::Generate(grok::parser::Expression *AST) { Builder->CreateBlock(); if (Builder->InsideFunction()) { auto nop = InstructionBuilder::Create<Instructions::noop>(); Builder->AddInstruction(std::move(nop)); } AST->emit(Builder); if (Builder->InsideFunction()) { auto ret = InstructionBuilder::Create<Instructions::ret>(); Builder->AddInstruction(std::move(ret)); } Builder->EndBlock(); Builder->Finalize(); IR = Builder->ReleaseInstructionList(); } std::shared_ptr<InstructionList> CodeGenerator::GetIR() { return IR; } } }
true
54d71303ca196f3a6e36cc87b504ee139170bf4f
C++
MasterHoracio/COJ-Solutions
/2803-AnotherSimpleProblemII.cpp
UTF-8
954
3.140625
3
[]
no_license
#include <iostream> #include <string> #define M 10 using namespace std; char cuadrado[M][M]; bool check(int i, int j, int n){ bool bien = true; if(j + 1 < n)//derecha if(cuadrado[i][j] == cuadrado[i][j + 1]) return false; if(j - 1 >= 0)//izquierda if(cuadrado[i][j] == cuadrado[i][j - 1]) return false; if(i + 1 < n)//abajo if(cuadrado[i][j] == cuadrado[i + 1][j]) return false; if(i - 1 >= 0)//arriba if(cuadrado[i][j] == cuadrado[i - 1][j]) return false; return true; } int main(){ string str; int TC, n; bool cont; cin >> TC; while(TC--){ cin >> n; cont = true; for(int i = 0; i < n; i++){ cin >> str; for(int j = 0; j < n; j++) cuadrado[i][j] = str[j]; } for(int i = 0; i < n && cont; i++) for(int j = 0; j < n && cont; j++) cont = check(i, j, n); (cont) ? cout << "YES" << endl : cout << "NO" << endl; } return 0; }
true
1649a26fac81d2d4d761bb97a7c5e63688cf76e7
C++
AditiB007/final-project-tdang018_abehe002_jnaje010
/abstractFactory/iEquipment.cpp
UTF-8
184
2.546875
3
[]
no_license
#include "iEquipment.h" IEquipment::IEquipment(){ this->name = ""; } void IEquipment::setName(string str){ this->name = str; } string IEquipment::getName(){ return this->name; }
true
1541c31b03461d1ca436ab1e29f8907548938f16
C++
truszkowski/studies
/inzynieria-algorytmiczna/punkty2.cpp
UTF-8
2,510
2.796875
3
[]
no_license
#include <cstdio> #include <cmath> #include <algorithm> using namespace std; const long MAX = 100000l; __inline__ long long mul(long long a, long long b) { return a*b; } __inline__ long long sq(long long a) { return a*a; } long ch[MAX+1]; pair<long,long> v[MAX]; long chn = 0, vn = 0; long long d = 0; // Kierunek long long direction(long i, long j, long k) { long long det = mul(v[i].first, v[j].second) + mul(v[k].first, v[i].second) + mul(v[j].first, v[k].second) - mul(v[i].first, v[k].second) - mul(v[k].first, v[j].second) - mul(v[j].first, v[i].second); return det; } void convex_hull(void) { // Sortujemy po x-ach. sort(v,v+vn); // Poczatkowo mamy 2 pierwsze punkty z v w otoczce. chn = 2; ch[0] = 0; ch[1] = 1; // Minimalna wielkosc otoczki - aby nie wywalac zbyt duzo z niej pktow long guard = 1; // Dokladamy kolejne punkty do otoczki, od 0->vn-1 for (long i = 2; i < vn; ++i) { while (chn > guard && direction(ch[chn-2], ch[chn-1], i) <= 0) --chn; // na prawo ch[chn++] = i; // na lewo } guard = chn; // W druga strone vn-1->0 for (long i = vn-2; i >= 0; --i) { while (chn > guard && direction(ch[chn-2], ch[chn-1], i) <= 0) --chn; // na prawo ch[chn++] = i; // na lewo } --chn; } long long dist(long i, long j) { return sq(v[i].first-v[j].first)+sq(v[i].second-v[j].second); } double dist(long a, long b, long i) { double A, B, C;// Ax+By+C=0 // A = v[a].second - v[b].second; B = v[b].first - v[a].first; C = mul(v[a].first, v[b].second) - mul(v[b].first, v[a].second); return abs(A*v[i].first + B*v[i].second + C) / sqrt(A*A + B*B); } void find_width(void) { d = 0; long long nd1 = 0, nd2 = 0; // Dla kazdej krawedzi z otoczki szukamy puntu najdalej od niej. for (long i = 0, x = 1; i < chn; ++i) { double ld = 0, tmp = -1; // Bedziemy szli po punktach z otoczki caly czas w te sama strone az // dojdziemy do punktu najbardziej oddalonego. for (long j = x; j < chn; ++j) { if ((nd1 = dist(ch[i], ch[j])) > d) d = nd1; if ((nd2 = dist(ch[i+1], ch[j])) > d) d = nd2; if ((tmp = dist(ch[i], ch[i+1], ch[j])) < ld) break; ld = tmp; x = j; } } } int main(void) { scanf("%ld", &vn); for (long i = 0; i < vn; ++i) scanf("%ld%ld", &v[i].first, &v[i].second); // Szukamy otoczki wypuklej, tylko punkty lezace na niej moga byc // najbardziej odleglymi. convex_hull(); // Szukamy po otoczce najwiekszej srednicy - czyli najbardziej // odleglych 2 punktow. find_width(); printf("%lld\n", d); return 0; }
true
dab28cfd763b4ac8fee6a84d7bf2966cee8d39a2
C++
animeshkarmakarAK/Computer-Programming
/LightOj/Lightoj1113Discover_the_web.cpp
UTF-8
1,367
2.875
3
[]
no_license
/* solved by myself -- solved complete */ #include<bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int t; cin>>t; for(int tc = 1; tc <= t; tc++){ printf("Case %d:\n",tc); string command; stack<string>forward,back; string curr_page = "http://www.lightoj.com/"; bool quit = false; while(quit == false){ cin>>command; if(command == "VISIT"){ string url; cin>>url; back.push(curr_page); curr_page = url; cout<<curr_page<<endl; while(!forward.empty()){ forward.pop(); } } else if(command == "BACK"){ if(back.empty()) cout<<"Ignored"<<endl; else{ forward.push(curr_page); curr_page = back.top(); cout<<curr_page<<endl; back.pop(); } } else if(command == "FORWARD"){ if(forward.empty()) cout<<"Ignored"<<endl; else { back.push(curr_page); curr_page = forward.top(); cout<<curr_page<<endl; forward.pop(); } } else quit = true; } } return 0; }
true