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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
606682dd474e2486ddae44750277596e1474b238 | C++ | cho-jae-seong/Algorithm | /Tallest_tower.cpp | UTF-8 | 846 | 2.71875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
struct Brick {
int s, h, w;
Brick(int a, int b, int c) {
s = a;
h = b;
w = c;
}
bool operator<(const Brick& b)const {
return s > b.s;
}
};
int main(void) {
int n, a, b, c, max_h = 0, res = 0;
scanf("%d", &n);
vector<Brick>Bricks;
vector<int>dp(n, 0);
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &a, &b, &c);
Bricks.push_back(Brick(a, b, c));
}
sort(Bricks.begin(), Bricks.end());
dp[0] = Bricks[0].h;
res = dp[0];
for (int i = 1; i < n; i++) {
max_h=0;
for (int j = i - 1; j >= 0; j--) {
if (Bricks[j].w > Bricks[i].w&& dp[j] > max_h) {
max_h = dp[j];
}
}
dp[i] = max_h + Bricks[i].h;
res = max(res, dp[i]);
}
printf("%d\n", res);
return 0;
} | true |
90e602a00d4bc0825fbb63aba15a80c43311a789 | C++ | SMara99/Labor2 | /complex.cpp | UTF-8 | 2,904 | 3.53125 | 4 | [] | no_license | #include "complex.h"
#include <math.h>
complex::complex() {
//constructor fara parametri
a = 0;
b = 0;
}
complex::complex(double a_value, double b_value) {
//constructor cu parametri
a = a_value;
b = b_value;
}
complex::~complex(){
//destructor
}
double complex::get_a() const {
// returneaza partea reala
return a;
}
double complex::get_b() const {
// returneaza partea imaginara
return b;
}
void complex::set_a(double a_value) {
// ocuparea partii reale
// param : a_value
a = a_value;
}
void complex::set_b(double b_value) {
// ocuparea partii imaginare
// param : b_value
b = b_value;
}
//arithmetic "+"
complex complex::add(complex other) {
// returneaza suma a doua numere complexe
complex auxiliar;
auxiliar.set_a(this->get_a() + other.get_a());
auxiliar.set_b(this->get_b() + other.get_b());
return auxiliar;
}
//arithmetic "*"
complex complex::mul(complex other) {
// returneaza inmultirea a doua numere complexe
complex auxiliar;
auxiliar.set_a(this->get_a() * other.get_a() - this->get_b() * other.get_b());
auxiliar.set_b(this->get_b() * other.get_b() + this->get_a() * other.get_b());
return auxiliar;
}
//arithmetic "/"
complex complex::quot(complex other) {
// returneaza impartirea a doua numere complexe
complex auxiliar;
double div = this->get_b() * this->get_b() + other.get_b() * other.get_b();
auxiliar.set_a(
(this->get_a() * other.get_a() + this->get_b() * other.get_b()) / div);
auxiliar.set_b(
(this->get_b() * other.get_b() - this->get_a() * other.get_b()) / div);
return auxiliar;
}
//absoluten Betrag
double complex::abs() {
// returneaza modulul unui numar complex
double result;
result =
sqrt(this->get_a() * this->get_a() + this->get_b() * this->get_b());
return result;
}
complex::complexa(double real, double imaginar)
//constructor
{
a = real;
b = imaginar;
}
double complex::getreal() const
//returns the real part of the number
{
return a;
}
double complex::getimg() const
//returns the imaginary part of the number
{
return b;
}
void complex::show_compl()
//returns a complex number
{
double r, i;
r = this->getreal();
i = this->getimg();
if (i == 0)
cout << "The number " << r << " is not a complex number";
else
if (i < 0)
cout << r << " " << i << " " << "i";
else
cout << r << " + " << i << "i";
}
void complex::show_exp()
//displays the exponential form of a complex number
{
int t;
double r, i;
r = this->getreal();
i = this->getimg();
t = atan2(i, r);
cout << r << " * e^" << "(" << t << " * i)";
}
void complex::compute_polar()
//displays the polar form of a complex number
{
int t;
double r, i;
r = this->getreal();
i = this->getimg();
t = atan2(i, r);
cout << "z = " << r << " * (cos" << t << " + isin" << t << ")";
}
| true |
3efe100ea7b006d6fdc24736636bf565c8fa3028 | C++ | ulinka/tbcnn-attention | /github_cpp/21/83.cpp | UTF-8 | 3,168 | 3.609375 | 4 | [] | no_license |
#include <iostream>
using namespace std;
void SelectionSort(int arr[], int size);
int SelectionSortPartB(int arr[], int arrSize, int sortSectionSize);
double median(int arr[], int size);
void printArray(int arr[], int size);
int main(int argc, const char * argv[]) {
int selectionSortArrPartA[10] = {4, 6, 8, 15, 20, 22, 10, 3, 9, 2};
int selectionSortArrPartB[10] = {4, 6, 8, 15, 20, 22, 10, 3, 9, 2};
int selectionSortArrPartC[7] = {22, 6, 15, 8, 20, 4, -9};
int userInputSize;
double getMedian;
cout << "Selection sort Part A unsorted\n";
printArray(selectionSortArrPartA, 10);
SelectionSort(selectionSortArrPartA, 10);
cout << "Selection sort Part A sorted\n";
printArray(selectionSortArrPartA, 10);
do{
cout << "Enter an integer >= 0: ";
cin >> userInputSize;
cin.clear();
cin.ignore(10000, '\n');
if(userInputSize <= 0)
cout << "\nBad Input (try again)\n";
}while(userInputSize <= 0);
cout << "Selection sort Part B unsorted\n";
printArray(selectionSortArrPartB, 10);
userInputSize = SelectionSortPartB(selectionSortArrPartB, 10, userInputSize);
cout << "Selection sort Part B sorted\n";
printArray(selectionSortArrPartB, userInputSize);
cout << "Part C array unsorted: \n";
printArray(selectionSortArrPartC, 7);
getMedian = median(selectionSortArrPartC, 7);
cout << "Median for part C array is: \n";
cout << getMedian << endl << endl;
return 0;
}
void SelectionSort(int arr[], int size)
{
for(int i = 0; i < size; i++)
{
int swapIndex = i;
for(int j = i + 1; j < size; j++)
{
if(arr[j] < arr[swapIndex])
swapIndex = j;
}
if(swapIndex != i)
{
int temp = arr[swapIndex];
arr[swapIndex] = arr[i];
arr[i] = temp;
}
}
}
int SelectionSortPartB(int arr[], int arrSize, int sortSectionSize)
{
if(sortSectionSize > arrSize || sortSectionSize < 0)
{
cout << "K is out of bounds. The whole array will be sorted.\n\n";
sortSectionSize = arrSize;
}
for(int i = 0; i < sortSectionSize; i++)
{
int swapIndex = i;
for(int j = i + 1; j < arrSize; j++)
{
if(arr[j] < arr[swapIndex])
swapIndex = j;
}
if(swapIndex != i)
{
int temp = arr[swapIndex];
arr[swapIndex] = arr[i];
arr[i] = temp;
}
}
return sortSectionSize;
}
double median(int arr[], int size)
{
int halved = size/2;
if(size % 2 == 0)
{
SelectionSortPartB(arr, size, halved + 1);
return (double) (arr[halved] + arr[halved - 1])/2;
}
SelectionSortPartB(arr, size, halved);
return (double) arr[halved];
}
void printArray(int arr[], int size)
{
for(int i = 0; i < size; i++)
{
cout << arr[i] << ((i == size -1) ? "\n\n" : ", ");
}
}
| true |
d090a0f74327bf3687ec0734784af5fb81859bb0 | C++ | ABX9801/Data-Structures | /linked-list/linkedlist1.cpp | UTF-8 | 1,010 | 3.765625 | 4 | [] | no_license | #include<iostream>
using namespace std;
// In this code we will observe linked list as a queue implementation
struct node
{
int data;
node* next;
};
node* head = NULL;
void append(int value){
if(head==NULL){
node* temp = (node*)malloc(sizeof(node));
head = temp;
temp->data = value;
temp->next = NULL;
}
else{
node* k = head;
while(k->next!=NULL){
k = k->next;
}
node* temp = (node*)malloc(sizeof(node));
k->next = temp;
temp->next = NULL;
temp->data = value;
}
}
//POP()
void pop(){
if(head->next==NULL){
head = NULL;
}
else{
head = head->next;
}
}
//Function that prints the components of linked list
void printlist(node* head){
node* k = head;
while(k!=NULL){
printf("%d ",k->data);
k = k->next;
}
cout<<endl;
}
int main(void){
append(1);
append(2);
append(3);
printlist(head);
return 0;
} | true |
fadbeea1c12c51f26ec2805f9224ef9be6ca68cf | C++ | Binarianz/Dataons | /ISI/D03-C++-Web1909B- J. Chevalier/SubmittedDocs/Joseph_LibraryExercise/Book.cpp | UTF-8 | 1,077 | 3.34375 | 3 | [] | no_license | #include "Book.h"
using namespace std;
Book::Book()
{
}
Book::Book(string title,string author, int pageCount):LibraryItem(title)
{
this->author = author;
this->pageCount = pageCount;
this->timesRead = 0;
this->dateLastRead = nullptr;
}
Book::~Book()
{
if (this->dateLastRead != nullptr)
delete dateLastRead;
}
string Book::getAuthor()
{
return author;
}
int Book::getPageCount()
{
return pageCount;
}
int Book::getTimesRead()
{
return timesRead;
}
Date* Book::getDateLastRead()
{
return this->dateLastRead;
}
string Book::toString()
{
string librarystring = LibraryItem::toString();
return librarystring+"Author = " + author + "Page count = " + to_string(pageCount) +
"times read = " + to_string(pageCount) + "last date read = " + dateLastRead->toString();
}
void Book::read()
{
this->timesRead += this->timesRead;
if (dateLastRead != nullptr)
delete dateLastRead;
dateLastRead = new Date(Date::getToday());
//Date today = Date::getToday();
//this->dateLastRead = &dateLastRead->getToday();
}
void Book::display()
{
cout << this->toString();
}
| true |
b5ea31fa8594fb60d09529a91050887029b93b47 | C++ | liuy307/Coding-Interviews | /01Operator.cpp | UTF-8 | 1,157 | 3.34375 | 3 | [] | no_license | #include<cstring>
#include<cstdio>
#include <assert.h>
#include <iostream>
class CMyString
{
public:
CMyString(char* pData = nullptr);
CMyString(const CMyString& str);
~CMyString(void);
CMyString& operator = (const CMyString& str);
private:
char* m_pData;
};
CMyString::CMyString(char* pData) {
std::cout << "构造函数" << std::endl;
if (pData == 0) {
m_pData = new char[1];
m_pData[0] = '\0';
}
else{
m_pData = new char[strlen(pData) + 1];
strcpy(m_pData, pData);
}
}
CMyString::~CMyString(void){
std::cout << "析构函数" << std::endl;
delete []m_pData;
m_pData = 0;
}
CMyString::CMyString(const CMyString& str){
//delete[]m_pData; //注意!delete空指针会出错
m_pData = new char[strlen(str.m_pData) + 1];
strcpy(m_pData, str.m_pData);
}
CMyString& CMyString::operator = (const CMyString& other) {
if (&other == this){
return *this;
}
else {
delete[]m_pData;
m_pData = 0;
m_pData = new char[strlen(other.m_pData) + 1];
strcpy(m_pData, other.m_pData);
return *this;
}
}
void Test() {
CMyString ms("hello");
CMyString ms2;
CMyString ms3;
ms3= ms2 = ms;
}
int main() {
Test();
return 0;
}
| true |
355bbc2b6c9807143b65db084f9f6e83bf2a4008 | C++ | Libaier/ABC | /算法/剑指offer/18.cpp | UTF-8 | 988 | 3.78125 | 4 | [
"MIT"
] | permissive | /*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool IsSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if (pRoot2==NULL)
{
return true;
}
if (pRoot1==NULL)
{
return false;
}
if (pRoot1->val == pRoot2->val)
{
return IsSubtree(pRoot1->left,pRoot2->left)&&
IsSubtree(pRoot1->right,pRoot2->right);
}
return false;
}
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
bool result = false;
if (pRoot1!=NULL&&pRoot2!=NULL)
{
if (pRoot1->val == pRoot2->val)
{
result = IsSubtree(pRoot1,pRoot2);
}
if(!result)
{
result = HasSubtree(pRoot1->left,pRoot2);
}
if(!result)
{
result = HasSubtree(pRoot1->right,pRoot2);
}
}
return result;
}
}; | true |
bc281dd435b9ea6fcab12ecd292a8241bc804440 | C++ | Anne-ClaireFouchier/ImageProcessingComputerVision | /AVSA/Histogram_based_object_tracking/src/Tracker.cpp | UTF-8 | 2,883 | 2.671875 | 3 | [] | no_license | #include "Tracker.hpp"
#include "ShowManyImages.hpp"
using namespace cv;
using namespace std;
// initializing the tracker parameters
Tracker::Tracker (Model* model, unsigned int nrCandidates, unsigned int stride)
{
this->model = model;
this->nrCandidates = nrCandidates;
this->stride = stride;
}
Tracker::~Tracker ()
{
delete model;
}
// get the best estimate for the given frame
Rect Tracker::GetEstimate (const Mat& frame) const
{
// offset the top left corner of the model which will be the starting point for the first candidate
int offset = (int)(sqrt(nrCandidates) / 2.0 * stride);
Point start = model->GetLocation ().tl () + Point (-offset, -offset);
// if the neighbourhood is outside of the frame in the top left corner decrease it to fit into the frame
if (start.x < 0) start.x = 0;
if (start.y < 0) start.y = 0;
// candidates have the same size as the model
Size candidateSize = model->GetLocation ().size ();
vector<Rect> candidates;
vector<double> colorScores;
vector<double> gradientScores;
// crate a double loop for the top left corners of the candidates
for (int x = start.x; x < start.x + offset * 2; x += stride) {
for (int y = start.y; y < start.y + offset * 2; y += stride) {
Rect currentLoc = Rect (Point (x, y), candidateSize);
// check if the current candidate is inside the frame
if (currentLoc.br ().x < frame.cols && currentLoc.br ().y < frame.rows) {
// calculate the two difference scores
colorScores.push_back (model->CalculateColorDifference (frame (currentLoc)));
gradientScores.push_back (model->CalculateGradientDifference (frame (currentLoc)));
// store the candidates to later select the one belonging to the smallest difference
candidates.push_back (currentLoc);
}
}
}
// normalize the scores to be abble to accumulate them
normalize (colorScores, colorScores, 1, 0, NORM_L1);
normalize (gradientScores, gradientScores, 1, 0, NORM_L1);
// add the two normalized scores together
std::transform (colorScores.begin (), colorScores.end (), gradientScores.begin (),
colorScores.begin (), std::plus<double> ());
// find the candidate belonging to the smallest difference
Rect minLocation = candidates[std::distance (colorScores.begin (), std::min_element (colorScores.begin (), colorScores.end ()))];
// only for Color Model
// plot histograms and best candidaets
//ShowManyImages ("Best candidate", 4,
// CreateHistogramImage("Best candidate", model->CalculateFeature (frame (minLocation))),
// frame(minLocation),
// CreateHistogramImage ("Model", model->GetFeature ()),
// model->ConvertPatch(frame(minLocation)));
// update the model. in the final version only the location is actually updated
model->UpdateModel (minLocation, frame (minLocation));
return minLocation;
}
| true |
55ceb0d78b4d7153becd9eb6e5a26b6d3ff4cde5 | C++ | PalashHawee/Data-Structures-and-Algorithms-My-Preparation-for-Software-Engineering | /String/Comparing_Strings.cpp | UTF-8 | 384 | 3.78125 | 4 | [] | no_license | //Comparing two strings
#include<stdio.h>
int main()
{
char A[]="Painter";
char B[]="Painting";
int i,j;
for(i=0,j=0;A[i]!='\0'&&B[j]!='\0';i++,j++)
{
if(A[i]!=B[j])
{
break;
}
if(A[i]==B[j])
{
printf("Two strings are equal");
}
else if(A[i]<B[j])
{
printf("A is smaller");
}
else
{
printf("A is greater");
}
}
}
| true |
ef5b31c95790f2d080d2e69e5790af9b44c03ee4 | C++ | yjhui0331/DesignPattern | /Adapter/main.cpp | UTF-8 | 1,491 | 2.875 | 3 | [] | no_license | // Adapter.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "Adapter.h"
#include <iostream>
/*
意图:
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
角色:
Target 目标使用的接口
Adaptee 第三方类接口
Adapter 适配器本身 通过继承Target,父接口,在接口中适配调用Adaptee特殊功能接口(对象组合方式实现)
适应性:
你想使用一个已经存在的类,而它的接口不符合你的需求。
你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
(仅适用于对象Adapter)你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。
*/
int main()
{
std::cout << "Adapter Test \n" << std::endl;
Adaptee* pAdaptee = new Adaptee;
Target* pTarget = new Adapter(pAdaptee);//创建 派生类
std::cout << std::endl;
pTarget->Request(); //调用特殊的功能
std::cout <<std::endl;
delete pTarget;
delete pAdaptee;
}
/*
执行结果
Adapter Test
Adaptee::Constructors
Target::Constructors
Adaptet::Constructors
Adaptet::Request()
Adaptee::SpecificRequest()
Adaptet::Destructors
Target::Destructors
Adaptee::Destructors
*/ | true |
600aaaa99a71a06628e8a44f517adfa4f09971a5 | C++ | ankitvashisht12/Competitve-programming | /SPOJ/AddingReversedNumbers.cpp | UTF-8 | 549 | 2.765625 | 3 | [] | no_license | /*
* Author : Ankit Vashisht
* Problem :https://www.spoj.com/problems/ADDREV/
*/
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int n;
cin>>n;
while(n--){
int res,resres =0,r=0;
string a,b;
cin>>a>>b;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
res = stoi(a)+stoi(b);
while(res){
r = res%10;
resres = resres*10+r;
res = res/10;
}
cout<<resres<<'\n';
}
return 0;
}
| true |
cb7ca17eaf9ba12ca5e0eaac80a7565e5e658fcb | C++ | Helvinion/libTuyaux | /include/Buffers/Buffer.hpp | UTF-8 | 435 | 2.78125 | 3 | [] | no_license | #ifndef INCLUDE_BUFFERS_BUFFER_HPP
# define INCLUDE_BUFFERS_BUFFER_HPP
class Buffer
{
public:
virtual ~Buffer() {};
virtual unsigned char& operator[](unsigned int index) = 0;
virtual const unsigned char& operator[](unsigned int index) const = 0;
virtual unsigned int size() const = 0;
virtual Buffer* split(unsigned int index) = 0;
virtual void dump(unsigned char* dst) const = 0;
};
#endif // INCLUDE_BUFFERS_BUFFER_HPP
| true |
7e2384dd564ea8c0136e0f218114e1d0a96b21d7 | C++ | BlackKvader/my_database | /main.cpp | UTF-8 | 846 | 2.546875 | 3 | [] | no_license | /*
databaza
forma:
subor sa vola hocijako.dat
C: category
T: title
K: keywords
Q: otazka
A: answer / data
*/
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "classes.hpp"
#define ss_clr() {ss.str(""); ss.clear();}
#define my_open(xx) {if (xx.is_open()) {xx.close();}; s=ss.str(); xx.open(s.c_str());}
using namespace std;
// global variables
stringstream ss;
string line;
string s;
ifstream infile;
ofstream outfile;
int main()
{
/// make list of all files in data/ to list.dat
system("cd data/; ls *.dat > list.dat");
ss_clr(); ss << "./list.dat";
my_open(infile);
stringstream ss2;
ss2.clear(); ss2.str("");
while(getline(infile,line)){
ss2 << line << "\n";
}
s = ss2.str();
cout << s;
return 0;
} | true |
e51711af4287c1f7b86bcce1f4fb19e6c754e35a | C++ | ihewro/iNet | /utils/UdpConnection.cpp | UTF-8 | 3,014 | 2.609375 | 3 | [] | no_license | /**
文件注释样例,参考: http://www.edparrish.net/common/cppdoc.html
socket 连接流程实现
@project netTester
@author Tao Zhang, Tao, Tao
@since 2020/4/26
@version 0.1.3 2020/4/30
*/
#include "UdpConnection.h"
#include "seeker/loggerApi.h"
using seeker::SocketUtil;
UdpConnection::UdpConnection() {}
UdpConnection& UdpConnection::setLocalIp(const string& ip) {
localIp = ip;
return *this;
}
UdpConnection& UdpConnection::setLocalPort(int port) {
localPort = port;
return *this;
}
UdpConnection& UdpConnection::setRemoteIp(const string& ip) {
remoteIp = ip;
return *this;
}
UdpConnection& UdpConnection::setRemotePort(int port) {
remotePort = port;
return *this;
}
UdpConnection& UdpConnection::init() {
if (inited) {
throw std::runtime_error("UdpConnection has been already inited.");
}
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (localPort > 0) {
localAddr = SocketUtil::createAddr(localPort, localIp);
if (bind(sock, (sockaddr*)&localAddr, sizeof(sockaddr_in)) == SOCKET_ERROR) {
SocketUtil::closeSocket(sock);
SocketUtil::cleanWSA();
auto msg = fmt::format("bind error: [{}:{}]", localIp, localPort);
throw std::runtime_error(msg);
}
D_LOG("connect inited with local address [{}:{}]", localIp, localPort);
inited = true;
}
if (remotePort > 0 && !remoteIp.empty()) {
remoteAddr = SocketUtil::createAddr(remotePort, remoteIp);
D_LOG("connect inited with remote address [{}:{}]", remoteIp, remotePort);
inited = true;
}
if (!inited) {
throw std::runtime_error("connection init failed.");
}
return *this;
}
void UdpConnection::close() {
SocketUtil::closeSocket(sock);
SocketUtil::cleanWSA();
}
SOCKET UdpConnection::getSocket() { return sock; }
void UdpConnection::updateRemoteAddr(const sockaddr_in& addr) {
// TODO lock maybe need here.
remoteIp = inet_ntoa(addr.sin_addr);
remotePort = ntohs(addr.sin_port);
remoteAddr.sin_family = addr.sin_family;
remoteAddr.sin_addr = addr.sin_addr;
remoteAddr.sin_port = addr.sin_port;
}
void UdpConnection::updateRemoteAddr() { updateRemoteAddr(lastAddr); }
void UdpConnection::sendData(char* buf, size_t len) {
if (inited && remoteAddr.sin_port != 0) {
static auto addrLen = sizeof(sockaddr);
sendto(sock, buf, len, 0, (sockaddr*)&remoteAddr, addrLen);
} else {
throw std::runtime_error("connection not inited or remoteAddr not set.");
}
}
void UdpConnection::reply(char* buf, size_t len) {
if (inited && lastAddr.sin_port != 0) {
static auto addrLen = sizeof(sockaddr);
sendto(sock, buf, len, 0, (sockaddr*)&lastAddr, addrLen);
} else {
throw std::runtime_error("connection not inited or lastAddr not set.");
}
}
int UdpConnection::recvData(char* buf, size_t len) {
if (inited) {
lastAddrLen = sizeof(lastAddr);
return recvfrom(sock, buf, len, 0, (sockaddr*)&lastAddr, (socklen_t*)&lastAddrLen);
} else {
throw std::runtime_error("connection not inited");
}
}
| true |
13dddcb9bd5553fc044645947a95fb79a739dbf7 | C++ | JHYOOOOON/Collection | /baekjoon/10826.cpp | UTF-8 | 787 | 3.203125 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
using namespace std;
string d[10001];
string sum(string a, string b) {
string ans = "";
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
while (a.length() < b.length()) a += '0';
while (b.length() < a.length()) b += '0';
int n, carry = 0;
for (int i = 0; i < a.length(); i++) {
n = (a[i] - '0' + b[i] - '0' + carry) % 10;
ans += to_string(n);
carry = (a[i] - '0' + b[i] - '0' + carry) / 10;
}
if (carry) ans += to_string(carry);
reverse(ans.begin(), ans.end());
return ans;
}
int main() {
int n;
cin >> n;
d[0] = '0';
d[1] = d[2] = '1';
for (int i = 3; i <= n; i++) d[i] = sum(d[i - 1], d[i - 2]);
cout << d[n] << "\n";
return 0;
}
| true |
b9956577dde3fe8489c28b8accbba6ed149ed020 | C++ | pikacsc/CodingTestPrac | /BAEKJOON_1904_01Tile/1904_01Tile_main.cpp | UHC | 1,604 | 3.515625 | 4 | [] | no_license | /*
https://www.acmicpc.net/problem/1904
01Ÿ
̿ 2 ֱ , ƹ Ÿϵ ̴ּ. Ÿϵ 0 Ǵ 1 ִ Ÿϵ̴.
ְ θ ϱ 0 Ÿϵ ٿ ̷ 00 Ÿϵ .
ᱹ 1 ϳ ̷ Ÿ Ǵ 0Ÿ 00Ÿϵ鸸 Ǿ.
Ƿ ̴ ŸϷ ̻ ũⰡ N 2 Ǿ. , N=1 1 ְ,
N=2 00, 11 ִ. (01, 10 Ǿ.) N=4 0011, 0000, 1001, 1100, 1111 5 2 ִ.
츮 ǥ N ־ ̰ ִ ̴. Ÿϵ .
Է
ù ° ٿ ڿ N ־. (1 N 1,000,000)
ù ° ٿ ̰ ִ ̰ N 2 15746 Ѵ.
Է 1
4
1
5
*/
#include <iostream>
long long dp[1000001];
int N;
int main()
{
std::cin >> N;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= N; ++i)
dp[i] = (dp[i - 1] + dp[i - 2]) % 15746;
std::cout << dp[N] % 15746;
return 0;
} | true |
4a9609c5020e62f037b24ba8a279cef7a442083c | C++ | magnusl/ssh | /src/sftp_transfer_observer.h | UTF-8 | 661 | 2.625 | 3 | [] | no_license | #ifndef _SFTP_TRANSFER_OBSERVER_H_
#define _SFTP_TRANSFER_OBSERVER_H_
#include "sftp_transfer_info.h"
namespace sftp
{
/* Class: sftp_transfer_observer
* Description: Used to notify a observer about the transfers.
*/
class sftp_transfer_observer
{
public:
// A new file transfer
virtual void OnNewTransfer(const sftp_transfer_info &) = 0;
// A file transfer was finished
virtual void OnTransferFinished(const sftp_transfer_info &) = 0;
// A file transfer failed
virtual void OnTransferError(const sftp_transfer_info &) = 0;
};
};
#endif | true |
cb5783e4d4984e0d7b70ebffcfc24c4a01e43fca | C++ | Daratrixx/cpp-gl4-engine | /src/Entity.h | UTF-8 | 937 | 2.8125 | 3 | [] | no_license | #pragma once
#ifndef ENTITY_H
#define ENTITY_H
#ifndef TYPES_H
#include "Types.h"
#endif
#ifndef GAMEOBJECT_H
#include "GameObject.h"
#endif
class Entity : public GameObject {
public:
Entity();
Entity(Entity* e);
virtual ~Entity();
virtual bool writeInFile(std::ofstream & fout);
virtual bool readFromFile(std::ifstream & fin);
void setRadius(const float & radius);
float getRadius() const;
virtual void push(const float & x, const float & y);
Entity* getTarget() const;
bool isTarget(Entity* e) const;
void setTarget(Entity* target);
float getMovingSpeed();
void setMovingSpeed(const float & movingSpeed);
virtual bool isAlive() const;
virtual bool isUnit() const;
virtual bool isMissile() const;
bool m_doCollision;
float m_lastCollisionHit;
float m_movingSpeed;
float m_collisionRadius;
Entity* m_target;
};
#endif
| true |
a4c33742ab4b2bd070eb42fceee92d52976ab484 | C++ | hezyin/pvz | /mainwindow.cpp | UTF-8 | 2,425 | 2.5625 | 3 | [] | no_license | #include <QtGui>
#include "mainwindow.h"
#include "plant.h"
#include "sunflower.h"
#include "backgroundmusic.h"
#include "sunlight.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
createActions();
createMenus();
QPushButton *quit = new QPushButton(tr("Quit"));
connect(quit, SIGNAL(clicked()), this, SLOT(close()));
SunLight *sun = new SunLight();
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(quit);
layout->addWidget(sun);
QGridLayout *grid = new QGridLayout;
layout->addLayout(grid);
Plant *pea = new Plant();
grid->addWidget(pea,0,0);
pea = new Plant();
grid->addWidget(pea,1,0);
Plant *flower = new SunFlower();
grid->addWidget(flower,0,1);
connect(flower,SIGNAL(produceSunLight(int)),sun,SLOT(addSunLight(int)));
flower = new SunFlower();
grid->addWidget(flower,1,1);
connect(flower,SIGNAL(produceSunLight(int)),sun,SLOT(addSunLight(int)));
QWidget *widget = new QWidget;
widget->setLayout(layout);
widget->show();
setWindowTitle(QObject::tr("Plant VS Zombies"));
setCentralWidget(widget);
BackgroundMusic *music = new BackgroundMusic;
music->startPlaying();
}
MainWindow::~MainWindow()
{
//delete ui;
}
void MainWindow::createMenus()
{
gameMenu = menuBar()->addMenu(tr("&Game"));
gameMenu->addAction(newGameAct);
gameMenu->addSeparator();
gameMenu->addAction(exitAct);
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
}
void MainWindow::createActions()
{
newGameAct = new QAction(tr("&New"),this);
newGameAct->setShortcut(tr("Ctrl+N"));
connect(newGameAct, SIGNAL(triggered()), this, SLOT(newGame()));
exitAct = new QAction(tr("E&xit"),this);
exitAct->setShortcut(tr("Ctrl+g"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(tr("&About"), this);
aboutAct->setStatusTip(tr("Show the application's About box"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About Application"),
tr("The <b>PVZ</b> was written by"
"Yang Sheng <yangsheng6810@gmail.com>"
" and "
" as a homework"));
}
void MainWindow::newGame()
{
QMessageBox::information(this, tr("Not implemented!"),tr("This function hasn't been implemented!"));
}
| true |
fbed0964742c9c9c420965cf148e3ba79b4fa521 | C++ | Laurie-S/ITC313-TP2 | /commande.cpp | UTF-8 | 2,072 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include "produit.h"
#include "commande.h"
#include "client.h"
commande::commande(client client1, vector<produit> produits) : client1_(client1), produit_(produits){
statusCommande_=false;
}
void commande::addProduit(produit prod1){
produit_.push_back(prod1);
}
client commande::getClient(){
return client1_;
}
void commande::livre(){
statusCommande_=true;
}
bool commande::getStatus(){
return statusCommande_;
}
int commande::tailleProd(){
return produit_.size();
}
produit commande::getProduit(int i){
return produit_.at(i);
}
vector<produit> commande::getPdtCom(){
return produit_;
}
ostream& operator << (ostream &out, commande *com1) {
int n;
client client1 = com1->getClient();
out << " ____________________________________________________________________________" << endl;
out << "| COMMANDE |" << endl;
out << "|----------------------------------------------------------------------------|" << endl;
out << "| Nom du client : " << client1.getNom();
n=59-(client1.getNom()).size();
for (int i =0; i<n; i++){
out << " ";
}
out << "|" << endl;
out << "|----------------------------------------------------------------------------| " << endl;
for(int i=0;i<com1->tailleProd();i++){
produit prod1=com1->getProduit(i);
out << &prod1;
}
bool statut = com1->getStatus();
if (statut==false){
out << "|----------------------------------------------------------------------------| " << endl;
out << "| En cours de livraison |" << endl;
}
else{
out << "|----------------------------------------------------------------------------| " << endl;
out << "| Livré |" << endl;
}
out << "|____________________________________________________________________________|" << endl;
out << endl << endl;
return out;
} | true |
fa942472174f43cdd95ea3d57049f24f97b8c805 | C++ | TGiumenta/SuperPaulBox | /source/UnitTest.Library.Desktop/VectorTests.cpp | UTF-8 | 12,449 | 2.8125 | 3 | [] | no_license | #include "pch.h"
#include <crtdbg.h>
#include <CppUnitTest.h>
#include "foo.h"
#include <exception>
#include "Vector.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace FieaGameEngine;
using namespace UnitTests;
namespace Microsoft::VisualStudio::CppUnitTestFramework
{
template<>
inline std::wstring ToString<Foo>(const Foo& t)
{
RETURN_WIDE_STRING(t.Data());
}
template<>
inline std::wstring ToString<Vector<Foo>::Iterator>(const Vector<Foo>::Iterator& t)
{
try
{
return ToString(*t);
}
catch (...)
{
return L"end()";
}
}
template<>
inline std::wstring ToString<Vector<Foo>::ConstIterator>(const Vector<Foo>::ConstIterator& t)
{
try
{
return ToString(*t);
}
catch (...)
{
return L"end()";
}
}
}
namespace UnitTestLibraryDesktop
{
struct CoolIncrementStrategy final
{
size_t operator()(size_t /*size*/, size_t capacity) const
{
return capacity + 100;
}
};
struct PrettyBadIncrementStrategy final
{
size_t operator()(size_t /*size*/, size_t capacity) const
{
return capacity - 1;
}
};
struct EvenWorseIncrementStrategy final
{
size_t operator()(size_t /*size*/, size_t capacity) const
{
return capacity * 0;
}
};
TEST_CLASS(VectorTests)
{
public:
TEST_CLASS_INITIALIZE(ClassInitialize)
{
}
TEST_CLASS_CLEANUP(ClassCleanup)
{
}
TEST_METHOD_INITIALIZE(Initialize)
{
#ifdef _DEBUG
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF);
_CrtMemCheckpoint(&sStartMemState);
#endif
}
TEST_METHOD_CLEANUP(Cleanup)
{
#ifdef _DEBUG
_CrtMemState endMemState, diffMemState;
_CrtMemCheckpoint(&endMemState);
if (_CrtMemDifference(&diffMemState, &sStartMemState, &endMemState))
{
_CrtMemDumpStatistics(&diffMemState);
Assert::Fail(L"Memory Leaks!");
}
#endif
}
TEST_METHOD(TestConstructor)
{
Vector<Foo> v(size_t(10));
Assert::IsTrue(v.IsEmpty());
Assert::AreEqual(v.Capacity(), size_t(10));
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
Vector<Foo> v2{ a, b, c, d };
Assert::AreEqual(v2.Size(), size_t(4));
Assert::AreEqual(v2.Front(), a);
Assert::AreEqual(v2.Back(), d);
}
TEST_METHOD(TestCopyConstructorAndAssignment)
{
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
Vector<Foo> v{ a, b, c, d };
Vector<Foo> v2(v);
Assert::AreEqual(v[0], v2[0]);
Assert::AreEqual(v[1], v2[1]);
Assert::AreEqual(v[2], v2[2]);
Assert::AreEqual(v[3], v2[3]);
Assert::AreEqual(v.Size(), v2.Size());
Assert::AreEqual(v.Capacity(), v2.Capacity());
Vector<Foo> v3{ d, a, b, c, a };
v3 = v;
Assert::AreEqual(v[0], v3[0]);
Assert::AreEqual(v[1], v3[1]);
Assert::AreEqual(v[2], v3[2]);
Assert::AreEqual(v[3], v3[3]);
Assert::AreEqual(v.Size(), v3.Size());
// Should this be true??
//Assert::AreEqual(v.Capacity(), v3.Capacity());
}
TEST_METHOD(TestMoveSemantics)
{
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
Vector<Foo> v{ a, b, c, d };
Vector<Foo> v2(std::move(v));
Assert::IsTrue(v.IsEmpty());
Assert::ExpectException<std::exception>([&v] { v[0]; });
Assert::AreEqual(v2[0], a);
Assert::AreEqual(v2[1], b);
Assert::AreEqual(v2[2], c);
Assert::AreEqual(v2[3], d);
Vector<Foo> v3{ d, a, b, c, a };
v3 = std::move(v2);
Assert::IsTrue(v2.IsEmpty());
Assert::ExpectException<std::exception>([&v2] { v2[0]; });
Assert::AreEqual(v3[0], a);
Assert::AreEqual(v3[1], b);
Assert::AreEqual(v3[2], c);
Assert::AreEqual(v3[3], d);
}
TEST_METHOD(TestPushBack)
{
Vector<Foo> v(size_t(3));
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
v.PushBack(a);
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(1));
Assert::AreEqual(v.Capacity(), size_t(3));
v.PushBack(b);
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(2));
Assert::AreEqual(v.Capacity(), size_t(3));
v.PushBack(c);
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(3));
Assert::AreEqual(v.Capacity(), size_t(3));
v.PushBack(d);
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(4));
Assert::AreEqual(v.Capacity(), size_t(4));
v.PushBack<PrettyBadIncrementStrategy>(a);
Assert::AreEqual(v.Size(), size_t(5));
Assert::AreEqual(v.Capacity(), size_t(5));
v.PushBack<EvenWorseIncrementStrategy>(a);
Assert::AreEqual(v.Size(), size_t(6));
Assert::AreEqual(v.Capacity(), size_t(6));
v.PushBack<CoolIncrementStrategy>(a);
Assert::AreEqual(v.Size(), size_t(7));
Assert::AreEqual(v.Capacity(), size_t(106));
}
TEST_METHOD(TestPushBackMoveSemantics)
{
Vector<Foo> v(size_t(3));
Foo a(1);
Foo b(2);
Foo c(3);
Foo d(4);
v.PushBack(std::move(a));
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(1));
Assert::AreEqual(v.Capacity(), size_t(3));
v.PushBack(std::move(b));
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(2));
Assert::AreEqual(v.Capacity(), size_t(3));
v.PushBack(std::move(c));
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(3));
Assert::AreEqual(v.Capacity(), size_t(3));
v.PushBack(std::move(d));
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(4));
Assert::AreEqual(v.Capacity(), size_t(4));
// Custom increment functors
v.PushBack<PrettyBadIncrementStrategy>(std::move(a));
Assert::AreEqual(v.Size(), size_t(5));
Assert::AreEqual(v.Capacity(), size_t(5));
v.PushBack<EvenWorseIncrementStrategy>(std::move(a));
Assert::AreEqual(v.Size(), size_t(6));
Assert::AreEqual(v.Capacity(), size_t(6));
v.PushBack<CoolIncrementStrategy>(std::move(a));
Assert::AreEqual(v.Size(), size_t(7));
Assert::AreEqual(v.Capacity(), size_t(106));
}
TEST_METHOD(TestBracketOperator)
{
Vector<Foo> v(size_t(3));
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
v.PushBack(a);
v.PushBack(b);
v.PushBack(c);
v.PushBack(d);
Assert::AreEqual(v[0], a);
Assert::AreEqual(v[1], b);
Assert::AreEqual(v[2], c);
Assert::AreEqual(v[3], d);
Assert::AreNotEqual(v[1], a);
Assert::ExpectException<std::exception>([&v] { v[4]; });
// const version
const Vector<Foo> v2(v);
Assert::AreEqual(v2[0], a);
Assert::AreEqual(v2[1], b);
Assert::AreEqual(v2[2], c);
Assert::AreEqual(v2[3], d);
Assert::AreNotEqual(v2[1], a);
Assert::ExpectException<std::exception>([&v2] { v2[4]; });
}
TEST_METHOD(TestAt)
{
// non-const version
Vector<Foo> v(size_t(3));
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
v.PushBack(a);
v.PushBack(b);
v.PushBack(c);
v.PushBack(d);
Assert::AreEqual(v.At(0), a);
Assert::AreEqual(v.At(1), b);
Assert::AreEqual(v.At(2), c);
Assert::AreEqual(v.At(3), d);
Assert::AreNotEqual(v.At(1), a);
Assert::ExpectException<std::exception>([&v] { v.At(4); });
// const version
const Vector<Foo> v2{ a, b, c, d };
Assert::AreEqual(v2.At(0), a);
Assert::AreEqual(v2.At(1), b);
Assert::AreEqual(v2.At(2), c);
Assert::AreEqual(v2.At(3), d);
Assert::AreNotEqual(v2.At(1), a);
Assert::ExpectException<std::exception>([&v2] { v2.At(4); });
}
TEST_METHOD(TestPopBack)
{
Vector<Foo> v(size_t(3));
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
v.PushBack(a);
v.PushBack(b);
v.PushBack(c);
v.PushBack(d);
v.PopBack();
Assert::IsFalse(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(3));
Assert::AreEqual(v.Capacity(), size_t(4));
v.PopBack();
Assert::AreEqual(v.Size(), size_t(2));
Assert::AreEqual(v.Capacity(), size_t(4));
v.PopBack();
Assert::AreEqual(v.Size(), size_t(1));
Assert::AreEqual(v.Capacity(), size_t(4));
v.PopBack();
Assert::IsTrue(v.IsEmpty());
Assert::AreEqual(v.Size(), size_t(0));
Assert::AreEqual(v.Capacity(), size_t(4));
v.PopBack();
}
TEST_METHOD(TestFrontBack)
{
// non-const versions
Vector<Foo> v(size_t(3));
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
Assert::ExpectException<std::exception>([&v] { v.Front(); });
Assert::ExpectException<std::exception>([&v] { v.Back(); });
v.PushBack(a);
Assert::AreEqual(v.Front(), a);
Assert::AreEqual(v.Back(), a);
v.PushBack(b);
v.PushBack(c);
v.PushBack(d);
Assert::AreEqual(v.Front(), a);
Assert::AreEqual(v.Back(), d);
// const versions
const Vector<Foo> v2{ a, b, c, d };
Assert::AreEqual(v2.Front(), a);
Assert::AreEqual(v2.Back(), d);
const Vector<Foo> v3;
Assert::ExpectException<std::exception>([&v3] { v3.Front(); });
Assert::ExpectException<std::exception>([&v3] { v3.Back(); });
}
TEST_METHOD(TestFind)
{
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
const Foo e(5);
Vector<Foo> v{ a, b, c, d };
auto itA = v.Find(a);
Assert::AreEqual(*itA, a);
auto itB = v.Find(b);
Assert::AreEqual(*itB, b);
auto itD = v.Find(d);
Assert::AreEqual(*itD, d);
auto itE = v.Find(e);
Assert::AreEqual(itE, v.end());
// const version
const Vector<Foo> v2(v);
auto itA2 = v2.Find(a);
Assert::AreEqual(*itA2, a);
auto itB2 = v2.Find(b);
Assert::AreEqual(*itB2, b);
auto itD2 = v2.Find(d);
Assert::AreEqual(*itD2, d);
auto itE2 = v2.Find(e);
Assert::AreEqual(itE2, v2.end());
}
TEST_METHOD(TestRemove)
{
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
const Foo e(5);
Vector<Foo> v{ a, b, c, d };
size_t test = sizeof(Foo);
test;
v.Remove(b);
Assert::AreEqual(v[0], a);
Assert::AreEqual(v[1], c);
Assert::AreEqual(v[2], d);
Assert::ExpectException<std::exception>([&v] { v[3]; });
Assert::IsFalse(v.Remove(e));
}
TEST_METHOD(TestRangedRemove)
{
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
const Foo e(5);
Vector<Foo> v{ a, b, c, d, a, b, c, d, a, b, c };
auto startIt = v.begin();
startIt++;
startIt++;
startIt++;
auto endIt = startIt;
endIt++;
endIt++;
endIt++;
// { a, b, c, || d, a, b, || c, d, a, b, c };
v.Remove(startIt, endIt);
// { a, b, c, c, d, a, b, c };
Assert::AreEqual(v.Size(), size_t(8));
Assert::AreEqual(v[0], a);
Assert::AreEqual(v[1], b);
Assert::AreEqual(v[2], c);
Assert::AreEqual(v[3], c);
Assert::AreEqual(v[4], d);
Assert::AreEqual(v[5], a);
Assert::AreEqual(v[6], b);
Assert::AreEqual(v[7], c);
Assert::ExpectException<std::exception>([&v] { v[8]; });
// startIt after endIt
Assert::ExpectException<std::exception>([&v, &endIt, &startIt] { v.Remove(endIt, startIt); });
Vector<Foo> v2(v);
auto otherIt = v2.end();
Assert::IsFalse(v.Remove(startIt, otherIt));
v.Resize(2);
}
TEST_METHOD(TestShrinkToFit)
{
const Foo a(1);
const Foo b(2);
const Foo c(3);
const Foo d(4);
const Foo e(5);
Vector<Foo> v{ a, b, c, d, a, b, c, d, a, b, c };
v.Reserve(100);
Assert::AreEqual(v.Capacity(), size_t(100));
v.ShrinkToFit();
Assert::AreEqual(v.Capacity(), size_t(11));
}
private:
static _CrtMemState sStartMemState;
};
_CrtMemState VectorTests::sStartMemState;
}
| true |
b213e054a9c9da12576cbf28c61146a4d8460b6f | C++ | kamilsan/algorithms-and-data-structures | /data-structures/linked-list/test.cpp | UTF-8 | 1,434 | 3.65625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include "linkedList.hpp"
int main()
{
LinkedList<int> list;
list.add_front(12);
list.add_front(42);
list.add_front(53);
list.for_each([](const int& n) { std::cout << n << " ";});
std::cout << std::endl;
std::cout << "Front: " << list.get_front() << std::endl;
std::cout << "Size: " << list.size() << std::endl;
std::cout << "Removing front..." << std::endl;
list.remove_front();
list.for_each([](const int& n) { std::cout << n << " ";});
std::cout << std::endl;
std::cout << "Adding some elements..." << std::endl;
list.add_front(1);
list.add_front(4);
list.add_front(5);
list.for_each([](const int& n) { std::cout << n << " ";});
std::cout << std::endl;
list.contains(4) ? std::cout << "4 is in the list." : std::cout << "4 is not on the list.";
std::cout << std::endl;
list.contains(35) ? std::cout << "35 is in the list." : std::cout << "35 is not on the list.";
std::cout << std::endl;
std::cout << "Removing 42..." << std::endl;
list.remove(42);
list.for_each([](const int& n) { std::cout << n << " ";});
std::cout << std::endl;
std::cout << "Removing 5..." << std::endl;
list.remove(5);
list.for_each([](const int& n) { std::cout << n << " ";});
std::cout << std::endl;
std::cout << "Removing 12..." << std::endl;
list.remove(12);
list.for_each([](const int& n) { std::cout << n << " ";});
std::cout << std::endl;
return 0;
} | true |
bf5c32531c773d3f74239ce275494bd9fe90cbb5 | C++ | arosh/NJPC2017 | /InputForm/solution/main.cc | UTF-8 | 186 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int L; string S;
cin >> L >> S;
cout << S.substr(0, min<int>(L, S.size())) << endl;
}
| true |
b0a63e9ac95bb88a0ea0b1d88890e7ed5f1f566a | C++ | daman94/Coding-Problems | /Stacks/2-Linked List Implementation.cpp | UTF-8 | 1,393 | 3.640625 | 4 | [] | no_license | //
// main.cpp
// Array
//
// Created by Daman Saroa on 09/06/15.
// Copyright (c) 2015 Daman Saroa. All rights reserved.
//
#include <iostream>
#include <stdlib.h>
#include <limits.h>
using namespace std;
struct stack {
int data;
struct stack* next;
};
struct stack* Create()
{
return NULL;
}
void Push(struct stack **topRef, int data)
{
struct stack* temp;
temp = (struct stack*)malloc(sizeof(struct stack));
if (!temp)
{
return;
}
temp->data = data;
temp->next = *topRef;
*topRef = temp;
}
int isEmptyStack(struct stack* top)
{
return (top == NULL);
}
int Pop(struct stack **topRef)
{
struct stack *temp = *topRef;
int data = temp->data;
if (isEmptyStack(*topRef))
{
cout << "stack is empty";
return INT_MIN;
}
*topRef = (*topRef)->next;
free(temp);
return data;
}
int Top(struct stack* top)
{
if (isEmptyStack(top))
{
return INT_MIN;
}
return top->data;
}
void DeleteStack(struct stack** topRef)
{
struct stack* temp = *topRef;
struct stack* p = temp;
while (p)
{
p = p->next;
free(temp);
temp = p;
}
}
//Main
int main()
{
struct stack* top = NULL;
Push(&top, 1);
Push(&top, 2);
Push(&top, 3);
cout << Pop(&top);
return 0;
}
| true |
58b184479249088d17dc59a588b8b294bb18c36c | C++ | eif-courses/tiesinePaieskapi20s | /main.cpp | UTF-8 | 4,994 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include "Studentas.h"
using namespace std;
int TiesinePaieska(const vector<int> &sarasas, int raktinisZodis);
vector<int> TiesinePaieskaSurandintiVisusAtitikmenis(const vector<int> &sarasas, int raktinisZodis);
int DvejetainePaieska(vector<int> &sarasas, int kaire, int desine, int raktinisZodis);
int TiesinePaieska(const vector<Studentas> &sarasas, int raktinisZodis);
int main() {
vector<int> test{44, 22, 888, 12, 54, 22, 55, 44, 2213, 424, 24141, 55, 44};
vector<Studentas> studentai{
Studentas(44, "Tomas", 120.45),
Studentas(55, "Paulius", 213.45),
Studentas(123, "Tomas", 876.45),
};
//vector<Zmogus> t{Zmogus("wae", 22, 2131, 123, 12)};
int stop = 1;
while (stop != 0) {
cout << "-------------MENIU------------------------" << endl;
cout << "1. Pagal raktini zodi Tiesine paieska." << endl;
cout << "2. Pagal raktini zodi Dvejetaine paieska." << endl;
cout << "3. Pagal raktini zodi is Studentas objekto Dvejetaine paieska." << endl;
cout << "0. Uzbaigti." << endl;
cout << "-------------------------------------" << endl;
cout << "Pasirinkite opcija: ";
cin >> stop;
cout << "-------------------------------------" << endl;
switch (stop) {
case 1: {
int raktinisZodis;
cout << "Nurodykite ko ieskote: ";
cin >> raktinisZodis;
int indeksas = TiesinePaieska(test, raktinisZodis);
vector<int> rastiRezultatai = TiesinePaieskaSurandintiVisusAtitikmenis(test, raktinisZodis);
cout << "-------TiesinePaieskaSurandintiVisusAtitikmenis()--------------" << endl;
if (!rastiRezultatai.empty()) {
for (int it: rastiRezultatai) {
cout << "Sekmingai rastas pozija: " << it << ", rastas: " << test[it] << endl;
}
} else {
cout << "Deja nepavyko rasti pagal pateikta fraze: " << "\"" << raktinisZodis << "\"" << endl;
}
cout << "-------------------------------------" << endl;
cout << "------------------TiesinePaieska()-------------------" << endl;
if (indeksas != -1) {
cout << "Sekmingai rastas pozija: " << indeksas << endl;
} else {
cout << "Deja nepavyko rasti pagal pateikta fraze: " << "\"" << raktinisZodis << "\"" << endl;
}
cout << "-------------------------------------" << endl;
break;
}
case 2: {
int raktinisZodis;
cout << "Nurodykite ko ieskote: ";
cin >> raktinisZodis;
int indeksas = DvejetainePaieska(test, 0, (int) test.size() - 1, raktinisZodis);
if (indeksas != -1) {
cout << "Sekmingai rastas pozija: " << indeksas << ", rastas: " << test[indeksas] << endl;
} else {
cout << "Deja nepavyko rasti pagal pateikta fraze: " << "\"" << raktinisZodis << "\"" << endl;
}
break;
}
case 3: {
int raktinisZodis;
cout << "Nurodykite ko ieskote: ";
cin >> raktinisZodis;
int indeksas = TiesinePaieska(studentai, raktinisZodis);
if (indeksas != -1) {
cout << "studentas yra! jo indeksas: " << indeksas << ", " << studentai[indeksas].GetVardas() << endl;
} else {
cout << "toks studentas neegzistuoja!" << endl;
}
break;
}
default:
cout << "nera tokio punkto" << endl;
break;
}
}
return 0;
}
int DvejetainePaieska(vector<int> &sarasas, int kaire, int desine, int raktinisZodis) {
std::sort(sarasas.begin(), sarasas.end()); // surikiuoja, surusiuoja
// for(auto it: sarasas){
// cout << it<<" ";
// }
// 12 22 22 44 44 44 54 55 55 424 888 2213 24141
// kaire = 0
// desine = 12
// vidurioElem = 0 + (12 - 0) / 2 = 6
//
while (kaire <= desine) {
int vidurioElementas = kaire + (desine - kaire) / 2;
if (sarasas[vidurioElementas] == raktinisZodis) {
return vidurioElementas;
}
// 54 < 44
if (sarasas[vidurioElementas] < raktinisZodis) {
kaire = vidurioElementas + 1; // eiti i desine puse
} else {
desine = vidurioElementas - 1; // i kaire puse
}
}
return -1;
}
//vector<int> test{44, 22, 888, 12, 54, 22, 55, 44, 2213, 424, 24141,55, 44};
int TiesinePaieska(const vector<int> &sarasas, int raktinisZodis) {
for (int i = 0; i < sarasas.size(); ++i) {
if (raktinisZodis == sarasas[i]) {
return i;
}
}
return -1;
}
int TiesinePaieska(const vector<Studentas> &sarasas, int raktinisZodis) {
for (int i = 0; i < sarasas.size(); ++i) {
if (raktinisZodis == sarasas[i].GetAmzius()) {
return i;
}
}
return -1;
}
vector<int> TiesinePaieskaSurandintiVisusAtitikmenis(const vector<int> &sarasas, int raktinisZodis) {
vector<int> laikinasSarasas;
for (int i = 0; i < sarasas.size(); ++i) {
if (raktinisZodis == sarasas[i]) {
laikinasSarasas.emplace_back(i);
}
}
return laikinasSarasas;
}
| true |
66914b63f3aa124cb350bccdd922497f35dc76d6 | C++ | needhourger/university | /数据结构/conversion.cpp | UTF-8 | 1,020 | 3.546875 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
void dec2bin(int n){
short a[32]={0};
unsigned short i=0;
if (n<0) {
printf("-");
n=-n;
}
while (n>0) {
a[i++]=n%2;
n/=2;
}
while(i>0) printf("%d",a[--i]);
printf("\n");
}
void dec2oct(int n){
short a[12]={0};
unsigned short i=0;
if (n<0) {
printf("-");
n=-n;
}
while (n>0) {
a[i++]=n%8;
n/=8;
}
while(i>0) printf("%d",a[--i]);
printf("\n");
}
void dec2hex(int n){
char a[8]={0};
unsigned short i=0;
if (n<0){
printf("-");
n=-n;
}
while (n>0){
if (n%16<10) a[i++]='0'+n%16;
else a[i++]='A'+n%16-10;
n/=16;
}
while (i>0) printf("%c",a[--i]);
printf("\n");
}
int main(){
int n;
while (1){
printf("\n=========================\nPlease input a Decimal number:\nn = ");
scanf("%d",&n);
printf("[%d] convert to binary:",n); dec2bin(n);
printf("[%d] convert to octonary:",n); dec2oct(n);
printf("[%d] convert to Hexadecimal:",n); dec2hex(n);
}
return 0;
}
| true |
a3474bdb657b1a9365a93b477d0d5c31cd8581ba | C++ | iamSamuelFu/ucsbhaha | /moreLinkedListFuncs.cpp | UTF-8 | 5,161 | 3.484375 | 3 | [] | no_license | #include <cassert>
#include "linkedList.h"
#include "linkedListFuncs.h"
Node * pointerToMax(LinkedList *list) {
assert(list!=NULL);
assert(list->head != NULL);
Node *p=list->head; //declare a new pointer p to iterate the list
int maxValue=p->data; //declare max value to the first data
Node *max=list->head; //declare a new pointer max to point to the node with max value
while(p){ //iterate through the list
if(p->data>maxValue){
max=p; //set pointer max point to the new node with max value
}
p=p->next;
}
return max;
}
Node * pointerToMin(LinkedList *list) {
assert(list!=NULL);
assert(list->head != NULL);
Node *p=list->head; //declare a new pointer p to iterate the list
int minValue=p->data; //declare min value to the first data
Node *min=list->head; //declare a new pointer min to point to the node with min value
while(p){ //iterate through the list
if((p->data)<minValue){
min=p; //set pointer min point to the new node with min value
}
p=p->next;
}
return min;
}
int largestValue(LinkedList *list) {
assert(list!=NULL);
assert(list->head != NULL);
Node *p=list->head; //declare a new pointer p to iterate the list
int maxValue=p->data; //declare max value to the first data
while(p){ //iterate through the list
if((p->data)>maxValue){
maxValue=p->data; //set max value to the new max value
}
p=p->next;
}
return maxValue;
}
int smallestValue(LinkedList *list) {
assert(list!=NULL);
assert(list->head != NULL);
Node *p=list->head; //declare a new pointer p to iterate the list
int minValue=p->data; //declare min value to the first data
while(p){ //iterate through the list
if((p->data)<minValue){
minValue=p->data; //set min value to the new min value
}
p=p->next;
}
return minValue;
}
int sum(LinkedList * list) {
assert(list!=NULL);
int sum=0; //declare and initialize the sum to 0
Node *p=list->head; //declare a new pointer p to iterate the list
if(list->head==NULL){ //empty list
return sum;
}else if(list->head->next==NULL){ //one node situation
return list->head->data;
}else{
while(p){
sum=sum+p->data;
p=p->next;
}
}
return sum;
}
void deleteNodeInteratively(LinkedList* list, int value){
if(list->head==NULL){ //empty list
return;
}else if(list->head == list->tail){ //one node
if(list->head->data == value){
delete list->head;
}
return;
}else{ //more than one node
Node *next = NULL;
Node *curr = NULL;
Node *prev = NULL;
while(list->head->data ==value){ //when the head of the list has data equal to value
next=list->head->next;
delete list->head;
list->head =next;
}
prev=list->head; // when a node in the middle has its data equal to value
curr=list->head->next;
while(curr->next){
if(curr->data == value){
curr=curr->next;
delete prev->next;
prev->next=curr;
}else{
curr=curr->next;
prev=prev->next;
}
}
if(curr->data == value){ //when the tail of the list has data equal to value
delete curr;
list->tail = prev;
}
}
}
void deleteNodeRecursively(LinkedList* list, int value){
return;
}
Node* deleteNodeHelper (Node* head, int value){
if(head==NULL){
return head;
}
Node *p = head;
Node *q = head->next;
if(p->data == value){
delete p;
head=q;
p=q;
q=q->next;
}
deleteNodeHelper (head->next, value);
}
void insertNodeToSortedList(LinkedList* list, int value){
Node *newNode = new Node; //declare a new Node object
newNode->data= value; //assign the data to value
newNode->next= NULL;
if(list->head ==NULL){ //empty list
list->head=newNode;
list->tail=newNode;
return;
}else if(list->head == list->tail){ //one node
if(list->head->data > value){
newNode->next=list->head;
list->head=newNode;
}else{
list->head->next=newNode;
list->tail=newNode;
}
return;
}else{
if(list->head->data > value){ //when value is less than data in the first node
newNode->next=list->head;
list->head=newNode;
return;
}
Node* curr=list->head->next; //when value should be placed to a position inside of the list
Node* prev=list->head;
while(curr){
if(curr->data > value){
newNode->next=curr;
prev->next=newNode;
return;
}
curr=curr->next;
prev=prev->next;
}
prev->next=newNode; //when value is greater than data in the last node
newNode->next=NULL;
list->tail=newNode;
return;
}
}
| true |
f5d65a4d613fb4a55fe7f8582eec160f5f4f77c7 | C++ | Aber4Nod/Templates | /basics_01/maxcommon.hpp | UTF-8 | 280 | 2.71875 | 3 | [] | no_license | //
// Created by n.mikhnenko on 04/01/2019.
//
#ifndef TEMPLATES_MAXCOMMON_HPP
#define TEMPLATES_MAXCOMMON_HPP
#include "type_traits"
template<typename T1, typename T2>
std::common_type_t<T1, T2> max(T1 a, T2 b)
{
return b < a ? a : b;
};
#endif //TEMPLATES_MAXCOMMON_HPP
| true |
f3b4cbb680a3b872fa262a4a8e78a53b14f6d07c | C++ | Polytechnic-Institute-of-Leiria/cg2020 | /Fire3D.cpp | UTF-8 | 2,576 | 2.546875 | 3 | [] | no_license | #include "Fire3D.h"
#define IMAGE_ROWS 4
#define IMAGE_COLS 8
//static const int IMAGE_COLS = 8;
static float vertices[4][3] = {
{ -.3f, 0.5f, 0.0f },
{ -.3f, 0.0f, 0.0f },
{ .3f, 0.5f, 0.0f },
{ .3f, 0.0f, 0.0f },
};
Fire3D::Fire3D()
{
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(2, vbo);
// vertices
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
// no colors
glDisableVertexAttribArray(1);
// textures coords
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(textCoords), textCoords, GL_STATIC_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(2);
SDL_Surface* image = SDL_LoadBMP("fire8x4.bmp");
if (image != NULL)
{
glGenTextures(1, &this->textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
// set the texture wrapping/filtering options (on the currently bound texture object)
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);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->w, image->h, 0, GL_BGRA,
GL_UNSIGNED_BYTE, image->pixels);
// glGenerateMipmap(GL_TEXTURE_2D);
}
SDL_FreeSurface(image);
}
Fire3D::~Fire3D()
{
}
void Fire3D::setFrame(int frame)
{
int col = frame % IMAGE_COLS;
int row = frame / IMAGE_COLS;
this->textureOffset.x = col * 1.0f / IMAGE_COLS;
this->textureOffset.y = row * 1.0f / IMAGE_ROWS;
//// bottom left
//textCoords[1][0] = 1.0f / IMAGE_COLS * col;
//textCoords[1][1] = 1.0f / IMAGE_ROWS * row;
//// top left
//textCoords[0][0] = textCoords[1][0];
//textCoords[0][1] = textCoords[1][1] + 1.0f / IMAGE_ROWS;
//// top right
//textCoords[2][0] = textCoords[1][0] + 1.0f / IMAGE_COLS;
//textCoords[2][1] = textCoords[0][1];
//// bottom right
//textCoords[3][0] = textCoords[2][0];
//textCoords[3][1] = textCoords[1][1];
//glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
//glBufferData(GL_ARRAY_BUFFER, sizeof(textCoords), textCoords, GL_STATIC_DRAW);
}
void Fire3D::draw(SceneViewer* v, bool transparent)
{
if (!transparent) {
return;
}
// v->setModelMatrix(this->transform); // already done by the scene!
glBindVertexArray(vao);
v->useTextures(1, &textureId, &this->textureOffset);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
| true |
9dc22042572f6aff87cca9a0b31ca0941877d01c | C++ | 49paunilay/Interfacing-with-arduino | /EEPROM.ino | UTF-8 | 750 | 2.953125 | 3 | [] | no_license | #include <EEPROM.h>
int value;
int address=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
String str="";
str=Serial.readString();
if(str.startsWith("read"))
{
address=str.substring(str.indexOf(' ')+1).toInt();
Serial.print("Address : ");
Serial.println(address);
Serial.println(EEPROM.read(address));
}
else if(str.startsWith("write"))
{
address=str.substring(6,7).toInt();
value=str.substring(8,str.length()).toInt();
Serial.print("ADDRESS :");
Serial.println(address);
Serial.print("Data->");
Serial.println(value);
EEPROM.write(address,value);
}
}
| true |
d3a4a37b216c4a27f561d6afffdc07e7ed29d1c8 | C++ | icode123/leetcode | /ZigZag Conversion.cpp | UTF-8 | 696 | 2.8125 | 3 | [] | no_license | class Solution {
public:
string convert(string s, int nRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(nRows<2) return s;
int n=s.size();
int l=2*nRows-2;
string res;
res.clear();
for(int i=0;i<n;i+=l)
{
res.push_back(s[i]);
}
for(int i=1;i<nRows-1;i++)
for(int j=i;j<n;j+=l)
{
res.push_back(s[j]);
int k=j-i+l-i;
if(k<n) res.push_back(s[k]);
}
for(int i=nRows-1;i<n;i+=l)
{
res.push_back(s[i]);
}
return res;
}
};
| true |
1f04ac05b538f3bcacb09857bdca56cc2914eb98 | C++ | TCtobychen/IntrotoAlgorithm | /C++Implementation/LuoguP1141.cpp | UTF-8 | 1,396 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define For(x,y) for(int i =x;i<y;i++)
using namespace std;
int N;
bool vis[1010][1010];
int a[1010][1010];
int poi[1010][1010];
int ans[100010];
queue<pair<int, int > > q;
void dojob(pair<int, int > pt, int n)
{
int x=pt.first, y =pt.second;
//cout << x << y << n << endl;
//cout << vis[x+1][y] << vis[x][y]<<endl;
if(x>0&&!vis[x-1][y]&&a[x-1][y]==!a[x][y])
{vis[x-1][y]=1;pair<int, int> p1(x-1,y);q.push(p1);poi[x-1][y]=n;}
if(x<N-1&&!vis[x+1][y]&&a[x+1][y]==!a[x][y])
{vis[x+1][y]=1;pair<int, int> p2(x+1,y);q.push(p2);poi[x+1][y]=n;}
if(y>0&&!vis[x][y-1]&&a[x][y-1]==!a[x][y])
{vis[x][y-1]=1;pair<int, int> p3(x,y-1);q.push(p3);poi[x][y-1]=n;}
if(y<N-1&&!vis[x][y+1]&&a[x][y+1]==!a[x][y])
{vis[x][y+1]=1;pair<int, int> p4(x,y+1);q.push(p4);poi[x][y+1]=n;}
}
int calc(int x, int y, int n)
{
if(poi[x][y]>0)
return ans[poi[x][y]];
int Ans=0;
pair<int, int > p(x,y);
vis[x][y]=1;
poi[x][y]=n;
q.push(p);
while(!q.empty())
{
pair<int , int > pt=q.front();
dojob(pt,n);
q.pop();
Ans++;
}
ans[n]=Ans;
return Ans;
}
int main()
{
int m,x,y;
cin >> N >>m;
For(0,N*N)
scanf("%1d",&a[i/N][i%N]);
memset(poi,0,sizeof(poi));
memset(vis,0,sizeof(vis));
For(0,m)
{
cin >> x >> y;
cout <<calc(x-1,y-1,i+1) << endl;
}
return 0;
}
| true |
d69dc2446a1ed33d74040fb2dc381a55231bbb54 | C++ | blockspacer/realtime_server_pub | /src/lib/variable/key_value_cache_storage.cc | UTF-8 | 817 | 2.71875 | 3 | [] | no_license | #include "key_value_cache_storage.h"
void KeyValueCacheStorage::set(const std::string& key, const std::string& value)
{
string_cache[key] = value;
}
KeyValueCacheStorage::Option KeyValueCacheStorage::get(const std::string& key)
{
std::map<std::string, std::string>::iterator it = string_cache.find(key);
if (it != string_cache.end()) {
return Option(it->second);
} else {
return Option();
}
}
void KeyValueCacheStorage::setObject(const std::string& key, void* data)
{
obj_cache[key] = data;
}
KeyValueCacheStorage::ObjOpt KeyValueCacheStorage::getObject(const std::string& key)
{
std::map<std::string, void*>::iterator it = obj_cache.find(key);
if (it != obj_cache.end()) {
return ObjOpt(it->second);
} else {
return ObjOpt();
}
}
| true |
c82b7018661f0e5e55d276db4d739f6a7f5c4608 | C++ | crafterrr/cpp_multithreading | /InputParallelizer.cpp | UTF-8 | 1,765 | 2.59375 | 3 | [] | no_license | #include <vector>
#include <stdint.h>
#include <string>
#include <sstream>
#include <thread>
#include <mutex>
#include <fstream>
#include <vector>
#include <stack>
#include <condition_variable>
#include "InputParallelizer.h"
// #include "exceptions.h"
using namespace std;
InputParallelizer::InputParallelizer(string in, string out){
input.open(in);
output.open(out);
}
void InputParallelizer::controlWorker(){
string cmd;
while (!finished_calc){
cin >> cmd;
if (cmd == "pause") paused = true;
else if (cmd == "resume" && paused) {
paused = false;
fworker.notify_all();
} else if (cmd == "exit") {
stopped = true;
break;
}
}
}
void InputParallelizer::readWorker(){
string s;
unique_lock<mutex> lck(mtx);
while (getline(input, s) && !stopped){
while(tasks.size() >= 10) {
#ifdef DEBUG
cout << "Reader waits until task completion" << endl;
#endif
ioworker.wait(lck);
}
if (stopped) break;
tasks.push(s);
fworker.notify_one();
}
finished_reading = true;
}
void InputParallelizer::writeWorker(){
string s;
unique_lock<mutex> lck(mtx);
while (!finished_calc || completed_tasks.size() != 0){
while(completed_tasks.size() == 0){
#ifdef DEBUG
cout << "Writer has 0 completed tasks" << endl;
#endif
ioworker.wait(lck);
if (finished_calc) return;
}
output << completed_tasks.top() << endl;
completed_tasks.pop();
}
}
| true |
7dd603fae12471bd7753dd7d47709336903f6d5c | C++ | asassoye/ESI-DEV3-Labos | /td08/resources/data_fraction.h | UTF-8 | 2,184 | 3.5 | 4 | [
"MIT"
] | permissive | /*!
* \file data_fraction.h
*
* \brief Fonctions pour la génération de données de création de
* fractions.
*/
#ifndef DATA_FRACTION_H
#define DATA_FRACTION_H
#include <vector>
#include <utility>
#include <tuple>
namespace nvs {
/*!
* \brief Énumération fortement typée pour choisir le type de
* comportement aléatoire.
*/
enum class Random {
/*!
* \brief Constante d'énumération destinée à représenter un
* comportement aléatoire reproductible d'une exécution
* l'autre.
*/
REPRODUCTIBLE,
/*!
* \brief Constante d'énumération destinée à représenter un
* comportement aléatoire _non_ reproductible
* d'une exécution l'autre.
*/
UNIQUE
};
/*!
* \brief Fonction pour la génération de fraction avec deux entiers
* signés en argument.
*
* Le premier attribut de chaque std::pair sert de numérateur,
* le second de dénominateur.
*
* Il peut y avoir des valeurs de dénominateur nulles.
*
* \param size le nombre de std::pair à produire.
* \param type le type de comportement aléatoire attendu.
*
* \return std::vector de `size` std::pair.
*/
std::vector<std::pair<int, int>>
data_signed(unsigned size = 1'000'000, Random type = Random::UNIQUE);
/*!
* \brief Fonction pour la génération de fraction avec un signe et
* deux entiers non signés en argument.
*
* Le premier champ de chaque std::tuple sert de signe,
* le deuxième de numérateur,
* le troisième de dénominateur.
*
* L'`int` prend ses valeurs parmi { -1, 0, 1 }, conformément aux
* valeurs de l'enum class nvs::Sign.
*
* Il peut y avoir des valeurs de signe nulles alors que le premier
* `ùnsigned` n'est pas nul, ou des valeurs de dénominateur nulles.
*
* \param size le nombre de std::tuple à produire.
* \param type le type de comportement aléatoire attendu.
*
* \return std::vector de `size` std::tuple.
*/
std::vector<std::tuple<int, unsigned, unsigned>>
data_unsigned(unsigned size = 1'000'000, Random type = Random::UNIQUE);
}
#endif // DATA_FRACTION_H
| true |
cffab1f85ed2677fa3bee570e754c511698cdbd0 | C++ | yutao-arch/2019-HIT-data-structure-lab | /数据结构实验4和实验5/1180300829-余涛-实验5/sort/sort/sort.cpp | UTF-8 | 7,708 | 3.40625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#define max 101
struct records
{
int key;
};
records a[max];
void createtest(records a[])
{
int i, j, temp,k;
for (i = 1; i < 101; i++)
{
a[i].key = i;
//printf("%d %d ", k, test[k]);
}
for (k = 1; k < 10000; k++)
{
i = rand() % max;
j = rand() % max;
if (i != 0 && j != 0)
{
temp = a[i].key;
a[i].key = a[j].key;
a[j].key = temp;
}
}
}
//产生待排序数组a
void swap(records &a, records &b)
{
records temp;
temp = a;
a = b;
b = temp;
}
//交换两个数
void bubblesort(int n)
{
int sp = 0;
for (int i = 1; i <= n-1; i++)
{
sp = 0; //每趟排序标志位都置0
for (int j = n; j >= i+1 ; j--)
{
if (a[j].key < a[j - 1].key)
{
swap(a[j], a[j - 1]);
sp = 1; //只要有发生交换,标志位为1;
}
}
if (sp == 0) //如果标志位为0,就说明所有元素已经有序,直接返回
{
return;
}
}
}
//冒泡排序
int findpivot(int i, int j) //返回a[i],a[j]总较大关键字的下标,若全相同则返回0
{
int firstkey = a[i].key;
int k;
for (k = i + 1; k <= j; k++) //从左到右查找不同的关键字
{
if (a[k].key > firstkey)
{
return k;
}
else if (a[k].key < firstkey)
{
return i;
}
}
return 0;
}
//找到数组a基准元素下标
int partition(int i, int j, int pivot)
{
int l, r;
do
{
for (l = i; a[l].key < pivot; l++);
for (r = j; a[r].key >= pivot; r--);
if (l < r)
{
swap(a[l], a[r]);
}
} while (l <= r);
return l;
}
//根据关键字划分两个序列
void quicksort(int i, int j)
{
int pivot;
int k; //关键字大于等于pivot的记录在序列中的起始下标
int pivotindex; //关键字为pivot的记录在数组A中的下标
pivotindex = findpivot(i, j);
if (pivotindex != 0)
{
pivot = a[pivotindex].key;
k = partition(i, j, pivot);
quicksort(i, k - 1);
quicksort(k, j);
}
}
//对数组a的元素a[i]......a[j]进行快速排序
void selectsort(int n)
{
int lowkey; //当前最小关键字
int i, j, lowindex; //当前最小关键字的下标
for (i = 1; i < n; i++) //在A[i…n]中选择最小的关键字,与A[i]交换
{
lowindex = i;
lowkey = a[i].key;
for (j = i + 1; j <= n; j++)
{
if (a[j].key < lowkey) //用当前最小关键字与每个关键字比较
{
lowkey = a[j].key;
lowindex = j;
}
}
swap(a[i], a[lowindex]);
}
}
//直接选择排序
void pushdown(int first, int last)
{
int r;
r = first; //r是被下推到的适当位置,初始值为根first
while (r <= last / 2)
{
if ((r == last / 2) && (last % 2 == 0)) //r有一个儿子在2*r上且为左儿子
{
if (a[r].key < a[2 * r].key) //如果儿子比自己大就交换
{
swap(a[r], a[2 * r]);
}
r = last; //结束循环
}
else if ((a[r].key < a[2 * r].key) && (a[2 * r].key >= a[2 * r + 1].key))
{
swap(a[r], a[2 * r]); //左孩子比右孩子大,与左孩子交换
r = 2 * r;
}
else if ((a[r].key < a[2 * r + 1].key) && (a[2 * r + 1].key > a[2 * r].key))
{
swap(a[r], a[2 * r + 1]); //右孩子比左孩子大,与右孩子交换
r = 2 * r + 1;
}
else
r = last;
}
}
//按照最大堆整理堆
void heapsort(int n)
{
int i;
for (i = n / 2; i >= 1; i--) //初始建堆,从最右非叶结点开始
{
pushdown(i, n); //整理堆,把以i为根,最大下标的叶为n
}
for (i = n; i >= 2; i--)
{
swap(a[1], a[i]); //堆顶与当前堆中的下标最大的叶结点交换
pushdown(1, i - 1); //整理堆把以1为根,最大叶下标为i - 1的完全二元树整理成堆
}
}
//堆排序
void insertsort(int n)
{
int i, j;
a[0].key = -INT_MAX;
for (i = 1; i <= n; i++)
{
j = i;
while (a[j].key < a[j - 1].key)
{
swap(a[j], a[j - 1]);
j = j - 1;
}
}
}
//插入排序
void shellsort(int n)
{
int i, j, d;
for (d = n / 2; d >= 1; d = d / 2)
{
for (i = d + 1; i <= n; i++) //将A[i]插入到所属的子序列中
{
a[0].key = a[i].key; //暂存待插入记录
j = i - d; //j指向所属子序列的最后一个记录
while (j > 0 && a[0].key < a[j].key)
{
a[j + d] = a[j]; //记录后移d个位置
j = j - d; //比较同一子序列的前一个记录
}
a[j + d] = a[0];
}
}
}
//希尔排序
void print()
{
for (int i = 1; i <= max-1; i++)
{
printf("%d ",a[i].key);
}
}
//打印排序数组
void merge(int s, int m, int t, records a[], records b[])
{
int i = s, j = m + 1, k = s; //置初值
while (i <= m && j <= t) //两个序列非空时,取小者输出到b[k]上
b[k++] = (a[i].key <= a[j].key) ? a[i++] : a[j++];
while (i <= m) //若第一个子序列非空(未处理完),则复制剩余部分到b
b[k++] = a[i++];
while (j <= t) // 若第二个子序列非空(未处理完),则复制剩余部分到b
b[k++] = a[j++];
}
//将有序序列A[s],…,A[m]和A[m+1],…,A[t]合并为一个有序序列B[s],…,B[t]
void mergepass(int n, int h, records a[], records b[])
{
int i, t;
for (i = 1; i + 2 * h - 1 <= n; i += 2 * h)
{
merge(i, i + h - 1, i + 2 * h - 1, a, b); //归并长度为h的两个有序子序列
}
if (i + h - 1 < n) //尚有两个子序列,其中最后一个长度小于h
{
merge(i, i + h - 1, n, a, b); //归并最后两个子序列
}
else //若i<= n且i+h-1>= n 时,则剩余一个子序列轮空,直接复制
{
for (t = i; t <= n; t++)
{
b[t] = a[t];
}
}
}
//把a长度为h的相邻序列归并成长度为2h的序列
void mergesort(int n)
{
int h = 1; //当前归并子序列的长度,初始为1
records b[max];
while (h < n)
{
mergepass(n, h, a, b);
h = 2 * h;
mergepass(n, h, b, a); //a、b互换位置
h = 2 * h;
}
}
//二路归并排序
void menu()
{
printf("-----------------\n");
printf("1.冒泡排序\n");
printf("2.快速排序\n");
printf("3.选择排序\n");
printf("4.堆排序\n");
printf("5.插入排序\n");
printf("6.希尔排序\n");
printf("7.二路归并排序\n");
printf("-----------------\n");
}
//菜单
int main()
{
int m;
menu();
while (1)
{
printf("请输入你的操作:");
scanf(" %d", &m);
switch (m)
{
case 1:
printf("待排序数列为:\n");
createtest(a);
print();
printf("\n");
printf("冒泡排序后的数列为:\n");
bubblesort(max - 1);
print();
printf("\n\n");
break;
case 2:
printf("待排序数列为:\n");
createtest(a);
print();
printf("\n");
printf("快速排序后的数列为:\n");
quicksort(1, max - 1);
print();
printf("\n\n");
break;
case 3:
printf("待排序数列为:\n");
createtest(a);
print();
printf("\n");
printf("选择排序后的数列为:\n");
selectsort(max - 1);
print();
printf("\n\n");
break;
case 4:
printf("待排序数列为:\n");
createtest(a);
print();
printf("\n");
printf("堆排序后的数列为:\n");
heapsort(max - 1);
print();
printf("\n\n");
break;
case 5:
printf("待排序数列为:\n");
createtest(a);
print();
printf("\n");
printf("插入排序后的数列为:\n");
insertsort(max-1);
print();
printf("\n\n");
break;
case 6:
printf("待排序数列为:\n");
createtest(a);
print();
printf("\n");
printf("希尔排序后的数列为:\n");
shellsort(max - 1);
print();
printf("\n\n");
break;
case 7:
printf("待排序数列为:\n");
createtest(a);
print();
printf("\n");
printf("二路归并排序后的数列为:\n");
mergesort(max-1);
print();
printf("\n\n");
break;
default:
printf("请输入正确操作:\n\n");
break;
}
}
return 0;
} | true |
4bff4f7cacaee3c591b3c50a78132e05de65ee71 | C++ | Rav263/Contests_4_2019 | /contest_7/dim.cpp | UTF-8 | 920 | 3.0625 | 3 | [] | no_license | #include <complex>
#include <vector>
#include <array>
namespace Equations
{
template <class T>
std::pair<bool, std::vector<std::complex<T>>> quadratic(const std::array<std::complex<T>, 3> &v)
{
std::pair<bool, std::vector<std::complex<T>>> res;
if (v[1] == std::complex<T>() && v[2] == std::complex<T>() && v[0] == std::complex<T>()) {
res.first = false;
return res;
}
res.first = true;
if (v[1] == std::complex<T>() && v[2] == std::complex<T>()) {
return res;
}
if (v[2] == std::complex<T>()) {
res.second.push_back(-v[0] / v[1]);
} else {
std::complex<T> sd = sqrt(v[1] * v[1] - v[0] * v[2] * ((T) 4.0));
res.second.push_back((-v[1] - sd) / (((T) 2.0) * v[2]));
res.second.push_back((-v[1] + sd) / (((T) 2.0) * v[2]));
}
return res;
}
}
| true |
107f757eb647a069abbc060e8d95eccadb307fef | C++ | per1234/ArduinoUnifiedLog | /LogModule.h | UTF-8 | 317 | 2.59375 | 3 | [] | no_license | #ifndef LogModule_h
#define LogModule_h
#include <Arduino.h>
class LogModule {
private:
int outputMinimumLogLevel = 0;
public:
int getMinimumLogLevel() { return outputMinimumLogLevel; }
void setMinimumLogLevel(int min) { outputMinimumLogLevel = min; }
virtual void write_message(String message);
};
#endif
| true |
f230ac31d42ecaafe9a3221fcff995aa0f994ab1 | C++ | CAHeap/CAHeap | /src/CPU/tests/testparam.cpp | UTF-8 | 1,706 | 2.671875 | 3 | [] | no_license | /*
* test how d affect the performance
*/
#include <stdio.h>
#include <stdlib.h>
#include "../AHeap/AHeap.h"
#include "../common/IO.h"
#include "../common/metric.h"
#include "../tasks/AHeap_CountingTasks.h"
#define MAX_FLOW_NUM 16000
/*
* 1. range d1 from 1 to largest size
* d2 is fixed to 4
* 2. range d2 from 1 to largest size
* d1 is fixed to 4
*
* parameters:
* M: size of 1st layer
* tuples: input file containing packets
* dstFile: output file to store the performance
*/
void test(int M, vector<string>& tuples, int N = MAX_FLOW_NUM){
int m;
int d1 = 2, d2 = 2;
// for(int d1 = 1; d1 <= 4; ++d1){
// for(int d2 = 1; d2 <= 10; ++d2){
m = M / (pow(2, d1 + d2) - 1);
// m = 10660;
printf("d1=%d, d2=%d, m=%d\n", d1, d2, m);
AHeap* aheap = new AHeap(m, 21, -1);
aheap->set_keylen(13);
FlowsizePerform fsp = accTest(aheap, tuples, N);
delete aheap;
printf("accuracy: %lf, AAE: %lf, ARE: %lf, load_factor: %lf\n\n",
fsp.accuracy, fsp.aae, fsp.are, fsp.load_factor);
AHeap* aheap = new AHeap(d1, d2, m);
fsp = accTest(aheap, tuples, N);
delete aheap;
printf("accuracy: %lf, AAE: %lf, ARE: %lf, load_factor: %lf\n\n",
fsp.accuracy, fsp.aae, fsp.are, fsp.load_factor);
// }
// }
}
/*
* ./testparam srcFile M dstFile
* M is the size of first layer
*/
int main(int argc, const char* argv[]){
if(argc != 4){
printf("\t./testparam srcFile M N\n\t\"srcFile\": file containing 5-tuples\n\t\"M\": maximum buckets number\n\t\"N\": maximum number of distinct flows\n");
exit(1);
}
vector<string> tuples;
Read5Tuples<KEY_LEN>(argv[1], tuples);
int M = atoi(argv[2]);
int N = atoi(argv[3]);
test(M, tuples, N);
}
| true |
bf019a10e31b55de53bb79255171d84bcb9429ae | C++ | yuna-s/yunatcoder | /AOJ/introduction1/cardGame.cpp | UTF-8 | 511 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <locale>
#include <vector>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
int main()
{
int n, p1 = 0, p2 = 0;
cin >> n;
rep(i, n)
{
string taro, hanako;
cin >> taro >> hanako;
if (taro == hanako)
{
p1++;
p2++;
}
else if (taro > hanako)
{
p1 += 3;
}
else
p2 += 3;
}
cout << p1 << " " << p2 << endl;
} | true |
2b3d2f133787499e4517814870e0cb9de16906a6 | C++ | braunm/CppADutils | /inst/include/cppad_atomic/dlogitbeta_log_at.h | UTF-8 | 2,031 | 2.53125 | 3 | [] | no_license | #ifndef __DLOGITBETA_LOG_AT
#define __DLOGITBETA_LOG_AT
#include <cppad_atomic/mb_atomic.h>
// NOTE: This is a NORMALIZED incomplete beta function.
// Equivalent to the cdf of a beta(z;a,b) distribution
using Eigen::MatrixBase;
using R::digamma;
using R::trigamma;
class dlogitbeta_log_cl {
public:
template<typename TX>
void eval(const MatrixBase<TX>& x,
double& f) {
const double p = exp(x(0) - R::log1pexp(x(0)));
const double a = x(1);
const double b = x(2);
f = R::dbeta(p, a, b, 1) + log(p) + log(1-p);
}
template<typename TX, typename TD>
void eval(const MatrixBase<TX>& x,
double& f,
const MatrixBase<TD>& df_) {
MatrixBase<TD>& df = const_cast<MatrixBase<TD>&>(df_);
const double p = exp(x(0) - R::log1pexp(x(0)));
const double a = x(1);
const double b = x(2);
const double psi_ab = digamma(a+b);
f = R::dbeta(p, a, b, 1) + log(p) + log(1-p);
df(0) = (a+b)*(1-p)-b;
df(1) = log(p) - digamma(a) + psi_ab;
df(2) = log(1-p)- digamma(b) + psi_ab;
}
template<typename TX, typename TD, typename TH>
void eval(const MatrixBase<TX>& x,
double& f,
const MatrixBase<TD>& df_,
const MatrixBase<TH>& hess_) {
MatrixBase<TD>& df = const_cast<MatrixBase<TD>&>(df_);
MatrixBase<TH>& hess = const_cast<MatrixBase<TH>&>(hess_);
const double p = exp(x(0) - R::log1pexp(x(0)));
const double a = x(1);
const double b = x(2);
const double psi_ab = digamma(a+b);
const double psi_1_ab = trigamma(a+b);
f = R::dbeta(p, a, b, 1) + log(p) + log(1-p);
df(0) = (a+b)*(1-p)-b;
df(1) = log(p) - digamma(a) + psi_ab;
df(2) = log(1-p)- digamma(b) + psi_ab;
hess(0,0) = -(a+b) * p * (1-p);
hess(1,1) = psi_1_ab - trigamma(a);
hess(2,2) = psi_1_ab - trigamma(b);
hess(0,1) = 1-p;
hess(1,0) = hess(0,1);
hess(0,2) = -p;
hess(2,0) = hess(0,2);
hess(1,2) = psi_1_ab;
hess(2,1) = hess(1,2);
}
};
#endif
| true |
8b760648db52e54bf2f4eca87064177d5060a48c | C++ | ablondal/comp-prog | /Real_Contests/CCPC2020/Dodec.cpp | UTF-8 | 1,266 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
#define max(a,b) ((a>b)?a:b)
#define min(a,b) ((a<b)?a:b)
// DONE
map <string,int> ntone = {
{"C",0},
{"C#",1},
{"D",2},
{"D#",3},
{"E",4},
{"F",5},
{"F#",6},
{"G",7},
{"G#",8},
{"A",9},
{"A#",10},
{"B",11}
};
int main(){
int notes;
cin >> notes;
string no;
vector <int> seq1(notes);
vector <int> seq2(notes);
for(int i=0; i<notes; ++i){
cin >> no;
seq1[i] = ntone[no];
}
for(int i=0; i<notes; ++i){
cin >> no;
seq2[i] = ntone[no];
}
// Test Transposition
bool T = true;
for(int i=0;i<12;++i){
T = true;
for(int j=0; j<notes; ++j){
if( (seq1[j]+i)%12 != seq2[j] ){
T = false;
break;
}
}
if (T){
cout << "Transposition" << endl;
return 0;
}
}
// Test Retrograde
bool R = true;
for(int i=0; i<notes; ++i){
if (seq1[i] != seq2[notes-1-i]){
R = false;
break;
}
}
if (R){
cout << "Retrograde" << endl;
return 0;
}
// Test Inversion
bool I = true;
for(int i=0; i<notes; ++i){
if ( (seq1[0]-seq1[i]+12)%12 != (seq2[i]-seq2[0]+12)%12 ){
I = false;
break;
}
}
if (I){
cout << "Inversion" << endl;
return 0;
}
cout << "Nonsense" << endl;
}
| true |
0738e6b22ae6e654891ce7583e5bb15a06a86703 | C++ | SarahWuTX/DataStructureCourseDesign | /P10/P10_1652677_吴桐欣.h | UTF-8 | 11,323 | 3.53125 | 4 | [] | no_license | //
// P10_1652677_吴桐欣.h
//
#ifndef P10_1652677_____h
#define P10_1652677_____h
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
void SWAP(int& a, int& b);//交换函数
void BubbleSort(vector<int> list);//冒泡排序函数
void SelectSort(vector<int> list);//选择排序函数
void InsertSort(vector<int> list);//直接插入排序函数
void ShellSort(vector<int> list);//希尔排序函数
void QuickSort(vector<int> list, const int left, const int right, int& count_comp, int& count_swap);
//快速排序函数
int& median3(vector<int>& list, const int left, const int right, int& count_comp, int& count_swap);
//快速排序-三者取中函数
int Partition(vector<int>& list, const int left, const int right, int& count_comp, int& count_swap);
//快速排序-一趟划分函数
void siftDown(vector<int>& heap, int s, int m);//堆排序-从s到m自顶向下调整最大堆
void HeapSort(vector<int> list);//堆排序函数
void Merge(vector<int>& list, const int left, const int mid, const int right, int& count_comp, int& count_swap);//归并排序-合并
void MergeSort(vector<int>& list, int left, int right, int& count_comp, int& count_swap);//归并排序函数
void RadixSort(vector<int> list);//基数排序函数
//交换函数
void SWAP(int& a, int& b){
int temp=a;
a=b;
b=temp;
}
//冒泡排序
void BubbleSort(vector<int> list){
long n=list.size();//元素个数
int count_comp=0;//记录比较次数
int count_swap=0;//记录交换次数
clock_t start=clock();
for (int i=0; i<n-1; i++) {
bool exchange=false;//是否产生交换
for (long j=n-1; j>0; j--) {
count_comp++;
if (list[j-1]>list[j]) {
//发现逆序,进行交换
SWAP(list[j], list[j-1]);
count_swap++;
exchange = true;
}
}
if (!exchange) {
//本轮不产生交换,排序完毕
break;
}
}
clock_t end=clock();
cout<<"冒泡排序所用时间:"<<(float)(end-start)/CLOCKS_PER_SEC<<" 秒"<<endl;
cout<<"冒泡排序比较次数:"<<count_comp<<endl;
cout<<"冒泡排序交换次数:"<<count_swap<<endl<<endl;
}
//选择排序
void SelectSort(vector<int> list){
long n=list.size();//元素个数
int count_comp=0;//记录比较次数
int count_swap=0;//记录交换次数
clock_t start=clock();
for (int i=0; i<n; i++) {
int min_i=i;//最小元素的序号
for (int j=i+1; j<n; j++) {
count_comp++;
if (list[min_i]>list[j]) {min_i = j;}
}
//交换
SWAP(list[i], list[min_i]);
count_swap++;
}
clock_t end=clock();
cout<<"选择排序所用时间:"<<(float)(end-start)/CLOCKS_PER_SEC<<" 秒"<<endl;
cout<<"选择排序比较次数:"<<count_comp<<endl;
cout<<"选择排序交换次数:"<<count_swap<<endl<<endl;
}
//直接插入排序
void InsertSort(vector<int> list){
long n=list.size();//元素个数
int count_comp=0;//记录比较次数
int count_swap=0;//记录交换次数
int temp;//暂存要插入的元素
clock_t start=clock();
for (int i=1; i<n; i++) {
//获取要插入的元素
temp=list[i];
//从后向前一个个比较
for (int j=i-1; j>=0; j--) {
count_comp++;
if (list[j]>temp) {
//将前一个元素后移
list[j+1]=list[j];
} else {
//若前面数小于temp,则找到要插入的位置
list[j+1]=temp;
break;
}
}
}
count_swap=count_comp;//每次比较都会修改数据,因此交换次数与比较次数相等
clock_t end=clock();
cout<<"直接插入排序所用时间:"<<(float)(end-start)/CLOCKS_PER_SEC<<" 秒"<<endl;
cout<<"直接插入排序比较次数:"<<count_comp<<endl;
cout<<"直接插入排序交换次数:"<<count_swap<<endl<<endl;
}
//希尔排序
void ShellSort(vector<int> list){
int count_comp=0;//记录比较次数
int count_swap=0;//记录交换次数
long n=list.size();//元素个数
int gap=(int)n;//增量
clock_t start=clock();
do{
gap = gap/3+1;//计算增量
for (int i=gap; i<n; i+=gap) {
count_comp++;
//若在子序列中发现逆序
if (list[i-gap]>list[i]) {
int temp=list[i];
//用直接插入法,从后向前比较
for (int j=i-gap; ; j-=gap) {
count_comp++;
if (list[j]<=temp) {
//小于等于temp,找到temp插入位置
list[j+gap]=temp;
count_swap++;
break;
} else {
//若比temp大,则后移一位
list[j+gap]=list[j];
count_swap++;
}
}
}
}
} while (gap>1);
clock_t end=clock();
cout<<"希尔排序所用时间:"<<(float)(end-start)/CLOCKS_PER_SEC<<" 秒"<<endl;
cout<<"希尔排序比较次数:"<<count_comp<<endl;
cout<<"希尔排序交换次数:"<<count_swap<<endl<<endl;
}
//快速排序-三者取中
int& median3(vector<int>& list, const int left, const int right, int& count_comp, int& count_swap){
int mid=(left+right)/2;
int k=left;
if (list[mid]<list[k]) {k=mid;}
if (list[right]<list[k]) {k=right;}//left,mid,right三者选最小
if (k!=left) {
SWAP(list[k], list[left]);
}//把最小值移到left位置
if (mid!=right && list[mid]<list[right]) {
SWAP(list[right], list[mid]);
}//把中间值,即基准,移到right位置
return list[right];
}
//快速排序-一趟划分
int Partition(vector<int>& list, const int left, const int right, int& count_comp, int& count_swap){
int i=left;
int j=right-1;
if (left<right) {
int pivot=median3(list, left, right, count_comp, count_swap);
for (; ; ) {
while (i<j && list[i]<pivot) {i++;count_comp++;}
while (i<j && list[j]>pivot) {j--;count_comp++;}
if (i<j) {
SWAP(list[i], list[j]);//交换list[i],list[j]的值
count_swap++;
i++;
j--;
} else {
break;
}
}
if (list[i]>pivot) {
list[right]=list[i];
list[i]=pivot;
count_swap++;
count_comp++;
}
}
return i;
}
//快速排序
void QuickSort(vector<int> list, const int left, const int right, int& count_comp, int& count_swap){
if (left==right) {}
else if (left==right-1) {
count_comp++;
if (list[left]>list[right]) {
SWAP(list[left], list[right]);
count_swap++;
}
}
else {
int pivotpos=Partition(list, left, right, count_comp, count_swap);//划分
QuickSort(list, left, pivotpos-1, count_comp, count_swap);
QuickSort(list, pivotpos+1, right, count_comp, count_swap);
}
}
//堆排序-从s到m自顶向下调整
void siftDown(vector<int>& heap, int s, int m, int& count_comp, int& count_swap){
int i=s;
int j=2*i+1;//j是i的左子女
int temp=heap[i];
while (j<=m) {
count_comp++;
if (j<m && heap[j]<heap[j+1]) {j++;}//j指向两子女中最大者
count_comp++;
if (temp>=heap[j]){
break;
} else {
count_swap++;
heap[i]=heap[j];
i=j;
j=2*i+1;//i降到子女的位置
}
}
heap[i]=temp;
count_swap++;
}
//堆排序
void HeapSort(vector<int> list){
int count_comp=0;//记录比较次数
int count_swap=0;//记录交换次数
int n=(int)list.size();//元素个数
clock_t start=clock();
for (int i=(n-2)/2; i>=0; i--) {
siftDown(list, i, n-1, count_comp, count_swap);
}
for (int i=n-1; i>=0; i--) {
SWAP(list[0], list[i]);
count_swap++;
siftDown(list, 0, i-1, count_comp, count_swap);
}
clock_t end=clock();
cout<<"堆排序所用时间:"<<(float)(end-start)/CLOCKS_PER_SEC<<" 秒"<<endl;
cout<<"堆排序比较次数:"<<count_comp<<endl;
cout<<"堆排序交换次数:"<<count_swap<<endl<<endl;
}
//归并排序-合并
void Merge(vector<int>& list, const int left, const int mid, const int right, int& count_comp, int& count_swap){
vector<int> tempList(list);
int s1=left,s2=mid+1,t=left;//s1,s2是检测指针,t是存放指针
while(s1<=mid && s2<=right){
count_comp++;
count_swap++;
if (tempList[s1]<=tempList[s2]) {
list[t++]=tempList[s1++];
} else {
list[t++]=tempList[s2++];
}
}
while (s1<=mid) {
list[t++]=tempList[s1++];
count_swap++;
}
while (s2<=right) {
list[t++]=tempList[s2++];
count_swap++;
}
}
//归并排序函数
void MergeSort(vector<int>& list, int left, int right, int& count_comp, int& count_swap){
if (left>=right) {
return;
}
int mid=(left+right)/2;
MergeSort(list, left, mid, count_comp, count_swap);//左子序列排序
MergeSort(list, mid+1, right, count_comp, count_swap);//右子序列排序
Merge(list, left, mid, right, count_comp, count_swap);//合并左右子序列
}
//基数排序
void RadixSort(vector<int> list){
int n=(int)list.size();//元素个数
int count_comp=0;//记录比较次数
int count_swap=0;//记录交换次数
vector<int> tempList(list);
clock_t start=clock();
for (long place=1; ; place*=10) {
int k=0;//存放指针
bool change=false;
for (int radix=0;; radix++) {
for (int i=0; i<tempList.size();i++) {
count_comp++;
if ((tempList[i]%(10*place))/place == radix) {
if (list[k]!=tempList[i]) {
list[k]=tempList[i];//放入结果列中
count_swap++;
change=true;
}
k++;//存放指针移至下一个位置
if (i!=tempList.size()-1) {
//将此数移到列尾
int temp_i=i;
while(temp_i!=tempList.size()-1){
tempList[temp_i]=tempList[temp_i+1];
temp_i++;
}
i--;//要使下一步从i位置开始
}
tempList.pop_back();
}
}
if (radix>9 || k>=n) {
break;
}
}
if (change==false) {
break;
}
tempList=list;
}
clock_t end=clock();
cout<<"基数排序所用时间:"<<(float)(end-start)/CLOCKS_PER_SEC<<" 秒"<<endl;
cout<<"基数排序比较次数:"<<count_comp<<endl;
cout<<"基数排序交换次数:"<<count_swap<<endl<<endl;
}
#endif /* P10_1652677_____h */
| true |
4be73e51be5520f92cecfd1de481b91507252a67 | C++ | dev-zero/quantum3body | /time_evolutions.hh | UTF-8 | 3,735 | 2.984375 | 3 | [] | no_license | /* vim: set sw=4 sts=4 ft=cpp et foldmethod=syntax : */
/*
* Copyright (c) 2011 Tiziano Müller <tm@dev-zero.ch>
* Christian Reinhardt
*
*
*/
#ifndef TIME_EVOLUTIONS_HH
#define TIME_EVOLUTIONS_HH
#include "two_dim_spo.hh"
#include <limits>
/**
* This is the "default" time evolution which is being used for
* to simulated a particle in a harmonic or flat potential.
*/
struct DefaultTimeEvolution :
public TimeEvolution
{
/**
* Set this to false if you want a flat zero potential
* instead of the default harmonic potential.
*/
bool useHarmonicPotential;
DefaultTimeEvolution() :
useHarmonicPotential(true)
{
}
/**
* Returns the value of the potential at a given (x,y).
* This will not be called by the SPO code, only by the
* evolve functions defined in this class. It has been
* written explicitly to ease the understanding
*/
inline double V(const double& x, const double& y) const
{
if (useHarmonicPotential)
return 0.5*(x*x+y*y);
else
return 0.0;
}
/**
* The time evolution in x-y-coordinates (aka "spatial evolution").
* The factor 0.5 in the implementation stems from the SPO method.
*/
complex x_y_evolve(const double& x, const double& y, const double& dt) const
{
return exp(-0.5 * V(x, y) * dt * I);
}
/**
* The time evolution in kx-y-coordinates (aka "momentum evolution for x").
*/
complex kx_y_evolve(const double& kx, const double& /* y */, const double& dt) const
{
return exp(-0.5 * kx*kx * dt * I);
}
/**
* The time evolution in x-ky-coordinates (aka "momentum evolution for y").
*/
complex x_ky_evolve(const double& /* x */, const double& ky, const double& dt) const
{
return exp(-0.5 * ky*ky * dt * I);
}
};
/**
* This is the quantum restricted 3-body time evolution.
* For a theoretical understanding, please consult the separate theoretical
* description.
*/
struct Quantum3BodyTimeEvolution :
public TimeEvolution
{
/**
* This parameter is the epsilon in the formula for the potential of the
* restricted 3-body problem. It is initially set to 0.2.
* Setting the initial conditions to (0,0,0,2*pi) for (x,y,px,py) should
* give a bound orbit around the primary body at (x,y)=(0.2,0).
*/
double e;
Quantum3BodyTimeEvolution() :
e(0.2)
{
}
/**
* This is the same potential as for the restricted 3-body problem.
*/
inline double V(const double& x, const double& y) const
{
double a(sqrt((x+e)*(x+e) + y*y));
double b(sqrt((x-1.0+e)*(x-1.0+e) + y*y));
if (fabs(a) < std::numeric_limits<double>::epsilon())
a = std::numeric_limits<double>::epsilon();
if (fabs(b) < std::numeric_limits<double>::epsilon())
b = std::numeric_limits<double>::epsilon();
return -(1.0-e)/a - e/b;
}
/**
* The time evolution in kx-y-coordinates (aka "momentum evolution for x").
*/
complex x_y_evolve(const double& x, const double& y, const double& dt) const
{
return exp(-0.5 * V(x, y) * dt * I);
}
/**
* The time evolution in kx-y-coordinates (aka "momentum evolution for x").
*/
complex kx_y_evolve(const double& kx, const double& y, const double& dt) const
{
return exp(-I*(0.5*kx*kx - y*kx)*dt);
}
/**
* The time evolution in x-ky-coordinates (aka "momentum evolution for y").
*/
complex x_ky_evolve(const double& x, const double& ky, const double& dt) const
{
return exp(-I*(0.5*ky*ky + x*ky)*dt);
}
};
#endif // TIME_EVOLUTIONS_HH
| true |
f31fa66e66a04ff31b1002b69d450fcffd62c1c8 | C++ | harini9804/operating_systems | /processclass.h | UTF-8 | 898 | 2.59375 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<vector>
class process{
public:
int pid;
int at;
int bt;
int ct,tat,wt;
void input(int id);
void output();
bool operator < (const process& obj) const {
if(at == obj.at){
return pid < obj.pid;
}else
return at < obj.at;
}
};
class processPri: public process{
public:
int pri;
void output();
};
class processRR: public process{
public:
float resp_ratio;
void output();
};
using namespace std;
class scheduler{
public:
void fcfs(vector<process> &ProcList, int n);
void sjf(vector<process> &ProcList, int n);
void srt(vector<process> &ProcList, int n);
void roundrobin(vector<process> &ProcList, int n);
void priority_npe(vector<process> &procList, int n);
void priority_pe(vector<process> &ProcList, int n);
void hrrn(vector<process> &procList, int n);
};
| true |
c5950ee7f1573cc82e0f2a67124a4343c6740af6 | C++ | mecha-rm/GDW_Y2-PJT-repos | /GDW_Y2 - CNZ/src/cherry/objects/Primitive.cpp | UTF-8 | 3,360 | 3 | 3 | [] | no_license | #include "Primitive.h"
#include "..\lights\LightManager.h"
// constructor
cherry::Primitive::Primitive() : cherry::Object()
{
}
// copy constructor.
// cherry::Primitive::Primitive(const cherry::Primitive& prim) : Object(prim)
// {
// baseColor = prim.GetColor();
// }
// destructor
cherry::Primitive::~Primitive()
{
// delete[] indices; // TODO: fix deletions
}
// gets the base colour of the primitive.
cherry::Vec4 cherry::Primitive::GetColor() const { return color; }
// generates a default material that has no lighting.
cherry::Material::Sptr cherry::Primitive::GenerateDefaultMaterial()
{
return Material::GenerateDefaultMaterial();
}
// generates the default lighting material for the primitive.
cherry::Material::Sptr cherry::Primitive::GenerateLightingMaterial()
{
// generates with no light list to fill in values.
return Material::GenerateLightingMaterialStatic(nullptr);
}
// generates the default lighting material for the primitive.
cherry::Material::Sptr cherry::Primitive::GenerateLightingMaterial(cherry::LightList* ll)
{
// generates with light list to fill in values.
return Material::GenerateLightingMaterialStatic(ll);
}
// calculates the normals of the primitive.
void cherry::Primitive::CalculateNormals()
{
// dynamic array of surface normals.
// float* surfaceNormals = new float[round(indicesTotal / 3.0F)];
unsigned int* vertexNormals = new unsigned int[verticesTotal] {0}; // gets the vertex normals
// setting up the normals
glm::vec3 uVec;
glm::vec3 vVec;
glm::vec3 uvVec;
// goes through each triangle and calculates the normal
for (int i = 0; i < indicesTotal; i += 3)
{
glm::vec3 tempVec;
// u = p2 - p1
uVec = vertices[indices[i + 1]].Position - vertices[indices[i]].Position;
// v = p3 - p1
vVec = vertices[indices[i + 2]].Position - vertices[indices[i]].Position;
// gets the normal vector, which uses cross product.
// uvVec = uVec.cross(vVec);
uvVec.x = uVec.y * vVec.z - uVec.z * vVec.y;
uvVec.y = uVec.z * vVec.x - uVec.x * vVec.z;
uvVec.z = uVec.x * vVec.y - uVec.y * vVec.x;
// saves the normals, and how many faces connect to the given vertex
vertices[indices[i]].Normal += uvVec;
vertexNormals[indices[i]]++;
vertices[indices[i + 1]].Normal += uvVec;
vertexNormals[indices[i + 1]]++;
vertices[indices[i + 2]].Normal += uvVec;
vertexNormals[indices[i + 2]]++;
}
// averages and normalizes each vertex normal.
for (int i = 0; i < verticesTotal; i++)
{
glm::vec3 x = vertices[i].Normal;
int y = vertexNormals[i];
// gets the average of the normals
vertices[i].Normal = glm::vec3(
vertices[i].Normal.x / vertexNormals[i],
vertices[i].Normal.y / vertexNormals[i],
vertices[i].Normal.z / vertexNormals[i]);
x = vertices[i].Normal;
// normalizes the normal (v / ||v||)
vertices[i].Normal = glm::vec3(
vertices[i].Normal.x / vertices[i].Normal.length(),
vertices[i].Normal.y / vertices[i].Normal.length(),
vertices[i].Normal.z / vertices[i].Normal.length());
x = vertices[i].Normal;
y = vertexNormals[i];
}
}
// flip the normals
void cherry::Primitive::InvertNormals()
{
if (vertices == nullptr)
return;
for (int i = 0; i < verticesTotal; i++)
vertices[i].Normal *= -1;
}
| true |
5c3f1777ed4feaa60a152787a0ce0d849b302abb | C++ | DejavuLeo/PyCAD | /CAD/LineArcDrawing.h | UTF-8 | 1,594 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | // LineArcDrawing.h
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include "Drawing.h"
enum EnumDrawingMode{
LineDrawingMode,
ArcDrawingMode,
ILineDrawingMode,
CircleDrawingMode,
};
enum EnumCircleDrawingMode{
CentreAndPointCircleMode,
ThreePointsCircleMode,
TwoPointsCircleMode,
CentreAndRadiusCircleMode // only one click needed ( edit radius in the properties before clicking)
};
class LineArcDrawing: public Drawing{
private:
bool m_A_down; // is key A pressed
HeeksObj* m_container;
bool m_add_to_sketch;
// Drawing's virtual functions
bool calculate_item(DigitizedPoint &end);
void set_previous_direction();
int number_of_steps();
int step_to_go_to_after_last_step();
bool is_an_add_level(int level);
HeeksObj* GetOwnerForDrawingObjects();
void AddPoint();
public:
// static wxCursor m_cursor_start;
// static wxCursor m_cursor_end;
EnumDrawingMode drawing_mode;
std::list<EnumDrawingMode> m_save_drawing_mode;
double radius_for_circle;
EnumCircleDrawingMode circle_mode;
bool m_previous_direction_set;
Point3d m_previous_direction;
LineArcDrawing(void);
virtual ~LineArcDrawing(void);
// InputMode's virtual functions
const wchar_t* GetTitle();
bool OnKeyDown(KeyCode key_code);
bool OnKeyUp(KeyCode key_code);
void set_cursor(void);
void GetProperties(std::list<Property *> *list);
void OnModeChange(void);
void EndDrawing(); // won't stay here; just a test
};
extern LineArcDrawing line_strip;
| true |
4b7eeee395b01b1d9091656c52a6d0f599c826c1 | C++ | Daga2001/Warshall-s_Algorithm | /main.cpp | UTF-8 | 2,235 | 3.390625 | 3 | [] | no_license | /*
File: main.cpp
Author: anonymous.
creation date: 2021-04-15
last update date: 2021-04-15
Versión: 1.0
Licencia: GNU-GPL
*/
#include <iostream>
#include "Warshall.h"
#define KnowMatrix(x) warshall.knowMatrix(x);warshall.optimizeAdjacencyMatrix();cout << "This is the original matrix, called " #x << endl;
using namespace std;
int main() {
try
{
Warshall warshall;
/*
INSTRUCTIONS:
PLEASE REMEMBER THAT YOU HAVE TO DEFINE A STRING QUADRATIC MATRIX, IN OTHER WORDS, A nxn MATRIX AND SET THE MATRIX IN KNOWMATRIX FUNCTION.
INFINITY can be expressed like: "i" or "I"
IF YOU WANT TO CALCULATE THE MAIN DIAGONAL, WRITE INSTEAD OF "-" A STRING "0"
-WRITE "min" IF YOU WANT TO CALCULATE THE MINIMUM WEIGTH PATH
-WRITE "max" IF YOU WANT TO CALCULATE THE MAXIMUM WEIGTH PATH
*/
vector<vector<string>> adjacencyMatrix_7x7=
{ {"-","1","2","i","i","i","i"},
{"-","1","2","i","i","i","i"},
{"i","-","i","2","3","i","i"},
{"i","i","-","5","i","i","i"},
{"i","i","i","-","i","2","9"},
{"i","i","i","i","-","4","11"},
{"4","5","i","i","i","11","i"} };
vector<vector<string>> adjacencyMatrix_6x6=
{ {"-","1","2","i","i","i"},
{"i","-","i","2","3","i"},
{"i","i","-","5","i","i"},
{"i","i","i","-","i","2"},
{"i","i","i","i","-","4"},
{"4","5","i","i","i","-"} };
vector<vector<string>> adjacencyMatrix_5x5=
{ {"-","1","i","7","i"},
{"i","-","4","2","i"},
{"i","i","-","i","3"},
{"i","i","1","-","5"},
{"i","i","i","i","-"} };
vector<vector<string>> connectivityMatrix_4x4=
{ {"0","1","0","0"},
{"1","0","1","0"},
{"0","0","0","1"},
{"0","0","0","0"} };
vector<vector<string>> adjacencyMatrix_3x3=
{ {"0","1","0"},
{"1","0","1"},
{"0","0","0"} };
vector<vector<string>> adjacencyMatrix_2x2=
{ {"0","1"},
{"0","0"} };
//you have to set here the matrix that you want to use for warshall's algorithm.
KnowMatrix(connectivityMatrix_4x4);
warshall.makeWarshallMatrices();
}
catch(const string &message)
{
cout << "ERROR! " << message << endl;
}
} | true |
fb7ea691bdc727a1abe89da512da506d59009fad | C++ | mwstrfld/WheelOfJeopardy | /PointManager.h | UTF-8 | 2,056 | 2.96875 | 3 | [] | no_license | #pragma once
#include <QtGlobal>
#include <WheelOfJeopardyTypes.h>
// Note: This is a singleton class to only have one instance
// of the PointManager object within the application
class PointManager
{
public:
// Function call to get the instance
static PointManager* instance();
// Add points functions for each round
void addPoints( Types::Player player, Types::FirstRoundPointValue points );
void addPoints( Types::Player player, Types::SecondRoundPointValue points );
// Subtract points functions for each round
void subtractPoints( Types::Player player, Types::FirstRoundPointValue points );
void subtractPoints( Types::Player player, Types::SecondRoundPointValue points );
// Bankrupt a player
void bankrupt( Types::Player player );
// Switch rounds
void switchRounds();
// Getters for the point totals
qint32 getPlayerTotalPoints( Types::Player player );
qint32 getPlayer1TotalPoints();
qint32 getPlayer2TotalPoints();
qint32 getPlayer3TotalPoints();
// Round 1
qint32 getPlayerRound1Points( Types::Player player );
qint32 getPlayer1Round1Points();
qint32 getPlayer2Round1Points();
qint32 getPlayer3Round1Points();
// Round 2
qint32 getPlayerRound2Points( Types::Player player );
qint32 getPlayer1Round2Points();
qint32 getPlayer2Round2Points();
qint32 getPlayer3Round2Points();
// Getter for the current leader
Types::Player getCurrentWinner();
protected:
// Players point totals
// Round 1
qint32 m_player1Round1Total;
qint32 m_player2Round1Total;
qint32 m_player3Round1Total;
// Round 2
qint32 m_player1Round2Total;
qint32 m_player2Round2Total;
qint32 m_player3Round2Total;
private:
// Hidden constructors and equals operator
PointManager();
PointManager( const PointManager& );
PointManager& operator=( const PointManager& );
~PointManager();
// Round indicator
bool m_firstRound;
// Actual instance
static PointManager* m_instance;
};
| true |
aed24de3e3da7baafdb0b8a8538ac41ca1994375 | C++ | dennis5blue/WMSN | /Reasearch/OldVersion/ScheduleFactory.cpp | UTF-8 | 4,864 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <vector>
#include "ScheduleFactory.h"
using namespace std;
ScheduleFactory::ScheduleFactory(int numCameras, vector< pair<double,double> > positions, vector< vector<int> > overhearTopology):
m_numCameras(numCameras),
m_positions(positions),
m_overhearTopology(overhearTopology)
{
power = 0.125; // Watt
bandwidth = 5000000.0; // Hz
N0 = 0.000000000000001; // W/kHz ( calculate by pow(10.0,-12.0)/1000.0 )
xA = m_positions.at(0).first; //Aggregator's position
yA = m_positions.at(0).second; //Aggregator's position
//Initialize Required bytes and Channel capacity
cout << "Capacity to Aggregator: " << endl;
for (int cam=0; cam!=m_numCameras; ++cam)
{
indepRequiredBytes.push_back( m_overhearTopology.at(cam).at(cam) );
capacityToAggregator.push_back( CapacityToAggregatorCal(xA, yA, m_positions.at(cam+1).first, m_positions.at(cam+1).second, power, bandwidth, N0) );
cout << capacityToAggregator.at(cam) << " ";
}
cout << endl;
// Generate the schedule order
GenerateSchedule(m_numCameras, m_overhearTopology);
}
vector<int> ScheduleFactory::GenerateSchedule(int m_numCameras, const vector< vector<int> > m_overhearTopology)
{
//Initialize the serach range for scheduling algorithm
vector<int> searchRange;
for(int j=0; j!=m_numCameras; ++j)
searchRange.push_back(j);
//Find the first transmitted camera ( smallest transmission time m_overhearTopology[i][i]/capacityToAggregator[i] )
int firstTrans = 0;
double tempIndepTime = indepRequiredBytes.at(0)/capacityToAggregator.at(0);
for (int i=1; i!=m_numCameras; ++i)
{
if ( indepRequiredBytes.at(i)/capacityToAggregator.at(i) < indepRequiredBytes.at(i-1)/capacityToAggregator.at(i-1) )
{
firstTrans = i;
tempIndepTime = indepRequiredBytes.at(i)/capacityToAggregator.at(i);
}
}
transSchedule.push_back(firstTrans);
searchRange.at(firstTrans) = -1; // -1 means we have already scheduled this camera
for (int k=1; k!=m_numCameras; ++k)
{
int nextCamera = FindBestRefTo(m_numCameras, transSchedule.at(k-1), indepRequiredBytes, m_overhearTopology, searchRange);
// If 'nextCamera' is already scheduled, choose the camera with the smallest indep. transmission time
if (searchRange.at(nextCamera) == -1)
{
tempIndepTime = 100000000;
for (int p=0; p!=searchRange.size(); ++p)
{
if ( searchRange.at(p)!=-1 && indepRequiredBytes.at(p)/capacityToAggregator.at(p) < tempIndepTime)
{
tempIndepTime = indepRequiredBytes.at(p)/capacityToAggregator.at(p);
nextCamera = p;
}
}
}
transSchedule.push_back(nextCamera);
searchRange.at(nextCamera) = -1;
}
return transSchedule;
}
//Find camera j for camera i to reference from, so that camera i requires the least transmission bytes
//Therefore, search for the ith row of overhearTopology and find the smallest column
int ScheduleFactory::FindBestReference(int m_numCameras, int m_targetCamera, const vector< vector<int> > m_overhearTopology)
{
int tempMin = m_overhearTopology.at(m_targetCamera).at(m_targetCamera);
int tempBestRef = m_targetCamera;
for (int j=0; j!=m_numCameras; ++j)
{
if (m_overhearTopology.at(m_targetCamera).at(j) > 0 && m_overhearTopology.at(m_targetCamera).at(j) < tempMin)
{
tempMin = m_overhearTopology.at(m_targetCamera).at(j);
tempBestRef = j;
}
}
return tempBestRef;
}
//Find camera j for camera i to reference to, that is, camera j can reduce the most transmission time by overhearing camera i
int ScheduleFactory::FindBestRefTo(int m_numCameras, int m_targetCamera, const vector<int> m_indepRequiredBytes, const vector< vector<int> > m_overhearTopology, const vector<int> m_searchRange)
{
double tempReducedTime = ( m_indepRequiredBytes.at(m_targetCamera) - m_overhearTopology.at(m_targetCamera).at(m_targetCamera) ) / capacityToAggregator.at(m_targetCamera);
int tempBestRefTo = m_targetCamera;
for (int j=0; j!=m_numCameras; ++j)
{
if ( m_overhearTopology.at(j).at(m_targetCamera) != -1 )
{
double ReducedTimeForj = ( m_indepRequiredBytes.at(j) - m_overhearTopology.at(j).at(m_targetCamera) ) / capacityToAggregator.at(j);
if ( ReducedTimeForj > tempReducedTime && m_searchRange.at(j)!=-1 ) //only compare the un-scheduled cameras
{
tempReducedTime = ReducedTimeForj;
tempBestRefTo = j;
}
}
}
return tempBestRefTo;
}
double ScheduleFactory::CapacityToAggregatorCal(double m_xA, double m_yA, double m_x, double m_y, double m_power, double m_bandwidth, double m_N0)
{
double dx = m_x-m_xA;
double dy = m_y-m_yA;
double G = pow(10.0,(-13.11-4.281*log10(sqrt(dx*dx+dy*dy)/1000.0)));
double C = m_bandwidth*log2(1+(m_power*G)/m_bandwidth/m_N0);
return C;
}
void ScheduleFactory::PrintSchedule()
{
cout << "Transmission schedule: " ;
for (int i=0; i!=transSchedule.size(); ++i)
cout << transSchedule.at(i) << " ";
cout << endl;
}
| true |
04f31ae494d9d54f36338afbdf8e7cd2757ffbbb | C++ | ups100/AAL2 | /src/CrisisAlgorithmCaseGenerator.cpp | UTF-8 | 2,325 | 2.90625 | 3 | [] | no_license | /**
* @file CrisisAlgorithmCaseGenerator.cpp
*
* @brief Implementation of the Class CrisisAlgorithmNamespace::CrisisAlgorithmCaseGenerator
*
* @details Implementation of project "AAL-9-LS KRYZYS"
*
* @date 28-10-2012 18:49:19
*
* @author Krzysztof Opasiak
*/
#include "CrisisAlgorithmCaseGenerator.h"
#include "InvalidArgumentsException.h"
#include <cstdlib>
#include <ctime>
#include <vector>
#include <fstream>
using namespace std;
namespace CrisisAlgorithmNamespace {
CrisisAlgorithmCaseGenerator::CrisisAlgorithmCaseGenerator()
: m_nmbOfCities(-1), m_capitol(-1)
{
}
void CrisisAlgorithmCaseGenerator::generate(int nmbOfCities)
{
//init generator
srand((unsigned) time(0));
m_nmbOfCities = nmbOfCities;
m_capitol = rand() % m_nmbOfCities;
m_connections.reserve(nmbOfCities * 2);
m_cutPath.reserve(nmbOfCities * 2);
int tmp1 = -1;
int tmp2 = -1;
for (int i = 0; i < nmbOfCities; ++i) {
while ((tmp1 = rand() % m_nmbOfCities) == i)
;
while (((tmp2 = rand() % m_nmbOfCities) == i) || (tmp2 == tmp1))
;
m_connections.push_back(make_pair(i, tmp1));
m_connections.push_back(make_pair(i, tmp2));
}
bool *removed = new bool[m_nmbOfCities * 2];
for (int i = 0; i < m_nmbOfCities * 2; ++i) {
removed[i] = false;
}
for (int i = 0; i < m_connections.size(); ++i) {
do {
tmp1 = rand() % (m_nmbOfCities * 2);
} while (removed[tmp1]);
removed[tmp1] = true;
m_cutPath.push_back(m_connections[tmp1]);
}
delete[] removed;
}
void CrisisAlgorithmCaseGenerator::saveGeneration(std::string fileName)
{
if (m_capitol == -1)
throw InvalidArgumentsException("Case not generated yet");
ofstream out;
out.open(fileName.c_str());
if (!out.is_open())
throw InvalidArgumentsException("Unable to open this file");
out << m_nmbOfCities << endl << endl;
for (int i = 0; i < m_nmbOfCities * 2; ++i) {
out << m_connections[i].first << "\t" << m_connections[i].second
<< endl;
}
out << endl;
for (int i = 0; i < m_nmbOfCities * 2; ++i) {
out << m_cutPath[i].first << "\t" << m_cutPath[i].second << endl;
}
out << endl << m_capitol << endl;
out.close();
}
}
| true |
b35709c3273a1b5a1581fa27c4df06fb708dee2b | C++ | Ruhtra47/Treino-OBI | /Prova Nível 1 Fase 2 Turno B/recorde.cpp | UTF-8 | 290 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int r, m, l;
cin >> r >> m >> l;
if (r < m) {
cout << "RM" << endl;
} else {
cout << "*" << endl;
}
if (r < l) {
cout << "RO" << endl;
} else {
cout << "*" << endl;
}
} | true |
1ddab7fc286625a18f18a4652f9b849f24b8c7ea | C++ | baidu/openrasp | /agent/php7/third_party/yaml-cpp/include/yaml-cpp/conversion.h | UTF-8 | 2,246 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef CONVERSION_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define CONVERSION_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once
#endif
#include "yaml-cpp/null.h"
#include "yaml-cpp/traits.h"
#include <limits>
#include <string>
#include <sstream>
namespace YAML
{
// traits for conversion
template<typename T>
struct is_scalar_convertible { enum { value = is_numeric<T>::value }; };
template<> struct is_scalar_convertible<std::string> { enum { value = true }; };
template<> struct is_scalar_convertible<bool> { enum { value = true }; };
template<> struct is_scalar_convertible<_Null> { enum { value = true }; };
// actual conversion
inline bool Convert(const std::string& input, std::string& output) {
output = input;
return true;
}
YAML_CPP_API bool Convert(const std::string& input, bool& output);
YAML_CPP_API bool Convert(const std::string& input, _Null& output);
inline bool IsInfinity(const std::string& input) {
return input == ".inf" || input == ".Inf" || input == ".INF" || input == "+.inf" || input == "+.Inf" || input == "+.INF";
}
inline bool IsNegativeInfinity(const std::string& input) {
return input == "-.inf" || input == "-.Inf" || input == "-.INF";
}
inline bool IsNaN(const std::string& input) {
return input == ".nan" || input == ".NaN" || input == ".NAN";
}
template <typename T>
inline bool Convert(const std::string& input, T& output, typename enable_if<is_numeric<T> >::type * = 0) {
std::stringstream stream(input);
stream.unsetf(std::ios::dec);
if((stream >> output) && (stream >> std::ws).eof())
return true;
if(std::numeric_limits<T>::has_infinity) {
if(IsInfinity(input)) {
output = std::numeric_limits<T>::infinity();
return true;
} else if(IsNegativeInfinity(input)) {
output = -std::numeric_limits<T>::infinity();
return true;
}
}
if(std::numeric_limits<T>::has_quiet_NaN && IsNaN(input)) {
output = std::numeric_limits<T>::quiet_NaN();
return true;
}
return false;
}
}
#endif // CONVERSION_H_62B23520_7C8E_11DE_8A39_0800200C9A66
| true |
5092fad9ee3caeeb5e8b61de60d96f28310a4243 | C++ | 741zxc606/LeetCodePractices | /Algorithm/cpp/91.DecodeWays.cpp | UTF-8 | 1,592 | 3.796875 | 4 | [
"MIT"
] | permissive | /*
* 91.Decode Ways
* A message containing letters from A-Z is being encoded to numbers using the following mapping:
* 'A' -> 1
* 'B' -> 2
* ...
* 'Z' -. 26
* Gicen an encoded message containing digits,determine the total number of ways to decode it.
* For example,
* Given encoded message "12",it could be decoded as "AB" (1 2) or "L" (12).
* The number of ways decoding "12" is 2.
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int check(char ch)
{
//check 0 or not
return (!isdigit(ch) || ch == '0') ? 0 : 1;
}
int check(char ch1, char ch2)
{
//check it is between 10 and 26
return (ch1 == '1' || (ch1 == '2'&&ch2 <= '6')) ? 1 : 0;
}
int numDecodings(string s)
{
if (s.size() <= 0) return 0;
if (s.size() == 1) return check(s[0]);
int* dp = new int[s.size()];
memset(dp, 0, s.size() * sizeof(int));
dp[0] = check(s[0]);
dp[1] = check(s[0])*check(s[1]) + check(s[0], s[1]);
for (int i = 2; i < s.size(); i++)
{
if (!isdigit(s[i])) break;
if (check(s[i]))
{
dp[i] = dp[i - 1];
}
if (check(s[i - 1], s[i]))
{
dp[i] += dp[i - 2];
}
}
int result = dp[s.size() - 1];
delete[] dp;
return result;
}
};
int main()
{
Solution s;
string s1 = "123";
cout << "\"" << s1 << "\":" << s.numDecodings(s1) << endl;
return 0;
}
| true |
c45c4dee0ec1a7899343fd29e902a67162b6232d | C++ | milasudril/coin | /dombuilder.hpp | UTF-8 | 1,575 | 2.75 | 3 | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | //@ {
//@ "targets":[{"name":"dombuilder.hpp","type":"include"}]
//@ }
#ifndef COIN_DOMBUILDER_HPP
#define COIN_DOMBUILDER_HPP
#include "input.hpp"
#include "element.hpp"
namespace CoIN
{
class DOMBuilder
{
public:
DOMBuilder(Element& element_out):m_elem_current("root"),r_element_out(element_out)
{}
void commentBegin(){}
void commentEnd(const std::string& str){}
void output(const std::string& str)
{
if(r_elem_current)
{r_elem_current->append(str);}
}
void elementBegin(const CoIN::Tag& tag)
{
m_elems_out.push(r_elem_current);
if(r_elem_current)
{r_elem_current=r_elem_current->create(Element(tag));}
else
{r_elem_current=m_elem_current.create(Element(tag));}
}
void elementEnd(const CoIN::Tag& tag)
{
auto temp=m_elems_out.top();
m_elems_out.pop();
if(temp)
{r_elem_current=temp;}
else
{
// This is the last thing that happens, so steal whatever r_elem_current reffers to.
r_element_out=std::move(*r_elem_current);
}
}
private:
Element::NodePtr<Element> r_elem_current;
Element m_elem_current;
std::stack<Element::NodePtr<Element>> m_elems_out;
Element& r_element_out;
};
template<class InputStream,class Lexer,class ErrorPolicy=ErrorPolicyDefault_>
inline ParseResult load(InputStream&& stream,Lexer&& lexer,Element& element,ErrorPolicy&& err=ErrorPolicyDefault_{})
{
return read(std::forward<InputStream>(stream),std::forward<Lexer>(lexer),DOMBuilder(element)
,std::forward<ErrorPolicy>(err));
}
}
#endif
| true |
498c961c1fa00b70db322bfb3f4a151cc872400a | C++ | dongheekim23/Algorithm-Problems | /LetterCombinationsOfAPhoneNumber.cpp | UTF-8 | 1,855 | 3.90625 | 4 | [] | no_license | // Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
void GetStrings(const std::string& digits, std::vector<std::vector<char>>& stringSet)
{
for (int i = 0; i < digits.size(); ++i)
{
if (digits[i] == '2')
stringSet.emplace_back(std::vector<char>{'a', 'b', 'c'});
else if (digits[i] == '3')
stringSet.emplace_back(std::vector<char>{'d', 'e', 'f'});
else if (digits[i] == '4')
stringSet.emplace_back(std::vector<char>{'g', 'h', 'i'});
else if (digits[i] == '5')
stringSet.emplace_back(std::vector<char>{'j', 'k', 'l'});
else if (digits[i] == '6')
stringSet.emplace_back(std::vector<char>{'m', 'n', 'o'});
else if (digits[i] == '7')
stringSet.emplace_back(std::vector<char>{'p', 'q', 'r', 's'});
else if (digits[i] == '8')
stringSet.emplace_back(std::vector<char>{'t', 'u', 'v'});
else if (digits[i] == '9')
stringSet.emplace_back(std::vector<char>{'w', 'x', 'y', 'z'});
}
}
void GetLetterCombinations(const std::vector<std::vector<char>>& stringSet, std::vector<std::string>& output,
int index, int index2, std::string tempString)
{
tempString += stringSet[index][index2];
++index;
if (index <= stringSet.size() - 1)
{
for (int i = 0; i < stringSet[index].size(); ++i)
{
GetLetterCombinations(stringSet, output, index, i, tempString);
}
}
else
{
output.emplace_back(tempString);
}
}
std::vector<std::string> letterCombinations(std::string digits)
{
if (digits.empty())
return std::vector<std::string>{};
std::vector<std::vector<char>> stringSet;
GetStrings(digits, stringSet);
std::vector<std::string> output;
for (int i = 0; i < stringSet[0].size(); ++i)
GetLetterCombinations(stringSet, output, 0, i, "");
return output;
}
| true |
314774e0c2a711bef9cc847c2ecf8bfce3041090 | C++ | drken1215/algorithm | /String/knuth_morris_pratt.cpp | EUC-JP | 2,196 | 3.125 | 3 | [
"CC0-1.0"
] | permissive | //
// Knuth-Morris-Pratt
// fail[i] := pat[0:i) suffix pat prefix ɤפ뤫 (Ĺ i ̤)
// O(N) ǹۤǤ
// Ѥưʲ줿
// pat[0:i) κǾ ("abcabcab" "abc" η֤ڤ뤳ȤǤǤΤ 3)
// ʸ S ˤ S[i:] prefix pat Ȱפ褦 i ٤Ƶ
//
// verified:
// ABC 150 F - Xor Shift
// https://atcoder.jp/contests/abc150/tasks/abc150_f
//
// ARC 060 F - ɽ
// https://atcoder.jp/contests/arc060/tasks/arc060_d
//
#include <iostream>
#include <vector>
using namespace std;
// T = string or vector<long long>
template<class T> struct KMP {
T pat;
vector<int> fail;
// construct
KMP(const T &p) { init(p); }
void init(const T &p) {
pat = p;
int m = (int)pat.size();
fail.assign(m+1, -1);
for (int i = 0, j = -1; i < m; ++i) {
while (j >= 0 && pat[i] != pat[j]) j = fail[j];
fail[i+1] = ++j;
}
}
// the period of S[0:i]
int period(int i) { return i - fail[i]; }
// the index i such that S[i:] has the exact prefix p
vector<int> match(const T &S) {
int n = (int)S.size(), m = (int)pat.size();
vector<int> res;
for (int i = 0, k = 0; i < n; ++i) {
while (k >= 0 && S[i] != pat[k]) k = fail[k];
++k;
if (k >= m) res.push_back(i - m + 1), k = fail[k];
}
return res;
}
};
void solve(int N, const vector<long long> &a, const vector<long long> &b) {
vector<long long> da(N*2), db(N);
for (int i = 0; i < N*2; ++i) {
int j = i % N;
int k = (i + 1) % N;
da[i] = a[j] ^ a[k];
if (i < N) db[i] = b[j] ^ b[k];
}
KMP<vector<long long> > kmp(db);
auto v = kmp.match(da);
for (auto k : v) {
if (k < N) cout << k << " " << (a[k] ^ b[0]) << endl;
}
}
int main() {
int N;
cin >> N;
vector<long long> a(N), b(N);
for (int i = 0; i < N; ++i) cin >> a[i];
for (int i = 0; i < N; ++i) cin >> b[i];
solve(N, a, b);
}
| true |
ef161e51aa384c06853cb792718ee0eaef38dd50 | C++ | ScottFitzgerald83/cosc_1337 | /Course Materials/Examples/04 function/function as assignment.cpp | UTF-8 | 567 | 3.5625 | 4 | [] | no_license | /*
Name
Date
Project
*****************
Description
Examples for assignment of a function
*/
#include <iostream> // for cin, cout, endl
using namespace std;
int calc(int );
int main()
{
int number = 5;
cout << "The value of number before calling the function " << number << endl;
cout << "The value of number after assignment of the function " << calc(number) << endl;
system("PAUSE");
return 0;
}// end of main
int calc(int num)
{
num = 30;
return num;
} //end of cal
| true |
95d340ebfb313548fa38beb1adf62f03527ba554 | C++ | zhuzhonghua/pixeldungeon_cpp | /engine/button.cpp | UTF-8 | 1,211 | 2.71875 | 3 | [] | no_license | #include "button.h"
#include "game.h"
float Button::longClick = 1.0f;
Button::TouchArea1::TouchArea1(Button* btn) :TouchArea(0, 0, 0, 0)
{
_btn = btn;
}
void Button::TouchArea1::onTouchDown(TouchScreen::Touch* touch)
{
_btn->_pressed = true;
_btn->_pressTime = 0;
_btn->_processed = false;
_btn->onTouchDown();
}
void Button::TouchArea1::onTouchUp(TouchScreen::Touch* touch)
{
_btn->_pressed = false;
_btn->onTouchUp();
}
void Button::TouchArea1::onClick(TouchScreen::Touch* touch)
{
if (!_btn->_processed)
{
_btn->onClick();
}
}
Button::Button()
{
_pressed = false;
_pressTime = 0;
_processed = false;
init();
}
void Button::layout()
{
hotArea->x = _x;
hotArea->y = _y;
hotArea->width = _width;
hotArea->height = _height;
}
void Button::createChildren()
{
hotArea = new TouchArea1(this);
add(hotArea);
}
void Button::update()
{
Component::update();
hotArea->active = visible;
if (_pressed)
{
if ((_pressTime += Game::elapsed) >= longClick)
{
_pressed = false;
if (onLongClick())
{
hotArea->reset();
_pressed = true;
onTouchUp();
Game::vibrate(50);
}
}
}
} | true |
f917f6cc20fd9c2c3da80abb4bad1d1016308b07 | C++ | nanlimarketing/Iris_gal_maker | /Button.hpp | UTF-8 | 1,743 | 2.640625 | 3 | [] | no_license | //按钮类
//用于选择和跳转
//First Draft: 2012.4.26
#ifndef SYS
#define SYS
#include "System.hpp"
#endif
#ifndef TEXT
#define TEXT
#include "Text.hpp"
#endif
#ifndef ANIMEM
#define ANIMEM
#include "AnimeManager.hpp"
#endif
class Button
{
public:
Button(); //构造函数
bool OnButton(const float x, const float y); //检测按钮的状态,鼠标是否在按钮上
void Init(const string picN, const string coverN, const string coverCN, const string clickedN, const float pX, const float pY, const float cX,
const float cY, unsigned int a, const float bX, const float bY,const unsigned int bW, const unsigned int bH); //初始化
void SetPositionX(const float x); //设置图片位置
void SetPositionY(const float y);
float GetPositionX();
float GetPositionY();
float GetOriginPosX();
float GetOriginPosY();
string GetPicName(); //返回图片名称
void DrawButton(AnimeManager& animeManager, sf::RenderWindow& window, bool bEffect); //绘制按钮
void SetInfo(const wstring); //设置返回的Info
wstring GetInfo(); //获得返回的信息
bool& Clicked();
bool& Cover();
private:
wstring info; //返回的信息
bool bShowCover; //是否显示遮罩
bool bClicked; //按钮是否已经按下
string picName; //按钮图片
string clickedName; //按下按钮的图片
string coverName; //遮罩图片
string clickedCoverName; //按下按钮的图片
unsigned int alpha; //遮罩图片的透明度
float picX,picY; //图片的位置
float oriPicX,oriPicY; //图片的初始位置
float coverX,coverY; //遮罩的位置
float buttonX,buttonY; //按钮判定的位置
unsigned int buttonHeight,buttonWidth; //按钮判定的区域
}; | true |
db47fd4c288d5a12bbceecdc94e0c9d21f7c1076 | C++ | easmith14/cse687-group1 | /source/TestObjects/testDLL/testDLL/equipment.cpp | UTF-8 | 2,284 | 2.890625 | 3 | [
"MIT"
] | permissive | #include "pch.h"
#include "equipment.h"
#include "../../../TestHarness/TestResult.h"
#include "../../../TestHarness/TestResponse.h"
#include <string>
using std::string;
static string _EquipmentName;
static int _durability;
static int _property;
static int _saved_property;
void create_equipment(const string a, const int b, const int c)
{
_EquipmentName = a;
_durability = b;
_property = c;
_saved_property = _property;
}
void degrade_equipment(const int a)
{
_durability -= a;
if (_durability <= 0)
{
destroy_equipment();
}
}
void repair_equipment(const int a)
{
_durability += a;
_property = _saved_property;
}
void upgrade_equipment(const int a)
{
_property += a;
}
void destroy_equipment()
{
_property = 0;
}
int get_equipment_property()
{
return _property;
}
TestResponse test()
{
TestResponse response;
// Test Case 1 : Passing Case
TestResult passResult;
passResult.LogLevel = 3;
passResult.TestName = "PASS Test";
passResult.TestNotes = "This test will always pass";
passResult.TestNumber = 1;
passResult.TestSuccess = true;
response.Results.push_back(passResult);
// Test Case 2 : Degrade Check
TestResult degradeResult;
degradeResult.LogLevel = 1;
degradeResult.TestName = "Degrade Check";
degradeResult.TestNotes = "Check whether or not the degrade system is working";
degradeResult.TestNumber = 2;
int origDurability = _durability;
int changeVal = 1;
degrade_equipment(changeVal);
if (origDurability == _durability - changeVal)
{
degradeResult.TestSuccess = true;
}
else
{
degradeResult.TestSuccess = false;
}
response.Results.push_back(degradeResult);
//// Test Case 3 : Character Transcends Humanity
//TestResult transcendResult;
//transcendResult.LogLevel = 1;
//transcendResult.TestName = "Transcend Mortal Coil";
//transcendResult.TestNotes = "And this is to go even further.. beyond";
//transcendResult.TestNumber = 3;
//// test should break since level is stored as an int
//unsigned long maxULong = 2147483647;
//for (unsigned long i = 0; i < maxULong; i++)
//{
// level_up();
//}
//// if the test made it this far then it is a pass
//transcendResult.TestSuccess = true;
//response.Results.push_back(transcendResult);
return response;
}
| true |
2ea13e229a08c131786cc6913b0ad329be9515a1 | C++ | mmardanova/C-lab-1 | /src/main1.cpp | UTF-8 | 694 | 2.890625 | 3 | [] | no_license | #include "task1.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
char gender = 0; float weight = 0, height = 0;
printf("Enter your gender:", gender);
scanf("%c", &gender);
if (gender != 'm' && gender != 'w')
{
printf("Gender is entered incorrectly\n");
return 1;
}
printf("Enter your weight:", weight);
scanf("%f", &weight);
printf("Enter yuor height:");
scanf("%f", &height);
int result = getRecommendation(gender, height, weight);
if (result == 0)
printf("Your weight is perfect\n");
if (result == -1)
printf("You need to get better\n", getRecommendation);
if (result == 1)
printf("You need to lose weight\n", getRecommendation);
return 0;
} | true |
02b379e49e90a2ffb7a2ccf6f8ed6a893cdb3a93 | C++ | vik228/SpojCodes | /ABCDEF.cpp | UTF-8 | 890 | 2.6875 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int *usr_val,*lhs,*rhs,t,sum=0,it1=0,it2=0,ans=0;
cin>>t;
usr_val=new int[t];
lhs=new int[t*t*t+1];
rhs=new int[t*t*t+1];
for(int i=0;i<t;i++)
{
cin>>usr_val[i];
}
for(int i=0;i<t;i++)
{
for(int j=0;j<t;j++)
{
for(int k=0;k<t;k++)
{
sum=usr_val[i]+usr_val[j];
if(usr_val[k]!=0)
{
rhs[it2]=usr_val[k]*sum;
it2++;
}
lhs[it1]=(usr_val[i]*usr_val[j])+usr_val[k];
it1++;
}
}
}
sort(lhs,lhs+it1);
sort(rhs,rhs+it2);
for(int i=0;i<it1;i++)
{
int val=lhs[i];
int countl=0;
while(lhs[i]==val)
{
countl++;
i++;
}
i--;
int *low=lower_bound(rhs,rhs+it2,val);
int index=low-rhs;
int countr=0;
if(index!=it2)
{
while(rhs[index]==val)
{
countr++;
index++;
}
}
ans=ans+countl*countr;
}
cout<<ans<<"\n";
return 0;
}
| true |
7164541100fc159f9333f5585b7b5fef74eb2725 | C++ | Francisco-Ibarra07/sparky | /src/modules/controls/include/controls/Motor.hpp | UTF-8 | 7,075 | 3.296875 | 3 | [
"MIT"
] | permissive | #ifndef MOTOR_H
#define MOTOR_H
#include <ros/ros.h>
#include "wiringSerial.h"
#include <string>
#include <unistd.h>
#include <stdexcept>
#include <stdbool.h>
typedef enum{
FRONT_L_MOTOR= 1,
FRONT_R_MOTOR= 2,
REAR_L_MOTOR= 3,
REAR_R_MOTOR= 4,
} MOTOR;
typedef enum {
directionNotInitialized,
FORWARD,
REVERSE
} DIRECTION;
class Motor{
int* fd; //Stores the address of 'fd' so we can use it in Motor.cpp/hpp
unsigned char controllerDeviceNumber; //Stores the device number of the motor needed for the pololu
unsigned char forwardDirectionID; //Stores the forward ID direction of the motor
unsigned char reverseDirectionID; //Stores the reverse ID direction of the motor
bool motorIsSafe; //Stores whether an error has occured with this motor
int motorSpeed; //Stores the speed of the motor. This variable is constantly adjusted.
DIRECTION direction; //Stores the direction of the motor. This variable is constantly adjusted.
std::string motorName; //Store the given name when the motor object is created
public:
//Constructor for a Motor object
Motor(MOTOR whichMotor, int* _fd); //Constructor that takes in the desired motor to initialize and the address of the file descriptor pointer (&fd)
~Motor(); //Destructor which prints out the name of the motor object which is being deleted
//---MOTOR MOVEMENT FUNCTIONS---//
int Motor_exitSafeStart(); //Function which writes to the microcontroller to get this motor to start. If anything goes wrong it will update the safety variable accordingly
int Motor_moveForward(int speed); //Takes in a speed and moves motor forward according to that speed
int Motor_moveReverse(int speed); //Takes in a speed and moves motor in reverse according to that speed
int Motor_stop(); //Stops the motor.
int Motor_disable(); //Disables the motor
//---MOTOR GETTERS---//
int getcontrollerDeviceNumber(); //Returns either 1, 2, 3, or 4 depending on the device number of the motor
int getMotorSpeed(); //Returns the speed of the motor
bool isOk(); //Returns whether or not the motor is error free
DIRECTION getDirection(); //Returns the direction in which the motor is moving (Either forward or reverse)
std::string getName(); //Returns the name of the motor
float getTemperature(); //Returns the temperature of the motor
//---MOTOR SETTERS---//
void setDirectionVar(DIRECTION newDirection); //Sets the new direction of the motor
void setSpeedVar(int newSpeed); //Sets the new speed and the direction of the motor
};
Motor::Motor(MOTOR whichMotor, int* _fd)
{
//Assigns device number, name, forward and reverse ID depending on motor chosen
switch(whichMotor)
{
case FRONT_L_MOTOR:
controllerDeviceNumber= 0x01;
motorName= "Front Left Motor";
forwardDirectionID= 0x06;
reverseDirectionID= 0x05;
break;
case FRONT_R_MOTOR:
controllerDeviceNumber= 0x02;
motorName= "Front Right Motor";
forwardDirectionID = 0x05;
reverseDirectionID = 0x06;
break;
case REAR_L_MOTOR:
controllerDeviceNumber= 0x03;
motorName= "Rear Left Motor";
forwardDirectionID = 0x06;
reverseDirectionID = 0x05;
break;
case REAR_R_MOTOR:
controllerDeviceNumber= 0x04;
motorName= "Rear Right Motor";
forwardDirectionID = 0x05;
reverseDirectionID = 0x06;
break;
default: //This case shouldn't happen because 'whichMotor' should always be a MOTOR enum value but just in case throw an error
ROS_FATAL("Illegal Argument: 'whichMotor' needs to be a valid MOTOR");
serialClose(*_fd);
break;
}
//Initialize the rest of the variables
fd= _fd;
motorSpeed= 0;
motorIsSafe = true;
direction = directionNotInitialized;
}
Motor::~Motor()
{
ROS_INFO("Controller #%d deleted !", controllerDeviceNumber);
}
bool Motor::isOk(){
return motorIsSafe;
}
int Motor::Motor_exitSafeStart()
{
int exitSafeStart_command[3] = {0xAA, this->controllerDeviceNumber, 0x83};
int check;
check = write(*fd, exitSafeStart_command, 3);
if(check == -1){
ROS_FATAL("Controller #%d failed to exitSafeStart()", controllerDeviceNumber);
motorIsSafe = false;
return -1;
}
else{
ROS_INFO("Controller #%d set !", controllerDeviceNumber);
return 0;
}
}
//---------------MOTOR MOVEMENT FUNCTIONS------------//
int Motor::Motor_moveForward(int newSpeed)
{
if(newSpeed <= 0){
newSpeed = 0;
}
else if (newSpeed >= 100){
newSpeed = 100;
}
int moveForward_command[5] = {0xAA, this->controllerDeviceNumber, forwardDirectionID, 0x00, newSpeed};
int check = write(*fd, moveForward_command, 5);
if(check == -1){
ROS_FATAL("Controller #%d failed to moveForward()", controllerDeviceNumber);
motorIsSafe = false;
return -1;
}
else{
setDirectionVar(FORWARD);
setSpeedVar(newSpeed);
return 0;
}
}
int Motor::Motor_moveReverse(int newSpeed)
{
if(newSpeed >= 0){
newSpeed = 0;
}
else if (newSpeed < -100){
newSpeed = -100;
}
int moveReverse_command[5] = {0xAA, this->controllerDeviceNumber, reverseDirectionID, 0x00, newSpeed};
int check = write(*fd, moveReverse_command, 5);
if(check == -1){
ROS_FATAL("Controller #%d failed to moveReverse()", controllerDeviceNumber);
motorIsSafe = false;
return -1;
}
else{
setDirectionVar(REVERSE);
setSpeedVar(newSpeed);
return 0;
}
}
int Motor::Motor_disable()
{
int disable_command[3] = {0xAA, this->controllerDeviceNumber, 0x60};
int check=0;
check = write(*fd, disable_command, 3);
if(check == -1){
ROS_FATAL("Controller #%d failed to stop",controllerDeviceNumber);
motorIsSafe = false;
return -1;
}
else{
ROS_INFO("Controller #%d disabled", controllerDeviceNumber);
return 0;
}
}
int Motor::Motor_stop()
{
int stop_command[5] = {0xAA, controllerDeviceNumber, reverseDirectionID, 0x00, 0x00};
int check = write(*fd, stop_command, 5);
if(check == -1){
ROS_FATAL("Controller #%d failed to stop",controllerDeviceNumber);
motorIsSafe = false;
return -1;
}
else{
ROS_INFO("Disable safestart on motor %d first", controllerDeviceNumber);
return 0;
}
}
//MOTOR GETTERS
int Motor::getcontrollerDeviceNumber(){
return this->controllerDeviceNumber;
}
int Motor::getMotorSpeed(){
return this->motorSpeed;
}
std::string Motor::getName(){
return this->motorName;
}
DIRECTION Motor::getDirection(){
return this->direction;
}
//Temperature returned is in units of 0.1 degrees Celsius
//For example if 295 is returned then the temp is 29.5 *Celsius
float Motor::getTemperature(){
int getTemp[4]= {0xAA, 0x02, 0x21, 24};
char lowByte, highByte;
write(*fd, getTemp, 4);
lowByte= serialGetchar(*fd);
highByte= serialGetchar(*fd);
return (lowByte + 256 * highByte) * 0.1;
}
//-------------MOTOR SETTERS--------------//
void Motor::setSpeedVar(int newSpeed){
this->motorSpeed = newSpeed;
}
void Motor::setDirectionVar(DIRECTION newDirection){
direction= newDirection;
}
#endif //MOTOR_H
| true |
6d12f2d5e0f09f39f261095cf0a72dcd5cbcddd9 | C++ | YuraTim/Ravage | /RavageRebuild/src/OpenGL/RavTextureOpenGL.cpp | UTF-8 | 1,781 | 2.609375 | 3 | [] | no_license | #include "OpenGL\RavTextureOpenGL.h"
namespace Ravage
{
TextureOpenGL::TextureOpenGL()
{
glGenTextures(1, &mTextureId);
}
TextureOpenGL::~TextureOpenGL()
{
glDeleteTextures(1, &mTextureId);
}
void TextureOpenGL::setFilterMode(FilterMode mode)
{
GLenum target = getTarget();
if (target == 0)
return;
glBindTexture(target, mTextureId);
switch(mode)
{
case FM_POINT:
glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(target, GL_GENERATE_MIPMAP, GL_FALSE);
case FM_BILINEAR:
glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE);
break;
case FM_TRILINEAR:
glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE);
}
}
void TextureOpenGL::setAnisoLevel(int level)
{
GLenum target = getTarget();
if (target == 0)
return;
glBindTexture(target, mTextureId);
if (GL_EXT_texture_filter_anisotropic)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (GLfloat)level);
}
void TextureOpenGL::setWrapMode(TexWrapMode mode)
{
GLenum target = getTarget();
if (target == 0)
return;
glBindTexture(target, mTextureId);
switch(mode)
{
case TWM_REPEAT:
glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_REPEAT);
break;
case TWM_CLAMP:
glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP);
break;
}
}
} | true |
9a9a2ec8489503ca6a8f38272bb0314dc55e52b2 | C++ | cypypccpy/SRSLAM | /include/srslam/datastruct/mappoint.h | UTF-8 | 1,377 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <memory>
#include <mutex>
#include <list>
#include <Eigen/Core>
#include <Eigen/Geometry>
class frame;
class feature;
/**
* 路标点类
* 特征点在三角化之后形成路标点
*/
class mappoint {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
unsigned long id_ = 0; // ID
bool is_outlier_ = false;
Eigen::Vector3d pos_ = Eigen::Vector3d::Zero(); // Position in world
std::mutex data_mutex_;
int observed_times_ = 0; // being observed by feature matching algo.
std::list<std::weak_ptr<feature>> observations_;
mappoint() {}
mappoint(long id, Eigen::Vector3d position);
Eigen::Vector3d Pos() {
std::unique_lock<std::mutex> lck(data_mutex_);
return pos_;
}
void SetPos(const Eigen::Vector3d &pos) {
std::unique_lock<std::mutex> lck(data_mutex_);
pos_ = pos;
};
void AddObservation(std::shared_ptr<feature> feature) {
std::unique_lock<std::mutex> lck(data_mutex_);
observations_.push_back(feature);
observed_times_++;
}
void RemoveObservation(std::shared_ptr<feature> feat);
std::list<std::weak_ptr<feature>> GetObs() {
std::unique_lock<std::mutex> lck(data_mutex_);
return observations_;
}
// factory function
static std::shared_ptr<mappoint> CreateNewMappoint();
};
| true |
1a89665c08dcfb038b201db8b0171daeb84287ca | C++ | ChaseDuncan/linkstate_distvec | /distvec.cpp | UTF-8 | 8,661 | 3.03125 | 3 | [] | no_license | #include "distvec.h"
using namespace std;
void Distvec::make_graph_and_list_edges(string topofile)
{
ifstream infile(topofile);
string line;
int ints[3];
while(getline(infile, line))
{
istringstream iss(line);
int number;
int idx=0;
while(iss >> number)
{
ints[idx] = number;
idx++;
}
pair<int, int> edge_1(ints[2], ints[1]);
tuple<int, int, int> edge_1a(ints[0], ints[2], ints[1]);
graph[ints[0]].push_back(edge_1);
pair<int, int> edge_2(ints[2], ints[0]);
tuple<int, int, int> edge_2a(ints[1], ints[2], ints[0]);
graph[ints[1]].push_back(edge_2);
edges.push_back(edge_1a);
edges.push_back(edge_2a);
}
}
int Distvec::parse_changes(string changesfile)
{
int num_changes=0;
ifstream infile(changesfile);
string line;
int ints[3];
queue<tuple<int, int, int> >tempchanges;
while(getline(infile, line))
{
istringstream iss(line);
int number;
int idx=0;
while(iss >> number)
{
ints[idx]=number;
idx++;
}
tuple<int, int, int> change(ints[0], ints[1], ints[2]);
changes.push_back(change);
num_changes+=1;
}
return num_changes;
}
void Distvec::bellman_ford(int source)
{
//cout<<"beginning of bellman"<<endl;
unordered_map<int, pair<int, int> > * dist = new unordered_map<int, pair<int, int> >;
//go through graph and initialize vertices
int vertices_size=0;
for(auto val : graph){
if(val.first==source){
pair<int, int> src(0, val.first); //dist, predecessor
(*dist)[val.first]=src;
}
else{
pair<int, int> inf(INT_MAX, -1);
(*dist)[val.first]=inf;
}
vertices_size+=1;
}
//"relax the edges"
for(int i=0;i<vertices_size;i++){
for(int j=0;j<edges.size();j++){
int cur_src=get<0>(edges[j]);
int cur_cost=get<1>(edges[j]);
int cur_dest=get<2>(edges[j]);
//if a better path
if((*dist)[cur_src].first != INT_MAX && (*dist)[cur_src].first+cur_cost<(*dist)[cur_dest].first){
(*dist)[cur_dest].first=(*dist)[cur_src].first+cur_cost;
//update predecessor
(*dist)[cur_dest].second=cur_src;
}
}
}
if(distances[source]!=NULL){
delete distances[source];
distances[source]=NULL;
}
distances[source]=dist;
/*for(auto & it: *dist){
cout<<"in bellman ford. Source: "<<source<<" dest: "<<it.first<<" distances: "<<it.second.first<<" predecessor: "<<it.second.second<<endl;
}*/
//cout<<"end of bellman"<<endl;
}
void Distvec::populate_distances()
{
//put in priorirty queue so we can go through in the right order
priority_queue<int> pq;
for(auto node:graph){
pq.push((node.first));
}
while(!pq.empty()){
int curnode=pq.top();
pq.pop();
bellman_ford(curnode);
}
}
void Distvec::print_message_path(ofstream & myfile, string message_file)
{
ifstream infile(message_file);
string line;
while(getline(infile, line)){
size_t srcidx=line.find(" ");
string srcstr=line.substr(0, srcidx);
int srcint=atoi(srcstr.c_str());
size_t destidx=line.find(" ", srcidx+1); //have to add one otherwise we're on the same space
string deststr=line.substr(srcidx+1, destidx-1);
int destint=atoi(deststr.c_str());
string message=line.substr(destidx+1);
myfile<<"from "<<srcint<<" to "<<destint<<" hops";
vector<int> route = routing_table[srcint][destint];
for(int i=0;i<route.size()-1;i++){
myfile<<" "<<route[i];
}
myfile<<" message "<<message<<"\n";
}
}
void Distvec::output_to_file(ofstream & myfile, string message_file)
{
print_routing_table(myfile);
print_message_path(myfile,message_file);
}
void Distvec::print_routing_table(ofstream & myfile)
{
for(auto source:distances){
int sourceint=source.first;
//need this so we can go through the nodes in the right order
//even though this isn't dijkstrajs, just using the priority queue
//since the map is unordered'
priority_queue<int> pq;
//go through all the destination
for(auto dest:(*source.second)){
int destint=dest.first;
pq.push((-1)*destint);
}
while(!pq.empty()){
int destint=(-1)*pq.top();
pq.pop();
int curhop=destint;
int prevcurhop=curhop;
int totaldist=(*source.second)[destint].first;
//fill out the routing table, backtrace
stack<int> backward_route;
while(curhop!=sourceint){
backward_route.push(curhop);
prevcurhop=curhop;
curhop=(*source.second)[curhop].second;
//cout<<"curhop: "<<curhop<<" prevcurhop: "<<prevcurhop<<" sourceint: "<<sourceint<<" destint: "<<destint<<endl;
}
//clear vector as this might be the second call after changes
routing_table[sourceint][destint].clear();
//push on the source as that's the "first hop"
routing_table[sourceint][destint].push_back(sourceint);
while(!backward_route.empty()){
int nextnode=backward_route.top();
backward_route.pop();
routing_table[sourceint][destint].push_back(nextnode);
}
myfile<<destint<<" "<<prevcurhop<<" "<<totaldist<<"\n";
}
myfile<<"\n"<<endl;
}
}
void Distvec::update_graph_and_edges(int ithchange)
{
int source=get<0>(changes[ithchange]);
int dest=get<1>(changes[ithchange]);
int newcost=get<2>(changes[ithchange]);
vector<pair<int, int> > vec=graph[source];
//deleted a node
if(newcost==-999){
for(int i=0;i<(graph[source]).size();i++){
//found edge, delete it
if(graph[source][i].second==dest){
graph[source].erase((graph[source]).begin()+i);
}
}
//do the same for the other edge
for(int i=0;i<graph[dest].size();i++){
if(graph[dest][i].second==source){
graph[dest].erase((graph[dest]).begin()+i);
}
}
//for deubugging
/*cout<<"in update graph";
for(int i=0;i<edges.size();i++){
int src=get<0>(edges[i]);
int dest=get<2>(edges[i]);
cout<<"src: "<<src<<" dest: "<<dest<<endl;
}*/
delete_edge(source, dest);
}
//insert or update weight
else{
bool found=false;
for(int i=0;i<vec.size();i++){
//found edge, update it
if(graph[source][i].second==dest){
found=true;
graph[source][i].second=newcost;
}
}
if(!found){
pair<int, int> p(newcost, dest);
graph[source].push_back(p);
pair<int, int> p2(newcost, source);
graph[dest].push_back(p2);
}
else if(found){
for(int i=0;i<graph[dest].size();i++){
if(graph[dest][i].second==source){
graph[dest][i].second=newcost;
}
}
}
update_edge(source, dest, newcost);
}
}
void Distvec::update_edge(int source, int dest, int newcost)
{
bool found=false;
for(int i=0;i<edges.size();i++){
int cursrc=get<0>(edges[i]);
int curdest=get<2>(edges[i]);
if((cursrc==source && curdest==dest)||(cursrc==dest && curdest==source)){
found=true;
get<1>(edges[i])=newcost;
}
}
//if adding new edge
if(!found){
tuple<int, int, int> a(source, newcost, dest);
tuple<int, int, int> b(dest, newcost, source);
edges.push_back(a);
edges.push_back(b);
}
}
void Distvec::delete_edge(int source, int dest)
{
priority_queue<int> tobedeleted;
//since the graph is undirected, we'll have to delete both sets of edges
for(int i=0;i<edges.size();i++){
int cursrc=get<0>(edges[i]);
int curdest=get<2>(edges[i]);
if((cursrc==source && curdest==dest) || (cursrc==dest && curdest==source)){
tobedeleted.push(i);
//edges.erase((edges.begin()+i));
}
//cout<<"at idx ten: "<<get<0>(edges[10])<<" second: "<<get<2>(edges[10])<<endl;
}
while(!tobedeleted.empty()){
int idx=tobedeleted.top();
tobedeleted.pop();
edges.erase((edges.begin()+idx));
}
}
/*just for testing purposes*/
void Distvec::print_graph()
{
for(unordered_map<int, vector<pair<int, int> > >::iterator it = graph.begin(); it != graph.end(); it++)
{
int src = it->first;
vector<pair<int, int> > vec = it->second;
for(int i=0;i<vec.size();i++)
{
int dest = vec[i].first;
int wgt = vec[i].second;
cout<< src<<" "<<dest << " "<< wgt<<endl;
}
}
}
/*just for testing purposes*/
void Distvec::print_edges()
{
for(int i=0;i<edges.size();i++)
{
int src=get<0>(edges[i]);
int cost=get<1>(edges[i]);
int dest=get<2>(edges[i]);
cout<<"source: "<<src<<" cost: "<<cost<<" dest: "<<dest<<endl;
}
}
int main(int argc, char *argv[])
{
Distvec dv;
ofstream output;
output.open("output.txt");
dv.make_graph_and_list_edges(argv[1]);
//cout<<"print graph:"<<endl;
//dv.print_graph();
int num_changes=dv.parse_changes(argv[3]);
dv.populate_distances();
dv.output_to_file(output, argv[2]);
//do everything again for each change
for(int i=0;i<num_changes;i++){
cout<<"print graph: "<<endl;
dv.print_graph();
//cout<<"print edges: "<<endl;
//dv.print_edges();
dv.update_graph_and_edges(i);
dv.populate_distances();
dv.output_to_file(output, argv[2]);
}
//cout<<"final graph: "<<endl;
//dv.print_graph();
//cout<<"edges: "<<endl;
//dv.print_edges();
output.close();
}
| true |
ac288486fc32eeb9b7b431da723b19c10adbee7c | C++ | jackflower/SCInfor | /SCInfor/source/Equipment/EquipmentData/EquipmentGunData.cpp | WINDOWS-1250 | 1,274 | 2.890625 | 3 | [] | no_license | // _____________________________________________
// | EquipmentGunData.cpp - class implementation |
// | Jack Flower - May 2016 |
// |_____________________________________________|
//
#include "EquipmentGunData.h"
#include "../Weapon/Gun/Gun.h"
#include "../../Logic/PhysicalManager.h"
namespace equipmentdata
{
RTTI_IMPL(EquipmentGunData, EquipmentData);
//Konstruktor
EquipmentGunData::EquipmentGunData()
:
EquipmentData{},//konstruktor klasy bazowej
p_gun{ nullptr }
{
}
//Konstruktor kopiujcy
EquipmentGunData::EquipmentGunData(const EquipmentGunData & EquipmentGunDataCopy)
:
EquipmentData{ EquipmentGunDataCopy },//konstruktor kopiujcy klasy bazowej
p_gun{ EquipmentGunDataCopy.p_gun }
{
}
//Destruktor wirtualny
EquipmentGunData::~EquipmentGunData()
{
//~EquipmentData()
if (p_gun)
gPhysicalManager.destroyPhysical(p_gun);
p_gun = nullptr;
}
//Metoda zwraca typ obiektu /RTTI/
const std::string EquipmentGunData::getType() const
{
return rtti.getNameClass();
}
//Metoda zwraca wskanik na obiekt klasy Gun
Gun *EquipmentGunData::getGun()
{
return p_gun;
}
//Metoda ustawia wskanik na obiekt klasy Gun
void EquipmentGunData::setGun(Gun *gun)
{
p_gun = gun;
}
}//namespace equipmentdata
| true |
8904ae7b5ca7e0a9d2722b68df63ec2169e94981 | C++ | coconetlero/algoritmos_clase | /queue_dynamic/main.cxx | UTF-8 | 781 | 3.5625 | 4 | [] | no_license | #include <stdio.h>
#include <assert.h>
#include <queue.h>
int main(int argc, char **argv)
{
printf("Create the queue \n");
Queue queue;
queue.head = NULL;
queue.tail = NULL;
printf("Add element = 3 \n");
enqueue(&queue, 3);
printf("Add element = 5 \n");
enqueue(&queue, 5);
printf("Add element = 10 \n");
enqueue(&queue, 10);
int elem = dequeue(&queue);
assert(elem);
printf("Dequeue element = %d \n", elem);
elem = dequeue(&queue);
assert(elem);
printf("Dequeue element = %d \n", elem);
elem = dequeue(&queue);
assert(elem);
printf("Dequeue element = %d \n", elem);
elem = dequeue(&queue);
assert(elem);
printf("Dequeue element = %d \n", elem);
}
| true |
a77c5aaabff97d4ad5b3656d39d6fc9536adae4f | C++ | fusaimoe/embedded-systems | /consegna-3/smart_car/ServoImpl.cpp | UTF-8 | 309 | 2.828125 | 3 | [] | no_license | #include "ServoImpl.h"
#include "Arduino.h"
ServoImpl::ServoImpl(int pin){
myservo.attach(pin);
}
void ServoImpl::setValue(int value){
Serial.println(value);
value = map(value, 0, 180, 750, 2250); // Only needed if using ServoTimer2 instead of servo
Serial.println(value);
myservo.write(value);
}
| true |
597f4ac011ce5061f17f93fdd9c11750f7d84906 | C++ | vladfux4/test | /scheduler_worker.cc | UTF-8 | 4,317 | 2.75 | 3 | [] | no_license | #include "scheduler_worker.h"
#include <sstream>
#include <fstream>
SchedulerWorker::SchedulerWorker(boost::ptr_vector<GeneratorWorker>& generators,
boost::ptr_vector<ComputeWorker>& computers,
const size_t block_count)
: kRequiredBlockCount(block_count),
generated_block_count_(0),
processed_new_block_count_(0),
processed_result_count_(0),
generated_block_count_mutex_(),
new_blocks_(),
results_(),
blocks_(),
generators_(generators),
computers_(computers),
error_counter_(0) {
}
SchedulerWorker::~SchedulerWorker() {
}
bool SchedulerWorker::AcquireBlock() {
boost::lock_guard<boost::mutex> lock(generated_block_count_mutex_);
bool ret_val = false;
if (generated_block_count_ < kRequiredBlockCount) {
generated_block_count_++;
ret_val = true;
}
return ret_val;
}
void SchedulerWorker::TakeEvent(const SharedBlock event) {
new_blocks_.push(event);
}
void SchedulerWorker::TakeEvent(const ResultEvent event) {
results_.push({event.block, event.crc});
}
void SchedulerWorker::ProcessEvents() {
ProcessNewBlocks();
ProcessResults();
CheckDoneCondition();
}
void SchedulerWorker::ProcessNewBlocks() {
while (false == new_blocks_.empty()) {
auto block = new_blocks_.front();
new_blocks_.pop();
processed_new_block_count_++;
VLOG(1) << "Process New Block: " << SerializeBlock(block);
blocks_.push_back(BlockData(block, computers_.size()));
for (std::size_t i = 0; i < computers_.size(); ++i) {
computers_[i].PushEvent(block);
}
}
}
void SchedulerWorker::ProcessResults() {
while (false == results_.empty()) {
auto result = results_.front();
results_.pop();
processed_result_count_++;
VLOG(1) << "Process Result: "
<< SerializeBlock(result.block)
<< " CRC: " << std::hex << result.crc;
//find in list
auto block_it = blocks_.begin();
for (; block_it != blocks_.end(); ++block_it) {
if (block_it->block.data.get() == result.block.data.get()) {
break;
}
}
if (blocks_.end() == block_it) {
LOG(ERROR) << "Block was not found";
} else {
block_it->results.push_back(result.crc);
VLOG(1) << "Stored CRC:" << result.crc << " result_count:" << block_it->results.size();
if (block_it->results.size() == block_it->kRequiredResultCount) {
if (false == CheckResults(*block_it)) {
StoreBrokenBlock(*block_it);
}
blocks_.erase(block_it);
}
}
}
}
bool SchedulerWorker::CheckResults(const SchedulerWorker::BlockData& data) {
VLOG(1) << "Check block: " << SerializeBlock(data.block)
<< " CRC: " << SerializeResults(data.results);
bool status = true;
auto prev = data.results[0];
for (std::size_t i = 1; i < data.results.size(); ++i) {
if (data.results[i] != prev) {
status = false;
break;
}
prev = data.results[i];
}
return status;
}
void SchedulerWorker::StoreBrokenBlock(const SchedulerWorker::BlockData& data) {
LOG(ERROR) << "Invalid Block";
std::stringstream ss;
ss << "invalid_crc_" << error_counter_
<< "_" << std::hex << data.results[0] << ".dat";
std::cout << "Invalid Block: " << SerializeBlock(data.block)
<< " CRC: " << SerializeResults(data.results)
<< " filename:" << ss.str() << std::endl;
std::ofstream out(ss.str());
for (std::size_t i = 0; i < data.block.length; ++i) {
out << data.block.data[i];
}
out.close();
error_counter_++;
}
void SchedulerWorker::CheckDoneCondition() {
VLOG(1) << "Processed: {new blocks:"
<< processed_new_block_count_
<< ", results:"
<< processed_result_count_
<< "}";
if ((kRequiredBlockCount == processed_new_block_count_) &&
((kRequiredBlockCount * computers_.size()) == processed_result_count_)) {
StopListen();
for (std::size_t i = 0; i < computers_.size(); ++i) {
computers_[i].NotifyStopListen();
}
}
}
std::string SchedulerWorker::SerializeResults(const BlockData::ResultData& results) {
std::stringstream ss;
for (std::size_t i = 0; i < results.size(); ++i) {
ss << std::hex << results[i] << " ";
}
return ss.str();
}
| true |
6f4232fb8567c88b0356a5a270c8677d356fb4a4 | C++ | abhishek1026/COP3530_Project_1 | /PSLL.h | UTF-8 | 15,703 | 3.4375 | 3 | [] | no_license | //
// Created by Abhishek on 9/11/2017.
//
#ifndef COP3530_PROJECT_1_PSLL_H
#define COP3530_PROJECT_1_PSLL_H
#include <iostream>
#include <stdexcept>
#include "List.h"
using namespace std;
namespace cop3530{
template <class T>
class PSLL: public List<T>{
private:
struct Node {
T data;
Node *next;
};
typedef struct Node *NodePtr;
NodePtr head = nullptr;
NodePtr tail = nullptr;
NodePtr free = nullptr;
void send_to_pool(NodePtr data){
if(grab_pool_length() >= 50){
delete data;
return;
}
//cout << "Sending Node back to Pool!" << endl;
if(this->free == nullptr){
this->free = data;
this->free->next = nullptr;
return;
}
NodePtr temp = this->free;
while(temp->next != nullptr){
temp = temp->next;
}
temp->next = data;
temp->next->next = nullptr;
return;
}
NodePtr grab_from_pool(){
if(grab_pool_length() == 0){
Node* newNode = new(std::nothrow) Node;
if(!newNode){
throw std::runtime_error("Pool is empty and out of external memory!");
}
return newNode;
}
NodePtr takeFree = this->free;
this->free = takeFree->next;
takeFree->next = nullptr;
//cout << "Grabbing Node from Pool!" << endl;
return takeFree;
}
public:
template<class DataT>
class PSLL_Iter: public std::iterator<std::forward_iterator_tag,DataT>{
public:
typedef DataT value_type;
typedef std::ptrdiff_t difference_type;
typedef DataT& reference;
typedef DataT* pointer;
typedef std::forward_iterator_tag iterator_category;
typedef PSLL_Iter self_type;
typedef PSLL_Iter& self_reference;
private:
Node* here;
public:
explicit PSLL_Iter(Node* start = nullptr) {
here = start;
}
PSLL_Iter(const PSLL_Iter& src) {
here = src.here;
}
reference operator*() const {
if (!here) {
throw std::runtime_error("Can't evaluate (*) at null node location!");
}
return here->data;
}
pointer operator->() const {
if (!here) {
throw std::runtime_error("Can't use -> operator with a null node");
}
return &(operator*());
}
self_reference operator=(PSLL_Iter<DataT>const& src) {
if(this == &src){
return *this;
}
here = src.here;
return *this;
}
self_reference operator++() {
if (!here) {
throw std::runtime_error("Can't use ++(pre) operator at null position");
}
here = here->next;
return *this;
}
self_type operator++(int) {
if (!here) {
throw std::runtime_error("Can't use ++(post) operator with a null node");
}
PSLL_Iter<DataT> hold(*this);
here = here->next;
return hold;
}
bool operator==(PSLL_Iter<DataT>const& test) const {
return here == test.here;
}
bool operator!=(PSLL_Iter<DataT>const& test) const {
return here != test.here;
}
};
//typedef std::size_t size_t;
typedef T value_type;
typedef PSLL_Iter<T> iterator;
typedef PSLL_Iter<T const> const_iterator;
iterator begin(){
return iterator(head);
}
iterator end(){
return iterator();
}
const_iterator begin() const{
return const_iterator(head);
}
const_iterator end() const{
return const_iterator();
}
iterator grab(PSLL_Iter<T>& src){
return iterator(src);
}
PSLL(){
cout << "Created a Pooled Singly Linked-List!!!" << endl;
cout << "Created Empty Pool!" << endl;
}
~PSLL(){
cout << "Destroying Pooled Singly Linked-List!!!" << endl;
NodePtr temp = this->head;
while(temp!= nullptr){
NodePtr deleteThis = temp;
temp = temp->next;
delete deleteThis;
}
temp = this->free;
while(temp!= nullptr){
NodePtr deleteThis = temp;
temp = temp->next;
delete deleteThis;
}
cout << "Destroyed Pool!" << endl;
this->head = this->tail = this->free = nullptr;
}
PSLL(const PSLL& src) {
Node* temp = src.head;
while (temp) {
push_back(temp->data);
temp = temp->next;
}
cout << "Created Pooled Singly Linked-List (Copy CTR)!!!" << endl;
cout << "Created Empty Pool!!!" << endl;
}
PSLL(PSLL&& src) {
this->head = src.head;
this->tail = src.tail;
this->free = src.free;
src.head = src.tail = src.free = nullptr;
cout << "Created Pooled Singly Linked-List (Move CTR)!!!" << endl;
cout << "Created Empty Pool!!!" << endl;
}
PSLL& operator=(const PSLL& src) {
if (&src == this)
return *this;
clear();
NodePtr temp = src.head;
while (temp) {
push_back(temp->data);
temp = temp->next;
}
return *this;
}
PSLL& operator=(PSLL&& src) {
if (&src == this)
return *this;
clear();
this->head = src.head;
this->tail = src.tail;
this->free = src.free;
src.head = src.tail = src.free = nullptr;
return *this;
}
T& operator[](size_t position) {
if (position < 0 || position >= length()) {
throw std::out_of_range("Array index out of bounds!");
}
Node* temp = head;
int cnt = position;
while(--cnt >= 0){
temp = temp->next;
}
return temp->data;
}
T const& operator[](size_t position) const {
if (position < 0 || position >= length()) {
throw std::out_of_range("Array index out of bounds!");
}
Node* temp = head;
for (size_t j = 0; j < position; j++) {
temp = temp->next;
}
return temp->data;
}
size_t length()const{
if(this->head == nullptr){
return 0;
}
NodePtr temp = this->head;
size_t cnt = 0;
while(temp != nullptr){
cnt++;
temp = temp->next;
}
return cnt;
}
bool is_empty()const{
return (this->head == nullptr);
}
bool is_full()const{
NodePtr test = new(std::nothrow) Node;
if(!test && grab_pool_length() == 0)
return true;
delete test;
return false;
}
void clear(){
NodePtr temp = this->head;
while(temp!= nullptr){
NodePtr thisOne = temp;
temp = temp->next;
delete thisOne;
}
this->head = this->tail = nullptr;
return;
}
std::ostream& print(std::ostream& stream)const{
if(is_empty()){
stream << "<empty list>";
return stream;
}
NodePtr temp = this->head;
stream << "[";
while(temp->next != nullptr){
stream << temp->data << ",";
temp = temp->next;
}
stream << temp->data;
stream << "]";
return stream;
}
T& peek_back()const{
if(is_empty()){
throw std::runtime_error("ERROR: Can't peek at back of PSLL because PSLL is empty!!!");
}
return this->tail->data;
}
T& peek_front()const{
if(is_empty()){
throw std::runtime_error("ERROR: Can't peek at front of PSLL because PSLL is empty!!!");
}
return this->head->data;
}
T pop_back(){
if(is_empty()){
throw std::runtime_error("ERROR: Can't pop at back of PSLL because PSLL is empty!!!");
}
if(length() == 1){
T result = this->tail->data;
NodePtr send_back = this->tail;
send_to_pool(send_back);
this->head = nullptr;
this->tail = nullptr;
return result;
}
NodePtr temp = this->head;
while(temp->next->next != nullptr){
temp = temp->next;
}
T result = temp->next->data;
NodePtr send_back = temp->next;
temp->next = nullptr;
this->tail = temp;
send_to_pool(send_back);
return result;
}
T pop_front(){
if(is_empty()){
throw std::runtime_error("ERROR: Can't pop at front of PSLL because PSLL is empty!!!");
}
if(length() == 1){
this->tail = nullptr;
}
T result = this->head->data;
NodePtr newHead = this->head->next;
this->head->next = nullptr;
send_to_pool(this->head);
this->head = newHead;
return result;
}
void push_front(const T& item){
if(is_full()){
throw std::runtime_error("ERROR: Can't push at front of PSLL because PSLL is full!!!");
}
NodePtr newNode = grab_from_pool();
newNode->data = item;
newNode->next = this->head;
this->head = newNode;
if(this->tail == nullptr){
this->tail = newNode;
}
return;
}
void push_back(const T& item){
if(is_full()){
throw std::runtime_error("ERROR: Can't push at back of PSLL because PSLL is full!!!");
}
NodePtr newNode = grab_from_pool();
newNode->data = item;
if(this->tail != nullptr){
this->tail->next = newNode;
}
else{
this->head = newNode;
}
newNode->next = nullptr;
this->tail = newNode;
return;
}
T& item_at(size_t position)const{
if(position < 0 || position >= length()){
throw std::runtime_error("ERROR: Invalid Input for position in T PSLL::item_at(size_t position)!");
}
if(position == 0){
return peek_front();
}
if((position + 1) == length()){
return peek_back();
}
int cnt = static_cast<int>(position);
NodePtr temp = this->head;
while(--cnt>=0){
temp = temp->next;
}
return temp->data;
}
T* contents()const{
T* arr = new T[length()];
NodePtr temp = this->head;
size_t len = length();
for(size_t i = 0; i < len; i++){
arr[i] = temp->data;
temp = temp->next;
}
return arr;
}
T remove(size_t position){
if(position < 0 || position >= length()){
throw std::runtime_error("ERROR: Invalid input for position in T PSLL:remove(size_t position)!");
}
if(position == 0){
return pop_front();
}
if((position + 1) == length()){
return pop_back();
}
NodePtr temp = this->head;
int cnt = static_cast<int>(position);
while(--cnt>0){
temp = temp->next;
}
NodePtr removeThis = temp->next;
T result = removeThis->data;
NodePtr newNext = removeThis->next;
temp->next = newNext;
removeThis->next = nullptr;
send_to_pool(removeThis);
return result;
}
bool contains(const T& element, bool (*equals)(const T&,const T&))const{
if(is_empty()){
return false;
}
NodePtr temp = this->head;
while(temp != nullptr){
if(equals(element, temp->data)){
return true;
}
temp = temp->next;
}
return false;
}
void insert(const T& element, size_t position){
if(position < 0 || position >= (length()+1)){
throw std::runtime_error("ERROR: Invalid input for position in void PSLL:insert(T element,size_t position)!");
}
if(position == 0){
push_front(element);
return;
}
if(position == length()){
push_back(element);
return;
}
int cnt = static_cast<int>(position);
NodePtr temp = head;
while(--cnt > 0){
temp = temp->next;
}
NodePtr newNode = grab_from_pool();
newNode->data = element;
NodePtr oldNext = temp->next;
temp->next = newNode;
newNode->next = oldNext;
return;
}
T replace(const T& element, size_t position){
if(position < 0 || position >= length()){
throw std::runtime_error("ERROR: Invalid Input for position in T PSLL:replace(T element,size_t position)!");
}
int cnt = static_cast<int>(position);
NodePtr temp = head;
while(--cnt >= 0){
temp = temp->next;
}
T result = temp->data;
temp->data = element;
return result;
}
unsigned int grab_pool_length() const{
if(this->free == nullptr)
return 0;
NodePtr temp = this->free;
unsigned int result = 0;
while(temp != nullptr){
result++;
temp = temp->next;
}
return result;
}
static bool equals(const T& element, const T& compareValue){
return (element == compareValue);
}
};
}
#endif //COP3530_PROJECT_1_PSLL_H
| true |
8348060565dd2ace18985dac050ed23bdc08d241 | C++ | bcooperstl/advent-of-code-2015 | /include/solutions/aoc_day_22.h | UTF-8 | 2,473 | 2.71875 | 3 | [
"MIT"
] | permissive | #ifndef __AOC_DAY_22__
#define __AOC_DAY_22__
#include <string>
#include "aoc_day.h"
#define MAX_TURNS 128
#define MAX_SPELLS 5
#define SPELL_MAGIC_MISSLE 0
#define SPELL_DRAIN 1
#define SPELL_SHEILD 2
#define SPELL_POISON 3
#define SPELL_RECHAHRGE 4
#define SPELL_NONE_OR_BOSS 99
#define PLAYER_START_MANA 500
#define PLAYER_START_ARMOR 0
#define PLAYER_START_HIT_POINTS 50
#define PLAYER_START_DAMAGE 0
#define GAME_NOT_OVER 0
#define GAME_OVER_PLAYER_WON 1
#define GAME_OVER_BOSS_WON 2
namespace Day22
{
struct GameStats
{
int turn_number;
int player_hit_points;
int player_armor;
int player_mana;
int player_damage;
int boss_hit_points;
int boss_damage;
int last_spell_played;
int player_total_mana_spent;
};
struct Spell
{
string name;
int cost;
int instant_damage_dealt;
int instant_healing_applied;
int num_turns;
int armor_boost;
int start_turn_damage_dealt;
int start_turn_mana_mined;
};
}
using namespace Day22;
class AocDay22 : public AocDay
{
private:
Spell m_spells[MAX_SPELLS];
void parse_input(string filename, int & enemy_hit_points, int & enemy_damage);
void init_spells();
void setup_turn_0(GameStats * turn_stats, int player_hit_points, int player_armor, int player_mana, int player_damage, int enemy_hit_points, int enemy_damage);
bool can_cast_spell(GameStats * turn_stats, int current_turn, int spell_number);
void clear_turn(GameStats * turn_stats, int current_turn);
void init_turn(GameStats * turn_stats, int current_turn, bool apply_hard_mode_adjustment);
void reinit_turn(GameStats * turn_stats, int current_turn, bool apply_hard_mode_adjustment);
void apply_spell(GameStats * turn_stats, int current_turn, int spell_number);
void boss_attack(GameStats * turn_stats, int current_turn);
int is_game_over(GameStats * turn_stats, int current_turn);
int find_player_win_least_mana(GameStats * turn_stats, bool is_hard_mode);
public:
AocDay22();
~AocDay22();
string run_test_scenario_part1(int scenario_number);
string part1(string filename, vector<string> extra_args);
string part2(string filename, vector<string> extra_args);
};
#endif
| true |
5d57e1540353639e361b7bda97d52692480ca604 | C++ | hphp/Algorithm | /Contest/ACM/2010_bak/MULTIPLE_2010/zstu/merge/cube/cube.cpp | UTF-8 | 1,487 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
const int MaxN = 505;
bool vis[15][5], success;
int n, top, deg[15], hash[MaxN];
struct E {
int s, e;
}edge[MaxN][5];
void Input ()
{
int i, j;
char str[5][10];
scanf ("%d", &n);
getchar ();
E tmp;
for (i = 0; i < n; i++) {
for (j = 0; j < 3; j++) {
gets (str[j]);
}
tmp.s = hash[str[0][1]]; tmp.e = hash[str[2][1]];
edge[i][0] = tmp;
tmp.s = hash[str[1][0]]; tmp.e = hash[str[1][2]];
edge[i][1] = tmp;
tmp.s = hash[str[1][1]]; tmp.e = hash[str[1][3]];
edge[i][2] = tmp;
}
}
void DFS (int deep, int ch)
{
int i, s, e;
if (deep == n) {
for (i = 1; i <= n; i++) {
if (deg[i] != 2 + ch * 2) break;
}
if (i <= n) return ;
if (ch == 0) DFS (0, 1);
else success = true;
return ;
}
for (i = 0; i < 3; i++) {
if (vis[deep][i]) continue;
s = edge[deep][i].s; e = edge[deep][i].e;
if (deg[s] > 1 + ch * 2 || deg[e] > 1 + ch * 2) continue;
vis[deep][i] = true;
deg[s]++; deg[e]++;
DFS (deep + 1, ch);
if (success) return ;
vis[deep][i] = false;
deg[s]--; deg[e]--;
}
}
int main ()
{
int i, T, CS = 1;
scanf ("%d", &T);
for (i = 'A'; i <= 'J'; i++) hash[i] = i - 'A' + 1;
while (T--) {
Input ();
success = false;
memset (deg, 0, sizeof (deg));
memset (vis, false, sizeof (vis));
DFS (0, 0);
printf ("Case #%d: ", CS++);
if (success) {
puts ("Yes");
}
else puts ("No");
}
return 0;
}
| true |
979f3574059adde8f39cd1f34d31b3172889b646 | C++ | notantony/cpp-course | /hw3/vector.cpp | UTF-8 | 4,827 | 2.859375 | 3 | [] | no_license | #include "vector.h"
#include <exception>
#include <algorithm>
vector::vector(): isEmpty(true) {}
vector::vector(size_t size) : vector(size, 0) {}
vector::vector(size_t size, uint32_t one) {
switch (size) {
case 0:
isEmpty = true;
break;
case 1:
isEmpty = false;
isSmall = true;
num = one;
break;
default:
isEmpty = false;
isSmall = false;
new (&shared) std::shared_ptr<std::vector<uint32_t>>(new std::vector<uint32_t>(size, one));
break;
}
}
vector::vector(vector const &one) {
if (one.isEmpty) {
isEmpty = one.isEmpty;
return;
}
if (one.isSmall) {
isEmpty = one.isEmpty;
isSmall = one.isSmall;
num = one.num;
return;
}
isEmpty = one.isEmpty;
isSmall = one.isSmall;
new (&shared) std::shared_ptr<std::vector<uint32_t>>(one.shared);
}
size_t vector::size() const {
if (isEmpty) {
return 0;
}
if (isSmall) {
return 1;
}
return shared.get()->size();
}
void vector::operator=(vector const& one) {
if (!isEmpty && !isSmall){
if (!one.isEmpty && !one.isSmall) {
shared = one.shared;
} else {
shared.~__shared_ptr();
num = one.num;
}
} else {
if (!one.isEmpty && !one.isSmall) {
new (&shared) std::shared_ptr<std::vector<uint32_t>>(one.shared);
} else {
num = one.num;
}
}
this->isEmpty = one.isEmpty;
this->isSmall = one.isSmall;
//swap(*this, tmp);
}
uint32_t vector::back() const {
if (isEmpty) {
throw std::runtime_error("Error: .back() called on empty vector");
}
if (isSmall) {
return num;
}
return shared.get()->back();
}
uint32_t const& vector::operator[](size_t i) const {
if (isEmpty) {
throw std::runtime_error("Error: operator[] called on empty vector");
}
if (isSmall) {
if (i == 0) {
return num;
} else {
throw std::runtime_error("Error: operator[] out of bound on small vector");
}
}
return (*shared.get())[i];
}
bool vector::operator==(vector const& one) const {
if (isEmpty || one.isEmpty) {
return isEmpty == one.isEmpty;
}
if (isSmall != one.isSmall) {
return false;
}
if (isSmall) {
return num == one.num;
}
return *shared.get() == *one.shared.get();
}
uint32_t& vector::operator[](size_t i) {
if (isEmpty) {
throw std::runtime_error("Error: operator[] called on empty vector");
}
if (isSmall) {
if (i == 0) {
return num;
} else {
throw std::runtime_error("Error: operator[] out of bound on small vector");
}
}
if(shared.use_count() != 1) {
shared.reset(new std::vector<uint32_t>(*shared.get()));
//shared = make_shared<std::vector<uint32_t>>(*shared.get());
}
return (*shared.get())[i];
}
void vector::pop_back() {
if (isEmpty) {
throw std::runtime_error("Error: .pop_back() called on empty vector");
}
if (isSmall) {
isEmpty = true;
return;
}
if (shared.use_count() != 1) {
shared.reset(new std::vector<uint32_t>(*shared.get()));
}
if (shared.get()->size() == 2) {
isSmall = 1;
uint32_t tmp = (*shared.get())[0];
shared.reset();
num = tmp;
return;
}
shared.get()->pop_back();
}
void vector::push_back(uint32_t x) {
if (isEmpty) {
isEmpty = false;
isSmall = true;
num = x;
return;
}
if (isSmall) {
isSmall = false;
//new (&shared)
//shared = std::make_shared<std::vector<uint32_t>>(1, num);
new (&shared) std::shared_ptr<std::vector<uint32_t>>(new std::vector<uint32_t>(1, num));
shared.get()->push_back(x);
return;
}
if (shared.use_count() != 1) {
shared.reset(new std::vector<uint32_t>(*shared.get()));
}
shared.get()->push_back(x);
}
void vector::reverse() {
if (isEmpty || isSmall) {
return;
}
if (shared.use_count() != 1) {
shared.reset(new std::vector<uint32_t>(*shared.get()));
}
std::reverse(shared.get()->begin(), shared.get()->end());
}
void vector::resize(size_t size) {
resize(size, 0);
}
void vector::resize(size_t size, uint32_t one) {
vector tmp = vector(size, one);
swap(tmp);
//swap(*this, tmp);
}
vector::~vector() {
if (isEmpty || isSmall) {
return;
}
//shared.reset();
shared.~__shared_ptr();//fix
//shared->~std::shared_ptr<std::vector<uint32_t>>();
//~shared();
}
void vector::swap(vector& one) {//fix
vector tmp(one);
one = *this;
*this = tmp;
}
| true |
d54ff83d32b8b49907c62e7cf3ccd98d5b38b656 | C++ | aditya81070/Data-Structures-and-Algoritham | /Codechef-solutions/LUCKFOUR.cpp | UTF-8 | 485 | 2.5625 | 3 | [] | no_license | #include<stdio.h>
#include<cmath>
int main() {
int t;
scanf("%d", &t);
long int n;
while(t--) {
scanf("%ld", &n);
long int count = 0, digits;
int last, first;
while(n > 0) {
last = n % 10;
n = n/10;
digits = int(log10(n));
first = n / pow(10, digits);
n = n - first * pow(10, digits);
if (first == 4) {
count++;
}
if(last == 4) {
count++;
}
}
printf("%ld", count);
}
return 0;
} | true |
f5e00755ad14984ee3794f7c7a2f24bd6d555c92 | C++ | SoWeBegin/Dark-Knight-Chess-Engine | /Dark Knight v.1/move_generator.cpp | UTF-8 | 17,152 | 2.8125 | 3 | [] | no_license | #include "move_generator.h"
#include "bitboard.h"
void MovesList::gen_blackpawnmoves(const Board& position, bool quiet) noexcept {
constexpr int forward{ -10 };
constexpr int diag_right{ -11 };
constexpr int diag_left{ -9 };
constexpr int color{ Enums::B_PAWN };
constexpr int initial_rank{ Enums::RANK7 };
for (int currpiece{}; currpiece < position.pieces_left_index(color); ++currpiece) {
int square{ position.pieces_list_index(color, currpiece) };
if (position.pieces_index(square + forward) == Enums::NO_PIECE) { // pawn can march forward
set_blackpawn_move(position, MoveUtils::gen_singlemove(square, square + forward), quiet);
auto doublepawnmove = square + (forward * 2);
if (position.get_rank[square] == initial_rank && position.pieces_index(doublepawnmove) == Enums::NO_PIECE) { // Two-moves forward (init pawn jump)
set_quietmove(position, MoveUtils::gen_singlemove(square, doublepawnmove, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::pawnfirst));
}
}
// Captures diagonally
if (Board::square_exists(square + diag_left) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_left)) == Enums::WHITE) {
set_blackpawn_move(position, MoveUtils::gen_singlemove(square, square + diag_left, position.pieces_index(square + diag_left)));
}
if (Board::square_exists(square + diag_right) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_right)) == Enums::WHITE) {
set_blackpawn_move(position, MoveUtils::gen_singlemove(square, square + diag_right, position.pieces_index(square + diag_right)));
}
auto ep_square{ position.enPassant_square() };
// Enpassant captures
if (ep_square != Enums::NO_SQUARE) {
if (square + diag_left == ep_square) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_left, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
if (square + diag_right == ep_square) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_right, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
}
}
}
void MovesList::gen_blackpawnmoves_capt(const Board& position) noexcept {
constexpr int diag_right{ -11 };
constexpr int diag_left{ -9 };
constexpr int color{ Enums::B_PAWN };
for (int currpiece{}; currpiece < position.pieces_left_index(color); ++currpiece) {
int square{ position.pieces_list_index(color, currpiece) };
if (Board::square_exists(square + diag_left) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_left)) == Enums::WHITE) {
set_blackpawn_move(position, MoveUtils::gen_singlemove(square, square + diag_left, position.pieces_index(square + diag_left)));
}
if (Board::square_exists(square + diag_right) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_right)) == Enums::WHITE) {
set_blackpawn_move(position, MoveUtils::gen_singlemove(square, square + diag_right, position.pieces_index(square + diag_right)));
}
auto ep_square{ position.enPassant_square() };
if (ep_square != Enums::NO_SQUARE) {
if (square + diag_left == ep_square) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_left, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
if (square + diag_right == ep_square) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_right, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
}
}
}
void MovesList::gen_whitepawnmove(const Board& position, bool quiet) noexcept {
constexpr int forward{ 10 };
constexpr int diag_right{ 11 };
constexpr int diag_left{ 9 };
constexpr int color{ Enums::W_PAWN };
constexpr int initial_rank{ Enums::RANK2 };
for (int currpiece{}; currpiece < position.pieces_left_index(color); ++currpiece) {
int square{ position.pieces_list_index(color, currpiece) };
if (position.pieces_index(square + forward) == Enums::NO_PIECE) { // pawn can march forward
set_whitepawn_move(position, MoveUtils::gen_singlemove(square, square + forward), quiet);
if (position.get_rank[square] == initial_rank && position.pieces_index(square + (forward + forward)) == Enums::NO_PIECE) { // Two-moves forward (init pawn jump)
set_quietmove(position, MoveUtils::gen_singlemove(square, square + (forward + forward), Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::pawnfirst));
}
}
// Captures diagonally
if (Board::square_exists(square + diag_left) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_left)) == Enums::BLACK) {
set_whitepawn_move(position, MoveUtils::gen_singlemove(square, square + diag_left, position.pieces_index(square + diag_left)));
}
if (Board::square_exists(square + diag_right) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_right)) == Enums::BLACK) {
set_whitepawn_move(position, MoveUtils::gen_singlemove(square, square + diag_right, position.pieces_index(square + diag_right)));
}
// Enpassant captures
auto ep{ position.enPassant_square() };
if (ep != Enums::NO_SQUARE) {
if (square + diag_left == ep) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_left, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
if (square + diag_right != 99 && square + diag_right == ep) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_right, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
}
}
}
void MovesList::gen_whitepawnmoves_capt(const Board& position) noexcept {
constexpr int diag_right{ 11 };
constexpr int diag_left{ 9 };
constexpr int color{ Enums::W_PAWN };
for (int currpiece{}; currpiece < position.pieces_left_index(color); ++currpiece) {
int square{ position.pieces_list_index(color, currpiece) };
if (Board::square_exists(square + diag_left) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_left)) == Enums::BLACK) {
set_whitepawn_move(position, MoveUtils::gen_singlemove(square, square + diag_left, position.pieces_index(square + diag_left)));
}
if (Board::square_exists(square + diag_right) &&
PieceInfo::get_piece_color(position.pieces_index(square + diag_right)) == Enums::BLACK) {
set_whitepawn_move(position, MoveUtils::gen_singlemove(square, square + diag_right, position.pieces_index(square + diag_right)));
}
auto ep{ position.enPassant_square() };
if (ep != Enums::NO_SQUARE) {
if (square + diag_left == ep) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_left, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
if (square + diag_right != 99 && square + diag_right == ep) {
set_epmove(position, MoveUtils::gen_singlemove(square, square + diag_right, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::enpassant));
}
}
}
}
void MovesList::gen_black_castle_moves(const Board& position) noexcept {
if ((position.castle_rights() & Enums::KING_SIDE_B) && position.pieces_index(Enums::F8) == Enums::NO_PIECE && position.pieces_index(Enums::G8) == Enums::NO_PIECE
&& !position.is_square_attacked(Enums::E8, Enums::WHITE) && !position.is_square_attacked(Enums::F8, Enums::WHITE)) {
set_quietmove(position, MoveUtils::gen_singlemove(Enums::E8, Enums::G8, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::castle));
}
if ((position.castle_rights() & Enums::QUEEN_SIDE_B) && position.pieces_index(Enums::D8) == Enums::NO_PIECE && position.pieces_index(Enums::C8) == Enums::NO_PIECE && position.pieces_index(Enums::B8) == Enums::NO_PIECE
&& !position.is_square_attacked(Enums::E8, Enums::WHITE) && !position.is_square_attacked(Enums::D8, Enums::WHITE)) {
set_quietmove(position, MoveUtils::gen_singlemove(Enums::E8, Enums::C8, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::castle));
}
}
void MovesList::gen_white_castle_moves(const Board& position) noexcept {
// King side castle available
// No pieces between king-rook
// no squares between king-rook attacked
if ((position.castle_rights() & Enums::KING_SIDE_W) && position.pieces_index(Enums::F1) == Enums::NO_PIECE && position.pieces_index(Enums::G1) == Enums::NO_PIECE
&& !position.is_square_attacked(Enums::E1, Enums::BLACK) && !position.is_square_attacked(Enums::F1, Enums::BLACK)) {
set_quietmove(position, MoveUtils::gen_singlemove(Enums::E1, Enums::G1, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::castle));
}
if ((position.castle_rights() & Enums::QUEEN_SIDE_W) && position.pieces_index(Enums::D1) == Enums::NO_PIECE && position.pieces_index(Enums::C1) == Enums::NO_PIECE
&& position.pieces_index(Enums::B1) == Enums::NO_PIECE && !position.is_square_attacked(Enums::E1, Enums::BLACK) && !position.is_square_attacked(Enums::D1, Enums::BLACK)) {
set_quietmove(position, MoveUtils::gen_singlemove(Enums::E1, Enums::C1, Enums::NO_PIECE, Enums::NO_PIECE, MoveUtils::castle));
}
}
void MovesList::gen_slide_moves(const Board& position, std::size_t piece_index) noexcept {
int piece{ PieceInfo::loop_slide[piece_index++] };
while (piece != Cnst::ZERO_PIECES) {
for (int currpiece{}; currpiece < position.pieces_left_index(piece); ++currpiece) {
int square{ position.pieces_list_index(piece, currpiece) };
for (int index{}; index < PieceInfo::get_tot_direction(piece); ++index) {
int direction{ PieceInfo::get_direction(piece, index) };
int temp_square{ square + direction };
while (Board::square_exists(temp_square)) {
if (position.pieces_index(temp_square) != Enums::NO_PIECE) {
if (PieceInfo::get_piece_color(position.pieces_index(temp_square)) == (position.turn() ^ 1)) {
set_tacticalmove(position, MoveUtils::gen_singlemove(square, temp_square, position.pieces_index(temp_square)));
}
break;
}
set_quietmove(position, MoveUtils::gen_singlemove(square, temp_square));
temp_square += direction;
}
}
}
piece = PieceInfo::loop_slide[piece_index++];
}
}
void MovesList::gen_slide_moves_capt(const Board& position, std::size_t piece_index) noexcept {
int piece{ PieceInfo::loop_slide[piece_index++] };
while (piece != Cnst::ZERO_PIECES) {
for (int currpiece{}; currpiece < position.pieces_left_index(piece); ++currpiece) {
int square{ position.pieces_list_index(piece, currpiece) };
for (int index{}; index < PieceInfo::get_tot_direction(piece); ++index) {
int direction{ PieceInfo::get_direction(piece, index) };
int temp_square{ square + direction };
while (Board::square_exists(temp_square)) {
if (position.pieces_index(temp_square) != Enums::NO_PIECE) {
if (PieceInfo::get_piece_color(position.pieces_index(temp_square)) == (position.turn() ^ 1)) {
set_tacticalmove(position, MoveUtils::gen_singlemove(square, temp_square, position.pieces_index(temp_square)));
}
break;
}
temp_square += direction;
}
}
}
piece = PieceInfo::loop_slide[piece_index++];
}
}
void MovesList::gen_nonslide_moves(const Board& position, std::size_t piece_index) noexcept {
int piece{ PieceInfo::loop_nonslide[piece_index++] };
auto pieces_left{ position.pieces_left() };
auto pieces_list{ position.pieces_list() };
auto pieces{ position.pieces() };
while (piece != Cnst::ZERO_PIECES) {
for (int currpiece{}; currpiece < pieces_left[piece]; ++currpiece) {
int square{ pieces_list[piece][currpiece] };
for (int index{}; index < PieceInfo::get_tot_direction(piece); ++index) {
int direction{ PieceInfo::get_direction(piece, index) };
int temp_square{ square + direction };
if (!Board::square_exists(temp_square)) continue;
if (pieces[temp_square] != Enums::NO_PIECE) {
// There's a piece on the generated move -> capture
if (PieceInfo::get_piece_color(pieces[temp_square]) == (position.turn() ^ 1)) {
set_tacticalmove(position, MoveUtils::gen_singlemove(square, temp_square, pieces[temp_square]));
}
continue;
}
set_quietmove(position, MoveUtils::gen_singlemove(square, temp_square));
}
}
piece = PieceInfo::loop_nonslide[piece_index++];
}
}
void MovesList::gen_nonslide_moves_capt(const Board& position, std::size_t piece_index) noexcept {
int piece{ PieceInfo::loop_nonslide[piece_index++] };
auto pieces_left{ position.pieces_left() };
auto pieces_list{ position.pieces_list() };
auto pieces{ position.pieces() };
while (piece != Cnst::ZERO_PIECES) {
for (int currpiece{}; currpiece < pieces_left[piece]; ++currpiece) {
int square{ pieces_list[piece][currpiece] };
for (int index{}; index < PieceInfo::get_tot_direction(piece); ++index) {
int direction{ PieceInfo::get_direction(piece, index) };
int temp_square{ square + direction };
if (!Board::square_exists(temp_square)) continue;
if (pieces[temp_square] != Enums::NO_PIECE) {
// There's a piece on the generated move -> capture
if (PieceInfo::get_piece_color(pieces[temp_square]) == (position.turn() ^ 1)) {
set_tacticalmove(position, MoveUtils::gen_singlemove(square, temp_square, pieces[temp_square]));
}
continue;
}
}
}
piece = PieceInfo::loop_nonslide[piece_index++];
}
}
void MovesList::set_whitepawn_move(const Boards::Board& position, int move, bool quiet) noexcept {
assert(Board::piece_exists(MoveUtils::get_capt(move)) && Board::square_exists(MoveUtils::get_from(move))
&& Board::square_exists(MoveUtils::get_to(move)));
auto cap{ MoveUtils::get_capt(move) };
auto to{ MoveUtils::get_to(move) };
auto from{ MoveUtils::get_from(move) };
if (quiet) {
if (Board::get_rank[from] == Enums::RANK7) { // Move is promotion
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_QUEEN));
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_ROOK));
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_BISHOP));
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_KNIGHT));
}
else {
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::NO_PIECE));
}
}
else {
if (Board::get_rank[from] == Enums::RANK7) { // Move is promotion
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_QUEEN));
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_ROOK));
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_BISHOP));
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::W_KNIGHT));
}
else {
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::NO_PIECE));
}
}
}
void MovesList::set_blackpawn_move(const Boards::Board& position, int move, bool quiet) noexcept {
assert(Board::piece_exists(MoveUtils::get_capt(move)) && Board::square_exists(MoveUtils::get_from(move))
&& Board::square_exists(MoveUtils::get_to(move)));
auto cap{ MoveUtils::get_capt(move) };
auto to{ MoveUtils::get_to(move) };
auto from{ MoveUtils::get_from(move) };
if (quiet) {
if (Board::get_rank[from] == Enums::RANK2) { // Move is promotion
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_QUEEN));
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_ROOK));
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_BISHOP));
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_KNIGHT));
}
else {
set_quietmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::NO_PIECE));
}
}
else {
if (Board::get_rank[from] == Enums::RANK2) { // Move is promotion
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_QUEEN));
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_ROOK));
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_BISHOP));
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::B_KNIGHT));
}
else {
set_tacticalmove(position, MoveUtils::gen_singlemove(from, to, cap, Enums::NO_PIECE));
}
}
}
void MovesList::generate_moves(const Board& position) noexcept {
assert(position.board_check());
tot_moves = 0;
int turn{ position.turn() };
if (turn == Enums::WHITE) {
gen_whitepawnmove(position);
gen_white_castle_moves(position);
gen_slide_moves(position, 0);
gen_nonslide_moves(position, 0);
}
else {
gen_blackpawnmoves(position);
gen_black_castle_moves(position);
gen_slide_moves(position, 4);
gen_nonslide_moves(position, 3);
}
}
void MovesList::gen_captures_only(const Board& position) noexcept {
tot_moves = 0;
if (position.turn() == Enums::WHITE) {
gen_whitepawnmoves_capt(position);
gen_slide_moves_capt(position, 0);
gen_nonslide_moves_capt(position, 0);
}
else {
gen_blackpawnmoves_capt(position);
gen_slide_moves_capt(position, 4);
gen_nonslide_moves_capt(position, 3);
}
}
[[nodiscard]] bool MovesList::move_check(Boards::Board& board, int move) noexcept {
// Sanity check in case two positions have the same zobrist key
generate_moves(board);
for (int curr{}; curr < tot_moves; ++curr) {
if (!board.make_move(all_moves[curr].move)) continue;
board.unmake_move();
if (all_moves[curr].move == move) return true;
}
return false;
}
| true |
24d085f416e309d3cba9a7a4bc40e2dbd90fcf2f | C++ | cxxtrace/cxxtrace | /test/pthread_thread_local_var.h | UTF-8 | 3,389 | 2.859375 | 3 | [] | no_license | #ifndef CXXTRACE_TEST_PTHREAD_THREAD_LOCAL_VAR_H
#define CXXTRACE_TEST_PTHREAD_THREAD_LOCAL_VAR_H
#if CXXTRACE_ENABLE_CONCURRENCY_STRESS
#include "concurrency_stress.h"
#include <array>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cxxtrace/detail/debug_source_location.h>
#include <cxxtrace/detail/warning.h>
#include <exception>
#include <memory>
#include <pthread.h>
#include <system_error>
#include <type_traits>
#endif
namespace cxxtrace_test {
#if CXXTRACE_ENABLE_CONCURRENCY_STRESS
template<class T>
class pthread_thread_local_var
{
public:
static_assert(std::is_trivial_v<T>);
explicit pthread_thread_local_var() noexcept(false)
: thread_state_{ pthread_key_create_checked(deallocate_thread_state) }
{}
pthread_thread_local_var(const pthread_thread_local_var&) = delete;
pthread_thread_local_var& operator=(const pthread_thread_local_var&) = delete;
~pthread_thread_local_var()
{
auto rc = ::pthread_key_delete(this->thread_state_);
if (rc != 0) {
std::perror(
"fatal: failed to set pthread_thread_local_var data thread-local key");
std::terminate();
}
}
auto operator-> () noexcept -> T* { return this->get(); }
auto operator*() noexcept -> T& { return *this->get(); }
auto get() noexcept -> T*
{
auto* current_thread_state =
static_cast<thread_state*>(::pthread_getspecific(this->thread_state_));
auto current_generation = current_concurrency_stress_generation();
if (current_thread_state) {
if (current_thread_state->initialized_generation != current_generation) {
current_thread_state->reset(current_generation);
}
} else {
auto unique_thread_state =
std::make_unique<thread_state>(current_generation);
current_thread_state = unique_thread_state.get();
auto rc =
::pthread_setspecific(this->thread_state_, current_thread_state);
if (rc != 0) {
std::perror("fatal: failed to set pthread_thread_local_var data for "
"current thread");
std::terminate();
}
unique_thread_state.release();
}
return ¤t_thread_state->value;
}
private:
struct thread_state
{
explicit thread_state(
concurrency_stress_generation current_generation) noexcept
{
this->reset(current_generation);
}
auto reset(concurrency_stress_generation current_generation) noexcept
-> void
{
this->initialized_generation = current_generation;
std::memset(&this->value, 0, sizeof(this->value));
}
concurrency_stress_generation initialized_generation /* uninitialized */;
T value /* uninitialized */;
};
static auto pthread_key_create_checked(void (*destructor)(void*)) noexcept(
false) -> ::pthread_key_t
{
::pthread_key_t key;
auto rc = ::pthread_key_create(&key, destructor);
if (rc != 0) {
throw std::system_error{ rc, std::generic_category() };
}
return key;
}
static auto deallocate_thread_state(void* opaque_thread_state) noexcept
-> void
{
deallocate_thread_state(static_cast<thread_state*>(opaque_thread_state));
}
static auto deallocate_thread_state(thread_state* state) noexcept -> void
{
auto unique_thread_state = std::unique_ptr<thread_state>(state);
unique_thread_state.reset();
}
::pthread_key_t thread_state_;
};
#endif
}
#endif
| true |
f202245b2549fcf5ab8977f79c3d34e606e950a7 | C++ | kajtuszd/PAiMSI | /lab4/src/Board.cpp | UTF-8 | 10,432 | 2.890625 | 3 | [] | no_license | #include "Board.h"
Spot Board::getBox(int y, int x)
{
if(x>boardLength-1 || y>boardLength-1 || x<0 || y<0)
{
std::cout << "Bad index" << std::endl;
}
return *boxes[y][x];
}
bool Board::cleanEndField(Spot &end)
{
if(!this->getBox(end.x,end.y).isEmpty())
{
this->boxes[end.x][end.y]->figure = NULL;
return true;
}
this->boxes[end.x][end.y]->figure = NULL;
return false;
}
std::vector<sf::FloatRect> Board::initializeSwapVectors()
{
std::vector<sf::FloatRect> vectors;
for (int i = 0; i < 4; ++i)
{
sf::FloatRect rect;
rect.left = i*56;
rect.top = 0;
rect.width = 56;
rect.height = 56;
vectors.push_back(rect);
}
return vectors;
}
void Board::chooseFigureToSwap(Figure* &fig, int &number)
{
sf::RenderWindow wind(sf::VideoMode(224,56),"Pawn exchange");
sf::Texture texture;
sf::Sprite sprite;
std::vector<sf::FloatRect> rects = initializeSwapVectors();
if(fig->isWhite())
{
if(!texture.loadFromFile("pic/black.png"))
std::cout << "Error while opening file" << std::endl;
}
else
{
if(!texture.loadFromFile("pic/white.png"))
std::cout << "Error while opening file" << std::endl;
}
sprite.setTexture(texture);
while(wind.isOpen())
{
sf::Event e;
sf::Vector2i mousePos = sf::Mouse::getPosition(wind);
while(wind.pollEvent(e))
{
if(e.type == sf::Event::Closed)
{
wind.close();
return;
}
if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
int k = 0;
for (std::vector<sf::FloatRect>::iterator i = rects.begin(); i != rects.end(); ++i)
{
sf::Vector2f position(mousePos);
if(i->contains(position))
{
number = k;
wind.close();
return;
}
k++;
}
}
}
wind.clear();
wind.draw(sprite);
wind.display();
sf::sleep(sf::milliseconds(10));
}
wind.close();
return;
}
int Board::rateBoard(bool cpuMove)
{
int whitePoints = 0;
int blackPoints = 0;
for (int i = 0; i < boardLength; ++i)
{
for (int j = 0; j < boardLength; ++j)
{
if(!this->getBox(i,j).isEmpty())
{
if(!this->getBox(i,j).getFigure()->isWhite())
whitePoints += this->rateField(i,j);
else
blackPoints += this->rateField(i,j);
}
}
}
if(cpuMove)
return blackPoints;
else
return whitePoints;
}
int Board::rateField(int x, int y)
{
int points;
points = this->getBox(x,y).getFigure()->points;
return points;
}
void Board::swapPawn(Spot &spot, Figure *&f, int num)
{
std::string name = f->name;
bool color = f->white;
sf::Vector2f move = f->picture.getPosition();
delete boxes[spot.x][spot.y]->getFigure();
boxes[spot.x][spot.y]->figure = NULL;
if(num == 0)
{
if(color)
{
boxes[spot.x][spot.y]->figure = new Rook(true);
}
else
{
boxes[spot.x][spot.y]->figure = new Rook(false);
}
}
if(num == 1)
{
if(color)
{
boxes[spot.x][spot.y]->figure = new Knight(true);
}
else
{
boxes[spot.x][spot.y]->figure = new Knight(false);
}
}
if(num == 2)
{
if(color)
{
boxes[spot.x][spot.y]->figure = new Bishop(true);
}
else
{
boxes[spot.x][spot.y]->figure = new Bishop(false);
}
}
if(num == 3)
{
if(color)
{
boxes[spot.x][spot.y]->figure = new Queen(true);
}
else
{
boxes[spot.x][spot.y]->figure = new Queen(false);
}
}
boxes[spot.x][spot.y]->getFigure()->picture.setPosition(move); /* ustawienie pozycji nowego sprajta */
}
void Board::moveFigure(Move &move, Figure *&f) /* utworzenie calkowicie nowego obiektu */
{
Spot end = move.getEnd();
Spot begin = move.getBegin();
delete boxes[end.x][end.y]->getFigure(); /* wyczyszczenie poczatkowego pola */
delete boxes[begin.x][begin.y]->getFigure(); /* wyczyszczenie koncowego pola */
if(f->name == "queen")
{
if(f->isWhite())
boxes[end.x][end.y]->figure = new Queen(true);
else
boxes[end.x][end.y]->figure = new Queen(false);
}
if(f->name == "king")
{
if(f->isWhite())
{
boxes[end.x][end.y]->figure = new King(true);
boxes[end.x][end.y]->figure->hasMoved = true;
}
else
{
boxes[end.x][end.y]->figure = new King(false);
boxes[end.x][end.y]->figure->hasMoved = true;
}
}
if(f->name == "bishop")
{
if(f->isWhite())
boxes[end.x][end.y]->figure = new Bishop(true);
else
boxes[end.x][end.y]->figure = new Bishop(false);
}
if(f->name == "knight")
{
if(f->isWhite())
boxes[end.x][end.y]->figure = new Knight(true);
else
boxes[end.x][end.y]->figure = new Knight(false);
}
if(f->name == "pawn")
{
if(f->isWhite())
{
boxes[end.x][end.y]->figure = new Pawn(true);
boxes[end.x][end.y]->figure->hasMoved = true;
}
else
{
boxes[end.x][end.y]->figure = new Pawn(false);
boxes[end.x][end.y]->figure->hasMoved = true;
}
}
if(f->name == "rook")
{
if(f->isWhite())
{
boxes[end.x][end.y]->figure = new Rook(true);
boxes[end.x][end.y]->figure->hasMoved = true;
}
else
{
boxes[end.x][end.y]->figure = new Rook(false);
boxes[end.x][end.y]->figure->hasMoved = true;
}
}
boxes[begin.x][begin.y]->figure = NULL;
}
void Board::setBoard()
{
loadBoardPic();
setFrames();
boxes[0][0] = new Spot(0,0, new Rook(true));
boxes[1][0] = new Spot(1,0, new Knight(true));
boxes[2][0] = new Spot(2,0, new Bishop(true));
boxes[3][0] = new Spot(3,0, new Queen(true));
boxes[4][0] = new Spot(4,0, new King(true));
boxes[5][0] = new Spot(5,0, new Bishop(true));
boxes[6][0] = new Spot(6,0, new Knight(true));
boxes[7][0] = new Spot(7,0, new Rook(true));
boxes[0][1] = new Spot(0,1, new Pawn(true));
boxes[1][1] = new Spot(1,1, new Pawn(true));
boxes[2][1] = new Spot(2,1, new Pawn(true));
boxes[3][1] = new Spot(3,1, new Pawn(true));
boxes[4][1] = new Spot(4,1, new Pawn(true));
boxes[5][1] = new Spot(5,1, new Pawn(true));
boxes[6][1] = new Spot(6,1, new Pawn(true));
boxes[7][1] = new Spot(7,1, new Pawn(true));
boxes[0][7] = new Spot(0,7, new Rook(false));
boxes[1][7] = new Spot(1,7, new Knight(false));
boxes[2][7] = new Spot(2,7, new Bishop(false));
boxes[3][7] = new Spot(3,7, new Queen(false));
boxes[4][7] = new Spot(4,7, new King(false));
boxes[5][7] = new Spot(5,7, new Bishop(false));
boxes[6][7] = new Spot(6,7, new Knight(false));
boxes[7][7] = new Spot(7,7, new Rook(false));
boxes[0][6] = new Spot(0,6, new Pawn(false));
boxes[1][6] = new Spot(1,6, new Pawn(false));
boxes[2][6] = new Spot(2,6, new Pawn(false));
boxes[3][6] = new Spot(3,6, new Pawn(false));
boxes[4][6] = new Spot(4,6, new Pawn(false));
boxes[5][6] = new Spot(5,6, new Pawn(false));
boxes[6][6] = new Spot(6,6, new Pawn(false));
boxes[7][6] = new Spot(7,6, new Pawn(false));
for (int i=0; i<8; i++)
{
for(int j=2; j<6; j++)
{
boxes[i][j] = new Spot(i,j,NULL);
}
}
setPositionsOnBoard();
}
void Board::loadBoardPic()
{
if(!this->board_tex.loadFromFile("pic/board.png"))
{
std::cout << "Error while opening file" << std::endl;
return;
}
board_tex.setSmooth(true);
this->board_spr.setTexture(board_tex);
return;
}
sf::Sprite Board::getSprite(int x, int y)
{
return this->getBox(x,y).getFigure()->picture;
}
void Board::setPositionsOnBoard()
{
for (int i = 0; i < 8; ++i)
{
for (int j = 0; j < 8; ++j)
{
if(getBox(i,j).getFigure() != NULL)
{
getBox(i,j).getFigure()->picture.setPosition(56*i+28,56*j+28);
}
}
}
}
std::list <Figure*> Board::returnFigures()
{
std::list <Figure*> allFigures;
allFigures.clear();
for (int i = 0; i < 8; ++i)
{
for (int j = 0; j < 8; ++j)
{
if(this->getBox(i,j).getFigure() != NULL)
{
allFigures.push_back(this->getBox(i,j).getFigure());
}
}
}
return allFigures;
}
std::list <Figure*> Board::returnFigures(bool color)
{
std::list <Figure*> colorFigures;
colorFigures.clear();
for (int i = 0; i < 8; ++i)
{
for (int j = 0; j < 8; ++j)
{
if(this->getBox(i,j).getFigure() != NULL)
{
if(this->getBox(i,j).getFigure()->isWhite() == color)
{
colorFigures.push_back(this->getBox(i,j).getFigure());
}
}
}
}
return colorFigures;
}
void Board::setFrames()
{
if(!this->yellow_texture.loadFromFile("pic/yellow.png"))
{
std::cout << "Error while opening file - yellow frame" << std::endl;
return;
}
if(!this->green_texture.loadFromFile("pic/green.png"))
{
std::cout << "Error while opening file - green frame" << std::endl;
return;
}
if(!this->red_texture.loadFromFile("pic/red.png"))
{
std::cout << "Error while opening file - red frame" << std::endl;
return;
}
this->yellowFrame.setTexture(yellow_texture);
this->greenFrame.setTexture(green_texture);
this->redFrame.setTexture(red_texture);
this->yellowFrame.setScale(56.0/210.0, 56.0/208.0);
this->redFrame.setScale(56.0/212.0, 56.0/212.0);
this->greenFrame.setScale(56.0/211.0, 56.0/214.0);
this->yellowFrame.setPosition(1000,1000);
this->redFrame.setPosition(1000,1000);
this->greenFrame.setPosition(1000,1000);
}
sf::Vector2f Board::adjustFrameSize(sf::Vector2f &vector)
{
vector.x = vector.x - 28;
vector.y = vector.y - 28;
int field_x = vector.x/56;
int field_y = vector.y/56;
sf::Vector2f result;
result.x = float(field_x)*56+28;
result.y = float(field_y)*56+28;
return result;
}
void Board::printFigures()
{
std::cout << std::endl;
for (unsigned int i = 0; i < boardLength; ++i)
{
for (unsigned int j = 0; j < boardLength; ++j)
{
if(boxes[j][i]->getFigure() == NULL)
std::cout << " ";
else
{
if (boxes[j][i]->getFigure()->name == "queen")
std::cout << "q ";
if (boxes[j][i]->getFigure()->name == "pawn")
std::cout << "p ";
if (boxes[j][i]->getFigure()->name == "bishop")
std::cout << "b ";
if (boxes[j][i]->getFigure()->name == "rook")
std::cout << "r ";
if (boxes[j][i]->getFigure()->name == "king")
std::cout << "k ";
if (boxes[j][i]->getFigure()->name == "knight")
std::cout << "^ ";
}
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void Board::printLegend()
{
std::cout << " Legend: " << std::endl;
std::cout << " q - queen " << std::endl;
std::cout << " p - pawn " << std::endl;
std::cout << " b - bishop " << std::endl;
std::cout << " r - rook " << std::endl;
std::cout << " k - king " << std::endl;
std::cout << " ^ - knight " << std::endl;
std::cout << " Preview map: " << std::endl;
std::cout << " Colors are not supported " << std::endl;
}
| true |
4883e9a29e273e190e75f7db038ccdd22bb2bc70 | C++ | mellery451/simple_code | /linked_list.cpp | UTF-8 | 2,438 | 3.828125 | 4 | [] | no_license | #include <cstdio>
#include <iostream>
#include <string>
#include <stdint.h>
#include <memory>
#include <cstdint>
/// @brief simple LL class to implement the
/// "classic" reverse a linked list interview
/// question
///
/// @tparam _T type held at each node, must be
/// copy constructable and have a public destructor
template <class _T>
class linked_list {
public:
linked_list() {};
struct node {
node() : _T() {};
node(const _T& t) : data(t) {};
_T data;
std::unique_ptr<node> pnext;
};
void add(const _T& thing) {
if (head) {
node* current = head.get();
node* last = nullptr;
while (current) {
last = current;
current = current->pnext.get();
}
last->pnext.reset(new node(thing));
}
else {
head.reset(new node(thing));
}
};
void reverse() {
node* last = nullptr;;
if (head) {
node* current = head.release();
while (current) {
node* temp = current->pnext.release();
current->pnext.reset(last);
last = current;
current = temp;
}
head.reset(last);
}
}
void print() {
node* pcurr = head.get();
while(pcurr) {
std::cout << pcurr->data << std::endl;
pcurr = pcurr->pnext.get();
}
}
private:
std::unique_ptr<node> head;
};
int main(int argc, char * argv[]) {
//LL with strings
linked_list<std::string> my_list_str;
my_list_str.add("one");
my_list_str.add("two");
my_list_str.add("three");
my_list_str.add("four");
my_list_str.add("five");
std::cout << "+++++++++++++++++++++++" << std::endl;
my_list_str.print();
std::cout << "-----------------------" << std::endl;
my_list_str.reverse();
my_list_str.print();
std::cout << "+++++++++++++++++++++++" << std::endl;
linked_list<uint32_t> my_list_int;
my_list_int.add(1);
my_list_int.add(2);
my_list_int.add(3);
my_list_int.add(4);
my_list_int.add(5);
std::cout << "+++++++++++++++++++++++" << std::endl;
my_list_int.print();
std::cout << "-----------------------" << std::endl;
my_list_int.reverse();
my_list_int.print();
std::cout << "+++++++++++++++++++++++" << std::endl;
return 0;
}
| true |
993114b3e07f42dbc4f97ba2586e6189816439cb | C++ | robotcator/acm-icpc | /sgu/p141.cpp | UTF-8 | 1,999 | 2.859375 | 3 | [] | no_license | // SGU 141 -- Jumping Joe
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const long long INF = 1000000000000000000LL;
long long gcd(long long a, long long b) {
return b == 0? a: gcd(b, a % b);
}
void solve(long long a, long long b, long long c, long long &x, long long &y) {
if (b == 0) {
x = c / a;
y = 0;
} else {
solve(b, a % b, c, y, x);
y -= a / b * x;
}
}
long long find(long long x_0, long long y_0, long long approximation, long long delta_x, long long delta_y, long long limit) {
for (long long t = approximation - 10; t <= approximation + 10; ++ t) {
long long tmp = abs(x_0 + delta_x * t) + abs(y_0 - delta_y * t);
if (tmp <= limit && ((limit - tmp) & 1) == 0) {
return t;
}
}
return INF;
}
long long a, b, c, m;
int main() {
cin >> a >> b >> c >> m;
long long d = gcd(a, b);
if (c % d == 0) {
long long x_0, y_0;
solve(a, b, c, x_0, y_0);
long long t_x = -x_0 / (b / d);
long long t_y = y_0 / (a / d);
long long choice = find(x_0, y_0, t_x, b / d, a / d, m);
if (choice == INF) {
choice = find(x_0, y_0, t_y, b / d, a / d, m);
}
if (choice == INF) {
cout << "NO" << endl;
} else {
long long x_1 = x_0 + b / d * choice;
long long y_1 = y_0 - a / d * choice;
long long left = m - abs(x_1) - abs(y_1);
long long x_positive = x_1 > 0? x_1: 0;
long long x_negative = x_1 < 0? -x_1: 0;
long long y_positive = y_1 > 0? y_1: 0;
long long y_negative = y_1 < 0? -y_1: 0;
x_positive += left / 2;
x_negative += left / 2;
cout << "YES" << endl;
cout << x_positive << " " << x_negative << " " << y_positive << " " << y_negative << endl;
}
} else {
cout << "NO" << endl;
}
return 0;
}
| true |
dd59cecc47b2f47903aa4cd192b363bbd3c16741 | C++ | k124k3n/competitive-programming-answer | /hackerrank/30 Days of Code/3. Intro to Conditional Statements.cpp | UTF-8 | 306 | 2.890625 | 3 | [
"MIT"
] | permissive | #include <iostream>
int n;
int main(){
std::cin>>n;
if(n % 2 != 0){
std::cout<<"Weird"<<std::endl;
}else{
if(n >= 2 && n <= 5){
std::cout<<"Not Weird"<<std::endl;
}else if(n >= 6 && n <= 20){
std::cout<<"Weird"<<std::endl;
}else{
std::cout<<"Not Weird"<<std::endl;
}
}
return 0;
} | true |
093396fb1a44c51febe5b2fc94cdfb3a163a0f69 | C++ | tanvirulz/cascade | /scrap/test_string.cpp | UTF-8 | 352 | 3.109375 | 3 | [] | no_license | // strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
typedef struct TestType {
int i;
} TestType;
int main ()
{
string str ("Please");
TestType tt;
tt.i=50;
cout<<str<<"\n";
str[2]='1';
cout<<str<<"\n";
cout<<str.length()<<"\n";
cout<<"tt has value: "<<tt.i<<endl;
return 0;
}
| true |
817d158d8c0016021c5e36919aac550c6bdd3498 | C++ | PrajwalaDeode/CPP | /templare.cpp | UTF-8 | 357 | 3.375 | 3 | [] | no_license |
#include<iostream>
using namespace std;
template<class T>
class addition
{
T a;
public:
addition(T num)
{
a=num;
cout<<"Value of a "<<a<<endl;
}
add(T num)
{
return a+num;
}
};
int main()
{
addition<int> a1(90);
cout<<"Addition is: "<<a1.add(78)<<endl;
return 0;
}
| true |
0502fc7ea57e064724f5e302f01a2862ce6f9871 | C++ | SteinsGate9/LinuxImageServer | /src/common/common.cpp | UTF-8 | 2,694 | 2.59375 | 3 | [] | no_license | /********************************************
* Content:
* Author: by shichenh.
* Date: on 2020-05-18.
********************************************/
#include "common.h"
/********************************************
* sighandlers
********************************************/
void addsig(int sig, void(handler)(int), bool restart) {
struct sigaction sa;
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = handler;
if (restart)
sa.sa_flags |= SA_RESTART;
sigfillset(&sa.sa_mask);
assert(sigaction(sig, &sa, NULL) != -1);
}
/********************************************
* file systems
********************************************/
int set_nonblocking(int fd)
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void set_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) < 0){
CONSOLE_LOG_ERROR("fcntl F_GETFL error with errno %d", errno);
}
val |= flags; /* turn on flags */
if (fcntl(fd, F_SETFL, val) < 0) {
CONSOLE_LOG_ERROR("fcntl F_SETFL error with errno %d", errno);
}
}
void clr_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) < 0) {
CONSOLE_LOG_ERROR("fcntl F_GETFL error with errno %d", errno);
}
val &= ~flags; /* turn flags off */
if (fcntl(fd, F_SETFL, val) < 0) {
CONSOLE_LOG_ERROR("fcntl F_SETFL error with errno %d", errno);
}
}
void add_fd(int epollfd, int fd, bool one_shot, bool LT)
{
epoll_event event;
event.data.fd = fd;
if (LT) {
event.events = EPOLLIN | EPOLLRDHUP;
}
else{
event.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
set_fl(fd, O_NONBLOCK);
}
if (one_shot)
event.events |= EPOLLONESHOT;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event) < 0){
CONSOLE_LOG_ERROR("epoll_ctl error: %s", strerror(errno));
}
}
void remove_fd(int epollfd, int fd)
{
if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0) < 0){
CONSOLE_LOG_ERROR("epoll_ctl error: %s", strerror(errno));
}
if (close(fd) <= 1){
CONSOLE_LOG_ERROR("close error: %s", strerror(errno));
}
}
void mod_fd(int epollfd, int fd, int ev)
{
epoll_event event;
event.data.fd = fd;
event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP;
epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &event);
}
/********************************************
* mem
********************************************/
//void unmap(char* file_address, ){
// if (file_address){
// munmap(file_address, m_file_stat.st_size);
// file_address = 0;
// }
//} | true |
9429642cc67b35310beb60ecf851ed455d33e3d0 | C++ | XFMemoirs/study | /线性表/双向缓冲链表.h | UTF-8 | 5,815 | 3.234375 | 3 | [] | no_license | #ifndef _LINK_LIST_H_
#define _LINK_LIST_H_
#include <stdint.h>
#define INIT_CACHE_LEN 16 // 初始化默认缓存长度
#define DILATATION_LEN 8 // 扩容长度
// 双向缓冲链表
template <typename T>
class Linklist
{
public:
// 节点
typedef struct ListNode
{
ListNode* mPre;
ListNode* mNext;
T mData;
}Ln;
public:
Linklist(int32_t cache_len = INIT_CACHE_LEN);
Linklist(const Linklist& other);
~Linklist(void);
T& operator [] (int32_t index);
Linklist& operator = (const Linklist& other);
Linklist& operator += (const Linklist& other);
// 推入
bool Push(T data);
// 弹出
bool Pop(void);
// 插入
bool Insert(T data, int32_t index);
// 清空
void Clear(void);
// 删除
bool Erase(int32_t index);
// 长度
int32_t Length(void) const;
// 获取数据
T& GetData(int32_t index) const;
protected:
// 扩容
void Dilatation(int32_t dilatation_len = DILATATION_LEN);
// 获取缓存
Ln* GetCacheNode(bool cut = false);
// 获取节点
Ln* GetUseNode(int32_t index) const;
private:
void InitUseHead(void);
void InitCacheHead(void);
private:
Ln* mUseHead;
Ln* mCacheHead;
int32_t mUseLen;
int32_t mCacheLen;
};
template <typename T>
void Linklist<T>::InitUseHead(void)
{
// 使用头
mUseHead = new Ln;
mUseHead->mPre = mUseHead;
mUseHead->mNext = mUseHead;
mUseLen = 0;
}
template <typename T>
void Linklist<T>::InitCacheHead(void)
{
// 缓存头
mCacheHead = new Ln;
mCacheHead->mPre = mCacheHead;
mCacheHead->mNext = mCacheHead;
mCacheLen = 0;
}
template <typename T>
Linklist<T>::Linklist(int32_t cache_len)
{
InitUseHead();
InitCacheHead();
// 扩容
if (cache_len > 0)
{
Dilatation(cache_len);
}
}
template <typename T>
Linklist<T>::Linklist(const Linklist& other)
{
InitUseHead();
InitCacheHead();
auto len = other.Length();
if (len > 0)
{
for (int32_t i = 0; i < len; ++i)
{
Push(other.GetData(i));
}
}
}
template <typename T>
Linklist<T>& Linklist<T>::operator = (const Linklist& other)
{
if (&other != this)
{
auto len = other.Length();
if (len > 0)
{
Clear();
for (int32_t i = 0; i < len; ++i)
{
Push(other.GetData(i));
}
}
}
return *this;
}
template <typename T>
Linklist<T>& Linklist<T>::operator += (const Linklist& other)
{
if (&other != this)
{
auto len = other.Length();
if (len > 0)
{
for (int32_t i = 0; i < len; ++i)
{
Push(other.GetData(i));
}
}
}
return *this;
}
template <typename T>
T& Linklist<T>::operator [] (int32_t index)
{
return GetData(index);
}
template <typename T>
Linklist<T>::~Linklist(void)
{
Clear();
auto cur = mCacheHead;
auto next = cur->mNext;
for (int32_t i = 0; i < mCacheLen; ++i)
{
cur = next;
next = next->mNext;
delete cur;
cur = nullptr;
}
delete mUseHead;
delete mCacheHead;
}
template <typename T>
bool Linklist<T>::Push(T data)
{
Ln* node = GetCacheNode(true);
node->mData = data;
node->mNext = mUseHead;
node->mPre = mUseHead->mPre;
mUseHead->mPre->mNext = node;
mUseHead->mPre = node;
++mUseLen;
--mCacheLen;
return true;
}
template <typename T>
bool Linklist<T>::Pop(void)
{
if (mUseLen <= 0)
{
return false;
}
auto node = mUseHead->mPre;
mUseHead->mPre = node->mPre;
mUseHead->mPre->mNext = mUseHead;
node->mNext = mCacheHead;
node->mPre = mCacheHead->mPre;
mCacheHead->mPre->mNext = node;
mCacheHead->mPre = node;
--mUseLen;
++mCacheLen;
return true;
}
template <typename T>
bool Linklist<T>::Insert(T data, int32_t index)
{
Ln* use_node = GetUseNode(index);
if (!use_node)
{
return false;
}
Ln* cache = GetCacheNode(true);
cache->mPre = use_node->mPre;
cache->mNext = use_node;
cache->mData = data;
use_node->mPre->mNext = cache;
use_node->mPre = cache;
++mUseLen;
--mCacheLen;
return true;
}
template <typename T>
void Linklist<T>::Clear(void)
{
mCacheLen += mUseLen;
mUseLen = 0;
auto node = mUseHead->mNext;
node->mPre = mUseHead->mPre;
node->mPre->mNext = node;
mUseHead->mPre = mUseHead;
mUseHead->mNext = mUseHead;
auto cache_last = mCacheHead->mPre;
auto node_last = node->mPre;
node->mPre = cache_last;
node_last->mNext = mCacheHead;
mCacheHead->mPre = node_last;
cache_last->mNext = node;
}
template <typename T>
bool Linklist<T>::Erase(int32_t index)
{
auto node = GetUseNode(index);
if (!node)
{
return false;
}
node->mPre->mNext = node->mNext;
node->mNext->mPre = node->mPre;
node->mPre = mCacheHead->mPre;
node->mNext = mCacheHead;
mCacheHead->mPre->mNext = node;
mCacheHead->mPre = node;
--mUseLen;
++mCacheLen;
return true;
}
template <typename T>
int32_t Linklist<T>::Length(void) const
{
return mUseLen;
}
template <typename T>
T& Linklist<T>::GetData(int32_t index) const
{
return GetUseNode(index)->mData;
}
template <typename T>
void Linklist<T>::Dilatation(int32_t dilatation_len)
{
mCacheLen += dilatation_len;
for (int16_t i = 0; i < dilatation_len; ++i)
{
Ln* cache = new Ln;
cache->mPre = mCacheHead->mPre;
cache->mNext = mCacheHead;
mCacheHead->mPre->mNext = cache;
mCacheHead->mPre = cache;
}
}
template <typename T>
typename Linklist<T>::Ln* Linklist<T>::GetCacheNode(bool cut)
{
if (mCacheLen <= 0)
{
Dilatation();
}
auto node = mCacheHead->mPre;
if (cut)
{
mCacheHead->mPre = node->mPre;
node->mPre->mNext = mCacheHead;
}
return node;
}
template <typename T>
typename Linklist<T>::Ln* Linklist<T>::GetUseNode(int32_t index) const
{
Ln* node = nullptr;
if (index >= 0 && index < mUseLen)
{
auto half = mUseLen / 2 - 1;
node = mUseHead;
// 正序
if (index <= half)
{
for (int32_t i = 0; i <= index; i++)
{
node = node->mNext;
}
}
// 反序
else
{
index = mUseLen - index;
for (int32_t i = 0; i < index; i++)
{
node = node->mPre;
}
}
}
return node;
}
#endif // !_LINK_LIST_H_
| true |
449c4b2613960aa0c9fb9e58bb2b0e79e4d603f0 | C++ | RustKnight/RoguePatterns | /RoguePatterns/Demo.h | UTF-8 | 5,417 | 2.53125 | 3 | [] | no_license | #pragma once
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
#include "Board.h"
#include "Creature.h"
#include "InputHandler.h"
#include "Strategy.h"
#include "Ai.h"
#include "InteractionHandler.h"
#include "Obstacle.h"
#include "map.h"
#include "turnTaker.h"
#include <vector>
#include <typeinfo>
// add weapons of different attack values (Ex: Axe +2, Sword +1, etc. - naming will just be flavor for now)
// add ability for players to pick up different weapons and be able to exchange them when desired
// make an AI that always is on a look out for a best weapon, and when possible it swaps it
// action text will be outputed in the command line
// make the world understand grids. grids can be empty or hold things
// ai and interactionHandler will be use of this container
// ai can scan based on his location, his surroundings
// 1 action = 1 move ; all creatures have 1 move per turn
// bump on wall = remain on original postion
// teams
// bump on enemy = means attack
// bump on friendly = remain on original postion
// animations / physics
//TODO: fix main loop
// - teams
// - possibly add turns system
// - accomodate implementation of animations
// a creature that is thrown should not care about map. It should go along its path and it's interactionHandlers job to monitor if it collides or not.
// if thrown creature stops, but it still had travel distance, it will take damage depending on how much travel dist. was left
// if a thrown action occurs, turnTaker should stop normal flow of turn and resolve thrown object. Then resume normal order.
// if two creatures collide, they should take damage
// animation for creature fragging that is hit against a wall (letter sign disappears and multiple other '&' signs jump randomly around)
// maybe have a function in creature called explode() -> how can Creature affect state of world? needs to create other flying entities
// have a class exploder that can explode objects (isolate flyThrough algorithm for improvement)
// Animation definition: ...
// when a thing is in the state of animation, it sort of stops the turn of all other things, until that animation is finished
// if several things are in animation state they will resolve their animation first before other things
class Demo : public olc::PixelGameEngine
{
public:
Demo() : winsizeX {800}, winsizeY {600},
board (25, 25, 25, 15, getWinWidth(), getWinHeight(), this),
map (board),
interactionHandler(map),
playerInput (this),
turnTaker (vpThings)
{
sAppName = "Demo";
}
public:
bool OnUserCreate() override
{
Creature* knight = new Creature("Knight", 'K', { 10,5 }, olc::DARK_RED, &interactionHandler, &playerInput, &fElapsedTime, this);
knight->equip(new Sword(this, &fElapsedTime));
vpThings.push_back(knight);
Creature* fiend = new Creature("Fiend", 'F', { 5,5 }, olc::DARK_MAGENTA, &interactionHandler, &ai, &fElapsedTime, this);
fiend->equip(new Axe(this, &fElapsedTime));
vpThings.push_back(fiend);
Creature* fiend2 = new Creature("Fiend2", 'F', { 0,5 }, olc::DARK_MAGENTA, &interactionHandler, &ai, &fElapsedTime, this);
fiend2->equip(new Axe(this, &fElapsedTime));
vpThings.push_back(fiend2);
for (int x = 0; x < 25; ++x)
for (int y = 0; y < 15; ++y) {
// left border
if (x == 0)
vpThings.push_back(new Obstacle("Wall", '@', { x,y }, olc::VERY_DARK_GREY, &interactionHandler, &fElapsedTime, this));
// right border
if (x == 24)
vpThings.push_back(new Obstacle("Wall", '@', { x,y }, olc::VERY_DARK_GREY, &interactionHandler, &fElapsedTime, this));
// top border
if (x != 0 && y == 0)
vpThings.push_back(new Obstacle("Wall", '@', { x,y }, olc::VERY_DARK_GREY, &interactionHandler, &fElapsedTime, this));
// bottom border
if (x != 0 && y == 14)
vpThings.push_back(new Obstacle("Wall", '@', { x,y }, olc::VERY_DARK_GREY, &interactionHandler, &fElapsedTime, this));
}
for (int i = 0; i < 20; ++i) {
int x = rand() % 26;
int y = rand() % 16;
vpThings.push_back(new Obstacle("Wall", '@', { x,y }, olc::VERY_DARK_GREY, &interactionHandler, &fElapsedTime, this));
}
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
this->fElapsedTime = fElapsedTime;
Clear(olc::BLACK);
{
if (GetMouseWheel() > 0) {
board.cellSizeX++;
board.cellSizeY++;
}
if (GetMouseWheel() < 0) {
board.cellSizeX--;
board.cellSizeY--;
}
if (GetKey(olc::G).bPressed)
board.toggleGrid();
}
actorSwitchDEBUG();
turnTaker.update(vpThings);
map.update(vpThings); // bugged af
turnTaker.handleTurns();
board.drawBoard();
for (Thing* thing : vpThings)
board.drawThing(*thing);
//board.drawTurnNotifier(turnTaker.whoPlaysNow());
return true;
}
// Demo public methods
public:
int getWinWidth() const { return winsizeX; };
int getWinHeight() const { return winsizeY; };
void actorSwitchDEBUG() {
if (this->GetKey(olc::L).bHeld)
static_cast<Creature*> (vpThings[0])->switchPossesor(&ai);
else
static_cast<Creature*> (vpThings[0])->switchPossesor(&playerInput);
}
// Demo private data members
private:
float fElapsedTime;
int winsizeX;
int winsizeY;
InteractionHandler interactionHandler;
Board board;
Map map;
Ai ai;
vector<Thing*>vpThings;
InputHandler playerInput;
TurnTaker turnTaker;
};
| true |
799810ece5abd5f2d148617dead9b2d4e56ddca2 | C++ | trymnilsen/BotVille | /BotVille/BotVille/SpriteBuffer.cpp | UTF-8 | 974 | 2.96875 | 3 | [] | no_license | #include "SpriteBuffer.h"
SpriteBuffer::SpriteBuffer(SDL_Window *window)
{
renderer=std::shared_ptr<SDL_Renderer>(SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED));
SDL_Surface *textureSurface = SDL_LoadBMP("unit.bmp");
unitTexture=std::shared_ptr<SDL_Texture>(
SDL_CreateTextureFromSurface(
renderer.get(),
textureSurface));
SDL_FreeSurface(textureSurface);
}
SpriteBuffer::~SpriteBuffer()
{
SDL_DestroyRenderer(renderer.get());
renderer.reset();
}
void SpriteBuffer::DrawUnit(Vector position, EntityType type)
{
SDL_Rect unitTextureSource;
SDL_Rect unitBufferDestination;
unitTextureSource.x=0;
unitTextureSource.y=unitSize*type;
unitTextureSource.w=unitSize;
unitTextureSource.h=unitSize;
unitBufferDestination.x=position.X;
unitBufferDestination.y=position.Y;
unitBufferDestination.w=unitSize;
unitBufferDestination.h=unitSize;
SDL_RenderCopy(renderer.get(),unitTexture.get(),&unitTextureSource,&unitBufferDestination);
} | true |
8cf45e325ca829493c0d31cf77703861b5ed76ef | C++ | nanguoshun/StatNLP-Framework | /src/common/types/token_array.h | UTF-8 | 556 | 2.53125 | 3 | [] | no_license | //
// Created by ngs on 06/10/2018.
//
#ifndef STATNLP_TOKEN_ARRAY_H
#define STATNLP_TOKEN_ARRAY_H
#include "linear_chain.h"
class TokenArray: public LinearChain{
public:
inline TokenArray(Token **pptr_tokens, int size){
pptr_tokens_ = pptr_tokens;
length_ = size;
}
inline ~TokenArray(){
}
Token *Get(int index) override {
return pptr_tokens_[index];
}
int GetLength() override {
return length_;
}
protected:
Token **pptr_tokens_;
int length_;
};
#endif //STATNLP_TOKEN_ARRAY_H
| true |
8b575da9fbd8dcdabbfab1baf17643e14fd61243 | C++ | turi-code/GraphLab-Create-SDK | /graphlab/cppipc/client/issue.hpp | UTF-8 | 2,877 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* Copyright (C) 2016 Turi
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#ifndef CPPIPC_CLIENT_ISSUE_HPP
#define CPPIPC_CLIENT_ISSUE_HPP
#include <tuple>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <graphlab/serialization/iarchive.hpp>
#include <graphlab/serialization/oarchive.hpp>
#include <graphlab/util/generics/remove_member_pointer.hpp>
#include <graphlab/cppipc/util/generics/member_function_return_type.hpp>
#include <graphlab/cppipc/util/generics/tuple.hpp>
#include <graphlab/cppipc/ipc_object_base.hpp>
namespace cppipc {
namespace detail{
/**
* \internal
* \ingroup cppipc
* Overload of issue_disect when the tuple list is not empty.
* Here we serialize the left most argument, shift the tuple and recursively
* forward the call.
*/
template <typename ArgumentTuple, typename... Args>
struct issue_disect { };
/**
* Overload of issue_disect when the tuple list is not empty.
* Here we serialize the left most argument, shift the tuple and recursively
* forward the call.
*/
template <typename ArgumentTuple, typename Arg, typename... Args>
struct issue_disect<ArgumentTuple, Arg, Args...> {
static void exec(graphlab::oarchive& msg,
const Arg& a, const Args&... args) {
static_assert(1 + sizeof...(Args) == std::tuple_size<ArgumentTuple>::value, "Argument Count Mismatch");
typedef typename std::tuple_element<0, ArgumentTuple>::type arg_type;
typedef typename std::decay<arg_type>::type decayed_arg_type;
if (std::is_same<decayed_arg_type, Arg>::value) {
msg << a;
} else {
msg << (decayed_arg_type)(a);
}
typedef typename left_shift_tuple<ArgumentTuple>::type shifted_tuple;
issue_disect<shifted_tuple, Args...>::exec(msg, args...);
}
};
/**
* \internal
* \ingroup cppipc
* Overload of execute_disect when the tuple list is empty,
* and there are no arguments. There is nothing to do here.
*/
template <typename... Args>
struct issue_disect<std::tuple<>, Args...> {
static void exec(graphlab::oarchive& msg, const Args&... args) {
static_assert(sizeof...(Args) == 0, "Too Many Arguments");
}
};
} // namespace detail
/**
* \internal
* \ingroup cppipc
* Casts the arguments into the required types for the member function
* and serializes it into the output archive
*/
template <typename MemFn, typename... Args>
void issue(graphlab::oarchive& msg,
MemFn fn,
const Args&... args) {
typedef typename boost::remove_member_pointer<MemFn>::type fntype;
typedef typename function_args_to_tuple<fntype>::type tuple;
detail::issue_disect<tuple, Args...>::exec(msg, args...);
}
} // cppipc
#endif
| true |
2f6d9cc7c67644431fd76b1ea18df39841b57af1 | C++ | nsehrt/GameOfLifeSFML | /src/gametime.h | UTF-8 | 1,089 | 3.15625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <SFML/System/Clock.hpp>
class GameTime
{
public:
explicit GameTime() = default;
//resets all internal clocks
void reset()
{
mInternalDeltaClock.restart();
mInternalTotalClock.restart();
}
//updates the delta time
void update()
{
mInternalDeltaTime = mInternalDeltaClock.restart();
}
//gets time scaled delta or true delta
sf::Time getDelta(bool scaled = true)
{
return scaled ? mInternalDeltaTime * mTimeScale : mInternalDeltaTime;
}
//gets time scaled total or true total
sf::Time getTotal(bool scaled = true)
{
return scaled ? mInternalTotalClock.getElapsedTime() * mTimeScale : mInternalTotalClock.getElapsedTime();
}
//set the time scale, 1.0f is default, 2.0f is twice as fast etc.
void setTimeScale(float timeScale = 1.0f)
{
mTimeScale = std::abs(timeScale);
}
private:
sf::Clock mInternalDeltaClock{};
sf::Clock mInternalTotalClock{};
sf::Time mInternalDeltaTime{};
float mTimeScale = 1.0f;
}; | true |
abf0ea371c5aaacf2fa7bbce409e7ca4d005a12b | C++ | plushmonkey/Terracotta | /terracotta/GameWindow.h | UTF-8 | 1,615 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef TERRACOTTA_GAME_WINDOW_H_
#define TERRACOTTA_GAME_WINDOW_H_
#include <GLFW/glfw3.h>
#include <vector>
#include <functional>
namespace terra {
using MouseSetCallback = std::function<void(double, double)>;
using MouseChangeCallback = std::function<void(double, double)>;
using MouseButtonCallback = std::function<void(int, int, int)>;
using MouseScrollCallback = std::function<void(double, double)>;
class GameWindow {
public:
GameWindow(GLFWwindow* window);
void OnKeyChange(int key, int code, int action, int mode);
void OnMouseMove(double x, double y);
void OnMouseButton(int button, int action, int mods);
void OnMouseScroll(double offset_x, double offset_y);
void RegisterMouseSet(MouseSetCallback callback) {
m_MouseSetCallbacks.push_back(callback);
}
void RegisterMouseChange(MouseChangeCallback callback) {
m_MouseChangeCallbacks.push_back(callback);
}
void RegisterMouseButton(MouseButtonCallback callback) {
m_MouseButtonCallbacks.push_back(callback);
}
void RegisterMouseScroll(MouseScrollCallback callback) {
m_MouseScrollCallbacks.push_back(callback);
}
bool IsKeyDown(int code);
private:
GLFWwindow* m_Window;
std::vector<MouseSetCallback> m_MouseSetCallbacks;
std::vector<MouseChangeCallback> m_MouseChangeCallbacks;
std::vector<MouseButtonCallback> m_MouseButtonCallbacks;
std::vector<MouseScrollCallback> m_MouseScrollCallbacks;
bool m_Keys[1024];
float m_LastMouseX;
float m_LastMouseY;
bool m_FirstMouse;
bool m_UpdateMouse;
};
} // ns terra
#endif
| true |
c92de7d6ace1a8051131029347d8ffc614559d4a | C++ | ascheel319/CSCI-340-Data-Structures | /hw2/assignment2.cc | UTF-8 | 5,107 | 3.484375 | 3 | [] | no_license | /****************************************
Name: Andrew Scheel
Z-ID: Z1790270
Section: section 3
Assignment: Assignment 1
Due Date: Feburary 5 2018
Purpose: In this assignment, you will use routines
from STL <algorithm> to implement these
algorithms.
****************************************/
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
//did not make these
const int DATA_SIZE = 100;
const int SEARCH_SIZE = 50;
const int DATA_SEED = 11;
const int SEARCH_SEED = 7;
//made these
const int NO_ITEMS = 10;//number of items per line
const int ITEM_W = 6;//number of space between numbers
const int LOW = 1;//for getRndNums
const int HIGH = 100;//for getRndNums
/****************************************
Function: genRndNums
Use: fill the vector with random numbers of a specific seed
Parameters: the vector to be filled and the seed to be used
Returns: none
****************************************/
void genRndNums(vector<int>& v, int seed)
{
srand(seed);
for(size_t i = 0; i < v.size(); i++)
{
v[i] = rand() % (HIGH - LOW + 1) + LOW;//range from low to high
}
}
/****************************************
Function: linearSearch
Use: perform a linear search on the vector by calling it from the routine algoithm
Parameters: the input vector and the search item
Returns: a true if it finds the item and a false if it doesn't
****************************************/
bool linearSearch(const vector<int>& inputVec, int x)
{
return find(inputVec.begin(), inputVec.end(), x) != inputVec.end();
}
/****************************************
Function: binarySearch
Use: perform a binary search on the inputed vector by calling it from the included routine algorithm
Parameters: a vector to search through and a value to search for
Returns: true if the searched for item is found and false if it is not found
****************************************/
bool binarySearch(const vector<int>& inputVec, int x)
{
return binary_search(inputVec.begin(), inputVec.end(), x);
}
/****************************************
Function: search
Use: searches through the inputed vector with the inputed search type
Parameters: a vector to search through, a vector of things to search for, and a type of search
Returns: the number of successful searches
****************************************/
int search(const vector<int>& inputVec, const vector<int>& searchVec, bool (*p)(const vector<int>&, int))
{
int success = 0;
for(size_t i = 0; i < searchVec.size(); i++)
{
if(p(inputVec, searchVec[i]))
success++;
}
return success;
}
/****************************************
Function: sortVector
Use: to sort the vector using the routine from algorithm
Parameters: a vector to sort
Returns: none
****************************************/
void sortVector (vector<int>& inputVec)
{
sort(inputVec.begin(), inputVec.end());//could it really be that simple???
}
/****************************************
Function: printStat
Use: to print the percent of successful searches as a floating-point number
Parameters: the total number of successes and the total size of the vector
Returns: none
****************************************/
void printStat (int totalSucCnt, int vec_size)
{
double num = ((double)totalSucCnt / (double)vec_size) * 100;
cout << fixed << setprecision(2) << "Successful Searches: " << num << "%" << endl;
}
/****************************************
Function: print_vec
Use: to print out the vector
Parameters: a vector to be printed
Returns: none
****************************************/
void print_vec(const vector<int>& vec)
{
cout << " ";//used for the first line to make it line up with the rest
for(size_t i = 0; i < vec.size(); i++)
{
cout << vec[i] << setw(ITEM_W);//number of spaces between the numbers
if((i+1) % NO_ITEMS == 0)//number of numbers per line
cout << endl;
}
}
int main()
{
vector<int> inputVec(DATA_SIZE);
vector<int> searchVec(SEARCH_SIZE);
genRndNums(inputVec, DATA_SEED);
genRndNums(searchVec, SEARCH_SEED);
cout << "----- Data source: " << inputVec.size() << " randomly generated numbers ------" << endl;
print_vec( inputVec );
cout << "----- " << searchVec.size() << " random numbers to be searched -------" << endl;
print_vec( searchVec );
cout << "\nConducting linear search on unsorted data source ..." << endl;
int linear_search_count = search( inputVec, searchVec, linearSearch );
printStat ( linear_search_count, SEARCH_SIZE );
cout << "\nConducting binary search on unsorted data source ..." << endl;
int binary_search_count = search( inputVec, searchVec, binarySearch );
printStat ( binary_search_count, SEARCH_SIZE );
sortVector( inputVec );
cout << "\nConducting linear search on sorted data source ..." << endl;
linear_search_count = search( inputVec, searchVec, linearSearch );
printStat ( linear_search_count, SEARCH_SIZE );
cout << "\nConducting binary search on sorted data source ..." << endl;
binary_search_count = search( inputVec, searchVec, binarySearch );
printStat ( binary_search_count, SEARCH_SIZE );
return 0;
}
| true |
b86fdbce1cbbde0463b7b9f758abc44a1785894a | C++ | Myung-Hyun/Data-Structure-Practice | /Chapter5/Sorted List/SortedType.h | UHC | 11,868 | 3.71875 | 4 | [] | no_license | // Header file for Unsorted List ADT.
#include <iostream>
template <class ItemType>
struct NodeType;
using namespace std;
// Assumption: ItemType is a type for which the operators "<"
// and "==" are defined-either an appropriate built-in type or
// a class that overloads these operators.
template <class ItemType>
class SortedType
{
public:
SortedType(); // Class constructor
~SortedType(); // Class destructor
bool IsFull() const;
// Determines whether list is full.
// Post: Function value = (list is full)
int LengthIs() const;
// Determines the number of elements in list.
// Post: Function value = number of elements in list.
void MakeEmpty();
// Initializes list to empty state.
// Post: List is empty.
void RetrieveItem(ItemType& item, bool& found);
// Retrieves list element whose key matches item's key
// (if present).
// Pre: Key member of item is initialized.
// Post: If there is an element someItem whose key matches
// item's key, then found = true and item is a copy
// of someItem; otherwise found = false and item is
// unchanged.
// List is unchanged.
void InsertItem(ItemType item);
// Adds item to list.
// Pre: List is not full.
// item is not in list.
// Post: item is in list.
void DeleteItem(ItemType item);
// Deletes the element whose key matches item's key.
// Pre: Key member of item is initialized.
// One and only one element in list has a key matching
// item's key.
// Post: No element in list has a key matching item's key.
void DeleteItem_a(ItemType item);
void DeleteItem_b(ItemType item);
void ResetList();
// Initializes current position for an iteration through the
// list.
// Post: Current position is prior to list.
void GetNextItem(ItemType&);
// Gets the next element in list.
// Pre: Current position is defined.
// Element at current position is not last in list.
// Post: Current position is updated to next position.
// item is a copy of element at current position.
void MergeLists(SortedType<ItemType>& other, SortedType<ItemType>& result);
private:
NodeType<ItemType>* listData;
int length;
NodeType<ItemType>* currentPos;
};
template<class ItemType>
struct NodeType
{
ItemType info;
NodeType* next;
};
template <class ItemType>
SortedType<ItemType>::SortedType() // Class constructor
{
length = 0;
listData = NULL;
}
template<class ItemType>
bool SortedType<ItemType>::IsFull() const
// Returns true if there is no room for another ItemType
// on the free store; false otherwise.
{
NodeType<ItemType>* location;
try
{
location = new NodeType<ItemType>;
delete location;
return false;
}
catch(std::bad_alloc exception)
{
return true;
}
}
template <class ItemType>
int SortedType<ItemType>::LengthIs() const
// Post: Number of items in the list is returned.
{
return length;
}
template <class ItemType>
void SortedType<ItemType>::MakeEmpty()
// Post: List is empty; all items have been deallocated.
{
NodeType<ItemType>* tempPtr;
while (listData != NULL)
{
tempPtr = listData;
listData = listData->next;
delete tempPtr;
}
length = 0;
}
template <class ItemType>
void SortedType<ItemType>::RetrieveItem(ItemType& item,
bool& found)
{
bool moreToSearch;
NodeType<ItemType>* location;
location = listData;
found = false;
moreToSearch = (location != NULL);
while (moreToSearch && !found)
{
if (location->info < item)
{
location = location->next;
moreToSearch = (location != NULL);
}
else if (item == location->info)
{
found = true;
item = location->info;
}
else
moreToSearch = false;
}
}
template <class ItemType>
void SortedType<ItemType>::InsertItem(ItemType item)
{
NodeType<ItemType>* newNode; // pointer to node being inserted
NodeType<ItemType>* predLoc; // trailing pointer
NodeType<ItemType>* location; // traveling pointer
bool moreToSearch;
location = listData;
predLoc = NULL;
moreToSearch = (location != NULL);
// Find insertion point.
while (moreToSearch)
{
if (location->info < item)
{
predLoc = location;
location = location->next;
moreToSearch = (location != NULL);
}
else
moreToSearch = false;
}
// Prepare node for insertion
newNode = new NodeType<ItemType>;
newNode->info = item;
// Insert node into list.
if (predLoc == NULL) // Insert as first
{
newNode->next = listData;
listData = newNode;
}
else
{
newNode->next = location;
predLoc->next = newNode;
}
length++;
}
template <class ItemType>
void SortedType<ItemType>::DeleteItem(ItemType item)
// Pre: item's key has been initialized.
// An element in the list has a key that matches item's.
// Post: No element in the list has a key that matches item's.
{
NodeType<ItemType>* location = listData;
NodeType<ItemType>* tempLocation;
// Locate node to be deleted.
if (item == listData->info)
{
tempLocation = location;
listData = listData->next; // Delete first node.
}
else
{
while (!(item==(location->next)->info))
location = location->next;
// Delete node at location->next
tempLocation = location->next;
location->next = (location->next)->next;
}
delete tempLocation;
length--;
}
template <class ItemType>
void SortedType<ItemType>::DeleteItem_a(ItemType item)
// Pre: item's key has been initialized.
// An element in the list has a key that matches item's.
// Post: No element in the list has a key that matches item's.
{
NodeType<ItemType>* location = listData;
NodeType<ItemType>* preLoc = NULL;
NodeType<ItemType>* tempLocation;
// Locate node to be deleted.
if (item == listData->info)
{
tempLocation = location;
listData = listData->next; // Delete first node.
}
else
{
preLoc = location;
location = location->next;
while (!(item == location->info)) //ã ߰ NULLƴϸ ã´.
{
preLoc = location;
location = location->next;
if (location == NULL) //while ǿ location NULL , location->info ع .
break;
}
tempLocation = location;
if (location != NULL)
{
preLoc->next = location->next;
}
}
if (location != NULL)
{
delete tempLocation;
}
length--;
}
template <class ItemType>
void SortedType<ItemType>::DeleteItem_b(ItemType item)
// Pre: item's key has been initialized.
// An element in the list has a key that matches item's.
// Post: No element in the list has a key that matches item's.
{
NodeType<ItemType>* location = listData;
NodeType<ItemType>* preLoc = NULL;
NodeType<ItemType>* tempLocation;
bool finish = false;
// Locate node to be deleted.
if (item == listData->info)
{
tempLocation = location;
listData = listData->next; // Delete first node.
delete tempLocation;
}
else
{
preLoc = location;
location = location->next;
while (finish != true)
{
while (item != location->info) //ã ߰ NULLƴϸ ã´.
{
preLoc = location;
location = location->next;
if (location->info>item) //˻ ϴ
{
finish = true;
break;
}
}
if (location->info > item)
{
break;
}
tempLocation = location;
preLoc->next = location->next;
location = location->next; // Ҹ , ˻ ߰־ ϴ ڵ, location NULL ȴ.
delete tempLocation;
}
}
length--;
}
template <class ItemType>
void SortedType<ItemType>::ResetList()
// Post: Current position has been initialized.
{
currentPos = NULL;
}
template <class ItemType>
void SortedType<ItemType>::GetNextItem(ItemType& item)
// Post: Current position has been updated; item is
// current item.
{
if (currentPos == NULL)
currentPos = listData;
item = currentPos->info;
currentPos = currentPos->next;
}
template <class ItemType>
SortedType<ItemType>::~SortedType()
// Post: List is empty; all items have been deallocated.
{
NodeType<ItemType>* tempPtr;
while (listData != NULL)
{
tempPtr = listData;
listData = listData->next;
delete tempPtr;
}
}
template <class ItemType>
void SortedType<ItemType>::MergeLists(SortedType<ItemType>& other, SortedType<ItemType>& result)
{
NodeType<ItemType>* ptr1 = listData;
NodeType<ItemType>* ptr2 = other.listData;
NodeType<ItemType>* location = result.listData; //result ֱ
while (ptr1 != NULL && ptr2 != NULL)
{
NodeType<ItemType>* temp = new NodeType<ItemType>; // while ҴƼ result ũ⸦ ø.
if (ptr1->info < ptr2->info) //ptr1 result
{
temp->info = ptr1->info;
if (location == NULL) //result ó ִ
{
result.listData = temp;
location = temp;
}
else
{
location->next = temp; // ο
location = temp; // ġ Ű
}
ptr1 = ptr1->next; //list1 Ҹ Ű ϰ ٽ .
}
else
{
temp->info = ptr2->info;
if (location == NULL)
{
result.listData = temp;
location = temp;
}
else
{
location->next = temp;
location = temp;
}
ptr2 = ptr2->next;
}
}
//̰ ٸ ־ .
//Ҵٴ Һ ū ̰ ̹ ĵǾ Ƿ, ũ ʿ .
if (ptr1 == NULL)
{
while (ptr2 != NULL)
{
NodeType<ItemType>* temp = new NodeType<ItemType>;
temp->info = ptr2->info;
location->next = temp;
location = temp;
ptr2 = ptr2->next; //while ٲٴ ڵ尡 while ȿ ־ while ȵ.
}
}
if (ptr2 == NULL)
{
while (ptr1 != NULL)
{
NodeType<ItemType>* temp = new NodeType<ItemType>;
temp->info = ptr1->info;
location->next = temp;
location = temp;
ptr1 = ptr1->next;
}
}
location->next = NULL; // ڵ Ҹ . NodeType next NULL ʱȭ Ǿ ʾƼ, node next NULL Ѵ.
}
| true |
fa419f47c8b718eab69814cc505fce60b8e2bdea | C++ | bsheline/android_ete_pytroch_lib | /recognizer_impl.cc | UTF-8 | 2,150 | 2.515625 | 3 | [] | no_license | // Copyright 2020 Mobvoi Inc. All Rights Reserved.
// Author: lyguo@mobvoi.com (Liyong Guo)
#include "recognizer_impl.h"
#include <fstream>
#include <iostream>
RecognizerImpl::RecognizerImpl(const std::string& dict_file,
const std::string& model_file) {
LoadDict(dict_file);
model_ = torch::jit::load(model_file);
model_.eval();
int num_bins = 80, sample_rate = 16000, frame_length = 400, frame_shift = 160;
fbank_extractor_.reset(
new Fbank(num_bins, sample_rate, frame_length, frame_shift));
}
void RecognizerImpl::LoadDict(const std::string& dict_file) {
std::ifstream is;
is.open(dict_file, std::ios::in);
std::string s;
while (getline(is, s)) {
std::string delimiter = " ";
size_t pos = s.find(delimiter);
std::string key = s.substr(0, pos);
dict_.push_back(key);
}
eos_ = dict_.size() - 1;
return;
}
std::string RecognizerImpl::recognize(const std::vector<float> waves) {
std::vector<float> tmp_fbank;
int tmp = 0;
int num_frames = fbank_extractor_->Compute(waves, &tmp_fbank);
std::cout << "tmp_fbank.size(): " << tmp_fbank.size() << std::endl;
int beam_size = 1;
int batch_size = 1;
int num_rows = tmp_fbank.size() / 80;
int max_length = num_rows;
int feat_dim = 80;
std::vector<int> lengths;
lengths.push_back(max_length);
torch::Tensor batch_feats =
torch::zeros({batch_size, max_length, feat_dim}, torch::kFloat);
for (int i = 0; i < batch_size; i++) {
for (int j = 0; j < num_rows; j++) {
for (int col_index = 0; col_index < feat_dim; ++col_index) {
batch_feats[i][j][col_index] = tmp_fbank[j * feat_dim + col_index];
}
}
}
torch::Tensor batch_lengths =
torch::from_blob(lengths.data(), {lengths.size()}, torch::kInt);
torch::jit::IValue output =
model_.run_method("recognize", batch_feats, batch_lengths, beam_size);
torch::Tensor ot = output.toTensor();
std::string text;
for (int j = 0; j < ot[0].size(0); j++) {
int token_id = ot[0][j].item<int>();
if (token_id == eos_) break;
text += dict_[token_id];
}
std::cout << "text: " << text << std::endl;
return text;
}
| true |
75508302903a020fd4bc2a927a5f64b49f935363 | C++ | LoysoPandohva/Chess | /Chess/Server.cpp | UTF-8 | 7,256 | 2.734375 | 3 | [] | no_license | #include "Server.h"
Server::Server() : port(27015), lose_connection(false) {}
Server::~Server() {
closeServer();
}
void Server::startServer() {
if (WSAStartup(MAKEWORD(2, 2), &wData) == 0) {
std::cout << "WSA Startup succes" << std::endl;
}
SOCKADDR_IN addr;
int addrl = sizeof(addr);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
addr.sin_port = htons(port);
addr.sin_family = AF_INET;
my_socket = socket(AF_INET, SOCK_STREAM, NULL);
if (my_socket == SOCKET_ERROR) {
std::cout << "Socket not created" << std::endl;
}
if (bind(my_socket, (struct sockaddr*)&addr, sizeof(addr)) != SOCKET_ERROR) {
std::cout << "Socket succed binded" << std::endl;
}
if (listen(my_socket, SOMAXCONN) != SOCKET_ERROR) {
std::cout << "Start listenin at port " << ntohs(addr.sin_port) << std::endl;
}
}
void Server::closeServer() {
closesocket(my_socket);
WSACleanup();
std::cout << "Server was stoped. You can close app" << std::endl;
}
void Server::close_app(sf::RenderWindow &_window) {
closeServer();
_window.close();
exit(0);
}
void Server::notification(sf::RenderWindow &_window, const char _notification[]) {
_window.clear(sf::Color(200, 200, 200));
sf::Font font;
font.loadFromFile("Font//cour.ttf");
sf::Text t;
t.setString(_notification);
t.setFont(font);
t.setCharacterSize(28);
t.setPosition(20, 236);
t.setFillColor(sf::Color::Black);
t.setStyle(sf::Text::Bold);
_window.draw(t);
_window.display();
}
void Server::read_buf(sf::Vector2i &_from, sf::Vector2i &_to, int &_type_piece, char _buf[], int _size) {
char num[2];
int index_sym = 0;
int nums[5];
int indesx_num = 0;
for (int i = 0; i < _size - 1; i++) {
num[0] = _buf[i];
num[1] = 0;
nums[indesx_num++] = atoi(num);
}
_from = sf::Vector2i(nums[0], nums[1]);
_to = sf::Vector2i(nums[2], nums[3]);
_type_piece = nums[4];
}
void Server::write_buf(char _buf[], int _size, sf::Vector2i &_last_pos, sf::Vector2i &_new_pos, int &_type_piece) {
memset(_buf, 0, _size);
int nums[5] = { _last_pos.x, _last_pos.y, _new_pos.x, _new_pos.y, _type_piece };
int index = 0;
for (int i = 0; i < 5; i++) {
char num[2];
itoa(nums[i], num, 10);
_buf[index++] = num[0];
}
_buf[index] = 0;
}
void Server::listen_opponent(sf::RenderWindow &_window, SOCKET &acceptS, Game &_game) {
const int size = 6;
char buf[size];
while (true) {
int bytesRecv = recv(acceptS, buf, size, 0);
if (bytesRecv > 0) {
read_buf(_game.last_pos, _game.new_pos, _game.new_piece, buf, size);
_game.opponent_move(_game.last_pos, _game.new_pos, _game.new_piece, _window);
}
if (bytesRecv <= 0) {
std::cout << WSAGetLastError() << std::endl;
lose_connection = true;
return;
}
memset(buf, 0, size);
}
}
void Server::show_time(sf::RenderWindow &_window, const char _your_time[], const char _opponent_time[], bool _your_color) {
static sf::Font font;
static sf::Text t[2];
static bool first_run = true;
if (first_run == true) {
font.loadFromFile("Font//cour.ttf");
for (size_t i = 0; i < 2; i++) {
t[i].setFont(font);
t[i].setCharacterSize(30);
t[i].setFillColor(sf::Color::Black);
t[i].setStyle(sf::Text::Bold);
}
if (_your_color == false) {
t[0].setPosition(510, 255);
t[1].setPosition(510, 215);
}
else {
t[0].setPosition(510, 215);
t[1].setPosition(510, 255);
}
first_run = false;
}
t[0].setString(_your_time);
t[1].setString(_opponent_time);
for (size_t i = 0; i < 2; i++) {
_window.draw(t[i]);
}
}
void Server::convert_time(int _time, char _res[]) {
int min = _time / 60;
int sec = _time % 60;
char buf[3];
itoa(min, buf, 10);
if (min < 10) {
_res[0] = '0';
_res[1] = buf[0];
}
else {
_res[0] = buf[0];
_res[1] = buf[1];
}
_res[2] = ':';
itoa(sec, buf, 10);
if (sec < 10) {
_res[3] = '0';
_res[4] = buf[0];
}
else {
_res[3] = buf[0];
_res[4] = buf[1];
}
}
char* Server::your_time(bool _your_move, const int _game_time) {
static sf::Clock clock;
static int time = (int)clock.getElapsedTime().asSeconds();
static int time_game = _game_time;
static int time_left = _game_time;
static int old_time = time;
if (_your_move == false) {
time = (int)clock.getElapsedTime().asSeconds();
if (time != old_time) {
old_time = time;
time_left = time_game - time;
}
}
else {
time_game = time_left;
clock.restart();
old_time = time;
}
if (time_left <= 0) {
static char end[4] = "end";
return end;
}
static char res[6];
convert_time(time_left, res);
return res;
}
char* Server::opponent_time(bool _opponent_move, const int _game_time) {
static sf::Clock clock;
static int time = (int)clock.getElapsedTime().asSeconds();
static int time_game = _game_time;
static int time_left = _game_time;
static int old_time = time;
if (_opponent_move == true) {
time = (int)clock.getElapsedTime().asSeconds();
if (time != old_time) {
old_time = time;
time_left = time_game - time;
}
}
else {
time_game = time_left;
clock.restart();
old_time = time;
}
if (time_left <= 0) {
static char end[4] = "end";
return end;
}
static char res[6];
convert_time(time_left, res);
return res;
}
void Server::handle(sf::RenderWindow &_window, Game &_game) {
SOCKET acceptS;
SOCKADDR_IN addr_c;
int addrlen = sizeof(addr_c);
std::cout << "Client can connected..." << std::endl;
notification(_window, "Wating for the opponent...");
if ((acceptS = accept(my_socket, (struct sockaddr*)&addr_c, &addrlen)) != 0) {
std::cout << "Client is connected" << std::endl;
}
std::thread th(&Server::listen_opponent, this, std::ref(_window), std::ref(acceptS), std::ref(_game));
th.detach();
sf::Event event;
while (_window.isOpen()) {
char *ptr1 = your_time(_game.get_whose_move(), 300);
char *ptr2 = opponent_time(_game.get_whose_move(), 300);
_window.pollEvent(event);
if (event.type == sf::Event::Closed) _window.close();
_game.get_cursor().action();
_game.selecting_piece(_window, _game.get_pob());
if (_game.get_whose_move() == false) {
_game.make_move(_game.get_pob(), _window);
if (_game.get_whose_move() == true) {
const int size = 6;
char buf[size];
write_buf(buf, size, _game.last_pos, _game.new_pos, _game.new_piece);
send(acceptS, buf, size, 0);
memset(buf, 0, size);
}
}
_window.clear(sf::Color(200, 200, 200));
_game.get_pob().draw_for_white(_window);
_game.get_cursor().draw(_window);
show_time(_window, ptr1, ptr2, _game.get_your_color());
_window.display();
if (strcmp(ptr1, "end") == 0) {
_game.notificaion(_window, "BLACK WIN", 29);
close_app(_window);
}
if (strcmp(ptr2, "end") == 0) {
_game.notificaion(_window, "WHITE WIN", 29);
close_app(_window);
}
if (_game.get_end() == true) {
if (_game.get_king_who_shah()->get_color() == true) {
_game.notificaion(_window, "WHITE WIN", 29);
}
if (_game.get_king_who_shah()->get_color() == false) {
_game.notificaion(_window, "BLACK WIN", 29);
}
close_app(_window);
}
if (lose_connection == true) {
while (true) {
notification(_window, " Lose connection");
_window.pollEvent(event);
if (event.type == sf::Event::Closed) break;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) {
break;
}
}
close_app(_window);
}
}
} | true |
3cd368af229355b7f805f68c02db8050ed77305e | C++ | wjshku/COMP2113 | /Module10/module10/assign1.cpp | UTF-8 | 780 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int num_seats, num_votes, num_lists;
int quota, idx_list, vote, seat;
cout << "Total number of seats: ";
cin >> num_seats;
cout << "Total number of votes: ";
cin >> num_votes;
cout << "Total number of lists: ";
cin >> num_lists;
quota = num_votes / num_seats;
idx_list = 1;
while (idx_list <= num_lists) {
cout << "Votes for list " << idx_list << ": ";
cin >> vote;
cout << "Automatic seat for list " << idx_list << ": ";
seat = vote / quota;
cout << seat << endl;
cout << "Remainder for list " << idx_list << ": ";
cout << vote - seat * quota << endl;
idx_list++;
}
return 0;
}
| true |
f238c9f369a9fb748de9982137e03e61eb821a22 | C++ | Peymansoft/ICP3038 | /Lectures/Chapter 02 -- Introduction to C++/example3.cpp | UTF-8 | 211 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
int main()
{
float f1, f2;
std::cout << "Enter 2 floating point numbers :";
std::cin >> f1 >> f2;
std::cout << "sum = " << f1 + f2 << std::endl;
return 0;
}
| true |
110d2919b34a9125f26751d0a79486ad8bc6559b | C++ | richerarc/Projet-SIM | /The_Journalist/The_Journalist/sources/Classes projet/GestionnaireMenu.h | UTF-8 | 478 | 3.109375 | 3 | [] | no_license | #pragma once
#include "Menu.h"
class GestionnaireMenu : public Singleton<GestionnaireMenu>{
private:
std::list<Menu*> Menus;
public:
GestionnaireMenu(){
}
void retirerMenu(Menu* Menu){
this->Menus.remove(Menu);
}
void ajouterMenu(Menu* Menu){
this->Menus.push_back(Menu);
}
void vider(){
if (this->Menus.empty == false){
this->Menus.clear();
}
}
std::list<Menu*> ObtenirListeMenu(){
return this->Menus;
}
~GestionnaireMenu(){
vider();
}
}; | true |
32796a68f6673a544330c2739d8b83d025f43403 | C++ | JackLas/Game-of-Life | /Source/Game.cpp | UTF-8 | 1,895 | 2.84375 | 3 | [] | no_license | #include "Game.hpp"
Game::Game(Settings settings): myWindow(sf::VideoMode(settings.winWidth, settings.winHeight), "Game of Life", sf::Style::Close),
gameField(settings)
{
mySettings = settings;
font.loadFromFile("font.ttf");
myWindow.setFramerateLimit(mySettings.FPS);
isPaused = true;
generationDelay = mySettings.generationDelay;
timeToGeneration = 0;
txGameStatus = sf::Text("Paused", font, 18);
txGameStatus.setFillColor(mySettings.text);
}
Game::~Game()
{
}
void Game::run()
{
while(myWindow.isOpen())
{
handleInput();
update();
render();
}
}
void Game::handleInput()
{
sf::Event event;
while(myWindow.pollEvent(event))
{
if(event.type == sf::Event::Closed)
myWindow.close();
if(event.type == sf::Event::KeyPressed)
{
if(event.key.code == sf::Keyboard::C && isPaused)
gameField.clear();
if(event.key.code == sf::Keyboard::R && isPaused)
gameField.randomize();
if(event.key.code == sf::Keyboard::Space)
{
switchPause();
gameField.clearHovers();
}
}
}
if(isPaused)
{
for(unsigned int y = 0; y < mySettings.numOfCellHeight; ++y)
{
for(unsigned int x = 0; x < mySettings.numOfCellWidth; ++x)
{
gameField.setHover(x, y, myWindow);
if(gameField.isCellHover(x, y) && sf::Mouse::isButtonPressed(sf::Mouse::Button::Left))
gameField.setAlive(x, y);
}
}
}
}
void Game::update()
{
sf::Time deltaTime = clock.restart();
gameField.update();
if(!isPaused)
{
timeToGeneration += deltaTime.asSeconds();
if(timeToGeneration >= generationDelay)
{
gameField.nextGeneration();
timeToGeneration = 0;
}
}
}
void Game::render()
{
myWindow.clear(mySettings.bg);
myWindow.draw(gameField);
myWindow.draw(txGameStatus);
myWindow.display();
}
void Game::switchPause()
{
isPaused = !isPaused;
isPaused ? txGameStatus.setString("Paused") : txGameStatus.setString("Simulation");
} | true |